@tldraw/editor 5.5.0-next.a2698a88ecfb → 5.5.0-next.b6a9f7cd7be2

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 (127) hide show
  1. package/dist-cjs/index.d.ts +2 -0
  2. package/dist-cjs/index.js +1 -1
  3. package/dist-cjs/lib/TldrawEditor.js +16 -12
  4. package/dist-cjs/lib/TldrawEditor.js.map +2 -2
  5. package/dist-cjs/lib/components/MenuClickCapture.js +42 -3
  6. package/dist-cjs/lib/components/MenuClickCapture.js.map +2 -2
  7. package/dist-cjs/lib/editor/Editor.js +144 -155
  8. package/dist-cjs/lib/editor/Editor.js.map +3 -3
  9. package/dist-cjs/lib/editor/derivations/bindingsIndex.js +2 -0
  10. package/dist-cjs/lib/editor/derivations/bindingsIndex.js.map +2 -2
  11. package/dist-cjs/lib/editor/managers/TextManager/TextManager.js +4 -4
  12. package/dist-cjs/lib/editor/managers/TextManager/TextManager.js.map +2 -2
  13. package/dist-cjs/lib/editor/shapes/group/GroupShapeUtil.js +14 -6
  14. package/dist-cjs/lib/editor/shapes/group/GroupShapeUtil.js.map +3 -3
  15. package/dist-cjs/lib/exports/ExportDelay.js +10 -2
  16. package/dist-cjs/lib/exports/ExportDelay.js.map +2 -2
  17. package/dist-cjs/lib/exports/FontEmbedder.js +25 -11
  18. package/dist-cjs/lib/exports/FontEmbedder.js.map +2 -2
  19. package/dist-cjs/lib/exports/StyleEmbedder.js +9 -4
  20. package/dist-cjs/lib/exports/StyleEmbedder.js.map +2 -2
  21. package/dist-cjs/lib/exports/fetchCache.js +3 -0
  22. package/dist-cjs/lib/exports/fetchCache.js.map +2 -2
  23. package/dist-cjs/lib/exports/getSvgAsImage.js +10 -4
  24. package/dist-cjs/lib/exports/getSvgAsImage.js.map +2 -2
  25. package/dist-cjs/lib/exports/getSvgJsx.js +18 -9
  26. package/dist-cjs/lib/exports/getSvgJsx.js.map +2 -2
  27. package/dist-cjs/lib/exports/parseCss.js +1 -1
  28. package/dist-cjs/lib/exports/parseCss.js.map +1 -1
  29. package/dist-cjs/lib/hooks/useCanvasEvents.js +24 -0
  30. package/dist-cjs/lib/hooks/useCanvasEvents.js.map +2 -2
  31. package/dist-cjs/lib/hooks/useIdentity.js +6 -2
  32. package/dist-cjs/lib/hooks/useIdentity.js.map +3 -3
  33. package/dist-cjs/lib/license/LicenseManager.js +9 -1
  34. package/dist-cjs/lib/license/LicenseManager.js.map +2 -2
  35. package/dist-cjs/lib/license/LicenseProvider.js +12 -4
  36. package/dist-cjs/lib/license/LicenseProvider.js.map +2 -2
  37. package/dist-cjs/lib/utils/deepLinks.js +2 -1
  38. package/dist-cjs/lib/utils/deepLinks.js.map +2 -2
  39. package/dist-cjs/lib/utils/sync/LocalIndexedDb.js +13 -17
  40. package/dist-cjs/lib/utils/sync/LocalIndexedDb.js.map +2 -2
  41. package/dist-cjs/lib/utils/sync/TLLocalSyncClient.js +78 -40
  42. package/dist-cjs/lib/utils/sync/TLLocalSyncClient.js.map +2 -2
  43. package/dist-cjs/version.js +3 -3
  44. package/dist-cjs/version.js.map +1 -1
  45. package/dist-esm/index.d.mts +2 -0
  46. package/dist-esm/index.mjs +1 -1
  47. package/dist-esm/lib/TldrawEditor.mjs +17 -13
  48. package/dist-esm/lib/TldrawEditor.mjs.map +2 -2
  49. package/dist-esm/lib/components/MenuClickCapture.mjs +42 -3
  50. package/dist-esm/lib/components/MenuClickCapture.mjs.map +2 -2
  51. package/dist-esm/lib/editor/Editor.mjs +144 -155
  52. package/dist-esm/lib/editor/Editor.mjs.map +3 -3
  53. package/dist-esm/lib/editor/derivations/bindingsIndex.mjs +2 -0
  54. package/dist-esm/lib/editor/derivations/bindingsIndex.mjs.map +2 -2
  55. package/dist-esm/lib/editor/managers/TextManager/TextManager.mjs +4 -4
  56. package/dist-esm/lib/editor/managers/TextManager/TextManager.mjs.map +2 -2
  57. package/dist-esm/lib/editor/shapes/group/GroupShapeUtil.mjs +14 -6
  58. package/dist-esm/lib/editor/shapes/group/GroupShapeUtil.mjs.map +3 -3
  59. package/dist-esm/lib/exports/ExportDelay.mjs +11 -3
  60. package/dist-esm/lib/exports/ExportDelay.mjs.map +2 -2
  61. package/dist-esm/lib/exports/FontEmbedder.mjs +25 -11
  62. package/dist-esm/lib/exports/FontEmbedder.mjs.map +2 -2
  63. package/dist-esm/lib/exports/StyleEmbedder.mjs +9 -4
  64. package/dist-esm/lib/exports/StyleEmbedder.mjs.map +2 -2
  65. package/dist-esm/lib/exports/fetchCache.mjs +3 -0
  66. package/dist-esm/lib/exports/fetchCache.mjs.map +2 -2
  67. package/dist-esm/lib/exports/getSvgAsImage.mjs +10 -4
  68. package/dist-esm/lib/exports/getSvgAsImage.mjs.map +2 -2
  69. package/dist-esm/lib/exports/getSvgJsx.mjs +18 -9
  70. package/dist-esm/lib/exports/getSvgJsx.mjs.map +2 -2
  71. package/dist-esm/lib/exports/parseCss.mjs +1 -1
  72. package/dist-esm/lib/exports/parseCss.mjs.map +1 -1
  73. package/dist-esm/lib/hooks/useCanvasEvents.mjs +24 -0
  74. package/dist-esm/lib/hooks/useCanvasEvents.mjs.map +2 -2
  75. package/dist-esm/lib/hooks/useIdentity.mjs +7 -3
  76. package/dist-esm/lib/hooks/useIdentity.mjs.map +3 -3
  77. package/dist-esm/lib/license/LicenseManager.mjs +9 -1
  78. package/dist-esm/lib/license/LicenseManager.mjs.map +2 -2
  79. package/dist-esm/lib/license/LicenseProvider.mjs +13 -5
  80. package/dist-esm/lib/license/LicenseProvider.mjs.map +2 -2
  81. package/dist-esm/lib/utils/deepLinks.mjs +2 -1
  82. package/dist-esm/lib/utils/deepLinks.mjs.map +2 -2
  83. package/dist-esm/lib/utils/sync/LocalIndexedDb.mjs +13 -17
  84. package/dist-esm/lib/utils/sync/LocalIndexedDb.mjs.map +2 -2
  85. package/dist-esm/lib/utils/sync/TLLocalSyncClient.mjs +78 -40
  86. package/dist-esm/lib/utils/sync/TLLocalSyncClient.mjs.map +2 -2
  87. package/dist-esm/version.mjs +3 -3
  88. package/dist-esm/version.mjs.map +1 -1
  89. package/editor.css +9 -1
  90. package/package.json +8 -11
  91. package/src/lib/TldrawEditor.tsx +27 -15
  92. package/src/lib/components/MenuClickCapture.tsx +55 -4
  93. package/src/lib/editor/Editor.test.ts +20 -0
  94. package/src/lib/editor/Editor.ts +221 -259
  95. package/src/lib/editor/derivations/bindingsIndex.ts +3 -0
  96. package/src/lib/editor/managers/TextManager/TextManager.test.ts +74 -0
  97. package/src/lib/editor/managers/TextManager/TextManager.ts +6 -5
  98. package/src/lib/editor/shapes/group/GroupShapeUtil.tsx +23 -8
  99. package/src/lib/exports/ExportDelay.tsx +16 -4
  100. package/src/lib/exports/FontEmbedder.test.ts +99 -0
  101. package/src/lib/exports/FontEmbedder.ts +32 -11
  102. package/src/lib/exports/StyleEmbedder.ts +13 -4
  103. package/src/lib/exports/fetchCache.test.ts +22 -0
  104. package/src/lib/exports/fetchCache.ts +4 -0
  105. package/src/lib/exports/getSvgAsImage.ts +13 -5
  106. package/src/lib/exports/getSvgJsx.test.ts +43 -1
  107. package/src/lib/exports/getSvgJsx.tsx +28 -16
  108. package/src/lib/exports/parseCss.test.ts +4 -0
  109. package/src/lib/exports/parseCss.ts +2 -2
  110. package/src/lib/hooks/useCanvasEvents.ts +42 -0
  111. package/src/lib/hooks/useIdentity.tsx +12 -1
  112. package/src/lib/license/LicenseManager.ts +13 -1
  113. package/src/lib/license/LicenseProvider.test.tsx +76 -0
  114. package/src/lib/license/LicenseProvider.tsx +19 -5
  115. package/src/lib/test/preserveFocus.test.tsx +81 -0
  116. package/src/lib/utils/deepLinks.test.ts +15 -0
  117. package/src/lib/utils/deepLinks.ts +8 -3
  118. package/src/lib/utils/sync/LocalIndexedDb.test.ts +28 -0
  119. package/src/lib/utils/sync/LocalIndexedDb.ts +18 -20
  120. package/src/lib/utils/sync/TLLocalSyncClient.test.ts +236 -0
  121. package/src/lib/utils/sync/TLLocalSyncClient.ts +106 -54
  122. package/src/version.ts +3 -3
  123. package/dist-cjs/lib/primitives/geometry/geometry.bench.js +0 -133
  124. package/dist-cjs/lib/primitives/geometry/geometry.bench.js.map +0 -7
  125. package/dist-esm/lib/primitives/geometry/geometry.bench.mjs +0 -132
  126. package/dist-esm/lib/primitives/geometry/geometry.bench.mjs.map +0 -7
  127. package/src/lib/primitives/geometry/geometry.bench.ts +0 -179
@@ -102,7 +102,12 @@ function measureContentBounds(canvas, trimPaddingPx) {
102
102
  const ctx = canvas.getContext("2d");
103
103
  const extraPx = Math.ceil(trimPaddingPx);
104
104
  if (extraPx <= 0 || extraPx * 2 >= w || extraPx * 2 >= h) return null;
105
- const imageData = ctx.getImageData(0, 0, w, h);
105
+ let imageData;
106
+ try {
107
+ imageData = ctx.getImageData(0, 0, w, h);
108
+ } catch {
109
+ return null;
110
+ }
106
111
  const data = imageData.data;
107
112
  const cornerR = data[0];
108
113
  const cornerG = data[1];
@@ -204,12 +209,13 @@ function trimExtraPadding(canvas, trimPaddingPx) {
204
209
  async function trimSvgToContent(svgString, options) {
205
210
  const { width, height, trimPadding, scale } = options;
206
211
  if (trimPadding <= 0) return null;
207
- const canvasWidth = Math.floor(width);
208
- const canvasHeight = Math.floor(height);
212
+ let [canvasWidth, canvasHeight] = (0, import_browserCanvasMaxSize.clampToBrowserMaxCanvasSize)(width, height);
213
+ canvasWidth = Math.floor(canvasWidth);
214
+ canvasHeight = Math.floor(canvasHeight);
209
215
  if (canvasWidth <= 0 || canvasHeight <= 0) return null;
210
216
  const canvas = await renderSvgToCanvas(svgString, canvasWidth, canvasHeight);
211
217
  if (!canvas) return null;
212
- const trimPaddingPx = trimPadding * scale;
218
+ const trimPaddingPx = trimPadding * scale * (canvasWidth / width);
213
219
  const bounds = measureContentBounds(canvas, trimPaddingPx);
214
220
  if (!bounds) return null;
215
221
  const { cropLeft, cropTop, cropRight, cropBottom } = bounds;
@@ -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'\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;AAAA;AAAA;AAAA,mBAAsD;AACtD,yBAAsB;AACtB,kCAA4C;AAC5C,yBAA2B;AAC3B,iBAAkC;AAGlC,eAAsB,cACrB,WACA,SAOC;AACD,QAAM,SAAS,MAAM,yBAAyB,WAAW,OAAO;AAChE,SAAO,QAAQ,QAAQ;AACxB;AAGA,eAAsB,yBACrB,WACA,SASgE;AAChE,QAAM,EAAE,MAAM,OAAO,QAAQ,UAAU,GAAG,aAAa,GAAG,cAAc,GAAG,QAAQ,EAAE,IAAI;AAEzF,MAAI,SAAS,KAAK,UAAU,EAAG,QAAO;AAEtC,MAAI,CAAC,cAAc,aAAa,QAAI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,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;",
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\tlet imageData: ImageData\n\ttry {\n\t\timageData = ctx.getImageData(0, 0, w, h)\n\t} catch {\n\t\t// a tainted or unallocatable canvas can't be measured; export untrimmed rather than fail\n\t\treturn null\n\t}\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, clamped like the raster path so a\n\t// large export doesn't exceed the browser's canvas limits\n\tlet [canvasWidth, canvasHeight] = clampToBrowserMaxCanvasSize(width, height)\n\tcanvasWidth = Math.floor(canvasWidth)\n\tcanvasHeight = Math.floor(canvasHeight)\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 * (canvasWidth / width)\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;AAAA;AAAA;AAAA,mBAAsD;AACtD,yBAAsB;AACtB,kCAA4C;AAC5C,yBAA2B;AAC3B,iBAAkC;AAGlC,eAAsB,cACrB,WACA,SAOC;AACD,QAAM,SAAS,MAAM,yBAAyB,WAAW,OAAO;AAChE,SAAO,QAAQ,QAAQ;AACxB;AAGA,eAAsB,yBACrB,WACA,SASgE;AAChE,QAAM,EAAE,MAAM,OAAO,QAAQ,UAAU,GAAG,aAAa,GAAG,cAAc,GAAG,QAAQ,EAAE,IAAI;AAEzF,MAAI,SAAS,KAAK,UAAU,EAAG,QAAO;AAEtC,MAAI,CAAC,cAAc,aAAa,QAAI;AAAA,IACnC,QAAQ;AAAA,IACR,SAAS;AAAA,EACV;AACA,iBAAe,KAAK,MAAM,YAAY;AACtC,kBAAgB,KAAK,MAAM,aAAa;AACxC,QAAM,iBAAiB,eAAe;AAEtC,QAAM,SAAS,MAAM,kBAAkB,WAAW,cAAc,aAAa;AAE7E,MAAI,CAAC,OAAQ,QAAO;AAGpB,QAAM,eACL,cAAc,IACX,iBAAiB,QAAQ,cAAc,QAAQ,cAAc,IAC7D,EAAE,QAAQ,OAAO,cAAc,QAAQ,cAAc;AAEzD,QAAM,OAAO,MAAM,IAAI;AAAA,IAAqB,CAAC,YAC5C,aAAa,OAAO;AAAA,MACnB,CAACA,UAAS;AACT,YAAI,CAACA,SAAQ,8BAAW,YAAY,IAAI,GAAG;AAC1C,kBAAQ,IAAI;AAAA,QACb;AACA,gBAAQA,KAAI;A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;AACrC,QAAM,eAAe,WAAW,kBAAkB,KAAK;AAEvD,SAAO,EAAE,KAAK,cAAc,OAAO,UAAU,QAAQ,UAAU;AAChE;",
6
6
  "names": ["blob"]
7
7
  }
@@ -24,6 +24,7 @@ __export(getSvgJsx_exports, {
24
24
  module.exports = __toCommonJS(getSvgJsx_exports);
25
25
  var import_jsx_runtime = require("react/jsx-runtime");
26
26
  var import_state_react = require("@tldraw/state-react");
27
+ var import_tlschema = require("@tldraw/tlschema");
27
28
  var import_utils = require("@tldraw/utils");
28
29
  var import_react = require("react");
29
30
  var import_react_dom = require("react-dom");
@@ -93,6 +94,7 @@ function getSvgJsx(editor, ids, opts = {}) {
93
94
  colorMode,
94
95
  renderingShapes,
95
96
  onMount: initialEffectPromise.resolve,
97
+ onError: exportDelay.fail,
96
98
  waitUntil: exportDelay.waitUntil
97
99
  }
98
100
  );
@@ -140,6 +142,7 @@ function SvgExport({
140
142
  colorMode,
141
143
  renderingShapes,
142
144
  onMount,
145
+ onError,
143
146
  waitUntil
144
147
  }) {
145
148
  const masksId = (0, import_useSafeId.useUniqueSafeId)();
@@ -302,8 +305,17 @@ function SvgExport({
302
305
  defsById: { ...state.defsById, ...shapeDefs }
303
306
  }));
304
307
  });
305
- })();
306
- }, [bbox, editor, exportContext, masksId, renderingShapes, singleFrameShapeId, stateAtom]);
308
+ })().catch(onError);
309
+ }, [
310
+ bbox,
311
+ editor,
312
+ exportContext,
313
+ masksId,
314
+ onError,
315
+ renderingShapes,
316
+ singleFrameShapeId,
317
+ stateAtom
318
+ ]);
307
319
  (0, import_react.useEffect)(() => {
308
320
  const fontsInUse = /* @__PURE__ */ new Set();
309
321
  for (const { id } of renderingShapes) {
@@ -328,13 +340,10 @@ function SvgExport({
328
340
  const colors = theme.colors[colorMode];
329
341
  let backgroundColor = background ? colors.background : "transparent";
330
342
  if (singleFrameShapeId && background) {
331
- const frameShapeUtil = editor.getShapeUtil("frame");
332
- if (frameShapeUtil?.options.showColors) {
333
- const shape = editor.getShape(singleFrameShapeId);
334
- backgroundColor = (0, import_defaultThemes.getColorValue)(colors, shape.props.color, "frameFill");
335
- } else {
336
- backgroundColor = colors.solid;
337
- }
343
+ const shape = editor.getShape(singleFrameShapeId);
344
+ const { showColors } = editor.getShapeUtil(shape).options;
345
+ const color = showColors ? editor.getShapeStyleIfExists(shape, import_tlschema.DefaultColorStyle) ?? ("color" in shape.props ? shape.props.color : null) : null;
346
+ backgroundColor = typeof color === "string" ? (0, import_defaultThemes.getColorValue)(colors, color, "frameFill") : colors.solid;
338
347
  }
339
348
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_SvgExportContext.SvgExportContextProvider, { editor, context: exportContext, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
340
349
  "svg",
@@ -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 { TLFrameShape, TLShape, TLShapeId } from '@tldraw/tlschema'\nimport { TLFontFace } 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 { getColorValue } from '../editor/managers/ThemeManager/defaultThemes'\nimport { ShapeUtil } from '../editor/shapes/ShapeUtil'\nimport { TLImageExportOptions } from '../editor/types/misc-types'\nimport {\n\tSvgExportContext,\n\tSvgExportContextProvider,\n\tSvgExportDef,\n} from '../editor/types/SvgExportContext'\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 colorMode: 'light' | 'dark' =\n\t\topts.darkMode !== undefined ? (opts.darkMode ? 'dark' : 'light') : editor.getColorMode()\n\tconst isDarkMode = colorMode === 'dark'\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 singleFrameShape = ids.length === 1 ? editor.getShape(ids[0]) : null\n\tconst singleFrameShapeId =\n\t\tsingleFrameShape && editor.isShapeFrameLike(singleFrameShape) ? 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\tcolorMode={colorMode}\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\tcolorMode,\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\tcolorMode: 'light' | 'dark'\n\trenderingShapes: TLRenderingShape[]\n\tonMount(): void\n\twaitUntil(promise: Promise<void>): void\n}) {\n\tconst masksId = useUniqueSafeId()\n\tconst theme = editor.getCurrentTheme()\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\tcolorMode,\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, colorMode, 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\tconst colors = theme.colors[colorMode]\n\tlet backgroundColor = background ? colors.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| {\n\t\t\t\t\toptions: {\n\t\t\t\t\t\tshowColors: boolean\n\t\t\t\t\t}\n\t\t\t }\n\t\tif (frameShapeUtil?.options.showColors) {\n\t\t\tconst shape = editor.getShape(singleFrameShapeId)! as TLFrameShape\n\t\t\tbackgroundColor = getColorValue(colors, shape.props.color, 'frameFill')\n\t\t} else {\n\t\t\tbackgroundColor = colors.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;AA2GE;AA3GF,yBAAkC;AAGlC,mBAA6D;AAC7D,mBASO;AACP,uBAA0B;AAC1B,2BAA8B;AAC9B,mBAAiD;AAEjD,2BAA8B;AAG9B,8BAIO;AACP,uBAA0B;AAC1B,sBAAyB;AACzB,uBAA8C;AAC9C,iBAAoB;AACpB,iBAAoB;AACpB,yBAA4B;AAErB,S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EACtC;AAEA,QAAM,SAAS,OAAO,iBAAiB,MAAM,EAAE,EAAE;AACjD,QAAM,QAAQ,KAAK,IAAI,OAAO,OAAO,CAAC;AACtC,QAAM,SAAS,KAAK,IAAI,OAAO,QAAQ,CAAC;AAExC,SACC,4CAAC,sCAAc,UAAU,MAAM,MAC9B;AAAA,IAAC;AAAA;AAAA,MACA,GAAG,KAAK;AAAA,MACR,GAAG,KAAK;AAAA,MACR,OAAO,KAAK;AAAA,MACZ,QAAQ,KAAK;AAAA,MACb,WAAU;AAAA,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 { DefaultColorStyle, TLShape, TLShapeId } from '@tldraw/tlschema'\nimport { TLFontFace } 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 { getColorValue } from '../editor/managers/ThemeManager/defaultThemes'\nimport { ShapeUtil } from '../editor/shapes/ShapeUtil'\nimport { TLImageExportOptions } from '../editor/types/misc-types'\nimport {\n\tSvgExportContext,\n\tSvgExportContextProvider,\n\tSvgExportDef,\n} from '../editor/types/SvgExportContext'\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 colorMode: 'light' | 'dark' =\n\t\topts.darkMode !== undefined ? (opts.darkMode ? 'dark' : 'light') : editor.getColorMode()\n\tconst isDarkMode = colorMode === 'dark'\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 singleFrameShape = ids.length === 1 ? editor.getShape(ids[0]) : null\n\tconst singleFrameShapeId =\n\t\tsingleFrameShape && editor.isShapeFrameLike(singleFrameShape) ? 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\tcolorMode={colorMode}\n\t\t\trenderingShapes={renderingShapes}\n\t\t\tonMount={initialEffectPromise.resolve}\n\t\t\tonError={exportDelay.fail}\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\tcolorMode,\n\trenderingShapes,\n\tonMount,\n\tonError,\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\tcolorMode: 'light' | 'dark'\n\trenderingShapes: TLRenderingShape[]\n\tonMount(): void\n\tonError(error: unknown): void\n\twaitUntil(promise: Promise<void>): void\n}) {\n\tconst masksId = useUniqueSafeId()\n\tconst theme = editor.getCurrentTheme()\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\tcolorMode,\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, colorMode, 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// the promise is caught at the end: a throwing `toSvg` would otherwise leave `onMount`\n\t\t// pending forever, so the export would wait out its max delay and snapshot an empty svg\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})().catch(onError)\n\t}, [\n\t\tbbox,\n\t\teditor,\n\t\texportContext,\n\t\tmasksId,\n\t\tonError,\n\t\trenderingShapes,\n\t\tsingleFrameShapeId,\n\t\tstateAtom,\n\t])\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\tconst colors = theme.colors[colorMode]\n\tlet backgroundColor = background ? colors.background : 'transparent'\n\n\tif (singleFrameShapeId && background) {\n\t\t// the frame-like shape's own util decides this - it may not be the default 'frame' util\n\t\tconst shape = editor.getShape(singleFrameShapeId)!\n\t\tconst { showColors } = editor.getShapeUtil(shape).options as { showColors?: boolean }\n\t\t// the color style may live under any prop key, so look it up through the style map and\n\t\t// fall back to a literal `color` prop for frame-like shapes that don't use the style\n\t\tconst color = showColors\n\t\t\t? (editor.getShapeStyleIfExists(shape, DefaultColorStyle) ??\n\t\t\t\t('color' in shape.props ? shape.props.color : null))\n\t\t\t: null\n\t\tbackgroundColor =\n\t\t\ttypeof color === 'string' ? getColorValue(colors, color, 'frameFill') : colors.solid\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\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C,WAAW,qCAAqC,aAAa,mBAAmB,iBAAiB;AAAA,MAEjG;AAAA,oDAAC,UACC,iBAAO,QAAQ,QAAQ,EAAE;AAAA,UAAI,CAAC,CAAC,KAAK,GAAG,MACvC,IAAI,UAAU,OAAO,4CAAC,yBAAoB,cAAI,WAAV,GAAkB;AAAA,QACvD,GACD;AAAA,QACC;AAAA;AAAA;AAAA,EACF,GACD;AAEF;AAEA,SAAS,mBAAmB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EACX;AAAA,EACA;AACD,GAOG;AACF,QAAM,aAAS,4BAAU;AAEzB,QAAM,YAAY,eAAI,UAAU,CAAC,KAAK,MAAM,CAAC,KAAK,IAAI,EAAE;AAAA,IACvD,OAAO,sBAAsB,MAAM,EAAE;AAAA,EACtC;AAEA,QAAM,SAAS,OAAO,iBAAiB,MAAM,EAAE,EAAE;AACjD,QAAM,QAAQ,KAAK,IAAI,OAAO,OAAO,CAAC;AACtC,QAAM,SAAS,KAAK,IAAI,OAAO,QAAQ,CAAC;AAExC,SACC,4CAAC,sCAAc,UAAU,MAAM,MAC9B;AAAA,IAAC;AAAA;AAAA,MACA,GAAG,KAAK;AAAA,MACR,GAAG,KAAK;AAAA,MACR,OAAO,KAAK;AAAA,MACZ,QAAQ,KAAK;AAAA,MACb,WAAU;AAAA,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;",
6
6
  "names": ["state", "scale"]
7
7
  }
@@ -27,7 +27,7 @@ __export(parseCss_exports, {
27
27
  });
28
28
  module.exports = __toCommonJS(parseCss_exports);
29
29
  var import_utils = require("@tldraw/utils");
30
- const importsRegex = /@import\s+(?:"([^"]+)"|'([^']+)'|url\s*\(\s*(?:"([^"]+)"|'([^']+)'|([^'")]+))\s*\))([^;]+);/gi;
30
+ const importsRegex = /@import\s+(?:"([^"]+)"|'([^']+)'|url\s*\(\s*(?:"([^"]+)"|'([^']+)'|([^'")]+))\s*\))([^;]*);/gi;
31
31
  const fontFaceRegex = /@font-face\s*{([^}]+)}/gi;
32
32
  const urlsRegex = /url\s*\(\s*(?:"([^"]+)"|'([^']+)'|([^'")]+))\s*\)/gi;
33
33
  const fontFamilyRegex = /(?:^|;)\s*font-family\s*:\s*(?:([^'"][^;\n]+)|"([^"]+)"|'([^']+)')\s*(?:;|$)/gi;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/exports/parseCss.ts"],
4
- "sourcesContent": ["import { safeParseUrl } from '@tldraw/utils'\n\nexport interface ParsedFontFace {\n\tfontFace: string\n\turls: { original: string; resolved: string | null; embedded?: Promise<string | null> }[]\n\tfontFamilies: Set<string>\n}\n\n// parsing CSS with regular expressions doesn't really work. There are almost certainly edge cases\n// in the regular expressions we're using here. They're based formal grammars of CSS, but aren't\n// perfect. These were written with https://regexper.com/ - give it a go if you're editing these.\n\n// The regexes themselves would be nicer to work with if we were using named capturing groups\n// (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group).\n// We use a lot of disjunctions (the `|`) to cover different syntaxes though, and at the time of\n// writing, browser support for using named capturing groups across disjunctions is rough.\n\n// Parse @import declarations:\n// https://developer.mozilla.org/en-US/docs/Web/CSS/@import#formal_syntax\nconst importsRegex =\n\t/@import\\s+(?:\"([^\"]+)\"|'([^']+)'|url\\s*\\(\\s*(?:\"([^\"]+)\"|'([^']+)'|([^'\")]+))\\s*\\))([^;]+);/gi\n\n// Locate @font-face declarations:\nconst fontFaceRegex = /@font-face\\s*{([^}]+)}/gi\n\n// Parse url() calls within a CSS value:\n// https://developer.mozilla.org/en-US/docs/Web/CSS/url#syntax\nconst urlsRegex = /url\\s*\\(\\s*(?:\"([^\"]+)\"|'([^']+)'|([^'\")]+))\\s*\\)/gi\n\n// Locate and parse the value of `font-family` within a @font-face declaration:\n// https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-family#formal_syntax\nconst fontFamilyRegex =\n\t/(?:^|;)\\s*font-family\\s*:\\s*(?:([^'\"][^;\\n]+)|\"([^\"]+)\"|'([^']+)')\\s*(?:;|$)/gi\n\nexport function parseCssImports(css: string) {\n\treturn Array.from(css.matchAll(importsRegex), (m) => ({\n\t\turl: m[1] || m[2] || m[3] || m[4] || m[5],\n\t\textras: m[6],\n\t}))\n}\n\nexport function parseCssFontFaces(css: string, baseUrl: string) {\n\treturn Array.from(css.matchAll(fontFaceRegex), (m): ParsedFontFace => {\n\t\tconst fontFace = m[1]\n\t\tconst urls = Array.from(fontFace.matchAll(urlsRegex), (m) => {\n\t\t\tconst original = m[1] || m[2] || m[3]\n\t\t\treturn {\n\t\t\t\toriginal,\n\t\t\t\tresolved: safeParseUrl(original, baseUrl)?.href ?? null,\n\t\t\t}\n\t\t})\n\t\tconst fontFamilies = new Set(\n\t\t\tArray.from(fontFace.matchAll(fontFamilyRegex), (m) => (m[1] || m[2] || m[3]).toLowerCase())\n\t\t)\n\n\t\treturn { fontFace, urls, fontFamilies }\n\t})\n}\n\nexport function parseCssFontFamilyValue(value: string) {\n\t// https://developer.mozilla.org/en-US/docs/Web/CSS/font-family#formal_syntax\n\t// we use two regexes here to parse each value in a comma separated list of font families\n\tconst valueRegex = /\\s*(?:([^'\"][^;\\n\\s,]+)|\"([^\"]+)\"|'([^']+)')\\s*/gi\n\tconst separatorRegex = /\\s*,\\s*/gi\n\n\tconst fontFamilies = new Set<string>()\n\n\twhile (true) {\n\t\tconst valueMatch = valueRegex.exec(value)\n\t\tif (!valueMatch) {\n\t\t\tbreak\n\t\t}\n\n\t\tconst fontFamily = valueMatch[1] || valueMatch[2] || valueMatch[3]\n\t\tfontFamilies.add(fontFamily.toLowerCase())\n\n\t\tseparatorRegex.lastIndex = valueRegex.lastIndex\n\t\tconst separatorMatch = separatorRegex.exec(value)\n\t\tif (!separatorMatch) {\n\t\t\tbreak\n\t\t}\n\n\t\tvalueRegex.lastIndex = separatorRegex.lastIndex\n\t}\n\n\treturn fontFamilies\n}\n\nexport function shouldIncludeCssProperty(property: string) {\n\tif (property.startsWith('-')) return false\n\tif (property.startsWith('animation')) return false\n\tif (property.startsWith('transition')) return false\n\tif (property === 'cursor') return false\n\tif (property === 'pointer-events') return false\n\tif (property === 'user-select') return false\n\tif (property === 'touch-action') return false\n\treturn true\n}\n\nexport function parseCss(css: string, baseUrl: string) {\n\treturn {\n\t\timports: parseCssImports(css),\n\t\tfontFaces: parseCssFontFaces(css, baseUrl),\n\t}\n}\n\nexport function parseCssValueUrls(value: string) {\n\treturn Array.from(value.matchAll(urlsRegex), (m) => ({\n\t\toriginal: m[0],\n\t\turl: m[1] || m[2] || m[3],\n\t})).filter((m) => !m.url.startsWith('#'))\n}\n"],
4
+ "sourcesContent": ["import { safeParseUrl } from '@tldraw/utils'\n\nexport interface ParsedFontFace {\n\tfontFace: string\n\turls: { original: string; resolved: string | null }[]\n\tfontFamilies: Set<string>\n}\n\n// parsing CSS with regular expressions doesn't really work. There are almost certainly edge cases\n// in the regular expressions we're using here. They're based formal grammars of CSS, but aren't\n// perfect. These were written with https://regexper.com/ - give it a go if you're editing these.\n\n// The regexes themselves would be nicer to work with if we were using named capturing groups\n// (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group).\n// We use a lot of disjunctions (the `|`) to cover different syntaxes though, and at the time of\n// writing, browser support for using named capturing groups across disjunctions is rough.\n\n// Parse @import declarations:\n// https://developer.mozilla.org/en-US/docs/Web/CSS/@import#formal_syntax\nconst importsRegex =\n\t/@import\\s+(?:\"([^\"]+)\"|'([^']+)'|url\\s*\\(\\s*(?:\"([^\"]+)\"|'([^']+)'|([^'\")]+))\\s*\\))([^;]*);/gi\n\n// Locate @font-face declarations:\nconst fontFaceRegex = /@font-face\\s*{([^}]+)}/gi\n\n// Parse url() calls within a CSS value:\n// https://developer.mozilla.org/en-US/docs/Web/CSS/url#syntax\nconst urlsRegex = /url\\s*\\(\\s*(?:\"([^\"]+)\"|'([^']+)'|([^'\")]+))\\s*\\)/gi\n\n// Locate and parse the value of `font-family` within a @font-face declaration:\n// https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-family#formal_syntax\nconst fontFamilyRegex =\n\t/(?:^|;)\\s*font-family\\s*:\\s*(?:([^'\"][^;\\n]+)|\"([^\"]+)\"|'([^']+)')\\s*(?:;|$)/gi\n\nexport function parseCssImports(css: string) {\n\treturn Array.from(css.matchAll(importsRegex), (m) => ({\n\t\turl: m[1] || m[2] || m[3] || m[4] || m[5],\n\t\textras: m[6],\n\t}))\n}\n\nexport function parseCssFontFaces(css: string, baseUrl: string) {\n\treturn Array.from(css.matchAll(fontFaceRegex), (m): ParsedFontFace => {\n\t\tconst fontFace = m[1]\n\t\tconst urls = Array.from(fontFace.matchAll(urlsRegex), (m) => {\n\t\t\tconst original = m[1] || m[2] || m[3]\n\t\t\treturn {\n\t\t\t\toriginal,\n\t\t\t\tresolved: safeParseUrl(original, baseUrl)?.href ?? null,\n\t\t\t}\n\t\t})\n\t\tconst fontFamilies = new Set(\n\t\t\tArray.from(fontFace.matchAll(fontFamilyRegex), (m) => (m[1] || m[2] || m[3]).toLowerCase())\n\t\t)\n\n\t\treturn { fontFace, urls, fontFamilies }\n\t})\n}\n\nexport function parseCssFontFamilyValue(value: string) {\n\t// https://developer.mozilla.org/en-US/docs/Web/CSS/font-family#formal_syntax\n\t// we use two regexes here to parse each value in a comma separated list of font families\n\tconst valueRegex = /\\s*(?:([^'\"][^;\\n\\s,]+)|\"([^\"]+)\"|'([^']+)')\\s*/gi\n\tconst separatorRegex = /\\s*,\\s*/gi\n\n\tconst fontFamilies = new Set<string>()\n\n\twhile (true) {\n\t\tconst valueMatch = valueRegex.exec(value)\n\t\tif (!valueMatch) {\n\t\t\tbreak\n\t\t}\n\n\t\tconst fontFamily = valueMatch[1] || valueMatch[2] || valueMatch[3]\n\t\tfontFamilies.add(fontFamily.toLowerCase())\n\n\t\tseparatorRegex.lastIndex = valueRegex.lastIndex\n\t\tconst separatorMatch = separatorRegex.exec(value)\n\t\tif (!separatorMatch) {\n\t\t\tbreak\n\t\t}\n\n\t\tvalueRegex.lastIndex = separatorRegex.lastIndex\n\t}\n\n\treturn fontFamilies\n}\n\nexport function shouldIncludeCssProperty(property: string) {\n\tif (property.startsWith('-')) return false\n\tif (property.startsWith('animation')) return false\n\tif (property.startsWith('transition')) return false\n\tif (property === 'cursor') return false\n\tif (property === 'pointer-events') return false\n\tif (property === 'user-select') return false\n\tif (property === 'touch-action') return false\n\treturn true\n}\n\nexport function parseCss(css: string, baseUrl: string) {\n\treturn {\n\t\timports: parseCssImports(css),\n\t\tfontFaces: parseCssFontFaces(css, baseUrl),\n\t}\n}\n\nexport function parseCssValueUrls(value: string) {\n\treturn Array.from(value.matchAll(urlsRegex), (m) => ({\n\t\toriginal: m[0],\n\t\turl: m[1] || m[2] || m[3],\n\t})).filter((m) => !m.url.startsWith('#'))\n}\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA6B;AAmB7B,MAAM,eACL;AAGD,MAAM,gBAAgB;AAItB,MAAM,YAAY;AAIlB,MAAM,kBACL;AAEM,SAAS,gBAAgB,KAAa;AAC5C,SAAO,MAAM,KAAK,IAAI,SAAS,YAAY,GAAG,CAAC,OAAO;AAAA,IACrD,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC;AAAA,IACxC,QAAQ,EAAE,CAAC;AAAA,EACZ,EAAE;AACH;AAEO,S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C,MAAI,aAAa,iBAAkB,QAAO;AAC1C,MAAI,aAAa,cAAe,QAAO;AACvC,MAAI,aAAa,eAAgB,QAAO;AACxC,SAAO;AACR;AAEO,SAAS,SAAS,KAAa,SAAiB;AACtD,SAAO;AAAA,IACN,SAAS,gBAAgB,GAAG;AAAA,IAC5B,WAAW,kBAAkB,KAAK,OAAO;AAAA,EAC1C;AACD;AAEO,SAAS,kBAAkB,OAAe;AAChD,SAAO,MAAM,KAAK,MAAM,SAAS,SAAS,GAAG,CAAC,OAAO;AAAA,IACpD,UAAU,EAAE,CAAC;AAAA,IACb,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC;AAAA,EACzB,EAAE,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,WAAW,GAAG,CAAC;AACzC;",
6
6
  "names": ["m"]
7
7
  }
@@ -35,6 +35,7 @@ function useCanvasEvents() {
35
35
  const events = (0, import_react.useMemo)(
36
36
  function canvasEvents() {
37
37
  let isSecondaryClickPointerDown = false;
38
+ const pointerDownButtons = /* @__PURE__ */ new Map();
38
39
  function onPointerDown(e) {
39
40
  if (editor.wasEventAlreadyHandled(e)) return;
40
41
  const button = (0, import_pointer.getPointerEventButton)(e);
@@ -51,6 +52,10 @@ function useCanvasEvents() {
51
52
  if (button !== 0 && button !== 1 && button !== 2 && button !== 5) return;
52
53
  const isPenDirect = (0, import_pointer.isDirectDisplayPen)(e);
53
54
  (0, import_dom.setPointerCapture)(e.currentTarget, e);
55
+ const isPenMode = editor.getInstanceState().isPenMode;
56
+ if (!editor.inputs.getIsPinching() && !(isPenMode && e.pointerType !== "pen")) {
57
+ pointerDownButtons.set(e.pointerId, button);
58
+ }
54
59
  editor.dispatch({
55
60
  type: "pointer",
56
61
  target: "canvas",
@@ -61,6 +66,7 @@ function useCanvasEvents() {
61
66
  }
62
67
  function onPointerUp(e) {
63
68
  if (editor.wasEventAlreadyHandled(e)) return;
69
+ pointerDownButtons.delete(e.pointerId);
64
70
  const button = isSecondaryClickPointerDown ? 2 : (0, import_pointer.getPointerEventButton)(e);
65
71
  if (button !== 0 && button !== 1 && button !== 2 && button !== 5) return;
66
72
  const rightClickPanning = editor.options.rightClickPanning;
@@ -88,6 +94,23 @@ function useCanvasEvents() {
88
94
  }
89
95
  isSecondaryClickPointerDown = false;
90
96
  }
97
+ function onPointerCancel(e) {
98
+ if (editor.wasEventAlreadyHandled(e)) return;
99
+ const pointerDownButton = pointerDownButtons.get(e.pointerId);
100
+ pointerDownButtons.delete(e.pointerId);
101
+ if (editor.getInstanceState().isPenMode && e.pointerType !== "pen") return;
102
+ (0, import_dom.releasePointerCapture)(e.currentTarget, e);
103
+ if (!editor.inputs.getIsPointing() || pointerDownButton === void 0) return;
104
+ editor.interrupt();
105
+ editor.dispatch({
106
+ type: "pointer",
107
+ target: "canvas",
108
+ name: "pointer_up",
109
+ ...(0, import_getPointerInfo.getPointerInfo)(editor, e),
110
+ button: pointerDownButton
111
+ });
112
+ isSecondaryClickPointerDown = false;
113
+ }
91
114
  function onPointerEnter(e) {
92
115
  if (editor.wasEventAlreadyHandled(e)) return;
93
116
  if (editor.getInstanceState().isPenMode && e.pointerType !== "pen") return;
@@ -169,6 +192,7 @@ function useCanvasEvents() {
169
192
  return {
170
193
  onPointerDown,
171
194
  onPointerUp,
195
+ onPointerCancel,
172
196
  onPointerEnter,
173
197
  onPointerLeave,
174
198
  onDragOver,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/hooks/useCanvasEvents.ts"],
4
- "sourcesContent": ["import { useValue } from '@tldraw/state-react'\nimport React, { useEffect, useMemo } from 'react'\nimport { tlenv } from '../globals/environment'\nimport {\n\telementShouldCaptureKeys,\n\tpreventDefault,\n\treleasePointerCapture,\n\tsetPointerCapture,\n} from '../utils/dom'\nimport { getPointerInfo } from '../utils/getPointerInfo'\nimport { getPointerEventButton, isDirectDisplayPen, isSecondaryClickEvent } from '../utils/pointer'\nimport { useEditor } from './useEditor'\n\nexport function useCanvasEvents() {\n\tconst editor = useEditor()\n\tconst ownerDocument = editor.getContainerDocument()\n\tconst currentTool = useValue('current tool', () => editor.getCurrentTool(), [editor])\n\n\tconst events = useMemo(\n\t\tfunction canvasEvents() {\n\t\t\tlet isSecondaryClickPointerDown = false\n\n\t\t\tfunction onPointerDown(e: React.PointerEvent) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\tconst button = getPointerEventButton(e)\n\t\t\t\tisSecondaryClickPointerDown = button === 2\n\n\t\t\t\t// With right-click panning disabled, fire right_click on press and let the\n\t\t\t\t// native contextmenu through so the menu opens at the pointer-down location.\n\t\t\t\tif (button === 2 && !editor.options.rightClickPanning) {\n\t\t\t\t\teditor.dispatch({\n\t\t\t\t\t\ttype: 'pointer',\n\t\t\t\t\t\ttarget: 'canvas',\n\t\t\t\t\t\tname: 'right_click',\n\t\t\t\t\t\t...getPointerInfo(editor, e),\n\t\t\t\t\t})\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif (button !== 0 && button !== 1 && button !== 2 && button !== 5) return\n\n\t\t\t\t// Detect direct-display pen input (Apple Pencil, Surface Pen on a touchscreen) so we\n\t\t\t\t// only auto-enable pen mode for it, not for an indirect desktop tablet stylus.\n\t\t\t\tconst isPenDirect = isDirectDisplayPen(e)\n\n\t\t\t\tsetPointerCapture(e.currentTarget, e)\n\n\t\t\t\teditor.dispatch({\n\t\t\t\t\ttype: 'pointer',\n\t\t\t\t\ttarget: 'canvas',\n\t\t\t\t\tname: 'pointer_down',\n\t\t\t\t\t...getPointerInfo(editor, e),\n\t\t\t\t\tisPenDirect,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tfunction onPointerUp(e: React.PointerEvent) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\tconst button = isSecondaryClickPointerDown ? 2 : getPointerEventButton(e)\n\t\t\t\tif (button !== 0 && button !== 1 && button !== 2 && button !== 5) return\n\n\t\t\t\tconst rightClickPanning = editor.options.rightClickPanning\n\t\t\t\t// Check before dispatch (which resets isPanning)\n\t\t\t\tconst wasRightClickPanning =\n\t\t\t\t\trightClickPanning && button === 2 && editor.inputs.getIsPanning()\n\n\t\t\t\treleasePointerCapture(e.currentTarget, e)\n\n\t\t\t\teditor.dispatch({\n\t\t\t\t\ttype: 'pointer',\n\t\t\t\t\ttarget: 'canvas',\n\t\t\t\t\tname: 'pointer_up',\n\t\t\t\t\t...getPointerInfo(editor, e),\n\t\t\t\t\tbutton,\n\t\t\t\t})\n\n\t\t\t\t// Static right-click: fire contextmenu at the pointer-up location\n\t\t\t\tif (rightClickPanning && button === 2 && !wasRightClickPanning) {\n\t\t\t\t\tconst contextMenuEvent = new PointerEvent('contextmenu', {\n\t\t\t\t\t\tbubbles: true,\n\t\t\t\t\t\tclientX: e.clientX,\n\t\t\t\t\t\tclientY: e.clientY,\n\t\t\t\t\t\tbutton: 2,\n\t\t\t\t\t\tbuttons: 0,\n\t\t\t\t\t\tpointerId: e.pointerId,\n\t\t\t\t\t\tpointerType: e.pointerType,\n\t\t\t\t\t\tisPrimary: e.isPrimary,\n\t\t\t\t\t})\n\t\t\t\t\te.currentTarget.dispatchEvent(contextMenuEvent)\n\t\t\t\t}\n\t\t\t\tisSecondaryClickPointerDown = false\n\t\t\t}\n\n\t\t\tfunction onPointerEnter(e: React.PointerEvent) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\tif (editor.getInstanceState().isPenMode && e.pointerType !== 'pen') return\n\t\t\t\tconst canHover = e.pointerType === 'mouse' || e.pointerType === 'pen'\n\t\t\t\teditor.updateInstanceState({ isHoveringCanvas: canHover ? true : null })\n\t\t\t}\n\n\t\t\tfunction onPointerLeave(e: React.PointerEvent) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\tif (editor.getInstanceState().isPenMode && e.pointerType !== 'pen') return\n\t\t\t\tconst canHover = e.pointerType === 'mouse' || e.pointerType === 'pen'\n\t\t\t\teditor.updateInstanceState({ isHoveringCanvas: canHover ? false : null })\n\t\t\t}\n\n\t\t\tfunction onTouchStart(e: React.TouchEvent) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\teditor.markEventAsHandled(e)\n\t\t\t\tpreventDefault(e)\n\t\t\t}\n\n\t\t\tfunction onTouchEnd(e: React.TouchEvent) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\teditor.markEventAsHandled(e)\n\t\t\t\tif (!(e.target instanceof editor.getContainerWindow().HTMLElement)) return\n\n\t\t\t\tconst editingShapeId = editor.getEditingShapeId()\n\t\t\t\tif (\n\t\t\t\t\t// if the target is not inside the editing shape\n\t\t\t\t\t!(editingShapeId && e.target.closest(`[data-shape-id=\"${editingShapeId}\"]`)) &&\n\t\t\t\t\t// and the target is not an clickable element\n\t\t\t\t\te.target.tagName !== 'A' &&\n\t\t\t\t\t// and the target is not an editable element\n\t\t\t\t\t!elementShouldCaptureKeys(e.target, false)\n\t\t\t\t) {\n\t\t\t\t\tpreventDefault(e)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfunction onDragOver(e: React.DragEvent<Element>) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\tpreventDefault(e)\n\t\t\t}\n\n\t\t\tasync function onDrop(e: React.DragEvent<Element>) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\tpreventDefault(e)\n\t\t\t\te.stopPropagation()\n\n\t\t\t\tconst pagePoint = editor.screenToPage({ x: e.clientX, y: e.clientY })\n\n\t\t\t\t// Call the custom onDropOnCanvas callback if provided\n\t\t\t\tif (editor.options.experimental__onDropOnCanvas) {\n\t\t\t\t\tconst handled = editor.options.experimental__onDropOnCanvas({\n\t\t\t\t\t\tpoint: pagePoint,\n\t\t\t\t\t\tevent: e,\n\t\t\t\t\t})\n\t\t\t\t\tif (handled) return\n\t\t\t\t}\n\n\t\t\t\tif (e.dataTransfer?.files?.length) {\n\t\t\t\t\tconst files = Array.from(e.dataTransfer.files)\n\n\t\t\t\t\teditor.markHistoryStoppingPoint('drop')\n\t\t\t\t\tawait editor.putExternalContent({\n\t\t\t\t\t\ttype: 'files',\n\t\t\t\t\t\tfiles,\n\t\t\t\t\t\tpoint: pagePoint,\n\t\t\t\t\t})\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconst url = e.dataTransfer.getData('url')\n\t\t\t\tif (url) {\n\t\t\t\t\teditor.markHistoryStoppingPoint('drop')\n\t\t\t\t\tawait editor.putExternalContent({\n\t\t\t\t\t\ttype: 'url',\n\t\t\t\t\t\turl,\n\t\t\t\t\t\tpoint: pagePoint,\n\t\t\t\t\t})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfunction onClick(e: React.MouseEvent) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\te.stopPropagation()\n\t\t\t}\n\n\t\t\tfunction onContextMenu(e: React.MouseEvent) {\n\t\t\t\t// With right-click panning disabled, let the native contextmenu through so the\n\t\t\t\t// menu opens on press.\n\t\t\t\tif (!editor.options.rightClickPanning) return\n\t\t\t\t// Synthetic events \u2014 our own dispatch from onPointerUp, or tests using\n\t\t\t\t// fireEvent.contextMenu \u2014 pass through so Radix can open the menu.\n\t\t\t\tif (!e.nativeEvent.isTrusted) return\n\t\t\t\t// Only suppress the native browser contextmenu when it follows a\n\t\t\t\t// secondary click. For those, our pointer handling has already\n\t\t\t\t// decided what to do (either we'll dispatch a synthetic contextmenu on\n\t\t\t\t// pointerup to open the menu at the release position, or we panned and\n\t\t\t\t// don't want a menu at all).\n\t\t\t\t//\n\t\t\t\t// Other contextmenu sources must reach Radix so the menu opens:\n\t\t\t\t// - long-press on touch devices (button=0, pointerType=touch)\n\t\t\t\tif (!isSecondaryClickEvent(e)) return\n\t\t\t\tpreventDefault(e)\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tonPointerDown,\n\t\t\t\tonPointerUp,\n\t\t\t\tonPointerEnter,\n\t\t\t\tonPointerLeave,\n\t\t\t\tonDragOver,\n\t\t\t\tonDrop,\n\t\t\t\tonTouchStart,\n\t\t\t\tonTouchEnd,\n\t\t\t\tonClick,\n\t\t\t\tonContextMenu,\n\t\t\t}\n\t\t},\n\t\t[editor]\n\t)\n\n\t// onPointerMove is special: where we're only interested in the other events when they're\n\t// happening _on_ the canvas (as opposed to outside of it, or on UI floating over it), we want\n\t// the pointer position to be up to date regardless of whether it's over the tldraw canvas or\n\t// not. So instead of returning a listener to be attached to the canvas, we directly attach a\n\t// listener to the whole document instead.\n\tuseEffect(() => {\n\t\tlet lastX: number, lastY: number\n\n\t\tfunction onPointerMove(e: PointerEvent) {\n\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\teditor.markEventAsHandled(e)\n\n\t\t\tif (e.clientX === lastX && e.clientY === lastY) return\n\t\t\tlastX = e.clientX\n\t\t\tlastY = e.clientY\n\n\t\t\t// For tools that benefit from a higher fidelity of events,\n\t\t\t// we dispatch the coalesced events.\n\t\t\t// N.B. Sometimes getCoalescedEvents isn't present on iOS, ugh.\n\t\t\t// Specifically, in local mode (non-https) mode, iOS does not `useCoalescedEvents`\n\t\t\t// so it appears like the ink is working locally, when really it's just that `useCoalescedEvents`\n\t\t\t// is disabled. The intent here is to have `useCoalescedEvents` disabled for iOS.\n\t\t\tconst events =\n\t\t\t\t!tlenv.isIos && currentTool.useCoalescedEvents && e.getCoalescedEvents\n\t\t\t\t\t? e.getCoalescedEvents()\n\t\t\t\t\t: [e]\n\n\t\t\tfor (const singleEvent of events) {\n\t\t\t\teditor.dispatch({\n\t\t\t\t\ttype: 'pointer',\n\t\t\t\t\ttarget: 'canvas',\n\t\t\t\t\tname: 'pointer_move',\n\t\t\t\t\t...getPointerInfo(editor, singleEvent),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\townerDocument.body.addEventListener('pointermove', onPointerMove)\n\t\treturn () => {\n\t\t\townerDocument.body.removeEventListener('pointermove', onPointerMove)\n\t\t}\n\t}, [editor, currentTool, ownerDocument])\n\n\treturn events\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAyB;AACzB,mBAA0C;AAC1C,yBAAsB;AACtB,iBAKO;AACP,4BAA+B;AAC/B,qBAAiF;AACjF,uBAA0B;AAEnB,SAAS,kBAAkB;AACjC,QAAM,aAAS,4BAAU;AACzB,QAAM,gBAAgB,OAAO,qBAAqB;AAClD,QAAM,kBAAc,6BAAS,gBAAgB,MAAM,OAAO,eAAe,GAAG,CAAC,MAAM,CAAC;AAEpF,QAAM,aAAS;AAAA,IACd,SAAS,eAAe;AACvB,UAAI,8BAA8B;AAElC,eAAS,cAAc,GAAuB;AAC7C,YAAI,OAAO,uBAAuB,CAAC,EAAG;AACtC,cAAM,aAAS,sCAAsB,CAAC;AACtC,sCAA8B,WAAW;AAIzC,YAAI,WAAW,KAAK,CAAC,OAAO,QAAQ,mBAAmB;AACtD,iBAAO,SAAS;AAAA,YACf,MAAM;AAAA,YACN,QAAQ;AAAA,YACR,MAAM;AAAA,YACN,OAAG,sCAAe,QAAQ,CAAC;AAAA,UAC5B,CAAC;AACD;AAAA,QACD;AAEA,YAAI,WAAW,KAAK,WAAW,KAAK,WAAW,KAAK,WAAW,EAAG;AAIlE,cAAM,kBAAc,mCAAmB,CAAC;AAExC,0CAAkB,EAAE,eAAe,CAAC;AAEpC,eAAO,SAAS;AAAA,UACf,MAAM;AAAA,UACN,QAAQ;AAAA,UACR,MAAM;AAAA,UACN,OAAG,sCAAe,QAAQ,CAAC;AAAA,UAC3B;AAAA,QACD,CAAC;AAAA,MACF;AAEA,eAAS,YAAY,GAAuB;AAC3C,YAAI,OAAO,uBAAuB,CAAC,EAAG;AACtC,cAAM,SAAS,8BAA8B,QAAI,sCAAsB,CAAC;AACxE,YAAI,WAAW,KAAK,WAAW,KAAK,WAAW,K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,UACR,CAAC;AACD;AAAA,QACD;AAAA,MACD;AAEA,eAAS,QAAQ,GAAqB;AACrC,YAAI,OAAO,uBAAuB,CAAC,EAAG;AACtC,UAAE,gBAAgB;AAAA,MACnB;AAEA,eAAS,cAAc,GAAqB;AAG3C,YAAI,CAAC,OAAO,QAAQ,kBAAmB;AAGvC,YAAI,CAAC,EAAE,YAAY,UAAW;AAS9B,YAAI,KAAC,sCAAsB,CAAC,EAAG;AAC/B,uCAAe,CAAC;AAAA,MACjB;AAEA,aAAO;AAAA,QACN;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACD;AAAA,IACD;AAAA,IACA,CAAC,MAAM;AAAA,EACR;AAOA,8BAAU,MAAM;AACf,QAAI,OAAe;AAEnB,aAAS,cAAc,GAAiB;AACvC,UAAI,OAAO,uBAAuB,CAAC,EAAG;AACtC,aAAO,mBAAmB,CAAC;AAE3B,UAAI,EAAE,YAAY,SAAS,EAAE,YAAY,MAAO;AAChD,cAAQ,EAAE;AACV,cAAQ,EAAE;AAQV,YAAMA,UACL,CAAC,yBAAM,SAAS,YAAY,sBAAsB,EAAE,qBACjD,EAAE,mBAAmB,IACrB,CAAC,CAAC;AAEN,iBAAW,eAAeA,SAAQ;AACjC,eAAO,SAAS;AAAA,UACf,MAAM;AAAA,UACN,QAAQ;AAAA,UACR,MAAM;AAAA,UACN,OAAG,sCAAe,QAAQ,WAAW;AAAA,QACtC,CAAC;AAAA,MACF;AAAA,IACD;AAEA,kBAAc,KAAK,iBAAiB,eAAe,aAAa;AAChE,WAAO,MAAM;AACZ,oBAAc,KAAK,oBAAoB,eAAe,aAAa;AAAA,IACpE;AAAA,EACD,GAAG,CAAC,QAAQ,aAAa,aAAa,CAAC;AAEvC,SAAO;AACR;",
4
+ "sourcesContent": ["import { useValue } from '@tldraw/state-react'\nimport React, { useEffect, useMemo } from 'react'\nimport { tlenv } from '../globals/environment'\nimport {\n\telementShouldCaptureKeys,\n\tpreventDefault,\n\treleasePointerCapture,\n\tsetPointerCapture,\n} from '../utils/dom'\nimport { getPointerInfo } from '../utils/getPointerInfo'\nimport { getPointerEventButton, isDirectDisplayPen, isSecondaryClickEvent } from '../utils/pointer'\nimport { useEditor } from './useEditor'\n\nexport function useCanvasEvents() {\n\tconst editor = useEditor()\n\tconst ownerDocument = editor.getContainerDocument()\n\tconst currentTool = useValue('current tool', () => editor.getCurrentTool(), [editor])\n\n\tconst events = useMemo(\n\t\tfunction canvasEvents() {\n\t\t\tlet isSecondaryClickPointerDown = false\n\t\t\t// The button each accepted press started with, by pointer id. pointercancel\n\t\t\t// reports button -1, so the synthetic pointer_up needs the original.\n\t\t\tconst pointerDownButtons = new Map<number, number>()\n\n\t\t\tfunction onPointerDown(e: React.PointerEvent) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\tconst button = getPointerEventButton(e)\n\t\t\t\tisSecondaryClickPointerDown = button === 2\n\n\t\t\t\t// With right-click panning disabled, fire right_click on press and let the\n\t\t\t\t// native contextmenu through so the menu opens at the pointer-down location.\n\t\t\t\tif (button === 2 && !editor.options.rightClickPanning) {\n\t\t\t\t\teditor.dispatch({\n\t\t\t\t\t\ttype: 'pointer',\n\t\t\t\t\t\ttarget: 'canvas',\n\t\t\t\t\t\tname: 'right_click',\n\t\t\t\t\t\t...getPointerInfo(editor, e),\n\t\t\t\t\t})\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif (button !== 0 && button !== 1 && button !== 2 && button !== 5) return\n\n\t\t\t\t// Detect direct-display pen input (Apple Pencil, Surface Pen on a touchscreen) so we\n\t\t\t\t// only auto-enable pen mode for it, not for an indirect desktop tablet stylus.\n\t\t\t\tconst isPenDirect = isDirectDisplayPen(e)\n\n\t\t\t\tsetPointerCapture(e.currentTarget, e)\n\n\t\t\t\t// Only remember presses the editor will act on. A rejected palm in pen mode\n\t\t\t\t// must not overwrite the button of the pen press it lands on top of, or the\n\t\t\t\t// pen's pointercancel would release the wrong button and skip the\n\t\t\t\t// stylus-eraser tool restore.\n\t\t\t\tconst isPenMode = editor.getInstanceState().isPenMode\n\t\t\t\tif (!editor.inputs.getIsPinching() && !(isPenMode && e.pointerType !== 'pen')) {\n\t\t\t\t\tpointerDownButtons.set(e.pointerId, button)\n\t\t\t\t}\n\n\t\t\t\teditor.dispatch({\n\t\t\t\t\ttype: 'pointer',\n\t\t\t\t\ttarget: 'canvas',\n\t\t\t\t\tname: 'pointer_down',\n\t\t\t\t\t...getPointerInfo(editor, e),\n\t\t\t\t\tisPenDirect,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tfunction onPointerUp(e: React.PointerEvent) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\tpointerDownButtons.delete(e.pointerId)\n\t\t\t\tconst button = isSecondaryClickPointerDown ? 2 : getPointerEventButton(e)\n\t\t\t\tif (button !== 0 && button !== 1 && button !== 2 && button !== 5) return\n\n\t\t\t\tconst rightClickPanning = editor.options.rightClickPanning\n\t\t\t\t// Check before dispatch (which resets isPanning)\n\t\t\t\tconst wasRightClickPanning =\n\t\t\t\t\trightClickPanning && button === 2 && editor.inputs.getIsPanning()\n\n\t\t\t\treleasePointerCapture(e.currentTarget, e)\n\n\t\t\t\teditor.dispatch({\n\t\t\t\t\ttype: 'pointer',\n\t\t\t\t\ttarget: 'canvas',\n\t\t\t\t\tname: 'pointer_up',\n\t\t\t\t\t...getPointerInfo(editor, e),\n\t\t\t\t\tbutton,\n\t\t\t\t})\n\n\t\t\t\t// Static right-click: fire contextmenu at the pointer-up location\n\t\t\t\tif (rightClickPanning && button === 2 && !wasRightClickPanning) {\n\t\t\t\t\tconst contextMenuEvent = new PointerEvent('contextmenu', {\n\t\t\t\t\t\tbubbles: true,\n\t\t\t\t\t\tclientX: e.clientX,\n\t\t\t\t\t\tclientY: e.clientY,\n\t\t\t\t\t\tbutton: 2,\n\t\t\t\t\t\tbuttons: 0,\n\t\t\t\t\t\tpointerId: e.pointerId,\n\t\t\t\t\t\tpointerType: e.pointerType,\n\t\t\t\t\t\tisPrimary: e.isPrimary,\n\t\t\t\t\t})\n\t\t\t\t\te.currentTarget.dispatchEvent(contextMenuEvent)\n\t\t\t\t}\n\t\t\t\tisSecondaryClickPointerDown = false\n\t\t\t}\n\n\t\t\tfunction onPointerCancel(e: React.PointerEvent) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\tconst pointerDownButton = pointerDownButtons.get(e.pointerId)\n\t\t\t\tpointerDownButtons.delete(e.pointerId)\n\t\t\t\t// In pen mode a cancelled touch is usually a rejected palm, and the pen's own\n\t\t\t\t// interaction must survive it.\n\t\t\t\tif (editor.getInstanceState().isPenMode && e.pointerType !== 'pen') return\n\n\t\t\t\treleasePointerCapture(e.currentTarget, e)\n\n\t\t\t\t// Nothing to end if the press itself was filtered out (pen mode, unsupported\n\t\t\t\t// button), or if this pointer never started an accepted press.\n\t\t\t\tif (!editor.inputs.getIsPointing() || pointerDownButton === undefined) return\n\n\t\t\t\t// The browser has taken the pointer (edge swipe, incoming call) and will never send\n\t\t\t\t// pointerup, so end the gesture here or the tool stays stuck in its pointing or\n\t\t\t\t// dragging state and the next touch continues it.\n\t\t\t\teditor.interrupt()\n\t\t\t\teditor.dispatch({\n\t\t\t\t\ttype: 'pointer',\n\t\t\t\t\ttarget: 'canvas',\n\t\t\t\t\tname: 'pointer_up',\n\t\t\t\t\t...getPointerInfo(editor, e),\n\t\t\t\t\tbutton: pointerDownButton,\n\t\t\t\t})\n\t\t\t\tisSecondaryClickPointerDown = false\n\t\t\t}\n\n\t\t\tfunction onPointerEnter(e: React.PointerEvent) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\tif (editor.getInstanceState().isPenMode && e.pointerType !== 'pen') return\n\t\t\t\tconst canHover = e.pointerType === 'mouse' || e.pointerType === 'pen'\n\t\t\t\teditor.updateInstanceState({ isHoveringCanvas: canHover ? true : null })\n\t\t\t}\n\n\t\t\tfunction onPointerLeave(e: React.PointerEvent) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\tif (editor.getInstanceState().isPenMode && e.pointerType !== 'pen') return\n\t\t\t\tconst canHover = e.pointerType === 'mouse' || e.pointerType === 'pen'\n\t\t\t\teditor.updateInstanceState({ isHoveringCanvas: canHover ? false : null })\n\t\t\t}\n\n\t\t\tfunction onTouchStart(e: React.TouchEvent) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\teditor.markEventAsHandled(e)\n\t\t\t\tpreventDefault(e)\n\t\t\t}\n\n\t\t\tfunction onTouchEnd(e: React.TouchEvent) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\teditor.markEventAsHandled(e)\n\t\t\t\tif (!(e.target instanceof editor.getContainerWindow().HTMLElement)) return\n\n\t\t\t\tconst editingShapeId = editor.getEditingShapeId()\n\t\t\t\tif (\n\t\t\t\t\t// if the target is not inside the editing shape\n\t\t\t\t\t!(editingShapeId && e.target.closest(`[data-shape-id=\"${editingShapeId}\"]`)) &&\n\t\t\t\t\t// and the target is not an clickable element\n\t\t\t\t\te.target.tagName !== 'A' &&\n\t\t\t\t\t// and the target is not an editable element\n\t\t\t\t\t!elementShouldCaptureKeys(e.target, false)\n\t\t\t\t) {\n\t\t\t\t\tpreventDefault(e)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfunction onDragOver(e: React.DragEvent<Element>) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\tpreventDefault(e)\n\t\t\t}\n\n\t\t\tasync function onDrop(e: React.DragEvent<Element>) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\tpreventDefault(e)\n\t\t\t\te.stopPropagation()\n\n\t\t\t\tconst pagePoint = editor.screenToPage({ x: e.clientX, y: e.clientY })\n\n\t\t\t\t// Call the custom onDropOnCanvas callback if provided\n\t\t\t\tif (editor.options.experimental__onDropOnCanvas) {\n\t\t\t\t\tconst handled = editor.options.experimental__onDropOnCanvas({\n\t\t\t\t\t\tpoint: pagePoint,\n\t\t\t\t\t\tevent: e,\n\t\t\t\t\t})\n\t\t\t\t\tif (handled) return\n\t\t\t\t}\n\n\t\t\t\tif (e.dataTransfer?.files?.length) {\n\t\t\t\t\tconst files = Array.from(e.dataTransfer.files)\n\n\t\t\t\t\teditor.markHistoryStoppingPoint('drop')\n\t\t\t\t\tawait editor.putExternalContent({\n\t\t\t\t\t\ttype: 'files',\n\t\t\t\t\t\tfiles,\n\t\t\t\t\t\tpoint: pagePoint,\n\t\t\t\t\t})\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconst url = e.dataTransfer.getData('url')\n\t\t\t\tif (url) {\n\t\t\t\t\teditor.markHistoryStoppingPoint('drop')\n\t\t\t\t\tawait editor.putExternalContent({\n\t\t\t\t\t\ttype: 'url',\n\t\t\t\t\t\turl,\n\t\t\t\t\t\tpoint: pagePoint,\n\t\t\t\t\t})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfunction onClick(e: React.MouseEvent) {\n\t\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\t\te.stopPropagation()\n\t\t\t}\n\n\t\t\tfunction onContextMenu(e: React.MouseEvent) {\n\t\t\t\t// With right-click panning disabled, let the native contextmenu through so the\n\t\t\t\t// menu opens on press.\n\t\t\t\tif (!editor.options.rightClickPanning) return\n\t\t\t\t// Synthetic events \u2014 our own dispatch from onPointerUp, or tests using\n\t\t\t\t// fireEvent.contextMenu \u2014 pass through so Radix can open the menu.\n\t\t\t\tif (!e.nativeEvent.isTrusted) return\n\t\t\t\t// Only suppress the native browser contextmenu when it follows a\n\t\t\t\t// secondary click. For those, our pointer handling has already\n\t\t\t\t// decided what to do (either we'll dispatch a synthetic contextmenu on\n\t\t\t\t// pointerup to open the menu at the release position, or we panned and\n\t\t\t\t// don't want a menu at all).\n\t\t\t\t//\n\t\t\t\t// Other contextmenu sources must reach Radix so the menu opens:\n\t\t\t\t// - long-press on touch devices (button=0, pointerType=touch)\n\t\t\t\tif (!isSecondaryClickEvent(e)) return\n\t\t\t\tpreventDefault(e)\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tonPointerDown,\n\t\t\t\tonPointerUp,\n\t\t\t\tonPointerCancel,\n\t\t\t\tonPointerEnter,\n\t\t\t\tonPointerLeave,\n\t\t\t\tonDragOver,\n\t\t\t\tonDrop,\n\t\t\t\tonTouchStart,\n\t\t\t\tonTouchEnd,\n\t\t\t\tonClick,\n\t\t\t\tonContextMenu,\n\t\t\t}\n\t\t},\n\t\t[editor]\n\t)\n\n\t// onPointerMove is special: where we're only interested in the other events when they're\n\t// happening _on_ the canvas (as opposed to outside of it, or on UI floating over it), we want\n\t// the pointer position to be up to date regardless of whether it's over the tldraw canvas or\n\t// not. So instead of returning a listener to be attached to the canvas, we directly attach a\n\t// listener to the whole document instead.\n\tuseEffect(() => {\n\t\tlet lastX: number, lastY: number\n\n\t\tfunction onPointerMove(e: PointerEvent) {\n\t\t\tif (editor.wasEventAlreadyHandled(e)) return\n\t\t\teditor.markEventAsHandled(e)\n\n\t\t\tif (e.clientX === lastX && e.clientY === lastY) return\n\t\t\tlastX = e.clientX\n\t\t\tlastY = e.clientY\n\n\t\t\t// For tools that benefit from a higher fidelity of events,\n\t\t\t// we dispatch the coalesced events.\n\t\t\t// N.B. Sometimes getCoalescedEvents isn't present on iOS, ugh.\n\t\t\t// Specifically, in local mode (non-https) mode, iOS does not `useCoalescedEvents`\n\t\t\t// so it appears like the ink is working locally, when really it's just that `useCoalescedEvents`\n\t\t\t// is disabled. The intent here is to have `useCoalescedEvents` disabled for iOS.\n\t\t\tconst events =\n\t\t\t\t!tlenv.isIos && currentTool.useCoalescedEvents && e.getCoalescedEvents\n\t\t\t\t\t? e.getCoalescedEvents()\n\t\t\t\t\t: [e]\n\n\t\t\tfor (const singleEvent of events) {\n\t\t\t\teditor.dispatch({\n\t\t\t\t\ttype: 'pointer',\n\t\t\t\t\ttarget: 'canvas',\n\t\t\t\t\tname: 'pointer_move',\n\t\t\t\t\t...getPointerInfo(editor, singleEvent),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\townerDocument.body.addEventListener('pointermove', onPointerMove)\n\t\treturn () => {\n\t\t\townerDocument.body.removeEventListener('pointermove', onPointerMove)\n\t\t}\n\t}, [editor, currentTool, ownerDocument])\n\n\treturn events\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAyB;AACzB,mBAA0C;AAC1C,yBAAsB;AACtB,iBAKO;AACP,4BAA+B;AAC/B,qBAAiF;AACjF,uBAA0B;AAEnB,SAAS,kBAAkB;AACjC,QAAM,aAAS,4BAAU;AACzB,QAAM,gBAAgB,OAAO,qBAAqB;AAClD,QAAM,kBAAc,6BAAS,gBAAgB,MAAM,OAAO,eAAe,GAAG,CAAC,MAAM,CAAC;AAEpF,QAAM,aAAS;AAAA,IACd,SAAS,eAAe;AACvB,UAAI,8BAA8B;AAGlC,YAAM,qBAAqB,oBAAI,IAAoB;AAEnD,eAAS,cAAc,GAAuB;AAC7C,YAAI,OAAO,uBAAuB,CAAC,EAAG;AACtC,cAAM,aAAS,sCAAsB,CAAC;AACtC,sCAA8B,WAAW;AAIzC,YAAI,WAAW,KAAK,CAAC,OAAO,QAAQ,mBAAmB;AACtD,iBAAO,SAAS;AAAA,YACf,MAAM;AAAA,YACN,QAAQ;AAAA,YACR,MAAM;AAAA,YACN,OAAG,sCAAe,QAAQ,CAAC;AAAA,UAC5B,CAAC;AACD;AAAA,QACD;AAEA,YAAI,WAAW,KAAK,WAAW,KAAK,WAAW,KAAK,WAAW,EAAG;AAIlE,cAAM,kBAAc,mCAAmB,CAAC;AAExC,0CAAkB,EAAE,eAAe,CAAC;AAMpC,cAAM,YAAY,OAAO,iBAAiB,EAAE;AA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AAC/B,uCAAe,CAAC;AAAA,MACjB;AAEA,aAAO;AAAA,QACN;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACD;AAAA,IACD;AAAA,IACA,CAAC,MAAM;AAAA,EACR;AAOA,8BAAU,MAAM;AACf,QAAI,OAAe;AAEnB,aAAS,cAAc,GAAiB;AACvC,UAAI,OAAO,uBAAuB,CAAC,EAAG;AACtC,aAAO,mBAAmB,CAAC;AAE3B,UAAI,EAAE,YAAY,SAAS,EAAE,YAAY,MAAO;AAChD,cAAQ,EAAE;AACV,cAAQ,EAAE;AAQV,YAAMA,UACL,CAAC,yBAAM,SAAS,YAAY,sBAAsB,EAAE,qBACjD,EAAE,mBAAmB,IACrB,CAAC,CAAC;AAEN,iBAAW,eAAeA,SAAQ;AACjC,eAAO,SAAS;AAAA,UACf,MAAM;AAAA,UACN,QAAQ;AAAA,UACR,MAAM;AAAA,UACN,OAAG,sCAAe,QAAQ,WAAW;AAAA,QACtC,CAAC;AAAA,MACF;AAAA,IACD;AAEA,kBAAc,KAAK,iBAAiB,eAAe,aAAa;AAChE,WAAO,MAAM;AACZ,oBAAc,KAAK,oBAAoB,eAAe,aAAa;AAAA,IACpE;AAAA,EACD,GAAG,CAAC,QAAQ,aAAa,aAAa,CAAC;AAEvC,SAAO;AACR;",
6
6
  "names": ["events"]
7
7
  }
@@ -18,15 +18,16 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var useIdentity_exports = {};
20
20
  __export(useIdentity_exports, {
21
+ useDeepObjectIdentity: () => useDeepObjectIdentity,
21
22
  useShallowArrayIdentity: () => useShallowArrayIdentity,
22
23
  useShallowObjectIdentity: () => useShallowObjectIdentity
23
24
  });
24
25
  module.exports = __toCommonJS(useIdentity_exports);
25
26
  var import_utils = require("@tldraw/utils");
26
27
  var import_react = require("react");
27
- function useIdentity(value, isEqual) {
28
+ function useIdentity(value, isEqual2) {
28
29
  const ref = (0, import_react.useRef)(value);
29
- if (isEqual(value, ref.current)) {
30
+ if (isEqual2(value, ref.current)) {
30
31
  return ref.current;
31
32
  }
32
33
  ref.current = value;
@@ -60,4 +61,7 @@ const areNullableObjectsShallowEqual = (a, b) => {
60
61
  function useShallowObjectIdentity(obj) {
61
62
  return useIdentity(obj, areNullableObjectsShallowEqual);
62
63
  }
64
+ function useDeepObjectIdentity(obj) {
65
+ return useIdentity(obj, import_utils.isEqual);
66
+ }
63
67
  //# sourceMappingURL=useIdentity.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/hooks/useIdentity.tsx"],
4
- "sourcesContent": ["import { areArraysShallowEqual, areObjectsShallowEqual } from '@tldraw/utils'\nimport { useRef } from 'react'\n\nfunction useIdentity<T>(value: T, isEqual: (a: T, b: T) => boolean): T {\n\tconst ref = useRef(value)\n\tif (isEqual(value, ref.current)) {\n\t\treturn ref.current\n\t}\n\tref.current = value\n\treturn value\n}\n\nconst areNullableArraysShallowEqual = (\n\ta: readonly any[] | null | undefined,\n\tb: readonly any[] | null | undefined\n) => {\n\ta ??= null\n\tb ??= null\n\tif (a === b) {\n\t\treturn true\n\t}\n\tif (!a || !b) {\n\t\treturn false\n\t}\n\treturn areArraysShallowEqual(a, b)\n}\n\n/** @internal */\nexport function useShallowArrayIdentity<T extends readonly any[] | null | undefined>(arr: T): T {\n\treturn useIdentity(arr, areNullableArraysShallowEqual)\n}\n\nconst areNullableObjectsShallowEqual = (\n\ta: object | null | undefined,\n\tb: object | null | undefined\n) => {\n\ta ??= null\n\tb ??= null\n\tif (a === b) {\n\t\treturn true\n\t}\n\tif (!a || !b) {\n\t\treturn false\n\t}\n\treturn areObjectsShallowEqual(a, b)\n}\n\n/** @internal */\nexport function useShallowObjectIdentity<T extends object | null | undefined>(obj: T): T {\n\treturn useIdentity(obj, areNullableObjectsShallowEqual)\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA8D;AAC9D,mBAAuB;AAEvB,SAAS,YAAe,OAAU,SAAqC;AACtE,QAAM,UAAM,qBAAO,KAAK;AACxB,MAAI,QAAQ,OAAO,IAAI,OAAO,GAAG;AAChC,WAAO,IAAI;AAAA,EACZ;AACA,MAAI,UAAU;AACd,SAAO;AACR;AAEA,MAAM,gCAAgC,CACrC,GACA,MACI;AACJ,QAAM;AACN,QAAM;AACN,MAAI,MAAM,GAAG;AACZ,WAAO;AAAA,EACR;AACA,MAAI,CAAC,KAAK,CAAC,GAAG;AACb,WAAO;AAAA,EACR;AACA,aAAO,oCAAsB,GAAG,CAAC;AAClC;AAGO,SAAS,wBAAqE,KAAW;AAC/F,SAAO,YAAY,KAAK,6BAA6B;AACtD;AAEA,MAAM,iCAAiC,CACtC,GACA,MACI;AACJ,QAAM;AACN,QAAM;AACN,MAAI,MAAM,GAAG;AACZ,WAAO;AAAA,EACR;AACA,MAAI,CAAC,KAAK,CAAC,GAAG;AACb,WAAO;AAAA,EACR;AACA,aAAO,qCAAuB,GAAG,CAAC;AACnC;AAGO,SAAS,yBAA8D,KAAW;AACxF,SAAO,YAAY,KAAK,8BAA8B;AACvD;",
6
- "names": []
4
+ "sourcesContent": ["import { areArraysShallowEqual, areObjectsShallowEqual, isEqual } from '@tldraw/utils'\nimport { useRef } from 'react'\n\nfunction useIdentity<T>(value: T, isEqual: (a: T, b: T) => boolean): T {\n\tconst ref = useRef(value)\n\tif (isEqual(value, ref.current)) {\n\t\treturn ref.current\n\t}\n\tref.current = value\n\treturn value\n}\n\nconst areNullableArraysShallowEqual = (\n\ta: readonly any[] | null | undefined,\n\tb: readonly any[] | null | undefined\n) => {\n\ta ??= null\n\tb ??= null\n\tif (a === b) {\n\t\treturn true\n\t}\n\tif (!a || !b) {\n\t\treturn false\n\t}\n\treturn areArraysShallowEqual(a, b)\n}\n\n/** @internal */\nexport function useShallowArrayIdentity<T extends readonly any[] | null | undefined>(arr: T): T {\n\treturn useIdentity(arr, areNullableArraysShallowEqual)\n}\n\nconst areNullableObjectsShallowEqual = (\n\ta: object | null | undefined,\n\tb: object | null | undefined\n) => {\n\ta ??= null\n\tb ??= null\n\tif (a === b) {\n\t\treturn true\n\t}\n\tif (!a || !b) {\n\t\treturn false\n\t}\n\treturn areObjectsShallowEqual(a, b)\n}\n\n/** @internal */\nexport function useShallowObjectIdentity<T extends object | null | undefined>(obj: T): T {\n\treturn useIdentity(obj, areNullableObjectsShallowEqual)\n}\n\n/**\n * For small option objects that may nest (e.g. camera constraints), where a shallow comparison\n * would still see a fresh identity on every render. Functions and class instances inside still\n * compare by reference, so an inline callback or a fresh `Extension.configure()` counts as a change.\n *\n * @internal\n */\nexport function useDeepObjectIdentity<T extends object | null | undefined>(obj: T): T {\n\treturn useIdentity(obj, isEqual)\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAuE;AACvE,mBAAuB;AAEvB,SAAS,YAAe,OAAUA,UAAqC;AACtE,QAAM,UAAM,qBAAO,KAAK;AACxB,MAAIA,SAAQ,OAAO,IAAI,OAAO,GAAG;AAChC,WAAO,IAAI;AAAA,EACZ;AACA,MAAI,UAAU;AACd,SAAO;AACR;AAEA,MAAM,gCAAgC,CACrC,GACA,MACI;AACJ,QAAM;AACN,QAAM;AACN,MAAI,MAAM,GAAG;AACZ,WAAO;AAAA,EACR;AACA,MAAI,CAAC,KAAK,CAAC,GAAG;AACb,WAAO;AAAA,EACR;AACA,aAAO,oCAAsB,GAAG,CAAC;AAClC;AAGO,SAAS,wBAAqE,KAAW;AAC/F,SAAO,YAAY,KAAK,6BAA6B;AACtD;AAEA,MAAM,iCAAiC,CACtC,GACA,MACI;AACJ,QAAM;AACN,QAAM;AACN,MAAI,MAAM,GAAG;AACZ,WAAO;AAAA,EACR;AACA,MAAI,CAAC,KAAK,CAAC,GAAG;AACb,WAAO;AAAA,EACR;AACA,aAAO,qCAAuB,GAAG,CAAC;AACnC;AAGO,SAAS,yBAA8D,KAAW;AACxF,SAAO,YAAY,KAAK,8BAA8B;AACvD;AASO,SAAS,sBAA2D,KAAW;AACrF,SAAO,YAAY,KAAK,oBAAO;AAChC;",
6
+ "names": ["isEqual"]
7
7
  }
@@ -26,6 +26,7 @@ __export(LicenseManager_exports, {
26
26
  });
27
27
  module.exports = __toCommonJS(LicenseManager_exports);
28
28
  var import_state = require("@tldraw/state");
29
+ var import_utils = require("@tldraw/utils");
29
30
  var import_version = require("../../version");
30
31
  var import_assets = require("../utils/assets");
31
32
  var import_licensing = require("../utils/licensing");
@@ -80,6 +81,7 @@ class LicenseManager {
80
81
  ...NO_FEATURES
81
82
  });
82
83
  verbose = true;
84
+ isDisposed = false;
83
85
  constructor(licenseKey, testPublicKey) {
84
86
  this.isTest = process.env.NODE_ENV === "test";
85
87
  this.isDevelopment = this.getIsDevelopment();
@@ -89,6 +91,7 @@ class LicenseManager {
89
91
  this.featureFlags.set({ ...ALL_FEATURES });
90
92
  }
91
93
  this.getLicenseFromKey(licenseKey).then((result) => {
94
+ if (this.isDisposed) return;
92
95
  const licenseState = getLicenseState(
93
96
  result,
94
97
  (messages) => this.outputMessages(messages),
@@ -100,10 +103,15 @@ class LicenseManager {
100
103
  this.featureFlags.set(getEnabledFeatures(result, licenseState, this.isDevelopment));
101
104
  });
102
105
  }).catch((error) => {
106
+ if (this.isDisposed) return;
103
107
  console.error("License validation failed:", error);
104
108
  this.state.set("unlicensed");
105
109
  });
106
110
  }
111
+ /** Ignore the pending validation: nothing is logged, tracked or set once the manager is replaced. */
112
+ dispose() {
113
+ this.isDisposed = true;
114
+ }
107
115
  /**
108
116
  * Returns whether a given licensable feature is enabled. Reactive: reading this inside a signal
109
117
  * recomputes when license validation resolves.
@@ -158,7 +166,7 @@ class LicenseManager {
158
166
  if (process.env.NODE_ENV) {
159
167
  url.searchParams.set("environment", process.env.NODE_ENV);
160
168
  }
161
- fetch(url.toString());
169
+ fetch(url.toString()).catch(import_utils.noop);
162
170
  }
163
171
  async extractLicenseKey(licenseKey) {
164
172
  const [data, signature] = licenseKey.split(".");