1. Copy, paste, cut and delete functions added to the web page

This commit is contained in:
2026-05-16 22:30:36 +08:00
parent cd4f25a421
commit bc6e03cf9e
3 changed files with 927 additions and 0 deletions
Binary file not shown.
+98
View File
@@ -637,6 +637,104 @@
const [gridSnap, setGridSnap] = useState(false);
// --- CLIPBOARD & ACTIONS ---
const [clipboard, setClipboard] = useState({ nodes: [] });
const handleCopy = useCallback(() => {
const currentNodes = reactFlowInstance.getNodes();
const selectedNodes = currentNodes.filter(n => n.selected);
if (selectedNodes.length > 0) {
// Deep clone the selected nodes to prevent reference issues
setClipboard({ nodes: JSON.parse(JSON.stringify(selectedNodes)) });
}
}, [reactFlowInstance]);
const handleCut = useCallback(() => {
const currentNodes = reactFlowInstance.getNodes();
const selectedNodes = currentNodes.filter(n => n.selected);
if (selectedNodes.length > 0) {
setClipboard({ nodes: JSON.parse(JSON.stringify(selectedNodes)) });
const selectedNodeIds = new Set(selectedNodes.map(n => n.id));
// Remove nodes and any edges connected to them
setNodes(nds => nds.filter(n => !selectedNodeIds.has(n.id)));
setEdges(eds => eds.filter(e => !selectedNodeIds.has(e.source) && !selectedNodeIds.has(e.target)));
}
}, [reactFlowInstance, setNodes, setEdges]);
const handlePaste = useCallback(() => {
if (clipboard.nodes.length > 0) {
const newNodes = clipboard.nodes.map(node => {
// Give the new node a unique ID and a slight positional offset
// so it doesn't overlap perfectly with the original
return {
...node,
id: Date.now().toString() + Math.random().toString(36).substr(2, 5),
position: {
x: node.position.x + 20,
y: node.position.y + 20
},
selected: true, // Automatically select the newly pasted node
data: {
...node.data,
// Ensure the pasted node gets a fresh display name (e.g., component_5)
componentDisplayName: generateComponentDisplayName()
}
};
});
// Deselect existing nodes and add the new ones
setNodes(nds => nds.map(n => ({...n, selected: false})).concat(newNodes));
// Update the clipboard with the new offset nodes so
// rapid pasting cascades them nicely
setClipboard({ nodes: newNodes });
}
}, [clipboard, setNodes, generateComponentDisplayName]);
const handleDelete = useCallback(() => {
const currentNodes = reactFlowInstance.getNodes();
const selectedNodes = currentNodes.filter(n => n.selected);
const selectedNodeIds = new Set(selectedNodes.map(n => n.id));
if (selectedNodeIds.size > 0) {
setNodes(nds => nds.filter(n => !selectedNodeIds.has(n.id)));
setEdges(eds => eds.filter(e => !selectedNodeIds.has(e.source) && !selectedNodeIds.has(e.target)));
}
}, [reactFlowInstance, setNodes, setEdges]);
// --- KEYBOARD SHORTCUTS ---
useEffect(() => {
const handleKeyDown = (e) => {
// Prevent actions if the user is typing in an input or textarea
if (document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA') {
return;
}
const cmdOrCtrl = e.ctrlKey || e.metaKey; // Supports Windows/Linux (Ctrl) and Mac (Cmd)
if (cmdOrCtrl && e.key.toLowerCase() === 'c') {
e.preventDefault();
handleCopy();
} else if (cmdOrCtrl && e.key.toLowerCase() === 'x') {
e.preventDefault();
handleCut();
} else if (cmdOrCtrl && e.key.toLowerCase() === 'v') {
e.preventDefault();
handlePaste();
} else if (e.key === 'Delete' || e.key === 'Backspace') {
// ReactFlow handles this natively if the canvas is focused,
// but this ensures it fires even if focus is outside the canvas wrapper.
handleDelete();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [handleCopy, handleCut, handlePaste, handleDelete]);
const componentCounterRef = useRef(1);
const generateComponentDisplayName = useCallback(() => {
+829
View File
@@ -0,0 +1,829 @@
<!DOCTYPE html>
<html lang="en">
{% raw %}
<head>
<meta charset="UTF-8">
<title>mxPIC Core - Canvas</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/reactflow@11/dist/umd/index.js" crossorigin></script>
<link rel="stylesheet" href="https://unpkg.com/reactflow@11/dist/style.css" />
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<style>
/* optihk Shared Dark Theme Variables */
:root {
--bg-main: #0f172a;
--bg-card: #1e293b;
--text-main: #f8fafc;
--text-muted: #94a3b8;
--accent: #38bdf8;
--accent-hover: #0284c7;
--border: #334155;
--input-bg: #0b1120;
}
body,
html,
#root {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
font-family: 'Inter', sans-serif;
background-color: var(--bg-main);
color: var(--text-main);
overflow: hidden;
}
/* Custom Dark Scrollbars */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--bg-main);
}
::-webkit-scrollbar-thumb {
background: var(--border);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--text-muted);
}
/* Tree View Styling */
details {
margin-left: 8px;
}
summary {
cursor: pointer;
padding: 4px 0;
color: var(--text-main);
}
.tree-folder summary {
font-weight: 500;
color: var(--accent);
}
.component-leaf {
cursor: grab;
padding: 4px 6px;
margin-left: 15px;
margin-top: 2px;
word-break: break-all;
white-space: normal;
border-radius: 4px;
color: var(--text-muted);
transition: background 0.2s ease, color 0.2s ease;
}
.component-leaf:hover {
background: var(--border);
color: var(--text-main);
}
/* Side Panel Blocks */
.left-block, .right-block {
background: var(--bg-main);
border: 1px solid var(--border);
border-radius: 6px;
margin-bottom: 12px;
overflow: hidden;
}
.left-block-header, .right-block-header {
background: var(--bg-card);
padding: 8px 12px;
font-weight: 600;
font-size: 0.85em;
border-bottom: 1px solid var(--border);
display: flex;
align-items: center;
justify-content: space-between;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 1px;
}
.left-block-body, .right-block-body {
padding: 12px;
font-size: 0.85em;
}
.placeholder-block {
border: 1px dashed var(--border);
padding: 12px;
color: var(--text-muted);
text-align: center;
background: var(--bg-main);
}
.toggle-btn {
background: none;
border: none;
font-size: 1.2em;
color: var(--text-muted);
cursor: pointer;
padding: 2px 6px;
border-radius: 4px;
transition: background 0.2s ease, color 0.2s ease;
}
.toggle-btn:hover {
background: var(--border);
color: var(--text-main);
}
/* Standard Form Inputs inside panels */
input[type="number"], input[type="text"] {
background-color: var(--input-bg);
border: 1px solid var(--border);
color: var(--text-main);
font-family: inherit;
font-size: 0.9em;
padding: 6px 10px;
border-radius: 4px;
outline: none;
width: 100%;
box-sizing: border-box;
transition: border-color 0.2s ease, box-shadow 0.2s ease;
}
input[type="number"]:focus, input[type="text"]:focus {
border-color: var(--accent);
box-shadow: 0 0 0 2px rgba(56, 189, 248, 0.2);
}
label {
font-weight: 500;
color: var(--text-muted);
margin-bottom: 4px;
display: block;
}
/* ReactFlow Dark Mode Overrides */
.react-flow__controls button {
background-color: var(--bg-card) !important;
border-bottom: 1px solid var(--border) !important;
fill: var(--text-main) !important;
}
.react-flow__controls button:hover {
background-color: var(--border) !important;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const { useState, useEffect, useRef, useCallback, useMemo, memo } = React;
const {
ReactFlow,
ReactFlowProvider,
useNodesState,
useEdgesState,
Controls,
Background,
useReactFlow,
addEdge,
Handle,
Position,
useUpdateNodeInternals,
} = window.ReactFlow;
// --- NODE DESIGN (Dark CAD Style) ---
const RotatableNode = ({ id, data, selected }) => {
const updateNodeInternals = useUpdateNodeInternals();
useEffect(() => {
updateNodeInternals(id);
}, [data.rotation, updateNodeInternals, id]);
const baseHandleStyle = {
width: 10, height: 10,
background: 'var(--bg-main)',
border: '2px solid var(--accent)',
borderRadius: '50%',
};
const leftTopPort = { ...baseHandleStyle, top: '24%', transform: 'translate(-50%, -50%)' };
const leftBottomPort = { ...baseHandleStyle, top: '76%', transform: 'translate(-50%, -50%)' };
const rightTopPort = { ...baseHandleStyle, top: '24%', transform: 'translate(50%, -50%)' };
const rightBottomPort = { ...baseHandleStyle, top: '76%', transform: 'translate(50%, -50%)' };
return (
<div style={{
padding: '10px 20px',
border: selected ? '2px solid var(--accent)' : '1px solid var(--border)',
borderRadius: 6,
background: 'var(--bg-card)',
color: 'var(--text-main)',
minWidth: 100, textAlign: 'center',
position: 'relative', transform: `rotate(${data.rotation || 0}deg)`,
transition: selected ? 'none' : 'transform 0.1s ease',
boxSizing: 'border-box',
boxShadow: selected ? '0 0 15px rgba(56, 189, 248, 0.2)' : '0 4px 6px rgba(0,0,0,0.3)',
fontFamily: "'Inter', sans-serif",
fontSize: '0.85rem'
}}>
<div>{data.componentDisplayName}</div>
<Handle type="source" position={Position.Left} id="port-lt-source" style={{ ...leftTopPort, zIndex: 10 }} />
<Handle type="target" position={Position.Left} id="port-lt-target" style={{ ...leftTopPort, zIndex: 5 }} />
<Handle type="source" position={Position.Left} id="port-lb-source" style={{ ...leftBottomPort, zIndex: 10 }} />
<Handle type="target" position={Position.Left} id="port-lb-target" style={{ ...leftBottomPort, zIndex: 5 }} />
<Handle type="source" position={Position.Right} id="port-rt-source" style={{ ...rightTopPort, zIndex: 10 }} />
<Handle type="target" position={Position.Right} id="port-rt-target" style={{ ...rightTopPort, zIndex: 5 }} />
<Handle type="source" position={Position.Right} id="port-rb-source" style={{ ...rightBottomPort, zIndex: 10 }} />
<Handle type="target" position={Position.Right} id="port-rb-target" style={{ ...rightBottomPort, zIndex: 5 }} />
</div>
);
};
const TreeNode = ({ name, children }) => {
if (children && children.__type__ === 'component') {
const componentName = children.__name__;
const handleDragStart = (event) => {
event.dataTransfer.setData('application/reactflow', componentName);
event.dataTransfer.effectAllowed = 'move';
};
return (
<div className="component-leaf" draggable onDragStart={handleDragStart}>
<span style={{color: 'var(--accent)', marginRight: '4px'}}></span> {name}
</div>
);
}
const hasChildren = children && Object.keys(children).length > 0;
return (
<details>
<summary className="tree-folder">
<span style={{ wordBreak: 'break-all', whiteSpace: 'normal' }}>📂 {name}</span>
</summary>
{hasChildren &&
Object.entries(children).map(([childName, childData]) => (
<TreeNode key={childName} name={childName} children={childData} />
))
}
</details>
);
};
const LeftPanel = ({ library, treeKey, expanded, onToggle, treeRef, width }) => (
<aside style={{
width: width, background: 'var(--bg-card)', borderRight: '1px solid var(--border)',
padding: 12, display: 'flex', flexDirection: 'column', height: '100%',
boxSizing: 'border-box', overflowY: 'auto'
}}>
<div className="left-block">
<div className="left-block-header">
<span>PDK Libraries</span>
<button className="toggle-btn" onClick={onToggle} title={expanded ? 'Collapse all' : 'Expand all'}>
{expanded ? '▾' : '▸'}
</button>
</div>
<div className="left-block-body" style={{ maxHeight: '45vh', overflowY: 'auto' }} key={treeKey} ref={treeRef}>
{library && Object.keys(library).length > 0 ? (
Object.entries(library).map(([key, value]) => (
<TreeNode key={key} name={key} children={value} />
))
) : (
<p style={{ color: 'var(--text-muted)', fontStyle: 'italic' }}>Loading library...</p>
)}
</div>
</div>
<div className="left-block">
<div className="left-block-header">Routing modes</div>
<div className="left-block-body">
<ul style={{ paddingLeft: 20, margin: 0, color: 'var(--text-muted)', lineHeight: '1.8' }}>
<li>Single mode wires</li>
<li>Multi-mode wires</li>
<li>DC electrical wires</li>
<li>RF electrical wires</li>
</ul>
</div>
</div>
<div className="left-block" style={{ marginTop: 'auto' }}>
<div className="left-block-header">Session</div>
<div className="left-block-body" style={{color: 'var(--text-muted)'}}>
<div style={{marginBottom: '4px'}}>Name: XXXXXX</div>
<div style={{marginBottom: '10px'}}>ID: 12345678</div>
<button disabled style={{
background: 'var(--border)', color: 'var(--text-muted)',
border: 'none', padding: '6px 12px', borderRadius: '4px', width: '100%'
}}>Log out</button>
</div>
</div>
</aside>
);
const RightPanel = memo(({ selectedNode, width, onRenameComponent }) => {
const [componentData, setComponentData] = useState(null);
const [loading, setLoading] = useState(false);
const [enlarged, setEnlarged] = useState(null);
const { setNodes } = useReactFlow();
const [editingComponentName, setEditingComponentName] = useState(false);
const [tempComponentName, setTempComponentName] = useState('');
const [localX, setLocalX] = useState('');
const [localY, setLocalY] = useState('');
const [localRotation, setLocalRotation] = useState('');
useEffect(() => {
const nodeId = selectedNode?.id;
if (!nodeId) {
setComponentData(null);
setLoading(false);
return;
}
const compName = selectedNode?.data?.componentName;
if (!compName) {
setComponentData(null);
setLoading(false);
return;
}
if (componentData && componentData.name === compName && componentData.nodeId === nodeId) return;
setLoading(true);
fetch(`/api/component/${encodeURIComponent(compName)}`)
.then(r => r.json())
.then(data => {
setComponentData({ ...data, nodeId: nodeId, componentDisplayName: selectedNode.data.componentDisplayName || data.name });
setLoading(false);
})
.catch(() => setLoading(false));
}, [selectedNode?.id, selectedNode?.data?.componentName, selectedNode?.data?.componentDisplayName]);
useEffect(() => {
if (selectedNode) {
setLocalX(selectedNode.position.x.toFixed(3));
setLocalY(selectedNode.position.y.toFixed(3));
setLocalRotation(((selectedNode.data?.rotation || 0)).toFixed(3));
}
}, [selectedNode?.position.x, selectedNode?.position.y, selectedNode?.data?.rotation, selectedNode?.id]);
const updatePosition = useCallback((id, axis, value) => {
const val = parseFloat(value);
if (isNaN(val)) return;
setNodes(nds => nds.map(n => n.id === id ? { ...n, position: { ...n.position, [axis]: val } } : n));
}, [setNodes]);
const updateRotation = useCallback((id, value) => {
const val = parseFloat(value);
if (isNaN(val)) return;
const clamped = Math.min(180, Math.max(-180, val));
setNodes(nds => nds.map(n => n.id === id ? { ...n, data: { ...n.data, rotation: clamped } } : n));
}, [setNodes]);
const formatPort = (port) => {
if (!port) return '—';
return `x:${port.x ?? '?'}, y:${port.y ?? '?'}, a:${port.a ?? '?'}, w:${port.width ?? '?'}`;
};
const currentRotation = selectedNode?.data?.rotation ?? 0;
const currentComponentDisplayName = selectedNode?.data?.componentDisplayName || '';
const handleStartEditName = () => {
setTempComponentName(currentComponentDisplayName);
setEditingComponentName(true);
};
const handleSaveName = () => {
const newName = tempComponentName.trim();
if (newName && selectedNode) {
onRenameComponent(selectedNode.id, newName);
}
setEditingComponentName(false);
};
const handleKeyDown = (e) => {
if (e.key === 'Enter') {
handleSaveName();
} else if (e.key === 'Escape') {
setEditingComponentName(false);
}
};
return (
<aside style={{
width: width, background: 'var(--bg-card)', borderLeft: '1px solid var(--border)',
padding: 12, display: 'flex', flexDirection: 'column', height: '100%',
boxSizing: 'border-box', overflowY: 'auto'
}}>
<div className="right-block">
<div className="right-block-header">Transforms</div>
<div className="right-block-body">
{selectedNode ? (
<div>
<label>X Coordinate</label>
<input
type="number"
step="1"
value={localX}
onChange={(e) => setLocalX(e.target.value)}
onBlur={() => {
const val = parseFloat(localX);
if (!isNaN(val) && selectedNode) {
updatePosition(selectedNode.id, 'x', val);
setLocalX(val.toFixed(3));
} else if (selectedNode) {
setLocalX(selectedNode.position.x.toFixed(3));
}
}}
onKeyDown={(e) => {
if (e.key === 'Enter') e.currentTarget.blur();
}}
/>
<br /><br />
<label>Y Coordinate</label>
<input
type="number"
step="1"
value={localY}
onChange={(e) => setLocalY(e.target.value)}
onBlur={() => {
const val = parseFloat(localY);
if (!isNaN(val) && selectedNode) {
updatePosition(selectedNode.id, 'y', val);
setLocalY(val.toFixed(3));
} else if (selectedNode) {
setLocalY(selectedNode.position.y.toFixed(3));
}
}}
onKeyDown={(e) => {
if (e.key === 'Enter') e.currentTarget.blur();
}}
/>
<br /><br />
<label>Angle (deg)</label>
<input
type="number"
step="1"
value={localRotation}
onChange={(e) => setLocalRotation(e.target.value)}
onBlur={() => {
const val = parseFloat(localRotation);
if (!isNaN(val) && selectedNode) {
updateRotation(selectedNode.id, val);
setLocalRotation(val.toFixed(3));
} else if (selectedNode) {
setLocalRotation(((selectedNode.data?.rotation || 0)).toFixed(3));
}
}}
onKeyDown={(e) => {
if (e.key === 'Enter') e.currentTarget.blur();
}}
/>
</div>
) : (
<p style={{ color: 'var(--text-muted)', fontStyle: 'italic', textAlign: 'center' }}>Select a node to inspect</p>
)}
</div>
</div>
{selectedNode?.data?.componentName && (
<div className="right-block">
<div className="right-block-header">Parameters</div>
<div className="right-block-body">
{loading ? (
<p style={{color: 'var(--text-muted)'}}>Loading data...</p>
) : componentData ? (
<>
<div style={{ marginBottom: '15px' }}>
<label>Instance Name</label>
{editingComponentName ? (
<input
type="text"
value={tempComponentName}
onChange={(e) => setTempComponentName(e.target.value)}
onBlur={handleSaveName}
onKeyDown={handleKeyDown}
autoFocus
/>
) : (
<div
style={{
cursor: 'pointer',
padding: '6px 8px',
backgroundColor: 'var(--input-bg)',
border: '1px solid var(--border)',
borderRadius: '4px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
wordBreak: 'break-all',
color: 'var(--accent)'
}}
onClick={handleStartEditName}
title="Click to edit"
>
<span>{currentComponentDisplayName || componentData.name}</span>
<span style={{fontSize: '12px', color: 'var(--text-muted)'}}></span>
</div>
)}
</div>
<div style={{color: 'var(--text-muted)', lineHeight: '1.6'}}>
<p style={{ margin: '0 0 8px 0', wordBreak: 'break-all' }}>
<strong style={{color: 'var(--text-main)'}}>Cell:</strong> {componentData.name}
</p>
<p style={{ margin: '0 0 8px 0' }}>
<strong style={{color: 'var(--text-main)'}}>Foundry:</strong> {componentData.foundry}<br/>
<strong style={{color: 'var(--text-main)'}}>Process:</strong> {componentData.process}
</p>
</div>
<p style={{color: 'var(--text-main)', fontWeight: '500', marginBottom: '4px'}}>Ports:</p>
<ul style={{ paddingLeft: 15, margin: '0 0 15px 0', color: 'var(--text-muted)' }}>
{componentData.ports && Object.entries(componentData.ports).map(([portName, portInfo]) => (
<li key={portName} style={{ letterSpacing: '0.5px' }}>
<span style={{color: 'var(--accent)'}}>{portName}</span>: {formatPort(portInfo)}
</li>
))}
</ul>
<p style={{color: 'var(--text-main)', fontWeight: '500', marginBottom: '4px'}}>Preview:</p>
<div style={{
border: '1px solid var(--border)', width: '100%', height: 100,
display: 'flex', alignItems: 'center', justifyContent: 'center',
background: 'var(--input-bg)', borderRadius: '4px',
overflow: 'hidden',
}}>
<img
src={`/api/component/${encodeURIComponent(componentData.name)}/image`}
alt="Component layout"
style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain', cursor: 'pointer' }}
onClick={() => setEnlarged(`/api/component/${encodeURIComponent(componentData.name)}/image`)}
onError={(e) => {
e.currentTarget.style.display = 'none';
e.currentTarget.parentElement.innerHTML = '<span style="color:var(--text-muted)">No preview</span>';
}}
/>
</div>
</>
) : (
<p style={{ color: 'var(--text-muted)' }}>No data available</p>
)}
</div>
</div>
)}
<div className="right-block" style={{ marginTop: 'auto' }}>
<div className="right-block-header">Inverse Design</div>
<div className="right-block-body placeholder-block">Requires AI Upgrade</div>
</div>
{enlarged && (
<div
style={{
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
backgroundColor: 'rgba(15, 23, 42, 0.9)', zIndex: 1000,
display: 'flex', alignItems: 'center', justifyContent: 'center',
cursor: 'zoom-out',
backdropFilter: 'blur(4px)'
}}
onClick={() => setEnlarged(null)}
>
<img
src={enlarged}
alt="Enlarged layout"
style={{ maxWidth: '90%', maxHeight: '90%', objectFit: 'contain', border: '1px solid var(--border)', background: 'var(--bg-main)' }}
/>
</div>
)}
</aside>
);
}, (prevProps, nextProps) => {
const prev = prevProps.selectedNode;
const next = nextProps.selectedNode;
if (prev?.id !== next?.id) return false;
if (prev?.position?.x !== next?.position?.x) return false;
if (prev?.position?.y !== next?.position?.y) return false;
if (prev?.data?.rotation !== next?.data?.rotation) return false;
if (prev?.data?.componentName !== next?.data?.componentName) return false;
if (prev?.data?.componentDisplayName !== next?.data?.componentDisplayName) return false;
if (prevProps.width !== nextProps.width) return false;
return true;
});
const ResizeHandle = ({ onMouseDown }) => (
<div
onMouseDown={onMouseDown}
style={{
width: 6, cursor: 'col-resize', background: 'transparent',
transition: 'background 0.2s', zIndex: 5, flexShrink: 0,
}}
onMouseEnter={(e) => e.currentTarget.style.background = 'var(--accent)'}
onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
/>
);
function App() {
const [nodes, setNodes, onNodesChange] = useNodesState([]);
const [edges, setEdges, onEdgesChange] = useEdgesState([]);
const reactFlowInstance = useReactFlow();
const [library, setLibrary] = useState(null);
const [treeKey, setTreeKey] = useState(0);
const [expanded, setExpanded] = useState(false);
const treeContainerRef = useRef(null);
const [leftWidth, setLeftWidth] = useState(260);
const [rightWidth, setRightWidth] = useState(260);
const [dragging, setDragging] = useState(null);
const [gridSnap, setGridSnap] = useState(false);
const componentCounterRef = useRef(1);
const generateComponentDisplayName = useCallback(() => {
const name = `component_${componentCounterRef.current}`;
componentCounterRef.current += 1;
return name;
}, []);
const renameComponent = useCallback((nodeId, newComponentDisplayName) => {
setNodes(nds => nds.map(n => {
if (n.id === nodeId) {
return {
...n,
data: {
...n.data,
componentDisplayName: newComponentDisplayName
}
};
}
return n;
}));
}, [setNodes]);
const fetchLibrary = useCallback(async () => {
try {
const res = await fetch('/api/library');
const data = await res.json();
setLibrary(data);
} catch (err) {
console.error('Failed to fetch library', err);
}
}, []);
useEffect(() => { fetchLibrary(); }, [fetchLibrary]);
const selectedNode = useMemo(() => nodes.find(n => n.selected), [nodes]);
const onDragOver = useCallback((event) => {
event.preventDefault();
event.dataTransfer.dropEffect = 'move';
}, []);
const onDrop = useCallback((event) => {
event.preventDefault();
const type = event.dataTransfer.getData('application/reactflow');
if (!type) return;
const position = reactFlowInstance.screenToFlowPosition({
x: event.clientX,
y: event.clientY,
});
const componentDisplayName = generateComponentDisplayName();
const newNode = {
id: Date.now().toString(),
type: 'rotatableNode',
position,
data: {
label: type,
componentName: type,
rotation: 0,
componentDisplayName: componentDisplayName
},
};
setNodes((nds) => nds.concat(newNode));
}, [setNodes, reactFlowInstance, generateComponentDisplayName]);
const onConnect = useCallback((connection) => {
setEdges((eds) => addEdge({ ...connection, type: 'smoothstep', style: { stroke: 'var(--accent)', strokeWidth: 2 } }, eds));
}, [setEdges]);
const expandAll = useCallback(() => {
if (treeContainerRef.current) {
treeContainerRef.current.querySelectorAll('details').forEach(d => d.open = true);
}
}, []);
const collapseAll = useCallback(() => setTreeKey(k => k + 1), []);
const handleToggle = useCallback(() => {
if (expanded) { collapseAll(); setExpanded(false); }
else { expandAll(); setExpanded(true); }
}, [expanded, expandAll, collapseAll]);
const handleResizeStart = useCallback((side) => (e) => {
e.preventDefault();
setDragging(side);
}, []);
useEffect(() => {
if (!dragging) return;
const onMouseMove = (e) => {
if (dragging === 'left') {
setLeftWidth(Math.min(500, Math.max(150, e.clientX)));
} else if (dragging === 'right') {
const newWidth = window.innerWidth - e.clientX;
setRightWidth(Math.min(500, Math.max(150, newWidth)));
}
};
const onMouseUp = () => setDragging(null);
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mouseup', onMouseUp);
return () => {
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', onMouseUp);
};
}, [dragging]);
const toggleGridSnap = useCallback(() => {
setGridSnap(prev => !prev);
}, []);
return (
<div style={{ display: 'flex', width: '100%', height: '100%', userSelect: dragging ? 'none' : 'auto' }}>
<LeftPanel
library={library} treeKey={treeKey} expanded={expanded}
onToggle={handleToggle} treeRef={treeContainerRef} width={leftWidth}
/>
<ResizeHandle onMouseDown={handleResizeStart('left')} />
<div style={{ flex: 1, position: 'relative' }}>
{/* Grid Snap Toggle Switch */}
<div style={{
position: 'absolute', top: 15, right: 15, zIndex: 10,
display: 'flex', alignItems: 'center', gap: 10,
background: 'var(--bg-card)', padding: '6px 12px', borderRadius: '8px',
border: '1px solid var(--border)', boxShadow: '0 4px 6px rgba(0,0,0,0.3)'
}}>
<span style={{
fontSize: '0.85em', fontWeight: '500', color: 'var(--text-main)', userSelect: 'none'
}}>Snap to Grid</span>
<div
onClick={toggleGridSnap}
style={{
width: 40, height: 20, borderRadius: 10,
background: gridSnap ? 'var(--accent)' : 'var(--input-bg)',
border: '1px solid ' + (gridSnap ? 'var(--accent)' : 'var(--border)'),
cursor: 'pointer', display: 'flex', alignItems: 'center',
padding: '0 2px', transition: 'background 0.3s, border-color 0.3s',
}}
>
<div style={{
width: 16, height: 16, borderRadius: '50%',
background: '#fff',
transform: gridSnap ? 'translateX(20px)' : 'translateX(0)',
transition: 'transform 0.2s',
}} />
</div>
</div>
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onDragOver={onDragOver}
onDrop={onDrop}
onConnect={onConnect}
nodeTypes={{ rotatableNode: RotatableNode }}
fitView
snapToGrid={gridSnap}
snapGrid={[10, 10]}
nodesDraggable={true}
nodesConnectable={true}
elementsSelectable={true}
connectionRadius={50}
>
<Controls style={{ bottom: 15, left: 15 }} />
{/* Dark mode background for the canvas */}
<Background color="#334155" gap={20} size={1} />
</ReactFlow>
</div>
<ResizeHandle onMouseDown={handleResizeStart('right')} />
<RightPanel
selectedNode={selectedNode}
width={rightWidth}
onRenameComponent={renameComponent}
/>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<ReactFlowProvider>
<App />
</ReactFlowProvider>
);
</script>
</body>
</html>
{% endraw %}