feat(canvas): Add Phase 3+4 - Bidirectional sync, templates, and visual polish

Phase 3 - Bidirectional Sync:
- Add loadFromIntent and loadFromConfig to canvas store
- Create useIntentParser hook for parsing Claude messages
- Create ConfigImporter component (file upload, paste JSON, load study)
- Add import/clear buttons to CanvasView header

Phase 4 - Templates & Polish:
- Create template library with 5 presets:
  - Mass Minimization (single-objective)
  - Multi-Objective Pareto (NSGA-II)
  - Turbo Mode (with MLP surrogate)
  - Mirror Zernike (optical optimization)
  - Frequency Optimization (modal)
- Create TemplateSelector component with category filters
- Enhanced BaseNode with animations, glow effects, status indicators
- Add colorBg to all node types for visual distinction
- Add notification toast system
- Update all exports

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-14 20:30:28 -05:00
parent 1ae35382da
commit 5bd142780f
18 changed files with 1389 additions and 35 deletions

View File

@@ -1,7 +1,16 @@
// Main Canvas Component
export { AtomizerCanvas } from './AtomizerCanvas';
// Palette
export { NodePalette } from './palette/NodePalette';
// Panels
export { NodeConfigPanel } from './panels/NodeConfigPanel';
export { ValidationPanel } from './panels/ValidationPanel';
export { ExecuteDialog } from './panels/ExecuteDialog';
export { ChatPanel } from './panels/ChatPanel';
export { ConfigImporter } from './panels/ConfigImporter';
export { TemplateSelector } from './panels/TemplateSelector';
// Nodes
export * from './nodes';

View File

@@ -6,7 +6,7 @@ import { AlgorithmNodeData } from '../../../lib/canvas/schema';
function AlgorithmNodeComponent(props: NodeProps<AlgorithmNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span>🧠</span>} color="text-indigo-600">
<BaseNode {...props} icon={<span>🧠</span>} color="text-indigo-600" colorBg="bg-indigo-50">
{data.method && <div>{data.method}</div>}
{data.maxTrials && (
<div className="text-xs text-gray-400">{data.maxTrials} trials</div>

View File

@@ -5,6 +5,7 @@ import { BaseNodeData } from '../../../lib/canvas/schema';
interface BaseNodeProps extends NodeProps<BaseNodeData> {
icon: ReactNode;
color: string;
colorBg?: string;
children?: ReactNode;
inputs?: number;
outputs?: number;
@@ -15,56 +16,126 @@ function BaseNodeComponent({
selected,
icon,
color,
colorBg = 'bg-gray-50',
children,
inputs = 1,
outputs = 1,
}: BaseNodeProps) {
const hasError = data.errors && data.errors.length > 0;
const isConfigured = data.configured;
return (
<div
className={`
px-4 py-3 rounded-lg border-2 min-w-[180px] bg-white shadow-sm
transition-all duration-200
${selected ? 'border-blue-500 shadow-lg' : 'border-gray-200'}
${!data.configured ? 'border-dashed' : ''}
${data.errors?.length ? 'border-red-400' : ''}
group relative px-4 py-3 rounded-xl border-2 min-w-[200px] bg-white
transition-all duration-300 ease-out
${selected
? 'border-blue-500 shadow-xl shadow-blue-100 scale-[1.02]'
: 'border-gray-200 shadow-md hover:shadow-lg hover:border-gray-300'}
${!isConfigured ? 'border-dashed opacity-80' : ''}
${hasError ? 'border-red-400 shadow-red-100' : ''}
`}
style={{
animation: 'nodeAppear 0.3s ease-out',
}}
>
{/* Glow effect on selection */}
{selected && (
<div
className="absolute inset-0 -z-10 rounded-xl opacity-20"
style={{
background: 'radial-gradient(ellipse at center, #3b82f6 0%, transparent 70%)',
transform: 'scale(1.3)',
}}
/>
)}
{/* Input handles */}
{inputs > 0 && (
<Handle
type="target"
position={Position.Left}
className="w-3 h-3 !bg-gray-400"
className={`
!w-4 !h-4 !border-2 !border-white !shadow-md
transition-all duration-200
${selected ? '!bg-blue-500' : '!bg-gray-400 group-hover:!bg-gray-500'}
`}
style={{ left: -8 }}
/>
)}
{/* Header */}
<div className="flex items-center gap-2 mb-2">
<span className={`text-lg ${color}`}>{icon}</span>
<span className="font-medium text-gray-800">{data.label}</span>
{!data.configured && (
<span className="text-xs text-orange-500">!</span>
)}
<div className="flex items-center gap-3 mb-2">
<div className={`
w-8 h-8 rounded-lg ${colorBg} flex items-center justify-center
transition-transform duration-200
${selected ? 'scale-110' : 'group-hover:scale-105'}
`}>
<span className={`text-lg ${color}`}>{icon}</span>
</div>
<div className="flex-1">
<span className="font-semibold text-gray-800 text-sm">{data.label}</span>
{!isConfigured && (
<span className="ml-2 text-xs text-orange-500 animate-pulse">Needs config</span>
)}
</div>
</div>
{/* Content */}
{children && <div className="text-sm text-gray-600">{children}</div>}
{children && (
<div className="text-sm text-gray-600 mt-2 pl-11">
{children}
</div>
)}
{/* Status indicator */}
<div className="absolute top-2 right-2">
{hasError ? (
<span className="w-2 h-2 bg-red-500 rounded-full block animate-pulse" />
) : isConfigured ? (
<span className="w-2 h-2 bg-green-500 rounded-full block" />
) : (
<span className="w-2 h-2 bg-orange-400 rounded-full block" />
)}
</div>
{/* Errors */}
{data.errors?.length ? (
<div className="mt-2 text-xs text-red-500">
{data.errors[0]}
{hasError && (
<div className="mt-3 pt-2 border-t border-red-100">
<p className="text-xs text-red-600 flex items-center gap-1">
<span></span>
{data.errors?.[0]}
</p>
</div>
) : null}
)}
{/* Output handles */}
{outputs > 0 && (
<Handle
type="source"
position={Position.Right}
className="w-3 h-3 !bg-gray-400"
className={`
!w-4 !h-4 !border-2 !border-white !shadow-md
transition-all duration-200
${selected ? '!bg-blue-500' : '!bg-gray-400 group-hover:!bg-gray-500'}
`}
style={{ right: -8 }}
/>
)}
{/* Inline styles for animation */}
<style>{`
@keyframes nodeAppear {
from {
opacity: 0;
transform: scale(0.9) translateY(10px);
}
to {
opacity: 1;
transform: scale(1) translateY(0);
}
}
`}</style>
</div>
);
}

View File

@@ -6,7 +6,7 @@ import { ConstraintNodeData } from '../../../lib/canvas/schema';
function ConstraintNodeComponent(props: NodeProps<ConstraintNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span>🚧</span>} color="text-orange-600">
<BaseNode {...props} icon={<span>🚧</span>} color="text-orange-600" colorBg="bg-orange-50">
{data.name && <div>{data.name}</div>}
{data.operator && data.value !== undefined && (
<div className="text-xs text-gray-400">

View File

@@ -6,7 +6,7 @@ import { DesignVarNodeData } from '../../../lib/canvas/schema';
function DesignVarNodeComponent(props: NodeProps<DesignVarNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span>📐</span>} color="text-green-600">
<BaseNode {...props} icon={<span>📐</span>} color="text-green-600" colorBg="bg-green-50">
{data.expressionName && <div className="font-mono">{data.expressionName}</div>}
{data.minValue !== undefined && data.maxValue !== undefined && (
<div className="text-xs text-gray-400">

View File

@@ -6,7 +6,7 @@ import { ExtractorNodeData } from '../../../lib/canvas/schema';
function ExtractorNodeComponent(props: NodeProps<ExtractorNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span>🔬</span>} color="text-cyan-600">
<BaseNode {...props} icon={<span>🔬</span>} color="text-cyan-600" colorBg="bg-cyan-50">
{data.extractorName && <div>{data.extractorName}</div>}
{data.extractorId && (
<div className="text-xs text-gray-400">{data.extractorId}</div>

View File

@@ -6,7 +6,7 @@ import { ModelNodeData } from '../../../lib/canvas/schema';
function ModelNodeComponent(props: NodeProps<ModelNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span>📦</span>} color="text-blue-600" inputs={0}>
<BaseNode {...props} icon={<span>📦</span>} color="text-blue-600" colorBg="bg-blue-50" inputs={0}>
{data.filePath && (
<div className="truncate max-w-[150px]">{data.filePath.split('/').pop()}</div>
)}

View File

@@ -6,7 +6,7 @@ import { ObjectiveNodeData } from '../../../lib/canvas/schema';
function ObjectiveNodeComponent(props: NodeProps<ObjectiveNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span>🎯</span>} color="text-red-600">
<BaseNode {...props} icon={<span>🎯</span>} color="text-red-600" colorBg="bg-red-50">
{data.name && <div>{data.name}</div>}
{data.direction && (
<div className="text-xs text-gray-400">

View File

@@ -6,7 +6,7 @@ import { SolverNodeData } from '../../../lib/canvas/schema';
function SolverNodeComponent(props: NodeProps<SolverNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span></span>} color="text-purple-600">
<BaseNode {...props} icon={<span></span>} color="text-purple-600" colorBg="bg-purple-50">
{data.solverType && <div>{data.solverType}</div>}
</BaseNode>
);

View File

@@ -6,7 +6,7 @@ import { SurrogateNodeData } from '../../../lib/canvas/schema';
function SurrogateNodeComponent(props: NodeProps<SurrogateNodeData>) {
const { data } = props;
return (
<BaseNode {...props} icon={<span>🚀</span>} color="text-pink-600" outputs={0}>
<BaseNode {...props} icon={<span>🚀</span>} color="text-pink-600" colorBg="bg-pink-50" outputs={0}>
<div>{data.enabled ? 'Enabled' : 'Disabled'}</div>
{data.enabled && data.modelType && (
<div className="text-xs text-gray-400">{data.modelType}</div>

View File

@@ -0,0 +1,242 @@
/**
* ConfigImporter - Import optimization configs into canvas
*
* Supports:
* - File upload (optimization_config.json)
* - Paste JSON directly
* - Load from study directory
*/
import { useState, useRef } from 'react';
import { useCanvasStore, OptimizationConfig } from '../../../hooks/useCanvasStore';
interface ConfigImporterProps {
isOpen: boolean;
onClose: () => void;
onImport: (source: string) => void;
}
export function ConfigImporter({ isOpen, onClose, onImport }: ConfigImporterProps) {
const [tab, setTab] = useState<'file' | 'paste' | 'study'>('file');
const [jsonText, setJsonText] = useState('');
const [studyPath, setStudyPath] = useState('');
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const { loadFromConfig } = useCanvasStore();
if (!isOpen) return null;
const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setError(null);
setIsLoading(true);
try {
const text = await file.text();
const config = JSON.parse(text) as OptimizationConfig;
validateConfig(config);
loadFromConfig(config);
onImport(`File: ${file.name}`);
handleClose();
} catch (err) {
setError(err instanceof Error ? err.message : 'Invalid JSON file');
} finally {
setIsLoading(false);
}
};
const handlePasteImport = () => {
setError(null);
try {
const config = JSON.parse(jsonText) as OptimizationConfig;
validateConfig(config);
loadFromConfig(config);
onImport('Pasted JSON');
handleClose();
} catch (err) {
setError(err instanceof Error ? err.message : 'Invalid JSON');
}
};
const handleStudyLoad = async () => {
setError(null);
setIsLoading(true);
try {
// Call backend API to load study config
const response = await fetch(`/api/studies/${encodeURIComponent(studyPath)}/config`);
if (!response.ok) {
throw new Error(`Study not found: ${studyPath}`);
}
const config = await response.json() as OptimizationConfig;
validateConfig(config);
loadFromConfig(config);
onImport(`Study: ${studyPath}`);
handleClose();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load study');
} finally {
setIsLoading(false);
}
};
const validateConfig = (config: OptimizationConfig) => {
if (!config) {
throw new Error('Empty configuration');
}
// Must have at least one design variable or objective
const hasDesignVars = config.design_variables && config.design_variables.length > 0;
const hasObjectives = config.objectives && config.objectives.length > 0;
if (!hasDesignVars && !hasObjectives) {
throw new Error('Configuration must have design variables or objectives');
}
};
const handleClose = () => {
setJsonText('');
setStudyPath('');
setError(null);
setTab('file');
onClose();
};
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white rounded-lg shadow-xl w-full max-w-lg">
{/* Header */}
<div className="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
<h2 className="text-xl font-semibold text-gray-800">Import Configuration</h2>
<button
onClick={handleClose}
className="text-gray-500 hover:text-gray-700 text-xl"
>
&times;
</button>
</div>
{/* Tabs */}
<div className="flex border-b border-gray-200">
{[
{ id: 'file', label: 'Upload File' },
{ id: 'paste', label: 'Paste JSON' },
{ id: 'study', label: 'Load Study' },
].map((t) => (
<button
key={t.id}
onClick={() => setTab(t.id as 'file' | 'paste' | 'study')}
className={`flex-1 px-4 py-3 text-sm font-medium transition-colors ${
tab === t.id
? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50'
: 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
}`}
>
{t.label}
</button>
))}
</div>
{/* Content */}
<div className="p-6">
{/* File Upload Tab */}
{tab === 'file' && (
<div className="space-y-4">
<p className="text-sm text-gray-600">
Upload an <code className="bg-gray-100 px-1 rounded">optimization_config.json</code> file
from an existing study.
</p>
<input
ref={fileInputRef}
type="file"
accept=".json"
onChange={handleFileSelect}
className="hidden"
/>
<button
onClick={() => fileInputRef.current?.click()}
disabled={isLoading}
className="w-full py-8 border-2 border-dashed border-gray-300 rounded-lg hover:border-blue-400 hover:bg-blue-50 transition-colors flex flex-col items-center gap-2"
>
<span className="text-3xl">📁</span>
<span className="text-gray-600">
{isLoading ? 'Loading...' : 'Click to select file'}
</span>
</button>
</div>
)}
{/* Paste JSON Tab */}
{tab === 'paste' && (
<div className="space-y-4">
<p className="text-sm text-gray-600">
Paste your optimization configuration JSON below.
</p>
<textarea
value={jsonText}
onChange={(e) => setJsonText(e.target.value)}
placeholder={`{
"design_variables": [...],
"objectives": [...],
"method": "TPE"
}`}
className="w-full h-48 px-3 py-2 border rounded-lg font-mono text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
/>
<button
onClick={handlePasteImport}
disabled={!jsonText.trim()}
className="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Import JSON
</button>
</div>
)}
{/* Load Study Tab */}
{tab === 'study' && (
<div className="space-y-4">
<p className="text-sm text-gray-600">
Enter a study name to load its configuration.
</p>
<input
type="text"
value={studyPath}
onChange={(e) => setStudyPath(e.target.value)}
placeholder="e.g., bracket_mass_v1 or M1_Mirror/m1_mirror_flatback"
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
/>
<button
onClick={handleStudyLoad}
disabled={!studyPath.trim() || isLoading}
className="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{isLoading ? 'Loading...' : 'Load Study Config'}
</button>
</div>
)}
{/* Error Display */}
{error && (
<div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-lg">
<p className="text-sm text-red-700">{error}</p>
</div>
)}
</div>
{/* Footer */}
<div className="px-6 py-4 border-t border-gray-200 bg-gray-50 rounded-b-lg">
<p className="text-xs text-gray-500">
Imported configurations will replace the current canvas content.
</p>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,224 @@
/**
* TemplateSelector - Choose from pre-built optimization templates
*
* Displays template cards with preview and one-click loading
*/
import { useState } from 'react';
import { templates, CanvasTemplate, instantiateTemplate, getTemplatesByCategory } from '../../../lib/canvas/templates';
import { useCanvasStore } from '../../../hooks/useCanvasStore';
interface TemplateSelectorProps {
isOpen: boolean;
onClose: () => void;
onSelect: (template: CanvasTemplate) => void;
}
export function TemplateSelector({ isOpen, onClose, onSelect }: TemplateSelectorProps) {
const [selectedCategory, setSelectedCategory] = useState<'all' | 'structural' | 'optical' | 'general'>('all');
const [hoveredTemplate, setHoveredTemplate] = useState<string | null>(null);
const { loadFromIntent, clear } = useCanvasStore();
if (!isOpen) return null;
const filteredTemplates = selectedCategory === 'all'
? templates
: getTemplatesByCategory(selectedCategory);
const handleSelect = (template: CanvasTemplate) => {
clear();
const intent = instantiateTemplate(template);
loadFromIntent(intent);
onSelect(template);
onClose();
};
const categories = [
{ id: 'all', label: 'All Templates', count: templates.length },
{ id: 'structural', label: 'Structural', count: getTemplatesByCategory('structural').length },
{ id: 'optical', label: 'Optical', count: getTemplatesByCategory('optical').length },
{ id: 'general', label: 'General', count: getTemplatesByCategory('general').length },
];
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div
className="bg-white rounded-xl shadow-2xl w-full max-w-4xl max-h-[80vh] flex flex-col overflow-hidden"
style={{ animation: 'fadeIn 0.2s ease-out' }}
>
{/* Header */}
<div className="px-6 py-4 border-b border-gray-200 flex justify-between items-center bg-gradient-to-r from-blue-50 to-purple-50">
<div>
<h2 className="text-xl font-semibold text-gray-800">Choose a Template</h2>
<p className="text-sm text-gray-500 mt-0.5">Start with a pre-configured optimization workflow</p>
</div>
<button
onClick={onClose}
className="w-8 h-8 flex items-center justify-center text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-full transition-colors"
>
&times;
</button>
</div>
{/* Category Filters */}
<div className="px-6 py-3 border-b border-gray-100 flex gap-2 bg-gray-50">
{categories.map((cat) => (
<button
key={cat.id}
onClick={() => setSelectedCategory(cat.id as typeof selectedCategory)}
className={`px-3 py-1.5 rounded-full text-sm font-medium transition-all ${
selectedCategory === cat.id
? 'bg-blue-600 text-white shadow-sm'
: 'bg-white text-gray-600 hover:bg-gray-100 border border-gray-200'
}`}
>
{cat.label}
<span className={`ml-1.5 ${selectedCategory === cat.id ? 'text-blue-200' : 'text-gray-400'}`}>
({cat.count})
</span>
</button>
))}
</div>
{/* Template Grid */}
<div className="flex-1 overflow-y-auto p-6">
<div className="grid grid-cols-2 gap-4">
{filteredTemplates.map((template) => (
<TemplateCard
key={template.id}
template={template}
isHovered={hoveredTemplate === template.id}
onHover={() => setHoveredTemplate(template.id)}
onLeave={() => setHoveredTemplate(null)}
onSelect={() => handleSelect(template)}
/>
))}
</div>
{filteredTemplates.length === 0 && (
<div className="text-center py-12">
<p className="text-gray-500">No templates in this category</p>
</div>
)}
</div>
{/* Footer */}
<div className="px-6 py-3 border-t border-gray-200 bg-gray-50 flex justify-between items-center">
<p className="text-xs text-gray-500">
Templates provide a starting point - customize parameters after loading
</p>
<button
onClick={onClose}
className="px-4 py-2 text-gray-600 hover:text-gray-800 text-sm"
>
Cancel
</button>
</div>
</div>
<style>{`
@keyframes fadeIn {
from { opacity: 0; transform: scale(0.95); }
to { opacity: 1; transform: scale(1); }
}
`}</style>
</div>
);
}
interface TemplateCardProps {
template: CanvasTemplate;
isHovered: boolean;
onHover: () => void;
onLeave: () => void;
onSelect: () => void;
}
function TemplateCard({ template, isHovered, onHover, onLeave, onSelect }: TemplateCardProps) {
const intent = template.intent;
const stats = {
designVars: intent.design_variables?.length || 0,
objectives: intent.objectives?.length || 0,
constraints: intent.constraints?.length || 0,
method: intent.optimization?.method || 'TPE',
hasSurrogate: intent.surrogate?.enabled || false,
};
const categoryColors = {
structural: 'bg-orange-100 text-orange-700',
optical: 'bg-purple-100 text-purple-700',
general: 'bg-blue-100 text-blue-700',
};
return (
<div
className={`border rounded-xl p-4 cursor-pointer transition-all duration-200 ${
isHovered
? 'border-blue-400 shadow-lg transform -translate-y-0.5 bg-blue-50/30'
: 'border-gray-200 hover:border-gray-300 bg-white'
}`}
onMouseEnter={onHover}
onMouseLeave={onLeave}
onClick={onSelect}
>
{/* Header */}
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-3">
<span className="text-2xl">{template.icon}</span>
<div>
<h3 className="font-semibold text-gray-800">{template.name}</h3>
<span className={`text-xs px-2 py-0.5 rounded-full ${categoryColors[template.category]}`}>
{template.category}
</span>
</div>
</div>
{stats.hasSurrogate && (
<span className="text-xs px-2 py-1 bg-green-100 text-green-700 rounded-full">
Turbo
</span>
)}
</div>
{/* Description */}
<p className="text-sm text-gray-600 mb-4 line-clamp-2">{template.description}</p>
{/* Stats */}
<div className="flex gap-4 text-xs text-gray-500">
<div className="flex items-center gap-1">
<span className="w-2 h-2 rounded-full bg-blue-400"></span>
<span>{stats.designVars} vars</span>
</div>
<div className="flex items-center gap-1">
<span className="w-2 h-2 rounded-full bg-green-400"></span>
<span>{stats.objectives} obj</span>
</div>
<div className="flex items-center gap-1">
<span className="w-2 h-2 rounded-full bg-orange-400"></span>
<span>{stats.constraints} con</span>
</div>
<div className="flex items-center gap-1">
<span className="font-medium text-gray-600">{stats.method}</span>
</div>
</div>
{/* Use Button (appears on hover) */}
<div
className={`mt-4 transition-all duration-200 overflow-hidden ${
isHovered ? 'max-h-10 opacity-100' : 'max-h-0 opacity-0'
}`}
>
<button
className="w-full py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors"
onClick={(e) => {
e.stopPropagation();
onSelect();
}}
>
Use This Template
</button>
</div>
</div>
);
}