port/archor box update, ruler function update

This commit is contained in:
xsxx03-art
2026-06-22 20:10:07 +08:00
parent 944bc26fb9
commit bc2e46f648
3 changed files with 484 additions and 73 deletions
+3 -3
View File
@@ -28,13 +28,13 @@
// Default editable canvas dimensions in micrometers.
const DEFAULT_CANVAS_SIZE = { width: 5000, height: 5000 };
// Base visual diameter and hit area used for port and anchor handles.
const PORT_NODE_SIZE = 30;
const PORT_NODE_SIZE = 11;
const FREE_WIRES_BUNDLE_GROUP = 'free_wires';
const PORT_LABEL_MIN_CHARS = 5;
const PORT_LABEL_CHAR_WIDTH = 7;
const PORT_LABEL_HORIZONTAL_PADDING = 12;
// Anchor body width used in the canvas visual representation.
const ANCHOR_NODE_WIDTH = 16;
const ANCHOR_NODE_WIDTH = 18;
// Default spacing between repeated anchor or port pins.
const DEFAULT_ELEMENT_PITCH = 10;
// Defines built-in port and anchor element metadata before per-node expansion.
@@ -810,7 +810,7 @@
return {
width: data && data.elementType === 'anchor' ? ANCHOR_NODE_WIDTH : PORT_NODE_SIZE,
height: data && data.elementType === 'anchor'
? Math.max(PORT_NODE_SIZE / 2, PORT_NODE_SIZE / 2 + Math.max(0, portNumber - 1) * handleClearance)
? Math.max(PORT_NODE_SIZE * 1.125, PORT_NODE_SIZE * 1.125 + Math.max(0, portNumber - 1) * handleClearance)
: Math.max(PORT_NODE_SIZE, PORT_NODE_SIZE + Math.max(0, portNumber - 1) * handleClearance)
};
};
+474 -69
View File
@@ -17,12 +17,24 @@ Organization : OptiHK Limited
<link rel="preconnect" href="https://unpkg.com">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600;700&family=IBM+Plex+Mono:wght@500;600&display=swap" rel="stylesheet">
<script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.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>
<script src="https://cdn.jsdelivr.net/npm/js-yaml@4/dist/js-yaml.min.js"></script>
<!-- 2026.06.22 Qin Yue revised for canvas break down error: previous floating dependency kept for reference. -->
<!-- <script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin></script> -->
<script src="https://unpkg.com/react@18.3.1/umd/react.production.min.js" crossorigin></script>
<!-- 2026.06.22 Qin Yue revised for canvas break down error: previous floating dependency kept for reference. -->
<!-- <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin></script> -->
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.production.min.js" crossorigin></script>
<!-- 2026.06.22 Qin Yue revised for canvas break down error: previous floating dependency kept for reference. -->
<!-- <script src="https://unpkg.com/reactflow@11/dist/umd/index.js" crossorigin></script> -->
<script src="https://unpkg.com/reactflow@11.11.4/dist/umd/index.js" crossorigin></script>
<!-- 2026.06.22 Qin Yue revised for canvas break down error: previous floating dependency kept for reference. -->
<!-- <link rel="stylesheet" href="https://unpkg.com/reactflow@11/dist/style.css" /> -->
<link rel="stylesheet" href="https://unpkg.com/reactflow@11.11.4/dist/style.css" />
<!-- 2026.06.22 Qin Yue revised for canvas break down error: previous floating dependency kept for reference. -->
<!-- <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> -->
<script src="https://unpkg.com/@babel/standalone@7.29.7/babel.min.js"></script>
<!-- 2026.06.22 Qin Yue revised for canvas break down error: previous floating dependency kept for reference. -->
<!-- <script src="https://cdn.jsdelivr.net/npm/js-yaml@4/dist/js-yaml.min.js"></script> -->
<script src="https://cdn.jsdelivr.net/npm/js-yaml@4.2.0/dist/js-yaml.min.js"></script>
<script src="/canvas-helpers.js"></script>
<style>
:root {
@@ -675,6 +687,20 @@ Organization : OptiHK Limited
box-shadow: 0 0 0 1px rgba(45, 212, 191, 0.2), 0 10px 20px rgba(45, 212, 191, 0.12);
}
.ruler-btn.active {
background: rgba(45, 212, 191, 0.18);
border-color: #2dd4bf;
color: #2dd4bf;
box-shadow: 0 0 0 1px rgba(45, 212, 191, 0.2), 0 6px 16px rgba(45, 212, 191, 0.15);
}
body.light-mode .ruler-btn.active {
background: rgba(13, 148, 136, 0.14);
border-color: #0d9488;
color: #0f766e;
box-shadow: 0 0 0 1px rgba(13, 148, 136, 0.18), 0 4px 12px rgba(13, 148, 136, 0.12);
}
body.light-mode .mini-btn {
background: var(--mini-button-bg);
border-color: rgba(30, 48, 69, 0.18);
@@ -1370,10 +1396,10 @@ Organization : OptiHK Limited
bottom: calc(100% + 7px);
transform: translateX(-50%);
z-index: 8;
min-width: 84px;
width: max-content;
max-width: 160px;
padding: 3px 6px;
border-radius: 5px;
padding: 2px 5px;
border-radius: 3px;
border: 1px solid var(--floating-label-border);
background: var(--floating-label-bg);
color: var(--text-main);
@@ -1435,6 +1461,18 @@ Organization : OptiHK Limited
font-size: 0.32rem;
}
.component-name-below {
margin-top: 5px;
color: var(--text-muted);
font-size: 0.3rem;
font-weight: 600;
font-family: 'IBM Plex Mono', Consolas, monospace;
text-align: center;
overflow-wrap: anywhere;
word-break: break-word;
pointer-events: none;
}
.canvas-size-panel {
display: grid;
grid-template-columns: 1fr 1fr;
@@ -1517,7 +1555,6 @@ Organization : OptiHK Limited
border: 2px solid #f8fafc;
background: var(--accent-green);
box-shadow: 0 0 0 4px rgba(45, 212, 191, 0.18), 0 8px 18px rgba(0, 0, 0, 0.28);
pointer-events: none;
}
.ruler-measurement-node {
@@ -1530,8 +1567,7 @@ Organization : OptiHK Limited
box-shadow: 0 10px 24px rgba(0, 0, 0, 0.3);
font: 600 0.5rem/1.35 'IBM Plex Mono', Consolas, Monaco, monospace;
text-align: center;
transform: translate(-50%, -50%);
pointer-events: none;
transform: translate(-50%, calc(-50% + 26px));
white-space: nowrap;
}
@@ -1541,6 +1577,25 @@ Organization : OptiHK Limited
box-shadow: 0 10px 24px rgba(18, 32, 51, 0.14);
}
.ruler-cursor-dot {
position: absolute;
pointer-events: none;
z-index: 100;
width: 12px;
height: 12px;
border-radius: 50%;
background: #2dd4bf;
border: 2px solid rgba(45, 212, 191, 0.5);
box-shadow: 0 0 12px rgba(45, 212, 191, 0.5), 0 0 4px rgba(45, 212, 191, 0.3);
transform: translate(-50%, -50%);
}
body.light-mode .ruler-cursor-dot {
background: #0d9488;
border-color: rgba(13, 148, 136, 0.5);
box-shadow: 0 0 12px rgba(13, 148, 136, 0.4), 0 0 4px rgba(13, 148, 136, 0.25);
}
.ruler-status {
position: absolute;
left: 50%;
@@ -1823,6 +1878,8 @@ Organization : OptiHK Limited
() => buildPortHandles(flippedPorts, { rotation: 0, boxSize: componentSize }),
[data.ports, data.rotation, data.flip, data.flop, componentSize]
);
const hasBottomHandles = portHandles.some(h => h.position === 'bottom');
const hasTopHandles = portHandles.some(h => h.position === 'top');
const portDirectionMap = useMemo(
() => new Map(portHandles.map(handle => [handle.name, handle.position])),
[portHandles]
@@ -1853,11 +1910,8 @@ Organization : OptiHK Limited
className="component-node-shell"
style={{ width: visualSize.width, minWidth: visualSize.width, maxWidth: visualSize.width, minHeight: visualSize.height }}
>
<div className="component-floating-label" title={data.componentDisplayName}>
<div className="component-floating-label" title={data.componentDisplayName} style={hasTopHandles ? { bottom: 'calc(100% + 27px)' } : undefined}>
<strong>{data.componentDisplayName}</strong>
{data.componentName && data.componentName !== data.componentDisplayName && (
<span title={data.componentName}>{data.componentName}</span>
)}
</div>
<div
className="component-visual-body"
@@ -1939,6 +1993,9 @@ Organization : OptiHK Limited
</span>
))}
</div>
{data.componentName && data.componentName !== data.componentDisplayName && (
<div className="component-name-below" title={data.componentName} style={{ marginTop: hasBottomHandles ? 24 : 5 }}>{data.componentName}</div>
)}
</div>
);
}, (prevProps, nextProps) => {
@@ -1993,8 +2050,8 @@ Organization : OptiHK Limited
width: 7,
height: 7,
borderRadius: '50%',
border: selected ? '2px solid white' : '1px solid rgba(239,68,68,0.5)',
boxShadow: selected ? '0 0 8px rgba(239,68,68,0.5)' : 'none'
border: selected ? '1.5px solid rgba(0,0,0,0.5)' : '1.5px solid #fff',
boxShadow: selected ? '0 0 10px rgba(0,0,0,0.35)' : '0 0 10px rgba(255,255,255,0.8)'
};
const pinLabelStyle = (portHandle) => {
const base = {
@@ -2012,10 +2069,18 @@ Organization : OptiHK Limited
transform: `scaleX(${data.flop ? -1 : 1}) scaleY(${data.flip ? -1 : 1})`
};
return (
<div style={{ width: elementSize.width, height: elementSize.height, position: 'relative' }}>
<>
<div style={{
width: elementSize.width,
height: elementSize.height,
position: 'relative',
border: '2px solid var(--border-strong)',
borderRadius: 4,
background: 'rgba(239,68,68,0.08)',
boxShadow: 'none'
}}>
<div className="component-floating-label" title={portDisplayName}>
<strong>{portDisplayName}</strong>
<span>Port</span>
</div>
{portHandles.map((portHandle) => (
<React.Fragment key={portHandle.name}>
@@ -2037,6 +2102,8 @@ Organization : OptiHK Limited
</React.Fragment>
))}
</div>
<div className="component-name-below">Port</div>
</>
);
};
@@ -2066,11 +2133,12 @@ Organization : OptiHK Limited
bottom: Position.Bottom
};
const baseHandleStyle = {
width: 5,
height: 5,
background: 'var(--accent)',
border: '1px solid var(--bg-main)',
borderRadius: '50%'
width: 7,
height: 7,
background: selected ? 'var(--accent)' : 'var(--accent)',
border: selected ? '1.5px solid rgba(0,0,0,0.5)' : '1.5px solid #fff',
borderRadius: '50%',
boxShadow: selected ? '0 0 10px rgba(0,0,0,0.35)' : '0 0 10px rgba(255,255,255,0.8)'
};
const anchorPortVisualSide = (portName) => {
const name = String(portName || '');
@@ -2104,21 +2172,21 @@ Organization : OptiHK Limited
}, [id, data.ports, data.rotation, data.flip, data.flop, updateNodeInternals]);
return (
<>
<div className="anchor-node-shell" style={{ width: elementSize.width, height: elementSize.height }}>
<div className="component-floating-label" title={anchorDisplayName}>
<strong>{anchorDisplayName}</strong>
<span>Anchor</span>
</div>
<div className="anchor-visual-body" style={{
width: elementSize.width,
height: elementSize.height,
borderRadius: 999,
background: selected ? 'var(--accent)' : 'var(--bg-card)',
border: selected ? '2px solid white' : '2px solid var(--accent)',
color: selected ? 'white' : 'var(--accent)',
borderRadius: 4,
background: 'rgba(239,68,68,0.08)',
border: '2px solid var(--border-strong)',
color: 'var(--accent)',
fontSize: 10,
fontWeight: 800,
boxShadow: selected ? '0 0 10px rgba(56,189,248,0.4)' : 'none',
boxShadow: 'none',
transform: `rotate(${anchorVisualRotation}deg)`,
}}>
{portHandles.map((portHandle) => (
@@ -2144,6 +2212,8 @@ Organization : OptiHK Limited
))}
</div>
</div>
<div className="component-name-below">Anchor</div>
</>
);
});
@@ -2170,8 +2240,14 @@ Organization : OptiHK Limited
return (
<>
<div className="ruler-point-node" title={data.label || 'Ruler point'} />
<Handle type="source" position={Position.Right} id="route" style={hiddenHandleStyle} isConnectable={false} />
<Handle type="target" position={Position.Left} id="route" style={hiddenHandleStyle} isConnectable={false} />
<Handle type="source" position={Position.Top} id="ruler-top" style={hiddenHandleStyle} isConnectable={false} />
<Handle type="source" position={Position.Bottom} id="ruler-bottom" style={hiddenHandleStyle} isConnectable={false} />
<Handle type="source" position={Position.Left} id="ruler-left" style={hiddenHandleStyle} isConnectable={false} />
<Handle type="source" position={Position.Right} id="ruler-right" style={hiddenHandleStyle} isConnectable={false} />
<Handle type="target" position={Position.Top} id="ruler-top" style={hiddenHandleStyle} isConnectable={false} />
<Handle type="target" position={Position.Bottom} id="ruler-bottom" style={hiddenHandleStyle} isConnectable={false} />
<Handle type="target" position={Position.Left} id="ruler-left" style={hiddenHandleStyle} isConnectable={false} />
<Handle type="target" position={Position.Right} id="ruler-right" style={hiddenHandleStyle} isConnectable={false} />
</>
);
});
@@ -2274,6 +2350,131 @@ Organization : OptiHK Limited
);
});
// Ruler measurement edge with native-DOM drag support.
// React Flow cannot natively drag edges; this component attaches raw
// mousedown/mousemove/mouseup to the SVG interaction path so the user
// can drag the edge itself to translate the whole measurement group.
// Line is drawn between node CENTERS (position + 6 for 12px nodes),
// NOT from React Flow's sourceX/sourceY, to guarantee the edge always
// passes through both endpoint centres regardless of handle selection.
const RulerEdge = memo(({ id, source, target, sourceX, sourceY, targetX, targetY, style, selected, data }) => {
const interactionRef = useRef(null);
const rfInstance = useReactFlow();
// Compute center-to-center endpoints from current node positions.
const getCenterEndpoints = () => {
const rfNodes = rfInstance.getNodes();
const startNode = rfNodes.find(n => n.id === source);
const endNode = rfNodes.find(n => n.id === target);
if (startNode && endNode) {
return {
cx1: startNode.position.x + 6,
cy1: startNode.position.y + 6,
cx2: endNode.position.x + 6,
cy2: endNode.position.y + 6
};
}
// Fallback to React Flow computed points.
return { cx1: sourceX, cy1: sourceY, cx2: targetX, cy2: targetY };
};
const { cx1, cy1, cx2, cy2 } = getCenterEndpoints();
useEffect(() => {
const el = interactionRef.current;
if (!el) return;
const handleMouseDown = (e) => {
e.preventDefault();
e.stopPropagation();
const rulerGroupId = data?.rulerGroupId;
if (!rulerGroupId) return;
const nodes = rfInstance.getNodes();
const groupNodes = nodes.filter(n => n.data?.rulerGroupId === rulerGroupId);
if (groupNodes.length === 0) return;
const startNodes = groupNodes.map(n => ({ id: n.id, x: n.position.x, y: n.position.y }));
const startMouse = rfInstance.screenToFlowPosition({ x: e.clientX, y: e.clientY });
if (!startMouse) return;
const canvasSize = data?.canvasSize || { width: 5000, height: 5000 };
const endpointIds = groupNodes
.filter(n => !n.id.startsWith('ruler_label_'))
.map(n => n.id);
// Select endpoints in React Flow store so they show selection rings.
const allNodesForSelect = rfInstance.getNodes();
rfInstance.setNodes(allNodesForSelect.map(n => ({
...n,
selected: endpointIds.includes(n.id)
})));
// Also select this edge (highlight it) and deselect other edges.
const allEdges = rfInstance.getEdges();
if (allEdges) {
rfInstance.setEdges(allEdges.map(e => ({
...e,
selected: e.data?.rulerGroupId === rulerGroupId
})));
}
const handleMouseMove = (me) => {
const currentPoint = rfInstance.screenToFlowPosition({ x: me.clientX, y: me.clientY });
if (!currentPoint) return;
const dx = Number((currentPoint.x - startMouse.x).toFixed(3));
const dy = Number((currentPoint.y - startMouse.y).toFixed(3));
if (Math.abs(dx) < 0.3 && Math.abs(dy) < 0.3) return;
const allNodes = rfInstance.getNodes();
rfInstance.setNodes(allNodes.map(node => {
const sn = startNodes.find(n => n.id === node.id);
if (!sn) return node;
const nx = Math.min(canvasSize.width, Math.max(0, sn.x + dx));
const ny = Math.min(canvasSize.height, Math.max(0, sn.y + dy));
return { ...node, position: { x: Number(nx.toFixed(3)), y: Number(ny.toFixed(3)) } };
}));
};
const handleMouseUp = () => {
window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mouseup', handleMouseUp);
};
window.addEventListener('mousemove', handleMouseMove);
window.addEventListener('mouseup', handleMouseUp);
};
el.addEventListener('mousedown', handleMouseDown);
return () => el.removeEventListener('mousedown', handleMouseDown);
}, [data?.rulerGroupId, data?.canvasSize, rfInstance]);
const d = `M ${cx1} ${cy1} L ${cx2} ${cy2}`;
const strokeColor = style?.stroke || '#2dd4bf';
const strokeW = selected ? 4 : (style?.strokeWidth || 2);
const pathFilter = selected ? 'drop-shadow(0 0 5px rgba(45,212,191,0.45))' : undefined;
return (
<g className="react-flow__edge">
{data?.rulerGroupId ? (
<path
d={d}
fill="none"
stroke="transparent"
strokeWidth={20}
ref={interactionRef}
style={{ cursor: 'pointer', pointerEvents: 'stroke' }}
/>
) : null}
<path
d={d}
fill="none"
stroke={strokeColor}
strokeWidth={strokeW}
filter={pathFilter}
style={{ pointerEvents: 'none' }}
/>
</g>
);
});
// Displays generated layout SVG previews with zoom and pan controls.
const LayoutSvgPreview = ({ page }) => {
const [layoutScale, setLayoutScale] = useState(null);
@@ -3952,6 +4153,7 @@ Organization : OptiHK Limited
const [activePageId, setActivePageId] = useState(null);
const reactFlowInstance = useReactFlow();
const spaceRotateNodeIdRef = useRef(null);
const rulerEdgeDragRef = useRef(null);
const [library, setLibrary] = useState(null);
const [treeKey, setTreeKey] = useState(0);
@@ -3993,7 +4195,7 @@ Organization : OptiHK Limited
const initializedRef = useRef(false);
const canvasViewportRef = useRef(null);
const edgeTypes = useMemo(() => ({ parallelRoute: ParallelRouteEdge }), []);
const edgeTypes = useMemo(() => ({ parallelRoute: ParallelRouteEdge, rulerEdge: RulerEdge }), []);
const activePage = useMemo(() => pages.find(p => p.id === activePageId) || null, [pages, activePageId]);
const compositePageNames = useMemo(() => pages.filter(page => page.type === 'composite').map(page => page.name), [pages]);
@@ -4143,7 +4345,8 @@ Organization : OptiHK Limited
draggable: false,
selectable: false,
deletable: false,
focusable: false
focusable: false,
style: { pointerEvents: 'none' }
}];
if (rulerActiveEndPoint) {
const isPreviewPoint = !rulerEndPoint;
@@ -4155,7 +4358,8 @@ Organization : OptiHK Limited
draggable: false,
selectable: false,
deletable: false,
focusable: false
focusable: false,
style: { pointerEvents: 'none' }
});
}
if (rulerMeasurement) {
@@ -4170,7 +4374,8 @@ Organization : OptiHK Limited
draggable: false,
selectable: false,
deletable: false,
focusable: false
focusable: false,
style: { pointerEvents: 'none' }
});
}
return nodes;
@@ -4182,7 +4387,7 @@ Organization : OptiHK Limited
id: '__ruler_edge__',
source: '__ruler_start__',
target: rulerPreviewMeasurement ? '__ruler_preview__' : '__ruler_end__',
type: 'straight',
type: 'rulerEdge',
selectable: false,
focusable: false,
data: { ruler: true },
@@ -4460,24 +4665,127 @@ Organization : OptiHK Limited
}));
}, []);
// Cleanup incomplete ruler groups: when a ruler endpoint is deleted individually,
// React Flow may remove only that node without cascading to the remaining group members.
// This effect detects orphaned ruler groups and removes all residual members.
useEffect(() => {
if (!activePage || !activePageId) return;
// Scan all ruler nodes and edges to find group IDs.
const groupNodes = new Map(); // groupId -> Set of node ids in this group
activePage.nodes.forEach(node => {
const m = node.id.match(/^ruler_(start|end|label)_(.+)$/);
if (!m) return;
const [, role, gid] = m;
if (!groupNodes.has(gid)) groupNodes.set(gid, new Set());
groupNodes.get(gid).add(role);
});
const groupEdges = new Map(); // groupId -> true if edge exists
activePage.edges.forEach(edge => {
const m = edge.id.match(/^ruler_edge_(.+)$/);
if (!m) return;
groupEdges.set(m[1], true);
});
// A complete group needs: start, end, label nodes + edge (= 3 roles and 1 edge)
const cleanupGroupIds = new Set();
const allRulerGroupIds = new Set([...groupNodes.keys(), ...groupEdges.keys()]);
allRulerGroupIds.forEach(gid => {
const roles = groupNodes.get(gid) || new Set();
const hasEdge = groupEdges.has(gid);
if (!(roles.has('start') && roles.has('end') && roles.has('label') && hasEdge)) {
cleanupGroupIds.add(gid);
}
});
if (cleanupGroupIds.size > 0) {
setPages(prev => prev.map(p => {
if (p.id !== activePageId) return p;
return {
...p,
nodes: p.nodes.filter(node => {
const m = node.id.match(/^ruler_(?:start|end|label)_(.+)$/);
if (!m) return true;
return !cleanupGroupIds.has(m[1]);
}),
edges: p.edges.filter(edge => {
const m = edge.id.match(/^ruler_edge_(.+)$/);
if (!m) return true;
return !cleanupGroupIds.has(m[1]);
})
};
}));
}
}, [activePage?.nodes, activePage?.edges, activePageId]);
// Apply React Flow node changes while preserving canvas-only helper nodes.
const onNodesChange = useCallback((changes) => {
if (!activePageId) return;
const relevantChanges = changes.filter(change => change.id !== '__canvas-boundary__' && change.id !== '__origin-marker__');
if (relevantChanges.length === 0) return;
const removedNodeIds = new Set(relevantChanges.filter(change => change.type === 'remove').map(change => change.id));
// Release display names for removed nodes (uses closure activePage, safe for non-critical cleanup).
if (removedNodeIds.size > 0 && activePage) {
releaseComponentDisplayNames(activePage.nodes.filter(node => removedNodeIds.has(node.id)));
}
setPages(prev => prev.map(p => {
if (p.id !== activePageId) return p;
const newNodes = applyNodeChanges(relevantChanges, p.nodes).map(node => {
let newNodes = applyNodeChanges(relevantChanges, p.nodes);
let newEdges = p.edges;
// Cascade: collect ruler group IDs from node ID patterns (reliable, doesn't depend on data object).
const rulerGroupIdsToRemove = new Set();
if (removedNodeIds.size > 0) {
p.nodes.forEach(node => {
if (!removedNodeIds.has(node.id)) return;
const m = node.id.match(/^ruler_(?:start|end|label)_(.+)$/);
if (m) rulerGroupIdsToRemove.add(m[1]);
});
}
if (rulerGroupIdsToRemove.size > 0) {
newNodes = newNodes.filter(node => {
const m = node.id.match(/^ruler_(?:start|end|label)_(.+)$/);
if (!m) return true;
return !rulerGroupIdsToRemove.has(m[1]);
});
newEdges = newEdges.filter(edge => {
const m = edge.id.match(/^ruler_edge_(.+)$/);
if (!m) return true;
return !rulerGroupIdsToRemove.has(m[1]);
});
}
newNodes = newNodes.map(node => {
if (!node.position || node.id === 'page-port') return node;
const boxSize = node.type === 'rotatableNode'
? normalizeBoxSize({ box_size: node.data?.boxSize }, DEFAULT_COMPONENT_BOX_SIZE)
: { width: 30, height: 30 };
return { ...node, position: clampPositionToCanvas(node.position, p.canvasSize || activeCanvasSize, boxSize) };
});
// Sync ruler label position and text when endpoints are dragged.
const rulerUpdates = new Map();
newNodes.forEach(node => {
const gid = node.data?.rulerGroupId;
if (!gid) return;
if (!rulerUpdates.has(gid)) rulerUpdates.set(gid, {});
const entry = rulerUpdates.get(gid);
if (node.id.startsWith('ruler_start_')) entry.start = { x: node.position.x + 6, y: node.position.y + 6 };
else if (node.id.startsWith('ruler_end_')) entry.end = { x: node.position.x + 6, y: node.position.y + 6 };
});
if (rulerUpdates.size > 0) {
newNodes = newNodes.map(node => {
const gid = node.data?.rulerGroupId;
if (!gid || !node.id.startsWith('ruler_label_')) return node;
const entry = rulerUpdates.get(gid);
if (!entry || !entry.start || !entry.end) return node;
const measurement = createRulerMeasurement(entry.start, entry.end);
if (!measurement) return node;
return {
...node,
position: { x: measurement.midpoint.x, y: measurement.midpoint.y },
data: {
...node.data,
label: measurement.label,
title: `Distance ${measurement.distance.toFixed(3)} um; dx ${measurement.dx.toFixed(3)}; dy ${measurement.dy.toFixed(3)}`
}
};
});
}
const portNode = newNodes.find(n => n.id === 'page-port');
let newPort = p.port;
if (portNode) {
@@ -4488,22 +4796,53 @@ Organization : OptiHK Limited
newPort = { x, y, a: angle, width };
}
}
return { ...p, nodes: newNodes, port: newPort };
return { ...p, nodes: newNodes, edges: newEdges, port: newPort };
}));
}, [activePageId, activePage, activeCanvasSize]);
// Apply React Flow edge changes while preserving route style and selection state.
// Also cascades ruler group deletion when a ruler edge is removed.
const onEdgesChange = useCallback((changes) => {
if (!activePageId) return;
const removedEdgeIds = new Set(changes.filter(change => change.type === 'remove').map(change => change.id));
setPages(prev => prev.map(p => {
if (p.id !== activePageId) return p;
const styledEdges = applyEdgeChanges(changes, p.edges).map(edge => {
let newEdges = applyEdgeChanges(changes, p.edges);
let newNodes = p.nodes;
// Cascade: collect ruler group IDs from edge ID patterns (reliable, doesn't depend on data object).
const rulerGroupIdsToRemove = new Set();
if (removedEdgeIds.size > 0) {
p.edges.forEach(edge => {
if (!removedEdgeIds.has(edge.id)) return;
const m = edge.id.match(/^ruler_edge_(.+)$/);
if (m) rulerGroupIdsToRemove.add(m[1]);
});
}
if (rulerGroupIdsToRemove.size > 0) {
newNodes = newNodes.filter(node => {
const m = node.id.match(/^ruler_(?:start|end|label)_(.+)$/);
if (!m) return true;
return !rulerGroupIdsToRemove.has(m[1]);
});
newEdges = newEdges.filter(edge => {
const m = edge.id.match(/^ruler_edge_(.+)$/);
if (!m) return true;
return !rulerGroupIdsToRemove.has(m[1]);
});
}
const styledEdges = newEdges.map(edge => {
// Skip route style for ruler edges.
if (edge.data?.ruler) {
return edge.selected
? { ...edge, style: { ...edge.style, strokeWidth: 4, filter: 'drop-shadow(0 0 5px rgba(45,212,191,0.45))' } }
: { ...edge, style: { stroke: '#2dd4bf', strokeWidth: 2 } };
}
const route = createRouteSettings(technologyManifest, edge.data?.route);
const view = routeStyleForSettings(route, edge.selected);
const hasRoutePoints = Array.isArray(edge.data?.points) && edge.data.points.length >= 2;
return { ...edge, type: hasRoutePoints ? 'parallelRoute' : view.type, style: view.style, data: { ...edge.data, route } };
});
return { ...p, edges: styledEdges };
return { ...p, nodes: newNodes, edges: styledEdges };
}));
}, [activePageId, technologyManifest]);
@@ -4606,6 +4945,7 @@ Organization : OptiHK Limited
// Clear the temporary Space-rotation target when the mouse is released.
const clearSpaceRotateNode = useCallback(() => {
spaceRotateNodeIdRef.current = null;
rulerEdgeDragRef.current = null;
}, []);
// Apply route setting edits and reject same-type route crossings.
@@ -6260,19 +6600,13 @@ Organization : OptiHK Limited
setCanvasTextVisible(prev => !prev);
}, []);
// Toggle the measurement ruler and clear partial measurements.
const toggleRulerMode = useCallback(() => {
setRulerMode(prev => {
const next = !prev;
if (!next) {
setRulerStartPoint(null);
setRulerEndPoint(null);
setRulerPreviewPoint(null);
} else {
setOriginPickMode(false);
}
return next;
});
// Enter ruler measurement mode (one-shot: two clicks complete one measurement, then auto-exit).
const enterRulerMode = useCallback(() => {
setRulerMode(true);
setRulerStartPoint(null);
setRulerEndPoint(null);
setRulerPreviewPoint(null);
setOriginPickMode(false);
}, []);
// Convert a pane click or pointer event into canvas coordinates.
@@ -6313,14 +6647,14 @@ Organization : OptiHK Limited
});
}, []);
// Set ruler start/end points from canvas clicks.
// Set ruler endpoints from canvas clicks. First click sets start, second click persists measurement and exits ruler mode.
const handleRulerPaneClick = useCallback((event) => {
if (!rulerMode || !reactFlowInstance || !activePage || activePage.type === 'layoutPreview') return;
event.preventDefault();
event.stopPropagation();
const nextPoint = eventToCanvasPoint(event);
if (!nextPoint) return;
if (!rulerStartPoint || rulerEndPoint) {
if (!rulerStartPoint) {
setRulerStartPoint(nextPoint);
setRulerEndPoint(null);
setRulerPreviewPoint(null);
@@ -6328,20 +6662,82 @@ Organization : OptiHK Limited
return;
}
const measurement = createRulerMeasurement(rulerStartPoint, nextPoint);
setRulerEndPoint(nextPoint);
if (!measurement) return;
// Persist the completed measurement as selectable/deletable nodes and edge.
const rulerGroupId = `ruler_${Date.now()}`;
const persistedNodes = [
{
id: `ruler_start_${rulerGroupId}`,
type: 'rulerPointNode',
position: { x: measurement.start.x - 6, y: measurement.start.y - 6 },
data: { label: `Start (${measurement.start.x.toFixed(3)}, ${measurement.start.y.toFixed(3)})`, rulerGroupId, ruler: true },
draggable: true,
selectable: true,
deletable: true,
focusable: true
},
{
id: `ruler_end_${rulerGroupId}`,
type: 'rulerPointNode',
position: { x: measurement.end.x - 6, y: measurement.end.y - 6 },
data: { label: `End (${measurement.end.x.toFixed(3)}, ${measurement.end.y.toFixed(3)})`, rulerGroupId, ruler: true },
draggable: true,
selectable: true,
deletable: true,
focusable: true
},
{
id: `ruler_label_${rulerGroupId}`,
type: 'rulerMeasurementNode',
position: { x: measurement.midpoint.x, y: measurement.midpoint.y },
data: {
label: measurement.label,
title: `Distance ${measurement.distance.toFixed(3)} um; dx ${measurement.dx.toFixed(3)}; dy ${measurement.dy.toFixed(3)}`,
rulerGroupId,
ruler: true
},
draggable: true,
selectable: false,
deletable: true,
focusable: false
}
];
const persistedEdge = {
id: `ruler_edge_${rulerGroupId}`,
source: `ruler_start_${rulerGroupId}`,
target: `ruler_end_${rulerGroupId}`,
type: 'rulerEdge',
selectable: true,
focusable: true,
data: { ruler: true, rulerGroupId, canvasSize: activePage.canvasSize || activeCanvasSize },
style: {
stroke: '#2dd4bf',
strokeWidth: 2
}
};
setPages(prev => prev.map(p => {
if (p.id !== activePageId) return p;
return {
...p,
nodes: [...p.nodes, ...persistedNodes],
edges: [...p.edges, persistedEdge]
};
}));
addLog(`Ruler distance: ${measurement.label}`);
// Exit ruler mode after persisting.
setRulerMode(false);
setRulerStartPoint(null);
setRulerEndPoint(null);
setRulerPreviewPoint(null);
if (measurement) {
addLog(`Ruler distance: ${measurement.label}`);
}
}, [rulerMode, reactFlowInstance, activePage, rulerStartPoint, rulerEndPoint, eventToCanvasPoint, addLog]);
}, [rulerMode, reactFlowInstance, activePage, activePageId, rulerStartPoint, eventToCanvasPoint, addLog]);
// Update the live ruler preview point while measuring.
const handleRulerMouseMove = useCallback((event) => {
if (!rulerMode || !reactFlowInstance || !activePage || activePage.type === 'layoutPreview') return;
if (!rulerStartPoint || rulerEndPoint) return;
if (!rulerStartPoint) return;
const nextPoint = eventToCanvasPoint(event);
if (nextPoint) setRulerPreviewPoint(nextPoint);
}, [rulerMode, reactFlowInstance, activePage, rulerStartPoint, rulerEndPoint, eventToCanvasPoint]);
}, [rulerMode, reactFlowInstance, activePage, rulerStartPoint, eventToCanvasPoint]);
const chooseCanvasOriginFromEvent = useCallback((event) => {
if (!originPickMode || !activePage || activePage.type === 'layoutPreview') return false;
@@ -6444,7 +6840,10 @@ Organization : OptiHK Limited
// Select standard React Flow edges while ignoring helper/ruler edges.
const handleReactFlowEdgeMouseDown = useCallback((event, edge) => {
if (rulerMode || !edge || edge.data?.draft || edge.data?.ruler) return;
if (rulerMode || !edge || edge.data?.draft) return;
// Ruler edges are handled entirely by the RulerEdge custom component
// (native DOM events for drag + React Flow setNodes for selection).
if (edge.data?.ruler) return;
event.preventDefault();
event.stopPropagation();
selectEdgeById(edge.id, event.shiftKey);
@@ -6853,7 +7252,7 @@ ${bundlesBlock}`;
</div>
<div
ref={canvasViewportRef}
style={{ flex: 1, position: 'relative' }}
style={{ flex: 1, position: 'relative', cursor: rulerMode ? 'none' : undefined }}
onMouseDownCapture={handleCanvasMouseDown}
onMouseMoveCapture={handleCanvasMouseMove}
onMouseLeave={handleCanvasMouseLeave}
@@ -6908,8 +7307,8 @@ ${bundlesBlock}`;
<button className="mini-btn" onClick={() => setThemeMode(themeMode === 'light' ? 'dark' : 'light')}>
{themeMode === 'light' ? 'Dark Mode' : 'Bright Mode'}
</button>
<button className="mini-btn" onClick={toggleRulerMode} aria-pressed={rulerMode ? 'true' : 'false'}>
{rulerMode ? 'Ruler On' : 'Ruler'}
<button className={`mini-btn ruler-btn ${rulerMode ? 'active' : ''}`} onClick={enterRulerMode} aria-pressed={rulerMode ? 'true' : 'false'}>
Ruler
</button>
<button
className={`mini-btn origin-select-btn ${originPickMode ? 'active' : ''}`}
@@ -6944,7 +7343,7 @@ ${bundlesBlock}`;
{activePage && activePage.type !== 'layoutPreview' && (
<div
className="coordinate-readout"
style={{ bottom: rulerMode ? 58 : 18 }}
style={{ bottom: 18 }}
title={`Origin (${canvasOrigin.x.toFixed(3)}, ${canvasOrigin.y.toFixed(3)}) um`}
>
X {displayMousePoint ? displayMousePoint.x.toFixed(3) : '--'} um
@@ -7014,6 +7413,12 @@ ${bundlesBlock}`;
<Background color="#334155" gap={10} size={1} />
</ReactFlow>
)}
{rulerMode && mouseScreenPoint && (
<div
className="ruler-cursor-dot"
style={{ left: mouseScreenPoint.x, top: mouseScreenPoint.y }}
/>
)}
</div>
<div className="app-log-terminal">
{logs.map((entry, index) => (