js-draw 0.3.2 → 0.4.1

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 (104) hide show
  1. package/.github/pull_request_template.md +15 -0
  2. package/.github/workflows/firebase-hosting-merge.yml +7 -0
  3. package/.github/workflows/firebase-hosting-pull-request.yml +10 -0
  4. package/.github/workflows/github-pages.yml +2 -0
  5. package/CHANGELOG.md +16 -1
  6. package/README.md +1 -3
  7. package/dist/bundle.js +1 -1
  8. package/dist/src/Editor.d.ts +11 -0
  9. package/dist/src/Editor.js +107 -77
  10. package/dist/src/Pointer.d.ts +1 -1
  11. package/dist/src/Pointer.js +8 -3
  12. package/dist/src/Viewport.d.ts +1 -0
  13. package/dist/src/Viewport.js +14 -1
  14. package/dist/src/components/AbstractComponent.js +1 -0
  15. package/dist/src/components/ImageComponent.d.ts +2 -2
  16. package/dist/src/components/Stroke.js +15 -9
  17. package/dist/src/components/Text.d.ts +1 -1
  18. package/dist/src/components/Text.js +1 -1
  19. package/dist/src/components/builders/FreehandLineBuilder.d.ts +1 -0
  20. package/dist/src/components/builders/FreehandLineBuilder.js +34 -36
  21. package/dist/src/language/assertions.d.ts +1 -0
  22. package/dist/src/language/assertions.js +5 -0
  23. package/dist/src/math/Mat33.d.ts +38 -2
  24. package/dist/src/math/Mat33.js +30 -1
  25. package/dist/src/math/Path.d.ts +1 -1
  26. package/dist/src/math/Path.js +10 -8
  27. package/dist/src/math/Vec3.d.ts +12 -2
  28. package/dist/src/math/Vec3.js +16 -1
  29. package/dist/src/math/rounding.d.ts +1 -0
  30. package/dist/src/math/rounding.js +13 -6
  31. package/dist/src/rendering/renderers/AbstractRenderer.js +2 -1
  32. package/dist/src/testing/beforeEachFile.d.ts +1 -0
  33. package/dist/src/testing/beforeEachFile.js +3 -0
  34. package/dist/src/testing/createEditor.d.ts +1 -0
  35. package/dist/src/testing/createEditor.js +7 -1
  36. package/dist/src/testing/loadExpectExtensions.d.ts +0 -15
  37. package/dist/src/toolbar/HTMLToolbar.js +5 -4
  38. package/dist/src/toolbar/widgets/SelectionToolWidget.d.ts +1 -1
  39. package/dist/src/tools/PasteHandler.js +3 -1
  40. package/dist/src/tools/Pen.js +1 -1
  41. package/dist/src/tools/SelectionTool/Selection.d.ts +54 -0
  42. package/dist/src/tools/SelectionTool/Selection.js +337 -0
  43. package/dist/src/tools/SelectionTool/SelectionHandle.d.ts +35 -0
  44. package/dist/src/tools/SelectionTool/SelectionHandle.js +75 -0
  45. package/dist/src/tools/SelectionTool/SelectionTool.d.ts +31 -0
  46. package/dist/src/tools/SelectionTool/SelectionTool.js +284 -0
  47. package/dist/src/tools/SelectionTool/TransformMode.d.ts +34 -0
  48. package/dist/src/tools/SelectionTool/TransformMode.js +98 -0
  49. package/dist/src/tools/SelectionTool/types.d.ts +9 -0
  50. package/dist/src/tools/SelectionTool/types.js +11 -0
  51. package/dist/src/tools/ToolController.js +1 -1
  52. package/dist/src/tools/lib.d.ts +1 -1
  53. package/dist/src/tools/lib.js +1 -1
  54. package/dist/src/types.d.ts +1 -1
  55. package/jest.config.js +5 -0
  56. package/package.json +15 -14
  57. package/src/Editor.css +1 -0
  58. package/src/Editor.ts +147 -108
  59. package/src/Pointer.ts +8 -3
  60. package/src/Viewport.ts +17 -2
  61. package/src/components/AbstractComponent.ts +4 -6
  62. package/src/components/ImageComponent.ts +2 -6
  63. package/src/components/Stroke.test.ts +0 -3
  64. package/src/components/Stroke.ts +14 -7
  65. package/src/components/Text.test.ts +0 -3
  66. package/src/components/Text.ts +4 -8
  67. package/src/components/builders/FreehandLineBuilder.ts +37 -43
  68. package/src/language/assertions.ts +6 -0
  69. package/src/math/LineSegment2.test.ts +8 -10
  70. package/src/math/Mat33.test.ts +14 -2
  71. package/src/math/Mat33.ts +43 -2
  72. package/src/math/Path.toString.test.ts +12 -1
  73. package/src/math/Path.ts +11 -9
  74. package/src/math/Rect2.test.ts +0 -3
  75. package/src/math/Vec2.test.ts +0 -3
  76. package/src/math/Vec3.test.ts +0 -3
  77. package/src/math/Vec3.ts +23 -2
  78. package/src/math/rounding.test.ts +30 -5
  79. package/src/math/rounding.ts +16 -7
  80. package/src/rendering/renderers/AbstractRenderer.ts +3 -2
  81. package/src/testing/beforeEachFile.ts +3 -0
  82. package/src/testing/createEditor.ts +8 -1
  83. package/src/testing/global.d.ts +17 -0
  84. package/src/testing/loadExpectExtensions.ts +0 -15
  85. package/src/toolbar/HTMLToolbar.ts +5 -4
  86. package/src/toolbar/toolbar.css +3 -2
  87. package/src/toolbar/widgets/SelectionToolWidget.ts +1 -1
  88. package/src/tools/PasteHandler.ts +4 -1
  89. package/src/tools/Pen.test.ts +150 -0
  90. package/src/tools/Pen.ts +1 -1
  91. package/src/tools/SelectionTool/Selection.ts +455 -0
  92. package/src/tools/SelectionTool/SelectionHandle.ts +99 -0
  93. package/src/tools/SelectionTool/SelectionTool.css +22 -0
  94. package/src/tools/{SelectionTool.test.ts → SelectionTool/SelectionTool.test.ts} +21 -21
  95. package/src/tools/SelectionTool/SelectionTool.ts +344 -0
  96. package/src/tools/SelectionTool/TransformMode.ts +114 -0
  97. package/src/tools/SelectionTool/types.ts +11 -0
  98. package/src/tools/ToolController.ts +1 -1
  99. package/src/tools/lib.ts +1 -1
  100. package/src/types.ts +1 -1
  101. package/tsconfig.json +3 -1
  102. package/dist/src/tools/SelectionTool.d.ts +0 -65
  103. package/dist/src/tools/SelectionTool.js +0 -647
  104. package/src/tools/SelectionTool.ts +0 -797
package/dist/bundle.js CHANGED
@@ -1 +1 @@
1
- (()=>{"use strict";var e={786:(t,e,n)=>{n.d(e,{Z:()=>a});var r=n(81),i=n.n(r),o=n(645),s=n.n(o)()(i());s.push([t.id,'.clr-picker {\r\n display: none;\r\n flex-wrap: wrap;\r\n position: absolute;\r\n width: 200px;\r\n z-index: 1000;\r\n border-radius: 10px;\r\n background-color: #fff;\r\n justify-content: space-between;\r\n box-shadow: 0 0 5px rgba(0,0,0,.05), 0 5px 20px rgba(0,0,0,.1);\r\n -moz-user-select: none;\r\n -webkit-user-select: none;\r\n user-select: none;\r\n}\r\n\r\n.clr-picker.clr-open,\r\n.clr-picker[data-inline="true"] {\r\n display: flex;\r\n}\r\n\r\n.clr-picker[data-inline="true"] {\r\n position: relative;\r\n}\r\n\r\n.clr-gradient {\r\n position: relative;\r\n width: 100%;\r\n height: 100px;\r\n margin-bottom: 15px;\r\n border-radius: 3px 3px 0 0;\r\n background-image: linear-gradient(rgba(0,0,0,0), #000), linear-gradient(90deg, #fff, currentColor);\r\n cursor: pointer;\r\n}\r\n\r\n.clr-marker {\r\n position: absolute;\r\n width: 12px;\r\n height: 12px;\r\n margin: -6px 0 0 -6px;\r\n border: 1px solid #fff;\r\n border-radius: 50%;\r\n background-color: currentColor;\r\n cursor: pointer;\r\n}\r\n\r\n.clr-picker input[type="range"]::-webkit-slider-runnable-track {\r\n width: 100%;\r\n height: 8px;\r\n}\r\n\r\n.clr-picker input[type="range"]::-webkit-slider-thumb {\r\n width: 8px;\r\n height: 8px;\r\n -webkit-appearance: none;\r\n}\r\n\r\n.clr-picker input[type="range"]::-moz-range-track {\r\n width: 100%;\r\n height: 8px;\r\n border: 0;\r\n}\r\n\r\n.clr-picker input[type="range"]::-moz-range-thumb {\r\n width: 8px;\r\n height: 8px;\r\n border: 0;\r\n}\r\n\r\n.clr-hue {\r\n background-image: linear-gradient(to right, #f00 0%, #ff0 16.66%, #0f0 33.33%, #0ff 50%, #00f 66.66%, #f0f 83.33%, #f00 100%);\r\n}\r\n\r\n.clr-hue,\r\n.clr-alpha {\r\n position: relative;\r\n width: calc(100% - 40px);\r\n height: 8px;\r\n margin: 5px 20px;\r\n border-radius: 4px;\r\n}\r\n\r\n.clr-alpha span {\r\n display: block;\r\n height: 100%;\r\n width: 100%;\r\n border-radius: inherit;\r\n background-image: linear-gradient(90deg, rgba(0,0,0,0), currentColor);\r\n}\r\n\r\n.clr-hue input,\r\n.clr-alpha input {\r\n position: absolute;\r\n width: calc(100% + 16px);\r\n height: 16px;\r\n left: -8px;\r\n top: -4px;\r\n margin: 0;\r\n background-color: transparent;\r\n opacity: 0;\r\n cursor: pointer;\r\n appearance: none;\r\n -webkit-appearance: none;\r\n}\r\n\r\n.clr-hue div,\r\n.clr-alpha div {\r\n position: absolute;\r\n width: 16px;\r\n height: 16px;\r\n left: 0;\r\n top: 50%;\r\n margin-left: -8px;\r\n transform: translateY(-50%);\r\n border: 2px solid #fff;\r\n border-radius: 50%;\r\n background-color: currentColor;\r\n box-shadow: 0 0 1px #888;\r\n pointer-events: none;\r\n}\r\n\r\n.clr-alpha div:before {\r\n content: \'\';\r\n position: absolute;\r\n height: 100%;\r\n width: 100%;\r\n left: 0;\r\n top: 0;\r\n border-radius: 50%;\r\n background-color: currentColor;\r\n}\r\n\r\n.clr-format {\r\n display: none;\r\n order: 1;\r\n width: calc(100% - 40px);\r\n margin: 0 20px 20px;\r\n}\r\n\r\n.clr-segmented {\r\n display: flex;\r\n position: relative;\r\n width: 100%;\r\n margin: 0;\r\n padding: 0;\r\n border: 1px solid #ddd;\r\n border-radius: 15px;\r\n box-sizing: border-box;\r\n color: #999;\r\n font-size: 12px;\r\n}\r\n\r\n.clr-segmented input,\r\n.clr-segmented legend {\r\n position: absolute;\r\n width: 100%;\r\n height: 100%;\r\n margin: 0;\r\n padding: 0;\r\n border: 0;\r\n left: 0;\r\n top: 0;\r\n opacity: 0;\r\n pointer-events: none;\r\n}\r\n\r\n.clr-segmented label {\r\n flex-grow: 1;\r\n padding: 4px 0;\r\n text-align: center;\r\n cursor: pointer;\r\n}\r\n\r\n.clr-segmented label:first-of-type {\r\n border-radius: 10px 0 0 10px;\r\n}\r\n\r\n.clr-segmented label:last-of-type {\r\n border-radius: 0 10px 10px 0;\r\n}\r\n\r\n.clr-segmented input:checked + label {\r\n color: #fff;\r\n background-color: #666;\r\n}\r\n\r\n.clr-swatches {\r\n order: 2;\r\n width: calc(100% - 32px);\r\n margin: 0 16px;\r\n}\r\n\r\n.clr-swatches div {\r\n display: flex;\r\n flex-wrap: wrap;\r\n padding-bottom: 12px;\r\n justify-content: center;\r\n}\r\n\r\n.clr-swatches button {\r\n position: relative;\r\n width: 20px;\r\n height: 20px;\r\n margin: 0 4px 6px 4px;\r\n border: 0;\r\n border-radius: 50%;\r\n color: inherit;\r\n text-indent: -1000px;\r\n white-space: nowrap;\r\n overflow: hidden;\r\n cursor: pointer;\r\n}\r\n\r\n.clr-swatches button:after {\r\n content: \'\';\r\n display: block;\r\n position: absolute;\r\n width: 100%;\r\n height: 100%;\r\n left: 0;\r\n top: 0;\r\n border-radius: inherit;\r\n background-color: currentColor;\r\n box-shadow: inset 0 0 0 1px rgba(0,0,0,.1);\r\n}\r\n\r\ninput.clr-color {\r\n order: 1;\r\n width: calc(100% - 80px);\r\n height: 32px;\r\n margin: 15px 20px 20px 0;\r\n padding: 0 10px;\r\n border: 1px solid #ddd;\r\n border-radius: 16px;\r\n color: #444;\r\n background-color: #fff;\r\n font-family: sans-serif;\r\n font-size: 14px;\r\n text-align: center;\r\n box-shadow: none;\r\n}\r\n\r\ninput.clr-color:focus {\r\n outline: none;\r\n border: 1px solid #1e90ff;\r\n}\r\n\r\n.clr-clear {\r\n display: none;\r\n order: 2;\r\n height: 24px;\r\n margin: 0 20px 20px auto;\r\n padding: 0 20px;\r\n border: 0;\r\n border-radius: 12px;\r\n color: #fff;\r\n background-color: #666;\r\n font-family: inherit;\r\n font-size: 12px;\r\n font-weight: 400;\r\n cursor: pointer;\r\n}\r\n\r\n.clr-preview {\r\n position: relative;\r\n width: 32px;\r\n height: 32px;\r\n margin: 15px 0 20px 20px;\r\n border: 0;\r\n border-radius: 50%;\r\n overflow: hidden;\r\n cursor: pointer;\r\n}\r\n\r\n.clr-preview:before,\r\n.clr-preview:after {\r\n content: \'\';\r\n position: absolute;\r\n height: 100%;\r\n width: 100%;\r\n left: 0;\r\n top: 0;\r\n border: 1px solid #fff;\r\n border-radius: 50%;\r\n}\r\n\r\n.clr-preview:after {\r\n border: 0;\r\n background-color: currentColor;\r\n box-shadow: inset 0 0 0 1px rgba(0,0,0,.1);\r\n}\r\n\r\n.clr-marker,\r\n.clr-hue div,\r\n.clr-alpha div,\r\n.clr-color {\r\n box-sizing: border-box;\r\n}\r\n\r\n.clr-field {\r\n display: inline-block;\r\n position: relative;\r\n color: transparent;\r\n}\r\n\r\n.clr-field button {\r\n position: absolute;\r\n width: 30px;\r\n height: 100%;\r\n right: 0;\r\n top: 50%;\r\n transform: translateY(-50%);\r\n border: 0;\r\n color: inherit;\r\n text-indent: -1000px;\r\n white-space: nowrap;\r\n overflow: hidden;\r\n pointer-events: none;\r\n}\r\n\r\n.clr-field button:after {\r\n content: \'\';\r\n display: block;\r\n position: absolute;\r\n width: 100%;\r\n height: 100%;\r\n left: 0;\r\n top: 0;\r\n border-radius: inherit;\r\n background-color: currentColor;\r\n box-shadow: inset 0 0 1px rgba(0,0,0,.5);\r\n}\r\n\r\n.clr-alpha,\r\n.clr-alpha div,\r\n.clr-swatches button,\r\n.clr-preview:before,\r\n.clr-field button {\r\n background-image: repeating-linear-gradient(45deg, #aaa 25%, transparent 25%, transparent 75%, #aaa 75%, #aaa), repeating-linear-gradient(45deg, #aaa 25%, #fff 25%, #fff 75%, #aaa 75%, #aaa);\r\n background-position: 0 0, 4px 4px;\r\n background-size: 8px 8px;\r\n}\r\n\r\n.clr-marker:focus {\r\n outline: none;\r\n}\r\n\r\n.clr-keyboard-nav .clr-marker:focus,\r\n.clr-keyboard-nav .clr-hue input:focus + div,\r\n.clr-keyboard-nav .clr-alpha input:focus + div,\r\n.clr-keyboard-nav .clr-segmented input:focus + label {\r\n outline: none;\r\n box-shadow: 0 0 0 2px #1e90ff, 0 0 2px 2px #fff;\r\n}\r\n\r\n.clr-picker[data-alpha="false"] .clr-alpha {\r\n display: none;\r\n}\r\n\r\n.clr-picker[data-minimal="true"] {\r\n padding-top: 16px;\r\n}\r\n\r\n.clr-picker[data-minimal="true"] .clr-gradient,\r\n.clr-picker[data-minimal="true"] .clr-hue,\r\n.clr-picker[data-minimal="true"] .clr-alpha,\r\n.clr-picker[data-minimal="true"] .clr-color,\r\n.clr-picker[data-minimal="true"] .clr-preview {\r\n display: none;\r\n}\r\n\r\n/** Dark theme **/\r\n\r\n.clr-dark {\r\n background-color: #444;\r\n}\r\n\r\n.clr-dark .clr-segmented {\r\n border-color: #777;\r\n}\r\n\r\n.clr-dark .clr-swatches button:after {\r\n box-shadow: inset 0 0 0 1px rgba(255,255,255,.3);\r\n}\r\n\r\n.clr-dark input.clr-color {\r\n color: #fff;\r\n border-color: #777;\r\n background-color: #555;\r\n}\r\n\r\n.clr-dark input.clr-color:focus {\r\n border-color: #1e90ff;\r\n}\r\n\r\n.clr-dark .clr-preview:after {\r\n box-shadow: inset 0 0 0 1px rgba(255,255,255,.5);\r\n}\r\n\r\n.clr-dark .clr-alpha,\r\n.clr-dark .clr-alpha div,\r\n.clr-dark .clr-swatches button,\r\n.clr-dark .clr-preview:before {\r\n background-image: repeating-linear-gradient(45deg, #666 25%, transparent 25%, transparent 75%, #888 75%, #888), repeating-linear-gradient(45deg, #888 25%, #444 25%, #444 75%, #888 75%, #888);\r\n}\r\n\r\n/** Polaroid theme **/\r\n\r\n.clr-picker.clr-polaroid {\r\n border-radius: 6px;\r\n box-shadow: 0 0 5px rgba(0,0,0,.1), 0 5px 30px rgba(0,0,0,.2);\r\n}\r\n\r\n.clr-picker.clr-polaroid:before {\r\n content: \'\';\r\n display: block;\r\n position: absolute;\r\n width: 16px;\r\n height: 10px;\r\n left: 20px;\r\n top: -10px;\r\n border: solid transparent;\r\n border-width: 0 8px 10px 8px;\r\n border-bottom-color: currentColor;\r\n box-sizing: border-box;\r\n color: #fff;\r\n filter: drop-shadow(0 -4px 3px rgba(0,0,0,.1));\r\n pointer-events: none;\r\n}\r\n\r\n.clr-picker.clr-polaroid.clr-dark:before {\r\n color: #444;\r\n}\r\n\r\n.clr-picker.clr-polaroid.clr-left:before {\r\n left: auto;\r\n right: 20px;\r\n}\r\n\r\n.clr-picker.clr-polaroid.clr-top:before {\r\n top: auto;\r\n bottom: -10px;\r\n transform: rotateZ(180deg);\r\n}\r\n\r\n.clr-polaroid .clr-gradient {\r\n width: calc(100% - 20px);\r\n height: 120px;\r\n margin: 10px;\r\n border-radius: 3px;\r\n}\r\n\r\n.clr-polaroid .clr-hue,\r\n.clr-polaroid .clr-alpha {\r\n width: calc(100% - 30px);\r\n height: 10px;\r\n margin: 6px 15px;\r\n border-radius: 5px;\r\n}\r\n\r\n.clr-polaroid .clr-hue div,\r\n.clr-polaroid .clr-alpha div {\r\n box-shadow: 0 0 5px rgba(0,0,0,.2);\r\n}\r\n\r\n.clr-polaroid .clr-format {\r\n width: calc(100% - 20px);\r\n margin: 0 10px 15px;\r\n}\r\n\r\n.clr-polaroid .clr-swatches {\r\n width: calc(100% - 12px);\r\n margin: 0 6px;\r\n}\r\n.clr-polaroid .clr-swatches div {\r\n padding-bottom: 10px;\r\n}\r\n\r\n.clr-polaroid .clr-swatches button {\r\n width: 22px;\r\n height: 22px;\r\n}\r\n\r\n.clr-polaroid input.clr-color {\r\n width: calc(100% - 60px);\r\n margin: 10px 10px 15px 0;\r\n}\r\n\r\n.clr-polaroid .clr-clear {\r\n margin: 0 10px 15px auto;\r\n}\r\n\r\n.clr-polaroid .clr-preview {\r\n margin: 10px 0 15px 10px;\r\n}\r\n\r\n/** Large theme **/\r\n\r\n.clr-picker.clr-large {\r\n width: 275px;\r\n}\r\n\r\n.clr-large .clr-gradient {\r\n height: 150px;\r\n}\r\n\r\n.clr-large .clr-swatches button {\r\n width: 22px;\r\n height: 22px;\r\n}\r\n\r\n/** Pill (horizontal) theme **/\r\n\r\n.clr-picker.clr-pill {\r\n width: 380px;\r\n padding-left: 180px;\r\n box-sizing: border-box;\r\n}\r\n\r\n.clr-pill .clr-gradient {\r\n position: absolute;\r\n width: 180px;\r\n height: 100%;\r\n left: 0;\r\n top: 0;\r\n margin-bottom: 0;\r\n border-radius: 3px 0 0 3px;\r\n}\r\n\r\n.clr-pill .clr-hue {\r\n margin-top: 20px;\r\n}',""]);const a=s},59:(t,e,n)=>{n.d(e,{Z:()=>c});var r=n(81),i=n.n(r),o=n(645),s=n.n(o),a=n(771),l=s()(i());l.i(a.Z),l.push([t.id,"\n.imageEditorContainer {\n\t/* Deafult colors for the editor */\n --primary-background-color: white;\n --primary-background-color-transparent: rgba(255, 255, 255, 0.5);\n --secondary-background-color: #faf;\n --primary-foreground-color: black;\n --secondary-foreground-color: black;\n\t--primary-shadow-color: rgba(0, 0, 0, 0.5);\n}\n\n@media (prefers-color-scheme: dark) {\n\t.imageEditorContainer {\n\t\t--primary-background-color: #151515;\n\t\t--primary-background-color-transparent: rgba(50, 50, 50, 0.5);\n\t\t--secondary-background-color: #607;\n\t\t--primary-foreground-color: white;\n\t\t--secondary-foreground-color: white;\n\t\t--primary-shadow-color: rgba(250, 250, 250, 0.5);\n\t}\n}\n\n.imageEditorContainer {\n\tcolor: var(--primary-foreground-color);\n\tfont-family: system-ui, -apple-system, sans-serif;\n\tbackground-color: var(--primary-background-color);\n\n\tdisplay: flex;\n\tflex-direction: column-reverse;\n}\n\n.imageEditorContainer .imageEditorRenderArea {\n\tdisplay: grid;\n\tgrid-template-columns: 1fr;\n\tflex-grow: 2;\n\tflex-shrink: 1;\n\tmin-height: 100px;\n}\n\n.imageEditorContainer .imageEditorRenderArea canvas {\n\t/* Stack all canvases on top of each other */\n\tgrid-row: 1 / 1;\n\tgrid-column: 1 / 1;\n\ttouch-action: none;\n\n\t/* Fill the container */\n\tbox-sizing: border-box;\n\twidth: 100%;\n\theight: 100%;\n}\n\n.imageEditorContainer .loadingMessage {\n\tposition: fixed;\n\ttext-align: center;\n\tfont-size: 2em;\n\n\tbottom: 0;\n\tleft: 0;\n\tright: 0;\n}\n\n.imageEditorContainer .accessibilityAnnouncement {\n\topacity: 0;\n\twidth: 0;\n\theight: 0;\n\toverflow: hidden;\n\tpointer-events: none;\n}\n\n.imageEditorContainer .textRendererOutputContainer {\n\twidth: 1px;\n\theight: 1px;\n\toverflow: hidden;\n}\n\n.imageEditorContainer .textRendererOutputContainer:focus-within {\n\toverflow: visible;\n}\n",""]);const c=l},771:(t,e,n)=>{n.d(e,{Z:()=>a});var r=n(81),i=n.n(r),o=n(645),s=n.n(o)()(i());s.push([t.id,".toolbar-root {\n\tbackground-color: var(--primary-background-color);\n\t--icon-color: var(--primary-foreground-color);\n\n\n\tborder: 1px solid var(--secondary-background-color);\n\tborder-radius: 2px;\n\tflex-wrap: wrap;\n\n\tbox-sizing: border-box;\n\twidth: 100%;\n\n\tdisplay: flex;\n\tflex-direction: row;\n\tjustify-content: center;\n\n\t/* Display above selection dialogs, etc. */\n\tz-index: 2;\n\n\tfont-family: system-ui, -apple-system, sans-serif;\n}\n\n.toolbar-root > .toolbar-toolContainer > .toolbar-button,\n.toolbar-root > .toolbar-toolContainer > * > button,\n.toolbar-root > .toolbar-buttonGroup > button,\n.toolbar-root > .toolbar-button {\n\twidth: min-content;\n\twhite-space: pre;\n\theight: min(20vh, 60px);\n}\n\n.toolbar-dropdown .toolbar-button > .toolbar-icon {\n\tmax-width: 50px;\n}\n\n.toolbar-button.disabled {\n\tfilter: opacity(0.8) saturate(0.1);\n}\n\n.toolbar-button, .toolbar-root button {\n\tcursor: pointer;\n\ttext-align: center;\n\tborder-radius: 6px;\n\n\t--icon-color: var(--primary-foreground-color);\n\tbackground-color: var(--primary-background-color);\n\tcolor: var(--primary-foreground-color);\n\tborder: none;\n\tbox-shadow: 0px 0px 2px var(--primary-shadow-color);\n\n\ttransition: background-color 0.25s ease, box-shadow 0.25s ease, opacity 0.3s ease;\n}\n\n.toolbar-button,\n.toolbar-buttonGroup > button,\n.toolbar-toolContainer > * > button,\n.toolbar-root > button {\n\tdisplay: flex;\n\tflex-direction: column;\n\talign-items: center;\n\tjustify-content: center;\n\n\tpadding-left: 3px;\n\tpadding-right: 3px;\n\tmargin-left: 3px;\n\tmargin-right: 3px;\n\n\tmin-width: 40px;\n\twidth: min-content;\n\tfont-size: 1em;\n}\n\n.toolbar-dropdown > .toolbar-toolContainer > button,\n.toolbar-dropdown > .toolbar-toolContainer > .toolbar-button {\n\twidth: 6em;\n}\n\n.toolbar-button:hover, .toolbar-root button:not(:disabled):hover {\n\tbox-shadow: 0px 2px 4px var(--primary-shadow-color);\n}\n\n.toolbar-root button:disabled {\n\tcursor: inherit;\n\tfilter: opacity(0.5);\n}\n\n.toolbar-root .toolbar-icon {\n\tflex-shrink: 1;\n\tmin-width: 30px;\n\tmin-height: 30px;\n}\n\n.toolbar-toolContainer.selected > .toolbar-button {\n\tbackground-color: var(--secondary-background-color);\n\tcolor: var(--secondary-foreground-color);\n\t--icon-color: var(--secondary-foreground-color);\n}\n\n.toolbar-toolContainer:not(.selected):not(.dropdownShowable) > .toolbar-button > .toolbar-showHideDropdownIcon {\n\tdisplay: none;\n}\n\n.toolbar-toolContainer > .toolbar-button > .toolbar-showHideDropdownIcon {\n\theight: 10px;\n\ttransition: transform 0.5s ease;\n}\n\n.toolbar-toolContainer.dropdownVisible > .toolbar-button > .toolbar-showHideDropdownIcon {\n\ttransform: rotate(180deg);\n}\n\n.toolbar-dropdown.hidden,\n.toolbar-toolContainer:not(.selected):not(.dropdownShowable) > .toolbar-dropdown {\n\tdisplay: none;\n}\n\n.toolbar-dropdown {\n\tposition: absolute;\n\tpadding: 15px;\n\tpadding-top: 5px;\n\n\t/* Prevent overlap/being displayed under the undo/redo buttons */\n\tz-index: 2;\n\tbackground-color: var(--primary-background-color);\n\tbox-shadow: 0px 3px 3px var(--primary-shadow-color);\n}\n\n.toolbar-buttonGroup {\n\tdisplay: flex;\n\tflex-direction: row;\n\tjustify-content: center;\n}\n\n.toolbar-closeColorPickerOverlay {\n\tdisplay: none;\n\tposition: fixed;\n\ttop: 0;\n\tleft: 0;\n\tbottom: 0;\n\tright: 0;\n\n\tbackground-color: var(--primary-background-color);\n\topacity: 0.3;\n}\n\n/* Make color selection buttons fill their containing label */\n.toolbar-dropdown .clr-field button {\n\twidth: 100%;\n\theight: 100%;\n\tborder-radius: 2px;\n\tmargin-left: 0;\n\tmargin-right: 0;\n}\n\n.toolbar-root .toolbar-zoomLevelEditor {\n\tdisplay: flex;\n\tflex-direction: row;\n}\n\n.toolbar-root .toolbar-zoomLevelEditor .zoomDisplay {\n\tflex-grow: 1;\n}\n\n.toolbar-root .toolbar-zoomLevelEditor button {\n\tmin-width: 48px;\n}\n\n.color-input-container {\n\tdisplay: inline-flex;\n\tflex-direction: row;\n}\n\n.color-input-container .pipetteButton {\n\twidth: 30px;\n\theight: 30px;\n\tpadding: 0;\n\tdisplay: inline-flex;\n}\n\n.color-input-container .pipetteButton > svg {\n\twidth: 100%;\n}\n\n.color-input-container .pipetteButton.active {\n\tbackground-color: var(--secondary-background-color);\n\t--icon-color: var(--secondary-foreground-color);\n}\n",""]);const a=s},645:t=>{t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var n="",r=void 0!==e[5];return e[4]&&(n+="@supports (".concat(e[4],") {")),e[2]&&(n+="@media ".concat(e[2]," {")),r&&(n+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),n+=t(e),r&&(n+="}"),e[2]&&(n+="}"),e[4]&&(n+="}"),n})).join("")},e.i=function(t,n,r,i,o){"string"==typeof t&&(t=[[null,t,void 0]]);var s={};if(r)for(var a=0;a<this.length;a++){var l=this[a][0];null!=l&&(s[l]=!0)}for(var c=0;c<t.length;c++){var h=[].concat(t[c]);r&&s[h[0]]||(void 0!==o&&(void 0===h[5]||(h[1]="@layer".concat(h[5].length>0?" ".concat(h[5]):""," {").concat(h[1],"}")),h[5]=o),n&&(h[2]?(h[1]="@media ".concat(h[2]," {").concat(h[1],"}"),h[2]=n):h[2]=n),i&&(h[4]?(h[1]="@supports (".concat(h[4],") {").concat(h[1],"}"),h[4]=i):h[4]="".concat(i)),e.push(h))}},e}},81:t=>{t.exports=function(t){return t[1]}},379:t=>{var e=[];function n(t){for(var n=-1,r=0;r<e.length;r++)if(e[r].identifier===t){n=r;break}return n}function r(t,r){for(var o={},s=[],a=0;a<t.length;a++){var l=t[a],c=r.base?l[0]+r.base:l[0],h=o[c]||0,d="".concat(c," ").concat(h);o[c]=h+1;var u=n(d),p={css:l[1],media:l[2],sourceMap:l[3],supports:l[4],layer:l[5]};if(-1!==u)e[u].references++,e[u].updater(p);else{var m=i(p,r);r.byIndex=a,e.splice(a,0,{identifier:d,updater:m,references:1})}s.push(d)}return s}function i(t,e){var n=e.domAPI(e);n.update(t);return function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap&&e.supports===t.supports&&e.layer===t.layer)return;n.update(t=e)}else n.remove()}}t.exports=function(t,i){var o=r(t=t||[],i=i||{});return function(t){t=t||[];for(var s=0;s<o.length;s++){var a=n(o[s]);e[a].references--}for(var l=r(t,i),c=0;c<o.length;c++){var h=n(o[c]);0===e[h].references&&(e[h].updater(),e.splice(h,1))}o=l}}},569:t=>{var e={};t.exports=function(t,n){var r=function(t){if(void 0===e[t]){var n=document.querySelector(t);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(t){n=null}e[t]=n}return e[t]}(t);if(!r)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");r.appendChild(n)}},216:t=>{t.exports=function(t){var e=document.createElement("style");return t.setAttributes(e,t.attributes),t.insert(e,t.options),e}},565:(t,e,n)=>{t.exports=function(t){var e=n.nc;e&&t.setAttribute("nonce",e)}},795:t=>{t.exports=function(t){var e=t.insertStyleElement(t);return{update:function(n){!function(t,e,n){var r="";n.supports&&(r+="@supports (".concat(n.supports,") {")),n.media&&(r+="@media ".concat(n.media," {"));var i=void 0!==n.layer;i&&(r+="@layer".concat(n.layer.length>0?" ".concat(n.layer):""," {")),r+=n.css,i&&(r+="}"),n.media&&(r+="}"),n.supports&&(r+="}");var o=n.sourceMap;o&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),e.styleTagTransform(r,t,e.options)}(e,t,n)},remove:function(){!function(t){if(null===t.parentNode)return!1;t.parentNode.removeChild(t)}(e)}}}},589:t=>{t.exports=function(t,e){if(e.styleSheet)e.styleSheet.cssText=t;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(t))}}}},n={};function r(t){var i=n[t];if(void 0!==i)return i.exports;var o=n[t]={id:t,exports:{}};return e[t](o,o.exports,r),o.exports}r.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return r.d(e,{a:e}),e},r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.nc=void 0;var i={};(()=>{r.r(i),r.d(i,{AbstractComponent:()=>z,ActionButtonWidget:()=>un,BaseTool:()=>G,BaseToolWidget:()=>cn,BaseWidget:()=>ln,Color4:()=>Et,Command:()=>w,Duplicate:()=>Nt,Editor:()=>On,EditorEventType:()=>D,EditorImage:()=>I,Erase:()=>Ot,EraserTool:()=>$t,EraserToolWidget:()=>dn,HTMLToolbar:()=>bn,HandToolWidget:()=>xn,ImageComponent:()=>Ft,InputEvtType:()=>M,LineSegment2:()=>B,Mat33:()=>P,PanZoomMode:()=>_,PanZoomTool:()=>Z,PasteHandler:()=>be,Path:()=>St,PenTool:()=>Lt,PenToolWidget:()=>hn,Pointer:()=>$,PointerDevice:()=>O,Rect2:()=>R,SelectionTool:()=>se,SelectionToolWidget:()=>pn,SerializableCommand:()=>T,Stroke:()=>Rt,StrokeComponent:()=>Rt,Text:()=>Ht,TextComponent:()=>Ht,TextTool:()=>ce,TextToolWidget:()=>mn,ToolController:()=>ye,ToolEnabledGroup:()=>Mt,ToolSwitcherShortcut:()=>de,UndoRedoShortcut:()=>ae,Vec2:()=>k,Vec3:()=>C,default:()=>$n,defaultEditorLocalization:()=>An,getLocalizationTable:()=>Mn,icons:()=>e,invertCommand:()=>pe,makeColorInput:()=>en,makeFreehandLineBuilder:()=>At,uniteCommands:()=>xe});var e={};r.r(e),r.d(e,{makeAllDevicePanningIcon:()=>je,makeDeleteSelectionIcon:()=>Ze,makeDropdownIcon:()=>Le,makeDuplicateSelectionIcon:()=>_e,makeEraserIcon:()=>Me,makeHandToolIcon:()=>$e,makeIconFromFactory:()=>We,makePenIcon:()=>Ve,makePipetteIcon:()=>He,makeRedoIcon:()=>Ie,makeResizeViewportIcon:()=>Ge,makeSelectionIcon:()=>De,makeTextIcon:()=>Ue,makeTouchPanningIcon:()=>Ne,makeUndoIcon:()=>Ae,makeZoomIcon:()=>Fe});var n=r(379),o=r.n(n),s=r(795),a=r.n(s),l=r(569),c=r.n(l),h=r(565),d=r.n(h),u=r(216),p=r.n(u),m=r(589),f=r.n(m),g=r(59),x={};x.styleTagTransform=f(),x.setAttributes=d(),x.insert=c().bind(null,"head"),x.domAPI=a(),x.insertStyleElement=p();o()(g.Z,x);g.Z&&g.Z.locals&&g.Z.locals;var v=r(786),b={};b.styleTagTransform=f(),b.setAttributes=d(),b.insert=c().bind(null,"head"),b.domAPI=a(),b.insertStyleElement=p();o()(v.Z,b);v.Z&&v.Z.locals&&v.Z.locals;class y{onDrop(t){}static union(t,e){return new class extends y{apply(n){t.apply(n),e.apply(n)}unapply(n){e.unapply(n),t.unapply(n)}description(n,r){const i=t.description(n,r),o=e.description(n,r);return i===o?i:`${i}, ${o}`}}}}y.empty=new class extends y{description(t,e){return""}apply(t){}unapply(t){}};const w=y;class T extends w{constructor(t){if(super(),this.commandTypeId=t,!(t in T.deserializationCallbacks))throw new Error(`Command ${t} must have a registered deserialization callback. To do this, call SerializableCommand.register.`)}serialize(){return{data:this.serializeToJSON(),commandType:this.commandTypeId}}static deserialize(t,e){const n="string"==typeof t?JSON.parse(t):t,r=n.commandType;if(!(r in T.deserializationCallbacks))throw new Error(`Unrecognised command type ${r}!`);return T.deserializationCallbacks[r](n.data,e)}static register(t,e){T.deserializationCallbacks[t]=e}}T.deserializationCallbacks={};class C{constructor(t,e,n){this.x=t,this.y=e,this.z=n}get xy(){return{x:this.x,y:this.y}}static of(t,e,n){return new C(t,e,n)}at(t){if(0===t)return this.x;if(1===t)return this.y;if(2===t)return this.z;throw new Error(`${t} out of bounds!`)}length(){return this.magnitude()}magnitude(){return Math.sqrt(this.dot(this))}magnitudeSquared(){return this.dot(this)}angle(){return Math.atan2(this.y,this.x)}normalized(){const t=this.magnitude();return C.of(this.x/t,this.y/t,this.z/t)}times(t){return C.of(this.x*t,this.y*t,this.z*t)}plus(t){return C.of(this.x+t.x,this.y+t.y,this.z+t.z)}minus(t){return this.plus(t.times(-1))}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}cross(t){return C.of(this.y*t.z-t.y*this.z,t.x*this.z-this.x*t.z,this.x*t.y-t.x*this.y)}orthog(){return 0===this.dot(C.unitX)&&0===this.dot(C.unitY)?0===this.dot(C.unitX)?C.unitX:this.cross(C.unitX).normalized():this.cross(C.unitZ.times(-1)).normalized()}extend(t,e){return this.plus(e.normalized().times(t))}lerp(t,e){return this.times(1-e).plus(t.times(e))}zip(t,e){return C.of(e(t.x,this.x),e(t.y,this.y),e(t.z,this.z))}map(t){return C.of(t(this.x,0),t(this.y,1),t(this.z,2))}asArray(){return[this.x,this.y,this.z]}eq(t,e){for(let n=0;n<3;n++)if(Math.abs(t.at(n)-this.at(n))>e)return!1;return!0}toString(){return`Vec(${this.x}, ${this.y}, ${this.z})`}}var k,S,E;C.unitX=C.of(1,0,0),C.unitY=C.of(0,1,0),C.unitZ=C.of(0,0,1),C.zero=C.of(0,0,0),function(t){t.of=(t,e)=>C.of(t,e,0),t.ofXY=({x:t,y:e})=>C.of(t,e,0),t.unitX=t.of(1,0),t.unitY=t.of(0,1),t.zero=t.of(0,0)}(k||(k={}));class P{constructor(t,e,n,r,i,o,s,a,l){this.a1=t,this.a2=e,this.a3=n,this.b1=r,this.b2=i,this.b3=o,this.c1=s,this.c2=a,this.c3=l,this.cachedInverse=void 0,this.rows=[C.of(t,e,n),C.of(r,i,o),C.of(s,a,l)]}static ofRows(t,e,n){return new P(t.x,t.y,t.z,e.x,e.y,e.z,n.x,n.y,n.z)}inverse(){var t;return null!==(t=this.computeInverse())&&void 0!==t?t:P.identity}invertable(){return null!==this.computeInverse()}computeInverse(){if(void 0!==this.cachedInverse)return this.cachedInverse;const t=[this.rows[0],this.rows[1],this.rows[2]],e=[C.unitX,C.unitY,C.unitZ];for(let n=0;n<3;n++){let r=t[n].at(n);const i=1e-10;if(Math.abs(r)<i){let o=-1;for(let e=1;e<=2;e++){const r=(n+e)%3;if(Math.abs(t[r].at(n))>=i){o=r;break}}if(-1===o)return this.cachedInverse=null,null;const s=t[n],a=e[n];t[n]=t[o],e[n]=e[o],t[o]=s,e[o]=a,r=t[n].at(n)}let o=1/r;t[n]=t[n].times(o),e[n]=e[n].times(o);const s=t[n],a=e[n];for(let r=1;r<=2;r++){const i=(n+r)%3;o=-t[i].at(n),t[i]=t[i].plus(s.times(o)),e[i]=e[i].plus(a.times(o))}}const n=P.ofRows(e[0],e[1],e[2]);return this.cachedInverse=n,n}transposed(){return new P(this.a1,this.b1,this.c1,this.a2,this.b2,this.c2,this.a3,this.b3,this.c3)}rightMul(t){t=t.transposed();const e=(e,n)=>this.rows[e].dot(t.rows[n]);return new P(e(0,0),e(0,1),e(0,2),e(1,0),e(1,1),e(1,2),e(2,0),e(2,1),e(2,2))}transformVec2(t){let e=C.of(t.x,t.y,1);return e=this.transformVec3(e),k.of(e.x,e.y)}transformVec3(t){return C.of(this.rows[0].dot(t),this.rows[1].dot(t),this.rows[2].dot(t))}eq(t,e=0){for(let n=0;n<3;n++)if(!this.rows[n].eq(t.rows[n],e))return!1;return!0}toString(){return`\n⎡ ${this.a1},\t ${this.a2},\t ${this.a3}\t ⎤\n⎢ ${this.b1},\t ${this.b2},\t ${this.b3}\t ⎥\n⎣ ${this.c1},\t ${this.c2},\t ${this.c3}\t ⎦\n\t\t`.trimEnd().trimStart()}toArray(){return[this.a1,this.a2,this.a3,this.b1,this.b2,this.b3,this.c1,this.c2,this.c3]}static translation(t){return new P(1,0,t.x,0,1,t.y,0,0,1)}static zRotation(t,e=k.zero){const n=Math.cos(t),r=Math.sin(t);let i=P.translation(e);return i=i.rightMul(new P(n,-r,0,r,n,0,0,0,1)),i.rightMul(P.translation(e.times(-1)))}static scaling2D(t,e=k.zero){let n,r,i=P.translation(e);return"number"==typeof t?(n=t,r=t):(n=t.x,r=t.y),i=i.rightMul(new P(n,0,0,0,r,0,0,0,1)),i.rightMul(P.translation(e.times(-1)))}static fromCSSMatrix(t){if(""===t||"none"===t)return P.identity;const e="([-]?\\d*(?:\\.\\d*)?(?:[eE][-]?\\d+)?)",n=`^\\s*matrix\\s*\\(${[e,e,e,e,e,e].join("[, \\t\\n]+")}[, \\t\\n]*\\)\\s*$`,r=new RegExp(n,"i").exec(t);if(!r)throw new Error(`Unsupported transformation: ${t}`);const i=r.slice(1).map((t=>parseFloat(t))),o=i[0],s=i[1],a=i[2],l=i[3],c=i[4],h=i[5];return new P(o,a,c,s,l,h,0,0,1)}}P.identity=new P(1,0,0,0,1,0,0,0,1);class z{constructor(t){if(this.componentKind=t,this.loadSaveData={},this.lastChangedTime=(new Date).getTime(),this.zIndex=z.zIndexCounter++,this.id=`${(new Date).getTime()}-${Math.random()}`,void 0===z.deserializationCallbacks[t])throw new Error(`Component ${t} has not been registered using AbstractComponent.registerComponent`)}getId(){return this.id}static registerComponent(t,e){this.deserializationCallbacks[t]=null!=e?e:null}attachLoadSaveData(t,e){this.loadSaveData[t]||(this.loadSaveData[t]=[]),this.loadSaveData[t].push(e)}getLoadSaveData(){return this.loadSaveData}getZIndex(){return this.zIndex}getBBox(){return this.contentBBox}transformBy(t){return new z.TransformElementCommand(t,this)}clone(){const t=this.createClone();for(const e in this.loadSaveData)for(const n of this.loadSaveData[e])t.attachLoadSaveData(e,n);return t}serialize(){const t=this.serializeToJSON();if(null===t)throw new Error(`${this} cannot be serialized.`);return{name:this.componentKind,zIndex:this.zIndex,id:this.id,loadSaveData:this.loadSaveData,data:t}}static isNotDeserializable(t){return"string"==typeof t&&(t=JSON.parse(t)),"object"!=typeof t||(!this.deserializationCallbacks[null==t?void 0:t.name]||!t.data)}static deserialize(t){if("string"==typeof t&&(t=JSON.parse(t)),z.isNotDeserializable(t))throw new Error(`Element with data ${t} cannot be deserialized.`);const e=this.deserializationCallbacks[t.name](t.data);return e.zIndex=t.zIndex,e.id=t.id,e}}z.zIndexCounter=0,z.deserializationCallbacks={},z.transformElementCommandId="transform-element",z.UnresolvedTransformElementCommand=class extends T{constructor(t,e){super(z.transformElementCommandId),this.affineTransfm=t,this.componentID=e,this.command=null}resolveCommand(t){if(this.command)return;const e=t.image.lookupElement(this.componentID);if(!e)throw new Error(`Unable to resolve component with ID ${this.componentID}`);this.command=new z.TransformElementCommand(this.affineTransfm,e)}apply(t){this.resolveCommand(t),this.command.apply(t)}unapply(t){this.resolveCommand(t),this.command.unapply(t)}description(t,e){return e.transformedElements(1)}serializeToJSON(){return{id:this.componentID,transfm:this.affineTransfm.toArray()}}},z.TransformElementCommand=(S=class extends T{constructor(t,e){super(z.transformElementCommandId),this.affineTransfm=t,this.component=e,this.origZIndex=e.zIndex}updateTransform(t,e){const n=t.image.findParent(this.component);let r=!1;n&&(n.remove(),r=!0),this.component.applyTransformation(e),r&&I.addElement(this.component).apply(t)}apply(t){this.component.zIndex=z.zIndexCounter++,this.updateTransform(t,this.affineTransfm),t.queueRerender()}unapply(t){this.component.zIndex=this.origZIndex,this.updateTransform(t,this.affineTransfm.inverse()),t.queueRerender()}description(t,e){return e.transformedElements(1)}serializeToJSON(){return{id:this.component.getId(),transfm:this.affineTransfm.toArray()}}},T.register(z.transformElementCommandId,((t,e)=>{const n=e.image.lookupElement(t.id),r=new P(...t.transfm);return n?new z.TransformElementCommand(r,n):new z.UnresolvedTransformElementCommand(r,t.id)})),S);class B{constructor(t,e){this.point1=t,this.point2=e,this.bbox=R.bboxOf([t,e]),this.direction=e.minus(t),this.length=this.direction.magnitude(),this.length>0&&(this.direction=this.direction.times(1/this.length))}get p1(){return this.point1}get p2(){return this.point2}get(t){return this.point1.plus(this.direction.times(t))}intersection(t){let e,n;if(0===this.direction.x){if(0===t.direction.x||0===this.direction.y)return null;const r=this.point1.x,i=(this.point1.x-t.point1.x)*t.direction.y/t.direction.x+t.point1.y;e=k.of(r,i),n=(i-this.point1.y)/this.direction.y}else{const r=(this.point1.y-t.point1.y)*this.direction.x*t.direction.x+this.direction.x*t.direction.y*t.point1.x-this.direction.y*t.direction.x*this.point1.x,i=t.direction.y*this.direction.x-this.direction.y*t.direction.x;if(0===i)return null;const o=r/i,s=(o-this.point1.x)/this.direction.x,a=this.point1.y+this.direction.y*s;e=k.of(o,a),n=(o-this.point1.x)/this.direction.x}const r=e.minus(this.point1).magnitude(),i=e.minus(this.point2).magnitude(),o=e.minus(t.point1).magnitude(),s=e.minus(t.point2).magnitude();return r>this.length||i>this.length||o>t.length||s>t.length?null:{point:e,t:n}}intersects(t){return null!==this.intersection(t)}closestPointTo(t){const e=t.minus(this.p1).dot(this.direction),n=this.length-e,r=this.p1.plus(this.direction.times(e));return e>0&&e<this.length?r:Math.abs(n)<Math.abs(e)?this.p2:this.p1}transformedBy(t){return new B(t.transformVec2(this.p1),t.transformVec2(this.p2))}toString(){return`LineSegment(${this.p1.toString()}, ${this.p2.toString()})`}}class R{constructor(t,e,n,r){this.x=t,this.y=e,this.w=n,this.h=r,n<0&&(this.x+=n,this.w=Math.abs(n)),r<0&&(this.y+=r,this.h=Math.abs(r)),this.topLeft=k.of(this.x,this.y),this.size=k.of(this.w,this.h),this.bottomRight=this.topLeft.plus(this.size),this.center=this.topLeft.plus(this.size.times(.5)),this.area=this.w*this.h}translatedBy(t){return new R(t.x+this.x,t.y+this.y,this.w,this.h)}resizedTo(t){return new R(this.x,this.y,t.x,t.y)}containsPoint(t){return this.x<=t.x&&this.y<=t.y&&this.x+this.w>=t.x&&this.y+this.h>=t.y}containsRect(t){return this.x<=t.x&&this.y<=t.y&&this.bottomRight.x>=t.bottomRight.x&&this.bottomRight.y>=t.bottomRight.y}intersects(t){const e=this.x,n=e+this.w,r=t.x,i=t.x+t.w;if(n<r||e>i)return!1;const o=this.y,s=o+this.h,a=t.y,l=t.y+t.h;return!(s<a||o>l)}intersection(t){if(!this.intersects(t))return null;const e=this.topLeft.zip(t.topLeft,Math.max),n=this.bottomRight.zip(t.bottomRight,Math.min);return R.fromCorners(e,n)}union(t){const e=this.topLeft.zip(t.topLeft,Math.min),n=this.bottomRight.zip(t.bottomRight,Math.max);return R.fromCorners(e,n)}divideIntoGrid(t,e){const n=[];if(t<=0||e<=0)return n;const r=this.w/t,i=this.h/e;0===r&&(t=1),0===i&&(e=1);for(let o=0;o<e;o++)for(let e=0;e<t;e++){const t=r*e+this.x,s=i*o+this.y;n.push(new R(t,s,r,i))}return n}grownToPoint(t,e=0){const n=new R(t.x-e,t.y-e,2*e,2*e);return this.union(n)}grownBy(t){return new R(this.x-t,this.y-t,this.w+2*t,this.h+2*t)}getClosestPointOnBoundaryTo(t){const e=this.getEdges().map((e=>e.closestPointTo(t)));let n=null,r=null;for(const i of e){const e=i.minus(t).length();(null===r||e<r)&&(n=i,r=e)}return n}get corners(){return[this.bottomRight,this.topRight,this.topLeft,this.bottomLeft]}get maxDimension(){return Math.max(this.w,this.h)}get topRight(){return this.bottomRight.plus(k.of(0,-this.h))}get bottomLeft(){return this.topLeft.plus(k.of(0,this.h))}get width(){return this.w}get height(){return this.h}getEdges(){const t=this.corners;return[new B(t[0],t[1]),new B(t[1],t[2]),new B(t[2],t[3]),new B(t[3],t[0])]}transformedBoundingBox(t){return R.bboxOf(this.corners.map((e=>t.transformVec2(e))))}eq(t,e=0){return this.topLeft.eq(t.topLeft,e)&&this.size.eq(t.size,e)}toString(){return`Rect(point(${this.x}, ${this.y}), size(${this.w}, ${this.h}))`}static fromCorners(t,e){return new R(Math.min(t.x,e.x),Math.min(t.y,e.y),Math.abs(t.x-e.x),Math.abs(t.y-e.y))}static bboxOf(t,e=0){let n=0,r=0,i=0,o=0,s=!0;for(const e of t)s&&(n=e.x,r=e.y,i=e.x,o=e.y,s=!1),n=Math.min(n,e.x),r=Math.min(r,e.y),i=Math.max(i,e.x),o=Math.max(o,e.y);return R.fromCorners(k.of(n-e,r-e),k.of(i+e,o+e))}static of(t){var e,n,r,i;const o=null!==(n=null!==(e=t.width)&&void 0!==e?e:t.w)&&void 0!==n?n:0,s=null!==(i=null!==(r=t.height)&&void 0!==r?r:t.h)&&void 0!==i?i:0;return new R(t.x,t.y,o,s)}}R.empty=new R(0,0,0,0),R.unitSquare=new R(0,0,1,1);const A=t=>{t.sort(((t,e)=>t.getContent().getZIndex()-e.getContent().getZIndex()))};class I{constructor(){this.root=new L,this.componentsById={}}findParent(t){const e=this.root.getLeavesIntersectingRegion(t.getBBox());for(const n of e)if(n.getContent()===t)return n;return null}renderWithCache(t,e,n){e.render(t,this.root,n)}render(t,e){this.root.render(t,e.visibleRect)}renderAll(t){const e=this.root.getLeaves();A(e);for(const n of e)n.getContent().render(t,n.getBBox())}getElementsIntersectingRegion(t){const e=this.root.getLeavesIntersectingRegion(t);return A(e),e.map((t=>t.getContent()))}onDestroyElement(t){delete this.componentsById[t.getId()]}lookupElement(t){var e;return null!==(e=this.componentsById[t])&&void 0!==e?e:null}addElementDirectly(t){return this.componentsById[t.getId()]=t,this.root.addLeaf(t)}static addElement(t,e=!1){return new I.AddElementCommand(t,e)}}I.AddElementCommand=(E=class extends T{constructor(t,e=!1){if(super("add-element"),this.element=t,this.applyByFlattening=e,this.serializedElem=t.serialize(),isNaN(t.getBBox().area))throw new Error("Elements in the image cannot have NaN bounding boxes")}apply(t){t.image.addElementDirectly(this.element),this.applyByFlattening?(this.applyByFlattening=!1,t.display.flatten()):t.queueRerender()}unapply(t){const e=t.image.findParent(this.element);null==e||e.remove(),t.queueRerender()}description(t,e){return e.addElementAction(this.element.description(e))}serializeToJSON(){return{elemData:this.serializedElem}}},T.register("add-element",((t,e)=>{const n=t.elemData.id,r=e.image.lookupElement(n),i=null!=r?r:z.deserialize(t.elemData);return new I.AddElementCommand(i)})),E);class L{constructor(t=null){this.parent=t,this.targetChildCount=30,this.children=[],this.bbox=R.empty,this.content=null,this.id=L.idCounter++}getId(){return this.id}onContentChange(){this.id=L.idCounter++}getContent(){return this.content}getParent(){return this.parent}getChildrenIntersectingRegion(t){return this.children.filter((e=>e.getBBox().intersects(t)))}getChildrenOrSelfIntersectingRegion(t){return this.content?[this]:this.getChildrenIntersectingRegion(t)}getLeavesIntersectingRegion(t,e){const n=[];let r;const i=[];i.push(this);const o=()=>{r=void 0;const o=i.pop();o&&!(null==e?void 0:e(o.bbox))&&(r=o,null!==r.content&&r.getBBox().intersection(t)&&n.push(r),i.push(...r.getChildrenIntersectingRegion(t)))};for(;i.length>0;)o();return n}getLeaves(){if(this.content)return[this];const t=[];for(const e of this.children)t.push(...e.getLeaves());return t}addLeaf(t){if(this.onContentChange(),null===this.content&&0===this.children.length)return this.content=t,this.recomputeBBox(!0),this;if(null!==this.content){console.assert(0===this.children.length);const t=new L(this);t.content=this.content,this.content=null,this.children.push(t),t.recomputeBBox(!1)}const e=t.getBBox();if(e.containsRect(this.getBBox())){const e=new L(this);if(this.children.length<this.targetChildCount)this.children.push(e);else{const t=new L(this);t.children=this.children,this.children=[e,t],t.recomputeBBox(!0),t.updateParents()}return e.addLeaf(t)}const n=this.children.filter((t=>t.getBBox().containsRect(e)));if(n.length>0&&this.children.length>=this.targetChildCount){n.sort(((t,e)=>t.getBBox().area-e.getBBox().area));const e=n[0].addLeaf(t);return e.rebalance(),e}const r=new L(this);return this.children.push(r),r.content=t,r.recomputeBBox(!0),r}getBBox(){return this.bbox}recomputeBBox(t){var e;const n=this.bbox;if(null!==this.content)this.bbox=this.content.getBBox();else{this.bbox=R.empty;let t=!0;for(const e of this.children)t?(this.bbox=e.getBBox(),t=!1):this.bbox=this.bbox.union(e.getBBox())}t&&!n.eq(this.bbox)&&(null===(e=this.parent)||void 0===e||e.recomputeBBox(!0))}updateParents(t=!1){for(const e of this.children)e.parent=this,t&&e.updateParents(t)}rebalance(){if(this.parent&&1===this.parent.children.length){console.assert(null===this.parent.content),console.assert(this.parent.children[0]===this);const t=this.parent;null!==t.parent?(t.children=[],this.parent=t.parent,this.parent.children.push(this),t.parent=null,this.parent.recomputeBBox(!1)):null===this.content&&(this.parent.children=this.children,this.parent.updateParents(),this.parent=null)}}remove(){if(!this.parent)return this.content=null,void(this.children=[]);const t=this.parent.children.length;this.parent.children=this.parent.children.filter((t=>t!==this)),console.assert(this.parent.children.length===t-1,`${t-1} ≠ ${this.parent.children.length} after removing all nodes equal to ${this}. Nodes should only be removed once.`),this.parent.children.forEach((t=>{t.rebalance()})),this.parent.recomputeBBox(!0),this.content=null,this.parent=null,this.children=[]}render(t,e){const n=this.getLeavesIntersectingRegion(e,(e=>t.isTooSmallToRender(e)));A(n);for(const r of n)r.getContent().render(t,e)}}var M,D,O;L.idCounter=0,function(t){t[t.PointerDownEvt=0]="PointerDownEvt",t[t.PointerMoveEvt=1]="PointerMoveEvt",t[t.PointerUpEvt=2]="PointerUpEvt",t[t.GestureCancelEvt=3]="GestureCancelEvt",t[t.WheelEvt=4]="WheelEvt",t[t.KeyPressEvent=5]="KeyPressEvent",t[t.KeyUpEvent=6]="KeyUpEvent",t[t.CopyEvent=7]="CopyEvent",t[t.PasteEvent=8]="PasteEvent"}(M||(M={})),function(t){t[t.ToolEnabled=0]="ToolEnabled",t[t.ToolDisabled=1]="ToolDisabled",t[t.ToolUpdated=2]="ToolUpdated",t[t.UndoRedoStackUpdated=3]="UndoRedoStackUpdated",t[t.CommandDone=4]="CommandDone",t[t.CommandUndone=5]="CommandUndone",t[t.ObjectAdded=6]="ObjectAdded",t[t.ViewportChanged=7]="ViewportChanged",t[t.DisplayResized=8]="DisplayResized",t[t.ColorPickerToggled=9]="ColorPickerToggled",t[t.ColorPickerColorSelected=10]="ColorPickerColorSelected",t[t.ToolbarDropdownShown=11]="ToolbarDropdownShown"}(D||(D={})),function(t){t[t.Pen=0]="Pen",t[t.Eraser=1]="Eraser",t[t.Touch=2]="Touch",t[t.PrimaryButtonMouse=3]="PrimaryButtonMouse",t[t.RightButtonMouse=4]="RightButtonMouse",t[t.Other=5]="Other"}(O||(O={}));class ${constructor(t,e,n,r,i,o,s,a){this.screenPos=t,this.canvasPos=e,this.pressure=n,this.isPrimary=r,this.down=i,this.device=o,this.id=s,this.timeStamp=a}static ofEvent(t,e,n){var r,i;const o=k.of(t.offsetX,t.offsetY);let s=null!==(r={mouse:O.PrimaryButtonMouse,pen:O.Pen,touch:O.Touch}[t.pointerType])&&void 0!==r?r:O.Other;s===O.Pen&&0!=(32&t.buttons)&&(s=O.Eraser);const a=(new Date).getTime(),l=n.roundPoint(n.screenToCanvas(o));return s===O.PrimaryButtonMouse&&(2&t.buttons?s=O.RightButtonMouse:1&t.buttons||(s=O.Other)),new $(o,l,null!==(i=t.pressure)&&void 0!==i?i:null,t.isPrimary,e,s,t.pointerId,a)}static ofCanvasPoint(t,e,n,r=0,i=O.Pen,o=!0,s=null){const a=n.canvasToScreen(t),l=(new Date).getTime();return new $(a,t,s,o,e,i,r,l)}}var N,j,F=function(t,e,n,r,i){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?i.call(t,n):i?i.value=n:e.set(t,n),n},U=function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)};class V extends w{}class W{constructor(t){this.notifier=t,this.resetTransform(P.identity),this.screenRect=R.empty}updateScreenSize(t){this.screenRect=this.screenRect.resizedTo(t)}get visibleRect(){return this.screenRect.transformedBoundingBox(this.inverseTransform)}screenToCanvas(t){return this.inverseTransform.transformVec2(t)}canvasToScreen(t){return this.transform.transformVec2(t)}static transformBy(t){return new W.ViewportTransform(t)}resetTransform(t=P.identity){const e=this.transform;this.transform=t,this.inverseTransform=t.inverse(),this.notifier.dispatch(D.ViewportChanged,{kind:D.ViewportChanged,newTransform:t,oldTransform:e})}get screenToCanvasTransform(){return this.inverseTransform}get canvasToScreenTransform(){return this.transform}getResolution(){return this.screenRect.size}getScaleFactor(){return this.transform.transformVec3(C.unitX).magnitude()}getSizeOfPixelOnCanvas(){return 1/this.getScaleFactor()}getRotationAngle(){return this.transform.transformVec3(C.unitX).angle()}static roundPoint(t,e){const n=Math.pow(10,Math.floor(Math.log10(e))),r=t=>Math.round(t/n)*n;return"number"==typeof t?r(t):t.map(r)}roundPoint(t){return W.roundPoint(t,1/this.getScaleFactor())}computeZoomToTransform(t,e=!0,n=!0){let r=P.identity;if(0===t.w||0===t.h)throw new Error(`${t.toString()} rectangle is empty! Cannot zoom to!`);if(isNaN(t.size.magnitude()))throw new Error(`${t.toString()} rectangle has NaN size! Cannot zoom to!`);const i=()=>{const t=this.visibleRect.transformedBoundingBox(r.inverse());return t.transformedBoundingBox(P.scaling2D(.8,t.center))};let o=i();const s=o.w<t.w||o.h<t.h,a=t.maxDimension/o.maxDimension<1/3;if(s&&n||a&&e){const e=(s?Math.max:Math.min)(t.w/o.w,t.h/o.h),n=P.scaling2D(e,o.topLeft).inverse();r=r.rightMul(n)}if(o=i(),!o.containsRect(t)){const e=t.center.minus(o.center),n=P.translation(e).inverse();r=r.rightMul(n)}return r.invertable()||(console.warn("Unable to zoom to ",t,"! Computed transform",r,"is singular."),r=P.identity),r}zoomTo(t,e=!0,n=!0){const r=this.computeZoomToTransform(t,e,n);return new W.ViewportTransform(r)}}W.ViewportTransform=(j=class extends V{constructor(t){super(),this.transform=t,N.set(this,void 0),F(this,N,t.inverse(),"f")}apply(t){const e=t.viewport;e.resetTransform(e.transform.rightMul(this.transform)),t.queueRerender()}unapply(t){const e=t.viewport;e.resetTransform(e.transform.rightMul(U(this,N,"f"))),t.queueRerender()}description(t,e){const n=[],r=t.viewport.visibleRect.center,i=this.transform.transformVec3(k.unitX),o=this.transform.transformVec2(r),s=i.magnitude(),a=180/Math.PI*i.angle(),l=o.minus(r);s>1.2?n.push(e.zoomedIn):s<.8&&n.push(e.zoomedOut),Math.floor(Math.abs(a))>0&&n.push(e.rotatedBy(Math.round(a)));const c=1e-4;return l.x>c?n.push(e.movedLeft):l.x<-1e-4&&n.push(e.movedRight),l.y<-1e-4?n.push(e.movedDown):l.y>c&&n.push(e.movedUp),n.join("; ")}},N=new WeakMap,j);const H=W;class G{constructor(t,e){this.notifier=t,this.description=e,this.enabled=!0,this.group=null}onPointerDown(t){return!1}onPointerMove(t){}onPointerUp(t){}onGestureCancel(){}onWheel(t){return!1}onCopy(t){return!1}onPaste(t){return!1}onKeyPress(t){return!1}onKeyUp(t){return!1}setEnabled(t){var e;this.enabled=t,t?(null===(e=this.group)||void 0===e||e.notifyEnabled(this),this.notifier.dispatch(D.ToolEnabled,{kind:D.ToolEnabled,tool:this})):this.notifier.dispatch(D.ToolDisabled,{kind:D.ToolDisabled,tool:this})}isEnabled(){return this.enabled}setToolGroup(t){this.isEnabled()&&t.notifyEnabled(this),this.group=t}getToolGroup(){return this.group?this.group:null}}var _;!function(t){t[t.OneFingerTouchGestures=1]="OneFingerTouchGestures",t[t.TwoFingerTouchGestures=2]="TwoFingerTouchGestures",t[t.RightClickDrags=4]="RightClickDrags",t[t.SinglePointerGestures=8]="SinglePointerGestures",t[t.Keyboard=16]="Keyboard"}(_||(_={}));class Z extends G{constructor(t,e,n){super(t.notifier,n),this.editor=t,this.mode=e,this.transform=null}computePinchData(t,e){const n=e.screenPos.minus(t.screenPos),r=n.angle(),i=n.magnitude();return{canvasCenter:e.canvasPos.plus(t.canvasPos).times(.5),screenCenter:e.screenPos.plus(t.screenPos).times(.5),angle:r,dist:i}}allPointersAreOfType(t,e){return t.every((t=>t.device===e))}onPointerDown({allPointers:t}){var e;let n=!1;const r=this.allPointersAreOfType(t,O.Touch),i=this.allPointersAreOfType(t,O.RightButtonMouse);if(r&&2===t.length&&this.mode&_.TwoFingerTouchGestures){const{screenCenter:e,angle:r,dist:i}=this.computePinchData(t[0],t[1]);this.lastAngle=r,this.lastDist=i,this.lastScreenCenter=e,n=!0}else 1===t.length&&(this.mode&_.OneFingerTouchGestures&&r||i&&this.mode&_.RightClickDrags||this.mode&_.SinglePointerGestures)&&(this.lastScreenCenter=t[0].screenPos,n=!0);return n&&(null!==(e=this.transform)&&void 0!==e||(this.transform=W.transformBy(P.identity)),this.editor.display.setDraftMode(!0)),n}getCenterDelta(t){return this.editor.viewport.screenToCanvasTransform.transformVec3(t.minus(this.lastScreenCenter))}handleTwoFingerMove(t){const{screenCenter:e,canvasCenter:n,angle:r,dist:i}=this.computePinchData(t[0],t[1]),o=this.getCenterDelta(e),s=P.translation(o).rightMul(P.scaling2D(i/this.lastDist,n)).rightMul(P.zRotation(r-this.lastAngle,n));this.lastScreenCenter=e,this.lastDist=i,this.lastAngle=r,this.transform=W.transformBy(this.transform.transform.rightMul(s))}handleOneFingerMove(t){const e=this.getCenterDelta(t.screenPos);this.transform=W.transformBy(this.transform.transform.rightMul(P.translation(e))),this.lastScreenCenter=t.screenPos}onPointerMove({allPointers:t}){var e;null!==(e=this.transform)&&void 0!==e||(this.transform=W.transformBy(P.identity));const n=this.transform;2===t.length?this.handleTwoFingerMove(t):1===t.length&&this.handleOneFingerMove(t[0]),n.unapply(this.editor),this.transform.apply(this.editor)}onPointerUp(t){this.transform&&(this.transform.unapply(this.editor),this.editor.dispatch(this.transform,!1)),this.editor.display.setDraftMode(!1),this.transform=null}onGestureCancel(){var t;null===(t=this.transform)||void 0===t||t.unapply(this.editor),this.editor.display.setDraftMode(!1),this.transform=null}updateTransform(t,e=!1){var n;let r=t;this.transform&&(r=this.transform.transform.rightMul(t)),null===(n=this.transform)||void 0===n||n.unapply(this.editor),this.transform=W.transformBy(r),this.transform.apply(this.editor),e&&this.editor.announceForAccessibility(this.transform.description(this.editor,this.editor.localization))}onWheel({delta:t,screenPos:e}){this.transform=W.transformBy(P.identity);const n=this.editor.viewport.screenToCanvas(e),r=this.editor.viewport.screenToCanvasTransform.transformVec3(C.of(-t.x,-t.y,0)),i=P.scaling2D(Math.max(.25,Math.min(Math.pow(1.04,-t.z),4)),n).rightMul(P.translation(r));return this.updateTransform(i,!0),!0}onKeyPress({key:t}){if(!(this.mode&_.Keyboard))return!1;this.transform=W.transformBy(P.identity);let e=k.zero,n=1,r=0;switch(t){case"a":case"h":case"ArrowLeft":e=k.of(-1,0);break;case"d":case"l":case"ArrowRight":e=k.of(1,0);break;case"q":case"k":case"ArrowUp":e=k.of(0,-1);break;case"e":case"j":case"ArrowDown":e=k.of(0,1);break;case"w":n=.5;break;case"s":n=2;break;case"r":r=1;break;case"R":r=-1;break;default:return!1}e=e.times(30),r*=Math.PI/8,e=e.times(-1),r*=-1,n=1/n,0!==r&&(r+=1e-4);e=this.editor.viewport.screenToCanvasTransform.transformVec3(e);const i=this.editor.viewport.visibleRect.center,o=P.scaling2D(n,i).rightMul(P.zRotation(r,i)).rightMul(P.translation(e));return this.updateTransform(o,!0),!0}setMode(t){t!==this.mode&&(this.mode=t,this.editor.notifier.dispatch(D.ToolUpdated,{kind:D.ToolUpdated,tool:this}))}getMode(){return this.mode}}const{abs:q,cos:K,sin:X,acos:J,atan2:Y,sqrt:Q,pow:tt}=Math;function et(t){return t<0?-tt(-t,1/3):tt(t,1/3)}const nt=Math.PI,rt=2*nt,it=nt/2,ot=Number.MAX_SAFE_INTEGER||9007199254740991,st=Number.MIN_SAFE_INTEGER||-9007199254740991,at={x:0,y:0,z:0},lt={Tvalues:[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213],Cvalues:[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872],arcfn:function(t,e){const n=e(t);let r=n.x*n.x+n.y*n.y;return void 0!==n.z&&(r+=n.z*n.z),Q(r)},compute:function(t,e,n){if(0===t)return e[0].t=0,e[0];const r=e.length-1;if(1===t)return e[r].t=1,e[r];const i=1-t;let o=e;if(0===r)return e[0].t=t,e[0];if(1===r){const e={x:i*o[0].x+t*o[1].x,y:i*o[0].y+t*o[1].y,t};return n&&(e.z=i*o[0].z+t*o[1].z),e}if(r<4){let e,s,a,l=i*i,c=t*t,h=0;2===r?(o=[o[0],o[1],o[2],at],e=l,s=i*t*2,a=c):3===r&&(e=l*i,s=l*t*3,a=i*c*3,h=t*c);const d={x:e*o[0].x+s*o[1].x+a*o[2].x+h*o[3].x,y:e*o[0].y+s*o[1].y+a*o[2].y+h*o[3].y,t};return n&&(d.z=e*o[0].z+s*o[1].z+a*o[2].z+h*o[3].z),d}const s=JSON.parse(JSON.stringify(e));for(;s.length>1;){for(let e=0;e<s.length-1;e++)s[e]={x:s[e].x+(s[e+1].x-s[e].x)*t,y:s[e].y+(s[e+1].y-s[e].y)*t},void 0!==s[e].z&&(s[e]=s[e].z+(s[e+1].z-s[e].z)*t);s.splice(s.length-1,1)}return s[0].t=t,s[0]},computeWithRatios:function(t,e,n,r){const i=1-t,o=n,s=e;let a,l=o[0],c=o[1],h=o[2],d=o[3];return l*=i,c*=t,2===s.length?(a=l+c,{x:(l*s[0].x+c*s[1].x)/a,y:(l*s[0].y+c*s[1].y)/a,z:!!r&&(l*s[0].z+c*s[1].z)/a,t}):(l*=i,c*=2*i,h*=t*t,3===s.length?(a=l+c+h,{x:(l*s[0].x+c*s[1].x+h*s[2].x)/a,y:(l*s[0].y+c*s[1].y+h*s[2].y)/a,z:!!r&&(l*s[0].z+c*s[1].z+h*s[2].z)/a,t}):(l*=i,c*=1.5*i,h*=3*i,d*=t*t*t,4===s.length?(a=l+c+h+d,{x:(l*s[0].x+c*s[1].x+h*s[2].x+d*s[3].x)/a,y:(l*s[0].y+c*s[1].y+h*s[2].y+d*s[3].y)/a,z:!!r&&(l*s[0].z+c*s[1].z+h*s[2].z+d*s[3].z)/a,t}):void 0))},derive:function(t,e){const n=[];for(let r=t,i=r.length,o=i-1;i>1;i--,o--){const t=[];for(let n,i=0;i<o;i++)n={x:o*(r[i+1].x-r[i].x),y:o*(r[i+1].y-r[i].y)},e&&(n.z=o*(r[i+1].z-r[i].z)),t.push(n);n.push(t),r=t}return n},between:function(t,e,n){return e<=t&&t<=n||lt.approximately(t,e)||lt.approximately(t,n)},approximately:function(t,e,n){return q(t-e)<=(n||1e-6)},length:function(t){const e=lt.Tvalues.length;let n=0;for(let r,i=0;i<e;i++)r=.5*lt.Tvalues[i]+.5,n+=lt.Cvalues[i]*lt.arcfn(r,t);return.5*n},map:function(t,e,n,r,i){return r+(i-r)*((t-e)/(n-e))},lerp:function(t,e,n){const r={x:e.x+t*(n.x-e.x),y:e.y+t*(n.y-e.y)};return void 0!==e.z&&void 0!==n.z&&(r.z=e.z+t*(n.z-e.z)),r},pointToString:function(t){let e=t.x+"/"+t.y;return void 0!==t.z&&(e+="/"+t.z),e},pointsToString:function(t){return"["+t.map(lt.pointToString).join(", ")+"]"},copy:function(t){return JSON.parse(JSON.stringify(t))},angle:function(t,e,n){const r=e.x-t.x,i=e.y-t.y,o=n.x-t.x,s=n.y-t.y;return Y(r*s-i*o,r*o+i*s)},round:function(t,e){const n=""+t,r=n.indexOf(".");return parseFloat(n.substring(0,r+1+e))},dist:function(t,e){const n=t.x-e.x,r=t.y-e.y;return Q(n*n+r*r)},closest:function(t,e){let n,r,i=tt(2,63);return t.forEach((function(t,o){r=lt.dist(e,t),r<i&&(i=r,n=o)})),{mdist:i,mpos:n}},abcratio:function(t,e){if(2!==e&&3!==e)return!1;if(void 0===t)t=.5;else if(0===t||1===t)return t;const n=tt(t,e)+tt(1-t,e);return q((n-1)/n)},projectionratio:function(t,e){if(2!==e&&3!==e)return!1;if(void 0===t)t=.5;else if(0===t||1===t)return t;const n=tt(1-t,e);return n/(tt(t,e)+n)},lli8:function(t,e,n,r,i,o,s,a){const l=(t-n)*(o-a)-(e-r)*(i-s);return 0!=l&&{x:((t*r-e*n)*(i-s)-(t-n)*(i*a-o*s))/l,y:((t*r-e*n)*(o-a)-(e-r)*(i*a-o*s))/l}},lli4:function(t,e,n,r){const i=t.x,o=t.y,s=e.x,a=e.y,l=n.x,c=n.y,h=r.x,d=r.y;return lt.lli8(i,o,s,a,l,c,h,d)},lli:function(t,e){return lt.lli4(t,t.c,e,e.c)},makeline:function(t,e){return new vt(t.x,t.y,(t.x+e.x)/2,(t.y+e.y)/2,e.x,e.y)},findbbox:function(t){let e=ot,n=ot,r=st,i=st;return t.forEach((function(t){const o=t.bbox();e>o.x.min&&(e=o.x.min),n>o.y.min&&(n=o.y.min),r<o.x.max&&(r=o.x.max),i<o.y.max&&(i=o.y.max)})),{x:{min:e,mid:(e+r)/2,max:r,size:r-e},y:{min:n,mid:(n+i)/2,max:i,size:i-n}}},shapeintersections:function(t,e,n,r,i){if(!lt.bboxoverlap(e,r))return[];const o=[],s=[t.startcap,t.forward,t.back,t.endcap],a=[n.startcap,n.forward,n.back,n.endcap];return s.forEach((function(e){e.virtual||a.forEach((function(r){if(r.virtual)return;const s=e.intersects(r,i);s.length>0&&(s.c1=e,s.c2=r,s.s1=t,s.s2=n,o.push(s))}))})),o},makeshape:function(t,e,n){const r=e.points.length,i=t.points.length,o=lt.makeline(e.points[r-1],t.points[0]),s=lt.makeline(t.points[i-1],e.points[0]),a={startcap:o,forward:t,back:e,endcap:s,bbox:lt.findbbox([o,t,e,s]),intersections:function(t){return lt.shapeintersections(a,a.bbox,t,t.bbox,n)}};return a},getminmax:function(t,e,n){if(!n)return{min:0,max:0};let r,i,o=ot,s=st;-1===n.indexOf(0)&&(n=[0].concat(n)),-1===n.indexOf(1)&&n.push(1);for(let a=0,l=n.length;a<l;a++)r=n[a],i=t.get(r),i[e]<o&&(o=i[e]),i[e]>s&&(s=i[e]);return{min:o,mid:(o+s)/2,max:s,size:s-o}},align:function(t,e){const n=e.p1.x,r=e.p1.y,i=-Y(e.p2.y-r,e.p2.x-n);return t.map((function(t){return{x:(t.x-n)*K(i)-(t.y-r)*X(i),y:(t.x-n)*X(i)+(t.y-r)*K(i)}}))},roots:function(t,e){e=e||{p1:{x:0,y:0},p2:{x:1,y:0}};const n=t.length-1,r=lt.align(t,e),i=function(t){return 0<=t&&t<=1};if(2===n){const t=r[0].y,e=r[1].y,n=r[2].y,o=t-2*e+n;if(0!==o){const r=-Q(e*e-t*n),s=-t+e;return[-(r+s)/o,-(-r+s)/o].filter(i)}return e!==n&&0===o?[(2*e-n)/(2*e-2*n)].filter(i):[]}const o=r[0].y,s=r[1].y,a=r[2].y;let l=3*s-o-3*a+r[3].y,c=3*o-6*s+3*a,h=-3*o+3*s,d=o;if(lt.approximately(l,0)){if(lt.approximately(c,0))return lt.approximately(h,0)?[]:[-d/h].filter(i);const t=Q(h*h-4*c*d),e=2*c;return[(t-h)/e,(-h-t)/e].filter(i)}c/=l,h/=l,d/=l;const u=(3*h-c*c)/3,p=u/3,m=(2*c*c*c-9*c*h+27*d)/27,f=m/2,g=f*f+p*p*p;let x,v,b,y,w;if(g<0){const t=-u/3,e=Q(t*t*t),n=-m/(2*e),r=J(n<-1?-1:n>1?1:n),o=2*et(e);return b=o*K(r/3)-c/3,y=o*K((r+rt)/3)-c/3,w=o*K((r+2*rt)/3)-c/3,[b,y,w].filter(i)}if(0===g)return x=f<0?et(-f):-et(f),b=2*x-c/3,y=-x-c/3,[b,y].filter(i);{const t=Q(g);return x=et(-f+t),v=et(f+t),[x-v-c/3].filter(i)}},droots:function(t){if(3===t.length){const e=t[0],n=t[1],r=t[2],i=e-2*n+r;if(0!==i){const t=-Q(n*n-e*r),o=-e+n;return[-(t+o)/i,-(-t+o)/i]}return n!==r&&0===i?[(2*n-r)/(2*(n-r))]:[]}if(2===t.length){const e=t[0],n=t[1];return e!==n?[e/(e-n)]:[]}return[]},curvature:function(t,e,n,r,i){let o,s,a,l,c=0,h=0;const d=lt.compute(t,e),u=lt.compute(t,n),p=d.x*d.x+d.y*d.y;if(r?(o=Q(tt(d.y*u.z-u.y*d.z,2)+tt(d.z*u.x-u.z*d.x,2)+tt(d.x*u.y-u.x*d.y,2)),s=tt(p+d.z*d.z,1.5)):(o=d.x*u.y-d.y*u.x,s=tt(p,1.5)),0===o||0===s)return{k:0,r:0};if(c=o/s,h=s/o,!i){const i=lt.curvature(t-.001,e,n,r,!0).k,o=lt.curvature(t+.001,e,n,r,!0).k;l=(o-c+(c-i))/2,a=(q(o-c)+q(c-i))/2}return{k:c,r:h,dk:l,adk:a}},inflections:function(t){if(t.length<4)return[];const e=lt.align(t,{p1:t[0],p2:t.slice(-1)[0]}),n=e[2].x*e[1].y,r=e[3].x*e[1].y,i=e[1].x*e[2].y,o=18*(-3*n+2*r+3*i-e[3].x*e[2].y),s=18*(3*n-r-3*i),a=18*(i-n);if(lt.approximately(o,0)){if(!lt.approximately(s,0)){let t=-a/s;if(0<=t&&t<=1)return[t]}return[]}const l=2*o;if(lt.approximately(l,0))return[];const c=s*s-4*o*a;if(c<0)return[];const h=Math.sqrt(c);return[(h-s)/l,-(s+h)/l].filter((function(t){return 0<=t&&t<=1}))},bboxoverlap:function(t,e){const n=["x","y"],r=n.length;for(let i,o,s,a,l=0;l<r;l++)if(i=n[l],o=t[i].mid,s=e[i].mid,a=(t[i].size+e[i].size)/2,q(o-s)>=a)return!1;return!0},expandbox:function(t,e){e.x.min<t.x.min&&(t.x.min=e.x.min),e.y.min<t.y.min&&(t.y.min=e.y.min),e.z&&e.z.min<t.z.min&&(t.z.min=e.z.min),e.x.max>t.x.max&&(t.x.max=e.x.max),e.y.max>t.y.max&&(t.y.max=e.y.max),e.z&&e.z.max>t.z.max&&(t.z.max=e.z.max),t.x.mid=(t.x.min+t.x.max)/2,t.y.mid=(t.y.min+t.y.max)/2,t.z&&(t.z.mid=(t.z.min+t.z.max)/2),t.x.size=t.x.max-t.x.min,t.y.size=t.y.max-t.y.min,t.z&&(t.z.size=t.z.max-t.z.min)},pairiteration:function(t,e,n){const r=t.bbox(),i=e.bbox(),o=1e5,s=n||.5;if(r.x.size+r.y.size<s&&i.x.size+i.y.size<s)return[(o*(t._t1+t._t2)/2|0)/o+"/"+(o*(e._t1+e._t2)/2|0)/o];let a=t.split(.5),l=e.split(.5),c=[{left:a.left,right:l.left},{left:a.left,right:l.right},{left:a.right,right:l.right},{left:a.right,right:l.left}];c=c.filter((function(t){return lt.bboxoverlap(t.left.bbox(),t.right.bbox())}));let h=[];return 0===c.length||(c.forEach((function(t){h=h.concat(lt.pairiteration(t.left,t.right,s))})),h=h.filter((function(t,e){return h.indexOf(t)===e}))),h},getccenter:function(t,e,n){const r=e.x-t.x,i=e.y-t.y,o=n.x-e.x,s=n.y-e.y,a=r*K(it)-i*X(it),l=r*X(it)+i*K(it),c=o*K(it)-s*X(it),h=o*X(it)+s*K(it),d=(t.x+e.x)/2,u=(t.y+e.y)/2,p=(e.x+n.x)/2,m=(e.y+n.y)/2,f=d+a,g=u+l,x=p+c,v=m+h,b=lt.lli8(d,u,f,g,p,m,x,v),y=lt.dist(b,t);let w,T=Y(t.y-b.y,t.x-b.x),C=Y(e.y-b.y,e.x-b.x),k=Y(n.y-b.y,n.x-b.x);return T<k?((T>C||C>k)&&(T+=rt),T>k&&(w=k,k=T,T=w)):k<C&&C<T?(w=k,k=T,T=w):k+=rt,b.s=T,b.e=k,b.r=y,b},numberSort:function(t,e){return t-e}};class ct{constructor(t){this.curves=[],this._3d=!1,t&&(this.curves=t,this._3d=this.curves[0]._3d)}valueOf(){return this.toString()}toString(){return"["+this.curves.map((function(t){return lt.pointsToString(t.points)})).join(", ")+"]"}addCurve(t){this.curves.push(t),this._3d=this._3d||t._3d}length(){return this.curves.map((function(t){return t.length()})).reduce((function(t,e){return t+e}))}curve(t){return this.curves[t]}bbox(){const t=this.curves;for(var e=t[0].bbox(),n=1;n<t.length;n++)lt.expandbox(e,t[n].bbox());return e}offset(t){const e=[];return this.curves.forEach((function(n){e.push(...n.offset(t))})),new ct(e)}}const{abs:ht,min:dt,max:ut,cos:pt,sin:mt,acos:ft,sqrt:gt}=Math,xt=Math.PI;class vt{constructor(t){let e=t&&t.forEach?t:Array.from(arguments).slice(),n=!1;if("object"==typeof e[0]){n=e.length;const t=[];e.forEach((function(e){["x","y","z"].forEach((function(n){void 0!==e[n]&&t.push(e[n])}))})),e=t}let r=!1;const i=e.length;if(n){if(n>4){if(1!==arguments.length)throw new Error("Only new Bezier(point[]) is accepted for 4th and higher order curves");r=!0}}else if(6!==i&&8!==i&&9!==i&&12!==i&&1!==arguments.length)throw new Error("Only new Bezier(point[]) is accepted for 4th and higher order curves");const o=this._3d=!r&&(9===i||12===i)||t&&t[0]&&void 0!==t[0].z,s=this.points=[];for(let t=0,n=o?3:2;t<i;t+=n){var a={x:e[t],y:e[t+1]};o&&(a.z=e[t+2]),s.push(a)}const l=this.order=s.length-1,c=this.dims=["x","y"];o&&c.push("z"),this.dimlen=c.length;const h=lt.align(s,{p1:s[0],p2:s[l]}),d=lt.dist(s[0],s[l]);this._linear=h.reduce(((t,e)=>t+ht(e.y)),0)<d/50,this._lut=[],this._t1=0,this._t2=1,this.update()}static quadraticFromPoints(t,e,n,r){if(void 0===r&&(r=.5),0===r)return new vt(e,e,n);if(1===r)return new vt(t,e,e);const i=vt.getABC(2,t,e,n,r);return new vt(t,i.A,n)}static cubicFromPoints(t,e,n,r,i){void 0===r&&(r=.5);const o=vt.getABC(3,t,e,n,r);void 0===i&&(i=lt.dist(e,o.C));const s=i*(1-r)/r,a=lt.dist(t,n),l=(n.x-t.x)/a,c=(n.y-t.y)/a,h=i*l,d=i*c,u=s*l,p=s*c,m=e.x-h,f=e.y-d,g=e.x+u,x=e.y+p,v=o.A,b=v.x+(m-v.x)/(1-r),y=v.y+(f-v.y)/(1-r),w=v.x+(g-v.x)/r,T=v.y+(x-v.y)/r,C={x:t.x+(b-t.x)/r,y:t.y+(y-t.y)/r},k={x:n.x+(w-n.x)/(1-r),y:n.y+(T-n.y)/(1-r)};return new vt(t,C,k,n)}static getUtils(){return lt}getUtils(){return vt.getUtils()}static get PolyBezier(){return ct}valueOf(){return this.toString()}toString(){return lt.pointsToString(this.points)}toSVG(){if(this._3d)return!1;const t=this.points,e=["M",t[0].x,t[0].y,2===this.order?"Q":"C"];for(let n=1,r=t.length;n<r;n++)e.push(t[n].x),e.push(t[n].y);return e.join(" ")}setRatios(t){if(t.length!==this.points.length)throw new Error("incorrect number of ratio values");this.ratios=t,this._lut=[]}verify(){const t=this.coordDigest();t!==this._print&&(this._print=t,this.update())}coordDigest(){return this.points.map((function(t,e){return""+e+t.x+t.y+(t.z?t.z:0)})).join("")}update(){this._lut=[],this.dpoints=lt.derive(this.points,this._3d),this.computedirection()}computedirection(){const t=this.points,e=lt.angle(t[0],t[this.order],t[1]);this.clockwise=e>0}length(){return lt.length(this.derivative.bind(this))}static getABC(t=2,e,n,r,i=.5){const o=lt.projectionratio(i,t),s=1-o,a={x:o*e.x+s*r.x,y:o*e.y+s*r.y},l=lt.abcratio(i,t);return{A:{x:n.x+(n.x-a.x)/l,y:n.y+(n.y-a.y)/l},B:n,C:a,S:e,E:r}}getABC(t,e){e=e||this.get(t);let n=this.points[0],r=this.points[this.order];return vt.getABC(this.order,n,e,r,t)}getLUT(t){if(this.verify(),t=t||100,this._lut.length===t)return this._lut;this._lut=[],t++,this._lut=[];for(let e,n,r=0;r<t;r++)n=r/(t-1),e=this.compute(n),e.t=n,this._lut.push(e);return this._lut}on(e,n){n=n||5;const r=this.getLUT(),i=[];for(let t,o=0,s=0;o<r.length;o++)t=r[o],lt.dist(t,e)<n&&(i.push(t),s+=o/r.length);return!!i.length&&(t/=i.length)}project(t){const e=this.getLUT(),n=e.length-1,r=lt.closest(e,t),i=r.mpos,o=(i-1)/n,s=(i+1)/n,a=.1/n;let l,c,h=r.mdist,d=o,u=d;for(h+=1;d<s+a;d+=a)l=this.compute(d),c=lt.dist(t,l),c<h&&(h=c,u=d);return u=u<0?0:u>1?1:u,l=this.compute(u),l.t=u,l.d=h,l}get(t){return this.compute(t)}point(t){return this.points[t]}compute(t){return this.ratios?lt.computeWithRatios(t,this.points,this.ratios,this._3d):lt.compute(t,this.points,this._3d,this.ratios)}raise(){const t=this.points,e=[t[0]],n=t.length;for(let r,i,o=1;o<n;o++)r=t[o],i=t[o-1],e[o]={x:(n-o)/n*r.x+o/n*i.x,y:(n-o)/n*r.y+o/n*i.y};return e[n]=t[n-1],new vt(e)}derivative(t){return lt.compute(t,this.dpoints[0],this._3d)}dderivative(t){return lt.compute(t,this.dpoints[1],this._3d)}align(){let t=this.points;return new vt(lt.align(t,{p1:t[0],p2:t[t.length-1]}))}curvature(t){return lt.curvature(t,this.dpoints[0],this.dpoints[1],this._3d)}inflections(){return lt.inflections(this.points)}normal(t){return this._3d?this.__normal3(t):this.__normal2(t)}__normal2(t){const e=this.derivative(t),n=gt(e.x*e.x+e.y*e.y);return{t,x:-e.y/n,y:e.x/n}}__normal3(t){const e=this.derivative(t),n=this.derivative(t+.01),r=gt(e.x*e.x+e.y*e.y+e.z*e.z),i=gt(n.x*n.x+n.y*n.y+n.z*n.z);e.x/=r,e.y/=r,e.z/=r,n.x/=i,n.y/=i,n.z/=i;const o={x:n.y*e.z-n.z*e.y,y:n.z*e.x-n.x*e.z,z:n.x*e.y-n.y*e.x},s=gt(o.x*o.x+o.y*o.y+o.z*o.z);o.x/=s,o.y/=s,o.z/=s;const a=[o.x*o.x,o.x*o.y-o.z,o.x*o.z+o.y,o.x*o.y+o.z,o.y*o.y,o.y*o.z-o.x,o.x*o.z-o.y,o.y*o.z+o.x,o.z*o.z];return{t,x:a[0]*e.x+a[1]*e.y+a[2]*e.z,y:a[3]*e.x+a[4]*e.y+a[5]*e.z,z:a[6]*e.x+a[7]*e.y+a[8]*e.z}}hull(t){let e=this.points,n=[],r=[],i=0;for(r[i++]=e[0],r[i++]=e[1],r[i++]=e[2],3===this.order&&(r[i++]=e[3]);e.length>1;){n=[];for(let o,s=0,a=e.length-1;s<a;s++)o=lt.lerp(t,e[s],e[s+1]),r[i++]=o,n.push(o);e=n}return r}split(t,e){if(0===t&&e)return this.split(e).left;if(1===e)return this.split(t).right;const n=this.hull(t),r={left:2===this.order?new vt([n[0],n[3],n[5]]):new vt([n[0],n[4],n[7],n[9]]),right:2===this.order?new vt([n[5],n[4],n[2]]):new vt([n[9],n[8],n[6],n[3]]),span:n};return r.left._t1=lt.map(0,0,1,this._t1,this._t2),r.left._t2=lt.map(t,0,1,this._t1,this._t2),r.right._t1=lt.map(t,0,1,this._t1,this._t2),r.right._t2=lt.map(1,0,1,this._t1,this._t2),e?(e=lt.map(e,t,1,0,1),r.right.split(e).left):r}extrema(){const t={};let e=[];return this.dims.forEach(function(n){let r=function(t){return t[n]},i=this.dpoints[0].map(r);t[n]=lt.droots(i),3===this.order&&(i=this.dpoints[1].map(r),t[n]=t[n].concat(lt.droots(i))),t[n]=t[n].filter((function(t){return t>=0&&t<=1})),e=e.concat(t[n].sort(lt.numberSort))}.bind(this)),t.values=e.sort(lt.numberSort).filter((function(t,n){return e.indexOf(t)===n})),t}bbox(){const t=this.extrema(),e={};return this.dims.forEach(function(n){e[n]=lt.getminmax(this,n,t[n])}.bind(this)),e}overlaps(t){const e=this.bbox(),n=t.bbox();return lt.bboxoverlap(e,n)}offset(t,e){if(void 0!==e){const n=this.get(t),r=this.normal(t),i={c:n,n:r,x:n.x+r.x*e,y:n.y+r.y*e};return this._3d&&(i.z=n.z+r.z*e),i}if(this._linear){const e=this.normal(0),n=this.points.map((function(n){const r={x:n.x+t*e.x,y:n.y+t*e.y};return n.z&&e.z&&(r.z=n.z+t*e.z),r}));return[new vt(n)]}return this.reduce().map((function(e){return e._linear?e.offset(t)[0]:e.scale(t)}))}simple(){if(3===this.order){const t=lt.angle(this.points[0],this.points[3],this.points[1]),e=lt.angle(this.points[0],this.points[3],this.points[2]);if(t>0&&e<0||t<0&&e>0)return!1}const t=this.normal(0),e=this.normal(1);let n=t.x*e.x+t.y*e.y;return this._3d&&(n+=t.z*e.z),ht(ft(n))<xt/3}reduce(){let t,e,n=0,r=0,i=.01,o=[],s=[],a=this.extrema().values;for(-1===a.indexOf(0)&&(a=[0].concat(a)),-1===a.indexOf(1)&&a.push(1),n=a[0],t=1;t<a.length;t++)r=a[t],e=this.split(n,r),e._t1=n,e._t2=r,o.push(e),n=r;return o.forEach((function(t){for(n=0,r=0;r<=1;)for(r=n+i;r<=1.01;r+=i)if(e=t.split(n,r),!e.simple()){if(r-=i,ht(n-r)<i)return[];e=t.split(n,r),e._t1=lt.map(n,0,1,t._t1,t._t2),e._t2=lt.map(r,0,1,t._t1,t._t2),s.push(e),n=r;break}n<1&&(e=t.split(n,1),e._t1=lt.map(n,0,1,t._t1,t._t2),e._t2=t._t2,s.push(e))})),s}translate(t,e,n){n="number"==typeof n?n:e;const r=this.order;let i=this.points.map(((t,i)=>(1-i/r)*e+i/r*n));return new vt(this.points.map(((e,n)=>({x:e.x+t.x*i[n],y:e.y+t.y*i[n]}))))}scale(t){const e=this.order;let n=!1;if("function"==typeof t&&(n=t),n&&2===e)return this.raise().scale(n);const r=this.clockwise,i=this.points;if(this._linear)return this.translate(this.normal(0),n?n(0):t,n?n(1):t);const o=n?n(0):t,s=n?n(1):t,a=[this.offset(0,10),this.offset(1,10)],l=[],c=lt.lli4(a[0],a[0].c,a[1],a[1].c);if(!c)throw new Error("cannot scale this curve. Try reducing it first.");return[0,1].forEach((function(t){const n=l[t*e]=lt.copy(i[t*e]);n.x+=(t?s:o)*a[t].n.x,n.y+=(t?s:o)*a[t].n.y})),n?([0,1].forEach((function(o){if(2!==e||!o){var s=i[o+1],a={x:s.x-c.x,y:s.y-c.y},h=n?n((o+1)/e):t;n&&!r&&(h=-h);var d=gt(a.x*a.x+a.y*a.y);a.x/=d,a.y/=d,l[o+1]={x:s.x+h*a.x,y:s.y+h*a.y}}})),new vt(l)):([0,1].forEach((t=>{if(2===e&&t)return;const n=l[t*e],r=this.derivative(t),o={x:n.x+r.x,y:n.y+r.y};l[t+1]=lt.lli4(n,o,c,i[t+1])})),new vt(l))}outline(t,e,n,r){if(e=void 0===e?t:e,this._linear){const i=this.normal(0),o=this.points[0],s=this.points[this.points.length-1];let a,l,c;void 0===n&&(n=t,r=e),a={x:o.x+i.x*t,y:o.y+i.y*t},c={x:s.x+i.x*n,y:s.y+i.y*n},l={x:(a.x+c.x)/2,y:(a.y+c.y)/2};const h=[a,l,c];a={x:o.x-i.x*e,y:o.y-i.y*e},c={x:s.x-i.x*r,y:s.y-i.y*r},l={x:(a.x+c.x)/2,y:(a.y+c.y)/2};const d=[c,l,a],u=lt.makeline(d[2],h[0]),p=lt.makeline(h[2],d[0]),m=[u,new vt(h),p,new vt(d)];return new ct(m)}const i=this.reduce(),o=i.length,s=[];let a,l=[],c=0,h=this.length();const d=void 0!==n&&void 0!==r;function u(t,e,n,r,i){return function(o){const s=r/n,a=(r+i)/n,l=e-t;return lt.map(o,0,1,t+s*l,t+a*l)}}i.forEach((function(i){const o=i.length();d?(s.push(i.scale(u(t,n,h,c,o))),l.push(i.scale(u(-e,-r,h,c,o)))):(s.push(i.scale(t)),l.push(i.scale(-e))),c+=o})),l=l.map((function(t){return a=t.points,a[3]?t.points=[a[3],a[2],a[1],a[0]]:t.points=[a[2],a[1],a[0]],t})).reverse();const p=s[0].points[0],m=s[o-1].points[s[o-1].points.length-1],f=l[o-1].points[l[o-1].points.length-1],g=l[0].points[0],x=lt.makeline(f,p),v=lt.makeline(m,g),b=[x].concat(s).concat([v]).concat(l);return new ct(b)}outlineshapes(t,e,n){e=e||t;const r=this.outline(t,e).curves,i=[];for(let t=1,e=r.length;t<e/2;t++){const o=lt.makeshape(r[t],r[e-t],n);o.startcap.virtual=t>1,o.endcap.virtual=t<e/2-1,i.push(o)}return i}intersects(t,e){return t?t.p1&&t.p2?this.lineIntersects(t):(t instanceof vt&&(t=t.reduce()),this.curveintersects(this.reduce(),t,e)):this.selfintersects(e)}lineIntersects(t){const e=dt(t.p1.x,t.p2.x),n=dt(t.p1.y,t.p2.y),r=ut(t.p1.x,t.p2.x),i=ut(t.p1.y,t.p2.y);return lt.roots(this.points,t).filter((t=>{var o=this.get(t);return lt.between(o.x,e,r)&&lt.between(o.y,n,i)}))}selfintersects(t){const e=this.reduce(),n=e.length-2,r=[];for(let i,o,s,a=0;a<n;a++)o=e.slice(a,a+1),s=e.slice(a+2),i=this.curveintersects(o,s,t),r.push(...i);return r}curveintersects(t,e,n){const r=[];t.forEach((function(t){e.forEach((function(e){t.overlaps(e)&&r.push({left:t,right:e})}))}));let i=[];return r.forEach((function(t){const e=lt.pairiteration(t.left,t.right,n);e.length>0&&(i=i.concat(e))})),i}arcs(t){return t=t||.5,this._iterate(t,[])}_error(t,e,n,r){const i=(r-n)/4,o=this.get(n+i),s=this.get(r-i),a=lt.dist(t,e),l=lt.dist(t,o),c=lt.dist(t,s);return ht(l-a)+ht(c-a)}_iterate(t,e){let n,r=0,i=1;do{n=0,i=1;let o,s,a,l,c,h=this.get(r),d=!1,u=!1,p=i,m=1,f=0;do{if(u=d,l=a,p=(r+i)/2,f++,o=this.get(p),s=this.get(i),a=lt.getccenter(h,o,s),a.interval={start:r,end:i},d=this._error(a,h,r,i)<=t,c=u&&!d,c||(m=i),d){if(i>=1){if(a.interval.end=m=1,l=a,i>1){let t={x:a.x+a.r*pt(a.e),y:a.y+a.r*mt(a.e)};a.e+=lt.angle({x:a.x,y:a.y},t,this.get(1))}break}i+=(i-r)/2}else i=p}while(!c&&n++<100);if(n>=100)break;l=l||a,e.push(l),r=m}while(i<1);return e}}const bt=t=>{const e=t.charAt(t.length-1);if(("0"===e||"."===e)&&"-0"===(t=(t=(t=t.replace(/([.]\d*[^0]+)0+$/,"$1")).replace(/[.]0+$/,".")).replace(/[.]$/,"")))return"0";const n=t.charAt(0);return"0"!==n&&"-"!==n||(t=(t=t.replace(/^(0+)[.]/,".")).replace(/^-(0+)[.]/,"-.")),t},yt=t=>{let e=t.toString(10);if(-1===e.indexOf("."))return e;const n=/^([-]?)(\d*)\.(\d{3,}9{4,})\d{1,2}$/.exec(e);if(n){const t=n[1],r=n[3],i=parseInt(r.charAt(r.length-1),10),o=parseInt(r,10),s=parseInt(n[2],10),a=n[3];let l=(o+10-i).toString(),c=0;for(l.length>o.toString().length&&(l=l.substring(1),c=1);l.length<a.length;)l=c.toString(10)+l,c=0;e=`${t+(s+c).toString()}.${l}`}return e=e.replace(/^([-]?\d*\.\d{3,})0{4,}\d{1,2}$/,"$1"),bt(e)},wt=/^([-]?)(\d*)[.](\d+)$/,Tt=t=>{const e=wt.exec(t);if(!e)return-1!==t.search(/[eE]/)||/^[a-zA-Z]+$/.exec(t)?-1:0;return e[3].length},Ct=(t,...e)=>{const n=t.toString(10),r=wt.exec(n);if(!r)return n;let i=-1;for(const t of e)i=Math.max(Tt(t),i);if(-1===i)return yt(t);let o=r[3].substring(0,i),s=r[2];const a=r[3].charAt(i);if(""!==a){if(parseInt(a,10)>=5){if(o.length>0){const t=/^(0+)(\d*)$/.exec(o);let e="",n=o;t&&(e=t[1],n=t[2]),o=(parseInt(o)+1).toString(),o.length>n.length&&e.length>0&&(e=e.substring(1)),o=e+o}(0===o.length||o.length>i)&&(s=(parseInt(s)+1).toString(),o=o.substring(1))}}const l=r[1];return bt(`${l}${s}.${o}`)};var kt;!function(t){t[t.LineTo=0]="LineTo",t[t.MoveTo=1]="MoveTo",t[t.CubicBezierTo=2]="CubicBezierTo",t[t.QuadraticBezierTo=3]="QuadraticBezierTo"}(kt||(kt={}));class St{constructor(t,e){this.startPoint=t,this.parts=e,this.cachedGeometry=null,this.cachedPolylineApproximation=null,this.cachedStringVersion=null,this.bbox=R.bboxOf([t]);for(const n of e)this.bbox=this.bbox.union(St.computeBBoxForSegment(t,n))}get geometry(){if(this.cachedGeometry)return this.cachedGeometry;let t=this.startPoint;const e=[];for(const n of this.parts)switch(n.kind){case kt.CubicBezierTo:e.push(new vt(t.xy,n.controlPoint1.xy,n.controlPoint2.xy,n.endPoint.xy)),t=n.endPoint;break;case kt.QuadraticBezierTo:e.push(new vt(t.xy,n.controlPoint.xy,n.endPoint.xy)),t=n.endPoint;break;case kt.LineTo:e.push(new B(t,n.point)),t=n.point;break;case kt.MoveTo:t=n.point}return this.cachedGeometry=e,this.cachedGeometry}polylineApproximation(){if(this.cachedPolylineApproximation)return this.cachedPolylineApproximation;const t=[];for(const e of this.parts)switch(e.kind){case kt.CubicBezierTo:t.push(e.controlPoint1,e.controlPoint2,e.endPoint);break;case kt.QuadraticBezierTo:t.push(e.controlPoint,e.endPoint);break;case kt.MoveTo:case kt.LineTo:t.push(e.point)}const e=[];let n=this.startPoint;for(const r of t)e.push(new B(n,r)),n=r;return e}static computeBBoxForSegment(t,e){const n=[t];let r;switch(e.kind){case kt.MoveTo:case kt.LineTo:n.push(e.point);break;case kt.CubicBezierTo:n.push(e.controlPoint1,e.controlPoint2,e.endPoint);break;case kt.QuadraticBezierTo:n.push(e.controlPoint,e.endPoint);break;default:return r=e,r}return R.bboxOf(n)}intersection(t){if(!t.bbox.intersects(this.bbox))return[];const e=[];for(const n of this.geometry)if(n instanceof B){const r=n.intersection(t);r&&e.push({curve:n,parameterValue:r.t,point:r.point})}else{const r=n.intersects(t).map((e=>{"string"==typeof e&&(e=parseFloat(e));const r=k.ofXY(n.get(e));return r.minus(t.p1).magnitude()>t.length||r.minus(t.p2).magnitude()>t.length?null:{point:r,parameterValue:e,curve:n}})).filter((t=>null!==t));e.push(...r)}return e}mapPoints(t){const e=t(this.startPoint),n=[];let r;for(const e of this.parts)switch(e.kind){case kt.MoveTo:case kt.LineTo:n.push({kind:e.kind,point:t(e.point)});break;case kt.CubicBezierTo:n.push({kind:e.kind,controlPoint1:t(e.controlPoint1),controlPoint2:t(e.controlPoint2),endPoint:t(e.endPoint)});break;case kt.QuadraticBezierTo:n.push({kind:e.kind,controlPoint:t(e.controlPoint),endPoint:t(e.endPoint)});break;default:return r=e,r}return new St(e,n)}transformedBy(t){return this.mapPoints((e=>t.transformVec2(e)))}union(t){return t?new St(this.startPoint,[...this.parts,{kind:kt.MoveTo,point:t.startPoint},...t.parts]):this}closedRoughlyIntersects(t){if(t.containsRect(this.bbox))return!0;const e=this.bbox.topLeft.minus(k.of(1,1)),n=t.corners,r=this.polylineApproximation();for(const t of n){const n=new B(t,e);let i=0;for(const t of r)t.intersects(n)&&i++;if(i%2==1)return!0}const i=t.grownBy(Math.min(t.size.x,t.size.y)),o=[];for(const t of i.divideIntoGrid(4,4))o.push(...t.getEdges());for(const t of o)for(const e of r)if(t.intersects(e))return!0;return!1}static fromRect(t,e=null){const n=[];let r,i;if(null!==e){const n=k.of(e,e).times(.5),o=R.fromCorners(t.topLeft.plus(n),t.bottomRight.minus(n)),s=R.fromCorners(t.topLeft.minus(n),t.bottomRight.plus(n));r=[o.corners[3],...o.corners,...s.corners.reverse()],i=s.corners[3]}else r=t.corners.slice(1),i=t.corners[0];for(const t of r)n.push({kind:kt.LineTo,point:t});return new St(i,n)}static fromRenderable(t){return t.path?t.path:new St(t.startPoint,t.commands)}toRenderable(t){return{startPoint:this.startPoint,style:t,commands:this.parts,path:this}}toString(){if(this.cachedStringVersion)return this.cachedStringVersion;const t=Math.abs(this.bbox.topLeft.x)>10&&Math.abs(this.bbox.topLeft.y)>10,e=St.toString(this.startPoint,this.parts,!t);return this.cachedStringVersion=e,e}serialize(){return this.toString()}static toString(t,e,n){const r=[];let i;const o=(t,...e)=>{const o=[],s=[],a=!i||n,l=i?yt(i.x):"",c=i?yt(i.y):"";for(const t of e)if(a){const e=yt(t.x),n=yt(t.y);o.push(`${e},${n}`)}else{const e=Ct(t.x-i.x,l,c),n=Ct(t.y-i.y,l,c);"-"===n.charAt(0)?s.push(`${e}${n}`):s.push(`${e},${n}`)}let h;h=a?`${t}${o.join(" ")}`:`${t.toLowerCase()}${s.join(" ")}`,"l0,0"!==h&&(r.push(h),e.length>0&&(i=e[e.length-1]))};let s;o("M",t);for(const t of e)switch(t.kind){case kt.MoveTo:o("M",t.point);break;case kt.LineTo:o("L",t.point);break;case kt.CubicBezierTo:o("C",t.controlPoint1,t.controlPoint2,t.endPoint);break;case kt.QuadraticBezierTo:o("Q",t.controlPoint,t.endPoint);break;default:return s=t,s}return r.join("")}static fromString(t){var e;t=t.split("\n").join(" ");let n=k.zero,r=null,i=null,o=!0;const s=[],a=t=>{o?o=!1:s.push({kind:kt.LineTo,point:t})},l={m:1,l:1,c:3,q:2,z:0,h:1,v:1},c=/([MZLHVCSQTA])\s*([^MZLHVCSQTA]*)/gi;let h;for(;null!==(h=c.exec(t));){const t=h[2].trim().split(/[^0-9Ee.-]/).filter((t=>t.length>0)).reduce(((t,e)=>{const n=(e=e.replace(/([^eE])[-]/g,"$1 -")).split(" -");return""!==n[0]&&t.push(n[0]),t.push(...n.slice(1).map((t=>`-${t}`))),t}),[]);let c=t.map((t=>parseFloat(t))),x=h[1].toLowerCase(),v=h[1]!==x;if("v"===x||"h"===x)c=c.reduce(((t,e)=>"v"===x?t.concat(v?n.x:0,e):t.concat(e,v?n.y:0)),[]),x="l";else if("z"===x){if(!r)continue;c=[r.x,r.y],r=n,v=!0,x="l"}const b=null!==(e=l[x])&&void 0!==e?e:0,y=c.reduce(((t,e,n,r)=>{if(n%2!=0){const i=e,o=r[n-1];return t.concat(k.of(o,i))}return t}),[]).map(((t,e)=>{let r;return r=v?t:n.plus(t),(e+1)%b==0&&(n=r),r}));if(y.length%b!=0)throw new Error([`Incorrect number of arguments: got ${JSON.stringify(y)} with a length of ${y.length} ≠ ${b}k, k ∈ ℤ.`,`The number of arguments to ${x} must be a multiple of ${b}!`,`Command: ${h[0]}`].join("\n"));for(let t=0;t<y.length;t+=b){const e=y.slice(t,t+b);switch(x.toLowerCase()){case"m":0===t?(g=e[0],o?o=!1:s.push({kind:kt.MoveTo,point:g})):a(e[0]);break;case"l":a(e[0]);break;case"c":p=e[0],m=e[1],f=e[2],s.push({kind:kt.CubicBezierTo,controlPoint1:p,controlPoint2:m,endPoint:f});break;case"q":d=e[0],u=e[1],s.push({kind:kt.QuadraticBezierTo,controlPoint:d,endPoint:u});break;default:throw new Error(`Unknown path command ${x}`)}o=!1}y.length>0&&(null!=r||(r=y[0]),null!=i||(i=r),n=y[y.length-1])}var d,u,p,m,f,g;const x=new St(null!=i?i:k.zero,s);return x.cachedStringVersion=t,x}}St.empty=new St(k.zero,[]);class Et{constructor(t,e,n,r){this.r=t,this.g=e,this.b=n,this.a=r,this.hexString=null}static ofRGB(t,e,n){return Et.ofRGBA(t,e,n,1)}static ofRGBA(t,e,n,r){return t=Math.max(0,Math.min(t,1)),e=Math.max(0,Math.min(e,1)),n=Math.max(0,Math.min(n,1)),r=Math.max(0,Math.min(r,1)),new Et(t,e,n,r)}static fromHex(t){var e;if(!(t=(t=(null!==(e=t.match(/^[#]?(.*)$/))&&void 0!==e?e:[])[1]).toUpperCase()).match(/^[0-9A-F]+$/))throw new Error(`${t} is not in a valid format.`);if(3===t.length||4===t.length){const e=t.split("");t=e.map((t=>`${t}0`)).join("")}6===t.length&&(t+="FF");const n=[];for(let e=2;e<=t.length;e+=2){const r=t.substring(e-2,e);n.push(parseInt(r,16)/255)}if(4!==n.length)throw new Error(`Unable to parse ${t}: Wrong number of components.`);return Et.ofRGBA(n[0],n[1],n[2],n[3])}static fromString(t){if(t.startsWith("#"))return Et.fromHex(t);{const e=document.createElement("canvas");e.width=1,e.height=1;const n=e.getContext("2d");n.fillStyle=t,n.fillRect(0,0,1,1);const r=n.getImageData(0,0,1,1),i=r.data[0]/255,o=r.data[1]/255,s=r.data[2]/255,a=r.data[3]/255;return Et.ofRGBA(i,o,s,a)}}eq(t){return null!=t&&this.toHexString()===t.toHexString()}toHexString(){if(this.hexString)return this.hexString;const t=t=>{const e=Math.round(255*t).toString(16);return 1===e.length?`0${e}`:e},e=t(this.a),n=t(this.r),r=t(this.g),i=t(this.b);return"ff"===e?`#${n}${r}${i}`:(this.hexString=`#${n}${r}${i}${e}`,this.hexString)}}Et.transparent=Et.ofRGBA(0,0,0,0),Et.red=Et.ofRGB(1,0,0),Et.green=Et.ofRGB(0,1,0),Et.blue=Et.ofRGB(0,0,1),Et.purple=Et.ofRGB(.5,.2,.5),Et.yellow=Et.ofRGB(1,1,.1),Et.clay=Et.ofRGB(.8,.4,.2),Et.black=Et.ofRGB(0,0,0),Et.white=Et.ofRGB(1,1,1);const Pt=(t,e)=>{var n,r,i,o,s,a;const l=t===e||t.fill.eq(e.fill)&&null==t.stroke==(null==e.stroke)&&(null===(o=null===(r=null===(n=t.stroke)||void 0===n?void 0:n.color)||void 0===r?void 0:r.eq(null===(i=e.stroke)||void 0===i?void 0:i.color))||void 0===o||o)&&(null===(s=t.stroke)||void 0===s?void 0:s.width)===(null===(a=e.stroke)||void 0===a?void 0:a.width);return null!=l&&l},zt=t=>{const e=t.stroke?{color:t.stroke.color.toHexString(),width:t.stroke.width}:void 0;return{fill:t.fill.toHexString(),stroke:e}},Bt=t=>{const e=t.stroke?{color:Et.fromHex(t.stroke.color),width:t.stroke.width}:void 0;return{fill:Et.fromHex(t.fill),stroke:e}};class Rt extends z{constructor(t){var e;super("stroke"),this.parts=t.map((t=>{const e=St.fromRenderable(t),n=this.bboxForPart(e.bbox,t.style);return this.contentBBox?this.contentBBox=this.contentBBox.union(n):this.contentBBox=n,{path:e,startPoint:e.startPoint,style:t.style,commands:e.parts}})),null!==(e=this.contentBBox)&&void 0!==e||(this.contentBBox=R.empty)}intersects(t){for(const e of this.parts)if(e.path.intersection(t).length>0)return!0;return!1}render(t,e){t.startObject(this.getBBox());for(const n of this.parts){const r=this.bboxForPart(n.path.bbox,n.style);if(e){if(!r.intersects(e))continue;if((r.size.x>2*e.size.x||r.size.y>2*e.size.y)&&!n.path.closedRoughlyIntersects(e))continue}t.drawPath(n)}t.endObject(this.getLoadSaveData())}bboxForPart(t,e){return e.stroke?t.grownBy(e.stroke.width/2):t}applyTransformation(t){this.contentBBox=R.empty;let e=!0;this.parts=this.parts.map((n=>{const r=n.path.transformedBy(t),i=this.bboxForPart(r.bbox,n.style);return e?(this.contentBBox=i,e=!1):this.contentBBox=this.contentBBox.union(i),{path:r,startPoint:r.startPoint,commands:r.parts,style:n.style}}))}getPath(){var t;return null!==(t=this.parts.reduce(((t,e)=>{var n;return null!==(n=null==t?void 0:t.union(e.path))&&void 0!==n?n:e.path}),null))&&void 0!==t?t:St.empty}description(t){return t.stroke}createClone(){return new Rt(this.parts)}serializeToJSON(){return this.parts.map((t=>({style:zt(t.style),path:t.path.serialize()})))}static deserializeFromJSON(t){if("string"==typeof t&&(t=JSON.parse(t)),"object"!=typeof t||"number"!=typeof t.length)throw new Error(`${t} is missing required field, parts, or parts is of the wrong type.`);const e=t.map((t=>{const e=Bt(t.style);return St.fromString(t.path).toRenderable(e)}));return new Rt(e)}}z.registerComponent("stroke",Rt.deserializeFromJSON);const At=(t,e)=>{const n=7*e.getSizeOfPixelOnCanvas(),r=e.getSizeOfPixelOnCanvas();return new It(t,r,n)};class It{constructor(t,e,n){this.startPoint=t,this.minFitAllowed=e,this.maxFitAllowed=n,this.isFirstSegment=!0,this.pathStartConnector=null,this.mostRecentConnector=null,this.lastExitingVec=null,this.currentCurve=null,this.lastPoint=this.startPoint,this.upperSegments=[],this.lowerSegments=[],this.buffer=[this.startPoint.pos],this.momentum=k.zero,this.currentCurve=null,this.curveStartWidth=t.width,this.bbox=new R(this.startPoint.pos.x,this.startPoint.pos.y,0,0)}getBBox(){return this.bbox}getRenderingStyle(){var t;return{fill:null!==(t=this.lastPoint.color)&&void 0!==t?t:null}}previewPath(){var t;let e,n,r,i;if(this.currentCurve){const{upperCurve:o,lowerToUpperConnector:s,upperToLowerConnector:a,lowerCurve:l}=this.currentSegmentToPath();e=this.upperSegments.concat(o),n=this.lowerSegments.concat(l),r=s,i=null!==(t=this.pathStartConnector)&&void 0!==t?t:a}else{if(null===this.mostRecentConnector||null===this.pathStartConnector)return null;e=this.upperSegments.slice(),n=this.lowerSegments.slice(),r=this.mostRecentConnector,i=this.pathStartConnector}return{startPoint:n[n.length-1].endPoint,commands:[r,...e.reverse(),i,...n],style:this.getRenderingStyle()}}previewStroke(){const t=this.previewPath();return t?new Rt([t]):null}preview(t){const e=this.previewPath();e&&t.drawPath(e)}build(){return this.lastPoint&&this.finalizeCurrentCurve(),this.previewStroke()}roundPoint(t){let e=Math.min(this.minFitAllowed,this.curveStartWidth/2);return e<1e-10&&(e=this.minFitAllowed),H.roundPoint(t,e)}finalizeCurrentCurve(){if(!this.currentCurve){if(!this.isFirstSegment)return;const t=H.roundPoint(this.startPoint.width/3.5,Math.min(this.minFitAllowed,this.startPoint.width/4)),e=this.roundPoint(this.startPoint.pos),n=this.startPoint.pos.plus(k.of(t,0));return this.lowerSegments.push({kind:kt.QuadraticBezierTo,controlPoint:e.plus(k.of(t,t)),endPoint:e.plus(k.of(0,t))},{kind:kt.QuadraticBezierTo,controlPoint:e.plus(k.of(-t,t)),endPoint:e.plus(k.of(-t,0))},{kind:kt.QuadraticBezierTo,controlPoint:e.plus(k.of(-t,-t)),endPoint:e.plus(k.of(0,-t))},{kind:kt.QuadraticBezierTo,controlPoint:e.plus(k.of(t,-t)),endPoint:e.plus(k.of(t,0))}),this.pathStartConnector={kind:kt.LineTo,point:n},void(this.mostRecentConnector=this.pathStartConnector)}const{upperCurve:t,lowerToUpperConnector:e,upperToLowerConnector:n,lowerCurve:r}=this.currentSegmentToPath();this.isFirstSegment&&(this.pathStartConnector=n,this.isFirstSegment=!1),this.mostRecentConnector=e,this.upperSegments.push(t),this.lowerSegments.push(r);const i=this.buffer[this.buffer.length-1];this.lastExitingVec=k.ofXY(this.currentCurve.points[2]).minus(k.ofXY(this.currentCurve.points[1])),console.assert(0!==this.lastExitingVec.magnitude(),"lastExitingVec has zero length!"),this.buffer=[this.buffer[this.buffer.length-2],i],this.currentCurve=null}currentSegmentToPath(){if(null==this.currentCurve)throw new Error("Invalid State: currentCurve is null!");let t=k.ofXY(this.currentCurve.normal(0)).normalized(),e=k.ofXY(this.currentCurve.normal(1)).normalized();t=t.times(this.curveStartWidth/2),e=e.times(this.curveEndWidth/2),isNaN(t.magnitude())&&(console.error("startVec is NaN",t,e,this.currentCurve),t=e);const n=k.ofXY(this.currentCurve.get(0)),r=k.ofXY(this.currentCurve.get(1)),i=k.ofXY(this.currentCurve.points[1]);let o=this.currentCurve.project(i.xy).t;o||(o=n.minus(i).magnitudeSquared()<r.minus(i).magnitudeSquared()?.1:.9);const s=o;let a=k.ofXY(this.currentCurve.normal(s)).normalized().times(this.curveStartWidth/2*s+this.curveEndWidth/2*(1-s));const l=(o,s)=>new vt(n.plus(t.times(o)),i.plus(s.times(o)),r.plus(e.times(o)));(()=>{const t=l(1,a),e=l(-1,a);return t.intersects(e).length>0})()&&(a=a.times(1.1));const c={kind:kt.QuadraticBezierTo,controlPoint:this.roundPoint(i.plus(a)),endPoint:this.roundPoint(r.plus(e))},h={kind:kt.LineTo,point:this.roundPoint(n.plus(t))},d={kind:kt.LineTo,point:this.roundPoint(r.minus(e))};return{upperCurve:{kind:kt.QuadraticBezierTo,controlPoint:this.roundPoint(i.minus(a)),endPoint:this.roundPoint(n.minus(t))},upperToLowerConnector:h,lowerToUpperConnector:d,lowerCurve:c}}computeExitingVec(){return this.momentum.normalized().times(this.lastPoint.width/2)}addPoint(t){var e,n;if(this.lastPoint){const e=1e-10,n=t.time-this.lastPoint.time;if(t.pos.eq(this.lastPoint.pos,e)||0===n)return void console.warn("Discarding identical point");if(isNaN(t.pos.magnitude()))return void console.warn("Discarding NaN point.",t);const r=Math.min(this.lastPoint.width,t.width)/3;if(this.startPoint.pos.minus(t.pos).magnitude()<r&&this.isFirstSegment)return;const i=t.pos.minus(this.lastPoint.pos).times(1/n*1e3);this.momentum=this.momentum.lerp(i,.9)}const r=null!==(e=this.lastPoint)&&void 0!==e?e:t;this.lastPoint=t,this.buffer.push(t.pos);const i=t.width/2,o=this.curveEndWidth;if(this.curveEndWidth=i,this.bbox=this.bbox.grownToPoint(t.pos,i),null===this.currentCurve){const e=r.pos,i=r.pos.plus(null!==(n=this.lastExitingVec)&&void 0!==n?n:k.unitX),o=t.pos;this.currentCurve=new vt(e.xy,i.xy,o.xy),this.curveStartWidth=r.width/2,console.assert(!isNaN(e.magnitude())&&!isNaN(i.magnitude())&&!isNaN(o.magnitude()),"Expected !NaN")}let s=this.lastExitingVec;if(!s){let t=Math.ceil(this.buffer.length/3);0===t&&(t=this.buffer.length-1),s=this.buffer[t].minus(this.buffer[0])}let a=this.computeExitingVec();const l=this.buffer[0],c=t.pos,h=c.minus(l).magnitude(),d=2*h;if(0===d||0===a.magnitude()||isNaN(a.magnitude()))return;console.assert(!isNaN(s.magnitude())),s=s.normalized(),a=a.normalized(),console.assert(!isNaN(s.magnitude()));const u=new B(l,l.plus(s.times(d))),p=new B(c.minus(a.times(d)),c).intersection(u);let m;m=p?p.point:l.plus(s.times(h/4)),(isNaN(m.magnitude())||isNaN(l.magnitude()))&&console.error("controlPoint is NaN",p,"Start:",l,"End:",c,"in:",s,"out:",a);const f=this.currentCurve;this.currentCurve=new vt(l.xy,m.xy,c.xy),isNaN(k.ofXY(this.currentCurve.normal(0)).magnitude())&&(console.error("NaN normal at 0. Curve:",this.currentCurve),this.currentCurve=f);const g=t=>{for(const e of this.buffer){const n=k.ofXY(t.project(e.xy)).minus(e).magnitude();if(n>Math.max(Math.min(this.curveStartWidth,this.curveEndWidth)/3,this.minFitAllowed)||n>this.maxFitAllowed)return!1}return!0},x=m.minus(l).magnitude()+c.minus(m).magnitude();return this.buffer.length>3&&x>this.curveEndWidth/3&&!g(this.currentCurve)?(this.currentCurve=f,this.curveEndWidth=o,this.lastPoint=r,void this.finalizeCurrentCurve()):void 0}}class Lt extends G{constructor(t,e,n){super(t.notifier,e),this.editor=t,this.style=n,this.builder=null,this.builderFactory=At,this.lastPoint=null}getPressureMultiplier(){return 1/this.editor.viewport.getScaleFactor()*this.style.thickness}toStrokePoint(t){var e;let n=Math.max(null!==(e=t.pressure)&&void 0!==e?e:1,.3);return isFinite(n)||(console.warn("Non-finite pressure!",t),n=.3),console.assert(isFinite(t.canvasPos.length()),"Non-finite canvas position!"),console.assert(isFinite(t.screenPos.length()),"Non-finite screen position!"),console.assert(isFinite(t.timeStamp),"Non-finite timeStamp on pointer!"),{pos:t.canvasPos,width:n*this.getPressureMultiplier(),color:this.style.color,time:t.timeStamp}}previewStroke(){var t;this.editor.clearWetInk(),null===(t=this.builder)||void 0===t||t.preview(this.editor.display.getWetInkRenderer())}addPointToStroke(t){if(!this.builder)throw new Error("No stroke is currently being generated.");this.builder.addPoint(t),this.lastPoint=t,this.previewStroke()}onPointerDown({current:t,allPointers:e}){const n=t.device===O.Eraser;let r=!1;for(const t of e)if(t.device===O.Pen){r=!0;break}return!((1!==e.length||n)&&!r)&&(this.builder=this.builderFactory(this.toStrokePoint(t),this.editor.viewport),!0)}onPointerMove({current:t}){this.addPointToStroke(this.toStrokePoint(t))}onPointerUp({current:t}){var e,n;if(!this.builder)return;const r=this.toStrokePoint(t),i=Object.assign(Object.assign({},r),{width:null!==(n=null===(e=this.lastPoint)||void 0===e?void 0:e.width)&&void 0!==n?n:r.width});if(this.addPointToStroke(i),this.builder&&t.isPrimary){const t=this.builder.build();if(this.previewStroke(),t.getBBox().area>0){const e=!0,n=I.addElement(t,e);this.editor.dispatch(n)}else console.warn("Pen: Not adding empty stroke",t,"to the canvas.")}this.builder=null,this.editor.clearWetInk()}onGestureCancel(){this.editor.clearWetInk()}noteUpdated(){this.editor.notifier.dispatch(D.ToolUpdated,{kind:D.ToolUpdated,tool:this})}setColor(t){t.toHexString()!==this.style.color.toHexString()&&(this.style=Object.assign(Object.assign({},this.style),{color:t}),this.noteUpdated())}setThickness(t){t!==this.style.thickness&&(this.style=Object.assign(Object.assign({},this.style),{thickness:t}),this.noteUpdated())}setStrokeFactory(t){t!==this.builderFactory&&(this.builderFactory=t,this.noteUpdated())}getThickness(){return this.style.thickness}getColor(){return this.style.color}getStrokeFactory(){return this.builderFactory}onKeyPress({key:t}){let e;return"-"===(t=t.toLowerCase())||"_"===t?e=2*this.getThickness()/3:"+"!==t&&"="!==t||(e=3*this.getThickness()/2),void 0!==e&&(e=Math.min(Math.max(1,e),128),this.setThickness(e),!0)}}class Mt{constructor(){}notifyEnabled(t){var e;t!==this.activeTool&&(null===(e=this.activeTool)||void 0===e||e.setEnabled(!1),this.activeTool=t)}}const Dt=(t,e)=>{if(0===e.length)return null;const n=e[0].description(t);for(const r of e)if(r.description(t)!==n)return null;return n};class Ot extends T{constructor(t){super("erase"),this.toRemove=t.map((t=>t)),this.applied=!1}apply(t){for(const e of this.toRemove){const n=t.image.findParent(e);n&&n.remove()}this.applied=!0,t.queueRerender()}unapply(t){for(const e of this.toRemove)t.image.findParent(e)||I.addElement(e).apply(t);this.applied=!1,t.queueRerender()}onDrop(t){if(this.applied)for(const e of this.toRemove)t.image.onDestroyElement(e)}description(t,e){var n;if(0===this.toRemove.length)return e.erasedNoElements;const r=null!==(n=Dt(e,this.toRemove))&&void 0!==n?n:e.elements;return e.eraseAction(r,this.toRemove.length)}serializeToJSON(){return this.toRemove.map((t=>t.getId()))}}T.register("erase",((t,e)=>{const n=t.map((t=>e.image.lookupElement(t))).filter((t=>null!==t));return new Ot(n)}));class $t extends G{constructor(t,e){super(t.notifier,e),this.editor=t,this.command=null}onPointerDown(t){return(1===t.allPointers.length||t.current.device===O.Eraser)&&(this.lastPoint=t.current.canvasPos,this.toRemove=[],!0)}onPointerMove(t){var e;const n=t.current.canvasPos;if(0===n.minus(this.lastPoint).magnitude())return;const r=new B(this.lastPoint,n),i=r.bbox;this.toRemove.push(...this.editor.image.getElementsIntersectingRegion(i).filter((t=>t.intersects(r)))),null===(e=this.command)||void 0===e||e.unapply(this.editor),this.command=new Ot(this.toRemove),this.command.apply(this.editor),this.lastPoint=n}onPointerUp(t){var e;this.command&&this.toRemove.length>0&&(null===(e=this.command)||void 0===e||e.unapply(this.editor),this.editor.dispatch(this.command)),this.command=null}onGestureCancel(){var t;null===(t=this.command)||void 0===t||t.unapply(this.editor),this.command=null}}class Nt extends T{constructor(t){super("duplicate"),this.toDuplicate=t,this.duplicates=t.map((t=>t.clone())),this.reverse=new Ot(this.duplicates)}apply(t){this.reverse.unapply(t)}unapply(t){this.reverse.apply(t)}description(t,e){var n;return 0===this.duplicates.length?e.duplicatedNoElements:e.duplicateAction(null!==(n=Dt(e,this.duplicates))&&void 0!==n?n:e.elements,this.duplicates.length)}serializeToJSON(){return this.toDuplicate.map((t=>t.getId()))}}T.register("duplicate",((t,e)=>{const n=t.map((t=>e.image.lookupElement(t)));return new Nt(n)}));var jt=function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{l(r.next(t))}catch(t){o(t)}}function a(t){try{l(r.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}l((r=r.apply(t,e||[])).next())}))};class Ft extends z{constructor(t){var e,n,r;super("image-component"),this.image=Object.assign(Object.assign({},t),{label:null!==(r=null!==(n=null!==(e=t.label)&&void 0!==e?e:t.image.getAttribute("alt"))&&void 0!==n?n:t.image.getAttribute("aria-label"))&&void 0!==r?r:void 0});void 0===t.image.getAttribute("src")||t.image.complete||(t.image.onload=()=>this.recomputeBBox()),this.recomputeBBox()}getImageRect(){return new R(0,0,this.image.image.width,this.image.image.height)}recomputeBBox(){this.contentBBox=this.getImageRect(),this.contentBBox=this.contentBBox.transformedBoundingBox(this.image.transform)}static fromImage(t,e){var n;return jt(this,void 0,void 0,(function*(){let r,i,o;t.complete||(yield new Promise(((e,n)=>{t.onload=e,t.onerror=n,t.onabort=n}))),"number"==typeof t.width&&"number"==typeof t.height&&0!==t.width&&0!==t.height?(r=t.width,i=t.height):(r=t.clientWidth,i=t.clientHeight);let s=null!==(n=t.src)&&void 0!==n?n:"";if(s.startsWith("data:image/"))o=new Image,o.src=s,o.width=r,o.height=i;else{const e=document.createElement("canvas");e.width=r,e.height=i;e.getContext("2d").drawImage(t,0,0,e.width,e.height),s=e.toDataURL(),o=e}return new Ft({image:o,base64Url:s,transform:e})}))}render(t,e){t.drawImage(this.image)}intersects(t){const e=this.getImageRect().getEdges().map((t=>t.transformedBy(this.image.transform)));for(const n of e)if(n.intersects(t))return!0;return!1}serializeToJSON(){return{src:this.image.base64Url,label:this.image.label,width:this.image.image.width,height:this.image.image.height,transform:this.image.transform.toArray()}}applyTransformation(t){this.image.transform=t.rightMul(this.image.transform),this.recomputeBBox()}description(t){return this.image.label?t.imageNode(this.image.label):t.unlabeledImageNode}createClone(){return new Ft(Object.assign({},this.image))}static deserializeFromJSON(t){if("string"!=typeof t.src)throw new Error(`${t} has invalid format! Expected src property.`);const e=new Image;return e.src=t.src,e.width=t.width,e.height=t.height,new Ft({image:e,base64Url:e.src,label:t.label,transform:new P(...t.transform)})}}z.registerComponent("image-component",Ft.deserializeFromJSON);const Ut="svg-global-attributes";class Vt extends z{constructor(t){super(Ut),this.attrs=t,this.contentBBox=R.empty}render(t,e){if(t instanceof te)for(const[e,n]of this.attrs)t.setRootSVGAttribute(e,n)}intersects(t){return!1}applyTransformation(t){}createClone(){return new Vt(this.attrs)}description(t){return t.svgObject}serializeToJSON(){return JSON.stringify(this.attrs)}static deserializeFromString(t){const e=JSON.parse(t),n=[],r=/^[ \t\n0-9.-eE]+$/;for(const[t,i]of e)"viewBox"!==t&&"width"!==t&&"height"!==t||i&&r.exec(i)&&n.push([t,i]);return new Vt(n)}}z.registerComponent(Ut,Vt.deserializeFromString);const Wt="text";class Ht extends z{constructor(t,e,n,r=Ht.getTextDimens){super(Wt),this.textObjects=t,this.transform=e,this.style=n,this.getTextDimens=r,this.recomputeBBox()}static applyTextStyles(t,e){var n,r;const i=e.fontFamily.match(/\s/)?e.fontFamily.replace(/["]/g,'\\"'):e.fontFamily;t.font=[(null!==(n=e.size)&&void 0!==n?n:12)+"px",null!==(r=e.fontWeight)&&void 0!==r?r:"",`${i}`,e.fontWeight].join(" "),t.textAlign="left"}static getTextDimens(t,e){var n;null!==(n=Ht.textMeasuringCtx)&&void 0!==n||(Ht.textMeasuringCtx=document.createElement("canvas").getContext("2d"));const r=Ht.textMeasuringCtx;Ht.applyTextStyles(r,e);const i=r.measureText(t),o=-i.actualBoundingBoxAscent,s=i.actualBoundingBoxAscent+i.actualBoundingBoxDescent;return new R(0,o,i.width,s)}computeBBoxOfPart(t){if("string"==typeof t){return this.getTextDimens(t,this.style).transformedBoundingBox(this.transform)}return t.contentBBox.transformedBoundingBox(this.transform)}recomputeBBox(){let t=null;for(const e of this.textObjects){const n=this.computeBBoxOfPart(e);null!=t||(t=n),t=t.union(n)}this.contentBBox=null!=t?t:R.empty}render(t,e){const n=this.transform;t.startObject(this.contentBBox);for(const e of this.textObjects)"string"==typeof e?t.drawText(e,n,this.style):(t.pushTransform(n),e.render(t),t.popTransform());t.endObject(this.getLoadSaveData())}intersects(t){const e=this.transform.inverse(),n=e.transformVec2(t.p1),r=e.transformVec2(t.p2);t=new B(n,r);for(const e of this.textObjects)if("string"==typeof e){if(Ht.getTextDimens(e,this.style).getEdges().some((e=>null!==t.intersection(e))))return!0}else if(e.intersects(t))return!0;return!1}applyTransformation(t){this.transform=t.rightMul(this.transform),this.recomputeBBox()}createClone(){return new Ht(this.textObjects,this.transform,this.style)}getText(){const t=[];for(const e of this.textObjects)"string"==typeof e?t.push(e):t.push(e.getText());return t.join(" ")}description(t){return t.text(this.getText())}serializeToJSON(){const t=Object.assign(Object.assign({},this.style),{renderingStyle:zt(this.style.renderingStyle)});return{textObjects:this.textObjects.map((t=>"string"==typeof t?{text:t}:{json:t.serializeToJSON()})),transform:this.transform.toArray(),style:t}}static deserializeFromString(t,e=Ht.getTextDimens){const n={renderingStyle:Bt(t.style.renderingStyle),size:t.style.size,fontWeight:t.style.fontWeight,fontVariant:t.style.fontVariant,fontFamily:t.style.fontFamily},r=t.textObjects.map((t=>{var e;return null!==(null!==(e=t.text)&&void 0!==e?e:null)?t.text:Ht.deserializeFromString(t.json)}));if(t.transform=t.transform.filter((t=>"number"==typeof t)),9!==t.transform.length)throw new Error(`Unable to deserialize transform, ${t.transform}.`);const i=t.transform,o=new P(...i);return new Ht(r,o,n,e)}}z.registerComponent(Wt,(t=>Ht.deserializeFromString(t)));const Gt="unknown-svg-object";class _t extends z{constructor(t){super(Gt),this.svgObject=t,this.contentBBox=R.of(t.getBoundingClientRect())}render(t,e){t instanceof te&&t.drawSVGElem(this.svgObject)}intersects(t){return this.contentBBox.getEdges().some((e=>null!==e.intersection(t)))}applyTransformation(t){}createClone(){return new _t(this.svgObject.cloneNode(!0))}description(t){return t.svgObject}serializeToJSON(){return JSON.stringify({html:this.svgObject.outerHTML})}}z.registerComponent(Gt,null);var Zt=function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{l(r.next(t))}catch(t){o(t)}}function a(t){try{l(r.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}l((r=r.apply(t,e||[])).next())}))};const qt=new R(0,0,500,500),Kt="svgAttrs",Xt="svgStyleAttrs";class Jt{constructor(t,e,n=!0){this.source=t,this.onFinish=e,this.storeUnknown=n,this.onAddComponent=null,this.onProgress=null,this.onDetermineExportRect=null,this.processedCount=0,this.totalToProcess=0}getStyle(t){var e,n,r;const i={fill:Et.transparent},o=null!==(e=t.getAttribute("fill"))&&void 0!==e?e:t.style.fill;if(o)try{i.fill=Et.fromString(o)}catch(t){console.error("Unknown fill color,",o)}const s=null!==(n=t.getAttribute("stroke"))&&void 0!==n?n:t.style.stroke,a=null!==(r=t.getAttribute("stroke-width"))&&void 0!==r?r:t.style.strokeWidth;if(s)try{let t=parseFloat(null!=a?a:"1");isFinite(t)||(t=0),i.stroke={width:t,color:Et.fromString(s)}}catch(t){console.error("Error parsing stroke data:",t)}return i}strokeDataFromElem(t){var e;const n=[],r=null!==(e=t.getAttribute("d"))&&void 0!==e?e:"",i=this.getStyle(t),o=r.split("M");let s=!0;for(const t of o){const e=/^[0-9., \t\n]+$/.exec(t);if(""!==t&&!e){const e=s?t:`M${t}`,r=St.fromString(e).toRenderable(i);n.push(r)}s=!1}return n}attachUnrecognisedAttrs(t,e,n,r){if(this.storeUnknown){for(const i of e.getAttributeNames())n.has(i)||"style"===i&&r||t.attachLoadSaveData(Kt,[i,e.getAttribute(i)]);if(r)for(const n of e.style)""!==n&&n&&(r.has(n)||t.attachLoadSaveData(Xt,{key:n,value:e.style.getPropertyValue(n),priority:e.style.getPropertyPriority(n)}))}}addPath(t){var e;let n;try{const e=this.strokeDataFromElem(t);n=new Rt(e);const r=["stroke","fill","stroke-width"];this.attachUnrecognisedAttrs(n,t,new Set([...r,"d"]),new Set(r))}catch(e){if(console.error("Invalid path in node",t,"\nError:",e,"\nAdding as an unknown object."),!this.storeUnknown)return;n=new _t(t)}null===(e=this.onAddComponent)||void 0===e||e.call(this,n)}getTransform(t,e,n){null!=n||(n=window.getComputedStyle(t));let r,i=n.transform;""!==i&&"none"!==i||(i=t.style.transform||"none");try{r=P.fromCSSMatrix(t.style.transform)}catch(t){r=P.fromCSSMatrix(i)}const o=t.getAttribute("x"),s=t.getAttribute("y");if(o&&s){const t=parseFloat(o),n=parseFloat(s);isNaN(t)||isNaN(n)||(null==e||e.push("x","y"),r=r.rightMul(P.translation(k.of(t,n))))}return r}makeText(t){var e;const n=[];for(const r of t.childNodes)if(r.nodeType===Node.TEXT_NODE)n.push(null!==(e=r.nodeValue)&&void 0!==e?e:"");else{if(r.nodeType!==Node.ELEMENT_NODE)throw new Error(`Unrecognized text child node: ${r}.`);{const t=r;if("tspan"!==t.tagName.toLowerCase())throw new Error(`Unrecognized text child element: ${t}`);n.push(this.makeText(t))}}const r=window.getComputedStyle(t),i=/^([-0-9.e]+)px/i.exec(r.fontSize),o=["fontFamily","fill","transform"];let s=12;i&&(o.push("fontSize"),s=parseFloat(i[1]));const a={size:s,fontFamily:r.fontFamily||t.style.fontFamily||"sans-serif",renderingStyle:{fill:Et.fromString(r.fill)}},l=[],c=this.getTransform(t,l,r),h=new Ht(n,c,a);return this.attachUnrecognisedAttrs(h,t,new Set(l),new Set(o)),h}addText(t){var e;try{const n=this.makeText(t);null===(e=this.onAddComponent)||void 0===e||e.call(this,n)}catch(e){console.error("Invalid text object in node",t,". Continuing.... Error:",e),this.addUnknownNode(t)}}addImage(t){var e,n;return Zt(this,void 0,void 0,(function*(){const r=new Image;r.src=null!==(e=t.getAttribute("xlink:href"))&&void 0!==e?e:t.href.baseVal;try{const e=[],i=this.getTransform(t,e),o=yield Ft.fromImage(r,i);this.attachUnrecognisedAttrs(o,t,new Set(e),new Set(["transform"])),null===(n=this.onAddComponent)||void 0===n||n.call(this,o)}catch(e){console.error("Error loading image:",e,". Element: ",t,". Continuing..."),this.addUnknownNode(t)}}))}addUnknownNode(t){var e;if(this.storeUnknown){const n=new _t(t);null===(e=this.onAddComponent)||void 0===e||e.call(this,n)}}updateViewBox(t){var e;const n=t.getAttribute("viewBox");if(this.rootViewBox||!n)return;const r=n.split(/[ \t\n,]+/),i=parseFloat(r[0]),o=parseFloat(r[1]),s=parseFloat(r[2]),a=parseFloat(r[3]);isNaN(i)||isNaN(o)||isNaN(s)||isNaN(a)?console.warn(`node ${t} has an unparsable viewbox. Viewbox: ${n}. Match: ${r}.`):(this.rootViewBox=new R(i,o,s,a),null===(e=this.onDetermineExportRect)||void 0===e||e.call(this,this.rootViewBox))}updateSVGAttrs(t){var e;this.storeUnknown&&(null===(e=this.onAddComponent)||void 0===e||e.call(this,new Vt(this.getSourceAttrs(t))))}visit(t){var e;return Zt(this,void 0,void 0,(function*(){this.totalToProcess+=t.childElementCount;let n=!0;switch(t.tagName.toLowerCase()){case"g":break;case"path":this.addPath(t);break;case"text":this.addText(t),n=!1;break;case"image":yield this.addImage(t),n=!1;break;case"svg":this.updateViewBox(t),this.updateSVGAttrs(t);break;default:return console.warn("Unknown SVG element,",t),t instanceof SVGElement||console.warn("Element",t,"is not an SVGElement!",this.storeUnknown?"Continuing anyway.":"Skipping."),void this.addUnknownNode(t)}if(n)for(const e of t.children)yield this.visit(e);this.processedCount++,yield null===(e=this.onProgress)||void 0===e?void 0:e.call(this,this.processedCount,this.totalToProcess)}))}getSourceAttrs(t){return t.getAttributeNames().map((e=>[e,t.getAttribute(e)]))}start(t,e,n=null){var r,i;return Zt(this,void 0,void 0,(function*(){this.onAddComponent=t,this.onProgress=e,this.onDetermineExportRect=n,this.totalToProcess=this.source.childElementCount,this.processedCount=0,this.rootViewBox=null,yield this.visit(this.source);this.rootViewBox||null===(r=this.onDetermineExportRect)||void 0===r||r.call(this,qt),null===(i=this.onFinish)||void 0===i||i.call(this)}))}static fromString(t,e=!1){var n,r;const i=document.createElement("iframe");if(i.src="about:blank",i.setAttribute("sandbox","allow-same-origin"),i.setAttribute("csp","default-src 'about:blank'"),i.style.display="none",document.body.appendChild(i),!i.hasAttribute("sandbox"))throw i.remove(),new Error("SVG loading iframe is not sandboxed.");const o=null!==(r=null===(n=i.contentWindow)||void 0===n?void 0:n.document)&&void 0!==r?r:i.contentDocument;if(null==o)throw new Error("Unable to open a sandboxed iframe!");o.open(),o.write("\n\t\t\t<!DOCTYPE html>\n\t\t\t<html>\n\t\t\t\t<head>\n\t\t\t\t\t<title>SVG Loading Sandbox</title>\n\t\t\t\t</head>\n\t\t\t\t<body>\n\t\t\t\t\t<script>\n\t\t\t\t\t\tconsole.error('JavaScript should not be able to run here!');\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'The SVG sandbox is broken! Please double-check the sandboxing setting.'\n\t\t\t\t\t\t);\n\t\t\t\t\t<\/script>\n\t\t\t\t</body>\n\t\t\t</html>\n\t\t"),o.close();const s=o.createElementNS("http://www.w3.org/2000/svg","svg");return s.innerHTML=t,o.body.appendChild(s),new Jt(s,(()=>{s.remove(),i.remove()}),!e)}}class Yt{constructor(t){this.viewport=t,this.selfTransform=null,this.transformStack=[],this.objectLevel=0,this.currentPaths=null}getViewport(){return this.viewport}setDraftMode(t){}flushPath(){if(!this.currentPaths)return;let t=null;for(const e of this.currentPaths){const{startPoint:n,commands:r,style:i}=e;t&&Pt(t,i)?this.moveTo(n):(t&&this.endPath(t),this.beginPath(n),t=i);for(const t of r)t.kind===kt.LineTo?this.lineTo(t.point):t.kind===kt.MoveTo?this.moveTo(t.point):t.kind===kt.CubicBezierTo?this.traceCubicBezierCurve(t.controlPoint1,t.controlPoint2,t.endPoint):t.kind===kt.QuadraticBezierTo&&this.traceQuadraticBezierCurve(t.controlPoint,t.endPoint)}t&&this.endPath(t)}drawPath(t){0===this.objectLevel?(this.currentPaths=[t],this.flushPath(),this.currentPaths=null):this.currentPaths.push(t)}drawRect(t,e,n){const r=St.fromRect(t,e);this.drawPath(r.toRenderable(n))}startObject(t,e){this.currentPaths=[],this.objectLevel++}endObject(t){if(this.flushPath(),this.currentPaths=null,this.objectLevel--,this.objectLevel<0)throw new Error("More objects have ended than have been started (negative object nesting level)!")}getNestingLevel(){return this.objectLevel}canRenderFromWithoutDataLoss(t){return!1}renderFromOtherOfSameType(t,e){throw new Error(`Unable to render from ${e}: Not implemented`)}setTransform(t){this.selfTransform=t}pushTransform(t){this.transformStack.push(this.selfTransform),this.setTransform(this.getCanvasToScreenTransform().rightMul(t))}popTransform(){var t;if(0===this.transformStack.length)throw new Error("Unable to pop more transforms than have been pushed!");this.setTransform(null!==(t=this.transformStack.pop())&&void 0!==t?t:null)}getCanvasToScreenTransform(){return this.selfTransform?this.selfTransform:this.viewport.canvasToScreenTransform}canvasToScreen(t){return this.getCanvasToScreenTransform().transformVec2(t)}getSizeOfCanvasPixelOnScreen(){return this.getCanvasToScreenTransform().transformVec3(k.unitX).length()}}const Qt="http://www.w3.org/2000/svg";class te extends Yt{constructor(t,e,n=!1){super(e),this.elem=t,this.sanitize=n,this.lastPathStyle=null,this.lastPathString=[],this.objectElems=null,this.overwrittenAttrs={},this.clear()}setRootSVGAttribute(t,e){this.sanitize||(t in this.overwrittenAttrs||(this.overwrittenAttrs[t]=this.elem.getAttribute(t)),null!==e?this.elem.setAttribute(t,e):this.elem.removeAttribute(t))}displaySize(){return k.of(this.elem.clientWidth,this.elem.clientHeight)}clear(){if(this.lastPathString=[],!this.sanitize){for(const t in this.overwrittenAttrs){const e=this.overwrittenAttrs[t];e?this.elem.setAttribute(t,e):this.elem.removeAttribute(t)}this.overwrittenAttrs={}}}addPathToSVG(){var t;if(!this.lastPathStyle||0===this.lastPathString.length)return;const e=document.createElementNS(Qt,"path");e.setAttribute("d",this.lastPathString.join(" "));const n=this.lastPathStyle;e.setAttribute("fill",n.fill.toHexString()),n.stroke&&(e.setAttribute("stroke",n.stroke.color.toHexString()),e.setAttribute("stroke-width",n.stroke.width.toString())),this.elem.appendChild(e),null===(t=this.objectElems)||void 0===t||t.push(e)}drawPath(t){var e;const n=t.style,r=St.fromRenderable(t);n.fill.eq(null===(e=this.lastPathStyle)||void 0===e?void 0:e.fill)&&0!==this.lastPathString.length||(this.addPathToSVG(),this.lastPathStyle=n,this.lastPathString=[]),this.lastPathString.push(r.toString())}transformFrom(t,e){let n=this.getCanvasToScreenTransform().rightMul(t);const r=n.transformVec2(k.zero);n=n.rightMul(P.translation(r.times(-1))),e.style.transform=`matrix(\n\t\t\t${n.a1}, ${n.b1},\n\t\t\t${n.a2}, ${n.b2},\n\t\t\t${n.a3}, ${n.b3}\n\t\t)`,e.setAttribute("x",`${yt(r.x)}`),e.setAttribute("y",`${yt(r.y)}`)}drawText(t,e,n){var r,i,o;const s=document.createElementNS(Qt,"text");if(s.appendChild(document.createTextNode(t)),this.transformFrom(e,s),s.style.fontFamily=n.fontFamily,s.style.fontVariant=null!==(r=n.fontVariant)&&void 0!==r?r:"",s.style.fontWeight=null!==(i=n.fontWeight)&&void 0!==i?i:"",s.style.fontSize=n.size+"px",s.style.fill=n.renderingStyle.fill.toHexString(),n.renderingStyle.stroke){const t=n.renderingStyle.stroke;s.style.stroke=t.color.toHexString(),s.style.strokeWidth=t.width+"px"}this.elem.appendChild(s),null===(o=this.objectElems)||void 0===o||o.push(s)}drawImage(t){var e,n,r,i,o;const s=document.createElementNS(Qt,"image");s.setAttribute("href",t.base64Url),s.setAttribute("width",null!==(e=t.image.getAttribute("width"))&&void 0!==e?e:""),s.setAttribute("height",null!==(n=t.image.getAttribute("height"))&&void 0!==n?n:""),s.setAttribute("aria-label",null!==(i=null!==(r=t.image.getAttribute("aria-label"))&&void 0!==r?r:t.image.getAttribute("alt"))&&void 0!==i?i:""),this.transformFrom(t.transform,s),this.elem.appendChild(s),null===(o=this.objectElems)||void 0===o||o.push(s)}startObject(t){super.startObject(t),this.lastPathString=[],this.lastPathStyle=null,this.objectElems=[]}endObject(t){var e;if(super.endObject(t),this.addPathToSVG(),t&&!this.sanitize)for(const n of null!==(e=this.objectElems)&&void 0!==e?e:[]){const e=t.svgAttrs,r=t.svgStyleAttrs;if(e)for(const[t,r]of e)n.setAttribute(t,r);if(r)for(const t of r)n.style.setProperty(t.key,t.value,t.priority)}}unimplementedMessage(){throw new Error("Not implemenented!")}beginPath(t){this.unimplementedMessage()}endPath(t){this.unimplementedMessage()}lineTo(t){this.unimplementedMessage()}moveTo(t){this.unimplementedMessage()}traceCubicBezierCurve(t,e,n){this.unimplementedMessage()}traceQuadraticBezierCurve(t,e){this.unimplementedMessage()}drawPoints(...t){t.map((t=>{const e=document.createElementNS(Qt,"circle");e.setAttribute("cx",`${t.x}`),e.setAttribute("cy",`${t.y}`),e.setAttribute("r","15"),this.elem.appendChild(e)}))}drawSVGElem(t){this.sanitize||this.elem.appendChild(t.cloneNode(!0))}isTooSmallToRender(t){return!1}}var ee,ne=function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{l(r.next(t))}catch(t){o(t)}}function a(t){try{l(r.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}l((r=r.apply(t,e||[])).next())}))};const re=30,ie=(t,e,n)=>{t.style.touchAction="none";let r,i,o=!1;t.addEventListener("touchstart",(t=>t.preventDefault())),t.addEventListener("pointerdown",(e=>!!e.isPrimary&&(o=!0,t.setPointerCapture(e.pointerId),r=e.pageX,i=e.pageY,!0))),t.addEventListener("pointermove",(t=>{if(t.isPrimary&&o){const n=k.of(t.pageX-r,t.pageY-i);return e(n,k.of(t.offsetX,t.offsetY)),r=t.pageX,i=t.pageY,!0}return!1}));const s=t=>!!t.isPrimary&&(o=!1,n(),!0);t.addEventListener("pointerup",s),t.addEventListener("pointercancel",s)};class oe{constructor(t,e){this.startPoint=t,this.editor=e,this.boxRotation=this.editor.viewport.getRotationAngle(),this.selectedElems=[],this.region=R.bboxOf([t]),this.backgroundBox=document.createElement("div");const n=document.createElement("div"),r=document.createElement("div");this.rotateCircle=document.createElement("div");const i=document.createElement("div");this.backgroundBox.classList.add("selectionBox"),n.classList.add("draggableBackground"),r.classList.add("resizeCorner"),this.rotateCircle.classList.add("rotateCircle"),i.classList.add("rotateCircleContainer"),i.appendChild(this.rotateCircle),this.backgroundBox.appendChild(n),this.backgroundBox.appendChild(i),this.backgroundBox.appendChild(r),this.transformationCommands=[],this.transform=P.identity,ie(n,(t=>{this.handleBackgroundDrag(t)}),(()=>this.finalizeTransform())),ie(r,(t=>{this.handleResizeCornerDrag(t)}),(()=>this.finalizeTransform())),ie(this.rotateCircle,((t,e)=>{this.handleRotateCircleDrag(e)}),(()=>this.finalizeTransform()))}handleBackgroundDrag(t){t=this.editor.viewport.screenToCanvasTransform.transformVec3(t),t=this.editor.viewport.roundPoint(t),this.transformPreview(P.translation(t))}handleResizeCornerDrag(t){t=this.editor.viewport.screenToCanvasTransform.transformVec3(t),t=this.editor.viewport.roundPoint(t);const e=this.region.w,n=this.region.h,r=this.region.size.plus(t);if(r.y>0&&r.x>0){const t=k.of(r.x/e,r.y/n);this.transformPreview(P.scaling2D(t,this.region.topLeft))}}handleRotateCircleDrag(t){let e=t.angle();e%=2*Math.PI,e<0&&(e+=2*Math.PI);let n=e-this.boxRotation;const r=Math.PI/12;if(!(Math.abs(n)<r)&&isFinite(n)){{const t=Math.sign(n);n=Math.floor(Math.abs(n)/r)*r,n*=t}this.transformPreview(P.zRotation(n,this.region.center))}}computeTransformCommands(){return this.selectedElems.map((t=>t.transformBy(this.transform)))}transformPreview(t){this.transform=this.transform.rightMul(t);const e=t.transformVec3(k.unitX).angle();t=t.rightMul(P.zRotation(-e,this.region.center)),this.boxRotation+=e,this.boxRotation=this.boxRotation%(2*Math.PI),this.boxRotation<0&&(this.boxRotation+=2*Math.PI);const n=t.transformVec3(this.region.size),r=t.transformVec2(this.region.topLeft).minus(this.region.topLeft);this.region=this.region.resizedTo(n),this.region=this.region.translatedBy(r),this.previewTransformCmds(),this.scrollTo()}finalizeTransform(){this.transformationCommands.forEach((t=>{t.unapply(this.editor)}));const t=this.transform,e=this.transform.inverse(),n=this.boxRotation,r=this.computeTransformCommands();this.transformationCommands=[],this.transform=P.identity,this.region=this.region.transformedBoundingBox(e),this.editor.dispatch(new oe.ApplyTransformationCommand(this,r,t,n))}previewTransformCmds(){this.selectedElems.length>100||(this.transformationCommands.forEach((t=>t.unapply(this.editor))),this.transformationCommands=this.computeTransformCommands(),this.transformationCommands.forEach((t=>t.apply(this.editor)))),this.updateUI()}appendBackgroundBoxTo(t){this.backgroundBox.parentElement&&this.backgroundBox.remove(),t.appendChild(this.backgroundBox)}setToPoint(t){this.region=this.region.grownToPoint(t),this.recomputeBoxRotation(),this.updateUI()}cancelSelection(){this.backgroundBox.parentElement&&this.backgroundBox.remove(),this.region=R.empty}setSelectedObjects(t,e){this.region=e,this.selectedElems=t,this.updateUI()}getSelectedObjects(){return this.selectedElems}resolveToObjects(){if(0===this.region.w||0===this.region.h){const t=this.editor.viewport.visibleRect.maxDimension/100;this.region=R.bboxOf(this.region.corners,t)}return this.selectedElems=this.editor.image.getElementsIntersectingRegion(this.region).filter((t=>{if(this.region.containsRect(t.getBBox()))return!0;const e=[];for(const t of this.region.divideIntoGrid(2,2))e.push(...t.getEdges());return e.some((e=>t.intersects(e)))})),!!this.recomputeRegion()&&(this.updateUI(),!0)}recomputeRegion(){const t=this.selectedElems.reduce(((t,e)=>(null!=t?t:e.getBBox()).union(e.getBBox())),null);if(!t)return this.cancelSelection(),!1;this.region=t;const e=this.getMinCanvasSize();if(this.region.w<e||this.region.h<e){const t=e/2;this.region=R.bboxOf(this.region.corners,t)}return this.recomputeBoxRotation(),!0}getMinCanvasSize(){return 2*(re/this.editor.viewport.getScaleFactor())}recomputeBoxRotation(){this.boxRotation=this.editor.viewport.getRotationAngle()}getSelectedItemCount(){return this.selectedElems.length}updateUI(){if(!this.backgroundBox)return;const t=this.region.topRight.minus(this.region.bottomRight),e=this.region.topLeft.minus(this.region.topRight),n=this.editor.viewport.canvasToScreenTransform,r=n.transformVec2(this.region.center),i=n.transformVec3(t).magnitude(),o=n.transformVec3(e).magnitude();this.backgroundBox.style.marginLeft=r.x-o/2+"px",this.backgroundBox.style.marginTop=r.y-i/2+"px",this.backgroundBox.style.width=`${o}px`,this.backgroundBox.style.height=`${i}px`;const s=180*this.boxRotation/Math.PI;this.backgroundBox.style.transform=`rotate(${s}deg)`,this.rotateCircle.style.transform=`rotate(${-s}deg)`}scrollTo(){const t=this.editor.viewport.visibleRect;if(!t.containsPoint(this.region.center)){const e=t.getClosestPointOnBoundaryTo(this.region.center),n=this.region.center.minus(e);this.editor.dispatchNoAnnounce(H.transformBy(P.translation(n.times(-1))),!1)}}deleteSelectedObjects(){return new Ot(this.selectedElems)}duplicateSelectedObjects(){return new Nt(this.selectedElems)}}ee=oe,T.register("selection-tool-transform",((t,e)=>{const n=new P(...t.transform),r=t.commands.map((t=>T.deserialize(t,e)));return new ee.ApplyTransformationCommand(null,r,n,0)})),oe.ApplyTransformationCommand=class extends T{constructor(t,e,n,r){super("selection-tool-transform"),this.selection=t,this.currentTransfmCommands=e,this.fullTransform=n,this.deltaBoxRotation=r}apply(t){var e,n;return ne(this,void 0,void 0,(function*(){this.selection&&(this.selection.region=this.selection.region.transformedBoundingBox(this.fullTransform),this.selection.boxRotation+=this.deltaBoxRotation,this.selection.updateUI()),yield t.asyncApplyCommands(this.currentTransfmCommands,100),null===(e=this.selection)||void 0===e||e.recomputeRegion(),null===(n=this.selection)||void 0===n||n.updateUI()}))}unapply(t){var e,n;return ne(this,void 0,void 0,(function*(){this.selection&&(this.selection.region=this.selection.region.transformedBoundingBox(this.fullTransform.inverse()),this.selection.boxRotation-=this.deltaBoxRotation,this.selection.updateUI()),yield t.asyncUnapplyCommands(this.currentTransfmCommands,100),null===(e=this.selection)||void 0===e||e.recomputeRegion(),null===(n=this.selection)||void 0===n||n.updateUI()}))}serializeToJSON(){return{commands:this.currentTransfmCommands.map((t=>t.serialize())),transform:this.fullTransform.toArray()}}description(t,e){return e.transformedElements(this.currentTransfmCommands.length)}};class se extends G{constructor(t,e){super(t.notifier,e),this.editor=t,this.handleOverlay=document.createElement("div"),t.createHTMLOverlay(this.handleOverlay),t.addStyleSheet("\n\t.handleOverlay {\n\t}\n\n\t.handleOverlay > .selectionBox {\n\t\tposition: absolute;\n\t\tz-index: 0;\n\t\ttransform-origin: center;\n\t}\n\n\t.handleOverlay > .selectionBox .draggableBackground {\n\t\tposition: absolute;\n\t\ttop: 0;\n\t\tleft: 0;\n\t\tright: 0;\n\t\tbottom: 0;\n\n\t\tbackground-color: var(--secondary-background-color);\n\t\topacity: 0.8;\n\t\tborder: 1px solid var(--primary-background-color);\n\t}\n\n\t.handleOverlay .resizeCorner {\n\t\twidth: 30px;\n\t\theight: 30px;\n\t\tmargin-right: -15px;\n\t\tmargin-bottom: -15px;\n\n\t\tposition: absolute;\n\t\tbottom: 0;\n\t\tright: 0;\n\n\t\topacity: 0.8;\n\t\tbackground-color: var(--primary-background-color);\n\t\tborder: 1px solid var(--primary-foreground-color);\n\t}\n\n\t.handleOverlay > .selectionBox .rotateCircleContainer {\n\t\tposition: absolute;\n\t\ttop: 50%;\n\t\tbottom: 50%;\n\t\tleft: 50%;\n\t\tright: 50%;\n\t}\n\n\t.handleOverlay .rotateCircle {\n\t\twidth: 30px;\n\t\theight: 30px;\n\t\tmargin-left: -15px;\n\t\tmargin-top: -15px;\n\t\topacity: 0.8;\n\n\t\tborder: 1px solid var(--primary-foreground-color);\n\t\tbackground-color: var(--primary-background-color);\n\t\tborder-radius: 100%;\n\t}\n"),this.handleOverlay.style.display="none",this.handleOverlay.classList.add("handleOverlay"),t.notifier.on(D.ViewportChanged,(t=>{var e,n;null===(e=this.selectionBox)||void 0===e||e.recomputeRegion(),null===(n=this.selectionBox)||void 0===n||n.updateUI()})),this.editor.handleKeyEventsFrom(this.handleOverlay)}makeSelectionBox(t){this.prevSelectionBox=this.selectionBox,this.selectionBox=new oe(t,this.editor),this.handleOverlay.replaceChildren(),this.selectionBox.appendBackgroundBoxTo(this.handleOverlay)}onPointerDown(t){return!(1!==t.allPointers.length||!t.current.isPrimary)&&(this.makeSelectionBox(t.current.canvasPos),!0)}onPointerMove(t){this.selectionBox&&this.selectionBox.setToPoint(t.current.canvasPos)}onGestureEnd(){if(!this.selectionBox)return;const t=this.selectionBox.resolveToObjects();this.editor.notifier.dispatch(D.ToolUpdated,{kind:D.ToolUpdated,tool:this}),t&&(this.editor.announceForAccessibility(this.editor.localization.selectedElements(this.selectionBox.getSelectedItemCount())),this.zoomToSelection())}zoomToSelection(){if(this.selectionBox){const t=this.selectionBox.region;this.editor.dispatchNoAnnounce(this.editor.viewport.zoomTo(t,!1),!1)}}onPointerUp(t){this.selectionBox&&(this.selectionBox.setToPoint(t.current.canvasPos),this.onGestureEnd())}onGestureCancel(){var t,e;null===(t=this.selectionBox)||void 0===t||t.cancelSelection(),this.selectionBox=this.prevSelectionBox,null===(e=this.selectionBox)||void 0===e||e.appendBackgroundBoxTo(this.handleOverlay)}onKeyPress(t){let e=0,n=0,r=0,i=0,o=0;switch(t.key){case"a":case"h":case"ArrowLeft":n-=1;break;case"d":case"l":case"ArrowRight":n+=1;break;case"q":case"k":case"ArrowUp":r-=1;break;case"e":case"j":case"ArrowDown":r+=1;break;case"r":e+=1;break;case"R":e-=1;break;case"i":i-=1;break;case"I":i+=1;break;case"o":o-=1;break;case"O":o+=1}let s=0!==n||0!==r||0!==e||0!==i||0!==o;if(this.selectionBox){if(s){const t=10*this.editor.viewport.getSizeOfPixelOnCanvas(),s=Math.PI/8,a=t/2,l=this.selectionBox.region,c=this.selectionBox.region.size.plus(k.of(i,o).times(a)),h=P.scaling2D(k.of(Math.max(.5,c.x/l.size.x),Math.max(.5,c.y/l.size.y)),l.topLeft).rightMul(P.zRotation(e*s,l.center)).rightMul(P.translation(k.of(n,r).times(t)));this.selectionBox.transformPreview(h)}}else s=!1;return!this.selectionBox||s||"Delete"!==t.key&&"Backspace"!==t.key||(this.editor.dispatch(this.selectionBox.deleteSelectedObjects()),this.clearSelection(),s=!0),s}onKeyUp(t){return!(!this.selectionBox||!se.handleableKeys.some((e=>e===t.key)))&&(this.selectionBox.finalizeTransform(),!0)}onCopy(t){if(!this.selectionBox)return!1;const e=this.selectionBox.getSelectedObjects(),n=this.selectionBox.region;if(0===e.length)return!1;const r=new H(this.editor.notifier);r.updateScreenSize(k.of(n.w,n.h)),r.resetTransform(P.translation(n.topLeft));const i=document.createElementNS("http://www.w3.org/2000/svg","svg"),o=new te(i,r,!0);for(const t of e)t.render(o);return t.setData("image/svg+xml",i.outerHTML),!0}setEnabled(t){super.setEnabled(t),this.handleOverlay.replaceChildren(),this.selectionBox=null,this.handleOverlay.style.display=t?"block":"none",t?(this.handleOverlay.tabIndex=0,this.handleOverlay.setAttribute("aria-label",this.editor.localization.selectionToolKeyboardShortcuts)):this.handleOverlay.tabIndex=-1}getSelection(){return this.selectionBox}setSelection(t){let e=null;for(const n of t)e=e?e.union(n.getBBox()):n.getBBox();e&&(this.clearSelection(),this.selectionBox||this.makeSelectionBox(e.topLeft),this.selectionBox.setSelectedObjects(t,e))}clearSelection(){this.handleOverlay.replaceChildren(),this.prevSelectionBox=this.selectionBox,this.selectionBox=null,this.editor.notifier.dispatch(D.ToolUpdated,{kind:D.ToolUpdated,tool:this})}}se.handleableKeys=["a","h","ArrowLeft","d","l","ArrowRight","q","k","ArrowUp","e","j","ArrowDown","r","R","i","I","o","O"];class ae extends G{constructor(t){super(t.notifier,t.localization.undoRedoTool),this.editor=t}onKeyPress({key:t,ctrlKey:e}){if(e){if("z"===t)return this.editor.history.undo(),!0;if("Z"===t)return this.editor.history.redo(),!0}return!1}}const le="textEditorOverlay";class ce extends G{constructor(t,e,n){super(t.notifier,e),this.editor=t,this.localizationTable=n,this.textInputElem=null,this.textTargetPosition=null,this.textMeasuringCtx=null,this.textStyle={size:32,fontFamily:"sans-serif",renderingStyle:{fill:Et.purple}},this.textEditOverlay=document.createElement("div"),this.textEditOverlay.classList.add(le),this.editor.addStyleSheet("\n\t\t\t.textEditorOverlay {\n\t\t\t\theight: 0;\n\t\t\t\toverflow: visible;\n\t\t\t}\n\n\t\t\t.textEditorOverlay input {\n\t\t\t\tbackground-color: rgba(0, 0, 0, 0);\n\t\t\t\tborder: none;\n\t\t\t\tpadding: 0;\n\t\t\t}\n\t\t"),this.editor.createHTMLOverlay(this.textEditOverlay),this.editor.notifier.on(D.ViewportChanged,(()=>this.updateTextInput()))}getTextAscent(t,e){var n;return null!==(n=this.textMeasuringCtx)&&void 0!==n||(this.textMeasuringCtx=document.createElement("canvas").getContext("2d")),this.textMeasuringCtx?(Ht.applyTextStyles(this.textMeasuringCtx,e),this.textMeasuringCtx.measureText(t).actualBoundingBoxAscent):2*e.size/3}flushInput(){if(this.textInputElem&&this.textTargetPosition){const t=this.textInputElem.value;if(this.textInputElem.remove(),this.textInputElem=null,""===t)return;const e=P.translation(this.textTargetPosition).rightMul(P.scaling2D(this.editor.viewport.getSizeOfPixelOnCanvas())).rightMul(P.zRotation(this.textRotation)),n=new Ht([t],e,this.textStyle),r=I.addElement(n);this.editor.dispatch(r)}}updateTextInput(){var t,e,n;if(!this.textInputElem||!this.textTargetPosition)return void(null===(t=this.textInputElem)||void 0===t||t.remove());const r=this.editor.viewport,i=r.canvasToScreen(this.textTargetPosition);this.textInputElem.type="text",this.textInputElem.placeholder=this.localizationTable.enterTextToInsert,this.textInputElem.style.fontFamily=this.textStyle.fontFamily,this.textInputElem.style.fontVariant=null!==(e=this.textStyle.fontVariant)&&void 0!==e?e:"",this.textInputElem.style.fontWeight=null!==(n=this.textStyle.fontWeight)&&void 0!==n?n:"",this.textInputElem.style.fontSize=`${this.textStyle.size}px`,this.textInputElem.style.color=this.textStyle.renderingStyle.fill.toHexString(),this.textInputElem.style.position="relative",this.textInputElem.style.left=`${i.x}px`,this.textInputElem.style.top=`${i.y}px`,this.textInputElem.style.margin="0";const o=this.textRotation+r.getRotationAngle(),s=this.getTextAscent(this.textInputElem.value||"W",this.textStyle);this.textInputElem.style.transform=`rotate(${180*o/Math.PI}deg) translate(0, ${-s}px)`,this.textInputElem.style.transformOrigin="top left"}startTextInput(t,e){this.flushInput(),this.textInputElem=document.createElement("input"),this.textInputElem.value=e,this.textTargetPosition=t,this.textRotation=-this.editor.viewport.getRotationAngle(),this.updateTextInput(),this.textInputElem.oninput=()=>{var t;this.textInputElem&&(this.textInputElem.size=(null===(t=this.textInputElem)||void 0===t?void 0:t.value.length)||10)},this.textInputElem.onblur=()=>{setTimeout((()=>this.flushInput()),0)},this.textInputElem.onkeyup=t=>{var e;"Enter"===t.key?(this.flushInput(),this.editor.focus()):"Escape"===t.key&&(null===(e=this.textInputElem)||void 0===e||e.remove(),this.textInputElem=null,this.editor.focus())},this.textEditOverlay.replaceChildren(this.textInputElem),setTimeout((()=>{var t;return null===(t=this.textInputElem)||void 0===t?void 0:t.focus()}),0)}setEnabled(t){super.setEnabled(t),t||this.flushInput(),this.textEditOverlay.style.display=t?"block":"none"}onPointerDown({current:t,allPointers:e}){return t.device!==O.Eraser&&(1===e.length&&(this.startTextInput(t.canvasPos,""),!0))}onGestureCancel(){this.flushInput(),this.editor.focus()}dispatchUpdateEvent(){this.updateTextInput(),this.editor.notifier.dispatch(D.ToolUpdated,{kind:D.ToolUpdated,tool:this})}setFontFamily(t){t!==this.textStyle.fontFamily&&(this.textStyle=Object.assign(Object.assign({},this.textStyle),{fontFamily:t}),this.dispatchUpdateEvent())}setColor(t){t.eq(this.textStyle.renderingStyle.fill)||(this.textStyle=Object.assign(Object.assign({},this.textStyle),{renderingStyle:Object.assign(Object.assign({},this.textStyle.renderingStyle),{fill:t})}),this.dispatchUpdateEvent())}setFontSize(t){t!==this.textStyle.size&&(this.textStyle=Object.assign(Object.assign({},this.textStyle),{size:t}),this.dispatchUpdateEvent())}getTextStyle(){return this.textStyle}}class he extends G{constructor(t,e){super(t.notifier,e),this.editor=t,this.colorPreviewListener=null,this.colorSelectListener=null}setColorListener(t,e){this.colorPreviewListener=t,this.colorSelectListener=e}clearColorListener(){this.colorPreviewListener=null,this.colorSelectListener=null}onPointerDown({current:t,allPointers:e}){return!(!this.colorPreviewListener||1!==e.length)&&(this.colorPreviewListener(this.editor.display.getColorAt(t.screenPos)),!0)}onPointerMove({current:t}){var e;null===(e=this.colorPreviewListener)||void 0===e||e.call(this,this.editor.display.getColorAt(t.screenPos))}onPointerUp({current:t}){var e;null===(e=this.colorSelectListener)||void 0===e||e.call(this,this.editor.display.getColorAt(t.screenPos))}onGestureCancel(){var t;null===(t=this.colorSelectListener)||void 0===t||t.call(this,null)}}class de extends G{constructor(t){super(t.notifier,t.localization.changeTool),this.editor=t}onKeyPress({key:t}){const e=this.editor.toolController.getPrimaryTools(),n=/^[0-9]$/.exec(t);let r;if(n){r=e[parseInt(n[0],10)-1]}return!!r&&(r.setEnabled(!0),!0)}}const ue=t=>{if(t instanceof T)return new class extends T{serializeToJSON(){return t.serialize()}apply(e){t.unapply(e)}unapply(e){t.unapply(e)}description(e,n){return n.inverseOf(t.description(e,n))}}("inverse");return new class extends w{apply(e){t.unapply(e)}unapply(e){t.apply(e)}description(e,n){return n.inverseOf(t.description(e,n))}}};T.register("inverse",((t,e)=>ue(T.deserialize(t,e))));const pe=ue;class me extends w{constructor(t,e){super(),this.commands=t,this.applyChunkSize=e}apply(t){if(void 0===this.applyChunkSize)for(const e of this.commands)e.apply(t);else t.asyncApplyCommands(this.commands,this.applyChunkSize)}unapply(t){if(void 0===this.applyChunkSize)for(const e of this.commands)e.unapply(t);else t.asyncUnapplyCommands(this.commands,this.applyChunkSize)}description(t,e){const n=[];let r=null,i=0;for(const o of this.commands){const s=o.description(t,e);s!==r&&null!==r&&(n.push(e.unionOf(r,i)),r=null,i=0),i++,null!=r||(r=s)}return i>1?n.push(e.unionOf(r,i)):1===i&&n.push(r),n.join(", ")}}class fe extends T{constructor(t,e){super("union"),this.commands=t,this.applyChunkSize=e,this.nonserializableCommand=new me(t,e)}serializeToJSON(){return{applyChunkSize:this.applyChunkSize,data:this.commands.map((t=>t.serialize()))}}apply(t){this.nonserializableCommand.apply(t)}unapply(t){this.nonserializableCommand.unapply(t)}description(t,e){return this.nonserializableCommand.description(t,e)}}const ge=(t,e)=>{let n=!0;for(const e of t)if(!(e instanceof T)){n=!1;break}if(n){return new fe(t,e)}return new me(t,e)};T.register("union",((t,e)=>{if("number"!=typeof t.data.length)throw new Error("Unions of commands must serialize to lists of serialization data.");const n=t.applyChunkSize;if("number"!=typeof n&&void 0!==n)throw new Error("serialized applyChunkSize is neither undefined nor a number.");const r=[];for(const n of t.data)r.push(T.deserialize(n,e));return ge(r,n)}));const xe=ge;var ve=function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{l(r.next(t))}catch(t){o(t)}}function a(t){try{l(r.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}l((r=r.apply(t,e||[])).next())}))};class be extends G{constructor(t){super(t.notifier,t.localization.pasteHandler),this.editor=t}onPaste(t){const e=t.mime.toLowerCase();return"image/svg+xml"===e?(this.doSVGPaste(t.data),!0):"text/plain"===e?(this.doTextPaste(t.data),!0):("image/png"===e||"image/jpeg"===e)&&(this.doImagePaste(t.data),!0)}addComponentsFromPaste(t){return ve(this,void 0,void 0,(function*(){let e=null;for(const n of t)e=e?e.union(n.getBBox()):n.getBBox();if(!e)return;const n=this.editor.viewport.visibleRect,r=n.width/e.width,i=n.height/e.height;let o=r;(e.width*o>n.width||e.height*o>n.height)&&(o=i),o*=2/3;const s=P.translation(n.center.minus(e.center)).rightMul(P.scaling2D(o,e.center)),a=[];for(const e of t)a.push(I.addElement(e)),a.push(e.transformBy(s));this.editor.dispatch(xe(a,100),!0);for(const e of this.editor.toolController.getMatchingTools(se))e.setEnabled(!0),e.setSelection(t)}))}doSVGPaste(t){return ve(this,void 0,void 0,(function*(){const e=Jt.fromString(t,!0),n=[];yield e.start((t=>{n.push(t)}),((t,e)=>null)),yield this.addComponentsFromPaste(n)}))}doTextPaste(t){var e,n;return ve(this,void 0,void 0,(function*(){const r=this.editor.toolController.getMatchingTools(ce);r.sort(((t,e)=>!t.isEnabled()&&e.isEnabled()?-1:!e.isEnabled()&&t.isEnabled()?1:0));const i={size:12,fontFamily:"sans",renderingStyle:{fill:Et.red}},o=null!==(n=null===(e=r[0])||void 0===e?void 0:e.getTextStyle())&&void 0!==n?n:i,s=t.split("\n");let a=null;const l=[];for(const t of s){let e=k.zero;if(a){const t=Math.floor(o.size);e=a.getBBox().bottomLeft.plus(k.unitY.times(t))}const n=new Ht([t],P.translation(e),o);l.push(n),a=n}1===l.length?yield this.addComponentsFromPaste([l[0]]):yield this.addComponentsFromPaste([new Ht(l,P.identity,o)])}))}doImagePaste(t){return ve(this,void 0,void 0,(function*(){const e=new Image;e.src=t;const n=yield Ft.fromImage(e,P.identity);yield this.addComponentsFromPaste([n])}))}}class ye{constructor(t,e){this.activeTool=null;const n=new Mt;this.primaryToolGroup=n;const r=new Z(t,_.TwoFingerTouchGestures|_.RightClickDrags,e.touchPanTool),i=new Z(t,_.Keyboard,e.keyboardPanZoom),o=new Lt(t,e.penTool(1),{color:Et.purple,thickness:16}),s=[o,new Lt(t,e.penTool(2),{color:Et.clay,thickness:4}),new Lt(t,e.penTool(3),{color:Et.ofRGBA(1,1,0,.5),thickness:64}),new $t(t,e.eraserTool),new se(t,e.selectionTool),new ce(t,e.textTool,e)];this.tools=[new he(t,e.pipetteTool),r,...s,i,new ae(t),new de(t),new be(t)],s.forEach((t=>t.setToolGroup(n))),r.setEnabled(!0),o.setEnabled(!0),t.notifier.on(D.ToolEnabled,(n=>{n.kind===D.ToolEnabled&&t.announceForAccessibility(e.toolEnabledAnnouncement(n.tool.description))})),t.notifier.on(D.ToolDisabled,(n=>{n.kind===D.ToolDisabled&&t.announceForAccessibility(e.toolDisabledAnnouncement(n.tool.description))})),this.activeTool=null}setTools(t,e){this.tools=t,this.primaryToolGroup=null!=e?e:new Mt}addPrimaryTool(t){t.setToolGroup(this.primaryToolGroup),t.isEnabled()&&this.primaryToolGroup.notifyEnabled(t),this.addTool(t)}getPrimaryTools(){return this.tools.filter((t=>t.getToolGroup()===this.primaryToolGroup))}addTool(t){this.tools.push(t)}dispatchInputEvent(t){var e,n;let r=!1;if(t.kind===M.PointerDownEvt){for(const n of this.tools)if(n.isEnabled()&&n.onPointerDown(t)){this.activeTool!==n&&(null===(e=this.activeTool)||void 0===e||e.onGestureCancel()),this.activeTool=n,r=!0;break}}else if(t.kind===M.PointerUpEvt)null===(n=this.activeTool)||void 0===n||n.onPointerUp(t),this.activeTool=null,r=!0;else if(t.kind===M.PointerMoveEvt)null!==this.activeTool&&(this.activeTool.onPointerMove(t),r=!0);else if(t.kind===M.GestureCancelEvt)null!==this.activeTool&&(this.activeTool.onGestureCancel(),this.activeTool=null);else{let e;for(const n of this.tools)if(n.isEnabled()){switch(t.kind){case M.KeyPressEvent:r=n.onKeyPress(t);break;case M.KeyUpEvent:r=n.onKeyUp(t);break;case M.WheelEvt:r=n.onWheel(t);break;case M.CopyEvent:r=n.onCopy(t);break;case M.PasteEvent:r=n.onPaste(t);break;default:return e=t,e}if(r)break}}return r}getMatchingTools(t){return this.tools.filter((e=>e instanceof t))}}const we=class{constructor(t,e,n){this.editor=t,this.announceRedoCallback=e,this.announceUndoCallback=n,this.maxUndoRedoStackSize=700,this.undoStack=[],this.redoStack=[]}fireUpdateEvent(){this.editor.notifier.dispatch(D.UndoRedoStackUpdated,{kind:D.UndoRedoStackUpdated,undoStackSize:this.undoStack.length,redoStackSize:this.redoStack.length})}push(t,e=!0){e&&t.apply(this.editor),this.undoStack.push(t);for(const t of this.redoStack)t.onDrop(this.editor);if(this.redoStack=[],this.undoStack.length>this.maxUndoRedoStackSize){const t=10;this.undoStack.splice(0,t).forEach((t=>t.onDrop(this.editor)))}this.fireUpdateEvent(),this.editor.notifier.dispatch(D.CommandDone,{kind:D.CommandDone,command:t})}undo(){const t=this.undoStack.pop();t&&(this.redoStack.push(t),t.unapply(this.editor),this.announceUndoCallback(t),this.fireUpdateEvent(),this.editor.notifier.dispatch(D.CommandUndone,{kind:D.CommandUndone,command:t}))}redo(){const t=this.redoStack.pop();t&&(this.undoStack.push(t),t.apply(this.editor),this.announceRedoCallback(t),this.fireUpdateEvent(),this.editor.notifier.dispatch(D.CommandDone,{kind:D.CommandDone,command:t}))}get undoStackSize(){return this.undoStack.length}get redoStackSize(){return this.redoStack.length}};class Te{constructor(){this.listeners={}}dispatch(t,e){const n=this.listeners[t];if(n)for(let t=0;t<n.length;t++)n[t](e)}on(t,e){return this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e),{remove:()=>{const n=this.listeners[t];return this.off(t,e),n.length!==this.listeners[t].length}}}off(t,e){const n=this.listeners[t];n&&(this.listeners[t]=n.filter((t=>t!==e)))}}var Ce=function(t,e,n){var r,i,o,s,a,l,c,h,d,u,p,m,f,g,x,v=e.createElement("canvas").getContext("2d"),b={r:0,g:0,b:0,h:0,s:0,v:0,a:1},y={el:"[data-coloris]",parent:"body",theme:"default",themeMode:"light",wrap:!0,margin:2,format:"hex",formatToggle:!1,swatches:[],swatchesOnly:!1,alpha:!0,forceAlpha:!1,focusInput:!0,selectInput:!1,inline:!1,defaultColor:"#000000",clearButton:!1,clearLabel:"Clear",a11y:{open:"Open color picker",close:"Close color picker",marker:"Saturation: {s}. Brightness: {v}.",hueSlider:"Hue slider",alphaSlider:"Opacity slider",input:"Color value field",format:"Color format",swatch:"Color swatch",instruction:"Saturation and brightness selector. Use up, down, left and right arrow keys to select."}},w={},T="",C={},k=!1;function S(n){if("object"==typeof n)for(var s in n)switch(s){case"el":B(n.el),!1!==n.wrap&&A(n.el);break;case"parent":(r=e.querySelector(n.parent))&&(r.appendChild(i),y.parent=n.parent,r===e.body&&(r=null));break;case"themeMode":y.themeMode=n.themeMode,"auto"===n.themeMode&&t.matchMedia&&t.matchMedia("(prefers-color-scheme: dark)").matches&&(y.themeMode="dark");case"theme":n.theme&&(y.theme=n.theme),i.className="clr-picker clr-"+y.theme+" clr-"+y.themeMode,y.inline&&R();break;case"margin":n.margin*=1,y.margin=isNaN(n.margin)?y.margin:n.margin;break;case"wrap":n.el&&n.wrap&&A(n.el);break;case"formatToggle":y.formatToggle=!!n.formatToggle,H("clr-format").style.display=y.formatToggle?"block":"none",y.formatToggle&&(y.format="auto");break;case"swatches":Array.isArray(n.swatches)&&function(){var t=[];n.swatches.forEach((function(e,n){t.push('<button type="button" id="clr-swatch-'+n+'" aria-labelledby="clr-swatch-label clr-swatch-'+n+'" style="color: '+e+';">'+e+"</button>")})),H("clr-swatches").innerHTML=t.length?"<div>"+t.join("")+"</div>":"",y.swatches=n.swatches.slice()}();break;case"swatchesOnly":y.swatchesOnly=!!n.swatchesOnly,i.setAttribute("data-minimal",y.swatchesOnly);break;case"alpha":y.alpha=!!n.alpha,i.setAttribute("data-alpha",y.alpha);break;case"inline":if(y.inline=!!n.inline,i.setAttribute("data-inline",y.inline),y.inline){var a=n.defaultColor||y.defaultColor;g=M(a),R(),L(a)}break;case"clearButton":"object"==typeof n.clearButton&&(n.clearButton.label&&(y.clearLabel=n.clearButton.label,h.innerHTML=y.clearLabel),n.clearButton=n.clearButton.show),y.clearButton=!!n.clearButton,h.style.display=y.clearButton?"block":"none";break;case"clearLabel":y.clearLabel=n.clearLabel,h.innerHTML=y.clearLabel;break;case"a11y":var u=n.a11y,m=!1;if("object"==typeof u)for(var f in u)u[f]&&y.a11y[f]&&(y.a11y[f]=u[f],m=!0);if(m){var x=H("clr-open-label"),v=H("clr-swatch-label");x.innerHTML=y.a11y.open,v.innerHTML=y.a11y.swatch,l.setAttribute("aria-label",y.a11y.close),d.setAttribute("aria-label",y.a11y.hueSlider),p.setAttribute("aria-label",y.a11y.alphaSlider),c.setAttribute("aria-label",y.a11y.input),o.setAttribute("aria-label",y.a11y.instruction)}default:y[s]=n[s]}}function E(t,e){"string"==typeof t&&"object"==typeof e&&(w[t]=e,k=!0)}function P(t){delete w[t],0===Object.keys(w).length&&(k=!1,t===T&&z())}function z(){Object.keys(C).length>0&&(S(C),T="",C={})}function B(t){G(e,"click",t,(function(t){y.inline||(function(t){if(k){var e=["el","wrap","inline","defaultColor","a11y"],n=function(n){var r=w[n];if(t.matches(n)){for(var i in T=n,C={},e.forEach((function(t){return delete r[t]})),r)C[i]=Array.isArray(y[i])?y[i].slice():y[i];return S(r),"break"}};for(var r in w)if("break"===n(r))break}}(t.target),f=t.target,x=f.value,g=M(x),i.classList.add("clr-open"),R(),L(x),(y.focusInput||y.selectInput)&&c.focus({preventScroll:!0}),y.selectInput&&c.select(),f.dispatchEvent(new Event("open",{bubbles:!0})))})),G(e,"input",t,(function(t){var e=t.target.parentNode;e.classList.contains("clr-field")&&(e.style.color=t.target.value)}))}function R(){var n,a,l,c=r,h=t.scrollY,d=i.offsetWidth,u=i.offsetHeight,p={left:!1,top:!1},m={x:0,y:0};if(c&&(n=t.getComputedStyle(c),a=parseFloat(n.marginTop),l=parseFloat(n.borderTopWidth),(m=c.getBoundingClientRect()).y+=l+h),!y.inline){var g=f.getBoundingClientRect(),x=g.x,v=h+g.y+g.height+y.margin;c?(x-=m.x,v-=m.y,x+d>c.clientWidth&&(x+=g.width-d,p.left=!0),v+u>c.clientHeight-a&&u+y.margin<=g.top-(m.y-h)&&(v-=g.height+u+2*y.margin,p.top=!0),v+=c.scrollTop):(x+d>e.documentElement.clientWidth&&(x+=g.width-d,p.left=!0),v+u-h>e.documentElement.clientHeight&&u+y.margin<=g.top&&(v=h+g.y-u-y.margin,p.top=!0)),i.classList.toggle("clr-left",p.left),i.classList.toggle("clr-top",p.top),i.style.left=x+"px",i.style.top=v+"px"}s={width:o.offsetWidth,height:o.offsetHeight,x:i.offsetLeft+o.offsetLeft+m.x,y:i.offsetTop+o.offsetTop+m.y}}function A(t){e.querySelectorAll(t).forEach((function(t){var n=t.parentNode;if(!n.classList.contains("clr-field")){var r=e.createElement("div");r.innerHTML='<button type="button" aria-labelledby="clr-open-label"></button>',n.insertBefore(r,t),r.setAttribute("class","clr-field"),r.style.color=t.value,r.appendChild(t)}}))}function I(t){f&&!y.inline&&(t&&x!==f.value&&(f.value=x,f.dispatchEvent(new Event("input",{bubbles:!0}))),x!==f.value&&f.dispatchEvent(new Event("change",{bubbles:!0})),i.classList.remove("clr-open"),k&&z(),f.dispatchEvent(new Event("close",{bubbles:!0})),y.focusInput&&f.focus({preventScroll:!0}),f=null)}function L(t){var e=function(t){var e,n,r=/^((rgba)|rgb)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i;return v.fillStyle="#000",v.fillStyle=t,(e=r.exec(v.fillStyle))?(n={r:1*e[3],g:1*e[4],b:1*e[5],a:1*e[6]}).a=+n.a.toFixed(2):n={r:(e=v.fillStyle.replace("#","").match(/.{2}/g).map((function(t){return parseInt(t,16)})))[0],g:e[1],b:e[2],a:1},n}(t),r=function(t){var e=t.r/255,r=t.g/255,i=t.b/255,o=n.max(e,r,i),s=n.min(e,r,i),a=o-s,l=o,c=0,h=0;return a&&(o===e&&(c=(r-i)/a),o===r&&(c=2+(i-e)/a),o===i&&(c=4+(e-r)/a),o&&(h=a/o)),{h:(c=n.floor(60*c))<0?c+360:c,s:n.round(100*h),v:n.round(100*l),a:t.a}}(e);$(r.s,r.v),F(e,r),d.value=r.h,i.style.color="hsl("+r.h+", 100%, 50%)",u.style.left=r.h/360*100+"%",a.style.left=s.width*r.s/100+"px",a.style.top=s.height-s.height*r.v/100+"px",p.value=100*r.a,m.style.left=100*r.a+"%"}function M(t){var e=t.substring(0,3).toLowerCase();return"rgb"===e||"hsl"===e?e:"hex"}function D(t){t=void 0!==t?t:c.value,f&&(f.value=t,f.dispatchEvent(new Event("input",{bubbles:!0}))),e.dispatchEvent(new CustomEvent("coloris:pick",{detail:{color:t}}))}function O(t,e){var r={h:1*d.value,s:t/s.width*100,v:100-e/s.height*100,a:p.value/100},i=function(t){var e=t.s/100,r=t.v/100,i=e*r,o=t.h/60,s=i*(1-n.abs(o%2-1)),a=r-i;i+=a,s+=a;var l=n.floor(o)%6,c=[i,s,a,a,s,i][l],h=[s,i,i,s,a,a][l],d=[a,a,s,i,i,s][l];return{r:n.round(255*c),g:n.round(255*h),b:n.round(255*d),a:t.a}}(r);$(r.s,r.v),F(i,r),D()}function $(t,e){var n=y.a11y.marker;t=1*t.toFixed(1),e=1*e.toFixed(1),n=(n=n.replace("{s}",t)).replace("{v}",e),a.setAttribute("aria-label",n)}function N(t){var e=function(t){return{pageX:t.changedTouches?t.changedTouches[0].pageX:t.pageX,pageY:t.changedTouches?t.changedTouches[0].pageY:t.pageY}}(t),n=e.pageX-s.x,i=e.pageY-s.y;r&&(i+=r.scrollTop),n=n<0?0:n>s.width?s.width:n,i=i<0?0:i>s.height?s.height:i,a.style.left=n+"px",a.style.top=i+"px",O(n,i),t.preventDefault(),t.stopPropagation()}function j(t,e){var n=1*a.style.left.replace("px","")+t,r=1*a.style.top.replace("px","")+e;a.style.left=n+"px",a.style.top=r+"px",O(n,r)}function F(t,r){void 0===t&&(t={}),void 0===r&&(r={});var i=y.format;for(var s in t)b[s]=t[s];for(var h in r)b[h]=r[h];var d,u=function(t){var e=t.r.toString(16),n=t.g.toString(16),r=t.b.toString(16),i="";if(t.r<16&&(e="0"+e),t.g<16&&(n="0"+n),t.b<16&&(r="0"+r),y.alpha&&(t.a<1||y.forceAlpha)){var o=255*t.a|0;i=o.toString(16),o<16&&(i="0"+i)}return"#"+e+n+r+i}(b),p=u.substring(0,7);switch(a.style.color=p,m.parentNode.style.color=p,m.style.color=u,l.style.color=u,o.style.display="none",o.offsetHeight,o.style.display="",m.nextElementSibling.style.display="none",m.nextElementSibling.offsetHeight,m.nextElementSibling.style.display="","mixed"===i?i=1===b.a?"hex":"rgb":"auto"===i&&(i=g),i){case"hex":c.value=u;break;case"rgb":c.value=function(t){return!y.alpha||1===t.a&&!y.forceAlpha?"rgb("+t.r+", "+t.g+", "+t.b+")":"rgba("+t.r+", "+t.g+", "+t.b+", "+t.a+")"}(b);break;case"hsl":c.value=(d=function(t){var e,r=t.v/100,i=r*(1-t.s/100/2);return i>0&&i<1&&(e=n.round((r-i)/n.min(i,1-i)*100)),{h:t.h,s:e||0,l:n.round(100*i),a:t.a}}(b),!y.alpha||1===d.a&&!y.forceAlpha?"hsl("+d.h+", "+d.s+"%, "+d.l+"%)":"hsla("+d.h+", "+d.s+"%, "+d.l+"%, "+d.a+")")}e.querySelector('.clr-format [value="'+i+'"]').checked=!0}function U(){var t=1*d.value,e=1*a.style.left.replace("px",""),n=1*a.style.top.replace("px","");i.style.color="hsl("+t+", 100%, 50%)",u.style.left=t/360*100+"%",O(e,n)}function V(){var t=p.value/100;m.style.left=100*t+"%",F({a:t}),D()}function W(){r=null,(i=e.createElement("div")).setAttribute("id","clr-picker"),i.className="clr-picker",i.innerHTML='<input id="clr-color-value" class="clr-color" type="text" value="" spellcheck="false" aria-label="'+y.a11y.input+'"><div id="clr-color-area" class="clr-gradient" role="application" aria-label="'+y.a11y.instruction+'"><div id="clr-color-marker" class="clr-marker" tabindex="0"></div></div><div class="clr-hue"><input id="clr-hue-slider" type="range" min="0" max="360" step="1" aria-label="'+y.a11y.hueSlider+'"><div id="clr-hue-marker"></div></div><div class="clr-alpha"><input id="clr-alpha-slider" type="range" min="0" max="100" step="1" aria-label="'+y.a11y.alphaSlider+'"><div id="clr-alpha-marker"></div><span></span></div><div id="clr-format" class="clr-format"><fieldset class="clr-segmented"><legend>'+y.a11y.format+'</legend><input id="clr-f1" type="radio" name="clr-format" value="hex"><label for="clr-f1">Hex</label><input id="clr-f2" type="radio" name="clr-format" value="rgb"><label for="clr-f2">RGB</label><input id="clr-f3" type="radio" name="clr-format" value="hsl"><label for="clr-f3">HSL</label><span></span></fieldset></div><div id="clr-swatches" class="clr-swatches"></div><button type="button" id="clr-clear" class="clr-clear">'+y.clearLabel+'</button><button type="button" id="clr-color-preview" class="clr-preview" aria-label="'+y.a11y.close+'"></button><span id="clr-open-label" hidden>'+y.a11y.open+'</span><span id="clr-swatch-label" hidden>'+y.a11y.swatch+"</span>",e.body.appendChild(i),o=H("clr-color-area"),a=H("clr-color-marker"),h=H("clr-clear"),l=H("clr-color-preview"),c=H("clr-color-value"),d=H("clr-hue-slider"),u=H("clr-hue-marker"),p=H("clr-alpha-slider"),m=H("clr-alpha-marker"),B(y.el),A(y.el),G(i,"mousedown",(function(t){i.classList.remove("clr-keyboard-nav"),t.stopPropagation()})),G(o,"mousedown",(function(t){G(e,"mousemove",N)})),G(o,"touchstart",(function(t){e.addEventListener("touchmove",N,{passive:!1})})),G(a,"mousedown",(function(t){G(e,"mousemove",N)})),G(a,"touchstart",(function(t){e.addEventListener("touchmove",N,{passive:!1})})),G(c,"change",(function(t){L(c.value),D()})),G(h,"click",(function(t){D(""),I()})),G(l,"click",(function(t){D(),I()})),G(e,"click",".clr-format input",(function(t){g=t.target.value,F(),D()})),G(i,"click",".clr-swatches button",(function(t){L(t.target.textContent),D(),y.swatchesOnly&&I()})),G(e,"mouseup",(function(t){e.removeEventListener("mousemove",N)})),G(e,"touchend",(function(t){e.removeEventListener("touchmove",N)})),G(e,"mousedown",(function(t){i.classList.remove("clr-keyboard-nav"),I()})),G(e,"keydown",(function(t){"Escape"===t.key?I(!0):"Tab"===t.key&&i.classList.add("clr-keyboard-nav")})),G(e,"click",".clr-field button",(function(t){k&&z(),t.target.nextElementSibling.dispatchEvent(new Event("click",{bubbles:!0}))})),G(a,"keydown",(function(t){var e={ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0]};-1!==Object.keys(e).indexOf(t.key)&&(j.apply(void 0,e[t.key]),t.preventDefault())})),G(o,"click",N),G(d,"input",U),G(p,"input",V)}function H(t){return e.getElementById(t)}function G(t,e,n,r){var i=Element.prototype.matches||Element.prototype.msMatchesSelector;"string"==typeof n?t.addEventListener(e,(function(t){i.call(t.target,n)&&r.call(t.target,t)})):(r=n,t.addEventListener(e,r))}function _(t,n){n=void 0!==n?n:[],"loading"!==e.readyState?t.apply(void 0,n):e.addEventListener("DOMContentLoaded",(function(){t.apply(void 0,n)}))}void 0!==NodeList&&NodeList.prototype&&!NodeList.prototype.forEach&&(NodeList.prototype.forEach=Array.prototype.forEach);var Z=function(){var t={init:W,set:S,wrap:A,close:I,setInstance:E,removeInstance:P,updatePosition:R};function e(t){_((function(){t&&("string"==typeof t?B(t):S(t))}))}var n=function(n){e[n]=function(){for(var e=arguments.length,r=new Array(e),i=0;i<e;i++)r[i]=arguments[i];_(t[n],r)}};for(var r in t)n(r);return e}();return Z.coloris=Z,Z}(window,document,Math),ke=Ce.coloris,Se=Ce.init;Ce.set,Ce.wrap,Ce.close;const Ee={pen:"Pen",eraser:"Eraser",select:"Select",handTool:"Pan",zoom:"Zoom",resetView:"Reset view",thicknessLabel:"Thickness: ",colorLabel:"Color: ",fontLabel:"Font: ",resizeImageToSelection:"Resize image to selection",deleteSelection:"Delete selection",duplicateSelection:"Duplicate selection",undo:"Undo",redo:"Redo",selectObjectType:"Object type: ",pickColorFromScreen:"Pick color from screen",clickToPickColorAnnouncement:"Click on the screen to pick a color",selectionToolKeyboardShortcuts:"Selection tool: Use arrow keys to move selected items, lowercase/uppercase ‘i’ and ‘o’ to resize.",touchPanning:"Touchscreen panning",anyDevicePanning:"Any device panning",freehandPen:"Freehand",arrowPen:"Arrow",linePen:"Line",outlinedRectanglePen:"Outlined rectangle",filledRectanglePen:"Filled rectangle",dropdownShown:t=>`Dropdown for ${t} shown`,dropdownHidden:t=>`Dropdown for ${t} hidden`,zoomLevel:t=>`Zoom: ${t}%`,colorChangedAnnouncement:t=>`Color changed to ${t}`},Pe="http://www.w3.org/2000/svg",ze="\n\tstyle='fill: var(--icon-color);'\n",Be="\n\t<pattern\n\t\tid='checkerboard'\n\t\tviewBox='0,0,10,10'\n\t\twidth='20%'\n\t\theight='20%'\n\t\tpatternUnits='userSpaceOnUse'\n\t>\n\t\t<rect x=0 y=0 width=10 height=10 fill='white'/>\n\t\t<rect x=0 y=0 width=5 height=5 fill='gray'/>\n\t\t<rect x=5 y=5 width=5 height=5 fill='gray'/>\n\t</pattern>\n",Re="url(#checkerboard)",Ae=()=>Ie(!0),Ie=(t=!1)=>{const e=document.createElementNS(Pe,"svg");return e.innerHTML=`\n\t\t<style>\n\t\t\t.toolbar-svg-undo-redo-icon {\n\t\t\t\tstroke: var(--icon-color);\n\t\t\t\tstroke-width: 12;\n\t\t\t\tstroke-linejoin: round;\n\t\t\t\tstroke-linecap: round;\n\t\t\t\tfill: none;\n\n\t\t\t\ttransform-origin: center;\n\t\t\t}\n\t\t</style>\n\t\t<path\n\t\t\td='M20,20 A15,15 0 0 1 70,80 L80,90 L60,70 L65,90 L87,90 L65,80'\n\t\t\tclass='toolbar-svg-undo-redo-icon'\n\t\t\tstyle='${t?"transform: scale(-1, 1);":""}'/>\n\t`,e.setAttribute("viewBox","0 0 100 100"),e},Le=()=>{const t=document.createElementNS(Pe,"svg");return t.innerHTML=`\n\t<g>\n\t\t<path\n\t\t\td='M5,10 L50,90 L95,10 Z'\n\t\t\t${ze}\n\t\t/>\n\t</g>\n\t`,t.setAttribute("viewBox","0 0 100 100"),t},Me=()=>{const t=document.createElementNS(Pe,"svg");return t.innerHTML=`\n\t<g>\n\t\t<rect x=10 y=50 width=80 height=30 rx=10 fill='pink' />\n\t\t<rect\n\t\t\tx=10 y=10 width=80 height=50\n\t\t\t${ze}\n\t\t/>\n\t</g>\n\t`,t.setAttribute("viewBox","0 0 100 100"),t},De=()=>{const t=document.createElementNS(Pe,"svg");return t.innerHTML="\n\t<g>\n\t\t<rect x=10 y=10 width=70 height=70 fill='pink' stroke='black'/>\n\t\t<rect x=75 y=75 width=10 height=10 fill='white' stroke='black'/>\n\t</g>\n\t",t.setAttribute("viewBox","0 0 100 100"),t},Oe=(t,e="var(--icon-color)",n="none",r="0px")=>{const i=document.createElementNS(Pe,"svg"),o=document.createElementNS(Pe,"path");return o.setAttribute("d",t),o.style.fill=e,o.style.stroke=n,o.style.strokeWidth=r,i.appendChild(o),i.setAttribute("viewBox","0 0 100 100"),i},$e=()=>Oe("\n\t\tm 10,60\n\t\t\t5,30\n\t\tH 90\n\t\tV 30\n\t\tC 90,20 75,20 75,30\n\t\tV 60\n\t\t\t20\n\t\tC 75,10 60,10 60,20\n\t\tV 60\n\t\t\t15\n\t\tC 60,5 45,5 45,15\n\t\tV 60\n\t\t\t25\n\t\tC 45,15 30,15 30,25\n\t\tV 60\n\t\t\t75\n\t\tL 25,60\n\t\tC 20,45 10,50 10,60\n\t\tZ\n\t","none","var(--icon-color)","3"),Ne=()=>Oe("\n\t\tM 5,5.5\n\t\tV 17.2\n\t\tL 16.25,5.46\n\t\tZ\n\n\t\tm 33.75,0\n\t\tL 50,17\n\t\tV 5.5\n\t\tZ\n\n\t\tM 5,40.7\n\t\tv 11.7\n\t\th 11.25\n\t\tz\n\n\t\tM 26,19\n\t\tC 19.8,19.4 17.65,30.4 21.9,34.8\n\t\tL 50,70\n\t\tH 27.5\n\t\tc -11.25,0 -11.25,17.6 0,17.6\n\t\tH 61.25\n\t\tC 94.9,87.8 95,87.6 95,40.7 78.125,23 67,29 55.6,46.5\n\t\tL 33.1,23\n\t\tC 30.3125,20.128192 27.9,19 25.830078,19.119756\n\t\tZ\n\t","none","var(--icon-color)","3"),je=()=>Oe("\n\t\tM 5 5\n\t\tL 5 17.5\n\t\t\t17.5 5\n\t\t\t5 5\n\t\tz\n\n\t\tM 42.5 5\n\t\tL 55 17.5\n\t\t\t55 5\n\t\t\t42.5 5\n\t\tz\n\n\t\tM 70 10\n\t\tL 70 21\n\t\t\t61 15\n\t\t\t55.5 23\n\t\t\t66 30\n\t\t\t56 37\n\t\t\t61 45\n\t\t\t70 39\n\t\t\t70 50\n\t\t\t80 50\n\t\t\t80 39\n\t\t\t89 45\n\t\t\t95 36\n\t\t\t84 30\n\t\t\t95 23\n\t\t\t89 15\n\t\t\t80 21\n\t\t\t80 10\n\t\t\t70 10\n\t\tz\n\n\t\tM 27.5 26.25\n\t\tL 27.5 91.25\n\t\tL 43.75 83.125\n\t\tL 52 99\n\t\tL 68 91\n\t\tL 60 75\n\t\tL 76.25 66.875\n\t\tL 27.5 26.25\n\t\tz\n\n\t\tM 5 42.5\n\t\tL 5 55\n\t\tL 17.5 55\n\t\tL 5 42.5\n\t\tz\n\t","none","var(--icon-color)","3"),Fe=()=>{const t=document.createElementNS(Pe,"svg");t.setAttribute("viewBox","0 0 100 100");const e=(e,n,r)=>{const i=document.createElementNS(Pe,"text");i.appendChild(document.createTextNode(e)),i.setAttribute("x",n.toString()),i.setAttribute("y",r.toString()),i.style.textAlign="center",i.style.textAnchor="middle",i.style.fontSize="55px",i.style.fill="var(--icon-color)",i.style.fontFamily="monospace",t.appendChild(i)};return e("+",40,45),e("-",70,75),t},Ue=t=>{var e,n;const r=document.createElementNS(Pe,"svg");r.setAttribute("viewBox","0 0 100 100");const i=document.createElementNS(Pe,"text");return i.appendChild(document.createTextNode("T")),i.style.fontFamily=t.fontFamily,i.style.fontWeight=null!==(e=t.fontWeight)&&void 0!==e?e:"",i.style.fontVariant=null!==(n=t.fontVariant)&&void 0!==n?n:"",i.style.fill=t.renderingStyle.fill.toHexString(),i.style.textAnchor="middle",i.setAttribute("x","50"),i.setAttribute("y","75"),i.style.fontSize="65px",i.style.filter="drop-shadow(0px 0px 10px var(--primary-shadow-color))",r.appendChild(i),r},Ve=(t,e)=>{e instanceof Et&&(e=e.toHexString());const n=document.createElementNS(Pe,"svg");n.setAttribute("viewBox","0 0 100 100");const r=t/2,i=`M14,63 L${50-r},95 L${50+r},90 L88,60 Z`,o=`M14,63 L${50-r},85 L${50+r},83 L88,60 Z`;return n.innerHTML=`\n\t<defs>\n\t\t${Be}\n\t</defs>\n\t<g>\n\t\t\x3c!-- Pen grip --\x3e\n\t\t<path\n\t\t\td='M10,10 L90,10 L90,60 L${50+r},80 L${50-r},80 L10,60 Z'\n\t\t\t\n\tstyle='fill: var(--icon-color); stroke: var(--icon-color);'\n\n\t\t/>\n\t</g>\n\t<g>\n\t\t\x3c!-- Checkerboard background for slightly transparent pens --\x3e\n\t\t<path d='${o}' fill='url(#checkerboard)'/>\n\n\t\t\x3c!-- Actual pen tip --\x3e\n\t\t<path\n\t\t\td='${i}'\n\t\t\tfill='${e}'\n\t\t\tstroke='${e}'\n\t\t/>\n\t</g>\n\t`,n},We=(t,e)=>{const n=t.getThickness(),r=(new Date).getTime(),i={pos:k.of(10,10),width:n/5,color:t.getColor(),time:r-100},o={pos:k.of(90,90),width:n/5,color:t.getColor(),time:r},s=new H(new Te),a=e(i,s);a.addPoint(o);const l=document.createElementNS(Pe,"svg");l.setAttribute("viewBox","0 0 100 100"),s.updateScreenSize(k.of(100,100));const c=new te(l,s);return a.preview(c),l},He=t=>{const e=document.createElementNS(Pe,"svg"),n=document.createElementNS(Pe,"path");if(n.setAttribute("d","\n\t\tM 47,6\n\t\tC 35,5 25,15 35,30\n\t\tc -9.2,1.3 -15,0 -15,3\n\t\t\t0,2 5,5 15,7\n\t\tV 81\n\t\tL 40,90\n\t\th 6\n\t\tL 40,80\n\t\tV 40\n\t\th 15\n\t\tv 40\n\t\tl -6,10\n\t\th 6\n\t\tl 5,-9.2\n\t\tV 40\n\t\tC 70,38 75,35 75,33\n\t\t\t75,30 69.2,31.2 60,30\n\t\t\t65,15 65,5 47,6\n\t\tZ\n\t"),n.style.fill="var(--icon-color)",t){const n=document.createElementNS(Pe,"defs");n.innerHTML=Be,e.appendChild(n);const r=document.createElementNS(Pe,"path"),i=document.createElementNS(Pe,"path"),o="\n\t\t\tm 40,50 c 5,5 10,0 15,-5 V 80 L 50,90 H 45 L 40,80 Z\n\t\t";i.setAttribute("d",o),r.setAttribute("d",o),i.style.fill=t.toHexString(),r.style.fill=Re,e.appendChild(r),e.appendChild(i)}return e.appendChild(n),e.setAttribute("viewBox","0 0 100 100"),e},Ge=()=>Oe("\n\t\tM 75 5 75 10 90 10 90 25 95 25 95 5 75 5 z\n\t\tM 15 15 15 30 20 30 20 20 30 20 30 15 15 15 z\n M 84 15 82 17 81 16 81 20 85 20 84 19 86 17 84 15 z\n M 26 24 24 26 26 28 25 29 29 29 29 25 28 26 26 24 z\n M 25 71 26 72 24 74 26 76 28 74 29 75 29 71 25 71 z\n M 15 75 15 85 25 85 25 80 20 80 20 75 15 75 z\n M 90 75 90 90 75 90 75 95 95 95 95 75 90 75 z\n M 81 81 81 85 82 84 84 86 86 84 84 82 85 81 81 81 z\n\t"),_e=()=>Oe("\n\t\tM 45,10 45,55 90,55 90,10 45,10 z\n\t\tM 10,25 10,90 70,90 70,60 40,60 40,25 10,25 z \n\t"),Ze=()=>Oe("\n\t\tM 10,10 90,90\n\t\tM 10,90 90,10\n\t","none","var(--icon-color)","5px"),qe=(t,e)=>new Ke(t);class Ke{constructor(t){this.startPoint=t,this.endPoint=t}getLineWidth(){return Math.max(this.endPoint.width,this.startPoint.width)}getBBox(){return this.buildPreview().getBBox()}buildPreview(){const t=this.startPoint.pos,e=this.endPoint.pos,n=e.minus(t).normalized(),r=e.minus(t).length(),i=Math.min(this.getLineWidth(),r/2),o=this.startPoint.width/2,s=this.endPoint.width/2,a=e.minus(n.times(i)),l=n.orthog(),c=l.times(o),h=l.times(s);return new Rt([{startPoint:a.minus(h),commands:[{kind:kt.LineTo,point:t.minus(c)},{kind:kt.LineTo,point:t.plus(c)},{kind:kt.LineTo,point:a.plus(h)},{kind:kt.LineTo,point:a.plus(l.times(i).plus(h))},{kind:kt.LineTo,point:e.plus(n.times(s))},{kind:kt.LineTo,point:a.plus(l.times(-i).minus(h))},{kind:kt.LineTo,point:a.minus(h)}],style:{fill:this.startPoint.color}}])}build(){return this.buildPreview()}preview(t){this.buildPreview().render(t)}addPoint(t){this.endPoint=t}}const Xe=(t,e)=>new Je(t);class Je{constructor(t){this.startPoint=t,this.endPoint=t}getBBox(){return this.buildPreview().getBBox()}buildPreview(){const t=this.startPoint.pos,e=this.endPoint.pos,n=e.minus(t).normalized(),r=this.startPoint.width/2,i=this.endPoint.width/2,o=n.orthog(),s=o.times(r),a=o.times(i);return new Rt([{startPoint:t.minus(s),commands:[{kind:kt.LineTo,point:t.plus(s)},{kind:kt.LineTo,point:e.plus(a)},{kind:kt.LineTo,point:e.minus(a)}],style:{fill:this.startPoint.color}}])}build(){return this.buildPreview()}preview(t){this.buildPreview().render(t)}addPoint(t){this.endPoint=t}}const Ye=(t,e)=>new tn(t,!0,e),Qe=(t,e)=>new tn(t,!1,e);class tn{constructor(t,e,n){this.startPoint=t,this.filled=e,this.viewport=n,this.endPoint=t}getBBox(){return this.buildPreview().getBBox()}buildPreview(){const t=this.viewport.getRotationAngle(),e=P.zRotation(-t),n=e.inverse().transformVec2(this.startPoint.pos),r=e.inverse().transformVec2(this.endPoint.pos),i=R.fromCorners(n,r),o=St.fromRect(i,this.filled?null:this.endPoint.width).transformedBy(e);return new Rt([o.toRenderable({fill:this.endPoint.color})])}build(){return this.buildPreview()}preview(t){this.buildPreview().render(t)}addPoint(t){this.endPoint=t}}const en=(t,e)=>{const n=document.createElement("span"),r=document.createElement("input");let i;r.type="button",r.classList.add("coloris_input"),n.classList.add("color-input-container"),n.appendChild(r),nn(t,n,(t=>{r.value=t.toHexString(),s();const e=r.parentElement;e&&e.classList.contains("clr-field")&&(e.style.color=r.value)}));const o=()=>{i=Et.fromHex(r.value)},s=()=>{o(),i&&(t.announceForAccessibility(t.localization.colorChangedAnnouncement(i.toHexString())),e(i),t.notifier.dispatch(D.ColorPickerColorSelected,{kind:D.ColorPickerColorSelected,color:i}))};return r.oninput=o,r.addEventListener("open",(()=>{t.notifier.dispatch(D.ColorPickerToggled,{kind:D.ColorPickerToggled,open:!0})})),r.addEventListener("close",(()=>{t.notifier.dispatch(D.ColorPickerToggled,{kind:D.ColorPickerToggled,open:!1}),s()})),[r,n]},nn=(t,e,n)=>{const r=document.createElement("button");r.classList.add("pipetteButton"),r.title=t.localization.pickColorFromScreen,r.setAttribute("alt",r.title);const i=t=>{r.replaceChildren(He(t))};i();const o=t.toolController.getMatchingTools(he)[0],s=()=>{null==o||o.clearColorListener(),i(),r.classList.remove("active")},a=t=>{s(),t&&n(t)},l=t=>{t?i(t):i()};r.onclick=()=>{r.classList.contains("active")?s():(null==o||o.setColorListener(l,a),o&&(r.classList.add("active"),t.announceForAccessibility(t.localization.clickToPickColorAnnouncement)))},e.appendChild(r)},rn=en;var on,sn=function(t,e,n,r,i){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?i.call(t,n):i?i.value=n:e.set(t,n),n},an=function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)};class ln{constructor(t,e){this.editor=t,this.localizationTable=e,on.set(this,void 0),this.disabled=!1,this.subWidgets=[],this.toplevel=!0,this.icon=null,this.container=document.createElement("div"),this.container.classList.add(`${vn}toolContainer`),this.dropdownContainer=document.createElement("div"),this.dropdownContainer.classList.add(`${vn}dropdown`),this.dropdownContainer.classList.add("hidden"),sn(this,on,!1,"f"),this.button=document.createElement("div"),this.button.classList.add(`${vn}button`),this.label=document.createElement("label"),this.button.setAttribute("role","button"),this.button.tabIndex=0}fillDropdown(t){if(0===this.subWidgets.length)return!1;for(const e of this.subWidgets)e.addTo(t),e.setIsToplevel(!1);return!0}setupActionBtnClickListener(t){const e={Enter:!0," ":!0};t.onkeydown=t=>{let n=!1;t.key in e&&(this.disabled||(this.handleClick(),n=!0)),n||this.editor.toolController.dispatchInputEvent({kind:M.KeyPressEvent,key:t.key,ctrlKey:t.ctrlKey})},t.onkeyup=t=>{t.key in e||this.editor.toolController.dispatchInputEvent({kind:M.KeyUpEvent,key:t.key,ctrlKey:t.ctrlKey})},t.onclick=()=>{this.disabled||this.handleClick()}}get hasDropdown(){return an(this,on,"f")}addSubWidget(t){this.subWidgets.push(t)}addTo(t){this.label.innerText=this.getTitle(),this.setupActionBtnClickListener(this.button),this.icon=null,this.updateIcon(),this.button.replaceChildren(this.icon,this.label),this.container.appendChild(this.button),sn(this,on,this.fillDropdown(this.dropdownContainer),"f"),an(this,on,"f")&&(this.dropdownIcon=this.createDropdownIcon(),this.button.appendChild(this.dropdownIcon),this.container.appendChild(this.dropdownContainer),this.editor.notifier.on(D.ToolbarDropdownShown,(t=>{t.kind===D.ToolbarDropdownShown&&t.parentWidget!==this&&t.parentWidget.toplevel&&this.setDropdownVisible(!1)}))),this.setDropdownVisible(!1),t.appendChild(this.container)}updateIcon(){var t;const e=this.createIcon();null===(t=this.icon)||void 0===t||t.replaceWith(e),this.icon=e,this.icon.classList.add(`${vn}icon`)}setDisabled(t){this.disabled=t,this.disabled?(this.button.classList.add("disabled"),this.button.setAttribute("aria-disabled","true")):(this.button.classList.remove("disabled"),this.button.removeAttribute("aria-disabled"))}setSelected(t){this.isSelected()!==t&&(t?(this.container.classList.add("selected"),this.button.ariaSelected="true"):(this.container.classList.remove("selected"),this.button.ariaSelected="false"))}setDropdownVisible(t){this.container.classList.contains("dropdownVisible")!==t&&(t?(this.dropdownContainer.classList.remove("hidden"),this.container.classList.add("dropdownVisible"),this.editor.announceForAccessibility(this.localizationTable.dropdownShown(this.getTitle())),this.editor.notifier.dispatch(D.ToolbarDropdownShown,{kind:D.ToolbarDropdownShown,parentWidget:this})):(this.dropdownContainer.classList.add("hidden"),this.container.classList.remove("dropdownVisible"),this.editor.announceForAccessibility(this.localizationTable.dropdownHidden(this.getTitle()))),this.repositionDropdown())}repositionDropdown(){const t=this.dropdownContainer.getBoundingClientRect(),e=document.body.clientWidth;t.left>e/2?(this.dropdownContainer.style.marginLeft=this.button.clientWidth+"px",this.dropdownContainer.style.transform="translate(-100%, 0)"):(this.dropdownContainer.style.marginLeft="",this.dropdownContainer.style.transform="")}setIsToplevel(t){this.toplevel=t}isDropdownVisible(){return!this.dropdownContainer.classList.contains("hidden")}isSelected(){return this.container.classList.contains("selected")}createDropdownIcon(){const t=Le();return t.classList.add(`${vn}showHideDropdownIcon`),t}}on=new WeakMap;class cn extends ln{constructor(t,e,n){super(t,n),this.editor=t,this.targetTool=e,this.localizationTable=n,t.notifier.on(D.ToolEnabled,(t=>{if(t.kind!==D.ToolEnabled)throw new Error("Incorrect event type! (Expected ToolEnabled)");t.tool===e&&this.setSelected(!0)})),t.notifier.on(D.ToolDisabled,(t=>{if(t.kind!==D.ToolDisabled)throw new Error("Incorrect event type! (Expected ToolDisabled)");t.tool===e&&(this.setSelected(!1),this.setDropdownVisible(!1))}))}handleClick(){this.hasDropdown?this.targetTool.isEnabled()?this.setDropdownVisible(!this.isDropdownVisible()):this.targetTool.setEnabled(!0):this.targetTool.setEnabled(!this.targetTool.isEnabled())}addTo(t){super.addTo(t),this.setSelected(this.targetTool.isEnabled())}}class hn extends cn{constructor(t,e,n){super(t,e,n),this.tool=e,this.updateInputs=()=>{},this.penTypes=[{name:n.freehandPen,factory:At},{name:n.arrowPen,factory:qe},{name:n.linePen,factory:Xe},{name:n.filledRectanglePen,factory:Ye},{name:n.outlinedRectanglePen,factory:Qe}],this.editor.notifier.on(D.ToolUpdated,(t=>{if(t.kind!==D.ToolUpdated)throw new Error("Invalid event type!");t.tool===this.tool&&(this.updateIcon(),this.updateInputs())}))}getTitle(){return this.targetTool.description}createIcon(){if(this.tool.getStrokeFactory()===At){const t=Math.round(4*Math.sqrt(this.tool.getThickness())),e=this.tool.getColor();return Ve(t,e.toHexString())}{const t=this.tool.getStrokeFactory();return We(this.tool,t)}}fillDropdown(t){const e=document.createElement("div"),n=document.createElement("div"),r=document.createElement("div"),i=document.createElement("label"),o=document.createElement("input"),s=document.createElement("label"),a=document.createElement("select");o.id=`${vn}thicknessInput${hn.idCounter++}`,a.id=`${vn}builderSelect${hn.idCounter++}`,i.innerText=this.localizationTable.thicknessLabel,i.setAttribute("for",o.id),s.innerText=this.localizationTable.selectObjectType,s.setAttribute("for",a.id),o.type="range",o.min="2",o.max="20",o.step="1",o.oninput=()=>{this.tool.setThickness(Math.pow(parseFloat(o.value),2))},n.appendChild(i),n.appendChild(o),a.oninput=()=>{const t=parseInt(a.value);t<0||t>=this.penTypes.length?console.error("Invalid pen type index",t):this.tool.setStrokeFactory(this.penTypes[t].factory)},r.appendChild(s),r.appendChild(a);const l=document.createElement("div"),c=document.createElement("label"),[h,d]=rn(this.editor,(t=>{this.tool.setColor(t)}));return h.id=`${vn}colorInput${hn.idCounter++}`,c.innerText=this.localizationTable.colorLabel,c.setAttribute("for",h.id),l.appendChild(c),l.appendChild(d),this.updateInputs=()=>{h.value=this.tool.getColor().toHexString(),o.value=Math.sqrt(this.tool.getThickness()).toString(),a.replaceChildren();for(let t=0;t<this.penTypes.length;t++){const e=this.penTypes[t],n=document.createElement("option");n.value=t.toString(),n.innerText=e.name,a.appendChild(n),e.factory===this.tool.getStrokeFactory()&&(a.value=t.toString())}},this.updateInputs(),e.replaceChildren(l,n,r),t.replaceChildren(e),!0}}hn.idCounter=0;class dn extends cn{getTitle(){return this.localizationTable.eraser}createIcon(){return Me()}fillDropdown(t){return!1}}class un extends ln{constructor(t,e,n,r,i){super(t,e),this.makeIcon=n,this.title=r,this.clickAction=i}handleClick(){this.clickAction()}getTitle(){return this.title}createIcon(){return this.makeIcon()}fillDropdown(t){return!1}}class pn extends cn{constructor(t,e,n){super(t,e,n),this.tool=e;const r=new un(t,n,Ge,this.localizationTable.resizeImageToSelection,(()=>{const t=this.tool.getSelection();this.editor.dispatch(this.editor.setImportExportRect(t.region))})),i=new un(t,n,Ze,this.localizationTable.deleteSelection,(()=>{const t=this.tool.getSelection();this.editor.dispatch(t.deleteSelectedObjects()),this.tool.clearSelection()})),o=new un(t,n,_e,this.localizationTable.duplicateSelection,(()=>{const t=this.tool.getSelection();this.editor.dispatch(t.duplicateSelectedObjects())}));this.addSubWidget(r),this.addSubWidget(i),this.addSubWidget(o);const s=t=>{r.setDisabled(t),i.setDisabled(t),o.setDisabled(t)};s(!0),this.editor.notifier.on(D.ToolUpdated,(t=>{if(t.kind!==D.ToolUpdated)throw new Error("Invalid event type!");if(t.tool===this.tool){const t=this.tool.getSelection(),e=t&&t.region.area>0;s(!e)}}))}getTitle(){return this.localizationTable.select}createIcon(){return De()}}class mn extends cn{constructor(t,e,n){super(t,e,n),this.tool=e,this.updateDropdownInputs=null,t.notifier.on(D.ToolUpdated,(t=>{var n;t.kind===D.ToolUpdated&&t.tool===e&&(this.updateIcon(),null===(n=this.updateDropdownInputs)||void 0===n||n.call(this))}))}getTitle(){return this.targetTool.description}createIcon(){const t=this.tool.getTextStyle();return Ue(t)}fillDropdown(t){const e=document.createElement("div"),n=document.createElement("div"),r=document.createElement("select"),i=document.createElement("label"),[o,s]=rn(this.editor,(t=>{this.tool.setColor(t)})),a=document.createElement("label"),l=new Set,c=t=>{const e=document.createElement("option");e.value=t,e.textContent=t,r.appendChild(e),l.add(t)};return i.innerText=this.localizationTable.fontLabel,a.innerText=this.localizationTable.colorLabel,o.id=`${vn}-text-color-input-${mn.idCounter++}`,a.setAttribute("for",o.id),c("monospace"),c("serif"),c("sans-serif"),r.id=`${vn}-text-font-input-${mn.idCounter++}`,i.setAttribute("for",r.id),r.onchange=()=>{this.tool.setFontFamily(r.value)},n.appendChild(a),n.appendChild(s),e.appendChild(i),e.appendChild(r),this.updateDropdownInputs=()=>{const t=this.tool.getTextStyle();o.value=t.renderingStyle.fill.toHexString(),l.has(t.fontFamily)||c(t.fontFamily),r.value=t.fontFamily},this.updateDropdownInputs(),t.replaceChildren(n,e),!0}}mn.idCounter=0;class fn extends ln{constructor(t,e){super(t,e),this.container.classList.add("dropdownShowable")}getTitle(){return this.localizationTable.zoom}createIcon(){return Fe()}handleClick(){this.setDropdownVisible(!this.isDropdownVisible())}fillDropdown(t){return t.appendChild(((t,e)=>{const n=document.createElement("div"),r=document.createElement("button"),i=document.createElement("button"),o=document.createElement("button"),s=document.createElement("span");let a;r.innerText="+",i.innerText="-",o.innerText=t.resetView,n.replaceChildren(s,r,i,o),n.classList.add(`${vn}zoomLevelEditor`),s.classList.add("zoomDisplay");const l=()=>{let n=100*e.viewport.getScaleFactor();n=n>.1?Math.round(10*n)/10:Math.round(1e3*n)/1e3,n!==a&&(s.innerText=t.zoomLevel(n),a=n)};l(),e.notifier.on(D.ViewportChanged,(t=>{t.kind===D.ViewportChanged&&(l(),o.disabled=t.newTransform.eq(P.identity))}));const c=t=>{const n=e.viewport.visibleRect.center,r=P.scaling2D(t,n);e.dispatch(H.transformBy(r),!1)};return r.onclick=()=>{c(5/4)},i.onclick=()=>{c(.8)},o.onclick=()=>{e.dispatch(H.transformBy(e.viewport.canvasToScreenTransform.inverse()),!0)},n})(this.localizationTable,this.editor)),!0}}class gn extends ln{constructor(t,e,n,r,i,o){super(t,e),this.tool=n,this.flag=r,this.makeIcon=i,this.title=o,t.notifier.on(D.ToolUpdated,(t=>{if(t.kind===D.ToolUpdated&&t.tool===n){const t=!!(n.getMode()&_.SinglePointerGestures);this.setSelected(!!(n.getMode()&r)||t),this.setDisabled(t&&r!==_.SinglePointerGestures)}})),this.setSelected(!1)}setModeFlag(t){const e=this.tool.getMode();t?this.tool.setMode(e|this.flag):this.tool.setMode(e&~this.flag)}handleClick(){this.setModeFlag(!this.isSelected())}getTitle(){return this.title}createIcon(){return this.makeIcon()}fillDropdown(t){return!1}}class xn extends cn{constructor(t,e,n){super(t,e,n),this.tool=e,this.container.classList.add("dropdownShowable"),this.touchPanningWidget=new gn(t,n,e,_.OneFingerTouchGestures,Ne,n.touchPanning),this.addSubWidget(this.touchPanningWidget),this.addSubWidget(new gn(t,n,e,_.SinglePointerGestures,je,n.anyDevicePanning)),this.addSubWidget(new fn(t,n))}getTitle(){return this.localizationTable.handTool}createIcon(){return $e()}setSelected(t){}handleClick(){this.setDropdownVisible(!this.isDropdownVisible())}}const vn="toolbar-";class bn{constructor(t,e,n=Ee){this.editor=t,this.localizationTable=n,this.updateColoris=null,this.container=document.createElement("div"),this.container.classList.add(`${vn}root`),this.container.setAttribute("role","toolbar"),e.appendChild(this.container),bn.colorisStarted||(Se(),bn.colorisStarted=!0),this.setupColorPickers()}setupColorPickers(){if(this.updateColoris)return void this.updateColoris();const t=document.createElement("div");t.className=`${vn}closeColorPickerOverlay`,this.editor.createHTMLOverlay(t);const e=[Et.red.toHexString(),Et.purple.toHexString(),Et.blue.toHexString(),Et.clay.toHexString(),Et.black.toHexString(),Et.white.toHexString()],n=e.length,r=()=>{ke({el:".coloris_input",format:"hex",selectInput:!1,focusInput:!1,themeMode:"auto",swatches:e})};r(),this.updateColoris=r;this.editor.notifier.on(D.ColorPickerToggled,(e=>{e.kind===D.ColorPickerToggled&&(t.style.display=e.open?"block":"none")})),this.editor.notifier.on(D.ColorPickerColorSelected,(t=>{t.kind===D.ColorPickerColorSelected&&(t=>{let i=!1;for(const n of e)n===t&&(i=!0);i||(e.push(t),e.length>12&&e.splice(n,1),r())})(t.color.toHexString())}))}addWidget(t){t.addTo(this.container),this.setupColorPickers()}addActionButton(t,e,n){const r=document.createElement("button");if(r.classList.add(`${vn}button`),"string"==typeof t)r.innerText=t;else{const e=t.icon.cloneNode(!0),n=document.createElement("label");e.setAttribute("alt",""),n.innerText=t.label,e.classList.add("toolbar-icon"),r.replaceChildren(e,n)}return r.onclick=e,(null!=n?n:this.container).appendChild(r),r}addUndoRedoButtons(){const t=document.createElement("div");t.classList.add(`${vn}buttonGroup`);const e=this.addActionButton({label:this.localizationTable.undo,icon:Ae()},(()=>{this.editor.history.undo()}),t),n=this.addActionButton({label:this.localizationTable.redo,icon:Ie()},(()=>{this.editor.history.redo()}),t);this.container.appendChild(t),e.disabled=!0,n.disabled=!0,this.editor.notifier.on(D.UndoRedoStackUpdated,(t=>{if(t.kind!==D.UndoRedoStackUpdated)throw new Error("Wrong event type!");e.disabled=0===t.undoStackSize,n.disabled=0===t.redoStackSize}))}addDefaultToolWidgets(){const t=this.editor.toolController;for(const e of t.getMatchingTools(Lt)){const t=new hn(this.editor,e,this.localizationTable);this.addWidget(t)}for(const e of t.getMatchingTools($t))this.addWidget(new dn(this.editor,e,this.localizationTable));for(const e of t.getMatchingTools(se))this.addWidget(new pn(this.editor,e,this.localizationTable));for(const e of t.getMatchingTools(ce))this.addWidget(new mn(this.editor,e,this.localizationTable));const e=t.getMatchingTools(Z)[0];e&&this.addWidget(new xn(this.editor,e,this.localizationTable))}addDefaultActionButtons(){this.addUndoRedoButtons()}}bn.colorisStarted=!1;class yn extends Yt{constructor(t,e){super(e),this.ctx=t,this.ignoreObjectsAboveLevel=null,this.ignoringObject=!1,this.clipLevels=[],this.setDraftMode(!1)}transformBy(t){this.ctx.transform(t.a1,t.b1,t.a2,t.b2,t.a3,t.b3)}canRenderFromWithoutDataLoss(t){return t instanceof yn}renderFromOtherOfSameType(t,e){if(!(e instanceof yn))throw new Error(`${e} cannot be rendered onto ${this}`);t=this.getCanvasToScreenTransform().rightMul(t),this.ctx.save(),this.transformBy(t),this.ctx.drawImage(e.ctx.canvas,0,0),this.ctx.restore()}setDraftMode(t){t?(this.minSquareCurveApproxDist=9,this.minRenderSizeBothDimens=2,this.minRenderSizeAnyDimen=.5):(this.minSquareCurveApproxDist=.5,this.minRenderSizeBothDimens=.3,this.minRenderSizeAnyDimen=1e-5)}displaySize(){return k.of(this.ctx.canvas.clientWidth,this.ctx.canvas.clientHeight)}clear(){this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height)}beginPath(t){t=this.canvasToScreen(t),this.ctx.beginPath(),this.ctx.moveTo(t.x,t.y)}endPath(t){this.ctx.fillStyle=t.fill.toHexString(),this.ctx.fill(),t.stroke&&(this.ctx.strokeStyle=t.stroke.color.toHexString(),this.ctx.lineWidth=this.getSizeOfCanvasPixelOnScreen()*t.stroke.width,this.ctx.stroke()),this.ctx.closePath()}lineTo(t){t=this.canvasToScreen(t),this.ctx.lineTo(t.x,t.y)}moveTo(t){t=this.canvasToScreen(t),this.ctx.moveTo(t.x,t.y)}traceCubicBezierCurve(t,e,n){t=this.canvasToScreen(t),e=this.canvasToScreen(e),n=this.canvasToScreen(n);const r=e.minus(t),i=n.minus(e);r.magnitudeSquared()<this.minSquareCurveApproxDist&&i.magnitudeSquared()<this.minSquareCurveApproxDist?this.ctx.lineTo(n.x,n.y):this.ctx.bezierCurveTo(t.x,t.y,e.x,e.y,n.x,n.y)}traceQuadraticBezierCurve(t,e){t=this.canvasToScreen(t),e=this.canvasToScreen(e);t.minus(e).magnitudeSquared()<this.minSquareCurveApproxDist?this.ctx.lineTo(e.x,e.y):this.ctx.quadraticCurveTo(t.x,t.y,e.x,e.y)}drawPath(t){this.ignoringObject||super.drawPath(t)}drawText(t,e,n){this.ctx.save(),e=this.getCanvasToScreenTransform().rightMul(e),this.transformBy(e),Ht.applyTextStyles(this.ctx,n),0!==n.renderingStyle.fill.a&&(this.ctx.fillStyle=n.renderingStyle.fill.toHexString(),this.ctx.fillText(t,0,0)),n.renderingStyle.stroke&&(this.ctx.strokeStyle=n.renderingStyle.stroke.color.toHexString(),this.ctx.lineWidth=n.renderingStyle.stroke.width,this.ctx.strokeText(t,0,0)),this.ctx.restore()}drawImage(t){this.ctx.save();const e=this.getCanvasToScreenTransform().rightMul(t.transform);this.transformBy(e),this.ctx.drawImage(t.image,0,0),this.ctx.restore()}startObject(t,e){if(this.isTooSmallToRender(t)&&(this.ignoreObjectsAboveLevel=this.getNestingLevel(),this.ignoringObject=!0),super.startObject(t),!this.ignoringObject&&e){this.clipLevels.push(this.objectLevel),this.ctx.save(),this.ctx.beginPath();for(const e of t.corners){const t=this.canvasToScreen(e);this.ctx.lineTo(t.x,t.y)}this.ctx.clip()}}endObject(){!this.ignoringObject&&this.clipLevels.length>0&&this.clipLevels[this.clipLevels.length-1]===this.objectLevel&&(this.ctx.restore(),this.clipLevels.pop()),super.endObject(),null!==this.ignoreObjectsAboveLevel&&this.getNestingLevel()<=this.ignoreObjectsAboveLevel&&(this.ignoreObjectsAboveLevel=null,this.ignoringObject=!1)}drawPoints(...t){for(let e=0;e<t.length;e++){const n=this.canvasToScreen(t[e]);this.ctx.beginPath(),this.ctx.arc(n.x,n.y,10,0,2*Math.PI),this.ctx.fillStyle=Et.ofRGBA(.5+Math.sin(e)/2,1,.5+Math.cos(.2*e)/4,.5).toHexString(),this.ctx.fill(),this.ctx.stroke(),this.ctx.closePath(),this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillStyle="black",this.ctx.fillText(`${e}`,n.x,n.y,20)}}isTooSmallToRender(t){const e=this.getCanvasToScreenTransform().transformVec3(t.size),n=this.minRenderSizeBothDimens,r=Math.abs(e.x)<n&&Math.abs(e.y)<n,i=this.minRenderSizeAnyDimen,o=Math.abs(e.x)<i||Math.abs(e.y)<i;return r||o}}class wn extends Yt{constructor(t){super(t),this.clearedCount=0,this.renderedPathCount=0,this.lastFillStyle=null,this.lastPoint=null,this.objectNestingLevel=0,this.lastText=null,this.lastImage=null,this.pointBuffer=[]}displaySize(){const t=this.getViewport().getResolution();return 0===t.x||0===t.y?k.of(640,480):t}clear(){if(this.clearedCount++,this.renderedPathCount=0,this.pointBuffer=[],this.lastText=null,this.lastImage=null,this.objectNestingLevel>0)throw new Error(`Within an object while clearing! Nesting level: ${this.objectNestingLevel}`)}beginPath(t){this.lastPoint=t,this.pointBuffer.push(t)}endPath(t){this.renderedPathCount++,this.lastFillStyle=t}lineTo(t){t=this.canvasToScreen(t),this.lastPoint=t,this.pointBuffer.push(t)}moveTo(t){t=this.canvasToScreen(t),this.lastPoint=t,this.pointBuffer.push(t)}traceCubicBezierCurve(t,e,n){t=this.canvasToScreen(t),e=this.canvasToScreen(e),n=this.canvasToScreen(n),this.lastPoint=n,this.pointBuffer.push(t,e,n)}traceQuadraticBezierCurve(t,e){t=this.canvasToScreen(t),e=this.canvasToScreen(e),this.lastPoint=e,this.pointBuffer.push(t,e)}drawPoints(...t){}drawText(t,e,n){this.lastText=t}drawImage(t){this.lastImage=t}startObject(t,e){super.startObject(t),this.objectNestingLevel+=1}endObject(){super.endObject(),this.objectNestingLevel-=1}isTooSmallToRender(t){return!1}canRenderFromWithoutDataLoss(t){return t instanceof wn}renderFromOtherOfSameType(t,e){if(!(e instanceof wn))throw new Error(`${e} cannot be rendered onto ${this}`);this.renderedPathCount+=e.renderedPathCount,this.lastFillStyle=e.lastFillStyle,this.lastPoint=e.lastPoint,this.pointBuffer.push(...e.pointBuffer.map((e=>t.transformVec2(e))))}}const Tn=!1;class Cn{constructor(t,e){this.region=t,this.cacheState=e,this.instantiatedChildren=[],this.parent=null,this.cachedRenderer=null,this.renderedIds=[],this.renderedMaxZIndex=null}generateParent(){if(this.parent)return this.parent;const t=R.fromCorners(this.region.topLeft.minus(this.region.size),this.region.bottomRight.plus(this.region.size)),e=new Cn(t,this.cacheState);e.generateChildren();const n=this.region.maxDimension/100,r=(e.instantiatedChildren.length-1)/2;if(!e.instantiatedChildren[r].region.eq(this.region,n))throw console.error(e.instantiatedChildren[r].region,"≠",this.region),new Error("Logic error: [this] is not contained within its parent's center child");return e.instantiatedChildren[r]=this,this.parent=e,e}generateChildren(){if(0===this.instantiatedChildren.length){const t=this.region.divideIntoGrid(3,3);if(0===this.region.size.x||0===this.region.size.y)return void console.warn("Cache element has zero size! Not generating children.");for(const e of t){const t=new Cn(e,this.cacheState);t.parent=this,this.instantiatedChildren.push(t)}}this.checkRep()}getChildren(){return this.checkRep(),this.generateChildren(),this.instantiatedChildren}smallestChildContaining(t){var e;const n=t.maxDimension>this.region.maxDimension/3;if(!this.region.containsRect(t)||n)return null;for(const n of this.getChildren())if(n.region.containsRect(t))return null!==(e=n.smallestChildContaining(t))&&void 0!==e?e:n;return null}renderingWouldBeHighEnoughResolution(t){const e=this.region.w/this.cacheState.props.blockResolution.x;return!(t.getScaleFactor()*e>this.cacheState.props.maxScale)}allChildrenCanRender(t,e){if(0===this.instantiatedChildren.length)return!1;for(const n of this.instantiatedChildren)if(n.region.intersects(t.visibleRect)&&!n.renderingIsUpToDate(this.idsOfIntersecting(e)))return!1;return!0}computeSortedByLeafIds(t){const e=t.slice();return e.sort(((t,e)=>t.getId()-e.getId())),e}idsOfIntersecting(t){const e=[];for(const n of t)n.getBBox().intersects(this.region)&&e.push(n.getId());return e}allRenderedIdsIn(t){if(this.renderedIds.length>t.length)return!1;for(let e=0;e<this.renderedIds.length;e++)if(t[e]!==this.renderedIds[e])return!1;return!0}renderingIsUpToDate(t){return null!==this.cachedRenderer&&t.length===this.renderedIds.length&&this.allRenderedIdsIn(t)}renderItems(t,e,n){var r,i;if(!n.visibleRect.intersects(this.region)||0===e.length)return;const o=[];for(const t of e){const e=t.getBBox();e.intersects(this.region)&&(e.maxDimension>=this.region.maxDimension?o.push(...t.getChildrenOrSelfIntersectingRegion(this.region)):o.push(t))}if(e=o,!this.cacheState.props.isOfCorrectType(t))return void e.forEach((e=>e.render(t,n.visibleRect)));if(this.renderingWouldBeHighEnoughResolution(n)){const o=t=>t.w/this.region.w<1/this.cacheState.props.blockResolution.x,s=[];for(const t of e)s.push(...t.getLeavesIntersectingRegion(this.region,o));A(s);const a=this.computeSortedByLeafIds(s);if(0===a.length)return;const l=a.map((t=>t.getId()));let c;if(this.renderingIsUpToDate(l))c=this.cachedRenderer.startRender();else{if(this.allChildrenCanRender(n,a)){for(const r of this.getChildren())r.renderItems(t,e,n);return}if(a.length>this.cacheState.props.minComponentsPerCache){let t=!0;if(this.cachedRenderer)if(a.length>this.renderedIds.length&&this.allRenderedIdsIn(l)&&null!==this.renderedMaxZIndex){const e=[];let n=null;for(let t=0;t<a.length;t++){const r=a[t],i=r.getContent().getZIndex();(t>=this.renderedIds.length||r.getId()!==this.renderedIds[t])&&(e.push(r),(null===n||i<n)&&(n=i))}if(null!==n&&n>this.renderedMaxZIndex){t=!1,c=this.cachedRenderer.startRender();for(let t=0;t<s.length;t++){const e=s[t],n=e.getContent().getZIndex();n>this.renderedMaxZIndex&&(e.render(c,this.region),this.renderedMaxZIndex=n)}Tn}}else Tn;else this.cachedRenderer=this.cacheState.recordManager.allocCanvas(this.region,(()=>this.onRegionDealloc()));if(t){c=this.cachedRenderer.startRender(),c.clear(),this.renderedMaxZIndex=null;for(const t of s){const e=t.getContent();null!==(r=this.renderedMaxZIndex)&&void 0!==r||(this.renderedMaxZIndex=e.getZIndex()),this.renderedMaxZIndex=Math.max(this.renderedMaxZIndex,e.getZIndex()),t.render(c,this.region)}Tn}this.renderedIds=l}else{null===(i=this.cachedRenderer)||void 0===i||i.dealloc();const e=n.getSizeOfPixelOnCanvas(),r=new R(this.region.x,this.region.y,this.region.w+e,this.region.h+e),o=!0;t.startObject(r,o);for(const e of s)e.render(t,this.region.intersection(n.visibleRect));t.endObject()}}if(c){const e=this.cachedRenderer.getTransform(this.region).inverse();t.renderFromOtherOfSameType(e,c)}this.instantiatedChildren.every((t=>t.isEmpty()))&&(this.instantiatedChildren=[])}else for(const r of this.getChildren())r.renderItems(t,e.filter((t=>t.getBBox().intersects(r.region))),n);this.checkRep()}isEmpty(){return null===this.cachedRenderer&&this.instantiatedChildren.every((t=>t.isEmpty()))}onRegionDealloc(){this.cachedRenderer=null,this.isEmpty()&&(this.instantiatedChildren=[])}checkRep(){if(9!==this.instantiatedChildren.length&&0!==this.instantiatedChildren.length)throw new Error(`Repcheck: Wrong number of children. Got ${this.instantiatedChildren.length}`);if(void 0!==this.renderedIds[1]&&this.renderedIds[0]>=this.renderedIds[1])throw console.error(this.renderedIds),new Error("Repcheck: First two ids are not in ascending order!");for(const t of this.instantiatedChildren)if(t.parent!==this)throw new Error("Children should be linked to their parents!");if(this.cachedRenderer&&!this.cachedRenderer.isAllocd())throw new Error("this' cachedRenderer != null, but is dealloc'd")}}class kn{constructor(t,e){this.onBeforeDeallocCallback=t,this.cacheState=e,this.allocd=!1,this.allocCount=0,this.renderer=e.props.createRenderer(),this.lastUsedCycle=-1,this.allocd=!0}startRender(){if(this.lastUsedCycle=this.cacheState.currentRenderingCycle,!this.allocd)throw new Error("Only alloc'd canvases can be rendered to");return this.renderer}dealloc(){var t;null===(t=this.onBeforeDeallocCallback)||void 0===t||t.call(this),this.allocd=!1,this.onBeforeDeallocCallback=null,this.lastUsedCycle=0}isAllocd(){return this.allocd}realloc(t){this.allocd&&this.dealloc(),this.allocd=!0,this.onBeforeDeallocCallback=t,this.lastUsedCycle=this.cacheState.currentRenderingCycle,this.allocCount++}getLastUsedCycle(){return this.lastUsedCycle}getTransform(t){return P.scaling2D(this.cacheState.props.blockResolution.x/t.size.x).rightMul(P.translation(t.topLeft.times(-1)))}setRenderingRegion(t){this.renderer.setTransform(this.getTransform(t))}}class Sn{constructor(t){this.cacheRecords=[],this.maxCanvases=Math.ceil(t.cacheSize/4/t.blockResolution.x/t.blockResolution.y)}setSharedState(t){this.cacheState=t}allocCanvas(t,e){if(this.cacheRecords.length<this.maxCanvases){const n=new kn(e,this.cacheState);return n.setRenderingRegion(t),this.cacheRecords.push(n),n}{const n=this.getLeastRecentlyUsedRecord();return n.realloc(e),n.setRenderingRegion(t),n}}getLeastRecentlyUsedRecord(){return this.cacheRecords.sort(((t,e)=>t.getLastUsedCycle()-e.getLastUsedCycle())),this.cacheRecords[0]}}class En{constructor(t){this.recordManager=new Sn(t),this.sharedState={props:t,currentRenderingCycle:0,recordManager:this.recordManager},this.recordManager.setSharedState(this.sharedState)}render(t,e,n){var r;const i=n.visibleRect;if(this.sharedState.currentRenderingCycle++,!this.sharedState.props.isOfCorrectType(t))return void e.render(t,i);if(!this.rootNode){const t=this.sharedState.props.blockResolution,e=i.topLeft;this.rootNode=new Cn(new R(e.x,e.y,t.x,t.y),this.sharedState)}for(;!this.rootNode.region.containsRect(i);)this.rootNode=this.rootNode.generateParent();this.rootNode=null!==(r=this.rootNode.smallestChildContaining(i))&&void 0!==r?r:this.rootNode;e.getLeavesIntersectingRegion(n.visibleRect,(e=>t.isTooSmallToRender(e))).length>this.sharedState.props.minComponentsToUseCache?this.rootNode.renderItems(t,[e],n):e.render(t,i)}}class Pn extends Yt{constructor(t,e){super(t),this.localizationTable=e,this.descriptionBuilder=[],this.pathCount=0,this.textNodeCount=0,this.imageNodeCount=0}displaySize(){return k.of(500,500)}clear(){this.descriptionBuilder=[],this.pathCount=0,this.textNodeCount=0}getDescription(){return[this.localizationTable.pathNodeCount(this.pathCount),...this.textNodeCount>0?this.localizationTable.textNodeCount(this.textNodeCount):[],...this.imageNodeCount>0?this.localizationTable.imageNodeCount(this.imageNodeCount):[],...this.descriptionBuilder].join("\n")}beginPath(t){}endPath(t){this.pathCount++}lineTo(t){}moveTo(t){}traceCubicBezierCurve(t,e,n){}traceQuadraticBezierCurve(t,e){}drawText(t,e,n){this.descriptionBuilder.push(this.localizationTable.textNode(t)),this.textNodeCount++}drawImage(t){const e=t.label?this.localizationTable.imageNode(t.label):this.localizationTable.unlabeledImageNode;this.descriptionBuilder.push(e),this.imageNodeCount++}isTooSmallToRender(t){return t.maxDimension<15/this.getSizeOfCanvasPixelOnScreen()}drawPoints(...t){}}var zn;!function(t){t[t.DummyRenderer=0]="DummyRenderer",t[t.CanvasRenderer=1]="CanvasRenderer"}(zn||(zn={}));class Bn{constructor(t,e,n){if(this.editor=t,this.parent=n,this.textRerenderOutput=null,this.getColorAt=t=>null,e===zn.CanvasRenderer)this.initializeCanvasRendering();else{if(e!==zn.DummyRenderer)throw new Error(`Unknown rendering mode, ${e}!`);this.dryInkRenderer=new wn(t.viewport),this.wetInkRenderer=new wn(t.viewport)}this.textRenderer=new Pn(t.viewport,t.localization),this.initializeTextRendering();const r=k.of(600,600);this.cache=new En({createRenderer:()=>{if(e===zn.DummyRenderer)return new wn(t.viewport);if(e!==zn.CanvasRenderer)throw new Error("Unspported rendering mode");const n=document.createElement("canvas");n.width=r.x+1,n.height=r.y+1;const i=n.getContext("2d");return new yn(i,t.viewport)},isOfCorrectType:t=>this.dryInkRenderer.canRenderFromWithoutDataLoss(t),blockResolution:r,cacheSize:1296e5,maxScale:1.4,minComponentsPerCache:20,minComponentsToUseCache:105}),this.editor.notifier.on(D.DisplayResized,(t=>{var e;if(t.kind!==D.DisplayResized)throw new Error("Mismatched event.kinds!");null===(e=this.resizeSurfacesCallback)||void 0===e||e.call(this)}))}get width(){return this.dryInkRenderer.displaySize().x}get height(){return this.dryInkRenderer.displaySize().y}getCache(){return this.cache}initializeCanvasRendering(){const t=document.createElement("canvas"),e=document.createElement("canvas"),n=t.getContext("2d"),r=e.getContext("2d");this.dryInkRenderer=new yn(n,this.editor.viewport),this.wetInkRenderer=new yn(r,this.editor.viewport),t.className="dryInkCanvas",e.className="wetInkCanvas",this.parent&&(this.parent.appendChild(t),this.parent.appendChild(e)),this.resizeSurfacesCallback=()=>{const n=t=>t.clientHeight!==t.height||t.clientWidth!==t.width;(n(t)||n(e))&&(t.width=t.clientWidth,t.height=t.clientHeight,e.width=e.clientWidth,e.height=e.clientHeight,this.editor.notifier.dispatch(D.DisplayResized,{kind:D.DisplayResized,newSize:k.of(this.width,this.height)}))},this.resizeSurfacesCallback(),this.flattenCallback=()=>{n.drawImage(e,0,0)},this.getColorAt=t=>{const e=n.getImageData(t.x,t.y,1,1),r=null==e?void 0:e.data;if(r){return Et.ofRGBA(r[0]/255,r[1]/255,r[2]/255,r[3]/255)}return null}}initializeTextRendering(){const t=document.createElement("div");t.classList.add("textRendererOutputContainer");const e=document.createElement("button");e.classList.add("rerenderButton"),e.innerText=this.editor.localization.rerenderAsText,this.textRerenderOutput=document.createElement("div"),this.textRerenderOutput.setAttribute("aria-live","polite"),e.onclick=()=>{this.rerenderAsText()},t.replaceChildren(e,this.textRerenderOutput),this.editor.createHTMLOverlay(t)}rerenderAsText(){this.textRenderer.clear(),this.editor.image.render(this.textRenderer,this.editor.viewport),this.textRerenderOutput&&(this.textRerenderOutput.innerText=this.textRenderer.getDescription())}startRerender(){var t;return null===(t=this.resizeSurfacesCallback)||void 0===t||t.call(this),this.wetInkRenderer.clear(),this.dryInkRenderer.clear(),this.dryInkRenderer}setDraftMode(t){this.dryInkRenderer.setDraftMode(t)}getDryInkRenderer(){return this.dryInkRenderer}getWetInkRenderer(){return this.wetInkRenderer}flatten(){var t;null===(t=this.flattenCallback)||void 0===t||t.call(this)}}const Rn={updatedViewport:"Transformed Viewport",transformedElements:t=>`Transformed ${t} element${1===t?"":"s"}`,resizeOutputCommand:t=>`Resized image to ${t.w}x${t.h}`,addElementAction:t=>`Added ${t}`,eraseAction:(t,e)=>`Erased ${e} ${t}`,duplicateAction:(t,e)=>`Duplicated ${e} ${t}`,unionOf:(t,e)=>`Union: ${e} ${t}`,inverseOf:t=>`Inverse of ${t}`,elements:"Elements",erasedNoElements:"Erased nothing",duplicatedNoElements:"Duplicated nothing",rotatedBy:t=>`Rotated by ${Math.abs(t)} degrees ${t<0?"clockwise":"counter-clockwise"}`,movedLeft:"Moved left",movedUp:"Moved up",movedDown:"Moved down",movedRight:"Moved right",zoomedOut:"Zoomed out",zoomedIn:"Zoomed in",selectedElements:t=>`Selected ${t} element${1===t?"":"s"}`},An=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Ee),{penTool:t=>`Pen ${t}`,selectionTool:"Selection",eraserTool:"Eraser",touchPanTool:"Touch panning",twoFingerPanZoomTool:"Panning and zooming",undoRedoTool:"Undo/Redo",rightClickDragPanTool:"Right-click drag",pipetteTool:"Pick color from screen",keyboardPanZoom:"Keyboard pan/zoom shortcuts",textTool:"Text",enterTextToInsert:"Text to insert",changeTool:"Change tool",pasteHandler:"Copy paste handler",copied:(t,e)=>`Copied ${t} ${e}`,pasted:(t,e)=>`Pasted ${t} ${e}`,toolEnabledAnnouncement:t=>`${t} enabled`,toolDisabledAnnouncement:t=>`${t} disabled`}),Rn),{unlabeledImageNode:"Unlabeled image node",stroke:"Stroke",svgObject:"SVG Object",text:t=>`Text object: ${t}`,imageNode:t=>`Image: ${t}`}),{pathNodeCount:t=>`There are ${t} visible path objects.`,textNodeCount:t=>`There are ${t} visible text nodes.`,imageNodeCount:t=>`There are ${t} visible image nodes.`,textNode:t=>`Text: ${t}`,imageNode:t=>`Image: ${t}`,unlabeledImageNode:"Unlabeled image",rerenderAsText:"Re-render as text"}),{accessibilityInputInstructions:['Press "t" to read the contents of the viewport as text.',"Use the arrow keys to move the viewport, click and drag to draw strokes.",'Press "w" to zoom in and "s" to zoom out.'].join(" "),loading:t=>`Loading ${t}%...`,imageEditor:"Image Editor",doneLoading:"Done loading",undoAnnouncement:t=>`Undid ${t}`,redoAnnouncement:t=>`Redid ${t}`}),In={de:Object.assign(Object.assign({},An),{pen:"Stift",eraser:"Radierer",select:"Auswahl",handTool:"Verschieben",zoom:"Vergrößerung",resetView:"Ansicht zurücksetzen",thicknessLabel:"Dicke: ",colorLabel:"Farbe: ",fontLabel:"Schriftart: ",resizeImageToSelection:"Bildgröße an Auswahl anpassen",deleteSelection:"Auswahl löschen",duplicateSelection:"Auswahl duplizieren",undo:"Rückgängig",redo:"Wiederholen",pickColorFromScreen:"Farbe von Bildschirm auswählen",clickToPickColorAnnouncement:"Klicke auf den Bildschirm, um eine Farbe auszuwählen",selectionToolKeyboardShortcuts:"Auswahl-Werkzeug: Verwende die Pfeiltasten, um ausgewählte Elemente zu verschieben und ‚i‘ und ‚o‘, um ihre Größe zu ändern.",touchPanning:"Ansicht mit Touchscreen verschieben",anyDevicePanning:"Ansicht mit jedem Eingabegerät verschieben",selectObjectType:"Objekt-Typ: ",freehandPen:"Freihand",arrowPen:"Pfeil",linePen:"Linie",outlinedRectanglePen:"Umrissenes Rechteck",filledRectanglePen:"Ausgefülltes Rechteck",dropdownShown:t=>`Dropdown-Menü für ${t} angezeigt`,dropdownHidden:t=>`Dropdown-Menü für ${t} versteckt`,zoomLevel:t=>`Vergößerung: ${t}%`,colorChangedAnnouncement:t=>`Farbe zu ${t} geändert`,penTool:t=>`Stift ${t}`,selectionTool:"Auswahl",eraserTool:"Radiergummi",touchPanTool:"Ansicht mit Touchscreen verschieben",twoFingerPanZoomTool:"Ansicht verschieben und vergrößern",undoRedoTool:"Rückgängig/Wiederholen",rightClickDragPanTool:"Rechtsklick-Ziehen",pipetteTool:"Farbe von Bildschirm auswählen",keyboardPanZoom:"Tastaturkürzel zum Verschieben/Vergrößern der Ansicht",textTool:"Text",enterTextToInsert:"Einzufügender Text",toolEnabledAnnouncement:t=>`${t} aktiviert`,toolDisabledAnnouncement:t=>`${t} deaktiviert`,updatedViewport:"Transformierte Ansicht",transformedElements:t=>`${t} Element${1===t?"":"e"} transformiert`,resizeOutputCommand:t=>`Bildgröße auf ${t.w}x${t.h} geändert`,addElementAction:t=>`${t} hinzugefügt`,eraseAction:(t,e)=>`${e} ${t} gelöscht`,duplicateAction:(t,e)=>`${e} ${t} dupliziert`,inverseOf:t=>`Umkehrung von ${t}`,elements:"Elemente",erasedNoElements:"Nichts entfernt",duplicatedNoElements:"Nichts dupliziert",rotatedBy:t=>`${Math.abs(t)} Grad ${t<0?"im Uhrzeigersinn":"gegen den Uhrzeigersinn"} gedreht`,movedLeft:"Nacht links bewegt",movedUp:"Nacht oben bewegt",movedDown:"Nacht unten bewegt",movedRight:"Nacht rechts bewegt",zoomedOut:"Ansicht verkleinert",zoomedIn:"Ansicht vergrößert",selectedElements:t=>`${t} Element${1===t?"":"e"} ausgewählt`,stroke:"Strich",svgObject:"SVG-Objekt",text:t=>`Text-Objekt: ${t}`,pathNodeCount:t=>`Es gibt ${t} sichtbare Pfad-Objekte.`,textNodeCount:t=>`Es gibt ${t} sichtbare Text-Knotenpunkte.`,textNode:t=>`Text: ${t}`,rerenderAsText:"Als Text darstellen",accessibilityInputInstructions:"Drücke ‚t‘, um den Inhalt des Ansichtsfensters als Text zu lesen. Verwende die Pfeiltasten, um die Ansicht zu verschieben, und klicke und ziehe, um Striche zu zeichnen. Drücke ‚w‘ zum Vergrößern und ‚s‘ zum Verkleinern der Ansicht.",loading:t=>`Laden ${t}%...`,doneLoading:"Laden fertig",imageEditor:"Bild-Editor",undoAnnouncement:t=>`Rückgangig gemacht ${t}`,redoAnnouncement:t=>`Wiederholt ${t}`}),en:Object.assign({},An),es:Object.assign(Object.assign({},An),{loading:t=>`Cargando: ${t}%...`,imageEditor:"Editor de dibujos",undoAnnouncement:t=>`${t} fue deshecho`,redoAnnouncement:t=>`${t} fue rehecho`,undo:"Deshace",redo:"Rehace",pen:"Lapiz",eraser:"Borrador",select:"Selecciona",thicknessLabel:"Tamaño: ",colorLabel:"Color: ",doneLoading:"El cargado terminó",fontLabel:"Fuente: ",anyDevicePanning:"Mover la pantalla con todo dispotivo",touchPanning:"Mover la pantalla con un dedo",touchPanTool:"Instrumento de mover la pantalla con un dedo",outlinedRectanglePen:"Rectángulo con nada más que un borde",filledRectanglePen:"Rectángulo sin borde",linePen:"Línea",arrowPen:"Flecha",freehandPen:"Dibuja sin restricción de forma",selectObjectType:"Forma de dibuja:",handTool:"Mover",zoom:"Zoom",resetView:"Reiniciar vista",resizeImageToSelection:"Redimensionar la imagen a lo que está seleccionado",deleteSelection:"Borra la selección",duplicateSelection:"Duplica la selección",pickColorFromScreen:"Selecciona un color de la pantalla",clickToPickColorAnnouncement:"Haga un clic en la pantalla para seleccionar un color",dropdownShown:t=>`Menú por ${t} es visible`,dropdownHidden:function(t){return`Menú por ${t} fue ocultado`},colorChangedAnnouncement:function(t){return`Color fue cambiado a ${t}`},keyboardPanZoom:"Mover la pantalla con el teclado",penTool:function(t){return`Lapiz ${t}`},selectionTool:"Selecciona",eraserTool:"Borrador",textTool:"Texto",enterTextToInsert:"Entra texto",rerenderAsText:"Redibuja la pantalla al texto"})},Ln=t=>{const e=/^(\w+)[_-](\w+)$/.exec(t);return e?e[1]:t},Mn=t=>{let e;null!=t||(t=navigator.languages);for(const n of t){const t=Ln(n);if(e&&t!==e&&e in In)return In[e];if(n in In)return In[n];e=t}return e&&e in In?In[e]:An};var Dn=function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{l(r.next(t))}catch(t){o(t)}}function a(t){try{l(r.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}l((r=r.apply(t,e||[])).next())}))};const On=class{constructor(t,e={}){var n,r,i,o;this.eventListenerTargets=[],this.previousAccessibilityAnnouncement="",this.announceUndoCallback=t=>{this.announceForAccessibility(this.localization.undoAnnouncement(t.description(this,this.localization)))},this.announceRedoCallback=t=>{this.announceForAccessibility(this.localization.redoAnnouncement(t.description(this,this.localization)))},this.rerenderQueued=!1,this.localization=Object.assign(Object.assign({},Mn()),e.localization),this.settings={wheelEventsEnabled:null===(n=e.wheelEventsEnabled)||void 0===n||n,renderingMode:null!==(r=e.renderingMode)&&void 0!==r?r:zn.CanvasRenderer,localization:this.localization,minZoom:null!==(i=e.minZoom)&&void 0!==i?i:2e-10,maxZoom:null!==(o=e.maxZoom)&&void 0!==o?o:1e12},this.container=document.createElement("div"),this.renderingRegion=document.createElement("div"),this.container.appendChild(this.renderingRegion),this.container.className="imageEditorContainer",this.loadingWarning=document.createElement("div"),this.loadingWarning.classList.add("loadingMessage"),this.loadingWarning.ariaLive="polite",this.container.appendChild(this.loadingWarning),this.accessibilityControlArea=document.createElement("textarea"),this.accessibilityControlArea.setAttribute("placeholder",this.localization.accessibilityInputInstructions),this.accessibilityControlArea.style.opacity="0",this.accessibilityControlArea.style.width="0",this.accessibilityControlArea.style.height="0",this.accessibilityControlArea.style.position="absolute",this.accessibilityAnnounceArea=document.createElement("div"),this.accessibilityAnnounceArea.setAttribute("aria-live","assertive"),this.accessibilityAnnounceArea.className="accessibilityAnnouncement",this.container.appendChild(this.accessibilityAnnounceArea),this.renderingRegion.style.touchAction="none",this.renderingRegion.className="imageEditorRenderArea",this.renderingRegion.appendChild(this.accessibilityControlArea),this.renderingRegion.setAttribute("tabIndex","0"),this.renderingRegion.setAttribute("alt",""),this.notifier=new Te,this.importExportViewport=new H(this.notifier),this.viewport=new H(this.notifier),this.display=new Bn(this,this.settings.renderingMode,this.renderingRegion),this.image=new I,this.history=new we(this,this.announceRedoCallback,this.announceUndoCallback),this.toolController=new ye(this,this.localization),t.appendChild(this.container),this.importExportViewport.updateScreenSize(k.of(500,500)),this.viewport.updateScreenSize(k.of(this.display.width,this.display.height)),this.registerListeners(),this.queueRerender(),this.hideLoadingWarning(),this.notifier.on(D.ViewportChanged,(t=>{if(t.kind===D.ViewportChanged){const e=t.newTransform.transformVec3(k.unitX).length();if(e>this.settings.maxZoom||e<this.settings.minZoom){const e=t.oldTransform.transformVec3(k.unitX).length();let n=P.identity;e<=this.settings.maxZoom&&e>=this.settings.minZoom&&(n=t.oldTransform),this.viewport.resetTransform(n)}}}))}getRootElement(){return this.container}showLoadingWarning(t){const e=Math.round(100*t);this.loadingWarning.innerText=this.localization.loading(e),this.loadingWarning.style.display="block"}hideLoadingWarning(){this.loadingWarning.style.display="none",this.announceForAccessibility(this.localization.doneLoading)}announceForAccessibility(t){t===this.previousAccessibilityAnnouncement&&(t+=". "),this.accessibilityAnnounceArea.innerText=t,this.previousAccessibilityAnnouncement=t}addToolbar(t=!0){const e=new bn(this,this.container,this.localization);return t&&(e.addDefaultToolWidgets(),e.addDefaultActionButtons()),e}registerListeners(){const t={},e=()=>{const e=(new Date).getTime(),n=[];for(const r in t){const i=2e3;t[r]&&e-t[r].timeStamp<i&&n.push(t[r])}return n};this.renderingRegion.addEventListener("touchstart",(t=>t.preventDefault())),this.renderingRegion.addEventListener("contextmenu",(t=>{t.preventDefault()})),this.renderingRegion.addEventListener("pointerdown",(n=>{const r=$.ofEvent(n,!0,this.viewport);t[r.id]=r,this.renderingRegion.setPointerCapture(r.id);const i={kind:M.PointerDownEvt,current:r,allPointers:e()};return this.toolController.dispatchInputEvent(i),!0})),this.renderingRegion.addEventListener("pointermove",(n=>{var r,i;const o=$.ofEvent(n,null!==(i=null===(r=t[n.pointerId])||void 0===r?void 0:r.down)&&void 0!==i&&i,this.viewport);if(o.down){const r=t[o.id];if(r){if(o.screenPos.minus(r.screenPos).magnitude()<2)return}t[o.id]=o,this.toolController.dispatchInputEvent({kind:M.PointerMoveEvt,current:o,allPointers:e()})&&n.preventDefault()}}));const n=n=>{const r=$.ofEvent(n,!1,this.viewport);t[r.id]&&(t[r.id]=r,this.renderingRegion.releasePointerCapture(r.id),this.toolController.dispatchInputEvent({kind:M.PointerUpEvt,current:r,allPointers:e()})&&n.preventDefault(),delete t[r.id])};this.renderingRegion.addEventListener("pointerup",(t=>{n(t)})),this.renderingRegion.addEventListener("pointercancel",(t=>{n(t)})),this.handleKeyEventsFrom(this.renderingRegion),this.container.addEventListener("wheel",(t=>{let e=C.of(t.deltaX,t.deltaY,t.deltaZ);if(!t.ctrlKey){if(!this.settings.wheelEventsEnabled)return;if("only-if-focused"===this.settings.wheelEventsEnabled){if(!this.container.querySelector(":focus"))return}}t.deltaMode===WheelEvent.DOM_DELTA_LINE?e=e.times(15):t.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(e=e.times(100)),t.ctrlKey&&(e=C.of(0,0,t.deltaY));const n=k.of(t.offsetX,t.offsetY);return!!this.toolController.dispatchInputEvent({kind:M.WheelEvt,delta:e,screenPos:n})&&(t.preventDefault(),!0)})),this.notifier.on(D.DisplayResized,(t=>{this.viewport.updateScreenSize(k.of(this.display.width,this.display.height))})),window.addEventListener("resize",(()=>{this.notifier.dispatch(D.DisplayResized,{kind:D.DisplayResized,newSize:k.of(this.display.width,this.display.height)}),this.queueRerender()})),this.accessibilityControlArea.addEventListener("input",(()=>{this.accessibilityControlArea.value=""})),document.addEventListener("copy",(t=>{if(!this.isEventSink(document.querySelector(":focus")))return;const e=t.clipboardData;this.toolController.dispatchInputEvent({kind:M.CopyEvent,setData:(t,n)=>{null==e||e.setData(t,n)}})&&t.preventDefault()})),document.addEventListener("paste",(t=>{this.handlePaste(t)}))}isEventSink(t){let e=t;for(;null!==e;){for(const t of this.eventListenerTargets)if(t===e)return!0;e=e.parentElement}return!1}handlePaste(t){var e,n;return Dn(this,void 0,void 0,(function*(){const r=null!==(e=document.querySelector(":focus"))&&void 0!==e?e:t.target;if(!this.isEventSink(r))return;const i=null!==(n=t.dataTransfer)&&void 0!==n?n:t.clipboardData;if(!i)return;for(const e of i.files)if("image/svg+xml"===e.type.toLowerCase()){const n=yield e.text();if(this.toolController.dispatchInputEvent({kind:M.PasteEvent,mime:e.type,data:n}))return void t.preventDefault()}for(const e of i.files){const n=e.type.toLowerCase();if("image/png"===n||"image/jpg"===n){const r=new FileReader;this.showLoadingWarning(0);try{const i=yield new Promise(((t,n)=>{r.onload=()=>t(r.result),r.onerror=n,r.onabort=n,r.onprogress=t=>{this.showLoadingWarning(t.loaded/t.total)},r.readAsDataURL(e)}));if(i&&this.toolController.dispatchInputEvent({kind:M.PasteEvent,mime:n,data:i}))return t.preventDefault(),void this.hideLoadingWarning()}catch(t){console.error("Error reading image:",t)}this.hideLoadingWarning()}}const o=["image/svg+xml","text/plain"];for(const e of o){const n=i.getData(e);if(n&&this.toolController.dispatchInputEvent({kind:M.PasteEvent,mime:e,data:n}))return void t.preventDefault()}}))}handleKeyEventsFrom(t){t.addEventListener("keydown",(t=>{"t"===t.key||"T"===t.key?(t.preventDefault(),this.display.rerenderAsText()):this.toolController.dispatchInputEvent({kind:M.KeyPressEvent,key:t.key,ctrlKey:t.ctrlKey})?t.preventDefault():"Escape"===t.key&&this.renderingRegion.blur()})),t.addEventListener("keyup",(t=>{this.toolController.dispatchInputEvent({kind:M.KeyUpEvent,key:t.key,ctrlKey:t.ctrlKey})&&t.preventDefault()})),t.ondragover=t=>{t.preventDefault()},t.ondrop=t=>{t.preventDefault(),this.handlePaste(t)},this.eventListenerTargets.push(t)}dispatch(t,e=!0){e?this.history.push(t):t.apply(this),this.announceForAccessibility(t.description(this,this.localization))}dispatchNoAnnounce(t,e=!1){e?this.history.push(t):t.apply(this)}asyncApplyOrUnapplyCommands(t,e,n){return Dn(this,void 0,void 0,(function*(){console.assert(n>0),this.display.setDraftMode(!0);for(let r=0;r<t.length;r+=n){this.showLoadingWarning(r/t.length);for(let i=r;i<t.length&&i<r+n;i++){const n=t[i];e?n.apply(this):n.unapply(this)}r+n<t.length&&(yield new Promise((t=>{this.rerender(),requestAnimationFrame(t)})))}this.display.setDraftMode(!1),this.hideLoadingWarning()}))}asyncApplyCommands(t,e){return this.asyncApplyOrUnapplyCommands(t,!0,e)}asyncUnapplyCommands(t,e){return this.asyncApplyOrUnapplyCommands(t,!1,e)}queueRerender(){this.rerenderQueued||(this.rerenderQueued=!0,requestAnimationFrame((()=>{this.rerender(),this.rerenderQueued=!1})))}rerender(t=!0){if(this.display.startRerender(),0===this.display.width||0===this.display.height)return;const e=this.display.getDryInkRenderer();if(this.image.renderWithCache(e,this.display.getCache(),this.viewport),t){const t={fill:Et.fromHex("#44444455")},n=5*this.viewport.getSizeOfPixelOnCanvas();e.drawRect(this.importExportViewport.visibleRect,n,t)}this.rerenderQueued=!1}drawWetInk(...t){for(const e of t)this.display.getWetInkRenderer().drawPath(e)}clearWetInk(){this.display.getWetInkRenderer().clear()}focus(){this.renderingRegion.focus()}createHTMLOverlay(t){return t.classList.add("overlay"),this.container.appendChild(t),{remove:()=>t.remove()}}addStyleSheet(t){const e=document.createElement("style");return e.innerText=t,this.container.appendChild(e),e}sendPenEvent(t,e,n){const r=$.ofCanvasPoint(e,t!==M.PointerUpEvt,this.viewport);this.toolController.dispatchInputEvent({kind:t,allPointers:null!=n?n:[r],current:r})}toSVG(){const t=this.importExportViewport,e="http://www.w3.org/2000/svg",n=document.createElementNS(e,"svg"),r=new te(n,t),i=t.canvasToScreenTransform;t.resetTransform(P.identity),this.image.renderAll(r),t.resetTransform(i);const o=t.visibleRect;return n.setAttribute("viewBox",`${o.x} ${o.y} ${o.w} ${o.h}`),n.setAttribute("width",`${o.w}`),n.setAttribute("height",`${o.h}`),n.setAttribute("version","1.1"),n.setAttribute("baseProfile","full"),n.setAttribute("xmlns",e),n}loadFrom(t){return Dn(this,void 0,void 0,(function*(){this.showLoadingWarning(0),this.display.setDraftMode(!0),yield t.start((t=>{this.dispatchNoAnnounce(I.addElement(t))}),((t,e)=>t%500==0?(this.showLoadingWarning(t/e),this.rerender(),new Promise((t=>{requestAnimationFrame((()=>t()))}))):null),(t=>{this.dispatchNoAnnounce(this.setImportExportRect(t),!1),this.dispatchNoAnnounce(this.viewport.zoomTo(t),!1)})),this.hideLoadingWarning(),this.display.setDraftMode(!1),this.queueRerender()}))}getImportExportRect(){return this.importExportViewport.visibleRect}setImportExportRect(t){const e=this.importExportViewport.visibleRect.size,n=this.importExportViewport.canvasToScreenTransform;return new class extends w{apply(e){const n=e.importExportViewport;n.updateScreenSize(t.size),n.resetTransform(P.translation(t.topLeft.times(-1))),e.queueRerender()}unapply(t){const r=t.importExportViewport;r.updateScreenSize(e),r.resetTransform(n),t.queueRerender()}description(e,n){return n.resizeOutputCommand(t)}}}loadFromSVG(t,e=!1){return Dn(this,void 0,void 0,(function*(){const n=Jt.fromString(t,e);yield this.loadFrom(n)}))}},$n=On})(),window.jsdraw=i})();
1
+ (()=>{"use strict";var e={786:(t,e,n)=>{n.d(e,{Z:()=>a});var r=n(81),i=n.n(r),o=n(645),s=n.n(o)()(i());s.push([t.id,'.clr-picker {\r\n display: none;\r\n flex-wrap: wrap;\r\n position: absolute;\r\n width: 200px;\r\n z-index: 1000;\r\n border-radius: 10px;\r\n background-color: #fff;\r\n justify-content: space-between;\r\n box-shadow: 0 0 5px rgba(0,0,0,.05), 0 5px 20px rgba(0,0,0,.1);\r\n -moz-user-select: none;\r\n -webkit-user-select: none;\r\n user-select: none;\r\n}\r\n\r\n.clr-picker.clr-open,\r\n.clr-picker[data-inline="true"] {\r\n display: flex;\r\n}\r\n\r\n.clr-picker[data-inline="true"] {\r\n position: relative;\r\n}\r\n\r\n.clr-gradient {\r\n position: relative;\r\n width: 100%;\r\n height: 100px;\r\n margin-bottom: 15px;\r\n border-radius: 3px 3px 0 0;\r\n background-image: linear-gradient(rgba(0,0,0,0), #000), linear-gradient(90deg, #fff, currentColor);\r\n cursor: pointer;\r\n}\r\n\r\n.clr-marker {\r\n position: absolute;\r\n width: 12px;\r\n height: 12px;\r\n margin: -6px 0 0 -6px;\r\n border: 1px solid #fff;\r\n border-radius: 50%;\r\n background-color: currentColor;\r\n cursor: pointer;\r\n}\r\n\r\n.clr-picker input[type="range"]::-webkit-slider-runnable-track {\r\n width: 100%;\r\n height: 8px;\r\n}\r\n\r\n.clr-picker input[type="range"]::-webkit-slider-thumb {\r\n width: 8px;\r\n height: 8px;\r\n -webkit-appearance: none;\r\n}\r\n\r\n.clr-picker input[type="range"]::-moz-range-track {\r\n width: 100%;\r\n height: 8px;\r\n border: 0;\r\n}\r\n\r\n.clr-picker input[type="range"]::-moz-range-thumb {\r\n width: 8px;\r\n height: 8px;\r\n border: 0;\r\n}\r\n\r\n.clr-hue {\r\n background-image: linear-gradient(to right, #f00 0%, #ff0 16.66%, #0f0 33.33%, #0ff 50%, #00f 66.66%, #f0f 83.33%, #f00 100%);\r\n}\r\n\r\n.clr-hue,\r\n.clr-alpha {\r\n position: relative;\r\n width: calc(100% - 40px);\r\n height: 8px;\r\n margin: 5px 20px;\r\n border-radius: 4px;\r\n}\r\n\r\n.clr-alpha span {\r\n display: block;\r\n height: 100%;\r\n width: 100%;\r\n border-radius: inherit;\r\n background-image: linear-gradient(90deg, rgba(0,0,0,0), currentColor);\r\n}\r\n\r\n.clr-hue input,\r\n.clr-alpha input {\r\n position: absolute;\r\n width: calc(100% + 16px);\r\n height: 16px;\r\n left: -8px;\r\n top: -4px;\r\n margin: 0;\r\n background-color: transparent;\r\n opacity: 0;\r\n cursor: pointer;\r\n appearance: none;\r\n -webkit-appearance: none;\r\n}\r\n\r\n.clr-hue div,\r\n.clr-alpha div {\r\n position: absolute;\r\n width: 16px;\r\n height: 16px;\r\n left: 0;\r\n top: 50%;\r\n margin-left: -8px;\r\n transform: translateY(-50%);\r\n border: 2px solid #fff;\r\n border-radius: 50%;\r\n background-color: currentColor;\r\n box-shadow: 0 0 1px #888;\r\n pointer-events: none;\r\n}\r\n\r\n.clr-alpha div:before {\r\n content: \'\';\r\n position: absolute;\r\n height: 100%;\r\n width: 100%;\r\n left: 0;\r\n top: 0;\r\n border-radius: 50%;\r\n background-color: currentColor;\r\n}\r\n\r\n.clr-format {\r\n display: none;\r\n order: 1;\r\n width: calc(100% - 40px);\r\n margin: 0 20px 20px;\r\n}\r\n\r\n.clr-segmented {\r\n display: flex;\r\n position: relative;\r\n width: 100%;\r\n margin: 0;\r\n padding: 0;\r\n border: 1px solid #ddd;\r\n border-radius: 15px;\r\n box-sizing: border-box;\r\n color: #999;\r\n font-size: 12px;\r\n}\r\n\r\n.clr-segmented input,\r\n.clr-segmented legend {\r\n position: absolute;\r\n width: 100%;\r\n height: 100%;\r\n margin: 0;\r\n padding: 0;\r\n border: 0;\r\n left: 0;\r\n top: 0;\r\n opacity: 0;\r\n pointer-events: none;\r\n}\r\n\r\n.clr-segmented label {\r\n flex-grow: 1;\r\n padding: 4px 0;\r\n text-align: center;\r\n cursor: pointer;\r\n}\r\n\r\n.clr-segmented label:first-of-type {\r\n border-radius: 10px 0 0 10px;\r\n}\r\n\r\n.clr-segmented label:last-of-type {\r\n border-radius: 0 10px 10px 0;\r\n}\r\n\r\n.clr-segmented input:checked + label {\r\n color: #fff;\r\n background-color: #666;\r\n}\r\n\r\n.clr-swatches {\r\n order: 2;\r\n width: calc(100% - 32px);\r\n margin: 0 16px;\r\n}\r\n\r\n.clr-swatches div {\r\n display: flex;\r\n flex-wrap: wrap;\r\n padding-bottom: 12px;\r\n justify-content: center;\r\n}\r\n\r\n.clr-swatches button {\r\n position: relative;\r\n width: 20px;\r\n height: 20px;\r\n margin: 0 4px 6px 4px;\r\n border: 0;\r\n border-radius: 50%;\r\n color: inherit;\r\n text-indent: -1000px;\r\n white-space: nowrap;\r\n overflow: hidden;\r\n cursor: pointer;\r\n}\r\n\r\n.clr-swatches button:after {\r\n content: \'\';\r\n display: block;\r\n position: absolute;\r\n width: 100%;\r\n height: 100%;\r\n left: 0;\r\n top: 0;\r\n border-radius: inherit;\r\n background-color: currentColor;\r\n box-shadow: inset 0 0 0 1px rgba(0,0,0,.1);\r\n}\r\n\r\ninput.clr-color {\r\n order: 1;\r\n width: calc(100% - 80px);\r\n height: 32px;\r\n margin: 15px 20px 20px 0;\r\n padding: 0 10px;\r\n border: 1px solid #ddd;\r\n border-radius: 16px;\r\n color: #444;\r\n background-color: #fff;\r\n font-family: sans-serif;\r\n font-size: 14px;\r\n text-align: center;\r\n box-shadow: none;\r\n}\r\n\r\ninput.clr-color:focus {\r\n outline: none;\r\n border: 1px solid #1e90ff;\r\n}\r\n\r\n.clr-clear {\r\n display: none;\r\n order: 2;\r\n height: 24px;\r\n margin: 0 20px 20px auto;\r\n padding: 0 20px;\r\n border: 0;\r\n border-radius: 12px;\r\n color: #fff;\r\n background-color: #666;\r\n font-family: inherit;\r\n font-size: 12px;\r\n font-weight: 400;\r\n cursor: pointer;\r\n}\r\n\r\n.clr-preview {\r\n position: relative;\r\n width: 32px;\r\n height: 32px;\r\n margin: 15px 0 20px 20px;\r\n border: 0;\r\n border-radius: 50%;\r\n overflow: hidden;\r\n cursor: pointer;\r\n}\r\n\r\n.clr-preview:before,\r\n.clr-preview:after {\r\n content: \'\';\r\n position: absolute;\r\n height: 100%;\r\n width: 100%;\r\n left: 0;\r\n top: 0;\r\n border: 1px solid #fff;\r\n border-radius: 50%;\r\n}\r\n\r\n.clr-preview:after {\r\n border: 0;\r\n background-color: currentColor;\r\n box-shadow: inset 0 0 0 1px rgba(0,0,0,.1);\r\n}\r\n\r\n.clr-marker,\r\n.clr-hue div,\r\n.clr-alpha div,\r\n.clr-color {\r\n box-sizing: border-box;\r\n}\r\n\r\n.clr-field {\r\n display: inline-block;\r\n position: relative;\r\n color: transparent;\r\n}\r\n\r\n.clr-field button {\r\n position: absolute;\r\n width: 30px;\r\n height: 100%;\r\n right: 0;\r\n top: 50%;\r\n transform: translateY(-50%);\r\n border: 0;\r\n color: inherit;\r\n text-indent: -1000px;\r\n white-space: nowrap;\r\n overflow: hidden;\r\n pointer-events: none;\r\n}\r\n\r\n.clr-field button:after {\r\n content: \'\';\r\n display: block;\r\n position: absolute;\r\n width: 100%;\r\n height: 100%;\r\n left: 0;\r\n top: 0;\r\n border-radius: inherit;\r\n background-color: currentColor;\r\n box-shadow: inset 0 0 1px rgba(0,0,0,.5);\r\n}\r\n\r\n.clr-alpha,\r\n.clr-alpha div,\r\n.clr-swatches button,\r\n.clr-preview:before,\r\n.clr-field button {\r\n background-image: repeating-linear-gradient(45deg, #aaa 25%, transparent 25%, transparent 75%, #aaa 75%, #aaa), repeating-linear-gradient(45deg, #aaa 25%, #fff 25%, #fff 75%, #aaa 75%, #aaa);\r\n background-position: 0 0, 4px 4px;\r\n background-size: 8px 8px;\r\n}\r\n\r\n.clr-marker:focus {\r\n outline: none;\r\n}\r\n\r\n.clr-keyboard-nav .clr-marker:focus,\r\n.clr-keyboard-nav .clr-hue input:focus + div,\r\n.clr-keyboard-nav .clr-alpha input:focus + div,\r\n.clr-keyboard-nav .clr-segmented input:focus + label {\r\n outline: none;\r\n box-shadow: 0 0 0 2px #1e90ff, 0 0 2px 2px #fff;\r\n}\r\n\r\n.clr-picker[data-alpha="false"] .clr-alpha {\r\n display: none;\r\n}\r\n\r\n.clr-picker[data-minimal="true"] {\r\n padding-top: 16px;\r\n}\r\n\r\n.clr-picker[data-minimal="true"] .clr-gradient,\r\n.clr-picker[data-minimal="true"] .clr-hue,\r\n.clr-picker[data-minimal="true"] .clr-alpha,\r\n.clr-picker[data-minimal="true"] .clr-color,\r\n.clr-picker[data-minimal="true"] .clr-preview {\r\n display: none;\r\n}\r\n\r\n/** Dark theme **/\r\n\r\n.clr-dark {\r\n background-color: #444;\r\n}\r\n\r\n.clr-dark .clr-segmented {\r\n border-color: #777;\r\n}\r\n\r\n.clr-dark .clr-swatches button:after {\r\n box-shadow: inset 0 0 0 1px rgba(255,255,255,.3);\r\n}\r\n\r\n.clr-dark input.clr-color {\r\n color: #fff;\r\n border-color: #777;\r\n background-color: #555;\r\n}\r\n\r\n.clr-dark input.clr-color:focus {\r\n border-color: #1e90ff;\r\n}\r\n\r\n.clr-dark .clr-preview:after {\r\n box-shadow: inset 0 0 0 1px rgba(255,255,255,.5);\r\n}\r\n\r\n.clr-dark .clr-alpha,\r\n.clr-dark .clr-alpha div,\r\n.clr-dark .clr-swatches button,\r\n.clr-dark .clr-preview:before {\r\n background-image: repeating-linear-gradient(45deg, #666 25%, transparent 25%, transparent 75%, #888 75%, #888), repeating-linear-gradient(45deg, #888 25%, #444 25%, #444 75%, #888 75%, #888);\r\n}\r\n\r\n/** Polaroid theme **/\r\n\r\n.clr-picker.clr-polaroid {\r\n border-radius: 6px;\r\n box-shadow: 0 0 5px rgba(0,0,0,.1), 0 5px 30px rgba(0,0,0,.2);\r\n}\r\n\r\n.clr-picker.clr-polaroid:before {\r\n content: \'\';\r\n display: block;\r\n position: absolute;\r\n width: 16px;\r\n height: 10px;\r\n left: 20px;\r\n top: -10px;\r\n border: solid transparent;\r\n border-width: 0 8px 10px 8px;\r\n border-bottom-color: currentColor;\r\n box-sizing: border-box;\r\n color: #fff;\r\n filter: drop-shadow(0 -4px 3px rgba(0,0,0,.1));\r\n pointer-events: none;\r\n}\r\n\r\n.clr-picker.clr-polaroid.clr-dark:before {\r\n color: #444;\r\n}\r\n\r\n.clr-picker.clr-polaroid.clr-left:before {\r\n left: auto;\r\n right: 20px;\r\n}\r\n\r\n.clr-picker.clr-polaroid.clr-top:before {\r\n top: auto;\r\n bottom: -10px;\r\n transform: rotateZ(180deg);\r\n}\r\n\r\n.clr-polaroid .clr-gradient {\r\n width: calc(100% - 20px);\r\n height: 120px;\r\n margin: 10px;\r\n border-radius: 3px;\r\n}\r\n\r\n.clr-polaroid .clr-hue,\r\n.clr-polaroid .clr-alpha {\r\n width: calc(100% - 30px);\r\n height: 10px;\r\n margin: 6px 15px;\r\n border-radius: 5px;\r\n}\r\n\r\n.clr-polaroid .clr-hue div,\r\n.clr-polaroid .clr-alpha div {\r\n box-shadow: 0 0 5px rgba(0,0,0,.2);\r\n}\r\n\r\n.clr-polaroid .clr-format {\r\n width: calc(100% - 20px);\r\n margin: 0 10px 15px;\r\n}\r\n\r\n.clr-polaroid .clr-swatches {\r\n width: calc(100% - 12px);\r\n margin: 0 6px;\r\n}\r\n.clr-polaroid .clr-swatches div {\r\n padding-bottom: 10px;\r\n}\r\n\r\n.clr-polaroid .clr-swatches button {\r\n width: 22px;\r\n height: 22px;\r\n}\r\n\r\n.clr-polaroid input.clr-color {\r\n width: calc(100% - 60px);\r\n margin: 10px 10px 15px 0;\r\n}\r\n\r\n.clr-polaroid .clr-clear {\r\n margin: 0 10px 15px auto;\r\n}\r\n\r\n.clr-polaroid .clr-preview {\r\n margin: 10px 0 15px 10px;\r\n}\r\n\r\n/** Large theme **/\r\n\r\n.clr-picker.clr-large {\r\n width: 275px;\r\n}\r\n\r\n.clr-large .clr-gradient {\r\n height: 150px;\r\n}\r\n\r\n.clr-large .clr-swatches button {\r\n width: 22px;\r\n height: 22px;\r\n}\r\n\r\n/** Pill (horizontal) theme **/\r\n\r\n.clr-picker.clr-pill {\r\n width: 380px;\r\n padding-left: 180px;\r\n box-sizing: border-box;\r\n}\r\n\r\n.clr-pill .clr-gradient {\r\n position: absolute;\r\n width: 180px;\r\n height: 100%;\r\n left: 0;\r\n top: 0;\r\n margin-bottom: 0;\r\n border-radius: 3px 0 0 3px;\r\n}\r\n\r\n.clr-pill .clr-hue {\r\n margin-top: 20px;\r\n}',""]);const a=s},59:(t,e,n)=>{n.d(e,{Z:()=>h});var r=n(81),i=n.n(r),o=n(645),s=n.n(o),a=n(771),l=n(611),c=s()(i());c.i(a.Z),c.i(l.Z),c.push([t.id,"\n.imageEditorContainer {\n\t/* Deafult colors for the editor */\n --primary-background-color: white;\n --primary-background-color-transparent: rgba(255, 255, 255, 0.5);\n --secondary-background-color: #faf;\n --primary-foreground-color: black;\n --secondary-foreground-color: black;\n\t--primary-shadow-color: rgba(0, 0, 0, 0.5);\n}\n\n@media (prefers-color-scheme: dark) {\n\t.imageEditorContainer {\n\t\t--primary-background-color: #151515;\n\t\t--primary-background-color-transparent: rgba(50, 50, 50, 0.5);\n\t\t--secondary-background-color: #607;\n\t\t--primary-foreground-color: white;\n\t\t--secondary-foreground-color: white;\n\t\t--primary-shadow-color: rgba(250, 250, 250, 0.5);\n\t}\n}\n\n.imageEditorContainer {\n\tcolor: var(--primary-foreground-color);\n\tfont-family: system-ui, -apple-system, sans-serif;\n\tbackground-color: var(--primary-background-color);\n\n\tdisplay: flex;\n\tflex-direction: column-reverse;\n}\n\n.imageEditorContainer .imageEditorRenderArea {\n\tdisplay: grid;\n\tgrid-template-columns: 1fr;\n\tflex-grow: 2;\n\tflex-shrink: 1;\n\tmin-height: 100px;\n}\n\n.imageEditorContainer .imageEditorRenderArea canvas {\n\t/* Stack all canvases on top of each other */\n\tgrid-row: 1 / 1;\n\tgrid-column: 1 / 1;\n\ttouch-action: none;\n\n\t/* Fill the container */\n\tbox-sizing: border-box;\n\twidth: 100%;\n\theight: 100%;\n}\n\n.imageEditorContainer .loadingMessage {\n\tposition: fixed;\n\ttext-align: center;\n\tfont-size: 2em;\n\n\tbottom: 0;\n\tleft: 0;\n\tright: 0;\n}\n\n.imageEditorContainer .accessibilityAnnouncement {\n\topacity: 0;\n\twidth: 0;\n\theight: 0;\n\toverflow: hidden;\n\tpointer-events: none;\n}\n\n.imageEditorContainer .textRendererOutputContainer {\n\twidth: 1px;\n\theight: 1px;\n\toverflow: hidden;\n}\n\n.imageEditorContainer .textRendererOutputContainer:focus-within {\n\toverflow: visible;\n}\n",""]);const h=c},771:(t,e,n)=>{n.d(e,{Z:()=>a});var r=n(81),i=n.n(r),o=n(645),s=n.n(o)()(i());s.push([t.id,".toolbar-root {\n\tbackground-color: var(--primary-background-color);\n\t--icon-color: var(--primary-foreground-color);\n\n\n\tborder: 1px solid var(--secondary-background-color);\n\tborder-radius: 2px;\n\tflex-wrap: wrap;\n\n\tbox-sizing: border-box;\n\twidth: 100%;\n\n\tdisplay: flex;\n\tflex-direction: row;\n\tjustify-content: center;\n\n\t/* Display above selection dialogs, etc. */\n\tz-index: 2;\n\n\tfont-family: system-ui, -apple-system, sans-serif;\n}\n\n.toolbar-root > .toolbar-toolContainer > .toolbar-button,\n.toolbar-root > .toolbar-toolContainer > * > button,\n.toolbar-root > .toolbar-buttonGroup > button,\n.toolbar-root > .toolbar-button {\n\twidth: min-content;\n\twhite-space: pre;\n\theight: min(20vh, 60px);\n}\n\n.toolbar-dropdown .toolbar-button > .toolbar-icon {\n\tmax-width: 50px;\n}\n\n.toolbar-button.disabled {\n\tfilter: opacity(0.5) sepia(0.2);\n\tcursor: unset;\n}\n\n.toolbar-button, .toolbar-root button {\n\tcursor: pointer;\n\ttext-align: center;\n\tborder-radius: 6px;\n\n\t--icon-color: var(--primary-foreground-color);\n\tbackground-color: var(--primary-background-color);\n\tcolor: var(--primary-foreground-color);\n\tborder: none;\n\tbox-shadow: 0px 0px 2px var(--primary-shadow-color);\n\n\ttransition: background-color 0.25s ease, box-shadow 0.25s ease, opacity 0.3s ease;\n}\n\n.toolbar-button,\n.toolbar-buttonGroup > button,\n.toolbar-toolContainer > * > button,\n.toolbar-root > button {\n\tdisplay: flex;\n\tflex-direction: column;\n\talign-items: center;\n\tjustify-content: center;\n\n\tpadding-left: 3px;\n\tpadding-right: 3px;\n\tmargin-left: 3px;\n\tmargin-right: 3px;\n\n\tmin-width: 40px;\n\twidth: min-content;\n\tfont-size: 1em;\n}\n\n.toolbar-dropdown > .toolbar-toolContainer > button,\n.toolbar-dropdown > .toolbar-toolContainer > .toolbar-button {\n\twidth: 6em;\n}\n\n.toolbar-button:not(.disabled):hover, .toolbar-root button:not(:disabled):hover {\n\tbox-shadow: 0px 2px 4px var(--primary-shadow-color);\n}\n\n.toolbar-root button:disabled {\n\tcursor: inherit;\n\tfilter: opacity(0.5);\n}\n\n.toolbar-root .toolbar-icon {\n\tflex-shrink: 1;\n\tmin-width: 30px;\n\tmin-height: 30px;\n}\n\n.toolbar-toolContainer.selected > .toolbar-button {\n\tbackground-color: var(--secondary-background-color);\n\tcolor: var(--secondary-foreground-color);\n\t--icon-color: var(--secondary-foreground-color);\n}\n\n.toolbar-toolContainer:not(.selected):not(.dropdownShowable) > .toolbar-button > .toolbar-showHideDropdownIcon {\n\tdisplay: none;\n}\n\n.toolbar-toolContainer > .toolbar-button > .toolbar-showHideDropdownIcon {\n\theight: 10px;\n\ttransition: transform 0.5s ease;\n}\n\n.toolbar-toolContainer.dropdownVisible > .toolbar-button > .toolbar-showHideDropdownIcon {\n\ttransform: rotate(180deg);\n}\n\n.toolbar-dropdown.hidden,\n.toolbar-toolContainer:not(.selected):not(.dropdownShowable) > .toolbar-dropdown {\n\tdisplay: none;\n}\n\n.toolbar-dropdown {\n\tposition: absolute;\n\tpadding: 15px;\n\tpadding-top: 5px;\n\n\t/* Prevent overlap/being displayed under the undo/redo buttons */\n\tz-index: 2;\n\tbackground-color: var(--primary-background-color);\n\tbox-shadow: 0px 3px 3px var(--primary-shadow-color);\n}\n\n.toolbar-buttonGroup {\n\tdisplay: flex;\n\tflex-direction: row;\n\tjustify-content: center;\n}\n\n.toolbar-closeColorPickerOverlay {\n\tdisplay: none;\n\tposition: fixed;\n\ttop: 0;\n\tleft: 0;\n\tbottom: 0;\n\tright: 0;\n\n\tbackground-color: var(--primary-background-color);\n\topacity: 0.3;\n}\n\n/* Make color selection buttons fill their containing label */\n.toolbar-dropdown .clr-field button {\n\twidth: 100%;\n\theight: 100%;\n\tborder-radius: 2px;\n\tmargin-left: 0;\n\tmargin-right: 0;\n}\n\n.toolbar-root .toolbar-zoomLevelEditor {\n\tdisplay: flex;\n\tflex-direction: row;\n}\n\n.toolbar-root .toolbar-zoomLevelEditor .zoomDisplay {\n\tflex-grow: 1;\n}\n\n.toolbar-root .toolbar-zoomLevelEditor button {\n\tmin-width: 48px;\n}\n\n.color-input-container {\n\tdisplay: inline-flex;\n\tflex-direction: row;\n}\n\n.color-input-container .pipetteButton {\n\twidth: 30px;\n\theight: 30px;\n\tpadding: 0;\n\tdisplay: inline-flex;\n}\n\n.color-input-container .pipetteButton > svg {\n\twidth: 100%;\n}\n\n.color-input-container .pipetteButton.active {\n\tbackground-color: var(--secondary-background-color);\n\t--icon-color: var(--secondary-foreground-color);\n}\n",""]);const a=s},611:(t,e,n)=>{n.d(e,{Z:()=>a});var r=n(81),i=n.n(r),o=n(645),s=n.n(o)()(i());s.push([t.id,"\n.selection-tool-selection-background {\n background-color: var(--secondary-background-color);\n opacity: 0.8;\n overflow: visible;\n}\n\n.selection-tool-handle {\n border: 1px solid var(--primary-foreground-color);\n background: var(--primary-background-color);\n position: absolute;\n cursor: grab;\n}\n\n.selection-tool-handle.selection-tool-circle {\n border-radius: 100%;\n}\n\n.overlay.handleOverlay {\n height: 0;\n overflow: visible;\n}",""]);const a=s},645:t=>{t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var n="",r=void 0!==e[5];return e[4]&&(n+="@supports (".concat(e[4],") {")),e[2]&&(n+="@media ".concat(e[2]," {")),r&&(n+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),n+=t(e),r&&(n+="}"),e[2]&&(n+="}"),e[4]&&(n+="}"),n})).join("")},e.i=function(t,n,r,i,o){"string"==typeof t&&(t=[[null,t,void 0]]);var s={};if(r)for(var a=0;a<this.length;a++){var l=this[a][0];null!=l&&(s[l]=!0)}for(var c=0;c<t.length;c++){var h=[].concat(t[c]);r&&s[h[0]]||(void 0!==o&&(void 0===h[5]||(h[1]="@layer".concat(h[5].length>0?" ".concat(h[5]):""," {").concat(h[1],"}")),h[5]=o),n&&(h[2]?(h[1]="@media ".concat(h[2]," {").concat(h[1],"}"),h[2]=n):h[2]=n),i&&(h[4]?(h[1]="@supports (".concat(h[4],") {").concat(h[1],"}"),h[4]=i):h[4]="".concat(i)),e.push(h))}},e}},81:t=>{t.exports=function(t){return t[1]}},379:t=>{var e=[];function n(t){for(var n=-1,r=0;r<e.length;r++)if(e[r].identifier===t){n=r;break}return n}function r(t,r){for(var o={},s=[],a=0;a<t.length;a++){var l=t[a],c=r.base?l[0]+r.base:l[0],h=o[c]||0,d="".concat(c," ").concat(h);o[c]=h+1;var u=n(d),p={css:l[1],media:l[2],sourceMap:l[3],supports:l[4],layer:l[5]};if(-1!==u)e[u].references++,e[u].updater(p);else{var m=i(p,r);r.byIndex=a,e.splice(a,0,{identifier:d,updater:m,references:1})}s.push(d)}return s}function i(t,e){var n=e.domAPI(e);n.update(t);return function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap&&e.supports===t.supports&&e.layer===t.layer)return;n.update(t=e)}else n.remove()}}t.exports=function(t,i){var o=r(t=t||[],i=i||{});return function(t){t=t||[];for(var s=0;s<o.length;s++){var a=n(o[s]);e[a].references--}for(var l=r(t,i),c=0;c<o.length;c++){var h=n(o[c]);0===e[h].references&&(e[h].updater(),e.splice(h,1))}o=l}}},569:t=>{var e={};t.exports=function(t,n){var r=function(t){if(void 0===e[t]){var n=document.querySelector(t);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(t){n=null}e[t]=n}return e[t]}(t);if(!r)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");r.appendChild(n)}},216:t=>{t.exports=function(t){var e=document.createElement("style");return t.setAttributes(e,t.attributes),t.insert(e,t.options),e}},565:(t,e,n)=>{t.exports=function(t){var e=n.nc;e&&t.setAttribute("nonce",e)}},795:t=>{t.exports=function(t){var e=t.insertStyleElement(t);return{update:function(n){!function(t,e,n){var r="";n.supports&&(r+="@supports (".concat(n.supports,") {")),n.media&&(r+="@media ".concat(n.media," {"));var i=void 0!==n.layer;i&&(r+="@layer".concat(n.layer.length>0?" ".concat(n.layer):""," {")),r+=n.css,i&&(r+="}"),n.media&&(r+="}"),n.supports&&(r+="}");var o=n.sourceMap;o&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),e.styleTagTransform(r,t,e.options)}(e,t,n)},remove:function(){!function(t){if(null===t.parentNode)return!1;t.parentNode.removeChild(t)}(e)}}}},589:t=>{t.exports=function(t,e){if(e.styleSheet)e.styleSheet.cssText=t;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(t))}}}},n={};function r(t){var i=n[t];if(void 0!==i)return i.exports;var o=n[t]={id:t,exports:{}};return e[t](o,o.exports,r),o.exports}r.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return r.d(e,{a:e}),e},r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.nc=void 0;var i={};(()=>{r.r(i),r.d(i,{AbstractComponent:()=>z,ActionButtonWidget:()=>yn,BaseTool:()=>G,BaseToolWidget:()=>gn,BaseWidget:()=>mn,Color4:()=>Et,Command:()=>w,Duplicate:()=>ne,Editor:()=>Vn,EditorEventType:()=>M,EditorImage:()=>I,Erase:()=>Ot,EraserTool:()=>$t,EraserToolWidget:()=>vn,HTMLToolbar:()=>kn,HandToolWidget:()=>Cn,ImageComponent:()=>Ft,InputEvtType:()=>D,LineSegment2:()=>R,Mat33:()=>P,PanZoomMode:()=>_,PanZoomTool:()=>q,PasteHandler:()=>ke,Path:()=>kt,PenTool:()=>Lt,PenToolWidget:()=>fn,Pointer:()=>$,PointerDevice:()=>O,Rect2:()=>B,SelectionTool:()=>ue,SelectionToolWidget:()=>xn,SerializableCommand:()=>T,Stroke:()=>Bt,StrokeComponent:()=>Bt,Text:()=>Wt,TextComponent:()=>Wt,TextTool:()=>ge,TextToolWidget:()=>bn,ToolController:()=>Ee,ToolEnabledGroup:()=>Dt,ToolSwitcherShortcut:()=>ve,UndoRedoShortcut:()=>pe,Vec2:()=>S,Vec3:()=>C,default:()=>Wn,defaultEditorLocalization:()=>$n,getLocalizationTable:()=>Un,icons:()=>e,invertCommand:()=>xe,makeColorInput:()=>ln,makeFreehandLineBuilder:()=>At,uniteCommands:()=>Ce});var e={};r.r(e),r.d(e,{makeAllDevicePanningIcon:()=>Ge,makeDeleteSelectionIcon:()=>Qe,makeDropdownIcon:()=>Fe,makeDuplicateSelectionIcon:()=>Ye,makeEraserIcon:()=>Ue,makeHandToolIcon:()=>We,makeIconFromFactory:()=>Ke,makePenIcon:()=>Ze,makePipetteIcon:()=>Xe,makeRedoIcon:()=>Ne,makeResizeViewportIcon:()=>Je,makeSelectionIcon:()=>je,makeTextIcon:()=>qe,makeTouchPanningIcon:()=>He,makeUndoIcon:()=>$e,makeZoomIcon:()=>_e});var n=r(379),o=r.n(n),s=r(795),a=r.n(s),l=r(569),c=r.n(l),h=r(565),d=r.n(h),u=r(216),p=r.n(u),m=r(589),g=r.n(m),f=r(59),v={};v.styleTagTransform=g(),v.setAttributes=d(),v.insert=c().bind(null,"head"),v.domAPI=a(),v.insertStyleElement=p();o()(f.Z,v);f.Z&&f.Z.locals&&f.Z.locals;var y=r(786),x={};x.styleTagTransform=g(),x.setAttributes=d(),x.insert=c().bind(null,"head"),x.domAPI=a(),x.insertStyleElement=p();o()(y.Z,x);y.Z&&y.Z.locals&&y.Z.locals;class b{onDrop(t){}static union(t,e){return new class extends b{apply(n){t.apply(n),e.apply(n)}unapply(n){e.unapply(n),t.unapply(n)}description(n,r){const i=t.description(n,r),o=e.description(n,r);return i===o?i:`${i}, ${o}`}}}}b.empty=new class extends b{description(t,e){return""}apply(t){}unapply(t){}};const w=b;class T extends w{constructor(t){if(super(),this.commandTypeId=t,!(t in T.deserializationCallbacks))throw new Error(`Command ${t} must have a registered deserialization callback. To do this, call SerializableCommand.register.`)}serialize(){return{data:this.serializeToJSON(),commandType:this.commandTypeId}}static deserialize(t,e){const n="string"==typeof t?JSON.parse(t):t,r=n.commandType;if(!(r in T.deserializationCallbacks))throw new Error(`Unrecognised command type ${r}!`);return T.deserializationCallbacks[r](n.data,e)}static register(t,e){T.deserializationCallbacks[t]=e}}T.deserializationCallbacks={};class C{constructor(t,e,n){this.x=t,this.y=e,this.z=n}get xy(){return{x:this.x,y:this.y}}static of(t,e,n){return new C(t,e,n)}at(t){if(0===t)return this.x;if(1===t)return this.y;if(2===t)return this.z;throw new Error(`${t} out of bounds!`)}length(){return this.magnitude()}magnitude(){return Math.sqrt(this.dot(this))}magnitudeSquared(){return this.dot(this)}angle(){return Math.atan2(this.y,this.x)}normalized(){const t=this.magnitude();return C.of(this.x/t,this.y/t,this.z/t)}times(t){return C.of(this.x*t,this.y*t,this.z*t)}plus(t){return C.of(this.x+t.x,this.y+t.y,this.z+t.z)}minus(t){return this.plus(t.times(-1))}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}cross(t){return C.of(this.y*t.z-t.y*this.z,t.x*this.z-this.x*t.z,this.x*t.y-t.x*this.y)}scale(t){return"number"==typeof t?this.times(t):C.of(this.x*t.x,this.y*t.y,this.z*t.z)}orthog(){return 0===this.dot(C.unitX)&&0===this.dot(C.unitY)?0===this.dot(C.unitX)?C.unitX:this.cross(C.unitX).normalized():this.cross(C.unitZ.times(-1)).normalized()}extend(t,e){return this.plus(e.normalized().times(t))}lerp(t,e){return this.times(1-e).plus(t.times(e))}zip(t,e){return C.of(e(t.x,this.x),e(t.y,this.y),e(t.z,this.z))}map(t){return C.of(t(this.x,0),t(this.y,1),t(this.z,2))}asArray(){return[this.x,this.y,this.z]}eq(t,e=1e-10){for(let n=0;n<3;n++)if(Math.abs(t.at(n)-this.at(n))>e)return!1;return!0}toString(){return`Vec(${this.x}, ${this.y}, ${this.z})`}}var S,k,E;C.unitX=C.of(1,0,0),C.unitY=C.of(0,1,0),C.unitZ=C.of(0,0,1),C.zero=C.of(0,0,0),function(t){t.of=(t,e)=>C.of(t,e,0),t.ofXY=({x:t,y:e})=>C.of(t,e,0),t.unitX=t.of(1,0),t.unitY=t.of(0,1),t.zero=t.of(0,0)}(S||(S={}));class P{constructor(t,e,n,r,i,o,s,a,l){this.a1=t,this.a2=e,this.a3=n,this.b1=r,this.b2=i,this.b3=o,this.c1=s,this.c2=a,this.c3=l,this.cachedInverse=void 0,this.rows=[C.of(t,e,n),C.of(r,i,o),C.of(s,a,l)]}static ofRows(t,e,n){return new P(t.x,t.y,t.z,e.x,e.y,e.z,n.x,n.y,n.z)}inverse(){var t;return null!==(t=this.computeInverse())&&void 0!==t?t:P.identity}invertable(){return null!==this.computeInverse()}computeInverse(){if(void 0!==this.cachedInverse)return this.cachedInverse;const t=[this.rows[0],this.rows[1],this.rows[2]],e=[C.unitX,C.unitY,C.unitZ];for(let n=0;n<3;n++){let r=t[n].at(n);const i=1e-10;if(Math.abs(r)<i){let o=-1;for(let e=1;e<=2;e++){const r=(n+e)%3;if(Math.abs(t[r].at(n))>=i){o=r;break}}if(-1===o)return this.cachedInverse=null,null;const s=t[n],a=e[n];t[n]=t[o],e[n]=e[o],t[o]=s,e[o]=a,r=t[n].at(n)}let o=1/r;t[n]=t[n].times(o),e[n]=e[n].times(o);const s=t[n],a=e[n];for(let r=1;r<=2;r++){const i=(n+r)%3;o=-t[i].at(n),t[i]=t[i].plus(s.times(o)),e[i]=e[i].plus(a.times(o))}}const n=P.ofRows(e[0],e[1],e[2]);return this.cachedInverse=n,n}transposed(){return new P(this.a1,this.b1,this.c1,this.a2,this.b2,this.c2,this.a3,this.b3,this.c3)}rightMul(t){t=t.transposed();const e=(e,n)=>this.rows[e].dot(t.rows[n]);return new P(e(0,0),e(0,1),e(0,2),e(1,0),e(1,1),e(1,2),e(2,0),e(2,1),e(2,2))}transformVec2(t){let e=C.of(t.x,t.y,1);return e=this.transformVec3(e),S.of(e.x,e.y)}transformVec3(t){return C.of(this.rows[0].dot(t),this.rows[1].dot(t),this.rows[2].dot(t))}eq(t,e=0){for(let n=0;n<3;n++)if(!this.rows[n].eq(t.rows[n],e))return!1;return!0}toString(){return`\n⎡ ${this.a1},\t ${this.a2},\t ${this.a3}\t ⎤\n⎢ ${this.b1},\t ${this.b2},\t ${this.b3}\t ⎥\n⎣ ${this.c1},\t ${this.c2},\t ${this.c3}\t ⎦\n\t\t`.trimEnd().trimStart()}toArray(){return[this.a1,this.a2,this.a3,this.b1,this.b2,this.b3,this.c1,this.c2,this.c3]}mapEntries(t){return new P(t(this.a1),t(this.a2),t(this.a3),t(this.b1),t(this.b2),t(this.b3),t(this.c1),t(this.c2),t(this.c3))}static translation(t){return new P(1,0,t.x,0,1,t.y,0,0,1)}static zRotation(t,e=S.zero){const n=Math.cos(t),r=Math.sin(t);let i=P.translation(e);return i=i.rightMul(new P(n,-r,0,r,n,0,0,0,1)),i.rightMul(P.translation(e.times(-1)))}static scaling2D(t,e=S.zero){let n,r,i=P.translation(e);return"number"==typeof t?(n=t,r=t):(n=t.x,r=t.y),i=i.rightMul(new P(n,0,0,0,r,0,0,0,1)),i.rightMul(P.translation(e.times(-1)))}toCSSMatrix(){return`matrix(${this.a1},${this.b1},${this.a2},${this.b2},${this.a3},${this.b3})`}static fromCSSMatrix(t){if(""===t||"none"===t)return P.identity;const e="([-]?\\d*(?:\\.\\d*)?(?:[eE][-]?\\d+)?)",n=`^\\s*matrix\\s*\\(${[e,e,e,e,e,e].join("[, \\t\\n]+")}[, \\t\\n]*\\)\\s*$`,r=new RegExp(n,"i").exec(t);if(!r)throw new Error(`Unsupported transformation: ${t}`);const i=r.slice(1).map((t=>parseFloat(t))),o=i[0],s=i[1],a=i[2],l=i[3],c=i[4],h=i[5];return new P(o,a,c,s,l,h,0,0,1)}}P.identity=new P(1,0,0,0,1,0,0,0,1);class z{constructor(t){if(this.componentKind=t,this.loadSaveData={},this.lastChangedTime=(new Date).getTime(),this.zIndex=z.zIndexCounter++,this.id=`${(new Date).getTime()}-${Math.random()}`,void 0===z.deserializationCallbacks[t])throw new Error(`Component ${t} has not been registered using AbstractComponent.registerComponent`)}getId(){return this.id}static registerComponent(t,e){this.deserializationCallbacks[t]=null!=e?e:null}attachLoadSaveData(t,e){this.loadSaveData[t]||(this.loadSaveData[t]=[]),this.loadSaveData[t].push(e)}getLoadSaveData(){return this.loadSaveData}getZIndex(){return this.zIndex}getBBox(){return this.contentBBox}transformBy(t){return new z.TransformElementCommand(t,this)}clone(){const t=this.createClone();for(const e in this.loadSaveData)for(const n of this.loadSaveData[e])t.attachLoadSaveData(e,n);return t}serialize(){const t=this.serializeToJSON();if(null===t)throw new Error(`${this} cannot be serialized.`);return{name:this.componentKind,zIndex:this.zIndex,id:this.id,loadSaveData:this.loadSaveData,data:t}}static isNotDeserializable(t){return"string"==typeof t&&(t=JSON.parse(t)),"object"!=typeof t||(!this.deserializationCallbacks[null==t?void 0:t.name]||!t.data)}static deserialize(t){if("string"==typeof t&&(t=JSON.parse(t)),z.isNotDeserializable(t))throw new Error(`Element with data ${t} cannot be deserialized.`);const e=this.deserializationCallbacks[t.name](t.data);return e.zIndex=t.zIndex,e.id=t.id,e}}z.zIndexCounter=0,z.deserializationCallbacks={},z.transformElementCommandId="transform-element",z.UnresolvedTransformElementCommand=class extends T{constructor(t,e){super(z.transformElementCommandId),this.affineTransfm=t,this.componentID=e,this.command=null}resolveCommand(t){if(this.command)return;const e=t.image.lookupElement(this.componentID);if(!e)throw new Error(`Unable to resolve component with ID ${this.componentID}`);this.command=new z.TransformElementCommand(this.affineTransfm,e)}apply(t){this.resolveCommand(t),this.command.apply(t)}unapply(t){this.resolveCommand(t),this.command.unapply(t)}description(t,e){return e.transformedElements(1)}serializeToJSON(){return{id:this.componentID,transfm:this.affineTransfm.toArray()}}},z.TransformElementCommand=(k=class extends T{constructor(t,e){super(z.transformElementCommandId),this.affineTransfm=t,this.component=e,this.origZIndex=e.zIndex}updateTransform(t,e){const n=t.image.findParent(this.component);let r=!1;n&&(n.remove(),r=!0),this.component.applyTransformation(e),r&&I.addElement(this.component).apply(t)}apply(t){this.component.zIndex=z.zIndexCounter++,this.updateTransform(t,this.affineTransfm),t.queueRerender()}unapply(t){this.component.zIndex=this.origZIndex,this.updateTransform(t,this.affineTransfm.inverse()),t.queueRerender()}description(t,e){return e.transformedElements(1)}serializeToJSON(){return{id:this.component.getId(),transfm:this.affineTransfm.toArray()}}},T.register(z.transformElementCommandId,((t,e)=>{const n=e.image.lookupElement(t.id),r=new P(...t.transfm);return n?new z.TransformElementCommand(r,n):new z.UnresolvedTransformElementCommand(r,t.id)})),k);class R{constructor(t,e){this.point1=t,this.point2=e,this.bbox=B.bboxOf([t,e]),this.direction=e.minus(t),this.length=this.direction.magnitude(),this.length>0&&(this.direction=this.direction.times(1/this.length))}get p1(){return this.point1}get p2(){return this.point2}get(t){return this.point1.plus(this.direction.times(t))}intersection(t){let e,n;if(0===this.direction.x){if(0===t.direction.x||0===this.direction.y)return null;const r=this.point1.x,i=(this.point1.x-t.point1.x)*t.direction.y/t.direction.x+t.point1.y;e=S.of(r,i),n=(i-this.point1.y)/this.direction.y}else{const r=(this.point1.y-t.point1.y)*this.direction.x*t.direction.x+this.direction.x*t.direction.y*t.point1.x-this.direction.y*t.direction.x*this.point1.x,i=t.direction.y*this.direction.x-this.direction.y*t.direction.x;if(0===i)return null;const o=r/i,s=(o-this.point1.x)/this.direction.x,a=this.point1.y+this.direction.y*s;e=S.of(o,a),n=(o-this.point1.x)/this.direction.x}const r=e.minus(this.point1).magnitude(),i=e.minus(this.point2).magnitude(),o=e.minus(t.point1).magnitude(),s=e.minus(t.point2).magnitude();return r>this.length||i>this.length||o>t.length||s>t.length?null:{point:e,t:n}}intersects(t){return null!==this.intersection(t)}closestPointTo(t){const e=t.minus(this.p1).dot(this.direction),n=this.length-e,r=this.p1.plus(this.direction.times(e));return e>0&&e<this.length?r:Math.abs(n)<Math.abs(e)?this.p2:this.p1}transformedBy(t){return new R(t.transformVec2(this.p1),t.transformVec2(this.p2))}toString(){return`LineSegment(${this.p1.toString()}, ${this.p2.toString()})`}}class B{constructor(t,e,n,r){this.x=t,this.y=e,this.w=n,this.h=r,n<0&&(this.x+=n,this.w=Math.abs(n)),r<0&&(this.y+=r,this.h=Math.abs(r)),this.topLeft=S.of(this.x,this.y),this.size=S.of(this.w,this.h),this.bottomRight=this.topLeft.plus(this.size),this.center=this.topLeft.plus(this.size.times(.5)),this.area=this.w*this.h}translatedBy(t){return new B(t.x+this.x,t.y+this.y,this.w,this.h)}resizedTo(t){return new B(this.x,this.y,t.x,t.y)}containsPoint(t){return this.x<=t.x&&this.y<=t.y&&this.x+this.w>=t.x&&this.y+this.h>=t.y}containsRect(t){return this.x<=t.x&&this.y<=t.y&&this.bottomRight.x>=t.bottomRight.x&&this.bottomRight.y>=t.bottomRight.y}intersects(t){const e=this.x,n=e+this.w,r=t.x,i=t.x+t.w;if(n<r||e>i)return!1;const o=this.y,s=o+this.h,a=t.y,l=t.y+t.h;return!(s<a||o>l)}intersection(t){if(!this.intersects(t))return null;const e=this.topLeft.zip(t.topLeft,Math.max),n=this.bottomRight.zip(t.bottomRight,Math.min);return B.fromCorners(e,n)}union(t){const e=this.topLeft.zip(t.topLeft,Math.min),n=this.bottomRight.zip(t.bottomRight,Math.max);return B.fromCorners(e,n)}divideIntoGrid(t,e){const n=[];if(t<=0||e<=0)return n;const r=this.w/t,i=this.h/e;0===r&&(t=1),0===i&&(e=1);for(let o=0;o<e;o++)for(let e=0;e<t;e++){const t=r*e+this.x,s=i*o+this.y;n.push(new B(t,s,r,i))}return n}grownToPoint(t,e=0){const n=new B(t.x-e,t.y-e,2*e,2*e);return this.union(n)}grownBy(t){return new B(this.x-t,this.y-t,this.w+2*t,this.h+2*t)}getClosestPointOnBoundaryTo(t){const e=this.getEdges().map((e=>e.closestPointTo(t)));let n=null,r=null;for(const i of e){const e=i.minus(t).length();(null===r||e<r)&&(n=i,r=e)}return n}get corners(){return[this.bottomRight,this.topRight,this.topLeft,this.bottomLeft]}get maxDimension(){return Math.max(this.w,this.h)}get topRight(){return this.bottomRight.plus(S.of(0,-this.h))}get bottomLeft(){return this.topLeft.plus(S.of(0,this.h))}get width(){return this.w}get height(){return this.h}getEdges(){const t=this.corners;return[new R(t[0],t[1]),new R(t[1],t[2]),new R(t[2],t[3]),new R(t[3],t[0])]}transformedBoundingBox(t){return B.bboxOf(this.corners.map((e=>t.transformVec2(e))))}eq(t,e=0){return this.topLeft.eq(t.topLeft,e)&&this.size.eq(t.size,e)}toString(){return`Rect(point(${this.x}, ${this.y}), size(${this.w}, ${this.h}))`}static fromCorners(t,e){return new B(Math.min(t.x,e.x),Math.min(t.y,e.y),Math.abs(t.x-e.x),Math.abs(t.y-e.y))}static bboxOf(t,e=0){let n=0,r=0,i=0,o=0,s=!0;for(const e of t)s&&(n=e.x,r=e.y,i=e.x,o=e.y,s=!1),n=Math.min(n,e.x),r=Math.min(r,e.y),i=Math.max(i,e.x),o=Math.max(o,e.y);return B.fromCorners(S.of(n-e,r-e),S.of(i+e,o+e))}static of(t){var e,n,r,i;const o=null!==(n=null!==(e=t.width)&&void 0!==e?e:t.w)&&void 0!==n?n:0,s=null!==(i=null!==(r=t.height)&&void 0!==r?r:t.h)&&void 0!==i?i:0;return new B(t.x,t.y,o,s)}}B.empty=new B(0,0,0,0),B.unitSquare=new B(0,0,1,1);const A=t=>{t.sort(((t,e)=>t.getContent().getZIndex()-e.getContent().getZIndex()))};class I{constructor(){this.root=new L,this.componentsById={}}findParent(t){const e=this.root.getLeavesIntersectingRegion(t.getBBox());for(const n of e)if(n.getContent()===t)return n;return null}renderWithCache(t,e,n){e.render(t,this.root,n)}render(t,e){this.root.render(t,e.visibleRect)}renderAll(t){const e=this.root.getLeaves();A(e);for(const n of e)n.getContent().render(t,n.getBBox())}getElementsIntersectingRegion(t){const e=this.root.getLeavesIntersectingRegion(t);return A(e),e.map((t=>t.getContent()))}onDestroyElement(t){delete this.componentsById[t.getId()]}lookupElement(t){var e;return null!==(e=this.componentsById[t])&&void 0!==e?e:null}addElementDirectly(t){return this.componentsById[t.getId()]=t,this.root.addLeaf(t)}static addElement(t,e=!1){return new I.AddElementCommand(t,e)}}I.AddElementCommand=(E=class extends T{constructor(t,e=!1){if(super("add-element"),this.element=t,this.applyByFlattening=e,this.serializedElem=t.serialize(),isNaN(t.getBBox().area))throw new Error("Elements in the image cannot have NaN bounding boxes")}apply(t){t.image.addElementDirectly(this.element),this.applyByFlattening?(this.applyByFlattening=!1,t.display.flatten()):t.queueRerender()}unapply(t){const e=t.image.findParent(this.element);null==e||e.remove(),t.queueRerender()}description(t,e){return e.addElementAction(this.element.description(e))}serializeToJSON(){return{elemData:this.serializedElem}}},T.register("add-element",((t,e)=>{const n=t.elemData.id,r=e.image.lookupElement(n),i=null!=r?r:z.deserialize(t.elemData);return new I.AddElementCommand(i)})),E);class L{constructor(t=null){this.parent=t,this.targetChildCount=30,this.children=[],this.bbox=B.empty,this.content=null,this.id=L.idCounter++}getId(){return this.id}onContentChange(){this.id=L.idCounter++}getContent(){return this.content}getParent(){return this.parent}getChildrenIntersectingRegion(t){return this.children.filter((e=>e.getBBox().intersects(t)))}getChildrenOrSelfIntersectingRegion(t){return this.content?[this]:this.getChildrenIntersectingRegion(t)}getLeavesIntersectingRegion(t,e){const n=[];let r;const i=[];i.push(this);const o=()=>{r=void 0;const o=i.pop();o&&!(null==e?void 0:e(o.bbox))&&(r=o,null!==r.content&&r.getBBox().intersection(t)&&n.push(r),i.push(...r.getChildrenIntersectingRegion(t)))};for(;i.length>0;)o();return n}getLeaves(){if(this.content)return[this];const t=[];for(const e of this.children)t.push(...e.getLeaves());return t}addLeaf(t){if(this.onContentChange(),null===this.content&&0===this.children.length)return this.content=t,this.recomputeBBox(!0),this;if(null!==this.content){console.assert(0===this.children.length);const t=new L(this);t.content=this.content,this.content=null,this.children.push(t),t.recomputeBBox(!1)}const e=t.getBBox();if(e.containsRect(this.getBBox())){const e=new L(this);if(this.children.length<this.targetChildCount)this.children.push(e);else{const t=new L(this);t.children=this.children,this.children=[e,t],t.recomputeBBox(!0),t.updateParents()}return e.addLeaf(t)}const n=this.children.filter((t=>t.getBBox().containsRect(e)));if(n.length>0&&this.children.length>=this.targetChildCount){n.sort(((t,e)=>t.getBBox().area-e.getBBox().area));const e=n[0].addLeaf(t);return e.rebalance(),e}const r=new L(this);return this.children.push(r),r.content=t,r.recomputeBBox(!0),r}getBBox(){return this.bbox}recomputeBBox(t){var e;const n=this.bbox;if(null!==this.content)this.bbox=this.content.getBBox();else{this.bbox=B.empty;let t=!0;for(const e of this.children)t?(this.bbox=e.getBBox(),t=!1):this.bbox=this.bbox.union(e.getBBox())}t&&!n.eq(this.bbox)&&(null===(e=this.parent)||void 0===e||e.recomputeBBox(!0))}updateParents(t=!1){for(const e of this.children)e.parent=this,t&&e.updateParents(t)}rebalance(){if(this.parent&&1===this.parent.children.length){console.assert(null===this.parent.content),console.assert(this.parent.children[0]===this);const t=this.parent;null!==t.parent?(t.children=[],this.parent=t.parent,this.parent.children.push(this),t.parent=null,this.parent.recomputeBBox(!1)):null===this.content&&(this.parent.children=this.children,this.parent.updateParents(),this.parent=null)}}remove(){if(!this.parent)return this.content=null,void(this.children=[]);const t=this.parent.children.length;this.parent.children=this.parent.children.filter((t=>t!==this)),console.assert(this.parent.children.length===t-1,`${t-1} ≠ ${this.parent.children.length} after removing all nodes equal to ${this}. Nodes should only be removed once.`),this.parent.children.forEach((t=>{t.rebalance()})),this.parent.recomputeBBox(!0),this.content=null,this.parent=null,this.children=[]}render(t,e){const n=this.getLeavesIntersectingRegion(e,(e=>t.isTooSmallToRender(e)));A(n);for(const r of n)r.getContent().render(t,e)}}var D,M,O;L.idCounter=0,function(t){t[t.PointerDownEvt=0]="PointerDownEvt",t[t.PointerMoveEvt=1]="PointerMoveEvt",t[t.PointerUpEvt=2]="PointerUpEvt",t[t.GestureCancelEvt=3]="GestureCancelEvt",t[t.WheelEvt=4]="WheelEvt",t[t.KeyPressEvent=5]="KeyPressEvent",t[t.KeyUpEvent=6]="KeyUpEvent",t[t.CopyEvent=7]="CopyEvent",t[t.PasteEvent=8]="PasteEvent"}(D||(D={})),function(t){t[t.ToolEnabled=0]="ToolEnabled",t[t.ToolDisabled=1]="ToolDisabled",t[t.ToolUpdated=2]="ToolUpdated",t[t.UndoRedoStackUpdated=3]="UndoRedoStackUpdated",t[t.CommandDone=4]="CommandDone",t[t.CommandUndone=5]="CommandUndone",t[t.ObjectAdded=6]="ObjectAdded",t[t.ViewportChanged=7]="ViewportChanged",t[t.DisplayResized=8]="DisplayResized",t[t.ColorPickerToggled=9]="ColorPickerToggled",t[t.ColorPickerColorSelected=10]="ColorPickerColorSelected",t[t.ToolbarDropdownShown=11]="ToolbarDropdownShown"}(M||(M={})),function(t){t[t.Pen=0]="Pen",t[t.Eraser=1]="Eraser",t[t.Touch=2]="Touch",t[t.PrimaryButtonMouse=3]="PrimaryButtonMouse",t[t.RightButtonMouse=4]="RightButtonMouse",t[t.Other=5]="Other"}(O||(O={}));class ${constructor(t,e,n,r,i,o,s,a){this.screenPos=t,this.canvasPos=e,this.pressure=n,this.isPrimary=r,this.down=i,this.device=o,this.id=s,this.timeStamp=a}static ofEvent(t,e,n,r){var i,o;let s=S.of(t.clientX,t.clientY);if(r){const t=r.getBoundingClientRect();s=s.minus(S.of(t.left,t.top))}let a=null!==(i={mouse:O.PrimaryButtonMouse,pen:O.Pen,touch:O.Touch}[t.pointerType])&&void 0!==i?i:O.Other;a===O.Pen&&0!=(32&t.buttons)&&(a=O.Eraser);const l=(new Date).getTime(),c=n.roundPoint(n.screenToCanvas(s));return a===O.PrimaryButtonMouse&&(2&t.buttons?a=O.RightButtonMouse:1&t.buttons||(a=O.Other)),new $(s,c,null!==(o=t.pressure)&&void 0!==o?o:null,t.isPrimary,e,a,t.pointerId,l)}static ofCanvasPoint(t,e,n,r=0,i=O.Pen,o=!0,s=null){const a=n.canvasToScreen(t),l=(new Date).getTime();return new $(a,t,s,o,e,i,r,l)}}var N,F,U=function(t,e,n,r,i){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?i.call(t,n):i?i.value=n:e.set(t,n),n},j=function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)};class V extends w{}class W{constructor(t){this.notifier=t,this.resetTransform(P.identity),this.screenRect=B.empty}updateScreenSize(t){this.screenRect=this.screenRect.resizedTo(t)}get visibleRect(){return this.screenRect.transformedBoundingBox(this.inverseTransform)}screenToCanvas(t){return this.inverseTransform.transformVec2(t)}canvasToScreen(t){return this.transform.transformVec2(t)}static transformBy(t){return new W.ViewportTransform(t)}resetTransform(t=P.identity){const e=this.transform;this.transform=t,this.inverseTransform=t.inverse(),this.notifier.dispatch(M.ViewportChanged,{kind:M.ViewportChanged,newTransform:t,oldTransform:e})}get screenToCanvasTransform(){return this.inverseTransform}get canvasToScreenTransform(){return this.transform}getResolution(){return this.screenRect.size}getScaleFactor(){return this.transform.transformVec3(C.unitX).magnitude()}getSizeOfPixelOnCanvas(){return 1/this.getScaleFactor()}getRotationAngle(){return this.transform.transformVec3(C.unitX).angle()}static roundPoint(t,e){const n=Math.pow(10,Math.floor(Math.log10(e))),r=t=>Math.round(t/n)*n;return"number"==typeof t?r(t):t.map(r)}roundPoint(t){return W.roundPoint(t,1/this.getScaleFactor())}static roundScaleRatio(t,e=1){if(Math.abs(t)<=1e-12)return 0;const n=Math.pow(10,Math.floor(Math.log10(Math.abs(t)))),r=Math.pow(2,e);return t=Math.round(t/n*r)/r*n}computeZoomToTransform(t,e=!0,n=!0){let r=P.identity;if(0===t.w||0===t.h)throw new Error(`${t.toString()} rectangle is empty! Cannot zoom to!`);if(isNaN(t.size.magnitude()))throw new Error(`${t.toString()} rectangle has NaN size! Cannot zoom to!`);const i=()=>{const t=this.visibleRect.transformedBoundingBox(r.inverse());return t.transformedBoundingBox(P.scaling2D(.8,t.center))};let o=i();const s=o.w<t.w||o.h<t.h,a=t.maxDimension/o.maxDimension<1/3;if(s&&n||a&&e){const e=(s?Math.max:Math.min)(t.w/o.w,t.h/o.h),n=P.scaling2D(e,o.topLeft).inverse();r=r.rightMul(n)}if(o=i(),!o.containsRect(t)){const e=t.center.minus(o.center),n=P.translation(e).inverse();r=r.rightMul(n)}return r.invertable()||(console.warn("Unable to zoom to ",t,"! Computed transform",r,"is singular."),r=P.identity),r}zoomTo(t,e=!0,n=!0){const r=this.computeZoomToTransform(t,e,n);return new W.ViewportTransform(r)}}W.ViewportTransform=(F=class extends V{constructor(t){super(),this.transform=t,N.set(this,void 0),U(this,N,t.inverse(),"f")}apply(t){const e=t.viewport;e.resetTransform(e.transform.rightMul(this.transform)),t.queueRerender()}unapply(t){const e=t.viewport;e.resetTransform(e.transform.rightMul(j(this,N,"f"))),t.queueRerender()}description(t,e){const n=[],r=t.viewport.visibleRect.center,i=this.transform.transformVec3(S.unitX),o=this.transform.transformVec2(r),s=i.magnitude(),a=180/Math.PI*i.angle(),l=o.minus(r);s>1.2?n.push(e.zoomedIn):s<.8&&n.push(e.zoomedOut),Math.floor(Math.abs(a))>0&&n.push(e.rotatedBy(Math.round(a)));const c=1e-4;return l.x>c?n.push(e.movedLeft):l.x<-1e-4&&n.push(e.movedRight),l.y<-1e-4?n.push(e.movedDown):l.y>c&&n.push(e.movedUp),n.join("; ")}},N=new WeakMap,F);const H=W;class G{constructor(t,e){this.notifier=t,this.description=e,this.enabled=!0,this.group=null}onPointerDown(t){return!1}onPointerMove(t){}onPointerUp(t){}onGestureCancel(){}onWheel(t){return!1}onCopy(t){return!1}onPaste(t){return!1}onKeyPress(t){return!1}onKeyUp(t){return!1}setEnabled(t){var e;this.enabled=t,t?(null===(e=this.group)||void 0===e||e.notifyEnabled(this),this.notifier.dispatch(M.ToolEnabled,{kind:M.ToolEnabled,tool:this})):this.notifier.dispatch(M.ToolDisabled,{kind:M.ToolDisabled,tool:this})}isEnabled(){return this.enabled}setToolGroup(t){this.isEnabled()&&t.notifyEnabled(this),this.group=t}getToolGroup(){return this.group?this.group:null}}var _;!function(t){t[t.OneFingerTouchGestures=1]="OneFingerTouchGestures",t[t.TwoFingerTouchGestures=2]="TwoFingerTouchGestures",t[t.RightClickDrags=4]="RightClickDrags",t[t.SinglePointerGestures=8]="SinglePointerGestures",t[t.Keyboard=16]="Keyboard"}(_||(_={}));class q extends G{constructor(t,e,n){super(t.notifier,n),this.editor=t,this.mode=e,this.transform=null}computePinchData(t,e){const n=e.screenPos.minus(t.screenPos),r=n.angle(),i=n.magnitude();return{canvasCenter:e.canvasPos.plus(t.canvasPos).times(.5),screenCenter:e.screenPos.plus(t.screenPos).times(.5),angle:r,dist:i}}allPointersAreOfType(t,e){return t.every((t=>t.device===e))}onPointerDown({allPointers:t}){var e;let n=!1;const r=this.allPointersAreOfType(t,O.Touch),i=this.allPointersAreOfType(t,O.RightButtonMouse);if(r&&2===t.length&&this.mode&_.TwoFingerTouchGestures){const{screenCenter:e,angle:r,dist:i}=this.computePinchData(t[0],t[1]);this.lastAngle=r,this.lastDist=i,this.lastScreenCenter=e,n=!0}else 1===t.length&&(this.mode&_.OneFingerTouchGestures&&r||i&&this.mode&_.RightClickDrags||this.mode&_.SinglePointerGestures)&&(this.lastScreenCenter=t[0].screenPos,n=!0);return n&&(null!==(e=this.transform)&&void 0!==e||(this.transform=W.transformBy(P.identity)),this.editor.display.setDraftMode(!0)),n}getCenterDelta(t){return this.editor.viewport.screenToCanvasTransform.transformVec3(t.minus(this.lastScreenCenter))}handleTwoFingerMove(t){const{screenCenter:e,canvasCenter:n,angle:r,dist:i}=this.computePinchData(t[0],t[1]),o=this.getCenterDelta(e),s=P.translation(o).rightMul(P.scaling2D(i/this.lastDist,n)).rightMul(P.zRotation(r-this.lastAngle,n));this.lastScreenCenter=e,this.lastDist=i,this.lastAngle=r,this.transform=W.transformBy(this.transform.transform.rightMul(s))}handleOneFingerMove(t){const e=this.getCenterDelta(t.screenPos);this.transform=W.transformBy(this.transform.transform.rightMul(P.translation(e))),this.lastScreenCenter=t.screenPos}onPointerMove({allPointers:t}){var e;null!==(e=this.transform)&&void 0!==e||(this.transform=W.transformBy(P.identity));const n=this.transform;2===t.length?this.handleTwoFingerMove(t):1===t.length&&this.handleOneFingerMove(t[0]),n.unapply(this.editor),this.transform.apply(this.editor)}onPointerUp(t){this.transform&&(this.transform.unapply(this.editor),this.editor.dispatch(this.transform,!1)),this.editor.display.setDraftMode(!1),this.transform=null}onGestureCancel(){var t;null===(t=this.transform)||void 0===t||t.unapply(this.editor),this.editor.display.setDraftMode(!1),this.transform=null}updateTransform(t,e=!1){var n;let r=t;this.transform&&(r=this.transform.transform.rightMul(t)),null===(n=this.transform)||void 0===n||n.unapply(this.editor),this.transform=W.transformBy(r),this.transform.apply(this.editor),e&&this.editor.announceForAccessibility(this.transform.description(this.editor,this.editor.localization))}onWheel({delta:t,screenPos:e}){this.transform=W.transformBy(P.identity);const n=this.editor.viewport.screenToCanvas(e),r=this.editor.viewport.screenToCanvasTransform.transformVec3(C.of(-t.x,-t.y,0)),i=P.scaling2D(Math.max(.25,Math.min(Math.pow(1.04,-t.z),4)),n).rightMul(P.translation(r));return this.updateTransform(i,!0),!0}onKeyPress({key:t}){if(!(this.mode&_.Keyboard))return!1;this.transform=W.transformBy(P.identity);let e=S.zero,n=1,r=0;switch(t){case"a":case"h":case"ArrowLeft":e=S.of(-1,0);break;case"d":case"l":case"ArrowRight":e=S.of(1,0);break;case"q":case"k":case"ArrowUp":e=S.of(0,-1);break;case"e":case"j":case"ArrowDown":e=S.of(0,1);break;case"w":n=.5;break;case"s":n=2;break;case"r":r=1;break;case"R":r=-1;break;default:return!1}e=e.times(30),r*=Math.PI/8,e=e.times(-1),r*=-1,n=1/n,0!==r&&(r+=1e-4);e=this.editor.viewport.screenToCanvasTransform.transformVec3(e);const i=this.editor.viewport.visibleRect.center,o=P.scaling2D(n,i).rightMul(P.zRotation(r,i)).rightMul(P.translation(e));return this.updateTransform(o,!0),!0}setMode(t){t!==this.mode&&(this.mode=t,this.editor.notifier.dispatch(M.ToolUpdated,{kind:M.ToolUpdated,tool:this}))}getMode(){return this.mode}}const{abs:Z,cos:K,sin:X,acos:J,atan2:Y,sqrt:Q,pow:tt}=Math;function et(t){return t<0?-tt(-t,1/3):tt(t,1/3)}const nt=Math.PI,rt=2*nt,it=nt/2,ot=Number.MAX_SAFE_INTEGER||9007199254740991,st=Number.MIN_SAFE_INTEGER||-9007199254740991,at={x:0,y:0,z:0},lt={Tvalues:[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213],Cvalues:[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872],arcfn:function(t,e){const n=e(t);let r=n.x*n.x+n.y*n.y;return void 0!==n.z&&(r+=n.z*n.z),Q(r)},compute:function(t,e,n){if(0===t)return e[0].t=0,e[0];const r=e.length-1;if(1===t)return e[r].t=1,e[r];const i=1-t;let o=e;if(0===r)return e[0].t=t,e[0];if(1===r){const e={x:i*o[0].x+t*o[1].x,y:i*o[0].y+t*o[1].y,t};return n&&(e.z=i*o[0].z+t*o[1].z),e}if(r<4){let e,s,a,l=i*i,c=t*t,h=0;2===r?(o=[o[0],o[1],o[2],at],e=l,s=i*t*2,a=c):3===r&&(e=l*i,s=l*t*3,a=i*c*3,h=t*c);const d={x:e*o[0].x+s*o[1].x+a*o[2].x+h*o[3].x,y:e*o[0].y+s*o[1].y+a*o[2].y+h*o[3].y,t};return n&&(d.z=e*o[0].z+s*o[1].z+a*o[2].z+h*o[3].z),d}const s=JSON.parse(JSON.stringify(e));for(;s.length>1;){for(let e=0;e<s.length-1;e++)s[e]={x:s[e].x+(s[e+1].x-s[e].x)*t,y:s[e].y+(s[e+1].y-s[e].y)*t},void 0!==s[e].z&&(s[e]=s[e].z+(s[e+1].z-s[e].z)*t);s.splice(s.length-1,1)}return s[0].t=t,s[0]},computeWithRatios:function(t,e,n,r){const i=1-t,o=n,s=e;let a,l=o[0],c=o[1],h=o[2],d=o[3];return l*=i,c*=t,2===s.length?(a=l+c,{x:(l*s[0].x+c*s[1].x)/a,y:(l*s[0].y+c*s[1].y)/a,z:!!r&&(l*s[0].z+c*s[1].z)/a,t}):(l*=i,c*=2*i,h*=t*t,3===s.length?(a=l+c+h,{x:(l*s[0].x+c*s[1].x+h*s[2].x)/a,y:(l*s[0].y+c*s[1].y+h*s[2].y)/a,z:!!r&&(l*s[0].z+c*s[1].z+h*s[2].z)/a,t}):(l*=i,c*=1.5*i,h*=3*i,d*=t*t*t,4===s.length?(a=l+c+h+d,{x:(l*s[0].x+c*s[1].x+h*s[2].x+d*s[3].x)/a,y:(l*s[0].y+c*s[1].y+h*s[2].y+d*s[3].y)/a,z:!!r&&(l*s[0].z+c*s[1].z+h*s[2].z+d*s[3].z)/a,t}):void 0))},derive:function(t,e){const n=[];for(let r=t,i=r.length,o=i-1;i>1;i--,o--){const t=[];for(let n,i=0;i<o;i++)n={x:o*(r[i+1].x-r[i].x),y:o*(r[i+1].y-r[i].y)},e&&(n.z=o*(r[i+1].z-r[i].z)),t.push(n);n.push(t),r=t}return n},between:function(t,e,n){return e<=t&&t<=n||lt.approximately(t,e)||lt.approximately(t,n)},approximately:function(t,e,n){return Z(t-e)<=(n||1e-6)},length:function(t){const e=lt.Tvalues.length;let n=0;for(let r,i=0;i<e;i++)r=.5*lt.Tvalues[i]+.5,n+=lt.Cvalues[i]*lt.arcfn(r,t);return.5*n},map:function(t,e,n,r,i){return r+(i-r)*((t-e)/(n-e))},lerp:function(t,e,n){const r={x:e.x+t*(n.x-e.x),y:e.y+t*(n.y-e.y)};return void 0!==e.z&&void 0!==n.z&&(r.z=e.z+t*(n.z-e.z)),r},pointToString:function(t){let e=t.x+"/"+t.y;return void 0!==t.z&&(e+="/"+t.z),e},pointsToString:function(t){return"["+t.map(lt.pointToString).join(", ")+"]"},copy:function(t){return JSON.parse(JSON.stringify(t))},angle:function(t,e,n){const r=e.x-t.x,i=e.y-t.y,o=n.x-t.x,s=n.y-t.y;return Y(r*s-i*o,r*o+i*s)},round:function(t,e){const n=""+t,r=n.indexOf(".");return parseFloat(n.substring(0,r+1+e))},dist:function(t,e){const n=t.x-e.x,r=t.y-e.y;return Q(n*n+r*r)},closest:function(t,e){let n,r,i=tt(2,63);return t.forEach((function(t,o){r=lt.dist(e,t),r<i&&(i=r,n=o)})),{mdist:i,mpos:n}},abcratio:function(t,e){if(2!==e&&3!==e)return!1;if(void 0===t)t=.5;else if(0===t||1===t)return t;const n=tt(t,e)+tt(1-t,e);return Z((n-1)/n)},projectionratio:function(t,e){if(2!==e&&3!==e)return!1;if(void 0===t)t=.5;else if(0===t||1===t)return t;const n=tt(1-t,e);return n/(tt(t,e)+n)},lli8:function(t,e,n,r,i,o,s,a){const l=(t-n)*(o-a)-(e-r)*(i-s);return 0!=l&&{x:((t*r-e*n)*(i-s)-(t-n)*(i*a-o*s))/l,y:((t*r-e*n)*(o-a)-(e-r)*(i*a-o*s))/l}},lli4:function(t,e,n,r){const i=t.x,o=t.y,s=e.x,a=e.y,l=n.x,c=n.y,h=r.x,d=r.y;return lt.lli8(i,o,s,a,l,c,h,d)},lli:function(t,e){return lt.lli4(t,t.c,e,e.c)},makeline:function(t,e){return new yt(t.x,t.y,(t.x+e.x)/2,(t.y+e.y)/2,e.x,e.y)},findbbox:function(t){let e=ot,n=ot,r=st,i=st;return t.forEach((function(t){const o=t.bbox();e>o.x.min&&(e=o.x.min),n>o.y.min&&(n=o.y.min),r<o.x.max&&(r=o.x.max),i<o.y.max&&(i=o.y.max)})),{x:{min:e,mid:(e+r)/2,max:r,size:r-e},y:{min:n,mid:(n+i)/2,max:i,size:i-n}}},shapeintersections:function(t,e,n,r,i){if(!lt.bboxoverlap(e,r))return[];const o=[],s=[t.startcap,t.forward,t.back,t.endcap],a=[n.startcap,n.forward,n.back,n.endcap];return s.forEach((function(e){e.virtual||a.forEach((function(r){if(r.virtual)return;const s=e.intersects(r,i);s.length>0&&(s.c1=e,s.c2=r,s.s1=t,s.s2=n,o.push(s))}))})),o},makeshape:function(t,e,n){const r=e.points.length,i=t.points.length,o=lt.makeline(e.points[r-1],t.points[0]),s=lt.makeline(t.points[i-1],e.points[0]),a={startcap:o,forward:t,back:e,endcap:s,bbox:lt.findbbox([o,t,e,s]),intersections:function(t){return lt.shapeintersections(a,a.bbox,t,t.bbox,n)}};return a},getminmax:function(t,e,n){if(!n)return{min:0,max:0};let r,i,o=ot,s=st;-1===n.indexOf(0)&&(n=[0].concat(n)),-1===n.indexOf(1)&&n.push(1);for(let a=0,l=n.length;a<l;a++)r=n[a],i=t.get(r),i[e]<o&&(o=i[e]),i[e]>s&&(s=i[e]);return{min:o,mid:(o+s)/2,max:s,size:s-o}},align:function(t,e){const n=e.p1.x,r=e.p1.y,i=-Y(e.p2.y-r,e.p2.x-n);return t.map((function(t){return{x:(t.x-n)*K(i)-(t.y-r)*X(i),y:(t.x-n)*X(i)+(t.y-r)*K(i)}}))},roots:function(t,e){e=e||{p1:{x:0,y:0},p2:{x:1,y:0}};const n=t.length-1,r=lt.align(t,e),i=function(t){return 0<=t&&t<=1};if(2===n){const t=r[0].y,e=r[1].y,n=r[2].y,o=t-2*e+n;if(0!==o){const r=-Q(e*e-t*n),s=-t+e;return[-(r+s)/o,-(-r+s)/o].filter(i)}return e!==n&&0===o?[(2*e-n)/(2*e-2*n)].filter(i):[]}const o=r[0].y,s=r[1].y,a=r[2].y;let l=3*s-o-3*a+r[3].y,c=3*o-6*s+3*a,h=-3*o+3*s,d=o;if(lt.approximately(l,0)){if(lt.approximately(c,0))return lt.approximately(h,0)?[]:[-d/h].filter(i);const t=Q(h*h-4*c*d),e=2*c;return[(t-h)/e,(-h-t)/e].filter(i)}c/=l,h/=l,d/=l;const u=(3*h-c*c)/3,p=u/3,m=(2*c*c*c-9*c*h+27*d)/27,g=m/2,f=g*g+p*p*p;let v,y,x,b,w;if(f<0){const t=-u/3,e=Q(t*t*t),n=-m/(2*e),r=J(n<-1?-1:n>1?1:n),o=2*et(e);return x=o*K(r/3)-c/3,b=o*K((r+rt)/3)-c/3,w=o*K((r+2*rt)/3)-c/3,[x,b,w].filter(i)}if(0===f)return v=g<0?et(-g):-et(g),x=2*v-c/3,b=-v-c/3,[x,b].filter(i);{const t=Q(f);return v=et(-g+t),y=et(g+t),[v-y-c/3].filter(i)}},droots:function(t){if(3===t.length){const e=t[0],n=t[1],r=t[2],i=e-2*n+r;if(0!==i){const t=-Q(n*n-e*r),o=-e+n;return[-(t+o)/i,-(-t+o)/i]}return n!==r&&0===i?[(2*n-r)/(2*(n-r))]:[]}if(2===t.length){const e=t[0],n=t[1];return e!==n?[e/(e-n)]:[]}return[]},curvature:function(t,e,n,r,i){let o,s,a,l,c=0,h=0;const d=lt.compute(t,e),u=lt.compute(t,n),p=d.x*d.x+d.y*d.y;if(r?(o=Q(tt(d.y*u.z-u.y*d.z,2)+tt(d.z*u.x-u.z*d.x,2)+tt(d.x*u.y-u.x*d.y,2)),s=tt(p+d.z*d.z,1.5)):(o=d.x*u.y-d.y*u.x,s=tt(p,1.5)),0===o||0===s)return{k:0,r:0};if(c=o/s,h=s/o,!i){const i=lt.curvature(t-.001,e,n,r,!0).k,o=lt.curvature(t+.001,e,n,r,!0).k;l=(o-c+(c-i))/2,a=(Z(o-c)+Z(c-i))/2}return{k:c,r:h,dk:l,adk:a}},inflections:function(t){if(t.length<4)return[];const e=lt.align(t,{p1:t[0],p2:t.slice(-1)[0]}),n=e[2].x*e[1].y,r=e[3].x*e[1].y,i=e[1].x*e[2].y,o=18*(-3*n+2*r+3*i-e[3].x*e[2].y),s=18*(3*n-r-3*i),a=18*(i-n);if(lt.approximately(o,0)){if(!lt.approximately(s,0)){let t=-a/s;if(0<=t&&t<=1)return[t]}return[]}const l=2*o;if(lt.approximately(l,0))return[];const c=s*s-4*o*a;if(c<0)return[];const h=Math.sqrt(c);return[(h-s)/l,-(s+h)/l].filter((function(t){return 0<=t&&t<=1}))},bboxoverlap:function(t,e){const n=["x","y"],r=n.length;for(let i,o,s,a,l=0;l<r;l++)if(i=n[l],o=t[i].mid,s=e[i].mid,a=(t[i].size+e[i].size)/2,Z(o-s)>=a)return!1;return!0},expandbox:function(t,e){e.x.min<t.x.min&&(t.x.min=e.x.min),e.y.min<t.y.min&&(t.y.min=e.y.min),e.z&&e.z.min<t.z.min&&(t.z.min=e.z.min),e.x.max>t.x.max&&(t.x.max=e.x.max),e.y.max>t.y.max&&(t.y.max=e.y.max),e.z&&e.z.max>t.z.max&&(t.z.max=e.z.max),t.x.mid=(t.x.min+t.x.max)/2,t.y.mid=(t.y.min+t.y.max)/2,t.z&&(t.z.mid=(t.z.min+t.z.max)/2),t.x.size=t.x.max-t.x.min,t.y.size=t.y.max-t.y.min,t.z&&(t.z.size=t.z.max-t.z.min)},pairiteration:function(t,e,n){const r=t.bbox(),i=e.bbox(),o=1e5,s=n||.5;if(r.x.size+r.y.size<s&&i.x.size+i.y.size<s)return[(o*(t._t1+t._t2)/2|0)/o+"/"+(o*(e._t1+e._t2)/2|0)/o];let a=t.split(.5),l=e.split(.5),c=[{left:a.left,right:l.left},{left:a.left,right:l.right},{left:a.right,right:l.right},{left:a.right,right:l.left}];c=c.filter((function(t){return lt.bboxoverlap(t.left.bbox(),t.right.bbox())}));let h=[];return 0===c.length||(c.forEach((function(t){h=h.concat(lt.pairiteration(t.left,t.right,s))})),h=h.filter((function(t,e){return h.indexOf(t)===e}))),h},getccenter:function(t,e,n){const r=e.x-t.x,i=e.y-t.y,o=n.x-e.x,s=n.y-e.y,a=r*K(it)-i*X(it),l=r*X(it)+i*K(it),c=o*K(it)-s*X(it),h=o*X(it)+s*K(it),d=(t.x+e.x)/2,u=(t.y+e.y)/2,p=(e.x+n.x)/2,m=(e.y+n.y)/2,g=d+a,f=u+l,v=p+c,y=m+h,x=lt.lli8(d,u,g,f,p,m,v,y),b=lt.dist(x,t);let w,T=Y(t.y-x.y,t.x-x.x),C=Y(e.y-x.y,e.x-x.x),S=Y(n.y-x.y,n.x-x.x);return T<S?((T>C||C>S)&&(T+=rt),T>S&&(w=S,S=T,T=w)):S<C&&C<T?(w=S,S=T,T=w):S+=rt,x.s=T,x.e=S,x.r=b,x},numberSort:function(t,e){return t-e}};class ct{constructor(t){this.curves=[],this._3d=!1,t&&(this.curves=t,this._3d=this.curves[0]._3d)}valueOf(){return this.toString()}toString(){return"["+this.curves.map((function(t){return lt.pointsToString(t.points)})).join(", ")+"]"}addCurve(t){this.curves.push(t),this._3d=this._3d||t._3d}length(){return this.curves.map((function(t){return t.length()})).reduce((function(t,e){return t+e}))}curve(t){return this.curves[t]}bbox(){const t=this.curves;for(var e=t[0].bbox(),n=1;n<t.length;n++)lt.expandbox(e,t[n].bbox());return e}offset(t){const e=[];return this.curves.forEach((function(n){e.push(...n.offset(t))})),new ct(e)}}const{abs:ht,min:dt,max:ut,cos:pt,sin:mt,acos:gt,sqrt:ft}=Math,vt=Math.PI;class yt{constructor(t){let e=t&&t.forEach?t:Array.from(arguments).slice(),n=!1;if("object"==typeof e[0]){n=e.length;const t=[];e.forEach((function(e){["x","y","z"].forEach((function(n){void 0!==e[n]&&t.push(e[n])}))})),e=t}let r=!1;const i=e.length;if(n){if(n>4){if(1!==arguments.length)throw new Error("Only new Bezier(point[]) is accepted for 4th and higher order curves");r=!0}}else if(6!==i&&8!==i&&9!==i&&12!==i&&1!==arguments.length)throw new Error("Only new Bezier(point[]) is accepted for 4th and higher order curves");const o=this._3d=!r&&(9===i||12===i)||t&&t[0]&&void 0!==t[0].z,s=this.points=[];for(let t=0,n=o?3:2;t<i;t+=n){var a={x:e[t],y:e[t+1]};o&&(a.z=e[t+2]),s.push(a)}const l=this.order=s.length-1,c=this.dims=["x","y"];o&&c.push("z"),this.dimlen=c.length;const h=lt.align(s,{p1:s[0],p2:s[l]}),d=lt.dist(s[0],s[l]);this._linear=h.reduce(((t,e)=>t+ht(e.y)),0)<d/50,this._lut=[],this._t1=0,this._t2=1,this.update()}static quadraticFromPoints(t,e,n,r){if(void 0===r&&(r=.5),0===r)return new yt(e,e,n);if(1===r)return new yt(t,e,e);const i=yt.getABC(2,t,e,n,r);return new yt(t,i.A,n)}static cubicFromPoints(t,e,n,r,i){void 0===r&&(r=.5);const o=yt.getABC(3,t,e,n,r);void 0===i&&(i=lt.dist(e,o.C));const s=i*(1-r)/r,a=lt.dist(t,n),l=(n.x-t.x)/a,c=(n.y-t.y)/a,h=i*l,d=i*c,u=s*l,p=s*c,m=e.x-h,g=e.y-d,f=e.x+u,v=e.y+p,y=o.A,x=y.x+(m-y.x)/(1-r),b=y.y+(g-y.y)/(1-r),w=y.x+(f-y.x)/r,T=y.y+(v-y.y)/r,C={x:t.x+(x-t.x)/r,y:t.y+(b-t.y)/r},S={x:n.x+(w-n.x)/(1-r),y:n.y+(T-n.y)/(1-r)};return new yt(t,C,S,n)}static getUtils(){return lt}getUtils(){return yt.getUtils()}static get PolyBezier(){return ct}valueOf(){return this.toString()}toString(){return lt.pointsToString(this.points)}toSVG(){if(this._3d)return!1;const t=this.points,e=["M",t[0].x,t[0].y,2===this.order?"Q":"C"];for(let n=1,r=t.length;n<r;n++)e.push(t[n].x),e.push(t[n].y);return e.join(" ")}setRatios(t){if(t.length!==this.points.length)throw new Error("incorrect number of ratio values");this.ratios=t,this._lut=[]}verify(){const t=this.coordDigest();t!==this._print&&(this._print=t,this.update())}coordDigest(){return this.points.map((function(t,e){return""+e+t.x+t.y+(t.z?t.z:0)})).join("")}update(){this._lut=[],this.dpoints=lt.derive(this.points,this._3d),this.computedirection()}computedirection(){const t=this.points,e=lt.angle(t[0],t[this.order],t[1]);this.clockwise=e>0}length(){return lt.length(this.derivative.bind(this))}static getABC(t=2,e,n,r,i=.5){const o=lt.projectionratio(i,t),s=1-o,a={x:o*e.x+s*r.x,y:o*e.y+s*r.y},l=lt.abcratio(i,t);return{A:{x:n.x+(n.x-a.x)/l,y:n.y+(n.y-a.y)/l},B:n,C:a,S:e,E:r}}getABC(t,e){e=e||this.get(t);let n=this.points[0],r=this.points[this.order];return yt.getABC(this.order,n,e,r,t)}getLUT(t){if(this.verify(),t=t||100,this._lut.length===t)return this._lut;this._lut=[],t++,this._lut=[];for(let e,n,r=0;r<t;r++)n=r/(t-1),e=this.compute(n),e.t=n,this._lut.push(e);return this._lut}on(e,n){n=n||5;const r=this.getLUT(),i=[];for(let t,o=0,s=0;o<r.length;o++)t=r[o],lt.dist(t,e)<n&&(i.push(t),s+=o/r.length);return!!i.length&&(t/=i.length)}project(t){const e=this.getLUT(),n=e.length-1,r=lt.closest(e,t),i=r.mpos,o=(i-1)/n,s=(i+1)/n,a=.1/n;let l,c,h=r.mdist,d=o,u=d;for(h+=1;d<s+a;d+=a)l=this.compute(d),c=lt.dist(t,l),c<h&&(h=c,u=d);return u=u<0?0:u>1?1:u,l=this.compute(u),l.t=u,l.d=h,l}get(t){return this.compute(t)}point(t){return this.points[t]}compute(t){return this.ratios?lt.computeWithRatios(t,this.points,this.ratios,this._3d):lt.compute(t,this.points,this._3d,this.ratios)}raise(){const t=this.points,e=[t[0]],n=t.length;for(let r,i,o=1;o<n;o++)r=t[o],i=t[o-1],e[o]={x:(n-o)/n*r.x+o/n*i.x,y:(n-o)/n*r.y+o/n*i.y};return e[n]=t[n-1],new yt(e)}derivative(t){return lt.compute(t,this.dpoints[0],this._3d)}dderivative(t){return lt.compute(t,this.dpoints[1],this._3d)}align(){let t=this.points;return new yt(lt.align(t,{p1:t[0],p2:t[t.length-1]}))}curvature(t){return lt.curvature(t,this.dpoints[0],this.dpoints[1],this._3d)}inflections(){return lt.inflections(this.points)}normal(t){return this._3d?this.__normal3(t):this.__normal2(t)}__normal2(t){const e=this.derivative(t),n=ft(e.x*e.x+e.y*e.y);return{t,x:-e.y/n,y:e.x/n}}__normal3(t){const e=this.derivative(t),n=this.derivative(t+.01),r=ft(e.x*e.x+e.y*e.y+e.z*e.z),i=ft(n.x*n.x+n.y*n.y+n.z*n.z);e.x/=r,e.y/=r,e.z/=r,n.x/=i,n.y/=i,n.z/=i;const o={x:n.y*e.z-n.z*e.y,y:n.z*e.x-n.x*e.z,z:n.x*e.y-n.y*e.x},s=ft(o.x*o.x+o.y*o.y+o.z*o.z);o.x/=s,o.y/=s,o.z/=s;const a=[o.x*o.x,o.x*o.y-o.z,o.x*o.z+o.y,o.x*o.y+o.z,o.y*o.y,o.y*o.z-o.x,o.x*o.z-o.y,o.y*o.z+o.x,o.z*o.z];return{t,x:a[0]*e.x+a[1]*e.y+a[2]*e.z,y:a[3]*e.x+a[4]*e.y+a[5]*e.z,z:a[6]*e.x+a[7]*e.y+a[8]*e.z}}hull(t){let e=this.points,n=[],r=[],i=0;for(r[i++]=e[0],r[i++]=e[1],r[i++]=e[2],3===this.order&&(r[i++]=e[3]);e.length>1;){n=[];for(let o,s=0,a=e.length-1;s<a;s++)o=lt.lerp(t,e[s],e[s+1]),r[i++]=o,n.push(o);e=n}return r}split(t,e){if(0===t&&e)return this.split(e).left;if(1===e)return this.split(t).right;const n=this.hull(t),r={left:2===this.order?new yt([n[0],n[3],n[5]]):new yt([n[0],n[4],n[7],n[9]]),right:2===this.order?new yt([n[5],n[4],n[2]]):new yt([n[9],n[8],n[6],n[3]]),span:n};return r.left._t1=lt.map(0,0,1,this._t1,this._t2),r.left._t2=lt.map(t,0,1,this._t1,this._t2),r.right._t1=lt.map(t,0,1,this._t1,this._t2),r.right._t2=lt.map(1,0,1,this._t1,this._t2),e?(e=lt.map(e,t,1,0,1),r.right.split(e).left):r}extrema(){const t={};let e=[];return this.dims.forEach(function(n){let r=function(t){return t[n]},i=this.dpoints[0].map(r);t[n]=lt.droots(i),3===this.order&&(i=this.dpoints[1].map(r),t[n]=t[n].concat(lt.droots(i))),t[n]=t[n].filter((function(t){return t>=0&&t<=1})),e=e.concat(t[n].sort(lt.numberSort))}.bind(this)),t.values=e.sort(lt.numberSort).filter((function(t,n){return e.indexOf(t)===n})),t}bbox(){const t=this.extrema(),e={};return this.dims.forEach(function(n){e[n]=lt.getminmax(this,n,t[n])}.bind(this)),e}overlaps(t){const e=this.bbox(),n=t.bbox();return lt.bboxoverlap(e,n)}offset(t,e){if(void 0!==e){const n=this.get(t),r=this.normal(t),i={c:n,n:r,x:n.x+r.x*e,y:n.y+r.y*e};return this._3d&&(i.z=n.z+r.z*e),i}if(this._linear){const e=this.normal(0),n=this.points.map((function(n){const r={x:n.x+t*e.x,y:n.y+t*e.y};return n.z&&e.z&&(r.z=n.z+t*e.z),r}));return[new yt(n)]}return this.reduce().map((function(e){return e._linear?e.offset(t)[0]:e.scale(t)}))}simple(){if(3===this.order){const t=lt.angle(this.points[0],this.points[3],this.points[1]),e=lt.angle(this.points[0],this.points[3],this.points[2]);if(t>0&&e<0||t<0&&e>0)return!1}const t=this.normal(0),e=this.normal(1);let n=t.x*e.x+t.y*e.y;return this._3d&&(n+=t.z*e.z),ht(gt(n))<vt/3}reduce(){let t,e,n=0,r=0,i=.01,o=[],s=[],a=this.extrema().values;for(-1===a.indexOf(0)&&(a=[0].concat(a)),-1===a.indexOf(1)&&a.push(1),n=a[0],t=1;t<a.length;t++)r=a[t],e=this.split(n,r),e._t1=n,e._t2=r,o.push(e),n=r;return o.forEach((function(t){for(n=0,r=0;r<=1;)for(r=n+i;r<=1.01;r+=i)if(e=t.split(n,r),!e.simple()){if(r-=i,ht(n-r)<i)return[];e=t.split(n,r),e._t1=lt.map(n,0,1,t._t1,t._t2),e._t2=lt.map(r,0,1,t._t1,t._t2),s.push(e),n=r;break}n<1&&(e=t.split(n,1),e._t1=lt.map(n,0,1,t._t1,t._t2),e._t2=t._t2,s.push(e))})),s}translate(t,e,n){n="number"==typeof n?n:e;const r=this.order;let i=this.points.map(((t,i)=>(1-i/r)*e+i/r*n));return new yt(this.points.map(((e,n)=>({x:e.x+t.x*i[n],y:e.y+t.y*i[n]}))))}scale(t){const e=this.order;let n=!1;if("function"==typeof t&&(n=t),n&&2===e)return this.raise().scale(n);const r=this.clockwise,i=this.points;if(this._linear)return this.translate(this.normal(0),n?n(0):t,n?n(1):t);const o=n?n(0):t,s=n?n(1):t,a=[this.offset(0,10),this.offset(1,10)],l=[],c=lt.lli4(a[0],a[0].c,a[1],a[1].c);if(!c)throw new Error("cannot scale this curve. Try reducing it first.");return[0,1].forEach((function(t){const n=l[t*e]=lt.copy(i[t*e]);n.x+=(t?s:o)*a[t].n.x,n.y+=(t?s:o)*a[t].n.y})),n?([0,1].forEach((function(o){if(2!==e||!o){var s=i[o+1],a={x:s.x-c.x,y:s.y-c.y},h=n?n((o+1)/e):t;n&&!r&&(h=-h);var d=ft(a.x*a.x+a.y*a.y);a.x/=d,a.y/=d,l[o+1]={x:s.x+h*a.x,y:s.y+h*a.y}}})),new yt(l)):([0,1].forEach((t=>{if(2===e&&t)return;const n=l[t*e],r=this.derivative(t),o={x:n.x+r.x,y:n.y+r.y};l[t+1]=lt.lli4(n,o,c,i[t+1])})),new yt(l))}outline(t,e,n,r){if(e=void 0===e?t:e,this._linear){const i=this.normal(0),o=this.points[0],s=this.points[this.points.length-1];let a,l,c;void 0===n&&(n=t,r=e),a={x:o.x+i.x*t,y:o.y+i.y*t},c={x:s.x+i.x*n,y:s.y+i.y*n},l={x:(a.x+c.x)/2,y:(a.y+c.y)/2};const h=[a,l,c];a={x:o.x-i.x*e,y:o.y-i.y*e},c={x:s.x-i.x*r,y:s.y-i.y*r},l={x:(a.x+c.x)/2,y:(a.y+c.y)/2};const d=[c,l,a],u=lt.makeline(d[2],h[0]),p=lt.makeline(h[2],d[0]),m=[u,new yt(h),p,new yt(d)];return new ct(m)}const i=this.reduce(),o=i.length,s=[];let a,l=[],c=0,h=this.length();const d=void 0!==n&&void 0!==r;function u(t,e,n,r,i){return function(o){const s=r/n,a=(r+i)/n,l=e-t;return lt.map(o,0,1,t+s*l,t+a*l)}}i.forEach((function(i){const o=i.length();d?(s.push(i.scale(u(t,n,h,c,o))),l.push(i.scale(u(-e,-r,h,c,o)))):(s.push(i.scale(t)),l.push(i.scale(-e))),c+=o})),l=l.map((function(t){return a=t.points,a[3]?t.points=[a[3],a[2],a[1],a[0]]:t.points=[a[2],a[1],a[0]],t})).reverse();const p=s[0].points[0],m=s[o-1].points[s[o-1].points.length-1],g=l[o-1].points[l[o-1].points.length-1],f=l[0].points[0],v=lt.makeline(g,p),y=lt.makeline(m,f),x=[v].concat(s).concat([y]).concat(l);return new ct(x)}outlineshapes(t,e,n){e=e||t;const r=this.outline(t,e).curves,i=[];for(let t=1,e=r.length;t<e/2;t++){const o=lt.makeshape(r[t],r[e-t],n);o.startcap.virtual=t>1,o.endcap.virtual=t<e/2-1,i.push(o)}return i}intersects(t,e){return t?t.p1&&t.p2?this.lineIntersects(t):(t instanceof yt&&(t=t.reduce()),this.curveintersects(this.reduce(),t,e)):this.selfintersects(e)}lineIntersects(t){const e=dt(t.p1.x,t.p2.x),n=dt(t.p1.y,t.p2.y),r=ut(t.p1.x,t.p2.x),i=ut(t.p1.y,t.p2.y);return lt.roots(this.points,t).filter((t=>{var o=this.get(t);return lt.between(o.x,e,r)&&lt.between(o.y,n,i)}))}selfintersects(t){const e=this.reduce(),n=e.length-2,r=[];for(let i,o,s,a=0;a<n;a++)o=e.slice(a,a+1),s=e.slice(a+2),i=this.curveintersects(o,s,t),r.push(...i);return r}curveintersects(t,e,n){const r=[];t.forEach((function(t){e.forEach((function(e){t.overlaps(e)&&r.push({left:t,right:e})}))}));let i=[];return r.forEach((function(t){const e=lt.pairiteration(t.left,t.right,n);e.length>0&&(i=i.concat(e))})),i}arcs(t){return t=t||.5,this._iterate(t,[])}_error(t,e,n,r){const i=(r-n)/4,o=this.get(n+i),s=this.get(r-i),a=lt.dist(t,e),l=lt.dist(t,o),c=lt.dist(t,s);return ht(l-a)+ht(c-a)}_iterate(t,e){let n,r=0,i=1;do{n=0,i=1;let o,s,a,l,c,h=this.get(r),d=!1,u=!1,p=i,m=1,g=0;do{if(u=d,l=a,p=(r+i)/2,g++,o=this.get(p),s=this.get(i),a=lt.getccenter(h,o,s),a.interval={start:r,end:i},d=this._error(a,h,r,i)<=t,c=u&&!d,c||(m=i),d){if(i>=1){if(a.interval.end=m=1,l=a,i>1){let t={x:a.x+a.r*pt(a.e),y:a.y+a.r*mt(a.e)};a.e+=lt.angle({x:a.x,y:a.y},t,this.get(1))}break}i+=(i-r)/2}else i=p}while(!c&&n++<100);if(n>=100)break;l=l||a,e.push(l),r=m}while(i<1);return e}}const xt=t=>{if(t.indexOf("e")>0&&t.match(/[eE][-]\d{2,}$/))return"0";const e=t.charAt(t.length-1);"0"!==e&&"."!==e||(t=(t=(t=t.replace(/([.]\d*[^0]+)0+$/,"$1")).replace(/[.]0+$/,".")).replace(/[.]$/,""));const n=t.charAt(0);return"0"!==n&&"-"!==n||(t=(t=(t=t.replace(/^(0+)[.]/,".")).replace(/^-(0+)[.]/,"-.")).replace(/^(-?)0+$/,"$10")),"-0"===t?"0":t},bt=t=>{let e=t.toString(10);if(-1===e.indexOf("."))return e;const n=/^([-]?)(\d*)\.(\d{3,}9{4,})\d{1,4}$/.exec(e);if(n){const t=n[1],r=n[3],i=parseInt(r.charAt(r.length-1),10),o=parseInt(r,10),s=parseInt(n[2],10),a=n[3];let l=(o+10-i).toString(),c=0;for(l.length>o.toString().length&&(l=l.substring(1),c=1);l.length<a.length;)l=c.toString(10)+l,c=0;e=`${t+(s+c).toString()}.${l}`}return e=e.replace(/^([-]?\d*\.\d{3,})0{4,}\d{1,4}$/,"$1"),xt(e)},wt=/^([-]?)(\d*)[.](\d+)$/,Tt=t=>{const e=wt.exec(t);if(!e)return-1!==t.search(/[eE]/)||/^[a-zA-Z]+$/.exec(t)?-1:0;return e[3].length},Ct=(t,...e)=>{const n=t.toString(10),r=wt.exec(n);if(!r)return n;let i=-1;for(const t of e)i=Math.max(Tt(t),i);if(-1===i)return bt(t);let o=r[3].substring(0,i),s=r[2];const a=r[3].charAt(i);if(""!==a){if(parseInt(a,10)>=5){if(o.length>0){const t=/^(0+)(\d*)$/.exec(o);let e="",n=o;t&&(e=t[1],n=t[2]),o=(parseInt(o)+1).toString(),o.length>n.length&&e.length>0&&(e=e.substring(1)),o=e+o}(0===o.length||o.length>i)&&(s=(parseInt(s)+1).toString(),o=o.substring(1))}}const l=r[1];return xt(`${l}${s}.${o}`)};var St;!function(t){t[t.LineTo=0]="LineTo",t[t.MoveTo=1]="MoveTo",t[t.CubicBezierTo=2]="CubicBezierTo",t[t.QuadraticBezierTo=3]="QuadraticBezierTo"}(St||(St={}));class kt{constructor(t,e){this.startPoint=t,this.parts=e,this.cachedGeometry=null,this.cachedPolylineApproximation=null,this.cachedStringVersion=null,this.bbox=B.bboxOf([t]);for(const n of e)this.bbox=this.bbox.union(kt.computeBBoxForSegment(t,n))}get geometry(){if(this.cachedGeometry)return this.cachedGeometry;let t=this.startPoint;const e=[];for(const n of this.parts)switch(n.kind){case St.CubicBezierTo:e.push(new yt(t.xy,n.controlPoint1.xy,n.controlPoint2.xy,n.endPoint.xy)),t=n.endPoint;break;case St.QuadraticBezierTo:e.push(new yt(t.xy,n.controlPoint.xy,n.endPoint.xy)),t=n.endPoint;break;case St.LineTo:e.push(new R(t,n.point)),t=n.point;break;case St.MoveTo:t=n.point}return this.cachedGeometry=e,this.cachedGeometry}polylineApproximation(){if(this.cachedPolylineApproximation)return this.cachedPolylineApproximation;const t=[];for(const e of this.parts)switch(e.kind){case St.CubicBezierTo:t.push(e.controlPoint1,e.controlPoint2,e.endPoint);break;case St.QuadraticBezierTo:t.push(e.controlPoint,e.endPoint);break;case St.MoveTo:case St.LineTo:t.push(e.point)}const e=[];let n=this.startPoint;for(const r of t)e.push(new R(n,r)),n=r;return e}static computeBBoxForSegment(t,e){const n=[t];let r;switch(e.kind){case St.MoveTo:case St.LineTo:n.push(e.point);break;case St.CubicBezierTo:n.push(e.controlPoint1,e.controlPoint2,e.endPoint);break;case St.QuadraticBezierTo:n.push(e.controlPoint,e.endPoint);break;default:return r=e,r}return B.bboxOf(n)}intersection(t){if(!t.bbox.intersects(this.bbox))return[];const e=[];for(const n of this.geometry)if(n instanceof R){const r=n.intersection(t);r&&e.push({curve:n,parameterValue:r.t,point:r.point})}else{const r=n.intersects(t).map((e=>{"string"==typeof e&&(e=parseFloat(e));const r=S.ofXY(n.get(e));return r.minus(t.p1).magnitude()>t.length||r.minus(t.p2).magnitude()>t.length?null:{point:r,parameterValue:e,curve:n}})).filter((t=>null!==t));e.push(...r)}return e}mapPoints(t){const e=t(this.startPoint),n=[];let r;for(const e of this.parts)switch(e.kind){case St.MoveTo:case St.LineTo:n.push({kind:e.kind,point:t(e.point)});break;case St.CubicBezierTo:n.push({kind:e.kind,controlPoint1:t(e.controlPoint1),controlPoint2:t(e.controlPoint2),endPoint:t(e.endPoint)});break;case St.QuadraticBezierTo:n.push({kind:e.kind,controlPoint:t(e.controlPoint),endPoint:t(e.endPoint)});break;default:return r=e,r}return new kt(e,n)}transformedBy(t){return this.mapPoints((e=>t.transformVec2(e)))}union(t){return t?new kt(this.startPoint,[...this.parts,{kind:St.MoveTo,point:t.startPoint},...t.parts]):this}closedRoughlyIntersects(t){if(t.containsRect(this.bbox))return!0;const e=this.bbox.topLeft.minus(S.of(1,1)),n=t.corners,r=this.polylineApproximation();for(const t of n){const n=new R(t,e);let i=0;for(const t of r)t.intersects(n)&&i++;if(i%2==1)return!0}const i=t.grownBy(Math.min(t.size.x,t.size.y)),o=[];for(const t of i.divideIntoGrid(4,4))o.push(...t.getEdges());for(const t of o)for(const e of r)if(t.intersects(e))return!0;return!1}static fromRect(t,e=null){const n=[];let r,i;if(null!==e){const n=S.of(e,e).times(.5),o=B.fromCorners(t.topLeft.plus(n),t.bottomRight.minus(n)),s=B.fromCorners(t.topLeft.minus(n),t.bottomRight.plus(n));r=[o.corners[3],...o.corners,...s.corners.reverse()],i=s.corners[3]}else r=t.corners.slice(1),i=t.corners[0];for(const t of r)n.push({kind:St.LineTo,point:t});return new kt(i,n)}static fromRenderable(t){return t.path?t.path:new kt(t.startPoint,t.commands)}toRenderable(t){return{startPoint:this.startPoint,style:t,commands:this.parts,path:this}}toString(t){if(this.cachedStringVersion)return this.cachedStringVersion;void 0===t&&(t=Math.abs(this.bbox.topLeft.x)>10&&Math.abs(this.bbox.topLeft.y)>10);const e=kt.toString(this.startPoint,this.parts,!t);return this.cachedStringVersion=e,e}serialize(){return this.toString()}static toString(t,e,n){const r=[];let i;const o=(t,...e)=>{const o=[],s=[],a=!i||n,l=i?bt(i.x):"",c=i?bt(i.y):"";for(const t of e){const e=bt(t.x),n=bt(t.y);if(a)o.push(`${e},${n}`);else{const r=Ct(t.x-i.x,e,l,c),o=Ct(t.y-i.y,n,l,c);"-"===o.charAt(0)?s.push(`${r}${o}`):s.push(`${r},${o}`)}}let h;h=a?`${t}${o.join(" ")}`:`${t.toLowerCase()}${s.join(" ")}`,"l0,0"!==h&&(r.push(h),e.length>0&&(i=e[e.length-1]))};let s;o("M",t);for(const t of e)switch(t.kind){case St.MoveTo:o("M",t.point);break;case St.LineTo:o("L",t.point);break;case St.CubicBezierTo:o("C",t.controlPoint1,t.controlPoint2,t.endPoint);break;case St.QuadraticBezierTo:o("Q",t.controlPoint,t.endPoint);break;default:return s=t,s}return r.join("")}static fromString(t){var e;t=t.split("\n").join(" ");let n=S.zero,r=null,i=null,o=!0;const s=[],a=t=>{o?o=!1:s.push({kind:St.LineTo,point:t})},l={m:1,l:1,c:3,q:2,z:0,h:1,v:1},c=/([MZLHVCSQTA])\s*([^MZLHVCSQTA]*)/gi;let h;for(;null!==(h=c.exec(t));){const t=h[2].trim().split(/[^0-9Ee.-]/).filter((t=>t.length>0)).reduce(((t,e)=>{const n=(e=e.replace(/([^eE])[-]/g,"$1 -")).split(" -");return""!==n[0]&&t.push(n[0]),t.push(...n.slice(1).map((t=>`-${t}`))),t}),[]);let c=t.map((t=>parseFloat(t))),v=h[1].toLowerCase(),y=h[1]!==v;if("v"===v||"h"===v)c=c.reduce(((t,e)=>"v"===v?t.concat(y?n.x:0,e):t.concat(e,y?n.y:0)),[]),v="l";else if("z"===v){if(!r)continue;c=[r.x,r.y],r=n,y=!0,v="l"}const x=null!==(e=l[v])&&void 0!==e?e:0,b=c.reduce(((t,e,n,r)=>{if(n%2!=0){const i=e,o=r[n-1];return t.concat(S.of(o,i))}return t}),[]).map(((t,e)=>{let r;return r=y?t:n.plus(t),(e+1)%x==0&&(n=r),r}));if(b.length%x!=0)throw new Error([`Incorrect number of arguments: got ${JSON.stringify(b)} with a length of ${b.length} ≠ ${x}k, k ∈ ℤ.`,`The number of arguments to ${v} must be a multiple of ${x}!`,`Command: ${h[0]}`].join("\n"));for(let t=0;t<b.length;t+=x){const e=b.slice(t,t+x);switch(v.toLowerCase()){case"m":0===t?(f=e[0],o?o=!1:s.push({kind:St.MoveTo,point:f})):a(e[0]);break;case"l":a(e[0]);break;case"c":p=e[0],m=e[1],g=e[2],s.push({kind:St.CubicBezierTo,controlPoint1:p,controlPoint2:m,endPoint:g});break;case"q":d=e[0],u=e[1],s.push({kind:St.QuadraticBezierTo,controlPoint:d,endPoint:u});break;default:throw new Error(`Unknown path command ${v}`)}o=!1}b.length>0&&(null!=r||(r=b[0]),null!=i||(i=r),n=b[b.length-1])}var d,u,p,m,g,f;const v=new kt(null!=i?i:S.zero,s);return v.cachedStringVersion=t,v}}kt.empty=new kt(S.zero,[]);class Et{constructor(t,e,n,r){this.r=t,this.g=e,this.b=n,this.a=r,this.hexString=null}static ofRGB(t,e,n){return Et.ofRGBA(t,e,n,1)}static ofRGBA(t,e,n,r){return t=Math.max(0,Math.min(t,1)),e=Math.max(0,Math.min(e,1)),n=Math.max(0,Math.min(n,1)),r=Math.max(0,Math.min(r,1)),new Et(t,e,n,r)}static fromHex(t){var e;if(!(t=(t=(null!==(e=t.match(/^[#]?(.*)$/))&&void 0!==e?e:[])[1]).toUpperCase()).match(/^[0-9A-F]+$/))throw new Error(`${t} is not in a valid format.`);if(3===t.length||4===t.length){const e=t.split("");t=e.map((t=>`${t}0`)).join("")}6===t.length&&(t+="FF");const n=[];for(let e=2;e<=t.length;e+=2){const r=t.substring(e-2,e);n.push(parseInt(r,16)/255)}if(4!==n.length)throw new Error(`Unable to parse ${t}: Wrong number of components.`);return Et.ofRGBA(n[0],n[1],n[2],n[3])}static fromString(t){if(t.startsWith("#"))return Et.fromHex(t);{const e=document.createElement("canvas");e.width=1,e.height=1;const n=e.getContext("2d");n.fillStyle=t,n.fillRect(0,0,1,1);const r=n.getImageData(0,0,1,1),i=r.data[0]/255,o=r.data[1]/255,s=r.data[2]/255,a=r.data[3]/255;return Et.ofRGBA(i,o,s,a)}}eq(t){return null!=t&&this.toHexString()===t.toHexString()}toHexString(){if(this.hexString)return this.hexString;const t=t=>{const e=Math.round(255*t).toString(16);return 1===e.length?`0${e}`:e},e=t(this.a),n=t(this.r),r=t(this.g),i=t(this.b);return"ff"===e?`#${n}${r}${i}`:(this.hexString=`#${n}${r}${i}${e}`,this.hexString)}}Et.transparent=Et.ofRGBA(0,0,0,0),Et.red=Et.ofRGB(1,0,0),Et.green=Et.ofRGB(0,1,0),Et.blue=Et.ofRGB(0,0,1),Et.purple=Et.ofRGB(.5,.2,.5),Et.yellow=Et.ofRGB(1,1,.1),Et.clay=Et.ofRGB(.8,.4,.2),Et.black=Et.ofRGB(0,0,0),Et.white=Et.ofRGB(1,1,1);const Pt=(t,e)=>{var n,r,i,o,s,a;const l=t===e||t.fill.eq(e.fill)&&null==t.stroke==(null==e.stroke)&&(null===(o=null===(r=null===(n=t.stroke)||void 0===n?void 0:n.color)||void 0===r?void 0:r.eq(null===(i=e.stroke)||void 0===i?void 0:i.color))||void 0===o||o)&&(null===(s=t.stroke)||void 0===s?void 0:s.width)===(null===(a=e.stroke)||void 0===a?void 0:a.width);return null!=l&&l},zt=t=>{const e=t.stroke?{color:t.stroke.color.toHexString(),width:t.stroke.width}:void 0;return{fill:t.fill.toHexString(),stroke:e}},Rt=t=>{const e=t.stroke?{color:Et.fromHex(t.stroke.color),width:t.stroke.width}:void 0;return{fill:Et.fromHex(t.fill),stroke:e}};class Bt extends z{constructor(t){var e;super("stroke"),this.parts=[];for(const e of t){const t=kt.fromRenderable(e),n=this.bboxForPart(t.bbox,e.style);this.contentBBox?this.contentBBox=this.contentBBox.union(n):this.contentBBox=n,this.parts.push({path:t,startPoint:t.startPoint,style:e.style,commands:t.parts})}null!==(e=this.contentBBox)&&void 0!==e||(this.contentBBox=B.empty)}intersects(t){for(const e of this.parts)if(e.path.intersection(t).length>0)return!0;return!1}render(t,e){t.startObject(this.getBBox());for(const n of this.parts){const r=this.bboxForPart(n.path.bbox,n.style);if(e){if(!r.intersects(e))continue;if((r.size.x>2*e.size.x||r.size.y>2*e.size.y)&&!n.path.closedRoughlyIntersects(e))continue}t.drawPath(n)}t.endObject(this.getLoadSaveData())}bboxForPart(t,e){return e.stroke?t.grownBy(e.stroke.width/2):t}applyTransformation(t){this.contentBBox=B.empty;let e=!0;this.parts=this.parts.map((n=>{const r=n.path.transformedBy(t),i=this.bboxForPart(r.bbox,n.style);return e?(this.contentBBox=i,e=!1):this.contentBBox=this.contentBBox.union(i),{path:r,startPoint:r.startPoint,commands:r.parts,style:n.style}}))}getPath(){let t=null;for(const e of this.parts)t?t=t.union(e.path):null!=t||(t=e.path);return null!=t?t:kt.empty}description(t){return t.stroke}createClone(){return new Bt(this.parts)}serializeToJSON(){return this.parts.map((t=>({style:zt(t.style),path:t.path.serialize()})))}static deserializeFromJSON(t){if("string"==typeof t&&(t=JSON.parse(t)),"object"!=typeof t||"number"!=typeof t.length)throw new Error(`${t} is missing required field, parts, or parts is of the wrong type.`);const e=t.map((t=>{const e=Rt(t.style);return kt.fromString(t.path).toRenderable(e)}));return new Bt(e)}}z.registerComponent("stroke",Bt.deserializeFromJSON);const At=(t,e)=>{const n=7*e.getSizeOfPixelOnCanvas(),r=e.getSizeOfPixelOnCanvas();return new It(t,r,n)};class It{constructor(t,e,n){this.startPoint=t,this.minFitAllowed=e,this.maxFitAllowed=n,this.isFirstSegment=!0,this.pathStartConnector=null,this.mostRecentConnector=null,this.lastExitingVec=null,this.currentCurve=null,this.lastPoint=this.startPoint,this.upperSegments=[],this.lowerSegments=[],this.buffer=[this.startPoint.pos],this.momentum=S.zero,this.currentCurve=null,this.curveStartWidth=t.width,this.bbox=new B(this.startPoint.pos.x,this.startPoint.pos.y,0,0)}getBBox(){return this.bbox}getRenderingStyle(){var t;return{fill:null!==(t=this.lastPoint.color)&&void 0!==t?t:null}}previewPath(){var t;let e,n,r,i;if(this.currentCurve){const{upperCurve:o,lowerToUpperConnector:s,upperToLowerConnector:a,lowerCurve:l}=this.currentSegmentToPath();e=this.upperSegments.concat(o),n=this.lowerSegments.concat(l),r=s,i=null!==(t=this.pathStartConnector)&&void 0!==t?t:a}else{if(null===this.mostRecentConnector||null===this.pathStartConnector)return null;e=this.upperSegments.slice(),n=this.lowerSegments.slice(),r=this.mostRecentConnector,i=this.pathStartConnector}return{startPoint:n[n.length-1].endPoint,commands:[r,...e.reverse(),i,...n],style:this.getRenderingStyle()}}previewStroke(){const t=this.previewPath();return t?new Bt([t]):null}preview(t){const e=this.previewPath();e&&t.drawPath(e)}build(){return this.lastPoint&&(0===this.lowerSegments.length||this.approxCurrentCurveLength()>2*this.curveStartWidth)&&this.finalizeCurrentCurve(),this.previewStroke()}roundPoint(t){let e=Math.min(this.minFitAllowed,this.curveStartWidth/2);return e<1e-10&&(e=this.minFitAllowed),H.roundPoint(t,e)}approxCurrentCurveLength(){if(!this.currentCurve)return 0;const t=S.ofXY(this.currentCurve.points[0]),e=S.ofXY(this.currentCurve.points[1]),n=S.ofXY(this.currentCurve.points[2]);return t.minus(e).length()+n.minus(e).length()}finalizeCurrentCurve(){if(!this.currentCurve){if(!this.isFirstSegment)return;const t=H.roundPoint(this.startPoint.width/3.5,Math.min(this.minFitAllowed,this.startPoint.width/4)),e=this.roundPoint(this.startPoint.pos),n=this.startPoint.pos.plus(S.of(t,0));return this.lowerSegments.push({kind:St.QuadraticBezierTo,controlPoint:e.plus(S.of(t,t)),endPoint:e.plus(S.of(0,t))},{kind:St.QuadraticBezierTo,controlPoint:e.plus(S.of(-t,t)),endPoint:e.plus(S.of(-t,0))},{kind:St.QuadraticBezierTo,controlPoint:e.plus(S.of(-t,-t)),endPoint:e.plus(S.of(0,-t))},{kind:St.QuadraticBezierTo,controlPoint:e.plus(S.of(t,-t)),endPoint:e.plus(S.of(t,0))}),this.pathStartConnector={kind:St.LineTo,point:n},void(this.mostRecentConnector=this.pathStartConnector)}const{upperCurve:t,lowerToUpperConnector:e,upperToLowerConnector:n,lowerCurve:r}=this.currentSegmentToPath();this.isFirstSegment&&(this.pathStartConnector=n,this.isFirstSegment=!1),this.mostRecentConnector=e,this.upperSegments.push(t),this.lowerSegments.push(r);const i=this.buffer[this.buffer.length-1];this.lastExitingVec=S.ofXY(this.currentCurve.points[2]).minus(S.ofXY(this.currentCurve.points[1])),console.assert(0!==this.lastExitingVec.magnitude(),"lastExitingVec has zero length!"),this.buffer=[this.buffer[this.buffer.length-2],i],this.currentCurve=null}currentSegmentToPath(){if(null==this.currentCurve)throw new Error("Invalid State: currentCurve is null!");let t=S.ofXY(this.currentCurve.normal(0)).normalized(),e=S.ofXY(this.currentCurve.normal(1)).normalized();t=t.times(this.curveStartWidth/2),e=e.times(this.curveEndWidth/2),isFinite(t.magnitude())||(console.error("Warning: startVec is NaN or ∞",t,e,this.currentCurve),t=e);const n=S.ofXY(this.currentCurve.get(0)),r=S.ofXY(this.currentCurve.get(1)),i=S.ofXY(this.currentCurve.points[1]);let o=this.currentCurve.project(i.xy).t;o||(o=n.minus(i).magnitudeSquared()<r.minus(i).magnitudeSquared()?.1:.9);const s=o,a=S.ofXY(this.currentCurve.normal(s)).normalized().times(this.curveStartWidth/2*s+this.curveEndWidth/2*(1-s)),l=this.roundPoint(i.plus(a)),c=this.roundPoint(r.plus(e)),h=this.roundPoint(i.minus(a)),d=this.roundPoint(r.minus(e)),u={kind:St.QuadraticBezierTo,controlPoint:l,endPoint:c},p={kind:St.LineTo,point:this.roundPoint(n.plus(t))},m={kind:St.LineTo,point:d};return{upperCurve:{kind:St.QuadraticBezierTo,controlPoint:h,endPoint:this.roundPoint(n.minus(t))},upperToLowerConnector:p,lowerToUpperConnector:m,lowerCurve:u}}computeExitingVec(){return this.momentum.normalized().times(this.lastPoint.width/2)}addPoint(t){var e,n;if(this.lastPoint){const e=1e-10,n=t.time-this.lastPoint.time;if(t.pos.eq(this.lastPoint.pos,e)||0===n)return;if(isNaN(t.pos.magnitude()))return void console.warn("Discarding NaN point.",t);const r=Math.min(this.lastPoint.width,t.width)/3;if(this.startPoint.pos.minus(t.pos).magnitude()<r&&this.isFirstSegment)return;const i=t.pos.minus(this.lastPoint.pos).times(1/n*1e3);this.momentum=this.momentum.lerp(i,.9)}const r=null!==(e=this.lastPoint)&&void 0!==e?e:t;this.lastPoint=t,this.buffer.push(t.pos);const i=t.width/2,o=this.curveEndWidth;if(this.curveEndWidth=i,this.bbox=this.bbox.grownToPoint(t.pos,i),null===this.currentCurve){const e=r.pos,i=r.pos.plus(null!==(n=this.lastExitingVec)&&void 0!==n?n:S.unitX),o=t.pos;this.currentCurve=new yt(e.xy,i.xy,o.xy),this.curveStartWidth=r.width/2,console.assert(!isNaN(e.magnitude())&&!isNaN(i.magnitude())&&!isNaN(o.magnitude()),"Expected !NaN")}let s=this.lastExitingVec;if(!s){let t=Math.ceil(this.buffer.length/3);0===t&&(t=this.buffer.length-1),s=this.buffer[t].minus(this.buffer[0])}let a=this.computeExitingVec();const l=this.buffer[0],c=t.pos,h=c.minus(l).magnitude(),d=3*h;if(0===d||0===a.magnitude()||!isFinite(a.magnitude()))return;console.assert(isFinite(s.magnitude()),"Pre-normalized enteringVec has NaN or ∞ magnitude!"),s=s.normalized(),a=a.normalized(),console.assert(isFinite(s.magnitude()),"Normalized enteringVec has NaN or ∞ magnitude!");const u=new R(l,l.plus(s.times(d))),p=new R(c.minus(a.times(d)),c).intersection(u);let m=null;p&&(m=p.point),(!m||l.eq(m)||c.eq(m))&&(m=l.plus(s.times(h/4))),console.assert(!l.eq(m,1e-11),"Start and control points are equal!"),console.assert(!m.eq(c,1e-11),"Control and end points are equal!");const g=this.currentCurve;this.currentCurve=new yt(l.xy,m.xy,c.xy),isNaN(S.ofXY(this.currentCurve.normal(0)).magnitude())&&(console.error("NaN normal at 0. Curve:",this.currentCurve),this.currentCurve=g);const f=t=>{for(const e of this.buffer){const n=S.ofXY(t.project(e.xy)).minus(e).magnitude();if(n>Math.max(Math.min(this.curveStartWidth,this.curveEndWidth)/3,this.minFitAllowed)||n>this.maxFitAllowed)return!1}return!0};return this.buffer.length>3&&this.approxCurrentCurveLength()>this.curveStartWidth&&!f(this.currentCurve)?(this.currentCurve=g,this.curveEndWidth=o,this.lastPoint=r,void this.finalizeCurrentCurve()):void 0}}class Lt extends G{constructor(t,e,n){super(t.notifier,e),this.editor=t,this.style=n,this.builder=null,this.builderFactory=At,this.lastPoint=null}getPressureMultiplier(){return 1/this.editor.viewport.getScaleFactor()*this.style.thickness}toStrokePoint(t){var e;let n=Math.max(null!==(e=t.pressure)&&void 0!==e?e:1,.3);return isFinite(n)||(console.warn("Non-finite pressure!",t),n=.3),console.assert(isFinite(t.canvasPos.length()),"Non-finite canvas position!"),console.assert(isFinite(t.screenPos.length()),"Non-finite screen position!"),console.assert(isFinite(t.timeStamp),"Non-finite timeStamp on pointer!"),{pos:t.canvasPos,width:n*this.getPressureMultiplier(),color:this.style.color,time:t.timeStamp}}previewStroke(){var t;this.editor.clearWetInk(),null===(t=this.builder)||void 0===t||t.preview(this.editor.display.getWetInkRenderer())}addPointToStroke(t){if(!this.builder)throw new Error("No stroke is currently being generated.");this.builder.addPoint(t),this.lastPoint=t,this.previewStroke()}onPointerDown({current:t,allPointers:e}){const n=t.device===O.Eraser;let r=!1;for(const t of e)if(t.device===O.Pen){r=!0;break}return!((1!==e.length||n)&&!r)&&(this.builder=this.builderFactory(this.toStrokePoint(t),this.editor.viewport),!0)}onPointerMove({current:t}){this.addPointToStroke(this.toStrokePoint(t))}onPointerUp({current:t}){var e,n;if(!this.builder)return;const r=this.toStrokePoint(t),i=Object.assign(Object.assign({},r),{width:null!==(n=null===(e=this.lastPoint)||void 0===e?void 0:e.width)&&void 0!==n?n:r.width});if(this.addPointToStroke(i),this.builder&&t.isPrimary){const t=this.builder.build();if(this.previewStroke(),t.getBBox().area>0){const e=!0,n=I.addElement(t,e);this.editor.dispatch(n)}else console.warn("Pen: Not adding empty stroke",t,"to the canvas.")}this.builder=null,this.editor.clearWetInk()}onGestureCancel(){this.editor.clearWetInk()}noteUpdated(){this.editor.notifier.dispatch(M.ToolUpdated,{kind:M.ToolUpdated,tool:this})}setColor(t){t.toHexString()!==this.style.color.toHexString()&&(this.style=Object.assign(Object.assign({},this.style),{color:t}),this.noteUpdated())}setThickness(t){t!==this.style.thickness&&(this.style=Object.assign(Object.assign({},this.style),{thickness:t}),this.noteUpdated())}setStrokeFactory(t){t!==this.builderFactory&&(this.builderFactory=t,this.noteUpdated())}getThickness(){return this.style.thickness}getColor(){return this.style.color}getStrokeFactory(){return this.builderFactory}onKeyPress({key:t}){let e;return"-"===(t=t.toLowerCase())||"_"===t?e=2*this.getThickness()/3:"+"!==t&&"="!==t||(e=3*this.getThickness()/2),void 0!==e&&(e=Math.min(Math.max(1,e),256),this.setThickness(e),!0)}}class Dt{constructor(){}notifyEnabled(t){var e;t!==this.activeTool&&(null===(e=this.activeTool)||void 0===e||e.setEnabled(!1),this.activeTool=t)}}const Mt=(t,e)=>{if(0===e.length)return null;const n=e[0].description(t);for(const r of e)if(r.description(t)!==n)return null;return n};class Ot extends T{constructor(t){super("erase"),this.toRemove=t.map((t=>t)),this.applied=!1}apply(t){for(const e of this.toRemove){const n=t.image.findParent(e);n&&n.remove()}this.applied=!0,t.queueRerender()}unapply(t){for(const e of this.toRemove)t.image.findParent(e)||I.addElement(e).apply(t);this.applied=!1,t.queueRerender()}onDrop(t){if(this.applied)for(const e of this.toRemove)t.image.onDestroyElement(e)}description(t,e){var n;if(0===this.toRemove.length)return e.erasedNoElements;const r=null!==(n=Mt(e,this.toRemove))&&void 0!==n?n:e.elements;return e.eraseAction(r,this.toRemove.length)}serializeToJSON(){return this.toRemove.map((t=>t.getId()))}}T.register("erase",((t,e)=>{const n=t.map((t=>e.image.lookupElement(t))).filter((t=>null!==t));return new Ot(n)}));class $t extends G{constructor(t,e){super(t.notifier,e),this.editor=t,this.command=null}onPointerDown(t){return(1===t.allPointers.length||t.current.device===O.Eraser)&&(this.lastPoint=t.current.canvasPos,this.toRemove=[],!0)}onPointerMove(t){var e;const n=t.current.canvasPos;if(0===n.minus(this.lastPoint).magnitude())return;const r=new R(this.lastPoint,n),i=r.bbox;this.toRemove.push(...this.editor.image.getElementsIntersectingRegion(i).filter((t=>t.intersects(r)))),null===(e=this.command)||void 0===e||e.unapply(this.editor),this.command=new Ot(this.toRemove),this.command.apply(this.editor),this.lastPoint=n}onPointerUp(t){var e;this.command&&this.toRemove.length>0&&(null===(e=this.command)||void 0===e||e.unapply(this.editor),this.editor.dispatch(this.command)),this.command=null}onGestureCancel(){var t;null===(t=this.command)||void 0===t||t.unapply(this.editor),this.command=null}}var Nt=function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{l(r.next(t))}catch(t){o(t)}}function a(t){try{l(r.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}l((r=r.apply(t,e||[])).next())}))};class Ft extends z{constructor(t){var e,n,r;super("image-component"),this.image=Object.assign(Object.assign({},t),{label:null!==(r=null!==(n=null!==(e=t.label)&&void 0!==e?e:t.image.getAttribute("alt"))&&void 0!==n?n:t.image.getAttribute("aria-label"))&&void 0!==r?r:void 0});void 0===t.image.getAttribute("src")||t.image.complete||(t.image.onload=()=>this.recomputeBBox()),this.recomputeBBox()}getImageRect(){return new B(0,0,this.image.image.width,this.image.image.height)}recomputeBBox(){this.contentBBox=this.getImageRect(),this.contentBBox=this.contentBBox.transformedBoundingBox(this.image.transform)}static fromImage(t,e){var n;return Nt(this,void 0,void 0,(function*(){let r,i,o;t.complete||(yield new Promise(((e,n)=>{t.onload=e,t.onerror=n,t.onabort=n}))),"number"==typeof t.width&&"number"==typeof t.height&&0!==t.width&&0!==t.height?(r=t.width,i=t.height):(r=t.clientWidth,i=t.clientHeight);let s=null!==(n=t.src)&&void 0!==n?n:"";if(s.startsWith("data:image/"))o=new Image,o.src=s,o.width=r,o.height=i;else{const e=document.createElement("canvas");e.width=r,e.height=i;e.getContext("2d").drawImage(t,0,0,e.width,e.height),s=e.toDataURL(),o=e}return new Ft({image:o,base64Url:s,transform:e})}))}render(t,e){t.drawImage(this.image)}intersects(t){const e=this.getImageRect().getEdges().map((t=>t.transformedBy(this.image.transform)));for(const n of e)if(n.intersects(t))return!0;return!1}serializeToJSON(){return{src:this.image.base64Url,label:this.image.label,width:this.image.image.width,height:this.image.image.height,transform:this.image.transform.toArray()}}applyTransformation(t){this.image.transform=t.rightMul(this.image.transform),this.recomputeBBox()}description(t){return this.image.label?t.imageNode(this.image.label):t.unlabeledImageNode}createClone(){return new Ft(Object.assign({},this.image))}static deserializeFromJSON(t){if("string"!=typeof t.src)throw new Error(`${t} has invalid format! Expected src property.`);const e=new Image;return e.src=t.src,e.width=t.width,e.height=t.height,new Ft({image:e,base64Url:e.src,label:t.label,transform:new P(...t.transform)})}}z.registerComponent("image-component",Ft.deserializeFromJSON);const Ut="svg-global-attributes";class jt extends z{constructor(t){super(Ut),this.attrs=t,this.contentBBox=B.empty}render(t,e){if(t instanceof Qt)for(const[e,n]of this.attrs)t.setRootSVGAttribute(e,n)}intersects(t){return!1}applyTransformation(t){}createClone(){return new jt(this.attrs)}description(t){return t.svgObject}serializeToJSON(){return JSON.stringify(this.attrs)}static deserializeFromString(t){const e=JSON.parse(t),n=[],r=/^[ \t\n0-9.-eE]+$/;for(const[t,i]of e)"viewBox"!==t&&"width"!==t&&"height"!==t||i&&r.exec(i)&&n.push([t,i]);return new jt(n)}}z.registerComponent(Ut,jt.deserializeFromString);const Vt="text";class Wt extends z{constructor(t,e,n,r=Wt.getTextDimens){super(Vt),this.textObjects=t,this.transform=e,this.style=n,this.getTextDimens=r,this.recomputeBBox()}static applyTextStyles(t,e){var n,r;const i=e.fontFamily.match(/\s/)?e.fontFamily.replace(/["]/g,'\\"'):e.fontFamily;t.font=[(null!==(n=e.size)&&void 0!==n?n:12)+"px",null!==(r=e.fontWeight)&&void 0!==r?r:"",`${i}`,e.fontWeight].join(" "),t.textAlign="left"}static getTextDimens(t,e){var n;null!==(n=Wt.textMeasuringCtx)&&void 0!==n||(Wt.textMeasuringCtx=document.createElement("canvas").getContext("2d"));const r=Wt.textMeasuringCtx;Wt.applyTextStyles(r,e);const i=r.measureText(t),o=-i.actualBoundingBoxAscent,s=i.actualBoundingBoxAscent+i.actualBoundingBoxDescent;return new B(0,o,i.width,s)}computeBBoxOfPart(t){if("string"==typeof t){return this.getTextDimens(t,this.style).transformedBoundingBox(this.transform)}return t.contentBBox.transformedBoundingBox(this.transform)}recomputeBBox(){let t=null;for(const e of this.textObjects){const n=this.computeBBoxOfPart(e);null!=t||(t=n),t=t.union(n)}this.contentBBox=null!=t?t:B.empty}render(t,e){const n=this.transform;t.startObject(this.contentBBox);for(const e of this.textObjects)"string"==typeof e?t.drawText(e,n,this.style):(t.pushTransform(n),e.render(t),t.popTransform());t.endObject(this.getLoadSaveData())}intersects(t){const e=this.transform.inverse(),n=e.transformVec2(t.p1),r=e.transformVec2(t.p2);t=new R(n,r);for(const e of this.textObjects)if("string"==typeof e){if(Wt.getTextDimens(e,this.style).getEdges().some((e=>null!==t.intersection(e))))return!0}else if(e.intersects(t))return!0;return!1}applyTransformation(t){this.transform=t.rightMul(this.transform),this.recomputeBBox()}createClone(){return new Wt(this.textObjects,this.transform,this.style)}getText(){const t=[];for(const e of this.textObjects)"string"==typeof e?t.push(e):t.push(e.getText());return t.join("\n")}description(t){return t.text(this.getText())}serializeToJSON(){const t=Object.assign(Object.assign({},this.style),{renderingStyle:zt(this.style.renderingStyle)});return{textObjects:this.textObjects.map((t=>"string"==typeof t?{text:t}:{json:t.serializeToJSON()})),transform:this.transform.toArray(),style:t}}static deserializeFromString(t,e=Wt.getTextDimens){const n={renderingStyle:Rt(t.style.renderingStyle),size:t.style.size,fontWeight:t.style.fontWeight,fontVariant:t.style.fontVariant,fontFamily:t.style.fontFamily},r=t.textObjects.map((t=>{var e;return null!==(null!==(e=t.text)&&void 0!==e?e:null)?t.text:Wt.deserializeFromString(t.json)}));if(t.transform=t.transform.filter((t=>"number"==typeof t)),9!==t.transform.length)throw new Error(`Unable to deserialize transform, ${t.transform}.`);const i=t.transform,o=new P(...i);return new Wt(r,o,n,e)}}z.registerComponent(Vt,(t=>Wt.deserializeFromString(t)));const Ht="unknown-svg-object";class Gt extends z{constructor(t){super(Ht),this.svgObject=t,this.contentBBox=B.of(t.getBoundingClientRect())}render(t,e){t instanceof Qt&&t.drawSVGElem(this.svgObject)}intersects(t){return this.contentBBox.getEdges().some((e=>null!==e.intersection(t)))}applyTransformation(t){}createClone(){return new Gt(this.svgObject.cloneNode(!0))}description(t){return t.svgObject}serializeToJSON(){return JSON.stringify({html:this.svgObject.outerHTML})}}z.registerComponent(Ht,null);var _t=function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{l(r.next(t))}catch(t){o(t)}}function a(t){try{l(r.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}l((r=r.apply(t,e||[])).next())}))};const qt=new B(0,0,500,500),Zt="svgAttrs",Kt="svgStyleAttrs";class Xt{constructor(t,e,n=!0){this.source=t,this.onFinish=e,this.storeUnknown=n,this.onAddComponent=null,this.onProgress=null,this.onDetermineExportRect=null,this.processedCount=0,this.totalToProcess=0}getStyle(t){var e,n,r;const i={fill:Et.transparent},o=null!==(e=t.getAttribute("fill"))&&void 0!==e?e:t.style.fill;if(o)try{i.fill=Et.fromString(o)}catch(t){console.error("Unknown fill color,",o)}const s=null!==(n=t.getAttribute("stroke"))&&void 0!==n?n:t.style.stroke,a=null!==(r=t.getAttribute("stroke-width"))&&void 0!==r?r:t.style.strokeWidth;if(s)try{let t=parseFloat(null!=a?a:"1");isFinite(t)||(t=0),i.stroke={width:t,color:Et.fromString(s)}}catch(t){console.error("Error parsing stroke data:",t)}return i}strokeDataFromElem(t){var e;const n=[],r=null!==(e=t.getAttribute("d"))&&void 0!==e?e:"",i=this.getStyle(t),o=r.split("M");let s=!0;for(const t of o){const e=/^[0-9., \t\n]+$/.exec(t);if(""!==t&&!e){const e=s?t:`M${t}`,r=kt.fromString(e).toRenderable(i);n.push(r)}s=!1}return n}attachUnrecognisedAttrs(t,e,n,r){if(this.storeUnknown){for(const i of e.getAttributeNames())n.has(i)||"style"===i&&r||t.attachLoadSaveData(Zt,[i,e.getAttribute(i)]);if(r)for(const n of e.style)""!==n&&n&&(r.has(n)||t.attachLoadSaveData(Kt,{key:n,value:e.style.getPropertyValue(n),priority:e.style.getPropertyPriority(n)}))}}addPath(t){var e;let n;try{const e=this.strokeDataFromElem(t);n=new Bt(e);const r=["stroke","fill","stroke-width"];this.attachUnrecognisedAttrs(n,t,new Set([...r,"d"]),new Set(r))}catch(e){if(console.error("Invalid path in node",t,"\nError:",e,"\nAdding as an unknown object."),!this.storeUnknown)return;n=new Gt(t)}null===(e=this.onAddComponent)||void 0===e||e.call(this,n)}getTransform(t,e,n){null!=n||(n=window.getComputedStyle(t));let r,i=n.transform;""!==i&&"none"!==i||(i=t.style.transform||"none");try{r=P.fromCSSMatrix(t.style.transform)}catch(t){r=P.fromCSSMatrix(i)}const o=t.getAttribute("x"),s=t.getAttribute("y");if(o&&s){const t=parseFloat(o),n=parseFloat(s);isNaN(t)||isNaN(n)||(null==e||e.push("x","y"),r=r.rightMul(P.translation(S.of(t,n))))}return r}makeText(t){var e;const n=[];for(const r of t.childNodes)if(r.nodeType===Node.TEXT_NODE)n.push(null!==(e=r.nodeValue)&&void 0!==e?e:"");else{if(r.nodeType!==Node.ELEMENT_NODE)throw new Error(`Unrecognized text child node: ${r}.`);{const t=r;if("tspan"!==t.tagName.toLowerCase())throw new Error(`Unrecognized text child element: ${t}`);n.push(this.makeText(t))}}const r=window.getComputedStyle(t),i=/^([-0-9.e]+)px/i.exec(r.fontSize),o=["fontFamily","fill","transform"];let s=12;i&&(o.push("fontSize"),s=parseFloat(i[1]));const a={size:s,fontFamily:r.fontFamily||t.style.fontFamily||"sans-serif",renderingStyle:{fill:Et.fromString(r.fill)}},l=[],c=this.getTransform(t,l,r),h=new Wt(n,c,a);return this.attachUnrecognisedAttrs(h,t,new Set(l),new Set(o)),h}addText(t){var e;try{const n=this.makeText(t);null===(e=this.onAddComponent)||void 0===e||e.call(this,n)}catch(e){console.error("Invalid text object in node",t,". Continuing.... Error:",e),this.addUnknownNode(t)}}addImage(t){var e,n;return _t(this,void 0,void 0,(function*(){const r=new Image;r.src=null!==(e=t.getAttribute("xlink:href"))&&void 0!==e?e:t.href.baseVal;try{const e=[],i=this.getTransform(t,e),o=yield Ft.fromImage(r,i);this.attachUnrecognisedAttrs(o,t,new Set(e),new Set(["transform"])),null===(n=this.onAddComponent)||void 0===n||n.call(this,o)}catch(e){console.error("Error loading image:",e,". Element: ",t,". Continuing..."),this.addUnknownNode(t)}}))}addUnknownNode(t){var e;if(this.storeUnknown){const n=new Gt(t);null===(e=this.onAddComponent)||void 0===e||e.call(this,n)}}updateViewBox(t){var e;const n=t.getAttribute("viewBox");if(this.rootViewBox||!n)return;const r=n.split(/[ \t\n,]+/),i=parseFloat(r[0]),o=parseFloat(r[1]),s=parseFloat(r[2]),a=parseFloat(r[3]);isNaN(i)||isNaN(o)||isNaN(s)||isNaN(a)?console.warn(`node ${t} has an unparsable viewbox. Viewbox: ${n}. Match: ${r}.`):(this.rootViewBox=new B(i,o,s,a),null===(e=this.onDetermineExportRect)||void 0===e||e.call(this,this.rootViewBox))}updateSVGAttrs(t){var e;this.storeUnknown&&(null===(e=this.onAddComponent)||void 0===e||e.call(this,new jt(this.getSourceAttrs(t))))}visit(t){var e;return _t(this,void 0,void 0,(function*(){this.totalToProcess+=t.childElementCount;let n=!0;switch(t.tagName.toLowerCase()){case"g":break;case"path":this.addPath(t);break;case"text":this.addText(t),n=!1;break;case"image":yield this.addImage(t),n=!1;break;case"svg":this.updateViewBox(t),this.updateSVGAttrs(t);break;default:return console.warn("Unknown SVG element,",t),t instanceof SVGElement||console.warn("Element",t,"is not an SVGElement!",this.storeUnknown?"Continuing anyway.":"Skipping."),void this.addUnknownNode(t)}if(n)for(const e of t.children)yield this.visit(e);this.processedCount++,yield null===(e=this.onProgress)||void 0===e?void 0:e.call(this,this.processedCount,this.totalToProcess)}))}getSourceAttrs(t){return t.getAttributeNames().map((e=>[e,t.getAttribute(e)]))}start(t,e,n=null){var r,i;return _t(this,void 0,void 0,(function*(){this.onAddComponent=t,this.onProgress=e,this.onDetermineExportRect=n,this.totalToProcess=this.source.childElementCount,this.processedCount=0,this.rootViewBox=null,yield this.visit(this.source);this.rootViewBox||null===(r=this.onDetermineExportRect)||void 0===r||r.call(this,qt),null===(i=this.onFinish)||void 0===i||i.call(this)}))}static fromString(t,e=!1){var n,r;const i=document.createElement("iframe");if(i.src="about:blank",i.setAttribute("sandbox","allow-same-origin"),i.setAttribute("csp","default-src 'about:blank'"),i.style.display="none",document.body.appendChild(i),!i.hasAttribute("sandbox"))throw i.remove(),new Error("SVG loading iframe is not sandboxed.");const o=null!==(r=null===(n=i.contentWindow)||void 0===n?void 0:n.document)&&void 0!==r?r:i.contentDocument;if(null==o)throw new Error("Unable to open a sandboxed iframe!");o.open(),o.write("\n\t\t\t<!DOCTYPE html>\n\t\t\t<html>\n\t\t\t\t<head>\n\t\t\t\t\t<title>SVG Loading Sandbox</title>\n\t\t\t\t</head>\n\t\t\t\t<body>\n\t\t\t\t\t<script>\n\t\t\t\t\t\tconsole.error('JavaScript should not be able to run here!');\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'The SVG sandbox is broken! Please double-check the sandboxing setting.'\n\t\t\t\t\t\t);\n\t\t\t\t\t<\/script>\n\t\t\t\t</body>\n\t\t\t</html>\n\t\t"),o.close();const s=o.createElementNS("http://www.w3.org/2000/svg","svg");return s.innerHTML=t,o.body.appendChild(s),new Xt(s,(()=>{s.remove(),i.remove()}),!e)}}class Jt{constructor(t){this.viewport=t,this.selfTransform=null,this.transformStack=[],this.objectLevel=0,this.currentPaths=null}getViewport(){return this.viewport}setDraftMode(t){}flushPath(){if(!this.currentPaths)return;let t=null;for(const e of this.currentPaths){const{startPoint:n,commands:r,style:i}=e;t&&Pt(t,i)?this.moveTo(n):(t&&this.endPath(t),this.beginPath(n),t=i);for(const t of r)t.kind===St.LineTo?this.lineTo(t.point):t.kind===St.MoveTo?this.moveTo(t.point):t.kind===St.CubicBezierTo?this.traceCubicBezierCurve(t.controlPoint1,t.controlPoint2,t.endPoint):t.kind===St.QuadraticBezierTo&&this.traceQuadraticBezierCurve(t.controlPoint,t.endPoint)}t&&this.endPath(t)}drawPath(t){0===this.objectLevel?(this.currentPaths=[t],this.flushPath(),this.currentPaths=null):this.currentPaths.push(t)}drawRect(t,e,n){const r=kt.fromRect(t,e);this.drawPath(r.toRenderable(n))}startObject(t,e){this.currentPaths=[],this.objectLevel++}endObject(t){if(this.flushPath(),this.currentPaths=null,this.objectLevel--,this.objectLevel<0)throw new Error("More objects have ended than have been started (negative object nesting level)!")}getNestingLevel(){return this.objectLevel}canRenderFromWithoutDataLoss(t){return!1}renderFromOtherOfSameType(t,e){throw new Error(`Unable to render from ${e}: Not implemented`)}setTransform(t){this.selfTransform=t}pushTransform(t){this.transformStack.push(this.selfTransform),this.setTransform(this.getCanvasToScreenTransform().rightMul(t))}popTransform(){var t;if(0===this.transformStack.length)throw new Error("Unable to pop more transforms than have been pushed!");this.setTransform(null!==(t=this.transformStack.pop())&&void 0!==t?t:null)}getCanvasToScreenTransform(){return this.selfTransform?this.selfTransform:this.viewport.canvasToScreenTransform}canvasToScreen(t){return this.getCanvasToScreenTransform().transformVec2(t)}getSizeOfCanvasPixelOnScreen(){return this.getCanvasToScreenTransform().transformVec3(S.unitX).length()}}const Yt="http://www.w3.org/2000/svg";class Qt extends Jt{constructor(t,e,n=!1){super(e),this.elem=t,this.sanitize=n,this.lastPathStyle=null,this.lastPathString=[],this.objectElems=null,this.overwrittenAttrs={},this.clear()}setRootSVGAttribute(t,e){this.sanitize||(t in this.overwrittenAttrs||(this.overwrittenAttrs[t]=this.elem.getAttribute(t)),null!==e?this.elem.setAttribute(t,e):this.elem.removeAttribute(t))}displaySize(){return S.of(this.elem.clientWidth,this.elem.clientHeight)}clear(){if(this.lastPathString=[],!this.sanitize){for(const t in this.overwrittenAttrs){const e=this.overwrittenAttrs[t];e?this.elem.setAttribute(t,e):this.elem.removeAttribute(t)}this.overwrittenAttrs={}}}addPathToSVG(){var t;if(!this.lastPathStyle||0===this.lastPathString.length)return;const e=document.createElementNS(Yt,"path");e.setAttribute("d",this.lastPathString.join(" "));const n=this.lastPathStyle;e.setAttribute("fill",n.fill.toHexString()),n.stroke&&(e.setAttribute("stroke",n.stroke.color.toHexString()),e.setAttribute("stroke-width",n.stroke.width.toString())),this.elem.appendChild(e),null===(t=this.objectElems)||void 0===t||t.push(e)}drawPath(t){var e;const n=t.style,r=kt.fromRenderable(t);n.fill.eq(null===(e=this.lastPathStyle)||void 0===e?void 0:e.fill)&&0!==this.lastPathString.length||(this.addPathToSVG(),this.lastPathStyle=n,this.lastPathString=[]),this.lastPathString.push(r.toString())}transformFrom(t,e){let n=this.getCanvasToScreenTransform().rightMul(t);const r=n.transformVec2(S.zero);n=n.rightMul(P.translation(r.times(-1))),e.style.transform=`matrix(\n\t\t\t${n.a1}, ${n.b1},\n\t\t\t${n.a2}, ${n.b2},\n\t\t\t${n.a3}, ${n.b3}\n\t\t)`,e.setAttribute("x",`${bt(r.x)}`),e.setAttribute("y",`${bt(r.y)}`)}drawText(t,e,n){var r,i,o;const s=document.createElementNS(Yt,"text");if(s.appendChild(document.createTextNode(t)),this.transformFrom(e,s),s.style.fontFamily=n.fontFamily,s.style.fontVariant=null!==(r=n.fontVariant)&&void 0!==r?r:"",s.style.fontWeight=null!==(i=n.fontWeight)&&void 0!==i?i:"",s.style.fontSize=n.size+"px",s.style.fill=n.renderingStyle.fill.toHexString(),n.renderingStyle.stroke){const t=n.renderingStyle.stroke;s.style.stroke=t.color.toHexString(),s.style.strokeWidth=t.width+"px"}this.elem.appendChild(s),null===(o=this.objectElems)||void 0===o||o.push(s)}drawImage(t){var e,n,r,i,o;const s=document.createElementNS(Yt,"image");s.setAttribute("href",t.base64Url),s.setAttribute("width",null!==(e=t.image.getAttribute("width"))&&void 0!==e?e:""),s.setAttribute("height",null!==(n=t.image.getAttribute("height"))&&void 0!==n?n:""),s.setAttribute("aria-label",null!==(i=null!==(r=t.image.getAttribute("aria-label"))&&void 0!==r?r:t.image.getAttribute("alt"))&&void 0!==i?i:""),this.transformFrom(t.transform,s),this.elem.appendChild(s),null===(o=this.objectElems)||void 0===o||o.push(s)}startObject(t){super.startObject(t),this.lastPathString=[],this.lastPathStyle=null,this.objectElems=[]}endObject(t){var e;if(super.endObject(t),this.addPathToSVG(),t&&!this.sanitize)for(const n of null!==(e=this.objectElems)&&void 0!==e?e:[]){const e=t.svgAttrs,r=t.svgStyleAttrs;if(e)for(const[t,r]of e)n.setAttribute(t,r);if(r)for(const t of r)n.style.setProperty(t.key,t.value,t.priority)}}unimplementedMessage(){throw new Error("Not implemenented!")}beginPath(t){this.unimplementedMessage()}endPath(t){this.unimplementedMessage()}lineTo(t){this.unimplementedMessage()}moveTo(t){this.unimplementedMessage()}traceCubicBezierCurve(t,e,n){this.unimplementedMessage()}traceQuadraticBezierCurve(t,e){this.unimplementedMessage()}drawPoints(...t){t.map((t=>{const e=document.createElementNS(Yt,"circle");e.setAttribute("cx",`${t.x}`),e.setAttribute("cy",`${t.y}`),e.setAttribute("r","15"),this.elem.appendChild(e)}))}drawSVGElem(t){this.sanitize||this.elem.appendChild(t.cloneNode(!0))}isTooSmallToRender(t){return!1}}var te;!function(t){t[t.Circle=0]="Circle",t[t.Square=1]="Square"}(te||(te={}));class ee{constructor(t,e,n,r,i,o){switch(this.shape=t,this.parentSide=e,this.parent=n,this.onDragStart=r,this.onDragUpdate=i,this.onDragEnd=o,this.dragLastPos=null,this.element=document.createElement("div"),this.element.classList.add(`${de}handle`),t){case te.Circle:this.element.classList.add(`${de}circle`);break;case te.Square:this.element.classList.add(`${de}square`);break;default:(t=>{throw new Error(`Should be unreachable. Key: ${t}.`)})(t)}this.updatePosition()}addTo(t){t.appendChild(this.element)}updatePosition(){const t=this.parent.screenRegion,e=S.of(30,30),n=t.size.scale(this.parentSide).minus(e.times(.5));this.element.style.marginLeft=`${n.x}px`,this.element.style.marginTop=`${n.y}px`,this.element.style.width=`${e.x}px`,this.element.style.height=`${e.y}px`}isTarget(t){return t===this.element}handleDragStart(t){this.onDragStart(t.canvasPos),this.dragLastPos=t.canvasPos}handleDragUpdate(t){this.dragLastPos&&this.onDragUpdate(t.canvasPos)}handleDragEnd(){this.dragLastPos&&this.onDragEnd()}}class ne extends T{constructor(t){super("duplicate"),this.toDuplicate=t,this.duplicates=t.map((t=>t.clone())),this.reverse=new Ot(this.duplicates)}apply(t){this.reverse.unapply(t)}unapply(t){this.reverse.apply(t)}description(t,e){var n;return 0===this.duplicates.length?e.duplicatedNoElements:e.duplicateAction(null!==(n=Mt(e,this.duplicates))&&void 0!==n?n:e.elements,this.duplicates.length)}serializeToJSON(){return this.toDuplicate.map((t=>t.getId()))}}var re,ie;T.register("duplicate",((t,e)=>{const n=t.map((t=>e.image.lookupElement(t)));return new ne(n)})),function(t){t[t.Both=0]="Both",t[t.HorizontalOnly=1]="HorizontalOnly",t[t.VerticalOnly=2]="VerticalOnly"}(re||(re={})),function(t){t[t.Snap=0]="Snap",t[t.NoSnap=1]="NoSnap"}(ie||(ie={}));class oe{constructor(t,e){this.editor=t,this.selection=e}onDragStart(t){this.selection.setTransform(P.identity),this.dragStartPoint=t}onDragUpdate(t){const e=this.editor.viewport.roundPoint(t.minus(this.dragStartPoint));this.selection.setTransform(P.translation(e))}onDragEnd(){this.selection.finalizeTransform()}}class se{constructor(t,e){this.editor=t,this.selection=e,this.mode=re.Both}onDragStart(t,e){this.selection.setTransform(P.identity),this.mode=e,this.dragStartPoint=t}onDragUpdate(t){const e=t.minus(this.dragStartPoint),n=this.selection.preTransformRegion.width,r=this.selection.preTransformRegion.height;let i=S.of(1,1);if(this.mode===re.HorizontalOnly){const t=n+e.x;i=S.of(t/n,i.y)}if(this.mode===re.VerticalOnly){const t=r+e.y;i=S.of(i.x,t/r)}if(this.mode===re.Both){const t=n+(Math.abs(e.x)>Math.abs(e.y)?e.x:e.y);i=S.of(t/n,t/n)}if(i=i.map((t=>H.roundScaleRatio(t,2))),i.x>0&&i.y>0){const t=this.editor.viewport.roundPoint(this.selection.preTransformRegion.topLeft);this.selection.setTransform(P.scaling2D(i,t))}}onDragEnd(){this.selection.finalizeTransform()}}class ae{constructor(t,e){this.editor=t,this.selection=e,this.startAngle=0}getAngle(t){const e=this.selection.preTransformRegion.center;return t.minus(e).angle()}roundAngle(t){const e=8/Math.PI;return Math.round(t*e)/e}onDragStart(t){this.selection.setTransform(P.identity),this.startAngle=this.getAngle(t)}onDragUpdate(t){const e=this.roundAngle(this.getAngle(t)-this.startAngle),n=this.editor.viewport.roundPoint(this.selection.preTransformRegion.center),r=P.zRotation(e).mapEntries((t=>H.roundScaleRatio(t))),i=P.translation(n).rightMul(r).rightMul(P.translation(n.times(-1)));this.selection.setTransform(i)}onDragEnd(){this.selection.finalizeTransform()}}var le,ce=function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{l(r.next(t))}catch(t){o(t)}}function a(t){try{l(r.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}l((r=r.apply(t,e||[])).next())}))};class he{constructor(t,e){this.editor=e,this.transform=P.identity,this.transformCommands=[],this.selectedElems=[],this.targetHandle=null,this.backgroundDragging=!1,this.originalRegion=new B(t.x,t.y,0,0),this.transformers={drag:new oe(e,this),resize:new se(e,this),rotate:new ae(e,this)},this.container=document.createElement("div"),this.backgroundElem=document.createElement("div"),this.backgroundElem.classList.add(`${de}selection-background`),this.container.appendChild(this.backgroundElem);const n=new ee(te.Square,S.of(1,.5),this,(t=>this.transformers.resize.onDragStart(t,re.HorizontalOnly)),(t=>this.transformers.resize.onDragUpdate(t)),(()=>this.transformers.resize.onDragEnd())),r=new ee(te.Square,S.of(.5,1),this,(t=>this.transformers.resize.onDragStart(t,re.VerticalOnly)),(t=>this.transformers.resize.onDragUpdate(t)),(()=>this.transformers.resize.onDragEnd())),i=new ee(te.Square,S.of(1,1),this,(t=>this.transformers.resize.onDragStart(t,re.Both)),(t=>this.transformers.resize.onDragUpdate(t)),(()=>this.transformers.resize.onDragEnd())),o=new ee(te.Circle,S.of(.5,0),this,(t=>this.transformers.rotate.onDragStart(t)),(t=>this.transformers.rotate.onDragUpdate(t)),(()=>this.transformers.rotate.onDragEnd()));this.handles=[i,n,r,o];for(const t of this.handles)t.addTo(this.backgroundElem)}getTransform(){return this.transform}get preTransformRegion(){return this.originalRegion}get region(){const t=P.zRotation(this.regionRotation,this.originalRegion.center),e=this.transform.rightMul(t.inverse());return this.originalRegion.transformedBoundingBox(e)}get regionRotation(){return this.transform.transformVec3(S.unitX).angle()}get preTransformedScreenRegion(){const t=t=>this.editor.viewport.canvasToScreen(t);return B.fromCorners(t(this.preTransformRegion.topLeft),t(this.preTransformRegion.bottomRight))}get preTransformedScreenRegionRotation(){return this.editor.viewport.getRotationAngle()}get screenRegion(){const t=this.editor.viewport.canvasToScreenTransform,e=this.editor.viewport.getScaleFactor(),n=t.transformVec2(this.region.center);return new B(n.x,n.y,e*this.region.width,e*this.region.height).translatedBy(this.region.size.times(-e/2))}get screenRegionRotation(){return this.regionRotation+this.editor.viewport.getRotationAngle()}computeTransformCommands(){return this.selectedElems.map((t=>t.transformBy(this.transform)))}setTransform(t,e=!0){this.transform=t,e&&(this.previewTransformCmds(),this.scrollTo())}finalizeTransform(){this.transformCommands.forEach((t=>{t.unapply(this.editor)}));const t=this.transform,e=this.computeTransformCommands();this.transformCommands=[],this.originalRegion=this.originalRegion.transformedBoundingBox(this.transform),this.transform=P.identity,this.editor.dispatch(new he.ApplyTransformationCommand(this,e,t))}previewTransformCmds(){this.selectedElems.length>100||(this.transformCommands.forEach((t=>t.unapply(this.editor))),this.transformCommands=this.computeTransformCommands(),this.transformCommands.forEach((t=>t.apply(this.editor)))),this.updateUI()}resolveToObjects(){let t=!1;if(this.transform=P.identity,0===this.region.w||0===this.region.h){const e=this.editor.viewport.visibleRect.maxDimension/200;this.originalRegion=B.bboxOf(this.region.corners,e),t=!0}return this.selectedElems=this.editor.image.getElementsIntersectingRegion(this.region).filter((t=>{if(this.region.containsRect(t.getBBox()))return!0;const e=[];for(const t of this.region.divideIntoGrid(2,2))e.push(...t.getEdges());return e.some((e=>t.intersects(e)))})),t&&this.selectedElems.length>0&&(this.selectedElems=[this.selectedElems[this.selectedElems.length-1]]),!!this.recomputeRegion()&&(this.updateUI(),!0)}recomputeRegion(){const t=this.selectedElems.reduce(((t,e)=>(null!=t?t:e.getBBox()).union(e.getBBox())),null);if(!t)return this.cancelSelection(),!1;this.originalRegion=t;const e=this.getMinCanvasSize();if(this.originalRegion.w<e||this.originalRegion.h<e){const t=e/2;this.originalRegion=B.bboxOf(this.originalRegion.corners,t)}return!0}getMinCanvasSize(){return 2*(30/this.editor.viewport.getScaleFactor())}getSelectedItemCount(){return this.selectedElems.length}updateUI(){this.backgroundElem.style.marginLeft=`${this.screenRegion.topLeft.x}px`,this.backgroundElem.style.marginTop=`${this.screenRegion.topLeft.y}px`,this.backgroundElem.style.width=`${this.screenRegion.width}px`,this.backgroundElem.style.height=`${this.screenRegion.height}px`;const t=180*this.screenRegionRotation/Math.PI;this.backgroundElem.style.transform=`rotate(${t}deg)`,this.backgroundElem.style.transformOrigin="center";for(const t of this.handles)t.updatePosition()}onDragStart(t,e){for(const n of this.handles)if(n.isTarget(e))return n.handleDragStart(t),this.targetHandle=n,!0;return this.backgroundElem===e&&(this.backgroundDragging=!0,this.transformers.drag.onDragStart(t.canvasPos),!0)}onDragUpdate(t){this.backgroundDragging&&this.transformers.drag.onDragUpdate(t.canvasPos),this.targetHandle&&this.targetHandle.handleDragUpdate(t),this.updateUI()}onDragEnd(){this.backgroundDragging?this.transformers.drag.onDragEnd():this.targetHandle&&this.targetHandle.handleDragEnd(),this.backgroundDragging=!1,this.targetHandle=null,this.updateUI()}onDragCancel(){this.backgroundDragging=!1,this.targetHandle=null,this.setTransform(P.identity)}scrollTo(){if(0===this.selectedElems.length)return;const t=new B(0,0,this.editor.display.width,this.editor.display.height);if(!t.containsPoint(this.screenRegion.center)){const e=t.getClosestPointOnBoundaryTo(this.screenRegion.center),n=this.screenRegion.center.minus(e),r=this.editor.viewport.screenToCanvasTransform.transformVec3(n);this.editor.dispatchNoAnnounce(H.transformBy(P.translation(r.times(-1))),!1)}}deleteSelectedObjects(){return new Ot(this.selectedElems)}duplicateSelectedObjects(){return new ne(this.selectedElems)}addTo(t){this.container.parentElement&&this.container.remove(),t.appendChild(this.container)}setToPoint(t){this.originalRegion=this.originalRegion.grownToPoint(t),this.updateUI()}cancelSelection(){this.container.parentElement&&this.container.remove(),this.originalRegion=B.empty}setSelectedObjects(t,e){this.originalRegion=e,this.selectedElems=t,this.updateUI()}getSelectedObjects(){return this.selectedElems}}le=he,T.register("selection-tool-transform",((t,e)=>{const n=new P(...t.transform),r=t.commands.map((t=>T.deserialize(t,e)));return new le.ApplyTransformationCommand(null,r,n)})),he.ApplyTransformationCommand=class extends T{constructor(t,e,n){super("selection-tool-transform"),this.selection=t,this.currentTransfmCommands=e,this.fullTransform=n}apply(t){var e,n,r,i,o;return ce(this,void 0,void 0,(function*(){null===(e=this.selection)||void 0===e||e.setTransform(this.fullTransform,!1),null===(n=this.selection)||void 0===n||n.updateUI(),yield t.asyncApplyCommands(this.currentTransfmCommands,100),null===(r=this.selection)||void 0===r||r.setTransform(P.identity,!1),null===(i=this.selection)||void 0===i||i.recomputeRegion(),null===(o=this.selection)||void 0===o||o.updateUI()}))}unapply(t){var e,n,r,i,o;return ce(this,void 0,void 0,(function*(){null===(e=this.selection)||void 0===e||e.setTransform(this.fullTransform.inverse(),!1),null===(n=this.selection)||void 0===n||n.updateUI(),yield t.asyncUnapplyCommands(this.currentTransfmCommands,100),null===(r=this.selection)||void 0===r||r.setTransform(P.identity),null===(i=this.selection)||void 0===i||i.recomputeRegion(),null===(o=this.selection)||void 0===o||o.updateUI()}))}serializeToJSON(){return{commands:this.currentTransfmCommands.map((t=>t.serialize())),transform:this.fullTransform.toArray()}}description(t,e){return e.transformedElements(this.currentTransfmCommands.length)}};const de="selection-tool-";class ue extends G{constructor(t,e){super(t.notifier,e),this.editor=t,this.lastEvtTarget=null,this.selectionBoxHandlingEvt=!1,this.handleOverlay=document.createElement("div"),t.createHTMLOverlay(this.handleOverlay),this.handleOverlay.style.display="none",this.handleOverlay.classList.add("handleOverlay"),t.notifier.on(M.ViewportChanged,(t=>{var e;null===(e=this.selectionBox)||void 0===e||e.updateUI()})),this.editor.handleKeyEventsFrom(this.handleOverlay),this.editor.handlePointerEventsFrom(this.handleOverlay,((t,e)=>("pointerdown"===t&&(this.lastEvtTarget=e.target),!0)))}makeSelectionBox(t){this.prevSelectionBox=this.selectionBox,this.selectionBox=new he(t,this.editor),this.handleOverlay.replaceChildren(),this.selectionBox.addTo(this.handleOverlay)}onPointerDown(t){var e;return!(1!==t.allPointers.length||!t.current.isPrimary)&&(this.lastEvtTarget&&(null===(e=this.selectionBox)||void 0===e?void 0:e.onDragStart(t.current,this.lastEvtTarget))?this.selectionBoxHandlingEvt=!0:this.makeSelectionBox(t.current.canvasPos),!0)}onPointerMove(t){this.selectionBox&&(this.selectionBoxHandlingEvt?this.selectionBox.onDragUpdate(t.current):this.selectionBox.setToPoint(t.current.canvasPos))}onSelectionUpdated(){var t,e;this.editor.notifier.dispatch(M.ToolUpdated,{kind:M.ToolUpdated,tool:this});const n=null!==(e=null===(t=this.selectionBox)||void 0===t?void 0:t.getSelectedItemCount())&&void 0!==e?e:0;n>0?(this.editor.announceForAccessibility(this.editor.localization.selectedElements(n)),this.zoomToSelection()):this.selectionBox&&(this.selectionBox.cancelSelection(),this.prevSelectionBox=this.selectionBox,this.selectionBox=null)}onGestureEnd(){this.lastEvtTarget=null,this.selectionBox&&(this.selectionBoxHandlingEvt?this.selectionBox.onDragEnd():(this.selectionBox.resolveToObjects(),this.onSelectionUpdated()),this.selectionBoxHandlingEvt=!1)}zoomToSelection(){if(this.selectionBox){const t=this.selectionBox.region;this.editor.dispatchNoAnnounce(this.editor.viewport.zoomTo(t,!1),!1)}}onPointerUp(t){this.selectionBox&&(this.selectionBox.setToPoint(t.current.canvasPos),this.onGestureEnd())}onGestureCancel(){var t,e,n;this.selectionBoxHandlingEvt?null===(t=this.selectionBox)||void 0===t||t.onDragCancel():(null===(e=this.selectionBox)||void 0===e||e.cancelSelection(),this.selectionBox=this.prevSelectionBox,null===(n=this.selectionBox)||void 0===n||n.addTo(this.handleOverlay))}onKeyPress(t){let e=0,n=0,r=0,i=0,o=0;switch(t.key){case"a":case"h":case"ArrowLeft":n-=1;break;case"d":case"l":case"ArrowRight":n+=1;break;case"q":case"k":case"ArrowUp":r-=1;break;case"e":case"j":case"ArrowDown":r+=1;break;case"r":e+=1;break;case"R":e-=1;break;case"i":i-=1;break;case"I":i+=1;break;case"o":o-=1;break;case"O":o+=1}let s=0!==n||0!==r||0!==e||0!==i||0!==o;if(this.selectionBox){if(s){const t=10*this.editor.viewport.getSizeOfPixelOnCanvas(),s=Math.PI/8,a=5/4,l=this.selectionBox.region,c=S.of(Math.pow(a,i),Math.pow(a,o)),h=P.zRotation(e*s).mapEntries((t=>H.roundScaleRatio(t))),d=this.editor.viewport.roundPoint(l.center),u=P.scaling2D(c,this.editor.viewport.roundPoint(l.topLeft)).rightMul(P.translation(d).rightMul(h).rightMul(P.translation(d.times(-1)))).rightMul(P.translation(this.editor.viewport.roundPoint(S.of(n,r).times(t)))),p=this.selectionBox.getTransform();this.selectionBox.setTransform(p.rightMul(u))}}else s=!1;return!this.selectionBox||s||"Delete"!==t.key&&"Backspace"!==t.key||(this.editor.dispatch(this.selectionBox.deleteSelectedObjects()),this.clearSelection(),s=!0),s}onKeyUp(t){return!(!this.selectionBox||!ue.handleableKeys.some((e=>e===t.key)))&&(this.selectionBox.finalizeTransform(),!0)}onCopy(t){if(!this.selectionBox)return!1;const e=this.selectionBox.getSelectedObjects(),n=this.selectionBox.region;if(0===e.length)return!1;const r=new H(this.editor.notifier);r.updateScreenSize(S.of(n.w,n.h)),r.resetTransform(P.translation(n.topLeft));const i=document.createElementNS("http://www.w3.org/2000/svg","svg"),o=new Qt(i,r,!0),s=[];for(const t of e)t.render(o),t instanceof Wt&&s.push(t.getText());return t.setData("image/svg+xml",i.outerHTML),s.length>0&&t.setData("text/plain",s.join("\n")),!0}setEnabled(t){super.setEnabled(t),this.handleOverlay.replaceChildren(),this.selectionBox=null,this.handleOverlay.style.display=t?"block":"none",t?(this.handleOverlay.tabIndex=0,this.handleOverlay.setAttribute("aria-label",this.editor.localization.selectionToolKeyboardShortcuts)):this.handleOverlay.tabIndex=-1}getSelection(){return this.selectionBox}setSelection(t){let e=null;for(const n of t)e=e?e.union(n.getBBox()):n.getBBox();e&&(this.clearSelection(),this.selectionBox||this.makeSelectionBox(e.topLeft),this.selectionBox.setSelectedObjects(t,e),this.onSelectionUpdated())}clearSelection(){this.handleOverlay.replaceChildren(),this.prevSelectionBox=this.selectionBox,this.selectionBox=null,this.onSelectionUpdated()}}ue.handleableKeys=["a","h","ArrowLeft","d","l","ArrowRight","q","k","ArrowUp","e","j","ArrowDown","r","R","i","I","o","O"];class pe extends G{constructor(t){super(t.notifier,t.localization.undoRedoTool),this.editor=t}onKeyPress({key:t,ctrlKey:e}){if(e){if("z"===t)return this.editor.history.undo(),!0;if("Z"===t)return this.editor.history.redo(),!0}return!1}}const me="textEditorOverlay";class ge extends G{constructor(t,e,n){super(t.notifier,e),this.editor=t,this.localizationTable=n,this.textInputElem=null,this.textTargetPosition=null,this.textMeasuringCtx=null,this.textStyle={size:32,fontFamily:"sans-serif",renderingStyle:{fill:Et.purple}},this.textEditOverlay=document.createElement("div"),this.textEditOverlay.classList.add(me),this.editor.addStyleSheet("\n\t\t\t.textEditorOverlay {\n\t\t\t\theight: 0;\n\t\t\t\toverflow: visible;\n\t\t\t}\n\n\t\t\t.textEditorOverlay input {\n\t\t\t\tbackground-color: rgba(0, 0, 0, 0);\n\t\t\t\tborder: none;\n\t\t\t\tpadding: 0;\n\t\t\t}\n\t\t"),this.editor.createHTMLOverlay(this.textEditOverlay),this.editor.notifier.on(M.ViewportChanged,(()=>this.updateTextInput()))}getTextAscent(t,e){var n;return null!==(n=this.textMeasuringCtx)&&void 0!==n||(this.textMeasuringCtx=document.createElement("canvas").getContext("2d")),this.textMeasuringCtx?(Wt.applyTextStyles(this.textMeasuringCtx,e),this.textMeasuringCtx.measureText(t).actualBoundingBoxAscent):2*e.size/3}flushInput(){if(this.textInputElem&&this.textTargetPosition){const t=this.textInputElem.value;if(this.textInputElem.remove(),this.textInputElem=null,""===t)return;const e=P.translation(this.textTargetPosition).rightMul(P.scaling2D(this.editor.viewport.getSizeOfPixelOnCanvas())).rightMul(P.zRotation(this.textRotation)),n=new Wt([t],e,this.textStyle),r=I.addElement(n);this.editor.dispatch(r)}}updateTextInput(){var t,e,n;if(!this.textInputElem||!this.textTargetPosition)return void(null===(t=this.textInputElem)||void 0===t||t.remove());const r=this.editor.viewport,i=r.canvasToScreen(this.textTargetPosition);this.textInputElem.type="text",this.textInputElem.placeholder=this.localizationTable.enterTextToInsert,this.textInputElem.style.fontFamily=this.textStyle.fontFamily,this.textInputElem.style.fontVariant=null!==(e=this.textStyle.fontVariant)&&void 0!==e?e:"",this.textInputElem.style.fontWeight=null!==(n=this.textStyle.fontWeight)&&void 0!==n?n:"",this.textInputElem.style.fontSize=`${this.textStyle.size}px`,this.textInputElem.style.color=this.textStyle.renderingStyle.fill.toHexString(),this.textInputElem.style.position="relative",this.textInputElem.style.left=`${i.x}px`,this.textInputElem.style.top=`${i.y}px`,this.textInputElem.style.margin="0";const o=this.textRotation+r.getRotationAngle(),s=this.getTextAscent(this.textInputElem.value||"W",this.textStyle);this.textInputElem.style.transform=`rotate(${180*o/Math.PI}deg) translate(0, ${-s}px)`,this.textInputElem.style.transformOrigin="top left"}startTextInput(t,e){this.flushInput(),this.textInputElem=document.createElement("input"),this.textInputElem.value=e,this.textTargetPosition=t,this.textRotation=-this.editor.viewport.getRotationAngle(),this.updateTextInput(),this.textInputElem.oninput=()=>{var t;this.textInputElem&&(this.textInputElem.size=(null===(t=this.textInputElem)||void 0===t?void 0:t.value.length)||10)},this.textInputElem.onblur=()=>{setTimeout((()=>this.flushInput()),0)},this.textInputElem.onkeyup=t=>{var e;"Enter"===t.key?(this.flushInput(),this.editor.focus()):"Escape"===t.key&&(null===(e=this.textInputElem)||void 0===e||e.remove(),this.textInputElem=null,this.editor.focus())},this.textEditOverlay.replaceChildren(this.textInputElem),setTimeout((()=>{var t;return null===(t=this.textInputElem)||void 0===t?void 0:t.focus()}),0)}setEnabled(t){super.setEnabled(t),t||this.flushInput(),this.textEditOverlay.style.display=t?"block":"none"}onPointerDown({current:t,allPointers:e}){return t.device!==O.Eraser&&(1===e.length&&(this.startTextInput(t.canvasPos,""),!0))}onGestureCancel(){this.flushInput(),this.editor.focus()}dispatchUpdateEvent(){this.updateTextInput(),this.editor.notifier.dispatch(M.ToolUpdated,{kind:M.ToolUpdated,tool:this})}setFontFamily(t){t!==this.textStyle.fontFamily&&(this.textStyle=Object.assign(Object.assign({},this.textStyle),{fontFamily:t}),this.dispatchUpdateEvent())}setColor(t){t.eq(this.textStyle.renderingStyle.fill)||(this.textStyle=Object.assign(Object.assign({},this.textStyle),{renderingStyle:Object.assign(Object.assign({},this.textStyle.renderingStyle),{fill:t})}),this.dispatchUpdateEvent())}setFontSize(t){t!==this.textStyle.size&&(this.textStyle=Object.assign(Object.assign({},this.textStyle),{size:t}),this.dispatchUpdateEvent())}getTextStyle(){return this.textStyle}}class fe extends G{constructor(t,e){super(t.notifier,e),this.editor=t,this.colorPreviewListener=null,this.colorSelectListener=null}setColorListener(t,e){this.colorPreviewListener=t,this.colorSelectListener=e}clearColorListener(){this.colorPreviewListener=null,this.colorSelectListener=null}onPointerDown({current:t,allPointers:e}){return!(!this.colorPreviewListener||1!==e.length)&&(this.colorPreviewListener(this.editor.display.getColorAt(t.screenPos)),!0)}onPointerMove({current:t}){var e;null===(e=this.colorPreviewListener)||void 0===e||e.call(this,this.editor.display.getColorAt(t.screenPos))}onPointerUp({current:t}){var e;null===(e=this.colorSelectListener)||void 0===e||e.call(this,this.editor.display.getColorAt(t.screenPos))}onGestureCancel(){var t;null===(t=this.colorSelectListener)||void 0===t||t.call(this,null)}}class ve extends G{constructor(t){super(t.notifier,t.localization.changeTool),this.editor=t}onKeyPress({key:t}){const e=this.editor.toolController.getPrimaryTools(),n=/^[0-9]$/.exec(t);let r;if(n){r=e[parseInt(n[0],10)-1]}return!!r&&(r.setEnabled(!0),!0)}}const ye=t=>{if(t instanceof T)return new class extends T{serializeToJSON(){return t.serialize()}apply(e){t.unapply(e)}unapply(e){t.unapply(e)}description(e,n){return n.inverseOf(t.description(e,n))}}("inverse");return new class extends w{apply(e){t.unapply(e)}unapply(e){t.apply(e)}description(e,n){return n.inverseOf(t.description(e,n))}}};T.register("inverse",((t,e)=>ye(T.deserialize(t,e))));const xe=ye;class be extends w{constructor(t,e){super(),this.commands=t,this.applyChunkSize=e}apply(t){if(void 0===this.applyChunkSize)for(const e of this.commands)e.apply(t);else t.asyncApplyCommands(this.commands,this.applyChunkSize)}unapply(t){if(void 0===this.applyChunkSize)for(const e of this.commands)e.unapply(t);else t.asyncUnapplyCommands(this.commands,this.applyChunkSize)}description(t,e){const n=[];let r=null,i=0;for(const o of this.commands){const s=o.description(t,e);s!==r&&null!==r&&(n.push(e.unionOf(r,i)),r=null,i=0),i++,null!=r||(r=s)}return i>1?n.push(e.unionOf(r,i)):1===i&&n.push(r),n.join(", ")}}class we extends T{constructor(t,e){super("union"),this.commands=t,this.applyChunkSize=e,this.nonserializableCommand=new be(t,e)}serializeToJSON(){return{applyChunkSize:this.applyChunkSize,data:this.commands.map((t=>t.serialize()))}}apply(t){this.nonserializableCommand.apply(t)}unapply(t){this.nonserializableCommand.unapply(t)}description(t,e){return this.nonserializableCommand.description(t,e)}}const Te=(t,e)=>{let n=!0;for(const e of t)if(!(e instanceof T)){n=!1;break}if(n){return new we(t,e)}return new be(t,e)};T.register("union",((t,e)=>{if("number"!=typeof t.data.length)throw new Error("Unions of commands must serialize to lists of serialization data.");const n=t.applyChunkSize;if("number"!=typeof n&&void 0!==n)throw new Error("serialized applyChunkSize is neither undefined nor a number.");const r=[];for(const n of t.data)r.push(T.deserialize(n,e));return Te(r,n)}));const Ce=Te;var Se=function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{l(r.next(t))}catch(t){o(t)}}function a(t){try{l(r.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}l((r=r.apply(t,e||[])).next())}))};class ke extends G{constructor(t){super(t.notifier,t.localization.pasteHandler),this.editor=t}onPaste(t){const e=t.mime.toLowerCase();return"image/svg+xml"===e?(this.doSVGPaste(t.data),!0):"text/plain"===e?(this.doTextPaste(t.data),!0):("image/png"===e||"image/jpeg"===e)&&(this.doImagePaste(t.data),!0)}addComponentsFromPaste(t){return Se(this,void 0,void 0,(function*(){let e=null;for(const n of t)e=e?e.union(n.getBBox()):n.getBBox();if(!e)return;const n=this.editor.viewport.visibleRect,r=n.width/e.width,i=n.height/e.height;let o=r;(e.width*o>n.width||e.height*o>n.height)&&(o=i),o*=2/3,o=H.roundScaleRatio(o);const s=P.translation(n.center.minus(e.center)).rightMul(P.scaling2D(o,e.center)),a=[];for(const e of t)a.push(I.addElement(e)),a.push(e.transformBy(s));this.editor.dispatch(Ce(a,100),!0);for(const e of this.editor.toolController.getMatchingTools(ue))e.setEnabled(!0),e.setSelection(t)}))}doSVGPaste(t){return Se(this,void 0,void 0,(function*(){const e=Xt.fromString(t,!0),n=[];yield e.start((t=>{n.push(t)}),((t,e)=>null)),yield this.addComponentsFromPaste(n)}))}doTextPaste(t){var e,n;return Se(this,void 0,void 0,(function*(){const r=this.editor.toolController.getMatchingTools(ge);r.sort(((t,e)=>!t.isEnabled()&&e.isEnabled()?-1:!e.isEnabled()&&t.isEnabled()?1:0));const i={size:12,fontFamily:"sans",renderingStyle:{fill:Et.red}},o=null!==(n=null===(e=r[0])||void 0===e?void 0:e.getTextStyle())&&void 0!==n?n:i,s=t.split("\n");let a=null;const l=[];for(const t of s){let e=S.zero;if(a){const t=Math.floor(o.size);e=a.getBBox().bottomLeft.plus(S.unitY.times(t))}const n=new Wt([t],P.translation(e),o);l.push(n),a=n}1===l.length?yield this.addComponentsFromPaste([l[0]]):yield this.addComponentsFromPaste([new Wt(l,P.identity,o)])}))}doImagePaste(t){return Se(this,void 0,void 0,(function*(){const e=new Image;e.src=t;const n=yield Ft.fromImage(e,P.identity);yield this.addComponentsFromPaste([n])}))}}class Ee{constructor(t,e){this.activeTool=null;const n=new Dt;this.primaryToolGroup=n;const r=new q(t,_.TwoFingerTouchGestures|_.RightClickDrags,e.touchPanTool),i=new q(t,_.Keyboard,e.keyboardPanZoom),o=new Lt(t,e.penTool(1),{color:Et.purple,thickness:16}),s=[o,new Lt(t,e.penTool(2),{color:Et.clay,thickness:4}),new Lt(t,e.penTool(3),{color:Et.ofRGBA(1,1,0,.5),thickness:64}),new $t(t,e.eraserTool),new ue(t,e.selectionTool),new ge(t,e.textTool,e)];this.tools=[new fe(t,e.pipetteTool),r,...s,i,new pe(t),new ve(t),new ke(t)],s.forEach((t=>t.setToolGroup(n))),r.setEnabled(!0),o.setEnabled(!0),t.notifier.on(M.ToolEnabled,(n=>{n.kind===M.ToolEnabled&&t.announceForAccessibility(e.toolEnabledAnnouncement(n.tool.description))})),t.notifier.on(M.ToolDisabled,(n=>{n.kind===M.ToolDisabled&&t.announceForAccessibility(e.toolDisabledAnnouncement(n.tool.description))})),this.activeTool=null}setTools(t,e){this.tools=t,this.primaryToolGroup=null!=e?e:new Dt}addPrimaryTool(t){t.setToolGroup(this.primaryToolGroup),t.isEnabled()&&this.primaryToolGroup.notifyEnabled(t),this.addTool(t)}getPrimaryTools(){return this.tools.filter((t=>t.getToolGroup()===this.primaryToolGroup))}addTool(t){this.tools.push(t)}dispatchInputEvent(t){var e,n;let r=!1;if(t.kind===D.PointerDownEvt){for(const n of this.tools)if(n.isEnabled()&&n.onPointerDown(t)){this.activeTool!==n&&(null===(e=this.activeTool)||void 0===e||e.onGestureCancel()),this.activeTool=n,r=!0;break}}else if(t.kind===D.PointerUpEvt)null===(n=this.activeTool)||void 0===n||n.onPointerUp(t),this.activeTool=null,r=!0;else if(t.kind===D.PointerMoveEvt)null!==this.activeTool&&(this.activeTool.onPointerMove(t),r=!0);else if(t.kind===D.GestureCancelEvt)null!==this.activeTool&&(this.activeTool.onGestureCancel(),this.activeTool=null);else{let e;for(const n of this.tools)if(n.isEnabled()){switch(t.kind){case D.KeyPressEvent:r=n.onKeyPress(t);break;case D.KeyUpEvent:r=n.onKeyUp(t);break;case D.WheelEvt:r=n.onWheel(t);break;case D.CopyEvent:r=n.onCopy(t);break;case D.PasteEvent:r=n.onPaste(t);break;default:return e=t,e}if(r)break}}return r}getMatchingTools(t){return this.tools.filter((e=>e instanceof t))}}const Pe=class{constructor(t,e,n){this.editor=t,this.announceRedoCallback=e,this.announceUndoCallback=n,this.maxUndoRedoStackSize=700,this.undoStack=[],this.redoStack=[]}fireUpdateEvent(){this.editor.notifier.dispatch(M.UndoRedoStackUpdated,{kind:M.UndoRedoStackUpdated,undoStackSize:this.undoStack.length,redoStackSize:this.redoStack.length})}push(t,e=!0){e&&t.apply(this.editor),this.undoStack.push(t);for(const t of this.redoStack)t.onDrop(this.editor);if(this.redoStack=[],this.undoStack.length>this.maxUndoRedoStackSize){const t=10;this.undoStack.splice(0,t).forEach((t=>t.onDrop(this.editor)))}this.fireUpdateEvent(),this.editor.notifier.dispatch(M.CommandDone,{kind:M.CommandDone,command:t})}undo(){const t=this.undoStack.pop();t&&(this.redoStack.push(t),t.unapply(this.editor),this.announceUndoCallback(t),this.fireUpdateEvent(),this.editor.notifier.dispatch(M.CommandUndone,{kind:M.CommandUndone,command:t}))}redo(){const t=this.redoStack.pop();t&&(this.undoStack.push(t),t.apply(this.editor),this.announceRedoCallback(t),this.fireUpdateEvent(),this.editor.notifier.dispatch(M.CommandDone,{kind:M.CommandDone,command:t}))}get undoStackSize(){return this.undoStack.length}get redoStackSize(){return this.redoStack.length}};class ze{constructor(){this.listeners={}}dispatch(t,e){const n=this.listeners[t];if(n)for(let t=0;t<n.length;t++)n[t](e)}on(t,e){return this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e),{remove:()=>{const n=this.listeners[t];return this.off(t,e),n.length!==this.listeners[t].length}}}off(t,e){const n=this.listeners[t];n&&(this.listeners[t]=n.filter((t=>t!==e)))}}var Re=function(t,e,n){var r,i,o,s,a,l,c,h,d,u,p,m,g,f,v,y=e.createElement("canvas").getContext("2d"),x={r:0,g:0,b:0,h:0,s:0,v:0,a:1},b={el:"[data-coloris]",parent:"body",theme:"default",themeMode:"light",wrap:!0,margin:2,format:"hex",formatToggle:!1,swatches:[],swatchesOnly:!1,alpha:!0,forceAlpha:!1,focusInput:!0,selectInput:!1,inline:!1,defaultColor:"#000000",clearButton:!1,clearLabel:"Clear",a11y:{open:"Open color picker",close:"Close color picker",marker:"Saturation: {s}. Brightness: {v}.",hueSlider:"Hue slider",alphaSlider:"Opacity slider",input:"Color value field",format:"Color format",swatch:"Color swatch",instruction:"Saturation and brightness selector. Use up, down, left and right arrow keys to select."}},w={},T="",C={},S=!1;function k(n){if("object"==typeof n)for(var s in n)switch(s){case"el":R(n.el),!1!==n.wrap&&A(n.el);break;case"parent":(r=e.querySelector(n.parent))&&(r.appendChild(i),b.parent=n.parent,r===e.body&&(r=null));break;case"themeMode":b.themeMode=n.themeMode,"auto"===n.themeMode&&t.matchMedia&&t.matchMedia("(prefers-color-scheme: dark)").matches&&(b.themeMode="dark");case"theme":n.theme&&(b.theme=n.theme),i.className="clr-picker clr-"+b.theme+" clr-"+b.themeMode,b.inline&&B();break;case"margin":n.margin*=1,b.margin=isNaN(n.margin)?b.margin:n.margin;break;case"wrap":n.el&&n.wrap&&A(n.el);break;case"formatToggle":b.formatToggle=!!n.formatToggle,H("clr-format").style.display=b.formatToggle?"block":"none",b.formatToggle&&(b.format="auto");break;case"swatches":Array.isArray(n.swatches)&&function(){var t=[];n.swatches.forEach((function(e,n){t.push('<button type="button" id="clr-swatch-'+n+'" aria-labelledby="clr-swatch-label clr-swatch-'+n+'" style="color: '+e+';">'+e+"</button>")})),H("clr-swatches").innerHTML=t.length?"<div>"+t.join("")+"</div>":"",b.swatches=n.swatches.slice()}();break;case"swatchesOnly":b.swatchesOnly=!!n.swatchesOnly,i.setAttribute("data-minimal",b.swatchesOnly);break;case"alpha":b.alpha=!!n.alpha,i.setAttribute("data-alpha",b.alpha);break;case"inline":if(b.inline=!!n.inline,i.setAttribute("data-inline",b.inline),b.inline){var a=n.defaultColor||b.defaultColor;f=D(a),B(),L(a)}break;case"clearButton":"object"==typeof n.clearButton&&(n.clearButton.label&&(b.clearLabel=n.clearButton.label,h.innerHTML=b.clearLabel),n.clearButton=n.clearButton.show),b.clearButton=!!n.clearButton,h.style.display=b.clearButton?"block":"none";break;case"clearLabel":b.clearLabel=n.clearLabel,h.innerHTML=b.clearLabel;break;case"a11y":var u=n.a11y,m=!1;if("object"==typeof u)for(var g in u)u[g]&&b.a11y[g]&&(b.a11y[g]=u[g],m=!0);if(m){var v=H("clr-open-label"),y=H("clr-swatch-label");v.innerHTML=b.a11y.open,y.innerHTML=b.a11y.swatch,l.setAttribute("aria-label",b.a11y.close),d.setAttribute("aria-label",b.a11y.hueSlider),p.setAttribute("aria-label",b.a11y.alphaSlider),c.setAttribute("aria-label",b.a11y.input),o.setAttribute("aria-label",b.a11y.instruction)}default:b[s]=n[s]}}function E(t,e){"string"==typeof t&&"object"==typeof e&&(w[t]=e,S=!0)}function P(t){delete w[t],0===Object.keys(w).length&&(S=!1,t===T&&z())}function z(){Object.keys(C).length>0&&(k(C),T="",C={})}function R(t){G(e,"click",t,(function(t){b.inline||(function(t){if(S){var e=["el","wrap","inline","defaultColor","a11y"],n=function(n){var r=w[n];if(t.matches(n)){for(var i in T=n,C={},e.forEach((function(t){return delete r[t]})),r)C[i]=Array.isArray(b[i])?b[i].slice():b[i];return k(r),"break"}};for(var r in w)if("break"===n(r))break}}(t.target),g=t.target,v=g.value,f=D(v),i.classList.add("clr-open"),B(),L(v),(b.focusInput||b.selectInput)&&c.focus({preventScroll:!0}),b.selectInput&&c.select(),g.dispatchEvent(new Event("open",{bubbles:!0})))})),G(e,"input",t,(function(t){var e=t.target.parentNode;e.classList.contains("clr-field")&&(e.style.color=t.target.value)}))}function B(){var n,a,l,c=r,h=t.scrollY,d=i.offsetWidth,u=i.offsetHeight,p={left:!1,top:!1},m={x:0,y:0};if(c&&(n=t.getComputedStyle(c),a=parseFloat(n.marginTop),l=parseFloat(n.borderTopWidth),(m=c.getBoundingClientRect()).y+=l+h),!b.inline){var f=g.getBoundingClientRect(),v=f.x,y=h+f.y+f.height+b.margin;c?(v-=m.x,y-=m.y,v+d>c.clientWidth&&(v+=f.width-d,p.left=!0),y+u>c.clientHeight-a&&u+b.margin<=f.top-(m.y-h)&&(y-=f.height+u+2*b.margin,p.top=!0),y+=c.scrollTop):(v+d>e.documentElement.clientWidth&&(v+=f.width-d,p.left=!0),y+u-h>e.documentElement.clientHeight&&u+b.margin<=f.top&&(y=h+f.y-u-b.margin,p.top=!0)),i.classList.toggle("clr-left",p.left),i.classList.toggle("clr-top",p.top),i.style.left=v+"px",i.style.top=y+"px"}s={width:o.offsetWidth,height:o.offsetHeight,x:i.offsetLeft+o.offsetLeft+m.x,y:i.offsetTop+o.offsetTop+m.y}}function A(t){e.querySelectorAll(t).forEach((function(t){var n=t.parentNode;if(!n.classList.contains("clr-field")){var r=e.createElement("div");r.innerHTML='<button type="button" aria-labelledby="clr-open-label"></button>',n.insertBefore(r,t),r.setAttribute("class","clr-field"),r.style.color=t.value,r.appendChild(t)}}))}function I(t){if(g&&!b.inline){var e=g;t&&(g=null,v!==e.value&&(e.value=v,e.dispatchEvent(new Event("input",{bubbles:!0})))),setTimeout((function(){v!==e.value&&e.dispatchEvent(new Event("change",{bubbles:!0}))})),i.classList.remove("clr-open"),S&&z(),e.dispatchEvent(new Event("close",{bubbles:!0})),b.focusInput&&e.focus({preventScroll:!0}),g=null}}function L(t){var e=function(t){var e,n,r=/^((rgba)|rgb)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i;return y.fillStyle="#000",y.fillStyle=t,(e=r.exec(y.fillStyle))?(n={r:1*e[3],g:1*e[4],b:1*e[5],a:1*e[6]}).a=+n.a.toFixed(2):n={r:(e=y.fillStyle.replace("#","").match(/.{2}/g).map((function(t){return parseInt(t,16)})))[0],g:e[1],b:e[2],a:1},n}(t),r=function(t){var e=t.r/255,r=t.g/255,i=t.b/255,o=n.max(e,r,i),s=n.min(e,r,i),a=o-s,l=o,c=0,h=0;return a&&(o===e&&(c=(r-i)/a),o===r&&(c=2+(i-e)/a),o===i&&(c=4+(e-r)/a),o&&(h=a/o)),{h:(c=n.floor(60*c))<0?c+360:c,s:n.round(100*h),v:n.round(100*l),a:t.a}}(e);$(r.s,r.v),U(e,r),d.value=r.h,i.style.color="hsl("+r.h+", 100%, 50%)",u.style.left=r.h/360*100+"%",a.style.left=s.width*r.s/100+"px",a.style.top=s.height-s.height*r.v/100+"px",p.value=100*r.a,m.style.left=100*r.a+"%"}function D(t){var e=t.substring(0,3).toLowerCase();return"rgb"===e||"hsl"===e?e:"hex"}function M(t){t=void 0!==t?t:c.value,g&&(g.value=t,g.dispatchEvent(new Event("input",{bubbles:!0}))),e.dispatchEvent(new CustomEvent("coloris:pick",{detail:{color:t}}))}function O(t,e){var r={h:1*d.value,s:t/s.width*100,v:100-e/s.height*100,a:p.value/100},i=function(t){var e=t.s/100,r=t.v/100,i=e*r,o=t.h/60,s=i*(1-n.abs(o%2-1)),a=r-i;i+=a,s+=a;var l=n.floor(o)%6,c=[i,s,a,a,s,i][l],h=[s,i,i,s,a,a][l],d=[a,a,s,i,i,s][l];return{r:n.round(255*c),g:n.round(255*h),b:n.round(255*d),a:t.a}}(r);$(r.s,r.v),U(i,r),M()}function $(t,e){var n=b.a11y.marker;t=1*t.toFixed(1),e=1*e.toFixed(1),n=(n=n.replace("{s}",t)).replace("{v}",e),a.setAttribute("aria-label",n)}function N(t){var e=function(t){return{pageX:t.changedTouches?t.changedTouches[0].pageX:t.pageX,pageY:t.changedTouches?t.changedTouches[0].pageY:t.pageY}}(t),n=e.pageX-s.x,i=e.pageY-s.y;r&&(i+=r.scrollTop),n=n<0?0:n>s.width?s.width:n,i=i<0?0:i>s.height?s.height:i,a.style.left=n+"px",a.style.top=i+"px",O(n,i),t.preventDefault(),t.stopPropagation()}function F(t,e){var n=1*a.style.left.replace("px","")+t,r=1*a.style.top.replace("px","")+e;a.style.left=n+"px",a.style.top=r+"px",O(n,r)}function U(t,r){void 0===t&&(t={}),void 0===r&&(r={});var i=b.format;for(var s in t)x[s]=t[s];for(var h in r)x[h]=r[h];var d,u=function(t){var e=t.r.toString(16),n=t.g.toString(16),r=t.b.toString(16),i="";if(t.r<16&&(e="0"+e),t.g<16&&(n="0"+n),t.b<16&&(r="0"+r),b.alpha&&(t.a<1||b.forceAlpha)){var o=255*t.a|0;i=o.toString(16),o<16&&(i="0"+i)}return"#"+e+n+r+i}(x),p=u.substring(0,7);switch(a.style.color=p,m.parentNode.style.color=p,m.style.color=u,l.style.color=u,o.style.display="none",o.offsetHeight,o.style.display="",m.nextElementSibling.style.display="none",m.nextElementSibling.offsetHeight,m.nextElementSibling.style.display="","mixed"===i?i=1===x.a?"hex":"rgb":"auto"===i&&(i=f),i){case"hex":c.value=u;break;case"rgb":c.value=function(t){return!b.alpha||1===t.a&&!b.forceAlpha?"rgb("+t.r+", "+t.g+", "+t.b+")":"rgba("+t.r+", "+t.g+", "+t.b+", "+t.a+")"}(x);break;case"hsl":c.value=(d=function(t){var e,r=t.v/100,i=r*(1-t.s/100/2);return i>0&&i<1&&(e=n.round((r-i)/n.min(i,1-i)*100)),{h:t.h,s:e||0,l:n.round(100*i),a:t.a}}(x),!b.alpha||1===d.a&&!b.forceAlpha?"hsl("+d.h+", "+d.s+"%, "+d.l+"%)":"hsla("+d.h+", "+d.s+"%, "+d.l+"%, "+d.a+")")}e.querySelector('.clr-format [value="'+i+'"]').checked=!0}function j(){var t=1*d.value,e=1*a.style.left.replace("px",""),n=1*a.style.top.replace("px","");i.style.color="hsl("+t+", 100%, 50%)",u.style.left=t/360*100+"%",O(e,n)}function V(){var t=p.value/100;m.style.left=100*t+"%",U({a:t}),M()}function W(){r=null,(i=e.createElement("div")).setAttribute("id","clr-picker"),i.className="clr-picker",i.innerHTML='<input id="clr-color-value" class="clr-color" type="text" value="" spellcheck="false" aria-label="'+b.a11y.input+'"><div id="clr-color-area" class="clr-gradient" role="application" aria-label="'+b.a11y.instruction+'"><div id="clr-color-marker" class="clr-marker" tabindex="0"></div></div><div class="clr-hue"><input id="clr-hue-slider" type="range" min="0" max="360" step="1" aria-label="'+b.a11y.hueSlider+'"><div id="clr-hue-marker"></div></div><div class="clr-alpha"><input id="clr-alpha-slider" type="range" min="0" max="100" step="1" aria-label="'+b.a11y.alphaSlider+'"><div id="clr-alpha-marker"></div><span></span></div><div id="clr-format" class="clr-format"><fieldset class="clr-segmented"><legend>'+b.a11y.format+'</legend><input id="clr-f1" type="radio" name="clr-format" value="hex"><label for="clr-f1">Hex</label><input id="clr-f2" type="radio" name="clr-format" value="rgb"><label for="clr-f2">RGB</label><input id="clr-f3" type="radio" name="clr-format" value="hsl"><label for="clr-f3">HSL</label><span></span></fieldset></div><div id="clr-swatches" class="clr-swatches"></div><button type="button" id="clr-clear" class="clr-clear">'+b.clearLabel+'</button><button type="button" id="clr-color-preview" class="clr-preview" aria-label="'+b.a11y.close+'"></button><span id="clr-open-label" hidden>'+b.a11y.open+'</span><span id="clr-swatch-label" hidden>'+b.a11y.swatch+"</span>",e.body.appendChild(i),o=H("clr-color-area"),a=H("clr-color-marker"),h=H("clr-clear"),l=H("clr-color-preview"),c=H("clr-color-value"),d=H("clr-hue-slider"),u=H("clr-hue-marker"),p=H("clr-alpha-slider"),m=H("clr-alpha-marker"),R(b.el),A(b.el),G(i,"mousedown",(function(t){i.classList.remove("clr-keyboard-nav"),t.stopPropagation()})),G(o,"mousedown",(function(t){G(e,"mousemove",N)})),G(o,"touchstart",(function(t){e.addEventListener("touchmove",N,{passive:!1})})),G(a,"mousedown",(function(t){G(e,"mousemove",N)})),G(a,"touchstart",(function(t){e.addEventListener("touchmove",N,{passive:!1})})),G(c,"change",(function(t){g&&(L(c.value),M())})),G(h,"click",(function(t){M(""),I()})),G(l,"click",(function(t){M(),I()})),G(e,"click",".clr-format input",(function(t){f=t.target.value,U(),M()})),G(i,"click",".clr-swatches button",(function(t){L(t.target.textContent),M(),b.swatchesOnly&&I()})),G(e,"mouseup",(function(t){e.removeEventListener("mousemove",N)})),G(e,"touchend",(function(t){e.removeEventListener("touchmove",N)})),G(e,"mousedown",(function(t){i.classList.remove("clr-keyboard-nav"),I()})),G(e,"keydown",(function(t){"Escape"===t.key?I(!0):"Tab"===t.key&&i.classList.add("clr-keyboard-nav")})),G(e,"click",".clr-field button",(function(t){S&&z(),t.target.nextElementSibling.dispatchEvent(new Event("click",{bubbles:!0}))})),G(a,"keydown",(function(t){var e={ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0]};-1!==Object.keys(e).indexOf(t.key)&&(F.apply(void 0,e[t.key]),t.preventDefault())})),G(o,"click",N),G(d,"input",j),G(p,"input",V)}function H(t){return e.getElementById(t)}function G(t,e,n,r){var i=Element.prototype.matches||Element.prototype.msMatchesSelector;"string"==typeof n?t.addEventListener(e,(function(t){i.call(t.target,n)&&r.call(t.target,t)})):(r=n,t.addEventListener(e,r))}function _(t,n){n=void 0!==n?n:[],"loading"!==e.readyState?t.apply(void 0,n):e.addEventListener("DOMContentLoaded",(function(){t.apply(void 0,n)}))}void 0!==NodeList&&NodeList.prototype&&!NodeList.prototype.forEach&&(NodeList.prototype.forEach=Array.prototype.forEach);var q=function(){var t={init:W,set:k,wrap:A,close:I,setInstance:E,removeInstance:P,updatePosition:B};function e(t){_((function(){t&&("string"==typeof t?R(t):k(t))}))}var n=function(n){e[n]=function(){for(var e=arguments.length,r=new Array(e),i=0;i<e;i++)r[i]=arguments[i];_(t[n],r)}};for(var r in t)n(r);return e}();return q.coloris=q,q}(window,document,Math),Be=Re.coloris,Ae=Re.init;Re.set,Re.wrap,Re.close;const Ie={pen:"Pen",eraser:"Eraser",select:"Select",handTool:"Pan",zoom:"Zoom",resetView:"Reset view",thicknessLabel:"Thickness: ",colorLabel:"Color: ",fontLabel:"Font: ",resizeImageToSelection:"Resize image to selection",deleteSelection:"Delete selection",duplicateSelection:"Duplicate selection",undo:"Undo",redo:"Redo",selectObjectType:"Object type: ",pickColorFromScreen:"Pick color from screen",clickToPickColorAnnouncement:"Click on the screen to pick a color",selectionToolKeyboardShortcuts:"Selection tool: Use arrow keys to move selected items, lowercase/uppercase ‘i’ and ‘o’ to resize.",touchPanning:"Touchscreen panning",anyDevicePanning:"Any device panning",freehandPen:"Freehand",arrowPen:"Arrow",linePen:"Line",outlinedRectanglePen:"Outlined rectangle",filledRectanglePen:"Filled rectangle",dropdownShown:t=>`Dropdown for ${t} shown`,dropdownHidden:t=>`Dropdown for ${t} hidden`,zoomLevel:t=>`Zoom: ${t}%`,colorChangedAnnouncement:t=>`Color changed to ${t}`},Le="http://www.w3.org/2000/svg",De="\n\tstyle='fill: var(--icon-color);'\n",Me="\n\t<pattern\n\t\tid='checkerboard'\n\t\tviewBox='0,0,10,10'\n\t\twidth='20%'\n\t\theight='20%'\n\t\tpatternUnits='userSpaceOnUse'\n\t>\n\t\t<rect x=0 y=0 width=10 height=10 fill='white'/>\n\t\t<rect x=0 y=0 width=5 height=5 fill='gray'/>\n\t\t<rect x=5 y=5 width=5 height=5 fill='gray'/>\n\t</pattern>\n",Oe="url(#checkerboard)",$e=()=>Ne(!0),Ne=(t=!1)=>{const e=document.createElementNS(Le,"svg");return e.innerHTML=`\n\t\t<style>\n\t\t\t.toolbar-svg-undo-redo-icon {\n\t\t\t\tstroke: var(--icon-color);\n\t\t\t\tstroke-width: 12;\n\t\t\t\tstroke-linejoin: round;\n\t\t\t\tstroke-linecap: round;\n\t\t\t\tfill: none;\n\n\t\t\t\ttransform-origin: center;\n\t\t\t}\n\t\t</style>\n\t\t<path\n\t\t\td='M20,20 A15,15 0 0 1 70,80 L80,90 L60,70 L65,90 L87,90 L65,80'\n\t\t\tclass='toolbar-svg-undo-redo-icon'\n\t\t\tstyle='${t?"transform: scale(-1, 1);":""}'/>\n\t`,e.setAttribute("viewBox","0 0 100 100"),e},Fe=()=>{const t=document.createElementNS(Le,"svg");return t.innerHTML=`\n\t<g>\n\t\t<path\n\t\t\td='M5,10 L50,90 L95,10 Z'\n\t\t\t${De}\n\t\t/>\n\t</g>\n\t`,t.setAttribute("viewBox","0 0 100 100"),t},Ue=()=>{const t=document.createElementNS(Le,"svg");return t.innerHTML=`\n\t<g>\n\t\t<rect x=10 y=50 width=80 height=30 rx=10 fill='pink' />\n\t\t<rect\n\t\t\tx=10 y=10 width=80 height=50\n\t\t\t${De}\n\t\t/>\n\t</g>\n\t`,t.setAttribute("viewBox","0 0 100 100"),t},je=()=>{const t=document.createElementNS(Le,"svg");return t.innerHTML="\n\t<g>\n\t\t<rect x=10 y=10 width=70 height=70 fill='pink' stroke='black'/>\n\t\t<rect x=75 y=75 width=10 height=10 fill='white' stroke='black'/>\n\t</g>\n\t",t.setAttribute("viewBox","0 0 100 100"),t},Ve=(t,e="var(--icon-color)",n="none",r="0px")=>{const i=document.createElementNS(Le,"svg"),o=document.createElementNS(Le,"path");return o.setAttribute("d",t),o.style.fill=e,o.style.stroke=n,o.style.strokeWidth=r,i.appendChild(o),i.setAttribute("viewBox","0 0 100 100"),i},We=()=>Ve("\n\t\tm 10,60\n\t\t\t5,30\n\t\tH 90\n\t\tV 30\n\t\tC 90,20 75,20 75,30\n\t\tV 60\n\t\t\t20\n\t\tC 75,10 60,10 60,20\n\t\tV 60\n\t\t\t15\n\t\tC 60,5 45,5 45,15\n\t\tV 60\n\t\t\t25\n\t\tC 45,15 30,15 30,25\n\t\tV 60\n\t\t\t75\n\t\tL 25,60\n\t\tC 20,45 10,50 10,60\n\t\tZ\n\t","none","var(--icon-color)","3"),He=()=>Ve("\n\t\tM 5,5.5\n\t\tV 17.2\n\t\tL 16.25,5.46\n\t\tZ\n\n\t\tm 33.75,0\n\t\tL 50,17\n\t\tV 5.5\n\t\tZ\n\n\t\tM 5,40.7\n\t\tv 11.7\n\t\th 11.25\n\t\tz\n\n\t\tM 26,19\n\t\tC 19.8,19.4 17.65,30.4 21.9,34.8\n\t\tL 50,70\n\t\tH 27.5\n\t\tc -11.25,0 -11.25,17.6 0,17.6\n\t\tH 61.25\n\t\tC 94.9,87.8 95,87.6 95,40.7 78.125,23 67,29 55.6,46.5\n\t\tL 33.1,23\n\t\tC 30.3125,20.128192 27.9,19 25.830078,19.119756\n\t\tZ\n\t","none","var(--icon-color)","3"),Ge=()=>Ve("\n\t\tM 5 5\n\t\tL 5 17.5\n\t\t\t17.5 5\n\t\t\t5 5\n\t\tz\n\n\t\tM 42.5 5\n\t\tL 55 17.5\n\t\t\t55 5\n\t\t\t42.5 5\n\t\tz\n\n\t\tM 70 10\n\t\tL 70 21\n\t\t\t61 15\n\t\t\t55.5 23\n\t\t\t66 30\n\t\t\t56 37\n\t\t\t61 45\n\t\t\t70 39\n\t\t\t70 50\n\t\t\t80 50\n\t\t\t80 39\n\t\t\t89 45\n\t\t\t95 36\n\t\t\t84 30\n\t\t\t95 23\n\t\t\t89 15\n\t\t\t80 21\n\t\t\t80 10\n\t\t\t70 10\n\t\tz\n\n\t\tM 27.5 26.25\n\t\tL 27.5 91.25\n\t\tL 43.75 83.125\n\t\tL 52 99\n\t\tL 68 91\n\t\tL 60 75\n\t\tL 76.25 66.875\n\t\tL 27.5 26.25\n\t\tz\n\n\t\tM 5 42.5\n\t\tL 5 55\n\t\tL 17.5 55\n\t\tL 5 42.5\n\t\tz\n\t","none","var(--icon-color)","3"),_e=()=>{const t=document.createElementNS(Le,"svg");t.setAttribute("viewBox","0 0 100 100");const e=(e,n,r)=>{const i=document.createElementNS(Le,"text");i.appendChild(document.createTextNode(e)),i.setAttribute("x",n.toString()),i.setAttribute("y",r.toString()),i.style.textAlign="center",i.style.textAnchor="middle",i.style.fontSize="55px",i.style.fill="var(--icon-color)",i.style.fontFamily="monospace",t.appendChild(i)};return e("+",40,45),e("-",70,75),t},qe=t=>{var e,n;const r=document.createElementNS(Le,"svg");r.setAttribute("viewBox","0 0 100 100");const i=document.createElementNS(Le,"text");return i.appendChild(document.createTextNode("T")),i.style.fontFamily=t.fontFamily,i.style.fontWeight=null!==(e=t.fontWeight)&&void 0!==e?e:"",i.style.fontVariant=null!==(n=t.fontVariant)&&void 0!==n?n:"",i.style.fill=t.renderingStyle.fill.toHexString(),i.style.textAnchor="middle",i.setAttribute("x","50"),i.setAttribute("y","75"),i.style.fontSize="65px",i.style.filter="drop-shadow(0px 0px 10px var(--primary-shadow-color))",r.appendChild(i),r},Ze=(t,e)=>{e instanceof Et&&(e=e.toHexString());const n=document.createElementNS(Le,"svg");n.setAttribute("viewBox","0 0 100 100");const r=t/2,i=`M14,63 L${50-r},95 L${50+r},90 L88,60 Z`,o=`M14,63 L${50-r},85 L${50+r},83 L88,60 Z`;return n.innerHTML=`\n\t<defs>\n\t\t${Me}\n\t</defs>\n\t<g>\n\t\t\x3c!-- Pen grip --\x3e\n\t\t<path\n\t\t\td='M10,10 L90,10 L90,60 L${50+r},80 L${50-r},80 L10,60 Z'\n\t\t\t\n\tstyle='fill: var(--icon-color); stroke: var(--icon-color);'\n\n\t\t/>\n\t</g>\n\t<g>\n\t\t\x3c!-- Checkerboard background for slightly transparent pens --\x3e\n\t\t<path d='${o}' fill='url(#checkerboard)'/>\n\n\t\t\x3c!-- Actual pen tip --\x3e\n\t\t<path\n\t\t\td='${i}'\n\t\t\tfill='${e}'\n\t\t\tstroke='${e}'\n\t\t/>\n\t</g>\n\t`,n},Ke=(t,e)=>{const n=t.getThickness(),r=(new Date).getTime(),i={pos:S.of(10,10),width:n/5,color:t.getColor(),time:r-100},o={pos:S.of(90,90),width:n/5,color:t.getColor(),time:r},s=new H(new ze),a=e(i,s);a.addPoint(o);const l=document.createElementNS(Le,"svg");l.setAttribute("viewBox","0 0 100 100"),s.updateScreenSize(S.of(100,100));const c=new Qt(l,s);return a.preview(c),l},Xe=t=>{const e=document.createElementNS(Le,"svg"),n=document.createElementNS(Le,"path");if(n.setAttribute("d","\n\t\tM 47,6\n\t\tC 35,5 25,15 35,30\n\t\tc -9.2,1.3 -15,0 -15,3\n\t\t\t0,2 5,5 15,7\n\t\tV 81\n\t\tL 40,90\n\t\th 6\n\t\tL 40,80\n\t\tV 40\n\t\th 15\n\t\tv 40\n\t\tl -6,10\n\t\th 6\n\t\tl 5,-9.2\n\t\tV 40\n\t\tC 70,38 75,35 75,33\n\t\t\t75,30 69.2,31.2 60,30\n\t\t\t65,15 65,5 47,6\n\t\tZ\n\t"),n.style.fill="var(--icon-color)",t){const n=document.createElementNS(Le,"defs");n.innerHTML=Me,e.appendChild(n);const r=document.createElementNS(Le,"path"),i=document.createElementNS(Le,"path"),o="\n\t\t\tm 40,50 c 5,5 10,0 15,-5 V 80 L 50,90 H 45 L 40,80 Z\n\t\t";i.setAttribute("d",o),r.setAttribute("d",o),i.style.fill=t.toHexString(),r.style.fill=Oe,e.appendChild(r),e.appendChild(i)}return e.appendChild(n),e.setAttribute("viewBox","0 0 100 100"),e},Je=()=>Ve("\n\t\tM 75 5 75 10 90 10 90 25 95 25 95 5 75 5 z\n\t\tM 15 15 15 30 20 30 20 20 30 20 30 15 15 15 z\n M 84 15 82 17 81 16 81 20 85 20 84 19 86 17 84 15 z\n M 26 24 24 26 26 28 25 29 29 29 29 25 28 26 26 24 z\n M 25 71 26 72 24 74 26 76 28 74 29 75 29 71 25 71 z\n M 15 75 15 85 25 85 25 80 20 80 20 75 15 75 z\n M 90 75 90 90 75 90 75 95 95 95 95 75 90 75 z\n M 81 81 81 85 82 84 84 86 86 84 84 82 85 81 81 81 z\n\t"),Ye=()=>Ve("\n\t\tM 45,10 45,55 90,55 90,10 45,10 z\n\t\tM 10,25 10,90 70,90 70,60 40,60 40,25 10,25 z \n\t"),Qe=()=>Ve("\n\t\tM 10,10 90,90\n\t\tM 10,90 90,10\n\t","none","var(--icon-color)","5px"),tn=(t,e)=>new en(t);class en{constructor(t){this.startPoint=t,this.endPoint=t}getLineWidth(){return Math.max(this.endPoint.width,this.startPoint.width)}getBBox(){return this.buildPreview().getBBox()}buildPreview(){const t=this.startPoint.pos,e=this.endPoint.pos,n=e.minus(t).normalized(),r=e.minus(t).length(),i=Math.min(this.getLineWidth(),r/2),o=this.startPoint.width/2,s=this.endPoint.width/2,a=e.minus(n.times(i)),l=n.orthog(),c=l.times(o),h=l.times(s);return new Bt([{startPoint:a.minus(h),commands:[{kind:St.LineTo,point:t.minus(c)},{kind:St.LineTo,point:t.plus(c)},{kind:St.LineTo,point:a.plus(h)},{kind:St.LineTo,point:a.plus(l.times(i).plus(h))},{kind:St.LineTo,point:e.plus(n.times(s))},{kind:St.LineTo,point:a.plus(l.times(-i).minus(h))},{kind:St.LineTo,point:a.minus(h)}],style:{fill:this.startPoint.color}}])}build(){return this.buildPreview()}preview(t){this.buildPreview().render(t)}addPoint(t){this.endPoint=t}}const nn=(t,e)=>new rn(t);class rn{constructor(t){this.startPoint=t,this.endPoint=t}getBBox(){return this.buildPreview().getBBox()}buildPreview(){const t=this.startPoint.pos,e=this.endPoint.pos,n=e.minus(t).normalized(),r=this.startPoint.width/2,i=this.endPoint.width/2,o=n.orthog(),s=o.times(r),a=o.times(i);return new Bt([{startPoint:t.minus(s),commands:[{kind:St.LineTo,point:t.plus(s)},{kind:St.LineTo,point:e.plus(a)},{kind:St.LineTo,point:e.minus(a)}],style:{fill:this.startPoint.color}}])}build(){return this.buildPreview()}preview(t){this.buildPreview().render(t)}addPoint(t){this.endPoint=t}}const on=(t,e)=>new an(t,!0,e),sn=(t,e)=>new an(t,!1,e);class an{constructor(t,e,n){this.startPoint=t,this.filled=e,this.viewport=n,this.endPoint=t}getBBox(){return this.buildPreview().getBBox()}buildPreview(){const t=this.viewport.getRotationAngle(),e=P.zRotation(-t),n=e.inverse().transformVec2(this.startPoint.pos),r=e.inverse().transformVec2(this.endPoint.pos),i=B.fromCorners(n,r),o=kt.fromRect(i,this.filled?null:this.endPoint.width).transformedBy(e);return new Bt([o.toRenderable({fill:this.endPoint.color})])}build(){return this.buildPreview()}preview(t){this.buildPreview().render(t)}addPoint(t){this.endPoint=t}}const ln=(t,e)=>{const n=document.createElement("span"),r=document.createElement("input");let i;r.type="button",r.classList.add("coloris_input"),n.classList.add("color-input-container"),n.appendChild(r),cn(t,n,(t=>{r.value=t.toHexString(),s();const e=r.parentElement;e&&e.classList.contains("clr-field")&&(e.style.color=r.value)}));const o=()=>{i=Et.fromHex(r.value)},s=()=>{o(),i&&(t.announceForAccessibility(t.localization.colorChangedAnnouncement(i.toHexString())),e(i),t.notifier.dispatch(M.ColorPickerColorSelected,{kind:M.ColorPickerColorSelected,color:i}))};return r.oninput=o,r.addEventListener("open",(()=>{t.notifier.dispatch(M.ColorPickerToggled,{kind:M.ColorPickerToggled,open:!0})})),r.addEventListener("close",(()=>{t.notifier.dispatch(M.ColorPickerToggled,{kind:M.ColorPickerToggled,open:!1}),s()})),[r,n]},cn=(t,e,n)=>{const r=document.createElement("button");r.classList.add("pipetteButton"),r.title=t.localization.pickColorFromScreen,r.setAttribute("alt",r.title);const i=t=>{r.replaceChildren(Xe(t))};i();const o=t.toolController.getMatchingTools(fe)[0],s=()=>{null==o||o.clearColorListener(),i(),r.classList.remove("active")},a=t=>{s(),t&&n(t)},l=t=>{t?i(t):i()};r.onclick=()=>{r.classList.contains("active")?s():(null==o||o.setColorListener(l,a),o&&(r.classList.add("active"),t.announceForAccessibility(t.localization.clickToPickColorAnnouncement)))},e.appendChild(r)},hn=ln;var dn,un=function(t,e,n,r,i){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?i.call(t,n):i?i.value=n:e.set(t,n),n},pn=function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)};class mn{constructor(t,e){this.editor=t,this.localizationTable=e,dn.set(this,void 0),this.disabled=!1,this.subWidgets=[],this.toplevel=!0,this.icon=null,this.container=document.createElement("div"),this.container.classList.add(`${Sn}toolContainer`),this.dropdownContainer=document.createElement("div"),this.dropdownContainer.classList.add(`${Sn}dropdown`),this.dropdownContainer.classList.add("hidden"),un(this,dn,!1,"f"),this.button=document.createElement("div"),this.button.classList.add(`${Sn}button`),this.label=document.createElement("label"),this.button.setAttribute("role","button"),this.button.tabIndex=0}fillDropdown(t){if(0===this.subWidgets.length)return!1;for(const e of this.subWidgets)e.addTo(t),e.setIsToplevel(!1);return!0}setupActionBtnClickListener(t){const e={Enter:!0," ":!0};t.onkeydown=t=>{let n=!1;t.key in e&&(this.disabled||(this.handleClick(),n=!0)),n||this.editor.toolController.dispatchInputEvent({kind:D.KeyPressEvent,key:t.key,ctrlKey:t.ctrlKey})},t.onkeyup=t=>{t.key in e||this.editor.toolController.dispatchInputEvent({kind:D.KeyUpEvent,key:t.key,ctrlKey:t.ctrlKey})},t.onclick=()=>{this.disabled||this.handleClick()}}get hasDropdown(){return pn(this,dn,"f")}addSubWidget(t){this.subWidgets.push(t)}addTo(t){this.label.innerText=this.getTitle(),this.setupActionBtnClickListener(this.button),this.icon=null,this.updateIcon(),this.button.replaceChildren(this.icon,this.label),this.container.appendChild(this.button),un(this,dn,this.fillDropdown(this.dropdownContainer),"f"),pn(this,dn,"f")&&(this.dropdownIcon=this.createDropdownIcon(),this.button.appendChild(this.dropdownIcon),this.container.appendChild(this.dropdownContainer),this.editor.notifier.on(M.ToolbarDropdownShown,(t=>{t.kind===M.ToolbarDropdownShown&&t.parentWidget!==this&&t.parentWidget.toplevel&&this.setDropdownVisible(!1)}))),this.setDropdownVisible(!1),t.appendChild(this.container)}updateIcon(){var t;const e=this.createIcon();null===(t=this.icon)||void 0===t||t.replaceWith(e),this.icon=e,this.icon.classList.add(`${Sn}icon`)}setDisabled(t){this.disabled=t,this.disabled?(this.button.classList.add("disabled"),this.button.setAttribute("aria-disabled","true")):(this.button.classList.remove("disabled"),this.button.removeAttribute("aria-disabled"))}setSelected(t){this.isSelected()!==t&&(t?(this.container.classList.add("selected"),this.button.ariaSelected="true"):(this.container.classList.remove("selected"),this.button.ariaSelected="false"))}setDropdownVisible(t){this.container.classList.contains("dropdownVisible")!==t&&(t?(this.dropdownContainer.classList.remove("hidden"),this.container.classList.add("dropdownVisible"),this.editor.announceForAccessibility(this.localizationTable.dropdownShown(this.getTitle())),this.editor.notifier.dispatch(M.ToolbarDropdownShown,{kind:M.ToolbarDropdownShown,parentWidget:this})):(this.dropdownContainer.classList.add("hidden"),this.container.classList.remove("dropdownVisible"),this.editor.announceForAccessibility(this.localizationTable.dropdownHidden(this.getTitle()))),this.repositionDropdown())}repositionDropdown(){const t=this.dropdownContainer.getBoundingClientRect(),e=document.body.clientWidth;t.left>e/2?(this.dropdownContainer.style.marginLeft=this.button.clientWidth+"px",this.dropdownContainer.style.transform="translate(-100%, 0)"):(this.dropdownContainer.style.marginLeft="",this.dropdownContainer.style.transform="")}setIsToplevel(t){this.toplevel=t}isDropdownVisible(){return!this.dropdownContainer.classList.contains("hidden")}isSelected(){return this.container.classList.contains("selected")}createDropdownIcon(){const t=Fe();return t.classList.add(`${Sn}showHideDropdownIcon`),t}}dn=new WeakMap;class gn extends mn{constructor(t,e,n){super(t,n),this.editor=t,this.targetTool=e,this.localizationTable=n,t.notifier.on(M.ToolEnabled,(t=>{if(t.kind!==M.ToolEnabled)throw new Error("Incorrect event type! (Expected ToolEnabled)");t.tool===e&&this.setSelected(!0)})),t.notifier.on(M.ToolDisabled,(t=>{if(t.kind!==M.ToolDisabled)throw new Error("Incorrect event type! (Expected ToolDisabled)");t.tool===e&&(this.setSelected(!1),this.setDropdownVisible(!1))}))}handleClick(){this.hasDropdown?this.targetTool.isEnabled()?this.setDropdownVisible(!this.isDropdownVisible()):this.targetTool.setEnabled(!0):this.targetTool.setEnabled(!this.targetTool.isEnabled())}addTo(t){super.addTo(t),this.setSelected(this.targetTool.isEnabled())}}class fn extends gn{constructor(t,e,n){super(t,e,n),this.tool=e,this.updateInputs=()=>{},this.penTypes=[{name:n.freehandPen,factory:At},{name:n.arrowPen,factory:tn},{name:n.linePen,factory:nn},{name:n.filledRectanglePen,factory:on},{name:n.outlinedRectanglePen,factory:sn}],this.editor.notifier.on(M.ToolUpdated,(t=>{if(t.kind!==M.ToolUpdated)throw new Error("Invalid event type!");t.tool===this.tool&&(this.updateIcon(),this.updateInputs())}))}getTitle(){return this.targetTool.description}createIcon(){if(this.tool.getStrokeFactory()===At){const t=Math.round(4*Math.sqrt(this.tool.getThickness())),e=this.tool.getColor();return Ze(t,e.toHexString())}{const t=this.tool.getStrokeFactory();return Ke(this.tool,t)}}fillDropdown(t){const e=document.createElement("div"),n=document.createElement("div"),r=document.createElement("div"),i=document.createElement("label"),o=document.createElement("input"),s=document.createElement("label"),a=document.createElement("select");o.id=`${Sn}thicknessInput${fn.idCounter++}`,a.id=`${Sn}builderSelect${fn.idCounter++}`,i.innerText=this.localizationTable.thicknessLabel,i.setAttribute("for",o.id),s.innerText=this.localizationTable.selectObjectType,s.setAttribute("for",a.id),o.type="range",o.min="2",o.max="20",o.step="1",o.oninput=()=>{this.tool.setThickness(Math.pow(parseFloat(o.value),2))},n.appendChild(i),n.appendChild(o),a.oninput=()=>{const t=parseInt(a.value);t<0||t>=this.penTypes.length?console.error("Invalid pen type index",t):this.tool.setStrokeFactory(this.penTypes[t].factory)},r.appendChild(s),r.appendChild(a);const l=document.createElement("div"),c=document.createElement("label"),[h,d]=hn(this.editor,(t=>{this.tool.setColor(t)}));return h.id=`${Sn}colorInput${fn.idCounter++}`,c.innerText=this.localizationTable.colorLabel,c.setAttribute("for",h.id),l.appendChild(c),l.appendChild(d),this.updateInputs=()=>{h.value=this.tool.getColor().toHexString(),o.value=Math.sqrt(this.tool.getThickness()).toString(),a.replaceChildren();for(let t=0;t<this.penTypes.length;t++){const e=this.penTypes[t],n=document.createElement("option");n.value=t.toString(),n.innerText=e.name,a.appendChild(n),e.factory===this.tool.getStrokeFactory()&&(a.value=t.toString())}},this.updateInputs(),e.replaceChildren(l,n,r),t.replaceChildren(e),!0}}fn.idCounter=0;class vn extends gn{getTitle(){return this.localizationTable.eraser}createIcon(){return Ue()}fillDropdown(t){return!1}}class yn extends mn{constructor(t,e,n,r,i){super(t,e),this.makeIcon=n,this.title=r,this.clickAction=i}handleClick(){this.clickAction()}getTitle(){return this.title}createIcon(){return this.makeIcon()}fillDropdown(t){return!1}}class xn extends gn{constructor(t,e,n){super(t,e,n),this.tool=e;const r=new yn(t,n,Je,this.localizationTable.resizeImageToSelection,(()=>{const t=this.tool.getSelection();this.editor.dispatch(this.editor.setImportExportRect(t.region))})),i=new yn(t,n,Qe,this.localizationTable.deleteSelection,(()=>{const t=this.tool.getSelection();this.editor.dispatch(t.deleteSelectedObjects()),this.tool.clearSelection()})),o=new yn(t,n,Ye,this.localizationTable.duplicateSelection,(()=>{const t=this.tool.getSelection();this.editor.dispatch(t.duplicateSelectedObjects())}));this.addSubWidget(r),this.addSubWidget(i),this.addSubWidget(o);const s=t=>{r.setDisabled(t),i.setDisabled(t),o.setDisabled(t)};s(!0),this.editor.notifier.on(M.ToolUpdated,(t=>{if(t.kind!==M.ToolUpdated)throw new Error("Invalid event type!");if(t.tool===this.tool){const t=this.tool.getSelection(),e=t&&t.region.area>0;s(!e)}}))}getTitle(){return this.localizationTable.select}createIcon(){return je()}}class bn extends gn{constructor(t,e,n){super(t,e,n),this.tool=e,this.updateDropdownInputs=null,t.notifier.on(M.ToolUpdated,(t=>{var n;t.kind===M.ToolUpdated&&t.tool===e&&(this.updateIcon(),null===(n=this.updateDropdownInputs)||void 0===n||n.call(this))}))}getTitle(){return this.targetTool.description}createIcon(){const t=this.tool.getTextStyle();return qe(t)}fillDropdown(t){const e=document.createElement("div"),n=document.createElement("div"),r=document.createElement("select"),i=document.createElement("label"),[o,s]=hn(this.editor,(t=>{this.tool.setColor(t)})),a=document.createElement("label"),l=new Set,c=t=>{const e=document.createElement("option");e.value=t,e.textContent=t,r.appendChild(e),l.add(t)};return i.innerText=this.localizationTable.fontLabel,a.innerText=this.localizationTable.colorLabel,o.id=`${Sn}-text-color-input-${bn.idCounter++}`,a.setAttribute("for",o.id),c("monospace"),c("serif"),c("sans-serif"),r.id=`${Sn}-text-font-input-${bn.idCounter++}`,i.setAttribute("for",r.id),r.onchange=()=>{this.tool.setFontFamily(r.value)},n.appendChild(a),n.appendChild(s),e.appendChild(i),e.appendChild(r),this.updateDropdownInputs=()=>{const t=this.tool.getTextStyle();o.value=t.renderingStyle.fill.toHexString(),l.has(t.fontFamily)||c(t.fontFamily),r.value=t.fontFamily},this.updateDropdownInputs(),t.replaceChildren(n,e),!0}}bn.idCounter=0;class wn extends mn{constructor(t,e){super(t,e),this.container.classList.add("dropdownShowable")}getTitle(){return this.localizationTable.zoom}createIcon(){return _e()}handleClick(){this.setDropdownVisible(!this.isDropdownVisible())}fillDropdown(t){return t.appendChild(((t,e)=>{const n=document.createElement("div"),r=document.createElement("button"),i=document.createElement("button"),o=document.createElement("button"),s=document.createElement("span");let a;r.innerText="+",i.innerText="-",o.innerText=t.resetView,n.replaceChildren(s,r,i,o),n.classList.add(`${Sn}zoomLevelEditor`),s.classList.add("zoomDisplay");const l=()=>{let n=100*e.viewport.getScaleFactor();n=n>.1?Math.round(10*n)/10:Math.round(1e3*n)/1e3,n!==a&&(s.innerText=t.zoomLevel(n),a=n)};l(),e.notifier.on(M.ViewportChanged,(t=>{t.kind===M.ViewportChanged&&(l(),o.disabled=t.newTransform.eq(P.identity))}));const c=t=>{const n=e.viewport.visibleRect.center,r=P.scaling2D(t,n);e.dispatch(H.transformBy(r),!1)};return r.onclick=()=>{c(5/4)},i.onclick=()=>{c(.8)},o.onclick=()=>{e.dispatch(H.transformBy(e.viewport.canvasToScreenTransform.inverse()),!0)},n})(this.localizationTable,this.editor)),!0}}class Tn extends mn{constructor(t,e,n,r,i,o){super(t,e),this.tool=n,this.flag=r,this.makeIcon=i,this.title=o,t.notifier.on(M.ToolUpdated,(t=>{if(t.kind===M.ToolUpdated&&t.tool===n){const t=!!(n.getMode()&_.SinglePointerGestures);this.setSelected(!!(n.getMode()&r)||t),this.setDisabled(t&&r!==_.SinglePointerGestures)}})),this.setSelected(!1)}setModeFlag(t){const e=this.tool.getMode();t?this.tool.setMode(e|this.flag):this.tool.setMode(e&~this.flag)}handleClick(){this.setModeFlag(!this.isSelected())}getTitle(){return this.title}createIcon(){return this.makeIcon()}fillDropdown(t){return!1}}class Cn extends gn{constructor(t,e,n){super(t,e,n),this.tool=e,this.container.classList.add("dropdownShowable"),this.touchPanningWidget=new Tn(t,n,e,_.OneFingerTouchGestures,He,n.touchPanning),this.addSubWidget(this.touchPanningWidget),this.addSubWidget(new Tn(t,n,e,_.SinglePointerGestures,Ge,n.anyDevicePanning)),this.addSubWidget(new wn(t,n))}getTitle(){return this.localizationTable.handTool}createIcon(){return We()}setSelected(t){}handleClick(){this.setDropdownVisible(!this.isDropdownVisible())}}const Sn="toolbar-";class kn{constructor(t,e,n=Ie){this.editor=t,this.localizationTable=n,this.updateColoris=null,this.container=document.createElement("div"),this.container.classList.add(`${Sn}root`),this.container.setAttribute("role","toolbar"),e.appendChild(this.container),kn.colorisStarted||(Ae(),kn.colorisStarted=!0),this.setupColorPickers()}setupColorPickers(){if(this.updateColoris)return void this.updateColoris();const t=document.createElement("div");t.className=`${Sn}closeColorPickerOverlay`,this.editor.createHTMLOverlay(t);const e=[Et.red.toHexString(),Et.purple.toHexString(),Et.blue.toHexString(),Et.clay.toHexString(),Et.black.toHexString(),Et.white.toHexString()],n=e.length,r=()=>{Be({el:".coloris_input",format:"hex",selectInput:!1,focusInput:!1,themeMode:"auto",swatches:e})};r(),this.updateColoris=r;this.editor.notifier.on(M.ColorPickerToggled,(e=>{e.kind===M.ColorPickerToggled&&(t.style.display=e.open?"block":"none")})),this.editor.notifier.on(M.ColorPickerColorSelected,(t=>{t.kind===M.ColorPickerColorSelected&&(t=>{let i=!1;for(const n of e)n===t&&(i=!0);i||(e.push(t),e.length>12&&e.splice(n,1),r())})(t.color.toHexString())}))}addWidget(t){t.addTo(this.container),this.setupColorPickers()}addActionButton(t,e,n){const r=document.createElement("button");if(r.classList.add(`${Sn}button`),"string"==typeof t)r.innerText=t;else{const e=t.icon.cloneNode(!0),n=document.createElement("label");e.setAttribute("alt",""),n.innerText=t.label,e.classList.add("toolbar-icon"),r.replaceChildren(e,n)}return r.onclick=e,(null!=n?n:this.container).appendChild(r),r}addUndoRedoButtons(){const t=document.createElement("div");t.classList.add(`${Sn}buttonGroup`);const e=this.addActionButton({label:this.localizationTable.undo,icon:$e()},(()=>{this.editor.history.undo()}),t),n=this.addActionButton({label:this.localizationTable.redo,icon:Ne()},(()=>{this.editor.history.redo()}),t);this.container.appendChild(t),e.disabled=!0,n.disabled=!0,this.editor.notifier.on(M.UndoRedoStackUpdated,(t=>{if(t.kind!==M.UndoRedoStackUpdated)throw new Error("Wrong event type!");e.disabled=0===t.undoStackSize,n.disabled=0===t.redoStackSize}))}addDefaultToolWidgets(){const t=this.editor.toolController;for(const e of t.getMatchingTools(Lt)){const t=new fn(this.editor,e,this.localizationTable);this.addWidget(t)}for(const e of t.getMatchingTools($t))this.addWidget(new vn(this.editor,e,this.localizationTable));for(const e of t.getMatchingTools(ue))this.addWidget(new xn(this.editor,e,this.localizationTable));for(const e of t.getMatchingTools(ge))this.addWidget(new bn(this.editor,e,this.localizationTable));const e=t.getMatchingTools(q)[0];e&&this.addWidget(new Cn(this.editor,e,this.localizationTable))}addDefaultActionButtons(){this.addUndoRedoButtons()}}kn.colorisStarted=!1;class En extends Jt{constructor(t,e){super(e),this.ctx=t,this.ignoreObjectsAboveLevel=null,this.ignoringObject=!1,this.clipLevels=[],this.setDraftMode(!1)}transformBy(t){this.ctx.transform(t.a1,t.b1,t.a2,t.b2,t.a3,t.b3)}canRenderFromWithoutDataLoss(t){return t instanceof En}renderFromOtherOfSameType(t,e){if(!(e instanceof En))throw new Error(`${e} cannot be rendered onto ${this}`);t=this.getCanvasToScreenTransform().rightMul(t),this.ctx.save(),this.transformBy(t),this.ctx.drawImage(e.ctx.canvas,0,0),this.ctx.restore()}setDraftMode(t){t?(this.minSquareCurveApproxDist=9,this.minRenderSizeBothDimens=2,this.minRenderSizeAnyDimen=.5):(this.minSquareCurveApproxDist=.5,this.minRenderSizeBothDimens=.3,this.minRenderSizeAnyDimen=1e-5)}displaySize(){return S.of(this.ctx.canvas.clientWidth,this.ctx.canvas.clientHeight)}clear(){this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height)}beginPath(t){t=this.canvasToScreen(t),this.ctx.beginPath(),this.ctx.moveTo(t.x,t.y)}endPath(t){this.ctx.fillStyle=t.fill.toHexString(),this.ctx.fill(),t.stroke&&(this.ctx.strokeStyle=t.stroke.color.toHexString(),this.ctx.lineWidth=this.getSizeOfCanvasPixelOnScreen()*t.stroke.width,this.ctx.stroke()),this.ctx.closePath()}lineTo(t){t=this.canvasToScreen(t),this.ctx.lineTo(t.x,t.y)}moveTo(t){t=this.canvasToScreen(t),this.ctx.moveTo(t.x,t.y)}traceCubicBezierCurve(t,e,n){t=this.canvasToScreen(t),e=this.canvasToScreen(e),n=this.canvasToScreen(n);const r=e.minus(t),i=n.minus(e);r.magnitudeSquared()<this.minSquareCurveApproxDist&&i.magnitudeSquared()<this.minSquareCurveApproxDist?this.ctx.lineTo(n.x,n.y):this.ctx.bezierCurveTo(t.x,t.y,e.x,e.y,n.x,n.y)}traceQuadraticBezierCurve(t,e){t=this.canvasToScreen(t),e=this.canvasToScreen(e);t.minus(e).magnitudeSquared()<this.minSquareCurveApproxDist?this.ctx.lineTo(e.x,e.y):this.ctx.quadraticCurveTo(t.x,t.y,e.x,e.y)}drawPath(t){this.ignoringObject||super.drawPath(t)}drawText(t,e,n){this.ctx.save(),e=this.getCanvasToScreenTransform().rightMul(e),this.transformBy(e),Wt.applyTextStyles(this.ctx,n),0!==n.renderingStyle.fill.a&&(this.ctx.fillStyle=n.renderingStyle.fill.toHexString(),this.ctx.fillText(t,0,0)),n.renderingStyle.stroke&&(this.ctx.strokeStyle=n.renderingStyle.stroke.color.toHexString(),this.ctx.lineWidth=n.renderingStyle.stroke.width,this.ctx.strokeText(t,0,0)),this.ctx.restore()}drawImage(t){this.ctx.save();const e=this.getCanvasToScreenTransform().rightMul(t.transform);this.transformBy(e),this.ctx.drawImage(t.image,0,0),this.ctx.restore()}startObject(t,e){if(this.isTooSmallToRender(t)&&(this.ignoreObjectsAboveLevel=this.getNestingLevel(),this.ignoringObject=!0),super.startObject(t),!this.ignoringObject&&e){this.clipLevels.push(this.objectLevel),this.ctx.save(),this.ctx.beginPath();for(const e of t.corners){const t=this.canvasToScreen(e);this.ctx.lineTo(t.x,t.y)}this.ctx.clip()}}endObject(){!this.ignoringObject&&this.clipLevels.length>0&&this.clipLevels[this.clipLevels.length-1]===this.objectLevel&&(this.ctx.restore(),this.clipLevels.pop()),super.endObject(),null!==this.ignoreObjectsAboveLevel&&this.getNestingLevel()<=this.ignoreObjectsAboveLevel&&(this.ignoreObjectsAboveLevel=null,this.ignoringObject=!1)}drawPoints(...t){for(let e=0;e<t.length;e++){const n=this.canvasToScreen(t[e]);this.ctx.beginPath(),this.ctx.arc(n.x,n.y,10,0,2*Math.PI),this.ctx.fillStyle=Et.ofRGBA(.5+Math.sin(e)/2,1,.5+Math.cos(.2*e)/4,.5).toHexString(),this.ctx.fill(),this.ctx.stroke(),this.ctx.closePath(),this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillStyle="black",this.ctx.fillText(`${e}`,n.x,n.y,20)}}isTooSmallToRender(t){const e=this.getCanvasToScreenTransform().transformVec3(t.size),n=this.minRenderSizeBothDimens,r=Math.abs(e.x)<n&&Math.abs(e.y)<n,i=this.minRenderSizeAnyDimen,o=Math.abs(e.x)<i||Math.abs(e.y)<i;return r||o}}class Pn extends Jt{constructor(t){super(t),this.clearedCount=0,this.renderedPathCount=0,this.lastFillStyle=null,this.lastPoint=null,this.objectNestingLevel=0,this.lastText=null,this.lastImage=null,this.pointBuffer=[]}displaySize(){const t=this.getViewport().getResolution();return 0===t.x||0===t.y?S.of(640,480):t}clear(){if(this.clearedCount++,this.renderedPathCount=0,this.pointBuffer=[],this.lastText=null,this.lastImage=null,this.objectNestingLevel>0)throw new Error(`Within an object while clearing! Nesting level: ${this.objectNestingLevel}`)}beginPath(t){this.lastPoint=t,this.pointBuffer.push(t)}endPath(t){this.renderedPathCount++,this.lastFillStyle=t}lineTo(t){t=this.canvasToScreen(t),this.lastPoint=t,this.pointBuffer.push(t)}moveTo(t){t=this.canvasToScreen(t),this.lastPoint=t,this.pointBuffer.push(t)}traceCubicBezierCurve(t,e,n){t=this.canvasToScreen(t),e=this.canvasToScreen(e),n=this.canvasToScreen(n),this.lastPoint=n,this.pointBuffer.push(t,e,n)}traceQuadraticBezierCurve(t,e){t=this.canvasToScreen(t),e=this.canvasToScreen(e),this.lastPoint=e,this.pointBuffer.push(t,e)}drawPoints(...t){}drawText(t,e,n){this.lastText=t}drawImage(t){this.lastImage=t}startObject(t,e){super.startObject(t),this.objectNestingLevel+=1}endObject(){super.endObject(),this.objectNestingLevel-=1}isTooSmallToRender(t){return!1}canRenderFromWithoutDataLoss(t){return t instanceof Pn}renderFromOtherOfSameType(t,e){if(!(e instanceof Pn))throw new Error(`${e} cannot be rendered onto ${this}`);this.renderedPathCount+=e.renderedPathCount,this.lastFillStyle=e.lastFillStyle,this.lastPoint=e.lastPoint,this.pointBuffer.push(...e.pointBuffer.map((e=>t.transformVec2(e))))}}const zn=!1;class Rn{constructor(t,e){this.region=t,this.cacheState=e,this.instantiatedChildren=[],this.parent=null,this.cachedRenderer=null,this.renderedIds=[],this.renderedMaxZIndex=null}generateParent(){if(this.parent)return this.parent;const t=B.fromCorners(this.region.topLeft.minus(this.region.size),this.region.bottomRight.plus(this.region.size)),e=new Rn(t,this.cacheState);e.generateChildren();const n=this.region.maxDimension/100,r=(e.instantiatedChildren.length-1)/2;if(!e.instantiatedChildren[r].region.eq(this.region,n))throw console.error(e.instantiatedChildren[r].region,"≠",this.region),new Error("Logic error: [this] is not contained within its parent's center child");return e.instantiatedChildren[r]=this,this.parent=e,e}generateChildren(){if(0===this.instantiatedChildren.length){const t=this.region.divideIntoGrid(3,3);if(0===this.region.size.x||0===this.region.size.y)return void console.warn("Cache element has zero size! Not generating children.");for(const e of t){const t=new Rn(e,this.cacheState);t.parent=this,this.instantiatedChildren.push(t)}}this.checkRep()}getChildren(){return this.checkRep(),this.generateChildren(),this.instantiatedChildren}smallestChildContaining(t){var e;const n=t.maxDimension>this.region.maxDimension/3;if(!this.region.containsRect(t)||n)return null;for(const n of this.getChildren())if(n.region.containsRect(t))return null!==(e=n.smallestChildContaining(t))&&void 0!==e?e:n;return null}renderingWouldBeHighEnoughResolution(t){const e=this.region.w/this.cacheState.props.blockResolution.x;return!(t.getScaleFactor()*e>this.cacheState.props.maxScale)}allChildrenCanRender(t,e){if(0===this.instantiatedChildren.length)return!1;for(const n of this.instantiatedChildren)if(n.region.intersects(t.visibleRect)&&!n.renderingIsUpToDate(this.idsOfIntersecting(e)))return!1;return!0}computeSortedByLeafIds(t){const e=t.slice();return e.sort(((t,e)=>t.getId()-e.getId())),e}idsOfIntersecting(t){const e=[];for(const n of t)n.getBBox().intersects(this.region)&&e.push(n.getId());return e}allRenderedIdsIn(t){if(this.renderedIds.length>t.length)return!1;for(let e=0;e<this.renderedIds.length;e++)if(t[e]!==this.renderedIds[e])return!1;return!0}renderingIsUpToDate(t){return null!==this.cachedRenderer&&t.length===this.renderedIds.length&&this.allRenderedIdsIn(t)}renderItems(t,e,n){var r,i;if(!n.visibleRect.intersects(this.region)||0===e.length)return;const o=[];for(const t of e){const e=t.getBBox();e.intersects(this.region)&&(e.maxDimension>=this.region.maxDimension?o.push(...t.getChildrenOrSelfIntersectingRegion(this.region)):o.push(t))}if(e=o,!this.cacheState.props.isOfCorrectType(t))return void e.forEach((e=>e.render(t,n.visibleRect)));if(this.renderingWouldBeHighEnoughResolution(n)){const o=t=>t.w/this.region.w<1/this.cacheState.props.blockResolution.x,s=[];for(const t of e)s.push(...t.getLeavesIntersectingRegion(this.region,o));A(s);const a=this.computeSortedByLeafIds(s);if(0===a.length)return;const l=a.map((t=>t.getId()));let c;if(this.renderingIsUpToDate(l))c=this.cachedRenderer.startRender();else{if(this.allChildrenCanRender(n,a)){for(const r of this.getChildren())r.renderItems(t,e,n);return}if(a.length>this.cacheState.props.minComponentsPerCache){let t=!0;if(this.cachedRenderer)if(a.length>this.renderedIds.length&&this.allRenderedIdsIn(l)&&null!==this.renderedMaxZIndex){const e=[];let n=null;for(let t=0;t<a.length;t++){const r=a[t],i=r.getContent().getZIndex();(t>=this.renderedIds.length||r.getId()!==this.renderedIds[t])&&(e.push(r),(null===n||i<n)&&(n=i))}if(null!==n&&n>this.renderedMaxZIndex){t=!1,c=this.cachedRenderer.startRender();for(let t=0;t<s.length;t++){const e=s[t],n=e.getContent().getZIndex();n>this.renderedMaxZIndex&&(e.render(c,this.region),this.renderedMaxZIndex=n)}zn}}else zn;else this.cachedRenderer=this.cacheState.recordManager.allocCanvas(this.region,(()=>this.onRegionDealloc()));if(t){c=this.cachedRenderer.startRender(),c.clear(),this.renderedMaxZIndex=null;for(const t of s){const e=t.getContent();null!==(r=this.renderedMaxZIndex)&&void 0!==r||(this.renderedMaxZIndex=e.getZIndex()),this.renderedMaxZIndex=Math.max(this.renderedMaxZIndex,e.getZIndex()),t.render(c,this.region)}zn}this.renderedIds=l}else{null===(i=this.cachedRenderer)||void 0===i||i.dealloc();const e=n.getSizeOfPixelOnCanvas(),r=new B(this.region.x,this.region.y,this.region.w+e,this.region.h+e),o=!0;t.startObject(r,o);for(const e of s)e.render(t,this.region.intersection(n.visibleRect));t.endObject()}}if(c){const e=this.cachedRenderer.getTransform(this.region).inverse();t.renderFromOtherOfSameType(e,c)}this.instantiatedChildren.every((t=>t.isEmpty()))&&(this.instantiatedChildren=[])}else for(const r of this.getChildren())r.renderItems(t,e.filter((t=>t.getBBox().intersects(r.region))),n);this.checkRep()}isEmpty(){return null===this.cachedRenderer&&this.instantiatedChildren.every((t=>t.isEmpty()))}onRegionDealloc(){this.cachedRenderer=null,this.isEmpty()&&(this.instantiatedChildren=[])}checkRep(){if(9!==this.instantiatedChildren.length&&0!==this.instantiatedChildren.length)throw new Error(`Repcheck: Wrong number of children. Got ${this.instantiatedChildren.length}`);if(void 0!==this.renderedIds[1]&&this.renderedIds[0]>=this.renderedIds[1])throw console.error(this.renderedIds),new Error("Repcheck: First two ids are not in ascending order!");for(const t of this.instantiatedChildren)if(t.parent!==this)throw new Error("Children should be linked to their parents!");if(this.cachedRenderer&&!this.cachedRenderer.isAllocd())throw new Error("this' cachedRenderer != null, but is dealloc'd")}}class Bn{constructor(t,e){this.onBeforeDeallocCallback=t,this.cacheState=e,this.allocd=!1,this.allocCount=0,this.renderer=e.props.createRenderer(),this.lastUsedCycle=-1,this.allocd=!0}startRender(){if(this.lastUsedCycle=this.cacheState.currentRenderingCycle,!this.allocd)throw new Error("Only alloc'd canvases can be rendered to");return this.renderer}dealloc(){var t;null===(t=this.onBeforeDeallocCallback)||void 0===t||t.call(this),this.allocd=!1,this.onBeforeDeallocCallback=null,this.lastUsedCycle=0}isAllocd(){return this.allocd}realloc(t){this.allocd&&this.dealloc(),this.allocd=!0,this.onBeforeDeallocCallback=t,this.lastUsedCycle=this.cacheState.currentRenderingCycle,this.allocCount++}getLastUsedCycle(){return this.lastUsedCycle}getTransform(t){return P.scaling2D(this.cacheState.props.blockResolution.x/t.size.x).rightMul(P.translation(t.topLeft.times(-1)))}setRenderingRegion(t){this.renderer.setTransform(this.getTransform(t))}}class An{constructor(t){this.cacheRecords=[],this.maxCanvases=Math.ceil(t.cacheSize/4/t.blockResolution.x/t.blockResolution.y)}setSharedState(t){this.cacheState=t}allocCanvas(t,e){if(this.cacheRecords.length<this.maxCanvases){const n=new Bn(e,this.cacheState);return n.setRenderingRegion(t),this.cacheRecords.push(n),n}{const n=this.getLeastRecentlyUsedRecord();return n.realloc(e),n.setRenderingRegion(t),n}}getLeastRecentlyUsedRecord(){return this.cacheRecords.sort(((t,e)=>t.getLastUsedCycle()-e.getLastUsedCycle())),this.cacheRecords[0]}}class In{constructor(t){this.recordManager=new An(t),this.sharedState={props:t,currentRenderingCycle:0,recordManager:this.recordManager},this.recordManager.setSharedState(this.sharedState)}render(t,e,n){var r;const i=n.visibleRect;if(this.sharedState.currentRenderingCycle++,!this.sharedState.props.isOfCorrectType(t))return void e.render(t,i);if(!this.rootNode){const t=this.sharedState.props.blockResolution,e=i.topLeft;this.rootNode=new Rn(new B(e.x,e.y,t.x,t.y),this.sharedState)}for(;!this.rootNode.region.containsRect(i);)this.rootNode=this.rootNode.generateParent();this.rootNode=null!==(r=this.rootNode.smallestChildContaining(i))&&void 0!==r?r:this.rootNode;e.getLeavesIntersectingRegion(n.visibleRect,(e=>t.isTooSmallToRender(e))).length>this.sharedState.props.minComponentsToUseCache?this.rootNode.renderItems(t,[e],n):e.render(t,i)}}class Ln extends Jt{constructor(t,e){super(t),this.localizationTable=e,this.descriptionBuilder=[],this.pathCount=0,this.textNodeCount=0,this.imageNodeCount=0}displaySize(){return S.of(500,500)}clear(){this.descriptionBuilder=[],this.pathCount=0,this.textNodeCount=0}getDescription(){return[this.localizationTable.pathNodeCount(this.pathCount),...this.textNodeCount>0?this.localizationTable.textNodeCount(this.textNodeCount):[],...this.imageNodeCount>0?this.localizationTable.imageNodeCount(this.imageNodeCount):[],...this.descriptionBuilder].join("\n")}beginPath(t){}endPath(t){this.pathCount++}lineTo(t){}moveTo(t){}traceCubicBezierCurve(t,e,n){}traceQuadraticBezierCurve(t,e){}drawText(t,e,n){this.descriptionBuilder.push(this.localizationTable.textNode(t)),this.textNodeCount++}drawImage(t){const e=t.label?this.localizationTable.imageNode(t.label):this.localizationTable.unlabeledImageNode;this.descriptionBuilder.push(e),this.imageNodeCount++}isTooSmallToRender(t){return t.maxDimension<15/this.getSizeOfCanvasPixelOnScreen()}drawPoints(...t){}}var Dn;!function(t){t[t.DummyRenderer=0]="DummyRenderer",t[t.CanvasRenderer=1]="CanvasRenderer"}(Dn||(Dn={}));class Mn{constructor(t,e,n){if(this.editor=t,this.parent=n,this.textRerenderOutput=null,this.getColorAt=t=>null,e===Dn.CanvasRenderer)this.initializeCanvasRendering();else{if(e!==Dn.DummyRenderer)throw new Error(`Unknown rendering mode, ${e}!`);this.dryInkRenderer=new Pn(t.viewport),this.wetInkRenderer=new Pn(t.viewport)}this.textRenderer=new Ln(t.viewport,t.localization),this.initializeTextRendering();const r=S.of(600,600);this.cache=new In({createRenderer:()=>{if(e===Dn.DummyRenderer)return new Pn(t.viewport);if(e!==Dn.CanvasRenderer)throw new Error("Unspported rendering mode");const n=document.createElement("canvas");n.width=r.x+1,n.height=r.y+1;const i=n.getContext("2d");return new En(i,t.viewport)},isOfCorrectType:t=>this.dryInkRenderer.canRenderFromWithoutDataLoss(t),blockResolution:r,cacheSize:1296e5,maxScale:1.4,minComponentsPerCache:20,minComponentsToUseCache:105}),this.editor.notifier.on(M.DisplayResized,(t=>{var e;if(t.kind!==M.DisplayResized)throw new Error("Mismatched event.kinds!");null===(e=this.resizeSurfacesCallback)||void 0===e||e.call(this)}))}get width(){return this.dryInkRenderer.displaySize().x}get height(){return this.dryInkRenderer.displaySize().y}getCache(){return this.cache}initializeCanvasRendering(){const t=document.createElement("canvas"),e=document.createElement("canvas"),n=t.getContext("2d"),r=e.getContext("2d");this.dryInkRenderer=new En(n,this.editor.viewport),this.wetInkRenderer=new En(r,this.editor.viewport),t.className="dryInkCanvas",e.className="wetInkCanvas",this.parent&&(this.parent.appendChild(t),this.parent.appendChild(e)),this.resizeSurfacesCallback=()=>{const n=t=>t.clientHeight!==t.height||t.clientWidth!==t.width;(n(t)||n(e))&&(t.width=t.clientWidth,t.height=t.clientHeight,e.width=e.clientWidth,e.height=e.clientHeight,this.editor.notifier.dispatch(M.DisplayResized,{kind:M.DisplayResized,newSize:S.of(this.width,this.height)}))},this.resizeSurfacesCallback(),this.flattenCallback=()=>{n.drawImage(e,0,0)},this.getColorAt=t=>{const e=n.getImageData(t.x,t.y,1,1),r=null==e?void 0:e.data;if(r){return Et.ofRGBA(r[0]/255,r[1]/255,r[2]/255,r[3]/255)}return null}}initializeTextRendering(){const t=document.createElement("div");t.classList.add("textRendererOutputContainer");const e=document.createElement("button");e.classList.add("rerenderButton"),e.innerText=this.editor.localization.rerenderAsText,this.textRerenderOutput=document.createElement("div"),this.textRerenderOutput.setAttribute("aria-live","polite"),e.onclick=()=>{this.rerenderAsText()},t.replaceChildren(e,this.textRerenderOutput),this.editor.createHTMLOverlay(t)}rerenderAsText(){this.textRenderer.clear(),this.editor.image.render(this.textRenderer,this.editor.viewport),this.textRerenderOutput&&(this.textRerenderOutput.innerText=this.textRenderer.getDescription())}startRerender(){var t;return null===(t=this.resizeSurfacesCallback)||void 0===t||t.call(this),this.wetInkRenderer.clear(),this.dryInkRenderer.clear(),this.dryInkRenderer}setDraftMode(t){this.dryInkRenderer.setDraftMode(t)}getDryInkRenderer(){return this.dryInkRenderer}getWetInkRenderer(){return this.wetInkRenderer}flatten(){var t;null===(t=this.flattenCallback)||void 0===t||t.call(this)}}const On={updatedViewport:"Transformed Viewport",transformedElements:t=>`Transformed ${t} element${1===t?"":"s"}`,resizeOutputCommand:t=>`Resized image to ${t.w}x${t.h}`,addElementAction:t=>`Added ${t}`,eraseAction:(t,e)=>`Erased ${e} ${t}`,duplicateAction:(t,e)=>`Duplicated ${e} ${t}`,unionOf:(t,e)=>`Union: ${e} ${t}`,inverseOf:t=>`Inverse of ${t}`,elements:"Elements",erasedNoElements:"Erased nothing",duplicatedNoElements:"Duplicated nothing",rotatedBy:t=>`Rotated by ${Math.abs(t)} degrees ${t<0?"clockwise":"counter-clockwise"}`,movedLeft:"Moved left",movedUp:"Moved up",movedDown:"Moved down",movedRight:"Moved right",zoomedOut:"Zoomed out",zoomedIn:"Zoomed in",selectedElements:t=>`Selected ${t} element${1===t?"":"s"}`},$n=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Ie),{penTool:t=>`Pen ${t}`,selectionTool:"Selection",eraserTool:"Eraser",touchPanTool:"Touch panning",twoFingerPanZoomTool:"Panning and zooming",undoRedoTool:"Undo/Redo",rightClickDragPanTool:"Right-click drag",pipetteTool:"Pick color from screen",keyboardPanZoom:"Keyboard pan/zoom shortcuts",textTool:"Text",enterTextToInsert:"Text to insert",changeTool:"Change tool",pasteHandler:"Copy paste handler",copied:(t,e)=>`Copied ${t} ${e}`,pasted:(t,e)=>`Pasted ${t} ${e}`,toolEnabledAnnouncement:t=>`${t} enabled`,toolDisabledAnnouncement:t=>`${t} disabled`}),On),{unlabeledImageNode:"Unlabeled image node",stroke:"Stroke",svgObject:"SVG Object",text:t=>`Text object: ${t}`,imageNode:t=>`Image: ${t}`}),{pathNodeCount:t=>`There are ${t} visible path objects.`,textNodeCount:t=>`There are ${t} visible text nodes.`,imageNodeCount:t=>`There are ${t} visible image nodes.`,textNode:t=>`Text: ${t}`,imageNode:t=>`Image: ${t}`,unlabeledImageNode:"Unlabeled image",rerenderAsText:"Re-render as text"}),{accessibilityInputInstructions:['Press "t" to read the contents of the viewport as text.',"Use the arrow keys to move the viewport, click and drag to draw strokes.",'Press "w" to zoom in and "s" to zoom out.'].join(" "),loading:t=>`Loading ${t}%...`,imageEditor:"Image Editor",doneLoading:"Done loading",undoAnnouncement:t=>`Undid ${t}`,redoAnnouncement:t=>`Redid ${t}`}),Nn={de:Object.assign(Object.assign({},$n),{pen:"Stift",eraser:"Radierer",select:"Auswahl",handTool:"Verschieben",zoom:"Vergrößerung",resetView:"Ansicht zurücksetzen",thicknessLabel:"Dicke: ",colorLabel:"Farbe: ",fontLabel:"Schriftart: ",resizeImageToSelection:"Bildgröße an Auswahl anpassen",deleteSelection:"Auswahl löschen",duplicateSelection:"Auswahl duplizieren",undo:"Rückgängig",redo:"Wiederholen",pickColorFromScreen:"Farbe von Bildschirm auswählen",clickToPickColorAnnouncement:"Klicke auf den Bildschirm, um eine Farbe auszuwählen",selectionToolKeyboardShortcuts:"Auswahl-Werkzeug: Verwende die Pfeiltasten, um ausgewählte Elemente zu verschieben und ‚i‘ und ‚o‘, um ihre Größe zu ändern.",touchPanning:"Ansicht mit Touchscreen verschieben",anyDevicePanning:"Ansicht mit jedem Eingabegerät verschieben",selectObjectType:"Objekt-Typ: ",freehandPen:"Freihand",arrowPen:"Pfeil",linePen:"Linie",outlinedRectanglePen:"Umrissenes Rechteck",filledRectanglePen:"Ausgefülltes Rechteck",dropdownShown:t=>`Dropdown-Menü für ${t} angezeigt`,dropdownHidden:t=>`Dropdown-Menü für ${t} versteckt`,zoomLevel:t=>`Vergößerung: ${t}%`,colorChangedAnnouncement:t=>`Farbe zu ${t} geändert`,penTool:t=>`Stift ${t}`,selectionTool:"Auswahl",eraserTool:"Radiergummi",touchPanTool:"Ansicht mit Touchscreen verschieben",twoFingerPanZoomTool:"Ansicht verschieben und vergrößern",undoRedoTool:"Rückgängig/Wiederholen",rightClickDragPanTool:"Rechtsklick-Ziehen",pipetteTool:"Farbe von Bildschirm auswählen",keyboardPanZoom:"Tastaturkürzel zum Verschieben/Vergrößern der Ansicht",textTool:"Text",enterTextToInsert:"Einzufügender Text",toolEnabledAnnouncement:t=>`${t} aktiviert`,toolDisabledAnnouncement:t=>`${t} deaktiviert`,updatedViewport:"Transformierte Ansicht",transformedElements:t=>`${t} Element${1===t?"":"e"} transformiert`,resizeOutputCommand:t=>`Bildgröße auf ${t.w}x${t.h} geändert`,addElementAction:t=>`${t} hinzugefügt`,eraseAction:(t,e)=>`${e} ${t} gelöscht`,duplicateAction:(t,e)=>`${e} ${t} dupliziert`,inverseOf:t=>`Umkehrung von ${t}`,elements:"Elemente",erasedNoElements:"Nichts entfernt",duplicatedNoElements:"Nichts dupliziert",rotatedBy:t=>`${Math.abs(t)} Grad ${t<0?"im Uhrzeigersinn":"gegen den Uhrzeigersinn"} gedreht`,movedLeft:"Nacht links bewegt",movedUp:"Nacht oben bewegt",movedDown:"Nacht unten bewegt",movedRight:"Nacht rechts bewegt",zoomedOut:"Ansicht verkleinert",zoomedIn:"Ansicht vergrößert",selectedElements:t=>`${t} Element${1===t?"":"e"} ausgewählt`,stroke:"Strich",svgObject:"SVG-Objekt",text:t=>`Text-Objekt: ${t}`,pathNodeCount:t=>`Es gibt ${t} sichtbare Pfad-Objekte.`,textNodeCount:t=>`Es gibt ${t} sichtbare Text-Knotenpunkte.`,textNode:t=>`Text: ${t}`,rerenderAsText:"Als Text darstellen",accessibilityInputInstructions:"Drücke ‚t‘, um den Inhalt des Ansichtsfensters als Text zu lesen. Verwende die Pfeiltasten, um die Ansicht zu verschieben, und klicke und ziehe, um Striche zu zeichnen. Drücke ‚w‘ zum Vergrößern und ‚s‘ zum Verkleinern der Ansicht.",loading:t=>`Laden ${t}%...`,doneLoading:"Laden fertig",imageEditor:"Bild-Editor",undoAnnouncement:t=>`Rückgangig gemacht ${t}`,redoAnnouncement:t=>`Wiederholt ${t}`}),en:Object.assign({},$n),es:Object.assign(Object.assign({},$n),{loading:t=>`Cargando: ${t}%...`,imageEditor:"Editor de dibujos",undoAnnouncement:t=>`${t} fue deshecho`,redoAnnouncement:t=>`${t} fue rehecho`,undo:"Deshace",redo:"Rehace",pen:"Lapiz",eraser:"Borrador",select:"Selecciona",thicknessLabel:"Tamaño: ",colorLabel:"Color: ",doneLoading:"El cargado terminó",fontLabel:"Fuente: ",anyDevicePanning:"Mover la pantalla con todo dispotivo",touchPanning:"Mover la pantalla con un dedo",touchPanTool:"Instrumento de mover la pantalla con un dedo",outlinedRectanglePen:"Rectángulo con nada más que un borde",filledRectanglePen:"Rectángulo sin borde",linePen:"Línea",arrowPen:"Flecha",freehandPen:"Dibuja sin restricción de forma",selectObjectType:"Forma de dibuja:",handTool:"Mover",zoom:"Zoom",resetView:"Reiniciar vista",resizeImageToSelection:"Redimensionar la imagen a lo que está seleccionado",deleteSelection:"Borra la selección",duplicateSelection:"Duplica la selección",pickColorFromScreen:"Selecciona un color de la pantalla",clickToPickColorAnnouncement:"Haga un clic en la pantalla para seleccionar un color",dropdownShown:t=>`Menú por ${t} es visible`,dropdownHidden:function(t){return`Menú por ${t} fue ocultado`},colorChangedAnnouncement:function(t){return`Color fue cambiado a ${t}`},keyboardPanZoom:"Mover la pantalla con el teclado",penTool:function(t){return`Lapiz ${t}`},selectionTool:"Selecciona",eraserTool:"Borrador",textTool:"Texto",enterTextToInsert:"Entra texto",rerenderAsText:"Redibuja la pantalla al texto"})},Fn=t=>{const e=/^(\w+)[_-](\w+)$/.exec(t);return e?e[1]:t},Un=t=>{let e;null!=t||(t=navigator.languages);for(const n of t){const t=Fn(n);if(e&&t!==e&&e in Nn)return Nn[e];if(n in Nn)return Nn[n];e=t}return e&&e in Nn?Nn[e]:$n};var jn=function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{l(r.next(t))}catch(t){o(t)}}function a(t){try{l(r.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}l((r=r.apply(t,e||[])).next())}))};const Vn=class{constructor(t,e={}){var n,r,i,o;this.eventListenerTargets=[],this.previousAccessibilityAnnouncement="",this.pointers={},this.announceUndoCallback=t=>{this.announceForAccessibility(this.localization.undoAnnouncement(t.description(this,this.localization)))},this.announceRedoCallback=t=>{this.announceForAccessibility(this.localization.redoAnnouncement(t.description(this,this.localization)))},this.rerenderQueued=!1,this.localization=Object.assign(Object.assign({},Un()),e.localization),this.settings={wheelEventsEnabled:null===(n=e.wheelEventsEnabled)||void 0===n||n,renderingMode:null!==(r=e.renderingMode)&&void 0!==r?r:Dn.CanvasRenderer,localization:this.localization,minZoom:null!==(i=e.minZoom)&&void 0!==i?i:2e-10,maxZoom:null!==(o=e.maxZoom)&&void 0!==o?o:1e12},this.container=document.createElement("div"),this.renderingRegion=document.createElement("div"),this.container.appendChild(this.renderingRegion),this.container.className="imageEditorContainer",this.loadingWarning=document.createElement("div"),this.loadingWarning.classList.add("loadingMessage"),this.loadingWarning.ariaLive="polite",this.container.appendChild(this.loadingWarning),this.accessibilityControlArea=document.createElement("textarea"),this.accessibilityControlArea.setAttribute("placeholder",this.localization.accessibilityInputInstructions),this.accessibilityControlArea.style.opacity="0",this.accessibilityControlArea.style.width="0",this.accessibilityControlArea.style.height="0",this.accessibilityControlArea.style.position="absolute",this.accessibilityAnnounceArea=document.createElement("div"),this.accessibilityAnnounceArea.setAttribute("aria-live","assertive"),this.accessibilityAnnounceArea.className="accessibilityAnnouncement",this.container.appendChild(this.accessibilityAnnounceArea),this.renderingRegion.style.touchAction="none",this.renderingRegion.className="imageEditorRenderArea",this.renderingRegion.appendChild(this.accessibilityControlArea),this.renderingRegion.setAttribute("tabIndex","0"),this.renderingRegion.setAttribute("alt",""),this.notifier=new ze,this.importExportViewport=new H(this.notifier),this.viewport=new H(this.notifier),this.display=new Mn(this,this.settings.renderingMode,this.renderingRegion),this.image=new I,this.history=new Pe(this,this.announceRedoCallback,this.announceUndoCallback),this.toolController=new Ee(this,this.localization),t.appendChild(this.container),this.importExportViewport.updateScreenSize(S.of(500,500)),this.viewport.updateScreenSize(S.of(this.display.width,this.display.height)),this.registerListeners(),this.queueRerender(),this.hideLoadingWarning(),this.notifier.on(M.ViewportChanged,(t=>{if(t.kind===M.ViewportChanged){const e=t.newTransform.transformVec3(S.unitX).length();if(e>this.settings.maxZoom||e<this.settings.minZoom){const e=t.oldTransform.transformVec3(S.unitX).length();let n=P.identity;e<=this.settings.maxZoom&&e>=this.settings.minZoom&&(n=t.oldTransform),this.viewport.resetTransform(n)}}}))}getRootElement(){return this.container}showLoadingWarning(t){const e=Math.round(100*t);this.loadingWarning.innerText=this.localization.loading(e),this.loadingWarning.style.display="block"}hideLoadingWarning(){this.loadingWarning.style.display="none",this.announceForAccessibility(this.localization.doneLoading)}announceForAccessibility(t){t===this.previousAccessibilityAnnouncement&&(t+=". "),this.accessibilityAnnounceArea.innerText=t,this.previousAccessibilityAnnouncement=t}addToolbar(t=!0){const e=new kn(this,this.container,this.localization);return t&&(e.addDefaultToolWidgets(),e.addDefaultActionButtons()),e}registerListeners(){this.handlePointerEventsFrom(this.renderingRegion),this.handleKeyEventsFrom(this.renderingRegion),this.container.addEventListener("wheel",(t=>{let e=C.of(t.deltaX,t.deltaY,t.deltaZ);if(!t.ctrlKey){if(!this.settings.wheelEventsEnabled)return;if("only-if-focused"===this.settings.wheelEventsEnabled){if(!this.container.querySelector(":focus"))return}}t.deltaMode===WheelEvent.DOM_DELTA_LINE?e=e.times(15):t.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(e=e.times(100)),t.ctrlKey&&(e=C.of(0,0,t.deltaY));const n=this.container.getBoundingClientRect(),r=S.of(t.clientX,t.clientY).minus(S.of(n.left,n.top));return!!this.toolController.dispatchInputEvent({kind:D.WheelEvt,delta:e,screenPos:r})&&(t.preventDefault(),!0)})),this.notifier.on(M.DisplayResized,(t=>{this.viewport.updateScreenSize(S.of(this.display.width,this.display.height))})),window.addEventListener("resize",(()=>{this.notifier.dispatch(M.DisplayResized,{kind:M.DisplayResized,newSize:S.of(this.display.width,this.display.height)}),this.queueRerender()})),this.accessibilityControlArea.addEventListener("input",(()=>{this.accessibilityControlArea.value=""})),document.addEventListener("copy",(t=>{if(!this.isEventSink(document.querySelector(":focus")))return;const e=t.clipboardData;this.toolController.dispatchInputEvent({kind:D.CopyEvent,setData:(t,n)=>{null==e||e.setData(t,n)}})&&t.preventDefault()})),document.addEventListener("paste",(t=>{this.handlePaste(t)}))}getPointerList(){const t=(new Date).getTime(),e=[];for(const n in this.pointers){const r=2e3;this.pointers[n]&&t-this.pointers[n].timeStamp<r&&e.push(this.pointers[n])}return e}handleHTMLPointerEvent(t,e){var n,r,i;const o=this.renderingRegion,s=null!==(n=e.target)&&void 0!==n?n:this.renderingRegion;if("pointerdown"===t){const t=$.ofEvent(e,!0,this.viewport,o);this.pointers[t.id]=t,s.setPointerCapture(t.id);const n={kind:D.PointerDownEvt,current:t,allPointers:this.getPointerList()};return this.toolController.dispatchInputEvent(n),!0}if("pointermove"===t){const t=$.ofEvent(e,null!==(i=null===(r=this.pointers[e.pointerId])||void 0===r?void 0:r.down)&&void 0!==i&&i,this.viewport,o);if(t.down){const n=this.pointers[t.id];if(n){if(t.screenPos.minus(n.screenPos).magnitude()<2)return!1}this.pointers[t.id]=t,this.toolController.dispatchInputEvent({kind:D.PointerMoveEvt,current:t,allPointers:this.getPointerList()})&&e.preventDefault()}return!0}if("pointercancel"===t||"pointerup"===t){const t=$.ofEvent(e,!1,this.viewport,o);return!!this.pointers[t.id]&&(this.pointers[t.id]=t,s.releasePointerCapture(t.id),this.toolController.dispatchInputEvent({kind:D.PointerUpEvt,current:t,allPointers:this.getPointerList()})&&e.preventDefault(),delete this.pointers[t.id],!0)}return t}isEventSink(t){let e=t;for(;null!==e;){for(const t of this.eventListenerTargets)if(t===e)return!0;e=e.parentElement}return!1}handlePaste(t){var e,n;return jn(this,void 0,void 0,(function*(){const r=null!==(e=document.querySelector(":focus"))&&void 0!==e?e:t.target;if(!this.isEventSink(r))return;const i=null!==(n=t.dataTransfer)&&void 0!==n?n:t.clipboardData;if(!i)return;for(const e of i.files)if("image/svg+xml"===e.type.toLowerCase()){const n=yield e.text();if(this.toolController.dispatchInputEvent({kind:D.PasteEvent,mime:e.type,data:n}))return void t.preventDefault()}for(const e of i.files){const n=e.type.toLowerCase();if("image/png"===n||"image/jpg"===n){const r=new FileReader;this.showLoadingWarning(0);try{const i=yield new Promise(((t,n)=>{r.onload=()=>t(r.result),r.onerror=n,r.onabort=n,r.onprogress=t=>{this.showLoadingWarning(t.loaded/t.total)},r.readAsDataURL(e)}));if(i&&this.toolController.dispatchInputEvent({kind:D.PasteEvent,mime:n,data:i}))return t.preventDefault(),void this.hideLoadingWarning()}catch(t){console.error("Error reading image:",t)}this.hideLoadingWarning()}}const o=["image/svg+xml","text/plain"];for(const e of o){const n=i.getData(e);if(n&&this.toolController.dispatchInputEvent({kind:D.PasteEvent,mime:e,data:n}))return void t.preventDefault()}}))}handlePointerEventsFrom(t,e){t.addEventListener("touchstart",(t=>t.preventDefault())),t.addEventListener("contextmenu",(t=>{t.preventDefault()}));const n=["pointerdown","pointermove","pointerup","pointercancel"];for(const r of n)t.addEventListener(r,(t=>!(!e||e(r,t))||this.handleHTMLPointerEvent(r,t)))}handleKeyEventsFrom(t){t.addEventListener("keydown",(t=>{"t"===t.key||"T"===t.key?(t.preventDefault(),this.display.rerenderAsText()):this.toolController.dispatchInputEvent({kind:D.KeyPressEvent,key:t.key,ctrlKey:t.ctrlKey})?t.preventDefault():"Escape"===t.key&&this.renderingRegion.blur()})),t.addEventListener("keyup",(t=>{this.toolController.dispatchInputEvent({kind:D.KeyUpEvent,key:t.key,ctrlKey:t.ctrlKey})&&t.preventDefault()})),t.ondragover=t=>{t.preventDefault()},t.ondrop=t=>{t.preventDefault(),this.handlePaste(t)},this.eventListenerTargets.push(t)}dispatch(t,e=!0){e?this.history.push(t):t.apply(this),this.announceForAccessibility(t.description(this,this.localization))}dispatchNoAnnounce(t,e=!1){e?this.history.push(t):t.apply(this)}asyncApplyOrUnapplyCommands(t,e,n){return jn(this,void 0,void 0,(function*(){console.assert(n>0),this.display.setDraftMode(!0);for(let r=0;r<t.length;r+=n){this.showLoadingWarning(r/t.length);for(let i=r;i<t.length&&i<r+n;i++){const n=t[i];e?n.apply(this):n.unapply(this)}r+n<t.length&&(yield new Promise((t=>{this.rerender(),requestAnimationFrame(t)})))}this.display.setDraftMode(!1),this.hideLoadingWarning()}))}asyncApplyCommands(t,e){return this.asyncApplyOrUnapplyCommands(t,!0,e)}asyncUnapplyCommands(t,e){return this.asyncApplyOrUnapplyCommands(t,!1,e)}queueRerender(){this.rerenderQueued||(this.rerenderQueued=!0,requestAnimationFrame((()=>{this.rerender(),this.rerenderQueued=!1})))}rerender(t=!0){if(this.display.startRerender(),0===this.display.width||0===this.display.height)return;const e=this.display.getDryInkRenderer();if(this.image.renderWithCache(e,this.display.getCache(),this.viewport),t){const t={fill:Et.fromHex("#44444455")},n=5*this.viewport.getSizeOfPixelOnCanvas();e.drawRect(this.importExportViewport.visibleRect,n,t)}this.rerenderQueued=!1}drawWetInk(...t){for(const e of t)this.display.getWetInkRenderer().drawPath(e)}clearWetInk(){this.display.getWetInkRenderer().clear()}focus(){this.renderingRegion.focus()}createHTMLOverlay(t){return t.classList.add("overlay"),this.container.appendChild(t),{remove:()=>t.remove()}}addStyleSheet(t){const e=document.createElement("style");return e.innerText=t,this.container.appendChild(e),e}sendKeyboardEvent(t,e,n=!1){this.toolController.dispatchInputEvent({kind:t,key:e,ctrlKey:n})}sendPenEvent(t,e,n){const r=$.ofCanvasPoint(e,t!==D.PointerUpEvt,this.viewport);this.toolController.dispatchInputEvent({kind:t,allPointers:null!=n?n:[r],current:r})}toSVG(){const t=this.importExportViewport,e="http://www.w3.org/2000/svg",n=document.createElementNS(e,"svg"),r=new Qt(n,t),i=t.canvasToScreenTransform;t.resetTransform(P.identity),this.image.renderAll(r),t.resetTransform(i);const o=t.visibleRect;return n.setAttribute("viewBox",`${o.x} ${o.y} ${o.w} ${o.h}`),n.setAttribute("width",`${o.w}`),n.setAttribute("height",`${o.h}`),n.setAttribute("version","1.1"),n.setAttribute("baseProfile","full"),n.setAttribute("xmlns",e),n}loadFrom(t){return jn(this,void 0,void 0,(function*(){this.showLoadingWarning(0),this.display.setDraftMode(!0),yield t.start((t=>{this.dispatchNoAnnounce(I.addElement(t))}),((t,e)=>t%500==0?(this.showLoadingWarning(t/e),this.rerender(),new Promise((t=>{requestAnimationFrame((()=>t()))}))):null),(t=>{this.dispatchNoAnnounce(this.setImportExportRect(t),!1),this.dispatchNoAnnounce(this.viewport.zoomTo(t),!1)})),this.hideLoadingWarning(),this.display.setDraftMode(!1),this.queueRerender()}))}getImportExportRect(){return this.importExportViewport.visibleRect}setImportExportRect(t){const e=this.importExportViewport.visibleRect.size,n=this.importExportViewport.canvasToScreenTransform;return new class extends w{apply(e){const n=e.importExportViewport;n.updateScreenSize(t.size),n.resetTransform(P.translation(t.topLeft.times(-1))),e.queueRerender()}unapply(t){const r=t.importExportViewport;r.updateScreenSize(e),r.resetTransform(n),t.queueRerender()}description(e,n){return n.resizeOutputCommand(t)}}}loadFromSVG(t,e=!1){return jn(this,void 0,void 0,(function*(){const n=Xt.fromString(t,e);yield this.loadFrom(n)}))}},Wn=Vn})(),window.jsdraw=i})();