@dou-ui/flow 0.1.0-alpha.3 → 0.1.0-alpha.30

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 (98) hide show
  1. package/dist/collaboration/index.js +114 -6
  2. package/dist/collaboration/index.js.map +1 -1
  3. package/dist/comments.js +257 -0
  4. package/dist/comments.js.map +1 -0
  5. package/dist/components/default-node.js.map +1 -1
  6. package/dist/components/default-node.vue_vue_type_script_setup_true_lang.js +4 -4
  7. package/dist/components/default-node.vue_vue_type_script_setup_true_lang.js.map +1 -1
  8. package/dist/components/flow-comments.js +6 -0
  9. package/dist/components/flow-comments.js.map +1 -0
  10. package/dist/components/flow-comments.vue_vue_type_script_setup_true_lang.js +218 -0
  11. package/dist/components/flow-comments.vue_vue_type_script_setup_true_lang.js.map +1 -0
  12. package/dist/components/flow-port.js.map +1 -1
  13. package/dist/components/flow-port.vue_vue_type_script_setup_true_lang.js +7 -42
  14. package/dist/components/flow-port.vue_vue_type_script_setup_true_lang.js.map +1 -1
  15. package/dist/components/flow-toolbar.js.map +1 -1
  16. package/dist/components/flow-toolbar.vue_vue_type_script_setup_true_lang.js +300 -9
  17. package/dist/components/flow-toolbar.vue_vue_type_script_setup_true_lang.js.map +1 -1
  18. package/dist/components/node-view.js.map +1 -1
  19. package/dist/components/node-view.vue_vue_type_script_setup_true_lang.js +2 -2
  20. package/dist/components/node-view.vue_vue_type_script_setup_true_lang.js.map +1 -1
  21. package/dist/components/port-view.js +6 -0
  22. package/dist/components/port-view.js.map +1 -0
  23. package/dist/components/port-view.vue_vue_type_script_setup_true_lang.js +60 -0
  24. package/dist/components/port-view.vue_vue_type_script_setup_true_lang.js.map +1 -0
  25. package/dist/context.js.map +1 -1
  26. package/dist/core/extension.js.map +1 -1
  27. package/dist/core/history.js +26 -0
  28. package/dist/core/history.js.map +1 -1
  29. package/dist/core/model.js.map +1 -1
  30. package/dist/core/node-types.js +39 -1
  31. package/dist/core/node-types.js.map +1 -1
  32. package/dist/core/transaction.js +5 -4
  33. package/dist/core/transaction.js.map +1 -1
  34. package/dist/document.js +1 -1
  35. package/dist/export/color.js +49 -6
  36. package/dist/export/color.js.map +1 -1
  37. package/dist/export/context.js +16 -9
  38. package/dist/export/context.js.map +1 -1
  39. package/dist/export/draw.js +6 -5
  40. package/dist/export/draw.js.map +1 -1
  41. package/dist/export/render.js +78 -0
  42. package/dist/export/render.js.map +1 -0
  43. package/dist/flow-editor.js.map +1 -1
  44. package/dist/flow-editor.vue_vue_type_script_setup_true_lang.js +757 -129
  45. package/dist/flow-editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
  46. package/dist/index.js +5 -4
  47. package/dist/index.js.map +1 -1
  48. package/dist/kit.js +1 -1
  49. package/dist/locale.js +102 -3
  50. package/dist/locale.js.map +1 -1
  51. package/dist/style.css +1 -1
  52. package/dist/style.js +2 -1
  53. package/dist/types/collaboration/index.d.ts +32 -4
  54. package/dist/types/comments.d.ts +73 -0
  55. package/dist/types/components/flow-comments.vue.d.ts +35 -0
  56. package/dist/types/components/flow-port.vue.d.ts +8 -2
  57. package/dist/types/components/port-view.vue.d.ts +10 -0
  58. package/dist/types/components/port.d.ts +2 -2
  59. package/dist/types/context.d.ts +48 -1
  60. package/dist/types/core/extension.d.ts +9 -1
  61. package/dist/types/core/history.d.ts +10 -0
  62. package/dist/types/core/menu.d.ts +60 -0
  63. package/dist/types/core/model.d.ts +22 -0
  64. package/dist/types/core/node-types.d.ts +18 -2
  65. package/dist/types/core/transaction.d.ts +2 -1
  66. package/dist/types/export/color.d.ts +6 -1
  67. package/dist/types/export/render.d.ts +27 -0
  68. package/dist/types/flow-editor.vue.d.ts +11 -1
  69. package/dist/types/index.d.ts +36 -7
  70. package/dist/types/locale.d.ts +27 -1
  71. package/dist/types/whiteboard/board-node.vue.d.ts +5 -0
  72. package/dist/types/whiteboard/colors.d.ts +36 -0
  73. package/dist/types/whiteboard/index.d.ts +2 -2
  74. package/dist/types/whiteboard/model.d.ts +24 -14
  75. package/dist/types/whiteboard/state.d.ts +2 -0
  76. package/dist/types/whiteboard/toolbar.d.ts +46 -0
  77. package/dist/whiteboard/board-node.js.map +1 -1
  78. package/dist/whiteboard/board-node.vue_vue_type_script_setup_true_lang.js +76 -20
  79. package/dist/whiteboard/board-node.vue_vue_type_script_setup_true_lang.js.map +1 -1
  80. package/dist/whiteboard/colors.js +84 -0
  81. package/dist/whiteboard/colors.js.map +1 -0
  82. package/dist/whiteboard/connector.js +47 -13
  83. package/dist/whiteboard/connector.js.map +1 -1
  84. package/dist/whiteboard/draw.js +26 -9
  85. package/dist/whiteboard/draw.js.map +1 -1
  86. package/dist/whiteboard/index.js +2 -1
  87. package/dist/whiteboard/kit.js +65 -8
  88. package/dist/whiteboard/kit.js.map +1 -1
  89. package/dist/whiteboard/model.js +5 -31
  90. package/dist/whiteboard/model.js.map +1 -1
  91. package/dist/whiteboard/state.js +6 -1
  92. package/dist/whiteboard/state.js.map +1 -1
  93. package/dist/whiteboard/toolbar.js +296 -0
  94. package/dist/whiteboard/toolbar.js.map +1 -0
  95. package/dist/whiteboard/whiteboard-toolbar.js.map +1 -1
  96. package/dist/whiteboard/whiteboard-toolbar.vue_vue_type_script_setup_true_lang.js +14 -7
  97. package/dist/whiteboard/whiteboard-toolbar.vue_vue_type_script_setup_true_lang.js.map +1 -1
  98. package/package.json +3 -3
@@ -1,16 +1,54 @@
1
1
  // src/export/color.ts
2
2
  var normalizer;
3
- var SRGB = /^(#|rgba?\()/;
3
+ var HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
4
+ var LEGACY_RGB = /^rgba?\(\s*[\d.+%-]+\s*,\s*[\d.+%-]+\s*,\s*[\d.+%-]+(?:\s*,\s*[\d.+%-]+)?\s*\)$/i;
5
+ var MODERN_RGB = /^rgba?\(\s*(?:[\d.+%-]+|none)\s+(?:[\d.+%-]+|none)\s+(?:[\d.+%-]+|none)(?:\s*\/\s*(?:[\d.+%-]+|none))?\s*\)$/i;
6
+ var CSS_WIDE = /^(?:inherit|initial|unset|revert|revert-layer)$/i;
7
+ var SAFE_CHARS = /^[a-z0-9#(),.%/+\-\s]+$/i;
8
+ var UNSAFE_FUNC = /\b(?:url|expression)\s*\(/i;
9
+ var COLOR_FUNC = /^(?:hsla?|hwb|lab|lch|oklab|oklch|color|color-mix|light-dark)\((.*)\)$/i;
10
+ var VAR_FUNC = /^var\(\s*--[a-z0-9_-]+(?:\s*,.*)?\)$/i;
11
+ var NAMED_COLOR = /^[a-z]+$/i;
12
+ var SRGB = (value) => HEX.test(value) || LEGACY_RGB.test(value);
13
+ function hasBalancedParens(value) {
14
+ let depth = 0;
15
+ for (let i = 0; i < value.length; i++) {
16
+ const ch = value[i];
17
+ if (ch === "(") depth++;
18
+ else if (ch === ")") {
19
+ depth--;
20
+ if (depth < 0) return false;
21
+ if (depth === 0 && i !== value.length - 1) return false;
22
+ }
23
+ }
24
+ return depth === 0;
25
+ }
26
+ /**
27
+ * Whether `value` has safe CSS color syntax (no quotes, markup, CSS
28
+ * declarations, `url()`, or CSS-wide keywords like `inherit`).
29
+ */
30
+ function isSafeCssColor(value) {
31
+ const trimmed = value.trim();
32
+ if (!trimmed || trimmed.toLowerCase() === "none" || CSS_WIDE.test(trimmed)) return false;
33
+ if (!SAFE_CHARS.test(trimmed) || UNSAFE_FUNC.test(trimmed) || !hasBalancedParens(trimmed)) return false;
34
+ if (trimmed.startsWith("#")) return HEX.test(trimmed);
35
+ if (/^rgba?\(/i.test(trimmed)) return LEGACY_RGB.test(trimmed) || MODERN_RGB.test(trimmed);
36
+ if (VAR_FUNC.test(trimmed)) return true;
37
+ if (COLOR_FUNC.test(trimmed)) return true;
38
+ return NAMED_COLOR.test(trimmed);
39
+ }
4
40
  /**
5
41
  * A computed color as `rgb(…)`, `rgba(…)` or `#rrggbb`, which every SVG reader
6
42
  * understands. A canvas converts most colors as it parses them; colors it
7
43
  * keeps in another space (`oklab(…)`, `color(…)`) are painted on a pixel
8
- * and read back.
44
+ * and read back. Invalid or unsafe values return `''`.
9
45
  */
10
46
  function plainColor(color) {
11
47
  const value = color.trim();
12
- if (!value || value === "none" || SRGB.test(value)) return value;
13
- if (value === "transparent") return "rgba(0, 0, 0, 0)";
48
+ if (!value || value === "none") return value;
49
+ if (SRGB(value)) return value;
50
+ if (value.toLowerCase() === "transparent") return "rgba(0, 0, 0, 0)";
51
+ if (!isSafeCssColor(value)) return "";
14
52
  if (normalizer === void 0) try {
15
53
  const sheet = document.createElement("canvas");
16
54
  sheet.width = sheet.height = 1;
@@ -22,7 +60,12 @@ function plainColor(color) {
22
60
  normalizer.fillStyle = "#000";
23
61
  normalizer.fillStyle = value;
24
62
  const parsed = String(normalizer.fillStyle);
25
- if (SRGB.test(parsed)) return parsed;
63
+ if (parsed === "#000000") {
64
+ normalizer.fillStyle = "#fff";
65
+ normalizer.fillStyle = value;
66
+ if (String(normalizer.fillStyle) === "#ffffff") return "";
67
+ }
68
+ if (SRGB(parsed)) return parsed;
26
69
  normalizer.clearRect(0, 0, 1, 1);
27
70
  normalizer.fillRect(0, 0, 1, 1);
28
71
  const [r, g, b, a] = normalizer.getImageData(0, 0, 1, 1).data;
@@ -33,6 +76,6 @@ function plainColor(color) {
33
76
  ].map((n) => n.toString(16).padStart(2, "0")).join("")}`;
34
77
  return `rgba(${r}, ${g}, ${b}, ${Math.round(a / 255 * 1e3) / 1e3})`;
35
78
  }
36
- export { plainColor };
79
+ export { isSafeCssColor, plainColor };
37
80
 
38
81
  //# sourceMappingURL=color.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"color.js","names":[],"sources":["../../src/export/color.ts"],"sourcesContent":["let normalizer: CanvasRenderingContext2D | null | undefined\n\nconst SRGB = /^(#|rgba?\\()/\n\n/**\n * A computed color as `rgb(…)`, `rgba(…)` or `#rrggbb`, which every SVG reader\n * understands. A canvas converts most colors as it parses them; colors it\n * keeps in another space (`oklab(…)`, `color(…)`) are painted on a pixel\n * and read back.\n */\nexport function plainColor(color: string): string {\n const value = color.trim()\n if (!value || value === 'none' || SRGB.test(value)) return value\n if (value === 'transparent') return 'rgba(0, 0, 0, 0)'\n if (normalizer === undefined)\n try {\n const sheet = document.createElement('canvas')\n sheet.width = sheet.height = 1\n normalizer = sheet.getContext('2d', { willReadFrequently: true })\n } catch {\n normalizer = null\n }\n if (!normalizer) return value\n normalizer.fillStyle = '#000'\n normalizer.fillStyle = value\n const parsed = String(normalizer.fillStyle)\n if (SRGB.test(parsed)) return parsed\n normalizer.clearRect(0, 0, 1, 1)\n normalizer.fillRect(0, 0, 1, 1)\n const [r, g, b, a] = normalizer.getImageData(0, 0, 1, 1).data\n if (a === 255) return `#${[r, g, b].map((n) => n!.toString(16).padStart(2, '0')).join('')}`\n return `rgba(${r}, ${g}, ${b}, ${Math.round((a! / 255) * 1000) / 1000})`\n}\n"],"mappings":";AAAA,IAAI;AAEJ,IAAM,OAAO;;;;;;;AAQb,SAAgB,WAAW,OAAuB;CAChD,MAAM,QAAQ,MAAM,KAAK;CACzB,IAAI,CAAC,SAAS,UAAU,UAAU,KAAK,KAAK,KAAK,GAAG,OAAO;CAC3D,IAAI,UAAU,eAAe,OAAO;CACpC,IAAI,eAAe,KAAA,GACjB,IAAI;EACF,MAAM,QAAQ,SAAS,cAAc,QAAQ;EAC7C,MAAM,QAAQ,MAAM,SAAS;EAC7B,aAAa,MAAM,WAAW,MAAM,EAAE,oBAAoB,KAAK,CAAC;CAClE,QAAQ;EACN,aAAa;CACf;CACF,IAAI,CAAC,YAAY,OAAO;CACxB,WAAW,YAAY;CACvB,WAAW,YAAY;CACvB,MAAM,SAAS,OAAO,WAAW,SAAS;CAC1C,IAAI,KAAK,KAAK,MAAM,GAAG,OAAO;CAC9B,WAAW,UAAU,GAAG,GAAG,GAAG,CAAC;CAC/B,WAAW,SAAS,GAAG,GAAG,GAAG,CAAC;CAC9B,MAAM,CAAC,GAAG,GAAG,GAAG,KAAK,WAAW,aAAa,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC;CACzD,IAAI,MAAM,KAAK,OAAO,IAAI;EAAC;EAAG;EAAG;CAAC,CAAC,CAAC,KAAK,MAAM,EAAG,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;CACxF,OAAO,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,KAAK,MAAO,IAAK,MAAO,GAAI,IAAI,IAAK;AACxE"}
1
+ {"version":3,"file":"color.js","names":[],"sources":["../../src/export/color.ts"],"sourcesContent":["let normalizer: CanvasRenderingContext2D | null | undefined\n\nconst HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i\nconst LEGACY_RGB =\n /^rgba?\\(\\s*[\\d.+%-]+\\s*,\\s*[\\d.+%-]+\\s*,\\s*[\\d.+%-]+(?:\\s*,\\s*[\\d.+%-]+)?\\s*\\)$/i\nconst MODERN_RGB =\n /^rgba?\\(\\s*(?:[\\d.+%-]+|none)\\s+(?:[\\d.+%-]+|none)\\s+(?:[\\d.+%-]+|none)(?:\\s*\\/\\s*(?:[\\d.+%-]+|none))?\\s*\\)$/i\nconst CSS_WIDE = /^(?:inherit|initial|unset|revert|revert-layer)$/i\nconst SAFE_CHARS = /^[a-z0-9#(),.%/+\\-\\s]+$/i\nconst UNSAFE_FUNC = /\\b(?:url|expression)\\s*\\(/i\nconst COLOR_FUNC = /^(?:hsla?|hwb|lab|lch|oklab|oklch|color|color-mix|light-dark)\\((.*)\\)$/i\nconst VAR_FUNC = /^var\\(\\s*--[a-z0-9_-]+(?:\\s*,.*)?\\)$/i\nconst NAMED_COLOR = /^[a-z]+$/i\n\nconst SRGB = (value: string) => HEX.test(value) || LEGACY_RGB.test(value)\n\nfunction hasBalancedParens(value: string): boolean {\n let depth = 0\n for (let i = 0; i < value.length; i++) {\n const ch = value[i]\n if (ch === '(') depth++\n else if (ch === ')') {\n depth--\n if (depth < 0) return false\n if (depth === 0 && i !== value.length - 1) return false\n }\n }\n return depth === 0\n}\n\n/**\n * Whether `value` has safe CSS color syntax (no quotes, markup, CSS\n * declarations, `url()`, or CSS-wide keywords like `inherit`).\n */\nexport function isSafeCssColor(value: string): boolean {\n const trimmed = value.trim()\n if (!trimmed || trimmed.toLowerCase() === 'none' || CSS_WIDE.test(trimmed)) return false\n if (!SAFE_CHARS.test(trimmed) || UNSAFE_FUNC.test(trimmed) || !hasBalancedParens(trimmed))\n return false\n if (trimmed.startsWith('#')) return HEX.test(trimmed)\n if (/^rgba?\\(/i.test(trimmed)) return LEGACY_RGB.test(trimmed) || MODERN_RGB.test(trimmed)\n if (VAR_FUNC.test(trimmed)) return true\n if (COLOR_FUNC.test(trimmed)) return true\n return NAMED_COLOR.test(trimmed)\n}\n\n/**\n * A computed color as `rgb(…)`, `rgba(…)` or `#rrggbb`, which every SVG reader\n * understands. A canvas converts most colors as it parses them; colors it\n * keeps in another space (`oklab(…)`, `color(…)`) are painted on a pixel\n * and read back. Invalid or unsafe values return `''`.\n */\nexport function plainColor(color: string): string {\n const value = color.trim()\n if (!value || value === 'none') return value\n if (SRGB(value)) return value\n if (value.toLowerCase() === 'transparent') return 'rgba(0, 0, 0, 0)'\n if (!isSafeCssColor(value)) return ''\n if (normalizer === undefined)\n try {\n const sheet = document.createElement('canvas')\n sheet.width = sheet.height = 1\n normalizer = sheet.getContext('2d', { willReadFrequently: true })\n } catch {\n normalizer = null\n }\n if (!normalizer) return value\n normalizer.fillStyle = '#000'\n normalizer.fillStyle = value\n const parsed = String(normalizer.fillStyle)\n if (parsed === '#000000') {\n normalizer.fillStyle = '#fff'\n normalizer.fillStyle = value\n if (String(normalizer.fillStyle) === '#ffffff') return ''\n }\n if (SRGB(parsed)) return parsed\n normalizer.clearRect(0, 0, 1, 1)\n normalizer.fillRect(0, 0, 1, 1)\n const [r, g, b, a] = normalizer.getImageData(0, 0, 1, 1).data\n if (a === 255) return `#${[r, g, b].map((n) => n!.toString(16).pad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Q,OAAO;CACvC,IAAI,KAAK,KAAK,GAAG,OAAO;CACxB,IAAI,MAAM,YAAY,MAAM,eAAe,OAAO;CAClD,IAAI,CAAC,eAAe,KAAK,GAAG,OAAO;CACnC,IAAI,eAAe,KAAA,GACjB,IAAI;EACF,MAAM,QAAQ,SAAS,cAAc,QAAQ;EAC7C,MAAM,QAAQ,MAAM,SAAS;EAC7B,aAAa,MAAM,WAAW,MAAM,EAAE,oBAAoB,KAAK,CAAC;CAClE,QAAQ;EACN,aAAa;CACf;CACF,IAAI,CAAC,YAAY,OAAO;CACxB,WAAW,YAAY;CACvB,WAAW,YAAY;CACvB,MAAM,SAAS,OAAO,WAAW,SAAS;CAC1C,IAAI,WAAW,WAAW;EACxB,WAAW,YAAY;EACvB,WAAW,YAAY;EACvB,IAAI,OAAO,WAAW,SAAS,MAAM,WAAW,OAAO;CACzD;CACA,IAAI,KAAK,MAAM,GAAG,OAAO;CACzB,WAAW,UAAU,GAAG,GAAG,GAAG,CAAC;CAC/B,WAAW,SAAS,GAAG,GAAG,GAAG,CAAC;CAC9B,MAAM,CAAC,GAAG,GAAG,GAAG,KAAK,WAAW,aAAa,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC;CACzD,IAAI,MAAM,KAAK,OAAO,IAAI;EAAC;EAAG;EAAG;CAAC,CAAC,CAAC,KAAK,MAAM,EAAG,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;CACxF,OAAO,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,KAAK,MAAO,IAAK,MAAO,GAAI,IAAI,IAAK;AACxE"}
@@ -1,4 +1,4 @@
1
- import { plainColor } from "./color.js";
1
+ import { isSafeCssColor, plainColor } from "./color.js";
2
2
  import { h, render } from "vue";
3
3
  import { ImageOffIcon } from "@dou-ui/icons";
4
4
  // src/export/context.ts
@@ -88,12 +88,19 @@ function drawTools(root, messages, imageHref = (src) => src) {
88
88
  const swatch = document.createElement("div");
89
89
  box.append(swatch);
90
90
  const color = (value) => {
91
- let found = colors.get(value);
91
+ const trimmed = value.trim();
92
+ if (!trimmed) return "";
93
+ if (trimmed.toLowerCase() === "none") return "none";
94
+ let found = colors.get(trimmed);
92
95
  if (found === void 0) {
93
- swatch.style.color = "";
94
- swatch.style.color = value;
95
- found = plainColor(getComputedStyle(swatch).color || value);
96
- colors.set(value, found);
96
+ if (!isSafeCssColor(trimmed)) found = "";
97
+ else {
98
+ swatch.style.color = "";
99
+ swatch.style.color = trimmed;
100
+ const accepted = swatch.style.color;
101
+ found = accepted ? plainColor(getComputedStyle(swatch).color || accepted) : "";
102
+ }
103
+ colors.set(trimmed, found);
97
104
  }
98
105
  return found;
99
106
  };
@@ -146,7 +153,7 @@ function drawTools(root, messages, imageHref = (src) => src) {
146
153
  const x = align === "center" ? area.x + area.width / 2 : align === "end" ? area.x + area.width : area.x;
147
154
  const anchor = align === "center" ? "middle" : align === "end" ? "end" : "start";
148
155
  const shift = baselineOffset(size);
149
- const fill = options.color ? ` fill="${options.color}"` : "";
156
+ const fill = options.color ? ` fill="${escapeXml(options.color)}"` : "";
150
157
  const bold = weight === 400 || weight === "400" ? "" : ` font-weight="${weight}"`;
151
158
  const spans = lines.map((line, i) => line ? `<tspan x="${round(x)}" y="${round(top + lineHeight * i + lineHeight / 2 + shift)}">${escapeXml(line)}</tspan>` : "").join("");
152
159
  return spans ? `<text font-size="${round(size)}"${bold}${fill} text-anchor="${anchor}" xml:space="preserve">${spans}</text>` : "";
@@ -168,7 +175,7 @@ function drawTools(root, messages, imageHref = (src) => src) {
168
175
  if (!markup) return "";
169
176
  return markup.replace(/^<svg\b([^>]*)>/, (_, attrs) => {
170
177
  return `<svg${attrs.replace(/\s(width|height|x|y|class|style|aria-[\w-]+|role)="[^"]*"/g, "")} x="${round(area.x)}" y="${round(area.y)}" width="${round(area.width)}" height="${round(area.height)}">`;
171
- }).replace(/currentColor/g, fill);
178
+ }).replace(/currentColor/g, () => escapeXml(fill));
172
179
  };
173
180
  const images = /* @__PURE__ */ new Set();
174
181
  let clips = 0;
@@ -178,7 +185,7 @@ function drawTools(root, messages, imageHref = (src) => src) {
178
185
  const { x, y, width, height } = area;
179
186
  if (href === null) {
180
187
  const side = Math.min(24, width * .4, height * .4);
181
- return `<rect x="${round(x)}" y="${round(y)}" width="${round(width)}" height="${round(height)}" rx="${options.radius ?? 0}" fill="${color("var(--dou-color-bg-muted)")}"/>` + icon(ImageOffIcon, {
188
+ return `<rect x="${round(x)}" y="${round(y)}" width="${round(width)}" height="${round(height)}" rx="${options.radius ?? 0}" fill="${escapeXml(color("var(--dou-color-bg-muted)"))}"/>` + icon(ImageOffIcon, {
182
189
  x: x + (width - side) / 2,
183
190
  y: y + (height - side) / 2,
184
191
  width: side,
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","names":[],"sources":["../../src/export/context.ts"],"sourcesContent":["import { ImageOffIcon } from '@dou-ui/icons'\nimport { h, render, type Component } from 'vue'\nimport type { PortAnchor } from '../context'\nimport type { Rect } from '../core/model'\nimport type { FlowMessages } from '../locale'\nimport { plainColor } from './color'\n\nexport interface FlowDrawTextOptions {\n /** In px; the editor's font size by default. */\n size?: number\n /** A CSS font weight, e.g. `500`. */\n weight?: string | number\n /** Line height in px; 1.5 times the size by default. */\n lineHeight?: number\n color?: string\n align?: 'start' | 'center' | 'end'\n /** Where the lines sit in the box when they take less than its height. */\n valign?: 'top' | 'middle'\n /** Keeps it to one line, cut with an ellipsis. */\n nowrap?: boolean\n}\n\n/**\n * What a node type's `draw` gets to draw a node as SVG, for `exportSVG` and\n * `exportPNG`. Coordinates are the node's own: `0, 0` is its top left.\n */\nexport interface FlowDrawContext {\n /** The node's size. */\n width: number\n height: number\n /** Its ports where they are on screen, relative to its top left. */\n ports: ReadonlyMap<string, PortAnchor>\n /**\n * A port as the editor draws it, where it is on screen: its ring or shape\n * in its type's color, filled once connected. Empty for a port not shown.\n */\n port: (id: string) => string\n /** The editor's current strings. */\n messages: FlowMessages\n /**\n * The computed style of an element made with these classes, outermost\n * first, inside the editor so its theme and variables apply. Pass colors\n * read from it through `color`.\n */\n style: (...classes: string[]) => CSSStyleDeclaration\n /**\n * A CSS color, also one with variables such as `var(--dou-color-text)`,\n * as `rgb(…)`, `rgba(…)` or `#rrggbb`, which every SVG reader understands.\n */\n color: (value: string) => string\n /** Text in a box, wrapped as on screen and cut where the box ends. */\n text: (value: string, box: Rect, options?: FlowDrawTextOptions) => string\n /** An icon component, e.g. from `@dou-ui/icons`, as SVG. */\n icon: (icon: Component, box: Rect, color: string) => string\n /** An image; in a PNG it is embedded when its address can be read. */\n image: (src: string, box: Rect, options?: { radius?: number }) => string\n /** Escapes text for SVG markup. */\n escape: (text: string) => string\n}\n\nexport const escapeXml = (text: string) =>\n text\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n // control characters other than tab and new line aren't allowed in XML\n // oxlint-disable-next-line no-control-regex -- strips them\n .replace(/[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F]/g, '')\n\nexport const round = (value: number) => Math.round(value * 100) / 100\n\n/** Characters a line may break after, as CSS breaks Chinese, Japanese and Korean text. */\nconst WIDE = /[⺀-鿿가-힯豈-﫿︰-﹏＀-￯]/\nconst TOKENS = /[⺀-鿿가-힯豈-﫿︰-﹏＀-￯]|[^\\s⺀-鿿가-힯豈-﫿︰-﹏＀-￯]+\\s*|\\s+/g\n\n/**\n * Lines of text that fit `max`: breaks between words and between wide\n * characters, inside a word only when it alone is too long, and at new lines.\n */\nexport function wrapText(text: string, max: number, measure: (text: string) => number): string[] {\n const out: string[] = []\n const breakLong = (word: string) => {\n let line = ''\n for (const char of word) {\n if (line && measure(line + char) > max) {\n out.push(line)\n line = ''\n }\n line += char\n }\n return line\n }\n for (const paragraph of text.split('\\n')) {\n let line = ''\n for (const token of paragraph.match(TOKENS) ?? []) {\n const next = line + token\n if (!line.trim() || measure(next.trimEnd()) <= max) {\n line = next\n if (measure(line.trimEnd()) > max) line = breakLong(line.trimEnd())\n continue\n }\n out.push(line.trimEnd())\n line = WIDE.test(token) ? token : token.trimStart()\n if (measure(line.trimEnd()) > max) line = breakLong(line.trimEnd())\n }\n out.push(line.trimEnd())\n }\n return out\n}\n\n/** Cuts text to fit `max`, with an ellipsis. */\nexport function cutText(\n text: string,\n max: number,\n measure: (text: string) => number,\n /** Ends it with an ellipsis even when it fits: more text follows. */\n more = false,\n) {\n if (more) text = text.trimEnd()\n if (!more && measure(text) <= max) return text\n let lo = 0\n let hi = text.length\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1\n if (measure(`${text.slice(0, mid)}…`) <= max) lo = mid\n else hi = mid - 1\n }\n return lo ? `${text.slice(0, lo)}…` : ''\n}\n\nexport interface DrawTools {\n /** Makes the context for one node. */\n forNode: (\n size: { width: number; height: number },\n ports: ReadonlyMap<string, PortAnchor>,\n port: (id: string) => string,\n ) => FlowDrawContext\n style: FlowDrawContext['style']\n color: FlowDrawContext['color']\n text: FlowDrawContext['text']\n measure: (text: string, size: number, weight?: string | number) => number\n fontFamily: string\n fontSize: number\n /** Image addresses the drawing used. */\n images: Set<string>\n dispose: () => void\n}\n\n/**\n * The tools a drawing needs, reading the page inside `root`: styles from\n * elements made in a hidden box there, text measured with the editor's font.\n * `imageHref` turns an image address into the one written out.\n */\nexport function drawTools(\n root: HTMLElement,\n messages: FlowMessages,\n imageHref: (src: string) => string | null = (src) => src,\n): DrawTools {\n const box = document.createElement('div')\n box.setAttribute('aria-hidden', 'true')\n box.style.cssText =\n 'position:absolute;top:0;left:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none'\n root.append(box)\n const rootStyle = getComputedStyle(root)\n const fontFamily = rootStyle.fontFamily || 'sans-serif'\n const fontSize = Number.parseFloat(rootStyle.fontSize) || 14\n\n const styles = new Map<string, CSSStyleDeclaration>()\n const style = (...classes: string[]) => {\n const key = classes.join('\\n')\n let found = styles.get(key)\n if (!found) {\n let parent: HTMLElement = box\n for (const name of classes) {\n const el = document.createElement('div')\n el.className = name\n parent.append(el)\n parent = el\n }\n found = getComputedStyle(parent)\n styles.set(key, found)\n }\n return found\n }\n\n const colors = new Map<string, string>()\n const swatch = document.createElement('div')\n box.append(swatch)\n const color = (value: string) => {\n let found = colors.get(value)\n if (found === undefined) {\n swatch.style.color = ''\n swatch.style.color = value\n found = plainColor(getComputedStyle(swatch).color || value)\n colors.set(value, found)\n }\n return found\n }\n\n let pen: CanvasRenderingContext2D | null | undefined\n const widths = new Map<string, number>()\n const measure = (text: string, size: number, weight: string | number = 400) => {\n const font = `${weight} ${size}px ${fontFamily}`\n const key = `${font}\\n${text}`\n let width = widths.get(key)\n if (width !== undefined) return width\n if (pen === undefined)\n try {\n pen = document.createElement('canvas').getContext('2d')\n } catch {\n pen = null\n }\n if (pen) {\n pen.font = font\n width = pen.measureText(text).width\n } else {\n // without a canvas, e.g. in tests: wide characters are square, others half\n width = 0\n for (const char of text) width += WIDE.test(char) ? size : size * 0.55\n }\n widths.set(key, width)\n return width\n }\n\n /** Where the baseline goes to centre a line of `size` in its line box. */\n const baselineOffset = (size: number) => {\n if (pen) {\n pen.font = `400 ${size}px ${fontFamily}`\n const m = pen.measureText('中Hg')\n if (m.fontBoundingBoxAscent) return (m.fontBoundingBoxAscent - m.fontBoundingBoxDescent) / 2\n }\n return size * 0.35\n }\n\n const text: FlowDrawContext['text'] = (value, area, options = {}) => {\n if (!value) return ''\n const size = options.size ?? fontSize\n const weight = options.weight ?? 400\n const lineHeight = options.lineHeight ?? size * 1.5\n const width = (line: string) => measure(line, size, weight)\n let lines = options.nowrap\n ? [cutText(value.replace(/\\s+/g, ' '), area.width, width)]\n : wrapText(value, area.width, width)\n // whole lines that fit, as the box clips them on screen\n const room = Math.max(1, Math.floor((area.height + 0.5) / lineHeight))\n if (lines.length > room) {\n lines = lines.slice(0, room)\n lines[room - 1] = cutText(lines[room - 1]!, area.width, width, true)\n }\n const total = lines.length * lineHeight\n const top = options.valign === 'middle' ? area.y + (area.height - total) / 2 : area.y\n const align = options.align ?? 'start'\n const x =\n align === 'center' ? area.x + area.width / 2 : align === 'end' ? area.x + area.width : area.x\n const anchor = align === 'center' ? 'middle' : align === 'end' ? 'end' : 'start'\n const shift = baselineOffset(size)\n const fill = options.color ? ` fill=\"${options.color}\"` : ''\n const bold = weight === 400 || weight === '400' ? '' : ` font-weight=\"${weight}\"`\n const spans = lines\n .map((line, i) =>\n line\n ? `<tspan x=\"${round(x)}\" y=\"${round(top + lineHeight * i + lineHeight / 2 + shift)}\">${escapeXml(line)}</tspan>`\n : '',\n )\n .join('')\n return spans\n ? `<text font-size=\"${round(size)}\"${bold}${fill} text-anchor=\"${anchor}\" xml:space=\"preserve\">${spans}</text>`\n : ''\n }\n\n const holder = document.createElement('div')\n const icons = new Map<Component, string>()\n const icon: FlowDrawContext['icon'] = (component, area, fill) => {\n let markup = icons.get(component)\n if (markup === undefined) {\n try {\n render(h(component), holder)\n markup = holder.querySelector('svg')?.outerHTML ?? ''\n } catch {\n markup = ''\n }\n render(null, holder)\n icons.set(component, markup)\n }\n if (!markup) return ''\n const svg = markup\n .replace(/^<svg\\b([^>]*)>/, (_, attrs: string) => {\n const kept = attrs.replace(/\\s(width|height|x|y|class|style|aria-[\\w-]+|role)=\"[^\"]*\"/g, '')\n return `<svg${kept} x=\"${round(area.x)}\" y=\"${round(area.y)}\" width=\"${round(area.width)}\" height=\"${round(area.height)}\">`\n })\n .replace(/currentColor/g, fill)\n return svg\n }\n\n const images = new Set<string>()\n let clips = 0\n const image: FlowDrawContext['image'] = (src, area, options = {}) => {\n images.add(src)\n const href = imageHref(src)\n const { x, y, width, height } = area\n if (href === null) {\n // not readable here: a plain box with a sign, as the canvas shows it\n const side = Math.min(24, width * 0.4, height * 0.4)\n return (\n `<rect x=\"${round(x)}\" y=\"${round(y)}\" width=\"${round(width)}\" height=\"${round(height)}\" rx=\"${options.radius ?? 0}\" fill=\"${color('var(--dou-color-bg-muted)')}\"/>` +\n icon(\n ImageOffIcon,\n { x: x + (width - side) / 2, y: y + (height - side) / 2, width: side, height: side },\n color('var(--dou-color-text-tertiary)'),\n )\n )\n }\n let clip = ''\n let defs = ''\n if (options.radius) {\n const id = `dou-flow-clip-${++clips}`\n defs = `<clipPath id=\"${id}\"><rect x=\"${round(x)}\" y=\"${round(y)}\" width=\"${round(width)}\" height=\"${round(height)}\" rx=\"${options.radius}\"/></clipPath>`\n clip = ` clip-path=\"url(#${id})\"`\n }\n return `${defs}<image href=\"${escapeXml(href)}\" x=\"${round(x)}\" y=\"${round(y)}\" width=\"${round(width)}\" height=\"${round(height)}\" preserveAspectRatio=\"xMidYMid meet\"${clip}/>`\n }\n\n return {\n forNode: (size, ports, port) => ({\n width: size.width,\n height: size.height,\n ports,\n port,\n messages,\n style,\n color,\n text,\n icon,\n image,\n escape: escapeXml,\n }),\n style,\n color,\n text,\n measure,\n fontFamily,\n fontSize,\n images,\n dispose: () => box.remove(),\n }\n}\n"],"mappings":";;;;AA4DA,IAAa,aAAa,SACxB,KACG,QAAQ,MAAM,OAAO,CAAC,CACtB,QAAQ,MAAM,MAAM,CAAC,CACrB,QAAQ,MAAM,MAAM,CAAC,CACrB,QAAQ,MAAM,QAAQ,CAAC,CAGvB,QAAQ,6CAA6C,EAAE;AAE5D,IAAa,SAAS,UAAkB,KAAK,MAAM,QAAQ,GAAG,IAAI;;AAGlE,IAAM,OAAO;AACb,IAAM,SAAS;;;;;AAMf,SAAgB,SAAS,MAAc,KAAa,SAA6C;CAC/F,MAAM,MAAgB,CAAC;CACvB,MAAM,aAAa,SAAiB;EAClC,IAAI,OAAO;EACX,KAAK,MAAM,QAAQ,MAAM;GACvB,IAAI,QAAQ,QAAQ,OAAO,IAAI,IAAI,KAAK;IACtC,IAAI,KAAK,IAAI;IACb,OAAO;GACT;GACA,QAAQ;EACV;EACA,OAAO;CACT;CACA,KAAK,MAAM,aAAa,KAAK,MAAM,IAAI,GAAG;EACxC,IAAI,OAAO;E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WAAW;EAChC,IAAI,SAAS,MAAM;GAEjB,MAAM,OAAO,KAAK,IAAI,IAAI,QAAQ,IAAK,SAAS,EAAG;GACnD,OACE,YAAY,MAAM,CAAC,EAAE,OAAO,MAAM,CAAC,EAAE,WAAW,MAAM,KAAK,EAAE,YAAY,MAAM,MAAM,EAAE,QAAQ,QAAQ,UAAU,EAAE,UAAU,MAAM,2BAA2B,EAAE,OAChK,KACE,cACA;IAAE,GAAG,KAAK,QAAQ,QAAQ;IAAG,GAAG,KAAK,SAAS,QAAQ;IAAG,OAAO;IAAM,QAAQ;GAAK,GACnF,MAAM,gCAAgC,CACxC;EAEJ;EACA,IAAI,OAAO;EACX,IAAI,OAAO;EACX,IAAI,QAAQ,QAAQ;GAClB,MAAM,KAAK,iBAAiB,EAAE;GAC9B,OAAO,iBAAiB,GAAG,aAAa,MAAM,CAAC,EAAE,OAAO,MAAM,CAAC,EAAE,WAAW,MAAM,KAAK,EAAE,YAAY,MAAM,MAAM,EAAE,QAAQ,QAAQ,OAAO;GAC1I,OAAO,oBAAoB,GAAG;EAChC;EACA,OAAO,GAAG,KAAK,eAAe,UAAU,IAAI,EAAE,OAAO,MAAM,CAAC,EAAE,OAAO,MAAM,CAAC,EAAE,WAAW,MAAM,KAAK,EAAE,YAAY,MAAM,MAAM,EAAE,uCAAuC,KAAK;CAC9K;CAEA,OAAO;EACL,UAAU,MAAM,OAAO,UAAU;GAC/B,OAAO,KAAK;GACZ,QAAQ,KAAK;GACb;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,QAAQ;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,eAAe,IAAI,OAAO;CAC5B;AACF"}
1
+ {"version":3,"file":"context.js","names":[],"sources":["../../src/export/context.ts"],"sourcesContent":["import { ImageOffIcon } from '@dou-ui/icons'\nimport { h, render, type Component } from 'vue'\nimport type { PortAnchor } from '../context'\nimport type { Rect } from '../core/model'\nimport type { FlowMessages } from '../locale'\nimport { isSafeCssColor, plainColor } from './color'\n\nexport interface FlowDrawTextOptions {\n /** In px; the editor's font size by default. */\n size?: number\n /** A CSS font weight, e.g. `500`. */\n weight?: string | number\n /** Line height in px; 1.5 times the size by default. */\n lineHeight?: number\n color?: string\n align?: 'start' | 'center' | 'end'\n /** Where the lines sit in the box when they take less than its height. */\n valign?: 'top' | 'middle'\n /** Keeps it to one line, cut with an ellipsis. */\n nowrap?: boolean\n}\n\n/**\n * What a node type's `draw` gets to draw a node as SVG, for `exportSVG` and\n * `exportPNG`. Coordinates are the node's own: `0, 0` is its top left.\n */\nexport interface FlowDrawContext {\n /** The node's size. */\n width: number\n height: number\n /** Its ports where they are on screen, relative to its top left. */\n ports: ReadonlyMap<string, PortAnchor>\n /**\n * A port as the editor draws it, where it is on screen: its ring or shape\n * in its type's color, filled once connected. Empty for a port not shown.\n */\n port: (id: string) => string\n /** The editor's current strings. */\n messages: FlowMessages\n /**\n * The computed style of an element made with these classes, outermost\n * first, inside the editor so its theme and variables apply. Pass colors\n * read from it through `color`.\n */\n style: (...classes: string[]) => CSSStyleDeclaration\n /**\n * A CSS color, also one with variables such as `var(--dou-color-text)`,\n * as `rgb(…)`, `rgba(…)` or `#rrggbb`, which every SVG reader understands.\n */\n color: (value: string) => string\n /** Text in a box, wrapped as on screen and cut where the box ends. */\n text: (value: string, box: Rect, options?: FlowDrawTextOptions) => string\n /** An icon component, e.g. from `@dou-ui/icons`, as SVG. */\n icon: (icon: Component, box: Rect, color: string) => string\n /** An image; in a PNG it is embedded when its address can be read. */\n image: (src: string, box: Rect, options?: { radius?: number }) => string\n /** Escapes text for SVG markup. */\n escape: (text: string) => string\n}\n\nexport const escapeXml = (text: string) =>\n text\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n // control characters other than tab and new line aren't allowed in XML\n // oxlint-disable-next-line no-control-regex -- strips them\n .replace(/[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F]/g, '')\n\nexport const round = (value: number) => Math.round(value * 100) / 100\n\n/** Characters a line may break after, as CSS breaks Chinese, Japanese and Korean text. */\nconst WIDE = /[⺀-鿿가-힯豈-﫿︰-﹏＀-￯]/\nconst TOKENS = /[⺀-鿿가-힯豈-﫿︰-﹏＀-￯]|[^\\s⺀-鿿가-힯豈-﫿︰-﹏＀-￯]+\\s*|\\s+/g\n\n/**\n * Lines of text that fit `max`: breaks between words and between wide\n * characters, inside a word only when it alone is too long, and at new lines.\n */\nexport function wrapText(text: string, max: number, measure: (text: string) => number): string[] {\n const out: string[] = []\n const breakLong = (word: string) => {\n let line = ''\n for (const char of word) {\n if (line && measure(line + char) > max) {\n out.push(line)\n line = ''\n }\n line += char\n }\n return line\n }\n for (const paragraph of text.split('\\n')) {\n let line = ''\n for (const token of paragraph.match(TOKENS) ?? []) {\n const next = line + token\n if (!line.trim() || measure(next.trimEnd()) <= max) {\n line = next\n if (measure(line.trimEnd()) > max) line = breakLong(line.trimEnd())\n continue\n }\n out.push(line.trimEnd())\n line = WIDE.test(token) ? token : token.trimStart()\n if (measure(line.trimEnd()) > max) line = breakLong(line.trimEnd())\n }\n out.push(line.trimEnd())\n }\n return out\n}\n\n/** Cuts text to fit `max`, with an ellipsis. */\nexport function cutText(\n text: string,\n max: number,\n measure: (text: string) => number,\n /** Ends it with an ellipsis even when it fits: more text follows. */\n more = false,\n) {\n if (more) text = text.trimEnd()\n if (!more && measure(text) <= max) return text\n let lo = 0\n let hi = text.length\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1\n if (measure(`${text.slice(0, mid)}…`) <= max) lo = mid\n else hi = mid - 1\n }\n return lo ? `${text.slice(0, lo)}…` : ''\n}\n\nexport interface DrawTools {\n /** Makes the context for one node. */\n forNode: (\n size: { width: number; height: number },\n ports: ReadonlyMap<string, PortAnchor>,\n port: (id: string) => string,\n ) => FlowDrawContext\n style: FlowDrawContext['style']\n color: FlowDrawContext['color']\n text: FlowDrawContext['text']\n measure: (text: string, size: number, weight?: string | number) => number\n fontFamily: string\n fontSize: number\n /** Image addresses the drawing used. */\n images: Set<string>\n dispose: () => void\n}\n\n/**\n * The tools a drawing needs, reading the page inside `root`: styles from\n * elements made in a hidden box there, text measured with the editor's font.\n * `imageHref` turns an image address into the one written out.\n */\nexport function drawTools(\n root: HTMLElement,\n messages: FlowMessages,\n imageHref: (src: string) => string | null = (src) => src,\n): DrawTools {\n const box = document.createElement('div')\n box.setAttribute('aria-hidden', 'true')\n box.style.cssText =\n 'position:absolute;top:0;left:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none'\n root.append(box)\n const rootStyle = getComputedStyle(root)\n const fontFamily = rootStyle.fontFamily || 'sans-serif'\n const fontSize = Number.parseFloat(rootStyle.fontSize) || 14\n\n const styles = new Map<string, CSSStyleDeclaration>()\n const style = (...classes: string[]) => {\n const key = classes.join('\\n')\n let found = styles.get(key)\n if (!found) {\n let parent: HTMLElement = box\n for (const name of classes) {\n const el = document.createElement('div')\n el.className = name\n parent.append(el)\n parent = el\n }\n found = getComputedStyle(parent)\n styles.set(key, found)\n }\n return found\n }\n\n const colors = new Map<string, string>()\n const swatch = document.createElement('div')\n box.append(swatch)\n const color = (value: string) => {\n const trimmed = value.trim()\n if (!trimmed) return ''\n if (trimmed.toLowerCase() === 'none') return 'none'\n let found = colors.get(trimmed)\n if (found === undefined) {\n if (!isSafeCssColor(trimmed)) {\n found = ''\n } else {\n swatch.style.color = ''\n swatch.style.color = trimmed\n const accepted = swatch.style.color\n found = accepted ? plainColor(getComputedStyle(swatch).color || accepted) : ''\n }\n colors.set(trimmed, found)\n }\n return found\n }\n\n let pen: CanvasRenderingContext2D | null | undefined\n const widths = new Map<string, number>()\n const measure = (text: string, size: number, weight: string | number = 400) => {\n const font = `${weight} ${size}px ${fontFamily}`\n const key = `${font}\\n${text}`\n let width = widths.get(key)\n if (width !== undefined) return width\n if (pen === undefined)\n try {\n pen = document.createElement('canvas').getContext('2d')\n } catch {\n pen = null\n }\n if (pen) {\n pen.font = font\n width = pen.measureText(text).width\n } else {\n // without a canvas, e.g. in tests: wide characters are square, others half\n width = 0\n for (const char of text) width += WIDE.test(char) ? size : size * 0.55\n }\n widths.set(key, width)\n return width\n }\n\n /** Where the baseline goes to centre a line of `size` in its line box. */\n const baselineOffset = (size: number) => {\n if (pen) {\n pen.font = `400 ${size}px ${fontFamily}`\n const m = pen.measureText('中Hg')\n if (m.fontBoundingBoxAscent) return (m.fontBoundingBoxAscent - m.fontBoundingBoxDescent) / 2\n }\n return size * 0.35\n }\n\n const text: FlowDrawContext['text'] = (value, area, options = {}) => {\n if (!value) return ''\n const size = options.size ?? fontSize\n const weight = options.weight ?? 400\n const lineHeight = options.lineHeight ?? size * 1.5\n const width = (line: string) => measure(line, size, weight)\n let lines = options.nowrap\n ? [cutText(value.replace(/\\s+/g, ' '), area.width, width)]\n : wrapText(value, area.width, width)\n // whole lines that fit, as the box clips them on screen\n const room = Math.max(1, Math.floor((area.height + 0.5) / lineHeight))\n if (lines.length > room) {\n lines = lines.slice(0, room)\n lines[room - 1] = cutText(lines[room - 1]!, area.width, width, true)\n }\n const total = lines.length * lineHeight\n const top = options.valign === 'middle' ? area.y + (area.height - total) / 2 : area.y\n const align = options.align ?? 'start'\n const x =\n align === 'center' ? area.x + area.width / 2 : align === 'end' ? area.x + area.width : area.x\n const anchor = align === 'center' ? 'middle' : align === 'end' ? 'end' : 'start'\n const shift = baselineOffset(size)\n const fill = options.color ? ` fill=\"${escapeXml(options.color)}\"` : ''\n const bold = weight === 400 || weight === '400' ? '' : ` font-weight=\"${weight}\"`\n const spans = lines\n .map((line, i) =>\n line\n ? `<tspan x=\"${round(x)}\" y=\"${round(top + lineHeight * i + lineHeight / 2 + shift)}\">${escapeXml(line)}</tspan>`\n : '',\n )\n .join('')\n return spans\n ? `<text font-size=\"${round(size)}\"${bold}${fill} text-anchor=\"${anchor}\" xml:space=\"preserve\">${spans}</text>`\n : ''\n }\n\n const holder = document.createElement('div')\n const icons = new Map<Component, string>()\n const icon: FlowDrawContext['icon'] = (component, area, fill) => {\n let markup = icons.get(component)\n if (markup === undefined) {\n try {\n render(h(component), holder)\n markup = holder.querySelector('svg')?.outerHTML ?? ''\n } catch {\n markup = ''\n }\n render(null, holder)\n icons.set(component, markup)\n }\n if (!markup) return ''\n const svg = markup\n .replace(/^<svg\\b([^>]*)>/, (_, attrs: string) => {\n const kept = attrs.replace(/\\s(width|height|x|y|class|style|aria-[\\w-]+|role)=\"[^\"]*\"/g, '')\n return `<svg${kept} x=\"${round(area.x)}\" y=\"${round(area.y)}\" width=\"${round(area.width)}\" height=\"${round(area.height)}\">`\n })\n .replace(/currentColor/g, () => escapeXml(fill))\n return svg\n }\n\n const images = new Set<string>()\n let clips = 0\n const image: FlowDrawContext['image'] = (src, area, options = {}) => {\n images.add(src)\n const href = imageHref(src)\n const { x, y, width, height } = area\n if (href === null) {\n // not readable here: a plain box with a sign, as the canvas shows it\n const side = Math.min(24, width * 0.4, height * 0.4)\n return (\n `<rect x=\"${round(x)}\" y=\"${round(y)}\" width=\"${round(width)}\" height=\"${round(height)}\" rx=\"${options.radius ?? 0}\" fill=\"${escapeXml(color('var(--dou-color-bg-muted)'))}\"/>` +\n icon(\n ImageOffIcon,\n { x: x + (width - side) / 2, y: y + (height - side) / 2, width: side, height: side },\n color('var(--dou-color-text-tertiary)'),\n )\n )\n }\n let clip = ''\n let defs = ''\n if (options.radius) {\n const id = `dou-flow-clip-${++clips}`\n defs = `<clipPath id=\"${id}\"><rect x=\"${round(x)}\" y=\"${round(y)}\" width=\"${round(width)}\" height=\"${round(height)}\" rx=\"${options.radius}\"/></clipPath>`\n clip = ` clip-path=\"url(#${id})\"`\n }\n return `${defs}<image href=\"${escapeXml(href)}\" x=\"${round(x)}\" y=\"${round(y)}\" width=\"${round(width)}\" height=\"${round(height)}\" preserveAspectRatio=\"xMidYMid meet\"${clip}/>`\n }\n\n return {\n forNode: (size, ports, port) => ({\n width: size.width,\n height: size.height,\n ports,\n port,\n messages,\n style,\n color,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IAAE,GAAG,KAAK,QAAQ,QAAQ;IAAG,GAAG,KAAK,SAAS,QAAQ;IAAG,OAAO;IAAM,QAAQ;GAAK,GACnF,MAAM,gCAAgC,CACxC;EAEJ;EACA,IAAI,OAAO;EACX,IAAI,OAAO;EACX,IAAI,QAAQ,QAAQ;GAClB,MAAM,KAAK,iBAAiB,EAAE;GAC9B,OAAO,iBAAiB,GAAG,aAAa,MAAM,CAAC,EAAE,OAAO,MAAM,CAAC,EAAE,WAAW,MAAM,KAAK,EAAE,YAAY,MAAM,MAAM,EAAE,QAAQ,QAAQ,OAAO;GAC1I,OAAO,oBAAoB,GAAG;EAChC;EACA,OAAO,GAAG,KAAK,eAAe,UAAU,IAAI,EAAE,OAAO,MAAM,CAAC,EAAE,OAAO,MAAM,CAAC,EAAE,WAAW,MAAM,KAAK,EAAE,YAAY,MAAM,MAAM,EAAE,uCAAuC,KAAK;CAC9K;CAEA,OAAO;EACL,UAAU,MAAM,OAAO,UAAU;GAC/B,OAAO,KAAK;GACZ,QAAQ,KAAK;GACb;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,QAAQ;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,eAAe,IAAI,OAAO;CAC5B;AACF"}
@@ -44,7 +44,7 @@ function drawCard(draw, classes = []) {
44
44
  const border = px(s.borderTopWidth, 1);
45
45
  const radius = px(s.borderTopLeftRadius, 8);
46
46
  const inset = border / 2;
47
- return `<rect x="${inset}" y="${inset}" width="${round(Math.max(0, draw.width - border))}" height="${round(Math.max(0, draw.height - border))}" rx="${round(Math.max(0, radius - inset))}" fill="${draw.color(s.backgroundColor)}" stroke="${draw.color(s.borderTopColor)}" stroke-width="${border}"/>`;
47
+ return `<rect x="${inset}" y="${inset}" width="${round(Math.max(0, draw.width - border))}" height="${round(Math.max(0, draw.height - border))}" rx="${round(Math.max(0, radius - inset))}" fill="${draw.escape(draw.color(s.backgroundColor))}" stroke="${draw.escape(draw.color(s.borderTopColor))}" stroke-width="${border}"/>`;
48
48
  }
49
49
  /** What a node type without `draw` is drawn as: its card, its name and its ports. */
50
50
  function drawFallback(draw, label, framed) {
@@ -98,7 +98,8 @@ function edgeLook(tools, root) {
98
98
  const s = getComputedStyle(path);
99
99
  const dash = s.strokeDasharray && s.strokeDasharray !== "none" ? s.strokeDasharray : "";
100
100
  const width = px(s.strokeWidth, 1);
101
- found = `fill="none" stroke="${tools.color(s.stroke || "var(--dou-flow-editor-edge)")}" stroke-width="${round(width)}"` + (dash ? ` stroke-dasharray="${dash.replace(/px/g, "").replace(/,\s*/g, " ")}"` : "") + (s.strokeLinecap && s.strokeLinecap !== "butt" ? ` stroke-linecap="${s.strokeLinecap}"` : "") + (s.strokeLinejoin && s.strokeLinejoin !== "miter" ? ` stroke-linejoin="${s.strokeLinejoin}"` : "");
101
+ const stroke = (s.stroke && s.stroke !== "none" ? tools.color(s.stroke) : "") || (item.stale ? tools.color("var(--dou-color-danger)") : "") || (style?.stroke ? tools.color(style.stroke) : "") || (style?.["--dou-flow-connector-color"] ? tools.color(style["--dou-flow-connector-color"]) : "") || tools.color("var(--dou-flow-editor-edge)");
102
+ found = `fill="none" stroke="${escapeXml(stroke)}" stroke-width="${round(width)}"` + (dash ? ` stroke-dasharray="${dash.replace(/px/g, "").replace(/,\s*/g, " ")}"` : "") + (s.strokeLinecap && s.strokeLinecap !== "butt" ? ` stroke-linecap="${s.strokeLinecap}"` : "") + (s.strokeLinejoin && s.strokeLinejoin !== "miter" ? ` stroke-linejoin="${s.strokeLinejoin}"` : "");
102
103
  looks.set(key, found);
103
104
  }
104
105
  return found;
@@ -120,7 +121,7 @@ function drawLabel(tools, text, at) {
120
121
  const y = at.y - height / 2;
121
122
  const radius = px(s.borderTopLeftRadius, 6);
122
123
  return {
123
- markup: `<rect x="${round(x + border / 2)}" y="${round(y + border / 2)}" width="${round(width - border)}" height="${round(height - border)}" rx="${round(radius)}" fill="${tools.color(s.backgroundColor)}" stroke="${tools.color(s.borderTopColor)}" stroke-width="${border}"/>` + tools.text(text, {
124
+ markup: `<rect x="${round(x + border / 2)}" y="${round(y + border / 2)}" width="${round(width - border)}" height="${round(height - border)}" rx="${round(radius)}" fill="${escapeXml(tools.color(s.backgroundColor))}" stroke="${escapeXml(tools.color(s.borderTopColor))}" stroke-width="${border}"/>` + tools.text(text, {
124
125
  x: x + border + padding,
125
126
  y,
126
127
  width: width - (border + padding) * 2,
@@ -219,9 +220,9 @@ function drawFlow(input, tools, root) {
219
220
  }
220
221
  }
221
222
  const rootStyle = getComputedStyle(root);
222
- const background = input.background ? `<rect x="${x}" y="${y}" width="${width}" height="${height}" fill="${tools.color(rootStyle.backgroundColor || "var(--dou-color-bg-canvas)")}"/>` : "";
223
+ const background = input.background ? `<rect x="${x}" y="${y}" width="${width}" height="${height}" fill="${escapeXml(tools.color(rootStyle.backgroundColor || "var(--dou-color-bg-canvas)"))}"/>` : "";
223
224
  return {
224
- svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="${x} ${y} ${width} ${height}" font-family="${escapeXml(tools.fontFamily)}" font-size="${round(tools.fontSize)}" fill="${tools.color("var(--dou-color-text)")}">` + background + containerParts.join("") + edgeParts.join("") + labelParts.join("") + nodeParts.join("") + layerParts.join("") + "</svg>",
225
+ svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="${x} ${y} ${width} ${height}" font-family="${escapeXml(tools.fontFamily)}" font-size="${round(tools.fontSize)}" fill="${escapeXml(tools.color("var(--dou-color-text)"))}">` + background + containerParts.join("") + edgeParts.join("") + labelParts.join("") + nodeParts.join("") + layerParts.join("") + "</svg>",
225
226
  width,
226
227
  height
227
228
  };
@@ -1 +1 @@
1
- {"version":3,"file":"draw.js","names":[],"sources":["../../src/export/draw.ts"],"sourcesContent":["import type { CSSProperties } from 'vue'\nimport type { PortAnchor } from '../context'\nimport type { EdgeRoute } from '../core/edge-types'\nimport type { FlowEdge, FlowNode, Rect } from '../core/model'\nimport { nodeBounds, type NodeTypeSpec } from '../core/node-types'\nimport { escapeXml, round, type DrawTools, type FlowDrawContext } from './context'\n\nexport interface FlowExportOptions {\n /**\n * `all` (the default): every node and edge. `view`: what is in view now,\n * at the canvas's size, cut at its edges. `selection`: the selected nodes,\n * what is inside selected groups, and the edges between them; it throws\n * when nothing is selected.\n */\n range?: 'all' | 'view' | 'selection'\n /** Room around the drawing, in px. Defaults to `24`; not used by `view`. */\n padding?: number\n /** Fills the canvas color behind it. Defaults to `true`; `false` leaves it see-through. */\n background?: boolean\n}\n\nexport interface FlowImageOptions extends FlowExportOptions {\n /** Pixels per CSS pixel. Defaults to `2`, sharp on most screens and in print. */\n pixelRatio?: number\n}\n\nexport interface DrawNode {\n node: FlowNode\n spec: NodeTypeSpec\n rect: Rect\n ports: ReadonlyMap<string, PortAnchor>\n container: boolean\n label: string\n /** Draws one of its ports, as `FlowDrawContext.port`. */\n port: (id: string) => string\n}\n\nexport interface DrawEdge {\n edge: FlowEdge\n type: string\n route: EdgeRoute\n style?: CSSProperties\n stale: boolean\n}\n\nexport interface DrawInput {\n /** Containers outer first, then the other nodes lowest first. */\n nodes: DrawNode[]\n edges: DrawEdge[]\n padding: number\n background: boolean\n /** The area to draw, in place of what the drawing covers plus `padding`. */\n frame?: Rect\n /** Extensions' layers over the nodes, as `FlowExtension.drawLayer`. */\n layers?: ((draw: FlowDrawContext) => string)[]\n}\n\n/** The points a path passes through or bends towards; the curve stays inside them. */\nexport function pathPoints(path: string) {\n const numbers = path.match(/-?\\d*\\.?\\d+(?:e[-+]?\\d+)?/gi)?.map(Number) ?? []\n const out: { x: number; y: number }[] = []\n for (let i = 0; i + 1 < numbers.length; i += 2) out.push({ x: numbers[i]!, y: numbers[i + 1]! })\n return out\n}\n\n/** A box that grows to hold what is added. */\nfunction extent() {\n let minX = Infinity\n let minY = Infinity\n let maxX = -Infinity\n let maxY = -Infinity\n return {\n add(rect: Rect) {\n minX = Math.min(minX, rect.x)\n minY = Math.min(minY, rect.y)\n maxX = Math.max(maxX, rect.x + rect.width)\n maxY = Math.max(maxY, rect.y + rect.height)\n },\n get(): Rect | null {\n return minX === Infinity\n ? null\n : { x: minX, y: minY, width: maxX - minX, height: maxY - minY }\n },\n }\n}\n\nconst px = (value: string, fallback = 0) => {\n const n = Number.parseFloat(value)\n return Number.isFinite(n) ? n : fallback\n}\n\n/** A card like the editor's frame: border, background and radius. */\nexport function drawCard(draw: FlowDrawContext, classes: string[] = []): string {\n const s = draw.style(['dou-flow-editor__node', ...classes].join(' '))\n const border = px(s.borderTopWidth, 1)\n const radius = px(s.borderTopLeftRadius, 8)\n const inset = border / 2\n return `<rect x=\"${inset}\" y=\"${inset}\" width=\"${round(Math.max(0, draw.width - border))}\" height=\"${round(Math.max(0, draw.height - border))}\" rx=\"${round(Math.max(0, radius - inset))}\" fill=\"${draw.color(s.backgroundColor)}\" stroke=\"${draw.color(s.borderTopColor)}\" stroke-width=\"${border}\"/>`\n}\n\n/** What a node type without `draw` is drawn as: its card, its name and its ports. */\nexport function drawFallback(draw: FlowDrawContext, label: string, framed: boolean): string {\n const parts = framed ? [drawCard(draw)] : []\n for (const id of draw.ports.keys()) parts.push(draw.port(id))\n parts.push(\n draw.text(\n label,\n { x: 12, y: 0, width: Math.max(0, draw.width - 24), height: draw.height },\n { align: 'center', valign: 'middle', color: draw.color('var(--dou-color-text)') },\n ),\n )\n return parts.join('')\n}\n\n/** The edges' look, read from paths made like the editor's. */\nfunction edgeLook(tools: DrawTools, root: HTMLElement) {\n const NS = 'http://www.w3.org/2000/svg'\n const svg = document.createElementNS(NS, 'svg')\n svg.setAttribute('class', 'dou-flow-editor__edges')\n svg.style.cssText = 'position:absolute;visibility:hidden;pointer-events:none'\n root.append(svg)\n const looks = new Map<string, string>()\n return {\n of(item: DrawEdge) {\n const style = item.style as Record<string, string | undefined> | undefined\n const key = [item.type, item.stale, item.edge.animated, JSON.stringify(style ?? {})].join('|')\n let found = looks.get(key)\n if (found === undefined) {\n const g = document.createElementNS(NS, 'g')\n g.setAttribute('data-edge-type', item.type)\n const path = document.createElementNS(NS, 'path')\n const classes = ['dou-flow-editor__edge']\n if (item.stale) classes.push('is-stale')\n if (item.edge.animated) classes.push('is-animated')\n path.setAttribute('class', classes.join(' '))\n for (const [name, value] of Object.entries(style ?? {})) {\n if (value === undefined) continue\n if (name.startsWith('--')) path.style.setProperty(name, value)\n else\n path.style.setProperty(\n name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`),\n value,\n )\n }\n g.append(path)\n svg.append(g)\n const s = getComputedStyle(path)\n const dash = s.strokeDasharray && s.strokeDasharray !== 'none' ? s.strokeDasharray : ''\n const width = px(s.strokeWidth, 1)\n found =\n `fill=\"none\" stroke=\"${tools.color(s.stroke || 'var(--dou-flow-editor-edge)')}\" stroke-width=\"${round(width)}\"` +\n (dash ? ` stroke-dasharray=\"${dash.replace(/px/g, '').replace(/,\\s*/g, ' ')}\"` : '') +\n (s.strokeLinecap && s.strokeLinecap !== 'butt'\n ? ` stroke-linecap=\"${s.strokeLinecap}\"`\n : '') +\n (s.strokeLinejoin && s.strokeLinejoin !== 'miter'\n ? ` stroke-linejoin=\"${s.strokeLinejoin}\"`\n : '')\n looks.set(key, found)\n }\n return found\n },\n dispose: () => svg.remove(),\n }\n}\n\n/** An edge's label: a pill with its text, as on screen. */\nfunction drawLabel(tools: DrawTools, text: string, at: { x: number; y: number }) {\n const s = tools.style('dou-flow-editor__label')\n const size = px(s.fontSize, 12)\n const padding = px(s.paddingLeft, 6)\n const border = px(s.borderTopWidth, 1)\n const height = px(s.lineHeight, 20) + border * 2\n const max = px(s.maxWidth, 200)\n const textWidth = Math.min(tools.measure(text, size), max - padding * 2 - border * 2)\n const width = Math.ceil(textWidth + padding * 2 + border * 2)\n const x = at.x - width / 2\n const y = at.y - height / 2\n const radius = px(s.borderTopLeftRadius, 6)\n const markup =\n `<rect x=\"${round(x + border / 2)}\" y=\"${round(y + border / 2)}\" width=\"${round(width - border)}\" height=\"${round(height - border)}\" rx=\"${round(radius)}\" fill=\"${tools.color(s.backgroundColor)}\" stroke=\"${tools.color(s.borderTopColor)}\" stroke-width=\"${border}\"/>` +\n tools.text(\n text,\n { x: x + border + padding, y, width: width - (border + padding) * 2, height },\n { size, lineHeight: height, color: tools.color(s.color), align: 'center', nowrap: true },\n )\n return { markup, box: { x, y, width, height } }\n}\n\n/**\n * The flow as an SVG document: containers, edges, edge labels, then the\n * other nodes, as the editor stacks them.\n */\nexport function drawFlow(input: DrawInput, tools: DrawTools, root: HTMLElement) {\n const bounds = extent()\n const nodeParts: string[] = []\n const containerParts: string[] = []\n for (const item of input.nodes) {\n const { node, spec, rect } = item\n bounds.add(nodeBounds(spec, node, rect))\n const draw = tools.forNode({ width: rect.width, height: rect.height }, item.ports, item.port)\n let body: string\n try {\n body = spec.draw\n ? spec.draw(node as never, draw)\n : drawFallback(draw, item.label, spec.frame !== false)\n } catch (error) {\n console.error(`[@dou-ui/flow] drawing node \"${node.id}\" failed`, error)\n body = drawFallback(draw, item.label, true)\n }\n if (!body) continue\n const g = `<g transform=\"translate(${round(rect.x)} ${round(rect.y)})\">${body}</g>`\n ;(item.container ? containerParts : nodeParts).push(g)\n }\n const looks = edgeLook(tools, root)\n const edgeParts: string[] = []\n const labelParts: string[] = []\n try {\n for (const item of input.edges) {\n for (const p of pathPoints(item.route.path))\n bounds.add({ x: p.x, y: p.y, width: 0, height: 0 })\n const look = looks.of(item)\n edgeParts.push(`<path d=\"${escapeXml(item.route.path)}\" ${look}/>`)\n // arrowheads and the like: the same stroke, never dashed\n if (item.route.marks)\n edgeParts.push(\n `<path d=\"${escapeXml(item.route.marks)}\" ${look.replace(/ stroke-dasharray=\"[^\"]*\"/, '')}/>`,\n )\n for (const p of pathPoints(item.route.marks ?? ''))\n bounds.add({ x: p.x, y: p.y, width: 0, height: 0 })\n if (item.edge.label) {\n const label = drawLabel(tools, item.edge.label, item.route.label)\n labelParts.push(label.markup)\n bounds.add(label.box)\n }\n }\n } finally {\n looks.dispose()\n }\n const box = input.frame ?? bounds.get() ?? { x: 0, y: 0, width: 0, height: 0 }\n const pad = input.frame ? 0 : input.padding\n const x = Math.floor(box.x - pad)\n const y = Math.floor(box.y - pad)\n const width = Math.ceil(box.x + box.width + pad) - x\n const height = Math.ceil(box.y + box.height + pad) - y\n const layerParts: string[] = []\n if (input.layers?.length) {\n const draw = tools.forNode({ width, height }, new Map(), () => '')\n for (const layer of input.layers) {\n try {\n layerParts.push(layer(draw))\n } catch (error) {\n console.error('[@dou-ui/flow] drawing a layer failed', error)\n }\n }\n }\n const rootStyle = getComputedStyle(root)\n const background = input.background\n ? `<rect x=\"${x}\" y=\"${y}\" width=\"${width}\" height=\"${height}\" fill=\"${tools.color(rootStyle.backgroundColor || 'var(--dou-color-bg-canvas)')}\"/>`\n : ''\n const font = escapeXml(tools.fontFamily)\n const svg =\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\" viewBox=\"${x} ${y} ${width} ${height}\" font-family=\"${font}\" font-size=\"${round(tools.fontSize)}\" fill=\"${tools.color('var(--dou-color-text)')}\">` +\n background +\n containerParts.join('') +\n edgeParts.join('') +\n labelParts.join('') +\n nodeParts.join('') +\n layerParts.join('') +\n '</svg>'\n return { svg, width, height }\n}\n\n/** Reads an image into a data URL, or `null` when it can't be read from this page. */\nexport async function readImage(src: string): Promise<string | null> {\n if (src.startsWith('data:')) return src\n try {\n const response = await fetch(src)\n if (!response.ok) return null\n const blob = await response.blob()\n // e.g. a page in place of a missing file\n if (!blob.type.startsWith('image/')) return null\n return await new Promise((resolve) => {\n const reader = new FileReader()\n reader.addEventListener('load', () => resolve(String(reader.result)))\n reader.addEventListener('error', () => resolve(null))\n reader.readAsDataURL(blob)\n })\n } catch {\n return null\n }\n}\n\nexport type { FlowDrawContext }\n"],"mappings":";;;;AA0DA,SAAgB,WAAW,MAAc;CACvC,MAAM,UAAU,KAAK,MAAM,6BAA6B,CAAC,EAAE,IAAI,MAAM,KAAK,CAAC;CAC3E,MAAM,M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EACzB,MAAM,OAAO,MAAM,SAAS,KAAK;EAEjC,IAAI,CAAC,KAAK,KAAK,WAAW,QAAQ,GAAG,OAAO;EAC5C,OAAO,MAAM,IAAI,SAAS,YAAY;GACpC,MAAM,SAAS,IAAI,WAAW;GAC9B,OAAO,iBAAiB,cAAc,QAAQ,OAAO,OAAO,MAAM,CAAC,CAAC;GACpE,OAAO,iBAAiB,eAAe,QAAQ,IAAI,CAAC;GACpD,OAAO,cAAc,IAAI;EAC3B,CAAC;CACH,QAAQ;EACN,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"draw.js","names":[],"sources":["../../src/export/draw.ts"],"sourcesContent":["import type { CSSProperties } from 'vue'\nimport type { PortAnchor } from '../context'\nimport type { EdgeRoute } from '../core/edge-types'\nimport type { FlowEdge, FlowNode, Rect } from '../core/model'\nimport { nodeBounds, type NodeTypeSpec } from '../core/node-types'\nimport { escapeXml, round, type DrawTools, type FlowDrawContext } from './context'\n\nexport interface FlowExportOptions {\n /**\n * `all` (the default): every node and edge. `view`: what is in view now,\n * at the canvas's size, cut at its edges. `selection`: the selected nodes,\n * what is inside selected groups, and the edges between them; it throws\n * when nothing is selected.\n */\n range?: 'all' | 'view' | 'selection'\n /** Room around the drawing, in px. Defaults to `24`; not used by `view`. */\n padding?: number\n /** Fills the canvas color behind it. Defaults to `true`; `false` leaves it see-through. */\n background?: boolean\n}\n\nexport interface FlowImageOptions extends FlowExportOptions {\n /** Pixels per CSS pixel. Defaults to `2`, sharp on most screens and in print. */\n pixelRatio?: number\n}\n\nexport interface DrawNode {\n node: FlowNode\n spec: NodeTypeSpec\n rect: Rect\n ports: ReadonlyMap<string, PortAnchor>\n container: boolean\n label: string\n /** Draws one of its ports, as `FlowDrawContext.port`. */\n port: (id: string) => string\n}\n\nexport interface DrawEdge {\n edge: FlowEdge\n type: string\n route: EdgeRoute\n style?: CSSProperties\n stale: boolean\n}\n\nexport interface DrawInput {\n /** Containers outer first, then the other nodes lowest first. */\n nodes: DrawNode[]\n edges: DrawEdge[]\n padding: number\n background: boolean\n /** The area to draw, in place of what the drawing covers plus `padding`. */\n frame?: Rect\n /** Extensions' layers over the nodes, as `FlowExtension.drawLayer`. */\n layers?: ((draw: FlowDrawContext) => string)[]\n}\n\n/** The points a path passes through or bends towards; the curve stays inside them. */\nexport function pathPoints(path: string) {\n const numbers = path.match(/-?\\d*\\.?\\d+(?:e[-+]?\\d+)?/gi)?.map(Number) ?? []\n const out: { x: number; y: number }[] = []\n for (let i = 0; i + 1 < numbers.length; i += 2) out.push({ x: numbers[i]!, y: numbers[i + 1]! })\n return out\n}\n\n/** A box that grows to hold what is added. */\nfunction extent() {\n let minX = Infinity\n let minY = Infinity\n let maxX = -Infinity\n let maxY = -Infinity\n return {\n add(rect: Rect) {\n minX = Math.min(minX, rect.x)\n minY = Math.min(minY, rect.y)\n maxX = Math.max(maxX, rect.x + rect.width)\n maxY = Math.max(maxY, rect.y + rect.height)\n },\n get(): Rect | null {\n return minX === Infinity\n ? null\n : { x: minX, y: minY, width: maxX - minX, height: maxY - minY }\n },\n }\n}\n\nconst px = (value: string, fallback = 0) => {\n const n = Number.parseFloat(value)\n return Number.isFinite(n) ? n : fallback\n}\n\n/** A card like the editor's frame: border, background and radius. */\nexport function drawCard(draw: FlowDrawContext, classes: string[] = []): string {\n const s = draw.style(['dou-flow-editor__node', ...classes].join(' '))\n const border = px(s.borderTopWidth, 1)\n const radius = px(s.borderTopLeftRadius, 8)\n const inset = border / 2\n return `<rect x=\"${inset}\" y=\"${inset}\" width=\"${round(Math.max(0, draw.width - border))}\" height=\"${round(Math.max(0, draw.height - border))}\" rx=\"${round(Math.max(0, radius - inset))}\" fill=\"${draw.escape(draw.color(s.backgroundColor))}\" stroke=\"${draw.escape(draw.color(s.borderTopColor))}\" stroke-width=\"${border}\"/>`\n}\n\n/** What a node type without `draw` is drawn as: its card, its name and its ports. */\nexport function drawFallback(draw: FlowDrawContext, label: string, framed: boolean): string {\n const parts = framed ? [drawCard(draw)] : []\n for (const id of draw.ports.keys()) parts.push(draw.port(id))\n parts.push(\n draw.text(\n label,\n { x: 12, y: 0, width: Math.max(0, draw.width - 24), height: draw.height },\n { align: 'center', valign: 'middle', color: draw.color('var(--dou-color-text)') },\n ),\n )\n return parts.join('')\n}\n\n/** The edges' look, read from paths made like the editor's. */\nfunction edgeLook(tools: DrawTools, root: HTMLElement) {\n const NS = 'http://www.w3.org/2000/svg'\n const svg = document.createElementNS(NS, 'svg')\n svg.setAttribute('class', 'dou-flow-editor__edges')\n svg.style.cssText = 'position:absolute;visibility:hidden;pointer-events:none'\n root.append(svg)\n const looks = new Map<string, string>()\n return {\n of(item: DrawEdge) {\n const style = item.style as Record<string, string | undefined> | undefined\n const key = [item.type, item.stale, item.edge.animated, JSON.stringify(style ?? {})].join('|')\n let found = looks.get(key)\n if (found === undefined) {\n const g = document.createElementNS(NS, 'g')\n g.setAttribute('data-edge-type', item.type)\n const path = document.createElementNS(NS, 'path')\n const classes = ['dou-flow-editor__edge']\n if (item.stale) classes.push('is-stale')\n if (item.edge.animated) classes.push('is-animated')\n path.setAttribute('class', classes.join(' '))\n for (const [name, value] of Object.entries(style ?? {})) {\n if (value === undefined) continue\n if (name.startsWith('--')) path.style.setProperty(name, value)\n else\n path.style.setProperty(\n name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`),\n value,\n )\n }\n g.append(path)\n svg.append(g)\n const s = getComputedStyle(path)\n const dash = s.strokeDasharray && s.strokeDasharray !== 'none' ? s.strokeDasharray : ''\n const width = px(s.strokeWidth, 1)\n const stroke =\n (s.stroke && s.stroke !== 'none' ? tools.color(s.stroke) : '') ||\n (item.stale ? tools.color('var(--dou-color-danger)') : '') ||\n (style?.stroke ? tools.color(style.stroke) : '') ||\n (style?.['--dou-flow-connector-color']\n ? tools.color(style['--dou-flow-connector-color'])\n : '') ||\n tools.color('var(--dou-flow-editor-edge)')\n found =\n `fill=\"none\" stroke=\"${escapeXml(stroke)}\" stroke-width=\"${round(width)}\"` +\n (dash ? ` stroke-dasharray=\"${dash.replace(/px/g, '').replace(/,\\s*/g, ' ')}\"` : '') +\n (s.strokeLinecap && s.strokeLinecap !== 'butt'\n ? ` stroke-linecap=\"${s.strokeLinecap}\"`\n : '') +\n (s.strokeLinejoin && s.strokeLinejoin !== 'miter'\n ? ` stroke-linejoin=\"${s.strokeLinejoin}\"`\n : '')\n looks.set(key, found)\n }\n return found\n },\n dispose: () => svg.remove(),\n }\n}\n\n/** An edge's label: a pill with its text, as on screen. */\nfunction drawLabel(tools: DrawTools, text: string, at: { x: number; y: number }) {\n const s = tools.style('dou-flow-editor__label')\n const size = px(s.fontSize, 12)\n const padding = px(s.paddingLeft, 6)\n const border = px(s.borderTopWidth, 1)\n const height = px(s.lineHeight, 20) + border * 2\n const max = px(s.maxWidth, 200)\n const textWidth = Math.min(tools.measure(text, size), max - padding * 2 - border * 2)\n const width = Math.ceil(textWidth + padding * 2 + border * 2)\n const x = at.x - width / 2\n const y = at.y - height / 2\n const radius = px(s.borderTopLeftRadius, 6)\n const markup =\n `<rect x=\"${round(x + border / 2)}\" y=\"${round(y + border / 2)}\" width=\"${round(width - border)}\" height=\"${round(height - border)}\" rx=\"${round(radius)}\" fill=\"${escapeXml(tools.color(s.backgroundColor))}\" stroke=\"${escapeXml(tools.color(s.borderTopColor))}\" stroke-width=\"${border}\"/>` +\n tools.text(\n text,\n { x: x + border + padding, y, width: width - (border + padding) * 2, height },\n { size, lineHeight: height, color: tools.color(s.color), align: 'center', nowrap: true },\n )\n return { markup, box: { x, y, width, height } }\n}\n\n/**\n * The flow as an SVG document: containers, edges, edge labels, then the\n * other nodes, as the editor stacks them.\n */\nexport function drawFlow(input: DrawInput, tools: DrawTools, root: HTMLElement) {\n const bounds = extent()\n const nodeParts: string[] = []\n const containerParts: string[] = []\n for (const item of input.nodes) {\n const { node, spec, rect } = item\n bounds.add(nodeBounds(spec, node, rect))\n const draw = tools.forNode({ width: rect.width, height: rect.height }, item.ports, item.port)\n let body: string\n try {\n body = spec.draw\n ? spec.draw(node as never, draw)\n : drawFallback(draw, item.label, spec.frame !== false)\n } catch (error) {\n console.error(`[@dou-ui/flow] drawing node \"${node.id}\" failed`, error)\n body = drawFallback(draw, item.label, true)\n }\n if (!body) continue\n const g = `<g transform=\"translate(${round(rect.x)} ${round(rect.y)})\">${body}</g>`\n ;(item.container ? containerParts : nodeParts).push(g)\n }\n const looks = edgeLook(tools, root)\n const edgeParts: string[] = []\n const labelParts: string[] = []\n try {\n for (const item of input.edges) {\n for (const p of pathPoints(item.route.path))\n bounds.add({ x: p.x, y: p.y, width: 0, height: 0 })\n const look = looks.of(item)\n edgeParts.push(`<path d=\"${escapeXml(item.route.path)}\" ${look}/>`)\n // arrowheads and the like: the same stroke, never dashed\n if (item.route.marks)\n edgeParts.push(\n `<path d=\"${escapeXml(item.route.marks)}\" ${look.replace(/ stroke-dasharray=\"[^\"]*\"/, '')}/>`,\n )\n for (const p of pathPoints(item.route.marks ?? ''))\n bounds.add({ x: p.x, y: p.y, width: 0, height: 0 })\n if (item.edge.label) {\n const label = drawLabel(tools, item.edge.label, item.route.label)\n labelParts.push(label.markup)\n bounds.add(label.box)\n }\n }\n } finally {\n looks.dispose()\n }\n const box = input.frame ?? bounds.get() ?? { x: 0, y: 0, width: 0, height: 0 }\n const pad = input.frame ? 0 : input.padding\n const x = Math.floor(box.x - pad)\n const y = Math.floor(box.y - pad)\n const width = Math.ceil(box.x + box.width + pad) - x\n const height = Math.ceil(box.y + box.height + pad) - y\n const layerParts: string[] = []\n if (input.layers?.length) {\n const draw = tools.forNode({ width, height }, new Map(), () => '')\n for (const layer of input.layers) {\n try {\n layerParts.push(layer(draw))\n } catch (error) {\n console.error('[@dou-ui/flow] drawing a layer failed', error)\n }\n }\n }\n const rootStyle = getComputedStyle(root)\n const background = input.background\n ? `<rect x=\"${x}\" y=\"${y}\" width=\"${width}\" height=\"${height}\" fill=\"${escapeXml(tools.color(rootStyle.backgroundColor || 'var(--dou-color-bg-canvas)'))}\"/>`\n : ''\n const font = escapeXml(tools.fontFamily)\n const svg =\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\" viewBox=\"${x} ${y} ${width} ${height}\" font-family=\"${font}\" font-size=\"${round(tools.fontSize)}\" fill=\"${escapeXml(tools.color('var(--dou-color-text)'))}\">` +\n background +\n containerParts.join('') +\n edgeParts.join('') +\n labelParts.join('') +\n nodeParts.join('') +\n layerParts.join('') +\n '</svg>'\n return { svg, width, height }\n}\n\n/** Reads an image into a data URL, or `null` when it can't be read from this page. */\nexport async function readImage(src: string): Promise<string | null> {\n if (src.startsWith('data:')) return src\n try {\n const response = await fetch(src)\n if (!response.ok) return null\n const blob = await response.blob()\n // e.g. a page in place of a missing file\n if (!blob.type.startsWith('image/')) return null\n return await new Promise((resolve) => {\n const reader = new FileReader()\n reader.addEventListener('load', () => resolve(String(reader.result)))\n reader.addEventListener('error', () => resolve(null))\n reader.readAsDataURL(blob)\n })\n } catch {\n return null\n }\n}\n\nexport type { FlowDrawContext }\n"],"mappings":";;;;AA0DA,SAAgB,WAAW,MAAc;CACvC,MAAM,UAAU,KAAK,MAAM,6BAA6B,CAAC,EAAE,IAAI,MAAM,KAAK,CAAC;CAC3E,MAAM,MAAkC,CAAC;CACzC,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,QAAQ,KAAK,GAAG,IAAI,KAAK;EAAE,GAAG,QAAQ;EAAK,GAAG,QAAQ,IAAI;CAAI,CAAC;CAC/F,OAAO;AACT;;AAGA,SAAS,SAAS;CAChB,IAAI,OAAO;CACX,IAAI,OAAO;CACX,IAAI,OAAO;CACX,IAAI,OAAO;CACX,OAAO;EACL,IAAI,MAAY;GACd,OAAO,KAAK,IAAI,MAAM,KAAK,CAAC;GAC5B,OAAO,KAAK,IAAI,MAAM,KAAK,CAAC;GAC5B,OAAO,KAAK,IAAI,MAAM,KAAK,IAAI,KAAK,KAAK;GACzC,OAAO,KAAK,IAAI,MAAM,KAAK,IAAI,KAAK,M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AAW;GAC9B,OAAO,iBAAiB,cAAc,QAAQ,OAAO,OAAO,MAAM,CAAC,CAAC;GACpE,OAAO,iBAAiB,eAAe,QAAQ,IAAI,CAAC;GACpD,OAAO,cAAc,IAAI;EAC3B,CAAC;CACH,QAAQ;EACN,OAAO;CACT;AACF"}
@@ -0,0 +1,78 @@
1
+ import flow_editor_default from "../flow-editor.js";
2
+ import { installedAppContext } from "dou-ui";
3
+ import { h, nextTick, render } from "vue";
4
+ // src/export/render.ts
5
+ var frame = () => new Promise((resolve) => typeof requestAnimationFrame === "undefined" ? setTimeout(resolve, 16) : requestAnimationFrame(() => resolve()));
6
+ /**
7
+ * Draws the document in an editor of its own, on the page but not seen, and
8
+ * hands the editor to `use` once every node has been laid out and measured;
9
+ * the editor is removed after. `name` is the function called, for errors.
10
+ */
11
+ async function withEditor(name, document, options, use) {
12
+ if (typeof window === "undefined") throw new Error(`[@dou-ui/flow] ${name} needs a browser: it lays out the nodes on the page`);
13
+ const host = window.document.createElement("div");
14
+ host.setAttribute("aria-hidden", "true");
15
+ host.inert = true;
16
+ host.style.cssText = "position:fixed;top:0;left:0;width:800px;height:600px;overflow:hidden;visibility:hidden;pointer-events:none;contain:strict;z-index:-1";
17
+ if (options.colorMode) host.setAttribute("data-dou-theme", options.colorMode);
18
+ window.document.body.append(host);
19
+ const vnode = h(flow_editor_default, {
20
+ modelValue: document,
21
+ extensions: options.extensions,
22
+ nodeTypes: options.nodeTypes,
23
+ edgeTypes: options.edgeTypes,
24
+ edgeType: options.edgeType,
25
+ portTypes: options.portTypes,
26
+ direction: options.direction,
27
+ messages: options.messages,
28
+ readonly: true,
29
+ fitView: false,
30
+ searchable: false
31
+ });
32
+ vnode.appContext = options.appContext === void 0 ? installedAppContext() : options.appContext;
33
+ try {
34
+ render(vnode, host);
35
+ const root = host.firstElementChild;
36
+ if (root && !getComputedStyle(root).getPropertyValue("--dou-flow-editor-node-bg")) throw new Error(`[@dou-ui/flow] ${name} needs the flow styles, which load with <DouFlowEditor> only: import '@dou-ui/flow/style'`);
37
+ await nextTick();
38
+ await frame();
39
+ if (window.document.fonts?.ready) await window.document.fonts.ready;
40
+ await frame();
41
+ await nextTick();
42
+ const editor = vnode.component?.exposed;
43
+ if (!editor) throw new Error("[@dou-ui/flow] the flow could not be drawn");
44
+ return await use(editor);
45
+ } finally {
46
+ render(null, host);
47
+ host.remove();
48
+ }
49
+ }
50
+ /**
51
+ * The document as an SVG document, drawn as `exportSVG` draws it, without an
52
+ * editor on the page: for thumbnails and previews. Give it the same node,
53
+ * edge and port types as the editor that shows the document.
54
+ */
55
+ function renderFlowSVG(document, options = {}) {
56
+ return withEditor("renderFlowSVG", document, options, (editor) => editor.exportSVG({
57
+ padding: options.padding,
58
+ background: options.background
59
+ }));
60
+ }
61
+ /** The document as a PNG image, as `exportPNG` draws it, without an editor on the page. */
62
+ function renderFlowPNG(document, options = {}) {
63
+ return withEditor("renderFlowPNG", document, options, async (editor) => {
64
+ try {
65
+ return await editor.exportPNG({
66
+ padding: options.padding,
67
+ background: options.background,
68
+ pixelRatio: options.pixelRatio
69
+ });
70
+ } catch (error) {
71
+ if (error instanceof RangeError && error.message.includes("exportSVG()")) throw new RangeError(error.message.replace(/; [^;]*exportSVG\(\)$/, "; use renderFlowSVG() instead"));
72
+ throw error;
73
+ }
74
+ });
75
+ }
76
+ export { renderFlowPNG, renderFlowSVG };
77
+
78
+ //# sourceMappingURL=render.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render.js","names":["FlowEditor"],"sources":["../../src/export/render.ts"],"sourcesContent":["import { type ResolvedColorMode, installedAppContext } from 'dou-ui'\nimport { type AppContext, h, nextTick, render } from 'vue'\nimport FlowEditor from '../flow-editor.vue'\nimport type { FlowEditorExpose, FlowEditorProps } from '../context'\nimport type { FlowDocument } from '../core/model'\nimport type { FlowExportOptions, FlowImageOptions } from './draw'\n\nexport interface RenderFlowOptions\n extends\n Pick<\n FlowEditorProps,\n 'extensions' | 'nodeTypes' | 'edgeTypes' | 'edgeType' | 'portTypes' | 'direction' | 'messages'\n >,\n Omit<FlowExportOptions, 'range'> {\n /** Light or dark colors; the page's own color mode by default. */\n colorMode?: ResolvedColorMode\n /**\n * The app context node components render in, for its locale, plugins and\n * provides, e.g. `getCurrentInstance()!.appContext`. Defaults to the app\n * `app.use(DouUI)` was called on.\n */\n appContext?: AppContext | null\n}\n\nexport interface RenderFlowImageOptions extends RenderFlowOptions {\n /** Pixels per CSS pixel. Defaults to `2`. */\n pixelRatio?: number\n}\n\nconst frame = () =>\n new Promise<void>((resolve) =>\n typeof requestAnimationFrame === 'undefined'\n ? setTimeout(resolve, 16)\n : requestAnimationFrame(() => resolve()),\n )\n\n/**\n * Draws the document in an editor of its own, on the page but not seen, and\n * hands the editor to `use` once every node has been laid out and measured;\n * the editor is removed after. `name` is the function called, for errors.\n */\nasync function withEditor<T>(\n name: string,\n document: FlowDocument,\n options: RenderFlowOptions,\n use: (editor: FlowEditorExpose) => T | Promise<T>,\n): Promise<T> {\n if (typeof window === 'undefined')\n throw new Error(`[@dou-ui/flow] ${name} needs a browser: it lays out the nodes on the page`)\n const host = window.document.createElement('div')\n host.setAttribute('aria-hidden', 'true')\n host.inert = true\n // Laid out, so nodes measure, but not seen and never in the way.\n host.style.cssText =\n 'position:fixed;top:0;left:0;width:800px;height:600px;overflow:hidden;visibility:hidden;pointer-events:none;contain:strict;z-index:-1'\n if (options.colorMode) host.setAttribute('data-dou-theme', options.colorMode)\n window.document.body.append(host)\n const vnode = h(FlowEditor, {\n modelValue: document,\n extensions: options.extensions,\n nodeTypes: options.nodeTypes,\n edgeTypes: options.edgeTypes,\n edgeType: options.edgeType,\n portTypes: options.portTypes,\n direction: options.direction,\n messages: options.messages,\n readonly: true,\n fitView: false,\n searchable: false,\n })\n vnode.appContext = options.appContext === undefined ? installedAppContext() : options.appContext\n try {\n render(vnode, host)\n // Without the flow's styles nodes lay out wrong, and the picture with them.\n const root = host.firstElementChild\n if (root && !getComputedStyle(root).getPropertyValue('--dou-flow-editor-node-bg'))\n throw new Error(\n `[@dou-ui/flow] ${name} needs the flow styles, which load with <DouFlowEditor> only: import '@dou-ui/flow/style'`,\n )\n // Nodes measure after they mount, and edges follow their ports; text needs its font.\n await nextTick()\n await frame()\n if (window.document.fonts?.ready) await window.document.fonts.ready\n await frame()\n await nextTick()\n const editor = vnode.component?.exposed as FlowEditorExpose | undefined\n if (!editor) throw new Error('[@dou-ui/flow] the flow could not be drawn')\n return await use(editor)\n } finally {\n render(null, host)\n host.remove()\n }\n}\n\n/**\n * The document as an SVG document, drawn as `exportSVG` draws it, without an\n * editor on the page: for thumbnails and previews. Give it the same node,\n * edge and port types as the editor that shows the document.\n */\nexport function renderFlowSVG(document: FlowDocument, options: RenderFlowOptions = {}) {\n return withEditor('renderFlowSVG', document, options, (editor) =>\n editor.exportSVG({ padding: options.padding, background: options.background }),\n )\n}\n\n/** The document as a PNG image, as `exportPNG` draws it, without an editor on the page. */\nexport function renderFlowPNG(document: FlowDocument, options: RenderFlowImageOptions = {}) {\n return withEditor('renderFlowPNG', document, options, async (editor) => {\n try {\n return await editor.exportPNG({\n padding: options.padding,\n background: options.background,\n pixelRatio: options.pixelRatio,\n } satisfies FlowImageOptions)\n } catch (error) {\n // the editor's advice is about its own ranges; here only the SVG helps\n if (error instanceof RangeError && error.message.includes('exportSVG()'))\n throw new RangeError(\n error.message.replace(/; [^;]*exportSVG\\(\\)$/, '; use renderFlowSVG() instead'),\n )\n throw error\n }\n })\n}\n"],"mappings":";;;;AA6BA,IAAM,cACJ,IAAI,SAAe,YACjB,OAAO,0BAA0B,cAC7B,WAAW,SAAS,EAAE,IACtB,4BAA4B,QAAQ,CAAC,CAC3C;;;;;;AAOF,eAAe,WACb,MACA,UACA,SACA,KACY;CACZ,IAAI,OAAO,WAAW,aACpB,MAAM,IAAI,MAAM,kBAAkB,KAAK,oDAAoD;CAC7F,MAAM,OAAO,OAAO,SAAS,cAAc,KAAK;CAChD,KAAK,aAAa,eAAe,MAAM;CACvC,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