@weasel-js/core 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +381 -0
  2. package/LICENSE +21 -0
  3. package/README.md +144 -0
  4. package/dist/DrawCommand-Dl0bXNfS.d.ts +500 -0
  5. package/dist/chunk-775XXAHR.js +216 -0
  6. package/dist/chunk-775XXAHR.js.map +1 -0
  7. package/dist/chunk-7V6JEOXE.js +27754 -0
  8. package/dist/chunk-7V6JEOXE.js.map +1 -0
  9. package/dist/chunk-AM6ARSPN.js +517 -0
  10. package/dist/chunk-AM6ARSPN.js.map +1 -0
  11. package/dist/chunk-BGGZ4CVF.js +248 -0
  12. package/dist/chunk-BGGZ4CVF.js.map +1 -0
  13. package/dist/chunk-BHVYVFGV.js +29 -0
  14. package/dist/chunk-BHVYVFGV.js.map +1 -0
  15. package/dist/chunk-CQNKCG34.js +831 -0
  16. package/dist/chunk-CQNKCG34.js.map +1 -0
  17. package/dist/chunk-GVCNT7UH.js +47 -0
  18. package/dist/chunk-GVCNT7UH.js.map +1 -0
  19. package/dist/chunk-PZ5AY32C.js +9 -0
  20. package/dist/chunk-PZ5AY32C.js.map +1 -0
  21. package/dist/chunk-UGFFCMQP.js +28 -0
  22. package/dist/chunk-UGFFCMQP.js.map +1 -0
  23. package/dist/chunk-VOVKONXA.js +103 -0
  24. package/dist/chunk-VOVKONXA.js.map +1 -0
  25. package/dist/chunk-Y52N27PF.js +39 -0
  26. package/dist/chunk-Y52N27PF.js.map +1 -0
  27. package/dist/clipboard.d.ts +91 -0
  28. package/dist/clipboard.js +6 -0
  29. package/dist/clipboard.js.map +1 -0
  30. package/dist/clone.d.ts +8 -0
  31. package/dist/clone.js +6 -0
  32. package/dist/clone.js.map +1 -0
  33. package/dist/fitViewToBounds-evGsnR8Q.d.ts +62 -0
  34. package/dist/grid-Cf87knjU.d.ts +153 -0
  35. package/dist/index-DZBYMsHI.d.ts +1555 -0
  36. package/dist/index.css +121 -0
  37. package/dist/index.css.map +1 -0
  38. package/dist/index.d.ts +10200 -0
  39. package/dist/index.js +13 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/insert.d.ts +33 -0
  42. package/dist/insert.js +81 -0
  43. package/dist/insert.js.map +1 -0
  44. package/dist/move.d.ts +69 -0
  45. package/dist/move.js +145 -0
  46. package/dist/move.js.map +1 -0
  47. package/dist/options-BPPBWMa7.d.ts +64 -0
  48. package/dist/patterns-builtin.d.ts +55 -0
  49. package/dist/patterns-builtin.js +100 -0
  50. package/dist/patterns-builtin.js.map +1 -0
  51. package/dist/pointSnapToGrid-D7s7QmOF.d.ts +185 -0
  52. package/dist/registerFont-CP-wCsrz.d.ts +109 -0
  53. package/dist/registerTexture-BzHTLhD9.d.ts +25 -0
  54. package/dist/renderer.css +121 -0
  55. package/dist/renderer.css.map +1 -0
  56. package/dist/renderer.d.ts +376 -0
  57. package/dist/renderer.js +13 -0
  58. package/dist/renderer.js.map +1 -0
  59. package/dist/resize.d.ts +78 -0
  60. package/dist/resize.js +5 -0
  61. package/dist/resize.js.map +1 -0
  62. package/dist/routing.css +35 -0
  63. package/dist/routing.css.map +1 -0
  64. package/dist/routing.d.ts +14 -0
  65. package/dist/routing.js +4 -0
  66. package/dist/routing.js.map +1 -0
  67. package/dist/types-B6MMiodD.d.ts +59 -0
  68. package/dist/types-BJ8_cyT7.d.ts +130 -0
  69. package/dist/types-B_-khFM0.d.ts +331 -0
  70. package/dist/types-BjUi2vA-.d.ts +355 -0
  71. package/dist/types-Cpb4hii1.d.ts +445 -0
  72. package/dist/types-D2tTKEU0.d.ts +18 -0
  73. package/dist/view-DSQgxBJB.d.ts +63 -0
  74. package/package.json +96 -0
@@ -0,0 +1,216 @@
1
+ import { createSetSelectionOp } from './chunk-BHVYVFGV.js';
2
+ import { createInsertOp } from './chunk-GVCNT7UH.js';
3
+ import { createContext, useRef, useMemo, useContext, useCallback } from 'react';
4
+ import { jsx } from 'react/jsx-runtime';
5
+
6
+ // src/core/applyOps.ts
7
+ function applyOpsTo(adapter, ops, _label) {
8
+ for (const op of ops) op.apply(adapter);
9
+ }
10
+ function dispatchApplyBatch(adapter, ops, label) {
11
+ const a = adapter;
12
+ if (a.applyOps) a.applyOps(ops, label);
13
+ else applyOpsTo(adapter, ops);
14
+ }
15
+
16
+ // src/debug/flag.ts
17
+ var KEYS = ["weasel.debug", "weaseldraw.debug"];
18
+ var cached = null;
19
+ function read() {
20
+ const empty = { all: false, set: /* @__PURE__ */ new Set() };
21
+ if (typeof localStorage === "undefined") return empty;
22
+ try {
23
+ for (const k of KEYS) {
24
+ const v = localStorage.getItem(k);
25
+ if (v == null || v === "") continue;
26
+ if (v === "1" || v === "true" || v === "*") return { all: true, set: /* @__PURE__ */ new Set() };
27
+ return { all: false, set: new Set(v.split(/[\s,]+/).filter(Boolean)) };
28
+ }
29
+ return empty;
30
+ } catch {
31
+ return empty;
32
+ }
33
+ }
34
+ function get() {
35
+ if (cached === null) cached = read();
36
+ return cached;
37
+ }
38
+ function isDebugEnabled(namespace) {
39
+ const c = get();
40
+ if (c.all) return true;
41
+ if (namespace === void 0) return c.set.size > 0;
42
+ return c.set.has(namespace);
43
+ }
44
+ function dlog(namespace, ...args) {
45
+ if (!isDebugEnabled(namespace)) return;
46
+ console.debug(`[${namespace}]`, ...args);
47
+ }
48
+ function dwarn(namespace, ...args) {
49
+ if (!isDebugEnabled(namespace)) return;
50
+ console.warn(`[${namespace}]`, ...args);
51
+ }
52
+ var PointerContext = createContext(null);
53
+ function PointerContextProvider({ children }) {
54
+ const pointerRef = useRef(null);
55
+ const value = useMemo(() => ({
56
+ pointerRef,
57
+ getDropPoint: () => pointerRef.current
58
+ }), []);
59
+ return /* @__PURE__ */ jsx(PointerContext.Provider, { value, children });
60
+ }
61
+ function usePointerContext() {
62
+ return useContext(PointerContext);
63
+ }
64
+
65
+ // src/interactions/actions/clipboard/wireFormat.ts
66
+ var WEASEL_CLIPBOARD_MIME = "application/x-weasel-clipboard+json";
67
+ var WEASEL_CLIPBOARD_MIME_WEB = `web ${WEASEL_CLIPBOARD_MIME}`;
68
+ function buildWeaselClipboardText(items, replacer) {
69
+ const payload = { weaselClipboard: 1, nodes: items };
70
+ return JSON.stringify(payload, replacer);
71
+ }
72
+ function sniffWeaselClipboardText(text) {
73
+ if (!text.includes('"weaselClipboard"')) return false;
74
+ try {
75
+ const parsed = JSON.parse(text);
76
+ return !!parsed && parsed.weaselClipboard === 1;
77
+ } catch {
78
+ return false;
79
+ }
80
+ }
81
+ var SVG_OPEN_TAG = /<svg(?:\s[^>]*)?>/i;
82
+ function embedWeaselMetadataInSvg(svgText, payloadText) {
83
+ const open = SVG_OPEN_TAG.exec(svgText);
84
+ if (!open) {
85
+ dwarn("clipboard", "embedWeaselMetadataInSvg: no <svg ...> open tag found \u2014 returning input unchanged");
86
+ return svgText;
87
+ }
88
+ const cdata = `<![CDATA[${payloadText.replaceAll("]]>", "]]]]><![CDATA[>")}]]>`;
89
+ const at = open.index + open[0].length;
90
+ return `${svgText.slice(0, at)}<metadata>${cdata}</metadata>${svgText.slice(at)}`;
91
+ }
92
+ function extractWeaselClipboardFromSvg(svgText) {
93
+ const block = /<metadata(?:\s[^>]*)?>([\s\S]*?)<\/metadata>/i.exec(svgText);
94
+ if (!block) return null;
95
+ const inner = block[1];
96
+ const payload = inner.includes("<![CDATA[") ? Array.from(inner.matchAll(/<!\[CDATA\[([\s\S]*?)\]\]>/g), (m) => m[1]).join("") : inner;
97
+ return sniffWeaselClipboardText(payload) ? payload : null;
98
+ }
99
+ function parseWeaselClipboardText(text, reviver) {
100
+ try {
101
+ const parsed = JSON.parse(text, reviver);
102
+ if (!parsed || parsed.weaselClipboard !== 1 || !Array.isArray(parsed.nodes)) return null;
103
+ return parsed.nodes;
104
+ } catch (err) {
105
+ dwarn("clipboard", `weasel payload failed to parse: ${String(err)}`);
106
+ return null;
107
+ }
108
+ }
109
+
110
+ // src/interactions/actions/clipboard/materializePaste.ts
111
+ function materializePaste(adapter, snapshot, opts) {
112
+ const commitPaste = adapter.commitPaste;
113
+ if (!commitPaste) return null;
114
+ const offset = adapter.getPasteOffset?.(snapshot) ?? { dx: 0, dy: 0 };
115
+ const ctx = opts.dropPoint != null ? { dropPoint: opts.dropPoint } : void 0;
116
+ const created = commitPaste.call(adapter, snapshot, offset, ctx);
117
+ if (created.length === 0) return null;
118
+ const newIds = created.map((o) => o.id);
119
+ const ops = [
120
+ ...created.map((o) => createInsertOp({ node: o })),
121
+ createSetSelectionOp({ from: opts.currentSelection, to: newIds })
122
+ ];
123
+ return { ops, newIds, created };
124
+ }
125
+
126
+ // src/interactions/actions/clipboard/clipboardOps.ts
127
+ var EMPTY = { items: [] };
128
+ function useClipboardOps(adapter, options) {
129
+ const { getSelection, onPaste, pasteLabel = "Paste", getDropPoint, produceFlavors, jsonReplacer } = options;
130
+ const pointerCtx = usePointerContext();
131
+ const effectiveGetDropPoint = getDropPoint ?? pointerCtx?.getDropPoint;
132
+ const clipboardRef = useRef(EMPTY);
133
+ const adapterRef = useRef(adapter);
134
+ adapterRef.current = adapter;
135
+ const optsRef = useRef({
136
+ getSelection,
137
+ onPaste,
138
+ pasteLabel,
139
+ getDropPoint: effectiveGetDropPoint,
140
+ produceFlavors,
141
+ jsonReplacer
142
+ });
143
+ optsRef.current = {
144
+ getSelection,
145
+ onPaste,
146
+ pasteLabel,
147
+ getDropPoint: effectiveGetDropPoint,
148
+ produceFlavors,
149
+ jsonReplacer
150
+ };
151
+ const copy = useCallback(() => {
152
+ const ids = optsRef.current.getSelection();
153
+ if (ids.length === 0) return;
154
+ const snap = adapterRef.current.snapshotSelection;
155
+ if (!snap) return;
156
+ clipboardRef.current = snap(ids);
157
+ let flavors = null;
158
+ try {
159
+ flavors = optsRef.current.produceFlavors?.(clipboardRef.current) ?? defaultFlavors(clipboardRef.current, optsRef.current.jsonReplacer);
160
+ } catch (err) {
161
+ dwarn("clipboard", `flavor producer threw \u2014 skipping OS write: ${String(err)}`);
162
+ }
163
+ if (flavors) void writeOsClipboard(flavors);
164
+ }, []);
165
+ const paste = useCallback(() => {
166
+ const cb = clipboardRef.current;
167
+ if (cb.items.length === 0) return;
168
+ const a = adapterRef.current;
169
+ const result = materializePaste(a, cb, {
170
+ currentSelection: optsRef.current.getSelection(),
171
+ dropPoint: optsRef.current.getDropPoint?.()
172
+ });
173
+ if (!result) return;
174
+ dispatchApplyBatch(a, result.ops, optsRef.current.pasteLabel);
175
+ clipboardRef.current = { items: result.created };
176
+ optsRef.current.onPaste?.(result.newIds);
177
+ }, []);
178
+ const isEmpty = useCallback(() => clipboardRef.current.items.length === 0, []);
179
+ return { copy, paste, isEmpty };
180
+ }
181
+ function defaultFlavors(snapshot, replacer) {
182
+ const text = buildWeaselClipboardText(snapshot.items, replacer);
183
+ return { [WEASEL_CLIPBOARD_MIME]: text, "text/plain": text };
184
+ }
185
+ var WELL_KNOWN_CLIPBOARD_MIMES = /* @__PURE__ */ new Set(["text/plain", "text/html", "image/png"]);
186
+ async function writeOsClipboard(flavors) {
187
+ const entries = Object.entries(flavors);
188
+ if (entries.length === 0) return;
189
+ const cb = typeof navigator !== "undefined" ? navigator.clipboard : void 0;
190
+ if (!cb?.write || typeof ClipboardItem === "undefined") return;
191
+ const wireMime = (mime) => WELL_KNOWN_CLIPBOARD_MIMES.has(mime) ? mime : `web ${mime}`;
192
+ const toItem = (fs) => new ClipboardItem(Object.fromEntries(
193
+ fs.map(([mime, text]) => {
194
+ const wire = wireMime(mime);
195
+ return [wire, new Blob([text], { type: wire })];
196
+ })
197
+ ));
198
+ try {
199
+ await cb.write([toItem(entries)]);
200
+ } catch {
201
+ const standard = entries.filter(([mime]) => WELL_KNOWN_CLIPBOARD_MIMES.has(mime));
202
+ if (standard.length === 0) {
203
+ dwarn("clipboard", "OS write failed; no standard flavors to fall back to");
204
+ return;
205
+ }
206
+ try {
207
+ await cb.write([toItem(standard)]);
208
+ } catch (err) {
209
+ dwarn("clipboard", `OS clipboard write failed twice \u2014 copy stays in-memory only: ${String(err)}`);
210
+ }
211
+ }
212
+ }
213
+
214
+ export { PointerContextProvider, WEASEL_CLIPBOARD_MIME, WEASEL_CLIPBOARD_MIME_WEB, applyOpsTo, buildWeaselClipboardText, dispatchApplyBatch, dlog, dwarn, embedWeaselMetadataInSvg, extractWeaselClipboardFromSvg, isDebugEnabled, materializePaste, parseWeaselClipboardText, sniffWeaselClipboardText, useClipboardOps, usePointerContext };
215
+ //# sourceMappingURL=chunk-775XXAHR.js.map
216
+ //# sourceMappingURL=chunk-775XXAHR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/applyOps.ts","../src/debug/flag.ts","../src/features/pointer/PointerContext.tsx","../src/interactions/actions/clipboard/wireFormat.ts","../src/interactions/actions/clipboard/materializePaste.ts","../src/interactions/actions/clipboard/clipboardOps.ts"],"names":["useRef"],"mappings":";;;;;;AAYO,SAAS,UAAA,CAAc,OAAA,EAAY,GAAA,EAAW,MAAA,EAAuB;AAC1E,EAAA,KAAA,MAAW,EAAA,IAAM,GAAA,EAAK,EAAA,CAAG,KAAA,CAAM,OAAO,CAAA;AACxC;AAOO,SAAS,kBAAA,CACd,OAAA,EACA,GAAA,EACA,KAAA,EACM;AACN,EAAA,MAAM,CAAA,GAAI,OAAA;AACV,EAAA,IAAI,CAAA,CAAE,QAAA,EAAU,CAAA,CAAE,QAAA,CAAS,KAAK,KAAK,CAAA;AAAA,OAChC,UAAA,CAAW,OAAA,EAAS,GAAU,CAAA;AACrC;;;ACFA,IAAM,IAAA,GAAO,CAAC,cAAA,EAAgB,kBAAkB,CAAA;AAOhD,IAAI,MAAA,GAAwB,IAAA;AAE5B,SAAS,IAAA,GAAe;AACtB,EAAA,MAAM,QAAgB,EAAE,GAAA,EAAK,OAAO,GAAA,kBAAK,IAAI,KAAI,EAAE;AACnD,EAAA,IAAI,OAAO,YAAA,KAAiB,WAAA,EAAa,OAAO,KAAA;AAChD,EAAA,IAAI;AACF,IAAA,KAAA,MAAW,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AAA,CAAO,OAAO,CAAC,CAAC,CAAA;AAAA,EAClC,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,MAAA,CAAO,CAAC,CAAC,IAAI,CAAA,KAAM,0BAAA,CAA2B,GAAA,CAAI,IAAI,CAAC,CAAA;AAChF,IAAA,IAAI,QAAA,CAAS,WAAW,CAAA,EAAG;AAAE,MAAA,KAAA,CAAM,aAAa,sDAAsD,CAAA;AAAG,MAAA;AAAA,IAAQ;AACjH,IAAA,IAAI;AACF,MAAA,MAAM,GAAG,KAAA,CAAM,CAAC,MAAA,CAAO,QAAQ,CAAC,CAAC,CAAA;AAAA,IACnC,SAAS,GAAA,EAAK;AACZ,MAAA,KAAA,CAAM,WAAA,EAAa,CAAA,kEAAA,EAAgE,MAAA,CAAO,GAAG,CAAC,CAAA,CAAE,CAAA;AAAA,IAClG;AAAA,EACF;AACF","file":"chunk-775XXAHR.js","sourcesContent":["import type { Op } from './ops/types';\n\n/**\n * Default `applyOps` implementation: apply each op in order against\n * `adapter`. Used by hooks when an adapter omits `applyOps`. Apps that\n * need history integration (checkpoint + push entry) supply their own\n * `applyOps` instead.\n *\n * The `_label` parameter mirrors the `applyOps(ops, label)` signature so\n * call-sites can dispatch through `(adapter.applyOps ?? applyOpsTo)` with\n * matching arguments. The default ignores it.\n */\nexport function applyOpsTo<A>(adapter: A, ops: Op[], _label?: string): void {\n for (const op of ops) op.apply(adapter);\n}\n\n/**\n * Dispatcher: invokes `adapter.applyOps` if present, otherwise falls back\n * to `applyOpsTo`. Convenience for hooks so they don't repeat the\n * `?? applyOpsTo` pattern at every call site.\n */\nexport function dispatchApplyBatch<A>(\n adapter: A,\n ops: Op[],\n label?: string,\n): void {\n const a = adapter as { applyOps?: (ops: Op[], label?: string) => void };\n if (a.applyOps) a.applyOps(ops, label);\n else applyOpsTo(adapter, ops, label);\n}\n","/**\n * Namespaced, opt-in console tracing for the kit.\n *\n * Enable in the browser:\n *\n * localStorage.setItem('weasel.debug', '*') // all namespaces\n * localStorage.setItem('weasel.debug', 'tools,dispatch') // specific ones\n * localStorage.setItem('weasel.debug', '1') // legacy \"all\"\n *\n * Each call site picks a stable namespace string. Off by default; the flag\n * is read once and cached per page session — reload to pick up a change.\n *\n * Mirrors `packages/ui/src/dlog.ts`. The two impls live in separate\n * packages because weasel-ui doesn't depend on the kit, but both read the\n * same localStorage keys so behavior is uniform from a debugger's POV.\n *\n * Known kit namespaces:\n * - tools — active-tool + hotkey transitions (useTools)\n * - dispatch — gesture start / end / cancel (dispatcher)\n * - drag-rect — useDragRect lifecycle\n * - drag-radial — useDragRadial lifecycle\n * - scene — restored-op replay gaps (history persistence)\n * - scene-canvas — SceneCanvas mount / unmount; adapter paste-translation warnings\n * - history — applyOps push, no-op suppression, serialize/restore\n * - clipboard — OS clipboard write/read failures, malformed payloads\n */\n\nconst KEYS = ['weasel.debug', 'weaseldraw.debug'] as const;\n\ninterface Cached {\n all: boolean;\n set: Set<string>;\n}\n\nlet cached: Cached | null = null;\n\nfunction read(): Cached {\n const empty: Cached = { all: false, set: new Set() };\n if (typeof localStorage === 'undefined') return empty;\n try {\n for (const k of KEYS) {\n const v = localStorage.getItem(k);\n if (v == null || v === '') continue;\n if (v === '1' || v === 'true' || v === '*') return { all: true, set: new Set() };\n return { all: false, set: new Set(v.split(/[\\s,]+/).filter(Boolean)) };\n }\n return empty;\n } catch {\n return empty;\n }\n}\n\nfunction get(): Cached {\n if (cached === null) cached = read();\n return cached;\n}\n\n/** True when `namespace` (or `*`) is enabled. Pass no argument to test\n * whether *any* namespace is on (legacy global-flag semantics). */\nexport function isDebugEnabled(namespace?: string): boolean {\n const c = get();\n if (c.all) return true;\n if (namespace === undefined) return c.set.size > 0;\n return c.set.has(namespace);\n}\n\n/** Conditional `console.debug` — no-op unless `namespace` (or `*`) is enabled.\n * Each call is prefixed with `[namespace]` so the source is searchable. */\nexport function dlog(namespace: string, ...args: unknown[]): void {\n if (!isDebugEnabled(namespace)) return;\n // eslint-disable-next-line no-console\n console.debug(`[${namespace}]`, ...args);\n}\n\n/** Conditional `console.warn` — like `dlog` but at warn level. Use for\n * diagnostics that indicate something worth surfacing during debugging\n * (e.g. no-op op batches suppressed). */\nexport function dwarn(namespace: string, ...args: unknown[]): void {\n if (!isDebugEnabled(namespace)) return;\n // eslint-disable-next-line no-console\n console.warn(`[${namespace}]`, ...args);\n}\n","/**\n * @experimental\n * PointerContext — a tiny ambient context that publishes the world-space\n * position of the canvas pointer, refreshed on every `pointermove` over\n * the canvas. Cleared (set to `null`) on `pointerleave`.\n *\n * Why ref-based and not state-based: cursor moves fire dozens of times per\n * second; routing those through React state would re-render every consumer\n * in the tree. The context exposes a stable `pointerRef` whose `.current`\n * is mutated directly by the publisher, plus a thunk `getDropPoint()` that\n * reads it on demand. Consumers (e.g. `useClipboard`) pull via the thunk\n * inside their callbacks — no subscription, no re-render.\n *\n * `<SceneCanvas>` publishes automatically. `useClipboardOps` consumes when\n * the caller didn't pass an explicit `getDropPoint` option. Other future\n * hit-on-cursor consumers (drop-zone hover, context-menu anchor) can reuse\n * the same context.\n */\nimport { createContext, useContext, useMemo, useRef, type MutableRefObject, type ReactNode } from 'react';\n\n/** @experimental World-space pointer position, or `null` when the pointer\n * isn't over the publishing canvas. */\nexport type PointerWorldPos = { worldX: number; worldY: number } | null;\n\n/** @experimental */\nexport interface PointerContextValue {\n /** Live ref — mutate to publish, read for the latest snapshot. The\n * identity is stable for the lifetime of the provider. */\n readonly pointerRef: MutableRefObject<PointerWorldPos>;\n /** Convenience thunk equivalent to `() => pointerRef.current`. Stable\n * identity for the lifetime of the provider; safe to pass to hooks. */\n readonly getDropPoint: () => PointerWorldPos;\n}\n\nconst PointerContext = createContext<PointerContextValue | null>(null);\n\n/**\n * @experimental\n * Wrap the part of the React tree that should share a pointer-position\n * context. Usually placed at the demo / app root, alongside\n * `<ActionsProvider>` and `<SelectionContextProvider>`.\n *\n * Most consumers don't need to mount this directly — `<SceneCanvas>` mounts\n * an internal provider when no parent provider is in scope, so child hooks\n * (`useClipboard` without an explicit `getDropPoint`) read the canvas's\n * tracked pointer for free.\n */\nexport function PointerContextProvider({ children }: { children: ReactNode }): ReactNode {\n const pointerRef = useRef<PointerWorldPos>(null);\n const value = useMemo<PointerContextValue>(() => ({\n pointerRef,\n getDropPoint: () => pointerRef.current,\n }), []);\n return <PointerContext.Provider value={value}>{children}</PointerContext.Provider>;\n}\n\n/** @experimental Read the surrounding pointer-context value, or `null` when\n * no provider is in scope. */\nexport function usePointerContext(): PointerContextValue | null {\n return useContext(PointerContext);\n}\n","import { dwarn } from 'debug/flag';\n\nexport const WEASEL_CLIPBOARD_MIME = 'application/x-weasel-clipboard+json';\n/** Chromium's async-clipboard spelling for custom formats. */\nexport const WEASEL_CLIPBOARD_MIME_WEB = `web ${WEASEL_CLIPBOARD_MIME}`;\n\ninterface WeaselClipboardPayload { weaselClipboard: 1; nodes: unknown[] }\n\ntype Replacer = (key: string, value: unknown) => unknown;\ntype Reviver = (key: string, value: unknown) => unknown;\n\n/** Serialize snapshot items into the versioned wire text.\n *\n * Function-valued fields (e.g. a container's `clipFromPose`) are dropped by\n * JSON serialization — OS-pasted clip containers arrive unclipped.\n * Consumers who need clips to survive the OS round-trip can translate\n * function ↔ registry key in their `jsonReplacer`/reviver pair (the\n * scene-serialization `clipFromPoseKey` precedent). */\nexport function buildWeaselClipboardText(items: unknown[], replacer?: Replacer): string {\n const payload: WeaselClipboardPayload = { weaselClipboard: 1, nodes: items };\n return JSON.stringify(payload, replacer as Parameters<typeof JSON.stringify>[1]);\n}\n\n/** Cheap check: could this text be a weasel clipboard payload? Substring\n * pre-check, then a guarded parse + marker/version test. */\nexport function sniffWeaselClipboardText(text: string): boolean {\n if (!text.includes('\"weaselClipboard\"')) return false;\n try {\n const parsed = JSON.parse(text) as Partial<WeaselClipboardPayload> | null;\n return !!parsed && parsed.weaselClipboard === 1;\n } catch {\n return false;\n }\n}\n\n// Opening `<svg ...>` tag of a serialized document. `[^>]*` is safe for OUR\n// serializer's output (attribute values are XML-escaped, so no raw `>` can\n// appear inside the tag) — see embedWeaselMetadataInSvg's contract note.\nconst SVG_OPEN_TAG = /<svg(?:\\s[^>]*)?>/i;\n\n/**\n * Embed a weasel clipboard payload in an SVG document as a `<metadata>`\n * child of the root — legal SVG 1.1, ignored by external tools — so one\n * `text/plain` flavor serves both audiences: external tools parse the SVG,\n * weasel extracts the JSON for full fidelity on draw→draw DOM paste.\n *\n * The payload rides in CDATA so JSON's `<` / `&` need no entity escaping; a\n * literal `]]>` inside the payload is split across CDATA sections\n * (`]]]]><![CDATA[>`), which {@link extractWeaselClipboardFromSvg} rejoins.\n *\n * Intended for OUR serializer's output only (`serializeSvg` — single\n * `<svg ...>` open tag, XML-escaped attributes). When no open tag is found\n * the input is returned unchanged with a debug warning.\n */\nexport function embedWeaselMetadataInSvg(svgText: string, payloadText: string): string {\n const open = SVG_OPEN_TAG.exec(svgText);\n if (!open) {\n dwarn('clipboard', 'embedWeaselMetadataInSvg: no <svg ...> open tag found — returning input unchanged');\n return svgText;\n }\n const cdata = `<![CDATA[${payloadText.replaceAll(']]>', ']]]]><![CDATA[>')}]]>`;\n const at = open.index + open[0].length;\n return `${svgText.slice(0, at)}<metadata>${cdata}</metadata>${svgText.slice(at)}`;\n}\n\n/**\n * Recover an embedded weasel clipboard payload from SVG text: read the first\n * `<metadata>` block, rejoin its CDATA sections (concatenation restores the\n * `]]>` split by {@link embedWeaselMetadataInSvg}; plain non-CDATA content\n * passes through as-is), and return the payload text iff it sniffs as the\n * weasel wire format — else null (external/non-weasel metadata declines).\n *\n * A text scan, not an XML parse — the payload is small and ours.\n */\nexport function extractWeaselClipboardFromSvg(svgText: string): string | null {\n const block = /<metadata(?:\\s[^>]*)?>([\\s\\S]*?)<\\/metadata>/i.exec(svgText);\n if (!block) return null;\n const inner = block[1];\n const payload = inner.includes('<![CDATA[')\n ? Array.from(inner.matchAll(/<!\\[CDATA\\[([\\s\\S]*?)\\]\\]>/g), (m) => m[1]).join('')\n : inner;\n return sniffWeaselClipboardText(payload) ? payload : null;\n}\n\n/** Parse wire text to snapshot items, or null when malformed/mismatched\n * (callers decline to the next content handler). */\nexport function parseWeaselClipboardText(text: string, reviver?: Reviver): unknown[] | null {\n try {\n const parsed = JSON.parse(text, reviver as Parameters<typeof JSON.parse>[1]) as\n Partial<WeaselClipboardPayload> | null;\n if (!parsed || parsed.weaselClipboard !== 1 || !Array.isArray(parsed.nodes)) return null;\n return parsed.nodes;\n } catch (err) {\n dwarn('clipboard', `weasel payload failed to parse: ${String(err)}`);\n return null;\n }\n}\n","/**\n * Shared paste materialization — the one place the paste recipe lives:\n * offset policy → `commitPaste` → the op batch (InsertOps parents-first +\n * a SetSelectionOp). Both `useClipboardOps.paste` (in-memory paste) and the\n * kit weasel-JSON content handler (OS-clipboard paste) dispatch exactly this\n * batch, so the two arrival paths stay indistinguishable in history.\n *\n * Pure: no dispatching here — callers own how the ops are applied\n * (`dispatchApplyBatch` vs `IngestCtx.applyOps`) and any post-paste\n * bookkeeping (the hook's cascade re-snapshot, the handler's selection set).\n */\nimport { createInsertOp } from 'core/ops/create';\nimport { createSetSelectionOp } from 'core/ops/select';\nimport type { Op } from 'core/ops/types';\nimport type { NodeId } from 'core/scene/types';\nimport type { ClipboardSnapshot, InsertAdapter } from 'core/adapters/types';\n\n/** Shared paste materialization: offset policy → commitPaste → the op batch\n * both the in-memory paste and the OS-paste handler dispatch. Returns null\n * when the adapter can't paste or nothing was created. */\nexport function materializePaste<TNode extends { id: string }>(\n adapter: InsertAdapter<TNode>,\n snapshot: ClipboardSnapshot,\n opts: {\n currentSelection: string[];\n dropPoint?: { worldX: number; worldY: number } | null;\n },\n): { ops: Op[]; newIds: string[]; created: TNode[] } | null {\n const commitPaste = adapter.commitPaste;\n if (!commitPaste) return null;\n const offset = adapter.getPasteOffset?.(snapshot) ?? { dx: 0, dy: 0 };\n const ctx = opts.dropPoint != null ? { dropPoint: opts.dropPoint } : undefined;\n const created = commitPaste.call(adapter, snapshot, offset, ctx);\n if (created.length === 0) return null;\n const newIds = created.map((o) => o.id);\n const ops: Op[] = [\n ...created.map((o) => createInsertOp({ node: o })),\n createSetSelectionOp({ from: opts.currentSelection as NodeId[], to: newIds as NodeId[] }),\n ];\n return { ops, newIds, created };\n}\n","import { useCallback, useRef } from 'react';\nimport type { NodeId } from 'core/scene/types';\nimport { dispatchApplyBatch } from 'core/applyOps';\nimport type { InsertAdapter } from 'core/adapters/types';\nimport type { ClipboardSnapshot } from './types';\nimport { usePointerContext } from 'features/pointer/PointerContext';\nimport { dwarn } from 'debug/flag';\nimport { materializePaste } from './materializePaste';\nimport { WEASEL_CLIPBOARD_MIME, buildWeaselClipboardText } from './wireFormat';\n\ntype Replacer = (key: string, value: unknown) => unknown;\n\n/** Options for `useClipboardOps`. */\nexport interface UseClipboardOpsOptions {\n /** How the hook reads \"current selection\" for copy. The kit doesn't assume\n * a global selection store; each consumer wires this. */\n getSelection: () => NodeId[];\n /** Called after a successful paste with the ids of the newly inserted objects. */\n onPaste?: (newIds: NodeId[]) => void;\n /** Label for the history entry produced by paste. Default 'Paste'. */\n pasteLabel?: string;\n /** Pulled once per paste() call. When non-null, threaded to commitPaste\n * as `ctx.dropPoint`; adapters typically use it as the cluster origin\n * (ignoring `offset`). When null/undefined, the hook falls back to the\n * existing cascade-offset behavior. */\n getDropPoint?: () => { worldX: number; worldY: number } | null;\n /** Produce the OS-clipboard flavor map for a copied snapshot. Keys are MIME\n * types, values the serialized payload. The kit default emits\n * `application/x-weasel-clipboard+json` plus `text/plain` carrying the\n * same JSON. Apps override to add richer flavors (e.g. real SVG) or to\n * replace the text flavor. Return an empty object to skip the OS write\n * entirely. */\n produceFlavors?: (snapshot: ClipboardSnapshot) => Record<string, string>;\n /** Replacer for the kit-default JSON flavor (typed arrays etc.). Ignored\n * when `produceFlavors` is supplied. */\n jsonReplacer?: Replacer;\n}\n\n/** Return shape of `useClipboardOps`: imperative `copy`, `paste`, and `isEmpty` functions. */\nexport interface UseClipboardOpsReturn {\n copy(): void;\n paste(): void;\n isEmpty(): boolean;\n}\n\nconst EMPTY: ClipboardSnapshot = { items: [] };\n\n/** In-memory copy/paste of selections via `InsertAdapter.snapshotSelection` / `commitPaste`. */\nexport function useClipboardOps<TNode extends { id: string }>(\n adapter: InsertAdapter<TNode>,\n options: UseClipboardOpsOptions,\n): UseClipboardOpsReturn {\n const { getSelection, onPaste, pasteLabel = 'Paste', getDropPoint, produceFlavors, jsonReplacer } = options;\n // Fall back to the ambient pointer context (auto-published by SceneCanvas)\n // when the caller didn't supply an explicit `getDropPoint`. Null context\n // (no provider in scope) and no caller-supplied thunk together mean\n // \"no drop point\" — paste uses the cascade offset instead.\n const pointerCtx = usePointerContext();\n const effectiveGetDropPoint = getDropPoint ?? pointerCtx?.getDropPoint;\n const clipboardRef = useRef<ClipboardSnapshot>(EMPTY);\n // Keep callbacks stable across renders.\n const adapterRef = useRef(adapter);\n adapterRef.current = adapter;\n const optsRef = useRef({\n getSelection, onPaste, pasteLabel, getDropPoint: effectiveGetDropPoint, produceFlavors, jsonReplacer,\n });\n optsRef.current = {\n getSelection, onPaste, pasteLabel, getDropPoint: effectiveGetDropPoint, produceFlavors, jsonReplacer,\n };\n\n const copy = useCallback(() => {\n const ids = optsRef.current.getSelection();\n if (ids.length === 0) return;\n const snap = adapterRef.current.snapshotSelection;\n if (!snap) return;\n clipboardRef.current = snap(ids);\n // Best-effort OS write. Never blocks or throws — the in-memory ref is\n // already set, and OS clipboard support varies (custom formats are\n // Chromium-only via the \"web \" prefix; jsdom/non-secure contexts have\n // no API at all). The flavor producer itself is untrusted consumer code\n // (`produceFlavors`), so guard its call too — a throwing producer must\n // not break `copy()`, it just skips the OS write.\n let flavors: Record<string, string> | null = null;\n try {\n flavors = optsRef.current.produceFlavors?.(clipboardRef.current)\n ?? defaultFlavors(clipboardRef.current, optsRef.current.jsonReplacer);\n } catch (err) {\n dwarn('clipboard', `flavor producer threw — skipping OS write: ${String(err)}`);\n }\n if (flavors) void writeOsClipboard(flavors);\n }, []);\n\n const paste = useCallback(() => {\n const cb = clipboardRef.current;\n if (cb.items.length === 0) return;\n const a = adapterRef.current;\n const result = materializePaste(a, cb, {\n currentSelection: optsRef.current.getSelection(),\n dropPoint: optsRef.current.getDropPoint?.(),\n });\n if (!result) return;\n dispatchApplyBatch(a, result.ops, optsRef.current.pasteLabel);\n // Use the just-created objects as the next cascade source. Re-snapshotting\n // via `adapter.snapshotSelection(newIds)` would read adapter state, but\n // React-state adapters haven't flushed yet — `itemsRef.current` still\n // points at the pre-insert array, so the snapshot would come back empty\n // and the next paste would no-op.\n clipboardRef.current = { items: result.created };\n optsRef.current.onPaste?.(result.newIds as NodeId[]);\n }, []);\n\n const isEmpty = useCallback(() => clipboardRef.current.items.length === 0, []);\n\n return { copy, paste, isEmpty };\n}\n\nfunction defaultFlavors(snapshot: ClipboardSnapshot, replacer?: Replacer): Record<string, string> {\n const text = buildWeaselClipboardText(snapshot.items, replacer);\n return { [WEASEL_CLIPBOARD_MIME]: text, 'text/plain': text };\n}\n\n/** MIME types the async Clipboard API accepts unprefixed. Every other type\n * (including our own custom MIME, and app-supplied flavors like\n * `image/svg+xml`) must carry Chromium's `web ` prefix or `ClipboardItem`'s\n * constructor throws. */\nconst WELL_KNOWN_CLIPBOARD_MIMES = new Set(['text/plain', 'text/html', 'image/png']);\n\n/** Degradation ladder: full map (every non-well-known MIME web-prefixed) →\n * well-known-only → give up with a dwarn.\n * @internal test seam — exported so unit tests can await the fire-and-forget\n * write directly; tests should still exercise this at least once through\n * the public `copy()` (see clipboardOps.test.tsx). */\nexport async function writeOsClipboard(flavors: Record<string, string>): Promise<void> {\n const entries = Object.entries(flavors);\n if (entries.length === 0) return;\n const cb = typeof navigator !== 'undefined' ? navigator.clipboard : undefined;\n if (!cb?.write || typeof ClipboardItem === 'undefined') return;\n const wireMime = (mime: string) => (WELL_KNOWN_CLIPBOARD_MIMES.has(mime) ? mime : `web ${mime}`);\n const toItem = (fs: [string, string][]) => new ClipboardItem(Object.fromEntries(\n fs.map(([mime, text]) => {\n const wire = wireMime(mime);\n return [wire, new Blob([text], { type: wire })];\n }),\n ));\n try {\n await cb.write([toItem(entries)]);\n } catch {\n const standard = entries.filter(([mime]) => WELL_KNOWN_CLIPBOARD_MIMES.has(mime));\n if (standard.length === 0) { dwarn('clipboard', 'OS write failed; no standard flavors to fall back to'); return; }\n try {\n await cb.write([toItem(standard)]);\n } catch (err) {\n dwarn('clipboard', `OS clipboard write failed twice — copy stays in-memory only: ${String(err)}`);\n }\n }\n}\n"]}