@tldraw/editor 5.5.0-next.f9308d324e1c → 5.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/dist-cjs/index.d.ts +49 -23
  2. package/dist-cjs/index.js +1 -1
  3. package/dist-cjs/index.js.map +2 -2
  4. package/dist-cjs/lib/TldrawEditor.js +16 -12
  5. package/dist-cjs/lib/TldrawEditor.js.map +2 -2
  6. package/dist-cjs/lib/components/MenuClickCapture.js +42 -3
  7. package/dist-cjs/lib/components/MenuClickCapture.js.map +2 -2
  8. package/dist-cjs/lib/components/default-components/DefaultCanvas.js +5 -1
  9. package/dist-cjs/lib/components/default-components/DefaultCanvas.js.map +2 -2
  10. package/dist-cjs/lib/components/default-components/DefaultErrorFallback.js +2 -5
  11. package/dist-cjs/lib/components/default-components/DefaultErrorFallback.js.map +3 -3
  12. package/dist-cjs/lib/components/default-components/DefaultSpinner.js.map +2 -2
  13. package/dist-cjs/lib/editor/Editor.js +168 -181
  14. package/dist-cjs/lib/editor/Editor.js.map +3 -3
  15. package/dist-cjs/lib/editor/derivations/bindingsIndex.js +2 -0
  16. package/dist-cjs/lib/editor/derivations/bindingsIndex.js.map +2 -2
  17. package/dist-cjs/lib/editor/managers/ClickManager/ClickManager.js +3 -2
  18. package/dist-cjs/lib/editor/managers/ClickManager/ClickManager.js.map +2 -2
  19. package/dist-cjs/lib/editor/managers/EditorManager.js +11 -2
  20. package/dist-cjs/lib/editor/managers/EditorManager.js.map +2 -2
  21. package/dist-cjs/lib/editor/managers/PerformanceManager/PerformanceManager.js +49 -63
  22. package/dist-cjs/lib/editor/managers/PerformanceManager/PerformanceManager.js.map +2 -2
  23. package/dist-cjs/lib/editor/managers/ScribbleManager/ScribbleManager.js +1 -1
  24. package/dist-cjs/lib/editor/managers/ScribbleManager/ScribbleManager.js.map +2 -2
  25. package/dist-cjs/lib/editor/managers/SnapManager/BoundsSnaps.js +24 -24
  26. package/dist-cjs/lib/editor/managers/SnapManager/BoundsSnaps.js.map +2 -2
  27. package/dist-cjs/lib/editor/managers/SnapManager/HandleSnaps.js +7 -1
  28. package/dist-cjs/lib/editor/managers/SnapManager/HandleSnaps.js.map +2 -2
  29. package/dist-cjs/lib/editor/managers/SnapManager/SnapManager.js +4 -3
  30. package/dist-cjs/lib/editor/managers/SnapManager/SnapManager.js.map +2 -2
  31. package/dist-cjs/lib/editor/managers/TextManager/TextManager.js +4 -4
  32. package/dist-cjs/lib/editor/managers/TextManager/TextManager.js.map +2 -2
  33. package/dist-cjs/lib/editor/shapes/group/GroupShapeUtil.js +14 -6
  34. package/dist-cjs/lib/editor/shapes/group/GroupShapeUtil.js.map +3 -3
  35. package/dist-cjs/lib/editor/types/external-content.js.map +1 -1
  36. package/dist-cjs/lib/exports/ExportDelay.js +10 -2
  37. package/dist-cjs/lib/exports/ExportDelay.js.map +2 -2
  38. package/dist-cjs/lib/exports/FontEmbedder.js +25 -11
  39. package/dist-cjs/lib/exports/FontEmbedder.js.map +2 -2
  40. package/dist-cjs/lib/exports/StyleEmbedder.js +9 -4
  41. package/dist-cjs/lib/exports/StyleEmbedder.js.map +2 -2
  42. package/dist-cjs/lib/exports/fetchCache.js +3 -0
  43. package/dist-cjs/lib/exports/fetchCache.js.map +2 -2
  44. package/dist-cjs/lib/exports/getSvgAsImage.js +10 -4
  45. package/dist-cjs/lib/exports/getSvgAsImage.js.map +2 -2
  46. package/dist-cjs/lib/exports/getSvgJsx.js +18 -9
  47. package/dist-cjs/lib/exports/getSvgJsx.js.map +2 -2
  48. package/dist-cjs/lib/exports/parseCss.js +1 -1
  49. package/dist-cjs/lib/exports/parseCss.js.map +1 -1
  50. package/dist-cjs/lib/hooks/EditorComponentsContext.js.map +2 -2
  51. package/dist-cjs/lib/hooks/useCanvasEvents.js +24 -0
  52. package/dist-cjs/lib/hooks/useCanvasEvents.js.map +2 -2
  53. package/dist-cjs/lib/hooks/useIdentity.js +6 -2
  54. package/dist-cjs/lib/hooks/useIdentity.js.map +3 -3
  55. package/dist-cjs/lib/license/LicenseManager.js +9 -1
  56. package/dist-cjs/lib/license/LicenseManager.js.map +2 -2
  57. package/dist-cjs/lib/license/LicenseProvider.js +12 -4
  58. package/dist-cjs/lib/license/LicenseProvider.js.map +2 -2
  59. package/dist-cjs/lib/utils/debug-flags.js +0 -6
  60. package/dist-cjs/lib/utils/debug-flags.js.map +2 -2
  61. package/dist-cjs/lib/utils/deepLinks.js +2 -1
  62. package/dist-cjs/lib/utils/deepLinks.js.map +2 -2
  63. package/dist-cjs/lib/utils/sync/LocalIndexedDb.js +32 -25
  64. package/dist-cjs/lib/utils/sync/LocalIndexedDb.js.map +2 -2
  65. package/dist-cjs/lib/utils/sync/TLLocalSyncClient.js +81 -40
  66. package/dist-cjs/lib/utils/sync/TLLocalSyncClient.js.map +2 -2
  67. package/dist-cjs/version.js +3 -3
  68. package/dist-cjs/version.js.map +1 -1
  69. package/dist-esm/index.d.mts +49 -23
  70. package/dist-esm/index.mjs +4 -2
  71. package/dist-esm/index.mjs.map +2 -2
  72. package/dist-esm/lib/TldrawEditor.mjs +17 -13
  73. package/dist-esm/lib/TldrawEditor.mjs.map +2 -2
  74. package/dist-esm/lib/components/MenuClickCapture.mjs +42 -3
  75. package/dist-esm/lib/components/MenuClickCapture.mjs.map +2 -2
  76. package/dist-esm/lib/components/default-components/DefaultCanvas.mjs +5 -1
  77. package/dist-esm/lib/components/default-components/DefaultCanvas.mjs.map +2 -2
  78. package/dist-esm/lib/components/default-components/DefaultErrorFallback.mjs +2 -5
  79. package/dist-esm/lib/components/default-components/DefaultErrorFallback.mjs.map +3 -3
  80. package/dist-esm/lib/components/default-components/DefaultSpinner.mjs.map +2 -2
  81. package/dist-esm/lib/editor/Editor.mjs +168 -181
  82. package/dist-esm/lib/editor/Editor.mjs.map +3 -3
  83. package/dist-esm/lib/editor/derivations/bindingsIndex.mjs +2 -0
  84. package/dist-esm/lib/editor/derivations/bindingsIndex.mjs.map +2 -2
  85. package/dist-esm/lib/editor/managers/ClickManager/ClickManager.mjs +3 -2
  86. package/dist-esm/lib/editor/managers/ClickManager/ClickManager.mjs.map +2 -2
  87. package/dist-esm/lib/editor/managers/EditorManager.mjs +11 -2
  88. package/dist-esm/lib/editor/managers/EditorManager.mjs.map +2 -2
  89. package/dist-esm/lib/editor/managers/PerformanceManager/PerformanceManager.mjs +49 -63
  90. package/dist-esm/lib/editor/managers/PerformanceManager/PerformanceManager.mjs.map +2 -2
  91. package/dist-esm/lib/editor/managers/ScribbleManager/ScribbleManager.mjs +1 -1
  92. package/dist-esm/lib/editor/managers/ScribbleManager/ScribbleManager.mjs.map +2 -2
  93. package/dist-esm/lib/editor/managers/SnapManager/BoundsSnaps.mjs +24 -24
  94. package/dist-esm/lib/editor/managers/SnapManager/BoundsSnaps.mjs.map +2 -2
  95. package/dist-esm/lib/editor/managers/SnapManager/HandleSnaps.mjs +7 -1
  96. package/dist-esm/lib/editor/managers/SnapManager/HandleSnaps.mjs.map +2 -2
  97. package/dist-esm/lib/editor/managers/SnapManager/SnapManager.mjs +4 -3
  98. package/dist-esm/lib/editor/managers/SnapManager/SnapManager.mjs.map +2 -2
  99. package/dist-esm/lib/editor/managers/TextManager/TextManager.mjs +4 -4
  100. package/dist-esm/lib/editor/managers/TextManager/TextManager.mjs.map +2 -2
  101. package/dist-esm/lib/editor/shapes/group/GroupShapeUtil.mjs +14 -6
  102. package/dist-esm/lib/editor/shapes/group/GroupShapeUtil.mjs.map +3 -3
  103. package/dist-esm/lib/exports/ExportDelay.mjs +11 -3
  104. package/dist-esm/lib/exports/ExportDelay.mjs.map +2 -2
  105. package/dist-esm/lib/exports/FontEmbedder.mjs +25 -11
  106. package/dist-esm/lib/exports/FontEmbedder.mjs.map +2 -2
  107. package/dist-esm/lib/exports/StyleEmbedder.mjs +9 -4
  108. package/dist-esm/lib/exports/StyleEmbedder.mjs.map +2 -2
  109. package/dist-esm/lib/exports/fetchCache.mjs +3 -0
  110. package/dist-esm/lib/exports/fetchCache.mjs.map +2 -2
  111. package/dist-esm/lib/exports/getSvgAsImage.mjs +10 -4
  112. package/dist-esm/lib/exports/getSvgAsImage.mjs.map +2 -2
  113. package/dist-esm/lib/exports/getSvgJsx.mjs +18 -9
  114. package/dist-esm/lib/exports/getSvgJsx.mjs.map +2 -2
  115. package/dist-esm/lib/exports/parseCss.mjs +1 -1
  116. package/dist-esm/lib/exports/parseCss.mjs.map +1 -1
  117. package/dist-esm/lib/hooks/EditorComponentsContext.mjs.map +2 -2
  118. package/dist-esm/lib/hooks/useCanvasEvents.mjs +24 -0
  119. package/dist-esm/lib/hooks/useCanvasEvents.mjs.map +2 -2
  120. package/dist-esm/lib/hooks/useIdentity.mjs +7 -3
  121. package/dist-esm/lib/hooks/useIdentity.mjs.map +3 -3
  122. package/dist-esm/lib/license/LicenseManager.mjs +9 -1
  123. package/dist-esm/lib/license/LicenseManager.mjs.map +2 -2
  124. package/dist-esm/lib/license/LicenseProvider.mjs +13 -5
  125. package/dist-esm/lib/license/LicenseProvider.mjs.map +2 -2
  126. package/dist-esm/lib/utils/debug-flags.mjs +0 -6
  127. package/dist-esm/lib/utils/debug-flags.mjs.map +2 -2
  128. package/dist-esm/lib/utils/deepLinks.mjs +2 -1
  129. package/dist-esm/lib/utils/deepLinks.mjs.map +2 -2
  130. package/dist-esm/lib/utils/sync/LocalIndexedDb.mjs +32 -25
  131. package/dist-esm/lib/utils/sync/LocalIndexedDb.mjs.map +2 -2
  132. package/dist-esm/lib/utils/sync/TLLocalSyncClient.mjs +81 -40
  133. package/dist-esm/lib/utils/sync/TLLocalSyncClient.mjs.map +2 -2
  134. package/dist-esm/version.mjs +3 -3
  135. package/dist-esm/version.mjs.map +1 -1
  136. package/editor.css +9 -1
  137. package/package.json +8 -11
  138. package/src/index.ts +5 -1
  139. package/src/lib/TldrawEditor.tsx +35 -21
  140. package/src/lib/components/MenuClickCapture.tsx +55 -4
  141. package/src/lib/components/default-components/DefaultCanvas.tsx +7 -1
  142. package/src/lib/components/default-components/DefaultErrorFallback.tsx +13 -5
  143. package/src/lib/components/default-components/DefaultSpinner.tsx +4 -1
  144. package/src/lib/editor/Editor.test.ts +65 -0
  145. package/src/lib/editor/Editor.ts +261 -294
  146. package/src/lib/editor/derivations/bindingsIndex.ts +3 -0
  147. package/src/lib/editor/managers/ClickManager/ClickManager.test.ts +1 -0
  148. package/src/lib/editor/managers/ClickManager/ClickManager.ts +3 -2
  149. package/src/lib/editor/managers/EditorManager.test.ts +32 -1
  150. package/src/lib/editor/managers/EditorManager.ts +15 -3
  151. package/src/lib/editor/managers/PerformanceManager/PerformanceManager.test.ts +80 -0
  152. package/src/lib/editor/managers/PerformanceManager/PerformanceManager.ts +54 -81
  153. package/src/lib/editor/managers/ScribbleManager/ScribbleManager.ts +1 -1
  154. package/src/lib/editor/managers/SnapManager/BoundsSnaps.ts +32 -36
  155. package/src/lib/editor/managers/SnapManager/HandleSnaps.ts +13 -2
  156. package/src/lib/editor/managers/SnapManager/SnapManager.test.ts +13 -0
  157. package/src/lib/editor/managers/SnapManager/SnapManager.ts +6 -4
  158. package/src/lib/editor/managers/TextManager/TextManager.test.ts +74 -0
  159. package/src/lib/editor/managers/TextManager/TextManager.ts +6 -5
  160. package/src/lib/editor/shapes/group/GroupShapeUtil.tsx +23 -8
  161. package/src/lib/editor/types/external-content.ts +5 -0
  162. package/src/lib/exports/ExportDelay.tsx +16 -4
  163. package/src/lib/exports/FontEmbedder.test.ts +99 -0
  164. package/src/lib/exports/FontEmbedder.ts +32 -11
  165. package/src/lib/exports/StyleEmbedder.ts +13 -4
  166. package/src/lib/exports/fetchCache.test.ts +22 -0
  167. package/src/lib/exports/fetchCache.ts +4 -0
  168. package/src/lib/exports/getSvgAsImage.ts +13 -5
  169. package/src/lib/exports/getSvgJsx.test.ts +43 -1
  170. package/src/lib/exports/getSvgJsx.tsx +28 -16
  171. package/src/lib/exports/parseCss.test.ts +4 -0
  172. package/src/lib/exports/parseCss.ts +2 -2
  173. package/src/lib/hooks/EditorComponentsContext.tsx +2 -1
  174. package/src/lib/hooks/useCanvasEvents.ts +42 -0
  175. package/src/lib/hooks/useIdentity.tsx +12 -1
  176. package/src/lib/license/LicenseManager.ts +13 -1
  177. package/src/lib/license/LicenseProvider.test.tsx +76 -0
  178. package/src/lib/license/LicenseProvider.tsx +19 -5
  179. package/src/lib/test/preserveFocus.test.tsx +81 -0
  180. package/src/lib/utils/debug-flags.ts +0 -6
  181. package/src/lib/utils/deepLinks.test.ts +15 -0
  182. package/src/lib/utils/deepLinks.ts +8 -3
  183. package/src/lib/utils/sync/LocalIndexedDb.test.ts +121 -1
  184. package/src/lib/utils/sync/LocalIndexedDb.ts +41 -28
  185. package/src/lib/utils/sync/TLLocalSyncClient.test.ts +257 -1
  186. package/src/lib/utils/sync/TLLocalSyncClient.ts +112 -54
  187. package/src/version.ts +3 -3
  188. package/dist-cjs/lib/primitives/geometry/geometry.bench.js +0 -133
  189. package/dist-cjs/lib/primitives/geometry/geometry.bench.js.map +0 -7
  190. package/dist-esm/lib/primitives/geometry/geometry.bench.mjs +0 -132
  191. package/dist-esm/lib/primitives/geometry/geometry.bench.mjs.map +0 -7
  192. package/src/lib/primitives/geometry/geometry.bench.ts +0 -179
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/exports/StyleEmbedder.ts"],
4
- "sourcesContent": ["import { assertExists, getOwnProperty, objectMapValues, uniqueId } from '@tldraw/utils'\nimport { ReadonlyStyles, Styles, cssRules } from './cssRules'\nimport {\n\telementStyle,\n\tgetComputedStyle,\n\tgetRenderedChildNodes,\n\tgetRenderedChildren,\n\tisElement,\n} from './domUtils'\nimport { resourceToDataUrl } from './fetchCache'\nimport { FontEmbedder } from './FontEmbedder'\nimport { parseCssValueUrls, shouldIncludeCssProperty } from './parseCss'\n\nconst NO_STYLES = {} as const\n\ninterface ElementStyleInfo {\n\tself: Styles\n\tbefore: Styles | undefined\n\tafter: Styles | undefined\n}\n\nexport class StyleEmbedder {\n\tconstructor(private readonly root: Element) {}\n\tprivate readonly styles = new Map<Element, ElementStyleInfo>()\n\treadonly fonts = new FontEmbedder()\n\n\treadRootElementStyles(rootElement: Element) {\n\t\t// when reading a root, we always apply _all_ the styles, even if they match the defaults\n\t\tthis.readElementStyles(rootElement, {\n\t\t\tshouldRespectDefaults: false,\n\t\t\tshouldSkipInheritedParentStyles: false,\n\t\t})\n\n\t\tconst children = Array.from(getRenderedChildren(rootElement))\n\t\twhile (children.length) {\n\t\t\tconst child = children.pop()!\n\t\t\tchildren.push(...getRenderedChildren(child))\n\n\t\t\t// when reading children, we don't apply styles that match the defaults for that\n\t\t\t// element, or that would be inherited from the parent\n\t\t\tthis.readElementStyles(child, {\n\t\t\t\tshouldRespectDefaults: true,\n\t\t\t\tshouldSkipInheritedParentStyles: true,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate readElementStyles(\n\t\telement: Element,\n\t\t{ shouldRespectDefaults = true, shouldSkipInheritedParentStyles = true }\n\t) {\n\t\tconst defaultStyles = shouldRespectDefaults\n\t\t\t? getDefaultStylesForTagName(element.ownerDocument, element.tagName.toLowerCase())\n\t\t\t: NO_STYLES\n\n\t\tconst parentStyles = Object.assign({}, NO_STYLES) as Styles\n\t\tif (shouldSkipInheritedParentStyles) {\n\t\t\tlet el = element.parentElement\n\t\t\t// Keep going up the tree to find all the relevant styles\n\t\t\twhile (el) {\n\t\t\t\tconst currentStyles = this.styles.get(el)?.self\n\t\t\t\tfor (const style in currentStyles) {\n\t\t\t\t\tif (!parentStyles[style]) {\n\t\t\t\t\t\tparentStyles[style] = currentStyles[style]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tel = el.parentElement\n\t\t\t}\n\t\t}\n\n\t\tconst info: ElementStyleInfo = {\n\t\t\tself: styleFromElement(element, { defaultStyles, parentStyles }),\n\t\t\tbefore: styleFromPseudoElement(element, '::before'),\n\t\t\tafter: styleFromPseudoElement(element, '::after'),\n\t\t}\n\t\tthis.styles.set(element, info)\n\t}\n\n\tfetchResources() {\n\t\tconst promises: Promise<void>[] = []\n\n\t\tfor (const info of this.styles.values()) {\n\t\t\tfor (const styles of objectMapValues(info)) {\n\t\t\t\tif (!styles) continue\n\t\t\t\tfor (const [property, value] of Object.entries(styles)) {\n\t\t\t\t\tif (!value) continue\n\t\t\t\t\tif (property === 'font-family') {\n\t\t\t\t\t\tthis.fonts.onFontFamilyValue(value)\n\t\t\t\t\t}\n\n\t\t\t\t\tconst urlMatches = parseCssValueUrls(value)\n\t\t\t\t\tif (urlMatches.length === 0) continue\n\n\t\t\t\t\tpromises.push(\n\t\t\t\t\t\t...urlMatches.map(async ({ url, original }) => {\n\t\t\t\t\t\t\tconst dataUrl = (await resourceToDataUrl(url)) ?? 'data:'\n\t\t\t\t\t\t\tstyles[property] = value.replace(original, `url(\"${dataUrl}\")`)\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn Promise.all(promises)\n\t}\n\n\t// custom elements are tricky. if we serialize the dom as-is, the custom elements wont have\n\t// their shadow-dom contents serialized. after we've read all the styles, we need to unwrap the\n\t// contents of each custom elements shadow dom directly into the parent element itself.\n\tunwrapCustomElements() {\n\t\tconst visited = new Set<Node>()\n\n\t\tconst visit = (element: Element, clonedParent: Element | null) => {\n\t\t\tif (visited.has(element)) return\n\t\t\tvisited.add(element)\n\n\t\t\tconst shadowRoot = element.shadowRoot\n\n\t\t\tif (shadowRoot) {\n\t\t\t\tconst clonedCustomEl = element.ownerDocument.createElement('div')\n\t\t\t\tthis.styles.set(clonedCustomEl, this.styles.get(element)!)\n\n\t\t\t\tclonedCustomEl.setAttribute('data-tl-custom-element', element.tagName)\n\t\t\t\t;(clonedParent ?? element.parentElement!).appendChild(clonedCustomEl)\n\n\t\t\t\tfor (const child of shadowRoot.childNodes) {\n\t\t\t\t\tif (isElement(child)) {\n\t\t\t\t\t\tvisit(child, clonedCustomEl)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclonedCustomEl.appendChild(child.cloneNode(true))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\telement.remove()\n\t\t\t} else if (clonedParent) {\n\t\t\t\tif (element.tagName.toLowerCase() === 'style') {\n\t\t\t\t\t// we don't clone style tags at that would break the style scoping. instead we\n\t\t\t\t\t// rely on the computed styles we've already read\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconst clonedEl = element.cloneNode(false) as Element\n\t\t\t\tthis.styles.set(clonedEl, this.styles.get(element)!)\n\n\t\t\t\tclonedParent.appendChild(clonedEl)\n\n\t\t\t\tfor (const child of getRenderedChildNodes(element)) {\n\t\t\t\t\tif (isElement(child)) {\n\t\t\t\t\t\tvisit(child, clonedEl)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclonedEl.appendChild(child.cloneNode(true))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const element of this.styles.keys()) {\n\t\t\tvisit(element, null)\n\t\t}\n\t}\n\n\tembedStyles(): string {\n\t\tlet css = ''\n\n\t\tfor (const [element, info] of this.styles) {\n\t\t\tif (info.after || info.before) {\n\t\t\t\tconst className = `pseudo-${uniqueId()}`\n\t\t\t\telement.classList.add(className)\n\n\t\t\t\tif (info.before) {\n\t\t\t\t\tcss += `.${className}::before {${formatCss(info.before)}}\\n`\n\t\t\t\t}\n\t\t\t\tif (info.after) {\n\t\t\t\t\tcss += `.${className}::after {${formatCss(info.after)}}\\n`\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst style = elementStyle(element)\n\t\t\tfor (const [property, value] of Object.entries(info.self)) {\n\t\t\t\tif (!value) continue\n\t\t\t\tstyle.setProperty(property, value)\n\t\t\t}\n\n\t\t\t// in HTML, font-kerning: auto is equivalent to font-kerning: normal. But in SVG, it's\n\t\t\t// none. We set it to normal here to match the HTML behavior, as otherwise this can\n\t\t\t// cause rendering differences.\n\t\t\tif (style.fontKerning === 'auto') {\n\t\t\t\tstyle.fontKerning = 'normal'\n\t\t\t}\n\t\t}\n\n\t\treturn css\n\t}\n\n\tasync getFontFaceCss() {\n\t\treturn await this.fonts.createCss()\n\t}\n\n\tdispose() {\n\t\tdestroyDefaultStyleFrame()\n\t}\n}\n\ninterface ReadStyleOpts {\n\tdefaultStyles: ReadonlyStyles\n\tparentStyles: ReadonlyStyles\n}\n\nfunction styleFromElement(element: Element, { defaultStyles, parentStyles }: ReadStyleOpts) {\n\t// `computedStyleMap` produces a more accurate representation of the styles, but it's not\n\t// supported in firefox at the time of writing. So we fall back to `getComputedStyle` if it's\n\t// not available.\n\tif (element.computedStyleMap) {\n\t\treturn styleFromComputedStyleMap(element.computedStyleMap(), { defaultStyles, parentStyles })\n\t}\n\treturn styleFromComputedStyle(getComputedStyle(element), { defaultStyles, parentStyles })\n}\n\nfunction styleFromPseudoElement(element: Element, pseudo: string) {\n\t// the equivalent of `computedStyleMap` for pseudo-elements isn't even fully specced out yet, so\n\t// for those we have to use `getComputedStyle` in all browsers.\n\tconst style = getComputedStyle(element, pseudo)\n\n\tconst content = style.getPropertyValue('content')\n\tif (content === '' || content === 'none') {\n\t\treturn undefined\n\t}\n\n\treturn styleFromComputedStyle(style, { defaultStyles: NO_STYLES, parentStyles: NO_STYLES })\n}\n\nfunction styleFromComputedStyleMap(\n\tstyle: StylePropertyMapReadOnly,\n\t{ defaultStyles, parentStyles }: ReadStyleOpts\n) {\n\tconst styles: Record<string, string> = {}\n\tconst currentColor = style.get('color')?.toString() || ''\n\tconst ruleOptions = {\n\t\tcurrentColor,\n\t\tparentStyles,\n\t\tdefaultStyles,\n\t\tgetStyle: (property: string) => style.get(property)?.toString() ?? '',\n\t}\n\tfor (const property of style.keys()) {\n\t\tif (!shouldIncludeCssProperty(property)) continue\n\n\t\tconst value = style.get(property)!.toString()\n\n\t\tif (defaultStyles[property] === value) continue\n\n\t\tconst rule = getOwnProperty(cssRules, property)\n\t\tif (rule && rule(value, property, ruleOptions)) continue\n\n\t\tstyles[property] = value\n\t}\n\n\treturn styles\n}\n\nfunction styleFromComputedStyle(\n\tstyle: CSSStyleDeclaration,\n\t{ defaultStyles, parentStyles }: ReadStyleOpts\n) {\n\tconst styles: Record<string, string> = {}\n\tconst currentColor = style.color\n\tconst ruleOptions = {\n\t\tcurrentColor,\n\t\tparentStyles,\n\t\tdefaultStyles,\n\t\tgetStyle: (property: string) => style.getPropertyValue(property),\n\t}\n\n\tfor (const property in style) {\n\t\tif (!shouldIncludeCssProperty(property)) continue\n\n\t\tconst value = style.getPropertyValue(property)\n\n\t\tif (defaultStyles[property] === value) continue\n\n\t\tconst rule = getOwnProperty(cssRules, property)\n\t\tif (rule && rule(value, property, ruleOptions)) continue\n\n\t\tstyles[property] = value\n\t}\n\treturn styles\n}\n\nfunction formatCss(style: ReadonlyStyles) {\n\tlet cssText = ''\n\tfor (const [property, value] of Object.entries(style)) {\n\t\tcssText += `${property}: ${value};`\n\t}\n\treturn cssText\n}\n\n// when we're figuring out the default values for a tag, we need read them from a separate document\n// so they're not affected by the current document's styles\nlet defaultStyleFrame:\n\t| {\n\t\t\tiframe: HTMLIFrameElement\n\t\t\tforeignObject: SVGForeignObjectElement\n\t\t\tdocument: Document\n\t\t\townerDocument: Document\n\t }\n\t| undefined\nconst defaultStylesByTagName: Record<string, ReadonlyStyles> = {}\nfunction getDefaultStyleFrame(ownerDoc: Document) {\n\tif (!defaultStyleFrame || defaultStyleFrame.ownerDocument !== ownerDoc) {\n\t\tdestroyDefaultStyleFrame()\n\t\tconst frame = ownerDoc.createElement('iframe')\n\t\tframe.style.display = 'none'\n\t\townerDoc.body.appendChild(frame)\n\t\tconst frameDocument = assertExists(frame.contentDocument, 'frame must have a document')\n\t\tconst svg = frameDocument.createElementNS('http://www.w3.org/2000/svg', 'svg')\n\t\tconst foreignObject = frameDocument.createElementNS(\n\t\t\t'http://www.w3.org/2000/svg',\n\t\t\t'foreignObject'\n\t\t)\n\t\tsvg.appendChild(foreignObject)\n\t\tframeDocument.body.appendChild(svg)\n\t\tdefaultStyleFrame = {\n\t\t\tiframe: frame,\n\t\t\tforeignObject,\n\t\t\tdocument: frameDocument,\n\t\t\townerDocument: ownerDoc,\n\t\t}\n\t}\n\treturn defaultStyleFrame\n}\n\nfunction destroyDefaultStyleFrame() {\n\tif (defaultStyleFrame) {\n\t\tdefaultStyleFrame.iframe.remove()\n\t\tdefaultStyleFrame = undefined\n\t}\n\tfor (const tagName in defaultStylesByTagName) {\n\t\tdelete defaultStylesByTagName[tagName]\n\t}\n}\n\nconst defaultStyleReadOptions: ReadStyleOpts = { defaultStyles: NO_STYLES, parentStyles: NO_STYLES }\nfunction getDefaultStylesForTagName(ownerDoc: Document, tagName: string) {\n\tlet existing = defaultStylesByTagName[tagName]\n\tif (!existing) {\n\t\tconst { foreignObject, document } = getDefaultStyleFrame(ownerDoc)\n\t\tconst element = document.createElement(tagName)\n\t\tforeignObject.appendChild(element)\n\t\texisting = element.computedStyleMap\n\t\t\t? styleFromComputedStyleMap(element.computedStyleMap(), defaultStyleReadOptions)\n\t\t\t: styleFromComputedStyle(getComputedStyle(element), defaultStyleReadOptions)\n\t\tforeignObject.removeChild(element)\n\t\tdefaultStylesByTagName[tagName] = existing\n\t}\n\treturn existing\n}\n"],
5
- "mappings": "AAAA,SAAS,cAAc,gBAAgB,iBAAiB,gBAAgB;AACxE,SAAiC,gBAAgB;AACjD;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AACP,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAC7B,SAAS,mBAAmB,gCAAgC;AAE5D,MAAM,YAAY,CAAC;AAQZ,MAAM,cAAc;AAAA,EAC1B,YAA6B,MAAe;AAAf;AAAA,EAAgB;AAAA,EAAhB;AAAA,EACZ,SAAS,oBAAI,IAA+B;AAAA,EACpD,QAAQ,IAAI,aAAa;AAAA,EAElC,sBAAsB,aAAsB;AAE3C,SAAK,kBAAkB,aAAa;AAAA,MACnC,uBAAuB;AAAA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SAAS,IAAI,qBAAqB,QAAQ;AACjE,UAAM,UAAU,SAAS,cAAc,OAAO;AAC9C,kBAAc,YAAY,OAAO;AACjC,eAAW,QAAQ,mBAChB,0BAA0B,QAAQ,iBAAiB,GAAG,uBAAuB,IAC7E,uBAAuB,iBAAiB,OAAO,GAAG,uBAAuB;AAC5E,kBAAc,YAAY,OAAO;AACjC,2BAAuB,OAAO,IAAI;AAAA,EACnC;AACA,SAAO;AACR;",
4
+ "sourcesContent": ["import { assertExists, getOwnProperty, objectMapValues, uniqueId } from '@tldraw/utils'\nimport { ReadonlyStyles, Styles, cssRules } from './cssRules'\nimport {\n\telementStyle,\n\tgetComputedStyle,\n\tgetRenderedChildNodes,\n\tgetRenderedChildren,\n\tisElement,\n} from './domUtils'\nimport { resourceToDataUrl } from './fetchCache'\nimport { FontEmbedder } from './FontEmbedder'\nimport { parseCssValueUrls, shouldIncludeCssProperty } from './parseCss'\n\nconst NO_STYLES = {} as const\n\ninterface ElementStyleInfo {\n\tself: Styles\n\tbefore: Styles | undefined\n\tafter: Styles | undefined\n}\n\nexport class StyleEmbedder {\n\tconstructor(private readonly root: Element) {}\n\tprivate readonly styles = new Map<Element, ElementStyleInfo>()\n\treadonly fonts = new FontEmbedder()\n\n\treadRootElementStyles(rootElement: Element) {\n\t\t// when reading a root, we always apply _all_ the styles, even if they match the defaults\n\t\tthis.readElementStyles(rootElement, {\n\t\t\tshouldRespectDefaults: false,\n\t\t\tshouldSkipInheritedParentStyles: false,\n\t\t})\n\n\t\tconst children = Array.from(getRenderedChildren(rootElement))\n\t\twhile (children.length) {\n\t\t\tconst child = children.pop()!\n\t\t\tchildren.push(...getRenderedChildren(child))\n\n\t\t\t// when reading children, we don't apply styles that match the defaults for that\n\t\t\t// element, or that would be inherited from the parent\n\t\t\tthis.readElementStyles(child, {\n\t\t\t\tshouldRespectDefaults: true,\n\t\t\t\tshouldSkipInheritedParentStyles: true,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate readElementStyles(\n\t\telement: Element,\n\t\t{ shouldRespectDefaults = true, shouldSkipInheritedParentStyles = true }\n\t) {\n\t\tconst defaultStyles = shouldRespectDefaults\n\t\t\t? getDefaultStylesForTagName(element.ownerDocument, element.tagName.toLowerCase())\n\t\t\t: NO_STYLES\n\n\t\tconst parentStyles = Object.assign({}, NO_STYLES) as Styles\n\t\tif (shouldSkipInheritedParentStyles) {\n\t\t\tlet el = element.parentElement\n\t\t\t// Keep going up the tree to find all the relevant styles\n\t\t\twhile (el) {\n\t\t\t\tconst currentStyles = this.styles.get(el)?.self\n\t\t\t\tfor (const style in currentStyles) {\n\t\t\t\t\tif (!parentStyles[style]) {\n\t\t\t\t\t\tparentStyles[style] = currentStyles[style]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tel = el.parentElement\n\t\t\t}\n\t\t}\n\n\t\tconst info: ElementStyleInfo = {\n\t\t\tself: styleFromElement(element, { defaultStyles, parentStyles }),\n\t\t\tbefore: styleFromPseudoElement(element, '::before'),\n\t\t\tafter: styleFromPseudoElement(element, '::after'),\n\t\t}\n\t\tthis.styles.set(element, info)\n\t}\n\n\tfetchResources() {\n\t\tconst promises: Promise<void>[] = []\n\n\t\tfor (const info of this.styles.values()) {\n\t\t\tfor (const styles of objectMapValues(info)) {\n\t\t\t\tif (!styles) continue\n\t\t\t\tfor (const [property, value] of Object.entries(styles)) {\n\t\t\t\t\tif (!value) continue\n\t\t\t\t\tif (property === 'font-family') {\n\t\t\t\t\t\tthis.fonts.onFontFamilyValue(value)\n\t\t\t\t\t}\n\n\t\t\t\t\tconst urlMatches = parseCssValueUrls(value)\n\t\t\t\t\tif (urlMatches.length === 0) continue\n\n\t\t\t\t\tpromises.push(\n\t\t\t\t\t\t(async () => {\n\t\t\t\t\t\t\t// resolve every url first, then rewrite the value in one pass - replacing\n\t\t\t\t\t\t\t// per-url from the original value would keep only whichever resolved last.\n\t\t\t\t\t\t\t// The replacer callback keeps `$` in a data url's mime segment literal.\n\t\t\t\t\t\t\tconst dataUrls = await Promise.all(\n\t\t\t\t\t\t\t\turlMatches.map(({ url }) => resourceToDataUrl(url))\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tstyles[property] = urlMatches.reduce(\n\t\t\t\t\t\t\t\t(result, { original }, i) =>\n\t\t\t\t\t\t\t\t\tresult.replace(original, () => `url(\"${dataUrls[i] ?? 'data:'}\")`),\n\t\t\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t})()\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn Promise.all(promises)\n\t}\n\n\t// custom elements are tricky. if we serialize the dom as-is, the custom elements wont have\n\t// their shadow-dom contents serialized. after we've read all the styles, we need to unwrap the\n\t// contents of each custom elements shadow dom directly into the parent element itself.\n\tunwrapCustomElements() {\n\t\tconst visited = new Set<Node>()\n\n\t\tconst visit = (element: Element, clonedParent: Element | null) => {\n\t\t\tif (visited.has(element)) return\n\t\t\tvisited.add(element)\n\n\t\t\tconst shadowRoot = element.shadowRoot\n\n\t\t\tif (shadowRoot) {\n\t\t\t\tconst clonedCustomEl = element.ownerDocument.createElement('div')\n\t\t\t\tthis.styles.set(clonedCustomEl, this.styles.get(element)!)\n\n\t\t\t\tclonedCustomEl.setAttribute('data-tl-custom-element', element.tagName)\n\t\t\t\t;(clonedParent ?? element.parentElement!).appendChild(clonedCustomEl)\n\n\t\t\t\tfor (const child of shadowRoot.childNodes) {\n\t\t\t\t\tif (isElement(child)) {\n\t\t\t\t\t\tvisit(child, clonedCustomEl)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclonedCustomEl.appendChild(child.cloneNode(true))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\telement.remove()\n\t\t\t} else if (clonedParent) {\n\t\t\t\tif (element.tagName.toLowerCase() === 'style') {\n\t\t\t\t\t// we don't clone style tags at that would break the style scoping. instead we\n\t\t\t\t\t// rely on the computed styles we've already read\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconst clonedEl = element.cloneNode(false) as Element\n\t\t\t\tthis.styles.set(clonedEl, this.styles.get(element)!)\n\n\t\t\t\tclonedParent.appendChild(clonedEl)\n\n\t\t\t\tfor (const child of getRenderedChildNodes(element)) {\n\t\t\t\t\tif (isElement(child)) {\n\t\t\t\t\t\tvisit(child, clonedEl)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclonedEl.appendChild(child.cloneNode(true))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const element of this.styles.keys()) {\n\t\t\tvisit(element, null)\n\t\t}\n\t}\n\n\tembedStyles(): string {\n\t\tlet css = ''\n\n\t\tfor (const [element, info] of this.styles) {\n\t\t\tif (info.after || info.before) {\n\t\t\t\tconst className = `pseudo-${uniqueId()}`\n\t\t\t\telement.classList.add(className)\n\n\t\t\t\tif (info.before) {\n\t\t\t\t\tcss += `.${className}::before {${formatCss(info.before)}}\\n`\n\t\t\t\t}\n\t\t\t\tif (info.after) {\n\t\t\t\t\tcss += `.${className}::after {${formatCss(info.after)}}\\n`\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst style = elementStyle(element)\n\t\t\tfor (const [property, value] of Object.entries(info.self)) {\n\t\t\t\tif (!value) continue\n\t\t\t\tstyle.setProperty(property, value)\n\t\t\t}\n\n\t\t\t// in HTML, font-kerning: auto is equivalent to font-kerning: normal. But in SVG, it's\n\t\t\t// none. We set it to normal here to match the HTML behavior, as otherwise this can\n\t\t\t// cause rendering differences.\n\t\t\tif (style.fontKerning === 'auto') {\n\t\t\t\tstyle.fontKerning = 'normal'\n\t\t\t}\n\t\t}\n\n\t\treturn css\n\t}\n\n\tasync getFontFaceCss() {\n\t\treturn await this.fonts.createCss()\n\t}\n\n\tdispose() {\n\t\tdestroyDefaultStyleFrame()\n\t}\n}\n\ninterface ReadStyleOpts {\n\tdefaultStyles: ReadonlyStyles\n\tparentStyles: ReadonlyStyles\n}\n\nfunction styleFromElement(element: Element, { defaultStyles, parentStyles }: ReadStyleOpts) {\n\t// `computedStyleMap` produces a more accurate representation of the styles, but it's not\n\t// supported in firefox at the time of writing. So we fall back to `getComputedStyle` if it's\n\t// not available.\n\tif (element.computedStyleMap) {\n\t\treturn styleFromComputedStyleMap(element.computedStyleMap(), { defaultStyles, parentStyles })\n\t}\n\treturn styleFromComputedStyle(getComputedStyle(element), { defaultStyles, parentStyles })\n}\n\nfunction styleFromPseudoElement(element: Element, pseudo: string) {\n\t// the equivalent of `computedStyleMap` for pseudo-elements isn't even fully specced out yet, so\n\t// for those we have to use `getComputedStyle` in all browsers.\n\tconst style = getComputedStyle(element, pseudo)\n\n\tconst content = style.getPropertyValue('content')\n\tif (content === '' || content === 'none') {\n\t\treturn undefined\n\t}\n\n\treturn styleFromComputedStyle(style, { defaultStyles: NO_STYLES, parentStyles: NO_STYLES })\n}\n\nfunction styleFromComputedStyleMap(\n\tstyle: StylePropertyMapReadOnly,\n\t{ defaultStyles, parentStyles }: ReadStyleOpts\n) {\n\tconst styles: Record<string, string> = {}\n\tconst currentColor = style.get('color')?.toString() || ''\n\tconst ruleOptions = {\n\t\tcurrentColor,\n\t\tparentStyles,\n\t\tdefaultStyles,\n\t\tgetStyle: (property: string) => style.get(property)?.toString() ?? '',\n\t}\n\tfor (const property of style.keys()) {\n\t\tif (!shouldIncludeCssProperty(property)) continue\n\n\t\tconst value = style.get(property)!.toString()\n\n\t\tif (defaultStyles[property] === value) continue\n\n\t\tconst rule = getOwnProperty(cssRules, property)\n\t\tif (rule && rule(value, property, ruleOptions)) continue\n\n\t\tstyles[property] = value\n\t}\n\n\treturn styles\n}\n\nfunction styleFromComputedStyle(\n\tstyle: CSSStyleDeclaration,\n\t{ defaultStyles, parentStyles }: ReadStyleOpts\n) {\n\tconst styles: Record<string, string> = {}\n\tconst currentColor = style.color\n\tconst ruleOptions = {\n\t\tcurrentColor,\n\t\tparentStyles,\n\t\tdefaultStyles,\n\t\tgetStyle: (property: string) => style.getPropertyValue(property),\n\t}\n\n\tfor (const property in style) {\n\t\tif (!shouldIncludeCssProperty(property)) continue\n\n\t\tconst value = style.getPropertyValue(property)\n\n\t\tif (defaultStyles[property] === value) continue\n\n\t\tconst rule = getOwnProperty(cssRules, property)\n\t\tif (rule && rule(value, property, ruleOptions)) continue\n\n\t\tstyles[property] = value\n\t}\n\treturn styles\n}\n\nfunction formatCss(style: ReadonlyStyles) {\n\tlet cssText = ''\n\tfor (const [property, value] of Object.entries(style)) {\n\t\tcssText += `${property}: ${value};`\n\t}\n\treturn cssText\n}\n\n// when we're figuring out the default values for a tag, we need read them from a separate document\n// so they're not affected by the current document's styles\nlet defaultStyleFrame:\n\t| {\n\t\t\tiframe: HTMLIFrameElement\n\t\t\tforeignObject: SVGForeignObjectElement\n\t\t\tdocument: Document\n\t\t\townerDocument: Document\n\t }\n\t| undefined\nconst defaultStylesByTagName: Record<string, ReadonlyStyles> = {}\nfunction getDefaultStyleFrame(ownerDoc: Document) {\n\tif (!defaultStyleFrame || defaultStyleFrame.ownerDocument !== ownerDoc) {\n\t\tdestroyDefaultStyleFrame()\n\t\tconst frame = ownerDoc.createElement('iframe')\n\t\tframe.style.display = 'none'\n\t\townerDoc.body.appendChild(frame)\n\t\tconst frameDocument = assertExists(frame.contentDocument, 'frame must have a document')\n\t\tconst svg = frameDocument.createElementNS('http://www.w3.org/2000/svg', 'svg')\n\t\tconst foreignObject = frameDocument.createElementNS(\n\t\t\t'http://www.w3.org/2000/svg',\n\t\t\t'foreignObject'\n\t\t)\n\t\tsvg.appendChild(foreignObject)\n\t\tframeDocument.body.appendChild(svg)\n\t\tdefaultStyleFrame = {\n\t\t\tiframe: frame,\n\t\t\tforeignObject,\n\t\t\tdocument: frameDocument,\n\t\t\townerDocument: ownerDoc,\n\t\t}\n\t}\n\treturn defaultStyleFrame\n}\n\nfunction destroyDefaultStyleFrame() {\n\tif (defaultStyleFrame) {\n\t\tdefaultStyleFrame.iframe.remove()\n\t\tdefaultStyleFrame = undefined\n\t}\n\tfor (const tagName in defaultStylesByTagName) {\n\t\tdelete defaultStylesByTagName[tagName]\n\t}\n}\n\nconst defaultStyleReadOptions: ReadStyleOpts = { defaultStyles: NO_STYLES, parentStyles: NO_STYLES }\nfunction getDefaultStylesForTagName(ownerDoc: Document, tagName: string) {\n\tlet existing = defaultStylesByTagName[tagName]\n\tif (!existing) {\n\t\tconst { foreignObject, document } = getDefaultStyleFrame(ownerDoc)\n\t\tconst element = document.createElement(tagName)\n\t\tforeignObject.appendChild(element)\n\t\texisting = element.computedStyleMap\n\t\t\t? styleFromComputedStyleMap(element.computedStyleMap(), defaultStyleReadOptions)\n\t\t\t: styleFromComputedStyle(getComputedStyle(element), defaultStyleReadOptions)\n\t\tforeignObject.removeChild(element)\n\t\tdefaultStylesByTagName[tagName] = existing\n\t}\n\treturn existing\n}\n"],
5
+ "mappings": "AAAA,SAAS,cAAc,gBAAgB,iBAAiB,gBAAgB;AACxE,SAAiC,gBAAgB;AACjD;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AACP,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAC7B,SAAS,mBAAmB,gCAAgC;AAE5D,MAAM,YAAY,CAAC;AAQZ,MAAM,cAAc;AAAA,EAC1B,YAA6B,MAAe;AAAf;AAAA,EAAgB;AAAA,EAAhB;AAAA,EACZ,SAAS,oBAAI,IAA+B;AAAA,EACpD,QAAQ,IAAI,aAAa;AAAA,EAElC,sBAAsB,aAAsB;AAE3C,SAAK,kBAAkB,aAAa;AAAA,MACnC,uBAAuB;AAAA,MACvB,iCAAiC;AAAA,IAClC,CAAC;AAED,UAAM,WAAW,MAAM,KAAK,oBAAoB,WAAW,CAAC;AAC5D,WAAO,SAAS,QAAQ;AACvB,YAAM,QAAQ,SAAS,IAAI;AAC3B,eAAS,KAAK,GAAG,oBAAoB,KAAK,CAAC;AAI3C,WAAK,kBAAkB,OAAO;AAAA,QAC7B,uBAAuB;AAAA,QACvB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,0BAA0B,QAAQ,iBAAiB,GAAG,uBAAuB,IAC7E,uBAAuB,iBAAiB,OAAO,GAAG,uBAAuB;AAC5E,kBAAc,YAAY,OAAO;AACjC,2BAAuB,OAAO,IAAI;AAAA,EACnC;AACA,SAAO;AACR;",
6
6
  "names": []
7
7
  }
@@ -15,6 +15,9 @@ function fetchCache(cb, init) {
15
15
  }
16
16
  })();
17
17
  cache.set(url, promise);
18
+ promise.then((result) => {
19
+ if (result === null && cache.get(url) === promise) cache.delete(url);
20
+ });
18
21
  return promise;
19
22
  };
20
23
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/exports/fetchCache.ts"],
4
- "sourcesContent": ["import { FileHelpers, LruCache, assert, fetch } from '@tldraw/utils'\n\nexport function fetchCache<T>(cb: (response: Response) => Promise<T>, init?: RequestInit) {\n\tconst cache = new LruCache<string, Promise<T | null>>(100)\n\n\treturn async function fetchCached(url: string): Promise<T | null> {\n\t\tconst existing = cache.get(url)\n\t\tif (existing) return existing\n\n\t\tconst promise = (async () => {\n\t\t\ttry {\n\t\t\t\tconst response = await fetch(url, init)\n\t\t\t\tassert(response.ok)\n\t\t\t\treturn await cb(response)\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(err)\n\t\t\t\treturn null\n\t\t\t}\n\t\t})()\n\t\tcache.set(url, promise)\n\t\treturn promise\n\t}\n}\n\nexport const resourceToDataUrl = fetchCache(async (response) => {\n\treturn await FileHelpers.blobToDataUrl(await response.blob())\n})\n"],
5
- "mappings": "AAAA,SAAS,aAAa,UAAU,QAAQ,aAAa;AAE9C,SAAS,WAAc,IAAwC,MAAoB;AACzF,QAAM,QAAQ,IAAI,SAAoC,GAAG;AAEzD,SAAO,eAAe,YAAY,KAAgC;AACjE,UAAM,WAAW,MAAM,IAAI,GAAG;AAC9B,QAAI,SAAU,QAAO;AAErB,UAAM,WAAW,YAAY;AAC5B,UAAI;AACH,cAAM,WAAW,MAAM,MAAM,KAAK,IAAI;AACtC,eAAO,SAAS,EAAE;AAClB,eAAO,MAAM,GAAG,QAAQ;AAAA,MACzB,SAAS,KAAK;AACb,gBAAQ,MAAM,GAAG;AACjB,eAAO;AAAA,MACR;AAAA,IACD,GAAG;AACH,UAAM,IAAI,KAAK,OAAO;AACtB,WAAO;AAAA,EACR;AACD;AAEO,MAAM,oBAAoB,WAAW,OAAO,aAAa;AAC/D,SAAO,MAAM,YAAY,cAAc,MAAM,SAAS,KAAK,CAAC;AAC7D,CAAC;",
4
+ "sourcesContent": ["import { FileHelpers, LruCache, assert, fetch } from '@tldraw/utils'\n\nexport function fetchCache<T>(cb: (response: Response) => Promise<T>, init?: RequestInit) {\n\tconst cache = new LruCache<string, Promise<T | null>>(100)\n\n\treturn async function fetchCached(url: string): Promise<T | null> {\n\t\tconst existing = cache.get(url)\n\t\tif (existing) return existing\n\n\t\tconst promise = (async () => {\n\t\t\ttry {\n\t\t\t\tconst response = await fetch(url, init)\n\t\t\t\tassert(response.ok)\n\t\t\t\treturn await cb(response)\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(err)\n\t\t\t\treturn null\n\t\t\t}\n\t\t})()\n\t\tcache.set(url, promise)\n\t\t// only keep successes, otherwise a transient failure poisons this url for the whole session\n\t\tpromise.then((result) => {\n\t\t\tif (result === null && cache.get(url) === promise) cache.delete(url)\n\t\t})\n\t\treturn promise\n\t}\n}\n\nexport const resourceToDataUrl = fetchCache(async (response) => {\n\treturn await FileHelpers.blobToDataUrl(await response.blob())\n})\n"],
5
+ "mappings": "AAAA,SAAS,aAAa,UAAU,QAAQ,aAAa;AAE9C,SAAS,WAAc,IAAwC,MAAoB;AACzF,QAAM,QAAQ,IAAI,SAAoC,GAAG;AAEzD,SAAO,eAAe,YAAY,KAAgC;AACjE,UAAM,WAAW,MAAM,IAAI,GAAG;AAC9B,QAAI,SAAU,QAAO;AAErB,UAAM,WAAW,YAAY;AAC5B,UAAI;AACH,cAAM,WAAW,MAAM,MAAM,KAAK,IAAI;AACtC,eAAO,SAAS,EAAE;AAClB,eAAO,MAAM,GAAG,QAAQ;AAAA,MACzB,SAAS,KAAK;AACb,gBAAQ,MAAM,GAAG;AACjB,eAAO;AAAA,MACR;AAAA,IACD,GAAG;AACH,UAAM,IAAI,KAAK,OAAO;AAEtB,YAAQ,KAAK,CAAC,WAAW;AACxB,UAAI,WAAW,QAAQ,MAAM,IAAI,GAAG,MAAM,QAAS,OAAM,OAAO,GAAG;AAAA,IACpE,CAAC;AACD,WAAO;AAAA,EACR;AACD;AAEO,MAAM,oBAAoB,WAAW,OAAO,aAAa;AAC/D,SAAO,MAAM,YAAY,cAAc,MAAM,SAAS,KAAK,CAAC;AAC7D,CAAC;",
6
6
  "names": []
7
7
  }
@@ -77,7 +77,12 @@ function measureContentBounds(canvas, trimPaddingPx) {
77
77
  const ctx = canvas.getContext("2d");
78
78
  const extraPx = Math.ceil(trimPaddingPx);
79
79
  if (extraPx <= 0 || extraPx * 2 >= w || extraPx * 2 >= h) return null;
80
- const imageData = ctx.getImageData(0, 0, w, h);
80
+ let imageData;
81
+ try {
82
+ imageData = ctx.getImageData(0, 0, w, h);
83
+ } catch {
84
+ return null;
85
+ }
81
86
  const data = imageData.data;
82
87
  const cornerR = data[0];
83
88
  const cornerG = data[1];
@@ -179,12 +184,13 @@ function trimExtraPadding(canvas, trimPaddingPx) {
179
184
  async function trimSvgToContent(svgString, options) {
180
185
  const { width, height, trimPadding, scale } = options;
181
186
  if (trimPadding <= 0) return null;
182
- const canvasWidth = Math.floor(width);
183
- const canvasHeight = Math.floor(height);
187
+ let [canvasWidth, canvasHeight] = clampToBrowserMaxCanvasSize(width, height);
188
+ canvasWidth = Math.floor(canvasWidth);
189
+ canvasHeight = Math.floor(canvasHeight);
184
190
  if (canvasWidth <= 0 || canvasHeight <= 0) return null;
185
191
  const canvas = await renderSvgToCanvas(svgString, canvasWidth, canvasHeight);
186
192
  if (!canvas) return null;
187
- const trimPaddingPx = trimPadding * scale;
193
+ const trimPaddingPx = trimPadding * scale * (canvasWidth / width);
188
194
  const bounds = measureContentBounds(canvas, trimPaddingPx);
189
195
  if (!bounds) return null;
190
196
  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,SAAS,aAAa,OAAO,YAAY,aAAa;AACtD,SAAS,aAAa;AACtB,SAAS,mCAAmC;AAC5C,SAAS,kBAAkB;AAC3B,SAAS,yBAAyB;AAGlC,eAAsB,cACrB,WACA,SAOC;AACD,QAAM,SAAS,MAAM,yBAAyB,WAAW,OAAO;AAChE,SAAO,QAAQ,QAAQ;AACxB;AAGA,eAAsB,yBACrB,WACA,SASgE;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7D,QAAM,QAAQ,IAAI;AAElB,QAAM,cAAc,MAAM,aAAa,SAAS;AAChD,MAAI,CAAC,YAAa,QAAO;AAEzB,QAAM,CAAC,QAAQ,QAAQ,KAAK,GAAG,IAAI,YAAY,MAAM,KAAK,EAAE,IAAI,MAAM;AAGtE,QAAM,UAAU,SAAU,WAAW,cAAe;AACpD,QAAM,UAAU,SAAU,UAAU,eAAgB;AACpD,QAAM,UAAW,YAAY,YAAY,cAAe;AACxD,QAAM,UAAW,aAAa,WAAW,eAAgB;AAGzD,QAAM,WAAW,SAAS;AAC1B,QAAM,YAAY,SAAS;AAG3B,QAAM,aAAa,WAAW,GAAG,OAAO,IAAI,OAAO,IAAI,MAAM,IAAI,MAAM,EAAE;AACzE,QAAM,aAAa,SAAS,OAAO,QAAQ,CAAC;AAC5C,QAAM,aAAa,UAAU,OAAO,SAAS,CAAC;AAG9C,QAAM,aAAa,IAAI,cAAc;AACrC,QAAM,eAAe,WAAW,kBAAkB,KAAK;AAEvD,SAAO,EAAE,KAAK,cAAc,OAAO,UAAU,QAAQ,UAAU;AAChE;",
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,SAAS,aAAa,OAAO,YAAY,aAAa;AACtD,SAAS,aAAa;AACtB,SAAS,mCAAmC;AAC5C,SAAS,kBAAkB;AAC3B,SAAS,yBAAyB;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,IAAI;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,YA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IAAI,MAAM,EAAE;AACzE,QAAM,aAAa,SAAS,OAAO,QAAQ,CAAC;AAC5C,QAAM,aAAa,UAAU,OAAO,SAAS,CAAC;AAG9C,QAAM,aAAa,IAAI,cAAc;AACrC,QAAM,eAAe,WAAW,kBAAkB,KAAK;AAEvD,SAAO,EAAE,KAAK,cAAc,OAAO,UAAU,QAAQ,UAAU;AAChE;",
6
6
  "names": ["blob"]
7
7
  }
@@ -1,5 +1,6 @@
1
1
  import { jsx, jsxs } from "react/jsx-runtime";
2
2
  import { useAtom, useValue } from "@tldraw/state-react";
3
+ import { DefaultColorStyle } from "@tldraw/tlschema";
3
4
  import { hasOwnProperty, promiseWithResolve, uniqueId } from "@tldraw/utils";
4
5
  import {
5
6
  Fragment,
@@ -77,6 +78,7 @@ function getSvgJsx(editor, ids, opts = {}) {
77
78
  colorMode,
78
79
  renderingShapes,
79
80
  onMount: initialEffectPromise.resolve,
81
+ onError: exportDelay.fail,
80
82
  waitUntil: exportDelay.waitUntil
81
83
  }
82
84
  );
@@ -124,6 +126,7 @@ function SvgExport({
124
126
  colorMode,
125
127
  renderingShapes,
126
128
  onMount,
129
+ onError,
127
130
  waitUntil
128
131
  }) {
129
132
  const masksId = useUniqueSafeId();
@@ -286,8 +289,17 @@ function SvgExport({
286
289
  defsById: { ...state.defsById, ...shapeDefs }
287
290
  }));
288
291
  });
289
- })();
290
- }, [bbox, editor, exportContext, masksId, renderingShapes, singleFrameShapeId, stateAtom]);
292
+ })().catch(onError);
293
+ }, [
294
+ bbox,
295
+ editor,
296
+ exportContext,
297
+ masksId,
298
+ onError,
299
+ renderingShapes,
300
+ singleFrameShapeId,
301
+ stateAtom
302
+ ]);
291
303
  useEffect(() => {
292
304
  const fontsInUse = /* @__PURE__ */ new Set();
293
305
  for (const { id } of renderingShapes) {
@@ -312,13 +324,10 @@ function SvgExport({
312
324
  const colors = theme.colors[colorMode];
313
325
  let backgroundColor = background ? colors.background : "transparent";
314
326
  if (singleFrameShapeId && background) {
315
- const frameShapeUtil = editor.getShapeUtil("frame");
316
- if (frameShapeUtil?.options.showColors) {
317
- const shape = editor.getShape(singleFrameShapeId);
318
- backgroundColor = getColorValue(colors, shape.props.color, "frameFill");
319
- } else {
320
- backgroundColor = colors.solid;
321
- }
327
+ const shape = editor.getShape(singleFrameShapeId);
328
+ const { showColors } = editor.getShapeUtil(shape).options;
329
+ const color = showColors ? editor.getShapeStyleIfExists(shape, DefaultColorStyle) ?? ("color" in shape.props ? shape.props.color : null) : null;
330
+ backgroundColor = typeof color === "string" ? getColorValue(colors, color, "frameFill") : colors.solid;
322
331
  }
323
332
  return /* @__PURE__ */ jsx(SvgExportContextProvider, { editor, context: exportContext, children: /* @__PURE__ */ jsxs(
324
333
  "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": "AA2GE,cAyWC,YAzWD;AA3GF,SAAS,SAAS,gBAAgB;AAGlC,SAAS,gBAAgB,oBAAoB,gBAAgB;AAC7D;AAAA,EAEC;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AACP,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;AAC9B,SAAS,YAAY,4BAA4B;AAEjD,SAAS,qBAAqB;AAG9B;AAAA,EAEC;AAAA,OAEM;AACP,SAAS,i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,IAAI,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,oBAAC,iBAAc,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,8BAAC,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,\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;AAAA,YACA;AAAA,UACD;AAAA,UAEA,8BAAC,aAAU,OAAc,MAAY;AAAA;AAAA,MACtC;AAAA;AAAA,EACD,GACD;AAEF;",
6
6
  "names": ["state", "scale"]
7
7
  }
@@ -1,5 +1,5 @@
1
1
  import { safeParseUrl } from "@tldraw/utils";
2
- const importsRegex = /@import\s+(?:"([^"]+)"|'([^']+)'|url\s*\(\s*(?:"([^"]+)"|'([^']+)'|([^'")]+))\s*\))([^;]+);/gi;
2
+ const importsRegex = /@import\s+(?:"([^"]+)"|'([^']+)'|url\s*\(\s*(?:"([^"]+)"|'([^']+)'|([^'")]+))\s*\))([^;]*);/gi;
3
3
  const fontFaceRegex = /@font-face\s*{([^}]+)}/gi;
4
4
  const urlsRegex = /url\s*\(\s*(?:"([^"]+)"|'([^']+)'|([^'")]+))\s*\)/gi;
5
5
  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,SAAS,oBAAoB;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,KAA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W,EAAG,QAAO;AAC7C,MAAI,SAAS,WAAW,YAAY,EAAG,QAAO;AAC9C,MAAI,aAAa,SAAU,QAAO;AAClC,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
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/hooks/EditorComponentsContext.tsx"],
4
- "sourcesContent": ["import { ComponentType, RefAttributes, createContext, useContext } from 'react'\nimport type { TLCanvasComponentProps } from '../components/default-components/DefaultCanvas'\nimport type { TLCursorProps } from '../components/default-components/DefaultCursor'\nimport type { TLErrorFallbackComponent } from '../components/default-components/DefaultErrorFallback'\nimport type { TLGridProps } from '../components/default-components/DefaultGrid'\nimport type { TLShapeErrorFallbackComponent } from '../components/default-components/DefaultShapeErrorFallback'\nimport type { TLShapeWrapperProps } from '../components/default-components/DefaultShapeWrapper'\n\n/** @public */\nexport interface TLEditorComponents {\n\tBackground?: ComponentType | null\n\tCanvas?: ComponentType<TLCanvasComponentProps> | null\n\tCollaboratorCursor?: ComponentType<TLCursorProps> | null\n\tGrid?: ComponentType<TLGridProps> | null\n\tInFrontOfTheCanvas?: ComponentType | null\n\tLoadingScreen?: ComponentType | null\n\tOnTheCanvas?: ComponentType | null\n\tShapeWrapper?: ComponentType<TLShapeWrapperProps & RefAttributes<HTMLDivElement>> | null\n\tSpinner?: ComponentType<React.SVGProps<SVGSVGElement>> | null\n\tSvgDefs?: ComponentType | null\n\n\t// These will always have defaults\n\tErrorFallback?: TLErrorFallbackComponent\n\tShapeErrorFallback?: TLShapeErrorFallbackComponent\n}\n\nexport const EditorComponentsContext = createContext<null | Required<TLEditorComponents>>(null)\n\n/** @public */\nexport function useEditorComponents() {\n\tconst components = useContext(EditorComponentsContext)\n\tif (!components) {\n\t\tthrow new Error('useEditorComponents must be used inside of <EditorComponentsProvider />')\n\t}\n\treturn components\n}\n"],
5
- "mappings": "AAAA,SAAuC,eAAe,kBAAkB;AA0BjE,MAAM,0BAA0B,cAAmD,IAAI;AAGvF,SAAS,sBAAsB;AACrC,QAAM,aAAa,WAAW,uBAAuB;AACrD,MAAI,CAAC,YAAY;AAChB,UAAM,IAAI,MAAM,yEAAyE;AAAA,EAC1F;AACA,SAAO;AACR;",
4
+ "sourcesContent": ["import { ComponentType, RefAttributes, createContext, useContext } from 'react'\nimport type { TLCanvasComponentProps } from '../components/default-components/DefaultCanvas'\nimport type { TLCursorProps } from '../components/default-components/DefaultCursor'\nimport type { TLErrorFallbackComponent } from '../components/default-components/DefaultErrorFallback'\nimport type { TLGridProps } from '../components/default-components/DefaultGrid'\nimport type { TLShapeErrorFallbackComponent } from '../components/default-components/DefaultShapeErrorFallback'\nimport type { TLShapeWrapperProps } from '../components/default-components/DefaultShapeWrapper'\nimport type { TLSpinnerProps } from '../components/default-components/DefaultSpinner'\n\n/** @public */\nexport interface TLEditorComponents {\n\tBackground?: ComponentType | null\n\tCanvas?: ComponentType<TLCanvasComponentProps> | null\n\tCollaboratorCursor?: ComponentType<TLCursorProps> | null\n\tGrid?: ComponentType<TLGridProps> | null\n\tInFrontOfTheCanvas?: ComponentType | null\n\tLoadingScreen?: ComponentType | null\n\tOnTheCanvas?: ComponentType | null\n\tShapeWrapper?: ComponentType<TLShapeWrapperProps & RefAttributes<HTMLDivElement>> | null\n\tSpinner?: ComponentType<TLSpinnerProps> | null\n\tSvgDefs?: ComponentType | null\n\n\t// These will always have defaults\n\tErrorFallback?: TLErrorFallbackComponent\n\tShapeErrorFallback?: TLShapeErrorFallbackComponent\n}\n\nexport const EditorComponentsContext = createContext<null | Required<TLEditorComponents>>(null)\n\n/** @public */\nexport function useEditorComponents() {\n\tconst components = useContext(EditorComponentsContext)\n\tif (!components) {\n\t\tthrow new Error('useEditorComponents must be used inside of <EditorComponentsProvider />')\n\t}\n\treturn components\n}\n"],
5
+ "mappings": "AAAA,SAAuC,eAAe,kBAAkB;AA2BjE,MAAM,0BAA0B,cAAmD,IAAI;AAGvF,SAAS,sBAAsB;AACrC,QAAM,aAAa,WAAW,uBAAuB;AACrD,MAAI,CAAC,YAAY;AAChB,UAAM,IAAI,MAAM,yEAAyE;AAAA,EAC1F;AACA,SAAO;AACR;",
6
6
  "names": []
7
7
  }
@@ -17,6 +17,7 @@ function useCanvasEvents() {
17
17
  const events = useMemo(
18
18
  function canvasEvents() {
19
19
  let isSecondaryClickPointerDown = false;
20
+ const pointerDownButtons = /* @__PURE__ */ new Map();
20
21
  function onPointerDown(e) {
21
22
  if (editor.wasEventAlreadyHandled(e)) return;
22
23
  const button = getPointerEventButton(e);
@@ -33,6 +34,10 @@ function useCanvasEvents() {
33
34
  if (button !== 0 && button !== 1 && button !== 2 && button !== 5) return;
34
35
  const isPenDirect = isDirectDisplayPen(e);
35
36
  setPointerCapture(e.currentTarget, e);
37
+ const isPenMode = editor.getInstanceState().isPenMode;
38
+ if (!editor.inputs.getIsPinching() && !(isPenMode && e.pointerType !== "pen")) {
39
+ pointerDownButtons.set(e.pointerId, button);
40
+ }
36
41
  editor.dispatch({
37
42
  type: "pointer",
38
43
  target: "canvas",
@@ -43,6 +48,7 @@ function useCanvasEvents() {
43
48
  }
44
49
  function onPointerUp(e) {
45
50
  if (editor.wasEventAlreadyHandled(e)) return;
51
+ pointerDownButtons.delete(e.pointerId);
46
52
  const button = isSecondaryClickPointerDown ? 2 : getPointerEventButton(e);
47
53
  if (button !== 0 && button !== 1 && button !== 2 && button !== 5) return;
48
54
  const rightClickPanning = editor.options.rightClickPanning;
@@ -70,6 +76,23 @@ function useCanvasEvents() {
70
76
  }
71
77
  isSecondaryClickPointerDown = false;
72
78
  }
79
+ function onPointerCancel(e) {
80
+ if (editor.wasEventAlreadyHandled(e)) return;
81
+ const pointerDownButton = pointerDownButtons.get(e.pointerId);
82
+ pointerDownButtons.delete(e.pointerId);
83
+ if (editor.getInstanceState().isPenMode && e.pointerType !== "pen") return;
84
+ releasePointerCapture(e.currentTarget, e);
85
+ if (!editor.inputs.getIsPointing() || pointerDownButton === void 0) return;
86
+ editor.interrupt();
87
+ editor.dispatch({
88
+ type: "pointer",
89
+ target: "canvas",
90
+ name: "pointer_up",
91
+ ...getPointerInfo(editor, e),
92
+ button: pointerDownButton
93
+ });
94
+ isSecondaryClickPointerDown = false;
95
+ }
73
96
  function onPointerEnter(e) {
74
97
  if (editor.wasEventAlreadyHandled(e)) return;
75
98
  if (editor.getInstanceState().isPenMode && e.pointerType !== "pen") return;
@@ -151,6 +174,7 @@ function useCanvasEvents() {
151
174
  return {
152
175
  onPointerDown,
153
176
  onPointerUp,
177
+ onPointerCancel,
154
178
  onPointerEnter,
155
179
  onPointerLeave,
156
180
  onDragOver,