@yuzhouu/canvas-kit 0.1.21 → 0.1.22

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/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- function e(e){return e}function t(e){return Object.freeze({id:e,kind:"api"})}function n(e,t){return e.require(t)}function s(e){zt(()=>{const t=e.current;if(!t)return;const n=t.closest("[data-canvas-kit]"),s=e=>{!e.ctrlKey&&((e,t)=>{let n=e instanceof Element?e:e instanceof Node?e.parentElement:null;for(;n&&t.contains(n);){if(n instanceof HTMLElement&&o(n))return!0;if(n===t)break;n=n.parentElement}return!1})(e.target,t)||Ot(e,t,n??void 0)&&(e.preventDefault(),e.stopPropagation())};return t.addEventListener("wheel",s,{passive:!1}),()=>{t.removeEventListener("wheel",s)}},[e])}function o(e){const{overflowY:t}=window.getComputedStyle(e);return e.scrollHeight>e.clientHeight&&("auto"===t||"scroll"===t||"overlay"===t)}function r({children:e}){const[t,n]=Vt(null),s=jt(e=>{n(e)},[]),o=qt(()=>({registerTarget:s,target:t}),[s,t]);
1
+ function e(e){return e}function t(e){return Object.freeze({id:e,kind:"api"})}function n(e,t){return e.require(t)}function s(e){zt(()=>{const t=e.current;if(!t)return;const n=t.closest("[data-canvas-kit]"),s=e=>{!e.ctrlKey&&((e,t)=>{let n=e instanceof Element?e:e instanceof Node?e.parentElement:null;for(;n&&t.contains(n);){if(n instanceof HTMLElement&&o(n))return!0;if(n===t)break;n=n.parentElement}return!1})(e.target,t)||$t(e,t,n??void 0)&&(e.preventDefault(),e.stopPropagation())};return t.addEventListener("wheel",s,{passive:!1}),()=>{t.removeEventListener("wheel",s)}},[e])}function o(e){const{overflowY:t}=window.getComputedStyle(e);return e.scrollHeight>e.clientHeight&&("auto"===t||"scroll"===t||"overlay"===t)}function r({children:e}){const[t,n]=Vt(null),s=jt(e=>{n(e)},[]),o=qt(()=>({registerTarget:s,target:t}),[s,t]);
2
2
  return Xt(Qt.Provider,{value:o,children:e})}function i(){const{registerTarget:e}=l(),t=Ut(null);return s(t),Xt("div",{ref:jt(n=>{t.current=n,e(n)},[e]),className:"land-canvas__floating-portal-host","data-ui":"canvas-kit-floating-portal-host"})}function a(){return l().target}function c(){return Kt(Qt)?.target??void 0}function l(){const e=Kt(Qt);if(!e)throw new Error("CanvasKit floating content must be rendered inside CanvasKitRoot.");return e}function d({canvas:e,children:t}){
3
- return Xt(en.Provider,{value:e,children:t})}function u(){const e=Kt(en);if(!e)throw new Error("useCanvasKit must be used inside CanvasKitProvider.");return e}function p(e){return Yt(e.subscribe,e.getSnapshot,e.getSnapshot)}function h({contributions:e,getHostElement:t,isEditing:n,onError:s,screenToPage:o}){return zt(()=>{const r=o=>{if(!y(t(),o)||n()||Lt(o.target))return;const r=w({source:"clipboard",dataTransfer:o.clipboardData});f(e,r)&&(o.preventDefault(),g(e,r).catch(e=>{s(new Error("Canvas clipboard import failed.",{cause:e}))}))},i=s=>{!y(t(),s)||n()||Lt(s.target)||m(e,v(s.dataTransfer))&&(s.preventDefault(),s.dataTransfer&&(s.dataTransfer.dropEffect="copy"))},a=r=>{const i=y(t(),r);if(!i||n()||Lt(r.target))return;const a=m(e,v(r.dataTransfer)),c=w({source:"drop",dataTransfer:r.dataTransfer,pagePoint:o(Bt(r,i))});f(e,c)?(r.preventDefault(),g(e,c).catch(e=>{s(new Error("Canvas drop import failed.",{cause:e}))})):a&&(r.preventDefault(),r.dataTransfer&&(r.dataTransfer.dropEffect="none"))};return window.addEventListener("paste",r),window.addEventListener("dragover",i),window.addEventListener("drop",a),()=>{window.removeEventListener("paste",r),window.removeEventListener("dragover",i),window.removeEventListener("drop",a)}},[e,t,n,s,o]),null}function f(e,t){return e.some(e=>e.accepts(t))}function m(e,t){return e.some(e=>e.acceptsPreview?.(t)??!1)}async function g(e,t){for(const n of e)if(n.accepts(t)&&"handled"===await n.import(t))return"handled";return"ignored"}function v(e){return e?{source:"drop",dataTypes:Array.from(e.types),fileTypes:Array.from(e.items).filter(e=>"file"===e.kind).map(e=>e.type).filter(Boolean)}:{source:"drop",dataTypes:[],fileTypes:[]}}function w({dataTransfer:e,pagePoint:t,source:n}){const s=e?.getData("text/plain")||void 0,o=e?.getData("text/html")||void 0,r=[...(e?.getData("text/uri-list")||void 0)?.split(/\r?\n/).filter(e=>e&&!e.startsWith("#"))??[],...s&&S(s.trim())?[s.trim()]:[]];return{source:n,files:b(e),text:s,html:o,...r.length>0?{urls:r}:{},pagePoint:t}}function y(e,t){if(!e)return null;const n=(t.target instanceof Element?t.target:document.activeElement)?.closest(Rt);return n instanceof HTMLElement&&e.contains(n)?n:null}function b(e){if(!e)return[];const t=Array.from(e.files);return t.length>0?t:Array.from(e.items).flatMap(e=>{if("file"!==e.kind)return[];const t=e.getAsFile();return t?[t]:[]})}function S(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return e.startsWith("data:image/")}}function x({bindings:e,getHostElement:t,onError:n}){const s=u(),o=p(s.viewport.grid.state),{editor:r,importContributions:i,renderBindings:a,setContextMenu:c}=e,l=jt(()=>s.tools.state.getSnapshot().isEditing,[s]),d=jt(e=>r.viewport.screenToPage(e),[r]);
4
- return Jt(_t,{children:[Xt($t.Provider,{value:r,children:Xt(Ft,{onContextMenuRequest:c,renderBindings:a,showGrid:o})}),Xt(h,{contributions:i,getHostElement:t,isEditing:l,onError:n,screenToPage:d})]})}function E(e){let t=e.target;return e.repeat||e.isComposing||t!==e.currentTarget&&t.matches("[contenteditable],input,select,textarea")}function C(e,t){return"function"==typeof e.getModifierState&&(e.getModifierState(t)||on.includes(t)&&e.getModifierState("AltGraph"))}function I(e){return e.trim().split(" ").map(e=>{let t=e.split(/(?<=\w|\])\+/),n=t.pop(),s=n.match(/^\((.+)\)$/),o=s?new RegExp(`^(?:${s[1]})$`,"iv"):n,r=[],i=[];for(const a of t){let e=a.match(/^\[(.*)\]$/),t=e?.[1]??a;t="$mod"===t?sn:t,e?i.push(t):r.push(t)}return[r,i,o]})}function k(e,[t,n,s]){const o=t.includes("AltGraph");return!((s instanceof RegExp?!s.test(e.key)&&!s.test(e.code):s.toUpperCase()!==e.key.toUpperCase()&&s!==e.code)||t.find(t=>!C(e,t))||tn.find(r=>!t.includes(r)&&!n.includes(r)&&s!==r&&C(e,r)&&!(o&&on.includes(r))))}function P(e){const t="string"==typeof e?{key:e}:e;return[...[t.accelKey&&"$mod",t.ctrlKey&&"Control",t.metaKey&&"Meta",t.altKey&&"Alt",t.shiftKey&&"Shift"].filter(Boolean)," "===t.key?"Space":t.key].join("+")}function T(e){const t="undefined"!=typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),n={Control:t?"⌃":"Ctrl",Meta:t?"⌘":"Win",Alt:t?"⌥":"Alt",Shift:t?"⇧":"Shift",Backspace:t?"⌫":"Backspace",Delete:"Del",Escape:"Esc",ArrowUp:"↑",ArrowDown:"↓",ArrowLeft:"←",ArrowRight:"→",Equal:"=",Minus:"-",BracketLeft:"[",BracketRight:"]",Slash:"/",Space:"Space"};return I(P(e)).map(([e,,s])=>[...e,String(s)].map(e=>n[e]??e.replace(/^(Key|Digit)(?=\w$)/,"").toUpperCase()).join(t?"":"+")).join(" ")}function A(e){return void 0===e?[]:Array.isArray(e)?e:[e]}function R(e,t){if(!t||0===Object.keys(t).length)return e;const n=new Set(Object.keys(t)),s=e.map(e=>{if(!Object.prototype.hasOwnProperty.call(t,e.id))return e;n.delete(e.id);const s=t[e.id];return{...e,shortcut:s??void 0}});if(n.size>0)throw new Error(`Unknown CanvasAction shortcut override ids: ${[...n].join(", ")}.`);return s}function L(e,t){if(e.api&&!t?.api)throw new Error(`Canvas plugin "${e.id}" declares API "${e.api.id}" but setup returned no API value.`);if(!e.api&&t?.api)throw new Error(`Canvas plugin "${e.id}" returned an API value without declaring an API token.`)}function M(e,t){return new Set((e.requires??[]).flatMap(e=>{const n=t.get(e.id);return n?.api?[n.api.id]:[]}))}function D(e,t){const n=new Set;for(const s of e){if(n.has(s))throw new Error(`Duplicate ${t} id: ${s}.`);n.add(s)}}function O(e){return"provider"===e.kind}function F(e){return"svg-inliner"===e.kind}function B(e,t){const n=new Set;for(const s of e){if(n.has(s))throw new Error(`Duplicate ${t}: ${s}.`);n.add(s)}}function $(){if("undefined"!=typeof window&&"function"==typeof window.requestAnimationFrame&&"function"==typeof window.cancelAnimationFrame)return{requestFrame:e=>window.requestAnimationFrame(e),cancelFrame:e=>window.cancelAnimationFrame(e),prefersReducedMotion:()=>"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}}function N(e){return{id:e.id,name:e.name,index:e.index,meta:{...e.meta}}}function H(e){return{id:e?.id??"document:main",meta:{...e?.meta??{}}}}function j(e,t){return{id:e.id,type:e.type,subType:e.subType,parentId:e.parentId,pageId:t,index:e.index,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,props:{...e.props},meta:{...e.meta}}}function K(e){const{editor:t}=e,n=t.state.session.get(),s=n.activeToolId;e.assertToolId(s);const o=t.pages.getAll().map(e=>({pageId:e.id,selectedShapeIds:[...t.selection.getIds(e.id)],camera:{...t.viewport.getCamera(e.id)}}));return{currentPageId:n.currentPageId,activeToolId:s,isToolLocked:n.isToolLocked,meta:{...n.meta},pages:o}}function z(e){return{type:e.type,subType:e.subType,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props?{...e.props}:void 0,meta:e.meta?{...e.meta}:void 0}}function W(e){return{id:e.id,subType:e.subType,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props?{...e.props}:void 0,meta:void 0===e.meta?void 0:{...e.meta}}}function q({childIds:e,companionIds:t,context:n,depth:s,editor:o,index:r,pageId:i,shape:a}){return{id:a.id,parentId:a.parentId,pageId:i,type:a.type,companionIds:t,childIds:e,siblingIndex:r,depth:s,canReceiveChildren:o.layers.canReceiveChildren(a.id),isHidden:a.isHidden,isLocked:a.isLocked,isEffectivelyHidden:_(o,n,a.id),isEffectivelyLocked:X(n,a.id)}}function U({bindings:e,editor:t,shapes:n}){const s=new Map(n.map(e=>[e.id,e])),o=t.bindings.getShapeCompanionRootIds(n.map(({id:e})=>e),e),r=new Map,i=new Map,a=new Map;for(const c of n){const e=o.get(c.id)??c.id,t=s.has(e)?e:c.id;if(r.set(c.id,t),t===c.id){const e=a.get(c.parentId);e?e.push(c):a.set(c.parentId,[c])}else{const e=i.get(t);e?e.push(c.id):i.set(t,[c.id])}}return{childShapesByParentId:a,companionIdsByRootId:i,rootIdByShapeId:r,shapeById:s}}function V(e,t){return e.childShapesByParentId.get(t)??[]}function Y(e,t){let n=0,s=e.shapeById.get(t);const o=new Set([t]);for(;s?.parentId.startsWith("shape:");){const t=s.parentId;if(o.has(t))break;o.add(t),s=e.shapeById.get(t),n+=1}return n}function _(e,t,n){const s=new Set;let o=t.shapeById.get(n);for(;o;){if(o.isHidden)return!0;if(!o.parentId.startsWith("shape:"))return!1;const n=o.parentId;if(s.has(n))return!1;s.add(n);const r=t.shapeById.get(n);if(!r)return!1;if(!e.shapes.getUtil(r).isChildVisible(r,o,{editor:e}))return!0;o=r}return!1}function X(e,t){const n=new Set;let s=e.shapeById.get(t);for(;s;){if(s.isLocked)return!0;if(!s.parentId.startsWith("shape:"))return!1;const t=s.parentId;if(n.has(t))return!1;n.add(t),s=e.shapeById.get(t)}return!1}function J(e){let t=e;const n=new Set;return{readable:{getSnapshot:()=>t,subscribe:e=>(n.add(e),()=>n.delete(e))},set(e){if(!Object.is(t,e)){t=e;for(const e of[...n])e()}}}}function Z({getDependencies:e,getSnapshot:t,name:n,signals:s}){let o,r=[],i=!1;const a=()=>{const n=e();return i&&((e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Object.is(e[n],t[n]))return!1;return!0})(r,n)||(r=n,o=t(n),i=!0),o};return{getSnapshot:a,subscribe(t){let o=a();return bt(n,{get:e,graph:s},()=>{const e=a();Object.is(o,e)||(o=e,t())},{fireImmediately:!1})}}}function G({apis:e,editor:t,exports:n,productId:s,startup:o}){const r=e=>(e?e.map(e=>t.shapes.get(e)).filter(e=>!!e):t.pages.getAll().flatMap(e=>t.shapes.getForPage(e.id))).map(e=>j(e,t.layers.getPageId(e.id))),i=e=>{const[n,...s]=e;return(({bindings:e,editor:t,pageId:n,shapes:s})=>{const o=[],r=U({bindings:e,editor:t,shapes:s}),i=(e,s)=>{V(r,e).forEach((e,a)=>{const c=V(r,e.id).map(e=>e.id);o.push(q({childIds:c,companionIds:r.companionIdsByRootId.get(e.id)??[],context:r,depth:s,editor:t,index:a,pageId:n,shape:e})),i(e.id,s+1)})};return i(n,0),o})({bindings:s.filter(Tt),editor:t,pageId:n,shapes:s.filter(Nt)})},a=e=>{if(!t.tools.hasTool(e))throw new Error(`Unknown canvas kit tool "${e}".`)},c={assertToolId:a,editor:t,productId:s},{readable:l,set:d}=J(!1),{readable:u,set:p}=J(null),h=(e,n="center")=>{const s="pointer"===n?t.inputs.state.get().currentScreenPoint:null;s?t.viewport.zoomAtScreenPoint(s,e,"system"):t.viewport.zoomAtCenter(e,"system")},f=Z({signals:t.signals,name:"CanvasKit.document",getDependencies:()=>[t.document.getMetadata()],getSnapshot:([e])=>H(e)}),m=Z({signals:t.signals,name:"CanvasKit.document.readonlyState",getDependencies:()=>[t.state.readonly.get()],getSnapshot:([e])=>e}),g=Z({signals:t.signals,name:"CanvasKit.document.lockedState",getDependencies:()=>[t.state.documentLocked.get()],getSnapshot:([e])=>e}),v=Z({signals:t.signals,name:"CanvasKit.session",getDependencies:()=>[t.state.session.get().meta],getSnapshot:([e])=>({meta:{...e}})}),w=Z({signals:t.signals,name:"CanvasKit.selection",getDependencies:()=>[t.state.selectedShapeIds.get(),t.state.selectedShapes.get(),t.state.selectionMetadata.get(),t.state.selectionPageBounds.get(),t.state.selectionAnchorPagePoint.get(),t.render.interaction.selectionTranslationActive.get(),t.state.currentPageId.get()],getSnapshot:([e,t,n,s,o,r,i])=>({...n,ids:[...e],shapes:t.map(e=>j(e,i)),pageBounds:s?{x:s.minX,y:s.minY,width:s.w,height:s.h}:null,anchorPagePoint:o?{x:o.x,y:o.y}:null,isTranslating:r})}),y=Z({signals:t.signals,name:"CanvasKit.pages",getDependencies:()=>[t.state.pages.get(),t.state.currentPageId.get(),t.state.currentPageShapeIds.get()],getSnapshot:([e,t,n])=>{const s=e.map(N),o=s.find(e=>e.id===t)??null;return{pages:s,currentPage:o,currentPageId:t,currentPageShapeIds:[...n],canDeleteCurrentPage:s.length>1&&null!==o}}}),b=Z({signals:t.signals,name:"CanvasKit.history",getDependencies:()=>[t.state.history.get()],getSnapshot:([e])=>({...e})}),S=Z({signals:t.signals,name:"CanvasKit.viewport",getDependencies:()=>[t.state.camera.get(),t.state.cameraLock.get(),t.state.viewportPageBounds.get(),t.state.pageTransform.get()],getSnapshot:([e,t,n,s])=>({camera:{...e},lock:t?{...t.pagePoint}:null,zoom:e.z,pageBounds:n?{x:n.minX,y:n.minY,width:n.w,height:n.h}:null,pageTransform:s.toCssString()})}),x=Z({signals:t.signals,name:"CanvasKit.tools",getDependencies:()=>[t.state.tool.get(),t.state.shapeEditing.get()],getSnapshot:([e,t])=>(a(e.activeToolId),{currentToolId:e.activeToolId,isLocked:e.isToolLocked,isEditing:null!==t.session})}),E=Z({signals:t.signals,name:"CanvasKit.layers",getDependencies:()=>Q(t,t.pages.getCurrentId()),getSnapshot:i});return{canvas:{startup:o,api:t=>e.get(t)??void 0,document:{state:f,readonlyState:m,lockedState:g,setLocked:e=>t.document.setLocked(e),getSnapshot:()=>(e=>{const{editor:t}=e,n=t.state.tool.get().activeToolId;return e.assertToolId(n),{productId:e.productId,document:H(t.document.getMetadata()),pageId:t.pages.getCurrentId(),activeToolId:n,selectedShapeIds:[...t.selection.getIds()],shapeCount:t.state.currentPageShapeIds.get().length,session:K(e)}})(c),updateMeta:e=>(t.document.updateMetadata({...e},"user"),H(t.document.getMetadata()))},session:{state:v,updateMeta(e){const n=t.session.get();return t.session.update({meta:{...n.meta,...e}},"user"),{meta:{...t.state.session.get().meta}}}},selection:{state:w,select:e=>t.commands.setSelectedShapeIds([...e],{source:"user"}),selectAll:()=>t.selection.selectAll("user"),clear:()=>t.commands.setSelectedShapeIds([],{source:"user"}),delete:()=>t.selection.delete("user"),duplicate:()=>t.selection.duplicate({source:"user"}),resetRotation:()=>t.selection.resetRotation("user"),flip:e=>t.selection.flip(e,"user"),setOpacity:e=>((e,t)=>{if(!Number.isFinite(t))return;const n=Math.min(1,Math.max(0,t)),s=e.state.selectedShapes.get().filter(e=>e.opacity!==n).map(e=>({id:e.id,opacity:n}));s.length>0&&e.commands.updateShapes(s,{source:"user"})})(t,e),align:e=>t.selection.align(e,"user"),distribute:e=>t.selection.distribute(e,"user")},pages:{state:y,create:e=>N(t.pages.createAndSelect(e?{name:e.name,meta:e.meta?{...e.meta}:void 0}:void 0,"user")),rename:(e,n)=>t.pages.rename(e,n,"user"),updateMeta:(e,n)=>t.pages.updateMetadata(e,{...n},"user")?.id??null,delete:e=>t.pages.delete(e,"user"),deleteCurrent:()=>t.pages.delete(t.pages.getCurrentId(),"user"),setCurrent:e=>t.pages.select(e,"user")},history:{state:b,batch:e=>t.operations.run({kind:"history.batch",source:"user"},e),clear:()=>t.history.clear(),undo:()=>t.history.undo(),redo:()=>t.history.redo()},viewport:{state:S,grid:{state:l,setVisible:d,toggle:()=>d(!l.getSnapshot())},setCamera:(e,n)=>t.commands.setCamera({pageId:n,camera:e},{source:"user"}),centerOnPoint:(e,n)=>t.viewport.centerOnPoint(e,{...n,source:"user"}),setLock:e=>t.viewport.setLock(e),zoomAtCenter:e=>{Number.isFinite(e)&&t.viewport.zoomAtCenter(e,"system")},zoomIn:e=>h(-120,e?.anchor),zoomOut:e=>h(120,e?.anchor),zoomToFit:()=>t.viewport.zoomToFit({source:"user"}),zoomToSelection:()=>t.viewport.zoomToSelection({source:"user"}),resetZoom:()=>t.viewport.resetZoom("user"),reset:()=>t.commands.setCamera({camera:{x:0,y:0,z:1}},{source:"user"})},tools:{state:x,setCurrent:e=>{if(!t.tools.hasTool(e))throw new Error(`Unknown product tool "${e}".`);t.tools.select(e,"user")},setLocked:e=>t.tools.setLocked(e,"user"),toggleLocked:()=>t.tools.toggleLocked("user")},shapes:{create:e=>((e,t)=>0===t.length?[]:e.commands.createShapes(t.map(z),{source:"user"}).map(e=>e.id))(t,e),get:e=>{const n=t.shapes.get(e);return n?j(n,t.layers.getPageId(n.id)):null},getMany:e=>r(e),getAll:()=>r(),getExportBounds:(e,n)=>{const s=t.shapes.get(e);if(!s)return null;let o;switch(n.space.type){case"shape-local":{const e=t.shapes.get(n.space.shapeId);if(!e)return null;if(o=t.shapes.computeExportBoundsInShapeSpace(s,e),!o)return null;break}case"page":o=t.shapes.computeExportPageBounds(s);break;default:throw new Error(`Unsupported canvas shape export bounds space "${String(n.space)}".`)}return![o.x,o.y,o.w,o.h].every(Number.isFinite)||o.w<0||o.h<0?null:{x:o.x,y:o.y,width:o.w,height:o.h}},update:e=>function(e,t){const n=t.filter(t=>{const n=e.shapes.get(t.id);return!!n&&((e,t)=>{return!(!t.props&&void 0===t.meta)||(void 0===t.subType?e.subType:t.subType)!==e.subType||(t.x??e.x)!==e.x||(t.y??e.y)!==e.y||(t.rotation??e.rotation)!==e.rotation||(t.scaleX??e.scaleX)!==e.scaleX||(t.scaleY??e.scaleY)!==e.scaleY||(void 0===t.opacity?e.opacity:(s=e.opacity,"number"==typeof(n=t.opacity)&&Number.isFinite(n)?Math.min(1,Math.max(0,n)):s))!==e.opacity||(t.isHidden??e.isHidden)!==e.isHidden||(t.isLocked??e.isLocked)!==e.isLocked||(t.parentId??e.parentId)!==e.parentId||(t.index??e.index)!==e.index;var n,s})(n,t)}).map(W);return 0===n.length?[]:(e.commands.updateShapes(n,{source:"user"}),n.map(e=>e.id))}(t,e),updateMeta:(e,n)=>{const s=t.shapes.get(e);return s?(t.commands.updateShapes([{id:e,meta:{...s.meta,...n}}],{source:"user"}),e):null},delete:e=>t.shapes.delete([...e],"user")},assets:{get:e=>{const n=t.assets.get(e);return n?(e=>({id:e.id,type:e.type,props:{...e.props},meta:{...e.meta}}))(n):null},resolveUrl:e=>t.assets.resolveUrl(e)},layers:{state:E,getTree:e=>i(Q(t,e??t.pages.getCurrentId())),getNode:e=>(({editor:e,id:t})=>{const n=e.shapes.get(t),s=n?e.layers.getPageId(n.id):null;if(!n||!s)return null;const o=e.shapes.getForPage(s),r=U({bindings:o.flatMap(t=>e.bindings.getForShape(t.id)),editor:e,shapes:o}),i=r.rootIdByShapeId.get(n.id)??n.id,a=r.shapeById.get(i);if(!a)return null;const c=V(r,a.parentId);return q({childIds:V(r,a.id).map(e=>e.id),companionIds:r.companionIdsByRootId.get(a.id)??[],context:r,depth:Y(r,a.id),editor:e,index:c.findIndex(e=>e.id===a.id),pageId:s,shape:a})})({editor:t,id:e}),getActionState:e=>({canGroup:t.layers.canGroup(e),canUngroup:t.layers.canUngroup(e),canMoveBackward:t.layers.canMove(e,"backward"),canMoveForward:t.layers.canMove(e,"forward")}),centerOn:(e,n)=>t.viewport.centerOnShape(e,{...n,source:"user"}),setHidden:(e,n)=>t.shapes.setHidden([...e],n,"user"),setLocked:(e,n)=>t.shapes.setLocked([...e],n,"user"),group:e=>t.layers.group([...e],"user")?.id??null,ungroup:e=>t.layers.ungroup([...e],"user"),move:(e,n)=>t.layers.move([...e],n,"user"),moveToEdge:(e,n)=>t.layers.moveToEdge([...e],n,"user"),moveToPlacement:(e,n)=>{const s=t.layers.moveToPlacement({ids:[...e],parentId:n.parentId,beforeId:n.beforeId??void 0},"user");return s.ok?{ok:!0,ids:s.movedIds}:{ok:!1,reason:"locked"===s.reason?"locked":"cycle"===s.reason?"cycle":"invalidBeforeId"===s.reason?"invalid-before":"unsupportedTransform"===s.reason?"mixed-parent":"notFound"===s.reason&&0===e.length?"empty-selection":"invalid-parent"}}},contextMenu:{state:u,dismiss:()=>p(null)},exports:{state:{getSnapshot:()=>n.getStatus(),subscribe:e=>n.subscribe(e)},getFormats:()=>n.getFormats(),getStatus:()=>n.getStatus(),export:(e,t)=>n.export(e,t)}},host:{setContextMenu:p}}}function Q(e,t){const n=e.shapes.getForPage(t).map(t=>e.shapes.getSignal(t.id).get()).filter(e=>!!e),s=new Map;for(const o of n)for(const t of e.bindings.getForShape(o.id))s.set(t.id,t);return[t,...n,...s.values()]}function ee(){const e=new Map;let t=!1;return{register({token:n,api:s,pluginId:o}){if(t)throw new Error("Canvas API registry is disposed.");if(e.has(n.id))throw new Error(`Duplicate canvas API token: ${n.id}.`);e.set(n.id,{token:n,api:s,pluginId:o})},view:t=>(({allowedTokenIds:t,ownerLabel:n})=>{const s=s=>{if(t&&!t.has(s.id))throw new Error(`${n} attempted to read undeclared canvas API "${s.id}".`);const o=e.get(s.id);return o?o.api:null};return{get:s,require(e){const t=s(e);if(null===t)throw new Error(`${n} requires unavailable canvas API "${e.id}".`);return t}}})(t),clear(){t||(t=!0,e.clear())}}}async function te(e,t={}){(e=>{if(!e||!Array.isArray(e.plugins))throw new Error("CanvasKit requires an explicit plugins array.");if(!("persistence"in e))throw new Error("CanvasKit requires an explicit persistence option.")})(e),t.signal?.throwIfAborted();const{canvasPlugins:n,editorPlugins:s,renderPlugins:o}=function(e){const t=(e=>e.flat(1/0))(e);B(t.map(({id:e})=>e),"canvas plugin id");const n=(e=>{const t=new Map(e.map(e=>[e.id,e])),n=[],s=new Set,o=new Set,r=e=>{if(!o.has(e.id)){if(s.has(e.id))throw new Error(`Circular canvas plugin dependency detected at "${e.id}".`);s.add(e.id);for(const n of e.requires??[]){const s=t.get(n.id);if(!s)throw new Error(`Canvas plugin "${e.id}" requires missing plugin "${n.id}".`);r(s)}s.delete(e.id),o.add(e.id),n.push(e)}};for(const i of e)r(i);return n})(t),s=n.flatMap(e=>e.editor?[e.editor]:[]),o=n.flatMap(e=>e.render?[e.render]:[]);return B(s.map(({id:e})=>e),"editor plugin id"),B(n.flatMap(e=>e.api?[e.api.id]:[]),"canvas API token"),{canvasPlugins:n,editorPlugins:s,renderPlugins:o}}(e.plugins),r=At(o),i=new an,a=t.signal?AbortSignal.any([i.signal,t.signal]):i.signal;try{const o=e.id??"canvas-kit",c=e.persistence;c&&i.own(c,e=>e.dispose?.());let l=[];const d=i.own((e=>{const t=Dt({cameraAnimationScheduler:$(),documentMeta:e.documentMeta,minZoom:e.minZoom,maxZoom:e.maxZoom,onUnhandledError:e.onUnhandledError,plugins:e.editorPlugins,resolveAssetUrl:e.resolveAssetUrl});return t.tools.register("select",e=>new yt(e)),t.tools.register("hand",e=>new kt(e)),t.tools.syncLockedState(t.state.tool.get().isToolLocked),t.commands.setActiveTool("select",{source:"system"}),t.history.clear(),t})({minZoom:e.minZoom,maxZoom:e.maxZoom,documentMeta:e.documentMeta?{...e.documentMeta}:void 0,onUnhandledError:e.onError,editorPlugins:s,resolveAssetUrl(e){for(const t of l){const n=t.resolve(e);if(n)return n}return null}}),e=>e.dispose()),u=c?i.own(new ln(d,c,{flushEvents:t.persistenceFlushEvents,onError:e.onError}),{shutdown:e=>e.shutdown(),rollback:e=>e.rollback()}):null,{apis:p,contributions:{assetResolvers:h,exports:f,imports:m}}=function({apis:e,canvasPlugins:t,editor:n,owner:s,productId:o}){const r=new Map(t.map(e=>[e.id,e])),i=[];for(const c of t){s.signal.throwIfAborted();const t=c.setup?.({editor:n,productId:o,apis:e.view({allowedTokenIds:M(c,r),ownerLabel:`Canvas plugin "${c.id}" setup`}),tasks:s.tasks});t&&(s.own(t,e=>e.dispose?.()),i.push({plugin:c,instance:t})),L(c,t),c.api&&t?.api&&e.register({token:c.api,api:t.api,pluginId:c.id})}const a=(e=>{const t=e.flatMap(({instance:e})=>e.imports??[]),n=e.flatMap(({instance:e})=>e.exports??[]),s=e.flatMap(({instance:e})=>e.assetResolvers??[]);return D(t.map(({id:e})=>e),"import contribution"),D(n.map(({id:e})=>e),"export contribution"),D(n.flatMap(e=>"provider"===e.kind?[e.format]:[]),"export format"),D(s.map(({id:e})=>e),"asset resolver contribution"),Object.freeze({imports:Object.freeze((o=t,o.map((e,t)=>({value:e,index:t})).sort((e,t)=>(e.value.order??0)-(t.value.order??0)||e.index-t.index).map(({value:e})=>e))),exports:Object.freeze([...n]),assetResolvers:Object.freeze([...s])});var o})(i);return{apis:e.view({ownerLabel:"CanvasKit"}),contributions:a}}({apis:i.own(ee(),e=>e.clear()),canvasPlugins:n,editor:d,owner:i,productId:o});l=h;const g=await(async({assetResolvers:e,editor:t,initialDocumentSnapshot:n,persistenceAdapter:s,persistenceCoordinator:o,signal:r})=>{const i=t.snapshots.getSession(),a=[],c=s?.load?await s.load({signal:r}):{documentSnapshot:null,sessionSnapshot:null};let l;r.throwIfAborted(),null!==c.documentSnapshot?(t.snapshots.loadDocument(c.documentSnapshot,{source:"system"}),l="restored"):void 0!==n?(t.snapshots.loadDocument(n,{source:"system"}),l="initial"):l="empty",r.throwIfAborted();let d=!1;if("restored"===l&&null!==c.sessionSnapshot)try{t.snapshots.loadSession(c.sessionSnapshot,{source:"system"}),d=!0}catch(u){r.throwIfAborted(),a.push(u),t.snapshots.loadSession(i,{source:"system"})}t.history.clear();for(const p of e){r.throwIfAborted();try{await(p.preload?.({editor:t,signal:r})),"restored"===l&&await(p.cleanupAfterRestore?.({editor:t,signal:r}))}catch(u){r.throwIfAborted(),a.push(u)}}return r.throwIfAborted(),o?.start(),{documentSource:l,sessionRestored:d,warnings:[...a]}})({assetResolvers:l,editor:d,initialDocumentSnapshot:e.initialDocumentSnapshot,persistenceAdapter:c,persistenceCoordinator:u,signal:a});!0===e.readonly&&d.document.setReadonly(!0),i.signal.throwIfAborted();const v=i.own(function({editor:e,contributions:t,tasks:n}){const s=t.filter(O),o=t.filter(F),r=new Map;for(const d of s){if(r.has(d.format))throw new Error(`Duplicate canvas export format: ${d.format}.`);r.set(d.format,d)}let i=rn,a=!1;const c=new Set,l=e=>{if(!Object.is(i,e)){i=e;for(const e of[...c])e()}};return{getFormats:()=>s.map(({format:e,label:t,mimeType:n,fileExtension:s})=>({format:e,label:t,mimeType:n,fileExtension:s})),getStatus:()=>i,subscribe:e=>(c.add(e),()=>c.delete(e)),export:async(t,s)=>n.run(async n=>{if(a)throw new Error("Canvas export controller is disposed.");if("exporting"===i.state)throw new Error("An export is already in progress.");const c=r.get(t);if(!c)throw new Error(`Canvas export format is unavailable: ${t}.`);l({state:"exporting",format:t});try{const t=((e,t)=>{if("selection"===t.scope)return e.selection.getIds();if("page"===t.scope)return e.state.currentPageShapeIds.get();if(!t.shapeIds)throw new Error("Canvas export requires a scope or shapeIds.");return t.shapeIds})(e,s);for(const s of o)n.throwIfAborted(),await(s.prepare?.({editor:e,requestedShapeIds:t,signal:n}));n.throwIfAborted();const r=await c.export({editor:e,shapeIds:t,options:s.options},{signal:n,async inlineSvg(e){let t=e.svg;for(const s of o)n.throwIfAborted(),t=await s.inline({editor:e.editor,exportedShapes:e.exportedShapes,exportedShapeIds:e.exportedShapeIds,svg:t,signal:n});return n.throwIfAborted(),t}});return n.throwIfAborted(),{format:c.format,label:c.label,mimeType:c.mimeType,fileExtension:c.fileExtension,...r}}finally{l(rn)}}),dispose(){a||(a=!0,l(rn),c.clear())}}}({editor:d,contributions:f,tasks:i.tasks}),e=>e.dispose());i.signal.throwIfAborted();const{canvas:w,host:y}=G({apis:p,editor:d,exports:v,productId:o,startup:g});return{canvas:w,dispose:i.publish({beforeShutdown:()=>d.closeWrites()}),productId:o,render:{editor:d,importContributions:m,onError:e.onError,renderBindings:r,setContextMenu:y.setContextMenu}}}catch(c){return i.rollback(c)}}function ne(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}function se({actions:e=un,chromeRenderer:t,onCanvasChange:n,options:s}){const o=(e=>{const[t,n]=Vt(null);return zt(()=>{let t=!0,s=null;const o=new AbortController,r=e.onError??ne;return n({options:e,state:dn}),te(e,{persistenceFlushEvents:{subscribe(e){const t=()=>{"hidden"===document.visibilityState&&e()},n=()=>e();return document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",n),window.addEventListener("beforeunload",n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",n),window.removeEventListener("beforeunload",n)}}},signal:o.signal}).then(o=>{s=o,t?n({options:e,state:{status:"ready",runtime:o}}):o.dispose().catch(r)},s=>{t&&n({options:e,state:{status:"error",error:s}})}),()=>{t=!1,o.abort(new DOMException("CanvasKitRoot was cleaned up.","AbortError")),s?.dispose().catch(r)}},[e]),t?.options===e?t.state:dn})(s);if("error"===o.status)throw o.error;return"ready"!==o.status?null:Xt(oe,{actions:e,chromeRenderer:t,onCanvasChange:n,runtime:o.runtime})}function oe({actions:e=un,chromeRenderer:t,onCanvasChange:n,runtime:s}){const o=Ut(n),a=Ut(null),c=jt(()=>a.current,[]),{canvas:l,productId:u,render:p}=s,h=p.onError??ne,f=jt(()=>l.tools.state.getSnapshot().isEditing,[l]);return o.current=n,zt(()=>(o.current?.(l),()=>o.current?.(null)),[l]),(({actions:e,canvas:t,getHostElement:n,isEditing:s,onError:o})=>{const r=Wt((e,t)=>{o(new Error(`Canvas action "${e.id}" failed.`,{cause:t}))}),i=Wt((e,n)=>{try{if(!e.isEnabled(t))return;if(n.preventDefault(),n.stopPropagation(),n.repeat&&!e.repeat)return;const s=e.run(t);s&&s.catch(t=>r(e,t))}catch(s){r(e,s)}}),a=Wt(e=>{const t=n(),o=e.composedPath()[0];return!t||!(o instanceof Element)||o.closest("[data-canvas-kit]")!==t||e.defaultPrevented||e.isComposing||229===e.keyCode||s()||Lt(o)||!!o.closest('[role="textbox"], [role="combobox"], [role="slider"], [role="spinbutton"]')||!!t.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]')||((e,t)=>{if("c"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return!1;const n=t.getSelection();return null!==n&&n.rangeCount>0&&!n.isCollapsed})(e,t.ownerDocument)});zt(()=>{const t=n();if(!t)return;const s=new Set,o={},r=new Map;for(const n of e){if(s.has(n.id))throw new Error(`Duplicate CanvasAction id "${n.id}".`);s.add(n.id);for(const e of A(n.shortcut)){const t=P(e),s=JSON.stringify(I(t).map(([e,t,n])=>[[...e].sort(),t,String(n).toLowerCase()])),a=r.get(s);if(a&&a!==n.id)throw new Error(`Canvas shortcut "${t}" is assigned to both "${a}" and "${n.id}".`);a||(r.set(s,n.id),o[t]=e=>i(n,e))}}return function(e,t,n={}){let s=n.event??"keydown",o=((e,t={})=>{let n=t.timeout??1e3,s=t.ignore??E,o=Object.keys(e).map(t=>[t,I(t),e[t]]),r=new Map,i=null;return e=>{if(!(e=>!!(e.key&&e.code&&e.getModifierState))(e)||s(e))return;let t=[];for(let[n,s,i]of o){let o=r.get(n),[a,...c]=o||s;if(k(e,a))if(c.length>0)r.set(n,c),t.push(n);else{if(r.delete(n),!t.length){i(e);break}console.warn(`tinykeys: Conflict found, "${n}" did not fire, waiting for:`,t)}else C(e,e.key)||r.delete(n)}i&&clearTimeout(i),i=setTimeout(()=>r.clear(),n)}})(t,n);return e.addEventListener(s,o,n.capture),()=>{e.removeEventListener(s,o,n.capture)}}(t,o,{ignore:a})},[e,n])})({actions:e,canvas:l,getHostElement:c,isEditing:f,onError:h}),Xt(d,{canvas:l,children:Xt(r,{children:Xt("div",{ref:a,"data-ui":"app-shell","data-canvas-kit":u,className:"land-canvas-kit__shell",children:Jt("main",{"data-ui":"workspace-viewport",className:"land-canvas-kit__viewport",children:[
5
- Xt(x,{bindings:p,getHostElement:c,onError:h}),t?.(l)??null,
6
- Xt(i,{})]})})})})}function re(){return"undefined"==typeof indexedDB?Promise.resolve(null):(hn||(hn=new Promise((e,t)=>{const n=indexedDB.open("canvas-kit.persistence",2);n.addEventListener("upgradeneeded",()=>{var e;(e=n.result).objectStoreNames.contains("snapshots")||e.createObjectStore(pn)}),n.addEventListener("success",()=>{const t=n.result;t.addEventListener("versionchange",()=>{t.close(),hn=null}),e(t)}),n.addEventListener("error",()=>{hn=null,t(n.error)})})),hn)}function ie(e={}){return{async load({signal:t}){t.throwIfAborted();const n=await ce(e);return t.throwIfAborted(),n},saveDocument:t=>ae({documentSnapshot:JSON.stringify(t),sessionSnapshot:null},e),saveSession:t=>ae({documentSnapshot:null,sessionSnapshot:JSON.stringify(t)},e)}}async function ae(e,t){const n=[];null!==e.documentSnapshot&&n.push([ue(t),e.documentSnapshot]),null!==e.sessionSnapshot&&n.push([pe(t),e.sessionSnapshot]),0!==n.length&&await(async(e,t)=>{if(0===t.length)return;const n=await re();n&&await new Promise((s,o)=>{const r=n.transaction(e,"readwrite"),i=r.objectStore(e);r.addEventListener("complete",()=>s()),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error));for(const[e,n]of t)i.put(n,e)})})(pn,n)}async function ce(e={}){const[t,n]=await fe([ue(e),pe(e)]);return{documentSnapshot:t,sessionSnapshot:n}}async function le(){return he(fn)}async function de(){return he(mn)}function ue(e){return e.storageNamespace?`${e.storageNamespace}.document`:fn}function pe(e){return e.storageNamespace?`${e.storageNamespace}.session`:mn}async function he(e){const[t]=await fe([e]);return t??null}async function fe(e){return(await(async(e,t)=>{if(0===t.length)return[];const n=await re();return n?new Promise((s,o)=>{const r=n.transaction(e,"readonly"),i=r.objectStore(e),a=new Array(t.length).fill(null);r.addEventListener("complete",()=>s(a)),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error)),t.forEach((e,t)=>{const n=i.get(e);n.addEventListener("success",()=>{a[t]=n.result??null}),n.addEventListener("error",()=>o(n.error))})}):null})("snapshots",e)??e.map(()=>null)).map(me)}function me(e){if(null==e)return null;if("string"!=typeof e)throw new Error("Persisted canvas snapshot is not a JSON string.");try{return JSON.parse(e)}catch(t){throw new Error("Persisted canvas snapshot contains invalid JSON.",{cause:t})}}function ge({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){const s=a();return s?Zt(Xt("div",{"data-ui":n,className:ve("land-canvas__floating-toolbar-layer",t),children:e}),s):null}function ve(...e){return e.filter(Boolean).join(" ")}function we(e,t){return"function"==typeof e?e(t):e}function ye(e){return e.split("-")[0]}function be(e){return e.split("-")[1]}function Se(e){return"y"===e?"height":"width"}function xe(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function Ee(e){return"x"===xe(e)?"y":"x"}function Ce(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}function Ie(e){const t=ye(e);return Sn[t]+e.slice(t.length)}function ke(e){const{x:t,y:n,width:s,height:o}=e;return{width:s,height:o,top:n,left:t,right:t+s,bottom:n+o,x:t,y:n}}function Pe(e,t,n){let{reference:s,floating:o}=e;const r=xe(t),i=Ee(t),a=Se(i),c=ye(t),l="y"===r,d=s.x+s.width/2-o.width/2,u=s.y+s.height/2-o.height/2,p=s[a]/2-o[a]/2;let h;switch(c){case"top":h={x:d,y:s.y-o.height};break;case"bottom":h={x:d,y:s.y+s.height};break;case"right":h={x:s.x+s.width,y:u};break;case"left":h={x:s.x-o.width,y:u};break;default:h={x:s.x,y:s.y}}switch(be(t)){case"start":h[i]-=p*(n&&l?-1:1);break;case"end":h[i]+=p*(n&&l?-1:1)}return h}async function Te(e,t){var n;void 0===t&&(t={});const{x:s,y:o,platform:r,rects:i,elements:a,strategy:c}=e,{boundary:l="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=we(t,e),f=(e=>"number"!=typeof e?(e=>({top:0,right:0,bottom:0,left:0,...e}))(e):{top:e,right:e,bottom:e,left:e})(h),m=a[p?"floating"===u?"reference":"floating":u],g=ke(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(m)))||n?m:m.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(a.floating)),boundary:l,rootBoundary:d,strategy:c})),v="floating"===u?{x:s,y:o,width:i.floating.width,height:i.floating.height}:i.reference,w=await(null==r.getOffsetParent?void 0:r.getOffsetParent(a.floating)),y=await(null==r.isElement?void 0:r.isElement(w))&&await(null==r.getScale?void 0:r.getScale(w))||{x:1,y:1},b=ke(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:w,strategy:c}):v);return{top:(g.top-b.top+f.top)/y.y,bottom:(b.bottom-g.bottom+f.bottom)/y.y,left:(g.left-b.left+f.left)/y.x,right:(b.right-g.right+f.right)/y.x}}function Ae(){return"undefined"!=typeof window}function Re(e){return De(e)?(e.nodeName||"").toLowerCase():"#document"}function Le(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Me(e){var t;return null==(t=(De(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function De(e){return!!Ae()&&(e instanceof Node||e instanceof Le(e).Node)}function Oe(e){return!!Ae()&&(e instanceof Element||e instanceof Le(e).Element)}function Fe(e){return!!Ae()&&(e instanceof HTMLElement||e instanceof Le(e).HTMLElement)}function Be(e){return!(!Ae()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Le(e).ShadowRoot)}function $e(e){const{overflow:t,overflowX:n,overflowY:s,display:o}=We(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+n)&&"inline"!==o&&"contents"!==o}function Ne(e){return/^(table|td|th)$/.test(Re(e))}function He(e){try{if(e.matches(":popover-open"))return!0}catch(t){}try{return e.matches(":modal")}catch(t){return!1}}function je(e){const t=Oe(e)?We(e):e;return An(t.transform)||An(t.translate)||An(t.scale)||An(t.rotate)||An(t.perspective)||!Ke()&&(An(t.backdropFilter)||An(t.filter))||Pn.test(t.willChange||"")||Tn.test(t.contain||"")}function Ke(){return null==Gt&&(Gt="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Gt}function ze(e){return/^(html|body|#document)$/.test(Re(e))}function We(e){return Le(e).getComputedStyle(e)}function qe(e){return Oe(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Ue(e){if("html"===Re(e))return e;const t=e.assignedSlot||e.parentNode||Be(e)&&e.host||Me(e);return Be(t)?t.host:t}function Ve(e){const t=Ue(e);return ze(t)?e.ownerDocument?e.ownerDocument.body:e.body:Fe(t)&&$e(t)?t:Ve(t)}function Ye(e,t,n){var s;void 0===t&&(t=[]),void 0===n&&(n=!0);const o=Ve(e),r=o===(null==(s=e.ownerDocument)?void 0:s.body),i=Le(o);if(r){const e=_e(i);return t.concat(i,i.visualViewport||[],$e(o)?o:[],e&&n?Ye(e):[])}return t.concat(o,Ye(o,[],n))}function _e(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Xe(e){const t=We(e);let n=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Fe(e),r=o?e.offsetWidth:n,i=o?e.offsetHeight:s,a=wn(n)!==r||wn(s)!==i;return a&&(n=r,s=i),{width:n,height:s,$:a}}function Je(e){return Oe(e)?e:e.contextElement}function Ze(e){const t=Je(e);if(!Fe(t))return bn(1);const n=t.getBoundingClientRect(),{width:s,height:o,$:r}=Xe(t);let i=(r?wn(n.width):n.width)/s,a=(r?wn(n.height):n.height)/o;return i&&Number.isFinite(i)||(i=1),a&&Number.isFinite(a)||(a=1),{x:i,y:a}}function Ge(e){const t=Le(e);return Ke()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:Rn}function Qe(e,t,n,s){void 0===t&&(t=!1),void 0===n&&(n=!1);const o=e.getBoundingClientRect(),r=Je(e);let i=bn(1);t&&(s?Oe(s)&&(i=Ze(s)):i=Ze(e));const a=((e,t,n)=>(void 0===t&&(t=!1),!(!n||t&&n!==Le(e))&&t))(r,n,s)?Ge(r):bn(0);let c=(o.left+a.x)/i.x,l=(o.top+a.y)/i.y,d=o.width/i.x,u=o.height/i.y;if(r){const e=Le(r),t=s&&Oe(s)?Le(s):s;let n=e,o=_e(n);for(;o&&s&&t!==n;){const e=Ze(o),t=o.getBoundingClientRect(),s=We(o),r=t.left+(o.clientLeft+parseFloat(s.paddingLeft))*e.x,i=t.top+(o.clientTop+parseFloat(s.paddingTop))*e.y;c*=e.x,l*=e.y,d*=e.x,u*=e.y,c+=r,l+=i,n=Le(o),o=_e(n)}}return ke({width:d,height:u,x:c,y:l})}function et(e,t){const n=qe(e).scrollLeft;return t?t.left+n:Qe(Me(e)).left+n}function tt(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-et(e,n),y:n.top+t.scrollTop}}function nt(e,t,n){let s;if("viewport"===t)s=((e,t)=>{const n=Le(e),s=Me(e),o=n.visualViewport;let r=s.clientWidth,i=s.clientHeight,a=0,c=0;if(o){r=o.width,i=o.height;const e=Ke();(!e||e&&"fixed"===t)&&(a=o.offsetLeft,c=o.offsetTop)}const l=et(s);if(l<=0){const e=s.ownerDocument,t=e.body,n=getComputedStyle(t),o="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(s.clientWidth-t.clientWidth-o);i<=25&&(r-=i)}else l<=25&&(r+=l);return{width:r,height:i,x:a,y:c}})(e,n);else if("document"===t)s=(e=>{const t=Me(e),n=qe(e),s=e.ownerDocument.body,o=vn(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),r=vn(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let i=-n.scrollLeft+et(e);const a=-n.scrollTop;return"rtl"===We(s).direction&&(i+=vn(t.clientWidth,s.clientWidth)-o),{width:o,height:r,x:i,y:a}})(Me(e));else if(Oe(t))s=((e,t)=>{const n=Qe(e,!0,"fixed"===t),s=n.top+e.clientTop,o=n.left+e.clientLeft,r=Fe(e)?Ze(e):bn(1);return{width:e.clientWidth*r.x,height:e.clientHeight*r.y,x:o*r.x,y:s*r.y}})(t,n);else{const n=Ge(e);s={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return ke(s)}function st(e,t){const n=Ue(e);return!(n===t||!Oe(n)||ze(n))&&("fixed"===We(n).position||st(n,t))}function ot(e,t){const n=t.get(e);if(n)return n;let s=Ye(e,[],!1).filter(e=>Oe(e)&&"body"!==Re(e)),o=null;const r="fixed"===We(e).position;let i=r?Ue(e):e;for(;Oe(i)&&!ze(i);){const t=We(i),n=je(i);n||"fixed"!==t.position||(o=null),(r?!n&&!o:!n&&"static"===t.position&&o&&("absolute"===o.position||"fixed"===o.position)||$e(i)&&!n&&st(e,i))?s=s.filter(e=>e!==i):o=t,i=Ue(i)}return t.set(e,s),s}function rt(e,t,n){function s(){l.x=et(r)}const o=Fe(t),r=Me(t),i="fixed"===n,a=Qe(e,!0,i,t);let c={scrollLeft:0,scrollTop:0};const l=bn(0);if(o||!o&&!i)if(("body"!==Re(t)||$e(r))&&(c=qe(t)),o){const e=Qe(t,!0,i,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}else r&&s();i&&!o&&r&&s();const d=!r||o||i?bn(0):tt(r,c);return{x:a.left+c.scrollLeft-l.x-d.x,y:a.top+c.scrollTop-l.y-d.y,width:a.width,height:a.height}}function it(e){return"static"===We(e).position}function at(e,t){if(!Fe(e)||"fixed"===We(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Me(e)===n&&(n=n.ownerDocument.body),n}function ct(e,t){const n=Le(e);if(He(e))return n;if(!Fe(e)){let t=Ue(e);for(;t&&!ze(t);){if(Oe(t)&&!it(t))return t;t=Ue(t)}return n}let s=at(e,t);for(;s&&Ne(s)&&it(s);)s=at(s,t);return s&&ze(s)&&it(s)&&!je(s)?n:s||(e=>{let t=Ue(e);for(;Fe(t)&&!ze(t);){if(je(t))return t;if(He(t))return null;t=Ue(t)}return null})(e)||n}function lt(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function dt({viewport:e,fallbackPlacements:t,floatingRef:n,getReferenceElement:s,onPlacementChange:o,offset:r,placement:i,visible:a=!0}){zt(()=>{const c=s(),l=n.current;if(!c||!l)return;let d=!1,u=0;l.style.visibility="hidden";const p=()=>{const e=++u,n=pt("--toolbar-floating-collision-padding",8);((e,t,n)=>{const s={platform:Ln,...n},o={...s.platform,_c:new Map};return(async(e,t,n)=>{const{placement:s="bottom",strategy:o="absolute",middleware:r=[],platform:i}=n,a=i.detectOverflow?i:{...i,detectOverflow:Te},c=await(null==i.isRTL?void 0:i.isRTL(t));let l=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:u}=Pe(l,s,c),p=s,h=0;const f={};for(let m=0;m<r.length;m++){const n=r[m];if(!n)continue;const{name:g,fn:v}=n,{x:w,y:y,data:b,reset:S}=await v({x:d,y:u,initialPlacement:s,placement:p,strategy:o,middlewareData:f,rects:l,platform:a,elements:{reference:e,floating:t}});d=null!=w?w:d,u=null!=y?y:u,f[g]={...f[g],...b},S&&h<50&&(h++,"object"==typeof S&&(S.placement&&(p=S.placement),S.rects&&(l=!0===S.rects?await i.getElementRects({reference:e,floating:t,strategy:o}):S.rects),({x:d,y:u}=Pe(l,p,c))),m=-1)}return{x:d,y:u,placement:p,strategy:o,middlewareData:f}})(e,t,{...s,platform:o})})(c,l,{strategy:"fixed",placement:i,middleware:ut({fallbackPlacements:t,offset:r??pt("--toolbar-floating-offset",38),padding:{top:pt("--toolbar-floating-safe-top",64),right:n,bottom:n,left:n}})}).then(({placement:t,x:n,y:s})=>{d||e!==u||(l.dataset.placement=t,o?.(t),l.style.transform=`translate3d(${Math.round(n)}px, ${Math.round(s)}px, 0)`,l.style.visibility=a?"visible":"hidden")})},h=function(e,t,n,s){void 0===s&&(s={});const{ancestorScroll:o=!0,ancestorResize:r=!0,elementResize:i="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=s,l=Je(e),d=o||r?[...l?Ye(l):[],...t?Ye(t):[]]:[];d.forEach(e=>{o&&e.addEventListener("scroll",n,{passive:!0}),r&&e.addEventListener("resize",n)});const u=l&&a?((e,t)=>{function n(){var e;clearTimeout(s),null==(e=o)||e.disconnect(),o=null}let s,o=null;const r=Me(e);return function i(a,c){function l(t){const n=t[0].intersectionRatio;if(n!==c){if(!g)return i();n?i(!1,n):s=setTimeout(()=>{i(!1,1e-7)},1e3)}1!==n||lt(d,e.getBoundingClientRect())||i(),g=!1}void 0===a&&(a=!1),void 0===c&&(c=1),n();const d=e.getBoundingClientRect(),{left:u,top:p,width:h,height:f}=d;if(a||t(),!h||!f)return;const m={rootMargin:-yn(p)+"px "+-yn(r.clientWidth-(u+h))+"px "+-yn(r.clientHeight-(p+f))+"px "+-yn(u)+"px",threshold:vn(0,gn(1,c))||1};let g=!0;try{o=new IntersectionObserver(l,{...m,root:r.ownerDocument})}catch(v){o=new IntersectionObserver(l,m)}o.observe(e)}(!0),n})(l,n):null;let p,h=-1,f=null;i&&(f=new ResizeObserver(e=>{let[s]=e;s&&s.target===l&&f&&t&&(f.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),l&&!c&&f.observe(l),t&&f.observe(t));let m=c?Qe(e):null;return c&&function t(){const s=Qe(e);m&&!lt(m,s)&&n(),m=s,p=requestAnimationFrame(t)}(),n(),()=>{var e;d.forEach(e=>{o&&e.removeEventListener("scroll",n),r&&e.removeEventListener("resize",n)}),u?.(),null==(e=f)||e.disconnect(),f=null,c&&cancelAnimationFrame(p)}}(c,l,p,{ancestorResize:!0,ancestorScroll:!0,elementResize:!0,layoutShift:!0}),f=e.subscribe(p);return p(),()=>{d=!0,l.style.visibility="hidden",h(),f()}},[e,t,n,s,o,r,i,a])}function ut({fallbackPlacements:e,offset:t,padding:n}){return[Mn(t),Dn({fallbackPlacements:[...e],padding:n})]}function pt(e,t){if("undefined"==typeof document)return t;const n=getComputedStyle(document.documentElement).getPropertyValue(e).trim();if(!n)return t;const s=Number.parseFloat(n);return Number.isFinite(s)?n.endsWith("rem")?16*s:s:t}function ht(e){const t=a();return t?Zt(Xt(ft,{...e}),t):null}function ft({fallbackPlacements:e=On,offset:t=8,placement:n="top",referenceElement:o,...r}){const i=u(),a=Ut(null),c=jt(()=>o,[o]);return s(a),dt({viewport:i.viewport.state,fallbackPlacements:e,floatingRef:a,getReferenceElement:c,offset:t,placement:n}),Xt("div",{...r,ref:a})}function mt(){return Kt($n)}function gt({children:e,className:t,dataUi:n="floating-selection-toolbar-slot",horizontalAlign:o="start",offset:r,visible:i=!0}){const a=u(),c=p(a.selection.state),l=p(a.viewport.state),d=Ut(null),h=Ut(null),[f,m]=Vt("center"===o?"top":"top-start"),g=c.pageBounds??(c.anchorPagePoint?{x:c.anchorPagePoint.x,y:c.anchorPagePoint.y,width:0,height:0}:null),v=i&&null!==g,w=v&&!c.isTranslating,y=jt(()=>d.current,[g?.height,g?.width,g?.x,g?.y]),b=jt(()=>d.current?.getBoundingClientRect()??null,[]),S=qt(()=>({placement:f,getContentBounds:b}),[g?.height,g?.width,g?.x,g?.y,b,f,l.pageTransform]);return s(h),dt({viewport:a.viewport.state,fallbackPlacements:"center"===o?Bn:Fn,floatingRef:h,getReferenceElement:y,onPlacementChange:m,offset:r,placement:"center"===o?"top":"top-start",visible:w}),v&&g?Jt(_t,{children:[Xt("div",{"data-ui":`${n}-page-space`,className:"land-canvas__floating-selection-page-space",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",transform:l.pageTransform,transformOrigin:"0 0"},children:Xt("div",{ref:d,"aria-hidden":"true",style:{position:"absolute",left:g.x,top:g.y,width:g.width,height:g.height,pointerEvents:"none"}})}),Xt("div",{ref:h,"data-ui":n,className:vt("land-canvas__floating-selection-anchor",t),style:{position:"fixed",left:0,top:0,visibility:"hidden",willChange:"transform"},children:Xt($n.Provider,{value:S,children:e})})]}):null}function vt(...e){return e.filter(Boolean).join(" ")}import{A as wt,D as yt,E as bt,F as St,I as xt,L as Et,M as Ct,N as It,O as kt,P as Pt,R as Tt,S as At,a as Rt,f as Lt,j as Mt,k as Dt,o as Ot,r as Ft,u as Bt,w as $t,z as Nt}from"./host-C9sTNI4D.mjs";import{createContext as Ht,useCallback as jt,useContext as Kt,useEffect as zt,useEffectEvent as Wt,useMemo as qt,useRef as Ut,useState as Vt,useSyncExternalStore as Yt}from"react";import{Fragment as _t,jsx as Xt,jsxs as Jt}from"react/jsx-runtime";import{createPortal as Zt}from"react-dom";var Gt,Qt=Ht(null),en=Ht(null),tn=["Shift","Meta","Alt","Control"],nn="object"==typeof navigator?navigator.platform:"",sn=/Mac|iPod|iPhone|iPad/.test(nn)?"Meta":"Control",on="Win32"===nn?["Control","Alt"]:["Alt"],rn={state:"idle"},an=class{abortController=new AbortController;activeTasks=new Set;disposers=[];phase="starting";close=null;signal=this.abortController.signal;tasks={run:e=>this.runTask(e)};own(e,t){if("starting"!==this.phase)throw new Error("Cannot register a resource after the Canvas Runtime is published or disposal starts.");return this.disposers.push(n=>"function"==typeof t?t(e):"rollback"===n&&t.rollback?t.rollback(e):t.shutdown(e)),e}publish({beforeShutdown:e}={}){if("starting"!==this.phase)throw new Error(`Only a starting Canvas Runtime can be published; received runtime in "${this.phase}" phase.`);return this.phase="ready",()=>null!==this.close?"shutdown"===this.close.mode?this.close.result:Promise.reject(new Error("Cannot shut down a Canvas Runtime during rollback.")):this.beginClose({mode:"shutdown",beforeShutdown:e})}rollback(e){return null!==this.close?"rollback"===this.close.mode?this.close.result:Promise.reject(new Error("Cannot roll back a Canvas Runtime during shutdown.")):"starting"!==this.phase?Promise.reject(new Error(`Only a starting Canvas Runtime can roll back; received runtime in "${this.phase}" phase.`)):this.beginClose({mode:"rollback",cause:e})}beginClose(e){const t=[],n=Promise.resolve().then(async()=>{const n=[...t,...await this.disposeResources(e.mode)];if(this.phase="disposed","rollback"===e.mode){if(n.length>0)throw new AggregateError([e.cause,...n],"CanvasKit Runtime initialization failed and cleanup reported errors.",{cause:e.cause});throw e.cause}if(n.length>0)throw new AggregateError(n,"Failed to dispose one or more CanvasKit Runtime resources.")});if(this.close={mode:e.mode,result:n},"shutdown"===e.mode)try{e.beforeShutdown?.()}catch(s){t.push(s)}return this.phase="disposing",this.abortController.abort("rollback"===e.mode?e.cause:new DOMException("Canvas runtime is disposing.","AbortError")),n}runTask(e){if("ready"!==this.phase)throw new Error(`Canvas tasks require a ready runtime; received runtime in "${this.phase}" phase.`);this.signal.throwIfAborted();const t=Promise.resolve().then(()=>e(this.signal));return this.activeTasks.add(t),t.finally(()=>this.activeTasks.delete(t)).catch(()=>{}),t}async disposeResources(e){await Promise.allSettled([...this.activeTasks]);const t=[];for(;this.disposers.length>0;){const s=this.disposers.pop();try{await s(e)}catch(n){t.push(n)}}return t}},cn=[500,1e3,2e3,5e3],ln=class{editor;adapter;options;unsubscribeDocument=null;unsubscribeSession=null;unsubscribeFlushEvents=null;documentTimer=null;sessionTimer=null;pendingDocument=null;pendingSession=null;documentVersion=0;sessionVersion=0;documentRetryCount=0;sessionRetryCount=0;writeChain=Promise.resolve();flushChain=Promise.resolve();isRunning=!1;disposeMode=null;disposePromise=null;constructor(e,t,n={}){this.editor=e,this.adapter=t,this.options=n}start(){if(null!==this.disposeMode)throw new Error("Cannot start disposed canvas persistence.");this.isRunning||(this.isRunning=!0,this.adapter.saveDocument&&(this.unsubscribeDocument=this.editor.operations.subscribe(e=>{var t;this.documentVersion+=1,this.documentRetryCount=0,this.pendingDocument={snapshot:(t=e.snapshot,JSON.parse(JSON.stringify(t))),version:this.documentVersion},this.scheduleDocumentSave(200)})),this.adapter.saveSession&&(this.unsubscribeSession=this.editor.listen(e=>{var t,n;((t=e.diff).added.some(e=>"session"===e.scope)||t.updated.some(e=>"session"===e.before.scope||"session"===e.after.scope)||t.removed.some(e=>"session"===e.scope))&&(this.sessionVersion+=1,this.sessionRetryCount=0,this.pendingSession={snapshot:(n=this.editor.snapshots.getSession(),JSON.parse(JSON.stringify(n))),version:this.sessionVersion},this.scheduleSessionSave(200))})),this.unsubscribeFlushEvents=this.options.flushEvents?.subscribe(this.flushForHostLifecycle)??null)}flush(){if(null!==this.disposeMode)return Promise.reject(new Error("Cannot flush disposed canvas persistence."));const e=this.flushChain.then(()=>this.flushNow());return this.flushChain=e.catch(()=>{}),e}shutdown(){return this.dispose("shutdown")}rollback(){return this.dispose("rollback")}dispose(e){return null!==this.disposeMode?this.disposeMode!==e?Promise.reject(new Error(`Canvas persistence disposal already started in "${this.disposeMode}" mode.`)):this.disposePromise:(this.disposeMode=e,this.disposePromise=Promise.resolve().then(()=>"shutdown"===e?this.finishShutdown():this.finishRollback()),this.disposePromise)}async finishShutdown(){this.stopIntake(),await this.flushChain,await this.flushNow()}async finishRollback(){this.stopIntake(),this.discardPendingSnapshots(),await this.flushChain,await this.writeChain,this.discardPendingSnapshots()}stopIntake(){this.isRunning=!1,this.cancelDocumentTimer(),this.cancelSessionTimer(),this.unsubscribeDocument?.(),this.unsubscribeSession?.(),this.unsubscribeFlushEvents?.(),this.unsubscribeDocument=null,this.unsubscribeSession=null,this.unsubscribeFlushEvents=null}async flushNow(){const e=await this.flushPendingSnapshots();try{await(this.adapter.flush?.())}catch(t){e.push(t)}if(e.length>0)throw new AggregateError(e,"Failed to flush canvas persistence.")}async flushPendingSnapshots(){this.cancelDocumentTimer(),this.cancelSessionTimer();const e=this.savePendingDocument(),t=this.savePendingSession();return(await Promise.allSettled([e,t])).flatMap(e=>"rejected"===e.status?[e.reason]:[])}discardPendingSnapshots(){this.cancelDocumentTimer(),this.cancelSessionTimer(),this.pendingDocument=null,this.pendingSession=null}savePendingDocument(){const e=this.pendingDocument;if(!e||!this.adapter.saveDocument)return this.writeChain;this.pendingDocument=null;const t=this.queueWrite(()=>Promise.resolve(this.adapter.saveDocument(e.snapshot))).then(()=>{this.documentVersion===e.version&&(this.documentRetryCount=0)}).catch(t=>{throw this.documentVersion===e.version&&null===this.pendingDocument&&(this.pendingDocument=e,this.scheduleDocumentRetry()),t});return this.writeChain=t.catch(()=>{}),t}savePendingSession(){const e=this.pendingSession;if(!e||!this.adapter.saveSession)return this.writeChain;this.pendingSession=null;const t=this.queueWrite(()=>Promise.resolve(this.adapter.saveSession(e.snapshot))).then(()=>{this.sessionVersion===e.version&&(this.sessionRetryCount=0)}).catch(t=>{throw this.sessionVersion===e.version&&null===this.pendingSession&&(this.pendingSession=e,this.scheduleSessionRetry()),t});return this.writeChain=t.catch(()=>{}),t}queueWrite(e){return this.writeChain.then(e)}scheduleDocumentSave(e){this.cancelDocumentTimer(),this.documentTimer=setTimeout(()=>{this.documentTimer=null,this.savePendingDocument().catch(e=>{this.reportError("Could not persist canvas document.",e)})},e)}scheduleSessionSave(e){this.cancelSessionTimer(),this.sessionTimer=setTimeout(()=>{this.sessionTimer=null,this.savePendingSession().catch(e=>{this.reportError("Could not persist canvas session.",e)})},e)}scheduleDocumentRetry(){if(!this.isRunning||null!==this.documentTimer)return;const e=cn[this.documentRetryCount];void 0!==e&&(this.documentRetryCount+=1,this.scheduleDocumentSave(e))}scheduleSessionRetry(){if(!this.isRunning||null!==this.sessionTimer)return;const e=cn[this.sessionRetryCount];void 0!==e&&(this.sessionRetryCount+=1,this.scheduleSessionSave(e))}cancelDocumentTimer(){null!==this.documentTimer&&(clearTimeout(this.documentTimer),this.documentTimer=null)}cancelSessionTimer(){null!==this.sessionTimer&&(clearTimeout(this.sessionTimer),this.sessionTimer=null)}flushForHostLifecycle=()=>{this.flush().catch(e=>{this.reportError("Could not persist canvas snapshot.",e)})};reportError(e,t){try{this.options.onError?.(new Error(e,{cause:t}))}catch{}}},dn={status:"starting"},un=[],pn="snapshots",hn=null,fn="canvas-kit.document",mn="canvas-kit.session",gn=Math.min,vn=Math.max,wn=Math.round,yn=Math.floor,bn=e=>({x:e,y:e}),Sn={left:"right",right:"left",bottom:"top",top:"bottom"},xn=["left","right"],En=["right","left"],Cn=["top","bottom"],In=["bottom","top"],kn=new Set(["left","top"]),Pn=/transform|translate|scale|rotate|perspective|filter/,Tn=/paint|layout|strict|content/,An=e=>!!e&&"none"!==e,Rn=bn(0),Ln={convertOffsetParentRelativeRectToViewportRelativeRect:e=>{let{elements:t,rect:n,offsetParent:s,strategy:o}=e;const r="fixed"===o,i=Me(s),a=!!t&&He(t.floating);if(s===i||a&&r)return n;let c={scrollLeft:0,scrollTop:0},l=bn(1);const d=bn(0),u=Fe(s);if((u||!u&&!r)&&(("body"!==Re(s)||$e(i))&&(c=qe(s)),u)){const e=Qe(s);l=Ze(s),d.x=e.x+s.clientLeft,d.y=e.y+s.clientTop}const p=!i||u||r?bn(0):tt(i,c);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+d.x+p.x,y:n.y*l.y-c.scrollTop*l.y+d.y+p.y}},getDocumentElement:Me,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:s,strategy:o}=e;const r=[..."clippingAncestors"===n?He(t)?[]:ot(t,this._c):[].concat(n),s],i=nt(t,r[0],o);let a=i.top,c=i.right,l=i.bottom,d=i.left;for(let u=1;u<r.length;u++){const e=nt(t,r[u],o);a=vn(e.top,a),c=gn(e.right,c),l=gn(e.bottom,l),d=vn(e.left,d)}return{width:c-d,height:l-a,x:d,y:a}},getOffsetParent:ct,getElementRects:async function(e){const t=this.getOffsetParent||ct,n=this.getDimensions,s=await n(e.floating);return{reference:rt(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}},getClientRects:e=>Array.from(e.getClientRects()),getDimensions:e=>{const{width:t,height:n}=Xe(e);return{width:t,height:n}},getScale:Ze,isElement:Oe,isRTL:e=>"rtl"===We(e).direction},Mn=e=>(void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var n,s;const{x:o,y:r,placement:i,middlewareData:a}=t,c=await(async(e,t)=>{const{placement:n,platform:s,elements:o}=e,r=await(null==s.isRTL?void 0:s.isRTL(o.floating)),i=ye(n),a=be(n),c="y"===xe(n),l=kn.has(i)?-1:1,d=r&&c?-1:1,u=we(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:f}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&"number"==typeof f&&(h="end"===a?-1*f:f),c?{x:h*d,y:p*l}:{x:p*l,y:h*d}})(t,e);return i===(null==(n=a.offset)?void 0:n.placement)&&null!=(s=a.arrow)&&s.alignmentOffset?{}:{x:o+c.x,y:r+c.y,data:{...c,placement:i}}}}),Dn=e=>(void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,s;const{placement:o,middlewareData:r,rects:i,initialPlacement:a,platform:c,elements:l}=t,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...g}=we(e,t);if(null!=(n=r.arrow)&&n.alignmentOffset)return{};const v=ye(o),w=xe(a),y=ye(a)===a,b=await(null==c.isRTL?void 0:c.isRTL(l.floating)),S=p||(y||!m?[Ie(a)]:(e=>{const t=Ie(e);return[Ce(e),t,Ce(t)]})(a)),x="none"!==f;!p&&x&&S.push(...function(e,t,n,s){const o=be(e);let r=((e,t,n)=>{switch(e){case"top":case"bottom":return n?t?En:xn:t?xn:En;case"left":case"right":return t?Cn:In;default:return[]}})(ye(e),"start"===n,s);return o&&(r=r.map(e=>e+"-"+o),t&&(r=r.concat(r.map(Ce)))),r}(a,m,f,b));const E=[a,...S],C=await c.detectOverflow(t,g),I=[];let k=(null==(s=r.flip)?void 0:s.overflows)||[];if(d&&I.push(C[v]),u){const e=((e,t,n)=>{void 0===n&&(n=!1);const s=be(e),o=Ee(e),r=Se(o);let i="x"===o?s===(n?"end":"start")?"right":"left":"start"===s?"bottom":"top";return t.reference[r]>t.floating[r]&&(i=Ie(i)),[i,Ie(i)]})(o,i,b);I.push(C[e[0]],C[e[1]])}if(k=[...k,{placement:o,overflows:I}],!I.every(e=>e<=0)){var P,T;const e=((null==(P=r.flip)?void 0:P.index)||0)+1,t=E[e];if(t&&("alignment"!==u||w===xe(t)||k.every(e=>xe(e.placement)!==w||e.overflows[0]>0)))return{data:{index:e,overflows:k},reset:{placement:t}};let n=null==(T=k.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:T.placement;if(!n)switch(h){case"bestFit":{var A;const e=null==(A=k.filter(e=>{if(x){const t=xe(e.placement);return t===w||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:A[0];e&&(n=e);break}case"initialPlacement":n=a}if(o!==n)return{reset:{placement:n}}}return{}}}),On=["bottom"],Fn=["bottom-start"],Bn=["bottom"],$n=Ht(null);export{ht as CanvasKitFloatingContent,ge as CanvasKitFloatingToolbarLayer,d as CanvasKitProvider,se as CanvasKitRoot,gt as FloatingSelectionToolbarPageSpace,R as applyCanvasActionShortcutOverrides,t as createCanvasApiToken,wt as createCustomShapeColor,ie as createLocalSnapshotPersistence,Mt as createThemeShapeColor,e as defineCanvasPlugin,T as formatCanvasActionShortcut,A as getCanvasActionShortcuts,Ct as getThemeColorTokenName,It as isCustomShapeColorRef,Pt as isThemeShapeColorRef,le as readPersistedDocumentSnapshot,ce as readPersistedEditorSnapshots,de as readPersistedSessionSnapshot,n as requireApi,St as resolveShapeColor,xt as shapeColorToCssColor,u as useCanvasKit,c as useCanvasKitFloatingPortalContainer,s as useCanvasKitWheelCapture,p as useCanvasValue,mt as useFloatingSelectionToolbarPosition};
3
+ return Xt(en.Provider,{value:e,children:t})}function u(){const e=Kt(en);if(!e)throw new Error("useCanvasKit must be used inside CanvasKitProvider.");return e}function p(e){return Yt(e.subscribe,e.getSnapshot,e.getSnapshot)}function h({contributions:e,getHostElement:t,isEditing:n,onError:s,screenToPage:o}){return zt(()=>{const r=o=>{if(!y(t(),o)||n()||Bt(o.target))return;const r=w({source:"clipboard",dataTransfer:o.clipboardData});f(e,r)&&(o.preventDefault(),g(e,r).catch(e=>{s(new Error("Canvas clipboard import failed.",{cause:e}))}))},i=s=>{!y(t(),s)||n()||Bt(s.target)||m(e,v(s.dataTransfer))&&(s.preventDefault(),s.dataTransfer&&(s.dataTransfer.dropEffect="copy"))},a=r=>{const i=y(t(),r);if(!i||n()||Bt(r.target))return;const a=m(e,v(r.dataTransfer)),c=w({source:"drop",dataTransfer:r.dataTransfer,pagePoint:o(Lt(r,i))});f(e,c)?(r.preventDefault(),g(e,c).catch(e=>{s(new Error("Canvas drop import failed.",{cause:e}))})):a&&(r.preventDefault(),r.dataTransfer&&(r.dataTransfer.dropEffect="none"))};return window.addEventListener("paste",r),window.addEventListener("dragover",i),window.addEventListener("drop",a),()=>{window.removeEventListener("paste",r),window.removeEventListener("dragover",i),window.removeEventListener("drop",a)}},[e,t,n,s,o]),null}function f(e,t){return e.some(e=>e.accepts(t))}function m(e,t){return e.some(e=>e.acceptsPreview?.(t)??!1)}async function g(e,t){for(const n of e)if(n.accepts(t)&&"handled"===await n.import(t))return"handled";return"ignored"}function v(e){return e?{source:"drop",dataTypes:Array.from(e.types),fileTypes:Array.from(e.items).filter(e=>"file"===e.kind).map(e=>e.type).filter(Boolean)}:{source:"drop",dataTypes:[],fileTypes:[]}}function w({dataTransfer:e,pagePoint:t,source:n}){const s=e?.getData("text/plain")||void 0,o=e?.getData("text/html")||void 0,r=[...(e?.getData("text/uri-list")||void 0)?.split(/\r?\n/).filter(e=>e&&!e.startsWith("#"))??[],...s&&x(s.trim())?[s.trim()]:[]];return{source:n,files:b(e),text:s,html:o,...r.length>0?{urls:r}:{},pagePoint:t}}function y(e,t){if(!e)return null;const n=(t.target instanceof Element?t.target:document.activeElement)?.closest(Ft);return n instanceof HTMLElement&&e.contains(n)?n:null}function b(e){if(!e)return[];const t=Array.from(e.files);return t.length>0?t:Array.from(e.items).flatMap(e=>{if("file"!==e.kind)return[];const t=e.getAsFile();return t?[t]:[]})}function x(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return e.startsWith("data:image/")}}function S({bindings:e,getHostElement:t,onError:n}){const s=u(),o=p(s.viewport.grid.state),{editor:r,importContributions:i,renderBindings:a,setContextMenu:c}=e,l=jt(()=>s.tools.state.getSnapshot().isEditing,[s]),d=jt(e=>r.viewport.screenToPage(e),[r]);
4
+ return Jt(_t,{children:[Xt(Rt.Provider,{value:r,children:Xt(Mt,{onContextMenuRequest:c,renderBindings:a,showGrid:o})}),Xt(h,{contributions:i,getHostElement:t,isEditing:l,onError:n,screenToPage:d})]})}function E(e){let t=e.target;return e.repeat||e.isComposing||t!==e.currentTarget&&t.matches("[contenteditable],input,select,textarea")}function C(e,t){return"function"==typeof e.getModifierState&&(e.getModifierState(t)||on.includes(t)&&e.getModifierState("AltGraph"))}function I(e){return e.trim().split(" ").map(e=>{let t=e.split(/(?<=\w|\])\+/),n=t.pop(),s=n.match(/^\((.+)\)$/),o=s?new RegExp(`^(?:${s[1]})$`,"iv"):n,r=[],i=[];for(const a of t){let e=a.match(/^\[(.*)\]$/),t=e?.[1]??a;t="$mod"===t?sn:t,e?i.push(t):r.push(t)}return[r,i,o]})}function k(e,[t,n,s]){const o=t.includes("AltGraph");return!((s instanceof RegExp?!s.test(e.key)&&!s.test(e.code):s.toUpperCase()!==e.key.toUpperCase()&&s!==e.code)||t.find(t=>!C(e,t))||tn.find(r=>!t.includes(r)&&!n.includes(r)&&s!==r&&C(e,r)&&!(o&&on.includes(r))))}function P(e){const t="string"==typeof e?{key:e}:e;return[...[t.accelKey&&"$mod",t.ctrlKey&&"Control",t.metaKey&&"Meta",t.altKey&&"Alt",t.shiftKey&&"Shift"].filter(Boolean)," "===t.key?"Space":t.key].join("+")}function T(e){const t="undefined"!=typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),n={Control:t?"⌃":"Ctrl",Meta:t?"⌘":"Win",Alt:t?"⌥":"Alt",Shift:t?"⇧":"Shift",Backspace:t?"⌫":"Backspace",Delete:"Del",Escape:"Esc",ArrowUp:"↑",ArrowDown:"↓",ArrowLeft:"←",ArrowRight:"→",Equal:"=",Minus:"-",BracketLeft:"[",BracketRight:"]",Slash:"/",Space:"Space"};return I(P(e)).map(([e,,s])=>[...e,String(s)].map(e=>n[e]??e.replace(/^(Key|Digit)(?=\w$)/,"").toUpperCase()).join(t?"":"+")).join(" ")}function A(e){return void 0===e?[]:Array.isArray(e)?e:[e]}function R(e,t){if(!t||0===Object.keys(t).length)return e;const n=new Set(Object.keys(t)),s=e.map(e=>{if(!Object.prototype.hasOwnProperty.call(t,e.id))return e;n.delete(e.id);const s=t[e.id];return{...e,shortcut:s??void 0}});if(n.size>0)throw new Error(`Unknown CanvasAction shortcut override ids: ${[...n].join(", ")}.`);return s}function L(e,t){if(e.api&&!t?.api)throw new Error(`Canvas plugin "${e.id}" declares API "${e.api.id}" but setup returned no API value.`);if(!e.api&&t?.api)throw new Error(`Canvas plugin "${e.id}" returned an API value without declaring an API token.`)}function M(e,t){return new Set((e.requires??[]).flatMap(e=>{const n=t.get(e.id);return n?.api?[n.api.id]:[]}))}function D(e,t){const n=new Set;for(const s of e){if(n.has(s))throw new Error(`Duplicate ${t} id: ${s}.`);n.add(s)}}function O(e){return"provider"===e.kind}function F(e){return"svg-inliner"===e.kind}function B(e,t){const n=new Set;for(const s of e){if(n.has(s))throw new Error(`Duplicate ${t}: ${s}.`);n.add(s)}}function $(){if("undefined"!=typeof window&&"function"==typeof window.requestAnimationFrame&&"function"==typeof window.cancelAnimationFrame)return{requestFrame:e=>window.requestAnimationFrame(e),cancelFrame:e=>window.cancelAnimationFrame(e),prefersReducedMotion:()=>"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}}function N(e){return{id:e.id,name:e.name,index:e.index,meta:{...e.meta}}}function H(e){return{id:e?.id??"document:main",meta:{...e?.meta??{}}}}function j(e,t){return{id:e.id,type:e.type,subType:e.subType,parentId:e.parentId,pageId:t,index:e.index,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,props:{...e.props},meta:{...e.meta}}}function K(e){const{editor:t}=e,n=t.state.session.get(),s=n.activeToolId;e.assertToolId(s);const o=t.pages.getAll().map(e=>({pageId:e.id,selectedShapeIds:[...t.selection.getIds(e.id)],camera:{...t.viewport.getCamera(e.id)}}));return{currentPageId:n.currentPageId,activeToolId:s,isToolLocked:n.isToolLocked,meta:{...n.meta},pages:o}}function z(e){return{type:e.type,subType:e.subType,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props?{...e.props}:void 0,meta:e.meta?{...e.meta}:void 0}}function W(e){return{id:e.id,subType:e.subType,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props?{...e.props}:void 0,meta:void 0===e.meta?void 0:{...e.meta}}}function q({childIds:e,companionIds:t,context:n,depth:s,editor:o,index:r,pageId:i,shape:a}){return{id:a.id,parentId:a.parentId,pageId:i,type:a.type,companionIds:t,childIds:e,siblingIndex:r,depth:s,canReceiveChildren:o.layers.canReceiveChildren(a.id),isHidden:a.isHidden,isLocked:a.isLocked,isEffectivelyHidden:_(o,n,a.id),isEffectivelyLocked:X(n,a.id)}}function U({bindings:e,editor:t,shapes:n}){const s=new Map(n.map(e=>[e.id,e])),o=t.bindings.getShapeCompanionRootIds(n.map(({id:e})=>e),e),r=new Map,i=new Map,a=new Map;for(const c of n){const e=o.get(c.id)??c.id,t=s.has(e)?e:c.id;if(r.set(c.id,t),t===c.id){const e=a.get(c.parentId);e?e.push(c):a.set(c.parentId,[c])}else{const e=i.get(t);e?e.push(c.id):i.set(t,[c.id])}}return{childShapesByParentId:a,companionIdsByRootId:i,rootIdByShapeId:r,shapeById:s}}function V(e,t){return e.childShapesByParentId.get(t)??[]}function Y(e,t){let n=0,s=e.shapeById.get(t);const o=new Set([t]);for(;s?.parentId.startsWith("shape:");){const t=s.parentId;if(o.has(t))break;o.add(t),s=e.shapeById.get(t),n+=1}return n}function _(e,t,n){const s=new Set;let o=t.shapeById.get(n);for(;o;){if(o.isHidden)return!0;if(!o.parentId.startsWith("shape:"))return!1;const n=o.parentId;if(s.has(n))return!1;s.add(n);const r=t.shapeById.get(n);if(!r)return!1;if(!e.shapes.getUtil(r).isChildVisible(r,o,{editor:e}))return!0;o=r}return!1}function X(e,t){const n=new Set;let s=e.shapeById.get(t);for(;s;){if(s.isLocked)return!0;if(!s.parentId.startsWith("shape:"))return!1;const t=s.parentId;if(n.has(t))return!1;n.add(t),s=e.shapeById.get(t)}return!1}function J(e){let t=e;const n=new Set;return{readable:{getSnapshot:()=>t,subscribe:e=>(n.add(e),()=>n.delete(e))},set(e){if(!Object.is(t,e)){t=e;for(const e of[...n])e()}}}}function Z({getDependencies:e,getSnapshot:t,name:n,signals:s}){let o,r=[],i=!1;const a=()=>{const n=e();return i&&((e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Object.is(e[n],t[n]))return!1;return!0})(r,n)||(r=n,o=t(n),i=!0),o};return{getSnapshot:a,subscribe(t){let o=a();return xt(n,{get:e,graph:s},()=>{const e=a();Object.is(o,e)||(o=e,t())},{fireImmediately:!1})}}}function G({apis:e,editor:t,exports:n,productId:s,startup:o}){const r=e=>(e?e.map(e=>t.shapes.get(e)).filter(e=>!!e):t.pages.getAll().flatMap(e=>t.shapes.getForPage(e.id))).map(e=>j(e,t.layers.getPageId(e.id))),i=e=>{const[n,...s]=e;return(({bindings:e,editor:t,pageId:n,shapes:s})=>{const o=[],r=U({bindings:e,editor:t,shapes:s}),i=(e,s)=>{V(r,e).forEach((e,a)=>{const c=V(r,e.id).map(e=>e.id);o.push(q({childIds:c,companionIds:r.companionIdsByRootId.get(e.id)??[],context:r,depth:s,editor:t,index:a,pageId:n,shape:e})),i(e.id,s+1)})};return i(n,0),o})({bindings:s.filter(Nt),editor:t,pageId:n,shapes:s.filter(yt)})},a=e=>{if(!t.tools.hasTool(e))throw new Error(`Unknown canvas kit tool "${e}".`)},c={assertToolId:a,editor:t,productId:s},{readable:l,set:d}=J(!1),{readable:u,set:p}=J(null),h=(e,n="center")=>{const s="pointer"===n?t.inputs.state.get().currentScreenPoint:null;s?t.viewport.zoomAtScreenPoint(s,e,"system"):t.viewport.zoomAtCenter(e,"system")},f=Z({signals:t.signals,name:"CanvasKit.document",getDependencies:()=>[t.document.getMetadata()],getSnapshot:([e])=>H(e)}),m=Z({signals:t.signals,name:"CanvasKit.document.readonlyState",getDependencies:()=>[t.state.readonly.get()],getSnapshot:([e])=>e}),g=Z({signals:t.signals,name:"CanvasKit.document.lockedState",getDependencies:()=>[t.state.documentLocked.get()],getSnapshot:([e])=>e}),v=Z({signals:t.signals,name:"CanvasKit.session",getDependencies:()=>[t.state.session.get().meta],getSnapshot:([e])=>({meta:{...e}})}),w=Z({signals:t.signals,name:"CanvasKit.selection",getDependencies:()=>[t.state.selectedShapeIds.get(),t.state.selectedShapes.get(),t.state.selectionMetadata.get(),t.state.selectionPageBounds.get(),t.state.selectionAnchorPagePoint.get(),t.render.interaction.selectionTranslationActive.get(),t.state.currentPageId.get()],getSnapshot:([e,t,n,s,o,r,i])=>({...n,ids:[...e],shapes:t.map(e=>j(e,i)),pageBounds:s?{x:s.minX,y:s.minY,width:s.w,height:s.h}:null,anchorPagePoint:o?{x:o.x,y:o.y}:null,isTranslating:r})}),y=Z({signals:t.signals,name:"CanvasKit.pages",getDependencies:()=>[t.state.pages.get(),t.state.currentPageId.get(),t.state.currentPageShapeIds.get()],getSnapshot:([e,t,n])=>{const s=e.map(N),o=s.find(e=>e.id===t)??null;return{pages:s,currentPage:o,currentPageId:t,currentPageShapeIds:[...n],canDeleteCurrentPage:s.length>1&&null!==o}}}),b=Z({signals:t.signals,name:"CanvasKit.history",getDependencies:()=>[t.state.history.get()],getSnapshot:([e])=>({...e})}),x=Z({signals:t.signals,name:"CanvasKit.viewport",getDependencies:()=>[t.state.camera.get(),t.state.cameraLock.get(),t.state.viewportPageBounds.get(),t.state.pageTransform.get()],getSnapshot:([e,t,n,s])=>({camera:{...e},lock:t?{...t.pagePoint}:null,zoom:e.z,pageBounds:n?{x:n.minX,y:n.minY,width:n.w,height:n.h}:null,pageTransform:s.toCssString()})}),S=Z({signals:t.signals,name:"CanvasKit.tools",getDependencies:()=>[t.state.tool.get(),t.state.shapeEditing.get()],getSnapshot:([e,t])=>(a(e.activeToolId),{currentToolId:e.activeToolId,isLocked:e.isToolLocked,isEditing:null!==t.session})}),E=Z({signals:t.signals,name:"CanvasKit.layers",getDependencies:()=>Q(t,t.pages.getCurrentId()),getSnapshot:i});return{canvas:{startup:o,api:t=>e.get(t)??void 0,document:{state:f,readonlyState:m,lockedState:g,setLocked:e=>t.document.setLocked(e),getSnapshot:()=>(e=>{const{editor:t}=e,n=t.state.tool.get().activeToolId;return e.assertToolId(n),{productId:e.productId,document:H(t.document.getMetadata()),pageId:t.pages.getCurrentId(),activeToolId:n,selectedShapeIds:[...t.selection.getIds()],shapeCount:t.state.currentPageShapeIds.get().length,session:K(e)}})(c),updateMeta:e=>(t.document.updateMetadata({...e},"user"),H(t.document.getMetadata()))},session:{state:v,updateMeta(e){const n=t.session.get();return t.session.update({meta:{...n.meta,...e}},"user"),{meta:{...t.state.session.get().meta}}}},selection:{state:w,select:e=>t.commands.setSelectedShapeIds([...e],{source:"user"}),selectAll:()=>t.selection.selectAll("user"),clear:()=>t.commands.setSelectedShapeIds([],{source:"user"}),delete:()=>t.selection.delete("user"),duplicate:()=>t.selection.duplicate({source:"user"}),resetRotation:()=>t.selection.resetRotation("user"),flip:e=>t.selection.flip(e,"user"),setOpacity:e=>((e,t)=>{if(!Number.isFinite(t))return;const n=Math.min(1,Math.max(0,t)),s=e.state.selectedShapes.get().filter(e=>e.opacity!==n).map(e=>({id:e.id,opacity:n}));s.length>0&&e.commands.updateShapes(s,{source:"user"})})(t,e),align:e=>t.selection.align(e,"user"),distribute:e=>t.selection.distribute(e,"user")},pages:{state:y,create:e=>N(t.pages.createAndSelect(e?{name:e.name,meta:e.meta?{...e.meta}:void 0}:void 0,"user")),rename:(e,n)=>t.pages.rename(e,n,"user"),updateMeta:(e,n)=>t.pages.updateMetadata(e,{...n},"user")?.id??null,delete:e=>t.pages.delete(e,"user"),deleteCurrent:()=>t.pages.delete(t.pages.getCurrentId(),"user"),setCurrent:e=>t.pages.select(e,"user")},history:{state:b,batch:e=>t.operations.run({kind:"history.batch",source:"user"},e),clear:()=>t.history.clear(),undo:()=>t.history.undo(),redo:()=>t.history.redo()},viewport:{state:x,grid:{state:l,setVisible:d,toggle:()=>d(!l.getSnapshot())},setCamera:(e,n)=>t.commands.setCamera({pageId:n,camera:e},{source:"user"}),centerOnPoint:(e,n)=>t.viewport.centerOnPoint(e,{...n,source:"user"}),setLock:e=>t.viewport.setLock(e),zoomAtCenter:e=>{Number.isFinite(e)&&t.viewport.zoomAtCenter(e,"system")},zoomIn:e=>h(-120,e?.anchor),zoomOut:e=>h(120,e?.anchor),zoomToFit:()=>t.viewport.zoomToFit({source:"user"}),zoomToSelection:()=>t.viewport.zoomToSelection({source:"user"}),resetZoom:()=>t.viewport.resetZoom("user"),reset:()=>t.commands.setCamera({camera:{x:0,y:0,z:1}},{source:"user"})},tools:{state:S,setCurrent:e=>{if(!t.tools.hasTool(e))throw new Error(`Unknown product tool "${e}".`);t.tools.select(e,"user")},setLocked:e=>t.tools.setLocked(e,"user"),toggleLocked:()=>t.tools.toggleLocked("user")},shapes:{create:e=>((e,t)=>0===t.length?[]:e.commands.createShapes(t.map(z),{source:"user"}).map(e=>e.id))(t,e),get:e=>{const n=t.shapes.get(e);return n?j(n,t.layers.getPageId(n.id)):null},getMany:e=>r(e),getAll:()=>r(),getExportBounds:(e,n)=>{const s=t.shapes.get(e);if(!s)return null;let o;switch(n.space.type){case"shape-local":{const e=t.shapes.get(n.space.shapeId);if(!e)return null;if(o=t.shapes.computeExportBoundsInShapeSpace(s,e),!o)return null;break}case"page":o=t.shapes.computeExportPageBounds(s);break;default:throw new Error(`Unsupported canvas shape export bounds space "${String(n.space)}".`)}return![o.x,o.y,o.w,o.h].every(Number.isFinite)||o.w<0||o.h<0?null:{x:o.x,y:o.y,width:o.w,height:o.h}},update:e=>function(e,t){const n=t.filter(t=>{const n=e.shapes.get(t.id);return!!n&&((e,t)=>{return!(!t.props&&void 0===t.meta)||(void 0===t.subType?e.subType:t.subType)!==e.subType||(t.x??e.x)!==e.x||(t.y??e.y)!==e.y||(t.rotation??e.rotation)!==e.rotation||(t.scaleX??e.scaleX)!==e.scaleX||(t.scaleY??e.scaleY)!==e.scaleY||(void 0===t.opacity?e.opacity:(s=e.opacity,"number"==typeof(n=t.opacity)&&Number.isFinite(n)?Math.min(1,Math.max(0,n)):s))!==e.opacity||(t.isHidden??e.isHidden)!==e.isHidden||(t.isLocked??e.isLocked)!==e.isLocked||(t.parentId??e.parentId)!==e.parentId||(t.index??e.index)!==e.index;var n,s})(n,t)}).map(W);return 0===n.length?[]:(e.commands.updateShapes(n,{source:"user"}),n.map(e=>e.id))}(t,e),updateMeta:(e,n)=>{const s=t.shapes.get(e);return s?(t.commands.updateShapes([{id:e,meta:{...s.meta,...n}}],{source:"user"}),e):null},delete:e=>t.shapes.delete([...e],"user")},assets:{get:e=>{const n=t.assets.get(e);return n?(e=>({id:e.id,type:e.type,props:{...e.props},meta:{...e.meta}}))(n):null},resolveUrl:e=>t.assets.resolveUrl(e)},layers:{state:E,getTree:e=>i(Q(t,e??t.pages.getCurrentId())),getNode:e=>(({editor:e,id:t})=>{const n=e.shapes.get(t),s=n?e.layers.getPageId(n.id):null;if(!n||!s)return null;const o=e.shapes.getForPage(s),r=U({bindings:o.flatMap(t=>e.bindings.getForShape(t.id)),editor:e,shapes:o}),i=r.rootIdByShapeId.get(n.id)??n.id,a=r.shapeById.get(i);if(!a)return null;const c=V(r,a.parentId);return q({childIds:V(r,a.id).map(e=>e.id),companionIds:r.companionIdsByRootId.get(a.id)??[],context:r,depth:Y(r,a.id),editor:e,index:c.findIndex(e=>e.id===a.id),pageId:s,shape:a})})({editor:t,id:e}),getActionState:e=>({canGroup:t.layers.canGroup(e),canUngroup:t.layers.canUngroup(e),canMoveBackward:t.layers.canMove(e,"backward"),canMoveForward:t.layers.canMove(e,"forward")}),centerOn:(e,n)=>t.viewport.centerOnShape(e,{...n,source:"user"}),setHidden:(e,n)=>t.shapes.setHidden([...e],n,"user"),setLocked:(e,n)=>t.shapes.setLocked([...e],n,"user"),group:e=>t.layers.group([...e],"user")?.id??null,ungroup:e=>t.layers.ungroup([...e],"user"),move:(e,n)=>t.layers.move([...e],n,"user"),moveToEdge:(e,n)=>t.layers.moveToEdge([...e],n,"user"),moveToPlacement:(e,n)=>{const s=t.layers.moveToPlacement({ids:[...e],parentId:n.parentId,beforeId:n.beforeId??void 0},"user");return s.ok?{ok:!0,ids:s.movedIds}:{ok:!1,reason:"locked"===s.reason?"locked":"cycle"===s.reason?"cycle":"invalidBeforeId"===s.reason?"invalid-before":"unsupportedTransform"===s.reason?"mixed-parent":"notFound"===s.reason&&0===e.length?"empty-selection":"invalid-parent"}}},contextMenu:{state:u,dismiss:()=>p(null)},exports:{state:{getSnapshot:()=>n.getStatus(),subscribe:e=>n.subscribe(e)},getFormats:()=>n.getFormats(),getStatus:()=>n.getStatus(),export:(e,t)=>n.export(e,t)}},host:{setContextMenu:p}}}function Q(e,t){const n=e.shapes.getForPage(t).map(t=>e.shapes.getSignal(t.id).get()).filter(e=>!!e),s=new Map;for(const o of n)for(const t of e.bindings.getForShape(o.id))s.set(t.id,t);return[t,...n,...s.values()]}function ee(){const e=new Map;let t=!1;return{register({token:n,api:s,pluginId:o}){if(t)throw new Error("Canvas API registry is disposed.");if(e.has(n.id))throw new Error(`Duplicate canvas API token: ${n.id}.`);e.set(n.id,{token:n,api:s,pluginId:o})},view:t=>(({allowedTokenIds:t,ownerLabel:n})=>{const s=s=>{if(t&&!t.has(s.id))throw new Error(`${n} attempted to read undeclared canvas API "${s.id}".`);const o=e.get(s.id);return o?o.api:null};return{get:s,require(e){const t=s(e);if(null===t)throw new Error(`${n} requires unavailable canvas API "${e.id}".`);return t}}})(t),clear(){t||(t=!0,e.clear())}}}async function te(e,t={}){(e=>{if(!e||!Array.isArray(e.plugins))throw new Error("CanvasKit requires an explicit plugins array.");if(!("persistence"in e))throw new Error("CanvasKit requires an explicit persistence option.")})(e),t.signal?.throwIfAborted();const{canvasPlugins:n,editorPlugins:s,renderPlugins:o}=function(e){const t=(e=>e.flat(1/0))(e);B(t.map(({id:e})=>e),"canvas plugin id");const n=(e=>{const t=new Map(e.map(e=>[e.id,e])),n=[],s=new Set,o=new Set,r=e=>{if(!o.has(e.id)){if(s.has(e.id))throw new Error(`Circular canvas plugin dependency detected at "${e.id}".`);s.add(e.id);for(const n of e.requires??[]){const s=t.get(n.id);if(!s)throw new Error(`Canvas plugin "${e.id}" requires missing plugin "${n.id}".`);r(s)}s.delete(e.id),o.add(e.id),n.push(e)}};for(const i of e)r(i);return n})(t),s=n.flatMap(e=>e.editor?[e.editor]:[]),o=n.flatMap(e=>e.render?[e.render]:[]);return B(s.map(({id:e})=>e),"editor plugin id"),B(n.flatMap(e=>e.api?[e.api.id]:[]),"canvas API token"),{canvasPlugins:n,editorPlugins:s,renderPlugins:o}}(e.plugins),r=bt(o),i=new an,a=t.signal?AbortSignal.any([i.signal,t.signal]):i.signal;try{const o=e.id??"canvas-kit",c=e.persistence;c&&i.own(c,e=>e.dispose?.());let l=[];const d=i.own((e=>{const t=wt({cameraAnimationScheduler:$(),documentMeta:e.documentMeta,minZoom:e.minZoom,maxZoom:e.maxZoom,onUnhandledError:e.onUnhandledError,plugins:e.editorPlugins,resolveAssetUrl:e.resolveAssetUrl});return t.tools.register("select",e=>new Pt(e)),t.tools.register("hand",e=>new Ot(e)),t.tools.syncLockedState(t.state.tool.get().isToolLocked),t.commands.setActiveTool("select",{source:"system"}),t.history.clear(),t})({minZoom:e.minZoom,maxZoom:e.maxZoom,documentMeta:e.documentMeta?{...e.documentMeta}:void 0,onUnhandledError:e.onError,editorPlugins:s,resolveAssetUrl(e){for(const t of l){const n=t.resolve(e);if(n)return n}return null}}),e=>e.dispose()),u=c?i.own(new ln(d,c,{flushEvents:t.persistenceFlushEvents,onError:e.onError}),{shutdown:e=>e.shutdown(),rollback:e=>e.rollback()}):null,{apis:p,contributions:{assetResolvers:h,exports:f,imports:m}}=function({apis:e,canvasPlugins:t,editor:n,owner:s,productId:o}){const r=new Map(t.map(e=>[e.id,e])),i=[];for(const c of t){s.signal.throwIfAborted();const t=c.setup?.({editor:n,productId:o,apis:e.view({allowedTokenIds:M(c,r),ownerLabel:`Canvas plugin "${c.id}" setup`}),tasks:s.tasks});t&&(s.own(t,e=>e.dispose?.()),i.push({plugin:c,instance:t})),L(c,t),c.api&&t?.api&&e.register({token:c.api,api:t.api,pluginId:c.id})}const a=(e=>{const t=e.flatMap(({instance:e})=>e.imports??[]),n=e.flatMap(({instance:e})=>e.exports??[]),s=e.flatMap(({instance:e})=>e.assetResolvers??[]);return D(t.map(({id:e})=>e),"import contribution"),D(n.map(({id:e})=>e),"export contribution"),D(n.flatMap(e=>"provider"===e.kind?[e.format]:[]),"export format"),D(s.map(({id:e})=>e),"asset resolver contribution"),Object.freeze({imports:Object.freeze((o=t,o.map((e,t)=>({value:e,index:t})).sort((e,t)=>(e.value.order??0)-(t.value.order??0)||e.index-t.index).map(({value:e})=>e))),exports:Object.freeze([...n]),assetResolvers:Object.freeze([...s])});var o})(i);return{apis:e.view({ownerLabel:"CanvasKit"}),contributions:a}}({apis:i.own(ee(),e=>e.clear()),canvasPlugins:n,editor:d,owner:i,productId:o});l=h;const g=await(async({assetResolvers:e,editor:t,initialDocumentSnapshot:n,persistenceAdapter:s,persistenceCoordinator:o,signal:r})=>{const i=t.snapshots.getSession(),a=[],c=s?.load?await s.load({signal:r}):{documentSnapshot:null,sessionSnapshot:null};let l;r.throwIfAborted(),null!==c.documentSnapshot?(t.snapshots.loadDocument(c.documentSnapshot,{source:"system"}),l="restored"):void 0!==n?(t.snapshots.loadDocument(n,{source:"system"}),l="initial"):l="empty",r.throwIfAborted();let d=!1;if("restored"===l&&null!==c.sessionSnapshot)try{t.snapshots.loadSession(c.sessionSnapshot,{source:"system"}),d=!0}catch(u){r.throwIfAborted(),a.push(u),t.snapshots.loadSession(i,{source:"system"})}t.history.clear();for(const p of e){r.throwIfAborted();try{await(p.preload?.({editor:t,signal:r})),"restored"===l&&await(p.cleanupAfterRestore?.({editor:t,signal:r}))}catch(u){r.throwIfAborted(),a.push(u)}}return r.throwIfAborted(),o?.start(),{documentSource:l,sessionRestored:d,warnings:[...a]}})({assetResolvers:l,editor:d,initialDocumentSnapshot:e.initialDocumentSnapshot,persistenceAdapter:c,persistenceCoordinator:u,signal:a});!0===e.readonly&&d.document.setReadonly(!0),i.signal.throwIfAborted();const v=i.own(function({editor:e,contributions:t,tasks:n}){const s=t.filter(O),o=t.filter(F),r=new Map;for(const d of s){if(r.has(d.format))throw new Error(`Duplicate canvas export format: ${d.format}.`);r.set(d.format,d)}let i=rn,a=!1;const c=new Set,l=e=>{if(!Object.is(i,e)){i=e;for(const e of[...c])e()}};return{getFormats:()=>s.map(({format:e,label:t,mimeType:n,fileExtension:s})=>({format:e,label:t,mimeType:n,fileExtension:s})),getStatus:()=>i,subscribe:e=>(c.add(e),()=>c.delete(e)),export:async(t,s)=>n.run(async n=>{if(a)throw new Error("Canvas export controller is disposed.");if("exporting"===i.state)throw new Error("An export is already in progress.");const c=r.get(t);if(!c)throw new Error(`Canvas export format is unavailable: ${t}.`);l({state:"exporting",format:t});try{const t=((e,t)=>{if("selection"===t.scope)return e.selection.getIds();if("page"===t.scope)return e.state.currentPageShapeIds.get();if(!t.shapeIds)throw new Error("Canvas export requires a scope or shapeIds.");return t.shapeIds})(e,s);for(const s of o)n.throwIfAborted(),await(s.prepare?.({editor:e,requestedShapeIds:t,signal:n}));n.throwIfAborted();const r=await c.export({editor:e,shapeIds:t,options:s.options},{signal:n,async inlineSvg(e){let t=e.svg;for(const s of o)n.throwIfAborted(),t=await s.inline({editor:e.editor,exportedShapes:e.exportedShapes,exportedShapeIds:e.exportedShapeIds,svg:t,signal:n});return n.throwIfAborted(),t}});return n.throwIfAborted(),{format:c.format,label:c.label,mimeType:c.mimeType,fileExtension:c.fileExtension,...r}}finally{l(rn)}}),dispose(){a||(a=!0,l(rn),c.clear())}}}({editor:d,contributions:f,tasks:i.tasks}),e=>e.dispose());i.signal.throwIfAborted();const{canvas:w,host:y}=G({apis:p,editor:d,exports:v,productId:o,startup:g});return{canvas:w,dispose:i.publish({beforeShutdown:()=>d.closeWrites()}),productId:o,render:{editor:d,importContributions:m,onError:e.onError,renderBindings:r,setContextMenu:y.setContextMenu}}}catch(c){return i.rollback(c)}}function ne(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}function se({actions:e=un,chromeRenderer:t,onCanvasChange:n,options:s}){const o=(e=>{const[t,n]=Vt(null);return zt(()=>{let t=!0,s=null;const o=new AbortController,r=e.onError??ne;return n({options:e,state:dn}),te(e,{persistenceFlushEvents:{subscribe(e){const t=()=>{"hidden"===document.visibilityState&&e()},n=()=>e();return document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",n),window.addEventListener("beforeunload",n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",n),window.removeEventListener("beforeunload",n)}}},signal:o.signal}).then(o=>{s=o,t?n({options:e,state:{status:"ready",runtime:o}}):o.dispose().catch(r)},s=>{t&&n({options:e,state:{status:"error",error:s}})}),()=>{t=!1,o.abort(new DOMException("CanvasKitRoot was cleaned up.","AbortError")),s?.dispose().catch(r)}},[e]),t?.options===e?t.state:dn})(s);if("error"===o.status)throw o.error;return"ready"!==o.status?null:Xt(oe,{actions:e,chromeRenderer:t,onCanvasChange:n,runtime:o.runtime})}function oe({actions:e=un,chromeRenderer:t,onCanvasChange:n,runtime:s}){const o=Ut(n),a=Ut(null),c=jt(()=>a.current,[]),{canvas:l,productId:u,render:p}=s,h=p.onError??ne,f=jt(()=>l.tools.state.getSnapshot().isEditing,[l]);return o.current=n,zt(()=>(o.current?.(l),()=>o.current?.(null)),[l]),(({actions:e,canvas:t,getHostElement:n,isEditing:s,onError:o})=>{const r=Wt((e,t)=>{o(new Error(`Canvas action "${e.id}" failed.`,{cause:t}))}),i=Wt((e,n)=>{try{if(!e.isEnabled(t))return;if(n.preventDefault(),n.stopPropagation(),n.repeat&&!e.repeat)return;const s=e.run(t);s&&s.catch(t=>r(e,t))}catch(s){r(e,s)}}),a=Wt(e=>{const t=n(),o=e.composedPath()[0];return!t||!(o instanceof Element)||o.closest("[data-canvas-kit]")!==t||e.defaultPrevented||e.isComposing||229===e.keyCode||s()||Bt(o)||!!o.closest('[role="textbox"], [role="combobox"], [role="slider"], [role="spinbutton"]')||!!t.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]')||((e,t)=>{if("c"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return!1;const n=t.getSelection();return null!==n&&n.rangeCount>0&&!n.isCollapsed})(e,t.ownerDocument)});zt(()=>{const t=n();if(!t)return;const s=new Set,o={},r=new Map;for(const n of e){if(s.has(n.id))throw new Error(`Duplicate CanvasAction id "${n.id}".`);s.add(n.id);for(const e of A(n.shortcut)){const t=P(e),s=JSON.stringify(I(t).map(([e,t,n])=>[[...e].sort(),t,String(n).toLowerCase()])),a=r.get(s);if(a&&a!==n.id)throw new Error(`Canvas shortcut "${t}" is assigned to both "${a}" and "${n.id}".`);a||(r.set(s,n.id),o[t]=e=>i(n,e))}}return function(e,t,n={}){let s=n.event??"keydown",o=((e,t={})=>{let n=t.timeout??1e3,s=t.ignore??E,o=Object.keys(e).map(t=>[t,I(t),e[t]]),r=new Map,i=null;return e=>{if(!(e=>!!(e.key&&e.code&&e.getModifierState))(e)||s(e))return;let t=[];for(let[n,s,i]of o){let o=r.get(n),[a,...c]=o||s;if(k(e,a))if(c.length>0)r.set(n,c),t.push(n);else{if(r.delete(n),!t.length){i(e);break}console.warn(`tinykeys: Conflict found, "${n}" did not fire, waiting for:`,t)}else C(e,e.key)||r.delete(n)}i&&clearTimeout(i),i=setTimeout(()=>r.clear(),n)}})(t,n);return e.addEventListener(s,o,n.capture),()=>{e.removeEventListener(s,o,n.capture)}}(t,o,{ignore:a})},[e,n])})({actions:e,canvas:l,getHostElement:c,isEditing:f,onError:h}),Xt(d,{canvas:l,children:Xt(r,{children:Xt("div",{ref:a,"data-ui":"app-shell","data-canvas-kit":u,className:"land-canvas-kit__shell",children:Jt("main",{"data-ui":"workspace-viewport",className:"land-canvas-kit__viewport",children:[
5
+ Xt(S,{bindings:p,getHostElement:c,onError:h}),t?.(l)??null,
6
+ Xt(i,{})]})})})})}function re(){return"undefined"==typeof indexedDB?Promise.resolve(null):(hn||(hn=new Promise((e,t)=>{const n=indexedDB.open("canvas-kit.persistence",2);n.addEventListener("upgradeneeded",()=>{var e;(e=n.result).objectStoreNames.contains("snapshots")||e.createObjectStore(pn)}),n.addEventListener("success",()=>{const t=n.result;t.addEventListener("versionchange",()=>{t.close(),hn=null}),e(t)}),n.addEventListener("error",()=>{hn=null,t(n.error)})})),hn)}function ie(e={}){return{async load({signal:t}){t.throwIfAborted();const n=await ce(e);return t.throwIfAborted(),n},saveDocument:t=>ae({documentSnapshot:JSON.stringify(t),sessionSnapshot:null},e),saveSession:t=>ae({documentSnapshot:null,sessionSnapshot:JSON.stringify(t)},e)}}async function ae(e,t){const n=[];null!==e.documentSnapshot&&n.push([ue(t),e.documentSnapshot]),null!==e.sessionSnapshot&&n.push([pe(t),e.sessionSnapshot]),0!==n.length&&await(async(e,t)=>{if(0===t.length)return;const n=await re();n&&await new Promise((s,o)=>{const r=n.transaction(e,"readwrite"),i=r.objectStore(e);r.addEventListener("complete",()=>s()),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error));for(const[e,n]of t)i.put(n,e)})})(pn,n)}async function ce(e={}){const[t,n]=await fe([ue(e),pe(e)]);return{documentSnapshot:t,sessionSnapshot:n}}async function le(){return he(fn)}async function de(){return he(mn)}function ue(e){return e.storageNamespace?`${e.storageNamespace}.document`:fn}function pe(e){return e.storageNamespace?`${e.storageNamespace}.session`:mn}async function he(e){const[t]=await fe([e]);return t??null}async function fe(e){return(await(async(e,t)=>{if(0===t.length)return[];const n=await re();return n?new Promise((s,o)=>{const r=n.transaction(e,"readonly"),i=r.objectStore(e),a=new Array(t.length).fill(null);r.addEventListener("complete",()=>s(a)),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error)),t.forEach((e,t)=>{const n=i.get(e);n.addEventListener("success",()=>{a[t]=n.result??null}),n.addEventListener("error",()=>o(n.error))})}):null})("snapshots",e)??e.map(()=>null)).map(me)}function me(e){if(null==e)return null;if("string"!=typeof e)throw new Error("Persisted canvas snapshot is not a JSON string.");try{return JSON.parse(e)}catch(t){throw new Error("Persisted canvas snapshot contains invalid JSON.",{cause:t})}}function ge({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){const s=a();return s?Zt(Xt("div",{"data-ui":n,className:ve("land-canvas__floating-toolbar-layer",t),children:e}),s):null}function ve(...e){return e.filter(Boolean).join(" ")}function we(e,t){return"function"==typeof e?e(t):e}function ye(e){return e.split("-")[0]}function be(e){return e.split("-")[1]}function xe(e){return"y"===e?"height":"width"}function Se(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function Ee(e){return"x"===Se(e)?"y":"x"}function Ce(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}function Ie(e){const t=ye(e);return xn[t]+e.slice(t.length)}function ke(e){const{x:t,y:n,width:s,height:o}=e;return{width:s,height:o,top:n,left:t,right:t+s,bottom:n+o,x:t,y:n}}function Pe(e,t,n){let{reference:s,floating:o}=e;const r=Se(t),i=Ee(t),a=xe(i),c=ye(t),l="y"===r,d=s.x+s.width/2-o.width/2,u=s.y+s.height/2-o.height/2,p=s[a]/2-o[a]/2;let h;switch(c){case"top":h={x:d,y:s.y-o.height};break;case"bottom":h={x:d,y:s.y+s.height};break;case"right":h={x:s.x+s.width,y:u};break;case"left":h={x:s.x-o.width,y:u};break;default:h={x:s.x,y:s.y}}switch(be(t)){case"start":h[i]-=p*(n&&l?-1:1);break;case"end":h[i]+=p*(n&&l?-1:1)}return h}async function Te(e,t){var n;void 0===t&&(t={});const{x:s,y:o,platform:r,rects:i,elements:a,strategy:c}=e,{boundary:l="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=we(t,e),f=(e=>"number"!=typeof e?(e=>({top:0,right:0,bottom:0,left:0,...e}))(e):{top:e,right:e,bottom:e,left:e})(h),m=a[p?"floating"===u?"reference":"floating":u],g=ke(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(m)))||n?m:m.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(a.floating)),boundary:l,rootBoundary:d,strategy:c})),v="floating"===u?{x:s,y:o,width:i.floating.width,height:i.floating.height}:i.reference,w=await(null==r.getOffsetParent?void 0:r.getOffsetParent(a.floating)),y=await(null==r.isElement?void 0:r.isElement(w))&&await(null==r.getScale?void 0:r.getScale(w))||{x:1,y:1},b=ke(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:w,strategy:c}):v);return{top:(g.top-b.top+f.top)/y.y,bottom:(b.bottom-g.bottom+f.bottom)/y.y,left:(g.left-b.left+f.left)/y.x,right:(b.right-g.right+f.right)/y.x}}function Ae(){return"undefined"!=typeof window}function Re(e){return De(e)?(e.nodeName||"").toLowerCase():"#document"}function Le(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Me(e){var t;return null==(t=(De(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function De(e){return!!Ae()&&(e instanceof Node||e instanceof Le(e).Node)}function Oe(e){return!!Ae()&&(e instanceof Element||e instanceof Le(e).Element)}function Fe(e){return!!Ae()&&(e instanceof HTMLElement||e instanceof Le(e).HTMLElement)}function Be(e){return!(!Ae()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Le(e).ShadowRoot)}function $e(e){const{overflow:t,overflowX:n,overflowY:s,display:o}=We(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+n)&&"inline"!==o&&"contents"!==o}function Ne(e){return/^(table|td|th)$/.test(Re(e))}function He(e){try{if(e.matches(":popover-open"))return!0}catch(t){}try{return e.matches(":modal")}catch(t){return!1}}function je(e){const t=Oe(e)?We(e):e;return An(t.transform)||An(t.translate)||An(t.scale)||An(t.rotate)||An(t.perspective)||!Ke()&&(An(t.backdropFilter)||An(t.filter))||Pn.test(t.willChange||"")||Tn.test(t.contain||"")}function Ke(){return null==Gt&&(Gt="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Gt}function ze(e){return/^(html|body|#document)$/.test(Re(e))}function We(e){return Le(e).getComputedStyle(e)}function qe(e){return Oe(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Ue(e){if("html"===Re(e))return e;const t=e.assignedSlot||e.parentNode||Be(e)&&e.host||Me(e);return Be(t)?t.host:t}function Ve(e){const t=Ue(e);return ze(t)?e.ownerDocument?e.ownerDocument.body:e.body:Fe(t)&&$e(t)?t:Ve(t)}function Ye(e,t,n){var s;void 0===t&&(t=[]),void 0===n&&(n=!0);const o=Ve(e),r=o===(null==(s=e.ownerDocument)?void 0:s.body),i=Le(o);if(r){const e=_e(i);return t.concat(i,i.visualViewport||[],$e(o)?o:[],e&&n?Ye(e):[])}return t.concat(o,Ye(o,[],n))}function _e(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Xe(e){const t=We(e);let n=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Fe(e),r=o?e.offsetWidth:n,i=o?e.offsetHeight:s,a=wn(n)!==r||wn(s)!==i;return a&&(n=r,s=i),{width:n,height:s,$:a}}function Je(e){return Oe(e)?e:e.contextElement}function Ze(e){const t=Je(e);if(!Fe(t))return bn(1);const n=t.getBoundingClientRect(),{width:s,height:o,$:r}=Xe(t);let i=(r?wn(n.width):n.width)/s,a=(r?wn(n.height):n.height)/o;return i&&Number.isFinite(i)||(i=1),a&&Number.isFinite(a)||(a=1),{x:i,y:a}}function Ge(e){const t=Le(e);return Ke()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:Rn}function Qe(e,t,n,s){void 0===t&&(t=!1),void 0===n&&(n=!1);const o=e.getBoundingClientRect(),r=Je(e);let i=bn(1);t&&(s?Oe(s)&&(i=Ze(s)):i=Ze(e));const a=((e,t,n)=>(void 0===t&&(t=!1),!(!n||t&&n!==Le(e))&&t))(r,n,s)?Ge(r):bn(0);let c=(o.left+a.x)/i.x,l=(o.top+a.y)/i.y,d=o.width/i.x,u=o.height/i.y;if(r){const e=Le(r),t=s&&Oe(s)?Le(s):s;let n=e,o=_e(n);for(;o&&s&&t!==n;){const e=Ze(o),t=o.getBoundingClientRect(),s=We(o),r=t.left+(o.clientLeft+parseFloat(s.paddingLeft))*e.x,i=t.top+(o.clientTop+parseFloat(s.paddingTop))*e.y;c*=e.x,l*=e.y,d*=e.x,u*=e.y,c+=r,l+=i,n=Le(o),o=_e(n)}}return ke({width:d,height:u,x:c,y:l})}function et(e,t){const n=qe(e).scrollLeft;return t?t.left+n:Qe(Me(e)).left+n}function tt(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-et(e,n),y:n.top+t.scrollTop}}function nt(e,t,n){let s;if("viewport"===t)s=((e,t)=>{const n=Le(e),s=Me(e),o=n.visualViewport;let r=s.clientWidth,i=s.clientHeight,a=0,c=0;if(o){r=o.width,i=o.height;const e=Ke();(!e||e&&"fixed"===t)&&(a=o.offsetLeft,c=o.offsetTop)}const l=et(s);if(l<=0){const e=s.ownerDocument,t=e.body,n=getComputedStyle(t),o="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(s.clientWidth-t.clientWidth-o);i<=25&&(r-=i)}else l<=25&&(r+=l);return{width:r,height:i,x:a,y:c}})(e,n);else if("document"===t)s=(e=>{const t=Me(e),n=qe(e),s=e.ownerDocument.body,o=vn(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),r=vn(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let i=-n.scrollLeft+et(e);const a=-n.scrollTop;return"rtl"===We(s).direction&&(i+=vn(t.clientWidth,s.clientWidth)-o),{width:o,height:r,x:i,y:a}})(Me(e));else if(Oe(t))s=((e,t)=>{const n=Qe(e,!0,"fixed"===t),s=n.top+e.clientTop,o=n.left+e.clientLeft,r=Fe(e)?Ze(e):bn(1);return{width:e.clientWidth*r.x,height:e.clientHeight*r.y,x:o*r.x,y:s*r.y}})(t,n);else{const n=Ge(e);s={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return ke(s)}function st(e,t){const n=Ue(e);return!(n===t||!Oe(n)||ze(n))&&("fixed"===We(n).position||st(n,t))}function ot(e,t){const n=t.get(e);if(n)return n;let s=Ye(e,[],!1).filter(e=>Oe(e)&&"body"!==Re(e)),o=null;const r="fixed"===We(e).position;let i=r?Ue(e):e;for(;Oe(i)&&!ze(i);){const t=We(i),n=je(i);n||"fixed"!==t.position||(o=null),(r?!n&&!o:!n&&"static"===t.position&&o&&("absolute"===o.position||"fixed"===o.position)||$e(i)&&!n&&st(e,i))?s=s.filter(e=>e!==i):o=t,i=Ue(i)}return t.set(e,s),s}function rt(e,t,n){function s(){l.x=et(r)}const o=Fe(t),r=Me(t),i="fixed"===n,a=Qe(e,!0,i,t);let c={scrollLeft:0,scrollTop:0};const l=bn(0);if(o||!o&&!i)if(("body"!==Re(t)||$e(r))&&(c=qe(t)),o){const e=Qe(t,!0,i,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}else r&&s();i&&!o&&r&&s();const d=!r||o||i?bn(0):tt(r,c);return{x:a.left+c.scrollLeft-l.x-d.x,y:a.top+c.scrollTop-l.y-d.y,width:a.width,height:a.height}}function it(e){return"static"===We(e).position}function at(e,t){if(!Fe(e)||"fixed"===We(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Me(e)===n&&(n=n.ownerDocument.body),n}function ct(e,t){const n=Le(e);if(He(e))return n;if(!Fe(e)){let t=Ue(e);for(;t&&!ze(t);){if(Oe(t)&&!it(t))return t;t=Ue(t)}return n}let s=at(e,t);for(;s&&Ne(s)&&it(s);)s=at(s,t);return s&&ze(s)&&it(s)&&!je(s)?n:s||(e=>{let t=Ue(e);for(;Fe(t)&&!ze(t);){if(je(t))return t;if(He(t))return null;t=Ue(t)}return null})(e)||n}function lt(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function dt({viewport:e,fallbackPlacements:t,floatingRef:n,getReferenceElement:s,onPlacementChange:o,offset:r,placement:i,visible:a=!0}){zt(()=>{const c=s(),l=n.current;if(!c||!l)return;let d=!1,u=0;l.style.visibility="hidden";const p=()=>{const e=++u,n=pt("--toolbar-floating-collision-padding",8);((e,t,n)=>{const s={platform:Ln,...n},o={...s.platform,_c:new Map};return(async(e,t,n)=>{const{placement:s="bottom",strategy:o="absolute",middleware:r=[],platform:i}=n,a=i.detectOverflow?i:{...i,detectOverflow:Te},c=await(null==i.isRTL?void 0:i.isRTL(t));let l=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:u}=Pe(l,s,c),p=s,h=0;const f={};for(let m=0;m<r.length;m++){const n=r[m];if(!n)continue;const{name:g,fn:v}=n,{x:w,y:y,data:b,reset:x}=await v({x:d,y:u,initialPlacement:s,placement:p,strategy:o,middlewareData:f,rects:l,platform:a,elements:{reference:e,floating:t}});d=null!=w?w:d,u=null!=y?y:u,f[g]={...f[g],...b},x&&h<50&&(h++,"object"==typeof x&&(x.placement&&(p=x.placement),x.rects&&(l=!0===x.rects?await i.getElementRects({reference:e,floating:t,strategy:o}):x.rects),({x:d,y:u}=Pe(l,p,c))),m=-1)}return{x:d,y:u,placement:p,strategy:o,middlewareData:f}})(e,t,{...s,platform:o})})(c,l,{strategy:"fixed",placement:i,middleware:ut({fallbackPlacements:t,offset:r??pt("--toolbar-floating-offset",38),padding:{top:pt("--toolbar-floating-safe-top",64),right:n,bottom:n,left:n}})}).then(({placement:t,x:n,y:s})=>{d||e!==u||(l.dataset.placement=t,o?.(t),l.style.transform=`translate3d(${Math.round(n)}px, ${Math.round(s)}px, 0)`,l.style.visibility=a?"visible":"hidden")})},h=function(e,t,n,s){void 0===s&&(s={});const{ancestorScroll:o=!0,ancestorResize:r=!0,elementResize:i="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=s,l=Je(e),d=o||r?[...l?Ye(l):[],...t?Ye(t):[]]:[];d.forEach(e=>{o&&e.addEventListener("scroll",n,{passive:!0}),r&&e.addEventListener("resize",n)});const u=l&&a?((e,t)=>{function n(){var e;clearTimeout(s),null==(e=o)||e.disconnect(),o=null}let s,o=null;const r=Me(e);return function i(a,c){function l(t){const n=t[0].intersectionRatio;if(n!==c){if(!g)return i();n?i(!1,n):s=setTimeout(()=>{i(!1,1e-7)},1e3)}1!==n||lt(d,e.getBoundingClientRect())||i(),g=!1}void 0===a&&(a=!1),void 0===c&&(c=1),n();const d=e.getBoundingClientRect(),{left:u,top:p,width:h,height:f}=d;if(a||t(),!h||!f)return;const m={rootMargin:-yn(p)+"px "+-yn(r.clientWidth-(u+h))+"px "+-yn(r.clientHeight-(p+f))+"px "+-yn(u)+"px",threshold:vn(0,gn(1,c))||1};let g=!0;try{o=new IntersectionObserver(l,{...m,root:r.ownerDocument})}catch(v){o=new IntersectionObserver(l,m)}o.observe(e)}(!0),n})(l,n):null;let p,h=-1,f=null;i&&(f=new ResizeObserver(e=>{let[s]=e;s&&s.target===l&&f&&t&&(f.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),l&&!c&&f.observe(l),t&&f.observe(t));let m=c?Qe(e):null;return c&&function t(){const s=Qe(e);m&&!lt(m,s)&&n(),m=s,p=requestAnimationFrame(t)}(),n(),()=>{var e;d.forEach(e=>{o&&e.removeEventListener("scroll",n),r&&e.removeEventListener("resize",n)}),u?.(),null==(e=f)||e.disconnect(),f=null,c&&cancelAnimationFrame(p)}}(c,l,p,{ancestorResize:!0,ancestorScroll:!0,elementResize:!0,layoutShift:!0}),f=e.subscribe(p);return p(),()=>{d=!0,l.style.visibility="hidden",h(),f()}},[e,t,n,s,o,r,i,a])}function ut({fallbackPlacements:e,offset:t,padding:n}){return[Mn(t),Dn({fallbackPlacements:[...e],padding:n})]}function pt(e,t){if("undefined"==typeof document)return t;const n=getComputedStyle(document.documentElement).getPropertyValue(e).trim();if(!n)return t;const s=Number.parseFloat(n);return Number.isFinite(s)?n.endsWith("rem")?16*s:s:t}function ht(e){const t=a();return t?Zt(Xt(ft,{...e}),t):null}function ft({fallbackPlacements:e=On,offset:t=8,placement:n="top",referenceElement:o,...r}){const i=u(),a=Ut(null),c=jt(()=>o,[o]);return s(a),dt({viewport:i.viewport.state,fallbackPlacements:e,floatingRef:a,getReferenceElement:c,offset:t,placement:n}),Xt("div",{...r,ref:a})}function mt(){return Kt($n)}function gt({children:e,className:t,dataUi:n="floating-selection-toolbar-slot",horizontalAlign:o="start",offset:r,visible:i=!0}){const a=u(),c=p(a.selection.state),l=p(a.viewport.state),d=Ut(null),h=Ut(null),[f,m]=Vt("center"===o?"top":"top-start"),g=c.pageBounds??(c.anchorPagePoint?{x:c.anchorPagePoint.x,y:c.anchorPagePoint.y,width:0,height:0}:null),v=i&&null!==g,w=v&&!c.isTranslating,y=jt(()=>d.current,[g?.height,g?.width,g?.x,g?.y]),b=jt(()=>d.current?.getBoundingClientRect()??null,[]),x=qt(()=>({placement:f,getContentBounds:b}),[g?.height,g?.width,g?.x,g?.y,b,f,l.pageTransform]);return s(h),dt({viewport:a.viewport.state,fallbackPlacements:"center"===o?Bn:Fn,floatingRef:h,getReferenceElement:y,onPlacementChange:m,offset:r,placement:"center"===o?"top":"top-start",visible:w}),v&&g?Jt(_t,{children:[Xt("div",{"data-ui":`${n}-page-space`,className:"land-canvas__floating-selection-page-space",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",transform:l.pageTransform,transformOrigin:"0 0"},children:Xt("div",{ref:d,"aria-hidden":"true",style:{position:"absolute",left:g.x,top:g.y,width:g.width,height:g.height,pointerEvents:"none"}})}),Xt("div",{ref:h,"data-ui":n,className:vt("land-canvas__floating-selection-anchor",t),style:{position:"fixed",left:0,top:0,visibility:"hidden",willChange:"transform"},children:Xt($n.Provider,{value:x,children:e})})]}):null}function vt(...e){return e.filter(Boolean).join(" ")}import{A as wt,B as yt,C as bt,D as xt,F as St,I as Et,L as Ct,M as It,N as kt,O as Pt,P as Tt,R as At,T as Rt,d as Lt,i as Mt,j as Dt,k as Ot,o as Ft,p as Bt,s as $t,z as Nt}from"./host-DL_DzXky.mjs";import{createContext as Ht,useCallback as jt,useContext as Kt,useEffect as zt,useEffectEvent as Wt,useMemo as qt,useRef as Ut,useState as Vt,useSyncExternalStore as Yt}from"react";import{Fragment as _t,jsx as Xt,jsxs as Jt}from"react/jsx-runtime";import{createPortal as Zt}from"react-dom";var Gt,Qt=Ht(null),en=Ht(null),tn=["Shift","Meta","Alt","Control"],nn="object"==typeof navigator?navigator.platform:"",sn=/Mac|iPod|iPhone|iPad/.test(nn)?"Meta":"Control",on="Win32"===nn?["Control","Alt"]:["Alt"],rn={state:"idle"},an=class{abortController=new AbortController;activeTasks=new Set;disposers=[];phase="starting";close=null;signal=this.abortController.signal;tasks={run:e=>this.runTask(e)};own(e,t){if("starting"!==this.phase)throw new Error("Cannot register a resource after the Canvas Runtime is published or disposal starts.");return this.disposers.push(n=>"function"==typeof t?t(e):"rollback"===n&&t.rollback?t.rollback(e):t.shutdown(e)),e}publish({beforeShutdown:e}={}){if("starting"!==this.phase)throw new Error(`Only a starting Canvas Runtime can be published; received runtime in "${this.phase}" phase.`);return this.phase="ready",()=>null!==this.close?"shutdown"===this.close.mode?this.close.result:Promise.reject(new Error("Cannot shut down a Canvas Runtime during rollback.")):this.beginClose({mode:"shutdown",beforeShutdown:e})}rollback(e){return null!==this.close?"rollback"===this.close.mode?this.close.result:Promise.reject(new Error("Cannot roll back a Canvas Runtime during shutdown.")):"starting"!==this.phase?Promise.reject(new Error(`Only a starting Canvas Runtime can roll back; received runtime in "${this.phase}" phase.`)):this.beginClose({mode:"rollback",cause:e})}beginClose(e){const t=[],n=Promise.resolve().then(async()=>{const n=[...t,...await this.disposeResources(e.mode)];if(this.phase="disposed","rollback"===e.mode){if(n.length>0)throw new AggregateError([e.cause,...n],"CanvasKit Runtime initialization failed and cleanup reported errors.",{cause:e.cause});throw e.cause}if(n.length>0)throw new AggregateError(n,"Failed to dispose one or more CanvasKit Runtime resources.")});if(this.close={mode:e.mode,result:n},"shutdown"===e.mode)try{e.beforeShutdown?.()}catch(s){t.push(s)}return this.phase="disposing",this.abortController.abort("rollback"===e.mode?e.cause:new DOMException("Canvas runtime is disposing.","AbortError")),n}runTask(e){if("ready"!==this.phase)throw new Error(`Canvas tasks require a ready runtime; received runtime in "${this.phase}" phase.`);this.signal.throwIfAborted();const t=Promise.resolve().then(()=>e(this.signal));return this.activeTasks.add(t),t.finally(()=>this.activeTasks.delete(t)).catch(()=>{}),t}async disposeResources(e){await Promise.allSettled([...this.activeTasks]);const t=[];for(;this.disposers.length>0;){const s=this.disposers.pop();try{await s(e)}catch(n){t.push(n)}}return t}},cn=[500,1e3,2e3,5e3],ln=class{editor;adapter;options;unsubscribeDocument=null;unsubscribeSession=null;unsubscribeFlushEvents=null;documentTimer=null;sessionTimer=null;pendingDocument=null;pendingSession=null;documentVersion=0;sessionVersion=0;documentRetryCount=0;sessionRetryCount=0;writeChain=Promise.resolve();flushChain=Promise.resolve();isRunning=!1;disposeMode=null;disposePromise=null;constructor(e,t,n={}){this.editor=e,this.adapter=t,this.options=n}start(){if(null!==this.disposeMode)throw new Error("Cannot start disposed canvas persistence.");this.isRunning||(this.isRunning=!0,this.adapter.saveDocument&&(this.unsubscribeDocument=this.editor.operations.subscribe(e=>{var t;this.documentVersion+=1,this.documentRetryCount=0,this.pendingDocument={snapshot:(t=e.snapshot,JSON.parse(JSON.stringify(t))),version:this.documentVersion},this.scheduleDocumentSave(200)})),this.adapter.saveSession&&(this.unsubscribeSession=this.editor.listen(e=>{var t,n;((t=e.diff).added.some(e=>"session"===e.scope)||t.updated.some(e=>"session"===e.before.scope||"session"===e.after.scope)||t.removed.some(e=>"session"===e.scope))&&(this.sessionVersion+=1,this.sessionRetryCount=0,this.pendingSession={snapshot:(n=this.editor.snapshots.getSession(),JSON.parse(JSON.stringify(n))),version:this.sessionVersion},this.scheduleSessionSave(200))})),this.unsubscribeFlushEvents=this.options.flushEvents?.subscribe(this.flushForHostLifecycle)??null)}flush(){if(null!==this.disposeMode)return Promise.reject(new Error("Cannot flush disposed canvas persistence."));const e=this.flushChain.then(()=>this.flushNow());return this.flushChain=e.catch(()=>{}),e}shutdown(){return this.dispose("shutdown")}rollback(){return this.dispose("rollback")}dispose(e){return null!==this.disposeMode?this.disposeMode!==e?Promise.reject(new Error(`Canvas persistence disposal already started in "${this.disposeMode}" mode.`)):this.disposePromise:(this.disposeMode=e,this.disposePromise=Promise.resolve().then(()=>"shutdown"===e?this.finishShutdown():this.finishRollback()),this.disposePromise)}async finishShutdown(){this.stopIntake(),await this.flushChain,await this.flushNow()}async finishRollback(){this.stopIntake(),this.discardPendingSnapshots(),await this.flushChain,await this.writeChain,this.discardPendingSnapshots()}stopIntake(){this.isRunning=!1,this.cancelDocumentTimer(),this.cancelSessionTimer(),this.unsubscribeDocument?.(),this.unsubscribeSession?.(),this.unsubscribeFlushEvents?.(),this.unsubscribeDocument=null,this.unsubscribeSession=null,this.unsubscribeFlushEvents=null}async flushNow(){const e=await this.flushPendingSnapshots();try{await(this.adapter.flush?.())}catch(t){e.push(t)}if(e.length>0)throw new AggregateError(e,"Failed to flush canvas persistence.")}async flushPendingSnapshots(){this.cancelDocumentTimer(),this.cancelSessionTimer();const e=this.savePendingDocument(),t=this.savePendingSession();return(await Promise.allSettled([e,t])).flatMap(e=>"rejected"===e.status?[e.reason]:[])}discardPendingSnapshots(){this.cancelDocumentTimer(),this.cancelSessionTimer(),this.pendingDocument=null,this.pendingSession=null}savePendingDocument(){const e=this.pendingDocument;if(!e||!this.adapter.saveDocument)return this.writeChain;this.pendingDocument=null;const t=this.queueWrite(()=>Promise.resolve(this.adapter.saveDocument(e.snapshot))).then(()=>{this.documentVersion===e.version&&(this.documentRetryCount=0)}).catch(t=>{throw this.documentVersion===e.version&&null===this.pendingDocument&&(this.pendingDocument=e,this.scheduleDocumentRetry()),t});return this.writeChain=t.catch(()=>{}),t}savePendingSession(){const e=this.pendingSession;if(!e||!this.adapter.saveSession)return this.writeChain;this.pendingSession=null;const t=this.queueWrite(()=>Promise.resolve(this.adapter.saveSession(e.snapshot))).then(()=>{this.sessionVersion===e.version&&(this.sessionRetryCount=0)}).catch(t=>{throw this.sessionVersion===e.version&&null===this.pendingSession&&(this.pendingSession=e,this.scheduleSessionRetry()),t});return this.writeChain=t.catch(()=>{}),t}queueWrite(e){return this.writeChain.then(e)}scheduleDocumentSave(e){this.cancelDocumentTimer(),this.documentTimer=setTimeout(()=>{this.documentTimer=null,this.savePendingDocument().catch(e=>{this.reportError("Could not persist canvas document.",e)})},e)}scheduleSessionSave(e){this.cancelSessionTimer(),this.sessionTimer=setTimeout(()=>{this.sessionTimer=null,this.savePendingSession().catch(e=>{this.reportError("Could not persist canvas session.",e)})},e)}scheduleDocumentRetry(){if(!this.isRunning||null!==this.documentTimer)return;const e=cn[this.documentRetryCount];void 0!==e&&(this.documentRetryCount+=1,this.scheduleDocumentSave(e))}scheduleSessionRetry(){if(!this.isRunning||null!==this.sessionTimer)return;const e=cn[this.sessionRetryCount];void 0!==e&&(this.sessionRetryCount+=1,this.scheduleSessionSave(e))}cancelDocumentTimer(){null!==this.documentTimer&&(clearTimeout(this.documentTimer),this.documentTimer=null)}cancelSessionTimer(){null!==this.sessionTimer&&(clearTimeout(this.sessionTimer),this.sessionTimer=null)}flushForHostLifecycle=()=>{this.flush().catch(e=>{this.reportError("Could not persist canvas snapshot.",e)})};reportError(e,t){try{this.options.onError?.(new Error(e,{cause:t}))}catch{}}},dn={status:"starting"},un=[],pn="snapshots",hn=null,fn="canvas-kit.document",mn="canvas-kit.session",gn=Math.min,vn=Math.max,wn=Math.round,yn=Math.floor,bn=e=>({x:e,y:e}),xn={left:"right",right:"left",bottom:"top",top:"bottom"},Sn=["left","right"],En=["right","left"],Cn=["top","bottom"],In=["bottom","top"],kn=new Set(["left","top"]),Pn=/transform|translate|scale|rotate|perspective|filter/,Tn=/paint|layout|strict|content/,An=e=>!!e&&"none"!==e,Rn=bn(0),Ln={convertOffsetParentRelativeRectToViewportRelativeRect:e=>{let{elements:t,rect:n,offsetParent:s,strategy:o}=e;const r="fixed"===o,i=Me(s),a=!!t&&He(t.floating);if(s===i||a&&r)return n;let c={scrollLeft:0,scrollTop:0},l=bn(1);const d=bn(0),u=Fe(s);if((u||!u&&!r)&&(("body"!==Re(s)||$e(i))&&(c=qe(s)),u)){const e=Qe(s);l=Ze(s),d.x=e.x+s.clientLeft,d.y=e.y+s.clientTop}const p=!i||u||r?bn(0):tt(i,c);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+d.x+p.x,y:n.y*l.y-c.scrollTop*l.y+d.y+p.y}},getDocumentElement:Me,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:s,strategy:o}=e;const r=[..."clippingAncestors"===n?He(t)?[]:ot(t,this._c):[].concat(n),s],i=nt(t,r[0],o);let a=i.top,c=i.right,l=i.bottom,d=i.left;for(let u=1;u<r.length;u++){const e=nt(t,r[u],o);a=vn(e.top,a),c=gn(e.right,c),l=gn(e.bottom,l),d=vn(e.left,d)}return{width:c-d,height:l-a,x:d,y:a}},getOffsetParent:ct,getElementRects:async function(e){const t=this.getOffsetParent||ct,n=this.getDimensions,s=await n(e.floating);return{reference:rt(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}},getClientRects:e=>Array.from(e.getClientRects()),getDimensions:e=>{const{width:t,height:n}=Xe(e);return{width:t,height:n}},getScale:Ze,isElement:Oe,isRTL:e=>"rtl"===We(e).direction},Mn=e=>(void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var n,s;const{x:o,y:r,placement:i,middlewareData:a}=t,c=await(async(e,t)=>{const{placement:n,platform:s,elements:o}=e,r=await(null==s.isRTL?void 0:s.isRTL(o.floating)),i=ye(n),a=be(n),c="y"===Se(n),l=kn.has(i)?-1:1,d=r&&c?-1:1,u=we(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:f}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&"number"==typeof f&&(h="end"===a?-1*f:f),c?{x:h*d,y:p*l}:{x:p*l,y:h*d}})(t,e);return i===(null==(n=a.offset)?void 0:n.placement)&&null!=(s=a.arrow)&&s.alignmentOffset?{}:{x:o+c.x,y:r+c.y,data:{...c,placement:i}}}}),Dn=e=>(void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,s;const{placement:o,middlewareData:r,rects:i,initialPlacement:a,platform:c,elements:l}=t,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...g}=we(e,t);if(null!=(n=r.arrow)&&n.alignmentOffset)return{};const v=ye(o),w=Se(a),y=ye(a)===a,b=await(null==c.isRTL?void 0:c.isRTL(l.floating)),x=p||(y||!m?[Ie(a)]:(e=>{const t=Ie(e);return[Ce(e),t,Ce(t)]})(a)),S="none"!==f;!p&&S&&x.push(...function(e,t,n,s){const o=be(e);let r=((e,t,n)=>{switch(e){case"top":case"bottom":return n?t?En:Sn:t?Sn:En;case"left":case"right":return t?Cn:In;default:return[]}})(ye(e),"start"===n,s);return o&&(r=r.map(e=>e+"-"+o),t&&(r=r.concat(r.map(Ce)))),r}(a,m,f,b));const E=[a,...x],C=await c.detectOverflow(t,g),I=[];let k=(null==(s=r.flip)?void 0:s.overflows)||[];if(d&&I.push(C[v]),u){const e=((e,t,n)=>{void 0===n&&(n=!1);const s=be(e),o=Ee(e),r=xe(o);let i="x"===o?s===(n?"end":"start")?"right":"left":"start"===s?"bottom":"top";return t.reference[r]>t.floating[r]&&(i=Ie(i)),[i,Ie(i)]})(o,i,b);I.push(C[e[0]],C[e[1]])}if(k=[...k,{placement:o,overflows:I}],!I.every(e=>e<=0)){var P,T;const e=((null==(P=r.flip)?void 0:P.index)||0)+1,t=E[e];if(t&&("alignment"!==u||w===Se(t)||k.every(e=>Se(e.placement)!==w||e.overflows[0]>0)))return{data:{index:e,overflows:k},reset:{placement:t}};let n=null==(T=k.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:T.placement;if(!n)switch(h){case"bestFit":{var A;const e=null==(A=k.filter(e=>{if(S){const t=Se(e.placement);return t===w||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:A[0];e&&(n=e);break}case"initialPlacement":n=a}if(o!==n)return{reset:{placement:n}}}return{}}}),On=["bottom"],Fn=["bottom-start"],Bn=["bottom"],$n=Ht(null);export{ht as CanvasKitFloatingContent,ge as CanvasKitFloatingToolbarLayer,d as CanvasKitProvider,se as CanvasKitRoot,gt as FloatingSelectionToolbarPageSpace,R as applyCanvasActionShortcutOverrides,t as createCanvasApiToken,Dt as createCustomShapeColor,ie as createLocalSnapshotPersistence,It as createThemeShapeColor,e as defineCanvasPlugin,T as formatCanvasActionShortcut,A as getCanvasActionShortcuts,kt as getThemeColorTokenName,Tt as isCustomShapeColorRef,St as isThemeShapeColorRef,le as readPersistedDocumentSnapshot,ce as readPersistedEditorSnapshots,de as readPersistedSessionSnapshot,n as requireApi,Et as resolveShapeColor,Ct as shapeColorToCssColor,u as useCanvasKit,c as useCanvasKitFloatingPortalContainer,s as useCanvasKitWheelCapture,p as useCanvasValue,mt as useFloatingSelectionToolbarPosition};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yuzhouu/canvas-kit",
3
- "version": "0.1.21",
3
+ "version": "0.1.22",
4
4
  "description": "Extensible Land canvas runtime, React product primitives, and typed API surface.",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
@@ -1 +1 @@
1
- import{C as s,S as a,T as o,_ as m,a as r,b as t,c as p,d as f,f as h,g as i,h as x,i as b,l as c,m as d,n as e,o as g,p as j,r as l,s as n,t as u,u as v,v as w,w as y,x as C,y as S}from"./host-C9sTNI4D.mjs";export{d as BindingSegmentsOverlay,b as CANVAS_SURFACE_DATA_UI,r as CANVAS_SURFACE_SELECTOR,l as Canvas,w as CanvasRenderBindingsContext,j as DefaultGrid,y as EditorContext,s as PageSpace,x as SHAPE_HOVER_STROKE,i as SHAPE_HOVER_STROKE_WIDTH,u as ShapeHeadingControl,a as createCanvasRenderBindings,e as createShapeHeadingDomEventGuard,g as forwardWheelEventToCanvasSurface,n as getCanvasSurfaceElement,p as getCanvasSurfaceElementForNode,c as getCanvasSurfacePagePoint,v as getCanvasSurfaceScreenPoint,f as getEditableEventTarget,h as isEditableEventTarget,S as useCanvasOverlays,t as useCanvasRenderBindings,C as useCanvasRenderers,o as useEditor,m as useValue};
1
+ import{C as s,E as a,S as o,T as m,_ as r,a as t,b as p,c as f,d as h,f as i,g as x,h as b,i as c,l as d,m as e,n as g,o as j,p as l,r as n,s as u,t as v,u as w,v as y,w as C,x as E,y as S}from"./host-DL_DzXky.mjs";export{b as BindingSegmentsOverlay,t as CANVAS_SURFACE_DATA_UI,j as CANVAS_SURFACE_SELECTOR,c as Canvas,S as CanvasRenderBindingsContext,e as DefaultGrid,m as EditorContext,C as PageSpace,x as SHAPE_HOVER_STROKE,r as SHAPE_HOVER_STROKE_WIDTH,v as ShapeHeadingControl,n as ShapeHoverRect,s as createCanvasRenderBindings,g as createShapeHeadingDomEventGuard,u as forwardWheelEventToCanvasSurface,f as getCanvasSurfaceElement,d as getCanvasSurfaceElementForNode,w as getCanvasSurfacePagePoint,h as getCanvasSurfaceScreenPoint,i as getEditableEventTarget,l as isEditableEventTarget,p as useCanvasOverlays,E as useCanvasRenderBindings,o as useCanvasRenderers,a as useEditor,y as useValue};