@umodeapporg/ui 0.24.0 → 0.24.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,21 @@
1
1
  import { jsxs, jsx } from "react/jsx-runtime";
2
+ import { useEffect } from "react";
2
3
  import { useTranslation } from "react-i18next";
3
4
  import ControlledButton from "../../Form/ControlledButton.js";
4
5
  import ControlledMenu from "../ControlledMenu.js";
5
6
  import { MaterialSymbol } from "../MaterialSymbol/index.js";
6
- import { Handle, Position } from "@xyflow/react";
7
+ import { useUpdateNodeInternals, Handle, Position } from "@xyflow/react";
7
8
  import FlowNodeShell from "./FlowNodeShell.js";
8
9
  const FLOW_INPUT_HANDLE_ID = "in";
9
10
  const portTop = (index, count) => `${(index + 1) / (count + 1) * 100}%`;
10
- const FlowBlockNode = ({ data, selected }) => {
11
+ const FlowBlockNode = ({ id, data, selected }) => {
11
12
  const { t } = useTranslation("ui");
13
+ const updateNodeInternals = useUpdateNodeInternals();
12
14
  const outputs = Array.isArray(data.outputs) ? data.outputs : [];
15
+ const handleSignature = `${data.hasInput ? FLOW_INPUT_HANDLE_ID : ""}|${outputs.join(",")}`;
16
+ useEffect(() => {
17
+ updateNodeInternals(id);
18
+ }, [id, handleSignature, updateNodeInternals]);
13
19
  const connectedPorts = Array.isArray(data.connectedPorts) ? data.connectedPorts : [];
14
20
  const addableBlocks = Array.isArray(data.addableBlocks) ? data.addableBlocks : [];
15
21
  const showPortLabels = !(outputs.length === 1 && outputs[0] === "next");
@@ -1 +1 @@
1
- {"version":3,"file":"FlowBlockNode.js","sources":["../../../../src/components/UI/Flow/FlowBlockNode.tsx"],"sourcesContent":["import { ReactNode } from 'react';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport ControlledMenu from '@/components/UI/ControlledMenu';\nimport { MaterialSymbol, type SymbolCodepoints } from '@/components/UI/MaterialSymbol';\nimport { Handle, type Node, type NodeProps, Position } from '@xyflow/react';\n\nimport FlowNodeShell from './FlowNodeShell';\nimport type { TFlowIssueSeverity, TFlowPortId, TFlowRunStepStatus } from './flowTypes';\n\nexport const FLOW_INPUT_HANDLE_ID = 'in';\n\nexport interface IFlowAddableBlock {\n type: string;\n label: string;\n icon: SymbolCodepoints;\n}\n\nexport interface IFlowBlockNodeData extends Record<string, unknown> {\n icon: SymbolCodepoints;\n title: string;\n categoryLabel: string;\n summary?: ReactNode;\n hasInput: boolean;\n outputs: Array<TFlowPortId>;\n /** Ports already wired: their edge carries the label, so the port does not repeat it. */\n connectedPorts: Array<TFlowPortId>;\n portLabels: Record<TFlowPortId, string>;\n /** What a free port can grow into; empty in a read-only canvas. */\n addableBlocks: Array<IFlowAddableBlock>;\n onAddFromPort?: (port: TFlowPortId, type: string) => void;\n disabled?: boolean;\n issueSeverity?: TFlowIssueSeverity;\n issueCount: number;\n runStatus?: TFlowRunStepStatus;\n}\n\nexport type TFlowBlockNode = Node<IFlowBlockNodeData, 'flowBlock'>;\n\nconst portTop = (index: number, count: number): string => `${((index + 1) / (count + 1)) * 100}%`;\n\n/**\n * Input on the left edge, output ports spread along the right edge; a lone `next` port needs no\n * label. A free port shows a \"+\" that adds the next block already wired to it.\n */\nconst FlowBlockNode: React.FC<NodeProps<TFlowBlockNode>> = ({ data, selected }) => {\n const { t } = useTranslation('ui');\n const outputs = Array.isArray(data.outputs) ? data.outputs : [];\n const connectedPorts = Array.isArray(data.connectedPorts) ? data.connectedPorts : [];\n const addableBlocks = Array.isArray(data.addableBlocks) ? data.addableBlocks : [];\n const showPortLabels = !(outputs.length === 1 && outputs[0] === 'next');\n const canAdd = Boolean(data.onAddFromPort) && addableBlocks.length > 0;\n\n return (\n <FlowNodeShell\n icon={data.icon}\n title={data.title}\n categoryLabel={data.categoryLabel}\n summary={data.summary}\n selected={selected}\n disabled={data.disabled}\n issueSeverity={data.issueSeverity}\n issueCount={data.issueCount}\n runStatus={data.runStatus}\n className={showPortLabels ? 'pr-12' : undefined}\n >\n {data.hasInput && (\n <Handle id={FLOW_INPUT_HANDLE_ID} type=\"target\" position={Position.Left} className=\"umode-flow-handle\" />\n )}\n {outputs.map((port, index) => (\n <Handle\n key={port}\n id={port}\n type=\"source\"\n position={Position.Right}\n className=\"umode-flow-handle\"\n data-port={port}\n style={{ top: portTop(index, outputs.length) }}\n >\n {showPortLabels && !connectedPorts.includes(port) && (\n <span className=\"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 whitespace-nowrap text-xxs font-semibold text-foreground-subtle\">\n {data.portLabels[port]}\n </span>\n )}\n </Handle>\n ))}\n {canAdd &&\n outputs.map((port, index) =>\n connectedPorts.includes(port) ? null : (\n <div\n key={`add|${port}`}\n className=\"nodrag nopan absolute -right-10 -translate-y-1/2\"\n style={{ top: portTop(index, outputs.length) }}\n >\n <ControlledMenu\n placement=\"right-start\"\n triggerTooltip={t('flow.node.addBlock')}\n items={addableBlocks.map((block) => ({\n key: block.type,\n label: block.label,\n icon: block.icon,\n onClick: () => data.onAddFromPort?.(port, block.type),\n }))}\n trigger={\n <ControlledButton\n defaultHtmlButton\n className=\"interactive flex size-6 items-center justify-center rounded-full border border-border-emphasis bg-surface text-foreground-muted shadow-sm hover:border-brand-border hover:bg-brand-soft hover:text-brand-emphasis focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <MaterialSymbol icon=\"add\" size={16} aria-hidden />\n </ControlledButton>\n }\n />\n </div>\n ),\n )}\n </FlowNodeShell>\n );\n};\n\nexport default FlowBlockNode;\n"],"names":[],"mappings":";;;;;;;AAWO,MAAM,uBAAuB;AA6BpC,MAAM,UAAU,CAAC,OAAe,UAA0B,IAAK,QAAQ,MAAM,QAAQ,KAAM,GAAG;AAM9F,MAAM,gBAAqD,CAAC,EAAE,MAAM,eAAe;AACjF,QAAM,EAAE,EAAA,IAAM,eAAe,IAAI;AACjC,QAAM,UAAU,MAAM,QAAQ,KAAK,OAAO,IAAI,KAAK,UAAU,CAAA;AAC7D,QAA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,cAE3C,UAAA;AAAA,gBAAC;AAAA,gBAAA;AAAA,kBACC,WAAU;AAAA,kBACV,gBAAgB,EAAE,oBAAoB;AAAA,kBACtC,OAAO,cAAc,IAAI,CAAC,WAAW;AAAA,oBACnC,KAAK,MAAM;AAAA,oBACX,OAAO,MAAM;AAAA,oBACb,MAAM,MAAM;AAAA,oBACZ,SAAS,MAAM,KAAK,gBAAgB,MAAM,MAAM,IAAI;AAAA,kBAAA,EACpD;AAAA,kBACF,SACE;AAAA,oBAAC;AAAA,oBAAA;AAAA,sBACC,mBAAiB;AAAA,sBACjB,WAAU;AAAA,sBAEV,8BAAC,gBAAA,EAAe,MAAK,OAAM,MAAM,IAAI,eAAW,KAAA,CAAC;AAAA,oBAAA;AAAA,kBAAA;AAAA,gBACnD;AAAA,cAAA;AAAA,YAEJ;AAAA,YArBK,OAAO,IAAI;AAAA,UAAA;AAAA,QAsBlB;AAAA,MAEJ;AAAA,IAAA;AAAA,EAAA;AAGR;"}
1
+ {"version":3,"file":"FlowBlockNode.js","sources":["../../../../src/components/UI/Flow/FlowBlockNode.tsx"],"sourcesContent":["import { ReactNode, useEffect } from 'react';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport ControlledMenu from '@/components/UI/ControlledMenu';\nimport { MaterialSymbol, type SymbolCodepoints } from '@/components/UI/MaterialSymbol';\nimport { Handle, type Node, type NodeProps, Position, useUpdateNodeInternals } from '@xyflow/react';\n\nimport FlowNodeShell from './FlowNodeShell';\nimport type { TFlowIssueSeverity, TFlowPortId, TFlowRunStepStatus } from './flowTypes';\n\nexport const FLOW_INPUT_HANDLE_ID = 'in';\n\nexport interface IFlowAddableBlock {\n type: string;\n label: string;\n icon: SymbolCodepoints;\n}\n\nexport interface IFlowBlockNodeData extends Record<string, unknown> {\n icon: SymbolCodepoints;\n title: string;\n categoryLabel: string;\n summary?: ReactNode;\n hasInput: boolean;\n outputs: Array<TFlowPortId>;\n /** Ports already wired: their edge carries the label, so the port does not repeat it. */\n connectedPorts: Array<TFlowPortId>;\n portLabels: Record<TFlowPortId, string>;\n /** What a free port can grow into; empty in a read-only canvas. */\n addableBlocks: Array<IFlowAddableBlock>;\n onAddFromPort?: (port: TFlowPortId, type: string) => void;\n disabled?: boolean;\n issueSeverity?: TFlowIssueSeverity;\n issueCount: number;\n runStatus?: TFlowRunStepStatus;\n}\n\nexport type TFlowBlockNode = Node<IFlowBlockNodeData, 'flowBlock'>;\n\nconst portTop = (index: number, count: number): string => `${((index + 1) / (count + 1)) * 100}%`;\n\n/**\n * Input on the left edge, output ports spread along the right edge; a lone `next` port needs no\n * label. A free port shows a \"+\" that adds the next block already wired to it.\n */\nconst FlowBlockNode: React.FC<NodeProps<TFlowBlockNode>> = ({ id, data, selected }) => {\n const { t } = useTranslation('ui');\n const updateNodeInternals = useUpdateNodeInternals();\n const outputs = Array.isArray(data.outputs) ? data.outputs : [];\n const handleSignature = `${data.hasInput ? FLOW_INPUT_HANDLE_ID : ''}|${outputs.join(',')}`;\n\n // React Flow measures handle positions only when the node is resized. An edge whose handle was\n // not in that measurement is never drawn, so remeasure after mount and whenever the ports change.\n useEffect(() => {\n updateNodeInternals(id);\n }, [id, handleSignature, updateNodeInternals]);\n const connectedPorts = Array.isArray(data.connectedPorts) ? data.connectedPorts : [];\n const addableBlocks = Array.isArray(data.addableBlocks) ? data.addableBlocks : [];\n const showPortLabels = !(outputs.length === 1 && outputs[0] === 'next');\n const canAdd = Boolean(data.onAddFromPort) && addableBlocks.length > 0;\n\n return (\n <FlowNodeShell\n icon={data.icon}\n title={data.title}\n categoryLabel={data.categoryLabel}\n summary={data.summary}\n selected={selected}\n disabled={data.disabled}\n issueSeverity={data.issueSeverity}\n issueCount={data.issueCount}\n runStatus={data.runStatus}\n className={showPortLabels ? 'pr-12' : undefined}\n >\n {data.hasInput && (\n <Handle id={FLOW_INPUT_HANDLE_ID} type=\"target\" position={Position.Left} className=\"umode-flow-handle\" />\n )}\n {outputs.map((port, index) => (\n <Handle\n key={port}\n id={port}\n type=\"source\"\n position={Position.Right}\n className=\"umode-flow-handle\"\n data-port={port}\n style={{ top: portTop(index, outputs.length) }}\n >\n {showPortLabels && !connectedPorts.includes(port) && (\n <span className=\"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 whitespace-nowrap text-xxs font-semibold text-foreground-subtle\">\n {data.portLabels[port]}\n </span>\n )}\n </Handle>\n ))}\n {canAdd &&\n outputs.map((port, index) =>\n connectedPorts.includes(port) ? null : (\n <div\n key={`add|${port}`}\n className=\"nodrag nopan absolute -right-10 -translate-y-1/2\"\n style={{ top: portTop(index, outputs.length) }}\n >\n <ControlledMenu\n placement=\"right-start\"\n triggerTooltip={t('flow.node.addBlock')}\n items={addableBlocks.map((block) => ({\n key: block.type,\n label: block.label,\n icon: block.icon,\n onClick: () => data.onAddFromPort?.(port, block.type),\n }))}\n trigger={\n <ControlledButton\n defaultHtmlButton\n className=\"interactive flex size-6 items-center justify-center rounded-full border border-border-emphasis bg-surface text-foreground-muted shadow-sm hover:border-brand-border hover:bg-brand-soft hover:text-brand-emphasis focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <MaterialSymbol icon=\"add\" size={16} aria-hidden />\n </ControlledButton>\n }\n />\n </div>\n ),\n )}\n </FlowNodeShell>\n );\n};\n\nexport default FlowBlockNode;\n"],"names":[],"mappings":";;;;;;;;AAWO,MAAM,uBAAuB;AA6BpC,MAAM,UAAU,CAAC,OAAe,UAA0B,IAAK,QAAQ,MAAM,QAAQ,KAAM,GAAG;AAM9F,MAAM,gBAAqD,CAAC,EAAE,IAAI,MAAM,eAAe;AACrF,QAAM,EAAE,EAAA,IAAM,eAAe,IAAI;AACjC,QAAM,sBAAsB,uBAAA;AAC5B,QAAM,UAAU,MAAM,QAAQ,KAAK,OAAO,IAAI,KAAK,UAAU,CAAA;AAC7D,QAAM,kBAAkB,GAAG,KAAK,WAAW,uBAAuB,EAAE,IAAI,QAAQ,KAAK,GAAG,CA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AA,YAAC;AAAA,YAAA;AAAA,cAEC,WAAU;AAAA,cACV,OAAO,EAAE,KAAK,QAAQ,OAAO,QAAQ,MAAM,EAAA;AAAA,cAE3C,UAAA;AAAA,gBAAC;AAAA,gBAAA;AAAA,kBACC,WAAU;AAAA,kBACV,gBAAgB,EAAE,oBAAoB;AAAA,kBACtC,OAAO,cAAc,IAAI,CAAC,WAAW;AAAA,oBACnC,KAAK,MAAM;AAAA,oBACX,OAAO,MAAM;AAAA,oBACb,MAAM,MAAM;AAAA,oBACZ,SAAS,MAAM,KAAK,gBAAgB,MAAM,MAAM,IAAI;AAAA,kBAAA,EACpD;AAAA,kBACF,SACE;AAAA,oBAAC;AAAA,oBAAA;AAAA,sBACC,mBAAiB;AAAA,sBACjB,WAAU;AAAA,sBAEV,8BAAC,gBAAA,EAAe,MAAK,OAAM,MAAM,IAAI,eAAW,KAAA,CAAC;AAAA,oBAAA;AAAA,kBAAA;AAAA,gBACnD;AAAA,cAAA;AAAA,YAEJ;AAAA,YArBK,OAAO,IAAI;AAAA,UAAA;AAAA,QAsBlB;AAAA,MAEJ;AAAA,IAAA;AAAA,EAAA;AAGR;"}
@@ -1,13 +1,14 @@
1
1
  import { jsx, jsxs } from "react/jsx-runtime";
2
- import { useMemo, useState, useCallback } from "react";
2
+ import { useMemo, useState, useRef, useEffect, useCallback } from "react";
3
3
  import { useTranslation } from "react-i18next";
4
4
  import { twMerge } from "tailwind-merge";
5
- import { MarkerType, ReactFlow, Background, BackgroundVariant, MiniMap } from "@xyflow/react";
5
+ import { useReactFlow, useStore, MarkerType, ReactFlow, Background, BackgroundVariant, MiniMap } from "@xyflow/react";
6
6
  import FlowBlockNode, { FLOW_INPUT_HANDLE_ID } from "./FlowBlockNode.js";
7
7
  import { flowOutputsOf } from "./flowBlockRegistry.js";
8
8
  import FlowConnectionEdge from "./FlowConnectionEdge.js";
9
9
  import { useFlowBlockRegistry, useFlowEditorStore, useFlowEditor } from "./FlowEditorProvider.js";
10
10
  import { canConnect, layoutFlowByLevels } from "./flowGraph.js";
11
+ import { boundsOfRects, viewportToReveal } from "./flowViewport.js";
11
12
  import FlowZoomControls from "./FlowZoomControls.js";
12
13
  import { useFlowLabels } from "./useFlowLabels.js";
13
14
  import "@xyflow/react/dist/base.css";
@@ -19,6 +20,7 @@ const MINIMAP_SIZE = { width: 160, height: 104 };
19
20
  const MINIMAP_MIN_NODES = 5;
20
21
  const SNAP_GRID = [16, 16];
21
22
  const PORTS = ["next", "true", "false", "error"];
23
+ const REVEAL_DURATION_MS = 200;
22
24
  const isPortId = (value) => PORTS.includes(value);
23
25
  const worstSeverity = (issues) => {
24
26
  if (issues.some((issue) => issue.severity === "error")) return "error";
@@ -46,6 +48,47 @@ const FlowCanvas = ({
46
48
  const canRedo = useFlowEditor((state) => state.future.length > 0);
47
49
  const safeIssues = useMemo(() => Array.isArray(issues) ? issues : [], [issues]);
48
50
  const [measuredSizes, setMeasuredSizes] = useState({});
51
+ const { getViewport, setViewport } = useReactFlow();
52
+ const canvasWidth = useStore((state) => state.width);
53
+ const canvasHeight = useStore((state) => state.height);
54
+ const [revealNodeIds, setRevealNodeIds] = useState([]);
55
+ const knownNodeIdsRef = useRef(null);
56
+ const pendingViewportRef = useRef(null);
57
+ useEffect(() => {
58
+ const currentIds = new Set(graph.nodes.map((node) => node.nodeId));
59
+ const knownIds = knownNodeIdsRef.current;
60
+ knownNodeIdsRef.current = currentIds;
61
+ const addedAndSelected = knownIds ? selectedNodeIds.filter((id) => currentIds.has(id) && !knownIds.has(id)) : [];
62
+ if (addedAndSelected.length > 0) {
63
+ setRevealNodeIds(addedAndSelected);
64
+ return;
65
+ }
66
+ setRevealNodeIds(
67
+ (current) => current.length > 0 && !current.every((id) => selectedNodeIds.includes(id)) ? [] : current
68
+ );
69
+ }, [graph.nodes, selectedNodeIds]);
70
+ useEffect(() => {
71
+ if (revealNodeIds.length === 0) return;
72
+ const rects = [];
73
+ for (const nodeId of revealNodeIds) {
74
+ const node = graph.nodes.find((candidate) => candidate.nodeId === nodeId);
75
+ const size = measuredSizes[nodeId];
76
+ if (!node || !size) return;
77
+ rects.push({ ...node.position, ...size });
78
+ }
79
+ const bounds = boundsOfRects(rects);
80
+ if (!bounds) return;
81
+ const pending = pendingViewportRef.current;
82
+ const baseViewport = pending && pending.settlesAt > Date.now() ? pending.viewport : getViewport();
83
+ const target = viewportToReveal(baseViewport, bounds, { width: canvasWidth, height: canvasHeight });
84
+ if (!target) return;
85
+ pendingViewportRef.current = { viewport: target, settlesAt: Date.now() + REVEAL_DURATION_MS };
86
+ void setViewport(target, { duration: REVEAL_DURATION_MS });
87
+ }, [revealNodeIds, graph.nodes, measuredSizes, canvasWidth, canvasHeight, getViewport, setViewport]);
88
+ const stopRevealing = useCallback(() => {
89
+ pendingViewportRef.current = null;
90
+ setRevealNodeIds((current) => current.length > 0 ? [] : current);
91
+ }, []);
49
92
  const addableBlocks = useMemo(() => {
50
93
  if (readOnly) return [];
51
94
  return registry.list.filter((definition) => definition.category !== "trigger").filter(
@@ -214,7 +257,13 @@ const FlowCanvas = ({
214
257
  onEdgesChange: handleEdgesChange,
215
258
  onConnect: handleConnect,
216
259
  isValidConnection,
217
- onNodeDragStart: () => store.getState().recordHistory(),
260
+ onNodeDragStart: () => {
261
+ stopRevealing();
262
+ store.getState().recordHistory();
263
+ },
264
+ onMoveStart: (event) => {
265
+ if (event) stopRevealing();
266
+ },
218
267
  onPaneClick: () => store.getState().setSelection({ nodeIds: [], edgeIds: [] }),
219
268
  deleteKeyCode: null,
220
269
  nodesDraggable: !readOnly,
@@ -1 +1 @@
1
- {"version":3,"file":"FlowCanvas.js","sources":["../../../../src/components/UI/Flow/FlowCanvas.tsx"],"sourcesContent":["import { KeyboardEvent, useCallback, useMemo, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { twMerge } from 'tailwind-merge';\n\nimport {\n Background,\n BackgroundVariant,\n type Connection,\n type EdgeChange,\n MarkerType,\n MiniMap,\n type NodeChange,\n type PanelPosition,\n type ProOptions,\n ReactFlow,\n} from '@xyflow/react';\n\nimport FlowBlockNode, { FLOW_INPUT_HANDLE_ID, type IFlowAddableBlock, type TFlowBlockNode } from './FlowBlockNode';\nimport { flowOutputsOf } from './flowBlockRegistry';\nimport FlowConnectionEdge, { type TFlowConnectionEdge } from './FlowConnectionEdge';\nimport { useFlowBlockRegistry, useFlowEditor, useFlowEditorStore } from './FlowEditorProvider';\nimport { canConnect, layoutFlowByLevels } from './flowGraph';\nimport type { IFlowIssue, IFlowPosition, IFlowRunOverlay, TFlowIssueSeverity, TFlowPortId } from './flowTypes';\nimport FlowZoomControls from './FlowZoomControls';\nimport { useFlowLabels } from './useFlowLabels';\n\nimport '@xyflow/react/dist/base.css';\nimport '../../../styles/flow.css';\n\nconst PRO_OPTIONS: ProOptions = { hideAttribution: true };\nconst NODE_TYPES = { flowBlock: FlowBlockNode };\nconst EDGE_TYPES = { flowConnection: FlowConnectionEdge };\nconst MINIMAP_SIZE = { width: 160, height: 104 };\n/** A small flow fits on screen whole, where a minimap only covers blocks. */\nconst MINIMAP_MIN_NODES = 5;\nconst SNAP_GRID: [number, number] = [16, 16];\nconst PORTS: Array<TFlowPortId> = ['next', 'true', 'false', 'error'];\n\nexport interface IFlowCanvasProps {\n issues?: Array<IFlowIssue>;\n runOverlay?: IFlowRunOverlay | null;\n readOnly?: boolean;\n /** Accessible name of the canvas region, from `t()`. Defaults to the library label. */\n ariaLabel?: string;\n className?: string;\n /** Where the zoom and history controls sit. */\n controlsPosition?: PanelPosition;\n /** The dot grid behind the blocks. Blocks still snap to the grid when it is hidden. */\n background?: 'dots' | 'none';\n}\n\nconst isPortId = (value: string | null | undefined): value is TFlowPortId => PORTS.includes(value as TFlowPortId);\n\nconst worstSeverity = (issues: Array<IFlowIssue>): TFlowIssueSeverity | undefined => {\n if (issues.some((issue) => issue.severity === 'error')) return 'error';\n if (issues.some((issue) => issue.severity === 'warning')) return 'warning';\n return undefined;\n};\n\nconst isTypingTarget = (target: EventTarget | null): boolean =>\n target instanceof HTMLElement &&\n (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName));\n\n/**\n * The editing surface. Renders the graph held by `FlowEditorProvider` and turns every\n * gesture (drag, connect, select, delete, shortcuts) into a store action, so undo\n * and the dirty flag see all of them.\n */\nconst FlowCanvas: React.FC<IFlowCanvasProps> = ({\n issues = [],\n runOverlay,\n readOnly = false,\n ariaLabel,\n className,\n controlsPosition,\n background = 'dots',\n}) => {\n const { t } = useTranslation('ui');\n const labels = useFlowLabels();\n const registry = useFlowBlockRegistry();\n const store = useFlowEditorStore();\n\n const graph = useFlowEditor((state) => state.graph);\n const selectedNodeIds = useFlowEditor((state) => state.selectedNodeIds);\n const selectedEdgeIds = useFlowEditor((state) => state.selectedEdgeIds);\n const canUndo = useFlowEditor((state) => state.past.length > 0);\n const canRedo = useFlowEditor((state) => state.future.length > 0);\n\n const safeIssues = useMemo(() => (Array.isArray(issues) ? issues : []), [issues]);\n // Measured sizes are view state, not part of the flow: kept here so the minimap can draw the blocks.\n const [measuredSizes, setMeasuredSizes] = useState<Record<string, { width: number; height: number }>>({});\n\n const addableBlocks = useMemo<Array<IFlowAddableBlock>>(() => {\n if (readOnly) return [];\n return registry.list\n .filter((definition) => definition.category !== 'trigger')\n .filter(\n (definition) =>\n definition.maxInstances === undefined ||\n graph.nodes.filter((node) => node.type === definition.type).length < definition.maxInstances,\n )\n .map((definition) => ({ type: definition.type, label: definition.label, icon: definition.icon }));\n }, [registry, graph.nodes, readOnly]);\n\n // A block in the middle of an edge needs an output to carry the flow on to the old target.\n const insertableBlocks = useMemo<Array<IFlowAddableBlock>>(\n () =>\n addableBlocks.filter((block) => {\n const definition = registry.get(block.type);\n return definition ? flowOutputsOf(definition, definition.createDefaultConfig()).length > 0 : false;\n }),\n [addableBlocks, registry],\n );\n\n const nodes = useMemo<Array<TFlowBlockNode>>(\n () =>\n graph.nodes.map((node) => {\n const definition = registry.get(node.type);\n const nodeIssues = safeIssues.filter((issue) => issue.nodeId === node.nodeId);\n return {\n id: node.nodeId,\n type: 'flowBlock',\n position: node.position,\n measured: measuredSizes[node.nodeId],\n selected: selectedNodeIds.includes(node.nodeId),\n draggable: !readOnly,\n connectable: !readOnly,\n data: {\n icon: definition?.resolveIcon?.(node.config) ?? definition?.icon ?? 'help',\n title: node.label ?? definition?.resolveLabel?.(node.config) ?? definition?.label ?? node.type,\n categoryLabel: definition ? labels.categories[definition.category] : '',\n summary: definition\n ? definition.renderSummary(node.config)\n : labels.issueMessage({ code: 'unknownBlock', severity: 'error' }),\n hasInput: definition ? definition.category !== 'trigger' : true,\n outputs: flowOutputsOf(definition, node.config),\n connectedPorts: graph.edges.filter((edge) => edge.source === node.nodeId).map((edge) => edge.sourcePort),\n portLabels: labels.ports,\n addableBlocks,\n onAddFromPort: readOnly\n ? undefined\n : (port, type) => store.getState().addNodeFromPort(type, node.nodeId, port),\n disabled: node.disabled,\n issueSeverity: worstSeverity(nodeIssues),\n issueCount: nodeIssues.length,\n runStatus: runOverlay?.steps?.[node.nodeId],\n },\n };\n }),\n [\n graph.nodes,\n graph.edges,\n registry,\n safeIssues,\n selectedNodeIds,\n readOnly,\n labels,\n runOverlay,\n measuredSizes,\n addableBlocks,\n store,\n ],\n );\n\n const edges = useMemo<Array<TFlowConnectionEdge>>(() => {\n const traversed = new Set(runOverlay?.traversedEdgeIds ?? []);\n return graph.edges.map((edge) => ({\n id: edge.edgeId,\n type: 'flowConnection',\n source: edge.source,\n sourceHandle: edge.sourcePort,\n target: edge.target,\n targetHandle: FLOW_INPUT_HANDLE_ID,\n selected: selectedEdgeIds.includes(edge.edgeId),\n markerEnd: { type: MarkerType.ArrowClosed, width: 16, height: 16 },\n data: {\n label: edge.sourcePort === 'next' ? undefined : labels.ports[edge.sourcePort],\n traversed: traversed.has(edge.edgeId),\n issueSeverity: worstSeverity(safeIssues.filter((issue) => issue.edgeId === edge.edgeId)),\n insertableBlocks,\n onInsert: readOnly ? undefined : (type: string) => store.getState().insertNodeOnEdge(type, edge.edgeId),\n },\n }));\n }, [graph.edges, selectedEdgeIds, runOverlay, labels, safeIssues, insertableBlocks, readOnly, store]);\n\n const handleNodesChange = useCallback(\n (changes: Array<NodeChange<TFlowBlockNode>>) => {\n const positions: Record<string, IFlowPosition> = {};\n const sizes: Record<string, { width: number; height: number }> = {};\n let selection: Array<string> | null = null;\n for (const change of changes) {\n if (change.type === 'dimensions' && change.dimensions) sizes[change.id] = change.dimensions;\n if (change.type === 'position' && change.position && !readOnly) positions[change.id] = change.position;\n if (change.type === 'select') {\n const current: Array<string> = selection ?? store.getState().selectedNodeIds;\n selection = change.selected\n ? [...new Set([...current, change.id])]\n : current.filter((id) => id !== change.id);\n }\n }\n if (Object.keys(sizes).length > 0) setMeasuredSizes((current) => ({ ...current, ...sizes }));\n if (Object.keys(positions).length > 0) store.getState().moveNodes(positions);\n if (selection) store.getState().setSelection({ nodeIds: selection });\n },\n [store, readOnly],\n );\n\n const handleEdgesChange = useCallback(\n (changes: Array<EdgeChange<TFlowConnectionEdge>>) => {\n let selection: Array<string> | null = null;\n for (const change of changes) {\n if (change.type !== 'select') continue;\n const current: Array<string> = selection ?? store.getState().selectedEdgeIds;\n selection = change.selected ? [...new Set([...current, change.id])] : current.filter((id) => id !== change.id);\n }\n if (selection) store.getState().setSelection({ edgeIds: selection });\n },\n [store],\n );\n\n const handleConnect = useCallback(\n (connection: Connection) => {\n if (readOnly || !isPortId(connection.sourceHandle)) return;\n store.getState().connect(connection.source, connection.sourceHandle, connection.target);\n },\n [store, readOnly],\n );\n\n const isValidConnection = useCallback(\n (connection: Connection | TFlowConnectionEdge) =>\n isPortId(connection.sourceHandle) &&\n canConnect(store.getState().graph, registry, {\n source: connection.source,\n sourcePort: connection.sourceHandle,\n target: connection.target,\n }),\n [store, registry],\n );\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n if (readOnly || isTypingTarget(event.target)) return;\n const state = store.getState();\n const withModifier = event.metaKey || event.ctrlKey;\n const key = event.key.toLowerCase();\n\n if (event.key === 'Delete' || event.key === 'Backspace') state.removeSelected();\n else if (withModifier && key === 'z' && event.shiftKey) state.redo();\n else if (withModifier && key === 'z') state.undo();\n else if (withModifier && key === 'y') state.redo();\n else if (withModifier && key === 'c') state.copySelected();\n else if (withModifier && key === 'v') state.paste();\n else if (withModifier && key === 'd') state.duplicateSelected();\n else return;\n event.preventDefault();\n },\n [store, readOnly],\n );\n\n const handleLayout = useCallback(() => {\n const state = store.getState();\n state.recordHistory();\n state.moveNodes(layoutFlowByLevels(state.graph, registry));\n }, [store, registry]);\n\n return (\n <div\n role=\"region\"\n aria-label={ariaLabel ?? t('flow.canvas')}\n tabIndex={0}\n onKeyDown={handleKeyDown}\n className={twMerge(\n 'umode-flow relative h-full min-h-[24rem] w-full rounded-xl bg-canvas focus:outline-none',\n className,\n )}\n >\n <ReactFlow<TFlowBlockNode, TFlowConnectionEdge>\n nodes={nodes}\n edges={edges}\n nodeTypes={NODE_TYPES}\n edgeTypes={EDGE_TYPES}\n onNodesChange={handleNodesChange}\n onEdgesChange={handleEdgesChange}\n onConnect={handleConnect}\n isValidConnection={isValidConnection}\n onNodeDragStart={() => store.getState().recordHistory()}\n onPaneClick={() => store.getState().setSelection({ nodeIds: [], edgeIds: [] })}\n deleteKeyCode={null}\n nodesDraggable={!readOnly}\n nodesConnectable={!readOnly}\n snapToGrid\n snapGrid={SNAP_GRID}\n minZoom={0.25}\n maxZoom={2}\n fitView\n fitViewOptions={{ padding: 0.2, maxZoom: 1 }}\n proOptions={PRO_OPTIONS}\n >\n {background === 'dots' && <Background variant={BackgroundVariant.Dots} gap={16} size={1} />}\n {nodes.length >= MINIMAP_MIN_NODES && (\n <MiniMap pannable zoomable position=\"bottom-right\" style={MINIMAP_SIZE} />\n )}\n <FlowZoomControls\n onUndo={readOnly ? undefined : () => store.getState().undo()}\n onRedo={readOnly ? undefined : () => store.getState().redo()}\n canUndo={canUndo}\n canRedo={canRedo}\n onLayout={readOnly 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,UAAA;AAAA,YAAA,eAAe,8BAAW,YAAA,EAAW,SAAS,kBAAkB,MAAM,KAAK,IAAI,MAAM,EAAA,CAAG;AAAA,YACxF,MAAM,UAAU,qBACf,oBAAC,SAAA,EAAQ,UAAQ,MAAC,UAAQ,MAAC,UAAS,gBAAe,OAAO,aAAA,CAAc;AAAA,YAE1E;AAAA,cAAC;AAAA,cAAA;AAAA,gBACC,QAAQ,WAAW,SAAY,MAAM,MAAM,SAAA,EAAW,KAAA;AAAA,gBACtD,QAAQ,WAAW,SAAY,MAAM,MAAM,SAAA,EAAW,KAAA;AAAA,gBACtD;AAAA,gBACA;AAAA,gBACA,UAAU,WAAW,SAAY;AAAA,gBACjC,UAAU;AAAA,cAAA;AAAA,YAAA;AAAA,UACZ;AAAA,QAAA;AAAA,MAAA;AAAA,IACF;AAAA,EAAA;AAGN;"}
1
+ {"version":3,"file":"FlowCanvas.js","sources":["../../../../src/components/UI/Flow/FlowCanvas.tsx"],"sourcesContent":["import { KeyboardEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { twMerge } from 'tailwind-merge';\n\nimport {\n Background,\n BackgroundVariant,\n type Connection,\n type EdgeChange,\n MarkerType,\n MiniMap,\n type NodeChange,\n type PanelPosition,\n type ProOptions,\n ReactFlow,\n useReactFlow,\n useStore as useReactFlowStore,\n} from '@xyflow/react';\n\nimport FlowBlockNode, { FLOW_INPUT_HANDLE_ID, type IFlowAddableBlock, type TFlowBlockNode } from './FlowBlockNode';\nimport { flowOutputsOf } from './flowBlockRegistry';\nimport FlowConnectionEdge, { type TFlowConnectionEdge } from './FlowConnectionEdge';\nimport { useFlowBlockRegistry, useFlowEditor, useFlowEditorStore } from './FlowEditorProvider';\nimport { canConnect, layoutFlowByLevels } from './flowGraph';\nimport type { IFlowIssue, IFlowPosition, IFlowRunOverlay, TFlowIssueSeverity, TFlowPortId } from './flowTypes';\nimport { boundsOfRects, type IFlowRect, type IFlowViewport, viewportToReveal } from './flowViewport';\nimport FlowZoomControls from './FlowZoomControls';\nimport { useFlowLabels } from './useFlowLabels';\n\nimport '@xyflow/react/dist/base.css';\nimport '../../../styles/flow.css';\n\nconst PRO_OPTIONS: ProOptions = { hideAttribution: true };\nconst NODE_TYPES = { flowBlock: FlowBlockNode };\nconst EDGE_TYPES = { flowConnection: FlowConnectionEdge };\nconst MINIMAP_SIZE = { width: 160, height: 104 };\n/** A small flow fits on screen whole, where a minimap only covers blocks. */\nconst MINIMAP_MIN_NODES = 5;\nconst SNAP_GRID: [number, number] = [16, 16];\nconst PORTS: Array<TFlowPortId> = ['next', 'true', 'false', 'error'];\nconst REVEAL_DURATION_MS = 200;\n\nexport interface IFlowCanvasProps {\n issues?: Array<IFlowIssue>;\n runOverlay?: IFlowRunOverlay | null;\n readOnly?: boolean;\n /** Accessible name of the canvas region, from `t()`. Defaults to the library label. */\n ariaLabel?: string;\n className?: string;\n /** Where the zoom and history controls sit. */\n controlsPosition?: PanelPosition;\n /** The dot grid behind the blocks. Blocks still snap to the grid when it is hidden. */\n background?: 'dots' | 'none';\n}\n\nconst isPortId = (value: string | null | undefined): value is TFlowPortId => PORTS.includes(value as TFlowPortId);\n\nconst worstSeverity = (issues: Array<IFlowIssue>): TFlowIssueSeverity | undefined => {\n if (issues.some((issue) => issue.severity === 'error')) return 'error';\n if (issues.some((issue) => issue.severity === 'warning')) return 'warning';\n return undefined;\n};\n\nconst isTypingTarget = (target: EventTarget | null): boolean =>\n target instanceof HTMLElement &&\n (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName));\n\n/**\n * The editing surface. Renders the graph held by `FlowEditorProvider` and turns every\n * gesture (drag, connect, select, delete, shortcuts) into a store action, so undo\n * and the dirty flag see all of them.\n */\nconst FlowCanvas: React.FC<IFlowCanvasProps> = ({\n issues = [],\n runOverlay,\n readOnly = false,\n ariaLabel,\n className,\n controlsPosition,\n background = 'dots',\n}) => {\n const { t } = useTranslation('ui');\n const labels = useFlowLabels();\n const registry = useFlowBlockRegistry();\n const store = useFlowEditorStore();\n\n const graph = useFlowEditor((state) => state.graph);\n const selectedNodeIds = useFlowEditor((state) => state.selectedNodeIds);\n const selectedEdgeIds = useFlowEditor((state) => state.selectedEdgeIds);\n const canUndo = useFlowEditor((state) => state.past.length > 0);\n const canRedo = useFlowEditor((state) => state.future.length > 0);\n\n const safeIssues = useMemo(() => (Array.isArray(issues) ? issues : []), [issues]);\n // Measured sizes are view state, not part of the flow: kept here so the minimap can draw the blocks.\n const [measuredSizes, setMeasuredSizes] = useState<Record<string, { width: number; height: number }>>({});\n\n const { getViewport, setViewport } = useReactFlow<TFlowBlockNode, TFlowConnectionEdge>();\n const canvasWidth = useReactFlowStore((state) => state.width);\n const canvasHeight = useReactFlowStore((state) => state.height);\n // Blocks just added and selected: kept in view until the user moves the view or the selection, so\n // the host panel that opens on selection (and narrows the canvas) cannot hide them.\n const [revealNodeIds, setRevealNodeIds] = useState<Array<string>>([]);\n const knownNodeIdsRef = useRef<Set<string> | null>(null);\n const pendingViewportRef = useRef<{ viewport: IFlowViewport; settlesAt: number } | null>(null);\n\n useEffect(() => {\n const currentIds = new Set(graph.nodes.map((node) => node.nodeId));\n const knownIds = knownNodeIdsRef.current;\n knownNodeIdsRef.current = currentIds;\n const addedAndSelected = knownIds ? selectedNodeIds.filter((id) => currentIds.has(id) && !knownIds.has(id)) : [];\n if (addedAndSelected.length > 0) {\n setRevealNodeIds(addedAndSelected);\n return;\n }\n setRevealNodeIds((current) =>\n current.length > 0 && !current.every((id) => selectedNodeIds.includes(id)) ? [] : current,\n );\n }, [graph.nodes, selectedNodeIds]);\n\n useEffect(() => {\n if (revealNodeIds.length === 0) return;\n const rects: Array<IFlowRect> = [];\n for (const nodeId of revealNodeIds) {\n const node = graph.nodes.find((candidate) => candidate.nodeId === nodeId);\n const size = measuredSizes[nodeId];\n if (!node || !size) return;\n rects.push({ ...node.position, ...size });\n }\n const bounds = boundsOfRects(rects);\n if (!bounds) return;\n // A pan still animating reports an in-between viewport; build on where it is heading instead.\n const pending = pendingViewportRef.current;\n const baseViewport = pending && pending.settlesAt > Date.now() ? pending.viewport : getViewport();\n const target = viewportToReveal(baseViewport, bounds, { width: canvasWidth, height: canvasHeight });\n if (!target) return;\n pendingViewportRef.current = { viewport: target, settlesAt: Date.now() + REVEAL_DURATION_MS };\n void setViewport(target, { duration: REVEAL_DURATION_MS });\n }, [revealNodeIds, graph.nodes, measuredSizes, canvasWidth, canvasHeight, getViewport, setViewport]);\n\n const stopRevealing = useCallback(() => {\n pendingViewportRef.current = null;\n setRevealNodeIds((current) => (current.length > 0 ? [] : current));\n }, []);\n\n const addableBlocks = useMemo<Array<IFlowAddableBlock>>(() => {\n if (readOnly) return [];\n return registry.list\n .filter((definition) => definition.category !== 'trigger')\n .filter(\n (definition) =>\n definition.maxInstances === undefined ||\n graph.nodes.filter((node) => node.type === definition.type).length < definition.maxInstances,\n )\n .map((definition) => ({ type: definition.type, label: definition.label, icon: definition.icon }));\n }, [registry, graph.nodes, readOnly]);\n\n // A block in the middle of an edge needs an output to carry the flow on to the old target.\n const insertableBlocks = useMemo<Array<IFlowAddableBlock>>(\n () =>\n addableBlocks.filter((block) => {\n const definition = registry.get(block.type);\n return definition ? flowOutputsOf(definition, definition.createDefaultConfig()).length > 0 : false;\n }),\n [addableBlocks, registry],\n );\n\n const nodes = useMemo<Array<TFlowBlockNode>>(\n () =>\n graph.nodes.map((node) => {\n const definition = registry.get(node.type);\n const nodeIssues = safeIssues.filter((issue) => issue.nodeId === node.nodeId);\n return {\n id: node.nodeId,\n type: 'flowBlock',\n position: node.position,\n measured: measuredSizes[node.nodeId],\n selected: selectedNodeIds.includes(node.nodeId),\n draggable: !readOnly,\n connectable: !readOnly,\n data: {\n icon: definition?.resolveIcon?.(node.config) ?? definition?.icon ?? 'help',\n title: node.label ?? definition?.resolveLabel?.(node.config) ?? definition?.label ?? node.type,\n categoryLabel: definition ? labels.categories[definition.category] : '',\n summary: definition\n ? definition.renderSummary(node.config)\n : labels.issueMessage({ code: 'unknownBlock', severity: 'error' }),\n hasInput: definition ? definition.category !== 'trigger' : true,\n outputs: flowOutputsOf(definition, node.config),\n connectedPorts: graph.edges.filter((edge) => edge.source === node.nodeId).map((edge) => edge.sourcePort),\n portLabels: labels.ports,\n addableBlocks,\n onAddFromPort: readOnly\n ? undefined\n : (port, type) => store.getState().addNodeFromPort(type, node.nodeId, port),\n disabled: node.disabled,\n issueSeverity: worstSeverity(nodeIssues),\n issueCount: nodeIssues.length,\n runStatus: runOverlay?.steps?.[node.nodeId],\n },\n };\n }),\n [\n graph.nodes,\n graph.edges,\n registry,\n safeIssues,\n selectedNodeIds,\n readOnly,\n labels,\n runOverlay,\n measuredSizes,\n addableBlocks,\n store,\n ],\n );\n\n const edges = useMemo<Array<TFlowConnectionEdge>>(() => {\n const traversed = new Set(runOverlay?.traversedEdgeIds ?? []);\n return graph.edges.map((edge) => ({\n id: edge.edgeId,\n type: 'flowConnection',\n source: edge.source,\n sourceHandle: edge.sourcePort,\n target: edge.target,\n targetHandle: FLOW_INPUT_HANDLE_ID,\n selected: selectedEdgeIds.includes(edge.edgeId),\n markerEnd: { type: MarkerType.ArrowClosed, width: 16, height: 16 },\n data: {\n label: edge.sourcePort === 'next' ? undefined : labels.ports[edge.sourcePort],\n traversed: traversed.has(edge.edgeId),\n issueSeverity: worstSeverity(safeIssues.filter((issue) => issue.edgeId === edge.edgeId)),\n insertableBlocks,\n onInsert: readOnly ? undefined : (type: string) => store.getState().insertNodeOnEdge(type, edge.edgeId),\n },\n }));\n }, [graph.edges, selectedEdgeIds, runOverlay, labels, safeIssues, insertableBlocks, readOnly, store]);\n\n const handleNodesChange = useCallback(\n (changes: Array<NodeChange<TFlowBlockNode>>) => {\n const positions: Record<string, IFlowPosition> = {};\n const sizes: Record<string, { width: number; height: number }> = {};\n let selection: Array<string> | null = null;\n for (const change of changes) {\n if (change.type === 'dimensions' && change.dimensions) sizes[change.id] = change.dimensions;\n if (change.type === 'position' && change.position && !readOnly) positions[change.id] = change.position;\n if (change.type === 'select') {\n const current: Array<string> = selection ?? store.getState().selectedNodeIds;\n selection = change.selected\n ? [...new Set([...current, change.id])]\n : current.filter((id) => id !== change.id);\n }\n }\n if (Object.keys(sizes).length > 0) setMeasuredSizes((current) => ({ ...current, ...sizes }));\n if (Object.keys(positions).length > 0) store.getState().moveNodes(positions);\n if (selection) store.getState().setSelection({ nodeIds: selection });\n },\n [store, readOnly],\n );\n\n const handleEdgesChange = useCallback(\n (changes: Array<EdgeChange<TFlowConnectionEdge>>) => {\n let selection: Array<string> | null = null;\n for (const change of changes) {\n if (change.type !== 'select') continue;\n const current: Array<string> = selection ?? store.getState().selectedEdgeIds;\n selection = change.selected ? [...new Set([...current, change.id])] : current.filter((id) => id !== change.id);\n }\n if (selection) store.getState().setSelection({ edgeIds: selection });\n },\n [store],\n );\n\n const handleConnect = useCallback(\n (connection: Connection) => {\n if (readOnly || !isPortId(connection.sourceHandle)) return;\n store.getState().connect(connection.source, connection.sourceHandle, connection.target);\n },\n [store, readOnly],\n );\n\n const isValidConnection = useCallback(\n (connection: Connection | TFlowConnectionEdge) =>\n isPortId(connection.sourceHandle) &&\n canConnect(store.getState().graph, registry, {\n source: connection.source,\n sourcePort: connection.sourceHandle,\n target: connection.target,\n }),\n [store, registry],\n );\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n if (readOnly || isTypingTarget(event.target)) return;\n const state = store.getState();\n const withModifier = event.metaKey || event.ctrlKey;\n const key = event.key.toLowerCase();\n\n if (event.key === 'Delete' || event.key === 'Backspace') state.removeSelected();\n else if (withModifier && key === 'z' && event.shiftKey) state.redo();\n else if (withModifier && key === 'z') state.undo();\n else if (withModifier && key === 'y') state.redo();\n else if (withModifier && key === 'c') state.copySelected();\n else if (withModifier && key === 'v') state.paste();\n else if (withModifier && key === 'd') state.duplicateSelected();\n else return;\n event.preventDefault();\n },\n [store, readOnly],\n );\n\n const handleLayout = useCallback(() => {\n const state = store.getState();\n state.recordHistory();\n state.moveNodes(layoutFlowByLevels(state.graph, registry));\n }, [store, registry]);\n\n return (\n <div\n role=\"region\"\n aria-label={ariaLabel ?? t('flow.canvas')}\n tabIndex={0}\n onKeyDown={handleKeyDown}\n className={twMerge(\n 'umode-flow relative h-full min-h-[24rem] w-full rounded-xl bg-canvas focus:outline-none',\n className,\n )}\n >\n <ReactFlow<TFlowBlockNode, TFlowConnectionEdge>\n nodes={nodes}\n edges={edges}\n nodeTypes={NODE_TYPES}\n edgeTypes={EDGE_TYPES}\n onNodesChange={handleNodesChange}\n onEdgesChange={handleEdgesChange}\n onConnect={handleConnect}\n isValidConnection={isValidConnection}\n onNodeDragStart={() => {\n stopRevealing();\n store.getState().recordHistory();\n }}\n onMoveStart={(event) => {\n if (event) stopRevealing();\n }}\n onPaneClick={() => store.getState().setSelection({ nodeIds: [], edgeIds: [] })}\n deleteKeyCode={null}\n nodesDraggable={!readOnly}\n nodesConnectable={!readOnly}\n snapToGrid\n snapGrid={SNAP_GRID}\n minZoom={0.25}\n maxZoom={2}\n fitView\n fitViewOptions={{ padding: 0.2, maxZoom: 1 }}\n proOptions={PRO_OPTIONS}\n >\n {background === 'dots' && <Background variant={BackgroundVariant.Dots} gap={16} size={1} />}\n {nodes.length >= MINIMAP_MIN_NODES && (\n <MiniMap pannable zoomable position=\"bottom-right\" style={MINIMAP_SIZE} />\n )}\n <FlowZoomControls\n onUndo={readOnly ? undefined : () => store.getState().undo()}\n onRedo={readOnly ? undefined : () => store.getState().redo()}\n canUndo={canUndo}\n canRedo={canRedo}\n onLayout={readOnly ? undefined : handleLayout}\n position={controlsPosition}\n />\n </ReactFlow>\n </div>\n );\n};\n\nexport default FlowCanvas;\n"],"names":["useReactFlowStore"],"mappings":";;;;;;;;;;;;;;;AAgCA,MAAM,cAA0B,EAAE,iBAAiB,KAAA;AACnD,MAAM,aAAa,EAAE,WAAW,cAAA;AAChC,MAAM,aAAa,EAAE,gBAAgB,mBAAA;AAC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BAAI,MAAO,eAAA;AAAA,UACb;AAAA,UACA,aAAa,MAAM,MAAM,WAAW,aAAa,EAAE,SAAS,CAAA,GAAI,SAAS,CAAA,GAAI;AAAA,UAC7E,eAAe;AAAA,UACf,gBAAgB,CAAC;AAAA,UACjB,kBAAkB,CAAC;AAAA,UACnB,YAAU;AAAA,UACV,UAAU;AAAA,UACV,SAAS;AAAA,UACT,SAAS;AAAA,UACT,SAAO;AAAA,UACP,gBAAgB,EAAE,SAAS,KAAK,SAAS,EAAA;AAAA,UACzC,YAAY;AAAA,UAEX,UAAA;AAAA,YAAA,eAAe,8BAAW,YAAA,EAAW,SAAS,kBAAkB,MAAM,KAAK,IAAI,MAAM,EAAA,CAAG;AAAA,YACxF,MAAM,UAAU,qBACf,oBAAC,SAAA,EAAQ,UAAQ,MAAC,UAAQ,MAAC,UAAS,gBAAe,OAAO,aAAA,CAAc;AAAA,YAE1E;AAAA,cAAC;AAAA,cAAA;AAAA,gBACC,QAAQ,WAAW,SAAY,MAAM,MAAM,SAAA,EAAW,KAAA;AAAA,gBACtD,QAAQ,WAAW,SAAY,MAAM,MAAM,SAAA,EAAW,KAAA;AAAA,gBACtD;AAAA,gBACA;AAAA,gBACA,UAAU,WAAW,SAAY;AAAA,gBACjC,UAAU;AAAA,cAAA;AAAA,YAAA;AAAA,UACZ;AAAA,QAAA;AAAA,MAAA;AAAA,IACF;AAAA,EAAA;AAGN;"}
@@ -7,6 +7,7 @@ import ControlledTooltip from "../ControlledTooltip.js";
7
7
  import { MaterialSymbol } from "../MaterialSymbol/index.js";
8
8
  import NoDataFound from "../NoDataFound/index.js";
9
9
  import { useFlowBlockRegistry, useFlowEditorStore, useFlowEditor } from "./FlowEditorProvider.js";
10
+ import { isFlowNodeRemovable } from "./flowGraph.js";
10
11
  import { useFlowLabels } from "./useFlowLabels.js";
11
12
  const FlowInspector = ({
12
13
  issues = [],
@@ -33,6 +34,8 @@ const FlowInspector = ({
33
34
  const definition = registry.get(selectedNode.type);
34
35
  const nodeIssues = (Array.isArray(issues) ? issues : []).filter((issue) => issue.nodeId === selectedNode.nodeId);
35
36
  const ConfigPanel = definition?.ConfigPanel;
37
+ const canDuplicate = definition?.category !== "trigger";
38
+ const canRemove = isFlowNodeRemovable(selectedNode, registry);
36
39
  return /* @__PURE__ */ jsxs("aside", { className: shellClass, "aria-label": t("flow.inspector.title"), children: [
37
40
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
38
41
  /* @__PURE__ */ jsx("span", { className: "flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground-muted", children: /* @__PURE__ */ jsx(
@@ -88,13 +91,14 @@ const FlowInspector = ({
88
91
  /* @__PURE__ */ jsx("span", { className: "text-xs text-foreground-muted", children: labels.issueMessage(issue) })
89
92
  ] }, `${issue.code}|${issue.edgeId ?? ""}`)) })
90
93
  ] }),
91
- !readOnly && /* @__PURE__ */ jsxs("div", { className: "flex gap-x-2", children: [
92
- definition?.category !== "trigger" && /* @__PURE__ */ jsxs(
94
+ !readOnly && (canDuplicate || canRemove) && /* @__PURE__ */ jsxs("div", { className: "flex gap-x-2", children: [
95
+ canDuplicate && /* @__PURE__ */ jsxs(
93
96
  ControlledButton,
94
97
  {
95
98
  size: "sm",
96
99
  variant: "outlined",
97
100
  tone: "neutral",
101
+ className: "normal-case",
98
102
  onClick: () => store.getState().duplicateSelected(),
99
103
  children: [
100
104
  /* @__PURE__ */ jsx(MaterialSymbol, { icon: "content_copy", size: 16, "aria-hidden": true }),
@@ -102,12 +106,13 @@ const FlowInspector = ({
102
106
  ]
103
107
  }
104
108
  ),
105
- /* @__PURE__ */ jsxs(
109
+ canRemove && /* @__PURE__ */ jsxs(
106
110
  ControlledButton,
107
111
  {
108
112
  size: "sm",
109
113
  variant: "outlined",
110
114
  tone: "danger",
115
+ className: "normal-case",
111
116
  onClick: () => store.getState().removeSelected(),
112
117
  children: [
113
118
  /* @__PURE__ */ jsx(MaterialSymbol, { icon: "delete", size: 16, "aria-hidden": true }),
@@ -1 +1 @@
1
- {"version":3,"file":"FlowInspector.js","sources":["../../../../src/components/UI/Flow/FlowInspector.tsx"],"sourcesContent":["import { useTranslation } from 'react-i18next';\nimport { twMerge } from 'tailwind-merge';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport ControlledInput from '@/components/Form/ControlledInput';\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport { MaterialSymbol } from '@/components/UI/MaterialSymbol';\nimport NoDataFound from '@/components/UI/NoDataFound';\n\nimport { useFlowBlockRegistry, useFlowEditor, useFlowEditorStore } from './FlowEditorProvider';\nimport type { IFlowIssue } from './flowTypes';\nimport { useFlowLabels } from './useFlowLabels';\n\ninterface IFlowInspectorProps {\n issues?: Array<IFlowIssue>;\n readOnly?: boolean;\n /** Renders nothing while no block is selected, instead of the empty state. */\n hideWhenEmpty?: boolean;\n className?: string;\n}\n\n/** The side panel of the selected block: its name, its own settings panel and its issues. */\nconst FlowInspector: React.FC<IFlowInspectorProps> = ({\n issues = [],\n readOnly = false,\n hideWhenEmpty = false,\n className,\n}) => {\n const { t } = useTranslation('ui');\n const labels = useFlowLabels();\n const registry = useFlowBlockRegistry();\n const store = useFlowEditorStore();\n const selectedNodeIds = useFlowEditor((state) => state.selectedNodeIds);\n const selectedNode = useFlowEditor((state) =>\n state.selectedNodeIds.length === 1\n ? state.graph.nodes.find((node) => node.nodeId === state.selectedNodeIds[0])\n : undefined,\n );\n\n const shellClass = twMerge(\n 'flex h-full min-h-0 flex-col gap-y-3 rounded-xl border border-border bg-surface p-4',\n className,\n );\n\n if (!selectedNode || selectedNodeIds.length !== 1) {\n if (hideWhenEmpty) return null;\n return (\n <aside className={shellClass} aria-label={t('flow.inspector.title')}>\n <NoDataFound size=\"sm\" variant=\"waiting\" message={t('flow.inspector.empty')} />\n </aside>\n );\n }\n\n const definition = registry.get(selectedNode.type);\n const nodeIssues = (Array.isArray(issues) ? issues : []).filter((issue) => issue.nodeId === selectedNode.nodeId);\n const ConfigPanel = definition?.ConfigPanel;\n\n return (\n <aside className={shellClass} aria-label={t('flow.inspector.title')}>\n <div className=\"flex items-center gap-x-2\">\n <span className=\"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground-muted\">\n <MaterialSymbol\n icon={definition?.resolveIcon?.(selectedNode.config) ?? definition?.icon ?? 'help'}\n size={18}\n aria-hidden\n />\n </span>\n <div className=\"flex min-w-0 flex-col\">\n {definition && (\n <span className=\"text-xxs font-semibold uppercase tracking-wide text-foreground-subtle\">\n {labels.categories[definition.category]}\n </span>\n )}\n <span className=\"truncate text-sm font-semibold text-foreground\">\n {definition?.resolveLabel?.(selectedNode.config) ?? definition?.label ?? selectedNode.type}\n </span>\n </div>\n <ControlledTooltip content={t('flow.inspector.close')} placement=\"left\">\n <ControlledButton\n defaultHtmlButton\n onClick={() => store.getState().setSelection({ nodeIds: [], edgeIds: [] })}\n className=\"interactive ml-auto flex size-8 shrink-0 items-center justify-center rounded-lg text-foreground-muted hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <MaterialSymbol icon=\"close\" size={18} aria-hidden />\n </ControlledButton>\n </ControlledTooltip>\n </div>\n\n <ControlledInput\n label={t('flow.inspector.label')}\n value={selectedNode.label ?? ''}\n disabled={readOnly}\n onChange={(event) => store.getState().updateNodeLabel(selectedNode.nodeId, event.target.value)}\n />\n\n <div className=\"flex min-h-0 flex-1 flex-col gap-y-3 overflow-y-auto\">\n {ConfigPanel ? (\n <ConfigPanel\n config={selectedNode.config}\n readOnly={readOnly}\n onChange={(next) => store.getState().updateNodeConfig(selectedNode.nodeId, next)}\n />\n ) : (\n <NoDataFound compact variant=\"error\" message={t('flow.inspector.unknownBlock')} />\n )}\n\n {nodeIssues.length > 0 && (\n <ul className=\"flex flex-col gap-y-1\">\n {nodeIssues.map((issue) => (\n <li key={`${issue.code}|${issue.edgeId ?? ''}`} className=\"flex items-start gap-x-2\">\n <MaterialSymbol\n icon={issue.severity === 'error' ? 'error' : 'warning'}\n size={16}\n className={issue.severity === 'error' ? 'text-danger-emphasis' : 'text-warning-emphasis'}\n aria-hidden\n />\n <span className=\"text-xs text-foreground-muted\">{labels.issueMessage(issue)}</span>\n </li>\n ))}\n </ul>\n )}\n </div>\n\n {!readOnly && (\n <div className=\"flex gap-x-2\">\n {definition?.category !== 'trigger' && (\n <ControlledButton\n size=\"sm\"\n variant=\"outlined\"\n tone=\"neutral\"\n onClick={() => store.getState().duplicateSelected()}\n >\n <MaterialSymbol icon=\"content_copy\" size={16} aria-hidden />\n {t('flow.inspector.duplicate')}\n </ControlledButton>\n )}\n <ControlledButton\n size=\"sm\"\n variant=\"outlined\"\n tone=\"danger\"\n onClick={() => store.getState().removeSelected()}\n >\n <MaterialSymbol icon=\"delete\" size={16} aria-hidden />\n {t('flow.inspector.delete')}\n </ControlledButton>\n </div>\n )}\n </aside>\n );\n};\n\nexport default FlowInspector;\n"],"names":[],"mappings":";;;;;;;;;;AAsBA,MAAM,gBAA+C,CAAC;AAAA,EACpD,SAAS,CAAA;AAAA,EACT,WAAW;AAAA,EACX,gBAAgB;AAAA,EAChB;AACF,MAAM;AACJ,QAAM,EAAE,EAAA,IAAM,eAAe,IAAI;AACjC,QAAM,SAAS,cAAA;AACf,QAAM,WAAW,qBAAA;AACjB,QAAM,QAAQ,mBAAA;AACd,QAAM,kBAAkB,cAAc,CAAC,UAAU,MAAM,eAAe;AACtE,QAAM,eAAe;AAAA,IAAc,CAAC,UAClC,MAAM,gBAAgB,WAAW,IAC7B,MAAM,MAAM,MAAM,KAAK,CAAC,SAAS,KAAK,WAAW,MAAM,gBAAgB,CAAC,CAAC,IACzE;AAAA,EAAA;AAGN,QAAM,aAAa;AAAA,IACjB;AAAA,IACA;AAAA,EAAA;AAGF,MAAI,CAAC,gBAAgB,gBAAgB,WAAW,GAAG;AACjD,QAAI,cAAe,QAAO;AAC1B,+BACG,SAAA,EAAM,WAAW,YAAY,cAAY,EAAE,sBAAsB,GAChE,UA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kBAAe,MAAK,gBAAe,MAAM,IAAI,eAAW,MAAC;AAAA,YACzD,EAAE,0BAA0B;AAAA,UAAA;AAAA,QAAA;AAAA,MAAA;AAAA,MAGjC;AAAA,QAAC;AAAA,QAAA;AAAA,UACC,MAAK;AAAA,UACL,SAAQ;AAAA,UACR,MAAK;AAAA,UACL,SAAS,MAAM,MAAM,SAAA,EAAW,eAAA;AAAA,UAEhC,UAAA;AAAA,YAAA,oBAAC,kBAAe,MAAK,UAAS,MAAM,IAAI,eAAW,MAAC;AAAA,YACnD,EAAE,uBAAuB;AAAA,UAAA;AAAA,QAAA;AAAA,MAAA;AAAA,IAC5B,EAAA,CACF;AAAA,EAAA,GAEJ;AAEJ;"}
1
+ {"version":3,"file":"FlowInspector.js","sources":["../../../../src/components/UI/Flow/FlowInspector.tsx"],"sourcesContent":["import { useTranslation } from 'react-i18next';\nimport { twMerge } from 'tailwind-merge';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport ControlledInput from '@/components/Form/ControlledInput';\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport { MaterialSymbol } from '@/components/UI/MaterialSymbol';\nimport NoDataFound from '@/components/UI/NoDataFound';\n\nimport { useFlowBlockRegistry, useFlowEditor, useFlowEditorStore } from './FlowEditorProvider';\nimport { isFlowNodeRemovable } from './flowGraph';\nimport type { IFlowIssue } from './flowTypes';\nimport { useFlowLabels } from './useFlowLabels';\n\ninterface IFlowInspectorProps {\n issues?: Array<IFlowIssue>;\n readOnly?: boolean;\n /** Renders nothing while no block is selected, instead of the empty state. */\n hideWhenEmpty?: boolean;\n className?: string;\n}\n\n/** The side panel of the selected block: its name, its own settings panel and its issues. */\nconst FlowInspector: React.FC<IFlowInspectorProps> = ({\n issues = [],\n readOnly = false,\n hideWhenEmpty = false,\n className,\n}) => {\n const { t } = useTranslation('ui');\n const labels = useFlowLabels();\n const registry = useFlowBlockRegistry();\n const store = useFlowEditorStore();\n const selectedNodeIds = useFlowEditor((state) => state.selectedNodeIds);\n const selectedNode = useFlowEditor((state) =>\n state.selectedNodeIds.length === 1\n ? state.graph.nodes.find((node) => node.nodeId === state.selectedNodeIds[0])\n : undefined,\n );\n\n const shellClass = twMerge(\n 'flex h-full min-h-0 flex-col gap-y-3 rounded-xl border border-border bg-surface p-4',\n className,\n );\n\n if (!selectedNode || selectedNodeIds.length !== 1) {\n if (hideWhenEmpty) return null;\n return (\n <aside className={shellClass} aria-label={t('flow.inspector.title')}>\n <NoDataFound size=\"sm\" variant=\"waiting\" message={t('flow.inspector.empty')} />\n </aside>\n );\n }\n\n const definition = registry.get(selectedNode.type);\n const nodeIssues = (Array.isArray(issues) ? issues : []).filter((issue) => issue.nodeId === selectedNode.nodeId);\n const ConfigPanel = definition?.ConfigPanel;\n const canDuplicate = definition?.category !== 'trigger';\n const canRemove = isFlowNodeRemovable(selectedNode, registry);\n\n return (\n <aside className={shellClass} aria-label={t('flow.inspector.title')}>\n <div className=\"flex items-center gap-x-2\">\n <span className=\"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground-muted\">\n <MaterialSymbol\n icon={definition?.resolveIcon?.(selectedNode.config) ?? definition?.icon ?? 'help'}\n size={18}\n aria-hidden\n />\n </span>\n <div className=\"flex min-w-0 flex-col\">\n {definition && (\n <span className=\"text-xxs font-semibold uppercase tracking-wide text-foreground-subtle\">\n {labels.categories[definition.category]}\n </span>\n )}\n <span className=\"truncate text-sm font-semibold text-foreground\">\n {definition?.resolveLabel?.(selectedNode.config) ?? definition?.label ?? selectedNode.type}\n </span>\n </div>\n <ControlledTooltip content={t('flow.inspector.close')} placement=\"left\">\n <ControlledButton\n defaultHtmlButton\n onClick={() => store.getState().setSelection({ nodeIds: [], edgeIds: [] })}\n className=\"interactive ml-auto flex size-8 shrink-0 items-center justify-center rounded-lg text-foreground-muted hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <MaterialSymbol icon=\"close\" size={18} aria-hidden />\n </ControlledButton>\n </ControlledTooltip>\n </div>\n\n <ControlledInput\n label={t('flow.inspector.label')}\n value={selectedNode.label ?? ''}\n disabled={readOnly}\n onChange={(event) => store.getState().updateNodeLabel(selectedNode.nodeId, event.target.value)}\n />\n\n <div className=\"flex min-h-0 flex-1 flex-col gap-y-3 overflow-y-auto\">\n {ConfigPanel ? (\n <ConfigPanel\n config={selectedNode.config}\n readOnly={readOnly}\n onChange={(next) => store.getState().updateNodeConfig(selectedNode.nodeId, next)}\n />\n ) : (\n <NoDataFound compact variant=\"error\" message={t('flow.inspector.unknownBlock')} />\n )}\n\n {nodeIssues.length > 0 && (\n <ul className=\"flex flex-col gap-y-1\">\n {nodeIssues.map((issue) => (\n <li key={`${issue.code}|${issue.edgeId ?? ''}`} className=\"flex items-start gap-x-2\">\n <MaterialSymbol\n icon={issue.severity === 'error' ? 'error' : 'warning'}\n size={16}\n className={issue.severity === 'error' ? 'text-danger-emphasis' : 'text-warning-emphasis'}\n aria-hidden\n />\n <span className=\"text-xs text-foreground-muted\">{labels.issueMessage(issue)}</span>\n </li>\n ))}\n </ul>\n )}\n </div>\n\n {!readOnly && (canDuplicate || canRemove) && (\n <div className=\"flex gap-x-2\">\n {canDuplicate && (\n <ControlledButton\n size=\"sm\"\n variant=\"outlined\"\n tone=\"neutral\"\n className=\"normal-case\"\n onClick={() => store.getState().duplicateSelected()}\n >\n <MaterialSymbol icon=\"content_copy\" size={16} aria-hidden />\n {t('flow.inspector.duplicate')}\n </ControlledButton>\n )}\n {canRemove && (\n <ControlledButton\n size=\"sm\"\n variant=\"outlined\"\n tone=\"danger\"\n className=\"normal-case\"\n onClick={() => store.getState().removeSelected()}\n >\n <MaterialSymbol icon=\"delete\" size={16} aria-hidden />\n {t('flow.inspector.delete')}\n </ControlledButton>\n )}\n </div>\n )}\n </aside>\n );\n};\n\nexport default FlowInspector;\n"],"names":[],"mappings":";;;;;;;;;;;AAuBA,MAAM,gBAA+C,CAAC;AAAA,EACpD,SAAS,CAAA;AAAA,EAC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} from "./flowBlockRegistry.js";
4
- import { canConnect, reachableFrom, FLOW_LEVEL_GAP, FLOW_SIBLING_GAP, layoutFlowByLevels } from "./flowGraph.js";
4
+ import { isFlowNodeRemovable, canConnect, reachableFrom, FLOW_LEVEL_GAP, FLOW_SIBLING_GAP, layoutFlowByLevels } from "./flowGraph.js";
5
5
  const HISTORY_LIMIT = 50;
6
6
  const PASTE_OFFSET = 32;
7
7
  const COALESCE_WINDOW_MS = 1e3;
@@ -226,11 +226,12 @@ const createFlowEditorStore = (initialGraph, registry) => createStore()((set, ge
226
226
  },
227
227
  removeSelected: () => {
228
228
  const { graph, selectedNodeIds, selectedEdgeIds } = get();
229
- if (selectedNodeIds.length === 0 && selectedEdgeIds.length === 0) return;
229
+ const removableNodeIds = graph.nodes.filter((node) => selectedNodeIds.includes(node.nodeId) && isFlowNodeRemovable(node, currentRegistry)).map((node) => node.nodeId);
230
+ if (removableNodeIds.length === 0 && selectedEdgeIds.length === 0) return;
230
231
  const removedEdges = new Set(selectedEdgeIds);
231
232
  const next = withoutNodes(
232
233
  { ...graph, edges: graph.edges.filter((edge) => !removedEdges.has(edge.edgeId)) },
233
- new Set(selectedNodeIds)
234
+ new Set(removableNodeIds)
234
235
  );
235
236
  commit(next, { nodeIds: [], edgeIds: [] });
236
237
  },
@@ -1 +1 @@
1
- {"version":3,"file":"flowEditorStore.js","sources":["../../../../src/components/UI/Flow/flowEditorStore.ts"],"sourcesContent":["import { createStore, type StoreApi } from 'zustand/vanilla';\n\nimport { generateUUID } from '@/helpers/utilityHelpers';\n\nimport { flowOutputsOf, type IFlowBlockRegistry } from './flowBlockRegistry';\nimport { canConnect, FLOW_LEVEL_GAP, FLOW_SIBLING_GAP, layoutFlowByLevels, reachableFrom } from './flowGraph';\nimport type { IFlowEdge, IFlowGraph, IFlowNode, IFlowPosition, TFlowPortId } from './flowTypes';\n\nconst HISTORY_LIMIT = 50;\nconst PASTE_OFFSET = 32;\n/** Edits to the same field within this window share one undo step (typing a name is one change). */\nconst COALESCE_WINDOW_MS = 1000;\n\nexport interface IFlowEditorState {\n graph: IFlowGraph;\n selectedNodeIds: Array<string>;\n selectedEdgeIds: Array<string>;\n past: Array<IFlowGraph>;\n future: Array<IFlowGraph>;\n clipboard: Array<IFlowNode>;\n isDirty: boolean;\n\n replaceGraph: (graph: IFlowGraph, options?: { keepHistory?: boolean }) => void;\n markClean: () => void;\n /** Snapshot before a gesture that changes the graph in many small steps (a drag). */\n recordHistory: () => void;\n addNode: (type: string) => string | null;\n /** Adds a block right of `sourceNodeId` and wires `sourcePort` to it in one undo step. */\n addNodeFromPort: (type: string, sourceNodeId: string, sourcePort: TFlowPortId) => string | null;\n /**\n * Puts a block in the middle of an edge: the edge now ends at the new block, whose first output\n * leads to the old target. The old target and everything after it move one column right, so the\n * new block takes the place it left. One undo step.\n */\n insertNodeOnEdge: (type: string, edgeId: string) => string | null;\n updateNodeConfig: (nodeId: string, config: unknown) => void;\n updateNodeLabel: (nodeId: string, label: string) => void;\n moveNodes: (positions: Record<string, IFlowPosition>) => void;\n connect: (source: string, sourcePort: TFlowPortId, target: string) => boolean;\n removeSelected: () => void;\n duplicateSelected: () => void;\n copySelected: () => void;\n paste: () => void;\n setSelection: (selection: { nodeIds?: Array<string>; edgeIds?: Array<string> }) => void;\n undo: () => void;\n redo: () => void;\n /** The host may rebuild its registry (labels after a language switch); gestures always read the latest. */\n setRegistry: (registry: IFlowBlockRegistry) => void;\n}\n\nexport type TFlowEditorStore = StoreApi<IFlowEditorState>;\n\nconst isPosition = (position: unknown): position is IFlowPosition =>\n typeof (position as IFlowPosition | undefined)?.x === 'number' &&\n typeof (position as IFlowPosition | undefined)?.y === 'number';\n\n/** Coerces a stored graph; a block saved without a position is placed by the automatic layout. */\nconst normalizeGraph = (graph: IFlowGraph | null | undefined, registry: IFlowBlockRegistry): IFlowGraph => {\n const normalized: IFlowGraph = {\n nodes: Array.isArray(graph?.nodes) ? graph.nodes : [],\n edges: Array.isArray(graph?.edges) ? graph.edges : [],\n };\n if (normalized.nodes.every((node) => isPosition(node.position))) return normalized;\n\n const layout = layoutFlowByLevels(normalized, registry);\n return {\n ...normalized,\n nodes: normalized.nodes.map((node) =>\n isPosition(node.position) ? node : { ...node, position: layout[node.nodeId] ?? { x: 0, y: 0 } },\n ),\n };\n};\n\nconst withoutNodes = (graph: IFlowGraph, nodeIds: Set<string>): IFlowGraph => ({\n nodes: graph.nodes.filter((node) => !nodeIds.has(node.nodeId)),\n edges: graph.edges.filter((edge) => !nodeIds.has(edge.source) && !nodeIds.has(edge.target)),\n});\n\nconst isPositionTaken = (graph: IFlowGraph, position: IFlowPosition): boolean =>\n graph.nodes.some(\n (node) =>\n Math.abs(node.position.x - position.x) < FLOW_LEVEL_GAP &&\n Math.abs(node.position.y - position.y) < FLOW_SIBLING_GAP,\n );\n\n/** Right of the selected block (or the rightmost one), stepping down the column until the slot is free. */\nconst nextFreePosition = (graph: IFlowGraph, selectedNodeIds: Array<string>): IFlowPosition => {\n if (graph.nodes.length === 0) return { x: 0, y: 0 };\n const anchor =\n graph.nodes.find((node) => node.nodeId === selectedNodeIds[0]) ??\n graph.nodes.reduce((current, node) => (node.position.x > current.position.x ? node : current));\n let candidate = { x: anchor.position.x + FLOW_LEVEL_GAP, y: anchor.position.y };\n while (isPositionTaken(graph, candidate)) candidate = { x: candidate.x, y: candidate.y + FLOW_SIBLING_GAP };\n return candidate;\n};\n\n/**\n * One store per editor instance (two canvases on a page never share state). The graph\n * is the source of truth; the canvas only renders it and reports gestures back.\n */\nexport const createFlowEditorStore = (initialGraph: IFlowGraph, registry: IFlowBlockRegistry): TFlowEditorStore =>\n createStore<IFlowEditorState>()((set, get) => {\n let currentRegistry = registry;\n let lastCoalesce: { key: string; at: number } | null = null;\n\n const commit = (\n next: IFlowGraph,\n selection?: { nodeIds?: Array<string>; edgeIds?: Array<string> },\n coalesceKey?: string,\n ) => {\n const { graph, past } = get();\n const now = Date.now();\n const extendsLastStep =\n coalesceKey !== undefined && lastCoalesce?.key === coalesceKey && now - lastCoalesce.at < COALESCE_WINDOW_MS;\n lastCoalesce = coalesceKey === undefined ? null : { key: coalesceKey, at: now };\n set({\n graph: next,\n past: extendsLastStep ? past : [...past, graph].slice(-HISTORY_LIMIT),\n future: [],\n isDirty: true,\n ...(selection?.nodeIds ? { selectedNodeIds: selection.nodeIds } : {}),\n ...(selection?.edgeIds ? { selectedEdgeIds: selection.edgeIds } : {}),\n });\n };\n\n const cloneNodes = (nodes: Array<IFlowNode>, offset: number): Array<IFlowNode> => {\n const instancesByType = new Map<string, number>();\n get().graph.nodes.forEach((node) => instancesByType.set(node.type, (instancesByType.get(node.type) ?? 0) + 1));\n return nodes\n .filter((node) => {\n const definition = currentRegistry.get(node.type);\n if (!definition || definition.category === 'trigger') return false;\n const instances = instancesByType.get(node.type) ?? 0;\n if (definition.maxInstances !== undefined && instances >= definition.maxInstances) return false;\n instancesByType.set(node.type, instances + 1);\n return true;\n })\n .map((node) => ({\n ...node,\n nodeId: generateUUID(),\n config: structuredClone(node.config),\n position: { x: node.position.x + offset, y: node.position.y + offset },\n }));\n };\n\n return {\n graph: normalizeGraph(initialGraph, registry),\n selectedNodeIds: [],\n selectedEdgeIds: [],\n past: [],\n future: [],\n clipboard: [],\n isDirty: false,\n\n replaceGraph: (graph, options) => {\n set((state) => ({\n graph: normalizeGraph(graph, currentRegistry),\n past: options?.keepHistory ? [...state.past, state.graph].slice(-HISTORY_LIMIT) : [],\n future: [],\n selectedNodeIds: [],\n selectedEdgeIds: [],\n isDirty: Boolean(options?.keepHistory),\n }));\n },\n\n markClean: () => set({ isDirty: false }),\n\n recordHistory: () => {\n const { graph, past } = get();\n set({ past: [...past, graph].slice(-HISTORY_LIMIT), future: [] });\n },\n\n addNode: (type) => {\n const definition = currentRegistry.get(type);\n if (!definition) return null;\n\n const { graph, selectedNodeIds } = get();\n const instances = graph.nodes.filter((node) => node.type === type).length;\n if (definition.maxInstances !== undefined && instances >= definition.maxInstances) return null;\n\n const node: IFlowNode = {\n nodeId: generateUUID(),\n type,\n typeVersion: definition.typeVersion,\n config: definition.createDefaultConfig(),\n position: nextFreePosition(graph, selectedNodeIds),\n };\n commit({ ...graph, nodes: [...graph.nodes, node] }, { nodeIds: [node.nodeId], edgeIds: [] });\n return node.nodeId;\n },\n\n addNodeFromPort: (type, sourceNodeId, sourcePort) => {\n const definition = currentRegistry.get(type);\n const { graph } = get();\n const source = graph.nodes.find((node) => node.nodeId === sourceNodeId);\n if (!definition || !source) return null;\n\n const instances = graph.nodes.filter((node) => node.type === type).length;\n if (definition.maxInstances !== undefined && instances >= definition.maxInstances) return null;\n if (graph.edges.some((edge) => edge.source === sourceNodeId && edge.sourcePort === sourcePort)) return null;\n\n const outputs = flowOutputsOf(currentRegistry.get(source.type), source.config);\n if (!outputs.includes(sourcePort)) return null;\n const portIndex = outputs.indexOf(sourcePort);\n let position = {\n x: source.position.x + FLOW_LEVEL_GAP,\n y: source.position.y + (portIndex - (outputs.length - 1) / 2) * FLOW_SIBLING_GAP,\n };\n while (isPositionTaken(graph, position)) position = { x: position.x, y: position.y + FLOW_SIBLING_GAP };\n\n const node: IFlowNode = {\n nodeId: generateUUID(),\n type,\n typeVersion: definition.typeVersion,\n config: definition.createDefaultConfig(),\n position,\n };\n const nodes = [...graph.nodes, node];\n const wires = canConnect({ ...graph, nodes }, currentRegistry, {\n source: sourceNodeId,\n sourcePort,\n target: node.nodeId,\n });\n const edges = wires\n ? [...graph.edges, { edgeId: generateUUID(), source: sourceNodeId, sourcePort, target: node.nodeId }]\n : graph.edges;\n commit({ nodes, edges }, { nodeIds: [node.nodeId], edgeIds: [] });\n return node.nodeId;\n },\n\n insertNodeOnEdge: (type, edgeId) => {\n const definition = currentRegistry.get(type);\n const { graph } = get();\n const edge = graph.edges.find((candidate) => candidate.edgeId === edgeId);\n const target = edge ? graph.nodes.find((node) => node.nodeId === edge.target) : undefined;\n const config = definition?.createDefaultConfig();\n const continuationPort = definition ? flowOutputsOf(definition, config)[0] : undefined;\n if (!definition || !edge || !target || !continuationPort || definition.category === 'trigger') return null;\n\n const instances = graph.nodes.filter((node) => node.type === type).length;\n if (definition.maxInstances !== undefined && instances >= definition.maxInstances) return null;\n\n const shifted = reachableFrom(graph, target.nodeId);\n const node: IFlowNode = {\n nodeId: generateUUID(),\n type,\n typeVersion: definition.typeVersion,\n config,\n position: { ...target.position },\n };\n const nodes = [\n ...graph.nodes.map((current) =>\n shifted.has(current.nodeId)\n ? { ...current, position: { x: current.position.x + FLOW_LEVEL_GAP, y: current.position.y } }\n : current,\n ),\n node,\n ];\n const withoutEdge = graph.edges.filter((current) => current.edgeId !== edgeId);\n const incoming: IFlowEdge = { ...edge, target: node.nodeId };\n const outgoing: IFlowEdge = {\n edgeId: generateUUID(),\n source: node.nodeId,\n sourcePort: continuationPort,\n target: target.nodeId,\n };\n\n const wiresIn = canConnect({ nodes, edges: withoutEdge }, currentRegistry, incoming);\n const wiresOut = canConnect({ nodes, edges: [...withoutEdge, incoming] }, currentRegistry, outgoing);\n if (!wiresIn || !wiresOut) return null;\n\n commit({ nodes, edges: [...withoutEdge, incoming, outgoing] }, { nodeIds: [node.nodeId], edgeIds: [] });\n return node.nodeId;\n },\n\n updateNodeConfig: (nodeId, config) => {\n const { graph } = get();\n const node = graph.nodes.find((candidate) => candidate.nodeId === nodeId);\n const outputs = node ? flowOutputsOf(currentRegistry.get(node.type), config) : [];\n commit(\n {\n nodes: graph.nodes.map((current) => (current.nodeId === nodeId ? { ...current, config } : current)),\n edges: graph.edges.filter((edge) => edge.source !== nodeId || outputs.includes(edge.sourcePort)),\n },\n undefined,\n `config:${nodeId}`,\n );\n },\n\n updateNodeLabel: (nodeId, label) => {\n const { graph } = get();\n const hasText = label.trim().length > 0;\n commit(\n {\n ...graph,\n nodes: graph.nodes.map((node) =>\n node.nodeId === nodeId ? { ...node, label: hasText ? label : undefined } : node,\n ),\n },\n undefined,\n `label:${nodeId}`,\n );\n },\n\n moveNodes: (positions) => {\n const { graph } = get();\n set({\n graph: {\n ...graph,\n nodes: graph.nodes.map((node) =>\n positions[node.nodeId] ? { ...node, position: positions[node.nodeId] } : node,\n ),\n },\n isDirty: true,\n });\n },\n\n connect: (source, sourcePort, target) => {\n const { graph } = get();\n if (!canConnect(graph, currentRegistry, { source, sourcePort, target })) return false;\n const edge: IFlowEdge = { edgeId: generateUUID(), source, sourcePort, target };\n commit({ ...graph, edges: [...graph.edges, edge] });\n return true;\n },\n\n removeSelected: () => {\n const { graph, selectedNodeIds, selectedEdgeIds } = get();\n if (selectedNodeIds.length === 0 && selectedEdgeIds.length === 0) return;\n const removedEdges = new Set(selectedEdgeIds);\n const next = withoutNodes(\n { ...graph, edges: graph.edges.filter((edge) => !removedEdges.has(edge.edgeId)) },\n new Set(selectedNodeIds),\n );\n commit(next, { nodeIds: [], edgeIds: [] });\n },\n\n duplicateSelected: () => {\n const { graph, selectedNodeIds } = get();\n const selected = graph.nodes.filter((node) => selectedNodeIds.includes(node.nodeId));\n const copies = cloneNodes(selected, PASTE_OFFSET);\n if (copies.length === 0) return;\n commit(\n { ...graph, nodes: [...graph.nodes, ...copies] },\n { nodeIds: copies.map((node) => node.nodeId), edgeIds: [] },\n );\n },\n\n copySelected: () => {\n const { graph, selectedNodeIds } = get();\n set({ clipboard: graph.nodes.filter((node) => selectedNodeIds.includes(node.nodeId)) });\n },\n\n paste: () => {\n const { graph, clipboard } = get();\n const copies = cloneNodes(clipboard, PASTE_OFFSET);\n if (copies.length === 0) return;\n commit(\n { ...graph, nodes: [...graph.nodes, ...copies] },\n { nodeIds: copies.map((node) => node.nodeId), edgeIds: [] },\n );\n set({ clipboard: copies });\n },\n\n setSelection: ({ nodeIds, edgeIds }) => {\n set((state) => ({\n selectedNodeIds: nodeIds ?? state.selectedNodeIds,\n selectedEdgeIds: edgeIds ?? state.selectedEdgeIds,\n }));\n },\n\n undo: () => {\n const { graph, past, future } = get();\n const previous = past[past.length - 1];\n if (!previous) return;\n set({\n graph: previous,\n past: past.slice(0, -1),\n future: [graph, ...future].slice(0, HISTORY_LIMIT),\n selectedNodeIds: [],\n selectedEdgeIds: [],\n isDirty: true,\n });\n },\n\n redo: () => {\n const { graph, past, future } = get();\n const following = future[0];\n if (!following) return;\n set({\n graph: following,\n past: [...past, graph].slice(-HISTORY_LIMIT),\n future: future.slice(1),\n selectedNodeIds: [],\n selectedEdgeIds: [],\n isDirty: true,\n });\n },\n\n setRegistry: (nextRegistry) => {\n currentRegistry = nextRegistry;\n },\n };\n });\n"],"names":["node"],"mappings":";;;;AAQA,MAAM,gBAAgB;AACtB,MAAM,eAAe;AAErB,MAAM,qBAAqB;AAyC3B,MAAM,aAAa,CAAC,aAClB,OAAQ,UAAwC,MAAM,YACtD,OAAQ,UAAwC,MAAM;AAGxD,MAAM,iBAAiB,CAAC,OAAsC,aAA6C;AACzG,QAAM,aAAyB;AAAA,IAC7B,OAAO,MAAM,QAAQ,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAA;AAAA,IACnD,OAAO,MAAM,QAAQ,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAA;AAAA,EAAC;AAEtD,MAAI,WAAW,MAAM,MAAM,CAAC,SAAS,WAAW,KAAK,QAAQ,CAAC,EAAG,QAAO;AAExE,QAAM,SAAS,mBAAmB,YAAY,QAAQ;AACtD,SAAO;AAAA,IACL,GAAG;AAAA,IACH,OAAO,WAAW,MAAM;AAAA,MAAI,CAAC,SAC3B,WAAW,KAAK,QAAQ,IAAI,OAAO,EAAE,GAAG,MAAM,UAAU,OAAO,KAAK,MAAM,KAAK,EAAE,GAAG,GAAG,GAAG,IAAE;AAAA,IAAE;AAAA,EAChG;AAEJ;AAEA,MAAM,eAAe,CAAC,OAAmB,aAAsC;AAAA,EAC7E,OAAO,MAAM,MAAM,OAAO,CAAC,SAAS,CAAC,QAAQ,IAAI,KAAK,MAAM,CAAC;AAAA,EAC7D,OAAO,MAAM,MAAM,OAAO,CAAC,SAAS,CAAC,QAAQ,IAAI,KAAK,MAAM,KAAK,CAAC,QAAQ,IAA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AAM,MAAM;AACV,YAAM,EAAE,OAAO,MAAM,OAAA,IAAW,IAAA;AAChC,YAAM,YAAY,OAAO,CAAC;AAC1B,UAAI,CAAC,UAAW;AAChB,UAAI;AAAA,QACF,OAAO;AAAA,QACP,MAAM,CAAC,GAAG,MAAM,KAAK,EAAE,MAAM,CAAC,aAAa;AAAA,QAC3C,QAAQ,OAAO,MAAM,CAAC;AAAA,QACtB,iBAAiB,CAAA;AAAA,QACjB,iBAAiB,CAAA;AAAA,QACjB,SAAS;AAAA,MAAA,CACV;AAAA,IACH;AAAA,IAEA,aAAa,CAAC,iBAAiB;AAC7B,wBAAkB;AAAA,IACpB;AAAA,EAAA;AAEJ,CAAC;"}
1
+ {"version":3,"file":"flowEditorStore.js","sources":["../../../../src/components/UI/Flow/flowEditorStore.ts"],"sourcesContent":["import { createStore, type StoreApi } from 'zustand/vanilla';\n\nimport { generateUUID } from '@/helpers/utilityHelpers';\n\nimport { flowOutputsOf, type IFlowBlockRegistry } from './flowBlockRegistry';\nimport {\n canConnect,\n FLOW_LEVEL_GAP,\n FLOW_SIBLING_GAP,\n isFlowNodeRemovable,\n layoutFlowByLevels,\n reachableFrom,\n} from './flowGraph';\nimport type { IFlowEdge, IFlowGraph, IFlowNode, IFlowPosition, TFlowPortId } from './flowTypes';\n\nconst HISTORY_LIMIT = 50;\nconst PASTE_OFFSET = 32;\n/** Edits to the same field within this window share one undo step (typing a name is one change). */\nconst COALESCE_WINDOW_MS = 1000;\n\nexport interface IFlowEditorState {\n graph: IFlowGraph;\n selectedNodeIds: Array<string>;\n selectedEdgeIds: Array<string>;\n past: Array<IFlowGraph>;\n future: Array<IFlowGraph>;\n clipboard: Array<IFlowNode>;\n isDirty: boolean;\n\n replaceGraph: (graph: IFlowGraph, options?: { keepHistory?: boolean }) => void;\n markClean: () => void;\n /** Snapshot before a gesture that changes the graph in many small steps (a drag). */\n recordHistory: () => void;\n addNode: (type: string) => string | null;\n /** Adds a block right of `sourceNodeId` and wires `sourcePort` to it in one undo step. */\n addNodeFromPort: (type: string, sourceNodeId: string, sourcePort: TFlowPortId) => string | null;\n /**\n * Puts a block in the middle of an edge: the edge now ends at the new block, whose first output\n * leads to the old target. The old target and everything after it move one column right, so the\n * new block takes the place it left. One undo step.\n */\n insertNodeOnEdge: (type: string, edgeId: string) => string | null;\n updateNodeConfig: (nodeId: string, config: unknown) => void;\n updateNodeLabel: (nodeId: string, label: string) => void;\n moveNodes: (positions: Record<string, IFlowPosition>) => void;\n connect: (source: string, sourcePort: TFlowPortId, target: string) => boolean;\n removeSelected: () => void;\n duplicateSelected: () => void;\n copySelected: () => void;\n paste: () => void;\n setSelection: (selection: { nodeIds?: Array<string>; edgeIds?: Array<string> }) => void;\n undo: () => void;\n redo: () => void;\n /** The host may rebuild its registry (labels after a language switch); gestures always read the latest. */\n setRegistry: (registry: IFlowBlockRegistry) => void;\n}\n\nexport type TFlowEditorStore = StoreApi<IFlowEditorState>;\n\nconst isPosition = (position: unknown): position is IFlowPosition =>\n typeof (position as IFlowPosition | undefined)?.x === 'number' &&\n typeof (position as IFlowPosition | undefined)?.y === 'number';\n\n/** Coerces a stored graph; a block saved without a position is placed by the automatic layout. */\nconst normalizeGraph = (graph: IFlowGraph | null | undefined, registry: IFlowBlockRegistry): IFlowGraph => {\n const normalized: IFlowGraph = {\n nodes: Array.isArray(graph?.nodes) ? graph.nodes : [],\n edges: Array.isArray(graph?.edges) ? graph.edges : [],\n };\n if (normalized.nodes.every((node) => isPosition(node.position))) return normalized;\n\n const layout = layoutFlowByLevels(normalized, registry);\n return {\n ...normalized,\n nodes: normalized.nodes.map((node) =>\n isPosition(node.position) ? node : { ...node, position: layout[node.nodeId] ?? { x: 0, y: 0 } },\n ),\n };\n};\n\nconst withoutNodes = (graph: IFlowGraph, nodeIds: Set<string>): IFlowGraph => ({\n nodes: graph.nodes.filter((node) => !nodeIds.has(node.nodeId)),\n edges: graph.edges.filter((edge) => !nodeIds.has(edge.source) && !nodeIds.has(edge.target)),\n});\n\nconst isPositionTaken = (graph: IFlowGraph, position: IFlowPosition): boolean =>\n graph.nodes.some(\n (node) =>\n Math.abs(node.position.x - position.x) < FLOW_LEVEL_GAP &&\n Math.abs(node.position.y - position.y) < FLOW_SIBLING_GAP,\n );\n\n/** Right of the selected block (or the rightmost one), stepping down the column until the slot is free. */\nconst nextFreePosition = (graph: IFlowGraph, selectedNodeIds: Array<string>): IFlowPosition => {\n if (graph.nodes.length === 0) return { x: 0, y: 0 };\n const anchor =\n graph.nodes.find((node) => node.nodeId === selectedNodeIds[0]) ??\n graph.nodes.reduce((current, node) => (node.position.x > current.position.x ? node : current));\n let candidate = { x: anchor.position.x + FLOW_LEVEL_GAP, y: anchor.position.y };\n while (isPositionTaken(graph, candidate)) candidate = { x: candidate.x, y: candidate.y + FLOW_SIBLING_GAP };\n return candidate;\n};\n\n/**\n * One store per editor instance (two canvases on a page never share state). The graph\n * is the source of truth; the canvas only renders it and reports gestures back.\n */\nexport const createFlowEditorStore = (initialGraph: IFlowGraph, registry: IFlowBlockRegistry): TFlowEditorStore =>\n createStore<IFlowEditorState>()((set, get) => {\n let currentRegistry = registry;\n let lastCoalesce: { key: string; at: number } | null = null;\n\n const commit = (\n next: IFlowGraph,\n selection?: { nodeIds?: Array<string>; edgeIds?: Array<string> },\n coalesceKey?: string,\n ) => {\n const { graph, past } = get();\n const now = Date.now();\n const extendsLastStep =\n coalesceKey !== undefined && lastCoalesce?.key === coalesceKey && now - lastCoalesce.at < COALESCE_WINDOW_MS;\n lastCoalesce = coalesceKey === undefined ? null : { key: coalesceKey, at: now };\n set({\n graph: next,\n past: extendsLastStep ? past : [...past, graph].slice(-HISTORY_LIMIT),\n future: [],\n isDirty: true,\n ...(selection?.nodeIds ? { selectedNodeIds: selection.nodeIds } : {}),\n ...(selection?.edgeIds ? { selectedEdgeIds: selection.edgeIds } : {}),\n });\n };\n\n const cloneNodes = (nodes: Array<IFlowNode>, offset: number): Array<IFlowNode> => {\n const instancesByType = new Map<string, number>();\n get().graph.nodes.forEach((node) => instancesByType.set(node.type, (instancesByType.get(node.type) ?? 0) + 1));\n return nodes\n .filter((node) => {\n const definition = currentRegistry.get(node.type);\n if (!definition || definition.category === 'trigger') return false;\n const instances = instancesByType.get(node.type) ?? 0;\n if (definition.maxInstances !== undefined && instances >= definition.maxInstances) return false;\n instancesByType.set(node.type, instances + 1);\n return true;\n })\n .map((node) => ({\n ...node,\n nodeId: generateUUID(),\n config: structuredClone(node.config),\n position: { x: node.position.x + offset, y: node.position.y + offset },\n }));\n };\n\n return {\n graph: normalizeGraph(initialGraph, registry),\n selectedNodeIds: [],\n selectedEdgeIds: [],\n past: [],\n future: [],\n clipboard: [],\n isDirty: false,\n\n replaceGraph: (graph, options) => {\n set((state) => ({\n graph: normalizeGraph(graph, currentRegistry),\n past: options?.keepHistory ? [...state.past, state.graph].slice(-HISTORY_LIMIT) : [],\n future: [],\n selectedNodeIds: [],\n selectedEdgeIds: [],\n isDirty: Boolean(options?.keepHistory),\n }));\n },\n\n markClean: () => set({ isDirty: false }),\n\n recordHistory: () => {\n const { graph, past } = get();\n set({ past: [...past, graph].slice(-HISTORY_LIMIT), future: [] });\n },\n\n addNode: (type) => {\n const definition = currentRegistry.get(type);\n if (!definition) return null;\n\n const { graph, selectedNodeIds } = get();\n const instances = graph.nodes.filter((node) => node.type === type).length;\n if (definition.maxInstances !== undefined && instances >= definition.maxInstances) return null;\n\n const node: IFlowNode = {\n nodeId: generateUUID(),\n type,\n typeVersion: definition.typeVersion,\n config: definition.createDefaultConfig(),\n position: nextFreePosition(graph, selectedNodeIds),\n };\n commit({ ...graph, nodes: [...graph.nodes, node] }, { nodeIds: [node.nodeId], edgeIds: [] });\n return node.nodeId;\n },\n\n addNodeFromPort: (type, sourceNodeId, sourcePort) => {\n const definition = currentRegistry.get(type);\n const { graph } = get();\n const source = graph.nodes.find((node) => node.nodeId === sourceNodeId);\n if (!definition || !source) return null;\n\n const instances = graph.nodes.filter((node) => node.type === type).length;\n if (definition.maxInstances !== undefined && instances >= definition.maxInstances) return null;\n if (graph.edges.some((edge) => edge.source === sourceNodeId && edge.sourcePort === sourcePort)) return null;\n\n const outputs = flowOutputsOf(currentRegistry.get(source.type), source.config);\n if (!outputs.includes(sourcePort)) return null;\n const portIndex = outputs.indexOf(sourcePort);\n let position = {\n x: source.position.x + FLOW_LEVEL_GAP,\n y: source.position.y + (portIndex - (outputs.length - 1) / 2) * FLOW_SIBLING_GAP,\n };\n while (isPositionTaken(graph, position)) position = { x: position.x, y: position.y + FLOW_SIBLING_GAP };\n\n const node: IFlowNode = {\n nodeId: generateUUID(),\n type,\n typeVersion: definition.typeVersion,\n config: definition.createDefaultConfig(),\n position,\n };\n const nodes = [...graph.nodes, node];\n const wires = canConnect({ ...graph, nodes }, currentRegistry, {\n source: sourceNodeId,\n sourcePort,\n target: node.nodeId,\n });\n const edges = wires\n ? [...graph.edges, { edgeId: generateUUID(), source: sourceNodeId, sourcePort, target: node.nodeId }]\n : graph.edges;\n commit({ nodes, edges }, { nodeIds: [node.nodeId], edgeIds: [] });\n return node.nodeId;\n },\n\n insertNodeOnEdge: (type, edgeId) => {\n const definition = currentRegistry.get(type);\n const { graph } = get();\n const edge = graph.edges.find((candidate) => candidate.edgeId === edgeId);\n const target = edge ? graph.nodes.find((node) => node.nodeId === edge.target) : undefined;\n const config = definition?.createDefaultConfig();\n const continuationPort = definition ? flowOutputsOf(definition, config)[0] : undefined;\n if (!definition || !edge || !target || !continuationPort || definition.category === 'trigger') return null;\n\n const instances = graph.nodes.filter((node) => node.type === type).length;\n if (definition.maxInstances !== undefined && instances >= definition.maxInstances) return null;\n\n const shifted = reachableFrom(graph, target.nodeId);\n const node: IFlowNode = {\n nodeId: generateUUID(),\n type,\n typeVersion: definition.typeVersion,\n config,\n position: { ...target.position },\n };\n const nodes = [\n ...graph.nodes.map((current) =>\n shifted.has(current.nodeId)\n ? { ...current, position: { x: current.position.x + FLOW_LEVEL_GAP, y: current.position.y } }\n : current,\n ),\n node,\n ];\n const withoutEdge = graph.edges.filter((current) => current.edgeId !== edgeId);\n const incoming: IFlowEdge = { ...edge, target: node.nodeId };\n const outgoing: IFlowEdge = {\n edgeId: generateUUID(),\n source: node.nodeId,\n sourcePort: continuationPort,\n target: target.nodeId,\n };\n\n const wiresIn = canConnect({ nodes, edges: withoutEdge }, currentRegistry, incoming);\n const wiresOut = canConnect({ nodes, edges: [...withoutEdge, incoming] }, currentRegistry, outgoing);\n if (!wiresIn || !wiresOut) return null;\n\n commit({ nodes, edges: [...withoutEdge, incoming, outgoing] }, { nodeIds: [node.nodeId], edgeIds: [] });\n return node.nodeId;\n },\n\n updateNodeConfig: (nodeId, config) => {\n const { graph } = get();\n const node = graph.nodes.find((candidate) => candidate.nodeId === nodeId);\n const outputs = node ? flowOutputsOf(currentRegistry.get(node.type), config) : [];\n commit(\n {\n nodes: graph.nodes.map((current) => (current.nodeId === nodeId ? { ...current, config } : current)),\n edges: graph.edges.filter((edge) => edge.source !== nodeId || outputs.includes(edge.sourcePort)),\n },\n undefined,\n `config:${nodeId}`,\n );\n },\n\n updateNodeLabel: (nodeId, label) => {\n const { graph } = get();\n const hasText = label.trim().length > 0;\n commit(\n {\n ...graph,\n nodes: graph.nodes.map((node) =>\n node.nodeId === nodeId ? { ...node, label: hasText ? label : undefined } : node,\n ),\n },\n undefined,\n `label:${nodeId}`,\n );\n },\n\n moveNodes: (positions) => {\n const { graph } = get();\n set({\n graph: {\n ...graph,\n nodes: graph.nodes.map((node) =>\n positions[node.nodeId] ? { ...node, position: positions[node.nodeId] } : node,\n ),\n },\n isDirty: true,\n });\n },\n\n connect: (source, sourcePort, target) => {\n const { graph } = get();\n if (!canConnect(graph, currentRegistry, { source, sourcePort, target })) return false;\n const edge: IFlowEdge = { edgeId: generateUUID(), source, sourcePort, target };\n commit({ ...graph, edges: [...graph.edges, edge] });\n return true;\n },\n\n removeSelected: () => {\n const { graph, selectedNodeIds, selectedEdgeIds } = get();\n const removableNodeIds = graph.nodes\n .filter((node) => selectedNodeIds.includes(node.nodeId) && isFlowNodeRemovable(node, currentRegistry))\n .map((node) => node.nodeId);\n if (removableNodeIds.length === 0 && selectedEdgeIds.length === 0) return;\n const removedEdges = new Set(selectedEdgeIds);\n const next = withoutNodes(\n { ...graph, edges: graph.edges.filter((edge) => !removedEdges.has(edge.edgeId)) },\n new Set(removableNodeIds),\n );\n commit(next, { nodeIds: [], edgeIds: [] });\n },\n\n duplicateSelected: () => {\n const { graph, selectedNodeIds } = get();\n const selected = graph.nodes.filter((node) => selectedNodeIds.includes(node.nodeId));\n const copies = cloneNodes(selected, PASTE_OFFSET);\n if (copies.length === 0) return;\n commit(\n { ...graph, nodes: [...graph.nodes, ...copies] },\n { nodeIds: copies.map((node) => node.nodeId), edgeIds: [] },\n );\n },\n\n copySelected: () => {\n const { graph, selectedNodeIds } = get();\n set({ clipboard: graph.nodes.filter((node) => selectedNodeIds.includes(node.nodeId)) });\n },\n\n paste: () => {\n const { graph, clipboard } = get();\n const copies = cloneNodes(clipboard, PASTE_OFFSET);\n if (copies.length === 0) return;\n commit(\n { ...graph, nodes: [...graph.nodes, ...copies] },\n { nodeIds: copies.map((node) => node.nodeId), edgeIds: [] },\n );\n set({ clipboard: copies });\n },\n\n setSelection: ({ nodeIds, edgeIds }) => {\n set((state) => ({\n selectedNodeIds: nodeIds ?? state.selectedNodeIds,\n selectedEdgeIds: edgeIds ?? state.selectedEdgeIds,\n }));\n },\n\n undo: () => {\n const { graph, past, future } = get();\n const previous = past[past.length - 1];\n if (!previous) return;\n set({\n graph: previous,\n past: past.slice(0, -1),\n future: [graph, ...future].slice(0, HISTORY_LIMIT),\n selectedNodeIds: [],\n selectedEdgeIds: [],\n isDirty: true,\n });\n },\n\n redo: () => {\n const { graph, past, future } = get();\n const following = future[0];\n if (!following) return;\n set({\n graph: following,\n past: [...past, graph].slice(-HISTORY_LIMIT),\n future: future.slice(1),\n selectedNodeIds: [],\n selectedEdgeIds: [],\n isDirty: true,\n });\n },\n\n setRegistry: (nextRegistry) =>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AC,UAAW;AAChB,UAAI;AAAA,QACF,OAAO;AAAA,QACP,MAAM,CAAC,GAAG,MAAM,KAAK,EAAE,MAAM,CAAC,aAAa;AAAA,QAC3C,QAAQ,OAAO,MAAM,CAAC;AAAA,QACtB,iBAAiB,CAAA;AAAA,QACjB,iBAAiB,CAAA;AAAA,QACjB,SAAS;AAAA,MAAA,CACV;AAAA,IACH;AAAA,IAEA,aAAa,CAAC,iBAAiB;AAC7B,wBAAkB;AAAA,IACpB;AAAA,EAAA;AAEJ,CAAC;"}
@@ -4,6 +4,7 @@ import { IFlowGraph, IFlowIssue, IFlowNode, IFlowPosition, TFlowPortId } from '.
4
4
  export declare const FLOW_LEVEL_GAP = 336;
5
5
  export declare const FLOW_SIBLING_GAP = 176;
6
6
  export declare const triggerNodesOf: (graph: IFlowGraph, registry: IFlowBlockRegistry) => Array<IFlowNode>;
7
+ export declare const isFlowNodeRemovable: (node: IFlowNode, registry: IFlowBlockRegistry) => boolean;
7
8
  /** Node ids reachable from `startNodeId` following edges, the start included. */
8
9
  export declare const reachableFrom: (graph: IFlowGraph, startNodeId: string) => Set<string>;
9
10
  /** The node ids of the first cycle found, in order, or null when the graph has none. */
@@ -11,6 +11,7 @@ const outgoingByNode = (graph) => {
11
11
  return outgoing;
12
12
  };
13
13
  const triggerNodesOf = (graph, registry) => nodesOf(graph).filter((node) => registry.get(node.type)?.category === "trigger");
14
+ const isFlowNodeRemovable = (node, registry) => registry.get(node.type)?.removable !== false;
14
15
  const reachableFrom = (graph, startNodeId) => {
15
16
  const outgoing = outgoingByNode(graph);
16
17
  const visited = /* @__PURE__ */ new Set();
@@ -147,6 +148,7 @@ export {
147
148
  canConnect,
148
149
  findCycle,
149
150
  hasBlockingIssues,
151
+ isFlowNodeRemovable,
150
152
  layoutFlowByLevels,
151
153
  reachableFrom,
152
154
  triggerNodesOf,
@@ -1 +1 @@
1
- {"version":3,"file":"flowGraph.js","sources":["../../../../src/components/UI/Flow/flowGraph.ts"],"sourcesContent":["import { flowOutputsOf, type IFlowBlockRegistry } from './flowBlockRegistry';\nimport type { IFlowEdge, IFlowGraph, IFlowIssue, IFlowNode, IFlowPosition, TFlowPortId } from './flowTypes';\n\n/** The flow reads left to right: one level per column, siblings stacked in the column. */\nexport const FLOW_LEVEL_GAP = 336;\nexport const FLOW_SIBLING_GAP = 176;\n\nconst nodesOf = (graph: IFlowGraph): Array<IFlowNode> => (Array.isArray(graph?.nodes) ? graph.nodes : []);\nconst edgesOf = (graph: IFlowGraph): Array<IFlowEdge> => (Array.isArray(graph?.edges) ? graph.edges : []);\n\nconst outgoingByNode = (graph: IFlowGraph): Map<string, Array<IFlowEdge>> => {\n const outgoing = new Map<string, Array<IFlowEdge>>();\n for (const edge of edgesOf(graph)) {\n outgoing.set(edge.source, [...(outgoing.get(edge.source) ?? []), edge]);\n }\n return outgoing;\n};\n\nexport const triggerNodesOf = (graph: IFlowGraph, registry: IFlowBlockRegistry): Array<IFlowNode> =>\n nodesOf(graph).filter((node) => registry.get(node.type)?.category === 'trigger');\n\n/** Node ids reachable from `startNodeId` following edges, the start included. */\nexport const reachableFrom = (graph: IFlowGraph, startNodeId: string): Set<string> => {\n const outgoing = outgoingByNode(graph);\n const visited = new Set<string>();\n const pending = [startNodeId];\n while (pending.length > 0) {\n const nodeId = pending.pop();\n if (nodeId === undefined || visited.has(nodeId)) continue;\n visited.add(nodeId);\n for (const edge of outgoing.get(nodeId) ?? []) pending.push(edge.target);\n }\n return visited;\n};\n\n/** The node ids of the first cycle found, in order, or null when the graph has none. */\nexport const findCycle = (graph: IFlowGraph): Array<string> | null => {\n const outgoing = outgoingByNode(graph);\n const state = new Map<string, 'visiting' | 'done'>();\n const path: Array<string> = [];\n\n const visit = (nodeId: string): Array<string> | null => {\n state.set(nodeId, 'visiting');\n path.push(nodeId);\n for (const edge of outgoing.get(nodeId) ?? []) {\n const targetState = state.get(edge.target);\n if (targetState === 'visiting') return path.slice(path.indexOf(edge.target));\n if (targetState === undefined) {\n const cycle = visit(edge.target);\n if (cycle) return cycle;\n }\n }\n path.pop();\n state.set(nodeId, 'done');\n return null;\n };\n\n for (const node of nodesOf(graph)) {\n if (state.has(node.nodeId)) continue;\n const cycle = visit(node.nodeId);\n if (cycle) return cycle;\n }\n return null;\n};\n\nexport interface IFlowConnectionCandidate {\n source: string;\n sourcePort: TFlowPortId;\n target: string;\n}\n\n/**\n * The V0 shape is a tree with no fan-out: one input per block, one edge per output\n * port, no edge into a trigger and no cycle. Keeping this rule here lets the canvas\n * refuse a bad connection while it is being drawn, not only when publishing.\n */\nexport const canConnect = (\n graph: IFlowGraph,\n registry: IFlowBlockRegistry,\n candidate: IFlowConnectionCandidate,\n): boolean => {\n const { source, sourcePort, target } = candidate;\n if (!source || !target || source === target) return false;\n\n const nodes = nodesOf(graph);\n const sourceNode = nodes.find((node) => node.nodeId === source);\n const targetNode = nodes.find((node) => node.nodeId === target);\n if (!sourceNode || !targetNode) return false;\n\n const sourceDefinition = registry.get(sourceNode.type);\n const targetDefinition = registry.get(targetNode.type);\n if (!flowOutputsOf(sourceDefinition, sourceNode.config).includes(sourcePort)) return false;\n if (!targetDefinition || targetDefinition.category === 'trigger') return false;\n\n const edges = edgesOf(graph);\n if (edges.some((edge) => edge.source === source && edge.sourcePort === sourcePort)) return false;\n if (edges.some((edge) => edge.target === target)) return false;\n\n return !reachableFrom(graph, target).has(source);\n};\n\n/** The structural rules of the V0 shape, plus each block's own `validate`. */\nexport const validateFlowGraph = (graph: IFlowGraph, registry: IFlowBlockRegistry): Array<IFlowIssue> => {\n const issues: Array<IFlowIssue> = [];\n const nodes = nodesOf(graph);\n const edges = edgesOf(graph);\n\n for (const node of nodes) {\n const definition = registry.get(node.type);\n if (!definition) {\n issues.push({ code: 'unknownBlock', severity: 'error', nodeId: node.nodeId });\n continue;\n }\n for (const blockIssue of definition.validate(node.config) ?? []) {\n issues.push({ ...blockIssue, nodeId: node.nodeId });\n }\n }\n\n const triggers = triggerNodesOf(graph, registry);\n if (triggers.length === 0) issues.push({ code: 'missingTrigger', severity: 'error' });\n triggers.slice(1).forEach((trigger) => {\n issues.push({ code: 'multipleTriggers', severity: 'error', nodeId: trigger.nodeId });\n });\n\n const firstTrigger = triggers[0];\n if (firstTrigger) {\n const reachable = reachableFrom(graph, firstTrigger.nodeId);\n nodes\n .filter((node) => !reachable.has(node.nodeId) && registry.get(node.type)?.category !== 'trigger')\n .forEach((node) => issues.push({ code: 'unreachableNode', severity: 'error', nodeId: node.nodeId }));\n }\n\n const inputCount = new Map<string, number>();\n const portCount = new Map<string, number>();\n for (const edge of edges) {\n inputCount.set(edge.target, (inputCount.get(edge.target) ?? 0) + 1);\n const portKey = `${edge.source}|${edge.sourcePort}`;\n portCount.set(portKey, (portCount.get(portKey) ?? 0) + 1);\n }\n inputCount.forEach((count, nodeId) => {\n if (count > 1) issues.push({ code: 'multipleInputs', severity: 'error', nodeId });\n });\n edges\n .filter((edge) => (portCount.get(`${edge.source}|${edge.sourcePort}`) ?? 0) > 1)\n .forEach((edge) =>\n issues.push({ code: 'portFanOut', severity: 'error', edgeId: edge.edgeId, nodeId: edge.source }),\n );\n\n const cycle = findCycle(graph);\n if (cycle) cycle.forEach((nodeId) => issues.push({ code: 'cycle', severity: 'error', nodeId }));\n\n nodes\n .filter((node) => flowOutputsOf(registry.get(node.type), node.config).includes('true'))\n .filter((node) => !edges.some((edge) => edge.source === node.nodeId && edge.sourcePort === 'true'))\n .forEach((node) => issues.push({ code: 'missingTrueBranch', severity: 'warning', nodeId: node.nodeId }));\n\n return issues;\n};\n\nexport const hasBlockingIssues = (issues: Array<IFlowIssue>): boolean =>\n (issues ?? []).some((issue) => issue.severity === 'error');\n\n/**\n * Lays the tree out by levels from the trigger: each level one column to the right,\n * siblings stacked in the column. Used only for a flow with no saved positions (one born from a rule) or when\n * the user asks for it; a position the user arranged is data and is never overwritten\n * implicitly.\n */\nexport const layoutFlowByLevels = (graph: IFlowGraph, registry: IFlowBlockRegistry): Record<string, IFlowPosition> => {\n const nodes = nodesOf(graph);\n const outgoing = outgoingByNode(graph);\n const levelOf = new Map<string, number>();\n const roots = triggerNodesOf(graph, registry);\n const queue: Array<string> = roots.map((root) => root.nodeId);\n roots.forEach((root) => levelOf.set(root.nodeId, 0));\n\n while (queue.length > 0) {\n const nodeId = queue.shift();\n if (nodeId === undefined) continue;\n const level = levelOf.get(nodeId) ?? 0;\n for (const edge of outgoing.get(nodeId) ?? []) {\n if (levelOf.has(edge.target)) continue;\n levelOf.set(edge.target, level + 1);\n queue.push(edge.target);\n }\n }\n\n const deepestLevel = Math.max(-1, ...Array.from(levelOf.values()));\n nodes.filter((node) => !levelOf.has(node.nodeId)).forEach((node) => levelOf.set(node.nodeId, deepestLevel + 1));\n\n const nodesByLevel = new Map<number, Array<string>>();\n nodes.forEach((node) => {\n const level = levelOf.get(node.nodeId) ?? 0;\n nodesByLevel.set(level, [...(nodesByLevel.get(level) ?? []), node.nodeId]);\n });\n\n const positions: Record<string, IFlowPosition> = {};\n nodesByLevel.forEach((nodeIds, level) => {\n const columnHeight = (nodeIds.length - 1) * FLOW_SIBLING_GAP;\n nodeIds.forEach((nodeId, index) => {\n positions[nodeId] = { x: level * FLOW_LEVEL_GAP, y: index * FLOW_SIBLING_GAP - columnHeight / 2 };\n });\n });\n return positions;\n};\n"],"names":[],"mappings":";AAIO,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AAEhC,MAAM,UAAU,CAAC,UAAyC,MAAM,QAAQ,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAA;AACtG,MAAM,UAAU,CAAC,UAAyC,MAAM,QAAQ,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAA;AAEtG,MAAM,iBAAiB,CAAC,UAAqD;AAC3E,QAAM,+BAAe,IAAA;AACrB,aAAW,QAAQ,QAAQ,KAAK,GAAG;AACjC,aAAS,IAAI,KAAK,QAAQ,CAAC,GAAI,SAAS,IAAI,KAAK,MAAM,KAAK,CAAA,GAAK,IAAI,CAAC;AAAA,EACxE;AACA,SAAO;A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CAAQ,CAAC;AACjE,QAAM,OAAO,CAAC,SAAS,CAAC,QAAQ,IAAI,KAAK,MAAM,CAAC,EAAE,QAAQ,CAAC,SAAS,QAAQ,IAAI,KAAK,QAAQ,eAAe,CAAC,CAAC;AAE9G,QAAM,mCAAmB,IAAA;AACzB,QAAM,QAAQ,CAAC,SAAS;AACtB,UAAM,QAAQ,QAAQ,IAAI,KAAK,MAAM,KAAK;AAC1C,iBAAa,IAAI,OAAO,CAAC,GAAI,aAAa,IAAI,KAAK,KAAK,CAAA,GAAK,KAAK,MAAM,CAAC;AAAA,EAC3E,CAAC;AAED,QAAM,YAA2C,CAAA;AACjD,eAAa,QAAQ,CAAC,SAAS,UAAU;AACvC,UAAM,gBAAgB,QAAQ,SAAS,KAAK;AAC5C,YAAQ,QAAQ,CAAC,QAAQ,UAAU;AACjC,gBAAU,MAAM,IAAI,EAAE,GAAG,QAAQ,gBAAgB,GAAG,QAAQ,mBAAmB,eAAe,EAAA;AAAA,IAChG,CAAC;AAAA,EACH,CAAC;AACD,SAAO;AACT;"}
1
+ {"version":3,"file":"flowGraph.js","sources":["../../../../src/components/UI/Flow/flowGraph.ts"],"sourcesContent":["import { flowOutputsOf, type IFlowBlockRegistry } from './flowBlockRegistry';\nimport type { IFlowEdge, IFlowGraph, IFlowIssue, IFlowNode, IFlowPosition, TFlowPortId } from './flowTypes';\n\n/** The flow reads left to right: one level per column, siblings stacked in the column. */\nexport const FLOW_LEVEL_GAP = 336;\nexport const FLOW_SIBLING_GAP = 176;\n\nconst nodesOf = (graph: IFlowGraph): Array<IFlowNode> => (Array.isArray(graph?.nodes) ? graph.nodes : []);\nconst edgesOf = (graph: IFlowGraph): Array<IFlowEdge> => (Array.isArray(graph?.edges) ? graph.edges : []);\n\nconst outgoingByNode = (graph: IFlowGraph): Map<string, Array<IFlowEdge>> => {\n const outgoing = new Map<string, Array<IFlowEdge>>();\n for (const edge of edgesOf(graph)) {\n outgoing.set(edge.source, [...(outgoing.get(edge.source) ?? []), edge]);\n }\n return outgoing;\n};\n\nexport const triggerNodesOf = (graph: IFlowGraph, registry: IFlowBlockRegistry): Array<IFlowNode> =>\n nodesOf(graph).filter((node) => registry.get(node.type)?.category === 'trigger');\n\nexport const isFlowNodeRemovable = (node: IFlowNode, registry: IFlowBlockRegistry): boolean =>\n registry.get(node.type)?.removable !== false;\n\n/** Node ids reachable from `startNodeId` following edges, the start included. */\nexport const reachableFrom = (graph: IFlowGraph, startNodeId: string): Set<string> => {\n const outgoing = outgoingByNode(graph);\n const visited = new Set<string>();\n const pending = [startNodeId];\n while (pending.length > 0) {\n const nodeId = pending.pop();\n if (nodeId === undefined || visited.has(nodeId)) continue;\n visited.add(nodeId);\n for (const edge of outgoing.get(nodeId) ?? []) pending.push(edge.target);\n }\n return visited;\n};\n\n/** The node ids of the first cycle found, in order, or null when the graph has none. */\nexport const findCycle = (graph: IFlowGraph): Array<string> | null => {\n const outgoing = outgoingByNode(graph);\n const state = new Map<string, 'visiting' | 'done'>();\n const path: Array<string> = [];\n\n const visit = (nodeId: string): Array<string> | null => {\n state.set(nodeId, 'visiting');\n path.push(nodeId);\n for (const edge of outgoing.get(nodeId) ?? []) {\n const targetState = state.get(edge.target);\n if (targetState === 'visiting') return path.slice(path.indexOf(edge.target));\n if (targetState === undefined) {\n const cycle = visit(edge.target);\n if (cycle) return cycle;\n }\n }\n path.pop();\n state.set(nodeId, 'done');\n return null;\n };\n\n for (const node of nodesOf(graph)) {\n if (state.has(node.nodeId)) continue;\n const cycle = visit(node.nodeId);\n if (cycle) return cycle;\n }\n return null;\n};\n\nexport interface IFlowConnectionCandidate {\n source: string;\n sourcePort: TFlowPortId;\n target: string;\n}\n\n/**\n * The V0 shape is a tree with no fan-out: one input per block, one edge per output\n * port, no edge into a trigger and no cycle. Keeping this rule here lets the canvas\n * refuse a bad connection while it is being drawn, not only when publishing.\n */\nexport const canConnect = (\n graph: IFlowGraph,\n registry: IFlowBlockRegistry,\n candidate: IFlowConnectionCandidate,\n): boolean => {\n const { source, sourcePort, target } = candidate;\n if (!source || !target || source === target) return false;\n\n const nodes = nodesOf(graph);\n const sourceNode = nodes.find((node) => node.nodeId === source);\n const targetNode = nodes.find((node) => node.nodeId === target);\n if (!sourceNode || !targetNode) return false;\n\n const sourceDefinition = registry.get(sourceNode.type);\n const targetDefinition = registry.get(targetNode.type);\n if (!flowOutputsOf(sourceDefinition, sourceNode.config).includes(sourcePort)) return false;\n if (!targetDefinition || targetDefinition.category === 'trigger') return false;\n\n const edges = edgesOf(graph);\n if (edges.some((edge) => edge.source === source && edge.sourcePort === sourcePort)) return false;\n if (edges.some((edge) => edge.target === target)) return false;\n\n return !reachableFrom(graph, target).has(source);\n};\n\n/** The structural rules of the V0 shape, plus each block's own `validate`. */\nexport const validateFlowGraph = (graph: IFlowGraph, registry: IFlowBlockRegistry): Array<IFlowIssue> => {\n const issues: Array<IFlowIssue> = [];\n const nodes = nodesOf(graph);\n const edges = edgesOf(graph);\n\n for (const node of nodes) {\n const definition = registry.get(node.type);\n if (!definition) {\n issues.push({ code: 'unknownBlock', severity: 'error', nodeId: node.nodeId });\n continue;\n }\n for (const blockIssue of definition.validate(node.config) ?? []) {\n issues.push({ ...blockIssue, nodeId: node.nodeId });\n }\n }\n\n const triggers = triggerNodesOf(graph, registry);\n if (triggers.length === 0) issues.push({ code: 'missingTrigger', severity: 'error' });\n triggers.slice(1).forEach((trigger) => {\n issues.push({ code: 'multipleTriggers', severity: 'error', nodeId: trigger.nodeId });\n });\n\n const firstTrigger = triggers[0];\n if (firstTrigger) {\n const reachable = reachableFrom(graph, firstTrigger.nodeId);\n nodes\n .filter((node) => !reachable.has(node.nodeId) && registry.get(node.type)?.category !== 'trigger')\n .forEach((node) => issues.push({ code: 'unreachableNode', severity: 'error', nodeId: node.nodeId }));\n }\n\n const inputCount = new Map<string, number>();\n const portCount = new Map<string, number>();\n for (const edge of edges) {\n inputCount.set(edge.target, (inputCount.get(edge.target) ?? 0) + 1);\n const portKey = `${edge.source}|${edge.sourcePort}`;\n portCount.set(portKey, (portCount.get(portKey) ?? 0) + 1);\n }\n inputCount.forEach((count, nodeId) => {\n if (count > 1) issues.push({ code: 'multipleInputs', severity: 'error', nodeId });\n });\n edges\n .filter((edge) => (portCount.get(`${edge.source}|${edge.sourcePort}`) ?? 0) > 1)\n .forEach((edge) =>\n issues.push({ code: 'portFanOut', severity: 'error', edgeId: edge.edgeId, nodeId: edge.source }),\n );\n\n const cycle = findCycle(graph);\n if (cycle) cycle.forEach((nodeId) => issues.push({ code: 'cycle', severity: 'error', nodeId }));\n\n nodes\n .filter((node) => flowOutputsOf(registry.get(node.type), node.config).includes('true'))\n .filter((node) => !edges.some((edge) => edge.source === node.nodeId && edge.sourcePort === 'true'))\n .forEach((node) => issues.push({ code: 'missingTrueBranch', severity: 'warning', nodeId: node.nodeId }));\n\n return issues;\n};\n\nexport const hasBlockingIssues = (issues: Array<IFlowIssue>): boolean =>\n (issues ?? []).some((issue) => issue.severity === 'error');\n\n/**\n * Lays the tree out by levels from the trigger: each level one column to the right,\n * siblings stacked in the column. Used only for a flow with no saved positions (one born from a rule) or when\n * the user asks for it; a position the user arranged is data and is never overwritten\n * implicitly.\n */\nexport const layoutFlowByLevels = (graph: IFlowGraph, registry: IFlowBlockRegistry): Record<string, IFlowPosition> => {\n const nodes = nodesOf(graph);\n const outgoing = outgoingByNode(graph);\n const levelOf = new Map<string, number>();\n const roots = triggerNodesOf(graph, registry);\n const queue: Array<string> = roots.map((root) => root.nodeId);\n roots.forEach((root) => levelOf.set(root.nodeId, 0));\n\n while (queue.length > 0) {\n const nodeId = queue.shift();\n if (nodeId === undefined) continue;\n const level = levelOf.get(nodeId) ?? 0;\n for (const edge of outgoing.get(nodeId) ?? []) {\n if (levelOf.has(edge.target)) continue;\n levelOf.set(edge.target, level + 1);\n queue.push(edge.target);\n }\n }\n\n const deepestLevel = Math.max(-1, ...Array.from(levelOf.values()));\n nodes.filter((node) => !levelOf.has(node.nodeId)).forEach((node) => levelOf.set(node.nodeId, deepestLevel + 1));\n\n const nodesByLevel = new Map<number, Array<string>>();\n nodes.forEach((node) => {\n const level = levelOf.get(node.nodeId) ?? 0;\n nodesByLevel.set(level, [...(nodesByLevel.get(level) ?? []), node.nodeId]);\n });\n\n const positions: Record<string, IFlowPosition> = {};\n nodesByLevel.forEach((nodeIds, level) => {\n const columnHeight = (nodeIds.length - 1) * FLOW_SIBLING_GAP;\n nodeIds.forEach((nodeId, index) => {\n positions[nodeId] = { x: level * FLOW_LEVEL_GAP, y: index * FLOW_SIBLING_GAP - columnHeight / 2 };\n });\n });\n return positions;\n};\n"],"names":[],"mappings":";AAIO,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AAEhC,MAAM,UAAU,CAAC,UAAyC,MAAM,QAAQ,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAA;AACtG,MAAM,UAAU,CAAC,UAAyC,MAAM,QAAQ,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAA;AAEtG,MAAM,iBAAiB,CAAC,UAAqD;AAC3E,QAAM,+BAAe,IAAA;AACrB,aAAW,QAAQ,QAAQ,KAAK,GAAG;AACjC,aAAS,IAAI,KAAK,QAAQ,CAAC,GAAI,SAAS,IAAI,KAAK,MAAM,KAAK,CAAA,GAAK,IAAI,CAAC;AAAA,EACxE;AACA,SAAO;AACT;AAEO,MAAM,iBAAiB,CAAC,OAAmB,aAChD,QAAQ,KAAK,EAAE,OAAO,CAAC,SAAS,SAAS,IAAI,KAAK,IAAI,GAAG,aAAa,SAAS;AAE1E,MAAM,sBAAsB,CAAC,MAAiB,aACnD,SAAS,IAAI,KAAK,IAAI,GAAG,cAAc;AAGlC,MAAM,gBAAgB,CAAC,OAAmB,gBAAqC;AACpF,QAAM,WAAW,eAAe,KAAK;AACrC,QAAM,8BAAc,IAAA;AACpB,QAAM,UAAU,CAAC,WAAW;AAC5B,SAAO,QAAQ,SAAS,GAAG;AACzB,UAAM,SAAS,QAAQ,IAAA;AACvB,QAAI,WAAW,UAAa,QAAQ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,CAAC;AAAA,EAC3E,CAAC;AAED,QAAM,YAA2C,CAAA;AACjD,eAAa,QAAQ,CAAC,SAAS,UAAU;AACvC,UAAM,gBAAgB,QAAQ,SAAS,KAAK;AAC5C,YAAQ,QAAQ,CAAC,QAAQ,UAAU;AACjC,gBAAU,MAAM,IAAI,EAAE,GAAG,QAAQ,gBAAgB,GAAG,QAAQ,mBAAmB,eAAe,EAAA;AAAA,IAChG,CAAC;AAAA,EACH,CAAC;AACD,SAAO;AACT;"}
@@ -61,6 +61,8 @@ export interface IFlowBlockDefinition<TConfig = unknown> {
61
61
  resolveOutputs?: (config: TConfig) => Array<TFlowPortId>;
62
62
  /** How many of this block a flow may hold; omit for no limit. */
63
63
  maxInstances?: number;
64
+ /** `false` keeps the block on the canvas: Delete and the inspector skip it. Defaults to `true`. */
65
+ removable?: boolean;
64
66
  createDefaultConfig: () => TConfig;
65
67
  ConfigPanel: ComponentType<IFlowBlockConfigPanelProps<TConfig>>;
66
68
  /** When one block stands for several kinds (chosen inside it), the icon and name of the chosen kind. */
@@ -0,0 +1,25 @@
1
+ export interface IFlowViewport {
2
+ x: number;
3
+ y: number;
4
+ zoom: number;
5
+ }
6
+ export interface IFlowRect {
7
+ x: number;
8
+ y: number;
9
+ width: number;
10
+ height: number;
11
+ }
12
+ export interface IFlowSize {
13
+ width: number;
14
+ height: number;
15
+ }
16
+ /** Breathing room between a revealed block and the edge of the canvas, in screen pixels. */
17
+ export declare const FLOW_REVEAL_PADDING = 32;
18
+ /**
19
+ * The smallest pan that brings `rect` (flow coordinates) fully inside a canvas of `canvasSize`
20
+ * (screen pixels), keeping the zoom. Returns null when the rect is already fully visible, so a
21
+ * block on screen never moves the view. A rect larger than the canvas is aligned to its top-left.
22
+ */
23
+ export declare const viewportToReveal: (viewport: IFlowViewport, rect: IFlowRect, canvasSize: IFlowSize, padding?: number) => IFlowViewport | null;
24
+ /** The box around several rects; null for none. */
25
+ export declare const boundsOfRects: (rects: Array<IFlowRect>) => IFlowRect | null;
@@ -0,0 +1,31 @@
1
+ const FLOW_REVEAL_PADDING = 32;
2
+ const shiftOnAxis = (start, end, min, max) => {
3
+ if (start < min) return min - start;
4
+ if (end > max) return Math.max(max - end, min - start);
5
+ return 0;
6
+ };
7
+ const viewportToReveal = (viewport, rect, canvasSize, padding = FLOW_REVEAL_PADDING) => {
8
+ if (canvasSize.width <= 0 || canvasSize.height <= 0) return null;
9
+ const left = viewport.x + rect.x * viewport.zoom;
10
+ const top = viewport.y + rect.y * viewport.zoom;
11
+ const right = left + rect.width * viewport.zoom;
12
+ const bottom = top + rect.height * viewport.zoom;
13
+ const deltaX = shiftOnAxis(left, right, padding, canvasSize.width - padding);
14
+ const deltaY = shiftOnAxis(top, bottom, padding, canvasSize.height - padding);
15
+ if (deltaX === 0 && deltaY === 0) return null;
16
+ return { x: viewport.x + deltaX, y: viewport.y + deltaY, zoom: viewport.zoom };
17
+ };
18
+ const boundsOfRects = (rects) => {
19
+ if (rects.length === 0) return null;
20
+ const minX = Math.min(...rects.map((rect) => rect.x));
21
+ const minY = Math.min(...rects.map((rect) => rect.y));
22
+ const maxX = Math.max(...rects.map((rect) => rect.x + rect.width));
23
+ const maxY = Math.max(...rects.map((rect) => rect.y + rect.height));
24
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
25
+ };
26
+ export {
27
+ FLOW_REVEAL_PADDING,
28
+ boundsOfRects,
29
+ viewportToReveal
30
+ };
31
+ //# sourceMappingURL=flowViewport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flowViewport.js","sources":["../../../../src/components/UI/Flow/flowViewport.ts"],"sourcesContent":["export interface IFlowViewport {\n x: number;\n y: number;\n zoom: number;\n}\n\nexport interface IFlowRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface IFlowSize {\n width: number;\n height: number;\n}\n\n/** Breathing room between a revealed block and the edge of the canvas, in screen pixels. */\nexport const FLOW_REVEAL_PADDING = 32;\n\nconst shiftOnAxis = (start: number, end: number, min: number, max: number): number => {\n if (start < min) return min - start;\n if (end > max) return Math.max(max - end, min - start);\n return 0;\n};\n\n/**\n * The smallest pan that brings `rect` (flow coordinates) fully inside a canvas of `canvasSize`\n * (screen pixels), keeping the zoom. Returns null when the rect is already fully visible, so a\n * block on screen never moves the view. A rect larger than the canvas is aligned to its top-left.\n */\nexport const viewportToReveal = (\n viewport: IFlowViewport,\n rect: IFlowRect,\n canvasSize: IFlowSize,\n padding: number = FLOW_REVEAL_PADDING,\n): IFlowViewport | null => {\n if (canvasSize.width <= 0 || canvasSize.height <= 0) return null;\n const left = viewport.x + rect.x * viewport.zoom;\n const top = viewport.y + rect.y * viewport.zoom;\n const right = left + rect.width * viewport.zoom;\n const bottom = top + rect.height * viewport.zoom;\n\n const deltaX = shiftOnAxis(left, right, padding, canvasSize.width - padding);\n const deltaY = shiftOnAxis(top, bottom, padding, canvasSize.height - padding);\n if (deltaX === 0 && deltaY === 0) return null;\n return { x: viewport.x + deltaX, y: viewport.y + deltaY, zoom: viewport.zoom };\n};\n\n/** The box around several rects; null for none. */\nexport const boundsOfRects = (rects: Array<IFlowRect>): IFlowRect | null => {\n if (rects.length === 0) return null;\n const minX = Math.min(...rects.map((rect) => rect.x));\n const minY = Math.min(...rects.map((rect) => rect.y));\n const maxX = Math.max(...rects.map((rect) => rect.x + rect.width));\n const maxY = Math.max(...rects.map((rect) => rect.y + rect.height));\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n};\n"],"names":[],"mappings":"AAmBO,MAAM,sBAAsB;AAEnC,MAAM,cAAc,CAAC,OAAe,KAAa,KAAa,QAAwB;AACpF,MAAI,QAAQ,IAAK,QAAO,MAAM;AAC9B,MAAI,MAAM,IAAK,QAAO,KAAK,IAAI,MAAM,KAAK,MAAM,KAAK;AACrD,SAAO;AACT;AAOO,MAAM,mBAAmB,CAC9B,UACA,MACA,YACA,UAAkB,wBACO;AACzB,MAAI,WAAW,SAAS,KAAK,WAAW,UAAU,EAAG,QAAO;AAC5D,QAAM,OAAO,SAAS,IAAI,KAAK,IAAI,SAAS;AAC5C,QAAM,MAAM,SAAS,IAAI,KAAK,IAAI,SAAS;AAC3C,QAAM,QAAQ,OAAO,KAAK,QAAQ,SAAS;AAC3C,QAAM,SAAS,MAAM,KAAK,SAAS,SAAS;AAE5C,QAAM,SAAS,YAAY,MAAM,OAAO,SAAS,WAAW,QAAQ,OAAO;AAC3E,QAAM,SAAS,YAAY,KAAK,QAAQ,SAAS,WAAW,SAAS,OAAO;AAC5E,MAAI,WAAW,KAAK,WAAW,EAAG,QAAO;AACzC,SAAO,EAAE,GAAG,SAAS,IAAI,QAAQ,GAAG,SAAS,IAAI,QAAQ,MAAM,SAAS,KAAA;AAC1E;AAGO,MAAM,gBAAgB,CAAC,UAA8C;AAC1E,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,QAAM,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC,SAAS,KAAK,CAAC,CAAC;AACpD,QAAM,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC,SAAS,KAAK,CAAC,CAAC;AACpD,QAAM,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC,SAAS,KAAK,IAAI,KAAK,KAAK,CAAC;AACjE,QAAM,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC,SAAS,KAAK,IAAI,KAAK,MAAM,CAAC;AAClE,SAAO,EAAE,GAAG,MAAM,GAAG,MAAM,OAAO,OAAO,MAAM,QAAQ,OAAO,KAAA;AAChE;"}
@@ -2,7 +2,7 @@ export { createFlowBlockRegistry, defineFlowBlock, flowOutputsOf, type IFlowBloc
2
2
  export { default as FlowCanvas, type IFlowCanvasProps } from './FlowCanvas';
3
3
  export { default as FlowEditorProvider, useFlowBlockRegistry, useFlowEditor, useFlowEditorStore, } from './FlowEditorProvider';
4
4
  export { createFlowEditorStore, type IFlowEditorState, type TFlowEditorStore } from './flowEditorStore';
5
- export { canConnect, findCycle, FLOW_LEVEL_GAP, FLOW_SIBLING_GAP, hasBlockingIssues, layoutFlowByLevels, reachableFrom, triggerNodesOf, validateFlowGraph, } from './flowGraph';
5
+ export { canConnect, findCycle, FLOW_LEVEL_GAP, FLOW_SIBLING_GAP, hasBlockingIssues, isFlowNodeRemovable, layoutFlowByLevels, reachableFrom, triggerNodesOf, validateFlowGraph, } from './flowGraph';
6
6
  export { default as FlowInspector } from './FlowInspector';
7
7
  export { default as FlowIssueList } from './FlowIssueList';
8
8
  export { default as FlowLaneMap, type IFlowArc, type IFlowLane, type TFlowArcTone } from './FlowLaneMap';
@@ -2,7 +2,7 @@ import { createFlowBlockRegistry, defineFlowBlock, flowOutputsOf } from "./flowB
2
2
  import { default as default2 } from "./FlowCanvas.js";
3
3
  import { default as default3, useFlowBlockRegistry, useFlowEditor, useFlowEditorStore } from "./FlowEditorProvider.js";
4
4
  import { createFlowEditorStore } from "./flowEditorStore.js";
5
- import { FLOW_LEVEL_GAP, FLOW_SIBLING_GAP, canConnect, findCycle, hasBlockingIssues, layoutFlowByLevels, reachableFrom, triggerNodesOf, validateFlowGraph } from "./flowGraph.js";
5
+ import { FLOW_LEVEL_GAP, FLOW_SIBLING_GAP, canConnect, findCycle, hasBlockingIssues, isFlowNodeRemovable, layoutFlowByLevels, reachableFrom, triggerNodesOf, validateFlowGraph } from "./flowGraph.js";
6
6
  import { default as default4 } from "./FlowInspector.js";
7
7
  import { default as default5 } from "./FlowIssueList.js";
8
8
  import { default as default6 } from "./FlowLaneMap.js";
@@ -27,6 +27,7 @@ export {
27
27
  findCycle,
28
28
  flowOutputsOf,
29
29
  hasBlockingIssues,
30
+ isFlowNodeRemovable,
30
31
  layoutFlowByLevels,
31
32
  reachableFrom,
32
33
  triggerNodesOf,
@@ -226,9 +226,9 @@ declare const _default: {
226
226
  "error": "Error"
227
227
  },
228
228
  "categories": {
229
- "trigger": "Triggers",
230
- "condition": "Conditions",
231
- "action": "Actions"
229
+ "trigger": "Trigger",
230
+ "condition": "Condition",
231
+ "action": "Action"
232
232
  },
233
233
  "inspector": {
234
234
  "title": "Block settings",
@@ -12,7 +12,7 @@ const detailsTable = { "size": "Size", "quantity": "Qty" };
12
12
  const errorPage = { "message": "This screen could not load", "headline": "Something unexpected happened while building the page. Refreshing usually fixes it. If it happens again, contact support and tell them what you were doing.", "backToStart": "Back to start" };
13
13
  const filters = { "activeFilters": "Applied filters", "appliedCount_one": "{{count}} filter applied", "appliedCount_other": "{{count}} filters applied", "clearAll": "Clear all", "noFields": "No filters available for this list.", "noOptions": "No options found.", "optionsError": "Could not load the options for {{field}}.", "rangeMax": "Maximum", "rangeMin": "Minimum", "rangeSeparator": "to", "searchOptions": "Search options" };
14
14
  const filtersDrawer = { "selectedFilters": "Selected filters:", "pendingChanges": "Pending changes", "discardChangesTitle": "Discard changes?", "discardChangesMessage": "You have unapplied filter changes. Discard them?", "keepEditing": "Keep editing", "discard": "Discard" };
15
- const flow = { "canvas": "Flow editor", "resizePanel": "Drag to adjust the width. Double click resets", "ports": { "next": "Next", "true": "Yes", "false": "No", "error": "Error" }, "categories": { "trigger": "Triggers", "condition": "Conditions", "action": "Actions" }, "inspector": { "title": "Block settings", "empty": "Select a block to configure it", "label": "Block name", "delete": "Delete block", "duplicate": "Duplicate block", "unknownBlock": "This block type no longer exists", "close": "Close" }, "issues": { "title": "Issues", "none": "No issues", "missingTrigger": "The flow needs a trigger", "multipleTriggers": "A flow can have only one trigger", "unknownBlock": "Block of a type that no longer exists", "unreachableNode": "Loose block: no path from the trigger reaches it", "multipleInputs": "Block with more than one input", "portFanOut": "An output can connect to one block only", "cycle": "The blocks form a cycle", "missingTrueBranch": "The condition has no yes path" }, "run": { "passed": "Passed", "failed": "Did not pass", "skipped": "Skipped", "wouldRun": "Would run", "error": "Error", "blocked": "Blocked" }, "controls": { "zoomIn": "Zoom in", "zoomOut": "Zoom out", "fitView": "Fit view", "undo": "Undo", "redo": "Redo", "layout": "Arrange blocks" }, "edge": { "insertBlock": "Insert a block here" }, "node": { "disabled": "Disabled", "addBlock": "Add the next block", "issueCount_one": "{{count}} issue", "issueCount_other": "{{count}} issues" }, "laneMap": { "label": "Flow map" } };
15
+ const flow = { "canvas": "Flow editor", "resizePanel": "Drag to adjust the width. Double click resets", "ports": { "next": "Next", "true": "Yes", "false": "No", "error": "Error" }, "categories": { "trigger": "Trigger", "condition": "Condition", "action": "Action" }, "inspector": { "title": "Block settings", "empty": "Select a block to configure it", "label": "Block name", "delete": "Delete block", "duplicate": "Duplicate block", "unknownBlock": "This block type no longer exists", "close": "Close" }, "issues": { "title": "Issues", "none": "No issues", "missingTrigger": "The flow needs a trigger", "multipleTriggers": "A flow can have only one trigger", "unknownBlock": "Block of a type that no longer exists", "unreachableNode": "Loose block: no path from the trigger reaches it", "multipleInputs": "Block with more than one input", "portFanOut": "An output can connect to one block only", "cycle": "The blocks form a cycle", "missingTrueBranch": "The condition has no yes path" }, "run": { "passed": "Passed", "failed": "Did not pass", "skipped": "Skipped", "wouldRun": "Would run", "error": "Error", "blocked": "Blocked" }, "controls": { "zoomIn": "Zoom in", "zoomOut": "Zoom out", "fitView": "Fit view", "undo": "Undo", "redo": "Redo", "layout": "Arrange blocks" }, "edge": { "insertBlock": "Insert a block here" }, "node": { "disabled": "Disabled", "addBlock": "Add the next block", "issueCount_one": "{{count}} issue", "issueCount_other": "{{count}} issues" }, "laneMap": { "label": "Flow map" } };
16
16
  const followUp = { "messages": "Messages", "chat": { "loadingMessages": "Loading messages", "placeholder": "Write a message...", "invalidMessage": "Please enter a valid message", "noMessagesYet": "No messages yet", "startConversation": "Start a conversation by adding the first message", "loadError": "Messages could not be loaded", "sendFailed": "The message could not be sent. Try again.", "sendFailedInline": "Failed to send", "resend": "Resend", "discard": "Discard", "today": "Today", "yesterday": "Yesterday", "typingOne": "{{name}} is typing...", "typingMany": "{{count}} people are typing...", "someone": "Someone", "you": "You", "newMessages": "New messages", "backToLatest": "Back to latest", "deletedMessage": "Message deleted", "edited": "edited", "readBy": "Read by {{names}}", "copied": "Message copied", "replyingTo": "Replying to {{name}}", "attachmentFallback": "Attachment", "editTitle": "Edit message", "deleteTitle": "Delete message?", "deleteSubtitle": "The message will be shown as deleted for every participant", "sendHint": "Enter sends, Shift+Enter adds a line break", "formatting": "Formatting" }, "actions": { "reply": "Reply", "copy": "Copy text", "edit": "Edit", "delete": "Delete" }, "attachments": { "attach": "Attach", "pickFile": "File", "pickImage": "Image", "takePhoto": "Take photo", "dropHere": "Drop files to attach", "tooMany": "Limit of {{max}} attachments per message", "tooLarge": "The file {{name}} exceeds the 50 MB limit", "uploadFailed": "Upload failed", "uploading": "Uploading attachments...", "imagePreview": "Preview image", "showTranscript": "Show transcript", "hideTranscript": "Hide transcript" }, "voice": { "record": "Record audio", "recording": "Recording", "stop": "Finish recording", "cancel": "Cancel recording", "rerecord": "Record again", "attach": "Add to message", "discard": "Discard", "transcriptLabel": "Transcript", "transcriptPlaceholder": "The speech transcript appears here and can be edited" }, "camera": { "title": "Take photo", "unavailable": "Camera unavailable", "unavailableHint": "Check the browser camera permission", "switch": "Switch camera", "capture": "Capture photo" }, "search": { "open": "Search in conversation", "placeholder": "Search messages", "noResults": "No messages found", "error": "Messages could not be searched" } };
17
17
  const generatedByAI = { "tooltip": "Generated by AI" };
18
18
  const imageAiAdjust = { "action": "Adjust with AI", "title": "Adjust image with AI", "subtitle": "Describe the adjustment. The AI changes only what you ask and preserves the rest of the image.", "original": "Original", "result": "Result", "resultHint": "Describe the adjustment and click Generate to see the result here.", "promptLabel": "Desired adjustment", "promptPlaceholder": "E.g. remove the background and make it white, smooth the sleeve creases, brighten the lighting", "generate": "Generate", "generating": "Generating the image...", "tryAgain": "Generate another", "useResult": "Use this image", "errorGenerate": "Could not adjust the image with AI", "errorSave": "Could not save the adjusted image", "errorRefused": "The AI could not make this adjustment: {{reason}}", "mask": { "start": "Mark the area", "stop": "Use the whole image", "hint": "Paint the area the AI may change. The rest of the image is kept." }, "verification": { "changedMoreThanRequested": "The AI changed more than requested. Check the areas outside the adjustment before using it.", "colorMismatch": "The garment color ({{dominant}}) differs from the requested color ({{target}})." } };
@@ -226,9 +226,9 @@ declare const _default: {
226
226
  "error": "Erro"
227
227
  },
228
228
  "categories": {
229
- "trigger": "Gatilhos",
230
- "condition": "Condições",
231
- "action": "Ações"
229
+ "trigger": "Gatilho",
230
+ "condition": "Condição",
231
+ "action": "Ação"
232
232
  },
233
233
  "inspector": {
234
234
  "title": "Configuração do bloco",
@@ -12,7 +12,7 @@ const detailsTable = { "size": "Tam", "quantity": "Qtd" };
12
12
  const errorPage = { "message": "Esta tela não conseguiu carregar", "headline": "Algo inesperado aconteceu ao montar a página. Atualizar costuma resolver. Se acontecer de novo, fale com o suporte contando o que você estava fazendo.", "backToStart": "Voltar para o início" };
13
13
  const filters = { "activeFilters": "Filtros aplicados", "appliedCount_one": "{{count}} filtro aplicado", "appliedCount_other": "{{count}} filtros aplicados", "clearAll": "Limpar tudo", "noFields": "Nenhum filtro disponível para esta listagem.", "noOptions": "Nenhuma opção encontrada.", "optionsError": "Não foi possível carregar as opções de {{field}}.", "rangeMax": "Máximo", "rangeMin": "Mínimo", "rangeSeparator": "até", "searchOptions": "Buscar opções" };
14
14
  const filtersDrawer = { "selectedFilters": "Filtros Selecionados:", "pendingChanges": "Alterações pendentes", "discardChangesTitle": "Descartar alterações?", "discardChangesMessage": "Você tem alterações de filtro não aplicadas. Deseja descartá-las?", "keepEditing": "Continuar editando", "discard": "Descartar" };
15
- const flow = { "canvas": "Editor de fluxo", "resizePanel": "Arraste para ajustar a largura. Clique duplo restaura", "ports": { "next": "Próximo", "true": "Sim", "false": "Não", "error": "Erro" }, "categories": { "trigger": "Gatilhos", "condition": "Condições", "action": "Ações" }, "inspector": { "title": "Configuração do bloco", "empty": "Selecione um bloco para configurar", "label": "Nome do bloco", "delete": "Excluir bloco", "duplicate": "Duplicar bloco", "unknownBlock": "Este tipo de bloco não existe mais", "close": "Fechar" }, "issues": { "title": "Pendências", "none": "Nenhuma pendência", "missingTrigger": "O fluxo precisa de um gatilho", "multipleTriggers": "O fluxo só pode ter um gatilho", "unknownBlock": "Bloco de um tipo que não existe mais", "unreachableNode": "Bloco solto: nenhum caminho do gatilho chega até ele", "multipleInputs": "Bloco com mais de uma entrada", "portFanOut": "Uma saída só pode ligar a um bloco", "cycle": "Os blocos formam um ciclo", "missingTrueBranch": "A condição não tem o caminho do sim" }, "run": { "passed": "Passou", "failed": "Não passou", "skipped": "Pulado", "wouldRun": "Executaria", "error": "Erro", "blocked": "Bloqueado" }, "controls": { "zoomIn": "Aproximar", "zoomOut": "Afastar", "fitView": "Enquadrar", "undo": "Desfazer", "redo": "Refazer", "layout": "Organizar blocos" }, "edge": { "insertBlock": "Inserir um bloco aqui" }, "node": { "disabled": "Desativado", "addBlock": "Adicionar o próximo bloco", "issueCount_one": "{{count}} pendência", "issueCount_other": "{{count}} pendências" }, "laneMap": { "label": "Mapa do fluxo" } };
15
+ const flow = { "canvas": "Editor de fluxo", "resizePanel": "Arraste para ajustar a largura. Clique duplo restaura", "ports": { "next": "Próximo", "true": "Sim", "false": "Não", "error": "Erro" }, "categories": { "trigger": "Gatilho", "condition": "Condição", "action": "Ação" }, "inspector": { "title": "Configuração do bloco", "empty": "Selecione um bloco para configurar", "label": "Nome do bloco", "delete": "Excluir bloco", "duplicate": "Duplicar bloco", "unknownBlock": "Este tipo de bloco não existe mais", "close": "Fechar" }, "issues": { "title": "Pendências", "none": "Nenhuma pendência", "missingTrigger": "O fluxo precisa de um gatilho", "multipleTriggers": "O fluxo só pode ter um gatilho", "unknownBlock": "Bloco de um tipo que não existe mais", "unreachableNode": "Bloco solto: nenhum caminho do gatilho chega até ele", "multipleInputs": "Bloco com mais de uma entrada", "portFanOut": "Uma saída só pode ligar a um bloco", "cycle": "Os blocos formam um ciclo", "missingTrueBranch": "A condição não tem o caminho do sim" }, "run": { "passed": "Passou", "failed": "Não passou", "skipped": "Pulado", "wouldRun": "Executaria", "error": "Erro", "blocked": "Bloqueado" }, "controls": { "zoomIn": "Aproximar", "zoomOut": "Afastar", "fitView": "Enquadrar", "undo": "Desfazer", "redo": "Refazer", "layout": "Organizar blocos" }, "edge": { "insertBlock": "Inserir um bloco aqui" }, "node": { "disabled": "Desativado", "addBlock": "Adicionar o próximo bloco", "issueCount_one": "{{count}} pendência", "issueCount_other": "{{count}} pendências" }, "laneMap": { "label": "Mapa do fluxo" } };
16
16
  const followUp = { "messages": "Mensagens", "chat": { "loadingMessages": "Carregando mensagens", "placeholder": "Escrever mensagem...", "invalidMessage": "Por favor, insira uma mensagem válida", "noMessagesYet": "Nenhuma mensagem por enquanto", "startConversation": "Inicie uma conversa adicionando a primeira mensagem", "loadError": "Não foi possível carregar as mensagens", "sendFailed": "Não foi possível enviar a mensagem. Tente novamente.", "sendFailedInline": "Falha no envio", "resend": "Reenviar", "discard": "Descartar", "today": "Hoje", "yesterday": "Ontem", "typingOne": "{{name}} está digitando...", "typingMany": "{{count}} pessoas estão digitando...", "someone": "Alguém", "you": "Você", "newMessages": "Novas mensagens", "backToLatest": "Voltar para as recentes", "deletedMessage": "Mensagem apagada", "edited": "editada", "readBy": "Lida por {{names}}", "copied": "Mensagem copiada", "replyingTo": "Respondendo a {{name}}", "attachmentFallback": "Anexo", "editTitle": "Editar mensagem", "deleteTitle": "Apagar mensagem?", "deleteSubtitle": "A mensagem será marcada como apagada para todos os participantes", "sendHint": "Enter envia, Shift+Enter quebra a linha", "formatting": "Formatação" }, "actions": { "reply": "Responder", "copy": "Copiar texto", "edit": "Editar", "delete": "Apagar" }, "attachments": { "attach": "Anexar", "pickFile": "Arquivo", "pickImage": "Imagem", "takePhoto": "Tirar foto", "dropHere": "Solte os arquivos para anexar", "tooMany": "Limite de {{max}} anexos por mensagem", "tooLarge": "O arquivo {{name}} passa do limite de 50 MB", "uploadFailed": "Falha no upload", "uploading": "Enviando anexos...", "imagePreview": "Visualizar imagem", "showTranscript": "Ver transcrição", "hideTranscript": "Ocultar transcrição" }, "voice": { "record": "Gravar áudio", "recording": "Gravando", "stop": "Concluir gravação", "cancel": "Cancelar gravação", "rerecord": "Regravar", "attach": "Adicionar ao envio", "discard": "Descartar", "transcriptLabel": "Transcrição", "transcriptPlaceholder": "A transcrição da fala aparece aqui e pode ser editada" }, "camera": { "title": "Tirar foto", "unavailable": "Câmera indisponível", "unavailableHint": "Verifique a permissão de câmera do navegador", "switch": "Alternar câmera", "capture": "Capturar foto" }, "search": { "open": "Buscar na conversa", "placeholder": "Buscar mensagens", "noResults": "Nenhuma mensagem encontrada", "error": "Não foi possível buscar as mensagens" } };
17
17
  const generatedByAI = { "tooltip": "Gerado por IA" };
18
18
  const imageAiAdjust = { "action": "Ajustar com IA", "title": "Ajustar imagem com IA", "subtitle": "Descreva o ajuste. A IA altera só o que você pedir e preserva o resto da imagem.", "original": "Original", "result": "Resultado", "resultHint": "Descreva o ajuste e clique em Gerar para ver o resultado aqui.", "promptLabel": "Ajuste desejado", "promptPlaceholder": "Ex.: remover o fundo e deixar branco, tirar os vincos da manga, clarear a iluminação", "generate": "Gerar", "generating": "Gerando a imagem...", "tryAgain": "Gerar outra", "useResult": "Usar esta imagem", "errorGenerate": "Não foi possível ajustar a imagem com IA", "errorSave": "Não foi possível salvar a imagem ajustada", "errorRefused": "A IA não conseguiu fazer este ajuste: {{reason}}", "mask": { "start": "Marcar a área", "stop": "Usar a imagem toda", "hint": "Pinte a área que a IA pode alterar. O resto da imagem é mantido." }, "verification": { "changedMoreThanRequested": "A IA mudou mais do que o pedido. Confira as áreas fora do ajuste antes de usar.", "colorMismatch": "A cor da peça ({{dominant}}) ficou diferente da cor pedida ({{target}})." } };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umodeapporg/ui",
3
- "version": "0.24.0",
3
+ "version": "0.24.2",
4
4
  "license": "UNLICENSED",
5
5
  "type": "module",
6
6
  "sideEffects": [