@affino/diagram-core 0.1.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.
Files changed (41) hide show
  1. package/README.md +133 -0
  2. package/dist/DiagramEngine.d.ts +72 -0
  3. package/dist/DiagramEngine.d.ts.map +1 -0
  4. package/dist/DiagramEngine.js +1545 -0
  5. package/dist/geometry.d.ts +14 -0
  6. package/dist/geometry.d.ts.map +1 -0
  7. package/dist/geometry.js +131 -0
  8. package/dist/index.d.ts +6 -0
  9. package/dist/index.d.ts.map +1 -0
  10. package/dist/index.js +4 -0
  11. package/dist/interaction.d.ts +48 -0
  12. package/dist/interaction.d.ts.map +1 -0
  13. package/dist/interaction.js +462 -0
  14. package/dist/internal/DiagramClipboardService.d.ts +10 -0
  15. package/dist/internal/DiagramClipboardService.d.ts.map +1 -0
  16. package/dist/internal/DiagramClipboardService.js +103 -0
  17. package/dist/internal/DiagramGeometryService.d.ts +9 -0
  18. package/dist/internal/DiagramGeometryService.d.ts.map +1 -0
  19. package/dist/internal/DiagramGeometryService.js +38 -0
  20. package/dist/internal/DiagramHistory.d.ts +15 -0
  21. package/dist/internal/DiagramHistory.d.ts.map +1 -0
  22. package/dist/internal/DiagramHistory.js +53 -0
  23. package/dist/internal/DiagramSceneStore.d.ts +18 -0
  24. package/dist/internal/DiagramSceneStore.d.ts.map +1 -0
  25. package/dist/internal/DiagramSceneStore.js +159 -0
  26. package/dist/internal/DiagramSpatialIndex.d.ts +13 -0
  27. package/dist/internal/DiagramSpatialIndex.d.ts.map +1 -0
  28. package/dist/internal/DiagramSpatialIndex.js +51 -0
  29. package/dist/internal/DiagramViewportService.d.ts +5 -0
  30. package/dist/internal/DiagramViewportService.d.ts.map +1 -0
  31. package/dist/internal/DiagramViewportService.js +16 -0
  32. package/dist/internal/model.d.ts +43 -0
  33. package/dist/internal/model.d.ts.map +1 -0
  34. package/dist/internal/model.js +2 -0
  35. package/dist/spatialIndex.d.ts +12 -0
  36. package/dist/spatialIndex.d.ts.map +1 -0
  37. package/dist/spatialIndex.js +71 -0
  38. package/dist/types.d.ts +337 -0
  39. package/dist/types.d.ts.map +1 -0
  40. package/dist/types.js +1 -0
  41. package/package.json +44 -0
package/README.md ADDED
@@ -0,0 +1,133 @@
1
+ # @affino/diagram-core
2
+
3
+ Framework-neutral diagram state, geometry, command, history, selection, viewport, and serialization engine. Vue, React, or canvas adapters should call core commands instead of reimplementing movement, hit testing, undo/redo, clipboard, or viewport math.
4
+
5
+
6
+ ## Internal Architecture
7
+
8
+ The public package entry stays `createDiagramEngine()`. Internally the facade delegates focused responsibilities to services under `src/internal`: `DiagramHistory` owns undo/redo stacks and history merging, `DiagramGeometryService` owns geometry caching and read diagnostics, `DiagramSceneStore` owns mutable scene state, immutable snapshots, subscribers, and last-change publication; `DiagramSpatialIndex` owns visible/hit/port indexes, `DiagramViewportService` owns fit math, and `DiagramClipboardService` owns selected subgraph export/import id remapping. Command patch creation remains package-internal and should be split behind `DiagramCommandEngine` in a follow-up slice without changing the public API.
9
+
10
+ ## Basic usage
11
+
12
+ ```ts
13
+ import { createDiagramEngine } from "@affino/diagram-core"
14
+
15
+ const engine = createDiagramEngine({
16
+ nodes: [{ id: "n1", kind: "node", x: 0, y: 0, width: 120, height: 64, portIds: ["p1"] }],
17
+ ports: [{ id: "p1", kind: "port", nodeId: "n1", x: 120, y: 32 }],
18
+ edges: [],
19
+ texts: [{ id: "t1", kind: "text", x: 12, y: 18, text: "Bay 1", width: 80, height: 18 }],
20
+ shapes: [],
21
+ viewport: { x: 0, y: 0, width: 900, height: 600, zoom: 1 },
22
+ })
23
+
24
+ engine.dispatch({ type: "setSelection", selection: { ids: ["n1"], primaryId: "n1" } })
25
+ engine.dispatch({ type: "moveEntities", ids: ["n1"], delta: { x: 24, y: 0 } })
26
+ engine.dispatch({ type: "undo" })
27
+ ```
28
+
29
+ ## Clipboard and duplication
30
+
31
+ Clipboard exports are scene-shaped and safe to persist or pass through app-level clipboard code. Import remaps all ids, offsets nodes/texts/shapes/edge waypoints, and remaps node port ids plus edge endpoints inside the selected subgraph.
32
+
33
+ ```ts
34
+ const clipboard = engine.exportSelection()
35
+ engine.duplicateSelection({ x: 32, y: 32 })
36
+ engine.importClipboard(clipboard, { x: 64, y: 64 })
37
+ ```
38
+
39
+ ## Text Rendering Contract
40
+
41
+ Static text is data in core and should be rendered by adapters as SVG `<text>`/`<tspan>` elements in diagram/world coordinates. Core remains renderer-agnostic: it exposes text bounds through geometry, owns `editText` commands/history/serialization, and does not depend on DOM, SVG, Canvas, Vue, or browser globals. DOM is appropriate only for one active editor overlay owned by an adapter.
42
+
43
+ ## Editor commands
44
+
45
+ ```ts
46
+ engine.dispatch({ type: "resizeEntities", entries: [{ id: "n1", width: 160, height: 80 }] }) // node-relative ports scale with the node
47
+ engine.dispatch({ type: "insertEdgeWaypoint", edgeId: "e1", index: 0, point: { x: 240, y: 120 } })
48
+ engine.dispatch({ type: "moveEdgeWaypoint", edgeId: "e1", index: 0, point: { x: 260, y: 140 } })
49
+ engine.dispatch({ type: "removeEdgeWaypoint", edgeId: "e1", index: 0 })
50
+ engine.dispatch({ type: "bringForward", ids: ["n1"] })
51
+ engine.dispatch({ type: "setLayer", ids: ["n1"], layer: "equipment", layerRole: "normal" })
52
+ engine.dispatch({ type: "rotateEntities", entries: [{ id: "n1", rotation: 90 }] }) // geometry exposes rotated bounds/corners
53
+ engine.dispatch({ type: "alignEntities", ids: ["n1", "n2"], edge: "left" })
54
+ ```
55
+
56
+ Entities can be marked with metadata constraints. `locked` and `readOnly` entities cannot move, resize, or delete; `nonDeletable` entities can move but cannot be deleted. Front/back commands write `metadata.zIndex` so render order can cross entity kinds. Background layers are excluded from default render ordering unless explicitly requested.
57
+
58
+ ## Pointer resize gestures
59
+
60
+ Adapters that use the headless interaction controller should start resize handles through core instead of calculating resize deltas in the renderer. Core owns capability checks, transient preview state, and the final history command.
61
+
62
+ ```ts
63
+ const interaction = createDiagramInteractionController(engine)
64
+
65
+ interaction.beginResizeHandle("n1", "se", pointerEvent)
66
+ interaction.beginResizeSelectionHandle("se", pointerEvent)
67
+ const preview = interaction.getSnapshot().resizePreview
68
+ const entries = interaction.getSnapshot().resizePreviewEntries
69
+ // Render previews when present, then pointer up commits one resizeEntities history entry.
70
+ ```
71
+
72
+ `resizePreview` is intentionally transient: it lets SVG render live dimensions without mutating serialized scene state on every pointer move. Drag deltas are mapped through entity rotation and the opposite rotated corner stays anchored, so handles follow the local resize axes exposed by rotated geometry. Multi-selection resize uses group bounds and emits one preview entry per resizable selected entity.
73
+
74
+ ## Keyboard and capability helpers
75
+
76
+ Adapters should use command helpers and capability checks so UI buttons do not guess state from selection alone.
77
+
78
+ ```ts
79
+ engine.canUndo()
80
+ engine.canRedo()
81
+ engine.canDelete()
82
+ engine.canMove()
83
+ engine.canResize()
84
+ engine.canRotate()
85
+ engine.canAlign()
86
+ engine.canEditText("t1")
87
+ engine.canPaste(clipboard)
88
+
89
+ engine.dispatchKeyboardCommand("nudge-right", { step: 8, largeStep: 32, shiftKey: event.shiftKey })
90
+ engine.dispatchKeyboardCommand("delete")
91
+ engine.dispatchKeyboardCommand("escape")
92
+ engine.dispatchKeyboardCommand("undo")
93
+ engine.dispatchKeyboardCommand("redo")
94
+ ```
95
+
96
+
97
+ ## Query and search
98
+
99
+ Use `queryEntities()` for headless search/filter plumbing. It returns ids in render order and can filter by entity kind, world bounds, text/id/simple metadata, port inclusion, and limit. UI state such as input focus, debounce, current match index, and highlighted styling belongs in the adapter or app. Domain predicates such as SLD equipment class or IEC paths should stay in metadata/app code.
100
+
101
+ ```ts
102
+ const matches = engine.queryEntities({
103
+ kinds: ["node", "text"],
104
+ text: "bay",
105
+ metadata: { status: "warning" },
106
+ limit: 20,
107
+ })
108
+ ```
109
+
110
+ ## Selection and viewport helpers
111
+
112
+ Pointer adapters can use additive, toggle, and replace selection modes. Marquee selection uses strict containment by default; pass `marqueeMode: "intersect"` only when partially intersecting objects should be selected.
113
+
114
+ ```ts
115
+ engine.dispatch({ type: "setSelection", selection: { ids: ["n1"], primaryId: "n1" }, mode: "replace" })
116
+ engine.dispatch({ type: "setSelection", selection: { ids: ["n2"], primaryId: "n2" }, mode: "add" })
117
+ engine.dispatch({ type: "setSelection", selection: { ids: ["n1"], primaryId: "n1" }, mode: "toggle" })
118
+
119
+ engine.fitSelection(32)
120
+ engine.fitBounds({ x: 0, y: 0, width: 500, height: 300 }, 24)
121
+ engine.fitScene(48)
122
+ ```
123
+
124
+ Fit helpers preserve the viewport screen size invariant: `viewport.width * viewport.zoom` and `viewport.height * viewport.zoom` stay stable, while world bounds and zoom change together. DOM label layers should use the same `viewport.zoom` as SVG overlays.
125
+
126
+ ## Diagnostics
127
+
128
+ ```ts
129
+ const diagnostics = engine.getDiagnostics()
130
+ // { visibleQueryCount, entityQueryCount, hitTestCount, geometryRecomputeCount, lastCommandMs }
131
+ ```
132
+
133
+ Use `pnpm --filter @affino/diagram-core bench` after building to refresh `artifacts/performance/bench-diagram-core.json` and watch visible query, entity search/query, clipboard, routing, resize, fit, and command latency metrics.
@@ -0,0 +1,72 @@
1
+ import type { DiagramChange, DiagramClipboard, DiagramCommand, DiagramCommandResult, DiagramDiagnostics, DiagramGeometry, DiagramHit, DiagramHitTestOptions, DiagramId, DiagramPoint, DiagramQueryOptions, DiagramRect, DiagramRenderOrderOptions, DiagramScene, DiagramSceneInput, DiagramSelection, DiagramKeyboardCommand, DiagramKeyboardOptions, DiagramSnapContext, DiagramSnapResult, DiagramSubscriber, SerializedDiagramScene } from "./types.js";
2
+ export declare class DiagramEngine {
3
+ private store;
4
+ private state;
5
+ private geometryService;
6
+ private spatialIndex;
7
+ private history;
8
+ private viewportService;
9
+ private clipboardService;
10
+ private visibleQueryCount;
11
+ private entityQueryCount;
12
+ private hitTestCount;
13
+ private lastCommandMs;
14
+ constructor(initialScene?: DiagramSceneInput);
15
+ getScene(): DiagramScene;
16
+ getLastChange(): DiagramChange;
17
+ getEntityVersion(id: DiagramId): number;
18
+ getGeometryReadCount(): number;
19
+ getGeometrySnapshot(id: DiagramId): DiagramGeometry | null;
20
+ dispatch(command: DiagramCommand): DiagramCommandResult;
21
+ transact(mutator: (draft: DiagramScene) => DiagramSceneInput): DiagramCommandResult;
22
+ queryVisible(bounds: DiagramRect): DiagramId[];
23
+ queryVisibleBruteForce(bounds: DiagramRect): DiagramId[];
24
+ queryEntities(options?: DiagramQueryOptions): DiagramId[];
25
+ hitTest(point: DiagramPoint, options?: DiagramHitTestOptions): DiagramHit | null;
26
+ nearestPort(point: DiagramPoint, radius: number, exclude?: ReadonlySet<DiagramId>): DiagramHit | null;
27
+ nearestPortBruteForce(point: DiagramPoint, radius: number, exclude?: ReadonlySet<DiagramId>): DiagramHit | null;
28
+ snapPoint(point: DiagramPoint, context?: DiagramSnapContext): DiagramSnapResult;
29
+ snapTranslation(selection: DiagramSelection, delta: DiagramPoint, context?: DiagramSnapContext): DiagramSnapResult;
30
+ canUndo(): boolean;
31
+ canRedo(): boolean;
32
+ canDelete(ids?: ReadonlyArray<DiagramId>): boolean;
33
+ canMove(ids?: ReadonlyArray<DiagramId>): boolean;
34
+ canResize(ids?: ReadonlyArray<DiagramId>): boolean;
35
+ canRotate(ids?: ReadonlyArray<DiagramId>): boolean;
36
+ canAlign(ids?: ReadonlyArray<DiagramId>): boolean;
37
+ canEditText(id?: DiagramId | null): boolean;
38
+ canPaste(clipboard: DiagramClipboard | null | undefined): boolean;
39
+ getDiagnostics(): DiagramDiagnostics;
40
+ getRenderOrder(options?: DiagramRenderOrderOptions): DiagramId[];
41
+ exportSelection(): DiagramClipboard;
42
+ importClipboard(clipboard: DiagramClipboard, offset?: DiagramPoint): DiagramCommandResult;
43
+ duplicateSelection(offset?: DiagramPoint): DiagramCommandResult;
44
+ dispatchKeyboardCommand(command: DiagramKeyboardCommand, options?: DiagramKeyboardOptions): DiagramCommandResult;
45
+ fitBounds(bounds: DiagramRect, padding?: number): DiagramCommandResult;
46
+ fitSelection(padding?: number): DiagramCommandResult;
47
+ fitScene(padding?: number): DiagramCommandResult;
48
+ subscribe(listener: DiagramSubscriber): {
49
+ unsubscribe: () => void;
50
+ };
51
+ serialize(): SerializedDiagramScene;
52
+ private undo;
53
+ private redo;
54
+ private commitPatch;
55
+ private collectInvalidatedIds;
56
+ private getGeometry;
57
+ private rebuildIndexGeometries;
58
+ private ensureIndexes;
59
+ private createPatch;
60
+ private snapToAlignment;
61
+ private createOrderedIds;
62
+ private createOrderIndex;
63
+ private hasEntity;
64
+ private getEntityKind;
65
+ private getEntityMetadata;
66
+ private isEntityLockedOrReadOnly;
67
+ private isEntityNonDeletable;
68
+ }
69
+ export declare function createDiagramEngine(initialScene?: DiagramSceneInput): DiagramEngine;
70
+ export declare function serializeScene(scene: DiagramScene): SerializedDiagramScene;
71
+ export declare function deserializeScene(scene: SerializedDiagramScene): DiagramSceneInput;
72
+ //# sourceMappingURL=DiagramEngine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DiagramEngine.d.ts","sourceRoot":"","sources":["../src/DiagramEngine.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EACV,aAAa,EACb,gBAAgB,EAChB,cAAc,EACd,oBAAoB,EACpB,kBAAkB,EAIlB,eAAe,EACf,UAAU,EACV,qBAAqB,EACrB,SAAS,EACT,YAAY,EAEZ,mBAAmB,EACnB,WAAW,EACX,yBAAyB,EAIzB,YAAY,EACZ,iBAAiB,EACjB,gBAAgB,EAChB,sBAAsB,EACtB,sBAAsB,EACtB,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EAEjB,sBAAsB,EACvB,MAAM,YAAY,CAAA;AAEnB,qBAAa,aAAa;IACxB,OAAO,CAAC,KAAK,CAAmB;IAChC,OAAO,CAAC,KAAK,CAAe;IAC5B,OAAO,CAAC,eAAe,CAA+B;IACtD,OAAO,CAAC,YAAY,CAA4B;IAChD,OAAO,CAAC,OAAO,CAAuB;IACtC,OAAO,CAAC,eAAe,CAA+B;IACtD,OAAO,CAAC,gBAAgB,CAAg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