@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
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { FlowStore } from "@statelyai/flow";
|
|
2
|
+
import type { MeasurementObserver } from "./index";
|
|
3
|
+
|
|
4
|
+
/** Observe one appearance-local connection border without changing visual bounds. */
|
|
5
|
+
export function observeAppearanceBounds(
|
|
6
|
+
store: FlowStore,
|
|
7
|
+
wrapper: Element,
|
|
8
|
+
key: string,
|
|
9
|
+
observer: MeasurementObserver,
|
|
10
|
+
options: { selector?: string } = {}
|
|
11
|
+
): () => void {
|
|
12
|
+
let boundary: Element | null = null;
|
|
13
|
+
const clear = () => {
|
|
14
|
+
if (boundary) observer.unobserve(boundary);
|
|
15
|
+
boundary = null;
|
|
16
|
+
if (store.getSnapshot().context.measurements.has(key)) {
|
|
17
|
+
store.trigger.removeMeasurements({ ids: [key] });
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
const refresh = () => {
|
|
21
|
+
let matches: NodeListOf<Element> | undefined;
|
|
22
|
+
try {
|
|
23
|
+
matches = wrapper.querySelectorAll(
|
|
24
|
+
options.selector ?? "[data-flow-connection-bounds]"
|
|
25
|
+
);
|
|
26
|
+
} catch {
|
|
27
|
+
// Invalid selectors use visual bounds, just like missing borders.
|
|
28
|
+
}
|
|
29
|
+
const next = matches?.length === 1 ? matches[0] : null;
|
|
30
|
+
if (!next || next !== boundary) {
|
|
31
|
+
clear();
|
|
32
|
+
boundary = next;
|
|
33
|
+
if (boundary) {
|
|
34
|
+
observer.observe(boundary, { appearanceId: key, relativeTo: wrapper });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
observer.measure(wrapper);
|
|
38
|
+
if (boundary) observer.measure(boundary);
|
|
39
|
+
};
|
|
40
|
+
const targetWindow = wrapper.ownerDocument.defaultView;
|
|
41
|
+
// Captions can move a border without changing the border's own size.
|
|
42
|
+
const resize = new (targetWindow?.ResizeObserver ?? ResizeObserver)(refresh);
|
|
43
|
+
resize.observe(wrapper);
|
|
44
|
+
// Compare layout styles without Flow's translation/will-change hot-path writes.
|
|
45
|
+
const style = wrapper.ownerDocument.createElement("div").style;
|
|
46
|
+
const layoutStyle = () => {
|
|
47
|
+
style.cssText = wrapper.getAttribute("style") ?? "";
|
|
48
|
+
return JSON.stringify(Array.from(style).sort()
|
|
49
|
+
.filter((property) => {
|
|
50
|
+
if (property === "will-change") return false;
|
|
51
|
+
return property !== "transform" ||
|
|
52
|
+
!/^translate\([^)]*\)$/.test(style.getPropertyValue(property));
|
|
53
|
+
})
|
|
54
|
+
.map((property) => [
|
|
55
|
+
property, style.getPropertyValue(property), style.getPropertyPriority(property),
|
|
56
|
+
]));
|
|
57
|
+
};
|
|
58
|
+
let previousStyle = layoutStyle();
|
|
59
|
+
const mutations = new (targetWindow?.MutationObserver ?? MutationObserver)((records) => {
|
|
60
|
+
const currentStyle = layoutStyle();
|
|
61
|
+
const layoutChanged = currentStyle !== previousStyle;
|
|
62
|
+
previousStyle = currentStyle;
|
|
63
|
+
if (layoutChanged || records.some((record) =>
|
|
64
|
+
record.type !== "attributes" || record.target !== wrapper || record.attributeName !== "style"
|
|
65
|
+
)) refresh();
|
|
66
|
+
});
|
|
67
|
+
mutations.observe(wrapper, {
|
|
68
|
+
subtree: true, childList: true, attributes: true, characterData: true,
|
|
69
|
+
});
|
|
70
|
+
wrapper.addEventListener("load", refresh, true);
|
|
71
|
+
refresh();
|
|
72
|
+
return () => {
|
|
73
|
+
resize.disconnect();
|
|
74
|
+
mutations.disconnect();
|
|
75
|
+
wrapper.removeEventListener("load", refresh, true);
|
|
76
|
+
clear();
|
|
77
|
+
};
|
|
78
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
createFlow,
|
|
4
|
+
createGraph,
|
|
5
|
+
createNode,
|
|
6
|
+
defaultFlowProfile,
|
|
7
|
+
} from '@statelyai/flow';
|
|
8
|
+
import { createFlowClipboard } from './clipboard';
|
|
9
|
+
|
|
10
|
+
describe('Flow clipboard', () => {
|
|
11
|
+
it('copies and pastes between independent controllers', async () => {
|
|
12
|
+
let text = '';
|
|
13
|
+
const transport = {
|
|
14
|
+
writeText: vi.fn(async (value: string) => { text = value; }),
|
|
15
|
+
readText: vi.fn(async () => text),
|
|
16
|
+
};
|
|
17
|
+
const source = createFlow({
|
|
18
|
+
graph: createGraph({ nodes: [createNode({ id: 'a', x: 20 })], edges: [] }),
|
|
19
|
+
});
|
|
20
|
+
const target = createFlow({
|
|
21
|
+
graph: createGraph({ nodes: [], edges: [] }),
|
|
22
|
+
createId: ({ sourceId }) => `pasted:${sourceId}`,
|
|
23
|
+
});
|
|
24
|
+
source.selection.set(['a']);
|
|
25
|
+
expect(await createFlowClipboard(source, { clipboard: transport }).copy()).toBe(true);
|
|
26
|
+
const result = await createFlowClipboard(target, { clipboard: transport }).paste();
|
|
27
|
+
expect(result.ok).toBe(true);
|
|
28
|
+
expect(target.getNode('pasted:a')).toBeDefined();
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('keeps memory fallback but does not delete after a failed cut write', async () => {
|
|
32
|
+
const flow = createFlow({
|
|
33
|
+
graph: createGraph({ nodes: [createNode({ id: 'a' })], edges: [] }),
|
|
34
|
+
});
|
|
35
|
+
flow.selection.set(['a']);
|
|
36
|
+
const clipboard = createFlowClipboard(flow, {
|
|
37
|
+
clipboard: { writeText: vi.fn(async () => { throw new Error('denied'); }) },
|
|
38
|
+
});
|
|
39
|
+
expect(await clipboard.cut()).toBe(false);
|
|
40
|
+
expect(flow.getNode('a')).toBeDefined();
|
|
41
|
+
expect((await clipboard.paste()).ok).toBe(true);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('does not write when copy or cut is denied', async () => {
|
|
45
|
+
const writeText = vi.fn(async () => {});
|
|
46
|
+
const flow = createFlow({
|
|
47
|
+
graph: createGraph({ nodes: [createNode({ id: 'a' })], edges: [] }),
|
|
48
|
+
store: {
|
|
49
|
+
profile: {
|
|
50
|
+
...defaultFlowProfile,
|
|
51
|
+
policies: { canCopy: false },
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
flow.selection.set(['a']);
|
|
56
|
+
const clipboard = createFlowClipboard(flow, {
|
|
57
|
+
clipboard: { writeText },
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
expect(await clipboard.copy()).toBe(false);
|
|
61
|
+
expect(await clipboard.cut()).toBe(false);
|
|
62
|
+
expect(writeText).not.toHaveBeenCalled();
|
|
63
|
+
expect(flow.getNode('a')).toBeDefined();
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('does not paste stale fallback content after a successful non-Flow read', async () => {
|
|
67
|
+
let text = '';
|
|
68
|
+
const transport = {
|
|
69
|
+
writeText: vi.fn(async (value: string) => {
|
|
70
|
+
text = value;
|
|
71
|
+
}),
|
|
72
|
+
readText: vi.fn(async () => text),
|
|
73
|
+
};
|
|
74
|
+
const flow = createFlow({
|
|
75
|
+
graph: createGraph({ nodes: [createNode({ id: 'a' })], edges: [] }),
|
|
76
|
+
});
|
|
77
|
+
flow.selection.set(['a']);
|
|
78
|
+
const clipboard = createFlowClipboard(flow, { clipboard: transport });
|
|
79
|
+
|
|
80
|
+
expect(await clipboard.copy()).toBe(true);
|
|
81
|
+
text = 'ordinary clipboard text';
|
|
82
|
+
expect((await clipboard.paste()).ok).toBe(false);
|
|
83
|
+
expect(flow.getSnapshot().graph.nodes).toHaveLength(1);
|
|
84
|
+
});
|
|
85
|
+
});
|
package/src/clipboard.ts
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
FlowContent,
|
|
3
|
+
FlowController,
|
|
4
|
+
FlowResult,
|
|
5
|
+
Point,
|
|
6
|
+
} from '@statelyai/flow';
|
|
7
|
+
|
|
8
|
+
export const FLOW_CONTENT_MIME = 'application/vnd.stately.flow+json';
|
|
9
|
+
|
|
10
|
+
export type ClipboardTransport = {
|
|
11
|
+
writeText?: (value: string) => Promise<void>;
|
|
12
|
+
readText?: () => Promise<string>;
|
|
13
|
+
write?: (items: unknown[]) => Promise<void>;
|
|
14
|
+
read?: () => Promise<Array<{ types: readonly string[]; getType(type: string): Promise<Blob> }>>;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export type FlowClipboard = {
|
|
18
|
+
copy: (targets?: Iterable<string>) => Promise<boolean>;
|
|
19
|
+
cut: (targets?: Iterable<string>) => Promise<boolean>;
|
|
20
|
+
paste: (options?: { point?: Point; preservePosition?: boolean }) => Promise<FlowResult<unknown, Error>>;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export function createFlowClipboard(
|
|
24
|
+
flow: FlowController,
|
|
25
|
+
options: {
|
|
26
|
+
clipboard?: ClipboardTransport;
|
|
27
|
+
ClipboardItem?: new (items: Record<string, Blob>) => unknown;
|
|
28
|
+
} = {},
|
|
29
|
+
): FlowClipboard {
|
|
30
|
+
const clipboard = options.clipboard ??
|
|
31
|
+
(globalThis.navigator?.clipboard as ClipboardTransport | undefined);
|
|
32
|
+
let fallback: FlowContent | null = null;
|
|
33
|
+
|
|
34
|
+
async function write(content: FlowContent): Promise<boolean> {
|
|
35
|
+
fallback = content;
|
|
36
|
+
const json = JSON.stringify(content);
|
|
37
|
+
try {
|
|
38
|
+
if (clipboard?.write && options.ClipboardItem) {
|
|
39
|
+
const html = `<div data-stately-flow>${escapeHtml(json)}</div>`;
|
|
40
|
+
await clipboard.write([
|
|
41
|
+
new options.ClipboardItem({
|
|
42
|
+
[FLOW_CONTENT_MIME]: new Blob([json], { type: FLOW_CONTENT_MIME }),
|
|
43
|
+
'text/plain': new Blob([json], { type: 'text/plain' }),
|
|
44
|
+
'text/html': new Blob([html], { type: 'text/html' }),
|
|
45
|
+
}),
|
|
46
|
+
]);
|
|
47
|
+
} else if (clipboard?.writeText) {
|
|
48
|
+
await clipboard.writeText(json);
|
|
49
|
+
}
|
|
50
|
+
return true;
|
|
51
|
+
} catch {
|
|
52
|
+
// The in-memory value remains available for this adapter instance.
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function read(): Promise<unknown> {
|
|
58
|
+
let readSucceeded = false;
|
|
59
|
+
try {
|
|
60
|
+
if (clipboard?.read) {
|
|
61
|
+
const items = await clipboard.read();
|
|
62
|
+
readSucceeded = true;
|
|
63
|
+
for (const item of items) {
|
|
64
|
+
const type = item.types.includes(FLOW_CONTENT_MIME)
|
|
65
|
+
? FLOW_CONTENT_MIME
|
|
66
|
+
: item.types.includes('text/plain')
|
|
67
|
+
? 'text/plain'
|
|
68
|
+
: null;
|
|
69
|
+
if (type) return parseJson(await (await item.getType(type)).text());
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (clipboard?.readText) {
|
|
73
|
+
const text = await clipboard.readText();
|
|
74
|
+
readSucceeded = true;
|
|
75
|
+
if (text) return parseJson(text);
|
|
76
|
+
}
|
|
77
|
+
} catch {
|
|
78
|
+
if (readSucceeded) return null;
|
|
79
|
+
return fallback;
|
|
80
|
+
}
|
|
81
|
+
return readSucceeded ? null : fallback;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function canRun(
|
|
85
|
+
command: 'copy' | 'cut',
|
|
86
|
+
targets: readonly string[] | undefined,
|
|
87
|
+
): boolean {
|
|
88
|
+
if (!targets) return flow.can(command);
|
|
89
|
+
return (
|
|
90
|
+
targets.length > 0 &&
|
|
91
|
+
targets.every((id) => flow.can(command, { id }))
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
async copy(targets) {
|
|
97
|
+
const ids = targets ? [...targets] : undefined;
|
|
98
|
+
if (!canRun('copy', ids)) return false;
|
|
99
|
+
const content = flow.content.extract(ids);
|
|
100
|
+
if (!content) return false;
|
|
101
|
+
await write(content);
|
|
102
|
+
return true;
|
|
103
|
+
},
|
|
104
|
+
async cut(targets) {
|
|
105
|
+
const ids = targets
|
|
106
|
+
? [...targets]
|
|
107
|
+
: [...flow.getSnapshot().selection];
|
|
108
|
+
if (!canRun('cut', ids)) return false;
|
|
109
|
+
const content = flow.content.extract(ids);
|
|
110
|
+
if (!content) return false;
|
|
111
|
+
if (!(await write(content))) return false;
|
|
112
|
+
flow.transaction((draft) => {
|
|
113
|
+
for (const id of ids) {
|
|
114
|
+
if (!draft.edges.delete(id)) draft.nodes.delete(id);
|
|
115
|
+
}
|
|
116
|
+
}, { origin: 'clipboard.cut' });
|
|
117
|
+
return true;
|
|
118
|
+
},
|
|
119
|
+
async paste(insertOptions) {
|
|
120
|
+
const content = await read();
|
|
121
|
+
if (!content) {
|
|
122
|
+
return {
|
|
123
|
+
ok: false,
|
|
124
|
+
error: new Error('Clipboard does not contain Flow content.'),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
return flow.content.insert(content, insertOptions);
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function parseJson(value: string): unknown | null {
|
|
133
|
+
try {
|
|
134
|
+
return JSON.parse(value);
|
|
135
|
+
} catch {
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function escapeHtml(value: string): string {
|
|
141
|
+
return value
|
|
142
|
+
.replaceAll('&', '&')
|
|
143
|
+
.replaceAll('<', '<')
|
|
144
|
+
.replaceAll('>', '>');
|
|
145
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import { resolveFlowColorMode, applyFlowColorMode, observeFlowColorMode } from './index';
|
|
3
|
+
|
|
4
|
+
describe('resolveFlowColorMode', () => {
|
|
5
|
+
it('resolves "light" to "light"', () => {
|
|
6
|
+
expect(resolveFlowColorMode('light')).toBe('light');
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
it('resolves "dark" to "dark"', () => {
|
|
10
|
+
expect(resolveFlowColorMode('dark')).toBe('dark');
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
it('resolves "system" to "light" when matchMedia does not match dark', () => {
|
|
14
|
+
const mockWindow = {
|
|
15
|
+
matchMedia: vi.fn().mockReturnValue({ matches: false }),
|
|
16
|
+
};
|
|
17
|
+
expect(resolveFlowColorMode('system', mockWindow)).toBe('light');
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it('resolves "system" to "dark" when matchMedia matches dark', () => {
|
|
21
|
+
const mockWindow = {
|
|
22
|
+
matchMedia: vi.fn().mockReturnValue({ matches: true }),
|
|
23
|
+
};
|
|
24
|
+
expect(resolveFlowColorMode('system', mockWindow)).toBe('dark');
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('uses the nearest ancestor theme and permits an explicit override', () => {
|
|
29
|
+
const outer = document.createElement('div');
|
|
30
|
+
outer.className = 'dark';
|
|
31
|
+
outer.innerHTML = '<div data-theme="light"><div></div></div>';
|
|
32
|
+
const canvas = outer.firstElementChild!.firstElementChild as HTMLElement;
|
|
33
|
+
expect(applyFlowColorMode(canvas, 'system')).toBe('light');
|
|
34
|
+
expect(applyFlowColorMode(canvas, 'dark')).toBe('dark');
|
|
35
|
+
outer.firstElementChild!.removeAttribute('data-theme');
|
|
36
|
+
expect(applyFlowColorMode(canvas, 'system')).toBe('dark');
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('tracks ancestor changes and stops observing on disposal', async () => {
|
|
40
|
+
const parent = document.createElement('div');
|
|
41
|
+
const canvas = document.createElement('div');
|
|
42
|
+
parent.append(canvas);
|
|
43
|
+
parent.dataset.theme = 'dark';
|
|
44
|
+
const changed = vi.fn();
|
|
45
|
+
const dispose = observeFlowColorMode(canvas, 'system', changed);
|
|
46
|
+
expect(canvas.dataset.flowColorMode).toBe('dark');
|
|
47
|
+
parent.dataset.theme = 'light';
|
|
48
|
+
await Promise.resolve();
|
|
49
|
+
expect(canvas.dataset.flowColorMode).toBe('light');
|
|
50
|
+
dispose();
|
|
51
|
+
parent.dataset.theme = 'dark';
|
|
52
|
+
await Promise.resolve();
|
|
53
|
+
expect(canvas.dataset.flowColorMode).toBe('light');
|
|
54
|
+
});
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { FlowColorMode } from '@statelyai/flow';
|
|
2
|
+
|
|
3
|
+
export type ResolvedFlowColorMode = 'light' | 'dark';
|
|
4
|
+
|
|
5
|
+
type ColorModeWindow = Pick<Window, 'matchMedia'>;
|
|
6
|
+
|
|
7
|
+
function inheritedColorMode(element?: Element | null): ResolvedFlowColorMode | undefined {
|
|
8
|
+
for (let ancestor = element?.parentElement; ancestor; ancestor = ancestor.parentElement) {
|
|
9
|
+
const theme = ancestor.getAttribute('data-theme') ?? ancestor.getAttribute('data-flow-color-mode');
|
|
10
|
+
if (theme === 'light' || theme === 'dark') return theme;
|
|
11
|
+
if (ancestor.classList.contains('dark')) return 'dark';
|
|
12
|
+
if (ancestor.classList.contains('light')) return 'light';
|
|
13
|
+
}
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function resolveFlowColorMode(
|
|
18
|
+
colorMode: FlowColorMode,
|
|
19
|
+
targetWindow: ColorModeWindow | undefined = typeof window === 'undefined' ? undefined : window,
|
|
20
|
+
element?: Element | null,
|
|
21
|
+
): ResolvedFlowColorMode {
|
|
22
|
+
if (colorMode !== 'system') return colorMode;
|
|
23
|
+
return inheritedColorMode(element) ?? (
|
|
24
|
+
targetWindow?.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function applyFlowColorMode(
|
|
29
|
+
element: HTMLElement,
|
|
30
|
+
colorMode: FlowColorMode,
|
|
31
|
+
targetWindow: ColorModeWindow | undefined = element.ownerDocument.defaultView ?? undefined,
|
|
32
|
+
): ResolvedFlowColorMode {
|
|
33
|
+
const resolved = resolveFlowColorMode(colorMode, targetWindow, element);
|
|
34
|
+
if (element.dataset.flowColorMode !== resolved) element.dataset.flowColorMode = resolved;
|
|
35
|
+
if (element.dataset.flowColorModePreference !== colorMode) element.dataset.flowColorModePreference = colorMode;
|
|
36
|
+
if (element.style.colorScheme !== resolved) element.style.colorScheme = resolved;
|
|
37
|
+
return resolved;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Track ancestor theme attributes and OS preference. Returns a cleanup function. */
|
|
41
|
+
export function observeFlowColorMode(
|
|
42
|
+
element: HTMLElement,
|
|
43
|
+
colorMode: FlowColorMode,
|
|
44
|
+
onChange?: (resolved: ResolvedFlowColorMode) => void,
|
|
45
|
+
): () => void {
|
|
46
|
+
const targetWindow = element.ownerDocument.defaultView;
|
|
47
|
+
// Apply even when the caller does not need a notification.
|
|
48
|
+
const refresh = () => {
|
|
49
|
+
const resolved = applyFlowColorMode(element, colorMode);
|
|
50
|
+
onChange?.(resolved);
|
|
51
|
+
};
|
|
52
|
+
refresh();
|
|
53
|
+
if (colorMode !== 'system') return () => {};
|
|
54
|
+
const media = targetWindow?.matchMedia?.('(prefers-color-scheme: dark)');
|
|
55
|
+
media?.addEventListener('change', refresh);
|
|
56
|
+
const Observer = targetWindow?.MutationObserver;
|
|
57
|
+
const observer = Observer ? new Observer(refresh) : undefined;
|
|
58
|
+
for (let ancestor = element.parentElement; ancestor; ancestor = ancestor.parentElement) {
|
|
59
|
+
observer?.observe(ancestor, {
|
|
60
|
+
attributes: true,
|
|
61
|
+
attributeFilter: ['class', 'data-theme', 'data-flow-color-mode'],
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
return () => {
|
|
65
|
+
media?.removeEventListener('change', refresh);
|
|
66
|
+
observer?.disconnect();
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
2
|
+
import { createFlowStore } from '@statelyai/flow';
|
|
3
|
+
import { attachContainer, canvasToClient, clientToCanvas, getAttachedContainer } from './index';
|
|
4
|
+
|
|
5
|
+
// Track created ResizeObserver instances so tests can assert on them.
|
|
6
|
+
const observerInstances: Array<{
|
|
7
|
+
observe: ReturnType<typeof vi.fn>;
|
|
8
|
+
disconnect: ReturnType<typeof vi.fn>;
|
|
9
|
+
callback: ResizeObserverCallback;
|
|
10
|
+
}> = [];
|
|
11
|
+
|
|
12
|
+
beforeEach(() => {
|
|
13
|
+
observerInstances.length = 0;
|
|
14
|
+
// Replace the global ResizeObserver with one that records each instance.
|
|
15
|
+
globalThis.ResizeObserver = class MockRO {
|
|
16
|
+
observe = vi.fn();
|
|
17
|
+
unobserve = vi.fn();
|
|
18
|
+
disconnect = vi.fn();
|
|
19
|
+
constructor(public callback: ResizeObserverCallback) {
|
|
20
|
+
observerInstances.push(this as unknown as (typeof observerInstances)[number]);
|
|
21
|
+
}
|
|
22
|
+
} as unknown as typeof ResizeObserver;
|
|
23
|
+
});
|
|
24
|
+
describe('attachContainer', () => {
|
|
25
|
+
it('fires updateViewportSize for a non-zero element', () => {
|
|
26
|
+
const store = createFlowStore();
|
|
27
|
+
const element = document.createElement('div');
|
|
28
|
+
vi.spyOn(element, 'getBoundingClientRect').mockReturnValue({
|
|
29
|
+
width: 800,
|
|
30
|
+
height: 600,
|
|
31
|
+
x: 0,
|
|
32
|
+
y: 0,
|
|
33
|
+
top: 0,
|
|
34
|
+
left: 0,
|
|
35
|
+
right: 800,
|
|
36
|
+
bottom: 600,
|
|
37
|
+
toJSON: () => ({}),
|
|
38
|
+
} as DOMRect);
|
|
39
|
+
|
|
40
|
+
attachContainer(store, element);
|
|
41
|
+
|
|
42
|
+
expect(store.getSnapshot().context.viewportSize).toEqual({ width: 800, height: 600 });
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('cleanup disconnects the observer and removes the container', () => {
|
|
46
|
+
const store = createFlowStore();
|
|
47
|
+
const element = document.createElement('div');
|
|
48
|
+
vi.spyOn(element, 'getBoundingClientRect').mockReturnValue({
|
|
49
|
+
width: 400,
|
|
50
|
+
height: 300,
|
|
51
|
+
x: 0,
|
|
52
|
+
y: 0,
|
|
53
|
+
top: 0,
|
|
54
|
+
left: 0,
|
|
55
|
+
right: 400,
|
|
56
|
+
bottom: 300,
|
|
57
|
+
toJSON: () => ({}),
|
|
58
|
+
} as DOMRect);
|
|
59
|
+
|
|
60
|
+
const cleanup = attachContainer(store, element);
|
|
61
|
+
expect(getAttachedContainer(store)).toBe(element);
|
|
62
|
+
|
|
63
|
+
cleanup();
|
|
64
|
+
|
|
65
|
+
expect(observerInstances[0]!.disconnect).toHaveBeenCalled();
|
|
66
|
+
expect(getAttachedContainer(store)).toBeUndefined();
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('ignores descendant scrolling and removes scroll handling on detach', () => {
|
|
70
|
+
const store = createFlowStore();
|
|
71
|
+
const element = document.createElement('div');
|
|
72
|
+
const child = document.createElement('div');
|
|
73
|
+
element.append(child);
|
|
74
|
+
const cleanup = attachContainer(store, element);
|
|
75
|
+
store.trigger.setViewport({ x: 100, y: 50, zoom: 2 });
|
|
76
|
+
child.scrollTop = 30;
|
|
77
|
+
child.dispatchEvent(new Event('scroll', { bubbles: true }));
|
|
78
|
+
expect(child.scrollTop).toBe(30);
|
|
79
|
+
expect(store.getSnapshot().context.viewport).toEqual({ x: 100, y: 50, zoom: 2 });
|
|
80
|
+
|
|
81
|
+
element.scrollLeft = 80;
|
|
82
|
+
element.scrollTop = 40;
|
|
83
|
+
element.dispatchEvent(new Event('scroll'));
|
|
84
|
+
expect(store.getSnapshot().context.viewport).toEqual({ x: 20, y: 10, zoom: 2 });
|
|
85
|
+
expect([element.scrollLeft, element.scrollTop]).toEqual([0, 0]);
|
|
86
|
+
cleanup();
|
|
87
|
+
element.scrollLeft = 25;
|
|
88
|
+
element.dispatchEvent(new Event('scroll'));
|
|
89
|
+
expect(store.getSnapshot().context.viewport).toEqual({ x: 20, y: 10, zoom: 2 });
|
|
90
|
+
expect(element.scrollLeft).toBe(25);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('skips zero-size elements (viewportSize unchanged)', () => {
|
|
94
|
+
const store = createFlowStore();
|
|
95
|
+
const element = document.createElement('div');
|
|
96
|
+
vi.spyOn(element, 'getBoundingClientRect').mockReturnValue({
|
|
97
|
+
width: 0,
|
|
98
|
+
height: 0,
|
|
99
|
+
x: 0,
|
|
100
|
+
y: 0,
|
|
101
|
+
top: 0,
|
|
102
|
+
left: 0,
|
|
103
|
+
right: 0,
|
|
104
|
+
bottom: 0,
|
|
105
|
+
toJSON: () => ({}),
|
|
106
|
+
} as DOMRect);
|
|
107
|
+
|
|
108
|
+
attachContainer(store, element);
|
|
109
|
+
|
|
110
|
+
expect(store.getSnapshot().context.viewportSize).toEqual({ width: 0, height: 0 });
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it('can preserve the viewport center across container resizes', () => {
|
|
114
|
+
const store = createFlowStore();
|
|
115
|
+
const element = document.createElement('div');
|
|
116
|
+
let rect = {
|
|
117
|
+
width: 800,
|
|
118
|
+
height: 600,
|
|
119
|
+
x: 0,
|
|
120
|
+
y: 0,
|
|
121
|
+
top: 0,
|
|
122
|
+
left: 0,
|
|
123
|
+
right: 800,
|
|
124
|
+
bottom: 600,
|
|
125
|
+
toJSON: () => ({}),
|
|
126
|
+
} as DOMRect;
|
|
127
|
+
vi.spyOn(element, 'getBoundingClientRect').mockImplementation(() => rect);
|
|
128
|
+
|
|
129
|
+
attachContainer(store, element, { preserveViewportCenter: true });
|
|
130
|
+
store.trigger.setViewport({ x: 100, y: 50, zoom: 1 });
|
|
131
|
+
rect = { ...rect, width: 600, right: 600 };
|
|
132
|
+
observerInstances[0]!.callback([], observerInstances[0] as unknown as ResizeObserver);
|
|
133
|
+
|
|
134
|
+
expect(store.getSnapshot().context.viewport).toEqual({
|
|
135
|
+
x: 0,
|
|
136
|
+
y: 50,
|
|
137
|
+
zoom: 1,
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it('converts between client and canvas coordinates using the attached container', () => {
|
|
142
|
+
const store = createFlowStore();
|
|
143
|
+
const element = document.createElement('div');
|
|
144
|
+
vi.spyOn(element, 'getBoundingClientRect').mockReturnValue({
|
|
145
|
+
width: 400,
|
|
146
|
+
height: 300,
|
|
147
|
+
x: 20,
|
|
148
|
+
y: 30,
|
|
149
|
+
top: 30,
|
|
150
|
+
left: 20,
|
|
151
|
+
right: 420,
|
|
152
|
+
bottom: 330,
|
|
153
|
+
toJSON: () => ({}),
|
|
154
|
+
} as DOMRect);
|
|
155
|
+
attachContainer(store, element);
|
|
156
|
+
store.trigger.setViewport({ x: 100, y: 50, zoom: 2 });
|
|
157
|
+
|
|
158
|
+
expect(clientToCanvas(store, { x: 160, y: 120 })).toEqual({
|
|
159
|
+
x: 20,
|
|
160
|
+
y: 20,
|
|
161
|
+
});
|
|
162
|
+
expect(canvasToClient(store, { x: 20, y: 20 })).toEqual({
|
|
163
|
+
x: 160,
|
|
164
|
+
y: 120,
|
|
165
|
+
});
|
|
166
|
+
});
|
|
167
|
+
});
|