@yuzhouu/canvas-kit 0.1.20 → 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.d.ts CHANGED
@@ -6,11 +6,11 @@ export type { ActiveCanvasContextMenu, CanvasApiToken, CanvasAssetResolverContri
6
6
  export type { CanvasRenderPlugin } from "./_vendor/canvas-react/host/index";
7
7
  export { CanvasKitRoot } from "./react/CanvasKitRoot";
8
8
  export { CanvasKitProvider, useCanvasKit, useCanvasValue, } from "./react/CanvasKitContext";
9
- export { applyCanvasActionShortcutOverrides, getCanvasActionShortcuts, } from "./react/canvasActions";
9
+ export { applyCanvasActionShortcutOverrides, getCanvasActionShortcuts, formatCanvasActionShortcut, } from "./react/canvasActions";
10
10
  export type { CanvasAction, CanvasActionShortcut, CanvasActionShortcutOverrides, CanvasKitChromeRenderer, CanvasKitRootProps, KeyboardShortcut, } from "./react/canvasKitRootContracts";
11
11
  export { createLocalSnapshotPersistence, readPersistedDocumentSnapshot, readPersistedEditorSnapshots, readPersistedSessionSnapshot, } from "./browser/persistence";
12
12
  export type { LocalSnapshotPersistenceOptions } from "./browser/persistence";
13
- export type { CanvasAssetsApi, CanvasContextMenuApi, CanvasDocumentApi, CanvasExportApi, CanvasGridApi, CanvasHistoryApi, CanvasHistoryState, CanvasErrorHandler, CanvasKit, CanvasKitOptions, CanvasKitSnapshot, CanvasKitStartupResult, CanvasLayersApi, CanvasPagesApi, CanvasPagesState, CanvasReadable, CanvasSelectionApi, CanvasSelectionBounds, CanvasSelectionState, CanvasShapeExportBounds, CanvasShapeExportBoundsOptions, CanvasShapeExportBoundsSpace, CanvasSessionApi, CanvasSessionState, CanvasShapesApi, CanvasToolsApi, CanvasToolsState, CanvasViewportApi, CanvasViewportLockPoint, CanvasViewportState, } from "./runtime/canvasKitContracts";
13
+ export type { CanvasAssetsApi, CanvasContextMenuApi, CanvasDocumentApi, CanvasExportApi, CanvasGridApi, CanvasHistoryApi, CanvasHistoryState, CanvasErrorHandler, CanvasKit, CanvasKitOptions, CanvasKitSnapshot, CanvasKitStartupResult, CanvasLayersApi, CanvasPagesApi, CanvasPagesState, CanvasPageBounds, CanvasReadable, CanvasSelectionApi, CanvasSelectionState, CanvasShapeExportBounds, CanvasShapeExportBoundsOptions, CanvasShapeExportBoundsSpace, CanvasSessionApi, CanvasSessionState, CanvasShapesApi, CanvasToolsApi, CanvasToolsState, CanvasViewportApi, CanvasViewportLockPoint, CanvasViewportState, } from "./runtime/canvasKitContracts";
14
14
  export { CanvasKitFloatingToolbarLayer, } from "./chrome/toolbar/CanvasKitFloatingToolbarLayer";
15
15
  export { CanvasKitFloatingContent } from "./chrome/floating/CanvasKitFloatingContent";
16
16
  export { useCanvasKitFloatingPortalContainer } from "./chrome/floating/CanvasKitFloatingPortal";
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){Nt(()=>{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)||Rt(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]=Kt(null),s=Ft(e=>{n(e)},[]),o=$t(()=>({registerTarget:s,target:t}),[s,t]);
2
- return Vt(_t.Provider,{value:o,children:e})}function i(){const{registerTarget:e}=l(),t=Ht(null);return s(t),Vt("div",{ref:Ft(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 Bt(_t)?.target??void 0}function l(){const e=Bt(_t);if(!e)throw new Error("CanvasKit floating content must be rendered inside CanvasKitRoot.");return e}function d({canvas:e,children:t}){
3
- return Vt(Yt.Provider,{value:e,children:t})}function u(){const e=Bt(Yt);if(!e)throw new Error("useCanvasKit must be used inside CanvasKitProvider.");return e}function p(e){return jt(e.subscribe,e.getSnapshot,e.getSnapshot)}function h({contributions:e,getHostElement:t,isEditing:n,onError:s,screenToPage:o}){return Nt(()=>{const r=o=>{if(!y(t(),o)||n()||Tt(o.target))return;const r=w({source:"clipboard",dataTransfer:o.clipboardData});f(e,r)&&(o.preventDefault(),m(e,r).catch(e=>{s(new Error("Canvas clipboard import failed.",{cause:e}))}))},i=s=>{!y(t(),s)||n()||Tt(s.target)||g(e,v(s.dataTransfer))&&(s.preventDefault(),s.dataTransfer&&(s.dataTransfer.dropEffect="copy"))},a=r=>{const i=y(t(),r);if(!i||n()||Tt(r.target))return;const a=g(e,v(r.dataTransfer)),c=w({source:"drop",dataTransfer:r.dataTransfer,pagePoint:o(At(r,i))});f(e,c)?(r.preventDefault(),m(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 g(e,t){return e.some(e=>e.acceptsPreview?.(t)??!1)}async function m(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(Ct);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=Ft(()=>s.tools.state.getSnapshot().isEditing,[s]),d=Ft(e=>r.viewport.screenToPage(e),[r]);
4
- return Wt(zt,{children:[Vt(ht.Provider,{value:r,children:Vt(Lt,{onContextMenuRequest:c,renderBindings:a,showGrid:o})}),Vt(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 L(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 A(){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 It(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(Et),editor:t,pageId:n,shapes:s.filter(Mt)})},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}),g=q({signals:t.signals,name:"CanvasKit.session",getDependencies:()=>[t.state.session.get().meta],getSnapshot:([e])=>({meta:{...e}})}),m=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.cameraLock.get(),t.state.pageTransform.get()],getSnapshot:([e,t,n])=>({camera:{...e},lock:t?{...t.pagePoint}:null,zoom:e.z,pageTransform:n.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:g,updateMeta(e){const n=t.session.get();return t.session.update({meta:{...n.meta,...e}},"user"),{meta:{...t.state.session.get().meta}}}},selection:{state:m,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"}),setLock:e=>t.viewport.setLock(e),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);L(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 L(s.map(({id:e})=>e),"editor plugin id"),L(n.flatMap(e=>e.api?[e.api.id]:[]),"canvas API token"),{canvasPlugins:n,editorPlugins:s,renderPlugins:o}}(e.plugins),r=Dt(o),i=new Jt,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=kt({cameraAnimationScheduler:A(),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 ft(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 Zt(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:g}}=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 m=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=Xt,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(Xt)}}),dispose(){a||(a=!0,l(Xt),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:m});return{canvas:w,dispose:i.publish({beforeShutdown:()=>d.closeWrites()}),productId:o,render:{editor:d,importContributions:g,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=en,chromeRenderer:t,onCanvasChange:n,options:s}){const o=(e=>{const[t,n]=Kt(null);return Nt(()=>{let t=!0,s=null;const o=new AbortController,r=e.onError??J;return n({options:e,state:Qt}),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:Qt})(s);if("error"===o.status)throw o.error;return"ready"!==o.status?null:Vt(Z,{actions:e,chromeRenderer:t,onCanvasChange:n,runtime:o.runtime})}function Z({actions:e=en,chromeRenderer:t,onCanvasChange:n,runtime:s}){const o=Ht(n),a=Ht(null),c=Ft(()=>a.current,[]),{canvas:l,productId:u,render:p}=s,h=p.onError??J,f=Ft(()=>l.tools.state.getSnapshot().isEditing,[l]);return o.current=n,Nt(()=>(o.current?.(l),()=>o.current?.(null)),[l]),function({actions:e,canvas:t,isEditing:n,onError:s}){Nt(()=>{(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()||Tt(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=>xt(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}),Vt(d,{canvas:l,children:Vt(r,{children:Vt("div",{ref:a,"data-ui":"app-shell","data-canvas-kit":u,className:"land-canvas-kit__shell",children:Wt("main",{"data-ui":"workspace-viewport",className:"land-canvas-kit__viewport",children:[
5
- Vt(S,{bindings:p,getHostElement:c,onError:h}),t?.(l)??null,
6
- Vt(i,{})]})})})})}function Q(){return"undefined"==typeof indexedDB?Promise.resolve(null):(nn||(nn=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(tn)}),n.addEventListener("success",()=>{const t=n.result;t.addEventListener("versionchange",()=>{t.close(),nn=null}),e(t)}),n.addEventListener("error",()=>{nn=null,t(n.error)})})),nn)}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)})})(tn,n)}async function ne(e={}){const[t,n]=await ce([re(e),ie(e)]);return{documentSnapshot:t,sessionSnapshot:n}}async function se(){return ae(sn)}async function oe(){return ae(on)}function re(e){return e.storageNamespace?`${e.storageNamespace}.document`:sn}function ie(e){return e.storageNamespace?`${e.storageNamespace}.session`:on}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?qt(Vt("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){return"function"==typeof e?e(t):e}function he(e){return e.split("-")[0]}function fe(e){return e.split("-")[1]}function ge(e){return"y"===e?"height":"width"}function me(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function ve(e){return"x"===me(e)?"y":"x"}function we(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}function ye(e){const t=he(e);return un[t]+e.slice(t.length)}function be(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 xe(e,t,n){let{reference:s,floating:o}=e;const r=me(t),i=ve(t),a=ge(i),c=he(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(fe(t)){case"start":h[i]-=p*(n&&l?-1:1);break;case"end":h[i]+=p*(n&&l?-1:1)}return h}async function Se(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}=pe(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),g=a[p?"floating"===u?"reference":"floating":u],m=be(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(g)))||n?g:g.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=be(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:w,strategy:c}):v);return{top:(m.top-b.top+f.top)/y.y,bottom:(b.bottom-m.bottom+f.bottom)/y.y,left:(m.left-b.left+f.left)/y.x,right:(b.right-m.right+f.right)/y.x}}function Ee(){return"undefined"!=typeof window}function Ie(e){return Pe(e)?(e.nodeName||"").toLowerCase():"#document"}function Ce(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Te(e){var t;return null==(t=(Pe(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Pe(e){return!!Ee()&&(e instanceof Node||e instanceof Ce(e).Node)}function ke(e){return!!Ee()&&(e instanceof Element||e instanceof Ce(e).Element)}function Re(e){return!!Ee()&&(e instanceof HTMLElement||e instanceof Ce(e).HTMLElement)}function Le(e){return!(!Ee()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Ce(e).ShadowRoot)}function Ae(e){const{overflow:t,overflowX:n,overflowY:s,display:o}=Ne(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+n)&&"inline"!==o&&"contents"!==o}function De(e){return/^(table|td|th)$/.test(Ie(e))}function Me(e){try{if(e.matches(":popover-open"))return!0}catch(t){}try{return e.matches(":modal")}catch(t){return!1}}function Oe(e){const t=ke(e)?Ne(e):e;return yn(t.transform)||yn(t.translate)||yn(t.scale)||yn(t.rotate)||yn(t.perspective)||!Fe()&&(yn(t.backdropFilter)||yn(t.filter))||vn.test(t.willChange||"")||wn.test(t.contain||"")}function Fe(){return null==Ut&&(Ut="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ut}function Be(e){return/^(html|body|#document)$/.test(Ie(e))}function Ne(e){return Ce(e).getComputedStyle(e)}function $e(e){return ke(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function He(e){if("html"===Ie(e))return e;const t=e.assignedSlot||e.parentNode||Le(e)&&e.host||Te(e);return Le(t)?t.host:t}function Ke(e){const t=He(e);return Be(t)?e.ownerDocument?e.ownerDocument.body:e.body:Re(t)&&Ae(t)?t:Ke(t)}function je(e,t,n){var s;void 0===t&&(t=[]),void 0===n&&(n=!0);const o=Ke(e),r=o===(null==(s=e.ownerDocument)?void 0:s.body),i=Ce(o);if(r){const e=ze(i);return t.concat(i,i.visualViewport||[],Ae(o)?o:[],e&&n?je(e):[])}return t.concat(o,je(o,[],n))}function ze(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Ve(e){const t=Ne(e);let n=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Re(e),r=o?e.offsetWidth:n,i=o?e.offsetHeight:s,a=cn(n)!==r||cn(s)!==i;return a&&(n=r,s=i),{width:n,height:s,$:a}}function We(e){return ke(e)?e:e.contextElement}function qe(e){const t=We(e);if(!Re(t))return dn(1);const n=t.getBoundingClientRect(),{width:s,height:o,$:r}=Ve(t);let i=(r?cn(n.width):n.width)/s,a=(r?cn(n.height):n.height)/o;return i&&Number.isFinite(i)||(i=1),a&&Number.isFinite(a)||(a=1),{x:i,y:a}}function Ue(e){const t=Ce(e);return Fe()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:bn}function _e(e,t,n,s){void 0===t&&(t=!1),void 0===n&&(n=!1);const o=e.getBoundingClientRect(),r=We(e);let i=dn(1);t&&(s?ke(s)&&(i=qe(s)):i=qe(e));const a=((e,t,n)=>(void 0===t&&(t=!1),!(!n||t&&n!==Ce(e))&&t))(r,n,s)?Ue(r):dn(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=Ce(r),t=s&&ke(s)?Ce(s):s;let n=e,o=ze(n);for(;o&&s&&t!==n;){const e=qe(o),t=o.getBoundingClientRect(),s=Ne(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=Ce(o),o=ze(n)}}return be({width:d,height:u,x:c,y:l})}function Ye(e,t){const n=$e(e).scrollLeft;return t?t.left+n:_e(Te(e)).left+n}function Xe(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Ye(e,n),y:n.top+t.scrollTop}}function Je(e,t,n){let s;if("viewport"===t)s=((e,t)=>{const n=Ce(e),s=Te(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=Fe();(!e||e&&"fixed"===t)&&(a=o.offsetLeft,c=o.offsetTop)}const l=Ye(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=Te(e),n=$e(e),s=e.ownerDocument.body,o=an(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),r=an(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let i=-n.scrollLeft+Ye(e);const a=-n.scrollTop;return"rtl"===Ne(s).direction&&(i+=an(t.clientWidth,s.clientWidth)-o),{width:o,height:r,x:i,y:a}})(Te(e));else if(ke(t))s=((e,t)=>{const n=_e(e,!0,"fixed"===t),s=n.top+e.clientTop,o=n.left+e.clientLeft,r=Re(e)?qe(e):dn(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=Ue(e);s={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return be(s)}function Ge(e,t){const n=He(e);return!(n===t||!ke(n)||Be(n))&&("fixed"===Ne(n).position||Ge(n,t))}function Ze(e,t){const n=t.get(e);if(n)return n;let s=je(e,[],!1).filter(e=>ke(e)&&"body"!==Ie(e)),o=null;const r="fixed"===Ne(e).position;let i=r?He(e):e;for(;ke(i)&&!Be(i);){const t=Ne(i),n=Oe(i);n||"fixed"!==t.position||(o=null),(r?!n&&!o:!n&&"static"===t.position&&o&&("absolute"===o.position||"fixed"===o.position)||Ae(i)&&!n&&Ge(e,i))?s=s.filter(e=>e!==i):o=t,i=He(i)}return t.set(e,s),s}function Qe(e,t,n){function s(){l.x=Ye(r)}const o=Re(t),r=Te(t),i="fixed"===n,a=_e(e,!0,i,t);let c={scrollLeft:0,scrollTop:0};const l=dn(0);if(o||!o&&!i)if(("body"!==Ie(t)||Ae(r))&&(c=$e(t)),o){const e=_e(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?dn(0):Xe(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 et(e){return"static"===Ne(e).position}function tt(e,t){if(!Re(e)||"fixed"===Ne(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Te(e)===n&&(n=n.ownerDocument.body),n}function nt(e,t){const n=Ce(e);if(Me(e))return n;if(!Re(e)){let t=He(e);for(;t&&!Be(t);){if(ke(t)&&!et(t))return t;t=He(t)}return n}let s=tt(e,t);for(;s&&De(s)&&et(s);)s=tt(s,t);return s&&Be(s)&&et(s)&&!Oe(s)?n:s||(e=>{let t=He(e);for(;Re(t)&&!Be(t);){if(Oe(t))return t;if(Me(t))return null;t=He(t)}return null})(e)||n}function st(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function ot({viewport:e,fallbackPlacements:t,floatingRef:n,getReferenceElement:s,onPlacementChange:o,offset:r,placement:i,visible:a=!0}){Nt(()=>{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=it("--toolbar-floating-collision-padding",8);((e,t,n)=>{const s={platform:xn,...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:Se},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}=xe(l,s,c),p=s,h=0;const f={};for(let g=0;g<r.length;g++){const n=r[g];if(!n)continue;const{name:m,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[m]={...f[m],...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}=xe(l,p,c))),g=-1)}return{x:d,y:u,placement:p,strategy:o,middlewareData:f}})(e,t,{...s,platform:o})})(c,l,{strategy:"fixed",placement:i,middleware:rt({fallbackPlacements:t,offset:r??it("--toolbar-floating-offset",38),padding:{top:it("--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=We(e),d=o||r?[...l?je(l):[],...t?je(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=Te(e);return function i(a,c){function l(t){const n=t[0].intersectionRatio;if(n!==c){if(!m)return i();n?i(!1,n):s=setTimeout(()=>{i(!1,1e-7)},1e3)}1!==n||st(d,e.getBoundingClientRect())||i(),m=!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 g={rootMargin:-ln(p)+"px "+-ln(r.clientWidth-(u+h))+"px "+-ln(r.clientHeight-(p+f))+"px "+-ln(u)+"px",threshold:an(0,rn(1,c))||1};let m=!0;try{o=new IntersectionObserver(l,{...g,root:r.ownerDocument})}catch(v){o=new IntersectionObserver(l,g)}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 g=c?_e(e):null;return c&&function t(){const s=_e(e);g&&!st(g,s)&&n(),g=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 rt({fallbackPlacements:e,offset:t,padding:n}){return[Sn(t),En({fallbackPlacements:[...e],padding:n})]}function it(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 at(e){const t=a();return t?qt(Vt(ct,{...e}),t):null}function ct({fallbackPlacements:e=In,offset:t=8,placement:n="top",referenceElement:o,...r}){const i=u(),a=Ht(null),c=Ft(()=>o,[o]);return s(a),ot({viewport:i.viewport.state,fallbackPlacements:e,floatingRef:a,getReferenceElement:c,offset:t,placement:n}),Vt("div",{...r,ref:a})}function lt(){return Bt(Pn)}function dt({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=Ht(null),h=Ht(null),[f,g]=Kt("center"===o?"top":"top-start"),m=c.pageBounds??(c.anchorPagePoint?{x:c.anchorPagePoint.x,y:c.anchorPagePoint.y,width:0,height:0}:null),v=i&&null!==m,w=v&&!c.isTranslating,y=Ft(()=>d.current,[m?.height,m?.width,m?.x,m?.y]),b=Ft(()=>d.current?.getBoundingClientRect()??null,[]),x=$t(()=>({placement:f,getContentBounds:b}),[m?.height,m?.width,m?.x,m?.y,b,f,l.pageTransform]);return s(h),ot({viewport:a.viewport.state,fallbackPlacements:"center"===o?Tn:Cn,floatingRef:h,getReferenceElement:y,onPlacementChange:g,offset:r,placement:"center"===o?"top":"top-start",visible:w}),v&&m?Wt(zt,{children:[Vt("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:Vt("div",{ref:d,"aria-hidden":"true",style:{position:"absolute",left:m.x,top:m.y,width:m.width,height:m.height,pointerEvents:"none"}})}),Vt("div",{ref:h,"data-ui":n,className:ut("land-canvas__floating-selection-anchor",t),style:{position:"fixed",left:0,top:0,visibility:"hidden",willChange:"transform"},children:Vt(Pn.Provider,{value:x,children:e})})]}):null}function ut(...e){return e.filter(Boolean).join(" ")}import{A as pt,C as ht,D as ft,E as gt,F as mt,I as vt,L as wt,M as yt,N as bt,O as xt,P as St,R as Et,T as It,a as Ct,f as Tt,j as Pt,k as kt,o as Rt,r as Lt,u as At,x as Dt,z as Mt}from"./host-s4jdMA_d.mjs";import{createContext as Ot,useCallback as Ft,useContext as Bt,useEffect as Nt,useMemo as $t,useRef as Ht,useState as Kt,useSyncExternalStore as jt}from"react";import{Fragment as zt,jsx as Vt,jsxs as Wt}from"react/jsx-runtime";import{createPortal as qt}from"react-dom";var Ut,_t=Ot(null),Yt=Ot(null),Xt={state:"idle"},Jt=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}},Gt=[500,1e3,2e3,5e3],Zt=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=Gt[this.documentRetryCount];void 0!==e&&(this.documentRetryCount+=1,this.scheduleDocumentSave(e))}scheduleSessionRetry(){if(!this.isRunning||null!==this.sessionTimer)return;const e=Gt[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{}}},Qt={status:"starting"},en=[],tn="snapshots",nn=null,sn="canvas-kit.document",on="canvas-kit.session",rn=Math.min,an=Math.max,cn=Math.round,ln=Math.floor,dn=e=>({x:e,y:e}),un={left:"right",right:"left",bottom:"top",top:"bottom"},pn=["left","right"],hn=["right","left"],fn=["top","bottom"],gn=["bottom","top"],mn=new Set(["left","top"]),vn=/transform|translate|scale|rotate|perspective|filter/,wn=/paint|layout|strict|content/,yn=e=>!!e&&"none"!==e,bn=dn(0),xn={convertOffsetParentRelativeRectToViewportRelativeRect:e=>{let{elements:t,rect:n,offsetParent:s,strategy:o}=e;const r="fixed"===o,i=Te(s),a=!!t&&Me(t.floating);if(s===i||a&&r)return n;let c={scrollLeft:0,scrollTop:0},l=dn(1);const d=dn(0),u=Re(s);if((u||!u&&!r)&&(("body"!==Ie(s)||Ae(i))&&(c=$e(s)),u)){const e=_e(s);l=qe(s),d.x=e.x+s.clientLeft,d.y=e.y+s.clientTop}const p=!i||u||r?dn(0):Xe(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:Te,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:s,strategy:o}=e;const r=[..."clippingAncestors"===n?Me(t)?[]:Ze(t,this._c):[].concat(n),s],i=Je(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=Je(t,r[u],o);a=an(e.top,a),c=rn(e.right,c),l=rn(e.bottom,l),d=an(e.left,d)}return{width:c-d,height:l-a,x:d,y:a}},getOffsetParent:nt,getElementRects:async function(e){const t=this.getOffsetParent||nt,n=this.getDimensions,s=await n(e.floating);return{reference:Qe(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}=Ve(e);return{width:t,height:n}},getScale:qe,isElement:ke,isRTL:e=>"rtl"===Ne(e).direction},Sn=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=he(n),a=fe(n),c="y"===me(n),l=mn.has(i)?-1:1,d=r&&c?-1:1,u=pe(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}}}}),En=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:g=!0,...m}=pe(e,t);if(null!=(n=r.arrow)&&n.alignmentOffset)return{};const v=he(o),w=me(a),y=he(a)===a,b=await(null==c.isRTL?void 0:c.isRTL(l.floating)),x=p||(y||!g?[ye(a)]:(e=>{const t=ye(e);return[we(e),t,we(t)]})(a)),S="none"!==f;!p&&S&&x.push(...function(e,t,n,s){const o=fe(e);let r=((e,t,n)=>{switch(e){case"top":case"bottom":return n?t?hn:pn:t?pn:hn;case"left":case"right":return t?fn:gn;default:return[]}})(he(e),"start"===n,s);return o&&(r=r.map(e=>e+"-"+o),t&&(r=r.concat(r.map(we)))),r}(a,g,f,b));const E=[a,...x],I=await c.detectOverflow(t,m),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=fe(e),o=ve(e),r=ge(o);let i="x"===o?s===(n?"end":"start")?"right":"left":"start"===s?"bottom":"top";return t.reference[r]>t.floating[r]&&(i=ye(i)),[i,ye(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===me(t)||T.every(e=>me(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=me(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{}}}),In=["bottom"],Cn=["bottom-start"],Tn=["bottom"],Pn=Ot(null);export{at as CanvasKitFloatingContent,de as CanvasKitFloatingToolbarLayer,d as CanvasKitProvider,G as CanvasKitRoot,dt as FloatingSelectionToolbarPageSpace,I as applyCanvasActionShortcutOverrides,t as createCanvasApiToken,pt as createCustomShapeColor,ee as createLocalSnapshotPersistence,Pt as createThemeShapeColor,e as defineCanvasPlugin,E as getCanvasActionShortcuts,yt as getThemeColorTokenName,bt as isCustomShapeColorRef,St as isThemeShapeColorRef,se as readPersistedDocumentSnapshot,ne as readPersistedEditorSnapshots,oe as readPersistedSessionSnapshot,n as requireApi,mt as resolveShapeColor,vt as shapeColorToCssColor,u as useCanvasKit,c as useCanvasKitFloatingPortalContainer,s as useCanvasKitWheelCapture,p as useCanvasValue,lt as useFloatingSelectionToolbarPosition};
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
+ 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()||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.20",
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,_ 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-s4jdMA_d.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,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};
@@ -1,3 +1,5 @@
1
1
  import type { CanvasAction, CanvasActionShortcut, CanvasActionShortcutOverrides, KeyboardShortcut } from "./canvasKitRootContracts";
2
+ export declare function getCanvasActionKeybinding(shortcut: KeyboardShortcut): string;
3
+ export declare function formatCanvasActionShortcut(shortcut: KeyboardShortcut): string;
2
4
  export declare function getCanvasActionShortcuts(shortcut: CanvasActionShortcut | undefined): readonly KeyboardShortcut[];
3
5
  export declare function applyCanvasActionShortcutOverrides(actions: readonly CanvasAction[], overrides: CanvasActionShortcutOverrides | undefined): readonly CanvasAction[];
@@ -8,6 +8,7 @@ export type CanvasKitChromeRenderer = (canvas: CanvasKit) => ReactNode;
8
8
  export interface CanvasAction {
9
9
  readonly id: string;
10
10
  readonly shortcut?: CanvasActionShortcut;
11
+ readonly repeat?: boolean;
11
12
  isEnabled(canvas: CanvasKit): boolean;
12
13
  run(canvas: CanvasKit): void | Promise<void>;
13
14
  }
@@ -1,8 +1,9 @@
1
1
  import type { CanvasAction } from "../../canvasKitRootContracts";
2
2
  import type { CanvasKit } from "../../../runtime/canvasKitContracts";
3
- export declare function useCanvasKeyboardShortcuts({ actions, canvas, isEditing, onError, }: {
3
+ export declare function useCanvasKeyboardShortcuts({ actions, canvas, getHostElement, isEditing, onError, }: {
4
4
  actions: readonly CanvasAction[];
5
5
  canvas: CanvasKit;
6
+ getHostElement(): HTMLElement | null;
6
7
  isEditing(): boolean;
7
8
  onError(error: unknown): void;
8
9
  }): void;
@@ -13,6 +13,9 @@ export interface CanvasReadable<T> {
13
13
  export interface CanvasDocumentApi {
14
14
  readonly state: CanvasReadable<CanvasProductDocumentRef>;
15
15
  readonly readonlyState: CanvasReadable<boolean>;
16
+ readonly lockedState: CanvasReadable<boolean>;
17
+ /** Toggles a temporary edit lock without overriding the configured readonly policy. */
18
+ setLocked(isLocked: boolean): void;
16
19
  getSnapshot(): CanvasKitSnapshot;
17
20
  updateMeta(patch: Readonly<Record<string, unknown>>): CanvasProductDocumentRef;
18
21
  }
@@ -23,7 +26,7 @@ export interface CanvasSessionApi {
23
26
  readonly state: CanvasReadable<CanvasSessionState>;
24
27
  updateMeta(patch: Readonly<Record<string, unknown>>): CanvasSessionState;
25
28
  }
26
- export interface CanvasSelectionBounds {
29
+ export interface CanvasPageBounds {
27
30
  readonly x: number;
28
31
  readonly y: number;
29
32
  readonly width: number;
@@ -43,7 +46,7 @@ export interface CanvasSelectionState {
43
46
  readonly canResetSelectionRotation: boolean;
44
47
  readonly ids: readonly ShapeId[];
45
48
  readonly shapes: readonly CanvasProductShapeData[];
46
- readonly pageBounds: CanvasSelectionBounds | null;
49
+ readonly pageBounds: CanvasPageBounds | null;
47
50
  readonly anchorPagePoint: {
48
51
  readonly x: number;
49
52
  readonly y: number;
@@ -85,6 +88,8 @@ export interface CanvasHistoryState {
85
88
  }
86
89
  export interface CanvasHistoryApi {
87
90
  readonly state: CanvasReadable<CanvasHistoryState>;
91
+ /** Groups synchronous document edits into one undo step and rolls them back on error. */
92
+ batch<T>(run: () => T): T;
88
93
  clear(): void;
89
94
  undo(): boolean;
90
95
  redo(): boolean;
@@ -93,6 +98,7 @@ export interface CanvasViewportState {
93
98
  readonly camera: Readonly<Camera>;
94
99
  readonly lock: CanvasViewportLockPoint | null;
95
100
  readonly zoom: number;
101
+ readonly pageBounds: CanvasPageBounds | null;
96
102
  readonly pageTransform: string;
97
103
  }
98
104
  export interface CanvasViewportLockPoint {
@@ -108,9 +114,24 @@ export interface CanvasViewportApi {
108
114
  readonly state: CanvasReadable<CanvasViewportState>;
109
115
  readonly grid: CanvasGridApi;
110
116
  setCamera(camera: Partial<Camera>, pageId?: string): void;
117
+ centerOnPoint(point: {
118
+ readonly x: number;
119
+ readonly y: number;
120
+ }, options?: {
121
+ readonly animation?: {
122
+ readonly durationMs: number;
123
+ };
124
+ }): boolean;
111
125
  setLock(pagePoint: CanvasViewportLockPoint | null): boolean;
112
- zoomIn(): void;
113
- zoomOut(): void;
126
+ zoomAtCenter(deltaY: number): void;
127
+ zoomIn(options?: {
128
+ readonly anchor?: "center" | "pointer";
129
+ }): void;
130
+ zoomOut(options?: {
131
+ readonly anchor?: "center" | "pointer";
132
+ }): void;
133
+ zoomToFit(): boolean;
134
+ zoomToSelection(): boolean;
114
135
  resetZoom(): void;
115
136
  reset(): void;
116
137
  }
@@ -199,6 +220,10 @@ export interface CanvasKit {
199
220
  export interface CanvasKitOptions {
200
221
  readonly id?: string;
201
222
  readonly plugins: readonly CanvasPluginInput[];
223
+ /** Minimum camera zoom factor (1 = 100%). Defaults to 0.1. */
224
+ readonly minZoom?: number;
225
+ /** Maximum camera zoom factor (1 = 100%). Defaults to 8. */
226
+ readonly maxZoom?: number;
202
227
  readonly documentMeta?: Record<string, unknown>;
203
228
  /**
204
229
  * Used only when persistence reports that no stored document exists.
@@ -1,6 +1,8 @@
1
1
  import { type AssetId, type Editor, type EditorPlugin } from "../_vendor/canvas-core/index";
2
2
  export interface CreateCanvasKitEditorOptions {
3
3
  editorPlugins: readonly EditorPlugin[];
4
+ minZoom?: number;
5
+ maxZoom?: number;
4
6
  documentMeta?: Record<string, unknown>;
5
7
  resolveAssetUrl?: (assetId: AssetId) => string | null;
6
8
  onUnhandledError?: (error: unknown) => void;