@yuzhouu/canvas-kit 0.1.15 → 0.1.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
function e(e){return e}function t(e){return Object.freeze({id:e,kind:"api"})}function n(e,t){return e.require(t)}function s(e){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)||
|
|
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
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()||
|
|
4
|
-
return Wt(zt,{children:[Vt(St.Provider,{value:r,children:Vt(kt,{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 P(e,t){return new Set((e.requires??[]).flatMap(e=>{const n=t.get(e.id);return n?.api?[n.api.id]:[]}))}function T(e,t){const n=new Set;for(const s of e){if(n.has(s))throw new Error(`Duplicate ${t} id: ${s}.`);n.add(s)}}function k(e){return"provider"===e.kind}function R(e){return"svg-inliner"===e.kind}function A(e,t){const n=new Set;for(const s of e){if(n.has(s))throw new Error(`Duplicate ${t}: ${s}.`);n.add(s)}}function L(){if("undefined"!=typeof window&&"function"==typeof window.requestAnimationFrame&&"function"==typeof window.cancelAnimationFrame)return{requestFrame:e=>window.requestAnimationFrame(e),cancelFrame:e=>window.cancelAnimationFrame(e),prefersReducedMotion:()=>"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}}function D(e){return{id:e.id,name:e.name,index:e.index,meta:{...e.meta}}}function M(e){return{id:e?.id??"document:main",meta:{...e?.meta??{}}}}function O(e,t){return{id:e.id,type:e.type,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{id:e.id,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 N({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:j(o,n,a.id),isEffectivelyLocked:z(n,a.id)}}function $({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 H(e,t){return e.childShapesByParentId.get(t)??[]}function K(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 j(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 z(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 V(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 W({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 At(n,{get:e,graph:s},()=>{const e=a();Object.is(o,e)||(o=e,t())},{fireImmediately:!1})}}}function q({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=$({bindings:e,editor:t,shapes:s}),i=(e,s)=>{H(r,e).forEach((e,a)=>{const c=H(r,e.id).map(e=>e.id);o.push(N({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(Ct),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}=V(!1),{readable:u,set:p}=V(null),h=W({signals:t.signals,name:"CanvasKit.document",getDependencies:()=>[t.document.getMetadata()],getSnapshot:([e])=>M(e)}),f=W({signals:t.signals,name:"CanvasKit.document.readonlyState",getDependencies:()=>[t.state.readonly.get()],getSnapshot:([e])=>e}),g=W({signals:t.signals,name:"CanvasKit.session",getDependencies:()=>[t.state.session.get().meta],getSnapshot:([e])=>({meta:{...e}})}),m=W({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=W({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=W({signals:t.signals,name:"CanvasKit.history",getDependencies:()=>[t.state.history.get()],getSnapshot:([e])=>({...e})}),y=W({signals:t.signals,name:"CanvasKit.viewport",getDependencies:()=>[t.state.camera.get(),t.state.pageTransform.get()],getSnapshot:([e,t])=>({camera:{...e},zoom:e.z,pageTransform:t.toCssString()})}),b=W({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=W({signals:t.signals,name:"CanvasKit.layers",getDependencies:()=>U(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"}),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:{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)||(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(B);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(U(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=$({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=H(r,a.parentId);return N({childIds:H(r,a.id).map(e=>e.id),companionIds:r.companionIdsByRootId.get(a.id)??[],context:r,depth:K(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 U(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 _(){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 Y(e,t={}){(e=>{if(!e||!Array.isArray(e.plugins))throw new Error("CanvasKit requires an explicit plugins array.");if(!("persistence"in e))throw new Error("CanvasKit requires an explicit persistence option.")})(e),t.signal?.throwIfAborted();const{canvasPlugins:n,editorPlugins:s,renderPlugins:o}=function(e){const t=(e=>e.flat(1/0))(e);A(t.map(({id:e})=>e),"canvas plugin id");const n=(e=>{const t=new Map(e.map(e=>[e.id,e])),n=[],s=new Set,o=new Set,r=e=>{if(!o.has(e.id)){if(s.has(e.id))throw new Error(`Circular canvas plugin dependency detected at "${e.id}".`);s.add(e.id);for(const n of e.requires??[]){const s=t.get(n.id);if(!s)throw new Error(`Canvas plugin "${e.id}" requires missing plugin "${n.id}".`);r(s)}s.delete(e.id),o.add(e.id),n.push(e)}};for(const i of e)r(i);return n})(t),s=n.flatMap(e=>e.editor?[e.editor]:[]),o=n.flatMap(e=>e.render?[e.render]:[]);return A(s.map(({id:e})=>e),"editor plugin id"),A(n.flatMap(e=>e.api?[e.api.id]:[]),"canvas API token"),{canvasPlugins:n,editorPlugins:s,renderPlugins:o}}(e.plugins),r=Et(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=wt({cameraAnimationScheduler:L(),documentMeta:e.documentMeta,onUnhandledError:e.onUnhandledError,plugins:e.editorPlugins,resolveAssetUrl:e.resolveAssetUrl});return t.tools.register("select",e=>new Mt(e)),t.tools.register("hand",e=>new xt(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:P(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 T(t.map(({id:e})=>e),"import contribution"),T(n.map(({id:e})=>e),"export contribution"),T(n.flatMap(e=>"provider"===e.kind?[e.format]:[]),"export format"),T(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(_(),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}=q({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 X(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}function J({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??X;return n({options:e,state:Qt}),Y(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(G,{actions:e,chromeRenderer:t,onCanvasChange:n,runtime:o.runtime})}function G({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??X,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()||Rt(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=>Dt(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:[
|
|
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()||Pt(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()||Pt(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()||Pt(r.target))return;const a=g(e,v(r.dataTransfer)),c=w({source:"drop",dataTransfer:r.dataTransfer,pagePoint:o(Lt(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(At,{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 P(e,t){return new Set((e.requires??[]).flatMap(e=>{const n=t.get(e.id);return n?.api?[n.api.id]:[]}))}function T(e,t){const n=new Set;for(const s of e){if(n.has(s))throw new Error(`Duplicate ${t} id: ${s}.`);n.add(s)}}function k(e){return"provider"===e.kind}function R(e){return"svg-inliner"===e.kind}function A(e,t){const n=new Set;for(const s of e){if(n.has(s))throw new Error(`Duplicate ${t}: ${s}.`);n.add(s)}}function L(){if("undefined"!=typeof window&&"function"==typeof window.requestAnimationFrame&&"function"==typeof window.cancelAnimationFrame)return{requestFrame:e=>window.requestAnimationFrame(e),cancelFrame:e=>window.cancelAnimationFrame(e),prefersReducedMotion:()=>"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}}function D(e){return{id:e.id,name:e.name,index:e.index,meta:{...e.meta}}}function M(e){return{id:e?.id??"document:main",meta:{...e?.meta??{}}}}function O(e,t){return{id:e.id,type:e.type,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{id:e.id,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 N({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:j(o,n,a.id),isEffectivelyLocked:z(n,a.id)}}function $({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 H(e,t){return e.childShapesByParentId.get(t)??[]}function K(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 j(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 z(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 V(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 W({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 q({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=$({bindings:e,editor:t,shapes:s}),i=(e,s)=>{H(r,e).forEach((e,a)=>{const c=H(r,e.id).map(e=>e.id);o.push(N({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}=V(!1),{readable:u,set:p}=V(null),h=W({signals:t.signals,name:"CanvasKit.document",getDependencies:()=>[t.document.getMetadata()],getSnapshot:([e])=>M(e)}),f=W({signals:t.signals,name:"CanvasKit.document.readonlyState",getDependencies:()=>[t.state.readonly.get()],getSnapshot:([e])=>e}),g=W({signals:t.signals,name:"CanvasKit.session",getDependencies:()=>[t.state.session.get().meta],getSnapshot:([e])=>({meta:{...e}})}),m=W({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=W({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=W({signals:t.signals,name:"CanvasKit.history",getDependencies:()=>[t.state.history.get()],getSnapshot:([e])=>({...e})}),y=W({signals:t.signals,name:"CanvasKit.viewport",getDependencies:()=>[t.state.camera.get(),t.state.pageTransform.get()],getSnapshot:([e,t])=>({camera:{...e},zoom:e.z,pageTransform:t.toCssString()})}),b=W({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=W({signals:t.signals,name:"CanvasKit.layers",getDependencies:()=>U(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"}),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:{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)||(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(B);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(U(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=$({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=H(r,a.parentId);return N({childIds:H(r,a.id).map(e=>e.id),companionIds:r.companionIdsByRootId.get(a.id)??[],context:r,depth:K(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 U(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 _(){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 Y(e,t={}){(e=>{if(!e||!Array.isArray(e.plugins))throw new Error("CanvasKit requires an explicit plugins array.");if(!("persistence"in e))throw new Error("CanvasKit requires an explicit persistence option.")})(e),t.signal?.throwIfAborted();const{canvasPlugins:n,editorPlugins:s,renderPlugins:o}=function(e){const t=(e=>e.flat(1/0))(e);A(t.map(({id:e})=>e),"canvas plugin id");const n=(e=>{const t=new Map(e.map(e=>[e.id,e])),n=[],s=new Set,o=new Set,r=e=>{if(!o.has(e.id)){if(s.has(e.id))throw new Error(`Circular canvas plugin dependency detected at "${e.id}".`);s.add(e.id);for(const n of e.requires??[]){const s=t.get(n.id);if(!s)throw new Error(`Canvas plugin "${e.id}" requires missing plugin "${n.id}".`);r(s)}s.delete(e.id),o.add(e.id),n.push(e)}};for(const i of e)r(i);return n})(t),s=n.flatMap(e=>e.editor?[e.editor]:[]),o=n.flatMap(e=>e.render?[e.render]:[]);return A(s.map(({id:e})=>e),"editor plugin id"),A(n.flatMap(e=>e.api?[e.api.id]:[]),"canvas API token"),{canvasPlugins:n,editorPlugins:s,renderPlugins:o}}(e.plugins),r=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:L(),documentMeta:e.documentMeta,onUnhandledError:e.onUnhandledError,plugins:e.editorPlugins,resolveAssetUrl:e.resolveAssetUrl});return t.tools.register("select",e=>new gt(e)),t.tools.register("hand",e=>new 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:P(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 T(t.map(({id:e})=>e),"import contribution"),T(n.map(({id:e})=>e),"export contribution"),T(n.flatMap(e=>"provider"===e.kind?[e.format]:[]),"export format"),T(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(_(),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}=q({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 X(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}function J({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??X;return n({options:e,state:Qt}),Y(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(G,{actions:e,chromeRenderer:t,onCanvasChange:n,runtime:o.runtime})}function G({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??X,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()||Pt(o.target))return;const r={key:o.key,shiftKey:o.shiftKey,altKey:o.altKey,ctrlKey:o.ctrlKey,metaKey:o.metaKey,accelKey:o.metaKey||o.ctrlKey},i=e.find(e=>void 0!==e.shortcut&&E(e.shortcut).some(e=>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
5
|
Vt(S,{bindings:p,getHostElement:c,onError:h}),t?.(l)??null,
|
|
6
|
-
Vt(i,{})]})})})})}function Z(){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 Q(e={}){return{async load({signal:t}){t.throwIfAborted();const n=await te(e);return t.throwIfAborted(),n},saveDocument:t=>ee({documentSnapshot:JSON.stringify(t),sessionSnapshot:null},e),saveSession:t=>ee({documentSnapshot:null,sessionSnapshot:JSON.stringify(t)},e)}}async function ee(e,t){const n=[];null!==e.documentSnapshot&&n.push([oe(t),e.documentSnapshot]),null!==e.sessionSnapshot&&n.push([re(t),e.sessionSnapshot]),0!==n.length&&await(async(e,t)=>{if(0===t.length)return;const n=await Z();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 te(e={}){const[t,n]=await ae([oe(e),re(e)]);return{documentSnapshot:t,sessionSnapshot:n}}async function ne(){return ie(sn)}async function se(){return ie(on)}function oe(e){return e.storageNamespace?`${e.storageNamespace}.document`:sn}function re(e){return e.storageNamespace?`${e.storageNamespace}.session`:on}async function ie(e){const[t]=await ae([e]);return t??null}async function ae(e){return(await(async(e,t)=>{if(0===t.length)return[];const n=await Z();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(ce)}function ce(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 le({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){const s=a();return s?qt(Vt("div",{"data-ui":n,className:de("land-canvas__floating-toolbar-layer",t),children:e}),s):null}function de(...e){return e.filter(Boolean).join(" ")}function ue(e,t,n){return an(e,rn(t,n))}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"x"===e?"y":"x"}function me(e){return"y"===e?"height":"width"}function ve(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function we(e){return ge(ve(e))}function ye(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}function be(e){const t=he(e);return un[t]+e.slice(t.length)}function xe(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 Se(e,t,n){let{reference:s,floating:o}=e;const r=ve(t),i=we(t),a=me(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 Ee(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=xe(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=xe(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 Ie(){return"undefined"!=typeof window}function Ce(e){return ke(e)?(e.nodeName||"").toLowerCase():"#document"}function Pe(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Te(e){var t;return null==(t=(ke(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function ke(e){return!!Ie()&&(e instanceof Node||e instanceof Pe(e).Node)}function Re(e){return!!Ie()&&(e instanceof Element||e instanceof Pe(e).Element)}function Ae(e){return!!Ie()&&(e instanceof HTMLElement||e instanceof Pe(e).HTMLElement)}function Le(e){return!(!Ie()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Pe(e).ShadowRoot)}function De(e){const{overflow:t,overflowX:n,overflowY:s,display:o}=$e(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+n)&&"inline"!==o&&"contents"!==o}function Me(e){return/^(table|td|th)$/.test(Ce(e))}function Oe(e){try{if(e.matches(":popover-open"))return!0}catch(t){}try{return e.matches(":modal")}catch(t){return!1}}function Fe(e){const t=Re(e)?$e(e):e;return yn(t.transform)||yn(t.translate)||yn(t.scale)||yn(t.rotate)||yn(t.perspective)||!Be()&&(yn(t.backdropFilter)||yn(t.filter))||vn.test(t.willChange||"")||wn.test(t.contain||"")}function Be(){return null==Ut&&(Ut="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ut}function Ne(e){return/^(html|body|#document)$/.test(Ce(e))}function $e(e){return Pe(e).getComputedStyle(e)}function He(e){return Re(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Ke(e){if("html"===Ce(e))return e;const t=e.assignedSlot||e.parentNode||Le(e)&&e.host||Te(e);return Le(t)?t.host:t}function je(e){const t=Ke(e);return Ne(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ae(t)&&De(t)?t:je(t)}function ze(e,t,n){var s;void 0===t&&(t=[]),void 0===n&&(n=!0);const o=je(e),r=o===(null==(s=e.ownerDocument)?void 0:s.body),i=Pe(o);if(r){const e=Ve(i);return t.concat(i,i.visualViewport||[],De(o)?o:[],e&&n?ze(e):[])}return t.concat(o,ze(o,[],n))}function Ve(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function We(e){const t=$e(e);let n=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Ae(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 qe(e){return Re(e)?e:e.contextElement}function Ue(e){const t=qe(e);if(!Ae(t))return dn(1);const n=t.getBoundingClientRect(),{width:s,height:o,$:r}=We(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 _e(e){const t=Pe(e);return Be()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:bn}function Ye(e,t,n,s){void 0===t&&(t=!1),void 0===n&&(n=!1);const o=e.getBoundingClientRect(),r=qe(e);let i=dn(1);t&&(s?Re(s)&&(i=Ue(s)):i=Ue(e));const a=((e,t,n)=>(void 0===t&&(t=!1),!(!n||t&&n!==Pe(e))&&t))(r,n,s)?_e(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=Pe(r),t=s&&Re(s)?Pe(s):s;let n=e,o=Ve(n);for(;o&&s&&t!==n;){const e=Ue(o),t=o.getBoundingClientRect(),s=$e(o),r=t.left+(o.clientLeft+parseFloat(s.paddingLeft))*e.x,i=t.top+(o.clientTop+parseFloat(s.paddingTop))*e.y;c*=e.x,l*=e.y,d*=e.x,u*=e.y,c+=r,l+=i,n=Pe(o),o=Ve(n)}}return xe({width:d,height:u,x:c,y:l})}function Xe(e,t){const n=He(e).scrollLeft;return t?t.left+n:Ye(Te(e)).left+n}function Je(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Xe(e,n),y:n.top+t.scrollTop}}function Ge(e,t,n){let s;if("viewport"===t)s=((e,t)=>{const n=Pe(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=Be();(!e||e&&"fixed"===t)&&(a=o.offsetLeft,c=o.offsetTop)}const l=Xe(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=He(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+Xe(e);const a=-n.scrollTop;return"rtl"===$e(s).direction&&(i+=an(t.clientWidth,s.clientWidth)-o),{width:o,height:r,x:i,y:a}})(Te(e));else if(Re(t))s=((e,t)=>{const n=Ye(e,!0,"fixed"===t),s=n.top+e.clientTop,o=n.left+e.clientLeft,r=Ae(e)?Ue(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=_e(e);s={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return xe(s)}function Ze(e,t){const n=Ke(e);return!(n===t||!Re(n)||Ne(n))&&("fixed"===$e(n).position||Ze(n,t))}function Qe(e,t){const n=t.get(e);if(n)return n;let s=ze(e,[],!1).filter(e=>Re(e)&&"body"!==Ce(e)),o=null;const r="fixed"===$e(e).position;let i=r?Ke(e):e;for(;Re(i)&&!Ne(i);){const t=$e(i),n=Fe(i);n||"fixed"!==t.position||(o=null),(r?!n&&!o:!n&&"static"===t.position&&o&&("absolute"===o.position||"fixed"===o.position)||De(i)&&!n&&Ze(e,i))?s=s.filter(e=>e!==i):o=t,i=Ke(i)}return t.set(e,s),s}function et(e,t,n){function s(){l.x=Xe(r)}const o=Ae(t),r=Te(t),i="fixed"===n,a=Ye(e,!0,i,t);let c={scrollLeft:0,scrollTop:0};const l=dn(0);if(o||!o&&!i)if(("body"!==Ce(t)||De(r))&&(c=He(t)),o){const e=Ye(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):Je(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 tt(e){return"static"===$e(e).position}function nt(e,t){if(!Ae(e)||"fixed"===$e(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Te(e)===n&&(n=n.ownerDocument.body),n}function st(e,t){const n=Pe(e);if(Oe(e))return n;if(!Ae(e)){let t=Ke(e);for(;t&&!Ne(t);){if(Re(t)&&!tt(t))return t;t=Ke(t)}return n}let s=nt(e,t);for(;s&&Me(s)&&tt(s);)s=nt(s,t);return s&&Ne(s)&&tt(s)&&!Fe(s)?n:s||(e=>{let t=Ke(e);for(;Ae(t)&&!Ne(t);){if(Fe(t))return t;if(Oe(t))return null;t=Ke(t)}return null})(e)||n}function ot(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function rt({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-shift-padding",8),s=r??it("--toolbar-floating-offset",38),p={top:it("--toolbar-floating-safe-top",64),right:n,bottom:n,left:n};((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:Ee},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}=Se(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}=Se(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:[Sn(s),In({fallbackPlacements:[...t],padding:p}),En({padding:p})]}).then(({placement:t,x:n,y:s})=>{d||e!==u||(l.dataset.placement=t,o?.(t),l.style.transform=`translate3d(${Math.round(n)}px, ${Math.round(s)}px, 0)`,l.style.visibility=a?"visible":"hidden")})},h=function(e,t,n,s){void 0===s&&(s={});const{ancestorScroll:o=!0,ancestorResize:r=!0,elementResize:i="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=s,l=qe(e),d=o||r?[...l?ze(l):[],...t?ze(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||ot(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?Ye(e):null;return c&&function t(){const s=Ye(e);g&&!ot(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 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=Cn,offset:t=8,placement:n="top",referenceElement:o,...r}){const i=u(),a=Ht(null),c=Ft(()=>o,[o]);return s(a),rt({viewport:i.viewport.state,fallbackPlacements:e,floatingRef:a,getReferenceElement:c,offset:t,placement:n}),Vt("div",{...r,ref:a})}function lt(){return Bt(kn)}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),rt({viewport:a.viewport.state,fallbackPlacements:"center"===o?Tn:Pn,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(kn.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,M as mt,O as vt,S as wt,T as yt,a as bt,b as xt,g as St,h as Et,i as It,j as Ct,k as Pt,o as Tt,r as kt,s as Rt,v as At,w as Lt,x as Dt,y as Mt}from"./host-VhUj_Gf6.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&&Oe(t.floating);if(s===i||a&&r)return n;let c={scrollLeft:0,scrollTop:0},l=dn(1);const d=dn(0),u=Ae(s);if((u||!u&&!r)&&(("body"!==Ce(s)||De(i))&&(c=He(s)),u)){const e=Ye(s);l=Ue(s),d.x=e.x+s.clientLeft,d.y=e.y+s.clientTop}const p=!i||u||r?dn(0):Je(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?Oe(t)?[]:Qe(t,this._c):[].concat(n),s],i=Ge(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=Ge(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:st,getElementRects:async function(e){const t=this.getOffsetParent||st,n=this.getDimensions,s=await n(e.floating);return{reference:et(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}=We(e);return{width:t,height:n}},getScale:Ue,isElement:Re,isRTL:e=>"rtl"===$e(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"===ve(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:"shift",options:e,async fn(t){const{x:n,y:s,placement:o,platform:r}=t,{mainAxis:i=!0,crossAxis:a=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=pe(e,t),d={x:n,y:s},u=await r.detectOverflow(t,l),p=ve(he(o)),h=ge(p);let f=d[h],g=d[p];i&&(f=ue(f+u["y"===h?"top":"left"],f,f-u["y"===h?"bottom":"right"])),a&&(g=ue(g+u["y"===p?"top":"left"],g,g-u["y"===p?"bottom":"right"]));const m=c.fn({...t,[h]:f,[p]:g});return{...m,data:{x:m.x-n,y:m.y-s,enabled:{[h]:i,[p]:a}}}}}),In=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=ve(a),y=he(a)===a,b=await(null==c.isRTL?void 0:c.isRTL(l.floating)),x=p||(y||!g?[be(a)]:(e=>{const t=be(e);return[ye(e),t,ye(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(ye)))),r}(a,g,f,b));const E=[a,...x],I=await c.detectOverflow(t,m),C=[];let P=(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=we(e),r=me(o);let i="x"===o?s===(n?"end":"start")?"right":"left":"start"===s?"bottom":"top";return t.reference[r]>t.floating[r]&&(i=be(i)),[i,be(i)]})(o,i,b);C.push(I[e[0]],I[e[1]])}if(P=[...P,{placement:o,overflows:C}],!C.every(e=>e<=0)){var T,k;const e=((null==(T=r.flip)?void 0:T.index)||0)+1,t=E[e];if(t&&("alignment"!==u||w===ve(t)||P.every(e=>ve(e.placement)!==w||e.overflows[0]>0)))return{data:{index:e,overflows:P},reset:{placement:t}};let n=null==(k=P.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=P.filter(e=>{if(S){const t=ve(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{}}}),Cn=["bottom"],Pn=["bottom-start"],Tn=["bottom"],kn=Ot(null);export{at as CanvasKitFloatingContent,le as CanvasKitFloatingToolbarLayer,d as CanvasKitProvider,J as CanvasKitRoot,dt as FloatingSelectionToolbarPageSpace,I as applyCanvasActionShortcutOverrides,t as createCanvasApiToken,ht as createCustomShapeColor,Q as createLocalSnapshotPersistence,Lt as createThemeShapeColor,e as defineCanvasPlugin,E as getCanvasActionShortcuts,yt as getThemeColorTokenName,gt as isCustomShapeColorRef,ft as isThemeShapeColorRef,ne as readPersistedDocumentSnapshot,te as readPersistedEditorSnapshots,se as readPersistedSessionSnapshot,n as requireApi,vt as resolveShapeColor,Pt as shapeColorToCssColor,u as useCanvasKit,c as useCanvasKitFloatingPortalContainer,s as useCanvasKitWheelCapture,p as useCanvasValue,lt as useFloatingSelectionToolbarPosition};
|
|
6
|
+
Vt(i,{})]})})})})}function Z(){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 Q(e={}){return{async load({signal:t}){t.throwIfAborted();const n=await te(e);return t.throwIfAborted(),n},saveDocument:t=>ee({documentSnapshot:JSON.stringify(t),sessionSnapshot:null},e),saveSession:t=>ee({documentSnapshot:null,sessionSnapshot:JSON.stringify(t)},e)}}async function ee(e,t){const n=[];null!==e.documentSnapshot&&n.push([oe(t),e.documentSnapshot]),null!==e.sessionSnapshot&&n.push([re(t),e.sessionSnapshot]),0!==n.length&&await(async(e,t)=>{if(0===t.length)return;const n=await Z();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 te(e={}){const[t,n]=await ae([oe(e),re(e)]);return{documentSnapshot:t,sessionSnapshot:n}}async function ne(){return ie(sn)}async function se(){return ie(on)}function oe(e){return e.storageNamespace?`${e.storageNamespace}.document`:sn}function re(e){return e.storageNamespace?`${e.storageNamespace}.session`:on}async function ie(e){const[t]=await ae([e]);return t??null}async function ae(e){return(await(async(e,t)=>{if(0===t.length)return[];const n=await Z();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(ce)}function ce(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 le({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){const s=a();return s?qt(Vt("div",{"data-ui":n,className:de("land-canvas__floating-toolbar-layer",t),children:e}),s):null}function de(...e){return e.filter(Boolean).join(" ")}function ue(e,t,n){return an(e,rn(t,n))}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"x"===e?"y":"x"}function me(e){return"y"===e?"height":"width"}function ve(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function we(e){return ge(ve(e))}function ye(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}function be(e){const t=he(e);return un[t]+e.slice(t.length)}function xe(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 Se(e,t,n){let{reference:s,floating:o}=e;const r=ve(t),i=we(t),a=me(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 Ee(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=xe(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=xe(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 Ie(){return"undefined"!=typeof window}function Ce(e){return ke(e)?(e.nodeName||"").toLowerCase():"#document"}function Pe(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Te(e){var t;return null==(t=(ke(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function ke(e){return!!Ie()&&(e instanceof Node||e instanceof Pe(e).Node)}function Re(e){return!!Ie()&&(e instanceof Element||e instanceof Pe(e).Element)}function Ae(e){return!!Ie()&&(e instanceof HTMLElement||e instanceof Pe(e).HTMLElement)}function Le(e){return!(!Ie()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Pe(e).ShadowRoot)}function De(e){const{overflow:t,overflowX:n,overflowY:s,display:o}=$e(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+n)&&"inline"!==o&&"contents"!==o}function Me(e){return/^(table|td|th)$/.test(Ce(e))}function Oe(e){try{if(e.matches(":popover-open"))return!0}catch(t){}try{return e.matches(":modal")}catch(t){return!1}}function Fe(e){const t=Re(e)?$e(e):e;return yn(t.transform)||yn(t.translate)||yn(t.scale)||yn(t.rotate)||yn(t.perspective)||!Be()&&(yn(t.backdropFilter)||yn(t.filter))||vn.test(t.willChange||"")||wn.test(t.contain||"")}function Be(){return null==Ut&&(Ut="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ut}function Ne(e){return/^(html|body|#document)$/.test(Ce(e))}function $e(e){return Pe(e).getComputedStyle(e)}function He(e){return Re(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Ke(e){if("html"===Ce(e))return e;const t=e.assignedSlot||e.parentNode||Le(e)&&e.host||Te(e);return Le(t)?t.host:t}function je(e){const t=Ke(e);return Ne(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ae(t)&&De(t)?t:je(t)}function ze(e,t,n){var s;void 0===t&&(t=[]),void 0===n&&(n=!0);const o=je(e),r=o===(null==(s=e.ownerDocument)?void 0:s.body),i=Pe(o);if(r){const e=Ve(i);return t.concat(i,i.visualViewport||[],De(o)?o:[],e&&n?ze(e):[])}return t.concat(o,ze(o,[],n))}function Ve(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function We(e){const t=$e(e);let n=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Ae(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 qe(e){return Re(e)?e:e.contextElement}function Ue(e){const t=qe(e);if(!Ae(t))return dn(1);const n=t.getBoundingClientRect(),{width:s,height:o,$:r}=We(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 _e(e){const t=Pe(e);return Be()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:bn}function Ye(e,t,n,s){void 0===t&&(t=!1),void 0===n&&(n=!1);const o=e.getBoundingClientRect(),r=qe(e);let i=dn(1);t&&(s?Re(s)&&(i=Ue(s)):i=Ue(e));const a=((e,t,n)=>(void 0===t&&(t=!1),!(!n||t&&n!==Pe(e))&&t))(r,n,s)?_e(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=Pe(r),t=s&&Re(s)?Pe(s):s;let n=e,o=Ve(n);for(;o&&s&&t!==n;){const e=Ue(o),t=o.getBoundingClientRect(),s=$e(o),r=t.left+(o.clientLeft+parseFloat(s.paddingLeft))*e.x,i=t.top+(o.clientTop+parseFloat(s.paddingTop))*e.y;c*=e.x,l*=e.y,d*=e.x,u*=e.y,c+=r,l+=i,n=Pe(o),o=Ve(n)}}return xe({width:d,height:u,x:c,y:l})}function Xe(e,t){const n=He(e).scrollLeft;return t?t.left+n:Ye(Te(e)).left+n}function Je(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Xe(e,n),y:n.top+t.scrollTop}}function Ge(e,t,n){let s;if("viewport"===t)s=((e,t)=>{const n=Pe(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=Be();(!e||e&&"fixed"===t)&&(a=o.offsetLeft,c=o.offsetTop)}const l=Xe(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=He(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+Xe(e);const a=-n.scrollTop;return"rtl"===$e(s).direction&&(i+=an(t.clientWidth,s.clientWidth)-o),{width:o,height:r,x:i,y:a}})(Te(e));else if(Re(t))s=((e,t)=>{const n=Ye(e,!0,"fixed"===t),s=n.top+e.clientTop,o=n.left+e.clientLeft,r=Ae(e)?Ue(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=_e(e);s={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return xe(s)}function Ze(e,t){const n=Ke(e);return!(n===t||!Re(n)||Ne(n))&&("fixed"===$e(n).position||Ze(n,t))}function Qe(e,t){const n=t.get(e);if(n)return n;let s=ze(e,[],!1).filter(e=>Re(e)&&"body"!==Ce(e)),o=null;const r="fixed"===$e(e).position;let i=r?Ke(e):e;for(;Re(i)&&!Ne(i);){const t=$e(i),n=Fe(i);n||"fixed"!==t.position||(o=null),(r?!n&&!o:!n&&"static"===t.position&&o&&("absolute"===o.position||"fixed"===o.position)||De(i)&&!n&&Ze(e,i))?s=s.filter(e=>e!==i):o=t,i=Ke(i)}return t.set(e,s),s}function et(e,t,n){function s(){l.x=Xe(r)}const o=Ae(t),r=Te(t),i="fixed"===n,a=Ye(e,!0,i,t);let c={scrollLeft:0,scrollTop:0};const l=dn(0);if(o||!o&&!i)if(("body"!==Ce(t)||De(r))&&(c=He(t)),o){const e=Ye(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):Je(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 tt(e){return"static"===$e(e).position}function nt(e,t){if(!Ae(e)||"fixed"===$e(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Te(e)===n&&(n=n.ownerDocument.body),n}function st(e,t){const n=Pe(e);if(Oe(e))return n;if(!Ae(e)){let t=Ke(e);for(;t&&!Ne(t);){if(Re(t)&&!tt(t))return t;t=Ke(t)}return n}let s=nt(e,t);for(;s&&Me(s)&&tt(s);)s=nt(s,t);return s&&Ne(s)&&tt(s)&&!Fe(s)?n:s||(e=>{let t=Ke(e);for(;Ae(t)&&!Ne(t);){if(Fe(t))return t;if(Oe(t))return null;t=Ke(t)}return null})(e)||n}function ot(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function rt({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-shift-padding",8),s=r??it("--toolbar-floating-offset",38),p={top:it("--toolbar-floating-safe-top",64),right:n,bottom:n,left:n};((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:Ee},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}=Se(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}=Se(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:[Sn(s),In({fallbackPlacements:[...t],padding:p}),En({padding:p})]}).then(({placement:t,x:n,y:s})=>{d||e!==u||(l.dataset.placement=t,o?.(t),l.style.transform=`translate3d(${Math.round(n)}px, ${Math.round(s)}px, 0)`,l.style.visibility=a?"visible":"hidden")})},h=function(e,t,n,s){void 0===s&&(s={});const{ancestorScroll:o=!0,ancestorResize:r=!0,elementResize:i="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=s,l=qe(e),d=o||r?[...l?ze(l):[],...t?ze(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||ot(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?Ye(e):null;return c&&function t(){const s=Ye(e);g&&!ot(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 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=Cn,offset:t=8,placement:n="top",referenceElement:o,...r}){const i=u(),a=Ht(null),c=Ft(()=>o,[o]);return s(a),rt({viewport:i.viewport.state,fallbackPlacements:e,floatingRef:a,getReferenceElement:c,offset:t,placement:n}),Vt("div",{...r,ref:a})}function lt(){return Bt(kn)}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),rt({viewport:a.viewport.state,fallbackPlacements:"center"===o?Tn:Pn,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(kn.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 Pt,j as Tt,k as kt,o as Rt,r as At,u as Lt,x as Dt,z as Mt}from"./host-BUc0SJe2.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&&Oe(t.floating);if(s===i||a&&r)return n;let c={scrollLeft:0,scrollTop:0},l=dn(1);const d=dn(0),u=Ae(s);if((u||!u&&!r)&&(("body"!==Ce(s)||De(i))&&(c=He(s)),u)){const e=Ye(s);l=Ue(s),d.x=e.x+s.clientLeft,d.y=e.y+s.clientTop}const p=!i||u||r?dn(0):Je(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?Oe(t)?[]:Qe(t,this._c):[].concat(n),s],i=Ge(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=Ge(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:st,getElementRects:async function(e){const t=this.getOffsetParent||st,n=this.getDimensions,s=await n(e.floating);return{reference:et(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}=We(e);return{width:t,height:n}},getScale:Ue,isElement:Re,isRTL:e=>"rtl"===$e(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"===ve(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:"shift",options:e,async fn(t){const{x:n,y:s,placement:o,platform:r}=t,{mainAxis:i=!0,crossAxis:a=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=pe(e,t),d={x:n,y:s},u=await r.detectOverflow(t,l),p=ve(he(o)),h=ge(p);let f=d[h],g=d[p];i&&(f=ue(f+u["y"===h?"top":"left"],f,f-u["y"===h?"bottom":"right"])),a&&(g=ue(g+u["y"===p?"top":"left"],g,g-u["y"===p?"bottom":"right"]));const m=c.fn({...t,[h]:f,[p]:g});return{...m,data:{x:m.x-n,y:m.y-s,enabled:{[h]:i,[p]:a}}}}}),In=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=ve(a),y=he(a)===a,b=await(null==c.isRTL?void 0:c.isRTL(l.floating)),x=p||(y||!g?[be(a)]:(e=>{const t=be(e);return[ye(e),t,ye(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(ye)))),r}(a,g,f,b));const E=[a,...x],I=await c.detectOverflow(t,m),C=[];let P=(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=we(e),r=me(o);let i="x"===o?s===(n?"end":"start")?"right":"left":"start"===s?"bottom":"top";return t.reference[r]>t.floating[r]&&(i=be(i)),[i,be(i)]})(o,i,b);C.push(I[e[0]],I[e[1]])}if(P=[...P,{placement:o,overflows:C}],!C.every(e=>e<=0)){var T,k;const e=((null==(T=r.flip)?void 0:T.index)||0)+1,t=E[e];if(t&&("alignment"!==u||w===ve(t)||P.every(e=>ve(e.placement)!==w||e.overflows[0]>0)))return{data:{index:e,overflows:P},reset:{placement:t}};let n=null==(k=P.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=P.filter(e=>{if(S){const t=ve(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{}}}),Cn=["bottom"],Pn=["bottom-start"],Tn=["bottom"],kn=Ot(null);export{at as CanvasKitFloatingContent,le as CanvasKitFloatingToolbarLayer,d as CanvasKitProvider,J as CanvasKitRoot,dt as FloatingSelectionToolbarPageSpace,I as applyCanvasActionShortcutOverrides,t as createCanvasApiToken,pt as createCustomShapeColor,Q as createLocalSnapshotPersistence,Tt as createThemeShapeColor,e as defineCanvasPlugin,E as getCanvasActionShortcuts,yt as getThemeColorTokenName,bt as isCustomShapeColorRef,St as isThemeShapeColorRef,ne as readPersistedDocumentSnapshot,te as readPersistedEditorSnapshots,se 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};
|
package/package.json
CHANGED
package/plugin-runtime.d.ts
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
export
|
|
3
|
-
export type { AnyRegisteredSelectionCustomHandleRenderer, AnyRegisteredShapeRenderer, CanvasDomEventGuard, CanvasDomEventGuardCursorInput, CanvasDomEventGuardDecision, CanvasDomEventGuardInput, CanvasDomEventGuardName, CanvasDomEventGuards, CanvasOverlayContribution, CanvasOverlayLookup, CanvasRenderBindings, CanvasRendererLookup, CanvasRenderPlugin, CanvasRenderPluginComponent, RegisteredSelectionCustomHandleRenderer, RegisteredShapeRenderer, SelectionCustomHandleRendererProps, ShapeHeadingControlProps, ShapeHeadingDataUi, ShapeHoverRendererProps, ShapeOpacityModifier, ShapeRendererProps, } from "./_vendor/canvas-react/host/index";
|
|
1
|
+
export * from "./_vendor/canvas-react/index";
|
|
2
|
+
export * from "./_vendor/canvas-react/host/index";
|
package/plugin-runtime.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
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-BUc0SJe2.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};
|