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

@@ -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>
);
}