@magicpages/kalotyp 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kalotyp.js CHANGED
@@ -1,103 +1,3 @@
1
- (function(it,rt){typeof exports=="object"&&typeof module<"u"?rt(exports):typeof define=="function"&&define.amd?define(["exports"],rt):(it=typeof globalThis<"u"?globalThis:it||self,rt(it.pintura={}))})(this,function(it){"use strict";class rt{listeners=new Map;on(e,n){let o=this.listeners.get(e);return o||(o=new Set,this.listeners.set(e,o)),o.add(n),()=>{o?.delete(n)}}off(e,n){this.listeners.get(e)?.delete(n)}emit(e,n){const o=this.listeners.get(e);if(o)for(const i of[...o])try{i(n)}catch(r){queueMicrotask(()=>{throw r})}}clear(){this.listeners.clear()}}async function oo(t){if(typeof createImageBitmap=="function"){const e=await io(t);if(e)try{const n=await createImageBitmap(e,{imageOrientation:"from-image"});return{element:n,width:n.width,height:n.height}}catch{}}return ro(t)}async function io(t){if(t instanceof Blob)return t;if(typeof fetch!="function")return null;try{const e=await fetch(t,{credentials:"omit"});return e.ok?await e.blob():null}catch{return null}}async function ro(t){const e=typeof t=="string"?t:URL.createObjectURL(t),n=typeof t!="string";try{const o=await new Promise((i,r)=>{const a=new Image;a.crossOrigin="anonymous",a.onload=()=>i(a),a.onerror=()=>r(new Error(`Failed to load image: ${e}`)),a.src=e});return{element:o,width:o.naturalWidth,height:o.naturalHeight}}finally{n&&URL.revokeObjectURL(e)}}const Ct=Object.freeze({zoom:1,panX:0,panY:0});function j(t,e,n=Ct){const o=Math.max(0,t.width-t.padding*2),i=Math.max(0,t.height-t.padding*2);if(e.width<=0||e.height<=0||o<=0||i<=0)return{displayRect:{x:t.padding,y:t.padding,width:0,height:0},scale:0};const r=Math.min(o/e.width,i/e.height),a=Math.max(0,n.zoom||0),s=r*a,c=e.width*s,l=e.height*s,u=t.padding+(o-c)/2,d=t.padding+(i-l)/2,h=u+n.panX,f=d+n.panY,m=ye(h,u,c,o,t.padding),g=ye(f,d,l,i,t.padding);return{displayRect:{x:m,y:g,width:c,height:l},scale:s}}function ye(t,e,n,o,i){if(n<=o)return e;const r=i,a=i+o,s=r+1-n,c=a-1;return t<s?s:t>c?c:t}function Wt(t,e){return e.scale===0?{x:0,y:0}:{x:(t.x-e.displayRect.x)/e.scale,y:(t.y-e.displayRect.y)/e.scale}}function be(t,e){return{x:e.displayRect.x+t.x*e.scale,y:e.displayRect.y+t.y*e.scale,width:t.width*e.scale,height:t.height*e.scale}}const we=8,Ce=.25;class ao{current;isPinching;listeners;constructor(e=Ct){this.current=ve(e),this.isPinching=!1,this.listeners=new Set}getTransform(){return this.current}getSnapshot(){return{transform:this.current,pinching:this.isPinching}}setTransform(e){const n=ve(e);ke(this.current,n)||(this.current=n,this.emit())}zoomAt(e,n,o){if(!Number.isFinite(e)||e<=0)return this.current;const i=this.current.zoom,r=i*e,a=xe(r,Ce,we);if(a===i)return this.current;const s=a/i,c=n.x-o.x,l=n.y-o.y,u=s*this.current.panX+(1-s)*c,d=s*this.current.panY+(1-s)*l;return this.current={zoom:a,panX:u,panY:d},this.emit(),this.current}panBy(e,n){e===0&&n===0||(this.current={zoom:this.current.zoom,panX:this.current.panX+e,panY:this.current.panY+n},this.emit())}resetToFit(){ke(this.current,Ct)||(this.current=Ct,this.emit())}resetPan(){this.current.panX===0&&this.current.panY===0||(this.current={zoom:this.current.zoom,panX:0,panY:0},this.emit())}getPinching(){return this.isPinching}setPinching(e){this.isPinching!==e&&(this.isPinching=e,this.emit())}computeViewport(e,n){return j(e,n,this.current)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear()}emit(){const e=this.getSnapshot();for(const n of this.listeners)n(e)}}function xe(t,e,n){return t<e?e:t>n?n:t}function ve(t){const e=xe(Number.isFinite(t.zoom)?t.zoom:1,Ce,we),n=Number.isFinite(t.panX)?t.panX:0,o=Number.isFinite(t.panY)?t.panY:0;return{zoom:e,panX:n,panY:o}}function ke(t,e){return t.zoom===e.zoom&&t.panX===e.panX&&t.panY===e.panY}function Q(t,e){if(so())return{kind:"offscreen",canvas:new OffscreenCanvas(t,e)};const n=document.createElement("canvas");return n.width=t,n.height=e,{kind:"html",canvas:n}}function et(t){if(t.kind==="offscreen"){const n=t.canvas.getContext("2d");if(!n)throw new Error("2D canvas context is not available");return n}const e=t.canvas.getContext("2d");if(!e)throw new Error("2D canvas context is not available");return e}async function Se(t,e,n){return t.kind==="offscreen"?t.canvas.convertToBlob({type:e,quality:n}):new Promise((o,i)=>{t.canvas.toBlob(r=>{r?o(r):i(new Error("toBlob produced null"))},e,n)})}function so(){return typeof OffscreenCanvas>"u"?!1:typeof OffscreenCanvas.prototype.convertToBlob=="function"}const Ee=new Map;function dt(t){const e=Ee.get(t);if(e)return e;const n=(async()=>{try{const o=Q(1,1),i=await Se(o,t,.5);return i.type===t&&i.size>0}catch{return!1}})();return Ee.set(t,n),n}function co(t,e,n,o){const i={x:t.x+e,y:t.y+n,width:t.width,height:t.height};return xt(i,o)}function xt(t,e){let{x:n,y:o,width:i,height:r}=t;return i>e.width&&(i=e.width),r>e.height&&(r=e.height),n<e.x&&(n=e.x),o<e.y&&(o=e.y),n+i>e.x+e.width&&(n=e.x+e.width-i),o+r>e.y+e.height&&(o=e.y+e.height-r),{x:n,y:o,width:i,height:r}}function lo(t){return{x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)}}function Ae(t){let e=t;const n=new Set;function o(i){for(const r of[...n])try{r(e,i)}catch(a){queueMicrotask(()=>{throw a})}}return{get(){return e},set(i){const r=e;e={...e,...i},o(r)},update(i){const r=e;e={...e,...i(e)},o(r)},subscribe(i){return n.add(i),()=>n.delete(i)}}}const Me=50;class uo{shadow;undoStack=[];redoStack=[];constructor(e){this.shadow=vt(e)}commit(e){ho(e,this.shadow)||(this.undoStack.push(this.shadow),this.undoStack.length>Me&&this.undoStack.shift(),this.shadow=vt(e),this.redoStack.length=0)}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undo(e){const n=this.undoStack.pop();return n?(this.redoStack.push(vt(e)),this.shadow=n,{snapshot:n,changed:Ie(e,n)}):null}redo(e){const n=this.redoStack.pop();return n?(this.undoStack.push(vt(e)),this.undoStack.length>Me&&this.undoStack.shift(),this.shadow=n,{snapshot:n,changed:Ie(e,n)}):null}size(){return{undo:this.undoStack.length,redo:this.redoStack.length}}}function ho(t,e){if(t.size!==e.size)return!1;for(const[n,o]of t)if(!e.has(n)||kt(o)!==kt(e.get(n)))return!1;return!0}function Ie(t,e){const n=new Set;for(const[o,i]of e)kt(i)!==kt(t.get(o))&&n.add(o);for(const o of t.keys())e.has(o)||n.add(o);return n}function vt(t){const e=new Map;for(const[n,o]of t)e.set(n,structuredClone(o));return e}function kt(t){return JSON.stringify(t,(e,n)=>{if(n&&typeof n=="object"&&!Array.isArray(n)){const o={};for(const i of Object.keys(n).sort())o[i]=n[i];return o}return n})}function qt(t,e){if(e<=0||t.width<=0||t.height<=0)return{x:t.x,y:t.y,width:0,height:0};const n=t.width/t.height;let o,i;return e>=n?(o=t.width,i=o/e):(i=t.height,o=i*e),{x:t.x+(t.width-o)/2,y:t.y+(t.height-i)/2,width:o,height:i}}function po(t,e,n,o){if(e<=0)return t;if(t.width<=0||t.height<=0)return qt(o,e);const i=t.width/t.height;let r,a;i>e?(a=t.height,r=a*e):(r=t.width,a=r/e);const s=Re(t,r,a,n),c=xt(s,o),l=c.height===0?0:c.width/c.height;return Math.abs(l-e)<=mo?c:fo(c,e,n)}const mo=1e-6;function Re(t,e,n,o){switch(o){case"tl":return{x:t.x,y:t.y,width:e,height:n};case"tr":return{x:t.x+t.width-e,y:t.y,width:e,height:n};case"bl":return{x:t.x,y:t.y+t.height-n,width:e,height:n};case"br":return{x:t.x+t.width-e,y:t.y+t.height-n,width:e,height:n};case"center":return{x:t.x+(t.width-e)/2,y:t.y+(t.height-n)/2,width:e,height:n}}}function fo(t,e,n){const o=qt(t,e);return Re(t,o.width,o.height,n)}function go(t,e,n,o){const i=o.minSize??1,r=t.x,a=t.y,s=t.x+t.width,c=t.y+t.height;let l=r,u=a,d=s,h=c;(e==="tl"||e==="l"||e==="bl")&&(l=n.x),(e==="tr"||e==="r"||e==="br")&&(d=n.x),(e==="tl"||e==="t"||e==="tr")&&(u=n.y),(e==="bl"||e==="b"||e==="br")&&(h=n.y),(e==="l"||e==="r")&&(u=a,h=c),(e==="t"||e==="b")&&(l=r,d=s);let f=Math.min(l,d),m=Math.min(u,h),g=Math.abs(d-l),p=Math.abs(h-u);g<i&&(g=i,e==="tl"||e==="l"||e==="bl"?f=s-i:(e==="tr"||e==="r"||e==="br")&&(f=r)),p<i&&(p=i,e==="tl"||e==="t"||e==="tr"?m=c-i:(e==="bl"||e==="b"||e==="br")&&(m=a));let w={x:f,y:m,width:g,height:p};return w=xt(w,o.bounds),o.aspectRatio!==void 0&&o.aspectRatio>0&&(w=po(w,o.aspectRatio,yo(e),o.bounds)),w}function yo(t){switch(t){case"tl":return"br";case"tr":return"bl";case"bl":return"tr";case"br":return"tl";case"t":return"bl";case"b":return"tl";case"l":return"tr";case"r":return"tl"}}function bo(t,e){const[n]=t;return n===void 0||e===void 0?!0:e==="landscape"?n>=1:e==="portrait"?n<1:!0}function wo(t,e){return t.filter(n=>bo(n,e))}function Co(t){return{rect:{x:0,y:0,width:t.imageSize.width,height:t.imageSize.height},aspectRatio:void 0,activePresetIndex:vo(t.presets),presets:t.presets,imageSize:t.imageSize}}function xo(t,e){const n=t.presets[e];if(!n)return t;const[o]=n;if(o===void 0)return{...t,aspectRatio:void 0,activePresetIndex:e};const i={x:0,y:0,width:t.imageSize.width,height:t.imageSize.height},r=qt(i,o);return{...t,rect:r,aspectRatio:o,activePresetIndex:e}}function vo(t){return t.findIndex(([e])=>e===void 0)}function ko(t,e){const n=lo(e.rect),o=St(n.x,0,t.width),i=St(n.y,0,t.height),r=St(n.width,1,t.width-o),a=St(n.height,1,t.height-i),s=Q(r,a);if(s.kind==="offscreen"){const l=s.canvas.getContext("2d");if(!l)throw new Error("2D canvas context is not available");return l.drawImage(t.bitmap,o,i,r,a,0,0,r,a),{bitmap:s.canvas,width:r,height:a,mimeType:t.mimeType}}const c=s.canvas.getContext("2d");if(!c)throw new Error("2D canvas context is not available");return c.drawImage(t.bitmap,o,i,r,a,0,0,r,a),{bitmap:s.canvas,width:r,height:a,mimeType:t.mimeType}}function St(t,e,n){return Math.max(e,Math.min(n,t))}const Ne={mimeChoice:"auto",quality:.85};function Le(t){return Number.isFinite(t)?t<0?0:t>1?1:t:Ne.quality}function So(t,e){return t.mimeChoice===e?t:{...t,mimeChoice:e}}function Eo(t,e){const n=Le(e);return t.quality===n?t:{...t,quality:n}}function Ao(t,e){return t.stripMetadata===e?t:{...t,stripMetadata:e}}const Te=[255,216],Fe=[255,225],Pe=[69,120,105,102,0,0];async function Mo(t){if(t.output.type&&t.output.type!=="image/jpeg")return t.output;const e=await $e(t.source);if(!De(e,Te))return t.output;const n=Io(e);if(!n)return t.output;const o=await $e(t.output);if(!De(o,Te))return t.output;const i=new Uint8Array(o.length+n.length);return i.set(o.subarray(0,2),0),i.set(n,2),i.set(o.subarray(2),2+n.length),new Blob([i],{type:"image/jpeg"})}async function $e(t){return typeof t.arrayBuffer=="function"?new Uint8Array(await t.arrayBuffer()):new Promise((e,n)=>{const o=new FileReader;o.onload=()=>{const i=o.result;i instanceof ArrayBuffer?e(new Uint8Array(i)):n(new Error("FileReader returned a non-ArrayBuffer result"))},o.onerror=()=>n(o.error??new Error("FileReader failed")),o.readAsArrayBuffer(t)})}function De(t,e){if(t.length<e.length)return!1;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return!1;return!0}function Io(t){let e=2;for(;e+4<=t.length;){if(t[e]!==255)return;const n=t[e+1];if(n===void 0||n===218||n===217)return;const o=t[e+2]!==void 0&&t[e+3]!==void 0?t[e+2]*256+t[e+3]:0;if(o<2)return;const i=e+2+o;if(i>t.length)return;if(t[e]===Fe[0]&&t[e+1]===Fe[1]&&Ro(t,e+4))return t.slice(e,i);e=i}}function Ro(t,e){for(let n=0;n<Pe.length;n++)if(t[e+n]!==Pe[n])return!1;return!0}const He="image/png",No=new Set(["image/png","image/webp","image/avif"]);async function Lo(t,e){return t.mimeChoice!=="auto"?await dt(t.mimeChoice)?t.mimeChoice:await dt("image/webp")?"image/webp":He:await dt("image/webp")?"image/webp":!No.has(e.mimeType)&&await dt("image/jpeg")?"image/jpeg":He}function To(t,e){const n=Po(e);if(!t)return`kalotyp-image.${n}`;const o=$o(t);if(!o)return`kalotyp-image.${n}`;const i=Ho(o);return i?`${i}.${n}`:`kalotyp-image.${n}`}async function Fo(t,e={}){const n=e.output??Ne,o=await Lo(n,t),i=Le(n.quality),r=To(e.sourceName,o),a=Q(t.width,t.height);if(a.kind==="offscreen"){const u=a.canvas.getContext("2d");if(!u)throw new Error("2D canvas context is not available");u.drawImage(t.bitmap,0,0)}else{const u=a.canvas.getContext("2d");if(!u)throw new Error("2D canvas context is not available");u.drawImage(t.bitmap,0,0)}const s=await Se(a,o,i),l=e.output?.stripMetadata===!1&&o==="image/jpeg"&&t.mimeType==="image/jpeg"&&e.sourceBlob!==void 0?await Mo({source:e.sourceBlob,output:s}):s;return new File([l],r,{type:o})}function Po(t){if(t==="image/jpeg")return"jpg";if(t==="image/png")return"png";if(t==="image/webp")return"webp";if(t==="image/avif")return"avif";const e=t.split("/")[1];return e&&e.length>0?e:"bin"}function $o(t){const n=Do(t).split(/[/\\]/);return n[n.length-1]}function Do(t){const e=t.indexOf("?");return e===-1?t:t.slice(0,e)}function Ho(t){const e=t.lastIndexOf(".");return e<=0?t:t.slice(0,e)}async function Oo(t,e){let n=e;for(const o of t)n=await o.plugin.bake(o.state,n);return n}function zo(){return{horizontal:!1,vertical:!1}}function Oe(t,e){return e==="horizontal"?{...t,horizontal:!t.horizontal}:{...t,vertical:!t.vertical}}function ze(t){return!t.horizontal&&!t.vertical}async function Bo(t,e){if(ze(t))return e;const{width:n,height:o}=e,i=Q(n,o),r=et(i),a=t.horizontal?-1:1,s=t.vertical?-1:1,c=t.horizontal?n:0,l=t.vertical?o:0;return r.setTransform(a,0,0,s,c,l),r.drawImage(e.bitmap,0,0),{bitmap:i.canvas,width:n,height:o,mimeType:e.mimeType}}const Ut=-45,Xt=45,Be=.1;function _o(){return{quarterTurns:0,freeAngle:0}}function Wo(t){return{...t,quarterTurns:(t.quarterTurns+1)%4}}function qo(t){return{...t,quarterTurns:(t.quarterTurns+3)%4}}function _e(t,e){const n=Uo(e,Ut,Xt),o=Math.round(n*10)/10;return{...t,freeAngle:o}}function We(t){return t.quarterTurns===0&&Math.abs(t.freeAngle)<1e-6}function Yt(t){return t.quarterTurns*90+t.freeAngle}function Uo(t,e,n){return Math.max(e,Math.min(n,t))}function qe(t,e){const n=t.width,o=t.height;if(n<=0||o<=0)return{width:0,height:0};const i=Math.abs(Math.cos(e)),r=Math.abs(Math.sin(e)),a=n*i+o*r,s=n*r+o*i,c=a>Ue?n*n/a:Number.POSITIVE_INFINITY,l=s>Ue?n*o/s:Number.POSITIVE_INFINITY,u=Math.min(c,l),d=u*o/n;return{width:u,height:d}}const Ue=1e-9;async function Xo(t,e){if(We(t))return e;const n=Yt(t),o=n*Math.PI/180,i=n-t.quarterTurns*90,r=Math.abs(i)<1e-6;let a,s;if(r)t.quarterTurns===1||t.quarterTurns===3?(a=e.height,s=e.width):(a=e.width,s=e.height);else{const u=qe(e,o);a=Math.max(1,Math.round(u.width)),s=Math.max(1,Math.round(u.height))}const c=Q(a,s),l=et(c);return l.imageSmoothingEnabled=!0,l.imageSmoothingQuality="high",l.translate(a/2,s/2),l.rotate(o),l.drawImage(e.bitmap,-e.width/2,-e.height/2),{bitmap:c.canvas,width:a,height:s,mimeType:e.mimeType}}const ht=8e3,Et=1;function Yo(){return{scaleX:1,scaleY:1,lockAspect:!0}}function Xe(t){return Math.abs(t.scaleX-1)<1e-9&&Math.abs(t.scaleY-1)<1e-9}function Ye(t,e){const n=At(Math.round(e.width*t.scaleX)),o=At(Math.round(e.height*t.scaleY));return{width:n,height:o}}function Go(t,e,n){if(n.width<=0)return t;const i=At(Math.round(e))/n.width,r=t.lockAspect?i:t.scaleY;return{...t,scaleX:i,scaleY:r}}function Ko(t,e,n){if(n.height<=0)return t;const i=At(Math.round(e))/n.height,r=t.lockAspect?i:t.scaleX;return{...t,scaleX:r,scaleY:i}}function Vo(t,e){const n=Qo(e/100);return{...t,scaleX:n,scaleY:n}}function jo(t,e){if(t.lockAspect===e)return t;if(!e)return{...t,lockAspect:!1};const n=(t.scaleX+t.scaleY)/2;return{scaleX:n,scaleY:n,lockAspect:!0}}function At(t){return Number.isFinite(t)?Math.max(Et,Math.min(ht,Math.trunc(t))):Et}function Qo(t){return!Number.isFinite(t)||t<=0?.01:Math.max(.01,Math.min(t,ht))}async function Jo(t,e){if(Xe(t))return e;const{width:n,height:o}=Ye(t,e);if(n<=0||o<=0)return e;const i=Zo(e.width,e.height,n,o);let r={bitmap:e.bitmap,width:e.width,height:e.height};for(let s=0;s<i;s++){const c=Math.max(n,Math.floor(r.width/2)),l=Math.max(o,Math.floor(r.height/2));r={bitmap:Ge(r,c,l).canvas,width:c,height:l}}return{bitmap:Ge(r,n,o).canvas,width:n,height:o,mimeType:e.mimeType}}function Zo(t,e,n,o){let i=t,r=e,a=0;for(;(i/2>n||r/2>o)&&a<16;)i=Math.floor(i/2),r=Math.floor(r/2),a+=1;return a}function Ge(t,e,n){const o=Q(e,n),i=et(o);return i.imageSmoothingEnabled=!0,i.imageSmoothingQuality="high",i.drawImage(t.bitmap,0,0,t.width,t.height,0,0,e,n),o}const Mt=-100,It=100,Rt=1,pt={brightness:0,contrast:0,saturation:0,exposure:0,clarity:0,gamma:0},Ke=[{key:"brightness",label:"Brightness"},{key:"contrast",label:"Contrast"},{key:"saturation",label:"Saturation"},{key:"exposure",label:"Exposure"},{key:"clarity",label:"Clarity"},{key:"gamma",label:"Gamma"}];function ti(){return pt}function Gt(t){return t.brightness===0&&t.contrast===0&&t.saturation===0&&t.exposure===0&&t.clarity===0&&t.gamma===0}function Ve(t,e,n){const o=oi(n);return t[e]===o?t:{...t,[e]:o}}function ei(t,e){return t[e]===0?t:{...t,[e]:0}}function ni(){return pt}function oi(t){return Number.isNaN(t)?0:t<=Mt?Mt:t>=It?It:Math.round(t/Rt)*Rt}function je(t){const e=new Uint8ClampedArray(256),n=t.brightness/200,o=1+t.contrast/100,i=1+t.exposure/200,r=ii(t.gamma);for(let a=0;a<256;a++){let s=a/255;s=s*i,s=(s-.5)*o+.5,s=s+n,s<0?s=0:s>1&&(s=1),s=s**r,s<0?s=0:s>1&&(s=1),e[a]=Math.round(s*255)}return e}function ii(t){return t===0?1:t>0?1-.5*(t/100):1+1*(-t/100)}function Qe(t,e,n,o){const i=t.length;if(e.length!==i)throw new Error("applyFinetuneLutAndSaturation: src/dst length mismatch");const r=1+o.saturation/100;if(r===1){for(let a=0;a<i;a+=4)e[a]=n[t[a]],e[a+1]=n[t[a+1]],e[a+2]=n[t[a+2]],e[a+3]=t[a+3];return}for(let a=0;a<i;a+=4){const s=n[t[a]],c=n[t[a+1]],l=n[t[a+2]],u=.2126*s+.7152*c+.0722*l;let d=u+(s-u)*r,h=u+(c-u)*r,f=u+(l-u)*r;d<0?d=0:d>255&&(d=255),h<0?h=0:h>255&&(h=255),f<0?f=0:f>255&&(f=255),e[a]=d,e[a+1]=h,e[a+2]=f,e[a+3]=t[a+3]}}function Je(t,e,n){if(n===0)return;const o=t.length;if(e.length!==o)throw new Error("applyClarity: dst/blurred length mismatch");const i=n/100;for(let r=0;r<o;r+=4){const a=t[r],s=t[r+1],c=t[r+2];let l=a+i*(a-e[r]),u=s+i*(s-e[r+1]),d=c+i*(c-e[r+2]);l<0?l=0:l>255&&(l=255),u<0?u=0:u>255&&(u=255),d<0?d=0:d>255&&(d=255),t[r]=l,t[r+1]=u,t[r+2]=d}}function Ze(t,e,n,o,i){if(t.length!==e.length||t.length!==n.length)throw new Error("boxBlur3x3: buffer length mismatch");for(let r=0;r<i;r++)for(let a=0;a<o;a++){const s=a===0?0:a-1,c=a===o-1?o-1:a+1,l=(r*o+a)*4,u=(r*o+s)*4,d=(r*o+c)*4;e[l]=(t[u]+t[l]+t[d])/3,e[l+1]=(t[u+1]+t[l+1]+t[d+1])/3,e[l+2]=(t[u+2]+t[l+2]+t[d+2])/3,e[l+3]=t[l+3]}for(let r=0;r<i;r++){const a=r===0?0:r-1,s=r===i-1?i-1:r+1;for(let c=0;c<o;c++){const l=(r*o+c)*4,u=(a*o+c)*4,d=(s*o+c)*4;n[l]=(e[u]+e[l]+e[d])/3,n[l+1]=(e[u+1]+e[l+1]+e[d+1])/3,n[l+2]=(e[u+2]+e[l+2]+e[d+2])/3,n[l+3]=e[l+3]}}}function Kt(t,e,n){if(e.width!==n.width||e.height!==n.height||e.data.length!==n.data.length)throw new Error("applyFinetuneToImageData: baseline/dst dimensions mismatch");const o=je(t);if(Qe(e.data,n.data,o,t),t.clarity!==0){const i=new Uint8ClampedArray(e.data.length),r=new Uint8ClampedArray(e.data.length);Ze(e.data,i,r,e.width,e.height),Je(n.data,r,t.clarity)}}async function ri(t,e){if(Gt(t))return e;const n=Q(e.width,e.height),o=et(n);o.imageSmoothingEnabled=!0,o.imageSmoothingQuality="high",o.drawImage(e.bitmap,0,0,e.width,e.height);const i=o.getImageData(0,0,e.width,e.height);if(t.clarity===0)Kt(t,i,i),o.putImageData(i,0,0);else{const r=new ImageData(new Uint8ClampedArray(i.data.length),i.width,i.height);Kt(t,i,r),o.putImageData(r,0,0)}return{bitmap:n.canvas,width:e.width,height:e.height,mimeType:e.mimeType}}const Vt=[{id:"none",label:"None",state:pt},{id:"vivid",label:"Vivid",state:{brightness:0,contrast:10,saturation:40,exposure:0,clarity:5,gamma:0}},{id:"mono",label:"Mono",state:{brightness:0,contrast:15,saturation:-100,exposure:0,clarity:0,gamma:0}},{id:"soft",label:"Soft",state:{brightness:5,contrast:-10,saturation:0,exposure:0,clarity:-25,gamma:0}},{id:"punch",label:"Punch",state:{brightness:0,contrast:30,saturation:5,exposure:0,clarity:25,gamma:0}},{id:"mute",label:"Mute",state:{brightness:0,contrast:5,saturation:-50,exposure:0,clarity:-5,gamma:0}},{id:"bright",label:"Bright",state:{brightness:5,contrast:5,saturation:0,exposure:15,clarity:0,gamma:0}}];function ai(t,e){return t.brightness===e.brightness&&t.contrast===e.contrast&&t.saturation===e.saturation&&t.exposure===e.exposure&&t.clarity===e.clarity&&t.gamma===e.gamma}function jt(t){for(const e of Vt)if(ai(e.state,t))return e}const si="rgba(255, 235, 59, 0.35)",ci=18,tn=32,li="#ff3b30",ui=4;function di(){return{color:li,strokeWidth:ui,fillColor:null,fontSize:tn}}function hi(t){return{shapes:[],selectedId:null,activeTool:"select",currentStyle:di(),imageSize:t.imageSize,nextShapeNumber:1}}function at(t){return{id:`s_${t.nextShapeNumber.toString(36)}`,nextShapeNumber:t.nextShapeNumber+1}}function Qt(t,e){return t.activeTool===e?t:{...t,activeTool:e,selectedId:e==="select"?t.selectedId:null}}function en(t,e){return{...t,currentStyle:{...t.currentStyle,...e}}}function mt(t,e){return t.selectedId===e?t:{...t,selectedId:e}}function st(t,e){return{...t,shapes:[...t.shapes,e],selectedId:e.id}}function nt(t,e){let n=!1;const o=t.shapes.map(i=>i.id!==e.id?i:(n=!0,e));return n?{...t,shapes:o}:t}function Nt(t,e){const n=t.shapes.filter(o=>o.id!==e);return n.length===t.shapes.length?t:{...t,shapes:n,selectedId:t.selectedId===e?null:t.selectedId}}function nn(t){let{x:e,y:n,width:o,height:i}=t;return o<0&&(e+=o,o=-o),i<0&&(n+=i,i=-i),{x:e,y:n,width:o,height:i}}function on(t,e,n){switch(t.kind){case"text":return{...t,x:t.x+e,y:t.y+n};case"rect":case"ellipse":return{...t,x:t.x+e,y:t.y+n};case"arrow":return{...t,x1:t.x1+e,y1:t.y1+n,x2:t.x2+e,y2:t.y2+n};case"freehand":case"highlight":return{...t,points:t.points.map(o=>({x:o.x+e,y:o.y+n}))};default:return Lt(t)}}function Lt(t){throw new Error(`Unhandled annotation shape kind: ${JSON.stringify(t)}`)}function rn(t){return t==="text"||t==="rect"||t==="ellipse"||t==="arrow"}function pi(t,e){const{imageSize:n,style:o,id:i}=e,r=Math.min(n.width,n.height),a=n.width/2,s=n.height/2;switch(t){case"rect":case"ellipse":{const c=Math.max(80,Math.round(r*.25)),l=Math.round(a-c/2),u=Math.round(s-c/2);return t==="rect"?{id:i,kind:"rect",x:l,y:u,width:c,height:c,strokeColor:o.color,strokeWidth:o.strokeWidth,fillColor:o.fillColor}:{id:i,kind:"ellipse",x:l,y:u,width:c,height:c,strokeColor:o.color,strokeWidth:o.strokeWidth,fillColor:o.fillColor}}case"arrow":{const c=Math.max(100,Math.round(r*.3)),l=Math.round(a-c/2),u=l+c,d=Math.round(s);return{id:i,kind:"arrow",x1:l,y1:d,x2:u,y2:d,color:o.color,strokeWidth:o.strokeWidth}}case"text":{const c=Math.round(a),l=Math.round(s-o.fontSize/2);return{id:i,kind:"text",x:c,y:l,text:"",fontSize:o.fontSize,color:o.color,textAlign:"center"}}}}function ft(t){switch(t.kind){case"text":{const{width:e,height:n}=fi(t.text,t.fontSize);return{x:gi(t.x,e,t.textAlign),y:t.y,width:e,height:n}}case"rect":case"ellipse":return{x:t.x,y:t.y,width:t.width,height:t.height};case"arrow":{const e=Math.min(t.x1,t.x2),n=Math.min(t.y1,t.y2);return{x:e,y:n,width:Math.abs(t.x2-t.x1),height:Math.abs(t.y2-t.y1)}}case"freehand":case"highlight":{const e=t.points[0];if(!e)return{x:0,y:0,width:0,height:0};let n=e.x,o=e.y,i=e.x,r=e.y;for(const a of t.points)a.x<n&&(n=a.x),a.x>i&&(i=a.x),a.y<o&&(o=a.y),a.y>r&&(r=a.y);return{x:n,y:o,width:i-n,height:r-o}}default:return Lt(t)}}const Tt=["tl","tr","bl","br","t","r","b","l"];function mi(t){const e=t.x,n=t.x+t.width,o=t.y,i=t.y+t.height,r=t.x+t.width/2,a=t.y+t.height/2;return{tl:{x:e,y:o},tr:{x:n,y:o},bl:{x:e,y:i},br:{x:n,y:i},t:{x:r,y:o},r:{x:n,y:a},b:{x:r,y:i},l:{x:e,y:a}}}function Jt(t,e,n){let o=t.x,i=t.y,r=t.x+t.width,a=t.y+t.height;return(e==="tl"||e==="l"||e==="bl")&&(o=n.x),(e==="tr"||e==="r"||e==="br")&&(r=n.x),(e==="tl"||e==="t"||e==="tr")&&(i=n.y),(e==="bl"||e==="b"||e==="br")&&(a=n.y),{x:o,y:i,width:r-o,height:a-i}}function fi(t,e){const n=t.length===0?[""]:t.split(`
2
- `);let o=0;for(const a of n)a.length>o&&(o=a.length);const i=Math.max(e*.6,o*e*.55),r=n.length*e*1.2;return{width:i,height:r}}function gi(t,e,n){switch(n){case"left":return t;case"center":return t-e/2;case"right":return t-e}}const ct=4;function yi(t,e){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o&&bi(o,e))return o}}function bi(t,e){switch(t.kind){case"text":return gt(e,ft(t));case"rect":{const n=gt(e,Ft(t));if(t.fillColor!==null)return n;const o=Zt(Ft(t),t.strokeWidth/2+ct),i=Zt(Ft(t),-(t.strokeWidth/2+ct));return gt(e,o)&&!gt(e,i)}case"ellipse":{const n=Ft(t),o=n.width/2,i=n.height/2,r=n.x+o,a=n.y+i;if(o<=0||i<=0)return!1;const s=(e.x-r)/o,c=(e.y-a)/i,l=s*s+c*c,u=(t.strokeWidth/2+ct)/Math.min(o,i);return t.fillColor!==null?l<=(1+u)**2:l<=(1+u)**2&&l>=(1-u)**2}case"arrow":return an(e,{x:t.x1,y:t.y1},{x:t.x2,y:t.y2},t.strokeWidth/2+ct);case"freehand":case"highlight":{const n=ft(t),o=Zt(n,t.strokeWidth/2+ct);if(!gt(e,o))return!1;const i=t.strokeWidth/2+ct;for(let r=1;r<t.points.length;r++){const a=t.points[r-1],s=t.points[r];if(a&&s&&an(e,a,s,i))return!0}if(t.points.length===1){const r=t.points[0];if(!r)return!1;const a=r.x-e.x,s=r.y-e.y;return a*a+s*s<=i*i}return!1}default:return Lt(t)}}function gt(t,e){return t.x>=e.x&&t.y>=e.y&&t.x<=e.x+e.width&&t.y<=e.y+e.height}function Zt(t,e){return{x:t.x-e,y:t.y-e,width:t.width+e*2,height:t.height+e*2}}function Ft(t){let{x:e,y:n,width:o,height:i}=t;return o<0&&(e+=o,o=-o),i<0&&(n+=i,i=-i),{x:e,y:n,width:o,height:i}}function an(t,e,n,o){const i=n.x-e.x,r=n.y-e.y,a=i*i+r*r;if(a===0){const h=t.x-e.x,f=t.y-e.y;return h*h+f*f<=o*o}let s=((t.x-e.x)*i+(t.y-e.y)*r)/a;s<0?s=0:s>1&&(s=1);const c=e.x+s*i,l=e.y+s*r,u=t.x-c,d=t.y-l;return u*u+d*d<=o*o}const sn=2;function wi(t){if(t.length<=1)return[...t];const e=t[0];if(!e)return[];const n=[e];let o=e;const i=sn*sn;for(let a=1;a<t.length-1;a++){const s=t[a];if(!s)continue;const c=s.x-o.x,l=s.y-o.y;c*c+l*l<i||(n.push(s),o=s)}const r=t[t.length-1];return r&&r!==o&&n.push(r),n}function cn(t,e){if(e.length===0)return;const n=e[0];if(!n)return;if(e.length===1){t.moveTo(n.x,n.y),t.lineTo(n.x,n.y);return}t.moveTo(n.x,n.y);for(let i=1;i<e.length-1;i++){const r=e[i],a=e[i+1];if(!r||!a)continue;const s=(r.x+a.x)/2,c=(r.y+a.y)/2;t.quadraticCurveTo(r.x,r.y,s,c)}const o=e[e.length-1];o&&t.lineTo(o.x,o.y)}const ln='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';async function Ci(t,e){if(t.shapes.length===0)return e;const n=Q(e.width,e.height),o=et(n);o.imageSmoothingEnabled=!0,o.imageSmoothingQuality="high",o.drawImage(e.bitmap,0,0,e.width,e.height);for(const i of t.shapes)te(o,i);return{bitmap:n.canvas,width:e.width,height:e.height,mimeType:e.mimeType}}function te(t,e){switch(e.kind){case"text":xi(t,e);return;case"rect":vi(t,e);return;case"ellipse":ki(t,e);return;case"arrow":Si(t,e);return;case"freehand":Ei(t,e);return;case"highlight":Ai(t,e);return;default:Lt(e)}}function xi(t,e){t.save(),t.fillStyle=e.color,t.font=`${e.fontSize}px ${ln}`,t.textAlign=e.textAlign,t.textBaseline="top";const n=e.text.length===0?[""]:e.text.split(`
3
- `),o=e.fontSize*1.2;for(let i=0;i<n.length;i++){const r=n[i];r!==void 0&&t.fillText(r,e.x,e.y+i*o)}t.restore()}function vi(t,e){t.save(),e.fillColor!==null&&(t.fillStyle=e.fillColor,t.fillRect(e.x,e.y,e.width,e.height)),e.strokeWidth>0&&(t.strokeStyle=e.strokeColor,t.lineWidth=e.strokeWidth,t.lineJoin="miter",t.strokeRect(e.x,e.y,e.width,e.height)),t.restore()}function ki(t,e){t.save();const n=e.width/2,o=e.height/2,i=e.x+n,r=e.y+o;t.beginPath(),t.ellipse(i,r,Math.max(0,n),Math.max(0,o),0,0,Math.PI*2),e.fillColor!==null&&(t.fillStyle=e.fillColor,t.fill()),e.strokeWidth>0&&(t.strokeStyle=e.strokeColor,t.lineWidth=e.strokeWidth,t.stroke()),t.restore()}function Si(t,e){const n=e.x2-e.x1,o=e.y2-e.y1,i=Math.sqrt(n*n+o*o);if(i<.5)return;t.save(),t.strokeStyle=e.color,t.fillStyle=e.color,t.lineWidth=e.strokeWidth,t.lineCap="round",t.lineJoin="round";const r=Math.min(Math.max(e.strokeWidth*5,28),i*.6),a=Math.max(e.strokeWidth*4,18),s=n/i,c=o/i,l=e.x2-s*r*.6,u=e.y2-c*r*.6;t.beginPath(),t.moveTo(e.x1,e.y1),t.lineTo(l,u),t.stroke();const d=e.x2-s*r,h=e.y2-c*r,f=-c,m=s;t.beginPath(),t.moveTo(e.x2,e.y2),t.lineTo(d+f*a/2,h+m*a/2),t.lineTo(d-f*a/2,h-m*a/2),t.closePath(),t.fill(),t.restore()}function Ei(t,e){e.points.length!==0&&(t.save(),t.strokeStyle=e.color,t.lineWidth=e.strokeWidth,t.lineCap="round",t.lineJoin="round",t.beginPath(),cn(t,e.points),t.stroke(),t.restore())}function Ai(t,e){e.points.length!==0&&(t.save(),t.globalCompositeOperation="multiply",t.strokeStyle=e.color,t.lineWidth=e.strokeWidth,t.lineCap="round",t.lineJoin="round",t.beginPath(),cn(t,e.points),t.stroke(),t.restore())}const Mi="#000000",Ii="pixelate";function Ri(t){return{regions:[],nextRegionNumber:1,selectedId:null,currentMode:Ii,currentColor:Mi,imageSize:t.imageSize}}function un(t){return{id:`r_${t.nextRegionNumber.toString(36)}`,nextRegionNumber:t.nextRegionNumber+1}}function dn(t,e){return{...t,regions:[...t.regions,e],selectedId:e.id}}function J(t,e){let n=!1;const o=t.regions.map(i=>i.id!==e.id?i:(n=!0,e));return n?{...t,regions:o}:t}function hn(t,e){const n=t.regions.filter(o=>o.id!==e);return n.length===t.regions.length?t:{...t,regions:n,selectedId:t.selectedId===e?null:t.selectedId}}function pn(t,e){return t.selectedId===e?t:{...t,selectedId:e}}function Ni(t,e){return t.currentMode===e?t:{...t,currentMode:e}}function Li(t,e){return t.currentColor===e?t:{...t,currentColor:e}}function Ti(t,e,n){const o=t.regions.find(i=>i.id===e);return!o||o.mode===n?t:J(t,{...o,mode:n})}function Fi(t,e,n){const o=t.regions.find(i=>i.id===e);return!o||o.color===n?t:J(t,{...o,color:n})}function lt(t){return t.selectedId===null?null:t.regions.find(e=>e.id===t.selectedId)??null}function Pi(t){let{x:e,y:n,width:o,height:i}=t;return o<0&&(e+=o,o=-o),i<0&&(n+=i,i=-i),{x:e,y:n,width:o,height:i}}function $i(t){const{imageSize:e,mode:n,color:o,id:i}=t,r=Math.min(e.width,e.height),a=Math.max(80,Math.round(r*.25)),s=e.width/2,c=e.height/2,l=Math.round(s-a/2),u=Math.round(c-a/2);return{id:i,x:l,y:u,width:a,height:a,mode:n,color:o}}function Di(t,e){if(t.imageSize.width===e.width&&t.imageSize.height===e.height)return t;const n=[];for(const i of t.regions)i.x+i.width<=0||i.y+i.height<=0||i.x>=e.width||i.y>=e.height||n.push(Hi(i,e));const o=t.selectedId!==null&&!n.some(i=>i.id===t.selectedId);return{...t,regions:n,imageSize:{width:e.width,height:e.height},selectedId:o?null:t.selectedId}}function Hi(t,e){const n=Math.max(0,t.x),o=Math.max(0,t.y),i=Math.min(e.width,t.x+t.width),r=Math.min(e.height,t.y+t.height);return{...t,x:n,y:o,width:Math.max(0,i-n),height:Math.max(0,r-o)}}async function Oi(t,e){if(t.regions.length===0)return e;const n=Q(e.width,e.height),o=et(n);o.drawImage(e.bitmap,0,0,e.width,e.height);for(const i of t.regions)mn(o,n.canvas,i,e);return{bitmap:n.canvas,width:e.width,height:e.height,mimeType:e.mimeType}}function mn(t,e,n,o){const i=Math.round(n.width),r=Math.round(n.height);if(i<1||r<1)return;const a=Math.round(n.x),s=Math.round(n.y);switch(n.mode){case"solid":zi(t,n,a,s,i,r);return;case"pixelate":Bi(t,e,o,a,s,i,r);return;case"blur":_i(t,e,o,a,s,i,r);return}}function zi(t,e,n,o,i,r){t.save(),t.fillStyle=e.color,t.fillRect(n,o,i,r),t.restore()}function Bi(t,e,n,o,i,r,a){const s=Math.max(r,a),c=Math.max(4,Math.round(8*Math.min(1,s/240))),l=Math.max(1,Math.round(r/s*c)),u=Math.max(1,Math.round(a/s*c));t.save();const d=ee(l,u);if(!d){t.restore();return}d.ctx.imageSmoothingEnabled=!0,d.ctx.imageSmoothingQuality="low",d.ctx.drawImage(e,o,i,r,a,0,0,l,u),t.imageSmoothingEnabled=!1,t.drawImage(d.canvas,0,0,l,u,o,i,r,a),t.restore()}function _i(t,e,n,o,i,r,a){const c=Math.max(1,Math.round(r*.125)),l=Math.max(1,Math.round(a*.125)),u=ee(c,l);if(!u)return;u.ctx.imageSmoothingEnabled=!0,u.ctx.imageSmoothingQuality="high",u.ctx.drawImage(e,o,i,r,a,0,0,c,l);const d=Math.max(1,Math.round(c*.5)),h=Math.max(1,Math.round(l*.5)),f=ee(d,h);if(!f){t.save(),t.imageSmoothingEnabled=!0,t.imageSmoothingQuality="high",t.drawImage(u.canvas,0,0,c,l,o,i,r,a),t.restore();return}f.ctx.imageSmoothingEnabled=!0,f.ctx.imageSmoothingQuality="high",f.ctx.drawImage(u.canvas,0,0,c,l,0,0,d,h),t.save(),t.imageSmoothingEnabled=!0,t.imageSmoothingQuality="high",t.drawImage(f.canvas,0,0,d,h,o,i,r,a),t.restore()}function ee(t,e){if(typeof OffscreenCanvas<"u")try{const i=new OffscreenCanvas(t,e),r=i.getContext("2d");if(r)return{canvas:i,ctx:r}}catch{}if(typeof document>"u")return null;const n=document.createElement("canvas");n.width=t,n.height=e;const o=n.getContext("2d");return o?{canvas:n,ctx:o}:null}const fn=[{id:"none",label:"None",acceptsColor:!1,defaultColor:"#000000"},{id:"solidSharp",label:"Mat Sharp",acceptsColor:!0,defaultColor:"#000000"},{id:"solidRound",label:"Mat Round",acceptsColor:!0,defaultColor:"#000000"},{id:"lineSingle",label:"Line Single",acceptsColor:!0,defaultColor:"#000000"},{id:"hook",label:"Corner Hooks",acceptsColor:!0,defaultColor:"#000000"},{id:"polaroid",label:"Polaroid",acceptsColor:!0,defaultColor:"#ffffff"}],Wi={presetId:"none",color:"#000000"};function qi(){return Wi}function gn(t){return t.presetId==="none"}function Ui(t,e){if(t.presetId===e)return t;const n=yn(t.presetId),o=yn(e);if(!o)return{...t,presetId:e};const r=n!==void 0&&t.color===n.defaultColor?o.defaultColor:t.color;return{presetId:e,color:r}}function Xi(t,e){return t.color===e?t:{...t,color:e}}function yn(t){return fn.find(e=>e.id===t)}async function Yi(t,e){return gn(t)?e:t.presetId==="polaroid"?Qi(t.color,e):t.presetId==="none"?e:Gi(t.presetId,t.color,e)}function Gi(t,e,n){const o=Q(n.width,n.height),i=et(o);return i.drawImage(n.bitmap,0,0,n.width,n.height),ne(i,t,e,n.width,n.height),{bitmap:o.canvas,width:n.width,height:n.height,mimeType:n.mimeType}}function ne(t,e,n,o,i){switch(e){case"solidSharp":bn(t,n,o,i);return;case"solidRound":Ki(t,n,o,i);return;case"lineSingle":Vi(t,n,o,i);return;case"hook":ji(t,n,o,i);return}}function bn(t,e,n,o){const i=wn(n,o);t.save(),t.fillStyle=e,t.fillRect(0,0,n,i),t.fillRect(0,o-i,n,i),t.fillRect(0,i,i,o-2*i),t.fillRect(n-i,i,i,o-2*i),t.restore()}function Ki(t,e,n,o){const r=wn(n,o);bn(t,e,n,o),t.save(),t.globalCompositeOperation="destination-out",t.fillStyle="#000",Pt(t,0,0,r,"tl"),Pt(t,n,0,r,"tr"),Pt(t,0,o,r,"bl"),Pt(t,n,o,r,"br"),t.restore()}function Pt(t,e,n,o,i){switch(t.beginPath(),t.moveTo(e,n),i){case"tl":t.lineTo(e+o,n),t.arc(e+o,n+o,o,-Math.PI/2,Math.PI,!0),t.lineTo(e,n);break;case"tr":t.lineTo(e,n+o),t.arc(e-o,n+o,o,0,-Math.PI/2,!0),t.lineTo(e,n);break;case"bl":t.lineTo(e+o,n),t.arc(e+o,n-o,o,Math.PI/2,Math.PI,!1),t.lineTo(e,n);break;case"br":t.lineTo(e-o,n),t.arc(e-o,n-o,o,Math.PI/2,0,!0),t.lineTo(e,n);break}t.closePath(),t.fill()}function Vi(t,e,n,o){const i=Math.round(Math.min(n,o)*.05),r=Math.max(2,Math.round(Math.min(n,o)*.01));t.save(),t.strokeStyle=e,t.lineWidth=r;const a=r/2;t.strokeRect(i+a,i+a,n-2*i-r,o-2*i-r),t.restore()}function ji(t,e,n,o){const i=Math.round(Math.min(n,o)*.08),r=Math.max(2,Math.round(Math.min(n,o)*.01)),a=Math.round(Math.min(n,o)*.05);t.save(),t.strokeStyle=e,t.lineWidth=r,t.lineCap="square";const s=r/2,c=(l,u,d,h)=>{t.beginPath(),t.moveTo(l+d*i,u),t.lineTo(l,u),t.lineTo(l,u+h*i),t.stroke()};c(a+s,a+s,1,1),c(n-a-s,a+s,-1,1),c(a+s,o-a-s,1,-1),c(n-a-s,o-a-s,-1,-1),t.restore()}function Qi(t,e){const n=Math.min(e.width,e.height),o=Math.round(n*.05),i=o,r=o,a=Math.round(n*.18),s=e.width+i+r,c=e.height+o+a,l=Q(s,c),u=et(l);return u.fillStyle=t,u.fillRect(0,0,s,c),u.drawImage(e.bitmap,i,o,e.width,e.height),{bitmap:l.canvas,width:s,height:c,mimeType:e.mimeType}}function wn(t,e){return Math.max(4,Math.round(Math.min(t,e)*.04))}function oe(t,e,n){if(t!=="polaroid")return{width:e,height:n};const o=Math.min(e,n),i=Math.round(o*.05),r=Math.round(o*.18);return{width:e+2*i,height:n+i+r}}/**
4
- * @license lucide v1.14.0 - ISC
5
- *
6
- * This source code is licensed under the ISC license.
7
- * See the LICENSE file in the root directory of this source tree.
8
- */const Ji=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];/**
9
- * @license lucide v1.14.0 - ISC
10
- *
11
- * This source code is licensed under the ISC license.
12
- * See the LICENSE file in the root directory of this source tree.
13
- */const Zi=[["path",{d:"M20 6 9 17l-5-5"}]];/**
14
- * @license lucide v1.14.0 - ISC
15
- *
16
- * This source code is licensed under the ISC license.
17
- * See the LICENSE file in the root directory of this source tree.
18
- */const tr=[["path",{d:"m6 9 6 6 6-6"}]];/**
19
- * @license lucide v1.14.0 - ISC
20
- *
21
- * This source code is licensed under the ISC license.
22
- * See the LICENSE file in the root directory of this source tree.
23
- */const er=[["circle",{cx:"12",cy:"12",r:"10"}]];/**
24
- * @license lucide v1.14.0 - ISC
25
- *
26
- * This source code is licensed under the ISC license.
27
- * See the LICENSE file in the root directory of this source tree.
28
- */const nr=[["path",{d:"m3 7 5 5-5 5V7"}],["path",{d:"m21 7-5 5 5 5V7"}],["path",{d:"M12 20v2"}],["path",{d:"M12 14v2"}],["path",{d:"M12 8v2"}],["path",{d:"M12 2v2"}]];/**
29
- * @license lucide v1.14.0 - ISC
30
- *
31
- * This source code is licensed under the ISC license.
32
- * See the LICENSE file in the root directory of this source tree.
33
- */const or=[["path",{d:"m17 3-5 5-5-5h10"}],["path",{d:"m17 21-5-5-5 5h10"}],["path",{d:"M4 12H2"}],["path",{d:"M10 12H8"}],["path",{d:"M16 12h-2"}],["path",{d:"M22 12h-2"}]];/**
34
- * @license lucide v1.14.0 - ISC
35
- *
36
- * This source code is licensed under the ISC license.
37
- * See the LICENSE file in the root directory of this source tree.
38
- */const ir=[["path",{d:"m9 11-6 6v3h9l3-3"}],["path",{d:"m22 12-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"}]];/**
39
- * @license lucide v1.14.0 - ISC
40
- *
41
- * This source code is licensed under the ISC license.
42
- * See the LICENSE file in the root directory of this source tree.
43
- */const rr=[["path",{d:"M10 8h.01"}],["path",{d:"M12 12h.01"}],["path",{d:"M14 8h.01"}],["path",{d:"M16 12h.01"}],["path",{d:"M18 8h.01"}],["path",{d:"M6 8h.01"}],["path",{d:"M7 16h10"}],["path",{d:"M8 12h.01"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}]];/**
44
- * @license lucide v1.14.0 - ISC
45
- *
46
- * This source code is licensed under the ISC license.
47
- * See the LICENSE file in the root directory of this source tree.
48
- */const ar=[["path",{d:"M9 17H7A5 5 0 0 1 7 7"}],["path",{d:"M15 7h2a5 5 0 0 1 4 8"}],["line",{x1:"8",x2:"12",y1:"12",y2:"12"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22"}]];/**
49
- * @license lucide v1.14.0 - ISC
50
- *
51
- * This source code is licensed under the ISC license.
52
- * See the LICENSE file in the root directory of this source tree.
53
- */const sr=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12"}]];/**
54
- * @license lucide v1.14.0 - ISC
55
- *
56
- * This source code is licensed under the ISC license.
57
- * See the LICENSE file in the root directory of this source tree.
58
- */const cr=[["path",{d:"M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z"}]];/**
59
- * @license lucide v1.14.0 - ISC
60
- *
61
- * This source code is licensed under the ISC license.
62
- * See the LICENSE file in the root directory of this source tree.
63
- */const lr=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];/**
64
- * @license lucide v1.14.0 - ISC
65
- *
66
- * This source code is licensed under the ISC license.
67
- * See the LICENSE file in the root directory of this source tree.
68
- */const ur=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];/**
69
- * @license lucide v1.14.0 - ISC
70
- *
71
- * This source code is licensed under the ISC license.
72
- * See the LICENSE file in the root directory of this source tree.
73
- */const dr=[["path",{d:"m15 14 5-5-5-5"}],["path",{d:"M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13"}]];/**
74
- * @license lucide v1.14.0 - ISC
75
- *
76
- * This source code is licensed under the ISC license.
77
- * See the LICENSE file in the root directory of this source tree.
78
- */const hr=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];/**
79
- * @license lucide v1.14.0 - ISC
80
- *
81
- * This source code is licensed under the ISC license.
82
- * See the LICENSE file in the root directory of this source tree.
83
- */const pr=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];/**
84
- * @license lucide v1.14.0 - ISC
85
- *
86
- * This source code is licensed under the ISC license.
87
- * See the LICENSE file in the root directory of this source tree.
88
- */const mr=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];/**
89
- * @license lucide v1.14.0 - ISC
90
- *
91
- * This source code is licensed under the ISC license.
92
- * See the LICENSE file in the root directory of this source tree.
93
- */const fr=[["path",{d:"M12 4v16"}],["path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2"}],["path",{d:"M9 20h6"}]];/**
94
- * @license lucide v1.14.0 - ISC
95
- *
96
- * This source code is licensed under the ISC license.
97
- * See the LICENSE file in the root directory of this source tree.
98
- */const gr=[["path",{d:"M9 14 4 9l5-5"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11"}]];/**
99
- * @license lucide v1.14.0 - ISC
100
- *
101
- * This source code is licensed under the ISC license.
102
- * See the LICENSE file in the root directory of this source tree.
103
- */const yr=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]],br={xmlns:"http://www.w3.org/2000/svg",width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"};function wr(t,e={}){const n={...br,...e},o=Object.entries(n).map(([r,a])=>`${r}="${a}"`).join(" "),i=t.map(([r,a])=>{const s=Object.entries(a).map(([c,l])=>`${c}="${l}"`).join(" ");return`<${r} ${s} />`}).join("");return`<svg ${o}>${i}</svg>`}function Cr(t){switch(t){case"select":return cr;case"text":return fr;case"rect":return pr;case"ellipse":return er;case"arrow":return Ji;case"freehand":return lr;case"highlight":return ir;case"undo":return gr;case"redo":return dr;case"close":return yr;case"delete":return mr;case"check":return Zi;case"lockClosed":return sr;case"lockOpen":return ar;case"plus":return ur;case"flipHorizontal":return nr;case"flipVertical":return or;case"chevronDown":return tr;case"settings":return hr;case"keyboard":return rr}}function B(t,e){return wr(Cr(t),e)}let xr=0;function vr(t){const e=`kalotyp-editor-${++xr}`,n=`${e}-title`,o=document.createElement("div");o.className="pintura-editor kalotyp-editor",o.id=e,o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.setAttribute("aria-labelledby",n),o.tabIndex=-1;const i=document.createElement("h2");i.id=n,i.className="kalotyp-visually-hidden",i.textContent="Image editor";const r=document.createElement("div");r.className="PinturaModal kalotyp-modal";const a=document.createElement("button");a.type="button",a.title="Close",a.setAttribute("aria-label","Close image editor"),a.className="kalotyp-button-close",a.innerHTML=B("close");const s=document.createElement("button");s.type="button",s.title="Preferences",s.setAttribute("aria-label","Open editor preferences"),s.setAttribute("aria-haspopup","dialog"),s.className="kalotyp-button-prefs",s.innerHTML=B("settings");const c=document.createElement("div");c.className="kalotyp-root",c.setAttribute("data-env","landscape has-navigation");const l=document.createElement("div");l.className="kalotyp-main";const u=document.createElement("div");u.className="kalotyp-stage",u.setAttribute("role","region"),u.setAttribute("aria-label","Image preview");const d=document.createElement("div");d.id=`${e}-panel`,d.className="kalotyp-util-main",d.setAttribute("role","tabpanel"),d.setAttribute("tabindex","0");const h=document.createElement("div");h.className="kalotyp-nav-tools";const f=document.createElement("div");f.className="kalotyp-util-footer";const m=document.createElement("div");m.className="kalotyp-export-group";const g=document.createElement("button");g.type="button",g.className="kalotyp-button-export";const p=document.createElement("span");p.className="kalotyp-button-inner",p.textContent=t.exportLabel,g.appendChild(p);const w=document.createElement("button");w.type="button",w.className="kalotyp-button-output-settings",w.title="Output settings",w.setAttribute("aria-label","Output settings (format and quality)"),w.setAttribute("aria-haspopup","dialog"),w.setAttribute("aria-expanded","false"),w.innerHTML=B("chevronDown"),m.appendChild(g),m.appendChild(w),f.appendChild(m);const y=document.createElement("div");return y.className="kalotyp-visually-hidden",y.setAttribute("role","status"),y.setAttribute("aria-live","polite"),y.setAttribute("aria-atomic","true"),l.appendChild(u),l.appendChild(d),c.appendChild(h),c.appendChild(l),c.appendChild(f),r.appendChild(i),r.appendChild(s),r.appendChild(a),r.appendChild(c),r.appendChild(y),o.appendChild(r),{editor:o,modal:r,root:c,main:l,stage:u,navTools:h,utilMain:d,utilFooter:f,closeButton:a,prefsButton:s,exportButton:g,outputSettingsButton:w,liveRegion:y,titleId:n}}function kr(t){const e=vr({exportLabel:t.exportLabel}),n=()=>t.onExportClick(),o=()=>t.onCloseClick(),i=()=>t.onOutputSettingsClick(),r=()=>t.onPrefsClick();e.exportButton.addEventListener("click",n),e.closeButton.addEventListener("click",o),e.outputSettingsButton.addEventListener("click",i),e.prefsButton.addEventListener("click",r),t.host.appendChild(e.editor);let a=!1;function s(c){a=!a,e.liveRegion.textContent=a?`${c} `:c}return{editor:e.editor,modal:e.modal,root:e.root,exportButton:e.exportButton,outputSettingsButton:e.outputSettingsButton,prefsButton:e.prefsButton,closeButton:e.closeButton,stage:e.stage,utilMain:e.utilMain,navTools:e.navTools,announce:s,destroy(){e.exportButton.removeEventListener("click",n),e.closeButton.removeEventListener("click",o),e.outputSettingsButton.removeEventListener("click",i),e.prefsButton.removeEventListener("click",r),e.editor.remove()}}}const ut=12;function Sr(t){const e=be(t.cropRectImage,t.viewport),{cornerAnchors:n,edgeHandles:o,bodyHitArea:i}=t;i.style.left=`${e.x}px`,i.style.top=`${e.y}px`,i.style.width=`${e.width}px`,i.style.height=`${e.height}px`,$t(n.tl,e.x,e.y),$t(n.tr,e.x+e.width,e.y),$t(n.bl,e.x,e.y+e.height),$t(n.br,e.x+e.width,e.y+e.height);const r=Math.max(0,e.width-ut*2),a=Math.max(0,e.height-ut*2);Cn(o.t,e.x+ut,e.y,r),Cn(o.b,e.x+ut,e.y+e.height,r),xn(o.l,e.x,e.y+ut,a),xn(o.r,e.x+e.width,e.y+ut,a)}function $t(t,e,n){t.style.left=`${e}px`,t.style.top=`${n}px`}function Cn(t,e,n,o){t.style.left=`${e}px`,t.style.top=`${n}px`,t.style.width=`${o}px`}function xn(t,e,n,o){t.style.left=`${e}px`,t.style.top=`${n}px`,t.style.height=`${o}px`}function Er(t,e,n,o,i){const r=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(n*r)),s=Math.max(1,Math.round(o*r));t.width!==a&&(t.width=a),t.height!==s&&(t.height=s),t.style.width=`${n}px`,t.style.height=`${o}px`;const c=t.getContext("2d");c&&(c.setTransform(r,0,0,r,0,0),c.clearRect(0,0,n,o),c.drawImage(e,i.displayRect.x,i.displayRect.y,i.displayRect.width,i.displayRect.height))}const Ar="rgba(0, 0, 0, 0.4)",Mr="rgba(0, 0, 0, 0.45)",Ir=3,Rr="rgba(255, 255, 255, 0.95)",Nr=1,Lr="rgba(0, 0, 0, 0.25)",Tr=2,Fr="rgba(255, 255, 255, 0.55)",Pr=1;function $r(t,e,n,o,i){const r=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(n*r)),s=Math.max(1,Math.round(o*r));t.width!==a&&(t.width=a),t.height!==s&&(t.height=s),t.style.width=`${n}px`,t.style.height=`${o}px`;const c=t.getContext("2d");if(!c)return;c.setTransform(r,0,0,r,0,0),c.clearRect(0,0,n,o);const l=be(e,i),u=i.displayRect;c.save(),c.fillStyle=Ar,c.fillRect(u.x,u.y,u.width,u.height),c.globalCompositeOperation="destination-out",c.fillRect(l.x,l.y,l.width,l.height),c.restore();const d=l.x+.5,h=l.y+.5,f=l.width-1,m=l.height-1;c.strokeStyle=Mr,c.lineWidth=Ir,c.strokeRect(d,h,f,m),c.strokeStyle=Rr,c.lineWidth=Nr,c.strokeRect(d,h,f,m),vn(c,l,Lr,Tr),vn(c,l,Fr,Pr)}function vn(t,e,n,o){t.strokeStyle=n,t.lineWidth=o,t.beginPath();for(let i=1;i<3;i++){const r=e.x+e.width*i/3,a=e.y+e.height*i/3;t.moveTo(r,e.y),t.lineTo(r,e.y+e.height),t.moveTo(e.x,a),t.lineTo(e.x+e.width,a)}t.stroke()}function Dr(t,e,n){const o=document.createElement("div");o.className="kalotyp-preset-row",o.setAttribute("role","radiogroup"),o.setAttribute("aria-label","Crop aspect ratio");const i=[];return t.forEach((r,a)=>{const[,s]=r,c=document.createElement("button");c.type="button",c.className="kalotyp-preset-button",c.textContent=s,c.setAttribute("role","radio"),c.setAttribute("aria-checked",a===e?"true":"false"),c.dataset.presetIndex=String(a),c.addEventListener("click",()=>n(a,r)),o.appendChild(c),i.push(c)}),{container:o,buttons:i}}function kn(t,e){t.forEach((n,o)=>{n.setAttribute("aria-checked",o===e?"true":"false")})}const Hr=["tl","tr","bl","br"],Or=["t","r","b","l"];function zr(){const t=document.createElement("div");t.className="kalotyp-stage-container";const e=document.createElement("canvas");e.className="kalotyp-stage-image",e.setAttribute("aria-hidden","true");const n=document.createElement("canvas");n.className="kalotyp-stage-overlay",n.setAttribute("aria-hidden","true");const o=document.createElement("div");o.className="kalotyp-stage-body";const i=document.createElement("div");i.className="kalotyp-handles",i.setAttribute("role","group"),i.setAttribute("aria-label","Crop region");const r={};for(const s of Or){const c=_r(s);r[s]=c,i.appendChild(c)}const a={};for(const s of Hr){const c=document.createElement("div");c.className="kalotyp-corner-anchor",c.dataset.direction=s;const l=Br(s);c.appendChild(l),r[s]=l,a[s]=c,i.appendChild(c)}return t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(i),{container:t,imageCanvas:e,overlayCanvas:n,handlesLayer:i,handles:r,cornerAnchors:a,bodyHitArea:o}}function Br(t){const e=document.createElement("button");return e.type="button",e.className="kalotyp-handle",e.dataset.shape="circle",e.dataset.direction=t,e.setAttribute("aria-label",Sn(t)),e.tabIndex=0,e}function _r(t){const e=document.createElement("button");return e.type="button",e.className="kalotyp-handle",e.dataset.shape="edge",e.dataset.direction=t,e.setAttribute("aria-label",Sn(t)),e.tabIndex=0,e}function Sn(t){switch(t){case"tl":return"Top-left crop handle";case"tr":return"Top-right crop handle";case"bl":return"Bottom-left crop handle";case"br":return"Bottom-right crop handle";case"t":return"Top crop handle";case"r":return"Right crop handle";case"b":return"Bottom crop handle";case"l":return"Left crop handle"}}function Wr(t,e,n){const o=[];for(const i of Object.keys(t.handles)){const r=t.handles[i];o.push(qr(r,i,e,n))}return o.push(Ur(t.bodyHitArea,e,n)),{destroy(){for(const i of o)i()}}}function qr(t,e,n,o){return En(t,()=>{const i=o.getViewport(),r=n.get(),a={x:0,y:0,width:r.imageSize.width,height:r.imageSize.height},s=r.aspectRatio;return{onMove(c){const l=ie(t,c.clientX,c.clientY),u=Wt(l,i),d=go(r.rect,e,u,{bounds:a,...s!==void 0?{aspectRatio:s}:{}});n.set({rect:d})},onCommit(){o.onCommit?.()},onCancel(){n.set({rect:r.rect})}}})}function Ur(t,e,n){return En(t,o=>{const i=n.getViewport(),r=e.get(),a={x:0,y:0,width:r.imageSize.width,height:r.imageSize.height},s=ie(t,o.clientX,o.clientY);return{onMove(c){const l=ie(t,c.clientX,c.clientY),u=(l.x-s.x)/i.scale,d=(l.y-s.y)/i.scale,h=co(r.rect,u,d,a);e.set({rect:h})},onCommit(){n.onCommit?.()},onCancel(){e.set({rect:r.rect})}}})}function En(t,e){const n=o=>{if(o.button!==0)return;o.preventDefault(),o.stopPropagation();const i=e(o);t.setPointerCapture(o.pointerId);let r,a=!1;const s=()=>{if(a=!1,!r)return;const h=r;r=void 0,i.onMove(h)},c=h=>{h.pointerId===o.pointerId&&(r={clientX:h.clientX,clientY:h.clientY},a||(a=!0,requestAnimationFrame(s)))},l=h=>{t.removeEventListener("pointermove",c),t.removeEventListener("pointerup",u),t.removeEventListener("pointercancel",d);try{t.releasePointerCapture(o.pointerId)}catch{}if(r){const f=r;r=void 0,i.onMove(f)}h?i.onCommit():i.onCancel()},u=h=>{h.pointerId===o.pointerId&&l(!0)},d=h=>{h.pointerId===o.pointerId&&l(!1)};t.addEventListener("pointermove",c),t.addEventListener("pointerup",u),t.addEventListener("pointercancel",d)};return t.addEventListener("pointerdown",n),()=>t.removeEventListener("pointerdown",n)}function ie(t,e,n){const i=(t.closest(".kalotyp-stage-container")??t).getBoundingClientRect();return{x:e-i.left,y:n-i.top}}const An=32;function Xr(t){const{stageHost:e,utilHost:n,source:o,presets:i,presetFilter:r,store:a,viewport:s}=t,c=t.onCommit??Gr,l=zr();e.appendChild(l.container);const u=document.createElement("div");u.className="kalotyp-crop-panel";const d=wo(i,r),h=Mn(a.get(),i,d),f=Dr(d,h,(A,T)=>{const $=i.indexOf(T);if($===-1)return;const O=xo(a.get(),$);a.set({rect:O.rect,aspectRatio:O.aspectRatio,activePresetIndex:$}),kn(f.buttons,A),c()});u.appendChild(f.container);const m=Yr({initial:a.get().rect,bounds:{width:o.width,height:o.height},onCommit(A){const T=a.get(),$={x:0,y:0,width:T.imageSize.width,height:T.imageSize.height},O=xt(A,$);a.set({rect:O}),c()}});u.appendChild(m.container),n.appendChild(u);let g=j({width:1,height:1,padding:An},{width:o.width,height:o.height});function p(){const A=l.container.getBoundingClientRect(),T={width:A.width,height:A.height,padding:An},$={width:o.width,height:o.height};g=s?s.computeViewport(T,$):j(T,$)}function w(){const A=l.container.getBoundingClientRect();A.width<=0||A.height<=0||(Er(l.imageCanvas,o.bitmap,A.width,A.height,g),y())}function y(){const A=l.container.getBoundingClientRect();A.width<=0||A.height<=0||($r(l.overlayCanvas,a.get().rect,A.width,A.height,g),Sr({cropRectImage:a.get().rect,viewport:g,cornerAnchors:l.cornerAnchors,edgeHandles:{t:l.handles.t,r:l.handles.r,b:l.handles.b,l:l.handles.l},bodyHitArea:l.bodyHitArea}))}p(),w();const C=new ResizeObserver(()=>{p(),w()});C.observe(l.container);let E=!1;const S=s?.subscribe(()=>{E||(E=!0,requestAnimationFrame(()=>{E=!1,p(),w()}))});let M=!1;const H=a.subscribe((A,T)=>{Vr(A,T,i,d,f.buttons),!Kr(A.rect,T.rect)&&(m.sync(A.rect),!M&&(M=!0,requestAnimationFrame(()=>{M=!1,y()})))}),R=Wr({handles:l.handles,bodyHitArea:l.bodyHitArea},a,{getViewport:()=>g,onCommit:c});return{destroy(){R.destroy(),H(),S?.(),C.disconnect(),l.container.remove(),u.remove()}}}function Yr(t){const e=document.createElement("div");e.className="kalotyp-crop-dims",e.setAttribute("role","group"),e.setAttribute("aria-label","Crop region dimensions");const n=Dt("Left",t.initial.x,0,t.bounds.width),o=Dt("Top",t.initial.y,0,t.bounds.height),i=Dt("Width",t.initial.width,1,t.bounds.width),r=Dt("Height",t.initial.height,1,t.bounds.height);function a(){return{x:Math.round(n.input.valueAsNumber),y:Math.round(o.input.valueAsNumber),width:Math.round(i.input.valueAsNumber),height:Math.round(r.input.valueAsNumber)}}for(const c of[n,o,i,r])c.input.addEventListener("change",()=>{const l=a();Number.isFinite(l.x+l.y+l.width+l.height)&&t.onCommit(l)});e.appendChild(n.wrapper),e.appendChild(o.wrapper),e.appendChild(i.wrapper),e.appendChild(r.wrapper);function s(c){n.input.valueAsNumber!==c.x&&(n.input.value=String(Math.round(c.x))),o.input.valueAsNumber!==c.y&&(o.input.value=String(Math.round(c.y))),i.input.valueAsNumber!==c.width&&(i.input.value=String(Math.round(c.width))),r.input.valueAsNumber!==c.height&&(r.input.value=String(Math.round(c.height)))}return{container:e,sync:s}}function Dt(t,e,n,o){const i=document.createElement("label");i.className="kalotyp-crop-dims-field";const r=document.createElement("span");r.className="kalotyp-crop-dims-label",r.textContent=t;const a=document.createElement("input");return a.type="number",a.className="kalotyp-crop-dims-input",a.min=String(n),a.max=String(o),a.step="1",a.value=String(Math.round(e)),a.inputMode="numeric",a.setAttribute("aria-label",`${t} (pixels)`),i.appendChild(r),i.appendChild(a),{wrapper:i,input:a}}function Gr(){}function Kr(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function Mn(t,e,n){if(t.activePresetIndex===-1)return-1;const o=e[t.activePresetIndex];return o?n.indexOf(o):-1}function Vr(t,e,n,o,i){if(t.activePresetIndex===e.activePresetIndex)return;const r=Mn(t,n,o);kn(i,r)}const jr="crop";function Qr(t){return{id:"crop",init(e){return Co({imageSize:{width:e.source.width,height:e.source.height},presets:t.presets,filter:t.presetFilter})},mount(e,n,o){const i=Xr({stageHost:e,utilHost:t.panelHost,source:n.source,presets:t.presets,presetFilter:t.presetFilter,store:o,viewport:n.viewport,onCommit:()=>n.bus.emit("commit",{utility:jr})});return{destroy:()=>i.destroy()}},async bake(e,n){return ko(n,{rect:e.rect})}}}const In=32;function yt(){const t=document.createElement("div");t.className="kalotyp-stage-container kalotyp-preview-container";const e=document.createElement("canvas");return e.className="kalotyp-stage-image kalotyp-preview-canvas",e.setAttribute("aria-hidden","true"),t.appendChild(e),{container:t,canvas:e}}function Ht(t,e,n){const o=t.getBoundingClientRect();if(o.width<=0||o.height<=0)return;const i={width:o.width,height:o.height,padding:In};return{viewport:n?n.computeViewport(i,e):j(i,e),stageWidth:o.width,stageHeight:o.height}}function re(t,e,n,o){const i=Math.max(1,window.devicePixelRatio||1),r=Math.max(1,Math.round(e*i)),a=Math.max(1,Math.round(n*i));t.width!==r&&(t.width=r),t.height!==a&&(t.height=a),t.style.width=`${e}px`,t.style.height=`${n}px`;const s=t.getContext("2d");s&&(s.setTransform(i,0,0,i,0,0),s.clearRect(0,0,e,n),s.imageSmoothingEnabled=!0,s.imageSmoothingQuality="high",o(s))}function Jr(t){const{stageHost:e,utilHost:n,source:o,store:i,viewport:r}=t,a=t.onCommit??(()=>{}),s=yt();e.appendChild(s.container);const c=Zr({onToggleHorizontal:()=>{i.set(Oe(i.get(),"horizontal")),a()},onToggleVertical:()=>{i.set(Oe(i.get(),"vertical")),a()}});n.appendChild(c.container);function l(){const p=Ht(s.container,{width:o.width,height:o.height},r);if(!p)return;const w=i.get();re(s.canvas,p.stageWidth,p.stageHeight,y=>{const C=p.viewport.displayRect,E=w.horizontal?-1:1,S=w.vertical?-1:1,M=C.x+C.width/2,H=C.y+C.height/2;y.translate(M,H),y.scale(E,S),y.drawImage(o.bitmap,-C.width/2,-C.height/2,C.width,C.height)})}function u(p){c.horizontalButton.setAttribute("aria-pressed",p.horizontal?"true":"false"),c.verticalButton.setAttribute("aria-pressed",p.vertical?"true":"false")}u(i.get()),l();const d=new ResizeObserver(()=>l());d.observe(s.container);let h=!1;const f=r?.subscribe(()=>{h||(h=!0,requestAnimationFrame(()=>{h=!1,l()}))});let m=!1;const g=i.subscribe(p=>{u(p),!m&&(m=!0,requestAnimationFrame(()=>{m=!1,l()}))});return{destroy(){g(),f?.(),d.disconnect(),s.container.remove(),c.container.remove()}}}function Zr(t){const e=document.createElement("div");e.className="kalotyp-flip-panel",e.setAttribute("role","group"),e.setAttribute("aria-label","Flip");const n=Rn("Flip horizontal",B("flipHorizontal"),t.onToggleHorizontal);n.classList.add("kalotyp-flip-button-h");const o=Rn("Flip vertical",B("flipVertical"),t.onToggleVertical);return o.classList.add("kalotyp-flip-button-v"),e.appendChild(n),e.appendChild(o),{container:e,horizontalButton:n,verticalButton:o}}function Rn(t,e,n){const o=document.createElement("button");return o.type="button",o.className="kalotyp-toggle-button",o.innerHTML=`${e}<span>${t}</span>`,o.setAttribute("aria-pressed","false"),o.setAttribute("aria-label",t),o.addEventListener("click",n),o}function ta(t){return{id:"flip",init:()=>zo(),mount(e,n,o){const i=Jr({stageHost:e,utilHost:t.panelHost,source:n.source,store:o,viewport:n.viewport,onCommit:()=>n.bus.emit("commit",{utility:"flip"})});return{destroy:()=>i.destroy()}},bake:Bo}}const ea="rgba(0, 0, 0, 0.4)",na="rgba(255, 255, 255, 0.95)",oa="rgba(0, 0, 0, 0.45)";function ia(t){const{stageHost:e,utilHost:n,source:o,store:i,viewport:r}=t,a=t.onCommit??sa,s=yt();e.appendChild(s.container);const c=ra({onCounterClockwise:()=>{i.set(qo(i.get())),a()},onClockwise:()=>{i.set(Wo(i.get())),a()},onAngleInput:p=>i.set(_e(i.get(),p)),onAngleCommit:()=>a(),onAngleReset:()=>{i.set(_e(i.get(),0)),a()}});n.appendChild(c.container);function l(){const p=s.container.getBoundingClientRect();if(p.width<=0||p.height<=0)return;const w=i.get(),y=Yt(w)*Math.PI/180,C=Yt(w)-w.quarterTurns*90,E=Math.abs(C)<1e-6,S=Math.abs(Math.cos(y)),M=Math.abs(Math.sin(y)),H=o.width*S+o.height*M,R=o.width*M+o.height*S,A={width:p.width,height:p.height,padding:In},T={width:H,height:R},$=r?r.computeViewport(A,T):j(A,T),O=$.displayRect,W=O.x+O.width/2,U=O.y+O.height/2,_=E?w.quarterTurns%2===0?{width:o.width,height:o.height}:{width:o.height,height:o.width}:qe(o,y);re(s.canvas,p.width,p.height,D=>{const G=o.width*$.scale,V=o.height*$.scale;D.save(),D.translate(W,U),D.rotate(y),D.drawImage(o.bitmap,-G/2,-V/2,G,V),D.restore();const Y=_.width*$.scale,x=_.height*$.scale,F=W-Y/2,N=U-x/2;E||(D.save(),D.beginPath(),D.rect(0,0,p.width,p.height),D.rect(F,N,Y,x),D.clip("evenodd"),D.fillStyle=ea,D.fillRect(0,0,p.width,p.height),D.restore()),D.save(),D.lineWidth=3,D.strokeStyle=oa,D.strokeRect(F+.5,N+.5,Y-1,x-1),D.lineWidth=1,D.strokeStyle=na,D.strokeRect(F+.5,N+.5,Y-1,x-1),D.restore()})}function u(p){c.angleSlider.valueAsNumber!==p.freeAngle&&(c.angleSlider.valueAsNumber=p.freeAngle);const w=aa(p.freeAngle);c.angleInput.value!==w&&(c.angleInput.value=w)}u(i.get()),l();const d=new ResizeObserver(()=>l());d.observe(s.container);let h=!1;const f=r?.subscribe(()=>{h||(h=!0,requestAnimationFrame(()=>{h=!1,l()}))});let m=!1;const g=i.subscribe(p=>{u(p),!m&&(m=!0,requestAnimationFrame(()=>{m=!1,l()}))});return{destroy(){g(),f?.(),d.disconnect(),s.container.remove(),c.container.remove()}}}function ra(t){const e=document.createElement("div");e.className="kalotyp-rotate-panel",e.setAttribute("role","group"),e.setAttribute("aria-label","Rotate");const n=Nn("Rotate 90° counter-clockwise","↺",t.onCounterClockwise),o=Nn("Rotate 90° clockwise","↻",t.onClockwise),i=document.createElement("label");i.className="kalotyp-rotate-slider-label",i.textContent="Straighten";const r=document.createElement("input");r.type="range",r.className="kalotyp-rotate-slider",r.min=String(Ut),r.max=String(Xt),r.step=String(Be),r.value="0",r.setAttribute("aria-label","Straighten angle"),r.addEventListener("input",()=>t.onAngleInput(r.valueAsNumber)),r.addEventListener("change",()=>t.onAngleCommit());const a=document.createElement("input");a.type="number",a.className="kalotyp-rotate-input",a.min=String(Ut),a.max=String(Xt),a.step=String(Be),a.value="0",a.setAttribute("aria-label","Straighten angle in degrees"),a.addEventListener("change",()=>{const h=a.valueAsNumber;Number.isFinite(h)&&(t.onAngleInput(h),t.onAngleCommit())});const s=document.createElement("span");s.className="kalotyp-rotate-suffix",s.setAttribute("aria-hidden","true"),s.textContent="°";const c=document.createElement("button");c.type="button",c.className="kalotyp-rotate-reset",c.textContent="Reset",c.addEventListener("click",t.onAngleReset);const l=document.createElement("div");l.className="kalotyp-rotate-row",l.appendChild(n),l.appendChild(o);const u=document.createElement("span");u.className="kalotyp-rotate-input-group",u.appendChild(a),u.appendChild(s);const d=document.createElement("div");return d.className="kalotyp-rotate-row kalotyp-rotate-slider-row",d.appendChild(i),d.appendChild(r),d.appendChild(u),d.appendChild(c),e.appendChild(l),e.appendChild(d),{container:e,angleSlider:r,angleInput:a}}function aa(t){const e=Math.round(t*10)/10;return Number.isInteger(e)?String(e):e.toFixed(1)}function sa(){}function Nn(t,e,n){const o=document.createElement("button");return o.type="button",o.className="kalotyp-quarter-button",o.setAttribute("aria-label",t),o.title=t,o.textContent=e,o.addEventListener("click",n),o}function ca(t){return{id:"rotate",init:()=>_o(),mount(e,n,o){const i=ia({stageHost:e,utilHost:t.panelHost,source:n.source,store:o,viewport:n.viewport,onCommit:()=>n.bus.emit("commit",{utility:"rotate"})});return{destroy:()=>i.destroy()}},bake:Xo}}function la(t){const{stageHost:e,utilHost:n,source:o,store:i,viewport:r}=t,a=t.onCommit??(()=>{}),s=yt();e.appendChild(s.container);const c={width:o.width,height:o.height},l=ua({upstream:c,onWidthChange:p=>{i.set(Go(i.get(),p,c)),a()},onHeightChange:p=>{i.set(Ko(i.get(),p,c)),a()},onPercentChange:p=>{i.set(Vo(i.get(),p)),a()},onLockChange:p=>{i.set(jo(i.get(),p)),a()}});n.appendChild(l.container);function u(){const p=Ht(s.container,c,r);p&&re(s.canvas,p.stageWidth,p.stageHeight,w=>{const y=p.viewport.displayRect;w.drawImage(o.bitmap,y.x,y.y,y.width,y.height)})}function d(p){const w=Ye(p,c);l.widthInput.valueAsNumber!==w.width&&(l.widthInput.value=String(w.width)),l.heightInput.valueAsNumber!==w.height&&(l.heightInput.value=String(w.height));const y=(p.scaleX+p.scaleY)/2,C=Math.round(y*1e3)/10;Number.parseFloat(l.percentInput.value||"0")!==C&&(l.percentInput.value=String(C)),l.lockButton.setAttribute("aria-pressed",p.lockAspect?"true":"false"),l.lockButton.setAttribute("aria-label",p.lockAspect?"Aspect ratio locked — click to unlock":"Aspect ratio unlocked — click to lock"),l.lockButton.title=p.lockAspect?"Aspect ratio locked":"Aspect ratio unlocked",l.lockButton.innerHTML=Ln(p.lockAspect),l.summary.textContent=`${w.width} × ${w.height}px (from ${c.width} × ${c.height}px)`}d(i.get()),u();const h=new ResizeObserver(()=>u());h.observe(s.container);let f=!1;const m=r?.subscribe(()=>{f||(f=!0,requestAnimationFrame(()=>{f=!1,u()}))}),g=i.subscribe(p=>{d(p)});return{destroy(){g(),m?.(),h.disconnect(),s.container.remove(),l.container.remove()}}}function ua(t){const e=document.createElement("div");e.className="kalotyp-resize-panel",e.setAttribute("role","group"),e.setAttribute("aria-label","Resize");const n=ae({label:"Width (px)",min:Et,max:ht,step:1,value:t.upstream.width,onChange:t.onWidthChange}),o=ae({label:"Height (px)",min:Et,max:ht,step:1,value:t.upstream.height,onChange:t.onHeightChange}),i=ae({label:"Scale (%)",min:1,max:1e3,step:.1,value:100,onChange:t.onPercentChange}),r=document.createElement("button");r.type="button",r.className="kalotyp-resize-lock",r.setAttribute("aria-pressed","true"),r.setAttribute("aria-label","Lock aspect ratio"),r.title="Lock aspect ratio",r.innerHTML=Ln(!0),r.addEventListener("click",()=>{const l=r.getAttribute("aria-pressed")!=="true";t.onLockChange(l)});const a=document.createElement("span");a.className="kalotyp-resize-summary",a.setAttribute("aria-live","polite"),a.textContent=`${t.upstream.width} × ${t.upstream.height}px`,e.title=`Maximum ${ht}px on either axis`;const s=document.createElement("div");s.className="kalotyp-resize-row kalotyp-resize-dims",s.appendChild(n.wrapper),s.appendChild(r),s.appendChild(o.wrapper);const c=document.createElement("div");return c.className="kalotyp-resize-row",c.appendChild(i.wrapper),c.appendChild(a),e.appendChild(s),e.appendChild(c),{container:e,widthInput:n.input,heightInput:o.input,percentInput:i.input,lockButton:r,summary:a}}function ae(t){const e=document.createElement("label");e.className="kalotyp-resize-field";const n=document.createElement("span");n.className="kalotyp-resize-field-label",n.textContent=t.label;const o=document.createElement("input");return o.type="number",o.className="kalotyp-resize-input",o.min=String(t.min),o.max=String(t.max),o.step=String(t.step),o.value=String(t.value),o.inputMode="numeric",o.setAttribute("aria-label",t.label),o.addEventListener("change",()=>{const i=o.valueAsNumber;Number.isFinite(i)&&t.onChange(i)}),e.appendChild(n),e.appendChild(o),{wrapper:e,input:o}}function Ln(t){return B(t?"lockClosed":"lockOpen")}function da(t){return{id:"resize",init:()=>Yo(),mount(e,n,o){const i=la({stageHost:e,utilHost:t.panelHost,source:n.source,store:o,viewport:n.viewport,onCommit:()=>n.bus.emit("commit",{utility:"resize"})});return{destroy:()=>i.destroy()}},bake:Jo}}function Tn(t){const{canvas:e,sourceBitmap:n}=t;let o;function i(s,c){if(s<=0||c<=0)return;const l=Fn(e);if(!l)return;e.width=s,e.height=c,l.imageSmoothingEnabled=!0,l.imageSmoothingQuality="high",l.clearRect(0,0,s,c),l.drawImage(n,0,0,s,c);const u=l.getImageData(0,0,s,c);o={baseline:new Uint8ClampedArray(u.data),scratch:u.data,blurred:void 0,width:s,height:c}}function r(s){if(!o)return;const c=Fn(e);if(!c)return;if(Gt(s)){const d=new ImageData(new Uint8ClampedArray(o.baseline),o.width,o.height);c.putImageData(d,0,0);return}const l=je(s);if(Qe(o.baseline,o.scratch,l,s),s.clarity!==0){if(!o.blurred){const d=new Uint8ClampedArray(o.baseline.length),h=new Uint8ClampedArray(o.baseline.length);Ze(o.baseline,d,h,o.width,o.height),o.blurred=h}Je(o.scratch,o.blurred,s.clarity)}const u=new ImageData(o.scratch,o.width,o.height);c.putImageData(u,0,0)}function a(){o=void 0}return{paint:r,rebuild:i,dispose:a}}function Fn(t){return t.getContext("2d",{willReadFrequently:!0})}function ha(t){const{stageHost:e,utilHost:n,source:o,store:i,viewport:r}=t,a=t.onCommit??fa,s=yt();e.appendChild(s.container);const c=Tn({canvas:s.canvas,sourceBitmap:o.bitmap}),l=pa({onSliderInput:(y,C)=>i.set(Ve(i.get(),y,C)),onSliderCommit:()=>a(),onNumberCommit:(y,C)=>{i.set(Ve(i.get(),y,C)),a()},onRowReset:y=>{i.set(ei(i.get(),y)),a()},onResetAll:()=>{i.update(()=>ni()),a()}});n.appendChild(l.container);let u={width:0,height:0};function d(){const y=Ht(s.container,{width:o.width,height:o.height},r);if(!y)return;const C=y.viewport.displayRect,E=Math.max(1,window.devicePixelRatio||1),S=Math.max(1,Math.round(C.width*E)),M=Math.max(1,Math.round(C.height*E));s.canvas.style.width=`${C.width}px`,s.canvas.style.height=`${C.height}px`,s.canvas.style.position="absolute",s.canvas.style.left=`${C.x}px`,s.canvas.style.top=`${C.y}px`,!(r?.getPinching()??!1)&&(u.width!==S||u.height!==M)&&(u={width:S,height:M},c.rebuild(S,M)),c.paint(i.get())}function h(y){for(const C of Ke){const E=l.rows.get(C.key);if(!E)continue;const S=y[C.key];E.slider.valueAsNumber!==S&&(E.slider.valueAsNumber=S),Number.parseFloat(E.input.value||"0")!==S&&(E.input.value=String(S))}}h(i.get()),d();const f=new ResizeObserver(()=>d());f.observe(s.container);let m=!1;const g=r?.subscribe(()=>{m||(m=!0,requestAnimationFrame(()=>{m=!1,d()}))});let p=!1;const w=i.subscribe(y=>{h(y),!p&&(p=!0,requestAnimationFrame(()=>{p=!1,c.paint(i.get())}))});return{destroy(){w(),g?.(),f.disconnect(),c.dispose(),s.container.remove(),l.container.remove()}}}function pa(t){const e=document.createElement("div");e.className="kalotyp-finetune-panel",e.setAttribute("role","group"),e.setAttribute("aria-label","Finetune adjustments");const n=new Map;for(const i of Ke){const r=ma(i.key,i.label,t);n.set(i.key,r),e.appendChild(r.row)}const o=document.createElement("button");return o.type="button",o.className="kalotyp-finetune-reset-all",o.textContent="Reset all",o.title="Reset every adjustment to 0",o.addEventListener("click",t.onResetAll),e.appendChild(o),{container:e,rows:n,resetAllButton:o}}function ma(t,e,n){const o=document.createElement("div");o.className="kalotyp-finetune-row",o.dataset.adjustment=t;const i=document.createElement("label");i.className="kalotyp-finetune-label",i.textContent=e;const r=document.createElement("input");r.type="range",r.className="kalotyp-finetune-slider",r.min=String(Mt),r.max=String(It),r.step=String(Rt),r.value="0",r.setAttribute("aria-label",`${e} adjustment`),r.addEventListener("input",()=>n.onSliderInput(t,r.valueAsNumber)),r.addEventListener("change",()=>n.onSliderCommit());const a=document.createElement("input");a.type="number",a.className="kalotyp-finetune-input",a.min=String(Mt),a.max=String(It),a.step=String(Rt),a.value="0",a.inputMode="numeric",a.setAttribute("aria-label",`${e} value`),a.addEventListener("change",()=>{const c=a.valueAsNumber;Number.isFinite(c)&&n.onNumberCommit(t,c)});const s=document.createElement("button");return s.type="button",s.className="kalotyp-finetune-row-reset",s.setAttribute("aria-label",`Reset ${e}`),s.title=`Reset ${e}`,s.textContent="↺",s.addEventListener("click",()=>n.onRowReset(t)),o.appendChild(i),o.appendChild(r),o.appendChild(a),o.appendChild(s),{row:o,slider:r,input:a,resetButton:s}}function fa(){}function ga(t){return{id:"finetune",init:()=>ti(),mount(e,n,o){const i=ha({stageHost:e,utilHost:t.panelHost,source:n.source,store:o,viewport:n.viewport,onCommit:()=>n.bus.emit("commit",{utility:"finetune"})});return{destroy:()=>i.destroy()}},bake:ri}}const Pn=80,$n=60;function ya(t){if(t.width<=0||t.height<=0)return{width:Pn,height:$n};const e=Pn/t.width,n=$n/t.height,o=Math.min(e,n),i=Math.max(1,Math.floor(t.width*o)),r=Math.max(1,Math.floor(t.height*o));return{width:i,height:r}}function ba(t){const{source:e,dims:n,dpr:o}=t,i=Math.max(1,Math.round(n.width*o)),r=Math.max(1,Math.round(n.height*o)),a=document.createElement("canvas");a.width=i,a.height=r;const s=a.getContext("2d",{willReadFrequently:!0});if(!s)return{get:()=>wa(n,o),dispose:()=>{}};s.imageSmoothingEnabled=!0,s.imageSmoothingQuality="high",s.drawImage(e,0,0,i,r);const c=s.getImageData(0,0,i,r),l={data:new Uint8ClampedArray(c.data),width:i,height:r},u=new Map;function d(h){const f=document.createElement("canvas");f.width=i,f.height=r,f.style.width=`${n.width}px`,f.style.height=`${n.height}px`;const m=f.getContext("2d");if(!m)return f;const g={data:new Uint8ClampedArray(l.data.length),width:i,height:r};return Kt(h.state,l,g),m.putImageData(new ImageData(g.data,i,r),0,0),f}return{get(h){const f=u.get(h.id);if(f)return f;const m=d(h);return u.set(h.id,m),m},dispose(){u.clear()}}}function wa(t,e){const n=document.createElement("canvas");return n.width=Math.max(1,Math.round(t.width*e)),n.height=Math.max(1,Math.round(t.height*e)),n.style.width=`${t.width}px`,n.style.height=`${t.height}px`,n}function Ca(t){const{stageHost:e,utilHost:n,source:o,store:i,viewport:r}=t,a=t.onCommit??va,s=yt();e.appendChild(s.container);const c=Tn({canvas:s.canvas,sourceBitmap:o.bitmap}),l=ya({width:o.width,height:o.height}),u=Math.max(1,window.devicePixelRatio||1),d=ba({source:o.bitmap,dims:l,dpr:u}),h=xa({presets:Vt,thumbnailCache:d,dims:l,onPresetClick:S=>{const M=i.get();if(jt(M)?.id===S.id&&S.id!=="none"){i.update(()=>pt),a();return}i.update(()=>S.state),a()}});n.appendChild(h.container);let f={width:0,height:0};function m(){const S=Ht(s.container,{width:o.width,height:o.height},r);if(!S)return;const M=S.viewport.displayRect,H=Math.max(1,Math.round(M.width*u)),R=Math.max(1,Math.round(M.height*u));s.canvas.style.width=`${M.width}px`,s.canvas.style.height=`${M.height}px`,s.canvas.style.position="absolute",s.canvas.style.left=`${M.x}px`,s.canvas.style.top=`${M.y}px`,!(r?.getPinching()??!1)&&(f.width!==H||f.height!==R)&&(f={width:H,height:R},c.rebuild(H,R)),c.paint(i.get())}function g(S){const M=jt(S)?.id;h.setActive(M)}g(i.get()),m();const p=new ResizeObserver(()=>m());p.observe(s.container);let w=!1;const y=r?.subscribe(()=>{w||(w=!0,requestAnimationFrame(()=>{w=!1,m()}))});let C=!1;const E=i.subscribe(S=>{g(S),!C&&(C=!0,requestAnimationFrame(()=>{C=!1,c.paint(i.get())}))});return{destroy(){E(),y?.(),p.disconnect(),c.dispose(),d.dispose(),s.container.remove(),h.container.remove()}}}function xa(t){const e=document.createElement("div");e.className="kalotyp-filter-panel",e.setAttribute("role","radiogroup"),e.setAttribute("aria-label","Filter presets");const n=document.createElement("div");n.className="kalotyp-filter-strip",e.appendChild(n);const o=new Map;for(const i of t.presets){const r=document.createElement("button");r.type="button",r.className="kalotyp-filter-thumb",r.dataset.presetId=i.id,r.setAttribute("role","radio"),r.setAttribute("aria-checked","false"),r.setAttribute("aria-label",`${i.label} filter`),r.title=i.label;const a=document.createElement("span");a.className="kalotyp-filter-thumb-image",a.style.width=`${t.dims.width}px`,a.style.height=`${t.dims.height}px`;const s=t.thumbnailCache.get(i);s.classList.add("kalotyp-filter-thumb-canvas"),a.appendChild(s);const c=document.createElement("span");c.className="kalotyp-filter-thumb-check",c.setAttribute("aria-hidden","true"),c.innerHTML="✓",a.appendChild(c);const l=document.createElement("span");l.className="kalotyp-filter-thumb-label",l.textContent=i.label,r.appendChild(a),r.appendChild(l),r.addEventListener("click",()=>t.onPresetClick(i)),n.appendChild(r),o.set(i.id,r)}return{container:e,setActive(i){for(const[r,a]of o){const s=r===i;a.setAttribute("aria-checked",s?"true":"false"),a.classList.toggle("kalotyp-filter-thumb--active",s)}}}}function va(){}function ka(t){return{id:"filter",init:()=>pt,mount(e,n,o){const i=Ca({stageHost:e,utilHost:t.panelHost,source:n.source,store:o,viewport:n.viewport,onCommit:()=>n.bus.emit("commit",{utility:"filter"})});return{destroy:()=>i.destroy()}},bake:Sa}}async function Sa(t,e){return e}const Ea=[{id:"x",label:"Left"},{id:"y",label:"Top"},{id:"width",label:"Width",min:1},{id:"height",label:"Height",min:1}],Aa=[{id:"x1",label:"Start X"},{id:"y1",label:"Start Y"},{id:"x2",label:"End X"},{id:"y2",label:"End Y"}],Ma=[{id:"x",label:"X"},{id:"y",label:"Y"}];function Ia(t){const e=document.createElement("div");e.className="kalotyp-annotate-coords",e.setAttribute("role","group"),e.setAttribute("aria-label","Selected annotation position"),e.hidden=!0;let n=null,o=null;const i=new Map;function r(l){e.replaceChildren(),i.clear();const u=Ra(l);for(const d of u){const h=document.createElement("label");h.className="kalotyp-annotate-coords-field";const f=document.createElement("span");f.className="kalotyp-annotate-coords-label",f.textContent=d.label;const m=document.createElement("input");m.type="number",m.className="kalotyp-annotate-coords-input",m.dataset.field=d.id,m.step="1",m.inputMode="numeric",d.min!==void 0&&(m.min=String(d.min)),d.max!==void 0&&(m.max=String(d.max)),m.setAttribute("aria-label",`${d.label} (pixels)`),m.addEventListener("change",s),h.appendChild(f),h.appendChild(m),e.appendChild(h),i.set(d.id,m)}o=l}function a(l){const u=(d,h)=>{const f=i.get(d);if(!f)return;const m=String(Math.round(h));document.activeElement!==f&&f.value!==m&&(f.value=m)};switch(l.kind){case"rect":case"ellipse":{u("x",l.x),u("y",l.y),u("width",l.width),u("height",l.height);return}case"arrow":{u("x1",l.x1),u("y1",l.y1),u("x2",l.x2),u("y2",l.y2);return}case"text":{u("x",l.x),u("y",l.y);return}default:return}}function s(){if(!n||!o)return;const l=c(n);if(!l)return;const u=Na(n,l);u!==n&&(n=u,t.onShapeChanged(u))}function c(l){const u=d=>{const h=i.get(d);return h?h.valueAsNumber:Number.NaN};switch(l.kind){case"rect":case"ellipse":{const d=Math.round(u("x")),h=Math.round(u("y")),f=Math.round(u("width")),m=Math.round(u("height"));return[d,h,f,m].every(Number.isFinite)?{kind:l.kind,x:d,y:h,width:f,height:m}:null}case"arrow":{const d=Math.round(u("x1")),h=Math.round(u("y1")),f=Math.round(u("x2")),m=Math.round(u("y2"));return[d,h,f,m].every(Number.isFinite)?{kind:"arrow",x1:d,y1:h,x2:f,y2:m}:null}case"text":{const d=Math.round(u("x")),h=Math.round(u("y"));return[d,h].every(Number.isFinite)?{kind:"text",x:d,y:h}:null}default:return null}}return{container:e,updateForShape(l){if(!l){n=null,o=null,e.hidden=!0,e.replaceChildren(),i.clear();return}if(l.kind==="freehand"||l.kind==="highlight"){n=l,o=null,e.hidden=!0,e.replaceChildren(),i.clear();return}n=l,o!==l.kind&&r(l.kind),a(l),e.hidden=!1},destroy(){e.replaceChildren(),i.clear(),e.remove()}}}function Ra(t){switch(t){case"rect":case"ellipse":return Ea;case"arrow":return Aa;case"text":return Ma}}function Na(t,e){switch(t.kind){case"rect":return e.kind!=="rect"?t:{...t,x:e.x,y:e.y,width:e.width,height:e.height};case"ellipse":return e.kind!=="ellipse"?t:{...t,x:e.x,y:e.y,width:e.width,height:e.height};case"arrow":return e.kind!=="arrow"?t:{...t,x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2};case"text":return e.kind!=="text"?t:{...t,x:e.x,y:e.y};default:return t}}const La=[{id:"select",label:"Select",icon:B("select",{fill:"currentColor","stroke-width":1})},{id:"text",label:"Text",icon:B("text")},{id:"rect",label:"Rectangle",icon:B("rect")},{id:"ellipse",label:"Ellipse",icon:B("ellipse")},{id:"arrow",label:"Arrow",icon:B("arrow")},{id:"freehand",label:"Freehand",icon:B("freehand")},{id:"highlight",label:"Highlight",icon:B("highlight")}],Ta=["#ff3b30","#ffcc00","#34c759","#007aff","#ffffff","#000000"];function Fa(t){const e=document.createElement("div");e.className="kalotyp-annotate-panel",e.setAttribute("role","group"),e.setAttribute("aria-label","Annotate");const n=document.createElement("div");n.className="kalotyp-annotate-toolbar",n.setAttribute("role","toolbar"),n.setAttribute("aria-label","Annotation tools");const o=new Map;for(const p of La){const w=document.createElement("button");w.type="button",w.className="kalotyp-annotate-tool",w.dataset.tool=p.id,w.setAttribute("aria-label",p.label),w.title=p.label,w.setAttribute("aria-pressed",p.id===t.initialTool?"true":"false"),w.innerHTML=p.icon,w.addEventListener("click",()=>t.onSelectTool(p.id)),n.appendChild(w),o.set(p.id,w)}const i=document.createElement("div");i.className="kalotyp-annotate-style-row";const r=[],a=document.createElement("div");a.className="kalotyp-annotate-swatches",a.setAttribute("role","radiogroup"),a.setAttribute("aria-label","Color");for(const p of Ta){const w=document.createElement("button");w.type="button",w.className="kalotyp-annotate-swatch",w.setAttribute("role","radio"),w.setAttribute("aria-label",`Use color ${p}`),w.dataset.color=p,w.style.setProperty("--kalotyp-swatch",p),w.addEventListener("click",()=>t.onColorChange(p)),a.appendChild(w),r.push(w)}let s=Hn(t.initialStyle.color);const c=document.createElement("input");c.type="text",c.className="kalotyp-annotate-hex",c.value=s,c.maxLength=7,c.spellcheck=!1,c.autocomplete="off",c.setAttribute("aria-label","Color hex code"),c.setAttribute("placeholder","#000000"),c.style.setProperty("--kalotyp-hex-swatch",s),c.addEventListener("change",()=>{const p=c.value.trim(),w=Pa(p);w?(c.value=w,s=w,c.style.setProperty("--kalotyp-hex-swatch",w),t.onColorChange(w)):c.value=s});const l=document.createElement("label");l.className="kalotyp-annotate-stroke-label",l.textContent="Width";const u=document.createElement("input");u.type="range",u.className="kalotyp-annotate-stroke",u.min="1",u.max="40",u.step="1",u.value=String(t.initialStyle.strokeWidth),u.setAttribute("aria-label","Stroke width"),u.addEventListener("change",()=>t.onStrokeWidthChange(u.valueAsNumber));const d=document.createElement("button");d.type="button",d.className="kalotyp-annotate-delete",d.innerHTML=`${B("delete")}<span>Delete</span>`,d.setAttribute("aria-label","Delete selected annotation"),d.title="Delete (Del)",d.disabled=!t.canDelete,d.addEventListener("click",()=>t.onDeleteSelected());const h=document.createElement("button");h.type="button",h.className="kalotyp-annotate-insert",h.innerHTML=`${B("plus")}<span>Insert at centre</span>`,h.setAttribute("aria-label","Insert annotation at image centre"),h.title="Insert at centre",h.disabled=!Dn(t.initialTool),h.addEventListener("click",()=>t.onInsertAtCenter()),i.appendChild(a),i.appendChild(c),i.appendChild(l),i.appendChild(u),i.appendChild(h),i.appendChild(d),e.appendChild(n),e.appendChild(i),e.appendChild(t.coordInputs);function f(p){for(const[w,y]of o)y.setAttribute("aria-pressed",w===p?"true":"false");h.disabled=!Dn(p)}function m(p){const w=Hn(p.color);c.value.toLowerCase()!==w.toLowerCase()&&(c.value=w),s=w,c.style.setProperty("--kalotyp-hex-swatch",w),u.valueAsNumber!==p.strokeWidth&&(u.value=String(p.strokeWidth));for(const y of r){const C=y.dataset.color?.toLowerCase()===p.color.toLowerCase();y.setAttribute("aria-checked",C?"true":"false")}}function g(p){d.disabled=!p}return m(t.initialStyle),{container:e,toolButtons:o,hexInput:c,colorSwatches:r,strokeRange:u,deleteButton:d,insertButton:h,setActiveTool:f,setStyle:m,setCanDelete:g}}function Dn(t){return t==="select"?!1:rn(t)}function Hn(t){if(/^#[0-9a-fA-F]{6}$/.test(t))return t;if(/^#[0-9a-fA-F]{3}$/.test(t)){const e=t[1],n=t[2],o=t[3];return`#${e}${e}${n}${n}${o}${o}`}return"#000000"}function Pa(t){const e=t.startsWith("#")?t.slice(1):t;if(/^[0-9a-fA-F]{6}$/.test(e))return`#${e.toLowerCase()}`;if(/^[0-9a-fA-F]{3}$/.test(e)){const n=e[0],o=e[1],i=e[2];return`#${n}${n}${o}${o}${i}${i}`.toLowerCase()}return null}function Ot(t,e){const n=o=>{if(o.button!==0)return;const i=e(o);if(!i)return;o.preventDefault(),o.stopPropagation();try{t.setPointerCapture(o.pointerId)}catch{}let r,a=!1,s=o.shiftKey;const c=()=>{if(a=!1,!r)return;const g=r;r=void 0,i.onMove(g)},l=g=>{r=g,a||(a=!0,requestAnimationFrame(c))},u=g=>{g.pointerId===o.pointerId&&(s=g.shiftKey,l({clientX:g.clientX,clientY:g.clientY,shiftKey:g.shiftKey}))},d=g=>{if(g.key!=="Shift"||g.shiftKey===s)return;s=g.shiftKey;const p=r,w=p?.clientX??o.clientX,y=p?.clientY??o.clientY;l({clientX:w,clientY:y,shiftKey:g.shiftKey})},h=g=>{t.removeEventListener("pointermove",u),t.removeEventListener("pointerup",f),t.removeEventListener("pointercancel",m),window.removeEventListener("keydown",d),window.removeEventListener("keyup",d);try{t.releasePointerCapture(o.pointerId)}catch{}if(r){const p=r;r=void 0,i.onMove(p)}g?i.onCommit():i.onCancel()},f=g=>{g.pointerId===o.pointerId&&h(!0)},m=g=>{g.pointerId===o.pointerId&&h(!1)};t.addEventListener("pointermove",u),t.addEventListener("pointerup",f),t.addEventListener("pointercancel",m),window.addEventListener("keydown",d),window.addEventListener("keyup",d)};return t.addEventListener("pointerdown",n),()=>t.removeEventListener("pointerdown",n)}function On(t,e,n){const o=t.getBoundingClientRect();return{x:e-o.left,y:n-o.top}}function zt(t,e,n){const o=Math.max(1,window.devicePixelRatio||1),i=Math.max(1,Math.round(e*o)),r=Math.max(1,Math.round(n*o));t.width!==i&&(t.width=i),t.height!==r&&(t.height=r),t.style.width=`${e}px`,t.style.height=`${n}px`;const a=t.getContext("2d");return a?(a.setTransform(o,0,0,o,0,0),a.clearRect(0,0,e,n),a):null}function $a(t,e,n,o,i){const r=zt(t,n,o);r&&(r.imageSmoothingEnabled=!0,r.imageSmoothingQuality="high",r.drawImage(e.bitmap,i.displayRect.x,i.displayRect.y,i.displayRect.width,i.displayRect.height))}function zn(t,e,n,o,i){const r=zt(t,n,o);if(r&&e.length!==0){r.save(),r.translate(i.displayRect.x,i.displayRect.y),r.scale(i.scale,i.scale);for(const a of e)te(r,a);r.restore()}}function Bn(t,e,n,o,i){const r=zt(t,n,o);r&&e!==null&&(r.save(),r.translate(i.displayRect.x,i.displayRect.y),r.scale(i.scale,i.scale),te(r,e),r.restore())}function Da(t,e,n,o,i){const r=zt(t,n,o);if(!r||!e)return;const a=i.displayRect.x+e.x*i.scale,s=i.displayRect.y+e.y*i.scale;let c=e.width*i.scale,l=e.height*i.scale,u=a,d=s;c<0&&(u=a+c,c=-c),l<0&&(d=s+l,l=-l),r.save(),r.fillStyle="rgba(99, 102, 241, 0.12)",r.fillRect(u,d,c,l),r.strokeStyle="rgba(99, 102, 241, 0.95)",r.lineWidth=1,r.setLineDash([4,3]),r.strokeRect(u+.5,d+.5,c-1,l-1),r.restore()}function Ha(t){const{host:e,toolContext:n}=t,o=new Map,i=[];for(const s of Tt){const c=document.createElement("button");c.type="button",c.className="kalotyp-annotate-handle",c.dataset.direction=s,c.setAttribute("aria-label",Ba(s)),c.tabIndex=-1,c.style.display="none",o.set(s,c),e.appendChild(c),i.push(Ot(c,l=>Oa(n,s)))}function r(s,c){if(!s){_n(o);return}if(s.kind==="arrow"){_n(o);const d=o.get("tl"),h=o.get("br");d&&ce(d,se({x:s.x1,y:s.y1},c)),h&&ce(h,se({x:s.x2,y:s.y2},c));return}const l=ft(s),u=mi(l);for(const d of Tt){const h=o.get(d);h&&ce(h,se(u[d],c))}}function a(){for(const s of i)s();for(const[,s]of o)s.remove();o.clear()}return{update:r,destroy:a}}function se(t,e){return{x:e.displayRect.x+t.x*e.scale,y:e.displayRect.y+t.y*e.scale}}function ce(t,e){t.style.display="",t.style.left=`${e.x}px`,t.style.top=`${e.y}px`}function _n(t){for(const[,e]of t)e.style.display="none"}function Oa(t,e,n){const o=t.store.get(),i=o.shapes.find(a=>a.id===o.selectedId);if(!i)return null;const r=i;return{onMove(a){const s=t.toImageSpace(a),c=za(r,e,s);c&&t.store.update(l=>nt(l,c))},onCommit(){t.commit()},onCancel(){t.store.update(a=>nt(a,r))}}}function za(t,e,n){switch(t.kind){case"rect":case"ellipse":{const o={x:t.x,y:t.y,width:t.width,height:t.height},i=Jt(o,e,n);return{...t,x:i.x,y:i.y,width:i.width,height:i.height}}case"arrow":{const o=t;return e==="tl"?{...o,x1:n.x,y1:n.y}:e==="br"?{...o,x2:n.x,y2:n.y}:t}case"text":{if(e!=="br")return t;const o=n.x-t.x,i=n.y-t.y,r=Math.max(8,Math.round(Math.max(o,i)*.6));return{...t,fontSize:r}}case"freehand":case"highlight":{const o=ft(t);if(o.width===0||o.height===0)return t;const i=Jt(o,e,n),r=i.width/o.width,a=i.height/o.height;if(!Number.isFinite(r)||!Number.isFinite(a))return t;const s=t.points.map(c=>({x:i.x+(c.x-o.x)*r,y:i.y+(c.y-o.y)*a}));return{...t,points:s}}}}function Ba(t){switch(t){case"tl":return"Resize from top-left";case"tr":return"Resize from top-right";case"bl":return"Resize from bottom-left";case"br":return"Resize from bottom-right";case"t":return"Resize from top";case"r":return"Resize from right";case"b":return"Resize from bottom";case"l":return"Resize from left"}}function Z(t){return t.selectedId===null?null:t.shapes.find(e=>e.id===t.selectedId)??null}function _a(){const t=document.createElement("div");t.className="kalotyp-annotate-stage";const e=document.createElement("canvas");e.className="kalotyp-annotate-image",e.setAttribute("aria-hidden","true");const n=document.createElement("canvas");n.className="kalotyp-annotate-shapes",n.setAttribute("aria-hidden","true");const o=document.createElement("canvas");o.className="kalotyp-annotate-live",o.setAttribute("aria-hidden","true");const i=document.createElement("div");i.className="kalotyp-annotate-hit",i.setAttribute("role","presentation");const r=document.createElement("div");r.className="kalotyp-annotate-handles",r.setAttribute("role","group"),r.setAttribute("aria-label","Selected annotation");const a=document.createElement("div");return a.className="kalotyp-annotate-text-overlay",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(i),t.appendChild(r),t.appendChild(a),{container:t,imageCanvas:e,shapesCanvas:n,liveCanvas:o,hitArea:i,handlesLayer:r,textOverlay:a}}function Wa(t){const e=document.createElement("div");e.className="kalotyp-annotate-text-editor",e.setAttribute("contenteditable","true"),e.setAttribute("role","textbox"),e.setAttribute("aria-label","Annotation text"),e.spellcheck=!1,e.style.display="none",t.host.appendChild(e);let n=null;const o=()=>{t.onInput(e.innerText)},i=a=>{if(a.key==="Enter"&&!a.shiftKey){a.preventDefault(),a.stopPropagation(),t.onCommit();return}a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),t.onCancel())},r=a=>{n!==null&&(e.contains(a.target)||t.onCommit())};return e.addEventListener("input",o),e.addEventListener("keydown",i),document.addEventListener("pointerdown",r,!0),{open(a,s,c){n=a;const l=s.displayRect.x+a.x*s.scale,u=s.displayRect.y+a.y*s.scale;e.style.display="",e.style.left=`${l}px`,e.style.top=`${u}px`,e.style.color=a.color,e.style.font=`${a.fontSize*s.scale}px ${ln}`,e.style.textAlign=a.textAlign,e.style.transformOrigin=qa(a.textAlign);const d=Math.max(100,s.displayRect.x+s.displayRect.width-l-8);e.style.maxWidth=`${d}px`,e.innerText=a.text,requestAnimationFrame(()=>{e.focus();const h=document.createRange();h.selectNodeContents(e),h.collapse(!1);const f=window.getSelection();f?.removeAllRanges(),f?.addRange(h)})},close(){n=null,e.style.display="none",e.blur()},destroy(){e.removeEventListener("input",o),e.removeEventListener("keydown",i),document.removeEventListener("pointerdown",r,!0),e.remove()}}}function qa(t){switch(t){case"left":return"top left";case"center":return"top center";case"right":return"top right"}}function Wn(t,e){const n=e.x-t.x,o=e.y-t.y,i=Math.max(Math.abs(n),Math.abs(o)),r=n===0?1:Math.sign(n),a=o===0?1:Math.sign(o);return{x:t.x+r*i,y:t.y+a*i}}function Ua(t,e){const n=e.x-t.x,o=e.y-t.y,i=Math.sqrt(n*n+o*o);if(i===0)return t;const r=Math.atan2(o,n),a=Math.round(r/(Math.PI/4))*(Math.PI/4);return{x:t.x+Math.cos(a)*i,y:t.y+Math.sin(a)*i}}function Xa(t,e){const n=e.x-t.x,o=e.y-t.y;return Math.abs(n)>=Math.abs(o)?{x:e.x,y:t.y}:{x:t.x,y:e.y}}function Ya(t,e){const n=t.toImageSpace(e),o=t.store.get(),{id:i,nextShapeNumber:r}=at(o);let a=n;return{onMove(s){const c=t.toImageSpace(s);a=s.shiftKey?Wn(n,c):c;const l={id:i,kind:"rect",x:n.x,y:n.y,width:a.x-n.x,height:a.y-n.y,strokeColor:o.currentStyle.color,strokeWidth:o.currentStyle.strokeWidth,fillColor:o.currentStyle.fillColor};t.setLiveShape(l)},onCommit(){const s=nn({x:n.x,y:n.y,width:a.x-n.x,height:a.y-n.y});if(t.setLiveShape(null),s.width<2||s.height<2)return;const c={id:i,kind:"rect",...s,strokeColor:o.currentStyle.color,strokeWidth:o.currentStyle.strokeWidth,fillColor:o.currentStyle.fillColor};t.store.update(l=>({...st(l,c),nextShapeNumber:r})),t.commit()},onCancel(){t.setLiveShape(null)}}}function Ga(t,e){const n=t.toImageSpace(e),o=t.store.get(),{id:i,nextShapeNumber:r}=at(o);let a=n;return{onMove(s){const c=t.toImageSpace(s);a=s.shiftKey?Wn(n,c):c;const l={id:i,kind:"ellipse",x:n.x,y:n.y,width:a.x-n.x,height:a.y-n.y,strokeColor:o.currentStyle.color,strokeWidth:o.currentStyle.strokeWidth,fillColor:o.currentStyle.fillColor};t.setLiveShape(l)},onCommit(){const s=nn({x:n.x,y:n.y,width:a.x-n.x,height:a.y-n.y});if(t.setLiveShape(null),s.width<2||s.height<2)return;const c={id:i,kind:"ellipse",...s,strokeColor:o.currentStyle.color,strokeWidth:o.currentStyle.strokeWidth,fillColor:o.currentStyle.fillColor};t.store.update(l=>({...st(l,c),nextShapeNumber:r})),t.commit()},onCancel(){t.setLiveShape(null)}}}function Ka(t,e){const n=t.toImageSpace(e),o=t.store.get(),{id:i,nextShapeNumber:r}=at(o);let a=n;return{onMove(s){const c=t.toImageSpace(s);a=s.shiftKey?Ua(n,c):c;const l={id:i,kind:"arrow",x1:n.x,y1:n.y,x2:a.x,y2:a.y,color:o.currentStyle.color,strokeWidth:o.currentStyle.strokeWidth};t.setLiveShape(l)},onCommit(){t.setLiveShape(null);const s=a.x-n.x,c=a.y-n.y;if(s*s+c*c<16)return;const l={id:i,kind:"arrow",x1:n.x,y1:n.y,x2:a.x,y2:a.y,color:o.currentStyle.color,strokeWidth:o.currentStyle.strokeWidth};t.store.update(u=>({...st(u,l),nextShapeNumber:r})),t.commit()},onCancel(){t.setLiveShape(null)}}}function qn(t,e,n){const o=t.toImageSpace(e),i=t.store.get(),{id:r,nextShapeNumber:a}=at(i),s=[o];let c=!1,l=o;const u=n.kind==="highlight",d=u?si:i.currentStyle.color,h=u?ci:i.currentStyle.strokeWidth;function f(m){const g={id:r,kind:n.kind,points:m,color:d,strokeWidth:h};t.setLiveShape(g)}return{onMove(m){const g=t.toImageSpace(m);c=m.shiftKey,m.shiftKey?(l=Xa(o,g),f([o,l])):(s.push(g),f(s))},onCommit(){t.setLiveShape(null);const m=c?[o,l]:wi(s);if(m.length<2)return;if(m.length===2){const p=m[0],w=m[1];if(p&&w){const y=w.x-p.x,C=w.y-p.y;if(y*y+C*C<4)return}}const g={id:r,kind:n.kind,points:m,color:d,strokeWidth:h};t.store.update(p=>({...st(p,g),nextShapeNumber:a})),t.commit()},onCancel(){t.setLiveShape(null)}}}function Va(t,e,n,o,i,r){const a=t.toImageSpace(e);return t.store.update(s=>mt(s,n)),{onMove(s){const c=t.toImageSpace(s),l=i(o,c.x-a.x,c.y-a.y);r(l)},onCommit(){t.commit()},onCancel(){r(o)}}}const Un=32;function ja(t){const{stageHost:e,utilHost:n,source:o,store:i,viewport:r}=t,a=t.onCommit??(()=>{}),s=t.onAnnounce??(()=>{}),c=_a();e.appendChild(c.container);let l=j({width:1,height:1,padding:Un},{width:o.width,height:o.height}),u=null,d=null;function h(){const b=c.container.getBoundingClientRect(),k={width:b.width,height:b.height,padding:Un},L={width:o.width,height:o.height};l=r?r.computeViewport(k,L):j(k,L)}function f(){const b=c.container.getBoundingClientRect();b.width<=0||b.height<=0||($a(c.imageCanvas,o,b.width,b.height,l),zn(c.shapesCanvas,i.get().shapes,b.width,b.height,l),Bn(c.liveCanvas,u,b.width,b.height,l),E.update(Z(i.get()),l))}function m(){const b=c.container.getBoundingClientRect();b.width<=0||b.height<=0||zn(c.shapesCanvas,i.get().shapes,b.width,b.height,l)}function g(){const b=c.container.getBoundingClientRect();b.width<=0||b.height<=0||(d!==null?Da(c.liveCanvas,d,b.width,b.height,l):Bn(c.liveCanvas,u,b.width,b.height,l))}function p(b){u=b,d=null,g()}function w(b){d=b,u=null,g()}function y(b){const k=On(c.container,b.clientX,b.clientY);return Wt(k,l)}const C={store:i,toImageSpace:y,setLiveShape:p,commit:a},E=Ha({host:c.handlesLayer,toolContext:C}),S=Wa({host:c.textOverlay,onInput:b=>{const k=Z(i.get());!k||k.kind!=="text"||i.update(L=>nt(L,{...k,text:b}))},onCommit:()=>{const b=Z(i.get());S.close(),b?.kind==="text"&&b.text.trim().length===0&&i.update(k=>Nt(k,b.id)),a(),i.update(k=>Qt(k,"select"))},onCancel:()=>{const b=Z(i.get());S.close(),b?.kind==="text"&&b.text.length===0&&i.update(k=>Nt(k,b.id)),i.update(k=>Qt(k,"select"))}}),M=Ot(c.hitArea,b=>{const k=i.get();switch(k.activeTool){case"select":return H(k,b);case"rect":return Ya(C,b);case"ellipse":return Ga(C,b);case"arrow":return Ka(C,b);case"freehand":return qn(C,b,{kind:"freehand"});case"highlight":return qn(C,b,{kind:"highlight"});case"text":return A(b),null;default:return null}});function H(b,k){const L=y(k),P=yi(b.shapes,L);return P?(b.selectedId!==P.id&&i.update(v=>mt(v,P.id)),Va(C,k,P.id,P,on,v=>i.update(I=>nt(I,v)))):R(k)}function R(b){const k=y(b);let L=k;return{onMove(P){L=y(P),w({x:k.x,y:k.y,width:L.x-k.x,height:L.y-k.y})},onCommit(){w(null);const P=L.x-k.x,v=L.y-k.y;if(Math.abs(P)<2&&Math.abs(v)<2){i.update(q=>mt(q,null));return}const I=Za({x:k.x,y:k.y,width:P,height:v}),z=ts(i.get().shapes,I);i.update(q=>mt(q,z?.id??null))},onCancel(){w(null)}}}function A(b){const k=i.get(),L=y(b),{id:P,nextShapeNumber:v}=at(k),I={id:P,kind:"text",x:L.x,y:L.y,text:"",fontSize:k.currentStyle.fontSize??tn,color:k.currentStyle.color,textAlign:"left"};i.update(z=>({...st(z,I),nextShapeNumber:v})),S.open(I,l,o)}function T(){const b=i.get(),k=b.activeTool;if(k==="select"||!rn(k))return;const{id:L,nextShapeNumber:P}=at(b),v=pi(k,{imageSize:{width:o.width,height:o.height},style:b.currentStyle,id:L});if(i.update(I=>({...st(I,v),nextShapeNumber:P})),v.kind==="text"){S.open(v,l,o),s("Text annotation placed at centre. Type to enter text.");return}s(`${os(v.kind)} placed at centre. Use arrow keys to nudge, or edit coordinates below.`),requestAnimationFrame(()=>{const I=$.container.querySelector(".kalotyp-annotate-coords-input");I?.focus(),I?.select()})}const $=Ia({onShapeChanged:b=>{i.update(k=>nt(k,b)),a()}}),O=i.get(),W=Fa({initialTool:O.activeTool,initialStyle:O.currentStyle,canDelete:O.selectedId!==null,coordInputs:$.container,onSelectTool:b=>i.update(k=>Qt(k,b)),onColorChange:b=>{i.update(k=>{let L=en(k,{color:b});const P=Z(k);return P&&(L=nt(L,Qa(P,b))),L}),a()},onStrokeWidthChange:b=>{i.update(k=>{let L=en(k,{strokeWidth:b});const P=Z(k);return P&&(L=nt(L,Ja(P,b))),L}),a()},onDeleteSelected:()=>{const b=i.get().selectedId;b&&(i.update(k=>Nt(k,b)),a())},onInsertAtCenter:()=>T()});n.appendChild(W.container),h(),f();const U=new ResizeObserver(()=>{h(),f()});U.observe(c.container);let _=!1;const D=r?.subscribe(()=>{_||(_=!0,requestAnimationFrame(()=>{_=!1,h(),f()}))});let G=i.get().shapes,V=i.get().selectedId,Y=i.get().activeTool,x=i.get().currentStyle;const F=i.subscribe(b=>{const k=b.shapes!==G,L=b.selectedId!==V;k&&(G=b.shapes,m()),L&&(V=b.selectedId,W.setCanDelete(b.selectedId!==null)),b.activeTool!==Y&&(Y=b.activeTool,W.setActiveTool(b.activeTool)),b.currentStyle!==x&&(x=b.currentStyle,W.setStyle(b.currentStyle)),E.update(Z(b),l),(L||k)&&$.updateForShape(Z(b))}),N=b=>{const k=b.target;if(ns(k))return;const L=i.get();if(b.key==="Escape"){L.selectedId!==null&&(b.preventDefault(),b.stopPropagation(),i.update(P=>mt(P,null)),s("Selection cleared."));return}if(b.key==="Delete"||b.key==="Backspace"){if(L.selectedId===null)return;b.preventDefault();const P=L.selectedId;i.update(v=>Nt(v,P)),a();return}if(b.key==="ArrowUp"||b.key==="ArrowDown"||b.key==="ArrowLeft"||b.key==="ArrowRight"){const P=Z(L);if(!P||b.ctrlKey||b.altKey||b.metaKey)return;const v=b.shiftKey?10:1,I=b.key==="ArrowLeft"?-v:b.key==="ArrowRight"?v:0,z=b.key==="ArrowUp"?-v:b.key==="ArrowDown"?v:0;b.preventDefault();const q=on(P,I,z);i.update(K=>nt(K,q)),a()}};return document.addEventListener("keydown",N,!0),{destroy(){document.removeEventListener("keydown",N,!0),M(),F(),D?.(),U.disconnect(),S.destroy(),E.destroy(),c.container.remove(),W.container.remove()}}}function Qa(t,e){switch(t.kind){case"text":return{...t,color:e};case"rect":case"ellipse":return{...t,strokeColor:e};case"arrow":case"freehand":case"highlight":return{...t,color:e}}}function Ja(t,e){switch(t.kind){case"text":return{...t,fontSize:Math.max(8,Math.round(e*4))};case"rect":case"ellipse":case"arrow":case"freehand":case"highlight":return{...t,strokeWidth:e}}}function Za(t){let{x:e,y:n,width:o,height:i}=t;return o<0&&(e+=o,o=-o),i<0&&(n+=i,i=-i),{x:e,y:n,width:o,height:i}}function ts(t,e){for(let n=t.length-1;n>=0;n--){const o=t[n];if(!o)continue;const i=ft(o);if(es(i,e))return o}}function es(t,e){return!(t.x+t.width<e.x||e.x+e.width<t.x||t.y+t.height<e.y||e.y+e.height<t.y)}function ns(t){if(!t)return!1;const e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"?!0:t.isContentEditable===!0}function os(t){switch(t){case"rect":return"Rectangle";case"ellipse":return"Ellipse";case"arrow":return"Arrow";case"text":return"Text annotation"}}function is(t){return{id:"annotate",init:e=>hi({imageSize:{width:e.source.width,height:e.source.height}}),mount(e,n,o){const i=ja({stageHost:e,utilHost:t.panelHost,source:n.source,store:o,viewport:n.viewport,onCommit:()=>n.bus.emit("commit",{utility:"annotate"}),onAnnounce:r=>n.bus.emit("announce",{message:r})});return{destroy:()=>i.destroy()}},bake:(e,n)=>Ci({shapes:e.shapes},n)}}const rs=[{id:"x",label:"Left"},{id:"y",label:"Top"},{id:"width",label:"Width",min:1},{id:"height",label:"Height",min:1}];function as(t){const e=document.createElement("div");e.className="kalotyp-redact-coords",e.setAttribute("role","group"),e.setAttribute("aria-label","Selected redaction position"),e.hidden=!0;let n=null;const o=new Map;for(const s of rs){const c=document.createElement("label");c.className="kalotyp-redact-coords-field";const l=document.createElement("span");l.className="kalotyp-redact-coords-label",l.textContent=s.label;const u=document.createElement("input");u.type="number",u.className="kalotyp-redact-coords-input",u.dataset.field=s.id,u.step="1",u.inputMode="numeric",s.min!==void 0&&(u.min=String(s.min)),u.setAttribute("aria-label",`${s.label} (pixels)`),u.addEventListener("change",r),c.appendChild(l),c.appendChild(u),e.appendChild(c),o.set(s.id,u)}function i(s){const c=(l,u)=>{const d=o.get(l);if(!d)return;const h=String(Math.round(u));document.activeElement!==d&&d.value!==h&&(d.value=h)};c("x",s.x),c("y",s.y),c("width",s.width),c("height",s.height)}function r(){if(!n)return;const s=a("x"),c=a("y"),l=a("width"),u=a("height");if(![s,c,l,u].every(Number.isFinite))return;const d={...n,x:s,y:c,width:l,height:u};d.x===n.x&&d.y===n.y&&d.width===n.width&&d.height===n.height||(n=d,t.onRegionChanged(d))}function a(s){const c=o.get(s);return c?Math.round(c.valueAsNumber):Number.NaN}return{container:e,updateForRegion(s){if(!s){n=null,e.hidden=!0;return}n=s,i(s),e.hidden=!1},destroy(){e.replaceChildren(),o.clear(),e.remove()}}}const ss=[{id:"pixelate",label:"Pixelate"},{id:"blur",label:"Blur"},{id:"solid",label:"Solid fill"}];function cs(t){const e=document.createElement("div");e.className="kalotyp-redact-panel",e.setAttribute("role","group"),e.setAttribute("aria-label","Redact");const n=document.createElement("div");n.className="kalotyp-redact-toolbar",n.setAttribute("role","radiogroup"),n.setAttribute("aria-label","Redaction mode");const o=new Map;for(const g of ss){const p=document.createElement("button");p.type="button",p.className="kalotyp-redact-mode",p.dataset.mode=g.id,p.setAttribute("role","radio"),p.setAttribute("aria-checked",g.id===t.initialMode?"true":"false"),p.setAttribute("aria-label",`${g.label} redaction`),p.title=g.label,p.textContent=g.label,p.addEventListener("click",()=>t.onSelectMode(g.id)),n.appendChild(p),o.set(g.id,p)}const i=document.createElement("div");i.className="kalotyp-redact-style-row";const r=document.createElement("input");r.type="color",r.className="kalotyp-redact-color",r.value=le(t.initialColor),r.setAttribute("aria-label","Solid fill colour (visual picker)"),r.addEventListener("change",()=>t.onColorChange(r.value));const a=document.createElement("input");a.type="text",a.className="kalotyp-redact-hex",a.value=le(t.initialColor),a.maxLength=7,a.spellcheck=!1,a.autocomplete="off",a.setAttribute("aria-label","Solid fill hex code"),a.setAttribute("placeholder","#000000"),a.addEventListener("change",()=>{const g=a.value.trim(),p=ls(g);p?(a.value=p,t.onColorChange(p)):a.value=r.value});const s=document.createElement("button");s.type="button",s.className="kalotyp-redact-insert",s.innerHTML=`${B("plus")}<span>Insert at centre</span>`,s.setAttribute("aria-label","Insert redaction region at image centre"),s.title="Insert at centre",s.addEventListener("click",()=>t.onInsertAtCenter());const c=document.createElement("button");c.type="button",c.className="kalotyp-redact-delete",c.innerHTML=`${B("delete")}<span>Delete</span>`,c.setAttribute("aria-label","Delete selected redaction region"),c.title="Delete (Del)",c.disabled=!t.canDelete,c.addEventListener("click",()=>t.onDeleteSelected());const l=document.createElement("div");l.className="kalotyp-redact-color-group",l.appendChild(r),l.appendChild(a);const u=document.createElement("span");u.className="kalotyp-redact-color-hint",u.textContent="Colour applies to Solid fill only.",u.setAttribute("aria-live","polite");const d=document.createElement("div");d.className="kalotyp-redact-button-group",d.appendChild(s),d.appendChild(c),i.appendChild(l),i.appendChild(u),i.appendChild(d),e.appendChild(n),e.appendChild(i),e.appendChild(t.coordInputs);function h(g){for(const[w,y]of o)y.setAttribute("aria-checked",w===g?"true":"false"),y.classList.toggle("kalotyp-redact-mode--active",w===g);const p=g==="solid";r.disabled=!p,a.disabled=!p,u.hidden=p}function f(g){const p=le(g);r.value!==p&&(r.value=p),a.value.toLowerCase()!==p.toLowerCase()&&(a.value=p)}function m(g){c.disabled=!g}return h(t.initialMode),{container:e,modeButtons:o,colorInput:r,hexInput:a,insertButton:s,deleteButton:c,setActiveMode:h,setColor:f,setCanDelete:m}}function le(t){if(/^#[0-9a-fA-F]{6}$/.test(t))return t;if(/^#[0-9a-fA-F]{3}$/.test(t)){const e=t[1],n=t[2],o=t[3];return`#${e}${e}${n}${n}${o}${o}`}return"#000000"}function ls(t){const e=t.startsWith("#")?t.slice(1):t;if(/^[0-9a-fA-F]{6}$/.test(e))return`#${e.toLowerCase()}`;if(/^[0-9a-fA-F]{3}$/.test(e)){const n=e[0],o=e[1],i=e[2];return`#${n}${n}${o}${o}${i}${i}`.toLowerCase()}return null}function ue(t,e,n){const o=Math.max(1,window.devicePixelRatio||1),i=Math.max(1,Math.round(e*o)),r=Math.max(1,Math.round(n*o));t.width!==i&&(t.width=i),t.height!==r&&(t.height=r),t.style.width=`${e}px`,t.style.height=`${n}px`;const a=t.getContext("2d");return a?(a.setTransform(o,0,0,o,0,0),a.clearRect(0,0,e,n),a):null}function us(t,e,n,o,i){const r=ue(t,n,o);r&&(r.imageSmoothingEnabled=!0,r.imageSmoothingQuality="high",r.drawImage(e.bitmap,i.displayRect.x,i.displayRect.y,i.displayRect.width,i.displayRect.height))}function ds(t,e,n,o,i,r,a){const s=ue(t,i,r);if(!s||n.length===0)return;const c=document.createElement("canvas"),l=Math.max(1,Math.round(a.displayRect.width)),u=Math.max(1,Math.round(a.displayRect.height));c.width=l,c.height=u;const d=c.getContext("2d");if(d){d.imageSmoothingEnabled=!0,d.imageSmoothingQuality="high",d.drawImage(e.bitmap,0,0,l,u);for(const h of n){const f={...h,x:h.x*a.scale,y:h.y*a.scale,width:h.width*a.scale,height:h.height*a.scale};mn(d,c,f,{})}s.drawImage(c,a.displayRect.x,a.displayRect.y,l,u);for(const h of n){const f=a.displayRect.x+h.x*a.scale,m=a.displayRect.y+h.y*a.scale,g=h.width*a.scale,p=h.height*a.scale;s.save(),h.id===o?(s.strokeStyle="rgba(99, 102, 241, 0.9)",s.lineWidth=1.5):(s.strokeStyle="rgba(255, 255, 255, 0.6)",s.lineWidth=1),s.setLineDash([4,3]),s.strokeRect(f+.5,m+.5,Math.max(0,g-1),Math.max(0,p-1)),s.restore()}}}function hs(t,e,n,o,i){const r=ue(t,n,o);if(!r||!e)return;const a=i.displayRect.x+e.x*i.scale,s=i.displayRect.y+e.y*i.scale;let c=e.width*i.scale,l=e.height*i.scale,u=a,d=s;c<0&&(u=a+c,c=-c),l<0&&(d=s+l,l=-l),r.save(),r.fillStyle=ps(e.mode,e.color),r.fillRect(u,d,c,l),r.strokeStyle="rgba(99, 102, 241, 0.95)",r.lineWidth=1.5,r.setLineDash([4,3]),r.strokeRect(u+.75,d+.75,Math.max(0,c-1.5),Math.max(0,l-1.5)),r.restore()}function ps(t,e){switch(t){case"solid":return ms(e,.7);case"pixelate":return"rgba(120, 120, 120, 0.6)";case"blur":return"rgba(180, 200, 220, 0.45)"}}function ms(t,e){const n=/^#([0-9a-fA-F]{6})$/.exec(t);if(!n)return t;const o=n[1];if(!o)return t;const i=Number.parseInt(o.slice(0,2),16),r=Number.parseInt(o.slice(2,4),16),a=Number.parseInt(o.slice(4,6),16);return`rgba(${i}, ${r}, ${a}, ${e})`}function fs(t){const{host:e,store:n}=t,o=new Map,i=[];for(const c of Tt){const l=document.createElement("button");l.type="button",l.className="kalotyp-redact-handle",l.dataset.direction=c,l.setAttribute("aria-label",bs(c)),l.tabIndex=-1,l.style.display="none",o.set(c,l),e.appendChild(l),i.push(Ot(l,u=>s(c)))}function r(c,l){if(!c){for(const[,h]of o)h.style.display="none";return}const u={x:c.x,y:c.y,width:c.width,height:c.height},d=gs(u);for(const h of Tt){const f=o.get(h);if(!f)continue;const m=ys(d[h],l);f.style.display="",f.style.left=`${m.x}px`,f.style.top=`${m.y}px`}}function a(){for(const c of i)c();for(const[,c]of o)c.remove();o.clear()}function s(c,l){const u=lt(n.get());return u?{onMove(d){const h=t.toImageSpace(d),f={x:u.x,y:u.y,width:u.width,height:u.height},m=Jt(f,c,h);n.update(g=>J(g,{...u,x:m.x,y:m.y,width:m.width,height:m.height}))},onCommit(){const d=lt(n.get());if(d&&(d.width<0||d.height<0)){let{x:h,y:f,width:m,height:g}=d;m<0&&(h+=m,m=-m),g<0&&(f+=g,g=-g),n.update(p=>J(p,{...d,x:h,y:f,width:m,height:g}))}t.commit()},onCancel(){n.update(d=>J(d,u))}}:null}return{update:r,destroy:a}}function gs(t){const e=t.x,n=t.x+t.width,o=t.y,i=t.y+t.height,r=t.x+t.width/2,a=t.y+t.height/2;return{tl:{x:e,y:o},tr:{x:n,y:o},bl:{x:e,y:i},br:{x:n,y:i},t:{x:r,y:o},r:{x:n,y:a},b:{x:r,y:i},l:{x:e,y:a}}}function ys(t,e){return{x:e.displayRect.x+t.x*e.scale,y:e.displayRect.y+t.y*e.scale}}function bs(t){switch(t){case"tl":return"Resize from top-left";case"tr":return"Resize from top-right";case"bl":return"Resize from bottom-left";case"br":return"Resize from bottom-right";case"t":return"Resize from top";case"r":return"Resize from right";case"b":return"Resize from bottom";case"l":return"Resize from left"}}function ws(){const t=document.createElement("div");t.className="kalotyp-redact-stage";const e=document.createElement("canvas");e.className="kalotyp-redact-image",e.setAttribute("aria-hidden","true");const n=document.createElement("canvas");n.className="kalotyp-redact-regions",n.setAttribute("aria-hidden","true");const o=document.createElement("canvas");o.className="kalotyp-redact-live",o.setAttribute("aria-hidden","true");const i=document.createElement("div");i.className="kalotyp-redact-hit",i.setAttribute("role","presentation");const r=document.createElement("div");return r.className="kalotyp-redact-handles",r.setAttribute("role","group"),r.setAttribute("aria-label","Selected redaction region"),t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(i),t.appendChild(r),{container:t,imageCanvas:e,regionsCanvas:n,liveCanvas:o,hitArea:i,handlesLayer:r}}const Xn=32;function Cs(t){const{stageHost:e,utilHost:n,source:o,store:i,viewport:r}=t,a=t.onCommit??(()=>{}),s=t.onAnnounce??(()=>{}),c=Di(i.get(),{width:o.width,height:o.height});c!==i.get()&&i.update(()=>c);const l=ws();e.appendChild(l.container);let u=j({width:1,height:1,padding:Xn},{width:o.width,height:o.height}),d=null;function h(){const x=l.container.getBoundingClientRect(),F={width:x.width,height:x.height,padding:Xn},N={width:o.width,height:o.height};u=r?r.computeViewport(F,N):j(F,N)}function f(){const x=l.container.getBoundingClientRect();x.width<=0||x.height<=0||us(l.imageCanvas,o,x.width,x.height,u)}function m(){const x=l.container.getBoundingClientRect();if(x.width<=0||x.height<=0)return;const F=i.get();ds(l.regionsCanvas,o,F.regions,F.selectedId,x.width,x.height,u)}function g(){const x=l.container.getBoundingClientRect();x.width<=0||x.height<=0||hs(l.liveCanvas,d,x.width,x.height,u)}function p(){f(),m(),g(),C.update(lt(i.get()),u)}function w(x){d=x,g()}function y(x){const F=On(l.container,x.clientX,x.clientY);return Wt(F,u)}const C=fs({host:l.handlesLayer,store:i,toImageSpace:y,getViewport:()=>u,commit:a}),E=Ot(l.hitArea,x=>{const F=i.get(),N=y(x),b=xs(F.regions,N);return b?(F.selectedId!==b.id&&i.update(k=>pn(k,b.id)),S(b,x)):M(F,x)});function S(x,F){const N=y(F);return{onMove(b){const k=y(b),L=k.x-N.x,P=k.y-N.y;i.update(v=>J(v,{...x,x:x.x+L,y:x.y+P}))},onCommit(){a()},onCancel(){i.update(b=>J(b,x))}}}function M(x,F){const N=y(F);let b=N;return{onMove(k){const L=y(k);if(k.shiftKey){const P=L.x-N.x,v=L.y-N.y,I=Math.max(Math.abs(P),Math.abs(v)),z=P===0?1:Math.sign(P),q=v===0?1:Math.sign(v);b={x:N.x+z*I,y:N.y+q*I}}else b=L;w({x:N.x,y:N.y,width:b.x-N.x,height:b.y-N.y,mode:x.currentMode,color:x.currentColor})},onCommit(){w(null);const k=Pi({x:N.x,y:N.y,width:b.x-N.x,height:b.y-N.y});if(k.width<4||k.height<4)return;const{id:L,nextRegionNumber:P}=un(x),v={id:L,x:k.x,y:k.y,width:k.width,height:k.height,mode:x.currentMode,color:x.currentColor};i.update(I=>({...dn(I,v),nextRegionNumber:P})),a()},onCancel(){w(null)}}}function H(){const x=i.get(),{id:F,nextRegionNumber:N}=un(x),b=$i({imageSize:{width:o.width,height:o.height},mode:x.currentMode,color:x.currentColor,id:F});i.update(k=>({...dn(k,b),nextRegionNumber:N})),s("Redaction region placed at centre. Use arrow keys to nudge, or edit coordinates below."),requestAnimationFrame(()=>{const k=R.container.querySelector(".kalotyp-redact-coords-input");k?.focus(),k?.select()}),a()}const R=as({onRegionChanged:x=>{i.update(F=>J(F,x)),a()}}),A=i.get(),T=cs({initialMode:A.currentMode,initialColor:A.currentColor,canDelete:A.selectedId!==null,coordInputs:R.container,onSelectMode:x=>{i.update(F=>{const N=Ni(F,x);return N.selectedId===null?N:Ti(N,N.selectedId,x)}),a()},onColorChange:x=>{i.update(F=>{const N=Li(F,x);return N.selectedId===null?N:Fi(N,N.selectedId,x)}),a()},onInsertAtCenter:()=>H(),onDeleteSelected:()=>{const x=i.get().selectedId;x&&(i.update(F=>hn(F,x)),a())}});n.appendChild(T.container),h(),p();const $=new ResizeObserver(()=>{h(),p()});$.observe(l.container);let O=!1;const W=r?.subscribe(()=>{O||(O=!0,requestAnimationFrame(()=>{O=!1,h(),p()}))});let U=i.get().regions,_=i.get().selectedId,D=i.get().currentMode,G=i.get().currentColor;const V=i.subscribe(x=>{const F=x.regions!==U,N=x.selectedId!==_;F&&(U=x.regions,m()),N&&(_=x.selectedId,T.setCanDelete(x.selectedId!==null)),x.currentMode!==D&&(D=x.currentMode,T.setActiveMode(x.currentMode)),x.currentColor!==G&&(G=x.currentColor,T.setColor(x.currentColor)),C.update(lt(x),u),(N||F)&&R.updateForRegion(lt(x))}),Y=x=>{const F=x.target;if(vs(F))return;const N=i.get();if(x.key==="Escape"){N.selectedId!==null&&(x.preventDefault(),x.stopPropagation(),i.update(b=>pn(b,null)),s("Selection cleared."));return}if(x.key==="Delete"||x.key==="Backspace"){if(N.selectedId===null)return;x.preventDefault();const b=N.selectedId;i.update(k=>hn(k,b)),a();return}if(x.key==="ArrowUp"||x.key==="ArrowDown"||x.key==="ArrowLeft"||x.key==="ArrowRight"){const b=lt(N);if(!b||x.ctrlKey||x.altKey||x.metaKey)return;const k=x.shiftKey?10:1,L=x.key==="ArrowLeft"?-k:x.key==="ArrowRight"?k:0,P=x.key==="ArrowUp"?-k:x.key==="ArrowDown"?k:0;x.preventDefault(),i.update(v=>J(v,{...b,x:b.x+L,y:b.y+P})),a()}};return document.addEventListener("keydown",Y,!0),{destroy(){document.removeEventListener("keydown",Y,!0),E(),V(),W?.(),$.disconnect(),R.destroy(),C.destroy(),l.container.remove(),T.container.remove()}}}function xs(t,e){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o&&e.x>=o.x&&e.x<=o.x+o.width&&e.y>=o.y&&e.y<=o.y+o.height)return o}}function vs(t){if(!t)return!1;const e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"?!0:t.isContentEditable===!0}function ks(t){return{id:"redact",init:e=>Ri({imageSize:{width:e.source.width,height:e.source.height}}),mount(e,n,o){const i=Cs({stageHost:e,utilHost:t.panelHost,source:n.source,store:o,viewport:n.viewport,onCommit:()=>n.bus.emit("commit",{utility:"redact"}),onAnnounce:r=>n.bus.emit("announce",{message:r})});return{destroy:()=>i.destroy()}},bake:(e,n)=>Oi({regions:e.regions},n)}}const Yn=32;function Ss(t){const{stageHost:e,utilHost:n,source:o,store:i,viewport:r}=t,a=t.onCommit??(()=>{}),s=document.createElement("div");s.className="kalotyp-stage-container kalotyp-frame-preview-container";const c=document.createElement("canvas");c.className="kalotyp-stage-image kalotyp-frame-preview-canvas",c.setAttribute("aria-hidden","true"),s.appendChild(c),e.appendChild(s);const l=i.get(),u=document.createElement("div");u.className="kalotyp-frame-panel";const d=Es({presets:fn,initialActiveId:l.presetId,labels:t.labels,source:o,initialState:l,onPresetClick:S=>{i.update(M=>Ui(M,S.id)),a()}});u.appendChild(d.container);const h=As({initialColor:l.color,initialPresetId:l.presetId,onColorChange:S=>{i.update(M=>Xi(M,S)),a()}});u.appendChild(h.container),n.appendChild(u);let f=j({width:1,height:1,padding:Yn},{width:o.width,height:o.height});function m(){const S=s.getBoundingClientRect();if(S.width<=0||S.height<=0)return;const M={width:S.width,height:S.height,padding:Yn},H=i.get(),R=oe(H.presetId,o.width,o.height);f=r?r.computeViewport(M,R):j(M,R)}function g(){const S=s.getBoundingClientRect();if(S.width<=0||S.height<=0)return;const M=Math.max(1,window.devicePixelRatio||1),H=Math.max(1,Math.round(S.width*M)),R=Math.max(1,Math.round(S.height*M));c.width!==H&&(c.width=H),c.height!==R&&(c.height=R),c.style.width=`${S.width}px`,c.style.height=`${S.height}px`;const A=c.getContext("2d");if(!A)return;A.setTransform(M,0,0,M,0,0),A.clearRect(0,0,S.width,S.height),A.imageSmoothingEnabled=!0,A.imageSmoothingQuality="high";const T=i.get(),$=oe(T.presetId,o.width,o.height),O=f.displayRect.x,W=f.displayRect.y,U=f.displayRect.width,_=f.displayRect.height;if(T.presetId==="polaroid"){A.fillStyle=T.color,A.fillRect(O,W,U,_);const D=o.width*(U/$.width),G=o.height*(_/$.height),V=Math.min(o.width,o.height),Y=Math.round(V*.05),x=O+Y*U/$.width,F=W+Y*_/$.height;A.drawImage(o.bitmap,x,F,D,G)}else A.drawImage(o.bitmap,O,W,U,_),T.presetId!=="none"&&(A.save(),A.translate(O,W),ne(A,T.presetId,T.color,U,_),A.restore())}m(),g();const p=new ResizeObserver(()=>{m(),g()});p.observe(s);let w=!1;const y=r?.subscribe(()=>{w||(w=!0,requestAnimationFrame(()=>{w=!1,m(),g()}))});let C=!1;const E=i.subscribe(S=>{d.setActive(S.presetId),h.setColor(S.color),h.setEnabled(S.presetId!=="none"),!C&&(C=!0,requestAnimationFrame(()=>{C=!1,m(),g()}))});return{destroy(){E(),y?.(),p.disconnect(),s.remove(),u.remove()}}}function Es(t){const e=document.createElement("div");e.className="kalotyp-frame-strip-wrap",e.setAttribute("role","radiogroup"),e.setAttribute("aria-label","Frame presets");const n=document.createElement("div");n.className="kalotyp-frame-strip",e.appendChild(n);const o=new Map;for(const r of t.presets){const a=document.createElement("button");a.type="button",a.className="kalotyp-frame-thumb",a.dataset.presetId=r.id,a.setAttribute("role","radio"),a.setAttribute("aria-checked","false");const s=t.labels?.[r.id]??r.label;a.setAttribute("aria-label",`${s} frame`),a.title=s;const c=document.createElement("span");c.className="kalotyp-frame-thumb-image";const l=Ms(r,t.source,t.initialState.color);l.classList.add("kalotyp-frame-thumb-canvas"),c.appendChild(l);const u=document.createElement("span");u.className="kalotyp-frame-thumb-check",u.setAttribute("aria-hidden","true"),u.innerHTML="✓",c.appendChild(u);const d=document.createElement("span");d.className="kalotyp-frame-thumb-label",d.textContent=s,a.appendChild(c),a.appendChild(d),a.addEventListener("click",()=>t.onPresetClick(r)),n.appendChild(a),o.set(r.id,a)}function i(r){for(const[a,s]of o){const c=a===r;s.setAttribute("aria-checked",c?"true":"false"),s.classList.toggle("kalotyp-frame-thumb--active",c)}}return i(t.initialActiveId),{container:e,setActive:i}}function As(t){const e=document.createElement("div");e.className="kalotyp-frame-color-row";const n=document.createElement("span");n.className="kalotyp-frame-color-label",n.textContent="Colour";const o=document.createElement("input");o.type="color",o.className="kalotyp-frame-color",o.value=de(t.initialColor),o.setAttribute("aria-label","Frame colour (visual picker)"),o.addEventListener("change",()=>t.onColorChange(o.value));const i=document.createElement("input");i.type="text",i.className="kalotyp-frame-hex",i.value=de(t.initialColor),i.maxLength=7,i.spellcheck=!1,i.autocomplete="off",i.setAttribute("aria-label","Frame colour hex code"),i.setAttribute("placeholder","#000000"),i.addEventListener("change",()=>{const c=i.value.trim(),l=Is(c);l?(i.value=l,t.onColorChange(l)):i.value=o.value});const r=document.createElement("span");r.className="kalotyp-frame-color-hint",r.textContent="Pick a frame preset to choose a colour.",r.setAttribute("aria-live","polite"),e.appendChild(n),e.appendChild(o),e.appendChild(i),e.appendChild(r);function a(c){o.disabled=!c,i.disabled=!c,r.hidden=c}function s(c){const l=de(c);o.value!==l&&(o.value=l),i.value.toLowerCase()!==l.toLowerCase()&&(i.value=l)}return a(t.initialPresetId!=="none"),{container:e,setColor:s,setEnabled:a}}function Ms(t,e,n){const o={width:80,height:60},i=oe(t.id,e.width,e.height),r=Math.min(o.width/i.width,o.height/i.height),a=Math.max(1,Math.floor(i.width*r)),s=Math.max(1,Math.floor(i.height*r)),c=Math.max(1,window.devicePixelRatio||1),l=document.createElement("canvas");l.width=Math.max(1,Math.round(a*c)),l.height=Math.max(1,Math.round(s*c)),l.style.width=`${a}px`,l.style.height=`${s}px`;const u=l.getContext("2d");if(!u)return l;if(u.setTransform(c,0,0,c,0,0),u.imageSmoothingEnabled=!0,u.imageSmoothingQuality="high",t.id==="polaroid"){u.fillStyle=n,u.fillRect(0,0,a,s);const d=Math.min(e.width,e.height),h=Math.round(d*.05/i.width*a),f=Math.round(d*.05/i.height*s),m=Math.round(e.width/i.width*a),g=Math.round(e.height/i.height*s);u.drawImage(e.bitmap,h,f,m,g)}else u.drawImage(e.bitmap,0,0,a,s),t.id!=="none"&&ne(u,t.id,n,a,s);return l}function de(t){if(/^#[0-9a-fA-F]{6}$/.test(t))return t;if(/^#[0-9a-fA-F]{3}$/.test(t)){const e=t[1],n=t[2],o=t[3];return`#${e}${e}${n}${n}${o}${o}`}return"#000000"}function Is(t){const e=t.startsWith("#")?t.slice(1):t;if(/^[0-9a-fA-F]{6}$/.test(e))return`#${e.toLowerCase()}`;if(/^[0-9a-fA-F]{3}$/.test(e)){const n=e[0],o=e[1],i=e[2];return`#${n}${n}${o}${o}${i}${i}`.toLowerCase()}return null}function Rs(t){return{id:"frame",init:()=>qi(),mount(e,n,o){const i=Ss({stageHost:e,utilHost:t.panelHost,source:n.source,store:o,viewport:n.viewport,labels:t.labels,onCommit:()=>n.bus.emit("commit",{utility:"frame"})});return{destroy:()=>i.destroy()}},bake:(e,n)=>Yi(e,n)}}function Ns(t,e,n,o){const i=document.createElement("div");i.className="kalotyp-util-nav",i.setAttribute("role","tablist"),i.setAttribute("aria-label","Editor tools");const r=new Map;for(const a of t){const s=document.createElement("button");s.type="button",s.className="kalotyp-util-nav-button",s.dataset.utilityId=a.id,s.id=`${o.panelId}-tab-${a.id}`,s.setAttribute("role","tab"),s.setAttribute("aria-selected",a.id===e?"true":"false"),s.setAttribute("aria-controls",o.panelId),s.tabIndex=a.id===e?0:-1,s.textContent=a.label,s.addEventListener("click",()=>n(a.id)),i.appendChild(s),r.set(a.id,s)}return i.addEventListener("keydown",a=>{if(a.key!=="ArrowLeft"&&a.key!=="ArrowRight"&&a.key!=="Home"&&a.key!=="End")return;const s=t.map(f=>f.id),l=a.target?.dataset?.utilityId,u=l?s.indexOf(l):-1;if(u===-1)return;let d=u;a.key==="ArrowLeft"?d=(u-1+s.length)%s.length:a.key==="ArrowRight"?d=(u+1)%s.length:a.key==="Home"?d=0:a.key==="End"&&(d=s.length-1);const h=s[d];!h||h===l||(a.preventDefault(),n(h),r.get(h)?.focus())}),{container:i,buttons:r}}function Gn(t,e,n){for(const[o,i]of t.buttons.entries()){const r=o===e;if(i.setAttribute("aria-selected",r?"true":"false"),i.tabIndex=r?0:-1,r){try{i.scrollIntoView({block:"nearest",inline:"nearest",behavior:"smooth"})}catch{}n&&n.setAttribute("aria-labelledby",i.id)}}}const Ls=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])","details","summary",'[tabindex]:not([tabindex="-1"])','[contenteditable="true"]'].join(", ");function Ts(t){const{host:e}=t,n=document.activeElement instanceof HTMLElement&&document.activeElement!==document.body?document.activeElement:null;function o(){return Array.from(e.querySelectorAll(Ls))}const i=t.initialFocus??o()[0];i&&requestAnimationFrame(()=>i.focus());const r=a=>{if(a.key!=="Tab")return;const s=o();if(s.length===0){a.preventDefault();return}const c=s[0],l=s[s.length-1];if(!c||!l)return;const u=document.activeElement;a.shiftKey?(u===c||!e.contains(u))&&(a.preventDefault(),l.focus()):(u===l||!e.contains(u))&&(a.preventDefault(),c.focus())};return document.addEventListener("keydown",r,!0),{refresh:()=>{},release:()=>{if(document.removeEventListener("keydown",r,!0),n?.isConnected)try{n.focus()}catch{}}}}const Fs=1.0015;function Ps(t,e){const n=new Map;let o=null;function i(){return t.getBoundingClientRect()}function r(m,g){const p=i();return{x:m-p.left,y:g-p.top}}function a(){const m=i();return{x:m.width/2,y:m.height/2}}function s(){if(n.size<2)return null;const m=n.values(),g=m.next().value,p=m.next().value,w=r((g.x+p.x)/2,(g.y+p.y)/2),y=p.x-g.x,C=p.y-g.y,E=Math.sqrt(y*y+C*C);return{midpoint:w,distance:E}}function c(){if(n.size<2||o!==null)return;const m=s();!m||m.distance<=0||(o={lastDistance:m.distance,lastMidpoint:m.midpoint},e.setPinching(!0))}function l(){o!==null&&(o=null,e.setPinching(!1))}function u(m){m.pointerType==="mouse"&&m.button!==0||(n.set(m.pointerId,{id:m.pointerId,x:m.clientX,y:m.clientY}),c())}function d(m){const g=n.get(m.pointerId);if(!g||(g.x=m.clientX,g.y=m.clientY,o===null))return;const p=s();if(!p||p.distance<=0)return;const w=p.distance/o.lastDistance;w!==1&&e.zoomAt(w,p.midpoint,a());const y=p.midpoint.x-o.lastMidpoint.x,C=p.midpoint.y-o.lastMidpoint.y;(y!==0||C!==0)&&e.panBy(y,C),o.lastDistance=p.distance,o.lastMidpoint=p.midpoint,m.preventDefault()}function h(m){n.has(m.pointerId)&&(n.delete(m.pointerId),n.size<2&&l())}function f(m){const g=Fs**-m.deltaY;if(g===1)return;const p=r(m.clientX,m.clientY);e.zoomAt(g,p,a()),m.preventDefault()}return t.addEventListener("pointerdown",u),t.addEventListener("pointermove",d),t.addEventListener("pointerup",h),t.addEventListener("pointercancel",h),t.addEventListener("pointerleave",h),t.addEventListener("wheel",f,{passive:!1}),()=>{t.removeEventListener("pointerdown",u),t.removeEventListener("pointermove",d),t.removeEventListener("pointerup",h),t.removeEventListener("pointercancel",h),t.removeEventListener("pointerleave",h),t.removeEventListener("wheel",f),n.clear(),o!==null&&e.setPinching(!1),o=null}}const $s=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])','[contenteditable="true"]'].join(", ");function he(t){const e=document.activeElement instanceof HTMLElement?document.activeElement:null,n=document.createElement("div");n.className="kalotyp-nested-overlay",t.variant&&n.classList.add(t.variant);const o=document.createElement("div");o.className="kalotyp-nested-surface",o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.tabIndex=-1;const i=`kalotyp-nested-title-${Math.random().toString(36).slice(2,8)}`;o.setAttribute("aria-labelledby",i);const r=document.createElement("div");r.className="kalotyp-nested-header";const a=document.createElement("h3");a.id=i,a.className="kalotyp-nested-title",a.textContent=t.title,r.appendChild(a);let s;t.showCloseButton!==!1&&(s=document.createElement("button"),s.type="button",s.className="kalotyp-nested-close",s.setAttribute("aria-label",`Close ${t.title}`),s.textContent="×",s.addEventListener("click",()=>h()),r.appendChild(s)),o.appendChild(r);const c=document.createElement("div");if(c.className="kalotyp-nested-body",c.appendChild(t.body),o.appendChild(c),n.appendChild(o),t.host.appendChild(n),t.anchor){n.classList.add("kalotyp-nested-overlay--popover"),Kn(n,o,t.anchor);const f=()=>Kn(n,o,t.anchor);window.addEventListener("resize",f),n.dataset.resizeListenerAttached="1",n.addEventListener("kalotyp-nested-cleanup",()=>{window.removeEventListener("resize",f)})}else n.classList.add("kalotyp-nested-overlay--modal");requestAnimationFrame(()=>o.focus());const l=f=>{if(f.key==="Escape"){f.preventDefault(),f.stopPropagation(),h();return}if(f.key!=="Tab")return;const m=Array.from(o.querySelectorAll($s));if(m.length===0){f.preventDefault(),o.focus();return}const g=m[0],p=m[m.length-1];if(!g||!p)return;const w=document.activeElement;f.shiftKey?(w===g||!o.contains(w))&&(f.preventDefault(),p.focus()):(w===p||!o.contains(w))&&(f.preventDefault(),g.focus())};document.addEventListener("keydown",l,!0);const u=f=>{const m=f.target;m&&(o.contains(m)||h())};n.addEventListener("mousedown",u);let d=!1;function h(){if(!d){if(d=!0,document.removeEventListener("keydown",l,!0),n.removeEventListener("mousedown",u),n.dispatchEvent(new Event("kalotyp-nested-cleanup")),n.remove(),e?.isConnected)try{e.focus()}catch{}t.onClose()}}return{element:n,close:h}}function Kn(t,e,n){const o=n.getBoundingClientRect(),i=t.parentElement?.getBoundingClientRect()??{top:0,right:window.innerWidth},r=e.getBoundingClientRect(),a=o.top-i.top-r.height-8,s=i.right-o.right;e.style.position="absolute",e.style.top=`${Math.max(8,a)}px`,e.style.right=`${Math.max(8,s)}px`}const pe=[{value:"auto",label:"Auto",description:"WebP when supported, PNG fallback.",requires:[]},{value:"image/webp",label:"WebP",description:"Best compression for most images.",requires:["image/webp"]},{value:"image/avif",label:"AVIF",description:"Smallest size; slower encode.",requires:["image/avif"]},{value:"image/jpeg",label:"JPEG",description:"Universal; no transparency.",requires:["image/jpeg"]},{value:"image/png",label:"PNG",description:"Lossless; preserves transparency.",requires:["image/png"]}];function Ds(t){const{host:e,anchor:n,store:o}=t,i=document.createElement("div");i.className="kalotyp-output-popover-body";const r=document.createElement("label");r.className="kalotyp-output-row";const a=document.createElement("span");a.className="kalotyp-output-row-label",a.textContent="Format",r.appendChild(a);const s=document.createElement("select");s.className="kalotyp-output-format",s.setAttribute("aria-label","Output format");for(const R of pe){const A=document.createElement("option");A.value=R.value,A.textContent=R.label,s.appendChild(A)}s.value=o.get().mimeChoice,s.addEventListener("change",()=>{const R=s.value;o.update(A=>So(A,R))}),r.appendChild(s);const c=document.createElement("p");c.className="kalotyp-output-hint",c.setAttribute("aria-live","polite");const l=document.createElement("label");l.className="kalotyp-output-row";const u=document.createElement("span");u.className="kalotyp-output-row-label",u.textContent="Quality",l.appendChild(u);const d=document.createElement("input");d.type="range",d.className="kalotyp-output-quality",d.min="50",d.max="100",d.step="1",d.value=String(Math.round(o.get().quality*100)),d.setAttribute("aria-label","Output quality"),d.addEventListener("input",()=>{o.update(R=>Eo(R,d.valueAsNumber/100))}),l.appendChild(d);const h=document.createElement("span");h.className="kalotyp-output-quality-readout",h.setAttribute("aria-hidden","true"),h.textContent=`${Math.round(o.get().quality*100)}`,l.appendChild(h);const f=document.createElement("p");f.className="kalotyp-output-summary",f.setAttribute("aria-live","polite");const m=document.createElement("label");m.className="kalotyp-output-metadata-row";const g=document.createElement("input");g.type="checkbox",g.className="kalotyp-output-metadata-checkbox",g.checked=o.get().stripMetadata,g.addEventListener("change",()=>{o.update(R=>Ao(R,g.checked))});const p=document.createElement("span");p.className="kalotyp-output-metadata-text",p.textContent="Strip EXIF, GPS, and camera metadata on save",m.appendChild(g),m.appendChild(p);const w=document.createElement("p");w.className="kalotyp-output-metadata-hint",w.setAttribute("aria-live","polite");const y=document.createElement("footer");y.className="kalotyp-output-footer";const C=document.createElement("button");C.type="button",C.className="kalotyp-output-done",C.textContent="Done",C.setAttribute("aria-label","Close output settings"),C.addEventListener("click",()=>S.close());const E=document.createElement("button");E.type="button",E.className="kalotyp-output-save",E.textContent="Save and close",E.addEventListener("click",()=>{t.canSave()&&t.onSaveAndClose()}),y.appendChild(C),y.appendChild(E),i.appendChild(r),i.appendChild(c),i.appendChild(l),i.appendChild(f),i.appendChild(m),i.appendChild(w),i.appendChild(y),n.setAttribute("aria-expanded","true");const S=he({host:e,anchor:n,title:"Output settings",body:i,variant:"kalotyp-output-popover",showCloseButton:!0,onClose:()=>{n.setAttribute("aria-expanded","false"),H(),t.onClose()}});function M(R){s.value!==R.mimeChoice&&(s.value=R.mimeChoice);const A=Math.round(R.quality*100);d.valueAsNumber!==A&&(d.value=String(A)),h.textContent=String(A);const T=pe.find(O=>O.value===R.mimeChoice);c.textContent=T?.description??"",f.textContent=Hs(R);const $=R.mimeChoice!=="image/png";d.disabled=!$,h.style.opacity=$?"1":"0.4",g.checked!==R.stripMetadata&&(g.checked=R.stripMetadata),w.textContent=Os(R),E.disabled=!t.canSave()}M(o.get());const H=o.subscribe(M);return(async()=>{for(const R of pe){if(R.requires.length===0)continue;if(!(await Promise.all(R.requires.map(T=>dt(T)))).every(Boolean)){const T=s.querySelector(`option[value="${R.value}"]`);T&&(T.disabled=!0,T.textContent=`${R.label} (unsupported)`)}}})(),{close:()=>S.close()}}function Hs(t){if(t.mimeChoice==="image/png")return"PNG · lossless";const e=Math.round(t.quality*100);switch(t.mimeChoice){case"auto":return`Auto · ${e}% quality`;case"image/webp":return`WebP · ${e}% quality`;case"image/avif":return`AVIF · ${e}% quality`;case"image/jpeg":return`JPEG · ${e}% quality`;default:return`${t.mimeChoice} · ${e}% quality`}}function Os(t){return t.stripMetadata?"":t.mimeChoice==="image/jpeg"?"EXIF preserved when the source is also JPEG.":t.mimeChoice==="auto"?"Metadata is preserved only when the resolved output is JPEG.":"Metadata can only be preserved when the output is JPEG."}const X={outputMimeChoice:"auto",outputQuality:.85,outputStripMetadata:!0,rememberAnnotationStyle:!0,rememberFilter:!0,rememberFrame:!0,lastAnnotationColor:"#ff3b30",lastAnnotationStrokeWidth:4,lastFilterPresetId:null,lastFramePresetId:null,lastFrameColor:"#000000"},zs="kalotyp:prefs:v1";function Bs(t){if(typeof t=="string")try{const e=new URL(t),n=e.pathname,o=n.indexOf("/content/"),i=o===-1?"":n.slice(0,o);return`${e.origin}${i}`}catch{}return typeof window<"u"?window.location.origin:"default"}function Vn(t){return`${zs}:${t}`}function _s(t){try{if(typeof localStorage>"u")return X;const e=localStorage.getItem(Vn(t));if(!e)return X;const n=JSON.parse(e);return Qn(n)}catch{return X}}function jn(t,e){try{if(typeof localStorage>"u")return;const n=Qn(e);localStorage.setItem(Vn(t),JSON.stringify(n))}catch{}}function Qn(t){const e=Ws(t.outputMimeChoice)?t.outputMimeChoice:X.outputMimeChoice,n=Jn(t.outputQuality,0,1,X.outputQuality),o=typeof t.outputStripMetadata=="boolean"?t.outputStripMetadata:X.outputStripMetadata,i=typeof t.rememberAnnotationStyle=="boolean"?t.rememberAnnotationStyle:X.rememberAnnotationStyle,r=typeof t.rememberFilter=="boolean"?t.rememberFilter:X.rememberFilter,a=typeof t.rememberFrame=="boolean"?t.rememberFrame:X.rememberFrame,s=typeof t.lastAnnotationColor=="string"?t.lastAnnotationColor:X.lastAnnotationColor,c=Jn(t.lastAnnotationStrokeWidth,1,40,X.lastAnnotationStrokeWidth),l=t.lastFilterPresetId===null||typeof t.lastFilterPresetId=="string"?t.lastFilterPresetId:X.lastFilterPresetId,u=t.lastFramePresetId===null||typeof t.lastFramePresetId=="string"?t.lastFramePresetId:X.lastFramePresetId,d=typeof t.lastFrameColor=="string"?t.lastFrameColor:X.lastFrameColor;return{outputMimeChoice:e,outputQuality:n,outputStripMetadata:o,rememberAnnotationStyle:i,rememberFilter:r,rememberFrame:a,lastAnnotationColor:s,lastAnnotationStrokeWidth:c,lastFilterPresetId:l,lastFramePresetId:u,lastFrameColor:d}}function Ws(t){return t==="auto"||t==="image/png"||t==="image/jpeg"||t==="image/webp"||t==="image/avif"}function Jn(t,e,n,o){return typeof t!="number"||!Number.isFinite(t)?o:t<e?e:t>n?n:t}const qs=[{value:"auto",label:"Auto (recommended)"},{value:"image/webp",label:"WebP"},{value:"image/avif",label:"AVIF"},{value:"image/jpeg",label:"JPEG"},{value:"image/png",label:"PNG"}];function Us(t){let e=t.initial;function n(E){e={...e,...E},t.onChange(e)}const o=document.createElement("div");o.className="kalotyp-preferences-body";const i=document.createElement("section");i.className="kalotyp-preferences-section",i.innerHTML="<h4>Output defaults</h4>";const r=Zn("Format"),a=document.createElement("select");a.className="kalotyp-output-format",a.setAttribute("aria-label","Default output format");for(const E of qs){const S=document.createElement("option");S.value=E.value,S.textContent=E.label,a.appendChild(S)}a.value=e.outputMimeChoice,a.addEventListener("change",()=>{n({outputMimeChoice:a.value})}),r.appendChild(a),i.appendChild(r);const s=Zn("Quality"),c=document.createElement("input");c.type="range",c.className="kalotyp-output-quality",c.min="50",c.max="100",c.step="1",c.value=String(Math.round(e.outputQuality*100)),c.setAttribute("aria-label","Default output quality"),c.addEventListener("input",()=>{n({outputQuality:c.valueAsNumber/100}),l.textContent=String(c.valueAsNumber)});const l=document.createElement("span");l.className="kalotyp-output-quality-readout",l.textContent=String(Math.round(e.outputQuality*100)),l.setAttribute("aria-hidden","true"),s.appendChild(c),s.appendChild(l),i.appendChild(s);const u=Bt("Strip EXIF, GPS, and camera metadata on save",e.outputStripMetadata,E=>n({outputStripMetadata:E}));i.appendChild(u);const d=document.createElement("section");d.className="kalotyp-preferences-section",d.innerHTML="<h4>Remember across sessions</h4>";const h=Bt("Annotation style (colour + stroke width)",e.rememberAnnotationStyle,E=>n({rememberAnnotationStyle:E})),f=Bt("Last filter preset",e.rememberFilter,E=>n({rememberFilter:E})),m=Bt("Last frame preset",e.rememberFrame,E=>n({rememberFrame:E}));d.appendChild(h),d.appendChild(f),d.appendChild(m);const g=document.createElement("footer");g.className="kalotyp-preferences-footer";const p=document.createElement("button");p.type="button",p.className="kalotyp-preferences-reset",p.textContent="Reset to defaults",p.addEventListener("click",()=>{e={...X},t.onChange(e),C(e)});const w=document.createElement("button");w.type="button",w.className="kalotyp-preferences-done",w.textContent="Done",w.addEventListener("click",()=>y.close()),g.appendChild(p),g.appendChild(w),o.appendChild(i),o.appendChild(d),o.appendChild(g);const y=he({host:t.host,title:"Preferences",body:o,variant:"kalotyp-preferences-modal",showCloseButton:!0,onClose:t.onClose});function C(E){a.value=E.outputMimeChoice,c.value=String(Math.round(E.outputQuality*100)),l.textContent=String(Math.round(E.outputQuality*100)),_t(u,E.outputStripMetadata),_t(h,E.rememberAnnotationStyle),_t(f,E.rememberFilter),_t(m,E.rememberFrame)}return{close:()=>y.close()}}function Zn(t){const e=document.createElement("div");e.className="kalotyp-output-row";const n=document.createElement("span");return n.className="kalotyp-output-row-label",n.textContent=t,e.appendChild(n),e}function Bt(t,e,n){const o=document.createElement("label");o.className="kalotyp-preferences-toggle";const i=document.createElement("input");i.type="checkbox",i.checked=e,i.addEventListener("change",()=>n(i.checked));const r=document.createElement("span");return r.textContent=t,o.appendChild(i),o.appendChild(r),o}function _t(t,e){const n=t.querySelector('input[type="checkbox"]');n&&n.checked!==e&&(n.checked=e)}const Xs=[{keys:["?"],description:"Show keyboard shortcuts",context:"editor"},{keys:["Esc"],description:"Close editor (or clear current selection)",context:"editor"},{keys:["Ctrl","Z"],description:"Undo",context:"editor"},{keys:["Ctrl","Shift","Z"],description:"Redo",context:"editor"},{keys:["Ctrl","Y"],description:"Redo (alternate)",context:"editor"},{keys:["Tab"],description:"Move focus to next control",context:"editor"},{keys:["Shift","Tab"],description:"Move focus to previous control",context:"editor"},{keys:["Delete"],description:"Delete the selected shape",context:"annotate"},{keys:["Arrow keys"],description:"Nudge the selected shape by 1 px",context:"annotate"},{keys:["Shift","Arrow keys"],description:"Nudge the selected shape by 10 px",context:"annotate"},{keys:["Shift","while drawing"],description:"Constrain shape (square, 45° line, circle)",context:"annotate"},{keys:["Delete"],description:"Delete the selected redaction region",context:"redact"},{keys:["Arrow keys"],description:"Nudge the selected region by 1 px",context:"redact"},{keys:["Shift","Arrow keys"],description:"Nudge the selected region by 10 px",context:"redact"},{keys:["Enter"],description:"Commit the text and close the editor",context:"text"},{keys:["Shift","Enter"],description:"Insert a line break",context:"text"},{keys:["Esc"],description:"Cancel the in-progress edit",context:"text"}],Ys={editor:"Editor",annotate:"Annotate",redact:"Redact",text:"Text editing"},Gs=["editor","annotate","redact","text"];function Ks(t){const e=document.createElement("div");e.className="kalotyp-cheatsheet-body";for(const o of Gs){const i=Xs.filter(r=>r.context===o);i.length!==0&&e.appendChild(Vs(o,i))}const n=he({host:t.host,title:"Keyboard shortcuts",body:e,variant:"kalotyp-cheatsheet-modal",showCloseButton:!0,onClose:t.onClose});return{close:()=>n.close()}}function Vs(t,e){const n=document.createElement("section");n.className="kalotyp-cheatsheet-section";const o=document.createElement("h4");o.className="kalotyp-cheatsheet-heading",o.textContent=Ys[t],n.appendChild(o);const i=document.createElement("dl");i.className="kalotyp-cheatsheet-list";for(const r of e){const a=document.createElement("dt");a.className="kalotyp-cheatsheet-keys",r.keys.forEach((c,l)=>{if(l>0){const d=document.createElement("span");d.className="kalotyp-cheatsheet-plus",d.setAttribute("aria-hidden","true"),d.textContent="+",a.appendChild(d)}const u=document.createElement("kbd");u.className="kalotyp-cheatsheet-kbd",u.textContent=c,a.appendChild(u)});const s=document.createElement("dd");s.className="kalotyp-cheatsheet-description",s.textContent=r.description,i.appendChild(a),i.appendChild(s)}return n.appendChild(i),n}const js=[[void 0,"Custom"],[1,"Square"],[2,"2:1"],[1.5,"3:2"],[4/3,"4:3"],[1.6,"16:10"],[16/9,"16:9"],[.5,"1:2"],[2/3,"2:3"],[.75,"3:4"],[10/16,"10:16"],[9/16,"9:16"]];async function Qs(t){return t instanceof File?t:t instanceof Blob?new File([t],"kalotyp-image.png",{type:t.type||"image/png"}):Js(t)}async function Js(t){const e=new URL(t,typeof window<"u"?window.location.href:"http://localhost"),n=await fetch(e.href,{credentials:"omit",mode:"cors"});if(!n.ok)throw new Error(`Source fetch failed: ${n.status} ${n.statusText}`);const o=await n.blob(),i=Zs(e,o.type);return new File([o],i,{type:o.type||"application/octet-stream"})}function Zs(t,e){const n=t.pathname.split("/").pop();return n&&/\.[a-z0-9]{2,5}$/i.test(n)?n:`kalotyp-image.${e.split("/")[1]??"bin"}`}const tc={sourceToFile:Qs,loadImage:oo,encodeSourceImage:Fo,createCropPlugin:Qr,createRotatePlugin:ca,createFlipPlugin:ta,createFinetunePlugin:ga,createFilterPlugin:ka,createAnnotatePlugin:is,createRedactPlugin:ks,createResizePlugin:da,createFramePlugin:Rs,runUtilityChain:Oo},me=[{id:"crop",label:"Crop"},{id:"rotate",label:"Rotate"},{id:"flip",label:"Flip"},{id:"filter",label:"Filter"},{id:"finetune",label:"Finetune"},{id:"annotate",label:"Annotate"},{id:"redact",label:"Redact"},{id:"resize",label:"Resize"},{id:"frame",label:"Frame"}];function to(t,e=tc){const n=new rt,o=new rt,i=new ao,r=rc(t),a=document.createElement("div");a.dataset.kalotypHost="",document.body.appendChild(a);let s=!1,c=!1;const l=Bs(t.src);let u=_s(l),d;function h(){d!==void 0&&clearTimeout(d),d=setTimeout(()=>{d=void 0,jn(l,u)},250)}function f(v){u={...u,...v},h()}const m=Ae({mimeChoice:u.outputMimeChoice,quality:u.outputQuality,stripMetadata:u.outputStripMetadata});m.subscribe(v=>{f({outputMimeChoice:v.mimeChoice,outputQuality:v.quality,outputStripMetadata:v.stripMetadata})});let g=null,p=null,w=null;const y={slots:new Map,sourceImage:void 0,sourceName:void 0,sourceFile:void 0,active:void 0,statusElement:void 0,history:void 0,committedChain:[],workingImage:void 0},C=kr({host:a,exportLabel:r,onExportClick:()=>{b()},onCloseClick:()=>{O()},onOutputSettingsClick:()=>{x()},onPrefsClick:()=>{N()}}),E=ic(t),S=Ns(me,E,v=>{W(v)},{panelId:C.utilMain.id});for(const v of S.buttons.values())v.disabled=!0;C.navTools.appendChild(S.container);const M=cc({onUndo:()=>D(),onRedo:()=>G()});M.undoButton.disabled=!0,M.redoButton.disabled=!0,C.modal.appendChild(M.container),C.exportButton.disabled=!0,eo(C.stage,"Loading image…",y);const H=Ts({host:C.editor,initialFocus:C.editor});C.announce("Image editor opened. Use Tab to navigate."),ec(C,t,y,e,S,E,o,i).then(()=>{C.exportButton.disabled=!1;for(const z of S.buttons.values())z.disabled=!1;no(y),_(),ac(y,u,f);const v=y.sourceImage?.width??0,I=y.sourceImage?.height??0;C.announce(`Image loaded. ${v} by ${I} pixels.`)},v=>{const I=v instanceof Error?v.message:"Failed to load image";n.emit("loaderror",{message:I,cause:v}),eo(C.stage,I,y),C.announce(`Failed to load image. ${I}`)});const R=o.on("commit",()=>{c||y.history&&(y.history.commit(bt(y)),_())}),A=o.on("announce",({message:v})=>{C.announce(v)}),T=lc({onUndo:()=>D(),onRedo:()=>G(),onEscape:()=>$(),onCheatsheet:()=>F()});function $(){L||(y.history?.canUndo()??!1)&&!window.confirm("You have unsaved changes. Discard them and close?")||O()}function O(){const v=t.willClose;return(v?v():!0)?(P(),!0):!1}async function W(v){if(!y.sourceImage||y.active?.id===v)return;const I=y.slots.get(v);if(!I)return;U()&&await nc(y,o,i),y.active?.handle.destroy(),y.active=void 0,Gn(S,v,C.utilMain),i.resetPan();const K={source:y.workingImage??y.sourceImage,bus:o,viewport:i},tt=I.plugin.mount(C.stage,K,I.store);y.active={id:v,handle:tt},y.history&&(y.history.commit(bt(y)),_())}function U(){if(!y.active)return!1;const v=y.active.id,I=v==="filter"?"finetune":v,z=y.slots.get(I);return z?!ge(I,z.store.get()):!1}function _(){M.undoButton.disabled=!y.history?.canUndo(),M.redoButton.disabled=!y.history?.canRedo()}function D(){if(!y.history)return;const v=y.history.undo(bt(y));v&&V(v)}function G(){if(!y.history)return;const v=y.history.redo(bt(y));v&&V(v)}async function V(v){c=!0;try{const q=v.snapshot.get(fe);q!==void 0&&(y.committedChain=q.map(K=>({id:K.id,state:K.state})),await oc(y,e));for(const[K,tt]of v.snapshot){if(K===fe)continue;const wt=y.slots.get(K);wt&&wt.store.update(()=>tt)}}finally{c=!1}_();const I=y.active?.id;if(I){const q=y.slots.get(I);if(q&&y.workingImage){y.active?.handle.destroy();const K={source:y.workingImage,bus:o,viewport:i},tt=q.plugin.mount(C.stage,K,q.store);y.active={id:I,handle:tt}}}if(I&&v.changed.has(I))return;const z=Y(v.changed);z&&z!==I&&await W(z)}function Y(v){for(const I of me)if(v.has(I.id))return I.id}function x(){if(g){g.close();return}g=Ds({host:C.editor,anchor:C.outputSettingsButton,store:m,canSave:()=>!s&&!C.exportButton.disabled,onSaveAndClose:()=>{g?.close(),b()},onClose:()=>{g=null}})}function F(){if(w){w.close();return}w=Ks({host:C.editor,onClose:()=>{w=null}})}function N(){if(p){p.close();return}p=Us({host:C.editor,initial:u,onChange:v=>{u=v,m.set({mimeChoice:v.outputMimeChoice,quality:v.outputQuality,stripMetadata:v.outputStripMetadata}),h()},onClose:()=>{p=null}})}async function b(){if(!s&&!(!y.sourceImage||y.slots.size===0)){s=!0;try{const v=y.workingImage??y.sourceImage;let I=v;const z=y.active;if(z){const tt=y.slots.get(z.id);if(tt){const wt=tt.store.get();ge(z.id,wt)||(I=await tt.plugin.bake(wt,v))}}const q={output:m.get(),...y.sourceName?{sourceName:y.sourceName}:{},...y.sourceFile?{sourceBlob:y.sourceFile}:{}},K=await e.encodeSourceImage(I,q);n.emit("process",{dest:K}),C.announce("Image saved."),P()}catch(v){const I=v instanceof Error?v.message:"Failed to export image";n.emit("loaderror",{message:I,cause:v}),C.announce(`Save failed. ${I}`)}finally{s=!1}}}const k=Ps(C.stage,i);let L=!1;function P(){L||(L=!0,g?.close(),g=null,p?.close(),p=null,w?.close(),w=null,d!==void 0&&(clearTimeout(d),d=void 0,jn(l,u)),y.active?.handle.destroy(),R(),A(),T(),k(),i.clear(),H.release(),C.destroy(),a.remove(),n.clear(),o.clear())}return{on(v,I){n.on(v,I)},off(v,I){n.off(v,I)}}}async function ec(t,e,n,o,i,r,a,s){const c=await o.sourceToFile(e.src),l=await o.loadImage(c),u={bitmap:l.element,width:l.width,height:l.height,mimeType:c.type||"image/png"},d=e.cropSelectPresetOptions??js,h=e.cropSelectPresetFilter,f=o.createCropPlugin({presets:d,presetFilter:h,panelHost:t.utilMain}),m=o.createRotatePlugin({panelHost:t.utilMain}),g=o.createFlipPlugin({panelHost:t.utilMain}),p=o.createFinetunePlugin({panelHost:t.utilMain}),w=o.createFilterPlugin({panelHost:t.utilMain}),y=o.createAnnotatePlugin({panelHost:t.utilMain}),C=o.createRedactPlugin({panelHost:t.utilMain}),E=o.createResizePlugin({panelHost:t.utilMain}),S=o.createFramePlugin({panelHost:t.utilMain,labels:sc(e)}),M={source:u,bus:a,viewport:s};ot(n,f,M),ot(n,m,M),ot(n,g,M),ot(n,p,M);const H=n.slots.get("finetune");H&&n.slots.set("filter",{id:"filter",plugin:w,store:H.store}),ot(n,y,M),ot(n,C,M),ot(n,E,M),ot(n,S,M),n.sourceImage=u,n.sourceName=c.name,n.sourceFile=c,n.workingImage=u,n.committedChain=[],n.history=new uo(bt(n));const R=n.slots.get(r);if(!R)return;const A={source:n.workingImage,bus:a,viewport:s},T=R.plugin.mount(t.stage,A,R.store);n.active={id:r,handle:T},Gn(i,r,t.utilMain)}function ot(t,e,n){const o=e.init(n),i=Ae(o);t.slots.set(e.id,{id:e.id,plugin:e,store:i})}const fe="__committedChain__";function bt(t){const e=new Map;for(const[n,o]of t.slots)e.set(n,o.store.get());return e.set(fe,t.committedChain),e}function ge(t,e){switch(t){case"crop":{const n=e;return!n.rect||!n.imageSize?!1:n.rect.x===0&&n.rect.y===0&&n.rect.width===n.imageSize.width&&n.rect.height===n.imageSize.height}case"rotate":{const n=e;return typeof n.quarterTurns!="number"||typeof n.freeAngle!="number"?!1:We(n)}case"flip":{const n=e;return typeof n.horizontal!="boolean"||typeof n.vertical!="boolean"?!1:ze(n)}case"finetune":case"filter":{const n=e;return n?Gt(n):!1}case"annotate":{const n=e.shapes;return Array.isArray(n)&&n.length===0}case"redact":{const n=e.regions;return Array.isArray(n)&&n.length===0}case"resize":{const n=e;return typeof n.scaleX!="number"||typeof n.scaleY!="number"?!1:Xe(n)}case"frame":{const n=e;return n.presetId?gn(n):!1}default:return!0}}async function nc(t,e,n){if(!t.active||!t.workingImage)return;const o=t.active.id,i=o==="filter"?"finetune":o,r=t.slots.get(i);if(!r)return;const a=r.store.get();if(ge(i,a))return;const s=await r.plugin.bake(a,t.workingImage);t.workingImage=s,t.committedChain.push({id:r.id,state:structuredClone(a)});const c={source:t.workingImage,bus:e,viewport:n},l=r.plugin.init(c);r.store.update(()=>l)}async function oc(t,e){if(!t.sourceImage)return;const n=[];for(const o of t.committedChain){const i=t.slots.get(o.id);i&&n.push({id:o.id,plugin:i.plugin,state:o.state})}if(n.length===0){t.workingImage=t.sourceImage;return}t.workingImage=await e.runUtilityChain(n,t.sourceImage)}function ic(t){const e=t.util;if(typeof e!="string")return"crop";for(const n of me)if(n.id===e)return n.id;return"crop"}function eo(t,e,n){no(n);const o=document.createElement("div");o.className="kalotyp-stage-status",o.setAttribute("role","status"),o.textContent=e,t.appendChild(o),n.statusElement=o}function no(t){t.statusElement?.remove(),t.statusElement=void 0}function rc(t){const e=t.locale?.labelButtonExport;return typeof e=="string"&&e.length>0?e:"Save and close"}function ac(t,e,n){if(e.rememberAnnotationStyle){const o=t.slots.get("annotate");if(o){const i=o.store;i.update(r=>({...r,currentStyle:{...r.currentStyle,color:e.lastAnnotationColor,strokeWidth:e.lastAnnotationStrokeWidth}})),i.subscribe(r=>{n({lastAnnotationColor:r.currentStyle.color,lastAnnotationStrokeWidth:r.currentStyle.strokeWidth})})}}if(e.rememberFilter&&e.lastFilterPresetId!==null){const o=t.slots.get("finetune"),i=Vt.find(r=>r.id===e.lastFilterPresetId);o&&i&&o.store.update(()=>i.state)}if(e.rememberFilter){const o=t.slots.get("finetune");o&&o.store.subscribe(r=>{const a=jt(r);n({lastFilterPresetId:a?.id??null})})}if(e.rememberFrame){const o=t.slots.get("frame");if(o){const i=o.store;e.lastFramePresetId&&i.update(()=>({presetId:e.lastFramePresetId,color:e.lastFrameColor})),i.subscribe(r=>{n({lastFramePresetId:r.presetId,lastFrameColor:r.color})})}}}function sc(t){const e=t.frameOptions;if(!Array.isArray(e))return;const n=t.locale??{},o={};for(const i of e){if(!Array.isArray(i))continue;const[r,a]=i,s=r===void 0?"none":r;try{const c=a(n);typeof c=="string"&&c.length>0&&(o[s]=c)}catch{}}return Object.keys(o).length===0?void 0:o}function cc(t){const e=document.createElement("div");e.className="kalotyp-history-controls",e.setAttribute("role","group"),e.setAttribute("aria-label","Edit history");const n=document.createElement("button");n.type="button",n.className="kalotyp-history-button kalotyp-history-undo",n.setAttribute("aria-label","Undo"),n.title="Undo (Ctrl+Z)",n.innerHTML=B("undo"),n.addEventListener("click",t.onUndo);const o=document.createElement("button");return o.type="button",o.className="kalotyp-history-button kalotyp-history-redo",o.setAttribute("aria-label","Redo"),o.title="Redo (Ctrl+Shift+Z)",o.innerHTML=B("redo"),o.addEventListener("click",t.onRedo),e.appendChild(n),e.appendChild(o),{container:e,undoButton:n,redoButton:o}}function lc(t){const e=n=>{if(n.key==="Escape"){n.preventDefault(),t.onEscape();return}const o=n.target;if(uc(o))return;if(n.key==="?"&&!n.ctrlKey&&!n.metaKey&&!n.altKey){n.preventDefault(),t.onCheatsheet();return}if(n.ctrlKey||n.metaKey){if(n.key==="z"||n.key==="Z"){n.preventDefault(),n.shiftKey?t.onRedo():t.onUndo();return}(n.key==="y"||n.key==="Y")&&(n.preventDefault(),t.onRedo())}};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)}function uc(t){if(!t)return!1;const e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"?!0:t.isContentEditable===!0}function dc(t=globalThis){const e=t.pintura;e&&typeof e=="object"||Object.defineProperty(t,"pintura",{value:{openDefaultEditor:to},writable:!0,configurable:!0,enumerable:!0})}typeof window<"u"&&dc(globalThis),it.openDefaultEditor=to,Object.defineProperty(it,Symbol.toStringTag,{value:"Module"})});
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.pintura={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e,t){if(i())return{kind:`offscreen`,canvas:new OffscreenCanvas(e,t)};let n=document.createElement(`canvas`);return n.width=e,n.height=t,{kind:`html`,canvas:n}}function n(e){if(e.kind===`offscreen`){let t=e.canvas.getContext(`2d`);if(!t)throw Error(`2D canvas context is not available`);return t}let t=e.canvas.getContext(`2d`);if(!t)throw Error(`2D canvas context is not available`);return t}async function r(e,t,n){return e.kind===`offscreen`?e.canvas.convertToBlob({type:t,quality:n}):new Promise((r,i)=>{e.canvas.toBlob(e=>{e?r(e):i(Error(`toBlob produced null`))},t,n)})}function i(){return typeof OffscreenCanvas>`u`?!1:typeof OffscreenCanvas.prototype.convertToBlob==`function`}var a=new Map;function o(e){let n=a.get(e);if(n)return n;let i=(async()=>{try{let n=await r(t(1,1),e,.5);return n.type===e&&n.size>0}catch{return!1}})();return a.set(e,i),i}async function s(e){if(typeof createImageBitmap==`function`){let t=await c(e);if(t)try{let e=await createImageBitmap(t,{imageOrientation:`from-image`});return{element:e,width:e.width,height:e.height}}catch{}}return l(e)}async function c(e){if(e instanceof Blob)return e;if(typeof fetch!=`function`)return null;try{let t=await fetch(e,{credentials:`omit`});return t.ok?await t.blob():null}catch{return null}}async function l(e){let t=typeof e==`string`?e:URL.createObjectURL(e),n=typeof e!=`string`;try{let e=await new Promise((e,n)=>{let r=new Image;r.crossOrigin=`anonymous`,r.onload=()=>e(r),r.onerror=()=>n(Error(`Failed to load image: ${t}`)),r.src=t});return{element:e,width:e.naturalWidth,height:e.naturalHeight}}finally{n&&URL.revokeObjectURL(t)}}var u=Object.freeze({zoom:1,panX:0,panY:0});function d(e,t,n=u){let r=Math.max(0,e.width-e.padding*2),i=Math.max(0,e.height-e.padding*2);if(t.width<=0||t.height<=0||r<=0||i<=0)return{displayRect:{x:e.padding,y:e.padding,width:0,height:0},scale:0};let a=Math.min(r/t.width,i/t.height)*Math.max(0,n.zoom||0),o=t.width*a,s=t.height*a,c=e.padding+(r-o)/2,l=e.padding+(i-s)/2,d=c+n.panX,p=l+n.panY;return{displayRect:{x:f(d,c,o,r,e.padding),y:f(p,l,s,i,e.padding),width:o,height:s},scale:a}}function f(e,t,n,r,i){if(n<=r)return t;let a=i,o=i+r,s=a+1-n,c=o-1;return e<s?s:e>c?c:e}function p(e,t){return t.scale===0?{x:0,y:0}:{x:(e.x-t.displayRect.x)/t.scale,y:(e.y-t.displayRect.y)/t.scale}}function m(e,t){return{x:t.displayRect.x+e.x*t.scale,y:t.displayRect.y+e.y*t.scale,width:e.width*t.scale,height:e.height*t.scale}}var h=.25,g=class{current;isPinching;listeners;constructor(e=u){this.current=v(e),this.isPinching=!1,this.listeners=new Set}getTransform(){return this.current}getSnapshot(){return{transform:this.current,pinching:this.isPinching}}setTransform(e){let t=v(e);y(this.current,t)||(this.current=t,this.emit())}zoomAt(e,t,n){if(!Number.isFinite(e)||e<=0)return this.current;let r=this.current.zoom,i=_(r*e,h,8);if(i===r)return this.current;let a=i/r,o=t.x-n.x,s=t.y-n.y,c=a*this.current.panX+(1-a)*o,l=a*this.current.panY+(1-a)*s;return this.current={zoom:i,panX:c,panY:l},this.emit(),this.current}panBy(e,t){e===0&&t===0||(this.current={zoom:this.current.zoom,panX:this.current.panX+e,panY:this.current.panY+t},this.emit())}resetToFit(){y(this.current,u)||(this.current=u,this.emit())}resetPan(){this.current.panX===0&&this.current.panY===0||(this.current={zoom:this.current.zoom,panX:0,panY:0},this.emit())}getPinching(){return this.isPinching}setPinching(e){this.isPinching!==e&&(this.isPinching=e,this.emit())}computeViewport(e,t){return d(e,t,this.current)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear()}emit(){let e=this.getSnapshot();for(let t of this.listeners)t(e)}};function _(e,t,n){return e<t?t:e>n?n:e}function v(e){return{zoom:_(Number.isFinite(e.zoom)?e.zoom:1,h,8),panX:Number.isFinite(e.panX)?e.panX:0,panY:Number.isFinite(e.panY)?e.panY:0}}function y(e,t){return e.zoom===t.zoom&&e.panX===t.panX&&e.panY===t.panY}var b=class{listeners=new Map;on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{n?.delete(t)}}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){let n=this.listeners.get(e);if(n)for(let e of[...n])try{e(t)}catch(e){queueMicrotask(()=>{throw e})}}clear(){this.listeners.clear()}};function x(e,t,n,r){return S({x:e.x+t,y:e.y+n,width:e.width,height:e.height},r)}function S(e,t){let{x:n,y:r,width:i,height:a}=e;return i>t.width&&(i=t.width),a>t.height&&(a=t.height),n<t.x&&(n=t.x),r<t.y&&(r=t.y),n+i>t.x+t.width&&(n=t.x+t.width-i),r+a>t.y+t.height&&(r=t.y+t.height-a),{x:n,y:r,width:i,height:a}}function C(e){return{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)}}var w=class{shadow;undoStack=[];redoStack=[];constructor(e){this.shadow=D(e)}commit(e){T(e,this.shadow)||(this.undoStack.push(this.shadow),this.undoStack.length>50&&this.undoStack.shift(),this.shadow=D(e),this.redoStack.length=0)}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undo(e){let t=this.undoStack.pop();return t?(this.redoStack.push(D(e)),this.shadow=t,{snapshot:t,changed:E(e,t)}):null}redo(e){let t=this.redoStack.pop();return t?(this.undoStack.push(D(e)),this.undoStack.length>50&&this.undoStack.shift(),this.shadow=t,{snapshot:t,changed:E(e,t)}):null}size(){return{undo:this.undoStack.length,redo:this.redoStack.length}}};function T(e,t){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||O(r)!==O(t.get(n)))return!1;return!0}function E(e,t){let n=new Set;for(let[r,i]of t)O(i)!==O(e.get(r))&&n.add(r);for(let r of e.keys())t.has(r)||n.add(r);return n}function D(e){let t=new Map;for(let[n,r]of e)t.set(n,structuredClone(r));return t}function O(e){return JSON.stringify(e,(e,t)=>{if(t&&typeof t==`object`&&!Array.isArray(t)){let e={};for(let n of Object.keys(t).sort())e[n]=t[n];return e}return t})}var k={mimeChoice:`auto`,quality:.85,stripMetadata:!0};function A(e){return Number.isFinite(e)?e<0?0:e>1?1:e:k.quality}function j(e,t){return e.mimeChoice===t?e:{...e,mimeChoice:t}}function M(e,t){let n=A(t);return e.quality===n?e:{...e,quality:n}}function N(e,t){return e.stripMetadata===t?e:{...e,stripMetadata:t}}var P=[255,216],F=[255,225],I=[69,120,105,102,0,0];async function L(e){if(e.output.type&&e.output.type!==`image/jpeg`)return e.output;let t=await R(e.source);if(!ee(t,P))return e.output;let n=te(t);if(!n)return e.output;let r=await R(e.output);if(!ee(r,P))return e.output;let i=new Uint8Array(r.length+n.length);return i.set(r.subarray(0,2),0),i.set(n,2),i.set(r.subarray(2),2+n.length),new Blob([i],{type:`image/jpeg`})}async function R(e){return typeof e.arrayBuffer==`function`?new Uint8Array(await e.arrayBuffer()):new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let e=r.result;e instanceof ArrayBuffer?t(new Uint8Array(e)):n(Error(`FileReader returned a non-ArrayBuffer result`))},r.onerror=()=>n(r.error??Error(`FileReader failed`)),r.readAsArrayBuffer(e)})}function ee(e,t){if(e.length<t.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function te(e){let t=2;for(;t+4<=e.length;){if(e[t]!==255)return;let n=e[t+1];if(n===void 0||n===218||n===217)return;let r=e[t+2]!==void 0&&e[t+3]!==void 0?e[t+2]*256+e[t+3]:0;if(r<2)return;let i=t+2+r;if(i>e.length)return;if(e[t]===F[0]&&e[t+1]===F[1]&&ne(e,t+4))return e.slice(t,i);t=i}}function ne(e,t){for(let n=0;n<I.length;n++)if(e[t+n]!==I[n])return!1;return!0}var re=`image/png`,ie=new Set([`image/png`,`image/webp`,`image/avif`]);async function ae(e,t){return e.mimeChoice===`auto`?await o(`image/webp`)?`image/webp`:!ie.has(t.mimeType)&&await o(`image/jpeg`)?`image/jpeg`:re:await o(e.mimeChoice)?e.mimeChoice:await o(`image/webp`)?`image/webp`:re}function oe(e,t){let n=ce(t);if(!e)return`kalotyp-image.${n}`;let r=le(e);if(!r)return`kalotyp-image.${n}`;let i=de(r);return i?`${i}.${n}`:`kalotyp-image.${n}`}async function se(e,n={}){let i=n.output??k,a=await ae(i,e),o=A(i.quality),s=oe(n.sourceName,a),c=t(e.width,e.height);if(c.kind===`offscreen`){let t=c.canvas.getContext(`2d`);if(!t)throw Error(`2D canvas context is not available`);t.drawImage(e.bitmap,0,0)}else{let t=c.canvas.getContext(`2d`);if(!t)throw Error(`2D canvas context is not available`);t.drawImage(e.bitmap,0,0)}let l=await r(c,a,o),u=n.output?.stripMetadata===!1&&a===`image/jpeg`&&e.mimeType===`image/jpeg`&&n.sourceBlob!==void 0?await L({source:n.sourceBlob,output:l}):l;return new File([u],s,{type:a})}function ce(e){if(e===`image/jpeg`)return`jpg`;if(e===`image/png`)return`png`;if(e===`image/webp`)return`webp`;if(e===`image/avif`)return`avif`;let t=e.split(`/`)[1];return t&&t.length>0?t:`bin`}function le(e){let t=ue(e).split(/[/\\]/);return t[t.length-1]}function ue(e){let t=e.indexOf(`?`);return t===-1?e:e.slice(0,t)}function de(e){let t=e.lastIndexOf(`.`);return t<=0?e:e.slice(0,t)}async function fe(e,t){let n=t;for(let t of e)n=await t.plugin.bake(t.state,n);return n}function pe(e){if(e.length<=1)return[...e];let t=e[0];if(!t)return[];let n=[t],r=t;for(let t=1;t<e.length-1;t++){let i=e[t];if(!i)continue;let a=i.x-r.x,o=i.y-r.y;a*a+o*o<4||(n.push(i),r=i)}let i=e[e.length-1];return i&&i!==r&&n.push(i),n}function me(e,t){if(t.length===0)return;let n=t[0];if(!n)return;if(t.length===1){e.moveTo(n.x,n.y),e.lineTo(n.x,n.y);return}e.moveTo(n.x,n.y);for(let n=1;n<t.length-1;n++){let r=t[n],i=t[n+1];if(!r||!i)continue;let a=(r.x+i.x)/2,o=(r.y+i.y)/2;e.quadraticCurveTo(r.x,r.y,a,o)}let r=t[t.length-1];r&&e.lineTo(r.x,r.y)}var he=`rgba(255, 235, 59, 0.35)`,ge=`#ff3b30`;function _e(){return{color:ge,strokeWidth:4,fillColor:null,fontSize:32}}function ve(e){return{shapes:[],selectedId:null,activeTool:`select`,currentStyle:_e(),imageSize:e.imageSize,nextShapeNumber:1}}function z(e){return{id:`s_${e.nextShapeNumber.toString(36)}`,nextShapeNumber:e.nextShapeNumber+1}}function ye(e,t){return e.activeTool===t?e:{...e,activeTool:t,selectedId:t===`select`?e.selectedId:null}}function be(e,t){return{...e,currentStyle:{...e.currentStyle,...t}}}function xe(e,t){return e.selectedId===t?e:{...e,selectedId:t}}function B(e,t){return{...e,shapes:[...e.shapes,t],selectedId:t.id}}function V(e,t){let n=!1,r=e.shapes.map(e=>e.id===t.id?(n=!0,t):e);return n?{...e,shapes:r}:e}function Se(e,t){let n=e.shapes.filter(e=>e.id!==t);return n.length===e.shapes.length?e:{...e,shapes:n,selectedId:e.selectedId===t?null:e.selectedId}}function Ce(e){let{x:t,y:n,width:r,height:i}=e;return r<0&&(t+=r,r=-r),i<0&&(n+=i,i=-i),{x:t,y:n,width:r,height:i}}function we(e,t,n){switch(e.kind){case`text`:return{...e,x:e.x+t,y:e.y+n};case`rect`:case`ellipse`:return{...e,x:e.x+t,y:e.y+n};case`arrow`:return{...e,x1:e.x1+t,y1:e.y1+n,x2:e.x2+t,y2:e.y2+n};case`freehand`:case`highlight`:return{...e,points:e.points.map(e=>({x:e.x+t,y:e.y+n}))};default:return Te(e)}}function Te(e){throw Error(`Unhandled annotation shape kind: ${JSON.stringify(e)}`)}function Ee(e){return e===`text`||e===`rect`||e===`ellipse`||e===`arrow`}function De(e,t){let{imageSize:n,style:r,id:i}=t,a=Math.min(n.width,n.height),o=n.width/2,s=n.height/2;switch(e){case`rect`:case`ellipse`:{let t=Math.max(80,Math.round(a*.25)),n=Math.round(o-t/2),c=Math.round(s-t/2);return e===`rect`?{id:i,kind:`rect`,x:n,y:c,width:t,height:t,strokeColor:r.color,strokeWidth:r.strokeWidth,fillColor:r.fillColor}:{id:i,kind:`ellipse`,x:n,y:c,width:t,height:t,strokeColor:r.color,strokeWidth:r.strokeWidth,fillColor:r.fillColor}}case`arrow`:{let e=Math.max(100,Math.round(a*.3)),t=Math.round(o-e/2),n=t+e,c=Math.round(s);return{id:i,kind:`arrow`,x1:t,y1:c,x2:n,y2:c,color:r.color,strokeWidth:r.strokeWidth}}case`text`:return{id:i,kind:`text`,x:Math.round(o),y:Math.round(s-r.fontSize/2),text:``,fontSize:r.fontSize,color:r.color,textAlign:`center`}}}var Oe=`-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif`;async function ke(e,r){if(e.shapes.length===0)return r;let i=t(r.width,r.height),a=n(i);a.imageSmoothingEnabled=!0,a.imageSmoothingQuality=`high`,a.drawImage(r.bitmap,0,0,r.width,r.height);for(let t of e.shapes)Ae(a,t);return{bitmap:i.canvas,width:r.width,height:r.height,mimeType:r.mimeType}}function Ae(e,t){switch(t.kind){case`text`:je(e,t);return;case`rect`:Me(e,t);return;case`ellipse`:Ne(e,t);return;case`arrow`:Pe(e,t);return;case`freehand`:Fe(e,t);return;case`highlight`:Ie(e,t);return;default:Te(t)}}function je(e,t){e.save(),e.fillStyle=t.color,e.font=`${t.fontSize}px ${Oe}`,e.textAlign=t.textAlign,e.textBaseline=`top`;let n=t.text.length===0?[``]:t.text.split(`
2
+ `),r=t.fontSize*1.2;for(let i=0;i<n.length;i++){let a=n[i];a!==void 0&&e.fillText(a,t.x,t.y+i*r)}e.restore()}function Me(e,t){e.save(),t.fillColor!==null&&(e.fillStyle=t.fillColor,e.fillRect(t.x,t.y,t.width,t.height)),t.strokeWidth>0&&(e.strokeStyle=t.strokeColor,e.lineWidth=t.strokeWidth,e.lineJoin=`miter`,e.strokeRect(t.x,t.y,t.width,t.height)),e.restore()}function Ne(e,t){e.save();let n=t.width/2,r=t.height/2,i=t.x+n,a=t.y+r;e.beginPath(),e.ellipse(i,a,Math.max(0,n),Math.max(0,r),0,0,Math.PI*2),t.fillColor!==null&&(e.fillStyle=t.fillColor,e.fill()),t.strokeWidth>0&&(e.strokeStyle=t.strokeColor,e.lineWidth=t.strokeWidth,e.stroke()),e.restore()}function Pe(e,t){let n=t.x2-t.x1,r=t.y2-t.y1,i=Math.sqrt(n*n+r*r);if(i<.5)return;e.save(),e.strokeStyle=t.color,e.fillStyle=t.color,e.lineWidth=t.strokeWidth,e.lineCap=`round`,e.lineJoin=`round`;let a=Math.min(Math.max(t.strokeWidth*5,28),i*.6),o=Math.max(t.strokeWidth*4,18),s=n/i,c=r/i,l=t.x2-s*a*.6,u=t.y2-c*a*.6;e.beginPath(),e.moveTo(t.x1,t.y1),e.lineTo(l,u),e.stroke();let d=t.x2-s*a,f=t.y2-c*a,p=-c,m=s;e.beginPath(),e.moveTo(t.x2,t.y2),e.lineTo(d+p*o/2,f+m*o/2),e.lineTo(d-p*o/2,f-m*o/2),e.closePath(),e.fill(),e.restore()}function Fe(e,t){t.points.length!==0&&(e.save(),e.strokeStyle=t.color,e.lineWidth=t.strokeWidth,e.lineCap=`round`,e.lineJoin=`round`,e.beginPath(),me(e,t.points),e.stroke(),e.restore())}function Ie(e,t){t.points.length!==0&&(e.save(),e.globalCompositeOperation=`multiply`,e.strokeStyle=t.color,e.lineWidth=t.strokeWidth,e.lineCap=`round`,e.lineJoin=`round`,e.beginPath(),me(e,t.points),e.stroke(),e.restore())}function H(e){switch(e.kind){case`text`:{let{width:t,height:n}=Be(e.text,e.fontSize);return{x:Ve(e.x,t,e.textAlign),y:e.y,width:t,height:n}}case`rect`:case`ellipse`:return{x:e.x,y:e.y,width:e.width,height:e.height};case`arrow`:return{x:Math.min(e.x1,e.x2),y:Math.min(e.y1,e.y2),width:Math.abs(e.x2-e.x1),height:Math.abs(e.y2-e.y1)};case`freehand`:case`highlight`:{let t=e.points[0];if(!t)return{x:0,y:0,width:0,height:0};let n=t.x,r=t.y,i=t.x,a=t.y;for(let t of e.points)t.x<n&&(n=t.x),t.x>i&&(i=t.x),t.y<r&&(r=t.y),t.y>a&&(a=t.y);return{x:n,y:r,width:i-n,height:a-r}}default:return Te(e)}}var Le=[`tl`,`tr`,`bl`,`br`,`t`,`r`,`b`,`l`];function Re(e){let t=e.x,n=e.x+e.width,r=e.y,i=e.y+e.height,a=e.x+e.width/2,o=e.y+e.height/2;return{tl:{x:t,y:r},tr:{x:n,y:r},bl:{x:t,y:i},br:{x:n,y:i},t:{x:a,y:r},r:{x:n,y:o},b:{x:a,y:i},l:{x:t,y:o}}}function ze(e,t,n){let r=e.x,i=e.y,a=e.x+e.width,o=e.y+e.height;return(t===`tl`||t===`l`||t===`bl`)&&(r=n.x),(t===`tr`||t===`r`||t===`br`)&&(a=n.x),(t===`tl`||t===`t`||t===`tr`)&&(i=n.y),(t===`bl`||t===`b`||t===`br`)&&(o=n.y),{x:r,y:i,width:a-r,height:o-i}}function Be(e,t){let n=e.length===0?[``]:e.split(`
3
+ `),r=0;for(let e of n)e.length>r&&(r=e.length);return{width:Math.max(t*.6,r*t*.55),height:n.length*t*1.2}}function Ve(e,t,n){switch(n){case`left`:return e;case`center`:return e-t/2;case`right`:return e-t}}function He(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r&&Ue(r,t))return r}}function Ue(e,t){switch(e.kind){case`text`:return U(t,H(e));case`rect`:{let n=U(t,Ge(e));if(e.fillColor!==null)return n;let r=We(Ge(e),e.strokeWidth/2+4),i=We(Ge(e),-(e.strokeWidth/2+4));return U(t,r)&&!U(t,i)}case`ellipse`:{let n=Ge(e),r=n.width/2,i=n.height/2,a=n.x+r,o=n.y+i;if(r<=0||i<=0)return!1;let s=(t.x-a)/r,c=(t.y-o)/i,l=s*s+c*c,u=(e.strokeWidth/2+4)/Math.min(r,i);return e.fillColor===null?l<=(1+u)**2&&l>=(1-u)**2:l<=(1+u)**2}case`arrow`:return Ke(t,{x:e.x1,y:e.y1},{x:e.x2,y:e.y2},e.strokeWidth/2+4);case`freehand`:case`highlight`:{if(!U(t,We(H(e),e.strokeWidth/2+4)))return!1;let n=e.strokeWidth/2+4;for(let r=1;r<e.points.length;r++){let i=e.points[r-1],a=e.points[r];if(i&&a&&Ke(t,i,a,n))return!0}if(e.points.length===1){let r=e.points[0];if(!r)return!1;let i=r.x-t.x,a=r.y-t.y;return i*i+a*a<=n*n}return!1}default:return Te(e)}}function U(e,t){return e.x>=t.x&&e.y>=t.y&&e.x<=t.x+t.width&&e.y<=t.y+t.height}function We(e,t){return{x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}}function Ge(e){let{x:t,y:n,width:r,height:i}=e;return r<0&&(t+=r,r=-r),i<0&&(n+=i,i=-i),{x:t,y:n,width:r,height:i}}function Ke(e,t,n,r){let i=n.x-t.x,a=n.y-t.y,o=i*i+a*a;if(o===0){let n=e.x-t.x,i=e.y-t.y;return n*n+i*i<=r*r}let s=((e.x-t.x)*i+(e.y-t.y)*a)/o;s<0?s=0:s>1&&(s=1);let c=t.x+s*i,l=t.y+s*a,u=e.x-c,d=e.y-l;return u*u+d*d<=r*r}function qe(e,t){if(t<=0||e.width<=0||e.height<=0)return{x:e.x,y:e.y,width:0,height:0};let n=e.width/e.height,r,i;return t>=n?(r=e.width,i=r/t):(i=e.height,r=i*t),{x:e.x+(e.width-r)/2,y:e.y+(e.height-i)/2,width:r,height:i}}function Je(e,t,n,r){if(t<=0)return e;if(e.width<=0||e.height<=0)return qe(r,t);let i=e.width/e.height,a,o;i>t?(o=e.height,a=o*t):(a=e.width,o=a/t);let s=S(Xe(e,a,o,n),r),c=s.height===0?0:s.width/s.height;return Math.abs(c-t)<=Ye?s:Ze(s,t,n)}var Ye=1e-6;function Xe(e,t,n,r){switch(r){case`tl`:return{x:e.x,y:e.y,width:t,height:n};case`tr`:return{x:e.x+e.width-t,y:e.y,width:t,height:n};case`bl`:return{x:e.x,y:e.y+e.height-n,width:t,height:n};case`br`:return{x:e.x+e.width-t,y:e.y+e.height-n,width:t,height:n};case`center`:return{x:e.x+(e.width-t)/2,y:e.y+(e.height-n)/2,width:t,height:n}}}function Ze(e,t,n){let r=qe(e,t);return Xe(e,r.width,r.height,n)}function Qe(e,n){let r=C(n.rect),i=$e(r.x,0,e.width),a=$e(r.y,0,e.height),o=$e(r.width,1,e.width-i),s=$e(r.height,1,e.height-a),c=t(o,s);if(c.kind===`offscreen`){let t=c.canvas.getContext(`2d`);if(!t)throw Error(`2D canvas context is not available`);return t.drawImage(e.bitmap,i,a,o,s,0,0,o,s),{bitmap:c.canvas,width:o,height:s,mimeType:e.mimeType}}let l=c.canvas.getContext(`2d`);if(!l)throw Error(`2D canvas context is not available`);return l.drawImage(e.bitmap,i,a,o,s,0,0,o,s),{bitmap:c.canvas,width:o,height:s,mimeType:e.mimeType}}function $e(e,t,n){return Math.max(t,Math.min(n,e))}function et(e,t){let[n]=e;return n===void 0||t===void 0?!0:t===`landscape`?n>=1:t===`portrait`?n<1:!0}function tt(e,t){return e.filter(e=>et(e,t))}function nt(e,t,n,r){let i=r.minSize??1,a=e.x,o=e.y,s=e.x+e.width,c=e.y+e.height,l=a,u=o,d=s,f=c;(t===`tl`||t===`l`||t===`bl`)&&(l=n.x),(t===`tr`||t===`r`||t===`br`)&&(d=n.x),(t===`tl`||t===`t`||t===`tr`)&&(u=n.y),(t===`bl`||t===`b`||t===`br`)&&(f=n.y),(t===`l`||t===`r`)&&(u=o,f=c),(t===`t`||t===`b`)&&(l=a,d=s);let p=Math.min(l,d),m=Math.min(u,f),h=Math.abs(d-l),g=Math.abs(f-u);h<i&&(h=i,t===`tl`||t===`l`||t===`bl`?p=s-i:(t===`tr`||t===`r`||t===`br`)&&(p=a)),g<i&&(g=i,t===`tl`||t===`t`||t===`tr`?m=c-i:(t===`bl`||t===`b`||t===`br`)&&(m=o));let _={x:p,y:m,width:h,height:g};return _=S(_,r.bounds),r.aspectRatio!==void 0&&r.aspectRatio>0&&(_=Je(_,r.aspectRatio,rt(t),r.bounds)),_}function rt(e){switch(e){case`tl`:return`br`;case`tr`:return`bl`;case`bl`:return`tr`;case`br`:return`tl`;case`t`:return`bl`;case`b`:return`tl`;case`l`:return`tr`;case`r`:return`tl`}}function it(e){return{rect:{x:0,y:0,width:e.imageSize.width,height:e.imageSize.height},aspectRatio:void 0,activePresetIndex:ot(e.presets),presets:e.presets,imageSize:e.imageSize}}function at(e,t){let n=e.presets[t];if(!n)return e;let[r]=n;if(r===void 0)return{...e,aspectRatio:void 0,activePresetIndex:t};let i=qe({x:0,y:0,width:e.imageSize.width,height:e.imageSize.height},r);return{...e,rect:i,aspectRatio:r,activePresetIndex:t}}function ot(e){return e.findIndex(([e])=>e===void 0)}var st=-100,W={brightness:0,contrast:0,saturation:0,exposure:0,clarity:0,gamma:0},ct=[{key:`brightness`,label:`Brightness`},{key:`contrast`,label:`Contrast`},{key:`saturation`,label:`Saturation`},{key:`exposure`,label:`Exposure`},{key:`clarity`,label:`Clarity`},{key:`gamma`,label:`Gamma`}];function lt(){return W}function ut(e){return e.brightness===0&&e.contrast===0&&e.saturation===0&&e.exposure===0&&e.clarity===0&&e.gamma===0}function dt(e,t,n){let r=mt(n);return e[t]===r?e:{...e,[t]:r}}function ft(e,t){return e[t]===0?e:{...e,[t]:0}}function pt(){return W}function mt(e){return Number.isNaN(e)?0:e<=-100?st:e>=100?100:Math.round(e/1)*1}var ht=[{id:`none`,label:`None`,state:W},{id:`vivid`,label:`Vivid`,state:{brightness:0,contrast:10,saturation:40,exposure:0,clarity:5,gamma:0}},{id:`mono`,label:`Mono`,state:{brightness:0,contrast:15,saturation:-100,exposure:0,clarity:0,gamma:0}},{id:`soft`,label:`Soft`,state:{brightness:5,contrast:-10,saturation:0,exposure:0,clarity:-25,gamma:0}},{id:`punch`,label:`Punch`,state:{brightness:0,contrast:30,saturation:5,exposure:0,clarity:25,gamma:0}},{id:`mute`,label:`Mute`,state:{brightness:0,contrast:5,saturation:-50,exposure:0,clarity:-5,gamma:0}},{id:`bright`,label:`Bright`,state:{brightness:5,contrast:5,saturation:0,exposure:15,clarity:0,gamma:0}}];function gt(e,t){return e.brightness===t.brightness&&e.contrast===t.contrast&&e.saturation===t.saturation&&e.exposure===t.exposure&&e.clarity===t.clarity&&e.gamma===t.gamma}function _t(e){for(let t of ht)if(gt(t.state,e))return t}function vt(e){let t=new Uint8ClampedArray(256),n=e.brightness/200,r=1+e.contrast/100,i=1+e.exposure/200,a=yt(e.gamma);for(let e=0;e<256;e++){let o=e/255;o*=i,o=(o-.5)*r+.5,o+=n,o<0?o=0:o>1&&(o=1),o**=a,o<0?o=0:o>1&&(o=1),t[e]=Math.round(o*255)}return t}function yt(e){return e===0?1:e>0?1-e/100*.5:1+1*(-e/100)}function bt(e,t,n,r){let i=e.length;if(t.length!==i)throw Error(`applyFinetuneLutAndSaturation: src/dst length mismatch`);let a=1+r.saturation/100;if(a===1){for(let r=0;r<i;r+=4)t[r]=n[e[r]],t[r+1]=n[e[r+1]],t[r+2]=n[e[r+2]],t[r+3]=e[r+3];return}for(let r=0;r<i;r+=4){let i=n[e[r]],o=n[e[r+1]],s=n[e[r+2]],c=.2126*i+.7152*o+.0722*s,l=c+(i-c)*a,u=c+(o-c)*a,d=c+(s-c)*a;l<0?l=0:l>255&&(l=255),u<0?u=0:u>255&&(u=255),d<0?d=0:d>255&&(d=255),t[r]=l,t[r+1]=u,t[r+2]=d,t[r+3]=e[r+3]}}function xt(e,t,n){if(n===0)return;let r=e.length;if(t.length!==r)throw Error(`applyClarity: dst/blurred length mismatch`);let i=n/100;for(let n=0;n<r;n+=4){let r=e[n],a=e[n+1],o=e[n+2],s=r+i*(r-t[n]),c=a+i*(a-t[n+1]),l=o+i*(o-t[n+2]);s<0?s=0:s>255&&(s=255),c<0?c=0:c>255&&(c=255),l<0?l=0:l>255&&(l=255),e[n]=s,e[n+1]=c,e[n+2]=l}}function St(e,t,n,r,i){if(e.length!==t.length||e.length!==n.length)throw Error(`boxBlur3x3: buffer length mismatch`);for(let n=0;n<i;n++)for(let i=0;i<r;i++){let a=i===0?0:i-1,o=i===r-1?r-1:i+1,s=(n*r+i)*4,c=(n*r+a)*4,l=(n*r+o)*4;t[s]=(e[c]+e[s]+e[l])/3,t[s+1]=(e[c+1]+e[s+1]+e[l+1])/3,t[s+2]=(e[c+2]+e[s+2]+e[l+2])/3,t[s+3]=e[s+3]}for(let e=0;e<i;e++){let a=e===0?0:e-1,o=e===i-1?i-1:e+1;for(let i=0;i<r;i++){let s=(e*r+i)*4,c=(a*r+i)*4,l=(o*r+i)*4;n[s]=(t[c]+t[s]+t[l])/3,n[s+1]=(t[c+1]+t[s+1]+t[l+1])/3,n[s+2]=(t[c+2]+t[s+2]+t[l+2])/3,n[s+3]=t[s+3]}}}function Ct(e,t,n){if(t.width!==n.width||t.height!==n.height||t.data.length!==n.data.length)throw Error(`applyFinetuneToImageData: baseline/dst dimensions mismatch`);let r=vt(e);if(bt(t.data,n.data,r,e),e.clarity!==0){let r=new Uint8ClampedArray(t.data.length),i=new Uint8ClampedArray(t.data.length);St(t.data,r,i,t.width,t.height),xt(n.data,i,e.clarity)}}async function wt(e,r){if(ut(e))return r;let i=t(r.width,r.height),a=n(i);a.imageSmoothingEnabled=!0,a.imageSmoothingQuality=`high`,a.drawImage(r.bitmap,0,0,r.width,r.height);let o=a.getImageData(0,0,r.width,r.height);if(e.clarity===0)Ct(e,o,o),a.putImageData(o,0,0);else{let t=new ImageData(new Uint8ClampedArray(o.data.length),o.width,o.height);Ct(e,o,t),a.putImageData(t,0,0)}return{bitmap:i.canvas,width:r.width,height:r.height,mimeType:r.mimeType}}function Tt(){return{horizontal:!1,vertical:!1}}function Et(e,t){return t===`horizontal`?{...e,horizontal:!e.horizontal}:{...e,vertical:!e.vertical}}function Dt(e){return!e.horizontal&&!e.vertical}async function Ot(e,r){if(Dt(e))return r;let{width:i,height:a}=r,o=t(i,a),s=n(o),c=e.horizontal?-1:1,l=e.vertical?-1:1,u=e.horizontal?i:0,d=e.vertical?a:0;return s.setTransform(c,0,0,l,u,d),s.drawImage(r.bitmap,0,0),{bitmap:o.canvas,width:i,height:a,mimeType:r.mimeType}}var kt=[{id:`none`,label:`None`,acceptsColor:!1,defaultColor:`#000000`},{id:`solidSharp`,label:`Mat Sharp`,acceptsColor:!0,defaultColor:`#000000`},{id:`solidRound`,label:`Mat Round`,acceptsColor:!0,defaultColor:`#000000`},{id:`lineSingle`,label:`Line Single`,acceptsColor:!0,defaultColor:`#000000`},{id:`hook`,label:`Corner Hooks`,acceptsColor:!0,defaultColor:`#000000`},{id:`polaroid`,label:`Polaroid`,acceptsColor:!0,defaultColor:`#ffffff`}],At={presetId:`none`,color:`#000000`};function jt(){return At}function Mt(e){return e.presetId===`none`}function Nt(e,t){if(e.presetId===t)return e;let n=Ft(e.presetId),r=Ft(t);return r?{presetId:t,color:n!==void 0&&e.color===n.defaultColor?r.defaultColor:e.color}:{...e,presetId:t}}function Pt(e,t){return e.color===t?e:{...e,color:t}}function Ft(e){return kt.find(t=>t.id===e)}async function It(e,t){return Mt(e)?t:e.presetId===`polaroid`?Wt(e.color,t):e.presetId===`none`?t:Lt(e.presetId,e.color,t)}function Lt(e,r,i){let a=t(i.width,i.height),o=n(a);return o.drawImage(i.bitmap,0,0,i.width,i.height),Rt(o,e,r,i.width,i.height),{bitmap:a.canvas,width:i.width,height:i.height,mimeType:i.mimeType}}function Rt(e,t,n,r,i){switch(t){case`solidSharp`:zt(e,n,r,i);return;case`solidRound`:Bt(e,n,r,i);return;case`lineSingle`:Ht(e,n,r,i);return;case`hook`:Ut(e,n,r,i);return}}function zt(e,t,n,r){let i=Gt(n,r);e.save(),e.fillStyle=t,e.fillRect(0,0,n,i),e.fillRect(0,r-i,n,i),e.fillRect(0,i,i,r-2*i),e.fillRect(n-i,i,i,r-2*i),e.restore()}function Bt(e,t,n,r){let i=Gt(n,r);zt(e,t,n,r),e.save(),e.globalCompositeOperation=`destination-out`,e.fillStyle=`#000`,Vt(e,0,0,i,`tl`),Vt(e,n,0,i,`tr`),Vt(e,0,r,i,`bl`),Vt(e,n,r,i,`br`),e.restore()}function Vt(e,t,n,r,i){switch(e.beginPath(),e.moveTo(t,n),i){case`tl`:e.lineTo(t+r,n),e.arc(t+r,n+r,r,-Math.PI/2,Math.PI,!0),e.lineTo(t,n);break;case`tr`:e.lineTo(t,n+r),e.arc(t-r,n+r,r,0,-Math.PI/2,!0),e.lineTo(t,n);break;case`bl`:e.lineTo(t+r,n),e.arc(t+r,n-r,r,Math.PI/2,Math.PI,!1),e.lineTo(t,n);break;case`br`:e.lineTo(t-r,n),e.arc(t-r,n-r,r,Math.PI/2,0,!0),e.lineTo(t,n);break}e.closePath(),e.fill()}function Ht(e,t,n,r){let i=Math.round(Math.min(n,r)*.05),a=Math.max(2,Math.round(Math.min(n,r)*.01));e.save(),e.strokeStyle=t,e.lineWidth=a;let o=a/2;e.strokeRect(i+o,i+o,n-2*i-a,r-2*i-a),e.restore()}function Ut(e,t,n,r){let i=Math.round(Math.min(n,r)*.08),a=Math.max(2,Math.round(Math.min(n,r)*.01)),o=Math.round(Math.min(n,r)*.05);e.save(),e.strokeStyle=t,e.lineWidth=a,e.lineCap=`square`;let s=a/2,c=(t,n,r,a)=>{e.beginPath(),e.moveTo(t+r*i,n),e.lineTo(t,n),e.lineTo(t,n+a*i),e.stroke()};c(o+s,o+s,1,1),c(n-o-s,o+s,-1,1),c(o+s,r-o-s,1,-1),c(n-o-s,r-o-s,-1,-1),e.restore()}function Wt(e,r){let i=Math.min(r.width,r.height),a=Math.round(i*.05),o=a,s=a,c=Math.round(i*.18),l=r.width+o+s,u=r.height+a+c,d=t(l,u),f=n(d);return f.fillStyle=e,f.fillRect(0,0,l,u),f.drawImage(r.bitmap,o,a,r.width,r.height),{bitmap:d.canvas,width:l,height:u,mimeType:r.mimeType}}function Gt(e,t){return Math.max(4,Math.round(Math.min(e,t)*.04))}function Kt(e,t,n){if(e!==`polaroid`)return{width:t,height:n};let r=Math.min(t,n),i=Math.round(r*.05),a=Math.round(r*.18);return{width:t+2*i,height:n+i+a}}async function qt(e,r){if(e.regions.length===0)return r;let i=t(r.width,r.height),a=n(i);a.drawImage(r.bitmap,0,0,r.width,r.height);for(let t of e.regions)Jt(a,i.canvas,t,r);return{bitmap:i.canvas,width:r.width,height:r.height,mimeType:r.mimeType}}function Jt(e,t,n,r){let i=Math.round(n.width),a=Math.round(n.height);if(i<1||a<1)return;let o=Math.round(n.x),s=Math.round(n.y);switch(n.mode){case`solid`:Yt(e,n,o,s,i,a);return;case`pixelate`:Xt(e,t,r,o,s,i,a);return;case`blur`:Zt(e,t,r,o,s,i,a);return}}function Yt(e,t,n,r,i,a){e.save(),e.fillStyle=t.color,e.fillRect(n,r,i,a),e.restore()}function Xt(e,t,n,r,i,a,o){let s=Math.max(a,o),c=Math.max(4,Math.round(8*Math.min(1,s/240))),l=Math.max(1,Math.round(a/s*c)),u=Math.max(1,Math.round(o/s*c));e.save();let d=Qt(l,u);if(!d){e.restore();return}d.ctx.imageSmoothingEnabled=!0,d.ctx.imageSmoothingQuality=`low`,d.ctx.drawImage(t,r,i,a,o,0,0,l,u),e.imageSmoothingEnabled=!1,e.drawImage(d.canvas,0,0,l,u,r,i,a,o),e.restore()}function Zt(e,t,n,r,i,a,o){let s=1/8,c=Math.max(1,Math.round(a*s)),l=Math.max(1,Math.round(o*s)),u=Qt(c,l);if(!u)return;u.ctx.imageSmoothingEnabled=!0,u.ctx.imageSmoothingQuality=`high`,u.ctx.drawImage(t,r,i,a,o,0,0,c,l);let d=Math.max(1,Math.round(c*.5)),f=Math.max(1,Math.round(l*.5)),p=Qt(d,f);if(!p){e.save(),e.imageSmoothingEnabled=!0,e.imageSmoothingQuality=`high`,e.drawImage(u.canvas,0,0,c,l,r,i,a,o),e.restore();return}p.ctx.imageSmoothingEnabled=!0,p.ctx.imageSmoothingQuality=`high`,p.ctx.drawImage(u.canvas,0,0,c,l,0,0,d,f),e.save(),e.imageSmoothingEnabled=!0,e.imageSmoothingQuality=`high`,e.drawImage(p.canvas,0,0,d,f,r,i,a,o),e.restore()}function Qt(e,t){if(typeof OffscreenCanvas<`u`)try{let n=new OffscreenCanvas(e,t),r=n.getContext(`2d`);if(r)return{canvas:n,ctx:r}}catch{}if(typeof document>`u`)return null;let n=document.createElement(`canvas`);n.width=e,n.height=t;let r=n.getContext(`2d`);return r?{canvas:n,ctx:r}:null}var $t=`#000000`,en=`pixelate`;function tn(e){return{regions:[],nextRegionNumber:1,selectedId:null,currentMode:en,currentColor:$t,imageSize:e.imageSize}}function nn(e){return{id:`r_${e.nextRegionNumber.toString(36)}`,nextRegionNumber:e.nextRegionNumber+1}}function rn(e,t){return{...e,regions:[...e.regions,t],selectedId:t.id}}function G(e,t){let n=!1,r=e.regions.map(e=>e.id===t.id?(n=!0,t):e);return n?{...e,regions:r}:e}function an(e,t){let n=e.regions.filter(e=>e.id!==t);return n.length===e.regions.length?e:{...e,regions:n,selectedId:e.selectedId===t?null:e.selectedId}}function on(e,t){return e.selectedId===t?e:{...e,selectedId:t}}function sn(e,t){return e.currentMode===t?e:{...e,currentMode:t}}function cn(e,t){return e.currentColor===t?e:{...e,currentColor:t}}function ln(e,t,n){let r=e.regions.find(e=>e.id===t);return!r||r.mode===n?e:G(e,{...r,mode:n})}function un(e,t,n){let r=e.regions.find(e=>e.id===t);return!r||r.color===n?e:G(e,{...r,color:n})}function K(e){return e.selectedId===null?null:e.regions.find(t=>t.id===e.selectedId)??null}function dn(e){let{x:t,y:n,width:r,height:i}=e;return r<0&&(t+=r,r=-r),i<0&&(n+=i,i=-i),{x:t,y:n,width:r,height:i}}function fn(e){let{imageSize:t,mode:n,color:r,id:i}=e,a=Math.min(t.width,t.height),o=Math.max(80,Math.round(a*.25)),s=t.width/2,c=t.height/2;return{id:i,x:Math.round(s-o/2),y:Math.round(c-o/2),width:o,height:o,mode:n,color:r}}function pn(e,t){if(e.imageSize.width===t.width&&e.imageSize.height===t.height)return e;let n=[];for(let r of e.regions)r.x+r.width<=0||r.y+r.height<=0||r.x>=t.width||r.y>=t.height||n.push(mn(r,t));let r=e.selectedId!==null&&!n.some(t=>t.id===e.selectedId);return{...e,regions:n,imageSize:{width:t.width,height:t.height},selectedId:r?null:e.selectedId}}function mn(e,t){let n=Math.max(0,e.x),r=Math.max(0,e.y),i=Math.min(t.width,e.x+e.width),a=Math.min(t.height,e.y+e.height);return{...e,x:n,y:r,width:Math.max(0,i-n),height:Math.max(0,a-r)}}var q=8e3;function hn(){return{scaleX:1,scaleY:1,lockAspect:!0}}function gn(e){return Math.abs(e.scaleX-1)<1e-9&&Math.abs(e.scaleY-1)<1e-9}function _n(e,t){return{width:Sn(Math.round(t.width*e.scaleX)),height:Sn(Math.round(t.height*e.scaleY))}}function vn(e,t,n){if(n.width<=0)return e;let r=Sn(Math.round(t))/n.width,i=e.lockAspect?r:e.scaleY;return{...e,scaleX:r,scaleY:i}}function yn(e,t,n){if(n.height<=0)return e;let r=Sn(Math.round(t))/n.height,i=e.lockAspect?r:e.scaleX;return{...e,scaleX:i,scaleY:r}}function bn(e,t){let n=Cn(t/100);return{...e,scaleX:n,scaleY:n}}function xn(e,t){if(e.lockAspect===t)return e;if(!t)return{...e,lockAspect:!1};let n=(e.scaleX+e.scaleY)/2;return{scaleX:n,scaleY:n,lockAspect:!0}}function Sn(e){return Number.isFinite(e)?Math.max(1,Math.min(q,Math.trunc(e))):1}function Cn(e){return!Number.isFinite(e)||e<=0?.01:Math.max(.01,Math.min(e,q))}async function wn(e,t){if(gn(e))return t;let{width:n,height:r}=_n(e,t);if(n<=0||r<=0)return t;let i=Tn(t.width,t.height,n,r),a={bitmap:t.bitmap,width:t.width,height:t.height},o=[];for(let e=0;e<i;e++){let e=Math.max(n,Math.floor(a.width/2)),t=Math.max(r,Math.floor(a.height/2)),i=En(a,e,t);o.push(i),a={bitmap:i.canvas,width:e,height:t}}let s=En(a,n,r);return o.length=0,{bitmap:s.canvas,width:n,height:r,mimeType:t.mimeType}}function Tn(e,t,n,r){let i=e,a=t,o=0;for(;(i/2>n||a/2>r)&&o<16;)i=Math.floor(i/2),a=Math.floor(a/2),o+=1;return o}function En(e,r,i){let a=t(r,i),o=n(a);return o.imageSmoothingEnabled=!0,o.imageSmoothingQuality=`high`,o.drawImage(e.bitmap,0,0,e.width,e.height,0,0,r,i),a}function Dn(e,t){let n=e.width,r=e.height;if(n<=0||r<=0)return{width:0,height:0};let i=Math.abs(Math.cos(t)),a=Math.abs(Math.sin(t)),o=n*i+r*a,s=n*a+r*i,c=o>On?n*n/o:1/0,l=s>On?n*r/s:1/0,u=Math.min(c,l);return{width:u,height:u*r/n}}var On=1e-9,kn=.1;function An(){return{quarterTurns:0,freeAngle:0}}function jn(e){return{...e,quarterTurns:(e.quarterTurns+1)%4}}function Mn(e){return{...e,quarterTurns:(e.quarterTurns+3)%4}}function Nn(e,t){let n=In(t,-45,45),r=Math.round(n*10)/10;return{...e,freeAngle:r}}function Pn(e){return e.quarterTurns===0&&Math.abs(e.freeAngle)<1e-6}function Fn(e){return e.quarterTurns*90+e.freeAngle}function In(e,t,n){return Math.max(t,Math.min(n,e))}async function Ln(e,r){if(Pn(e))return r;let i=Fn(e),a=i*Math.PI/180,o=i-e.quarterTurns*90,s=Math.abs(o)<1e-6,c,l;if(s)e.quarterTurns===1||e.quarterTurns===3?(c=r.height,l=r.width):(c=r.width,l=r.height);else{let e=Dn(r,a);c=Math.max(1,Math.round(e.width)),l=Math.max(1,Math.round(e.height))}let u=t(c,l),d=n(u);return d.imageSmoothingEnabled=!0,d.imageSmoothingQuality=`high`,d.translate(c/2,l/2),d.rotate(a),d.drawImage(r.bitmap,-r.width/2,-r.height/2),{bitmap:u.canvas,width:c,height:l,mimeType:r.mimeType}}function Rn(e){let t=e,n=new Set;function r(e){for(let r of[...n])try{r(t,e)}catch(e){queueMicrotask(()=>{throw e})}}return{get(){return t},set(e){let n=t;t={...t,...e},r(n)},update(e){let n=t;t={...t,...e(t)},r(n)},subscribe(e){return n.add(e),()=>n.delete(e)}}}var zn=1.0015;function Bn(e,t){let n=new Map,r=null;function i(){return e.getBoundingClientRect()}function a(e,t){let n=i();return{x:e-n.left,y:t-n.top}}function o(){let e=i();return{x:e.width/2,y:e.height/2}}function s(){if(n.size<2)return null;let e=n.values(),t=e.next().value,r=e.next().value,i=a((t.x+r.x)/2,(t.y+r.y)/2),o=r.x-t.x,s=r.y-t.y;return{midpoint:i,distance:Math.sqrt(o*o+s*s)}}function c(){if(n.size<2||r!==null)return;let e=s();!e||e.distance<=0||(r={lastDistance:e.distance,lastMidpoint:e.midpoint},t.setPinching(!0))}function l(){r!==null&&(r=null,t.setPinching(!1))}function u(e){e.pointerType===`mouse`&&e.button!==0||(n.set(e.pointerId,{id:e.pointerId,x:e.clientX,y:e.clientY}),c())}function d(e){let i=n.get(e.pointerId);if(!i||(i.x=e.clientX,i.y=e.clientY,r===null))return;let a=s();if(!a||a.distance<=0)return;let c=a.distance/r.lastDistance;c!==1&&t.zoomAt(c,a.midpoint,o());let l=a.midpoint.x-r.lastMidpoint.x,u=a.midpoint.y-r.lastMidpoint.y;(l!==0||u!==0)&&t.panBy(l,u),r.lastDistance=a.distance,r.lastMidpoint=a.midpoint,e.preventDefault()}function f(e){n.has(e.pointerId)&&(n.delete(e.pointerId),n.size<2&&l())}function p(e){let n=zn**-e.deltaY;if(n===1)return;let r=a(e.clientX,e.clientY);t.zoomAt(n,r,o()),e.preventDefault()}return e.addEventListener(`pointerdown`,u),e.addEventListener(`pointermove`,d),e.addEventListener(`pointerup`,f),e.addEventListener(`pointercancel`,f),e.addEventListener(`pointerleave`,f),e.addEventListener(`wheel`,p,{passive:!1}),()=>{e.removeEventListener(`pointerdown`,u),e.removeEventListener(`pointermove`,d),e.removeEventListener(`pointerup`,f),e.removeEventListener(`pointercancel`,f),e.removeEventListener(`pointerleave`,f),e.removeEventListener(`wheel`,p),n.clear(),r!==null&&t.setPinching(!1),r=null}}var Vn=[`a[href]`,`button:not([disabled])`,`input:not([disabled]):not([type="hidden"])`,`select:not([disabled])`,`textarea:not([disabled])`,`[tabindex]:not([tabindex="-1"])`,`[contenteditable="true"]`].join(`, `);function Hn(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,n=document.createElement(`div`);n.className=`kalotyp-nested-overlay`,e.variant&&n.classList.add(e.variant);let r=document.createElement(`div`);r.className=`kalotyp-nested-surface`,r.setAttribute(`role`,`dialog`),r.setAttribute(`aria-modal`,`true`),r.tabIndex=-1;let i=`kalotyp-nested-title-${Math.random().toString(36).slice(2,8)}`;r.setAttribute(`aria-labelledby`,i);let a=document.createElement(`div`);a.className=`kalotyp-nested-header`;let o=document.createElement(`h3`);o.id=i,o.className=`kalotyp-nested-title`,o.textContent=e.title,a.appendChild(o);let s;e.showCloseButton!==!1&&(s=document.createElement(`button`),s.type=`button`,s.className=`kalotyp-nested-close`,s.setAttribute(`aria-label`,`Close ${e.title}`),s.textContent=`×`,s.addEventListener(`click`,()=>f()),a.appendChild(s)),r.appendChild(a);let c=document.createElement(`div`);if(c.className=`kalotyp-nested-body`,c.appendChild(e.body),r.appendChild(c),n.appendChild(r),e.host.appendChild(n),e.anchor){n.classList.add(`kalotyp-nested-overlay--popover`),Un(n,r,e.anchor);let t=()=>Un(n,r,e.anchor);window.addEventListener(`resize`,t),n.dataset.resizeListenerAttached=`1`,n.addEventListener(`kalotyp-nested-cleanup`,()=>{window.removeEventListener(`resize`,t)})}else n.classList.add(`kalotyp-nested-overlay--modal`);requestAnimationFrame(()=>r.focus());let l=e=>{if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),f();return}if(e.key!==`Tab`)return;let t=Array.from(r.querySelectorAll(Vn));if(t.length===0){e.preventDefault(),r.focus();return}let n=t[0],i=t[t.length-1];if(!n||!i)return;let a=document.activeElement;e.shiftKey?(a===n||!r.contains(a))&&(e.preventDefault(),i.focus()):(a===i||!r.contains(a))&&(e.preventDefault(),n.focus())};document.addEventListener(`keydown`,l,!0);let u=e=>{let t=e.target;t&&(r.contains(t)||f())};n.addEventListener(`mousedown`,u);let d=!1;function f(){if(!d){if(d=!0,document.removeEventListener(`keydown`,l,!0),n.removeEventListener(`mousedown`,u),n.dispatchEvent(new Event(`kalotyp-nested-cleanup`)),n.remove(),t?.isConnected)try{t.focus()}catch{}e.onClose()}}return{element:n,close:f}}function Un(e,t,n){let r=n.getBoundingClientRect(),i=e.parentElement?.getBoundingClientRect()??{left:0,top:0,right:window.innerWidth,bottom:window.innerHeight},a=t.getBoundingClientRect(),o=r.top-i.top-a.height-8,s=i.right-r.right;t.style.position=`absolute`,t.style.top=`${Math.max(8,o)}px`,t.style.right=`${Math.max(8,s)}px`}var Wn=[{keys:[`?`],description:`Show keyboard shortcuts`,context:`editor`},{keys:[`Esc`],description:`Close editor (or clear current selection)`,context:`editor`},{keys:[`Ctrl`,`Z`],description:`Undo`,context:`editor`},{keys:[`Ctrl`,`Shift`,`Z`],description:`Redo`,context:`editor`},{keys:[`Ctrl`,`Y`],description:`Redo (alternate)`,context:`editor`},{keys:[`Tab`],description:`Move focus to next control`,context:`editor`},{keys:[`Shift`,`Tab`],description:`Move focus to previous control`,context:`editor`},{keys:[`Delete`],description:`Delete the selected shape`,context:`annotate`},{keys:[`Arrow keys`],description:`Nudge the selected shape by 1 px`,context:`annotate`},{keys:[`Shift`,`Arrow keys`],description:`Nudge the selected shape by 10 px`,context:`annotate`},{keys:[`Shift`,`while drawing`],description:`Constrain shape (square, 45° line, circle)`,context:`annotate`},{keys:[`Delete`],description:`Delete the selected redaction region`,context:`redact`},{keys:[`Arrow keys`],description:`Nudge the selected region by 1 px`,context:`redact`},{keys:[`Shift`,`Arrow keys`],description:`Nudge the selected region by 10 px`,context:`redact`},{keys:[`Enter`],description:`Commit the text and close the editor`,context:`text`},{keys:[`Shift`,`Enter`],description:`Insert a line break`,context:`text`},{keys:[`Esc`],description:`Cancel the in-progress edit`,context:`text`}],Gn={editor:`Editor`,annotate:`Annotate`,redact:`Redact`,text:`Text editing`},Kn=[`editor`,`annotate`,`redact`,`text`];function qn(e){let t=document.createElement(`div`);t.className=`kalotyp-cheatsheet-body`;for(let e of Kn){let n=Wn.filter(t=>t.context===e);n.length!==0&&t.appendChild(Jn(e,n))}let n=Hn({host:e.host,title:`Keyboard shortcuts`,body:t,variant:`kalotyp-cheatsheet-modal`,showCloseButton:!0,onClose:e.onClose});return{close:()=>n.close()}}function Jn(e,t){let n=document.createElement(`section`);n.className=`kalotyp-cheatsheet-section`;let r=document.createElement(`h4`);r.className=`kalotyp-cheatsheet-heading`,r.textContent=Gn[e],n.appendChild(r);let i=document.createElement(`dl`);i.className=`kalotyp-cheatsheet-list`;for(let e of t){let t=document.createElement(`dt`);t.className=`kalotyp-cheatsheet-keys`,e.keys.forEach((e,n)=>{if(n>0){let e=document.createElement(`span`);e.className=`kalotyp-cheatsheet-plus`,e.setAttribute(`aria-hidden`,`true`),e.textContent=`+`,t.appendChild(e)}let r=document.createElement(`kbd`);r.className=`kalotyp-cheatsheet-kbd`,r.textContent=e,t.appendChild(r)});let n=document.createElement(`dd`);n.className=`kalotyp-cheatsheet-description`,n.textContent=e.description,i.appendChild(t),i.appendChild(n)}return n.appendChild(i),n}function Yn(e,t,n,r){let i=document.createElement(`div`);i.className=`kalotyp-util-nav`,i.setAttribute(`role`,`tablist`),i.setAttribute(`aria-label`,`Editor tools`);let a=new Map;for(let o of e){let e=document.createElement(`button`);e.type=`button`,e.className=`kalotyp-util-nav-button`,e.dataset.utilityId=o.id,e.id=`${r.panelId}-tab-${o.id}`,e.setAttribute(`role`,`tab`),e.setAttribute(`aria-selected`,o.id===t?`true`:`false`),e.setAttribute(`aria-controls`,r.panelId),e.tabIndex=o.id===t?0:-1,e.textContent=o.label,e.addEventListener(`click`,()=>n(o.id)),i.appendChild(e),a.set(o.id,e)}return i.addEventListener(`keydown`,t=>{if(t.key!==`ArrowLeft`&&t.key!==`ArrowRight`&&t.key!==`Home`&&t.key!==`End`)return;let r=e.map(e=>e.id),i=t.target?.dataset?.utilityId,o=i?r.indexOf(i):-1;if(o===-1)return;let s=o;t.key===`ArrowLeft`?s=(o-1+r.length)%r.length:t.key===`ArrowRight`?s=(o+1)%r.length:t.key===`Home`?s=0:t.key===`End`&&(s=r.length-1);let c=r[s];!c||c===i||(t.preventDefault(),n(c),a.get(c)?.focus())}),{container:i,buttons:a}}function Xn(e,t,n){for(let[r,i]of e.buttons.entries()){let e=r===t;if(i.setAttribute(`aria-selected`,e?`true`:`false`),i.tabIndex=e?0:-1,e){try{i.scrollIntoView({block:`nearest`,inline:`nearest`,behavior:`smooth`})}catch{}n&&n.setAttribute(`aria-labelledby`,i.id)}}}var Zn=[`a[href]`,`button:not([disabled])`,`input:not([disabled]):not([type="hidden"])`,`select:not([disabled])`,`textarea:not([disabled])`,`details`,`summary`,`[tabindex]:not([tabindex="-1"])`,`[contenteditable="true"]`].join(`, `);function Qn(e){let{host:t}=e,n=document.activeElement instanceof HTMLElement&&document.activeElement!==document.body?document.activeElement:null;function r(){return Array.from(t.querySelectorAll(Zn))}let i=e.initialFocus??r()[0];i&&requestAnimationFrame(()=>i.focus());let a=e=>{if(e.key!==`Tab`)return;let n=r();if(n.length===0){e.preventDefault();return}let i=n[0],a=n[n.length-1];if(!i||!a)return;let o=document.activeElement;e.shiftKey?(o===i||!t.contains(o))&&(e.preventDefault(),a.focus()):(o===a||!t.contains(o))&&(e.preventDefault(),i.focus())};return document.addEventListener(`keydown`,a,!0),{refresh:()=>{},release:()=>{if(document.removeEventListener(`keydown`,a,!0),n?.isConnected)try{n.focus()}catch{}}}}var $n=[[`path`,{d:`M5 12h14`}],[`path`,{d:`m12 5 7 7-7 7`}]],er=[[`path`,{d:`M20 6 9 17l-5-5`}]],tr=[[`path`,{d:`m6 9 6 6 6-6`}]],nr=[[`circle`,{cx:`12`,cy:`12`,r:`10`}]],rr=[[`path`,{d:`m3 7 5 5-5 5V7`}],[`path`,{d:`m21 7-5 5 5 5V7`}],[`path`,{d:`M12 20v2`}],[`path`,{d:`M12 14v2`}],[`path`,{d:`M12 8v2`}],[`path`,{d:`M12 2v2`}]],ir=[[`path`,{d:`m17 3-5 5-5-5h10`}],[`path`,{d:`m17 21-5-5-5 5h10`}],[`path`,{d:`M4 12H2`}],[`path`,{d:`M10 12H8`}],[`path`,{d:`M16 12h-2`}],[`path`,{d:`M22 12h-2`}]],ar=[[`path`,{d:`m9 11-6 6v3h9l3-3`}],[`path`,{d:`m22 12-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4`}]],or=[[`path`,{d:`M10 8h.01`}],[`path`,{d:`M12 12h.01`}],[`path`,{d:`M14 8h.01`}],[`path`,{d:`M16 12h.01`}],[`path`,{d:`M18 8h.01`}],[`path`,{d:`M6 8h.01`}],[`path`,{d:`M7 16h10`}],[`path`,{d:`M8 12h.01`}],[`rect`,{width:`20`,height:`16`,x:`2`,y:`4`,rx:`2`}]],sr=[[`path`,{d:`M9 17H7A5 5 0 0 1 7 7h2`}],[`path`,{d:`M15 7h2a5 5 0 1 1 0 10h-2`}],[`line`,{x1:`8`,x2:`16`,y1:`12`,y2:`12`}]],cr=[[`path`,{d:`M9 17H7A5 5 0 0 1 7 7`}],[`path`,{d:`M15 7h2a5 5 0 0 1 4 8`}],[`line`,{x1:`8`,x2:`12`,y1:`12`,y2:`12`}],[`line`,{x1:`2`,x2:`22`,y1:`2`,y2:`22`}]],lr=[[`path`,{d:`M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z`}]],ur=[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`}],[`path`,{d:`m15 5 4 4`}]],dr=[[`path`,{d:`M5 12h14`}],[`path`,{d:`M12 5v14`}]],fr=[[`path`,{d:`m15 14 5-5-5-5`}],[`path`,{d:`M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13`}]],pr=[[`path`,{d:`M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915`}],[`circle`,{cx:`12`,cy:`12`,r:`3`}]],mr=[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`}]],hr=[[`path`,{d:`M10 11v6`}],[`path`,{d:`M14 11v6`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`}],[`path`,{d:`M3 6h18`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`}]],gr=[[`path`,{d:`M12 4v16`}],[`path`,{d:`M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2`}],[`path`,{d:`M9 20h6`}]],_r=[[`path`,{d:`M9 14 4 9l5-5`}],[`path`,{d:`M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11`}]],vr=[[`path`,{d:`M18 6 6 18`}],[`path`,{d:`m6 6 12 12`}]],yr={xmlns:`http://www.w3.org/2000/svg`,width:16,height:16,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":2,"stroke-linecap":`round`,"stroke-linejoin":`round`,"aria-hidden":`true`};function br(e,t={}){let n={...yr,...t};return`<svg ${Object.entries(n).map(([e,t])=>`${e}="${t}"`).join(` `)}>${e.map(([e,t])=>`<${e} ${Object.entries(t).map(([e,t])=>`${e}="${t}"`).join(` `)} />`).join(``)}</svg>`}function xr(e){switch(e){case`select`:return lr;case`text`:return gr;case`rect`:return mr;case`ellipse`:return nr;case`arrow`:return $n;case`freehand`:return ur;case`highlight`:return ar;case`undo`:return _r;case`redo`:return fr;case`close`:return vr;case`delete`:return hr;case`check`:return er;case`lockClosed`:return sr;case`lockOpen`:return cr;case`plus`:return dr;case`flipHorizontal`:return rr;case`flipVertical`:return ir;case`chevronDown`:return tr;case`settings`:return pr;case`keyboard`:return or}}function J(e,t){return br(xr(e),t)}var Sr=[{value:`auto`,label:`Auto`,description:`WebP when supported, PNG fallback.`,requires:[]},{value:`image/webp`,label:`WebP`,description:`Best compression for most images.`,requires:[`image/webp`]},{value:`image/avif`,label:`AVIF`,description:`Smallest size; slower encode.`,requires:[`image/avif`]},{value:`image/jpeg`,label:`JPEG`,description:`Universal; no transparency.`,requires:[`image/jpeg`]},{value:`image/png`,label:`PNG`,description:`Lossless; preserves transparency.`,requires:[`image/png`]}];function Cr(e){let{host:t,anchor:n,store:r}=e,i=document.createElement(`div`);i.className=`kalotyp-output-popover-body`;let a=document.createElement(`label`);a.className=`kalotyp-output-row`;let s=document.createElement(`span`);s.className=`kalotyp-output-row-label`,s.textContent=`Format`,a.appendChild(s);let c=document.createElement(`select`);c.className=`kalotyp-output-format`,c.setAttribute(`aria-label`,`Output format`);for(let e of Sr){let t=document.createElement(`option`);t.value=e.value,t.textContent=e.label,c.appendChild(t)}c.value=r.get().mimeChoice,c.addEventListener(`change`,()=>{let e=c.value;r.update(t=>j(t,e))}),a.appendChild(c);let l=document.createElement(`p`);l.className=`kalotyp-output-hint`,l.setAttribute(`aria-live`,`polite`);let u=document.createElement(`label`);u.className=`kalotyp-output-row`;let d=document.createElement(`span`);d.className=`kalotyp-output-row-label`,d.textContent=`Quality`,u.appendChild(d);let f=document.createElement(`input`);f.type=`range`,f.className=`kalotyp-output-quality`,f.min=`50`,f.max=`100`,f.step=`1`,f.value=String(Math.round(r.get().quality*100)),f.setAttribute(`aria-label`,`Output quality`),f.addEventListener(`input`,()=>{r.update(e=>M(e,f.valueAsNumber/100))}),u.appendChild(f);let p=document.createElement(`span`);p.className=`kalotyp-output-quality-readout`,p.setAttribute(`aria-hidden`,`true`),p.textContent=`${Math.round(r.get().quality*100)}`,u.appendChild(p);let m=document.createElement(`p`);m.className=`kalotyp-output-summary`,m.setAttribute(`aria-live`,`polite`);let h=document.createElement(`label`);h.className=`kalotyp-output-metadata-row`;let g=document.createElement(`input`);g.type=`checkbox`,g.className=`kalotyp-output-metadata-checkbox`,g.checked=r.get().stripMetadata,g.addEventListener(`change`,()=>{r.update(e=>N(e,g.checked))});let _=document.createElement(`span`);_.className=`kalotyp-output-metadata-text`,_.textContent=`Strip EXIF, GPS, and camera metadata on save`,h.appendChild(g),h.appendChild(_);let v=document.createElement(`p`);v.className=`kalotyp-output-metadata-hint`,v.setAttribute(`aria-live`,`polite`);let y=document.createElement(`footer`);y.className=`kalotyp-output-footer`;let b=document.createElement(`button`);b.type=`button`,b.className=`kalotyp-output-done`,b.textContent=`Done`,b.setAttribute(`aria-label`,`Close output settings`),b.addEventListener(`click`,()=>S.close());let x=document.createElement(`button`);x.type=`button`,x.className=`kalotyp-output-save`,x.textContent=`Save and close`,x.addEventListener(`click`,()=>{e.canSave()&&e.onSaveAndClose()}),y.appendChild(b),y.appendChild(x),i.appendChild(a),i.appendChild(l),i.appendChild(u),i.appendChild(m),i.appendChild(h),i.appendChild(v),i.appendChild(y),n.setAttribute(`aria-expanded`,`true`);let S=Hn({host:t,anchor:n,title:`Output settings`,body:i,variant:`kalotyp-output-popover`,showCloseButton:!0,onClose:()=>{n.setAttribute(`aria-expanded`,`false`),w(),e.onClose()}});function C(t){c.value!==t.mimeChoice&&(c.value=t.mimeChoice);let n=Math.round(t.quality*100);f.valueAsNumber!==n&&(f.value=String(n)),p.textContent=String(n),l.textContent=Sr.find(e=>e.value===t.mimeChoice)?.description??``,m.textContent=wr(t);let r=t.mimeChoice!==`image/png`;f.disabled=!r,p.style.opacity=r?`1`:`0.4`,g.checked!==t.stripMetadata&&(g.checked=t.stripMetadata),v.textContent=Tr(t),x.disabled=!e.canSave()}C(r.get());let w=r.subscribe(C);return(async()=>{for(let e of Sr)if(e.requires.length!==0&&!(await Promise.all(e.requires.map(e=>o(e)))).every(Boolean)){let t=c.querySelector(`option[value="${e.value}"]`);t&&(t.disabled=!0,t.textContent=`${e.label} (unsupported)`)}})(),{close:()=>S.close()}}function wr(e){if(e.mimeChoice===`image/png`)return`PNG · lossless`;let t=Math.round(e.quality*100);switch(e.mimeChoice){case`auto`:return`Auto · ${t}% quality`;case`image/webp`:return`WebP · ${t}% quality`;case`image/avif`:return`AVIF · ${t}% quality`;case`image/jpeg`:return`JPEG · ${t}% quality`;default:return`${e.mimeChoice} · ${t}% quality`}}function Tr(e){return e.stripMetadata?``:e.mimeChoice===`image/jpeg`?`EXIF preserved when the source is also JPEG.`:e.mimeChoice===`auto`?`Metadata is preserved only when the resolved output is JPEG.`:`Metadata can only be preserved when the output is JPEG.`}var Er=[{id:`x`,label:`Left`},{id:`y`,label:`Top`},{id:`width`,label:`Width`,min:1},{id:`height`,label:`Height`,min:1}],Dr=[{id:`x1`,label:`Start X`},{id:`y1`,label:`Start Y`},{id:`x2`,label:`End X`},{id:`y2`,label:`End Y`}],Or=[{id:`x`,label:`X`},{id:`y`,label:`Y`}];function kr(e){let t=document.createElement(`div`);t.className=`kalotyp-annotate-coords`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,`Selected annotation position`),t.hidden=!0;let n=null,r=null,i=new Map;function a(e){t.replaceChildren(),i.clear();let n=Ar(e);for(let e of n){let n=document.createElement(`label`);n.className=`kalotyp-annotate-coords-field`;let r=document.createElement(`span`);r.className=`kalotyp-annotate-coords-label`,r.textContent=e.label;let a=document.createElement(`input`);a.type=`number`,a.className=`kalotyp-annotate-coords-input`,a.dataset.field=e.id,a.step=`1`,a.inputMode=`numeric`,e.min!==void 0&&(a.min=String(e.min)),e.max!==void 0&&(a.max=String(e.max)),a.setAttribute(`aria-label`,`${e.label} (pixels)`),a.addEventListener(`change`,s),n.appendChild(r),n.appendChild(a),t.appendChild(n),i.set(e.id,a)}r=e}function o(e){let t=(e,t)=>{let n=i.get(e);if(!n)return;let r=String(Math.round(t));document.activeElement!==n&&n.value!==r&&(n.value=r)};switch(e.kind){case`rect`:case`ellipse`:t(`x`,e.x),t(`y`,e.y),t(`width`,e.width),t(`height`,e.height);return;case`arrow`:t(`x1`,e.x1),t(`y1`,e.y1),t(`x2`,e.x2),t(`y2`,e.y2);return;case`text`:t(`x`,e.x),t(`y`,e.y);return;default:return}}function s(){if(!n||!r)return;let t=c(n);if(!t)return;let i=jr(n,t);i!==n&&(n=i,e.onShapeChanged(i))}function c(e){let t=e=>{let t=i.get(e);return t?t.valueAsNumber:NaN};switch(e.kind){case`rect`:case`ellipse`:{let n=Math.round(t(`x`)),r=Math.round(t(`y`)),i=Math.round(t(`width`)),a=Math.round(t(`height`));return[n,r,i,a].every(Number.isFinite)?{kind:e.kind,x:n,y:r,width:i,height:a}:null}case`arrow`:{let e=Math.round(t(`x1`)),n=Math.round(t(`y1`)),r=Math.round(t(`x2`)),i=Math.round(t(`y2`));return[e,n,r,i].every(Number.isFinite)?{kind:`arrow`,x1:e,y1:n,x2:r,y2:i}:null}case`text`:{let e=Math.round(t(`x`)),n=Math.round(t(`y`));return[e,n].every(Number.isFinite)?{kind:`text`,x:e,y:n}:null}default:return null}}return{container:t,updateForShape(e){if(!e){n=null,r=null,t.hidden=!0,t.replaceChildren(),i.clear();return}if(e.kind===`freehand`||e.kind===`highlight`){n=e,r=null,t.hidden=!0,t.replaceChildren(),i.clear();return}n=e,r!==e.kind&&a(e.kind),o(e),t.hidden=!1},destroy(){t.replaceChildren(),i.clear(),t.remove()}}}function Ar(e){switch(e){case`rect`:case`ellipse`:return Er;case`arrow`:return Dr;case`text`:return Or}}function jr(e,t){switch(e.kind){case`rect`:return t.kind===`rect`?{...e,x:t.x,y:t.y,width:t.width,height:t.height}:e;case`ellipse`:return t.kind===`ellipse`?{...e,x:t.x,y:t.y,width:t.width,height:t.height}:e;case`arrow`:return t.kind===`arrow`?{...e,x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2}:e;case`text`:return t.kind===`text`?{...e,x:t.x,y:t.y}:e;default:return e}}var Mr=[{id:`select`,label:`Select`,icon:J(`select`,{fill:`currentColor`,"stroke-width":1})},{id:`text`,label:`Text`,icon:J(`text`)},{id:`rect`,label:`Rectangle`,icon:J(`rect`)},{id:`ellipse`,label:`Ellipse`,icon:J(`ellipse`)},{id:`arrow`,label:`Arrow`,icon:J(`arrow`)},{id:`freehand`,label:`Freehand`,icon:J(`freehand`)},{id:`highlight`,label:`Highlight`,icon:J(`highlight`)}],Nr=[`#ff3b30`,`#ffcc00`,`#34c759`,`#007aff`,`#ffffff`,`#000000`];function Pr(e){let t=document.createElement(`div`);t.className=`kalotyp-annotate-panel`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,`Annotate`);let n=document.createElement(`div`);n.className=`kalotyp-annotate-toolbar`,n.setAttribute(`role`,`toolbar`),n.setAttribute(`aria-label`,`Annotation tools`);let r=new Map;for(let t of Mr){let i=document.createElement(`button`);i.type=`button`,i.className=`kalotyp-annotate-tool`,i.dataset.tool=t.id,i.setAttribute(`aria-label`,t.label),i.title=t.label,i.setAttribute(`aria-pressed`,t.id===e.initialTool?`true`:`false`),i.innerHTML=t.icon,i.addEventListener(`click`,()=>e.onSelectTool(t.id)),n.appendChild(i),r.set(t.id,i)}let i=document.createElement(`div`);i.className=`kalotyp-annotate-style-row`;let a=[],o=document.createElement(`div`);o.className=`kalotyp-annotate-swatches`,o.setAttribute(`role`,`radiogroup`),o.setAttribute(`aria-label`,`Color`);for(let t of Nr){let n=document.createElement(`button`);n.type=`button`,n.className=`kalotyp-annotate-swatch`,n.setAttribute(`role`,`radio`),n.setAttribute(`aria-label`,`Use color ${t}`),n.dataset.color=t,n.style.setProperty(`--kalotyp-swatch`,t),n.addEventListener(`click`,()=>e.onColorChange(t)),o.appendChild(n),a.push(n)}let s=Ir(e.initialStyle.color),c=document.createElement(`input`);c.type=`text`,c.className=`kalotyp-annotate-hex`,c.value=s,c.maxLength=7,c.spellcheck=!1,c.autocomplete=`off`,c.setAttribute(`aria-label`,`Color hex code`),c.setAttribute(`placeholder`,`#000000`),c.style.setProperty(`--kalotyp-hex-swatch`,s),c.addEventListener(`change`,()=>{let t=Lr(c.value.trim());t?(c.value=t,s=t,c.style.setProperty(`--kalotyp-hex-swatch`,t),e.onColorChange(t)):c.value=s});let l=document.createElement(`label`);l.className=`kalotyp-annotate-stroke-label`,l.textContent=`Width`;let u=document.createElement(`input`);u.type=`range`,u.className=`kalotyp-annotate-stroke`,u.min=`1`,u.max=`40`,u.step=`1`,u.value=String(e.initialStyle.strokeWidth),u.setAttribute(`aria-label`,`Stroke width`),u.addEventListener(`change`,()=>e.onStrokeWidthChange(u.valueAsNumber));let d=document.createElement(`button`);d.type=`button`,d.className=`kalotyp-annotate-delete`,d.innerHTML=`${J(`delete`)}<span>Delete</span>`,d.setAttribute(`aria-label`,`Delete selected annotation`),d.title=`Delete (Del)`,d.disabled=!e.canDelete,d.addEventListener(`click`,()=>e.onDeleteSelected());let f=document.createElement(`button`);f.type=`button`,f.className=`kalotyp-annotate-insert`,f.innerHTML=`${J(`plus`)}<span>Insert at centre</span>`,f.setAttribute(`aria-label`,`Insert annotation at image centre`),f.title=`Insert at centre`,f.disabled=!Fr(e.initialTool),f.addEventListener(`click`,()=>e.onInsertAtCenter()),i.appendChild(o),i.appendChild(c),i.appendChild(l),i.appendChild(u),i.appendChild(f),i.appendChild(d),t.appendChild(n),t.appendChild(i),t.appendChild(e.coordInputs);function p(e){for(let[t,n]of r)n.setAttribute(`aria-pressed`,t===e?`true`:`false`);f.disabled=!Fr(e)}function m(e){let t=Ir(e.color);c.value.toLowerCase()!==t.toLowerCase()&&(c.value=t),s=t,c.style.setProperty(`--kalotyp-hex-swatch`,t),u.valueAsNumber!==e.strokeWidth&&(u.value=String(e.strokeWidth));for(let t of a){let n=t.dataset.color?.toLowerCase()===e.color.toLowerCase();t.setAttribute(`aria-checked`,n?`true`:`false`)}}function h(e){d.disabled=!e}return m(e.initialStyle),{container:t,toolButtons:r,hexInput:c,colorSwatches:a,strokeRange:u,deleteButton:d,insertButton:f,setActiveTool:p,setStyle:m,setCanDelete:h}}function Fr(e){return e===`select`?!1:Ee(e)}function Ir(e){if(/^#[0-9a-fA-F]{6}$/.test(e))return e;if(/^#[0-9a-fA-F]{3}$/.test(e)){let t=e[1],n=e[2],r=e[3];return`#${t}${t}${n}${n}${r}${r}`}return`#000000`}function Lr(e){let t=e.startsWith(`#`)?e.slice(1):e;if(/^[0-9a-fA-F]{6}$/.test(t))return`#${t.toLowerCase()}`;if(/^[0-9a-fA-F]{3}$/.test(t)){let e=t[0],n=t[1],r=t[2];return`#${e}${e}${n}${n}${r}${r}`.toLowerCase()}return null}function Rr(e,t){let n=n=>{if(n.button!==0)return;let r=t(n);if(!r)return;n.preventDefault(),n.stopPropagation();try{e.setPointerCapture(n.pointerId)}catch{}let i,a=!1,o=n.shiftKey,s=()=>{if(a=!1,!i)return;let e=i;i=void 0,r.onMove(e)},c=e=>{i=e,a||(a=!0,requestAnimationFrame(s))},l=e=>{e.pointerId===n.pointerId&&(o=e.shiftKey,c({clientX:e.clientX,clientY:e.clientY,shiftKey:e.shiftKey}))},u=e=>{if(e.key!==`Shift`||e.shiftKey===o)return;o=e.shiftKey;let t=i;c({clientX:t?.clientX??n.clientX,clientY:t?.clientY??n.clientY,shiftKey:e.shiftKey})},d=t=>{e.removeEventListener(`pointermove`,l),e.removeEventListener(`pointerup`,f),e.removeEventListener(`pointercancel`,p),window.removeEventListener(`keydown`,u),window.removeEventListener(`keyup`,u);try{e.releasePointerCapture(n.pointerId)}catch{}if(i){let e=i;i=void 0,r.onMove(e)}t?r.onCommit():r.onCancel()},f=e=>{e.pointerId===n.pointerId&&d(!0)},p=e=>{e.pointerId===n.pointerId&&d(!1)};e.addEventListener(`pointermove`,l),e.addEventListener(`pointerup`,f),e.addEventListener(`pointercancel`,p),window.addEventListener(`keydown`,u),window.addEventListener(`keyup`,u)};return e.addEventListener(`pointerdown`,n),()=>e.removeEventListener(`pointerdown`,n)}function zr(e,t,n){let r=e.getBoundingClientRect();return{x:t-r.left,y:n-r.top}}function Br(e,t,n){let r=Math.max(1,window.devicePixelRatio||1),i=Math.max(1,Math.round(t*r)),a=Math.max(1,Math.round(n*r));e.width!==i&&(e.width=i),e.height!==a&&(e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o?(o.setTransform(r,0,0,r,0,0),o.clearRect(0,0,t,n),o):null}function Vr(e,t,n,r,i){let a=Br(e,n,r);a&&(a.imageSmoothingEnabled=!0,a.imageSmoothingQuality=`high`,a.drawImage(t.bitmap,i.displayRect.x,i.displayRect.y,i.displayRect.width,i.displayRect.height))}function Hr(e,t,n,r,i){let a=Br(e,n,r);if(a&&t.length!==0){a.save(),a.translate(i.displayRect.x,i.displayRect.y),a.scale(i.scale,i.scale);for(let e of t)Ae(a,e);a.restore()}}function Ur(e,t,n,r,i){let a=Br(e,n,r);a&&t!==null&&(a.save(),a.translate(i.displayRect.x,i.displayRect.y),a.scale(i.scale,i.scale),Ae(a,t),a.restore())}function Wr(e,t,n,r,i){let a=Br(e,n,r);if(!a||!t)return;let o=i.displayRect.x+t.x*i.scale,s=i.displayRect.y+t.y*i.scale,c=t.width*i.scale,l=t.height*i.scale,u=o,d=s;c<0&&(u=o+c,c=-c),l<0&&(d=s+l,l=-l),a.save(),a.fillStyle=`rgba(99, 102, 241, 0.12)`,a.fillRect(u,d,c,l),a.strokeStyle=`rgba(99, 102, 241, 0.95)`,a.lineWidth=1,a.setLineDash([4,3]),a.strokeRect(u+.5,d+.5,c-1,l-1),a.restore()}function Gr(e){let{host:t,toolContext:n}=e,r=new Map,i=[];for(let e of Le){let a=document.createElement(`button`);a.type=`button`,a.className=`kalotyp-annotate-handle`,a.dataset.direction=e,a.setAttribute(`aria-label`,Zr(e)),a.tabIndex=-1,a.style.display=`none`,r.set(e,a),t.appendChild(a),i.push(Rr(a,t=>Yr(n,e,t)))}function a(e,t){if(!e){Jr(r);return}if(e.kind===`arrow`){Jr(r);let n=r.get(`tl`),i=r.get(`br`);n&&qr(n,Kr({x:e.x1,y:e.y1},t)),i&&qr(i,Kr({x:e.x2,y:e.y2},t));return}let n=Re(H(e));for(let e of Le){let i=r.get(e);i&&qr(i,Kr(n[e],t))}}function o(){for(let e of i)e();for(let[,e]of r)e.remove();r.clear()}return{update:a,destroy:o}}function Kr(e,t){return{x:t.displayRect.x+e.x*t.scale,y:t.displayRect.y+e.y*t.scale}}function qr(e,t){e.style.display=``,e.style.left=`${t.x}px`,e.style.top=`${t.y}px`}function Jr(e){for(let[,t]of e)t.style.display=`none`}function Yr(e,t,n){let r=e.store.get(),i=r.shapes.find(e=>e.id===r.selectedId);if(!i)return null;let a=i;return{onMove(n){let r=Xr(a,t,e.toImageSpace(n));r&&e.store.update(e=>V(e,r))},onCommit(){e.commit()},onCancel(){e.store.update(e=>V(e,a))}}}function Xr(e,t,n){switch(e.kind){case`rect`:case`ellipse`:{let r=ze({x:e.x,y:e.y,width:e.width,height:e.height},t,n);return{...e,x:r.x,y:r.y,width:r.width,height:r.height}}case`arrow`:{let r=e;return t===`tl`?{...r,x1:n.x,y1:n.y}:t===`br`?{...r,x2:n.x,y2:n.y}:e}case`text`:{if(t!==`br`)return e;let r=n.x-e.x,i=n.y-e.y,a=Math.max(8,Math.round(Math.max(r,i)*.6));return{...e,fontSize:a}}case`freehand`:case`highlight`:{let r=H(e);if(r.width===0||r.height===0)return e;let i=ze(r,t,n),a=i.width/r.width,o=i.height/r.height;if(!Number.isFinite(a)||!Number.isFinite(o))return e;let s=e.points.map(e=>({x:i.x+(e.x-r.x)*a,y:i.y+(e.y-r.y)*o}));return{...e,points:s}}}}function Zr(e){switch(e){case`tl`:return`Resize from top-left`;case`tr`:return`Resize from top-right`;case`bl`:return`Resize from bottom-left`;case`br`:return`Resize from bottom-right`;case`t`:return`Resize from top`;case`r`:return`Resize from right`;case`b`:return`Resize from bottom`;case`l`:return`Resize from left`}}function Y(e){return e.selectedId===null?null:e.shapes.find(t=>t.id===e.selectedId)??null}function Qr(){let e=document.createElement(`div`);e.className=`kalotyp-annotate-stage`;let t=document.createElement(`canvas`);t.className=`kalotyp-annotate-image`,t.setAttribute(`aria-hidden`,`true`);let n=document.createElement(`canvas`);n.className=`kalotyp-annotate-shapes`,n.setAttribute(`aria-hidden`,`true`);let r=document.createElement(`canvas`);r.className=`kalotyp-annotate-live`,r.setAttribute(`aria-hidden`,`true`);let i=document.createElement(`div`);i.className=`kalotyp-annotate-hit`,i.setAttribute(`role`,`presentation`);let a=document.createElement(`div`);a.className=`kalotyp-annotate-handles`,a.setAttribute(`role`,`group`),a.setAttribute(`aria-label`,`Selected annotation`);let o=document.createElement(`div`);return o.className=`kalotyp-annotate-text-overlay`,e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(i),e.appendChild(a),e.appendChild(o),{container:e,imageCanvas:t,shapesCanvas:n,liveCanvas:r,hitArea:i,handlesLayer:a,textOverlay:o}}function $r(e){let t=document.createElement(`div`);t.className=`kalotyp-annotate-text-editor`,t.setAttribute(`contenteditable`,`true`),t.setAttribute(`role`,`textbox`),t.setAttribute(`aria-label`,`Annotation text`),t.spellcheck=!1,t.style.display=`none`,e.host.appendChild(t);let n=null,r=()=>{e.onInput(t.innerText)},i=t=>{if(t.key===`Enter`&&!t.shiftKey){t.preventDefault(),t.stopPropagation(),e.onCommit();return}t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),e.onCancel())},a=r=>{n!==null&&(t.contains(r.target)||e.onCommit())};return t.addEventListener(`input`,r),t.addEventListener(`keydown`,i),document.addEventListener(`pointerdown`,a,!0),{open(e,r,i){n=e;let a=r.displayRect.x+e.x*r.scale,o=r.displayRect.y+e.y*r.scale;t.style.display=``,t.style.left=`${a}px`,t.style.top=`${o}px`,t.style.color=e.color,t.style.font=`${e.fontSize*r.scale}px ${Oe}`,t.style.textAlign=e.textAlign,t.style.transformOrigin=ei(e.textAlign);let s=Math.max(100,r.displayRect.x+r.displayRect.width-a-8);t.style.maxWidth=`${s}px`,t.innerText=e.text,requestAnimationFrame(()=>{t.focus();let e=document.createRange();e.selectNodeContents(t),e.collapse(!1);let n=window.getSelection();n?.removeAllRanges(),n?.addRange(e)})},close(){n=null,t.style.display=`none`,t.blur()},destroy(){t.removeEventListener(`input`,r),t.removeEventListener(`keydown`,i),document.removeEventListener(`pointerdown`,a,!0),t.remove()}}}function ei(e){switch(e){case`left`:return`top left`;case`center`:return`top center`;case`right`:return`top right`}}function ti(e,t){let n=t.x-e.x,r=t.y-e.y,i=Math.max(Math.abs(n),Math.abs(r)),a=n===0?1:Math.sign(n),o=r===0?1:Math.sign(r);return{x:e.x+a*i,y:e.y+o*i}}function ni(e,t){let n=t.x-e.x,r=t.y-e.y,i=Math.sqrt(n*n+r*r);if(i===0)return e;let a=Math.round(Math.atan2(r,n)/(Math.PI/4))*(Math.PI/4);return{x:e.x+Math.cos(a)*i,y:e.y+Math.sin(a)*i}}function ri(e,t){let n=t.x-e.x,r=t.y-e.y;return Math.abs(n)>=Math.abs(r)?{x:t.x,y:e.y}:{x:e.x,y:t.y}}function ii(e,t){let n=e.toImageSpace(t),r=e.store.get(),{id:i,nextShapeNumber:a}=z(r),o=n;return{onMove(t){let a=e.toImageSpace(t);o=t.shiftKey?ti(n,a):a;let s={id:i,kind:`rect`,x:n.x,y:n.y,width:o.x-n.x,height:o.y-n.y,strokeColor:r.currentStyle.color,strokeWidth:r.currentStyle.strokeWidth,fillColor:r.currentStyle.fillColor};e.setLiveShape(s)},onCommit(){let t=Ce({x:n.x,y:n.y,width:o.x-n.x,height:o.y-n.y});if(e.setLiveShape(null),t.width<2||t.height<2)return;let s={id:i,kind:`rect`,...t,strokeColor:r.currentStyle.color,strokeWidth:r.currentStyle.strokeWidth,fillColor:r.currentStyle.fillColor};e.store.update(e=>({...B(e,s),nextShapeNumber:a})),e.commit()},onCancel(){e.setLiveShape(null)}}}function ai(e,t){let n=e.toImageSpace(t),r=e.store.get(),{id:i,nextShapeNumber:a}=z(r),o=n;return{onMove(t){let a=e.toImageSpace(t);o=t.shiftKey?ti(n,a):a;let s={id:i,kind:`ellipse`,x:n.x,y:n.y,width:o.x-n.x,height:o.y-n.y,strokeColor:r.currentStyle.color,strokeWidth:r.currentStyle.strokeWidth,fillColor:r.currentStyle.fillColor};e.setLiveShape(s)},onCommit(){let t=Ce({x:n.x,y:n.y,width:o.x-n.x,height:o.y-n.y});if(e.setLiveShape(null),t.width<2||t.height<2)return;let s={id:i,kind:`ellipse`,...t,strokeColor:r.currentStyle.color,strokeWidth:r.currentStyle.strokeWidth,fillColor:r.currentStyle.fillColor};e.store.update(e=>({...B(e,s),nextShapeNumber:a})),e.commit()},onCancel(){e.setLiveShape(null)}}}function oi(e,t){let n=e.toImageSpace(t),r=e.store.get(),{id:i,nextShapeNumber:a}=z(r),o=n;return{onMove(t){let a=e.toImageSpace(t);o=t.shiftKey?ni(n,a):a;let s={id:i,kind:`arrow`,x1:n.x,y1:n.y,x2:o.x,y2:o.y,color:r.currentStyle.color,strokeWidth:r.currentStyle.strokeWidth};e.setLiveShape(s)},onCommit(){e.setLiveShape(null);let t=o.x-n.x,s=o.y-n.y;if(t*t+s*s<16)return;let c={id:i,kind:`arrow`,x1:n.x,y1:n.y,x2:o.x,y2:o.y,color:r.currentStyle.color,strokeWidth:r.currentStyle.strokeWidth};e.store.update(e=>({...B(e,c),nextShapeNumber:a})),e.commit()},onCancel(){e.setLiveShape(null)}}}function si(e,t,n){let r=e.toImageSpace(t),i=e.store.get(),{id:a,nextShapeNumber:o}=z(i),s=[r],c=!1,l=r,u=n.kind===`highlight`,d=u?he:i.currentStyle.color,f=u?18:i.currentStyle.strokeWidth;function p(t){let r={id:a,kind:n.kind,points:t,color:d,strokeWidth:f};e.setLiveShape(r)}return{onMove(t){let n=e.toImageSpace(t);c=t.shiftKey,t.shiftKey?(l=ri(r,n),p([r,l])):(s.push(n),p(s))},onCommit(){e.setLiveShape(null);let t=c?[r,l]:pe(s);if(t.length<2)return;if(t.length===2){let e=t[0],n=t[1];if(e&&n){let t=n.x-e.x,r=n.y-e.y;if(t*t+r*r<4)return}}let i={id:a,kind:n.kind,points:t,color:d,strokeWidth:f};e.store.update(e=>({...B(e,i),nextShapeNumber:o})),e.commit()},onCancel(){e.setLiveShape(null)}}}function ci(e,t,n,r,i,a){let o=e.toImageSpace(t);return e.store.update(e=>xe(e,n)),{onMove(t){let n=e.toImageSpace(t);a(i(r,n.x-o.x,n.y-o.y))},onCommit(){e.commit()},onCancel(){a(r)}}}var li=32;function ui(e){let{stageHost:t,utilHost:n,source:r,store:i,viewport:a}=e,o=e.onCommit??(()=>{}),s=e.onAnnounce??(()=>{}),c=Qr();t.appendChild(c.container);let l=d({width:1,height:1,padding:li},{width:r.width,height:r.height}),u=null,f=null;function m(){let e=c.container.getBoundingClientRect(),t={width:e.width,height:e.height,padding:li},n={width:r.width,height:r.height};l=a?a.computeViewport(t,n):d(t,n)}function h(){let e=c.container.getBoundingClientRect();e.width<=0||e.height<=0||(Vr(c.imageCanvas,r,e.width,e.height,l),Hr(c.shapesCanvas,i.get().shapes,e.width,e.height,l),Ur(c.liveCanvas,u,e.width,e.height,l),S.update(Y(i.get()),l))}function g(){let e=c.container.getBoundingClientRect();e.width<=0||e.height<=0||Hr(c.shapesCanvas,i.get().shapes,e.width,e.height,l)}function _(){let e=c.container.getBoundingClientRect();e.width<=0||e.height<=0||(f===null?Ur(c.liveCanvas,u,e.width,e.height,l):Wr(c.liveCanvas,f,e.width,e.height,l))}function v(e){u=e,f=null,_()}function y(e){f=e,u=null,_()}function b(e){return p(zr(c.container,e.clientX,e.clientY),l)}let x={store:i,toImageSpace:b,setLiveShape:v,commit:o},S=Gr({host:c.handlesLayer,stageElement:c.container,toolContext:x,getViewport:()=>l}),C=$r({host:c.textOverlay,onInput:e=>{let t=Y(i.get());t?.kind===`text`&&i.update(n=>V(n,{...t,text:e}))},onCommit:()=>{let e=Y(i.get());C.close(),e?.kind===`text`&&e.text.trim().length===0&&i.update(t=>Se(t,e.id)),o(),i.update(e=>ye(e,`select`))},onCancel:()=>{let e=Y(i.get());C.close(),e?.kind===`text`&&e.text.length===0&&i.update(t=>Se(t,e.id)),i.update(e=>ye(e,`select`))}}),w=Rr(c.hitArea,e=>{let t=i.get();switch(t.activeTool){case`select`:return T(t,e);case`rect`:return ii(x,e);case`ellipse`:return ai(x,e);case`arrow`:return oi(x,e);case`freehand`:return si(x,e,{kind:`freehand`});case`highlight`:return si(x,e,{kind:`highlight`});case`text`:return D(e),null;default:return null}});function T(e,t){let n=b(t),r=He(e.shapes,n);return r?(e.selectedId!==r.id&&i.update(e=>xe(e,r.id)),ci(x,t,r.id,r,we,e=>i.update(t=>V(t,e)))):E(t)}function E(e){let t=b(e),n=t;return{onMove(e){n=b(e),y({x:t.x,y:t.y,width:n.x-t.x,height:n.y-t.y})},onCommit(){y(null);let e=n.x-t.x,r=n.y-t.y;if(Math.abs(e)<2&&Math.abs(r)<2){i.update(e=>xe(e,null));return}let a=pi({x:t.x,y:t.y,width:e,height:r}),o=mi(i.get().shapes,a);i.update(e=>xe(e,o?.id??null))},onCancel(){y(null)}}}function D(e){let t=i.get(),n=b(e),{id:a,nextShapeNumber:o}=z(t),s={id:a,kind:`text`,x:n.x,y:n.y,text:``,fontSize:t.currentStyle.fontSize??32,color:t.currentStyle.color,textAlign:`left`};i.update(e=>({...B(e,s),nextShapeNumber:o})),C.open(s,l,r)}function O(){let e=i.get(),t=e.activeTool;if(t===`select`||!Ee(t))return;let{id:n,nextShapeNumber:a}=z(e),o=De(t,{imageSize:{width:r.width,height:r.height},style:e.currentStyle,id:n});if(i.update(e=>({...B(e,o),nextShapeNumber:a})),o.kind===`text`){C.open(o,l,r),s(`Text annotation placed at centre. Type to enter text.`);return}s(`${_i(o.kind)} placed at centre. Use arrow keys to nudge, or edit coordinates below.`),requestAnimationFrame(()=>{let e=k.container.querySelector(`.kalotyp-annotate-coords-input`);e?.focus(),e?.select()})}let k=kr({onShapeChanged:e=>{i.update(t=>V(t,e)),o()}}),A=i.get(),j=Pr({initialTool:A.activeTool,initialStyle:A.currentStyle,canDelete:A.selectedId!==null,coordInputs:k.container,onSelectTool:e=>i.update(t=>ye(t,e)),onColorChange:e=>{i.update(t=>{let n=be(t,{color:e}),r=Y(t);return r&&(n=V(n,di(r,e))),n}),o()},onStrokeWidthChange:e=>{i.update(t=>{let n=be(t,{strokeWidth:e}),r=Y(t);return r&&(n=V(n,fi(r,e))),n}),o()},onDeleteSelected:()=>{let e=i.get().selectedId;e&&(i.update(t=>Se(t,e)),o())},onInsertAtCenter:()=>O()});n.appendChild(j.container),m(),h();let M=new ResizeObserver(()=>{m(),h()});M.observe(c.container);let N=!1,P=a?.subscribe(()=>{N||(N=!0,requestAnimationFrame(()=>{N=!1,m(),h()}))}),F=i.get().shapes,I=i.get().selectedId,L=i.get().activeTool,R=i.get().currentStyle,ee=i.subscribe(e=>{let t=e.shapes!==F,n=e.selectedId!==I;t&&(F=e.shapes,g()),n&&(I=e.selectedId,j.setCanDelete(e.selectedId!==null)),e.activeTool!==L&&(L=e.activeTool,j.setActiveTool(e.activeTool)),e.currentStyle!==R&&(R=e.currentStyle,j.setStyle(e.currentStyle)),S.update(Y(e),l),(n||t)&&k.updateForShape(Y(e))}),te=e=>{let t=e.target;if(gi(t))return;let n=i.get();if(e.key===`Escape`){n.selectedId!==null&&(e.preventDefault(),e.stopPropagation(),i.update(e=>xe(e,null)),s(`Selection cleared.`));return}if(e.key===`Delete`||e.key===`Backspace`){if(n.selectedId===null)return;e.preventDefault();let t=n.selectedId;i.update(e=>Se(e,t)),o();return}if(e.key===`ArrowUp`||e.key===`ArrowDown`||e.key===`ArrowLeft`||e.key===`ArrowRight`){let t=Y(n);if(!t||e.ctrlKey||e.altKey||e.metaKey)return;let r=e.shiftKey?10:1,a=e.key===`ArrowLeft`?-r:e.key===`ArrowRight`?r:0,s=e.key===`ArrowUp`?-r:e.key===`ArrowDown`?r:0;e.preventDefault();let c=we(t,a,s);i.update(e=>V(e,c)),o()}};return document.addEventListener(`keydown`,te,!0),{destroy(){document.removeEventListener(`keydown`,te,!0),w(),ee(),P?.(),M.disconnect(),C.destroy(),S.destroy(),c.container.remove(),j.container.remove()}}}function di(e,t){switch(e.kind){case`text`:return{...e,color:t};case`rect`:case`ellipse`:return{...e,strokeColor:t};case`arrow`:case`freehand`:case`highlight`:return{...e,color:t}}}function fi(e,t){switch(e.kind){case`text`:return{...e,fontSize:Math.max(8,Math.round(t*4))};case`rect`:case`ellipse`:case`arrow`:case`freehand`:case`highlight`:return{...e,strokeWidth:t}}}function pi(e){let{x:t,y:n,width:r,height:i}=e;return r<0&&(t+=r,r=-r),i<0&&(n+=i,i=-i),{x:t,y:n,width:r,height:i}}function mi(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r&&hi(H(r),t))return r}}function hi(e,t){return!(e.x+e.width<t.x||t.x+t.width<e.x||e.y+e.height<t.y||t.y+t.height<e.y)}function gi(e){if(!e)return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`?!0:e.isContentEditable===!0}function _i(e){switch(e){case`rect`:return`Rectangle`;case`ellipse`:return`Ellipse`;case`arrow`:return`Arrow`;case`text`:return`Text annotation`}}function vi(e){return{id:`annotate`,init:e=>ve({imageSize:{width:e.source.width,height:e.source.height}}),mount(t,n,r){let i=ui({stageHost:t,utilHost:e.panelHost,source:n.source,store:r,viewport:n.viewport,onCommit:()=>n.bus.emit(`commit`,{utility:`annotate`}),onAnnounce:e=>n.bus.emit(`announce`,{message:e})});return{destroy:()=>i.destroy()}},bake:(e,t)=>ke({shapes:e.shapes},t)}}var X=12;function yi(e){let t=m(e.cropRectImage,e.viewport),{cornerAnchors:n,edgeHandles:r,bodyHitArea:i}=e;i.style.left=`${t.x}px`,i.style.top=`${t.y}px`,i.style.width=`${t.width}px`,i.style.height=`${t.height}px`,bi(n.tl,t.x,t.y),bi(n.tr,t.x+t.width,t.y),bi(n.bl,t.x,t.y+t.height),bi(n.br,t.x+t.width,t.y+t.height);let a=Math.max(0,t.width-X*2),o=Math.max(0,t.height-X*2);xi(r.t,t.x+X,t.y,a),xi(r.b,t.x+X,t.y+t.height,a),Si(r.l,t.x,t.y+X,o),Si(r.r,t.x+t.width,t.y+X,o)}function bi(e,t,n){e.style.left=`${t}px`,e.style.top=`${n}px`}function xi(e,t,n,r){e.style.left=`${t}px`,e.style.top=`${n}px`,e.style.width=`${r}px`}function Si(e,t,n,r){e.style.left=`${t}px`,e.style.top=`${n}px`,e.style.height=`${r}px`}function Ci(e,t,n,r,i){let a=Math.max(1,window.devicePixelRatio||1),o=Math.max(1,Math.round(n*a)),s=Math.max(1,Math.round(r*a));e.width!==o&&(e.width=o),e.height!==s&&(e.height=s),e.style.width=`${n}px`,e.style.height=`${r}px`;let c=e.getContext(`2d`);c&&(c.setTransform(a,0,0,a,0,0),c.clearRect(0,0,n,r),c.drawImage(t,i.displayRect.x,i.displayRect.y,i.displayRect.width,i.displayRect.height))}var wi=`rgba(0, 0, 0, 0.4)`,Ti=`rgba(0, 0, 0, 0.45)`,Ei=3,Di=`rgba(255, 255, 255, 0.95)`,Oi=1,ki=`rgba(0, 0, 0, 0.25)`,Ai=2,ji=`rgba(255, 255, 255, 0.55)`,Mi=1;function Ni(e,t,n,r,i){let a=Math.max(1,window.devicePixelRatio||1),o=Math.max(1,Math.round(n*a)),s=Math.max(1,Math.round(r*a));e.width!==o&&(e.width=o),e.height!==s&&(e.height=s),e.style.width=`${n}px`,e.style.height=`${r}px`;let c=e.getContext(`2d`);if(!c)return;c.setTransform(a,0,0,a,0,0),c.clearRect(0,0,n,r);let l=m(t,i),u=i.displayRect;c.save(),c.fillStyle=wi,c.fillRect(u.x,u.y,u.width,u.height),c.globalCompositeOperation=`destination-out`,c.fillRect(l.x,l.y,l.width,l.height),c.restore();let d=l.x+.5,f=l.y+.5,p=l.width-1,h=l.height-1;c.strokeStyle=Ti,c.lineWidth=Ei,c.strokeRect(d,f,p,h),c.strokeStyle=Di,c.lineWidth=Oi,c.strokeRect(d,f,p,h),Pi(c,l,ki,Ai),Pi(c,l,ji,Mi)}function Pi(e,t,n,r){e.strokeStyle=n,e.lineWidth=r,e.beginPath();for(let n=1;n<3;n++){let r=t.x+t.width*n/3,i=t.y+t.height*n/3;e.moveTo(r,t.y),e.lineTo(r,t.y+t.height),e.moveTo(t.x,i),e.lineTo(t.x+t.width,i)}e.stroke()}function Fi(e,t,n){let r=document.createElement(`div`);r.className=`kalotyp-preset-row`,r.setAttribute(`role`,`radiogroup`),r.setAttribute(`aria-label`,`Crop aspect ratio`);let i=[];return e.forEach((e,a)=>{let[,o]=e,s=document.createElement(`button`);s.type=`button`,s.className=`kalotyp-preset-button`,s.textContent=o,s.setAttribute(`role`,`radio`),s.setAttribute(`aria-checked`,a===t?`true`:`false`),s.dataset.presetIndex=String(a),s.addEventListener(`click`,()=>n(a,e)),r.appendChild(s),i.push(s)}),{container:r,buttons:i}}function Ii(e,t){e.forEach((e,n)=>{e.setAttribute(`aria-checked`,n===t?`true`:`false`)})}var Li=[`tl`,`tr`,`bl`,`br`],Ri=[`t`,`r`,`b`,`l`];function zi(){let e=document.createElement(`div`);e.className=`kalotyp-stage-container`;let t=document.createElement(`canvas`);t.className=`kalotyp-stage-image`,t.setAttribute(`aria-hidden`,`true`);let n=document.createElement(`canvas`);n.className=`kalotyp-stage-overlay`,n.setAttribute(`aria-hidden`,`true`);let r=document.createElement(`div`);r.className=`kalotyp-stage-body`;let i=document.createElement(`div`);i.className=`kalotyp-handles`,i.setAttribute(`role`,`group`),i.setAttribute(`aria-label`,`Crop region`);let a={};for(let e of Ri){let t=Vi(e);a[e]=t,i.appendChild(t)}let o={};for(let e of Li){let t=document.createElement(`div`);t.className=`kalotyp-corner-anchor`,t.dataset.direction=e;let n=Bi(e);t.appendChild(n),a[e]=n,o[e]=t,i.appendChild(t)}return e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(i),{container:e,imageCanvas:t,overlayCanvas:n,handlesLayer:i,handles:a,cornerAnchors:o,bodyHitArea:r}}function Bi(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`kalotyp-handle`,t.dataset.shape=`circle`,t.dataset.direction=e,t.setAttribute(`aria-label`,Hi(e)),t.tabIndex=0,t}function Vi(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`kalotyp-handle`,t.dataset.shape=`edge`,t.dataset.direction=e,t.setAttribute(`aria-label`,Hi(e)),t.tabIndex=0,t}function Hi(e){switch(e){case`tl`:return`Top-left crop handle`;case`tr`:return`Top-right crop handle`;case`bl`:return`Bottom-left crop handle`;case`br`:return`Bottom-right crop handle`;case`t`:return`Top crop handle`;case`r`:return`Right crop handle`;case`b`:return`Bottom crop handle`;case`l`:return`Left crop handle`}}function Ui(e,t,n){let r=[];for(let i of Object.keys(e.handles)){let a=e.handles[i];r.push(Wi(a,i,t,n))}return r.push(Gi(e.bodyHitArea,t,n)),{destroy(){for(let e of r)e()}}}function Wi(e,t,n,r){return Ki(e,()=>{let i=r.getViewport(),a=n.get(),o={x:0,y:0,width:a.imageSize.width,height:a.imageSize.height},s=a.aspectRatio;return{onMove(r){let c=p(qi(e,r.clientX,r.clientY),i),l=nt(a.rect,t,c,{bounds:o,...s===void 0?{}:{aspectRatio:s}});n.set({rect:l})},onCommit(){r.onCommit?.()},onCancel(){n.set({rect:a.rect})}}})}function Gi(e,t,n){return Ki(e,r=>{let i=n.getViewport(),a=t.get(),o={x:0,y:0,width:a.imageSize.width,height:a.imageSize.height},s=qi(e,r.clientX,r.clientY);return{onMove(n){let r=qi(e,n.clientX,n.clientY),c=(r.x-s.x)/i.scale,l=(r.y-s.y)/i.scale,u=x(a.rect,c,l,o);t.set({rect:u})},onCommit(){n.onCommit?.()},onCancel(){t.set({rect:a.rect})}}})}function Ki(e,t){let n=n=>{if(n.button!==0)return;n.preventDefault(),n.stopPropagation();let r=t(n);e.setPointerCapture(n.pointerId);let i,a=!1,o=()=>{if(a=!1,!i)return;let e=i;i=void 0,r.onMove(e)},s=e=>{e.pointerId===n.pointerId&&(i={clientX:e.clientX,clientY:e.clientY},a||(a=!0,requestAnimationFrame(o)))},c=t=>{e.removeEventListener(`pointermove`,s),e.removeEventListener(`pointerup`,l),e.removeEventListener(`pointercancel`,u);try{e.releasePointerCapture(n.pointerId)}catch{}if(i){let e=i;i=void 0,r.onMove(e)}t?r.onCommit():r.onCancel()},l=e=>{e.pointerId===n.pointerId&&c(!0)},u=e=>{e.pointerId===n.pointerId&&c(!1)};e.addEventListener(`pointermove`,s),e.addEventListener(`pointerup`,l),e.addEventListener(`pointercancel`,u)};return e.addEventListener(`pointerdown`,n),()=>e.removeEventListener(`pointerdown`,n)}function qi(e,t,n){let r=(e.closest(`.kalotyp-stage-container`)??e).getBoundingClientRect();return{x:t-r.left,y:n-r.top}}var Ji=32;function Yi(e){let{stageHost:t,utilHost:n,source:r,presets:i,presetFilter:a,store:o,viewport:s}=e,c=e.onCommit??Qi,l=zi();t.appendChild(l.container);let u=document.createElement(`div`);u.className=`kalotyp-crop-panel`;let f=tt(i,a),p=Fi(f,ea(o.get(),i,f),(e,t)=>{let n=i.indexOf(t);if(n===-1)return;let r=at(o.get(),n);o.set({rect:r.rect,aspectRatio:r.aspectRatio,activePresetIndex:n}),Ii(p.buttons,e),c()});u.appendChild(p.container);let m=Xi({initial:o.get().rect,bounds:{width:r.width,height:r.height},onCommit(e){let t=o.get(),n=S(e,{x:0,y:0,width:t.imageSize.width,height:t.imageSize.height});o.set({rect:n}),c()}});u.appendChild(m.container),n.appendChild(u);let h=d({width:1,height:1,padding:Ji},{width:r.width,height:r.height});function g(){let e=l.container.getBoundingClientRect(),t={width:e.width,height:e.height,padding:Ji},n={width:r.width,height:r.height};h=s?s.computeViewport(t,n):d(t,n)}function _(){let e=l.container.getBoundingClientRect();e.width<=0||e.height<=0||(Ci(l.imageCanvas,r.bitmap,e.width,e.height,h),v())}function v(){let e=l.container.getBoundingClientRect();e.width<=0||e.height<=0||(Ni(l.overlayCanvas,o.get().rect,e.width,e.height,h),yi({cropRectImage:o.get().rect,viewport:h,cornerAnchors:l.cornerAnchors,edgeHandles:{t:l.handles.t,r:l.handles.r,b:l.handles.b,l:l.handles.l},bodyHitArea:l.bodyHitArea}))}g(),_();let y=new ResizeObserver(()=>{g(),_()});y.observe(l.container);let b=!1,x=s?.subscribe(()=>{b||(b=!0,requestAnimationFrame(()=>{b=!1,g(),_()}))}),C=!1,w=o.subscribe((e,t)=>{ta(e,t,i,f,p.buttons),!$i(e.rect,t.rect)&&(m.sync(e.rect),!C&&(C=!0,requestAnimationFrame(()=>{C=!1,v()})))}),T=Ui({stageElement:l.container,handles:l.handles,bodyHitArea:l.bodyHitArea},o,{getViewport:()=>h,onCommit:c});return{destroy(){T.destroy(),w(),x?.(),y.disconnect(),l.container.remove(),u.remove()}}}function Xi(e){let t=document.createElement(`div`);t.className=`kalotyp-crop-dims`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,`Crop region dimensions`);let n=Zi(`Left`,e.initial.x,0,e.bounds.width),r=Zi(`Top`,e.initial.y,0,e.bounds.height),i=Zi(`Width`,e.initial.width,1,e.bounds.width),a=Zi(`Height`,e.initial.height,1,e.bounds.height);function o(){return{x:Math.round(n.input.valueAsNumber),y:Math.round(r.input.valueAsNumber),width:Math.round(i.input.valueAsNumber),height:Math.round(a.input.valueAsNumber)}}for(let t of[n,r,i,a])t.input.addEventListener(`change`,()=>{let t=o();Number.isFinite(t.x+t.y+t.width+t.height)&&e.onCommit(t)});t.appendChild(n.wrapper),t.appendChild(r.wrapper),t.appendChild(i.wrapper),t.appendChild(a.wrapper);function s(e){n.input.valueAsNumber!==e.x&&(n.input.value=String(Math.round(e.x))),r.input.valueAsNumber!==e.y&&(r.input.value=String(Math.round(e.y))),i.input.valueAsNumber!==e.width&&(i.input.value=String(Math.round(e.width))),a.input.valueAsNumber!==e.height&&(a.input.value=String(Math.round(e.height)))}return{container:t,sync:s}}function Zi(e,t,n,r){let i=document.createElement(`label`);i.className=`kalotyp-crop-dims-field`;let a=document.createElement(`span`);a.className=`kalotyp-crop-dims-label`,a.textContent=e;let o=document.createElement(`input`);return o.type=`number`,o.className=`kalotyp-crop-dims-input`,o.min=String(n),o.max=String(r),o.step=`1`,o.value=String(Math.round(t)),o.inputMode=`numeric`,o.setAttribute(`aria-label`,`${e} (pixels)`),i.appendChild(a),i.appendChild(o),{wrapper:i,input:o}}function Qi(){}function $i(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function ea(e,t,n){if(e.activePresetIndex===-1)return-1;let r=t[e.activePresetIndex];return r?n.indexOf(r):-1}function ta(e,t,n,r,i){e.activePresetIndex!==t.activePresetIndex&&Ii(i,ea(e,n,r))}var na=`crop`;function ra(e){return{id:`crop`,init(t){return it({imageSize:{width:t.source.width,height:t.source.height},presets:e.presets,filter:e.presetFilter})},mount(t,n,r){let i=Yi({stageHost:t,utilHost:e.panelHost,source:n.source,presets:e.presets,presetFilter:e.presetFilter,store:r,viewport:n.viewport,onCommit:()=>n.bus.emit(`commit`,{utility:na})});return{destroy:()=>i.destroy()}},async bake(e,t){return Qe(t,{rect:e.rect})}}}function ia(){let e=document.createElement(`div`);e.className=`kalotyp-stage-container kalotyp-preview-container`;let t=document.createElement(`canvas`);return t.className=`kalotyp-stage-image kalotyp-preview-canvas`,t.setAttribute(`aria-hidden`,`true`),e.appendChild(t),{container:e,canvas:t}}function aa(e,t,n){let r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return;let i={width:r.width,height:r.height,padding:32};return{viewport:n?n.computeViewport(i,t):d(i,t),stageWidth:r.width,stageHeight:r.height}}function oa(e,t,n,r){let i=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(t*i)),o=Math.max(1,Math.round(n*i));e.width!==a&&(e.width=a),e.height!==o&&(e.height=o),e.style.width=`${t}px`,e.style.height=`${n}px`;let s=e.getContext(`2d`);s&&(s.setTransform(i,0,0,i,0,0),s.clearRect(0,0,t,n),s.imageSmoothingEnabled=!0,s.imageSmoothingQuality=`high`,r(s))}function sa(e){let{canvas:t,sourceBitmap:n}=e,r;function i(e,i){if(e<=0||i<=0)return;let a=ca(t);if(!a)return;t.width=e,t.height=i,a.imageSmoothingEnabled=!0,a.imageSmoothingQuality=`high`,a.clearRect(0,0,e,i),a.drawImage(n,0,0,e,i);let o=a.getImageData(0,0,e,i);r={baseline:new Uint8ClampedArray(o.data),scratch:o.data,blurred:void 0,width:e,height:i}}function a(e){if(!r)return;let n=ca(t);if(!n)return;if(ut(e)){let e=new ImageData(new Uint8ClampedArray(r.baseline),r.width,r.height);n.putImageData(e,0,0);return}let i=vt(e);if(bt(r.baseline,r.scratch,i,e),e.clarity!==0){if(!r.blurred){let e=new Uint8ClampedArray(r.baseline.length),t=new Uint8ClampedArray(r.baseline.length);St(r.baseline,e,t,r.width,r.height),r.blurred=t}xt(r.scratch,r.blurred,e.clarity)}let a=new ImageData(r.scratch,r.width,r.height);n.putImageData(a,0,0)}function o(){r=void 0}return{paint:a,rebuild:i,dispose:o}}function ca(e){return e.getContext(`2d`,{willReadFrequently:!0})}function la(e){if(e.width<=0||e.height<=0)return{width:80,height:60};let t=80/e.width,n=60/e.height,r=Math.min(t,n);return{width:Math.max(1,Math.floor(e.width*r)),height:Math.max(1,Math.floor(e.height*r))}}function ua(e){let{source:t,dims:n,dpr:r}=e,i=Math.max(1,Math.round(n.width*r)),a=Math.max(1,Math.round(n.height*r)),o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`,{willReadFrequently:!0});if(!s)return{get:()=>da(n,r),dispose:()=>{}};s.imageSmoothingEnabled=!0,s.imageSmoothingQuality=`high`,s.drawImage(t,0,0,i,a);let c=s.getImageData(0,0,i,a),l={data:new Uint8ClampedArray(c.data),width:i,height:a},u=new Map;function d(e){let t=document.createElement(`canvas`);t.width=i,t.height=a,t.style.width=`${n.width}px`,t.style.height=`${n.height}px`;let r=t.getContext(`2d`);if(!r)return t;let o={data:new Uint8ClampedArray(l.data.length),width:i,height:a};return Ct(e.state,l,o),r.putImageData(new ImageData(o.data,i,a),0,0),t}return{get(e){let t=u.get(e.id);if(t)return t;let n=d(e);return u.set(e.id,n),n},dispose(){u.clear()}}}function da(e,t){let n=document.createElement(`canvas`);return n.width=Math.max(1,Math.round(e.width*t)),n.height=Math.max(1,Math.round(e.height*t)),n.style.width=`${e.width}px`,n.style.height=`${e.height}px`,n}function fa(e){let{stageHost:t,utilHost:n,source:r,store:i,viewport:a}=e,o=e.onCommit??ma,s=ia();t.appendChild(s.container);let c=sa({canvas:s.canvas,sourceBitmap:r.bitmap}),l=la({width:r.width,height:r.height}),u=Math.max(1,window.devicePixelRatio||1),d=ua({source:r.bitmap,dims:l,dpr:u}),f=pa({presets:ht,thumbnailCache:d,dims:l,onPresetClick:e=>{if(_t(i.get())?.id===e.id&&e.id!==`none`){i.update(()=>W),o();return}i.update(()=>e.state),o()}});n.appendChild(f.container);let p={width:0,height:0};function m(){let e=aa(s.container,{width:r.width,height:r.height},a);if(!e)return;let t=e.viewport.displayRect,n=Math.max(1,Math.round(t.width*u)),o=Math.max(1,Math.round(t.height*u));s.canvas.style.width=`${t.width}px`,s.canvas.style.height=`${t.height}px`,s.canvas.style.position=`absolute`,s.canvas.style.left=`${t.x}px`,s.canvas.style.top=`${t.y}px`,!(a?.getPinching()??!1)&&(p.width!==n||p.height!==o)&&(p={width:n,height:o},c.rebuild(n,o)),c.paint(i.get())}function h(e){let t=_t(e)?.id;f.setActive(t)}h(i.get()),m();let g=new ResizeObserver(()=>m());g.observe(s.container);let _=!1,v=a?.subscribe(()=>{_||(_=!0,requestAnimationFrame(()=>{_=!1,m()}))}),y=!1,b=i.subscribe(e=>{h(e),!y&&(y=!0,requestAnimationFrame(()=>{y=!1,c.paint(i.get())}))});return{destroy(){b(),v?.(),g.disconnect(),c.dispose(),d.dispose(),s.container.remove(),f.container.remove()}}}function pa(e){let t=document.createElement(`div`);t.className=`kalotyp-filter-panel`,t.setAttribute(`role`,`radiogroup`),t.setAttribute(`aria-label`,`Filter presets`);let n=document.createElement(`div`);n.className=`kalotyp-filter-strip`,t.appendChild(n);let r=new Map;for(let t of e.presets){let i=document.createElement(`button`);i.type=`button`,i.className=`kalotyp-filter-thumb`,i.dataset.presetId=t.id,i.setAttribute(`role`,`radio`),i.setAttribute(`aria-checked`,`false`),i.setAttribute(`aria-label`,`${t.label} filter`),i.title=t.label;let a=document.createElement(`span`);a.className=`kalotyp-filter-thumb-image`,a.style.width=`${e.dims.width}px`,a.style.height=`${e.dims.height}px`;let o=e.thumbnailCache.get(t);o.classList.add(`kalotyp-filter-thumb-canvas`),a.appendChild(o);let s=document.createElement(`span`);s.className=`kalotyp-filter-thumb-check`,s.setAttribute(`aria-hidden`,`true`),s.innerHTML=`✓`,a.appendChild(s);let c=document.createElement(`span`);c.className=`kalotyp-filter-thumb-label`,c.textContent=t.label,i.appendChild(a),i.appendChild(c),i.addEventListener(`click`,()=>e.onPresetClick(t)),n.appendChild(i),r.set(t.id,i)}return{container:t,setActive(e){for(let[t,n]of r){let r=t===e;n.setAttribute(`aria-checked`,r?`true`:`false`),n.classList.toggle(`kalotyp-filter-thumb--active`,r)}}}}function ma(){}function ha(e){return{id:`filter`,init:()=>W,mount(t,n,r){let i=fa({stageHost:t,utilHost:e.panelHost,source:n.source,store:r,viewport:n.viewport,onCommit:()=>n.bus.emit(`commit`,{utility:`filter`})});return{destroy:()=>i.destroy()}},bake:ga}}async function ga(e,t){return t}function _a(e){let{stageHost:t,utilHost:n,source:r,store:i,viewport:a}=e,o=e.onCommit??ba,s=ia();t.appendChild(s.container);let c=sa({canvas:s.canvas,sourceBitmap:r.bitmap}),l=va({onSliderInput:(e,t)=>i.set(dt(i.get(),e,t)),onSliderCommit:()=>o(),onNumberCommit:(e,t)=>{i.set(dt(i.get(),e,t)),o()},onRowReset:e=>{i.set(ft(i.get(),e)),o()},onResetAll:()=>{i.update(()=>pt()),o()}});n.appendChild(l.container);let u={width:0,height:0};function d(){let e=aa(s.container,{width:r.width,height:r.height},a);if(!e)return;let t=e.viewport.displayRect,n=Math.max(1,window.devicePixelRatio||1),o=Math.max(1,Math.round(t.width*n)),l=Math.max(1,Math.round(t.height*n));s.canvas.style.width=`${t.width}px`,s.canvas.style.height=`${t.height}px`,s.canvas.style.position=`absolute`,s.canvas.style.left=`${t.x}px`,s.canvas.style.top=`${t.y}px`,!(a?.getPinching()??!1)&&(u.width!==o||u.height!==l)&&(u={width:o,height:l},c.rebuild(o,l)),c.paint(i.get())}function f(e){for(let t of ct){let n=l.rows.get(t.key);if(!n)continue;let r=e[t.key];n.slider.valueAsNumber!==r&&(n.slider.valueAsNumber=r),Number.parseFloat(n.input.value||`0`)!==r&&(n.input.value=String(r))}}f(i.get()),d();let p=new ResizeObserver(()=>d());p.observe(s.container);let m=!1,h=a?.subscribe(()=>{m||(m=!0,requestAnimationFrame(()=>{m=!1,d()}))}),g=!1,_=i.subscribe(e=>{f(e),!g&&(g=!0,requestAnimationFrame(()=>{g=!1,c.paint(i.get())}))});return{destroy(){_(),h?.(),p.disconnect(),c.dispose(),s.container.remove(),l.container.remove()}}}function va(e){let t=document.createElement(`div`);t.className=`kalotyp-finetune-panel`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,`Finetune adjustments`);let n=new Map;for(let r of ct){let i=ya(r.key,r.label,e);n.set(r.key,i),t.appendChild(i.row)}let r=document.createElement(`button`);return r.type=`button`,r.className=`kalotyp-finetune-reset-all`,r.textContent=`Reset all`,r.title=`Reset every adjustment to 0`,r.addEventListener(`click`,e.onResetAll),t.appendChild(r),{container:t,rows:n,resetAllButton:r}}function ya(e,t,n){let r=document.createElement(`div`);r.className=`kalotyp-finetune-row`,r.dataset.adjustment=e;let i=document.createElement(`label`);i.className=`kalotyp-finetune-label`,i.textContent=t;let a=document.createElement(`input`);a.type=`range`,a.className=`kalotyp-finetune-slider`,a.min=String(st),a.max=`100`,a.step=`1`,a.value=`0`,a.setAttribute(`aria-label`,`${t} adjustment`),a.addEventListener(`input`,()=>n.onSliderInput(e,a.valueAsNumber)),a.addEventListener(`change`,()=>n.onSliderCommit());let o=document.createElement(`input`);o.type=`number`,o.className=`kalotyp-finetune-input`,o.min=String(st),o.max=`100`,o.step=`1`,o.value=`0`,o.inputMode=`numeric`,o.setAttribute(`aria-label`,`${t} value`),o.addEventListener(`change`,()=>{let t=o.valueAsNumber;Number.isFinite(t)&&n.onNumberCommit(e,t)});let s=document.createElement(`button`);return s.type=`button`,s.className=`kalotyp-finetune-row-reset`,s.setAttribute(`aria-label`,`Reset ${t}`),s.title=`Reset ${t}`,s.textContent=`↺`,s.addEventListener(`click`,()=>n.onRowReset(e)),r.appendChild(i),r.appendChild(a),r.appendChild(o),r.appendChild(s),{row:r,slider:a,input:o,resetButton:s}}function ba(){}function xa(e){return{id:`finetune`,init:()=>lt(),mount(t,n,r){let i=_a({stageHost:t,utilHost:e.panelHost,source:n.source,store:r,viewport:n.viewport,onCommit:()=>n.bus.emit(`commit`,{utility:`finetune`})});return{destroy:()=>i.destroy()}},bake:wt}}function Sa(e){let{stageHost:t,utilHost:n,source:r,store:i,viewport:a}=e,o=e.onCommit??(()=>{}),s=ia();t.appendChild(s.container);let c=Ca({onToggleHorizontal:()=>{i.set(Et(i.get(),`horizontal`)),o()},onToggleVertical:()=>{i.set(Et(i.get(),`vertical`)),o()}});n.appendChild(c.container);function l(){let e=aa(s.container,{width:r.width,height:r.height},a);if(!e)return;let t=i.get();oa(s.canvas,e.stageWidth,e.stageHeight,n=>{let i=e.viewport.displayRect,a=t.horizontal?-1:1,o=t.vertical?-1:1,s=i.x+i.width/2,c=i.y+i.height/2;n.translate(s,c),n.scale(a,o),n.drawImage(r.bitmap,-i.width/2,-i.height/2,i.width,i.height)})}function u(e){c.horizontalButton.setAttribute(`aria-pressed`,e.horizontal?`true`:`false`),c.verticalButton.setAttribute(`aria-pressed`,e.vertical?`true`:`false`)}u(i.get()),l();let d=new ResizeObserver(()=>l());d.observe(s.container);let f=!1,p=a?.subscribe(()=>{f||(f=!0,requestAnimationFrame(()=>{f=!1,l()}))}),m=!1,h=i.subscribe(e=>{u(e),!m&&(m=!0,requestAnimationFrame(()=>{m=!1,l()}))});return{destroy(){h(),p?.(),d.disconnect(),s.container.remove(),c.container.remove()}}}function Ca(e){let t=document.createElement(`div`);t.className=`kalotyp-flip-panel`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,`Flip`);let n=wa(`Flip horizontal`,J(`flipHorizontal`),e.onToggleHorizontal);n.classList.add(`kalotyp-flip-button-h`);let r=wa(`Flip vertical`,J(`flipVertical`),e.onToggleVertical);return r.classList.add(`kalotyp-flip-button-v`),t.appendChild(n),t.appendChild(r),{container:t,horizontalButton:n,verticalButton:r}}function wa(e,t,n){let r=document.createElement(`button`);return r.type=`button`,r.className=`kalotyp-toggle-button`,r.innerHTML=`${t}<span>${e}</span>`,r.setAttribute(`aria-pressed`,`false`),r.setAttribute(`aria-label`,e),r.addEventListener(`click`,n),r}function Ta(e){return{id:`flip`,init:()=>Tt(),mount(t,n,r){let i=Sa({stageHost:t,utilHost:e.panelHost,source:n.source,store:r,viewport:n.viewport,onCommit:()=>n.bus.emit(`commit`,{utility:`flip`})});return{destroy:()=>i.destroy()}},bake:Ot}}var Ea=32;function Da(e){let{stageHost:t,utilHost:n,source:r,store:i,viewport:a}=e,o=e.onCommit??(()=>{}),s=document.createElement(`div`);s.className=`kalotyp-stage-container kalotyp-frame-preview-container`;let c=document.createElement(`canvas`);c.className=`kalotyp-stage-image kalotyp-frame-preview-canvas`,c.setAttribute(`aria-hidden`,`true`),s.appendChild(c),t.appendChild(s);let l=i.get(),u=document.createElement(`div`);u.className=`kalotyp-frame-panel`;let f=Oa({presets:kt,initialActiveId:l.presetId,labels:e.labels,source:r,initialState:l,onPresetClick:e=>{i.update(t=>Nt(t,e.id)),o()}});u.appendChild(f.container);let p=ka({initialColor:l.color,initialPresetId:l.presetId,onColorChange:e=>{i.update(t=>Pt(t,e)),o()}});u.appendChild(p.container),n.appendChild(u);let m=d({width:1,height:1,padding:Ea},{width:r.width,height:r.height});function h(){let e=s.getBoundingClientRect();if(e.width<=0||e.height<=0)return;let t={width:e.width,height:e.height,padding:Ea},n=Kt(i.get().presetId,r.width,r.height);m=a?a.computeViewport(t,n):d(t,n)}function g(){let e=s.getBoundingClientRect();if(e.width<=0||e.height<=0)return;let t=Math.max(1,window.devicePixelRatio||1),n=Math.max(1,Math.round(e.width*t)),a=Math.max(1,Math.round(e.height*t));c.width!==n&&(c.width=n),c.height!==a&&(c.height=a),c.style.width=`${e.width}px`,c.style.height=`${e.height}px`;let o=c.getContext(`2d`);if(!o)return;o.setTransform(t,0,0,t,0,0),o.clearRect(0,0,e.width,e.height),o.imageSmoothingEnabled=!0,o.imageSmoothingQuality=`high`;let l=i.get(),u=Kt(l.presetId,r.width,r.height),d=m.displayRect.x,f=m.displayRect.y,p=m.displayRect.width,h=m.displayRect.height;if(l.presetId===`polaroid`){o.fillStyle=l.color,o.fillRect(d,f,p,h);let e=r.width*(p/u.width),t=r.height*(h/u.height),n=Math.min(r.width,r.height),i=Math.round(n*.05),a=d+i*p/u.width,s=f+i*h/u.height;o.drawImage(r.bitmap,a,s,e,t)}else o.drawImage(r.bitmap,d,f,p,h),l.presetId!==`none`&&(o.save(),o.translate(d,f),Rt(o,l.presetId,l.color,p,h),o.restore())}h(),g();let _=new ResizeObserver(()=>{h(),g()});_.observe(s);let v=!1,y=a?.subscribe(()=>{v||(v=!0,requestAnimationFrame(()=>{v=!1,h(),g()}))}),b=!1,x=i.subscribe(e=>{f.setActive(e.presetId),p.setColor(e.color),p.setEnabled(e.presetId!==`none`),!b&&(b=!0,requestAnimationFrame(()=>{b=!1,h(),g()}))});return{destroy(){x(),y?.(),_.disconnect(),s.remove(),u.remove()}}}function Oa(e){let t=document.createElement(`div`);t.className=`kalotyp-frame-strip-wrap`,t.setAttribute(`role`,`radiogroup`),t.setAttribute(`aria-label`,`Frame presets`);let n=document.createElement(`div`);n.className=`kalotyp-frame-strip`,t.appendChild(n);let r=new Map;for(let t of e.presets){let i=document.createElement(`button`);i.type=`button`,i.className=`kalotyp-frame-thumb`,i.dataset.presetId=t.id,i.setAttribute(`role`,`radio`),i.setAttribute(`aria-checked`,`false`);let a=e.labels?.[t.id]??t.label;i.setAttribute(`aria-label`,`${a} frame`),i.title=a;let o=document.createElement(`span`);o.className=`kalotyp-frame-thumb-image`;let s=Aa(t,e.source,e.initialState.color);s.classList.add(`kalotyp-frame-thumb-canvas`),o.appendChild(s);let c=document.createElement(`span`);c.className=`kalotyp-frame-thumb-check`,c.setAttribute(`aria-hidden`,`true`),c.innerHTML=`✓`,o.appendChild(c);let l=document.createElement(`span`);l.className=`kalotyp-frame-thumb-label`,l.textContent=a,i.appendChild(o),i.appendChild(l),i.addEventListener(`click`,()=>e.onPresetClick(t)),n.appendChild(i),r.set(t.id,i)}function i(e){for(let[t,n]of r){let r=t===e;n.setAttribute(`aria-checked`,r?`true`:`false`),n.classList.toggle(`kalotyp-frame-thumb--active`,r)}}return i(e.initialActiveId),{container:t,setActive:i}}function ka(e){let t=document.createElement(`div`);t.className=`kalotyp-frame-color-row`;let n=document.createElement(`span`);n.className=`kalotyp-frame-color-label`,n.textContent=`Colour`;let r=document.createElement(`input`);r.type=`color`,r.className=`kalotyp-frame-color`,r.value=ja(e.initialColor),r.setAttribute(`aria-label`,`Frame colour (visual picker)`),r.addEventListener(`change`,()=>e.onColorChange(r.value));let i=document.createElement(`input`);i.type=`text`,i.className=`kalotyp-frame-hex`,i.value=ja(e.initialColor),i.maxLength=7,i.spellcheck=!1,i.autocomplete=`off`,i.setAttribute(`aria-label`,`Frame colour hex code`),i.setAttribute(`placeholder`,`#000000`),i.addEventListener(`change`,()=>{let t=Ma(i.value.trim());t?(i.value=t,e.onColorChange(t)):i.value=r.value});let a=document.createElement(`span`);a.className=`kalotyp-frame-color-hint`,a.textContent=`Pick a frame preset to choose a colour.`,a.setAttribute(`aria-live`,`polite`),t.appendChild(n),t.appendChild(r),t.appendChild(i),t.appendChild(a);function o(e){r.disabled=!e,i.disabled=!e,a.hidden=e}function s(e){let t=ja(e);r.value!==t&&(r.value=t),i.value.toLowerCase()!==t.toLowerCase()&&(i.value=t)}return o(e.initialPresetId!==`none`),{container:t,setColor:s,setEnabled:o}}function Aa(e,t,n){let r={width:80,height:60},i=Kt(e.id,t.width,t.height),a=Math.min(r.width/i.width,r.height/i.height),o=Math.max(1,Math.floor(i.width*a)),s=Math.max(1,Math.floor(i.height*a)),c=Math.max(1,window.devicePixelRatio||1),l=document.createElement(`canvas`);l.width=Math.max(1,Math.round(o*c)),l.height=Math.max(1,Math.round(s*c)),l.style.width=`${o}px`,l.style.height=`${s}px`;let u=l.getContext(`2d`);if(!u)return l;if(u.setTransform(c,0,0,c,0,0),u.imageSmoothingEnabled=!0,u.imageSmoothingQuality=`high`,e.id===`polaroid`){u.fillStyle=n,u.fillRect(0,0,o,s);let e=Math.min(t.width,t.height),r=Math.round(e*.05/i.width*o),a=Math.round(e*.05/i.height*s),c=Math.round(t.width/i.width*o),l=Math.round(t.height/i.height*s);u.drawImage(t.bitmap,r,a,c,l)}else u.drawImage(t.bitmap,0,0,o,s),e.id!==`none`&&Rt(u,e.id,n,o,s);return l}function ja(e){if(/^#[0-9a-fA-F]{6}$/.test(e))return e;if(/^#[0-9a-fA-F]{3}$/.test(e)){let t=e[1],n=e[2],r=e[3];return`#${t}${t}${n}${n}${r}${r}`}return`#000000`}function Ma(e){let t=e.startsWith(`#`)?e.slice(1):e;if(/^[0-9a-fA-F]{6}$/.test(t))return`#${t.toLowerCase()}`;if(/^[0-9a-fA-F]{3}$/.test(t)){let e=t[0],n=t[1],r=t[2];return`#${e}${e}${n}${n}${r}${r}`.toLowerCase()}return null}function Na(e){return{id:`frame`,init:()=>jt(),mount(t,n,r){let i=Da({stageHost:t,utilHost:e.panelHost,source:n.source,store:r,viewport:n.viewport,labels:e.labels,onCommit:()=>n.bus.emit(`commit`,{utility:`frame`})});return{destroy:()=>i.destroy()}},bake:(e,t)=>It(e,t)}}var Pa=[{id:`x`,label:`Left`},{id:`y`,label:`Top`},{id:`width`,label:`Width`,min:1},{id:`height`,label:`Height`,min:1}];function Fa(e){let t=document.createElement(`div`);t.className=`kalotyp-redact-coords`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,`Selected redaction position`),t.hidden=!0;let n=null,r=new Map;for(let e of Pa){let n=document.createElement(`label`);n.className=`kalotyp-redact-coords-field`;let i=document.createElement(`span`);i.className=`kalotyp-redact-coords-label`,i.textContent=e.label;let o=document.createElement(`input`);o.type=`number`,o.className=`kalotyp-redact-coords-input`,o.dataset.field=e.id,o.step=`1`,o.inputMode=`numeric`,e.min!==void 0&&(o.min=String(e.min)),o.setAttribute(`aria-label`,`${e.label} (pixels)`),o.addEventListener(`change`,a),n.appendChild(i),n.appendChild(o),t.appendChild(n),r.set(e.id,o)}function i(e){let t=(e,t)=>{let n=r.get(e);if(!n)return;let i=String(Math.round(t));document.activeElement!==n&&n.value!==i&&(n.value=i)};t(`x`,e.x),t(`y`,e.y),t(`width`,e.width),t(`height`,e.height)}function a(){if(!n)return;let t=o(`x`),r=o(`y`),i=o(`width`),a=o(`height`);if(![t,r,i,a].every(Number.isFinite))return;let s={...n,x:t,y:r,width:i,height:a};s.x===n.x&&s.y===n.y&&s.width===n.width&&s.height===n.height||(n=s,e.onRegionChanged(s))}function o(e){let t=r.get(e);return t?Math.round(t.valueAsNumber):NaN}return{container:t,updateForRegion(e){if(!e){n=null,t.hidden=!0;return}n=e,i(e),t.hidden=!1},destroy(){t.replaceChildren(),r.clear(),t.remove()}}}var Ia=[{id:`pixelate`,label:`Pixelate`},{id:`blur`,label:`Blur`},{id:`solid`,label:`Solid fill`}];function La(e){let t=document.createElement(`div`);t.className=`kalotyp-redact-panel`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,`Redact`);let n=document.createElement(`div`);n.className=`kalotyp-redact-toolbar`,n.setAttribute(`role`,`radiogroup`),n.setAttribute(`aria-label`,`Redaction mode`);let r=new Map;for(let t of Ia){let i=document.createElement(`button`);i.type=`button`,i.className=`kalotyp-redact-mode`,i.dataset.mode=t.id,i.setAttribute(`role`,`radio`),i.setAttribute(`aria-checked`,t.id===e.initialMode?`true`:`false`),i.setAttribute(`aria-label`,`${t.label} redaction`),i.title=t.label,i.textContent=t.label,i.addEventListener(`click`,()=>e.onSelectMode(t.id)),n.appendChild(i),r.set(t.id,i)}let i=document.createElement(`div`);i.className=`kalotyp-redact-style-row`;let a=document.createElement(`input`);a.type=`color`,a.className=`kalotyp-redact-color`,a.value=Ra(e.initialColor),a.setAttribute(`aria-label`,`Solid fill colour (visual picker)`),a.addEventListener(`change`,()=>e.onColorChange(a.value));let o=document.createElement(`input`);o.type=`text`,o.className=`kalotyp-redact-hex`,o.value=Ra(e.initialColor),o.maxLength=7,o.spellcheck=!1,o.autocomplete=`off`,o.setAttribute(`aria-label`,`Solid fill hex code`),o.setAttribute(`placeholder`,`#000000`),o.addEventListener(`change`,()=>{let t=za(o.value.trim());t?(o.value=t,e.onColorChange(t)):o.value=a.value});let s=document.createElement(`button`);s.type=`button`,s.className=`kalotyp-redact-insert`,s.innerHTML=`${J(`plus`)}<span>Insert at centre</span>`,s.setAttribute(`aria-label`,`Insert redaction region at image centre`),s.title=`Insert at centre`,s.addEventListener(`click`,()=>e.onInsertAtCenter());let c=document.createElement(`button`);c.type=`button`,c.className=`kalotyp-redact-delete`,c.innerHTML=`${J(`delete`)}<span>Delete</span>`,c.setAttribute(`aria-label`,`Delete selected redaction region`),c.title=`Delete (Del)`,c.disabled=!e.canDelete,c.addEventListener(`click`,()=>e.onDeleteSelected());let l=document.createElement(`div`);l.className=`kalotyp-redact-color-group`,l.appendChild(a),l.appendChild(o);let u=document.createElement(`span`);u.className=`kalotyp-redact-color-hint`,u.textContent=`Colour applies to Solid fill only.`,u.setAttribute(`aria-live`,`polite`);let d=document.createElement(`div`);d.className=`kalotyp-redact-button-group`,d.appendChild(s),d.appendChild(c),i.appendChild(l),i.appendChild(u),i.appendChild(d),t.appendChild(n),t.appendChild(i),t.appendChild(e.coordInputs);function f(e){for(let[t,n]of r)n.setAttribute(`aria-checked`,t===e?`true`:`false`),n.classList.toggle(`kalotyp-redact-mode--active`,t===e);let t=e===`solid`;a.disabled=!t,o.disabled=!t,u.hidden=t}function p(e){let t=Ra(e);a.value!==t&&(a.value=t),o.value.toLowerCase()!==t.toLowerCase()&&(o.value=t)}function m(e){c.disabled=!e}return f(e.initialMode),{container:t,modeButtons:r,colorInput:a,hexInput:o,insertButton:s,deleteButton:c,setActiveMode:f,setColor:p,setCanDelete:m}}function Ra(e){if(/^#[0-9a-fA-F]{6}$/.test(e))return e;if(/^#[0-9a-fA-F]{3}$/.test(e)){let t=e[1],n=e[2],r=e[3];return`#${t}${t}${n}${n}${r}${r}`}return`#000000`}function za(e){let t=e.startsWith(`#`)?e.slice(1):e;if(/^[0-9a-fA-F]{6}$/.test(t))return`#${t.toLowerCase()}`;if(/^[0-9a-fA-F]{3}$/.test(t)){let e=t[0],n=t[1],r=t[2];return`#${e}${e}${n}${n}${r}${r}`.toLowerCase()}return null}function Ba(e,t,n){let r=Math.max(1,window.devicePixelRatio||1),i=Math.max(1,Math.round(t*r)),a=Math.max(1,Math.round(n*r));e.width!==i&&(e.width=i),e.height!==a&&(e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o?(o.setTransform(r,0,0,r,0,0),o.clearRect(0,0,t,n),o):null}function Va(e,t,n,r,i){let a=Ba(e,n,r);a&&(a.imageSmoothingEnabled=!0,a.imageSmoothingQuality=`high`,a.drawImage(t.bitmap,i.displayRect.x,i.displayRect.y,i.displayRect.width,i.displayRect.height))}function Ha(e,t,n,r,i,a,o){let s=Ba(e,i,a);if(!s||n.length===0)return;let c=document.createElement(`canvas`),l=Math.max(1,Math.round(o.displayRect.width)),u=Math.max(1,Math.round(o.displayRect.height));c.width=l,c.height=u;let d=c.getContext(`2d`);if(d){d.imageSmoothingEnabled=!0,d.imageSmoothingQuality=`high`,d.drawImage(t.bitmap,0,0,l,u);for(let e of n)Jt(d,c,{...e,x:e.x*o.scale,y:e.y*o.scale,width:e.width*o.scale,height:e.height*o.scale},{bitmap:c,width:l,height:u,mimeType:`image/png`});s.drawImage(c,o.displayRect.x,o.displayRect.y,l,u);for(let e of n){let t=o.displayRect.x+e.x*o.scale,n=o.displayRect.y+e.y*o.scale,i=e.width*o.scale,a=e.height*o.scale;s.save(),e.id===r?(s.strokeStyle=`rgba(99, 102, 241, 0.9)`,s.lineWidth=1.5):(s.strokeStyle=`rgba(255, 255, 255, 0.6)`,s.lineWidth=1),s.setLineDash([4,3]),s.strokeRect(t+.5,n+.5,Math.max(0,i-1),Math.max(0,a-1)),s.restore()}}}function Ua(e,t,n,r,i){let a=Ba(e,n,r);if(!a||!t)return;let o=i.displayRect.x+t.x*i.scale,s=i.displayRect.y+t.y*i.scale,c=t.width*i.scale,l=t.height*i.scale,u=o,d=s;c<0&&(u=o+c,c=-c),l<0&&(d=s+l,l=-l),a.save(),a.fillStyle=Wa(t.mode,t.color),a.fillRect(u,d,c,l),a.strokeStyle=`rgba(99, 102, 241, 0.95)`,a.lineWidth=1.5,a.setLineDash([4,3]),a.strokeRect(u+.75,d+.75,Math.max(0,c-1.5),Math.max(0,l-1.5)),a.restore()}function Wa(e,t){switch(e){case`solid`:return Ga(t,.7);case`pixelate`:return`rgba(120, 120, 120, 0.6)`;case`blur`:return`rgba(180, 200, 220, 0.45)`}}function Ga(e,t){let n=/^#([0-9a-fA-F]{6})$/.exec(e);if(!n)return e;let r=n[1];return r?`rgba(${Number.parseInt(r.slice(0,2),16)}, ${Number.parseInt(r.slice(2,4),16)}, ${Number.parseInt(r.slice(4,6),16)}, ${t})`:e}function Ka(e){let{host:t,store:n}=e,r=new Map,i=[];for(let e of Le){let n=document.createElement(`button`);n.type=`button`,n.className=`kalotyp-redact-handle`,n.dataset.direction=e,n.setAttribute(`aria-label`,Ya(e)),n.tabIndex=-1,n.style.display=`none`,r.set(e,n),t.appendChild(n),i.push(Rr(n,t=>s(e,t)))}function a(e,t){if(!e){for(let[,e]of r)e.style.display=`none`;return}let n=qa({x:e.x,y:e.y,width:e.width,height:e.height});for(let e of Le){let i=r.get(e);if(!i)continue;let a=Ja(n[e],t);i.style.display=``,i.style.left=`${a.x}px`,i.style.top=`${a.y}px`}}function o(){for(let e of i)e();for(let[,e]of r)e.remove();r.clear()}function s(t,r){let i=K(n.get());return i?{onMove(r){let a=e.toImageSpace(r),o=ze({x:i.x,y:i.y,width:i.width,height:i.height},t,a);n.update(e=>G(e,{...i,x:o.x,y:o.y,width:o.width,height:o.height}))},onCommit(){let t=K(n.get());if(t&&(t.width<0||t.height<0)){let{x:e,y:r,width:i,height:a}=t;i<0&&(e+=i,i=-i),a<0&&(r+=a,a=-a),n.update(n=>G(n,{...t,x:e,y:r,width:i,height:a}))}e.commit()},onCancel(){n.update(e=>G(e,i))}}:null}return{update:a,destroy:o}}function qa(e){let t=e.x,n=e.x+e.width,r=e.y,i=e.y+e.height,a=e.x+e.width/2,o=e.y+e.height/2;return{tl:{x:t,y:r},tr:{x:n,y:r},bl:{x:t,y:i},br:{x:n,y:i},t:{x:a,y:r},r:{x:n,y:o},b:{x:a,y:i},l:{x:t,y:o}}}function Ja(e,t){return{x:t.displayRect.x+e.x*t.scale,y:t.displayRect.y+e.y*t.scale}}function Ya(e){switch(e){case`tl`:return`Resize from top-left`;case`tr`:return`Resize from top-right`;case`bl`:return`Resize from bottom-left`;case`br`:return`Resize from bottom-right`;case`t`:return`Resize from top`;case`r`:return`Resize from right`;case`b`:return`Resize from bottom`;case`l`:return`Resize from left`}}function Xa(){let e=document.createElement(`div`);e.className=`kalotyp-redact-stage`;let t=document.createElement(`canvas`);t.className=`kalotyp-redact-image`,t.setAttribute(`aria-hidden`,`true`);let n=document.createElement(`canvas`);n.className=`kalotyp-redact-regions`,n.setAttribute(`aria-hidden`,`true`);let r=document.createElement(`canvas`);r.className=`kalotyp-redact-live`,r.setAttribute(`aria-hidden`,`true`);let i=document.createElement(`div`);i.className=`kalotyp-redact-hit`,i.setAttribute(`role`,`presentation`);let a=document.createElement(`div`);return a.className=`kalotyp-redact-handles`,a.setAttribute(`role`,`group`),a.setAttribute(`aria-label`,`Selected redaction region`),e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(i),e.appendChild(a),{container:e,imageCanvas:t,regionsCanvas:n,liveCanvas:r,hitArea:i,handlesLayer:a}}var Za=32;function Qa(e){let{stageHost:t,utilHost:n,source:r,store:i,viewport:a}=e,o=e.onCommit??(()=>{}),s=e.onAnnounce??(()=>{}),c=pn(i.get(),{width:r.width,height:r.height});c!==i.get()&&i.update(()=>c);let l=Xa();t.appendChild(l.container);let u=d({width:1,height:1,padding:Za},{width:r.width,height:r.height}),f=null;function m(){let e=l.container.getBoundingClientRect(),t={width:e.width,height:e.height,padding:Za},n={width:r.width,height:r.height};u=a?a.computeViewport(t,n):d(t,n)}function h(){let e=l.container.getBoundingClientRect();e.width<=0||e.height<=0||Va(l.imageCanvas,r,e.width,e.height,u)}function g(){let e=l.container.getBoundingClientRect();if(e.width<=0||e.height<=0)return;let t=i.get();Ha(l.regionsCanvas,r,t.regions,t.selectedId,e.width,e.height,u)}function _(){let e=l.container.getBoundingClientRect();e.width<=0||e.height<=0||Ua(l.liveCanvas,f,e.width,e.height,u)}function v(){h(),g(),_(),x.update(K(i.get()),u)}function y(e){f=e,_()}function b(e){return p(zr(l.container,e.clientX,e.clientY),u)}let x=Ka({host:l.handlesLayer,store:i,toImageSpace:b,getViewport:()=>u,commit:o}),S=Rr(l.hitArea,e=>{let t=i.get(),n=b(e),r=$a(t.regions,n);return r?(t.selectedId!==r.id&&i.update(e=>on(e,r.id)),C(r,e)):w(t,e)});function C(e,t){let n=b(t);return{onMove(t){let r=b(t),a=r.x-n.x,o=r.y-n.y;i.update(t=>G(t,{...e,x:e.x+a,y:e.y+o}))},onCommit(){o()},onCancel(){i.update(t=>G(t,e))}}}function w(e,t){let n=b(t),r=n;return{onMove(t){let i=b(t);if(t.shiftKey){let e=i.x-n.x,t=i.y-n.y,a=Math.max(Math.abs(e),Math.abs(t)),o=e===0?1:Math.sign(e),s=t===0?1:Math.sign(t);r={x:n.x+o*a,y:n.y+s*a}}else r=i;y({x:n.x,y:n.y,width:r.x-n.x,height:r.y-n.y,mode:e.currentMode,color:e.currentColor})},onCommit(){y(null);let t=dn({x:n.x,y:n.y,width:r.x-n.x,height:r.y-n.y});if(t.width<4||t.height<4)return;let{id:a,nextRegionNumber:s}=nn(e),c={id:a,x:t.x,y:t.y,width:t.width,height:t.height,mode:e.currentMode,color:e.currentColor};i.update(e=>({...rn(e,c),nextRegionNumber:s})),o()},onCancel(){y(null)}}}function T(){let e=i.get(),{id:t,nextRegionNumber:n}=nn(e),a=fn({imageSize:{width:r.width,height:r.height},mode:e.currentMode,color:e.currentColor,id:t});i.update(e=>({...rn(e,a),nextRegionNumber:n})),s(`Redaction region placed at centre. Use arrow keys to nudge, or edit coordinates below.`),requestAnimationFrame(()=>{let e=E.container.querySelector(`.kalotyp-redact-coords-input`);e?.focus(),e?.select()}),o()}let E=Fa({onRegionChanged:e=>{i.update(t=>G(t,e)),o()}}),D=i.get(),O=La({initialMode:D.currentMode,initialColor:D.currentColor,canDelete:D.selectedId!==null,coordInputs:E.container,onSelectMode:e=>{i.update(t=>{let n=sn(t,e);return n.selectedId===null?n:ln(n,n.selectedId,e)}),o()},onColorChange:e=>{i.update(t=>{let n=cn(t,e);return n.selectedId===null?n:un(n,n.selectedId,e)}),o()},onInsertAtCenter:()=>T(),onDeleteSelected:()=>{let e=i.get().selectedId;e&&(i.update(t=>an(t,e)),o())}});n.appendChild(O.container),m(),v();let k=new ResizeObserver(()=>{m(),v()});k.observe(l.container);let A=!1,j=a?.subscribe(()=>{A||(A=!0,requestAnimationFrame(()=>{A=!1,m(),v()}))}),M=i.get().regions,N=i.get().selectedId,P=i.get().currentMode,F=i.get().currentColor,I=i.subscribe(e=>{let t=e.regions!==M,n=e.selectedId!==N;t&&(M=e.regions,g()),n&&(N=e.selectedId,O.setCanDelete(e.selectedId!==null)),e.currentMode!==P&&(P=e.currentMode,O.setActiveMode(e.currentMode)),e.currentColor!==F&&(F=e.currentColor,O.setColor(e.currentColor)),x.update(K(e),u),(n||t)&&E.updateForRegion(K(e))}),L=e=>{let t=e.target;if(eo(t))return;let n=i.get();if(e.key===`Escape`){n.selectedId!==null&&(e.preventDefault(),e.stopPropagation(),i.update(e=>on(e,null)),s(`Selection cleared.`));return}if(e.key===`Delete`||e.key===`Backspace`){if(n.selectedId===null)return;e.preventDefault();let t=n.selectedId;i.update(e=>an(e,t)),o();return}if(e.key===`ArrowUp`||e.key===`ArrowDown`||e.key===`ArrowLeft`||e.key===`ArrowRight`){let t=K(n);if(!t||e.ctrlKey||e.altKey||e.metaKey)return;let r=e.shiftKey?10:1,a=e.key===`ArrowLeft`?-r:e.key===`ArrowRight`?r:0,s=e.key===`ArrowUp`?-r:e.key===`ArrowDown`?r:0;e.preventDefault(),i.update(e=>G(e,{...t,x:t.x+a,y:t.y+s})),o()}};return document.addEventListener(`keydown`,L,!0),{destroy(){document.removeEventListener(`keydown`,L,!0),S(),I(),j?.(),k.disconnect(),E.destroy(),x.destroy(),l.container.remove(),O.container.remove()}}}function $a(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r&&t.x>=r.x&&t.x<=r.x+r.width&&t.y>=r.y&&t.y<=r.y+r.height)return r}}function eo(e){if(!e)return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`?!0:e.isContentEditable===!0}function to(e){return{id:`redact`,init:e=>tn({imageSize:{width:e.source.width,height:e.source.height}}),mount(t,n,r){let i=Qa({stageHost:t,utilHost:e.panelHost,source:n.source,store:r,viewport:n.viewport,onCommit:()=>n.bus.emit(`commit`,{utility:`redact`}),onAnnounce:e=>n.bus.emit(`announce`,{message:e})});return{destroy:()=>i.destroy()}},bake:(e,t)=>qt({regions:e.regions},t)}}function no(e){let{stageHost:t,utilHost:n,source:r,store:i,viewport:a}=e,o=e.onCommit??(()=>{}),s=ia();t.appendChild(s.container);let c={width:r.width,height:r.height},l=ro({upstream:c,onWidthChange:e=>{i.set(vn(i.get(),e,c)),o()},onHeightChange:e=>{i.set(yn(i.get(),e,c)),o()},onPercentChange:e=>{i.set(bn(i.get(),e)),o()},onLockChange:e=>{i.set(xn(i.get(),e)),o()}});n.appendChild(l.container);function u(){let e=aa(s.container,c,a);e&&oa(s.canvas,e.stageWidth,e.stageHeight,t=>{let n=e.viewport.displayRect;t.drawImage(r.bitmap,n.x,n.y,n.width,n.height)})}function d(e){let t=_n(e,c);l.widthInput.valueAsNumber!==t.width&&(l.widthInput.value=String(t.width)),l.heightInput.valueAsNumber!==t.height&&(l.heightInput.value=String(t.height));let n=(e.scaleX+e.scaleY)/2,r=Math.round(n*1e3)/10;Number.parseFloat(l.percentInput.value||`0`)!==r&&(l.percentInput.value=String(r)),l.lockButton.setAttribute(`aria-pressed`,e.lockAspect?`true`:`false`),l.lockButton.setAttribute(`aria-label`,e.lockAspect?`Aspect ratio locked — click to unlock`:`Aspect ratio unlocked — click to lock`),l.lockButton.title=e.lockAspect?`Aspect ratio locked`:`Aspect ratio unlocked`,l.lockButton.innerHTML=ao(e.lockAspect),l.summary.textContent=`${t.width} × ${t.height}px (from ${c.width} × ${c.height}px)`}d(i.get()),u();let f=new ResizeObserver(()=>u());f.observe(s.container);let p=!1,m=a?.subscribe(()=>{p||(p=!0,requestAnimationFrame(()=>{p=!1,u()}))}),h=i.subscribe(e=>{d(e)});return{destroy(){h(),m?.(),f.disconnect(),s.container.remove(),l.container.remove()}}}function ro(e){let t=document.createElement(`div`);t.className=`kalotyp-resize-panel`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,`Resize`);let n=io({label:`Width (px)`,min:1,max:q,step:1,value:e.upstream.width,onChange:e.onWidthChange}),r=io({label:`Height (px)`,min:1,max:q,step:1,value:e.upstream.height,onChange:e.onHeightChange}),i=io({label:`Scale (%)`,min:1,max:1e3,step:.1,value:100,onChange:e.onPercentChange}),a=document.createElement(`button`);a.type=`button`,a.className=`kalotyp-resize-lock`,a.setAttribute(`aria-pressed`,`true`),a.setAttribute(`aria-label`,`Lock aspect ratio`),a.title=`Lock aspect ratio`,a.innerHTML=ao(!0),a.addEventListener(`click`,()=>{let t=a.getAttribute(`aria-pressed`)!==`true`;e.onLockChange(t)});let o=document.createElement(`span`);o.className=`kalotyp-resize-summary`,o.setAttribute(`aria-live`,`polite`),o.textContent=`${e.upstream.width} × ${e.upstream.height}px`,t.title=`Maximum ${q}px on either axis`;let s=document.createElement(`div`);s.className=`kalotyp-resize-row kalotyp-resize-dims`,s.appendChild(n.wrapper),s.appendChild(a),s.appendChild(r.wrapper);let c=document.createElement(`div`);return c.className=`kalotyp-resize-row`,c.appendChild(i.wrapper),c.appendChild(o),t.appendChild(s),t.appendChild(c),{container:t,widthInput:n.input,heightInput:r.input,percentInput:i.input,lockButton:a,summary:o}}function io(e){let t=document.createElement(`label`);t.className=`kalotyp-resize-field`;let n=document.createElement(`span`);n.className=`kalotyp-resize-field-label`,n.textContent=e.label;let r=document.createElement(`input`);return r.type=`number`,r.className=`kalotyp-resize-input`,r.min=String(e.min),r.max=String(e.max),r.step=String(e.step),r.value=String(e.value),r.inputMode=`numeric`,r.setAttribute(`aria-label`,e.label),r.addEventListener(`change`,()=>{let t=r.valueAsNumber;Number.isFinite(t)&&e.onChange(t)}),t.appendChild(n),t.appendChild(r),{wrapper:t,input:r}}function ao(e){return J(e?`lockClosed`:`lockOpen`)}function oo(e){return{id:`resize`,init:()=>hn(),mount(t,n,r){let i=no({stageHost:t,utilHost:e.panelHost,source:n.source,store:r,viewport:n.viewport,onCommit:()=>n.bus.emit(`commit`,{utility:`resize`})});return{destroy:()=>i.destroy()}},bake:wn}}var so=`rgba(0, 0, 0, 0.4)`,co=`rgba(255, 255, 255, 0.95)`,lo=`rgba(0, 0, 0, 0.45)`;function uo(e){let{stageHost:t,utilHost:n,source:r,store:i,viewport:a}=e,o=e.onCommit??mo,s=ia();t.appendChild(s.container);let c=fo({onCounterClockwise:()=>{i.set(Mn(i.get())),o()},onClockwise:()=>{i.set(jn(i.get())),o()},onAngleInput:e=>i.set(Nn(i.get(),e)),onAngleCommit:()=>o(),onAngleReset:()=>{i.set(Nn(i.get(),0)),o()}});n.appendChild(c.container);function l(){let e=s.container.getBoundingClientRect();if(e.width<=0||e.height<=0)return;let t=i.get(),n=Fn(t)*Math.PI/180,o=Fn(t)-t.quarterTurns*90,c=Math.abs(o)<1e-6,l=Math.abs(Math.cos(n)),u=Math.abs(Math.sin(n)),f=r.width*l+r.height*u,p=r.width*u+r.height*l,m={width:e.width,height:e.height,padding:32},h={width:f,height:p},g=a?a.computeViewport(m,h):d(m,h),_=g.displayRect,v=_.x+_.width/2,y=_.y+_.height/2,b=c?t.quarterTurns%2==0?{width:r.width,height:r.height}:{width:r.height,height:r.width}:Dn(r,n);oa(s.canvas,e.width,e.height,t=>{let i=r.width*g.scale,a=r.height*g.scale;t.save(),t.translate(v,y),t.rotate(n),t.drawImage(r.bitmap,-i/2,-a/2,i,a),t.restore();let o=b.width*g.scale,s=b.height*g.scale,l=v-o/2,u=y-s/2;c||(t.save(),t.beginPath(),t.rect(0,0,e.width,e.height),t.rect(l,u,o,s),t.clip(`evenodd`),t.fillStyle=so,t.fillRect(0,0,e.width,e.height),t.restore()),t.save(),t.lineWidth=3,t.strokeStyle=lo,t.strokeRect(l+.5,u+.5,o-1,s-1),t.lineWidth=1,t.strokeStyle=co,t.strokeRect(l+.5,u+.5,o-1,s-1),t.restore()})}function u(e){c.angleSlider.valueAsNumber!==e.freeAngle&&(c.angleSlider.valueAsNumber=e.freeAngle);let t=po(e.freeAngle);c.angleInput.value!==t&&(c.angleInput.value=t)}u(i.get()),l();let f=new ResizeObserver(()=>l());f.observe(s.container);let p=!1,m=a?.subscribe(()=>{p||(p=!0,requestAnimationFrame(()=>{p=!1,l()}))}),h=!1,g=i.subscribe(e=>{u(e),!h&&(h=!0,requestAnimationFrame(()=>{h=!1,l()}))});return{destroy(){g(),m?.(),f.disconnect(),s.container.remove(),c.container.remove()}}}function fo(e){let t=document.createElement(`div`);t.className=`kalotyp-rotate-panel`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,`Rotate`);let n=ho(`Rotate 90° counter-clockwise`,`↺`,e.onCounterClockwise),r=ho(`Rotate 90° clockwise`,`↻`,e.onClockwise),i=document.createElement(`label`);i.className=`kalotyp-rotate-slider-label`,i.textContent=`Straighten`;let a=document.createElement(`input`);a.type=`range`,a.className=`kalotyp-rotate-slider`,a.min=`-45`,a.max=`45`,a.step=String(kn),a.value=`0`,a.setAttribute(`aria-label`,`Straighten angle`),a.addEventListener(`input`,()=>e.onAngleInput(a.valueAsNumber)),a.addEventListener(`change`,()=>e.onAngleCommit());let o=document.createElement(`input`);o.type=`number`,o.className=`kalotyp-rotate-input`,o.min=`-45`,o.max=`45`,o.step=String(kn),o.value=`0`,o.setAttribute(`aria-label`,`Straighten angle in degrees`),o.addEventListener(`change`,()=>{let t=o.valueAsNumber;Number.isFinite(t)&&(e.onAngleInput(t),e.onAngleCommit())});let s=document.createElement(`span`);s.className=`kalotyp-rotate-suffix`,s.setAttribute(`aria-hidden`,`true`),s.textContent=`°`;let c=document.createElement(`button`);c.type=`button`,c.className=`kalotyp-rotate-reset`,c.textContent=`Reset`,c.addEventListener(`click`,e.onAngleReset);let l=document.createElement(`div`);l.className=`kalotyp-rotate-row`,l.appendChild(n),l.appendChild(r);let u=document.createElement(`span`);u.className=`kalotyp-rotate-input-group`,u.appendChild(o),u.appendChild(s);let d=document.createElement(`div`);return d.className=`kalotyp-rotate-row kalotyp-rotate-slider-row`,d.appendChild(i),d.appendChild(a),d.appendChild(u),d.appendChild(c),t.appendChild(l),t.appendChild(d),{container:t,angleSlider:a,angleInput:o}}function po(e){let t=Math.round(e*10)/10;return Number.isInteger(t)?String(t):t.toFixed(1)}function mo(){}function ho(e,t,n){let r=document.createElement(`button`);return r.type=`button`,r.className=`kalotyp-quarter-button`,r.setAttribute(`aria-label`,e),r.title=e,r.textContent=t,r.addEventListener(`click`,n),r}function go(e){return{id:`rotate`,init:()=>An(),mount(t,n,r){let i=uo({stageHost:t,utilHost:e.panelHost,source:n.source,store:r,viewport:n.viewport,onCommit:()=>n.bus.emit(`commit`,{utility:`rotate`})});return{destroy:()=>i.destroy()}},bake:Ln}}var Z={outputMimeChoice:`auto`,outputQuality:.85,outputStripMetadata:!0,rememberAnnotationStyle:!0,rememberFilter:!0,rememberFrame:!0,lastAnnotationColor:`#ff3b30`,lastAnnotationStrokeWidth:4,lastFilterPresetId:null,lastFramePresetId:null,lastFrameColor:`#000000`},_o=`kalotyp:prefs:v1`;function vo(e){if(typeof e==`string`)try{let t=new URL(e),n=t.pathname,r=n.indexOf(`/content/`),i=r===-1?``:n.slice(0,r);return`${t.origin}${i}`}catch{}return typeof window<`u`?window.location.origin:`default`}function yo(e){return`${_o}:${e}`}function bo(e){try{if(typeof localStorage>`u`)return Z;let t=localStorage.getItem(yo(e));return t?So(JSON.parse(t)):Z}catch{return Z}}function xo(e,t){try{if(typeof localStorage>`u`)return;let n=So(t);localStorage.setItem(yo(e),JSON.stringify(n))}catch{}}function So(e){return{outputMimeChoice:Co(e.outputMimeChoice)?e.outputMimeChoice:Z.outputMimeChoice,outputQuality:wo(e.outputQuality,0,1,Z.outputQuality),outputStripMetadata:typeof e.outputStripMetadata==`boolean`?e.outputStripMetadata:Z.outputStripMetadata,rememberAnnotationStyle:typeof e.rememberAnnotationStyle==`boolean`?e.rememberAnnotationStyle:Z.rememberAnnotationStyle,rememberFilter:typeof e.rememberFilter==`boolean`?e.rememberFilter:Z.rememberFilter,rememberFrame:typeof e.rememberFrame==`boolean`?e.rememberFrame:Z.rememberFrame,lastAnnotationColor:typeof e.lastAnnotationColor==`string`?e.lastAnnotationColor:Z.lastAnnotationColor,lastAnnotationStrokeWidth:wo(e.lastAnnotationStrokeWidth,1,40,Z.lastAnnotationStrokeWidth),lastFilterPresetId:e.lastFilterPresetId===null||typeof e.lastFilterPresetId==`string`?e.lastFilterPresetId:Z.lastFilterPresetId,lastFramePresetId:e.lastFramePresetId===null||typeof e.lastFramePresetId==`string`?e.lastFramePresetId:Z.lastFramePresetId,lastFrameColor:typeof e.lastFrameColor==`string`?e.lastFrameColor:Z.lastFrameColor}}function Co(e){return e===`auto`||e===`image/png`||e===`image/jpeg`||e===`image/webp`||e===`image/avif`}function wo(e,t,n,r){return typeof e!=`number`||!Number.isFinite(e)?r:e<t?t:e>n?n:e}var To=[{value:`auto`,label:`Auto (recommended)`},{value:`image/webp`,label:`WebP`},{value:`image/avif`,label:`AVIF`},{value:`image/jpeg`,label:`JPEG`},{value:`image/png`,label:`PNG`}];function Eo(e){let t=e.initial;function n(n){t={...t,...n},e.onChange(t)}let r=document.createElement(`div`);r.className=`kalotyp-preferences-body`;let i=document.createElement(`section`);i.className=`kalotyp-preferences-section`,i.innerHTML=`<h4>Output defaults</h4>`;let a=Do(`Format`),o=document.createElement(`select`);o.className=`kalotyp-output-format`,o.setAttribute(`aria-label`,`Default output format`);for(let e of To){let t=document.createElement(`option`);t.value=e.value,t.textContent=e.label,o.appendChild(t)}o.value=t.outputMimeChoice,o.addEventListener(`change`,()=>{n({outputMimeChoice:o.value})}),a.appendChild(o),i.appendChild(a);let s=Do(`Quality`),c=document.createElement(`input`);c.type=`range`,c.className=`kalotyp-output-quality`,c.min=`50`,c.max=`100`,c.step=`1`,c.value=String(Math.round(t.outputQuality*100)),c.setAttribute(`aria-label`,`Default output quality`),c.addEventListener(`input`,()=>{n({outputQuality:c.valueAsNumber/100}),l.textContent=String(c.valueAsNumber)});let l=document.createElement(`span`);l.className=`kalotyp-output-quality-readout`,l.textContent=String(Math.round(t.outputQuality*100)),l.setAttribute(`aria-hidden`,`true`),s.appendChild(c),s.appendChild(l),i.appendChild(s);let u=Oo(`Strip EXIF, GPS, and camera metadata on save`,t.outputStripMetadata,e=>n({outputStripMetadata:e}));i.appendChild(u);let d=document.createElement(`section`);d.className=`kalotyp-preferences-section`,d.innerHTML=`<h4>Remember across sessions</h4>`;let f=Oo(`Annotation style (colour + stroke width)`,t.rememberAnnotationStyle,e=>n({rememberAnnotationStyle:e})),p=Oo(`Last filter preset`,t.rememberFilter,e=>n({rememberFilter:e})),m=Oo(`Last frame preset`,t.rememberFrame,e=>n({rememberFrame:e}));d.appendChild(f),d.appendChild(p),d.appendChild(m);let h=document.createElement(`footer`);h.className=`kalotyp-preferences-footer`;let g=document.createElement(`button`);g.type=`button`,g.className=`kalotyp-preferences-reset`,g.textContent=`Reset to defaults`,g.addEventListener(`click`,()=>{t={...Z},e.onChange(t),y(t)});let _=document.createElement(`button`);_.type=`button`,_.className=`kalotyp-preferences-done`,_.textContent=`Done`,_.addEventListener(`click`,()=>v.close()),h.appendChild(g),h.appendChild(_),r.appendChild(i),r.appendChild(d),r.appendChild(h);let v=Hn({host:e.host,title:`Preferences`,body:r,variant:`kalotyp-preferences-modal`,showCloseButton:!0,onClose:e.onClose});function y(e){o.value=e.outputMimeChoice,c.value=String(Math.round(e.outputQuality*100)),l.textContent=String(Math.round(e.outputQuality*100)),ko(u,e.outputStripMetadata),ko(f,e.rememberAnnotationStyle),ko(p,e.rememberFilter),ko(m,e.rememberFrame)}return{close:()=>v.close()}}function Do(e){let t=document.createElement(`div`);t.className=`kalotyp-output-row`;let n=document.createElement(`span`);return n.className=`kalotyp-output-row-label`,n.textContent=e,t.appendChild(n),t}function Oo(e,t,n){let r=document.createElement(`label`);r.className=`kalotyp-preferences-toggle`;let i=document.createElement(`input`);i.type=`checkbox`,i.checked=t,i.addEventListener(`change`,()=>n(i.checked));let a=document.createElement(`span`);return a.textContent=e,r.appendChild(i),r.appendChild(a),r}function ko(e,t){let n=e.querySelector(`input[type="checkbox"]`);n&&n.checked!==t&&(n.checked=t)}var Ao=0;function jo(e){let t=`kalotyp-editor-${++Ao}`,n=`${t}-title`,r=document.createElement(`div`);r.className=`pintura-editor kalotyp-editor`,r.id=t,r.setAttribute(`role`,`dialog`),r.setAttribute(`aria-modal`,`true`),r.setAttribute(`aria-labelledby`,n),r.tabIndex=-1;let i=document.createElement(`h2`);i.id=n,i.className=`kalotyp-visually-hidden`,i.textContent=`Image editor`;let a=document.createElement(`div`);a.className=`PinturaModal kalotyp-modal`;let o=document.createElement(`button`);o.type=`button`,o.title=`Close`,o.setAttribute(`aria-label`,`Close image editor`),o.className=`kalotyp-button-close`,o.innerHTML=J(`close`);let s=document.createElement(`button`);s.type=`button`,s.title=`Preferences`,s.setAttribute(`aria-label`,`Open editor preferences`),s.setAttribute(`aria-haspopup`,`dialog`),s.className=`kalotyp-button-prefs`,s.innerHTML=J(`settings`);let c=document.createElement(`div`);c.className=`kalotyp-root`,c.setAttribute(`data-env`,`landscape has-navigation`);let l=document.createElement(`div`);l.className=`kalotyp-main`;let u=document.createElement(`div`);u.className=`kalotyp-stage`,u.setAttribute(`role`,`region`),u.setAttribute(`aria-label`,`Image preview`);let d=document.createElement(`div`);d.id=`${t}-panel`,d.className=`kalotyp-util-main`,d.setAttribute(`role`,`tabpanel`),d.setAttribute(`tabindex`,`0`);let f=document.createElement(`div`);f.className=`kalotyp-nav-tools`;let p=document.createElement(`div`);p.className=`kalotyp-util-footer`;let m=document.createElement(`div`);m.className=`kalotyp-export-group`;let h=document.createElement(`button`);h.type=`button`,h.className=`kalotyp-button-export`;let g=document.createElement(`span`);g.className=`kalotyp-button-inner`,g.textContent=e.exportLabel,h.appendChild(g);let _=document.createElement(`button`);_.type=`button`,_.className=`kalotyp-button-output-settings`,_.title=`Output settings`,_.setAttribute(`aria-label`,`Output settings (format and quality)`),_.setAttribute(`aria-haspopup`,`dialog`),_.setAttribute(`aria-expanded`,`false`),_.innerHTML=J(`chevronDown`),m.appendChild(h),m.appendChild(_),p.appendChild(m);let v=document.createElement(`div`);return v.className=`kalotyp-visually-hidden`,v.setAttribute(`role`,`status`),v.setAttribute(`aria-live`,`polite`),v.setAttribute(`aria-atomic`,`true`),l.appendChild(u),l.appendChild(d),c.appendChild(f),c.appendChild(l),c.appendChild(p),a.appendChild(i),a.appendChild(s),a.appendChild(o),a.appendChild(c),a.appendChild(v),r.appendChild(a),{editor:r,modal:a,root:c,main:l,stage:u,navTools:f,utilMain:d,utilFooter:p,closeButton:o,prefsButton:s,exportButton:h,outputSettingsButton:_,liveRegion:v,titleId:n}}function Mo(e){let t=jo({exportLabel:e.exportLabel}),n=()=>e.onExportClick(),r=()=>e.onCloseClick(),i=()=>e.onOutputSettingsClick(),a=()=>e.onPrefsClick();t.exportButton.addEventListener(`click`,n),t.closeButton.addEventListener(`click`,r),t.outputSettingsButton.addEventListener(`click`,i),t.prefsButton.addEventListener(`click`,a),e.host.appendChild(t.editor);let o=!1;function s(e){o=!o,t.liveRegion.textContent=o?`${e} `:e}return{editor:t.editor,modal:t.modal,root:t.root,exportButton:t.exportButton,outputSettingsButton:t.outputSettingsButton,prefsButton:t.prefsButton,closeButton:t.closeButton,stage:t.stage,utilMain:t.utilMain,navTools:t.navTools,announce:s,destroy(){t.exportButton.removeEventListener(`click`,n),t.closeButton.removeEventListener(`click`,r),t.outputSettingsButton.removeEventListener(`click`,i),t.prefsButton.removeEventListener(`click`,a),t.editor.remove()}}}var No=[[void 0,`Custom`],[1,`Square`],[2,`2:1`],[1.5,`3:2`],[4/3,`4:3`],[1.6,`16:10`],[16/9,`16:9`],[.5,`1:2`],[2/3,`2:3`],[.75,`3:4`],[10/16,`10:16`],[9/16,`9:16`]];async function Po(e){return e instanceof File?e:e instanceof Blob?new File([e],`kalotyp-image.png`,{type:e.type||`image/png`}):Fo(e)}async function Fo(e){let t=new URL(e,typeof window<`u`?window.location.href:`http://localhost`),n=await fetch(t.href,{credentials:`omit`,mode:`cors`});if(!n.ok)throw Error(`Source fetch failed: ${n.status} ${n.statusText}`);let r=await n.blob(),i=Io(t,r.type);return new File([r],i,{type:r.type||`application/octet-stream`})}function Io(e,t){let n=e.pathname.split(`/`).pop();return n&&/\.[a-z0-9]{2,5}$/i.test(n)?n:`kalotyp-image.${t.split(`/`)[1]??`bin`}`}var Lo={sourceToFile:Po,loadImage:s,encodeSourceImage:se,createCropPlugin:ra,createRotatePlugin:go,createFlipPlugin:Ta,createFinetunePlugin:xa,createFilterPlugin:ha,createAnnotatePlugin:vi,createRedactPlugin:to,createResizePlugin:oo,createFramePlugin:Na,runUtilityChain:fe},Ro=[{id:`crop`,label:`Crop`},{id:`rotate`,label:`Rotate`},{id:`flip`,label:`Flip`},{id:`filter`,label:`Filter`},{id:`finetune`,label:`Finetune`},{id:`annotate`,label:`Annotate`},{id:`redact`,label:`Redact`},{id:`resize`,label:`Resize`},{id:`frame`,label:`Frame`}];function zo(e,t=Lo){let n=new b,r=new b,i=new g,a=Jo(e),o=document.createElement(`div`);o.dataset.kalotypHost=``,document.body.appendChild(o);let s=!1,c=!1,l=vo(e.src),u=bo(l),d;function f(){d!==void 0&&clearTimeout(d),d=setTimeout(()=>{d=void 0,xo(l,u)},250)}function p(e){u={...u,...e},f()}let m=Rn({mimeChoice:u.outputMimeChoice,quality:u.outputQuality,stripMetadata:u.outputStripMetadata});m.subscribe(e=>{p({outputMimeChoice:e.mimeChoice,outputQuality:e.quality,outputStripMetadata:e.stripMetadata})});let h=null,_=null,v=null,y={slots:new Map,sourceImage:void 0,sourceName:void 0,sourceFile:void 0,active:void 0,statusElement:void 0,history:void 0,committedChain:[],workingImage:void 0},x=Mo({host:o,exportLabel:a,onExportClick:()=>{ne()},onCloseClick:()=>{A()},onOutputSettingsClick:()=>{R()},onPrefsClick:()=>{te()}}),S=Go(e),C=Yn(Ro,S,e=>{j(e)},{panelId:x.utilMain.id});for(let e of C.buttons.values())e.disabled=!0;x.navTools.appendChild(C.container);let w=Zo({onUndo:()=>P(),onRedo:()=>F()});w.undoButton.disabled=!0,w.redoButton.disabled=!0,x.modal.appendChild(w.container),x.exportButton.disabled=!0,Ko(x.stage,`Loading image…`,y);let T=Qn({host:x.editor,initialFocus:x.editor});x.announce(`Image editor opened. Use Tab to navigate.`),Bo(x,e,y,t,C,S,r,i).then(()=>{x.exportButton.disabled=!1;for(let e of C.buttons.values())e.disabled=!1;qo(y),N(),Yo(y,u,p);let e=y.sourceImage?.width??0,t=y.sourceImage?.height??0;x.announce(`Image loaded. ${e} by ${t} pixels.`)},e=>{let t=e instanceof Error?e.message:`Failed to load image`;n.emit(`loaderror`,{message:t,cause:e}),Ko(x.stage,t,y),x.announce(`Failed to load image. ${t}`)});let E=r.on(`commit`,()=>{c||y.history&&(y.history.commit($(y)),N())}),D=r.on(`announce`,({message:e})=>{x.announce(e)}),O=Qo({onUndo:()=>P(),onRedo:()=>F(),onEscape:()=>k(),onCheatsheet:()=>ee()});function k(){ie||(y.history?.canUndo()??!1)&&!window.confirm(`You have unsaved changes. Discard them and close?`)||A()}function A(){let t=e.willClose;return!t||t()?(ae(),!0):!1}async function j(e){if(!y.sourceImage||y.active?.id===e)return;let t=y.slots.get(e);if(!t)return;M()&&await Uo(y,r,i),y.active?.handle.destroy(),y.active=void 0,Xn(C,e,x.utilMain),i.resetPan();let n={source:y.workingImage??y.sourceImage,bus:r,viewport:i};y.active={id:e,handle:t.plugin.mount(x.stage,n,t.store)},y.history&&(y.history.commit($(y)),N())}function M(){if(!y.active)return!1;let e=y.active.id,t=e===`filter`?`finetune`:e,n=y.slots.get(t);return n?!Ho(t,n.store.get()):!1}function N(){w.undoButton.disabled=!y.history?.canUndo(),w.redoButton.disabled=!y.history?.canRedo()}function P(){if(!y.history)return;let e=y.history.undo($(y));e&&I(e)}function F(){if(!y.history)return;let e=y.history.redo($(y));e&&I(e)}async function I(e){c=!0;try{let n=e.snapshot.get(Vo);n!==void 0&&(y.committedChain=n.map(e=>({id:e.id,state:e.state})),await Wo(y,t));for(let[t,n]of e.snapshot){if(t===Vo)continue;let e=y.slots.get(t);e&&e.store.update(()=>n)}}finally{c=!1}N();let n=y.active?.id;if(n){let e=y.slots.get(n);if(e&&y.workingImage){y.active?.handle.destroy();let t={source:y.workingImage,bus:r,viewport:i};y.active={id:n,handle:e.plugin.mount(x.stage,t,e.store)}}}if(n&&e.changed.has(n))return;let a=L(e.changed);a&&a!==n&&await j(a)}function L(e){for(let t of Ro)if(e.has(t.id))return t.id}function R(){if(h){h.close();return}h=Cr({host:x.editor,anchor:x.outputSettingsButton,store:m,canSave:()=>!s&&!x.exportButton.disabled,onSaveAndClose:()=>{h?.close(),ne()},onClose:()=>{h=null}})}function ee(){if(v){v.close();return}v=qn({host:x.editor,onClose:()=>{v=null}})}function te(){if(_){_.close();return}_=Eo({host:x.editor,initial:u,onChange:e=>{u=e,m.set({mimeChoice:e.outputMimeChoice,quality:e.outputQuality,stripMetadata:e.outputStripMetadata}),f()},onClose:()=>{_=null}})}async function ne(){if(!s&&!(!y.sourceImage||y.slots.size===0)){s=!0;try{let e=y.workingImage??y.sourceImage,r=e,i=y.active;if(i){let t=y.slots.get(i.id);if(t){let n=t.store.get();Ho(i.id,n)||(r=await t.plugin.bake(n,e))}}let a={output:m.get(),...y.sourceName?{sourceName:y.sourceName}:{},...y.sourceFile?{sourceBlob:y.sourceFile}:{}},o=await t.encodeSourceImage(r,a);n.emit(`process`,{dest:o}),x.announce(`Image saved.`),ae()}catch(e){let t=e instanceof Error?e.message:`Failed to export image`;n.emit(`loaderror`,{message:t,cause:e}),x.announce(`Save failed. ${t}`)}finally{s=!1}}}let re=Bn(x.stage,i),ie=!1;function ae(){ie||(ie=!0,h?.close(),h=null,_?.close(),_=null,v?.close(),v=null,d!==void 0&&(clearTimeout(d),d=void 0,xo(l,u)),y.active?.handle.destroy(),E(),D(),O(),re(),i.clear(),T.release(),x.destroy(),o.remove(),n.clear(),r.clear())}return{on(e,t){n.on(e,t)},off(e,t){n.off(e,t)}}}async function Bo(e,t,n,r,i,a,o,s){let c=await r.sourceToFile(t.src),l=await r.loadImage(c),u={bitmap:l.element,width:l.width,height:l.height,mimeType:c.type||`image/png`},d=t.cropSelectPresetOptions??No,f=t.cropSelectPresetFilter,p=r.createCropPlugin({presets:d,presetFilter:f,panelHost:e.utilMain}),m=r.createRotatePlugin({panelHost:e.utilMain}),h=r.createFlipPlugin({panelHost:e.utilMain}),g=r.createFinetunePlugin({panelHost:e.utilMain}),_=r.createFilterPlugin({panelHost:e.utilMain}),v=r.createAnnotatePlugin({panelHost:e.utilMain}),y=r.createRedactPlugin({panelHost:e.utilMain}),b=r.createResizePlugin({panelHost:e.utilMain}),x=r.createFramePlugin({panelHost:e.utilMain,labels:Xo(t)}),S={source:u,bus:o,viewport:s};Q(n,p,S),Q(n,m,S),Q(n,h,S),Q(n,g,S);let C=n.slots.get(`finetune`);C&&n.slots.set(`filter`,{id:`filter`,plugin:_,store:C.store}),Q(n,v,S),Q(n,y,S),Q(n,b,S),Q(n,x,S),n.sourceImage=u,n.sourceName=c.name,n.sourceFile=c,n.workingImage=u,n.committedChain=[],n.history=new w($(n));let T=n.slots.get(a);if(!T)return;let E={source:n.workingImage,bus:o,viewport:s};n.active={id:a,handle:T.plugin.mount(e.stage,E,T.store)},Xn(i,a,e.utilMain)}function Q(e,t,n){let r=Rn(t.init(n));e.slots.set(t.id,{id:t.id,plugin:t,store:r})}var Vo=`__committedChain__`;function $(e){let t=new Map;for(let[n,r]of e.slots)t.set(n,r.store.get());return t.set(Vo,e.committedChain),t}function Ho(e,t){switch(e){case`crop`:{let e=t;return!e.rect||!e.imageSize?!1:e.rect.x===0&&e.rect.y===0&&e.rect.width===e.imageSize.width&&e.rect.height===e.imageSize.height}case`rotate`:{let e=t;return typeof e.quarterTurns!=`number`||typeof e.freeAngle!=`number`?!1:Pn(e)}case`flip`:{let e=t;return typeof e.horizontal!=`boolean`||typeof e.vertical!=`boolean`?!1:Dt(e)}case`finetune`:case`filter`:{let e=t;return e?ut(e):!1}case`annotate`:{let e=t.shapes;return Array.isArray(e)&&e.length===0}case`redact`:{let e=t.regions;return Array.isArray(e)&&e.length===0}case`resize`:{let e=t;return typeof e.scaleX!=`number`||typeof e.scaleY!=`number`?!1:gn(e)}case`frame`:{let e=t;return e.presetId?Mt(e):!1}default:return!0}}async function Uo(e,t,n){if(!e.active||!e.workingImage)return;let r=e.active.id,i=r===`filter`?`finetune`:r,a=e.slots.get(i);if(!a)return;let o=a.store.get();if(Ho(i,o))return;e.workingImage=await a.plugin.bake(o,e.workingImage),e.committedChain.push({id:a.id,state:structuredClone(o)});let s={source:e.workingImage,bus:t,viewport:n},c=a.plugin.init(s);a.store.update(()=>c)}async function Wo(e,t){if(!e.sourceImage)return;let n=[];for(let t of e.committedChain){let r=e.slots.get(t.id);r&&n.push({id:t.id,plugin:r.plugin,state:t.state})}if(n.length===0){e.workingImage=e.sourceImage;return}e.workingImage=await t.runUtilityChain(n,e.sourceImage)}function Go(e){let t=e.util;if(typeof t!=`string`)return`crop`;for(let e of Ro)if(e.id===t)return e.id;return`crop`}function Ko(e,t,n){qo(n);let r=document.createElement(`div`);r.className=`kalotyp-stage-status`,r.setAttribute(`role`,`status`),r.textContent=t,e.appendChild(r),n.statusElement=r}function qo(e){e.statusElement?.remove(),e.statusElement=void 0}function Jo(e){let t=e.locale?.labelButtonExport;return typeof t==`string`&&t.length>0?t:`Save and close`}function Yo(e,t,n){if(t.rememberAnnotationStyle){let r=e.slots.get(`annotate`);if(r){let e=r.store;e.update(e=>({...e,currentStyle:{...e.currentStyle,color:t.lastAnnotationColor,strokeWidth:t.lastAnnotationStrokeWidth}})),e.subscribe(e=>{n({lastAnnotationColor:e.currentStyle.color,lastAnnotationStrokeWidth:e.currentStyle.strokeWidth})})}}if(t.rememberFilter&&t.lastFilterPresetId!==null){let n=e.slots.get(`finetune`),r=ht.find(e=>e.id===t.lastFilterPresetId);n&&r&&n.store.update(()=>r.state)}if(t.rememberFilter){let t=e.slots.get(`finetune`);t&&t.store.subscribe(e=>{n({lastFilterPresetId:_t(e)?.id??null})})}if(t.rememberFrame){let r=e.slots.get(`frame`);if(r){let e=r.store;t.lastFramePresetId&&e.update(()=>({presetId:t.lastFramePresetId,color:t.lastFrameColor})),e.subscribe(e=>{n({lastFramePresetId:e.presetId,lastFrameColor:e.color})})}}}function Xo(e){let t=e.frameOptions;if(!Array.isArray(t))return;let n=e.locale??{},r={};for(let e of t){if(!Array.isArray(e))continue;let[t,i]=e,a=t===void 0?`none`:t;try{let e=i(n);typeof e==`string`&&e.length>0&&(r[a]=e)}catch{}}return Object.keys(r).length===0?void 0:r}function Zo(e){let t=document.createElement(`div`);t.className=`kalotyp-history-controls`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,`Edit history`);let n=document.createElement(`button`);n.type=`button`,n.className=`kalotyp-history-button kalotyp-history-undo`,n.setAttribute(`aria-label`,`Undo`),n.title=`Undo (Ctrl+Z)`,n.innerHTML=J(`undo`),n.addEventListener(`click`,e.onUndo);let r=document.createElement(`button`);return r.type=`button`,r.className=`kalotyp-history-button kalotyp-history-redo`,r.setAttribute(`aria-label`,`Redo`),r.title=`Redo (Ctrl+Shift+Z)`,r.innerHTML=J(`redo`),r.addEventListener(`click`,e.onRedo),t.appendChild(n),t.appendChild(r),{container:t,undoButton:n,redoButton:r}}function Qo(e){let t=t=>{if(t.key===`Escape`){t.preventDefault(),e.onEscape();return}let n=t.target;if(!$o(n)){if(t.key===`?`&&!t.ctrlKey&&!t.metaKey&&!t.altKey){t.preventDefault(),e.onCheatsheet();return}if(t.ctrlKey||t.metaKey){if(t.key===`z`||t.key===`Z`){t.preventDefault(),t.shiftKey?e.onRedo():e.onUndo();return}(t.key===`y`||t.key===`Y`)&&(t.preventDefault(),e.onRedo())}}};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)}function $o(e){if(!e)return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`?!0:e.isContentEditable===!0}function es(e=globalThis){let t=e.pintura;t&&typeof t==`object`||Object.defineProperty(e,"pintura",{value:{openDefaultEditor:zo},writable:!0,configurable:!0,enumerable:!0})}typeof window<`u`&&es(globalThis),e.openDefaultEditor=zo});