@gamesberry/karmyc-core
Version:
A flexible and powerful layout management system for React applications
28 lines • 163 kB
JavaScript
"use strict";var e=require("react/jsx-runtime"),t=require("react"),r=require("@szhsin/react-menu");const a=new Map,n=e=>{const t=a.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([e,t])=>[e,t.getState()])):{}},o=(e,t={})=>(r,o,i)=>{const{enabled:c,anonymousActionType:l,store:d,...u}=t;let p;try{p=(null==c||c)&&window.__REDUX_DEVTOOLS_EXTENSION__}catch(e){}if(!p)return c&&console.warn("[zustand devtools middleware] Please install/enable Redux devtools extension"),e(r,o,i);const{connection:f,...h}=((e,t,r)=>{if(void 0===e)return{type:"untracked",connection:t.connect(r)};const n=a.get(r.name);if(n)return{type:"tracked",store:e,...n};const o={connection:t.connect(r),stores:{}};return a.set(r.name,o),{type:"tracked",store:e,...o}})(d,p,u);let y=!0;i.setState=(e,t,a)=>{const s=r(e,t);if(!y)return s;const c=void 0===a?{type:l||"anonymous"}:"string"==typeof a?{type:a}:a;return void 0===d?(null==f||f.send(c,o()),s):(null==f||f.send({...c,type:`${d}/${c.type}`},{...n(u.name),[d]:i.getState()}),s)};const g=(...e)=>{const t=y;y=!1,r(...e),y=t},m=e(i.setState,o,i);if("untracked"===h.type?null==f||f.init(m):(h.stores[h.store]=i,null==f||f.init(Object.fromEntries(Object.entries(h.stores).map(([e,t])=>[e,e===h.store?m:t.getState()])))),i.dispatchFromDevtools&&"function"==typeof i.dispatch){let e=!1;const t=i.dispatch;i.dispatch=(...r)=>{"__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 f.subscribe(e=>{var t;switch(e.type){case"ACTION":return"string"!=typeof e.payload?void console.error("[zustand devtools middleware] Unsupported action format"):s(e.payload,e=>{if("__setState"===e.type){if(void 0===d)return void g(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[d];if(null==t)return;return void(JSON.stringify(i.getState())!==JSON.stringify(t)&&g(t))}i.dispatchFromDevtools&&"function"==typeof i.dispatch&&i.dispatch(e)});case"DISPATCH":switch(e.payload.type){case"RESET":return g(m),void 0===d?null==f?void 0:f.init(i.getState()):null==f?void 0:f.init(n(u.name));case"COMMIT":return void 0===d?void(null==f||f.init(i.getState())):null==f?void 0:f.init(n(u.name));case"ROLLBACK":return s(e.state,e=>{if(void 0===d)return g(e),void(null==f||f.init(i.getState()));g(e[d]),null==f||f.init(n(u.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return s(e.state,e=>{void 0!==d?JSON.stringify(i.getState())!==JSON.stringify(e[d])&&g(e[d]):g(e)});case"IMPORT_STATE":{const{nextLiftedState:r}=e.payload,a=null==(t=r.computedStates.slice(-1)[0])?void 0:t.state;if(!a)return;return g(void 0===d?a:a[d]),void(null==f||f.send(null,r))}case"PAUSE_RECORDING":return y=!y}return}}),m},s=(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)},i=e=>(t,r,a)=>{const n=a.subscribe;a.subscribe=(e,t,r)=>{let o=e;if(t){const n=(null==r?void 0:r.equalityFn)||Object.is;let s=e(a.getState());o=r=>{const a=e(r);if(!n(s,a)){const e=s;t(s=a,e)}},(null==r?void 0:r.fireImmediately)&&t(s,s)}return n(o)};return e(t,r,a)};function c(e,t){let r;try{r=e()}catch(e){return}return{getItem:e=>{var t;const a=e=>null===e?null:JSON.parse(e,void 0),n=null!=(t=r.getItem(e))?t:null;return n instanceof Promise?n.then(a):a(n)},setItem:(e,t)=>r.setItem(e,JSON.stringify(t,void 0)),removeItem:e=>r.removeItem(e)}}const l=e=>t=>{try{const r=e(t);return r instanceof Promise?r:{then:e=>l(e)(r),catch(e){return this}}}catch(e){return{then(e){return this},catch:t=>l(t)(e)}}},d=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?(console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),((e,t)=>(r,a,n)=>{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)},a,n);const u=l(o.serialize),p=()=>{const e=o.partialize({...a()});let t;const r=u({state:e,version:o.version}).then(e=>d.setItem(o.name,e)).catch(e=>{t=e});if(t)throw t;return r},f=n.setState;n.setState=(e,t)=>{f(e,t),p()};const h=e((...e)=>{r(...e),p()},a,n);let y;const g=()=>{var e;if(!d)return;s=!1,i.forEach(e=>e(a()));const t=(null==(e=o.onRehydrateStorage)?void 0:e.call(o,a()))||void 0;return l(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 y=o.merge(e,null!=(t=a())?t:h),r(y,!0),p()}).then(()=>{null==t||t(y,void 0),s=!0,c.forEach(e=>e(y))}).catch(e=>{null==t||t(void 0,e)})};return n.persist={setOptions:e=>{o={...o,...e},e.getStorage&&(d=e.getStorage())},clearStorage:()=>{null==d||d.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>g(),hasHydrated:()=>s,onHydrate:e=>(i.add(e),()=>{i.delete(e)}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e)})},g(),y||h})(e,t)):((e,t)=>(r,a,n)=>{let o={storage:c(()=>localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},s=!1;const i=new Set,d=new Set;let u=o.storage;if(!u)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),r(...e)},a,n);const p=()=>{const e=o.partialize({...a()});return u.setItem(o.name,{state:e,version:o.version})},f=n.setState;n.setState=(e,t)=>{f(e,t),p()};const h=e((...e)=>{r(...e),p()},a,n);let y;n.getInitialState=()=>h;const g=()=>{var e,t;if(!u)return;s=!1,i.forEach(e=>{var t;return e(null!=(t=a())?t:h)});const n=(null==(t=o.onRehydrateStorage)?void 0:t.call(o,null!=(e=a())?e:h))||void 0;return l(u.getItem.bind(u))(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[n,s]=e;if(y=o.merge(s,null!=(t=a())?t:h),r(y,!0),n)return p()}).then(()=>{null==n||n(y,void 0),y=a(),s=!0,d.forEach(e=>e(y))}).catch(e=>{null==n||n(void 0,e)})};return n.persist={setOptions:e=>{o={...o,...e},e.storage&&(u=e.storage)},clearStorage:()=>{null==u||u.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>g(),hasHydrated:()=>s,onHydrate:e=>(i.add(e),()=>{i.delete(e)}),onFinishHydration:e=>(d.add(e),()=>{d.delete(e)})},o.skipHydration||g(),y||h})(e,t),u=e=>t=>{e(e=>{const r=e.screens[e.activeScreenId]?.areas;r&&r.joinPreview!==t&&(r.joinPreview=t,e.lastUpdated=Date.now())})};function p(e){const t={};if(!e)return console.error("computeAreaToParentRow received null or undefined layout."),{};const r=Object.keys(e);for(let a=0;a<r.length;a+=1){const n=e[r[a]];if(!n||"area_row"!==n.type)continue;const o=n;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 f(e,t){if(!t)return;const r=e.layout[t];if(!r||"area_row"!==r.type)return;const a=r;if(1!==a.areas.length)return;const n=a.areas[0],o=n.id,s=p(e.layout)[t];if(s&&"area_row"===e.layout[s]?.type){const r=e.layout[s],a=r.areas.findIndex(e=>e.id===t);if(-1===a)return void console.error(`[simplifyLayoutNodeIfNeeded] Cleanup Error: Row ${t} not found in parent ${s}.`);{const e=r.areas[a].size??n.size??.5;r.areas[a]={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 h(e,t){const r=e[t];return r?"area"===r.type?t:"area_row"===r.type?0===r.areas.length?null:h(e,r.areas[0].id):null:null}const y=e=>t=>{let r=null;return e(e=>{const a=e.screens[e.activeScreenId]?.areas;if(!a)return;const{areaIdToSplit:n,parentRowId:o,horizontal:s}=t,i=a.layout[n];if("area_row"===i.type&&"stack"===i.orientation){const e=i.areas,t=[];for(const r of e){const e=a.areas[r.id];if(!e)continue;const n=`area-${a._id+1}`;a._id+=1,a.areas[n]={id:n,type:e.type,state:{...e.state}},a.layout[n]={type:"area",id:n},t.push({id:n,size:r.size})}const c=`row-${a._id+1}`;a._id+=1;const l={id:c,type:"area_row",orientation:"stack",areas:t,activeTabId:t[0]?.id};a.layout[c]=l;const d=`row-${a._id+1}`;a._id+=1;const u={id:d,type:"area_row",orientation:s?"horizontal":"vertical",areas:[{id:n,size:.5},{id:c,size:.5}]};if(a.layout[d]=u,o){const e=a.layout[o];if("area_row"===e?.type){const t=e.areas.findIndex(e=>e.id===n);if(-1!==t){const r=e.areas[t].size??.5;e.areas[t]={id:d,size:r}}}}else a.rootId=d;return void(r={newRowId:d,separatorIndex:1})}a._id+=1;const c=a._id,l=`area-${c}`,d=`row-${c+1}`;if(a.areas[l]||a.layout[l])return void console.error(`splitArea: ID conflict for new area ${l}`);const u=a.areas[n];if(a.areas[l]={id:l,type:u?.type||i.type,state:{...u?.state},spaceId:u?.spaceId},a.layout[l]={type:"area",id:l},a.layout[d])return void console.error(`splitArea: ID conflict for new row ${d}`);const h={id:d,type:"area_row",orientation:s?"horizontal":"vertical",areas:[{id:n,size:.5},{id:l,size:.5}]};a.layout[d]=h;let y=.5;if(o){const e=a.layout[o];if("area_row"===e?.type){const t=e.areas.findIndex(e=>e.id===n);if(-1!==t)if(y=e.areas[t].size??.5,e.orientation===h.orientation){const a=h.areas.map(e=>({id:e.id,size:(e.size??.5)*y}));e.areas.splice(t,1,...a),r={newRowId:o,separatorIndex:t+1}}else e.areas[t]={id:d,size:y},r={newRowId:d,separatorIndex:1};else console.error(`splitArea Error: Area ${n} not in parent ${o}.`)}else console.error(`splitArea Error: Parent ${o} not found or not row.`)}else a.rootId===n?(a.rootId=d,r={newRowId:d,separatorIndex:1}):console.error(`splitArea Error: Area ${n} has no parent and is not root.`);a._id=c+2,a.lastSplitResultData=r,function(e){if(!e)return;let t=e;for(;t;){const e=a.layout[t];f(a,t);if(t=p(a.layout)[t],!e||a.layout[e.id])break}}(o),function e(t,r=null){if(!t)return;const n=a.layout[t];if(!n||"area_row"!==n.type)return;let o=!1;for(let e=0;e<n.areas.length;){const t=n.areas[e].id,r=a.layout[t];if(r&&"area_row"===r.type&&r.orientation===n.orientation){const s=r,i=n.areas[e].size??1/n.areas.length,c=s.areas.reduce((e,t)=>e+(t.size??0),0)||1,l=s.areas.map(e=>({id:e.id,size:(e.size??1/s.areas.length)*i/c}));n.areas.splice(e,1,...l.filter(e=>!n.areas.some(t=>t.id===e.id))),delete a.layout[t],o=!0}else e++}for(const r of n.areas)e(r.id,t);o&&e(t,r)}(a.rootId),function(){const e=new Set;!function t(r){if(!r||e.has(r))return;e.add(r);const n=a.layout[r];if(n&&"area_row"===n.type)for(const e of n.areas)t(e.id)}(a.rootId);for(const t in a.layout){const r=a.layout[t];r&&"area_row"===r.type&&!e.has(t)&&delete a.layout[t]}}(),e.lastUpdated=Date.now()}),r},g=(e,t,r)=>{const a=t,n=a+r;if(a<0||a>=e.areas.length||n<0||n>=e.areas.length)throw new Error(`Invalid indices: source=${a}, target=${n}, length=${e.areas.length}, direction=${-1===r?"west":"east"}`);const o=e.areas[a],s=e.areas[n];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[n]={id:o.id,size:i},c.splice(a,1);return{area:{...e,areas:c},removedAreaId:s.id}};let m=[],w=!1,v=null;const S=e=>{const t=w;t||(w=!0,m=[]);try{e()}finally{!t&&w&&Zt.setState(e=>(m.forEach(e=>e()),m=[],w=!1,e.lastUpdated=Date.now(),e))}},b=e=>t=>{S(()=>{e(e=>{const r=e.screens[e.activeScreenId]?.areas;if(!r)return;const{sourceAreaId:a,targetAreaId:n}=t,{parentRow:o,sourceIndex:s,targetIndex:i}=function(e,t,r){for(const a in e){const n=e[a];if("area_row"===n.type){const e=n,a=e.areas.findIndex(e=>e.id===t),o=e.areas.findIndex(e=>e.id===r);if(-1!==a&&-1!==o&&1===Math.abs(a-o))return{parentRow:e,sourceIndex:a,targetIndex:o}}}return{parentRow:null,sourceIndex:-1,targetIndex:-1}}(r.layout,a,n);if(!o||"area_row"!==o.type)return r.errors=[`Could not find adjacent areas ${a}/${n} in the same row.`],void(r.joinPreview=null);const c=o.id,l=p(r.layout)[c],d=JSON.parse(JSON.stringify(o)),u=i>s?1:-1,h=s;try{const e=g(d,h,u),{area:t,removedAreaId:a}=e,n=function(e,t){const r=new Set,a=[t],n=new Set;for(;a.length>0;){const t=a.shift();if(n.has(t))continue;n.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&&a.push(e.id)})}}return"area"===e[t]?.type&&r.add(t),r}(r.layout,a);if(n.add(a),n.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&&f(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}),l&&"area_row"===r.layout[l]?.type){const e=r.layout[l],a=e.areas.findIndex(e=>e.id===c);if(-1!==a){const r=e.areas[a].size??.5;e.areas[a]={id:t.id,size:r}}else console.error(`[joinOrMoveArea] Cleanup Error: Row ${c} not found in grandparent ${l}.`)}else r.rootId===c&&(r.rootId=t.id);r.activeAreaId&&n.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()})})},A=[];for(let e=0;e<256;++e)A.push((e+256).toString(16).slice(1));let I;const x=new Uint8Array(16);var E={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function _(e,t,r){if(E.randomUUID&&!e)return E.randomUUID();const a=(e=e||{}).random??e.rng?.()??function(){if(!I){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");I=crypto.getRandomValues.bind(crypto)}return I(x)}();if(a.length<16)throw new Error("Random bytes length must be >= 16");return a[6]=15&a[6]|64,a[8]=63&a[8]|128,function(e,t=0){return(A[e[t+0]]+A[e[t+1]]+A[e[t+2]]+A[e[t+3]]+"-"+A[e[t+4]]+A[e[t+5]]+"-"+A[e[t+6]]+A[e[t+7]]+"-"+A[e[t+8]]+A[e[t+9]]+"-"+A[e[t+10]]+A[e[t+11]]+A[e[t+12]]+A[e[t+13]]+A[e[t+14]]+A[e[t+15]]).toLowerCase()}(a)}const O=new Map,k={registerComponent:(e,t)=>{const r=O.get(e)||{};O.set(e,{...r,component:t})},registerInitialState:(e,t)=>{const r=O.get(e)||{};O.set(e,{...r,initialState:t})},registerDisplayName:(e,t)=>{const r=O.get(e)||{};O.set(e,{...r,displayName:t})},registerIcon:(e,t)=>{const r=O.get(e)||{};O.set(e,{...r,icon:t})},registerDefaultSize:(e,t)=>{const r=O.get(e)||{};O.set(e,{...r,defaultSize:t})},registerSupportedActions:(e,t)=>{const r=O.get(e)||{};O.set(e,{...r,supportedActions:t})},getComponent:e=>O.get(e)?.component,getInitialState:e=>O.get(e)?.initialState||{},getDisplayName:e=>O.get(e)?.displayName||e,getIcon:e=>O.get(e)?.icon,getDefaultSize:e=>O.get(e)?.defaultSize,getSupportedActions:e=>O.get(e)?.supportedActions,getRegisteredTypes:()=>new Set(Array.from(O.keys())),unregisterAreaType:e=>{O.delete(e)},isRegistered:e=>O.has(e),getFallbackType:e=>(O.has(e)||console.warn(`[AreaRegistry] Type "${e}" not registered, using original type`),e)};var T;exports.ActionPriority=void 0,(T=exports.ActionPriority||(exports.ActionPriority={}))[T.CRITICAL=1e3]="CRITICAL",T[T.HIGH=800]="HIGH",T[T.NORMAL=500]="NORMAL",T[T.LOW=200]="LOW",T[T.BACKGROUND=100]="BACKGROUND";const M={LEAD:"LEAD",FOLLOW:"FOLLOW",SELF:"SELF"},C=e=>{let t;const r=new Set,a=(e,a)=>{const n="function"==typeof e?e(t):e;if(!Object.is(n,t)){const e=t;t=(null!=a?a:"object"!=typeof n||null===n)?n:Object.assign({},t,n),r.forEach(r=>r(t,e))}},n=()=>t,o={setState:a,getState:n,getInitialState:()=>s,subscribe:e=>(r.add(e),()=>r.delete(e)),destroy:()=>{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(a,n,o);return o};function z(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var D,j={exports:{}},R={},L={exports:{}},N={};var P,$,F,H={};
/**
* @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 U(){return $||($=1,"production"===process.env.NODE_ENV?L.exports=function(){if(D)return N;D=1;var e=t,r="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},a=e.useState,n=e.useEffect,o=e.useLayoutEffect,s=e.useDebugValue;function i(e){var t=e.getSnapshot;e=e.value;try{var a=t();return!r(e,a)}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 r=t(),c=a({inst:{value:r,getSnapshot:t}}),l=c[0].inst,d=c[1];return o(function(){l.value=r,l.getSnapshot=t,i(l)&&d({inst:l})},[e,r,t]),n(function(){return i(l)&&d({inst:l}),e(function(){i(l)&&d({inst:l})})},[e]),s(r),r};return N.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:c,N}():L.exports=(P||(P=1,"production"!==process.env.NODE_ENV&&function(){function e(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!a(e,r)}catch(e){return!0}}"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var r=t,a="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},n=r.useState,o=r.useEffect,s=r.useLayoutEffect,i=r.useDebugValue,c=!1,l=!1,d="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(t,d){c||void 0===r.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=d();if(!l){var p=d();a(u,p)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),l=!0)}var f=(p=n({inst:{value:u,getSnapshot:d}}))[0].inst,h=p[1];return s(function(){f.value=u,f.getSnapshot=d,e(f)&&h({inst:f})},[t,u,d]),o(function(){return e(f)&&h({inst:f}),t(function(){e(f)&&h({inst:f})})},[t]),i(u),u};H.useSyncExternalStore=void 0!==r.useSyncExternalStore?r.useSyncExternalStore:d,"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),H)),L.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 V,B={};
/**
* @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?j.exports=function(){if(F)return R;F=1;var e=t,r=U(),a="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},n=r.useSyncExternalStore,o=e.useRef,s=e.useEffect,i=e.useMemo,c=e.useDebugValue;return R.useSyncExternalStoreWithSelector=function(e,t,r,l,d){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,n=e,e=l(e),void 0!==d&&p.hasValue){var t=p.value;if(d(t,e))return o=t}return o=e}if(t=o,a(n,e))return t;var r=l(e);return void 0!==d&&d(t,r)?(n=e,t):(n=e,o=r)}var n,o,s=!1,i=void 0===r?null:r;return[function(){return e(t())},null===i?void 0:function(){return e(i())}]},[t,r,l,d]);var f=n(e,u[0],u[1]);return s(function(){p.hasValue=!0,p.value=f},[f]),c(f),f},R}():j.exports=(V||(V=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=t,r=U(),a="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},n=r.useSyncExternalStore,o=e.useRef,s=e.useEffect,i=e.useMemo,c=e.useDebugValue;B.useSyncExternalStoreWithSelector=function(e,t,r,l,d){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,n=e,e=l(e),void 0!==d&&p.hasValue){var t=p.value;if(d(t,e))return o=t}return o=e}if(t=o,a(n,e))return t;var r=l(e);return void 0!==d&&d(t,r)?(n=e,t):(n=e,o=r)}var n,o,s=!1,i=void 0===r?null:r;return[function(){return e(t())},null===i?void 0:function(){return e(i())}]},[t,r,l,d]);var f=n(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())}()),B);var K=z(j.exports);const{useDebugValue:q}=t,{useSyncExternalStoreWithSelector:J}=K;let G=!1;const W=e=>e;const Y=e=>{"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?C(e):C)(e):e,r=(e,r)=>function(e,t=W,r){r&&!G&&(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"),G=!0);const a=J(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,r);return q(a),a}(t,e,r);return Object.assign(r,t),r},X=e=>e?Y(e):Y;var Z=Symbol.for("immer-nothing"),Q=Symbol.for("immer-draftable"),ee=Symbol.for("immer-state"),te="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 re(e,...t){if("production"!==process.env.NODE_ENV){const r=te[e],a="function"==typeof r?r.apply(null,t):r;throw new Error(`[Immer] ${a}`)}throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var ae=Object.getPrototypeOf;function ne(e){return!!e&&!!e[ee]}function oe(e){return!!e&&(ie(e)||Array.isArray(e)||!!e[Q]||!!e.constructor?.[Q]||pe(e)||fe(e))}var se=Object.prototype.constructor.toString();function ie(e){if(!e||"object"!=typeof e)return!1;const t=ae(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)===se}function ce(e,t){0===le(e)?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,a)=>t(a,r,e))}function le(e){const t=e[ee];return t?t.type_:Array.isArray(e)?1:pe(e)?2:fe(e)?3:0}function de(e,t){return 2===le(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ue(e,t,r){const a=le(e);2===a?e.set(t,r):3===a?e.add(r):e[t]=r}function pe(e){return e instanceof Map}function fe(e){return e instanceof Set}function he(e){return e.copy_||e.base_}function ye(e,t){if(pe(e))return new Map(e);if(fe(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const r=ie(e);if(!0===t||"class_only"===t&&!r){const t=Object.getOwnPropertyDescriptors(e);delete t[ee];let r=Reflect.ownKeys(t);for(let a=0;a<r.length;a++){const n=r[a],o=t[n];!1===o.writable&&(o.writable=!0,o.configurable=!0),(o.get||o.set)&&(t[n]={configurable:!0,writable:!0,enumerable:o.enumerable,value:e[n]})}return Object.create(ae(e),t)}{const t=ae(e);if(null!==t&&r)return{...e};const a=Object.create(t);return Object.assign(a,e)}}function ge(e,t=!1){return we(e)||ne(e)||!oe(e)||(le(e)>1&&(e.set=e.add=e.clear=e.delete=me),Object.freeze(e),t&&Object.entries(e).forEach(([e,t])=>ge(t,!0))),e}function me(){re(2)}function we(e){return Object.isFrozen(e)}var ve,Se={};function be(e){const t=Se[e];return t||re(0,e),t}function Ae(){return ve}function Ie(e,t){t&&(be("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function xe(e){Ee(e),e.drafts_.forEach(Oe),e.drafts_=null}function Ee(e){e===ve&&(ve=e.parent_)}function _e(e){return ve={drafts_:[],parent_:ve,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Oe(e){const t=e[ee];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function ke(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];return void 0!==e&&e!==r?(r[ee].modified_&&(xe(t),re(4)),oe(e)&&(e=Te(t,e),t.parent_||Ce(t,e)),t.patches_&&be("Patches").generateReplacementPatches_(r[ee].base_,e,t.patches_,t.inversePatches_)):e=Te(t,r,[]),xe(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Z?e:void 0}function Te(e,t,r){if(we(t))return t;const a=t[ee];if(!a)return ce(t,(n,o)=>Me(e,a,t,n,o,r)),t;if(a.scope_!==e)return t;if(!a.modified_)return Ce(e,a.base_,!0),a.base_;if(!a.finalized_){a.finalized_=!0,a.scope_.unfinalizedDrafts_--;const t=a.copy_;let n=t,o=!1;3===a.type_&&(n=new Set(t),t.clear(),o=!0),ce(n,(n,s)=>Me(e,a,t,n,s,r,o)),Ce(e,t,!1),r&&e.patches_&&be("Patches").generatePatches_(a,r,e.patches_,e.inversePatches_)}return a.copy_}function Me(e,t,r,a,n,o,s){if("production"!==process.env.NODE_ENV&&n===r&&re(5),ne(n)){const s=Te(e,n,o&&t&&3!==t.type_&&!de(t.assigned_,a)?o.concat(a):void 0);if(ue(r,a,s),!ne(s))return;e.canAutoFreeze_=!1}else s&&r.add(n);if(oe(n)&&!we(n)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Te(e,n),t&&t.scope_.parent_||"symbol"==typeof a||!Object.prototype.propertyIsEnumerable.call(r,a)||Ce(e,n)}}function Ce(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ge(t,r)}var ze={get(e,t){if(t===ee)return e;const r=he(e);if(!de(r,t))return function(e,t,r){const a=Re(t,r);return a?"value"in a?a.value:a.get?.call(e.draft_):void 0}(e,r,t);const a=r[t];return e.finalized_||!oe(a)?a:a===je(e.base_,t)?(Ne(e),e.copy_[t]=Pe(a,e)):a},has:(e,t)=>t in he(e),ownKeys:e=>Reflect.ownKeys(he(e)),set(e,t,r){const a=Re(he(e),t);if(a?.set)return a.set.call(e.draft_,r),!0;if(!e.modified_){const a=je(he(e),t),s=a?.[ee];if(s&&s.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(((n=r)===(o=a)?0!==n||1/n==1/o:n!=n&&o!=o)&&(void 0!==r||de(e.base_,t)))return!0;Ne(e),Le(e)}var n,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!==je(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,Ne(e),Le(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const r=he(e),a=Reflect.getOwnPropertyDescriptor(r,t);return a?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:a.enumerable,value:r[t]}:a},defineProperty(){re(11)},getPrototypeOf:e=>ae(e.base_),setPrototypeOf(){re(12)}},De={};function je(e,t){const r=e[ee];return(r?he(r):e)[t]}function Re(e,t){if(!(t in e))return;let r=ae(e);for(;r;){const e=Object.getOwnPropertyDescriptor(r,t);if(e)return e;r=ae(r)}}function Le(e){e.modified_||(e.modified_=!0,e.parent_&&Le(e.parent_))}function Ne(e){e.copy_||(e.copy_=ye(e.base_,e.scope_.immer_.useStrictShallowCopy_))}ce(ze,(e,t)=>{De[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),De.deleteProperty=function(e,t){return"production"!==process.env.NODE_ENV&&isNaN(parseInt(t))&&re(13),De.set.call(this,e,t,void 0)},De.set=function(e,t,r){return"production"!==process.env.NODE_ENV&&"length"!==t&&isNaN(parseInt(t))&&re(14),ze.set.call(this,e[0],t,r,e[0])};function Pe(e,t){const r=pe(e)?be("MapSet").proxyMap_(e,t):fe(e)?be("MapSet").proxySet_(e,t):function(e,t){const r=Array.isArray(e),a={type_:r?1:0,scope_:t?t.scope_:Ae(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let n=a,o=ze;r&&(n=[a],o=De);const{revoke:s,proxy:i}=Proxy.revocable(n,o);return a.draft_=i,a.revoke_=s,i}(e,t);return(t?t.scope_:Ae()).drafts_.push(r),r}function $e(e){if(!oe(e)||we(e))return e;const t=e[ee];let r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=ye(e,t.scope_.immer_.useStrictShallowCopy_)}else r=ye(e,!0);return ce(r,(e,t)=>{ue(r,e,$e(t))}),t&&(t.finalized_=!1),r}var Fe=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 a=this;return function(e=r,...n){return a.produce(e,e=>t.call(this,e,...n))}}let a;if("function"!=typeof t&&re(6),void 0!==r&&"function"!=typeof r&&re(7),oe(e)){const n=_e(this),o=Pe(e,void 0);let s=!0;try{a=t(o),s=!1}finally{s?xe(n):Ee(n)}return Ie(n,r),ke(a,n)}if(!e||"object"!=typeof e){if(a=t(e),void 0===a&&(a=e),a===Z&&(a=void 0),this.autoFreeze_&&ge(a,!0),r){const t=[],n=[];be("Patches").generateReplacementPatches_(e,a,t,n),r(t,n)}return a}re(1,e)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...r)=>this.produceWithPatches(t,t=>e(t,...r));let r,a;return[this.produce(e,t,(e,t)=>{r=e,a=t}),r,a]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){oe(e)||re(8),ne(e)&&(e=function(e){ne(e)||re(10,e);return $e(e)}(e));const t=_e(this),r=Pe(e,void 0);return r[ee].isManual_=!0,Ee(t),r}finishDraft(e,t){const r=e&&e[ee];r&&r.isManual_||re(9);const{scope_:a}=r;return Ie(a,t),ke(void 0,a)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const a=t[r];if(0===a.path.length&&"replace"===a.op){e=a.value;break}}r>-1&&(t=t.slice(r+1));const a=be("Patches").applyPatches_;return ne(e)?a(e,t):this.produce(e,e=>a(e,t))}},He=Fe.produce;Fe.produceWithPatches.bind(Fe),Fe.setAutoFreeze.bind(Fe),Fe.setUseStrictShallowCopy.bind(Fe),Fe.applyPatches.bind(Fe),Fe.createDraft.bind(Fe),Fe.finishDraft.bind(Fe);const Ue=e=>(t,r,a)=>(a.setState=(e,r,...a)=>{const n="function"==typeof e?He(e):e;return t(n,r,...a)},e(a.setState,r,a)),Ve={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"},Be={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"},Ke={maxHistorySize:100,captureState:!0,enableNotifications:!0,enableSelections:!0,filter:()=>!0,groupBy:e=>e.metadata.actionType},qe=()=>({currentState:{},pastActions:[],futureActions:[],isActionInProgress:!1,currentActionId:null,actionMetadata:{},subscribers:[]}),Je=(e,t,r=[],a,n=!1,o=[])=>({id:e,name:t,timestamp:Date.now(),diffs:r,state:a,allowIndexShift:n,modifiedRelated:o.includes("selection"),metadata:{actionType:t,payload:{},duration:0},indexDirection:1}),Ge=(e,t)=>{e.sharedState.subscribers.forEach(e=>{try{e(t)}catch(e){console.error("Error in history subscriber:",e)}})},We=X()(Ue(o(d((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 a=_(),n={id:a,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[a]=n,e.openSpaceIds.push(a),e.errors=[]}),a},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:a,...n}=t;e.spaces[a]={...r,...n},e.errors=[]}else e.errors=[`Space with ID ${t.id} not found for update.`],console.error("Update failed:",e.errors)})},startAction:(r,a)=>{const n=t().spaces[r];return n?n.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=a,t.sharedState.currentState={...t.sharedState.currentState})}),{success:!0,metadata:{actionId:a}}):{success:!1,error:`Space with ID ${r} not found`}},submitAction:(r,a,n=[],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=Je(i.sharedState.currentActionId,a,n,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>Ke.maxHistorySize&&t.sharedState.pastActions.shift())}),Ge(i,c),{success:!0,action:c}},cancelAction:r=>{const a=t().spaces[r];return a?a.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 a=t().spaces[r];if(!a)return{success:!1,error:`Space with ID ${r} not found`};if(console.log(`[undoEnhanced] Start for space ${r}:`,{pastActionsLength:a.sharedState.pastActions?.length||0,futureActionsLength:a.sharedState.futureActions?.length||0,pastActions:a.sharedState.pastActions,futureActions:a.sharedState.futureActions}),!Array.isArray(a.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===a.sharedState.pastActions.length)return console.log(`[undoEnhanced] No action to undo for space ${r}`),{success:!1,error:"No actions to undo"};const n=a.sharedState.pastActions;if(!Array.isArray(n)||0===n.length)return console.error(`Space ${r} has invalid pastActions after validation:`,n),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=n.length-1,s=n[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=n.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}),Ge(a,s),{success:!0,action:s}},redoEnhanced:r=>{const a=t().spaces[r];if(!a)return{success:!1,error:`Space with ID ${r} not found`};if(console.log(`[redoEnhanced] Start for space ${r}:`,{pastActionsLength:a.sharedState.pastActions?.length||0,futureActionsLength:a.sharedState.futureActions?.length||0,pastActions:a.sharedState.pastActions,futureActions:a.sharedState.futureActions}),!Array.isArray(a.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===a.sharedState.futureActions.length)return console.log(`[redoEnhanced] No action to redo for space ${r}`),{success:!1,error:"No actions to redo"};const n=a.sharedState.futureActions;if(!Array.isArray(n)||0===n.length)return console.error(`Space ${r} has invalid futureActions after validation:`,n),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=n.length-1,s=n[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=n.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 l=t().spaces[r];return l&&"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("karmyc-state-changed",{detail:{state:l.sharedState.currentState}})),console.log(`[redoEnhanced] After redo for space ${r}:`,{pastActionsLength:t().spaces[r]?.sharedState?.pastActions?.length||0,newFutureActionsLength:c.length}),Ge(a,s),{success:!0,action:s}},setSelectionState:(t,r)=>{e(e=>{const a=e.spaces[t];a&&(a.sharedState.selectionState=r)})},subscribeToHistory:(t,r)=>(e(e=>{const a=e.spaces[t];a&&a.sharedState.subscribers.push(r)}),()=>{e(e=>{const a=e.spaces[t];a&&(a.sharedState.subscribers=a.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:a,futureActions:n}=r.sharedState,o=a.length+n.length,s=a[a.length-1];return{totalActions:o,pastActions:a.length,futureActions:n.length,memoryUsage:JSON.stringify(r.sharedState).length,lastActionTime:s?.timestamp||0,averageActionDuration:o>0?a.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:a,changes:n,actionName:o,actionDescription:s}=r,i=t().spaces[a];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,l=n.actionType||o||"UPDATE_SHARED_STATE";n.payload,e(e=>{const t=e.spaces[a];if(t){const{actionType:r,payload:a,...o}=n;t.sharedState.currentState={...t.sharedState.currentState,...o},e.errors=[]}});const d=t().spaces[a]?.sharedState.currentState;if(!d)return void console.error("Shared state update failed: Space disappeared after update?");const u=Je(`${l}-${Date.now()}`,s||l,[],c,!1,[]);u.metadata={...u.metadata,nextState:d},e(e=>{const t=e.spaces[a];t&&(t.sharedState.pastActions.push(u),t.sharedState.futureActions=[])})},jumpToHistoryAction:(r,a)=>{const n=t().spaces[r];if(!n)return;const o=n.sharedState.pastActions||[],s=n.sharedState.futureActions||[];let i=o.findIndex(e=>e.id===a);if(-1!==i){const t=o.slice(0,i+1),a=[...o.slice(i+1),...s];return void e(e=>{const n=e.spaces[r];n&&(n.sharedState.pastActions=t,n.sharedState.futureActions=a,n.sharedState.currentState=o[i].state)})}if(i=s.findIndex(e=>e.id===a),-1!==i){const t=[...o,...s.slice(0,i+1)],a=s.slice(i+1);e(e=>{const n=e.spaces[r];n&&(n.sharedState.pastActions=t,n.sharedState.futureActions=a,n.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:a,...n}=e.spaces[r],{pastActions:o,futureActions:s,subscribers:i,...c}=a??{};t[r]={...n,sharedState:c}}const{activeSpaceId:r}=e;return{spaces:t,activeSpaceId:r}},merge:(e,t)=>{const r=e,a={},n=r?.spaces??{},o=t.spaces,s=new Set([...Object.keys(n),...Object.keys(o)]);for(const e of s){const t=n[e],r=o[e];if(!t&&!r)continue;const s=r?.sharedState??qe(),i=t?.sharedState??{};a[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:[]}},a[e].color||(a[e].color="#000000")}return{...t,activeSpaceId:r?.activeSpaceId??t.activeSpaceId,spaces:a,errors:[]}}})))),Ye=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}},Xe=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}},Ze=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}},Qe=e=>t=>{let r="";return e(e=>{const a=e.screens[e.activeScreenId]?.areas;if(!a)return;const n=t.id||_();let o;if(t.type){o=(k._roleMap||{})[t.type]}const s={...t,id:n,role:o};if(o===M.LEAD&&!s.spaceId){const e=We.getState().spaces,r=Object.keys(e);if(r.length>0){const e=We.getState().activeSpaceId;s.spaceId=e||r[0]}else{const e=We.getState().addSpace({name:`Space for ${t.type}`,sharedState:{}});e&&(s.spaceId=e)}}const i=Ye(s);i.isValid?(a.areas[n]=s,a._id+=1,a.errors=[],r=n,e.lastUpdated=Date.now()):(a.errors=i.errors,console.error("Validation failed for area:",i.errors))}),r};const et=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))}},tt=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 a=r.layout[e];if("area_row"===a.type){const n=a,o=n.areas.findIndex(e=>e.id===t);if(-1!==o)if(n.areas.splice(o,1),"stack"===n.orientation){if(n.activeTabId===t&&(n.activeTabId=n.areas[0]?.id||void 0),0===n.areas.length)delete r.layout[e];else if(1===n.areas.length){const t=Object.keys(r.layout).find(t=>{const a=r.layout[t];return"area_row"===a.type&&a.areas.some(t=>t.id===e)});if(t){const a=r.layout[t],o=a.areas.findIndex(t=>t.id===e);-1!==o&&(a.areas[o]={...n.areas[0]}),delete r.layout[e]}else r.rootId===e&&(r.rootId=n.areas[0].id,delete r.layout[e])}}else 0===n.areas.length&&delete r.layout[e]}}r.rootId===t&&(r.rootId=null),r.activeAreaId===t&&(r.activeAreaId=null),r.errors=[],e.lastUpdated=Date.now(),et.publish({type:"cleanup",areaId:t})}})},rt=(e,t,r)=>e*(1-r)+t*r,at=(e,t,r)=>Math.min(t,Math.max(e,r)),nt=e=>e instanceof ot?e:"number"==typeof e.left?new ot(e.left,e.top):new ot(e.x,e.y);class ot{static new(e,t){return"number"==typeof e?new ot(e,t):"number"==typeof e.left?new ot(e.left,e.top):new ot(e.x,e.y)}static fromEvent(e){return new ot(e.clientX,e.clientY)}static dot(e,t){const r=nt(e),a=nt(t);return r.x*a.x+r.y*a.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=nt(e);return t.atOrigin?this:new ot(this.x+t.x,this.y+t.y)}addX(e){return new ot(this.x+e,this.y)}addY(e){return new ot(this.x,this.y+e)}sub(e){const t=nt(e);return t.atOrigin?this:new ot(this.x-t.x,this.y-t.y)}subX(e){return new ot(this.x-e,this.y)}subY(e){return new ot(this.x,this.y-e)}subXY(e,t){return new ot(this.x-e,this.y-t)}scale(e,t=ot.new(0,0)){if(1===e)return this;const r=nt(t);return new ot(r.x+(this.x-r.x)*e,r.y+(this.y-r.y)*e)}scaleX(e,t=ot.new(0,0)){if(1===e)return this;const r=nt(t);return new ot(r.x+(this.x-r.x)*e,this.y)}scaleY(e,t=ot.new(0,0)){if(1===e)return this;const r=nt(t);return new ot(this.x,r.y+(this.y-r.y)*e)}scaleXY(e,t,r=ot.new(0,0)){if(1===e&&1===t)return this;const a=nt(r);return new ot(a.x+(this.x-a.x)*e,a.y+(this.y-a.y)*t)}rotate(e,t=ot.new(0,0)){if(0===e)return this;const r=nt(t),a=this.x-r.x,n=this.y-r.y,o=Math.cos(e),s=Math.sin(e),i=a*s+n*o;return new ot(a*o-n*s+r.x,i+r.y)}multiplyMat2(e,t=ot.new(0,0)){const r=nt(t);return e.multiplyVec2(this.sub(r)).add(r)}copy(){return new ot(this.x,this.y)}lerp(e,t){const r=nt(e);return new ot(rt(this.x,r.x,t),rt(this.y,r.y,t))}round(){return ot.new(Math.round(this.x),Math.round(this.y))}apply(e){return nt(e(this))}length(){return Math.hypot(this.x,this.y)}eq(e){const t=nt(e);return t.x===this.x&&t.y===this.y}toJSON(){return{x:this.x,y:this.y,__objectType:"vec2"}}}ot.ORIGIN=ot.new(0,0);const st=(e,t,r,a)=>{const n=a?ot.new(e.x+a.x/15,e.y+a.y/15):e;let o,s,i,c=1/0;return Object.entries(r).forEach(([e,r])=>{const a=t.layout[e];if(!a||"area"!==a.type&&("area_row"!==a.type||"stack"!==a.orientation))return;if(n.x>=r.left&&n.x<=r.left+r.width&&n.y>=r.top&&n.y<=r.top+r.height)return void("area_row"===a.type&&"stack"===a.orientation?o=e:"area"===a.type&&(s=e));cons