@yuzhouu/canvas-kit 0.1.17 → 0.1.18

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
@@ -3,4 +3,4 @@ return Wt(Yt.Provider,{value:o,children:e})}function i(){const{registerTarget:e}
3
3
  return Wt(Xt.Provider,{value:e,children:t})}function u(){const e=Nt(Xt);if(!e)throw new Error("useCanvasKit must be used inside CanvasKitProvider.");return e}function p(e){return zt(e.subscribe,e.getSnapshot,e.getSnapshot)}function h({contributions:e,getHostElement:t,isEditing:n,onError:s,screenToPage:o}){return $t(()=>{const r=o=>{if(!y(t(),o)||n()||Pt(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()||Pt(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()||Pt(r.target))return;const a=m(e,v(r.dataTransfer)),c=w({source:"drop",dataTransfer:r.dataTransfer,pagePoint:o(Dt(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(Tt);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=Bt(()=>s.tools.state.getSnapshot().isEditing,[s]),d=Bt(e=>r.viewport.screenToPage(e),[r]);
4
4
  return qt(Vt,{children:[Wt(ft.Provider,{value:r,children:Wt(Lt,{onContextMenuRequest:c,renderBindings:a,showGrid:o})}),Wt(h,{contributions:i,getHostElement:t,isEditing:l,onError:n,screenToPage:d})]})}function E(e){return void 0===e?[]:Array.isArray(e)?e:[e]}function I(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 C(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 T(e,t){return new Set((e.requires??[]).flatMap(e=>{const n=t.get(e.id);return n?.api?[n.api.id]:[]}))}function P(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 k(e){return"provider"===e.kind}function R(e){return"svg-inliner"===e.kind}function A(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 L(){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 D(e){return{id:e.id,name:e.name,index:e.index,meta:{...e.meta}}}function M(e){return{id:e?.id??"document:main",meta:{...e?.meta??{}}}}function O(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 F(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 B(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 N(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 $({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:z(o,n,a.id),isEffectivelyLocked:V(n,a.id)}}function H({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 K(e,t){return e.childShapesByParentId.get(t)??[]}function j(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 z(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 V(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 W(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 q({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 Ct(n,{get:e,graph:s},()=>{const e=a();Object.is(o,e)||(o=e,t())},{fireImmediately:!1})}}}function U({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=>O(e,t.layers.getPageId(e.id))),i=e=>{const[n,...s]=e;return(({bindings:e,editor:t,pageId:n,shapes:s})=>{const o=[],r=H({bindings:e,editor:t,shapes:s}),i=(e,s)=>{K(r,e).forEach((e,a)=>{const c=K(r,e.id).map(e=>e.id);o.push($({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(It),editor:t,pageId:n,shapes:s.filter(Ot)})},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}=W(!1),{readable:u,set:p}=W(null),h=q({signals:t.signals,name:"CanvasKit.document",getDependencies:()=>[t.document.getMetadata()],getSnapshot:([e])=>M(e)}),f=q({signals:t.signals,name:"CanvasKit.document.readonlyState",getDependencies:()=>[t.state.readonly.get()],getSnapshot:([e])=>e}),m=q({signals:t.signals,name:"CanvasKit.session",getDependencies:()=>[t.state.session.get().meta],getSnapshot:([e])=>({meta:{...e}})}),g=q({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=>O(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})}),v=q({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(D),o=s.find(e=>e.id===t)??null;return{pages:s,currentPage:o,currentPageId:t,currentPageShapeIds:[...n],canDeleteCurrentPage:s.length>1&&null!==o}}}),w=q({signals:t.signals,name:"CanvasKit.history",getDependencies:()=>[t.state.history.get()],getSnapshot:([e])=>({...e})}),y=q({signals:t.signals,name:"CanvasKit.viewport",getDependencies:()=>[t.state.camera.get(),t.state.pageTransform.get()],getSnapshot:([e,t])=>({camera:{...e},zoom:e.z,pageTransform:t.toCssString()})}),b=q({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})}),x=q({signals:t.signals,name:"CanvasKit.layers",getDependencies:()=>_(t,t.pages.getCurrentId()),getSnapshot:i});return{canvas:{startup:o,api:t=>e.get(t)??void 0,document:{state:h,readonlyState:f,getSnapshot:()=>(e=>{const{editor:t}=e,n=t.state.tool.get().activeToolId;return e.assertToolId(n),{productId:e.productId,document:M(t.document.getMetadata()),pageId:t.pages.getCurrentId(),activeToolId:n,selectedShapeIds:[...t.selection.getIds()],shapeCount:t.state.currentPageShapeIds.get().length,session:F(e)}})(c),updateMeta:e=>(t.document.updateMetadata({...e},"user"),M(t.document.getMetadata()))},session:{state:m,updateMeta(e){const n=t.session.get();return t.session.update({meta:{...n.meta,...e}},"user"),{meta:{...t.state.session.get().meta}}}},selection:{state:g,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:v,create:e=>D(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:w,clear:()=>t.history.clear(),undo:()=>t.history.undo(),redo:()=>t.history.redo()},viewport:{state:y,grid:{state:l,setVisible:d,toggle:()=>d(!l.getSnapshot())},setCamera:(e,n)=>t.commands.setCamera({pageId:n,camera:e},{source:"user"}),zoomIn:()=>t.viewport.zoomAtCenter(-120,"system"),zoomOut:()=>t.viewport.zoomAtCenter(120,"system"),resetZoom:()=>t.viewport.resetZoom("user"),reset:()=>t.commands.setCamera({camera:{x:0,y:0,z:1}},{source:"user"})},tools:{state:b,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(B),{source:"user"}).map(e=>e.id))(t,e),get:e=>{const n=t.shapes.get(e);return n?O(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(N);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:x,getTree:e=>i(_(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=H({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=K(r,a.parentId);return $({childIds:K(r,a.id).map(e=>e.id),companionIds:r.companionIdsByRootId.get(a.id)??[],context:r,depth:j(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 _(e,t){const n=e.shapes.getForPage(t),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 Y(){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 X(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);A(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 A(s.map(({id:e})=>e),"editor plugin id"),A(n.flatMap(e=>e.api?[e.api.id]:[]),"canvas API token"),{canvasPlugins:n,editorPlugins:s,renderPlugins:o}}(e.plugins),r=Mt(o),i=new Gt,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=Rt({cameraAnimationScheduler:L(),documentMeta:e.documentMeta,onUnhandledError:e.onUnhandledError,plugins:e.editorPlugins,resolveAssetUrl:e.resolveAssetUrl});return t.tools.register("select",e=>new gt(e)),t.tools.register("hand",e=>new mt(e)),t.tools.syncLockedState(t.state.tool.get().isToolLocked),t.commands.setActiveTool("select",{source:"system"}),t.history.clear(),t})({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 Qt(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:T(c,r),ownerLabel:`Canvas plugin "${c.id}" setup`}),tasks:s.tasks});t&&(s.own(t,e=>e.dispose?.()),i.push({plugin:c,instance:t})),C(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 P(t.map(({id:e})=>e),"import contribution"),P(n.map(({id:e})=>e),"export contribution"),P(n.flatMap(e=>"provider"===e.kind?[e.format]:[]),"export format"),P(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(Y(),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(k),o=t.filter(R),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=Jt,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(Jt)}}),dispose(){a||(a=!0,l(Jt),c.clear())}}}({editor:d,contributions:f,tasks:i.tasks}),e=>e.dispose());i.signal.throwIfAborted();const{canvas:w,host:y}=U({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 J(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}function G({actions:e=tn,chromeRenderer:t,onCanvasChange:n,options:s}){const o=(e=>{const[t,n]=jt(null);return $t(()=>{let t=!0,s=null;const o=new AbortController,r=e.onError??J;return n({options:e,state:en}),X(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:en})(s);if("error"===o.status)throw o.error;return"ready"!==o.status?null:Wt(Z,{actions:e,chromeRenderer:t,onCanvasChange:n,runtime:o.runtime})}function Z({actions:e=tn,chromeRenderer:t,onCanvasChange:n,runtime:s}){const o=Kt(n),a=Kt(null),c=Bt(()=>a.current,[]),{canvas:l,productId:u,render:p}=s,h=p.onError??J,f=Bt(()=>l.tools.state.getSnapshot().isEditing,[l]);return o.current=n,$t(()=>(o.current?.(l),()=>o.current?.(null)),[l]),function({actions:e,canvas:t,isEditing:n,onError:s}){$t(()=>{(e=>{const t=new Set;for(const n of e){if(t.has(n.id))throw new Error(`Duplicate CanvasAction id "${n.id}".`);t.add(n.id)}})(e);const o=o=>{if(n()||Pt(o.target))return;const r={key:o.key,shiftKey:o.shiftKey,altKey:o.altKey,ctrlKey:o.ctrlKey,metaKey:o.metaKey,accelKey:o.metaKey||o.ctrlKey},i=e.find(e=>void 0!==e.shortcut&&E(e.shortcut).some(e=>St(e,r)));if(!i)return;if(o.preventDefault(),o.stopPropagation(),!i.isEnabled(t))return;let a;try{a=i.run(t)}catch(c){return void s(new Error(`Canvas action "${i.id}" failed.`,{cause:c}))}a instanceof Promise&&a.catch(e=>{s(new Error(`Canvas action "${i.id}" failed.`,{cause:e}))})};return window.addEventListener("keydown",o,!0),()=>window.removeEventListener("keydown",o,!0)},[e,t,n,s])}({actions:e,canvas:l,isEditing:f,onError:h}),Wt(d,{canvas:l,children:Wt(r,{children:Wt("div",{ref:a,"data-ui":"app-shell","data-canvas-kit":u,className:"land-canvas-kit__shell",children:qt("main",{"data-ui":"workspace-viewport",className:"land-canvas-kit__viewport",children:[
5
5
  Wt(S,{bindings:p,getHostElement:c,onError:h}),t?.(l)??null,
6
- Wt(i,{})]})})})})}function Q(){return"undefined"==typeof indexedDB?Promise.resolve(null):(sn||(sn=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(nn)}),n.addEventListener("success",()=>{const t=n.result;t.addEventListener("versionchange",()=>{t.close(),sn=null}),e(t)}),n.addEventListener("error",()=>{sn=null,t(n.error)})})),sn)}function ee(e={}){return{async load({signal:t}){t.throwIfAborted();const n=await ne(e);return t.throwIfAborted(),n},saveDocument:t=>te({documentSnapshot:JSON.stringify(t),sessionSnapshot:null},e),saveSession:t=>te({documentSnapshot:null,sessionSnapshot:JSON.stringify(t)},e)}}async function te(e,t){const n=[];null!==e.documentSnapshot&&n.push([re(t),e.documentSnapshot]),null!==e.sessionSnapshot&&n.push([ie(t),e.sessionSnapshot]),0!==n.length&&await(async(e,t)=>{if(0===t.length)return;const n=await Q();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)})})(nn,n)}async function ne(e={}){const[t,n]=await ce([re(e),ie(e)]);return{documentSnapshot:t,sessionSnapshot:n}}async function se(){return ae(on)}async function oe(){return ae(rn)}function re(e){return e.storageNamespace?`${e.storageNamespace}.document`:on}function ie(e){return e.storageNamespace?`${e.storageNamespace}.session`:rn}async function ae(e){const[t]=await ce([e]);return t??null}async function ce(e){return(await(async(e,t)=>{if(0===t.length)return[];const n=await Q();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(le)}function le(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 de({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){const s=a();return s?Ut(Wt("div",{"data-ui":n,className:ue("land-canvas__floating-toolbar-layer",t),children:e}),s):null}function ue(...e){return e.filter(Boolean).join(" ")}function pe(e,t,n){return cn(e,an(t,n))}function he(e,t){return"function"==typeof e?e(t):e}function fe(e){return e.split("-")[0]}function me(e){return e.split("-")[1]}function ge(e){return"x"===e?"y":"x"}function ve(e){return"y"===e?"height":"width"}function we(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function ye(e){return ge(we(e))}function be(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}function xe(e){const t=fe(e);return pn[t]+e.slice(t.length)}function Se(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 Ee(e,t,n){let{reference:s,floating:o}=e;const r=we(t),i=ye(t),a=ve(i),c=fe(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(me(t)){case"start":h[i]-=p*(n&&l?-1:1);break;case"end":h[i]+=p*(n&&l?-1:1)}return h}async function Ie(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}=he(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=Se(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=Se(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 Ce(){return"undefined"!=typeof window}function Te(e){return Re(e)?(e.nodeName||"").toLowerCase():"#document"}function Pe(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function ke(e){var t;return null==(t=(Re(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Re(e){return!!Ce()&&(e instanceof Node||e instanceof Pe(e).Node)}function Ae(e){return!!Ce()&&(e instanceof Element||e instanceof Pe(e).Element)}function Le(e){return!!Ce()&&(e instanceof HTMLElement||e instanceof Pe(e).HTMLElement)}function De(e){return!(!Ce()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Pe(e).ShadowRoot)}function Me(e){const{overflow:t,overflowX:n,overflowY:s,display:o}=He(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+n)&&"inline"!==o&&"contents"!==o}function Oe(e){return/^(table|td|th)$/.test(Te(e))}function Fe(e){try{if(e.matches(":popover-open"))return!0}catch(t){}try{return e.matches(":modal")}catch(t){return!1}}function Be(e){const t=Ae(e)?He(e):e;return bn(t.transform)||bn(t.translate)||bn(t.scale)||bn(t.rotate)||bn(t.perspective)||!Ne()&&(bn(t.backdropFilter)||bn(t.filter))||wn.test(t.willChange||"")||yn.test(t.contain||"")}function Ne(){return null==_t&&(_t="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),_t}function $e(e){return/^(html|body|#document)$/.test(Te(e))}function He(e){return Pe(e).getComputedStyle(e)}function Ke(e){return Ae(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function je(e){if("html"===Te(e))return e;const t=e.assignedSlot||e.parentNode||De(e)&&e.host||ke(e);return De(t)?t.host:t}function ze(e){const t=je(e);return $e(t)?e.ownerDocument?e.ownerDocument.body:e.body:Le(t)&&Me(t)?t:ze(t)}function Ve(e,t,n){var s;void 0===t&&(t=[]),void 0===n&&(n=!0);const o=ze(e),r=o===(null==(s=e.ownerDocument)?void 0:s.body),i=Pe(o);if(r){const e=We(i);return t.concat(i,i.visualViewport||[],Me(o)?o:[],e&&n?Ve(e):[])}return t.concat(o,Ve(o,[],n))}function We(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function qe(e){const t=He(e);let n=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Le(e),r=o?e.offsetWidth:n,i=o?e.offsetHeight:s,a=ln(n)!==r||ln(s)!==i;return a&&(n=r,s=i),{width:n,height:s,$:a}}function Ue(e){return Ae(e)?e:e.contextElement}function _e(e){const t=Ue(e);if(!Le(t))return un(1);const n=t.getBoundingClientRect(),{width:s,height:o,$:r}=qe(t);let i=(r?ln(n.width):n.width)/s,a=(r?ln(n.height):n.height)/o;return i&&Number.isFinite(i)||(i=1),a&&Number.isFinite(a)||(a=1),{x:i,y:a}}function Ye(e){const t=Pe(e);return Ne()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:xn}function Xe(e,t,n,s){void 0===t&&(t=!1),void 0===n&&(n=!1);const o=e.getBoundingClientRect(),r=Ue(e);let i=un(1);t&&(s?Ae(s)&&(i=_e(s)):i=_e(e));const a=((e,t,n)=>(void 0===t&&(t=!1),!(!n||t&&n!==Pe(e))&&t))(r,n,s)?Ye(r):un(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=Pe(r),t=s&&Ae(s)?Pe(s):s;let n=e,o=We(n);for(;o&&s&&t!==n;){const e=_e(o),t=o.getBoundingClientRect(),s=He(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=Pe(o),o=We(n)}}return Se({width:d,height:u,x:c,y:l})}function Je(e,t){const n=Ke(e).scrollLeft;return t?t.left+n:Xe(ke(e)).left+n}function Ge(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Je(e,n),y:n.top+t.scrollTop}}function Ze(e,t,n){let s;if("viewport"===t)s=((e,t)=>{const n=Pe(e),s=ke(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=Ne();(!e||e&&"fixed"===t)&&(a=o.offsetLeft,c=o.offsetTop)}const l=Je(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=ke(e),n=Ke(e),s=e.ownerDocument.body,o=cn(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),r=cn(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let i=-n.scrollLeft+Je(e);const a=-n.scrollTop;return"rtl"===He(s).direction&&(i+=cn(t.clientWidth,s.clientWidth)-o),{width:o,height:r,x:i,y:a}})(ke(e));else if(Ae(t))s=((e,t)=>{const n=Xe(e,!0,"fixed"===t),s=n.top+e.clientTop,o=n.left+e.clientLeft,r=Le(e)?_e(e):un(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=Ye(e);s={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Se(s)}function Qe(e,t){const n=je(e);return!(n===t||!Ae(n)||$e(n))&&("fixed"===He(n).position||Qe(n,t))}function et(e,t){const n=t.get(e);if(n)return n;let s=Ve(e,[],!1).filter(e=>Ae(e)&&"body"!==Te(e)),o=null;const r="fixed"===He(e).position;let i=r?je(e):e;for(;Ae(i)&&!$e(i);){const t=He(i),n=Be(i);n||"fixed"!==t.position||(o=null),(r?!n&&!o:!n&&"static"===t.position&&o&&("absolute"===o.position||"fixed"===o.position)||Me(i)&&!n&&Qe(e,i))?s=s.filter(e=>e!==i):o=t,i=je(i)}return t.set(e,s),s}function tt(e,t,n){function s(){l.x=Je(r)}const o=Le(t),r=ke(t),i="fixed"===n,a=Xe(e,!0,i,t);let c={scrollLeft:0,scrollTop:0};const l=un(0);if(o||!o&&!i)if(("body"!==Te(t)||Me(r))&&(c=Ke(t)),o){const e=Xe(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?un(0):Ge(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 nt(e){return"static"===He(e).position}function st(e,t){if(!Le(e)||"fixed"===He(e).position)return null;if(t)return t(e);let n=e.offsetParent;return ke(e)===n&&(n=n.ownerDocument.body),n}function ot(e,t){const n=Pe(e);if(Fe(e))return n;if(!Le(e)){let t=je(e);for(;t&&!$e(t);){if(Ae(t)&&!nt(t))return t;t=je(t)}return n}let s=st(e,t);for(;s&&Oe(s)&&nt(s);)s=st(s,t);return s&&$e(s)&&nt(s)&&!Be(s)?n:s||(e=>{let t=je(e);for(;Le(t)&&!$e(t);){if(Be(t))return t;if(Fe(t))return null;t=je(t)}return null})(e)||n}function rt(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function it({viewport:e,fallbackPlacements:t,floatingRef:n,getReferenceElement:s,onPlacementChange:o,offset:r,placement:i,visible:a=!0}){$t(()=>{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=at("--toolbar-floating-shift-padding",8),s=r??at("--toolbar-floating-offset",38),p={top:at("--toolbar-floating-safe-top",64),right:n,bottom:n,left:n};((e,t,n)=>{const s={platform:Sn,...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:Ie},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}=Ee(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}=Ee(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:[En(s),Cn({fallbackPlacements:[...t],padding:p}),In({padding:p})]}).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=Ue(e),d=o||r?[...l?Ve(l):[],...t?Ve(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=ke(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||rt(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:-dn(p)+"px "+-dn(r.clientWidth-(u+h))+"px "+-dn(r.clientHeight-(p+f))+"px "+-dn(u)+"px",threshold:cn(0,an(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?Xe(e):null;return c&&function t(){const s=Xe(e);m&&!rt(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 at(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 ct(e){const t=a();return t?Ut(Wt(lt,{...e}),t):null}function lt({fallbackPlacements:e=Tn,offset:t=8,placement:n="top",referenceElement:o,...r}){const i=u(),a=Kt(null),c=Bt(()=>o,[o]);return s(a),it({viewport:i.viewport.state,fallbackPlacements:e,floatingRef:a,getReferenceElement:c,offset:t,placement:n}),Wt("div",{...r,ref:a})}function dt(){return Nt(Rn)}function ut({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=Kt(null),h=Kt(null),[f,m]=jt("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=Bt(()=>d.current,[g?.height,g?.width,g?.x,g?.y]),b=Bt(()=>d.current?.getBoundingClientRect()??null,[]),x=Ht(()=>({placement:f,getContentBounds:b}),[g?.height,g?.width,g?.x,g?.y,b,f,l.pageTransform]);return s(h),it({viewport:a.viewport.state,fallbackPlacements:"center"===o?kn:Pn,floatingRef:h,getReferenceElement:y,onPlacementChange:m,offset:r,placement:"center"===o?"top":"top-start",visible:w}),v&&g?qt(Vt,{children:[Wt("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:Wt("div",{ref:d,"aria-hidden":"true",style:{position:"absolute",left:g.x,top:g.y,width:g.width,height:g.height,pointerEvents:"none"}})}),Wt("div",{ref:h,"data-ui":n,className:pt("land-canvas__floating-selection-anchor",t),style:{position:"fixed",left:0,top:0,visibility:"hidden",willChange:"transform"},children:Wt(Rn.Provider,{value:x,children:e})})]}):null}function pt(...e){return e.filter(Boolean).join(" ")}import{A as ht,C as ft,D as mt,E as gt,F as vt,I as wt,L as yt,M as bt,N as xt,O as St,P as Et,R as It,T as Ct,a as Tt,f as Pt,j as kt,k as Rt,o as At,r as Lt,u as Dt,x as Mt,z as Ot}from"./host-DYfq8ME2.mjs";import{createContext as Ft,useCallback as Bt,useContext as Nt,useEffect as $t,useMemo as Ht,useRef as Kt,useState as jt,useSyncExternalStore as zt}from"react";import{Fragment as Vt,jsx as Wt,jsxs as qt}from"react/jsx-runtime";import{createPortal as Ut}from"react-dom";var _t,Yt=Ft(null),Xt=Ft(null),Jt={state:"idle"},Gt=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}},Zt=[500,1e3,2e3,5e3],Qt=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=Zt[this.documentRetryCount];void 0!==e&&(this.documentRetryCount+=1,this.scheduleDocumentSave(e))}scheduleSessionRetry(){if(!this.isRunning||null!==this.sessionTimer)return;const e=Zt[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{}}},en={status:"starting"},tn=[],nn="snapshots",sn=null,on="canvas-kit.document",rn="canvas-kit.session",an=Math.min,cn=Math.max,ln=Math.round,dn=Math.floor,un=e=>({x:e,y:e}),pn={left:"right",right:"left",bottom:"top",top:"bottom"},hn=["left","right"],fn=["right","left"],mn=["top","bottom"],gn=["bottom","top"],vn=new Set(["left","top"]),wn=/transform|translate|scale|rotate|perspective|filter/,yn=/paint|layout|strict|content/,bn=e=>!!e&&"none"!==e,xn=un(0),Sn={convertOffsetParentRelativeRectToViewportRelativeRect:e=>{let{elements:t,rect:n,offsetParent:s,strategy:o}=e;const r="fixed"===o,i=ke(s),a=!!t&&Fe(t.floating);if(s===i||a&&r)return n;let c={scrollLeft:0,scrollTop:0},l=un(1);const d=un(0),u=Le(s);if((u||!u&&!r)&&(("body"!==Te(s)||Me(i))&&(c=Ke(s)),u)){const e=Xe(s);l=_e(s),d.x=e.x+s.clientLeft,d.y=e.y+s.clientTop}const p=!i||u||r?un(0):Ge(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:ke,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:s,strategy:o}=e;const r=[..."clippingAncestors"===n?Fe(t)?[]:et(t,this._c):[].concat(n),s],i=Ze(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=Ze(t,r[u],o);a=cn(e.top,a),c=an(e.right,c),l=an(e.bottom,l),d=cn(e.left,d)}return{width:c-d,height:l-a,x:d,y:a}},getOffsetParent:ot,getElementRects:async function(e){const t=this.getOffsetParent||ot,n=this.getDimensions,s=await n(e.floating);return{reference:tt(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}=qe(e);return{width:t,height:n}},getScale:_e,isElement:Ae,isRTL:e=>"rtl"===He(e).direction},En=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=fe(n),a=me(n),c="y"===we(n),l=vn.has(i)?-1:1,d=r&&c?-1:1,u=he(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}}}}),In=e=>(void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:s,placement:o,platform:r}=t,{mainAxis:i=!0,crossAxis:a=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=he(e,t),d={x:n,y:s},u=await r.detectOverflow(t,l),p=we(fe(o)),h=ge(p);let f=d[h],m=d[p];i&&(f=pe(f+u["y"===h?"top":"left"],f,f-u["y"===h?"bottom":"right"])),a&&(m=pe(m+u["y"===p?"top":"left"],m,m-u["y"===p?"bottom":"right"]));const g=c.fn({...t,[h]:f,[p]:m});return{...g,data:{x:g.x-n,y:g.y-s,enabled:{[h]:i,[p]:a}}}}}),Cn=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}=he(e,t);if(null!=(n=r.arrow)&&n.alignmentOffset)return{};const v=fe(o),w=we(a),y=fe(a)===a,b=await(null==c.isRTL?void 0:c.isRTL(l.floating)),x=p||(y||!m?[xe(a)]:(e=>{const t=xe(e);return[be(e),t,be(t)]})(a)),S="none"!==f;!p&&S&&x.push(...function(e,t,n,s){const o=me(e);let r=((e,t,n)=>{switch(e){case"top":case"bottom":return n?t?fn:hn:t?hn:fn;case"left":case"right":return t?mn:gn;default:return[]}})(fe(e),"start"===n,s);return o&&(r=r.map(e=>e+"-"+o),t&&(r=r.concat(r.map(be)))),r}(a,m,f,b));const E=[a,...x],I=await c.detectOverflow(t,g),C=[];let T=(null==(s=r.flip)?void 0:s.overflows)||[];if(d&&C.push(I[v]),u){const e=((e,t,n)=>{void 0===n&&(n=!1);const s=me(e),o=ye(e),r=ve(o);let i="x"===o?s===(n?"end":"start")?"right":"left":"start"===s?"bottom":"top";return t.reference[r]>t.floating[r]&&(i=xe(i)),[i,xe(i)]})(o,i,b);C.push(I[e[0]],I[e[1]])}if(T=[...T,{placement:o,overflows:C}],!C.every(e=>e<=0)){var P,k;const e=((null==(P=r.flip)?void 0:P.index)||0)+1,t=E[e];if(t&&("alignment"!==u||w===we(t)||T.every(e=>we(e.placement)!==w||e.overflows[0]>0)))return{data:{index:e,overflows:T},reset:{placement:t}};let n=null==(k=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:k.placement;if(!n)switch(h){case"bestFit":{var R;const e=null==(R=T.filter(e=>{if(S){const t=we(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:R[0];e&&(n=e);break}case"initialPlacement":n=a}if(o!==n)return{reset:{placement:n}}}return{}}}),Tn=["bottom"],Pn=["bottom-start"],kn=["bottom"],Rn=Ft(null);export{ct as CanvasKitFloatingContent,de as CanvasKitFloatingToolbarLayer,d as CanvasKitProvider,G as CanvasKitRoot,ut as FloatingSelectionToolbarPageSpace,I as applyCanvasActionShortcutOverrides,t as createCanvasApiToken,ht as createCustomShapeColor,ee as createLocalSnapshotPersistence,kt as createThemeShapeColor,e as defineCanvasPlugin,E as getCanvasActionShortcuts,bt as getThemeColorTokenName,xt as isCustomShapeColorRef,Et as isThemeShapeColorRef,se as readPersistedDocumentSnapshot,ne as readPersistedEditorSnapshots,oe as readPersistedSessionSnapshot,n as requireApi,vt as resolveShapeColor,wt as shapeColorToCssColor,u as useCanvasKit,c as useCanvasKitFloatingPortalContainer,s as useCanvasKitWheelCapture,p as useCanvasValue,dt as useFloatingSelectionToolbarPosition};
6
+ Wt(i,{})]})})})})}function Q(){return"undefined"==typeof indexedDB?Promise.resolve(null):(sn||(sn=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(nn)}),n.addEventListener("success",()=>{const t=n.result;t.addEventListener("versionchange",()=>{t.close(),sn=null}),e(t)}),n.addEventListener("error",()=>{sn=null,t(n.error)})})),sn)}function ee(e={}){return{async load({signal:t}){t.throwIfAborted();const n=await ne(e);return t.throwIfAborted(),n},saveDocument:t=>te({documentSnapshot:JSON.stringify(t),sessionSnapshot:null},e),saveSession:t=>te({documentSnapshot:null,sessionSnapshot:JSON.stringify(t)},e)}}async function te(e,t){const n=[];null!==e.documentSnapshot&&n.push([re(t),e.documentSnapshot]),null!==e.sessionSnapshot&&n.push([ie(t),e.sessionSnapshot]),0!==n.length&&await(async(e,t)=>{if(0===t.length)return;const n=await Q();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)})})(nn,n)}async function ne(e={}){const[t,n]=await ce([re(e),ie(e)]);return{documentSnapshot:t,sessionSnapshot:n}}async function se(){return ae(on)}async function oe(){return ae(rn)}function re(e){return e.storageNamespace?`${e.storageNamespace}.document`:on}function ie(e){return e.storageNamespace?`${e.storageNamespace}.session`:rn}async function ae(e){const[t]=await ce([e]);return t??null}async function ce(e){return(await(async(e,t)=>{if(0===t.length)return[];const n=await Q();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(le)}function le(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 de({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){const s=a();return s?Ut(Wt("div",{"data-ui":n,className:ue("land-canvas__floating-toolbar-layer",t),children:e}),s):null}function ue(...e){return e.filter(Boolean).join(" ")}function pe(e,t,n){return cn(e,an(t,n))}function he(e,t){return"function"==typeof e?e(t):e}function fe(e){return e.split("-")[0]}function me(e){return e.split("-")[1]}function ge(e){return"x"===e?"y":"x"}function ve(e){return"y"===e?"height":"width"}function we(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function ye(e){return ge(we(e))}function be(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}function xe(e){const t=fe(e);return pn[t]+e.slice(t.length)}function Se(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 Ee(e,t,n){let{reference:s,floating:o}=e;const r=we(t),i=ye(t),a=ve(i),c=fe(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(me(t)){case"start":h[i]-=p*(n&&l?-1:1);break;case"end":h[i]+=p*(n&&l?-1:1)}return h}async function Ie(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}=he(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=Se(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=Se(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 Ce(){return"undefined"!=typeof window}function Te(e){return Re(e)?(e.nodeName||"").toLowerCase():"#document"}function Pe(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function ke(e){var t;return null==(t=(Re(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Re(e){return!!Ce()&&(e instanceof Node||e instanceof Pe(e).Node)}function Ae(e){return!!Ce()&&(e instanceof Element||e instanceof Pe(e).Element)}function Le(e){return!!Ce()&&(e instanceof HTMLElement||e instanceof Pe(e).HTMLElement)}function De(e){return!(!Ce()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Pe(e).ShadowRoot)}function Me(e){const{overflow:t,overflowX:n,overflowY:s,display:o}=He(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+n)&&"inline"!==o&&"contents"!==o}function Oe(e){return/^(table|td|th)$/.test(Te(e))}function Fe(e){try{if(e.matches(":popover-open"))return!0}catch(t){}try{return e.matches(":modal")}catch(t){return!1}}function Be(e){const t=Ae(e)?He(e):e;return bn(t.transform)||bn(t.translate)||bn(t.scale)||bn(t.rotate)||bn(t.perspective)||!Ne()&&(bn(t.backdropFilter)||bn(t.filter))||wn.test(t.willChange||"")||yn.test(t.contain||"")}function Ne(){return null==_t&&(_t="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),_t}function $e(e){return/^(html|body|#document)$/.test(Te(e))}function He(e){return Pe(e).getComputedStyle(e)}function Ke(e){return Ae(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function je(e){if("html"===Te(e))return e;const t=e.assignedSlot||e.parentNode||De(e)&&e.host||ke(e);return De(t)?t.host:t}function ze(e){const t=je(e);return $e(t)?e.ownerDocument?e.ownerDocument.body:e.body:Le(t)&&Me(t)?t:ze(t)}function Ve(e,t,n){var s;void 0===t&&(t=[]),void 0===n&&(n=!0);const o=ze(e),r=o===(null==(s=e.ownerDocument)?void 0:s.body),i=Pe(o);if(r){const e=We(i);return t.concat(i,i.visualViewport||[],Me(o)?o:[],e&&n?Ve(e):[])}return t.concat(o,Ve(o,[],n))}function We(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function qe(e){const t=He(e);let n=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Le(e),r=o?e.offsetWidth:n,i=o?e.offsetHeight:s,a=ln(n)!==r||ln(s)!==i;return a&&(n=r,s=i),{width:n,height:s,$:a}}function Ue(e){return Ae(e)?e:e.contextElement}function _e(e){const t=Ue(e);if(!Le(t))return un(1);const n=t.getBoundingClientRect(),{width:s,height:o,$:r}=qe(t);let i=(r?ln(n.width):n.width)/s,a=(r?ln(n.height):n.height)/o;return i&&Number.isFinite(i)||(i=1),a&&Number.isFinite(a)||(a=1),{x:i,y:a}}function Ye(e){const t=Pe(e);return Ne()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:xn}function Xe(e,t,n,s){void 0===t&&(t=!1),void 0===n&&(n=!1);const o=e.getBoundingClientRect(),r=Ue(e);let i=un(1);t&&(s?Ae(s)&&(i=_e(s)):i=_e(e));const a=((e,t,n)=>(void 0===t&&(t=!1),!(!n||t&&n!==Pe(e))&&t))(r,n,s)?Ye(r):un(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=Pe(r),t=s&&Ae(s)?Pe(s):s;let n=e,o=We(n);for(;o&&s&&t!==n;){const e=_e(o),t=o.getBoundingClientRect(),s=He(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=Pe(o),o=We(n)}}return Se({width:d,height:u,x:c,y:l})}function Je(e,t){const n=Ke(e).scrollLeft;return t?t.left+n:Xe(ke(e)).left+n}function Ge(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Je(e,n),y:n.top+t.scrollTop}}function Ze(e,t,n){let s;if("viewport"===t)s=((e,t)=>{const n=Pe(e),s=ke(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=Ne();(!e||e&&"fixed"===t)&&(a=o.offsetLeft,c=o.offsetTop)}const l=Je(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=ke(e),n=Ke(e),s=e.ownerDocument.body,o=cn(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),r=cn(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let i=-n.scrollLeft+Je(e);const a=-n.scrollTop;return"rtl"===He(s).direction&&(i+=cn(t.clientWidth,s.clientWidth)-o),{width:o,height:r,x:i,y:a}})(ke(e));else if(Ae(t))s=((e,t)=>{const n=Xe(e,!0,"fixed"===t),s=n.top+e.clientTop,o=n.left+e.clientLeft,r=Le(e)?_e(e):un(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=Ye(e);s={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Se(s)}function Qe(e,t){const n=je(e);return!(n===t||!Ae(n)||$e(n))&&("fixed"===He(n).position||Qe(n,t))}function et(e,t){const n=t.get(e);if(n)return n;let s=Ve(e,[],!1).filter(e=>Ae(e)&&"body"!==Te(e)),o=null;const r="fixed"===He(e).position;let i=r?je(e):e;for(;Ae(i)&&!$e(i);){const t=He(i),n=Be(i);n||"fixed"!==t.position||(o=null),(r?!n&&!o:!n&&"static"===t.position&&o&&("absolute"===o.position||"fixed"===o.position)||Me(i)&&!n&&Qe(e,i))?s=s.filter(e=>e!==i):o=t,i=je(i)}return t.set(e,s),s}function tt(e,t,n){function s(){l.x=Je(r)}const o=Le(t),r=ke(t),i="fixed"===n,a=Xe(e,!0,i,t);let c={scrollLeft:0,scrollTop:0};const l=un(0);if(o||!o&&!i)if(("body"!==Te(t)||Me(r))&&(c=Ke(t)),o){const e=Xe(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?un(0):Ge(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 nt(e){return"static"===He(e).position}function st(e,t){if(!Le(e)||"fixed"===He(e).position)return null;if(t)return t(e);let n=e.offsetParent;return ke(e)===n&&(n=n.ownerDocument.body),n}function ot(e,t){const n=Pe(e);if(Fe(e))return n;if(!Le(e)){let t=je(e);for(;t&&!$e(t);){if(Ae(t)&&!nt(t))return t;t=je(t)}return n}let s=st(e,t);for(;s&&Oe(s)&&nt(s);)s=st(s,t);return s&&$e(s)&&nt(s)&&!Be(s)?n:s||(e=>{let t=je(e);for(;Le(t)&&!$e(t);){if(Be(t))return t;if(Fe(t))return null;t=je(t)}return null})(e)||n}function rt(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function it({viewport:e,fallbackPlacements:t,floatingRef:n,getReferenceElement:s,onPlacementChange:o,offset:r,placement:i,visible:a=!0}){$t(()=>{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=at("--toolbar-floating-shift-padding",8),s=r??at("--toolbar-floating-offset",38),p={top:at("--toolbar-floating-safe-top",64),right:n,bottom:n,left:n};((e,t,n)=>{const s={platform:Sn,...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:Ie},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}=Ee(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}=Ee(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:[En(s),Cn({fallbackPlacements:[...t],padding:p}),In({padding:p})]}).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=Ue(e),d=o||r?[...l?Ve(l):[],...t?Ve(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=ke(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||rt(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:-dn(p)+"px "+-dn(r.clientWidth-(u+h))+"px "+-dn(r.clientHeight-(p+f))+"px "+-dn(u)+"px",threshold:cn(0,an(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?Xe(e):null;return c&&function t(){const s=Xe(e);m&&!rt(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 at(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 ct(e){const t=a();return t?Ut(Wt(lt,{...e}),t):null}function lt({fallbackPlacements:e=Tn,offset:t=8,placement:n="top",referenceElement:o,...r}){const i=u(),a=Kt(null),c=Bt(()=>o,[o]);return s(a),it({viewport:i.viewport.state,fallbackPlacements:e,floatingRef:a,getReferenceElement:c,offset:t,placement:n}),Wt("div",{...r,ref:a})}function dt(){return Nt(Rn)}function ut({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=Kt(null),h=Kt(null),[f,m]=jt("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=Bt(()=>d.current,[g?.height,g?.width,g?.x,g?.y]),b=Bt(()=>d.current?.getBoundingClientRect()??null,[]),x=Ht(()=>({placement:f,getContentBounds:b}),[g?.height,g?.width,g?.x,g?.y,b,f,l.pageTransform]);return s(h),it({viewport:a.viewport.state,fallbackPlacements:"center"===o?kn:Pn,floatingRef:h,getReferenceElement:y,onPlacementChange:m,offset:r,placement:"center"===o?"top":"top-start",visible:w}),v&&g?qt(Vt,{children:[Wt("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:Wt("div",{ref:d,"aria-hidden":"true",style:{position:"absolute",left:g.x,top:g.y,width:g.width,height:g.height,pointerEvents:"none"}})}),Wt("div",{ref:h,"data-ui":n,className:pt("land-canvas__floating-selection-anchor",t),style:{position:"fixed",left:0,top:0,visibility:"hidden",willChange:"transform"},children:Wt(Rn.Provider,{value:x,children:e})})]}):null}function pt(...e){return e.filter(Boolean).join(" ")}import{A as ht,C as ft,D as mt,E as gt,F as vt,I as wt,L as yt,M as bt,N as xt,O as St,P as Et,R as It,T as Ct,a as Tt,f as Pt,j as kt,k as Rt,o as At,r as Lt,u as Dt,x as Mt,z as Ot}from"./host-Djw688Kd.mjs";import{createContext as Ft,useCallback as Bt,useContext as Nt,useEffect as $t,useMemo as Ht,useRef as Kt,useState as jt,useSyncExternalStore as zt}from"react";import{Fragment as Vt,jsx as Wt,jsxs as qt}from"react/jsx-runtime";import{createPortal as Ut}from"react-dom";var _t,Yt=Ft(null),Xt=Ft(null),Jt={state:"idle"},Gt=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}},Zt=[500,1e3,2e3,5e3],Qt=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=Zt[this.documentRetryCount];void 0!==e&&(this.documentRetryCount+=1,this.scheduleDocumentSave(e))}scheduleSessionRetry(){if(!this.isRunning||null!==this.sessionTimer)return;const e=Zt[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{}}},en={status:"starting"},tn=[],nn="snapshots",sn=null,on="canvas-kit.document",rn="canvas-kit.session",an=Math.min,cn=Math.max,ln=Math.round,dn=Math.floor,un=e=>({x:e,y:e}),pn={left:"right",right:"left",bottom:"top",top:"bottom"},hn=["left","right"],fn=["right","left"],mn=["top","bottom"],gn=["bottom","top"],vn=new Set(["left","top"]),wn=/transform|translate|scale|rotate|perspective|filter/,yn=/paint|layout|strict|content/,bn=e=>!!e&&"none"!==e,xn=un(0),Sn={convertOffsetParentRelativeRectToViewportRelativeRect:e=>{let{elements:t,rect:n,offsetParent:s,strategy:o}=e;const r="fixed"===o,i=ke(s),a=!!t&&Fe(t.floating);if(s===i||a&&r)return n;let c={scrollLeft:0,scrollTop:0},l=un(1);const d=un(0),u=Le(s);if((u||!u&&!r)&&(("body"!==Te(s)||Me(i))&&(c=Ke(s)),u)){const e=Xe(s);l=_e(s),d.x=e.x+s.clientLeft,d.y=e.y+s.clientTop}const p=!i||u||r?un(0):Ge(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:ke,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:s,strategy:o}=e;const r=[..."clippingAncestors"===n?Fe(t)?[]:et(t,this._c):[].concat(n),s],i=Ze(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=Ze(t,r[u],o);a=cn(e.top,a),c=an(e.right,c),l=an(e.bottom,l),d=cn(e.left,d)}return{width:c-d,height:l-a,x:d,y:a}},getOffsetParent:ot,getElementRects:async function(e){const t=this.getOffsetParent||ot,n=this.getDimensions,s=await n(e.floating);return{reference:tt(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}=qe(e);return{width:t,height:n}},getScale:_e,isElement:Ae,isRTL:e=>"rtl"===He(e).direction},En=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=fe(n),a=me(n),c="y"===we(n),l=vn.has(i)?-1:1,d=r&&c?-1:1,u=he(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}}}}),In=e=>(void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:s,placement:o,platform:r}=t,{mainAxis:i=!0,crossAxis:a=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=he(e,t),d={x:n,y:s},u=await r.detectOverflow(t,l),p=we(fe(o)),h=ge(p);let f=d[h],m=d[p];i&&(f=pe(f+u["y"===h?"top":"left"],f,f-u["y"===h?"bottom":"right"])),a&&(m=pe(m+u["y"===p?"top":"left"],m,m-u["y"===p?"bottom":"right"]));const g=c.fn({...t,[h]:f,[p]:m});return{...g,data:{x:g.x-n,y:g.y-s,enabled:{[h]:i,[p]:a}}}}}),Cn=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}=he(e,t);if(null!=(n=r.arrow)&&n.alignmentOffset)return{};const v=fe(o),w=we(a),y=fe(a)===a,b=await(null==c.isRTL?void 0:c.isRTL(l.floating)),x=p||(y||!m?[xe(a)]:(e=>{const t=xe(e);return[be(e),t,be(t)]})(a)),S="none"!==f;!p&&S&&x.push(...function(e,t,n,s){const o=me(e);let r=((e,t,n)=>{switch(e){case"top":case"bottom":return n?t?fn:hn:t?hn:fn;case"left":case"right":return t?mn:gn;default:return[]}})(fe(e),"start"===n,s);return o&&(r=r.map(e=>e+"-"+o),t&&(r=r.concat(r.map(be)))),r}(a,m,f,b));const E=[a,...x],I=await c.detectOverflow(t,g),C=[];let T=(null==(s=r.flip)?void 0:s.overflows)||[];if(d&&C.push(I[v]),u){const e=((e,t,n)=>{void 0===n&&(n=!1);const s=me(e),o=ye(e),r=ve(o);let i="x"===o?s===(n?"end":"start")?"right":"left":"start"===s?"bottom":"top";return t.reference[r]>t.floating[r]&&(i=xe(i)),[i,xe(i)]})(o,i,b);C.push(I[e[0]],I[e[1]])}if(T=[...T,{placement:o,overflows:C}],!C.every(e=>e<=0)){var P,k;const e=((null==(P=r.flip)?void 0:P.index)||0)+1,t=E[e];if(t&&("alignment"!==u||w===we(t)||T.every(e=>we(e.placement)!==w||e.overflows[0]>0)))return{data:{index:e,overflows:T},reset:{placement:t}};let n=null==(k=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:k.placement;if(!n)switch(h){case"bestFit":{var R;const e=null==(R=T.filter(e=>{if(S){const t=we(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:R[0];e&&(n=e);break}case"initialPlacement":n=a}if(o!==n)return{reset:{placement:n}}}return{}}}),Tn=["bottom"],Pn=["bottom-start"],kn=["bottom"],Rn=Ft(null);export{ct as CanvasKitFloatingContent,de as CanvasKitFloatingToolbarLayer,d as CanvasKitProvider,G as CanvasKitRoot,ut as FloatingSelectionToolbarPageSpace,I as applyCanvasActionShortcutOverrides,t as createCanvasApiToken,ht as createCustomShapeColor,ee as createLocalSnapshotPersistence,kt as createThemeShapeColor,e as defineCanvasPlugin,E as getCanvasActionShortcuts,bt as getThemeColorTokenName,xt as isCustomShapeColorRef,Et as isThemeShapeColorRef,se as readPersistedDocumentSnapshot,ne as readPersistedEditorSnapshots,oe as readPersistedSessionSnapshot,n as requireApi,vt as resolveShapeColor,wt as shapeColorToCssColor,u as useCanvasKit,c as useCanvasKitFloatingPortalContainer,s as useCanvasKitWheelCapture,p as useCanvasValue,dt as useFloatingSelectionToolbarPosition};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yuzhouu/canvas-kit",
3
- "version": "0.1.17",
3
+ "version": "0.1.18",
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,_ as o,a as m,b as r,c as t,d as p,f,g as h,h as i,i as x,l as b,m as c,n as d,o as e,p as g,r as j,s as l,t as n,u,v,w,x as y,y as C}from"./host-DYfq8ME2.mjs";export{x as CANVAS_SURFACE_DATA_UI,m as CANVAS_SURFACE_SELECTOR,j as Canvas,o as CanvasRenderBindingsContext,g as DefaultGrid,s as EditorContext,a as PageSpace,c as SHAPE_HOVER_STROKE,i as SHAPE_HOVER_STROKE_WIDTH,n as ShapeHeadingControl,y as createCanvasRenderBindings,d as createShapeHeadingDomEventGuard,e as forwardWheelEventToCanvasSurface,l as getCanvasSurfaceElement,t as getCanvasSurfaceElementForNode,b as getCanvasSurfacePagePoint,u as getCanvasSurfaceScreenPoint,p as getEditableEventTarget,f as isEditableEventTarget,v as useCanvasOverlays,C as useCanvasRenderBindings,r as useCanvasRenderers,w as useEditor,h as useValue};
1
+ import{C as s,S as a,_ as o,a as m,b as r,c as t,d as p,f,g as h,h as i,i as x,l as b,m as c,n as d,o as e,p as g,r as j,s as l,t as n,u,v,w,x as y,y as C}from"./host-Djw688Kd.mjs";export{x as CANVAS_SURFACE_DATA_UI,m as CANVAS_SURFACE_SELECTOR,j as Canvas,o as CanvasRenderBindingsContext,g as DefaultGrid,s as EditorContext,a as PageSpace,c as SHAPE_HOVER_STROKE,i as SHAPE_HOVER_STROKE_WIDTH,n as ShapeHeadingControl,y as createCanvasRenderBindings,d as createShapeHeadingDomEventGuard,e as forwardWheelEventToCanvasSurface,l as getCanvasSurfaceElement,t as getCanvasSurfaceElementForNode,b as getCanvasSurfacePagePoint,u as getCanvasSurfaceScreenPoint,p as getEditableEventTarget,f as isEditableEventTarget,v as useCanvasOverlays,C as useCanvasRenderBindings,r as useCanvasRenderers,w as useEditor,h as useValue};