@conscience-technology/ovenn 0.6.7 → 0.7.0
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.
- package/assets/components/AIMessage/AIMessage.module.css +2 -1
- package/assets/components/Accordion/Accordion.module.css +3 -0
- package/assets/components/AppFrame/AppFrame.module.css +2 -0
- package/assets/components/AttachmentItem/AttachmentItem.module.css +9 -3
- package/assets/components/AttachmentThumb/AttachmentThumb.module.css +4 -0
- package/assets/components/Avatar/Avatar.module.css +26 -11
- package/assets/components/Avatar/Avatar.tsx +1 -1
- package/assets/components/AvatarUpload/AvatarUpload.module.css +4 -3
- package/assets/components/Badge/Badge.module.css +96 -70
- package/assets/components/Badge/Badge.tsx +33 -25
- package/assets/components/Breadcrumb/Breadcrumb.module.css +8 -4
- package/assets/components/Breadcrumb/Breadcrumb.tsx +1 -1
- package/assets/components/Bubble/Bubble.module.css +6 -0
- package/assets/components/Button/Button.module.css +6 -0
- package/assets/components/Calendar/Calendar.module.css +244 -0
- package/assets/components/Calendar/Calendar.tsx +419 -0
- package/assets/components/Calendar/index.ts +2 -0
- package/assets/components/Callout/Callout.module.css +1 -0
- package/assets/components/Canvas/Canvas.module.css +75 -0
- package/assets/components/Canvas/Canvas.tsx +699 -0
- package/assets/components/Canvas/alignment.ts +34 -0
- package/assets/components/Canvas/clipboard.ts +30 -0
- package/assets/components/Canvas/collision.ts +67 -0
- package/assets/components/Canvas/edgeOptions.ts +11 -0
- package/assets/components/Canvas/graph.ts +11 -0
- package/assets/components/Canvas/history.ts +41 -0
- package/assets/components/Canvas/index.ts +4 -0
- package/assets/components/Canvas/selection.ts +56 -0
- package/assets/components/Canvas/tokens.css +61 -0
- package/assets/components/Canvas/types.ts +27 -0
- package/assets/components/Canvas/useCanvasSettlement.ts +79 -0
- package/assets/components/CanvasEdge/CanvasEdge.module.css +62 -0
- package/assets/components/CanvasEdge/CanvasEdge.tsx +121 -0
- package/assets/components/CanvasEdge/geometry.ts +350 -0
- package/assets/components/CanvasEdge/index.ts +4 -0
- package/assets/components/CanvasEdge/interactions.ts +14 -0
- package/assets/components/CanvasEdge/tokens.css +29 -0
- package/assets/components/CanvasNode/CanvasNode.module.css +234 -30
- package/assets/components/CanvasNode/CanvasNode.tsx +95 -28
- package/assets/components/CanvasNode/index.ts +1 -1
- package/assets/components/CanvasNode/runningOutline.ts +59 -0
- package/assets/components/CanvasNode/tokens.css +76 -13
- package/assets/components/Card/Card.module.css +5 -0
- package/assets/components/Chart/Chart.module.css +278 -0
- package/assets/components/Chart/Chart.tsx +385 -0
- package/assets/components/Chart/entrance.tsx +57 -0
- package/assets/components/Chart/index.ts +14 -0
- package/assets/components/ChatInput/ChatInput.module.css +5 -0
- package/assets/components/Checkbox/Checkbox.module.css +39 -0
- package/assets/components/Checkbox/Checkbox.tsx +99 -14
- package/assets/components/Checkbox/index.ts +1 -1
- package/assets/components/CheckboxCard/CheckboxCard.module.css +1 -177
- package/assets/components/CheckboxCard/CheckboxCard.tsx +6 -72
- package/assets/components/Chip/Chip.module.css +20 -30
- package/assets/components/Code/Code.module.css +1 -0
- package/assets/components/CodeBlock/CodeBlock.module.css +7 -3
- package/assets/components/ColorArea/ColorArea.module.css +3 -0
- package/assets/components/ColorField/ColorField.module.css +6 -0
- package/assets/components/ColorField/ColorField.tsx +3 -1
- package/assets/components/ColorPicker/ColorPicker.module.css +310 -0
- package/assets/components/ColorPicker/ColorPicker.tsx +387 -0
- package/assets/components/ColorPicker/index.ts +16 -0
- package/assets/components/ColorSlider/ColorSlider.module.css +15 -12
- package/assets/components/ColorSlider/ColorSlider.tsx +3 -3
- package/assets/components/ColorSwatch/ColorSwatch.module.css +2 -2
- package/assets/components/ColorSwatchPicker/ColorSwatchPicker.module.css +4 -3
- package/assets/components/Combobox/Combobox.module.css +1 -1
- package/assets/components/Combobox/Combobox.tsx +1 -1
- package/assets/components/CommandPalette/CommandPalette.module.css +18 -23
- package/assets/components/CommandPalette/CommandPalette.tsx +7 -5
- package/assets/components/Comment/Comment.module.css +25 -0
- package/assets/components/Comment/Comment.tsx +44 -0
- package/assets/components/Comment/CommentComposer.module.css +26 -0
- package/assets/components/Comment/CommentComposer.tsx +56 -0
- package/assets/components/Comment/CommentEditor.module.css +8 -0
- package/assets/components/Comment/CommentEditor.tsx +43 -0
- package/assets/components/Comment/CommentMentionInput.module.css +9 -0
- package/assets/components/Comment/CommentMentionInput.tsx +150 -0
- package/assets/components/Comment/index.ts +9 -0
- package/assets/components/Comment/types.ts +1 -0
- package/assets/components/ContextMenu/ContextMenu.module.css +5 -2
- package/assets/components/ContextMenu/ContextMenu.tsx +5 -0
- package/assets/components/ControlGroup/ControlGroup.module.css +7 -1
- package/assets/components/DataTable/DataTable.module.css +2 -0
- package/assets/components/DatePicker/DatePicker.module.css +36 -3
- package/assets/components/DatePicker/DatePicker.tsx +11 -1
- package/assets/components/DatePicker/TimeSelector.tsx +1 -1
- package/assets/components/Disclosure/Disclosure.module.css +1 -0
- package/assets/components/Drawer/Drawer.module.css +11 -4
- package/assets/components/Drawer/Drawer.tsx +5 -1
- package/assets/components/DropdownMenu/DropdownMenu.tsx +5 -0
- package/assets/components/EventChip/EventChip.module.css +120 -53
- package/assets/components/EventChip/EventChip.tsx +54 -6
- package/assets/components/EventChip/index.ts +1 -1
- package/assets/components/EventListItem/EventListItem.module.css +3 -0
- package/assets/components/EventListItem/EventListItem.tsx +15 -8
- package/assets/components/FileIcon/FileIcon.module.css +2 -0
- package/assets/components/FileUpload/FileUpload.module.css +10 -3
- package/assets/components/FileUpload/FileUpload.tsx +5 -9
- package/assets/components/FileUpload/FileUploadItem.tsx +34 -0
- package/assets/components/GalleryItem/GalleryItem.module.css +16 -19
- package/assets/components/GeneratedImage/GeneratedImage.module.css +2 -0
- package/assets/components/Icon/Icon.tsx +264 -1088
- package/assets/components/Icon/LucideFamilyIcon.tsx +434 -0
- package/assets/components/Icon/MissingIcon.tsx +25 -0
- package/assets/components/Icon/SolarFamilyIcon.tsx +439 -0
- package/assets/components/Icon/catalogNames.ts +8 -0
- package/assets/components/Icon/context.tsx +1 -1
- package/assets/components/Icon/index.ts +2 -0
- package/assets/components/Icon/lucideCatalog.ts +11358 -0
- package/assets/components/Icon/phosphorCatalog.ts +3052 -0
- package/assets/components/Icon/solarCatalog.ts +16064 -0
- package/assets/components/IconButton/IconButton.module.css +3 -2
- package/assets/components/Input/Input.module.css +30 -12
- package/assets/components/Input/Input.tsx +1 -1
- package/assets/components/Kanban/Kanban.module.css +6 -0
- package/assets/components/ListItem/ListItem.module.css +9 -6
- package/assets/components/MenuItem/MenuItem.module.css +24 -22
- package/assets/components/MenuItem/MenuItem.tsx +12 -12
- package/assets/components/MessageActions/MessageActions.module.css +36 -0
- package/assets/components/MessageActions/MessageActions.tsx +53 -28
- package/assets/components/MessageQuote/MessageQuote.module.css +1 -0
- package/assets/components/MessageSources/MessageSources.module.css +2 -0
- package/assets/components/MessageState/MessageState.module.css +1 -1
- package/assets/components/MetricCard/MetricCard.module.css +96 -108
- package/assets/components/MetricCard/MetricCard.tsx +45 -23
- package/assets/components/MetricCard/tokens.css +10 -0
- package/assets/components/MiniCalendar/MiniCalendar.module.css +130 -0
- package/assets/components/MiniCalendar/MiniCalendar.tsx +161 -0
- package/assets/components/MiniCalendar/index.ts +2 -0
- package/assets/components/Modal/Modal.module.css +13 -4
- package/assets/components/Modal/Modal.tsx +4 -0
- package/assets/components/Onboarding/LayoutBuilder.tsx +12 -50
- package/assets/components/Onboarding/Onboarding.module.css +211 -278
- package/assets/components/Onboarding/OnboardingAxisPanel.tsx +81 -125
- package/assets/components/Onboarding/OnboardingPage.tsx +244 -467
- package/assets/components/Onboarding/actions.ts +5 -0
- package/assets/components/Onboarding/palette.css +8 -0
- package/assets/components/Onboarding/wizardData.ts +8 -8
- package/assets/components/ProgressBar/ProgressBar.module.css +8 -8
- package/assets/components/ProgressBar/ProgressBar.tsx +0 -5
- package/assets/components/ProgressBar/index.ts +0 -1
- package/assets/components/QuotationBar/QuotationBar.module.css +2 -0
- package/assets/components/Radio/Radio.module.css +2 -0
- package/assets/components/RadioCard/RadioCard.module.css +78 -3
- package/assets/components/RadioCard/RadioCard.tsx +34 -12
- package/assets/components/RadioCard/index.ts +1 -1
- package/assets/components/SegmentedChart/SegmentedChart.module.css +16 -0
- package/assets/components/SegmentedChart/SegmentedChart.tsx +25 -8
- package/assets/components/Select/Select.tsx +7 -4
- package/assets/components/Shortcut/Shortcut.module.css +2 -0
- package/assets/components/Sidebar/Sidebar.module.css +1 -0
- package/assets/components/Sidebar/Sidebar.tsx +2 -2
- package/assets/components/Skeleton/Skeleton.module.css +33 -0
- package/assets/components/Skeleton/Skeleton.tsx +20 -0
- package/assets/components/Skeleton/index.ts +2 -0
- package/assets/components/Skeleton/tokens.css +11 -0
- package/assets/components/Slider/Slider.module.css +3 -0
- package/assets/components/Slider/Slider.tsx +7 -2
- package/assets/components/Spinner/LottiePlayer.tsx +4 -4
- package/assets/components/Spinner/Spinner.module.css +3 -0
- package/assets/components/Spinner/lottieManifest.ts +3 -0
- package/assets/components/Stepper/Stepper.module.css +56 -8
- package/assets/components/Stepper/Stepper.tsx +13 -4
- package/assets/components/Switch/Switch.module.css +55 -42
- package/assets/components/Switch/Switch.tsx +6 -2
- package/assets/components/Switch/index.ts +1 -1
- package/assets/components/TabStrip/TabStrip.module.css +5 -1
- package/assets/components/TableCell/TableCell.module.css +8 -1
- package/assets/components/TableCell/TableCellBadge.tsx +7 -3
- package/assets/components/TableCell/TableCellImage.tsx +1 -1
- package/assets/components/TableCell/TableCellTag.tsx +23 -0
- package/assets/components/TableCell/index.ts +3 -0
- package/assets/components/TableHeader/TableHeader.module.css +4 -0
- package/assets/components/TableRow/TableRow.module.css +3 -0
- package/assets/components/TableRowEdit/TableRowEdit.module.css +2 -0
- package/assets/components/TableToolbar/TableToolbar.module.css +1 -0
- package/assets/components/Tabs/Tabs.module.css +22 -7
- package/assets/components/Tabs/Tabs.tsx +2 -1
- package/assets/components/Tag/Tag.module.css +101 -0
- package/assets/components/Tag/Tag.tsx +55 -0
- package/assets/components/Tag/index.ts +2 -0
- package/assets/components/TemplateBoundary/TemplateBoundary.tsx +22 -18
- package/assets/components/TemplateBoundary/types.ts +2 -0
- package/assets/components/Textarea/Textarea.module.css +7 -0
- package/assets/components/ThemeController.tsx +30 -3
- package/assets/components/TimePicker/TimePicker.module.css +1 -0
- package/assets/components/TimePicker/TimePicker.tsx +37 -16
- package/assets/components/TimelineView/TimelineEventBar.tsx +109 -0
- package/assets/components/TimelineView/TimelineView.module.css +203 -0
- package/assets/components/TimelineView/TimelineView.tsx +137 -0
- package/assets/components/TimelineView/axis.ts +62 -0
- package/assets/components/TimelineView/index.ts +3 -0
- package/assets/components/TimelineView/layout.ts +56 -0
- package/assets/components/TimelineView/move.ts +51 -0
- package/assets/components/TimelineView/useTimelineDrag.ts +215 -0
- package/assets/components/TimelineView/useTimelineZoom.ts +92 -0
- package/assets/components/Toast/Toast.module.css +2 -0
- package/assets/components/Toolbar/Toolbar.module.css +31 -24
- package/assets/components/Toolbar/Toolbar.tsx +4 -3
- package/assets/components/Tooltip/Tooltip.module.css +10 -0
- package/assets/components/Tooltip/Tooltip.tsx +17 -8
- package/assets/components/TopLoader/TopLoader.module.css +1 -0
- package/assets/components/TreeNav/TreeNav.module.css +1 -0
- package/assets/components/_color.ts +2 -2
- package/assets/components/_data.ts +33 -32
- package/assets/components/_utils.css +5 -0
- package/assets/components/axisOptions.ts +2 -0
- package/assets/components/component-registry.json +151 -2
- package/assets/components/index.ts +16 -0
- package/assets/components/materialScope.tsx +11 -0
- package/assets/components/reset.css +1 -0
- package/assets/components/themeBootScript.ts +3 -2
- package/assets/components/tokens.css +225 -71
- package/assets/components/useChartEntrance.ts +119 -0
- package/assets/prompts/ASSEMBLY.md +9 -7
- package/assets/prompts/CATALOG.md +18 -4
- package/assets/prompts/FEEDBACK_PROCESS.md +19 -0
- package/assets/prompts/PRINCIPLES.md +14 -0
- package/assets/prompts/WORKFLOW_DESIGN.md +46 -70
- package/assets/prompts/axes/font.md +6 -1
- package/assets/prompts/axes/icon.md +6 -4
- package/assets/prompts/axes/material.md +40 -0
- package/assets/prompts/axes/palette.md +2 -1
- package/assets/prompts/axes/shape.md +8 -0
- package/assets/prompts/components/attachment-item.md +2 -1
- package/assets/prompts/components/badge.md +32 -97
- package/assets/prompts/components/breadcrumb.md +1 -0
- package/assets/prompts/components/calendar.md +151 -0
- package/assets/prompts/components/canvas-edge.md +67 -0
- package/assets/prompts/components/canvas-node.md +25 -8
- package/assets/prompts/components/canvas.md +82 -0
- package/assets/prompts/components/card.md +10 -10
- package/assets/prompts/components/chart-bar.md +77 -0
- package/assets/prompts/components/chart-pie.md +63 -0
- package/assets/prompts/components/chart-radar.md +56 -0
- package/assets/prompts/components/chart-radial.md +56 -0
- package/assets/prompts/components/chart.md +129 -0
- package/assets/prompts/components/checkbox-card.md +26 -45
- package/assets/prompts/components/checkbox.md +23 -0
- package/assets/prompts/components/chip.md +6 -6
- package/assets/prompts/components/code-block.md +1 -0
- package/assets/prompts/components/color-picker.md +173 -0
- package/assets/prompts/components/color-slider.md +7 -7
- package/assets/prompts/components/command-palette.md +7 -6
- package/assets/prompts/components/comment.md +72 -0
- package/assets/prompts/components/context-menu.md +6 -3
- package/assets/prompts/components/data-table.md +9 -0
- package/assets/prompts/components/date-picker.md +10 -0
- package/assets/prompts/components/drawer.md +10 -0
- package/assets/prompts/components/dropdown-menu.md +3 -1
- package/assets/prompts/components/event-chip.md +60 -18
- package/assets/prompts/components/event-list-item.md +14 -10
- package/assets/prompts/components/file-upload.md +1 -1
- package/assets/prompts/components/gallery-item.md +5 -4
- package/assets/prompts/components/icon.md +30 -8
- package/assets/prompts/components/kanban.md +1 -1
- package/assets/prompts/components/list-item.md +11 -2
- package/assets/prompts/components/menu-item.md +8 -3
- package/assets/prompts/components/message-actions.md +9 -0
- package/assets/prompts/components/metric-card.md +57 -109
- package/assets/prompts/components/mini-calendar.md +72 -0
- package/assets/prompts/components/modal.md +1 -0
- package/assets/prompts/components/onboarding.md +11 -7
- package/assets/prompts/components/page-header.md +11 -2
- package/assets/prompts/components/progress-bar.md +12 -2
- package/assets/prompts/components/radio-card.md +33 -117
- package/assets/prompts/components/segmented-chart.md +19 -5
- package/assets/prompts/components/select.md +1 -0
- package/assets/prompts/components/sidebar.md +12 -3
- package/assets/prompts/components/skeleton.md +44 -0
- package/assets/prompts/components/stepper.md +15 -1
- package/assets/prompts/components/switch.md +15 -10
- package/assets/prompts/components/tab-strip.md +1 -0
- package/assets/prompts/components/table-cell.md +6 -4
- package/assets/prompts/components/table-row.md +12 -3
- package/assets/prompts/components/table-toolbar.md +9 -0
- package/assets/prompts/components/tabs.md +4 -2
- package/assets/prompts/components/tag.md +54 -0
- package/assets/prompts/components/time-picker.md +1 -0
- package/assets/prompts/components/timeline-view.md +129 -0
- package/assets/prompts/components/toast.md +1 -1
- package/assets/prompts/components/toolbar.md +17 -4
- package/assets/prompts/components/tooltip.md +21 -3
- package/assets/prompts/components/top-loader.md +1 -1
- package/assets/prompts/components/topbar.md +9 -0
- package/assets/prompts/components/tree-nav.md +1 -1
- package/assets/prompts/templates/ains.md +2 -1
- package/assets/prompts/templates/aurora.md +5 -4
- package/assets/prompts/templates/glass-button.md +6 -5
- package/assets/prompts/templates/minimal.md +8 -6
- package/assets/prompts/templates/workspace.md +3 -3
- package/assets/prompts/tokens/color.md +4 -2
- package/assets/prompts/tokens/material.md +51 -0
- package/assets/prompts/tokens/radius.md +12 -0
- package/assets/prompts/tokens/typography.md +24 -2
- package/assets/prompts/use-cases/chart-chart-area.md +1334 -0
- package/assets/prompts/use-cases/chart-chart-bar.md +1886 -0
- package/assets/prompts/use-cases/chart-chart-pie.md +1031 -0
- package/assets/prompts/use-cases/chart-chart-radar.md +785 -0
- package/assets/prompts/use-cases/chart-chart-radial.md +988 -0
- package/assets/prompts/use-cases/chart-segmented-chart.md +262 -0
- package/assets/prompts/use-cases/data-comment.md +360 -0
- package/assets/prompts/use-cases/data-data-table.md +249 -0
- package/assets/prompts/use-cases/data-list-item.md +1056 -0
- package/assets/prompts/use-cases/data-metric-card.md +673 -0
- package/assets/prompts/use-cases/data-table-row.md +966 -0
- package/assets/prompts/use-cases/data-table-toolbar.md +481 -0
- package/assets/prompts/use-cases/feedback-drawer.md +1163 -0
- package/assets/prompts/use-cases/feedback-progress-bar.md +427 -0
- package/assets/prompts/use-cases/general-toolbar.md +854 -0
- package/assets/prompts/use-cases/general-tooltip.md +652 -0
- package/assets/prompts/use-cases/input-checkbox.md +443 -0
- package/assets/prompts/use-cases/structure-card.md +603 -0
- package/assets/prompts/use-cases/structure-page-header.md +755 -0
- package/assets/prompts/use-cases/structure-sidebar.md +1132 -0
- package/assets/prompts/use-cases/structure-topbar.md +1200 -0
- package/assets/public/ovenn-wordmark.svg +19 -0
- package/package.json +6 -2
- package/src/commands/info.js +1 -1
|
@@ -0,0 +1,699 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
import { useCallback, useMemo, useEffect, useId, useLayoutEffect, useRef, useState, type ClipboardEvent, type CSSProperties, type HTMLAttributes, type KeyboardEvent, type PointerEvent } from "react";
|
|
4
|
+
import { Icon } from "../Icon";
|
|
5
|
+
import { CanvasNode, type CanvasNodePortSide } from "../CanvasNode";
|
|
6
|
+
import { CanvasEdge, type CanvasEdgeObstacle, type CanvasEdgeEndpoint, type CanvasEdgeLineStyle } from "../CanvasEdge";
|
|
7
|
+
import { Button } from "../Button";
|
|
8
|
+
import { Toolbar, type ToolbarOrientation } from "../Toolbar";
|
|
9
|
+
import { IconButton } from "../IconButton";
|
|
10
|
+
import { canvasNodeSelectionIds, canvasEdgeSelectionIds, makeCanvasSelection, canvasPathIntersectsRect, canvasSelectionRect, canvasNodesInRect, sameCanvasSelection, type CanvasSelectionRect } from "./selection";
|
|
11
|
+
import { alignCanvasNodes, type CanvasAlignmentGuide, type CanvasAlignmentConfig } from "./alignment";
|
|
12
|
+
import { CanvasHistory, canvasGraphSignature, snapshotCanvasGraph, restoreCanvasGraph, type CanvasGraph, type CanvasSnapshot } from "./history";
|
|
13
|
+
import { useCanvasSettlement } from "./useCanvasSettlement";
|
|
14
|
+
import { constrainCanvasMovement, findCanvasPlacement } from "./collision";
|
|
15
|
+
import { snapshotCanvasSelection, storeCanvasClipboard, readCanvasClipboard } from "./clipboard";
|
|
16
|
+
import { canConnectCanvas, samePort } from "./graph";
|
|
17
|
+
import { resolveCanvasCornerRadius, type CanvasCornerRadii } from "./edgeOptions";
|
|
18
|
+
import type { CanvasBackground, CanvasEdgeCornerRadius, CanvasConnection, CanvasItem, CanvasLabels, CanvasLink, CanvasPort, CanvasSelection } from "./types";
|
|
19
|
+
import "./tokens.css";
|
|
20
|
+
import styles from "./Canvas.module.css";
|
|
21
|
+
|
|
22
|
+
type Point = { x: number; y: number };
|
|
23
|
+
type Viewport = Point & { zoom: number };
|
|
24
|
+
type Metrics = { width: number; height: number; body: CanvasEdgeObstacle; captions: CanvasEdgeObstacle[]; ports: Partial<Record<CanvasNodePortSide, Point>> };
|
|
25
|
+
type GesturePointer = Pick<globalThis.PointerEvent, "pointerId" | "clientX" | "clientY">;
|
|
26
|
+
type Gesture = { pointerId: number; start: Point; last?: Point; moved: boolean } & (
|
|
27
|
+
{ type: "node"; id: string; origins: Record<string, Point>; collapseOnClick: boolean; needsSettlement?: boolean; restoreOrigins?: Record<string, Point> } | { type: "pan"; origin: Viewport; clearOnClick?: boolean } | { type: "connect"; source: CanvasPort } | { type: "marquee"; anchor: Point; previous: CanvasSelection; additive: boolean }
|
|
28
|
+
);
|
|
29
|
+
const english: CanvasLabels = {
|
|
30
|
+
canvas: "Canvas", controls: "View controls", zoomIn: "Zoom in", zoomOut: "Zoom out", fit: "Fit to view",
|
|
31
|
+
zoom: "Zoom",
|
|
32
|
+
instructions: "Drag nodes to move. Drag between handles or click two handles to connect. Arrow keys move a focused node; Shift moves faster. Escape cancels. Delete removes selection. Cmd/Ctrl+Z undoes edits; add Shift to redo. Drag the background to select nodes and connections. Hold Shift to add to selection. Hold Space while dragging, or use the middle mouse button, to pan.",
|
|
33
|
+
connecting: "Choose another node’s handle to connect. Escape cancels.", connected: "Connection added.", cancelled: "Connection cancelled.",
|
|
34
|
+
port: (title, side) => `${title}, ${side} connection handle`,
|
|
35
|
+
};
|
|
36
|
+
export interface CanvasProps extends Omit<HTMLAttributes<HTMLDivElement>, "children" | "onChange" | "onSelect"> {
|
|
37
|
+
nodes: readonly CanvasItem[];
|
|
38
|
+
edges: readonly CanvasLink[];
|
|
39
|
+
onNodesChange?: (nodes: CanvasItem[]) => void;
|
|
40
|
+
onEdgesChange?: (edges: CanvasLink[]) => void;
|
|
41
|
+
selection?: CanvasSelection;
|
|
42
|
+
onSelectionChange?: (selection: CanvasSelection) => void;
|
|
43
|
+
isValidConnection?: (connection: CanvasConnection) => boolean;
|
|
44
|
+
/** Three Shape-aware presets. Omitted values follow the nearest Shape scope. */
|
|
45
|
+
edgeCornerRadius?: CanvasEdgeCornerRadius;
|
|
46
|
+
lineStyle?: CanvasEdgeLineStyle;
|
|
47
|
+
readOnly?: boolean;
|
|
48
|
+
/** Legacy dots toggle; background/defaultBackground take precedence. */
|
|
49
|
+
grid?: boolean;
|
|
50
|
+
background?: CanvasBackground;
|
|
51
|
+
/** Pattern spacing only; does not change viewport zoom. 0.5–2. */
|
|
52
|
+
backgroundScale?: number;
|
|
53
|
+
defaultBackground?: CanvasBackground;
|
|
54
|
+
controls?: boolean;
|
|
55
|
+
/** Direction of the view toolbar; defaults to horizontal. */
|
|
56
|
+
controlsOrientation?: ToolbarOrientation;
|
|
57
|
+
labels?: Partial<CanvasLabels>;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A controlled graph surface composed from CanvasNode and CanvasEdge. */
|
|
61
|
+
export function Canvas({ nodes, edges, onNodesChange, onEdgesChange, selection: controlledSelection, onSelectionChange,
|
|
62
|
+
isValidConnection, edgeCornerRadius, lineStyle = "solid", readOnly = false, grid = true, background, backgroundScale = .9, defaultBackground, controls = true, controlsOrientation = "horizontal",
|
|
63
|
+
labels, className, onKeyDown, ...rest }: CanvasProps) {
|
|
64
|
+
const text = { ...english, ...labels };
|
|
65
|
+
const helpId = useId();
|
|
66
|
+
const captionMaskId = useId();
|
|
67
|
+
const [surfaceSize, setSurfaceSize] = useState({ width: 1, height: 1 });
|
|
68
|
+
const root = useRef<HTMLDivElement>(null);
|
|
69
|
+
const nodeElements = useRef(new Map<string, HTMLDivElement>());
|
|
70
|
+
const gesture = useRef<Gesture | null>(null);
|
|
71
|
+
const suppressClick = useRef(false);
|
|
72
|
+
const spacePressed = useRef(false);
|
|
73
|
+
const spaceUsedForPan = useRef(false);
|
|
74
|
+
const cancelRef = useRef<() => void>(() => {});
|
|
75
|
+
const releaseRef = useRef<(event: GesturePointer) => void>(() => {});
|
|
76
|
+
const moveRef = useRef<(event: GesturePointer) => void>(() => {});
|
|
77
|
+
const [guides, setGuides] = useState<CanvasAlignmentGuide[]>([]);
|
|
78
|
+
const guideLatch = useRef<CanvasAlignmentGuide[]>([]);
|
|
79
|
+
const [guideConfig, setGuideConfig] = useState<CanvasAlignmentConfig>({ threshold: 6, release: 10, extension: 12 });
|
|
80
|
+
const clearGuides = useCallback(() => { guideLatch.current = []; setGuides([]); }, []);
|
|
81
|
+
const [panReady, setPanReady] = useState(false);
|
|
82
|
+
const [marquee, setMarquee] = useState<CanvasSelectionRect | null>(null);
|
|
83
|
+
const fitted = useRef(false);
|
|
84
|
+
const [compactControls, setCompactControls] = useState(false);
|
|
85
|
+
const [initialBackground] = useState<CanvasBackground | undefined>(defaultBackground);
|
|
86
|
+
const resolvedBackground = background ?? initialBackground ?? (grid ? "dots" : "none");
|
|
87
|
+
const [nodeGap, setNodeGap] = useState(24);
|
|
88
|
+
const [cornerRadii, setCornerRadii] = useState<CanvasCornerRadii | null>(null);
|
|
89
|
+
const defaultCornerRadius = cornerRadii ? resolveCanvasCornerRadius(edgeCornerRadius, cornerRadii) : undefined;
|
|
90
|
+
const patternScale = Number.isFinite(backgroundScale) ? Math.min(2, Math.max(.5, backgroundScale)) : .9;
|
|
91
|
+
const [metrics, setMetrics] = useState<Record<string, Metrics>>({});
|
|
92
|
+
const [viewport, setViewport] = useState<Viewport>({ x: 0, y: 0, zoom: 1 });
|
|
93
|
+
const settlement = useCanvasSettlement(root, nodes);
|
|
94
|
+
const visualNodes = useMemo(() => nodes.map(node => settlement.positions[node.id] ? { ...node, position: settlement.positions[node.id] } : node), [nodes, settlement.positions]);
|
|
95
|
+
const [localSelection, setLocalSelection] = useState<CanvasSelection>(null);
|
|
96
|
+
const selected = controlledSelection === undefined ? localSelection : controlledSelection;
|
|
97
|
+
const [pending, setPending] = useState<CanvasPort | null>(null);
|
|
98
|
+
const draftId = useRef<string | null>(null);
|
|
99
|
+
const [pointer, setPointer] = useState<Point>({ x: 0, y: 0 });
|
|
100
|
+
const [candidate, setCandidate] = useState<CanvasPort | null>(null);
|
|
101
|
+
const [hoveredNode, setHoveredNode] = useState<string | null>(null);
|
|
102
|
+
const [focusedNode, setFocusedNode] = useState<string | null>(null);
|
|
103
|
+
const [dragging, setDragging] = useState<string | null>(null);
|
|
104
|
+
const [panning, setPanning] = useState(false);
|
|
105
|
+
const [announcement, setAnnouncement] = useState("");
|
|
106
|
+
const history = useRef(new CanvasHistory());
|
|
107
|
+
const graph = useRef<CanvasGraph>({ nodes, edges });
|
|
108
|
+
const ownGraphs = useRef(new Set<string>());
|
|
109
|
+
const dragHistory = useRef<{ before: CanvasSnapshot; selection: CanvasSelection } | null>(null);
|
|
110
|
+
useLayoutEffect(() => {
|
|
111
|
+
const actual = { nodes, edges }, signature = canvasGraphSignature(actual);
|
|
112
|
+
if (signature === canvasGraphSignature(graph.current)) { graph.current = actual; ownGraphs.current.clear(); }
|
|
113
|
+
else if (!ownGraphs.current.has(signature)) {
|
|
114
|
+
graph.current = actual; ownGraphs.current.clear(); history.current.clear(); dragHistory.current = null;
|
|
115
|
+
const current = gesture.current;
|
|
116
|
+
if (current?.type === "node") {
|
|
117
|
+
gesture.current = null; setDragging(null); clearGuides();
|
|
118
|
+
if (root.current?.hasPointerCapture(current.pointerId)) root.current.releasePointerCapture(current.pointerId);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}, [nodes, edges, clearGuides]);
|
|
122
|
+
const publishGraph = (next: CanvasGraph) => {
|
|
123
|
+
const previous = graph.current;
|
|
124
|
+
const nodeChanged = canvasGraphSignature({ nodes: previous.nodes, edges: [] }) !== canvasGraphSignature({ nodes: next.nodes, edges: [] });
|
|
125
|
+
const edgeChanged = canvasGraphSignature({ nodes: [], edges: previous.edges }) !== canvasGraphSignature({ nodes: [], edges: next.edges });
|
|
126
|
+
if (!nodeChanged && !edgeChanged) return;
|
|
127
|
+
for (const value of [previous, { nodes: next.nodes, edges: previous.edges }, { nodes: previous.nodes, edges: next.edges }, next]) ownGraphs.current.add(canvasGraphSignature(value));
|
|
128
|
+
while (ownGraphs.current.size > 128) ownGraphs.current.delete(ownGraphs.current.values().next().value!);
|
|
129
|
+
graph.current = next;
|
|
130
|
+
if (nodeChanged) onNodesChange?.([...next.nodes]);
|
|
131
|
+
if (edgeChanged) onEdgesChange?.([...next.edges]);
|
|
132
|
+
};
|
|
133
|
+
const publishNodes = (next: readonly CanvasItem[]) => publishGraph({ nodes: next, edges: graph.current.edges });
|
|
134
|
+
const selectedNodeIds = new Set(canvasNodeSelectionIds(selected));
|
|
135
|
+
const selectedEdgeIds = new Set(canvasEdgeSelectionIds(selected));
|
|
136
|
+
// Final commits must follow pending preview updates, even when equal to this render.
|
|
137
|
+
const select = (value: CanvasSelection, commit = false) => { if (commit || !sameCanvasSelection(selected, value)) { setLocalSelection(value); onSelectionChange?.(value); } };
|
|
138
|
+
const selectNode = (id: string, additive = false) => {
|
|
139
|
+
if (!additive) { select({ type: "node", id }); return; }
|
|
140
|
+
const ids = canvasNodeSelectionIds(selected);
|
|
141
|
+
select(makeCanvasSelection(ids.includes(id) ? ids.filter(value => value !== id) : [...ids, id], canvasEdgeSelectionIds(selected)));
|
|
142
|
+
};
|
|
143
|
+
const selectEdge = (id: string, additive = false) => {
|
|
144
|
+
clearConnection();
|
|
145
|
+
const ids = canvasEdgeSelectionIds(selected);
|
|
146
|
+
select(additive ? makeCanvasSelection(canvasNodeSelectionIds(selected), ids.includes(id) ? ids.filter(value => value !== id) : [...ids, id]) : { type: "edge", id });
|
|
147
|
+
};
|
|
148
|
+
useEffect(() => {
|
|
149
|
+
const down = (event: globalThis.KeyboardEvent) => {
|
|
150
|
+
if (event.code !== "Space" || event.ctrlKey || event.metaKey || event.altKey || (event.target instanceof Element && event.target.closest("input, textarea, select, [contenteditable='true'], [role='textbox'], [role='slider'], [data-canvas-controls]"))) return;
|
|
151
|
+
spacePressed.current = true; setPanReady(true);
|
|
152
|
+
const element = root.current;
|
|
153
|
+
if (element && (element.contains(document.activeElement) || element.matches(":hover")) && !(event.target instanceof Element && event.target.closest("button, a, [role='button']"))) event.preventDefault();
|
|
154
|
+
};
|
|
155
|
+
const up = (event: globalThis.KeyboardEvent) => {
|
|
156
|
+
if (event.code !== "Space") return;
|
|
157
|
+
if (spaceUsedForPan.current) event.preventDefault();
|
|
158
|
+
spacePressed.current = false; spaceUsedForPan.current = false; setPanReady(false);
|
|
159
|
+
};
|
|
160
|
+
const blur = () => { spacePressed.current = false; spaceUsedForPan.current = false; setPanReady(false); cancelRef.current(); };
|
|
161
|
+
window.addEventListener("keydown", down, true); window.addEventListener("keyup", up, true); window.addEventListener("blur", blur);
|
|
162
|
+
return () => { window.removeEventListener("keydown", down, true); window.removeEventListener("keyup", up, true); window.removeEventListener("blur", blur); };
|
|
163
|
+
}, []);
|
|
164
|
+
useEffect(() => {
|
|
165
|
+
const up = (event: globalThis.PointerEvent) => {
|
|
166
|
+
if ((gesture.current?.type === "node" || gesture.current?.type === "connect") && !root.current?.hasPointerCapture(event.pointerId)) releaseRef.current(event);
|
|
167
|
+
};
|
|
168
|
+
const move = (event: globalThis.PointerEvent) => {
|
|
169
|
+
const current = gesture.current, element = root.current;
|
|
170
|
+
if ((current?.type !== "node" && current?.type !== "connect") || current.pointerId !== event.pointerId || !element || element.hasPointerCapture(event.pointerId)
|
|
171
|
+
|| (event.target instanceof Node && element.contains(event.target))) return;
|
|
172
|
+
moveRef.current(event);
|
|
173
|
+
};
|
|
174
|
+
const cancel = (event: globalThis.PointerEvent) => { if ((gesture.current?.type === "node" || gesture.current?.type === "connect") && gesture.current.pointerId === event.pointerId) cancelRef.current(); };
|
|
175
|
+
const hidden = () => { if (document.hidden && (gesture.current?.type === "node" || gesture.current?.type === "connect")) cancelRef.current(); };
|
|
176
|
+
window.addEventListener("pointerup", up, true); window.addEventListener("pointermove", move, true); window.addEventListener("pointercancel", cancel, true);
|
|
177
|
+
document.addEventListener("visibilitychange", hidden);
|
|
178
|
+
return () => {
|
|
179
|
+
window.removeEventListener("pointerup", up, true); window.removeEventListener("pointermove", move, true); window.removeEventListener("pointercancel", cancel, true);
|
|
180
|
+
document.removeEventListener("visibilitychange", hidden);
|
|
181
|
+
};
|
|
182
|
+
}, []);
|
|
183
|
+
useLayoutEffect(() => {
|
|
184
|
+
const element = root.current;
|
|
185
|
+
if (!element) return;
|
|
186
|
+
const update = () => {
|
|
187
|
+
setCompactControls(element.clientWidth < 420);
|
|
188
|
+
setSurfaceSize(previous => previous.width === element.clientWidth && previous.height === element.clientHeight ? previous : { width: element.clientWidth, height: element.clientHeight });
|
|
189
|
+
};
|
|
190
|
+
update(); const observer = new ResizeObserver(update); observer.observe(element);
|
|
191
|
+
return () => observer.disconnect();
|
|
192
|
+
}, []);
|
|
193
|
+
useLayoutEffect(() => {
|
|
194
|
+
const element = root.current;
|
|
195
|
+
if (!element) return;
|
|
196
|
+
const update = () => {
|
|
197
|
+
const style = getComputedStyle(element);
|
|
198
|
+
const read = (name: string) => parseFloat(style.getPropertyValue(`--canvas-edge-radius-${name}`));
|
|
199
|
+
const gap = parseFloat(style.getPropertyValue("--canvas-node-gap"));
|
|
200
|
+
setNodeGap(Number.isFinite(gap) && gap >= 0 ? gap : 24);
|
|
201
|
+
const guideValue = (name: string, fallback: number) => { const value = parseFloat(style.getPropertyValue(`--canvas-guide-${name}`)); return Number.isFinite(value) && value >= 0 ? value : fallback; };
|
|
202
|
+
const guides = { threshold: guideValue("threshold", 6), release: guideValue("release", 10), extension: guideValue("extension", 12) };
|
|
203
|
+
setGuideConfig(previous => previous.threshold === guides.threshold && previous.release === guides.release && previous.extension === guides.extension ? previous : guides);
|
|
204
|
+
const next = { sm: read("sm"), md: read("md"), lg: read("lg"), default: read("default") };
|
|
205
|
+
setCornerRadii(previous => previous && Object.keys(next).every(key => previous[key as keyof CanvasCornerRadii] === next[key as keyof CanvasCornerRadii]) ? previous : next);
|
|
206
|
+
};
|
|
207
|
+
update();
|
|
208
|
+
const observer = new MutationObserver(update);
|
|
209
|
+
for (let ancestor: HTMLElement | null = element; ancestor; ancestor = ancestor.parentElement) {
|
|
210
|
+
observer.observe(ancestor, { attributes: true, attributeFilter: ["data-shape", "class", "data-token-scope"] });
|
|
211
|
+
}
|
|
212
|
+
return () => observer.disconnect();
|
|
213
|
+
}, []);
|
|
214
|
+
const position = (event: { clientX: number; clientY: number }): Point => {
|
|
215
|
+
const bounds = root.current!.getBoundingClientRect();
|
|
216
|
+
return { x: (event.clientX - bounds.left - viewport.x) / viewport.zoom, y: (event.clientY - bounds.top - viewport.y) / viewport.zoom };
|
|
217
|
+
};
|
|
218
|
+
const obstacleBounds = useMemo(() => new Map(visualNodes.map(node => {
|
|
219
|
+
const measured = metrics[node.id];
|
|
220
|
+
const relativeBody = measured?.body ?? { x: 0, y: 0, width: node.shape === "card" || !node.shape ? 176 : 64, height: 64 };
|
|
221
|
+
const absolute = (bounds: CanvasEdgeObstacle) => ({ ...bounds, x: node.position.x + bounds.x, y: node.position.y + bounds.y });
|
|
222
|
+
return [node.id, { body: absolute(relativeBody), captions: (measured?.captions ?? []).map(absolute) }];
|
|
223
|
+
})), [visualNodes, metrics]);
|
|
224
|
+
const collisionRects = (node: CanvasItem, at = node.position) => {
|
|
225
|
+
const measured = metrics[node.id];
|
|
226
|
+
const body = measured?.body ?? { x: 0, y: 0, width: node.shape === "card" || !node.shape ? 176 : 64, height: 64 };
|
|
227
|
+
return [body, ...(measured?.captions ?? [])].filter(rect => rect.width > 0 && rect.height > 0)
|
|
228
|
+
.map(rect => ({ ...rect, x: rect.x + at.x, y: rect.y + at.y }));
|
|
229
|
+
};
|
|
230
|
+
const connectionObstacles = useMemo(() => {
|
|
231
|
+
const cache = new Map<string, CanvasEdgeObstacle[]>();
|
|
232
|
+
return (sourceId?: string, targetId?: string) => {
|
|
233
|
+
const key = JSON.stringify([sourceId, targetId]);
|
|
234
|
+
let obstacles = cache.get(key);
|
|
235
|
+
if (!obstacles) {
|
|
236
|
+
obstacles = [...obstacleBounds].flatMap(([id, bounds]) => id !== sourceId && id !== targetId ? [bounds.body] : []);
|
|
237
|
+
cache.set(key, obstacles);
|
|
238
|
+
}
|
|
239
|
+
return obstacles;
|
|
240
|
+
};
|
|
241
|
+
}, [obstacleBounds]);
|
|
242
|
+
const captionMaskBounds = { x: (-viewport.x - 32) / viewport.zoom, y: (-viewport.y - 32) / viewport.zoom,
|
|
243
|
+
width: (surfaceSize.width + 64) / viewport.zoom, height: (surfaceSize.height + 64) / viewport.zoom };
|
|
244
|
+
const endpoint = (port: CanvasPort): CanvasEdgeEndpoint | null => {
|
|
245
|
+
const node = visualNodes.find(node => node.id === port.nodeId);
|
|
246
|
+
const offset = metrics[port.nodeId]?.ports[port.side];
|
|
247
|
+
return node && offset ? { x: node.position.x + offset.x, y: node.position.y + offset.y, side: port.side, bounds: obstacleBounds.get(node.id)?.body } : null;
|
|
248
|
+
};
|
|
249
|
+
const fit = useCallback((initial = false) => {
|
|
250
|
+
if (!root.current || !nodes.length) { setViewport({ x: 0, y: 0, zoom: 1 }); return; }
|
|
251
|
+
const routes = [...root.current.querySelectorAll<SVGPathElement>("[data-canvas-edge-id] [data-edge-part='track']")]
|
|
252
|
+
.map(path => path.getBBox()).filter(bounds => [bounds.x, bounds.y, bounds.width, bounds.height].every(Number.isFinite));
|
|
253
|
+
const left = Math.min(...nodes.map(n => n.position.x), ...routes.map(bounds => bounds.x));
|
|
254
|
+
const top = Math.min(...nodes.map(n => n.position.y), ...routes.map(bounds => bounds.y));
|
|
255
|
+
const right = Math.max(...nodes.map(n => n.position.x + (metrics[n.id]?.width ?? 176)), ...routes.map(bounds => bounds.x + bounds.width));
|
|
256
|
+
const bottom = Math.max(...nodes.map(n => n.position.y + (metrics[n.id]?.height ?? 96)), ...routes.map(bounds => bounds.y + bounds.height));
|
|
257
|
+
const { width, height } = root.current.getBoundingClientRect();
|
|
258
|
+
const padding = width < 420 ? 32 : 80;
|
|
259
|
+
const topInset = 32;
|
|
260
|
+
const bottomInset = controls ? 72 : 32;
|
|
261
|
+
const workHeight = Math.max(1, height - topInset - bottomInset);
|
|
262
|
+
const leftInset = padding / 2;
|
|
263
|
+
const rightInset = controls && controlsOrientation === "vertical"
|
|
264
|
+
? Math.max(leftInset, (root.current.querySelector<HTMLElement>("[data-canvas-controls='view']")?.offsetWidth ?? 48) + 32)
|
|
265
|
+
: leftInset;
|
|
266
|
+
const workWidth = Math.max(1, width - leftInset - rightInset);
|
|
267
|
+
const zoom = Math.max(initial ? .85 : .25, Math.min(1, workWidth / Math.max(1, right - left), workHeight / Math.max(1, bottom - top)));
|
|
268
|
+
setViewport({ x: leftInset + (workWidth - (right - left) * zoom) / 2 - left * zoom, y: topInset + (workHeight - (bottom - top) * zoom) / 2 - top * zoom, zoom });
|
|
269
|
+
}, [nodes, metrics, controls, controlsOrientation]);
|
|
270
|
+
const nodeSignature = nodes.map(n => `${n.id}:${n.shape}:${n.title}:${n.description}:${n.status}:${(n.ports ?? ["left", "right"]).join()}`).join("|");
|
|
271
|
+
useLayoutEffect(() => {
|
|
272
|
+
const measure = () => {
|
|
273
|
+
const next: Record<string, Metrics> = Object.create(null);
|
|
274
|
+
nodeElements.current.forEach((element, id) => {
|
|
275
|
+
const bounds = element.getBoundingClientRect();
|
|
276
|
+
const ports: Metrics["ports"] = {};
|
|
277
|
+
element.querySelectorAll<HTMLElement>("[data-side]").forEach(port => {
|
|
278
|
+
const r = port.getBoundingClientRect();
|
|
279
|
+
ports[port.dataset.side as CanvasNodePortSide] = { x: (r.left + r.width / 2 - bounds.left) / viewport.zoom, y: (r.top + r.height / 2 - bounds.top) / viewport.zoom };
|
|
280
|
+
});
|
|
281
|
+
const relative = (child: Element): CanvasEdgeObstacle => {
|
|
282
|
+
const r = child.getBoundingClientRect();
|
|
283
|
+
return { x: (r.left - bounds.left) / viewport.zoom, y: (r.top - bounds.top) / viewport.zoom, width: r.width / viewport.zoom, height: r.height / viewport.zoom };
|
|
284
|
+
};
|
|
285
|
+
const children = [...element.children];
|
|
286
|
+
const body = children[0] ? relative(children[0]) : { x: 0, y: 0, width: bounds.width / viewport.zoom, height: bounds.height / viewport.zoom };
|
|
287
|
+
const captions = children.slice(1).map(relative).filter(r => r.width > 1 && r.height > 1);
|
|
288
|
+
next[id] = { width: bounds.width / viewport.zoom, height: bounds.height / viewport.zoom, body, captions, ports };
|
|
289
|
+
});
|
|
290
|
+
setMetrics(previous => JSON.stringify(previous) === JSON.stringify(next) ? previous : next);
|
|
291
|
+
};
|
|
292
|
+
measure();
|
|
293
|
+
const observer = new ResizeObserver(measure);
|
|
294
|
+
nodeElements.current.forEach(element => { observer.observe(element); for (const child of element.children) observer.observe(child); });
|
|
295
|
+
return () => observer.disconnect();
|
|
296
|
+
// Positions do not change a node's measured size or relative port offsets.
|
|
297
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
298
|
+
}, [nodeSignature, viewport.zoom]);
|
|
299
|
+
useLayoutEffect(() => {
|
|
300
|
+
if (!nodes.length || fitted.current || nodes.some(n => !metrics[n.id])) return;
|
|
301
|
+
fitted.current = true; fit(true);
|
|
302
|
+
}, [nodes, metrics, fit]);
|
|
303
|
+
useLayoutEffect(() => {
|
|
304
|
+
const element = root.current;
|
|
305
|
+
if (!element) return;
|
|
306
|
+
const wheel = (event: WheelEvent) => {
|
|
307
|
+
if ((!event.ctrlKey && !event.metaKey) || gesture.current) return;
|
|
308
|
+
event.preventDefault();
|
|
309
|
+
const bounds = element.getBoundingClientRect();
|
|
310
|
+
setViewport(v => {
|
|
311
|
+
const zoom = Math.max(.25, Math.min(2, v.zoom * Math.exp(-event.deltaY * .01)));
|
|
312
|
+
const x = event.clientX - bounds.left, y = event.clientY - bounds.top;
|
|
313
|
+
return { x: x - (x - v.x) * zoom / v.zoom, y: y - (y - v.y) * zoom / v.zoom, zoom };
|
|
314
|
+
});
|
|
315
|
+
};
|
|
316
|
+
element.addEventListener("wheel", wheel, { passive: false });
|
|
317
|
+
return () => element.removeEventListener("wheel", wheel);
|
|
318
|
+
}, []);
|
|
319
|
+
useEffect(() => {
|
|
320
|
+
const current = gesture.current;
|
|
321
|
+
const lockedNode = current?.type === "node" && (readOnly || !onNodesChange || !nodes.some(n => n.id === current.id && !n.disabled));
|
|
322
|
+
const lockedConnection = current?.type === "connect" && (readOnly || !onEdgesChange);
|
|
323
|
+
if (lockedNode || lockedConnection) {
|
|
324
|
+
gesture.current = null; dragHistory.current = null; setDragging(null); clearGuides();
|
|
325
|
+
if (root.current?.hasPointerCapture(current.pointerId)) root.current.releasePointerCapture(current.pointerId);
|
|
326
|
+
}
|
|
327
|
+
if (pending && (readOnly || !onEdgesChange || !nodes.some(n => n.id === pending.nodeId && !n.disabled && (n.ports ?? ["left", "right"]).includes(pending.side)))) {
|
|
328
|
+
draftId.current = null; setPending(null); setCandidate(null); gesture.current = null;
|
|
329
|
+
}
|
|
330
|
+
}, [pending, readOnly, onEdgesChange, onNodesChange, nodes, clearGuides]);
|
|
331
|
+
const valid = (source: CanvasPort, target: CanvasPort) => canConnectCanvas(nodes, edges, { source, target }) && (isValidConnection?.({ source, target }) ?? true);
|
|
332
|
+
const nearest = (point: Point, source: CanvasPort): CanvasPort | null => {
|
|
333
|
+
let best: CanvasPort | null = null, distance = 20 / Math.max(1, viewport.zoom);
|
|
334
|
+
for (const node of nodes) for (const side of node.ports ?? ["left", "right"] as const) {
|
|
335
|
+
const port = { nodeId: node.id, side }, at = endpoint(port);
|
|
336
|
+
if (!at || !valid(source, port)) continue;
|
|
337
|
+
const d = Math.hypot(point.x - at.x, point.y - at.y);
|
|
338
|
+
if (d < distance) { distance = d; best = port; }
|
|
339
|
+
}
|
|
340
|
+
return best;
|
|
341
|
+
};
|
|
342
|
+
const clearConnection = (cancelled = false) => { draftId.current = null; setPending(null); setCandidate(null); if (cancelled) setAnnouncement(text.cancelled); };
|
|
343
|
+
const connect = (source: CanvasPort, target: CanvasPort) => {
|
|
344
|
+
if (readOnly || !onEdgesChange || !valid(source, target)) return false;
|
|
345
|
+
const id = draftId.current ?? `edge-${crypto.randomUUID()}`;
|
|
346
|
+
const before = snapshotCanvasGraph(graph.current, selected), selection: CanvasSelection = { type: "edge", id };
|
|
347
|
+
publishGraph({ nodes: graph.current.nodes, edges: [...graph.current.edges, { id, source, target }] });
|
|
348
|
+
history.current.record(before, snapshotCanvasGraph(graph.current, selection));
|
|
349
|
+
select(selection); clearConnection(); setAnnouncement(text.connected); return true;
|
|
350
|
+
};
|
|
351
|
+
const cancelGesture = (rollback = true) => {
|
|
352
|
+
const current = gesture.current;
|
|
353
|
+
gesture.current = null;
|
|
354
|
+
if (current?.type === "node" && (current.moved || current.needsSettlement)) {
|
|
355
|
+
if (rollback) {
|
|
356
|
+
const origins = current.restoreOrigins ?? current.origins;
|
|
357
|
+
publishNodes(nodes.map(n => origins[n.id] && !n.disabled ? { ...n, position: origins[n.id] } : n));
|
|
358
|
+
} else {
|
|
359
|
+
const last = current.last ?? current.start;
|
|
360
|
+
moveNodes(current.id, current.origins, { x: (last.x - current.start.x) / viewport.zoom, y: (last.y - current.start.y) / viewport.zoom }, "drop");
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
if (current?.type === "node" && rollback) dragHistory.current = null;
|
|
364
|
+
if (current?.type === "marquee") select(current.previous, true);
|
|
365
|
+
if (current?.type === "pan" && rollback) setViewport(current.origin);
|
|
366
|
+
gesture.current = null;
|
|
367
|
+
if (current && root.current?.hasPointerCapture(current.pointerId)) root.current.releasePointerCapture(current.pointerId);
|
|
368
|
+
setDragging(null); setPanning(false); setMarquee(null); clearGuides(); clearConnection(!!pending);
|
|
369
|
+
};
|
|
370
|
+
cancelRef.current = () => cancelGesture(false);
|
|
371
|
+
const interruptGesture = (event: PointerEvent<HTMLDivElement>) => {
|
|
372
|
+
const current = gesture.current;
|
|
373
|
+
if (!current || event.pointerId !== current.pointerId) return;
|
|
374
|
+
// A child's implicit capture loss must not cancel the root's active gesture.
|
|
375
|
+
if (event.type === "lostpointercapture" && (event.target !== event.currentTarget || event.currentTarget.hasPointerCapture(event.pointerId))) return;
|
|
376
|
+
// Node moves and connections can finish via window listeners after capture loss.
|
|
377
|
+
if (event.type === "lostpointercapture" && (current.type === "node" || current.type === "connect")) return;
|
|
378
|
+
// Browser/OS interruption keeps the last node/pan position. Escape rolls back.
|
|
379
|
+
cancelGesture(false);
|
|
380
|
+
};
|
|
381
|
+
const capture = (event: PointerEvent, next: Gesture) => {
|
|
382
|
+
clearGuides(); gesture.current = { ...next, last: next.start }; root.current?.setPointerCapture(event.pointerId);
|
|
383
|
+
};
|
|
384
|
+
const portDown = (event: PointerEvent<HTMLButtonElement>, port: CanvasPort) => {
|
|
385
|
+
if (!event.isPrimary || event.button !== 0 || gesture.current) return;
|
|
386
|
+
event.preventDefault(); event.stopPropagation(); event.currentTarget.focus();
|
|
387
|
+
if (pending && samePort(pending, port)) { clearConnection(true); return; }
|
|
388
|
+
const source = pending ?? port;
|
|
389
|
+
if (!pending) { draftId.current = `edge-${crypto.randomUUID()}`; setPending(port); const at = endpoint(port); if (at) setPointer(at); setAnnouncement(text.connecting); }
|
|
390
|
+
capture(event, { type: "connect", pointerId: event.pointerId, start: { x: event.clientX, y: event.clientY }, moved: false, source });
|
|
391
|
+
};
|
|
392
|
+
const nodeDown = (event: PointerEvent, node: CanvasItem) => {
|
|
393
|
+
if (!event.isPrimary || event.button !== 0 || gesture.current || node.disabled || (event.target as Element).closest("[data-canvas-port]")) return;
|
|
394
|
+
event.preventDefault(); event.stopPropagation(); clearConnection(); suppressClick.current = true;
|
|
395
|
+
nodeElements.current.get(node.id)?.querySelector<HTMLButtonElement>("button")?.focus({ preventScroll: true });
|
|
396
|
+
const ids = canvasNodeSelectionIds(selected);
|
|
397
|
+
if (event.shiftKey) { selectNode(node.id, true); return; }
|
|
398
|
+
const group = ids.includes(node.id) ? ids : [node.id];
|
|
399
|
+
if (!ids.includes(node.id)) select({ type: "node", id: node.id });
|
|
400
|
+
if (readOnly || !onNodesChange) return;
|
|
401
|
+
dragHistory.current = { before: snapshotCanvasGraph(graph.current, selected), selection: makeCanvasSelection(group, ids.includes(node.id) ? canvasEdgeSelectionIds(selected) : []) };
|
|
402
|
+
const interrupted = group.some(id => settlement.positions[id]) ? settlement.stop(group) : null;
|
|
403
|
+
const originals: Record<string, Point> = Object.assign(Object.create(null), Object.fromEntries(nodes.filter(n => group.includes(n.id) && !n.disabled).map(n => [n.id, n.position])));
|
|
404
|
+
const origins: Record<string, Point> = Object.assign(Object.create(null), Object.fromEntries(nodes.filter(n => group.includes(n.id) && !n.disabled).map(n => [n.id, interrupted?.current[n.id] ?? n.position])));
|
|
405
|
+
if (interrupted) publishNodes(nodes.map(n => origins[n.id] ? { ...n, position: origins[n.id] } : n));
|
|
406
|
+
capture(event, { type: "node", id: node.id, origins, needsSettlement: !!interrupted, restoreOrigins: interrupted ? originals : undefined, collapseOnClick: group.length > 1 || selected?.type === "group", start: { x: event.clientX, y: event.clientY }, moved: false, pointerId: event.pointerId });
|
|
407
|
+
};
|
|
408
|
+
const updateMarquee = (current: Extract<Gesture, { type: "marquee" }>, point: Point, commit = false) => {
|
|
409
|
+
const rect = canvasSelectionRect(current.anchor, point);
|
|
410
|
+
const bodies = new Map([...obstacleBounds].map(([id, bounds]) => [id, bounds.body]));
|
|
411
|
+
const hits = canvasNodesInRect(nodes, bodies, rect);
|
|
412
|
+
const hitNodes = new Set(hits);
|
|
413
|
+
const paths = new Map<string, SVGPathElement>();
|
|
414
|
+
root.current?.querySelectorAll<SVGGElement>("[data-canvas-edge-id]").forEach(element => {
|
|
415
|
+
const path = element.querySelector<SVGPathElement>("[data-edge-part='track']");
|
|
416
|
+
if (path) paths.set(element.dataset.canvasEdgeId!, path);
|
|
417
|
+
});
|
|
418
|
+
const hitEdges = edges.filter(edge => !edge.disabled && ((hitNodes.has(edge.source.nodeId) && hitNodes.has(edge.target.nodeId))
|
|
419
|
+
|| (paths.has(edge.id) && canvasPathIntersectsRect(paths.get(edge.id)!, rect)))).map(edge => edge.id);
|
|
420
|
+
select(makeCanvasSelection(current.additive ? [...canvasNodeSelectionIds(current.previous), ...hits] : hits,
|
|
421
|
+
current.additive ? [...canvasEdgeSelectionIds(current.previous), ...hitEdges] : hitEdges), commit);
|
|
422
|
+
setMarquee(rect);
|
|
423
|
+
};
|
|
424
|
+
const moveNodes = (id: string, origins: Record<string, Point>, desired: Point, phase: "preview" | "drop" | "step" = "step") => {
|
|
425
|
+
if (readOnly || !onNodesChange || !nodes.some(node => node.id === id && !node.disabled)) return;
|
|
426
|
+
const before = phase === "step" ? snapshotCanvasGraph(graph.current, selected) : null;
|
|
427
|
+
const moving = nodes.filter(node => origins[node.id] && !node.disabled);
|
|
428
|
+
const movingIds = new Set(moving.map(node => node.id));
|
|
429
|
+
const movingRects = moving.flatMap(node => collisionRects(node, origins[node.id]));
|
|
430
|
+
const fixedRects = nodes.filter(node => !movingIds.has(node.id)).flatMap(node => collisionRects(node));
|
|
431
|
+
let delta = desired;
|
|
432
|
+
if (phase !== "step") {
|
|
433
|
+
const body = (node: CanvasItem, at = node.position) => ({ id: node.id, ...collisionRects(node, at)[0] });
|
|
434
|
+
const aligned = alignCanvasNodes(moving.map(node => body(node, origins[node.id])), nodes.filter(node => !movingIds.has(node.id)).map(node => body(node)), desired, viewport.zoom, guideConfig, guideLatch.current);
|
|
435
|
+
delta = aligned.delta; guideLatch.current = aligned.guides;
|
|
436
|
+
if (phase === "preview") setGuides(aligned.guides);
|
|
437
|
+
}
|
|
438
|
+
const intended = delta;
|
|
439
|
+
if (phase === "drop") {
|
|
440
|
+
const correction = findCanvasPlacement(movingRects.map(rect => ({ ...rect, x: rect.x + intended.x, y: rect.y + intended.y })), fixedRects, nodeGap);
|
|
441
|
+
delta = { x: intended.x + correction.x, y: intended.y + correction.y };
|
|
442
|
+
if (Math.abs(correction.x) + Math.abs(correction.y) > 1e-7) {
|
|
443
|
+
settlement.start(Object.fromEntries(moving.map(node => [node.id, { x: origins[node.id].x + intended.x, y: origins[node.id].y + intended.y }])),
|
|
444
|
+
Object.fromEntries(moving.map(node => [node.id, { x: origins[node.id].x + delta.x, y: origins[node.id].y + delta.y }])));
|
|
445
|
+
}
|
|
446
|
+
} else if (phase === "step") delta = constrainCanvasMovement(movingRects, fixedRects, desired, nodeGap);
|
|
447
|
+
publishNodes(nodes.map(node => movingIds.has(node.id) ? { ...node, position: {
|
|
448
|
+
x: origins[node.id].x + delta.x, y: origins[node.id].y + delta.y,
|
|
449
|
+
} } : node));
|
|
450
|
+
if (phase === "drop" && dragHistory.current) {
|
|
451
|
+
history.current.record(dragHistory.current.before, snapshotCanvasGraph(graph.current, dragHistory.current.selection));
|
|
452
|
+
dragHistory.current = null;
|
|
453
|
+
} else if (before) history.current.record(before, snapshotCanvasGraph(graph.current,
|
|
454
|
+
makeCanvasSelection(Object.keys(origins), selectedNodeIds.has(id) ? canvasEdgeSelectionIds(selected) : [])));
|
|
455
|
+
};
|
|
456
|
+
const trackPointer = (event: GesturePointer) => {
|
|
457
|
+
if (![event.clientX, event.clientY].every(Number.isFinite)) return;
|
|
458
|
+
const current = gesture.current;
|
|
459
|
+
const point = position(event);
|
|
460
|
+
if (!current) { if (pending) { setPointer(point); setCandidate(nearest(point, pending)); } return; }
|
|
461
|
+
if (current.pointerId !== event.pointerId) return;
|
|
462
|
+
current.last = { x: event.clientX, y: event.clientY };
|
|
463
|
+
if (current.type === "node" && (readOnly || !onNodesChange || !nodes.some(n => n.id === current.id && !n.disabled))) return;
|
|
464
|
+
if (current.type === "connect" && (readOnly || !onEdgesChange)) return;
|
|
465
|
+
const dx = event.clientX - current.start.x, dy = event.clientY - current.start.y;
|
|
466
|
+
current.moved ||= Math.hypot(dx, dy) > 3;
|
|
467
|
+
if (current.type === "connect") { setPointer(point); setCandidate(nearest(point, current.source)); }
|
|
468
|
+
if (!current.moved) return;
|
|
469
|
+
if (current.type === "node") {
|
|
470
|
+
setDragging(current.id); suppressClick.current = true;
|
|
471
|
+
moveNodes(current.id, current.origins, { x: dx / viewport.zoom, y: dy / viewport.zoom }, "preview");
|
|
472
|
+
}
|
|
473
|
+
if (current.type === "marquee") { suppressClick.current = true; updateMarquee(current, point); }
|
|
474
|
+
if (current.type === "pan") { setPanning(true); setViewport({ ...current.origin, x: current.origin.x + dx, y: current.origin.y + dy }); }
|
|
475
|
+
};
|
|
476
|
+
moveRef.current = trackPointer;
|
|
477
|
+
const move = (event: PointerEvent) => { if (event.currentTarget.contains(event.target as Node)) trackPointer(event); };
|
|
478
|
+
const release = (event: GesturePointer) => {
|
|
479
|
+
const current = gesture.current;
|
|
480
|
+
if (!current || current.pointerId !== event.pointerId) return;
|
|
481
|
+
// Fast releases can arrive before the last pointermove is handled.
|
|
482
|
+
// Commit the final position/selection from pointerup for every gesture.
|
|
483
|
+
const dx = event.clientX - current.start.x, dy = event.clientY - current.start.y;
|
|
484
|
+
current.moved ||= Math.hypot(dx, dy) > 3;
|
|
485
|
+
gesture.current = null; setDragging(null); setPanning(false); setMarquee(null);
|
|
486
|
+
if (current.type === "marquee") {
|
|
487
|
+
if (current.moved) { suppressClick.current = true; updateMarquee(current, position(event), true); }
|
|
488
|
+
else if (!current.additive) select(null, true);
|
|
489
|
+
setMarquee(null);
|
|
490
|
+
}
|
|
491
|
+
if (current.type === "node") {
|
|
492
|
+
if (current.moved || current.needsSettlement) { suppressClick.current = true; moveNodes(current.id, current.origins, { x: dx / viewport.zoom, y: dy / viewport.zoom }, "drop"); }
|
|
493
|
+
else { dragHistory.current = null; if (current.collapseOnClick) select({ type: "node", id: current.id }); }
|
|
494
|
+
}
|
|
495
|
+
if (current.type === "pan") {
|
|
496
|
+
if (current.moved) setViewport({ ...current.origin, x: current.origin.x + dx, y: current.origin.y + dy });
|
|
497
|
+
else if (current.clearOnClick) select(null);
|
|
498
|
+
}
|
|
499
|
+
if (current.type === "connect") {
|
|
500
|
+
const target = nearest(position(event), current.source);
|
|
501
|
+
if (target) connect(current.source, target);
|
|
502
|
+
else if (current.moved) clearConnection(true);
|
|
503
|
+
if (current.moved) { suppressClick.current = true; root.current?.focus({ preventScroll: true }); }
|
|
504
|
+
}
|
|
505
|
+
clearGuides();
|
|
506
|
+
if (root.current?.hasPointerCapture(event.pointerId)) root.current.releasePointerCapture(event.pointerId);
|
|
507
|
+
};
|
|
508
|
+
releaseRef.current = release;
|
|
509
|
+
const remove = () => {
|
|
510
|
+
if (readOnly || !selected) return;
|
|
511
|
+
const nodeIds = canvasNodeSelectionIds(selected);
|
|
512
|
+
if (nodeIds.length && (!onNodesChange || !onEdgesChange)) return;
|
|
513
|
+
const ids = new Set(nodeIds.filter(id => !nodes.find(n => n.id === id)?.disabled));
|
|
514
|
+
const edgeIds = new Set(canvasEdgeSelectionIds(selected).filter(id => !edges.find(edge => edge.id === id)?.disabled));
|
|
515
|
+
if (!onEdgesChange) return;
|
|
516
|
+
const before = snapshotCanvasGraph(graph.current, selected);
|
|
517
|
+
publishGraph({ nodes: ids.size ? nodes.filter(node => !ids.has(node.id)) : graph.current.nodes,
|
|
518
|
+
edges: edges.filter(edge => !edgeIds.has(edge.id) && !ids.has(edge.source.nodeId) && !ids.has(edge.target.nodeId)) });
|
|
519
|
+
history.current.record(before, snapshotCanvasGraph(graph.current, null));
|
|
520
|
+
select(null);
|
|
521
|
+
clearConnection();
|
|
522
|
+
};
|
|
523
|
+
const clipboardTarget = (event: ClipboardEvent<HTMLDivElement>) => event.currentTarget.contains(event.target as Node)
|
|
524
|
+
&& !(event.target as Element).closest("input, textarea, select, [contenteditable]:not([contenteditable='false']), [role='textbox']");
|
|
525
|
+
const copy = (event: ClipboardEvent<HTMLDivElement>) => {
|
|
526
|
+
rest.onCopy?.(event);
|
|
527
|
+
if (event.defaultPrevented || !clipboardTarget(event) || gesture.current || window.getSelection()?.toString()) return;
|
|
528
|
+
const snapshot = snapshotCanvasSelection(nodes, edges, canvasNodeSelectionIds(selected), new Map(nodes.map(node => [node.id, collisionRects(node)])));
|
|
529
|
+
if (!snapshot.nodes.length) return;
|
|
530
|
+
const token = storeCanvasClipboard(snapshot);
|
|
531
|
+
event.clipboardData.setData("text/plain", token);
|
|
532
|
+
event.preventDefault(); event.stopPropagation();
|
|
533
|
+
};
|
|
534
|
+
const paste = (event: ClipboardEvent<HTMLDivElement>) => {
|
|
535
|
+
rest.onPaste?.(event);
|
|
536
|
+
if (event.defaultPrevented || !clipboardTarget(event) || gesture.current || readOnly || !onNodesChange || !onEdgesChange) return;
|
|
537
|
+
const snapshot = readCanvasClipboard(event.clipboardData.getData("text/plain"));
|
|
538
|
+
if (!snapshot) return;
|
|
539
|
+
event.preventDefault(); event.stopPropagation(); clearConnection();
|
|
540
|
+
const displacement = findCanvasPlacement(snapshot.nodes.flatMap(node => snapshot.footprints?.[node.id]?.length ? snapshot.footprints[node.id] : collisionRects(node)),
|
|
541
|
+
nodes.flatMap(node => collisionRects(node)), nodeGap);
|
|
542
|
+
const pastedNodes = snapshot.nodes.map(node => ({ ...node, position: { x: node.position.x + displacement.x, y: node.position.y + displacement.y } }));
|
|
543
|
+
const before = snapshotCanvasGraph(graph.current, selected);
|
|
544
|
+
const selection = makeCanvasSelection(snapshot.nodes.map(node => node.id), snapshot.edges.map(edge => edge.id));
|
|
545
|
+
publishGraph({ nodes: [...graph.current.nodes, ...pastedNodes], edges: [...graph.current.edges, ...snapshot.edges] });
|
|
546
|
+
history.current.record(before, snapshotCanvasGraph(graph.current, selection));
|
|
547
|
+
select(selection);
|
|
548
|
+
const element = root.current;
|
|
549
|
+
if (element) {
|
|
550
|
+
const bounds = pastedNodes.map(node => ({ ...node.position, width: node.shape === "card" || !node.shape ? 176 : 64, height: 64 }));
|
|
551
|
+
const visible = bounds.some(body => body.x * viewport.zoom + viewport.x < element.clientWidth && (body.x + body.width) * viewport.zoom + viewport.x > 0
|
|
552
|
+
&& body.y * viewport.zoom + viewport.y < element.clientHeight && (body.y + body.height) * viewport.zoom + viewport.y > 0);
|
|
553
|
+
if (!visible) {
|
|
554
|
+
const left = Math.min(...bounds.map(body => body.x)), right = Math.max(...bounds.map(body => body.x + body.width));
|
|
555
|
+
const top = Math.min(...bounds.map(body => body.y)), bottom = Math.max(...bounds.map(body => body.y + body.height));
|
|
556
|
+
setViewport({ ...viewport, x: element.clientWidth / 2 - (left + right) / 2 * viewport.zoom, y: element.clientHeight / 2 - (top + bottom) / 2 * viewport.zoom });
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
};
|
|
560
|
+
const travelHistory = (redo: boolean) => {
|
|
561
|
+
if (readOnly) return;
|
|
562
|
+
if (gesture.current || pending) { cancelGesture(); return; }
|
|
563
|
+
const snapshot = history.current.peek(redo);
|
|
564
|
+
if (!snapshot) return;
|
|
565
|
+
const restored = restoreCanvasGraph(snapshot, graph.current);
|
|
566
|
+
const nodeChange = canvasGraphSignature({ nodes: restored.nodes, edges: [] }) !== canvasGraphSignature({ nodes: graph.current.nodes, edges: [] });
|
|
567
|
+
const edgeChange = canvasGraphSignature({ nodes: [], edges: restored.edges }) !== canvasGraphSignature({ nodes: [], edges: graph.current.edges });
|
|
568
|
+
if (nodeChange && !onNodesChange || edgeChange && !onEdgesChange) return;
|
|
569
|
+
history.current.take(redo); settlement.stop(); clearGuides(); clearConnection(); suppressClick.current = true;
|
|
570
|
+
publishGraph(restored); select(restored.selection, true);
|
|
571
|
+
};
|
|
572
|
+
const keyDown = (event: KeyboardEvent<HTMLDivElement>) => {
|
|
573
|
+
if (!event.currentTarget.contains(event.target as Node)) return;
|
|
574
|
+
onKeyDown?.(event); if (event.defaultPrevented) return;
|
|
575
|
+
if ((event.target as Element).closest("input, textarea, select, [contenteditable]:not([contenteditable='false']), [role='textbox']")) return;
|
|
576
|
+
if ((event.metaKey || event.ctrlKey) && !event.altKey && event.key.toLowerCase() === "z") {
|
|
577
|
+
event.preventDefault(); event.stopPropagation(); travelHistory(event.shiftKey); return;
|
|
578
|
+
}
|
|
579
|
+
if (event.key === "Escape") { event.preventDefault(); cancelGesture(); return; }
|
|
580
|
+
if ((event.target as Element).closest("[data-canvas-controls], [data-canvas-port]")) return;
|
|
581
|
+
if (event.key === "Delete" || event.key === "Backspace") { event.preventDefault(); remove(); return; }
|
|
582
|
+
const element = (event.target as Element).closest<HTMLElement>("[data-canvas-item]");
|
|
583
|
+
const node = nodes.find(n => n.id === element?.dataset.canvasItem);
|
|
584
|
+
if (!node || node.disabled) return;
|
|
585
|
+
if (event.shiftKey && (event.key === "Enter" || event.key === " ")) { event.preventDefault(); event.stopPropagation(); selectNode(node.id, true); return; }
|
|
586
|
+
if (readOnly || !onNodesChange) return;
|
|
587
|
+
const delta: Record<string, Point> = { ArrowLeft: { x: -1, y: 0 }, ArrowRight: { x: 1, y: 0 }, ArrowUp: { x: 0, y: -1 }, ArrowDown: { x: 0, y: 1 } };
|
|
588
|
+
if (!delta[event.key]) return;
|
|
589
|
+
event.preventDefault(); const step = event.shiftKey ? 24 : 8;
|
|
590
|
+
const ids = selectedNodeIds.has(node.id) ? selectedNodeIds : new Set([node.id]);
|
|
591
|
+
if (!selectedNodeIds.has(node.id)) select({ type: "node", id: node.id });
|
|
592
|
+
const origins = Object.assign(Object.create(null), Object.fromEntries(nodes.filter(item => ids.has(item.id) && !item.disabled).map(item => [item.id, item.position])));
|
|
593
|
+
moveNodes(node.id, origins, { x: delta[event.key].x * step, y: delta[event.key].y * step });
|
|
594
|
+
};
|
|
595
|
+
const setZoom = (value: number) => {
|
|
596
|
+
if (!root.current || gesture.current) return;
|
|
597
|
+
const { width, height } = root.current.getBoundingClientRect();
|
|
598
|
+
setViewport(v => {
|
|
599
|
+
const next = Math.max(.25, Math.min(2, value));
|
|
600
|
+
return { x: width / 2 - (width / 2 - v.x) * next / v.zoom, y: height / 2 - (height / 2 - v.y) * next / v.zoom, zoom: next };
|
|
601
|
+
});
|
|
602
|
+
};
|
|
603
|
+
const zoomInButton = <IconButton icon={<Icon name="plus" />} aria-label={text.zoomIn} title={text.zoomIn} onClick={() => setZoom(viewport.zoom * 1.2)} disabled={viewport.zoom >= 2} />;
|
|
604
|
+
const zoomOutButton = <IconButton icon={<Icon name="minus" />} aria-label={text.zoomOut} title={text.zoomOut} onClick={() => setZoom(viewport.zoom / 1.2)} disabled={viewport.zoom <= .25} />;
|
|
605
|
+
const from = pending && endpoint(pending);
|
|
606
|
+
const to = candidate && endpoint(candidate);
|
|
607
|
+
return <div {...rest} ref={root} data-slot="canvas" data-background={resolvedBackground} data-panning={panning || undefined}
|
|
608
|
+
data-connecting={!!pending || undefined} data-pan-ready={panReady || undefined} data-selecting={!!marquee || undefined} className={[styles.root, className].filter(Boolean).join(" ")}
|
|
609
|
+
role="region" aria-label={rest["aria-label"] ?? text.canvas} aria-describedby={[rest["aria-describedby"], helpId].filter(Boolean).join(" ")} tabIndex={0}
|
|
610
|
+
onKeyDown={keyDown} onCopy={copy} onPaste={paste}
|
|
611
|
+
onClickCapture={event => { if (suppressClick.current && event.detail > 0) { event.preventDefault(); event.stopPropagation(); suppressClick.current = false; return; } rest.onClickCapture?.(event); }}
|
|
612
|
+
onPointerDownCapture={event => {
|
|
613
|
+
rest.onPointerDownCapture?.(event);
|
|
614
|
+
if (event.defaultPrevented || !event.currentTarget.contains(event.target as Node) || !event.isPrimary || gesture.current) return;
|
|
615
|
+
suppressClick.current = false;
|
|
616
|
+
if ((event.target as Element).closest("[data-canvas-controls]")) return;
|
|
617
|
+
if (event.button !== 1 && !(event.button === 0 && spacePressed.current)) return;
|
|
618
|
+
event.preventDefault(); event.stopPropagation(); root.current?.focus({ preventScroll: true }); clearConnection(!!pending);
|
|
619
|
+
suppressClick.current = true; spaceUsedForPan.current ||= spacePressed.current;
|
|
620
|
+
capture(event, { type: "pan", pointerId: event.pointerId, moved: false, start: { x: event.clientX, y: event.clientY }, origin: viewport });
|
|
621
|
+
}}
|
|
622
|
+
onPointerMove={move} onPointerUp={release} onPointerCancel={interruptGesture}
|
|
623
|
+
onLostPointerCapture={interruptGesture}
|
|
624
|
+
onDragStartCapture={event => { rest.onDragStartCapture?.(event); event.preventDefault(); }}
|
|
625
|
+
onPointerDown={event => {
|
|
626
|
+
if (!event.currentTarget.contains(event.target as Node)) return;
|
|
627
|
+
if (!event.isPrimary || (event.button !== 0 && event.button !== 1) || gesture.current || (event.target as Element).closest("button, [data-slot='canvas-edge'], [data-canvas-item]")) return;
|
|
628
|
+
event.preventDefault(); root.current?.focus({ preventScroll: true }); clearConnection(!!pending);
|
|
629
|
+
if (event.pointerType === "touch") capture(event, { type: "pan", pointerId: event.pointerId, moved: false, start: { x: event.clientX, y: event.clientY }, origin: viewport, clearOnClick: true });
|
|
630
|
+
else capture(event, { type: "marquee", pointerId: event.pointerId, moved: false, start: { x: event.clientX, y: event.clientY }, anchor: position(event), previous: selected, additive: event.shiftKey });
|
|
631
|
+
}}
|
|
632
|
+
style={{ ...rest.style, "--canvas-zoom": viewport.zoom, "--canvas-background-scale": patternScale, "--canvas-grid-x": `${viewport.x}px`, "--canvas-grid-y": `${viewport.y}px` } as CSSProperties}>
|
|
633
|
+
<p id={helpId} className={styles.srOnly}>{text.instructions}</p>
|
|
634
|
+
<span className={styles.srOnly} role="status" aria-live="polite">{announcement}</span>
|
|
635
|
+
<div className={styles.world} style={{ transform: `translate(${viewport.x}px, ${viewport.y}px) scale(${viewport.zoom})` }}>
|
|
636
|
+
<svg className={styles.edges} aria-label={text.canvas}>
|
|
637
|
+
<defs><mask id={captionMaskId} data-canvas-caption-mask maskUnits="userSpaceOnUse" {...captionMaskBounds} style={{ maskType: "luminance" }}>
|
|
638
|
+
<rect {...captionMaskBounds} fill="white" />
|
|
639
|
+
{[...obstacleBounds].flatMap(([id, bounds]) => bounds.captions.map((caption, index) =>
|
|
640
|
+
<rect key={`${id}-${index}`} data-caption-node={id} {...caption} fill="black" stroke="black" strokeWidth="calc(var(--canvas-caption-clearance) * 2)" />))}
|
|
641
|
+
</mask></defs>
|
|
642
|
+
<g mask={`url(#${captionMaskId})`}>
|
|
643
|
+
{[...edges.map(({ id, ...edge }) => {
|
|
644
|
+
const source = endpoint(edge.source), target = endpoint(edge.target);
|
|
645
|
+
if (!source || !target) return null;
|
|
646
|
+
const a = nodes.find(n => n.id === edge.source.nodeId), b = nodes.find(n => n.id === edge.target.nodeId);
|
|
647
|
+
return <CanvasEdge key={id} {...edge} source={source} target={target} variant="orthogonal" lineStyle={edge.lineStyle ?? lineStyle}
|
|
648
|
+
obstacles={connectionObstacles(edge.source.nodeId, edge.target.nodeId)} cornerRadius={cornerRadii ? resolveCanvasCornerRadius(edge.cornerRadius, cornerRadii, defaultCornerRadius) : undefined}
|
|
649
|
+
data-canvas-edge-id={id} selected={selectedEdgeIds.has(id)} label={`${a?.title} → ${b?.title}`}
|
|
650
|
+
onClick={event => { if (event.shiftKey) { event.preventDefault(); selectEdge(id, true); } }}
|
|
651
|
+
onKeyDown={event => { if (event.shiftKey && (event.key === "Enter" || event.key === " ")) { event.preventDefault(); selectEdge(id, true); } }}
|
|
652
|
+
onSelect={() => selectEdge(id)} />;
|
|
653
|
+
}),
|
|
654
|
+
from ? <CanvasEdge key={draftId.current ?? "canvas-preview"} source={from} target={to ?? { ...pointer, side: ({ left: "right", right: "left", top: "bottom", bottom: "top" } as const)[from.side] }} obstacles={connectionObstacles(pending?.nodeId, candidate?.nodeId)} cornerRadius={defaultCornerRadius} variant="orthogonal" lineStyle={lineStyle} preview /> : null]}
|
|
655
|
+
</g>
|
|
656
|
+
</svg>
|
|
657
|
+
{visualNodes.map(({ id, position: at, ...node }) => {
|
|
658
|
+
const ports = [...new Set(node.ports ?? ["left", "right"] as const)];
|
|
659
|
+
const connected = ports.filter(side => edges.some(e => samePort(e.source, { nodeId: id, side }) || samePort(e.target, { nodeId: id, side })));
|
|
660
|
+
return <div key={id} data-canvas-item={id} data-settling={!!settlement.positions[id] || undefined} data-dragging={!!dragging && selectedNodeIds.has(id) || undefined} className={styles.node}
|
|
661
|
+
style={{ left: at.x, top: at.y }} onPointerDown={e => nodeDown(e, { id, position: at, ...node })}
|
|
662
|
+
onPointerEnter={() => setHoveredNode(id)} onPointerLeave={() => setHoveredNode(null)}
|
|
663
|
+
onFocusCapture={() => setFocusedNode(id)} onBlurCapture={e => { if (!e.currentTarget.contains(e.relatedTarget as Node)) setFocusedNode(null); }}
|
|
664
|
+
>
|
|
665
|
+
<CanvasNode {...node} ref={element => { if (element) nodeElements.current.set(id, element); else nodeElements.current.delete(id); }}
|
|
666
|
+
connectedPorts={connected} portsVisible={!!pending || hoveredNode === id || focusedNode === id}
|
|
667
|
+
selected={selectedNodeIds.has(id)} onSelect={() => { clearConnection(); selectNode(id); }} />
|
|
668
|
+
{!readOnly && !!onEdgesChange && !node.disabled && ports.map(side => {
|
|
669
|
+
const port = { nodeId: id, side }, offset = metrics[id]?.ports[side];
|
|
670
|
+
if (!offset) return null;
|
|
671
|
+
return <Button key={side} variant="ghost" data-canvas-port={side} data-node-id={id} className={styles.port}
|
|
672
|
+
style={{ left: offset.x, top: offset.y }} aria-label={text.port(node.title, side)} aria-pressed={!!pending && samePort(pending, port)}
|
|
673
|
+
data-target={candidate && samePort(candidate, port) || undefined} onPointerDown={e => portDown(e, port)}
|
|
674
|
+
onClick={e => { if (e.detail !== 0) return; if (pending) { if (!connect(pending, port) && samePort(pending, port)) clearConnection(true); }
|
|
675
|
+
else { draftId.current = `edge-${crypto.randomUUID()}`; setPending(port); const at = endpoint(port); if (at) setPointer(at); setAnnouncement(text.connecting); } }} />;
|
|
676
|
+
})}
|
|
677
|
+
</div>;
|
|
678
|
+
})}
|
|
679
|
+
</div>
|
|
680
|
+
{guides.length > 0 && <svg className={styles.guides} data-canvas-guides aria-hidden="true" focusable="false">
|
|
681
|
+
{guides.map(guide => <line key={guide.axis} data-axis={guide.axis}
|
|
682
|
+
x1={(guide.axis === "x" ? guide.at : guide.from) * viewport.zoom + viewport.x}
|
|
683
|
+
x2={(guide.axis === "x" ? guide.at : guide.to) * viewport.zoom + viewport.x}
|
|
684
|
+
y1={(guide.axis === "y" ? guide.at : guide.from) * viewport.zoom + viewport.y}
|
|
685
|
+
y2={(guide.axis === "y" ? guide.at : guide.to) * viewport.zoom + viewport.y} />)}
|
|
686
|
+
</svg>}
|
|
687
|
+
{marquee && <div className={styles.marquee} data-canvas-marquee aria-hidden="true" style={{ left: marquee.x * viewport.zoom + viewport.x, top: marquee.y * viewport.zoom + viewport.y, width: marquee.width * viewport.zoom, height: marquee.height * viewport.zoom }} />}
|
|
688
|
+
{controls && <>
|
|
689
|
+
<div className={styles.viewControls} data-canvas-controls="view" data-orientation={controlsOrientation}>
|
|
690
|
+
<Toolbar aria-label={text.controls} orientation={controlsOrientation} size={compactControls ? "sm" : "md"}>
|
|
691
|
+
{controlsOrientation === "vertical" ? zoomInButton : zoomOutButton}
|
|
692
|
+
{controlsOrientation === "horizontal" && <output className={styles.zoomValue} aria-label={text.zoom} aria-live="off">{Math.round(viewport.zoom * 100)}%</output>}
|
|
693
|
+
{controlsOrientation === "vertical" ? zoomOutButton : zoomInButton}
|
|
694
|
+
<IconButton icon={<Icon name="target" />} aria-label={text.fit} title={text.fit} onClick={() => fit()} />
|
|
695
|
+
</Toolbar>
|
|
696
|
+
</div>
|
|
697
|
+
</>}
|
|
698
|
+
</div>;
|
|
699
|
+
}
|