@statelyai/flow-dom 3.6.2 → 3.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/dist/esm/index.d.ts +14 -4
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +93 -12
- package/dist/esm/index.js.map +1 -0
- package/package.json +4 -3
- package/src/appearance-bounds.test.ts +97 -0
- package/src/appearance-bounds.ts +78 -0
- package/src/clipboard.test.ts +85 -0
- package/src/clipboard.ts +145 -0
- package/src/color-mode.test.ts +54 -0
- package/src/color-mode.ts +68 -0
- package/src/container.test.ts +167 -0
- package/src/culling.test.ts +182 -0
- package/src/culling.ts +153 -0
- package/src/entity-geometry.test.ts +391 -0
- package/src/entity-geometry.ts +227 -0
- package/src/exportImage.test.ts +70 -0
- package/src/exportImage.ts +213 -0
- package/src/index.ts +1062 -0
- package/src/input.test.ts +705 -0
- package/src/interaction-cursor.test.ts +20 -0
- package/src/interaction-cursor.ts +20 -0
- package/src/measurement-lifecycle.test.ts +287 -0
- package/src/measurement.test.ts +99 -0
- package/src/render-styles.test.ts +42 -0
- package/src/render-styles.ts +71 -0
- package/src/viewport-transform.test.ts +148 -0
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { EdgePathData, FlowColorMode, FlowController, FlowEngine, FlowEntityChangeNotifierOptions, FlowInputEffects, FlowInputEvent, FlowResult, FlowStore, FlowStoreContext, Point, Rect } from "@statelyai/flow";
|
|
2
2
|
export * from "@statelyai/flow";
|
|
3
|
+
//#region src/interaction-cursor.d.ts
|
|
4
|
+
/** Expose gesture cursors without changing an inherited CSS property. */
|
|
5
|
+
declare function attachInteractionCursor(store: FlowStore, element: HTMLElement): () => void;
|
|
6
|
+
//#endregion
|
|
3
7
|
//#region src/appearance-bounds.d.ts
|
|
4
8
|
/** Observe one appearance-local connection border without changing visual bounds. */
|
|
5
9
|
declare function observeAppearanceBounds(store: FlowStore, wrapper: Element, key: string, observer: MeasurementObserver, options?: {
|
|
@@ -194,10 +198,15 @@ type EntityGeometryObserver = {
|
|
|
194
198
|
*/
|
|
195
199
|
declare function createEntityGeometryObserver(store: FlowStore, options?: EntityGeometryObserverOptions): EntityGeometryObserver;
|
|
196
200
|
//#endregion
|
|
197
|
-
//#region src/
|
|
201
|
+
//#region src/color-mode.d.ts
|
|
198
202
|
type ResolvedFlowColorMode = 'light' | 'dark';
|
|
199
|
-
|
|
200
|
-
declare function
|
|
203
|
+
type ColorModeWindow = Pick<Window, 'matchMedia'>;
|
|
204
|
+
declare function resolveFlowColorMode(colorMode: FlowColorMode, targetWindow?: ColorModeWindow | undefined, element?: Element | null): ResolvedFlowColorMode;
|
|
205
|
+
declare function applyFlowColorMode(element: HTMLElement, colorMode: FlowColorMode, targetWindow?: ColorModeWindow | undefined): ResolvedFlowColorMode;
|
|
206
|
+
/** Track ancestor theme attributes and OS preference. Returns a cleanup function. */
|
|
207
|
+
declare function observeFlowColorMode(element: HTMLElement, colorMode: FlowColorMode, onChange?: (resolved: ResolvedFlowColorMode) => void): () => void;
|
|
208
|
+
//#endregion
|
|
209
|
+
//#region src/index.d.ts
|
|
201
210
|
type MeasurementTarget = {
|
|
202
211
|
appearanceId: string;
|
|
203
212
|
relativeTo: Element;
|
|
@@ -278,4 +287,5 @@ type AttachInputOptions = {
|
|
|
278
287
|
};
|
|
279
288
|
declare function attachInput(options: AttachInputOptions): () => void;
|
|
280
289
|
//#endregion
|
|
281
|
-
export { AttachInputOptions, type ClipboardTransport, type ComputeRenderableIdsOptions, type EntityBoundsTarget, type EntityEdgeTarget, type EntityGeometryObserver, type EntityGeometryObserverOptions, type EntityRectTarget, FLOW_CONTENT_MIME, type FlowClipboard, type FlowImageExportOptions, type FlowImageExportResult, type FlowView, MeasurementObserver, MeasurementObserverOptions, MeasurementTarget, type NodePositionStyle, type RenderableIds, ResolvedFlowColorMode, type SettledRenderableIds, type ViewportStyle, ViewportTransformOptions, applyFlowColorMode, attachContainer, attachInput, attachViewportTransform, canvasToClient, clientToCanvas, computeRenderableIds, computeSettledRenderableIds, createEntityGeometryObserver, createFlowClipboard, createFlowView, createMeasurementObserver, exportFlowImage, getAttachedContainer, nodePositionStyle, observeAppearanceBounds, renderableIdsEqual, resolveFlowColorMode, viewportStyle, writeZoomVariables };
|
|
290
|
+
export { AttachInputOptions, type ClipboardTransport, type ComputeRenderableIdsOptions, type EntityBoundsTarget, type EntityEdgeTarget, type EntityGeometryObserver, type EntityGeometryObserverOptions, type EntityRectTarget, FLOW_CONTENT_MIME, type FlowClipboard, type FlowImageExportOptions, type FlowImageExportResult, type FlowView, MeasurementObserver, MeasurementObserverOptions, MeasurementTarget, type NodePositionStyle, type RenderableIds, type ResolvedFlowColorMode, type SettledRenderableIds, type ViewportStyle, ViewportTransformOptions, applyFlowColorMode, attachContainer, attachInput, attachInteractionCursor, attachViewportTransform, canvasToClient, clientToCanvas, computeRenderableIds, computeSettledRenderableIds, createEntityGeometryObserver, createFlowClipboard, createFlowView, createMeasurementObserver, exportFlowImage, getAttachedContainer, nodePositionStyle, observeAppearanceBounds, observeFlowColorMode, renderableIdsEqual, resolveFlowColorMode, viewportStyle, writeZoomVariables };
|
|
291
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/interaction-cursor.ts","../../src/appearance-bounds.ts","../../src/clipboard.ts","../../src/exportImage.ts","../../src/culling.ts","../../src/render-styles.ts","../../src/entity-geometry.ts","../../src/color-mode.ts","../../src/index.ts"],"mappings":";;;;iBAGgB,wBAAwB,OAAO,WAAW,SAAS;;;;iBCCnD,wBACd,OAAO,WACP,SAAS,SACT,aACA,UAAU,qBACV;EAAW;;;;cCFA;KAED;EACV,aAAa,kBAAkB;EAC/B,iBAAiB;EACjB,SAAS,qBAAqB;EAC9B,aAAa,QAAQ;IAAQ;IAA0B,QAAQ,eAAe,QAAQ;;;KAG5E;EACV,OA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KAEP,kBAAkB,KAAK;iBAYZ,qBACd,WAAW,eACX,eAAc,6BACd,UAAU,iBACT;iBAOa,mBACd,SAAS,aACT,WAAW,eACX,eAAc,8BACb;;iBASa,qBACd,SAAS,aACT,WAAW,eACX,YAAY,UAAU;;;KCQZ;EACN;EAAsB,YAAY;;EAClC;;EACA;EAAgB;;EAChB;;KAEM;EACV,QAAQ,SAAS,SAAS,QAAQ;;EAElC,QAAQ,SAAS;EACjB,QAAQ,UAAU,kBAAkB;EACpC,UAAU,SAAS;EACnB;;KAGU;EACV,YAAY,iBAAiB;EAC7B;;iBAec,0BACd,OAAO,WACP,UAAS,6BACR;;iBAoMa,qBAAqB,OAAO,YAAY;iBAIxC,eACd,OAAO,WACP,OAAO,OACP,YAAW,6BACV;iBAUa,eACd,OAAO,WACP,OAAO,OACP,YAAW,6BACV;iBASa,gBACd,OAAO,WACP,SAAS,SACT;EAAW;;KA0DD;;EAEV;;;;;;;;EAQA;;;;;;iBAOc,mBAAmB,SAAS,aAAa;iBAOzC,wBACd,OAAO,WACP,SAAS,aACT,UAAS;KAqEC;EACV,WAAW;EACX,OAAO;EACP;IACE,KAAK,OAAO,iBAAiB;IAC7B;IACA;;;;;;EAMF,0CAA0C;;;;;;;;;EAS1C,WACE,SAAS,WAAW,sCACpB;IAAe;IAAW;;IACrB;IAAW;;;iBAGJ,YAAY,SAAS"}
|
package/dist/esm/index.js
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
import { createEntityChangeNotifier, pathToSVG } from "@statelyai/flow";
|
|
2
2
|
export * from "@statelyai/flow";
|
|
3
|
+
//#region src/interaction-cursor.ts
|
|
4
|
+
/** Expose gesture cursors without changing an inherited CSS property. */
|
|
5
|
+
function attachInteractionCursor(store, element) {
|
|
6
|
+
const previous = element.getAttribute("data-flow-cursor");
|
|
7
|
+
const update = () => {
|
|
8
|
+
const state = store.getSnapshot().context.canvasState;
|
|
9
|
+
const cursor = state === "dragging" || state === "panning" ? "grabbing" : null;
|
|
10
|
+
if (element.getAttribute("data-flow-cursor") === cursor) return;
|
|
11
|
+
if (cursor) element.setAttribute("data-flow-cursor", cursor);
|
|
12
|
+
else element.removeAttribute("data-flow-cursor");
|
|
13
|
+
};
|
|
14
|
+
update();
|
|
15
|
+
const subscription = store.subscribe(update);
|
|
16
|
+
return () => {
|
|
17
|
+
subscription.unsubscribe();
|
|
18
|
+
if (previous === null) element.removeAttribute("data-flow-cursor");
|
|
19
|
+
else element.setAttribute("data-flow-cursor", previous);
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
3
23
|
//#region src/appearance-bounds.ts
|
|
4
24
|
/** Observe one appearance-local connection border without changing visual bounds. */
|
|
5
25
|
function observeAppearanceBounds(store, wrapper, key, observer, options = {}) {
|
|
@@ -538,19 +558,63 @@ function createEntityGeometryObserver(store, options = {}) {
|
|
|
538
558
|
};
|
|
539
559
|
}
|
|
540
560
|
//#endregion
|
|
541
|
-
//#region src/
|
|
542
|
-
function
|
|
561
|
+
//#region src/color-mode.ts
|
|
562
|
+
function inheritedColorMode(element) {
|
|
563
|
+
for (let ancestor = element?.parentElement; ancestor; ancestor = ancestor.parentElement) {
|
|
564
|
+
const theme = ancestor.getAttribute("data-theme") ?? ancestor.getAttribute("data-flow-color-mode");
|
|
565
|
+
if (theme === "light" || theme === "dark") return theme;
|
|
566
|
+
if (ancestor.classList.contains("dark")) return "dark";
|
|
567
|
+
if (ancestor.classList.contains("light")) return "light";
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
function resolveFlowColorMode(colorMode, targetWindow = typeof window === "undefined" ? void 0 : window, element) {
|
|
543
571
|
if (colorMode !== "system") return colorMode;
|
|
544
|
-
return targetWindow?.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
|
|
572
|
+
return inheritedColorMode(element) ?? (targetWindow?.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light");
|
|
545
573
|
}
|
|
546
574
|
function applyFlowColorMode(element, colorMode, targetWindow = element.ownerDocument.defaultView ?? void 0) {
|
|
547
|
-
const
|
|
548
|
-
element.dataset.flowColorMode =
|
|
549
|
-
element.dataset.flowColorModePreference = colorMode;
|
|
550
|
-
element.style.colorScheme =
|
|
551
|
-
return
|
|
575
|
+
const resolved = resolveFlowColorMode(colorMode, targetWindow, element);
|
|
576
|
+
if (element.dataset.flowColorMode !== resolved) element.dataset.flowColorMode = resolved;
|
|
577
|
+
if (element.dataset.flowColorModePreference !== colorMode) element.dataset.flowColorModePreference = colorMode;
|
|
578
|
+
if (element.style.colorScheme !== resolved) element.style.colorScheme = resolved;
|
|
579
|
+
return resolved;
|
|
580
|
+
}
|
|
581
|
+
/** Track ancestor theme attributes and OS preference. Returns a cleanup function. */
|
|
582
|
+
function observeFlowColorMode(element, colorMode, onChange) {
|
|
583
|
+
const targetWindow = element.ownerDocument.defaultView;
|
|
584
|
+
const refresh = () => {
|
|
585
|
+
const resolved = applyFlowColorMode(element, colorMode);
|
|
586
|
+
onChange?.(resolved);
|
|
587
|
+
};
|
|
588
|
+
refresh();
|
|
589
|
+
if (colorMode !== "system") return () => {};
|
|
590
|
+
const media = targetWindow?.matchMedia?.("(prefers-color-scheme: dark)");
|
|
591
|
+
media?.addEventListener("change", refresh);
|
|
592
|
+
const Observer = targetWindow?.MutationObserver;
|
|
593
|
+
const observer = Observer ? new Observer(refresh) : void 0;
|
|
594
|
+
for (let ancestor = element.parentElement; ancestor; ancestor = ancestor.parentElement) observer?.observe(ancestor, {
|
|
595
|
+
attributes: true,
|
|
596
|
+
attributeFilter: [
|
|
597
|
+
"class",
|
|
598
|
+
"data-theme",
|
|
599
|
+
"data-flow-color-mode"
|
|
600
|
+
]
|
|
601
|
+
});
|
|
602
|
+
return () => {
|
|
603
|
+
media?.removeEventListener("change", refresh);
|
|
604
|
+
observer?.disconnect();
|
|
605
|
+
};
|
|
552
606
|
}
|
|
607
|
+
//#endregion
|
|
608
|
+
//#region src/index.ts
|
|
553
609
|
const containers = /* @__PURE__ */ new WeakMap();
|
|
610
|
+
function hasOwnScale(element) {
|
|
611
|
+
const transform = element.ownerDocument.defaultView?.getComputedStyle(element).transform;
|
|
612
|
+
if (!transform || transform === "none") return false;
|
|
613
|
+
const values = /^matrix\(([^)]*)\)$/.exec(transform)?.[1].split(",").map(Number);
|
|
614
|
+
if (!values) return true;
|
|
615
|
+
const [a, b, c, d] = values;
|
|
616
|
+
return a !== 1 || b !== 0 || c !== 0 || d !== 1;
|
|
617
|
+
}
|
|
554
618
|
function createMeasurementObserver(store, options = {}) {
|
|
555
619
|
const equalityThreshold = options.equalityThreshold ?? .5;
|
|
556
620
|
const elementMap = /* @__PURE__ */ new Map();
|
|
@@ -567,6 +631,9 @@ function createMeasurementObserver(store, options = {}) {
|
|
|
567
631
|
}
|
|
568
632
|
function pushMeasurement(element, registration, layoutSize) {
|
|
569
633
|
const { target } = registration;
|
|
634
|
+
if (layoutSize) registration.layoutSize = layoutSize;
|
|
635
|
+
else layoutSize = registration.layoutSize;
|
|
636
|
+
if (layoutSize && hasOwnScale(element)) layoutSize = void 0;
|
|
570
637
|
const viewport = store.getSnapshot().context.viewport;
|
|
571
638
|
const zoom = viewport.zoom || 1;
|
|
572
639
|
const rect = element.getBoundingClientRect();
|
|
@@ -579,14 +646,26 @@ function createMeasurementObserver(store, options = {}) {
|
|
|
579
646
|
height: layoutSize ? layoutSize.height : rect.height / zoom
|
|
580
647
|
};
|
|
581
648
|
const id = "appearanceId" in target ? target.appearanceId : "portName" in target ? `${target.nodeId}:${target.portName}` : "nodeId" in target ? target.nodeId : target.edgeId;
|
|
649
|
+
let origin;
|
|
650
|
+
if ("portName" in target) for (let owner = element.parentElement; owner; owner = owner.parentElement) {
|
|
651
|
+
if (owner.getAttribute("data-entity-id") !== target.nodeId) continue;
|
|
652
|
+
const bounds = owner.getBoundingClientRect();
|
|
653
|
+
origin = {
|
|
654
|
+
x: (bounds.left - (containerRect?.left ?? 0) - viewport.x) / zoom,
|
|
655
|
+
y: (bounds.top - (containerRect?.top ?? 0) - viewport.y) / zoom
|
|
656
|
+
};
|
|
657
|
+
break;
|
|
658
|
+
}
|
|
582
659
|
const existing = store.getSnapshot().context.measurements.get(id);
|
|
583
|
-
if (existing && Math.abs(existing.x - measurement.x) < equalityThreshold && Math.abs(existing.y - measurement.y) < equalityThreshold && Math.abs(existing.width - measurement.width) < equalityThreshold && Math.abs(existing.height - measurement.height) < equalityThreshold) return;
|
|
660
|
+
if (existing && origin?.x === registration.origin?.x && origin?.y === registration.origin?.y && Math.abs(existing.x - measurement.x) < equalityThreshold && Math.abs(existing.y - measurement.y) < equalityThreshold && Math.abs(existing.width - measurement.width) < equalityThreshold && Math.abs(existing.height - measurement.height) < equalityThreshold) return;
|
|
661
|
+
registration.origin = origin;
|
|
584
662
|
pendingMeasurements.push({
|
|
585
663
|
element,
|
|
586
664
|
registration,
|
|
587
665
|
measurement: {
|
|
588
666
|
id,
|
|
589
|
-
rect: measurement
|
|
667
|
+
rect: measurement,
|
|
668
|
+
...origin ? { origin } : {}
|
|
590
669
|
}
|
|
591
670
|
});
|
|
592
671
|
scheduleFlush();
|
|
@@ -618,7 +697,7 @@ function createMeasurementObserver(store, options = {}) {
|
|
|
618
697
|
const replacing = elementMap.has(element);
|
|
619
698
|
const registration = { target };
|
|
620
699
|
elementMap.set(element, registration);
|
|
621
|
-
getObserver(element).observe(element);
|
|
700
|
+
getObserver(element).observe(element, { box: "border-box" });
|
|
622
701
|
if (replacing) pushMeasurement(element, registration);
|
|
623
702
|
},
|
|
624
703
|
/**
|
|
@@ -1163,4 +1242,6 @@ function attachInput(options) {
|
|
|
1163
1242
|
};
|
|
1164
1243
|
}
|
|
1165
1244
|
//#endregion
|
|
1166
|
-
export { FLOW_CONTENT_MIME, applyFlowColorMode, attachContainer, attachInput, attachViewportTransform, canvasToClient, clientToCanvas, computeRenderableIds, computeSettledRenderableIds, createEntityGeometryObserver, createFlowClipboard, createFlowView, createMeasurementObserver, exportFlowImage, getAttachedContainer, nodePositionStyle, observeAppearanceBounds, renderableIdsEqual, resolveFlowColorMode, viewportStyle, writeZoomVariables };
|
|
1245
|
+
export { FLOW_CONTENT_MIME, applyFlowColorMode, attachContainer, attachInput, attachInteractionCursor, attachViewportTransform, canvasToClient, clientToCanvas, computeRenderableIds, computeSettledRenderableIds, createEntityGeometryObserver, createFlowClipboard, createFlowView, createMeasurementObserver, exportFlowImage, getAttachedContainer, nodePositionStyle, observeAppearanceBounds, observeFlowColorMode, renderableIdsEqual, resolveFlowColorMode, viewportStyle, writeZoomVariables };
|
|
1246
|
+
|
|
1247
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/interaction-cursor.ts","../../src/appearance-bounds.ts","../../src/clipboard.ts","../../src/exportImage.ts","../../src/culling.ts","../../src/render-styles.ts","../../src/entity-geometry.ts","../../src/color-mode.ts","../../src/index.ts"],"sourcesContent":["import type { FlowStore } from '@statelyai/flow';\n\n/** Expose gesture cursors without changing an inherited CSS property. */\nexport function attachInteractionCursor(store: FlowStore, element: HTMLElement): () => void {\n const previous = element.getAttribute('data-flow-cursor');\n const update = () => {\n const state = store.getSnapshot().context.canvasState;\n const cursor = state === 'dragging' || state === 'panning' ? 'grabbing' : null;\n if (element.getAttribute('data-flow-cursor') === cursor) return;\n if (cursor) element.setAttribute('data-flow-cursor', cursor);\n else element.removeAttribute('data-flow-cursor');\n };\n update();\n const subscription = store.subscribe(update);\n return () => {\n subscription.unsubscribe();\n if (previous === null) element.removeAttribute('data-flow-cursor');\n else element.setAttribute('data-flow-cursor', previous);\n };\n}\n","import type { FlowStore } from \"@statelyai/flow\";\nimport type { MeasurementObserver } from \"./index\";\n\n/** Observe one appearance-local connection border without changing visual bounds. */\nexport function observeAppearanceBounds(\n store: FlowStore,\n wrapper: Element,\n key: string,\n observer: MeasurementObserver,\n options: { selector?: string } = {}\n): () => void {\n let boundary: Element | null = null;\n const clear = () => {\n if (boundary) observer.unobserve(boundary);\n boundary = null;\n if (store.getSnapshot().context.measurements.has(key)) {\n store.trigger.removeMeasurements({ ids: [key] });\n }\n };\n const refresh = () => {\n let matches: NodeListOf<Element> | undefined;\n try {\n matches = wrapper.querySelectorAll(\n options.selector ?? \"[data-flow-connection-bounds]\"\n );\n } catch {\n // Invalid selectors use visual bounds, just like missing borders.\n }\n const next = matches?.length === 1 ? matches[0] : null;\n if (!next || next !== boundary) {\n clear();\n boundary = next;\n if (boundary) {\n observer.observe(boundary, { appearanceId: key, relativeTo: wrapper });\n }\n }\n observer.measure(wrapper);\n if (boundary) observer.measure(boundary);\n };\n const targetWindow = wrapper.ownerDocument.defaultView;\n // Captions can move a border without changing the border's own size.\n const resize = new (targetWindow?.ResizeObserver ?? ResizeObserver)(refresh);\n resize.observe(wrapper);\n // Compare layout styles without Flow's translation/will-change hot-path writes.\n const style = wrapper.ownerDocument.createElement(\"div\").style;\n const layoutStyle = () => {\n style.cssText = wrapper.getAttribute(\"style\") ?? \"\";\n return JSON.stringify(Array.from(style).sort()\n .filter((property) => {\n if (property === \"will-change\") return false;\n return property !== \"transform\" ||\n !/^translate\\([^)]*\\)$/.test(style.getPropertyValue(property));\n })\n .map((property) => [\n property, style.getPropertyValue(property), style.getPropertyPriority(property),\n ]));\n };\n let previousStyle = layoutStyle();\n const mutations = new (targetWindow?.MutationObserver ?? MutationObserver)((records) => {\n const currentStyle = layoutStyle();\n const layoutChanged = currentStyle !== previousStyle;\n previousStyle = currentStyle;\n if (layoutChanged || records.some((record) =>\n record.type !== \"attributes\" || record.target !== wrapper || record.attributeName !== \"style\"\n )) refresh();\n });\n mutations.observe(wrapper, {\n subtree: true, childList: true, attributes: true, characterData: true,\n });\n wrapper.addEventListener(\"load\", refresh, true);\n refresh();\n return () => {\n resize.disconnect();\n mutations.disconnect();\n wrapper.removeEventListener(\"load\", refresh, true);\n clear();\n };\n}\n","import type {\n FlowContent,\n FlowController,\n FlowResult,\n Point,\n} from '@statelyai/flow';\n\nexport const FLOW_CONTENT_MIME = 'application/vnd.stately.flow+json';\n\nexport type ClipboardTransport = {\n writeText?: (value: string) => Promise<void>;\n readText?: () => Promise<string>;\n write?: (items: unknown[]) => Promise<void>;\n read?: () => Promise<Array<{ types: readonly string[]; getType(type: string): Promise<Blob> }>>;\n};\n\nexport type FlowClipboard = {\n copy: (targets?: Iterable<string>) => Promise<boolean>;\n cut: (targets?: Iterable<string>) => Promise<boolean>;\n paste: (options?: { point?: Point; preservePosition?: boolean }) => Promise<FlowResult<unknown, Error>>;\n};\n\nexport function createFlowClipboard(\n flow: FlowController,\n options: {\n clipboard?: ClipboardTransport;\n ClipboardItem?: new (items: Record<string, Blob>) => unknown;\n } = {},\n): FlowClipboard {\n const clipboard = options.clipboard ??\n (globalThis.navigator?.clipboard as ClipboardTransport | undefined);\n let fallback: FlowContent | null = null;\n\n async function write(content: FlowContent): Promise<boolean> {\n fallback = content;\n const json = JSON.stringify(content);\n try {\n if (clipboard?.write && options.ClipboardItem) {\n const html = `<div data-stately-flow>${escapeHtml(json)}</div>`;\n await clipboard.write([\n new options.ClipboardItem({\n [FLOW_CONTENT_MIME]: new Blob([json], { type: FLOW_CONTENT_MIME }),\n 'text/plain': new Blob([json], { type: 'text/plain' }),\n 'text/html': new Blob([html], { type: 'text/html' }),\n }),\n ]);\n } else if (clipboard?.writeText) {\n await clipboard.writeText(json);\n }\n return true;\n } catch {\n // The in-memory value remains available for this adapter instance.\n return false;\n }\n }\n\n async function read(): Promise<unknown> {\n let readSucceeded = false;\n try {\n if (clipboard?.read) {\n const items = await clipboard.read();\n readSucceeded = true;\n for (const item of items) {\n const type = item.types.includes(FLOW_CONTENT_MIME)\n ? FLOW_CONTENT_MIME\n : item.types.includes('text/plain')\n ? 'text/plain'\n : null;\n if (type) return parseJson(await (await item.getType(type)).text());\n }\n }\n if (clipboard?.readText) {\n const text = await clipboard.readText();\n readSucceeded = true;\n if (text) return parseJson(text);\n }\n } catch {\n if (readSucceeded) return null;\n return fallback;\n }\n return readSucceeded ? null : fallback;\n }\n\n function canRun(\n command: 'copy' | 'cut',\n targets: readonly string[] | undefined,\n ): boolean {\n if (!targets) return flow.can(command);\n return (\n targets.length > 0 &&\n targets.every((id) => flow.can(command, { id }))\n );\n }\n\n return {\n async copy(targets) {\n const ids = targets ? [...targets] : undefined;\n if (!canRun('copy', ids)) return false;\n const content = flow.content.extract(ids);\n if (!content) return false;\n await write(content);\n return true;\n },\n async cut(targets) {\n const ids = targets\n ? [...targets]\n : [...flow.getSnapshot().selection];\n if (!canRun('cut', ids)) return false;\n const content = flow.content.extract(ids);\n if (!content) return false;\n if (!(await write(content))) return false;\n flow.transaction((draft) => {\n for (const id of ids) {\n if (!draft.edges.delete(id)) draft.nodes.delete(id);\n }\n }, { origin: 'clipboard.cut' });\n return true;\n },\n async paste(insertOptions) {\n const content = await read();\n if (!content) {\n return {\n ok: false,\n error: new Error('Clipboard does not contain Flow content.'),\n };\n }\n return flow.content.insert(content, insertOptions);\n },\n };\n}\n\nfunction parseJson(value: string): unknown | null {\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>');\n}\n","import type { Rect } from '@statelyai/flow';\nimport type { MeasurementObserver } from './index';\n\nexport type FlowImageExportOptions = {\n format?: 'svg' | 'png' | 'webp';\n region?: 'graph' | 'viewport' | 'selection' | Rect;\n padding?: number;\n scale?: number;\n pixelRatio?: number;\n background?: string;\n styles?: 'computed' | 'none';\n include?: (element: Element) => boolean;\n signal?: { readonly aborted: boolean; addEventListener(type: 'abort', listener: () => void, options?: { once?: boolean }): void };\n};\n\nexport type FlowImageExportResult = {\n blob: Blob;\n width: number;\n height: number;\n};\n\nexport type FlowView = {\n exportImage: (options?: FlowImageExportOptions) => Promise<FlowImageExportResult>;\n refreshMeasurements: (targets?: Iterable<string | Element>) => void;\n};\n\nexport function createFlowView(\n container: HTMLElement,\n options: { measurements?: MeasurementObserver } = {},\n): FlowView {\n return {\n exportImage: (options) => exportFlowImage(container, options),\n refreshMeasurements: (targets) => options.measurements?.refresh(targets),\n };\n}\n\nexport async function exportFlowImage(\n container: HTMLElement,\n options: FlowImageExportOptions = {},\n): Promise<FlowImageExportResult> {\n throwIfAborted(options.signal);\n const win = container.ownerDocument.defaultView;\n if (!win) throw new Error('Flow export requires a window.');\n await nextFrame(win, options.signal);\n\n const format = options.format ?? 'svg';\n const padding = Math.max(0, options.padding ?? 0);\n const scale = Math.max(0.01, options.scale ?? 1);\n const pixelRatio = Math.max(0.01, options.pixelRatio ?? win.devicePixelRatio ?? 1);\n const region = resolveRegion(container, options.region ?? 'graph');\n const width = Math.max(1, Math.ceil((region.width + padding * 2) * scale));\n const height = Math.max(1, Math.ceil((region.height + padding * 2) * scale));\n const clone = container.cloneNode(true) as HTMLElement;\n if ((options.styles ?? 'computed') === 'computed') {\n inlineComputedStyles(win, container, clone);\n }\n if (options.include) {\n const originals = [container, ...Array.from(container.querySelectorAll('*'))];\n const clones = [clone, ...Array.from(clone.querySelectorAll('*'))];\n for (let index = originals.length - 1; index >= 0; index--) {\n if (!options.include(originals[index])) clones[index]?.remove();\n }\n }\n const serializer = new win.XMLSerializer();\n const markup = serializer.serializeToString(clone);\n const background = options.background\n ? `<rect width=\"100%\" height=\"100%\" fill=\"${escapeXml(options.background)}\"/>`\n : '';\n const containerRect = container.getBoundingClientRect();\n const svg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\" viewBox=\"${region.x - padding} ${region.y - padding} ${region.width + padding * 2} ${region.height + padding * 2}\">${background}<foreignObject x=\"0\" y=\"0\" width=\"${containerRect.width}\" height=\"${containerRect.height}\">${markup}</foreignObject></svg>`;\n const svgBlob = new Blob([svg], { type: 'image/svg+xml' });\n if (format === 'svg') return { blob: svgBlob, width, height };\n\n throwIfAborted(options.signal);\n const url = await blobDataUrl(win, svgBlob, options.signal);\n const image = await loadImage(win, url, options.signal);\n const canvas = container.ownerDocument.createElement('canvas');\n canvas.width = Math.ceil(width * pixelRatio);\n canvas.height = Math.ceil(height * pixelRatio);\n const context = canvas.getContext('2d');\n if (!context) throw new Error('Canvas 2D context is unavailable.');\n context.scale(pixelRatio, pixelRatio);\n context.drawImage(image, 0, 0, width, height);\n const blob = await canvasBlob(canvas, `image/${format}`, options.signal);\n return { blob, width, height };\n}\n\nfunction inlineComputedStyles(\n win: Window,\n originalRoot: HTMLElement,\n cloneRoot: HTMLElement,\n): void {\n const originals = [originalRoot, ...Array.from(originalRoot.querySelectorAll('*'))];\n const clones = [cloneRoot, ...Array.from(cloneRoot.querySelectorAll('*'))];\n for (let index = 0; index < originals.length; index++) {\n const clone = clones[index] as (Element & { style?: CSSStyleDeclaration }) | undefined;\n if (!clone?.style) continue;\n const computed = win.getComputedStyle(originals[index]);\n for (let propertyIndex = 0; propertyIndex < computed.length; propertyIndex++) {\n const property = computed.item(propertyIndex);\n clone.style.setProperty(\n property,\n computed.getPropertyValue(property),\n computed.getPropertyPriority(property),\n );\n }\n }\n}\n\nfunction blobDataUrl(\n win: Window,\n blob: Blob,\n signal: FlowImageExportOptions['signal'],\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const Reader = (win as unknown as { FileReader: typeof FileReader }).FileReader;\n const reader = new Reader();\n reader.onload = () => resolve(String(reader.result));\n reader.onerror = () => reject(reader.error ?? new Error('Unable to encode Flow SVG.'));\n signal?.addEventListener('abort', () => {\n reader.abort();\n reject(abortError());\n }, { once: true });\n reader.readAsDataURL(blob);\n });\n}\n\nfunction resolveRegion(\n container: HTMLElement,\n region: NonNullable<FlowImageExportOptions['region']>,\n): Rect {\n if (typeof region === 'object') return region;\n const selector = region === 'selection'\n ? '[data-flow-selected=\"true\"], [aria-selected=\"true\"]'\n : region === 'graph'\n ? '[data-entity-id]'\n : null;\n const elements = selector ? Array.from(container.querySelectorAll(selector)) : [container];\n const containerRect = container.getBoundingClientRect();\n if (elements.length === 0) {\n return { x: 0, y: 0, width: containerRect.width, height: containerRect.height };\n }\n const rects = elements.map((element) => element.getBoundingClientRect());\n const left = Math.min(...rects.map((rect) => rect.left));\n const top = Math.min(...rects.map((rect) => rect.top));\n const right = Math.max(...rects.map((rect) => rect.right));\n const bottom = Math.max(...rects.map((rect) => rect.bottom));\n return {\n x: left - containerRect.left,\n y: top - containerRect.top,\n width: right - left,\n height: bottom - top,\n };\n}\n\nfunction nextFrame(\n win: Window,\n signal: FlowImageExportOptions['signal'],\n): Promise<void> {\n return new Promise((resolve, reject) => {\n const id = win.requestAnimationFrame(() => {\n if (signal?.aborted) reject(abortError());\n else resolve();\n });\n signal?.addEventListener('abort', () => {\n win.cancelAnimationFrame(id);\n reject(abortError());\n }, { once: true });\n });\n}\n\nfunction loadImage(\n win: Window,\n url: string,\n signal: FlowImageExportOptions['signal'],\n): Promise<HTMLImageElement> {\n return new Promise((resolve, reject) => {\n const ImageCtor = (win as unknown as { Image: new () => HTMLImageElement }).Image;\n const image = new ImageCtor();\n image.onload = () => resolve(image);\n image.onerror = () => reject(new Error('Unable to render Flow SVG.'));\n signal?.addEventListener('abort', () => reject(abortError()), { once: true });\n image.src = url;\n });\n}\n\nfunction canvasBlob(\n canvas: HTMLCanvasElement,\n type: string,\n signal: FlowImageExportOptions['signal'],\n): Promise<Blob> {\n return new Promise((resolve, reject) => {\n canvas.toBlob((blob) => {\n if (signal?.aborted) reject(abortError());\n else if (blob) resolve(blob);\n else reject(new Error(`Unable to encode ${type}.`));\n }, type);\n });\n}\n\nfunction throwIfAborted(signal: FlowImageExportOptions['signal']): void {\n if (signal?.aborted) throw abortError();\n}\n\nfunction abortError(): Error {\n const error = new Error('The operation was aborted.');\n error.name = 'AbortError';\n return error;\n}\n\nfunction escapeXml(value: string): string {\n return value.replaceAll('&', '&').replaceAll('\"', '"').replaceAll('<', '<');\n}\n","import type { FlowEngine, FlowStoreContext } from \"@statelyai/flow\";\n\n// Culling (framework-agnostic \"what to mount\" policy)\n//\n// Decides which entities a DOM adapter should mount for the current viewport.\n// This is pure rendering policy with no framework or DOM dependency, so it\n// lives here (the source of rendering truth) rather than being re-derived in\n// every adapter — including the coverage gate that made zoomed-out drags laggy\n// when each adapter forgot it. See ADAPTER_NOTES.md.\n\n/** Overscan (canvas px) added around the viewport so entities just off-screen\n * stay mounted and don't pop in/out at the edges. */\nconst CULL_OVERSCAN = 100;\n\nexport type ComputeRenderableIdsOptions = {\n overscan?: number;\n};\n\n/**\n * Node/edge ids worth mounting, or `null` meaning \"render everything\" — either\n * because culling is disabled, the viewport hasn't been measured yet, or the\n * whole graph already fits the viewport (so culling would mount everything\n * anyway). Adapters mount exactly these ids; `null` means mount all.\n */\nexport type RenderableIds = {\n nodeIds: Set<string>;\n edgeIds: Set<string>;\n} | null;\n\nfunction idSetsEqual(a: Set<string>, b: Set<string>): boolean {\n if (a.size !== b.size) return false;\n for (const value of a) {\n if (!b.has(value)) return false;\n }\n return true;\n}\n\n/**\n * Compare two `computeRenderableIds` results by contents. Adapters use this as\n * the equality function for their reactive subscription so a layer only\n * re-renders when the visible set actually changes — not on every store\n * transition (e.g. every drag frame).\n */\nexport function renderableIdsEqual(a: RenderableIds, b: RenderableIds): boolean {\n return (\n a === b ||\n (a !== null &&\n b !== null &&\n idSetsEqual(a.nodeIds, b.nodeIds) &&\n idSetsEqual(a.edgeIds, b.edgeIds))\n );\n}\n\n/**\n * Which entities should be mounted for the current viewport, or `null` to mount\n * everything.\n *\n * Returns `null` when:\n * - `enabled` is false (culling off),\n * - the viewport is unmeasured (0×0 — culling against it would blank the first\n * paint),\n * - or the whole graph fits the viewport (+overscan). In that case culling\n * would mount every entity anyway, so we skip the per-frame O(n+e) cull and\n * the N-id Set build entirely — running it for zero benefit is what makes a\n * zoomed-out drag laggy. The containment check is one O(n) `getGraphBounds`,\n * far cheaper than the cull it avoids.\n *\n * Otherwise returns the visible node/edge id sets (viewport cull + overscan).\n *\n * `context` must be the engine's current snapshot (the engine reads its own\n * `getGraphBounds`/`getRenderableEntities` from the live store) — which holds\n * when called inside a store-subscription selector.\n */\nexport function computeRenderableIds(\n engine: FlowEngine,\n context: FlowStoreContext,\n enabled: boolean | undefined,\n options: ComputeRenderableIdsOptions = {}\n): RenderableIds {\n if (!enabled) return null;\n const overscan = options.overscan ?? CULL_OVERSCAN;\n\n const viewportSize = context.viewportSize;\n if (viewportSize.width === 0 || viewportSize.height === 0) return null;\n\n // Coverage gate: the graph already fits the viewport → mounting everything is\n // unavoidable, so don't pay for the cull.\n const viewport = context.viewport;\n const left = -viewport.x / viewport.zoom - overscan;\n const top = -viewport.y / viewport.zoom - overscan;\n const right = left + viewportSize.width / viewport.zoom + overscan * 2;\n const bottom = top + viewportSize.height / viewport.zoom + overscan * 2;\n const bounds = engine.getGraphBounds();\n if (\n left <= bounds.x &&\n top <= bounds.y &&\n right >= bounds.x + bounds.width &&\n bottom >= bounds.y + bounds.height\n ) {\n return null;\n }\n\n const renderable = engine.getRenderableEntities({\n cull: \"viewport\",\n overscan,\n });\n return {\n nodeIds: new Set(renderable.nodes.map((node) => node.id)),\n edgeIds: new Set(renderable.edges.map((edge) => edge.id)),\n };\n}\n\n/** A cull and the inputs it was computed for. See `computeSettledRenderableIds`. */\nexport type SettledRenderableIds = {\n value: RenderableIds;\n graph: FlowStoreContext[\"graph\"];\n enabled: boolean | undefined;\n settledZoom: number | undefined;\n};\n\n/**\n * `computeRenderableIds` that holds the previous cull during a zoom gesture.\n * While the live zoom differs from `settledZoom`, it returns `previous` as long\n * as the graph, `enabled` and `settledZoom` are unchanged: mounting what a zoom\n * frame reveals costs far more than the transform. Any other case recomputes.\n * Omitting `settledZoom` always recomputes. Pass the returned value back as\n * `previous` on the next call.\n */\nexport function computeSettledRenderableIds(\n engine: FlowEngine,\n context: FlowStoreContext,\n enabled: boolean | undefined,\n settledZoom: number | undefined,\n previous: SettledRenderableIds | null,\n options: ComputeRenderableIdsOptions = {}\n): SettledRenderableIds {\n if (\n settledZoom !== undefined &&\n context.viewport.zoom !== settledZoom &&\n previous &&\n previous.graph === context.graph &&\n previous.enabled === enabled &&\n previous.settledZoom === settledZoom\n ) {\n return previous;\n }\n return {\n value: computeRenderableIds(engine, context, enabled, options),\n graph: context.graph,\n enabled,\n settledZoom,\n };\n}\n","import type { Rect } from \"@statelyai/flow\";\n\n// Render styles (framework-agnostic structure rules)\n//\n// Style recipes that bake in the performance rules so an adapter can't get the\n// canvas structure wrong: transform-based positioning (never left/top), the\n// single transformed viewport, and GPU-promotion of the moving node. They style\n// the *structure* (the viewport element, the per-node wrapper) — NOT node/edge\n// content. Custom node/edge components render their content inside the wrapper\n// and are unaffected. See ADAPTER_NOTES.md.\n\nexport type NodePositionStyle = {\n position: \"absolute\";\n top: 0;\n left: 0;\n transform: string;\n transformOrigin: \"0 0\";\n willChange: \"transform\" | undefined;\n width: number | \"max-content\";\n height: number | undefined;\n};\n\n/**\n * Position + size for a node's *wrapper* element. Always uses `transform`\n * (compositor-friendly), never `left/top`, and GPU-promotes the wrapper while\n * it is being dragged so moving it doesn't repaint its neighbours.\n *\n * `autoSize` nodes are sized by their content (the DOM owns the size and the\n * measurement observer feeds it back); all others use the graph-owned size.\n *\n * This styles the wrapper box only — the node's content (including any custom\n * component) renders inside and is untouched.\n */\nexport function nodePositionStyle(\n bounds: Rect,\n options: { autoSize?: boolean; dragging?: boolean } = {}\n): NodePositionStyle {\n return {\n position: \"absolute\",\n top: 0,\n left: 0,\n transform: `translate(${bounds.x}px, ${bounds.y}px)`,\n transformOrigin: \"0 0\",\n willChange: options.dragging ? \"transform\" : undefined,\n width: options.autoSize ? \"max-content\" : bounds.width,\n height: options.autoSize ? undefined : bounds.height,\n };\n}\n\nexport type ViewportStyle = {\n position: \"absolute\";\n inset: 0;\n transformOrigin: \"0 0\";\n pointerEvents: \"none\";\n};\n\n/**\n * Style for the single transformed viewport element that wraps all canvas\n * layers (nodes, edges, labels as static children). Its `transform` is set\n * imperatively by `attachViewportTransform` and is deliberately NOT in this\n * recipe — so a reactive framework binding can't re-render the node tree on\n * every pan frame by owning the transform.\n */\nexport function viewportStyle(): ViewportStyle {\n return {\n position: \"absolute\",\n inset: 0,\n transformOrigin: \"0 0\",\n pointerEvents: \"none\",\n };\n}\n","import {\n createEntityChangeNotifier,\n pathToSVG,\n type EdgePathData,\n type FlowEntityChangeNotifierOptions,\n type FlowStore,\n type Rect,\n} from \"@statelyai/flow\";\n\nexport type EntityRectTarget = {\n id: string;\n getRect: () => Rect | null;\n autoSize?: boolean;\n};\n\nexport type EntityBoundsTarget = {\n ids: readonly string[];\n getRect: () => Rect | null;\n};\n\nexport type EntityEdgeTarget = {\n id: string;\n getPathData: () => EdgePathData | null;\n};\n\nexport type EntityGeometryObserverOptions =\n FlowEntityChangeNotifierOptions & {\n requestFrame?: (callback: FrameRequestCallback) => number;\n cancelFrame?: (handle: number) => void;\n };\n\nexport type EntityGeometryObserver = {\n observeRect(element: HTMLElement, target: EntityRectTarget): () => void;\n observeBounds(element: HTMLElement, target: EntityBoundsTarget): () => void;\n observeEdge(element: SVGElement, target: EntityEdgeTarget): () => void;\n /** Flush pending writes synchronously. Primarily useful for deterministic hosts/tests. */\n flush(): void;\n disconnect(): void;\n};\n\ntype Observation = {\n write: () => void;\n unsubscribe: () => void;\n};\n\n/**\n * Batches transient entity geometry into imperative DOM writes. One core\n * entity-change notifier keeps dispatch O(changed); framework adapters retain\n * ownership of content, selection, and other durable rendering.\n */\nexport function createEntityGeometryObserver(\n store: FlowStore,\n options: EntityGeometryObserverOptions = {},\n): EntityGeometryObserver {\n const requestFrame =\n options.requestFrame ?? ((callback) => requestAnimationFrame(callback));\n const cancelFrame =\n options.cancelFrame ?? ((handle) => cancelAnimationFrame(handle));\n const createNotifier = () =>\n createEntityChangeNotifier(store, {\n getEdgeDependents: options.getEdgeDependents,\n });\n let notifier: ReturnType<typeof createEntityChangeNotifier> | null =\n createNotifier();\n const getNotifier = () => (notifier ??= createNotifier());\n const observations = new Set<Observation>();\n const pending = new Set<Observation>();\n let frame: number | null = null;\n\n const flush = () => {\n if (frame !== null) {\n cancelFrame(frame);\n frame = null;\n }\n const current = [...pending];\n pending.clear();\n for (const observation of current) observation.write();\n };\n\n const schedule = (observation: Observation) => {\n pending.add(observation);\n if (frame === null) {\n frame = requestFrame(() => {\n frame = null;\n const current = [...pending];\n pending.clear();\n for (const pendingObservation of current) pendingObservation.write();\n });\n }\n };\n\n const observeIds = (\n ids: Iterable<string>,\n write: () => void,\n ): (() => void) => {\n const observation = {\n write,\n unsubscribe: () => {},\n };\n const unsubscribers = [...new Set(ids)].map((id) =>\n getNotifier().subscribe(id, () => schedule(observation)),\n );\n observation.unsubscribe = () => {\n for (const unsubscribe of unsubscribers) unsubscribe();\n };\n observations.add(observation);\n write();\n\n return () => {\n observation.unsubscribe();\n observations.delete(observation);\n pending.delete(observation);\n };\n };\n\n const observe = (id: string, write: () => void): (() => void) =>\n observeIds([id], write);\n\n return {\n observeRect(element, target) {\n return observe(target.id, () => {\n const rect = target.getRect();\n if (!rect) return;\n const context = store.getSnapshot().context;\n const dragging =\n context.canvasState === \"dragging\" && context.selection.has(target.id);\n const resizing = context.resizingEntityId === target.id;\n const layoutAnimating =\n context.layoutAnimation.status === \"running\" &&\n context.layoutAnimation.offsets.has(target.id);\n\n element.style.transform = `translate(${rect.x}px, ${rect.y}px)`;\n // An auto-sized node is content-owned until an explicit resize begins.\n // During the gesture Flow owns the live rectangle, so the hot path must\n // still write width/height without waiting for a framework render.\n if (!target.autoSize || resizing) {\n element.style.width = `${rect.width}px`;\n element.style.height = `${rect.height}px`;\n }\n if (dragging || resizing || layoutAnimating) {\n element.style.willChange = resizing\n ? \"transform, width, height\"\n : \"transform\";\n } else {\n element.style.removeProperty(\"will-change\");\n }\n });\n },\n\n observeBounds(element, target) {\n return observeIds(target.ids, () => {\n const rect = target.getRect();\n if (!rect) return;\n const context = store.getSnapshot().context;\n\n element.style.transform = `translate(${rect.x}px, ${rect.y}px)`;\n element.style.width = `${rect.width}px`;\n element.style.height = `${rect.height}px`;\n if (\n context.canvasState === \"dragging\" ||\n context.canvasState === \"resizing\" ||\n context.layoutAnimation.status === \"running\"\n ) {\n element.style.willChange = \"transform, width, height\";\n } else {\n element.style.removeProperty(\"will-change\");\n }\n });\n },\n\n observeEdge(element, target) {\n // Legacy custom renderers emit route paths without segment attributes.\n // Bind exact route copies (including hit strokes) once, then retain the\n // binding as their d values change. Unrelated decoration paths stay owned\n // by the renderer; explicit segment attributes always take precedence.\n const inferredSegments = new WeakMap<SVGPathElement, number>();\n return observe(target.id, () => {\n const pathData = target.getPathData();\n if (!pathData) return;\n\n const svgSegments = pathData.segments.map(pathToSVG);\n element\n .querySelectorAll<SVGPathElement>(\"path\")\n .forEach((path) => {\n const explicitIndex = path.dataset.flowEdgeSegment;\n let index = explicitIndex === undefined\n ? inferredSegments.get(path)\n : Number(explicitIndex);\n if (index === undefined) {\n const matchedIndex = svgSegments.indexOf(path.getAttribute(\"d\") ?? \"\");\n if (matchedIndex < 0) return;\n index = matchedIndex;\n inferredSegments.set(path, index);\n }\n const segment = svgSegments[index];\n if (segment !== undefined) path.setAttribute(\"d\", segment);\n });\n\n const first = pathData.segments[0]?.points[0];\n const last = pathData.segments.at(-1)?.points.at(-1);\n for (const [end, point] of [[\"source\", first], [\"target\", last]] as const) {\n if (!point) continue;\n element.querySelectorAll<SVGCircleElement>(\n `[data-flow-edge-endpoint=\"${end}\"]`,\n ).forEach((handle) => {\n const x = Number(handle.dataset.flowEdgeEndpointOffsetX ?? 0);\n const y = Number(handle.dataset.flowEdgeEndpointOffsetY ?? 0);\n handle.setAttribute(\"cx\", String(point.x + (Number.isFinite(x) ? x : 0)));\n handle.setAttribute(\"cy\", String(point.y + (Number.isFinite(y) ? y : 0)));\n });\n }\n });\n },\n\n flush,\n\n disconnect() {\n if (frame !== null) cancelFrame(frame);\n frame = null;\n pending.clear();\n for (const observation of observations) observation.unsubscribe();\n observations.clear();\n notifier?.destroy();\n notifier = null;\n },\n };\n}\n","import type { FlowColorMode } from '@statelyai/flow';\n\nexport type ResolvedFlowColorMode = 'light' | 'dark';\n\ntype ColorModeWindow = Pick<Window, 'matchMedia'>;\n\nfunction inheritedColorMode(element?: Element | null): ResolvedFlowColorMode | undefined {\n for (let ancestor = element?.parentElement; ancestor; ancestor = ancestor.parentElement) {\n const theme = ancestor.getAttribute('data-theme') ?? ancestor.getAttribute('data-flow-color-mode');\n if (theme === 'light' || theme === 'dark') return theme;\n if (ancestor.classList.contains('dark')) return 'dark';\n if (ancestor.classList.contains('light')) return 'light';\n }\n return undefined;\n}\n\nexport function resolveFlowColorMode(\n colorMode: FlowColorMode,\n targetWindow: ColorModeWindow | undefined = typeof window === 'undefined' ? undefined : window,\n element?: Element | null,\n): ResolvedFlowColorMode {\n if (colorMode !== 'system') return colorMode;\n return inheritedColorMode(element) ?? (\n targetWindow?.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'\n );\n}\n\nexport function applyFlowColorMode(\n element: HTMLElement,\n colorMode: FlowColorMode,\n targetWindow: ColorModeWindow | undefined = element.ownerDocument.defaultView ?? undefined,\n): ResolvedFlowColorMode {\n const resolved = resolveFlowColorMode(colorMode, targetWindow, element);\n if (element.dataset.flowColorMode !== resolved) element.dataset.flowColorMode = resolved;\n if (element.dataset.flowColorModePreference !== colorMode) element.dataset.flowColorModePreference = colorMode;\n if (element.style.colorScheme !== resolved) element.style.colorScheme = resolved;\n return resolved;\n}\n\n/** Track ancestor theme attributes and OS preference. Returns a cleanup function. */\nexport function observeFlowColorMode(\n element: HTMLElement,\n colorMode: FlowColorMode,\n onChange?: (resolved: ResolvedFlowColorMode) => void,\n): () => void {\n const targetWindow = element.ownerDocument.defaultView;\n // Apply even when the caller does not need a notification.\n const refresh = () => {\n const resolved = applyFlowColorMode(element, colorMode);\n onChange?.(resolved);\n };\n refresh();\n if (colorMode !== 'system') return () => {};\n const media = targetWindow?.matchMedia?.('(prefers-color-scheme: dark)');\n media?.addEventListener('change', refresh);\n const Observer = targetWindow?.MutationObserver;\n const observer = Observer ? new Observer(refresh) : undefined;\n for (let ancestor = element.parentElement; ancestor; ancestor = ancestor.parentElement) {\n observer?.observe(ancestor, {\n attributes: true,\n attributeFilter: ['class', 'data-theme', 'data-flow-color-mode'],\n });\n }\n return () => {\n media?.removeEventListener('change', refresh);\n observer?.disconnect();\n };\n}\n","export { attachInteractionCursor } from './interaction-cursor';\nexport { observeAppearanceBounds } from \"./appearance-bounds\";\nimport type { FlowStore, Point } from '@statelyai/flow';\n\nexport * from '@statelyai/flow';\nexport {\n createFlowClipboard,\n FLOW_CONTENT_MIME,\n type ClipboardTransport,\n type FlowClipboard,\n} from './clipboard';\nexport {\n createFlowView,\n exportFlowImage,\n type FlowImageExportOptions,\n type FlowImageExportResult,\n type FlowView,\n} from './exportImage';\n\nexport {\n computeRenderableIds,\n computeSettledRenderableIds,\n renderableIdsEqual,\n type ComputeRenderableIdsOptions,\n type RenderableIds,\n type SettledRenderableIds,\n} from './culling';\n\nexport {\n nodePositionStyle,\n viewportStyle,\n type NodePositionStyle,\n type ViewportStyle,\n} from './render-styles';\n\nexport {\n createEntityGeometryObserver,\n type EntityBoundsTarget,\n type EntityEdgeTarget,\n type EntityGeometryObserver,\n type EntityGeometryObserverOptions,\n type EntityRectTarget,\n} from './entity-geometry';\n\nexport {\n resolveFlowColorMode,\n applyFlowColorMode,\n observeFlowColorMode,\n type ResolvedFlowColorMode,\n} from './color-mode';\n\nexport type MeasurementTarget =\n | { appearanceId: string; relativeTo: Element }\n | { nodeId: string }\n | { nodeId: string; portName: string }\n | { edgeId: string };\n\nexport type MeasurementObserver = {\n observe(element: Element, target: MeasurementTarget): void;\n /** Re-measure now (position-only changes don't fire ResizeObserver). */\n measure(element: Element): void;\n refresh(targets?: Iterable<string | Element>): void;\n unobserve(element: Element): void;\n disconnect(): void;\n};\n\nexport type MeasurementObserverOptions = {\n container?: Element | (() => Element | null | undefined) | null;\n equalityThreshold?: number;\n};\n\nconst containers = new WeakMap<FlowStore, Element>();\n\nfunction hasOwnScale(element: Element): boolean {\n const transform = element.ownerDocument.defaultView\n ?.getComputedStyle(element).transform;\n if (!transform || transform === 'none') return false;\n const values = /^matrix\\(([^)]*)\\)$/.exec(transform)?.[1].split(',').map(Number);\n if (!values) return true;\n const [a, b, c, d] = values;\n return a !== 1 || b !== 0 || c !== 0 || d !== 1;\n}\n\nexport function createMeasurementObserver(\n store: FlowStore,\n options: MeasurementObserverOptions = {}\n): MeasurementObserver {\n const equalityThreshold = options.equalityThreshold ?? 0.5;\n type Registration = {\n target: MeasurementTarget;\n origin?: Point;\n /** The element's last ResizeObserver layout size. */\n layoutSize?: { width: number; height: number };\n };\n const elementMap = new Map<Element, Registration>();\n let pendingMeasurements: Array<{\n element: Element;\n registration: Registration;\n measurement: {\n id: string;\n origin?: Point;\n rect: { x: number; y: number; width: number; height: number };\n };\n }> = [];\n let rafId: number | null = null;\n\n function flush() {\n rafId = null;\n\n const measurements = pendingMeasurements\n .filter(({ element, registration }) => elementMap.get(element) === registration)\n .map(({ measurement }) => measurement);\n pendingMeasurements = [];\n if (measurements.length > 0) {\n store.trigger.updateMeasurements({ measurements });\n }\n }\n\n function scheduleFlush() {\n if (rafId === null) {\n rafId = requestAnimationFrame(flush);\n }\n }\n\n function pushMeasurement(\n element: Element,\n registration: Registration,\n // Layout (border-box) size from a ResizeObserver entry. Preferred for\n // width/height because it is independent of the canvas zoom transform —\n // unlike getBoundingClientRect()/zoom, which races with an in-flight zoom\n // and wrote corrupted sizes back into the graph (the \"node resizing\" bug).\n layoutSize?: { width: number; height: number }\n ): void {\n const { target } = registration;\n // A re-measure keeps the last observed layout size: only a resize changes\n // it, and ResizeObserver reports every resize.\n if (layoutSize) registration.layoutSize = layoutSize;\n else layoutSize = registration.layoutSize;\n // An element with its own scale (e.g. an inverse-zoom port) renders at a\n // different size than its layout box, so only its screen rect is right.\n if (layoutSize && hasOwnScale(element)) layoutSize = undefined;\n const viewport = store.getSnapshot().context.viewport;\n const zoom = viewport.zoom || 1;\n const rect = element.getBoundingClientRect();\n const containerRect = (\n getContainer(options.container) ?? containers.get(store)\n )?.getBoundingClientRect();\n const relativeRect = \"relativeTo\" in target ? target.relativeTo.getBoundingClientRect() : undefined;\n const measurement = {\n x: (rect.left - (relativeRect?.left ?? (containerRect?.left ?? 0) + viewport.x)) / zoom,\n y: (rect.top - (relativeRect?.top ?? (containerRect?.top ?? 0) + viewport.y)) / zoom,\n width: layoutSize ? layoutSize.width : rect.width / zoom,\n height: layoutSize ? layoutSize.height : rect.height / zoom,\n };\n\n const id =\n 'appearanceId' in target ? target.appearanceId : 'portName' in target\n ? `${target.nodeId}:${target.portName}`\n : 'nodeId' in target\n ? target.nodeId\n : target.edgeId;\n\n let origin: Point | undefined;\n if ('portName' in target) {\n for (let owner = element.parentElement; owner; owner = owner.parentElement) {\n if (owner.getAttribute('data-entity-id') !== target.nodeId) continue;\n const bounds = owner.getBoundingClientRect();\n origin = {\n x: (bounds.left - (containerRect?.left ?? 0) - viewport.x) / zoom,\n y: (bounds.top - (containerRect?.top ?? 0) - viewport.y) / zoom,\n };\n break;\n }\n }\n // Idempotence: skip when the store already holds this measurement —\n // keeps repeated re-measures (e.g. per-render port reporting) from\n // producing new store transitions every frame.\n const existing = store.getSnapshot().context.measurements.get(id);\n if (\n existing &&\n origin?.x === registration.origin?.x && origin?.y === registration.origin?.y &&\n Math.abs(existing.x - measurement.x) < equalityThreshold &&\n Math.abs(existing.y - measurement.y) < equalityThreshold &&\n Math.abs(existing.width - measurement.width) < equalityThreshold &&\n Math.abs(existing.height - measurement.height) < equalityThreshold\n ) {\n return;\n }\n\n registration.origin = origin;\n pendingMeasurements.push({ element, registration, measurement: {\n id, rect: measurement, ...(origin ? { origin } : {}),\n } });\n scheduleFlush();\n }\n\n const handleResize: ResizeObserverCallback = (entries, source) => {\n if (source !== observer) return;\n for (const entry of entries) {\n const registration = elementMap.get(entry.target);\n if (!registration) continue;\n // Border-box size is the zoom-independent layout size; fall back to the\n // content rect, then to getBoundingClientRect()/zoom inside pushMeasurement.\n const box = entry.borderBoxSize?.[0];\n const layoutSize = box\n ? { width: box.inlineSize, height: box.blockSize }\n : entry.contentRect\n ? { width: entry.contentRect.width, height: entry.contentRect.height }\n : undefined;\n pushMeasurement(entry.target, registration, layoutSize);\n }\n };\n let observer: ResizeObserver | null = null;\n\n function getObserver(element: Element): ResizeObserver {\n if (observer) return observer;\n const ResizeObserverCtor = element.ownerDocument.defaultView?.ResizeObserver ?? ResizeObserver;\n observer = new ResizeObserverCtor(handleResize);\n return observer;\n }\n\n return {\n observe(element: Element, target: MeasurementTarget) {\n const replacing = elementMap.has(element);\n const registration = { target };\n elementMap.set(element, registration);\n // Border-box observation also reports border-only size changes.\n getObserver(element).observe(element, { box: 'border-box' });\n // ResizeObserver need not notify again for an unchanged observed element.\n if (replacing) pushMeasurement(element, registration);\n },\n\n /**\n * Re-measure an observed element immediately. ResizeObserver only fires\n * on SIZE changes — position-only changes (layout passes, graph swaps,\n * a port moving within its node) need an explicit re-measure.\n */\n measure(element: Element) {\n const registration = elementMap.get(element);\n if (registration) pushMeasurement(element, registration);\n },\n\n refresh(targets) {\n const requested = targets ? new Set(targets) : null;\n for (const [element, registration] of elementMap) {\n const { target } = registration;\n const id =\n 'appearanceId' in target ? target.appearanceId : 'portName' in target\n ? `${target.nodeId}:${target.portName}`\n : 'nodeId' in target\n ? target.nodeId\n : target.edgeId;\n if (requested && !requested.has(element) && !requested.has(id)) continue;\n pushMeasurement(element, registration);\n }\n },\n\n unobserve(element: Element) {\n elementMap.delete(element);\n observer?.unobserve(element);\n },\n\n disconnect() {\n elementMap.clear();\n observer?.disconnect();\n observer = null;\n\n if (rafId !== null) {\n cancelAnimationFrame(rafId);\n rafId = null;\n }\n\n pendingMeasurements = [];\n },\n };\n}\n\nfunction getContainer(container: MeasurementObserverOptions['container']): Element | null {\n return typeof container === 'function' ? container() ?? null : container ?? null;\n}\n\n/** The container element registered for this store via `attachContainer`. */\nexport function getAttachedContainer(store: FlowStore): Element | undefined {\n return containers.get(store);\n}\n\nexport function clientToCanvas(\n store: FlowStore,\n point: Point,\n container: Element | null | undefined = containers.get(store)\n): Point {\n const rect = container?.getBoundingClientRect();\n const viewport = store.getSnapshot().context.viewport;\n const zoom = viewport.zoom || 1;\n return {\n x: (point.x - (rect?.left ?? 0) - viewport.x) / zoom,\n y: (point.y - (rect?.top ?? 0) - viewport.y) / zoom,\n };\n}\n\nexport function canvasToClient(\n store: FlowStore,\n point: Point,\n container: Element | null | undefined = containers.get(store)\n): Point {\n const rect = container?.getBoundingClientRect();\n const viewport = store.getSnapshot().context.viewport;\n return {\n x: point.x * viewport.zoom + viewport.x + (rect?.left ?? 0),\n y: point.y * viewport.zoom + viewport.y + (rect?.top ?? 0),\n };\n}\n\nexport function attachContainer(\n store: FlowStore,\n element: Element,\n options: { preserveViewportCenter?: boolean } = {}\n): () => void {\n containers.set(store, element);\n\n const update = () => {\n const rect = element.getBoundingClientRect();\n\n if (rect.width > 0 && rect.height > 0) {\n store.trigger.updateViewportSize({\n width: rect.width,\n height: rect.height,\n preserveCenter: options.preserveViewportCenter,\n });\n }\n };\n\n // Browsers can scroll overflow:hidden containers to reveal focused inputs.\n // Keep that reveal, but express it in the viewport so backgrounds, overlays,\n // and client/canvas coordinate conversion stay aligned with the graph.\n const onScroll = (event: Event) => {\n if (event.target !== element) return;\n const { scrollLeft, scrollTop } = element;\n if (!scrollLeft && !scrollTop) return;\n element.scrollLeft = 0;\n element.scrollTop = 0;\n store.trigger.panBy({ x: -scrollLeft, y: -scrollTop });\n };\n element.addEventListener('scroll', onScroll);\n\n update();\n\n const ResizeObserverCtor = element.ownerDocument.defaultView?.ResizeObserver ?? ResizeObserver;\n const observer = new ResizeObserverCtor(update);\n observer.observe(element);\n\n return () => {\n if (containers.get(store) === element) {\n containers.delete(store);\n }\n\n element.removeEventListener('scroll', onScroll);\n observer.disconnect();\n };\n}\n\n// Viewport transform (framework-agnostic \"source of rendering truth\" for pan/zoom)\n//\n// Drives one canvas element's pan/zoom transform imperatively from the store —\n// NOT through a framework's reactive style binding, which would re-render every\n// node on every frame. It also GPU-promotes the element (`will-change:\n// transform`) for the duration of any active interaction (dragging/panning/\n// resizing/...), so the thousands of static nodes/edges inside are rasterized\n// once and the GPU just slides the layer instead of repainting it each frame;\n// the hint is dropped shortly after activity stops so layer memory isn't held\n// at idle. Framework adapters should mount a single transformed viewport element\n// (with all node/edge layers as static children) and hand it here. See\n// ADAPTER_NOTES.md for the full set of rules a performant DOM adapter must follow.\n\nexport type ViewportTransformOptions = {\n /** Idle delay (ms) before dropping the GPU-layer hint after interaction stops. */\n promoteIdleMs?: number;\n /**\n * The zoom written to `--flow-zoom` and `--flow-inverse-zoom`, when it\n * should differ from the live zoom. Every element below the viewport\n * inherits these variables, so changing them restyles the whole canvas.\n * Returning a settled zoom during a zoom gesture keeps each frame to a\n * transform change. Defaults to the live zoom.\n */\n getVariableZoom?: () => number | undefined;\n};\n\n/**\n * Write `--flow-zoom` and `--flow-inverse-zoom`. Every element below inherits\n * them, so a change restyles the whole canvas; an unchanged value is skipped.\n */\nexport function writeZoomVariables(element: HTMLElement, zoom: number): void {\n const value = String(zoom);\n if (element.style.getPropertyValue('--flow-zoom') === value) return;\n element.style.setProperty('--flow-zoom', value);\n element.style.setProperty('--flow-inverse-zoom', String(1 / zoom));\n}\n\nexport function attachViewportTransform(\n store: FlowStore,\n element: HTMLElement,\n options: ViewportTransformOptions = {}\n): () => void {\n const promoteIdleMs = options.promoteIdleMs ?? 200;\n let prevViewport = store.getSnapshot().context.viewport;\n let prevState = store.getSnapshot().context.canvasState;\n let idle: ReturnType<typeof setTimeout> | undefined;\n\n const writeTransform = (viewport: { x: number; y: number; zoom: number }): void => {\n element.style.transform = `translate(${viewport.x}px, ${viewport.y}px) scale(${viewport.zoom})`;\n // Expose zoom to CSS so descendants can keep on-screen sizes constant\n // (e.g. selection outlines via `calc(1px / var(--flow-zoom))`).\n writeZoomVariables(element, options.getVariableZoom?.() ?? viewport.zoom);\n };\n const promote = (): void => {\n element.style.willChange = 'transform';\n if (idle !== undefined) clearTimeout(idle);\n };\n const scheduleClear = (): void => {\n if (idle !== undefined) clearTimeout(idle);\n idle = setTimeout(() => {\n element.style.willChange = 'auto';\n }, promoteIdleMs);\n };\n\n writeTransform(prevViewport);\n if (prevState === 'panning') promote();\n\n const subscription = store.subscribe((snapshot) => {\n const context = snapshot.context;\n if (context.viewport !== prevViewport) {\n prevViewport = context.viewport;\n writeTransform(context.viewport);\n // Wheel-zoom changes the viewport without entering a non-idle state.\n promote();\n if (context.canvasState !== 'panning') scheduleClear();\n }\n if (context.canvasState !== prevState) {\n prevState = context.canvasState;\n if (prevState === 'panning') promote();\n else scheduleClear();\n }\n });\n\n return () => {\n if (idle !== undefined) clearTimeout(idle);\n subscription.unsubscribe();\n };\n}\n\n// Input binding (DOM → FlowInputRuntime)\n//\n// Normalizes browser pointer/wheel/keyboard events into FlowInputEvents and\n// feeds them to a core input runtime (`createFlowInputRuntime` from\n// @statelyai/flow). Target detection uses the data attributes that flow\n// renderers set explicitly (`data-entity-id`, `data-flow-edge-label`,\n// `data-flow-port-name`, `data-flow-canvas-layer`) — no magic class names.\n//\n// Only type imports from @statelyai/flow are used here so the peer stays\n// optional for consumers that only need the measurement/color helpers.\n\nimport type {\n FlowInputEffects,\n FlowInputEvent,\n FlowInputModifiers,\n FlowInputTarget,\n} from '@statelyai/flow';\n\ntype FlowPoint = { x: number; y: number };\n\nexport type AttachInputOptions = {\n container: HTMLElement;\n store: FlowStore;\n runtime: {\n send(event: FlowInputEvent): FlowInputEffects;\n cancelSession(): void;\n getActiveSession?(): string | null;\n };\n /**\n * Where keyboard events are listened for. Defaults to the flow container so\n * multiple flow instances do not all react to global Delete/undo/arrow keys.\n */\n keyboardTarget?: 'window' | 'container' | HTMLElement;\n /**\n * Auto-pan policy, evaluated once per animation frame while a gesture\n * session holds the pointer near the container edge. Pass\n * `getAutoPanDelta` from @statelyai/flow (injected as a function so this\n * package keeps no runtime dependency on the optional peer). When it\n * returns a delta, the binder pans the viewport and re-sends the\n * stationary pointer so the dragged entity follows the canvas.\n */\n autoPan?: (\n context: ReturnType<FlowStore['getSnapshot']>['context'],\n screenPoint: { x: number; y: number }\n ) => { x: number; y: number } | null;\n};\n\nexport function attachInput(options: AttachInputOptions): () => void {\n const { container, store, runtime } = options;\n const doc = container.ownerDocument;\n const win = doc.defaultView;\n const ElementCtor = win?.Element;\n const HTMLElementCtor = win?.HTMLElement;\n const keyboardTarget = options.keyboardTarget ?? 'container';\n const keyboardElement =\n keyboardTarget === 'window' ? win : keyboardTarget === 'container' ? container : keyboardTarget;\n let capturedPointerId: number | null = null;\n let pointerCaptureOwner = {};\n let gestureContainerOffset: { left: number; top: number } | null = null;\n let lastContainerOffset: { left: number; top: number } | null = null;\n let lastClient: {\n x: number;\n y: number;\n pointerId: number;\n modifiers: FlowInputModifiers;\n } | null = null;\n let autoPanFrame: number | null = null;\n const activeTouchPointers = new Map<\n number,\n {\n clientX: number;\n clientY: number;\n modifiers: FlowInputModifiers;\n }\n >();\n let pinchActive = false;\n // Native PointerEvent.detail is unreliable for click counting: most browsers\n // leave `detail` as 0 on `pointerdown` (the click-count only lands on the\n // compatibility mouse events / `click` / `dblclick`). doubleClickZoomMode\n // gates on `detail >= 2`, so we derive the click count ourselves — mirroring\n // how a browser increments MouseEvent.detail — for mouse/pen pointerdowns.\n const DOUBLE_CLICK_MS = 500;\n const DOUBLE_CLICK_DISTANCE = 4;\n let lastClickDown: { time: number; x: number; y: number } | null = null;\n let clickCount = 0;\n let lastPinch: {\n screenCenter: FlowPoint;\n center: FlowPoint;\n distance: number;\n modifiers: FlowInputModifiers;\n } | null = null;\n\n function stopAutoPan(): void {\n if (autoPanFrame !== null) {\n win?.cancelAnimationFrame(autoPanFrame);\n autoPanFrame = null;\n }\n }\n\n function autoPanTick(): void {\n autoPanFrame = null;\n if (!options.autoPan || capturedPointerId === null || !lastClient) {\n return;\n }\n const rect = gestureContainerOffset ?? container.getBoundingClientRect();\n const screenPoint = {\n x: lastClient.x - rect.left,\n y: lastClient.y - rect.top,\n };\n const delta = options.autoPan(store.getSnapshot().context, screenPoint);\n if (delta) {\n store.trigger.panBy({ x: -delta.x, y: -delta.y });\n // Re-send the stationary pointer through the runtime: the canvas moved\n // under it, so the active session sees the new canvas position.\n sendPointer('pointer.move', lastClient.x, lastClient.y, {\n pointerId: lastClient.pointerId,\n button: -1,\n modifiers: lastClient.modifiers,\n target: null,\n });\n }\n scheduleAutoPan();\n }\n\n function scheduleAutoPan(): void {\n if (options.autoPan && autoPanFrame === null && win) {\n autoPanFrame = win.requestAnimationFrame(autoPanTick);\n }\n }\n\n function modifiers(event: {\n shiftKey: boolean;\n metaKey: boolean;\n ctrlKey: boolean;\n altKey: boolean;\n }): FlowInputModifiers {\n return {\n shift: event.shiftKey,\n meta: event.metaKey,\n ctrl: event.ctrlKey,\n alt: event.altKey,\n };\n }\n\n // Derive the click count for a mouse/pen pointerdown. Native\n // PointerEvent.detail can't be trusted here (see clickCount declaration), so\n // we count downs that land close together in time and space, resetting\n // otherwise — matching browser MouseEvent.detail semantics.\n function computeClickDetail(event: PointerEvent): number {\n if (event.pointerType === 'touch') return event.detail || 0;\n const now = event.timeStamp || (win ? win.performance.now() : Date.now());\n if (\n lastClickDown &&\n now - lastClickDown.time <= DOUBLE_CLICK_MS &&\n Math.abs(event.clientX - lastClickDown.x) <= DOUBLE_CLICK_DISTANCE &&\n Math.abs(event.clientY - lastClickDown.y) <= DOUBLE_CLICK_DISTANCE\n ) {\n clickCount += 1;\n } else {\n clickCount = 1;\n }\n lastClickDown = { time: now, x: event.clientX, y: event.clientY };\n return clickCount;\n }\n\n function toPoints(event: { clientX: number; clientY: number }): {\n screenPoint: FlowPoint;\n point: FlowPoint;\n } {\n const rect = gestureContainerOffset ?? container.getBoundingClientRect();\n lastContainerOffset = { left: rect.left, top: rect.top };\n if (capturedPointerId !== null && gestureContainerOffset === null) {\n gestureContainerOffset = lastContainerOffset;\n }\n const screenPoint = {\n x: event.clientX - rect.left,\n y: event.clientY - rect.top,\n };\n const { viewport } = store.getSnapshot().context;\n const zoom = viewport.zoom || 1;\n return {\n screenPoint,\n point: {\n x: (screenPoint.x - viewport.x) / zoom,\n y: (screenPoint.y - viewport.y) / zoom,\n },\n };\n }\n\n function resolveTarget(event: {\n clientX: number;\n clientY: number;\n target: EventTarget | null;\n }): FlowInputTarget {\n // While the container holds pointer capture, event.target is the capture\n // element — hit-test the document instead so drags see what is under the\n // pointer.\n const element =\n capturedPointerId !== null\n ? doc.elementFromPoint(event.clientX, event.clientY)\n : ElementCtor && event.target instanceof ElementCtor\n ? event.target\n : null;\n if (!element) return { kind: 'none' };\n if (!container.contains(element)) return { kind: 'none' };\n const owningRoot = element.closest('[data-flow-root]');\n if (owningRoot && owningRoot !== container) return { kind: 'none' };\n\n const portElement = element.closest<HTMLElement>('[data-flow-port-name]');\n if (portElement?.dataset.flowPortName) {\n return {\n kind: 'port',\n nodeId: portElement.dataset.flowNodeId ?? '',\n portName: portElement.dataset.flowPortName,\n portId: portElement.dataset.flowPortId,\n interaction:\n portElement.dataset.flowPortInteraction === \"inspect\"\n ? \"inspect\"\n : \"connect\",\n };\n }\n\n // Opt-out for custom interactive content inside entities (resize\n // handles, buttons, inputs, control points): presses inside a\n // [data-flow-interactive] subtree are invisible to gesture modes, so\n // the element's own pointer handlers run unopposed.\n if (\n element.closest(\n '[data-flow-interactive], .nodrag, input, textarea, select, button, a[href], [contenteditable]:not([contenteditable=\"false\"])'\n )\n ) {\n return { kind: 'none' };\n }\n const entityElement = element.closest<HTMLElement>('[data-entity-id]');\n if (entityElement?.dataset.entityId) {\n const isLabel = element.closest('[data-flow-edge-label]') !== null;\n const partElement = element.closest<HTMLElement>('[data-flow-part]');\n const part = partElement?.dataset.flowPart ?? (isLabel ? 'label' : undefined);\n const entityHasDragHandle = entityElement.querySelector('[data-flow-drag-handle]') !== null;\n const pressedDragHandle =\n entityHasDragHandle && element.closest('[data-flow-drag-handle]') !== null;\n return {\n kind: 'entity',\n id: entityElement.dataset.entityId,\n ...(part ? { part } : {}),\n ...(entityHasDragHandle ? { entityHasDragHandle, pressedDragHandle } : {}),\n } as FlowInputTarget;\n }\n\n if (element === container || element.closest('[data-flow-canvas-layer]') !== null) {\n return { kind: 'pane' };\n }\n\n return { kind: 'none' };\n }\n\n function applyEffects(event: Event, effects: FlowInputEffects): void {\n if (effects.preventDefault) event.preventDefault();\n if (effects.stopPropagation) event.stopPropagation();\n }\n\n function sendPointer(\n kind: 'pointer.down' | 'pointer.move' | 'pointer.up' | 'pointer.cancel',\n clientX: number,\n clientY: number,\n info: {\n pointerId: number;\n pointerType?: 'mouse' | 'pen' | 'touch';\n button: number;\n detail?: number;\n modifiers: FlowInputModifiers;\n /** Pass null to hit-test via elementFromPoint (synthetic re-sends). */\n target: EventTarget | null;\n }\n ): FlowInputEffects {\n const { screenPoint, point } = toPoints({ clientX, clientY });\n const activeSession = runtime.getActiveSession?.() ?? null;\n const targetIndependentSession =\n activeSession === 'entity-press' ||\n activeSession === 'pan' ||\n activeSession === 'pane-press' ||\n activeSession === 'box-select';\n const effects = runtime.send({\n kind,\n pointerId: info.pointerId,\n pointerType: info.pointerType ?? 'mouse',\n button: info.button,\n detail: info.detail,\n point,\n screenPoint,\n // Built-in drag/pan/select sessions use pointer geometry only. Avoid a\n // document hit test on every captured move; connection/reconnect and\n // custom sessions still receive exact targets.\n target:\n kind === 'pointer.move' && targetIndependentSession\n ? { kind: 'none' }\n : resolveTarget({ clientX, clientY, target: info.target }),\n modifiers: info.modifiers,\n } as unknown as FlowInputEvent);\n\n if (effects.sessionStarted && kind === 'pointer.down') {\n try {\n container.setPointerCapture(info.pointerId);\n } catch {\n // Inactive pointer (e.g. synthetic events) — capture is best-effort.\n }\n capturedPointerId = info.pointerId;\n pointerCaptureOwner = {};\n // Container geometry is stable for one captured gesture. Reusing the\n // pointer-down offset avoids a forced layout read on every move.\n gestureContainerOffset =\n lastContainerOffset ?? (() => {\n const rect = container.getBoundingClientRect();\n return { left: rect.left, top: rect.top };\n })();\n scheduleAutoPan();\n }\n if (effects.sessionEnded && capturedPointerId !== null) {\n releaseCapturedPointer();\n }\n return effects;\n }\n\n function touchPoints() {\n return [...activeTouchPointers.values()];\n }\n\n function pinchGeometry(): {\n screenCenter: FlowPoint;\n center: FlowPoint;\n distance: number;\n modifiers: FlowInputModifiers;\n } | null {\n const touches = touchPoints();\n if (touches.length < 2) return null;\n const [a, b] = touches;\n const screenCenter = {\n x: (a.clientX + b.clientX) / 2 - container.getBoundingClientRect().left,\n y: (a.clientY + b.clientY) / 2 - container.getBoundingClientRect().top,\n };\n const { point: center } = toPoints({\n clientX: (a.clientX + b.clientX) / 2,\n clientY: (a.clientY + b.clientY) / 2,\n });\n return {\n screenCenter,\n center,\n distance: Math.hypot(b.clientX - a.clientX, b.clientY - a.clientY),\n modifiers: a.modifiers,\n };\n }\n\n function sendPinch(kind: 'pinch.start' | 'pinch.move' | 'pinch.end'): FlowInputEffects {\n const geometry = kind === 'pinch.end' ? lastPinch : pinchGeometry();\n const fallback = geometry ?? lastPinch;\n if (!fallback) return makeNoEffects();\n lastPinch = fallback;\n return runtime.send({\n kind,\n center: fallback.center,\n screenCenter: fallback.screenCenter,\n distance: fallback.distance,\n pointerCount: activeTouchPointers.size,\n modifiers: fallback.modifiers,\n } as unknown as FlowInputEvent);\n }\n\n function makeNoEffects(): FlowInputEffects {\n return {\n preventDefault: false,\n stopPropagation: false,\n sessionStarted: false,\n sessionEnded: false,\n handledBy: null,\n };\n }\n\n function releaseCapturedPointer(): void {\n if (capturedPointerId === null) return;\n const pointerId = capturedPointerId;\n capturedPointerId = null;\n try {\n if (container.hasPointerCapture(pointerId)) {\n container.releasePointerCapture(pointerId);\n }\n } catch {\n // Already released.\n }\n gestureContainerOffset = null;\n lastClient = null;\n stopAutoPan();\n }\n\n function handlePointer(kind: 'pointer.down' | 'pointer.move' | 'pointer.up' | 'pointer.cancel') {\n return (event: PointerEvent) => {\n if (kind === 'pointer.down') {\n focusContainerForPanePress(event);\n }\n const pointerType =\n event.pointerType === 'touch' ||\n event.pointerType === 'pen' ||\n event.pointerType === 'mouse'\n ? event.pointerType\n : 'mouse';\n if (pointerType === 'touch') {\n if (kind === 'pointer.down') {\n activeTouchPointers.set(event.pointerId, {\n clientX: event.clientX,\n clientY: event.clientY,\n modifiers: modifiers(event),\n });\n if (activeTouchPointers.size === 2) {\n runtime.cancelSession();\n releaseCapturedPointer();\n pinchActive = true;\n lastPinch = pinchGeometry();\n const effects = sendPinch('pinch.start');\n applyEffects(event, effects);\n return;\n }\n if (activeTouchPointers.size > 2) {\n applyEffects(event, sendPinch('pinch.move'));\n return;\n }\n } else if (activeTouchPointers.has(event.pointerId)) {\n if (kind === 'pointer.move') {\n activeTouchPointers.set(event.pointerId, {\n clientX: event.clientX,\n clientY: event.clientY,\n modifiers: modifiers(event),\n });\n if (pinchActive) {\n const effects = sendPinch('pinch.move');\n applyEffects(event, effects);\n return;\n }\n } else if (kind === 'pointer.up' || kind === 'pointer.cancel') {\n activeTouchPointers.delete(event.pointerId);\n if (pinchActive) {\n const effects = sendPinch('pinch.end');\n pinchActive = false;\n lastPinch = null;\n applyEffects(event, effects);\n return;\n }\n }\n }\n }\n\n if (\n kind === 'pointer.down' ||\n (capturedPointerId !== null && event.pointerId === capturedPointerId)\n ) {\n lastClient = {\n x: event.clientX,\n y: event.clientY,\n pointerId: event.pointerId,\n modifiers: modifiers(event),\n };\n }\n // Only left-button pointerdowns carry a derived click count; native\n // detail is unreliable on pointer events, so we compute it here.\n const detail =\n kind === 'pointer.down' && event.button === 0 ? computeClickDetail(event) : event.detail;\n const effects = sendPointer(kind, event.clientX, event.clientY, {\n pointerId: event.pointerId,\n pointerType,\n button: event.button,\n detail,\n modifiers: modifiers(event),\n target: event.target,\n });\n applyEffects(event, effects);\n };\n }\n\n function handleWheel(event: WheelEvent): void {\n const { screenPoint, point } = toPoints(event);\n const effects = runtime.send({\n kind: 'wheel',\n deltaX: event.deltaX,\n deltaY: event.deltaY,\n deltaMode: event.deltaMode,\n point,\n screenPoint,\n target: resolveTarget(event),\n modifiers: modifiers(event),\n });\n applyEffects(event, effects);\n }\n\n function handleContextMenu(event: MouseEvent): void {\n const effects = sendPointer('pointer.down', event.clientX, event.clientY, {\n pointerId: -1,\n pointerType: 'mouse',\n button: 2,\n detail: event.detail,\n modifiers: modifiers(event),\n target: event.target,\n });\n applyEffects(event, effects);\n }\n\n function isEditableTarget(target: EventTarget | null): boolean {\n if (!HTMLElementCtor || !(target instanceof HTMLElementCtor)) return false;\n return (\n target.isContentEditable ||\n target.matches(\"input, textarea, select, [contenteditable='true']\")\n );\n }\n\n function isInteractiveTarget(target: EventTarget | null): boolean {\n return (\n !!ElementCtor &&\n target instanceof ElementCtor &&\n target.closest('[data-flow-interactive]') !== null\n );\n }\n\n function focusContainerForPanePress(event: PointerEvent): void {\n if (keyboardTarget !== 'container') return;\n if (isEditableTarget(event.target) || isInteractiveTarget(event.target)) return;\n if (\n resolveTarget({\n clientX: event.clientX,\n clientY: event.clientY,\n target: event.target,\n }).kind !== 'pane'\n )\n return;\n container.focus({ preventScroll: true });\n }\n\n function handleKey(kind: 'key.down' | 'key.up') {\n return (event: KeyboardEvent) => {\n const previousCaptureOwner = pointerCaptureOwner;\n const effects = runtime.send({\n kind,\n key: event.key,\n editableTarget: isEditableTarget(event.target),\n modifiers: modifiers(event),\n });\n if (effects.sessionEnded && pointerCaptureOwner === previousCaptureOwner) {\n releaseCapturedPointer();\n }\n applyEffects(event, effects);\n };\n }\n\n const onPointerDown = handlePointer('pointer.down');\n const onPointerMove = handlePointer('pointer.move');\n const onPointerUp = handlePointer('pointer.up');\n const onPointerCancel = handlePointer('pointer.cancel');\n const onLostPointerCapture = (event: PointerEvent) => {\n if (capturedPointerId === null || capturedPointerId !== event.pointerId) return;\n stopAutoPan();\n runtime.cancelSession();\n capturedPointerId = null;\n gestureContainerOffset = null;\n lastClient = null;\n };\n const onWindowBlur = () => {\n stopAutoPan();\n runtime.cancelSession();\n activeTouchPointers.clear();\n capturedPointerId = null;\n gestureContainerOffset = null;\n lastClient = null;\n };\n const onContainerGeometryChange = () => {\n gestureContainerOffset = null;\n lastContainerOffset = null;\n };\n const onKeyDown = handleKey('key.down') as EventListener;\n const onKeyUp = handleKey('key.up') as EventListener;\n\n if (keyboardTarget === 'container' && !container.hasAttribute('tabindex')) {\n container.tabIndex = 0;\n }\n container.addEventListener('pointerdown', onPointerDown);\n container.addEventListener('pointermove', onPointerMove);\n container.addEventListener('pointerup', onPointerUp);\n container.addEventListener('pointercancel', onPointerCancel);\n container.addEventListener('lostpointercapture', onLostPointerCapture);\n container.addEventListener('contextmenu', handleContextMenu);\n container.addEventListener('wheel', handleWheel, { passive: false });\n keyboardElement?.addEventListener('keydown', onKeyDown);\n keyboardElement?.addEventListener('keyup', onKeyUp);\n win?.addEventListener('blur', onWindowBlur);\n win?.addEventListener('resize', onContainerGeometryChange);\n win?.addEventListener('scroll', onContainerGeometryChange, true);\n\n return () => {\n stopAutoPan();\n runtime.cancelSession();\n activeTouchPointers.clear();\n pinchActive = false;\n lastPinch = null;\n container.removeEventListener('pointerdown', onPointerDown);\n container.removeEventListener('pointermove', onPointerMove);\n container.removeEventListener('pointerup', onPointerUp);\n container.removeEventListener('pointercancel', onPointerCancel);\n container.removeEventListener('lostpointercapture', onLostPointerCapture);\n container.removeEventListener('contextmenu', handleContextMenu);\n container.removeEventListener('wheel', handleWheel);\n keyboardElement?.removeEventListener('keydown', onKeyDown);\n keyboardElement?.removeEventListener('keyup', onKeyUp);\n win?.removeEventListener('blur', onWindowBlur);\n win?.removeEventListener('resize', onContainerGeometryChange);\n win?.removeEventListener('scroll', onContainerGeometryChange, true);\n };\n}\n"],"mappings":";;;;AAGA,SAAgB,wBAAwB,OAAkB,SAAkC;CAC1F,MAAM,WAAW,QAAQ,aAAa,kBAAkB;CACxD,MAAM,eAAe;EACnB,MAAM,QAAQ,MAAM,YAAY,CAAC,CAAC,QAAQ;EAC1C,MAAM,SAAS,UAAU,cAA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C5D,KAAK,oBAAoB,UAAU,2BAA2B,IAAI;CACpE;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@statelyai/flow-dom",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.7.0",
|
|
4
4
|
"description": "DOM-specific helpers for @statelyai/flow with core re-exports.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
"resizeobserver"
|
|
12
12
|
],
|
|
13
13
|
"files": [
|
|
14
|
-
"dist"
|
|
14
|
+
"dist",
|
|
15
|
+
"src"
|
|
15
16
|
],
|
|
16
17
|
"source": "src/index.ts",
|
|
17
18
|
"main": "dist/esm/index.js",
|
|
@@ -27,7 +28,7 @@
|
|
|
27
28
|
},
|
|
28
29
|
"license": "MIT",
|
|
29
30
|
"dependencies": {
|
|
30
|
-
"@statelyai/flow": "0.
|
|
31
|
+
"@statelyai/flow": "0.15.0"
|
|
31
32
|
},
|
|
32
33
|
"devDependencies": {
|
|
33
34
|
"@vitest/coverage-v8": "^4.1.0",
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from "vitest";
|
|
2
|
+
import { createFlowStore } from "@statelyai/flow";
|
|
3
|
+
import { observeAppearanceBounds } from "./appearance-bounds";
|
|
4
|
+
import { createMeasurementObserver, type MeasurementObserver } from "./index";
|
|
5
|
+
|
|
6
|
+
function setup(selector = "[data-body]") {
|
|
7
|
+
const store = createFlowStore();
|
|
8
|
+
const wrapper = document.createElement("div");
|
|
9
|
+
wrapper.innerHTML = '<div data-body></div>';
|
|
10
|
+
const observer: MeasurementObserver = {
|
|
11
|
+
observe: vi.fn(), measure: vi.fn(), refresh: vi.fn(),
|
|
12
|
+
unobserve: vi.fn(), disconnect: vi.fn(),
|
|
13
|
+
};
|
|
14
|
+
const cleanup = observeAppearanceBounds(store, wrapper, "border", observer, { selector });
|
|
15
|
+
return { store, wrapper, observer, cleanup };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
describe("appearance selector borders", () => {
|
|
19
|
+
it("scopes measurement to one descendant and follows replacements without a framework render", async () => {
|
|
20
|
+
const { wrapper, observer, cleanup } = setup();
|
|
21
|
+
const old = wrapper.firstElementChild!;
|
|
22
|
+
expect(observer.observe).toHaveBeenCalledWith(old, { appearanceId: "border", relativeTo: wrapper });
|
|
23
|
+
wrapper.innerHTML = '<span data-body></span>';
|
|
24
|
+
await Promise.resolve();
|
|
25
|
+
expect(observer.unobserve).toHaveBeenCalledWith(old);
|
|
26
|
+
expect(observer.observe).toHaveBeenLastCalledWith(wrapper.firstElementChild, { appearanceId: "border", relativeTo: wrapper });
|
|
27
|
+
cleanup();
|
|
28
|
+
expect(observer.unobserve).toHaveBeenLastCalledWith(wrapper.firstElementChild);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it("clears stale bounds for absent, ambiguous, and invalid selectors", async () => {
|
|
32
|
+
const { store, wrapper, cleanup } = setup();
|
|
33
|
+
store.trigger.updateMeasurements({ measurements: [{ id: "border", rect: { x: 1, y: 2, width: 3, height: 4 } }] });
|
|
34
|
+
wrapper.innerHTML = '<div data-body></div><div data-body></div>';
|
|
35
|
+
await Promise.resolve();
|
|
36
|
+
expect(store.getSnapshot().context.measurements.has("border")).toBe(false);
|
|
37
|
+
cleanup();
|
|
38
|
+
for (const selector of ["[", "[data-missing]"]) {
|
|
39
|
+
const test = setup(selector);
|
|
40
|
+
expect(test.observer.observe).not.toHaveBeenCalled();
|
|
41
|
+
test.cleanup();
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it("remeasures in-place caption edits and layout-changing wrapper styles", async () => {
|
|
46
|
+
const { wrapper, observer, cleanup } = setup();
|
|
47
|
+
const caption = document.createTextNode("Caption");
|
|
48
|
+
wrapper.prepend(caption);
|
|
49
|
+
await Promise.resolve();
|
|
50
|
+
vi.mocked(observer.measure).mockClear();
|
|
51
|
+
caption.data = "Caption with another line";
|
|
52
|
+
await Promise.resolve();
|
|
53
|
+
expect(observer.measure).toHaveBeenCalledWith(wrapper.firstElementChild);
|
|
54
|
+
vi.mocked(observer.measure).mockClear();
|
|
55
|
+
wrapper.style.paddingTop = "20px";
|
|
56
|
+
await Promise.resolve();
|
|
57
|
+
expect(observer.measure).toHaveBeenCalledWith(wrapper.firstElementChild);
|
|
58
|
+
vi.mocked(observer.measure).mockClear();
|
|
59
|
+
wrapper.style.transform = "translate(10px, 20px)";
|
|
60
|
+
wrapper.style.willChange = "transform";
|
|
61
|
+
await Promise.resolve();
|
|
62
|
+
expect(observer.measure).not.toHaveBeenCalled();
|
|
63
|
+
wrapper.style.transform = "scale(2)";
|
|
64
|
+
await Promise.resolve();
|
|
65
|
+
expect(observer.measure).toHaveBeenCalled();
|
|
66
|
+
cleanup();
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("supports the existing border attribute without selector configuration", () => {
|
|
70
|
+
const store = createFlowStore();
|
|
71
|
+
const wrapper = document.createElement("div");
|
|
72
|
+
wrapper.innerHTML = '<div data-flow-connection-bounds></div>';
|
|
73
|
+
const observer: MeasurementObserver = {
|
|
74
|
+
observe: vi.fn(), measure: vi.fn(), refresh: vi.fn(),
|
|
75
|
+
unobserve: vi.fn(), disconnect: vi.fn(),
|
|
76
|
+
};
|
|
77
|
+
const cleanup = observeAppearanceBounds(store, wrapper, "legacy", observer);
|
|
78
|
+
expect(observer.observe).toHaveBeenCalledWith(wrapper.firstElementChild,
|
|
79
|
+
{ appearanceId: "legacy", relativeTo: wrapper });
|
|
80
|
+
cleanup();
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it("discards queued measurements when a border is unobserved", async () => {
|
|
84
|
+
const store = createFlowStore();
|
|
85
|
+
const observer = createMeasurementObserver(store);
|
|
86
|
+
const wrapper = document.createElement("div");
|
|
87
|
+
const border = document.createElement("div");
|
|
88
|
+
wrapper.append(border);
|
|
89
|
+
observer.observe(border, { appearanceId: "border", relativeTo: wrapper });
|
|
90
|
+
observer.measure(border);
|
|
91
|
+
observer.unobserve(border);
|
|
92
|
+
observer.refresh();
|
|
93
|
+
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
|
|
94
|
+
expect(store.getSnapshot().context.measurements.has("border")).toBe(false);
|
|
95
|
+
observer.disconnect();
|
|
96
|
+
});
|
|
97
|
+
});
|