js-draw 0.1.10 → 0.1.11

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.
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\twidth: min-content;\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\tmax-width: 70px;\n\tfont-size: 11pt;\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\twidth: min-content;\n\theight: min-content;\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 f=i(p,r);r.byIndex=a,e.splice(a,0,{identifier:d,updater:f,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,{Editor:()=>en,default:()=>nn,getLocalizationTable:()=>Je});var e=r(379),n=r.n(e),o=r(795),s=r.n(o),a=r(569),l=r.n(a),c=r(565),h=r.n(c),d=r(216),u=r.n(d),p=r(589),f=r.n(p),m=r(59),g={};g.styleTagTransform=f(),g.setAttributes=h(),g.insert=l().bind(null,"head"),g.domAPI=s(),g.insertStyleElement=u();n()(m.Z,g);m.Z&&m.Z.locals&&m.Z.locals;var x=r(786),v={};v.styleTagTransform=f(),v.setAttributes=h(),v.insert=l().bind(null,"head"),v.domAPI=s(),v.insertStyleElement=u();n()(x.Z,v);x.Z&&x.Z.locals&&x.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){const r=t.description(n),i=e.description(n);return r===i?r:`${r}, ${i}`}}}}y.empty=new class extends y{description(t){return""}apply(t){}unapply(t){}};const b=y;class w extends b{constructor(t){if(super(),this.commandTypeId=t,!(t in w.deserializationCallbacks))throw new Error(`Command ${t} must have a registered deserialization callback. To do this, call SerializableCommand.register.`)}serialize(){return JSON.stringify({data:this.serializeToString(),commandType:this.commandTypeId})}static deserialize(t,e){const n=JSON.parse(t),r=n.commandType;if(!(r in w.deserializationCallbacks))throw new Error(`Unrecognised command type ${r}!`);return w.deserializationCallbacks[r](n.data,e)}static register(t,e){w.deserializationCallbacks[t]=e}}w.deserializationCallbacks={};class T{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 T(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 T.of(this.x/t,this.y/t,this.z/t)}times(t){return T.of(this.x*t,this.y*t,this.z*t)}plus(t){return T.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 T.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(T.unitX)&&0===this.dot(T.unitY)?0===this.dot(T.unitX)?T.unitX:this.cross(T.unitX).normalized():this.cross(T.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 T.of(e(t.x,this.x),e(t.y,this.y),e(t.z,this.z))}map(t){return T.of(t(this.x),t(this.y),t(this.z))}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,C;T.unitX=T.of(1,0,0),T.unitY=T.of(0,1,0),T.unitZ=T.of(0,0,1),T.zero=T.of(0,0,0),function(t){t.of=(t,e)=>T.of(t,e,0),t.ofXY=({x:t,y:e})=>T.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=[T.of(t,e,n),T.of(r,i,o),T.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=[T.unitX,T.unitY,T.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=T.of(t.x,t.y,1);return e=this.transformVec3(e),k.of(e.x,e.y)}transformVec3(t){return T.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`.trimRight()}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 E{constructor(t){if(this.componentKind=t,this.loadSaveData={},this.lastChangedTime=(new Date).getTime(),this.zIndex=E.zIndexCounter++,this.id=`${(new Date).getTime()}-${Math.random()}`,void 0===E.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 E.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.serializeToString();if(null===t)throw new Error(`${this} cannot be serialized.`);return JSON.stringify({name:this.componentKind,zIndex:this.zIndex,id:this.id,loadSaveData:this.loadSaveData,data:t})}static isNotDeserializable(t){const e=JSON.parse(t);return"object"!=typeof e||(!this.deserializationCallbacks[null==e?void 0:e.name]||!e.data)}static deserialize(t){if(E.isNotDeserializable(t))throw new Error(`Element with data ${t} cannot be deserialized.`);const e=JSON.parse(t),n=this.deserializationCallbacks[e.name](e.data);return n.zIndex=e.zIndex,n.id=e.id,n}}E.zIndexCounter=0,E.deserializationCallbacks={},E.TransformElementCommand=(S=class extends w{constructor(t,e){super("transform-element"),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&&L.addElement(this.component).apply(t)}apply(t){this.component.zIndex=E.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){return t.transformedElements(1)}serializeToString(){return JSON.stringify({id:this.component.getId(),transfm:this.affineTransfm.toArray()})}},w.register("transform-element",((t,e)=>{const n=JSON.parse(t),r=e.image.lookupElement(n.id);if(!r)throw new Error(`Unable to retrieve non-existent element, ${r}`);const i=n.transfm;return new E.TransformElementCommand(new P(...i),r)})),S);class z{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}}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}}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 z(t[0],t[1]),new z(t[1],t[2]),new z(t[2],t[3]),new z(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 B=t=>{t.sort(((t,e)=>t.getContent().getZIndex()-e.getContent().getZIndex()))};class L{constructor(){this.root=new M,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();B(e);for(const n of e)n.getContent().render(t,n.getBBox())}getElementsIntersectingRegion(t){const e=this.root.getLeavesIntersectingRegion(t);return B(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 L.AddElementCommand(t,e)}}L.AddElementCommand=(C=class extends w{constructor(t,e=!1){if(super("add-element"),this.element=t,this.applyByFlattening=e,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){return t.addElementAction(this.element.description(t))}serializeToString(){return JSON.stringify({elemData:this.element.serialize()})}},w.register("add-element",((t,e)=>{const n=JSON.parse(t),r=E.deserialize(n.elemData);return new L.AddElementCommand(r)})),C);class M{constructor(t=null){this.parent=t,this.targetChildCount=30,this.children=[],this.bbox=R.empty,this.content=null,this.id=M.idCounter++}getId(){return this.id}onContentChange(){this.id=M.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=[];if(null==e?void 0:e(this.bbox))return[];null!==this.content&&this.getBBox().intersects(t)&&n.push(this);const r=this.getChildrenIntersectingRegion(t);for(const i of r)n.push(...i.getLeavesIntersectingRegion(t,e));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 M(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 M(this),n=new M(this);return n.children=this.children,this.children=[e,n],n.recomputeBBox(!0),n.updateParents(),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 M(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)));B(n);for(const r of n)r.getContent().render(t,e)}}var A,I,O;M.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"}(A||(A={})),function(t){t[t.ToolEnabled=0]="ToolEnabled",t[t.ToolDisabled=1]="ToolDisabled",t[t.ToolUpdated=2]="ToolUpdated",t[t.UndoRedoStackUpdated=3]="UndoRedoStackUpdated",t[t.ObjectAdded=4]="ObjectAdded",t[t.ViewportChanged=5]="ViewportChanged",t[t.DisplayResized=6]="DisplayResized",t[t.ColorPickerToggled=7]="ColorPickerToggled",t[t.ColorPickerColorSelected=8]="ColorPickerColorSelected"}(I||(I={})),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 D{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 D(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 D(a,t,s,o,e,i,r,l)}}var N,$,j=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},F=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 U{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)}resetTransform(t=P.identity){this.transform=t,this.inverseTransform=t.inverse(),this.notifier.dispatch(I.ViewportChanged,{kind:I.ViewportChanged,newTransform:t})}get screenToCanvasTransform(){return this.inverseTransform}get canvasToScreenTransform(){return this.transform}getResolution(){return this.screenRect.size}getScaleFactor(){return this.transform.transformVec3(T.unitX).magnitude()}getSizeOfPixelOnCanvas(){return 1/this.getScaleFactor()}getRotationAngle(){return this.transform.transformVec3(T.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 U.roundPoint(t,1/this.getScaleFactor())}zoomTo(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),new U.ViewportTransform(r)}}U.ViewportTransform=($=class extends b{constructor(t){super(),this.transform=t,N.set(this,void 0),j(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(F(this,N,"f"))),t.queueRerender()}description(t){const e=[],n=k.unitX,r=this.transform.transformVec3(k.unitX),i=this.transform.transformVec2(k.unitX),o=r.magnitude(),s=180/Math.PI*r.angle(),a=i.minus(n);o>1.2?e.push(t.zoomedIn):o<.8&&e.push(t.zoomedOut),Math.floor(Math.abs(s))>0&&e.push(t.rotatedBy(Math.round(s)));const l=1e-4;return a.x>l?e.push(t.movedLeft):a.x<-1e-4&&e.push(t.movedRight),a.y<l?e.push(t.movedDown):a.y>l&&e.push(t.movedUp),e.join("; ")}},N=new WeakMap,$);const V=U;class W{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}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(I.ToolEnabled,{kind:I.ToolEnabled,tool:this})):this.notifier.dispatch(I.ToolDisabled,{kind:I.ToolDisabled,tool:this})}isEnabled(){return this.enabled}setToolGroup(t){this.isEnabled()&&t.notifyEnabled(this),this.group=t}}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 H extends W{constructor(t,e,n){super(t.notifier,n),this.editor=t,this.mode=e,this.kind=Wt.PanZoom,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=new U.ViewportTransform(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=new U.ViewportTransform(this.transform.transform.rightMul(s))}handleOneFingerMove(t){const e=this.getCenterDelta(t.screenPos);this.transform=new U.ViewportTransform(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=new U.ViewportTransform(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){var e;let n=t;this.transform&&(n=this.transform.transform.rightMul(t)),null===(e=this.transform)||void 0===e||e.unapply(this.editor),this.transform=new U.ViewportTransform(n),this.transform.apply(this.editor)}onWheel({delta:t,screenPos:e}){null===this.transform&&(this.transform=new U.ViewportTransform(P.identity));const n=this.editor.viewport.screenToCanvas(e),r=this.editor.viewport.screenToCanvasTransform.transformVec3(T.of(-t.x,-t.y,0)),i=P.scaling2D(Math.pow(1.04,-t.z),n).rightMul(P.translation(r));return this.updateTransform(i),!0}onKeyPress({key:t}){if(!(this.mode&_.Keyboard))return!1;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"k":case"ArrowUp":e=k.of(0,-1);break;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;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}setMode(t){t!==this.mode&&(this.mode=t,this.editor.notifier.dispatch(I.ToolUpdated,{kind:I.ToolUpdated,tool:this}))}getMode(){return this.mode}}const{abs:G,cos:q,sin:Z,acos:K,atan2:X,sqrt:Y,pow:Q}=Math;function J(t){return t<0?-Q(-t,1/3):Q(t,1/3)}const tt=Math.PI,et=2*tt,nt=tt/2,rt=Number.MAX_SAFE_INTEGER||9007199254740991,it=Number.MIN_SAFE_INTEGER||-9007199254740991,ot={x:0,y:0,z:0},st={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),Y(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],ot],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||st.approximately(t,e)||st.approximately(t,n)},approximately:function(t,e,n){return G(t-e)<=(n||1e-6)},length:function(t){const e=st.Tvalues.length;let n=0;for(let r,i=0;i<e;i++)r=.5*st.Tvalues[i]+.5,n+=st.Cvalues[i]*st.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(st.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 X(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 Y(n*n+r*r)},closest:function(t,e){let n,r,i=Q(2,63);return t.forEach((function(t,o){r=st.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=Q(t,e)+Q(1-t,e);return G((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=Q(1-t,e);return n/(Q(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 st.lli8(i,o,s,a,l,c,h,d)},lli:function(t,e){return st.lli4(t,t.c,e,e.c)},makeline:function(t,e){return new gt(t.x,t.y,(t.x+e.x)/2,(t.y+e.y)/2,e.x,e.y)},findbbox:function(t){let e=rt,n=rt,r=it,i=it;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(!st.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=st.makeline(e.points[r-1],t.points[0]),s=st.makeline(t.points[i-1],e.points[0]),a={startcap:o,forward:t,back:e,endcap:s,bbox:st.findbbox([o,t,e,s]),intersections:function(t){return st.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=rt,s=it;-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=-X(e.p2.y-r,e.p2.x-n);return t.map((function(t){return{x:(t.x-n)*q(i)-(t.y-r)*Z(i),y:(t.x-n)*Z(i)+(t.y-r)*q(i)}}))},roots:function(t,e){e=e||{p1:{x:0,y:0},p2:{x:1,y:0}};const n=t.length-1,r=st.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=-Y(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(st.approximately(l,0)){if(st.approximately(c,0))return st.approximately(h,0)?[]:[-d/h].filter(i);const t=Y(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,f=(2*c*c*c-9*c*h+27*d)/27,m=f/2,g=m*m+p*p*p;let x,v,y,b,w;if(g<0){const t=-u/3,e=Y(t*t*t),n=-f/(2*e),r=K(n<-1?-1:n>1?1:n),o=2*J(e);return y=o*q(r/3)-c/3,b=o*q((r+et)/3)-c/3,w=o*q((r+2*et)/3)-c/3,[y,b,w].filter(i)}if(0===g)return x=m<0?J(-m):-J(m),y=2*x-c/3,b=-x-c/3,[y,b].filter(i);{const t=Y(g);return x=J(-m+t),v=J(m+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=-Y(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=st.compute(t,e),u=st.compute(t,n),p=d.x*d.x+d.y*d.y;if(r?(o=Y(Q(d.y*u.z-u.y*d.z,2)+Q(d.z*u.x-u.z*d.x,2)+Q(d.x*u.y-u.x*d.y,2)),s=Q(p+d.z*d.z,1.5)):(o=d.x*u.y-d.y*u.x,s=Q(p,1.5)),0===o||0===s)return{k:0,r:0};if(c=o/s,h=s/o,!i){const i=st.curvature(t-.001,e,n,r,!0).k,o=st.curvature(t+.001,e,n,r,!0).k;l=(o-c+(c-i))/2,a=(G(o-c)+G(c-i))/2}return{k:c,r:h,dk:l,adk:a}},inflections:function(t){if(t.length<4)return[];const e=st.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(st.approximately(o,0)){if(!st.approximately(s,0)){let t=-a/s;if(0<=t&&t<=1)return[t]}return[]}const l=2*o;if(st.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,G(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 st.bboxoverlap(t.left.bbox(),t.right.bbox())}));let h=[];return 0===c.length||(c.forEach((function(t){h=h.concat(st.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*q(nt)-i*Z(nt),l=r*Z(nt)+i*q(nt),c=o*q(nt)-s*Z(nt),h=o*Z(nt)+s*q(nt),d=(t.x+e.x)/2,u=(t.y+e.y)/2,p=(e.x+n.x)/2,f=(e.y+n.y)/2,m=d+a,g=u+l,x=p+c,v=f+h,y=st.lli8(d,u,m,g,p,f,x,v),b=st.dist(y,t);let w,T=X(t.y-y.y,t.x-y.x),k=X(e.y-y.y,e.x-y.x),S=X(n.y-y.y,n.x-y.x);return T<S?((T>k||k>S)&&(T+=et),T>S&&(w=S,S=T,T=w)):S<k&&k<T?(w=S,S=T,T=w):S+=et,y.s=T,y.e=S,y.r=b,y},numberSort:function(t,e){return t-e}};class at{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 st.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++)st.expandbox(e,t[n].bbox());return e}offset(t){const e=[];return this.curves.forEach((function(n){e.push(...n.offset(t))})),new at(e)}}const{abs:lt,min:ct,max:ht,cos:dt,sin:ut,acos:pt,sqrt:ft}=Math,mt=Math.PI;class gt{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=st.align(s,{p1:s[0],p2:s[l]}),d=st.dist(s[0],s[l]);this._linear=h.reduce(((t,e)=>t+lt(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 gt(e,e,n);if(1===r)return new gt(t,e,e);const i=gt.getABC(2,t,e,n,r);return new gt(t,i.A,n)}static cubicFromPoints(t,e,n,r,i){void 0===r&&(r=.5);const o=gt.getABC(3,t,e,n,r);void 0===i&&(i=st.dist(e,o.C));const s=i*(1-r)/r,a=st.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,f=e.x-h,m=e.y-d,g=e.x+u,x=e.y+p,v=o.A,y=v.x+(f-v.x)/(1-r),b=v.y+(m-v.y)/(1-r),w=v.x+(g-v.x)/r,T=v.y+(x-v.y)/r,k={x:t.x+(y-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 gt(t,k,S,n)}static getUtils(){return st}getUtils(){return gt.getUtils()}static get PolyBezier(){return at}valueOf(){return this.toString()}toString(){return st.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=st.derive(this.points,this._3d),this.computedirection()}computedirection(){const t=this.points,e=st.angle(t[0],t[this.order],t[1]);this.clockwise=e>0}length(){return st.length(this.derivative.bind(this))}static getABC(t=2,e,n,r,i=.5){const o=st.projectionratio(i,t),s=1-o,a={x:o*e.x+s*r.x,y:o*e.y+s*r.y},l=st.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 gt.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],st.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=st.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=st.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?st.computeWithRatios(t,this.points,this.ratios,this._3d):st.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 gt(e)}derivative(t){return st.compute(t,this.dpoints[0],this._3d)}dderivative(t){return st.compute(t,this.dpoints[1],this._3d)}align(){let t=this.points;return new gt(st.align(t,{p1:t[0],p2:t[t.length-1]}))}curvature(t){return st.curvature(t,this.dpoints[0],this.dpoints[1],this._3d)}inflections(){return st.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=st.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 gt([n[0],n[3],n[5]]):new gt([n[0],n[4],n[7],n[9]]),right:2===this.order?new gt([n[5],n[4],n[2]]):new gt([n[9],n[8],n[6],n[3]]),span:n};return r.left._t1=st.map(0,0,1,this._t1,this._t2),r.left._t2=st.map(t,0,1,this._t1,this._t2),r.right._t1=st.map(t,0,1,this._t1,this._t2),r.right._t2=st.map(1,0,1,this._t1,this._t2),e?(e=st.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]=st.droots(i),3===this.order&&(i=this.dpoints[1].map(r),t[n]=t[n].concat(st.droots(i))),t[n]=t[n].filter((function(t){return t>=0&&t<=1})),e=e.concat(t[n].sort(st.numberSort))}.bind(this)),t.values=e.sort(st.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]=st.getminmax(this,n,t[n])}.bind(this)),e}overlaps(t){const e=this.bbox(),n=t.bbox();return st.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 gt(n)]}return this.reduce().map((function(e){return e._linear?e.offset(t)[0]:e.scale(t)}))}simple(){if(3===this.order){const t=st.angle(this.points[0],this.points[3],this.points[1]),e=st.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),lt(pt(n))<mt/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,lt(n-r)<i)return[];e=t.split(n,r),e._t1=st.map(n,0,1,t._t1,t._t2),e._t2=st.map(r,0,1,t._t1,t._t2),s.push(e),n=r;break}n<1&&(e=t.split(n,1),e._t1=st.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 gt(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=st.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]=st.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 gt(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]=st.lli4(n,o,c,i[t+1])})),new gt(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=st.makeline(d[2],h[0]),p=st.makeline(h[2],d[0]),f=[u,new gt(h),p,new gt(d)];return new at(f)}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 st.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],f=s[o-1].points[s[o-1].points.length-1],m=l[o-1].points[l[o-1].points.length-1],g=l[0].points[0],x=st.makeline(m,p),v=st.makeline(f,g),y=[x].concat(s).concat([v]).concat(l);return new at(y)}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=st.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 gt&&(t=t.reduce()),this.curveintersects(this.reduce(),t,e)):this.selfintersects(e)}lineIntersects(t){const e=ct(t.p1.x,t.p2.x),n=ct(t.p1.y,t.p2.y),r=ht(t.p1.x,t.p2.x),i=ht(t.p1.y,t.p2.y);return st.roots(this.points,t).filter((t=>{var o=this.get(t);return st.between(o.x,e,r)&&st.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=st.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=st.dist(t,e),l=st.dist(t,o),c=st.dist(t,s);return lt(l-a)+lt(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,f=1,m=0;do{if(u=d,l=a,p=(r+i)/2,m++,o=this.get(p),s=this.get(i),a=st.getccenter(h,o,s),a.interval={start:r,end:i},d=this._error(a,h,r,i)<=t,c=u&&!d,c||(f=i),d){if(i>=1){if(a.interval.end=f=1,l=a,i>1){let t={x:a.x+a.r*dt(a.e),y:a.y+a.r*ut(a.e)};a.e+=st.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=f}while(i<1);return e}}var xt;!function(t){t[t.LineTo=0]="LineTo",t[t.MoveTo=1]="MoveTo",t[t.CubicBezierTo=2]="CubicBezierTo",t[t.QuadraticBezierTo=3]="QuadraticBezierTo"}(xt||(xt={}));class vt{constructor(t,e){this.startPoint=t,this.parts=e,this.cachedGeometry=null,this.bbox=R.bboxOf([t]);for(const n of e)this.bbox=this.bbox.union(vt.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 xt.CubicBezierTo:e.push(new gt(t.xy,n.controlPoint1.xy,n.controlPoint2.xy,n.endPoint.xy)),t=n.endPoint;break;case xt.QuadraticBezierTo:e.push(new gt(t.xy,n.controlPoint.xy,n.endPoint.xy)),t=n.endPoint;break;case xt.LineTo:e.push(new z(t,n.point)),t=n.point;break;case xt.MoveTo:t=n.point}return this.cachedGeometry=e,this.cachedGeometry}static computeBBoxForSegment(t,e){const n=[t];let r;switch(e.kind){case xt.MoveTo:case xt.LineTo:n.push(e.point);break;case xt.CubicBezierTo:n.push(e.controlPoint1,e.controlPoint2,e.endPoint);break;case xt.QuadraticBezierTo:n.push(e.controlPoint,e.endPoint);break;default:return r=e,r}return R.bboxOf(n)}intersection(t){const e=[];for(const n of this.geometry)if(n instanceof z){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}transformedBy(t){const e=t.transformVec2(this.startPoint),n=[];let r;for(const e of this.parts)switch(e.kind){case xt.MoveTo:case xt.LineTo:n.push({kind:e.kind,point:t.transformVec2(e.point)});break;case xt.CubicBezierTo:n.push({kind:e.kind,controlPoint1:t.transformVec2(e.controlPoint1),controlPoint2:t.transformVec2(e.controlPoint2),endPoint:t.transformVec2(e.endPoint)});break;case xt.QuadraticBezierTo:n.push({kind:e.kind,controlPoint:t.transformVec2(e.controlPoint),endPoint:t.transformVec2(e.endPoint)});break;default:return r=e,r}return new vt(e,n)}union(t){return t?new vt(this.startPoint,[...this.parts,{kind:xt.MoveTo,point:t.startPoint},...t.parts]):this}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:xt.LineTo,point:t});return new vt(i,n)}static fromRenderable(t){return new vt(t.startPoint,t.commands)}toRenderable(t){return{startPoint:this.startPoint,style:t,commands:this.parts}}toString(){return vt.toString(this.startPoint,this.parts)}serialize(){return this.toString()}static toString(t,e){const n=[],r=t=>{let e=t.toString();if(-1===e.indexOf("."))return e;const n=/^([-]?)(\d*)\.(\d{3,}9{4,}\d)$/.exec(e);if(n){const t=n[1],r=parseInt(e.charAt(e.length-1),10),i=parseInt(n[3],10),o=parseInt(n[2],10),s=n[3];let a=(i+10-r).toString(),l=0;for(a.length>i.toString().length&&(a=a.substring(1),l=1);a.length<s.length;)a=l.toString(10)+a,l=0;e=`${t+(o+l).toString()}.${a}`}return e=e.replace(/^([-]?\d*\.\d{3,})0{4,}\d$/,"$1"),e=e.replace(/([.]\d*[^0]+)0+$/,"$1"),e=e.replace(/[.]0+$/,"."),e.replace(/[.]$/,"")},i=(t,...e)=>{const i=[];for(const t of e){const e=r(t.x),n=r(t.y);i.push(`${e},${n}`)}n.push(`${t}${i.join(" ")}`)};let o;i("M",t);for(const t of e)switch(t.kind){case xt.MoveTo:i("M",t.point);break;case xt.LineTo:i("L",t.point);break;case xt.CubicBezierTo:i("C",t.controlPoint1,t.controlPoint2,t.endPoint);break;case xt.QuadraticBezierTo:i("Q",t.controlPoint,t.endPoint);break;default:return o=t,o}return n.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:xt.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 y=null!==(e=l[x])&&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(k.of(o,i))}return t}),[]).map(((t,e)=>{let r;return r=v?t:n.plus(t),(e+1)%y==0&&(n=r),r}));if(b.length%y!=0)throw new Error([`Incorrect number of arguments: got ${JSON.stringify(b)} with a length of ${b.length} ≠ ${y}k, k ∈ ℤ.`,`The number of arguments to ${x} must be a multiple of ${y}!`,`Command: ${h[0]}`].join("\n"));for(let t=0;t<b.length;t+=y){const e=b.slice(t,t+y);switch(x.toLowerCase()){case"m":0===t?(g=e[0],o?o=!1:s.push({kind:xt.MoveTo,point:g})):a(e[0]);break;case"l":a(e[0]);break;case"c":p=e[0],f=e[1],m=e[2],s.push({kind:xt.CubicBezierTo,controlPoint1:p,controlPoint2:f,endPoint:m});break;case"q":d=e[0],u=e[1],s.push({kind:xt.QuadraticBezierTo,controlPoint:d,endPoint:u});break;default:throw new Error(`Unknown path command ${x}`)}o=!1}b.length>0&&(null!=r||(r=b[0]),null!=i||(i=r),n=b[b.length-1])}var d,u,p,f,m,g;return new vt(null!=i?i:k.zero,s)}}vt.empty=new vt(k.zero,[]);class yt{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 yt.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 yt(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 yt.ofRGBA(n[0],n[1],n[2],n[3])}static fromString(t){if(t.startsWith("#"))return yt.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 yt.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)}}yt.transparent=yt.ofRGBA(0,0,0,0),yt.red=yt.ofRGB(1,0,0),yt.green=yt.ofRGB(0,1,0),yt.blue=yt.ofRGB(0,0,1),yt.purple=yt.ofRGB(.5,.2,.5),yt.yellow=yt.ofRGB(1,1,.1),yt.clay=yt.ofRGB(.8,.4,.2),yt.black=yt.ofRGB(0,0,0),yt.white=yt.ofRGB(1,1,1);const bt=(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},wt=t=>{const e=t.stroke?{color:t.stroke.color.toHexString(),width:t.stroke.width}:void 0;return{fill:t.fill.toHexString(),stroke:e}},Tt=t=>{const e=t.stroke?{color:yt.fromHex(t.stroke.color),width:t.stroke.width}:void 0;return{fill:yt.fromHex(t.fill),stroke:e}};class kt extends E{constructor(t){var e;super("stroke"),this.parts=t.map((t=>{const e=vt.fromRenderable(t),n=this.bboxForPart(e.bbox,t.style);return this.contentBBox?this.contentBBox=this.contentBBox.union(n):this.contentBBox=n,{path:e,bbox:n,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=n.bbox;e&&!r.intersects(e)||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,bbox:i,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:vt.empty}description(t){return t.stroke}createClone(){return new kt(this.parts)}serializeToString(){return JSON.stringify(this.parts.map((t=>({style:wt(t.style),path:t.path.serialize()}))))}static deserializeFromString(t){const e=JSON.parse(t);if("object"!=typeof e||"number"!=typeof e.length)throw new Error(`${t} is missing required field, parts, or parts is of the wrong type.`);const n=e.map((t=>{const e=Tt(t.style);return vt.fromString(t.path).toRenderable(e)}));return new kt(n)}}E.registerComponent("stroke",kt.deserializeFromString);const St=(t,e)=>{const n=e.screenToCanvasTransform,r=7*n.transformVec3(k.unitX).magnitude(),i=2*n.transformVec3(k.unitX).magnitude();return new Ct(t,i,r)};class Ct{constructor(t,e,n){this.startPoint=t,this.minFitAllowed=e,this.maxFitAllowed=n,this.currentCurve=null,this.lastPoint=this.startPoint,this.segments=[],this.buffer=[this.startPoint.pos],this.momentum=k.zero,this.currentCurve=null,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}}getPreview(){if(this.currentCurve&&this.lastPoint){const t=this.currentSegmentToPath();return this.segments.concat(t)}return this.segments}preview(t){for(const e of this.getPreview())t.drawPath(e)}build(){return this.lastPoint&&this.finalizeCurrentCurve(),new kt(this.segments)}roundPoint(t){return V.roundPoint(t,this.minFitAllowed)}finalizeCurrentCurve(){if(!this.currentCurve){if(this.segments.length>0)return;const t=V.roundPoint(this.startPoint.width/3,this.minFitAllowed),e=this.roundPoint(this.startPoint.pos);return void this.segments.push({startPoint:this.startPoint.pos.plus(k.of(t,0)),commands:[{kind:xt.QuadraticBezierTo,controlPoint:e.plus(k.of(t,t)),endPoint:e.plus(k.of(0,t))},{kind:xt.QuadraticBezierTo,controlPoint:e.plus(k.of(-t,t)),endPoint:e.plus(k.of(-t,0))},{kind:xt.QuadraticBezierTo,controlPoint:e.plus(k.of(-t,-t)),endPoint:e.plus(k.of(0,-t))},{kind:xt.QuadraticBezierTo,controlPoint:e.plus(k.of(t,-t)),endPoint:e.plus(k.of(t,0))}],style:this.getRenderingStyle()})}this.segments.push(this.currentSegmentToPath());const t=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()),this.buffer=[this.buffer[this.buffer.length-2],t],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 gt(n.plus(t.times(o)),i.plus(s.times(o)),r.plus(e.times(o))),c=l(1,a),h=l(-1,a);c.intersects(h).length>0&&(a=a.times(2));const d=[{kind:xt.QuadraticBezierTo,controlPoint:this.roundPoint(i.plus(a)),endPoint:this.roundPoint(r.plus(e))},{kind:xt.LineTo,point:this.roundPoint(r.minus(e))},{kind:xt.QuadraticBezierTo,controlPoint:this.roundPoint(i.minus(a)),endPoint:this.roundPoint(n.minus(t))}];return{startPoint:this.roundPoint(n.plus(t)),commands:d,style:this.getRenderingStyle()}}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)/4;if(this.startPoint.pos.minus(t.pos).magnitude()<r&&0===this.segments.length)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 gt(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 z(l,l.plus(s.times(d))),p=new z(c.minus(a.times(d)),c).intersection(u);let f;f=p?p.point:l.plus(s.times(h/4)),(isNaN(f.magnitude())||isNaN(l.magnitude()))&&console.error("controlPoint is NaN",p,"Start:",l,"End:",c,"in:",s,"out:",a);const m=this.currentCurve;this.currentCurve=new gt(l.xy,f.xy,c.xy),isNaN(k.ofXY(this.currentCurve.normal(0)).magnitude())&&(console.error("NaN normal at 0. Curve:",this.currentCurve),this.currentCurve=m);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)/2,this.minFitAllowed)||n>this.maxFitAllowed)return!1}return!0};return this.buffer.length>3&&!g(this.currentCurve)?(this.currentCurve=m,this.curveEndWidth=o,this.lastPoint=r,void this.finalizeCurrentCurve()):void 0}}class Pt extends W{constructor(t,e,n){super(t.notifier,e),this.editor=t,this.style=n,this.builder=null,this.builderFactory=St,this.lastPoint=null,this.kind=Wt.Pen}getPressureMultiplier(){return 1/this.editor.viewport.getScaleFactor()*this.style.thickness}getStrokePoint(t){var e;const n=Math.max(null!==(e=t.pressure)&&void 0!==e?e:1,.3);return{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}){return t.device!==O.Eraser&&((1===e.length||t.device===O.Pen)&&(this.builder=this.builderFactory(this.getStrokePoint(t),this.editor.viewport),!0))}onPointerMove({current:t}){this.addPointToStroke(this.getStrokePoint(t))}onPointerUp({current:t}){var e,n;if(!this.builder)return;const r=this.getStrokePoint(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=L.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(I.ToolUpdated,{kind:I.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}}class Et{constructor(){}notifyEnabled(t){var e;t!==this.activeTool&&(null===(e=this.activeTool)||void 0===e||e.setEnabled(!1),this.activeTool=t)}}const zt=(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 Rt extends w{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)||L.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){var e;if(0===this.toRemove.length)return t.erasedNoElements;const n=null!==(e=zt(t,this.toRemove))&&void 0!==e?e:t.elements;return t.eraseAction(n,this.toRemove.length)}serializeToString(){const t=this.toRemove.map((t=>t.getId()));return JSON.stringify(t)}}w.register("erase",((t,e)=>{const n=JSON.parse(t).map((t=>e.image.lookupElement(t)));return new Rt(n)}));class Bt extends W{constructor(t,e){super(t.notifier,e),this.editor=t,this.command=null,this.kind=Wt.Eraser}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 z(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 Rt(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 Lt extends w{constructor(t){super("duplicate"),this.toDuplicate=t,this.duplicates=t.map((t=>t.clone())),this.reverse=new Rt(this.duplicates)}apply(t){this.reverse.unapply(t)}unapply(t){this.reverse.apply(t)}description(t){var e;return 0===this.duplicates.length?t.duplicatedNoElements:t.duplicateAction(null!==(e=zt(t,this.duplicates))&&void 0!==e?e:t.elements,this.duplicates.length)}serializeToString(){return JSON.stringify(this.toDuplicate.map((t=>t.getId())))}}w.register("duplicate",((t,e)=>{const n=JSON.parse(t).map((t=>e.image.lookupElement(t)));return new Lt(n)}));var Mt=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 At=30,It=(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 Ot{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,It(n,(t=>{this.handleBackgroundDrag(t)}),(()=>this.finalizeTransform())),It(r,(t=>{this.handleResizeCornerDrag(t)}),(()=>this.finalizeTransform())),It(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 Ot.ApplyTransformationCommand(this,r,t,e,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}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*(At/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(new V.ViewportTransform(P.translation(n.times(-1))),!1)}}deleteSelectedObjects(){return new Rt(this.selectedElems)}duplicateSelectedObjects(){return new Lt(this.selectedElems)}}Ot.ApplyTransformationCommand=class extends b{constructor(t,e,n,r,i){super(),this.selection=t,this.currentTransfmCommands=e,this.fullTransform=n,this.inverseTransform=r,this.deltaBoxRotation=i}apply(t){return Mt(this,void 0,void 0,(function*(){this.selection.region=this.selection.region.transformedBoundingBox(this.fullTransform),this.selection.boxRotation+=this.deltaBoxRotation,this.selection.updateUI(),yield t.asyncApplyCommands(this.currentTransfmCommands,100),this.selection.recomputeRegion(),this.selection.updateUI()}))}unapply(t){return Mt(this,void 0,void 0,(function*(){this.selection.region=this.selection.region.transformedBoundingBox(this.inverseTransform),this.selection.boxRotation-=this.deltaBoxRotation,this.selection.updateUI(),yield t.asyncUnapplyCommands(this.currentTransfmCommands,100),this.selection.recomputeRegion(),this.selection.updateUI()}))}description(t){return t.transformedElements(this.currentTransfmCommands.length)}};class Dt extends W{constructor(t,e){super(t.notifier,e),this.editor=t,this.kind=Wt.Selection,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(I.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)}onPointerDown(t){return!(1!==t.allPointers.length||!t.current.isPrimary)&&(this.prevSelectionBox=this.selectionBox,this.selectionBox=new Ot(t.current.canvasPos,this.editor),this.handleOverlay.replaceChildren(),this.selectionBox.appendBackgroundBoxTo(this.handleOverlay),!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(I.ToolUpdated,{kind:I.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 s}onKeyUp(t){return!(!this.selectionBox||!Dt.handleableKeys.some((e=>e===t.key)))&&(this.selectionBox.finalizeTransform(),!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.ariaLabel=this.editor.localization.selectionToolKeyboardShortcuts):this.handleOverlay.tabIndex=-1}getSelection(){return this.selectionBox}clearSelection(){this.handleOverlay.replaceChildren(),this.prevSelectionBox=this.selectionBox,this.selectionBox=null,this.editor.notifier.dispatch(I.ToolUpdated,{kind:I.ToolUpdated,tool:this})}}Dt.handleableKeys=["a","h","ArrowLeft","d","l","ArrowRight","q","k","ArrowUp","e","j","ArrowDown","r","R","i","I","o","O"];class Nt extends W{constructor(t){super(t.notifier,t.localization.undoRedoTool),this.editor=t,this.kind=Wt.UndoRedoShortcut}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 $t="text";class jt extends E{constructor(t,e,n,r=jt.getTextDimens){super($t),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=jt.textMeasuringCtx)&&void 0!==n||(jt.textMeasuringCtx=document.createElement("canvas").getContext("2d"));const r=jt.textMeasuringCtx;jt.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 z(n,r);for(const e of this.textObjects)if("string"==typeof e){if(jt.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 jt(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())}serializeToString(){const t=Object.assign(Object.assign({},this.style),{renderingStyle:wt(this.style.renderingStyle)}),e=this.textObjects.map((t=>"string"==typeof t?{text:t}:{json:t.serializeToString()}));return JSON.stringify({textObjects:e,transform:this.transform.toArray(),style:t})}static deserializeFromString(t,e=jt.getTextDimens){const n=JSON.parse(t),r={renderingStyle:Tt(n.style.renderingStyle),size:n.style.size,fontWeight:n.style.fontWeight,fontVariant:n.style.fontVariant,fontFamily:n.style.fontFamily},i=n.textObjects.map((t=>{var e;return null!==(null!==(e=t.text)&&void 0!==e?e:null)?t.text:jt.deserializeFromString(t.json)}));if(n.transform=n.transform.filter((t=>"number"==typeof t)),9!==n.transform.length)throw new Error(`Unable to deserialize transform, ${n.transform}.`);const o=n.transform,s=new P(...o);return new jt(i,s,r,e)}}E.registerComponent($t,(t=>jt.deserializeFromString(t)));const Ft="textEditorOverlay";class Ut extends W{constructor(t,e,n){super(t.notifier,e),this.editor=t,this.localizationTable=n,this.kind=Wt.Text,this.textInputElem=null,this.textTargetPosition=null,this.textMeasuringCtx=null,this.textStyle={size:32,fontFamily:"sans-serif",renderingStyle:{fill:yt.purple}},this.textEditOverlay=document.createElement("div"),this.textEditOverlay.classList.add(Ft),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(I.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?(jt.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 jt([t],e,this.textStyle),r=L.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(I.ToolUpdated,{kind:I.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 Vt extends W{constructor(t,e){super(t.notifier,e),this.editor=t,this.kind=Wt.Pipette,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)}}var Wt;!function(t){t[t.Pen=0]="Pen",t[t.Selection=1]="Selection",t[t.Eraser=2]="Eraser",t[t.PanZoom=3]="PanZoom",t[t.Text=4]="Text",t[t.UndoRedoShortcut=5]="UndoRedoShortcut",t[t.Pipette=6]="Pipette",t[t.Other=7]="Other"}(Wt||(Wt={}));class _t{constructor(t,e){const n=new Et,r=new H(t,_.TwoFingerTouchGestures|_.RightClickDrags,e.touchPanTool),i=new H(t,_.Keyboard,e.keyboardPanZoom),o=new Pt(t,e.penTool(1),{color:yt.purple,thickness:16}),s=[new Dt(t,e.selectionTool),new Bt(t,e.eraserTool),o,new Pt(t,e.penTool(2),{color:yt.clay,thickness:8}),new Pt(t,e.penTool(3),{color:yt.ofRGBA(1,1,0,.5),thickness:64}),new Ut(t,e.textTool,e)];this.tools=[new Vt(t,e.pipetteTool),r,...s,i,new Nt(t)],s.forEach((t=>t.setToolGroup(n))),r.setEnabled(!0),o.setEnabled(!0),t.notifier.on(I.ToolEnabled,(n=>{n.kind===I.ToolEnabled&&t.announceForAccessibility(e.toolEnabledAnnouncement(n.tool.description))})),t.notifier.on(I.ToolDisabled,(n=>{n.kind===I.ToolDisabled&&t.announceForAccessibility(e.toolDisabledAnnouncement(n.tool.description))})),this.activeTool=null}dispatchInputEvent(t){var e,n;let r=!1;if(t.kind===A.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===A.PointerUpEvt)null===(n=this.activeTool)||void 0===n||n.onPointerUp(t),this.activeTool=null,r=!0;else if(t.kind===A.WheelEvt||t.kind===A.KeyPressEvent||t.kind===A.KeyUpEvent){const e=t.kind===A.KeyPressEvent,n=t.kind===A.KeyUpEvent,i=t.kind===A.WheelEvt;for(const o of this.tools){if(!o.isEnabled())continue;const s=i&&o.onWheel(t),a=e&&o.onKeyPress(t),l=n&&o.onKeyUp(t);if(r=a||s||l,r)break}}else if(null!==this.activeTool){let e;switch(t.kind){case A.PointerMoveEvt:this.activeTool.onPointerMove(t);break;case A.GestureCancelEvt:this.activeTool.onGestureCancel(),this.activeTool=null;break;default:return e=t,e}r=!0}else r=!1;return r}getMatchingTools(t){return this.tools.filter((e=>e.kind===t))}}const Ht=class{constructor(t,e,n){this.editor=t,this.announceRedoCallback=e,this.announceUndoCallback=n,this.undoStack=[],this.redoStack=[]}fireUpdateEvent(){this.editor.notifier.dispatch(I.UndoRedoStackUpdated,{kind:I.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);this.redoStack=[],this.fireUpdateEvent()}undo(){const t=this.undoStack.pop();t&&(this.redoStack.push(t),t.unapply(this.editor),this.announceUndoCallback(t)),this.fireUpdateEvent()}redo(){const t=this.redoStack.pop();t&&(this.undoStack.push(t),t.apply(this.editor),this.announceRedoCallback(t)),this.fireUpdateEvent()}get undoStackSize(){return this.undoStack.length}get redoStackSize(){return this.redoStack.length}};class Gt{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 qt=function(t,e,n){var r,i,o,s,a,l,c,h,d,u,p,f,m,g,x,v=e.createElement("canvas").getContext("2d"),y={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="",k={},S=!1;function C(n){if("object"==typeof n)for(var s in n)switch(s){case"el":R(n.el),!1!==n.wrap&&L(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&&L(n.el);break;case"formatToggle":b.formatToggle=!!n.formatToggle,_("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>")})),_("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;g=I(a),B(),A(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,f=!1;if("object"==typeof u)for(var m in u)u[m]&&b.a11y[m]&&(b.a11y[m]=u[m],f=!0);if(f){var x=_("clr-open-label"),v=_("clr-swatch-label");x.innerHTML=b.a11y.open,v.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 P(t,e){"string"==typeof t&&"object"==typeof e&&(w[t]=e,S=!0)}function E(t){delete w[t],0===Object.keys(w).length&&(S=!1,t===T&&z())}function z(){Object.keys(k).length>0&&(C(k),T="",k={})}function R(t){H(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,k={},e.forEach((function(t){return delete r[t]})),r)k[i]=Array.isArray(b[i])?b[i].slice():b[i];return C(r),"break"}};for(var r in w)if("break"===n(r))break}}(t.target),m=t.target,x=m.value,g=I(x),i.classList.add("clr-open"),B(),A(x),(b.focusInput||b.selectInput)&&c.focus({preventScroll:!0}),b.selectInput&&c.select(),m.dispatchEvent(new Event("open",{bubbles:!0})))})),H(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},f={x:0,y:0};if(c&&(n=t.getComputedStyle(c),a=parseFloat(n.marginTop),l=parseFloat(n.borderTopWidth),(f=c.getBoundingClientRect()).y+=l+h),!b.inline){var g=m.getBoundingClientRect(),x=g.x,v=h+g.y+g.height+b.margin;c?(x-=f.x,v-=f.y,x+d>c.clientWidth&&(x+=g.width-d,p.left=!0),v+u>c.clientHeight-a&&u+b.margin<=g.top-(f.y-h)&&(v-=g.height+u+2*b.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+b.margin<=g.top&&(v=h+g.y-u-b.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+f.x,y:i.offsetTop+o.offsetTop+f.y}}function L(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 M(t){m&&!b.inline&&(t&&x!==m.value&&(m.value=x,m.dispatchEvent(new Event("input",{bubbles:!0}))),x!==m.value&&m.dispatchEvent(new Event("change",{bubbles:!0})),i.classList.remove("clr-open"),S&&z(),m.dispatchEvent(new Event("close",{bubbles:!0})),b.focusInput&&m.focus({preventScroll:!0}),m=null)}function A(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);N(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,f.style.left=100*r.a+"%"}function I(t){var e=t.substring(0,3).toLowerCase();return"rgb"===e||"hsl"===e?e:"hex"}function O(t){t=void 0!==t?t:c.value,m&&(m.value=t,m.dispatchEvent(new Event("input",{bubbles:!0}))),e.dispatchEvent(new CustomEvent("coloris:pick",{detail:{color:t}}))}function D(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);N(r.s,r.v),F(i,r),O()}function N(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 $(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",D(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",D(n,r)}function F(t,r){void 0===t&&(t={}),void 0===r&&(r={});var i=b.format;for(var s in t)y[s]=t[s];for(var h in r)y[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}(y),p=u.substring(0,7);switch(a.style.color=p,f.parentNode.style.color=p,f.style.color=u,l.style.color=u,o.style.display="none",o.offsetHeight,o.style.display="",f.nextElementSibling.style.display="none",f.nextElementSibling.offsetHeight,f.nextElementSibling.style.display="","mixed"===i?i=1===y.a?"hex":"rgb":"auto"===i&&(i=g),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+")"}(y);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}}(y),!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 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+"%",D(e,n)}function V(){var t=p.value/100;f.style.left=100*t+"%",F({a:t}),O()}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=_("clr-color-area"),a=_("clr-color-marker"),h=_("clr-clear"),l=_("clr-color-preview"),c=_("clr-color-value"),d=_("clr-hue-slider"),u=_("clr-hue-marker"),p=_("clr-alpha-slider"),f=_("clr-alpha-marker"),R(b.el),L(b.el),H(i,"mousedown",(function(t){i.classList.remove("clr-keyboard-nav"),t.stopPropagation()})),H(o,"mousedown",(function(t){H(e,"mousemove",$)})),H(o,"touchstart",(function(t){e.addEventListener("touchmove",$,{passive:!1})})),H(a,"mousedown",(function(t){H(e,"mousemove",$)})),H(a,"touchstart",(function(t){e.addEventListener("touchmove",$,{passive:!1})})),H(c,"change",(function(t){A(c.value),O()})),H(h,"click",(function(t){O(""),M()})),H(l,"click",(function(t){O(),M()})),H(e,"click",".clr-format input",(function(t){g=t.target.value,F(),O()})),H(i,"click",".clr-swatches button",(function(t){A(t.target.textContent),O(),b.swatchesOnly&&M()})),H(e,"mouseup",(function(t){e.removeEventListener("mousemove",$)})),H(e,"touchend",(function(t){e.removeEventListener("touchmove",$)})),H(e,"mousedown",(function(t){i.classList.remove("clr-keyboard-nav"),M()})),H(e,"keydown",(function(t){"Escape"===t.key?M(!0):"Tab"===t.key&&i.classList.add("clr-keyboard-nav")})),H(e,"click",".clr-field button",(function(t){S&&z(),t.target.nextElementSibling.dispatchEvent(new Event("click",{bubbles:!0}))})),H(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())})),H(o,"click",$),H(d,"input",U),H(p,"input",V)}function _(t){return e.getElementById(t)}function H(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 G(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:C,wrap:L,close:M,setInstance:P,removeInstance:E,updatePosition:B};function e(t){G((function(){t&&("string"==typeof t?R(t):C(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];G(t[n],r)}};for(var r in t)n(r);return e}();return q.coloris=q,q}(window,document,Math),Zt=qt.coloris,Kt=qt.init;qt.set,qt.wrap,qt.close;const Xt={pen:"Pen",eraser:"Eraser",select:"Select",handTool:"Pan",zoom:"Zoom",thicknessLabel:"Thickness: ",colorLabel:"Color: ",fontLabel:"Font: ",resizeImageToSelection:"Resize image to selection",deleteSelection:"Delete selection",duplicateSelection:"Duplicate selection",undo:"Undo",redo:"Redo",selectObjectType:"Object type: ",pickColorFronScreen:"Pick color from screen",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}`},Yt="svg-global-attributes";class Qt extends E{constructor(t){super(Yt),this.attrs=t,this.contentBBox=R.empty}render(t,e){if(t instanceof le)for(const[e,n]of this.attrs)t.setRootSVGAttribute(e,n)}intersects(t){return!1}applyTransformation(t){}createClone(){return new Qt(this.attrs)}description(t){return t.svgObject}serializeToString(){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 Qt(n)}}E.registerComponent(Yt,Qt.deserializeFromString);const Jt="unknown-svg-object";class te extends E{constructor(t){super(Jt),this.svgObject=t,this.contentBBox=R.of(t.getBoundingClientRect())}render(t,e){t instanceof le&&t.drawSVGElem(this.svgObject)}intersects(t){return this.contentBBox.getEdges().some((e=>null!==e.intersection(t)))}applyTransformation(t){}createClone(){return new te(this.svgObject.cloneNode(!0))}description(t){return t.svgObject}serializeToString(){return JSON.stringify({html:this.svgObject.outerHTML})}}E.registerComponent(Jt,null);var ee=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 ne=new R(0,0,500,500),re="svgAttrs",ie="svgStyleAttrs";class oe{constructor(t,e){this.source=t,this.onFinish=e,this.onAddComponent=null,this.onProgress=null,this.onDetermineExportRect=null,this.processedCount=0,this.totalToProcess=0}getStyle(t){var e,n,r;const i={fill:yt.transparent},o=null!==(e=t.getAttribute("fill"))&&void 0!==e?e:t.style.fill;if(o)try{i.fill=yt.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:yt.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=vt.fromString(e).toRenderable(i);n.push(r)}s=!1}return n}attachUnrecognisedAttrs(t,e,n,r){for(const i of e.getAttributeNames())n.has(i)||"style"===i&&r||t.attachLoadSaveData(re,[i,e.getAttribute(i)]);if(r)for(const n of e.style)""!==n&&n&&(r.has(n)||t.attachLoadSaveData(ie,{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 kt(e);const r=["stroke","fill","stroke-width"];this.attachUnrecognisedAttrs(n,t,new Set([...r,"d"]),new Set(r))}catch(e){console.error("Invalid path in node",t,"\nError:",e,"\nAdding as an unknown object."),n=new te(t)}null===(e=this.onAddComponent)||void 0===e||e.call(this,n)}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:yt.fromString(r.fill)}};let l=r.transform;""!==l&&"none"!==l||(l=t.style.transform||"none");let c=P.fromCSSMatrix(l);const h=[],d=t.getAttribute("x"),u=t.getAttribute("y");if(d&&u){const t=parseFloat(d),e=parseFloat(u);isNaN(t)||isNaN(e)||(h.push("x","y"),c=c.rightMul(P.translation(k.of(t,e))))}const p=new jt(n,c,a);return this.attachUnrecognisedAttrs(p,t,new Set(h),new Set(o)),p}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,". Adding as an unknown object. Error:",e),this.addUnknownNode(t)}}addUnknownNode(t){var e;const n=new te(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;null===(e=this.onAddComponent)||void 0===e||e.call(this,new Qt(this.getSourceAttrs(t)))}visit(t){var e;return ee(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"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! Continuing anyway."),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 ee(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,ne),null===(i=this.onFinish)||void 0===i||i.call(this)}))}static fromString(t){var e,n;const r=document.createElement("iframe");if(r.src="about:blank",r.setAttribute("sandbox","allow-same-origin"),r.setAttribute("csp","default-src 'about:blank'"),r.style.display="none",document.body.appendChild(r),!r.hasAttribute("sandbox"))throw r.remove(),new Error("SVG loading iframe is not sandboxed.");const i=null!==(n=null===(e=r.contentWindow)||void 0===e?void 0:e.document)&&void 0!==n?n:r.contentDocument;if(null==i)throw new Error("Unable to open a sandboxed iframe!");i.open(),i.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"),i.close();const o=i.createElementNS("http://www.w3.org/2000/svg","svg");return o.innerHTML=t,i.body.appendChild(o),new oe(o,(()=>{o.remove(),r.remove()}))}}class se{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&&bt(t,i)?this.moveTo(n):(t&&this.endPath(t),this.beginPath(n),t=i);for(const t of r)t.kind===xt.LineTo?this.lineTo(t.point):t.kind===xt.MoveTo?this.moveTo(t.point):t.kind===xt.CubicBezierTo?this.traceCubicBezierCurve(t.controlPoint1,t.controlPoint2,t.endPoint):t.kind===xt.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=vt.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 ae="http://www.w3.org/2000/svg";class le extends se{constructor(t,e){super(e),this.elem=t,this.objectElems=null,this.overwrittenAttrs={},this.clear()}setRootSVGAttribute(t,e){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(){for(const t in this.overwrittenAttrs){const e=this.overwrittenAttrs[t];e?this.elem.setAttribute(t,e):this.elem.removeAttribute(t)}this.overwrittenAttrs={}}beginPath(t){var e;this.currentPath=[],this.pathStart=this.canvasToScreen(t),null!==(e=this.lastPathStart)&&void 0!==e||(this.lastPathStart=this.pathStart)}endPath(t){var e;if(null==this.currentPath)throw new Error("No path exists to end! Make sure beginPath was called!");t.fill.eq(null===(e=this.lastPathStyle)||void 0===e?void 0:e.fill)&&null!=this.lastPath?(this.lastPath.push({kind:xt.MoveTo,point:this.pathStart},...this.currentPath),this.pathStart=null,this.currentPath=null):(this.addPathToSVG(),this.lastPathStart=this.pathStart,this.lastPathStyle=t,this.lastPath=this.currentPath,this.pathStart=null,this.currentPath=null)}addPathToSVG(){var t;if(!this.lastPathStyle||!this.lastPath)return;const e=document.createElementNS(ae,"path");e.setAttribute("d",vt.toString(this.lastPathStart,this.lastPath));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)}drawText(t,e,n){var r,i,o;e=this.getCanvasToScreenTransform().rightMul(e);const s=document.createElementNS(ae,"text");if(s.appendChild(document.createTextNode(t)),s.style.transform=`matrix(\n\t\t\t${e.a1}, ${e.b1},\n\t\t\t${e.a2}, ${e.b2},\n\t\t\t${e.a3}, ${e.b3}\n\t\t)`,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)}startObject(t){super.startObject(t),this.lastPath=null,this.lastPathStart=null,this.lastPathStyle=null,this.objectElems=[]}endObject(t){var e;if(super.endObject(t),this.addPathToSVG(),t)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)}}lineTo(t){t=this.canvasToScreen(t),this.currentPath.push({kind:xt.LineTo,point:t})}moveTo(t){t=this.canvasToScreen(t),this.currentPath.push({kind:xt.MoveTo,point:t})}traceCubicBezierCurve(t,e,n){t=this.canvasToScreen(t),e=this.canvasToScreen(e),n=this.canvasToScreen(n),this.currentPath.push({kind:xt.CubicBezierTo,controlPoint1:t,controlPoint2:e,endPoint:n})}traceQuadraticBezierCurve(t,e){t=this.canvasToScreen(t),e=this.canvasToScreen(e),this.currentPath.push({kind:xt.QuadraticBezierTo,controlPoint:t,endPoint:e})}drawPoints(...t){t.map((t=>{const e=document.createElementNS(ae,"circle");e.setAttribute("cx",`${t.x}`),e.setAttribute("cy",`${t.y}`),e.setAttribute("r","15"),this.elem.appendChild(e)}))}drawSVGElem(t){this.elem.appendChild(t.cloneNode(!0))}isTooSmallToRender(t){return!1}}const ce="http://www.w3.org/2000/svg",he="\n\tstyle='fill: var(--icon-color);'\n",de="\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",ue="url(#checkerboard)",pe=(t=!1)=>{const e=document.createElementNS(ce,"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(ce,"svg");return t.innerHTML="\n\t\t<path\n\t\t\td='\n\t\t\t\tM 5,5.5\n\t\t\t\tV 17.2\n\t\t\t\tL 16.25,5.46\n\t\t\t\tZ\n\n\t\t\t\tm 33.75,0\n\t\t\t\tL 50,17\n\t\t\t\tV 5.5\n\t\t\t\tZ\n\n\t\t\t\tM 5,40.7\n\t\t\t\tv 11.7\n\t\t\t\th 11.25\n\t\t\t\tz\n\t\t\t\t\n\t\t\t\tM 26,19\n\t\t\t\tC 19.8,19.4 17.65,30.4 21.9,34.8\n\t\t\t\tL 50,70\n\t\t\t\tH 27.5\n\t\t\t\tc -11.25,0 -11.25,17.6 0,17.6\n\t\t\t\tH 61.25\n\t\t\t\tC 94.9,87.8 95,87.6 95,40.7 78.125,23 67,29 55.6,46.5\n\t\t\t\tL 33.1,23\n\t\t\t\tC 30.3125,20.128192 27.9,19 25.830078,19.119756\n\t\t\t\tZ\n\t\t\t'\n\t\t\tfill='none'\n\t\t\tstyle='\n\t\t\t\tstroke: var(--icon-color);\n\t\t\t\tstroke-width: 2;\n\t\t\t'\n\t\t/>\n\t",t.setAttribute("viewBox","0 0 100 100"),t},me=()=>{const t=document.createElementNS(ce,"svg");return t.innerHTML="\n\t\t<path\n\t\t\td='\n\t\t\t\tM 5 5\n\t\t\t\tL 5 17.5\n\t\t\t\t 17.5 5\n\t\t\t\t 5 5\n\t\t\t\tz\n\t\t\t\t\n\t\t\t\tM 42.5 5\n\t\t\t\tL 55 17.5\n\t\t\t\t 55 5\n\t\t\t\t 42.5 5\n\t\t\t\tz\n\t\t\t\t\n\t\t\t\tM 70 10\n\t\t\t\tL 70 21\n\t\t\t\t 61 15\n\t\t\t 55.5 23\n\t\t\t 66 30\n\t\t\t\t 56 37\n\t\t\t\t 61 45\n\t\t\t\t 70 39\n\t\t\t\t 70 50\n\t\t\t\t 80 50\n\t\t\t\t 80 39\n\t\t\t\t 89 45\n\t\t\t\t 95 36\n\t\t\t\t 84 30\n\t\t\t\t 95 23\n\t\t\t\t 89 15\n\t\t\t\t 80 21\n\t\t\t\t 80 10\n\t\t\t\t 70 10\n\t\t\t\tz\n\n\t\t\t\tM 27.5 26.25\n\t\t\t\tL 27.5 91.25\n\t\t\t\tL 43.75 83.125\n\t\t\t\tL 52 99\n\t\t\t\tL 68 91\n\t\t\t\tL 60 75\n\t\t\t\tL 76.25 66.875\n\t\t\t\tL 27.5 26.25\n\t\t\t\tz\n\t\t\t\t\n\t\t\t\tM 5 42.5\n\t\t\t\tL 5 55\n\t\t\t\tL 17.5 55\n\t\t\t\tL 5 42.5\n\t\t\t\tz \n\t\t\t'\n\t\t\tfill='none'\n\t\t\tstyle='\n\t\t\t\tstroke: var(--icon-color);\n\t\t\t\tstroke-width: 2;\n\t\t\t'\n\t\t/>\n\t",t.setAttribute("viewBox","0 0 100 100"),t},ge=(t,e)=>new xe(t);class xe{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 kt([{startPoint:a.minus(h),commands:[{kind:xt.LineTo,point:t.minus(c)},{kind:xt.LineTo,point:t.plus(c)},{kind:xt.LineTo,point:a.plus(h)},{kind:xt.LineTo,point:a.plus(l.times(i).plus(h))},{kind:xt.LineTo,point:e.plus(n.times(s))},{kind:xt.LineTo,point:a.plus(l.times(-i).minus(h))},{kind:xt.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 ve=(t,e)=>new ye(t);class ye{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 kt([{startPoint:t.minus(s),commands:[{kind:xt.LineTo,point:t.plus(s)},{kind:xt.LineTo,point:e.plus(a)},{kind:xt.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 be=(t,e)=>new Te(t,!0,e),we=(t,e)=>new Te(t,!1,e);class Te{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=vt.fromRect(i,this.filled?null:this.endPoint.width).transformedBy(e);return new kt([o.toRenderable({fill:this.endPoint.color})])}build(){return this.buildPreview()}preview(t){this.buildPreview().render(t)}addPoint(t){this.endPoint=t}}const ke=(t,e,n)=>{const r=document.createElement("button");r.classList.add("pipetteButton"),r.title=t.localization.pickColorFronScreen,r.setAttribute("alt",r.title);const i=t=>{r.replaceChildren((t=>{const e=document.createElementNS(ce,"svg"),n=document.createElementNS(ce,"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(ce,"defs");n.innerHTML=de,e.appendChild(n);const r=document.createElementNS(ce,"path"),i=document.createElementNS(ce,"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=ue,e.appendChild(r),e.appendChild(i)}return e.appendChild(n),e.setAttribute("viewBox","0 0 100 100"),e})(t))};i();const o=t.toolController.getMatchingTools(Wt.Pipette)[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"))},e.appendChild(r)},Se=(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),ke(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=yt.fromHex(r.value)},s=()=>{o(),i&&(t.announceForAccessibility(t.localization.colorChangedAnnouncement(i.toHexString())),e(i),t.notifier.dispatch(I.ColorPickerColorSelected,{kind:I.ColorPickerColorSelected,color:i}))};return r.oninput=o,r.addEventListener("open",(()=>{t.notifier.dispatch(I.ColorPickerToggled,{kind:I.ColorPickerToggled,open:!0})})),r.addEventListener("close",(()=>{t.notifier.dispatch(I.ColorPickerToggled,{kind:I.ColorPickerToggled,open:!1}),s()})),[r,n]};var Ce,Pe=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},Ee=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 ze{constructor(t,e){this.editor=t,this.localizationTable=e,Ce.set(this,void 0),this.disabled=!1,this.subWidgets=[],this.icon=null,this.container=document.createElement("div"),this.container.classList.add(`${Ne}toolContainer`),this.dropdownContainer=document.createElement("div"),this.dropdownContainer.classList.add(`${Ne}dropdown`),this.dropdownContainer.classList.add("hidden"),Pe(this,Ce,!1,"f"),this.button=document.createElement("div"),this.button.classList.add(`${Ne}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);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:A.KeyPressEvent,key:t.key,ctrlKey:t.ctrlKey})},t.onkeyup=t=>{t.key in e||this.editor.toolController.dispatchInputEvent({kind:A.KeyUpEvent,key:t.key,ctrlKey:t.ctrlKey})},t.onclick=()=>{this.disabled||this.handleClick()}}get hasDropdown(){return Ee(this,Ce,"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),Pe(this,Ce,this.fillDropdown(this.dropdownContainer),"f"),Ee(this,Ce,"f")&&(this.dropdownIcon=this.createDropdownIcon(),this.button.appendChild(this.dropdownIcon),this.container.appendChild(this.dropdownContainer)),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(`${Ne}icon`)}setDisabled(t){this.disabled=t,this.disabled?this.button.classList.add("disabled"):this.button.classList.remove("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.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="")}isDropdownVisible(){return!this.dropdownContainer.classList.contains("hidden")}isSelected(){return this.container.classList.contains("selected")}createDropdownIcon(){const t=(()=>{const t=document.createElementNS(ce,"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${he}\n\t\t/>\n\t</g>\n\t`,t.setAttribute("viewBox","0 0 100 100"),t})();return t.classList.add(`${Ne}showHideDropdownIcon`),t}}Ce=new WeakMap;class Re extends ze{constructor(t,e,n){super(t,n),this.editor=t,this.targetTool=e,this.localizationTable=n,t.notifier.on(I.ToolEnabled,(t=>{if(t.kind!==I.ToolEnabled)throw new Error("Incorrect event type! (Expected ToolEnabled)");t.tool===e&&this.setSelected(!0)})),t.notifier.on(I.ToolDisabled,(t=>{if(t.kind!==I.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 Be extends Re{constructor(t,e,n){super(t,e,n),this.tool=e,this.updateInputs=()=>{},this.penTypes=[{name:n.freehandPen,factory:St},{name:n.arrowPen,factory:ge},{name:n.linePen,factory:ve},{name:n.filledRectanglePen,factory:be},{name:n.outlinedRectanglePen,factory:we}],this.editor.notifier.on(I.ToolUpdated,(t=>{if(t.kind!==I.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()===St){return((t,e)=>{const n=document.createElementNS(ce,"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${de}\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})(Math.round(4*Math.sqrt(this.tool.getThickness())),this.tool.getColor().toHexString())}{const t=this.tool.getStrokeFactory();return((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 V(new Gt),a=e(i,s);a.addPoint(o);const l=document.createElementNS(ce,"svg");l.setAttribute("viewBox","0 0 100 100"),s.updateScreenSize(k.of(100,100));const c=new le(l,s);return a.preview(c),l})(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=`${Ne}thicknessInput${Be.idCounter++}`,a.id=`${Ne}builderSelect${Be.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="1",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]=Se(this.editor,(t=>{this.tool.setColor(t)}));return h.id=`${Ne}colorInput${Be.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}}Be.idCounter=0;class Le extends Re{getTitle(){return this.localizationTable.eraser}createIcon(){return(()=>{const t=document.createElementNS(ce,"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${he}\n\t\t/>\n\t</g>\n\t`,t.setAttribute("viewBox","0 0 100 100"),t})()}fillDropdown(t){return!1}}class Me extends Re{constructor(t,e,n){super(t,e,n),this.tool=e}getTitle(){return this.localizationTable.select}createIcon(){return(()=>{const t=document.createElementNS(ce,"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})()}fillDropdown(t){const e=document.createElement("div"),n=document.createElement("button"),r=document.createElement("button"),i=document.createElement("button");return n.innerText=this.localizationTable.resizeImageToSelection,n.disabled=!0,i.innerText=this.localizationTable.deleteSelection,i.disabled=!0,r.innerText=this.localizationTable.duplicateSelection,r.disabled=!0,n.onclick=()=>{const t=this.tool.getSelection();this.editor.dispatch(this.editor.setImportExportRect(t.region))},i.onclick=()=>{const t=this.tool.getSelection();this.editor.dispatch(t.deleteSelectedObjects()),this.tool.clearSelection()},r.onclick=()=>{const t=this.tool.getSelection();this.editor.dispatch(t.duplicateSelectedObjects())},this.editor.notifier.on(I.ToolUpdated,(t=>{if(t.kind!==I.ToolUpdated)throw new Error("Invalid event type!");if(t.tool===this.tool){const t=this.tool.getSelection(),e=t&&t.region.area>0;n.disabled=!e,i.disabled=n.disabled,r.disabled=n.disabled}})),e.replaceChildren(n,r,i),t.appendChild(e),!0}}class Ae extends Re{constructor(t,e,n){super(t,e,n),this.tool=e,this.updateDropdownInputs=null,t.notifier.on(I.ToolUpdated,(t=>{var n;t.kind===I.ToolUpdated&&t.tool===e&&(this.updateIcon(),null===(n=this.updateDropdownInputs)||void 0===n||n.call(this))}))}getTitle(){return this.targetTool.description}createIcon(){return(t=>{var e,n;const r=document.createElementNS(ce,"svg");r.setAttribute("viewBox","0 0 100 100");const i=document.createElementNS(ce,"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})(this.tool.getTextStyle())}fillDropdown(t){const e=document.createElement("div"),n=document.createElement("div"),r=document.createElement("select"),i=document.createElement("label"),[o,s]=Se(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=`${Ne}-text-color-input-${Ae.idCounter++}`,a.setAttribute("for",o.id),c("monospace"),c("serif"),c("sans-serif"),r.id=`${Ne}-text-font-input-${Ae.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}}Ae.idCounter=0;class Ie extends ze{constructor(t,e){super(t,e),this.container.classList.add("dropdownShowable")}getTitle(){return this.localizationTable.zoom}createIcon(){return(()=>{const t=document.createElementNS(ce,"svg");t.setAttribute("viewBox","0 0 100 100");const e=(e,n,r)=>{const i=document.createElementNS(ce,"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})()}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("span");let s;r.innerText="+",i.innerText="-",n.replaceChildren(o,r,i),n.classList.add(`${Ne}zoomLevelEditor`),o.classList.add("zoomDisplay");const a=()=>{let n=100*e.viewport.getScaleFactor();n=n>.1?Math.round(10*n)/10:Math.round(1e3*n)/1e3,n!==s&&(o.innerText=t.zoomLevel(n),s=n)};a(),e.notifier.on(I.ViewportChanged,(t=>{t.kind===I.ViewportChanged&&a()}));const l=t=>{const n=e.viewport.visibleRect.center,r=P.scaling2D(t,n);e.dispatch(new V.ViewportTransform(r),!1)};return r.onclick=()=>{l(5/4)},i.onclick=()=>{l(.8)},n})(this.localizationTable,this.editor)),!0}}class Oe extends ze{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(I.ToolUpdated,(t=>{if(t.kind===I.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 De extends Re{constructor(t,e,n){super(t,e,n),this.tool=e,this.container.classList.add("dropdownShowable"),this.touchPanningWidget=new Oe(t,n,e,_.OneFingerTouchGestures,fe,n.touchPanning),this.addSubWidget(this.touchPanningWidget),this.addSubWidget(new Oe(t,n,e,_.SinglePointerGestures,me,n.anyDevicePanning)),this.addSubWidget(new Ie(t,n))}getTitle(){return this.localizationTable.handTool}createIcon(){return(()=>{const t=document.createElementNS(ce,"svg");return t.innerHTML="\n\t<g>\n\t\t<path d='\n\t\t\tm 10,60\n\t\t\t 5,30\n\t\t\tH 90\n\t\t\tV 30\n\t\t\tC 90,20 75,20 75,30\n\t\t\tV 60\n\t\t\t 20\n\t\t\tC 75,10 60,10 60,20\n\t\t\tV 60\n\t\t\t 15\n\t\t\tC 60,5 45,5 45,15\n\t\t\tV 60\n\t\t\t 25\n\t\t\tC 45,15 30,15 30,25\n\t\t\tV 60\n\t\t\t 75\n\t\t\tL 25,60\n\t\t\tC 20,45 10,50 10,60 \n\t\t\tZ'\n\t\t\t\n\t\t\tfill='none'\n\t\t\tstyle='\n\t\t\t\tstroke: var(--icon-color);\n\t\t\t\tstroke-width: 2;\n\t\t\t'\n\t\t/>\n\t</g>\n\t",t.setAttribute("viewBox","0 0 100 100"),t})()}setSelected(t){}handleClick(){this.setDropdownVisible(!this.isDropdownVisible())}}const Ne="toolbar-";class $e{constructor(t,e,n=Xt){this.editor=t,this.localizationTable=n,this.container=document.createElement("div"),this.container.classList.add(`${Ne}root`),this.container.setAttribute("role","toolbar"),e.appendChild(this.container),$e.colorisStarted||(Kt(),$e.colorisStarted=!0),this.setupColorPickers()}setupColorPickers(){const t=document.createElement("div");t.className=`${Ne}closeColorPickerOverlay`,this.editor.createHTMLOverlay(t);const e=[yt.red.toHexString(),yt.purple.toHexString(),yt.blue.toHexString(),yt.clay.toHexString(),yt.black.toHexString(),yt.white.toHexString()],n=e.length,r=()=>{Zt({el:".coloris_input",format:"hex",selectInput:!1,focusInput:!1,themeMode:"auto",swatches:e})};r();this.editor.notifier.on(I.ColorPickerToggled,(e=>{e.kind===I.ColorPickerToggled&&(t.style.display=e.open?"block":"none")})),this.editor.notifier.on(I.ColorPickerColorSelected,(t=>{t.kind===I.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())}))}addActionButton(t,e,n){const r=document.createElement("button");if(r.classList.add(`${Ne}toolButton`),"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(`${Ne}buttonGroup`);const e=this.addActionButton({label:this.localizationTable.undo,icon:pe(!0)},(()=>{this.editor.history.undo()}),t),n=this.addActionButton({label:this.localizationTable.redo,icon:pe()},(()=>{this.editor.history.redo()}),t);this.container.appendChild(t),e.disabled=!0,n.disabled=!0,this.editor.notifier.on(I.UndoRedoStackUpdated,(t=>{if(t.kind!==I.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(Wt.Pen)){if(!(e instanceof Pt))throw new Error("All `Pen` tools must have kind === ToolType.Pen");new Be(this.editor,e,this.localizationTable).addTo(this.container)}for(const e of t.getMatchingTools(Wt.Eraser)){if(!(e instanceof Bt))throw new Error("All Erasers must have kind === ToolType.Eraser!");new Le(this.editor,e,this.localizationTable).addTo(this.container)}for(const e of t.getMatchingTools(Wt.Selection)){if(!(e instanceof Dt))throw new Error("All SelectionTools must have kind === ToolType.Selection");new Me(this.editor,e,this.localizationTable).addTo(this.container)}for(const e of t.getMatchingTools(Wt.Text)){if(!(e instanceof Ut))throw new Error("All text tools must have kind === ToolType.Text");new Ae(this.editor,e,this.localizationTable).addTo(this.container)}const e=t.getMatchingTools(Wt.PanZoom)[0];e&&e instanceof H&&new De(this.editor,e,this.localizationTable).addTo(this.container),this.setupColorPickers()}addDefaultActionButtons(){this.addUndoRedoButtons()}}$e.colorisStarted=!1;class je extends se{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 je}renderFromOtherOfSameType(t,e){if(!(e instanceof je))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=64,this.minRenderSizeBothDimens=8,this.minRenderSizeAnyDimen=2):(this.minSquareCurveApproxDist=1,this.minRenderSizeBothDimens=1,this.minRenderSizeAnyDimen=0)}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),jt.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()}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=yt.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 Fe extends se{constructor(t){super(t),this.clearedCount=0,this.renderedPathCount=0,this.lastFillStyle=null,this.lastPoint=null,this.objectNestingLevel=0,this.lastText=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.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}startObject(t,e){super.startObject(t),this.objectNestingLevel+=1}endObject(){super.endObject(),this.objectNestingLevel-=1}isTooSmallToRender(t){return!1}canRenderFromWithoutDataLoss(t){return t instanceof Fe}renderFromOtherOfSameType(t,e){if(!(e instanceof Fe))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 Ue=!1;class Ve{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 Ve(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 Ve(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}renderingIsUpToDate(t){if(null===this.cachedRenderer||t.length!==this.renderedIds.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==this.renderedIds[e])return!1;return!0}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=[];for(const t of e)o.push(...t.getLeavesIntersectingRegion(this.region,(t=>t.w/this.region.w<2/this.cacheState.props.blockResolution.x)));B(o);const s=this.computeSortedByLeafIds(o);if(0===s.length)return;const a=s.map((t=>t.getId()));let l;if(this.renderingIsUpToDate(a))l=this.cachedRenderer.startRender();else{if(this.allChildrenCanRender(n,s)){for(const r of this.getChildren())r.renderItems(t,e,n);return}if(s.length>this.cacheState.props.minComponentsPerCache){let t=!0;if(this.cachedRenderer){if(s.length>this.renderedIds.length&&null!==this.renderedMaxZIndex){const e=[];let n=null;for(let t=0;t<s.length;t++){const r=s[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,l=this.cachedRenderer.startRender();for(let t=0;t<o.length;t++){const e=o[t],n=e.getContent().getZIndex();n>this.renderedMaxZIndex&&(e.render(l,this.region),this.renderedMaxZIndex=n)}Ue}}}else this.cachedRenderer=this.cacheState.recordManager.allocCanvas(this.region,(()=>this.onRegionDealloc()));if(t){l=this.cachedRenderer.startRender(),l.clear(),this.renderedMaxZIndex=null;for(const t of o){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(l,this.region)}Ue}this.renderedIds=a}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),s=!0;t.startObject(r,s);for(const e of o)e.render(t,this.region.intersection(n.visibleRect));t.endObject()}}if(l){const e=this.cachedRenderer.getTransform(this.region).inverse();t.renderFromOtherOfSameType(e,l)}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 We{constructor(t,e){this.onBeforeDeallocCallback=t,this.cacheState=e,this.allocd=!1,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}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 _e{constructor(t){this.cacheState=t,this.cacheRecords=[];const e=t.props;this.maxCanvases=Math.ceil(e.cacheSize/4/e.blockResolution.x/e.blockResolution.y)}allocCanvas(t,e){if(this.cacheRecords.length<this.maxCanvases){const n=new We(e,Object.assign(Object.assign({},this.cacheState),{recordManager:this}));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 He{constructor(t){this.partialSharedState={props:t,currentRenderingCycle:0},this.recordManager=new _e(this.partialSharedState)}getSharedState(){return Object.assign(Object.assign({},this.partialSharedState),{recordManager:this.recordManager})}render(t,e,n){var r;const i=n.visibleRect;if(this.partialSharedState.currentRenderingCycle++,!this.partialSharedState.props.isOfCorrectType(t))return void e.render(t,i);if(!this.rootNode){const t=this.partialSharedState.props.blockResolution,e=i.topLeft;this.rootNode=new Ve(new R(e.x,e.y,t.x,t.y),this.getSharedState())}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.partialSharedState.props.minComponentsToUseCache?this.rootNode.renderItems(t,[e],n):e.render(t,i)}}class Ge extends se{constructor(t,e){super(t),this.localizationTable=e,this.descriptionBuilder=[]}displaySize(){return k.of(500,500)}clear(){this.descriptionBuilder=[]}getDescription(){return this.descriptionBuilder.join("\n")}beginPath(t){}endPath(t){}lineTo(t){}moveTo(t){}traceCubicBezierCurve(t,e,n){}traceQuadraticBezierCurve(t,e){}drawText(t,e,n){this.descriptionBuilder.push(this.localizationTable.textNode(t))}isTooSmallToRender(t){return t.maxDimension<10/this.getSizeOfCanvasPixelOnScreen()}drawPoints(...t){}}var qe;!function(t){t[t.DummyRenderer=0]="DummyRenderer",t[t.CanvasRenderer=1]="CanvasRenderer"}(qe||(qe={}));class Ze{constructor(t,e,n){if(this.editor=t,this.parent=n,this.getColorAt=t=>null,e===qe.CanvasRenderer)this.initializeCanvasRendering();else{if(e!==qe.DummyRenderer)throw new Error(`Unknown rendering mode, ${e}!`);this.dryInkRenderer=new Fe(t.viewport),this.wetInkRenderer=new Fe(t.viewport)}this.textRenderer=new Ge(t.viewport,t.localization),this.initializeTextRendering();const r=k.of(600,600);this.cache=new He({createRenderer:()=>{if(e===qe.DummyRenderer)return new Fe(t.viewport);if(e!==qe.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 je(i,t.viewport)},isOfCorrectType:t=>this.dryInkRenderer.canRenderFromWithoutDataLoss(t),blockResolution:r,cacheSize:2e8,maxScale:1.5,minComponentsPerCache:50,minComponentsToUseCache:120}),this.editor.notifier.on(I.DisplayResized,(t=>{var e;if(t.kind!==I.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 je(n,this.editor.viewport),this.wetInkRenderer=new je(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(I.DisplayResized,{kind:I.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 yt.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;const n=document.createElement("div");n.ariaLive="polite",e.onclick=()=>{this.textRenderer.clear(),this.editor.image.render(this.textRenderer,this.editor.viewport),n.innerText=this.textRenderer.getDescription()},t.replaceChildren(e,n),this.editor.createHTMLOverlay(t)}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 Ke={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}`,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"}`},Xe=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Xt),{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",toolEnabledAnnouncement:t=>`${t} enabled`,toolDisabledAnnouncement:t=>`${t} disabled`}),Ke),{stroke:"Stroke",svgObject:"SVG Object",text:t=>`Text object: ${t}`}),{textNode:t=>`Text: ${t}`,rerenderAsText:"Re-render as text"}),{loading:t=>`Loading ${t}%...`,imageEditor:"Image Editor",doneLoading:"Done loading",undoAnnouncement:t=>`Undid ${t}`,redoAnnouncement:t=>`Redid ${t}`}),Ye={en:Object.assign({},Xe),es:Object.assign(Object.assign({},Xe),{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",resizeImageToSelection:"Redimensionar la imagen a lo que está seleccionado",deleteSelection:"Borra la selección",duplicateSelection:"Duplica la selección",pickColorFronScreen:"Selecciona un color de la pantalla",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"})},Qe=t=>{const e=/^(\w+)[_-](\w+)$/.exec(t);return e?e[1]:t},Je=t=>{let e;null!=t||(t=navigator.languages);for(const n of t){const t=Qe(n);if(e&&t!==e&&e in Ye)return Ye[e];if(n in Ye)return Ye[n];e=t}return e&&e in Ye?Ye[e]:Xe};var tn=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 en=class{constructor(t,e={}){var n,r;this.announceUndoCallback=t=>{this.announceForAccessibility(this.localization.undoAnnouncement(t.description(this.localization)))},this.announceRedoCallback=t=>{this.announceForAccessibility(this.localization.redoAnnouncement(t.description(this.localization)))},this.rerenderQueued=!1,this.localization=Object.assign(Object.assign({},Je()),e.localization),this.settings={wheelEventsEnabled:null===(n=e.wheelEventsEnabled)||void 0===n||n,renderingMode:null!==(r=e.renderingMode)&&void 0!==r?r:qe.CanvasRenderer,localization:this.localization},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.accessibilityAnnounceArea=document.createElement("div"),this.accessibilityAnnounceArea.ariaLive="assertive",this.accessibilityAnnounceArea.className="accessibilityAnnouncement",this.container.appendChild(this.accessibilityAnnounceArea),this.renderingRegion.style.touchAction="none",this.renderingRegion.className="imageEditorRenderArea",this.renderingRegion.setAttribute("tabIndex","0"),this.renderingRegion.ariaLabel=this.localization.imageEditor,this.notifier=new Gt,this.importExportViewport=new V(this.notifier),this.viewport=new V(this.notifier),this.display=new Ze(this,this.settings.renderingMode,this.renderingRegion),this.image=new L,this.history=new Ht(this,this.announceRedoCallback,this.announceUndoCallback),this.toolController=new _t(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()}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){this.accessibilityAnnounceArea.innerText=t}addToolbar(t=!0){const e=new $e(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=D.ofEvent(n,!0,this.viewport);t[r.id]=r,this.renderingRegion.setPointerCapture(r.id);const i={kind:A.PointerDownEvt,current:r,allPointers:e()};return this.toolController.dispatchInputEvent(i),!0})),this.renderingRegion.addEventListener("pointermove",(n=>{var r,i;const o=D.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:A.PointerMoveEvt,current:o,allPointers:e()})&&n.preventDefault()}}));const n=n=>{const r=D.ofEvent(n,!1,this.viewport);t[r.id]&&(t[r.id]=r,this.renderingRegion.releasePointerCapture(r.id),this.toolController.dispatchInputEvent({kind:A.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=T.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=T.of(0,0,t.deltaY));const n=k.of(t.offsetX,t.offsetY);return!!this.toolController.dispatchInputEvent({kind:A.WheelEvt,delta:e,screenPos:n})&&(t.preventDefault(),!0)})),this.notifier.on(I.DisplayResized,(t=>{this.viewport.updateScreenSize(k.of(this.display.width,this.display.height))})),window.addEventListener("resize",(()=>{this.notifier.dispatch(I.DisplayResized,{kind:I.DisplayResized,newSize:k.of(this.display.width,this.display.height)}),this.queueRerender()}))}handleKeyEventsFrom(t){t.addEventListener("keydown",(t=>{this.toolController.dispatchInputEvent({kind:A.KeyPressEvent,key:t.key,ctrlKey:t.ctrlKey})?t.preventDefault():"Escape"===t.key&&this.renderingRegion.blur()})),t.addEventListener("keyup",(t=>{this.toolController.dispatchInputEvent({kind:A.KeyUpEvent,key:t.key,ctrlKey:t.ctrlKey})&&t.preventDefault()}))}dispatch(t,e=!0){e?this.history.push(t):t.apply(this),this.announceForAccessibility(t.description(this.localization))}dispatchNoAnnounce(t,e=!1){e?this.history.push(t):t.apply(this)}asyncApplyOrUnapplyCommands(t,e,n){return tn(this,void 0,void 0,(function*(){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:yt.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=D.ofCanvasPoint(e,t!==A.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 le(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 tn(this,void 0,void 0,(function*(){this.showLoadingWarning(0),this.display.setDraftMode(!0),yield t.start((t=>{this.dispatchNoAnnounce(L.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 b{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){return e.resizeOutputCommand(t)}}}loadFromSVG(t){return tn(this,void 0,void 0,(function*(){const e=oe.fromString(t);yield this.loadFrom(e)}))}},nn=en})(),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:()=>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\twidth: min-content;\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\tmax-width: 70px;\n\tfont-size: 11pt;\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 f=i(p,r);r.byIndex=a,e.splice(a,0,{identifier:d,updater:f,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,{Editor:()=>en,default:()=>nn,getLocalizationTable:()=>Je});var e=r(379),n=r.n(e),o=r(795),s=r.n(o),a=r(569),l=r.n(a),c=r(565),h=r.n(c),d=r(216),u=r.n(d),p=r(589),f=r.n(p),m=r(59),g={};g.styleTagTransform=f(),g.setAttributes=h(),g.insert=l().bind(null,"head"),g.domAPI=s(),g.insertStyleElement=u();n()(m.Z,g);m.Z&&m.Z.locals&&m.Z.locals;var x=r(786),v={};v.styleTagTransform=f(),v.setAttributes=h(),v.insert=l().bind(null,"head"),v.domAPI=s(),v.insertStyleElement=u();n()(x.Z,v);x.Z&&x.Z.locals&&x.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){const r=t.description(n),i=e.description(n);return r===i?r:`${r}, ${i}`}}}}y.empty=new class extends y{description(t){return""}apply(t){}unapply(t){}};const b=y;class w extends b{constructor(t){if(super(),this.commandTypeId=t,!(t in w.deserializationCallbacks))throw new Error(`Command ${t} must have a registered deserialization callback. To do this, call SerializableCommand.register.`)}serialize(){return JSON.stringify({data:this.serializeToString(),commandType:this.commandTypeId})}static deserialize(t,e){const n=JSON.parse(t),r=n.commandType;if(!(r in w.deserializationCallbacks))throw new Error(`Unrecognised command type ${r}!`);return w.deserializationCallbacks[r](n.data,e)}static register(t,e){w.deserializationCallbacks[t]=e}}w.deserializationCallbacks={};class T{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 T(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 T.of(this.x/t,this.y/t,this.z/t)}times(t){return T.of(this.x*t,this.y*t,this.z*t)}plus(t){return T.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 T.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(T.unitX)&&0===this.dot(T.unitY)?0===this.dot(T.unitX)?T.unitX:this.cross(T.unitX).normalized():this.cross(T.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 T.of(e(t.x,this.x),e(t.y,this.y),e(t.z,this.z))}map(t){return T.of(t(this.x),t(this.y),t(this.z))}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,C;T.unitX=T.of(1,0,0),T.unitY=T.of(0,1,0),T.unitZ=T.of(0,0,1),T.zero=T.of(0,0,0),function(t){t.of=(t,e)=>T.of(t,e,0),t.ofXY=({x:t,y:e})=>T.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=[T.of(t,e,n),T.of(r,i,o),T.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=[T.unitX,T.unitY,T.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=T.of(t.x,t.y,1);return e=this.transformVec3(e),k.of(e.x,e.y)}transformVec3(t){return T.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`.trimRight()}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 E{constructor(t){if(this.componentKind=t,this.loadSaveData={},this.lastChangedTime=(new Date).getTime(),this.zIndex=E.zIndexCounter++,this.id=`${(new Date).getTime()}-${Math.random()}`,void 0===E.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 E.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.serializeToString();if(null===t)throw new Error(`${this} cannot be serialized.`);return JSON.stringify({name:this.componentKind,zIndex:this.zIndex,id:this.id,loadSaveData:this.loadSaveData,data:t})}static isNotDeserializable(t){const e=JSON.parse(t);return"object"!=typeof e||(!this.deserializationCallbacks[null==e?void 0:e.name]||!e.data)}static deserialize(t){if(E.isNotDeserializable(t))throw new Error(`Element with data ${t} cannot be deserialized.`);const e=JSON.parse(t),n=this.deserializationCallbacks[e.name](e.data);return n.zIndex=e.zIndex,n.id=e.id,n}}E.zIndexCounter=0,E.deserializationCallbacks={},E.TransformElementCommand=(S=class extends w{constructor(t,e){super("transform-element"),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&&L.addElement(this.component).apply(t)}apply(t){this.component.zIndex=E.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){return t.transformedElements(1)}serializeToString(){return JSON.stringify({id:this.component.getId(),transfm:this.affineTransfm.toArray()})}},w.register("transform-element",((t,e)=>{const n=JSON.parse(t),r=e.image.lookupElement(n.id);if(!r)throw new Error(`Unable to retrieve non-existent element, ${r}`);const i=n.transfm;return new E.TransformElementCommand(new P(...i),r)})),S);class z{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}}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}}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 z(t[0],t[1]),new z(t[1],t[2]),new z(t[2],t[3]),new z(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 B=t=>{t.sort(((t,e)=>t.getContent().getZIndex()-e.getContent().getZIndex()))};class L{constructor(){this.root=new M,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();B(e);for(const n of e)n.getContent().render(t,n.getBBox())}getElementsIntersectingRegion(t){const e=this.root.getLeavesIntersectingRegion(t);return B(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 L.AddElementCommand(t,e)}}L.AddElementCommand=(C=class extends w{constructor(t,e=!1){if(super("add-element"),this.element=t,this.applyByFlattening=e,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){return t.addElementAction(this.element.description(t))}serializeToString(){return JSON.stringify({elemData:this.element.serialize()})}},w.register("add-element",((t,e)=>{const n=JSON.parse(t),r=E.deserialize(n.elemData);return new L.AddElementCommand(r)})),C);class M{constructor(t=null){this.parent=t,this.targetChildCount=30,this.children=[],this.bbox=R.empty,this.content=null,this.id=M.idCounter++}getId(){return this.id}onContentChange(){this.id=M.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=[];if(null==e?void 0:e(this.bbox))return[];null!==this.content&&this.getBBox().intersects(t)&&n.push(this);const r=this.getChildrenIntersectingRegion(t);for(const i of r)n.push(...i.getLeavesIntersectingRegion(t,e));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 M(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 M(this),n=new M(this);return n.children=this.children,this.children=[e,n],n.recomputeBBox(!0),n.updateParents(),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 M(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)));B(n);for(const r of n)r.getContent().render(t,e)}}var A,I,O;M.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"}(A||(A={})),function(t){t[t.ToolEnabled=0]="ToolEnabled",t[t.ToolDisabled=1]="ToolDisabled",t[t.ToolUpdated=2]="ToolUpdated",t[t.UndoRedoStackUpdated=3]="UndoRedoStackUpdated",t[t.ObjectAdded=4]="ObjectAdded",t[t.ViewportChanged=5]="ViewportChanged",t[t.DisplayResized=6]="DisplayResized",t[t.ColorPickerToggled=7]="ColorPickerToggled",t[t.ColorPickerColorSelected=8]="ColorPickerColorSelected"}(I||(I={})),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 D{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 D(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 D(a,t,s,o,e,i,r,l)}}var N,$,j=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},F=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{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)}resetTransform(t=P.identity){const e=this.transform;this.transform=t,this.inverseTransform=t.inverse(),this.notifier.dispatch(I.ViewportChanged,{kind:I.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(T.unitX).magnitude()}getSizeOfPixelOnCanvas(){return 1/this.getScaleFactor()}getRotationAngle(){return this.transform.transformVec3(T.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 V.roundPoint(t,1/this.getScaleFactor())}zoomTo(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),new V.ViewportTransform(r)}}V.ViewportTransform=($=class extends b{constructor(t){super(),this.transform=t,N.set(this,void 0),j(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(F(this,N,"f"))),t.queueRerender()}description(t){const e=[],n=k.unitX,r=this.transform.transformVec3(k.unitX),i=this.transform.transformVec2(k.unitX),o=r.magnitude(),s=180/Math.PI*r.angle(),a=i.minus(n);o>1.2?e.push(t.zoomedIn):o<.8&&e.push(t.zoomedOut),Math.floor(Math.abs(s))>0&&e.push(t.rotatedBy(Math.round(s)));const l=1e-4;return a.x>l?e.push(t.movedLeft):a.x<-1e-4&&e.push(t.movedRight),a.y<l?e.push(t.movedDown):a.y>l&&e.push(t.movedUp),e.join("; ")}},N=new WeakMap,$);const U=V;class W{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}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(I.ToolEnabled,{kind:I.ToolEnabled,tool:this})):this.notifier.dispatch(I.ToolDisabled,{kind:I.ToolDisabled,tool:this})}isEnabled(){return this.enabled}setToolGroup(t){this.isEnabled()&&t.notifyEnabled(this),this.group=t}}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 H extends W{constructor(t,e,n){super(t.notifier,n),this.editor=t,this.mode=e,this.kind=Wt.PanZoom,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=new V.ViewportTransform(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=new V.ViewportTransform(this.transform.transform.rightMul(s))}handleOneFingerMove(t){const e=this.getCenterDelta(t.screenPos);this.transform=new V.ViewportTransform(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=new V.ViewportTransform(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){var e;let n=t;this.transform&&(n=this.transform.transform.rightMul(t)),null===(e=this.transform)||void 0===e||e.unapply(this.editor),this.transform=new V.ViewportTransform(n),this.transform.apply(this.editor)}onWheel({delta:t,screenPos:e}){this.transform=new V.ViewportTransform(P.identity);const n=this.editor.viewport.screenToCanvas(e),r=this.editor.viewport.screenToCanvasTransform.transformVec3(T.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}onKeyPress({key:t}){if(!(this.mode&_.Keyboard))return!1;this.transform=new V.ViewportTransform(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"k":case"ArrowUp":e=k.of(0,-1);break;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;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}setMode(t){t!==this.mode&&(this.mode=t,this.editor.notifier.dispatch(I.ToolUpdated,{kind:I.ToolUpdated,tool:this}))}getMode(){return this.mode}}const{abs:G,cos:Z,sin:q,acos:K,atan2:X,sqrt:Y,pow:Q}=Math;function J(t){return t<0?-Q(-t,1/3):Q(t,1/3)}const tt=Math.PI,et=2*tt,nt=tt/2,rt=Number.MAX_SAFE_INTEGER||9007199254740991,it=Number.MIN_SAFE_INTEGER||-9007199254740991,ot={x:0,y:0,z:0},st={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),Y(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],ot],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||st.approximately(t,e)||st.approximately(t,n)},approximately:function(t,e,n){return G(t-e)<=(n||1e-6)},length:function(t){const e=st.Tvalues.length;let n=0;for(let r,i=0;i<e;i++)r=.5*st.Tvalues[i]+.5,n+=st.Cvalues[i]*st.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(st.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 X(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 Y(n*n+r*r)},closest:function(t,e){let n,r,i=Q(2,63);return t.forEach((function(t,o){r=st.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=Q(t,e)+Q(1-t,e);return G((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=Q(1-t,e);return n/(Q(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 st.lli8(i,o,s,a,l,c,h,d)},lli:function(t,e){return st.lli4(t,t.c,e,e.c)},makeline:function(t,e){return new gt(t.x,t.y,(t.x+e.x)/2,(t.y+e.y)/2,e.x,e.y)},findbbox:function(t){let e=rt,n=rt,r=it,i=it;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(!st.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=st.makeline(e.points[r-1],t.points[0]),s=st.makeline(t.points[i-1],e.points[0]),a={startcap:o,forward:t,back:e,endcap:s,bbox:st.findbbox([o,t,e,s]),intersections:function(t){return st.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=rt,s=it;-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=-X(e.p2.y-r,e.p2.x-n);return t.map((function(t){return{x:(t.x-n)*Z(i)-(t.y-r)*q(i),y:(t.x-n)*q(i)+(t.y-r)*Z(i)}}))},roots:function(t,e){e=e||{p1:{x:0,y:0},p2:{x:1,y:0}};const n=t.length-1,r=st.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=-Y(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(st.approximately(l,0)){if(st.approximately(c,0))return st.approximately(h,0)?[]:[-d/h].filter(i);const t=Y(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,f=(2*c*c*c-9*c*h+27*d)/27,m=f/2,g=m*m+p*p*p;let x,v,y,b,w;if(g<0){const t=-u/3,e=Y(t*t*t),n=-f/(2*e),r=K(n<-1?-1:n>1?1:n),o=2*J(e);return y=o*Z(r/3)-c/3,b=o*Z((r+et)/3)-c/3,w=o*Z((r+2*et)/3)-c/3,[y,b,w].filter(i)}if(0===g)return x=m<0?J(-m):-J(m),y=2*x-c/3,b=-x-c/3,[y,b].filter(i);{const t=Y(g);return x=J(-m+t),v=J(m+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=-Y(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=st.compute(t,e),u=st.compute(t,n),p=d.x*d.x+d.y*d.y;if(r?(o=Y(Q(d.y*u.z-u.y*d.z,2)+Q(d.z*u.x-u.z*d.x,2)+Q(d.x*u.y-u.x*d.y,2)),s=Q(p+d.z*d.z,1.5)):(o=d.x*u.y-d.y*u.x,s=Q(p,1.5)),0===o||0===s)return{k:0,r:0};if(c=o/s,h=s/o,!i){const i=st.curvature(t-.001,e,n,r,!0).k,o=st.curvature(t+.001,e,n,r,!0).k;l=(o-c+(c-i))/2,a=(G(o-c)+G(c-i))/2}return{k:c,r:h,dk:l,adk:a}},inflections:function(t){if(t.length<4)return[];const e=st.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(st.approximately(o,0)){if(!st.approximately(s,0)){let t=-a/s;if(0<=t&&t<=1)return[t]}return[]}const l=2*o;if(st.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,G(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 st.bboxoverlap(t.left.bbox(),t.right.bbox())}));let h=[];return 0===c.length||(c.forEach((function(t){h=h.concat(st.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*Z(nt)-i*q(nt),l=r*q(nt)+i*Z(nt),c=o*Z(nt)-s*q(nt),h=o*q(nt)+s*Z(nt),d=(t.x+e.x)/2,u=(t.y+e.y)/2,p=(e.x+n.x)/2,f=(e.y+n.y)/2,m=d+a,g=u+l,x=p+c,v=f+h,y=st.lli8(d,u,m,g,p,f,x,v),b=st.dist(y,t);let w,T=X(t.y-y.y,t.x-y.x),k=X(e.y-y.y,e.x-y.x),S=X(n.y-y.y,n.x-y.x);return T<S?((T>k||k>S)&&(T+=et),T>S&&(w=S,S=T,T=w)):S<k&&k<T?(w=S,S=T,T=w):S+=et,y.s=T,y.e=S,y.r=b,y},numberSort:function(t,e){return t-e}};class at{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 st.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++)st.expandbox(e,t[n].bbox());return e}offset(t){const e=[];return this.curves.forEach((function(n){e.push(...n.offset(t))})),new at(e)}}const{abs:lt,min:ct,max:ht,cos:dt,sin:ut,acos:pt,sqrt:ft}=Math,mt=Math.PI;class gt{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=st.align(s,{p1:s[0],p2:s[l]}),d=st.dist(s[0],s[l]);this._linear=h.reduce(((t,e)=>t+lt(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 gt(e,e,n);if(1===r)return new gt(t,e,e);const i=gt.getABC(2,t,e,n,r);return new gt(t,i.A,n)}static cubicFromPoints(t,e,n,r,i){void 0===r&&(r=.5);const o=gt.getABC(3,t,e,n,r);void 0===i&&(i=st.dist(e,o.C));const s=i*(1-r)/r,a=st.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,f=e.x-h,m=e.y-d,g=e.x+u,x=e.y+p,v=o.A,y=v.x+(f-v.x)/(1-r),b=v.y+(m-v.y)/(1-r),w=v.x+(g-v.x)/r,T=v.y+(x-v.y)/r,k={x:t.x+(y-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 gt(t,k,S,n)}static getUtils(){return st}getUtils(){return gt.getUtils()}static get PolyBezier(){return at}valueOf(){return this.toString()}toString(){return st.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=st.derive(this.points,this._3d),this.computedirection()}computedirection(){const t=this.points,e=st.angle(t[0],t[this.order],t[1]);this.clockwise=e>0}length(){return st.length(this.derivative.bind(this))}static getABC(t=2,e,n,r,i=.5){const o=st.projectionratio(i,t),s=1-o,a={x:o*e.x+s*r.x,y:o*e.y+s*r.y},l=st.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 gt.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],st.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=st.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=st.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?st.computeWithRatios(t,this.points,this.ratios,this._3d):st.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 gt(e)}derivative(t){return st.compute(t,this.dpoints[0],this._3d)}dderivative(t){return st.compute(t,this.dpoints[1],this._3d)}align(){let t=this.points;return new gt(st.align(t,{p1:t[0],p2:t[t.length-1]}))}curvature(t){return st.curvature(t,this.dpoints[0],this.dpoints[1],this._3d)}inflections(){return st.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=st.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 gt([n[0],n[3],n[5]]):new gt([n[0],n[4],n[7],n[9]]),right:2===this.order?new gt([n[5],n[4],n[2]]):new gt([n[9],n[8],n[6],n[3]]),span:n};return r.left._t1=st.map(0,0,1,this._t1,this._t2),r.left._t2=st.map(t,0,1,this._t1,this._t2),r.right._t1=st.map(t,0,1,this._t1,this._t2),r.right._t2=st.map(1,0,1,this._t1,this._t2),e?(e=st.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]=st.droots(i),3===this.order&&(i=this.dpoints[1].map(r),t[n]=t[n].concat(st.droots(i))),t[n]=t[n].filter((function(t){return t>=0&&t<=1})),e=e.concat(t[n].sort(st.numberSort))}.bind(this)),t.values=e.sort(st.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]=st.getminmax(this,n,t[n])}.bind(this)),e}overlaps(t){const e=this.bbox(),n=t.bbox();return st.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 gt(n)]}return this.reduce().map((function(e){return e._linear?e.offset(t)[0]:e.scale(t)}))}simple(){if(3===this.order){const t=st.angle(this.points[0],this.points[3],this.points[1]),e=st.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),lt(pt(n))<mt/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,lt(n-r)<i)return[];e=t.split(n,r),e._t1=st.map(n,0,1,t._t1,t._t2),e._t2=st.map(r,0,1,t._t1,t._t2),s.push(e),n=r;break}n<1&&(e=t.split(n,1),e._t1=st.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 gt(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=st.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]=st.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 gt(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]=st.lli4(n,o,c,i[t+1])})),new gt(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=st.makeline(d[2],h[0]),p=st.makeline(h[2],d[0]),f=[u,new gt(h),p,new gt(d)];return new at(f)}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 st.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],f=s[o-1].points[s[o-1].points.length-1],m=l[o-1].points[l[o-1].points.length-1],g=l[0].points[0],x=st.makeline(m,p),v=st.makeline(f,g),y=[x].concat(s).concat([v]).concat(l);return new at(y)}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=st.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 gt&&(t=t.reduce()),this.curveintersects(this.reduce(),t,e)):this.selfintersects(e)}lineIntersects(t){const e=ct(t.p1.x,t.p2.x),n=ct(t.p1.y,t.p2.y),r=ht(t.p1.x,t.p2.x),i=ht(t.p1.y,t.p2.y);return st.roots(this.points,t).filter((t=>{var o=this.get(t);return st.between(o.x,e,r)&&st.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=st.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=st.dist(t,e),l=st.dist(t,o),c=st.dist(t,s);return lt(l-a)+lt(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,f=1,m=0;do{if(u=d,l=a,p=(r+i)/2,m++,o=this.get(p),s=this.get(i),a=st.getccenter(h,o,s),a.interval={start:r,end:i},d=this._error(a,h,r,i)<=t,c=u&&!d,c||(f=i),d){if(i>=1){if(a.interval.end=f=1,l=a,i>1){let t={x:a.x+a.r*dt(a.e),y:a.y+a.r*ut(a.e)};a.e+=st.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=f}while(i<1);return e}}var xt;!function(t){t[t.LineTo=0]="LineTo",t[t.MoveTo=1]="MoveTo",t[t.CubicBezierTo=2]="CubicBezierTo",t[t.QuadraticBezierTo=3]="QuadraticBezierTo"}(xt||(xt={}));class vt{constructor(t,e){this.startPoint=t,this.parts=e,this.cachedGeometry=null,this.bbox=R.bboxOf([t]);for(const n of e)this.bbox=this.bbox.union(vt.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 xt.CubicBezierTo:e.push(new gt(t.xy,n.controlPoint1.xy,n.controlPoint2.xy,n.endPoint.xy)),t=n.endPoint;break;case xt.QuadraticBezierTo:e.push(new gt(t.xy,n.controlPoint.xy,n.endPoint.xy)),t=n.endPoint;break;case xt.LineTo:e.push(new z(t,n.point)),t=n.point;break;case xt.MoveTo:t=n.point}return this.cachedGeometry=e,this.cachedGeometry}static computeBBoxForSegment(t,e){const n=[t];let r;switch(e.kind){case xt.MoveTo:case xt.LineTo:n.push(e.point);break;case xt.CubicBezierTo:n.push(e.controlPoint1,e.controlPoint2,e.endPoint);break;case xt.QuadraticBezierTo:n.push(e.controlPoint,e.endPoint);break;default:return r=e,r}return R.bboxOf(n)}intersection(t){const e=[];for(const n of this.geometry)if(n instanceof z){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}transformedBy(t){const e=t.transformVec2(this.startPoint),n=[];let r;for(const e of this.parts)switch(e.kind){case xt.MoveTo:case xt.LineTo:n.push({kind:e.kind,point:t.transformVec2(e.point)});break;case xt.CubicBezierTo:n.push({kind:e.kind,controlPoint1:t.transformVec2(e.controlPoint1),controlPoint2:t.transformVec2(e.controlPoint2),endPoint:t.transformVec2(e.endPoint)});break;case xt.QuadraticBezierTo:n.push({kind:e.kind,controlPoint:t.transformVec2(e.controlPoint),endPoint:t.transformVec2(e.endPoint)});break;default:return r=e,r}return new vt(e,n)}union(t){return t?new vt(this.startPoint,[...this.parts,{kind:xt.MoveTo,point:t.startPoint},...t.parts]):this}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:xt.LineTo,point:t});return new vt(i,n)}static fromRenderable(t){return new vt(t.startPoint,t.commands)}toRenderable(t){return{startPoint:this.startPoint,style:t,commands:this.parts}}toString(){return vt.toString(this.startPoint,this.parts)}serialize(){return this.toString()}static toString(t,e){const n=[],r=t=>{let e=t.toString();if(-1===e.indexOf("."))return e;const n=/^([-]?)(\d*)\.(\d{3,}9{4,}\d)$/.exec(e);if(n){const t=n[1],r=parseInt(e.charAt(e.length-1),10),i=parseInt(n[3],10),o=parseInt(n[2],10),s=n[3];let a=(i+10-r).toString(),l=0;for(a.length>i.toString().length&&(a=a.substring(1),l=1);a.length<s.length;)a=l.toString(10)+a,l=0;e=`${t+(o+l).toString()}.${a}`}return e=e.replace(/^([-]?\d*\.\d{3,})0{4,}\d$/,"$1"),e=e.replace(/([.]\d*[^0]+)0+$/,"$1"),e=e.replace(/[.]0+$/,"."),e.replace(/[.]$/,"")},i=(t,...e)=>{const i=[];for(const t of e){const e=r(t.x),n=r(t.y);i.push(`${e},${n}`)}n.push(`${t}${i.join(" ")}`)};let o;i("M",t);for(const t of e)switch(t.kind){case xt.MoveTo:i("M",t.point);break;case xt.LineTo:i("L",t.point);break;case xt.CubicBezierTo:i("C",t.controlPoint1,t.controlPoint2,t.endPoint);break;case xt.QuadraticBezierTo:i("Q",t.controlPoint,t.endPoint);break;default:return o=t,o}return n.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:xt.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 y=null!==(e=l[x])&&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(k.of(o,i))}return t}),[]).map(((t,e)=>{let r;return r=v?t:n.plus(t),(e+1)%y==0&&(n=r),r}));if(b.length%y!=0)throw new Error([`Incorrect number of arguments: got ${JSON.stringify(b)} with a length of ${b.length} ≠ ${y}k, k ∈ ℤ.`,`The number of arguments to ${x} must be a multiple of ${y}!`,`Command: ${h[0]}`].join("\n"));for(let t=0;t<b.length;t+=y){const e=b.slice(t,t+y);switch(x.toLowerCase()){case"m":0===t?(g=e[0],o?o=!1:s.push({kind:xt.MoveTo,point:g})):a(e[0]);break;case"l":a(e[0]);break;case"c":p=e[0],f=e[1],m=e[2],s.push({kind:xt.CubicBezierTo,controlPoint1:p,controlPoint2:f,endPoint:m});break;case"q":d=e[0],u=e[1],s.push({kind:xt.QuadraticBezierTo,controlPoint:d,endPoint:u});break;default:throw new Error(`Unknown path command ${x}`)}o=!1}b.length>0&&(null!=r||(r=b[0]),null!=i||(i=r),n=b[b.length-1])}var d,u,p,f,m,g;return new vt(null!=i?i:k.zero,s)}}vt.empty=new vt(k.zero,[]);class yt{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 yt.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 yt(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 yt.ofRGBA(n[0],n[1],n[2],n[3])}static fromString(t){if(t.startsWith("#"))return yt.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 yt.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)}}yt.transparent=yt.ofRGBA(0,0,0,0),yt.red=yt.ofRGB(1,0,0),yt.green=yt.ofRGB(0,1,0),yt.blue=yt.ofRGB(0,0,1),yt.purple=yt.ofRGB(.5,.2,.5),yt.yellow=yt.ofRGB(1,1,.1),yt.clay=yt.ofRGB(.8,.4,.2),yt.black=yt.ofRGB(0,0,0),yt.white=yt.ofRGB(1,1,1);const bt=(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},wt=t=>{const e=t.stroke?{color:t.stroke.color.toHexString(),width:t.stroke.width}:void 0;return{fill:t.fill.toHexString(),stroke:e}},Tt=t=>{const e=t.stroke?{color:yt.fromHex(t.stroke.color),width:t.stroke.width}:void 0;return{fill:yt.fromHex(t.fill),stroke:e}};class kt extends E{constructor(t){var e;super("stroke"),this.parts=t.map((t=>{const e=vt.fromRenderable(t),n=this.bboxForPart(e.bbox,t.style);return this.contentBBox?this.contentBBox=this.contentBBox.union(n):this.contentBBox=n,{path:e,bbox:n,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=n.bbox;e&&!r.intersects(e)||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,bbox:i,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:vt.empty}description(t){return t.stroke}createClone(){return new kt(this.parts)}serializeToString(){return JSON.stringify(this.parts.map((t=>({style:wt(t.style),path:t.path.serialize()}))))}static deserializeFromString(t){const e=JSON.parse(t);if("object"!=typeof e||"number"!=typeof e.length)throw new Error(`${t} is missing required field, parts, or parts is of the wrong type.`);const n=e.map((t=>{const e=Tt(t.style);return vt.fromString(t.path).toRenderable(e)}));return new kt(n)}}E.registerComponent("stroke",kt.deserializeFromString);const St=(t,e)=>{const n=e.screenToCanvasTransform,r=7*n.transformVec3(k.unitX).magnitude(),i=2*n.transformVec3(k.unitX).magnitude();return new Ct(t,i,r)};class Ct{constructor(t,e,n){this.startPoint=t,this.minFitAllowed=e,this.maxFitAllowed=n,this.currentCurve=null,this.lastPoint=this.startPoint,this.segments=[],this.buffer=[this.startPoint.pos],this.momentum=k.zero,this.currentCurve=null,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}}getPreview(){if(this.currentCurve&&this.lastPoint){const t=this.currentSegmentToPath();return this.segments.concat(t)}return this.segments}preview(t){for(const e of this.getPreview())t.drawPath(e)}build(){return this.lastPoint&&this.finalizeCurrentCurve(),new kt(this.segments)}roundPoint(t){return U.roundPoint(t,this.minFitAllowed)}finalizeCurrentCurve(){if(!this.currentCurve){if(this.segments.length>0)return;const t=U.roundPoint(this.startPoint.width/3,this.minFitAllowed),e=this.roundPoint(this.startPoint.pos);return void this.segments.push({startPoint:this.startPoint.pos.plus(k.of(t,0)),commands:[{kind:xt.QuadraticBezierTo,controlPoint:e.plus(k.of(t,t)),endPoint:e.plus(k.of(0,t))},{kind:xt.QuadraticBezierTo,controlPoint:e.plus(k.of(-t,t)),endPoint:e.plus(k.of(-t,0))},{kind:xt.QuadraticBezierTo,controlPoint:e.plus(k.of(-t,-t)),endPoint:e.plus(k.of(0,-t))},{kind:xt.QuadraticBezierTo,controlPoint:e.plus(k.of(t,-t)),endPoint:e.plus(k.of(t,0))}],style:this.getRenderingStyle()})}this.segments.push(this.currentSegmentToPath());const t=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()),this.buffer=[this.buffer[this.buffer.length-2],t],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 gt(n.plus(t.times(o)),i.plus(s.times(o)),r.plus(e.times(o))),c=l(1,a),h=l(-1,a);c.intersects(h).length>0&&(a=a.times(2));const d=[{kind:xt.QuadraticBezierTo,controlPoint:this.roundPoint(i.plus(a)),endPoint:this.roundPoint(r.plus(e))},{kind:xt.LineTo,point:this.roundPoint(r.minus(e))},{kind:xt.QuadraticBezierTo,controlPoint:this.roundPoint(i.minus(a)),endPoint:this.roundPoint(n.minus(t))}];return{startPoint:this.roundPoint(n.plus(t)),commands:d,style:this.getRenderingStyle()}}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)/4;if(this.startPoint.pos.minus(t.pos).magnitude()<r&&0===this.segments.length)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 gt(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 z(l,l.plus(s.times(d))),p=new z(c.minus(a.times(d)),c).intersection(u);let f;f=p?p.point:l.plus(s.times(h/4)),(isNaN(f.magnitude())||isNaN(l.magnitude()))&&console.error("controlPoint is NaN",p,"Start:",l,"End:",c,"in:",s,"out:",a);const m=this.currentCurve;this.currentCurve=new gt(l.xy,f.xy,c.xy),isNaN(k.ofXY(this.currentCurve.normal(0)).magnitude())&&(console.error("NaN normal at 0. Curve:",this.currentCurve),this.currentCurve=m);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)/2,this.minFitAllowed)||n>this.maxFitAllowed)return!1}return!0};return this.buffer.length>3&&!g(this.currentCurve)?(this.currentCurve=m,this.curveEndWidth=o,this.lastPoint=r,void this.finalizeCurrentCurve()):void 0}}class Pt extends W{constructor(t,e,n){super(t.notifier,e),this.editor=t,this.style=n,this.builder=null,this.builderFactory=St,this.lastPoint=null,this.kind=Wt.Pen}getPressureMultiplier(){return 1/this.editor.viewport.getScaleFactor()*this.style.thickness}getStrokePoint(t){var e;const n=Math.max(null!==(e=t.pressure)&&void 0!==e?e:1,.3);return{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}){return t.device!==O.Eraser&&((1===e.length||t.device===O.Pen)&&(this.builder=this.builderFactory(this.getStrokePoint(t),this.editor.viewport),!0))}onPointerMove({current:t}){this.addPointToStroke(this.getStrokePoint(t))}onPointerUp({current:t}){var e,n;if(!this.builder)return;const r=this.getStrokePoint(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=L.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(I.ToolUpdated,{kind:I.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}}class Et{constructor(){}notifyEnabled(t){var e;t!==this.activeTool&&(null===(e=this.activeTool)||void 0===e||e.setEnabled(!1),this.activeTool=t)}}const zt=(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 Rt extends w{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)||L.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){var e;if(0===this.toRemove.length)return t.erasedNoElements;const n=null!==(e=zt(t,this.toRemove))&&void 0!==e?e:t.elements;return t.eraseAction(n,this.toRemove.length)}serializeToString(){const t=this.toRemove.map((t=>t.getId()));return JSON.stringify(t)}}w.register("erase",((t,e)=>{const n=JSON.parse(t).map((t=>e.image.lookupElement(t)));return new Rt(n)}));class Bt extends W{constructor(t,e){super(t.notifier,e),this.editor=t,this.command=null,this.kind=Wt.Eraser}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 z(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 Rt(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 Lt extends w{constructor(t){super("duplicate"),this.toDuplicate=t,this.duplicates=t.map((t=>t.clone())),this.reverse=new Rt(this.duplicates)}apply(t){this.reverse.unapply(t)}unapply(t){this.reverse.apply(t)}description(t){var e;return 0===this.duplicates.length?t.duplicatedNoElements:t.duplicateAction(null!==(e=zt(t,this.duplicates))&&void 0!==e?e:t.elements,this.duplicates.length)}serializeToString(){return JSON.stringify(this.toDuplicate.map((t=>t.getId())))}}w.register("duplicate",((t,e)=>{const n=JSON.parse(t).map((t=>e.image.lookupElement(t)));return new Lt(n)}));var Mt=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 At=30,It=(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 Ot{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,It(n,(t=>{this.handleBackgroundDrag(t)}),(()=>this.finalizeTransform())),It(r,(t=>{this.handleResizeCornerDrag(t)}),(()=>this.finalizeTransform())),It(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 Ot.ApplyTransformationCommand(this,r,t,e,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}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*(At/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(new U.ViewportTransform(P.translation(n.times(-1))),!1)}}deleteSelectedObjects(){return new Rt(this.selectedElems)}duplicateSelectedObjects(){return new Lt(this.selectedElems)}}Ot.ApplyTransformationCommand=class extends b{constructor(t,e,n,r,i){super(),this.selection=t,this.currentTransfmCommands=e,this.fullTransform=n,this.inverseTransform=r,this.deltaBoxRotation=i}apply(t){return Mt(this,void 0,void 0,(function*(){this.selection.region=this.selection.region.transformedBoundingBox(this.fullTransform),this.selection.boxRotation+=this.deltaBoxRotation,this.selection.updateUI(),yield t.asyncApplyCommands(this.currentTransfmCommands,100),this.selection.recomputeRegion(),this.selection.updateUI()}))}unapply(t){return Mt(this,void 0,void 0,(function*(){this.selection.region=this.selection.region.transformedBoundingBox(this.inverseTransform),this.selection.boxRotation-=this.deltaBoxRotation,this.selection.updateUI(),yield t.asyncUnapplyCommands(this.currentTransfmCommands,100),this.selection.recomputeRegion(),this.selection.updateUI()}))}description(t){return t.transformedElements(this.currentTransfmCommands.length)}};class Dt extends W{constructor(t,e){super(t.notifier,e),this.editor=t,this.kind=Wt.Selection,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(I.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)}onPointerDown(t){return!(1!==t.allPointers.length||!t.current.isPrimary)&&(this.prevSelectionBox=this.selectionBox,this.selectionBox=new Ot(t.current.canvasPos,this.editor),this.handleOverlay.replaceChildren(),this.selectionBox.appendBackgroundBoxTo(this.handleOverlay),!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(I.ToolUpdated,{kind:I.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 s}onKeyUp(t){return!(!this.selectionBox||!Dt.handleableKeys.some((e=>e===t.key)))&&(this.selectionBox.finalizeTransform(),!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.ariaLabel=this.editor.localization.selectionToolKeyboardShortcuts):this.handleOverlay.tabIndex=-1}getSelection(){return this.selectionBox}clearSelection(){this.handleOverlay.replaceChildren(),this.prevSelectionBox=this.selectionBox,this.selectionBox=null,this.editor.notifier.dispatch(I.ToolUpdated,{kind:I.ToolUpdated,tool:this})}}Dt.handleableKeys=["a","h","ArrowLeft","d","l","ArrowRight","q","k","ArrowUp","e","j","ArrowDown","r","R","i","I","o","O"];class Nt extends W{constructor(t){super(t.notifier,t.localization.undoRedoTool),this.editor=t,this.kind=Wt.UndoRedoShortcut}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 $t="text";class jt extends E{constructor(t,e,n,r=jt.getTextDimens){super($t),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=jt.textMeasuringCtx)&&void 0!==n||(jt.textMeasuringCtx=document.createElement("canvas").getContext("2d"));const r=jt.textMeasuringCtx;jt.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 z(n,r);for(const e of this.textObjects)if("string"==typeof e){if(jt.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 jt(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())}serializeToString(){const t=Object.assign(Object.assign({},this.style),{renderingStyle:wt(this.style.renderingStyle)}),e=this.textObjects.map((t=>"string"==typeof t?{text:t}:{json:t.serializeToString()}));return JSON.stringify({textObjects:e,transform:this.transform.toArray(),style:t})}static deserializeFromString(t,e=jt.getTextDimens){const n=JSON.parse(t),r={renderingStyle:Tt(n.style.renderingStyle),size:n.style.size,fontWeight:n.style.fontWeight,fontVariant:n.style.fontVariant,fontFamily:n.style.fontFamily},i=n.textObjects.map((t=>{var e;return null!==(null!==(e=t.text)&&void 0!==e?e:null)?t.text:jt.deserializeFromString(t.json)}));if(n.transform=n.transform.filter((t=>"number"==typeof t)),9!==n.transform.length)throw new Error(`Unable to deserialize transform, ${n.transform}.`);const o=n.transform,s=new P(...o);return new jt(i,s,r,e)}}E.registerComponent($t,(t=>jt.deserializeFromString(t)));const Ft="textEditorOverlay";class Vt extends W{constructor(t,e,n){super(t.notifier,e),this.editor=t,this.localizationTable=n,this.kind=Wt.Text,this.textInputElem=null,this.textTargetPosition=null,this.textMeasuringCtx=null,this.textStyle={size:32,fontFamily:"sans-serif",renderingStyle:{fill:yt.purple}},this.textEditOverlay=document.createElement("div"),this.textEditOverlay.classList.add(Ft),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(I.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?(jt.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 jt([t],e,this.textStyle),r=L.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(I.ToolUpdated,{kind:I.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 Ut extends W{constructor(t,e){super(t.notifier,e),this.editor=t,this.kind=Wt.Pipette,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)}}var Wt;!function(t){t[t.Pen=0]="Pen",t[t.Selection=1]="Selection",t[t.Eraser=2]="Eraser",t[t.PanZoom=3]="PanZoom",t[t.Text=4]="Text",t[t.UndoRedoShortcut=5]="UndoRedoShortcut",t[t.Pipette=6]="Pipette",t[t.Other=7]="Other"}(Wt||(Wt={}));class _t{constructor(t,e){const n=new Et,r=new H(t,_.TwoFingerTouchGestures|_.RightClickDrags,e.touchPanTool),i=new H(t,_.Keyboard,e.keyboardPanZoom),o=new Pt(t,e.penTool(1),{color:yt.purple,thickness:16}),s=[new Dt(t,e.selectionTool),new Bt(t,e.eraserTool),o,new Pt(t,e.penTool(2),{color:yt.clay,thickness:8}),new Pt(t,e.penTool(3),{color:yt.ofRGBA(1,1,0,.5),thickness:64}),new Vt(t,e.textTool,e)];this.tools=[new Ut(t,e.pipetteTool),r,...s,i,new Nt(t)],s.forEach((t=>t.setToolGroup(n))),r.setEnabled(!0),o.setEnabled(!0),t.notifier.on(I.ToolEnabled,(n=>{n.kind===I.ToolEnabled&&t.announceForAccessibility(e.toolEnabledAnnouncement(n.tool.description))})),t.notifier.on(I.ToolDisabled,(n=>{n.kind===I.ToolDisabled&&t.announceForAccessibility(e.toolDisabledAnnouncement(n.tool.description))})),this.activeTool=null}dispatchInputEvent(t){var e,n;let r=!1;if(t.kind===A.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===A.PointerUpEvt)null===(n=this.activeTool)||void 0===n||n.onPointerUp(t),this.activeTool=null,r=!0;else if(t.kind===A.WheelEvt||t.kind===A.KeyPressEvent||t.kind===A.KeyUpEvent){const e=t.kind===A.KeyPressEvent,n=t.kind===A.KeyUpEvent,i=t.kind===A.WheelEvt;for(const o of this.tools){if(!o.isEnabled())continue;const s=i&&o.onWheel(t),a=e&&o.onKeyPress(t),l=n&&o.onKeyUp(t);if(r=a||s||l,r)break}}else if(null!==this.activeTool){let e;switch(t.kind){case A.PointerMoveEvt:this.activeTool.onPointerMove(t);break;case A.GestureCancelEvt:this.activeTool.onGestureCancel(),this.activeTool=null;break;default:return e=t,e}r=!0}else r=!1;return r}getMatchingTools(t){return this.tools.filter((e=>e.kind===t))}}const Ht=class{constructor(t,e,n){this.editor=t,this.announceRedoCallback=e,this.announceUndoCallback=n,this.undoStack=[],this.redoStack=[]}fireUpdateEvent(){this.editor.notifier.dispatch(I.UndoRedoStackUpdated,{kind:I.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);this.redoStack=[],this.fireUpdateEvent()}undo(){const t=this.undoStack.pop();t&&(this.redoStack.push(t),t.unapply(this.editor),this.announceUndoCallback(t)),this.fireUpdateEvent()}redo(){const t=this.redoStack.pop();t&&(this.undoStack.push(t),t.apply(this.editor),this.announceRedoCallback(t)),this.fireUpdateEvent()}get undoStackSize(){return this.undoStack.length}get redoStackSize(){return this.redoStack.length}};class Gt{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 Zt=function(t,e,n){var r,i,o,s,a,l,c,h,d,u,p,f,m,g,x,v=e.createElement("canvas").getContext("2d"),y={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="",k={},S=!1;function C(n){if("object"==typeof n)for(var s in n)switch(s){case"el":R(n.el),!1!==n.wrap&&L(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&&L(n.el);break;case"formatToggle":b.formatToggle=!!n.formatToggle,_("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>")})),_("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;g=I(a),B(),A(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,f=!1;if("object"==typeof u)for(var m in u)u[m]&&b.a11y[m]&&(b.a11y[m]=u[m],f=!0);if(f){var x=_("clr-open-label"),v=_("clr-swatch-label");x.innerHTML=b.a11y.open,v.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 P(t,e){"string"==typeof t&&"object"==typeof e&&(w[t]=e,S=!0)}function E(t){delete w[t],0===Object.keys(w).length&&(S=!1,t===T&&z())}function z(){Object.keys(k).length>0&&(C(k),T="",k={})}function R(t){H(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,k={},e.forEach((function(t){return delete r[t]})),r)k[i]=Array.isArray(b[i])?b[i].slice():b[i];return C(r),"break"}};for(var r in w)if("break"===n(r))break}}(t.target),m=t.target,x=m.value,g=I(x),i.classList.add("clr-open"),B(),A(x),(b.focusInput||b.selectInput)&&c.focus({preventScroll:!0}),b.selectInput&&c.select(),m.dispatchEvent(new Event("open",{bubbles:!0})))})),H(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},f={x:0,y:0};if(c&&(n=t.getComputedStyle(c),a=parseFloat(n.marginTop),l=parseFloat(n.borderTopWidth),(f=c.getBoundingClientRect()).y+=l+h),!b.inline){var g=m.getBoundingClientRect(),x=g.x,v=h+g.y+g.height+b.margin;c?(x-=f.x,v-=f.y,x+d>c.clientWidth&&(x+=g.width-d,p.left=!0),v+u>c.clientHeight-a&&u+b.margin<=g.top-(f.y-h)&&(v-=g.height+u+2*b.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+b.margin<=g.top&&(v=h+g.y-u-b.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+f.x,y:i.offsetTop+o.offsetTop+f.y}}function L(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 M(t){m&&!b.inline&&(t&&x!==m.value&&(m.value=x,m.dispatchEvent(new Event("input",{bubbles:!0}))),x!==m.value&&m.dispatchEvent(new Event("change",{bubbles:!0})),i.classList.remove("clr-open"),S&&z(),m.dispatchEvent(new Event("close",{bubbles:!0})),b.focusInput&&m.focus({preventScroll:!0}),m=null)}function A(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);N(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,f.style.left=100*r.a+"%"}function I(t){var e=t.substring(0,3).toLowerCase();return"rgb"===e||"hsl"===e?e:"hex"}function O(t){t=void 0!==t?t:c.value,m&&(m.value=t,m.dispatchEvent(new Event("input",{bubbles:!0}))),e.dispatchEvent(new CustomEvent("coloris:pick",{detail:{color:t}}))}function D(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);N(r.s,r.v),F(i,r),O()}function N(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 $(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",D(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",D(n,r)}function F(t,r){void 0===t&&(t={}),void 0===r&&(r={});var i=b.format;for(var s in t)y[s]=t[s];for(var h in r)y[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}(y),p=u.substring(0,7);switch(a.style.color=p,f.parentNode.style.color=p,f.style.color=u,l.style.color=u,o.style.display="none",o.offsetHeight,o.style.display="",f.nextElementSibling.style.display="none",f.nextElementSibling.offsetHeight,f.nextElementSibling.style.display="","mixed"===i?i=1===y.a?"hex":"rgb":"auto"===i&&(i=g),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+")"}(y);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}}(y),!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 V(){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+"%",D(e,n)}function U(){var t=p.value/100;f.style.left=100*t+"%",F({a:t}),O()}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=_("clr-color-area"),a=_("clr-color-marker"),h=_("clr-clear"),l=_("clr-color-preview"),c=_("clr-color-value"),d=_("clr-hue-slider"),u=_("clr-hue-marker"),p=_("clr-alpha-slider"),f=_("clr-alpha-marker"),R(b.el),L(b.el),H(i,"mousedown",(function(t){i.classList.remove("clr-keyboard-nav"),t.stopPropagation()})),H(o,"mousedown",(function(t){H(e,"mousemove",$)})),H(o,"touchstart",(function(t){e.addEventListener("touchmove",$,{passive:!1})})),H(a,"mousedown",(function(t){H(e,"mousemove",$)})),H(a,"touchstart",(function(t){e.addEventListener("touchmove",$,{passive:!1})})),H(c,"change",(function(t){A(c.value),O()})),H(h,"click",(function(t){O(""),M()})),H(l,"click",(function(t){O(),M()})),H(e,"click",".clr-format input",(function(t){g=t.target.value,F(),O()})),H(i,"click",".clr-swatches button",(function(t){A(t.target.textContent),O(),b.swatchesOnly&&M()})),H(e,"mouseup",(function(t){e.removeEventListener("mousemove",$)})),H(e,"touchend",(function(t){e.removeEventListener("touchmove",$)})),H(e,"mousedown",(function(t){i.classList.remove("clr-keyboard-nav"),M()})),H(e,"keydown",(function(t){"Escape"===t.key?M(!0):"Tab"===t.key&&i.classList.add("clr-keyboard-nav")})),H(e,"click",".clr-field button",(function(t){S&&z(),t.target.nextElementSibling.dispatchEvent(new Event("click",{bubbles:!0}))})),H(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())})),H(o,"click",$),H(d,"input",V),H(p,"input",U)}function _(t){return e.getElementById(t)}function H(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 G(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:C,wrap:L,close:M,setInstance:P,removeInstance:E,updatePosition:B};function e(t){G((function(){t&&("string"==typeof t?R(t):C(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];G(t[n],r)}};for(var r in t)n(r);return e}();return Z.coloris=Z,Z}(window,document,Math),qt=Zt.coloris,Kt=Zt.init;Zt.set,Zt.wrap,Zt.close;const Xt={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: ",pickColorFronScreen:"Pick color from screen",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}`},Yt="svg-global-attributes";class Qt extends E{constructor(t){super(Yt),this.attrs=t,this.contentBBox=R.empty}render(t,e){if(t instanceof le)for(const[e,n]of this.attrs)t.setRootSVGAttribute(e,n)}intersects(t){return!1}applyTransformation(t){}createClone(){return new Qt(this.attrs)}description(t){return t.svgObject}serializeToString(){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 Qt(n)}}E.registerComponent(Yt,Qt.deserializeFromString);const Jt="unknown-svg-object";class te extends E{constructor(t){super(Jt),this.svgObject=t,this.contentBBox=R.of(t.getBoundingClientRect())}render(t,e){t instanceof le&&t.drawSVGElem(this.svgObject)}intersects(t){return this.contentBBox.getEdges().some((e=>null!==e.intersection(t)))}applyTransformation(t){}createClone(){return new te(this.svgObject.cloneNode(!0))}description(t){return t.svgObject}serializeToString(){return JSON.stringify({html:this.svgObject.outerHTML})}}E.registerComponent(Jt,null);var ee=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 ne=new R(0,0,500,500),re="svgAttrs",ie="svgStyleAttrs";class oe{constructor(t,e){this.source=t,this.onFinish=e,this.onAddComponent=null,this.onProgress=null,this.onDetermineExportRect=null,this.processedCount=0,this.totalToProcess=0}getStyle(t){var e,n,r;const i={fill:yt.transparent},o=null!==(e=t.getAttribute("fill"))&&void 0!==e?e:t.style.fill;if(o)try{i.fill=yt.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:yt.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=vt.fromString(e).toRenderable(i);n.push(r)}s=!1}return n}attachUnrecognisedAttrs(t,e,n,r){for(const i of e.getAttributeNames())n.has(i)||"style"===i&&r||t.attachLoadSaveData(re,[i,e.getAttribute(i)]);if(r)for(const n of e.style)""!==n&&n&&(r.has(n)||t.attachLoadSaveData(ie,{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 kt(e);const r=["stroke","fill","stroke-width"];this.attachUnrecognisedAttrs(n,t,new Set([...r,"d"]),new Set(r))}catch(e){console.error("Invalid path in node",t,"\nError:",e,"\nAdding as an unknown object."),n=new te(t)}null===(e=this.onAddComponent)||void 0===e||e.call(this,n)}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:yt.fromString(r.fill)}};let l=r.transform;""!==l&&"none"!==l||(l=t.style.transform||"none");let c=P.fromCSSMatrix(l);const h=[],d=t.getAttribute("x"),u=t.getAttribute("y");if(d&&u){const t=parseFloat(d),e=parseFloat(u);isNaN(t)||isNaN(e)||(h.push("x","y"),c=c.rightMul(P.translation(k.of(t,e))))}const p=new jt(n,c,a);return this.attachUnrecognisedAttrs(p,t,new Set(h),new Set(o)),p}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,". Adding as an unknown object. Error:",e),this.addUnknownNode(t)}}addUnknownNode(t){var e;const n=new te(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;null===(e=this.onAddComponent)||void 0===e||e.call(this,new Qt(this.getSourceAttrs(t)))}visit(t){var e;return ee(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"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! Continuing anyway."),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 ee(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,ne),null===(i=this.onFinish)||void 0===i||i.call(this)}))}static fromString(t){var e,n;const r=document.createElement("iframe");if(r.src="about:blank",r.setAttribute("sandbox","allow-same-origin"),r.setAttribute("csp","default-src 'about:blank'"),r.style.display="none",document.body.appendChild(r),!r.hasAttribute("sandbox"))throw r.remove(),new Error("SVG loading iframe is not sandboxed.");const i=null!==(n=null===(e=r.contentWindow)||void 0===e?void 0:e.document)&&void 0!==n?n:r.contentDocument;if(null==i)throw new Error("Unable to open a sandboxed iframe!");i.open(),i.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"),i.close();const o=i.createElementNS("http://www.w3.org/2000/svg","svg");return o.innerHTML=t,i.body.appendChild(o),new oe(o,(()=>{o.remove(),r.remove()}))}}class se{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&&bt(t,i)?this.moveTo(n):(t&&this.endPath(t),this.beginPath(n),t=i);for(const t of r)t.kind===xt.LineTo?this.lineTo(t.point):t.kind===xt.MoveTo?this.moveTo(t.point):t.kind===xt.CubicBezierTo?this.traceCubicBezierCurve(t.controlPoint1,t.controlPoint2,t.endPoint):t.kind===xt.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=vt.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 ae="http://www.w3.org/2000/svg";class le extends se{constructor(t,e){super(e),this.elem=t,this.objectElems=null,this.overwrittenAttrs={},this.clear()}setRootSVGAttribute(t,e){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(){for(const t in this.overwrittenAttrs){const e=this.overwrittenAttrs[t];e?this.elem.setAttribute(t,e):this.elem.removeAttribute(t)}this.overwrittenAttrs={}}beginPath(t){var e;this.currentPath=[],this.pathStart=this.canvasToScreen(t),null!==(e=this.lastPathStart)&&void 0!==e||(this.lastPathStart=this.pathStart)}endPath(t){var e;if(null==this.currentPath)throw new Error("No path exists to end! Make sure beginPath was called!");t.fill.eq(null===(e=this.lastPathStyle)||void 0===e?void 0:e.fill)&&null!=this.lastPath?(this.lastPath.push({kind:xt.MoveTo,point:this.pathStart},...this.currentPath),this.pathStart=null,this.currentPath=null):(this.addPathToSVG(),this.lastPathStart=this.pathStart,this.lastPathStyle=t,this.lastPath=this.currentPath,this.pathStart=null,this.currentPath=null)}addPathToSVG(){var t;if(!this.lastPathStyle||!this.lastPath)return;const e=document.createElementNS(ae,"path");e.setAttribute("d",vt.toString(this.lastPathStart,this.lastPath));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)}drawText(t,e,n){var r,i,o;e=this.getCanvasToScreenTransform().rightMul(e);const s=document.createElementNS(ae,"text");if(s.appendChild(document.createTextNode(t)),s.style.transform=`matrix(\n\t\t\t${e.a1}, ${e.b1},\n\t\t\t${e.a2}, ${e.b2},\n\t\t\t${e.a3}, ${e.b3}\n\t\t)`,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)}startObject(t){super.startObject(t),this.lastPath=null,this.lastPathStart=null,this.lastPathStyle=null,this.objectElems=[]}endObject(t){var e;if(super.endObject(t),this.addPathToSVG(),t)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)}}lineTo(t){t=this.canvasToScreen(t),this.currentPath.push({kind:xt.LineTo,point:t})}moveTo(t){t=this.canvasToScreen(t),this.currentPath.push({kind:xt.MoveTo,point:t})}traceCubicBezierCurve(t,e,n){t=this.canvasToScreen(t),e=this.canvasToScreen(e),n=this.canvasToScreen(n),this.currentPath.push({kind:xt.CubicBezierTo,controlPoint1:t,controlPoint2:e,endPoint:n})}traceQuadraticBezierCurve(t,e){t=this.canvasToScreen(t),e=this.canvasToScreen(e),this.currentPath.push({kind:xt.QuadraticBezierTo,controlPoint:t,endPoint:e})}drawPoints(...t){t.map((t=>{const e=document.createElementNS(ae,"circle");e.setAttribute("cx",`${t.x}`),e.setAttribute("cy",`${t.y}`),e.setAttribute("r","15"),this.elem.appendChild(e)}))}drawSVGElem(t){this.elem.appendChild(t.cloneNode(!0))}isTooSmallToRender(t){return!1}}const ce="http://www.w3.org/2000/svg",he="\n\tstyle='fill: var(--icon-color);'\n",de="\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",ue="url(#checkerboard)",pe=(t=!1)=>{const e=document.createElementNS(ce,"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(ce,"svg");return t.innerHTML="\n\t\t<path\n\t\t\td='\n\t\t\t\tM 5,5.5\n\t\t\t\tV 17.2\n\t\t\t\tL 16.25,5.46\n\t\t\t\tZ\n\n\t\t\t\tm 33.75,0\n\t\t\t\tL 50,17\n\t\t\t\tV 5.5\n\t\t\t\tZ\n\n\t\t\t\tM 5,40.7\n\t\t\t\tv 11.7\n\t\t\t\th 11.25\n\t\t\t\tz\n\t\t\t\t\n\t\t\t\tM 26,19\n\t\t\t\tC 19.8,19.4 17.65,30.4 21.9,34.8\n\t\t\t\tL 50,70\n\t\t\t\tH 27.5\n\t\t\t\tc -11.25,0 -11.25,17.6 0,17.6\n\t\t\t\tH 61.25\n\t\t\t\tC 94.9,87.8 95,87.6 95,40.7 78.125,23 67,29 55.6,46.5\n\t\t\t\tL 33.1,23\n\t\t\t\tC 30.3125,20.128192 27.9,19 25.830078,19.119756\n\t\t\t\tZ\n\t\t\t'\n\t\t\tfill='none'\n\t\t\tstyle='\n\t\t\t\tstroke: var(--icon-color);\n\t\t\t\tstroke-width: 2;\n\t\t\t'\n\t\t/>\n\t",t.setAttribute("viewBox","0 0 100 100"),t},me=()=>{const t=document.createElementNS(ce,"svg");return t.innerHTML="\n\t\t<path\n\t\t\td='\n\t\t\t\tM 5 5\n\t\t\t\tL 5 17.5\n\t\t\t\t 17.5 5\n\t\t\t\t 5 5\n\t\t\t\tz\n\t\t\t\t\n\t\t\t\tM 42.5 5\n\t\t\t\tL 55 17.5\n\t\t\t\t 55 5\n\t\t\t\t 42.5 5\n\t\t\t\tz\n\t\t\t\t\n\t\t\t\tM 70 10\n\t\t\t\tL 70 21\n\t\t\t\t 61 15\n\t\t\t 55.5 23\n\t\t\t 66 30\n\t\t\t\t 56 37\n\t\t\t\t 61 45\n\t\t\t\t 70 39\n\t\t\t\t 70 50\n\t\t\t\t 80 50\n\t\t\t\t 80 39\n\t\t\t\t 89 45\n\t\t\t\t 95 36\n\t\t\t\t 84 30\n\t\t\t\t 95 23\n\t\t\t\t 89 15\n\t\t\t\t 80 21\n\t\t\t\t 80 10\n\t\t\t\t 70 10\n\t\t\t\tz\n\n\t\t\t\tM 27.5 26.25\n\t\t\t\tL 27.5 91.25\n\t\t\t\tL 43.75 83.125\n\t\t\t\tL 52 99\n\t\t\t\tL 68 91\n\t\t\t\tL 60 75\n\t\t\t\tL 76.25 66.875\n\t\t\t\tL 27.5 26.25\n\t\t\t\tz\n\t\t\t\t\n\t\t\t\tM 5 42.5\n\t\t\t\tL 5 55\n\t\t\t\tL 17.5 55\n\t\t\t\tL 5 42.5\n\t\t\t\tz \n\t\t\t'\n\t\t\tfill='none'\n\t\t\tstyle='\n\t\t\t\tstroke: var(--icon-color);\n\t\t\t\tstroke-width: 2;\n\t\t\t'\n\t\t/>\n\t",t.setAttribute("viewBox","0 0 100 100"),t},ge=(t,e)=>new xe(t);class xe{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 kt([{startPoint:a.minus(h),commands:[{kind:xt.LineTo,point:t.minus(c)},{kind:xt.LineTo,point:t.plus(c)},{kind:xt.LineTo,point:a.plus(h)},{kind:xt.LineTo,point:a.plus(l.times(i).plus(h))},{kind:xt.LineTo,point:e.plus(n.times(s))},{kind:xt.LineTo,point:a.plus(l.times(-i).minus(h))},{kind:xt.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 ve=(t,e)=>new ye(t);class ye{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 kt([{startPoint:t.minus(s),commands:[{kind:xt.LineTo,point:t.plus(s)},{kind:xt.LineTo,point:e.plus(a)},{kind:xt.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 be=(t,e)=>new Te(t,!0,e),we=(t,e)=>new Te(t,!1,e);class Te{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=vt.fromRect(i,this.filled?null:this.endPoint.width).transformedBy(e);return new kt([o.toRenderable({fill:this.endPoint.color})])}build(){return this.buildPreview()}preview(t){this.buildPreview().render(t)}addPoint(t){this.endPoint=t}}const ke=(t,e,n)=>{const r=document.createElement("button");r.classList.add("pipetteButton"),r.title=t.localization.pickColorFronScreen,r.setAttribute("alt",r.title);const i=t=>{r.replaceChildren((t=>{const e=document.createElementNS(ce,"svg"),n=document.createElementNS(ce,"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(ce,"defs");n.innerHTML=de,e.appendChild(n);const r=document.createElementNS(ce,"path"),i=document.createElementNS(ce,"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=ue,e.appendChild(r),e.appendChild(i)}return e.appendChild(n),e.setAttribute("viewBox","0 0 100 100"),e})(t))};i();const o=t.toolController.getMatchingTools(Wt.Pipette)[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"))},e.appendChild(r)},Se=(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),ke(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=yt.fromHex(r.value)},s=()=>{o(),i&&(t.announceForAccessibility(t.localization.colorChangedAnnouncement(i.toHexString())),e(i),t.notifier.dispatch(I.ColorPickerColorSelected,{kind:I.ColorPickerColorSelected,color:i}))};return r.oninput=o,r.addEventListener("open",(()=>{t.notifier.dispatch(I.ColorPickerToggled,{kind:I.ColorPickerToggled,open:!0})})),r.addEventListener("close",(()=>{t.notifier.dispatch(I.ColorPickerToggled,{kind:I.ColorPickerToggled,open:!1}),s()})),[r,n]};var Ce,Pe=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},Ee=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 ze{constructor(t,e){this.editor=t,this.localizationTable=e,Ce.set(this,void 0),this.disabled=!1,this.subWidgets=[],this.icon=null,this.container=document.createElement("div"),this.container.classList.add(`${Ne}toolContainer`),this.dropdownContainer=document.createElement("div"),this.dropdownContainer.classList.add(`${Ne}dropdown`),this.dropdownContainer.classList.add("hidden"),Pe(this,Ce,!1,"f"),this.button=document.createElement("div"),this.button.classList.add(`${Ne}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);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:A.KeyPressEvent,key:t.key,ctrlKey:t.ctrlKey})},t.onkeyup=t=>{t.key in e||this.editor.toolController.dispatchInputEvent({kind:A.KeyUpEvent,key:t.key,ctrlKey:t.ctrlKey})},t.onclick=()=>{this.disabled||this.handleClick()}}get hasDropdown(){return Ee(this,Ce,"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),Pe(this,Ce,this.fillDropdown(this.dropdownContainer),"f"),Ee(this,Ce,"f")&&(this.dropdownIcon=this.createDropdownIcon(),this.button.appendChild(this.dropdownIcon),this.container.appendChild(this.dropdownContainer)),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(`${Ne}icon`)}setDisabled(t){this.disabled=t,this.disabled?this.button.classList.add("disabled"):this.button.classList.remove("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.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="")}isDropdownVisible(){return!this.dropdownContainer.classList.contains("hidden")}isSelected(){return this.container.classList.contains("selected")}createDropdownIcon(){const t=(()=>{const t=document.createElementNS(ce,"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${he}\n\t\t/>\n\t</g>\n\t`,t.setAttribute("viewBox","0 0 100 100"),t})();return t.classList.add(`${Ne}showHideDropdownIcon`),t}}Ce=new WeakMap;class Re extends ze{constructor(t,e,n){super(t,n),this.editor=t,this.targetTool=e,this.localizationTable=n,t.notifier.on(I.ToolEnabled,(t=>{if(t.kind!==I.ToolEnabled)throw new Error("Incorrect event type! (Expected ToolEnabled)");t.tool===e&&this.setSelected(!0)})),t.notifier.on(I.ToolDisabled,(t=>{if(t.kind!==I.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 Be extends Re{constructor(t,e,n){super(t,e,n),this.tool=e,this.updateInputs=()=>{},this.penTypes=[{name:n.freehandPen,factory:St},{name:n.arrowPen,factory:ge},{name:n.linePen,factory:ve},{name:n.filledRectanglePen,factory:be},{name:n.outlinedRectanglePen,factory:we}],this.editor.notifier.on(I.ToolUpdated,(t=>{if(t.kind!==I.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()===St){return((t,e)=>{const n=document.createElementNS(ce,"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${de}\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})(Math.round(4*Math.sqrt(this.tool.getThickness())),this.tool.getColor().toHexString())}{const t=this.tool.getStrokeFactory();return((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 U(new Gt),a=e(i,s);a.addPoint(o);const l=document.createElementNS(ce,"svg");l.setAttribute("viewBox","0 0 100 100"),s.updateScreenSize(k.of(100,100));const c=new le(l,s);return a.preview(c),l})(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=`${Ne}thicknessInput${Be.idCounter++}`,a.id=`${Ne}builderSelect${Be.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="1",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]=Se(this.editor,(t=>{this.tool.setColor(t)}));return h.id=`${Ne}colorInput${Be.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}}Be.idCounter=0;class Le extends Re{getTitle(){return this.localizationTable.eraser}createIcon(){return(()=>{const t=document.createElementNS(ce,"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${he}\n\t\t/>\n\t</g>\n\t`,t.setAttribute("viewBox","0 0 100 100"),t})()}fillDropdown(t){return!1}}class Me extends Re{constructor(t,e,n){super(t,e,n),this.tool=e}getTitle(){return this.localizationTable.select}createIcon(){return(()=>{const t=document.createElementNS(ce,"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})()}fillDropdown(t){const e=document.createElement("div"),n=document.createElement("button"),r=document.createElement("button"),i=document.createElement("button");return n.innerText=this.localizationTable.resizeImageToSelection,n.disabled=!0,i.innerText=this.localizationTable.deleteSelection,i.disabled=!0,r.innerText=this.localizationTable.duplicateSelection,r.disabled=!0,n.onclick=()=>{const t=this.tool.getSelection();this.editor.dispatch(this.editor.setImportExportRect(t.region))},i.onclick=()=>{const t=this.tool.getSelection();this.editor.dispatch(t.deleteSelectedObjects()),this.tool.clearSelection()},r.onclick=()=>{const t=this.tool.getSelection();this.editor.dispatch(t.duplicateSelectedObjects())},this.editor.notifier.on(I.ToolUpdated,(t=>{if(t.kind!==I.ToolUpdated)throw new Error("Invalid event type!");if(t.tool===this.tool){const t=this.tool.getSelection(),e=t&&t.region.area>0;n.disabled=!e,i.disabled=n.disabled,r.disabled=n.disabled}})),e.replaceChildren(n,r,i),t.appendChild(e),!0}}class Ae extends Re{constructor(t,e,n){super(t,e,n),this.tool=e,this.updateDropdownInputs=null,t.notifier.on(I.ToolUpdated,(t=>{var n;t.kind===I.ToolUpdated&&t.tool===e&&(this.updateIcon(),null===(n=this.updateDropdownInputs)||void 0===n||n.call(this))}))}getTitle(){return this.targetTool.description}createIcon(){return(t=>{var e,n;const r=document.createElementNS(ce,"svg");r.setAttribute("viewBox","0 0 100 100");const i=document.createElementNS(ce,"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})(this.tool.getTextStyle())}fillDropdown(t){const e=document.createElement("div"),n=document.createElement("div"),r=document.createElement("select"),i=document.createElement("label"),[o,s]=Se(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=`${Ne}-text-color-input-${Ae.idCounter++}`,a.setAttribute("for",o.id),c("monospace"),c("serif"),c("sans-serif"),r.id=`${Ne}-text-font-input-${Ae.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}}Ae.idCounter=0;class Ie extends ze{constructor(t,e){super(t,e),this.container.classList.add("dropdownShowable")}getTitle(){return this.localizationTable.zoom}createIcon(){return(()=>{const t=document.createElementNS(ce,"svg");t.setAttribute("viewBox","0 0 100 100");const e=(e,n,r)=>{const i=document.createElementNS(ce,"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})()}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(`${Ne}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(I.ViewportChanged,(t=>{t.kind===I.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(new U.ViewportTransform(r),!1)};return r.onclick=()=>{c(5/4)},i.onclick=()=>{c(.8)},o.onclick=()=>{e.dispatch(new U.ViewportTransform(e.viewport.canvasToScreenTransform.inverse()),!0)},n})(this.localizationTable,this.editor)),!0}}class Oe extends ze{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(I.ToolUpdated,(t=>{if(t.kind===I.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 De extends Re{constructor(t,e,n){super(t,e,n),this.tool=e,this.container.classList.add("dropdownShowable"),this.touchPanningWidget=new Oe(t,n,e,_.OneFingerTouchGestures,fe,n.touchPanning),this.addSubWidget(this.touchPanningWidget),this.addSubWidget(new Oe(t,n,e,_.SinglePointerGestures,me,n.anyDevicePanning)),this.addSubWidget(new Ie(t,n))}getTitle(){return this.localizationTable.handTool}createIcon(){return(()=>{const t=document.createElementNS(ce,"svg");return t.innerHTML="\n\t<g>\n\t\t<path d='\n\t\t\tm 10,60\n\t\t\t 5,30\n\t\t\tH 90\n\t\t\tV 30\n\t\t\tC 90,20 75,20 75,30\n\t\t\tV 60\n\t\t\t 20\n\t\t\tC 75,10 60,10 60,20\n\t\t\tV 60\n\t\t\t 15\n\t\t\tC 60,5 45,5 45,15\n\t\t\tV 60\n\t\t\t 25\n\t\t\tC 45,15 30,15 30,25\n\t\t\tV 60\n\t\t\t 75\n\t\t\tL 25,60\n\t\t\tC 20,45 10,50 10,60 \n\t\t\tZ'\n\t\t\t\n\t\t\tfill='none'\n\t\t\tstyle='\n\t\t\t\tstroke: var(--icon-color);\n\t\t\t\tstroke-width: 2;\n\t\t\t'\n\t\t/>\n\t</g>\n\t",t.setAttribute("viewBox","0 0 100 100"),t})()}setSelected(t){}handleClick(){this.setDropdownVisible(!this.isDropdownVisible())}}const Ne="toolbar-";class $e{constructor(t,e,n=Xt){this.editor=t,this.localizationTable=n,this.container=document.createElement("div"),this.container.classList.add(`${Ne}root`),this.container.setAttribute("role","toolbar"),e.appendChild(this.container),$e.colorisStarted||(Kt(),$e.colorisStarted=!0),this.setupColorPickers()}setupColorPickers(){const t=document.createElement("div");t.className=`${Ne}closeColorPickerOverlay`,this.editor.createHTMLOverlay(t);const e=[yt.red.toHexString(),yt.purple.toHexString(),yt.blue.toHexString(),yt.clay.toHexString(),yt.black.toHexString(),yt.white.toHexString()],n=e.length,r=()=>{qt({el:".coloris_input",format:"hex",selectInput:!1,focusInput:!1,themeMode:"auto",swatches:e})};r();this.editor.notifier.on(I.ColorPickerToggled,(e=>{e.kind===I.ColorPickerToggled&&(t.style.display=e.open?"block":"none")})),this.editor.notifier.on(I.ColorPickerColorSelected,(t=>{t.kind===I.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())}))}addActionButton(t,e,n){const r=document.createElement("button");if(r.classList.add(`${Ne}toolButton`),"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(`${Ne}buttonGroup`);const e=this.addActionButton({label:this.localizationTable.undo,icon:pe(!0)},(()=>{this.editor.history.undo()}),t),n=this.addActionButton({label:this.localizationTable.redo,icon:pe()},(()=>{this.editor.history.redo()}),t);this.container.appendChild(t),e.disabled=!0,n.disabled=!0,this.editor.notifier.on(I.UndoRedoStackUpdated,(t=>{if(t.kind!==I.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(Wt.Pen)){if(!(e instanceof Pt))throw new Error("All `Pen` tools must have kind === ToolType.Pen");new Be(this.editor,e,this.localizationTable).addTo(this.container)}for(const e of t.getMatchingTools(Wt.Eraser)){if(!(e instanceof Bt))throw new Error("All Erasers must have kind === ToolType.Eraser!");new Le(this.editor,e,this.localizationTable).addTo(this.container)}for(const e of t.getMatchingTools(Wt.Selection)){if(!(e instanceof Dt))throw new Error("All SelectionTools must have kind === ToolType.Selection");new Me(this.editor,e,this.localizationTable).addTo(this.container)}for(const e of t.getMatchingTools(Wt.Text)){if(!(e instanceof Vt))throw new Error("All text tools must have kind === ToolType.Text");new Ae(this.editor,e,this.localizationTable).addTo(this.container)}const e=t.getMatchingTools(Wt.PanZoom)[0];e&&e instanceof H&&new De(this.editor,e,this.localizationTable).addTo(this.container),this.setupColorPickers()}addDefaultActionButtons(){this.addUndoRedoButtons()}}$e.colorisStarted=!1;class je extends se{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 je}renderFromOtherOfSameType(t,e){if(!(e instanceof je))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=64,this.minRenderSizeBothDimens=8,this.minRenderSizeAnyDimen=2):(this.minSquareCurveApproxDist=1,this.minRenderSizeBothDimens=1,this.minRenderSizeAnyDimen=0)}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),jt.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()}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=yt.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 Fe extends se{constructor(t){super(t),this.clearedCount=0,this.renderedPathCount=0,this.lastFillStyle=null,this.lastPoint=null,this.objectNestingLevel=0,this.lastText=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.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}startObject(t,e){super.startObject(t),this.objectNestingLevel+=1}endObject(){super.endObject(),this.objectNestingLevel-=1}isTooSmallToRender(t){return!1}canRenderFromWithoutDataLoss(t){return t instanceof Fe}renderFromOtherOfSameType(t,e){if(!(e instanceof Fe))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 Ve=!1;class Ue{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 Ue(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 Ue(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}renderingIsUpToDate(t){if(null===this.cachedRenderer||t.length!==this.renderedIds.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==this.renderedIds[e])return!1;return!0}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=[];for(const t of e)o.push(...t.getLeavesIntersectingRegion(this.region,(t=>t.w/this.region.w<2/this.cacheState.props.blockResolution.x)));B(o);const s=this.computeSortedByLeafIds(o);if(0===s.length)return;const a=s.map((t=>t.getId()));let l;if(this.renderingIsUpToDate(a))l=this.cachedRenderer.startRender();else{if(this.allChildrenCanRender(n,s)){for(const r of this.getChildren())r.renderItems(t,e,n);return}if(s.length>this.cacheState.props.minComponentsPerCache){let t=!0;if(this.cachedRenderer){if(s.length>this.renderedIds.length&&null!==this.renderedMaxZIndex){const e=[];let n=null;for(let t=0;t<s.length;t++){const r=s[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,l=this.cachedRenderer.startRender();for(let t=0;t<o.length;t++){const e=o[t],n=e.getContent().getZIndex();n>this.renderedMaxZIndex&&(e.render(l,this.region),this.renderedMaxZIndex=n)}Ve}}}else this.cachedRenderer=this.cacheState.recordManager.allocCanvas(this.region,(()=>this.onRegionDealloc()));if(t){l=this.cachedRenderer.startRender(),l.clear(),this.renderedMaxZIndex=null;for(const t of o){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(l,this.region)}Ve}this.renderedIds=a}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),s=!0;t.startObject(r,s);for(const e of o)e.render(t,this.region.intersection(n.visibleRect));t.endObject()}}if(l){const e=this.cachedRenderer.getTransform(this.region).inverse();t.renderFromOtherOfSameType(e,l)}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 We{constructor(t,e){this.onBeforeDeallocCallback=t,this.cacheState=e,this.allocd=!1,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}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 _e{constructor(t){this.cacheState=t,this.cacheRecords=[];const e=t.props;this.maxCanvases=Math.ceil(e.cacheSize/4/e.blockResolution.x/e.blockResolution.y)}allocCanvas(t,e){if(this.cacheRecords.length<this.maxCanvases){const n=new We(e,Object.assign(Object.assign({},this.cacheState),{recordManager:this}));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 He{constructor(t){this.partialSharedState={props:t,currentRenderingCycle:0},this.recordManager=new _e(this.partialSharedState)}getSharedState(){return Object.assign(Object.assign({},this.partialSharedState),{recordManager:this.recordManager})}render(t,e,n){var r;const i=n.visibleRect;if(this.partialSharedState.currentRenderingCycle++,!this.partialSharedState.props.isOfCorrectType(t))return void e.render(t,i);if(!this.rootNode){const t=this.partialSharedState.props.blockResolution,e=i.topLeft;this.rootNode=new Ue(new R(e.x,e.y,t.x,t.y),this.getSharedState())}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.partialSharedState.props.minComponentsToUseCache?this.rootNode.renderItems(t,[e],n):e.render(t,i)}}class Ge extends se{constructor(t,e){super(t),this.localizationTable=e,this.descriptionBuilder=[]}displaySize(){return k.of(500,500)}clear(){this.descriptionBuilder=[]}getDescription(){return this.descriptionBuilder.join("\n")}beginPath(t){}endPath(t){}lineTo(t){}moveTo(t){}traceCubicBezierCurve(t,e,n){}traceQuadraticBezierCurve(t,e){}drawText(t,e,n){this.descriptionBuilder.push(this.localizationTable.textNode(t))}isTooSmallToRender(t){return t.maxDimension<10/this.getSizeOfCanvasPixelOnScreen()}drawPoints(...t){}}var Ze;!function(t){t[t.DummyRenderer=0]="DummyRenderer",t[t.CanvasRenderer=1]="CanvasRenderer"}(Ze||(Ze={}));class qe{constructor(t,e,n){if(this.editor=t,this.parent=n,this.getColorAt=t=>null,e===Ze.CanvasRenderer)this.initializeCanvasRendering();else{if(e!==Ze.DummyRenderer)throw new Error(`Unknown rendering mode, ${e}!`);this.dryInkRenderer=new Fe(t.viewport),this.wetInkRenderer=new Fe(t.viewport)}this.textRenderer=new Ge(t.viewport,t.localization),this.initializeTextRendering();const r=k.of(600,600);this.cache=new He({createRenderer:()=>{if(e===Ze.DummyRenderer)return new Fe(t.viewport);if(e!==Ze.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 je(i,t.viewport)},isOfCorrectType:t=>this.dryInkRenderer.canRenderFromWithoutDataLoss(t),blockResolution:r,cacheSize:2e8,maxScale:1.5,minComponentsPerCache:50,minComponentsToUseCache:120}),this.editor.notifier.on(I.DisplayResized,(t=>{var e;if(t.kind!==I.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 je(n,this.editor.viewport),this.wetInkRenderer=new je(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(I.DisplayResized,{kind:I.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 yt.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;const n=document.createElement("div");n.ariaLive="polite",e.onclick=()=>{this.textRenderer.clear(),this.editor.image.render(this.textRenderer,this.editor.viewport),n.innerText=this.textRenderer.getDescription()},t.replaceChildren(e,n),this.editor.createHTMLOverlay(t)}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 Ke={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}`,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"}`},Xe=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Xt),{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",toolEnabledAnnouncement:t=>`${t} enabled`,toolDisabledAnnouncement:t=>`${t} disabled`}),Ke),{stroke:"Stroke",svgObject:"SVG Object",text:t=>`Text object: ${t}`}),{textNode:t=>`Text: ${t}`,rerenderAsText:"Re-render as text"}),{loading:t=>`Loading ${t}%...`,imageEditor:"Image Editor",doneLoading:"Done loading",undoAnnouncement:t=>`Undid ${t}`,redoAnnouncement:t=>`Redid ${t}`}),Ye={en:Object.assign({},Xe),es:Object.assign(Object.assign({},Xe),{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",pickColorFronScreen:"Selecciona un color de la pantalla",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"})},Qe=t=>{const e=/^(\w+)[_-](\w+)$/.exec(t);return e?e[1]:t},Je=t=>{let e;null!=t||(t=navigator.languages);for(const n of t){const t=Qe(n);if(e&&t!==e&&e in Ye)return Ye[e];if(n in Ye)return Ye[n];e=t}return e&&e in Ye?Ye[e]:Xe};var tn=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 en=class{constructor(t,e={}){var n,r,i,o;this.announceUndoCallback=t=>{this.announceForAccessibility(this.localization.undoAnnouncement(t.description(this.localization)))},this.announceRedoCallback=t=>{this.announceForAccessibility(this.localization.redoAnnouncement(t.description(this.localization)))},this.rerenderQueued=!1,this.localization=Object.assign(Object.assign({},Je()),e.localization),this.settings={wheelEventsEnabled:null===(n=e.wheelEventsEnabled)||void 0===n||n,renderingMode:null!==(r=e.renderingMode)&&void 0!==r?r:Ze.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.accessibilityAnnounceArea=document.createElement("div"),this.accessibilityAnnounceArea.ariaLive="assertive",this.accessibilityAnnounceArea.className="accessibilityAnnouncement",this.container.appendChild(this.accessibilityAnnounceArea),this.renderingRegion.style.touchAction="none",this.renderingRegion.className="imageEditorRenderArea",this.renderingRegion.setAttribute("tabIndex","0"),this.renderingRegion.ariaLabel=this.localization.imageEditor,this.notifier=new Gt,this.importExportViewport=new U(this.notifier),this.viewport=new U(this.notifier),this.display=new qe(this,this.settings.renderingMode,this.renderingRegion),this.image=new L,this.history=new Ht(this,this.announceRedoCallback,this.announceUndoCallback),this.toolController=new _t(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(I.ViewportChanged,(t=>{if(t.kind===I.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){this.accessibilityAnnounceArea.innerText=t}addToolbar(t=!0){const e=new $e(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=D.ofEvent(n,!0,this.viewport);t[r.id]=r,this.renderingRegion.setPointerCapture(r.id);const i={kind:A.PointerDownEvt,current:r,allPointers:e()};return this.toolController.dispatchInputEvent(i),!0})),this.renderingRegion.addEventListener("pointermove",(n=>{var r,i;const o=D.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:A.PointerMoveEvt,current:o,allPointers:e()})&&n.preventDefault()}}));const n=n=>{const r=D.ofEvent(n,!1,this.viewport);t[r.id]&&(t[r.id]=r,this.renderingRegion.releasePointerCapture(r.id),this.toolController.dispatchInputEvent({kind:A.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=T.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=T.of(0,0,t.deltaY));const n=k.of(t.offsetX,t.offsetY);return!!this.toolController.dispatchInputEvent({kind:A.WheelEvt,delta:e,screenPos:n})&&(t.preventDefault(),!0)})),this.notifier.on(I.DisplayResized,(t=>{this.viewport.updateScreenSize(k.of(this.display.width,this.display.height))})),window.addEventListener("resize",(()=>{this.notifier.dispatch(I.DisplayResized,{kind:I.DisplayResized,newSize:k.of(this.display.width,this.display.height)}),this.queueRerender()}))}handleKeyEventsFrom(t){t.addEventListener("keydown",(t=>{this.toolController.dispatchInputEvent({kind:A.KeyPressEvent,key:t.key,ctrlKey:t.ctrlKey})?t.preventDefault():"Escape"===t.key&&this.renderingRegion.blur()})),t.addEventListener("keyup",(t=>{this.toolController.dispatchInputEvent({kind:A.KeyUpEvent,key:t.key,ctrlKey:t.ctrlKey})&&t.preventDefault()}))}dispatch(t,e=!0){e?this.history.push(t):t.apply(this),this.announceForAccessibility(t.description(this.localization))}dispatchNoAnnounce(t,e=!1){e?this.history.push(t):t.apply(this)}asyncApplyOrUnapplyCommands(t,e,n){return tn(this,void 0,void 0,(function*(){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:yt.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=D.ofCanvasPoint(e,t!==A.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 le(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 tn(this,void 0,void 0,(function*(){this.showLoadingWarning(0),this.display.setDraftMode(!0),yield t.start((t=>{this.dispatchNoAnnounce(L.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 b{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){return e.resizeOutputCommand(t)}}}loadFromSVG(t){return tn(this,void 0,void 0,(function*(){const e=oe.fromString(t);yield this.loadFrom(e)}))}},nn=en})(),window.jsdraw=i})();