@haklex/rich-ext-whiteboard 0.65.7 → 0.67.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 (99) hide show
  1. package/README.md +45 -5
  2. package/dist/InteractiveScene-CpoWGP_L.js +424 -0
  3. package/dist/WhiteboardEditor-cZ32fLqJ.js +4799 -0
  4. package/dist/WhiteboardExpandShell-BBjXd5qK.js +474 -0
  5. package/dist/editor/ContextMenu.d.ts +9 -0
  6. package/dist/editor/ContextMenu.d.ts.map +1 -0
  7. package/dist/editor/MobileDock.d.ts +2 -0
  8. package/dist/editor/MobileDock.d.ts.map +1 -1
  9. package/dist/editor/TextEditor.d.ts.map +1 -1
  10. package/dist/editor/Toolbar.d.ts +1 -0
  11. package/dist/editor/Toolbar.d.ts.map +1 -1
  12. package/dist/editor/WhiteboardCanvas.d.ts +2 -1
  13. package/dist/editor/WhiteboardCanvas.d.ts.map +1 -1
  14. package/dist/editor/WhiteboardEditor.d.ts +15 -0
  15. package/dist/editor/WhiteboardEditor.d.ts.map +1 -1
  16. package/dist/editor/card-actions.d.ts +8 -0
  17. package/dist/editor/card-actions.d.ts.map +1 -0
  18. package/dist/editor/chrome.css.d.ts +3 -0
  19. package/dist/editor/chrome.css.d.ts.map +1 -1
  20. package/dist/editor/context-menu.d.ts +27 -0
  21. package/dist/editor/context-menu.d.ts.map +1 -0
  22. package/dist/editor/context-menu.test.d.ts +2 -0
  23. package/dist/editor/context-menu.test.d.ts.map +1 -0
  24. package/dist/editor/embed.test.d.ts +2 -0
  25. package/dist/editor/embed.test.d.ts.map +1 -0
  26. package/dist/editor/focus.d.ts +11 -0
  27. package/dist/editor/focus.d.ts.map +1 -0
  28. package/dist/editor/remote-edit.test.d.ts +2 -0
  29. package/dist/editor/remote-edit.test.d.ts.map +1 -0
  30. package/dist/editor/shortcuts.d.ts +1 -1
  31. package/dist/editor/shortcuts.d.ts.map +1 -1
  32. package/dist/editor/store.d.ts +10 -1
  33. package/dist/editor/store.d.ts.map +1 -1
  34. package/dist/editor/tools/card.d.ts +0 -2
  35. package/dist/editor/tools/card.d.ts.map +1 -1
  36. package/dist/editor-entry.d.ts +28 -0
  37. package/dist/editor-entry.d.ts.map +1 -0
  38. package/dist/editor.mjs +186 -0
  39. package/dist/export/export.test.d.ts +2 -0
  40. package/dist/export/export.test.d.ts.map +1 -0
  41. package/dist/export/fonts.d.ts +22 -0
  42. package/dist/export/fonts.d.ts.map +1 -0
  43. package/dist/export/index.d.ts +7 -0
  44. package/dist/export/index.d.ts.map +1 -0
  45. package/dist/export/png.d.ts +10 -0
  46. package/dist/export/png.d.ts.map +1 -0
  47. package/dist/export/svg.d.ts +19 -0
  48. package/dist/export/svg.d.ts.map +1 -0
  49. package/dist/export-B_abF5zK.js +248 -0
  50. package/dist/index.mjs +6 -4408
  51. package/dist/model/reconcile.d.ts +14 -0
  52. package/dist/model/reconcile.d.ts.map +1 -0
  53. package/dist/model/reconcile.test.d.ts +2 -0
  54. package/dist/model/reconcile.test.d.ts.map +1 -0
  55. package/dist/model/restore-fonts.test.d.ts +2 -0
  56. package/dist/model/restore-fonts.test.d.ts.map +1 -0
  57. package/dist/model/restore.d.ts +5 -0
  58. package/dist/model/restore.d.ts.map +1 -1
  59. package/dist/model/richtext-layout.d.ts +2 -0
  60. package/dist/model/richtext-layout.d.ts.map +1 -1
  61. package/dist/model/skeleton.d.ts +21 -0
  62. package/dist/model/skeleton.d.ts.map +1 -0
  63. package/dist/model/skeleton.test.d.ts +2 -0
  64. package/dist/model/skeleton.test.d.ts.map +1 -0
  65. package/dist/model/supersede.d.ts +3 -0
  66. package/dist/model/supersede.d.ts.map +1 -0
  67. package/dist/model/viewport-fit.d.ts +24 -0
  68. package/dist/model/viewport-fit.d.ts.map +1 -0
  69. package/dist/reconcile-Of9Y1rFE.js +57 -0
  70. package/dist/rich-ext-whiteboard.css +1 -1
  71. package/dist/scene/InteractiveScene.d.ts +14 -1
  72. package/dist/scene/InteractiveScene.d.ts.map +1 -1
  73. package/dist/scene/Scene.d.ts +1 -0
  74. package/dist/scene/Scene.d.ts.map +1 -1
  75. package/dist/scene/SceneControls.d.ts +10 -0
  76. package/dist/scene/SceneControls.d.ts.map +1 -0
  77. package/dist/scene/context.d.ts +2 -0
  78. package/dist/scene/context.d.ts.map +1 -1
  79. package/dist/scene/elements.d.ts.map +1 -1
  80. package/dist/scene/fonts.d.ts +2 -0
  81. package/dist/scene/fonts.d.ts.map +1 -1
  82. package/dist/scene/fonts.test.d.ts +2 -0
  83. package/dist/scene/fonts.test.d.ts.map +1 -0
  84. package/dist/scene/interactive.test.d.ts +2 -0
  85. package/dist/scene/interactive.test.d.ts.map +1 -0
  86. package/dist/scene/richtext/RichTextSvgBody.d.ts +6 -0
  87. package/dist/scene/richtext/RichTextSvgBody.d.ts.map +1 -0
  88. package/dist/scene/transform.d.ts +18 -0
  89. package/dist/scene/transform.d.ts.map +1 -0
  90. package/dist/scene/useSceneFocus.d.ts +35 -0
  91. package/dist/scene/useSceneFocus.d.ts.map +1 -0
  92. package/dist/scene/useSceneGestures.d.ts +20 -0
  93. package/dist/scene/useSceneGestures.d.ts.map +1 -0
  94. package/dist/scene-entry.d.ts +16 -0
  95. package/dist/scene-entry.d.ts.map +1 -0
  96. package/dist/scene.mjs +5 -0
  97. package/dist/static.mjs +1 -1
  98. package/dist/{WhiteboardExpandShell-D1s7iDKh.js → viewport-fit-DzCmuJXY.js} +306 -814
  99. package/package.json +13 -5
@@ -1,116 +1,7 @@
1
- import { EXCALIDRAW_BLOCK_TRANSFORMER } from "@haklex/rich-headless/transformers";
2
- import { Component, Suspense, createContext, lazy, memo, use, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
1
+ import { createContext, memo, use, useId } from "react";
3
2
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
- import { createRendererDecoration, useColorScheme } from "@haklex/rich-editor/static";
5
- import { Maximize2, PenLine, ScanSearch, TriangleAlert, X, ZoomIn, ZoomOut } from "lucide-react";
6
3
  import { getStroke } from "perfect-freehand";
7
4
  import { RoughGenerator } from "roughjs/bin/generator";
8
- import { ViewportGate } from "@haklex/rich-editor-ui";
9
- import { DecoratorNode } from "lexical";
10
- //#region \0rolldown/runtime.js
11
- var __defProp = Object.defineProperty;
12
- var __exportAll = (all, no_symbols) => {
13
- let target = {};
14
- for (var name in all) __defProp(target, name, {
15
- get: all[name],
16
- enumerable: true
17
- });
18
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
19
- return target;
20
- };
21
- //#endregion
22
- //#region src/slot.ts
23
- var WHITEBOARD_NODE_KEY = "Whiteboard";
24
- //#endregion
25
- //#region src/styles.css.ts
26
- var whiteboardStaticContainer = "_1xd3mo40";
27
- var whiteboardEditorContainer = "_1xd3mo41";
28
- var whiteboardPlaceholder = "_1xd3mo42";
29
- var whiteboardStateLayer = "_1xd3mo43";
30
- var whiteboardStateIcon = "_1xd3mo44";
31
- var whiteboardLoading = "_1xd3mo46";
32
- var whiteboardEmpty = "_1xd3mo47";
33
- var whiteboardError = "_1xd3mo48";
34
- var whiteboardErrorIcon = "_1xd3mo49";
35
- var whiteboardFullscreenPopup = "_1xd3mo4b";
36
- var whiteboardDialogHeader = "_1xd3mo4c";
37
- var whiteboardDialogHeaderTitle = "_1xd3mo4d";
38
- var whiteboardDialogTitle = "_1xd3mo4e";
39
- var whiteboardHeaderClose = "_1xd3mo4g";
40
- var whiteboardDialogCanvas = "_1xd3mo4h";
41
- var whiteboardDialogBody = "_1xd3mo4i";
42
- var whiteboardShell = "_1xd3mo4j";
43
- var whiteboardSavedDot = "_1xd3mo4k";
44
- var whiteboardOptionsActions = "_1xd3mo4l";
45
- var whiteboardOptionsAdvanced = "_1xd3mo4m";
46
- var whiteboardOptionsHeading = "_1xd3mo4n";
47
- var whiteboardOptionsGroup = "_1xd3mo4o";
48
- var whiteboardOptionsLabel = "_1xd3mo4p";
49
- var whiteboardEditOverlay = "_1xd3mo4q";
50
- var whiteboardEditLabel = "_1xd3mo4r";
51
- //#endregion
52
- //#region src/types.ts
53
- var LOCAL_SCENE_PATH = /^(?:\.{1,2}\/)?[\w-][\w./-]*\.excalidraw$/;
54
- function isLocalScenePath(ref) {
55
- return LOCAL_SCENE_PATH.test(ref);
56
- }
57
- function parseSnapshot(raw) {
58
- if (!raw || !raw.trim()) return null;
59
- try {
60
- const json = JSON.parse(raw);
61
- if (json && typeof json === "object") return {
62
- type: "inline",
63
- data: json
64
- };
65
- } catch {}
66
- const lines = raw.split("\n");
67
- const firstLine = lines[0].trim();
68
- if (!firstLine.startsWith("http") && !firstLine.startsWith("blob:") && !firstLine.startsWith("ref:") && !isLocalScenePath(firstLine)) return null;
69
- const remaining = lines.slice(1).join("\n").trim();
70
- if (remaining) try {
71
- const delta = JSON.parse(remaining);
72
- if (delta && typeof delta === "object") return {
73
- type: "delta",
74
- baseUrl: firstLine,
75
- delta
76
- };
77
- } catch {}
78
- return {
79
- type: "remote",
80
- url: firstLine
81
- };
82
- }
83
- function serializeSnapshot(snapshot) {
84
- switch (snapshot.type) {
85
- case "inline": return JSON.stringify(snapshot.data);
86
- case "remote": return snapshot.url;
87
- case "delta": return [snapshot.baseUrl, JSON.stringify(snapshot.delta)].join("\n");
88
- }
89
- }
90
- //#endregion
91
- //#region src/WhiteboardConfigContext.tsx
92
- var WhiteboardConfigContext = createContext({});
93
- function WhiteboardConfigProvider({ apiUrl, fontCssHref, saveSnapshot, uploadFile, children }) {
94
- const value = useMemo(() => ({
95
- apiUrl,
96
- fontCssHref,
97
- saveSnapshot,
98
- uploadFile
99
- }), [
100
- apiUrl,
101
- fontCssHref,
102
- saveSnapshot,
103
- uploadFile
104
- ]);
105
- return /* @__PURE__ */ jsx(WhiteboardConfigContext.Provider, {
106
- value,
107
- children
108
- });
109
- }
110
- function useWhiteboardConfig() {
111
- return use(WhiteboardConfigContext);
112
- }
113
- //#endregion
114
5
  //#region src/model/geometry.ts
115
6
  function rotatePoint([x, y], [cx, cy], angle) {
116
7
  if (!angle) return [x, y];
@@ -280,7 +171,29 @@ function elementsInBox(elements, box) {
280
171
  var HAND_FONT_STACK = "\"LXGW WenKai Screen\", \"LXGW WenKai\", \"Excalifont\", \"Virgil\", \"Comic Sans MS\", \"Segoe Print\", \"Bradley Hand\", cursive";
281
172
  var SANS_FONT_STACK = "Helvetica, \"PingFang SC\", \"Microsoft YaHei\", \"Segoe UI Emoji\", \"Segoe UI Symbol\", system-ui, sans-serif";
282
173
  var MONO_FONT_STACK = "\"Cascadia Code\", \"Cascadia\", ui-monospace, SFMono-Regular, \"SF Mono\", Menlo, Consolas, monospace";
174
+ var WHITEBOARD_FONT_STACK = {
175
+ hand: HAND_FONT_STACK,
176
+ sans: SANS_FONT_STACK,
177
+ mono: MONO_FONT_STACK
178
+ };
179
+ var stackOverrides = /* @__PURE__ */ new Map();
180
+ function setFontFamilyStack(id, stack) {
181
+ if (stack) stackOverrides.set(id, stack);
182
+ else stackOverrides.delete(id);
183
+ }
184
+ var NOT_HANDWRITTEN = /* @__PURE__ */ new Set([
185
+ 2,
186
+ 3,
187
+ 6,
188
+ 8,
189
+ 9
190
+ ]);
191
+ function isHandFontFamily(id) {
192
+ return !NOT_HANDWRITTEN.has(id);
193
+ }
283
194
  function fontFamilyToCss(id) {
195
+ const override = id === void 0 ? void 0 : stackOverrides.get(id);
196
+ if (override) return override;
284
197
  switch (id) {
285
198
  case 2:
286
199
  case 6:
@@ -984,6 +897,44 @@ function refreshTextDimensions(textEl, container) {
984
897
  };
985
898
  }
986
899
  //#endregion
900
+ //#region \0@oxc-project+runtime@0.154.0/helpers/esm/typeof.js
901
+ function _typeof(o) {
902
+ "@babel/helpers - typeof";
903
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
904
+ return typeof o;
905
+ } : function(o) {
906
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
907
+ }, _typeof(o);
908
+ }
909
+ //#endregion
910
+ //#region \0@oxc-project+runtime@0.154.0/helpers/esm/toPrimitive.js
911
+ function toPrimitive(t, r) {
912
+ if ("object" != _typeof(t) || !t) return t;
913
+ var e = t[Symbol.toPrimitive];
914
+ if (void 0 !== e) {
915
+ var i = e.call(t, r || "default");
916
+ if ("object" != _typeof(i)) return i;
917
+ throw new TypeError("@@toPrimitive must return a primitive value.");
918
+ }
919
+ return ("string" === r ? String : Number)(t);
920
+ }
921
+ //#endregion
922
+ //#region \0@oxc-project+runtime@0.154.0/helpers/esm/toPropertyKey.js
923
+ function toPropertyKey(t) {
924
+ var i = toPrimitive(t, "string");
925
+ return "symbol" == _typeof(i) ? i : i + "";
926
+ }
927
+ //#endregion
928
+ //#region \0@oxc-project+runtime@0.154.0/helpers/esm/defineProperty.js
929
+ function _defineProperty(e, r, t) {
930
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
931
+ value: t,
932
+ enumerable: !0,
933
+ configurable: !0,
934
+ writable: !0
935
+ }) : e[r] = t, e;
936
+ }
937
+ //#endregion
987
938
  //#region src/model/restore.ts
988
939
  function defaultsFor(raw) {
989
940
  switch (raw.type) {
@@ -1021,10 +972,47 @@ function normalizeElement(raw) {
1021
972
  if ((raw.type === "line" || raw.type === "arrow") && !raw.points) merged.points = [[0, 0], [raw.width ?? 0, raw.height ?? 0]];
1022
973
  return merged;
1023
974
  }
1024
- async function loadFonts(elements) {
975
+ var FontLoadError = class extends Error {
976
+ constructor(font) {
977
+ super(`Could not load ${font}`);
978
+ _defineProperty(this, "font", void 0);
979
+ this.font = font;
980
+ this.name = "FontLoadError";
981
+ }
982
+ };
983
+ var familyName = (value) => value.trim().replaceAll(/^["']|["']$/g, "");
984
+ var HAND_WEB_FAMILIES = new Set(HAND_FONT_STACK.split(",").slice(0, 4).map(familyName));
985
+ function hasRegisteredHandFace(stack) {
986
+ const wanted = stack.split(",").map(familyName).filter((family) => HAND_WEB_FAMILIES.has(family));
987
+ if (wanted.length === 0) return true;
988
+ try {
989
+ for (const face of document.fonts) if (wanted.includes(familyName(face.family))) return true;
990
+ } catch {
991
+ return false;
992
+ }
993
+ return false;
994
+ }
995
+ async function loadFonts(elements, strict) {
1025
996
  if (typeof document === "undefined" || !document.fonts?.load) return;
1026
- const fonts = new Set(elements.filter((el) => el.type === "text").map((el) => `${el.fontSize}px ${fontFamilyToCss(el.fontFamily)}`));
1027
- await Promise.all([...fonts].map((font) => document.fonts.load(font).catch(() => [])));
997
+ const samples = /* @__PURE__ */ new Map();
998
+ for (const el of elements) {
999
+ if (el.type !== "text" || el.isDeleted) continue;
1000
+ const stack = fontFamilyToCss(el.fontFamily);
1001
+ const font = `${el.fontSize}px ${stack}`;
1002
+ const sample = samples.get(font) ?? {
1003
+ chars: /* @__PURE__ */ new Set(),
1004
+ stack
1005
+ };
1006
+ for (const ch of el.originalText ?? el.text) sample.chars.add(ch);
1007
+ samples.set(font, sample);
1008
+ }
1009
+ await Promise.all([...samples].map(async ([font, { chars, stack }]) => {
1010
+ const faces = await document.fonts.load(font, [...chars].join("")).catch(() => {
1011
+ if (strict) throw new FontLoadError(font);
1012
+ return [];
1013
+ });
1014
+ if (strict && faces.length === 0 && !hasRegisteredHandFace(stack)) throw new FontLoadError(font);
1015
+ }));
1028
1016
  }
1029
1017
  function textChanged(a, b) {
1030
1018
  return a.text !== b.text || a.width !== b.width || a.height !== b.height || a.x !== b.x || a.y !== b.y;
@@ -1032,7 +1020,7 @@ function textChanged(a, b) {
1032
1020
  async function restoreElements(elements, _localElements, opts = {}) {
1033
1021
  const normalized = syncIndices(elements.map((el) => normalizeElement(el)));
1034
1022
  if (!opts.refreshDimensions) return normalized;
1035
- await loadFonts(normalized);
1023
+ await loadFonts(normalized, opts.strictFonts ?? false);
1036
1024
  const byId = new Map(normalized.map((el) => [el.id, el]));
1037
1025
  return normalized.map((el) => {
1038
1026
  if (el.type !== "text") return el;
@@ -1111,6 +1099,8 @@ function resolveRichTextHeights(elements) {
1111
1099
  //#endregion
1112
1100
  //#region src/scene/context.ts
1113
1101
  var SceneDarkContext = createContext(null);
1102
+ var SceneHandFontContext = createContext(null);
1103
+ var SceneExportContext = createContext(false);
1114
1104
  //#endregion
1115
1105
  //#region src/scene/freedraw.ts
1116
1106
  var average = (a, b) => (a + b) / 2;
@@ -1292,6 +1282,78 @@ var RichTextBody = ({ el }) => /* @__PURE__ */ jsx("foreignObject", {
1292
1282
  })
1293
1283
  });
1294
1284
  //#endregion
1285
+ //#region src/scene/richtext/RichTextSvgBody.tsx
1286
+ var BASELINE_RATIO = .8;
1287
+ var MARKER_GAP = 6;
1288
+ var QUOTE_BAR = "#c4c4c4";
1289
+ function colorOf(node) {
1290
+ const styled = (node.children ?? []).find((child) => typeof child.style === "string");
1291
+ const match = /(?:^|;)\s*color\s*:\s*([^;]+)/i.exec(styled?.style ?? "");
1292
+ return match ? match[1].trim() : RICHTEXT_TEXT_COLOR;
1293
+ }
1294
+ function drawBlock(node, x, width, cursor, marker) {
1295
+ const { fontSize, fontWeight, lineHeight } = blockTypography(node);
1296
+ const font = richTextFont(node);
1297
+ const indent = childIndent(node);
1298
+ const lines = wrapText(richTextPlainText(node), font, Math.max(1, width - indent)).split("\n");
1299
+ const step = fontSizeOf(font) * lineHeight;
1300
+ const top = cursor.y;
1301
+ const baseline = top + (step - fontSize) / 2 + fontSize * BASELINE_RATIO;
1302
+ const key = cursor.nodes.length;
1303
+ if (node.type === "quote") cursor.nodes.push(/* @__PURE__ */ jsx("rect", {
1304
+ fill: QUOTE_BAR,
1305
+ height: lines.length * step,
1306
+ width: 3,
1307
+ x,
1308
+ y: top
1309
+ }, `q${key}`));
1310
+ if (marker) cursor.nodes.push(/* @__PURE__ */ jsx("text", {
1311
+ fill: RICHTEXT_TEXT_COLOR,
1312
+ fontFamily: SANS_FONT_STACK,
1313
+ fontSize,
1314
+ textAnchor: "end",
1315
+ x: x - MARKER_GAP,
1316
+ y: baseline,
1317
+ children: marker
1318
+ }, `m${key}`));
1319
+ cursor.nodes.push(/* @__PURE__ */ jsx("text", {
1320
+ fill: colorOf(node),
1321
+ fontFamily: SANS_FONT_STACK,
1322
+ fontSize,
1323
+ fontWeight,
1324
+ style: { whiteSpace: "pre" },
1325
+ x: x + indent,
1326
+ y: baseline,
1327
+ children: lines.map((line, i) => /* @__PURE__ */ jsx("tspan", {
1328
+ dy: i === 0 ? 0 : step,
1329
+ x: x + indent,
1330
+ children: line || " "
1331
+ }, i))
1332
+ }, `t${key}`));
1333
+ cursor.y += lines.length * step;
1334
+ }
1335
+ function drawStack(nodes, x, width, cursor, list) {
1336
+ nodes.forEach((node, i) => {
1337
+ if (isBlockContainer(node) && hasBlockChildren(node)) {
1338
+ const indent = childIndent(node);
1339
+ drawStack(node.children ?? [], x + indent, width - indent, cursor, node.type === "list" ? node : void 0);
1340
+ return;
1341
+ }
1342
+ drawBlock(node, x, width, cursor, list ? list.listType === "number" ? `${i + 1}.` : "•" : void 0);
1343
+ });
1344
+ }
1345
+ var RichTextSvgBody = ({ el }) => {
1346
+ const cursor = {
1347
+ nodes: [],
1348
+ y: 12
1349
+ };
1350
+ drawStack(contentRoot(el.content).children ?? [], 12, el.width - 24, cursor);
1351
+ return /* @__PURE__ */ jsx("g", {
1352
+ "data-richtext-body": el.id,
1353
+ children: cursor.nodes
1354
+ });
1355
+ };
1356
+ //#endregion
1295
1357
  //#region src/scene/rough.ts
1296
1358
  var _gen = null;
1297
1359
  function gen() {
@@ -1428,7 +1490,7 @@ var ElementContent = ({ el, files }) => {
1428
1490
  files
1429
1491
  });
1430
1492
  case "svg": return /* @__PURE__ */ jsx(SvgRender, { el });
1431
- case "richtext": return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(RectangleRender, { el }), /* @__PURE__ */ jsx(RichTextBody, { el })] });
1493
+ case "richtext": return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(RectangleRender, { el }), /* @__PURE__ */ jsx(RichTextCardBody, { el })] });
1432
1494
  case "frame":
1433
1495
  case "magicframe": return /* @__PURE__ */ jsx(FrameRender, { el });
1434
1496
  case "embeddable":
@@ -1626,7 +1688,8 @@ var TextRender = ({ el }) => {
1626
1688
  const lineHeight = el.lineHeight ?? DEFAULT_LINE_HEIGHT;
1627
1689
  const lines = el.text.split("\n");
1628
1690
  const fontSize = el.fontSize;
1629
- const family = fontFamilyToCss(el.fontFamily);
1691
+ const handFont = use(SceneHandFontContext);
1692
+ const family = handFont && isHandFontFamily(el.fontFamily) ? handFont : fontFamilyToCss(el.fontFamily);
1630
1693
  const anchor = el.textAlign === "center" ? "middle" : el.textAlign === "right" ? "end" : "start";
1631
1694
  const ax = el.textAlign === "center" ? el.width / 2 : el.textAlign === "right" ? el.width : 0;
1632
1695
  const dy = fontSize * lineHeight;
@@ -1647,6 +1710,7 @@ var TextRender = ({ el }) => {
1647
1710
  }, i))
1648
1711
  });
1649
1712
  };
1713
+ var RichTextCardBody = ({ el }) => use(SceneExportContext) ? /* @__PURE__ */ jsx(RichTextSvgBody, { el }) : /* @__PURE__ */ jsx(RichTextBody, { el });
1650
1714
  var ImageRender = ({ el, files }) => {
1651
1715
  const darkFilter = use(SceneDarkContext);
1652
1716
  const clipId = `rich-excalidraw-crop-${useId().replaceAll(/[^\w-]/g, "")}`;
@@ -1793,8 +1857,49 @@ var CounterInvertFilter = ({ id }) => /* @__PURE__ */ jsxs("filter", {
1793
1857
  })]
1794
1858
  });
1795
1859
  var isFrame = (el) => el.type === "frame" || el.type === "magicframe";
1796
- var SceneContent = memo(({ dark = false, elementProps, files, hiddenIds, scene }) => {
1860
+ var LABEL_PAD = 4;
1861
+ var LINE_PAD = 64;
1862
+ function labelCuts(elements) {
1863
+ const lines = new Map(elements.filter((el) => el.type === "arrow" || el.type === "line").map((el) => [el.id, el]));
1864
+ const cuts = /* @__PURE__ */ new Map();
1865
+ for (const el of elements) {
1866
+ if (el.type !== "text" || !el.containerId || !el.text?.trim()) continue;
1867
+ const line = lines.get(el.containerId);
1868
+ if (!line) continue;
1869
+ const points = line.points ?? [];
1870
+ const xs = [
1871
+ 0,
1872
+ line.width,
1873
+ ...points.map(([x]) => x)
1874
+ ];
1875
+ const ys = [
1876
+ 0,
1877
+ line.height,
1878
+ ...points.map(([, y]) => y)
1879
+ ];
1880
+ const left = line.x + Math.min(...xs) - LINE_PAD;
1881
+ const top = line.y + Math.min(...ys) - LINE_PAD;
1882
+ cuts.set(line.id, {
1883
+ area: [
1884
+ left,
1885
+ top,
1886
+ line.x + Math.max(...xs) + LINE_PAD - left,
1887
+ line.y + Math.max(...ys) + LINE_PAD - top
1888
+ ],
1889
+ hole: [
1890
+ el.x - LABEL_PAD,
1891
+ el.y - LABEL_PAD,
1892
+ el.width + 8,
1893
+ el.height + 8
1894
+ ]
1895
+ });
1896
+ }
1897
+ return cuts;
1898
+ }
1899
+ var SceneContent = memo(({ dark = false, elementProps, files, handFontOverride, hiddenIds, scene }) => {
1797
1900
  const elements = resolveRichTextHeights(scene.elements.filter((el) => !el.isDeleted));
1901
+ const inheritedHandFont = use(SceneHandFontContext);
1902
+ const handFont = handFontOverride ?? inheritedHandFont;
1798
1903
  const uid = useId().replaceAll(/[^\w-]/g, "");
1799
1904
  const filterId = `rich-excalidraw-counter-invert-${uid}`;
1800
1905
  const frames = new Map(elements.filter(isFrame).map((f) => [f.id, f]));
@@ -1802,48 +1907,78 @@ var SceneContent = memo(({ dark = false, elementProps, files, hiddenIds, scene }
1802
1907
  const clipId = (frameId) => `rich-excalidraw-frame-${uid}-${frameId.replaceAll(/[^\w-]/g, "")}`;
1803
1908
  const shadowId = `rich-excalidraw-shadow-${uid}`;
1804
1909
  const anyShadow = elements.some(hasShadow);
1805
- const hasDefs = dark || usedFrames.size > 0 || anyShadow;
1806
- return /* @__PURE__ */ jsxs(SceneDarkContext, {
1910
+ const cuts = labelCuts(elements);
1911
+ const cutId = (id) => `rich-excalidraw-label-${uid}-${id.replaceAll(/[^\w-]/g, "")}`;
1912
+ const hasDefs = dark || usedFrames.size > 0 || anyShadow || cuts.size > 0;
1913
+ return /* @__PURE__ */ jsx(SceneDarkContext, {
1807
1914
  value: dark ? { filterId } : null,
1808
- children: [hasDefs && /* @__PURE__ */ jsxs("defs", { children: [
1809
- dark && /* @__PURE__ */ jsx(CounterInvertFilter, { id: filterId }),
1810
- anyShadow && /* @__PURE__ */ jsx(ShadowFilter, {
1811
- dark,
1812
- id: shadowId
1813
- }),
1814
- [...usedFrames].map((id) => {
1815
- const f = frames.get(id);
1816
- return /* @__PURE__ */ jsx("clipPath", {
1817
- id: clipId(id),
1818
- children: /* @__PURE__ */ jsx("rect", {
1819
- height: f.height,
1820
- width: f.width,
1821
- x: f.x,
1822
- y: f.y
1823
- })
1824
- }, id);
1825
- })
1826
- ] }), elements.map((el) => {
1827
- if (hiddenIds?.has(el.id)) return null;
1828
- const element = /* @__PURE__ */ jsx(ElementGroup, {
1829
- el,
1830
- extra: elementProps?.(el),
1831
- files
1832
- }, el.id);
1833
- const group = hasShadow(el) ? /* @__PURE__ */ jsx("g", {
1834
- filter: `url(#${shadowId})`,
1835
- children: element
1836
- }, el.id) : element;
1837
- if (el.frameId && usedFrames.has(el.frameId)) return /* @__PURE__ */ jsx("g", {
1838
- clipPath: `url(#${clipId(el.frameId)})`,
1839
- children: group
1840
- }, el.id);
1841
- return group;
1842
- })]
1915
+ children: /* @__PURE__ */ jsxs(SceneHandFontContext, {
1916
+ value: handFont,
1917
+ children: [hasDefs && /* @__PURE__ */ jsxs("defs", { children: [
1918
+ dark && /* @__PURE__ */ jsx(CounterInvertFilter, { id: filterId }),
1919
+ anyShadow && /* @__PURE__ */ jsx(ShadowFilter, {
1920
+ dark,
1921
+ id: shadowId
1922
+ }),
1923
+ [...usedFrames].map((id) => {
1924
+ const f = frames.get(id);
1925
+ return /* @__PURE__ */ jsx("clipPath", {
1926
+ id: clipId(id),
1927
+ children: /* @__PURE__ */ jsx("rect", {
1928
+ height: f.height,
1929
+ width: f.width,
1930
+ x: f.x,
1931
+ y: f.y
1932
+ })
1933
+ }, id);
1934
+ }),
1935
+ [...cuts].map(([id, { area, hole }]) => /* @__PURE__ */ jsxs("mask", {
1936
+ height: area[3],
1937
+ id: cutId(id),
1938
+ maskUnits: "userSpaceOnUse",
1939
+ width: area[2],
1940
+ x: area[0],
1941
+ y: area[1],
1942
+ children: [/* @__PURE__ */ jsx("rect", {
1943
+ fill: "#fff",
1944
+ height: area[3],
1945
+ width: area[2],
1946
+ x: area[0],
1947
+ y: area[1]
1948
+ }), /* @__PURE__ */ jsx("rect", {
1949
+ fill: "#000",
1950
+ height: hole[3],
1951
+ width: hole[2],
1952
+ x: hole[0],
1953
+ y: hole[1]
1954
+ })]
1955
+ }, id))
1956
+ ] }), elements.map((el) => {
1957
+ if (hiddenIds?.has(el.id)) return null;
1958
+ const drawn = /* @__PURE__ */ jsx(ElementGroup, {
1959
+ el,
1960
+ extra: elementProps?.(el),
1961
+ files
1962
+ }, el.id);
1963
+ const element = cuts.has(el.id) ? /* @__PURE__ */ jsx("g", {
1964
+ mask: `url(#${cutId(el.id)})`,
1965
+ children: drawn
1966
+ }, el.id) : drawn;
1967
+ const group = hasShadow(el) ? /* @__PURE__ */ jsx("g", {
1968
+ filter: `url(#${shadowId})`,
1969
+ children: element
1970
+ }, el.id) : element;
1971
+ if (el.frameId && usedFrames.has(el.frameId)) return /* @__PURE__ */ jsx("g", {
1972
+ clipPath: `url(#${clipId(el.frameId)})`,
1973
+ children: group
1974
+ }, el.id);
1975
+ return group;
1976
+ })]
1977
+ })
1843
1978
  });
1844
1979
  });
1845
1980
  SceneContent.displayName = "SceneContent";
1846
- var Scene = ({ className, files, scene, style, theme = "light" }) => {
1981
+ var Scene = ({ className, files, handFontOverride, scene, style, theme = "light" }) => {
1847
1982
  const bounds = computeSceneBounds(scene.elements.filter((el) => !el.isDeleted));
1848
1983
  const isDark = theme === "dark";
1849
1984
  return /* @__PURE__ */ jsx("svg", {
@@ -1862,6 +1997,7 @@ var Scene = ({ className, files, scene, style, theme = "light" }) => {
1862
1997
  children: /* @__PURE__ */ jsx(SceneContent, {
1863
1998
  dark: isDark,
1864
1999
  files: files ?? scene.files,
2000
+ handFontOverride,
1865
2001
  scene
1866
2002
  })
1867
2003
  });
@@ -1885,666 +2021,22 @@ var ElementGroup = ({ el, extra, files }) => {
1885
2021
  });
1886
2022
  };
1887
2023
  //#endregion
1888
- //#region src/scene/styles.css.ts
1889
- var sceneRoot = "hfbknr0";
1890
- var sceneSvg = "hfbknr1";
1891
- var toolbar = "hfbknr2";
1892
- var toolButton = "hfbknr3";
1893
- var zoomLabel = "hfbknr4";
1894
- var toolSeparator = "hfbknr5";
1895
- //#endregion
1896
- //#region src/scene/InteractiveScene.tsx
1897
- var MIN_SCALE = .05;
1898
- var MAX_SCALE = 16;
1899
- var ZOOM_STEP = 1.2;
1900
- var InteractiveScene = ({ mode = "inline", onExpand, scene, theme = "light" }) => {
1901
- const containerRef = useRef(null);
1902
- const [size, setSize] = useState({
1903
- w: 0,
1904
- h: 0
1905
- });
1906
- const [transform, setTransform] = useState({
1907
- s: 1,
1908
- tx: 0,
1909
- ty: 0
1910
- });
1911
- const [panning, setPanning] = useState(false);
1912
- const transformRef = useRef(transform);
1913
- const userInteractedRef = useRef(false);
1914
- const elements = useMemo(() => scene.elements.filter((el) => !el.isDeleted), [scene]);
1915
- const bounds = useMemo(() => computeSceneBounds(elements), [elements]);
1916
- useEffect(() => {
1917
- transformRef.current = transform;
1918
- }, [transform]);
1919
- useLayoutEffect(() => {
1920
- const node = containerRef.current;
1921
- if (!node) return;
1922
- const rect = node.getBoundingClientRect();
1923
- setSize({
1924
- w: rect.width,
1925
- h: rect.height
1926
- });
1927
- const ro = new ResizeObserver((entries) => {
1928
- const r = entries[0].contentRect;
1929
- setSize({
1930
- w: r.width,
1931
- h: r.height
1932
- });
1933
- });
1934
- ro.observe(node);
1935
- return () => ro.disconnect();
1936
- }, []);
1937
- const computeFit = useCallback(() => {
1938
- if (!size.w || !size.h) return {
1939
- s: 1,
1940
- tx: 0,
1941
- ty: 0
1942
- };
1943
- const sceneW = bounds.width || 1;
1944
- const sceneH = bounds.height || 1;
1945
- const s = Math.max(MIN_SCALE, Math.min(MAX_SCALE, Math.min((size.w - 64) / sceneW, (size.h - 64) / sceneH)));
1946
- return {
1947
- s,
1948
- tx: size.w / 2 - (bounds.minX + sceneW / 2) * s,
1949
- ty: size.h / 2 - (bounds.minY + sceneH / 2) * s
1950
- };
1951
- }, [size, bounds]);
1952
- const fitToContent = useCallback(() => {
1953
- setTransform(computeFit());
1954
- userInteractedRef.current = false;
1955
- }, [computeFit]);
1956
- useLayoutEffect(() => {
1957
- if (userInteractedRef.current) return;
1958
- if (!size.w || !size.h) return;
1959
- setTransform(computeFit());
1960
- }, [size, computeFit]);
1961
- useEffect(() => {
1962
- userInteractedRef.current = false;
1963
- }, [scene]);
1964
- const zoomAt = useCallback((factor, anchorX, anchorY) => {
1965
- const t = transformRef.current;
1966
- const newS = Math.max(MIN_SCALE, Math.min(MAX_SCALE, t.s * factor));
1967
- const k = newS / t.s;
1968
- if (k === 1) return;
1969
- userInteractedRef.current = true;
1970
- setTransform({
1971
- s: newS,
1972
- tx: anchorX - (anchorX - t.tx) * k,
1973
- ty: anchorY - (anchorY - t.ty) * k
1974
- });
1975
- }, []);
1976
- useEffect(() => {
1977
- const node = containerRef.current;
1978
- if (!node) return;
1979
- const onWheel = (e) => {
1980
- if (!e.ctrlKey && !e.metaKey) return;
1981
- e.preventDefault();
1982
- const rect = node.getBoundingClientRect();
1983
- zoomAt(e.deltaY > 0 ? .9 : 1.1, e.clientX - rect.left, e.clientY - rect.top);
1984
- };
1985
- node.addEventListener("wheel", onWheel, { passive: false });
1986
- return () => node.removeEventListener("wheel", onWheel);
1987
- }, [zoomAt]);
1988
- const pointersRef = useRef(/* @__PURE__ */ new Map());
1989
- const panRef = useRef(null);
1990
- const pinchRef = useRef(null);
1991
- const ownsPointer = (e) => !(mode === "inline" && e.pointerType === "touch");
1992
- const startPinch = () => {
1993
- const pts = [...pointersRef.current.values()];
1994
- const node = containerRef.current;
1995
- if (pts.length < 2 || !node) return;
1996
- const rect = node.getBoundingClientRect();
1997
- pinchRef.current = {
1998
- distance: Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y) || 1,
1999
- origScale: transformRef.current.s,
2000
- origTx: transformRef.current.tx,
2001
- origTy: transformRef.current.ty,
2002
- midX: (pts[0].x + pts[1].x) / 2 - rect.left,
2003
- midY: (pts[0].y + pts[1].y) / 2 - rect.top
2004
- };
2005
- };
2006
- const handlePointerDown = (e) => {
2007
- if (!ownsPointer(e)) return;
2008
- if (e.pointerType === "mouse" && e.button !== 0) return;
2009
- if (e.target.closest("button")) return;
2010
- e.currentTarget.setPointerCapture(e.pointerId);
2011
- pointersRef.current.set(e.pointerId, {
2012
- x: e.clientX,
2013
- y: e.clientY
2014
- });
2015
- if (pointersRef.current.size === 1) {
2016
- panRef.current = {
2017
- startX: e.clientX,
2018
- startY: e.clientY,
2019
- origTx: transformRef.current.tx,
2020
- origTy: transformRef.current.ty
2021
- };
2022
- setPanning(true);
2023
- } else if (pointersRef.current.size === 2) {
2024
- panRef.current = null;
2025
- startPinch();
2026
- }
2027
- };
2028
- const handlePointerMove = (e) => {
2029
- if (!pointersRef.current.has(e.pointerId)) return;
2030
- pointersRef.current.set(e.pointerId, {
2031
- x: e.clientX,
2032
- y: e.clientY
2033
- });
2034
- const pinch = pinchRef.current;
2035
- if (pinch && pointersRef.current.size === 2) {
2036
- userInteractedRef.current = true;
2037
- const pts = [...pointersRef.current.values()];
2038
- const ratio = (Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y) || 1) / pinch.distance;
2039
- const newS = Math.max(MIN_SCALE, Math.min(MAX_SCALE, pinch.origScale * ratio));
2040
- const k = newS / pinch.origScale;
2041
- setTransform({
2042
- s: newS,
2043
- tx: pinch.midX - (pinch.midX - pinch.origTx) * k,
2044
- ty: pinch.midY - (pinch.midY - pinch.origTy) * k
2045
- });
2046
- return;
2047
- }
2048
- const pan = panRef.current;
2049
- if (pan && pointersRef.current.size === 1) {
2050
- userInteractedRef.current = true;
2051
- setTransform((t) => ({
2052
- s: t.s,
2053
- tx: pan.origTx + e.clientX - pan.startX,
2054
- ty: pan.origTy + e.clientY - pan.startY
2055
- }));
2056
- }
2057
- };
2058
- const releasePointer = (e) => {
2059
- if (!pointersRef.current.delete(e.pointerId)) return;
2060
- if (pointersRef.current.size < 2) pinchRef.current = null;
2061
- if (pointersRef.current.size === 0) {
2062
- panRef.current = null;
2063
- setPanning(false);
2064
- }
2065
- if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId);
2066
- };
2067
- const handleDoubleClick = (e) => {
2068
- if (e.target.closest("button")) return;
2069
- fitToContent();
2070
- };
2071
- const centerZoom = (factor) => zoomAt(factor, size.w / 2, size.h / 2);
2072
- const isDark = theme === "dark";
2073
- const label = `Whiteboard, ${elements.length} elements`;
2074
- return /* @__PURE__ */ jsxs("div", {
2075
- className: sceneRoot,
2076
- "data-color-scheme": theme,
2077
- "data-mode": mode,
2078
- "data-panning": panning,
2079
- ref: containerRef,
2080
- onDoubleClick: handleDoubleClick,
2081
- onPointerCancel: releasePointer,
2082
- onPointerDown: handlePointerDown,
2083
- onPointerMove: handlePointerMove,
2084
- onPointerUp: releasePointer,
2085
- children: [/* @__PURE__ */ jsx("svg", {
2086
- "aria-label": label,
2087
- className: sceneSvg,
2088
- preserveAspectRatio: "xMinYMin meet",
2089
- role: "img",
2090
- style: isDark ? { filter: DARK_SCENE_FILTER } : void 0,
2091
- viewBox: `0 0 ${size.w || 1} ${size.h || 1}`,
2092
- xmlns: "http://www.w3.org/2000/svg",
2093
- children: /* @__PURE__ */ jsx("g", {
2094
- transform: `translate(${transform.tx} ${transform.ty}) scale(${transform.s})`,
2095
- children: /* @__PURE__ */ jsx(SceneContent, {
2096
- dark: isDark,
2097
- files: scene.files,
2098
- scene
2099
- })
2100
- })
2101
- }), /* @__PURE__ */ jsxs("div", {
2102
- className: toolbar,
2103
- children: [
2104
- /* @__PURE__ */ jsx("button", {
2105
- "aria-label": "Zoom out",
2106
- className: toolButton,
2107
- title: "Zoom out (⌘/Ctrl + scroll)",
2108
- type: "button",
2109
- onClick: () => centerZoom(1 / ZOOM_STEP),
2110
- children: /* @__PURE__ */ jsx(ZoomOut, {})
2111
- }),
2112
- /* @__PURE__ */ jsxs("span", {
2113
- className: zoomLabel,
2114
- children: [Math.round(transform.s * 100), "%"]
2115
- }),
2116
- /* @__PURE__ */ jsx("button", {
2117
- "aria-label": "Zoom in",
2118
- className: toolButton,
2119
- title: "Zoom in (⌘/Ctrl + scroll)",
2120
- type: "button",
2121
- onClick: () => centerZoom(ZOOM_STEP),
2122
- children: /* @__PURE__ */ jsx(ZoomIn, {})
2123
- }),
2124
- /* @__PURE__ */ jsx("span", {
2125
- "aria-hidden": true,
2126
- className: toolSeparator
2127
- }),
2128
- /* @__PURE__ */ jsx("button", {
2129
- "aria-label": "Fit to content",
2130
- className: toolButton,
2131
- title: "Fit to content (double-click)",
2132
- type: "button",
2133
- onClick: fitToContent,
2134
- children: /* @__PURE__ */ jsx(ScanSearch, {})
2135
- }),
2136
- onExpand && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
2137
- "aria-hidden": true,
2138
- className: "hfbknr5"
2139
- }), /* @__PURE__ */ jsx("button", {
2140
- "aria-label": "Fullscreen",
2141
- className: "hfbknr3",
2142
- title: "Fullscreen",
2143
- type: "button",
2144
- onClick: (e) => onExpand(e.currentTarget),
2145
- children: /* @__PURE__ */ jsx(Maximize2, {})
2146
- })] })
2147
- ]
2148
- })]
2149
- });
2150
- };
2151
- //#endregion
2152
- //#region src/scene/normalize.ts
2153
- function toScene(data) {
2154
- if (!data) return null;
2155
- if (typeof data !== "object") return null;
2156
- if (!Array.isArray(data.elements) && data.data !== void 0) return toScene(data.data);
2157
- return {
2158
- type: "excalidraw",
2159
- elements: Array.isArray(data.elements) ? data.elements : [],
2160
- appState: data.appState ?? {},
2161
- files: data.files ?? {}
2162
- };
2163
- }
2164
- function countElements(scene) {
2165
- return scene.elements.filter((el) => !el.isDeleted).length;
2166
- }
2167
- //#endregion
2168
- //#region src/useWhiteboardData.ts
2169
- function resolveUrl(url, apiUrl) {
2170
- const refLine = url;
2171
- if (url.startsWith("http") || url.startsWith("blob:") || isLocalScenePath(url)) return {
2172
- fetchUrl: url,
2173
- refLine
2174
- };
2175
- if (url.startsWith("ref:") && apiUrl) return {
2176
- fetchUrl: `${apiUrl}/objects/${url.slice(4)}`,
2177
- refLine
2178
- };
2179
- return { error: url.startsWith("ref:") ? "Missing apiUrl for ref resolution" : "Unrecognized snapshot format" };
2180
- }
2181
- function typedToParsed(typed, apiUrl) {
2182
- switch (typed.type) {
2183
- case "inline": return {
2184
- type: "inline",
2185
- snapshot: typed.data
2186
- };
2187
- case "remote": {
2188
- const result = resolveUrl(typed.url, apiUrl);
2189
- if ("error" in result) return {
2190
- type: "error",
2191
- error: result.error
2192
- };
2193
- return {
2194
- type: "remote",
2195
- fetchUrl: result.fetchUrl,
2196
- refLine: result.refLine
2197
- };
2198
- }
2199
- case "delta": {
2200
- const result = resolveUrl(typed.baseUrl, apiUrl);
2201
- if ("error" in result) return {
2202
- type: "error",
2203
- error: result.error
2204
- };
2205
- return {
2206
- type: "incremental",
2207
- fetchUrl: result.fetchUrl,
2208
- refLine: result.refLine,
2209
- delta: typed.delta
2210
- };
2211
- }
2212
- }
2213
- }
2214
- function stringToParsed(data, apiUrl) {
2215
- if (!data.trim()) return { type: "empty" };
2216
- const typed = parseSnapshot(data);
2217
- if (!typed) return {
2218
- type: "error",
2219
- error: "Unrecognized snapshot format"
2220
- };
2221
- return typedToParsed(typed, apiUrl);
2222
- }
2223
- function useWhiteboardData(data) {
2224
- const { apiUrl } = useWhiteboardConfig();
2225
- const parsed = useMemo(() => {
2226
- if (data === null || data === void 0) return { type: "empty" };
2227
- if (typeof data === "string") return stringToParsed(data, apiUrl);
2228
- return typedToParsed(data, apiUrl);
2229
- }, [data, apiUrl]);
2230
- const [remoteSnapshot, setRemoteSnapshot] = useState();
2231
- const [baseData, setBaseData] = useState();
2232
- const [loading, setLoading] = useState(parsed.type === "remote" || parsed.type === "incremental");
2233
- const [error, setError] = useState("");
2234
- const [attempt, setAttempt] = useState(0);
2235
- const retry = useCallback(() => setAttempt((n) => n + 1), []);
2236
- useEffect(() => {
2237
- if (parsed.type !== "remote" && parsed.type !== "incremental") return;
2238
- const { fetchUrl } = parsed;
2239
- const delta = parsed.type === "incremental" ? parsed.delta : void 0;
2240
- let cancelled = false;
2241
- setLoading(true);
2242
- setError("");
2243
- fetch(fetchUrl).then((res) => {
2244
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
2245
- return res.json();
2246
- }).then(async (json) => {
2247
- if (cancelled) return;
2248
- setBaseData(json);
2249
- if ((delta ? Object.keys(delta) : []).length > 0) {
2250
- const { patch } = await import("jsondiffpatch");
2251
- if (cancelled) return;
2252
- const patched = patch(structuredClone(json), delta);
2253
- setRemoteSnapshot(patched);
2254
- } else setRemoteSnapshot(json);
2255
- setLoading(false);
2256
- }).catch((err) => {
2257
- if (!cancelled) {
2258
- setError(err instanceof Error ? err.message : "Failed to load");
2259
- setLoading(false);
2260
- }
2261
- });
2262
- return () => {
2263
- cancelled = true;
2264
- };
2265
- }, [parsed, attempt]);
2266
- if (parsed.type === "inline") return {
2267
- snapshot: parsed.snapshot,
2268
- loading: false,
2269
- error: "",
2270
- retry,
2271
- retryable: false
2272
- };
2273
- if (parsed.type === "remote" || parsed.type === "incremental") return {
2274
- snapshot: remoteSnapshot,
2275
- loading,
2276
- error,
2277
- retry,
2278
- retryable: Boolean(error),
2279
- baseRef: parsed.refLine,
2280
- baseData
2281
- };
2282
- if (parsed.type === "error") return {
2283
- snapshot: void 0,
2284
- loading: false,
2285
- error: parsed.error,
2286
- retry,
2287
- retryable: false
2288
- };
2024
+ //#region src/model/viewport-fit.ts
2025
+ function viewportFor(bounds, size, { insets = {}, maxZoom = 30, minZoom = .1, padding = 0, zoomFactor = 1 } = {}) {
2026
+ const left = insets.left ?? 0;
2027
+ const top = insets.top ?? 0;
2028
+ const width = Math.max(1, size.width - left - (insets.right ?? 0));
2029
+ const height = Math.max(1, size.height - top - (insets.bottom ?? 0));
2030
+ const [minX, minY, maxX, maxY] = bounds;
2031
+ const w = Math.max(1, maxX - minX);
2032
+ const h = Math.max(1, maxY - minY);
2033
+ const fit = Math.min((width - padding * 2) / w, (height - padding * 2) / h) * zoomFactor;
2034
+ const zoom = Math.min(maxZoom, Math.max(minZoom, fit));
2289
2035
  return {
2290
- snapshot: void 0,
2291
- loading: false,
2292
- error: "",
2293
- retry,
2294
- retryable: false
2036
+ zoom,
2037
+ scrollX: (left + width / 2) / zoom - (minX + w / 2),
2038
+ scrollY: (top + height / 2) / zoom - (minY + h / 2)
2295
2039
  };
2296
2040
  }
2297
2041
  //#endregion
2298
- //#region src/useWhiteboardFont.ts
2299
- var DEFAULT_FONT_CSS_HREF = "https://cdn.jsdelivr.net/npm/lxgw-wenkai-screen-webfont/style.css";
2300
- function useWhiteboardFont() {
2301
- const { fontCssHref = DEFAULT_FONT_CSS_HREF } = useWhiteboardConfig();
2302
- useEffect(() => {
2303
- if (!fontCssHref || typeof document === "undefined") return;
2304
- if (document.head.querySelector(`link[href="${CSS.escape(fontCssHref)}"]`)) return;
2305
- const link = document.createElement("link");
2306
- link.rel = "stylesheet";
2307
- link.href = fontCssHref;
2308
- document.head.append(link);
2309
- }, [fontCssHref]);
2310
- }
2311
- //#endregion
2312
- //#region src/WhiteboardFrameStates.tsx
2313
- var WhiteboardPlaceholderState = ({ elementCount }) => {
2314
- const label = elementCount ? `Whiteboard · ${elementCount} elements` : "Whiteboard";
2315
- return /* @__PURE__ */ jsxs("div", {
2316
- "aria-label": label,
2317
- className: whiteboardStateLayer,
2318
- children: [/* @__PURE__ */ jsx(PenLine, {
2319
- "aria-hidden": true,
2320
- className: whiteboardStateIcon
2321
- }), /* @__PURE__ */ jsx("span", { children: label })]
2322
- });
2323
- };
2324
- var WhiteboardLoadingState = () => /* @__PURE__ */ jsx("div", {
2325
- "aria-busy": true,
2326
- className: whiteboardLoading,
2327
- children: /* @__PURE__ */ jsx("span", { children: "Loading whiteboard…" })
2328
- });
2329
- var WhiteboardEmptyState = () => /* @__PURE__ */ jsx("div", {
2330
- className: whiteboardEmpty,
2331
- children: /* @__PURE__ */ jsx("span", { children: "Empty whiteboard" })
2332
- });
2333
- var WhiteboardErrorState = ({ message, onRetry }) => /* @__PURE__ */ jsxs("div", {
2334
- className: whiteboardError,
2335
- role: "alert",
2336
- children: [
2337
- /* @__PURE__ */ jsx(TriangleAlert, {
2338
- "aria-hidden": true,
2339
- className: whiteboardErrorIcon
2340
- }),
2341
- /* @__PURE__ */ jsx("span", { children: message }),
2342
- onRetry && /* @__PURE__ */ jsx("button", {
2343
- className: "_1xd3mo4a",
2344
- type: "button",
2345
- onClick: onRetry,
2346
- children: "Retry"
2347
- })
2348
- ]
2349
- });
2350
- //#endregion
2351
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/typeof.js
2352
- function _typeof(o) {
2353
- "@babel/helpers - typeof";
2354
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
2355
- return typeof o;
2356
- } : function(o) {
2357
- return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
2358
- }, _typeof(o);
2359
- }
2360
- //#endregion
2361
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/toPrimitive.js
2362
- function toPrimitive(t, r) {
2363
- if ("object" != _typeof(t) || !t) return t;
2364
- var e = t[Symbol.toPrimitive];
2365
- if (void 0 !== e) {
2366
- var i = e.call(t, r || "default");
2367
- if ("object" != _typeof(i)) return i;
2368
- throw new TypeError("@@toPrimitive must return a primitive value.");
2369
- }
2370
- return ("string" === r ? String : Number)(t);
2371
- }
2372
- //#endregion
2373
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/toPropertyKey.js
2374
- function toPropertyKey(t) {
2375
- var i = toPrimitive(t, "string");
2376
- return "symbol" == _typeof(i) ? i : i + "";
2377
- }
2378
- //#endregion
2379
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/defineProperty.js
2380
- function _defineProperty(e, r, t) {
2381
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
2382
- value: t,
2383
- enumerable: !0,
2384
- configurable: !0,
2385
- writable: !0
2386
- }) : e[r] = t, e;
2387
- }
2388
- //#endregion
2389
- //#region src/WhiteboardDisplayRenderer.tsx
2390
- var WhiteboardDisplayRenderer_exports = /* @__PURE__ */ __exportAll({ WhiteboardDisplayRenderer: () => WhiteboardDisplayRenderer });
2391
- var WhiteboardDisplayRenderer = ({ onExpand, snapshot }) => {
2392
- const theme = useColorScheme();
2393
- const { snapshot: data, loading, error, retry, retryable } = useWhiteboardData(snapshot);
2394
- const scene = useMemo(() => toScene(data), [data]);
2395
- useWhiteboardFont();
2396
- const handleExpand = useCallback((target) => {
2397
- if (!onExpand || !scene) return;
2398
- onExpand({
2399
- content: /* @__PURE__ */ jsx(InteractiveScene, {
2400
- mode: "fullscreen",
2401
- scene,
2402
- theme
2403
- }),
2404
- elementCount: countElements(scene),
2405
- target,
2406
- theme
2407
- });
2408
- }, [
2409
- onExpand,
2410
- scene,
2411
- theme
2412
- ]);
2413
- let body;
2414
- if (loading) body = /* @__PURE__ */ jsx(WhiteboardLoadingState, {});
2415
- else if (error) body = /* @__PURE__ */ jsx(WhiteboardErrorState, {
2416
- message: error,
2417
- onRetry: retryable ? retry : void 0
2418
- });
2419
- else if (!data) body = /* @__PURE__ */ jsx(WhiteboardEmptyState, {});
2420
- else if (!scene) body = /* @__PURE__ */ jsx(WhiteboardErrorState, { message: "Invalid whiteboard data" });
2421
- else if (countElements(scene) === 0) body = /* @__PURE__ */ jsx(WhiteboardEmptyState, {});
2422
- else body = /* @__PURE__ */ jsx(WhiteboardErrorBoundary, {
2423
- fallback: /* @__PURE__ */ jsx(WhiteboardErrorState, { message: "Failed to render whiteboard" }),
2424
- children: /* @__PURE__ */ jsx(InteractiveScene, {
2425
- scene,
2426
- theme,
2427
- onExpand: onExpand ? handleExpand : void 0
2428
- })
2429
- });
2430
- return /* @__PURE__ */ jsx("div", {
2431
- className: whiteboardStaticContainer,
2432
- "data-theme": theme,
2433
- children: body
2434
- });
2435
- };
2436
- var WhiteboardErrorBoundary = class extends Component {
2437
- constructor(..._args) {
2438
- super(..._args);
2439
- _defineProperty(this, "state", { hasError: false });
2440
- }
2441
- static getDerivedStateFromError() {
2442
- return { hasError: true };
2443
- }
2444
- render() {
2445
- return this.state.hasError ? this.props.fallback : this.props.children;
2446
- }
2447
- };
2448
- //#endregion
2449
- //#region src/WhiteboardSSRRenderer.tsx
2450
- var LazyDisplayRenderer = lazy(() => Promise.resolve().then(() => WhiteboardDisplayRenderer_exports).then((m) => ({ default: m.WhiteboardDisplayRenderer })));
2451
- function countInlineElements(snapshot) {
2452
- try {
2453
- const data = JSON.parse(snapshot);
2454
- if (data && typeof data === "object" && Array.isArray(data.elements)) return data.elements.filter((el) => !el?.isDeleted).length;
2455
- } catch {}
2456
- }
2457
- var WhiteboardPlaceholder = ({ snapshot }) => /* @__PURE__ */ jsx("div", {
2458
- className: whiteboardPlaceholder,
2459
- children: /* @__PURE__ */ jsx(WhiteboardPlaceholderState, { elementCount: countInlineElements(snapshot) })
2460
- });
2461
- var WhiteboardSSRRenderer = ({ onExpand, snapshot }) => {
2462
- return /* @__PURE__ */ jsx(ViewportGate, {
2463
- fallback: /* @__PURE__ */ jsx(WhiteboardPlaceholder, { snapshot }),
2464
- children: /* @__PURE__ */ jsx(Suspense, {
2465
- fallback: /* @__PURE__ */ jsx(WhiteboardPlaceholder, { snapshot }),
2466
- children: /* @__PURE__ */ jsx(LazyDisplayRenderer, {
2467
- snapshot,
2468
- onExpand
2469
- })
2470
- })
2471
- });
2472
- };
2473
- //#endregion
2474
- //#region src/WhiteboardNode.ts
2475
- var WhiteboardNode = class WhiteboardNode extends DecoratorNode {
2476
- static getType() {
2477
- return "excalidraw";
2478
- }
2479
- static clone(node) {
2480
- return new WhiteboardNode(node.__snapshot, node.__key);
2481
- }
2482
- constructor(snapshot, key) {
2483
- super(key);
2484
- _defineProperty(this, "__snapshot", void 0);
2485
- this.__snapshot = snapshot;
2486
- }
2487
- createDOM(_config) {
2488
- const div = document.createElement("div");
2489
- div.className = "rich-excalidraw-wrapper";
2490
- return div;
2491
- }
2492
- updateDOM() {
2493
- return false;
2494
- }
2495
- isInline() {
2496
- return false;
2497
- }
2498
- static importJSON(_serializedNode) {
2499
- return $createWhiteboardNode(_serializedNode.snapshot).updateFromJSON(_serializedNode);
2500
- }
2501
- exportJSON() {
2502
- return {
2503
- ...super.exportJSON(),
2504
- type: "excalidraw",
2505
- snapshot: this.__snapshot,
2506
- version: 1
2507
- };
2508
- }
2509
- getSnapshot() {
2510
- return this.__snapshot;
2511
- }
2512
- setSnapshot(snapshot) {
2513
- const writable = this.getWritable();
2514
- writable.__snapshot = snapshot;
2515
- }
2516
- decorate(_editor, _config) {
2517
- return createRendererDecoration(WHITEBOARD_NODE_KEY, WhiteboardSSRRenderer, { snapshot: this.__snapshot });
2518
- }
2519
- };
2520
- function $createWhiteboardNode(snapshot) {
2521
- return new WhiteboardNode(snapshot);
2522
- }
2523
- function $isWhiteboardNode(node) {
2524
- return node instanceof WhiteboardNode;
2525
- }
2526
- //#endregion
2527
- //#region src/WhiteboardExpandShell.tsx
2528
- var WhiteboardExpandShell = ({ children, dismiss, meta = "excalidraw", title = "Whiteboard" }) => /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("div", {
2529
- className: whiteboardDialogHeader,
2530
- children: [/* @__PURE__ */ jsxs("div", {
2531
- className: whiteboardDialogHeaderTitle,
2532
- children: [/* @__PURE__ */ jsx("span", {
2533
- className: whiteboardDialogTitle,
2534
- children: title
2535
- }), meta != null && /* @__PURE__ */ jsx("span", {
2536
- className: "_1xd3mo4f",
2537
- children: meta
2538
- })]
2539
- }), /* @__PURE__ */ jsx("button", {
2540
- className: whiteboardHeaderClose,
2541
- type: "button",
2542
- onClick: dismiss,
2543
- children: /* @__PURE__ */ jsx(X, { size: 18 })
2544
- })]
2545
- }), /* @__PURE__ */ jsx("div", {
2546
- className: whiteboardDialogCanvas,
2547
- children
2548
- })] });
2549
- //#endregion
2550
- export { angleOf as $, newElement as A, randomId as B, layoutBoundText as C, whiteboardSavedDot as Ct, bumpVersion as D, parseSvgSize as E, __exportAll as Et, newRichTextElement as F, getCommonBounds as G, DEFAULT_STYLE as H, newSvgElement as I, getElementCenter as J, getElementAbsoluteCorners as K, newTextElement as L, newFreedrawElement as M, newImageElement as N, syncIndices as O, newLinearElement as P, toLocalPoint as Q, contentRoot as R, restoreElements as S, whiteboardOptionsLabel as St, isSvgSource as T, WHITEBOARD_NODE_KEY as Tt, fontFamilyToCss as U, randomInteger as V, elementsInBox as W, hitTestElement as X, getLinearAbsolutePoints as Y, isLinear as Z, Scene as _, whiteboardFullscreenPopup as _t, WhiteboardSSRRenderer as a, rotatePoint as at, resolveRichTextHeights as b, whiteboardOptionsGroup as bt, WhiteboardEmptyState as c, isLocalScenePath as ct, DEFAULT_FONT_CSS_HREF as d, EXCALIDRAW_BLOCK_TRANSFORMER as dt, boundsContain as et, useWhiteboardFont as f, whiteboardDialogBody as ft, DARK_SCENE_FILTER as g, whiteboardEditorContainer as gt, toScene as h, whiteboardEditOverlay as ht, WhiteboardNode as i, normalizeBox as it, newFrameElement as j, getLineHeight as k, WhiteboardErrorState as l, parseSnapshot as lt, countElements as m, whiteboardEditLabel as mt, $createWhiteboardNode as n, boundsOfPoints as nt, WhiteboardDisplayRenderer as o, WhiteboardConfigProvider as ot, useWhiteboardData as p, whiteboardDialogCanvas as pt, getElementBounds as q, $isWhiteboardNode as r, distanceToSegment as rt, _defineProperty as s, useWhiteboardConfig as st, WhiteboardExpandShell as t, boundsIntersect as tt, WhiteboardLoadingState as u, serializeSnapshot as ut, SceneContent as v, whiteboardOptionsActions as vt, refreshTextDimensions as w, whiteboardShell as wt, normalizeElement as x, whiteboardOptionsHeading as xt, RICHTEXT_BASE_STYLE as y, whiteboardOptionsAdvanced as yt, richTextPlainText as z };
2042
+ export { boundsIntersect as $, contentRoot as A, isHandFontFamily as B, newFrameElement as C, newRichTextElement as D, newLinearElement as E, HAND_FONT_STACK as F, getElementBounds as G, elementsInBox as H, MONO_FONT_STACK as I, hitTestElement as J, getElementCenter as K, SANS_FONT_STACK as L, randomId as M, randomInteger as N, newSvgElement as O, DEFAULT_STYLE as P, boundsContain as Q, WHITEBOARD_FONT_STACK as R, newElement as S, newImageElement as T, getCommonBounds as U, setFontFamilyStack as V, getElementAbsoluteCorners as W, toLocalPoint as X, isLinear as Y, angleOf as Z, parseSvgSize as _, computeSceneBounds as a, syncIndices as b, SceneHandFontContext as c, normalizeElement as d, boundsOfPoints as et, restoreElements as f, isSvgSource as g, refreshTextDimensions as h, SceneContent as i, richTextPlainText as j, newTextElement as k, resolveRichTextHeights as l, layoutBoundText as m, DARK_SCENE_FILTER as n, normalizeBox as nt, RICHTEXT_BASE_STYLE as o, _defineProperty as p, getLinearAbsolutePoints as q, Scene as r, rotatePoint as rt, SceneExportContext as s, viewportFor as t, distanceToSegment as tt, FontLoadError as u, bumpVersion as v, newFreedrawElement as w, getLineHeight as x, isValidIndex as y, fontFamilyToCss as z };