@tldraw/editor 4.5.3 → 4.6.0-canary.0bcbb3ed5bcb

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 (226) hide show
  1. package/dist-cjs/index.d.ts +37 -6
  2. package/dist-cjs/index.js +6 -1
  3. package/dist-cjs/index.js.map +2 -2
  4. package/dist-cjs/lib/TldrawEditor.js +7 -5
  5. package/dist-cjs/lib/TldrawEditor.js.map +3 -3
  6. package/dist-cjs/lib/components/default-components/CanvasShapeIndicators.js +3 -2
  7. package/dist-cjs/lib/components/default-components/CanvasShapeIndicators.js.map +2 -2
  8. package/dist-cjs/lib/components/default-components/DefaultCanvas.js +1 -1
  9. package/dist-cjs/lib/components/default-components/DefaultCanvas.js.map +2 -2
  10. package/dist-cjs/lib/components/default-components/DefaultErrorFallback.js +8 -5
  11. package/dist-cjs/lib/components/default-components/DefaultErrorFallback.js.map +2 -2
  12. package/dist-cjs/lib/config/TLSessionStateSnapshot.js +8 -5
  13. package/dist-cjs/lib/config/TLSessionStateSnapshot.js.map +2 -2
  14. package/dist-cjs/lib/config/TLUserPreferences.js +3 -2
  15. package/dist-cjs/lib/config/TLUserPreferences.js.map +2 -2
  16. package/dist-cjs/lib/config/createTLStore.js +1 -0
  17. package/dist-cjs/lib/config/createTLStore.js.map +2 -2
  18. package/dist-cjs/lib/editor/Editor.js +52 -16
  19. package/dist-cjs/lib/editor/Editor.js.map +2 -2
  20. package/dist-cjs/lib/editor/managers/FocusManager/FocusManager.js +62 -6
  21. package/dist-cjs/lib/editor/managers/FocusManager/FocusManager.js.map +2 -2
  22. package/dist-cjs/lib/editor/managers/FontManager/FontManager.js +4 -3
  23. package/dist-cjs/lib/editor/managers/FontManager/FontManager.js.map +2 -2
  24. package/dist-cjs/lib/editor/managers/HistoryManager/HistoryManager.js +5 -0
  25. package/dist-cjs/lib/editor/managers/HistoryManager/HistoryManager.js.map +2 -2
  26. package/dist-cjs/lib/editor/managers/TextManager/TextManager.js +2 -2
  27. package/dist-cjs/lib/editor/managers/TextManager/TextManager.js.map +2 -2
  28. package/dist-cjs/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.js +3 -2
  29. package/dist-cjs/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.js.map +2 -2
  30. package/dist-cjs/lib/editor/types/misc-types.js.map +1 -1
  31. package/dist-cjs/lib/exports/FontEmbedder.js +9 -8
  32. package/dist-cjs/lib/exports/FontEmbedder.js.map +2 -2
  33. package/dist-cjs/lib/exports/StyleEmbedder.js +27 -15
  34. package/dist-cjs/lib/exports/StyleEmbedder.js.map +3 -3
  35. package/dist-cjs/lib/exports/domUtils.js +15 -0
  36. package/dist-cjs/lib/exports/domUtils.js.map +2 -2
  37. package/dist-cjs/lib/exports/embedMedia.js +15 -12
  38. package/dist-cjs/lib/exports/embedMedia.js.map +2 -2
  39. package/dist-cjs/lib/exports/exportToSvg.js +8 -7
  40. package/dist-cjs/lib/exports/exportToSvg.js.map +2 -2
  41. package/dist-cjs/lib/exports/getSvgAsImage.js +181 -29
  42. package/dist-cjs/lib/exports/getSvgAsImage.js.map +3 -3
  43. package/dist-cjs/lib/exports/getSvgJsx.js +21 -9
  44. package/dist-cjs/lib/exports/getSvgJsx.js.map +2 -2
  45. package/dist-cjs/lib/globals/environment.js +4 -3
  46. package/dist-cjs/lib/globals/environment.js.map +2 -2
  47. package/dist-cjs/lib/hooks/useCanvasEvents.js +2 -2
  48. package/dist-cjs/lib/hooks/useCanvasEvents.js.map +2 -2
  49. package/dist-cjs/lib/hooks/useDocumentEvents.js +13 -11
  50. package/dist-cjs/lib/hooks/useDocumentEvents.js.map +2 -2
  51. package/dist-cjs/lib/hooks/useFixSafariDoubleTapZoomPencilEvents.js +3 -2
  52. package/dist-cjs/lib/hooks/useFixSafariDoubleTapZoomPencilEvents.js.map +2 -2
  53. package/dist-cjs/lib/hooks/useScreenBounds.js +10 -6
  54. package/dist-cjs/lib/hooks/useScreenBounds.js.map +2 -2
  55. package/dist-cjs/lib/hooks/useViewportHeight.js +13 -11
  56. package/dist-cjs/lib/hooks/useViewportHeight.js.map +3 -3
  57. package/dist-cjs/lib/license/Watermark.js +10 -0
  58. package/dist-cjs/lib/license/Watermark.js.map +2 -2
  59. package/dist-cjs/lib/primitives/Vec.js +35 -22
  60. package/dist-cjs/lib/primitives/Vec.js.map +2 -2
  61. package/dist-cjs/lib/primitives/geometry/Arc2d.js +6 -13
  62. package/dist-cjs/lib/primitives/geometry/Arc2d.js.map +2 -2
  63. package/dist-cjs/lib/primitives/geometry/Circle2d.js +31 -2
  64. package/dist-cjs/lib/primitives/geometry/Circle2d.js.map +2 -2
  65. package/dist-cjs/lib/primitives/geometry/CubicBezier2d.js +9 -0
  66. package/dist-cjs/lib/primitives/geometry/CubicBezier2d.js.map +2 -2
  67. package/dist-cjs/lib/primitives/geometry/CubicSpline2d.js +9 -0
  68. package/dist-cjs/lib/primitives/geometry/CubicSpline2d.js.map +2 -2
  69. package/dist-cjs/lib/primitives/geometry/Edge2d.js +32 -18
  70. package/dist-cjs/lib/primitives/geometry/Edge2d.js.map +2 -2
  71. package/dist-cjs/lib/primitives/geometry/Ellipse2d.js +12 -0
  72. package/dist-cjs/lib/primitives/geometry/Ellipse2d.js.map +2 -2
  73. package/dist-cjs/lib/primitives/geometry/Polyline2d.js +51 -12
  74. package/dist-cjs/lib/primitives/geometry/Polyline2d.js.map +2 -2
  75. package/dist-cjs/lib/primitives/geometry/Stadium2d.js +12 -0
  76. package/dist-cjs/lib/primitives/geometry/Stadium2d.js.map +2 -2
  77. package/dist-cjs/lib/primitives/geometry/geometry.bench.js +133 -0
  78. package/dist-cjs/lib/primitives/geometry/geometry.bench.js.map +7 -0
  79. package/dist-cjs/lib/primitives/intersect.js +16 -15
  80. package/dist-cjs/lib/primitives/intersect.js.map +2 -2
  81. package/dist-cjs/lib/primitives/utils.js +0 -1
  82. package/dist-cjs/lib/primitives/utils.js.map +2 -2
  83. package/dist-cjs/lib/utils/browserCanvasMaxSize.js +3 -2
  84. package/dist-cjs/lib/utils/browserCanvasMaxSize.js.map +2 -2
  85. package/dist-cjs/lib/utils/dom.js +15 -2
  86. package/dist-cjs/lib/utils/dom.js.map +2 -2
  87. package/dist-cjs/version.js +3 -3
  88. package/dist-cjs/version.js.map +1 -1
  89. package/dist-esm/index.d.mts +37 -6
  90. package/dist-esm/index.mjs +8 -1
  91. package/dist-esm/index.mjs.map +2 -2
  92. package/dist-esm/lib/TldrawEditor.mjs +7 -5
  93. package/dist-esm/lib/TldrawEditor.mjs.map +3 -3
  94. package/dist-esm/lib/components/default-components/CanvasShapeIndicators.mjs +2 -1
  95. package/dist-esm/lib/components/default-components/CanvasShapeIndicators.mjs.map +2 -2
  96. package/dist-esm/lib/components/default-components/DefaultCanvas.mjs +1 -1
  97. package/dist-esm/lib/components/default-components/DefaultCanvas.mjs.map +2 -2
  98. package/dist-esm/lib/components/default-components/DefaultErrorFallback.mjs +8 -5
  99. package/dist-esm/lib/components/default-components/DefaultErrorFallback.mjs.map +2 -2
  100. package/dist-esm/lib/config/TLSessionStateSnapshot.mjs +8 -5
  101. package/dist-esm/lib/config/TLSessionStateSnapshot.mjs.map +2 -2
  102. package/dist-esm/lib/config/TLUserPreferences.mjs +3 -2
  103. package/dist-esm/lib/config/TLUserPreferences.mjs.map +2 -2
  104. package/dist-esm/lib/config/createTLStore.mjs +1 -0
  105. package/dist-esm/lib/config/createTLStore.mjs.map +2 -2
  106. package/dist-esm/lib/editor/Editor.mjs +53 -17
  107. package/dist-esm/lib/editor/Editor.mjs.map +2 -2
  108. package/dist-esm/lib/editor/managers/FocusManager/FocusManager.mjs +64 -6
  109. package/dist-esm/lib/editor/managers/FocusManager/FocusManager.mjs.map +2 -2
  110. package/dist-esm/lib/editor/managers/FontManager/FontManager.mjs +4 -3
  111. package/dist-esm/lib/editor/managers/FontManager/FontManager.mjs.map +2 -2
  112. package/dist-esm/lib/editor/managers/HistoryManager/HistoryManager.mjs +5 -0
  113. package/dist-esm/lib/editor/managers/HistoryManager/HistoryManager.mjs.map +2 -2
  114. package/dist-esm/lib/editor/managers/TextManager/TextManager.mjs +2 -2
  115. package/dist-esm/lib/editor/managers/TextManager/TextManager.mjs.map +2 -2
  116. package/dist-esm/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.mjs +3 -2
  117. package/dist-esm/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.mjs.map +2 -2
  118. package/dist-esm/lib/exports/FontEmbedder.mjs +9 -8
  119. package/dist-esm/lib/exports/FontEmbedder.mjs.map +2 -2
  120. package/dist-esm/lib/exports/StyleEmbedder.mjs +29 -16
  121. package/dist-esm/lib/exports/StyleEmbedder.mjs.map +3 -3
  122. package/dist-esm/lib/exports/domUtils.mjs +15 -0
  123. package/dist-esm/lib/exports/domUtils.mjs.map +2 -2
  124. package/dist-esm/lib/exports/embedMedia.mjs +16 -13
  125. package/dist-esm/lib/exports/embedMedia.mjs.map +2 -2
  126. package/dist-esm/lib/exports/exportToSvg.mjs +8 -7
  127. package/dist-esm/lib/exports/exportToSvg.mjs.map +2 -2
  128. package/dist-esm/lib/exports/getSvgAsImage.mjs +181 -29
  129. package/dist-esm/lib/exports/getSvgAsImage.mjs.map +3 -3
  130. package/dist-esm/lib/exports/getSvgJsx.mjs +21 -9
  131. package/dist-esm/lib/exports/getSvgJsx.mjs.map +2 -2
  132. package/dist-esm/lib/globals/environment.mjs +4 -3
  133. package/dist-esm/lib/globals/environment.mjs.map +2 -2
  134. package/dist-esm/lib/hooks/useCanvasEvents.mjs +2 -2
  135. package/dist-esm/lib/hooks/useCanvasEvents.mjs.map +2 -2
  136. package/dist-esm/lib/hooks/useDocumentEvents.mjs +13 -11
  137. package/dist-esm/lib/hooks/useDocumentEvents.mjs.map +2 -2
  138. package/dist-esm/lib/hooks/useFixSafariDoubleTapZoomPencilEvents.mjs +3 -2
  139. package/dist-esm/lib/hooks/useFixSafariDoubleTapZoomPencilEvents.mjs.map +2 -2
  140. package/dist-esm/lib/hooks/useScreenBounds.mjs +10 -6
  141. package/dist-esm/lib/hooks/useScreenBounds.mjs.map +2 -2
  142. package/dist-esm/lib/hooks/useViewportHeight.mjs +13 -11
  143. package/dist-esm/lib/hooks/useViewportHeight.mjs.map +3 -3
  144. package/dist-esm/lib/license/Watermark.mjs +10 -0
  145. package/dist-esm/lib/license/Watermark.mjs.map +2 -2
  146. package/dist-esm/lib/primitives/Vec.mjs +35 -22
  147. package/dist-esm/lib/primitives/Vec.mjs.map +2 -2
  148. package/dist-esm/lib/primitives/geometry/Arc2d.mjs +6 -13
  149. package/dist-esm/lib/primitives/geometry/Arc2d.mjs.map +2 -2
  150. package/dist-esm/lib/primitives/geometry/Circle2d.mjs +31 -2
  151. package/dist-esm/lib/primitives/geometry/Circle2d.mjs.map +2 -2
  152. package/dist-esm/lib/primitives/geometry/CubicBezier2d.mjs +9 -0
  153. package/dist-esm/lib/primitives/geometry/CubicBezier2d.mjs.map +2 -2
  154. package/dist-esm/lib/primitives/geometry/CubicSpline2d.mjs +9 -0
  155. package/dist-esm/lib/primitives/geometry/CubicSpline2d.mjs.map +2 -2
  156. package/dist-esm/lib/primitives/geometry/Edge2d.mjs +32 -18
  157. package/dist-esm/lib/primitives/geometry/Edge2d.mjs.map +2 -2
  158. package/dist-esm/lib/primitives/geometry/Ellipse2d.mjs +13 -1
  159. package/dist-esm/lib/primitives/geometry/Ellipse2d.mjs.map +2 -2
  160. package/dist-esm/lib/primitives/geometry/Polyline2d.mjs +51 -12
  161. package/dist-esm/lib/primitives/geometry/Polyline2d.mjs.map +2 -2
  162. package/dist-esm/lib/primitives/geometry/Stadium2d.mjs +13 -1
  163. package/dist-esm/lib/primitives/geometry/Stadium2d.mjs.map +2 -2
  164. package/dist-esm/lib/primitives/geometry/geometry.bench.mjs +132 -0
  165. package/dist-esm/lib/primitives/geometry/geometry.bench.mjs.map +7 -0
  166. package/dist-esm/lib/primitives/intersect.mjs +17 -16
  167. package/dist-esm/lib/primitives/intersect.mjs.map +2 -2
  168. package/dist-esm/lib/primitives/utils.mjs +0 -1
  169. package/dist-esm/lib/primitives/utils.mjs.map +2 -2
  170. package/dist-esm/lib/utils/browserCanvasMaxSize.mjs +3 -2
  171. package/dist-esm/lib/utils/browserCanvasMaxSize.mjs.map +2 -2
  172. package/dist-esm/lib/utils/dom.mjs +15 -2
  173. package/dist-esm/lib/utils/dom.mjs.map +2 -2
  174. package/dist-esm/version.mjs +3 -3
  175. package/dist-esm/version.mjs.map +1 -1
  176. package/package.json +7 -7
  177. package/src/index.ts +3 -0
  178. package/src/lib/TldrawEditor.tsx +7 -5
  179. package/src/lib/components/default-components/CanvasShapeIndicators.tsx +2 -1
  180. package/src/lib/components/default-components/DefaultCanvas.tsx +1 -1
  181. package/src/lib/components/default-components/DefaultErrorFallback.tsx +8 -5
  182. package/src/lib/config/TLSessionStateSnapshot.ts +8 -5
  183. package/src/lib/config/TLUserPreferences.ts +3 -2
  184. package/src/lib/config/createTLStore.ts +3 -0
  185. package/src/lib/editor/Editor.ts +53 -15
  186. package/src/lib/editor/managers/FocusManager/FocusManager.test.ts +7 -6
  187. package/src/lib/editor/managers/FocusManager/FocusManager.ts +10 -7
  188. package/src/lib/editor/managers/FontManager/FontManager.test.ts +1 -0
  189. package/src/lib/editor/managers/FontManager/FontManager.ts +4 -3
  190. package/src/lib/editor/managers/HistoryManager/HistoryManager.test.ts +16 -0
  191. package/src/lib/editor/managers/HistoryManager/HistoryManager.ts +7 -2
  192. package/src/lib/editor/managers/TextManager/TextManager.test.ts +4 -5
  193. package/src/lib/editor/managers/TextManager/TextManager.ts +2 -2
  194. package/src/lib/editor/managers/UserPreferencesManager/UserPreferencesManager.ts +3 -2
  195. package/src/lib/editor/types/misc-types.ts +8 -2
  196. package/src/lib/exports/FontEmbedder.ts +10 -9
  197. package/src/lib/exports/StyleEmbedder.ts +33 -15
  198. package/src/lib/exports/domUtils.ts +20 -0
  199. package/src/lib/exports/embedMedia.ts +23 -17
  200. package/src/lib/exports/exportToSvg.tsx +8 -7
  201. package/src/lib/exports/getSvgAsImage.ts +292 -32
  202. package/src/lib/exports/getSvgJsx.test.ts +103 -101
  203. package/src/lib/exports/getSvgJsx.tsx +33 -10
  204. package/src/lib/globals/environment.ts +4 -3
  205. package/src/lib/hooks/useCanvasEvents.ts +2 -3
  206. package/src/lib/hooks/useDocumentEvents.ts +16 -11
  207. package/src/lib/hooks/useFixSafariDoubleTapZoomPencilEvents.ts +3 -3
  208. package/src/lib/hooks/useScreenBounds.ts +10 -6
  209. package/src/lib/hooks/useViewportHeight.ts +13 -11
  210. package/src/lib/license/Watermark.tsx +10 -0
  211. package/src/lib/primitives/Vec.ts +51 -24
  212. package/src/lib/primitives/geometry/Arc2d.ts +10 -15
  213. package/src/lib/primitives/geometry/Circle2d.ts +40 -2
  214. package/src/lib/primitives/geometry/CubicBezier2d.ts +10 -0
  215. package/src/lib/primitives/geometry/CubicSpline2d.ts +10 -0
  216. package/src/lib/primitives/geometry/Edge2d.ts +41 -18
  217. package/src/lib/primitives/geometry/Ellipse2d.ts +14 -1
  218. package/src/lib/primitives/geometry/Polyline2d.ts +60 -12
  219. package/src/lib/primitives/geometry/Stadium2d.ts +14 -1
  220. package/src/lib/primitives/geometry/geometry.bench.ts +179 -0
  221. package/src/lib/primitives/intersect.ts +27 -27
  222. package/src/lib/primitives/utils.ts +4 -4
  223. package/src/lib/test/TestEditor.ts +1 -0
  224. package/src/lib/utils/browserCanvasMaxSize.ts +4 -2
  225. package/src/lib/utils/dom.ts +34 -2
  226. package/src/version.ts +3 -3
@@ -18,15 +18,23 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var getSvgAsImage_exports = {};
20
20
  __export(getSvgAsImage_exports, {
21
- getSvgAsImage: () => getSvgAsImage
21
+ getSvgAsImage: () => getSvgAsImage,
22
+ getSvgAsImageWithOptions: () => getSvgAsImageWithOptions,
23
+ trimSvgToContent: () => trimSvgToContent
22
24
  });
23
25
  module.exports = __toCommonJS(getSvgAsImage_exports);
24
26
  var import_utils = require("@tldraw/utils");
25
27
  var import_environment = require("../globals/environment");
26
28
  var import_browserCanvasMaxSize = require("../utils/browserCanvasMaxSize");
27
29
  var import_debug_flags = require("../utils/debug-flags");
30
+ var import_dom = require("../utils/dom");
28
31
  async function getSvgAsImage(svgString, options) {
29
- const { type, width, height, quality = 1, pixelRatio = 2 } = options;
32
+ const result = await getSvgAsImageWithOptions(svgString, options);
33
+ return result?.blob ?? null;
34
+ }
35
+ async function getSvgAsImageWithOptions(svgString, options) {
36
+ const { type, width, height, quality = 1, pixelRatio = 2, trimPadding = 0, scale = 1 } = options;
37
+ if (width <= 0 || height <= 0) return null;
30
38
  let [clampedWidth, clampedHeight] = (0, import_browserCanvasMaxSize.clampToBrowserMaxCanvasSize)(
31
39
  width * pixelRatio,
32
40
  height * pixelRatio
@@ -34,32 +42,11 @@ async function getSvgAsImage(svgString, options) {
34
42
  clampedWidth = Math.floor(clampedWidth);
35
43
  clampedHeight = Math.floor(clampedHeight);
36
44
  const effectiveScale = clampedWidth / width;
37
- const svgUrl = await import_utils.FileHelpers.blobToDataUrl(new Blob([svgString], { type: "image/svg+xml" }));
38
- const canvas = await new Promise((resolve) => {
39
- const image = (0, import_utils.Image)();
40
- image.crossOrigin = "anonymous";
41
- image.onload = async () => {
42
- if (import_environment.tlenv.isSafari) {
43
- await (0, import_utils.sleep)(250);
44
- }
45
- const canvas2 = document.createElement("canvas");
46
- const ctx = canvas2.getContext("2d");
47
- canvas2.width = clampedWidth;
48
- canvas2.height = clampedHeight;
49
- ctx.imageSmoothingEnabled = true;
50
- ctx.imageSmoothingQuality = "high";
51
- ctx.drawImage(image, 0, 0, clampedWidth, clampedHeight);
52
- URL.revokeObjectURL(svgUrl);
53
- resolve(canvas2);
54
- };
55
- image.onerror = () => {
56
- resolve(null);
57
- };
58
- image.src = svgUrl;
59
- });
45
+ const canvas = await renderSvgToCanvas(svgString, clampedWidth, clampedHeight);
60
46
  if (!canvas) return null;
47
+ const outputCanvas = trimPadding > 0 ? trimExtraPadding(canvas, trimPadding * scale * effectiveScale) : { canvas, width: clampedWidth, height: clampedHeight };
61
48
  const blob = await new Promise(
62
- (resolve) => canvas.toBlob(
49
+ (resolve) => outputCanvas.canvas.toBlob(
63
50
  (blob2) => {
64
51
  if (!blob2 || import_debug_flags.debugFlags.throwToBlob.get()) {
65
52
  resolve(null);
@@ -71,13 +58,178 @@ async function getSvgAsImage(svgString, options) {
71
58
  )
72
59
  );
73
60
  if (!blob) return null;
61
+ let resultBlob;
74
62
  if (type === "png") {
75
- const view = new DataView(await blob.arrayBuffer());
76
- return import_utils.PngHelpers.setPhysChunk(view, effectiveScale, {
63
+ resultBlob = import_utils.PngHelpers.setPhysChunk(new DataView(await blob.arrayBuffer()), effectiveScale, {
77
64
  type: "image/" + type
78
65
  });
79
66
  } else {
80
- return blob;
67
+ resultBlob = blob;
68
+ }
69
+ return {
70
+ blob: resultBlob,
71
+ width: outputCanvas.width / effectiveScale,
72
+ height: outputCanvas.height / effectiveScale
73
+ };
74
+ }
75
+ async function renderSvgToCanvas(svgString, width, height) {
76
+ const svgUrl = await import_utils.FileHelpers.blobToDataUrl(new Blob([svgString], { type: "image/svg+xml" }));
77
+ return new Promise((resolve) => {
78
+ const image = (0, import_utils.Image)();
79
+ image.crossOrigin = "anonymous";
80
+ image.onload = async () => {
81
+ if (import_environment.tlenv.isSafari) {
82
+ await (0, import_utils.sleep)(250);
83
+ }
84
+ const canvas = (0, import_dom.getGlobalDocument)().createElement("canvas");
85
+ const ctx = canvas.getContext("2d");
86
+ canvas.width = width;
87
+ canvas.height = height;
88
+ ctx.imageSmoothingEnabled = true;
89
+ ctx.imageSmoothingQuality = "high";
90
+ ctx.drawImage(image, 0, 0, width, height);
91
+ resolve(canvas);
92
+ };
93
+ image.onerror = () => {
94
+ resolve(null);
95
+ };
96
+ image.src = svgUrl;
97
+ });
98
+ }
99
+ function measureContentBounds(canvas, trimPaddingPx) {
100
+ const w = canvas.width;
101
+ const h = canvas.height;
102
+ const ctx = canvas.getContext("2d");
103
+ const extraPx = Math.ceil(trimPaddingPx);
104
+ if (extraPx <= 0 || extraPx * 2 >= w || extraPx * 2 >= h) return null;
105
+ const imageData = ctx.getImageData(0, 0, w, h);
106
+ const data = imageData.data;
107
+ const cornerR = data[0];
108
+ const cornerG = data[1];
109
+ const cornerB = data[2];
110
+ const cornerA = data[3];
111
+ const hasTransparentBackground = cornerA === 0;
112
+ function isContentPixel(offset) {
113
+ if (hasTransparentBackground) {
114
+ return data[offset + 3] > 0;
115
+ } else {
116
+ const a = data[offset + 3];
117
+ if (a !== cornerA) return true;
118
+ const r = data[offset];
119
+ const g = data[offset + 1];
120
+ const b = data[offset + 2];
121
+ return r !== cornerR || g !== cornerG || b !== cornerB;
122
+ }
81
123
  }
124
+ const declaredLeft = extraPx;
125
+ const declaredTop = extraPx;
126
+ const declaredRight = w - extraPx;
127
+ const declaredBottom = h - extraPx;
128
+ let cropTop = declaredTop;
129
+ for (let y = 0; y < declaredTop; y++) {
130
+ let hasContent = false;
131
+ for (let x = 0; x < w; x++) {
132
+ if (isContentPixel((y * w + x) * 4)) {
133
+ hasContent = true;
134
+ break;
135
+ }
136
+ }
137
+ if (hasContent) {
138
+ cropTop = y;
139
+ break;
140
+ }
141
+ }
142
+ let cropBottom = declaredBottom;
143
+ for (let y = h - 1; y >= declaredBottom; y--) {
144
+ let hasContent = false;
145
+ for (let x = 0; x < w; x++) {
146
+ if (isContentPixel((y * w + x) * 4)) {
147
+ hasContent = true;
148
+ break;
149
+ }
150
+ }
151
+ if (hasContent) {
152
+ cropBottom = y + 1;
153
+ break;
154
+ }
155
+ }
156
+ let cropLeft = declaredLeft;
157
+ for (let x = 0; x < declaredLeft; x++) {
158
+ let hasContent = false;
159
+ for (let y = cropTop; y < cropBottom; y++) {
160
+ if (isContentPixel((y * w + x) * 4)) {
161
+ hasContent = true;
162
+ break;
163
+ }
164
+ }
165
+ if (hasContent) {
166
+ cropLeft = x;
167
+ break;
168
+ }
169
+ }
170
+ let cropRight = declaredRight;
171
+ for (let x = w - 1; x >= declaredRight; x--) {
172
+ let hasContent = false;
173
+ for (let y = cropTop; y < cropBottom; y++) {
174
+ if (isContentPixel((y * w + x) * 4)) {
175
+ hasContent = true;
176
+ break;
177
+ }
178
+ }
179
+ if (hasContent) {
180
+ cropRight = x + 1;
181
+ break;
182
+ }
183
+ }
184
+ if (cropLeft === 0 && cropTop === 0 && cropRight === w && cropBottom === h) {
185
+ return null;
186
+ }
187
+ return { cropLeft, cropTop, cropRight, cropBottom };
188
+ }
189
+ function trimExtraPadding(canvas, trimPaddingPx) {
190
+ const w = canvas.width;
191
+ const h = canvas.height;
192
+ const bounds = measureContentBounds(canvas, trimPaddingPx);
193
+ if (!bounds) return { canvas, width: w, height: h };
194
+ const { cropLeft, cropTop, cropRight, cropBottom } = bounds;
195
+ const cropW = cropRight - cropLeft;
196
+ const cropH = cropBottom - cropTop;
197
+ const croppedCanvas = (0, import_dom.getGlobalDocument)().createElement("canvas");
198
+ croppedCanvas.width = cropW;
199
+ croppedCanvas.height = cropH;
200
+ const croppedCtx = croppedCanvas.getContext("2d");
201
+ croppedCtx.drawImage(canvas, cropLeft, cropTop, cropW, cropH, 0, 0, cropW, cropH);
202
+ return { canvas: croppedCanvas, width: cropW, height: cropH };
203
+ }
204
+ async function trimSvgToContent(svgString, options) {
205
+ const { width, height, trimPadding, scale } = options;
206
+ if (trimPadding <= 0) return null;
207
+ const canvasWidth = Math.floor(width);
208
+ const canvasHeight = Math.floor(height);
209
+ if (canvasWidth <= 0 || canvasHeight <= 0) return null;
210
+ const canvas = await renderSvgToCanvas(svgString, canvasWidth, canvasHeight);
211
+ if (!canvas) return null;
212
+ const trimPaddingPx = trimPadding * scale;
213
+ const bounds = measureContentBounds(canvas, trimPaddingPx);
214
+ if (!bounds) return null;
215
+ const { cropLeft, cropTop, cropRight, cropBottom } = bounds;
216
+ const parser = new DOMParser();
217
+ const doc = parser.parseFromString(svgString, "image/svg+xml");
218
+ const svgEl = doc.documentElement;
219
+ const viewBoxAttr = svgEl.getAttribute("viewBox");
220
+ if (!viewBoxAttr) return null;
221
+ const [vbMinX, vbMinY, vbW, vbH] = viewBoxAttr.split(/\s+/).map(Number);
222
+ const newMinX = vbMinX + cropLeft / canvasWidth * vbW;
223
+ const newMinY = vbMinY + cropTop / canvasHeight * vbH;
224
+ const newVbW = (cropRight - cropLeft) / canvasWidth * vbW;
225
+ const newVbH = (cropBottom - cropTop) / canvasHeight * vbH;
226
+ const newWidth = newVbW * scale;
227
+ const newHeight = newVbH * scale;
228
+ svgEl.setAttribute("viewBox", `${newMinX} ${newMinY} ${newVbW} ${newVbH}`);
229
+ svgEl.setAttribute("width", String(newWidth));
230
+ svgEl.setAttribute("height", String(newHeight));
231
+ const serializer = new XMLSerializer();
232
+ const newSvgString = serializer.serializeToString(svgEl);
233
+ return { svg: newSvgString, width: newWidth, height: newHeight };
82
234
  }
83
235
  //# sourceMappingURL=getSvgAsImage.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/exports/getSvgAsImage.ts"],
4
- "sourcesContent": ["import { FileHelpers, Image, PngHelpers, sleep } from '@tldraw/utils'\nimport { tlenv } from '../globals/environment'\nimport { clampToBrowserMaxCanvasSize } from '../utils/browserCanvasMaxSize'\nimport { debugFlags } from '../utils/debug-flags'\n\n/** @public */\nexport async function getSvgAsImage(\n\tsvgString: string,\n\toptions: {\n\t\ttype: 'png' | 'jpeg' | 'webp'\n\t\twidth: number\n\t\theight: number\n\t\tquality?: number\n\t\tpixelRatio?: number\n\t}\n) {\n\tconst { type, width, height, quality = 1, pixelRatio = 2 } = options\n\n\tlet [clampedWidth, clampedHeight] = clampToBrowserMaxCanvasSize(\n\t\twidth * pixelRatio,\n\t\theight * pixelRatio\n\t)\n\tclampedWidth = Math.floor(clampedWidth)\n\tclampedHeight = Math.floor(clampedHeight)\n\tconst effectiveScale = clampedWidth / width\n\n\t// usually we would use `URL.createObjectURL` here, but chrome has a bug where `blob:` URLs of\n\t// SVGs that use <foreignObject> mark the canvas as tainted, where data: ones do not.\n\t// https://issues.chromium.org/issues/41054640\n\tconst svgUrl = await FileHelpers.blobToDataUrl(new Blob([svgString], { type: 'image/svg+xml' }))\n\n\tconst canvas = await new Promise<HTMLCanvasElement | null>((resolve) => {\n\t\tconst image = Image()\n\t\timage.crossOrigin = 'anonymous'\n\n\t\timage.onload = async () => {\n\t\t\t// safari will fire `onLoad` before the fonts in the SVG are\n\t\t\t// actually loaded. just waiting around a while is brittle, but\n\t\t\t// there doesn't seem to be any better solution for now :( see\n\t\t\t// https://bugs.webkit.org/show_bug.cgi?id=219770\n\t\t\tif (tlenv.isSafari) {\n\t\t\t\tawait sleep(250)\n\t\t\t}\n\n\t\t\tconst canvas = document.createElement('canvas') as HTMLCanvasElement\n\t\t\tconst ctx = canvas.getContext('2d')!\n\n\t\t\tcanvas.width = clampedWidth\n\t\t\tcanvas.height = clampedHeight\n\n\t\t\tctx.imageSmoothingEnabled = true\n\t\t\tctx.imageSmoothingQuality = 'high'\n\t\t\tctx.drawImage(image, 0, 0, clampedWidth, clampedHeight)\n\n\t\t\tURL.revokeObjectURL(svgUrl)\n\n\t\t\tresolve(canvas)\n\t\t}\n\n\t\timage.onerror = () => {\n\t\t\tresolve(null)\n\t\t}\n\n\t\timage.src = svgUrl\n\t})\n\n\tif (!canvas) return null\n\n\tconst blob = await new Promise<Blob | null>((resolve) =>\n\t\tcanvas.toBlob(\n\t\t\t(blob) => {\n\t\t\t\tif (!blob || debugFlags.throwToBlob.get()) {\n\t\t\t\t\tresolve(null)\n\t\t\t\t}\n\t\t\t\tresolve(blob)\n\t\t\t},\n\t\t\t'image/' + type,\n\t\t\tquality\n\t\t)\n\t)\n\n\tif (!blob) return null\n\n\tif (type === 'png') {\n\t\tconst view = new DataView(await blob.arrayBuffer())\n\t\treturn PngHelpers.setPhysChunk(view, effectiveScale, {\n\t\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AI,CAACA,SAAQ,8BAAW,YAAY,IAAI,GAAG;AAC1C,kBAAQ,IAAI;AAAA,QACb;AACA,gBAAQA,KAAI;AAAA,MACb;AAAA,MACA,WAAW;AAAA,MACX;AAAA,IACD;AAAA,EACD;AAEA,MAAI,CAAC,KAAM,QAAO;AAElB,MAAI,SAAS,OAAO;AACnB,UAAM,OAAO,IAAI,SAAS,MAAM,KAAK,YAAY,CAAC;AAClD,WAAO,wBAAW,aAAa,MAAM,gBAAgB;AAAA,MACpD,MAAM,WAAW;AAAA,IAClB,CAAC;AAAA,EACF,OAAO;AACN,WAAO;AAAA,EACR;AACD;",
6
- "names": ["canvas", "blob"]
4
+ "sourcesContent": ["import { FileHelpers, Image, PngHelpers, sleep } from '@tldraw/utils'\nimport { tlenv } from '../globals/environment'\nimport { clampToBrowserMaxCanvasSize } from '../utils/browserCanvasMaxSize'\nimport { debugFlags } from '../utils/debug-flags'\nimport { getGlobalDocument } from '../utils/dom'\n\n/** @public */\nexport async function getSvgAsImage(\n\tsvgString: string,\n\toptions: {\n\t\ttype: 'png' | 'jpeg' | 'webp'\n\t\twidth: number\n\t\theight: number\n\t\tquality?: number\n\t\tpixelRatio?: number\n\t}\n) {\n\tconst result = await getSvgAsImageWithOptions(svgString, options)\n\treturn result?.blob ?? null\n}\n\n/** @internal */\nexport async function getSvgAsImageWithOptions(\n\tsvgString: string,\n\toptions: {\n\t\ttype: 'png' | 'jpeg' | 'webp'\n\t\twidth: number\n\t\theight: number\n\t\tquality?: number\n\t\tpixelRatio?: number\n\t\ttrimPadding?: number\n\t\tscale?: number\n\t}\n): Promise<{ blob: Blob; width: number; height: number } | null> {\n\tconst { type, width, height, quality = 1, pixelRatio = 2, trimPadding = 0, scale = 1 } = options\n\n\tif (width <= 0 || height <= 0) return null\n\n\tlet [clampedWidth, clampedHeight] = clampToBrowserMaxCanvasSize(\n\t\twidth * pixelRatio,\n\t\theight * pixelRatio\n\t)\n\tclampedWidth = Math.floor(clampedWidth)\n\tclampedHeight = Math.floor(clampedHeight)\n\tconst effectiveScale = clampedWidth / width\n\n\tconst canvas = await renderSvgToCanvas(svgString, clampedWidth, clampedHeight)\n\n\tif (!canvas) return null\n\n\t// If we rendered with extra padding to capture visual overflow, trim it now\n\tconst outputCanvas =\n\t\ttrimPadding > 0\n\t\t\t? trimExtraPadding(canvas, trimPadding * scale * effectiveScale)\n\t\t\t: { canvas, width: clampedWidth, height: clampedHeight }\n\n\tconst blob = await new Promise<Blob | null>((resolve) =>\n\t\toutputCanvas.canvas.toBlob(\n\t\t\t(blob) => {\n\t\t\t\tif (!blob || debugFlags.throwToBlob.get()) {\n\t\t\t\t\tresolve(null)\n\t\t\t\t}\n\t\t\t\tresolve(blob)\n\t\t\t},\n\t\t\t'image/' + type,\n\t\t\tquality\n\t\t)\n\t)\n\n\tif (!blob) return null\n\n\tlet resultBlob: Blob\n\tif (type === 'png') {\n\t\tresultBlob = PngHelpers.setPhysChunk(new DataView(await blob.arrayBuffer()), effectiveScale, {\n\t\t\ttype: 'image/' + type,\n\t\t})\n\t} else {\n\t\tresultBlob = blob\n\t}\n\n\treturn {\n\t\tblob: resultBlob,\n\t\twidth: outputCanvas.width / effectiveScale,\n\t\theight: outputCanvas.height / effectiveScale,\n\t}\n}\n\nasync function renderSvgToCanvas(\n\tsvgString: string,\n\twidth: number,\n\theight: number\n): Promise<HTMLCanvasElement | null> {\n\t// usually we would use `URL.createObjectURL` here, but chrome has a bug where `blob:` URLs of\n\t// SVGs that use <foreignObject> mark the canvas as tainted, where data: ones do not.\n\t// https://issues.chromium.org/issues/41054640\n\tconst svgUrl = await FileHelpers.blobToDataUrl(new Blob([svgString], { type: 'image/svg+xml' }))\n\n\treturn new Promise<HTMLCanvasElement | null>((resolve) => {\n\t\tconst image = Image()\n\t\timage.crossOrigin = 'anonymous'\n\n\t\timage.onload = async () => {\n\t\t\t// safari will fire `onLoad` before the fonts in the SVG are\n\t\t\t// actually loaded. just waiting around a while is brittle, but\n\t\t\t// there doesn't seem to be any better solution for now :( see\n\t\t\t// https://bugs.webkit.org/show_bug.cgi?id=219770\n\t\t\tif (tlenv.isSafari) {\n\t\t\t\tawait sleep(250)\n\t\t\t}\n\n\t\t\tconst canvas = getGlobalDocument().createElement('canvas') as HTMLCanvasElement\n\t\t\tconst ctx = canvas.getContext('2d')!\n\t\t\tcanvas.width = width\n\t\t\tcanvas.height = height\n\t\t\tctx.imageSmoothingEnabled = true\n\t\t\tctx.imageSmoothingQuality = 'high'\n\t\t\tctx.drawImage(image, 0, 0, width, height)\n\t\t\tresolve(canvas)\n\t\t}\n\n\t\timage.onerror = () => {\n\t\t\tresolve(null)\n\t\t}\n\n\t\timage.src = svgUrl\n\t})\n}\n\n/**\n * Scans a canvas from each edge inward (up to trimPaddingPx pixels) to find\n * the first row/column containing non-background content. Returns the crop\n * rectangle in canvas pixel coordinates, or null if no trimming is needed.\n */\nfunction measureContentBounds(\n\tcanvas: HTMLCanvasElement,\n\ttrimPaddingPx: number\n): { cropLeft: number; cropTop: number; cropRight: number; cropBottom: number } | null {\n\tconst w = canvas.width\n\tconst h = canvas.height\n\tconst ctx = canvas.getContext('2d')!\n\n\tconst extraPx = Math.ceil(trimPaddingPx)\n\n\t// Nothing to trim if the extra padding is negligible or larger than half the canvas\n\t// (extraPx * 2 >= w means declaredRight <= declaredLeft, producing zero/negative crop)\n\tif (extraPx <= 0 || extraPx * 2 >= w || extraPx * 2 >= h) return null\n\n\tconst imageData = ctx.getImageData(0, 0, w, h)\n\tconst data = imageData.data\n\n\t// Determine how to detect \"empty\" pixels.\n\t// Sample the corner pixel to detect the background color.\n\tconst cornerR = data[0]\n\tconst cornerG = data[1]\n\tconst cornerB = data[2]\n\tconst cornerA = data[3]\n\tconst hasTransparentBackground = cornerA === 0\n\n\tfunction isContentPixel(offset: number): boolean {\n\t\tif (hasTransparentBackground) {\n\t\t\t// For transparent background, any non-transparent pixel is content\n\t\t\treturn data[offset + 3] > 0\n\t\t} else {\n\t\t\t// For opaque background, look for pixels that differ from the background\n\t\t\tconst a = data[offset + 3]\n\t\t\tif (a !== cornerA) return true\n\t\t\tconst r = data[offset]\n\t\t\tconst g = data[offset + 1]\n\t\t\tconst b = data[offset + 2]\n\t\t\treturn r !== cornerR || g !== cornerG || b !== cornerB\n\t\t}\n\t}\n\n\t// The declared bounds area (content area without extra padding)\n\tconst declaredLeft = extraPx\n\tconst declaredTop = extraPx\n\tconst declaredRight = w - extraPx\n\tconst declaredBottom = h - extraPx\n\n\t// Scan from top edge inward: find first row with content or declared bounds\n\tlet cropTop = declaredTop\n\tfor (let y = 0; y < declaredTop; y++) {\n\t\tlet hasContent = false\n\t\tfor (let x = 0; x < w; x++) {\n\t\t\tif (isContentPixel((y * w + x) * 4)) {\n\t\t\t\thasContent = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif (hasContent) {\n\t\t\tcropTop = y\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Scan from bottom edge inward\n\tlet cropBottom = declaredBottom\n\tfor (let y = h - 1; y >= declaredBottom; y--) {\n\t\tlet hasContent = false\n\t\tfor (let x = 0; x < w; x++) {\n\t\t\tif (isContentPixel((y * w + x) * 4)) {\n\t\t\t\thasContent = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif (hasContent) {\n\t\t\tcropBottom = y + 1\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Scan from left edge inward\n\tlet cropLeft = declaredLeft\n\tfor (let x = 0; x < declaredLeft; x++) {\n\t\tlet hasContent = false\n\t\tfor (let y = cropTop; y < cropBottom; y++) {\n\t\t\tif (isContentPixel((y * w + x) * 4)) {\n\t\t\t\thasContent = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif (hasContent) {\n\t\t\tcropLeft = x\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Scan from right edge inward\n\tlet cropRight = declaredRight\n\tfor (let x = w - 1; x >= declaredRight; x--) {\n\t\tlet hasContent = false\n\t\tfor (let y = cropTop; y < cropBottom; y++) {\n\t\t\tif (isContentPixel((y * w + x) * 4)) {\n\t\t\t\thasContent = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif (hasContent) {\n\t\t\tcropRight = x + 1\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If no trimming needed (content fills or exceeds the entire render area)\n\tif (cropLeft === 0 && cropTop === 0 && cropRight === w && cropBottom === h) {\n\t\treturn null\n\t}\n\n\treturn { cropLeft, cropTop, cropRight, cropBottom }\n}\n\n/**\n * Trims extra padding from a canvas by scanning from each edge inward to find\n * non-transparent (or non-background) pixels. Stops at either content pixels or\n * the declared bounds (the area without extra padding).\n */\nfunction trimExtraPadding(\n\tcanvas: HTMLCanvasElement,\n\ttrimPaddingPx: number\n): { canvas: HTMLCanvasElement; width: number; height: number } {\n\tconst w = canvas.width\n\tconst h = canvas.height\n\n\tconst bounds = measureContentBounds(canvas, trimPaddingPx)\n\tif (!bounds) return { canvas, width: w, height: h }\n\n\tconst { cropLeft, cropTop, cropRight, cropBottom } = bounds\n\tconst cropW = cropRight - cropLeft\n\tconst cropH = cropBottom - cropTop\n\n\t// Create a new cropped canvas\n\tconst croppedCanvas = getGlobalDocument().createElement('canvas')\n\tcroppedCanvas.width = cropW\n\tcroppedCanvas.height = cropH\n\tconst croppedCtx = croppedCanvas.getContext('2d')!\n\tcroppedCtx.drawImage(canvas, cropLeft, cropTop, cropW, cropH, 0, 0, cropW, cropH)\n\n\treturn { canvas: croppedCanvas, width: cropW, height: cropH }\n}\n\n/**\n * Trims an SVG string to its visual content bounds by rendering it to a\n * temporary canvas, measuring the actual content area, then adjusting the\n * SVG's viewBox and dimensions to match.\n *\n * @param svgString - The SVG string to trim.\n * @param options - Options for trimming.\n * @returns The trimmed SVG string with updated dimensions, or null if no trimming was needed.\n *\n * @internal\n */\nexport async function trimSvgToContent(\n\tsvgString: string,\n\toptions: {\n\t\twidth: number\n\t\theight: number\n\t\ttrimPadding: number\n\t\tscale: number\n\t}\n): Promise<{ svg: string; width: number; height: number } | null> {\n\tconst { width, height, trimPadding, scale } = options\n\n\tif (trimPadding <= 0) return null\n\n\t// Render SVG to a temporary canvas at 1:1 pixel ratio\n\tconst canvasWidth = Math.floor(width)\n\tconst canvasHeight = Math.floor(height)\n\n\tif (canvasWidth <= 0 || canvasHeight <= 0) return null\n\n\tconst canvas = await renderSvgToCanvas(svgString, canvasWidth, canvasHeight)\n\n\tif (!canvas) return null\n\n\t// Measure content bounds on the canvas\n\tconst trimPaddingPx = trimPadding * scale\n\tconst bounds = measureContentBounds(canvas, trimPaddingPx)\n\tif (!bounds) return null\n\n\tconst { cropLeft, cropTop, cropRight, cropBottom } = bounds\n\n\t// Parse the SVG to get the current viewBox\n\tconst parser = new DOMParser()\n\tconst doc = parser.parseFromString(svgString, 'image/svg+xml')\n\tconst svgEl = doc.documentElement\n\n\tconst viewBoxAttr = svgEl.getAttribute('viewBox')\n\tif (!viewBoxAttr) return null\n\n\tconst [vbMinX, vbMinY, vbW, vbH] = viewBoxAttr.split(/\\s+/).map(Number)\n\n\t// Convert canvas pixel coords to viewBox coords\n\tconst newMinX = vbMinX + (cropLeft / canvasWidth) * vbW\n\tconst newMinY = vbMinY + (cropTop / canvasHeight) * vbH\n\tconst newVbW = ((cropRight - cropLeft) / canvasWidth) * vbW\n\tconst newVbH = ((cropBottom - cropTop) / canvasHeight) * vbH\n\n\t// New SVG dimensions maintain the same scale\n\tconst newWidth = newVbW * scale\n\tconst newHeight = newVbH * scale\n\n\t// Update SVG attributes\n\tsvgEl.setAttribute('viewBox', `${newMinX} ${newMinY} ${newVbW} ${newVbH}`)\n\tsvgEl.setAttribute('width', String(newWidth))\n\tsvgEl.setAttribute('height', String(newHeight))\n\n\t// Serialize back\n\tconst serializer = new XMLSerializer()\n\tconst newSvgString = serializer.serializeToString(svgEl)\n\n\treturn { svg: newSvgString, width: newWidth, height: newHeight }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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;AAGpB,QAAM,gBAAgB,cAAc;AACpC,QAAM,SAAS,qBAAqB,QAAQ,aAAa;AACzD,MAAI,CAAC,OAAQ,QAAO;AAEpB,QAAM,EAAE,UAAU,SAAS,WAAW,WAAW,IAAI;AAGrD,QAAM,SAAS,IAAI,UAAU;AAC7B,QAAM,MAAM,OAAO,gBAAgB,WAAW,eAAe;AAC7D,QAAM,QAAQ,IAAI;AAElB,QAAM,cAAc,MAAM,aAAa,SAAS;AAChD,MAAI,CAAC,YAAa,QAAO;AAEzB,QAAM,CAAC,QAAQ,QAAQ,KAAK,GAAG,IAAI,YAAY,MAAM,KAAK,EAAE,IAAI,MAAM;AAGtE,QAAM,UAAU,SAAU,WAAW,cAAe;AACpD,QAAM,UAAU,SAAU,UAAU,eAAgB;AACpD,QAAM,UAAW,YAAY,YAAY,cAAe;AACxD,QAAM,UAAW,aAAa,WAAW,eAAgB;AAGzD,QAAM,WAAW,SAAS;AAC1B,QAAM,YAAY,SAAS;AAG3B,QAAM,aAAa,WAAW,GAAG,OAAO,IAAI,OAAO,IAAI,MAAM,IAAI,MAAM,EAAE;AACzE,QAAM,aAAa,SAAS,OAAO,QAAQ,CAAC;AAC5C,QAAM,aAAa,UAAU,OAAO,SAAS,CAAC;AAG9C,QAAM,aAAa,IAAI,cAAc;AACrC,QAAM,eAAe,WAAW,kBAAkB,KAAK;AAEvD,SAAO,EAAE,KAAK,cAAc,OAAO,UAAU,QAAQ,UAAU;AAChE;",
6
+ "names": ["blob"]
7
7
  }
@@ -38,29 +38,40 @@ var import_Box = require("../primitives/Box");
38
38
  var import_Mat = require("../primitives/Mat");
39
39
  var import_ExportDelay = require("./ExportDelay");
40
40
  function getSvgJsx(editor, ids, opts = {}) {
41
- if (!window.document) throw Error("No document");
41
+ const editorDocument = editor.getContainerDocument();
42
+ if (!editorDocument) throw Error("No document");
42
43
  const {
43
44
  scale = 1,
44
45
  // should we include the background in the export? or is it transparent?
45
46
  background = editor.getInstanceState().exportBackground,
46
- padding = editor.options.defaultSvgPadding,
47
47
  preserveAspectRatio
48
48
  } = opts;
49
+ const isAutoTrim = typeof opts.padding !== "number";
50
+ const renderPadding = typeof opts.padding === "number" ? opts.padding : editor.options.defaultSvgPadding;
49
51
  const isDarkMode = opts.darkMode ?? editor.user.getIsDarkMode();
50
52
  const shapeIdsToInclude = editor.getShapeAndDescendantIds(ids);
51
53
  const renderingShapes = editor.getUnorderedRenderingShapes(false).filter(({ id }) => shapeIdsToInclude.has(id));
52
54
  const singleFrameShapeId = ids.length === 1 && editor.isShapeOfType(editor.getShape(ids[0]), "frame") ? ids[0] : null;
53
55
  let bbox = null;
56
+ let paddingWasApplied = false;
54
57
  if (opts.bounds) {
55
- bbox = opts.bounds.clone().expandBy(padding);
58
+ bbox = isAutoTrim ? opts.bounds.clone() : opts.bounds.clone().expandBy(renderPadding);
56
59
  } else {
57
- bbox = getExportDefaultBounds(editor, renderingShapes, padding, singleFrameShapeId);
60
+ const result = getExportDefaultBounds(
61
+ editor,
62
+ renderingShapes,
63
+ renderPadding,
64
+ singleFrameShapeId
65
+ );
66
+ bbox = result.box;
67
+ paddingWasApplied = result.paddingApplied;
58
68
  }
59
69
  if (!bbox) return;
70
+ const trimPadding = isAutoTrim && paddingWasApplied ? renderPadding : 0;
60
71
  const w = bbox.width * scale;
61
72
  const h = bbox.height * scale;
62
73
  try {
63
- document.body.focus?.();
74
+ editorDocument.body.focus?.();
64
75
  } catch {
65
76
  }
66
77
  const exportDelay = new import_ExportDelay.ExportDelay(editor.options.maxExportDelayMs);
@@ -82,7 +93,7 @@ function getSvgJsx(editor, ids, opts = {}) {
82
93
  waitUntil: exportDelay.waitUntil
83
94
  }
84
95
  );
85
- return { jsx: svg, width: w, height: h, exportDelay };
96
+ return { jsx: svg, width: w, height: h, exportDelay, trimPadding };
86
97
  }
87
98
  function getExportDefaultBounds(editor, renderingShapes, padding, singleFrameShapeId) {
88
99
  let isBoundedByContainer = false;
@@ -107,11 +118,12 @@ function getExportDefaultBounds(editor, renderingShapes, padding, singleFrameSha
107
118
  bbox = maskedPageBounds.clone();
108
119
  }
109
120
  }
110
- if (!bbox) return null;
111
- if (!singleFrameShapeId && !isBoundedByContainer) {
121
+ if (!bbox) return { box: null, paddingApplied: false };
122
+ const paddingApplied = !singleFrameShapeId && !isBoundedByContainer;
123
+ if (paddingApplied) {
112
124
  bbox.expandBy(padding);
113
125
  }
114
- return bbox;
126
+ return { box: bbox, paddingApplied };
115
127
  }
116
128
  function SvgExport({
117
129
  editor,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/exports/getSvgJsx.tsx"],
4
- "sourcesContent": ["import { useAtom, useValue } from '@tldraw/state-react'\nimport {\n\tTLFrameShape,\n\tTLShape,\n\tTLShapeId,\n\tgetColorValue,\n\tgetDefaultColorTheme,\n} from '@tldraw/tlschema'\nimport { hasOwnProperty, promiseWithResolve, uniqueId } from '@tldraw/utils'\nimport {\n\tComponentType,\n\tFragment,\n\tReactElement,\n\tReactNode,\n\tuseEffect,\n\tuseLayoutEffect,\n\tuseMemo,\n\tuseRef,\n} from 'react'\nimport { flushSync } from 'react-dom'\nimport { ErrorBoundary } from '../components/ErrorBoundary'\nimport { InnerShape, InnerShapeBackground } from '../components/Shape'\nimport type { Editor, TLRenderingShape } from '../editor/Editor'\nimport { TLFontFace } from '../editor/managers/FontManager/FontManager'\nimport { ShapeUtil } from '../editor/shapes/ShapeUtil'\nimport {\n\tSvgExportContext,\n\tSvgExportContextProvider,\n\tSvgExportDef,\n} from '../editor/types/SvgExportContext'\nimport { TLImageExportOptions } from '../editor/types/misc-types'\nimport { useEditor } from '../hooks/useEditor'\nimport { useEvent } from '../hooks/useEvent'\nimport { suffixSafeId, useUniqueSafeId } from '../hooks/useSafeId'\nimport { Box } from '../primitives/Box'\nimport { Mat } from '../primitives/Mat'\nimport { ExportDelay } from './ExportDelay'\n\nexport function getSvgJsx(editor: Editor, ids: TLShapeId[], opts: TLImageExportOptions = {}) {\n\tif (!window.document) throw Error('No document')\n\n\tconst {\n\t\tscale = 1,\n\t\t// should we include the background in the export? or is it transparent?\n\t\tbackground = editor.getInstanceState().exportBackground,\n\t\tpadding = editor.options.defaultSvgPadding,\n\t\tpreserveAspectRatio,\n\t} = opts\n\n\tconst isDarkMode = opts.darkMode ?? editor.user.getIsDarkMode()\n\n\t// ---Figure out which shapes we need to include\n\tconst shapeIdsToInclude = editor.getShapeAndDescendantIds(ids)\n\tconst renderingShapes = editor\n\t\t.getUnorderedRenderingShapes(false)\n\t\t.filter(({ id }) => shapeIdsToInclude.has(id))\n\n\t// --- Common bounding box of all shapes\n\tconst singleFrameShapeId =\n\t\tids.length === 1 && editor.isShapeOfType(editor.getShape(ids[0])!, 'frame') ? ids[0] : null\n\n\tlet bbox: null | Box = null\n\tif (opts.bounds) {\n\t\tbbox = opts.bounds.clone().expandBy(padding)\n\t} else {\n\t\tbbox = getExportDefaultBounds(editor, renderingShapes, padding, singleFrameShapeId)\n\t}\n\n\t// no unmasked shapes to export\n\tif (!bbox) return\n\n\t// We want the svg image to be BIGGER THAN USUAL to account for image quality\n\tconst w = bbox.width * scale\n\tconst h = bbox.height * scale\n\n\ttry {\n\t\tdocument.body.focus?.() // weird but necessary\n\t} catch {\n\t\t// not implemented\n\t}\n\n\tconst exportDelay = new ExportDelay(editor.options.maxExportDelayMs)\n\n\tconst initialEffectPromise = promiseWithResolve<void>()\n\texportDelay.waitUntil(initialEffectPromise)\n\n\tconst svg = (\n\t\t<SvgExport\n\t\t\teditor={editor}\n\t\t\tpreserveAspectRatio={preserveAspectRatio}\n\t\t\tscale={scale}\n\t\t\tpixelRatio={opts.pixelRatio ?? null}\n\t\t\tbbox={bbox}\n\t\t\tbackground={background}\n\t\t\tsingleFrameShapeId={singleFrameShapeId}\n\t\t\tisDarkMode={isDarkMode}\n\t\t\trenderingShapes={renderingShapes}\n\t\t\tonMount={initialEffectPromise.resolve}\n\t\t\twaitUntil={exportDelay.waitUntil}\n\t\t>\n\t\t\t{}\n\t\t</SvgExport>\n\t)\n\n\treturn { jsx: svg, width: w, height: h, exportDelay }\n}\n\n/**\n * Calculates the default bounds for an SVG export. This function handles:\n * 1. Computing masked page bounds for each shape\n * 2. Container logic: if a shape is marked as an export bounds container and it\n * contains all other shapes, use its bounds and skip padding\n * 3. Otherwise, create a union of all shape bounds and apply padding\n *\n * The container logic is useful for cases like annotating on an image - if the image\n * contains all annotations, we want to export exactly the image bounds without extra padding.\n *\n * @param editor - The editor instance\n * @param renderingShapes - The shapes to include in the export\n * @param padding - Padding to add around the bounds (only applied if no container bounds)\n * @param singleFrameShapeId - If exporting a single frame, this is its ID (skips padding)\n * @returns The calculated bounds box, or null if no shapes to export\n */\nexport function getExportDefaultBounds(\n\teditor: Editor,\n\trenderingShapes: TLRenderingShape[],\n\tpadding: number,\n\tsingleFrameShapeId: TLShapeId | null\n) {\n\tlet isBoundedByContainer = false\n\tlet bbox: null | Box = null\n\n\tfor (const { id } of renderingShapes) {\n\t\tconst maskedPageBounds = editor.getShapeMaskedPageBounds(id)\n\t\tif (!maskedPageBounds) continue\n\n\t\t// Check if this shape is an export bounds container (e.g., an image being annotated)\n\t\tconst shape = editor.getShape(id)!\n\t\tconst isContainer = editor.getShapeUtil(shape).isExportBoundsContainer(shape)\n\n\t\tif (bbox) {\n\t\t\t// Container logic: if this is a container and it contains all shapes processed so far,\n\t\t\t// use the container's bounds instead of the union. This prevents extra padding around\n\t\t\t// things like annotated images.\n\t\t\tif (isContainer && Box.ContainsApproximately(maskedPageBounds, bbox)) {\n\t\t\t\tisBoundedByContainer = true\n\t\t\t\tbbox = maskedPageBounds.clone()\n\t\t\t} else {\n\t\t\t\t// If we were previously bounded by a container but this shape extends outside it,\n\t\t\t\t// we're no longer bounded by a container\n\t\t\t\tif (isBoundedByContainer && !Box.ContainsApproximately(bbox, maskedPageBounds)) {\n\t\t\t\t\tisBoundedByContainer = false\n\t\t\t\t}\n\t\t\t\t// Expand the bounding box to include this shape\n\t\t\t\tbbox.union(maskedPageBounds)\n\t\t\t}\n\t\t} else {\n\t\t\t// First shape sets the initial bounds\n\t\t\tisBoundedByContainer = isContainer\n\t\t\tbbox = maskedPageBounds.clone()\n\t\t}\n\t}\n\n\t// No unmasked shapes to export\n\tif (!bbox) return null\n\n\t// Only apply padding if:\n\t// - Not exporting a single frame (frames have their own padding rules)\n\t// - Not bounded by a container (containers define their own bounds precisely)\n\tif (!singleFrameShapeId && !isBoundedByContainer) {\n\t\tbbox.expandBy(padding)\n\t}\n\n\treturn bbox\n}\n\nfunction SvgExport({\n\teditor,\n\tpreserveAspectRatio,\n\tscale,\n\tpixelRatio,\n\tbbox,\n\tbackground,\n\tsingleFrameShapeId,\n\tisDarkMode,\n\trenderingShapes,\n\tonMount,\n\twaitUntil,\n}: {\n\teditor: Editor\n\tpreserveAspectRatio?: string\n\tscale: number\n\tpixelRatio: number | null\n\tbbox: Box\n\tbackground: boolean\n\tsingleFrameShapeId: TLShapeId | null\n\tisDarkMode: boolean\n\trenderingShapes: TLRenderingShape[]\n\tonMount(): void\n\twaitUntil(promise: Promise<void>): void\n}) {\n\tconst masksId = useUniqueSafeId()\n\tconst theme = getDefaultColorTheme({ isDarkMode })\n\n\tconst stateAtom = useAtom<{\n\t\tdefsById: Record<\n\t\t\tstring,\n\t\t\t{ pending: false; element: ReactNode } | { pending: true; element: Promise<ReactNode> }\n\t\t>\n\t\tshapeElements: ReactElement[] | null\n\t}>('export state', { defsById: {}, shapeElements: null })\n\tconst { defsById, shapeElements } = useValue(stateAtom)\n\n\tconst addExportDef = useEvent((def: SvgExportDef) => {\n\t\tstateAtom.update((state) => {\n\t\t\tif (hasOwnProperty(state.defsById, def.key)) return state\n\n\t\t\tconst promise = Promise.resolve(def.getElement())\n\t\t\twaitUntil(\n\t\t\t\tpromise.then((result) => {\n\t\t\t\t\tstateAtom.update((state) => ({\n\t\t\t\t\t\t...state,\n\t\t\t\t\t\tdefsById: { ...state.defsById, [def.key]: { pending: false, element: result } },\n\t\t\t\t\t}))\n\t\t\t\t})\n\t\t\t)\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tdefsById: { ...state.defsById, [def.key]: { pending: true, element: promise } },\n\t\t\t}\n\t\t})\n\t})\n\n\tconst exportContext = useMemo(\n\t\t(): SvgExportContext => ({\n\t\t\tisDarkMode,\n\t\t\twaitUntil,\n\t\t\taddExportDef,\n\t\t\tscale,\n\t\t\tpixelRatio,\n\t\t\tasync resolveAssetUrl(assetId, width) {\n\t\t\t\tconst asset = editor.getAsset(assetId)\n\t\t\t\tif (!asset || (asset.type !== 'image' && asset.type !== 'video')) return null\n\n\t\t\t\treturn await editor.resolveAssetUrl(assetId, {\n\t\t\t\t\tscreenScale: scale * (width / asset.props.w),\n\t\t\t\t\tshouldResolveToOriginal: pixelRatio === null,\n\t\t\t\t\tdpr: pixelRatio ?? undefined,\n\t\t\t\t})\n\t\t\t},\n\t\t}),\n\t\t[isDarkMode, waitUntil, addExportDef, scale, pixelRatio, editor]\n\t)\n\n\tconst didRenderRef = useRef(false)\n\tuseLayoutEffect(() => {\n\t\tif (didRenderRef.current) {\n\t\t\tthrow new Error('SvgExport should only render once - do not use with react strict mode')\n\t\t}\n\t\tdidRenderRef.current = true\n\t\t;(async () => {\n\t\t\tconst shapeDefs: Record<string, { pending: false; element: ReactElement }> = {}\n\n\t\t\t// Then render everything. The shapes with assets should all hit the cache\n\t\t\tconst unorderedShapeElementPromises = renderingShapes.map(\n\t\t\t\tasync ({ id, opacity, index, backgroundIndex }) => {\n\t\t\t\t\t// Don't render the frame if we're only exporting a single frame and it's children\n\t\t\t\t\tif (id === singleFrameShapeId) return []\n\n\t\t\t\t\tconst shape = editor.getShape(id)!\n\n\t\t\t\t\tif (editor.isShapeOfType(shape, 'group')) return []\n\n\t\t\t\t\tconst elements = []\n\t\t\t\t\tconst util = editor.getShapeUtil(shape)\n\n\t\t\t\t\tif (util.toSvg || util.toBackgroundSvg) {\n\t\t\t\t\t\t// If the shape has any sort of custom svg export, let's use that.\n\t\t\t\t\t\tconst [toSvgResult, toBackgroundSvgResult] = await Promise.all([\n\t\t\t\t\t\t\tutil.toSvg?.(shape, exportContext),\n\t\t\t\t\t\t\tutil.toBackgroundSvg?.(shape, exportContext),\n\t\t\t\t\t\t])\n\n\t\t\t\t\t\tconst pageTransform = editor.getShapePageTransform(shape)\n\t\t\t\t\t\tlet pageTransformString = pageTransform!.toCssString()\n\t\t\t\t\t\tlet scale = 1\n\t\t\t\t\t\tif ('scale' in shape.props) {\n\t\t\t\t\t\t\tif (shape.props.scale !== 1) {\n\t\t\t\t\t\t\t\tscale = shape.props.scale\n\t\t\t\t\t\t\t\tpageTransformString = `${pageTransformString} scale(${shape.props.scale}, ${shape.props.scale})`\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Create svg mask if shape has a frame as parent\n\t\t\t\t\t\tconst pageMask = editor.getShapeMask(shape.id)\n\t\t\t\t\t\tconst shapeMask = pageMask\n\t\t\t\t\t\t\t? Mat.From(Mat.Inverse(pageTransform)).applyToPoints(pageMask)\n\t\t\t\t\t\t\t: null\n\t\t\t\t\t\tconst shapeMaskId = suffixSafeId(masksId, shape.id)\n\t\t\t\t\t\tif (shapeMask) {\n\t\t\t\t\t\t\t// Create a clip path and add it to defs\n\t\t\t\t\t\t\tshapeDefs[shapeMaskId] = {\n\t\t\t\t\t\t\t\tpending: false,\n\t\t\t\t\t\t\t\telement: (\n\t\t\t\t\t\t\t\t\t<clipPath id={shapeMaskId}>\n\t\t\t\t\t\t\t\t\t\t{/* Create a polyline mask that does the clipping */}\n\t\t\t\t\t\t\t\t\t\t<path\n\t\t\t\t\t\t\t\t\t\t\td={`M${shapeMask.map(({ x, y }) => `${x / scale},${y / scale}`).join('L')}Z`}\n\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t</clipPath>\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (toSvgResult) {\n\t\t\t\t\t\t\telements.push({\n\t\t\t\t\t\t\t\tzIndex: index,\n\t\t\t\t\t\t\t\telement: (\n\t\t\t\t\t\t\t\t\t<g\n\t\t\t\t\t\t\t\t\t\tkey={`fg_${shape.id}`}\n\t\t\t\t\t\t\t\t\t\ttransform={pageTransformString}\n\t\t\t\t\t\t\t\t\t\topacity={opacity}\n\t\t\t\t\t\t\t\t\t\tclipPath={pageMask ? `url(#${shapeMaskId})` : undefined}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{toSvgResult}\n\t\t\t\t\t\t\t\t\t</g>\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (toBackgroundSvgResult) {\n\t\t\t\t\t\t\telements.push({\n\t\t\t\t\t\t\t\tzIndex: backgroundIndex,\n\t\t\t\t\t\t\t\telement: (\n\t\t\t\t\t\t\t\t\t<g\n\t\t\t\t\t\t\t\t\t\tkey={`bg_${shape.id}`}\n\t\t\t\t\t\t\t\t\t\ttransform={pageTransformString}\n\t\t\t\t\t\t\t\t\t\topacity={opacity}\n\t\t\t\t\t\t\t\t\t\tclipPath={pageMask ? `url(#${shapeMaskId})` : undefined}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{toBackgroundSvgResult}\n\t\t\t\t\t\t\t\t\t</g>\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// If the shape doesn't have a custom svg export, we'll use its normal HTML\n\t\t\t\t\t\t// renderer in a foreignObject.\n\t\t\t\t\t\telements.push({\n\t\t\t\t\t\t\tzIndex: index,\n\t\t\t\t\t\t\telement: (\n\t\t\t\t\t\t\t\t<ForeignObjectShape\n\t\t\t\t\t\t\t\t\tkey={`fg_${shape.id}`}\n\t\t\t\t\t\t\t\t\tshape={shape}\n\t\t\t\t\t\t\t\t\tutil={util}\n\t\t\t\t\t\t\t\t\tcomponent={InnerShape}\n\t\t\t\t\t\t\t\t\tclassName=\"tl-shape\"\n\t\t\t\t\t\t\t\t\tbbox={bbox}\n\t\t\t\t\t\t\t\t\topacity={opacity}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t})\n\n\t\t\t\t\t\tif (util.backgroundComponent) {\n\t\t\t\t\t\t\telements.push({\n\t\t\t\t\t\t\t\tzIndex: backgroundIndex,\n\t\t\t\t\t\t\t\telement: (\n\t\t\t\t\t\t\t\t\t<ForeignObjectShape\n\t\t\t\t\t\t\t\t\t\tkey={`bg_${shape.id}`}\n\t\t\t\t\t\t\t\t\t\tshape={shape}\n\t\t\t\t\t\t\t\t\t\tutil={util}\n\t\t\t\t\t\t\t\t\t\tcomponent={InnerShapeBackground}\n\t\t\t\t\t\t\t\t\t\tclassName=\"tl-shape tl-shape-background\"\n\t\t\t\t\t\t\t\t\t\tbbox={bbox}\n\t\t\t\t\t\t\t\t\t\topacity={opacity}\n\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn elements\n\t\t\t\t}\n\t\t\t)\n\n\t\t\tconst unorderedShapeElements = (await Promise.all(unorderedShapeElementPromises)).flat()\n\n\t\t\tflushSync(() => {\n\t\t\t\tstateAtom.update((state) => ({\n\t\t\t\t\t...state,\n\t\t\t\t\tshapeElements: unorderedShapeElements\n\t\t\t\t\t\t.sort((a, b) => a.zIndex - b.zIndex)\n\t\t\t\t\t\t.map(({ element }) => element),\n\t\t\t\t\tdefsById: { ...state.defsById, ...shapeDefs },\n\t\t\t\t}))\n\t\t\t})\n\t\t})()\n\t}, [bbox, editor, exportContext, masksId, renderingShapes, singleFrameShapeId, stateAtom])\n\n\tuseEffect(() => {\n\t\tconst fontsInUse = new Set<TLFontFace>()\n\t\tfor (const { id } of renderingShapes) {\n\t\t\tfor (const font of editor.fonts.getShapeFontFaces(id)) {\n\t\t\t\tfontsInUse.add(font)\n\t\t\t}\n\t\t}\n\n\t\tfor (const font of fontsInUse) {\n\t\t\taddExportDef({\n\t\t\t\tkey: uniqueId(),\n\t\t\t\tgetElement: async () => {\n\t\t\t\t\tconst declaration = await editor.fonts.toEmbeddedCssDeclaration(font)\n\t\t\t\t\treturn <style nonce={editor.options.nonce}>{declaration}</style>\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t}, [editor, renderingShapes, addExportDef])\n\n\tuseEffect(() => {\n\t\tif (shapeElements === null) return\n\t\tonMount()\n\t}, [onMount, shapeElements])\n\n\tlet backgroundColor = background ? theme.background : 'transparent'\n\n\tif (singleFrameShapeId && background) {\n\t\tconst frameShapeUtil = editor.getShapeUtil('frame') as any as\n\t\t\t| undefined\n\t\t\t| { options: { showColors: boolean } }\n\t\tif (frameShapeUtil?.options.showColors) {\n\t\t\tconst shape = editor.getShape(singleFrameShapeId)! as TLFrameShape\n\t\t\tbackgroundColor = getColorValue(theme, shape.props.color, 'frameFill')\n\t\t} else {\n\t\t\tbackgroundColor = theme.solid\n\t\t}\n\t}\n\n\treturn (\n\t\t<SvgExportContextProvider editor={editor} context={exportContext}>\n\t\t\t<svg\n\t\t\t\tpreserveAspectRatio={preserveAspectRatio}\n\t\t\t\tdirection=\"ltr\"\n\t\t\t\twidth={bbox.width * scale}\n\t\t\t\theight={bbox.height * scale}\n\t\t\t\tviewBox={`${bbox.minX} ${bbox.minY} ${bbox.width} ${bbox.height}`}\n\t\t\t\tstrokeLinecap=\"round\"\n\t\t\t\tstrokeLinejoin=\"round\"\n\t\t\t\tstyle={{ backgroundColor }}\n\t\t\t\tdata-color-mode={isDarkMode ? 'dark' : 'light'}\n\t\t\t\tclassName={`tl-container tl-theme__force-sRGB ${isDarkMode ? 'tl-theme__dark' : 'tl-theme__light'}`}\n\t\t\t>\n\t\t\t\t<defs>\n\t\t\t\t\t{Object.entries(defsById).map(([key, def]) =>\n\t\t\t\t\t\tdef.pending ? null : <Fragment key={key}>{def.element}</Fragment>\n\t\t\t\t\t)}\n\t\t\t\t</defs>\n\t\t\t\t{shapeElements}\n\t\t\t</svg>\n\t\t</SvgExportContextProvider>\n\t)\n}\n\nfunction ForeignObjectShape({\n\tshape,\n\tutil,\n\tclassName,\n\tcomponent: Component,\n\tbbox,\n\topacity,\n}: {\n\tshape: TLShape\n\tutil: ShapeUtil\n\tclassName?: string\n\tcomponent: ComponentType<{ shape: TLShape; util: ShapeUtil }>\n\tbbox: Box\n\topacity: number\n}) {\n\tconst editor = useEditor()\n\n\tconst transform = Mat.Translate(-bbox.minX, -bbox.minY).multiply(\n\t\teditor.getShapePageTransform(shape.id)!\n\t)\n\n\tconst bounds = editor.getShapeGeometry(shape.id).bounds\n\tconst width = Math.max(bounds.width, 1)\n\tconst height = Math.max(bounds.height, 1)\n\n\treturn (\n\t\t<ErrorBoundary fallback={() => null}>\n\t\t\t<foreignObject\n\t\t\t\tx={bbox.minX}\n\t\t\t\ty={bbox.minY}\n\t\t\t\twidth={bbox.w}\n\t\t\t\theight={bbox.h}\n\t\t\t\tclassName=\"tl-shape-foreign-object tl-export-embed-styles\"\n\t\t\t>\n\t\t\t\t<div\n\t\t\t\t\tclassName={className}\n\t\t\t\t\tdata-shape-type={shape.type}\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\tclipPath: editor.getShapeClipPath(shape.id),\n\t\t\t\t\t\ttransform: transform.toCssString(),\n\t\t\t\t\t\twidth,\n\t\t\t\t\t\theight,\n\t\t\t\t\t\topacity,\n\t\t\t\t\t}}\n\t\t\t\t>\n\t\t\t\t\t<Component shape={shape} util={util} />\n\t\t\t\t</div>\n\t\t\t</foreignObject>\n\t\t</ErrorBoundary>\n\t)\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuFE;AAvFF,yBAAkC;AAClC,sBAMO;AACP,mBAA6D;AAC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AAA,MAEV;AAAA,QAAC;AAAA;AAAA,UACA;AAAA,UACA,mBAAiB,MAAM;AAAA,UACvB,OAAO;AAAA,YACN,UAAU,OAAO,iBAAiB,MAAM,EAAE;AAAA,YAC1C,WAAW,UAAU,YAAY;AAAA,YACjC;AAAA,YACA;AAAA,YACA;AAAA,UACD;AAAA,UAEA,sDAAC,aAAU,OAAc,MAAY;AAAA;AAAA,MACtC;AAAA;AAAA,EACD,GACD;AAEF;",
4
+ "sourcesContent": ["import { useAtom, useValue } from '@tldraw/state-react'\nimport {\n\tTLFrameShape,\n\tTLShape,\n\tTLShapeId,\n\tgetColorValue,\n\tgetDefaultColorTheme,\n} from '@tldraw/tlschema'\nimport { hasOwnProperty, promiseWithResolve, uniqueId } from '@tldraw/utils'\nimport {\n\tComponentType,\n\tFragment,\n\tReactElement,\n\tReactNode,\n\tuseEffect,\n\tuseLayoutEffect,\n\tuseMemo,\n\tuseRef,\n} from 'react'\nimport { flushSync } from 'react-dom'\nimport { ErrorBoundary } from '../components/ErrorBoundary'\nimport { InnerShape, InnerShapeBackground } from '../components/Shape'\nimport type { Editor, TLRenderingShape } from '../editor/Editor'\nimport { TLFontFace } from '../editor/managers/FontManager/FontManager'\nimport { ShapeUtil } from '../editor/shapes/ShapeUtil'\nimport {\n\tSvgExportContext,\n\tSvgExportContextProvider,\n\tSvgExportDef,\n} from '../editor/types/SvgExportContext'\nimport { TLImageExportOptions } from '../editor/types/misc-types'\nimport { useEditor } from '../hooks/useEditor'\nimport { useEvent } from '../hooks/useEvent'\nimport { suffixSafeId, useUniqueSafeId } from '../hooks/useSafeId'\nimport { Box } from '../primitives/Box'\nimport { Mat } from '../primitives/Mat'\nimport { ExportDelay } from './ExportDelay'\n\nexport function getSvgJsx(editor: Editor, ids: TLShapeId[], opts: TLImageExportOptions = {}) {\n\tconst editorDocument = editor.getContainerDocument()\n\tif (!editorDocument) throw Error('No document')\n\n\tconst {\n\t\tscale = 1,\n\t\t// should we include the background in the export? or is it transparent?\n\t\tbackground = editor.getInstanceState().exportBackground,\n\t\tpreserveAspectRatio,\n\t} = opts\n\n\t// Resolve the padding mode:\n\t// - 'auto' (or undefined): render with default padding, then trim to actual visual content\n\t// - number: fixed padding, no trimming\n\tconst isAutoTrim = typeof opts.padding !== 'number'\n\tconst renderPadding =\n\t\ttypeof opts.padding === 'number' ? opts.padding : editor.options.defaultSvgPadding\n\n\tconst isDarkMode = opts.darkMode ?? editor.user.getIsDarkMode()\n\n\t// ---Figure out which shapes we need to include\n\tconst shapeIdsToInclude = editor.getShapeAndDescendantIds(ids)\n\tconst renderingShapes = editor\n\t\t.getUnorderedRenderingShapes(false)\n\t\t.filter(({ id }) => shapeIdsToInclude.has(id))\n\n\t// --- Common bounding box of all shapes\n\tconst singleFrameShapeId =\n\t\tids.length === 1 && editor.isShapeOfType(editor.getShape(ids[0])!, 'frame') ? ids[0] : null\n\n\tlet bbox: null | Box = null\n\tlet paddingWasApplied = false\n\tif (opts.bounds) {\n\t\t// Explicit bounds: use exact bounds when auto, expand by padding when fixed\n\t\tbbox = isAutoTrim ? opts.bounds.clone() : opts.bounds.clone().expandBy(renderPadding)\n\t} else {\n\t\tconst result = getExportDefaultBounds(\n\t\t\teditor,\n\t\t\trenderingShapes,\n\t\t\trenderPadding,\n\t\t\tsingleFrameShapeId\n\t\t)\n\t\tbbox = result.box\n\t\tpaddingWasApplied = result.paddingApplied\n\t}\n\n\t// no unmasked shapes to export\n\tif (!bbox) return\n\n\t// When auto-trim is active and padding was applied by getExportDefaultBounds,\n\t// the padding region is trimmable: exports will scan pixels from each edge inward\n\t// and trim to the actual visual content bounds. This ensures visual overflow\n\t// (strokes, arrowheads) is captured without unnecessary whitespace.\n\tconst trimPadding = isAutoTrim && paddingWasApplied ? renderPadding : 0\n\n\t// We want the svg image to be BIGGER THAN USUAL to account for image quality\n\tconst w = bbox.width * scale\n\tconst h = bbox.height * scale\n\n\ttry {\n\t\teditorDocument.body.focus?.() // weird but necessary\n\t} catch {\n\t\t// not implemented\n\t}\n\n\tconst exportDelay = new ExportDelay(editor.options.maxExportDelayMs)\n\n\tconst initialEffectPromise = promiseWithResolve<void>()\n\texportDelay.waitUntil(initialEffectPromise)\n\n\tconst svg = (\n\t\t<SvgExport\n\t\t\teditor={editor}\n\t\t\tpreserveAspectRatio={preserveAspectRatio}\n\t\t\tscale={scale}\n\t\t\tpixelRatio={opts.pixelRatio ?? null}\n\t\t\tbbox={bbox}\n\t\t\tbackground={background}\n\t\t\tsingleFrameShapeId={singleFrameShapeId}\n\t\t\tisDarkMode={isDarkMode}\n\t\t\trenderingShapes={renderingShapes}\n\t\t\tonMount={initialEffectPromise.resolve}\n\t\t\twaitUntil={exportDelay.waitUntil}\n\t\t>\n\t\t\t{}\n\t\t</SvgExport>\n\t)\n\n\treturn { jsx: svg, width: w, height: h, exportDelay, trimPadding }\n}\n\n/**\n * Calculates the default bounds for an SVG export. This function handles:\n * 1. Computing masked page bounds for each shape\n * 2. Container logic: if a shape is marked as an export bounds container and it\n * contains all other shapes, use its bounds and skip padding\n * 3. Otherwise, create a union of all shape bounds and apply padding\n *\n * The container logic is useful for cases like annotating on an image - if the image\n * contains all annotations, we want to export exactly the image bounds without extra padding.\n *\n * @param editor - The editor instance\n * @param renderingShapes - The shapes to include in the export\n * @param padding - Padding to add around the bounds (only applied if no container bounds)\n * @param singleFrameShapeId - If exporting a single frame, this is its ID (skips padding)\n * @returns The calculated bounds box, or null if no shapes to export\n */\nexport function getExportDefaultBounds(\n\teditor: Editor,\n\trenderingShapes: TLRenderingShape[],\n\tpadding: number,\n\tsingleFrameShapeId: TLShapeId | null\n): { box: Box; paddingApplied: boolean } | { box: null; paddingApplied: false } {\n\tlet isBoundedByContainer = false\n\tlet bbox: null | Box = null\n\n\tfor (const { id } of renderingShapes) {\n\t\tconst maskedPageBounds = editor.getShapeMaskedPageBounds(id)\n\t\tif (!maskedPageBounds) continue\n\n\t\t// Check if this shape is an export bounds container (e.g., an image being annotated)\n\t\tconst shape = editor.getShape(id)!\n\t\tconst isContainer = editor.getShapeUtil(shape).isExportBoundsContainer(shape)\n\n\t\tif (bbox) {\n\t\t\t// Container logic: if this is a container and it contains all shapes processed so far,\n\t\t\t// use the container's bounds instead of the union. This prevents extra padding around\n\t\t\t// things like annotated images.\n\t\t\tif (isContainer && Box.ContainsApproximately(maskedPageBounds, bbox)) {\n\t\t\t\tisBoundedByContainer = true\n\t\t\t\tbbox = maskedPageBounds.clone()\n\t\t\t} else {\n\t\t\t\t// If we were previously bounded by a container but this shape extends outside it,\n\t\t\t\t// we're no longer bounded by a container\n\t\t\t\tif (isBoundedByContainer && !Box.ContainsApproximately(bbox, maskedPageBounds)) {\n\t\t\t\t\tisBoundedByContainer = false\n\t\t\t\t}\n\t\t\t\t// Expand the bounding box to include this shape\n\t\t\t\tbbox.union(maskedPageBounds)\n\t\t\t}\n\t\t} else {\n\t\t\t// First shape sets the initial bounds\n\t\t\tisBoundedByContainer = isContainer\n\t\t\tbbox = maskedPageBounds.clone()\n\t\t}\n\t}\n\n\t// No unmasked shapes to export\n\tif (!bbox) return { box: null, paddingApplied: false }\n\n\t// Only apply padding if:\n\t// - Not exporting a single frame (frames have their own padding rules)\n\t// - Not bounded by a container (containers define their own bounds precisely)\n\tconst paddingApplied = !singleFrameShapeId && !isBoundedByContainer\n\tif (paddingApplied) {\n\t\tbbox.expandBy(padding)\n\t}\n\n\treturn { box: bbox, paddingApplied }\n}\n\nfunction SvgExport({\n\teditor,\n\tpreserveAspectRatio,\n\tscale,\n\tpixelRatio,\n\tbbox,\n\tbackground,\n\tsingleFrameShapeId,\n\tisDarkMode,\n\trenderingShapes,\n\tonMount,\n\twaitUntil,\n}: {\n\teditor: Editor\n\tpreserveAspectRatio?: string\n\tscale: number\n\tpixelRatio: number | null\n\tbbox: Box\n\tbackground: boolean\n\tsingleFrameShapeId: TLShapeId | null\n\tisDarkMode: boolean\n\trenderingShapes: TLRenderingShape[]\n\tonMount(): void\n\twaitUntil(promise: Promise<void>): void\n}) {\n\tconst masksId = useUniqueSafeId()\n\tconst theme = getDefaultColorTheme({ isDarkMode })\n\n\tconst stateAtom = useAtom<{\n\t\tdefsById: Record<\n\t\t\tstring,\n\t\t\t{ pending: false; element: ReactNode } | { pending: true; element: Promise<ReactNode> }\n\t\t>\n\t\tshapeElements: ReactElement[] | null\n\t}>('export state', { defsById: {}, shapeElements: null })\n\tconst { defsById, shapeElements } = useValue(stateAtom)\n\n\tconst addExportDef = useEvent((def: SvgExportDef) => {\n\t\tstateAtom.update((state) => {\n\t\t\tif (hasOwnProperty(state.defsById, def.key)) return state\n\n\t\t\tconst promise = Promise.resolve(def.getElement())\n\t\t\twaitUntil(\n\t\t\t\tpromise.then((result) => {\n\t\t\t\t\tstateAtom.update((state) => ({\n\t\t\t\t\t\t...state,\n\t\t\t\t\t\tdefsById: { ...state.defsById, [def.key]: { pending: false, element: result } },\n\t\t\t\t\t}))\n\t\t\t\t})\n\t\t\t)\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tdefsById: { ...state.defsById, [def.key]: { pending: true, element: promise } },\n\t\t\t}\n\t\t})\n\t})\n\n\tconst exportContext = useMemo(\n\t\t(): SvgExportContext => ({\n\t\t\tisDarkMode,\n\t\t\twaitUntil,\n\t\t\taddExportDef,\n\t\t\tscale,\n\t\t\tpixelRatio,\n\t\t\tasync resolveAssetUrl(assetId, width) {\n\t\t\t\tconst asset = editor.getAsset(assetId)\n\t\t\t\tif (!asset || (asset.type !== 'image' && asset.type !== 'video')) return null\n\n\t\t\t\treturn await editor.resolveAssetUrl(assetId, {\n\t\t\t\t\tscreenScale: scale * (width / asset.props.w),\n\t\t\t\t\tshouldResolveToOriginal: pixelRatio === null,\n\t\t\t\t\tdpr: pixelRatio ?? undefined,\n\t\t\t\t})\n\t\t\t},\n\t\t}),\n\t\t[isDarkMode, waitUntil, addExportDef, scale, pixelRatio, editor]\n\t)\n\n\tconst didRenderRef = useRef(false)\n\tuseLayoutEffect(() => {\n\t\tif (didRenderRef.current) {\n\t\t\tthrow new Error('SvgExport should only render once - do not use with react strict mode')\n\t\t}\n\t\tdidRenderRef.current = true\n\t\t;(async () => {\n\t\t\tconst shapeDefs: Record<string, { pending: false; element: ReactElement }> = {}\n\n\t\t\t// Then render everything. The shapes with assets should all hit the cache\n\t\t\tconst unorderedShapeElementPromises = renderingShapes.map(\n\t\t\t\tasync ({ id, opacity, index, backgroundIndex }) => {\n\t\t\t\t\t// Don't render the frame if we're only exporting a single frame and it's children\n\t\t\t\t\tif (id === singleFrameShapeId) return []\n\n\t\t\t\t\tconst shape = editor.getShape(id)!\n\n\t\t\t\t\tif (editor.isShapeOfType(shape, 'group')) return []\n\n\t\t\t\t\tconst elements = []\n\t\t\t\t\tconst util = editor.getShapeUtil(shape)\n\n\t\t\t\t\tif (util.toSvg || util.toBackgroundSvg) {\n\t\t\t\t\t\t// If the shape has any sort of custom svg export, let's use that.\n\t\t\t\t\t\tconst [toSvgResult, toBackgroundSvgResult] = await Promise.all([\n\t\t\t\t\t\t\tutil.toSvg?.(shape, exportContext),\n\t\t\t\t\t\t\tutil.toBackgroundSvg?.(shape, exportContext),\n\t\t\t\t\t\t])\n\n\t\t\t\t\t\tconst pageTransform = editor.getShapePageTransform(shape)\n\t\t\t\t\t\tlet pageTransformString = pageTransform!.toCssString()\n\t\t\t\t\t\tlet scale = 1\n\t\t\t\t\t\tif ('scale' in shape.props) {\n\t\t\t\t\t\t\tif (shape.props.scale !== 1) {\n\t\t\t\t\t\t\t\tscale = shape.props.scale\n\t\t\t\t\t\t\t\tpageTransformString = `${pageTransformString} scale(${shape.props.scale}, ${shape.props.scale})`\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Create svg mask if shape has a frame as parent\n\t\t\t\t\t\tconst pageMask = editor.getShapeMask(shape.id)\n\t\t\t\t\t\tconst shapeMask = pageMask\n\t\t\t\t\t\t\t? Mat.From(Mat.Inverse(pageTransform)).applyToPoints(pageMask)\n\t\t\t\t\t\t\t: null\n\t\t\t\t\t\tconst shapeMaskId = suffixSafeId(masksId, shape.id)\n\t\t\t\t\t\tif (shapeMask) {\n\t\t\t\t\t\t\t// Create a clip path and add it to defs\n\t\t\t\t\t\t\tshapeDefs[shapeMaskId] = {\n\t\t\t\t\t\t\t\tpending: false,\n\t\t\t\t\t\t\t\telement: (\n\t\t\t\t\t\t\t\t\t<clipPath id={shapeMaskId}>\n\t\t\t\t\t\t\t\t\t\t{/* Create a polyline mask that does the clipping */}\n\t\t\t\t\t\t\t\t\t\t<path\n\t\t\t\t\t\t\t\t\t\t\td={`M${shapeMask.map(({ x, y }) => `${x / scale},${y / scale}`).join('L')}Z`}\n\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t</clipPath>\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (toSvgResult) {\n\t\t\t\t\t\t\telements.push({\n\t\t\t\t\t\t\t\tzIndex: index,\n\t\t\t\t\t\t\t\telement: (\n\t\t\t\t\t\t\t\t\t<g\n\t\t\t\t\t\t\t\t\t\tkey={`fg_${shape.id}`}\n\t\t\t\t\t\t\t\t\t\ttransform={pageTransformString}\n\t\t\t\t\t\t\t\t\t\topacity={opacity}\n\t\t\t\t\t\t\t\t\t\tclipPath={pageMask ? `url(#${shapeMaskId})` : undefined}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{toSvgResult}\n\t\t\t\t\t\t\t\t\t</g>\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (toBackgroundSvgResult) {\n\t\t\t\t\t\t\telements.push({\n\t\t\t\t\t\t\t\tzIndex: backgroundIndex,\n\t\t\t\t\t\t\t\telement: (\n\t\t\t\t\t\t\t\t\t<g\n\t\t\t\t\t\t\t\t\t\tkey={`bg_${shape.id}`}\n\t\t\t\t\t\t\t\t\t\ttransform={pageTransformString}\n\t\t\t\t\t\t\t\t\t\topacity={opacity}\n\t\t\t\t\t\t\t\t\t\tclipPath={pageMask ? `url(#${shapeMaskId})` : undefined}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{toBackgroundSvgResult}\n\t\t\t\t\t\t\t\t\t</g>\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// If the shape doesn't have a custom svg export, we'll use its normal HTML\n\t\t\t\t\t\t// renderer in a foreignObject.\n\t\t\t\t\t\telements.push({\n\t\t\t\t\t\t\tzIndex: index,\n\t\t\t\t\t\t\telement: (\n\t\t\t\t\t\t\t\t<ForeignObjectShape\n\t\t\t\t\t\t\t\t\tkey={`fg_${shape.id}`}\n\t\t\t\t\t\t\t\t\tshape={shape}\n\t\t\t\t\t\t\t\t\tutil={util}\n\t\t\t\t\t\t\t\t\tcomponent={InnerShape}\n\t\t\t\t\t\t\t\t\tclassName=\"tl-shape\"\n\t\t\t\t\t\t\t\t\tbbox={bbox}\n\t\t\t\t\t\t\t\t\topacity={opacity}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t})\n\n\t\t\t\t\t\tif (util.backgroundComponent) {\n\t\t\t\t\t\t\telements.push({\n\t\t\t\t\t\t\t\tzIndex: backgroundIndex,\n\t\t\t\t\t\t\t\telement: (\n\t\t\t\t\t\t\t\t\t<ForeignObjectShape\n\t\t\t\t\t\t\t\t\t\tkey={`bg_${shape.id}`}\n\t\t\t\t\t\t\t\t\t\tshape={shape}\n\t\t\t\t\t\t\t\t\t\tutil={util}\n\t\t\t\t\t\t\t\t\t\tcomponent={InnerShapeBackground}\n\t\t\t\t\t\t\t\t\t\tclassName=\"tl-shape tl-shape-background\"\n\t\t\t\t\t\t\t\t\t\tbbox={bbox}\n\t\t\t\t\t\t\t\t\t\topacity={opacity}\n\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn elements\n\t\t\t\t}\n\t\t\t)\n\n\t\t\tconst unorderedShapeElements = (await Promise.all(unorderedShapeElementPromises)).flat()\n\n\t\t\tflushSync(() => {\n\t\t\t\tstateAtom.update((state) => ({\n\t\t\t\t\t...state,\n\t\t\t\t\tshapeElements: unorderedShapeElements\n\t\t\t\t\t\t.sort((a, b) => a.zIndex - b.zIndex)\n\t\t\t\t\t\t.map(({ element }) => element),\n\t\t\t\t\tdefsById: { ...state.defsById, ...shapeDefs },\n\t\t\t\t}))\n\t\t\t})\n\t\t})()\n\t}, [bbox, editor, exportContext, masksId, renderingShapes, singleFrameShapeId, stateAtom])\n\n\tuseEffect(() => {\n\t\tconst fontsInUse = new Set<TLFontFace>()\n\t\tfor (const { id } of renderingShapes) {\n\t\t\tfor (const font of editor.fonts.getShapeFontFaces(id)) {\n\t\t\t\tfontsInUse.add(font)\n\t\t\t}\n\t\t}\n\n\t\tfor (const font of fontsInUse) {\n\t\t\taddExportDef({\n\t\t\t\tkey: uniqueId(),\n\t\t\t\tgetElement: async () => {\n\t\t\t\t\tconst declaration = await editor.fonts.toEmbeddedCssDeclaration(font)\n\t\t\t\t\treturn <style nonce={editor.options.nonce}>{declaration}</style>\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t}, [editor, renderingShapes, addExportDef])\n\n\tuseEffect(() => {\n\t\tif (shapeElements === null) return\n\t\tonMount()\n\t}, [onMount, shapeElements])\n\n\tlet backgroundColor = background ? theme.background : 'transparent'\n\n\tif (singleFrameShapeId && background) {\n\t\tconst frameShapeUtil = editor.getShapeUtil('frame') as any as\n\t\t\t| undefined\n\t\t\t| { options: { showColors: boolean } }\n\t\tif (frameShapeUtil?.options.showColors) {\n\t\t\tconst shape = editor.getShape(singleFrameShapeId)! as TLFrameShape\n\t\t\tbackgroundColor = getColorValue(theme, shape.props.color, 'frameFill')\n\t\t} else {\n\t\t\tbackgroundColor = theme.solid\n\t\t}\n\t}\n\n\treturn (\n\t\t<SvgExportContextProvider editor={editor} context={exportContext}>\n\t\t\t<svg\n\t\t\t\tpreserveAspectRatio={preserveAspectRatio}\n\t\t\t\tdirection=\"ltr\"\n\t\t\t\twidth={bbox.width * scale}\n\t\t\t\theight={bbox.height * scale}\n\t\t\t\tviewBox={`${bbox.minX} ${bbox.minY} ${bbox.width} ${bbox.height}`}\n\t\t\t\tstrokeLinecap=\"round\"\n\t\t\t\tstrokeLinejoin=\"round\"\n\t\t\t\tstyle={{ backgroundColor }}\n\t\t\t\tdata-color-mode={isDarkMode ? 'dark' : 'light'}\n\t\t\t\tclassName={`tl-container tl-theme__force-sRGB ${isDarkMode ? 'tl-theme__dark' : 'tl-theme__light'}`}\n\t\t\t>\n\t\t\t\t<defs>\n\t\t\t\t\t{Object.entries(defsById).map(([key, def]) =>\n\t\t\t\t\t\tdef.pending ? null : <Fragment key={key}>{def.element}</Fragment>\n\t\t\t\t\t)}\n\t\t\t\t</defs>\n\t\t\t\t{shapeElements}\n\t\t\t</svg>\n\t\t</SvgExportContextProvider>\n\t)\n}\n\nfunction ForeignObjectShape({\n\tshape,\n\tutil,\n\tclassName,\n\tcomponent: Component,\n\tbbox,\n\topacity,\n}: {\n\tshape: TLShape\n\tutil: ShapeUtil\n\tclassName?: string\n\tcomponent: ComponentType<{ shape: TLShape; util: ShapeUtil }>\n\tbbox: Box\n\topacity: number\n}) {\n\tconst editor = useEditor()\n\n\tconst transform = Mat.Translate(-bbox.minX, -bbox.minY).multiply(\n\t\teditor.getShapePageTransform(shape.id)!\n\t)\n\n\tconst bounds = editor.getShapeGeometry(shape.id).bounds\n\tconst width = Math.max(bounds.width, 1)\n\tconst height = Math.max(bounds.height, 1)\n\n\treturn (\n\t\t<ErrorBoundary fallback={() => null}>\n\t\t\t<foreignObject\n\t\t\t\tx={bbox.minX}\n\t\t\t\ty={bbox.minY}\n\t\t\t\twidth={bbox.w}\n\t\t\t\theight={bbox.h}\n\t\t\t\tclassName=\"tl-shape-foreign-object tl-export-embed-styles\"\n\t\t\t>\n\t\t\t\t<div\n\t\t\t\t\tclassName={className}\n\t\t\t\t\tdata-shape-type={shape.type}\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\tclipPath: editor.getShapeClipPath(shape.id),\n\t\t\t\t\t\ttransform: transform.toCssString(),\n\t\t\t\t\t\twidth,\n\t\t\t\t\t\theight,\n\t\t\t\t\t\topacity,\n\t\t\t\t\t}}\n\t\t\t\t>\n\t\t\t\t\t<Component shape={shape} util={util} />\n\t\t\t\t</div>\n\t\t\t</foreignObject>\n\t\t</ErrorBoundary>\n\t)\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6GE;AA7GF,yBAAkC;AAClC,sBAMO;AACP,mBAA6D;AAC7D,mBASO;AACP,uBAA0B;AAC1B,2BAA8B;AAC9B,mBAAiD;AAIjD,8BAIO;AAEP,uBAA0B;AAC1B,sBAAyB;AACzB,uBAA8C;AAC9C,iBAAoB;AACpB,iBAAoB;AACpB,yBAA4B;AAErB,SAAS,UAAU,QAAgB,KAAkB,OAA6B,CAAC,GAAG;AAC5F,QAAM,iBAAiB,OAAO,qBAAqB;AACnD,MAAI,CAAC,eAAgB,OAAM,MAAM,aAAa;AAE9C,QAAM;AAAA,IACL,QAAQ;AAAA;AAAA,IAER,aAAa,OAAO,iBAAiB,EAAE;AAAA,IACvC;AAAA,EACD,IAAI;AAKJ,QAAM,aAAa,OAAO,KAAK,YAAY;AAC3C,QAAM,gBACL,OAAO,KAAK,YAAY,WAAW,KAAK,UAAU,OAAO,QAAQ;AAElE,QAAM,aAAa,KAAK,YAAY,OAAO,KAAK,cAAc;AAG9D,QAAM,oBAAoB,OAAO,yBAAyB,GAAG;AAC7D,QAAM,kBAAkB,OACtB,4BAA4B,KAAK,EACjC,OAAO,CAAC,EAAE,GAAG,MAAM,kBAAkB,IAAI,EA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 __export(environment_exports, {
23
23
  });
24
24
  module.exports = __toCommonJS(environment_exports);
25
25
  var import_state = require("@tldraw/state");
26
+ var import_dom = require("../utils/dom");
26
27
  const tlenv = {
27
28
  isSafari: false,
28
29
  isIos: false,
@@ -41,7 +42,7 @@ if (typeof window !== "undefined") {
41
42
  tlenv.isChromeForIos = /crios.*safari/i.test(navigator.userAgent);
42
43
  tlenv.isFirefox = /firefox/i.test(navigator.userAgent);
43
44
  tlenv.isAndroid = /android/i.test(navigator.userAgent);
44
- tlenv.isDarwin = window.navigator.userAgent.toLowerCase().indexOf("mac") > -1;
45
+ tlenv.isDarwin = (0, import_dom.getGlobalWindow)().navigator.userAgent.toLowerCase().indexOf("mac") > -1;
45
46
  }
46
47
  tlenv.hasCanvasSupport = "Promise" in window && "HTMLCanvasElement" in window;
47
48
  isForcedFinePointer = tlenv.isFirefox && !tlenv.isAndroid && !tlenv.isIos;
@@ -53,7 +54,7 @@ const tlenvReactive = (0, import_state.atom)("tlenvReactive", {
53
54
  isCoarsePointer: false
54
55
  });
55
56
  if (typeof window !== "undefined" && !isForcedFinePointer) {
56
- const mql = window.matchMedia && window.matchMedia("(any-pointer: coarse)");
57
+ const mql = (0, import_dom.getGlobalWindow)().matchMedia && (0, import_dom.getGlobalWindow)().matchMedia("(any-pointer: coarse)");
57
58
  const isCurrentCoarsePointer = () => tlenvReactive.__unsafe__getWithoutCapture().isCoarsePointer;
58
59
  if (mql) {
59
60
  const updateIsCoarsePointer = () => {
@@ -65,7 +66,7 @@ if (typeof window !== "undefined" && !isForcedFinePointer) {
65
66
  updateIsCoarsePointer();
66
67
  mql.addEventListener("change", updateIsCoarsePointer);
67
68
  }
68
- window.addEventListener(
69
+ (0, import_dom.getGlobalWindow)().addEventListener(
69
70
  "pointerdown",
70
71
  (e) => {
71
72
  const isCoarseEvent = e.pointerType !== "mouse";
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/globals/environment.ts"],
4
- "sourcesContent": ["import { atom } from '@tldraw/state'\n\n/**\n * An object that contains information about the current device and environment.\n * This object is not reactive and will not update automatically when the environment changes,\n * so only include values that are fixed, such as the user's browser and operating system.\n *\n * @public\n */\nconst tlenv = {\n\tisSafari: false,\n\tisIos: false,\n\tisChromeForIos: false,\n\tisFirefox: false,\n\tisAndroid: false,\n\tisWebview: false,\n\tisDarwin: false,\n\thasCanvasSupport: false,\n}\n\nlet isForcedFinePointer = false\n\nif (typeof window !== 'undefined') {\n\tif ('navigator' in window) {\n\t\ttlenv.isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent)\n\t\ttlenv.isIos = !!navigator.userAgent.match(/iPad/i) || !!navigator.userAgent.match(/iPhone/i)\n\t\ttlenv.isChromeForIos = /crios.*safari/i.test(navigator.userAgent)\n\t\ttlenv.isFirefox = /firefox/i.test(navigator.userAgent)\n\t\ttlenv.isAndroid = /android/i.test(navigator.userAgent)\n\t\ttlenv.isDarwin = window.navigator.userAgent.toLowerCase().indexOf('mac') > -1\n\t}\n\ttlenv.hasCanvasSupport = 'Promise' in window && 'HTMLCanvasElement' in window\n\tisForcedFinePointer = tlenv.isFirefox && !tlenv.isAndroid && !tlenv.isIos\n}\n\n/**\n * An atom that contains information about the current device and environment.\n * This object is reactive and will update automatically when the environment changes.\n * Use it for values that may change over time, such as the pointer type.\n *\n * @public\n */\nconst tlenvReactive = atom('tlenvReactive', {\n\t// Whether the user's device has a coarse pointer. This is dynamic on many systems, especially\n\t// on touch-screen laptops, which will become \"coarse\" if the user touches the screen.\n\t// See https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@media/pointer#coarse\n\tisCoarsePointer: false,\n})\n\nif (typeof window !== 'undefined' && !isForcedFinePointer) {\n\tconst mql = window.matchMedia && window.matchMedia('(any-pointer: coarse)')\n\n\tconst isCurrentCoarsePointer = () => tlenvReactive.__unsafe__getWithoutCapture().isCoarsePointer\n\n\tif (mql) {\n\t\t// 1. Update the coarse pointer automatically when the media query changes\n\t\tconst updateIsCoarsePointer = () => {\n\t\t\tconst isCoarsePointer = mql.matches\n\t\t\tif (isCoarsePointer !== isCurrentCoarsePointer()) {\n\t\t\t\ttlenvReactive.update((prev) => ({ ...prev, isCoarsePointer: isCoarsePointer }))\n\t\t\t}\n\t\t}\n\t\tupdateIsCoarsePointer()\n\t\tmql.addEventListener('change', updateIsCoarsePointer)\n\t}\n\n\t// 2. Also update the coarse pointer state when a pointer down event occurs. We need `capture: true`\n\t// here because the tldraw component itself stops propagation on pointer events it receives.\n\twindow.addEventListener(\n\t\t'pointerdown',\n\t\t(e: PointerEvent) => {\n\t\t\t// when the user interacts with a mouse, we assume they have a fine pointer.\n\t\t\t// otherwise, we assume they have a coarse pointer.\n\t\t\tconst isCoarseEvent = e.pointerType !== 'mouse'\n\t\t\tif (isCoarseEvent !== isCurrentCoarsePointer()) {\n\t\t\t\ttlenvReactive.update((prev) => ({ ...prev, isCoarsePointer: isCoarseEvent }))\n\t\t\t}\n\t\t},\n\t\t{ capture: true }\n\t)\n}\n\nexport { tlenv, tlenvReactive }\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAqB;AASrB,MAAM,QAAQ;AAAA,EACb,UAAU;AAAA,EACV,OAAO;AAAA,EACP,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,UAAU;AAAA,EACV,kBAAkB;AACnB;AAEA,IAAI,sBAAsB;AAE1B,IAAI,OAAO,WAAW,aAAa;AAClC,MAAI,eAAe,QAAQ;AAC1B,UAAM,WAAW,iCAAiC,KAAK,UAAU,SAAS;AAC1E,UAAM,QAAQ,CAAC,CAAC,UAAU,UAAU,MAAM,OAAO,KAAK,CAAC,CAAC,UAAU,UAAU,MAAM,SAAS;AAC3F,UAAM,iBAAiB,iBAAiB,KAAK,UAAU,SAAS;AAChE,UAAM,YAAY,WAAW,KAAK,UAAU,SAAS;AACrD,UAAM,YAAY,WAAW,KAAK,UAAU,SAAS;AACrD,UAAM,WAAW,OAAO,UAAU,UAAU,YAAY,EAAE,QAAQ,KAAK,IAAI;AAAA,EAC5E;AACA,QAAM,mBAAmB,aAAa,UAAU,uBAAuB;AACvE,wBAAsB,MAAM,aAAa,CAAC,MAAM,aAAa,CAAC,MAAM;AACrE;AASA,MAAM,oBAAgB,mBAAK,iBAAiB;AAAA;AAAA;AAAA;AAAA,EAI3C,iBAAiB;AAClB,CAAC;AAED,IAAI,OAAO,WAAW,eAAe,CAAC,qBAAqB;AAC1D,QAAM,MAAM,OAAO,cAAc,OAAO,WAAW,uBAAuB;AAE1E,QAAM,yBAAyB,MAAM,cAAc,4BAA4B,EAAE;AAEjF,MAAI,KAAK;AAER,UAAM,wBAAwB,MAAM;AACnC,YAAM,kBAAkB,IAAI;AAC5B,UAAI,oBAAoB,uBAAuB,GAAG;AACjD,sBAAc,OAAO,CAAC,UAAU,EAAE,GAAG,MAAM,gBAAiC,EAAE;AAAA,MAC/E;AAAA,IACD;AACA,0BAAsB;AACtB,QAAI,iBAAiB,UAAU,qBAAqB;AAAA,EACrD;AAIA,SAAO;AAAA,IACN;AAAA,IACA,CAAC,MAAoB;AAGpB,YAAM,gBAAgB,EAAE,gBAAgB;AACxC,UAAI,kBAAkB,uBAAuB,GAAG;AAC/C,sBAAc,OAAO,CAAC,UAAU,EAAE,GAAG,MAAM,iBAAiB,cAAc,EAAE;AAAA,MAC7E;AAAA,IACD;AAAA,IACA,EAAE,SAAS,KAAK;AAAA,EACjB;AACD;",
4
+ "sourcesContent": ["import { atom } from '@tldraw/state'\nimport { getGlobalWindow } from '../utils/dom'\n\n/**\n * An object that contains information about the current device and environment.\n * This object is not reactive and will not update automatically when the environment changes,\n * so only include values that are fixed, such as the user's browser and operating system.\n *\n * @public\n */\nconst tlenv = {\n\tisSafari: false,\n\tisIos: false,\n\tisChromeForIos: false,\n\tisFirefox: false,\n\tisAndroid: false,\n\tisWebview: false,\n\tisDarwin: false,\n\thasCanvasSupport: false,\n}\n\nlet isForcedFinePointer = false\n\nif (typeof window !== 'undefined') {\n\tif ('navigator' in window) {\n\t\ttlenv.isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent)\n\t\ttlenv.isIos = !!navigator.userAgent.match(/iPad/i) || !!navigator.userAgent.match(/iPhone/i)\n\t\ttlenv.isChromeForIos = /crios.*safari/i.test(navigator.userAgent)\n\t\ttlenv.isFirefox = /firefox/i.test(navigator.userAgent)\n\t\ttlenv.isAndroid = /android/i.test(navigator.userAgent)\n\t\ttlenv.isDarwin = getGlobalWindow().navigator.userAgent.toLowerCase().indexOf('mac') > -1\n\t}\n\ttlenv.hasCanvasSupport = 'Promise' in window && 'HTMLCanvasElement' in window\n\tisForcedFinePointer = tlenv.isFirefox && !tlenv.isAndroid && !tlenv.isIos\n}\n\n/**\n * An atom that contains information about the current device and environment.\n * This object is reactive and will update automatically when the environment changes.\n * Use it for values that may change over time, such as the pointer type.\n *\n * @public\n */\nconst tlenvReactive = atom('tlenvReactive', {\n\t// Whether the user's device has a coarse pointer. This is dynamic on many systems, especially\n\t// on touch-screen laptops, which will become \"coarse\" if the user touches the screen.\n\t// See https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@media/pointer#coarse\n\tisCoarsePointer: false,\n})\n\nif (typeof window !== 'undefined' && !isForcedFinePointer) {\n\tconst mql = getGlobalWindow().matchMedia && getGlobalWindow().matchMedia('(any-pointer: coarse)')\n\n\tconst isCurrentCoarsePointer = () => tlenvReactive.__unsafe__getWithoutCapture().isCoarsePointer\n\n\tif (mql) {\n\t\t// 1. Update the coarse pointer automatically when the media query changes\n\t\tconst updateIsCoarsePointer = () => {\n\t\t\tconst isCoarsePointer = mql.matches\n\t\t\tif (isCoarsePointer !== isCurrentCoarsePointer()) {\n\t\t\t\ttlenvReactive.update((prev) => ({ ...prev, isCoarsePointer: isCoarsePointer }))\n\t\t\t}\n\t\t}\n\t\tupdateIsCoarsePointer()\n\t\tmql.addEventListener('change', updateIsCoarsePointer)\n\t}\n\n\t// 2. Also update the coarse pointer state when a pointer down event occurs. We need `capture: true`\n\t// here because the tldraw component itself stops propagation on pointer events it receives.\n\tgetGlobalWindow().addEventListener(\n\t\t'pointerdown',\n\t\t(e: PointerEvent) => {\n\t\t\t// when the user interacts with a mouse, we assume they have a fine pointer.\n\t\t\t// otherwise, we assume they have a coarse pointer.\n\t\t\tconst isCoarseEvent = e.pointerType !== 'mouse'\n\t\t\tif (isCoarseEvent !== isCurrentCoarsePointer()) {\n\t\t\t\ttlenvReactive.update((prev) => ({ ...prev, isCoarsePointer: isCoarseEvent }))\n\t\t\t}\n\t\t},\n\t\t{ capture: true }\n\t)\n}\n\nexport { tlenv, tlenvReactive }\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAqB;AACrB,iBAAgC;AAShC,MAAM,QAAQ;AAAA,EACb,UAAU;AAAA,EACV,OAAO;AAAA,EACP,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,UAAU;AAAA,EACV,kBAAkB;AACnB;AAEA,IAAI,sBAAsB;AAE1B,IAAI,OAAO,WAAW,aAAa;AAClC,MAAI,eAAe,QAAQ;AAC1B,UAAM,WAAW,iCAAiC,KAAK,UAAU,SAAS;AAC1E,UAAM,QAAQ,CAAC,CAAC,UAAU,UAAU,MAAM,OAAO,KAAK,CAAC,CAAC,UAAU,UAAU,MAAM,SAAS;AAC3F,UAAM,iBAAiB,iBAAiB,KAAK,UAAU,SAAS;AAChE,UAAM,YAAY,WAAW,KAAK,UAAU,SAAS;AACrD,UAAM,YAAY,WAAW,KAAK,UAAU,SAAS;AACrD,UAAM,eAAW,4BAAgB,EAAE,UAAU,UAAU,YAAY,EAAE,QAAQ,KAAK,IAAI;AAAA,EACvF;AACA,QAAM,mBAAmB,aAAa,UAAU,uBAAuB;AACvE,wBAAsB,MAAM,aAAa,CAAC,MAAM,aAAa,CAAC,MAAM;AACrE;AASA,MAAM,oBAAgB,mBAAK,iBAAiB;AAAA;AAAA;AAAA;AAAA,EAI3C,iBAAiB;AAClB,CAAC;AAED,IAAI,OAAO,WAAW,eAAe,CAAC,qBAAqB;AAC1D,QAAM,UAAM,4BAAgB,EAAE,kBAAc,4BAAgB,EAAE,WAAW,uBAAuB;AAEhG,QAAM,yBAAyB,MAAM,cAAc,4BAA4B,EAAE;AAEjF,MAAI,KAAK;AAER,UAAM,wBAAwB,MAAM;AACnC,YAAM,kBAAkB,IAAI;AAC5B,UAAI,oBAAoB,uBAAuB,GAAG;AACjD,sBAAc,OAAO,CAAC,UAAU,EAAE,GAAG,MAAM,gBAAiC,EAAE;AAAA,MAC/E;AAAA,IACD;AACA,0BAAsB;AACtB,QAAI,iBAAiB,UAAU,qBAAqB;AAAA,EACrD;AAIA,kCAAgB,EAAE;AAAA,IACjB;AAAA,IACA,CAAC,MAAoB;AAGpB,YAAM,gBAAgB,EAAE,gBAAgB;AACxC,UAAI,kBAAkB,uBAAuB,GAAG;AAC/C,sBAAc,OAAO,CAAC,UAAU,EAAE,GAAG,MAAM,iBAAiB,cAAc,EAAE;AAAA,MAC7E;AAAA,IACD;AAAA,IACA,EAAE,SAAS,KAAK;AAAA,EACjB;AACD;",
6
6
  "names": []
7
7
  }
@@ -30,7 +30,7 @@ var import_getPointerInfo = require("../utils/getPointerInfo");
30
30
  var import_useEditor = require("./useEditor");
31
31
  function useCanvasEvents() {
32
32
  const editor = (0, import_useEditor.useEditor)();
33
- const ownerDocument = editor.getContainer().ownerDocument;
33
+ const ownerDocument = editor.getContainerDocument();
34
34
  const currentTool = (0, import_state_react.useValue)("current tool", () => editor.getCurrentTool(), [editor]);
35
35
  const events = (0, import_react.useMemo)(
36
36
  function canvasEvents() {
@@ -85,7 +85,7 @@ function useCanvasEvents() {
85
85
  function onTouchEnd(e) {
86
86
  if (editor.wasEventAlreadyHandled(e)) return;
87
87
  editor.markEventAsHandled(e);
88
- if (!(e.target instanceof HTMLElement)) return;
88
+ if (!(e.target instanceof editor.getContainerWindow().HTMLElement)) return;
89
89
  const editingShapeId = editor.getEditingShapeId();
90
90
  if (
91
91
  // if the target is not inside the editing shape