@hy-bricks/canvas 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
1
  !function(){"use strict";try{if("undefined"!=typeof document){var e=document.createElement("style");e.appendChild(document.createTextNode(".hc-canvas-stage[data-v-825e0ee8]{position:relative;width:100%;height:100%;overflow:hidden;background:#f1f5f9;isolation:isolate}.hc-canvas-stage__world[data-v-825e0ee8]{position:absolute;top:0;left:0;will-change:transform}")),document.head.appendChild(e)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}}();
2
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),n=require("@hy-bricks/core");function t(e){return JSON.parse(JSON.stringify(e))}const o="[hc-canvas/normalizeBindings]";function i(e){if(!Array.isArray(e))return[];const n=[];for(let t=0;t<e.length;t++){const i=e[t];if(!i||"object"!=typeof i){console.warn(`${o} dropped non-object binding at index ${t}`);continue}if(a(i)){n.push(i);continue}const c=r(i);null!==c&&n.push(c)}return n}function a(e){if(!e||"object"!=typeof e)return!1;const n=e;if("string"!=typeof n.id||0===n.id.length)return!1;if("event"!==n.type&&"init"!==n.type&&"data"!==n.type)return!1;const t=n.source;if(!t||"object"!=typeof t)return!1;if("string"!=typeof t.kind)return!1;const o=n.target;return!(!o||"object"!=typeof o)&&"string"==typeof o.kind}function r(e){if("string"!=typeof e.id||0===e.id.length)return console.warn(`${o} dropped binding with missing/invalid id`),null;const n=e.target;if(!n||"object"!=typeof n||"string"!=typeof n.instanceId||""===n.instanceId||"string"!=typeof n.method)return console.warn(`${o} dropped binding "${e.id}" missing/invalid target`),null;const i=e.type;let a;if("event"===i){const n=e.source;if(!n||"object"!=typeof n||"string"!=typeof n.instanceId||""===n.instanceId||"string"!=typeof n.event)return console.warn(`${o} dropped event binding "${e.id}" missing/invalid source`),null;a={kind:"instanceEvent",instanceId:n.instanceId,event:n.event}}else{if("init"!==i)return console.warn(`${o} dropped binding "${e.id}" with unknown legacy type "${String(e.type)}"`),null;{const n=e.source;n&&"string"==typeof n.instanceId&&""!==n.instanceId&&console.warn(`${o} init binding "${e.id}" had source.instanceId, discarded`),a={kind:"page",hook:"pageInit"}}}const r={kind:"instanceMethod",instanceId:n.instanceId,method:n.method};let c;c=void 0===n.args?{kind:"passthrough"}:Array.isArray(n.args)&&0===n.args.length?{kind:"static",args:[]}:Array.isArray(n.args)?{kind:"static",args:t(n.args)}:{kind:"passthrough"};const s={},d=e.options;d&&"object"==typeof d&&(!0===d.once&&(s.once=!0),"number"==typeof d.throttleMs&&(s.throttle={windowMs:d.throttleMs}),"number"==typeof d.debounceMs&&(s.debounce={windowMs:d.debounceMs}));const l=void 0!==s.once||void 0!==s.throttle||void 0!==s.debounce,u={id:e.id,source:a,target:r,mapping:c,...void 0!==e.disabled?{disabled:e.disabled}:{},...l?{schedule:s}:{}};return"event"===i?{...u,type:"event"}:{...u,type:"init"}}function c(e){const n=e.instances.map(p),t=u(e.componentOverrides,n),o=i(e.bindings);if("1"===e.schemaVersion){const i=R(w(e.layout)?e.layout:I(e.layout));return{...e,layout:i,instances:n,bindings:o,componentOverrides:t}}return{schemaVersion:"1",layout:R(I(e.layout)),instances:n,bindings:o,componentOverrides:t}}function s(e){const n=function(e){var n;const t=new Map;for(const o of e){if(!o.parentId)continue;if(void 0!==o.slot)continue;const e=t.get(o.parentId),i=null==(n=o.layoutItem)?void 0:n.ratio;e?e.push(i):t.set(o.parentId,[i])}let o=!1;const i=e.map(e=>{if(!e.containerLayout||"split"!==e.containerLayout.mode)return e;const n=t.get(e.instanceId)??[],i=e.containerLayout.ratios,a=y(i,n);return i.length===a.length&&i.every((e,n)=>e===a[n])?e:(o=!0,{...e,containerLayout:{...e.containerLayout,ratios:a}})});return o?i:e}(e.instances),t=e.layout.rootLayout?function(e,n){const t=e.rootLayout;if(!t||"split"!==t.mode)return e;const o=n.filter(e=>void 0===e.parentId).map(e=>{var n;return null==(n=e.layoutItem)?void 0:n.ratio}),i=t.ratios,a=y(i,o);return i.length===a.length&&i.every((e,n)=>e===a[n])?e:{...e,rootLayout:{...t,ratios:a}}}(e.layout,n):e.layout;return n===e.instances&&t===e.layout?e:{...e,layout:t,instances:n}}function d(e){const n=new Map,t=new Set;for(const o of e.instances){const e=o.containerLayout;if("grid"!==(null==e?void 0:e.mode))continue;t.add(o.instanceId);const i=e.cells;i&&"object"==typeof i&&Object.keys(i).length>0&&n.set(o.instanceId,l(i))}if(0===t.size)return e;let o=!1;const i=e.instances.map(e=>{if(!e.parentId)return e;if(void 0!==e.slot)return e;if(!t.has(e.parentId))return e;const i=e.layoutItem;if(i&&("number"==typeof i.row||"number"==typeof i.column)){const n=function(e){const n="number"==typeof e.row&&Number.isFinite(e.row)&&e.row<1,t="number"==typeof e.column&&Number.isFinite(e.column)&&e.column<1;if(!n&&!t)return e;const o={...e};return n&&(o.row=1),t&&(o.column=1),o}(i);return n===i?e:(o=!0,{...e,layoutItem:n})}const a=n.get(e.parentId),r=null==a?void 0:a[e.instanceId];if(!r)return e;const c=function(e){const n={};return"number"==typeof e.row&&Number.isFinite(e.row)&&(n.row=e.row<1?1:e.row),"number"==typeof e.column&&Number.isFinite(e.column)&&(n.column=e.column<1?1:e.column),void 0===n.row&&void 0===n.column?null:("number"==typeof e.rowSpan&&Number.isFinite(e.rowSpan)&&e.rowSpan>0&&e.rowSpan<=32&&(n.rowSpan=e.rowSpan),"number"==typeof e.columnSpan&&Number.isFinite(e.columnSpan)&&e.columnSpan>0&&e.columnSpan<=32&&(n.columnSpan=e.columnSpan),n)}(r);return c?(o=!0,{...e,layoutItem:{...i??{},...c}}):e});return o?{...e,instances:i}:e}function l(e){let n=!1;for(const t of Object.values(e))if(t&&(0===t.row||0===t.column)){n=!0;break}if(!n)return e;const t={};for(const[n,o]of Object.entries(e)){if(!o)continue;const e={...o};"number"==typeof e.row&&Number.isFinite(e.row)&&(e.row=e.row+1),"number"==typeof e.column&&Number.isFinite(e.column)&&(e.column=e.column+1),t[n]=e}return t}function u(e,n){if(!e||"object"!=typeof e||Array.isArray(e))return{};const t=new Set(n.map(e=>e.instanceId)),o={};for(const[n,i]of Object.entries(e)){if(!i||"object"!=typeof i||Array.isArray(i))continue;const e=i;e.instanceId===n&&t.has(e.instanceId)&&"string"==typeof e.baseVersionKey&&e.baseVersionKey&&T(e.source)&&C(e.contract)&&(o[n]={instanceId:e.instanceId,baseVersionKey:e.baseVersionKey,source:e.source,contract:e.contract,...z(e.contractParseError)?{contractParseError:z(e.contractParseError)}:{},..."string"==typeof e.createdAt?{createdAt:e.createdAt}:{},..."string"==typeof e.updatedAt?{updatedAt:e.updatedAt}:{}})}return o}function p(e){let n=e;void 0===n.parentId&&n.slotPlacement&&(n={...n,parentId:n.slotPlacement.parentInstanceId,slot:n.slotPlacement.slotName}),""!==n.slot&&"default"!==n.slot||(n={...n,slot:void 0}),void 0===n.placement&&(n={...n,placement:void 0===n.parentId?"absolute":"slot"});const t=h(n.sizing,n.size);if(t!==n.size&&(n={...n,size:t}),void 0!==n.containerLayout){const e=v(n.containerLayout);if(e!==n.containerLayout)if(null===e){const{containerLayout:e,...t}=n;n=t}else n={...n,containerLayout:e}}if(n=P(n),n=D(n),void 0!==n.layoutItem){const e=A(n.layoutItem);if(null===e){const{layoutItem:e,...t}=n;n=t}else e!==n.layoutItem&&(n={...n,layoutItem:e})}if(!0===n.locked){const e={};void 0===n.lockPosition&&(e.lockPosition=!0),void 0===n.lockSize&&(e.lockSize=!0),Object.keys(e).length>0&&(n={...n,...e})}return n}const f=new Set(["px","percent","fill","hug","auto"]);function h(e,n){var t,o,i,a;const r=n?function(e){const n={},t=m(e.width),o=m(e.height);return t&&(n.width=t),o&&(n.height=o),n.width||n.height?n:void 0}(n):void 0;if(!e)return r;const c={};if(e.width){const n=g(e.width,null==(t=e.min)?void 0:t.w,null==(o=e.max)?void 0:o.w);n&&(c.width=n)}if(e.height){const n=g(e.height,null==(i=e.min)?void 0:i.h,null==(a=e.max)?void 0:a.h);n&&(c.height=n)}return r?{width:r.width??c.width,height:r.height??c.height}:Object.keys(c).length>0?c:void 0}function g(e,n,t){if(!e||"object"!=typeof e)return null;let o;switch(e.mode){case"fixed":o="px";break;case"percent":o="percent";break;case"fill":o="fill";break;case"hug":o="hug";break;default:return null}const i={mode:o};return"px"!==o&&"percent"!==o||"number"!=typeof e.value||(i.value=e.value),"number"==typeof n&&(i.min=n),"number"==typeof t&&(i.max=t),i}function m(e){if(!e||"object"!=typeof e)return null;if("string"!=typeof e.mode)return null;if(!f.has(e.mode))return null;const n={mode:e.mode};return"px"!==e.mode&&"percent"!==e.mode||"number"!=typeof e.value||(n.value=e.value),"number"==typeof e.min&&(n.min=e.min),"number"==typeof e.max&&(n.max=e.max),n}function v(e){if(!e||"object"!=typeof e)return null;if("none"===e.mode)return{mode:"none"};if("free"===e.mode)return{mode:"free"};if("flex"===e.mode){const n=e,t={mode:"flex",direction:"row"===n.direction||"column"===n.direction?n.direction:"row"};return!0===n.wrap&&(t.wrap=!0),"number"==typeof n.gap&&Number.isFinite(n.gap)&&n.gap>=0&&(t.gap=n.gap),"start"!==n.justify&&"center"!==n.justify&&"end"!==n.justify&&"space-between"!==n.justify&&"space-around"!==n.justify||(t.justify=n.justify),"start"!==n.align&&"center"!==n.align&&"end"!==n.align&&"stretch"!==n.align||(t.align=n.align),t}if("split"===e.mode){const n=e;if("horizontal"!==n.direction&&"vertical"!==n.direction)return null;if(!Array.isArray(n.ratios))return null;const t=n.ratios.filter(e=>"number"==typeof e&&Number.isFinite(e)&&e>=0),o={mode:"split",direction:n.direction,ratios:t};return"number"==typeof n.gap&&Number.isFinite(n.gap)&&n.gap>=0&&(o.gap=n.gap),o}if("grid"===e.mode){const n=e;if(!Array.isArray(n.columns)||!Array.isArray(n.rows))return null;const t={mode:"grid",columns:n.columns.filter(e=>!!e&&("fr"===e.mode||"px"===e.mode||"percent"===e.mode)&&"number"==typeof e.value&&Number.isFinite(e.value)&&e.value>=0).slice(0,32),rows:n.rows.filter(e=>!!e&&("fr"===e.mode||"px"===e.mode||"percent"===e.mode||"auto"===e.mode)&&("auto"===e.mode&&void 0===e.value||"number"==typeof e.value&&Number.isFinite(e.value)&&e.value>=0)).slice(0,32)};if("number"==typeof n.gap&&Number.isFinite(n.gap)&&n.gap>=0)t.gap=n.gap;else if(n.gap&&"object"==typeof n.gap){const e={};"number"==typeof n.gap.row&&Number.isFinite(n.gap.row)&&n.gap.row>=0&&(e.row=n.gap.row),"number"==typeof n.gap.column&&Number.isFinite(n.gap.column)&&n.gap.column>=0&&(e.column=n.gap.column),Object.keys(e).length>0&&(t.gap=e)}if(n.cells&&"object"==typeof n.cells&&!Array.isArray(n.cells)){const e={};for(const[t,o]of Object.entries(n.cells)){if(!o||"object"!=typeof o)continue;if(!Number.isFinite(o.row)||!Number.isFinite(o.column))continue;const n={row:o.row,column:o.column};"number"==typeof o.rowSpan&&Number.isFinite(o.rowSpan)&&o.rowSpan>0&&o.rowSpan<=32&&(n.rowSpan=o.rowSpan),"number"==typeof o.columnSpan&&Number.isFinite(o.columnSpan)&&o.columnSpan>0&&o.columnSpan<=32&&(n.columnSpan=o.columnSpan),e[t]=n}Object.keys(e).length>0&&(t.cells=e)}return t}return null}function y(e,n){const t=(e??[]).map(e=>"number"==typeof e&&Number.isFinite(e)&&e>=0?e:0),o=[];for(let e=0;e<n.length;e++){const i=n[e];if("number"==typeof i&&Number.isFinite(i)&&i>0){o.push(i);continue}const a=t[e];"number"==typeof a&&a>0?o.push(a):o.push(1)}return o}function I(e){if(!e)return{type:"free",canvas:{width:{mode:"px",value:1920},height:{mode:"px",value:1080}}};if(w(e))return e;const n=e,t={width:{mode:"px",value:n.canvas.w},height:{mode:"px",value:n.canvas.h}},o=function(e){if(!e)return;const n={};if(void 0!==e.color&&(n.color=e.color),void 0!==e.imageAssetId){const t={id:e.imageAssetId,type:"image"};n.image=t}return void 0!==e.fit&&(n.imageFit="original"===e.fit?"center":e.fit),Object.keys(n).length>0?n:void 0}(n.canvas.background),i={type:n.type,canvas:t};return o&&(i.background=o),void 0!==n.canvas.gridSize&&(i.guides={grid:{size:n.canvas.gridSize}}),i}function w(e){if(!e)return!1;const n=e.canvas;if(!n)return!1;const t=n.width;return"object"==typeof t&&null!==t&&"mode"in t&&"string"==typeof t.mode}function x(e,n,t=1920){switch(e.mode){case"px":return e.value;case"percent":return n>0?n*e.value/100:t;case"vw":return"undefined"!=typeof window?window.innerWidth*e.value/100:t;case"vh":return"undefined"!=typeof window?window.innerHeight*e.value/100:t;case"auto":case"fill":return n>0?n:t}}function b(e,n,t,o,i){const a=k(e.widthMode,e.width),r=k(e.heightMode,e.height),c="free"===o,s={boxSizing:"border-box",minWidth:0,minHeight:0,overflow:e.overflow??"hidden",zIndex:n};return null!==a&&(s.width=a),null!==r&&(s.height=r),"split"===o&&("vertical"===i?s.height="100%":s.width="100%"),"number"==typeof t&&Number.isFinite(t)&&0!==t&&(s.transform=`rotate(${t}deg)`),c?(s.position="absolute",s.left=`${e.x}px`,s.top=`${e.y}px`):s.position="relative",s}function k(e,n){switch(e){case"px":return`${n}px`;case"percent":return`${n}%`;case"fill":return"100%";case"auto":return"auto"}}function S(e){if(!e||"none"===e.mode||"free"===e.mode)return null;if("flex"===e.mode){const n={display:"flex"};if(n.flexDirection=e.direction??"row",e.wrap&&(n.flexWrap="wrap"),"number"==typeof e.gap&&(n.gap=`${e.gap}px`),e.justify){const t={start:"flex-start",end:"flex-end",center:"center","space-between":"space-between","space-around":"space-around"};n.justifyContent=t[e.justify]??e.justify}if(e.align){const t={start:"flex-start",end:"flex-end",center:"center",stretch:"stretch"};n.alignItems=t[e.align]??e.align}return n}if("grid"===e.mode){const n={display:"grid"},t=(e.columns??[]).map(e=>"fr"===e.mode?`${e.value}fr`:"px"===e.mode?`${e.value}px`:`${e.value}%`).join(" "),o=(e.rows??[]).map(e=>"auto"===e.mode?"auto":"fr"===e.mode?`${e.value??1}fr`:"px"===e.mode?`${e.value??0}px`:`${e.value??0}%`).join(" ");if(t&&(n.gridTemplateColumns=t),o&&(n.gridTemplateRows=o),"number"==typeof e.gap)n.gap=`${e.gap}px`;else if(e.gap&&"object"==typeof e.gap){const t=e.gap.row??0,o=e.gap.column??0;n.gap=`${t}px ${o}px`}return n}if("split"===e.mode){const n=(Array.isArray(e.ratios)?e.ratios:[]).map(e=>"number"==typeof e&&Number.isFinite(e)&&e>=0?e:0).filter(e=>e>0),t=n.length>0?n.map(e=>`${e}fr`).join(" "):"1fr",o={display:"grid"};return"vertical"===e.direction?o.gridTemplateRows=t:o.gridTemplateColumns=t,"number"==typeof e.gap&&(o.gap=`${e.gap}px`),o}return null}function B(e,n){if(!e)return null;if("flex"===n){const n={};return"number"==typeof e.order&&(n.order=e.order),"number"==typeof e.grow&&(n.flexGrow=e.grow),"number"==typeof e.shrink&&(n.flexShrink=e.shrink),Object.keys(n).length>0?n:null}if("grid"===n){const n={};if("number"==typeof e.row){const t="number"==typeof e.rowSpan&&e.rowSpan>0?e.rowSpan:1;n.gridRow=t>1?`${e.row} / span ${t}`:`${e.row}`}if("number"==typeof e.column){const t="number"==typeof e.columnSpan&&e.columnSpan>0?e.columnSpan:1;n.gridColumn=t>1?`${e.column} / span ${t}`:`${e.column}`}return Object.keys(n).length>0?n:null}return null}function M(e){switch(e.mode){case"px":return`${e.value}px`;case"percent":return`${e.value}%`;case"vw":return`${e.value}vw`;case"vh":return`${e.value}vh`;case"auto":return"auto";case"fill":return"100%"}}function T(e){return!!e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.html&&"string"==typeof e.js&&"string"==typeof e.css}function C(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const n=e;return["propsDecl","emitsDecl","methodsDecl","slotsDecl","modelDecl","dataInputsDecl","dataOutputsDecl"].every(e=>Array.isArray(n[e]))}function z(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const n=e;return"string"==typeof n.message?{message:n.message,..."number"==typeof n.line?{line:n.line}:{},..."number"==typeof n.column?{column:n.column}:{}}:void 0}const L=new Set(["px","percent","fill","auto"]),E=new Set(["hidden","visible","auto"]);function P(e){const n=e.placement;return"canvas"===n||"container"===n?e:"absolute"===n?{...e,placement:"canvas"}:"slot"===n?{...e,placement:"container"}:{...e,placement:e.parentId?"container":"canvas"}}function D(e){var n,t;const o=e.rect??{x:0,y:0,w:0,h:0},i=null==(n=e.size)?void 0:n.width,a=null==(t=e.size)?void 0:t.height,r=e=>{if(e)return"hug"===e.mode?"auto":"percent"===e.mode?"percent":"fill"===e.mode?"fill":"auto"===e.mode?"auto":"px"===e.mode?"px":void 0},c=e.layoutBox,s=c&&L.has(c.widthMode)?c.widthMode:r(i)??"px",d=c&&L.has(c.heightMode)?c.heightMode:r(a)??"px",l=(e,n)=>"number"==typeof e&&Number.isFinite(e)?e:n,u={x:l(null==c?void 0:c.x,o.x),y:l(null==c?void 0:c.y,o.y),width:l(null==c?void 0:c.width,(null==i?void 0:i.value)??o.w),height:l(null==c?void 0:c.height,(null==a?void 0:a.value)??o.h),widthMode:s,heightMode:d,overflow:(null==c?void 0:c.overflow)&&E.has(c.overflow)?c.overflow:"hidden"};return c&&c.x===u.x&&c.y===u.y&&c.width===u.width&&c.height===u.height&&c.widthMode===u.widthMode&&c.heightMode===u.heightMode&&c.overflow===u.overflow?e:{...e,layoutBox:u}}function R(e){if(e.rootLayout){const o=v(e.rootLayout);return null===o?{...e,rootLayout:{mode:"free"}}:(t=o,(n=e.rootLayout).mode===t.mode&&JSON.stringify(n)===JSON.stringify(t)?e:{...e,rootLayout:o})}var n,t;return{...e,rootLayout:{mode:"free"}}}function O(e){return"container"===e||"slot"===e}function $(e,n,t){var o,i;const a=n.find(e=>e.instanceId===t);if(!a)return;if(void 0===a.parentId)return(null==(o=null==e?void 0:e.rootLayout)?void 0:o.mode)??"free";const r=n.find(e=>e.instanceId===a.parentId);return(null==(i=null==r?void 0:r.containerLayout)?void 0:i.mode)??"none"}function A(e){if(!e||"object"!=typeof e)return null;const n={},t=["order","grow","shrink","row","column","rowSpan","columnSpan","ratio"];for(const o of t){const t=e[o];"number"==typeof t&&Number.isFinite(t)&&(n[o]=t)}return Object.keys(n).length>0?n:null}function N(n={}){const{rootMargin:t="500px",disposeDelayMs:o=1500,mountConcurrency:i=2,root:a=null}=n,r={state:e.reactive({}),elById:new Map,idByEl:new WeakMap,mountQueue:[],disposeTimers:new Map,idleScheduled:!1,io:null};function c(e){for(const n of e){const e=r.idByEl.get(n.target);e&&(n.isIntersecting?s(e):d(e))}}function s(e){const n=r.disposeTimers.get(e);n&&(clearTimeout(n),r.disposeTimers.delete(e));const t=r.state[e];"mounted"!==t&&"disposing"!==t?(r.state[e]="mounting",r.mountQueue.includes(e)||r.mountQueue.push(e),l()):r.state[e]="mounted"}function d(e){const n=r.state[e];if("pending"===n||"idle"===n)return;if("mounting"===n){const n=r.mountQueue.indexOf(e);return n>=0&&r.mountQueue.splice(n,1),void(r.state[e]="pending")}r.state[e]="disposing";const t=r.disposeTimers.get(e);t&&clearTimeout(t);const i=setTimeout(()=>{"disposing"===r.state[e]&&(r.state[e]="pending",r.disposeTimers.delete(e))},o);r.disposeTimers.set(e,i)}function l(){r.idleScheduled||0===r.mountQueue.length||(r.idleScheduled=!0,function(e,n=50){const t=globalThis;"function"==typeof t.requestIdleCallback?t.requestIdleCallback(()=>e(),{timeout:n}):setTimeout(e,16)}(()=>{r.idleScheduled=!1;let e=0;for(;e<i&&r.mountQueue.length>0;){const n=r.mountQueue.shift();"mounting"===r.state[n]&&(r.state[n]="mounted",e++)}r.mountQueue.length>0&&l()}))}return{register(e,n){const o=r.elById.get(e);if(o&&o!==n){const e=r.io;e&&e.unobserve(o),r.idByEl.delete(o)}r.elById.set(e,n),r.idByEl.set(n,e),r.state[e]="pending";const i=r.io?r.io:"undefined"==typeof IntersectionObserver?null:(r.io=new IntersectionObserver(c,{root:a,rootMargin:t}),r.io);i?i.observe(n):r.state[e]="mounted"},unregister(e){const n=r.elById.get(e);if(n){const t=r.io;t&&t.unobserve(n),r.idByEl.delete(n),r.elById.delete(e)}const t=r.disposeTimers.get(e);t&&(clearTimeout(t),r.disposeTimers.delete(e));const o=r.mountQueue.indexOf(e);o>=0&&r.mountQueue.splice(o,1),delete r.state[e]},isMounted(e){const n=r.state[e];return"mounted"===n||"disposing"===n},getState:e=>r.state[e]??"idle",get state(){return r.state},dispose(){r.io&&(r.io.disconnect(),r.io=null);for(const e of r.disposeTimers.values())clearTimeout(e);r.disposeTimers.clear(),r.elById.clear(),r.mountQueue.length=0;for(const e of Object.keys(r.state))delete r.state[e]}}}function F(e){const n=[];switch(e.source.kind){case"instanceEvent":case"lifecycle":n.push({canvasId:e.source.canvasId,instanceId:e.source.instanceId});break;case"page":case"dataSource":break;default:V(e.source)}switch(e.target.kind){case"instanceMethod":case"instanceEmit":case"instanceDataInput":n.push({canvasId:e.target.canvasId,instanceId:e.target.instanceId});break;default:q(e.target)}return n}function j(e,n,t){for(const o of F(e))if(o.instanceId===n&&o.canvasId===t)return!0;return!1}function V(e){throw new Error(`[hc-canvas/bindingRefs] Unhandled BindingSource.kind: ${e.kind}`)}function q(e){throw new Error(`[hc-canvas/bindingRefs] Unhandled BindingTarget.kind: ${e.kind}`)}function _(e){const n={type:e.type,canvas:{...e.canvas,width:{...e.canvas.width},height:{...e.canvas.height}}};return e.background&&(n.background={...e.background,...e.background.image?{image:{...e.background.image}}:{}}),e.behavior&&(n.behavior={...e.behavior}),e.guides&&(n.guides={...e.guides,...e.guides.items?{items:[...e.guides.items]}:{}}),e.rootLayout&&(n.rootLayout="grid"===(t=e.rootLayout).mode?{...t,columns:t.columns?t.columns.map(e=>({...e})):[],rows:t.rows?t.rows.map(e=>({...e})):[],...t.cells?{cells:{...t.cells}}:{},..."object"==typeof t.gap&&null!==t.gap?{gap:{...t.gap}}:{}}:"split"===t.mode?{...t,ratios:Array.isArray(t.ratios)?[...t.ratios]:[]}:{...t}),n;var t}function K(e={}){return JSON.parse(JSON.stringify(e))}function J(n={schemaVersion:"1",layout:{type:"free",canvas:{width:{mode:"fill"},height:{mode:"fill"}}},instances:[],bindings:[]}){const o=d(c(n)),a=e.reactive({schemaVersion:"1",layout:_(o.layout),instances:o.instances.map(e=>({...e,rect:{...e.rect}})),bindings:o.bindings.map(e=>t(e)),componentOverrides:K(o.componentOverrides)});function r(e){return a.instances.findIndex(n=>n.instanceId===e)}function s(e){return a.bindings.findIndex(n=>n.id===e)}return{get document(){return a},instanceCount:e.computed(()=>a.instances.length),bindingCount:e.computed(()=>a.bindings.length),addInstance(e){if(r(e.instanceId)>=0)return void console.warn(`[hc-canvas/doc-store] instanceId "${e.instanceId}" 已存在,addInstance 忽略`);const n=e.rect?{...e.rect}:function(e){if(!e)return{x:0,y:0,w:0,h:0};const n=(e,n)=>"number"==typeof e&&Number.isFinite(e)?e:n;return{x:n(e.x,0),y:n(e.y,0),w:n(e.width,0),h:n(e.height,0)}}(e.layoutBox),t={...e,rect:n};!0===t.locked&&(void 0===t.lockPosition&&(t.lockPosition=!0),void 0===t.lockSize&&(t.lockSize=!0)),a.instances.push(t)},removeInstance(e){var n;const t=r(e);t<0||(a.instances.splice(t,1),null==(n=a.componentOverrides)||delete n[e],a.bindings=a.bindings.filter(n=>!j(n,e)))},updateInstance(e,n){const t=a.instances.find(n=>n.instanceId===e);if(t&&(Object.assign(t,n),n.rect&&t.layoutBox&&(t.layoutBox={...t.layoutBox,x:t.rect.x,y:t.rect.y,..."px"===t.layoutBox.widthMode?{width:t.rect.w}:{},..."px"===t.layoutBox.heightMode?{height:t.rect.h}:{}}),n.layoutBox)){const e=t.layoutBox??n.layoutBox,o=e=>"number"==typeof e&&Number.isFinite(e);t.rect={x:o(e.x)?e.x:t.rect.x,y:o(e.y)?e.y:t.rect.y,w:"px"===e.widthMode&&o(e.width)?e.width:t.rect.w,h:"px"===e.heightMode&&o(e.height)?e.height:t.rect.h}}},moveInstance(e,n,t){const o=a.instances.find(n=>n.instanceId===e);o&&(o.rect.x=n,o.rect.y=t,o.layoutBox&&(o.layoutBox={...o.layoutBox,x:n,y:t}))},resizeInstance(e,n,t){const o=a.instances.find(n=>n.instanceId===e);if(!o)return;const i=Math.max(1,n),r=Math.max(1,t);o.rect.w=i,o.rect.h=r,o.layoutBox&&(o.layoutBox={...o.layoutBox,width:i,height:r,widthMode:"px",heightMode:"px"})},setInstanceProp(e,n,t){const o=a.instances.find(n=>n.instanceId===e);o&&(o.props={...o.props,[n]:t})},setInstanceLocked(e,n){const t=a.instances.find(n=>n.instanceId===e);t&&(t.locked=n,n?(t.lockPosition=!0,t.lockSize=!0):(delete t.lockPosition,delete t.lockSize))},setInstanceSize(e,n){const t=a.instances.find(n=>n.instanceId===e);if(t)if(null===n)delete t.size,t.layoutBox&&(t.layoutBox={...t.layoutBox,width:t.rect.w,height:t.rect.h,widthMode:"px",heightMode:"px"});else if(t.size=n,t.layoutBox){const e=n.width,o=n.height,i={...t.layoutBox};e&&("px"===e.mode?(i.widthMode="px","number"==typeof e.value&&Number.isFinite(e.value)&&(i.width=e.value)):"percent"===e.mode?(i.widthMode="percent","number"==typeof e.value&&Number.isFinite(e.value)&&(i.width=e.value)):"fill"===e.mode?(i.widthMode="fill",Number.isFinite(i.width)||(i.width=t.rect.w)):"auto"!==e.mode&&"hug"!==e.mode||(i.widthMode="auto",Number.isFinite(i.width)||(i.width=t.rect.w))),o&&("px"===o.mode?(i.heightMode="px","number"==typeof o.value&&Number.isFinite(o.value)&&(i.height=o.value)):"percent"===o.mode?(i.heightMode="percent","number"==typeof o.value&&Number.isFinite(o.value)&&(i.height=o.value)):"fill"===o.mode?(i.heightMode="fill",Number.isFinite(i.height)||(i.height=t.rect.h)):"auto"!==o.mode&&"hug"!==o.mode||(i.heightMode="auto",Number.isFinite(i.height)||(i.height=t.rect.h))),t.layoutBox=i}},setInstanceContainerLayout(e,n){const t=a.instances.find(n=>n.instanceId===e);t&&(null===n?delete t.containerLayout:t.containerLayout=n)},updateInstanceLayoutBox(e,n){const t=a.instances.find(n=>n.instanceId===e);if(!t)return;const o=t.layoutBox??{x:t.rect.x,y:t.rect.y,width:t.rect.w,height:t.rect.h,widthMode:"px",heightMode:"px",overflow:"hidden"},i={},r=["x","y","width","height"];for(const e of r){const t=n[e];"number"==typeof t&&Number.isFinite(t)&&(i[e]=t)}if("px"!==n.widthMode&&"percent"!==n.widthMode&&"fill"!==n.widthMode&&"auto"!==n.widthMode||(i.widthMode=n.widthMode),"px"!==n.heightMode&&"percent"!==n.heightMode&&"fill"!==n.heightMode&&"auto"!==n.heightMode||(i.heightMode=n.heightMode),"hidden"!==n.overflow&&"visible"!==n.overflow&&"auto"!==n.overflow||(i.overflow=n.overflow),0===Object.keys(i).length)return;const c={...o,...i};t.layoutBox=c;const s=i.widthMode??o.widthMode,d=i.heightMode??o.heightMode;t.rect={x:c.x,y:c.y,w:"px"===s?c.width:t.rect.w,h:"px"===d?c.height:t.rect.h}},updateInstanceLayoutItem(e,n){const t=a.instances.find(n=>n.instanceId===e);if(!t)return;if(null===n)return void delete t.layoutItem;const o=["order","grow","shrink","row","column","rowSpan","columnSpan","ratio"],i={};for(const e of o){const t=n[e];"number"==typeof t&&Number.isFinite(t)&&(i[e]=t)}if(0===Object.keys(i).length)return;const r=t.layoutItem??{};t.layoutItem={...r,...i}},setInstanceRotation(e,n){const t=a.instances.find(n=>n.instanceId===e);t&&Number.isFinite(n)&&(0===n?delete t.rotation:t.rotation=n)},duplicateInstance(e,n,t){var o;const i=a.instances.find(n=>n.instanceId===e);if(!i)return;const r=JSON.parse(JSON.stringify(i));if(r.instanceId=n,r.rect={...r.rect,x:i.rect.x+t.x,y:i.rect.y+t.y},r.layoutBox&&(r.layoutBox={...r.layoutBox,x:r.layoutBox.x+t.x,y:r.layoutBox.y+t.y}),delete r.locked,delete r.lockPosition,delete r.lockSize,a.instances.some(e=>e.instanceId===n))return void console.warn(`[hc-canvas/doc-store] duplicateInstance: newInstanceId "${n}" 已存在,忽略`);a.instances.push(r);const c=null==(o=a.componentOverrides)?void 0:o[e];c&&(a.componentOverrides={...a.componentOverrides??{},[n]:{...JSON.parse(JSON.stringify(c)),instanceId:n}})},addBinding(e){if(s(e.id)>=0)return void console.warn(`[hc-canvas/doc-store] binding id "${e.id}" 已存在,addBinding 忽略`);const[n]=i([e]);n?a.bindings.push(t(n)):console.warn(`[hc-canvas/doc-store] addBinding "${null==e?void 0:e.id}" dropped by normalize`)},removeBinding(e){const n=s(e);n<0||a.bindings.splice(n,1)},updateBinding(e,n){const o=a.bindings.find(n=>n.id===e);if(!o)return;const i=t(n);Object.assign(o,i)},updateLayout(e){for(const n of Object.keys(e)){const t=e[n];void 0===t?delete a.layout[n]:a.layout[n]=t}},setComponentOverride(e,n){null!==n?(a.componentOverrides||(a.componentOverrides={}),a.componentOverrides[e]=n):a.componentOverrides&&e in a.componentOverrides&&delete a.componentOverrides[e]},replaceDocument(e){const n=d(c(e));a.schemaVersion="1",a.layout=_(n.layout),a.instances=n.instances.map(e=>({...e,rect:{...e.rect}})),a.bindings=n.bindings.map(e=>t(e)),a.componentOverrides=K(n.componentOverrides)},getInstance:e=>a.instances.find(n=>n.instanceId===e),listInstancesByComponentVersionKey:e=>a.instances.filter(n=>n.componentVersionKey===e)}}function U(){const n=e.reactive({ids:[]});return{selectedIds:e.computed(()=>n.ids),size:e.computed(()=>n.ids.length),primaryId:e.computed(()=>n.ids[0]),select(e){n.ids=[e]},toggleSelect(e){const t=n.ids.indexOf(e);t>=0?n.ids.splice(t,1):n.ids.push(e)},addToSelection(e){n.ids.includes(e)||n.ids.push(e)},removeFromSelection(e){const t=n.ids.indexOf(e);t>=0&&n.ids.splice(t,1)},clearSelection(){n.ids=[]},selectAll(e){n.ids=Array.from(new Set(e))},purgeOrphans(e){const t=new Set(e);n.ids=n.ids.filter(e=>t.has(e))},isSelected:e=>n.ids.includes(e)}}function X(n={}){const{minScale:t=.25,maxScale:o=4,initialScale:i=1}=n,a=e.reactive({scale:i,panX:0,panY:0});function r(e){return Math.max(t,Math.min(o,e))}return{state:a,scale:e.computed(()=>a.scale),panX:e.computed(()=>a.panX),panY:e.computed(()=>a.panY),setScale(e){a.scale=r(e)},zoomAt(e,n){const t=a.scale,o=r(t+n);if(o===t)return;const i=o/t;a.panX=e.x-(e.x-a.panX)*i,a.panY=e.y-(e.y-a.panY)*i,a.scale=o},setPan(e,n){a.panX=e,a.panY=n},panBy(e,n){a.panX+=e,a.panY+=n},resetView(){a.scale=i,a.panX=0,a.panY=0},fitToScreen(e,n,t=40){const o=Math.max(1,n.w-2*t),i=Math.max(1,n.h-2*t),c=o/e.w,s=i/e.h,d=r(Math.min(c,s)),l=e.w*d,u=e.h*d;a.scale=d,a.panX=(n.w-l)/2,a.panY=(n.h-u)/2},toCanvasPoint:e=>({x:(e.x-a.panX)/a.scale,y:(e.y-a.panY)/a.scale}),toViewportPoint:e=>({x:e.x*a.scale+a.panX,y:e.y*a.scale+a.panY})}}function Y(e){const n=new Map;return{resolve(t){const o=function(e){return e.id||e.url||""}(t);if(o&&n.has(o))return n.get(o);if(!e){const e=t.url??"";return o&&n.set(o,e),e}const i=e.resolve(t);return"string"==typeof i?(o&&n.set(o,i),i):(o&&n.set(o,i),i.then(e=>{o&&n.set(o,e)},e=>{console.warn(`[hc-canvas/assets] resolve("${o}") 失败,缓存里删条目允许重试:`,e),o&&n.delete(o)}),i)},__clearCache(){n.clear()}}}function H(e,n,t){if(!n||0===Object.keys(n).length)return`${e}::{}`;const o=G(n,t);return null===o?`${e}::__fresh_${Date.now()}_${Math.random().toString(36).slice(2,8)}__`:`${e}::${o}`}function G(e,n,t=new WeakSet){if(null==e)return JSON.stringify(e);const o=typeof e;if("string"===o||"number"===o||"boolean"===o)return JSON.stringify(e);if("function"===o||"symbol"===o||"bigint"===o)return null==n||n(),null;if(Array.isArray(e)){if(t.has(e))return null==n||n(),null;t.add(e);const o=[];for(const i of e){const e=G(i,n,t);if(null===e)return null;o.push(e)}return`[${o.join(",")}]`}if("object"===o){const o=Object.getPrototypeOf(e);if(o!==Object.prototype&&null!==o)return null==n||n(),null;const i=e;if(t.has(i))return null==n||n(),null;t.add(i);const a=Object.keys(i).sort(),r=[];for(const e of a){const o=G(i[e],n,t);if(null===o)return null;r.push(`${JSON.stringify(e)}:${o}`)}return`{${r.join(",")}}`}return null==n||n(),null}function W(e){const n=new Map,t=new Map,o=new Map,i=new Map,a=new Map,r=new Map;let c=!1,s=!1,d=0,l=null;function u(e){if(!s&&null!==l)try{l(e)}catch(e){console.error("[hc-canvas/dataStore] trace bridge listener threw",e)}}function p(e,n){var t;const a=o.get(e);if(a)for(const e of a)null==(t=i.get(e))||t.onUpdate(n)}function f(e,t){let o=n.get(e);return o||(o={cacheKey:e,sourceId:t,status:"idle"},n.set(e,o)),o}function h(t,r,c){if(!e)return;const l=a.get(t);l&&l.abort();const h=new AbortController;a.set(t,h);const g=f(t,r);g.status="loading";const m=g.writeSeq??0;Promise.resolve().then(()=>async function(e,n){return{value:await Promise.resolve(e.query(n))}}(e,{sourceId:r,params:c,signal:h.signal})).then(e=>{if(s)return;if(a.get(t)!==h)return;a.delete(t);const o=n.get(t);o&&((o.writeSeq??0)>m?u({kind:"data-query-skipped",cacheKey:t,sourceId:r,writeSeq:o.writeSeq,reason:"race-stale"}):(o.status="success",o.value=e.value,o.error=void 0,o.lastFetchedAt=Date.now(),o.writeSeq=++d,u({kind:"data-source-update",cacheKey:t,sourceId:r,writeSeq:o.writeSeq,value:e.value}),p(t,e.value)))}).catch(e=>{if(s)return;if(function(e){return null!==e&&"object"==typeof e&&"AbortError"===e.name}(e))return;if(a.get(t)!==h)return;a.delete(t);const c=n.get(t);c&&((c.writeSeq??0)>m?u({kind:"data-query-skipped",cacheKey:t,sourceId:r,writeSeq:c.writeSeq,reason:"race-stale-reject"}):(c.status="error",c.error=e,c.lastFetchedAt=Date.now(),function(e,n){var t,a;const r=o.get(e);if(r)for(const e of r)null==(a=null==(t=i.get(e))?void 0:t.onError)||a.call(t,n)}(t,e)))})}function g(e){if(s)return;const{bindingId:d,sourceId:l,params:u,onUpdate:p,onError:f}=e,g=H(l,u,()=>{c||(console.warn(`[hc-canvas/dataStore] params for "${l}" contains non-plain values; fresh query every call (no cache)`),c=!0)});!function(e,i){const c=t.get(e);if(c===i)return;if(c){const t=o.get(c);if(t&&(t.delete(e),0===t.size)){o.delete(c);const e=a.get(c);e&&(e.abort(),a.delete(c)),n.delete(c)}const i=r.get(e);if(i){try{i()}catch{}r.delete(e)}}t.set(e,i);let s=o.get(i);s||(s=new Set,o.set(i,s)),s.add(e)}(d,g),i.set(d,{onUpdate:p,onError:f});const m=n.get(g);if(m){if("success"===m.status)return void p(m.value);if("error"===m.status)return void(null==f||f(m.error));if("loading"===m.status)return}h(g,l,u)}return{request:g,subscribe:function(n){if(s)return;const{bindingId:o,sourceId:i,params:a,onUpdate:c,onError:l}=n;if(g({bindingId:o,sourceId:i,params:a,onUpdate:c,onError:l}),!e)return;const h=t.get(o);if(!h)return;let m=!0;try{const n=function(e,n){if(e.subscribe)return e.subscribe(n,e=>{if(s)return;if(!m)return;if(t.get(o)!==h)return;const n=f(h,i);n.status="success",n.value=e,n.lastFetchedAt=Date.now(),n.writeSeq=++d,u({kind:"data-source-update",cacheKey:h,sourceId:i,writeSeq:n.writeSeq,value:e}),p(h,e)})}(e,{sourceId:i,params:a});n?r.set(o,()=>{m=!1;try{n()}catch{}}):r.set(o,()=>{m=!1})}catch(e){m=!1,s||null==l||l(e)}},removeBinding:function(e,c){if(s)return;const d=!0===(null==c?void 0:c.preserveCache),l=r.get(e);if(l){try{l()}catch{}r.delete(e)}i.delete(e);const u=function(e){const n=t.get(e);if(!n)return;t.delete(e);const i=o.get(n);return i&&(i.delete(e),0===i.size&&o.delete(n)),n}(e);if(u&&!o.has(u)){const e=n.get(u);if(!d||"success"!==(null==e?void 0:e.status)){const e=a.get(u);e&&(e.abort(),a.delete(u)),n.delete(u)}}},invalidate:function(e){if(s)return;const t=[];for(const[o,i]of n)void 0!==e&&i.sourceId!==e||t.push(o);for(const e of t){const t=n.get(e);if(!t)continue;const i=o.get(e);if(!i||0===i.size){n.delete(e);const t=a.get(e);t&&(t.abort(),a.delete(e));continue}t.status="stale",h(e,t.sourceId,void 0)}},getSnapshot:function(){return{entries:Array.from(n.values()).map(e=>({cacheKey:e.cacheKey,sourceId:e.sourceId,status:e.status,value:e.value,error:e.error,lastFetchedAt:e.lastFetchedAt}))}},disposeAll:function(){if(!s){s=!0;for(const e of a.values())try{e.abort()}catch{}a.clear();for(const e of r.values())try{e()}catch{}r.clear(),n.clear(),t.clear(),o.clear(),i.clear(),l=null}},attachTraceBridge:function(e){return s?()=>{}:(l=e,()=>{l===e&&(l=null)})},getBindingsForCacheKey:function(e){const n=o.get(e);return n?Array.from(n):[]},get isDisposed(){return s}}}const Q=Symbol("hc:canvas:context");function Z(n={}){var t,o;const i=J(n.initialDocument),a=U(),r=X(n.viewport),c=N(n.scheduler),s=W(null==(t=n.adapters)?void 0:t.data);let d=!1;const l=[];n.hooks&&l.push(n.hooks);const u=e.ref(!1),p=e.computed(()=>u.value),f=e.ref({}),g=e.computed(()=>f.value),m=e.computed(()=>{var e;const t=(null==(e=n.getMode)?void 0:e.call(n))??"design",o=function(e){switch(e){case"design":return{selectable:!0,draggable:!0,resizable:!0,keyboardMove:!0,snap:!0,grid:!1,allowOverflow:!0,locked:!1};case"preview":case"runtime":return{selectable:!1,draggable:!1,resizable:!1,keyboardMove:!1,snap:!0,grid:!1,allowOverflow:!0,locked:!1};case"inspect":return{selectable:!0,draggable:!1,resizable:!1,keyboardMove:!1,snap:!0,grid:!1,allowOverflow:!0,locked:!1}}}(t),a=i.document.layout.behavior??{};if("design"!==t){const{selectable:e,draggable:n,resizable:t,keyboardMove:i,...r}=a;return{...o,...r,...f.value}}return{...o,...a,...f.value}}),y=Y(null==(o=n.adapters)?void 0:o.assets),I=e.ref("select"),w=e.ref(null),b=e.computed(()=>w.value??I.value),k=e.ref(null),S=e.computed(()=>k.value),B=e.ref(null),M=e.ref({w:0,h:0}),T=e.computed(()=>M.value),C=e.computed(()=>{const e=i.document.layout,n=M.value;return{w:x(e.canvas.width,n.w,1920),h:x(e.canvas.height,n.h,1080)}}),z=e.ref([]),L=e.computed(()=>z.value),E=e.ref(0),P=e.computed(()=>E.value>0);return{document:i,selection:a,viewport:r,scheduler:c,adapters:n.adapters??{},dataStore:s,dispatch:function(e){var n,t;if(d)console.warn("[hc-canvas/context] dispatch called after dispose()");else{for(const t of l)if(!1===(null==(n=t.onBeforeAction)?void 0:n.call(t,e)))return;switch(e.type){case"addInstance":i.addInstance(e.payload.instance);break;case"removeInstance":i.removeInstance(e.payload.instanceId),a.removeFromSelection(e.payload.instanceId);break;case"updateInstance":i.updateInstance(e.payload.instanceId,e.payload.patch);break;case"moveInstance":i.moveInstance(e.payload.instanceId,e.payload.x,e.payload.y);break;case"resizeInstance":i.resizeInstance(e.payload.instanceId,e.payload.w,e.payload.h);break;case"setInstanceProp":i.setInstanceProp(e.payload.instanceId,e.payload.key,e.payload.value);break;case"addBinding":i.addBinding(e.payload.binding);break;case"removeBinding":i.removeBinding(e.payload.bindingId);break;case"updateBinding":i.updateBinding(e.payload.bindingId,e.payload.patch);break;case"updateLayout":i.updateLayout(e.payload.patch);break;case"setRootLayout":{const{rootLayout:n}=e.payload;i.updateLayout({rootLayout:null===n?void 0:n});break}case"replaceDocument":i.replaceDocument(e.payload.document),a.purgeOrphans(i.document.instances.map(e=>e.instanceId));break;case"setComponentOverride":{const{instanceId:n,override:t}=e.payload;if(void 0===i.getInstance(n)){console.warn(`[hc-canvas/context] setComponentOverride: instance "${n}" 不存在,no-op`);break}i.setComponentOverride(n,t);break}case"setInstanceLocked":i.setInstanceLocked(e.payload.instanceId,e.payload.locked);break;case"duplicateInstance":i.duplicateInstance(e.payload.instanceId,e.payload.newInstanceId,e.payload.offset??{x:20,y:20});break;case"setInstanceSize":{const{instanceId:n,size:t}=e.payload;if(null===t)i.setInstanceSize(n,null);else{const e=h(void 0,t);i.setInstanceSize(n,e??null)}break}case"setContainerLayout":{const{instanceId:n,containerLayout:t}=e.payload;if(null===t)i.setInstanceContainerLayout(n,null);else{const e=v(t);null!==e&&i.setInstanceContainerLayout(n,e)}break}case"updateLayoutBox":i.updateInstanceLayoutBox(e.payload.instanceId,e.payload.patch);break;case"updateLayoutItem":i.updateInstanceLayoutItem(e.payload.instanceId,e.payload.patch);break;case"updateRotation":i.setInstanceRotation(e.payload.instanceId,e.payload.value);break;case"select":a.select(e.payload.instanceId);break;case"toggleSelect":a.toggleSelect(e.payload.instanceId);break;case"addToSelection":a.addToSelection(e.payload.instanceId);break;case"removeFromSelection":a.removeFromSelection(e.payload.instanceId);break;case"clearSelection":a.clearSelection();break;case"selectAll":a.selectAll(e.payload.instanceIds);break;default:{const n=e;console.warn("[hc-canvas/context] unknown action",n)}}for(const n of l)null==(t=n.onAfterAction)||t.call(n,e)}},dispose:function(){d||(d=!0,u.value=!1,c.dispose(),s.disposeAll())},isBatching:p,beginBatch:function(){d||u.value||(u.value=!0)},endBatch:function(e){var n;if(!d&&u.value){for(const t of l)null==(n=t.onAfterBatch)||n.call(t,e);u.value=!1}},registerHooks:function(e){return l.push(e),()=>{const n=l.indexOf(e);n>=0&&l.splice(n,1)}},isRecordingSuppressed:P,suppressRecording:function(e){E.value++;try{return e()}finally{E.value--}},effectiveBehavior:m,interactionOptions:g,setInteractionOptions:function(e){const n={...f.value};for(const t of Object.keys(e)){const o=e[t];void 0===o?delete n[t]:n[t]=o}f.value=n},resolveAsset:function(e){return y.resolve(e)},toolMode:b,setToolMode:function(e){I.value=e},setTemporaryToolMode:function(e){w.value=e},mouseCanvasPoint:S,setMouseCanvasPoint:function(e){k.value=e},measuredStageSize:T,measuredCanvasSize:C,setMeasuredStageSize:function(e){const n=Math.max(0,Math.round(e.w)),t=Math.max(0,Math.round(e.h));M.value.w===n&&M.value.h===t||(M.value={w:n,h:t})},layoutIssues:L,setLayoutIssues:function(e){z.value=e},cannotDragLayoutManagedChildEvent:e.readonly(B),setCannotDragLayoutManagedChildEvent:function(e){B.value=e}}}function ee(n){e.provide(Q,n)}function ne(){const n=e.inject(Q);if(!n)throw new Error("[hc-canvas] useCanvasContext() called outside <CanvasProvider> / <HyperCardCanvasDesigner>. Make sure the component tree is wrapped by a provider.");return n}const te="default";function oe(e){return e.slot??te}function ie(e,n){const t=[],o=n.resolveContract,i=n.maxDepth??8,a=new Map;for(const n of e.instances)a.set(n.instanceId,n);for(const n of e.instances){if(void 0===n.parentId&&void 0!==n.slot&&n.slot!==te){ae(t,"orphan-slot",n.instanceId,`slot "${n.slot}" 没有 parentId,数据不完整`);continue}if(void 0===n.parentId)continue;if(!a.has(n.parentId)){ae(t,"missing-parent",n.instanceId,`parentId "${n.parentId}" 指向不存在的实例`);continue}"absolute"!==n.placement&&"canvas"!==n.placement||ae(t,"absolute-child-rejected",n.instanceId,"parentId + placement='absolute'|'canvas' 在 D4.5f MVP 不支持,只允许 root absolute/canvas 或 child slot/container");const e=a.get(n.parentId),i=o(e.componentVersionKey);if(!i)continue;const r=i.slotsDecl??[];if(0===r.length){ae(t,"parent-not-layout",n.instanceId,`父组件 "${e.componentId}" 不是布局组件(slotsDecl 为空)`);continue}const c=oe(n),s=re(r,c);s?s.accepts&&s.accepts.length>0&&(s.accepts.includes(n.componentId)||ae(t,"slot-not-allowed-component",n.instanceId,`slot "${c}" 不允许 componentId "${n.componentId}"(accepts: ${s.accepts.join(", ")})`)):ae(t,"invalid-slot",n.instanceId,`slot "${c}" 不在父 "${e.componentId}" 的 slotsDecl 中(可能组件升级删除了该 slot)`)}const r=new Map;for(const n of e.instances){if(void 0===n.parentId)continue;const e=oe(n),t=`${n.parentId}::${e}`;let o=r.get(t);o||(o=[],r.set(t,o)),o.push(n)}for(const[e,n]of r){if(n.length<=1)continue;const[i,r]=ce(e),c=a.get(i);if(!c)continue;const s=o(c.componentVersionKey);if(!s)continue;const d=re(s.slotsDecl??[],r);if(d&&!0!==d.multiple)for(let e=1;e<n.length;e++)ae(t,"slot-multiple-violated",n[e].instanceId,`slot "${r}" 不允许多个子实例(SlotDecl.multiple !== true)`)}const c=new Map;for(const n of e.instances)c.set(n.instanceId,0);for(const n of e.instances)0===c.get(n.instanceId)&&s(n.instanceId,[],0);function s(e,n,o){c.set(e,1);const r=a.get(e);if(o>i)return ae(t,"depth-exceeded",e,`嵌套深度 ${o} 超过上限 ${i}`),void c.set(e,2);const d=r.parentId;if(void 0===d)return void c.set(e,2);if(!a.has(d))return void c.set(e,2);const l=c.get(d);if(1===l)return ae(t,"cycle",e,`parentId 链成环:${[...n,e,d].join(" → ")}`),void c.set(e,2);2!==l?(s(d,[...n,e],o+1),c.set(e,2)):c.set(e,2)}return t}function ae(e,n,t,o){e.push({kind:n,instanceId:t,detail:o})}function re(e,n){return e.find(e=>e.name===n)}function ce(e){const n=e.indexOf("::");return[e.slice(0,n),e.slice(n+2)]}function se(e,n,t){const o=(null==e?void 0:e.onError)??"log";switch(o){case"stop":return"stop";case"log":return console.error(`[hc-canvas/wirePageBindings] binding "${t}" threw:`,n),"continue";case"continue":return"continue";default:return console.error(`[hc-canvas/wirePageBindings] binding "${t}" threw (unknown onError="${String(o)}"):`,n),"continue"}}function de(e,n){return e&&"passthrough"!==e.kind?"static"===e.kind?function(e){if("function"==typeof structuredClone)try{return structuredClone(e)}catch{}try{return JSON.parse(JSON.stringify(e))}catch{return[...e]}}(e.args):"pickPath"===e.kind?function(e,n){const t=[];let o;for(const i of e){const e=le(n,i.from);void 0===i.to?t.push(e):"number"==typeof i.to?(ue(t,i.to+1),t[i.to]=e):(o||(t.length>0&&"object"==typeof t[0]&&null!==t[0]&&!Array.isArray(t[0])?o=t[0]:(o={},0===t.length?t.push(o):t[0]=o)),o[i.to]=e)}return t}(e.paths,n):[n]:[n]}function le(e,n){if(""===n)return e;const t=n.split(".");let o=e;for(const e of t){if(null==o)return;if("object"!=typeof o)return;o=o[e]}return o}function ue(e,n){for(;e.length<n;)e.push(void 0)}function pe(e,n,t,o){e.debouncePendingTimer=null;const i=e.debounceDirty,a=e.debouncePendingChainId,r=e.debouncePendingPayload;e.debouncePendingChainId=null,e.debouncePendingPayload=void 0,e.debounceDirty=!1,t&&i&&null!==a&&he(n,e).pass&&o(r,a)}function fe(e,n,t){e.throttleTrailingTimer=null;const o=e.throttleTrailingPendingChainId,i=e.throttleTrailingPendingPayload;e.throttleTrailingPendingChainId=null,e.throttleTrailingPendingPayload=void 0,e.throttleWindowStartTs=null,null!==o&&(n.once&&e.onceConsumed||(n.once&&(e.onceConsumed=!0),e.throttleLastFireTs=ve(),t(i,o)))}function he(e,n){const t=e.throttle;if(t){t.leading;const e=t.windowMs,o=ve(),i=n.throttleLastFireTs;if(null!==i&&o-i<e)return{pass:!1,reason:"throttle-window"};n.throttleLastFireTs=o}if(e.once){if(n.onceConsumed)return{pass:!1,reason:"once-consumed"};n.onceConsumed=!0}return{pass:!0}}function ge(e){return!(!e||!(e.throttle&&!1===e.throttle.leading&&!1===e.throttle.trailing||e.debounce&&!1===e.debounce.leading&&!1===e.debounce.trailing))}let me=()=>Date.now();function ve(){return me()}let ye=0;function Ie(t){var o,i;const a=t.canvasId,{source:r}=t,c=t.dataStore,s=new Set;let d="off",l=0,u=!1;const p="w"+ ++ye;let f=0;function h(){return`${p}-${++f}`}let g=0;function m(e){L.hasListeners("binding:trace")&&L.emit("binding:trace",{canvasId:a,ts:Date.now(),seq:++g,...e})}let v=!1,y=null;function I(){v&&(y&&y(),y=null,v=!1)}const w=new Map,x=new Map,b=new Set,k=new Set,S=new Set,B=new Set,M=new Map;let T=new Set;const C=[],z=[],L=function(e){const n=new Set,t=new Set,o=new Set;return{on(i,a){var r;if("binding:fire"===i){const e=a;return n.add(e),()=>n.delete(e)}if("binding:error"===i){const e=a;return t.add(e),()=>t.delete(e)}const c=a;return o.add(c),null==(r=null==e?void 0:e.onTraceListenerCountChange)||r.call(e,o.size),()=>{var n;o.delete(c),null==(n=null==e?void 0:e.onTraceListenerCountChange)||n.call(e,o.size)}},emit(e,i){if("binding:fire"===e)for(const e of n)try{e(i)}catch(e){console.error("[hc-canvas/wirePageBindings] listener threw",e)}else if("binding:error"===e)for(const e of t)try{e(i)}catch(e){console.error("[hc-canvas/wirePageBindings] listener threw",e)}else for(const e of o)try{e(i)}catch(e){console.error("[hc-canvas/wirePageBindings] trace listener threw",e)}},hasListeners:e=>"binding:fire"===e?n.size>0:"binding:error"===e?t.size>0:o.size>0,clear(){n.clear(),t.clear(),o.clear()}}}({onTraceListenerCountChange:function(e){e>0?!v&&c&&(y=c.attachTraceBridge(e=>{if(u)return;const n=c.getBindingsForCacheKey(e.cacheKey);for(const t of n)m({kind:e.kind,bindingId:t,cacheKey:e.cacheKey,sourceId:e.sourceId,writeSeq:e.writeSeq,reason:e.reason,payload:e.value})}),v=!0):I()}}),E=function(e){let n=[],t=200,o=null,i=null;return{start:function(a){i&&(i(),i=null,n=[]),t=(null==a?void 0:a.capacity)??200,o=(null==a?void 0:a.filterKinds)&&a.filterKinds.length>0?new Set(a.filterKinds):null,i=e.on("binding:trace",e=>{o&&!o.has(e.kind)||(n.push(e),n.length>t&&n.shift())})},stop:function(){i&&(i(),i=null);const e=n.slice();return n=[],e},snapshot:function(){return n.slice()},get isRunning(){return null!==i}}}({on:(e,n)=>L.on(e,n)});function P(e){return void 0===e.canvasId||e.canvasId===a}function D(e){for(const n of F(e))if(void 0!==n.canvasId&&n.canvasId!==a)return!0;return!1}function R(e){return JSON.stringify({id:e.id,type:e.type,disabled:e.disabled??!1,source:e.source,target:e.target,mapping:e.mapping??null,schedule:e.schedule??null,errorPolicy:e.errorPolicy??null})}function O(e,n){return void 0===n||R(e)!==n}function $(){var e;return(null==(e=r.getDocument())?void 0:e.bindings)??[]}function A(e){return $().find(n=>n.id===e)}function N(e){try{e()}catch(e){console.error("[hc-canvas/wirePageBindings] cleanup threw",e)}}function j(e,n){L.emit("binding:fire",e),m({kind:"fire",bindingId:e.bindingId,chainId:n,payload:e.payload,args:e.args})}function V(e,n){L.emit("binding:error",e),m({kind:(null==n?void 0:n.traceKind)??"error",bindingId:e.bindingId,chainId:null==n?void 0:n.chainId,code:e.code,message:e.message,detail:e.detail})}function q(e,n=!1){const t=w.get(e);if(t)for(const e of t)N(e);w.delete(e);const o=x.get(e);if(o){const n=function(e){const n={};return null!==e.debouncePendingTimer&&(clearTimeout(e.debouncePendingTimer),e.debouncePendingTimer=null,null!==e.debouncePendingChainId&&(n.droppedDebounce={chainId:e.debouncePendingChainId,payload:e.debouncePendingPayload})),null!==e.debouncePendingTimer||null===e.debouncePendingChainId||n.droppedDebounce||(n.droppedDebounce={chainId:e.debouncePendingChainId,payload:e.debouncePendingPayload}),e.debouncePendingChainId=null,e.debouncePendingPayload=void 0,e.debounceDirty=!1,null!==e.throttleTrailingTimer&&(clearTimeout(e.throttleTrailingTimer),e.throttleTrailingTimer=null),null!==e.throttleTrailingPendingChainId&&(n.droppedThrottleTrailing={chainId:e.throttleTrailingPendingChainId,payload:e.throttleTrailingPendingPayload}),e.throttleTrailingPendingChainId=null,e.throttleTrailingPendingPayload=void 0,e.throttleWindowStartTs=null,n}(o);n.droppedDebounce&&m({kind:"scheduled-dropped",bindingId:e,chainId:n.droppedDebounce.chainId,payload:n.droppedDebounce.payload}),n.droppedThrottleTrailing&&m({kind:"scheduled-dropped",bindingId:e,chainId:n.droppedThrottleTrailing.chainId,payload:n.droppedThrottleTrailing.payload}),x.delete(e)}k.delete(e),M.delete(e),S.delete(e),B.delete(e),s.delete(e),c&&c.removeBinding(e,{preserveCache:n})}function _(e=!1){for(const n of[...w.keys()])q(n,e)}function K(e){if(u)return;if(w.has(e.id))return;if(D(e))return void(S.has(e.id)||(V({bindingId:e.id,code:"unsupported-cross-canvas"}),S.add(e.id),m({kind:"wire-skipped",bindingId:e.id,reason:"unsupported-cross-canvas"})));const t=function(e){return e.disabled?"disabled":b.has(e.id)?"stopped":null}(e);if(t)return void m({kind:"wire-skipped",bindingId:e.id,reason:t});if("data-preview"===d&&"dataSource"!==e.source.kind)return void m({kind:"wire-skipped",bindingId:e.id,reason:"mode-matrix-data-preview"});ge(e.schedule)&&!B.has(e.id)&&(console.warn(`[hc-canvas/wirePageBindings] schedule.{throttle|debounce}.{leading=false,trailing=false} 永远不会 fire (binding "${e.id}")`),B.add(e.id));const o=[];switch(e.source.kind){case"instanceEvent":{const t=n.getInstance(e.source.instanceId,a);if(!t)return void k.add(e.id);const i=e.source.event,r=t.on(i,n=>U(e,n));o.push(r);break}case"lifecycle":case"page":break;case"dataSource":{if(!c)return void(s.has(e.id)||(V({bindingId:e.id,code:"no-data-adapter"}),m({kind:"wire-skipped",bindingId:e.id,reason:"no-data-adapter"}),s.add(e.id)));const n=e.source,t="change"===n.watch,o=n=>U(e,n),i=n=>{V({bindingId:e.id,code:"data-query-failed",message:n instanceof Error?n.message:String(n),detail:n}),"stop"===se(e.errorPolicy,n,e.id)&&b.add(e.id)};m({kind:"data-query-started",bindingId:e.id,sourceId:n.sourceId}),t?c.subscribe({bindingId:e.id,sourceId:n.sourceId,onUpdate:o,onError:i}):c.request({bindingId:e.id,sourceId:n.sourceId,onUpdate:o,onError:i});break}default:return}w.set(e.id,o),M.set(e.id,R(e))}function J(){for(const e of $())K(e)}function U(e,n){if(u)return;if("off"===d)return;if(b.has(e.id))return void m({kind:"stopped-skipped",bindingId:e.id});if(D(e))return;if(l>=8){const n=h();return void V({bindingId:e.id,code:"cycle-detected"},{chainId:n,traceKind:"cycle-detected"})}const t=h(),o=function(e,n,t,o){return ge(e)?{fire:!1,deferred:!1,reason:"schedule-no-fire"}:(null==e?void 0:e.debounce)?function(e,n,t,o){const i=e.debounce,a=i.leading??!1,r=i.trailing??!0,c=i.windowMs;if(null===n.debouncePendingTimer){if(a){const t=he(e,n);return t.pass?(n.debounceLeadingFireTs=ve(),n.debounceDirty=!1,n.debouncePendingPayload=void 0,n.debouncePendingChainId=null,{fire:!0,deferred:!1,scheduleDeferred:t=>{n.debouncePendingTimer=setTimeout(()=>{pe(n,e,r,t)},c)}}):{fire:!1,deferred:!1,reason:t.reason}}return n.debouncePendingPayload=t,n.debouncePendingChainId=o,n.debounceDirty=!0,{fire:!1,deferred:!0,scheduleDeferred:t=>{n.debouncePendingTimer=setTimeout(()=>{pe(n,e,r,t)},c)}}}const s=null!==n.debouncePendingChainId?{chainId:n.debouncePendingChainId,payload:n.debouncePendingPayload}:void 0;return n.debounceDirty=!0,r&&(n.debouncePendingPayload=t,n.debouncePendingChainId=o),clearTimeout(n.debouncePendingTimer),n.debouncePendingTimer=null,r?{fire:!1,deferred:!0,droppedByReschedule:s,scheduleDeferred:t=>{n.debouncePendingTimer=setTimeout(()=>{pe(n,e,r,t)},c)}}:{fire:!1,deferred:!1,reason:"debounce-window",scheduleDeferred:t=>{n.debouncePendingTimer=setTimeout(()=>{pe(n,e,r,t)},c)}}}(e,n,t,o):function(e,n,t,o){const i=null==e?void 0:e.throttle;if(!i)return function(e,n){if(null==e?void 0:e.once){if(n.onceConsumed)return{fire:!1,deferred:!1,reason:"once-consumed"};n.onceConsumed=!0}return{fire:!0,deferred:!1}}(e,n);const a=i.leading??!0,r=i.trailing??!1,c=i.windowMs,s=ve();if(a){const i=n.throttleLastFireTs;if(!(null!==i&&s-i<c))return(null==e?void 0:e.once)&&n.onceConsumed?{fire:!1,deferred:!1,reason:"once-consumed"}:((null==e?void 0:e.once)&&(n.onceConsumed=!0),n.throttleLastFireTs=s,{fire:!0,deferred:!1});if(!r)return{fire:!1,deferred:!1,reason:"throttle-window"};const a=null!==n.throttleTrailingPendingChainId?{chainId:n.throttleTrailingPendingChainId,payload:n.throttleTrailingPendingPayload}:void 0;if(n.throttleTrailingPendingPayload=t,n.throttleTrailingPendingChainId=o,null===n.throttleTrailingTimer){const t=c-(s-i);return{fire:!1,deferred:!0,scheduleDeferred:o=>{n.throttleTrailingTimer=setTimeout(()=>{fe(n,e,o)},t)}}}return{fire:!1,deferred:!1,reason:"throttle-window",droppedByReschedule:a}}if(null===n.throttleWindowStartTs)return n.throttleWindowStartTs=s,n.throttleTrailingPendingPayload=t,n.throttleTrailingPendingChainId=o,{fire:!1,deferred:!0,reason:"leading-disabled",scheduleDeferred:t=>{n.throttleTrailingTimer=setTimeout(()=>{fe(n,e,t)},c)}};const d=null!==n.throttleTrailingPendingChainId?{chainId:n.throttleTrailingPendingChainId,payload:n.throttleTrailingPendingPayload}:void 0;return n.throttleTrailingPendingPayload=t,n.throttleTrailingPendingChainId=o,{fire:!1,deferred:!1,reason:"throttle-window",droppedByReschedule:d}}(e,n,t,o)}(e.schedule,function(e){let n=x.get(e);return n||(n={onceConsumed:!1,throttleLastFireTs:null,throttleWindowStartTs:null,throttleTrailingPendingPayload:void 0,throttleTrailingPendingChainId:null,throttleTrailingTimer:null,debouncePendingTimer:null,debouncePendingPayload:void 0,debouncePendingChainId:null,debounceDirty:!1,debounceLeadingFireTs:null},x.set(e,n)),n}(e.id),n,t),i=function(e){if(e)return e.throttle?{kind:"throttle",windowMs:e.throttle.windowMs,leading:e.throttle.leading,trailing:e.throttle.trailing}:e.debounce?{kind:"debounce",windowMs:e.debounce.windowMs,leading:e.debounce.leading,trailing:e.debounce.trailing}:void 0}(e.schedule);o.droppedByReschedule&&m({kind:"scheduled-dropped",bindingId:e.id,chainId:o.droppedByReschedule.chainId,payload:o.droppedByReschedule.payload,schedule:i}),o.scheduleDeferred&&o.scheduleDeferred((n,t)=>{u||(m({kind:"scheduled-flushed",bindingId:e.id,chainId:t,payload:n,schedule:i}),X(e,n,t))}),o.reason?m({kind:"scheduled-skipped",bindingId:e.id,chainId:t,reason:o.reason,payload:n,schedule:i}):!o.deferred||o.fire?o.fire&&X(e,n,t):m({kind:"scheduled-deferred",bindingId:e.id,chainId:t,payload:n,schedule:i})}function X(e,t,o){if(u)return;const i=n.getInstance(e.target.instanceId,a);if(!i)return void V({bindingId:e.id,code:"target-not-mounted"},{chainId:o});let r,c;try{r=de(e.mapping,t)}catch(n){return m({kind:"mapping-failed",bindingId:e.id,chainId:o,message:n instanceof Error?n.message:String(n),detail:n}),void("stop"===se(e.errorPolicy,n,e.id)&&b.add(e.id))}if("instanceDataInput"===e.target.kind){const n=i.vm.custom,a=null==n?void 0:n[e.target.key];if(!a||"object"!=typeof a||!0!==a.dataInput)return void V({bindingId:e.id,code:"unknown-target-data-input",message:n&&e.target.key in n?`target.key "${e.target.key}" on instance "${e.target.instanceId}" is not declared with dataInput:true`:`target.key "${e.target.key}" not declared on instance "${e.target.instanceId}"`},{chainId:o});try{i.setDataInput(e.target.key,r[0])}catch(n){return"stop"===se(e.errorPolicy,n,e.id)&&b.add(e.id),void V({bindingId:e.id,code:"invoke-failed",message:n instanceof Error?n.message:String(n),detail:n},{chainId:o})}return void j({bindingId:e.id,source:e.source,target:e.target,payload:t,args:r},o)}l++;try{c=function(e,n,t){switch(n.kind){case"instanceMethod":return e.call(n.method,...t);case"instanceEmit":return void e.emit(n.event,t[0]);default:return}}(i,e.target,r),j({bindingId:e.id,source:e.source,target:e.target,payload:t,args:r},o)}catch(n){return"stop"===se(e.errorPolicy,n,e.id)&&b.add(e.id),void V({bindingId:e.id,code:"invoke-failed",message:n instanceof Error?n.message:String(n),detail:n},{chainId:o})}finally{l--}var s;"object"==typeof(s=c)&&null!==s&&"function"==typeof s.then&&Promise.resolve(c).catch(n=>{u||("stop"===se(e.errorPolicy,n,e.id)&&b.add(e.id),V({bindingId:e.id,code:"invoke-failed",message:n instanceof Error?n.message:String(n),detail:n},{chainId:o}))})}const Y=null==(o=r.onAction)?void 0:o.call(r,e=>{var n,t,o,i;if(u)return;if("off"===d)return;const a=e;if(a&&"object"==typeof a)switch(a.type){case"addBinding":{const e=null==(t=null==(n=a.payload)?void 0:n.binding)?void 0:t.id;if(!e)return;const o=A(e);o&&K(o);break}case"updateBinding":{const e=null==(o=a.payload)?void 0:o.bindingId;if(!e)return;q(e);const n=A(e);n&&K(n);break}case"removeBinding":{const e=null==(i=a.payload)?void 0:i.bindingId;if(!e)return;q(e),b.delete(e);break}case"replaceDocument":_(),b.clear(),k.clear(),J();break;case"removeInstance":!function(){const e=new Set($().map(e=>e.id));for(const n of[...w.keys()])e.has(n)||(q(n),b.delete(n));for(const e of $())K(e)}()}});Y&&C.push(Y);const H=null==(i=r.onDocumentChange)?void 0:i.call(r,()=>{if(u)return;if("off"===d)return;const e=$(),n=new Set(e.map(e=>e.id)),t=new Set(w.keys());for(const e of t)n.has(e)||q(e);for(const n of e)w.has(n.id)?O(n,M.get(n.id))&&(q(n.id),K(n)):K(n)});function G(){return new Set(n.listInstances({canvasId:a}).map(e=>e.instanceId))}H&&C.push(H),T=G();const W=e.watch(n.registryVersion,()=>{if(u)return;if("off"===d)return;const e=G(),n=we(e,T),t=we(T,e);T=e;for(const n of[...k]){const t=A(n);t?Q(t,e)&&(k.delete(n),K(t)):k.delete(n)}if(t.size>0)for(const e of[...w.keys()]){const n=A(e);n&&F(n).some(e=>P(e)&&t.has(e.instanceId))&&(q(e),k.add(e))}!function(e){if(0!==e.size)for(const n of $())"lifecycle"===n.source.kind&&"mounted"===n.source.hook&&P({canvasId:n.source.canvasId,instanceId:n.source.instanceId})&&e.has(n.source.instanceId)&&U(n,{instanceId:n.source.instanceId,hook:"mounted"})}(n),function(e){if(0!==e.size)for(const n of $())"lifecycle"===n.source.kind&&"unmounted"===n.source.hook&&P({canvasId:n.source.canvasId,instanceId:n.source.instanceId})&&e.has(n.source.instanceId)&&U(n,{instanceId:n.source.instanceId,hook:"unmounted"})}(t)},{flush:"post"});function Q(e,n){for(const t of F(e)){if(!P(t))return!1;if(!n.has(t.instanceId))return!1}return!0}return z.push(W),{setMode:function(e){u||e!==d&&(_(!0),b.clear(),k.clear(),d=e,"off"!==e&&J(),"runtime"===e&&function(){for(const e of $())"page"===e.source.kind&&"pageInit"===e.source.hook&&U(e,{hook:"pageInit"})}())},getMode:()=>d,testBinding(e,t){const o=[],i=A(e);if(!i)return o.push({bindingId:e,phase:"skipped",details:{reason:"binding-not-found"}}),o;if(i.disabled)return o.push({bindingId:e,phase:"skipped",details:{reason:"disabled"}}),o;if(D(i))return o.push({bindingId:e,phase:"skipped",details:{reason:"unsupported-cross-canvas"}}),o;let r;try{r=de(i.mapping,t),o.push({bindingId:e,phase:"mapping",details:{payload:t,args:r}})}catch(n){return o.push({bindingId:e,phase:"error",details:{stage:"mapping",message:n instanceof Error?n.message:String(n)}}),o}const c=n.getInstance(i.target.instanceId,a);if(!c)return o.push({bindingId:e,phase:"skipped",details:{reason:"target-not-mounted"}}),o;if("instanceDataInput"===i.target.kind){const n=c.vm.custom,t=null==n?void 0:n[i.target.key];if(!t||"object"!=typeof t||!0!==t.dataInput)return o.push({bindingId:e,phase:"skipped",details:{reason:"unknown-target-data-input",key:i.target.key}}),o}return o.push({bindingId:e,phase:"calling-target",details:{target:i.target,dryRun:!0}}),o.push({bindingId:e,phase:"done",details:{args:r}}),o},on:(e,n)=>L.on(e,n),startTracing(e){E.start(e)},stopTracing:()=>E.stop(),getTraceBuffer:()=>E.snapshot(),dispose:function(){if(!u){"runtime"===d&&function(){for(const e of $())"page"===e.source.kind&&"pageBeforeUnmount"===e.source.hook&&U(e,{hook:"pageBeforeUnmount"})}(),u=!0,_();for(const e of C)N(e);for(const e of z)N(e);C.length=0,z.length=0,b.clear(),k.clear(),S.clear(),B.clear(),M.clear(),T.clear(),x.clear(),E.stop(),L.clear(),I(),d="off"}}}}function we(e,n){const t=new Set;for(const o of e)n.has(o)||t.add(o);return t}const xe=["display","gridTemplateColumns","gridTemplateRows","gridAutoFlow","flexDirection","flexWrap","gap","rowGap","columnGap","justifyContent","alignItems","position"];function be(e,t){const o="string"==typeof(null==e?void 0:e.js)?e.js:"",i="string"==typeof(null==e?void 0:e.html)?e.html:"",a=n.parseComponentSource(o,i);return!a.ok&&(null==t?void 0:t.fallback)?t.fallback:{propsDecl:a.propsDecl.map(Se),emitsDecl:a.emitsDecl.map(Me),methodsDecl:a.methodsDecl.map(Be),slotsDecl:a.slotsDecl.map(Te),modelDecl:a.modelDecl.map(Ce),dataInputsDecl:a.dataInputsDecl.map(ze),dataOutputsDecl:a.dataOutputsDecl.map(ze)}}function ke(e){if("string"===e||"number"===e||"boolean"===e||"object"===e||"array"===e||"any"===e)return e}function Se(e){const n=e.key,t="string"==typeof e.name?e.name:void 0;return{key:n,type:ke(e.type)??"string",...void 0!==e.value?{value:e.value}:{},...t&&t!==n?{label:t}:{},...e.enum?{enum:e.enum}:{}}}function Be(e){return{key:e.name,...e.params?{params:e.params}:{}}}function Me(e){return{event:e.event}}function Te(e){return{name:e.name,...void 0!==e.multiple?{multiple:e.multiple}:{},...void 0!==e.accepts?{accepts:e.accepts}:{},...void 0!==e.maxChildren?{maxChildren:e.maxChildren}:{},...void 0!==e.label?{label:e.label}:{}}}function Ce(e){const n=ke(e.type);return{key:e.key,...void 0!==e.prop?{prop:e.prop}:{},...void 0!==e.event?{event:e.event}:{},...n?{type:n}:{},...void 0!==e.defaultValue?{defaultValue:e.defaultValue}:{}}}function ze(e){const n=ke(e.type);return{key:e.key,...n?{type:n}:{},...void 0!==e.label?{label:e.label}:{}}}const Le=["data-hc-canvas-id"],Ee=["data-instance-id","data-hc-hidden"],Pe={key:0,class:"hc-page-instance-fallback",style:{width:"100%",height:"100%",border:"2px dashed #f59e0b",background:"#fef3c7",color:"#92400e",padding:"8px",fontSize:"11px",fontFamily:"monospace",overflow:"hidden",borderRadius:"4px",boxSizing:"border-box"}},De={style:{opacity:"0.8"}},Re={style:{opacity:"0.6","margin-top":"4px","word-break":"break-all"}},Oe={key:2,class:"hc-page-instance-skeleton",style:{width:"100%",height:"100%",background:"linear-gradient(90deg, #f1f5f9 0%, #e2e8f0 50%, #f1f5f9 100%)",backgroundSize:"200% 100%",animation:"hc-skeleton-shimmer 1.5s infinite ease-in-out",borderRadius:"4px",boxSizing:"border-box"}},$e=["data-instance-id","data-hc-placement","data-hc-hidden"],Ae={key:0,class:"hc-page-instance-fallback",style:{width:"100%",height:"100%",border:"2px dashed #f59e0b",background:"#fef3c7",color:"#92400e",padding:"8px","font-size":"11px","font-family":"monospace",overflow:"hidden","border-radius":"4px","box-sizing":"border-box"}},Ne={style:{opacity:"0.6"}},Fe=["title"],je={key:1,class:"hc-page-renderer-empty",style:{padding:"24px",color:"#64748b","font-size":"13px"}},Ve=e.defineComponent({__name:"HyperCardPageRenderer",props:{payload:{},document:{},componentSourceMap:{},schedulerOptions:{},canvasId:{},adapters:{}},setup(t,{expose:o}){var i,a;const r=t,l=r.canvasId??function(){var e;const n="undefined"!=typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;return`auto-${(null==(e=null==n?void 0:n.randomUUID)?void 0:e.call(n).replace(/-/g,"").slice(0,8))??Math.random().toString(36).slice(2,10)}`}();e.provide(n.HC_CANVAS_ID_KEY,l);const u=N(r.schedulerOptions),p=e.ref(null);let f=!1;e.onMounted(()=>{U||e.nextTick(()=>{var e;if(f)return;if(!p.value)return;if("fill"!==(null==(e=K.value)?void 0:e.canvas.height.mode))return;const n=p.value.parentElement;n&&(n.getBoundingClientRect().height>0||(f=!0,console.warn("[hypercard] HyperCardPageRenderer 父容器高度为 0,fill 模式画布不可见。请给父容器设置明确 height 或改用 px 模式。")))})}),e.onBeforeUnmount(()=>{H.value&&(H.value.dispose(),H.value=null),u.dispose(),G&&G.disposeAll(),l!==n.DEFAULT_CANVAS_ID&&n.disposeCanvas(l)});const h=e.ref(new Map),g=e.ref(new Map),m=new Map,v=e.ref(!1);let y=null;function I(){v.value=!1,y&&clearTimeout(y),y=setTimeout(()=>{v.value=!0},300)}function w(e,n){const t=new Map;if(n.querySelectorAll("[data-hc-slot]").forEach(e=>{if(e.closest("[data-instance-id]")!==n)return;const o=e.getAttribute("data-hc-slot")||te;t.has(o)||t.set(o,e)}),function(e,n){if(!e||e.size!==n.size)return!1;for(const[t,o]of n)if(e.get(t)!==o)return!1;return!0}(g.value.get(e),t))return;const o=new Map(g.value);o.set(e,t),g.value=o,x(e,t)}function x(e,n){const t=n.get(te);if(!t)return;const o=T.value,i=null==o?void 0:o.instances.find(n=>n.instanceId===e);!function(e,n){!function(e){const n=e.style;for(const e of xe)n[e]=""}(e);const t=null==n?void 0:n.mode;if(!n||"none"===t||void 0===t)return;if("free"===t)return void(e.style.position="relative");const o=S(n);o&&Object.assign(e.style,o)}(t,null==i?void 0:i.containerLayout)}function k(e,n){const t=h.value.get(e);n&&n!==t?(h.value.set(e,n),u.register(e,n),function(e,n){const t=m.get(e);t&&t.disconnect(),w(e,n);const o=new MutationObserver(()=>w(e,n));o.observe(n,{childList:!0,subtree:!0}),m.set(e,o)}(e,n)):!n&&t&&(u.unregister(e),h.value.delete(e),function(e){const n=m.get(e);if(n&&(n.disconnect(),m.delete(e)),g.value.has(e)){const n=new Map(g.value);n.delete(e),g.value=n}}(e))}e.onMounted(I),e.watch(g,I),e.onBeforeUnmount(()=>{for(const e of m.values())e.disconnect();m.clear(),g.value=new Map,y&&clearTimeout(y)});const T=e.computed(()=>{var e;const n=(null==(e=r.payload)?void 0:e.document)??r.document??null;return n?d(s(c(n))):null});e.watch(T,()=>{e.nextTick(()=>function(){for(const[e,n]of g.value)x(e,n)}())},{flush:"post"});const C=e.computed(()=>function(e){const n={};for(const t of Object.keys(e)){const o=e[t],i=o.source;o&&"ok"===o.status&&i&&("string"==typeof i.html||"string"==typeof i.js)?n[t]={...o,contract:be({html:i.html??"",js:i.js??"",css:i.css??""},{fallback:o.contract})}:n[t]=o}return n}(r.payload?r.payload.componentVersions:r.componentSourceMap??{})),z=e.computed(()=>{const e=T.value,n=C.value;return e?e.instances.map(t=>{var o;const i=n[t.componentVersionKey]??null,a=(null==(o=e.componentOverrides)?void 0:o[t.instanceId])??null,r=a&&a.baseVersionKey===t.componentVersionKey?a:null,c=r?`${r.baseVersionKey}#override:${t.instanceId}`:t.componentVersionKey;if(r)return{instance:t,asset:i,override:r,renderSource:r.source,scopeId:c,status:"ok"};if(!i)return{instance:t,asset:null,override:null,renderSource:null,scopeId:c,status:"missing-source",invalidReason:`componentVersionKey "${t.componentVersionKey}" not in sourceMap`};if("ok"!==i.status)return{instance:t,asset:i,override:null,renderSource:null,scopeId:c,status:"unavailable",invalidReason:i.invalidReason??`component version unavailable (${i.status})`};let s=null;return s=function(e){return!!e&&!0===e.isDraft}(i)?i.lastGoodSource:i.source??null,s?{instance:t,asset:i,override:null,renderSource:s,scopeId:c,status:"ok"}:{instance:t,asset:i,override:null,renderSource:null,scopeId:c,status:"missing-source",invalidReason:"asset.status=ok but source missing"}}):[]});function L(e){const n=C.value[e];return null==n?void 0:n.contract}const E=e.computed(()=>{const e=T.value;return e?ie(e,{resolveContract:L}):[]}),P=e.inject(Q,null);e.watch(E,e=>{P&&"function"==typeof P.setLayoutIssues&&P.setLayoutIssues(e)},{immediate:!0});const D=e.computed(()=>{const e=new Set;for(const n of E.value)"missing-parent"!==n.kind&&"invalid-slot"!==n.kind&&"parent-not-layout"!==n.kind&&"orphan-slot"!==n.kind&&"cycle"!==n.kind&&"absolute-child-rejected"!==n.kind||e.add(n.instanceId);return e}),R=e.computed(()=>z.value.filter(e=>void 0===e.instance.parentId)),A=e.computed(()=>z.value.filter(e=>void 0!==e.instance.parentId&&O(e.instance.placement)));function F(e){const n=e.layoutBox??{x:e.rect.x,y:e.rect.y,width:e.rect.w,height:e.rect.h,widthMode:"px",heightMode:"px",overflow:"hidden"},t=function(e){const n=T.value;if(n)return $(K.value??void 0,n.instances,e.instanceId)}(e),o=b(n,e.zIndex,e.rotation,t,function(e){var n,t;const o=T.value;if(!o)return;if(void 0===e.parentId){const e=null==(n=K.value)?void 0:n.rootLayout;return"split"===(null==e?void 0:e.mode)?e.direction:void 0}const i=null==(t=o.instances.find(n=>n.instanceId===e.parentId))?void 0:t.containerLayout;return"split"===(null==i?void 0:i.mode)?i.direction:void 0}(e)),i=B(e.layoutItem,t);return i&&Object.assign(o,i),o}const j=e.computed(()=>{var e;return S(null==(e=K.value)?void 0:e.rootLayout)});function V(e){if(!e.parentId)return null;const n=g.value.get(e.parentId);return n?n.get(oe(e))??null:null}function q(e){return{position:"absolute",left:"8px",top:8+28*A.value.indexOf(e)+"px",padding:"4px 8px",background:"hsla(40, 90%, 50%, 0.95)",color:"#5b3a00",fontSize:"11px",fontFamily:"ui-monospace, monospace",borderRadius:"4px",zIndex:9999,maxWidth:"60%",textOverflow:"ellipsis",overflow:"hidden",whiteSpace:"nowrap"}}function _(e){return"实例 "+e.instance.instanceId+':slot "'+oe(e.instance)+'" 不可用'}const K=e.computed(()=>{var e;return(null==(e=T.value)?void 0:e.layout)??null}),J=e.computed(()=>{if(!K.value)return null;if(U){const e=U.measuredCanvasSize.value;return{width:`${e.w}px`,height:`${e.h}px`,overflow:K.value.canvas.overflow??"hidden"}}return{width:M(K.value.canvas.width),height:M(K.value.canvas.height),overflow:K.value.canvas.overflow??"hidden"}}),U=e.inject(Q,void 0),X=U?null:Y(null==(i=r.adapters)?void 0:i.assets),H=e.shallowRef(null),G=U||!(null==(a=r.adapters)?void 0:a.data)?null:W(r.adapters.data);if(!U){const n=Ie({canvasId:l,source:{getDocument:()=>T.value,onDocumentChange:n=>e.watch(T,n,{flush:"post"})},dataStore:G??void 0});H.value=n,e.nextTick(()=>{n.setMode("runtime")})}o({binding:H,data:U?{invalidateDataSource(e){U.dataStore.invalidate(e)},getDataSourceSnapshot:()=>U.dataStore.getSnapshot()}:G?{invalidateDataSource(e){G.invalidate(e)},getDataSourceSnapshot:()=>G.getSnapshot()}:null});const Z=e.ref(null);let ee=0;e.watch(()=>{var e,n;return null==(n=null==(e=K.value)?void 0:e.background)?void 0:n.image},e=>{ee++;const n=ee;if(!e)return void(Z.value=null);const t=(o=e,U?U.resolveAsset(o):X.resolve(o));var o;"string"!=typeof t?(Z.value=null,t.then(t=>{var o,i;n===ee&&(null==(i=null==(o=K.value)?void 0:o.background)?void 0:i.image)===e&&(Z.value=t||null)},()=>{n===ee&&(Z.value=null)})):Z.value=t||null},{immediate:!0,deep:!0});const ne=e.computed(()=>{var e;const n=null==(e=K.value)?void 0:e.background;if(!n)return null;const t={position:"absolute",inset:"0",pointerEvents:"none",zIndex:-1};return n.color&&(t.background=n.color),n.image&&Z.value&&(t.backgroundImage=`url("${Z.value}")`,t.backgroundRepeat="repeat"===n.imageFit?"repeat":"no-repeat",t.backgroundPosition=n.imagePosition??"center","stretch"===n.imageFit?t.backgroundSize="100% 100%":n.imageFit&&"repeat"!==n.imageFit&&"center"!==n.imageFit&&(t.backgroundSize=n.imageFit)),void 0!==n.opacity&&(t.opacity=n.opacity),t});return(t,o)=>K.value&&J.value?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"rootEl",ref:p,class:"hc-page-renderer","data-hc-canvas-id":e.unref(l),style:e.normalizeStyle({position:"relative",...J.value,...j.value??{}})},[ne.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"hc-canvas-bg","data-hc-canvas-bg":"",style:e.normalizeStyle(ne.value)},null,4)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(R.value,t=>e.withDirectives((e.openBlock(),e.createElementBlock("div",{key:t.instance.instanceId,ref_for:!0,ref:e=>k(t.instance.instanceId,e),"data-instance-id":t.instance.instanceId,"data-hc-hidden":t.instance.hidden?"true":void 0,style:e.normalizeStyle(F(t.instance))},["ok"===t.status&&t.renderSource?e.unref(u).isMounted(t.instance.instanceId)?(e.openBlock(),e.createBlock(e.unref(n.RuntimeBox),{key:1,"canvas-id":e.unref(l),"instance-id":t.instance.instanceId,"component-id":t.instance.componentId,"scope-id":t.scopeId,"html-source":t.renderSource.html,"js-source":t.renderSource.js,"css-source":t.renderSource.css,"custom-values":{...t.instance.props,__containerLayout:t.instance.containerLayout}},null,8,["canvas-id","instance-id","component-id","scope-id","html-source","js-source","css-source","custom-values"])):(e.openBlock(),e.createElementBlock("div",Oe)):(e.openBlock(),e.createElementBlock("div",Pe,[o[0]||(o[0]=e.createElementVNode("div",{style:{"font-weight":"600","margin-bottom":"4px"}}," ⚠️ 组件不可渲染 ",-1)),e.createElementVNode("div",De,e.toDisplayString(t.instance.alias??t.instance.instanceId),1),e.createElementVNode("div",Re,e.toDisplayString(t.invalidReason),1)]))],12,Ee)),[[e.vShow,!t.instance.hidden]])),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(A.value,t=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:`child-${t.instance.instanceId}`},[V(t.instance)&&!D.value.has(t.instance.instanceId)?(e.openBlock(),e.createBlock(e.Teleport,{key:0,to:V(t.instance)},[e.withDirectives(e.createElementVNode("div",{ref_for:!0,ref:e=>k(t.instance.instanceId,e),"data-instance-id":t.instance.instanceId,"data-hc-placement":t.instance.placement,"data-hc-hidden":t.instance.hidden?"true":void 0,style:e.normalizeStyle(F(t.instance))},["ok"===t.status&&t.renderSource?(e.openBlock(),e.createBlock(e.unref(n.RuntimeBox),{key:1,"canvas-id":e.unref(l),"instance-id":t.instance.instanceId,"component-id":t.instance.componentId,"scope-id":t.scopeId,"html-source":t.renderSource.html,"js-source":t.renderSource.js,"css-source":t.renderSource.css,"custom-values":{...t.instance.props,__containerLayout:t.instance.containerLayout}},null,8,["canvas-id","instance-id","component-id","scope-id","html-source","js-source","css-source","custom-values"])):(e.openBlock(),e.createElementBlock("div",Ae,[o[1]||(o[1]=e.createElementVNode("div",{style:{"font-weight":"600"}},"⚠️ 组件不可渲染",-1)),e.createElementVNode("div",Ne,e.toDisplayString(t.invalidReason),1)]))],12,$e),[[e.vShow,!t.instance.hidden]])],8,["to"])):D.value.has(t.instance.instanceId)||v.value?(e.openBlock(),e.createElementBlock("div",{key:1,class:"hc-layout-issue-warning",title:_(t),style:e.normalizeStyle(q(t))}," ⚠ 布局问题:"+e.toDisplayString(t.instance.instanceId)+'(slot "'+e.toDisplayString(e.unref(oe)(t.instance))+'") ',13,Fe)):e.createCommentVNode("",!0)],64))),128))],12,Le)):(e.openBlock(),e.createElementBlock("div",je," No page to render(payload / document 都未提供) "))}}),qe=new Map,_e=new Set;function Ke(){const e=Object.freeze(Array.from(qe.keys()));for(const n of _e)try{n(e)}catch{}}function Je(e,n){qe.set(e,n),Ke()}function Ue(e){qe.delete(e)&&Ke()}function Xe(e,n){var o;const i=n.document;switch(e.type){case"addInstance":{const{instance:n}=e.payload;return i.getInstance(n.instanceId)?null:[{type:"removeInstance",payload:{instanceId:n.instanceId}}]}case"removeInstance":{const{instanceId:n}=e.payload,o=i.getInstance(n);if(!o)return null;const a=i.document.bindings.filter(e=>j(e,n)),r=[{type:"addInstance",payload:{instance:He(o)}}];for(const e of a)r.push({type:"addBinding",payload:{binding:t(e)}});return r}case"updateInstance":{const{instanceId:n,patch:o}=e.payload,a=i.getInstance(n);if(!a)return null;const r={};for(const e of Object.keys(o)){const n=a[e];r[e]=Ye(n)?t(n):n}return[{type:"updateInstance",payload:{instanceId:n,patch:r}}]}case"moveInstance":{const{instanceId:n,x:t,y:o}=e.payload,a=i.getInstance(n);return a?a.rect.x===t&&a.rect.y===o?null:a.layoutBox?[{type:"updateLayoutBox",payload:{instanceId:n,patch:{...a.layoutBox}}}]:[{type:"moveInstance",payload:{instanceId:n,x:a.rect.x,y:a.rect.y}}]:null}case"resizeInstance":{const{instanceId:n,w:t,h:o}=e.payload,a=i.getInstance(n);return a?a.rect.w===t&&a.rect.h===o?null:a.layoutBox?[{type:"updateLayoutBox",payload:{instanceId:n,patch:{...a.layoutBox}}}]:[{type:"resizeInstance",payload:{instanceId:n,w:a.rect.w,h:a.rect.h}}]:null}case"setInstanceProp":{const{instanceId:n,key:t,value:o}=e.payload,a=i.getInstance(n);return a?a.props[t]===o?null:[{type:"updateInstance",payload:{instanceId:n,patch:{props:{...a.props}}}}]:null}case"addBinding":{const{binding:n}=e.payload;return i.document.bindings.some(e=>e.id===n.id)?null:[{type:"removeBinding",payload:{bindingId:n.id}}]}case"removeBinding":{const{bindingId:n}=e.payload,o=i.document.bindings.find(e=>e.id===n);return o?[{type:"addBinding",payload:{binding:t(o)}}]:null}case"updateBinding":{const{bindingId:n,patch:o}=e.payload,a=i.document.bindings.find(e=>e.id===n);if(!a)return null;const r={};for(const e of Object.keys(o)){const n=a[e];r[e]=Ye(n)?t(n):n}return[{type:"updateBinding",payload:{bindingId:n,patch:r}}]}case"updateLayout":{const{patch:n}=e.payload,o={};for(const e of Object.keys(n)){const n=i.document.layout[e];o[e]=Ye(n)?t(n):n}return[{type:"updateLayout",payload:{patch:o}}]}case"setRootLayout":{const{rootLayout:n}=e.payload,o=i.document.layout.rootLayout,a=void 0!==o;return a||null!==n?[{type:"setRootLayout",payload:{rootLayout:a?t(o):null}}]:null}case"setComponentOverride":{const{instanceId:n,override:a}=e.payload;if(void 0===i.getInstance(n))return null;const r=null==(o=i.document.componentOverrides)?void 0:o[n],c=void 0!==r;return c||null!==a?[{type:"setComponentOverride",payload:{instanceId:n,override:c?t(r):null}}]:null}case"replaceDocument":return[{type:"replaceDocument",payload:{document:t(i.document)}}];case"setInstanceLocked":{const{instanceId:n,locked:t}=e.payload,o=i.getInstance(n);if(!o)return null;const a=o.locked??!1,r=o.lockPosition,c=o.lockSize;return a===t&&r===(!!t||void 0)&&c===(!!t||void 0)?null:[{type:"updateInstance",payload:{instanceId:n,patch:{locked:a,lockPosition:r,lockSize:c}}}]}case"duplicateInstance":{const{instanceId:n,newInstanceId:t}=e.payload;return i.getInstance(n)?i.getInstance(t)?null:[{type:"removeInstance",payload:{instanceId:t}}]:null}case"setInstanceSize":{const{instanceId:n,size:o}=e.payload,a=i.getInstance(n);if(!a)return null;const r=a.size,c="size"in a&&void 0!==r;return c||null!==o?[{type:"setInstanceSize",payload:{instanceId:n,size:(c?t(r):null)??null}}]:null}case"setContainerLayout":{const{instanceId:n,containerLayout:o}=e.payload,a=i.getInstance(n);if(!a)return null;const r=a.containerLayout,c="containerLayout"in a&&void 0!==r;return c||null!==o?[{type:"setContainerLayout",payload:{instanceId:n,containerLayout:(c?t(r):null)??null}}]:null}case"updateLayoutBox":{const{instanceId:n,patch:t}=e.payload,o=i.getInstance(n);if(!o)return null;const a=o.layoutBox??{x:o.rect.x,y:o.rect.y,width:o.rect.w,height:o.rect.h,widthMode:"px",heightMode:"px",overflow:"hidden"},r={};let c=!1;const s=["x","y","width","height"];for(const e of s){const n=t[e];"number"==typeof n&&Number.isFinite(n)&&(r[e]=a[e],c=!0)}return"px"!==t.widthMode&&"percent"!==t.widthMode&&"fill"!==t.widthMode&&"auto"!==t.widthMode||(r.widthMode=a.widthMode,c=!0),"px"!==t.heightMode&&"percent"!==t.heightMode&&"fill"!==t.heightMode&&"auto"!==t.heightMode||(r.heightMode=a.heightMode,c=!0),"hidden"!==t.overflow&&"visible"!==t.overflow&&"auto"!==t.overflow||(r.overflow=a.overflow,c=!0),c?[{type:"updateLayoutBox",payload:{instanceId:n,patch:r}}]:null}case"updateLayoutItem":{const{instanceId:n,patch:o}=e.payload,a=i.getInstance(n);if(!a)return null;const r=a.layoutItem,c="layoutItem"in a&&void 0!==r,s=null===o;if(!c&&s)return null;if(!s){const e=["order","grow","shrink","row","column","rowSpan","columnSpan","ratio"];let n=!1;for(const t of e){const e=o[t];if("number"==typeof e&&Number.isFinite(e)){n=!0;break}}if(!n)return null}return[{type:"updateLayoutItem",payload:{instanceId:n,patch:(c?t(r):null)??null}}]}case"updateRotation":{const{instanceId:n,value:t}=e.payload,o=i.getInstance(n);if(!o)return null;if(!Number.isFinite(t))return null;const a=o.rotation,r="number"==typeof a&&Number.isFinite(a)?a:0;return r===t?null:[{type:"updateRotation",payload:{instanceId:n,value:r}}]}case"select":case"toggleSelect":case"addToSelection":case"removeFromSelection":case"clearSelection":case"selectAll":return null;default:{const n=e;return console.warn("[hc-canvas/computeInverse] unknown action",n),null}}}function Ye(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function He(e){return t(e)}function Ge(n,t={}){const o=t.maxSize??100,i=e.ref([]),a=e.ref([]);let r={redo:[],undo:[]},c=null;function s(e){var n;0===r.redo.length&&0===r.undo.length||(n={type:e,redo:r.redo,undo:r.undo,timestamp:Date.now()},i.value.push(n),i.value.length>o&&i.value.shift(),a.value.length>0&&(a.value=[]),r={redo:[],undo:[]},c=null)}const d={onBeforeAction(e){if(n.isRecordingSuppressed.value)return;const t=Xe(e,n);if(null!==t){r.redo.push(e);for(let e=t.length-1;e>=0;e--)r.undo.unshift(t[e]);c=e.type}},onAfterAction(e){n.isRecordingSuppressed.value||n.isBatching.value||s(c??"action")},onAfterBatch(e){n.isRecordingSuppressed.value||s(e??"batch")}},l=n.registerHooks(d);function u(){i.value=[],a.value=[],r={redo:[],undo:[]},c=null}return{undo:function(){if(0===i.value.length)return;const e=i.value.pop();n.suppressRecording(()=>{n.beginBatch();for(const t of e.undo)n.dispatch(t);n.endBatch("undo")}),a.value.push(e)},redo:function(){if(0===a.value.length)return;const e=a.value.pop();n.suppressRecording(()=>{n.beginBatch();for(const t of e.redo)n.dispatch(t);n.endBatch("redo")}),i.value.push(e)},clear:u,canUndo:e.computed(()=>i.value.length>0),canRedo:e.computed(()=>a.value.length>0),undoStackSize:e.computed(()=>i.value.length),redoStackSize:e.computed(()=>a.value.length),dispose:function(){l(),u()}}}function We(e,n,t){let o=null;for(const i of e)for(const e of n){const n=e.pos-i,a=Math.abs(n);a<=t&&(!o||a<Math.abs(o.delta))&&(o={delta:n,candidate:e,targetPos:i})}return o}function Qe(e){var n,t,o,i;const a=e.threshold??5,r=function(e){if(0===e.length)return null;let n=1/0,t=-1/0,o=1/0,i=-1/0;for(const a of e)a.x<n&&(n=a.x),a.x+a.w>t&&(t=a.x+a.w),a.y<o&&(o=a.y),a.y+a.h>i&&(i=a.y+a.h);return{left:n,right:t,top:o,bottom:i,centerX:(n+t)/2,centerY:(o+i)/2,width:t-n,height:i-o}}(e.draggedRects);if(!r)return{dx:0,dy:0,lines:[]};const c=function(e,n,t){const o=[];for(const n of e)o.push({pos:n.x,kind:"edge-left",source:n}),o.push({pos:n.x+n.w,kind:"edge-right",source:n}),o.push({pos:n.x+n.w/2,kind:"center-x",source:n});if(o.push({pos:0,kind:"canvas-edge"}),o.push({pos:n.w,kind:"canvas-edge"}),o.push({pos:n.w/2,kind:"canvas-edge"}),t)for(const e of t)o.push({pos:e,kind:"guide"});return o}(e.otherRects,e.canvasSize,null==(n=e.manualGuides)?void 0:n.x),s=function(e,n,t){const o=[];for(const n of e)o.push({pos:n.y,kind:"edge-top",source:n}),o.push({pos:n.y+n.h,kind:"edge-bottom",source:n}),o.push({pos:n.y+n.h/2,kind:"center-y",source:n});if(o.push({pos:0,kind:"canvas-edge"}),o.push({pos:n.h,kind:"canvas-edge"}),o.push({pos:n.h/2,kind:"canvas-edge"}),t)for(const e of t)o.push({pos:e,kind:"guide"});return o}(e.otherRects,e.canvasSize,null==(t=e.manualGuides)?void 0:t.y),d=[r.left,r.right,r.centerX],l=[r.top,r.bottom,r.centerY],u=We(d,c,a),p=We(l,s,a),f=(null==u?void 0:u.delta)??0,h=(null==p?void 0:p.delta)??0,g=[];if(u){const n=(null==(o=u.candidate.source)?void 0:o.y)??0,t=u.candidate.source?u.candidate.source.y+u.candidate.source.h:e.canvasSize.h,i=Math.min(r.top+h,n),a=Math.max(r.bottom+h,t);g.push({axis:"x",pos:u.candidate.pos,from:i,to:a,kind:u.candidate.kind})}if(p){const n=(null==(i=p.candidate.source)?void 0:i.x)??0,t=p.candidate.source?p.candidate.source.x+p.candidate.source.w:e.canvasSize.w,o=Math.min(r.left+f,n),a=Math.max(r.right+f,t);g.push({axis:"y",pos:p.candidate.pos,from:o,to:a,kind:p.candidate.kind})}return{dx:f,dy:h,lines:g}}function Ze(e,n,t){const o=new Map;for(let e=0;e<n.length;e++)o.set(n[e].instanceId,e);const i=new Map;function a(e){const t=i.get(e);if(t)return t;const o=[];let a=e;const r=new Set;for(;a&&!r.has(a);){r.add(a),o.push(a);const e=n.find(e=>e.instanceId===a);if(!(null==e?void 0:e.parentId))break;a=e.parentId}const c=o.reverse();return i.set(e,c),c}function r(e,t){const i=a(e),r=a(t);let c=0;for(;c<i.length&&c<r.length&&i[c]===r[c];)c++;if(c===i.length&&c===r.length)return 0;if(c===i.length)return-1;if(c===r.length)return 1;const s=i[c],d=r[c],l=n.find(e=>e.instanceId===s),u=n.find(e=>e.instanceId===d),p=(null==l?void 0:l.zIndex)??0,f=(null==u?void 0:u.zIndex)??0;return p!==f?p-f:(o.get(s)??-1)-(o.get(d)??-1)}let c=null,s=-1;for(let o=0;o<n.length;o++){const i=n[o];if(i.hidden)continue;const a=(null==t?void 0:t(i.instanceId))??i.rect;if(!(e.x>=a.x&&e.x<=a.x+a.w&&e.y>=a.y&&e.y<=a.y+a.h))continue;if(null===c){c=i.instanceId,s=o;continue}const d=r(i.instanceId,c);let l;l=d>0||!(d<0)&&o>s,l&&(c=i.instanceId,s=o)}return c}function en(e,n){return{x:Math.min(e.x,n.x),y:Math.min(e.y,n.y),w:Math.abs(e.x-n.x),h:Math.abs(e.y-n.y)}}function nn(e,n,t){const o=[];for(const i of n){if(i.hidden)continue;const n=(null==t?void 0:t(i.instanceId))??i.rect;n.x>=e.x&&n.y>=e.y&&n.x+n.w<=e.x+e.w&&n.y+n.h<=e.y+e.h&&o.push(i.instanceId)}return o}function tn(e,n){if(!e||"function"!=typeof e.querySelector)return null;const t=e.querySelector(n);if(t)return t;if(e instanceof Element&&"function"==typeof e.closest){const t=e.closest("[data-hc-canvas-designer]");if(t&&t!==e){const e=t.querySelector(n);if(e)return e}}return null}function on(e,n,t){var o;const i=t??("undefined"!=typeof document&&"function"==typeof document.querySelector?document:null);if(!i)return null;const a=n??"default",r=""===a?"default":a,c="undefined"!=typeof globalThis&&(null==(o=globalThis.CSS)?void 0:o.escape)?globalThis.CSS.escape:e=>e.replace(/["\\]/g,e=>`\\${e}`),s=tn(i,`[data-instance-id="${c(e)}"] [data-hc-slot="${c(r)}"]`);return s&&s instanceof HTMLElement?s.getBoundingClientRect():null}function an(e,n,t){var o;const i=n??("undefined"!=typeof document&&"function"==typeof document.querySelector?document:null);if(!i)return null;if("function"!=typeof i.querySelector)return null;const a=`[data-instance-id="${("undefined"!=typeof globalThis&&(null==(o=globalThis.CSS)?void 0:o.escape)?globalThis.CSS.escape:e=>e.replace(/["\\]/g,e=>`\\${e}`))(e)}"]`,r=t?tn(i,a):i.querySelector(a);return r&&r instanceof HTMLElement?r.getBoundingClientRect():null}function rn(e,n){return $(e.document.document.layout,e.document.document.instances,n)}function cn(e){return"free"===e||"none"===e||void 0===e}const sn=new Set(["e","w","ne","nw","se","sw"]),dn=new Set(["n","s","ne","nw","se","sw"]);function ln(e,n,t,o){if(cn(e))return!0;const i=sn.has(n),a=dn.has(n);return!(i&&"fill"===t||a&&"fill"===o)}function un(e,n,t){if(!n)return null;const o=an(e,n,!0);if(!o)return null;const i=n.getBoundingClientRect(),a=t.toCanvasPoint({x:o.left-i.left,y:o.top-i.top}),r=t.toCanvasPoint({x:o.right-i.left,y:o.bottom-i.top});return{x:a.x,y:a.y,w:Math.max(0,r.x-a.x),h:Math.max(0,r.y-a.y)}}function pn(e,n,t){const o=Math.max(8,n);if(!e)return{mode:"px",value:o};switch(e.mode){case"px":return{...e,mode:"px",value:o};case"percent":{if(!t||t<=0)return{...e,mode:"px",value:o};const n=o/t*100,i=Math.max(0,Math.min(1e3,n));return{...e,mode:"percent",value:i}}case"fill":case"hug":case"auto":return{mode:"px",value:o,min:e.min,max:e.max}}}function fn(e,n,t){const o=Math.max(8,n);switch(e){case"px":case"fill":case"auto":default:return{mode:"px",value:o};case"percent":{if(!t||t<=0)return{mode:"px",value:o};const e=o/t*100;return{mode:"percent",value:Math.max(0,Math.min(1e3,e))}}}}function hn(e){return e.shift||e.ctrl||e.meta}function gn(e,n,t){const o=n.getBoundingClientRect(),i={x:e.x-o.left,y:e.y-o.top};return t.toCanvasPoint(i)}function mn(e,n){const t=new Set(n.map(e=>e.instanceId));return e.filter(e=>t.has(e))}function vn(n,t={}){const o=e.reactive({active:!1,start:null,end:null,additive:!1,priorSelection:[]}),i=e.reactive({status:"idle",startPt:null,startRects:new Map,deferredClickSelect:null}),a=e.reactive({status:"idle",handle:null,startPt:null,startRect:null,instanceId:null,placement:null,parentLayoutMode:void 0,startSize:null,startLayoutBox:null,startOutletCanvasSize:null}),r=e.ref([]),c=e.ref(null);let s=0;const d=e.ref(null);let l=0;const u=e.computed(()=>o.active&&o.start&&o.end?en(o.start,o.end):null),p=e.computed(()=>"active"===i.status),f=e.computed(()=>"active"===a.status);function h(){o.active=!1,o.start=null,o.end=null,o.additive=!1,o.priorSelection=[]}function g(){i.status="idle",i.startPt=null,i.startRects=new Map,i.deferredClickSelect=null,r.value=[]}function m(){a.status="idle",a.handle=null,a.startPt=null,a.startRect=null,a.instanceId=null,a.placement=null,a.startSize=null,a.startOutletCanvasSize=null,a.parentLayoutMode=void 0,a.startLayoutBox=null}return{marquee:o,marqueeRect:u,drag:i,isDragging:p,resize:a,isResizing:f,snapLines:r,cannotDragSlotChildEvent:c,cannotDragLayoutManagedChildEvent:d,handlePointerDown(e,a){var r;const u=n.effectiveBehavior.value;if(!u.selectable)return{startTracking:!1};const p=n.toolMode.value;if("hand"===p)return{startTracking:!1};const f=hn(a),h="marquee"===p?null:Ze(e,n.document.document.instances,t.getDomBox);if(h){const t=n.document.getInstance(h),o=!0===((null==t?void 0:t.lockPosition)??(null==t?void 0:t.locked)),a=n.selection.selectedIds.value.includes(h),g=n.selection.size.value>1;f?n.dispatch({type:"toggleSelect",payload:{instanceId:h}}):o?n.dispatch({type:"select",payload:{instanceId:h}}):a&&g&&u.draggable&&"inspect"!==p?i.deferredClickSelect=h:n.dispatch({type:"select",payload:{instanceId:h}});const m="slot"===(null==t?void 0:t.placement)||"container"===(null==t?void 0:t.placement),v=rn(n,h),y="inspect"===p;if(o||!u.draggable||y||(null==t?void 0:t.hidden))return{startTracking:!1};if(!cn(v)){if(!f){l++;const e={instanceId:h,parentId:null==t?void 0:t.parentId,parentLayoutMode:v,token:l};d.value=e,null==(r=n.setCannotDragLayoutManagedChildEvent)||r.call(n,e),m&&(s++,c.value={instanceId:h,parentId:null==t?void 0:t.parentId,token:s})}return{startTracking:!1}}return i.status="pending",i.startPt={...e},i.startRects=function(){const e=n.selection.selectedIds.value,t=new Map;for(const o of e){const e=n.document.getInstance(o);e&&!0!==(e.lockPosition??e.locked)&&t.set(o,{x:e.rect.x,y:e.rect.y})}return t}(),{startTracking:!0}}return f||n.dispatch({type:"clearSelection"}),o.active=!0,o.start={...e},o.end={...e},o.additive=f,o.priorSelection=f?[...n.selection.selectedIds.value]:[],{startTracking:!0}},handlePointerMove(e){var c,s;if("active"===a.status&&a.startPt&&a.startRect&&a.instanceId){const t=e.x-a.startPt.x,o=e.y-a.startPt.y,i=a.startRect,r=a.handle,c=n.document.getInstance(a.instanceId);if(!c)return;const s=a.parentLayoutMode,d=void 0!==s&&!cn(s);let l=i.x,u=i.y,p=i.w,f=i.h;const h="w"===r||"nw"===r||"sw"===r,g="e"===r||"ne"===r||"se"===r,m="n"===r||"ne"===r||"nw"===r,v="s"===r||"se"===r||"sw"===r;g?p=i.w+t:h&&(p=i.w-t,d||(l=i.x+t)),v?f=i.h+o:m&&(f=i.h-o,d||(u=i.y+o)),p<8&&(!d&&h&&(l=i.x+i.w-8),p=8),f<8&&(!d&&m&&(u=i.y+i.h-8),f=8);const y=a.startLayoutBox,I=a.startOutletCanvasSize,w=g||h,x=v||m,b=!d&&h,k=!d&&m,S=w?fn(y.widthMode,p,I?I.w:null):null,B=x?fn(y.heightMode,f,I?I.h:null):null,M="canvas"===a.placement||"absolute"===a.placement,T=!(S&&"px"!==S.mode||B&&"px"!==B.mode||w&&"px"!==y.widthMode||x&&"px"!==y.heightMode);if(M&&T)(w&&c.rect.w!==p||x&&c.rect.h!==f)&&n.dispatch({type:"resizeInstance",payload:{instanceId:a.instanceId,w:w?p:c.rect.w,h:x?f:c.rect.h}}),(b&&c.rect.x!==l||k&&c.rect.y!==u)&&n.dispatch({type:"moveInstance",payload:{instanceId:a.instanceId,x:b?l:c.rect.x,y:k?u:c.rect.y}});else{const e={};S&&(e.widthMode=S.mode,e.width=S.value),B&&(e.heightMode=B.mode,e.height=B.value),b&&(e.x=l),k&&(e.y=u);const t=c.layoutBox;let o=!1;t?(void 0!==e.x&&e.x!==t.x&&(o=!0),void 0!==e.y&&e.y!==t.y&&(o=!0),void 0!==e.width&&e.width!==t.width&&(o=!0),void 0!==e.height&&e.height!==t.height&&(o=!0),void 0!==e.widthMode&&e.widthMode!==t.widthMode&&(o=!0),void 0!==e.heightMode&&e.heightMode!==t.heightMode&&(o=!0)):o=Object.keys(e).length>0,o&&n.dispatch({type:"updateLayoutBox",payload:{instanceId:a.instanceId,patch:e}})}if(("container"===a.placement||"slot"===a.placement)&&(null!==a.startSize||T)){const e=a.startSize,t={};w?t.width=pn(null==e?void 0:e.width,p,I?I.w:null):(null==e?void 0:e.width)&&(t.width=JSON.parse(JSON.stringify(e.width))),x?t.height=pn(null==e?void 0:e.height,f,I?I.h:null):(null==e?void 0:e.height)&&(t.height=JSON.parse(JSON.stringify(e.height)));const o=c.size;JSON.stringify(o)!==JSON.stringify(t)&&n.dispatch({type:"setInstanceSize",payload:{instanceId:a.instanceId,size:t}})}return}if("pending"===i.status&&i.startPt){const t=e.x-i.startPt.x,o=e.y-i.startPt.y;t*t+o*o>=9&&(i.status="active",n.beginBatch())}if("active"===i.status&&i.startPt){const o=e.x-i.startPt.x,a=e.y-i.startPt.y,d=(null==(c=t.getRoot)?void 0:c.call(t))??null,l=d instanceof HTMLElement?d:null,u=n.document.document.instances,p=null!==l&&u.length<=50,f=(e,t)=>p?un(e,l,n.viewport)??t:t,h=[];for(const[e,t]of i.startRects){const i=n.document.getInstance(e);if(!i)continue;const r=f(e,i.rect);h.push({x:t.x+o,y:t.y+a,w:r.w,h:r.h})}const g=[],m=new Set(i.startRects.keys());for(const e of u)m.has(e.instanceId)||g.push(f(e.instanceId,e.rect));const v=n.document.document.layout,y=!1!==n.effectiveBehavior.value.snap,I=(null==(s=v.guides)?void 0:s.items)??[],w=[],x=[];for(const e of I)"x"===e.axis?w.push(e.position):x.push(e.position);const b=y?Qe({draggedRects:h,otherRects:g,canvasSize:{w:n.measuredCanvasSize.value.w,h:n.measuredCanvasSize.value.h},manualGuides:w.length||x.length?{x:w,y:x}:void 0}):{dx:0,dy:0,lines:[]};r.value=b.lines;const k=o+b.dx,S=a+b.dy;for(const[e,t]of i.startRects)n.document.getInstance(e)&&n.dispatch({type:"moveInstance",payload:{instanceId:e,x:t.x+k,y:t.y+S}});return}o.active&&(o.end={...e})},handlePointerUp(){if("active"===a.status){const e="slot"===a.placement||"container"===a.placement?"resize-slot-child":"resize";return n.endBatch(e),void m()}if("active"===i.status)return n.endBatch("drag"),void g();if("pending"===i.status)return i.deferredClickSelect&&n.dispatch({type:"select",payload:{instanceId:i.deferredClickSelect}}),void g();if(!o.active)return;const e=u.value,t=n.document.document.instances;if(e&&(e.w>0||e.h>0)){const i=mn(nn(e,t),t);if(o.additive){const e=mn(o.priorSelection,t),a=Array.from(new Set([...e,...i]));n.dispatch({type:"selectAll",payload:{instanceIds:a}})}else i.length>0&&n.dispatch({type:"selectAll",payload:{instanceIds:i}})}h()},cancelMarquee(){h()},cancelDrag(){"active"===i.status&&n.endBatch("drag-cancel"),g()},handleResizeStart(e,o,i){var r,c,s,d,l,u;const p=n.document.getInstance(e);if(!p)return{startTracking:!1};if(!0===(p.lockSize??p.locked))return{startTracking:!1};if(p.hidden)return{startTracking:!1};if(!n.effectiveBehavior.value.resizable)return{startTracking:!1};const f="slot"===p.placement||"container"===p.placement,h=rn(n,e);if(!ln(h,o,null==(r=p.layoutBox)?void 0:r.widthMode,null==(c=p.layoutBox)?void 0:c.heightMode))return{startTracking:!1};a.status="active",a.handle=o,a.startPt={...i};const g=un(e,(null==(s=t.getRoot)?void 0:s.call(t))??null,n.viewport);a.startRect=g??{...p.rect},a.instanceId=e,a.placement=f?"container":"canvas",a.parentLayoutMode=h,a.startLayoutBox=p.layoutBox?JSON.parse(JSON.stringify(p.layoutBox)):{x:p.rect.x,y:p.rect.y,width:p.rect.w,height:p.rect.h,widthMode:"px",heightMode:"px",overflow:"hidden"},a.startSize=f&&p.size?JSON.parse(JSON.stringify(p.size)):null;const m=p.parentId,v=p.slot,y=(null==(d=t.getRoot)?void 0:d.call(t))??null;let I=m?on(m,v,y):null;if(m&&(!I||0===I.width&&0===I.height)){const n=tn(y,`[data-instance-id="${e.replace(/["\\]/g,e=>`\\${e}`)}"]`),t=n instanceof HTMLElement?n.parentElement:null;if(t){const e=t.getBoundingClientRect();(e.width>0||e.height>0)&&(I=e)}}if(I){const e=n.viewport.scale.value||1;a.startOutletCanvasSize={w:I.width/e,h:I.height/e}}else if(void 0===m)a.startOutletCanvasSize={w:n.measuredCanvasSize.value.w,h:n.measuredCanvasSize.value.h};else{const n=a.startLayoutBox.widthMode,t=a.startLayoutBox.heightMode,o="percent"===n||"percent"===t;o&&console.debug("[hc-canvas/interaction] resize: 父 outlet 找不到,percent 模式将退化到 px。",{instanceId:e,parentId:m,slot:v});const i=a.startSize,r="percent"===(null==(l=null==i?void 0:i.width)?void 0:l.mode)||"percent"===(null==(u=null==i?void 0:i.height)?void 0:u.mode);!o&&r&&console.debug("[hc-canvas/interaction] slot child resize: 父 outlet 找不到,percent 模式将退化到 px。",{instanceId:e,parentId:m,slot:v}),a.startOutletCanvasSize=null}return n.beginBatch(),{startTracking:!0}},cancelResize(){if("active"===a.status){const e="slot"===a.placement||"container"===a.placement?"resize-slot-child-cancel":"resize-cancel";n.endBatch(e)}m()}}}function yn(e,n){return{ok:!1,reason:e,message:n}}function In(e,n,t,o={}){const i=new Map;for(const n of e)i.set(n.instanceId,n);const a=i.get(n);if(!a)return yn("instance-not-exists",`实例 "${n}" 不存在,无法 reparent`);const r=null===t.parentId||void 0===t.parentId?void 0:t.parentId;if(r===n)return yn("self-parent",`parentId 不能等于自身 "${n}"`);if(void 0!==r){const e=i.get(r);if(!e)return yn("parent-not-exists",`目标 parentId "${r}" 不存在`);const t=new Set;let o=e.parentId;for(;void 0!==o&&!t.has(o);){if(t.add(o),o===n)return yn("cycle",`目标 parent "${r}" 是 "${n}" 的后代,会循环`);const e=i.get(o);o=null==e?void 0:e.parentId}}if(void 0===r)return{ok:!0};const c=o.resolveContract;if(!c)return{ok:!0};const s=i.get(r),d=c(s.componentVersionKey);if(!d)return{ok:!0};const l=d.slotsDecl??[];if(0===l.length)return yn("parent-not-layout",`父组件 "${s.componentId}" 不是布局组件(slotsDecl 空)`);const u=void 0===t.slot||""===t.slot||"default"===t.slot?te:t.slot,p=(f=u,l.find(e=>e.name===f));var f;if(!p)return yn("slot-not-exists",`slot "${u}" 不在父 "${s.componentId}" 的 slotsDecl`);if(p.accepts&&p.accepts.length>0&&!p.accepts.includes(a.componentId))return yn("accepts-violation",`slot "${u}" 不允许 componentId "${a.componentId}"(accepts: ${p.accepts.join(", ")})`);if(!0!==p.multiple){const t=e.filter(e=>e.instanceId!==n&&e.parentId===r&&oe(e)===u);if(t.length>0)return yn("slot-multiple-violated",`slot "${u}" 不允许多个子实例(已有 "${t[0].instanceId}")`)}if("number"==typeof p.maxChildren&&Number.isFinite(p.maxChildren)&&p.maxChildren>=1){const t=e.filter(e=>e.instanceId!==n&&e.parentId===r&&oe(e)===u);if(t.length+1>p.maxChildren)return yn("max-children-exceeded",`slot "${u}" 最多接受 ${p.maxChildren} 个子(已有 ${t.length} 个)`)}return{ok:!0}}function wn(e){const n=new Set(e.map(e=>e.instanceId)),t=new Map;for(const n of e)t.set(n.instanceId,bn(n));const o=[],i=new Map;e.forEach((e,a)=>{const r={inst:e,node:t.get(e.instanceId),originalIndex:a},c=e.parentId;if(c){if(!n.has(c))return console.warn(`[hc-canvas/instance-tree] instance "${e.instanceId}" parentId="${c}" 不存在,降级当顶层`),void o.push(r);i.has(c)||i.set(c,[]),i.get(c).push(r)}else o.push(r)});for(const[e,n]of i){const o=t.get(e);o&&(o.children=xn(n).map(e=>e.node))}return o.slice().sort((e,n)=>{const t=(n.inst.zIndex??0)-(e.inst.zIndex??0);return 0!==t?t:e.originalIndex-n.originalIndex}).map(e=>e.node)}function xn(e){const n=new Map;for(const t of e){const e=t.inst.slot??"default";let o=n.get(e);o||(o={firstIndex:t.originalIndex,entries:[]},n.set(e,o)),o.entries.push(t)}return Array.from(n.values()).sort((e,n)=>e.firstIndex-n.firstIndex).flatMap(e=>e.entries.slice().sort((e,n)=>e.originalIndex-n.originalIndex))}function bn(e){const n={instanceId:e.instanceId,componentId:e.componentId,componentVersionKey:e.componentVersionKey,kind:"visual",label:e.alias??e.instanceId};return void 0!==e.locked&&(n.locked=e.locked),void 0!==e.lockPosition&&(n.lockPosition=e.lockPosition),void 0!==e.lockSize&&(n.lockSize=e.lockSize),void 0!==e.hidden&&(n.hidden=e.hidden),n}function kn(e,n){for(const t of e){if(t.instanceId===n)return[t];if(t.children&&t.children.length>0){const e=kn(t.children,n);if(e.length>0)return[t,...e]}}return[]}function Sn(e,n){const t=new Map;for(const n of e)t.set(n.instanceId,n);const o=t.get(n);if(!o)return[];const i=[o];let a=o;const r=e.length;for(;a&&a.parentId;){if(i.length>r){console.warn(`[hc-canvas/instance-tree] breadcrumb for "${n}" exceeds depth ${r},疑似环,截断`);break}const e=t.get(a.parentId);if(!e)break;i.unshift(e),a=e}return i}function Bn(e,n,t){const o=n||void 0;return e.filter(e=>(e.parentId||void 0)===o&&e.slot===t).map((e,n)=>({inst:e,originalIndex:n})).sort((e,n)=>{const t=(n.inst.zIndex??0)-(e.inst.zIndex??0);return 0!==t?t:e.originalIndex-n.originalIndex}).map(e=>e.inst)}function Mn(e){if(0===e.length)return null;let n=1/0,t=1/0,o=-1/0,i=-1/0;for(const a of e)a.x<n&&(n=a.x),a.y<t&&(t=a.y),a.x+a.w>o&&(o=a.x+a.w),a.y+a.h>i&&(i=a.y+a.h);return{x:n,y:t,w:o-n,h:i-t}}function Tn(e){return Mn(e.map(e=>e.rect))}function Cn(e,n){if(0===n.length)return null;const t=new Set(n),o=[];for(const n of e)t.has(n.instanceId)&&o.push(n.rect);return Mn(o)}function zn(e,n,t){const o=(null==t?void 0:t.padding)??40,i=Math.max(1,n.w-2*o),a=Math.max(1,n.h-2*o),r=Math.max(1,e.w),c=Math.max(1,e.h);let s=Math.min(i/r,a/c);void 0!==(null==t?void 0:t.maxScale)&&(s=Math.min(s,t.maxScale)),void 0!==(null==t?void 0:t.minScale)&&(s=Math.max(s,t.minScale));const d=e.x+e.w/2,l=e.y+e.h/2;return{scale:s,panX:n.w/2-d*s,panY:n.h/2-l*s}}function Ln(e,n){const t=e.scale||1;return{x:-e.panX/t+0,y:-e.panY/t+0,w:n.w/t,h:n.h/t}}function En(e){const n=[];(e.metaKey||e.ctrlKey)&&n.push("mod"),e.shiftKey&&n.push("shift"),e.altKey&&n.push("alt");let t=e.key;return t="Meta"===t||"Control"===t?"mod":" "===t||"Space"===e.code?"space":(t.length,t.toLowerCase()),n[n.length-1]===t||n.push(t),n.join("+")}function Pn(e){if(!(e&&e instanceof HTMLElement))return!1;const n=e.tagName;return"INPUT"===n||"TEXTAREA"===n||"SELECT"===n||!!e.isContentEditable}function Dn(e,n){const t=En(n);for(const n of e.keys)if(Rn(n)===t)return!0;return!1}function Rn(e){return e.split("+").map(e=>e.trim().toLowerCase()).join("+")}function On(n,t){const o=Ge(n,t.recorder);function i(e){const o=t.getStageEl();if(!o)return console.warn("[hc-canvas/handle] clientToCanvasPoint called before stage mounted; falling back to viewport.toCanvasPoint(raw clientPt). 结果可能偏移。"),n.viewport.toCanvasPoint(e);const i=o.getBoundingClientRect();return n.viewport.toCanvasPoint({x:e.x-i.left,y:e.y-i.top})}function a(e,t){const o=n.document.getInstance(e);if(!o)return null;const i=(null==t?void 0:t.newInstanceId)??function(e){var n;const t="undefined"!=typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;return`${e}_${(null==(n=null==t?void 0:t.randomUUID)?void 0:n.call(t).replace(/-/g,"").slice(0,8))??Math.random().toString(36).slice(2,10)}`}(o.componentId);return n.dispatch({type:"duplicateInstance",payload:{instanceId:e,newInstanceId:i,...void 0!==(null==t?void 0:t.offset)?{offset:t.offset}:{}}}),n.document.getInstance(i)?i:null}function r(){return JSON.parse(JSON.stringify(n.document.document.layout))}function c(){return wn(n.document.document.instances)}function s(e,o){const i=n.document.getInstance(e);if(!i)return console.warn(`[hc-canvas/handle] ${o}: instance "${e}" 不存在`),!1;const a=t.getStageEl();if(!a)return console.warn(`[hc-canvas/handle] ${o}: stage 未挂载,跳过滚动(${e})`),!1;const r=un(e,a,n.viewport),c=r&&(r.w>0||r.h>0)?r:{x:i.rect.x,y:i.rect.y,w:i.rect.w,h:i.rect.h},s=a.getBoundingClientRect(),d=n.viewport.scale.value,l=s.width/2-(c.x+c.w/2)*d,u=s.height/2-(c.y+c.h/2)*d;return n.viewport.setPan(l,u),!0}const d=e.ref(null);let l=0;function u(e){var n;return"undefined"!=typeof globalThis&&(null==(n=globalThis.CSS)?void 0:n.escape)?globalThis.CSS.escape(e):e.replace(/["\\]/g,e=>`\\${e}`)}function p(){const e=t.getStageEl();if(!e)return null;const n=e.getBoundingClientRect();return{w:n.width,h:n.height}}function f(){return{scale:n.viewport.scale.value,panX:n.viewport.panX.value,panY:n.viewport.panY.value}}function h(){return Tn(n.document.document.instances)}function g(){return Cn(n.document.document.instances,n.selection.selectedIds.value)}function m(e,t){const o=p();if(!o)return void n.viewport.setScale(e);const i=f();let a;if(null==t?void 0:t.center)a=t.center;else{const e=Ln(i,o);a={x:e.x+e.w/2,y:e.y+e.h/2}}const r=a.x*i.scale+i.panX,c=a.y*i.scale+i.panY,s=r-a.x*e,d=c-a.y*e;n.viewport.setScale(e),n.viewport.setPan(s,d)}function v(e,t){m(n.viewport.scale.value+e,t)}function y(){n.viewport.resetView()}function I(e,t){const o=p();if(!o)return void console.warn("[hc-canvas/handle] scrollToRect: stage 未挂载,跳过");const i=zn(e,o,t);n.viewport.setScale(i.scale),n.viewport.setPan(i.panX,i.panY)}function w(e){const n=h();n&&I(n,e)}function x(e){const n=g();n&&I(n,e)}const b=Object.freeze([{id:"undo",keys:["mod+z"],command:"undo",when:"notEditingText"},{id:"redo",keys:["mod+shift+z","mod+y"],command:"redo",when:"notEditingText"},{id:"deleteSelection",keys:["delete","backspace"],command:"deleteSelection",when:"hasSelection"},{id:"duplicateSelection",keys:["mod+d"],command:"duplicateSelection",when:"hasSelection"},{id:"fitToSelectionOrContent",keys:["f"],command:"fitToSelectionOrContent",when:"notEditingText"},{id:"zoom100",keys:["1"],command:"zoom100",when:"notEditingText"},{id:"resetViewport",keys:["0"],command:"resetViewport",when:"notEditingText"},{id:"zoomIn",keys:["+","="],command:"zoomIn",when:"notEditingText"},{id:"zoomOut",keys:["-"],command:"zoomOut",when:"notEditingText"},{id:"nudgeLeft",keys:["arrowleft"],command:"nudgeSelection",payload:{dx:-1,dy:0},when:"hasSelection"},{id:"nudgeRight",keys:["arrowright"],command:"nudgeSelection",payload:{dx:1,dy:0},when:"hasSelection"},{id:"nudgeUp",keys:["arrowup"],command:"nudgeSelection",payload:{dx:0,dy:-1},when:"hasSelection"},{id:"nudgeDown",keys:["arrowdown"],command:"nudgeSelection",payload:{dx:0,dy:1},when:"hasSelection"},{id:"nudgeLeftLarge",keys:["shift+arrowleft"],command:"nudgeSelectionLarge",payload:{dx:-1,dy:0},when:"hasSelection"},{id:"nudgeRightLarge",keys:["shift+arrowright"],command:"nudgeSelectionLarge",payload:{dx:1,dy:0},when:"hasSelection"},{id:"nudgeUpLarge",keys:["shift+arrowup"],command:"nudgeSelectionLarge",payload:{dx:0,dy:-1},when:"hasSelection"},{id:"nudgeDownLarge",keys:["shift+arrowdown"],command:"nudgeSelectionLarge",payload:{dx:0,dy:1},when:"hasSelection"},{id:"cancelInteraction",keys:["escape"],command:"cancelInteraction",when:"notEditingText"}]);function k(){const e=n.selection.selectedIds.value;if(0===e.length)return!1;for(const t of e){const e=n.document.getInstance(t);if(e&&!0!==(e.lockPosition??e.locked))return!0}return!1}function S(e,t,o){const i=o?10:1,a=n.selection.selectedIds.value;if(0===a.length)return;const r=!n.isBatching.value;r&&n.beginBatch();try{for(const o of a){const a=n.document.getInstance(o);if(!a||!0===(a.lockPosition??a.locked))continue;const r=rn(n,o);cn(r)?n.dispatch({type:"moveInstance",payload:{instanceId:o,x:a.rect.x+e*i,y:a.rect.y+t*i}}):"undefined"!=typeof console&&"function"==typeof console.debug&&console.debug("[hc-canvas/handle] executeNudge: 拒绝 layout-managed 子 nudge",{instanceId:o,parentLayoutMode:r})}}finally{r&&n.endBatch(o?"arrow-move-large":"arrow-move")}}function B(e){const t=[...n.selection.selectedIds.value];if(0===t.length)return;const o=!n.isBatching.value;o&&n.beginBatch();try{for(const o of t)n.dispatch({type:"setInstanceLocked",payload:{instanceId:o,locked:e}})}finally{o&&n.endBatch(e?"lock-selection":"unlock-selection")}}function M(e){const t=n.selection.selectedIds.value;if(0===t.length)return;const o=n.document.document.instances;if(0===o.length)return;const i=o.map((e,n)=>({inst:e,origIdx:n})).sort((e,n)=>{const t=e.inst.zIndex??0,o=n.inst.zIndex??0;return t!==o?t-o:e.origIdx-n.origIdx}).map(e=>e.inst),a=new Set(t),r=[];for(let e=0;e<i.length;e++)a.has(i[e].instanceId)&&r.push(e);if(0===r.length)return;if(r.length===i.length)return;const c=r.map(e=>i[e]),s=i.filter(e=>!a.has(e.instanceId));let d;if("toFront"===e)d=[...s,...c];else if("toBack"===e)d=[...c,...s];else if("forward"===e){let e=r[r.length-1]+1;for(;e<i.length&&a.has(i[e].instanceId);)e++;if(e>=i.length)return;const n=i[e],t=s.indexOf(n);d=[...s.slice(0,t+1),...c,...s.slice(t+1)]}else{let e=r[0]-1;for(;e>=0&&a.has(i[e].instanceId);)e--;if(e<0)return;const n=i[e],t=s.indexOf(n);d=[...s.slice(0,t),...c,...s.slice(t)]}const l=[];for(let e=0;e<d.length;e++){const n=d[e];(n.zIndex??0)!==e&&l.push({id:n.instanceId,zIndex:e})}if(0===l.length)return;const u=!n.isBatching.value;u&&n.beginBatch();try{for(const e of l)n.dispatch({type:"updateInstance",payload:{instanceId:e.id,patch:{zIndex:e.zIndex}}})}finally{u&&n.endBatch(`z-order-${e}`)}}const T={undo:{execute:()=>o.undo(),canExecute:()=>o.canUndo.value},redo:{execute:()=>o.redo(),canExecute:()=>o.canRedo.value},deleteSelection:{execute:function(){const e=[...n.selection.selectedIds.value];if(0===e.length)return;const t=!n.isBatching.value;t&&n.beginBatch();try{for(const t of e)n.dispatch({type:"removeInstance",payload:{instanceId:t}})}finally{t&&n.endBatch("delete-selection")}},canExecute:()=>n.selection.selectedIds.value.length>0},duplicateSelection:{execute:function(){const e=[...n.selection.selectedIds.value];if(0===e.length)return;const t=[],o=!n.isBatching.value;o&&n.beginBatch();try{for(const n of e){const e=a(n);e&&t.push(e)}t.length>0&&n.dispatch({type:"selectAll",payload:{instanceIds:t}})}finally{o&&n.endBatch("duplicate-selection")}},canExecute:()=>n.selection.selectedIds.value.length>0},clearSelection:{execute:()=>n.dispatch({type:"clearSelection"}),canExecute:()=>n.selection.selectedIds.value.length>0},cancelInteraction:{execute:()=>n.dispatch({type:"clearSelection"}),canExecute:()=>!0},zoomIn:{execute:()=>v(.1),canExecute:()=>!0},zoomOut:{execute:()=>v(-.1),canExecute:()=>!0},zoom100:{execute:()=>m(1),canExecute:()=>!0},resetViewport:{execute:()=>y(),canExecute:()=>!0},fitToContent:{execute:()=>w(),canExecute:()=>null!==h()},fitToSelection:{execute:()=>x(),canExecute:()=>null!==g()},fitToSelectionOrContent:{execute:()=>{g()?x():w()},canExecute:()=>null!==g()||null!==h()},nudgeSelection:{execute:e=>{const n=e??{dx:0,dy:0};S(n.dx,n.dy,!1)},canExecute:k},nudgeSelectionLarge:{execute:e=>{const n=e??{dx:0,dy:0};S(n.dx,n.dy,!0)},canExecute:k},lockSelection:{execute:()=>B(!0),canExecute:()=>n.selection.selectedIds.value.length>0},unlockSelection:{execute:()=>B(!1),canExecute:()=>n.selection.selectedIds.value.length>0},bringForward:{execute:()=>M("forward"),canExecute:()=>n.selection.selectedIds.value.length>0},sendBackward:{execute:()=>M("backward"),canExecute:()=>n.selection.selectedIds.value.length>0},bringToFront:{execute:()=>M("toFront"),canExecute:()=>n.selection.selectedIds.value.length>0},sendToBack:{execute:()=>M("toBack"),canExecute:()=>n.selection.selectedIds.value.length>0},toggleGrid:{execute:function(){var e;const t=null==(e=n.document.document.layout.guides)?void 0:e.grid;D(!(null==t?void 0:t.visible))},canExecute:()=>!0},toggleRuler:{execute:function(){var e;const t=null==(e=n.document.document.layout.guides)?void 0:e.ruler;P(!(null==t?void 0:t.visible))},canExecute:()=>!0}};function C(e,t){const o=null===t?null:JSON.parse(JSON.stringify(t));n.dispatch({type:"setComponentOverride",payload:{instanceId:e,override:o}})}function z(e,t){const o=e??"notEditingText";return"always"===o||("notEditingText"===o?!Pn(t.target):"design"===o?!Pn(t.target)&&!1!==n.effectiveBehavior.value.draggable:"hasSelection"===o&&!Pn(t.target)&&n.selection.selectedIds.value.length>0)}function L(){return n.document.document.layout.guides??{}}function E(e){n.dispatch({type:"updateLayout",payload:{patch:{guides:e}}})}function P(e){const n=L();E({...n,ruler:{...n.ruler??{},visible:e}})}function D(e){const n=L();E({...n,grid:{...n.grid??{},visible:e}})}const R=e.computed(()=>{const e=n.selection.selectedIds.value;if(0===e.length)return[];const t=new Set(e);return n.document.document.instances.filter(e=>t.has(e.instanceId))}),O=n.selection.selectedIds,$=e.readonly(O),A=e.readonly(n.isBatching);let N=null,F=null;function j(e){var o,i,a,r,c,s,d,l,u;const p=e.parentId||void 0;if(void 0===p)return e;const f=(null==(i=null==(o=n.document.getInstance(p))?void 0:o.containerLayout)?void 0:i.mode)??"none";if("flex"!==f&&"split"!==f&&"grid"!==f)return e;const h=e.layoutBox,g=void 0!==h,m=void 0!==h,v=null==(a=t.resolveContract)?void 0:a.call(t,e.componentVersionKey),y=null==(c=null==(r=null==v?void 0:v.layoutDecl)?void 0:r.sizing)?void 0:c.defaultChildSize,I=e.rect??{w:240,h:60},w=h??{x:0,y:0,width:I.w,height:I.h,widthMode:"px",heightMode:"px"},x=e=>{if(void 0!==e)return"hug"===e?"auto":e},b=g?w.widthMode:x(null==(s=null==y?void 0:y.width)?void 0:s.mode)??"fill",k=m?w.heightMode:x(null==(d=null==y?void 0:y.height)?void 0:d.mode)??"fill",S=g||void 0===(null==(l=null==y?void 0:y.width)?void 0:l.value)?w.width:y.width.value,B=m||void 0===(null==(u=null==y?void 0:y.height)?void 0:u.value)?w.height:y.height.value;return{...e,layoutBox:{...w,x:0,y:0,width:S,height:B,widthMode:b,heightMode:k}}}return{dispatch:e=>function(e){if("addInstance"===e.type){const o=function(e){var n,o,i,a;if(void 0!==e.containerLayout)return e;const r=null==(n=t.resolveContract)?void 0:n.call(t,e.componentVersionKey);if(!r)return e;if(!("container"===(null==(o=r.layoutDecl)?void 0:o.role)||((null==(i=r.slotsDecl)?void 0:i.length)??0)>0))return e;const c=null==(a=r.layoutDecl)?void 0:a.defaultLayout;return void 0===c?e:{...e,containerLayout:JSON.parse(JSON.stringify(c))}}(e.payload.instance);return void n.dispatch({type:"addInstance",payload:{instance:j(o)}})}n.dispatch(e)}(e),beginBatch:()=>n.beginBatch(),endBatch:e=>n.endBatch(e),isBatching:A,getSnapshot:()=>JSON.parse(JSON.stringify(n.document.document)),selectedIds:$,selectedInstances:R,viewport:n.viewport,clientToCanvasPoint:i,getInstanceAtClientPoint:function(e){const o=t.getStageEl();if(!o)return null;const a=Ze(i(e),n.document.document.instances,e=>un(e,o,n.viewport));return a?n.document.getInstance(a)??null:null},getDropTarget:function(e,o,i){var a;const r=o??(null==(a=t.getStageEl)?void 0:a.call(t))??("undefined"!=typeof document&&"function"==typeof document.querySelectorAll?document:null);if(!r)return null;const c=void 0!==(null==i?void 0:i.excludeInstanceId),s=c?`[data-instance-id="${u(i.excludeInstanceId)}"]`:null;let d=s?r.querySelector(s):null;if(!d&&c&&r instanceof Element){const e=r.closest("[data-hc-canvas-designer]");e&&e!==r&&(d=e.querySelector(s))}let l=r.querySelectorAll("[data-hc-slot]");if(0===l.length&&c&&r instanceof Element){const e=r.closest("[data-hc-canvas-designer]");e&&e!==r&&(l=e.querySelectorAll("[data-hc-slot]"))}let p=null;for(const n of l){if(!(n instanceof HTMLElement))continue;if(d&&d.contains(n))continue;const t=n.getBoundingClientRect();if(0===t.width&&0===t.height)continue;if(e.x<t.left||e.x>t.right)continue;if(e.y<t.top||e.y>t.bottom)continue;let o=0,i=n;for(;i;)o++,i=i.parentElement;(!p||o>p.depth)&&(p={el:n,depth:o})}if(!p)return null;const f=p.el,h=f.closest("[data-instance-id]");if(!h)return null;const g=h.getAttribute("data-instance-id");return g&&n.document.getInstance(g)?{parentId:g,slot:f.getAttribute("data-hc-slot")||"default",outletEl:f}:null},duplicateInstance:a,undo:o.undo,redo:o.redo,canUndo:o.canUndo,canRedo:o.canRedo,undoStackSize:o.undoStackSize,redoStackSize:o.redoStackSize,clearHistory:o.clear,getLayoutConfig:r,updateCanvasSize:function(e){const t={...r().canvas,...e};n.dispatch({type:"updateLayout",payload:{patch:{canvas:t}}})},updateCanvasBackground:function(e){if(null===e)return void n.dispatch({type:"updateLayout",payload:{patch:{background:void 0}}});const t={...r().background??{},...e};n.dispatch({type:"updateLayout",payload:{patch:{background:t}}})},updateBehavior:function(e){const t={...r().behavior??{},...e};n.dispatch({type:"updateLayout",payload:{patch:{behavior:t}}})},setInteractionOptions:function(e){n.setInteractionOptions(e)},getEffectiveBehavior:function(){return{...n.effectiveBehavior.value}},setRootLayout:function(e){let t;if(null===e)t=null;else if("string"==typeof e)switch(e){case"free":t={mode:"free"};break;case"none":t={mode:"none"};break;case"split":t={mode:"split",direction:"horizontal",ratios:[.5,.5]};break;case"grid":t={mode:"grid",columns:[{mode:"fr",value:1},{mode:"fr",value:1}],rows:[{mode:"fr",value:1},{mode:"fr",value:1}]};break;case"flex":t={mode:"flex",direction:"row"};break;default:return void console.warn(`[hc-canvas/handle] setRootLayout: 未知 mode "${e}",忽略`)}else t=e;n.dispatch({type:"setRootLayout",payload:{rootLayout:t}})},getInstanceTree:c,getInstanceList:function(){return n.document.document.instances.map(e=>JSON.parse(JSON.stringify(e)))},getInstance:function(e){const t=n.document.getInstance(e);return t?JSON.parse(JSON.stringify(t)):null},getSelectedPath:function(){const e=n.selection.primaryId.value;return e?kn(c(),e):[]},getBreadcrumb:function(e){return Sn(n.document.document.instances,e).map(e=>JSON.parse(JSON.stringify(e)))},focusInstance:function(e){n.document.getInstance(e)?(n.dispatch({type:"select",payload:{instanceId:e}}),s(e,"focusInstance")):console.warn(`[hc-canvas/handle] focusInstance: instance "${e}" 不存在`)},scrollToInstance:function(e){s(e,"scrollToInstance")},moveInstanceInTree:function(e,o){var i,a,r;const c=In(n.document.document.instances,e,o,{resolveContract:t.resolveContract});if(!c.ok)return console.warn(`[hc-canvas/handle] moveInstanceInTree 守门拒绝(${c.reason}): ${c.message}`),void function(e,n,t,o){l++,d.value={instanceId:e,target:{...n},reason:t,message:o,token:l}}(e,o,c.reason,c.message??`reparent rejected: ${c.reason}`);const s=n.document.getInstance(e),u=null===o.parentId?void 0:o.parentId,p=(s.parentId||void 0)!==(u||void 0),f=s.slot!==o.slot,h={};if(p&&(h.parentId=u),f&&(h.slot=o.slot),p){const e=void 0===u?"canvas":"container";s.placement!==e&&(h.placement=e);const t=n.document.document.layout,o=void 0===u?(null==(i=null==t?void 0:t.rootLayout)?void 0:i.mode)??"free":(null==(r=null==(a=n.document.getInstance(u))?void 0:a.containerLayout)?void 0:r.mode)??"none";if(s.layoutBox)if("container"!==e||"flex"!==o&&"split"!==o&&"grid"!==o){if("canvas"===e){const e="fill"===s.layoutBox.widthMode?"px":s.layoutBox.widthMode,n="fill"===s.layoutBox.heightMode?"px":s.layoutBox.heightMode;e===s.layoutBox.widthMode&&n===s.layoutBox.heightMode||(h.layoutBox={...s.layoutBox,widthMode:e,heightMode:n})}}else h.layoutBox={...s.layoutBox,x:0,y:0,widthMode:"fill",heightMode:"fill"},h.rect={x:0,y:0,w:s.rect.w,h:s.rect.h};if("container"===e&&"grid"===o){const e=s.layoutItem??{};void 0!==e.row&&void 0!==e.column||(h.layoutItem={...e,row:e.row??1,column:e.column??1})}}const g=[];if(void 0!==o.index){const t=Bn(n.document.document.instances,u,o.slot).filter(n=>n.instanceId!==e),i=Math.max(0,Math.min(o.index,t.length));t.splice(i,0,s),t.forEach((e,n)=>{const o=t.length-1-n;(e.zIndex??0)!==o&&g.push({id:e.instanceId,zIndex:o})})}if(0===Object.keys(h).length&&0===g.length)return;const m=!n.isBatching.value;m&&n.beginBatch();try{Object.keys(h).length>0&&n.dispatch({type:"updateInstance",payload:{instanceId:e,patch:h}});for(const e of g)n.dispatch({type:"updateInstance",payload:{instanceId:e.id,patch:{zIndex:e.zIndex}}})}finally{m&&n.endBatch("moveInstanceInTree")}},canReparent:function(e,o){return In(n.document.document.instances,e,o,{resolveContract:t.resolveContract})},cannotReparentEvent:e.readonly(d),cannotDragLayoutManagedChildEvent:n.cannotDragLayoutManagedChildEvent,resolveAsset:function(e){return n.resolveAsset(e)},getViewportState:f,getVisibleBounds:function(){const e=p();return e?Ln(f(),e):{x:0,y:0,w:0,h:0}},getCanvasBounds:function(){const e=n.measuredCanvasSize.value;return{x:0,y:0,w:e.w,h:e.h}},getContentBounds:h,getSelectionBounds:g,getInstanceBounds:function(e){const t=n.document.getInstance(e);return t?{...t.rect}:null},panBy:function(e,t){n.viewport.setPan(n.viewport.panX.value+e,n.viewport.panY.value+t)},panTo:function(e,t){n.viewport.setPan(e,t)},zoomTo:m,zoomBy:v,zoomToPoint:function(e,o){const i=t.getStageEl();if(!i)return void console.warn("[hc-canvas/handle] zoomToPoint: stage 未挂载,跳过");const a=i.getBoundingClientRect(),r=o.x-a.left,c=o.y-a.top,s=f(),d=r-(r-s.panX)/s.scale*e,l=c-(c-s.panY)/s.scale*e;n.viewport.setScale(e),n.viewport.setPan(d,l)},resetViewport:y,fitToContent:w,fitToSelection:x,scrollToRect:I,toolMode:n.toolMode,getToolMode:function(){return n.toolMode.value},setToolMode:function(e){n.setToolMode(e)},setTemporaryToolMode:function(e){n.setTemporaryToolMode(e)},getDefaultShortcuts:function(){return[{id:"undo",keys:["mod+z"],command:"undo",when:"notEditingText"},{id:"redo",keys:["mod+shift+z","mod+y"],command:"redo",when:"notEditingText"},{id:"deleteSelection",keys:["delete","backspace"],command:"deleteSelection",when:"hasSelection"},{id:"duplicateSelection",keys:["mod+d"],command:"duplicateSelection",when:"hasSelection"},{id:"fitToSelectionOrContent",keys:["f"],command:"fitToSelectionOrContent",when:"notEditingText"},{id:"zoom100",keys:["1"],command:"zoom100",when:"notEditingText"},{id:"resetViewport",keys:["0"],command:"resetViewport",when:"notEditingText"},{id:"zoomIn",keys:["+","="],command:"zoomIn",when:"notEditingText"},{id:"zoomOut",keys:["-"],command:"zoomOut",when:"notEditingText"},{id:"nudgeLeft",keys:["arrowleft"],command:"nudgeSelection",payload:{dx:-1,dy:0},when:"hasSelection"},{id:"nudgeRight",keys:["arrowright"],command:"nudgeSelection",payload:{dx:1,dy:0},when:"hasSelection"},{id:"nudgeUp",keys:["arrowup"],command:"nudgeSelection",payload:{dx:0,dy:-1},when:"hasSelection"},{id:"nudgeDown",keys:["arrowdown"],command:"nudgeSelection",payload:{dx:0,dy:1},when:"hasSelection"},{id:"nudgeLeftLarge",keys:["shift+arrowleft"],command:"nudgeSelectionLarge",payload:{dx:-1,dy:0},when:"hasSelection"},{id:"nudgeRightLarge",keys:["shift+arrowright"],command:"nudgeSelectionLarge",payload:{dx:1,dy:0},when:"hasSelection"},{id:"nudgeUpLarge",keys:["shift+arrowup"],command:"nudgeSelectionLarge",payload:{dx:0,dy:-1},when:"hasSelection"},{id:"nudgeDownLarge",keys:["shift+arrowdown"],command:"nudgeSelectionLarge",payload:{dx:0,dy:1},when:"hasSelection"},{id:"cancelInteraction",keys:["escape"],command:"cancelInteraction",when:"notEditingText"}]},executeShortcut:function(e){for(const n of b){if(!Dn(n,e))continue;if(!z(n.when,e))continue;const t=T[n.command];return!!t&&!!t.canExecute()&&(t.execute(n.payload),!1!==n.preventDefault&&e.preventDefault(),!0)}return!1},executeCommand:function(e,n){const t=T[e];t?t.canExecute()&&t.execute(n):console.warn(`[hc-canvas/handle] executeCommand: 未知命令 "${e}"`)},canExecuteCommand:function(e){const n=T[e];return!!n&&n.canExecute()},getStaleComponentOverrides:function(){const e=n.document.document.componentOverrides??{},t=[];for(const o of n.document.document.instances){const n=e[o.instanceId];n&&n.baseVersionKey!==o.componentVersionKey&&t.push({instanceId:o.instanceId,baseVersionKey:n.baseVersionKey,currentVersionKey:o.componentVersionKey})}return t},setComponentOverride:C,discardComponentOverride:function(e){C(e,null)},getLayoutIssues:function(){return n.layoutIssues.value},setRulerVisible:P,setGridVisible:D,updateRulerConfig:function(e){const n=L();E({...n,ruler:{...n.ruler??{},...e}})},updateGridConfig:function(e){const n=L();E({...n,grid:{...n.grid??{},...e}})},addGuide:function(e){const n=L(),t=n.items??[],o=e.id??function(){var e;const n="undefined"!=typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;return`g_${(null==(e=null==n?void 0:n.randomUUID)?void 0:e.call(n).replace(/-/g,"").slice(0,8))??Math.random().toString(36).slice(2,10)}`}();if(t.some(e=>e.id===o))return console.warn(`[hc-canvas/handle] addGuide: id "${o}" 已存在,忽略`),o;const i={id:o,axis:e.axis,position:e.position};return void 0!==e.locked&&(i.locked=e.locked),void 0!==e.label&&(i.label=e.label),E({...n,items:[...t,i]}),o},removeGuide:function(e){const n=L(),t=n.items??[];t.some(n=>n.id===e)&&E({...n,items:t.filter(n=>n.id!==e)})},updateGuide:function(e,n){const t=L(),o=t.items??[],i=o.findIndex(n=>n.id===e);if(i<0)return void console.warn(`[hc-canvas/handle] updateGuide: id "${e}" 不存在,忽略`);const{id:a,...r}=n,c={...o[i],...r},s=[...o];s[i]=c,E({...t,items:s})},getGuides:function(){return(L().items??[]).map(e=>({...e}))},clearGuides:function(){const e=L();e.items&&0!==e.items.length&&E({...e,items:[]})},getMouseCanvasPoint:function(){const e=n.mouseCanvasPoint.value;return e?{x:e.x,y:e.y}:null},getInstanceSize:function(e){const t=n.document.getInstance(e);if(t&&void 0!==t.size)return JSON.parse(JSON.stringify(t.size))},updateInstanceSize:function(e,t){n.dispatch({type:"setInstanceSize",payload:{instanceId:e,size:t}})},getContainerLayout:function(e){const t=n.document.getInstance(e);return t&&void 0!==t.containerLayout?JSON.parse(JSON.stringify(t.containerLayout)):null},updateContainerLayout:function(e,t){n.dispatch({type:"setContainerLayout",payload:{instanceId:e,containerLayout:t}})},getInstanceOutletRect:function(e,n){if("undefined"==typeof document||"function"!=typeof document.querySelector)return null;const t=n??"default",o=""===t?"default":t,i=`[data-instance-id="${u(e)}"]`,a=`[data-hc-slot="${u(o)}"]`,r=document.querySelector(`${i} ${a}`);return r&&r instanceof HTMLElement?r.getBoundingClientRect():null},getLayoutBox:function(e){const t=n.document.getInstance(e);if(t&&void 0!==t.layoutBox)return JSON.parse(JSON.stringify(t.layoutBox))},updateLayoutBox:function(e,t){n.dispatch({type:"updateLayoutBox",payload:{instanceId:e,patch:t}})},getLayoutItem:function(e){const t=n.document.getInstance(e);if(t&&void 0!==t.layoutItem)return JSON.parse(JSON.stringify(t.layoutItem))},updateLayoutItem:function(e,t){n.dispatch({type:"updateLayoutItem",payload:{instanceId:e,patch:t}})},getRotation:function(e){const t=n.document.getInstance(e);if(!t)return 0;const o=t.rotation;return"number"==typeof o&&Number.isFinite(o)?o:0},updateRotation:function(e,t){n.dispatch({type:"updateRotation",payload:{instanceId:e,value:t}})},setBindingMode:function(e){null==N||N.setMode(e)},getBindingMode:function(){return(null==N?void 0:N.getMode())??"off"},testBinding:function(e,n){return(null==N?void 0:N.testBinding(e,n))??[]},on:function(e,n){return N?N.on(e,n):()=>{}},attachBindingDelegate:function(e,n){N=e,null===e?F=null:arguments.length>=2&&(F=n??null)},invalidateDataSource:function(e){null==F||F.invalidate(e)},getDataSourceSnapshot:function(){return(null==F?void 0:F.getSnapshot())??{entries:[]}},startTracing:function(e){null==N||N.startTracing(e)},stopTracing:function(){return(null==N?void 0:N.stopTracing())??[]},getTraceBuffer:function(){return(null==N?void 0:N.getTraceBuffer())??[]},dispose:o.dispose}}const $n=Symbol("hc:canvas:reparent-bridge");function An(e){return"preview"===e||"runtime"===e?"runtime":"off"}const Nn=(e=>{const n=e.__vccOpts||e;for(const[e,t]of[["__scopeId","data-v-825e0ee8"]])n[e]=t;return n})(e.defineComponent({__name:"CanvasStage",setup(n){const t=ne(),o=e.ref(null);let i=null;const a=e.computed(()=>{const{scale:e,panX:n,panY:o}=t.viewport.state;return`translate(${n}px, ${o}px) scale(${e})`});function r(){const e=o.value;if(!e)return;const n=e.getBoundingClientRect();t.setMeasuredStageSize({w:n.width,h:n.height})}return e.onMounted(()=>{e.nextTick(r),"undefined"!=typeof ResizeObserver&&o.value&&(i=new ResizeObserver(r),i.observe(o.value)),window.addEventListener("resize",r)}),e.onBeforeUnmount(()=>{null==i||i.disconnect(),i=null,window.removeEventListener("resize",r)}),(n,t)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"stageEl",ref:o,class:"hc-canvas-stage","data-hc-stage":""},[e.createElementVNode("div",{class:"hc-canvas-stage__world","data-hc-stage-world":"",style:e.normalizeStyle({transform:a.value,transformOrigin:"0 0"})},[e.renderSlot(n.$slots,"default",{},void 0,!0)],4)],512))}})),Fn=["data-mode"],jn=e.defineComponent({__name:"RuntimeLayer",props:{componentSourceMap:{},mode:{default:"design"},schedulerOptions:{},canvasId:{}},setup(n){const t=ne(),o=e.computed(()=>t.document.document);return(i,a)=>(e.openBlock(),e.createElementBlock("div",{class:"hc-runtime-layer","data-hc-runtime-layer":"","data-mode":n.mode,style:e.normalizeStyle({position:"absolute",top:0,left:0,pointerEvents:e.unref(t).effectiveBehavior.value.selectable?"none":"auto"})},[e.createVNode(Ve,{document:o.value,"component-source-map":n.componentSourceMap,"scheduler-options":n.schedulerOptions,"canvas-id":n.canvasId},null,8,["document","component-source-map","scheduler-options","canvas-id"])],12,Fn))}});function Vn(e,n,t,o=0){if(!n||n.length<2)return[];if(e.w<=0||e.h<=0)return[];const i=n.map(e=>"number"==typeof e&&Number.isFinite(e)&&e>0?e:0),a=i.reduce((e,n)=>e+n,0);if(a<=0)return[];const r=i.length-1,c=Math.max(0,o)*r,s="horizontal"===t?e.w:e.h,d=Math.max(0,s-c);if(d<=0)return[];const l=o>0?o:8,u=[];let p=0;for(let n=0;n<r;n++){p+=i[n]/a*d;const r=p+n*o+o/2;let c;c="horizontal"===t?{x:e.x+r-l/2,y:e.y,w:l,h:e.h}:{x:e.x,y:e.y+r-l/2,w:e.w,h:l},u.push({index:n,rect:c,direction:t})}return u}function qn(e,n,t,o,i=0){if(!e||n<0||n>=e.length-1)return e.slice();const a=e.map(e=>"number"==typeof e&&Number.isFinite(e)&&e>0?e:0),r=a[n],c=a[n+1],s=r+c;if(s<=0)return a;const d=a.length-1,l=Math.max(0,i)*d,u=Math.max(0,o-l);if(u<=0)return a;const p=a.reduce((e,n)=>e+n,0);if(p<=0)return a;const f=t/u*p,h=.05*p;let g=r+f,m=c-f;g<h&&(g=h,m=s-h),m<h&&(m=h,g=s-h);const v=a.slice();return v[n]=g,v[n+1]=m,v}function _n(n){const t=e.reactive({status:"idle",parentId:null,dividerIndex:null,startRatios:null,childIds:null,parentAxisPx:0,startPt:null,direction:null,gap:0}),o=e.computed(()=>"active"===t.status);function i(){t.status="idle",t.parentId=null,t.dividerIndex=null,t.startRatios=null,t.childIds=null,t.parentAxisPx=0,t.startPt=null,t.direction=null,t.gap=0}return{drag:t,isDragging:o,handleSplitDividerStart:function(e){if(!e.parentId)return{startTracking:!1};if(e.dividerIndex<0)return{startTracking:!1};if(!e.startRatios||e.startRatios.length<2)return{startTracking:!1};if(!e.childIds||e.childIds.length<=e.dividerIndex+1||!e.childIds[e.dividerIndex]||!e.childIds[e.dividerIndex+1])return{startTracking:!1};const o=n.document.getInstance(e.parentId);return o&&o.containerLayout&&"split"===o.containerLayout.mode?(t.status="active",t.parentId=e.parentId,t.dividerIndex=e.dividerIndex,t.startRatios=e.startRatios.slice(),t.childIds=e.childIds.slice(),t.parentAxisPx=e.parentAxisPx,t.startPt={...e.canvasPt},t.direction=e.direction,t.gap=e.gap,n.beginBatch(),{startTracking:!0}):{startTracking:!1}},handleSplitDividerMove:function(e){var o,i;if("active"!==t.status)return;if(!(t.startPt&&t.startRatios&&t.childIds&&t.direction&&null!==t.dividerIndex))return;const a=n.document.getInstance(t.parentId);if(!a||!a.containerLayout||"split"!==a.containerLayout.mode)return;const r="horizontal"===t.direction?e.x-t.startPt.x:e.y-t.startPt.y,c=qn(t.startRatios,t.dividerIndex,r,t.parentAxisPx,t.gap),s=t.dividerIndex,d=t.childIds[s],l=t.childIds[s+1];if(!d||!l)return;const u=c[s],p=c[s+1],f=n.document.getInstance(d),h=n.document.getInstance(l),g=null==(o=null==f?void 0:f.layoutItem)?void 0:o.ratio,m=null==(i=null==h?void 0:h.layoutItem)?void 0:i.ratio;g===u&&m===p||(n.dispatch({type:"updateLayoutItem",payload:{instanceId:d,patch:{ratio:u}}}),n.dispatch({type:"updateLayoutItem",payload:{instanceId:l,patch:{ratio:p}}}))},handleSplitDividerEnd:function(){"active"===t.status&&(n.endBatch("split-divider-drag"),i())},cancelSplitDividerDrag:function(){"active"===t.status&&n.endBatch("split-divider-cancel"),i()}}}function Kn(e){return!0===(e.lockPosition??e.locked)}function Jn(e){return!0===(e.lockSize??e.locked)}function Un(e){return Kn(e)||Jn(e)}const Xn=["data-mode"],Yn=["data-selection-box","data-locked","data-placement"],Hn=["data-lock-badge"],Gn=["data-resize-handle","data-resize-instance","onPointerdown"],Wn=["data-hc-divider-direction","data-hc-divider-index","data-hc-parent-id","data-hc-divider-dragging","onPointerdown"],Qn=["data-axis","data-kind"],Zn=["data-hc-reparent-state"],et=["data-hc-reparent-ghost-reason"],nt={key:0,"data-hc-reparent-ghost-reason-chip":"",style:{flex:"none",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",fontSize:"10px",lineHeight:"14px",padding:"0 4px",borderRadius:"2px",background:"rgba(0, 0, 0, 0.25)",color:"#fff",whiteSpace:"nowrap"}},tt=e.defineComponent({__name:"InteractionLayer",props:{mode:{default:"design"}},emits:["cannot-drag-slot-child","cannot-drag-layout-managed-child"],setup(n,{emit:t}){const o=t,i=ne(),a=vn(i,{getRoot:()=>$(),getDomBox:e=>{const n=un(e,$(),i.viewport);return n?0===n.w&&0===n.h?null:n:null}}),r=_n(i),c=e.inject($n,null);e.watch(()=>a.cannotDragSlotChildEvent.value,e=>{e&&o("cannot-drag-slot-child",{instanceId:e.instanceId,parentId:e.parentId})},{flush:"sync"}),e.watch(()=>a.cannotDragLayoutManagedChildEvent.value,e=>{e&&o("cannot-drag-layout-managed-child",{instanceId:e.instanceId,parentId:e.parentId,parentLayoutMode:e.parentLayoutMode})},{flush:"sync"});const s=e.ref(null);let d=null;const l=e.computed(()=>{const e=new Set(i.selection.selectedIds.value);return i.document.document.instances.filter(n=>e.has(n.instanceId)&&!n.hidden)}),u=e.computed(()=>i.measuredCanvasSize.value),p=e.shallowRef({});function f(){const e=$(),n={};for(const t of l.value)n[t.instanceId]=un(t.instanceId,e,i.viewport);p.value=n}let h=null;function g(){"undefined"!=typeof requestAnimationFrame?null===h&&(h=requestAnimationFrame(()=>{h=null,f()})):f()}let m=null;function v(){m=null,f(),(a.isResizing.value||a.isDragging.value||r.isDragging.value)&&(m=requestAnimationFrame(v))}function I(e){const n=p.value[e.instanceId];if(n)return n;const t=un(e.instanceId,$(),i.viewport);if(t&&(t.w>0||t.h>0))return t;const o=e.layoutBox;return o?{x:o.x,y:o.y,w:o.width,h:o.height}:{x:e.rect.x,y:e.rect.y,w:e.rect.w,h:e.rect.h}}e.watch(()=>i.selection.selectedIds.value,()=>{g()},{flush:"post",deep:!0}),e.watch(()=>i.viewport.scale.value,()=>g()),e.watch(()=>[i.viewport.panX.value,i.viewport.panY.value],()=>g()),e.watch(()=>l.value.map(e=>{const n=e.layoutBox;return n?`${n.x}|${n.y}|${n.width}|${n.height}|${n.widthMode}|${n.heightMode}`:""}),()=>g(),{flush:"post",deep:!0}),e.watch(()=>a.isResizing.value,e=>{e&&null===m&&(m=requestAnimationFrame(v))}),e.watch(()=>a.isDragging.value,e=>{e&&null===m&&(m=requestAnimationFrame(v))}),e.watch(()=>r.isDragging.value,e=>{e&&null===m&&(m=requestAnimationFrame(v))}),e.onMounted(()=>{g()});const w=e.computed(()=>l.value.map(e=>({instance:e,box:I(e)}))),x=e.computed(()=>{var e,n;if(!i.effectiveBehavior.value.resizable)return[];const t=[];for(const o of w.value){const a=o.instance;if(!0===(a.lockSize??a.locked))continue;if(!o.box)continue;const r=rn(i,a.instanceId),{x:c,y:s,w:d,h:l}=o.box,u=[{handle:"nw",cx:c,cy:s,cursor:"nwse-resize"},{handle:"n",cx:c+d/2,cy:s,cursor:"ns-resize"},{handle:"ne",cx:c+d,cy:s,cursor:"nesw-resize"},{handle:"e",cx:c+d,cy:s+l/2,cursor:"ew-resize"},{handle:"se",cx:c+d,cy:s+l,cursor:"nwse-resize"},{handle:"s",cx:c+d/2,cy:s+l,cursor:"ns-resize"},{handle:"sw",cx:c,cy:s+l,cursor:"nesw-resize"},{handle:"w",cx:c,cy:s+l/2,cursor:"ew-resize"}],p=null==(e=a.layoutBox)?void 0:e.widthMode,f=null==(n=a.layoutBox)?void 0:n.heightMode,h=u.filter(e=>ln(r,e.handle,p,f));for(const e of h)t.push({instanceId:a.instanceId,handle:e.handle,left:e.cx-4,top:e.cy-4,cursor:e.cursor})}return t});function b(e,n,t){return"percent"===n?`${Math.round(t)}%`:"fill"===n?"fill":"auto"===n?"auto":String(Math.round(e))}const k=e.computed(()=>{if(!a.isResizing.value)return null;const e=a.resize.instanceId;if(!e)return null;const n=i.document.getInstance(e);if(!n)return null;const t=I(n);if(!t)return null;const o=n.layoutBox,r=b(t.w,null==o?void 0:o.widthMode,(null==o?void 0:o.width)??t.w),c=b(t.h,null==o?void 0:o.heightMode,(null==o?void 0:o.height)??t.h);return{x:t.x,y:t.y,w:t.w,h:t.h,wText:r,hText:c}}),S={nw:"nwse-resize",se:"nwse-resize",ne:"nesw-resize",sw:"nesw-resize",n:"ns-resize",s:"ns-resize",w:"ew-resize",e:"ew-resize"};function B(e){var n;const t=[],o=[];for(const a of i.document.document.instances)a.parentId===e&&void 0===a.slot&&(t.push(a.instanceId),o.push(null==(n=a.layoutItem)?void 0:n.ratio));return{ids:t,ratios:o}}const M=e.computed(()=>{var e,n;const t=new Set;for(const o of l.value)if("split"===(null==(e=o.containerLayout)?void 0:e.mode)&&t.add(o.instanceId),o.parentId){const e=i.document.getInstance(o.parentId);"split"===(null==(n=null==e?void 0:e.containerLayout)?void 0:n.mode)&&t.add(e.instanceId)}if(0===t.size)return[];const o=[];for(const e of t){const n=i.document.getInstance(e);if(!n)continue;const t=n.containerLayout;if(!t||"split"!==t.mode)continue;const a=E(e)??I(n);if(!a)continue;const r=t,c=r.direction,s=r.gap??0,{ids:d,ratios:l}=B(e),u=y(r.ratios??[],l),p=Vn(a,u,c,s);0!==p.length&&o.push({parentId:e,direction:c,gap:s,effectiveRatios:u,childIds:d,parentBox:a,dividers:p})}return o}),T=e.computed(()=>a.isResizing.value&&a.resize.handle?S[a.resize.handle]:r.isDragging.value?"horizontal"===r.drag.direction?"ew-resize":"ns-resize":a.isDragging.value?"grabbing":"hand"===i.toolMode.value?F?"grabbing":"grab":"marquee"===i.toolMode.value?"crosshair":"default"),C=e.shallowRef(null);function z(){if(!c)return!1;if(!a.isDragging.value)return!1;if(1!==a.drag.startRects.size)return!1;const e=Array.from(a.drag.startRects.keys())[0],n=i.document.getInstance(e);return!(!n||void 0!==n.placement&&"canvas"!==n.placement&&"absolute"!==n.placement||!0===(n.lockPosition??n.locked)||n.hidden)}function L(e){const n=$();if(!n)return null;const t=e.getBoundingClientRect(),o=n.getBoundingClientRect(),a=i.viewport.toCanvasPoint({x:t.left-o.left,y:t.top-o.top}),r=i.viewport.toCanvasPoint({x:t.right-o.left,y:t.bottom-o.top});return{x:a.x,y:a.y,w:Math.max(0,r.x-a.x),h:Math.max(0,r.y-a.y)}}function E(e){var n;const t=$();if(!t)return null;const o=tn(t,`[data-instance-id="${("undefined"!=typeof globalThis&&(null==(n=globalThis.CSS)?void 0:n.escape)?globalThis.CSS.escape:e=>e.replace(/["\\]/g,e=>`\\${e}`))(e)}"] [data-hc-slot="default"]`);return o&&o instanceof HTMLElement?L(o):null}let P=null,D=null;function R(e){if(!z()||!c)return void(null!==C.value&&(C.value=null));const n=Array.from(a.drag.startRects.keys())[0],t=c.getDropTarget(e,{excludeInstanceId:n});if(!t)return void(null!==C.value&&(C.value=null));const o=i.document.getInstance(n);if(o&&o.parentId===t.parentId&&(o.slot??"default")===(t.slot||"default"))return void(null!==C.value&&(C.value=null));const r=L(t.outletEl);if(!r)return void(null!==C.value&&(C.value=null));const s={parentId:t.parentId,slot:t.slot},d=c.canReparent(n,s);C.value={rect:r,target:t,result:d}}const O=e.computed(()=>C.value);function $(){return d||(s.value?(d=s.value.closest("[data-hc-stage]"),d):null)}function A(e){const n=$();if(!n)return;const t=gn({x:e.clientX,y:e.clientY},n,i.viewport);i.setMouseCanvasPoint(t)}function N(){i.setMouseCanvasPoint(null)}let F=null;function j(e){if(0!==e.button)return;const n=$();if(!n)return;if("hand"===i.toolMode.value)return F={clientX:e.clientX,clientY:e.clientY,panX:i.viewport.panX.value,panY:i.viewport.panY.value},window.addEventListener("pointermove",V),window.addEventListener("pointerup",q),void e.preventDefault();const t=gn({x:e.clientX,y:e.clientY},n,i.viewport),{startTracking:o}=a.handlePointerDown(t,{shift:e.shiftKey,ctrl:e.ctrlKey,meta:e.metaKey});o&&(_(),e.preventDefault())}function V(e){if(!F)return;const n=e.clientX-F.clientX,t=e.clientY-F.clientY;i.viewport.setPan(F.panX+n,F.panY+t)}function q(){F=null,window.removeEventListener("pointermove",V),window.removeEventListener("pointerup",q)}function _(){window.addEventListener("pointermove",K),window.addEventListener("pointerup",J),window.addEventListener("keydown",U)}function K(e){const n=$();if(!n)return;const t=gn({x:e.clientX,y:e.clientY},n,i.viewport);var o;a.handlePointerMove(t),r.handleSplitDividerMove(t),r.isDragging.value&&g(),o={x:e.clientX,y:e.clientY},P=o,"undefined"!=typeof requestAnimationFrame?null===D&&(D=requestAnimationFrame(()=>{D=null,P&&R(P)})):R(o)}function J(e){if(r.isDragging.value)return r.handleSplitDividerEnd(),void X();e&&c&&z()&&R({x:e.clientX,y:e.clientY}),null!==D&&"undefined"!=typeof cancelAnimationFrame&&(cancelAnimationFrame(D),D=null);const n=C.value;if(n&&c){const e=Array.from(a.drag.startRects.keys())[0];return n.result.ok&&e?(a.cancelDrag(),c.moveInstanceInTree(e,{parentId:n.target.parentId,slot:n.target.slot})):a.cancelDrag(),C.value=null,void X()}a.handlePointerUp(),X()}function U(e){"Escape"===e.key&&(a.cancelResize(),a.cancelDrag(),a.cancelMarquee(),r.cancelSplitDividerDrag(),C.value=null,null!==D&&"undefined"!=typeof cancelAnimationFrame&&(cancelAnimationFrame(D),D=null),q(),X())}function X(){window.removeEventListener("pointermove",K),window.removeEventListener("pointerup",J),window.removeEventListener("keydown",U)}return e.onBeforeUnmount(()=>{a.cancelResize(),a.cancelDrag(),a.cancelMarquee(),r.cancelSplitDividerDrag(),C.value=null,X(),q(),null!==h&&"undefined"!=typeof cancelAnimationFrame&&(cancelAnimationFrame(h),h=null),null!==m&&"undefined"!=typeof cancelAnimationFrame&&(cancelAnimationFrame(m),m=null),null!==D&&"undefined"!=typeof cancelAnimationFrame&&(cancelAnimationFrame(D),D=null),P=null}),(t,o)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"layerEl",ref:s,class:"hc-interaction-layer","data-hc-interaction-layer":"","data-mode":n.mode,style:e.normalizeStyle({position:"absolute",top:0,left:0,width:u.value.w+"px",height:u.value.h+"px",pointerEvents:e.unref(i).effectiveBehavior.value.selectable?"auto":"none",cursor:T.value,zIndex:9999}),onPointerdown:j,onPointermove:A,onPointerleave:N},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(w.value,n=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:"sel-"+n.instance.instanceId},[n.box?(e.openBlock(),e.createElementBlock("div",{key:0,class:"hc-selection-box","data-selection-box":n.instance.instanceId,"data-locked":e.unref(Un)(n.instance)?"true":"false","data-placement":n.instance.placement??"absolute",style:e.normalizeStyle({position:"absolute",left:n.box.x+"px",top:n.box.y+"px",width:n.box.w+"px",height:n.box.h+"px",border:"2px solid "+(e.unref(Un)(n.instance)?"#9ca3af":"#3b82f6"),boxSizing:"border-box",pointerEvents:"none",boxShadow:"0 0 0 1px rgba(59, 130, 246, 0.2)"})},null,12,Yn)):e.createCommentVNode("",!0)],64))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(w.value.filter(n=>e.unref(Un)(n.instance)),n=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:"lock-"+n.instance.instanceId},[n.box?(e.openBlock(),e.createElementBlock("div",{key:0,class:"hc-lock-badge","data-lock-badge":n.instance.instanceId,style:e.normalizeStyle({position:"absolute",left:n.box.x+n.box.w-18+"px",top:n.box.y+2+"px",width:"16px",height:"16px",background:"#9ca3af",color:"#fff",fontSize:"11px",lineHeight:"16px",textAlign:"center",borderRadius:"3px",pointerEvents:"none",userSelect:"none"})},"🔒",12,Hn)):e.createCommentVNode("",!0)],64))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(x.value,n=>(e.openBlock(),e.createElementBlock("div",{key:"rh-"+n.instanceId+"-"+n.handle,class:"hc-resize-handle","data-resize-handle":n.handle,"data-resize-instance":n.instanceId,style:e.normalizeStyle({position:"absolute",left:n.left+"px",top:n.top+"px",width:"8px",height:"8px",background:"#fff",border:"1px solid #3b82f6",boxSizing:"border-box",cursor:n.cursor,pointerEvents:"auto",zIndex:2}),onPointerdown:e=>function(e,n,t){if(0!==e.button)return;e.stopPropagation();const o=$();if(!o)return;const r=gn({x:e.clientX,y:e.clientY},o,i.viewport),{startTracking:c}=a.handleResizeStart(n,t,r);c&&(_(),e.preventDefault())}(e,n.instanceId,n.handle)},null,44,Gn))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(M.value,n=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:"sd-parent-"+n.parentId},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.dividers,o=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:"sd-"+n.parentId+"-"+o.index},[t.$slots["split-divider"]?e.renderSlot(t.$slots,"split-divider",{key:0,state:{parentId:n.parentId,dividerIndex:o.index,direction:o.direction,rect:o.rect,isDragging:e.unref(r).isDragging.value&&e.unref(r).drag.parentId===n.parentId&&e.unref(r).drag.dividerIndex===o.index}}):(e.openBlock(),e.createElementBlock("div",{key:1,class:"hc-split-divider","data-hc-divider-direction":o.direction,"data-hc-divider-index":o.index,"data-hc-parent-id":n.parentId,"data-hc-divider-dragging":e.unref(r).isDragging.value&&e.unref(r).drag.parentId===n.parentId&&e.unref(r).drag.dividerIndex===o.index?"true":"false",style:e.normalizeStyle({position:"absolute",left:o.rect.x+"px",top:o.rect.y+"px",width:o.rect.w+"px",height:o.rect.h+"px",background:e.unref(r).isDragging.value&&e.unref(r).drag.parentId===n.parentId&&e.unref(r).drag.dividerIndex===o.index?"rgba(59, 130, 246, 0.6)":"rgba(59, 130, 246, 0.18)",cursor:"horizontal"===o.direction?"ew-resize":"ns-resize",pointerEvents:"auto",boxSizing:"border-box",zIndex:3}),onPointerdown:e=>function(e,n,t){if(0!==e.button)return;e.stopPropagation();const o=$();if(!o)return;const a=i.document.getInstance(n);if(!a)return;const c=a.containerLayout;if(!c||"split"!==c.mode)return;const s=c,d=E(n)??I(a);if(!d)return;const l="horizontal"===s.direction?d.w:d.h,{ids:u,ratios:p}=B(n),f=y(s.ratios??[],p),h=gn({x:e.clientX,y:e.clientY},o,i.viewport),{startTracking:g}=r.handleSplitDividerStart({parentId:n,dividerIndex:t,startRatios:f,childIds:u,parentAxisPx:l,direction:s.direction,gap:s.gap??0,canvasPt:h});g&&(_(),e.preventDefault())}(e,n.parentId,o.index)},null,44,Wn))],64))),128))],64))),128)),k.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"hc-resize-badge","data-resize-badge":"",style:e.normalizeStyle({position:"absolute",left:k.value.x+"px",top:k.value.y-22+"px",padding:"2px 6px",background:"#3b82f6",color:"#fff",fontSize:"11px",lineHeight:"14px",borderRadius:"3px",pointerEvents:"none",userSelect:"none",whiteSpace:"nowrap",fontFamily:"ui-monospace, SFMono-Regular, monospace"})},e.toDisplayString(k.value.wText)+" × "+e.toDisplayString(k.value.hText),5)):e.createCommentVNode("",!0),e.unref(a).marqueeRect.value?(e.openBlock(),e.createElementBlock("div",{key:1,class:"hc-marquee-box","data-marquee-box":"",style:e.normalizeStyle({position:"absolute",left:e.unref(a).marqueeRect.value.x+"px",top:e.unref(a).marqueeRect.value.y+"px",width:e.unref(a).marqueeRect.value.w+"px",height:e.unref(a).marqueeRect.value.h+"px",border:"1px dashed #3b82f6",background:"rgba(59, 130, 246, 0.08)",pointerEvents:"none",boxSizing:"border-box"})},null,4)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(a).snapLines.value,(n,t)=>(e.openBlock(),e.createElementBlock("div",{key:"snap-"+t,class:"hc-snap-line","data-snap-line":"","data-axis":n.axis,"data-kind":n.kind,style:e.normalizeStyle("x"===n.axis?{position:"absolute",left:n.pos+"px",top:n.from+"px",width:"0px",height:n.to-n.from+"px",borderLeft:"1px dashed #ec4899",pointerEvents:"none"}:{position:"absolute",left:n.from+"px",top:n.pos+"px",width:n.to-n.from+"px",height:"0px",borderTop:"1px dashed #ec4899",pointerEvents:"none"})},null,12,Qn))),128)),O.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:2},[t.$slots["reparent-ghost"]?e.renderSlot(t.$slots,"reparent-ghost",{key:0,state:O.value}):(e.openBlock(),e.createElementBlock("div",{key:1,class:"hc-reparent-ghost","data-hc-reparent-ghost":"","data-hc-reparent-state":O.value.result.ok?"legal":"illegal",style:e.normalizeStyle({position:"absolute",left:O.value.rect.x+"px",top:O.value.rect.y+"px",width:O.value.rect.w+"px",height:O.value.rect.h+"px",pointerEvents:"none",boxSizing:"border-box",border:"2px solid "+(O.value.result.ok?"#22c55e":"#ef4444"),background:O.value.result.ok?"rgba(34, 197, 94, 0.12)":"rgba(239, 68, 68, 0.12)"})},[!O.value.result.ok&&O.value.result.message?(e.openBlock(),e.createElementBlock("div",{key:0,class:"hc-reparent-ghost__message","data-hc-reparent-ghost-message":"","data-hc-reparent-ghost-reason":O.value.result.reason||"",style:{position:"absolute",left:"0",top:"100%",marginTop:"4px",maxWidth:"280px",padding:"3px 6px",background:"#ef4444",color:"#fff",fontSize:"11px",lineHeight:"16px",borderRadius:"3px",whiteSpace:"normal",wordBreak:"break-all",pointerEvents:"none",display:"flex",flexWrap:"wrap",alignItems:"baseline",gap:"4px"}},[O.value.result.reason?(e.openBlock(),e.createElementBlock("span",nt,"["+e.toDisplayString(O.value.result.reason)+"]",1)):e.createCommentVNode("",!0),e.createElementVNode("span",null,e.toDisplayString(O.value.result.message),1)],8,et)):e.createCommentVNode("",!0)],12,Zn))],64)):e.createCommentVNode("",!0)],44,Xn))}}),ot=e.defineComponent({__name:"HyperCardCanvasDesigner",props:{modelValue:{},componentSourceMap:{},mode:{default:"design"},schedulerOptions:{},adapters:{},canvasId:{}},emits:["update:modelValue","context-ready","handle-ready","cannot-drag-slot-child","cannot-drag-layout-managed-child"],setup(n,{expose:t,emit:o}){const i=n,a=o;let r=!1;const c=Z({initialDocument:i.modelValue,getMode:()=>i.mode,adapters:i.adapters});ee(c);const s=e.ref(null),d=On(c,{getStageEl:()=>{var e;return(null==(e=s.value)?void 0:e.querySelector("[data-hc-stage]"))??null},resolveContract:function(e){var n;const t=null==(n=i.componentSourceMap)?void 0:n[e];if(t)return"contract"in t&&t.contract?t.contract:void 0}}),l=i.canvasId??function(){const e=globalThis.crypto;return e&&"function"==typeof e.randomUUID?`hc-designer-${e.randomUUID()}`:`hc-designer-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}(),u=!!c.adapters.data,p=Ie({canvasId:l,source:{getDocument:()=>c.document.document,onAction:e=>c.registerHooks({onAfterAction:n=>e(n)})},initialMode:An(i.mode),dataStore:u?c.dataStore:void 0});d.attachBindingDelegate(p,u?c.dataStore:null),a("context-ready",c),a("handle-ready",d);const f={getDropTarget:(e,n)=>d.getDropTarget(e,s.value,n),canReparent:(e,n)=>d.canReparent(e,n),moveInstanceInTree:(e,n)=>d.moveInstanceInTree(e,n),cannotReparentEvent:d.cannotReparentEvent};function h(){a("update:modelValue",JSON.parse(JSON.stringify(c.document.document)))}return e.provide($n,f),e.watch(()=>i.modelValue,(e,n)=>{if(e&&e!==n){r=!0;try{c.suppressRecording(()=>{c.dispatch({type:"replaceDocument",payload:{document:e}})})}finally{r=!1}}}),e.watch(()=>c.document.document,()=>{r||c.isBatching.value||h()},{deep:!0,flush:"sync"}),e.watch(()=>c.isBatching.value,(e,n)=>{!n||e||r||h()},{flush:"sync"}),e.onMounted(()=>{Je(l,d),e.nextTick(()=>{p.setMode(An(i.mode))})}),e.watch(()=>i.mode,e=>{p.setMode(An(e))}),e.onBeforeUnmount(()=>{p.dispose(),d.attachBindingDelegate(null,null),Ue(l),d.dispose(),c.dispose()}),t({context:c,handle:d,canvasId:l}),(t,o)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"stageContainerEl",ref:s,class:"hc-canvas-designer",style:{width:"100%",height:"100%",position:"relative"},"data-hc-canvas-designer":""},[e.createVNode(Nn,null,{default:e.withCtx(()=>[e.createVNode(jn,{"component-source-map":n.componentSourceMap,mode:n.mode,"scheduler-options":n.schedulerOptions,"canvas-id":e.unref(l)},null,8,["component-source-map","mode","scheduler-options","canvas-id"]),"runtime"!==n.mode?(e.openBlock(),e.createBlock(tt,{key:0,mode:n.mode,onCannotDragSlotChild:o[0]||(o[0]=e=>a("cannot-drag-slot-child",e)),onCannotDragLayoutManagedChild:o[1]||(o[1]=e=>a("cannot-drag-layout-managed-child",e))},e.createSlots({_:2},[t.$slots["reparent-ghost"]?{name:"reparent-ghost",fn:e.withCtx(n=>[e.renderSlot(t.$slots,"reparent-ghost",e.normalizeProps(e.guardReactiveProps(n)))]),key:"0"}:void 0,t.$slots["split-divider"]?{name:"split-divider",fn:e.withCtx(n=>[e.renderSlot(t.$slots,"split-divider",e.normalizeProps(e.guardReactiveProps(n)))]),key:"1"}:void 0]),1032,["mode"])):e.createCommentVNode("",!0),e.renderSlot(t.$slots,"canvas-overlay",{viewport:e.unref(d).viewport,handle:e.unref(d)}),e.renderSlot(t.$slots,"default")]),_:3})],512))}});function it(e={}){const{canvasWidth:n=1280,canvasHeight:t=720,rootLayout:o="free",instances:i=[],bindings:a=[]}=e;return{schemaVersion:"1",layout:{type:"free",canvas:{width:{mode:"px",value:n},height:{mode:"px",value:t}},rootLayout:"string"==typeof o?{mode:o}:o},instances:i,bindings:a}}const at={event:["instanceEvent"],init:["lifecycle","page"],data:["dataSource"]};function rt(e){return at[e.type].includes(e.source.kind)}function ct(e,n,t,o){const i={level:n,code:e,bindingId:t.id,message:`${e} on binding "${t.id}"`};return o.instanceId&&(i.instanceId=o.instanceId),o.canvasId&&(i.canvasId=o.canvasId),i}function st(e){return"instanceEvent"===e.source.kind||"lifecycle"===e.source.kind?{instanceId:e.source.instanceId}:"instanceMethod"===e.target.kind||"instanceDataInput"===e.target.kind||"instanceEmit"===e.target.kind?{instanceId:e.target.instanceId}:{}}function dt(e){switch(e.source.kind){case"instanceEvent":case"lifecycle":return e.source.canvasId;case"page":case"dataSource":return}}function lt(e){switch(e.target.kind){case"instanceMethod":case"instanceEmit":case"instanceDataInput":return e.target.canvasId}}exports.CANVAS_CONTEXT_KEY=Q,exports.CANVAS_REPARENT_BRIDGE_KEY=$n,exports.CanvasStage=Nn,exports.DEFAULT_FIT_PADDING=40,exports.DIVIDER_HIT_THICKNESS=8,exports.DRAG_THRESHOLD_CANVAS_PX=3,exports.EFFECTIVE_DEFAULT_SLOT=te,exports.HyperCardCanvasDesigner=ot,exports.HyperCardPageRenderer=Ve,exports.InteractionLayer=tt,exports.MAX_INSTANCE_TREE_DEPTH=8,exports.MIN_INSTANCE_SIZE=8,exports.MIN_RATIO_FRACTION=.05,exports.RuntimeLayer=jn,exports.SLOT_CHILD_RESIZE_HANDLES=["e","s","se"],exports.VERSION="0.0.0-d3.6c-stage",exports.applyEffectiveSplitRatiosToDocument=s,exports.applySplitDividerDrag=qn,exports.assertNeverBindingSource=V,exports.assertNeverBindingTarget=q,exports.bindingModeForCanvasMode=An,exports.bindingReferencesInstance=j,exports.buildInstanceTree=wn,exports.canReparent=In,exports.canvasSizeToCss=M,exports.cleanLayoutItem=A,exports.clientToCanvas=gn,exports.computeContentBounds=Tn,exports.computeEffectiveSplitRatios=y,exports.computeFit=zn,exports.computeInverse=Xe,exports.computeNextAxisSize=pn,exports.computeNextLayoutBoxAxis=fn,exports.computeParentLayoutMode=$,exports.computeSelectionBounds=Cn,exports.computeSlotChildCanvasRect=un,exports.computeSnap=Qe,exports.computeSplitDividers=Vn,exports.computeVisibleBounds=Ln,exports.containerLayoutToCss=S,exports.createAssetResolver=Y,exports.createCanvasContext=Z,exports.createCanvasHandle=On,exports.createCanvasInteraction=vn,exports.createCommandRecorder=Ge,exports.createDocumentStore=J,exports.createFreePageDocument=function(e={}){return it({...e,rootLayout:"free"})},exports.createMinimalPageDocument=it,exports.createRenderScheduler=N,exports.createSelectionStore=U,exports.createSplitDividerInteraction=_n,exports.createViewportStore=X,exports.deriveComponentContract=be,exports.deriveComponentKind=function(e,t){const o="string"==typeof(null==e?void 0:e.js)?e.js:"",i="string"==typeof(null==e?void 0:e.html)?e.html:"",a=n.parseComponentSource(o,i);return!a.ok&&(null==t?void 0:t.fallback)?t.fallback:a.kind},exports.effectiveSlot=oe,exports.emptyComponentContract=function(){return{propsDecl:[],emitsDecl:[],methodsDecl:[],slotsDecl:[],modelDecl:[],dataInputsDecl:[],dataOutputsDecl:[]}},exports.emptyPageDocument=function(){return{schemaVersion:"1",layout:{type:"free",canvas:{width:{mode:"fill"},height:{mode:"fill"}}},instances:[],bindings:[]}},exports.filterExistingIds=mn,exports.filterInstancesInRect=nn,exports.findInstanceBreadcrumb=Sn,exports.findInstancePath=kn,exports.getBindingInstanceRefs=F,exports.getDefaultShortcuts=function(){return[{id:"undo",keys:["mod+z"],command:"undo",when:"notEditingText"},{id:"redo",keys:["mod+shift+z","mod+y"],command:"redo",when:"notEditingText"},{id:"deleteSelection",keys:["delete","backspace"],command:"deleteSelection",when:"hasSelection"},{id:"duplicateSelection",keys:["mod+d"],command:"duplicateSelection",when:"hasSelection"},{id:"fitToSelectionOrContent",keys:["f"],command:"fitToSelectionOrContent",when:"notEditingText"},{id:"zoom100",keys:["1"],command:"zoom100",when:"notEditingText"},{id:"resetViewport",keys:["0"],command:"resetViewport",when:"notEditingText"},{id:"zoomIn",keys:["+","="],command:"zoomIn",when:"notEditingText"},{id:"zoomOut",keys:["-"],command:"zoomOut",when:"notEditingText"},{id:"nudgeLeft",keys:["arrowleft"],command:"nudgeSelection",payload:{dx:-1,dy:0},when:"hasSelection"},{id:"nudgeRight",keys:["arrowright"],command:"nudgeSelection",payload:{dx:1,dy:0},when:"hasSelection"},{id:"nudgeUp",keys:["arrowup"],command:"nudgeSelection",payload:{dx:0,dy:-1},when:"hasSelection"},{id:"nudgeDown",keys:["arrowdown"],command:"nudgeSelection",payload:{dx:0,dy:1},when:"hasSelection"},{id:"nudgeLeftLarge",keys:["shift+arrowleft"],command:"nudgeSelectionLarge",payload:{dx:-1,dy:0},when:"hasSelection"},{id:"nudgeRightLarge",keys:["shift+arrowright"],command:"nudgeSelectionLarge",payload:{dx:1,dy:0},when:"hasSelection"},{id:"nudgeUpLarge",keys:["shift+arrowup"],command:"nudgeSelectionLarge",payload:{dx:0,dy:-1},when:"hasSelection"},{id:"nudgeDownLarge",keys:["shift+arrowdown"],command:"nudgeSelectionLarge",payload:{dx:0,dy:1},when:"hasSelection"},{id:"cancelInteraction",keys:["escape"],command:"cancelInteraction",when:"notEditingText"}]},exports.getDesignerHandle=function(e){return qe.get(e)??null},exports.getInstanceWrapperRectFromDom=an,exports.getOutletRectFromDom=on,exports.getParentLayoutMode=rn,exports.getSiblings=Bn,exports.getSlotChildRectFromDom=function(e,n){var t;const o=n??("undefined"!=typeof document&&"function"==typeof document.querySelector?document:null);if(!o)return null;const i="undefined"!=typeof globalThis&&(null==(t=globalThis.CSS)?void 0:t.escape)?globalThis.CSS.escape:e=>e.replace(/["\\]/g,e=>`\\${e}`),a=o.querySelector(`[data-instance-id="${i(e)}"][data-hc-placement="slot"]`);return a&&a instanceof HTMLElement?a.getBoundingClientRect():null},exports.hitTestInstance=Ze,exports.isAdditive=hn,exports.isCanvasRootPlacement=function(e){return"canvas"===e||"absolute"===e||void 0===e},exports.isContainerChildPlacement=O,exports.isDraftKey=function(e){return"string"==typeof e&&e.includes("@draft:")},exports.isEditingText=Pn,exports.isFreePositionLayoutMode=cn,exports.isInstanceEffectivelyLocked=Un,exports.isInstancePositionLocked=Kn,exports.isInstanceSizeLocked=Jn,exports.isResizeHandleAllowed=ln,exports.isV1Layout=w,exports.layoutItemToCss=B,exports.listRegisteredCanvasIds=function(){return Object.freeze(Array.from(qe.keys()))},exports.matchBinding=Dn,exports.migrateGridCellsToLayoutItem=d,exports.migrateInstanceToLayoutBox=D,exports.migrateLayoutV0ToV1=I,exports.migratePlacementToCanvasContainer=P,exports.migrateRootLayout=R,exports.normalizeComponentOverrides=u,exports.normalizeGridCells0Based=l,exports.normalizeInstanceSlotFields=p,exports.normalizeKeyString=Rn,exports.normalizeMarqueeRect=en,exports.normalizePageBindings=i,exports.normalizePageDocument=c,exports.parseComponentVersionKey=function(e){if("string"!=typeof e||!e.includes("@"))return null;const n=e.indexOf("@"),t=e.slice(0,n),o=e.slice(n+1);if(!t)return null;if(o.startsWith("draft:")){const e=o.slice(6),n=e.indexOf(":");if(n<=0)return null;const i=e.slice(0,n),a=e.slice(n+1);return i&&a?{kind:"draft",componentId:t,pageId:i,baseVersion:a,baseVersionKey:`${t}@${a}`}:null}return o?{kind:"published",componentId:t,version:o}:null},exports.parseKeyEvent=En,exports.provideCanvasContext=ee,exports.registerDesignerHandle=Je,exports.renderLayoutBoxStyle=b,exports.resolveCanvasSizePx=function(e,n=1920){return"px"===e.mode?e.value:n},exports.resolveMeasuredCanvasSizePx=x,exports.subscribeDesignerRegistry=function(e){return _e.add(e),()=>{_e.delete(e)}},exports.unionRects=Mn,exports.unregisterDesignerHandle=Ue,exports.useCanvasContext=ne,exports.validateBindings=function(e,n){var t,o,i;const a=[],r=new Map;for(const n of e.instances)r.set(n.instanceId,n);const c=null==n?void 0:n.currentCanvasId,s=null==n?void 0:n.resolveContract;let d=null,l=null;if(s){d=new Map,l=new Map;for(const n of e.instances){const e=s(n.componentVersionKey);if(d.set(n.instanceId,e),e)for(const t of e.dataInputsDecl)if(t.required){let e=l.get(n.instanceId);e||(e=new Set,l.set(n.instanceId,e)),e.add(t.key)}}}for(const n of e.bindings)if(rt(n)){if(void 0!==c){const e=dt(n),t=lt(n);void 0!==e&&e!==c&&a.push(ct("unsupported-cross-canvas","error",n,{canvasId:e})),void 0!==t&&t!==c&&a.push(ct("unsupported-cross-canvas","error",n,{canvasId:t}))}switch(n.source.kind){case"instanceEvent":{const e=n.source.event,t=r.get(n.source.instanceId);if(t){if(d){const o=d.get(t.instanceId);o&&!o.emitsDecl.some(n=>n.event===e)&&a.push(ct("unknown-source-event","error",n,{instanceId:t.instanceId}))}}else a.push(ct("orphan-binding","warn",n,{instanceId:n.source.instanceId}));break}case"lifecycle":r.get(n.source.instanceId)||a.push(ct("orphan-binding","warn",n,{instanceId:n.source.instanceId}))}switch(n.target.kind){case"instanceMethod":{const e=n.target.method,t=r.get(n.target.instanceId);if(t){if(d){const o=d.get(t.instanceId);o&&!o.methodsDecl.some(n=>n.key===e)&&a.push(ct("unknown-target-method","error",n,{instanceId:t.instanceId}))}}else a.push(ct("orphan-binding","warn",n,{instanceId:n.target.instanceId}));break}case"instanceEmit":{const e=n.target.event,t=r.get(n.target.instanceId);if(t){if(d){const o=d.get(t.instanceId);o&&!o.emitsDecl.some(n=>n.event===e)&&a.push(ct("unknown-target-event","error",n,{instanceId:t.instanceId}))}}else a.push(ct("orphan-binding","warn",n,{instanceId:n.target.instanceId}));break}case"instanceDataInput":{const e=n.target.key,o=r.get(n.target.instanceId);if(o){if(d){const i=d.get(o.instanceId);i&&!i.dataInputsDecl.some(n=>n.key===e)?a.push(ct("unknown-target-data-input","error",n,{instanceId:o.instanceId})):l&&(null==(t=l.get(o.instanceId))||t.delete(e))}}else a.push(ct("orphan-binding","warn",n,{instanceId:n.target.instanceId}));break}}(null==(o=n.schedule)?void 0:o.throttle)&&n.schedule.throttle.windowMs<16&&a.push(ct("schedule-window-too-small","info",n,st(n))),(null==(i=n.schedule)?void 0:i.debounce)&&n.schedule.debounce.windowMs<16&&a.push(ct("schedule-window-too-small","info",n,st(n)))}else a.push(ct("invalid-type-source-kind","error",n,st(n)));if(l)for(const[e,n]of l)for(const t of n){const n={level:"warn",code:"required-data-input-missing",instanceId:e,key:t,message:`Required dataInput "${t}" on instance "${e}" is not fed by any binding`};a.push(n)}return a},exports.validateInstanceTree=ie,exports.wirePageBindings=Ie;
2
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),n=require("@hy-bricks/core");function t(e){return JSON.parse(JSON.stringify(e))}const o="[hc-canvas/normalizeBindings]";function i(e){if(!Array.isArray(e))return[];const n=[];for(let t=0;t<e.length;t++){const i=e[t];if(!i||"object"!=typeof i){console.warn(`${o} dropped non-object binding at index ${t}`);continue}if(a(i)){n.push(i);continue}const c=r(i);null!==c&&n.push(c)}return n}function a(e){if(!e||"object"!=typeof e)return!1;const n=e;if("string"!=typeof n.id||0===n.id.length)return!1;if("event"!==n.type&&"init"!==n.type&&"data"!==n.type)return!1;const t=n.source;if(!t||"object"!=typeof t)return!1;if("string"!=typeof t.kind)return!1;const o=n.target;return!(!o||"object"!=typeof o)&&"string"==typeof o.kind}function r(e){if("string"!=typeof e.id||0===e.id.length)return console.warn(`${o} dropped binding with missing/invalid id`),null;const n=e.target;if(!n||"object"!=typeof n||"string"!=typeof n.instanceId||""===n.instanceId||"string"!=typeof n.method)return console.warn(`${o} dropped binding "${e.id}" missing/invalid target`),null;const i=e.type;let a;if("event"===i){const n=e.source;if(!n||"object"!=typeof n||"string"!=typeof n.instanceId||""===n.instanceId||"string"!=typeof n.event)return console.warn(`${o} dropped event binding "${e.id}" missing/invalid source`),null;a={kind:"instanceEvent",instanceId:n.instanceId,event:n.event}}else{if("init"!==i)return console.warn(`${o} dropped binding "${e.id}" with unknown legacy type "${String(e.type)}"`),null;{const n=e.source;n&&"string"==typeof n.instanceId&&""!==n.instanceId&&console.warn(`${o} init binding "${e.id}" had source.instanceId, discarded`),a={kind:"page",hook:"pageInit"}}}const r={kind:"instanceMethod",instanceId:n.instanceId,method:n.method};let c;c=void 0===n.args?{kind:"passthrough"}:Array.isArray(n.args)&&0===n.args.length?{kind:"static",args:[]}:Array.isArray(n.args)?{kind:"static",args:t(n.args)}:{kind:"passthrough"};const s={},d=e.options;d&&"object"==typeof d&&(!0===d.once&&(s.once=!0),"number"==typeof d.throttleMs&&(s.throttle={windowMs:d.throttleMs}),"number"==typeof d.debounceMs&&(s.debounce={windowMs:d.debounceMs}));const l=void 0!==s.once||void 0!==s.throttle||void 0!==s.debounce,u={id:e.id,source:a,target:r,mapping:c,...void 0!==e.disabled?{disabled:e.disabled}:{},...l?{schedule:s}:{}};return"event"===i?{...u,type:"event"}:{...u,type:"init"}}function c(e){const n=e.instances.map(p),t=u(e.componentOverrides,n),o=i(e.bindings);if("1"===e.schemaVersion){const i=R(w(e.layout)?e.layout:I(e.layout));return{...e,layout:i,instances:n,bindings:o,componentOverrides:t}}return{schemaVersion:"1",layout:R(I(e.layout)),instances:n,bindings:o,componentOverrides:t}}function s(e){const n=function(e){var n;const t=new Map;for(const o of e){if(!o.parentId)continue;if(void 0!==o.slot)continue;const e=t.get(o.parentId),i=null==(n=o.layoutItem)?void 0:n.ratio;e?e.push(i):t.set(o.parentId,[i])}let o=!1;const i=e.map(e=>{if(!e.containerLayout||"split"!==e.containerLayout.mode)return e;const n=t.get(e.instanceId)??[],i=e.containerLayout.ratios,a=y(i,n);return i.length===a.length&&i.every((e,n)=>e===a[n])?e:(o=!0,{...e,containerLayout:{...e.containerLayout,ratios:a}})});return o?i:e}(e.instances),t=e.layout.rootLayout?function(e,n){const t=e.rootLayout;if(!t||"split"!==t.mode)return e;const o=n.filter(e=>void 0===e.parentId).map(e=>{var n;return null==(n=e.layoutItem)?void 0:n.ratio}),i=t.ratios,a=y(i,o);return i.length===a.length&&i.every((e,n)=>e===a[n])?e:{...e,rootLayout:{...t,ratios:a}}}(e.layout,n):e.layout;return n===e.instances&&t===e.layout?e:{...e,layout:t,instances:n}}function d(e){const n=new Map,t=new Set;for(const o of e.instances){const e=o.containerLayout;if("grid"!==(null==e?void 0:e.mode))continue;t.add(o.instanceId);const i=e.cells;i&&"object"==typeof i&&Object.keys(i).length>0&&n.set(o.instanceId,l(i))}if(0===t.size)return e;let o=!1;const i=e.instances.map(e=>{if(!e.parentId)return e;if(void 0!==e.slot)return e;if(!t.has(e.parentId))return e;const i=e.layoutItem;if(i&&("number"==typeof i.row||"number"==typeof i.column)){const n=function(e){const n="number"==typeof e.row&&Number.isFinite(e.row)&&e.row<1,t="number"==typeof e.column&&Number.isFinite(e.column)&&e.column<1;if(!n&&!t)return e;const o={...e};return n&&(o.row=1),t&&(o.column=1),o}(i);return n===i?e:(o=!0,{...e,layoutItem:n})}const a=n.get(e.parentId),r=null==a?void 0:a[e.instanceId];if(!r)return e;const c=function(e){const n={};return"number"==typeof e.row&&Number.isFinite(e.row)&&(n.row=e.row<1?1:e.row),"number"==typeof e.column&&Number.isFinite(e.column)&&(n.column=e.column<1?1:e.column),void 0===n.row&&void 0===n.column?null:("number"==typeof e.rowSpan&&Number.isFinite(e.rowSpan)&&e.rowSpan>0&&e.rowSpan<=32&&(n.rowSpan=e.rowSpan),"number"==typeof e.columnSpan&&Number.isFinite(e.columnSpan)&&e.columnSpan>0&&e.columnSpan<=32&&(n.columnSpan=e.columnSpan),n)}(r);return c?(o=!0,{...e,layoutItem:{...i??{},...c}}):e});return o?{...e,instances:i}:e}function l(e){let n=!1;for(const t of Object.values(e))if(t&&(0===t.row||0===t.column)){n=!0;break}if(!n)return e;const t={};for(const[n,o]of Object.entries(e)){if(!o)continue;const e={...o};"number"==typeof e.row&&Number.isFinite(e.row)&&(e.row=e.row+1),"number"==typeof e.column&&Number.isFinite(e.column)&&(e.column=e.column+1),t[n]=e}return t}function u(e,n){if(!e||"object"!=typeof e||Array.isArray(e))return{};const t=new Set(n.map(e=>e.instanceId)),o={};for(const[n,i]of Object.entries(e)){if(!i||"object"!=typeof i||Array.isArray(i))continue;const e=i;e.instanceId===n&&t.has(e.instanceId)&&"string"==typeof e.baseVersionKey&&e.baseVersionKey&&T(e.source)&&C(e.contract)&&(o[n]={instanceId:e.instanceId,baseVersionKey:e.baseVersionKey,source:e.source,contract:e.contract,...z(e.contractParseError)?{contractParseError:z(e.contractParseError)}:{},..."string"==typeof e.createdAt?{createdAt:e.createdAt}:{},..."string"==typeof e.updatedAt?{updatedAt:e.updatedAt}:{}})}return o}function p(e){let n=e;void 0===n.parentId&&n.slotPlacement&&(n={...n,parentId:n.slotPlacement.parentInstanceId,slot:n.slotPlacement.slotName}),""!==n.slot&&"default"!==n.slot||(n={...n,slot:void 0}),void 0===n.placement&&(n={...n,placement:void 0===n.parentId?"absolute":"slot"});const t=h(n.sizing,n.size);if(t!==n.size&&(n={...n,size:t}),void 0!==n.containerLayout){const e=v(n.containerLayout);if(e!==n.containerLayout)if(null===e){const{containerLayout:e,...t}=n;n=t}else n={...n,containerLayout:e}}if(n=P(n),n=D(n),void 0!==n.layoutItem){const e=A(n.layoutItem);if(null===e){const{layoutItem:e,...t}=n;n=t}else e!==n.layoutItem&&(n={...n,layoutItem:e})}if(!0===n.locked){const e={};void 0===n.lockPosition&&(e.lockPosition=!0),void 0===n.lockSize&&(e.lockSize=!0),Object.keys(e).length>0&&(n={...n,...e})}return n}const f=new Set(["px","percent","fill","hug","auto"]);function h(e,n){var t,o,i,a;const r=n?function(e){const n={},t=m(e.width),o=m(e.height);return t&&(n.width=t),o&&(n.height=o),n.width||n.height?n:void 0}(n):void 0;if(!e)return r;const c={};if(e.width){const n=g(e.width,null==(t=e.min)?void 0:t.w,null==(o=e.max)?void 0:o.w);n&&(c.width=n)}if(e.height){const n=g(e.height,null==(i=e.min)?void 0:i.h,null==(a=e.max)?void 0:a.h);n&&(c.height=n)}return r?{width:r.width??c.width,height:r.height??c.height}:Object.keys(c).length>0?c:void 0}function g(e,n,t){if(!e||"object"!=typeof e)return null;let o;switch(e.mode){case"fixed":o="px";break;case"percent":o="percent";break;case"fill":o="fill";break;case"hug":o="hug";break;default:return null}const i={mode:o};return"px"!==o&&"percent"!==o||"number"!=typeof e.value||(i.value=e.value),"number"==typeof n&&(i.min=n),"number"==typeof t&&(i.max=t),i}function m(e){if(!e||"object"!=typeof e)return null;if("string"!=typeof e.mode)return null;if(!f.has(e.mode))return null;const n={mode:e.mode};return"px"!==e.mode&&"percent"!==e.mode||"number"!=typeof e.value||(n.value=e.value),"number"==typeof e.min&&(n.min=e.min),"number"==typeof e.max&&(n.max=e.max),n}function v(e){if(!e||"object"!=typeof e)return null;if("none"===e.mode)return{mode:"none"};if("free"===e.mode)return{mode:"free"};if("flex"===e.mode){const n=e,t={mode:"flex",direction:"row"===n.direction||"column"===n.direction?n.direction:"row"};return!0===n.wrap&&(t.wrap=!0),"number"==typeof n.gap&&Number.isFinite(n.gap)&&n.gap>=0&&(t.gap=n.gap),"start"!==n.justify&&"center"!==n.justify&&"end"!==n.justify&&"space-between"!==n.justify&&"space-around"!==n.justify||(t.justify=n.justify),"start"!==n.align&&"center"!==n.align&&"end"!==n.align&&"stretch"!==n.align||(t.align=n.align),t}if("split"===e.mode){const n=e;if("horizontal"!==n.direction&&"vertical"!==n.direction)return null;if(!Array.isArray(n.ratios))return null;const t=n.ratios.filter(e=>"number"==typeof e&&Number.isFinite(e)&&e>=0),o={mode:"split",direction:n.direction,ratios:t};return"number"==typeof n.gap&&Number.isFinite(n.gap)&&n.gap>=0&&(o.gap=n.gap),o}if("grid"===e.mode){const n=e;if(!Array.isArray(n.columns)||!Array.isArray(n.rows))return null;const t={mode:"grid",columns:n.columns.filter(e=>!!e&&("fr"===e.mode||"px"===e.mode||"percent"===e.mode)&&"number"==typeof e.value&&Number.isFinite(e.value)&&e.value>=0).slice(0,32),rows:n.rows.filter(e=>!!e&&("fr"===e.mode||"px"===e.mode||"percent"===e.mode||"auto"===e.mode)&&("auto"===e.mode&&void 0===e.value||"number"==typeof e.value&&Number.isFinite(e.value)&&e.value>=0)).slice(0,32)};if("number"==typeof n.gap&&Number.isFinite(n.gap)&&n.gap>=0)t.gap=n.gap;else if(n.gap&&"object"==typeof n.gap){const e={};"number"==typeof n.gap.row&&Number.isFinite(n.gap.row)&&n.gap.row>=0&&(e.row=n.gap.row),"number"==typeof n.gap.column&&Number.isFinite(n.gap.column)&&n.gap.column>=0&&(e.column=n.gap.column),Object.keys(e).length>0&&(t.gap=e)}if(n.cells&&"object"==typeof n.cells&&!Array.isArray(n.cells)){const e={};for(const[t,o]of Object.entries(n.cells)){if(!o||"object"!=typeof o)continue;if(!Number.isFinite(o.row)||!Number.isFinite(o.column))continue;const n={row:o.row,column:o.column};"number"==typeof o.rowSpan&&Number.isFinite(o.rowSpan)&&o.rowSpan>0&&o.rowSpan<=32&&(n.rowSpan=o.rowSpan),"number"==typeof o.columnSpan&&Number.isFinite(o.columnSpan)&&o.columnSpan>0&&o.columnSpan<=32&&(n.columnSpan=o.columnSpan),e[t]=n}Object.keys(e).length>0&&(t.cells=e)}return t}return null}function y(e,n){const t=(e??[]).map(e=>"number"==typeof e&&Number.isFinite(e)&&e>=0?e:0),o=[];for(let e=0;e<n.length;e++){const i=n[e];if("number"==typeof i&&Number.isFinite(i)&&i>0){o.push(i);continue}const a=t[e];"number"==typeof a&&a>0?o.push(a):o.push(1)}return o}function I(e){if(!e)return{type:"free",canvas:{width:{mode:"px",value:1920},height:{mode:"px",value:1080}}};if(w(e))return e;const n=e,t={width:{mode:"px",value:n.canvas.w},height:{mode:"px",value:n.canvas.h}},o=function(e){if(!e)return;const n={};if(void 0!==e.color&&(n.color=e.color),void 0!==e.imageAssetId){const t={id:e.imageAssetId,type:"image"};n.image=t}return void 0!==e.fit&&(n.imageFit="original"===e.fit?"center":e.fit),Object.keys(n).length>0?n:void 0}(n.canvas.background),i={type:n.type,canvas:t};return o&&(i.background=o),void 0!==n.canvas.gridSize&&(i.guides={grid:{size:n.canvas.gridSize}}),i}function w(e){if(!e)return!1;const n=e.canvas;if(!n)return!1;const t=n.width;return"object"==typeof t&&null!==t&&"mode"in t&&"string"==typeof t.mode}function x(e,n,t=1920){switch(e.mode){case"px":return e.value;case"percent":return n>0?n*e.value/100:t;case"vw":return"undefined"!=typeof window?window.innerWidth*e.value/100:t;case"vh":return"undefined"!=typeof window?window.innerHeight*e.value/100:t;case"auto":case"fill":return n>0?n:t}}function b(e,n,t,o,i){const a=k(e.widthMode,e.width),r=k(e.heightMode,e.height),c="free"===o,s={boxSizing:"border-box",minWidth:0,minHeight:0,overflow:e.overflow??"hidden",zIndex:n};return null!==a&&(s.width=a),null!==r&&(s.height=r),"split"===o&&("vertical"===i?s.height="100%":s.width="100%"),"number"==typeof t&&Number.isFinite(t)&&0!==t&&(s.transform=`rotate(${t}deg)`),c?(s.position="absolute",s.left=`${e.x}px`,s.top=`${e.y}px`):s.position="relative",s}function k(e,n){switch(e){case"px":return`${n}px`;case"percent":return`${n}%`;case"fill":return"100%";case"auto":return"auto"}}function S(e){if(!e||"none"===e.mode||"free"===e.mode)return null;if("flex"===e.mode){const n={display:"flex"};if(n.flexDirection=e.direction??"row",e.wrap&&(n.flexWrap="wrap"),"number"==typeof e.gap&&(n.gap=`${e.gap}px`),e.justify){const t={start:"flex-start",end:"flex-end",center:"center","space-between":"space-between","space-around":"space-around"};n.justifyContent=t[e.justify]??e.justify}if(e.align){const t={start:"flex-start",end:"flex-end",center:"center",stretch:"stretch"};n.alignItems=t[e.align]??e.align}return n}if("grid"===e.mode){const n={display:"grid"},t=(e.columns??[]).map(e=>"fr"===e.mode?`${e.value}fr`:"px"===e.mode?`${e.value}px`:`${e.value}%`).join(" "),o=(e.rows??[]).map(e=>"auto"===e.mode?"auto":"fr"===e.mode?`${e.value??1}fr`:"px"===e.mode?`${e.value??0}px`:`${e.value??0}%`).join(" ");if(t&&(n.gridTemplateColumns=t),o&&(n.gridTemplateRows=o),"number"==typeof e.gap)n.gap=`${e.gap}px`;else if(e.gap&&"object"==typeof e.gap){const t=e.gap.row??0,o=e.gap.column??0;n.gap=`${t}px ${o}px`}return n}if("split"===e.mode){const n=(Array.isArray(e.ratios)?e.ratios:[]).map(e=>"number"==typeof e&&Number.isFinite(e)&&e>=0?e:0).filter(e=>e>0),t=n.length>0?n.map(e=>`${e}fr`).join(" "):"1fr",o={display:"grid"};return"vertical"===e.direction?o.gridTemplateRows=t:o.gridTemplateColumns=t,"number"==typeof e.gap&&(o.gap=`${e.gap}px`),o}return null}function B(e,n){if(!e)return null;if("flex"===n){const n={};return"number"==typeof e.order&&(n.order=e.order),"number"==typeof e.grow&&(n.flexGrow=e.grow),"number"==typeof e.shrink&&(n.flexShrink=e.shrink),Object.keys(n).length>0?n:null}if("grid"===n){const n={};if("number"==typeof e.row){const t="number"==typeof e.rowSpan&&e.rowSpan>0?e.rowSpan:1;n.gridRow=t>1?`${e.row} / span ${t}`:`${e.row}`}if("number"==typeof e.column){const t="number"==typeof e.columnSpan&&e.columnSpan>0?e.columnSpan:1;n.gridColumn=t>1?`${e.column} / span ${t}`:`${e.column}`}return Object.keys(n).length>0?n:null}return null}function M(e){switch(e.mode){case"px":return`${e.value}px`;case"percent":return`${e.value}%`;case"vw":return`${e.value}vw`;case"vh":return`${e.value}vh`;case"auto":return"auto";case"fill":return"100%"}}function T(e){return!!e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.html&&"string"==typeof e.js&&"string"==typeof e.css}function C(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const n=e;return["propsDecl","emitsDecl","methodsDecl","slotsDecl","modelDecl","dataInputsDecl","dataOutputsDecl"].every(e=>Array.isArray(n[e]))}function z(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const n=e;return"string"==typeof n.message?{message:n.message,..."number"==typeof n.line?{line:n.line}:{},..."number"==typeof n.column?{column:n.column}:{}}:void 0}const L=new Set(["px","percent","fill","auto"]),E=new Set(["hidden","visible","auto"]);function P(e){const n=e.placement;return"canvas"===n||"container"===n?e:"absolute"===n?{...e,placement:"canvas"}:"slot"===n?{...e,placement:"container"}:{...e,placement:e.parentId?"container":"canvas"}}function D(e){var n,t;const o=e.rect??{x:0,y:0,w:0,h:0},i=null==(n=e.size)?void 0:n.width,a=null==(t=e.size)?void 0:t.height,r=e=>{if(e)return"hug"===e.mode?"auto":"percent"===e.mode?"percent":"fill"===e.mode?"fill":"auto"===e.mode?"auto":"px"===e.mode?"px":void 0},c=e.layoutBox,s=c&&L.has(c.widthMode)?c.widthMode:r(i)??"px",d=c&&L.has(c.heightMode)?c.heightMode:r(a)??"px",l=(e,n)=>"number"==typeof e&&Number.isFinite(e)?e:n,u={x:l(null==c?void 0:c.x,o.x),y:l(null==c?void 0:c.y,o.y),width:l(null==c?void 0:c.width,(null==i?void 0:i.value)??o.w),height:l(null==c?void 0:c.height,(null==a?void 0:a.value)??o.h),widthMode:s,heightMode:d,overflow:(null==c?void 0:c.overflow)&&E.has(c.overflow)?c.overflow:"hidden"};return c&&c.x===u.x&&c.y===u.y&&c.width===u.width&&c.height===u.height&&c.widthMode===u.widthMode&&c.heightMode===u.heightMode&&c.overflow===u.overflow?e:{...e,layoutBox:u}}function R(e){if(e.rootLayout){const o=v(e.rootLayout);return null===o?{...e,rootLayout:{mode:"free"}}:(t=o,(n=e.rootLayout).mode===t.mode&&JSON.stringify(n)===JSON.stringify(t)?e:{...e,rootLayout:o})}var n,t;return{...e,rootLayout:{mode:"free"}}}function O(e){return"container"===e||"slot"===e}function $(e,n,t){var o,i;const a=n.find(e=>e.instanceId===t);if(!a)return;if(void 0===a.parentId)return(null==(o=null==e?void 0:e.rootLayout)?void 0:o.mode)??"free";const r=n.find(e=>e.instanceId===a.parentId);return(null==(i=null==r?void 0:r.containerLayout)?void 0:i.mode)??"none"}function A(e){if(!e||"object"!=typeof e)return null;const n={},t=["order","grow","shrink","row","column","rowSpan","columnSpan","ratio"];for(const o of t){const t=e[o];"number"==typeof t&&Number.isFinite(t)&&(n[o]=t)}return Object.keys(n).length>0?n:null}function N(n={}){const{rootMargin:t="500px",disposeDelayMs:o=1500,mountConcurrency:i=2,root:a=null}=n,r={state:e.reactive({}),elById:new Map,idByEl:new WeakMap,mountQueue:[],disposeTimers:new Map,idleScheduled:!1,io:null};function c(e){for(const n of e){const e=r.idByEl.get(n.target);e&&(n.isIntersecting?s(e):d(e))}}function s(e){const n=r.disposeTimers.get(e);n&&(clearTimeout(n),r.disposeTimers.delete(e));const t=r.state[e];"mounted"!==t&&"disposing"!==t?(r.state[e]="mounting",r.mountQueue.includes(e)||r.mountQueue.push(e),l()):r.state[e]="mounted"}function d(e){const n=r.state[e];if("pending"===n||"idle"===n)return;if("mounting"===n){const n=r.mountQueue.indexOf(e);return n>=0&&r.mountQueue.splice(n,1),void(r.state[e]="pending")}r.state[e]="disposing";const t=r.disposeTimers.get(e);t&&clearTimeout(t);const i=setTimeout(()=>{"disposing"===r.state[e]&&(r.state[e]="pending",r.disposeTimers.delete(e))},o);r.disposeTimers.set(e,i)}function l(){r.idleScheduled||0===r.mountQueue.length||(r.idleScheduled=!0,function(e,n=50){const t=globalThis;"function"==typeof t.requestIdleCallback?t.requestIdleCallback(()=>e(),{timeout:n}):setTimeout(e,16)}(()=>{r.idleScheduled=!1;let e=0;for(;e<i&&r.mountQueue.length>0;){const n=r.mountQueue.shift();"mounting"===r.state[n]&&(r.state[n]="mounted",e++)}r.mountQueue.length>0&&l()}))}return{register(e,n){const o=r.elById.get(e);if(o&&o!==n){const e=r.io;e&&e.unobserve(o),r.idByEl.delete(o)}r.elById.set(e,n),r.idByEl.set(n,e),r.state[e]="pending";const i=r.io?r.io:"undefined"==typeof IntersectionObserver?null:(r.io=new IntersectionObserver(c,{root:a,rootMargin:t}),r.io);i?i.observe(n):r.state[e]="mounted"},unregister(e){const n=r.elById.get(e);if(n){const t=r.io;t&&t.unobserve(n),r.idByEl.delete(n),r.elById.delete(e)}const t=r.disposeTimers.get(e);t&&(clearTimeout(t),r.disposeTimers.delete(e));const o=r.mountQueue.indexOf(e);o>=0&&r.mountQueue.splice(o,1),delete r.state[e]},isMounted(e){const n=r.state[e];return"mounted"===n||"disposing"===n},getState:e=>r.state[e]??"idle",get state(){return r.state},dispose(){r.io&&(r.io.disconnect(),r.io=null);for(const e of r.disposeTimers.values())clearTimeout(e);r.disposeTimers.clear(),r.elById.clear(),r.mountQueue.length=0;for(const e of Object.keys(r.state))delete r.state[e]}}}function F(e){const n=[];switch(e.source.kind){case"instanceEvent":case"lifecycle":n.push({canvasId:e.source.canvasId,instanceId:e.source.instanceId});break;case"page":case"dataSource":break;default:V(e.source)}switch(e.target.kind){case"instanceMethod":case"instanceEmit":case"instanceDataInput":n.push({canvasId:e.target.canvasId,instanceId:e.target.instanceId});break;default:q(e.target)}return n}function j(e,n,t){for(const o of F(e))if(o.instanceId===n&&o.canvasId===t)return!0;return!1}function V(e){throw new Error(`[hc-canvas/bindingRefs] Unhandled BindingSource.kind: ${e.kind}`)}function q(e){throw new Error(`[hc-canvas/bindingRefs] Unhandled BindingTarget.kind: ${e.kind}`)}function _(e){const n={type:e.type,canvas:{...e.canvas,width:{...e.canvas.width},height:{...e.canvas.height}}};return e.background&&(n.background={...e.background,...e.background.image?{image:{...e.background.image}}:{}}),e.behavior&&(n.behavior={...e.behavior}),e.guides&&(n.guides={...e.guides,...e.guides.items?{items:[...e.guides.items]}:{}}),e.rootLayout&&(n.rootLayout="grid"===(t=e.rootLayout).mode?{...t,columns:t.columns?t.columns.map(e=>({...e})):[],rows:t.rows?t.rows.map(e=>({...e})):[],...t.cells?{cells:{...t.cells}}:{},..."object"==typeof t.gap&&null!==t.gap?{gap:{...t.gap}}:{}}:"split"===t.mode?{...t,ratios:Array.isArray(t.ratios)?[...t.ratios]:[]}:{...t}),n;var t}function K(e={}){return JSON.parse(JSON.stringify(e))}function J(n={schemaVersion:"1",layout:{type:"free",canvas:{width:{mode:"fill"},height:{mode:"fill"}}},instances:[],bindings:[]}){const o=d(c(n)),a=e.reactive({schemaVersion:"1",layout:_(o.layout),instances:o.instances.map(e=>({...e,rect:{...e.rect}})),bindings:o.bindings.map(e=>t(e)),componentOverrides:K(o.componentOverrides)});function r(e){return a.instances.findIndex(n=>n.instanceId===e)}function s(e){return a.bindings.findIndex(n=>n.id===e)}return{get document(){return a},instanceCount:e.computed(()=>a.instances.length),bindingCount:e.computed(()=>a.bindings.length),addInstance(e){if(r(e.instanceId)>=0)return void console.warn(`[hc-canvas/doc-store] instanceId "${e.instanceId}" 已存在,addInstance 忽略`);const n=e.rect?{...e.rect}:function(e){if(!e)return{x:0,y:0,w:0,h:0};const n=(e,n)=>"number"==typeof e&&Number.isFinite(e)?e:n;return{x:n(e.x,0),y:n(e.y,0),w:n(e.width,0),h:n(e.height,0)}}(e.layoutBox),t={...e,rect:n};!0===t.locked&&(void 0===t.lockPosition&&(t.lockPosition=!0),void 0===t.lockSize&&(t.lockSize=!0)),a.instances.push(t)},removeInstance(e){var n;const t=r(e);t<0||(a.instances.splice(t,1),null==(n=a.componentOverrides)||delete n[e],a.bindings=a.bindings.filter(n=>!j(n,e)))},updateInstance(e,n){const t=a.instances.find(n=>n.instanceId===e);if(t&&(Object.assign(t,n),n.rect&&t.layoutBox&&(t.layoutBox={...t.layoutBox,x:t.rect.x,y:t.rect.y,..."px"===t.layoutBox.widthMode?{width:t.rect.w}:{},..."px"===t.layoutBox.heightMode?{height:t.rect.h}:{}}),n.layoutBox)){const e=t.layoutBox??n.layoutBox,o=e=>"number"==typeof e&&Number.isFinite(e);t.rect={x:o(e.x)?e.x:t.rect.x,y:o(e.y)?e.y:t.rect.y,w:"px"===e.widthMode&&o(e.width)?e.width:t.rect.w,h:"px"===e.heightMode&&o(e.height)?e.height:t.rect.h}}},moveInstance(e,n,t){const o=a.instances.find(n=>n.instanceId===e);o&&(o.rect.x=n,o.rect.y=t,o.layoutBox&&(o.layoutBox={...o.layoutBox,x:n,y:t}))},resizeInstance(e,n,t){const o=a.instances.find(n=>n.instanceId===e);if(!o)return;const i=Math.max(1,n),r=Math.max(1,t);o.rect.w=i,o.rect.h=r,o.layoutBox&&(o.layoutBox={...o.layoutBox,width:i,height:r,widthMode:"px",heightMode:"px"})},setInstanceProp(e,n,t){const o=a.instances.find(n=>n.instanceId===e);o&&(o.props={...o.props,[n]:t})},setInstanceLocked(e,n){const t=a.instances.find(n=>n.instanceId===e);t&&(t.locked=n,n?(t.lockPosition=!0,t.lockSize=!0):(delete t.lockPosition,delete t.lockSize))},setInstanceSize(e,n){const t=a.instances.find(n=>n.instanceId===e);if(t)if(null===n)delete t.size,t.layoutBox&&(t.layoutBox={...t.layoutBox,width:t.rect.w,height:t.rect.h,widthMode:"px",heightMode:"px"});else if(t.size=n,t.layoutBox){const e=n.width,o=n.height,i={...t.layoutBox};e&&("px"===e.mode?(i.widthMode="px","number"==typeof e.value&&Number.isFinite(e.value)&&(i.width=e.value)):"percent"===e.mode?(i.widthMode="percent","number"==typeof e.value&&Number.isFinite(e.value)&&(i.width=e.value)):"fill"===e.mode?(i.widthMode="fill",Number.isFinite(i.width)||(i.width=t.rect.w)):"auto"!==e.mode&&"hug"!==e.mode||(i.widthMode="auto",Number.isFinite(i.width)||(i.width=t.rect.w))),o&&("px"===o.mode?(i.heightMode="px","number"==typeof o.value&&Number.isFinite(o.value)&&(i.height=o.value)):"percent"===o.mode?(i.heightMode="percent","number"==typeof o.value&&Number.isFinite(o.value)&&(i.height=o.value)):"fill"===o.mode?(i.heightMode="fill",Number.isFinite(i.height)||(i.height=t.rect.h)):"auto"!==o.mode&&"hug"!==o.mode||(i.heightMode="auto",Number.isFinite(i.height)||(i.height=t.rect.h))),t.layoutBox=i}},setInstanceContainerLayout(e,n){const t=a.instances.find(n=>n.instanceId===e);t&&(null===n?delete t.containerLayout:t.containerLayout=n)},updateInstanceLayoutBox(e,n){const t=a.instances.find(n=>n.instanceId===e);if(!t)return;const o=t.layoutBox??{x:t.rect.x,y:t.rect.y,width:t.rect.w,height:t.rect.h,widthMode:"px",heightMode:"px",overflow:"hidden"},i={},r=["x","y","width","height"];for(const e of r){const t=n[e];"number"==typeof t&&Number.isFinite(t)&&(i[e]=t)}if("px"!==n.widthMode&&"percent"!==n.widthMode&&"fill"!==n.widthMode&&"auto"!==n.widthMode||(i.widthMode=n.widthMode),"px"!==n.heightMode&&"percent"!==n.heightMode&&"fill"!==n.heightMode&&"auto"!==n.heightMode||(i.heightMode=n.heightMode),"hidden"!==n.overflow&&"visible"!==n.overflow&&"auto"!==n.overflow||(i.overflow=n.overflow),0===Object.keys(i).length)return;const c={...o,...i};t.layoutBox=c;const s=i.widthMode??o.widthMode,d=i.heightMode??o.heightMode;t.rect={x:c.x,y:c.y,w:"px"===s?c.width:t.rect.w,h:"px"===d?c.height:t.rect.h}},updateInstanceLayoutItem(e,n){const t=a.instances.find(n=>n.instanceId===e);if(!t)return;if(null===n)return void delete t.layoutItem;const o=["order","grow","shrink","row","column","rowSpan","columnSpan","ratio"],i={};for(const e of o){const t=n[e];"number"==typeof t&&Number.isFinite(t)&&(i[e]=t)}if(0===Object.keys(i).length)return;const r=t.layoutItem??{};t.layoutItem={...r,...i}},setInstanceRotation(e,n){const t=a.instances.find(n=>n.instanceId===e);t&&Number.isFinite(n)&&(0===n?delete t.rotation:t.rotation=n)},duplicateInstance(e,n,t){var o;const i=a.instances.find(n=>n.instanceId===e);if(!i)return;const r=JSON.parse(JSON.stringify(i));if(r.instanceId=n,r.rect={...r.rect,x:i.rect.x+t.x,y:i.rect.y+t.y},r.layoutBox&&(r.layoutBox={...r.layoutBox,x:r.layoutBox.x+t.x,y:r.layoutBox.y+t.y}),delete r.locked,delete r.lockPosition,delete r.lockSize,a.instances.some(e=>e.instanceId===n))return void console.warn(`[hc-canvas/doc-store] duplicateInstance: newInstanceId "${n}" 已存在,忽略`);a.instances.push(r);const c=null==(o=a.componentOverrides)?void 0:o[e];c&&(a.componentOverrides={...a.componentOverrides??{},[n]:{...JSON.parse(JSON.stringify(c)),instanceId:n}})},addBinding(e){if(s(e.id)>=0)return void console.warn(`[hc-canvas/doc-store] binding id "${e.id}" 已存在,addBinding 忽略`);const[n]=i([e]);n?a.bindings.push(t(n)):console.warn(`[hc-canvas/doc-store] addBinding "${null==e?void 0:e.id}" dropped by normalize`)},removeBinding(e){const n=s(e);n<0||a.bindings.splice(n,1)},updateBinding(e,n){const o=a.bindings.find(n=>n.id===e);if(!o)return;const i=t(n);Object.assign(o,i)},updateLayout(e){for(const n of Object.keys(e)){const t=e[n];void 0===t?delete a.layout[n]:a.layout[n]=t}},setComponentOverride(e,n){null!==n?(a.componentOverrides||(a.componentOverrides={}),a.componentOverrides[e]=n):a.componentOverrides&&e in a.componentOverrides&&delete a.componentOverrides[e]},replaceDocument(e){const n=d(c(e));a.schemaVersion="1",a.layout=_(n.layout),a.instances=n.instances.map(e=>({...e,rect:{...e.rect}})),a.bindings=n.bindings.map(e=>t(e)),a.componentOverrides=K(n.componentOverrides)},getInstance:e=>a.instances.find(n=>n.instanceId===e),listInstancesByComponentVersionKey:e=>a.instances.filter(n=>n.componentVersionKey===e)}}function U(){const n=e.reactive({ids:[]});return{selectedIds:e.computed(()=>n.ids),size:e.computed(()=>n.ids.length),primaryId:e.computed(()=>n.ids[0]),select(e){n.ids=[e]},toggleSelect(e){const t=n.ids.indexOf(e);t>=0?n.ids.splice(t,1):n.ids.push(e)},addToSelection(e){n.ids.includes(e)||n.ids.push(e)},removeFromSelection(e){const t=n.ids.indexOf(e);t>=0&&n.ids.splice(t,1)},clearSelection(){n.ids=[]},selectAll(e){n.ids=Array.from(new Set(e))},purgeOrphans(e){const t=new Set(e);n.ids=n.ids.filter(e=>t.has(e))},isSelected:e=>n.ids.includes(e)}}function H(n={}){const{minScale:t=.25,maxScale:o=4,initialScale:i=1}=n,a=e.reactive({scale:i,panX:0,panY:0});function r(e){return Math.max(t,Math.min(o,e))}return{state:a,scale:e.computed(()=>a.scale),panX:e.computed(()=>a.panX),panY:e.computed(()=>a.panY),setScale(e){a.scale=r(e)},zoomAt(e,n){const t=a.scale,o=r(t+n);if(o===t)return;const i=o/t;a.panX=e.x-(e.x-a.panX)*i,a.panY=e.y-(e.y-a.panY)*i,a.scale=o},setPan(e,n){a.panX=e,a.panY=n},panBy(e,n){a.panX+=e,a.panY+=n},resetView(){a.scale=i,a.panX=0,a.panY=0},fitToScreen(e,n,t=40){const o=Math.max(1,n.w-2*t),i=Math.max(1,n.h-2*t),c=o/e.w,s=i/e.h,d=r(Math.min(c,s)),l=e.w*d,u=e.h*d;a.scale=d,a.panX=(n.w-l)/2,a.panY=(n.h-u)/2},toCanvasPoint:e=>({x:(e.x-a.panX)/a.scale,y:(e.y-a.panY)/a.scale}),toViewportPoint:e=>({x:e.x*a.scale+a.panX,y:e.y*a.scale+a.panY})}}function X(e){const n=new Map;return{resolve(t){const o=function(e){return e.id||e.url||""}(t);if(o&&n.has(o))return n.get(o);if(!e){const e=t.url??"";return o&&n.set(o,e),e}const i=e.resolve(t);return"string"==typeof i?(o&&n.set(o,i),i):(o&&n.set(o,i),i.then(e=>{o&&n.set(o,e)},e=>{console.warn(`[hc-canvas/assets] resolve("${o}") 失败,缓存里删条目允许重试:`,e),o&&n.delete(o)}),i)},__clearCache(){n.clear()}}}function Y(e,n,t){if(!n||0===Object.keys(n).length)return`${e}::{}`;const o=G(n,t);return null===o?`${e}::__fresh_${Date.now()}_${Math.random().toString(36).slice(2,8)}__`:`${e}::${o}`}function G(e,n,t=new WeakSet){if(null==e)return JSON.stringify(e);const o=typeof e;if("string"===o||"number"===o||"boolean"===o)return JSON.stringify(e);if("function"===o||"symbol"===o||"bigint"===o)return null==n||n(),null;if(Array.isArray(e)){if(t.has(e))return null==n||n(),null;t.add(e);const o=[];for(const i of e){const e=G(i,n,t);if(null===e)return null;o.push(e)}return`[${o.join(",")}]`}if("object"===o){const o=Object.getPrototypeOf(e);if(o!==Object.prototype&&null!==o)return null==n||n(),null;const i=e;if(t.has(i))return null==n||n(),null;t.add(i);const a=Object.keys(i).sort(),r=[];for(const e of a){const o=G(i[e],n,t);if(null===o)return null;r.push(`${JSON.stringify(e)}:${o}`)}return`{${r.join(",")}}`}return null==n||n(),null}function W(e){const n=new Map,t=new Map,o=new Map,i=new Map,a=new Map,r=new Map;let c=!1,s=!1,d=0,l=null;function u(e){if(!s&&null!==l)try{l(e)}catch(e){console.error("[hc-canvas/dataStore] trace bridge listener threw",e)}}function p(e,n){var t;const a=o.get(e);if(a)for(const e of a)null==(t=i.get(e))||t.onUpdate(n)}function f(e,t){let o=n.get(e);return o||(o={cacheKey:e,sourceId:t,status:"idle"},n.set(e,o)),o}function h(t,r,c){if(!e)return;const l=a.get(t);l&&l.abort();const h=new AbortController;a.set(t,h);const g=f(t,r);g.status="loading";const m=g.writeSeq??0;Promise.resolve().then(()=>async function(e,n){return{value:await Promise.resolve(e.query(n))}}(e,{sourceId:r,params:c,signal:h.signal})).then(e=>{if(s)return;if(a.get(t)!==h)return;a.delete(t);const o=n.get(t);o&&((o.writeSeq??0)>m?u({kind:"data-query-skipped",cacheKey:t,sourceId:r,writeSeq:o.writeSeq,reason:"race-stale"}):(o.status="success",o.value=e.value,o.error=void 0,o.lastFetchedAt=Date.now(),o.writeSeq=++d,u({kind:"data-source-update",cacheKey:t,sourceId:r,writeSeq:o.writeSeq,value:e.value}),p(t,e.value)))}).catch(e=>{if(s)return;if(function(e){return null!==e&&"object"==typeof e&&"AbortError"===e.name}(e))return;if(a.get(t)!==h)return;a.delete(t);const c=n.get(t);c&&((c.writeSeq??0)>m?u({kind:"data-query-skipped",cacheKey:t,sourceId:r,writeSeq:c.writeSeq,reason:"race-stale-reject"}):(c.status="error",c.error=e,c.lastFetchedAt=Date.now(),function(e,n){var t,a;const r=o.get(e);if(r)for(const e of r)null==(a=null==(t=i.get(e))?void 0:t.onError)||a.call(t,n)}(t,e)))})}function g(e){if(s)return;const{bindingId:d,sourceId:l,params:u,onUpdate:p,onError:f}=e,g=Y(l,u,()=>{c||(console.warn(`[hc-canvas/dataStore] params for "${l}" contains non-plain values; fresh query every call (no cache)`),c=!0)});!function(e,i){const c=t.get(e);if(c===i)return;if(c){const t=o.get(c);if(t&&(t.delete(e),0===t.size)){o.delete(c);const e=a.get(c);e&&(e.abort(),a.delete(c)),n.delete(c)}const i=r.get(e);if(i){try{i()}catch{}r.delete(e)}}t.set(e,i);let s=o.get(i);s||(s=new Set,o.set(i,s)),s.add(e)}(d,g),i.set(d,{onUpdate:p,onError:f});const m=n.get(g);if(m){if("success"===m.status)return void p(m.value);if("error"===m.status)return void(null==f||f(m.error));if("loading"===m.status)return}h(g,l,u)}return{request:g,subscribe:function(n){if(s)return;const{bindingId:o,sourceId:i,params:a,onUpdate:c,onError:l}=n;if(g({bindingId:o,sourceId:i,params:a,onUpdate:c,onError:l}),!e)return;const h=t.get(o);if(!h)return;let m=!0;try{const n=function(e,n){if(e.subscribe)return e.subscribe(n,e=>{if(s)return;if(!m)return;if(t.get(o)!==h)return;const n=f(h,i);n.status="success",n.value=e,n.lastFetchedAt=Date.now(),n.writeSeq=++d,u({kind:"data-source-update",cacheKey:h,sourceId:i,writeSeq:n.writeSeq,value:e}),p(h,e)})}(e,{sourceId:i,params:a});n?r.set(o,()=>{m=!1;try{n()}catch{}}):r.set(o,()=>{m=!1})}catch(e){m=!1,s||null==l||l(e)}},removeBinding:function(e,c){if(s)return;const d=!0===(null==c?void 0:c.preserveCache),l=r.get(e);if(l){try{l()}catch{}r.delete(e)}i.delete(e);const u=function(e){const n=t.get(e);if(!n)return;t.delete(e);const i=o.get(n);return i&&(i.delete(e),0===i.size&&o.delete(n)),n}(e);if(u&&!o.has(u)){const e=n.get(u);if(!d||"success"!==(null==e?void 0:e.status)){const e=a.get(u);e&&(e.abort(),a.delete(u)),n.delete(u)}}},invalidate:function(e){if(s)return;const t=[];for(const[o,i]of n)void 0!==e&&i.sourceId!==e||t.push(o);for(const e of t){const t=n.get(e);if(!t)continue;const i=o.get(e);if(!i||0===i.size){n.delete(e);const t=a.get(e);t&&(t.abort(),a.delete(e));continue}t.status="stale",h(e,t.sourceId,void 0)}},getSnapshot:function(){return{entries:Array.from(n.values()).map(e=>({cacheKey:e.cacheKey,sourceId:e.sourceId,status:e.status,value:e.value,error:e.error,lastFetchedAt:e.lastFetchedAt}))}},getCachedBySourceId:function(e,t){if(s)return;const o=Y(e,t,()=>{c||(console.warn(`[hc-canvas/dataStore] params for "${e}" contains non-plain values; cannot compute stable cache key, cache lookup will miss`),c=!0)}),i=n.get(o);return i?{value:i.value,status:i.status}:void 0},disposeAll:function(){if(!s){s=!0;for(const e of a.values())try{e.abort()}catch{}a.clear();for(const e of r.values())try{e()}catch{}r.clear(),n.clear(),t.clear(),o.clear(),i.clear(),l=null}},attachTraceBridge:function(e){return s?()=>{}:(l=e,()=>{l===e&&(l=null)})},getBindingsForCacheKey:function(e){const n=o.get(e);return n?Array.from(n):[]},get isDisposed(){return s}}}const Q=Symbol("hc:canvas:context");function Z(t={}){var o,i;const a=t.canvasId??n.DEFAULT_CANVAS_ID,r=J(t.initialDocument),c=U(),s=H(t.viewport),d=N(t.scheduler),l=W(null==(o=t.adapters)?void 0:o.data);let u=!1;const p=[];t.hooks&&p.push(t.hooks);const f=e.ref(!1),g=e.computed(()=>f.value),m=e.ref({}),y=e.computed(()=>m.value),I=e.computed(()=>{var e;const n=(null==(e=t.getMode)?void 0:e.call(t))??"design",o=function(e){switch(e){case"design":return{selectable:!0,draggable:!0,resizable:!0,keyboardMove:!0,snap:!0,grid:!1,allowOverflow:!0,locked:!1};case"preview":case"runtime":return{selectable:!1,draggable:!1,resizable:!1,keyboardMove:!1,snap:!0,grid:!1,allowOverflow:!0,locked:!1};case"inspect":return{selectable:!0,draggable:!1,resizable:!1,keyboardMove:!1,snap:!0,grid:!1,allowOverflow:!0,locked:!1}}}(n),i=r.document.layout.behavior??{};if("design"!==n){const{selectable:e,draggable:n,resizable:t,keyboardMove:a,...r}=i;return{...o,...r,...m.value}}return{...o,...i,...m.value}}),w=X(null==(i=t.adapters)?void 0:i.assets),b=e.ref("select"),k=e.ref(null),S=e.computed(()=>k.value??b.value),B=e.ref(null),M=e.computed(()=>B.value),T=e.ref(null),C=e.ref({w:0,h:0}),z=e.computed(()=>C.value),L=e.computed(()=>{const e=r.document.layout,n=C.value;return{w:x(e.canvas.width,n.w,1920),h:x(e.canvas.height,n.h,1080)}}),E=e.ref([]),P=e.computed(()=>E.value),D=e.ref(0),R=e.computed(()=>D.value>0);return{canvasId:a,document:r,selection:c,viewport:s,scheduler:d,adapters:t.adapters??{},dataStore:l,dispatch:function(e){var n,t;if(u)console.warn("[hc-canvas/context] dispatch called after dispose()");else{for(const t of p)if(!1===(null==(n=t.onBeforeAction)?void 0:n.call(t,e)))return;switch(e.type){case"addInstance":r.addInstance(e.payload.instance);break;case"removeInstance":r.removeInstance(e.payload.instanceId),c.removeFromSelection(e.payload.instanceId);break;case"updateInstance":r.updateInstance(e.payload.instanceId,e.payload.patch);break;case"moveInstance":r.moveInstance(e.payload.instanceId,e.payload.x,e.payload.y);break;case"resizeInstance":r.resizeInstance(e.payload.instanceId,e.payload.w,e.payload.h);break;case"setInstanceProp":r.setInstanceProp(e.payload.instanceId,e.payload.key,e.payload.value);break;case"addBinding":r.addBinding(e.payload.binding);break;case"removeBinding":r.removeBinding(e.payload.bindingId);break;case"updateBinding":r.updateBinding(e.payload.bindingId,e.payload.patch);break;case"updateLayout":r.updateLayout(e.payload.patch);break;case"setRootLayout":{const{rootLayout:n}=e.payload;r.updateLayout({rootLayout:null===n?void 0:n});break}case"replaceDocument":r.replaceDocument(e.payload.document),c.purgeOrphans(r.document.instances.map(e=>e.instanceId));break;case"setComponentOverride":{const{instanceId:n,override:t}=e.payload;if(void 0===r.getInstance(n)){console.warn(`[hc-canvas/context] setComponentOverride: instance "${n}" 不存在,no-op`);break}r.setComponentOverride(n,t);break}case"setInstanceLocked":r.setInstanceLocked(e.payload.instanceId,e.payload.locked);break;case"duplicateInstance":r.duplicateInstance(e.payload.instanceId,e.payload.newInstanceId,e.payload.offset??{x:20,y:20});break;case"setInstanceSize":{const{instanceId:n,size:t}=e.payload;if(null===t)r.setInstanceSize(n,null);else{const e=h(void 0,t);r.setInstanceSize(n,e??null)}break}case"setContainerLayout":{const{instanceId:n,containerLayout:t}=e.payload;if(null===t)r.setInstanceContainerLayout(n,null);else{const e=v(t);null!==e&&r.setInstanceContainerLayout(n,e)}break}case"updateLayoutBox":r.updateInstanceLayoutBox(e.payload.instanceId,e.payload.patch);break;case"updateLayoutItem":r.updateInstanceLayoutItem(e.payload.instanceId,e.payload.patch);break;case"updateRotation":r.setInstanceRotation(e.payload.instanceId,e.payload.value);break;case"select":c.select(e.payload.instanceId);break;case"toggleSelect":c.toggleSelect(e.payload.instanceId);break;case"addToSelection":c.addToSelection(e.payload.instanceId);break;case"removeFromSelection":c.removeFromSelection(e.payload.instanceId);break;case"clearSelection":c.clearSelection();break;case"selectAll":c.selectAll(e.payload.instanceIds);break;default:{const n=e;console.warn("[hc-canvas/context] unknown action",n)}}for(const n of p)null==(t=n.onAfterAction)||t.call(n,e)}},dispose:function(){u||(u=!0,f.value=!1,d.dispose(),l.disposeAll())},isBatching:g,beginBatch:function(){u||f.value||(f.value=!0)},endBatch:function(e){var n;if(!u&&f.value){for(const t of p)null==(n=t.onAfterBatch)||n.call(t,e);f.value=!1}},registerHooks:function(e){return p.push(e),()=>{const n=p.indexOf(e);n>=0&&p.splice(n,1)}},isRecordingSuppressed:R,suppressRecording:function(e){D.value++;try{return e()}finally{D.value--}},effectiveBehavior:I,interactionOptions:y,setInteractionOptions:function(e){const n={...m.value};for(const t of Object.keys(e)){const o=e[t];void 0===o?delete n[t]:n[t]=o}m.value=n},resolveAsset:function(e){return w.resolve(e)},toolMode:S,setToolMode:function(e){b.value=e},setTemporaryToolMode:function(e){k.value=e},mouseCanvasPoint:M,setMouseCanvasPoint:function(e){B.value=e},measuredStageSize:z,measuredCanvasSize:L,setMeasuredStageSize:function(e){const n=Math.max(0,Math.round(e.w)),t=Math.max(0,Math.round(e.h));C.value.w===n&&C.value.h===t||(C.value={w:n,h:t})},layoutIssues:P,setLayoutIssues:function(e){E.value=e},cannotDragLayoutManagedChildEvent:e.readonly(T),setCannotDragLayoutManagedChildEvent:function(e){T.value=e}}}function ee(n){e.provide(Q,n)}function ne(){const n=e.inject(Q);if(!n)throw new Error("[hc-canvas] useCanvasContext() called outside <CanvasProvider> / <HyperCardCanvasDesigner>. Make sure the component tree is wrapped by a provider.");return n}const te="default";function oe(e){return e.slot??te}function ie(e,n){const t=[],o=n.resolveContract,i=n.maxDepth??8,a=new Map;for(const n of e.instances)a.set(n.instanceId,n);for(const n of e.instances){if(void 0===n.parentId&&void 0!==n.slot&&n.slot!==te){ae(t,"orphan-slot",n.instanceId,`slot "${n.slot}" 没有 parentId,数据不完整`);continue}if(void 0===n.parentId)continue;if(!a.has(n.parentId)){ae(t,"missing-parent",n.instanceId,`parentId "${n.parentId}" 指向不存在的实例`);continue}"absolute"!==n.placement&&"canvas"!==n.placement||ae(t,"absolute-child-rejected",n.instanceId,"parentId + placement='absolute'|'canvas' 在 D4.5f MVP 不支持,只允许 root absolute/canvas 或 child slot/container");const e=a.get(n.parentId),i=o(e.componentVersionKey);if(!i)continue;const r=i.slotsDecl??[];if(0===r.length){ae(t,"parent-not-layout",n.instanceId,`父组件 "${e.componentId}" 不是布局组件(slotsDecl 为空)`);continue}const c=oe(n),s=re(r,c);s?s.accepts&&s.accepts.length>0&&(s.accepts.includes(n.componentId)||ae(t,"slot-not-allowed-component",n.instanceId,`slot "${c}" 不允许 componentId "${n.componentId}"(accepts: ${s.accepts.join(", ")})`)):ae(t,"invalid-slot",n.instanceId,`slot "${c}" 不在父 "${e.componentId}" 的 slotsDecl 中(可能组件升级删除了该 slot)`)}const r=new Map;for(const n of e.instances){if(void 0===n.parentId)continue;const e=oe(n),t=`${n.parentId}::${e}`;let o=r.get(t);o||(o=[],r.set(t,o)),o.push(n)}for(const[e,n]of r){if(n.length<=1)continue;const[i,r]=ce(e),c=a.get(i);if(!c)continue;const s=o(c.componentVersionKey);if(!s)continue;const d=re(s.slotsDecl??[],r);if(d&&!0!==d.multiple)for(let e=1;e<n.length;e++)ae(t,"slot-multiple-violated",n[e].instanceId,`slot "${r}" 不允许多个子实例(SlotDecl.multiple !== true)`)}const c=new Map;for(const n of e.instances)c.set(n.instanceId,0);for(const n of e.instances)0===c.get(n.instanceId)&&s(n.instanceId,[],0);function s(e,n,o){c.set(e,1);const r=a.get(e);if(o>i)return ae(t,"depth-exceeded",e,`嵌套深度 ${o} 超过上限 ${i}`),void c.set(e,2);const d=r.parentId;if(void 0===d)return void c.set(e,2);if(!a.has(d))return void c.set(e,2);const l=c.get(d);if(1===l)return ae(t,"cycle",e,`parentId 链成环:${[...n,e,d].join(" → ")}`),void c.set(e,2);2!==l?(s(d,[...n,e],o+1),c.set(e,2)):c.set(e,2)}return t}function ae(e,n,t,o){e.push({kind:n,instanceId:t,detail:o})}function re(e,n){return e.find(e=>e.name===n)}function ce(e){const n=e.indexOf("::");return[e.slice(0,n),e.slice(n+2)]}function se(e,n,t){const o=(null==e?void 0:e.onError)??"log";switch(o){case"stop":return"stop";case"log":return console.error(`[hc-canvas/wirePageBindings] binding "${t}" threw:`,n),"continue";case"continue":return"continue";default:return console.error(`[hc-canvas/wirePageBindings] binding "${t}" threw (unknown onError="${String(o)}"):`,n),"continue"}}function de(e,n){return e&&"passthrough"!==e.kind?"static"===e.kind?function(e){if("function"==typeof structuredClone)try{return structuredClone(e)}catch{}try{return JSON.parse(JSON.stringify(e))}catch{return[...e]}}(e.args):"pickPath"===e.kind?function(e,n){const t=[];let o;for(const i of e){const e=le(n,i.from);void 0===i.to?t.push(e):"number"==typeof i.to?(ue(t,i.to+1),t[i.to]=e):(o||(t.length>0&&"object"==typeof t[0]&&null!==t[0]&&!Array.isArray(t[0])?o=t[0]:(o={},0===t.length?t.push(o):t[0]=o)),o[i.to]=e)}return t}(e.paths,n):[n]:[n]}function le(e,n){if(""===n)return e;const t=n.split(".");let o=e;for(const e of t){if(null==o)return;if("object"!=typeof o)return;o=o[e]}return o}function ue(e,n){for(;e.length<n;)e.push(void 0)}function pe(e,n,t,o){e.debouncePendingTimer=null;const i=e.debounceDirty,a=e.debouncePendingChainId,r=e.debouncePendingPayload;e.debouncePendingChainId=null,e.debouncePendingPayload=void 0,e.debounceDirty=!1,t&&i&&null!==a&&he(n,e).pass&&o(r,a)}function fe(e,n,t){e.throttleTrailingTimer=null;const o=e.throttleTrailingPendingChainId,i=e.throttleTrailingPendingPayload;e.throttleTrailingPendingChainId=null,e.throttleTrailingPendingPayload=void 0,e.throttleWindowStartTs=null,null!==o&&(n.once&&e.onceConsumed||(n.once&&(e.onceConsumed=!0),e.throttleLastFireTs=ve(),t(i,o)))}function he(e,n){const t=e.throttle;if(t){t.leading;const e=t.windowMs,o=ve(),i=n.throttleLastFireTs;if(null!==i&&o-i<e)return{pass:!1,reason:"throttle-window"};n.throttleLastFireTs=o}if(e.once){if(n.onceConsumed)return{pass:!1,reason:"once-consumed"};n.onceConsumed=!0}return{pass:!0}}function ge(e){return!(!e||!(e.throttle&&!1===e.throttle.leading&&!1===e.throttle.trailing||e.debounce&&!1===e.debounce.leading&&!1===e.debounce.trailing))}let me=()=>Date.now();function ve(){return me()}let ye=0;function Ie(t){var o,i;const a=t.canvasId,{source:r}=t,c=t.dataStore,s=new Set;let d="off",l=0,u=!1;const p="w"+ ++ye;let f=0;function h(){return`${p}-${++f}`}let g=0;function m(e){L.hasListeners("binding:trace")&&L.emit("binding:trace",{canvasId:a,ts:Date.now(),seq:++g,...e})}let v=!1,y=null;function I(){v&&(y&&y(),y=null,v=!1)}const w=new Map,x=new Map,b=new Set,k=new Set,S=new Set,B=new Set,M=new Map;let T=new Set;const C=[],z=[],L=function(e){const n=new Set,t=new Set,o=new Set;return{on(i,a){var r;if("binding:fire"===i){const e=a;return n.add(e),()=>n.delete(e)}if("binding:error"===i){const e=a;return t.add(e),()=>t.delete(e)}const c=a;return o.add(c),null==(r=null==e?void 0:e.onTraceListenerCountChange)||r.call(e,o.size),()=>{var n;o.delete(c),null==(n=null==e?void 0:e.onTraceListenerCountChange)||n.call(e,o.size)}},emit(e,i){if("binding:fire"===e)for(const e of n)try{e(i)}catch(e){console.error("[hc-canvas/wirePageBindings] listener threw",e)}else if("binding:error"===e)for(const e of t)try{e(i)}catch(e){console.error("[hc-canvas/wirePageBindings] listener threw",e)}else for(const e of o)try{e(i)}catch(e){console.error("[hc-canvas/wirePageBindings] trace listener threw",e)}},hasListeners:e=>"binding:fire"===e?n.size>0:"binding:error"===e?t.size>0:o.size>0,clear(){n.clear(),t.clear(),o.clear()}}}({onTraceListenerCountChange:function(e){e>0?!v&&c&&(y=c.attachTraceBridge(e=>{if(u)return;const n=c.getBindingsForCacheKey(e.cacheKey);for(const t of n)m({kind:e.kind,bindingId:t,cacheKey:e.cacheKey,sourceId:e.sourceId,writeSeq:e.writeSeq,reason:e.reason,payload:e.value})}),v=!0):I()}}),E=function(e){let n=[],t=200,o=null,i=null;return{start:function(a){i&&(i(),i=null,n=[]),t=(null==a?void 0:a.capacity)??200,o=(null==a?void 0:a.filterKinds)&&a.filterKinds.length>0?new Set(a.filterKinds):null,i=e.on("binding:trace",e=>{o&&!o.has(e.kind)||(n.push(e),n.length>t&&n.shift())})},stop:function(){i&&(i(),i=null);const e=n.slice();return n=[],e},snapshot:function(){return n.slice()},get isRunning(){return null!==i}}}({on:(e,n)=>L.on(e,n)});function P(e){return void 0===e.canvasId||e.canvasId===a}function D(e){for(const n of F(e))if(void 0!==n.canvasId&&n.canvasId!==a)return!0;return!1}function R(e){return JSON.stringify({id:e.id,type:e.type,disabled:e.disabled??!1,source:e.source,target:e.target,mapping:e.mapping??null,schedule:e.schedule??null,errorPolicy:e.errorPolicy??null})}function O(e,n){return void 0===n||R(e)!==n}function $(){var e;return(null==(e=r.getDocument())?void 0:e.bindings)??[]}function A(e){return $().find(n=>n.id===e)}function N(e){try{e()}catch(e){console.error("[hc-canvas/wirePageBindings] cleanup threw",e)}}function j(e,n){L.emit("binding:fire",e),m({kind:"fire",bindingId:e.bindingId,chainId:n,payload:e.payload,args:e.args})}function V(e,n){L.emit("binding:error",e),m({kind:(null==n?void 0:n.traceKind)??"error",bindingId:e.bindingId,chainId:null==n?void 0:n.chainId,code:e.code,message:e.message,detail:e.detail})}function q(e,n=!1){const t=w.get(e);if(t)for(const e of t)N(e);w.delete(e);const o=x.get(e);if(o){const n=function(e){const n={};return null!==e.debouncePendingTimer&&(clearTimeout(e.debouncePendingTimer),e.debouncePendingTimer=null,null!==e.debouncePendingChainId&&(n.droppedDebounce={chainId:e.debouncePendingChainId,payload:e.debouncePendingPayload})),null!==e.debouncePendingTimer||null===e.debouncePendingChainId||n.droppedDebounce||(n.droppedDebounce={chainId:e.debouncePendingChainId,payload:e.debouncePendingPayload}),e.debouncePendingChainId=null,e.debouncePendingPayload=void 0,e.debounceDirty=!1,null!==e.throttleTrailingTimer&&(clearTimeout(e.throttleTrailingTimer),e.throttleTrailingTimer=null),null!==e.throttleTrailingPendingChainId&&(n.droppedThrottleTrailing={chainId:e.throttleTrailingPendingChainId,payload:e.throttleTrailingPendingPayload}),e.throttleTrailingPendingChainId=null,e.throttleTrailingPendingPayload=void 0,e.throttleWindowStartTs=null,n}(o);n.droppedDebounce&&m({kind:"scheduled-dropped",bindingId:e,chainId:n.droppedDebounce.chainId,payload:n.droppedDebounce.payload}),n.droppedThrottleTrailing&&m({kind:"scheduled-dropped",bindingId:e,chainId:n.droppedThrottleTrailing.chainId,payload:n.droppedThrottleTrailing.payload}),x.delete(e)}k.delete(e),M.delete(e),S.delete(e),B.delete(e),s.delete(e),c&&c.removeBinding(e,{preserveCache:n})}function _(e=!1){for(const n of[...w.keys()])q(n,e)}function K(e){if(u)return;if(w.has(e.id))return;if(D(e))return void(S.has(e.id)||(V({bindingId:e.id,code:"unsupported-cross-canvas"}),S.add(e.id),m({kind:"wire-skipped",bindingId:e.id,reason:"unsupported-cross-canvas"})));const t=function(e){return e.disabled?"disabled":b.has(e.id)?"stopped":null}(e);if(t)return void m({kind:"wire-skipped",bindingId:e.id,reason:t});if("data-preview"===d&&"dataSource"!==e.source.kind)return void m({kind:"wire-skipped",bindingId:e.id,reason:"mode-matrix-data-preview"});ge(e.schedule)&&!B.has(e.id)&&(console.warn(`[hc-canvas/wirePageBindings] schedule.{throttle|debounce}.{leading=false,trailing=false} 永远不会 fire (binding "${e.id}")`),B.add(e.id));const o=[];switch(e.source.kind){case"instanceEvent":{const t=n.getInstance(e.source.instanceId,a);if(!t)return void k.add(e.id);const i=e.source.event,r=t.on(i,n=>U(e,n));o.push(r);break}case"lifecycle":case"page":break;case"dataSource":{if(!c)return void(s.has(e.id)||(V({bindingId:e.id,code:"no-data-adapter"}),m({kind:"wire-skipped",bindingId:e.id,reason:"no-data-adapter"}),s.add(e.id)));const n=e.source,t="change"===n.watch,o=n=>U(e,n),i=n=>{V({bindingId:e.id,code:"data-query-failed",message:n instanceof Error?n.message:String(n),detail:n}),"stop"===se(e.errorPolicy,n,e.id)&&b.add(e.id)};m({kind:"data-query-started",bindingId:e.id,sourceId:n.sourceId}),t?c.subscribe({bindingId:e.id,sourceId:n.sourceId,onUpdate:o,onError:i}):c.request({bindingId:e.id,sourceId:n.sourceId,onUpdate:o,onError:i});break}default:return}w.set(e.id,o),M.set(e.id,R(e))}function J(){for(const e of $())K(e)}function U(e,n){if(u)return;if("off"===d)return;if(b.has(e.id))return void m({kind:"stopped-skipped",bindingId:e.id});if(D(e))return;if(l>=8){const n=h();return void V({bindingId:e.id,code:"cycle-detected"},{chainId:n,traceKind:"cycle-detected"})}const t=h(),o=function(e,n,t,o){return ge(e)?{fire:!1,deferred:!1,reason:"schedule-no-fire"}:(null==e?void 0:e.debounce)?function(e,n,t,o){const i=e.debounce,a=i.leading??!1,r=i.trailing??!0,c=i.windowMs;if(null===n.debouncePendingTimer){if(a){const t=he(e,n);return t.pass?(n.debounceLeadingFireTs=ve(),n.debounceDirty=!1,n.debouncePendingPayload=void 0,n.debouncePendingChainId=null,{fire:!0,deferred:!1,scheduleDeferred:t=>{n.debouncePendingTimer=setTimeout(()=>{pe(n,e,r,t)},c)}}):{fire:!1,deferred:!1,reason:t.reason}}return n.debouncePendingPayload=t,n.debouncePendingChainId=o,n.debounceDirty=!0,{fire:!1,deferred:!0,scheduleDeferred:t=>{n.debouncePendingTimer=setTimeout(()=>{pe(n,e,r,t)},c)}}}const s=null!==n.debouncePendingChainId?{chainId:n.debouncePendingChainId,payload:n.debouncePendingPayload}:void 0;return n.debounceDirty=!0,r&&(n.debouncePendingPayload=t,n.debouncePendingChainId=o),clearTimeout(n.debouncePendingTimer),n.debouncePendingTimer=null,r?{fire:!1,deferred:!0,droppedByReschedule:s,scheduleDeferred:t=>{n.debouncePendingTimer=setTimeout(()=>{pe(n,e,r,t)},c)}}:{fire:!1,deferred:!1,reason:"debounce-window",scheduleDeferred:t=>{n.debouncePendingTimer=setTimeout(()=>{pe(n,e,r,t)},c)}}}(e,n,t,o):function(e,n,t,o){const i=null==e?void 0:e.throttle;if(!i)return function(e,n){if(null==e?void 0:e.once){if(n.onceConsumed)return{fire:!1,deferred:!1,reason:"once-consumed"};n.onceConsumed=!0}return{fire:!0,deferred:!1}}(e,n);const a=i.leading??!0,r=i.trailing??!1,c=i.windowMs,s=ve();if(a){const i=n.throttleLastFireTs;if(!(null!==i&&s-i<c))return(null==e?void 0:e.once)&&n.onceConsumed?{fire:!1,deferred:!1,reason:"once-consumed"}:((null==e?void 0:e.once)&&(n.onceConsumed=!0),n.throttleLastFireTs=s,{fire:!0,deferred:!1});if(!r)return{fire:!1,deferred:!1,reason:"throttle-window"};const a=null!==n.throttleTrailingPendingChainId?{chainId:n.throttleTrailingPendingChainId,payload:n.throttleTrailingPendingPayload}:void 0;if(n.throttleTrailingPendingPayload=t,n.throttleTrailingPendingChainId=o,null===n.throttleTrailingTimer){const t=c-(s-i);return{fire:!1,deferred:!0,scheduleDeferred:o=>{n.throttleTrailingTimer=setTimeout(()=>{fe(n,e,o)},t)}}}return{fire:!1,deferred:!1,reason:"throttle-window",droppedByReschedule:a}}if(null===n.throttleWindowStartTs)return n.throttleWindowStartTs=s,n.throttleTrailingPendingPayload=t,n.throttleTrailingPendingChainId=o,{fire:!1,deferred:!0,reason:"leading-disabled",scheduleDeferred:t=>{n.throttleTrailingTimer=setTimeout(()=>{fe(n,e,t)},c)}};const d=null!==n.throttleTrailingPendingChainId?{chainId:n.throttleTrailingPendingChainId,payload:n.throttleTrailingPendingPayload}:void 0;return n.throttleTrailingPendingPayload=t,n.throttleTrailingPendingChainId=o,{fire:!1,deferred:!1,reason:"throttle-window",droppedByReschedule:d}}(e,n,t,o)}(e.schedule,function(e){let n=x.get(e);return n||(n={onceConsumed:!1,throttleLastFireTs:null,throttleWindowStartTs:null,throttleTrailingPendingPayload:void 0,throttleTrailingPendingChainId:null,throttleTrailingTimer:null,debouncePendingTimer:null,debouncePendingPayload:void 0,debouncePendingChainId:null,debounceDirty:!1,debounceLeadingFireTs:null},x.set(e,n)),n}(e.id),n,t),i=function(e){if(e)return e.throttle?{kind:"throttle",windowMs:e.throttle.windowMs,leading:e.throttle.leading,trailing:e.throttle.trailing}:e.debounce?{kind:"debounce",windowMs:e.debounce.windowMs,leading:e.debounce.leading,trailing:e.debounce.trailing}:void 0}(e.schedule);o.droppedByReschedule&&m({kind:"scheduled-dropped",bindingId:e.id,chainId:o.droppedByReschedule.chainId,payload:o.droppedByReschedule.payload,schedule:i}),o.scheduleDeferred&&o.scheduleDeferred((n,t)=>{u||(m({kind:"scheduled-flushed",bindingId:e.id,chainId:t,payload:n,schedule:i}),H(e,n,t))}),o.reason?m({kind:"scheduled-skipped",bindingId:e.id,chainId:t,reason:o.reason,payload:n,schedule:i}):!o.deferred||o.fire?o.fire&&H(e,n,t):m({kind:"scheduled-deferred",bindingId:e.id,chainId:t,payload:n,schedule:i})}function H(e,t,o){if(u)return;const i=n.getInstance(e.target.instanceId,a);if(!i)return void V({bindingId:e.id,code:"target-not-mounted"},{chainId:o});let r,c;try{r=de(e.mapping,t)}catch(n){return m({kind:"mapping-failed",bindingId:e.id,chainId:o,message:n instanceof Error?n.message:String(n),detail:n}),void("stop"===se(e.errorPolicy,n,e.id)&&b.add(e.id))}if("instanceDataInput"===e.target.kind){const n=i.vm.custom,a=null==n?void 0:n[e.target.key];if(!a||"object"!=typeof a||!0!==a.dataInput)return void V({bindingId:e.id,code:"unknown-target-data-input",message:n&&e.target.key in n?`target.key "${e.target.key}" on instance "${e.target.instanceId}" is not declared with dataInput:true`:`target.key "${e.target.key}" not declared on instance "${e.target.instanceId}"`},{chainId:o});try{i.setDataInput(e.target.key,r[0])}catch(n){return"stop"===se(e.errorPolicy,n,e.id)&&b.add(e.id),void V({bindingId:e.id,code:"invoke-failed",message:n instanceof Error?n.message:String(n),detail:n},{chainId:o})}return void j({bindingId:e.id,source:e.source,target:e.target,payload:t,args:r},o)}l++;try{c=function(e,n,t){switch(n.kind){case"instanceMethod":return e.call(n.method,...t);case"instanceEmit":return void e.emit(n.event,t[0]);default:return}}(i,e.target,r),j({bindingId:e.id,source:e.source,target:e.target,payload:t,args:r},o)}catch(n){return"stop"===se(e.errorPolicy,n,e.id)&&b.add(e.id),void V({bindingId:e.id,code:"invoke-failed",message:n instanceof Error?n.message:String(n),detail:n},{chainId:o})}finally{l--}var s;"object"==typeof(s=c)&&null!==s&&"function"==typeof s.then&&Promise.resolve(c).catch(n=>{u||("stop"===se(e.errorPolicy,n,e.id)&&b.add(e.id),V({bindingId:e.id,code:"invoke-failed",message:n instanceof Error?n.message:String(n),detail:n},{chainId:o}))})}const X=null==(o=r.onAction)?void 0:o.call(r,e=>{var n,t,o,i;if(u)return;if("off"===d)return;const a=e;if(a&&"object"==typeof a)switch(a.type){case"addBinding":{const e=null==(t=null==(n=a.payload)?void 0:n.binding)?void 0:t.id;if(!e)return;const o=A(e);o&&K(o);break}case"updateBinding":{const e=null==(o=a.payload)?void 0:o.bindingId;if(!e)return;q(e);const n=A(e);n&&K(n);break}case"removeBinding":{const e=null==(i=a.payload)?void 0:i.bindingId;if(!e)return;q(e),b.delete(e);break}case"replaceDocument":_(),b.clear(),k.clear(),J();break;case"removeInstance":!function(){const e=new Set($().map(e=>e.id));for(const n of[...w.keys()])e.has(n)||(q(n),b.delete(n));for(const e of $())K(e)}()}});X&&C.push(X);const Y=null==(i=r.onDocumentChange)?void 0:i.call(r,()=>{if(u)return;if("off"===d)return;const e=$(),n=new Set(e.map(e=>e.id)),t=new Set(w.keys());for(const e of t)n.has(e)||q(e);for(const n of e)w.has(n.id)?O(n,M.get(n.id))&&(q(n.id),K(n)):K(n)});function G(){return new Set(n.listInstances({canvasId:a}).map(e=>e.instanceId))}Y&&C.push(Y),T=G();const W=e.watch(n.registryVersion,()=>{if(u)return;if("off"===d)return;const e=G(),n=we(e,T),t=we(T,e);T=e;for(const n of[...k]){const t=A(n);t?Q(t,e)&&(k.delete(n),K(t)):k.delete(n)}if(t.size>0)for(const e of[...w.keys()]){const n=A(e);n&&F(n).some(e=>P(e)&&t.has(e.instanceId))&&(q(e),k.add(e))}!function(e){if(0!==e.size)for(const n of $())"lifecycle"===n.source.kind&&"mounted"===n.source.hook&&P({canvasId:n.source.canvasId,instanceId:n.source.instanceId})&&e.has(n.source.instanceId)&&U(n,{instanceId:n.source.instanceId,hook:"mounted"})}(n),function(e){if(0!==e.size)for(const n of $())"lifecycle"===n.source.kind&&"unmounted"===n.source.hook&&P({canvasId:n.source.canvasId,instanceId:n.source.instanceId})&&e.has(n.source.instanceId)&&U(n,{instanceId:n.source.instanceId,hook:"unmounted"})}(t)},{flush:"post"});function Q(e,n){for(const t of F(e)){if(!P(t))return!1;if(!n.has(t.instanceId))return!1}return!0}return z.push(W),{setMode:function(e){u||e!==d&&(_(!0),b.clear(),k.clear(),d=e,"off"!==e&&J(),"runtime"===e&&function(){for(const e of $())"page"===e.source.kind&&"pageInit"===e.source.hook&&U(e,{hook:"pageInit"})}())},getMode:()=>d,testBinding(e,t){const o=[],i=A(e);if(!i)return o.push({bindingId:e,phase:"skipped",details:{reason:"binding-not-found"}}),o;if(i.disabled)return o.push({bindingId:e,phase:"skipped",details:{reason:"disabled"}}),o;if(D(i))return o.push({bindingId:e,phase:"skipped",details:{reason:"unsupported-cross-canvas"}}),o;let r;try{r=de(i.mapping,t),o.push({bindingId:e,phase:"mapping",details:{payload:t,args:r}})}catch(n){return o.push({bindingId:e,phase:"error",details:{stage:"mapping",message:n instanceof Error?n.message:String(n)}}),o}const c=n.getInstance(i.target.instanceId,a);if(!c)return o.push({bindingId:e,phase:"skipped",details:{reason:"target-not-mounted"}}),o;if("instanceDataInput"===i.target.kind){const n=c.vm.custom,t=null==n?void 0:n[i.target.key];if(!t||"object"!=typeof t||!0!==t.dataInput)return o.push({bindingId:e,phase:"skipped",details:{reason:"unknown-target-data-input",key:i.target.key}}),o}return o.push({bindingId:e,phase:"calling-target",details:{target:i.target,dryRun:!0}}),o.push({bindingId:e,phase:"done",details:{args:r}}),o},on:(e,n)=>L.on(e,n),startTracing(e){E.start(e)},stopTracing:()=>E.stop(),getTraceBuffer:()=>E.snapshot(),dispose:function(){if(!u){"runtime"===d&&function(){for(const e of $())"page"===e.source.kind&&"pageBeforeUnmount"===e.source.hook&&U(e,{hook:"pageBeforeUnmount"})}(),u=!0,_();for(const e of C)N(e);for(const e of z)N(e);C.length=0,z.length=0,b.clear(),k.clear(),S.clear(),B.clear(),M.clear(),T.clear(),x.clear(),E.stop(),L.clear(),I(),d="off"}}}}function we(e,n){const t=new Set;for(const o of e)n.has(o)||t.add(o);return t}const xe=["display","gridTemplateColumns","gridTemplateRows","gridAutoFlow","flexDirection","flexWrap","gap","rowGap","columnGap","justifyContent","alignItems","position"];function be(e,t){const o="string"==typeof(null==e?void 0:e.js)?e.js:"",i="string"==typeof(null==e?void 0:e.html)?e.html:"",a=n.parseComponentSource(o,i);return!a.ok&&(null==t?void 0:t.fallback)?t.fallback:{propsDecl:a.propsDecl.map(Se),emitsDecl:a.emitsDecl.map(Me),methodsDecl:a.methodsDecl.map(Be),slotsDecl:a.slotsDecl.map(Te),modelDecl:a.modelDecl.map(Ce),dataInputsDecl:a.dataInputsDecl.map(ze),dataOutputsDecl:a.dataOutputsDecl.map(ze)}}function ke(e){if("string"===e||"number"===e||"boolean"===e||"object"===e||"array"===e||"any"===e)return e}function Se(e){const n=e.key,t="string"==typeof e.name?e.name:void 0;return{key:n,type:ke(e.type)??"string",...void 0!==e.value?{value:e.value}:{},...t&&t!==n?{label:t}:{},...e.enum?{enum:e.enum}:{}}}function Be(e){return{key:e.name,...e.params?{params:e.params}:{}}}function Me(e){return{event:e.event}}function Te(e){return{name:e.name,...void 0!==e.multiple?{multiple:e.multiple}:{},...void 0!==e.accepts?{accepts:e.accepts}:{},...void 0!==e.maxChildren?{maxChildren:e.maxChildren}:{},...void 0!==e.label?{label:e.label}:{}}}function Ce(e){const n=ke(e.type);return{key:e.key,...void 0!==e.prop?{prop:e.prop}:{},...void 0!==e.event?{event:e.event}:{},...n?{type:n}:{},...void 0!==e.defaultValue?{defaultValue:e.defaultValue}:{}}}function ze(e){const n=ke(e.type);return{key:e.key,...n?{type:n}:{},...void 0!==e.label?{label:e.label}:{}}}const Le=["data-hc-canvas-id"],Ee=["data-instance-id","data-hc-hidden"],Pe={key:0,class:"hc-page-instance-fallback",style:{width:"100%",height:"100%",border:"2px dashed #f59e0b",background:"#fef3c7",color:"#92400e",padding:"8px",fontSize:"11px",fontFamily:"monospace",overflow:"hidden",borderRadius:"4px",boxSizing:"border-box"}},De={style:{opacity:"0.8"}},Re={style:{opacity:"0.6","margin-top":"4px","word-break":"break-all"}},Oe={key:2,class:"hc-page-instance-skeleton",style:{width:"100%",height:"100%",background:"linear-gradient(90deg, #f1f5f9 0%, #e2e8f0 50%, #f1f5f9 100%)",backgroundSize:"200% 100%",animation:"hc-skeleton-shimmer 1.5s infinite ease-in-out",borderRadius:"4px",boxSizing:"border-box"}},$e=["data-instance-id","data-hc-placement","data-hc-hidden"],Ae={key:0,class:"hc-page-instance-fallback",style:{width:"100%",height:"100%",border:"2px dashed #f59e0b",background:"#fef3c7",color:"#92400e",padding:"8px","font-size":"11px","font-family":"monospace",overflow:"hidden","border-radius":"4px","box-sizing":"border-box"}},Ne={style:{opacity:"0.6"}},Fe=["title"],je={key:1,class:"hc-page-renderer-empty",style:{padding:"24px",color:"#64748b","font-size":"13px"}},Ve=e.defineComponent({__name:"HyperCardPageRenderer",props:{payload:{},document:{},componentSourceMap:{},schedulerOptions:{},canvasId:{},adapters:{}},setup(t,{expose:o}){var i,a;const r=t,l=r.canvasId??function(){var e;const n="undefined"!=typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;return`auto-${(null==(e=null==n?void 0:n.randomUUID)?void 0:e.call(n).replace(/-/g,"").slice(0,8))??Math.random().toString(36).slice(2,10)}`}();e.provide(n.HC_CANVAS_ID_KEY,l);const u=N(r.schedulerOptions),p=e.ref(null);let f=!1;e.onMounted(()=>{U||e.nextTick(()=>{var e;if(f)return;if(!p.value)return;if("fill"!==(null==(e=K.value)?void 0:e.canvas.height.mode))return;const n=p.value.parentElement;n&&(n.getBoundingClientRect().height>0||(f=!0,console.warn("[hypercard] HyperCardPageRenderer 父容器高度为 0,fill 模式画布不可见。请给父容器设置明确 height 或改用 px 模式。")))})}),e.onBeforeUnmount(()=>{Y.value&&(Y.value.dispose(),Y.value=null),u.dispose(),G&&G.disposeAll(),l!==n.DEFAULT_CANVAS_ID&&n.disposeCanvas(l)});const h=e.ref(new Map),g=e.ref(new Map),m=new Map,v=e.ref(!1);let y=null;function I(){v.value=!1,y&&clearTimeout(y),y=setTimeout(()=>{v.value=!0},300)}function w(e,n){const t=new Map;if(n.querySelectorAll("[data-hc-slot]").forEach(e=>{if(e.closest("[data-instance-id]")!==n)return;const o=e.getAttribute("data-hc-slot")||te;t.has(o)||t.set(o,e)}),function(e,n){if(!e||e.size!==n.size)return!1;for(const[t,o]of n)if(e.get(t)!==o)return!1;return!0}(g.value.get(e),t))return;const o=new Map(g.value);o.set(e,t),g.value=o,x(e,t)}function x(e,n){const t=n.get(te);if(!t)return;const o=T.value,i=null==o?void 0:o.instances.find(n=>n.instanceId===e);!function(e,n){!function(e){const n=e.style;for(const e of xe)n[e]=""}(e);const t=null==n?void 0:n.mode;if(!n||"none"===t||void 0===t)return;if("free"===t)return void(e.style.position="relative");const o=S(n);o&&Object.assign(e.style,o)}(t,null==i?void 0:i.containerLayout)}function k(e,n){const t=h.value.get(e);n&&n!==t?(h.value.set(e,n),u.register(e,n),function(e,n){const t=m.get(e);t&&t.disconnect(),w(e,n);const o=new MutationObserver(()=>w(e,n));o.observe(n,{childList:!0,subtree:!0}),m.set(e,o)}(e,n)):!n&&t&&(u.unregister(e),h.value.delete(e),function(e){const n=m.get(e);if(n&&(n.disconnect(),m.delete(e)),g.value.has(e)){const n=new Map(g.value);n.delete(e),g.value=n}}(e))}e.onMounted(I),e.watch(g,I),e.onBeforeUnmount(()=>{for(const e of m.values())e.disconnect();m.clear(),g.value=new Map,y&&clearTimeout(y)});const T=e.computed(()=>{var e;const n=(null==(e=r.payload)?void 0:e.document)??r.document??null;return n?d(s(c(n))):null});e.watch(T,()=>{e.nextTick(()=>function(){for(const[e,n]of g.value)x(e,n)}())},{flush:"post"});const C=e.computed(()=>function(e){const n={};for(const t of Object.keys(e)){const o=e[t],i=o.source;o&&"ok"===o.status&&i&&("string"==typeof i.html||"string"==typeof i.js)?n[t]={...o,contract:be({html:i.html??"",js:i.js??"",css:i.css??""},{fallback:o.contract})}:n[t]=o}return n}(r.payload?r.payload.componentVersions:r.componentSourceMap??{})),z=e.computed(()=>{const e=T.value,n=C.value;return e?e.instances.map(t=>{var o;const i=n[t.componentVersionKey]??null,a=(null==(o=e.componentOverrides)?void 0:o[t.instanceId])??null,r=a&&a.baseVersionKey===t.componentVersionKey?a:null,c=r?`${r.baseVersionKey}#override:${t.instanceId}`:t.componentVersionKey;if(r)return{instance:t,asset:i,override:r,renderSource:r.source,scopeId:c,status:"ok"};if(!i)return{instance:t,asset:null,override:null,renderSource:null,scopeId:c,status:"missing-source",invalidReason:`componentVersionKey "${t.componentVersionKey}" not in sourceMap`};if("ok"!==i.status)return{instance:t,asset:i,override:null,renderSource:null,scopeId:c,status:"unavailable",invalidReason:i.invalidReason??`component version unavailable (${i.status})`};let s=null;return s=function(e){return!!e&&!0===e.isDraft}(i)?i.lastGoodSource:i.source??null,s?{instance:t,asset:i,override:null,renderSource:s,scopeId:c,status:"ok"}:{instance:t,asset:i,override:null,renderSource:null,scopeId:c,status:"missing-source",invalidReason:"asset.status=ok but source missing"}}):[]});function L(e){const n=C.value[e];return null==n?void 0:n.contract}const E=e.computed(()=>{const e=T.value;return e?ie(e,{resolveContract:L}):[]}),P=e.inject(Q,null);e.watch(E,e=>{P&&"function"==typeof P.setLayoutIssues&&P.setLayoutIssues(e)},{immediate:!0});const D=e.computed(()=>{const e=new Set;for(const n of E.value)"missing-parent"!==n.kind&&"invalid-slot"!==n.kind&&"parent-not-layout"!==n.kind&&"orphan-slot"!==n.kind&&"cycle"!==n.kind&&"absolute-child-rejected"!==n.kind||e.add(n.instanceId);return e}),R=e.computed(()=>z.value.filter(e=>void 0===e.instance.parentId)),A=e.computed(()=>z.value.filter(e=>void 0!==e.instance.parentId&&O(e.instance.placement)));function F(e){const n=e.layoutBox??{x:e.rect.x,y:e.rect.y,width:e.rect.w,height:e.rect.h,widthMode:"px",heightMode:"px",overflow:"hidden"},t=function(e){const n=T.value;if(n)return $(K.value??void 0,n.instances,e.instanceId)}(e),o=b(n,e.zIndex,e.rotation,t,function(e){var n,t;const o=T.value;if(!o)return;if(void 0===e.parentId){const e=null==(n=K.value)?void 0:n.rootLayout;return"split"===(null==e?void 0:e.mode)?e.direction:void 0}const i=null==(t=o.instances.find(n=>n.instanceId===e.parentId))?void 0:t.containerLayout;return"split"===(null==i?void 0:i.mode)?i.direction:void 0}(e)),i=B(e.layoutItem,t);return i&&Object.assign(o,i),o}const j=e.computed(()=>{var e;return S(null==(e=K.value)?void 0:e.rootLayout)});function V(e){if(!e.parentId)return null;const n=g.value.get(e.parentId);return n?n.get(oe(e))??null:null}function q(e){return{position:"absolute",left:"8px",top:8+28*A.value.indexOf(e)+"px",padding:"4px 8px",background:"hsla(40, 90%, 50%, 0.95)",color:"#5b3a00",fontSize:"11px",fontFamily:"ui-monospace, monospace",borderRadius:"4px",zIndex:9999,maxWidth:"60%",textOverflow:"ellipsis",overflow:"hidden",whiteSpace:"nowrap"}}function _(e){return"实例 "+e.instance.instanceId+':slot "'+oe(e.instance)+'" 不可用'}const K=e.computed(()=>{var e;return(null==(e=T.value)?void 0:e.layout)??null}),J=e.computed(()=>{if(!K.value)return null;if(U){const e=U.measuredCanvasSize.value;return{width:`${e.w}px`,height:`${e.h}px`,overflow:K.value.canvas.overflow??"hidden"}}return{width:M(K.value.canvas.width),height:M(K.value.canvas.height),overflow:K.value.canvas.overflow??"hidden"}}),U=e.inject(Q,void 0),H=U?null:X(null==(i=r.adapters)?void 0:i.assets),Y=e.shallowRef(null),G=U||!(null==(a=r.adapters)?void 0:a.data)?null:W(r.adapters.data);if(!U){const n=Ie({canvasId:l,source:{getDocument:()=>T.value,onDocumentChange:n=>e.watch(T,n,{flush:"post"})},dataStore:G??void 0});Y.value=n,e.nextTick(()=>{n.setMode("runtime")})}o({binding:Y,data:U?{invalidateDataSource(e){U.dataStore.invalidate(e)},getDataSourceSnapshot:()=>U.dataStore.getSnapshot(),getCachedBySourceId:(e,n)=>U.dataStore.getCachedBySourceId(e,n)}:G?{invalidateDataSource(e){G.invalidate(e)},getDataSourceSnapshot:()=>G.getSnapshot(),getCachedBySourceId:(e,n)=>G.getCachedBySourceId(e,n)}:null});const Z=e.ref(null);let ee=0;e.watch(()=>{var e,n;return null==(n=null==(e=K.value)?void 0:e.background)?void 0:n.image},e=>{ee++;const n=ee;if(!e)return void(Z.value=null);const t=(o=e,U?U.resolveAsset(o):H.resolve(o));var o;"string"!=typeof t?(Z.value=null,t.then(t=>{var o,i;n===ee&&(null==(i=null==(o=K.value)?void 0:o.background)?void 0:i.image)===e&&(Z.value=t||null)},()=>{n===ee&&(Z.value=null)})):Z.value=t||null},{immediate:!0,deep:!0});const ne=e.computed(()=>{var e;const n=null==(e=K.value)?void 0:e.background;if(!n)return null;const t={position:"absolute",inset:"0",pointerEvents:"none",zIndex:-1};return n.color&&(t.background=n.color),n.image&&Z.value&&(t.backgroundImage=`url("${Z.value}")`,t.backgroundRepeat="repeat"===n.imageFit?"repeat":"no-repeat",t.backgroundPosition=n.imagePosition??"center","stretch"===n.imageFit?t.backgroundSize="100% 100%":n.imageFit&&"repeat"!==n.imageFit&&"center"!==n.imageFit&&(t.backgroundSize=n.imageFit)),void 0!==n.opacity&&(t.opacity=n.opacity),t});return(t,o)=>K.value&&J.value?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"rootEl",ref:p,class:"hc-page-renderer","data-hc-canvas-id":e.unref(l),style:e.normalizeStyle({position:"relative",...J.value,...j.value??{}})},[ne.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"hc-canvas-bg","data-hc-canvas-bg":"",style:e.normalizeStyle(ne.value)},null,4)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(R.value,t=>e.withDirectives((e.openBlock(),e.createElementBlock("div",{key:t.instance.instanceId,ref_for:!0,ref:e=>k(t.instance.instanceId,e),"data-instance-id":t.instance.instanceId,"data-hc-hidden":t.instance.hidden?"true":void 0,style:e.normalizeStyle(F(t.instance))},["ok"===t.status&&t.renderSource?e.unref(u).isMounted(t.instance.instanceId)?(e.openBlock(),e.createBlock(e.unref(n.RuntimeBox),{key:1,"canvas-id":e.unref(l),"instance-id":t.instance.instanceId,"component-id":t.instance.componentId,"scope-id":t.scopeId,"html-source":t.renderSource.html,"js-source":t.renderSource.js,"css-source":t.renderSource.css,"custom-values":{...t.instance.props,__containerLayout:t.instance.containerLayout}},null,8,["canvas-id","instance-id","component-id","scope-id","html-source","js-source","css-source","custom-values"])):(e.openBlock(),e.createElementBlock("div",Oe)):(e.openBlock(),e.createElementBlock("div",Pe,[o[0]||(o[0]=e.createElementVNode("div",{style:{"font-weight":"600","margin-bottom":"4px"}}," ⚠️ 组件不可渲染 ",-1)),e.createElementVNode("div",De,e.toDisplayString(t.instance.alias??t.instance.instanceId),1),e.createElementVNode("div",Re,e.toDisplayString(t.invalidReason),1)]))],12,Ee)),[[e.vShow,!t.instance.hidden]])),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(A.value,t=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:`child-${t.instance.instanceId}`},[V(t.instance)&&!D.value.has(t.instance.instanceId)?(e.openBlock(),e.createBlock(e.Teleport,{key:0,to:V(t.instance)},[e.withDirectives(e.createElementVNode("div",{ref_for:!0,ref:e=>k(t.instance.instanceId,e),"data-instance-id":t.instance.instanceId,"data-hc-placement":t.instance.placement,"data-hc-hidden":t.instance.hidden?"true":void 0,style:e.normalizeStyle(F(t.instance))},["ok"===t.status&&t.renderSource?(e.openBlock(),e.createBlock(e.unref(n.RuntimeBox),{key:1,"canvas-id":e.unref(l),"instance-id":t.instance.instanceId,"component-id":t.instance.componentId,"scope-id":t.scopeId,"html-source":t.renderSource.html,"js-source":t.renderSource.js,"css-source":t.renderSource.css,"custom-values":{...t.instance.props,__containerLayout:t.instance.containerLayout}},null,8,["canvas-id","instance-id","component-id","scope-id","html-source","js-source","css-source","custom-values"])):(e.openBlock(),e.createElementBlock("div",Ae,[o[1]||(o[1]=e.createElementVNode("div",{style:{"font-weight":"600"}},"⚠️ 组件不可渲染",-1)),e.createElementVNode("div",Ne,e.toDisplayString(t.invalidReason),1)]))],12,$e),[[e.vShow,!t.instance.hidden]])],8,["to"])):D.value.has(t.instance.instanceId)||v.value?(e.openBlock(),e.createElementBlock("div",{key:1,class:"hc-layout-issue-warning",title:_(t),style:e.normalizeStyle(q(t))}," ⚠ 布局问题:"+e.toDisplayString(t.instance.instanceId)+'(slot "'+e.toDisplayString(e.unref(oe)(t.instance))+'") ',13,Fe)):e.createCommentVNode("",!0)],64))),128))],12,Le)):(e.openBlock(),e.createElementBlock("div",je," No page to render(payload / document 都未提供) "))}}),qe=new Map,_e=new Set;function Ke(){const e=Object.freeze(Array.from(qe.keys()));for(const n of _e)try{n(e)}catch{}}function Je(e,n){qe.set(e,n),Ke()}function Ue(e){qe.delete(e)&&Ke()}function He(e,n){var o;const i=n.document;switch(e.type){case"addInstance":{const{instance:n}=e.payload;return i.getInstance(n.instanceId)?null:[{type:"removeInstance",payload:{instanceId:n.instanceId}}]}case"removeInstance":{const{instanceId:n}=e.payload,o=i.getInstance(n);if(!o)return null;const a=i.document.bindings.filter(e=>j(e,n)),r=[{type:"addInstance",payload:{instance:Ye(o)}}];for(const e of a)r.push({type:"addBinding",payload:{binding:t(e)}});return r}case"updateInstance":{const{instanceId:n,patch:o}=e.payload,a=i.getInstance(n);if(!a)return null;const r={};for(const e of Object.keys(o)){const n=a[e];r[e]=Xe(n)?t(n):n}return[{type:"updateInstance",payload:{instanceId:n,patch:r}}]}case"moveInstance":{const{instanceId:n,x:t,y:o}=e.payload,a=i.getInstance(n);return a?a.rect.x===t&&a.rect.y===o?null:a.layoutBox?[{type:"updateLayoutBox",payload:{instanceId:n,patch:{...a.layoutBox}}}]:[{type:"moveInstance",payload:{instanceId:n,x:a.rect.x,y:a.rect.y}}]:null}case"resizeInstance":{const{instanceId:n,w:t,h:o}=e.payload,a=i.getInstance(n);return a?a.rect.w===t&&a.rect.h===o?null:a.layoutBox?[{type:"updateLayoutBox",payload:{instanceId:n,patch:{...a.layoutBox}}}]:[{type:"resizeInstance",payload:{instanceId:n,w:a.rect.w,h:a.rect.h}}]:null}case"setInstanceProp":{const{instanceId:n,key:t,value:o}=e.payload,a=i.getInstance(n);return a?a.props[t]===o?null:[{type:"updateInstance",payload:{instanceId:n,patch:{props:{...a.props}}}}]:null}case"addBinding":{const{binding:n}=e.payload;return i.document.bindings.some(e=>e.id===n.id)?null:[{type:"removeBinding",payload:{bindingId:n.id}}]}case"removeBinding":{const{bindingId:n}=e.payload,o=i.document.bindings.find(e=>e.id===n);return o?[{type:"addBinding",payload:{binding:t(o)}}]:null}case"updateBinding":{const{bindingId:n,patch:o}=e.payload,a=i.document.bindings.find(e=>e.id===n);if(!a)return null;const r={};for(const e of Object.keys(o)){const n=a[e];r[e]=Xe(n)?t(n):n}return[{type:"updateBinding",payload:{bindingId:n,patch:r}}]}case"updateLayout":{const{patch:n}=e.payload,o={};for(const e of Object.keys(n)){const n=i.document.layout[e];o[e]=Xe(n)?t(n):n}return[{type:"updateLayout",payload:{patch:o}}]}case"setRootLayout":{const{rootLayout:n}=e.payload,o=i.document.layout.rootLayout,a=void 0!==o;return a||null!==n?[{type:"setRootLayout",payload:{rootLayout:a?t(o):null}}]:null}case"setComponentOverride":{const{instanceId:n,override:a}=e.payload;if(void 0===i.getInstance(n))return null;const r=null==(o=i.document.componentOverrides)?void 0:o[n],c=void 0!==r;return c||null!==a?[{type:"setComponentOverride",payload:{instanceId:n,override:c?t(r):null}}]:null}case"replaceDocument":return[{type:"replaceDocument",payload:{document:t(i.document)}}];case"setInstanceLocked":{const{instanceId:n,locked:t}=e.payload,o=i.getInstance(n);if(!o)return null;const a=o.locked??!1,r=o.lockPosition,c=o.lockSize;return a===t&&r===(!!t||void 0)&&c===(!!t||void 0)?null:[{type:"updateInstance",payload:{instanceId:n,patch:{locked:a,lockPosition:r,lockSize:c}}}]}case"duplicateInstance":{const{instanceId:n,newInstanceId:t}=e.payload;return i.getInstance(n)?i.getInstance(t)?null:[{type:"removeInstance",payload:{instanceId:t}}]:null}case"setInstanceSize":{const{instanceId:n,size:o}=e.payload,a=i.getInstance(n);if(!a)return null;const r=a.size,c="size"in a&&void 0!==r;return c||null!==o?[{type:"setInstanceSize",payload:{instanceId:n,size:(c?t(r):null)??null}}]:null}case"setContainerLayout":{const{instanceId:n,containerLayout:o}=e.payload,a=i.getInstance(n);if(!a)return null;const r=a.containerLayout,c="containerLayout"in a&&void 0!==r;return c||null!==o?[{type:"setContainerLayout",payload:{instanceId:n,containerLayout:(c?t(r):null)??null}}]:null}case"updateLayoutBox":{const{instanceId:n,patch:t}=e.payload,o=i.getInstance(n);if(!o)return null;const a=o.layoutBox??{x:o.rect.x,y:o.rect.y,width:o.rect.w,height:o.rect.h,widthMode:"px",heightMode:"px",overflow:"hidden"},r={};let c=!1;const s=["x","y","width","height"];for(const e of s){const n=t[e];"number"==typeof n&&Number.isFinite(n)&&(r[e]=a[e],c=!0)}return"px"!==t.widthMode&&"percent"!==t.widthMode&&"fill"!==t.widthMode&&"auto"!==t.widthMode||(r.widthMode=a.widthMode,c=!0),"px"!==t.heightMode&&"percent"!==t.heightMode&&"fill"!==t.heightMode&&"auto"!==t.heightMode||(r.heightMode=a.heightMode,c=!0),"hidden"!==t.overflow&&"visible"!==t.overflow&&"auto"!==t.overflow||(r.overflow=a.overflow,c=!0),c?[{type:"updateLayoutBox",payload:{instanceId:n,patch:r}}]:null}case"updateLayoutItem":{const{instanceId:n,patch:o}=e.payload,a=i.getInstance(n);if(!a)return null;const r=a.layoutItem,c="layoutItem"in a&&void 0!==r,s=null===o;if(!c&&s)return null;if(!s){const e=["order","grow","shrink","row","column","rowSpan","columnSpan","ratio"];let n=!1;for(const t of e){const e=o[t];if("number"==typeof e&&Number.isFinite(e)){n=!0;break}}if(!n)return null}return[{type:"updateLayoutItem",payload:{instanceId:n,patch:(c?t(r):null)??null}}]}case"updateRotation":{const{instanceId:n,value:t}=e.payload,o=i.getInstance(n);if(!o)return null;if(!Number.isFinite(t))return null;const a=o.rotation,r="number"==typeof a&&Number.isFinite(a)?a:0;return r===t?null:[{type:"updateRotation",payload:{instanceId:n,value:r}}]}case"select":case"toggleSelect":case"addToSelection":case"removeFromSelection":case"clearSelection":case"selectAll":return null;default:{const n=e;return console.warn("[hc-canvas/computeInverse] unknown action",n),null}}}function Xe(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Ye(e){return t(e)}function Ge(n,t={}){const o=t.maxSize??100,i=e.ref([]),a=e.ref([]);let r={redo:[],undo:[]},c=null;function s(e){var n;0===r.redo.length&&0===r.undo.length||(n={type:e,redo:r.redo,undo:r.undo,timestamp:Date.now()},i.value.push(n),i.value.length>o&&i.value.shift(),a.value.length>0&&(a.value=[]),r={redo:[],undo:[]},c=null)}const d={onBeforeAction(e){if(n.isRecordingSuppressed.value)return;const t=He(e,n);if(null!==t){r.redo.push(e);for(let e=t.length-1;e>=0;e--)r.undo.unshift(t[e]);c=e.type}},onAfterAction(e){n.isRecordingSuppressed.value||n.isBatching.value||s(c??"action")},onAfterBatch(e){n.isRecordingSuppressed.value||s(e??"batch")}},l=n.registerHooks(d);function u(){i.value=[],a.value=[],r={redo:[],undo:[]},c=null}return{undo:function(){if(0===i.value.length)return;const e=i.value.pop();n.suppressRecording(()=>{n.beginBatch();for(const t of e.undo)n.dispatch(t);n.endBatch("undo")}),a.value.push(e)},redo:function(){if(0===a.value.length)return;const e=a.value.pop();n.suppressRecording(()=>{n.beginBatch();for(const t of e.redo)n.dispatch(t);n.endBatch("redo")}),i.value.push(e)},clear:u,canUndo:e.computed(()=>i.value.length>0),canRedo:e.computed(()=>a.value.length>0),undoStackSize:e.computed(()=>i.value.length),redoStackSize:e.computed(()=>a.value.length),dispose:function(){l(),u()}}}function We(e,n,t){let o=null;for(const i of e)for(const e of n){const n=e.pos-i,a=Math.abs(n);a<=t&&(!o||a<Math.abs(o.delta))&&(o={delta:n,candidate:e,targetPos:i})}return o}function Qe(e){var n,t,o,i;const a=e.threshold??5,r=function(e){if(0===e.length)return null;let n=1/0,t=-1/0,o=1/0,i=-1/0;for(const a of e)a.x<n&&(n=a.x),a.x+a.w>t&&(t=a.x+a.w),a.y<o&&(o=a.y),a.y+a.h>i&&(i=a.y+a.h);return{left:n,right:t,top:o,bottom:i,centerX:(n+t)/2,centerY:(o+i)/2,width:t-n,height:i-o}}(e.draggedRects);if(!r)return{dx:0,dy:0,lines:[]};const c=function(e,n,t){const o=[];for(const n of e)o.push({pos:n.x,kind:"edge-left",source:n}),o.push({pos:n.x+n.w,kind:"edge-right",source:n}),o.push({pos:n.x+n.w/2,kind:"center-x",source:n});if(o.push({pos:0,kind:"canvas-edge"}),o.push({pos:n.w,kind:"canvas-edge"}),o.push({pos:n.w/2,kind:"canvas-edge"}),t)for(const e of t)o.push({pos:e,kind:"guide"});return o}(e.otherRects,e.canvasSize,null==(n=e.manualGuides)?void 0:n.x),s=function(e,n,t){const o=[];for(const n of e)o.push({pos:n.y,kind:"edge-top",source:n}),o.push({pos:n.y+n.h,kind:"edge-bottom",source:n}),o.push({pos:n.y+n.h/2,kind:"center-y",source:n});if(o.push({pos:0,kind:"canvas-edge"}),o.push({pos:n.h,kind:"canvas-edge"}),o.push({pos:n.h/2,kind:"canvas-edge"}),t)for(const e of t)o.push({pos:e,kind:"guide"});return o}(e.otherRects,e.canvasSize,null==(t=e.manualGuides)?void 0:t.y),d=[r.left,r.right,r.centerX],l=[r.top,r.bottom,r.centerY],u=We(d,c,a),p=We(l,s,a),f=(null==u?void 0:u.delta)??0,h=(null==p?void 0:p.delta)??0,g=[];if(u){const n=(null==(o=u.candidate.source)?void 0:o.y)??0,t=u.candidate.source?u.candidate.source.y+u.candidate.source.h:e.canvasSize.h,i=Math.min(r.top+h,n),a=Math.max(r.bottom+h,t);g.push({axis:"x",pos:u.candidate.pos,from:i,to:a,kind:u.candidate.kind})}if(p){const n=(null==(i=p.candidate.source)?void 0:i.x)??0,t=p.candidate.source?p.candidate.source.x+p.candidate.source.w:e.canvasSize.w,o=Math.min(r.left+f,n),a=Math.max(r.right+f,t);g.push({axis:"y",pos:p.candidate.pos,from:o,to:a,kind:p.candidate.kind})}return{dx:f,dy:h,lines:g}}function Ze(e,n,t){const o=new Map;for(let e=0;e<n.length;e++)o.set(n[e].instanceId,e);const i=new Map;function a(e){const t=i.get(e);if(t)return t;const o=[];let a=e;const r=new Set;for(;a&&!r.has(a);){r.add(a),o.push(a);const e=n.find(e=>e.instanceId===a);if(!(null==e?void 0:e.parentId))break;a=e.parentId}const c=o.reverse();return i.set(e,c),c}function r(e,t){const i=a(e),r=a(t);let c=0;for(;c<i.length&&c<r.length&&i[c]===r[c];)c++;if(c===i.length&&c===r.length)return 0;if(c===i.length)return-1;if(c===r.length)return 1;const s=i[c],d=r[c],l=n.find(e=>e.instanceId===s),u=n.find(e=>e.instanceId===d),p=(null==l?void 0:l.zIndex)??0,f=(null==u?void 0:u.zIndex)??0;return p!==f?p-f:(o.get(s)??-1)-(o.get(d)??-1)}let c=null,s=-1;for(let o=0;o<n.length;o++){const i=n[o];if(i.hidden)continue;const a=(null==t?void 0:t(i.instanceId))??i.rect;if(!(e.x>=a.x&&e.x<=a.x+a.w&&e.y>=a.y&&e.y<=a.y+a.h))continue;if(null===c){c=i.instanceId,s=o;continue}const d=r(i.instanceId,c);let l;l=d>0||!(d<0)&&o>s,l&&(c=i.instanceId,s=o)}return c}function en(e,n){return{x:Math.min(e.x,n.x),y:Math.min(e.y,n.y),w:Math.abs(e.x-n.x),h:Math.abs(e.y-n.y)}}function nn(e,n,t){const o=[];for(const i of n){if(i.hidden)continue;const n=(null==t?void 0:t(i.instanceId))??i.rect;n.x>=e.x&&n.y>=e.y&&n.x+n.w<=e.x+e.w&&n.y+n.h<=e.y+e.h&&o.push(i.instanceId)}return o}function tn(e,n){if(!e||"function"!=typeof e.querySelector)return null;const t=e.querySelector(n);if(t)return t;if(e instanceof Element&&"function"==typeof e.closest){const t=e.closest("[data-hc-canvas-designer]");if(t&&t!==e){const e=t.querySelector(n);if(e)return e}}return null}function on(e,n,t){var o;const i=t??("undefined"!=typeof document&&"function"==typeof document.querySelector?document:null);if(!i)return null;const a=n??"default",r=""===a?"default":a,c="undefined"!=typeof globalThis&&(null==(o=globalThis.CSS)?void 0:o.escape)?globalThis.CSS.escape:e=>e.replace(/["\\]/g,e=>`\\${e}`),s=tn(i,`[data-instance-id="${c(e)}"] [data-hc-slot="${c(r)}"]`);return s&&s instanceof HTMLElement?s.getBoundingClientRect():null}function an(e,n,t){var o;const i=n??("undefined"!=typeof document&&"function"==typeof document.querySelector?document:null);if(!i)return null;if("function"!=typeof i.querySelector)return null;const a=`[data-instance-id="${("undefined"!=typeof globalThis&&(null==(o=globalThis.CSS)?void 0:o.escape)?globalThis.CSS.escape:e=>e.replace(/["\\]/g,e=>`\\${e}`))(e)}"]`,r=t?tn(i,a):i.querySelector(a);return r&&r instanceof HTMLElement?r.getBoundingClientRect():null}function rn(e,n){return $(e.document.document.layout,e.document.document.instances,n)}function cn(e){return"free"===e||"none"===e||void 0===e}const sn=new Set(["e","w","ne","nw","se","sw"]),dn=new Set(["n","s","ne","nw","se","sw"]);function ln(e,n,t,o){if(cn(e))return!0;const i=sn.has(n),a=dn.has(n);return!(i&&"fill"===t||a&&"fill"===o)}function un(e,n,t){if(!n)return null;const o=an(e,n,!0);if(!o)return null;const i=n.getBoundingClientRect(),a=t.toCanvasPoint({x:o.left-i.left,y:o.top-i.top}),r=t.toCanvasPoint({x:o.right-i.left,y:o.bottom-i.top});return{x:a.x,y:a.y,w:Math.max(0,r.x-a.x),h:Math.max(0,r.y-a.y)}}function pn(e,n,t){const o=Math.max(8,n);if(!e)return{mode:"px",value:o};switch(e.mode){case"px":return{...e,mode:"px",value:o};case"percent":{if(!t||t<=0)return{...e,mode:"px",value:o};const n=o/t*100,i=Math.max(0,Math.min(1e3,n));return{...e,mode:"percent",value:i}}case"fill":case"hug":case"auto":return{mode:"px",value:o,min:e.min,max:e.max}}}function fn(e,n,t){const o=Math.max(8,n);switch(e){case"px":case"fill":case"auto":default:return{mode:"px",value:o};case"percent":{if(!t||t<=0)return{mode:"px",value:o};const e=o/t*100;return{mode:"percent",value:Math.max(0,Math.min(1e3,e))}}}}function hn(e){return e.shift||e.ctrl||e.meta}function gn(e,n,t){const o=n.getBoundingClientRect(),i={x:e.x-o.left,y:e.y-o.top};return t.toCanvasPoint(i)}function mn(e,n){const t=new Set(n.map(e=>e.instanceId));return e.filter(e=>t.has(e))}function vn(n,t={}){const o=e.reactive({active:!1,start:null,end:null,additive:!1,priorSelection:[]}),i=e.reactive({status:"idle",startPt:null,startRects:new Map,deferredClickSelect:null}),a=e.reactive({status:"idle",handle:null,startPt:null,startRect:null,instanceId:null,placement:null,parentLayoutMode:void 0,startSize:null,startLayoutBox:null,startOutletCanvasSize:null}),r=e.ref([]),c=e.ref(null);let s=0;const d=e.ref(null);let l=0;const u=e.computed(()=>o.active&&o.start&&o.end?en(o.start,o.end):null),p=e.computed(()=>"active"===i.status),f=e.computed(()=>"active"===a.status);function h(){o.active=!1,o.start=null,o.end=null,o.additive=!1,o.priorSelection=[]}function g(){i.status="idle",i.startPt=null,i.startRects=new Map,i.deferredClickSelect=null,r.value=[]}function m(){a.status="idle",a.handle=null,a.startPt=null,a.startRect=null,a.instanceId=null,a.placement=null,a.startSize=null,a.startOutletCanvasSize=null,a.parentLayoutMode=void 0,a.startLayoutBox=null}return{marquee:o,marqueeRect:u,drag:i,isDragging:p,resize:a,isResizing:f,snapLines:r,cannotDragSlotChildEvent:c,cannotDragLayoutManagedChildEvent:d,handlePointerDown(e,a){var r;const u=n.effectiveBehavior.value;if(!u.selectable)return{startTracking:!1};const p=n.toolMode.value;if("hand"===p)return{startTracking:!1};const f=hn(a),h="marquee"===p?null:Ze(e,n.document.document.instances,t.getDomBox);if(h){const t=n.document.getInstance(h),o=!0===((null==t?void 0:t.lockPosition)??(null==t?void 0:t.locked)),a=n.selection.selectedIds.value.includes(h),g=n.selection.size.value>1;f?n.dispatch({type:"toggleSelect",payload:{instanceId:h}}):o?n.dispatch({type:"select",payload:{instanceId:h}}):a&&g&&u.draggable&&"inspect"!==p?i.deferredClickSelect=h:n.dispatch({type:"select",payload:{instanceId:h}});const m="slot"===(null==t?void 0:t.placement)||"container"===(null==t?void 0:t.placement),v=rn(n,h),y="inspect"===p;if(o||!u.draggable||y||(null==t?void 0:t.hidden))return{startTracking:!1};if(!cn(v)){if(!f){l++;const e={instanceId:h,parentId:null==t?void 0:t.parentId,parentLayoutMode:v,token:l};d.value=e,null==(r=n.setCannotDragLayoutManagedChildEvent)||r.call(n,e),m&&(s++,c.value={instanceId:h,parentId:null==t?void 0:t.parentId,token:s})}return{startTracking:!1}}return i.status="pending",i.startPt={...e},i.startRects=function(){const e=n.selection.selectedIds.value,t=new Map;for(const o of e){const e=n.document.getInstance(o);e&&!0!==(e.lockPosition??e.locked)&&t.set(o,{x:e.rect.x,y:e.rect.y})}return t}(),{startTracking:!0}}return f||n.dispatch({type:"clearSelection"}),o.active=!0,o.start={...e},o.end={...e},o.additive=f,o.priorSelection=f?[...n.selection.selectedIds.value]:[],{startTracking:!0}},handlePointerMove(e){var c,s;if("active"===a.status&&a.startPt&&a.startRect&&a.instanceId){const t=e.x-a.startPt.x,o=e.y-a.startPt.y,i=a.startRect,r=a.handle,c=n.document.getInstance(a.instanceId);if(!c)return;const s=a.parentLayoutMode,d=void 0!==s&&!cn(s);let l=i.x,u=i.y,p=i.w,f=i.h;const h="w"===r||"nw"===r||"sw"===r,g="e"===r||"ne"===r||"se"===r,m="n"===r||"ne"===r||"nw"===r,v="s"===r||"se"===r||"sw"===r;g?p=i.w+t:h&&(p=i.w-t,d||(l=i.x+t)),v?f=i.h+o:m&&(f=i.h-o,d||(u=i.y+o)),p<8&&(!d&&h&&(l=i.x+i.w-8),p=8),f<8&&(!d&&m&&(u=i.y+i.h-8),f=8);const y=a.startLayoutBox,I=a.startOutletCanvasSize,w=g||h,x=v||m,b=!d&&h,k=!d&&m,S=w?fn(y.widthMode,p,I?I.w:null):null,B=x?fn(y.heightMode,f,I?I.h:null):null,M="canvas"===a.placement||"absolute"===a.placement,T=!(S&&"px"!==S.mode||B&&"px"!==B.mode||w&&"px"!==y.widthMode||x&&"px"!==y.heightMode);if(M&&T)(w&&c.rect.w!==p||x&&c.rect.h!==f)&&n.dispatch({type:"resizeInstance",payload:{instanceId:a.instanceId,w:w?p:c.rect.w,h:x?f:c.rect.h}}),(b&&c.rect.x!==l||k&&c.rect.y!==u)&&n.dispatch({type:"moveInstance",payload:{instanceId:a.instanceId,x:b?l:c.rect.x,y:k?u:c.rect.y}});else{const e={};S&&(e.widthMode=S.mode,e.width=S.value),B&&(e.heightMode=B.mode,e.height=B.value),b&&(e.x=l),k&&(e.y=u);const t=c.layoutBox;let o=!1;t?(void 0!==e.x&&e.x!==t.x&&(o=!0),void 0!==e.y&&e.y!==t.y&&(o=!0),void 0!==e.width&&e.width!==t.width&&(o=!0),void 0!==e.height&&e.height!==t.height&&(o=!0),void 0!==e.widthMode&&e.widthMode!==t.widthMode&&(o=!0),void 0!==e.heightMode&&e.heightMode!==t.heightMode&&(o=!0)):o=Object.keys(e).length>0,o&&n.dispatch({type:"updateLayoutBox",payload:{instanceId:a.instanceId,patch:e}})}if(("container"===a.placement||"slot"===a.placement)&&(null!==a.startSize||T)){const e=a.startSize,t={};w?t.width=pn(null==e?void 0:e.width,p,I?I.w:null):(null==e?void 0:e.width)&&(t.width=JSON.parse(JSON.stringify(e.width))),x?t.height=pn(null==e?void 0:e.height,f,I?I.h:null):(null==e?void 0:e.height)&&(t.height=JSON.parse(JSON.stringify(e.height)));const o=c.size;JSON.stringify(o)!==JSON.stringify(t)&&n.dispatch({type:"setInstanceSize",payload:{instanceId:a.instanceId,size:t}})}return}if("pending"===i.status&&i.startPt){const t=e.x-i.startPt.x,o=e.y-i.startPt.y;t*t+o*o>=9&&(i.status="active",n.beginBatch())}if("active"===i.status&&i.startPt){const o=e.x-i.startPt.x,a=e.y-i.startPt.y,d=(null==(c=t.getRoot)?void 0:c.call(t))??null,l=d instanceof HTMLElement?d:null,u=n.document.document.instances,p=null!==l&&u.length<=50,f=(e,t)=>p?un(e,l,n.viewport)??t:t,h=[];for(const[e,t]of i.startRects){const i=n.document.getInstance(e);if(!i)continue;const r=f(e,i.rect);h.push({x:t.x+o,y:t.y+a,w:r.w,h:r.h})}const g=[],m=new Set(i.startRects.keys());for(const e of u)m.has(e.instanceId)||g.push(f(e.instanceId,e.rect));const v=n.document.document.layout,y=!1!==n.effectiveBehavior.value.snap,I=(null==(s=v.guides)?void 0:s.items)??[],w=[],x=[];for(const e of I)"x"===e.axis?w.push(e.position):x.push(e.position);const b=y?Qe({draggedRects:h,otherRects:g,canvasSize:{w:n.measuredCanvasSize.value.w,h:n.measuredCanvasSize.value.h},manualGuides:w.length||x.length?{x:w,y:x}:void 0}):{dx:0,dy:0,lines:[]};r.value=b.lines;const k=o+b.dx,S=a+b.dy;for(const[e,t]of i.startRects)n.document.getInstance(e)&&n.dispatch({type:"moveInstance",payload:{instanceId:e,x:t.x+k,y:t.y+S}});return}o.active&&(o.end={...e})},handlePointerUp(){if("active"===a.status){const e="slot"===a.placement||"container"===a.placement?"resize-slot-child":"resize";return n.endBatch(e),void m()}if("active"===i.status)return n.endBatch("drag"),void g();if("pending"===i.status)return i.deferredClickSelect&&n.dispatch({type:"select",payload:{instanceId:i.deferredClickSelect}}),void g();if(!o.active)return;const e=u.value,t=n.document.document.instances;if(e&&(e.w>0||e.h>0)){const i=mn(nn(e,t),t);if(o.additive){const e=mn(o.priorSelection,t),a=Array.from(new Set([...e,...i]));n.dispatch({type:"selectAll",payload:{instanceIds:a}})}else i.length>0&&n.dispatch({type:"selectAll",payload:{instanceIds:i}})}h()},cancelMarquee(){h()},cancelDrag(){"active"===i.status&&n.endBatch("drag-cancel"),g()},handleResizeStart(e,o,i){var r,c,s,d,l,u;const p=n.document.getInstance(e);if(!p)return{startTracking:!1};if(!0===(p.lockSize??p.locked))return{startTracking:!1};if(p.hidden)return{startTracking:!1};if(!n.effectiveBehavior.value.resizable)return{startTracking:!1};const f="slot"===p.placement||"container"===p.placement,h=rn(n,e);if(!ln(h,o,null==(r=p.layoutBox)?void 0:r.widthMode,null==(c=p.layoutBox)?void 0:c.heightMode))return{startTracking:!1};a.status="active",a.handle=o,a.startPt={...i};const g=un(e,(null==(s=t.getRoot)?void 0:s.call(t))??null,n.viewport);a.startRect=g??{...p.rect},a.instanceId=e,a.placement=f?"container":"canvas",a.parentLayoutMode=h,a.startLayoutBox=p.layoutBox?JSON.parse(JSON.stringify(p.layoutBox)):{x:p.rect.x,y:p.rect.y,width:p.rect.w,height:p.rect.h,widthMode:"px",heightMode:"px",overflow:"hidden"},a.startSize=f&&p.size?JSON.parse(JSON.stringify(p.size)):null;const m=p.parentId,v=p.slot,y=(null==(d=t.getRoot)?void 0:d.call(t))??null;let I=m?on(m,v,y):null;if(m&&(!I||0===I.width&&0===I.height)){const n=tn(y,`[data-instance-id="${e.replace(/["\\]/g,e=>`\\${e}`)}"]`),t=n instanceof HTMLElement?n.parentElement:null;if(t){const e=t.getBoundingClientRect();(e.width>0||e.height>0)&&(I=e)}}if(I){const e=n.viewport.scale.value||1;a.startOutletCanvasSize={w:I.width/e,h:I.height/e}}else if(void 0===m)a.startOutletCanvasSize={w:n.measuredCanvasSize.value.w,h:n.measuredCanvasSize.value.h};else{const n=a.startLayoutBox.widthMode,t=a.startLayoutBox.heightMode,o="percent"===n||"percent"===t;o&&console.debug("[hc-canvas/interaction] resize: 父 outlet 找不到,percent 模式将退化到 px。",{instanceId:e,parentId:m,slot:v});const i=a.startSize,r="percent"===(null==(l=null==i?void 0:i.width)?void 0:l.mode)||"percent"===(null==(u=null==i?void 0:i.height)?void 0:u.mode);!o&&r&&console.debug("[hc-canvas/interaction] slot child resize: 父 outlet 找不到,percent 模式将退化到 px。",{instanceId:e,parentId:m,slot:v}),a.startOutletCanvasSize=null}return n.beginBatch(),{startTracking:!0}},cancelResize(){if("active"===a.status){const e="slot"===a.placement||"container"===a.placement?"resize-slot-child-cancel":"resize-cancel";n.endBatch(e)}m()}}}function yn(e,n){return{ok:!1,reason:e,message:n}}function In(e,n,t,o={}){const i=new Map;for(const n of e)i.set(n.instanceId,n);const a=i.get(n);if(!a)return yn("instance-not-exists",`实例 "${n}" 不存在,无法 reparent`);const r=null===t.parentId||void 0===t.parentId?void 0:t.parentId;if(r===n)return yn("self-parent",`parentId 不能等于自身 "${n}"`);if(void 0!==r){const e=i.get(r);if(!e)return yn("parent-not-exists",`目标 parentId "${r}" 不存在`);const t=new Set;let o=e.parentId;for(;void 0!==o&&!t.has(o);){if(t.add(o),o===n)return yn("cycle",`目标 parent "${r}" 是 "${n}" 的后代,会循环`);const e=i.get(o);o=null==e?void 0:e.parentId}}if(void 0===r)return{ok:!0};const c=o.resolveContract;if(!c)return{ok:!0};const s=i.get(r),d=c(s.componentVersionKey);if(!d)return{ok:!0};const l=d.slotsDecl??[];if(0===l.length)return yn("parent-not-layout",`父组件 "${s.componentId}" 不是布局组件(slotsDecl 空)`);const u=void 0===t.slot||""===t.slot||"default"===t.slot?te:t.slot,p=(f=u,l.find(e=>e.name===f));var f;if(!p)return yn("slot-not-exists",`slot "${u}" 不在父 "${s.componentId}" 的 slotsDecl`);if(p.accepts&&p.accepts.length>0&&!p.accepts.includes(a.componentId))return yn("accepts-violation",`slot "${u}" 不允许 componentId "${a.componentId}"(accepts: ${p.accepts.join(", ")})`);if(!0!==p.multiple){const t=e.filter(e=>e.instanceId!==n&&e.parentId===r&&oe(e)===u);if(t.length>0)return yn("slot-multiple-violated",`slot "${u}" 不允许多个子实例(已有 "${t[0].instanceId}")`)}if("number"==typeof p.maxChildren&&Number.isFinite(p.maxChildren)&&p.maxChildren>=1){const t=e.filter(e=>e.instanceId!==n&&e.parentId===r&&oe(e)===u);if(t.length+1>p.maxChildren)return yn("max-children-exceeded",`slot "${u}" 最多接受 ${p.maxChildren} 个子(已有 ${t.length} 个)`)}return{ok:!0}}function wn(e){const n=new Set(e.map(e=>e.instanceId)),t=new Map;for(const n of e)t.set(n.instanceId,bn(n));const o=[],i=new Map;e.forEach((e,a)=>{const r={inst:e,node:t.get(e.instanceId),originalIndex:a},c=e.parentId;if(c){if(!n.has(c))return console.warn(`[hc-canvas/instance-tree] instance "${e.instanceId}" parentId="${c}" 不存在,降级当顶层`),void o.push(r);i.has(c)||i.set(c,[]),i.get(c).push(r)}else o.push(r)});for(const[e,n]of i){const o=t.get(e);o&&(o.children=xn(n).map(e=>e.node))}return o.slice().sort((e,n)=>{const t=(n.inst.zIndex??0)-(e.inst.zIndex??0);return 0!==t?t:e.originalIndex-n.originalIndex}).map(e=>e.node)}function xn(e){const n=new Map;for(const t of e){const e=t.inst.slot??"default";let o=n.get(e);o||(o={firstIndex:t.originalIndex,entries:[]},n.set(e,o)),o.entries.push(t)}return Array.from(n.values()).sort((e,n)=>e.firstIndex-n.firstIndex).flatMap(e=>e.entries.slice().sort((e,n)=>e.originalIndex-n.originalIndex))}function bn(e){const n={instanceId:e.instanceId,componentId:e.componentId,componentVersionKey:e.componentVersionKey,kind:"visual",label:e.alias??e.instanceId};return void 0!==e.locked&&(n.locked=e.locked),void 0!==e.lockPosition&&(n.lockPosition=e.lockPosition),void 0!==e.lockSize&&(n.lockSize=e.lockSize),void 0!==e.hidden&&(n.hidden=e.hidden),n}function kn(e,n){for(const t of e){if(t.instanceId===n)return[t];if(t.children&&t.children.length>0){const e=kn(t.children,n);if(e.length>0)return[t,...e]}}return[]}function Sn(e,n){const t=new Map;for(const n of e)t.set(n.instanceId,n);const o=t.get(n);if(!o)return[];const i=[o];let a=o;const r=e.length;for(;a&&a.parentId;){if(i.length>r){console.warn(`[hc-canvas/instance-tree] breadcrumb for "${n}" exceeds depth ${r},疑似环,截断`);break}const e=t.get(a.parentId);if(!e)break;i.unshift(e),a=e}return i}function Bn(e,n,t){const o=n||void 0;return e.filter(e=>(e.parentId||void 0)===o&&e.slot===t).map((e,n)=>({inst:e,originalIndex:n})).sort((e,n)=>{const t=(n.inst.zIndex??0)-(e.inst.zIndex??0);return 0!==t?t:e.originalIndex-n.originalIndex}).map(e=>e.inst)}function Mn(e){if(0===e.length)return null;let n=1/0,t=1/0,o=-1/0,i=-1/0;for(const a of e)a.x<n&&(n=a.x),a.y<t&&(t=a.y),a.x+a.w>o&&(o=a.x+a.w),a.y+a.h>i&&(i=a.y+a.h);return{x:n,y:t,w:o-n,h:i-t}}function Tn(e){return Mn(e.map(e=>e.rect))}function Cn(e,n){if(0===n.length)return null;const t=new Set(n),o=[];for(const n of e)t.has(n.instanceId)&&o.push(n.rect);return Mn(o)}function zn(e,n,t){const o=(null==t?void 0:t.padding)??40,i=Math.max(1,n.w-2*o),a=Math.max(1,n.h-2*o),r=Math.max(1,e.w),c=Math.max(1,e.h);let s=Math.min(i/r,a/c);void 0!==(null==t?void 0:t.maxScale)&&(s=Math.min(s,t.maxScale)),void 0!==(null==t?void 0:t.minScale)&&(s=Math.max(s,t.minScale));const d=e.x+e.w/2,l=e.y+e.h/2;return{scale:s,panX:n.w/2-d*s,panY:n.h/2-l*s}}function Ln(e,n){const t=e.scale||1;return{x:-e.panX/t+0,y:-e.panY/t+0,w:n.w/t,h:n.h/t}}function En(e){const n=[];(e.metaKey||e.ctrlKey)&&n.push("mod"),e.shiftKey&&n.push("shift"),e.altKey&&n.push("alt");let t=e.key;return t="Meta"===t||"Control"===t?"mod":" "===t||"Space"===e.code?"space":(t.length,t.toLowerCase()),n[n.length-1]===t||n.push(t),n.join("+")}function Pn(e){if(!(e&&e instanceof HTMLElement))return!1;const n=e.tagName;return"INPUT"===n||"TEXTAREA"===n||"SELECT"===n||!!e.isContentEditable}function Dn(e,n){const t=En(n);for(const n of e.keys)if(Rn(n)===t)return!0;return!1}function Rn(e){return e.split("+").map(e=>e.trim().toLowerCase()).join("+")}class On extends Error{constructor(e="CanvasHandle has been disposed"){super(e),this.name="HandleDisposedError"}}function $n(t,o){const i=Ge(t,o.recorder);function a(e){const n=o.getStageEl();if(!n)return console.warn("[hc-canvas/handle] clientToCanvasPoint called before stage mounted; falling back to viewport.toCanvasPoint(raw clientPt). 结果可能偏移。"),t.viewport.toCanvasPoint(e);const i=n.getBoundingClientRect();return t.viewport.toCanvasPoint({x:e.x-i.left,y:e.y-i.top})}function r(e,n){const o=t.document.getInstance(e);if(!o)return null;const i=(null==n?void 0:n.newInstanceId)??function(e){var n;const t="undefined"!=typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;return`${e}_${(null==(n=null==t?void 0:t.randomUUID)?void 0:n.call(t).replace(/-/g,"").slice(0,8))??Math.random().toString(36).slice(2,10)}`}(o.componentId);return t.dispatch({type:"duplicateInstance",payload:{instanceId:e,newInstanceId:i,...void 0!==(null==n?void 0:n.offset)?{offset:n.offset}:{}}}),t.document.getInstance(i)?i:null}function c(){return JSON.parse(JSON.stringify(t.document.document.layout))}function s(){return wn(t.document.document.instances)}function d(e,n){const i=t.document.getInstance(e);if(!i)return console.warn(`[hc-canvas/handle] ${n}: instance "${e}" 不存在`),!1;const a=o.getStageEl();if(!a)return console.warn(`[hc-canvas/handle] ${n}: stage 未挂载,跳过滚动(${e})`),!1;const r=un(e,a,t.viewport),c=r&&(r.w>0||r.h>0)?r:{x:i.rect.x,y:i.rect.y,w:i.rect.w,h:i.rect.h},s=a.getBoundingClientRect(),d=t.viewport.scale.value,l=s.width/2-(c.x+c.w/2)*d,u=s.height/2-(c.y+c.h/2)*d;return t.viewport.setPan(l,u),!0}const l=e.ref(null);let u=0;function p(e){var n;return"undefined"!=typeof globalThis&&(null==(n=globalThis.CSS)?void 0:n.escape)?globalThis.CSS.escape(e):e.replace(/["\\]/g,e=>`\\${e}`)}function f(){const e=o.getStageEl();if(!e)return null;const n=e.getBoundingClientRect();return{w:n.width,h:n.height}}function h(){return{scale:t.viewport.scale.value,panX:t.viewport.panX.value,panY:t.viewport.panY.value}}function g(){return Tn(t.document.document.instances)}function m(){return Cn(t.document.document.instances,t.selection.selectedIds.value)}function v(e,n){const o=f();if(!o)return void t.viewport.setScale(e);const i=h();let a;if(null==n?void 0:n.center)a=n.center;else{const e=Ln(i,o);a={x:e.x+e.w/2,y:e.y+e.h/2}}const r=a.x*i.scale+i.panX,c=a.y*i.scale+i.panY,s=r-a.x*e,d=c-a.y*e;t.viewport.setScale(e),t.viewport.setPan(s,d)}function y(e,n){v(t.viewport.scale.value+e,n)}function I(){t.viewport.resetView()}function w(e,n){const o=f();if(!o)return void console.warn("[hc-canvas/handle] scrollToRect: stage 未挂载,跳过");const i=zn(e,o,n);t.viewport.setScale(i.scale),t.viewport.setPan(i.panX,i.panY)}function x(e){const n=g();n&&w(n,e)}function b(e){const n=m();n&&w(n,e)}const k=Object.freeze([{id:"undo",keys:["mod+z"],command:"undo",when:"notEditingText"},{id:"redo",keys:["mod+shift+z","mod+y"],command:"redo",when:"notEditingText"},{id:"deleteSelection",keys:["delete","backspace"],command:"deleteSelection",when:"hasSelection"},{id:"duplicateSelection",keys:["mod+d"],command:"duplicateSelection",when:"hasSelection"},{id:"fitToSelectionOrContent",keys:["f"],command:"fitToSelectionOrContent",when:"notEditingText"},{id:"zoom100",keys:["1"],command:"zoom100",when:"notEditingText"},{id:"resetViewport",keys:["0"],command:"resetViewport",when:"notEditingText"},{id:"zoomIn",keys:["+","="],command:"zoomIn",when:"notEditingText"},{id:"zoomOut",keys:["-"],command:"zoomOut",when:"notEditingText"},{id:"nudgeLeft",keys:["arrowleft"],command:"nudgeSelection",payload:{dx:-1,dy:0},when:"hasSelection"},{id:"nudgeRight",keys:["arrowright"],command:"nudgeSelection",payload:{dx:1,dy:0},when:"hasSelection"},{id:"nudgeUp",keys:["arrowup"],command:"nudgeSelection",payload:{dx:0,dy:-1},when:"hasSelection"},{id:"nudgeDown",keys:["arrowdown"],command:"nudgeSelection",payload:{dx:0,dy:1},when:"hasSelection"},{id:"nudgeLeftLarge",keys:["shift+arrowleft"],command:"nudgeSelectionLarge",payload:{dx:-1,dy:0},when:"hasSelection"},{id:"nudgeRightLarge",keys:["shift+arrowright"],command:"nudgeSelectionLarge",payload:{dx:1,dy:0},when:"hasSelection"},{id:"nudgeUpLarge",keys:["shift+arrowup"],command:"nudgeSelectionLarge",payload:{dx:0,dy:-1},when:"hasSelection"},{id:"nudgeDownLarge",keys:["shift+arrowdown"],command:"nudgeSelectionLarge",payload:{dx:0,dy:1},when:"hasSelection"},{id:"cancelInteraction",keys:["escape"],command:"cancelInteraction",when:"notEditingText"}]);function S(){const e=t.selection.selectedIds.value;if(0===e.length)return!1;for(const n of e){const e=t.document.getInstance(n);if(e&&!0!==(e.lockPosition??e.locked))return!0}return!1}function B(e,n,o){const i=o?10:1,a=t.selection.selectedIds.value;if(0===a.length)return;const r=!t.isBatching.value;r&&t.beginBatch();try{for(const o of a){const a=t.document.getInstance(o);if(!a||!0===(a.lockPosition??a.locked))continue;const r=rn(t,o);cn(r)?t.dispatch({type:"moveInstance",payload:{instanceId:o,x:a.rect.x+e*i,y:a.rect.y+n*i}}):"undefined"!=typeof console&&"function"==typeof console.debug&&console.debug("[hc-canvas/handle] executeNudge: 拒绝 layout-managed 子 nudge",{instanceId:o,parentLayoutMode:r})}}finally{r&&t.endBatch(o?"arrow-move-large":"arrow-move")}}function M(e){const n=[...t.selection.selectedIds.value];if(0===n.length)return;const o=!t.isBatching.value;o&&t.beginBatch();try{for(const o of n)t.dispatch({type:"setInstanceLocked",payload:{instanceId:o,locked:e}})}finally{o&&t.endBatch(e?"lock-selection":"unlock-selection")}}function T(e){const n=t.selection.selectedIds.value;if(0===n.length)return;const o=t.document.document.instances;if(0===o.length)return;const i=o.map((e,n)=>({inst:e,origIdx:n})).sort((e,n)=>{const t=e.inst.zIndex??0,o=n.inst.zIndex??0;return t!==o?t-o:e.origIdx-n.origIdx}).map(e=>e.inst),a=new Set(n),r=[];for(let e=0;e<i.length;e++)a.has(i[e].instanceId)&&r.push(e);if(0===r.length)return;if(r.length===i.length)return;const c=r.map(e=>i[e]),s=i.filter(e=>!a.has(e.instanceId));let d;if("toFront"===e)d=[...s,...c];else if("toBack"===e)d=[...c,...s];else if("forward"===e){let e=r[r.length-1]+1;for(;e<i.length&&a.has(i[e].instanceId);)e++;if(e>=i.length)return;const n=i[e],t=s.indexOf(n);d=[...s.slice(0,t+1),...c,...s.slice(t+1)]}else{let e=r[0]-1;for(;e>=0&&a.has(i[e].instanceId);)e--;if(e<0)return;const n=i[e],t=s.indexOf(n);d=[...s.slice(0,t),...c,...s.slice(t)]}const l=[];for(let e=0;e<d.length;e++){const n=d[e];(n.zIndex??0)!==e&&l.push({id:n.instanceId,zIndex:e})}if(0===l.length)return;const u=!t.isBatching.value;u&&t.beginBatch();try{for(const e of l)t.dispatch({type:"updateInstance",payload:{instanceId:e.id,patch:{zIndex:e.zIndex}}})}finally{u&&t.endBatch(`z-order-${e}`)}}const C={undo:{execute:()=>i.undo(),canExecute:()=>i.canUndo.value},redo:{execute:()=>i.redo(),canExecute:()=>i.canRedo.value},deleteSelection:{execute:function(){const e=[...t.selection.selectedIds.value];if(0===e.length)return;const n=!t.isBatching.value;n&&t.beginBatch();try{for(const n of e)t.dispatch({type:"removeInstance",payload:{instanceId:n}})}finally{n&&t.endBatch("delete-selection")}},canExecute:()=>t.selection.selectedIds.value.length>0},duplicateSelection:{execute:function(){const e=[...t.selection.selectedIds.value];if(0===e.length)return;const n=[],o=!t.isBatching.value;o&&t.beginBatch();try{for(const t of e){const e=r(t);e&&n.push(e)}n.length>0&&t.dispatch({type:"selectAll",payload:{instanceIds:n}})}finally{o&&t.endBatch("duplicate-selection")}},canExecute:()=>t.selection.selectedIds.value.length>0},clearSelection:{execute:()=>t.dispatch({type:"clearSelection"}),canExecute:()=>t.selection.selectedIds.value.length>0},cancelInteraction:{execute:()=>t.dispatch({type:"clearSelection"}),canExecute:()=>!0},zoomIn:{execute:()=>y(.1),canExecute:()=>!0},zoomOut:{execute:()=>y(-.1),canExecute:()=>!0},zoom100:{execute:()=>v(1),canExecute:()=>!0},resetViewport:{execute:()=>I(),canExecute:()=>!0},fitToContent:{execute:()=>x(),canExecute:()=>null!==g()},fitToSelection:{execute:()=>b(),canExecute:()=>null!==m()},fitToSelectionOrContent:{execute:()=>{m()?b():x()},canExecute:()=>null!==m()||null!==g()},nudgeSelection:{execute:e=>{const n=e??{dx:0,dy:0};B(n.dx,n.dy,!1)},canExecute:S},nudgeSelectionLarge:{execute:e=>{const n=e??{dx:0,dy:0};B(n.dx,n.dy,!0)},canExecute:S},lockSelection:{execute:()=>M(!0),canExecute:()=>t.selection.selectedIds.value.length>0},unlockSelection:{execute:()=>M(!1),canExecute:()=>t.selection.selectedIds.value.length>0},bringForward:{execute:()=>T("forward"),canExecute:()=>t.selection.selectedIds.value.length>0},sendBackward:{execute:()=>T("backward"),canExecute:()=>t.selection.selectedIds.value.length>0},bringToFront:{execute:()=>T("toFront"),canExecute:()=>t.selection.selectedIds.value.length>0},sendToBack:{execute:()=>T("toBack"),canExecute:()=>t.selection.selectedIds.value.length>0},toggleGrid:{execute:function(){var e;const n=null==(e=t.document.document.layout.guides)?void 0:e.grid;R(!(null==n?void 0:n.visible))},canExecute:()=>!0},toggleRuler:{execute:function(){var e;const n=null==(e=t.document.document.layout.guides)?void 0:e.ruler;D(!(null==n?void 0:n.visible))},canExecute:()=>!0}};function z(e,n){const o=null===n?null:JSON.parse(JSON.stringify(n));t.dispatch({type:"setComponentOverride",payload:{instanceId:e,override:o}})}function L(e,n){const o=e??"notEditingText";return"always"===o||("notEditingText"===o?!Pn(n.target):"design"===o?!Pn(n.target)&&!1!==t.effectiveBehavior.value.draggable:"hasSelection"===o&&!Pn(n.target)&&t.selection.selectedIds.value.length>0)}function E(){return t.document.document.layout.guides??{}}function P(e){t.dispatch({type:"updateLayout",payload:{patch:{guides:e}}})}function D(e){const n=E();P({...n,ruler:{...n.ruler??{},visible:e}})}function R(e){const n=E();P({...n,grid:{...n.grid??{},visible:e}})}const O=e.computed(()=>{const e=t.selection.selectedIds.value;if(0===e.length)return[];const n=new Set(e);return t.document.document.instances.filter(e=>n.has(e.instanceId))}),$=t.selection.selectedIds,A=e.readonly($),N=e.readonly(t.isBatching);let F=null,j=null;const V=t.canvasId,q=new Set,_=new Set;let K=!1;function J(e){var n,i,a,r,c,s,d,l,u;const p=e.parentId||void 0;if(void 0===p)return e;const f=(null==(i=null==(n=t.document.getInstance(p))?void 0:n.containerLayout)?void 0:i.mode)??"none";if("flex"!==f&&"split"!==f&&"grid"!==f)return e;const h=e.layoutBox,g=void 0!==h,m=void 0!==h,v=null==(a=o.resolveContract)?void 0:a.call(o,e.componentVersionKey),y=null==(c=null==(r=null==v?void 0:v.layoutDecl)?void 0:r.sizing)?void 0:c.defaultChildSize,I=e.rect??{w:240,h:60},w=h??{x:0,y:0,width:I.w,height:I.h,widthMode:"px",heightMode:"px"},x=e=>{if(void 0!==e)return"hug"===e?"auto":e},b=g?w.widthMode:x(null==(s=null==y?void 0:y.width)?void 0:s.mode)??"fill",k=m?w.heightMode:x(null==(d=null==y?void 0:y.height)?void 0:d.mode)??"fill",S=g||void 0===(null==(l=null==y?void 0:y.width)?void 0:l.value)?w.width:y.width.value,B=m||void 0===(null==(u=null==y?void 0:y.height)?void 0:u.value)?w.height:y.height.value;return{...e,layoutBox:{...w,x:0,y:0,width:S,height:B,widthMode:b,heightMode:k}}}return{dispatch:e=>function(e){if("addInstance"===e.type){const n=function(e){var n,t,i,a;if(void 0!==e.containerLayout)return e;const r=null==(n=o.resolveContract)?void 0:n.call(o,e.componentVersionKey);if(!r)return e;if(!("container"===(null==(t=r.layoutDecl)?void 0:t.role)||((null==(i=r.slotsDecl)?void 0:i.length)??0)>0))return e;const c=null==(a=r.layoutDecl)?void 0:a.defaultLayout;return void 0===c?e:{...e,containerLayout:JSON.parse(JSON.stringify(c))}}(e.payload.instance);return void t.dispatch({type:"addInstance",payload:{instance:J(n)}})}t.dispatch(e)}(e),beginBatch:()=>t.beginBatch(),endBatch:e=>t.endBatch(e),isBatching:N,getSnapshot:()=>JSON.parse(JSON.stringify(t.document.document)),selectedIds:A,selectedInstances:O,viewport:t.viewport,clientToCanvasPoint:a,getInstanceAtClientPoint:function(e){const n=o.getStageEl();if(!n)return null;const i=Ze(a(e),t.document.document.instances,e=>un(e,n,t.viewport));return i?t.document.getInstance(i)??null:null},getDropTarget:function(e,n,i){var a;const r=n??(null==(a=o.getStageEl)?void 0:a.call(o))??("undefined"!=typeof document&&"function"==typeof document.querySelectorAll?document:null);if(!r)return null;const c=void 0!==(null==i?void 0:i.excludeInstanceId),s=c?`[data-instance-id="${p(i.excludeInstanceId)}"]`:null;let d=s?r.querySelector(s):null;if(!d&&c&&r instanceof Element){const e=r.closest("[data-hc-canvas-designer]");e&&e!==r&&(d=e.querySelector(s))}let l=r.querySelectorAll("[data-hc-slot]");if(0===l.length&&c&&r instanceof Element){const e=r.closest("[data-hc-canvas-designer]");e&&e!==r&&(l=e.querySelectorAll("[data-hc-slot]"))}let u=null;for(const n of l){if(!(n instanceof HTMLElement))continue;if(d&&d.contains(n))continue;const t=n.getBoundingClientRect();if(0===t.width&&0===t.height)continue;if(e.x<t.left||e.x>t.right)continue;if(e.y<t.top||e.y>t.bottom)continue;let o=0,i=n;for(;i;)o++,i=i.parentElement;(!u||o>u.depth)&&(u={el:n,depth:o})}if(!u)return null;const f=u.el,h=f.closest("[data-instance-id]");if(!h)return null;const g=h.getAttribute("data-instance-id");return g&&t.document.getInstance(g)?{parentId:g,slot:f.getAttribute("data-hc-slot")||"default",outletEl:f}:null},duplicateInstance:r,undo:i.undo,redo:i.redo,canUndo:i.canUndo,canRedo:i.canRedo,undoStackSize:i.undoStackSize,redoStackSize:i.redoStackSize,clearHistory:i.clear,getLayoutConfig:c,updateCanvasSize:function(e){const n={...c().canvas,...e};t.dispatch({type:"updateLayout",payload:{patch:{canvas:n}}})},updateCanvasBackground:function(e){if(null===e)return void t.dispatch({type:"updateLayout",payload:{patch:{background:void 0}}});const n={...c().background??{},...e};t.dispatch({type:"updateLayout",payload:{patch:{background:n}}})},updateBehavior:function(e){const n={...c().behavior??{},...e};t.dispatch({type:"updateLayout",payload:{patch:{behavior:n}}})},setInteractionOptions:function(e){t.setInteractionOptions(e)},getEffectiveBehavior:function(){return{...t.effectiveBehavior.value}},setRootLayout:function(e){let n;if(null===e)n=null;else if("string"==typeof e)switch(e){case"free":n={mode:"free"};break;case"none":n={mode:"none"};break;case"split":n={mode:"split",direction:"horizontal",ratios:[.5,.5]};break;case"grid":n={mode:"grid",columns:[{mode:"fr",value:1},{mode:"fr",value:1}],rows:[{mode:"fr",value:1},{mode:"fr",value:1}]};break;case"flex":n={mode:"flex",direction:"row"};break;default:return void console.warn(`[hc-canvas/handle] setRootLayout: 未知 mode "${e}",忽略`)}else n=e;t.dispatch({type:"setRootLayout",payload:{rootLayout:n}})},getInstanceTree:s,getInstanceList:function(){return t.document.document.instances.map(e=>JSON.parse(JSON.stringify(e)))},getInstance:function(e){const n=t.document.getInstance(e);return n?JSON.parse(JSON.stringify(n)):null},getSelectedPath:function(){const e=t.selection.primaryId.value;return e?kn(s(),e):[]},getBreadcrumb:function(e){return Sn(t.document.document.instances,e).map(e=>JSON.parse(JSON.stringify(e)))},focusInstance:function(e){t.document.getInstance(e)?(t.dispatch({type:"select",payload:{instanceId:e}}),d(e,"focusInstance")):console.warn(`[hc-canvas/handle] focusInstance: instance "${e}" 不存在`)},scrollToInstance:function(e){d(e,"scrollToInstance")},moveInstanceInTree:function(e,n){var i,a,r;const c=In(t.document.document.instances,e,n,{resolveContract:o.resolveContract});if(!c.ok)return console.warn(`[hc-canvas/handle] moveInstanceInTree 守门拒绝(${c.reason}): ${c.message}`),void function(e,n,t,o){u++,l.value={instanceId:e,target:{...n},reason:t,message:o,token:u}}(e,n,c.reason,c.message??`reparent rejected: ${c.reason}`);const s=t.document.getInstance(e),d=null===n.parentId?void 0:n.parentId,p=(s.parentId||void 0)!==(d||void 0),f=s.slot!==n.slot,h={};if(p&&(h.parentId=d),f&&(h.slot=n.slot),p){const e=void 0===d?"canvas":"container";s.placement!==e&&(h.placement=e);const n=t.document.document.layout,o=void 0===d?(null==(i=null==n?void 0:n.rootLayout)?void 0:i.mode)??"free":(null==(r=null==(a=t.document.getInstance(d))?void 0:a.containerLayout)?void 0:r.mode)??"none";if(s.layoutBox)if("container"!==e||"flex"!==o&&"split"!==o&&"grid"!==o){if("canvas"===e){const e="fill"===s.layoutBox.widthMode?"px":s.layoutBox.widthMode,n="fill"===s.layoutBox.heightMode?"px":s.layoutBox.heightMode;e===s.layoutBox.widthMode&&n===s.layoutBox.heightMode||(h.layoutBox={...s.layoutBox,widthMode:e,heightMode:n})}}else h.layoutBox={...s.layoutBox,x:0,y:0,widthMode:"fill",heightMode:"fill"},h.rect={x:0,y:0,w:s.rect.w,h:s.rect.h};if("container"===e&&"grid"===o){const e=s.layoutItem??{};void 0!==e.row&&void 0!==e.column||(h.layoutItem={...e,row:e.row??1,column:e.column??1})}}const g=[];if(void 0!==n.index){const o=Bn(t.document.document.instances,d,n.slot).filter(n=>n.instanceId!==e),i=Math.max(0,Math.min(n.index,o.length));o.splice(i,0,s),o.forEach((e,n)=>{const t=o.length-1-n;(e.zIndex??0)!==t&&g.push({id:e.instanceId,zIndex:t})})}if(0===Object.keys(h).length&&0===g.length)return;const m=!t.isBatching.value;m&&t.beginBatch();try{Object.keys(h).length>0&&t.dispatch({type:"updateInstance",payload:{instanceId:e,patch:h}});for(const e of g)t.dispatch({type:"updateInstance",payload:{instanceId:e.id,patch:{zIndex:e.zIndex}}})}finally{m&&t.endBatch("moveInstanceInTree")}},canReparent:function(e,n){return In(t.document.document.instances,e,n,{resolveContract:o.resolveContract})},cannotReparentEvent:e.readonly(l),cannotDragLayoutManagedChildEvent:t.cannotDragLayoutManagedChildEvent,resolveAsset:function(e){return t.resolveAsset(e)},getViewportState:h,getVisibleBounds:function(){const e=f();return e?Ln(h(),e):{x:0,y:0,w:0,h:0}},getCanvasBounds:function(){const e=t.measuredCanvasSize.value;return{x:0,y:0,w:e.w,h:e.h}},getContentBounds:g,getSelectionBounds:m,getInstanceBounds:function(e){const n=t.document.getInstance(e);return n?{...n.rect}:null},panBy:function(e,n){t.viewport.setPan(t.viewport.panX.value+e,t.viewport.panY.value+n)},panTo:function(e,n){t.viewport.setPan(e,n)},zoomTo:v,zoomBy:y,zoomToPoint:function(e,n){const i=o.getStageEl();if(!i)return void console.warn("[hc-canvas/handle] zoomToPoint: stage 未挂载,跳过");const a=i.getBoundingClientRect(),r=n.x-a.left,c=n.y-a.top,s=h(),d=r-(r-s.panX)/s.scale*e,l=c-(c-s.panY)/s.scale*e;t.viewport.setScale(e),t.viewport.setPan(d,l)},resetViewport:I,fitToContent:x,fitToSelection:b,scrollToRect:w,toolMode:t.toolMode,getToolMode:function(){return t.toolMode.value},setToolMode:function(e){t.setToolMode(e)},setTemporaryToolMode:function(e){t.setTemporaryToolMode(e)},getDefaultShortcuts:function(){return[{id:"undo",keys:["mod+z"],command:"undo",when:"notEditingText"},{id:"redo",keys:["mod+shift+z","mod+y"],command:"redo",when:"notEditingText"},{id:"deleteSelection",keys:["delete","backspace"],command:"deleteSelection",when:"hasSelection"},{id:"duplicateSelection",keys:["mod+d"],command:"duplicateSelection",when:"hasSelection"},{id:"fitToSelectionOrContent",keys:["f"],command:"fitToSelectionOrContent",when:"notEditingText"},{id:"zoom100",keys:["1"],command:"zoom100",when:"notEditingText"},{id:"resetViewport",keys:["0"],command:"resetViewport",when:"notEditingText"},{id:"zoomIn",keys:["+","="],command:"zoomIn",when:"notEditingText"},{id:"zoomOut",keys:["-"],command:"zoomOut",when:"notEditingText"},{id:"nudgeLeft",keys:["arrowleft"],command:"nudgeSelection",payload:{dx:-1,dy:0},when:"hasSelection"},{id:"nudgeRight",keys:["arrowright"],command:"nudgeSelection",payload:{dx:1,dy:0},when:"hasSelection"},{id:"nudgeUp",keys:["arrowup"],command:"nudgeSelection",payload:{dx:0,dy:-1},when:"hasSelection"},{id:"nudgeDown",keys:["arrowdown"],command:"nudgeSelection",payload:{dx:0,dy:1},when:"hasSelection"},{id:"nudgeLeftLarge",keys:["shift+arrowleft"],command:"nudgeSelectionLarge",payload:{dx:-1,dy:0},when:"hasSelection"},{id:"nudgeRightLarge",keys:["shift+arrowright"],command:"nudgeSelectionLarge",payload:{dx:1,dy:0},when:"hasSelection"},{id:"nudgeUpLarge",keys:["shift+arrowup"],command:"nudgeSelectionLarge",payload:{dx:0,dy:-1},when:"hasSelection"},{id:"nudgeDownLarge",keys:["shift+arrowdown"],command:"nudgeSelectionLarge",payload:{dx:0,dy:1},when:"hasSelection"},{id:"cancelInteraction",keys:["escape"],command:"cancelInteraction",when:"notEditingText"}]},executeShortcut:function(e){for(const n of k){if(!Dn(n,e))continue;if(!L(n.when,e))continue;const t=C[n.command];return!!t&&!!t.canExecute()&&(t.execute(n.payload),!1!==n.preventDefault&&e.preventDefault(),!0)}return!1},executeCommand:function(e,n){const t=C[e];t?t.canExecute()&&t.execute(n):console.warn(`[hc-canvas/handle] executeCommand: 未知命令 "${e}"`)},canExecuteCommand:function(e){const n=C[e];return!!n&&n.canExecute()},getStaleComponentOverrides:function(){const e=t.document.document.componentOverrides??{},n=[];for(const o of t.document.document.instances){const t=e[o.instanceId];t&&t.baseVersionKey!==o.componentVersionKey&&n.push({instanceId:o.instanceId,baseVersionKey:t.baseVersionKey,currentVersionKey:o.componentVersionKey})}return n},setComponentOverride:z,discardComponentOverride:function(e){z(e,null)},getLayoutIssues:function(){return t.layoutIssues.value},setRulerVisible:D,setGridVisible:R,updateRulerConfig:function(e){const n=E();P({...n,ruler:{...n.ruler??{},...e}})},updateGridConfig:function(e){const n=E();P({...n,grid:{...n.grid??{},...e}})},addGuide:function(e){const n=E(),t=n.items??[],o=e.id??function(){var e;const n="undefined"!=typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;return`g_${(null==(e=null==n?void 0:n.randomUUID)?void 0:e.call(n).replace(/-/g,"").slice(0,8))??Math.random().toString(36).slice(2,10)}`}();if(t.some(e=>e.id===o))return console.warn(`[hc-canvas/handle] addGuide: id "${o}" 已存在,忽略`),o;const i={id:o,axis:e.axis,position:e.position};return void 0!==e.locked&&(i.locked=e.locked),void 0!==e.label&&(i.label=e.label),P({...n,items:[...t,i]}),o},removeGuide:function(e){const n=E(),t=n.items??[];t.some(n=>n.id===e)&&P({...n,items:t.filter(n=>n.id!==e)})},updateGuide:function(e,n){const t=E(),o=t.items??[],i=o.findIndex(n=>n.id===e);if(i<0)return void console.warn(`[hc-canvas/handle] updateGuide: id "${e}" 不存在,忽略`);const{id:a,...r}=n,c={...o[i],...r},s=[...o];s[i]=c,P({...t,items:s})},getGuides:function(){return(E().items??[]).map(e=>({...e}))},clearGuides:function(){const e=E();e.items&&0!==e.items.length&&P({...e,items:[]})},getMouseCanvasPoint:function(){const e=t.mouseCanvasPoint.value;return e?{x:e.x,y:e.y}:null},getInstanceSize:function(e){const n=t.document.getInstance(e);if(n&&void 0!==n.size)return JSON.parse(JSON.stringify(n.size))},updateInstanceSize:function(e,n){t.dispatch({type:"setInstanceSize",payload:{instanceId:e,size:n}})},getContainerLayout:function(e){const n=t.document.getInstance(e);return n&&void 0!==n.containerLayout?JSON.parse(JSON.stringify(n.containerLayout)):null},updateContainerLayout:function(e,n){t.dispatch({type:"setContainerLayout",payload:{instanceId:e,containerLayout:n}})},getInstanceOutletRect:function(e,n){if("undefined"==typeof document||"function"!=typeof document.querySelector)return null;const t=n??"default",o=""===t?"default":t,i=`[data-instance-id="${p(e)}"]`,a=`[data-hc-slot="${p(o)}"]`,r=document.querySelector(`${i} ${a}`);return r&&r instanceof HTMLElement?r.getBoundingClientRect():null},getLayoutBox:function(e){const n=t.document.getInstance(e);if(n&&void 0!==n.layoutBox)return JSON.parse(JSON.stringify(n.layoutBox))},updateLayoutBox:function(e,n){t.dispatch({type:"updateLayoutBox",payload:{instanceId:e,patch:n}})},getLayoutItem:function(e){const n=t.document.getInstance(e);if(n&&void 0!==n.layoutItem)return JSON.parse(JSON.stringify(n.layoutItem))},updateLayoutItem:function(e,n){t.dispatch({type:"updateLayoutItem",payload:{instanceId:e,patch:n}})},getRotation:function(e){const n=t.document.getInstance(e);if(!n)return 0;const o=n.rotation;return"number"==typeof o&&Number.isFinite(o)?o:0},updateRotation:function(e,n){t.dispatch({type:"updateRotation",payload:{instanceId:e,value:n}})},setBindingMode:function(e){null==F||F.setMode(e)},getBindingMode:function(){return(null==F?void 0:F.getMode())??"off"},testBinding:function(e,n){return(null==F?void 0:F.testBinding(e,n))??[]},on:function(e,t){if(K)return()=>{};if("instance:ready"===e||"instance:unmounted"===e){const o=e,i=t,a=n.onInstanceLifecycle(o,e=>{e.canvasId===V&&i(e.instanceId)});let r=!1;const c=()=>{r||(r=!0,_.delete(c),a())};return _.add(c),c}return F?F.on(e,t):()=>{}},attachBindingDelegate:function(e,n){K||(F=e,null===e?j=null:arguments.length>=2&&(j=n??null))},invalidateDataSource:function(e){null==j||j.invalidate(e)},getDataSourceSnapshot:function(){return(null==j?void 0:j.getSnapshot())??{entries:[]}},getCachedBySourceId:function(e,n){return null==j?void 0:j.getCachedBySourceId(e,n)},getInstanceReady:function(e){return K?Promise.reject(new On):"string"!=typeof e||0===e.length?Promise.reject(new TypeError("getInstanceReady: instanceId must be a non-empty string")):n.getInstance(e,V)?Promise.resolve():new Promise((t,o)=>{let i,a,r=!1;const c=()=>{r=!0;try{null==i||i()}catch{}a&&q.delete(a)};i=n.onInstanceLifecycle("instance:ready",n=>{r||n.canvasId===V&&n.instanceId===e&&(c(),t())}),a={off:i,reject:e=>{r||(c(),o(e))}},q.add(a),!r&&n.getInstance(e,V)&&(c(),t())})},getInstanceRuntime:function(e){return K?null:n.getInstance(e,V)},startTracing:function(e){null==F||F.startTracing(e)},stopTracing:function(){return(null==F?void 0:F.stopTracing())??[]},getTraceBuffer:function(){return(null==F?void 0:F.getTraceBuffer())??[]},dispose:function(){if(K)return;K=!0;const e=[...q];q.clear();for(const n of e)try{n.reject(new On)}catch(e){console.error("[hc-canvas/handle] pending ready rejection threw on dispose",e)}const n=[..._];_.clear();for(const e of n)try{e()}catch(e){console.error("[hc-canvas/handle] instance listener off threw on dispose",e)}F=null,j=null,i.dispose()}}}const An=Symbol("hc:canvas:reparent-bridge");function Nn(e){return"preview"===e||"runtime"===e?"runtime":"off"}const Fn=(e=>{const n=e.__vccOpts||e;for(const[e,t]of[["__scopeId","data-v-825e0ee8"]])n[e]=t;return n})(e.defineComponent({__name:"CanvasStage",setup(n){const t=ne(),o=e.ref(null);let i=null;const a=e.computed(()=>{const{scale:e,panX:n,panY:o}=t.viewport.state;return`translate(${n}px, ${o}px) scale(${e})`});function r(){const e=o.value;if(!e)return;const n=e.getBoundingClientRect();t.setMeasuredStageSize({w:n.width,h:n.height})}return e.onMounted(()=>{e.nextTick(r),"undefined"!=typeof ResizeObserver&&o.value&&(i=new ResizeObserver(r),i.observe(o.value)),window.addEventListener("resize",r)}),e.onBeforeUnmount(()=>{null==i||i.disconnect(),i=null,window.removeEventListener("resize",r)}),(n,t)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"stageEl",ref:o,class:"hc-canvas-stage","data-hc-stage":""},[e.createElementVNode("div",{class:"hc-canvas-stage__world","data-hc-stage-world":"",style:e.normalizeStyle({transform:a.value,transformOrigin:"0 0"})},[e.renderSlot(n.$slots,"default",{},void 0,!0)],4)],512))}})),jn=["data-mode"],Vn=e.defineComponent({__name:"RuntimeLayer",props:{componentSourceMap:{},mode:{default:"design"},schedulerOptions:{},canvasId:{}},setup(n){const t=ne(),o=e.computed(()=>t.document.document);return(i,a)=>(e.openBlock(),e.createElementBlock("div",{class:"hc-runtime-layer","data-hc-runtime-layer":"","data-mode":n.mode,style:e.normalizeStyle({position:"absolute",top:0,left:0,pointerEvents:e.unref(t).effectiveBehavior.value.selectable?"none":"auto"})},[e.createVNode(Ve,{document:o.value,"component-source-map":n.componentSourceMap,"scheduler-options":n.schedulerOptions,"canvas-id":n.canvasId},null,8,["document","component-source-map","scheduler-options","canvas-id"])],12,jn))}});function qn(e,n,t,o=0){if(!n||n.length<2)return[];if(e.w<=0||e.h<=0)return[];const i=n.map(e=>"number"==typeof e&&Number.isFinite(e)&&e>0?e:0),a=i.reduce((e,n)=>e+n,0);if(a<=0)return[];const r=i.length-1,c=Math.max(0,o)*r,s="horizontal"===t?e.w:e.h,d=Math.max(0,s-c);if(d<=0)return[];const l=o>0?o:8,u=[];let p=0;for(let n=0;n<r;n++){p+=i[n]/a*d;const r=p+n*o+o/2;let c;c="horizontal"===t?{x:e.x+r-l/2,y:e.y,w:l,h:e.h}:{x:e.x,y:e.y+r-l/2,w:e.w,h:l},u.push({index:n,rect:c,direction:t})}return u}function _n(e,n,t,o,i=0){if(!e||n<0||n>=e.length-1)return e.slice();const a=e.map(e=>"number"==typeof e&&Number.isFinite(e)&&e>0?e:0),r=a[n],c=a[n+1],s=r+c;if(s<=0)return a;const d=a.length-1,l=Math.max(0,i)*d,u=Math.max(0,o-l);if(u<=0)return a;const p=a.reduce((e,n)=>e+n,0);if(p<=0)return a;const f=t/u*p,h=.05*p;let g=r+f,m=c-f;g<h&&(g=h,m=s-h),m<h&&(m=h,g=s-h);const v=a.slice();return v[n]=g,v[n+1]=m,v}function Kn(n){const t=e.reactive({status:"idle",parentId:null,dividerIndex:null,startRatios:null,childIds:null,parentAxisPx:0,startPt:null,direction:null,gap:0}),o=e.computed(()=>"active"===t.status);function i(){t.status="idle",t.parentId=null,t.dividerIndex=null,t.startRatios=null,t.childIds=null,t.parentAxisPx=0,t.startPt=null,t.direction=null,t.gap=0}return{drag:t,isDragging:o,handleSplitDividerStart:function(e){if(!e.parentId)return{startTracking:!1};if(e.dividerIndex<0)return{startTracking:!1};if(!e.startRatios||e.startRatios.length<2)return{startTracking:!1};if(!e.childIds||e.childIds.length<=e.dividerIndex+1||!e.childIds[e.dividerIndex]||!e.childIds[e.dividerIndex+1])return{startTracking:!1};const o=n.document.getInstance(e.parentId);return o&&o.containerLayout&&"split"===o.containerLayout.mode?(t.status="active",t.parentId=e.parentId,t.dividerIndex=e.dividerIndex,t.startRatios=e.startRatios.slice(),t.childIds=e.childIds.slice(),t.parentAxisPx=e.parentAxisPx,t.startPt={...e.canvasPt},t.direction=e.direction,t.gap=e.gap,n.beginBatch(),{startTracking:!0}):{startTracking:!1}},handleSplitDividerMove:function(e){var o,i;if("active"!==t.status)return;if(!(t.startPt&&t.startRatios&&t.childIds&&t.direction&&null!==t.dividerIndex))return;const a=n.document.getInstance(t.parentId);if(!a||!a.containerLayout||"split"!==a.containerLayout.mode)return;const r="horizontal"===t.direction?e.x-t.startPt.x:e.y-t.startPt.y,c=_n(t.startRatios,t.dividerIndex,r,t.parentAxisPx,t.gap),s=t.dividerIndex,d=t.childIds[s],l=t.childIds[s+1];if(!d||!l)return;const u=c[s],p=c[s+1],f=n.document.getInstance(d),h=n.document.getInstance(l),g=null==(o=null==f?void 0:f.layoutItem)?void 0:o.ratio,m=null==(i=null==h?void 0:h.layoutItem)?void 0:i.ratio;g===u&&m===p||(n.dispatch({type:"updateLayoutItem",payload:{instanceId:d,patch:{ratio:u}}}),n.dispatch({type:"updateLayoutItem",payload:{instanceId:l,patch:{ratio:p}}}))},handleSplitDividerEnd:function(){"active"===t.status&&(n.endBatch("split-divider-drag"),i())},cancelSplitDividerDrag:function(){"active"===t.status&&n.endBatch("split-divider-cancel"),i()}}}function Jn(e){return!0===(e.lockPosition??e.locked)}function Un(e){return!0===(e.lockSize??e.locked)}function Hn(e){return Jn(e)||Un(e)}const Xn=["data-mode"],Yn=["data-selection-box","data-locked","data-placement"],Gn=["data-lock-badge"],Wn=["data-resize-handle","data-resize-instance","onPointerdown"],Qn=["data-hc-divider-direction","data-hc-divider-index","data-hc-parent-id","data-hc-divider-dragging","onPointerdown"],Zn=["data-axis","data-kind"],et=["data-hc-reparent-state"],nt=["data-hc-reparent-ghost-reason"],tt={key:0,"data-hc-reparent-ghost-reason-chip":"",style:{flex:"none",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",fontSize:"10px",lineHeight:"14px",padding:"0 4px",borderRadius:"2px",background:"rgba(0, 0, 0, 0.25)",color:"#fff",whiteSpace:"nowrap"}},ot=e.defineComponent({__name:"InteractionLayer",props:{mode:{default:"design"}},emits:["cannot-drag-slot-child","cannot-drag-layout-managed-child"],setup(n,{emit:t}){const o=t,i=ne(),a=vn(i,{getRoot:()=>$(),getDomBox:e=>{const n=un(e,$(),i.viewport);return n?0===n.w&&0===n.h?null:n:null}}),r=Kn(i),c=e.inject(An,null);e.watch(()=>a.cannotDragSlotChildEvent.value,e=>{e&&o("cannot-drag-slot-child",{instanceId:e.instanceId,parentId:e.parentId})},{flush:"sync"}),e.watch(()=>a.cannotDragLayoutManagedChildEvent.value,e=>{e&&o("cannot-drag-layout-managed-child",{instanceId:e.instanceId,parentId:e.parentId,parentLayoutMode:e.parentLayoutMode})},{flush:"sync"});const s=e.ref(null);let d=null;const l=e.computed(()=>{const e=new Set(i.selection.selectedIds.value);return i.document.document.instances.filter(n=>e.has(n.instanceId)&&!n.hidden)}),u=e.computed(()=>i.measuredCanvasSize.value),p=e.shallowRef({});function f(){const e=$(),n={};for(const t of l.value)n[t.instanceId]=un(t.instanceId,e,i.viewport);p.value=n}let h=null;function g(){"undefined"!=typeof requestAnimationFrame?null===h&&(h=requestAnimationFrame(()=>{h=null,f()})):f()}let m=null;function v(){m=null,f(),(a.isResizing.value||a.isDragging.value||r.isDragging.value)&&(m=requestAnimationFrame(v))}function I(e){const n=p.value[e.instanceId];if(n)return n;const t=un(e.instanceId,$(),i.viewport);if(t&&(t.w>0||t.h>0))return t;const o=e.layoutBox;return o?{x:o.x,y:o.y,w:o.width,h:o.height}:{x:e.rect.x,y:e.rect.y,w:e.rect.w,h:e.rect.h}}e.watch(()=>i.selection.selectedIds.value,()=>{g()},{flush:"post",deep:!0}),e.watch(()=>i.viewport.scale.value,()=>g()),e.watch(()=>[i.viewport.panX.value,i.viewport.panY.value],()=>g()),e.watch(()=>l.value.map(e=>{const n=e.layoutBox;return n?`${n.x}|${n.y}|${n.width}|${n.height}|${n.widthMode}|${n.heightMode}`:""}),()=>g(),{flush:"post",deep:!0}),e.watch(()=>a.isResizing.value,e=>{e&&null===m&&(m=requestAnimationFrame(v))}),e.watch(()=>a.isDragging.value,e=>{e&&null===m&&(m=requestAnimationFrame(v))}),e.watch(()=>r.isDragging.value,e=>{e&&null===m&&(m=requestAnimationFrame(v))}),e.onMounted(()=>{g()});const w=e.computed(()=>l.value.map(e=>({instance:e,box:I(e)}))),x=e.computed(()=>{var e,n;if(!i.effectiveBehavior.value.resizable)return[];const t=[];for(const o of w.value){const a=o.instance;if(!0===(a.lockSize??a.locked))continue;if(!o.box)continue;const r=rn(i,a.instanceId),{x:c,y:s,w:d,h:l}=o.box,u=[{handle:"nw",cx:c,cy:s,cursor:"nwse-resize"},{handle:"n",cx:c+d/2,cy:s,cursor:"ns-resize"},{handle:"ne",cx:c+d,cy:s,cursor:"nesw-resize"},{handle:"e",cx:c+d,cy:s+l/2,cursor:"ew-resize"},{handle:"se",cx:c+d,cy:s+l,cursor:"nwse-resize"},{handle:"s",cx:c+d/2,cy:s+l,cursor:"ns-resize"},{handle:"sw",cx:c,cy:s+l,cursor:"nesw-resize"},{handle:"w",cx:c,cy:s+l/2,cursor:"ew-resize"}],p=null==(e=a.layoutBox)?void 0:e.widthMode,f=null==(n=a.layoutBox)?void 0:n.heightMode,h=u.filter(e=>ln(r,e.handle,p,f));for(const e of h)t.push({instanceId:a.instanceId,handle:e.handle,left:e.cx-4,top:e.cy-4,cursor:e.cursor})}return t});function b(e,n,t){return"percent"===n?`${Math.round(t)}%`:"fill"===n?"fill":"auto"===n?"auto":String(Math.round(e))}const k=e.computed(()=>{if(!a.isResizing.value)return null;const e=a.resize.instanceId;if(!e)return null;const n=i.document.getInstance(e);if(!n)return null;const t=I(n);if(!t)return null;const o=n.layoutBox,r=b(t.w,null==o?void 0:o.widthMode,(null==o?void 0:o.width)??t.w),c=b(t.h,null==o?void 0:o.heightMode,(null==o?void 0:o.height)??t.h);return{x:t.x,y:t.y,w:t.w,h:t.h,wText:r,hText:c}}),S={nw:"nwse-resize",se:"nwse-resize",ne:"nesw-resize",sw:"nesw-resize",n:"ns-resize",s:"ns-resize",w:"ew-resize",e:"ew-resize"};function B(e){var n;const t=[],o=[];for(const a of i.document.document.instances)a.parentId===e&&void 0===a.slot&&(t.push(a.instanceId),o.push(null==(n=a.layoutItem)?void 0:n.ratio));return{ids:t,ratios:o}}const M=e.computed(()=>{var e,n;const t=new Set;for(const o of l.value)if("split"===(null==(e=o.containerLayout)?void 0:e.mode)&&t.add(o.instanceId),o.parentId){const e=i.document.getInstance(o.parentId);"split"===(null==(n=null==e?void 0:e.containerLayout)?void 0:n.mode)&&t.add(e.instanceId)}if(0===t.size)return[];const o=[];for(const e of t){const n=i.document.getInstance(e);if(!n)continue;const t=n.containerLayout;if(!t||"split"!==t.mode)continue;const a=E(e)??I(n);if(!a)continue;const r=t,c=r.direction,s=r.gap??0,{ids:d,ratios:l}=B(e),u=y(r.ratios??[],l),p=qn(a,u,c,s);0!==p.length&&o.push({parentId:e,direction:c,gap:s,effectiveRatios:u,childIds:d,parentBox:a,dividers:p})}return o}),T=e.computed(()=>a.isResizing.value&&a.resize.handle?S[a.resize.handle]:r.isDragging.value?"horizontal"===r.drag.direction?"ew-resize":"ns-resize":a.isDragging.value?"grabbing":"hand"===i.toolMode.value?F?"grabbing":"grab":"marquee"===i.toolMode.value?"crosshair":"default"),C=e.shallowRef(null);function z(){if(!c)return!1;if(!a.isDragging.value)return!1;if(1!==a.drag.startRects.size)return!1;const e=Array.from(a.drag.startRects.keys())[0],n=i.document.getInstance(e);return!(!n||void 0!==n.placement&&"canvas"!==n.placement&&"absolute"!==n.placement||!0===(n.lockPosition??n.locked)||n.hidden)}function L(e){const n=$();if(!n)return null;const t=e.getBoundingClientRect(),o=n.getBoundingClientRect(),a=i.viewport.toCanvasPoint({x:t.left-o.left,y:t.top-o.top}),r=i.viewport.toCanvasPoint({x:t.right-o.left,y:t.bottom-o.top});return{x:a.x,y:a.y,w:Math.max(0,r.x-a.x),h:Math.max(0,r.y-a.y)}}function E(e){var n;const t=$();if(!t)return null;const o=tn(t,`[data-instance-id="${("undefined"!=typeof globalThis&&(null==(n=globalThis.CSS)?void 0:n.escape)?globalThis.CSS.escape:e=>e.replace(/["\\]/g,e=>`\\${e}`))(e)}"] [data-hc-slot="default"]`);return o&&o instanceof HTMLElement?L(o):null}let P=null,D=null;function R(e){if(!z()||!c)return void(null!==C.value&&(C.value=null));const n=Array.from(a.drag.startRects.keys())[0],t=c.getDropTarget(e,{excludeInstanceId:n});if(!t)return void(null!==C.value&&(C.value=null));const o=i.document.getInstance(n);if(o&&o.parentId===t.parentId&&(o.slot??"default")===(t.slot||"default"))return void(null!==C.value&&(C.value=null));const r=L(t.outletEl);if(!r)return void(null!==C.value&&(C.value=null));const s={parentId:t.parentId,slot:t.slot},d=c.canReparent(n,s);C.value={rect:r,target:t,result:d}}const O=e.computed(()=>C.value);function $(){return d||(s.value?(d=s.value.closest("[data-hc-stage]"),d):null)}function A(e){const n=$();if(!n)return;const t=gn({x:e.clientX,y:e.clientY},n,i.viewport);i.setMouseCanvasPoint(t)}function N(){i.setMouseCanvasPoint(null)}let F=null;function j(e){if(0!==e.button)return;const n=$();if(!n)return;if("hand"===i.toolMode.value)return F={clientX:e.clientX,clientY:e.clientY,panX:i.viewport.panX.value,panY:i.viewport.panY.value},window.addEventListener("pointermove",V),window.addEventListener("pointerup",q),void e.preventDefault();const t=gn({x:e.clientX,y:e.clientY},n,i.viewport),{startTracking:o}=a.handlePointerDown(t,{shift:e.shiftKey,ctrl:e.ctrlKey,meta:e.metaKey});o&&(_(),e.preventDefault())}function V(e){if(!F)return;const n=e.clientX-F.clientX,t=e.clientY-F.clientY;i.viewport.setPan(F.panX+n,F.panY+t)}function q(){F=null,window.removeEventListener("pointermove",V),window.removeEventListener("pointerup",q)}function _(){window.addEventListener("pointermove",K),window.addEventListener("pointerup",J),window.addEventListener("keydown",U)}function K(e){const n=$();if(!n)return;const t=gn({x:e.clientX,y:e.clientY},n,i.viewport);var o;a.handlePointerMove(t),r.handleSplitDividerMove(t),r.isDragging.value&&g(),o={x:e.clientX,y:e.clientY},P=o,"undefined"!=typeof requestAnimationFrame?null===D&&(D=requestAnimationFrame(()=>{D=null,P&&R(P)})):R(o)}function J(e){if(r.isDragging.value)return r.handleSplitDividerEnd(),void H();e&&c&&z()&&R({x:e.clientX,y:e.clientY}),null!==D&&"undefined"!=typeof cancelAnimationFrame&&(cancelAnimationFrame(D),D=null);const n=C.value;if(n&&c){const e=Array.from(a.drag.startRects.keys())[0];return n.result.ok&&e?(a.cancelDrag(),c.moveInstanceInTree(e,{parentId:n.target.parentId,slot:n.target.slot})):a.cancelDrag(),C.value=null,void H()}a.handlePointerUp(),H()}function U(e){"Escape"===e.key&&(a.cancelResize(),a.cancelDrag(),a.cancelMarquee(),r.cancelSplitDividerDrag(),C.value=null,null!==D&&"undefined"!=typeof cancelAnimationFrame&&(cancelAnimationFrame(D),D=null),q(),H())}function H(){window.removeEventListener("pointermove",K),window.removeEventListener("pointerup",J),window.removeEventListener("keydown",U)}return e.onBeforeUnmount(()=>{a.cancelResize(),a.cancelDrag(),a.cancelMarquee(),r.cancelSplitDividerDrag(),C.value=null,H(),q(),null!==h&&"undefined"!=typeof cancelAnimationFrame&&(cancelAnimationFrame(h),h=null),null!==m&&"undefined"!=typeof cancelAnimationFrame&&(cancelAnimationFrame(m),m=null),null!==D&&"undefined"!=typeof cancelAnimationFrame&&(cancelAnimationFrame(D),D=null),P=null}),(t,o)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"layerEl",ref:s,class:"hc-interaction-layer","data-hc-interaction-layer":"","data-mode":n.mode,style:e.normalizeStyle({position:"absolute",top:0,left:0,width:u.value.w+"px",height:u.value.h+"px",pointerEvents:e.unref(i).effectiveBehavior.value.selectable?"auto":"none",cursor:T.value,zIndex:9999}),onPointerdown:j,onPointermove:A,onPointerleave:N},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(w.value,n=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:"sel-"+n.instance.instanceId},[n.box?(e.openBlock(),e.createElementBlock("div",{key:0,class:"hc-selection-box","data-selection-box":n.instance.instanceId,"data-locked":e.unref(Hn)(n.instance)?"true":"false","data-placement":n.instance.placement??"absolute",style:e.normalizeStyle({position:"absolute",left:n.box.x+"px",top:n.box.y+"px",width:n.box.w+"px",height:n.box.h+"px",border:"2px solid "+(e.unref(Hn)(n.instance)?"#9ca3af":"#3b82f6"),boxSizing:"border-box",pointerEvents:"none",boxShadow:"0 0 0 1px rgba(59, 130, 246, 0.2)"})},null,12,Yn)):e.createCommentVNode("",!0)],64))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(w.value.filter(n=>e.unref(Hn)(n.instance)),n=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:"lock-"+n.instance.instanceId},[n.box?(e.openBlock(),e.createElementBlock("div",{key:0,class:"hc-lock-badge","data-lock-badge":n.instance.instanceId,style:e.normalizeStyle({position:"absolute",left:n.box.x+n.box.w-18+"px",top:n.box.y+2+"px",width:"16px",height:"16px",background:"#9ca3af",color:"#fff",fontSize:"11px",lineHeight:"16px",textAlign:"center",borderRadius:"3px",pointerEvents:"none",userSelect:"none"})},"🔒",12,Gn)):e.createCommentVNode("",!0)],64))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(x.value,n=>(e.openBlock(),e.createElementBlock("div",{key:"rh-"+n.instanceId+"-"+n.handle,class:"hc-resize-handle","data-resize-handle":n.handle,"data-resize-instance":n.instanceId,style:e.normalizeStyle({position:"absolute",left:n.left+"px",top:n.top+"px",width:"8px",height:"8px",background:"#fff",border:"1px solid #3b82f6",boxSizing:"border-box",cursor:n.cursor,pointerEvents:"auto",zIndex:2}),onPointerdown:e=>function(e,n,t){if(0!==e.button)return;e.stopPropagation();const o=$();if(!o)return;const r=gn({x:e.clientX,y:e.clientY},o,i.viewport),{startTracking:c}=a.handleResizeStart(n,t,r);c&&(_(),e.preventDefault())}(e,n.instanceId,n.handle)},null,44,Wn))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(M.value,n=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:"sd-parent-"+n.parentId},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.dividers,o=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:"sd-"+n.parentId+"-"+o.index},[t.$slots["split-divider"]?e.renderSlot(t.$slots,"split-divider",{key:0,state:{parentId:n.parentId,dividerIndex:o.index,direction:o.direction,rect:o.rect,isDragging:e.unref(r).isDragging.value&&e.unref(r).drag.parentId===n.parentId&&e.unref(r).drag.dividerIndex===o.index}}):(e.openBlock(),e.createElementBlock("div",{key:1,class:"hc-split-divider","data-hc-divider-direction":o.direction,"data-hc-divider-index":o.index,"data-hc-parent-id":n.parentId,"data-hc-divider-dragging":e.unref(r).isDragging.value&&e.unref(r).drag.parentId===n.parentId&&e.unref(r).drag.dividerIndex===o.index?"true":"false",style:e.normalizeStyle({position:"absolute",left:o.rect.x+"px",top:o.rect.y+"px",width:o.rect.w+"px",height:o.rect.h+"px",background:e.unref(r).isDragging.value&&e.unref(r).drag.parentId===n.parentId&&e.unref(r).drag.dividerIndex===o.index?"rgba(59, 130, 246, 0.6)":"rgba(59, 130, 246, 0.18)",cursor:"horizontal"===o.direction?"ew-resize":"ns-resize",pointerEvents:"auto",boxSizing:"border-box",zIndex:3}),onPointerdown:e=>function(e,n,t){if(0!==e.button)return;e.stopPropagation();const o=$();if(!o)return;const a=i.document.getInstance(n);if(!a)return;const c=a.containerLayout;if(!c||"split"!==c.mode)return;const s=c,d=E(n)??I(a);if(!d)return;const l="horizontal"===s.direction?d.w:d.h,{ids:u,ratios:p}=B(n),f=y(s.ratios??[],p),h=gn({x:e.clientX,y:e.clientY},o,i.viewport),{startTracking:g}=r.handleSplitDividerStart({parentId:n,dividerIndex:t,startRatios:f,childIds:u,parentAxisPx:l,direction:s.direction,gap:s.gap??0,canvasPt:h});g&&(_(),e.preventDefault())}(e,n.parentId,o.index)},null,44,Qn))],64))),128))],64))),128)),k.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"hc-resize-badge","data-resize-badge":"",style:e.normalizeStyle({position:"absolute",left:k.value.x+"px",top:k.value.y-22+"px",padding:"2px 6px",background:"#3b82f6",color:"#fff",fontSize:"11px",lineHeight:"14px",borderRadius:"3px",pointerEvents:"none",userSelect:"none",whiteSpace:"nowrap",fontFamily:"ui-monospace, SFMono-Regular, monospace"})},e.toDisplayString(k.value.wText)+" × "+e.toDisplayString(k.value.hText),5)):e.createCommentVNode("",!0),e.unref(a).marqueeRect.value?(e.openBlock(),e.createElementBlock("div",{key:1,class:"hc-marquee-box","data-marquee-box":"",style:e.normalizeStyle({position:"absolute",left:e.unref(a).marqueeRect.value.x+"px",top:e.unref(a).marqueeRect.value.y+"px",width:e.unref(a).marqueeRect.value.w+"px",height:e.unref(a).marqueeRect.value.h+"px",border:"1px dashed #3b82f6",background:"rgba(59, 130, 246, 0.08)",pointerEvents:"none",boxSizing:"border-box"})},null,4)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(a).snapLines.value,(n,t)=>(e.openBlock(),e.createElementBlock("div",{key:"snap-"+t,class:"hc-snap-line","data-snap-line":"","data-axis":n.axis,"data-kind":n.kind,style:e.normalizeStyle("x"===n.axis?{position:"absolute",left:n.pos+"px",top:n.from+"px",width:"0px",height:n.to-n.from+"px",borderLeft:"1px dashed #ec4899",pointerEvents:"none"}:{position:"absolute",left:n.from+"px",top:n.pos+"px",width:n.to-n.from+"px",height:"0px",borderTop:"1px dashed #ec4899",pointerEvents:"none"})},null,12,Zn))),128)),O.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:2},[t.$slots["reparent-ghost"]?e.renderSlot(t.$slots,"reparent-ghost",{key:0,state:O.value}):(e.openBlock(),e.createElementBlock("div",{key:1,class:"hc-reparent-ghost","data-hc-reparent-ghost":"","data-hc-reparent-state":O.value.result.ok?"legal":"illegal",style:e.normalizeStyle({position:"absolute",left:O.value.rect.x+"px",top:O.value.rect.y+"px",width:O.value.rect.w+"px",height:O.value.rect.h+"px",pointerEvents:"none",boxSizing:"border-box",border:"2px solid "+(O.value.result.ok?"#22c55e":"#ef4444"),background:O.value.result.ok?"rgba(34, 197, 94, 0.12)":"rgba(239, 68, 68, 0.12)"})},[!O.value.result.ok&&O.value.result.message?(e.openBlock(),e.createElementBlock("div",{key:0,class:"hc-reparent-ghost__message","data-hc-reparent-ghost-message":"","data-hc-reparent-ghost-reason":O.value.result.reason||"",style:{position:"absolute",left:"0",top:"100%",marginTop:"4px",maxWidth:"280px",padding:"3px 6px",background:"#ef4444",color:"#fff",fontSize:"11px",lineHeight:"16px",borderRadius:"3px",whiteSpace:"normal",wordBreak:"break-all",pointerEvents:"none",display:"flex",flexWrap:"wrap",alignItems:"baseline",gap:"4px"}},[O.value.result.reason?(e.openBlock(),e.createElementBlock("span",tt,"["+e.toDisplayString(O.value.result.reason)+"]",1)):e.createCommentVNode("",!0),e.createElementVNode("span",null,e.toDisplayString(O.value.result.message),1)],8,nt)):e.createCommentVNode("",!0)],12,et))],64)):e.createCommentVNode("",!0)],44,Xn))}}),it=e.defineComponent({__name:"HyperCardCanvasDesigner",props:{modelValue:{},componentSourceMap:{},mode:{default:"design"},schedulerOptions:{},adapters:{},canvasId:{}},emits:["update:modelValue","context-ready","handle-ready","cannot-drag-slot-child","cannot-drag-layout-managed-child"],setup(n,{expose:t,emit:o}){const i=n,a=o;let r=!1;const c=i.canvasId??function(){const e=globalThis.crypto;return e&&"function"==typeof e.randomUUID?`hc-designer-${e.randomUUID()}`:`hc-designer-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}(),s=Z({canvasId:c,initialDocument:i.modelValue,getMode:()=>i.mode,adapters:i.adapters});ee(s);const d=e.ref(null),l=$n(s,{getStageEl:()=>{var e;return(null==(e=d.value)?void 0:e.querySelector("[data-hc-stage]"))??null},resolveContract:function(e){var n;const t=null==(n=i.componentSourceMap)?void 0:n[e];if(t)return"contract"in t&&t.contract?t.contract:void 0}}),u=!!s.adapters.data,p=Ie({canvasId:c,source:{getDocument:()=>s.document.document,onAction:e=>s.registerHooks({onAfterAction:n=>e(n)})},initialMode:Nn(i.mode),dataStore:u?s.dataStore:void 0});l.attachBindingDelegate(p,u?s.dataStore:null),a("context-ready",s),a("handle-ready",l);const f={getDropTarget:(e,n)=>l.getDropTarget(e,d.value,n),canReparent:(e,n)=>l.canReparent(e,n),moveInstanceInTree:(e,n)=>l.moveInstanceInTree(e,n),cannotReparentEvent:l.cannotReparentEvent};function h(){a("update:modelValue",JSON.parse(JSON.stringify(s.document.document)))}return e.provide(An,f),e.watch(()=>i.modelValue,(e,n)=>{if(e&&e!==n){r=!0;try{s.suppressRecording(()=>{s.dispatch({type:"replaceDocument",payload:{document:e}})})}finally{r=!1}}}),e.watch(()=>s.document.document,()=>{r||s.isBatching.value||h()},{deep:!0,flush:"sync"}),e.watch(()=>s.isBatching.value,(e,n)=>{!n||e||r||h()},{flush:"sync"}),e.onMounted(()=>{Je(c,l),e.nextTick(()=>{p.setMode(Nn(i.mode))})}),e.watch(()=>i.mode,e=>{p.setMode(Nn(e))}),e.onBeforeUnmount(()=>{p.dispose(),l.attachBindingDelegate(null,null),Ue(c),l.dispose(),s.dispose()}),t({context:s,handle:l,canvasId:c}),(t,o)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"stageContainerEl",ref:d,class:"hc-canvas-designer",style:{width:"100%",height:"100%",position:"relative"},"data-hc-canvas-designer":""},[e.createVNode(Fn,null,{default:e.withCtx(()=>[e.createVNode(Vn,{"component-source-map":n.componentSourceMap,mode:n.mode,"scheduler-options":n.schedulerOptions,"canvas-id":e.unref(c)},null,8,["component-source-map","mode","scheduler-options","canvas-id"]),"runtime"!==n.mode?(e.openBlock(),e.createBlock(ot,{key:0,mode:n.mode,onCannotDragSlotChild:o[0]||(o[0]=e=>a("cannot-drag-slot-child",e)),onCannotDragLayoutManagedChild:o[1]||(o[1]=e=>a("cannot-drag-layout-managed-child",e))},e.createSlots({_:2},[t.$slots["reparent-ghost"]?{name:"reparent-ghost",fn:e.withCtx(n=>[e.renderSlot(t.$slots,"reparent-ghost",e.normalizeProps(e.guardReactiveProps(n)))]),key:"0"}:void 0,t.$slots["split-divider"]?{name:"split-divider",fn:e.withCtx(n=>[e.renderSlot(t.$slots,"split-divider",e.normalizeProps(e.guardReactiveProps(n)))]),key:"1"}:void 0]),1032,["mode"])):e.createCommentVNode("",!0),e.renderSlot(t.$slots,"canvas-overlay",{viewport:e.unref(l).viewport,handle:e.unref(l)}),e.renderSlot(t.$slots,"default")]),_:3})],512))}});function at(e={}){const{canvasWidth:n=1280,canvasHeight:t=720,rootLayout:o="free",instances:i=[],bindings:a=[]}=e;return{schemaVersion:"1",layout:{type:"free",canvas:{width:{mode:"px",value:n},height:{mode:"px",value:t}},rootLayout:"string"==typeof o?{mode:o}:o},instances:i,bindings:a}}const rt={event:["instanceEvent"],init:["lifecycle","page"],data:["dataSource"]};function ct(e){return rt[e.type].includes(e.source.kind)}function st(e,n,t,o){const i={level:n,code:e,bindingId:t.id,message:`${e} on binding "${t.id}"`};return o.instanceId&&(i.instanceId=o.instanceId),o.canvasId&&(i.canvasId=o.canvasId),i}function dt(e){return"instanceEvent"===e.source.kind||"lifecycle"===e.source.kind?{instanceId:e.source.instanceId}:"instanceMethod"===e.target.kind||"instanceDataInput"===e.target.kind||"instanceEmit"===e.target.kind?{instanceId:e.target.instanceId}:{}}function lt(e){switch(e.source.kind){case"instanceEvent":case"lifecycle":return e.source.canvasId;case"page":case"dataSource":return}}function ut(e){switch(e.target.kind){case"instanceMethod":case"instanceEmit":case"instanceDataInput":return e.target.canvasId}}exports.CANVAS_CONTEXT_KEY=Q,exports.CANVAS_REPARENT_BRIDGE_KEY=An,exports.CanvasStage=Fn,exports.DEFAULT_FIT_PADDING=40,exports.DIVIDER_HIT_THICKNESS=8,exports.DRAG_THRESHOLD_CANVAS_PX=3,exports.EFFECTIVE_DEFAULT_SLOT=te,exports.HandleDisposedError=On,exports.HyperCardCanvasDesigner=it,exports.HyperCardPageRenderer=Ve,exports.InteractionLayer=ot,exports.MAX_INSTANCE_TREE_DEPTH=8,exports.MIN_INSTANCE_SIZE=8,exports.MIN_RATIO_FRACTION=.05,exports.RuntimeLayer=Vn,exports.SLOT_CHILD_RESIZE_HANDLES=["e","s","se"],exports.VERSION="0.0.0-d3.6c-stage",exports.applyEffectiveSplitRatiosToDocument=s,exports.applySplitDividerDrag=_n,exports.assertNeverBindingSource=V,exports.assertNeverBindingTarget=q,exports.bindingModeForCanvasMode=Nn,exports.bindingReferencesInstance=j,exports.buildInstanceTree=wn,exports.canReparent=In,exports.canvasSizeToCss=M,exports.cleanLayoutItem=A,exports.clientToCanvas=gn,exports.computeContentBounds=Tn,exports.computeEffectiveSplitRatios=y,exports.computeFit=zn,exports.computeInverse=He,exports.computeNextAxisSize=pn,exports.computeNextLayoutBoxAxis=fn,exports.computeParentLayoutMode=$,exports.computeSelectionBounds=Cn,exports.computeSlotChildCanvasRect=un,exports.computeSnap=Qe,exports.computeSplitDividers=qn,exports.computeVisibleBounds=Ln,exports.containerLayoutToCss=S,exports.createAssetResolver=X,exports.createCanvasContext=Z,exports.createCanvasHandle=$n,exports.createCanvasInteraction=vn,exports.createCommandRecorder=Ge,exports.createDocumentStore=J,exports.createFreePageDocument=function(e={}){return at({...e,rootLayout:"free"})},exports.createMinimalPageDocument=at,exports.createRenderScheduler=N,exports.createSelectionStore=U,exports.createSplitDividerInteraction=Kn,exports.createViewportStore=H,exports.deriveComponentContract=be,exports.deriveComponentKind=function(e,t){const o="string"==typeof(null==e?void 0:e.js)?e.js:"",i="string"==typeof(null==e?void 0:e.html)?e.html:"",a=n.parseComponentSource(o,i);return!a.ok&&(null==t?void 0:t.fallback)?t.fallback:a.kind},exports.effectiveSlot=oe,exports.emptyComponentContract=function(){return{propsDecl:[],emitsDecl:[],methodsDecl:[],slotsDecl:[],modelDecl:[],dataInputsDecl:[],dataOutputsDecl:[]}},exports.emptyPageDocument=function(){return{schemaVersion:"1",layout:{type:"free",canvas:{width:{mode:"fill"},height:{mode:"fill"}}},instances:[],bindings:[]}},exports.filterExistingIds=mn,exports.filterInstancesInRect=nn,exports.findInstanceBreadcrumb=Sn,exports.findInstancePath=kn,exports.getBindingInstanceRefs=F,exports.getDefaultShortcuts=function(){return[{id:"undo",keys:["mod+z"],command:"undo",when:"notEditingText"},{id:"redo",keys:["mod+shift+z","mod+y"],command:"redo",when:"notEditingText"},{id:"deleteSelection",keys:["delete","backspace"],command:"deleteSelection",when:"hasSelection"},{id:"duplicateSelection",keys:["mod+d"],command:"duplicateSelection",when:"hasSelection"},{id:"fitToSelectionOrContent",keys:["f"],command:"fitToSelectionOrContent",when:"notEditingText"},{id:"zoom100",keys:["1"],command:"zoom100",when:"notEditingText"},{id:"resetViewport",keys:["0"],command:"resetViewport",when:"notEditingText"},{id:"zoomIn",keys:["+","="],command:"zoomIn",when:"notEditingText"},{id:"zoomOut",keys:["-"],command:"zoomOut",when:"notEditingText"},{id:"nudgeLeft",keys:["arrowleft"],command:"nudgeSelection",payload:{dx:-1,dy:0},when:"hasSelection"},{id:"nudgeRight",keys:["arrowright"],command:"nudgeSelection",payload:{dx:1,dy:0},when:"hasSelection"},{id:"nudgeUp",keys:["arrowup"],command:"nudgeSelection",payload:{dx:0,dy:-1},when:"hasSelection"},{id:"nudgeDown",keys:["arrowdown"],command:"nudgeSelection",payload:{dx:0,dy:1},when:"hasSelection"},{id:"nudgeLeftLarge",keys:["shift+arrowleft"],command:"nudgeSelectionLarge",payload:{dx:-1,dy:0},when:"hasSelection"},{id:"nudgeRightLarge",keys:["shift+arrowright"],command:"nudgeSelectionLarge",payload:{dx:1,dy:0},when:"hasSelection"},{id:"nudgeUpLarge",keys:["shift+arrowup"],command:"nudgeSelectionLarge",payload:{dx:0,dy:-1},when:"hasSelection"},{id:"nudgeDownLarge",keys:["shift+arrowdown"],command:"nudgeSelectionLarge",payload:{dx:0,dy:1},when:"hasSelection"},{id:"cancelInteraction",keys:["escape"],command:"cancelInteraction",when:"notEditingText"}]},exports.getDesignerHandle=function(e){return qe.get(e)??null},exports.getInstanceWrapperRectFromDom=an,exports.getOutletRectFromDom=on,exports.getParentLayoutMode=rn,exports.getSiblings=Bn,exports.getSlotChildRectFromDom=function(e,n){var t;const o=n??("undefined"!=typeof document&&"function"==typeof document.querySelector?document:null);if(!o)return null;const i="undefined"!=typeof globalThis&&(null==(t=globalThis.CSS)?void 0:t.escape)?globalThis.CSS.escape:e=>e.replace(/["\\]/g,e=>`\\${e}`),a=o.querySelector(`[data-instance-id="${i(e)}"][data-hc-placement="slot"]`);return a&&a instanceof HTMLElement?a.getBoundingClientRect():null},exports.hitTestInstance=Ze,exports.isAdditive=hn,exports.isCanvasRootPlacement=function(e){return"canvas"===e||"absolute"===e||void 0===e},exports.isContainerChildPlacement=O,exports.isDraftKey=function(e){return"string"==typeof e&&e.includes("@draft:")},exports.isEditingText=Pn,exports.isFreePositionLayoutMode=cn,exports.isInstanceEffectivelyLocked=Hn,exports.isInstancePositionLocked=Jn,exports.isInstanceSizeLocked=Un,exports.isResizeHandleAllowed=ln,exports.isV1Layout=w,exports.layoutItemToCss=B,exports.listRegisteredCanvasIds=function(){return Object.freeze(Array.from(qe.keys()))},exports.matchBinding=Dn,exports.migrateGridCellsToLayoutItem=d,exports.migrateInstanceToLayoutBox=D,exports.migrateLayoutV0ToV1=I,exports.migratePlacementToCanvasContainer=P,exports.migrateRootLayout=R,exports.normalizeComponentOverrides=u,exports.normalizeGridCells0Based=l,exports.normalizeInstanceSlotFields=p,exports.normalizeKeyString=Rn,exports.normalizeMarqueeRect=en,exports.normalizePageBindings=i,exports.normalizePageDocument=c,exports.parseComponentVersionKey=function(e){if("string"!=typeof e||!e.includes("@"))return null;const n=e.indexOf("@"),t=e.slice(0,n),o=e.slice(n+1);if(!t)return null;if(o.startsWith("draft:")){const e=o.slice(6),n=e.indexOf(":");if(n<=0)return null;const i=e.slice(0,n),a=e.slice(n+1);return i&&a?{kind:"draft",componentId:t,pageId:i,baseVersion:a,baseVersionKey:`${t}@${a}`}:null}return o?{kind:"published",componentId:t,version:o}:null},exports.parseKeyEvent=En,exports.provideCanvasContext=ee,exports.registerDesignerHandle=Je,exports.renderLayoutBoxStyle=b,exports.resolveCanvasSizePx=function(e,n=1920){return"px"===e.mode?e.value:n},exports.resolveMeasuredCanvasSizePx=x,exports.subscribeDesignerRegistry=function(e){return _e.add(e),()=>{_e.delete(e)}},exports.unionRects=Mn,exports.unregisterDesignerHandle=Ue,exports.useCanvasContext=ne,exports.validateBindings=function(e,n){var t,o,i;const a=[],r=new Map;for(const n of e.instances)r.set(n.instanceId,n);const c=null==n?void 0:n.currentCanvasId,s=null==n?void 0:n.resolveContract;let d=null,l=null;if(s){d=new Map,l=new Map;for(const n of e.instances){const e=s(n.componentVersionKey);if(d.set(n.instanceId,e),e)for(const t of e.dataInputsDecl)if(t.required){let e=l.get(n.instanceId);e||(e=new Set,l.set(n.instanceId,e)),e.add(t.key)}}}for(const n of e.bindings)if(ct(n)){if(void 0!==c){const e=lt(n),t=ut(n);void 0!==e&&e!==c&&a.push(st("unsupported-cross-canvas","error",n,{canvasId:e})),void 0!==t&&t!==c&&a.push(st("unsupported-cross-canvas","error",n,{canvasId:t}))}switch(n.source.kind){case"instanceEvent":{const e=n.source.event,t=r.get(n.source.instanceId);if(t){if(d){const o=d.get(t.instanceId);o&&!o.emitsDecl.some(n=>n.event===e)&&a.push(st("unknown-source-event","error",n,{instanceId:t.instanceId}))}}else a.push(st("orphan-binding","warn",n,{instanceId:n.source.instanceId}));break}case"lifecycle":r.get(n.source.instanceId)||a.push(st("orphan-binding","warn",n,{instanceId:n.source.instanceId}))}switch(n.target.kind){case"instanceMethod":{const e=n.target.method,t=r.get(n.target.instanceId);if(t){if(d){const o=d.get(t.instanceId);o&&!o.methodsDecl.some(n=>n.key===e)&&a.push(st("unknown-target-method","error",n,{instanceId:t.instanceId}))}}else a.push(st("orphan-binding","warn",n,{instanceId:n.target.instanceId}));break}case"instanceEmit":{const e=n.target.event,t=r.get(n.target.instanceId);if(t){if(d){const o=d.get(t.instanceId);o&&!o.emitsDecl.some(n=>n.event===e)&&a.push(st("unknown-target-event","error",n,{instanceId:t.instanceId}))}}else a.push(st("orphan-binding","warn",n,{instanceId:n.target.instanceId}));break}case"instanceDataInput":{const e=n.target.key,o=r.get(n.target.instanceId);if(o){if(d){const i=d.get(o.instanceId);i&&!i.dataInputsDecl.some(n=>n.key===e)?a.push(st("unknown-target-data-input","error",n,{instanceId:o.instanceId})):l&&(null==(t=l.get(o.instanceId))||t.delete(e))}}else a.push(st("orphan-binding","warn",n,{instanceId:n.target.instanceId}));break}}(null==(o=n.schedule)?void 0:o.throttle)&&n.schedule.throttle.windowMs<16&&a.push(st("schedule-window-too-small","info",n,dt(n))),(null==(i=n.schedule)?void 0:i.debounce)&&n.schedule.debounce.windowMs<16&&a.push(st("schedule-window-too-small","info",n,dt(n)))}else a.push(st("invalid-type-source-kind","error",n,dt(n)));if(l)for(const[e,n]of l)for(const t of n){const n={level:"warn",code:"required-data-input-missing",instanceId:e,key:t,message:`Required dataInput "${t}" on instance "${e}" is not fed by any binding`};a.push(n)}return a},exports.validateInstanceTree=ie,exports.wirePageBindings=Ie;