@gamesberry/karmyc-core
Version:
A flexible and powerful layout management system for React applications
28 lines • 161 kB
JavaScript
import{jsx as e,Fragment as t,jsxs as r}from"react/jsx-runtime";import n,{useRef as a,useState as o,useEffect as s,useCallback as i,forwardRef as c,createElement as d,useMemo as l}from"react";import{ControlledMenu as u,SubMenu as p,MenuItem as f}from"@szhsin/react-menu";const h=new Map,y=e=>{const t=h.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([e,t])=>[e,t.getState()])):{}},g=(e,t={})=>(r,n,a)=>{const{enabled:o,anonymousActionType:s,store:i,...c}=t;let d;try{d=(null!=o?o:"production"!==(import.meta.env?import.meta.env.MODE:void 0))&&window.__REDUX_DEVTOOLS_EXTENSION__}catch(e){}if(!d)return"production"!==(import.meta.env?import.meta.env.MODE:void 0)&&o&&console.warn("[zustand devtools middleware] Please install/enable Redux devtools extension"),e(r,n,a);const{connection:l,...u}=((e,t,r)=>{if(void 0===e)return{type:"untracked",connection:t.connect(r)};const n=h.get(r.name);if(n)return{type:"tracked",store:e,...n};const a={connection:t.connect(r),stores:{}};return h.set(r.name,a),{type:"tracked",store:e,...a}})(i,d,c);let p=!0;a.setState=(e,t,o)=>{const d=r(e,t);if(!p)return d;const u=void 0===o?{type:s||"anonymous"}:"string"==typeof o?{type:o}:o;return void 0===i?(null==l||l.send(u,n()),d):(null==l||l.send({...u,type:`${i}/${u.type}`},{...y(c.name),[i]:a.getState()}),d)};const f=(...e)=>{const t=p;p=!1,r(...e),p=t},g=e(a.setState,n,a);if("untracked"===u.type?null==l||l.init(g):(u.stores[u.store]=a,null==l||l.init(Object.fromEntries(Object.entries(u.stores).map(([e,t])=>[e,e===u.store?g:t.getState()])))),a.dispatchFromDevtools&&"function"==typeof a.dispatch){let e=!1;const t=a.dispatch;a.dispatch=(...r)=>{"production"===(import.meta.env?import.meta.env.MODE:void 0)||"__setState"!==r[0].type||e||(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),e=!0),t(...r)}}return l.subscribe(e=>{var t;switch(e.type){case"ACTION":return"string"!=typeof e.payload?void console.error("[zustand devtools middleware] Unsupported action format"):m(e.payload,e=>{if("__setState"===e.type){if(void 0===i)return void f(e.state);1!==Object.keys(e.state).length&&console.error('\n [zustand devtools middleware] Unsupported __setState action format. \n When using \'store\' option in devtools(), the \'state\' should have only one key, which is a value of \'store\' that was passed in devtools(),\n and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }\n ');const t=e.state[i];if(null==t)return;return void(JSON.stringify(a.getState())!==JSON.stringify(t)&&f(t))}a.dispatchFromDevtools&&"function"==typeof a.dispatch&&a.dispatch(e)});case"DISPATCH":switch(e.payload.type){case"RESET":return f(g),void 0===i?null==l?void 0:l.init(a.getState()):null==l?void 0:l.init(y(c.name));case"COMMIT":return void 0===i?void(null==l||l.init(a.getState())):null==l?void 0:l.init(y(c.name));case"ROLLBACK":return m(e.state,e=>{if(void 0===i)return f(e),void(null==l||l.init(a.getState()));f(e[i]),null==l||l.init(y(c.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return m(e.state,e=>{void 0!==i?JSON.stringify(a.getState())!==JSON.stringify(e[i])&&f(e[i]):f(e)});case"IMPORT_STATE":{const{nextLiftedState:r}=e.payload,n=null==(t=r.computedStates.slice(-1)[0])?void 0:t.state;if(!n)return;return f(void 0===i?n:n[i]),void(null==l||l.send(null,r))}case"PAUSE_RECORDING":return p=!p}return}}),g},m=(e,t)=>{let r;try{r=JSON.parse(e)}catch(e){console.error("[zustand devtools middleware] Could not parse the received json",e)}void 0!==r&&t(r)},v=e=>(t,r,n)=>{const a=n.subscribe;n.subscribe=(e,t,r)=>{let o=e;if(t){const a=(null==r?void 0:r.equalityFn)||Object.is;let s=e(n.getState());o=r=>{const n=e(r);if(!a(s,n)){const e=s;t(s=n,e)}},(null==r?void 0:r.fireImmediately)&&t(s,s)}return a(o)};return e(t,r,n)};function w(e,t){let r;try{r=e()}catch(e){return}return{getItem:e=>{var t;const n=e=>null===e?null:JSON.parse(e,void 0),a=null!=(t=r.getItem(e))?t:null;return a instanceof Promise?a.then(n):n(a)},setItem:(e,t)=>r.setItem(e,JSON.stringify(t,void 0)),removeItem:e=>r.removeItem(e)}}const S=e=>t=>{try{const r=e(t);return r instanceof Promise?r:{then:e=>S(e)(r),catch(e){return this}}}catch(e){return{then(e){return this},catch:t=>S(t)(e)}}},b=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?("production"!==(import.meta.env?import.meta.env.MODE:void 0)&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),((e,t)=>(r,n,a)=>{let o={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},s=!1;const i=new Set,c=new Set;let d;try{d=o.getStorage()}catch(e){}if(!d)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),r(...e)},n,a);const l=S(o.serialize),u=()=>{const e=o.partialize({...n()});let t;const r=l({state:e,version:o.version}).then(e=>d.setItem(o.name,e)).catch(e=>{t=e});if(t)throw t;return r},p=a.setState;a.setState=(e,t)=>{p(e,t),u()};const f=e((...e)=>{r(...e),u()},n,a);let h;const y=()=>{var e;if(!d)return;s=!1,i.forEach(e=>e(n()));const t=(null==(e=o.onRehydrateStorage)?void 0:e.call(o,n()))||void 0;return S(d.getItem.bind(d))(o.name).then(e=>{if(e)return o.deserialize(e)}).then(e=>{if(e){if("number"!=typeof e.version||e.version===o.version)return e.state;if(o.migrate)return o.migrate(e.state,e.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}}).then(e=>{var t;return h=o.merge(e,null!=(t=n())?t:f),r(h,!0),u()}).then(()=>{null==t||t(h,void 0),s=!0,c.forEach(e=>e(h))}).catch(e=>{null==t||t(void 0,e)})};return a.persist={setOptions:e=>{o={...o,...e},e.getStorage&&(d=e.getStorage())},clearStorage:()=>{null==d||d.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>y(),hasHydrated:()=>s,onHydrate:e=>(i.add(e),()=>{i.delete(e)}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e)})},y(),h||f})(e,t)):((e,t)=>(r,n,a)=>{let o={storage:w(()=>localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},s=!1;const i=new Set,c=new Set;let d=o.storage;if(!d)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),r(...e)},n,a);const l=()=>{const e=o.partialize({...n()});return d.setItem(o.name,{state:e,version:o.version})},u=a.setState;a.setState=(e,t)=>{u(e,t),l()};const p=e((...e)=>{r(...e),l()},n,a);let f;a.getInitialState=()=>p;const h=()=>{var e,t;if(!d)return;s=!1,i.forEach(e=>{var t;return e(null!=(t=n())?t:p)});const a=(null==(t=o.onRehydrateStorage)?void 0:t.call(o,null!=(e=n())?e:p))||void 0;return S(d.getItem.bind(d))(o.name).then(e=>{if(e){if("number"!=typeof e.version||e.version===o.version)return[!1,e.state];if(o.migrate)return[!0,o.migrate(e.state,e.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}return[!1,void 0]}).then(e=>{var t;const[a,s]=e;if(f=o.merge(s,null!=(t=n())?t:p),r(f,!0),a)return l()}).then(()=>{null==a||a(f,void 0),f=n(),s=!0,c.forEach(e=>e(f))}).catch(e=>{null==a||a(void 0,e)})};return a.persist={setOptions:e=>{o={...o,...e},e.storage&&(d=e.storage)},clearStorage:()=>{null==d||d.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>h(),hasHydrated:()=>s,onHydrate:e=>(i.add(e),()=>{i.delete(e)}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e)})},o.skipHydration||h(),f||p})(e,t),I=e=>t=>{e(e=>{const r=e.screens[e.activeScreenId]?.areas;r&&r.joinPreview!==t&&(r.joinPreview=t,e.lastUpdated=Date.now())})};function A(e){const t={};if(!e)return console.error("computeAreaToParentRow received null or undefined layout."),{};const r=Object.keys(e);for(let n=0;n<r.length;n+=1){const a=e[r[n]];if(!a||"area_row"!==a.type)continue;const o=a;if(o.areas&&Array.isArray(o.areas))for(let e=0;e<o.areas.length;e+=1)o.areas[e]&&o.areas[e].id&&(t[o.areas[e].id]=o.id)}return t}function E(e,t){if(!t)return;const r=e.layout[t];if(!r||"area_row"!==r.type)return;const n=r;if(1!==n.areas.length)return;const a=n.areas[0],o=a.id,s=A(e.layout)[t];if(s&&"area_row"===e.layout[s]?.type){const r=e.layout[s],n=r.areas.findIndex(e=>e.id===t);if(-1===n)return void console.error(`[simplifyLayoutNodeIfNeeded] Cleanup Error: Row ${t} not found in parent ${s}.`);{const e=r.areas[n].size??a.size??.5;r.areas[n]={id:o,size:e}}}else e.rootId===t?e.rootId=o:console.warn(`[simplifyLayoutNodeIfNeeded] Row ${t} has single child ${o} but no parent and is not root. Removing row.`);delete e.layout[t]}function _(e,t){const r=e[t];return r?"area"===r.type?t:"area_row"===r.type?0===r.areas.length?null:_(e,r.areas[0].id):null:null}const x=e=>t=>{let r=null;return e(e=>{const n=e.screens[e.activeScreenId]?.areas;if(!n)return;const{areaIdToSplit:a,parentRowId:o,horizontal:s}=t,i=n.layout[a];if("area_row"===i.type&&"stack"===i.orientation){const e=i.areas,t=[];for(const r of e){const e=n.areas[r.id];if(!e)continue;const a=`area-${n._id+1}`;n._id+=1,n.areas[a]={id:a,type:e.type,state:{...e.state}},n.layout[a]={type:"area",id:a},t.push({id:a,size:r.size})}const c=`row-${n._id+1}`;n._id+=1;const d={id:c,type:"area_row",orientation:"stack",areas:t,activeTabId:t[0]?.id};n.layout[c]=d;const l=`row-${n._id+1}`;n._id+=1;const u={id:l,type:"area_row",orientation:s?"horizontal":"vertical",areas:[{id:a,size:.5},{id:c,size:.5}]};if(n.layout[l]=u,o){const e=n.layout[o];if("area_row"===e?.type){const t=e.areas.findIndex(e=>e.id===a);if(-1!==t){const r=e.areas[t].size??.5;e.areas[t]={id:l,size:r}}}}else n.rootId=l;return void(r={newRowId:l,separatorIndex:1})}n._id+=1;const c=n._id,d=`area-${c}`,l=`row-${c+1}`;if(n.areas[d]||n.layout[d])return void console.error(`splitArea: ID conflict for new area ${d}`);const u=n.areas[a];if(n.areas[d]={id:d,type:u?.type||i.type,state:{...u?.state},spaceId:u?.spaceId},n.layout[d]={type:"area",id:d},n.layout[l])return void console.error(`splitArea: ID conflict for new row ${l}`);const p={id:l,type:"area_row",orientation:s?"horizontal":"vertical",areas:[{id:a,size:.5},{id:d,size:.5}]};n.layout[l]=p;let f=.5;if(o){const e=n.layout[o];if("area_row"===e?.type){const t=e.areas.findIndex(e=>e.id===a);if(-1!==t)if(f=e.areas[t].size??.5,e.orientation===p.orientation){const n=p.areas.map(e=>({id:e.id,size:(e.size??.5)*f}));e.areas.splice(t,1,...n),r={newRowId:o,separatorIndex:t+1}}else e.areas[t]={id:l,size:f},r={newRowId:l,separatorIndex:1};else console.error(`splitArea Error: Area ${a} not in parent ${o}.`)}else console.error(`splitArea Error: Parent ${o} not found or not row.`)}else n.rootId===a?(n.rootId=l,r={newRowId:l,separatorIndex:1}):console.error(`splitArea Error: Area ${a} has no parent and is not root.`);n._id=c+2,n.lastSplitResultData=r,function(e){if(!e)return;let t=e;for(;t;){const e=n.layout[t];E(n,t);if(t=A(n.layout)[t],!e||n.layout[e.id])break}}(o),function e(t,r=null){if(!t)return;const a=n.layout[t];if(!a||"area_row"!==a.type)return;let o=!1;for(let e=0;e<a.areas.length;){const t=a.areas[e].id,r=n.layout[t];if(r&&"area_row"===r.type&&r.orientation===a.orientation){const s=r,i=a.areas[e].size??1/a.areas.length,c=s.areas.reduce((e,t)=>e+(t.size??0),0)||1,d=s.areas.map(e=>({id:e.id,size:(e.size??1/s.areas.length)*i/c}));a.areas.splice(e,1,...d.filter(e=>!a.areas.some(t=>t.id===e.id))),delete n.layout[t],o=!0}else e++}for(const r of a.areas)e(r.id,t);o&&e(t,r)}(n.rootId),function(){const e=new Set;!function t(r){if(!r||e.has(r))return;e.add(r);const a=n.layout[r];if(a&&"area_row"===a.type)for(const e of a.areas)t(e.id)}(n.rootId);for(const t in n.layout){const r=n.layout[t];r&&"area_row"===r.type&&!e.has(t)&&delete n.layout[t]}}(),e.lastUpdated=Date.now()}),r},O=(e,t,r)=>{const n=t,a=n+r;if(n<0||n>=e.areas.length||a<0||a>=e.areas.length)throw new Error(`Invalid indices: source=${n}, target=${a}, length=${e.areas.length}, direction=${-1===r?"west":"east"}`);const o=e.areas[n],s=e.areas[a];if(!o||!s)throw new Error(`Missing areas: source=${o}, target=${s}`);const i=(o.size||1)+(s.size||1);if(2===e.areas.length){return{area:{type:"area",id:o.id},removedAreaId:s.id}}const c=[...e.areas];c[a]={id:o.id,size:i},c.splice(n,1);return{area:{...e,areas:c},removedAreaId:s.id}};let z=[],k=!1,M=null;const T=e=>{const t=k;t||(k=!0,z=[]);try{e()}finally{!t&&k&&yr.setState(e=>(z.forEach(e=>e()),z=[],k=!1,e.lastUpdated=Date.now(),e))}},D=e=>t=>{T(()=>{e(e=>{const r=e.screens[e.activeScreenId]?.areas;if(!r)return;const{sourceAreaId:n,targetAreaId:a}=t,{parentRow:o,sourceIndex:s,targetIndex:i}=function(e,t,r){for(const n in e){const a=e[n];if("area_row"===a.type){const e=a,n=e.areas.findIndex(e=>e.id===t),o=e.areas.findIndex(e=>e.id===r);if(-1!==n&&-1!==o&&1===Math.abs(n-o))return{parentRow:e,sourceIndex:n,targetIndex:o}}}return{parentRow:null,sourceIndex:-1,targetIndex:-1}}(r.layout,n,a);if(!o||"area_row"!==o.type)return r.errors=[`Could not find adjacent areas ${n}/${a} in the same row.`],void(r.joinPreview=null);const c=o.id,d=A(r.layout)[c],l=JSON.parse(JSON.stringify(o)),u=i>s?1:-1,p=s;try{const e=O(l,p,u),{area:t,removedAreaId:n}=e,a=function(e,t){const r=new Set,n=[t],a=new Set;for(;n.length>0;){const t=n.shift();if(a.has(t))continue;a.add(t);const o=e[t];if(o)if("area"===o.type)r.add(t);else if("area_row"===o.type){const e=o;e.areas&&Array.isArray(e.areas)&&e.areas.forEach(e=>{e&&e.id&&n.push(e.id)})}}return"area"===e[t]?.type&&r.add(t),r}(r.layout,n);if(a.add(n),a.forEach(e=>{delete r.areas[e],delete r.layout[e]}),t.id===c&&"area_row"===t.type){const e=t;if(r.layout[c]=e,e.areas){const t=e.areas.reduce((e,t)=>e+(t.size||0),0);if(t>0){const r=1/t;e.areas=e.areas.map(e=>({...e,size:(e.size||0)*r}))}}1===e.areas?.length&&E(r,c)}else if(delete r.layout[c],r.layout[t.id]||"area_row"!==t.type&&(r.layout[t.id]={type:"area",id:t.id}),d&&"area_row"===r.layout[d]?.type){const e=r.layout[d],n=e.areas.findIndex(e=>e.id===c);if(-1!==n){const r=e.areas[n].size??.5;e.areas[n]={id:t.id,size:r}}else console.error(`[joinOrMoveArea] Cleanup Error: Row ${c} not found in grandparent ${d}.`)}else r.rootId===c&&(r.rootId=t.id);r.activeAreaId&&a.has(r.activeAreaId)&&("area"===t.type?r.activeAreaId=t.id:r.activeAreaId=null),r.errors=[],r.joinPreview=null}catch(e){console.error("Error during joinOrMoveArea:",e),r.errors=[e instanceof Error?e.message:String(e)],r.joinPreview=null}e.lastUpdated=Date.now()})})},L=[];for(let e=0;e<256;++e)L.push((e+256).toString(16).slice(1));let C;const N=new Uint8Array(16);var R={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function $(e,t,r){if(R.randomUUID&&!e)return R.randomUUID();const n=(e=e||{}).random??e.rng?.()??function(){if(!C){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");C=crypto.getRandomValues.bind(crypto)}return C(N)}();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=15&n[6]|64,n[8]=63&n[8]|128,function(e,t=0){return(L[e[t+0]]+L[e[t+1]]+L[e[t+2]]+L[e[t+3]]+"-"+L[e[t+4]]+L[e[t+5]]+"-"+L[e[t+6]]+L[e[t+7]]+"-"+L[e[t+8]]+L[e[t+9]]+"-"+L[e[t+10]]+L[e[t+11]]+L[e[t+12]]+L[e[t+13]]+L[e[t+14]]+L[e[t+15]]).toLowerCase()}(n)}const P=new Map,j={registerComponent:(e,t)=>{const r=P.get(e)||{};P.set(e,{...r,component:t})},registerInitialState:(e,t)=>{const r=P.get(e)||{};P.set(e,{...r,initialState:t})},registerDisplayName:(e,t)=>{const r=P.get(e)||{};P.set(e,{...r,displayName:t})},registerIcon:(e,t)=>{const r=P.get(e)||{};P.set(e,{...r,icon:t})},registerDefaultSize:(e,t)=>{const r=P.get(e)||{};P.set(e,{...r,defaultSize:t})},registerSupportedActions:(e,t)=>{const r=P.get(e)||{};P.set(e,{...r,supportedActions:t})},getComponent:e=>P.get(e)?.component,getInitialState:e=>P.get(e)?.initialState||{},getDisplayName:e=>P.get(e)?.displayName||e,getIcon:e=>P.get(e)?.icon,getDefaultSize:e=>P.get(e)?.defaultSize,getSupportedActions:e=>P.get(e)?.supportedActions,getRegisteredTypes:()=>new Set(Array.from(P.keys())),unregisterAreaType:e=>{P.delete(e)},isRegistered:e=>P.has(e),getFallbackType:e=>(P.has(e)||console.warn(`[AreaRegistry] Type "${e}" not registered, using original type`),e)};var F;!function(e){e[e.CRITICAL=1e3]="CRITICAL",e[e.HIGH=800]="HIGH",e[e.NORMAL=500]="NORMAL",e[e.LOW=200]="LOW",e[e.BACKGROUND=100]="BACKGROUND"}(F||(F={}));const U={LEAD:"LEAD",FOLLOW:"FOLLOW",SELF:"SELF"},H=e=>{let t;const r=new Set,n=(e,n)=>{const a="function"==typeof e?e(t):e;if(!Object.is(a,t)){const e=t;t=(null!=n?n:"object"!=typeof a||null===a)?a:Object.assign({},t,a),r.forEach(r=>r(t,e))}},a=()=>t,o={setState:n,getState:a,getInitialState:()=>s,subscribe:e=>(r.add(e),()=>r.delete(e)),destroy:()=>{"production"!==(import.meta.env?import.meta.env.MODE:void 0)&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),r.clear()}},s=t=e(n,a,o);return o};function V(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var B,K={exports:{}},J={},q={exports:{}},W={};var G,Y,X,Z={};
/**
* @license React
* use-sync-external-store-shim.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/function Q(){return Y||(Y=1,"production"===process.env.NODE_ENV?q.exports=function(){if(B)return W;B=1;var e=n,t="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=e.useState,a=e.useEffect,o=e.useLayoutEffect,s=e.useDebugValue;function i(e){var r=e.getSnapshot;e=e.value;try{var n=r();return!t(e,n)}catch(e){return!0}}var c="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(e,t){var n=t(),c=r({inst:{value:n,getSnapshot:t}}),d=c[0].inst,l=c[1];return o(function(){d.value=n,d.getSnapshot=t,i(d)&&l({inst:d})},[e,n,t]),a(function(){return i(d)&&l({inst:d}),e(function(){i(d)&&l({inst:d})})},[e]),s(n),n};return W.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:c,W}():q.exports=(G||(G=1,"production"!==process.env.NODE_ENV&&function(){function e(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch(e){return!0}}"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var t=n,r="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},a=t.useState,o=t.useEffect,s=t.useLayoutEffect,i=t.useDebugValue,c=!1,d=!1,l="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(n,l){c||void 0===t.startTransition||(c=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var u=l();if(!d){var p=l();r(u,p)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),d=!0)}var f=(p=a({inst:{value:u,getSnapshot:l}}))[0].inst,h=p[1];return s(function(){f.value=u,f.getSnapshot=l,e(f)&&h({inst:f})},[n,u,l]),o(function(){return e(f)&&h({inst:f}),n(function(){e(f)&&h({inst:f})})},[n]),i(u),u};Z.useSyncExternalStore=void 0!==t.useSyncExternalStore?t.useSyncExternalStore:l,"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),Z)),q.exports}
/**
* @license React
* use-sync-external-store-shim/with-selector.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var ee,te={};
/**
* @license React
* use-sync-external-store-shim/with-selector.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/"production"===process.env.NODE_ENV?K.exports=function(){if(X)return J;X=1;var e=n,t=Q(),r="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},a=t.useSyncExternalStore,o=e.useRef,s=e.useEffect,i=e.useMemo,c=e.useDebugValue;return J.useSyncExternalStoreWithSelector=function(e,t,n,d,l){var u=o(null);if(null===u.current){var p={hasValue:!1,value:null};u.current=p}else p=u.current;u=i(function(){function e(e){if(!s){if(s=!0,a=e,e=d(e),void 0!==l&&p.hasValue){var t=p.value;if(l(t,e))return o=t}return o=e}if(t=o,r(a,e))return t;var n=d(e);return void 0!==l&&l(t,n)?(a=e,t):(a=e,o=n)}var a,o,s=!1,i=void 0===n?null:n;return[function(){return e(t())},null===i?void 0:function(){return e(i())}]},[t,n,d,l]);var f=a(e,u[0],u[1]);return s(function(){p.hasValue=!0,p.value=f},[f]),c(f),f},J}():K.exports=(ee||(ee=1,"production"!==process.env.NODE_ENV&&function(){"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var e=n,t=Q(),r="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},a=t.useSyncExternalStore,o=e.useRef,s=e.useEffect,i=e.useMemo,c=e.useDebugValue;te.useSyncExternalStoreWithSelector=function(e,t,n,d,l){var u=o(null);if(null===u.current){var p={hasValue:!1,value:null};u.current=p}else p=u.current;u=i(function(){function e(e){if(!s){if(s=!0,a=e,e=d(e),void 0!==l&&p.hasValue){var t=p.value;if(l(t,e))return o=t}return o=e}if(t=o,r(a,e))return t;var n=d(e);return void 0!==l&&l(t,n)?(a=e,t):(a=e,o=n)}var a,o,s=!1,i=void 0===n?null:n;return[function(){return e(t())},null===i?void 0:function(){return e(i())}]},[t,n,d,l]);var f=a(e,u[0],u[1]);return s(function(){p.hasValue=!0,p.value=f},[f]),c(f),f},"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),te);var re=V(K.exports);const{useDebugValue:ne}=n,{useSyncExternalStoreWithSelector:ae}=re;let oe=!1;const se=e=>e;const ie=e=>{"production"!==(import.meta.env?import.meta.env.MODE:void 0)&&"function"!=typeof e&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const t="function"==typeof e?(e=>e?H(e):H)(e):e,r=(e,r)=>function(e,t=se,r){"production"!==(import.meta.env?import.meta.env.MODE:void 0)&&r&&!oe&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),oe=!0);const n=ae(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,r);return ne(n),n}(t,e,r);return Object.assign(r,t),r},ce=e=>e?ie(e):ie;var de=Symbol.for("immer-nothing"),le=Symbol.for("immer-draftable"),ue=Symbol.for("immer-state"),pe="production"!==process.env.NODE_ENV?[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}]:[];function fe(e,...t){if("production"!==process.env.NODE_ENV){const r=pe[e],n="function"==typeof r?r.apply(null,t):r;throw new Error(`[Immer] ${n}`)}throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var he=Object.getPrototypeOf;function ye(e){return!!e&&!!e[ue]}function ge(e){return!!e&&(ve(e)||Array.isArray(e)||!!e[le]||!!e.constructor?.[le]||Ae(e)||Ee(e))}var me=Object.prototype.constructor.toString();function ve(e){if(!e||"object"!=typeof e)return!1;const t=he(e);if(null===t)return!0;const r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object||"function"==typeof r&&Function.toString.call(r)===me}function we(e,t){0===Se(e)?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Se(e){const t=e[ue];return t?t.type_:Array.isArray(e)?1:Ae(e)?2:Ee(e)?3:0}function be(e,t){return 2===Se(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Ie(e,t,r){const n=Se(e);2===n?e.set(t,r):3===n?e.add(r):e[t]=r}function Ae(e){return e instanceof Map}function Ee(e){return e instanceof Set}function _e(e){return e.copy_||e.base_}function xe(e,t){if(Ae(e))return new Map(e);if(Ee(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const r=ve(e);if(!0===t||"class_only"===t&&!r){const t=Object.getOwnPropertyDescriptors(e);delete t[ue];let r=Reflect.ownKeys(t);for(let n=0;n<r.length;n++){const a=r[n],o=t[a];!1===o.writable&&(o.writable=!0,o.configurable=!0),(o.get||o.set)&&(t[a]={configurable:!0,writable:!0,enumerable:o.enumerable,value:e[a]})}return Object.create(he(e),t)}{const t=he(e);if(null!==t&&r)return{...e};const n=Object.create(t);return Object.assign(n,e)}}function Oe(e,t=!1){return ke(e)||ye(e)||!ge(e)||(Se(e)>1&&(e.set=e.add=e.clear=e.delete=ze),Object.freeze(e),t&&Object.entries(e).forEach(([e,t])=>Oe(t,!0))),e}function ze(){fe(2)}function ke(e){return Object.isFrozen(e)}var Me,Te={};function De(e){const t=Te[e];return t||fe(0,e),t}function Le(){return Me}function Ce(e,t){t&&(De("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Ne(e){Re(e),e.drafts_.forEach(Pe),e.drafts_=null}function Re(e){e===Me&&(Me=e.parent_)}function $e(e){return Me={drafts_:[],parent_:Me,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Pe(e){const t=e[ue];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function je(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];return void 0!==e&&e!==r?(r[ue].modified_&&(Ne(t),fe(4)),ge(e)&&(e=Fe(t,e),t.parent_||He(t,e)),t.patches_&&De("Patches").generateReplacementPatches_(r[ue].base_,e,t.patches_,t.inversePatches_)):e=Fe(t,r,[]),Ne(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==de?e:void 0}function Fe(e,t,r){if(ke(t))return t;const n=t[ue];if(!n)return we(t,(a,o)=>Ue(e,n,t,a,o,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return He(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const t=n.copy_;let a=t,o=!1;3===n.type_&&(a=new Set(t),t.clear(),o=!0),we(a,(a,s)=>Ue(e,n,t,a,s,r,o)),He(e,t,!1),r&&e.patches_&&De("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function Ue(e,t,r,n,a,o,s){if("production"!==process.env.NODE_ENV&&a===r&&fe(5),ye(a)){const s=Fe(e,a,o&&t&&3!==t.type_&&!be(t.assigned_,n)?o.concat(n):void 0);if(Ie(r,n,s),!ye(s))return;e.canAutoFreeze_=!1}else s&&r.add(a);if(ge(a)&&!ke(a)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Fe(e,a),t&&t.scope_.parent_||"symbol"==typeof n||!Object.prototype.propertyIsEnumerable.call(r,n)||He(e,a)}}function He(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Oe(t,r)}var Ve={get(e,t){if(t===ue)return e;const r=_e(e);if(!be(r,t))return function(e,t,r){const n=Je(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}(e,r,t);const n=r[t];return e.finalized_||!ge(n)?n:n===Ke(e.base_,t)?(We(e),e.copy_[t]=Ge(n,e)):n},has:(e,t)=>t in _e(e),ownKeys:e=>Reflect.ownKeys(_e(e)),set(e,t,r){const n=Je(_e(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){const n=Ke(_e(e),t),s=n?.[ue];if(s&&s.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(((a=r)===(o=n)?0!==a||1/a==1/o:a!=a&&o!=o)&&(void 0!==r||be(e.base_,t)))return!0;We(e),qe(e)}var a,o;return e.copy_[t]===r&&(void 0!==r||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty:(e,t)=>(void 0!==Ke(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,We(e),qe(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const r=_e(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:n.enumerable,value:r[t]}:n},defineProperty(){fe(11)},getPrototypeOf:e=>he(e.base_),setPrototypeOf(){fe(12)}},Be={};function Ke(e,t){const r=e[ue];return(r?_e(r):e)[t]}function Je(e,t){if(!(t in e))return;let r=he(e);for(;r;){const e=Object.getOwnPropertyDescriptor(r,t);if(e)return e;r=he(r)}}function qe(e){e.modified_||(e.modified_=!0,e.parent_&&qe(e.parent_))}function We(e){e.copy_||(e.copy_=xe(e.base_,e.scope_.immer_.useStrictShallowCopy_))}we(Ve,(e,t)=>{Be[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),Be.deleteProperty=function(e,t){return"production"!==process.env.NODE_ENV&&isNaN(parseInt(t))&&fe(13),Be.set.call(this,e,t,void 0)},Be.set=function(e,t,r){return"production"!==process.env.NODE_ENV&&"length"!==t&&isNaN(parseInt(t))&&fe(14),Ve.set.call(this,e[0],t,r,e[0])};function Ge(e,t){const r=Ae(e)?De("MapSet").proxyMap_(e,t):Ee(e)?De("MapSet").proxySet_(e,t):function(e,t){const r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Le(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let a=n,o=Ve;r&&(a=[n],o=Be);const{revoke:s,proxy:i}=Proxy.revocable(a,o);return n.draft_=i,n.revoke_=s,i}(e,t);return(t?t.scope_:Le()).drafts_.push(r),r}function Ye(e){if(!ge(e)||ke(e))return e;const t=e[ue];let r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=xe(e,t.scope_.immer_.useStrictShallowCopy_)}else r=xe(e,!0);return we(r,(e,t)=>{Ie(r,e,Ye(t))}),t&&(t.finalized_=!1),r}var Xe=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,r)=>{if("function"==typeof e&&"function"!=typeof t){const r=t;t=e;const n=this;return function(e=r,...a){return n.produce(e,e=>t.call(this,e,...a))}}let n;if("function"!=typeof t&&fe(6),void 0!==r&&"function"!=typeof r&&fe(7),ge(e)){const a=$e(this),o=Ge(e,void 0);let s=!0;try{n=t(o),s=!1}finally{s?Ne(a):Re(a)}return Ce(a,r),je(n,a)}if(!e||"object"!=typeof e){if(n=t(e),void 0===n&&(n=e),n===de&&(n=void 0),this.autoFreeze_&&Oe(n,!0),r){const t=[],a=[];De("Patches").generateReplacementPatches_(e,n,t,a),r(t,a)}return n}fe(1,e)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...r)=>this.produceWithPatches(t,t=>e(t,...r));let r,n;return[this.produce(e,t,(e,t)=>{r=e,n=t}),r,n]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){ge(e)||fe(8),ye(e)&&(e=function(e){ye(e)||fe(10,e);return Ye(e)}(e));const t=$e(this),r=Ge(e,void 0);return r[ue].isManual_=!0,Re(t),r}finishDraft(e,t){const r=e&&e[ue];r&&r.isManual_||fe(9);const{scope_:n}=r;return Ce(n,t),je(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const n=t[r];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}r>-1&&(t=t.slice(r+1));const n=De("Patches").applyPatches_;return ye(e)?n(e,t):this.produce(e,e=>n(e,t))}},Ze=Xe.produce;Xe.produceWithPatches.bind(Xe),Xe.setAutoFreeze.bind(Xe),Xe.setUseStrictShallowCopy.bind(Xe),Xe.applyPatches.bind(Xe),Xe.createDraft.bind(Xe),Xe.finishDraft.bind(Xe);const Qe=e=>(t,r,n)=>(n.setState=(e,r,...n)=>{const a="function"==typeof e?Ze(e):e;return t(a,r,...n)},e(n.setState,r,n)),et={CREATE:"CREATE",UPDATE:"UPDATE",DELETE:"DELETE",MOVE:"MOVE",COPY:"COPY",PASTE:"PASTE",SELECT:"SELECT",DESELECT:"DESELECT",SELECT_ALL:"SELECT_ALL",DESELECT_ALL:"DESELECT_ALL",GROUP:"GROUP",UNGROUP:"UNGROUP",TRANSFORM:"TRANSFORM",ROTATE:"ROTATE",SCALE:"SCALE",TRANSLATE:"TRANSLATE",TIMELINE_UPDATE:"TIMELINE_UPDATE",KEYFRAME_ADD:"KEYFRAME_ADD",KEYFRAME_REMOVE:"KEYFRAME_REMOVE",KEYFRAME_UPDATE:"KEYFRAME_UPDATE",CUSTOM:"CUSTOM"},tt={ACTION_STARTED:"action-started",ACTION_SUBMITTED:"action-submitted",ACTION_CANCELLED:"action-cancelled",UNDO_PERFORMED:"undo-performed",REDO_PERFORMED:"redo-performed",HISTORY_CLEARED:"history-cleared",STATE_RESTORED:"state-restored"},rt={maxHistorySize:100,captureState:!0,enableNotifications:!0,enableSelections:!0,filter:()=>!0,groupBy:e=>e.metadata.actionType},nt=()=>({currentState:{},pastActions:[],futureActions:[],isActionInProgress:!1,currentActionId:null,actionMetadata:{},subscribers:[]}),at=(e,t,r=[],n,a=!1,o=[])=>({id:e,name:t,timestamp:Date.now(),diffs:r,state:n,allowIndexShift:a,modifiedRelated:o.includes("selection"),metadata:{actionType:t,payload:{},duration:0},indexDirection:1}),ot=(e,t)=>{e.sharedState.subscribers.forEach(e=>{try{e(t)}catch(e){console.error("Error in history subscriber:",e)}})},st=ce()(Qe(g(b((e,t)=>({spaces:{},activeSpaceId:null,openSpaceIds:[],errors:[],pilotMode:"AUTO",addSpace:r=>{if(!r.name)return e(e=>{e.errors=["Space name cannot be empty."]}),void console.error("Validation failed for space:",t().errors);const n=$(),a={id:n,name:r.name,description:r.description??"",color:r.color??"#000000",sharedState:{currentState:{},pastActions:[],futureActions:[],isActionInProgress:!1,currentActionId:null,actionMetadata:{},subscribers:[],...r.sharedState||{}}};return e(e=>{e.spaces[n]=a,e.openSpaceIds.push(n),e.errors=[]}),n},removeSpace:t=>{e(e=>{delete e.spaces[t],e.activeSpaceId===t&&(e.activeSpaceId=null),e.openSpaceIds=e.openSpaceIds.filter(e=>e!==t),e.errors=[]})},setActiveSpace:t=>{e(e=>{null===t||e.spaces[t]?e.activeSpaceId=t:console.warn(`Attempted to set active space to non-existent ID: ${t}`),e.errors=[]})},setPilotMode:t=>{e(e=>{e.pilotMode=t})},openSpace:t=>{e(e=>{e.spaces[t]&&!e.openSpaceIds.includes(t)&&e.openSpaceIds.push(t)})},closeSpace:t=>{e(e=>{e.openSpaceIds=e.openSpaceIds.filter(e=>e!==t),e.activeSpaceId===t&&(e.activeSpaceId=e.openSpaceIds[e.openSpaceIds.length-1]||null)})},updateSpace:t=>{e(e=>{const r=e.spaces[t.id];if(r){if(""===t.name)return e.errors=["Space name cannot be empty."],void console.error("Validation failed for space update:",e.errors);const{id:n,...a}=t;e.spaces[n]={...r,...a},e.errors=[]}else e.errors=[`Space with ID ${t.id} not found for update.`],console.error("Update failed:",e.errors)})},startAction:(r,n)=>{const a=t().spaces[r];return a?a.sharedState.isActionInProgress?{success:!1,error:"Another action is already in progress"}:(e(e=>{const t=e.spaces[r];t&&(t.sharedState.isActionInProgress=!0,t.sharedState.currentActionId=n,t.sharedState.currentState={...t.sharedState.currentState})}),{success:!0,metadata:{actionId:n}}):{success:!1,error:`Space with ID ${r} not found`}},submitAction:(r,n,a=[],o=!1,s=[])=>{const i=t().spaces[r];if(!i)return{success:!1,error:`Space with ID ${r} not found`};if(!i.sharedState.isActionInProgress)return{success:!1,error:"No action in progress to submit"};const c=at(i.sharedState.currentActionId,n,a,i.sharedState.currentState,o,s);return e(e=>{const t=e.spaces[r];t&&(t.sharedState.pastActions.push(c),t.sharedState.futureActions=[],t.sharedState.isActionInProgress=!1,t.sharedState.currentActionId=null,t.sharedState.pastActions.length>rt.maxHistorySize&&t.sharedState.pastActions.shift())}),ot(i,c),{success:!0,action:c}},cancelAction:r=>{const n=t().spaces[r];return n?n.sharedState.isActionInProgress?(e(e=>{const t=e.spaces[r];t&&(t.sharedState.isActionInProgress=!1,t.sharedState.currentActionId=null)}),{success:!0}):{success:!1,error:"No action in progress to cancel"}:{success:!1,error:`Space with ID ${r} not found`}},undoEnhanced:r=>{const n=t().spaces[r];if(!n)return{success:!1,error:`Space with ID ${r} not found`};if(console.log(`[undoEnhanced] Start for space ${r}:`,{pastActionsLength:n.sharedState.pastActions?.length||0,futureActionsLength:n.sharedState.futureActions?.length||0,pastActions:n.sharedState.pastActions,futureActions:n.sharedState.futureActions}),!Array.isArray(n.sharedState.pastActions))return console.warn(`Space ${r} has invalid pastActions, initializing...`),e(e=>{const t=e.spaces[r];t&&(t.sharedState.pastActions=[],t.sharedState.futureActions=[])}),{success:!1,error:"History was corrupted, please try again"};if(0===n.sharedState.pastActions.length)return console.log(`[undoEnhanced] No action to undo for space ${r}`),{success:!1,error:"No actions to undo"};const a=n.sharedState.pastActions;if(!Array.isArray(a)||0===a.length)return console.error(`Space ${r} has invalid pastActions after validation:`,a),e(e=>{const t=e.spaces[r];t&&(t.sharedState.pastActions=[],t.sharedState.futureActions=[])}),{success:!1,error:"History was corrupted, please try again"};const o=a.length-1,s=a[o];if(!s)return console.error(`Space ${r} failed to get action from pastActions at index ${o}`),{success:!1,error:"Failed to retrieve action for undo"};console.log("[undoEnhanced] Action to undo:",s),console.log("[undoEnhanced] State to restore:",s.state);const i=a.slice(0,o);e(e=>{const t=e.spaces[r];t&&(t.sharedState.pastActions=i,t.sharedState.currentState=s.state,Array.isArray(t.sharedState.futureActions)||(t.sharedState.futureActions=[]),t.sharedState.futureActions.push(s))});const c=t().spaces[r];return c&&"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("karmyc-state-changed",{detail:{state:c.sharedState.currentState}})),console.log(`[undoEnhanced] After undo for space ${r}:`,{newPastActionsLength:i.length,futureActionsLength:t().spaces[r]?.sharedState?.futureActions?.length||0,restoredState:t().spaces[r]?.sharedState?.currentState}),ot(n,s),{success:!0,action:s}},redoEnhanced:r=>{const n=t().spaces[r];if(!n)return{success:!1,error:`Space with ID ${r} not found`};if(console.log(`[redoEnhanced] Start for space ${r}:`,{pastActionsLength:n.sharedState.pastActions?.length||0,futureActionsLength:n.sharedState.futureActions?.length||0,pastActions:n.sharedState.pastActions,futureActions:n.sharedState.futureActions}),!Array.isArray(n.sharedState.futureActions))return console.warn(`Space ${r} has invalid futureActions, initializing...`),e(e=>{const t=e.spaces[r];t&&(t.sharedState.pastActions=[],t.sharedState.futureActions=[])}),{success:!1,error:"History was corrupted, please try again"};if(0===n.sharedState.futureActions.length)return console.log(`[redoEnhanced] No action to redo for space ${r}`),{success:!1,error:"No actions to redo"};const a=n.sharedState.futureActions;if(!Array.isArray(a)||0===a.length)return console.error(`Space ${r} has invalid futureActions after validation:`,a),e(e=>{const t=e.spaces[r];t&&(t.sharedState.pastActions=[],t.sharedState.futureActions=[])}),{success:!1,error:"History was corrupted, please try again"};const o=a.length-1,s=a[o];if(!s)return console.error(`Space ${r} failed to get action from futureActions at index ${o}`),{success:!1,error:"Failed to retrieve action for redo"};console.log("[redoEnhanced] Action to redo:",s);const i=s.metadata?.nextState||s.state;console.log("[redoEnhanced] State to restore for redo:",i);const c=a.slice(0,o);e(e=>{const t=e.spaces[r];t&&(t.sharedState.futureActions=c,t.sharedState.currentState=i,Array.isArray(t.sharedState.pastActions)||(t.sharedState.pastActions=[]),t.sharedState.pastActions.push(s))});const d=t().spaces[r];return d&&"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("karmyc-state-changed",{detail:{state:d.sharedState.currentState}})),console.log(`[redoEnhanced] After redo for space ${r}:`,{pastActionsLength:t().spaces[r]?.sharedState?.pastActions?.length||0,newFutureActionsLength:c.length}),ot(n,s),{success:!0,action:s}},setSelectionState:(t,r)=>{e(e=>{const n=e.spaces[t];n&&(n.sharedState.selectionState=r)})},subscribeToHistory:(t,r)=>(e(e=>{const n=e.spaces[t];n&&n.sharedState.subscribers.push(r)}),()=>{e(e=>{const n=e.spaces[t];n&&(n.sharedState.subscribers=n.sharedState.subscribers.filter(e=>e!==r))})}),canUndo:e=>{const r=t().spaces[e];return!!r&&(Array.isArray(r.sharedState.pastActions)?r.sharedState.pastActions.length>0:(t().migrateSpaceHistory(e),!1))},canRedo:e=>{const r=t().spaces[e];return!!r&&(Array.isArray(r.sharedState.futureActions)?r.sharedState.futureActions.length>0:(t().migrateSpaceHistory(e),!1))},getCurrentAction:e=>{const r=t().spaces[e];return r&&r.sharedState.currentActionId&&r.sharedState.pastActions.find(e=>e.id===r.sharedState.currentActionId)||null},getHistoryLength:e=>{const r=t().spaces[e];return r?r.sharedState.pastActions.length:0},getHistoryStats:e=>{const r=t().spaces[e];if(!r)return{totalActions:0,pastActions:0,futureActions:0,memoryUsage:0,lastActionTime:0,averageActionDuration:0};const{pastActions:n,futureActions:a}=r.sharedState,o=n.length+a.length,s=n[n.length-1];return{totalActions:o,pastActions:n.length,futureActions:a.length,memoryUsage:JSON.stringify(r.sharedState).length,lastActionTime:s?.timestamp||0,averageActionDuration:o>0?n.reduce((e,t)=>e+(t.metadata.duration||0),0)/o:0}},clearHistory:t=>{e(e=>{const r=e.spaces[t];r&&(r.sharedState.pastActions=[],r.sharedState.futureActions=[],r.sharedState.isActionInProgress=!1,r.sharedState.currentActionId=null)})},migrateSpaceHistory:t=>{e(e=>{const r=e.spaces[t];r&&(Array.isArray(r.sharedState.pastActions)||(r.sharedState.pastActions=[]),Array.isArray(r.sharedState.futureActions)||(r.sharedState.futureActions=[]),"boolean"!=typeof r.sharedState.isActionInProgress&&(r.sharedState.isActionInProgress=!1),void 0===r.sharedState.currentActionId&&(r.sharedState.currentActionId=null),r.sharedState.currentState||(r.sharedState.currentState={}),r.sharedState.actionMetadata||(r.sharedState.actionMetadata={}),Array.isArray(r.sharedState.subscribers)||(r.sharedState.subscribers=[]),console.log(`Space ${t} history migrated successfully`))})},clearErrors:()=>{e(e=>{e.errors=[]})},updateSpaceGenericSharedState:r=>{const{spaceId:n,changes:a,actionName:o,actionDescription:s}=r,i=t().spaces[n];if(!i)return e(e=>{e.errors=[`Space with ID ${r.spaceId} not found for shared state update.`]}),void console.error("Shared state update failed: Space not found");const c=i.sharedState.currentState,d=a.actionType||o||"UPDATE_SHARED_STATE";a.payload,e(e=>{const t=e.spaces[n];if(t){const{actionType:r,payload:n,...o}=a;t.sharedState.currentState={...t.sharedState.currentState,...o},e.errors=[]}});const l=t().spaces[n]?.sharedState.currentState;if(!l)return void console.error("Shared state update failed: Space disappeared after update?");const u=at(`${d}-${Date.now()}`,s||d,[],c,!1,[]);u.metadata={...u.metadata,nextState:l},e(e=>{const t=e.spaces[n];t&&(t.sharedState.pastActions.push(u),t.sharedState.futureActions=[])})},jumpToHistoryAction:(r,n)=>{const a=t().spaces[r];if(!a)return;const o=a.sharedState.pastActions||[],s=a.sharedState.futureActions||[];let i=o.findIndex(e=>e.id===n);if(-1!==i){const t=o.slice(0,i+1),n=[...o.slice(i+1),...s];return void e(e=>{const a=e.spaces[r];a&&(a.sharedState.pastActions=t,a.sharedState.futureActions=n,a.sharedState.currentState=o[i].state)})}if(i=s.findIndex(e=>e.id===n),-1!==i){const t=[...o,...s.slice(0,i+1)],n=s.slice(i+1);e(e=>{const a=e.spaces[r];a&&(a.sharedState.pastActions=t,a.sharedState.futureActions=n,a.sharedState.currentState=s[i].state)})}},getSpaceById:e=>t().spaces[e],getAllSpaces:()=>t().spaces,getActiveSpace:()=>{const e=t();return e.activeSpaceId?e.spaces[e.activeSpaceId]:null},getActiveSpaceId:()=>t().activeSpaceId,getOpenSpaces:()=>{const e=t();return e.openSpaceIds.map(t=>e.spaces[t]).filter(e=>void 0!==e)},getSpaceErrors:()=>t().errors,getPilotMode:()=>t().pilotMode}),{name:"karmyc-space-store",partialize:e=>{const t={};for(const r in e.spaces){const{sharedState:n,...a}=e.spaces[r],{pastActions:o,futureActions:s,subscribers:i,...c}=n??{};t[r]={...a,sharedState:c}}const{activeSpaceId:r}=e;return{spaces:t,activeSpaceId:r}},merge:(e,t)=>{const r=e,n={},a=r?.spaces??{},o=t.spaces,s=new Set([...Object.keys(a),...Object.keys(o)]);for(const e of s){const t=a[e],r=o[e];if(!t&&!r)continue;const s=r?.sharedState??nt(),i=t?.sharedState??{};n[e]={id:t?.id??r?.id??e,name:t?.name??r?.name??`Space ${e}`,description:t?.description??r?.description??"",color:t?.color??r?.color??"#0000ff",sharedState:{...s,...i,pastActions:[],futureActions:[],subscribers:[]}},n[e].color||(n[e].color="#000000")}return{...t,activeSpaceId:r?.activeSpaceId??t.activeSpaceId,spaces:n,errors:[]}}})))),it=e=>{const t=[];return e.id||t.push("Missing ID"),e.type||t.push("Missing type"),e.state||t.push("Missing state"),{isValid:0===t.length,errors:t}},ct=e=>{const t=[];return"number"!=typeof e.x&&t.push("Position X must be a number"),"number"!=typeof e.y&&t.push("Position Y must be a number"),isNaN(e.x)&&t.push("Position X is NaN"),isNaN(e.y)&&t.push("Position Y is NaN"),{isValid:0===t.length,errors:t}},dt=e=>{const t=[];return e.id||t.push("Missing ID"),e.label||t.push("Missing label"),e.actionId||t.push("Missing actionId"),{isValid:0===t.length,errors:t}},lt=e=>t=>{let r="";return e(e=>{const n=e.screens[e.activeScreenId]?.areas;if(!n)return;const a=t.id||$();let o;if(t.type){o=(j._roleMap||{})[t.type]}const s={...t,id:a,role:o};if(o===U.LEAD&&!s.spaceId){const e=st.getState().spaces,r=Object.keys(e);if(r.length>0){const e=st.getState().activeSpaceId;s.spaceId=e||r[0]}else{const e=st.getState().addSpace({name:`Space for ${t.type}`,sharedState:{}});e&&(s.spaceId=e)}}const i=it(s);i.isValid?(n.areas[a]=s,n._id+=1,n.errors=[],r=a,e.lastUpdated=Date.now()):(n.errors=i.errors,console.error("Validation failed for area:",i.errors))}),r};const ut=new class{constructor(){this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}publish(e){this.listeners.forEach(t=>t(e))}},pt=e=>t=>{e(e=>{const r=e.screens[e.activeScreenId]?.areas;if(!r)return;if(Object.keys(r.areas).length<=1)console.warn("Cannot remove the last area of a screen");else{delete r.areas[t],delete r.layout[t];for(const e in r.layout){const n=r.layout[e];if("area_row"===n.type){const a=n,o=a.areas.findIndex(e=>e.id===t);if(-1!==o)if(a.areas.splice(o,1),"stack"===a.orientation){if(a.activeTabId===t&&(a.activeTabId=a.areas[0]?.id||void 0),0===a.areas.length)delete r.layout[e];else if(1===a.areas.length){const t=Object.keys(r.layout).find(t=>{const n=r.layout[t];return"area_row"===n.type&&n.areas.some(t=>t.id===e)});if(t){const n=r.layout[t],o=n.areas.findIndex(t=>t.id===e);-1!==o&&(n.areas[o]={...a.areas[0]}),delete r.layout[e]}else r.rootId===e&&(r.rootId=a.areas[0].id,delete r.layout[e])}}else 0===a.areas.length&&delete r.layout[e]}}r.rootId===t&&(r.rootId=null),r.activeAreaId===t&&(r.activeAreaId=null),r.errors=[],e.lastUpdated=Date.now(),ut.publish({type:"cleanup",areaId:t})}})},ft=(e,t,r)=>e*(1-r)+t*r,ht=(e,t,r)=>Math.min(t,Math.max(e,r)),yt=e=>e instanceof gt?e:"number"==typeof e.left?new gt(e.left,e.top):new gt(e.x,e.y);class gt{static new(e,t){return"number"==typeof e?new gt(e,t):"number"==typeof e.left?new gt(e.left,e.top):new gt(e.x,e.y)}static fromEvent(e){return new gt(e.clientX,e.clientY)}static dot(e,t){const r=yt(e),n=yt(t);return r.x*n.x+r.y*n.y}constructor(e,t){"number"==typeof e?(this._x=e,this._y=t):(this._x=e.x,this._y=e.y),this.atOrigin=0===this.x&&0===this.y,this.apply=this.apply.bind(this)}set x(e){this._x=e,this.atOrigin=0===this.x&&0===this.y}get x(){return this._x}set y(e){this._y=e,this.atOrigin=0===this.x&&0===this.y}get y(){return this._y}add(e){const t=yt(e);return t.atOrigin?this:new gt(this.x+t.x,this.y+t.y)}addX(e){return new gt(this.x+e,this.y)}addY(e){return new gt(this.x,this.y+e)}sub(e){const t=yt(e);return t.atOrigin?this:new gt(this.x-t.x,this.y-t.y)}subX(e){return new gt(this.x-e,this.y)}subY(e){return new gt(this.x,this.y-e)}subXY(e,t){return new gt(this.x-e,this.y-t)}scale(e,t=gt.new(0,0)){if(1===e)return this;const r=yt(t);return new gt(r.x+(this.x-r.x)*e,r.y+(this.y-r.y)*e)}scaleX(e,t=gt.new(0,0)){if(1===e)return this;const r=yt(t);return new gt(r.x+(this.x-r.x)*e,this.y)}scaleY(e,t=gt.new(0,0)){if(1===e)return this;const r=yt(t);return new gt(this.x,r.y+(this.y-r.y)*e)}scaleXY(e,t,r=gt.new(0,0)){if(1===e&&1===t)return this;const n=yt(r);return new gt(n.x+(this.x-n.x)*e,n.y+(this.y-n.y)*t)}rotate(e,t=gt.new(0,0)){if(0===e)return this;const r=yt(t),n=this.x-r.x,a=this.y-r.y,o=Math.cos(e),s=Math.sin(e),i=n*s+a*o;return new gt(n*o-a*s+r.x,i+r.y)}multiplyMat2(e,t=gt.new(0,0)){const r=yt(t);return e.multiplyVec2(this.sub(r)).add(r)}copy(){return new gt(this.x,this.y)}lerp(e,t){const r=yt(e);return new gt(ft(this.x,r.x,t),ft(this.y,r.y,t))}round(){return gt.new(Math.round(this.x),Math.round(this.y))}apply(e)