Files
2026-08-23 20:43:00 -04:00

9 lines
240 KiB
JavaScript

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var Pr=Object.defineProperty;var sa=Object.getOwnPropertyDescriptor;var aa=Object.getOwnPropertyNames;var la=Object.prototype.hasOwnProperty;var ca=(r,e)=>{for(var t in e)Pr(r,t,{get:e[t],enumerable:!0})},da=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of aa(e))!la.call(r,o)&&o!==t&&Pr(r,o,{get:()=>e[o],enumerable:!(n=sa(e,o))||n.enumerable});return r};var ua=r=>da(Pr({},"__esModule",{value:!0}),r);var _u={};ca(_u,{default:()=>mr});module.exports=ua(_u);var Y=require("obsidian");var ro=require("obsidian");function no(r){let e=r.workspace.getMostRecentLeaf();if(!e)return null;let t=e.view;if(t.getViewType()!=="canvas")return null;let n=ha(r,t);return!n||n.extension!=="canvas"?null:{leaf:e,view:t,file:n,containerEl:t.containerEl}}function ha(r,e){let t=e.file;if(t instanceof ro.TFile)return t;let n=r.workspace.getActiveFile();return(n==null?void 0:n.extension)==="canvas"?n:null}var I=require("obsidian");var X=require("obsidian");var H={strokeThinning:{label:"Thinning",min:-.99,max:.99,step:.01,defaultValue:.5,ariaLabel:"Stroke thinning"},strokeStreamline:{label:"Streamline",min:.01,max:.99,step:.01,defaultValue:.5,ariaLabel:"Stroke streamline"},strokeSmoothing:{label:"Smoothing",min:.01,max:.99,step:.01,defaultValue:.5,ariaLabel:"Stroke smoothing"},strokeTaperStart:{label:"Taper start",min:0,max:100,step:1,defaultValue:8,ariaLabel:"Stroke taper start"},strokeTaperEnd:{label:"Taper end",min:0,max:100,step:1,defaultValue:8,ariaLabel:"Stroke taper end"}},Ce={strokeColor:"#ff5a5f",strokeWidth:4,strokeHardness:100,strokeOpacity:100,beautifulStrokes:!1,usePenCursorFallback:!0,allowTinyCanvasElements:!1,strokeThinning:.5,strokeStreamline:.5,strokeSmoothing:.5,strokeTaperStart:8,strokeTaperEnd:8};function y(r){let e=typeof r=="number"?r:Number(r);if(!Number.isFinite(e))return 4;let t=Math.round(e/1)*1;return Math.min(32,Math.max(1,t))}function x(r){let e=typeof r=="number"?r:Number(r);if(!Number.isFinite(e))return 100;let t=Math.round(e/1)*1;return Math.min(100,Math.max(0,t))}function f(r){let e=typeof r=="number"?r:Number(r);if(!Number.isFinite(e))return 100;let t=Math.round(e/1)*1;return Math.min(100,Math.max(1,t))}function k(r,e){let t=H[r],n=typeof e=="number"?e:Number(e);if(!Number.isFinite(n))return t.defaultValue;let o=Math.round(n/t.step)*t.step,i=Math.min(t.max,Math.max(t.min,o));return pa(i,t.step)}function oo(r){var t;let e=r!=null?r:{};return{...Ce,...e,strokeColor:((t=e.strokeColor)==null?void 0:t.trim())||Ce.strokeColor,strokeWidth:y(e.strokeWidth),strokeHardness:x(e.strokeHardness),strokeOpacity:f(e.strokeOpacity),beautifulStrokes:e.beautifulStrokes===!0,usePenCursorFallback:e.usePenCursorFallback!==!1,allowTinyCanvasElements:e.allowTinyCanvasElements===!0,strokeThinning:k("strokeThinning",e.strokeThinning),strokeStreamline:k("strokeStreamline",e.strokeStreamline),strokeSmoothing:k("strokeSmoothing",e.strokeSmoothing),strokeTaperStart:k("strokeTaperStart",e.strokeTaperStart),strokeTaperEnd:k("strokeTaperEnd",e.strokeTaperEnd)}}function pa(r,e){var n,o;let t=(o=(n=e.toString().split(".")[1])==null?void 0:n.length)!=null?o:0;return Number(r.toFixed(t))}var kt=class extends X.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this;e.empty();let t=activeDocument.createElement("h2");t.textContent="Draw in canvas",e.appendChild(t),new X.Setting(e).setName("Stroke color").setDesc("Any CSS color, such as #ff5a5f, red, or rgb(255, 90, 95).").addText(o=>o.setPlaceholder(Ce.strokeColor).setValue(this.plugin.settings.strokeColor).onChange(async i=>{this.plugin.settings.strokeColor=i.trim()||Ce.strokeColor,this.plugin.refreshActiveLayerSettings(),await this.plugin.saveSettings()})),new X.Setting(e).setName("Stroke width").setDesc("Screen-pixel width for new freehand strokes at the current canvas zoom.").addSlider(o=>o.setLimits(1,32,1).setValue(y(this.plugin.settings.strokeWidth)).setDynamicTooltip().onChange(i=>{this.plugin.setStrokeWidth(i)})),new X.Setting(e).setName("Stroke hardness").setDesc("Softens new stroke edges like brush hardness.").addSlider(o=>o.setLimits(0,100,1).setValue(x(this.plugin.settings.strokeHardness)).setDynamicTooltip().onChange(i=>{this.plugin.setStrokeHardness(i)})),new X.Setting(e).setName("Stroke opacity").setDesc("Controls how transparent new strokes are, like brush opacity.").addSlider(o=>o.setLimits(1,100,1).setValue(f(this.plugin.settings.strokeOpacity)).setDynamicTooltip().onChange(i=>{this.plugin.setStrokeOpacity(i)})),new X.Setting(e).setName("Handwritten strokes").setDesc("Smooth strokes with subtle tapered starts and ends. Pen strokes use real stylus pressure when available.").addToggle(o=>o.setValue(this.plugin.settings.beautifulStrokes).onChange(i=>{this.plugin.setBeautifulStrokes(i)})),new X.Setting(e).setName("Stylus pointer fallback").setDesc("Show a plugin pointer while drawing with a stylus when the native pointer is hidden or unreliable.").addToggle(o=>o.setValue(this.plugin.settings.usePenCursorFallback).onChange(i=>{this.plugin.setPenCursorFallback(i)})),new X.Setting(e).setName("Allow tiny canvas items").setDesc("Lower Obsidian's canvas item size limit so native cards, groups, and plugin strokes can be resized much smaller. Also lets native canvas zoom go past the normal zoom-in limit, adds +/\u2212 size buttons and a layer submenu to the native selection menu, and keeps shift-resizing proportional while this plugin is active.").addToggle(o=>o.setValue(this.plugin.settings.allowTinyCanvasElements).onChange(i=>{this.plugin.setAllowTinyCanvasElements(i)}));let n=activeDocument.createElement("p");n.classList.add("setting-item-description"),n.textContent="Drawings are stored inside each .canvas file as plugin JSON metadata.",e.appendChild(n)}};var ye={beautifulStrokes:!1,strokeThinning:.5,strokeStreamline:.5,strokeSmoothing:.5,strokeTaperStart:8,strokeTaperEnd:8},Sa={strokeThinning:{min:-.99,max:.99,step:.01,defaultValue:ye.strokeThinning},strokeStreamline:{min:.01,max:.99,step:.01,defaultValue:ye.strokeStreamline},strokeSmoothing:{min:.01,max:.99,step:.01,defaultValue:ye.strokeSmoothing},strokeTaperStart:{min:0,max:100,step:1,defaultValue:ye.strokeTaperStart},strokeTaperEnd:{min:0,max:100,step:1,defaultValue:ye.strokeTaperEnd}},va=2;function He(r){return{enabled:r.beautifulStrokes===!0,thinning:j("strokeThinning",r.strokeThinning),streamline:j("strokeStreamline",r.strokeStreamline),smoothing:j("strokeSmoothing",r.strokeSmoothing),taperStart:j("strokeTaperStart",r.strokeTaperStart),taperEnd:j("strokeTaperEnd",r.strokeTaperEnd)}}function Lr(r,e=ye){var n,o,i;let t=He(e);return ao(r)?{enabled:typeof r.enabled=="boolean"?r.enabled:t.enabled,thinning:j("strokeThinning",(n=r.thinning)!=null?n:t.thinning),streamline:j("strokeStreamline",(o=r.streamline)!=null?o:t.streamline),smoothing:j("strokeSmoothing",(i=r.smoothing)!=null?i:t.smoothing),taperStart:io(r.taperStart,t.taperStart),taperEnd:io(r.taperEnd,t.taperEnd)}:t}function ne(r,e=ye){return Dr(r.handwriting)?r.handwriting:Lr(r.handwriting,e)}function Dr(r){return ao(r)&&typeof r.enabled=="boolean"&&Rr("strokeThinning",r.thinning)&&Rr("strokeStreamline",r.streamline)&&Rr("strokeSmoothing",r.smoothing)&&Nr(r.taperStart)&&Nr(r.taperEnd)}function so(r,e){return!Number.isFinite(r)||!Number.isFinite(e)||e<=0?!0:r>=e*va}function j(r,e){let t=Sa[r],n=typeof e=="number"?e:Number(e);if(!Number.isFinite(n))return t.defaultValue;let o=Math.round(n/t.step)*t.step,i=Math.min(t.max,Math.max(t.min,o));return ma(i,t.step)}function io(r,e){return Nr(r)?r:e}function Nr(r){return typeof r=="number"&&Number.isFinite(r)&&r>=0}function Rr(r,e){return typeof e=="number"&&Number.isFinite(e)&&j(r,e)===e}function ma(r,e){var n,o;let t=(o=(n=e.toString().split(".")[1])==null?void 0:n.length)!=null?o:0;return Number(r.toFixed(t))}function ao(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}var Ar="drawInCanvas";function tt(){return{version:2,strokes:[],colorHistory:[]}}function w(){return`stroke-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function v(r){return Math.round(r*1e4)/1e4}function Rt(r){if(typeof r!="number"||!Number.isFinite(r))return;let e=Math.min(1,Math.max(0,r));return Math.round(e*1e3)/1e3}function Mr(r,e={}){return e.smooth?ga(r):lo(r)}function lo(r){let e=r[0];if(!e)return"";let t=[`M ${R(e.x)} ${R(e.y)}`];if(r.length===1)return t.push(`L ${R(e.x+.01)} ${R(e.y+.01)}`),t.join(" ");for(let n=1;n<r.length;n++){let o=r[n];o&&t.push(`L ${R(o.x)} ${R(o.y)}`)}return t.join(" ")}function ga(r){let e=r[0];if(!e||r.length<3)return lo(r);let t=[`M ${R(e.x)} ${R(e.y)}`];for(let o=1;o<r.length-1;o++){let i=r[o],s=r[o+1];if(!i||!s)continue;let a={x:(i.x+s.x)/2,y:(i.y+s.y)/2};t.push(`Q ${R(i.x)} ${R(i.y)} ${R(a.x)} ${R(a.y)}`)}let n=r[r.length-1];return n&&t.push(`L ${R(n.x)} ${R(n.y)}`),t.join(" ")}function R(r){return v(r).toString()}async function uo(r,e,t){let n=await So(r,e);return po(n[Ar],t)}async function ho(r,e,t){let n=await So(r,e);n[Ar]=po(t).data,await ba(r,e,n)}function po(r,e){if(!Lt(r))return{data:tt(),didBackfillStrokeHandwriting:!1};let n=(Array.isArray(r.strokes)?r.strokes:[]).map(s=>Ea(s,e)).filter(vo),o=n.map(s=>s.stroke),i=Ca(r.colorHistory);return{data:{version:2,strokes:o,colorHistory:i},didBackfillStrokeHandwriting:n.some(s=>s.didBackfillStrokeHandwriting)}}function Ca(r){if(!Array.isArray(r))return[];let e=[];for(let t of r){if(typeof t!="string")continue;let n=ya(t);if(!(!n||e.includes(n))&&(e.push(n),e.length>=10))break}return e}function ya(r){let e=/^#?([\da-f]{6})$/i.exec(r.trim()),t=e==null?void 0:e[1];return t?`#${t.toLowerCase()}`:null}function Ea(r,e){if(!Lt(r))return null;let n=(Array.isArray(r.points)?r.points:[]).map(ka).filter(vo);return n.length===0?null:{stroke:{id:typeof r.id=="string"&&r.id.length>0?r.id:w(),color:typeof r.color=="string"&&r.color.length>0?r.color:"#ff5a5f",width:co(r.width,4),hardness:x(r.hardness),opacity:f(r.opacity),handwriting:Lr(r.handwriting,e),points:n,createdAt:co(r.createdAt,Date.now())},didBackfillStrokeHandwriting:!Dr(r.handwriting)}}function ka(r){if(!Lt(r)||typeof r.x!="number"||typeof r.y!="number"||!Number.isFinite(r.x)||!Number.isFinite(r.y))return null;let e=Rt(r.pressure),t={x:r.x,y:r.y};return e!==void 0&&(t.pressure=e),t}function co(r,e){return typeof r=="number"&&Number.isFinite(r)&&r>0?r:e}async function So(r,e){let t=await r.vault.read(e),n=JSON.parse(t||"{}");if(!Lt(n))throw new Error("Canvas file did not contain a JSON object.");return n}async function ba(r,e,t){await r.vault.modify(e,`${JSON.stringify(t,null," ")}
`)}function Lt(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function vo(r){return r!==null}function mo(r){return!Number.isFinite(r)||r<=0?1:Math.min(1,r)}function go(r){return Number.isFinite(r)?Math.min(12,Math.max(-4,r)):r>0?12:-4}function fo(r){return Number.isFinite(r)?Math.min(4096,Math.max(.0625,r)):r>0?4096:.0625}var Hr=20,wa=2**1;function yo(r){if(!Number.isFinite(r))return Hr;if(r>1){let e=Hr/2**(r-1);return Number.isFinite(e)&&e>0?e:Number.EPSILON}return Pa(r)}function Eo(r,e){return Co(r)?Co(e)?e<=wa?Math.ceil(r/e):r/e:Math.ceil(r):0}function Pa(r){return r<-3.3?160:r<-2.16?80:r<-.91?40:Hr}function Co(r){return typeof r=="number"&&Number.isFinite(r)&&r>0}var ko=10,bo=2**1,Be=new WeakMap;function To(r){var t;let e=(t=r.menu)==null?void 0:t.selection;return e?Aa(e):null}function xo(r){let e=Be.get(r);if(e)return e.refCount++,()=>wo(r);let t=r.update,n=Object.prototype.hasOwnProperty.call(r,"update");if(!Br(t))return _a;let o={original:t,patched:Ta(t),hadOwnUpdate:n,refCount:1};return r.update=o.patched,Be.set(r,o),()=>wo(r)}function wo(r){let e=Be.get(r);e&&(e.refCount--,!(e.refCount>0)&&(r.update===e.patched&&(e.hadOwnUpdate?r.update=e.original:delete r.update),Be.delete(r)))}function Ta(r){return function(t){if(!La(this,t)){r.call(this,t);return}try{xa(this,t)}catch(n){r.call(this,t)}}}function xa(r,e){var s,a,l,c;let t=r.selectionEl,n=(s=r.canvas)==null?void 0:s.canvasEl;r.bbox=e,t.parentNode||(a=n.appendChild)==null||a.call(n,t);for(let d of(l=r.resizerEls)!=null?l:[])(c=t.appendChild)==null||c.call(t,d);let o=Ia(r),i=Na(e,o);Ma(t,{transform:`translate(${Dt(i.minX)}, ${Dt(i.minY)})`,width:Dt(i.maxX-i.minX),height:Dt(i.maxY-i.minY)})}function Ia(r){var t;if(Ra(r))return 0;let e=(t=r.canvas)==null?void 0:t.scale;return!Ba(e)||e<=bo?ko:ko*bo/e}function Ra(r){let e=r.selectionEl;return!!e&&!Po(e,"mod-group-selection")&&!Po(e,"mod-node-highlight")}function Na(r,e){return{minX:r.minX-e,minY:r.minY-e,maxX:r.maxX+e,maxY:r.maxY+e}}function La(r,e){var t;return Da(e)&&!!r.selectionEl&&!!((t=r.canvas)!=null&&t.canvasEl)}function Da(r){return rt(r.minX)&&rt(r.minY)&&rt(r.maxX)&&rt(r.maxY)}function Aa(r){let e=Object.getPrototypeOf(r);for(;e&&e!==Object.prototype;){if(Object.prototype.hasOwnProperty.call(e,"update"))return Be.has(e)||Br(e.update)?e:null;e=Object.getPrototypeOf(e)}return Object.prototype.hasOwnProperty.call(r,"update")&&(Be.has(r)||Br(r.update))?r:null}function Br(r){if(typeof r!="function")return!1;let e=Function.prototype.toString.call(r);return e.includes("selectionEl")&&e.includes("resizerEls")&&e.includes("setCssStyles")&&e.includes("10")}function Ma(r,e){var t;if(typeof r.setCssStyles=="function"){r.setCssStyles(e);return}for(let[n,o]of Object.entries(e))typeof((t=r.style)==null?void 0:t.setProperty)=="function"?r.style.setProperty(n,o):r.style&&(r.style[n]=o)}function Po(r,e){var t;return r?typeof((t=r.classList)==null?void 0:t.contains)=="function"&&r.classList.contains(e)?!0:Ha(r).includes(e):!1}function Ha(r){let e=r.className;if(typeof e=="string")return e.split(/\s+/).filter(t=>t.length>0);if(e&&typeof e=="object"&&"baseVal"in e){let t=e.baseVal;return typeof t=="string"?t.split(/\s+/).filter(n=>n.length>0):[]}return[]}function Dt(r){return`${Number(r.toFixed(6)).toString()}px`}function rt(r){return typeof r=="number"&&Number.isFinite(r)}function Ba(r){return rt(r)&&r>0}function _a(){}var Io=1,Ro=1.1,At=class{constructor(e){this.canvas=null;this.hasOriginalMinContainerDimension=!1;this.isRequestFramePatched=!1;this.hadOwnRequestFrame=!1;this.isZoomToBboxPatched=!1;this.hadOwnZoomToBbox=!1;this.isGridSpacingPatched=!1;this.hadOwnGridSpacing=!1;this.isSnapDistancePatched=!1;this.hadOwnSnapDistance=!1;this.selectionOverlayPatchPrototype=null;this.releaseSelectionOverlayPatchCallback=null;this.target=e}setEnabled(e){let t=Va(this.target);if(!e||!t){this.restore();return}this.canvas&&this.canvas!==t&&this.restore(),this.canvas=t,this.applyMinimumDimensionOverride(t),this.applyZoomOverrides(t)}dispose(){this.restore()}applyMinimumDimensionOverride(e){e.config&&(this.hasOriginalMinContainerDimension||(this.originalMinContainerDimension=e.config.minContainerDimension,this.hasOriginalMinContainerDimension=!0),e.config.minContainerDimension=Io)}applyZoomOverrides(e){this.patchRequestFrame(e),this.patchZoomToBbox(e),this.patchGridSpacing(e),this.patchSnapDistance(e),this.patchSelectionOverlay(e)}patchRequestFrame(e){if(this.isRequestFramePatched||typeof e.requestFrame!="function")return;let t=e.requestFrame;this.hadOwnRequestFrame=Object.prototype.hasOwnProperty.call(e,"requestFrame"),this.originalRequestFrame=t;let n=o=>{var l,c;let i=(c=(l=e.canvasEl)==null?void 0:l.win)!=null?c:window,s=Reflect.get(i,"requestAnimationFrame"),a=s.bind(i);Reflect.set(i,"requestAnimationFrame",d=>a(u=>{this.runWithZoomClampBypass(e,()=>d(u))}));try{t.call(e,o)}finally{Reflect.set(i,"requestAnimationFrame",s)}};e.requestFrame=n,this.patchedRequestFrame=n,this.isRequestFramePatched=!0}patchZoomToBbox(e){if(this.isZoomToBboxPatched||typeof e.zoomToBbox!="function")return;let t=e.zoomToBbox;this.hadOwnZoomToBbox=Object.prototype.hasOwnProperty.call(e,"zoomToBbox"),this.originalZoomToBbox=t;let n=o=>{this.zoomToBboxWithoutUpperZoomLimit(e,o)||t.call(e,o)};e.zoomToBbox=n,this.patchedZoomToBbox=n,this.isZoomToBboxPatched=!0}patchGridSpacing(e){var o;if(this.isGridSpacingPatched)return;let t=Object.getOwnPropertyDescriptor(e,"gridSpacing");if(t&&!t.configurable)return;let n=()=>yo(No(e));try{Object.defineProperty(e,"gridSpacing",{configurable:!0,enumerable:(o=t==null?void 0:t.enumerable)!=null?o:!1,get:n})}catch(i){return}this.hadOwnGridSpacing=!!t,this.originalGridSpacingDescriptor=t,this.patchedGridSpacingGetter=n,this.isGridSpacingPatched=!0}patchSnapDistance(e){var o;if(this.isSnapDistancePatched)return;let t=Object.getOwnPropertyDescriptor(e,"snapDistance");if(t&&!t.configurable)return;let n=()=>{var i;return Eo((i=e.config)==null?void 0:i.objectSnapDistance,Fa(e))};try{Object.defineProperty(e,"snapDistance",{configurable:!0,enumerable:(o=t==null?void 0:t.enumerable)!=null?o:!1,get:n})}catch(i){return}this.hadOwnSnapDistance=!!t,this.originalSnapDistanceDescriptor=t,this.patchedSnapDistanceGetter=n,this.isSnapDistancePatched=!0}patchSelectionOverlay(e){let t=To(e);!t||t===this.selectionOverlayPatchPrototype||(this.restoreSelectionOverlayPatch(),this.selectionOverlayPatchPrototype=t,this.releaseSelectionOverlayPatchCallback=xo(t))}zoomToBboxWithoutUpperZoomLimit(e,t){let n=e.canvasRect;if(!n||typeof e.markViewportChanged!="function")return!1;let o=n.width,i=n.height,s=t.maxX-t.minX,a=t.maxY-t.minY;if(!_e(o)||!_e(i)||!_e(s)||!_e(a))return!1;let l=Math.min(o/(Ro*s),i/(Ro*a));if(!_e(l))return!1;let c=fo(l);return e.tx=(t.minX+t.maxX)/2,e.ty=(t.minY+t.maxY)/2,e.zoomCenter=null,e.tZoom=Math.log2(c),e.markViewportChanged(),!0}runWithZoomClampBypass(e,t){let n=Math,o=n.clamp;if(typeof o!="function"||!this.shouldBypassZoomClamp(e)){t();return}n.clamp=(i,s,a)=>s===-4&&a===1&&i>1?go(i):o(i,s,a);try{t()}finally{n.clamp=o}}shouldBypassZoomClamp(e){if(e!==this.canvas)return!1;let t=typeof e.tZoom=="number"?e.tZoom:e.zoom;return typeof t=="number"&&Number.isFinite(t)&&t>1}restore(){let e=this.canvas;e&&(this.restoreMinimumDimensionOverride(e),this.restoreZoomOverrides(e),this.canvas=null)}restoreMinimumDimensionOverride(e){this.hasOriginalMinContainerDimension&&e.config&&e.config.minContainerDimension===Io&&(e.config.minContainerDimension=this.originalMinContainerDimension),this.hasOriginalMinContainerDimension=!1,this.originalMinContainerDimension=void 0}restoreZoomOverrides(e){this.restoreRequestFrame(e),this.restoreZoomToBbox(e),this.restoreGridSpacing(e),this.restoreSnapDistance(e),this.restoreSelectionOverlayPatch(),this.restoreNativeZoomClamp(e)}restoreSelectionOverlayPatch(){var e;(e=this.releaseSelectionOverlayPatchCallback)==null||e.call(this),this.releaseSelectionOverlayPatchCallback=null,this.selectionOverlayPatchPrototype=null}restoreNativeZoomClamp(e){var t;typeof e.tZoom!="number"||e.tZoom<=1||(e.tZoom=1,(t=e.markViewportChanged)==null||t.call(e))}restoreRequestFrame(e){this.isRequestFramePatched&&(e.requestFrame===this.patchedRequestFrame&&(this.hadOwnRequestFrame?e.requestFrame=this.originalRequestFrame:delete e.requestFrame),this.isRequestFramePatched=!1,this.hadOwnRequestFrame=!1,this.originalRequestFrame=void 0,this.patchedRequestFrame=void 0)}restoreZoomToBbox(e){this.isZoomToBboxPatched&&(e.zoomToBbox===this.patchedZoomToBbox&&(this.hadOwnZoomToBbox?e.zoomToBbox=this.originalZoomToBbox:delete e.zoomToBbox),this.isZoomToBboxPatched=!1,this.hadOwnZoomToBbox=!1,this.originalZoomToBbox=void 0,this.patchedZoomToBbox=void 0)}restoreGridSpacing(e){if(!this.isGridSpacingPatched)return;let t=Object.getOwnPropertyDescriptor(e,"gridSpacing");(t==null?void 0:t.get)===this.patchedGridSpacingGetter&&(this.hadOwnGridSpacing&&this.originalGridSpacingDescriptor?Object.defineProperty(e,"gridSpacing",this.originalGridSpacingDescriptor):delete e.gridSpacing),this.isGridSpacingPatched=!1,this.hadOwnGridSpacing=!1,this.originalGridSpacingDescriptor=void 0,this.patchedGridSpacingGetter=void 0}restoreSnapDistance(e){if(!this.isSnapDistancePatched)return;let t=Object.getOwnPropertyDescriptor(e,"snapDistance");(t==null?void 0:t.get)===this.patchedSnapDistanceGetter&&(this.hadOwnSnapDistance&&this.originalSnapDistanceDescriptor?Object.defineProperty(e,"snapDistance",this.originalSnapDistanceDescriptor):delete e.snapDistance),this.isSnapDistancePatched=!1,this.hadOwnSnapDistance=!1,this.originalSnapDistanceDescriptor=void 0,this.patchedSnapDistanceGetter=void 0}};function Va(r){var e;return(e=r.view.canvas)!=null?e:null}function No(r){return typeof r.zoom=="number"&&Number.isFinite(r.zoom)?r.zoom:typeof r.tZoom=="number"?r.tZoom:1}function Fa(r){return _e(r.scale)?r.scale:2**No(r)}function _e(r){return typeof r=="number"&&Number.isFinite(r)&&r>0}var Vt=require("obsidian");var za="drawInCanvasScale",Ht="draw-in-canvas-scaled-node-content";var Bt=class{constructor(e){this.hasSyncedContentScales=!1;this.hasTrackedContentScales=!1;this.contentScaleCanvas=null;this.hasContentScaleNodeMap=!1;this.contentScaleNodeCount=0;this.scaledContentByNodeId=new Map;this.getContainerEl=e}syncForCanvas(e){if(!(e!=null&&e.nodes)){this.clear(),this.contentScaleCanvas=e,this.hasContentScaleNodeMap=!1;return}if(e!==this.contentScaleCanvas||!this.hasContentScaleNodeMap||!this.hasSyncedContentScales||e.nodes.size!==this.contentScaleNodeCount){this.syncFull(e);return}this.hasTrackedContentScales&&this.syncTrackedContentScales(e)}syncChangedNodes(e,t){if(t.length!==0){if(!(e!=null&&e.nodes)){this.syncForCanvas(e);return}if(e!==this.contentScaleCanvas||!this.hasContentScaleNodeMap||!this.hasSyncedContentScales||e.nodes.size!==this.contentScaleNodeCount){this.syncFull(e);return}for(let n of t){let o=Ga(n);!o||e.nodes.get(o)!==n||this.syncNodeContentScale(o,n)}this.hasTrackedContentScales=this.scaledContentByNodeId.size>0}}clear(){for(let e of Array.from(this.getContainerEl().querySelectorAll(`.${Ht}`)))Ee(e);this.scaledContentByNodeId.clear(),this.hasSyncedContentScales=!0,this.hasTrackedContentScales=!1,this.contentScaleCanvas=null,this.hasContentScaleNodeMap=!1,this.contentScaleNodeCount=0}syncFull(e){var n,o,i,s,a;let t=new Set;this.scaledContentByNodeId.clear();for(let[l,c]of(o=(n=e.nodes)==null?void 0:n.entries())!=null?o:[]){let d=(i=c.getData)==null?void 0:i.call(c),u=_r(d),h=u?Or(d):1,p=u&&!_t(h),S=Vr(c);if(!S){p&&this.scaledContentByNodeId.set(l,{contentEl:null});continue}if(!p){Ee(S);continue}Fr(S,h),t.add(S),this.scaledContentByNodeId.set(l,{contentEl:S})}this.clearStaleContentScaleEls(t),this.hasSyncedContentScales=!0,this.hasTrackedContentScales=this.scaledContentByNodeId.size>0,this.contentScaleCanvas=e,this.hasContentScaleNodeMap=!0,this.contentScaleNodeCount=(a=(s=e.nodes)==null?void 0:s.size)!=null?a:0}syncTrackedContentScales(e){var t;for(let[n,o]of Array.from(this.scaledContentByNodeId.entries())){let i=(t=e.nodes)==null?void 0:t.get(n);if(!i){Mt(o,null),this.scaledContentByNodeId.delete(n);continue}this.syncNodeContentScale(n,i)}this.hasTrackedContentScales=this.scaledContentByNodeId.size>0}syncNodeContentScale(e,t){var l;let n=this.scaledContentByNodeId.get(e),o=(l=t.getData)==null?void 0:l.call(t),i=Vr(t),s=_r(o),a=s?Or(o):1;if(!s){Mt(n,i),i&&Ee(i),this.scaledContentByNodeId.delete(e);return}if(_t(a)){Mt(n,i),i&&Ee(i),n?this.scaledContentByNodeId.set(e,{contentEl:i}):this.scaledContentByNodeId.delete(e);return}Mt(n,i),i&&Fr(i,a),this.scaledContentByNodeId.set(e,{contentEl:i})}clearStaleContentScaleEls(e){for(let t of Array.from(this.getContainerEl().querySelectorAll(`.${Ht}`)))e.has(t)||Ee(t)}};function Lo(r,e){return zr(r)?Wa(Do(r)*e):null}function zr(r){var e;return _r((e=r.getData)==null?void 0:e.call(r))}function Do(r){var e;return Or((e=r.getData)==null?void 0:e.call(r))}function Ao(r,e){if(e===null||_t(e)){delete r.drawInCanvasScale;return}r.drawInCanvasScale=e}function Kr(r){let e=Vr(r);if(!e)return;let t=Do(r);if(_t(t)){Ee(e);return}Fr(e,t)}function _r(r){return(r==null?void 0:r.type)==="text"?!0:(r==null?void 0:r.type)==="file"&&Ka(r.file)}function Ka(r){return typeof r=="string"&&r.toLowerCase().endsWith(".md")}function Or(r){let e=r==null?void 0:r[za];return Ya(e)?Math.min(100,Math.max(.01,e)):1}function Vr(r){var e,t;return(t=(e=r.nodeEl)==null?void 0:e.querySelector(".canvas-node-content"))!=null?t:null}function Fr(r,e){r.classList.add(Ht),r.setCssStyles({transform:`scale(${e})`,transformOrigin:"top left",width:`${100/e}%`,height:`${100/e}%`,flex:"0 0 auto"})}function Ee(r){r.classList.remove(Ht),r.setCssStyles({transform:"",transformOrigin:"",width:"",height:"",flex:""})}function Mt(r,e){r!=null&&r.contentEl&&r.contentEl!==e&&Ee(r.contentEl)}function Ga(r){var t;if(typeof r.id=="string"&&r.id.length>0)return r.id;let e=(t=r.getData)==null?void 0:t.call(r).id;return typeof e=="string"&&e.length>0?e:null}function _t(r){return Math.abs(r-1)<.001}function Wa(r){let e=Math.min(100,Math.max(.01,r));return Math.round(e*1e3)/1e3}function Ua(r){return typeof r=="number"&&Number.isFinite(r)}function Ya(r){return Ua(r)&&r>0}function Ho(r){var t;let e=new Set;for(let n of(t=r.selection)!=null?t:[]){let o=qa(r,n);if(!(!o||!Za(o)))for(let i of Xa(o))e.add(i)}return Array.from(e)}function Xa(r){let e=[],t=Object.getPrototypeOf(r);for(;t&&t!==Object.prototype;){let n=t;Object.prototype.hasOwnProperty.call(n,"onResizePointerdown")&&typeof n.onResizePointerdown=="function"&&e.push(n),t=Object.getPrototypeOf(t)}return e}function qa(r,e){var t,n;if(Gr(e)){let o=(t=r.nodes)==null?void 0:t.get(e.id);return Gr(o)?o:null}if(typeof e=="string"){let o=(n=r.nodes)==null?void 0:n.get(e);return Gr(o)?o:null}return null}function Gr(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.id=="string"&&e.id.length>0}function Za(r){return Mo(r.width)&&Mo(r.height)&&Wr(r.x)&&Wr(r.y)&&(typeof r.moveAndResize=="function"||typeof r.getData=="function"&&typeof r.setData=="function")}function Wr(r){return typeof r=="number"&&Number.isFinite(r)}function Mo(r){return Wr(r)&&r>0}function nt(r,e,t){let n=e instanceof Set?e:new Set(e);switch(t){case"bring-forward":return $a(r,n);case"bring-to-front":return Ja(r,n);case"send-backward":return ja(r,n);case"send-to-back":return Qa(r,n);default:return el(t)}}function oe(r,e,t){let n=nt(r,e,t);return!ot(r,n)}function Bo(r,e){let t=e instanceof Set?e:new Set(e);return{"bring-forward":oe(r,t,"bring-forward"),"bring-to-front":oe(r,t,"bring-to-front"),"send-backward":oe(r,t,"send-backward"),"send-to-back":oe(r,t,"send-to-back")}}function ot(r,e){return r.length!==e.length?!1:r.every((t,n)=>t===e[n])}function Ot(r,e){let t=new Map;for(let i of r)typeof i.id=="string"&&t.set(i.id,i);let n=[],o=new Set;for(let i of e){let s=t.get(i);!s||o.has(i)||(n.push(s),o.add(i))}for(let i of r)(typeof i.id!="string"||!o.has(i.id))&&n.push(i);return n}function $a(r,e){let t=[...r];for(let n=t.length-2;n>=0;n--){let o=t[n],i=t[n+1];o&&i&&e.has(o)&&!e.has(i)&&(t[n]=i,t[n+1]=o)}return t}function ja(r,e){let t=[...r];for(let n=1;n<t.length;n++){let o=t[n],i=t[n-1];o&&i&&e.has(o)&&!e.has(i)&&(t[n-1]=o,t[n]=i)}return t}function Ja(r,e){return _o(r,e,"selected-last")}function Qa(r,e){return _o(r,e,"selected-first")}function _o(r,e,t){let n=[],o=[];for(let i of r)e.has(i)?n.push(i):o.push(i);return t==="selected-first"?[...n,...o]:[...o,...n]}function el(r){throw new Error(`Unexpected layer action: ${String(r)}`)}var it=new WeakMap;function Vo(r){var t,n;let e=new Set;for(let o of(n=(t=r.nodes)==null?void 0:t.values())!=null?n:[]){let i=rl(o);!i||e.has(i)||(it.has(i)||zo(i.renderZIndex))&&e.add(i)}return Array.from(e)}function Fo(r){let e=it.get(r);if(e)return e.refCount++,()=>Oo(r);let t=r.renderZIndex,n=Object.prototype.hasOwnProperty.call(r,"renderZIndex");if(!zo(t))return ol;let o={original:t,patched:tl(t),hadOwnRenderZIndex:n,refCount:1};return r.renderZIndex=o.patched,it.set(r,o),()=>Oo(r)}function Ur(r){var e,t,n;for(let o of(t=(e=r.nodes)==null?void 0:e.values())!=null?t:[])(n=o.renderZIndex)==null||n.call(o)}function Oo(r){let e=it.get(r);e&&(e.refCount--,!(e.refCount>0)&&(r.renderZIndex===e.patched&&(e.hadOwnRenderZIndex?r.renderZIndex=e.original:delete r.renderZIndex),it.delete(r)))}function tl(r){return function(){if(!this.nodeEl){r.call(this);return}let t=nl(this.zIndex)?this.zIndex:0;this.renderedZIndex!==t&&(this.nodeEl.style.zIndex=t.toString(),this.renderedZIndex=t)}}function rl(r){let e=Object.getPrototypeOf(r);for(;e&&e!==Object.prototype;){if(Object.prototype.hasOwnProperty.call(e,"renderZIndex"))return e;e=Object.getPrototypeOf(e)}return Object.prototype.hasOwnProperty.call(r,"renderZIndex")?r:null}function zo(r){if(typeof r!="function")return!1;let e=Function.prototype.toString.call(r);return e.includes("selection")&&e.includes("zIndexCounter")&&e.includes("renderedZIndex")}function nl(r){return typeof r=="number"&&Number.isFinite(r)}function ol(){}var Ko=1.25,il=1,qr="draw-in-canvas-scale-button",sl="draw-in-canvas-scale-grow-button",al="draw-in-canvas-scale-shrink-button",qo="draw-in-canvas-native-layer-menu",ll="draw-in-canvas-layer-menu",Zo="draw-in-canvas-layer-menu-button",Xr="draw-in-canvas-layer-submenu-button",cl=`.${qr}, .${qo}`,dl=["send-to-back","send-backward","bring-forward","bring-to-front"],ul={"send-to-back":{label:"Send selected canvas item to back",icon:"arrow-down-to-line"},"send-backward":{label:"Send selected canvas item backward",icon:"arrow-down"},"bring-forward":{label:"Bring selected canvas item forward",icon:"arrow-up"},"bring-to-front":{label:"Bring selected canvas item to front",icon:"arrow-up-to-line"}},hl=1e-4,zt=new WeakMap,Kt=class{constructor(e){this.enabled=!1;this.buttonEls=[];this.layerMenuEl=null;this.buttonDisposers=[];this.releaseResizePatches=new Map;this.releaseZIndexPatches=new Map;this.deferredSyncFrameId=null;this.handleButtonPointerDown=e=>{e.preventDefault(),e.stopPropagation()};this.target=e,this.contentScaleSync=new Bt(()=>this.target.containerEl)}setEnabled(e){this.enabled=e;let t=Oe(this.target);if(!e){this.removeControls(),this.releaseAspectRatioResizePatch(),this.releaseZIndexPatch(t),this.cancelDeferredSync(),this.contentScaleSync.syncForCanvas(t);return}this.sync(),this.scheduleDeferredSync()}syncForCanvasDomChange(){if(this.enabled){this.sync();return}this.contentScaleSync.syncForCanvas(Oe(this.target))}sync(e={}){let t=Oe(this.target);if(!t){this.removeControls(),this.contentScaleSync.clear(),this.releaseAspectRatioResizePatch(),this.releaseZIndexPatch();return}if(e.skipContentScaleSync||this.contentScaleSync.syncForCanvas(t),!this.enabled){this.removeControls(),this.releaseAspectRatioResizePatch(),this.releaseZIndexPatch(t);return}this.syncZIndexPatch(t),this.syncAspectRatioResizePatch(t);let n=this.findNativeMenuEl();if(!n||Zr(t).length===0){this.removeControls();return}if(this.removeStaleControls(n),this.areControlsMountedIn(n)){this.syncLayerMenuButtonStates(t);return}this.removeControls();let o=this.createScaleButton("grow"),i=this.createScaleButton("shrink"),s=this.createLayerMenuEl(t);this.buttonEls.push(o,i),this.layerMenuEl=s,this.insertControls(n,o,i,s)}dispose(){let e=Oe(this.target);this.enabled=!1,this.cancelDeferredSync(),this.removeControls(),this.releaseAspectRatioResizePatch(),this.releaseZIndexPatch(e),this.contentScaleSync.clear()}getOwnedElements(){var e;return[...this.buttonEls.filter(t=>t.isConnected),...(e=this.layerMenuEl)!=null&&e.isConnected?[this.layerMenuEl]:[]]}createScaleButton(e){let t=activeDocument.createElement("button");return t.type="button",t.classList.add("clickable-icon",qr),t.classList.add(e==="grow"?sl:al),t.setAttribute("aria-label",e==="grow"?"Make selected canvas item larger":"Make selected canvas item smaller"),t.setAttribute("data-tooltip-position","top"),(0,Vt.setIcon)(t,e==="grow"?"plus":"minus"),this.buttonDisposers.push(this.addListener(t,"pointerdown",this.handleButtonPointerDown),this.addListener(t,"click",n=>this.handleScaleButtonClick(n,e))),t}createLayerMenuEl(e){let t=activeDocument.createElement("div");t.classList.add(ll,qo);let n=activeDocument.createElement("button");n.type="button",n.classList.add("clickable-icon",Zo),n.setAttribute("aria-label","Layer selected canvas item"),n.setAttribute("aria-haspopup","menu"),n.setAttribute("aria-expanded","false"),n.setAttribute("data-tooltip-position","top"),(0,Vt.setIcon)(n,"layers");let o=activeDocument.createElement("div");o.classList.add("canvas-menu","draw-in-canvas-layer-submenu"),o.setAttribute("role","menu");let i=Wo(e);return o.append(...dl.map(s=>this.createLayerActionButton(i,s))),t.append(n,o),this.buttonDisposers.push(this.addListener(n,"pointerdown",this.handleButtonPointerDown),this.addListener(n,"click",s=>this.handleLayerMenuButtonClick(s,t,n))),t}createLayerActionButton(e,t){let n=ul[t],o=activeDocument.createElement("button");return o.type="button",o.classList.add("clickable-icon",Xr),o.dataset.layerAction=t,o.disabled=!e[t],o.setAttribute("aria-label",n.label),o.setAttribute("data-tooltip-position","top"),o.setAttribute("role","menuitem"),(0,Vt.setIcon)(o,n.icon),this.buttonDisposers.push(this.addListener(o,"pointerdown",this.handleButtonPointerDown),this.addListener(o,"click",i=>this.handleLayerActionButtonClick(i,t))),o}insertControls(e,...t){let n=Hl(e);for(let o of t)e.insertBefore(o,n)}areControlsMountedIn(e){var t;return this.buttonEls.length===2&&this.buttonEls.every(n=>n.isConnected&&n.parentElement===e)&&!!((t=this.layerMenuEl)!=null&&t.isConnected&&this.layerMenuEl.parentElement===e)}removeStaleControls(e){let t=new Set([...this.buttonEls]);this.layerMenuEl&&t.add(this.layerMenuEl);let n=Array.from(this.target.containerEl.querySelectorAll(cl));for(let o of n)(!t.has(o)||o.parentElement!==e)&&o.remove()}removeControls(){var e;for(let t of this.buttonDisposers.splice(0))t();for(let t of this.buttonEls.splice(0))t.remove();(e=this.layerMenuEl)==null||e.remove(),this.layerMenuEl=null}findNativeMenuEl(){return this.target.containerEl.querySelector(".canvas-menu:not(.draw-in-canvas-stroke-scale-menu):not(.draw-in-canvas-layer-submenu)")}syncAspectRatioResizePatch(e){let t=new Set(Ho(e));for(let[n,o]of this.releaseResizePatches)t.has(n)||(o(),this.releaseResizePatches.delete(n));for(let n of t)this.releaseResizePatches.has(n)||this.releaseResizePatches.set(n,pl(n))}releaseAspectRatioResizePatch(){for(let e of this.releaseResizePatches.values())e();this.releaseResizePatches.clear()}syncZIndexPatch(e){let t=new Set(Vo(e));for(let[n,o]of this.releaseZIndexPatches)t.has(n)||(o(),this.releaseZIndexPatches.delete(n));for(let n of t)this.releaseZIndexPatches.has(n)||this.releaseZIndexPatches.set(n,Fo(n));Ur(e)}releaseZIndexPatch(e){for(let t of this.releaseZIndexPatches.values())t();this.releaseZIndexPatches.clear(),e&&Ur(e)}scheduleDeferredSync(){this.deferredSyncFrameId===null&&(this.deferredSyncFrameId=window.requestAnimationFrame(()=>{this.deferredSyncFrameId=null,this.enabled&&this.sync()}))}cancelDeferredSync(){this.deferredSyncFrameId!==null&&(window.cancelAnimationFrame(this.deferredSyncFrameId),this.deferredSyncFrameId=null)}handleScaleButtonClick(e,t){var s,a,l,c;e.preventDefault(),e.stopPropagation();let n=Oe(this.target);if(!n){this.removeControls();return}let o=t==="grow"?Ko:1/Ko,i=wl(n,o);if(!i.didScale){this.sync();return}this.contentScaleSync.syncChangedNodes(n,i.contentScaleNodes),(s=n.requestSave)==null||s.call(n,!0),(l=(a=n.menu)==null?void 0:a.render)==null||l.call(a,!0),(c=n.requestFrame)==null||c.call(n),this.sync({skipContentScaleSync:!0})}handleLayerMenuButtonClick(e,t,n){e.preventDefault(),e.stopPropagation();let o=!t.classList.contains("is-open");t.classList.toggle("is-open",o),n.setAttribute("aria-expanded",o.toString())}handleLayerActionButtonClick(e,t){var o,i,s,a;e.preventDefault(),e.stopPropagation();let n=Oe(this.target);if(!n){this.removeControls();return}if(!El(n,t)){this.sync();return}(o=n.requestSave)==null||o.call(n,!0),(s=(i=n.menu)==null?void 0:i.render)==null||s.call(i,!0),(a=n.requestFrame)==null||a.call(n),this.sync()}syncLayerMenuButtonStates(e){var n,o;let t=Wo(e);for(let i of Array.from((o=(n=this.layerMenuEl)==null?void 0:n.querySelectorAll(`.${Xr}`))!=null?o:[])){let s=Bl(i.dataset.layerAction);s&&(i.disabled=!t[s])}}addListener(e,t,n,o){let i=n;return e.addEventListener(t,i,o),()=>e.removeEventListener(t,i,o)}};function pl(r){let e=r.onResizePointerdown,t=Object.prototype.hasOwnProperty.call(r,"onResizePointerdown");if(typeof e!="function")return yl;let n=zt.get(r);if(n)return n.refCount++,()=>Go(r);let o={original:e,patched:Sl(e),hadOwnResizePointerdown:t,refCount:1};return r.onResizePointerdown=o.patched,zt.set(r,o),()=>Go(r)}function Go(r){let e=zt.get(r);e&&(e.refCount--,!(e.refCount>0)&&(r.onResizePointerdown===e.patched&&(e.hadOwnResizePointerdown?r.onResizePointerdown=e.original:delete r.onResizePointerdown),zt.delete(r)))}function Sl(r){return function(t,n){if(!vl(this,t)){r.call(this,t,n);return}let o=this.aspectRatio,i=ml(this);if(!ke(i)){r.call(this,t,n);return}this.aspectRatio=i;let s=gl(this,o,i);try{r.call(this,t,n)}catch(a){throw s(),a}if(t.defaultPrevented){fl(t,s);return}s()}}function vl(r,e){return e.shiftKey&&e.isPrimary&&e.button===0&&!ke(r.aspectRatio)&&ke(r.width)&&ke(r.height)}function ml(r){return r.width/r.height}function gl(r,e,t){let n=!1;return()=>{var o;n||(n=!0,Math.abs(((o=r.aspectRatio)!=null?o:0)-t)<hl&&(r.aspectRatio=e))}}function fl(r,e){let t=Cl(r),n=[],o=()=>{for(let i of n.splice(0))i();t.setTimeout(e,0)};n=[Yr(t,"pointerup",o,!0),Yr(t,"pointercancel",o,!0),Yr(t,"blur",o,!0)]}function Yr(r,e,t,n){let o=t;return r.addEventListener(e,o,n),()=>r.removeEventListener(e,o,n)}function Cl(r){var e,t;return(t=(e=r.win)!=null?e:r.view)!=null?t:window}function yl(){}function Wo(r){return Bo($o(r),jo(r))}function El(r,e){let t=jo(r),n=$o(r),o=nt(n,t,e);return t.length===0||!oe(n,t,e)?!1:(kl(r,o),!0)}function kl(r,e){var i,s,a,l;let t=Jo(r),n=Ot(t,e),o=t.map((c,d)=>J(c.zIndex)?c.zIndex:d+1).sort((c,d)=>c-d);for(let c=0;c<n.length;c++){let d=n[c],u=(i=o[c])!=null?i:c+1;d&&(d.zIndex=u,(s=d.renderZIndex)==null||s.call(d),(a=d.render)==null||a.call(d))}r.zIndexCounter=Math.max((l=r.zIndexCounter)!=null?l:0,...o)}function $o(r){return Jo(r).map(e=>e.id).filter(Qo)}function jo(r){return Zr(r).map(e=>e.id).filter(Qo)}function Jo(r){var e,t;return Array.from((t=(e=r.nodes)==null?void 0:e.values())!=null?t:[]).filter(Ft).sort(bl)}function bl(r,e){return Uo(r)-Uo(e)}function Uo(r){return J(r.zIndex)?r.zIndex:0}function wl(r,e){let t=Pl(r),n=Rl(t);if(!n)return{didScale:!1,contentScaleNodes:[]};let o=Al(r),i=Dl(n),s=[],a=!1;for(let l of t){let c={x:l.x+l.width/2,y:l.y+l.height/2},d=Yo(l.width,e,o),u=Yo(l.height,e,o),h={x:i.x+(c.x-i.x)*e,y:i.y+(c.y-i.y)*e},p={x:Xo(h.x-d/2),y:Xo(h.y-u/2),width:d,height:u},S=Lo(l,e);Ml(l,p)&&S===null||Il(l,p,S)&&(a=!0,zr(l)&&s.push(l))}return{didScale:a,contentScaleNodes:s}}function Pl(r){return Zr(r).filter(xl)}function Zr(r){let e=r.selection;if(!e)return[];let t=[];for(let n of e){let o=Tl(r,n);o&&t.push(o)}return t}function Tl(r,e){var t,n;if(Ft(e)){let o=(t=r.nodes)==null?void 0:t.get(e.id);return Ft(o)?o:null}if(typeof e=="string"){let o=(n=r.nodes)==null?void 0:n.get(e);return Ft(o)?o:null}return null}function Ft(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.id=="string"&&e.id.length>0}function xl(r){if(!r||typeof r!="object")return!1;let e=r;return ke(e.width)&&ke(e.height)&&J(e.x)&&J(e.y)&&(typeof e.moveAndResize=="function"||typeof e.getData=="function"&&typeof e.setData=="function")}function Il(r,e,t){var n,o;if(typeof r.getData=="function"&&typeof r.setData=="function"){let i={...r.getData(),...e};return Ao(i,t),r.setData(i),(n=r.render)==null||n.call(r),Kr(r),!0}return typeof r.moveAndResize=="function"?(r.moveAndResize(e),(o=r.render)==null||o.call(r),Kr(r),!0):!1}function Rl(r){let e=null;for(let t of r){let n=Nl(t);e=e?Ll(e,n):n}return e}function Nl(r){var t;let e=(t=r.getBBox)==null?void 0:t.call(r);return e&&_l(e)?e:{minX:r.x,minY:r.y,maxX:r.x+r.width,maxY:r.y+r.height}}function Ll(r,e){return{minX:Math.min(r.minX,e.minX),minY:Math.min(r.minY,e.minY),maxX:Math.max(r.maxX,e.maxX),maxY:Math.max(r.maxY,e.maxY)}}function Dl(r){return{x:(r.minX+r.maxX)/2,y:(r.minY+r.maxY)/2}}function Al(r){var t;let e=(t=r.config)==null?void 0:t.minContainerDimension;return ke(e)?e:il}function Yo(r,e,t){let n=r*e,o=e<1?Math.floor(n):Math.ceil(n);return Math.max(t,o)}function Ml(r,e){return r.x===e.x&&r.y===e.y&&r.width===e.width&&r.height===e.height}function Hl(r){return r.querySelector(`button.clickable-icon:not(.${qr}):not(.${Zo}):not(.${Xr})`)}function Oe(r){var e;return(e=r.view.canvas)!=null?e:null}function Bl(r){return r==="bring-forward"||r==="bring-to-front"||r==="send-backward"||r==="send-to-back"?r:null}function Qo(r){return r!==void 0}function _l(r){return J(r.minX)&&J(r.minY)&&J(r.maxX)&&J(r.maxY)&&r.maxX>=r.minX&&r.maxY>=r.minY}function J(r){return typeof r=="number"&&Number.isFinite(r)}function ke(r){return J(r)&&r>0}function Xo(r){return Math.round(r)}var Q={syncTinyCanvasControls:!1,syncNativeElementControls:!1},K={syncTinyCanvasControls:!0,syncNativeElementControls:!0},ti="draw-in-canvas-",en=["canvas-menu","canvas-node","canvas-node-content","canvas-selection"],Ol=["canvas-menu","canvas-node","canvas-selection"],Ut=["canvas-edges","canvas-display-path","canvas-interaction-path","canvas-path-end","canvas-snaps"],ri=["canvas"],Vl=["canvas","canvas-wrapper","canvas-controls","view-content"],Fl=["canvas-controls","canvas-node-content"];function ni(r){if(r.length===0)return{...K};let e={...Q};for(let t of r)if(e=st(e,zl(t)),$r(e,K))break;return e}function st(r,e){return{syncTinyCanvasControls:r.syncTinyCanvasControls||e.syncTinyCanvasControls,syncNativeElementControls:r.syncNativeElementControls||e.syncNativeElementControls}}function zl(r){let e=r;return e.type==="attributes"?Kl(e):e.type==="childList"?Gl(e):{...K}}function Kl(r){let e=Ve(r.target);return e?Yl(r,e)?{...Q}:_(e,Ut)||Gt(e,["canvas-edges","canvas-snaps"])?{syncTinyCanvasControls:!0,syncNativeElementControls:!1}:_(e,ri)?{syncTinyCanvasControls:!0,syncNativeElementControls:!1}:_(e,en)||Gt(e,["canvas-menu"])?{syncTinyCanvasControls:!1,syncNativeElementControls:!0}:Gt(e,Fl)?{...Q}:{...K}:{...K}}function Gl(r){let e=Ve(r.target);if(!e)return{...K};let t={...Q},n=!1,o=!1,i=!1;for(let a of[...Wt(r.addedNodes),...Wt(r.removedNodes)]){let l=Ve(a);if(!l)continue;if(Jr(l)){o=!0;continue}i=!0;let c=Wl(l);t=st(t,c),$r(c,Q)&&(n=!0)}if(o&&!i&&!n)return{...Q};let s=Ul(e);return t=st(t,s),$r(t,Q)?Jr(e)||_(e,["canvas-node-content"])?{...Q}:n?{...K}:_(e,Vl)?{...Q}:{...K}:t}function Wl(r){return{syncTinyCanvasControls:jr(r,Ut),syncNativeElementControls:jr(r,en)}}function Ul(r){return{syncTinyCanvasControls:_(r,Ut)||Gt(r,["canvas-edges","canvas-snaps"]),syncNativeElementControls:_(r,Ol)}}function $r(r,e){return r.syncTinyCanvasControls===e.syncTinyCanvasControls&&r.syncNativeElementControls===e.syncNativeElementControls}function jr(r,e){if(_(r,e))return!0;let t=e.map(n=>`.${n}`).join(", ");if(typeof r.querySelector=="function")try{if(r.querySelector(t))return!0}catch(n){}for(let n of jl(r)){let o=Ve(n);if(o&&jr(o,e))return!0}return!1}function Gt(r,e){let t=r;for(;t;){if(_(t,e))return!0;t=Ve(t.parentElement)}return!1}function Yl(r,e){return Jr(e)?_(e,en)?r.attributeName==="class"?typeof r.oldValue=="string"&&$l(r.oldValue,ii(e)):r.attributeName==="style":!0:!1}function Jr(r){return _(r,Ut)||_(r,ri)?!1:Xl(r,ti)}function Xl(r,e){let t=r;for(;t;){if(Zl(t,e))return!0;t=Ve(t.parentElement)}return!1}function _(r,e){return e.some(t=>ql(r,t))}function ql(r,e){var t;return typeof((t=r.classList)==null?void 0:t.contains)=="function"&&r.classList.contains(e)?!0:oi(r).includes(e)}function Zl(r,e){return oi(r).some(t=>t.startsWith(e))}function $l(r,e){let t=ei(Qr(r)),n=ei(Qr(e));return t.length!==n.length?!1:t.every((o,i)=>o===n[i])}function ei(r){return r.filter(e=>!e.startsWith(ti)).sort()}function oi(r){return Qr(ii(r))}function ii(r){let e=r.className;if(typeof e=="string")return e;if(e&&typeof e=="object"&&"baseVal"in e){let t=e.baseVal;return typeof t=="string"?t:""}return""}function Qr(r){return r.split(/\s+/).filter(e=>e.length>0)}function jl(r){let e=Wt(r.childNodes);return e.length>0?e:Wt(r.children)}function Wt(r){if(!r)return[];let e=r;return typeof e[Symbol.iterator]=="function"?Array.from(e):typeof r.length=="number"?Array.from(r):[]}function Ve(r){if(!r||typeof r!="object")return null;let e=r;return e.nodeType===1||"classList"in e||"className"in e||"querySelector"in e?e:null}function at(r){return{width:r.width,hardness:r.hardness,opacity:r.opacity,handwriting:{...ne(r)}}}function si(r,e){let t=q(e);return be(at(r),t)?!1:(r.width=t.width,r.hardness=t.hardness,r.opacity=t.opacity,r.handwriting=t.handwriting,!0)}function q(r){return{...r,handwriting:{...r.handwriting}}}function be(r,e){return r.width===e.width&&r.hardness===e.hardness&&r.opacity===e.opacity&&r.handwriting.enabled===e.handwriting.enabled&&r.handwriting.thinning===e.handwriting.thinning&&r.handwriting.streamline===e.handwriting.streamline&&r.handwriting.smoothing===e.handwriting.smoothing&&r.handwriting.taperStart===e.handwriting.taperStart&&r.handwriting.taperEnd===e.handwriting.taperEnd}function tn(r){return r.isDrawingEnabled||r.selectedStrokeCount>0}function ai(r){return!r.isDrawingEnabled&&r.selectedStrokeCount>0?"selection":"brush"}function li(r){return r==="selection"?"Selected stroke size, color, stroke settings, and opacity":"Brush size, color, stroke settings, and opacity"}function ci(r,e){return r==="selection"?e?"Close selected stroke color":"Open selected stroke color":e?"Close stroke color":"Open stroke color"}function di(r,e){return r==="selection"?e?"Close selected stroke and handwriting settings":"Open selected stroke and handwriting settings":e?"Close stroke and handwriting settings":"Open stroke and handwriting settings"}function rn(r){return r==="selection"?"Selected stroke size":"Brush size"}function nn(r){return r==="selection"?"Selected stroke opacity":"Brush opacity"}var{PI:Jl}=Math,pi=.275,Fe=Jl+1e-4,on=13,Si=29,vi=13,ui=3;function mi(r){return!Number.isFinite(r)||r<=0?ui:Math.min(ui,r)}var gi=.15,fi=.85,hi=.01;function Ci(r){return!Number.isFinite(r)||r<=0?hi:Math.min(hi,r/100)}var yi=.25,sn=.5,an=[1,1];function ln(r,e,t,n=o=>o){return r*n(.5-e*(.5-t))}var{min:cn}=Math;function dn(r,e,t){let n=cn(1,e/t),o=cn(1,1-n);return cn(1,r+(o-r)*(n*pi))}function Ei(r){return[-r[0],-r[1]]}function O(r,e){return[r[0]+e[0],r[1]+e[1]]}function un(r,e,t){return r[0]=e[0]+t[0],r[1]=e[1]+t[1],r}function ee(r,e){return[r[0]-e[0],r[1]-e[1]]}function lt(r,e,t){return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r}function te(r,e){return[r[0]*e,r[1]*e]}function Yt(r,e,t){return r[0]=e[0]*t,r[1]=e[1]*t,r}function Ql(r,e){return[r[0]/e,r[1]/e]}function hn(r){return[r[1],-r[0]]}function Xt(r,e){let t=e[0];return r[0]=e[1],r[1]=-t,r}function pn(r,e){return r[0]*e[0]+r[1]*e[1]}function ki(r,e){return r[0]===e[0]&&r[1]===e[1]}function ec(r){return Math.hypot(r[0],r[1])}function Sn(r,e){let t=r[0]-e[0],n=r[1]-e[1];return t*t+n*n}function qt(r){return Ql(r,ec(r))}function bi(r,e){return Math.hypot(r[1]-e[1],r[0]-e[0])}function Zt(r,e,t){let n=Math.sin(t),o=Math.cos(t),i=r[0]-e[0],s=r[1]-e[1],a=i*o-s*n,l=i*n+s*o;return[a+e[0],l+e[1]]}function vn(r,e,t,n){let o=Math.sin(n),i=Math.cos(n),s=e[0]-t[0],a=e[1]-t[1],l=s*i-a*o,c=s*o+a*i;return r[0]=l+t[0],r[1]=c+t[1],r}function mn(r,e,t){return O(r,te(ee(e,r),t))}function wi(r,e,t,n){let o=t[0]-e[0],i=t[1]-e[1];return r[0]=e[0]+o*n,r[1]=e[1]+i*n,r}function gn(r,e,t){return O(r,te(e,t))}var b=[0,0],ie=[0,0],se=[0,0];function tc(r,e){let t=O(r,[1,1]),n=gn(r,qt(hn(ee(r,t))),-e),o=[],i=1/on;for(let s=i;s<=1;s+=i)o.push(Zt(n,r,Fe*2*s));return o}function rc(r,e,t){let n=[],o=1/t;for(let i=o;i<=1;i+=o)n.push(Zt(e,r,Fe*i));return n}function nc(r,e,t){let n=ee(e,t),o=te(n,.5),i=te(n,.51);return[ee(r,o),ee(r,i),O(r,i),O(r,o)]}function oc(r,e,t,n){let o=[],i=gn(r,e,t),s=1/n;for(let a=s;a<1;a+=s)o.push(Zt(i,r,Fe*3*a));return o}function ic(r,e,t){return[O(r,te(e,t)),O(r,te(e,t*.99)),ee(r,te(e,t*.99)),ee(r,te(e,t))]}function Pi(r,e,t){return r===!1||r===void 0?0:r===!0?Math.max(e,t):r}function sc(r,e,t){return r.slice(0,10).reduce((n,o)=>{let i=o.pressure;return e&&(i=dn(n,o.distance,t)),(n+i)/2},r[0].pressure)}function Ti(r,e={}){let{size:t=16,smoothing:n=.5,thinning:o=.5,simulatePressure:i=!0,easing:s=C=>C,start:a={},end:l={},last:c=!1}=e,{cap:d=!0,easing:u=C=>C*(2-C)}=a,{cap:h=!0,easing:p=C=>--C*C*C+1}=l;if(r.length===0||t<=0)return[];let S=r[r.length-1].runningLength,g=Pi(a.taper,t,S),D=Pi(l.taper,t,S),me=Math.pow(t*n,2),Qs=mi(t),ea=Ci(t),je=[],Me=[],Qn=sc(r,i,t),z=ln(t,o,r[r.length-1].pressure,s),gr,fr=r[0].vector,Je=r[0].point,ft=Je,ge=Je,fe=ft,Cr=!1;for(let C=0;C<r.length;C++){let{pressure:br}=r[C],{point:re,vector:Qe,distance:ta,runningLength:et}=r[C],yt=C===r.length-1;if(!yt&&S-et<Qs)continue;o?(i&&(br=dn(Qn,ta,t)),z=ln(t,o,br,s)):z=t/2,gr===void 0&&(gr=z);let ra=et<g?u(et/g):1,na=S-et<D?p((S-et)/D):1;z=Math.max(ea,z*Math.min(ra,na));let eo=(yt?r[C]:r[C+1]).vector,wr=yt?1:pn(Qe,eo),oa=pn(Qe,fr)<0&&!Cr,to=wr!==null&&wr<0;if(oa||to){Xt(b,fr),Yt(b,b,z);let ia=1/vi;for(let Et=0;Et<=1;Et+=ia)lt(ie,re,b),vn(ie,ie,re,Fe*Et),ge=[ie[0],ie[1]],je.push(ge),un(se,re,b),vn(se,se,re,Fe*-Et),fe=[se[0],se[1]],Me.push(fe);Je=ge,ft=fe,to&&(Cr=!0);continue}if(Cr=!1,yt){Xt(b,Qe),Yt(b,b,z),je.push(ee(re,b)),Me.push(O(re,b));continue}wi(b,eo,Qe,wr),Xt(b,b),Yt(b,b,z),lt(ie,re,b),ge=[ie[0],ie[1]],(C<=1||Sn(Je,ge)>me)&&(je.push(ge),Je=ge),un(se,re,b),fe=[se[0],se[1]],(C<=1||Sn(ft,fe)>me)&&(Me.push(fe),ft=fe),Qn=br,fr=Qe}let yr=[r[0].point[0],r[0].point[1]],Er=r.length>1?[r[r.length-1].point[0],r[r.length-1].point[1]]:O(r[0].point,[1,1]),kr=[],Ct=[];if(r.length===1){if(!(g||D)||c)return tc(yr,gr||z)}else{g||D&&r.length===1||(d?kr.push(...rc(yr,Me[0],on)):kr.push(...nc(yr,je[0],Me[0])));let C=hn(Ei(r[r.length-1].vector));D||g&&r.length===1?Ct.push(Er):h?Ct.push(...oc(Er,C,z,Si)):Ct.push(...ic(Er,C,z))}return je.concat(Ct,Me.reverse(),kr)}var xi=[0,0];function Ii(r){return r!=null&&r>=0}function Ri(r,e={}){var h;let{streamline:t=.5,size:n=16,last:o=!1}=e;if(r.length===0)return[];let i=gi+(1-t)*fi,s=Array.isArray(r[0])?r:r.map(({x:p,y:S,pressure:g=sn})=>[p,S,g]);if(s.length===2){let p=s[1];s=s.slice(0,-1);for(let S=1;S<5;S++)s.push(mn(s[0],p,S/4))}s.length===1&&(s=[...s,[...O(s[0],an),...s[0].slice(2)]]);let a=[{point:[s[0][0],s[0][1]],pressure:Ii(s[0][2])?s[0][2]:yi,vector:[...an],distance:0,runningLength:0}],l=!1,c=0,d=a[0],u=s.length-1;for(let p=1;p<s.length;p++){let S=o&&p===u?[s[p][0],s[p][1]]:mn(d.point,s[p],i);if(ki(d.point,S))continue;let g=bi(S,d.point);if(c+=g,p<u&&!l){if(c<n)continue;l=!0}lt(xi,d.point,S),d={point:S,pressure:Ii(s[p][2])?s[p][2]:sn,vector:qt(xi),distance:g,runningLength:c},a.push(d)}return a[0].vector=((h=a[1])==null?void 0:h.vector)||[0,0],a}function fn(r,e={}){return Ti(Ri(r,e),e)}function Ni(r,e){if(r.classList.contains("mod-handwritten")){r.setAttribute("fill",e);return}r.setAttribute("stroke",e)}function Cn(r,e){return ac(r,e,8192,2048)}function Li(r){return Math.max(0,r-1)}function ac(r,e,t,n){if(!Number.isFinite(r)||!Number.isFinite(e)||r-e<=t+n)return null;let o=Math.max(0,Math.floor(e)),i=Math.min(o+n,Math.floor(r));return i-o<2?null:{startIndex:o,endIndex:i,nextCommittedPointIndex:i}}var $t=class{constructor(e=256){this.recordsById=new Map;this.cellIdsByKey=new Map;this.cellSize=e}rebuild(e){this.clear();for(let t of e)this.set(t.id,t.bounds,t.order)}clear(){this.recordsById.clear(),this.cellIdsByKey.clear()}set(e,t,n){if(this.remove(e),!yn(t)||!Number.isFinite(n))return;let o=this.getCellKeys(t);this.recordsById.set(e,{bounds:t,order:n,cellKeys:o});for(let i of o){let s=this.cellIdsByKey.get(i);s||(s=new Set,this.cellIdsByKey.set(i,s)),s.add(e)}}updateBounds(e,t){var o;let n=(o=this.recordsById.get(e))==null?void 0:o.order;n!==void 0&&this.set(e,t,n)}remove(e){let t=this.recordsById.get(e);if(t){for(let n of t.cellKeys){let o=this.cellIdsByKey.get(n);o&&(o.delete(e),o.size===0&&this.cellIdsByKey.delete(n))}this.recordsById.delete(e)}}setOrder(e){e.forEach((t,n)=>{let o=this.recordsById.get(t);o&&(o.order=n)})}queryBounds(e,t="ascending"){if(!yn(e))return[];let n=new Set;for(let o of this.getCellKeys(e)){let i=this.cellIdsByKey.get(o);if(i)for(let s of i){let a=this.recordsById.get(s);a&&Di(e,a.bounds)&&n.add(s)}}return this.sortIds(Array.from(n),t)}forEachBounds(e,t){if(!yn(e))return;let n=new Set;for(let o of this.getCellKeys(e)){let i=this.cellIdsByKey.get(o);if(i)for(let s of i){if(n.has(s))continue;let a=this.recordsById.get(s);if(!(!a||!Di(e,a.bounds))&&(n.add(s),t(s)===!1))return}}}sortIdsByOrder(e,t="ascending"){return this.sortIds([...e],t)}sortIds(e,t){if(t==="none")return e;let n=t==="ascending"?1:-1;return e.sort((o,i)=>n*(this.getOrder(o)-this.getOrder(i))),e}getOrder(e){var t,n;return(n=(t=this.recordsById.get(e))==null?void 0:t.order)!=null?n:Number.MAX_SAFE_INTEGER}getCellKeys(e){let t=this.getCellRange(e),n=[];for(let o=t.minCellX;o<=t.maxCellX;o++)for(let i=t.minCellY;i<=t.maxCellY;i++)n.push(lc(o,i));return n}getCellRange(e){return{minCellX:Math.floor(e.minX/this.cellSize),maxCellX:Math.floor(e.maxX/this.cellSize),minCellY:Math.floor(e.minY/this.cellSize),maxCellY:Math.floor(e.maxY/this.cellSize)}}};function A(r,e){let t=Number.isFinite(e)?Math.max(0,e/2):0;return En(r,t)}function Ai(r,e){return{minX:r.x-e,minY:r.y-e,maxX:r.x+e,maxY:r.y+e}}function En(r,e){return{minX:r.minX-e,minY:r.minY-e,maxX:r.maxX+e,maxY:r.maxY+e}}function Di(r,e){return r.minX<=e.maxX&&r.maxX>=e.minX&&r.minY<=e.maxY&&r.maxY>=e.minY}function yn(r){return Number.isFinite(r.minX)&&Number.isFinite(r.minY)&&Number.isFinite(r.maxX)&&Number.isFinite(r.maxY)&&r.minX<=r.maxX&&r.minY<=r.maxY}function lc(r,e){return`${r},${e}`}function ct(r,e=80){return{minX:r.minX-e,minY:r.minY-e,maxX:r.maxX+e,maxY:r.maxY+e}}function Mi(r,e,t){return r.filter(n=>{let o=t(n);return o!==null&&cc(e,o)})}function cc(r,e){return r.minX<=e.maxX&&r.maxX>=e.minX&&r.minY<=e.maxY&&r.maxY>=e.minY}function dc(r,e){let t=Math.max(0,r.maxX-r.minX),n=Math.max(0,r.maxY-r.minY);return Math.max(t,n)*e}function ze(r,e,t=!1,n=.5){return t||!Number.isFinite(e)||e<=0?!0:dc(r,e)>=n}function Hi(r){return r.opacity!=="1"||r.blurRadius>0?null:r.kind==="handwritten"?["handwritten",r.color].join("|"):typeof r.width!="number"||!Number.isFinite(r.width)?null:["linear",r.color,r.width].join("|")}function Bi(r){let e=[],t=null,n=[],o=()=>{n.length!==0&&(n.length===1||t===null?e.push(...n.map(i=>({type:"single",strokeId:i}))):e.push({type:"batch",strokeIds:n,batchKey:t}),n=[],t=null)};for(let i of r){if(i.isSelected||i.batchKey===null){o(),e.push({type:"single",strokeId:i.id});continue}t!==null&&t!==i.batchKey&&o(),t=i.batchKey,n.push(i.id)}return o(),e}var uc=1e3,hc=3500,kn=8,bn=64,pc=96,Sc=2;function jt(r){return r>uc}function Oi(r){return r>hc}function vc(r){return!Number.isFinite(r)||r<=0?80:Math.min(80,pc/r)}function Ke(r,e,t=vc(e)){return ct(r,t)}function Vi(r){let e=[],t=[],n=()=>{t.length!==0&&(e.push({type:"raster",strokeIds:t}),t=[])};for(let o of r){if(o.isSelected){n(),e.push({type:"single",strokeId:o.id});continue}t.push(o.id)}return n(),e}function Fi(r){return!Number.isFinite(r)||r<=0?1:Math.min(r,Sc)}function Gi(r,e){return!e&&Number.isFinite(r)&&r>1e4}function Wi(r,e=128){return!Number.isFinite(r)||r<=0?e:e/r}function mc(r,e,t,n){return[r,e,Ki(t),Ki(n)].join(",")}function gc(r,e){return{minX:r.tileX*e,minY:r.tileY*e,maxX:r.tileX*e+e,maxY:r.tileY*e+e}}function Ui(r,e,t){if(!Cc(r,e))return[];let n=wn(r,e),o=[];for(let i=n.minTileY;i<=n.maxTileY;i++)for(let s=n.minTileX;s<=n.maxTileX;s++){let a={tileX:s,tileY:i};o.push({...a,key:mc(s,i,e,t),bounds:gc(a,e)})}return o}function wn(r,e){return{minTileX:Math.floor(r.minX/e),maxTileX:Math.floor((r.maxX-Number.EPSILON)/e),minTileY:Math.floor(r.minY/e),maxTileY:Math.floor((r.maxY-Number.EPSILON)/e)}}function Yi(r){let e=Number.POSITIVE_INFINITY,t=Number.NEGATIVE_INFINITY,n=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(let i of r)e=Math.min(e,i.tileX),t=Math.max(t,i.tileX),n=Math.min(n,i.tileY),o=Math.max(o,i.tileY);return{minTileX:e,maxTileX:t,minTileY:n,maxTileY:o}}function Xi(r,e){return zi(r)?e.some(t=>zi(t)&&fc(r,t)):!1}function fc(r,e){return r.minX<=e.maxX&&r.maxX>=e.minX&&r.minY<=e.maxY&&r.maxY>=e.minY}function zi(r){return Number.isFinite(r.minX)&&Number.isFinite(r.minY)&&Number.isFinite(r.maxX)&&Number.isFinite(r.maxY)&&r.minX<=r.maxX&&r.minY<=r.maxY}function Cc(r,e){return Number.isFinite(e)&&e>0&&Number.isFinite(r.minX)&&Number.isFinite(r.minY)&&Number.isFinite(r.maxX)&&Number.isFinite(r.maxY)&&r.minX<=r.maxX&&r.minY<=r.maxY}function Ki(r){return Math.round(r*1e3)/1e3}var yc=2e4,Ec=8192,Jt=class{constructor(e=yc,t=Ec){this.pathDataByKey=new Map;this.rasterPathByKey=new Map;this.pathDataKeysByStrokeId=new Map;this.rasterPathKeysByStrokeId=new Map;this.maxPathDataEntries=e,this.maxRasterPathEntries=t}getPathData(e,t,n){if(this.maxPathDataEntries<=0)return n();let o=this.pathDataByKey.get(t);if(o!==void 0)return o;let i=n();return this.pathDataByKey.set(t,i),Zi(this.pathDataKeysByStrokeId,e,t),this.evictOldestPathDataEntries(),i}getRasterPath(e,t,n){if(this.maxRasterPathEntries<=0)return n();let o=this.rasterPathByKey.get(t);if(o!==void 0)return o;let i=n();return this.rasterPathByKey.set(t,i),Zi(this.rasterPathKeysByStrokeId,e,t),this.evictOldestRasterPathEntries(),i}invalidateStroke(e){ji(this.pathDataByKey,this.pathDataKeysByStrokeId,e),ji(this.rasterPathByKey,this.rasterPathKeysByStrokeId,e)}clear(){this.pathDataByKey.clear(),this.rasterPathByKey.clear(),this.pathDataKeysByStrokeId.clear(),this.rasterPathKeysByStrokeId.clear()}getPathDataEntryCount(){return this.pathDataByKey.size}getRasterPathEntryCount(){return this.rasterPathByKey.size}evictOldestPathDataEntries(){$i(this.pathDataByKey,this.pathDataKeysByStrokeId,this.maxPathDataEntries)}evictOldestRasterPathEntries(){$i(this.rasterPathByKey,this.rasterPathKeysByStrokeId,this.maxRasterPathEntries)}};function Qt(r,e){return[r.id,e.kind,kc(r),bc(r,e)].join("|")}function kc(r){let e=r.points[0],t=r.points[r.points.length-1];return[r.points.length,qi(e),qi(t),r.width].join(":")}function qi(r){var e;return r?[r.x,r.y,(e=r.pressure)!=null?e:""].join(","):""}function bc(r,e){var n,o,i,s;let t=ne(r,e.settings);return e.kind==="linear"?t.enabled?"smooth":"linear":[(n=e.isComplete)!=null?n:!0,(o=e.hasPressure)!=null?o:!1,(i=e.isStart)!=null?i:!0,(s=e.isEnd)!=null?s:!0,t.thinning,t.smoothing,t.streamline,t.taperStart,t.taperEnd].join(":")}function Zi(r,e,t){let n=r.get(e);n||(n=new Set,r.set(e,n)),n.add(t)}function $i(r,e,t){for(;r.size>t;){let n=r.keys().next().value;if(n===void 0)return;r.delete(n),wc(e,n)}}function ji(r,e,t){let n=e.get(t);if(n){for(let o of n)r.delete(o);e.delete(t)}}function wc(r,e){let t=e.split("|",1)[0];if(!t)return;let n=r.get(t);n&&(n.delete(e),n.size===0&&r.delete(t))}function Ji(r,e){return dt(y(r),e)}function dt(r,e){return Pc(r)/Tc(e)}function Qi(r,e){return{...r,taperStart:dt(r.taperStart,e),taperEnd:dt(r.taperEnd,e)}}function Pc(r){return Number.isFinite(r)&&r>0?r:0}function Tc(r){return Number.isFinite(r)&&r>0?r:1}var G="http://www.w3.org/2000/svg",ts="http://www.w3.org/1999/xhtml",Nc=1,rs=1,Lc=10,Dc=12,ns=10,Ac=6,os=4,is=1.5,Mc=6,Hc=4,Bc=4,_c=2,ss=10,ut=10,as=180,ls=42,Oc=["send-to-back","send-backward","bring-forward","bring-to-front"],Vc={"send-to-back":{label:"Send selected drawing to back",icon:"arrow-down-to-line"},"send-backward":{label:"Send selected drawing backward",icon:"arrow-down"},"bring-forward":{label:"Bring selected drawing forward",icon:"arrow-up"},"bring-to-front":{label:"Bring selected drawing to front",icon:"arrow-up-to-line"}},Fc=.05,zc=.001,Pn=.001,Kc=.001,Gc=300,Wc=450,_s=3,Uc=_s+1,Yc=160,cs=96,ds=[{name:"Red",value:"#ef4444"},{name:"Orange",value:"#f97316"},{name:"Amber",value:"#f59e0b"},{name:"Yellow",value:"#eab308"},{name:"Lime",value:"#84cc16"},{name:"Green",value:"#22c55e"},{name:"Emerald",value:"#10b981"},{name:"Teal",value:"#14b8a6"},{name:"Cyan",value:"#06b6d4"},{name:"Blue",value:"#3b82f6"},{name:"Indigo",value:"#6366f1"},{name:"Violet",value:"#8b5cf6"},{name:"Purple",value:"#a855f7"},{name:"Fuchsia",value:"#d946ef"},{name:"Pink",value:"#ec4899"},{name:"Rose",value:"#f43f5e"},{name:"Coral",value:"#fb7185"},{name:"Brown",value:"#92400e"},{name:"Slate",value:"#64748b"},{name:"Black",value:"#111827"},{name:"White",value:"#ffffff"},{name:"Stone",value:"#a8a29e"},{name:"Gray",value:"#9ca3af"},{name:"Charcoal",value:"#374151"},{name:"Maroon",value:"#7f1d1d"},{name:"Ochre",value:"#b45309"},{name:"Olive",value:"#4d7c0f"},{name:"Forest",value:"#166534"},{name:"Navy",value:"#1e3a8a"},{name:"Lavender",value:"#c4b5fd"}],$="#8b5cf6",Xc=6,U=[{id:"disc",label:"Disc"},{id:"palettes",label:"Palettes"}],us=40.25,qc=2,Tn=15,Zc=.02,xn=.1,$c=14,Os=0,$n=359,he=0,Wn=100,vt=1,Un=[{id:"hue",label:"Hue",min:Os,max:$n,step:vt,ariaLabel:"Stroke color HSL hue"},{id:"saturation",label:"Saturation",min:he,max:Wn,step:vt,ariaLabel:"Stroke color HSL saturation"},{id:"lightness",label:"Lightness",min:he,max:Wn,step:vt,ariaLabel:"Stroke color HSL lightness"}],xe=0,$e=255,mt=1,pe=0,gt=100,Se=-128,ve=127,Ie=1,Vs=[{id:"hsl",label:"HSL"},{id:"rgb",label:"RGB"},{id:"lab",label:"Lab"}],jc=[{id:"red",label:"Red",min:xe,max:$e,step:mt,ariaLabel:"Stroke color red channel"},{id:"green",label:"Green",min:xe,max:$e,step:mt,ariaLabel:"Stroke color green channel"},{id:"blue",label:"Blue",min:xe,max:$e,step:mt,ariaLabel:"Stroke color blue channel"}],Jc=[{id:"labLightness",label:"Lightness",min:pe,max:gt,step:Ie,ariaLabel:"Stroke color Lab lightness"},{id:"labA",label:"A",min:Se,max:ve,step:Ie,ariaLabel:"Stroke color Lab a axis"},{id:"labB",label:"B",min:Se,max:ve,step:Ie,ariaLabel:"Stroke color Lab b axis"}],Fs=".draw-in-canvas-control-group, .draw-in-canvas-render-layer, .draw-in-canvas-capture-layer, .draw-in-canvas-brush-controls, .draw-in-canvas-color-palette, .draw-in-canvas-stroke-settings-palette, .draw-in-canvas-brush-preview, .draw-in-canvas-stroke-width-preview, .draw-in-canvas-pen-cursor, .draw-in-canvas-scale-button, .draw-in-canvas-native-layer-menu, .draw-in-canvas-stroke-scale-menu-container",zs="draw-in-canvas-stale",Qc="draw-in-canvas-color-palette-open",hs="draw-in-canvas-tiny-control-scale",ed=1,td=.5,rd=1,nd=.5,od=2,In=20,Rn=20,ps=3,id=2,sd=5.5,ad=24,ld=1,cd=2,dd=3,ud=3,hd=1;function jn(r){let e=Array.from(r.querySelectorAll(Fs));for(let t of e)t.classList.add(zs)}function pd(r,e){let t=Array.from(r.querySelectorAll(Fs));for(let n of t)n.classList.toggle(zs,!e.has(n))}var ur=class{constructor(e,t,n,o,i,s,a,l,c,d){this.drawingData=tt();this.strokeById=new Map;this.strokeGroupById=new Map;this.strokeBatchEls=[];this.strokeRasterEls=[];this.strokeRasterTileEls=[];this.rasterTileCache=new Map;this.rasterTileRenderJobs=[];this.rasterTileSetupJobs=[];this.rasterTileSetupFrameId=null;this.rasterTileRenderFrameId=null;this.rasterTileRenderGeneration=0;this.rasterTileUsageCounter=0;this.rasterRenderFrameIds=new Set;this.rasterRenderGeneration=0;this.strokeBoundsById=new Map;this.strokeSpatialIndex=new $t;this.strokePathCache=new Jt;this.captureEl=null;this.svgEl=null;this.strokeInteractionEl=null;this.toolbarGroupEl=null;this.toolbarButtonEl=null;this.selectButtonEl=null;this.toolbarControlsEl=null;this.toolbarControlsOriginalZIndex=null;this.colorPaletteEl=null;this.strokeSettingsPaletteEl=null;this.brushControlsEl=null;this.brushColorButtonEl=null;this.brushSettingsButtonEl=null;this.colorPaletteTriggerEl=null;this.strokeSettingsPaletteTriggerEl=null;this.colorPaletteTarget="brush";this.strokeSettingsPaletteTarget="brush";this.customColorHex=$;this.colorPaletteTab="disc";this.colorWheelHsv=pt($);this.colorValueMode="hsl";this.colorValueHsl=ce($);this.preserveHslColorValueForHex=null;this.colorValueLab=le($);this.preserveLabColorValueForHex=null;this.shouldSelectCustomColorHexOnClick=!1;this.toolbarPressState=null;this.brushPreviewEl=null;this.brushPreviewState=null;this.penCursorEl=null;this.pendingPenCursorPosition=null;this.penCursorFrameId=null;this.penCursorAppearanceKey="";this.undoButtonEl=null;this.redoButtonEl=null;this.activeStroke=null;this.activeStrokeGroupEl=null;this.activeStrokePathEl=null;this.activeStrokePreviewFrameId=null;this.activeStrokePointerId=null;this.activeStrokeHasPressure=!1;this.activeStrokePreviewCommittedPointIndex=0;this.activeStrokePreviewChunkPathEls=[];this.selectedStrokeIds=new Set;this.selectionBoxEl=null;this.selectionHandleEls=[];this.strokeScaleMenuContainerEl=null;this.pendingSelectedStrokeRecolorChanges=null;this.pendingSelectedStrokeStyleChanges=null;this.dragState=null;this.resizeState=null;this.nativeSelectionDragState=null;this.mutationObserver=null;this.isObservingCanvasAttributes=null;this.domSyncFrameId=null;this.pendingDomSyncFlags=null;this.renderViewportObserver=null;this.renderViewportObservedEl=null;this.renderViewportFrameId=null;this.renderedStrokeIds=[];this.renderedSelectedStrokeIds=[];this.renderedRasterViewportKey="";this.saveTimeoutId=null;this.hasPendingSave=!1;this.positionedEl=null;this.previousPosition="";this.suppressNextNativeUndoClick=!1;this.suppressNextNativeRedoClick=!1;this.isSpaceKeyPressed=!1;this.interactionCursor=null;this.tinyControlScaleWrapperEl=null;this.tinyControlScaleKey="";this.nativeEdgePathOverrides=new Map;this.captureDisposers=[];this.toolbarDisposers=[];this.colorPaletteDisposers=[];this.strokeSettingsPaletteDisposers=[];this.brushControlsDisposers=[];this.brushPreviewDisposers=[];this.renderDisposers=[];this.strokeInteractionDisposers=[];this.canvasHistoryButtonDisposers=[];this.strokeScaleMenuDisposers=[];this.undoStack=[];this.redoStack=[];this.handlePointerDown=e=>{if(e.button!==0||!this.captureEl)return;if(this.isSpaceKeyPressed){this.hidePenCursor();return}this.showPenCursorFromEvent(e),this.mountRenderLayer();let t=this.clientPointToCanvasPoint(e);if(!t||!this.svgEl)return;e.preventDefault(),e.stopPropagation(),Ge(this.captureEl,e.pointerId);let n=this.getCanvasScreenScale(),o={id:w(),color:this.settings.strokeColor,width:Ji(this.settings.strokeWidth,n),hardness:this.settings.strokeHardness,opacity:this.settings.strokeOpacity,handwriting:Qi(He(this.settings),n),points:[t],createdAt:Date.now()},i=activeDocument.createElementNS(G,"g");i.classList.add("draw-in-canvas-active-stroke"),i.setAttribute("pointer-events","none"),i.setAttribute("opacity",Ye(o.opacity));let s=this.createPathEl(o,!1);s.removeAttribute("opacity"),i.appendChild(s),this.activeStroke=o,this.activeStrokeGroupEl=i,this.activeStrokePathEl=s,this.activeStrokePointerId=e.pointerId,this.activeStrokeHasPressure=t.pressure!==void 0,this.initializeActiveStrokePreviewState(),this.addStroke(o),this.svgEl.appendChild(i)};this.handlePointerMove=e=>{this.showPenCursorFromEvent(e),!(!this.activeStroke||!this.activeStrokeGroupEl||e.pointerId!==this.activeStrokePointerId)&&this.appendActiveStrokePointerPoints(e)&&(e.preventDefault(),e.stopPropagation(),this.scheduleActiveStrokePreviewUpdate())};this.handlePointerUp=e=>{var t;if(!this.activeStroke||e.pointerId!==this.activeStrokePointerId){e.type==="pointercancel"&&this.hidePenCursor();return}this.appendActiveStrokePointerPoints(e),e.preventDefault(),e.stopPropagation(),(t=this.captureEl)!=null&&t.hasPointerCapture(e.pointerId)&&this.captureEl.releasePointerCapture(e.pointerId),this.finishActiveStroke(),this.updatePenCursorAfterPointerEnd(e)};this.handlePointerLeave=e=>{cr(e)&&(this.activeStroke&&e.pointerId===this.activeStrokePointerId||this.hidePenCursor())};this.handleCaptureWindowBlur=()=>{this.hidePenCursor()};this.handleKeyDown=e=>{if(this.shouldUseSelectToolShortcut(e)){e.preventDefault(),e.stopPropagation(),this.enableSelectMode();return}e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.requestToggleDrawingMode())};this.handleSelectToolbarPointerDown=e=>{e.button!==0||!this.selectButtonEl||(e.preventDefault(),e.stopPropagation(),this.selectButtonEl.focus({preventScroll:!0}),this.enableSelectMode())};this.handleSelectToolbarKeyDown=e=>{tr(e)&&(e.preventDefault(),e.stopPropagation(),this.enableSelectMode())};this.handleToolbarPointerDown=e=>{if(e.button!==0||!this.toolbarButtonEl)return;e.preventDefault(),e.stopPropagation(),this.toolbarButtonEl.focus({preventScroll:!0}),this.clearToolbarPressState(),Ge(this.toolbarButtonEl,e.pointerId);let t={pointerId:e.pointerId,timeoutId:window.setTimeout(()=>{this.toolbarPressState===t&&(t.didOpenPalette=!0,this.toggleColorPalette())},Wc),didOpenPalette:!1};this.toolbarPressState=t};this.handleToolbarPointerUp=e=>{let t=this.toolbarPressState;if(!t||t.pointerId!==e.pointerId)return;e.preventDefault(),e.stopPropagation();let n=!t.didOpenPalette;this.clearToolbarPressState(),n&&(this.closeBrushPopovers(),this.requestToggleDrawingMode())};this.handleToolbarPointerCancel=e=>{let t=this.toolbarPressState;!t||t.pointerId!==e.pointerId||(e.preventDefault(),e.stopPropagation(),this.clearToolbarPressState())};this.handleToolbarKeyDown=e=>{if(e.key==="ArrowDown"){e.preventDefault(),e.stopPropagation(),this.toggleColorPalette();return}tr(e)&&(e.preventDefault(),e.stopPropagation(),this.closeBrushPopovers(),this.requestToggleDrawingMode())};this.handleColorSwatchPointerDown=e=>{e.preventDefault(),e.stopPropagation()};this.handleHistoryColorSwatchPointerDown=e=>{this.getHistoryColorSwatchEventTarget(e)&&(e.preventDefault(),e.stopPropagation())};this.handleHistoryColorSwatchClick=e=>{let t=this.getHistoryColorSwatchEventTarget(e);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.dataset.color;n&&(this.setStrokeColor(n),this.recordColorHistory(n))};this.handlePresetColorSwatchClick=e=>{if(e.preventDefault(),e.stopPropagation(),!(e.currentTarget instanceof HTMLElement))return;let t=e.currentTarget.dataset.color;t&&(this.setStrokeColor(t),this.recordColorHistory(t))};this.handleColorPaletteTabClick=e=>{if(e.preventDefault(),e.stopPropagation(),!(e.currentTarget instanceof HTMLElement))return;let t=rr(e.currentTarget.dataset.colorPaletteTab);t&&(this.colorPaletteTab=t,this.syncColorPaletteTabControls(),this.positionColorPalette())};this.handleColorPaletteTabKeyDown=e=>{var o,i;if(!(e.currentTarget instanceof HTMLElement))return;let t=rr(e.currentTarget.dataset.colorPaletteTab);if(!t)return;let n=xd(t,e);n&&(e.preventDefault(),e.stopPropagation(),this.colorPaletteTab=n,this.syncColorPaletteTabControls(),this.positionColorPalette(),(i=(o=this.colorPaletteEl)==null?void 0:o.querySelector(`[data-color-palette-tab="${n}"]`))==null||i.focus({preventScroll:!0}))};this.handleColorValueModeClick=e=>{if(e.preventDefault(),e.stopPropagation(),!(e.currentTarget instanceof HTMLElement))return;let t=Id(e.currentTarget.dataset.colorValueMode);t&&this.setColorValueMode(t)};this.handleColorWheelPointerDown=e=>{if(e.button!==0||!(e.currentTarget instanceof HTMLElement))return;let t=Dn(e.currentTarget.dataset.colorWheelControl);t&&(e.preventDefault(),e.stopPropagation(),e.currentTarget.focus({preventScroll:!0}),Ge(e.currentTarget,e.pointerId),this.updateColorWheelFromPointer(e.currentTarget,e,t))};this.handleColorWheelPointerMove=e=>{if(!(e.currentTarget instanceof HTMLElement)||!e.currentTarget.hasPointerCapture(e.pointerId))return;let t=Dn(e.currentTarget.dataset.colorWheelControl);t&&(e.preventDefault(),e.stopPropagation(),this.updateColorWheelFromPointer(e.currentTarget,e,t))};this.handleColorWheelPointerUp=e=>{!(e.currentTarget instanceof HTMLElement)||!e.currentTarget.hasPointerCapture(e.pointerId)||(e.preventDefault(),e.stopPropagation(),this.recordColorHistory(this.customColorHex))};this.handleColorWheelKeyDown=e=>{if(!(e.currentTarget instanceof HTMLElement))return;let t=Dn(e.currentTarget.dataset.colorWheelControl),n=t==="hue"?Gd(this.colorWheelHsv,e):t==="disc"?Wd(this.colorWheelHsv,e):null;n&&(e.preventDefault(),e.stopPropagation(),this.setColorWheelHsv(n),this.recordColorHistory(nr(n)))};this.handleHslSliderPointerDown=e=>{e.stopPropagation()};this.handleHslSliderInput=e=>{e.stopPropagation(),e.currentTarget instanceof HTMLInputElement&&this.updateHslSliderFromInput(e.currentTarget)};this.handleHslSliderChange=e=>{e.stopPropagation(),e.currentTarget instanceof HTMLInputElement&&this.updateHslSliderFromInput(e.currentTarget)&&this.recordColorHistory(this.customColorHex)};this.handleCurrentColorHslPointerDown=e=>{e.stopPropagation(),!(!(e.currentTarget instanceof HTMLInputElement)||!e.currentTarget.readOnly)&&(e.preventDefault(),e.currentTarget.focus({preventScroll:!0}))};this.handleCurrentColorHslClick=e=>{if(e.stopPropagation(),!(!(e.currentTarget instanceof HTMLInputElement)||!e.currentTarget.readOnly)){if(e.preventDefault(),e.detail>=2){this.beginCurrentColorHslEdit(e.currentTarget);return}this.copyCurrentColorHslToClipboard(e.currentTarget)}};this.handleCurrentColorHslDoubleClick=e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget instanceof HTMLInputElement&&this.beginCurrentColorHslEdit(e.currentTarget)};this.handleCurrentColorHslFocus=e=>{if(!(e.currentTarget instanceof HTMLInputElement)||e.currentTarget.readOnly)return;let t=e.currentTarget;window.requestAnimationFrame(()=>{activeDocument.activeElement===t&&!t.readOnly&&t.select()})};this.handleCurrentColorHslInput=e=>{if(e.stopPropagation(),!(e.currentTarget instanceof HTMLInputElement)||e.currentTarget.readOnly)return;let t=Cs(this.colorValueMode,e.currentTarget.value),n=e.currentTarget.value.trim().length===0;we(e.currentTarget,!!t||n),t&&this.setColorValueHex(t.hexColor,t.fallbackHue,t.labColor,t.hslColor)};this.handleCurrentColorHslChange=e=>{e.stopPropagation(),e.currentTarget instanceof HTMLInputElement&&this.commitCurrentColorHslEdit(e.currentTarget)};this.handleCurrentColorHslKeyDown=e=>{if(e.stopPropagation(),e.currentTarget instanceof HTMLInputElement){if(e.currentTarget.readOnly){if(e.key==="Enter"||e.key==="F2"){e.preventDefault(),this.beginCurrentColorHslEdit(e.currentTarget);return}(e.key===" "||ws(e))&&(e.preventDefault(),this.copyCurrentColorHslToClipboard(e.currentTarget));return}if(e.key==="Enter"){e.preventDefault(),e.currentTarget.blur();return}e.key==="Escape"&&(e.preventDefault(),this.resetCurrentColorHslInput(e.currentTarget),e.currentTarget.blur())}};this.handleCurrentColorHexPointerDown=e=>{e.stopPropagation(),!(!(e.currentTarget instanceof HTMLInputElement)||!e.currentTarget.readOnly)&&(e.preventDefault(),e.currentTarget.focus({preventScroll:!0}))};this.handleCurrentColorHexClick=e=>{if(e.stopPropagation(),!(!(e.currentTarget instanceof HTMLInputElement)||!e.currentTarget.readOnly)){if(e.preventDefault(),e.detail>=2){this.beginCurrentColorHexEdit(e.currentTarget);return}this.copyCurrentColorHexToClipboard(e.currentTarget)}};this.handleCurrentColorHexDoubleClick=e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget instanceof HTMLInputElement&&this.beginCurrentColorHexEdit(e.currentTarget)};this.handleCurrentColorHexFocus=e=>{if(!(e.currentTarget instanceof HTMLInputElement)||e.currentTarget.readOnly)return;let t=e.currentTarget;window.requestAnimationFrame(()=>{activeDocument.activeElement===t&&!t.readOnly&&t.select()})};this.handleCurrentColorHexInput=e=>{if(e.stopPropagation(),!(e.currentTarget instanceof HTMLInputElement)||e.currentTarget.readOnly)return;let t=E(e.currentTarget.value),n=e.currentTarget.value.trim().length===0;W(e.currentTarget,!!t||n),t&&(this.customColorHex=t,this.setStrokeColor(t))};this.handleCurrentColorHexChange=e=>{e.stopPropagation(),e.currentTarget instanceof HTMLInputElement&&this.commitCurrentColorHexEdit(e.currentTarget)};this.handleCurrentColorHexKeyDown=e=>{if(e.stopPropagation(),e.currentTarget instanceof HTMLInputElement){if(e.currentTarget.readOnly){if(e.key==="Enter"||e.key==="F2"){e.preventDefault(),this.beginCurrentColorHexEdit(e.currentTarget);return}(e.key===" "||ws(e))&&(e.preventDefault(),this.copyCurrentColorHexToClipboard(e.currentTarget));return}if(e.key==="Enter"){e.preventDefault(),e.currentTarget.blur();return}e.key==="Escape"&&(e.preventDefault(),this.resetCurrentColorHexInput(e.currentTarget),e.currentTarget.blur())}};this.handleNativeColorPickerInput=e=>{if(e.stopPropagation(),!(e.currentTarget instanceof HTMLInputElement))return;let t=E(e.currentTarget.value);t&&(this.customColorHex=t,this.setStrokeColor(t),e.type==="change"&&this.recordColorHistory(t))};this.handleCustomColorHexPointerDown=e=>{e.stopPropagation(),e.currentTarget instanceof HTMLInputElement&&(this.shouldSelectCustomColorHexOnClick=activeDocument.activeElement!==e.currentTarget)};this.handleCustomColorHexClick=e=>{e.stopPropagation(),e.currentTarget instanceof HTMLInputElement&&this.shouldSelectCustomColorHexOnClick&&(e.currentTarget.select(),this.shouldSelectCustomColorHexOnClick=!1)};this.handleCustomColorHexFocus=e=>{if(!(e.currentTarget instanceof HTMLInputElement))return;let t=e.currentTarget;window.requestAnimationFrame(()=>{activeDocument.activeElement===t&&t.select()})};this.handleCustomColorHexInput=e=>{if(e.stopPropagation(),!(e.currentTarget instanceof HTMLInputElement))return;let t=E(e.currentTarget.value),n=e.currentTarget.value.trim().length===0;W(e.currentTarget,!!t||n),t&&(this.customColorHex=t,this.setStrokeColor(t))};this.handleCustomColorHexChange=e=>{if(e.stopPropagation(),this.shouldSelectCustomColorHexOnClick=!1,!(e.currentTarget instanceof HTMLInputElement))return;let t=E(e.currentTarget.value);t&&(this.customColorHex=t,this.setStrokeColor(t),this.recordColorHistory(t)),e.currentTarget.value=Z(this.customColorHex),W(e.currentTarget,!0)};this.handleCustomColorHexKeyDown=e=>{e.stopPropagation(),!(e.key!=="Enter"||!(e.currentTarget instanceof HTMLInputElement))&&(e.preventDefault(),e.currentTarget.blur())};this.handleCustomColorShadeClick=e=>{if(e.preventDefault(),e.stopPropagation(),!(e.currentTarget instanceof HTMLElement))return;let t=e.currentTarget.dataset.color;t&&(this.setStrokeColor(t),this.recordColorHistory(t))};this.handleStrokeWidthSliderPointerDown=e=>{e.stopPropagation(),e.currentTarget instanceof HTMLInputElement&&(e.currentTarget.focus({preventScroll:!0}),this.openBrushPreview(e,e.currentTarget,"size"))};this.handleBrushSliderPointerDown=e=>{if(e.button!==0||!(e.currentTarget instanceof HTMLElement))return;let t=Ln(e.currentTarget.dataset.brushSlider);t&&(e.preventDefault(),e.stopPropagation(),e.currentTarget.focus({preventScroll:!0}),this.openBrushPreview(e,e.currentTarget,t),this.updateBrushSliderFromPointer(e.currentTarget,e))};this.handleBrushSliderPointerMove=e=>{!(e.currentTarget instanceof HTMLElement)||!e.currentTarget.hasPointerCapture(e.pointerId)||(e.preventDefault(),e.stopPropagation(),this.updateBrushSliderFromPointer(e.currentTarget,e))};this.handleBrushSliderPointerUp=e=>{e.currentTarget instanceof HTMLElement&&(e.preventDefault(),e.stopPropagation(),this.closeBrushPreview(),this.getBrushControlsTarget()==="selection"&&this.commitPendingSelectedStrokeStyleChanges())};this.handleBrushSliderKeyDown=e=>{if(!(e.currentTarget instanceof HTMLElement))return;let t=Ln(e.currentTarget.dataset.brushSlider);if(!t)return;let n=Pd(t,e,this.getBrushSliderCurrentValue(t));n!==null&&(e.preventDefault(),e.stopPropagation(),this.setBrushSliderValue(t,n),this.getBrushControlsTarget()==="selection"&&this.commitPendingSelectedStrokeStyleChanges())};this.handleBrushButtonPointerDown=e=>{e.stopPropagation()};this.handleBrushButtonKeyDown=e=>{e.key!=="Tab"&&e.stopPropagation()};this.handleBrushColorButtonClick=e=>{e.preventDefault(),e.stopPropagation(),this.toggleColorPalette(this.getBrushControlsTarget())};this.handleBrushSettingsButtonClick=e=>{e.preventDefault(),e.stopPropagation(),this.toggleStrokeSettingsPalette(this.getBrushControlsTarget())};this.handleStrokeWidthSliderKeyDown=e=>{e.stopPropagation()};this.handleStrokeWidthSliderInput=e=>{if(e.stopPropagation(),!(e.currentTarget instanceof HTMLInputElement))return;let t=Number(e.currentTarget.value);if(this.strokeSettingsPaletteTarget==="selection"){this.setSelectedStrokeWidth(t);return}this.setStrokeWidth(t),this.updateBrushPreview("size")};this.handleStrokeHardnessSliderInput=e=>{if(e.stopPropagation(),e.currentTarget instanceof HTMLInputElement){if(this.strokeSettingsPaletteTarget==="selection"){this.setSelectedStrokeHardness(Number(e.currentTarget.value));return}this.setStrokeHardness(Number(e.currentTarget.value))}};this.handleStrokeOpacitySliderInput=e=>{if(e.stopPropagation(),e.currentTarget instanceof HTMLInputElement){if(this.strokeSettingsPaletteTarget==="selection"){this.setSelectedStrokeOpacity(Number(e.currentTarget.value));return}this.setStrokeOpacity(Number(e.currentTarget.value)),this.updateBrushPreview("opacity")}};this.handleFreehandSliderInput=e=>{if(e.stopPropagation(),!(e.currentTarget instanceof HTMLInputElement))return;let t=yd(e.currentTarget.dataset.freehandSetting);if(t){if(this.strokeSettingsPaletteTarget==="selection"){this.setSelectedStrokeFreehandSliderValue(t,Number(e.currentTarget.value));return}this.setFreehandSliderValue(t,Number(e.currentTarget.value))}};this.handleHandwritingToggleChange=e=>{if(e.stopPropagation(),e.currentTarget instanceof HTMLInputElement){if(this.strokeSettingsPaletteTarget==="selection"){this.setSelectedStrokeBeautifulStrokes(e.currentTarget.checked);return}this.setBeautifulStrokes(e.currentTarget.checked)}};this.handleFreehandResetClick=e=>{if(e.preventDefault(),e.stopPropagation(),this.strokeSettingsPaletteTarget==="selection"){this.resetSelectedStrokeFreehandSliderValues();return}this.resetFreehandSliderValues()};this.handleBrushPreviewPointerMove=e=>{let t=this.brushPreviewState;!t||t.pointerId!==e.pointerId||(this.positionBrushPreview(e.clientX,e.clientY),this.updateBrushPreview(t.setting))};this.handleBrushPreviewPointerUp=e=>{let t=this.brushPreviewState;!t||t.pointerId!==e.pointerId||this.closeBrushPreview()};this.handleBrushPreviewWindowBlur=()=>{this.closeBrushPreview()};this.handleBrushPopoverDocumentPointerDown=e=>{var n,o,i,s,a;let t=e.target;t instanceof Node&&((n=this.toolbarGroupEl)!=null&&n.contains(t)||(o=this.colorPaletteEl)!=null&&o.contains(t)||(i=this.strokeSettingsPaletteEl)!=null&&i.contains(t)||(s=this.brushControlsEl)!=null&&s.contains(t)||(a=this.strokeScaleMenuContainerEl)!=null&&a.contains(t))||this.closeBrushPopovers()};this.handleColorPaletteDocumentKeyDown=e=>{var n,o;if(e.key!=="Escape")return;e.preventDefault(),e.stopPropagation();let t=(o=(n=this.colorPaletteTriggerEl)!=null?n:this.brushColorButtonEl)!=null?o:this.toolbarButtonEl;this.closeColorPalette(),t==null||t.focus({preventScroll:!0})};this.handleStrokeSettingsPaletteDocumentKeyDown=e=>{var n;if(e.key!=="Escape")return;e.preventDefault(),e.stopPropagation();let t=(n=this.strokeSettingsPaletteTriggerEl)!=null?n:this.brushSettingsButtonEl;this.closeStrokeSettingsPalette(),t==null||t.focus({preventScroll:!0})};this.handleStrokePointerDown=e=>{if(this.captureEl||e.button!==0||this.isSpaceKeyPressed||Ls(e.target))return;let t=this.clientPointToCanvasPoint(e);if(!t)return;let n=this.findResizeHandleAtPoint(t);if(n&&this.startStrokeResize(e.pointerId,n)){e.preventDefault(),e.stopPropagation();return}let o=this.findStrokeAtPoint(t);if(o){this.handleStrokeHitPointerDown(e,t,o);return}if(this.isPointInSelectionBox(t)){let i=this.getSelectedStrokeIds();i.length>0&&this.startStrokeDrag(e.pointerId,t,i)&&(e.preventDefault(),e.stopPropagation());return}if(Ns(e.target)){Fn(e)||this.selectStrokes([]);return}this.startNativeSelectionDrag(e,t)};this.handleStrokePointerMove=e=>{if(this.resizeState&&e.pointerId===this.resizeState.pointerId){this.handleStrokeResizePointerMove(e,this.resizeState);return}if(this.dragState&&e.pointerId===this.dragState.pointerId){this.handleStrokeDragPointerMove(e,this.dragState);return}if(this.nativeSelectionDragState&&e.pointerId===this.nativeSelectionDragState.pointerId){this.handleNativeSelectionDragPointerMove(e,this.nativeSelectionDragState);return}this.updateInteractionCursorFromEvent(e)};this.handleStrokePointerUp=e=>{if(this.resizeState&&e.pointerId===this.resizeState.pointerId){this.handleStrokeResizePointerUp(e,this.resizeState);return}if(this.dragState&&e.pointerId===this.dragState.pointerId){this.handleStrokeDragPointerUp(e,this.dragState);return}this.nativeSelectionDragState&&e.pointerId===this.nativeSelectionDragState.pointerId&&this.handleNativeSelectionDragPointerUp(e,this.nativeSelectionDragState)};this.handleStrokePointerLeave=()=>{this.resizeState||this.dragState||this.nativeSelectionDragState||this.setInteractionCursor(null)};this.handleWindowKeyDown=e=>{this.handleDrawingHistoryShortcut(e)};this.handleDocumentKeyDown=e=>{var t;if(!this.handleDrawingHistoryShortcut(e)){if(this.shouldUseSelectToolShortcut(e)){e.preventDefault(),e.stopPropagation(),this.enableSelectMode();return}if(!(e.target instanceof Node&&((t=this.brushControlsEl)!=null&&t.contains(e.target)))){if(Rs(e)&&!ir(e.target)){this.isSpaceKeyPressed=!0;return}this.captureEl||this.selectedStrokeIds.size===0||e.key!=="Delete"&&e.key!=="Backspace"||ir(e.target)||(e.preventDefault(),e.stopPropagation(),this.deleteSelectedStrokes())}}};this.handleDocumentKeyUp=e=>{Rs(e)&&(this.isSpaceKeyPressed=!1)};this.handleWindowBlur=()=>{this.isSpaceKeyPressed=!1};this.handleWindowResize=()=>{this.scheduleCanvasDomSync(),this.scheduleRenderViewportSync()};this.handleCanvasUndoPointerDown=e=>{this.undoStack.length!==0&&(e.preventDefault(),e.stopPropagation(),this.suppressNextNativeUndoClick=!0,this.undoLastStroke())};this.handleCanvasRedoPointerDown=e=>{this.redoStack.length!==0&&(e.preventDefault(),e.stopPropagation(),this.redoLastStroke(),this.suppressNextNativeRedoClick=!0)};this.handleCanvasUndoClick=e=>{this.suppressNextNativeUndoClick&&(this.suppressNextNativeUndoClick=!1,e.preventDefault(),e.stopPropagation())};this.handleCanvasRedoClick=e=>{this.suppressNextNativeRedoClick&&(this.suppressNextNativeRedoClick=!1,e.preventDefault(),e.stopPropagation())};this.handleCanvasUndoKeyDown=e=>{!tr(e)||this.undoStack.length===0||(e.preventDefault(),e.stopPropagation(),this.suppressNextNativeUndoClick=!0,this.undoLastStroke())};this.handleCanvasRedoKeyDown=e=>{!tr(e)||this.redoStack.length===0||(e.preventDefault(),e.stopPropagation(),this.suppressNextNativeRedoClick=!0,this.redoLastStroke())};this.handleStrokeScaleButtonPointerDown=e=>{e.preventDefault(),e.stopPropagation()};this.handleSelectedStrokeDeleteButtonClick=e=>{e.preventDefault(),e.stopPropagation(),this.commitPendingSelectedStrokeRecolor(),this.deleteSelectedStrokes()};var u;this.app=e,this.target=t,this.nativeCanvasLimits=new At(t),this.nativeElementScaleControls=new Kt(t),this.settings={...n},this.customColorHex=(u=E(n.strokeColor))!=null?u:$,this.colorWheelHsv=pt(this.customColorHex,this.colorWheelHsv.h),this.colorValueHsl=ce(this.customColorHex,this.colorWheelHsv.h),this.colorValueLab=le(this.customColorHex),this.requestToggleDrawingMode=o,this.requestSetStrokeColor=i,this.requestSetStrokeWidth=s,this.requestSetStrokeHardness=a,this.requestSetStrokeOpacity=l,this.requestSetFreehandSliderValue=c,this.requestSetBeautifulStrokes=d}async start(){let e=await uo(this.app,this.target.file,this.settings);this.drawingData=e.data,this.hasPendingSave=e.didBackfillStrokeHandwriting,this.rebuildStrokeIndex(),this.mountRenderLayer(),this.injectToolbarButton(),this.observeCanvasDom(),this.syncTinyCanvasFeatureState()}async stop(){var e,t;this.disableDrawingMode(),this.closeBrushPopovers(),this.removeToolbarButton(),this.removeCanvasHistoryButtonListeners(),this.removeStrokeInteractionListeners(),(e=this.mutationObserver)==null||e.disconnect(),this.mutationObserver=null,this.isObservingCanvasAttributes=null,this.domSyncFrameId!==null&&(window.cancelAnimationFrame(this.domSyncFrameId),this.domSyncFrameId=null,this.pendingDomSyncFlags=null),this.disconnectRenderViewportObserver(),this.renderViewportFrameId!==null&&(window.cancelAnimationFrame(this.renderViewportFrameId),this.renderViewportFrameId=null),this.cancelActiveStrokePreviewUpdate(),this.cancelPendingRasterRenders(),this.clearRasterTileCache(),this.strokePathCache.clear();for(let n of this.renderDisposers.splice(0))n();this.clearNativeSelectionDrag(),this.resizeState&&(this.clearStrokeResizeTransform(this.resizeState),this.resizeState=null),(t=this.svgEl)==null||t.remove(),this.svgEl=null,this.removeSelectionOverlay(),this.strokeGroupById.clear(),this.saveTimeoutId!==null&&(window.clearTimeout(this.saveTimeoutId),this.saveTimeoutId=null),this.clearTinyControlScale(),this.nativeCanvasLimits.dispose(),this.nativeElementScaleControls.dispose(),await this.saveNow()}isDrawingEnabled(){return this.captureEl!==null}enableDrawingMode(){this.captureEl||(this.dragState=null,this.resizeState=null,this.clearNativeSelectionDrag(),this.selectStrokes([]),this.mountRenderLayer(),this.mountCaptureLayer(),this.syncBrushControlsMountState(),this.syncToolbarButton())}disableDrawingMode(){var e;this.finishActiveStroke(),this.removePenCursor();for(let t of this.captureDisposers.splice(0))t();(e=this.captureEl)==null||e.remove(),this.captureEl=null,this.syncBrushControlsMountState(),this.positionedEl&&(this.positionedEl.setCssStyles({position:this.previousPosition}),this.positionedEl=null,this.previousPosition=""),this.syncToolbarButton()}setSettings(e){let t=Cd(this.settings,e),n=this.settings.allowTinyCanvasElements!==e.allowTinyCanvasElements;this.settings={...e},this.syncCanvasDomObserver();let o=this.syncTinyCanvasFeatureState();(n||o)&&this.selectedStrokeIds.size>0&&this.renderSelectionBox(),this.updateCustomColorFromStrokeColor(),this.syncToolbarButton(),this.syncColorPaletteSelection(),this.syncStrokeSettingsPaletteControls(),this.syncBrushControls(),this.settings.usePenCursorFallback?this.penCursorAppearanceKey="":this.hidePenCursor(),t&&(this.clearRasterTileCache(),this.strokePathCache.clear(),this.activeStroke?(this.resetActiveStrokePreviewState(),this.updateActiveStrokePreview()):this.renderStrokes())}async clear(){this.finishActiveStroke(),this.commitPendingSelectedStrokeRecolor(),this.drawingData.strokes.length!==0&&(this.pushHistory({type:"clear-strokes",strokes:pr(this.drawingData.strokes)}),this.drawingData={...tt(),colorHistory:this.drawingData.colorHistory},this.rebuildStrokeIndex(),this.selectStrokes([]),this.renderStrokes(),this.hasPendingSave=!0,await this.saveNow())}async undoLastStroke(){this.finishActiveStroke(),this.commitPendingSelectedStrokeRecolor();let e=this.undoStack.pop();return e?(this.applyHistoryAction(e,"undo"),this.redoStack.push(Gn(e)),this.hasPendingSave=!0,this.syncCanvasUndoRedoButtons(),await this.saveNow(),!0):!1}async redoLastStroke(){this.finishActiveStroke(),this.commitPendingSelectedStrokeRecolor();let e=this.redoStack.pop();return e?(this.applyHistoryAction(e,"redo"),this.undoStack.push(Gn(e)),this.hasPendingSave=!0,this.syncCanvasUndoRedoButtons(),await this.saveNow(),!0):!1}mountCaptureLayer(){let e=this.findCanvasWrapperEl();this.ensurePositioned(e);let t=activeDocument.createElement("div");t.classList.add("draw-in-canvas-capture-layer"),t.tabIndex=0,e.appendChild(t),this.captureEl=t,this.hideStaleElements(),this.captureDisposers.push(this.addListener(t,"pointerdown",this.handlePointerDown),this.addListener(t,"pointermove",this.handlePointerMove),this.addListener(t,"pointerup",this.handlePointerUp),this.addListener(t,"pointercancel",this.handlePointerUp),this.addListener(t,"pointerleave",this.handlePointerLeave),this.addListener(t,"keydown",this.handleKeyDown),this.addListener(window,"blur",this.handleCaptureWindowBlur)),window.requestAnimationFrame(()=>t.focus({preventScroll:!0}))}mountRenderLayer(){let e=this.findCanvasWorldEl(),t=this.svgEl,n=!1;t||(t=activeDocument.createElementNS(G,"svg"),t.classList.add("draw-in-canvas-render-layer"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),this.svgEl=t,n=!0),(t.parentElement!==e||e.lastElementChild!==t)&&(e.appendChild(t),n=!0),this.syncRenderViewportObserver(e),n?this.renderStrokes():this.syncVisibleStrokeElements(),this.syncStrokeInteractionListeners(),this.hideStaleElements()}injectToolbarButton(){var i;let e=this.target.containerEl.querySelector(".canvas-controls");if(!e)return;if(this.syncCanvasHistoryButtonListeners(e),(i=this.toolbarGroupEl)!=null&&i.isConnected&&this.toolbarGroupEl.parentElement===e){this.ensureToolbarControlsAboveCaptureLayer(e),this.syncToolbarButton();return}this.removeToolbarButton(),this.ensureToolbarControlsAboveCaptureLayer(e);let t=activeDocument.createElement("div");t.classList.add("canvas-control-group","mod-raised","draw-in-canvas-control-group");let n=activeDocument.createElement("div");n.classList.add("canvas-control-item","draw-in-canvas-control-item","draw-in-canvas-select-control-item"),n.setAttribute("aria-label","Select canvas items (1)"),n.setAttribute("data-tooltip-position","left"),n.setAttribute("role","button"),n.setAttribute("aria-keyshortcuts","1"),n.tabIndex=0,(0,I.setIcon)(n,"mouse-pointer-2");let o=activeDocument.createElement("div");o.classList.add("canvas-control-item","draw-in-canvas-control-item","draw-in-canvas-pencil-control-item"),o.setAttribute("aria-label","Toggle drawing mode. Long press or press the down arrow for stroke color"),o.setAttribute("data-tooltip-position","left"),o.setAttribute("role","button"),o.setAttribute("aria-haspopup","dialog"),o.setAttribute("aria-expanded","false"),o.tabIndex=0,(0,I.setIcon)(o,"pencil"),t.append(n,o),e.insertBefore(t,Td(e)),this.toolbarGroupEl=t,this.selectButtonEl=n,this.toolbarButtonEl=o,this.toolbarDisposers.push(this.addListener(n,"pointerdown",this.handleSelectToolbarPointerDown),this.addListener(n,"keydown",this.handleSelectToolbarKeyDown),this.addListener(o,"pointerdown",this.handleToolbarPointerDown),this.addListener(o,"pointerup",this.handleToolbarPointerUp),this.addListener(o,"pointercancel",this.handleToolbarPointerCancel),this.addListener(o,"keydown",this.handleToolbarKeyDown)),this.syncToolbarButton(),this.hideStaleElements()}removeToolbarButton(){var e;this.closeBrushPopovers(),this.clearToolbarPressState(),this.restoreToolbarControlsZIndex();for(let t of this.toolbarDisposers.splice(0))t();(e=this.toolbarGroupEl)==null||e.remove(),this.toolbarGroupEl=null,this.toolbarButtonEl=null,this.selectButtonEl=null}ensureToolbarControlsAboveCaptureLayer(e){this.toolbarControlsEl&&this.toolbarControlsEl!==e&&this.restoreToolbarControlsZIndex(),this.toolbarControlsEl||(this.toolbarControlsEl=e,this.toolbarControlsOriginalZIndex=e.style.zIndex);let t=Number.parseInt(window.getComputedStyle(e).zIndex,10);(!Number.isFinite(t)||t<=_s)&&(e.style.zIndex=Uc.toString())}restoreToolbarControlsZIndex(){var e;this.toolbarControlsEl&&(this.toolbarControlsEl.style.zIndex=(e=this.toolbarControlsOriginalZIndex)!=null?e:"",this.toolbarControlsEl=null,this.toolbarControlsOriginalZIndex=null)}syncToolbarButton(){var t,n;if(!this.toolbarButtonEl)return;let e=this.isDrawingEnabled();(t=this.selectButtonEl)==null||t.classList.toggle("is-active",!e),(n=this.selectButtonEl)==null||n.setAttribute("aria-pressed",(!e).toString()),this.toolbarButtonEl.classList.toggle("is-active",e),this.toolbarButtonEl.setAttribute("aria-pressed",e.toString()),this.toolbarButtonEl.setCssProps({"--draw-in-canvas-current-color":this.settings.strokeColor}),this.syncColorPaletteExpandedState(),this.syncStrokeSettingsPaletteExpandedState()}syncBrushControlsMountState(){if(!tn(this.getStrokeControlsState())){this.removeBrushControls();return}this.mountBrushControls()}getStrokeControlsState(){return{isDrawingEnabled:this.isDrawingEnabled(),selectedStrokeCount:this.selectedStrokeIds.size}}getBrushControlsTarget(){return ai(this.getStrokeControlsState())}mountBrushControls(){var i;if(!tn(this.getStrokeControlsState())){this.removeBrushControls();return}let e=this.findCanvasWrapperEl();if((i=this.brushControlsEl)!=null&&i.isConnected&&this.brushControlsEl.parentElement===e){this.syncBrushControls(),this.hideStaleElements();return}this.removeBrushControls();let t=activeDocument.createElement("div");t.classList.add("draw-in-canvas-brush-controls"),t.setAttribute("role","group");let n=this.createBrushColorButtonEl(),o=this.createBrushSettingsButtonEl();t.append(this.createBrushSizeSliderControlEl(),n,o,this.createBrushOpacitySliderControlEl()),e.appendChild(t),this.brushControlsEl=t,this.syncBrushControls(),this.hideStaleElements()}removeBrushControls(){var e;this.closeBrushPopovers(),this.closeBrushPreview();for(let t of this.brushControlsDisposers.splice(0))t();(e=this.brushControlsEl)==null||e.remove(),this.brushControlsEl=null,this.brushColorButtonEl=null,this.brushSettingsButtonEl=null}createBrushSizeSliderControlEl(){let e=ms("size",rn(this.getBrushControlsTarget()),"draw-in-canvas-brush-size-value",We(y(this.getBrushControlsStyle().width)));return e.classList.add("draw-in-canvas-brush-size-slider"),this.brushControlsDisposers.push(this.addListener(e,"pointerdown",this.handleBrushSliderPointerDown),this.addListener(e,"pointermove",this.handleBrushSliderPointerMove),this.addListener(e,"pointerup",this.handleBrushSliderPointerUp),this.addListener(e,"pointercancel",this.handleBrushSliderPointerUp),this.addListener(e,"keydown",this.handleBrushSliderKeyDown)),e}createBrushColorButtonEl(){var t,n;let e=activeDocument.createElement("button");return e.type="button",e.classList.add("draw-in-canvas-brush-color-button"),e.setAttribute("aria-haspopup","dialog"),e.setAttribute("aria-expanded",((n=(t=this.colorPaletteEl)==null?void 0:t.isConnected)!=null?n:!1).toString()),this.brushColorButtonEl=e,this.brushControlsDisposers.push(this.addListener(e,"pointerdown",this.handleBrushButtonPointerDown),this.addListener(e,"click",this.handleBrushColorButtonClick),this.addListener(e,"keydown",this.handleBrushButtonKeyDown)),e}createBrushSettingsButtonEl(){var t,n;let e=activeDocument.createElement("button");return e.type="button",e.classList.add("draw-in-canvas-brush-settings-button"),e.setAttribute("aria-haspopup","dialog"),e.setAttribute("aria-expanded",((n=(t=this.strokeSettingsPaletteEl)==null?void 0:t.isConnected)!=null?n:!1).toString()),(0,I.setIcon)(e,"sliders-horizontal"),this.brushSettingsButtonEl=e,this.brushControlsDisposers.push(this.addListener(e,"pointerdown",this.handleBrushButtonPointerDown),this.addListener(e,"click",this.handleBrushSettingsButtonClick),this.addListener(e,"keydown",this.handleBrushButtonKeyDown)),e}createBrushOpacitySliderControlEl(){let e=ms("opacity",nn(this.getBrushControlsTarget()),"draw-in-canvas-brush-opacity-value",Ue(f(this.getBrushControlsStyle().opacity)));return e.classList.add("draw-in-canvas-brush-opacity-slider"),this.brushControlsDisposers.push(this.addListener(e,"pointerdown",this.handleBrushSliderPointerDown),this.addListener(e,"pointermove",this.handleBrushSliderPointerMove),this.addListener(e,"pointerup",this.handleBrushSliderPointerUp),this.addListener(e,"pointercancel",this.handleBrushSliderPointerUp),this.addListener(e,"keydown",this.handleBrushSliderKeyDown)),e}syncBrushControls(){if(!this.brushControlsEl)return;let e=this.getBrushControlsTarget(),t=this.getBrushControlsStyle();this.brushControlsEl.setAttribute("aria-label",li(e)),this.brushControlsEl.setCssProps({"--draw-in-canvas-current-color":this.getStrokeColorForTarget(e)}),this.syncColorPaletteExpandedState(),this.syncStrokeSettingsPaletteExpandedState(),this.syncBrushSlider("size",".draw-in-canvas-brush-size-slider",".draw-in-canvas-brush-size-value",y(t.width),We,rn(e)),this.syncBrushSlider("opacity",".draw-in-canvas-brush-opacity-slider",".draw-in-canvas-brush-opacity-value",f(t.opacity),Ue,nn(e))}syncBrushSlider(e,t,n,o,i,s){var h,p;let a=Sr(e),l=i(o),c=(h=this.brushControlsEl)==null?void 0:h.querySelector(t),d=(p=this.brushControlsEl)==null?void 0:p.querySelector(n),u=c==null?void 0:c.querySelector(".draw-in-canvas-brush-slider-label");c&&(c.title=`${s}: ${l}`,c.setCssProps({"--draw-in-canvas-brush-slider-position":bd(e,o)}),c.setAttribute("aria-valuemin",a.min.toString()),c.setAttribute("aria-valuemax",a.max.toString()),c.setAttribute("aria-valuenow",Te(e,o).toString()),c.setAttribute("aria-valuetext",l)),u&&(u.textContent=s),d&&(d.textContent=l)}toggleColorPalette(e="brush"){var t;if((t=this.colorPaletteEl)!=null&&t.isConnected&&this.colorPaletteTarget===e){this.closeColorPalette();return}this.openColorPalette(e)}toggleStrokeSettingsPalette(e="brush"){var t;if((t=this.strokeSettingsPaletteEl)!=null&&t.isConnected&&this.strokeSettingsPaletteTarget===e){this.closeStrokeSettingsPalette();return}this.openStrokeSettingsPalette(e)}openColorPalette(e="brush"){var u,h,p,S,g;if(e==="brush"&&!this.isDrawingEnabled()&&this.enableDrawingMode(),e==="selection"&&this.selectedStrokeIds.size===0)return;(u=this.colorPaletteEl)!=null&&u.isConnected&&this.colorPaletteTarget!==e&&this.closeColorPalette(),this.colorPaletteTarget=e,this.updateCustomColorFromStrokeColor();let t=this.getColorPaletteTriggerEl(e);if(!t){this.colorPaletteTarget="brush";return}if(this.closeStrokeSettingsPalette(),this.colorPaletteTriggerEl=t,(h=this.colorPaletteEl)!=null&&h.isConnected){this.syncColorPaletteSelection(),this.syncColorPaletteTabControls(),this.positionColorPalette(),this.syncColorPaletteExpandedState(),this.syncPopoverOpenBodyClass();return}this.closeColorPalette(),this.colorPaletteTarget=e,this.colorPaletteTriggerEl=t;let n=activeDocument.createElement("div");n.classList.add("draw-in-canvas-color-palette"),n.setAttribute("role","dialog");let o=activeDocument.createElement("span");o.id=w(),o.classList.add("draw-in-canvas-visually-hidden"),o.textContent=e==="selection"?"Selected stroke color":"Stroke color",n.setAttribute("aria-labelledby",o.id),n.appendChild(o);let i={disc:w(),palettes:w()},s=[],a=activeDocument.createElement("div");a.classList.add("draw-in-canvas-color-palette-panels"),a.append(this.createColorDiscPanelEl(i.disc),this.createPresetPalettePanelEl(i.palettes,s)),n.append(this.createColorPaletteHeaderEl(),a,this.createColorPaletteTabsEl(i)),activeDocument.body.appendChild(n),this.colorPaletteEl=n,this.syncPopoverOpenBodyClass(),this.syncColorPaletteExpandedState(),this.colorPaletteDisposers.push(this.addListener(activeDocument,"pointerdown",this.handleBrushPopoverDocumentPointerDown,!0),this.addListener(activeDocument,"keydown",this.handleColorPaletteDocumentKeyDown,!0)),this.syncColorPaletteSelection(),this.syncColorPaletteTabControls(),this.positionColorPalette();let l=this.getColorPaletteStrokeColor(),c=s.find(D=>{var me;return V((me=D.dataset.color)!=null?me:"",l)}),d=this.colorPaletteTab==="palettes"?c!=null?c:s[0]:(g=(S=(p=n.querySelector(".draw-in-canvas-color-wheel-disc-field"))!=null?p:n.querySelector(".draw-in-canvas-color-palette-tab.is-active"))!=null?S:c)!=null?g:s[0];window.requestAnimationFrame(()=>d==null?void 0:d.focus({preventScroll:!0}))}getColorPaletteTriggerEl(e=this.colorPaletteTarget){var t,n;return(t=this.brushColorButtonEl)!=null&&t.isConnected&&this.getBrushControlsTarget()===e?this.brushColorButtonEl:e==="brush"&&((n=this.toolbarButtonEl)!=null&&n.isConnected)?this.toolbarButtonEl:null}getColorPaletteAnchorEl(){var e;return(e=this.brushControlsEl)!=null&&e.isConnected&&this.getBrushControlsTarget()===this.colorPaletteTarget?this.brushControlsEl:this.getColorPaletteTriggerEl()}positionColorPalette(){let e=this.getColorPaletteAnchorEl();!this.colorPaletteEl||!e||this.positionBrushPopover(this.colorPaletteEl,e)}openStrokeSettingsPalette(e="brush"){var s,a;if(e==="brush"&&!this.isDrawingEnabled()&&this.enableDrawingMode(),e==="selection"&&this.selectedStrokeIds.size===0)return;(s=this.strokeSettingsPaletteEl)!=null&&s.isConnected&&this.strokeSettingsPaletteTarget!==e&&this.closeStrokeSettingsPalette(),this.strokeSettingsPaletteTarget=e;let t=this.getStrokeSettingsPaletteTriggerEl(e);if(!t){this.strokeSettingsPaletteTarget="brush";return}if(this.closeColorPalette(),this.strokeSettingsPaletteTriggerEl=t,(a=this.strokeSettingsPaletteEl)!=null&&a.isConnected){this.positionStrokeSettingsPalette(),this.syncStrokeSettingsPaletteControls(),this.syncStrokeSettingsPaletteExpandedState(),this.syncPopoverOpenBodyClass();return}this.closeStrokeSettingsPalette(),this.strokeSettingsPaletteTarget=e,this.strokeSettingsPaletteTriggerEl=t;let n=activeDocument.createElement("div");n.classList.add("draw-in-canvas-stroke-settings-palette"),n.setAttribute("role","dialog");let o=activeDocument.createElement("span");o.id=w(),o.classList.add("draw-in-canvas-visually-hidden"),o.textContent=e==="selection"?"Selected stroke settings":"Stroke and handwriting settings",n.setAttribute("aria-labelledby",o.id),n.appendChild(o),n.appendChild(this.createStrokeSettingsControlEl()),activeDocument.body.appendChild(n),this.strokeSettingsPaletteEl=n,this.syncPopoverOpenBodyClass(),this.positionStrokeSettingsPalette(),this.syncStrokeSettingsPaletteExpandedState(),this.strokeSettingsPaletteDisposers.push(this.addListener(activeDocument,"pointerdown",this.handleBrushPopoverDocumentPointerDown,!0),this.addListener(activeDocument,"keydown",this.handleStrokeSettingsPaletteDocumentKeyDown,!0)),this.syncStrokeSettingsPaletteControls();let i=n.querySelector("input, button");window.requestAnimationFrame(()=>i==null?void 0:i.focus({preventScroll:!0}))}getStrokeSettingsPaletteTriggerEl(e=this.strokeSettingsPaletteTarget){var t;return(t=this.brushSettingsButtonEl)!=null&&t.isConnected&&this.getBrushControlsTarget()===e?this.brushSettingsButtonEl:null}getStrokeSettingsPaletteAnchorEl(){var e;return(e=this.brushControlsEl)!=null&&e.isConnected&&this.getBrushControlsTarget()===this.strokeSettingsPaletteTarget?this.brushControlsEl:this.getStrokeSettingsPaletteTriggerEl()}positionStrokeSettingsPalette(){let e=this.getStrokeSettingsPaletteAnchorEl();!this.strokeSettingsPaletteEl||!e||this.positionBrushPopover(this.strokeSettingsPaletteEl,e)}positionBrushPopover(e,t){var c;let n=t.getBoundingClientRect(),o=e.getBoundingClientRect(),i=8,s=8,a=Math.max(i,Math.min(n.top,window.innerHeight-o.height-i));if((c=this.brushControlsEl)!=null&&c.isConnected&&t===this.brushControlsEl){let d=Math.max(i,Math.min(n.right+s,window.innerWidth-o.width-i));e.setCssStyles({top:`${a}px`,left:`${d}px`,right:"auto"});return}let l=Math.max(i,window.innerWidth-n.left+s);e.setCssStyles({top:`${a}px`,right:`${l}px`,left:"auto"})}closeBrushPopovers(){this.closeColorPalette(),this.closeStrokeSettingsPalette()}closeColorPalette(){var e;this.commitPendingSelectedStrokeRecolor(),this.closeBrushPreview();for(let t of this.colorPaletteDisposers.splice(0))t();(e=this.colorPaletteEl)==null||e.remove(),this.colorPaletteEl=null,this.colorPaletteTriggerEl=null,this.colorPaletteTarget="brush",this.syncPopoverOpenBodyClass(),this.syncColorPaletteExpandedState()}closeStrokeSettingsPalette(){var e;this.commitPendingSelectedStrokeStyleChanges(),this.closeBrushPreview();for(let t of this.strokeSettingsPaletteDisposers.splice(0))t();(e=this.strokeSettingsPaletteEl)==null||e.remove(),this.strokeSettingsPaletteEl=null,this.strokeSettingsPaletteTriggerEl=null,this.strokeSettingsPaletteTarget="brush",this.syncPopoverOpenBodyClass(),this.syncStrokeSettingsPaletteExpandedState()}syncPopoverOpenBodyClass(){var e,t,n,o;activeDocument.body.classList.toggle(Qc,((t=(e=this.colorPaletteEl)==null?void 0:e.isConnected)!=null?t:!1)||((o=(n=this.strokeSettingsPaletteEl)==null?void 0:n.isConnected)!=null?o:!1))}syncColorPaletteExpandedState(){var i,s,a,l,c;let e=(s=(i=this.colorPaletteEl)==null?void 0:i.isConnected)!=null?s:!1,t=e&&this.colorPaletteTarget==="brush",n=this.getBrushControlsTarget(),o=e&&this.colorPaletteTarget===n;(a=this.toolbarButtonEl)==null||a.setAttribute("aria-expanded",t.toString()),(l=this.brushColorButtonEl)==null||l.setAttribute("aria-expanded",o.toString()),(c=this.brushColorButtonEl)==null||c.setAttribute("aria-label",ci(n,o))}syncStrokeSettingsPaletteExpandedState(){var o,i,s,a;let e=(i=(o=this.strokeSettingsPaletteEl)==null?void 0:o.isConnected)!=null?i:!1,t=this.getBrushControlsTarget(),n=e&&this.strokeSettingsPaletteTarget===t;(s=this.brushSettingsButtonEl)==null||s.setAttribute("aria-expanded",n.toString()),(a=this.brushSettingsButtonEl)==null||a.setAttribute("aria-label",di(t,n))}syncColorPaletteSelection(){var n,o,i;let e=(o=(n=this.colorPaletteEl)==null?void 0:n.querySelectorAll(".draw-in-canvas-preset-color-swatch, .draw-in-canvas-history-color-swatch"))!=null?o:[],t=this.getColorPaletteStrokeColor();for(let s of Array.from(e)){let a=V((i=s.dataset.color)!=null?i:"",t);s.classList.toggle("is-selected",a),s.setAttribute("aria-pressed",a.toString())}this.syncCustomColorControls(),this.syncColorWheelControls(),this.syncHslSliderControls(),this.syncColorPaletteHeader()}recordColorHistory(e){this.commitPendingSelectedStrokeRecolor();let t=E(e);if(!t)return;let n=[t,...this.drawingData.colorHistory.filter(i=>!V(i,t))].slice(0,10);(n.length!==this.drawingData.colorHistory.length||n.some((i,s)=>{var a;return!V(i,(a=this.drawingData.colorHistory[s])!=null?a:"")}))&&(this.drawingData.colorHistory=n,this.renderColorHistorySwatches(),this.scheduleSave())}renderColorHistorySwatches(){var t;let e=(t=this.colorPaletteEl)==null?void 0:t.querySelector(".draw-in-canvas-color-history-swatches");e&&this.populateColorHistorySwatches(e)}populateColorHistorySwatches(e){let t=this.drawingData.colorHistory.slice(0,10);if(e.replaceChildren(),e.classList.toggle("is-empty",t.length===0),e.setAttribute("aria-label",t.length===0?"Color history, empty":"Color history"),t.length===0){let n=activeDocument.createElement("span");n.classList.add("draw-in-canvas-color-history-empty"),n.textContent="No colors yet",e.appendChild(n);return}for(let[n,o]of t.entries()){let i=activeDocument.createElement("button");i.type="button",i.classList.add("draw-in-canvas-color-disc-palette-swatch","draw-in-canvas-history-color-swatch"),i.dataset.color=o,i.setAttribute("aria-label",`Use history color ${n+1} ${Z(o)} stroke color`),i.setCssProps({"--draw-in-canvas-swatch-color":o});let s=V(o,this.getColorPaletteStrokeColor());i.classList.toggle("is-selected",s),i.setAttribute("aria-pressed",s.toString()),e.appendChild(i)}}syncStrokeSettingsPaletteControls(){let e=this.strokeSettingsPaletteEl,t=this.getStrokeSettingsPaletteStyle();if(!t)return;let n=e==null?void 0:e.querySelector(".draw-in-canvas-handwriting-toggle-input"),o=e==null?void 0:e.querySelector(".draw-in-canvas-freehand-controls");n&&(n.checked=t.handwriting.enabled),o==null||o.classList.toggle("is-disabled",!t.handwriting.enabled),o==null||o.setAttribute("aria-disabled",(!t.handwriting.enabled).toString()),this.syncPaletteSlider(e,".draw-in-canvas-stroke-width-slider-control",".draw-in-canvas-stroke-width-slider-value",y(t.width),We),this.syncPaletteSlider(e,".draw-in-canvas-stroke-hardness-slider",".draw-in-canvas-stroke-hardness-value",x(t.hardness),Ts),this.syncPaletteSlider(e,".draw-in-canvas-stroke-opacity-slider",".draw-in-canvas-stroke-opacity-value",f(t.opacity),Ue);for(let i of Nn()){let s=vs(t.handwriting,i),a=`[data-freehand-setting="${i}"]`;this.syncPaletteSlider(e,a,`[data-freehand-value="${i}"]`,s,c=>Ss(i,c));let l=e==null?void 0:e.querySelector(a);l&&(l.disabled=!t.handwriting.enabled)}}syncPaletteSlider(e,t,n,o,i){let s=e==null?void 0:e.querySelector(t),a=e==null?void 0:e.querySelector(n);s&&(s.value=o.toString()),a&&(a.textContent=i(o))}syncCustomColorControls(){var a,l,c,d,u;this.updateCustomColorFromStrokeColor();let e=this.getColorPaletteStrokeColor(),t=(a=this.colorPaletteEl)==null?void 0:a.querySelector(".draw-in-canvas-custom-color-hex-input"),n=(l=this.colorPaletteEl)==null?void 0:l.querySelector(".draw-in-canvas-native-color-picker"),o=(c=this.colorPaletteEl)==null?void 0:c.querySelector(".draw-in-canvas-color-picker-swatch"),i=(u=(d=this.colorPaletteEl)==null?void 0:d.querySelectorAll(".draw-in-canvas-custom-color-shade"))!=null?u:[];t&&activeDocument.activeElement!==t&&(t.value=Z(this.customColorHex),W(t,!0)),n&&(n.value=this.customColorHex),o&&(o.setCssProps({"--draw-in-canvas-swatch-color":this.customColorHex}),o.classList.toggle("is-selected",V(this.customColorHex,e)));let s=Qd(this.customColorHex);for(let h of Array.from(i)){let p=Number(h.dataset.shadeIndex),S=s[p];if(!S)continue;h.dataset.color=S.value,h.setAttribute("aria-label",`Use ${S.name.toLowerCase()} ${Z(S.value)} stroke color`),h.setCssProps({"--draw-in-canvas-custom-shade-color":S.value});let g=V(S.value,e);h.classList.toggle("is-selected",g),h.setAttribute("aria-pressed",g.toString())}}syncColorWheelControls(){var u,h;let e=(u=this.colorPaletteEl)==null?void 0:u.querySelector(".draw-in-canvas-color-disc-picker");if(!e)return;let t=nr({h:this.colorWheelHsv.h,s:1,v:1}),n=(h=E(this.customColorHex))!=null?h:nr(this.colorWheelHsv),o=Ud(this.colorWheelHsv.h),i=Math.round(this.colorWheelHsv.h),s=Math.round(this.colorWheelHsv.s*100),a=Math.round(this.colorWheelHsv.v*100),l=e.querySelector('[data-color-wheel-control="hue"]'),c=e.querySelector('[data-color-wheel-control="disc"]'),d=Kd(this.colorWheelHsv,c);e.setCssProps({"--draw-in-canvas-color-wheel-hue-color":t,"--draw-in-canvas-color-wheel-selected-color":n,"--draw-in-canvas-color-wheel-hue-x":`${o.x}%`,"--draw-in-canvas-color-wheel-hue-y":`${o.y}%`,"--draw-in-canvas-color-wheel-disc-x":`${d.x}%`,"--draw-in-canvas-color-wheel-disc-y":`${d.y}%`}),l&&(l.setAttribute("aria-valuenow",i.toString()),l.setAttribute("aria-valuetext",`${i}\xB0 hue`)),c&&(c.setAttribute("aria-valuenow",s.toString()),c.setAttribute("aria-valuetext",`Saturation ${s}%, brightness ${a}%`))}syncHslSliderControls(){var o,i,s,a;this.syncColorValueModeControls();let e=(i=(o=this.colorPaletteEl)==null?void 0:o.querySelectorAll(".draw-in-canvas-hsl-slider"))!=null?i:[],t=this.getColorValueInputText(),n=(s=this.colorPaletteEl)==null?void 0:s.querySelector(".draw-in-canvas-hsl-value-input");n&&(activeDocument.activeElement!==n||n.readOnly)&&(n.value=t,we(n,!0));for(let l of Array.from(e)){let c=Xn(this.colorValueMode,l.dataset.colorValueSlider);if(!c)continue;let d=this.getColorValueSliderValue(c.id),u=qn(this.colorValueMode,c.id,d),h=(a=l.closest(".draw-in-canvas-hsl-slider-control"))==null?void 0:a.querySelector("output");l.value=d.toString(),l.setAttribute("aria-valuenow",d.toString()),l.setAttribute("aria-valuetext",ys(this.colorValueMode,c.id,d)),l.setCssProps(this.getColorValueSliderCssProps(c.id)),h&&(h.textContent=u)}}syncColorValueModeControls(){var s,a,l,c,d;let e=fs(this.colorValueMode),t=(a=(s=this.colorPaletteEl)==null?void 0:s.querySelectorAll("[data-color-value-mode]"))!=null?a:[],n=(l=this.colorPaletteEl)==null?void 0:l.querySelector(".draw-in-canvas-hsl-value-input"),o=(d=(c=this.colorPaletteEl)==null?void 0:c.querySelectorAll(".draw-in-canvas-hsl-slider"))!=null?d:[],i=Yn(this.colorValueMode);for(let u of Array.from(t)){let h=u.dataset.colorValueMode===this.colorValueMode;u.classList.toggle("is-active",h),u.setAttribute("aria-pressed",h.toString())}n&&(n.placeholder=e.placeholder,n.maxLength=e.maxLength,n.setAttribute("aria-label",e.ariaLabel));for(let[u,h]of Array.from(o).entries()){let p=i[u];if(!p)continue;h.min=p.min.toString(),h.max=p.max.toString(),h.step=p.step.toString(),h.dataset.colorValueSlider=p.id,h.setAttribute("aria-label",p.ariaLabel);let S=h.closest(".draw-in-canvas-hsl-slider-control"),g=S==null?void 0:S.querySelector("label"),D=S==null?void 0:S.querySelector("output");g&&(g.textContent=p.label),D&&D.setAttribute("data-color-value-value",p.id)}}getColorValueInputText(){switch(this.colorValueMode){case"hsl":return Jn(this.colorValueHsl);case"lab":return $s(this.colorValueLab);default:return Bd(this.colorValueMode,this.customColorHex,this.colorWheelHsv.h)}}getColorValueSliderValue(e){switch(this.colorValueMode){case"hsl":{let t=Ne(e);return t?ue(t,this.colorValueHsl):he}case"lab":return Od(e,this.colorValueLab);default:return Rd(this.colorValueMode,e,this.customColorHex,this.colorWheelHsv.h)}}getColorValueSliderCssProps(e){switch(this.colorValueMode){case"hsl":return Dd(e,this.colorValueHsl);case"lab":return Ad(e,this.colorValueLab);default:return Ld(this.colorValueMode,e,this.customColorHex,this.colorWheelHsv.h)}}syncColorValueHslFromHex(e,t=this.colorWheelHsv.h){let n=E(e);!n||n===this.preserveHslColorValueForHex||(this.colorValueHsl=ce(n,t),this.preserveHslColorValueForHex=null)}syncColorValueLabFromHex(e){let t=E(e);!t||t===this.preserveLabColorValueForHex||(this.colorValueLab=le(t),this.preserveLabColorValueForHex=null)}syncColorPaletteHeader(){var i,s,a,l,c,d;let e=(s=(i=this.colorPaletteEl)==null?void 0:i.querySelectorAll(".draw-in-canvas-current-color-preview"))!=null?s:[],t=(l=(a=this.colorPaletteEl)==null?void 0:a.querySelectorAll(".draw-in-canvas-current-color-label"))!=null?l:[],n=this.getColorPaletteStrokeColor(),o=(d=(c=E(n))==null?void 0:c.toUpperCase())!=null?d:n;for(let u of Array.from(e))u.setCssProps({"--draw-in-canvas-current-color":n});for(let u of Array.from(t)){if(u.instanceOf(HTMLInputElement)){(activeDocument.activeElement!==u||u.readOnly)&&(u.value=o,W(u,!0));continue}u.textContent=o}}syncColorPaletteTabControls(){let e=this.colorPaletteEl;if(!e)return;let t=e.querySelectorAll(".draw-in-canvas-color-palette-tab"),n=e.querySelectorAll(".draw-in-canvas-color-palette-panel");for(let o of Array.from(t)){let s=rr(o.dataset.colorPaletteTab)===this.colorPaletteTab;o.classList.toggle("is-active",s),o.tabIndex=s?0:-1,o.setAttribute("aria-selected",s.toString())}for(let o of Array.from(n)){let s=rr(o.dataset.colorPalettePanel)===this.colorPaletteTab;o.hidden=!s,o.classList.toggle("is-active",s),o.setAttribute("aria-hidden",(!s).toString())}}updateCustomColorFromStrokeColor(){let e=E(this.getColorPaletteStrokeColor());e&&(this.customColorHex=e,this.colorWheelHsv=pt(e,this.colorWheelHsv.h),this.syncColorValueHslFromHex(e,this.colorWheelHsv.h),this.syncColorValueLabFromHex(e))}setColorWheelHsv(e){let t=Zs(e),n=nr(t);this.colorWheelHsv=t,this.customColorHex=n,this.syncColorValueHslFromHex(n,t.h),this.syncColorValueLabFromHex(n),this.setStrokeColor(n),this.syncColorWheelControls(),this.syncHslSliderControls(),this.syncColorPaletteHeader()}setHslColor(e){let t=Zn(e);this.setColorValueHex(hr(t),t.h,void 0,t)}setColorValueSliderValue(e,t){if(this.colorValueMode==="hsl"){let o=Ne(e);if(!o)return;let i=Ws(this.colorValueHsl,o,t);this.setColorValueHex(hr(i),i.h,void 0,i);return}if(this.colorValueMode==="lab"){let o=Gs(this.colorValueLab,e,t);if(!o)return;this.setColorValueHex(Re(o),this.colorWheelHsv.h,o);return}let n=Nd(this.colorValueMode,e,t,this.customColorHex,this.colorWheelHsv.h);n&&this.setColorValueHex(n.hexColor,n.fallbackHue,n.labColor,n.hslColor)}setColorValueHex(e,t=this.colorWheelHsv.h,n,o){let i=E(e);i&&(o?(this.colorValueHsl=Zn(o),this.preserveHslColorValueForHex=i):(this.preserveHslColorValueForHex=null,this.syncColorValueHslFromHex(i,t)),n?(this.colorValueLab=Js(n),this.preserveLabColorValueForHex=i):(this.preserveLabColorValueForHex=null,this.syncColorValueLabFromHex(i)),this.colorWheelHsv=pt(i,t),this.customColorHex=i,this.setStrokeColor(i),this.syncColorWheelControls(),this.syncHslSliderControls(),this.syncColorPaletteHeader())}setStrokeColor(e){let t=E(e);if(t&&(this.customColorHex=t,this.colorWheelHsv=pt(t,this.colorWheelHsv.h),this.syncColorValueHslFromHex(t,this.colorWheelHsv.h),this.syncColorValueLabFromHex(t)),this.colorPaletteTarget==="selection"&&this.selectedStrokeIds.size>0&&this.recolorSelectedStrokes(e),V(e,this.settings.strokeColor)){this.syncColorWheelControls(),this.syncHslSliderControls(),this.syncColorPaletteHeader(),this.syncBrushControls();return}this.settings={...this.settings,strokeColor:e},this.requestSetStrokeColor(e),this.syncToolbarButton(),this.syncColorPaletteSelection(),this.syncBrushControls()}getColorPaletteStrokeColor(){return this.getStrokeColorForTarget(this.colorPaletteTarget)}getStrokeColorForTarget(e){var t;return e==="selection"?(t=this.getSelectedStrokePaletteColor())!=null?t:this.settings.strokeColor:this.settings.strokeColor}getSelectedStrokePaletteColor(){for(let e of this.selectedStrokeIds){let t=this.findStroke(e);if(t)return t.color}return null}getBrushControlsStyle(){var e;return(e=this.getStrokeSettingsStyleForTarget(this.getBrushControlsTarget()))!=null?e:this.getDefaultStrokeStyle()}getStrokeSettingsPaletteStyle(){return this.getStrokeSettingsStyleForTarget(this.strokeSettingsPaletteTarget)}getStrokeSettingsStyleForTarget(e){return e==="selection"?this.getSelectedStrokeStyle():this.getDefaultStrokeStyle()}getDefaultStrokeStyle(){return{width:this.settings.strokeWidth,hardness:this.settings.strokeHardness,opacity:this.settings.strokeOpacity,handwriting:He(this.settings)}}getSelectedStrokeStyle(){for(let e of this.selectedStrokeIds){let t=this.findStroke(e);if(t)return at(t)}return null}recolorSelectedStrokes(e){var i,s;let t=Array.from(this.selectedStrokeIds);if(t.length===0)return;let n=new Map;for(let a of(i=this.pendingSelectedStrokeRecolorChanges)!=null?i:[])n.set(a.strokeId,{...a});let o=!1;for(let a of t){let l=this.findStroke(a);if(!l)continue;let c=n.get(a);!c&&V(l.color,e)||(n.set(a,{strokeId:a,previousColor:(s=c==null?void 0:c.previousColor)!=null?s:l.color,nextColor:e}),V(l.color,e)||(l.color=e,this.updateStrokePaintAttributes(l),o=!0))}this.pendingSelectedStrokeRecolorChanges=Array.from(n.values()).filter(a=>!V(a.previousColor,a.nextColor)),!(!o&&this.pendingSelectedStrokeRecolorChanges.length===0)&&(this.syncBrushControls(),this.scheduleSave())}commitPendingSelectedStrokeRecolor(){var t,n;let e=(n=(t=this.pendingSelectedStrokeRecolorChanges)==null?void 0:t.filter(o=>!V(o.previousColor,o.nextColor)))!=null?n:[];this.pendingSelectedStrokeRecolorChanges=null,e.length>0&&(this.pushHistory({type:"recolor-strokes",changes:e}),this.scheduleSave()),this.commitPendingSelectedStrokeStyleChanges()}commitPendingSelectedStrokeStyleChanges(){var t,n;let e=(n=(t=this.pendingSelectedStrokeStyleChanges)==null?void 0:t.filter(o=>!be(o.previousStyle,o.nextStyle)))!=null?n:[];this.pendingSelectedStrokeStyleChanges=null,e.length!==0&&(this.pushHistory({type:"restyle-strokes",changes:e}),this.scheduleSave())}createColorPaletteHeaderEl(){var a,l;let e=activeDocument.createElement("div");e.classList.add("draw-in-canvas-color-palette-header");let t=activeDocument.createElement("div");t.classList.add("draw-in-canvas-color-palette-title"),t.textContent="Colors";let n=activeDocument.createElement("div");n.classList.add("draw-in-canvas-current-color"),n.setAttribute("aria-label","Current stroke color");let o=activeDocument.createElement("span");o.classList.add("draw-in-canvas-current-color-preview"),o.setCssProps({"--draw-in-canvas-current-color":this.settings.strokeColor});let i=activeDocument.createElement("input");i.classList.add("draw-in-canvas-current-color-label"),i.type="text",i.inputMode="text",i.maxLength=7,i.pattern="#?[0-9A-Fa-f]{6}",i.spellcheck=!1,i.readOnly=!0,i.value=(l=(a=E(this.settings.strokeColor))==null?void 0:a.toUpperCase())!=null?l:this.settings.strokeColor,i.title="Click to copy; double-click to edit.",i.setAttribute("aria-label","Current hex stroke color. Click to copy; double-click or press enter to edit."),W(i,!0),this.colorPaletteDisposers.push(this.addListener(i,"pointerdown",this.handleCurrentColorHexPointerDown),this.addListener(i,"click",this.handleCurrentColorHexClick),this.addListener(i,"dblclick",this.handleCurrentColorHexDoubleClick),this.addListener(i,"focus",this.handleCurrentColorHexFocus),this.addListener(i,"input",this.handleCurrentColorHexInput),this.addListener(i,"change",this.handleCurrentColorHexChange),this.addListener(i,"blur",this.handleCurrentColorHexChange),this.addListener(i,"keydown",this.handleCurrentColorHexKeyDown));let s=activeDocument.createElement("div");return s.classList.add("draw-in-canvas-current-color-values"),s.append(i,this.createColorValueInputEl()),n.append(o,s),e.append(t,n),e}createColorValueInputEl(){let e=fs(this.colorValueMode),t=activeDocument.createElement("input");return t.classList.add("draw-in-canvas-hsl-value-input","draw-in-canvas-current-color-value-input"),t.type="text",t.inputMode="text",t.maxLength=e.maxLength,t.placeholder=e.placeholder,t.spellcheck=!1,t.readOnly=!0,t.value=this.getColorValueInputText(),t.title="Click to copy; double-click to edit.",t.setAttribute("aria-label",e.ariaLabel),we(t,!0),this.colorPaletteDisposers.push(this.addListener(t,"pointerdown",this.handleCurrentColorHslPointerDown),this.addListener(t,"click",this.handleCurrentColorHslClick),this.addListener(t,"dblclick",this.handleCurrentColorHslDoubleClick),this.addListener(t,"focus",this.handleCurrentColorHslFocus),this.addListener(t,"input",this.handleCurrentColorHslInput),this.addListener(t,"change",this.handleCurrentColorHslChange),this.addListener(t,"blur",this.handleCurrentColorHslChange),this.addListener(t,"keydown",this.handleCurrentColorHslKeyDown)),t}createColorDiscPanelEl(e){let t=activeDocument.createElement("div");t.id=e,t.classList.add("draw-in-canvas-color-palette-panel","draw-in-canvas-color-disc-panel"),t.dataset.colorPalettePanel="disc",t.setAttribute("role","tabpanel");let n=activeDocument.createElement("div");n.classList.add("draw-in-canvas-color-disc-picker"),n.setAttribute("aria-label","Color disc");let o=activeDocument.createElement("div");o.classList.add("draw-in-canvas-color-wheel-hue-control"),o.dataset.colorWheelControl="hue",o.tabIndex=0,o.setAttribute("role","slider"),o.setAttribute("aria-label","Stroke color hue"),o.setAttribute("aria-valuemin","0"),o.setAttribute("aria-valuemax","360");let i=activeDocument.createElement("span");i.classList.add("draw-in-canvas-color-wheel-thumb","draw-in-canvas-color-wheel-hue-thumb"),i.setAttribute("aria-hidden","true"),o.appendChild(i);let s=activeDocument.createElement("div");s.classList.add("draw-in-canvas-color-wheel-disc-field"),s.dataset.colorWheelControl="disc",s.tabIndex=0,s.setAttribute("role","slider"),s.setAttribute("aria-label","Stroke color saturation and brightness"),s.setAttribute("aria-valuemin","0"),s.setAttribute("aria-valuemax","100");let a=activeDocument.createElement("span");a.classList.add("draw-in-canvas-color-wheel-thumb","draw-in-canvas-color-wheel-disc-thumb"),a.setAttribute("aria-hidden","true"),s.appendChild(a);for(let l of[o,s])this.colorPaletteDisposers.push(this.addListener(l,"pointerdown",this.handleColorWheelPointerDown),this.addListener(l,"pointermove",this.handleColorWheelPointerMove),this.addListener(l,"pointerup",this.handleColorWheelPointerUp),this.addListener(l,"pointercancel",this.handleColorWheelPointerUp),this.addListener(l,"keydown",this.handleColorWheelKeyDown));return n.append(o,s),t.append(n,this.createCustomColorShadesEl("Selected color shades"),this.createHslSliderControlsEl(),this.createColorHistorySectionEl(),this.createColorDiscPaletteEl()),t}createHslSliderControlsEl(){let e=activeDocument.createElement("div");e.classList.add("draw-in-canvas-color-disc-palette","draw-in-canvas-hsl-controls");let t=activeDocument.createElement("div");t.classList.add("draw-in-canvas-hsl-header");let n=activeDocument.createElement("div");n.classList.add("draw-in-canvas-color-mode-segmented"),n.setAttribute("role","group"),n.setAttribute("aria-label","Color model");for(let i of Vs){let s=activeDocument.createElement("button"),a=i.id===this.colorValueMode;s.classList.add("draw-in-canvas-color-mode-button"),s.type="button",s.dataset.colorValueMode=i.id,s.textContent=i.label,s.title=`Show ${i.label} color controls`,s.setAttribute("aria-pressed",a.toString()),s.classList.toggle("is-active",a),n.appendChild(s),this.colorPaletteDisposers.push(this.addListener(s,"click",this.handleColorValueModeClick))}t.appendChild(n);let o=activeDocument.createElement("div");o.classList.add("draw-in-canvas-hsl-slider-list");for(let i of Yn(this.colorValueMode))o.appendChild(this.createHslSliderControlEl(i));return e.append(t,o),e}createHslSliderControlEl(e){let t=w(),n=this.getColorValueSliderValue(e.id),o=activeDocument.createElement("input");o.id=t,o.classList.add("draw-in-canvas-stroke-width-slider","draw-in-canvas-hsl-slider"),o.type="range",o.min=e.min.toString(),o.max=e.max.toString(),o.step=e.step.toString(),o.value=n.toString(),o.dataset.colorValueSlider=e.id,o.setAttribute("aria-label",e.ariaLabel),o.setAttribute("aria-valuetext",ys(this.colorValueMode,e.id,n)),o.setCssProps(this.getColorValueSliderCssProps(e.id)),this.colorPaletteDisposers.push(this.addListener(o,"pointerdown",this.handleHslSliderPointerDown),this.addListener(o,"keydown",this.handleStrokeWidthSliderKeyDown),this.addListener(o,"input",this.handleHslSliderInput),this.addListener(o,"change",this.handleHslSliderChange));let i=ht(t,e.label,"draw-in-canvas-stroke-width-value",qn(this.colorValueMode,e.id,n),o),s=i.querySelector("output");return i.classList.add("draw-in-canvas-hsl-slider-control"),s==null||s.classList.add("draw-in-canvas-hsl-slider-value"),s==null||s.setAttribute("data-color-value-value",e.id),i}createColorHistorySectionEl(){let e=activeDocument.createElement("div");e.classList.add("draw-in-canvas-color-disc-palette","draw-in-canvas-color-history");let t=activeDocument.createElement("div");t.classList.add("draw-in-canvas-color-disc-palette-title"),t.textContent="History";let n=activeDocument.createElement("div");return n.classList.add("draw-in-canvas-color-disc-palette-swatches","draw-in-canvas-color-history-swatches"),this.colorPaletteDisposers.push(this.addListener(n,"pointerdown",this.handleHistoryColorSwatchPointerDown),this.addListener(n,"click",this.handleHistoryColorSwatchClick)),this.populateColorHistorySwatches(n),e.append(t,n),e}createColorDiscPaletteEl(){let e=activeDocument.createElement("div");e.classList.add("draw-in-canvas-color-disc-palette");let t=activeDocument.createElement("div");t.classList.add("draw-in-canvas-color-disc-palette-title"),t.textContent="Palette";let n=activeDocument.createElement("div");n.classList.add("draw-in-canvas-color-disc-palette-swatches"),n.setAttribute("aria-label","Preset stroke colors");for(let o of ds){let i=activeDocument.createElement("button");i.type="button",i.classList.add("draw-in-canvas-color-disc-palette-swatch","draw-in-canvas-preset-color-swatch"),i.dataset.color=o.value,i.setAttribute("aria-label",`Use ${o.name.toLowerCase()} stroke color`),i.setCssProps({"--draw-in-canvas-swatch-color":o.value}),this.colorPaletteDisposers.push(this.addListener(i,"pointerdown",this.handleColorSwatchPointerDown),this.addListener(i,"click",this.handlePresetColorSwatchClick)),n.appendChild(i)}return e.append(t,n),e}createPresetPalettePanelEl(e,t){let n=activeDocument.createElement("div");n.id=e,n.classList.add("draw-in-canvas-color-palette-panel","draw-in-canvas-presets-panel"),n.dataset.colorPalettePanel="palettes",n.setAttribute("role","tabpanel");let o=activeDocument.createElement("div");o.classList.add("draw-in-canvas-color-palette-swatch-grid"),o.setAttribute("aria-label","Preset stroke colors");for(let i of ds){let s=activeDocument.createElement("button");s.type="button",s.classList.add("draw-in-canvas-color-swatch","draw-in-canvas-preset-color-swatch"),s.dataset.color=i.value,s.setAttribute("aria-label",`Use ${i.name.toLowerCase()} stroke color`),s.setCssProps({"--draw-in-canvas-swatch-color":i.value}),this.colorPaletteDisposers.push(this.addListener(s,"pointerdown",this.handleColorSwatchPointerDown),this.addListener(s,"click",this.handlePresetColorSwatchClick)),o.appendChild(s),t.push(s)}return n.append(o,this.createNativeColorPickerEl(),this.createCustomColorControlEl()),n}createColorPaletteTabsEl(e){let t=activeDocument.createElement("div");t.classList.add("draw-in-canvas-color-palette-tabs"),t.setAttribute("role","tablist"),t.setAttribute("aria-label","Color picker views");for(let n of U){let o=activeDocument.createElement("button");o.type="button",o.classList.add("draw-in-canvas-color-palette-tab"),o.dataset.colorPaletteTab=n.id,o.setAttribute("role","tab"),o.setAttribute("aria-controls",e[n.id]),o.textContent=n.label,this.colorPaletteDisposers.push(this.addListener(o,"click",this.handleColorPaletteTabClick),this.addListener(o,"keydown",this.handleColorPaletteTabKeyDown)),t.appendChild(o)}return t}createNativeColorPickerEl(){let e=activeDocument.createElement("label");e.classList.add("draw-in-canvas-color-swatch","draw-in-canvas-color-picker-swatch"),e.setAttribute("title","Choose custom color"),e.setCssProps({"--draw-in-canvas-swatch-color":this.customColorHex});let t=activeDocument.createElement("input");t.classList.add("draw-in-canvas-native-color-picker"),t.type="color",t.value=this.customColorHex,t.setAttribute("aria-label","Choose custom stroke color");let n=activeDocument.createElement("span");n.classList.add("draw-in-canvas-color-picker-icon"),(0,I.setIcon)(n,"palette");let o=activeDocument.createElement("span");return o.classList.add("draw-in-canvas-visually-hidden"),o.textContent="Choose custom stroke color",this.colorPaletteDisposers.push(this.addListener(t,"input",this.handleNativeColorPickerInput),this.addListener(t,"change",this.handleNativeColorPickerInput)),e.append(t,n,o),e}createCustomColorShadesEl(e){let t=activeDocument.createElement("div");t.classList.add("draw-in-canvas-custom-color-shades"),t.setAttribute("aria-label",e);for(let n=0;n<Xc;n++){let o=activeDocument.createElement("button");o.type="button",o.classList.add("draw-in-canvas-custom-color-shade"),o.dataset.shadeIndex=n.toString(),this.colorPaletteDisposers.push(this.addListener(o,"pointerdown",this.handleColorSwatchPointerDown),this.addListener(o,"click",this.handleCustomColorShadeClick)),t.appendChild(o)}return t}createCustomColorControlEl(){let e=activeDocument.createElement("div");e.classList.add("draw-in-canvas-custom-color-control");let t=activeDocument.createElement("div");t.classList.add("draw-in-canvas-custom-color-field");let n=w(),o=activeDocument.createElement("label");o.htmlFor=n,o.textContent="Hex color";let i=activeDocument.createElement("input");i.id=n,i.classList.add("draw-in-canvas-custom-color-hex-input"),i.type="text",i.inputMode="text",i.maxLength=7,i.pattern="#?[0-9A-Fa-f]{6}",i.placeholder="#123456",i.spellcheck=!1,i.value=Z(this.customColorHex),i.setAttribute("aria-label","Custom hex stroke color"),t.append(o,i);let s=this.createCustomColorShadesEl("Custom color shades");return this.colorPaletteDisposers.push(this.addListener(i,"pointerdown",this.handleCustomColorHexPointerDown),this.addListener(i,"focus",this.handleCustomColorHexFocus),this.addListener(i,"click",this.handleCustomColorHexClick),this.addListener(i,"input",this.handleCustomColorHexInput),this.addListener(i,"change",this.handleCustomColorHexChange),this.addListener(i,"blur",this.handleCustomColorHexChange),this.addListener(i,"keydown",this.handleCustomColorHexKeyDown)),e.append(t,s),e}createStrokeSettingsControlEl(){let e=activeDocument.createElement("div");e.classList.add("draw-in-canvas-stroke-settings-control");let t=activeDocument.createElement("div");return t.classList.add("draw-in-canvas-palette-section"),t.appendChild(this.createPaletteSectionTitleEl("Stroke")),t.append(this.createStrokeWidthSliderControlEl(),this.createStrokeHardnessSliderControlEl(),this.createStrokeOpacitySliderControlEl()),e.appendChild(t),e.appendChild(this.createHandwritingControlsEl()),e}createStrokeWidthSliderControlEl(){var i,s,a;let e=w(),t=y((s=(i=this.getStrokeSettingsPaletteStyle())==null?void 0:i.width)!=null?s:this.settings.strokeWidth),n=activeDocument.createElement("input");n.id=e,n.classList.add("draw-in-canvas-stroke-width-slider","draw-in-canvas-stroke-width-slider-control"),n.type="range",n.min=1 .toString(),n.max=32 .toString(),n.step=1 .toString(),n.value=t.toString(),n.setAttribute("aria-label","Stroke width"),this.strokeSettingsPaletteDisposers.push(this.addListener(n,"keydown",this.handleStrokeWidthSliderKeyDown),this.addListener(n,"input",this.handleStrokeWidthSliderInput));let o=ht(e,"Width","draw-in-canvas-stroke-width-value",We(t),n);return(a=o.querySelector("output"))==null||a.classList.add("draw-in-canvas-stroke-width-slider-value"),o}createStrokeHardnessSliderControlEl(){var i,s,a;let e=w(),t=x((s=(i=this.getStrokeSettingsPaletteStyle())==null?void 0:i.hardness)!=null?s:this.settings.strokeHardness),n=activeDocument.createElement("input");n.id=e,n.classList.add("draw-in-canvas-stroke-width-slider","draw-in-canvas-stroke-hardness-slider"),n.type="range",n.min=0 .toString(),n.max=100 .toString(),n.step=1 .toString(),n.value=t.toString(),n.setAttribute("aria-label","Stroke hardness"),this.strokeSettingsPaletteDisposers.push(this.addListener(n,"keydown",this.handleStrokeWidthSliderKeyDown),this.addListener(n,"input",this.handleStrokeHardnessSliderInput));let o=ht(e,"Hardness","draw-in-canvas-stroke-width-value",Ts(t),n);return(a=o.querySelector("output"))==null||a.classList.add("draw-in-canvas-stroke-hardness-value"),o}createStrokeOpacitySliderControlEl(){var i,s,a;let e=w(),t=f((s=(i=this.getStrokeSettingsPaletteStyle())==null?void 0:i.opacity)!=null?s:this.settings.strokeOpacity),n=activeDocument.createElement("input");n.id=e,n.classList.add("draw-in-canvas-stroke-width-slider","draw-in-canvas-stroke-opacity-slider"),n.type="range",n.min=1 .toString(),n.max=100 .toString(),n.step=1 .toString(),n.value=t.toString(),n.setAttribute("aria-label","Stroke opacity"),this.strokeSettingsPaletteDisposers.push(this.addListener(n,"keydown",this.handleStrokeWidthSliderKeyDown),this.addListener(n,"input",this.handleStrokeOpacitySliderInput));let o=ht(e,"Opacity","draw-in-canvas-stroke-width-value",Ue(t),n);return(a=o.querySelector("output"))==null||a.classList.add("draw-in-canvas-stroke-opacity-value"),o}createHandwritingControlsEl(){var u,h;let e=activeDocument.createElement("div"),t=w(),n=(h=(u=this.getStrokeSettingsPaletteStyle())==null?void 0:u.handwriting)!=null?h:He(this.settings);e.classList.add("draw-in-canvas-palette-section","draw-in-canvas-freehand-controls"),e.setAttribute("aria-labelledby",t);let o=activeDocument.createElement("div");o.classList.add("draw-in-canvas-palette-section-header");let i=this.createPaletteSectionTitleEl("Handwriting");i.id=t;let s=activeDocument.createElement("div");s.classList.add("draw-in-canvas-palette-section-actions");let a=activeDocument.createElement("button");a.type="button",a.classList.add("draw-in-canvas-palette-reset-button"),a.textContent="Reset",a.setAttribute("aria-label","Reset handwriting controls to defaults");let l=activeDocument.createElement("label");l.classList.add("draw-in-canvas-handwriting-toggle");let c=activeDocument.createElement("input");c.classList.add("draw-in-canvas-handwriting-toggle-input"),c.type="checkbox",c.checked=n.enabled,c.setAttribute("aria-label","Enable handwritten strokes");let d=activeDocument.createElement("span");d.textContent="On",l.append(c,d),s.append(a,l),o.append(i,s),e.appendChild(o);for(let p of Nn())e.appendChild(this.createFreehandSliderControlEl(p));return this.strokeSettingsPaletteDisposers.push(this.addListener(c,"change",this.handleHandwritingToggleChange),this.addListener(a,"click",this.handleFreehandResetClick)),e}createPaletteSectionTitleEl(e){let t=activeDocument.createElement("div");return t.classList.add("draw-in-canvas-palette-section-title"),t.textContent=e,t}createFreehandSliderControlEl(e){var c,d,u;let t=H[e],n=w(),o=(d=(c=this.getStrokeSettingsPaletteStyle())==null?void 0:c.handwriting)!=null?d:He(this.settings),i=vs(o,e),s=activeDocument.createElement("input");s.id=n,s.classList.add("draw-in-canvas-stroke-width-slider","draw-in-canvas-freehand-slider"),s.type="range",s.min=t.min.toString(),s.max=t.max.toString(),s.step=t.step.toString(),s.value=i.toString(),s.dataset.freehandSetting=e,s.setAttribute("aria-label",t.ariaLabel),s.disabled=!o.enabled,this.strokeSettingsPaletteDisposers.push(this.addListener(s,"input",this.handleFreehandSliderInput));let l=ht(n,t.label,"draw-in-canvas-stroke-width-value",Ss(e,i),s);return l.classList.add("draw-in-canvas-freehand-control"),(u=l.querySelector("output"))==null||u.setAttribute("data-freehand-value",e),l}setStrokeWidth(e){let t=y(e);t!==y(this.settings.strokeWidth)&&(this.settings={...this.settings,strokeWidth:t},this.requestSetStrokeWidth(t),this.syncBrushControls(),this.syncStrokeSettingsPaletteControls())}setStrokeHardness(e){let t=x(e);t!==x(this.settings.strokeHardness)&&(this.settings={...this.settings,strokeHardness:t},this.requestSetStrokeHardness(t),this.syncStrokeSettingsPaletteControls())}setStrokeOpacity(e){let t=f(e);t!==f(this.settings.strokeOpacity)&&(this.settings={...this.settings,strokeOpacity:t},this.requestSetStrokeOpacity(t),this.syncBrushControls(),this.syncStrokeSettingsPaletteControls())}setFreehandSliderValue(e,t){let n=k(e,t);n!==k(e,this.settings[e])&&(this.requestSetFreehandSliderValue(e,n),this.settings={...this.settings,[e]:n},this.syncStrokeSettingsPaletteControls())}resetFreehandSliderValues(){let e=this.settings;for(let t of Nn()){let n=H[t].defaultValue;k(t,e[t])!==n&&(e={...e,[t]:n},this.requestSetFreehandSliderValue(t,n))}this.settings=e,this.syncStrokeSettingsPaletteControls()}setBeautifulStrokes(e){e!==this.settings.beautifulStrokes&&(this.settings={...this.settings,beautifulStrokes:e},this.requestSetBeautifulStrokes(e),this.syncStrokeSettingsPaletteControls())}setSelectedStrokeWidth(e){let t=y(e);this.updateSelectedStrokeStyles(n=>({...n,width:t}))}setSelectedStrokeHardness(e){let t=x(e);this.updateSelectedStrokeStyles(n=>({...n,hardness:t}))}setSelectedStrokeOpacity(e){let t=f(e);this.updateSelectedStrokeStyles(n=>({...n,opacity:t}))}setSelectedStrokeFreehandSliderValue(e,t){let n=k(e,t);this.updateSelectedStrokeStyles(o=>({...o,handwriting:Ed(o.handwriting,e,n)}))}resetSelectedStrokeFreehandSliderValues(){this.updateSelectedStrokeStyles(e=>({...e,handwriting:kd(e.handwriting.enabled)}))}setSelectedStrokeBeautifulStrokes(e){this.updateSelectedStrokeStyles(t=>({...t,handwriting:{...t.handwriting,enabled:e}}))}updateSelectedStrokeStyles(e){var i;let t=this.getSelectedStrokeIds();if(t.length===0){this.closeStrokeSettingsPalette();return}let n=new Map;for(let s of(i=this.pendingSelectedStrokeStyleChanges)!=null?i:[])n.set(s.strokeId,{strokeId:s.strokeId,previousStyle:q(s.previousStyle),nextStyle:q(s.nextStyle)});let o=!1;for(let s of t){let a=this.findStroke(s);if(!a)continue;let l=at(a),c=q(e(l)),d=n.get(s),u=d?q(d.previousStyle):l;be(l,c)||(be(u,c)?n.delete(s):n.set(s,{strokeId:s,previousStyle:u,nextStyle:q(c)}),this.applyStrokeStyle(a,c)&&(o=!0))}this.pendingSelectedStrokeStyleChanges=Array.from(n.values()).filter(s=>!be(s.previousStyle,s.nextStyle)),!(!o&&this.pendingSelectedStrokeStyleChanges.length===0)&&(this.syncStrokeSettingsPaletteControls(),this.syncBrushControls(),this.renderSelectionBox(),this.positionStrokeSettingsPalette(),this.scheduleSave())}applyStrokeStyle(e,t){var a;let n=q(t);if(be(at(e),n))return!1;let o=(a=this.strokeBoundsById.get(e.id))!=null?a:this.setStrokeBounds(e),i=e.width;this.strokePathCache.invalidateStroke(e.id),si(e,n);let s=this.setStrokeBounds(e);return s?this.strokeSpatialIndex.updateBounds(e.id,A(s,e.width)):this.strokeSpatialIndex.remove(e.id),this.invalidateRasterTilesForStrokeGeometries([{bounds:o,strokeWidth:i},{bounds:s,strokeWidth:e.width}]),this.updateStrokeElement(e),!0}openBrushPreview(e,t,n){this.closeBrushPreview(),this.brushPreviewState={pointerId:e.pointerId,triggerEl:t,setting:n,x:e.clientX,y:e.clientY},Ge(t,e.pointerId),this.brushPreviewDisposers.push(this.addListener(activeDocument,"pointermove",this.handleBrushPreviewPointerMove,!0),this.addListener(activeDocument,"pointerup",this.handleBrushPreviewPointerUp,!0),this.addListener(activeDocument,"pointercancel",this.handleBrushPreviewPointerUp,!0),this.addListener(window,"blur",this.handleBrushPreviewWindowBlur)),this.positionBrushPreview(e.clientX,e.clientY),this.updateBrushPreview(n)}closeBrushPreview(){var t;for(let n of this.brushPreviewDisposers.splice(0))n();let e=this.brushPreviewState;e!=null&&e.triggerEl.hasPointerCapture(e.pointerId)&&e.triggerEl.releasePointerCapture(e.pointerId),(t=this.brushPreviewEl)==null||t.remove(),this.brushPreviewEl=null,this.brushPreviewState=null}positionBrushPreview(e,t){let n=this.ensureBrushPreviewEl(),o=this.brushPreviewState;o&&(o.x=e,o.y=t);let i=n.getBoundingClientRect(),s=8,a=18,l=i.width||96,c=i.height||56,d=Math.max(s,Math.min(e+a,window.innerWidth-l-s)),u=Math.max(s,Math.min(t-c/2,window.innerHeight-c-s));n.setCssStyles({left:`${d}px`,top:`${u}px`})}updateBrushPreview(e=(n=>(n=(t=>(t=this.brushPreviewState)==null?void 0:t.setting)())!=null?n:"size")()){let o=this.brushPreviewState;if(!o)return;let i=this.getBrushControlsTarget(),s=this.getBrushControlsStyle(),a=y(s.width),l=f(s.opacity),c=this.ensureBrushPreviewEl(),d=c.querySelector(".draw-in-canvas-brush-preview-value"),u=c.querySelector(".draw-in-canvas-brush-preview-detail");c.dataset.brushPreviewSetting=e,c.setCssProps({"--draw-in-canvas-brush-preview-size":`${Math.max(4,a)}px`,"--draw-in-canvas-brush-preview-color":this.getStrokeColorForTarget(i),"--draw-in-canvas-brush-preview-opacity":Ye(l)}),d&&(d.textContent=e==="opacity"?Ue(l):We(a)),u&&(u.textContent=e==="opacity"?`${We(a)} ${i==="selection"?"stroke":"brush"}`:`${Ue(l)} opacity`),this.positionBrushPreview(o.x,o.y)}ensureBrushPreviewEl(){var a;if((a=this.brushPreviewEl)!=null&&a.isConnected)return this.brushPreviewEl;let e=activeDocument.createElement("div");e.classList.add("draw-in-canvas-brush-preview"),e.setAttribute("aria-hidden","true");let t=activeDocument.createElement("span");t.classList.add("draw-in-canvas-brush-preview-sample");let n=activeDocument.createElement("span");n.classList.add("draw-in-canvas-brush-preview-dot"),t.appendChild(n);let o=activeDocument.createElement("span");o.classList.add("draw-in-canvas-brush-preview-text");let i=activeDocument.createElement("span");i.classList.add("draw-in-canvas-brush-preview-value");let s=activeDocument.createElement("span");return s.classList.add("draw-in-canvas-brush-preview-detail"),o.append(i,s),e.append(t,o),activeDocument.body.appendChild(e),this.brushPreviewEl=e,e}clearToolbarPressState(){var t;let e=this.toolbarPressState;e&&(window.clearTimeout(e.timeoutId),(t=this.toolbarButtonEl)!=null&&t.hasPointerCapture(e.pointerId)&&this.toolbarButtonEl.releasePointerCapture(e.pointerId),this.toolbarPressState=null)}syncCanvasHistoryButtonListeners(e){let t=gs(e,"Undo"),n=gs(e,"Redo");if(this.undoButtonEl===t&&this.redoButtonEl===n){this.syncCanvasUndoRedoButtons();return}this.removeCanvasHistoryButtonListeners(),this.undoButtonEl=t,this.redoButtonEl=n,t&&this.canvasHistoryButtonDisposers.push(this.addListener(t,"pointerdown",this.handleCanvasUndoPointerDown),this.addListener(t,"click",this.handleCanvasUndoClick),this.addListener(t,"keydown",this.handleCanvasUndoKeyDown)),n&&this.canvasHistoryButtonDisposers.push(this.addListener(n,"pointerdown",this.handleCanvasRedoPointerDown),this.addListener(n,"click",this.handleCanvasRedoClick),this.addListener(n,"keydown",this.handleCanvasRedoKeyDown)),this.syncCanvasUndoRedoButtons()}removeCanvasHistoryButtonListeners(){for(let e of this.canvasHistoryButtonDisposers.splice(0))e();this.undoButtonEl=null,this.suppressNextNativeUndoClick=!1,this.suppressNextNativeRedoClick=!1,this.redoButtonEl=null}syncCanvasUndoRedoButtons(){var e,t;(e=this.undoButtonEl)==null||e.classList.toggle("draw-in-canvas-can-undo",this.undoStack.length>0),(t=this.redoButtonEl)==null||t.classList.toggle("draw-in-canvas-can-redo",this.redoStack.length>0)}syncStrokeInteractionListeners(){let e=this.findCanvasWrapperEl();if(this.strokeInteractionEl!==e&&(this.removeStrokeInteractionListeners(),this.strokeInteractionEl=e,this.strokeInteractionDisposers.push(this.addListener(e,"pointerdown",this.handleStrokePointerDown,!0),this.addListener(e,"pointermove",this.handleStrokePointerMove,!0),this.addListener(e,"pointerup",this.handleStrokePointerUp,!0),this.addListener(e,"pointercancel",this.handleStrokePointerUp,!0),this.addListener(e,"pointerleave",this.handleStrokePointerLeave,!0),this.addListener(window,"keydown",this.handleWindowKeyDown,!0),this.addListener(activeDocument,"keydown",this.handleDocumentKeyDown,!0),this.addListener(activeDocument,"keyup",this.handleDocumentKeyUp,!0),this.addListener(window,"blur",this.handleWindowBlur),this.addListener(window,"resize",this.handleWindowResize)),typeof ResizeObserver!="undefined")){let t=new ResizeObserver(()=>this.handleWindowResize());t.observe(e),this.strokeInteractionDisposers.push(()=>t.disconnect())}}removeStrokeInteractionListeners(){this.setInteractionCursor(null);for(let e of this.strokeInteractionDisposers.splice(0))e();this.isSpaceKeyPressed=!1,this.strokeInteractionEl=null}observeCanvasDom(){this.mutationObserver=new MutationObserver(e=>this.scheduleCanvasDomSync(ni(e))),this.syncCanvasDomObserver()}syncCanvasDomObserver(){if(!this.mutationObserver)return;let e=this.settings.allowTinyCanvasElements;this.isObservingCanvasAttributes!==e&&(this.mutationObserver.disconnect(),this.mutationObserver.observe(this.target.containerEl,e?{attributes:!0,attributeFilter:["class","style"],attributeOldValue:!0,childList:!0,subtree:!0}:{childList:!0,subtree:!0}),this.isObservingCanvasAttributes=e)}scheduleCanvasDomSync(e=K){this.pendingDomSyncFlags=this.pendingDomSyncFlags?st(this.pendingDomSyncFlags,e):e,this.domSyncFrameId===null&&(this.domSyncFrameId=window.requestAnimationFrame(()=>{var o;let t=(o=this.pendingDomSyncFlags)!=null?o:K;this.pendingDomSyncFlags=null,this.domSyncFrameId=null,this.mountRenderLayer(),this.injectToolbarButton();let n=this.syncTinyCanvasFeaturesForDomChange(t);this.selectedStrokeIds.size>0&&!this.dragState&&!this.resizeState&&!this.nativeSelectionDragState&&(n?this.renderSelectionBox():this.syncSelectedStrokeScaleMenuPosition()),this.syncBrushControlsMountState()}))}syncTinyCanvasFeatureState(){let e=this.syncTinyControlScale();return this.nativeCanvasLimits.setEnabled(this.settings.allowTinyCanvasElements),this.nativeElementScaleControls.setEnabled(this.settings.allowTinyCanvasElements),e}syncTinyCanvasFeaturesForDomChange(e){if(this.settings.allowTinyCanvasElements){let t=e.syncTinyCanvasControls?this.syncTinyControlScale():!1;return this.nativeCanvasLimits.setEnabled(!0),e.syncNativeElementControls&&this.nativeElementScaleControls.syncForCanvasDomChange(),t}return e.syncNativeElementControls&&this.nativeElementScaleControls.syncForCanvasDomChange(),!1}renderStrokes(){this.svgEl&&(this.renderVisibleStrokeElements(),this.renderSelectionBox())}syncRenderViewportObserver(e){this.renderViewportObservedEl!==e&&(this.disconnectRenderViewportObserver(),this.renderViewportObserver=new MutationObserver(()=>this.scheduleRenderViewportSync()),this.renderViewportObserver.observe(e,{attributes:!0,attributeFilter:["style"]}),this.renderViewportObservedEl=e)}disconnectRenderViewportObserver(){var e;(e=this.renderViewportObserver)==null||e.disconnect(),this.renderViewportObserver=null,this.renderViewportObservedEl=null}scheduleRenderViewportSync(){this.renderViewportFrameId===null&&(this.renderViewportFrameId=window.requestAnimationFrame(()=>{this.renderViewportFrameId=null,this.syncVisibleStrokeElements(),this.selectedStrokeIds.size>0&&!this.dragState&&!this.resizeState&&!this.nativeSelectionDragState&&this.renderSelectionBox()}))}renderVisibleStrokeElements(){if(!this.svgEl)return;let e=this.getTiledRasterRenderRequest();if(e){this.renderTiledRasterStrokeElements(e);return}this.renderVisibleStrokeIds(this.getVisibleStrokeIds())}renderVisibleStrokeIds(e){if(!this.svgEl)return;this.clearRenderedStrokeElements();let t=this.createStrokeRenderFragment(e);this.svgEl.insertBefore(t.fragment,this.getStrokeRenderAnchor()),this.renderedStrokeIds=[...e],this.renderedSelectedStrokeIds=this.getVisibleSelectedStrokeIds(e),this.renderedRasterViewportKey=t.rasterViewportKey}renderTiledRasterStrokeElements(e){this.svgEl&&(this.clearRenderedStrokeElements(),this.svgEl.insertBefore(this.createStrokeTiledRasterRenderFragment(e),this.getStrokeRenderAnchor()),this.renderedStrokeIds=[],this.renderedSelectedStrokeIds=[],this.renderedRasterViewportKey=e.rasterViewportKey)}syncVisibleStrokeElements(){if(!this.svgEl)return;let e=this.getTiledRasterRenderRequest();if(e){this.areRenderedTiledRasterElementsCurrent(e)||this.renderTiledRasterStrokeElements(e);return}let t=this.getVisibleStrokeIds();this.areRenderedStrokeIdsCurrent(t)||this.renderVisibleStrokeIds(t)}areRenderedTiledRasterElementsCurrent(e){return this.strokeRasterTileEls.length===e.entries.length&&this.strokeRasterTileEls.length>0&&this.strokeGroupById.size===0&&this.strokeBatchEls.length===0&&this.strokeRasterEls.length===0&&this.strokeRasterTileEls.every(t=>t.isConnected)&&this.renderedRasterViewportKey===e.rasterViewportKey}areRenderedStrokeIdsCurrent(e){let t=this.getVisibleSelectedStrokeIds(e),n=this.getCurrentRasterViewportKey();return ot(this.renderedStrokeIds,e)&&ot(this.renderedSelectedStrokeIds,t)&&t.every(o=>!!this.findStrokeGroupEl(o))&&this.strokeBatchEls.every(o=>o.isConnected)&&this.strokeRasterEls.every(o=>o.isConnected)&&this.strokeRasterTileEls.every(o=>o.isConnected)&&this.renderedRasterViewportKey===n}getVisibleSelectedStrokeIds(e){return e.filter(t=>this.selectedStrokeIds.has(t))}getCurrentRasterViewportKey(){let e=this.getRenderViewportBounds();return this.strokeRasterTileEls.length>0?this.getTiledRasterViewportKey(e):this.strokeRasterEls.length>0?this.getRasterViewportKey(e):""}clearRenderedStrokeElements(){this.cancelPendingRasterRenders();for(let e of this.strokeGroupById.values())e.remove();this.strokeGroupById.clear();for(let e of this.strokeBatchEls.splice(0))e.remove();for(let e of this.strokeRasterEls.splice(0))e.remove();for(let e of this.strokeRasterTileEls.splice(0))e.remove();this.renderedStrokeIds=[],this.renderedSelectedStrokeIds=[],this.renderedRasterViewportKey=""}cancelPendingRasterRenders(){this.rasterRenderGeneration++;for(let e of this.rasterRenderFrameIds)window.cancelAnimationFrame(e);this.rasterRenderFrameIds.clear()}requestRasterRenderFrame(e){let t=window.requestAnimationFrame(n=>{this.rasterRenderFrameIds.delete(t),e(n)});this.rasterRenderFrameIds.add(t)}cancelPendingRasterTileRenders(){this.rasterTileRenderGeneration++,this.rasterTileSetupFrameId!==null&&(window.cancelAnimationFrame(this.rasterTileSetupFrameId),this.rasterTileSetupFrameId=null),this.rasterTileRenderFrameId!==null&&(window.cancelAnimationFrame(this.rasterTileRenderFrameId),this.rasterTileRenderFrameId=null);for(let e of this.rasterTileSetupJobs.splice(0))this.cancelRasterTileSetupJob(e);for(let e of this.rasterTileRenderJobs.splice(0))e.context&&this.resetRasterCanvasContext(e.context),e.record.isRendering=!1}clearRasterTileCache(){this.cancelPendingRasterTileRenders();for(let e of this.rasterTileCache.values())e.foreignObjectEl.remove();this.rasterTileCache.clear(),this.strokeRasterTileEls.length=0}invalidateRasterTilesForStroke(e){this.invalidateRasterTilesForStrokeGeometries([{bounds:this.getStrokeBounds(e),strokeWidth:e.width}])}invalidateRasterTilesForStrokeGeometries(e){if(this.rasterTileCache.size===0)return;let t=e.map(n=>n.bounds?A(n.bounds,n.strokeWidth):null).filter(Xe);if(t.length!==0){if(this.hasPendingRasterTileWork()){this.clearRasterTileCache();return}for(let[n,o]of Array.from(this.rasterTileCache.entries()))Xi(o.bounds,t)&&(o.foreignObjectEl.remove(),this.rasterTileCache.delete(n),ku(this.strokeRasterTileEls,o.foreignObjectEl))}}hasPendingRasterTileWork(){return this.rasterTileSetupJobs.length>0||this.rasterTileRenderJobs.length>0||this.rasterTileSetupFrameId!==null||this.rasterTileRenderFrameId!==null}scheduleRasterTileSetupQueue(){this.rasterTileSetupFrameId!==null||this.rasterTileSetupJobs.length===0||(this.rasterTileSetupFrameId=window.requestAnimationFrame(()=>this.processRasterTileSetupQueue()))}processRasterTileSetupQueue(){this.rasterTileSetupFrameId=null;let e=performance.now(),t=0;for(;this.rasterTileSetupJobs.length>0;){let n=this.rasterTileSetupJobs[0];if(!n)break;if(n.renderGeneration!==this.rasterTileRenderGeneration){this.cancelRasterTileSetupJob(n),this.rasterTileSetupJobs.shift();continue}for(;n.strokeIndex<this.drawingData.strokes.length;){let o=this.drawingData.strokes[n.strokeIndex++];if(o&&this.addStrokeToRasterTileSetupJob(n,o),t++,t>=64&&(t=0,performance.now()-e>=7.5)){this.scheduleRasterTileSetupQueue();return}}this.finishRasterTileSetupJob(n),this.rasterTileSetupJobs.shift()}this.scheduleRasterTileSetupQueue()}addStrokeToRasterTileSetupJob(e,t){var s;if(t.id===((s=this.activeStroke)==null?void 0:s.id))return;let n=this.getStrokeBounds(t);if(!n)return;let o=A(n,t.width);if(!zn(e.rasterBounds,o)||!ze(o,e.screenScale,!1))return;let i=wn(o,e.tileWorldSize);for(let a=Math.max(i.minTileY,e.range.minTileY);a<=Math.min(i.maxTileY,e.range.maxTileY);a++){let l=(a-e.range.minTileY)*e.columnCount;for(let c=Math.max(i.minTileX,e.range.minTileX);c<=Math.min(i.maxTileX,e.range.maxTileX);c++){let d=l+c-e.range.minTileX,u=e.entries[d],h=e.records[d];(u==null?void 0:u.tileX)===c&&u.tileY===a&&(h==null?void 0:h.setupGeneration)===e.renderGeneration&&h.isSettingUp&&!h.isSetupComplete&&zn(o,u.bounds)&&h.strokeIds.push(t.id)}}}finishRasterTileSetupJob(e){for(let t of new Set(e.records))if(t.setupGeneration===e.renderGeneration){if(t.isSettingUp=!1,t.setupGeneration=null,e.renderGeneration!==this.rasterTileRenderGeneration||this.rasterTileCache.get(t.key)!==t){t.strokeIds=[],t.strokeCount=0,t.foreignObjectEl.dataset.strokeCount="0";continue}t.isSetupComplete=!0,t.strokeCount=t.strokeIds.length,t.foreignObjectEl.dataset.strokeCount=t.strokeCount.toString(),t.isRendered=t.strokeIds.length===0,this.enqueueRasterTileRender(t)}}cancelRasterTileSetupJob(e){for(let t of new Set(e.records))t.setupGeneration===e.renderGeneration&&(t.isSettingUp=!1,t.setupGeneration=null,t.isSetupComplete||(t.strokeIds=[],t.strokeCount=0,t.foreignObjectEl.dataset.strokeCount="0",t.isRendered=!1))}scheduleRasterTileRenderQueue(){this.rasterTileRenderFrameId!==null||this.rasterTileRenderJobs.length===0||(this.rasterTileRenderFrameId=window.requestAnimationFrame(()=>this.processRasterTileRenderQueue()))}processRasterTileRenderQueue(){this.rasterTileRenderFrameId=null;let e=performance.now(),t=0;for(;this.rasterTileRenderJobs.length>0;){let n=this.rasterTileRenderJobs[0];if(!n)break;if(n.renderGeneration!==this.rasterTileRenderGeneration){this.finishRasterTileRenderJob(n),this.rasterTileRenderJobs.shift();continue}if(!n.context&&(n.context=this.prepareRasterCanvasContext(n.record.canvasEl,n.record.bounds,n.rasterScale),!n.context)){n.record.isRendering=!1,this.rasterTileRenderJobs.shift();continue}for(;n.strokeIndex<n.record.strokeIds.length;){let o=n.record.strokeIds[n.strokeIndex++];if(o){let i=this.findStroke(o);i&&(n.currentFilter=this.drawStrokeOnPreparedRasterCanvas(n.context,i,n.currentFilter))}if(t++,t>=bn&&(t=0,performance.now()-e>=kn)){this.scheduleRasterTileRenderQueue();return}}this.finishRasterTileRenderJob(n),this.rasterTileRenderJobs.shift()}this.scheduleRasterTileRenderQueue()}finishRasterTileRenderJob(e){e.context&&(this.resetRasterCanvasContext(e.context),e.context=null),e.record.isRendering=!1,e.record.isRendered=e.renderGeneration===this.rasterTileRenderGeneration}getVisibleStrokeIds(){var i;let e=this.getRenderViewportBounds();if(!e)return this.drawingData.strokes.map(s=>s.id).filter(s=>{var a;return s!==((a=this.activeStroke)==null?void 0:a.id)});let t=ct(e),n=[],o=this.getCanvasScreenScale();for(let s of this.strokeSpatialIndex.queryBounds(t,"ascending")){if(s===((i=this.activeStroke)==null?void 0:i.id))continue;let a=this.findStroke(s),l=a?this.getStrokeBounds(a):null;!a||!l||ze(A(l,a.width),o,this.selectedStrokeIds.has(s))&&n.push(s)}return n}shouldRenderStroke(e){var i;if(e.id===((i=this.activeStroke)==null?void 0:i.id))return!1;let t=this.getRenderViewportBounds();if(!t)return!0;let n=this.getStrokeBounds(e);if(!n)return!1;let o=A(n,e.width);return ze(o,this.getCanvasScreenScale(),this.selectedStrokeIds.has(e.id))?Mi([e.id],ct(t),()=>o).length>0:!1}getRenderViewportBounds(){var n;let e=this.target.view.canvas,t=(n=e==null?void 0:e.getViewportBBox)==null?void 0:n.call(e);return t&&Mu(t)?t:this.getSvgScreenViewportBounds()}getSvgScreenViewportBounds(){if(!this.svgEl)return null;let e=this.svgEl.getScreenCTM();if(!e)return null;let t=this.svgEl.getBoundingClientRect(),n=e.inverse(),o=this.svgEl.createSVGPoint(),i=[{x:t.left,y:t.top},{x:t.right,y:t.top},{x:t.left,y:t.bottom},{x:t.right,y:t.bottom}].map(s=>(o.x=s.x,o.y=s.y,o.matrixTransform(n)));return{minX:Math.min(...i.map(s=>s.x)),minY:Math.min(...i.map(s=>s.y)),maxX:Math.max(...i.map(s=>s.x)),maxY:Math.max(...i.map(s=>s.y))}}getStrokeRenderAnchor(){var e,t,n;return(e=this.activeStrokeGroupEl)!=null&&e.isConnected?this.activeStrokeGroupEl:(t=this.selectionBoxEl)!=null&&t.isConnected?this.selectionBoxEl:(n=this.selectionHandleEls.find(o=>o.isConnected))!=null?n:null}getTiledRasterRenderRequest(){let e=this.getRenderViewportBounds();if(!e||this.selectedStrokeIds.size>0||!this.hasTiledRasterStrokeCount(e))return null;let t=this.getRasterTileEntriesForViewport(e);return t.length===0?null:{viewportBounds:e,entries:t,rasterViewportKey:this.getTiledRasterViewportKeyForEntries(t)}}hasTiledRasterStrokeCount(e){let t=this.getCanvasScreenScale(),n=Ke(e,t),o=0;return this.strokeSpatialIndex.forEachBounds(n,i=>{var l;if(i===((l=this.activeStroke)==null?void 0:l.id))return;let s=this.findStroke(i),a=s?this.getStrokeBounds(s):null;if(!(!s||!a))return ze(A(a,s.width),t,!1)&&o++,o<=1e4}),Gi(o,!1)}createStrokeRenderFragment(e){let t=this.getRenderViewportBounds(),n=t?this.shouldRasterizeVisibleStrokes(e):!1;if(t&&n)return{fragment:this.createStrokeRasterRenderFragment(e,t),rasterViewportKey:this.getRasterViewportKey(t)};let o=Bi(e.map(i=>{let s=this.findStroke(i);return{id:i,batchKey:s?this.getStrokeRenderBatchKey(s):null,isSelected:this.selectedStrokeIds.has(i)}}));return{fragment:this.createStrokeSvgRenderFragment(o),rasterViewportKey:""}}shouldRasterizeVisibleStrokes(e){let t=0,n=null,o=!1,i=()=>o?(t++,n=null,o=!1,jt(t)):!1;for(let s of e){let a=this.findStroke(s),l=a&&!this.selectedStrokeIds.has(s)?this.getStrokeRenderBatchKey(a):null;if(l===null){if(i()||(t++,jt(t)))return!0;continue}if(n!==null&&n!==l&&i())return!0;n=l,o=!0}return i()||jt(t)}createStrokeSvgRenderFragment(e){let t=activeDocument.createDocumentFragment();for(let n of e){if(n.type==="single"){let s=this.findStroke(n.strokeId);s&&t.appendChild(this.createStrokeGroupEl(s));continue}let o=n.strokeIds.map(s=>this.findStroke(s)).filter(Xe);if(o.length===0)continue;let i=o[0];if(o.length===1&&i){t.appendChild(this.createStrokeGroupEl(i));continue}t.appendChild(this.createStrokeBatchPathEl(o))}return t}createStrokeTiledRasterRenderFragment(e){let t=activeDocument.createDocumentFragment(),n=new Set,o=[],i=[];for(let s of e.entries){let a=this.rasterTileCache.get(s.key);a||(a=this.createRasterTileCacheRecord(s,[],!1),this.rasterTileCache.set(a.key,a)),!a.isSetupComplete&&!a.isSettingUp&&i.push(a),o.push(a),a.lastUsedAt=++this.rasterTileUsageCounter,n.add(a.key),t.appendChild(a.foreignObjectEl),this.strokeRasterTileEls.push(a.foreignObjectEl)}return this.setupRasterTileRecords(e,o,i),this.evictRasterTileCache(n),t}setupRasterTileRecords(e,t,n){if(n.length!==0){if(n.length===e.entries.length){this.enqueueRasterTileSetup(e,t);return}for(let o of n)this.completeRasterTileSetupRecord(o,this.getRasterTileStrokeIds(o.bounds))}}enqueueRasterTileSetup(e,t){let n=e.entries[0];if(!n)return;let o=n.bounds.maxX-n.bounds.minX;if(!Number.isFinite(o)||o<=0)return;let i=Yi(e.entries),s=i.maxTileX-i.minTileX+1;if(!(!Number.isFinite(s)||s<=0)){for(let a of t)a.isSetupComplete||a.isSettingUp||(a.strokeIds=[],a.strokeCount=0,a.foreignObjectEl.dataset.strokeCount="0",a.isRendered=!1,a.isRendering=!1,a.isSettingUp=!0,a.setupGeneration=this.rasterTileRenderGeneration);this.rasterTileSetupJobs.push({entries:[...e.entries],records:[...t],range:i,columnCount:s,tileWorldSize:o,rasterBounds:Ke(e.viewportBounds,this.getCanvasScreenScale()),screenScale:this.getCanvasScreenScale(),strokeIndex:0,renderGeneration:this.rasterTileRenderGeneration}),this.scheduleRasterTileSetupQueue()}}getRasterTileEntriesForViewport(e){let t=this.getCanvasScreenScale(),n=this.getRasterBitmapScale(),o=Wi(t),i=Ke(e,t);return Ui(i,o,n)}getTiledRasterViewportKey(e){return e?this.getTiledRasterViewportKeyForEntries(this.getRasterTileEntriesForViewport(e)):""}getTiledRasterViewportKeyForEntries(e){let t=e[0],n=e[e.length-1];return!t||!n?"":["tiles",t.key,n.key,e.length].join("|")}createRasterTileCacheRecord(e,t,n=!0){let o=activeDocument.createElementNS(G,"foreignObject"),i=activeDocument.createElementNS(ts,"canvas"),s=Math.max(1,e.bounds.maxX-e.bounds.minX),a=Math.max(1,e.bounds.maxY-e.bounds.minY),l=this.getRasterBitmapScale(),c=[...t];return o.classList.add("draw-in-canvas-stroke-raster","draw-in-canvas-stroke-raster-tile"),o.setAttribute("x",v(e.bounds.minX).toString()),o.setAttribute("y",v(e.bounds.minY).toString()),o.setAttribute("width",v(s).toString()),o.setAttribute("height",v(a).toString()),o.setAttribute("pointer-events","none"),o.dataset.tileKey=e.key,o.dataset.strokeCount=c.length.toString(),i.classList.add("draw-in-canvas-stroke-raster-canvas"),i.width=Math.max(1,Math.ceil(s*l)),i.height=Math.max(1,Math.ceil(a*l)),i.setAttribute("aria-hidden","true"),o.appendChild(i),{key:e.key,foreignObjectEl:o,canvasEl:i,bounds:e.bounds,strokeIds:c,strokeCount:c.length,lastUsedAt:++this.rasterTileUsageCounter,isSetupComplete:n,isSettingUp:!1,setupGeneration:null,isRendered:n&&c.length===0,isRendering:!1}}completeRasterTileSetupRecord(e,t){e.strokeIds=[...t],e.strokeCount=e.strokeIds.length,e.foreignObjectEl.dataset.strokeCount=e.strokeCount.toString(),e.isSetupComplete=!0,e.isSettingUp=!1,e.setupGeneration=null,e.isRendered=e.strokeIds.length===0,this.enqueueRasterTileRender(e)}getRasterTileStrokeIds(e){let t=this.getCanvasScreenScale();return this.strokeSpatialIndex.queryBounds(e,"ascending").filter(n=>{var s;if(n===((s=this.activeStroke)==null?void 0:s.id))return!1;let o=this.findStroke(n),i=o?this.getStrokeBounds(o):null;return!!(o&&i&&ze(A(i,o.width),t,!1))})}enqueueRasterTileRender(e){!e.isSetupComplete||e.isRendered||e.isRendering||e.strokeIds.length===0||(e.isRendering=!0,this.rasterTileRenderJobs.push({record:e,strokeIndex:0,currentFilter:"none",rasterScale:this.getRasterBitmapScale(),renderGeneration:this.rasterTileRenderGeneration,context:null}),this.scheduleRasterTileRenderQueue())}evictRasterTileCache(e){if(this.rasterTileCache.size<=512)return;let t=Array.from(this.rasterTileCache.values()).filter(n=>!e.has(n.key)&&!n.isRendering&&!n.isSettingUp).sort((n,o)=>n.lastUsedAt-o.lastUsedAt);for(let n of t){if(this.rasterTileCache.size<=512)break;n.foreignObjectEl.remove(),this.rasterTileCache.delete(n.key)}}createStrokeRasterRenderFragment(e,t){let n=activeDocument.createDocumentFragment(),o=Ke(t,this.getCanvasScreenScale()),i=Vi(e.map(s=>({id:s,isSelected:this.selectedStrokeIds.has(s)})));for(let s of i){if(s.type==="single"){let l=this.findStroke(s.strokeId);l&&n.appendChild(this.createStrokeGroupEl(l));continue}let a=s.strokeIds.map(l=>this.findStroke(l)).filter(Xe);a.length>0&&n.appendChild(this.createStrokeRasterForeignObjectEl(a,o))}return n}getRasterViewportKey(e){if(!e)return"";let t=Ke(e,this.getCanvasScreenScale());return[v(t.minX),v(t.minY),v(t.maxX),v(t.maxY),v(this.getRasterBitmapScale())].join("|")}createStrokeRasterForeignObjectEl(e,t){let n=activeDocument.createElementNS(G,"foreignObject"),o=activeDocument.createElementNS(ts,"canvas"),i=Math.max(1,t.maxX-t.minX),s=Math.max(1,t.maxY-t.minY),a=this.getRasterBitmapScale();n.classList.add("draw-in-canvas-stroke-raster"),n.setAttribute("x",v(t.minX).toString()),n.setAttribute("y",v(t.minY).toString()),n.setAttribute("width",v(i).toString()),n.setAttribute("height",v(s).toString()),n.setAttribute("pointer-events","none"),n.dataset.strokeCount=e.length.toString(),o.classList.add("draw-in-canvas-stroke-raster-canvas"),o.width=Math.max(1,Math.ceil(i*a)),o.height=Math.max(1,Math.ceil(s*a)),o.setAttribute("aria-hidden","true"),n.appendChild(o);let l=this.rasterRenderGeneration;return Oi(e.length)?this.renderStrokesToRasterCanvasChunked(o,t,e,a,l):this.renderStrokesToRasterCanvas(o,t,e,a),this.strokeRasterEls.push(n),n}getRasterBitmapScale(){var n;let e=(n=this.svgEl)==null?void 0:n.getScreenCTM(),t=e?Is(e):1;return Fi(window.devicePixelRatio)*t}renderStrokesToRasterCanvas(e,t,n,o){let i=this.prepareRasterCanvasContext(e,t,o);if(!i)return;let s="none";for(let a of n)s=this.drawStrokeOnPreparedRasterCanvas(i,a,s);this.resetRasterCanvasContext(i)}renderStrokesToRasterCanvasChunked(e,t,n,o,i){let s=this.prepareRasterCanvasContext(e,t,o);if(!s)return;let a=0,l="none",c=()=>{if(i!==this.rasterRenderGeneration){this.resetRasterCanvasContext(s);return}if(a>0&&!e.isConnected){this.resetRasterCanvasContext(s);return}let d=performance.now(),u=0;for(;a<n.length;){let h=n[a++];if(h&&(l=this.drawStrokeOnPreparedRasterCanvas(s,h,l)),u++,u>=bn&&(u=0,performance.now()-d>=kn)){this.requestRasterRenderFrame(c);return}}this.resetRasterCanvasContext(s)};c()}prepareRasterCanvasContext(e,t,n){let o=e.getContext("2d");return o?(o.setTransform(n,0,0,n,0,0),o.clearRect(0,0,t.maxX-t.minX,t.maxY-t.minY),o.translate(-t.minX,-t.minY),o.lineCap="round",o.lineJoin="round",o.filter="none",o):null}drawStrokeOnPreparedRasterCanvas(e,t,n){let o=Vn(t),i=o>0?`blur(${o}px)`:"none";return i!==n&&(e.filter=i),this.drawStrokeOnRasterCanvas(e,t),i}resetRasterCanvasContext(e){e.setTransform(1,0,0,1,0,0),e.globalAlpha=1,e.filter="none"}drawStrokeOnRasterCanvas(e,t){let n=Pe(t),o=this.shouldUseHandwrittenStrokePath(t,n),i=f(t.opacity)/100;e.globalAlpha=o?i*.96:i,o?this.drawHandwrittenStrokeOnRasterCanvas(e,t,n):this.drawLinearStrokeOnRasterCanvas(e,t)}drawHandwrittenStrokeOnRasterCanvas(e,t,n){if(typeof Path2D=="undefined")return;let o=Qt(t,{kind:"handwritten",settings:this.settings,isComplete:!0,hasPressure:n,isStart:!0,isEnd:!0}),i=this.strokePathCache.getRasterPath(t.id,o,()=>{let s=this.strokePathCache.getPathData(t.id,o,()=>this.createHandwrittenStrokeShapePath(t,!0,n,!0,!0));return s.length>0?new Path2D(s):null});i&&(e.fillStyle=t.color,e.fill(i))}drawLinearStrokeOnRasterCanvas(e,t){let n=t.points[0];if(!(!n||t.points.length<2)){e.strokeStyle=t.color,e.lineWidth=t.width,e.beginPath(),e.moveTo(n.x,n.y);for(let o=1;o<t.points.length;o++){let i=t.points[o];i&&e.lineTo(i.x,i.y)}e.stroke()}}createStrokeBatchPathEl(e){let t=activeDocument.createElementNS(G,"path"),n=e[0];if(t.classList.add("draw-in-canvas-stroke","draw-in-canvas-stroke-batch"),t.setAttribute("pointer-events","none"),t.dataset.strokeCount=e.length.toString(),!n)return t;let o=Pe(n),i=this.shouldUseHandwrittenStrokePath(n,o),s=e.map(a=>this.getStrokeRenderPathData(a,!0)).filter(a=>a.length>0).join(" ");return t.classList.toggle("mod-handwritten",i),t.setAttribute("opacity",Ye(n.opacity)),this.applyStrokeHardness(t,n),t.setAttribute("d",s),i?(t.setAttribute("fill",n.color),t.setAttribute("stroke","none"),t.removeAttribute("stroke-width"),t.removeAttribute("stroke-linecap"),t.removeAttribute("stroke-linejoin")):(t.setAttribute("stroke",n.color),t.setAttribute("stroke-width",n.width.toString()),t.setAttribute("fill","none"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round")),this.strokeBatchEls.push(t),t}getStrokeRenderBatchKey(e){let t=Pe(e);return Hi({kind:this.shouldUseHandwrittenStrokePath(e,t)?"handwritten":"linear",color:e.color,opacity:Ye(e.opacity),blurRadius:Vn(e),width:e.width})}getStrokeRenderPathData(e,t){let n=Pe(e);return this.shouldUseHandwrittenStrokePath(e,n)?this.getHandwrittenStrokeShapePath(e,t,n):this.getStrokeCenterPath(e)}createStrokeGroupEl(e){let t=activeDocument.createElementNS(G,"g");return t.classList.add("draw-in-canvas-stroke-wrapper"),t.classList.toggle("is-selected",this.selectedStrokeIds.has(e.id)),t.dataset.strokeId=e.id,t.appendChild(this.createPathEl(e)),this.strokeGroupById.set(e.id,t),t}createPathEl(e,t=!0){let n=activeDocument.createElementNS(G,"path");return n.classList.add("draw-in-canvas-stroke"),this.updateVisibleStrokePathEl(n,e,t),n}updateVisibleStrokePathEl(e,t,n=!0,o={}){var a;let i=(a=o.hasPressure)!=null?a:Pe(t),s=this.shouldUseHandwrittenStrokePath(t,i);if(e.classList.toggle("mod-handwritten",s),e.setAttribute("pointer-events","none"),e.setAttribute("opacity",Ye(t.opacity)),this.applyStrokeHardness(e,t),s){e.setAttribute("d",this.getHandwrittenStrokeShapePath(t,n,i,o)),e.setAttribute("fill",t.color),e.setAttribute("stroke","none"),e.removeAttribute("stroke-width"),e.removeAttribute("stroke-linecap"),e.removeAttribute("stroke-linejoin");return}e.setAttribute("d",this.getStrokeCenterPath(t,n)),e.setAttribute("stroke",t.color),e.setAttribute("stroke-width",t.width.toString()),e.setAttribute("fill","none"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round")}applyStrokeHardness(e,t){let n=Vn(t);e.classList.toggle("mod-soft-edge",n>0),e.setCssStyles({filter:n>0?`blur(${n}px)`:""})}shouldUseHandwrittenStrokePath(e,t=Pe(e)){return!ne(e,this.settings).enabled&&!t?!1:so(vu(e.points),e.width)}getStrokeCenterPath(e,t=!0){let n=ne(e,this.settings);if(!t)return Mr(e.points,{smooth:n.enabled});let o=Qt(e,{kind:"linear",settings:this.settings});return this.strokePathCache.getPathData(e.id,o,()=>Mr(e.points,{smooth:n.enabled}))}getHandwrittenStrokeShapePath(e,t,n=Pe(e),o={}){var l,c;let i=(l=o.isStart)!=null?l:!0,s=(c=o.isEnd)!=null?c:!0;if(!t||!i||!s)return this.createHandwrittenStrokeShapePath(e,t,n,i,s);let a=Qt(e,{kind:"handwritten",settings:this.settings,isComplete:t,hasPressure:n,isStart:i,isEnd:s});return this.strokePathCache.getPathData(e.id,a,()=>this.createHandwrittenStrokeShapePath(e,t,n,i,s))}createHandwrittenStrokeShapePath(e,t,n,o,i){let s=ne(e,this.settings),a=fn(e.points,{size:e.width,thinning:s.thinning,streamline:s.streamline,smoothing:s.smoothing,simulatePressure:!n,start:{cap:o&&s.taperStart===0,taper:o?s.taperStart:0},end:{cap:i&&s.taperEnd===0,taper:i?s.taperEnd:0},last:t&&i});return Sd(a)}showPenCursorFromEvent(e){if(!this.settings.usePenCursorFallback||!cr(e)||!this.captureEl||this.isSpaceKeyPressed){this.hidePenCursor();return}this.ensurePenCursorEl().classList.add("is-visible"),this.captureEl.classList.add("is-pen-cursor-active"),this.pendingPenCursorPosition={x:e.clientX,y:e.clientY},this.schedulePenCursorUpdate()}updatePenCursorAfterPointerEnd(e){if(cr(e)){if(e.type==="pointercancel"||!this.captureEl||!hu(e,this.captureEl)){this.hidePenCursor();return}this.showPenCursorFromEvent(e)}}ensurePenCursorEl(){var t;if((t=this.penCursorEl)!=null&&t.isConnected)return this.penCursorEl;let e=activeDocument.createElement("div");return e.classList.add("draw-in-canvas-pen-cursor"),e.setAttribute("aria-hidden","true"),activeDocument.body.appendChild(e),this.penCursorEl=e,this.penCursorAppearanceKey="",e}schedulePenCursorUpdate(){this.penCursorFrameId===null&&(this.penCursorFrameId=window.requestAnimationFrame(()=>{this.penCursorFrameId=null,this.updatePenCursorFromPendingPosition()}))}updatePenCursorFromPendingPosition(){!this.penCursorEl||!this.pendingPenCursorPosition||(this.syncPenCursorAppearance(this.penCursorEl),this.penCursorEl.setCssStyles({transform:`translate3d(${this.pendingPenCursorPosition.x}px, ${this.pendingPenCursorPosition.y}px, 0) translate(-50%, -50%)`}))}syncPenCursorAppearance(e){let t=this.settings.strokeColor,n=`${this.getPenCursorDiameter()}px`,o=`${t}|${n}`;o!==this.penCursorAppearanceKey&&(e.setCssProps({"--draw-in-canvas-current-color":t,"--draw-in-canvas-pen-cursor-size":n}),this.penCursorAppearanceKey=o)}hidePenCursor(){var e,t;this.cancelPenCursorUpdate(),this.pendingPenCursorPosition=null,(e=this.penCursorEl)==null||e.classList.remove("is-visible"),(t=this.captureEl)==null||t.classList.remove("is-pen-cursor-active")}removePenCursor(){var e;this.hidePenCursor(),(e=this.penCursorEl)==null||e.remove(),this.penCursorEl=null,this.penCursorAppearanceKey=""}cancelPenCursorUpdate(){this.penCursorFrameId!==null&&(window.cancelAnimationFrame(this.penCursorFrameId),this.penCursorFrameId=null)}getPenCursorDiameter(){let e=y(this.settings.strokeWidth);return Math.round(Math.min(96,Math.max(8,e)))}appendActiveStrokePointerPoints(e){let t=this.activeStroke;if(!t)return!1;let n=this.createCanvasPointMapper();if(!n)return!1;let o=dt(Nc,this.getCanvasScreenScale()),i=!1,s=l=>{let c=n(l),d=t.points[t.points.length-1];!d||de(d,c)<o||(t.points.push(c),c.pressure!==void 0&&(this.activeStrokeHasPressure=!0),i=!0)},a=pu(e);for(let l of a)s(l);return(a.length===0||a[a.length-1]!==e)&&s(e),i}scheduleActiveStrokePreviewUpdate(){this.activeStrokePreviewFrameId===null&&(this.activeStrokePreviewFrameId=window.requestAnimationFrame(()=>{this.activeStrokePreviewFrameId=null,this.updateActiveStrokePreview()}))}updateActiveStrokePreview(){if(!this.activeStroke||!this.activeStrokePathEl)return;let e=this.activeStrokeHasPressure;if(this.shouldUseHandwrittenStrokePath(this.activeStroke,e)){this.updateHandwrittenActiveStrokePreview(this.activeStroke,e);return}this.updateLinearActiveStrokePreview(this.activeStroke)}initializeActiveStrokePreviewState(){this.resetActiveStrokePreviewState()}resetActiveStrokePreviewState(){for(let e of this.activeStrokePreviewChunkPathEls.splice(0))e.remove();this.activeStrokePreviewCommittedPointIndex=0}updateLinearActiveStrokePreview(e){if(!this.activeStrokePathEl)return;this.flushLinearActiveStrokePreviewChunks(e);let t=Math.max(0,this.activeStrokePreviewCommittedPointIndex-1),n=or(e,t,e.points.length);this.updateLinearStrokePathEl(this.activeStrokePathEl,n),this.activeStrokePathEl.removeAttribute("opacity")}flushLinearActiveStrokePreviewChunks(e){if(!(!this.activeStrokeGroupEl||!this.activeStrokePathEl))for(;e.points.length-this.activeStrokePreviewCommittedPointIndex>Yc+cs;){let t=this.activeStrokePreviewCommittedPointIndex,n=Math.min(t+cs,e.points.length);if(n-t<2)return;let o=or(e,t,n),i=activeDocument.createElementNS(G,"path");i.classList.add("draw-in-canvas-stroke"),this.updateLinearStrokePathEl(i,o),i.removeAttribute("opacity"),this.activeStrokeGroupEl.insertBefore(i,this.activeStrokePathEl),this.activeStrokePreviewChunkPathEls.push(i),this.activeStrokePreviewCommittedPointIndex=n}}updateLinearStrokePathEl(e,t){e.classList.remove("mod-handwritten"),e.setAttribute("pointer-events","none"),e.setAttribute("opacity",Ye(t.opacity)),this.applyStrokeHardness(e,t),e.setAttribute("d",this.getStrokeCenterPath(t,!1)),e.setAttribute("stroke",t.color),e.setAttribute("stroke-width",t.width.toString()),e.setAttribute("fill","none"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round")}updateHandwrittenActiveStrokePreview(e,t){if(!this.activeStrokePathEl)return;this.flushHandwrittenActiveStrokePreviewChunks(e,t);let n=Li(this.activeStrokePreviewCommittedPointIndex),o=or(e,n,e.points.length);this.updateVisibleStrokePathEl(this.activeStrokePathEl,o,!1,{hasPressure:t,isStart:n===0,isEnd:!0}),this.activeStrokePathEl.removeAttribute("opacity")}flushHandwrittenActiveStrokePreviewChunks(e,t){if(!this.activeStrokeGroupEl||!this.activeStrokePathEl)return;let n=Cn(e.points.length,this.activeStrokePreviewCommittedPointIndex);for(;n;){let o=or(e,n.startIndex,n.endIndex),i=activeDocument.createElementNS(G,"path");i.classList.add("draw-in-canvas-stroke"),this.updateVisibleStrokePathEl(i,o,!1,{hasPressure:t,isStart:n.startIndex===0,isEnd:!1}),i.removeAttribute("opacity"),this.activeStrokeGroupEl.insertBefore(i,this.activeStrokePathEl),this.activeStrokePreviewChunkPathEls.push(i),this.activeStrokePreviewCommittedPointIndex=n.nextCommittedPointIndex,n=Cn(e.points.length,this.activeStrokePreviewCommittedPointIndex)}}cancelActiveStrokePreviewUpdate(){this.activeStrokePreviewFrameId!==null&&(window.cancelAnimationFrame(this.activeStrokePreviewFrameId),this.activeStrokePreviewFrameId=null)}enableSelectMode(){if(this.closeBrushPopovers(),this.clearToolbarPressState(),this.isDrawingEnabled()){this.disableDrawingMode();return}this.syncToolbarButton()}shouldUseSelectToolShortcut(e){var t,n,o;return!this.captureEl||!Su(e)||ir(e.target)||e.target instanceof Node&&((t=this.colorPaletteEl)!=null&&t.contains(e.target)||(n=this.strokeSettingsPaletteEl)!=null&&n.contains(e.target)||(o=this.brushControlsEl)!=null&&o.contains(e.target))?!1:this.app.workspace.getMostRecentLeaf()===this.target.leaf}getHistoryColorSwatchEventTarget(e){if(!(e.target instanceof Element)||!(e.currentTarget instanceof HTMLElement))return null;let t=e.target.closest(".draw-in-canvas-history-color-swatch");return t&&e.currentTarget.contains(t)?t:null}setColorValueMode(e){e!==this.colorValueMode&&(this.colorValueMode=e,e==="hsl"?(this.colorValueHsl=ce(this.customColorHex,this.colorWheelHsv.h),this.preserveHslColorValueForHex=null):e==="lab"&&(this.colorValueLab=le(this.customColorHex),this.preserveLabColorValueForHex=null),this.syncHslSliderControls(),this.positionColorPalette())}updateColorWheelFromPointer(e,t,n){let o=n==="hue"?{...this.colorWheelHsv,h:Fd(e,t.clientX,t.clientY)}:{...this.colorWheelHsv,...zd(e,t.clientX,t.clientY)};this.setColorWheelHsv(o)}updateHslSliderFromInput(e){let t=Xn(this.colorValueMode,e.dataset.colorValueSlider);return t?(this.setColorValueSliderValue(t.id,Number(e.value)),!0):!1}beginCurrentColorHslEdit(e){e.readOnly=!1,e.classList.add("is-editing"),e.value=this.getColorValueInputText(),we(e,!0),e.focus({preventScroll:!0}),window.requestAnimationFrame(()=>{activeDocument.activeElement===e&&!e.readOnly&&e.select()})}commitCurrentColorHslEdit(e){let t=!e.readOnly,n=Cs(this.colorValueMode,e.value);n&&t&&(this.setColorValueHex(n.hexColor,n.fallbackHue,n.labColor,n.hslColor),this.recordColorHistory(this.customColorHex)),e.readOnly=!0,e.classList.remove("is-editing"),e.value=this.getColorValueInputText(),we(e,!0)}resetCurrentColorHslInput(e){e.readOnly=!0,e.classList.remove("is-editing"),e.value=this.getColorValueInputText(),we(e,!0)}async copyCurrentColorHslToClipboard(e){let t=this.getColorValueInputText();e.value=t,we(e,!0);try{await bs(t),new I.Notice(`Copied ${t}`)}catch(n){console.error("Draw in canvas could not copy color value",n),new I.Notice("Draw in canvas could not copy color value. See console for details.")}}beginCurrentColorHexEdit(e){e.readOnly=!1,e.classList.add("is-editing"),e.value=Z(this.getColorPaletteStrokeColor()),W(e,!0),e.focus({preventScroll:!0}),window.requestAnimationFrame(()=>{activeDocument.activeElement===e&&!e.readOnly&&e.select()})}commitCurrentColorHexEdit(e){let t=!e.readOnly,n=E(e.value);n&&t&&(this.customColorHex=n,this.setStrokeColor(n),this.recordColorHistory(n)),e.readOnly=!0,e.classList.remove("is-editing"),e.value=Z(this.getColorPaletteStrokeColor()),W(e,!0)}resetCurrentColorHexInput(e){e.readOnly=!0,e.classList.remove("is-editing"),e.value=Z(this.getColorPaletteStrokeColor()),W(e,!0)}async copyCurrentColorHexToClipboard(e){let t=Z(this.getColorPaletteStrokeColor());e.value=t,W(e,!0);try{await bs(t),new I.Notice(`Copied ${t}`)}catch(n){console.error("Draw in canvas could not copy hex color",n),new I.Notice("Draw in canvas could not copy hex color. See console for details.")}}updateBrushSliderFromPointer(e,t){let n=Ln(e.dataset.brushSlider);n&&this.setBrushSliderValue(n,wd(n,e,t.clientY))}getBrushSliderCurrentValue(e){let t=this.getBrushControlsStyle();return e==="size"?y(t.width):f(t.opacity)}setBrushSliderValue(e,t){let n=this.getBrushControlsTarget();if(e==="size"){let i=y(t);n==="selection"?this.setSelectedStrokeWidth(i):this.setStrokeWidth(i),this.updateBrushPreview("size");return}let o=f(t);n==="selection"?this.setSelectedStrokeOpacity(o):this.setStrokeOpacity(o),this.updateBrushPreview("opacity")}updateInteractionCursorFromEvent(e){if(this.captureEl||this.isSpaceKeyPressed||Ns(e.target)||Ls(e.target)){this.setInteractionCursor(null);return}let t=this.clientPointToCanvasPoint(e);if(!t){this.setInteractionCursor(null);return}let n=this.findResizeHandleAtPoint(t);if(n){this.setInteractionCursor(Kn(n));return}this.setInteractionCursor(this.findStrokeAtPoint(t)?"move":null)}setInteractionCursor(e){var t;this.interactionCursor!==e&&(this.interactionCursor=e,(t=this.strokeInteractionEl)==null||t.setCssStyles({cursor:e!=null?e:""}))}handleStrokeHitPointerDown(e,t,n){e.preventDefault(),e.stopPropagation();let o=this.selectedStrokeIds.has(n.id);if(Fn(e)){if(o){this.selectedStrokeIds.delete(n.id),this.syncVisibleStrokeElements(),this.renderSelectionBox();return}this.selectStrokes([...this.selectedStrokeIds,n.id])}else o||this.selectStrokes([n.id]);this.startStrokeDrag(e.pointerId,t,this.getSelectedStrokeIds())}startStrokeDrag(e,t,n){let o=n.map(i=>this.findStrokeGroupEl(i)).filter(Xe);return o.length===0?!1:(this.clearNativeSelectionDrag(),this.dragState={pointerId:e,strokeIds:[...n],startPoint:t,currentDelta:{x:0,y:0},strokeGroupEls:o,hasMoved:!1},this.strokeInteractionEl&&Ge(this.strokeInteractionEl,e),!0)}handleStrokeDragPointerMove(e,t){let n=this.clientPointToCanvasPoint(e);if(!n)return;let o={x:v(n.x-t.startPoint.x),y:v(n.y-t.startPoint.y)};!t.hasMoved&&Math.hypot(o.x,o.y)<rs||(e.preventDefault(),e.stopPropagation(),t.hasMoved=!0,t.currentDelta=o,this.applyStrokeDragTransform(t,o))}handleStrokeDragPointerUp(e,t){var i;if(e.preventDefault(),e.stopPropagation(),(i=this.strokeInteractionEl)!=null&&i.hasPointerCapture(e.pointerId)&&this.strokeInteractionEl.releasePointerCapture(e.pointerId),this.dragState=null,this.clearStrokeDragTransform(t),!t.hasMoved)return;let n=t.currentDelta,o=[];for(let s of t.strokeIds){let a=this.findStroke(s);a&&(this.translateStroke(a,n),this.updateStrokeElement(a),o.push(s))}if(o.length===0){this.renderSelectionBox();return}this.selectStrokes(o),this.pushHistory({type:"move-strokes",strokeIds:o,delta:n}),this.hasPendingSave=!0,this.scheduleSave()}startStrokeResize(e,t){let n=this.getSelectedStrokeBounds(),o=this.getSelectedStrokeIds(),i=o.map(d=>this.findStrokeGroupEl(d)).filter(Xe);if(!n||i.length===0)return!1;let s=qe(n.bounds,n.padding),a=sr(s,bu(t)),l=sr(s,t),c=Math.max(de(a,l),1);return this.clearNativeSelectionDrag(),this.dragState=null,this.resizeState={pointerId:e,strokeIds:o,handle:t,origin:a,referencePoint:l,referenceDistance:c,currentScale:1,strokeGroupEls:i,hasMoved:!1},this.setInteractionCursor(Kn(t)),this.strokeInteractionEl&&Ge(this.strokeInteractionEl,e),!0}handleStrokeResizePointerMove(e,t){let n=this.clientPointToCanvasPoint(e);if(!n)return;let o=this.settings.allowTinyCanvasElements?zc:Fc,i=Math.max(o,de(t.origin,n)/t.referenceDistance);!t.hasMoved&&Math.abs(i-1)<Pn||(e.preventDefault(),e.stopPropagation(),this.setInteractionCursor(Kn(t.handle)),t.hasMoved=!0,t.currentScale=i,this.applyStrokeResizeTransform(t,i))}handleStrokeResizePointerUp(e,t){var o;if(e.preventDefault(),e.stopPropagation(),(o=this.strokeInteractionEl)!=null&&o.hasPointerCapture(e.pointerId)&&this.strokeInteractionEl.releasePointerCapture(e.pointerId),this.resizeState=null,this.clearStrokeResizeTransform(t),this.updateInteractionCursorFromEvent(e),!t.hasMoved||Math.abs(t.currentScale-1)<Pn){this.renderSelectionBox();return}let n=[];for(let i of t.strokeIds){let s=this.findStroke(i);s&&(this.scaleStroke(s,t.origin,t.currentScale),this.updateStrokeElement(s),n.push(i))}if(n.length===0){this.renderSelectionBox();return}this.selectStrokes(n),this.pushHistory({type:"resize-strokes",strokeIds:n,origin:t.origin,scale:t.currentScale}),this.hasPendingSave=!0,this.scheduleSave(),this.updateInteractionCursorFromEvent(e)}startNativeSelectionDrag(e,t){let n={pointerId:e.pointerId,startPoint:t,currentPoint:t,initialSelectedStrokeIds:new Set(this.selectedStrokeIds),isAdditive:Fn(e),hasMoved:!1};this.nativeSelectionDragState=n,n.isAdditive||this.selectStrokes([])}handleNativeSelectionDragPointerMove(e,t){let n=this.clientPointToCanvasPoint(e);if(!n)return;let o={x:n.x-t.startPoint.x,y:n.y-t.startPoint.y};!t.hasMoved&&Math.hypot(o.x,o.y)<rs||(t.hasMoved=!0,t.currentPoint=n,this.selectStrokes(this.getNativeSelectionDragStrokeIds(t)))}handleNativeSelectionDragPointerUp(e,t){if(this.nativeSelectionDragState=null,!t.hasMoved){t.isAdditive||this.selectStrokes([]);return}this.selectStrokes(this.getNativeSelectionDragStrokeIds(t))}getNativeSelectionDragStrokeIds(e){let t=yu(e.startPoint,e.currentPoint),n=e.isAdditive?new Set(e.initialSelectedStrokeIds):new Set,o=this.getCanvasUnitsForScreenPixels(os),i=this.strokeSpatialIndex.queryBounds(En(t,o));for(let s of i){let a=this.findStroke(s);if(!a)continue;let l=this.getStrokeBounds(a),c=Math.max(a.width/2,o);!l||!zn(t,l,c)||n.add(a.id)}return this.strokeSpatialIndex.sortIdsByOrder(Array.from(n))}clearNativeSelectionDrag(){this.nativeSelectionDragState=null}handleDrawingHistoryShortcut(e){let t=Jd(e);return!t||!this.shouldUseDrawingHistoryShortcut(e,t)?!1:(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),t==="undo"?this.undoLastStroke():this.redoLastStroke(),!0)}shouldUseDrawingHistoryShortcut(e,t){return ir(e.target)||this.app.workspace.getMostRecentLeaf()!==this.target.leaf?!1:t==="undo"?this.undoStack.length>0:this.redoStack.length>0}finishActiveStroke(){if(!this.activeStroke)return;let e=this.activeStroke;this.cancelActiveStrokePreviewUpdate();let t=e.points[0];if(t&&e.points.length===1){let i={x:v(t.x+.01),y:v(t.y+.01)};t.pressure!==void 0&&(i.pressure=t.pressure),e.points.push(i)}this.strokePathCache.invalidateStroke(e.id);let n=this.setStrokeBounds(e);n&&this.strokeSpatialIndex.updateBounds(e.id,A(n,e.width)),this.invalidateRasterTilesForStrokeGeometries([{bounds:n,strokeWidth:e.width}]);let o=this.activeStrokeGroupEl;this.activeStroke=null,this.activeStrokeGroupEl=null,this.activeStrokePathEl=null,this.activeStrokePointerId=null,this.activeStrokeHasPressure=!1,this.resetActiveStrokePreviewState(),o==null||o.remove(),this.renderVisibleStrokeElements(),this.pushHistory({type:"add-stroke",stroke:Ze(e)}),this.scheduleSave()}selectStrokes(e){let t=new Set;for(let o of e)this.findStroke(o)&&t.add(o);(t.size!==this.selectedStrokeIds.size||Array.from(t).some(o=>!this.selectedStrokeIds.has(o)))&&this.commitPendingSelectedStrokeRecolor(),this.selectedStrokeIds.clear();for(let o of t)this.selectedStrokeIds.add(o);this.syncVisibleStrokeElements(),this.renderSelectionBox(),this.syncBrushControlsMountState(),this.colorPaletteTarget==="selection"&&(this.selectedStrokeIds.size===0?this.closeColorPalette():(this.syncColorPaletteSelection(),this.positionColorPalette())),this.strokeSettingsPaletteTarget==="selection"&&(this.selectedStrokeIds.size===0?this.closeStrokeSettingsPalette():(this.syncStrokeSettingsPaletteControls(),this.positionStrokeSettingsPalette()))}getSelectedStrokeIds(){let e=[];for(let t of this.drawingData.strokes)this.selectedStrokeIds.has(t.id)&&e.push(t.id);return e}syncChangedSelectedStrokeElements(e){for(let t of e)this.syncSelectedStrokeElement(t);for(let t of this.selectedStrokeIds)e.has(t)||this.syncSelectedStrokeElement(t)}syncSelectedStrokeElement(e){let t=this.findStrokeGroupEl(e);t==null||t.classList.toggle("is-selected",this.selectedStrokeIds.has(e))}syncSelectedStrokeElements(){for(let[e,t]of this.strokeGroupById){if(!t.isConnected){this.strokeGroupById.delete(e);continue}t.classList.toggle("is-selected",this.selectedStrokeIds.has(e))}}renderSelectionBox(){this.removeSelectionOverlay();let e=this.getSelectedStrokeBounds();if(!this.svgEl||!e)return;this.syncTinyControlScale();let t=qe(e.bounds,e.padding),n=this.getCanvasUnitsForScreenPixels(1),o=activeDocument.createElementNS(G,"rect");o.classList.add("draw-in-canvas-selection-box"),o.setAttribute("x",v(t.minX).toString()),o.setAttribute("y",v(t.minY).toString()),o.setAttribute("width",v(t.maxX-t.minX).toString()),o.setAttribute("height",v(t.maxY-t.minY).toString()),o.setAttribute("rx",P(Bc*n)),o.style.setProperty("stroke-width",P(is*n)),o.style.setProperty("stroke-dasharray",`${P(Mc*n)} ${P(Hc*n)}`),o.setAttribute("pointer-events","none"),this.svgEl.appendChild(o),this.selectionBoxEl=o;for(let i of["nw","ne","se","sw"]){let s=this.createSelectionHandleEl(i,t);this.svgEl.appendChild(s),this.selectionHandleEls.push(s)}this.renderStrokeScaleMenu(t)}removeSelectionOverlay(){var e;this.removeStrokeScaleMenu(),(e=this.selectionBoxEl)==null||e.remove(),this.selectionBoxEl=null;for(let t of this.selectionHandleEls.splice(0))t.remove()}createSelectionHandleEl(e,t){let n=sr(t,e),o=activeDocument.createElementNS(G,"rect");o.classList.add("draw-in-canvas-selection-handle",`mod-${e}`),o.dataset.resizeHandle=e;let i=this.getCanvasUnitsForScreenPixels(ns),s=i/2;return o.setAttribute("x",v(n.x-s).toString()),o.setAttribute("y",v(n.y-s).toString()),o.setAttribute("width",P(i)),o.setAttribute("height",P(i)),o.setAttribute("rx",P(this.getCanvasUnitsForScreenPixels(_c))),o.style.setProperty("stroke-width",P(this.getCanvasUnitsForScreenPixels(is))),o.setAttribute("pointer-events","none"),o}syncSelectedStrokeScaleMenuPosition(){let e=this.getSelectedStrokeBounds();if(!e){this.removeStrokeScaleMenu();return}this.renderStrokeScaleMenu(qe(e.bounds,e.padding))}renderStrokeScaleMenu(e){var n;if(!this.settings.allowTinyCanvasElements||!this.svgEl){this.removeStrokeScaleMenu();return}let t=this.findCanvasWrapperEl();(!((n=this.strokeScaleMenuContainerEl)!=null&&n.isConnected)||this.strokeScaleMenuContainerEl.parentElement!==t)&&(this.removeStrokeScaleMenu(),this.strokeScaleMenuContainerEl=this.createStrokeScaleMenuContainerEl(),t.appendChild(this.strokeScaleMenuContainerEl)),this.positionStrokeScaleMenu(e)}createStrokeScaleMenuContainerEl(){let e=activeDocument.createElement("div");e.classList.add("canvas-menu-container","draw-in-canvas-stroke-scale-menu-container");let t=activeDocument.createElement("div");return t.classList.add("canvas-menu","draw-in-canvas-stroke-scale-menu"),t.append(this.createStrokeScaleButtonEl("grow"),this.createStrokeScaleButtonEl("shrink"),this.createSelectedStrokeLayerMenuEl(),this.createSelectedStrokeDeleteButtonEl()),e.appendChild(t),this.syncColorPaletteExpandedState(),this.syncStrokeSettingsPaletteExpandedState(),e}createStrokeScaleButtonEl(e){let t=activeDocument.createElement("button");return t.type="button",t.classList.add("clickable-icon","draw-in-canvas-stroke-action-button","draw-in-canvas-stroke-scale-button"),t.setAttribute("aria-label",e==="grow"?"Make selected drawing larger":"Make selected drawing smaller"),t.setAttribute("data-tooltip-position","top"),(0,I.setIcon)(t,e==="grow"?"plus":"minus"),this.strokeScaleMenuDisposers.push(this.addListener(t,"pointerdown",this.handleStrokeScaleButtonPointerDown),this.addListener(t,"click",n=>this.handleStrokeScaleButtonClick(n,e))),t}createSelectedStrokeLayerMenuEl(){let e=activeDocument.createElement("div");e.classList.add("draw-in-canvas-layer-menu","draw-in-canvas-stroke-layer-menu");let t=activeDocument.createElement("button");t.type="button",t.classList.add("clickable-icon","draw-in-canvas-stroke-action-button","draw-in-canvas-layer-menu-button"),t.setAttribute("aria-label","Layer selected drawing"),t.setAttribute("aria-haspopup","menu"),t.setAttribute("aria-expanded","false"),t.setAttribute("data-tooltip-position","top"),(0,I.setIcon)(t,"layers");let n=activeDocument.createElement("div");return n.classList.add("canvas-menu","draw-in-canvas-layer-submenu"),n.setAttribute("role","menu"),n.append(...Oc.map(o=>this.createSelectedStrokeLayerButtonEl(o))),e.append(t,n),this.strokeScaleMenuDisposers.push(this.addListener(t,"pointerdown",this.handleStrokeScaleButtonPointerDown),this.addListener(t,"click",o=>this.handleSelectedStrokeLayerMenuButtonClick(o,e,t))),e}createSelectedStrokeLayerButtonEl(e){let t=Vc[e],n=activeDocument.createElement("button");return n.type="button",n.classList.add("clickable-icon","draw-in-canvas-stroke-action-button","draw-in-canvas-layer-submenu-button"),n.disabled=!this.canReorderSelectedStrokes(e),n.setAttribute("aria-label",t.label),n.setAttribute("data-tooltip-position","top"),n.setAttribute("role","menuitem"),(0,I.setIcon)(n,t.icon),this.strokeScaleMenuDisposers.push(this.addListener(n,"pointerdown",this.handleStrokeScaleButtonPointerDown),this.addListener(n,"click",o=>this.handleSelectedStrokeLayerButtonClick(o,e))),n}createSelectedStrokeDeleteButtonEl(){let e=activeDocument.createElement("button");return e.type="button",e.classList.add("clickable-icon","draw-in-canvas-stroke-action-button","draw-in-canvas-stroke-delete-button"),e.setAttribute("aria-label","Delete selected stroke"),e.setAttribute("data-tooltip-position","top"),(0,I.setIcon)(e,"trash-2"),this.strokeScaleMenuDisposers.push(this.addListener(e,"pointerdown",this.handleStrokeScaleButtonPointerDown),this.addListener(e,"click",this.handleSelectedStrokeDeleteButtonClick)),e}positionStrokeScaleMenu(e){if(!this.svgEl||!this.strokeScaleMenuContainerEl)return;let t=this.svgEl.getScreenCTM();if(!t)return;let o=this.findCanvasWrapperEl().getBoundingClientRect();this.strokeScaleMenuContainerEl.style.setProperty("--draw-in-canvas-stroke-scale-menu-max-width",m(Math.max(0,o.width-ut*2)));let i=this.getStrokeScaleMenuSize(),s=this.svgEl.createSVGPoint();s.x=(e.minX+e.maxX)/2,s.y=e.minY;let a=this.svgEl.createSVGPoint();a.x=s.x,a.y=e.maxY;let l=s.matrixTransform(t),c=a.matrixTransform(t),d=ut,u=Math.max(d,o.width-i.width-ut),h=As(l.x-o.left-i.width/2,d,u),p=ut,S=Math.max(p,o.height-i.height-ut),g=l.y-o.top-i.height-ss,D=c.y-o.top+ss,me=g<p&&D<=S?D:As(g,p,S);this.setStrokeScaleMenuPosition(h,me)}getStrokeScaleMenuSize(){var s,a,l;let e=this.strokeScaleMenuContainerEl;if(!e)return{width:as,height:ls};let t=(s=e.querySelector(".draw-in-canvas-stroke-scale-menu"))==null?void 0:s.getBoundingClientRect(),n=e.getBoundingClientRect(),o=(a=t==null?void 0:t.width)!=null?a:0,i=(l=t==null?void 0:t.height)!=null?l:0;return{width:o>0?o:n.width||as,height:i>0?i:n.height||ls}}setStrokeScaleMenuPosition(e,t){if(!this.strokeScaleMenuContainerEl)return;let n=m(e),o=m(t);this.strokeScaleMenuContainerEl.style.left===n&&this.strokeScaleMenuContainerEl.style.top===o||this.strokeScaleMenuContainerEl.setCssStyles({left:n,top:o})}removeStrokeScaleMenu(){var e;for(let t of this.strokeScaleMenuDisposers.splice(0))t();(e=this.strokeScaleMenuContainerEl)==null||e.remove(),this.strokeScaleMenuContainerEl=null}handleStrokeScaleButtonClick(e,t){if(e.preventDefault(),e.stopPropagation(),!this.settings.allowTinyCanvasElements){this.removeStrokeScaleMenu();return}this.commitPendingSelectedStrokeRecolor(),this.scaleSelectedStrokes(t==="grow"?1.25:.8)}handleSelectedStrokeLayerMenuButtonClick(e,t,n){e.preventDefault(),e.stopPropagation();let o=!t.classList.contains("is-open");t.classList.toggle("is-open",o),n.setAttribute("aria-expanded",o.toString())}handleSelectedStrokeLayerButtonClick(e,t){if(e.preventDefault(),e.stopPropagation(),!this.settings.allowTinyCanvasElements){this.removeStrokeScaleMenu();return}this.reorderSelectedStrokes(t)}canReorderSelectedStrokes(e){return oe(this.getStrokeIds(),this.selectedStrokeIds,e)}reorderSelectedStrokes(e){this.commitPendingSelectedStrokeRecolor();let t=this.getSelectedStrokeIds(),n=this.getStrokeIds(),o=nt(n,t,e);t.length===0||ot(n,o)||(this.applyStrokeOrder(o),this.renderStrokes(),this.selectStrokes(t),this.pushHistory({type:"reorder-strokes",beforeStrokeIds:n,afterStrokeIds:o,selectedStrokeIds:t}),this.hasPendingSave=!0,this.scheduleSave())}scaleSelectedStrokes(e){let t=this.getSelectedStrokeBounds(),n=this.getSelectedStrokeIds();if(!t||n.length===0||Math.abs(e-1)<Pn)return;let o=Eu(t.bounds),i=[];for(let s of n){let a=this.findStroke(s);a&&(this.scaleStroke(a,o,e),this.updateStrokeElement(a),i.push(s))}if(i.length===0){this.renderSelectionBox();return}this.selectStrokes(i),this.pushHistory({type:"resize-strokes",strokeIds:i,origin:o,scale:e}),this.hasPendingSave=!0,this.scheduleSave()}findResizeHandleAtPoint(e){let t=this.getSelectedStrokeBounds();if(!t)return null;let n=qe(t.bounds,t.padding),o=this.getCanvasUnitsForScreenPixels(ns/2+Ac),i=null,s=Number.POSITIVE_INFINITY;for(let a of["nw","ne","se","sw"]){let l=de(e,sr(n,a));l<=o&&l<s&&(i=a,s=l)}return i}getSelectedStrokeBounds(){if(this.selectedStrokeIds.size===0)return null;let e=null,t=this.getCanvasUnitsForScreenPixels(os),n=t;for(let o of this.selectedStrokeIds){let i=this.findStroke(o);if(!i)continue;let s=this.getStrokeBounds(i);s&&(e=e?Cu(e,s):s,n=Math.max(n,i.width/2+t))}return e?{bounds:e,padding:n}:null}isPointInSelectionBox(e){let t=this.getSelectedStrokeBounds();return t?Ds(e,t.bounds,t.padding):!1}deleteSelectedStrokes(){this.commitPendingSelectedStrokeRecolor();let e=this.drawingData.strokes.map((t,n)=>({stroke:t,index:n})).filter(({stroke:t})=>this.selectedStrokeIds.has(t.id));e.length!==0&&(this.pushHistory({type:"delete-strokes",strokes:e.map(({stroke:t})=>Ze(t)),indices:e.map(({index:t})=>t)}),this.removeStrokes(e.map(({stroke:t})=>t.id)),this.selectStrokes([]),this.hasPendingSave=!0,this.scheduleSave())}updateStrokeElement(e){if(!this.svgEl)return;let t=this.findStrokeGroupEl(e.id);if(!this.shouldRenderStroke(e)){t==null||t.remove(),this.strokeGroupById.delete(e.id),this.renderVisibleStrokeElements();return}if(t&&this.selectedStrokeIds.has(e.id)){t.replaceWith(this.createStrokeGroupEl(e));return}this.renderVisibleStrokeElements()}updateStrokePaintAttributes(e){this.invalidateRasterTilesForStroke(e);let t=this.findVisibleStrokePathEl(e.id);if(!t){this.updateStrokeElement(e);return}Ni(t,e.color)}findVisibleStrokePathEl(e){var n;let t=this.findStrokeGroupEl(e);return(n=t==null?void 0:t.querySelector("path.draw-in-canvas-stroke"))!=null?n:null}pushHistory(e){this.undoStack.push(Gn(e)),this.redoStack.length=0,this.syncCanvasUndoRedoButtons()}applyHistoryAction(e,t){switch(e.type){case"add-stroke":if(t==="undo")this.removeStrokes([e.stroke.id]),this.selectStrokes([]);else{let n=Ze(e.stroke);this.addStroke(n),this.updateStrokeElement(n),this.selectStrokes([n.id])}break;case"clear-strokes":this.setStrokes(t==="undo"?pr(e.strokes):[]),this.selectStrokes([]),this.renderStrokes();break;case"delete-strokes":t==="undo"?(this.insertStrokesAtIndices(e.strokes,e.indices),this.selectStrokes(e.strokes.map(n=>n.id)),this.renderStrokes()):(this.removeStrokes(e.strokes.map(n=>n.id)),this.selectStrokes([]));break;case"reorder-strokes":{let n=t==="undo"?e.beforeStrokeIds:e.afterStrokeIds;this.applyStrokeOrder(n),this.renderStrokes(),this.selectStrokes(e.selectedStrokeIds);break}case"move-stroke":{let n=this.findStroke(e.strokeId);n&&(this.translateStroke(n,t==="undo"?Bs(e.delta):e.delta),this.updateStrokeElement(n),this.selectStrokes([e.strokeId]));break}case"move-strokes":{let n=t==="undo"?Bs(e.delta):e.delta,o=[];for(let i of e.strokeIds){let s=this.findStroke(i);s&&(this.translateStroke(s,n),this.updateStrokeElement(s),o.push(i))}this.selectStrokes(o);break}case"resize-strokes":{let n=t==="undo"?1/e.scale:e.scale,o=[];for(let i of e.strokeIds){let s=this.findStroke(i);s&&(this.scaleStroke(s,e.origin,n),this.updateStrokeElement(s),o.push(i))}this.selectStrokes(o);break}case"recolor-strokes":{let n=[];for(let o of e.changes){let i=this.findStroke(o.strokeId);i&&(i.color=t==="undo"?o.previousColor:o.nextColor,this.updateStrokePaintAttributes(i),n.push(o.strokeId))}this.selectStrokes(n);break}case"restyle-strokes":{let n=[];for(let o of e.changes){let i=this.findStroke(o.strokeId);i&&(this.applyStrokeStyle(i,t==="undo"?o.previousStyle:o.nextStyle),n.push(o.strokeId))}this.selectStrokes(n);break}default:Ae(e)}}findStroke(e){var t;return(t=this.strokeById.get(e))!=null?t:null}findStrokeAtPoint(e){let t=this.getCanvasUnitsForScreenPixels(Lc),n=this.getCanvasUnitsForScreenPixels(Dc),o=Math.max(t,n)/2,i=this.strokeSpatialIndex.queryBounds(Ai(e,o),"descending");for(let s of i){let a=this.findStroke(s);if(!a)continue;let l=Math.max(a.width+t,n)/2,c=this.getStrokeBounds(a);if(!(!c||!Ds(e,c,l))&&mu(e,a.points,l)<=l)return a}return null}removeStroke(e){var o;let t=this.findStroke(e);t&&this.invalidateRasterTilesForStroke(t),this.strokePathCache.invalidateStroke(e);let n=this.drawingData.strokes.findIndex(i=>i.id===e);n!==-1&&this.drawingData.strokes.splice(n,1),this.strokeById.delete(e),this.strokeBoundsById.delete(e),this.strokeSpatialIndex.remove(e),this.strokeSpatialIndex.setOrder(this.getStrokeIds()),(o=this.findStrokeGroupEl(e))==null||o.remove(),this.strokeGroupById.delete(e)}findStrokeGroupEl(e){let t=this.strokeGroupById.get(e);return t!=null&&t.isConnected?t:(this.strokeGroupById.delete(e),null)}rebuildStrokeIndex(){this.clearRasterTileCache(),this.strokePathCache.clear(),this.strokeById.clear(),this.strokeBoundsById.clear();let e=[];for(let t=0;t<this.drawingData.strokes.length;t++){let n=this.drawingData.strokes[t];if(!n)continue;this.strokeById.set(n.id,n);let o=this.setStrokeBounds(n);o&&e.push({id:n.id,bounds:A(o,n.width),order:t})}this.strokeSpatialIndex.rebuild(e)}setStrokes(e){this.drawingData.strokes=e,this.rebuildStrokeIndex()}getStrokeIds(){return this.drawingData.strokes.map(e=>e.id)}applyStrokeOrder(e){this.drawingData.strokes=Ot(this.drawingData.strokes,e),this.clearRasterTileCache(),this.strokeSpatialIndex.setOrder(this.getStrokeIds())}addStroke(e){this.strokePathCache.invalidateStroke(e.id),this.drawingData.strokes.push(e),this.strokeById.set(e.id,e);let t=this.setStrokeBounds(e);t&&(this.strokeSpatialIndex.set(e.id,A(t,e.width),this.drawingData.strokes.length-1),e!==this.activeStroke&&this.invalidateRasterTilesForStrokeGeometries([{bounds:t,strokeWidth:e.width}]))}removeStrokes(e){var n;this.invalidateRasterTilesForStrokeGeometries(e.map(o=>{let i=this.findStroke(o);return i?{bounds:this.getStrokeBounds(i),strokeWidth:i.width}:null}).filter(Xe));for(let o of e)this.strokePathCache.invalidateStroke(o);let t=new Set(e);this.drawingData.strokes=this.drawingData.strokes.filter(o=>!t.has(o.id));for(let o of t)this.strokeById.delete(o),this.strokeBoundsById.delete(o),this.strokeSpatialIndex.remove(o),(n=this.findStrokeGroupEl(o))==null||n.remove(),this.strokeGroupById.delete(o),this.selectedStrokeIds.delete(o);this.strokeSpatialIndex.setOrder(this.getStrokeIds()),this.renderSelectionBox()}insertStrokesAtIndices(e,t){var n;for(let o=0;o<e.length;o++){let i=e[o];if(!i)continue;let s=Ze(i),a=Math.max(0,Math.min((n=t[o])!=null?n:this.drawingData.strokes.length,this.drawingData.strokes.length));this.drawingData.strokes.splice(a,0,s)}this.rebuildStrokeIndex()}getStrokeBounds(e){var t;return(t=this.strokeBoundsById.get(e.id))!=null?t:this.setStrokeBounds(e)}setStrokeBounds(e){let t=fu(e);return t?this.strokeBoundsById.set(e.id,t):this.strokeBoundsById.delete(e.id),t}translateStroke(e,t){var s;let n=(s=this.strokeBoundsById.get(e.id))!=null?s:this.setStrokeBounds(e),o=e.width;this.strokePathCache.invalidateStroke(e.id),wu(e.points,t);let i=n?Ms(n,t):this.setStrokeBounds(e);i?(this.strokeBoundsById.set(e.id,i),this.strokeSpatialIndex.updateBounds(e.id,A(i,e.width))):this.strokeSpatialIndex.remove(e.id),this.invalidateRasterTilesForStrokeGeometries([{bounds:n,strokeWidth:o},{bounds:i,strokeWidth:e.width}])}scaleStroke(e,t,n){var a;let o=(a=this.strokeBoundsById.get(e.id))!=null?a:this.setStrokeBounds(e),i=e.width;this.strokePathCache.invalidateStroke(e.id),Pu(e.points,t,n),e.width=Math.max(Kc,v(e.width*n));let s=o?Hs(o,t,n):this.setStrokeBounds(e);s?(this.strokeBoundsById.set(e.id,s),this.strokeSpatialIndex.updateBounds(e.id,A(s,e.width))):this.strokeSpatialIndex.remove(e.id),this.invalidateRasterTilesForStrokeGeometries([{bounds:o,strokeWidth:i},{bounds:s,strokeWidth:e.width}])}applyStrokeDragTransform(e,t){var i;let n=Tu(t);for(let s of e.strokeGroupEls)s.setAttribute("transform",n);(i=this.selectionBoxEl)==null||i.setAttribute("transform",n);for(let s of this.selectionHandleEls)s.setAttribute("transform",n);let o=this.getSelectedStrokeBounds();o&&this.positionStrokeScaleMenu(Ms(qe(o.bounds,o.padding),t))}clearStrokeDragTransform(e){var t;for(let n of e.strokeGroupEls)n.removeAttribute("transform");(t=this.selectionBoxEl)==null||t.removeAttribute("transform");for(let n of this.selectionHandleEls)n.removeAttribute("transform")}applyStrokeResizeTransform(e,t){var i;let n=xu(e.origin,t);for(let s of e.strokeGroupEls)s.setAttribute("transform",n);(i=this.selectionBoxEl)==null||i.setAttribute("transform",n);for(let s of this.selectionHandleEls)s.setAttribute("transform",n);let o=this.getSelectedStrokeBounds();o&&this.positionStrokeScaleMenu(Hs(qe(o.bounds,o.padding),e.origin,t))}clearStrokeResizeTransform(e){var t;for(let n of e.strokeGroupEls)n.removeAttribute("transform");(t=this.selectionBoxEl)==null||t.removeAttribute("transform");for(let n of this.selectionHandleEls)n.removeAttribute("transform")}clientPointToCanvasPoint(e){var t,n;return(n=(t=this.createCanvasPointMapper())==null?void 0:t(e))!=null?n:null}createCanvasPointMapper(){if(!this.svgEl)return null;let e=this.svgEl.getScreenCTM();if(e){let n=e.inverse(),o=this.svgEl.createSVGPoint();return i=>{o.x=i.clientX,o.y=i.clientY;let s=o.matrixTransform(n);return xs(s.x,s.y,i)}}let t=this.svgEl.getBoundingClientRect();return n=>xs(n.clientX-t.left,n.clientY-t.top,n)}scheduleSave(){this.hasPendingSave=!0,this.saveTimeoutId!==null&&window.clearTimeout(this.saveTimeoutId),this.saveTimeoutId=window.setTimeout(()=>{this.saveTimeoutId=null,this.saveNow()},Gc)}async saveNow(){if(this.hasPendingSave){this.hasPendingSave=!1;try{await ho(this.app,this.target.file,this.drawingData)}catch(e){this.hasPendingSave=!0,console.error("Draw in canvas could not save strokes",e),new I.Notice("Draw in canvas could not save strokes. See console for details.")}}}findViewContentEl(){var e;return(e=this.target.containerEl.querySelector(".view-content"))!=null?e:this.target.containerEl}findCanvasWrapperEl(){var e;return(e=this.target.containerEl.querySelector(".canvas-wrapper"))!=null?e:this.findViewContentEl()}findCanvasWorldEl(){var e;return(e=this.target.containerEl.querySelector(".canvas"))!=null?e:this.findViewContentEl()}syncTinyControlScale(){if(!this.settings.allowTinyCanvasElements){let i=this.tinyControlScaleWrapperEl!==null||this.tinyControlScaleKey!=="";return this.clearTinyControlScale(),i}let e=this.findCanvasWrapperEl();this.tinyControlScaleWrapperEl&&this.tinyControlScaleWrapperEl!==e&&this.clearTinyControlScale();let t=this.getCanvasUnitsForScreenPixels(1),n=mo(t),o=P(t);return e.classList.add(hs),this.tinyControlScaleWrapperEl===e&&this.tinyControlScaleKey===o?(this.syncNativeCanvasEdgeEndpoints(n),!1):(e.setCssProps({"--draw-in-canvas-tiny-border-width":m(ed*t),"--draw-in-canvas-tiny-card-shadow-y":m(td*t),"--draw-in-canvas-tiny-card-shadow-blur":m(rd*t),"--draw-in-canvas-tiny-card-shadow-spread":m(nd*t),"--draw-in-canvas-tiny-focus-spread":m(od*t),"--draw-in-canvas-tiny-resizer-size":m(In*t),"--draw-in-canvas-tiny-resizer-half":m(In*t/2),"--draw-in-canvas-tiny-resizer-offset":m(-In*t/2),"--draw-in-canvas-tiny-connection-border":m(ps*t),"--draw-in-canvas-tiny-connection-native-border":m(ps),"--draw-in-canvas-tiny-connection-native-size":m(Rn),"--draw-in-canvas-tiny-connection-scale":P(t),"--draw-in-canvas-tiny-connection-size":m(Rn*t),"--draw-in-canvas-tiny-connection-half":m(Rn*t/2),"--draw-in-canvas-tiny-edge-width":m(id*n),"--draw-in-canvas-tiny-edge-focus-width":m(sd*n),"--draw-in-canvas-tiny-edge-hit-width":m(ad*t),"--draw-in-canvas-tiny-edge-arrow-scale":P(n),"--draw-in-canvas-tiny-snap-line-width":m(ld*t),"--draw-in-canvas-tiny-snap-point-scale":P(t),"--draw-in-canvas-tiny-selection-border-width":m(cd*t),"--draw-in-canvas-tiny-group-selection-border-width":m(dd*t),"--draw-in-canvas-tiny-group-selection-radius":m(ud*t),"--draw-in-canvas-tiny-label-gap":m(-hd*t),"--draw-in-canvas-tiny-label-scale":P(t)}),this.syncNativeCanvasEdgeEndpoints(n),this.tinyControlScaleWrapperEl=e,this.tinyControlScaleKey=o,!0)}syncNativeCanvasEdgeEndpoints(e){this.pruneNativeEdgePathOverrides();let t=Array.from(this.target.containerEl.querySelectorAll(".canvas-edges g")).filter(i=>i.querySelector("path.canvas-display-path")),n=Array.from(this.target.containerEl.querySelectorAll(".canvas-edges polygon.canvas-path-end")).map(i=>i.parentNode).filter(i=>i instanceof SVGGElement),o=Math.min(t.length,n.length);for(let i=0;i<o;i++){let s=t[i],a=n[i];if(!s||!a)continue;let l=md(a,e);if(l)for(let c of Array.from(s.querySelectorAll("path.canvas-display-path, path.canvas-interaction-path"))){let d=c.getAttribute("d"),u=fd(d,l);u&&u!==d&&(this.storeNativeEdgePathOverride(c,d,u),c.setAttribute("d",u))}}}storeNativeEdgePathOverride(e,t,n){let o=this.nativeEdgePathOverrides.get(e),i=o&&t===o.patchedPathData?o.originalPathData:t;this.nativeEdgePathOverrides.set(e,{originalPathData:i,patchedPathData:n})}restoreNativeEdgePathOverrides(){for(let[e,t]of this.nativeEdgePathOverrides)e.isConnected&&e.getAttribute("d")===t.patchedPathData&&(t.originalPathData===null?e.removeAttribute("d"):e.setAttribute("d",t.originalPathData));this.nativeEdgePathOverrides.clear()}pruneNativeEdgePathOverrides(){for(let e of this.nativeEdgePathOverrides.keys())e.isConnected||this.nativeEdgePathOverrides.delete(e)}clearTinyControlScale(){let e=this.tinyControlScaleWrapperEl;this.restoreNativeEdgePathOverrides(),e&&(e.classList.remove(hs),vd(e,["--draw-in-canvas-tiny-border-width","--draw-in-canvas-tiny-card-shadow-y","--draw-in-canvas-tiny-card-shadow-blur","--draw-in-canvas-tiny-card-shadow-spread","--draw-in-canvas-tiny-focus-spread","--draw-in-canvas-tiny-resizer-size","--draw-in-canvas-tiny-resizer-half","--draw-in-canvas-tiny-resizer-offset","--draw-in-canvas-tiny-connection-border","--draw-in-canvas-tiny-connection-native-border","--draw-in-canvas-tiny-connection-native-size","--draw-in-canvas-tiny-connection-scale","--draw-in-canvas-tiny-connection-size","--draw-in-canvas-tiny-connection-half","--draw-in-canvas-tiny-edge-width","--draw-in-canvas-tiny-edge-focus-width","--draw-in-canvas-tiny-edge-hit-width","--draw-in-canvas-tiny-edge-arrow-scale","--draw-in-canvas-tiny-snap-line-width","--draw-in-canvas-tiny-snap-point-scale","--draw-in-canvas-tiny-selection-border-width","--draw-in-canvas-tiny-group-selection-border-width","--draw-in-canvas-tiny-group-selection-radius","--draw-in-canvas-tiny-label-gap","--draw-in-canvas-tiny-label-scale"])),this.tinyControlScaleWrapperEl=null,this.tinyControlScaleKey=""}getCanvasUnitsForScreenPixels(e){return e/this.getCanvasScreenScale()}getCanvasScreenScale(){var t;let e=(t=this.svgEl)==null?void 0:t.getScreenCTM();return e?Is(e):1}hideStaleElements(){let e=new Set;this.captureEl&&e.add(this.captureEl),this.svgEl&&e.add(this.svgEl),this.toolbarGroupEl&&e.add(this.toolbarGroupEl),this.colorPaletteEl&&e.add(this.colorPaletteEl),this.strokeSettingsPaletteEl&&e.add(this.strokeSettingsPaletteEl),this.brushControlsEl&&e.add(this.brushControlsEl);for(let t of this.nativeElementScaleControls.getOwnedElements())e.add(t);this.strokeScaleMenuContainerEl&&e.add(this.strokeScaleMenuContainerEl),pd(this.target.containerEl,e)}ensurePositioned(e){getComputedStyle(e).position==="static"&&(this.positionedEl=e,this.previousPosition=e.style.position,e.setCssStyles({position:"relative"}))}addListener(e,t,n,o){let i=n;return e.addEventListener(t,i,o),()=>e.removeEventListener(t,i,o)}};function Sd(r,e=!0){let t=r.length;if(t<4)return"";let n=r[0],o=r[1],i=r[2];if(!n||!o||!i)return"";let s=`M${ae(n[0])},${ae(n[1])} Q${ae(o[0])},${ae(o[1])} ${ae(er(o[0],i[0]))},${ae(er(o[1],i[1]))} T`;for(let a=2,l=t-1;a<l;a++)n=r[a],o=r[a+1],!(!n||!o)&&(s+=`${ae(er(n[0],o[0]))},${ae(er(n[1],o[1]))} `);return e?`${s}Z`:s}function er(r,e){return(r+e)/2}function ae(r){return v(r).toString()}function P(r){return Number(r.toFixed(6)).toString()}function m(r){return`${P(r)}px`}function vd(r,e){for(let t of e)r.style.removeProperty(t)}function md(r,e){let t=r.querySelector("polygon.canvas-path-end"),n=r.ownerSVGElement,o=r.getCTM(),i=t?gd(t):null;if(!n||!o||i===null)return null;let s=n.createSVGPoint();s.x=0,s.y=i*e;let a=s.matrixTransform(o);return!Number.isFinite(a.x)||!Number.isFinite(a.y)?null:{x:v(a.x),y:v(a.y)}}function gd(r){if(r.points.numberOfItems===0)return null;let e=Number.POSITIVE_INFINITY,t=Number.NEGATIVE_INFINITY;for(let o=0;o<r.points.numberOfItems;o++){let i=r.points.getItem(o);e=Math.min(e,i.y),t=Math.max(t,i.y)}let n=t-e;return Number.isFinite(n)&&n>0?n:null}function fd(r,e){if(!r)return null;let t=String.raw`[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?`,n=new RegExp(`(${t})([\\s,]+)(${t})(\\s*)$`,"i"),o=!1,i=r.replace(n,(s,a,l,c,d)=>(o=!0,`${P(e.x)}${l}${P(e.y)}${d}`));return o?i:null}function Cd(r,e){return!1}function Nn(){return Object.keys(H)}function yd(r){return r&&Object.prototype.hasOwnProperty.call(H,r)?r:null}function Ss(r,e){return H[r].step<1?e.toFixed(2):Math.round(e).toString()}function vs(r,e){switch(e){case"strokeThinning":return k(e,r.thinning);case"strokeStreamline":return k(e,r.streamline);case"strokeSmoothing":return k(e,r.smoothing);case"strokeTaperStart":return k(e,r.taperStart);case"strokeTaperEnd":return k(e,r.taperEnd);default:return Ae(e)}}function Ed(r,e,t){let n=k(e,t);switch(e){case"strokeThinning":return{...r,thinning:n};case"strokeStreamline":return{...r,streamline:n};case"strokeSmoothing":return{...r,smoothing:n};case"strokeTaperStart":return{...r,taperStart:n};case"strokeTaperEnd":return{...r,taperEnd:n};default:return Ae(e)}}function kd(r){return{enabled:r,thinning:H.strokeThinning.defaultValue,streamline:H.strokeStreamline.defaultValue,smoothing:H.strokeSmoothing.defaultValue,taperStart:H.strokeTaperStart.defaultValue,taperEnd:H.strokeTaperEnd.defaultValue}}function Ln(r){return r==="size"||r==="opacity"?r:null}function Sr(r){return r==="size"?{min:1,max:32,step:1}:{min:1,max:100,step:1}}function Te(r,e){return r==="size"?y(e):f(e)}function bd(r,e){let t=Sr(r);return`${(1-(Te(r,e)-t.min)/(t.max-t.min))*100}%`}function wd(r,e,t){let n=Sr(r),o=e.getBoundingClientRect(),i=Math.min(1,Math.max(0,(o.bottom-t)/o.height));return Te(r,n.min+i*(n.max-n.min))}function Pd(r,e,t){let n=Sr(r),o=n.step*5;switch(e.key){case"ArrowUp":case"ArrowRight":return Te(r,Math.min(n.max,t+n.step));case"ArrowDown":case"ArrowLeft":return Te(r,Math.max(n.min,t-n.step));case"PageUp":return Te(r,Math.min(n.max,t+o));case"PageDown":return Te(r,Math.max(n.min,t-o));case"Home":return n.min;case"End":return n.max;default:return null}}function ms(r,e,t,n){let o=activeDocument.createElement("div"),i=w();o.classList.add("draw-in-canvas-brush-slider-control","draw-in-canvas-brush-slider"),o.dataset.brushSlider=r,o.tabIndex=0,o.setAttribute("role","slider"),o.setAttribute("aria-labelledby",i),o.setAttribute("aria-orientation","vertical");let s=activeDocument.createElement("span");s.id=i,s.classList.add("draw-in-canvas-brush-slider-label"),s.textContent=e;let a=activeDocument.createElement("span");a.classList.add("draw-in-canvas-brush-slider-track");let l=activeDocument.createElement("span");l.classList.add("draw-in-canvas-brush-slider-thumb"),a.appendChild(l);let c=activeDocument.createElement("output");return c.classList.add("draw-in-canvas-brush-slider-value",t),c.setAttribute("aria-live","polite"),c.textContent=n,o.append(s,a,c),o}function ht(r,e,t,n,o){let i=activeDocument.createElement("div");i.classList.add("draw-in-canvas-stroke-slider-control");let s=activeDocument.createElement("label");s.htmlFor=r,s.classList.add("draw-in-canvas-stroke-width-label"),s.textContent=e;let a=activeDocument.createElement("output");return a.classList.add(t),a.setAttribute("for",r),a.setAttribute("aria-live","polite"),a.textContent=n,i.append(s,o,a),i}function Ge(r,e){try{r.setPointerCapture(e)}catch(t){if(t instanceof DOMException&&t.name==="NotFoundError")return;throw t}}function Td(r){var e,t;return(t=(e=Array.from(r.children).find(n=>n.classList.contains("canvas-control-group")))==null?void 0:e.nextElementSibling)!=null?t:null}function gs(r,e){var t;return(t=Array.from(r.querySelectorAll(".canvas-control-item")).find(n=>{var o;return(o=n.getAttribute("aria-label"))==null?void 0:o.startsWith(e)}))!=null?t:null}function tr(r){return r.key==="Enter"||r.key===" "}function rr(r){return U.some(e=>e.id===r)?r:null}function xd(r,e){var n,o,i,s,a,l,c,d;let t=U.findIndex(u=>u.id===r);if(t===-1)return null;switch(e.key){case"ArrowRight":case"ArrowDown":return(o=(n=U[(t+1)%U.length])==null?void 0:n.id)!=null?o:r;case"ArrowLeft":case"ArrowUp":return(s=(i=U[(t-1+U.length)%U.length])==null?void 0:i.id)!=null?s:r;case"Home":return(l=(a=U[0])==null?void 0:a.id)!=null?l:r;case"End":return(d=(c=U[U.length-1])==null?void 0:c.id)!=null?d:r;default:return null}}function Dn(r){return r==="hue"||r==="disc"?r:null}function Id(r){return Vs.some(e=>e.id===r)?r:null}function fs(r){switch(r){case"hsl":return{placeholder:"0, 0%, 0%",ariaLabel:"Current hsl stroke color. Click to copy; double-click or press enter to edit.",maxLength:32};case"rgb":return{placeholder:"0, 0, 0",ariaLabel:"Current rgb stroke color. Click to copy; double-click or press enter to edit.",maxLength:32};case"lab":return{placeholder:"50% 0 0",ariaLabel:"Current Lab stroke color. Click to copy; double-click or press enter to edit.",maxLength:36};default:return{placeholder:"",ariaLabel:"Current stroke color value. Click to copy; double-click or press enter to edit.",maxLength:36}}}function Yn(r){switch(r){case"hsl":return Un;case"rgb":return jc;case"lab":return Jc;default:return Un}}function Xn(r,e){var t;return(t=Yn(r).find(n=>n.id===e))!=null?t:null}function Rd(r,e,t,n=0){switch(r){case"hsl":{let o=Ne(e);return o?ue(o,ce(t,n)):he}case"rgb":{let o=vr(t);switch(e){case"red":return L(o.r);case"green":return L(o.g);case"blue":return L(o.b);default:return xe}}case"lab":{let o=le(t);switch(e){case"labLightness":return De(o.l);case"labA":return F(o.a);case"labB":return F(o.b);default:return pe}}default:return he}}function Nd(r,e,t,n,o=0){switch(r){case"hsl":{let i=Ne(e);if(!i)return null;let s=Ws(ce(n,o),i,t);return{hexColor:hr(s),fallbackHue:s.h,hslColor:s}}case"rgb":{let i=vr(n);switch(e){case"red":return{hexColor:M({...i,r:L(t)})};case"green":return{hexColor:M({...i,g:L(t)})};case"blue":return{hexColor:M({...i,b:L(t)})};default:return null}}case"lab":{let i=Gs(le(n),e,t);return i?{hexColor:Re(i),labColor:i}:null}default:return null}}function Ld(r,e,t,n=0){var o;return{"--draw-in-canvas-hsl-slider-gradient":Md(r,e,t,n),"--draw-in-canvas-hsl-slider-thumb-color":(o=E(t))!=null?o:$}}function Dd(r,e){let t=Ne(r);return{"--draw-in-canvas-hsl-slider-gradient":t?Ys(t,e):"var(--background-modifier-border)","--draw-in-canvas-hsl-slider-thumb-color":Jn(e)}}function Ad(r,e){return{"--draw-in-canvas-hsl-slider-gradient":Ks(r,e),"--draw-in-canvas-hsl-slider-thumb-color":Re(e)}}function Md(r,e,t,n=0){switch(r){case"hsl":{let o=Ne(e);return o?Ys(o,ce(t,n)):"var(--background-modifier-border)"}case"rgb":return Hd(e,vr(t));case"lab":return Ks(e,le(t));default:return"var(--background-modifier-border)"}}function Hd(r,e){let t=L(e.r),n=L(e.g),o=L(e.b);switch(r){case"red":return`linear-gradient(to right, rgb(0, ${n}, ${o}), rgb(255, ${n}, ${o}))`;case"green":return`linear-gradient(to right, rgb(${t}, 0, ${o}), rgb(${t}, 255, ${o}))`;case"blue":return`linear-gradient(to right, rgb(${t}, ${n}, 0), rgb(${t}, ${n}, 255))`;default:return"var(--background-modifier-border)"}}function Ks(r,e){switch(r){case"labLightness":return An(pe,gt,t=>Re({...e,l:t}));case"labA":return An(Se,ve,t=>Re({...e,a:t}));case"labB":return An(Se,ve,t=>Re({...e,b:t}));default:return"var(--background-modifier-border)"}}function An(r,e,t){let o=[];for(let i=0;i<=6;i++){let s=r+(e-r)*(i/6);o.push(t(s))}return`linear-gradient(to right, ${o.join(", ")})`}function Bd(r,e,t=0){switch(r){case"hsl":return Jn(ce(e,t));case"rgb":return Yd(vr(e));case"lab":return $s(le(e));default:return Z(e)}}function Cs(r,e){switch(r){case"hsl":{let t=Xd(e);return t?{hexColor:hr(t),fallbackHue:t.h,hslColor:t}:null}case"rgb":{let t=qd(e);return t?{hexColor:M(t)}:null}case"lab":{let t=Zd(e);return t?{hexColor:Re(t),labColor:t}:null}default:return null}}function qn(r,e,t){switch(r){case"hsl":{let n=Ne(e);return n?Vd(n,t):Math.round(t).toString()}case"rgb":return L(t).toString();case"lab":return e==="labLightness"?`${De(t)}%`:F(t).toString();default:return Math.round(t).toString()}}function ys(r,e,t){return`${_d(r,e)} ${qn(r,e,t)}`}function _d(r,e){var n;let t=Xn(r,e);return(n=t==null?void 0:t.label)!=null?n:"Color"}function vr(r){var e,t;return(t=(e=Le(r))!=null?e:Le($))!=null?t:{r:0,g:0,b:0}}function le(r){var e,t;return(t=(e=Ps(r))!=null?e:Ps($))!=null?t:{l:0,a:0,b:0}}function Od(r,e){switch(r){case"labLightness":return De(e.l);case"labA":return F(e.a);case"labB":return F(e.b);default:return pe}}function Gs(r,e,t){let n=Js(r);switch(e){case"labLightness":return{...n,l:De(t)};case"labA":return{...n,a:F(t)};case"labB":return{...n,b:F(t)};default:return null}}function Ne(r){return Un.some(e=>e.id===r)?r:null}function ue(r,e){switch(r){case"hue":{let t=Math.round(T(e.h));return Math.min($n,t)}case"saturation":return Math.round(N(e.s)*100);case"lightness":return Math.round(N(e.l)*100);default:return he}}function Ws(r,e,t){let n=Us(e,t);switch(e){case"hue":return{...r,h:n};case"saturation":return{...r,s:n/100};case"lightness":return{...r,l:n/100};default:return r}}function Us(r,e){let t=Number.isFinite(e)?e:he,n=r==="hue"?Os:he,o=r==="hue"?$n:Wn,i=Math.round(t/vt)*vt;return Math.min(o,Math.max(n,i))}function Ys(r,e){let t=ue("hue",e),n=ue("saturation",e),o=ue("lightness",e);switch(r){case"hue":return"linear-gradient(to right, hsl(0, 100%, 50%), hsl(60, 100%, 50%), hsl(120, 100%, 50%), hsl(180, 100%, 50%), hsl(240, 100%, 50%), hsl(300, 100%, 50%), hsl(360, 100%, 50%))";case"saturation":return`linear-gradient(to right, hsl(${t}, 0%, ${o}%), hsl(${t}, 100%, ${o}%))`;case"lightness":return`linear-gradient(to right, hsl(${t}, ${n}%, 0%), hsl(${t}, ${n}%, 50%), hsl(${t}, ${n}%, 100%))`;default:return"var(--background-modifier-border)"}}function Vd(r,e){let t=Us(r,e);return r==="hue"?`${t}\xB0`:`${t}%`}function Fd(r,e,t){let n=r.getBoundingClientRect(),o=e-(n.left+n.width/2),i=t-(n.top+n.height/2);return T(Math.atan2(i,o)*180/Math.PI)}function zd(r,e,t){let n=r.getBoundingClientRect(),o=Xs({x:N((e-n.left)/n.width),y:N((t-n.top)/n.height)},qs(r));return{s:o.x,v:1-o.y}}function Kd(r,e){let t=Xs({x:r.s,y:1-r.v},qs(e));return{x:t.x*100,y:t.y*100}}function Xs(r,e){let t=Math.max(0,.5-e),n=r.x-.5,o=r.y-.5,i=Math.hypot(n,o);if(i<=t||i===0)return r;let s=t/i;return{x:.5+n*s,y:.5+o*s}}function qs(r){var n,o;let e=r==null?void 0:r.getBoundingClientRect(),t=Math.min((n=e==null?void 0:e.width)!=null?n:0,(o=e==null?void 0:e.height)!=null?o:0);return t<=0?0:Math.min(.5,$c/2/t)}function Gd(r,e){let t=e.shiftKey?Tn:qc;switch(e.key){case"ArrowRight":case"ArrowUp":return{...r,h:T(r.h+t)};case"ArrowLeft":case"ArrowDown":return{...r,h:T(r.h-t)};case"PageUp":return{...r,h:T(r.h+Tn)};case"PageDown":return{...r,h:T(r.h-Tn)};case"Home":return{...r,h:0};case"End":return{...r,h:359};default:return null}}function Wd(r,e){let t=e.shiftKey?xn:Zc;switch(e.key){case"ArrowRight":return{...r,s:N(r.s+t)};case"ArrowLeft":return{...r,s:N(r.s-t)};case"ArrowUp":return{...r,v:N(r.v+t)};case"ArrowDown":return{...r,v:N(r.v-t)};case"PageUp":return{...r,v:N(r.v+xn)};case"PageDown":return{...r,v:N(r.v-xn)};case"Home":return{...r,s:0};case"End":return{...r,s:1};default:return null}}function Ud(r){let e=T(r)*Math.PI/180;return{x:50+Math.cos(e)*us,y:50+Math.sin(e)*us}}function pt(r,e=0){let t=eu(r);return t?{...t,h:t.s===0?T(e):t.h}:{h:T(e),s:0,v:0}}function Zs(r){return{h:T(r.h),s:N(r.s),v:N(r.v)}}function ce(r,e=0){let t=tu(r);return t?{...t,h:t.s===0?T(e):t.h}:{h:T(e),s:0,l:0}}function Zn(r){return{h:T(r.h),s:N(r.s),l:N(r.l)}}function V(r,e){let t=E(r),n=E(e);return t&&n?t===n:r.trim().toLowerCase()===e.trim().toLowerCase()}function E(r){let e=/^#?([\da-f]{6})$/i.exec(r.trim()),t=e==null?void 0:e[1];return t?`#${t.toLowerCase()}`:null}function Z(r){var e;return((e=E(r))!=null?e:$).toUpperCase()}function Jn(r){let e=ue("hue",r),t=ue("saturation",r),n=ue("lightness",r);return`hsl(${e}, ${t}%, ${n}%)`}function Yd(r){return`rgb(${L(r.r)}, ${L(r.g)}, ${L(r.b)})`}function $s(r){return`lab(${De(r.l)}% ${F(r.a)} ${F(r.b)})`}function Xd(r){var h;let e=r.trim();if(!e)return null;let t=/^hsla?\(\s*(.*?)\s*\)$/i.exec(e),o=((h=t==null?void 0:t[1])!=null?h:e).replace(/\s*\/\s*[-+]?(?:\d+\.?\d*|\.\d+)%?\s*$/,"").trim(),i=o.includes(",")?o.split(",").map(p=>p.trim()).filter(p=>p.length>0):o.split(/\s+/).map(p=>p.trim()).filter(p=>p.length>0);if(i.length!==3&&i.length!==4)return null;let[s,a,l]=i;if(s===void 0||a===void 0||l===void 0)return null;let c=jd(s),d=ks(a),u=ks(l);return c===null||d===null||u===null?null:{h:T(c),s:d/100,l:u/100}}function qd(r){let e=js(r,/^rgba?\(\s*(.*?)\s*\)$/i);if(!e)return null;let[t,n,o]=e;if(t===void 0||n===void 0||o===void 0)return null;let i=Mn(t),s=Mn(n),a=Mn(o);return i===null||s===null||a===null?null:{r:i,g:s,b:a}}function Zd(r){let e=js(r,/^lab\(\s*(.*?)\s*\)$/i);if(!e)return null;let[t,n,o]=e;if(t===void 0||n===void 0||o===void 0)return null;let i=$d(t),s=Es(n),a=Es(o);return i===null||s===null||a===null?null:{l:i,a:s,b:a}}function js(r,e){var a;let t=r.trim();if(!t)return null;let n=e.exec(t);if(/^[a-z]+\(/i.test(t)&&!n)return null;let i=((a=n==null?void 0:n[1])!=null?a:t).replace(/\s*\/\s*[-+]?(?:\d+\.?\d*|\.\d+)%?\s*$/,"").trim(),s=i.includes(",")?i.split(",").map(l=>l.trim()).filter(l=>l.length>0):i.split(/\s+/).map(l=>l.trim()).filter(l=>l.length>0);return s.length===3||s.length===4?s:null}function Mn(r){let e=/^([-+]?(?:\d+\.?\d*|\.\d+))(%?)$/.exec(r.trim()),t=e==null?void 0:e[1];if(t===void 0)return null;let n=Number(t);if(!Number.isFinite(n))return null;let o=(e==null?void 0:e[2])==="%"?n/100*$e:n;return o<xe||o>$e?null:L(o)}function $d(r){let e=/^([-+]?(?:\d+\.?\d*|\.\d+))%?$/.exec(r.trim()),t=e==null?void 0:e[1];if(t===void 0)return null;let n=Number(t);return!Number.isFinite(n)||n<pe||n>gt?null:De(n)}function Es(r){let e=/^([-+]?(?:\d+\.?\d*|\.\d+))$/.exec(r.trim()),t=e==null?void 0:e[1];if(t===void 0)return null;let n=Number(t);return!Number.isFinite(n)||n<Se||n>ve?null:F(n)}function jd(r){var i,s;let e=/^([-+]?(?:\d+\.?\d*|\.\d+))(deg|°|rad|turn|grad)?$/i.exec(r.trim()),t=e==null?void 0:e[1];if(t===void 0)return null;let n=Number(t);if(!Number.isFinite(n))return null;switch((s=(i=e==null?void 0:e[2])==null?void 0:i.toLowerCase())!=null?s:"deg"){case"turn":return n*360;case"rad":return n*180/Math.PI;case"grad":return n*.9;case"deg":case"\xB0":return n;default:return null}}function ks(r){let e=/^([-+]?(?:\d+\.?\d*|\.\d+))%?$/.exec(r.trim()),t=e==null?void 0:e[1];if(t===void 0)return null;let n=Number(t);return!Number.isFinite(n)||n<0||n>100?null:n}function we(r,e){W(r,e)}function W(r,e){r.classList.toggle("is-invalid",!e),r.setAttribute("aria-invalid",(!e).toString())}async function bs(r){if(!navigator.clipboard)throw new Error("Clipboard API is unavailable");await navigator.clipboard.writeText(r)}function ws(r){return(r.ctrlKey||r.metaKey)&&r.key.toLowerCase()==="c"}function Jd(r){if(r.altKey||!r.ctrlKey&&!r.metaKey)return null;let e=r.key.toLowerCase();return e==="z"?r.shiftKey?"redo":"undo":e==="y"&&r.ctrlKey&&!r.metaKey&&!r.shiftKey?"redo":null}function Qd(r){var t;let e=(t=Le(r))!=null?t:Le($);return e?[{name:"Lightest shade",value:M(St(e,{r:255,g:255,b:255},.72))},{name:"Light shade",value:M(St(e,{r:255,g:255,b:255},.48))},{name:"Soft shade",value:M(St(e,{r:255,g:255,b:255},.24))},{name:"Base shade",value:M(e)},{name:"Deep shade",value:M(St(e,{r:0,g:0,b:0},.18))},{name:"Darkest shade",value:M(St(e,{r:0,g:0,b:0},.36))}]:[]}function Le(r){var t;let e=(t=E(r))==null?void 0:t.slice(1);return e?{r:Number.parseInt(e.slice(0,2),16),g:Number.parseInt(e.slice(2,4),16),b:Number.parseInt(e.slice(4,6),16)}:null}function eu(r){let e=Le(r);return e?ru(e):null}function tu(r){let e=Le(r);return e?nu(e):null}function Ps(r){let e=Le(r);return e?su(e):null}function ru(r){let e=r.r/255,t=r.g/255,n=r.b/255,o=Math.max(e,t,n),i=Math.min(e,t,n),s=o-i,a=0;return s>0&&(o===e?a=60*((t-n)/s%6):o===t?a=60*((n-e)/s+2):a=60*((e-t)/s+4)),{h:T(a),s:o===0?0:s/o,v:o}}function nu(r){let e=r.r/255,t=r.g/255,n=r.b/255,o=Math.max(e,t,n),i=Math.min(e,t,n),s=o-i,a=(o+i)/2,l=0;return s>0&&(o===e?l=60*((t-n)/s%6):o===t?l=60*((n-e)/s+2):l=60*((e-t)/s+4)),{h:T(l),s:s===0?0:s/(1-Math.abs(2*a-1)),l:a}}function nr(r){return M(ou(r))}function ou(r){let e=Zs(r),t=e.h/60,n=e.v*e.s,o=n*(1-Math.abs(t%2-1)),i=e.v-n,s=0,a=0,l=0;return t<1?(s=n,a=o):t<2?(s=o,a=n):t<3?(a=n,l=o):t<4?(a=o,l=n):t<5?(s=o,l=n):(s=n,l=o),{r:(s+i)*255,g:(a+i)*255,b:(l+i)*255}}function hr(r){return M(iu(r))}function iu(r){let e=Zn(r),t=e.h/60,n=(1-Math.abs(2*e.l-1))*e.s,o=n*(1-Math.abs(t%2-1)),i=e.l-n/2,s=0,a=0,l=0;return t<1?(s=n,a=o):t<2?(s=o,a=n):t<3?(a=n,l=o):t<4?(a=o,l=n):t<5?(s=o,l=n):(s=n,l=o),{r:(s+i)*255,g:(a+i)*255,b:(l+i)*255}}function Re(r){return M(au(r))}function su(r){let e=lu(r),t=_n(e.x/.95047),n=_n(e.y),o=_n(e.z/1.08883);return{l:116*n-16,a:500*(t-n),b:200*(n-o)}}function au(r){let e={l:Math.min(gt,Math.max(pe,Number.isFinite(r.l)?r.l:0)),a:Math.min(ve,Math.max(Se,Number.isFinite(r.a)?r.a:0)),b:Math.min(ve,Math.max(Se,Number.isFinite(r.b)?r.b:0))},t=(e.l+16)/116,n=e.a/500+t,o=t-e.b/200,i={x:.95047*On(n),y:On(t),z:1.08883*On(o)};return cu(i)}function lu(r){let e=Hn(lr(r.r)/255),t=Hn(lr(r.g)/255),n=Hn(lr(r.b)/255);return{x:e*.4124564+t*.3575761+n*.1804375,y:e*.2126729+t*.7151522+n*.072175,z:e*.0193339+t*.119192+n*.9503041}}function cu(r){let e=r.x*3.2404542+r.y*-1.5371385+r.z*-.4985314,t=r.x*-.969266+r.y*1.8760108+r.z*.041556,n=r.x*.0556434+r.y*-.2040259+r.z*1.0572252;return{r:Bn(e)*255,g:Bn(t)*255,b:Bn(n)*255}}function Hn(r){return r<=.04045?r/12.92:((r+.055)/1.055)**2.4}function Bn(r){let e=Math.min(1,Math.max(0,r));return e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055}function _n(r){return r>216/24389?Math.cbrt(r):841/108*r+4/29}function On(r){let e=r**3;return e>216/24389?e:108/841*(r-4/29)}function St(r,e,t){return{r:Math.round(r.r+(e.r-r.r)*t),g:Math.round(r.g+(e.g-r.g)*t),b:Math.round(r.b+(e.b-r.b)*t)}}function M(r){return`#${[r.r,r.g,r.b].map(e=>lr(e).toString(16).padStart(2,"0")).join("")}`}function lr(r){return Math.min(255,Math.max(0,Math.round(r)))}function L(r){let e=Number.isFinite(r)?r:xe,t=Math.round(e/mt)*mt;return Math.min($e,Math.max(xe,t))}function De(r){let e=Number.isFinite(r)?r:pe,t=Math.round(e/Ie)*Ie;return Math.min(gt,Math.max(pe,t))}function F(r){let e=Number.isFinite(r)?r:0,t=Math.round(e/Ie)*Ie;return Math.min(ve,Math.max(Se,t))}function Js(r){return{l:De(r.l),a:F(r.a),b:F(r.b)}}function N(r){return Math.min(1,Math.max(0,Number.isFinite(r)?r:0))}function T(r){return Number.isFinite(r)?(r%360+360)%360:0}function We(r){return`${y(r)} px`}function Ts(r){return`${x(r)}%`}function Ue(r){return`${f(r)}%`}function Ye(r){return(f(r)/100).toString()}function Vn(r){let e=1-x(r.hardness)/100;return e<=0?0:v(Math.max(0,r.width*e*.35))}function xs(r,e,t){let n={x:v(r),y:v(e)},o=du(t);return o!==void 0&&(n.pressure=o),n}function du(r){if(uu(r))return Rt(r.pressure)}function uu(r){return cr(r)}function cr(r){return r.pointerType==="pen"}function hu(r,e){let t=e.getBoundingClientRect();return r.clientX>=t.left&&r.clientX<=t.right&&r.clientY>=t.top&&r.clientY<=t.bottom}function Is(r){let e=Math.max(Math.hypot(r.a,r.b),Math.hypot(r.c,r.d));return Number.isFinite(e)&&e>0?e:1}function pu(r){return typeof r.getCoalescedEvents=="function"?r.getCoalescedEvents():[]}function or(r,e,t){return{...r,points:r.points.slice(e,t)}}function Pe(r){return r.points.some(e=>e.pressure!==void 0)}function Fn(r){return r.shiftKey||r.ctrlKey||r.metaKey}function Rs(r){return r.code==="Space"||r.key===" "}function Su(r){return r.key==="1"&&!r.altKey&&!r.ctrlKey&&!r.metaKey&&!r.shiftKey}function ir(r){return r instanceof HTMLElement?r.isContentEditable||r.instanceOf(HTMLInputElement)||r.instanceOf(HTMLTextAreaElement)||r.instanceOf(HTMLSelectElement):!1}function Ns(r){return r instanceof Element?!!r.closest(".canvas-node, .canvas-edge, .canvas-card-menu, .canvas-menu, .canvas-menu-container, .canvas-controls, .canvas-control-group, .canvas-control-item"):!1}function Ls(r){return r instanceof Element?!!r.closest(".canvas-menu, .canvas-menu-container, .canvas-controls, .canvas-control-group, .canvas-control-item, .draw-in-canvas-brush-controls, .draw-in-canvas-color-palette, .draw-in-canvas-stroke-settings-palette"):!1}function Xe(r){return r!==null}function de(r,e){return Math.hypot(r.x-e.x,r.y-e.y)}function vu(r){let e=0;for(let t=1;t<r.length;t++){let n=r[t-1],o=r[t];n&&o&&(e+=de(n,o))}return e}function mu(r,e,t){let n=e[0];if(!n)return Number.POSITIVE_INFINITY;if(e.length===1)return de(r,n);let o=Number.POSITIVE_INFINITY;for(let i=1;i<e.length;i++){let s=e[i-1],a=e[i];if(!(!s||!a)&&(o=Math.min(o,gu(r,s,a)),t!==void 0&&o<=t))return o}return o}function gu(r,e,t){let n=t.x-e.x,o=t.y-e.y,i=n*n+o*o;if(i===0)return de(r,e);let s=Math.max(0,Math.min(1,((r.x-e.x)*n+(r.y-e.y)*o)/i)),a={x:e.x+s*n,y:e.y+s*o};return de(r,a)}function fu(r){let e=r.points[0];if(!e)return null;let t=e.x,n=e.x,o=e.y,i=e.y;for(let s=1;s<r.points.length;s++){let a=r.points[s];a&&(t=Math.min(t,a.x),n=Math.max(n,a.x),o=Math.min(o,a.y),i=Math.max(i,a.y))}return{minX:t,minY:o,maxX:n,maxY:i}}function Cu(r,e){return{minX:Math.min(r.minX,e.minX),minY:Math.min(r.minY,e.minY),maxX:Math.max(r.maxX,e.maxX),maxY:Math.max(r.maxY,e.maxY)}}function yu(r,e){return{minX:Math.min(r.x,e.x),minY:Math.min(r.y,e.y),maxX:Math.max(r.x,e.x),maxY:Math.max(r.y,e.y)}}function zn(r,e,t=0){return r.minX<=e.maxX+t&&r.maxX>=e.minX-t&&r.minY<=e.maxY+t&&r.maxY>=e.minY-t}function Ds(r,e,t){return r.x>=e.minX-t&&r.x<=e.maxX+t&&r.y>=e.minY-t&&r.y<=e.maxY+t}function qe(r,e){return{minX:r.minX-e,minY:r.minY-e,maxX:r.maxX+e,maxY:r.maxY+e}}function Eu(r){return{x:(r.minX+r.maxX)/2,y:(r.minY+r.maxY)/2}}function As(r,e,t){return Math.min(t,Math.max(e,r))}function ku(r,e){let t=r.indexOf(e);t!==-1&&r.splice(t,1)}function sr(r,e){switch(e){case"nw":return{x:r.minX,y:r.minY};case"ne":return{x:r.maxX,y:r.minY};case"se":return{x:r.maxX,y:r.maxY};case"sw":return{x:r.minX,y:r.maxY};default:return Ae(e)}}function bu(r){switch(r){case"nw":return"se";case"ne":return"sw";case"se":return"nw";case"sw":return"ne";default:return Ae(r)}}function Kn(r){switch(r){case"nw":case"se":return"nwse-resize";case"ne":case"sw":return"nesw-resize";default:return Ae(r)}}function wu(r,e){for(let t of r)t.x=v(t.x+e.x),t.y=v(t.y+e.y)}function Pu(r,e,t){for(let n of r)n.x=v(e.x+(n.x-e.x)*t),n.y=v(e.y+(n.y-e.y)*t)}function Ms(r,e){return{minX:v(r.minX+e.x),minY:v(r.minY+e.y),maxX:v(r.maxX+e.x),maxY:v(r.maxY+e.y)}}function Hs(r,e,t){let n=ar({x:r.minX,y:r.minY},e,t),o=ar({x:r.maxX,y:r.minY},e,t),i=ar({x:r.maxX,y:r.maxY},e,t),s=ar({x:r.minX,y:r.maxY},e,t);return{minX:Math.min(n.x,o.x,i.x,s.x),minY:Math.min(n.y,o.y,i.y,s.y),maxX:Math.max(n.x,o.x,i.x,s.x),maxY:Math.max(n.y,o.y,i.y,s.y)}}function ar(r,e,t){return{x:v(e.x+(r.x-e.x)*t),y:v(e.y+(r.y-e.y)*t)}}function Bs(r){return{x:-r.x,y:-r.y}}function Tu(r){return`translate(${r.x} ${r.y})`}function xu(r,e){let t=Iu(e);return`translate(${r.x} ${r.y}) scale(${t}) translate(${-r.x} ${-r.y})`}function Iu(r){return Number(r.toFixed(4)).toString()}function dr(r){let e={x:r.x,y:r.y};return r.pressure!==void 0&&(e.pressure=r.pressure),e}function Ru(r){return r.map(dr)}function Ze(r){return{...r,handwriting:{...r.handwriting},points:Ru(r.points)}}function pr(r){return r.map(Ze)}function Nu(r){return{...r}}function Lu(r){return r.map(Nu)}function Du(r){return{strokeId:r.strokeId,previousStyle:q(r.previousStyle),nextStyle:q(r.nextStyle)}}function Au(r){return r.map(Du)}function Gn(r){switch(r.type){case"add-stroke":return{type:"add-stroke",stroke:Ze(r.stroke)};case"clear-strokes":return{type:"clear-strokes",strokes:pr(r.strokes)};case"delete-strokes":return{type:"delete-strokes",strokes:pr(r.strokes),indices:[...r.indices]};case"reorder-strokes":return{type:"reorder-strokes",beforeStrokeIds:[...r.beforeStrokeIds],afterStrokeIds:[...r.afterStrokeIds],selectedStrokeIds:[...r.selectedStrokeIds]};case"recolor-strokes":return{type:"recolor-strokes",changes:Lu(r.changes)};case"restyle-strokes":return{type:"restyle-strokes",changes:Au(r.changes)};case"move-stroke":return{type:"move-stroke",strokeId:r.strokeId,delta:dr(r.delta)};case"move-strokes":return{type:"move-strokes",strokeIds:[...r.strokeIds],delta:dr(r.delta)};case"resize-strokes":return{type:"resize-strokes",strokeIds:[...r.strokeIds],origin:dr(r.origin),scale:r.scale};default:return Ae(r)}}function Mu(r){return Number.isFinite(r.minX)&&Number.isFinite(r.minY)&&Number.isFinite(r.maxX)&&Number.isFinite(r.maxY)&&r.minX<=r.maxX&&r.minY<=r.maxY}function Ae(r){throw new Error(`Unexpected history action: ${JSON.stringify(r)}`)}var mr=class extends Y.Plugin{constructor(){super(...arguments);this.settings={...Ce};this.activeLayer=null;this.activeTarget=null;this.layers=new Set;this.isSyncing=!1;this.needsSync=!1}async onload(){await this.loadSettings(),jn(activeDocument),this.addCommand({id:"toggle-drawing-mode",name:"Toggle drawing mode on active canvas",callback:()=>{this.toggleDrawingMode()}}),this.addCommand({id:"undo-last-stroke",name:"Undo last canvas drawing stroke",callback:()=>{this.undoLastStroke()}}),this.addCommand({id:"redo-last-stroke",name:"Redo last canvas drawing stroke",callback:()=>{this.redoLastStroke()}}),this.addCommand({id:"clear-drawings",name:"Clear drawings from active canvas",callback:()=>{this.clearActiveCanvasDrawings()}}),this.addSettingTab(new kt(this.app,this)),this.app.workspace.onLayoutReady(()=>{this.syncActiveCanvasLayer()}),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>{this.syncActiveCanvasLayer()})),this.registerEvent(this.app.workspace.on("file-open",()=>{this.syncActiveCanvasLayer()}))}onunload(){this.stopActiveCanvasLayer(),jn(activeDocument)}async toggleDrawingMode(){let t=await this.ensureActiveCanvasLayer();if(!t){new Y.Notice("Open a canvas file before enabling drawing mode.");return}this.toggleLayerDrawingMode(t)}async disableDrawingMode(t){var n;(n=this.activeLayer)!=null&&n.isDrawingEnabled()&&this.activeLayer.disableDrawingMode()}async clearActiveCanvasDrawings(){let t=await this.ensureActiveCanvasLayer();if(!t){new Y.Notice("Open a canvas file before clearing drawing strokes.");return}await t.clear(),new Y.Notice("Draw in canvas strokes cleared.")}async undoLastStroke(){let t=await this.ensureActiveCanvasLayer();if(!t){new Y.Notice("Open a canvas file before undoing a stroke.");return}let n=await t.undoLastStroke();new Y.Notice(n?"Last Draw in canvas stroke removed.":"No Draw in canvas strokes to undo.")}async redoLastStroke(){let t=await this.ensureActiveCanvasLayer();if(!t){new Y.Notice("Open a canvas file before redoing a stroke.");return}let n=await t.redoLastStroke();new Y.Notice(n?"Last Draw in canvas stroke restored.":"No Draw in canvas strokes to redo.")}refreshActiveLayerSettings(){var t;for(let n of this.layers)n.setSettings(this.settings);(t=this.activeLayer)==null||t.setSettings(this.settings)}setStrokeColor(t){var n;this.settings.strokeColor=t;for(let o of this.layers)o.setSettings(this.settings);(n=this.activeLayer)==null||n.setSettings(this.settings),this.saveSettings()}setStrokeWidth(t){var o;let n=y(t);this.settings.strokeWidth=n;for(let i of this.layers)i.setSettings(this.settings);(o=this.activeLayer)==null||o.setSettings(this.settings),this.saveSettings()}setStrokeHardness(t){var o;let n=x(t);this.settings.strokeHardness=n;for(let i of this.layers)i.setSettings(this.settings);(o=this.activeLayer)==null||o.setSettings(this.settings),this.saveSettings()}setStrokeOpacity(t){var o;let n=f(t);this.settings.strokeOpacity=n;for(let i of this.layers)i.setSettings(this.settings);(o=this.activeLayer)==null||o.setSettings(this.settings),this.saveSettings()}setFreehandSliderValue(t,n){this.settings[t]=k(t,n),this.refreshActiveLayerSettings(),this.saveSettings()}setBeautifulStrokes(t){this.settings.beautifulStrokes=t,this.refreshActiveLayerSettings(),this.saveSettings()}setPenCursorFallback(t){this.settings.usePenCursorFallback=t,this.refreshActiveLayerSettings(),this.saveSettings()}setAllowTinyCanvasElements(t){this.settings.allowTinyCanvasElements=t,this.refreshActiveLayerSettings(),this.saveSettings()}async loadSettings(){this.settings=oo(await this.loadData())}async saveSettings(){await this.saveData(this.settings)}async ensureActiveCanvasLayer(){return await this.syncActiveCanvasLayer(),this.activeLayer}async syncActiveCanvasLayer(){if(this.isSyncing){this.needsSync=!0;return}this.isSyncing=!0;try{do this.needsSync=!1,await this.syncActiveCanvasLayerOnce();while(this.needsSync)}finally{this.isSyncing=!1}}async syncActiveCanvasLayerOnce(){let t=no(this.app);if(!t){await this.stopActiveCanvasLayer();return}if(this.activeLayer&&this.activeTarget&&Hu(this.activeTarget,t)){this.activeLayer.setSettings(this.settings);return}await this.stopActiveCanvasLayer();let n=null;try{n=new ur(this.app,t,this.settings,()=>{this.toggleActiveLayerDrawingMode()},o=>{this.setStrokeColor(o)},o=>{this.setStrokeWidth(o)},o=>{this.setStrokeHardness(o)},o=>{this.setStrokeOpacity(o)},(o,i)=>{this.setFreehandSliderValue(o,i)},o=>{this.setBeautifulStrokes(o)}),this.layers.add(n),await n.start(),this.activeLayer=n,this.activeTarget=t}catch(o){n&&(this.layers.delete(n),await n.stop()),console.error("Draw in canvas could not start",o),new Y.Notice(`Draw in canvas could not start: ${Bu(o)}`)}}toggleActiveLayerDrawingMode(){this.activeLayer&&this.toggleLayerDrawingMode(this.activeLayer)}toggleLayerDrawingMode(t){t.isDrawingEnabled()?t.disableDrawingMode():t.enableDrawingMode()}async stopActiveCanvasLayer(){let t=new Set(this.layers);this.activeLayer&&t.add(this.activeLayer),this.layers.clear(),this.activeLayer=null,this.activeTarget=null;for(let n of t)await n.stop()}};function Hu(r,e){return r.leaf===e.leaf&&r.file.path===e.file.path}function Bu(r){return r instanceof Error?r.message:String(r)}
/* nosourcemap */