@object-ui/console 3.0.3 → 3.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/assets/AdvancedChartImpl-D711bBuO.js +7 -0
- package/dist/assets/AppManagementPage-D_71FpIH.js +1 -0
- package/dist/assets/AuditLogPage-D3g_VEdE.js +1 -0
- package/dist/assets/AuthPageLayout-9l5xWV_-.js +1 -0
- package/dist/assets/{ChartImpl-2ivTljUi.js → ChartImpl-B9B4Fnbe.js} +1 -1
- package/dist/assets/CreateAppPage-mqt5j4rK.js +1 -0
- package/dist/assets/DashboardDesignPage-Cijb3jeF.js +1 -0
- package/dist/assets/DashboardView-DjhlMHLV.js +1 -0
- package/dist/assets/EditAppPage-BiK_DWcO.js +1 -0
- package/dist/assets/ForgotPasswordPage-Bzady8r_.js +1 -0
- package/dist/assets/KanbanEnhanced-OvdpYe81.js +1 -0
- package/dist/assets/KanbanImpl-EcxwmGw7.js +1 -0
- package/dist/assets/LoginPage-valW4Wu1.js +1 -0
- package/dist/assets/{MarkdownImpl-BshtTFK2.js → MarkdownImpl-C0wRapHT.js} +2 -2
- package/dist/assets/OrgManagementPage-D0d52PdP.js +1 -0
- package/dist/assets/PageDesignPage-hpFLdWCR.js +1 -0
- package/dist/assets/PageView-DxIAf-SB.js +2 -0
- package/dist/assets/PermissionManagementPage-ELCC8HyK.js +1 -0
- package/dist/assets/ProfilePage-Dj1N0mY3.js +1 -0
- package/dist/assets/RecordDetailView-DS9tEr5f.js +1 -0
- package/dist/assets/RegisterPage-DqUU8oW-.js +1 -0
- package/dist/assets/ReportView-CNi0A66t.js +1 -0
- package/dist/assets/RoleManagementPage-DRvuG53j.js +1 -0
- package/dist/assets/SearchResultsPage-nMlMQCb8.js +1 -0
- package/dist/assets/SystemHubPage-CAY-YvG2.js +1 -0
- package/dist/assets/UserManagementPage-fzvfJxav.js +1 -0
- package/dist/assets/data-adapter-rvE3xy2B.js +1 -0
- package/dist/assets/framework-BM176iet.js +10 -0
- package/dist/assets/index-B6cpm7bF.css +1 -0
- package/dist/assets/index-CTBPkbPG.js +9 -0
- package/dist/assets/index-Dv78M4Xq.js +1 -0
- package/dist/assets/infrastructure-n1j_TN6w.js +1 -0
- package/dist/assets/maplibre-gl-DVmJFhI2.js +811 -0
- package/dist/assets/plugins-core-qwgXbAqa.js +8 -0
- package/dist/assets/plugins-views-CveFN6PV.js +62 -0
- package/dist/assets/ui-components-BxvihT61.js +36 -0
- package/dist/assets/ui-components-CRV2BvKI.css +1 -0
- package/dist/assets/ui-layout-C6KWQtRO.js +1 -0
- package/dist/assets/{vendor-charts-CSvoW-yB.js → vendor-charts-BLNOCZWl.js} +2 -2
- package/dist/assets/vendor-dndkit-CX1oDZqy.js +5 -0
- package/dist/assets/vendor-i18n-E3-WitRV.js +9 -0
- package/dist/assets/{vendor-icons-CQ8b-fGy.js → vendor-icons-ndICq8DC.js} +3425 -3535
- package/dist/assets/vendor-objectstack-YKtcdalX.js +34 -0
- package/dist/assets/{vendor-radix-BbeYj_o4.js → vendor-radix-C6qchjxv.js} +1 -1
- package/dist/assets/vendor-react-9M-xu2bR.js +60 -0
- package/dist/assets/vendor-ui-utils-3tkeUVaX.js +1 -0
- package/dist/assets/vendor-zod-DxQVy2_o.js +39 -0
- package/dist/index.html +23 -22
- package/package.json +49 -46
- package/plugin.d.ts +1 -2
- package/plugin.js +1 -2
- package/plugin.ts +1 -2
- package/dist/assets/AdvancedChartImpl-DAS1mU9o.js +0 -7
- package/dist/assets/AdvancedChartImpl-DAS1mU9o.js.br +0 -0
- package/dist/assets/AdvancedChartImpl-DAS1mU9o.js.gz +0 -0
- package/dist/assets/AuditLogPage-CyY7VZJW.js +0 -1
- package/dist/assets/AuditLogPage-CyY7VZJW.js.br +0 -0
- package/dist/assets/AuditLogPage-CyY7VZJW.js.gz +0 -0
- package/dist/assets/ChartImpl-2ivTljUi.js.br +0 -0
- package/dist/assets/ChartImpl-2ivTljUi.js.gz +0 -0
- package/dist/assets/DashboardView-DSh9LYBb.js +0 -1
- package/dist/assets/DashboardView-DSh9LYBb.js.br +0 -0
- package/dist/assets/DashboardView-DSh9LYBb.js.gz +0 -0
- package/dist/assets/ForgotPasswordPage-DUfjj-wh.js +0 -1
- package/dist/assets/KanbanEnhanced-ZOndyXyg.js +0 -1
- package/dist/assets/KanbanEnhanced-ZOndyXyg.js.br +0 -0
- package/dist/assets/KanbanEnhanced-ZOndyXyg.js.gz +0 -0
- package/dist/assets/KanbanImpl-BsMtStI7.js +0 -1
- package/dist/assets/KanbanImpl-BsMtStI7.js.br +0 -0
- package/dist/assets/KanbanImpl-BsMtStI7.js.gz +0 -0
- package/dist/assets/LoginPage-2CoFvwsL.js +0 -1
- package/dist/assets/MarkdownImpl-BshtTFK2.js.br +0 -0
- package/dist/assets/MarkdownImpl-BshtTFK2.js.gz +0 -0
- package/dist/assets/OrgManagementPage-BJt5Iiun.js +0 -1
- package/dist/assets/OrgManagementPage-BJt5Iiun.js.br +0 -0
- package/dist/assets/OrgManagementPage-BJt5Iiun.js.gz +0 -0
- package/dist/assets/PageView-bHvRhycc.js +0 -1
- package/dist/assets/PageView-bHvRhycc.js.br +0 -0
- package/dist/assets/PageView-bHvRhycc.js.gz +0 -0
- package/dist/assets/ProfilePage-MVUfKMrp.js +0 -1
- package/dist/assets/ProfilePage-MVUfKMrp.js.br +0 -0
- package/dist/assets/ProfilePage-MVUfKMrp.js.gz +0 -0
- package/dist/assets/RecordDetailView-Sm8_iQw_.js +0 -1
- package/dist/assets/RecordDetailView-Sm8_iQw_.js.br +0 -0
- package/dist/assets/RecordDetailView-Sm8_iQw_.js.gz +0 -0
- package/dist/assets/RegisterPage-B9itUVYp.js +0 -1
- package/dist/assets/ReportView-B0D9jx4v.js +0 -1
- package/dist/assets/ReportView-B0D9jx4v.js.br +0 -0
- package/dist/assets/ReportView-B0D9jx4v.js.gz +0 -0
- package/dist/assets/RoleManagementPage-BRqaeF_L.js +0 -1
- package/dist/assets/RoleManagementPage-BRqaeF_L.js.br +0 -0
- package/dist/assets/RoleManagementPage-BRqaeF_L.js.gz +0 -0
- package/dist/assets/SearchResultsPage-wlC0eLLr.js +0 -1
- package/dist/assets/SearchResultsPage-wlC0eLLr.js.br +0 -0
- package/dist/assets/SearchResultsPage-wlC0eLLr.js.gz +0 -0
- package/dist/assets/UserManagementPage-DOH6ql6-.js +0 -1
- package/dist/assets/UserManagementPage-DOH6ql6-.js.br +0 -0
- package/dist/assets/UserManagementPage-DOH6ql6-.js.gz +0 -0
- package/dist/assets/ViewDesignerPage-TCaXYb43.js +0 -1
- package/dist/assets/ViewDesignerPage-TCaXYb43.js.br +0 -0
- package/dist/assets/ViewDesignerPage-TCaXYb43.js.gz +0 -0
- package/dist/assets/data-adapter-D15yh-pb.js +0 -1
- package/dist/assets/data-adapter-D15yh-pb.js.br +0 -0
- package/dist/assets/data-adapter-D15yh-pb.js.gz +0 -0
- package/dist/assets/framework-mHWN965c.js +0 -10
- package/dist/assets/framework-mHWN965c.js.br +0 -0
- package/dist/assets/framework-mHWN965c.js.gz +0 -0
- package/dist/assets/index-CUnVdETN.css +0 -1
- package/dist/assets/index-CUnVdETN.css.br +0 -0
- package/dist/assets/index-CUnVdETN.css.gz +0 -0
- package/dist/assets/index-RAPqkKVL.js +0 -9
- package/dist/assets/index-RAPqkKVL.js.br +0 -0
- package/dist/assets/index-RAPqkKVL.js.gz +0 -0
- package/dist/assets/infrastructure-Di0WqY4l.js +0 -1
- package/dist/assets/infrastructure-Di0WqY4l.js.br +0 -0
- package/dist/assets/infrastructure-Di0WqY4l.js.gz +0 -0
- package/dist/assets/maplibre-gl-D2AsLM0J.js +0 -811
- package/dist/assets/maplibre-gl-D2AsLM0J.js.br +0 -0
- package/dist/assets/maplibre-gl-D2AsLM0J.js.gz +0 -0
- package/dist/assets/plugins-core-Cv2TPt86.js +0 -4
- package/dist/assets/plugins-core-Cv2TPt86.js.br +0 -0
- package/dist/assets/plugins-core-Cv2TPt86.js.gz +0 -0
- package/dist/assets/plugins-views-P3eB-els.css.br +0 -0
- package/dist/assets/plugins-views-P3eB-els.css.gz +0 -0
- package/dist/assets/plugins-views-divN-xXs.js +0 -60
- package/dist/assets/plugins-views-divN-xXs.js.br +0 -0
- package/dist/assets/plugins-views-divN-xXs.js.gz +0 -0
- package/dist/assets/systemObjects-DSpePIIy.js.br +0 -2
- package/dist/assets/systemObjects-DSpePIIy.js.gz +0 -0
- package/dist/assets/ui-components-CseD2Dpn.js +0 -31
- package/dist/assets/ui-components-CseD2Dpn.js.br +0 -0
- package/dist/assets/ui-components-CseD2Dpn.js.gz +0 -0
- package/dist/assets/ui-components-GrNdJOi1.css +0 -1
- package/dist/assets/ui-components-GrNdJOi1.css.br +0 -0
- package/dist/assets/ui-components-GrNdJOi1.css.gz +0 -0
- package/dist/assets/ui-layout-CF_1bNSv.js +0 -1
- package/dist/assets/ui-layout-CF_1bNSv.js.br +0 -0
- package/dist/assets/ui-layout-CF_1bNSv.js.gz +0 -0
- package/dist/assets/vendor-charts-CSvoW-yB.js.br +0 -0
- package/dist/assets/vendor-charts-CSvoW-yB.js.gz +0 -0
- package/dist/assets/vendor-dndkit-DRGpK6sP.js +0 -5
- package/dist/assets/vendor-dndkit-DRGpK6sP.js.br +0 -0
- package/dist/assets/vendor-dndkit-DRGpK6sP.js.gz +0 -0
- package/dist/assets/vendor-i18n-D5KbMT7w.js +0 -9
- package/dist/assets/vendor-i18n-D5KbMT7w.js.br +0 -0
- package/dist/assets/vendor-i18n-D5KbMT7w.js.gz +0 -0
- package/dist/assets/vendor-icons-CQ8b-fGy.js.br +0 -0
- package/dist/assets/vendor-icons-CQ8b-fGy.js.gz +0 -0
- package/dist/assets/vendor-objectstack-Bifvxvds.js +0 -1
- package/dist/assets/vendor-objectstack-Bifvxvds.js.br +0 -0
- package/dist/assets/vendor-objectstack-Bifvxvds.js.gz +0 -0
- package/dist/assets/vendor-radix-BbeYj_o4.js.br +0 -0
- package/dist/assets/vendor-radix-BbeYj_o4.js.gz +0 -0
- package/dist/assets/vendor-react-Dy_xkBQQ.js +0 -60
- package/dist/assets/vendor-react-Dy_xkBQQ.js.br +0 -0
- package/dist/assets/vendor-react-Dy_xkBQQ.js.gz +0 -0
- package/dist/assets/vendor-ui-utils-h6yAcIi9.js +0 -1
- package/dist/assets/vendor-ui-utils-h6yAcIi9.js.br +0 -0
- package/dist/assets/vendor-ui-utils-h6yAcIi9.js.gz +0 -0
- package/dist/assets/vendor-zod-UZPqlszj.js +0 -39
- package/dist/assets/vendor-zod-UZPqlszj.js.br +0 -0
- package/dist/assets/vendor-zod-UZPqlszj.js.gz +0 -0
- package/dist/index.html.br +0 -0
- package/dist/index.html.gz +0 -0
- package/dist/mockServiceWorker.js.br +0 -0
- package/dist/mockServiceWorker.js.gz +0 -0
- package/dist/stats.html +0 -4949
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ChartImpl-2ivTljUi.js","assets/vendor-react-Dy_xkBQQ.js","assets/vendor-charts-CSvoW-yB.js","assets/vendor-ui-utils-h6yAcIi9.js","assets/vendor-i18n-D5KbMT7w.js","assets/AdvancedChartImpl-DAS1mU9o.js","assets/KanbanImpl-BsMtStI7.js","assets/vendor-dndkit-DRGpK6sP.js","assets/ui-components-CseD2Dpn.js","assets/framework-mHWN965c.js","assets/vendor-icons-CQ8b-fGy.js","assets/vendor-radix-BbeYj_o4.js","assets/ui-components-GrNdJOi1.css","assets/KanbanEnhanced-ZOndyXyg.js","assets/plugins-core-Cv2TPt86.js","assets/plugins-views-divN-xXs.js","assets/plugins-views-P3eB-els.css","assets/RecordDetailView-Sm8_iQw_.js","assets/infrastructure-Di0WqY4l.js","assets/data-adapter-D15yh-pb.js","assets/vendor-objectstack-Bifvxvds.js","assets/vendor-zod-UZPqlszj.js","assets/ui-layout-CF_1bNSv.js","assets/DashboardView-DSh9LYBb.js","assets/PageView-bHvRhycc.js","assets/ReportView-B0D9jx4v.js","assets/ViewDesignerPage-TCaXYb43.js","assets/SearchResultsPage-wlC0eLLr.js","assets/LoginPage-2CoFvwsL.js","assets/RegisterPage-B9itUVYp.js","assets/ForgotPasswordPage-DUfjj-wh.js","assets/UserManagementPage-DOH6ql6-.js","assets/systemObjects-DSpePIIy.js","assets/OrgManagementPage-BJt5Iiun.js","assets/RoleManagementPage-BRqaeF_L.js","assets/AuditLogPage-CyY7VZJW.js","assets/ProfilePage-MVUfKMrp.js","assets/maplibre-gl-D2AsLM0J.js","assets/MarkdownImpl-BshtTFK2.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as i,j as t,L as te,u as at,h as ye,i as Oe,R as q,k as qt,B as Ja,l as Jt,m as V,N as nt,d as Yt,n as Ya}from"./vendor-react-Dy_xkBQQ.js";import{ac as Zt,ad as Za,ae as Xa,af as Q,ag as pe,t as ae,u as ne,ah as ge,v as se,ai as yt,w as G,aa as ke,aj as Qa,ak as xe,al as Be,am as be,an as en,ao as tn,ap as vt,aq as wt,ar as Nt,as as an,a2 as nn,a3 as sn,a4 as rn,B as $,c as P,W as on,at as ln,au as cn,av as dn,aw as un,ax as mn,ay as fn,az as hn,aA as pn,aB as gn,aC as xn,aD as bn,aE as X,aF as J,aG as ze,aH as Le,aI as Ae,aJ as st,aK as jn,_ as K,a9 as ve,N as we,P as yn,J as vn,K as wn,aL as Nn,x as Xt,y as Qt,z as ea,A as ta,C as ee,S as Dn,h as Cn,D as rt,l as ot,n as it,o as lt,p as ct,aM as Dt}from"./ui-components-CseD2Dpn.js";import{O as Sn,a as kn}from"./plugins-core-Cv2TPt86.js";import{E as dt,k as Fn,C as z,g as me,c as ut,f as Ne,l as En,m as Tn}from"./framework-mHWN965c.js";import{b as Ge,T as Mn}from"./vendor-ui-utils-h6yAcIi9.js";import{u as aa,g as Ct,a as na,b as oe,A as Ve,P as Rn,c as _n,I as On}from"./infrastructure-Di0WqY4l.js";import{O as sa}from"./data-adapter-D15yh-pb.js";import{A as Ln}from"./ui-layout-CF_1bNSv.js";import{k as St,as as de,m as je,H as ra,ac as An,at as Pn,au as In,av as $n,r as Z,a as Pe,aw as We,ax as He,ay as oa,az as zn,aA as kt,L as Me,g as mt,C as qe,S as Re,aB as Vn,aC as Kn,aD as ia,a1 as Un,aE as la,T as ca,aF as Bn,aG as Gn,b as da,j as ua,aH as Wn,d as Hn,V as qn,aI as Fe,aJ as Ft,Y as Jn,aK as Yn,J as Zn,aL as Xn,_ as Qn,$ as es,aM as ts,R as ma,X as as,c as ns,O as ss,I as rs,aN as os,aO as is}from"./vendor-icons-CQ8b-fGy.js";import{u as fa,L as ls,D as cs,M as ds}from"./plugins-views-divN-xXs.js";import{G as us}from"./vendor-objectstack-Bifvxvds.js";import{o as ft,s as W,t as ms,n as Ke}from"./vendor-zod-UZPqlszj.js";import"./vendor-radix-BbeYj_o4.js";import"./vendor-i18n-D5KbMT7w.js";import"./vendor-charts-CSvoW-yB.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))o(s);new MutationObserver(s=>{for(const r of s)if(r.type==="childList")for(const c of r.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&o(c)}).observe(document,{childList:!0,subtree:!0});function n(s){const r={};return s.integrity&&(r.integrity=s.integrity),s.referrerPolicy&&(r.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?r.credentials="include":s.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function o(s){if(s.ep)return;s.ep=!0;const r=n(s);fetch(s.href,r)}})();const ha=i.createContext(null);function fe(e){return e&&typeof e=="object"&&"items"in e&&Array.isArray(e.items)?e.items:[]}async function Et(e){const a=e.getClient(),[n,o,s,r,c]=await Promise.all([a.meta.getItems("app").catch(()=>({items:[]})),a.meta.getItems("object").catch(()=>({items:[]})),a.meta.getItems("dashboard").catch(()=>({items:[]})),a.meta.getItems("report").catch(()=>({items:[]})),a.meta.getItems("page").catch(()=>({items:[]}))]);return{apps:fe(n),objects:fe(o),dashboards:fe(s),reports:fe(r),pages:fe(c)}}function fs({children:e,adapter:a}){const[n,o]=i.useState({apps:[],objects:[],dashboards:[],reports:[],pages:[],loading:!0,error:null}),s=i.useRef(a);s.current=a;const r=i.useCallback(async()=>{o(l=>({...l,loading:!0,error:null}));try{const l=await Et(s.current);o({...l,loading:!1,error:null})}catch(l){o(d=>({...d,loading:!1,error:l instanceof Error?l:new Error(String(l))}))}},[]);i.useEffect(()=>{let l=!1;return(async()=>{try{const d=await Et(a);l||o({...d,loading:!1,error:null})}catch(d){l||o(h=>({...h,loading:!1,error:d instanceof Error?d:new Error(String(d))}))}})(),()=>{l=!0}},[a]);const c={...n,refresh:r};return t.jsx(ha.Provider,{value:c,children:e})}function ht(){const e=i.useContext(ha);if(!e)throw new Error("useMetadata must be used within a <MetadataProvider>");return e}const pa=i.createContext(null);function ga(){return i.useContext(pa)}function hs({children:e,adapter:a}){const[n,o]=i.useState(a??null);return i.useEffect(()=>{if(a){o(a);return}let s=!1;async function r(){try{const c=new sa({baseUrl:"",autoReconnect:!0,maxReconnectAttempts:5,reconnectDelay:1e3,cache:{maxSize:50,ttl:3e5}});await c.connect(),s||o(c)}catch(c){s||console.error("[Console] Failed to initialize:",c)}}return r(),()=>{s=!0}},[a]),t.jsx(pa.Provider,{value:n,children:e})}const xa=i.createContext(null);function ps({children:e,user:a={},app:n={},data:o={}}){const s=i.useMemo(()=>{const r={user:a,app:n,data:o},c=new dt(r);return{user:a,app:n,data:o,evaluator:c}},[a,n,o]);return t.jsx(xa.Provider,{value:s,children:e})}function ba(){const e=i.useContext(xa);if(!e){const a={user:{},app:{},data:{}};return{...a,evaluator:new dt(a)}}return e}function _e(e,a){if(e==null||e===!0||e==="true")return!0;if(e===!1||e==="false")return!1;if(typeof e=="string"&&e.includes("${"))try{return a.evaluateCondition(e)}catch{return!0}return!0}const ja="objectui-recent-items",gs=8;function Tt(){try{const e=localStorage.getItem(ja);return e?JSON.parse(e):[]}catch{return[]}}function Mt(e){try{localStorage.setItem(ja,JSON.stringify(e))}catch{}}function ya(){const[e,a]=i.useState(Tt);i.useEffect(()=>{a(Tt())},[]);const n=i.useCallback(s=>{a(r=>{const c=r.filter(d=>d.id!==s.id),l=[{...s,visitedAt:new Date().toISOString()},...c].slice(0,gs);return Mt(l),l})},[]),o=i.useCallback(()=>{a([]),Mt([])},[]);return{recentItems:e,addRecentItem:n,clearRecentItems:o}}const va="objectui-favorites",Rt=20;function _t(){try{const e=localStorage.getItem(va);return e?JSON.parse(e):[]}catch{return[]}}function De(e){try{localStorage.setItem(va,JSON.stringify(e))}catch{}}function xs(){const[e,a]=i.useState(_t);i.useEffect(()=>{a(_t())},[]);const n=i.useCallback(l=>{a(d=>{if(d.some(x=>x.id===l.id))return d;const h=[{...l,favoritedAt:new Date().toISOString()},...d].slice(0,Rt);return De(h),h})},[]),o=i.useCallback(l=>{a(d=>{const h=d.filter(x=>x.id!==l);return De(h),h})},[]),s=i.useCallback(l=>{a(d=>{const x=d.some(u=>u.id===l.id)?d.filter(u=>u.id!==l.id):[{...l,favoritedAt:new Date().toISOString()},...d].slice(0,Rt);return De(x),x})},[]),r=i.useCallback(l=>e.some(d=>d.id===l),[e]),c=i.useCallback(()=>{a([]),De([])},[]);return{favorites:e,addFavorite:n,removeFavorite:o,toggleFavorite:s,isFavorite:r,clearFavorites:c}}function Ue(e){if(e!=null)return typeof e=="string"?e:e.defaultValue||e.key}function bs(e){const a=`objectui-nav-order-${e}`,[n,o]=i.useState(()=>{try{const l=localStorage.getItem(a);if(!l)return{};const d=JSON.parse(l);if(typeof d!="object"||d===null||Array.isArray(d))return{};const h={};for(const[x,u]of Object.entries(d))Array.isArray(u)&&u.every(g=>typeof g=="string")&&(h[x]=u);return h}catch{return{}}}),s=i.useCallback(l=>{o(l);try{localStorage.setItem(a,JSON.stringify(l))}catch{}},[a]),r=i.useCallback((l,d)=>{const h=n[l];if(!h)return d;const x=new Map(d.map(g=>[g.id,g])),u=[];for(const g of h){const b=x.get(g);b&&(u.push(b),x.delete(g))}return x.forEach(g=>u.push(g)),u},[n]),c=i.useCallback((l,d)=>{s({...n,[l]:d})},[n,s]);return{applyOrder:r,saveOrder:c}}const wa=i.createContext(null);function Ee(e){if(!e)return de;if(Z[e])return Z[e];const a=e.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("");return Z[a]?Z[a]:de}function js({activeAppName:e,onAppChange:a}){const{isMobile:n}=Zt(),{user:o,signOut:s}=aa();i.useEffect(()=>{let N=0;const T=S=>{N=S.touches[0].clientX},O=S=>{const w=S.changedTouches[0].clientX-N;N<30&&w>50&&n&&document.querySelector('[data-sidebar="trigger"]')?.dispatchEvent(new MouseEvent("click",{bubbles:!0}))};return document.addEventListener("touchstart",T,{passive:!0}),document.addEventListener("touchend",O,{passive:!0}),()=>{document.removeEventListener("touchstart",T),document.removeEventListener("touchend",O)}},[n]);const{recentItems:r}=ya(),{favorites:c,removeFavorite:l}=xs(),{apps:d}=ht(),x=(d||[]).filter(m=>m.active!==!1),u=x.find(m=>m.name===e)||x[0],g=u?.branding?.logo,b=u?.branding?.primaryColor,{applyOrder:f,saveOrder:j}=bs(e),[v,C]=i.useState(null),[E,_]=i.useState(null),[F,y]=i.useState(null),p=i.useMemo(()=>({dragItemId:v,dragGroupKey:E,dropTargetId:F,onDragStart:(m,D)=>{_(m),C(D)},onDragOver:(m,D)=>{m.preventDefault(),m.dataTransfer.dropEffect="move",y(D)},onDrop:(m,D,N)=>{if(m.preventDefault(),!v||D!==E)return;const T=N.map(k=>k.id),O=T.indexOf(v),S=T.indexOf(F);if(O===-1||S===-1||O===S)return;const w=[...T];w.splice(O,1),w.splice(S,0,v),j(D,w)},onDragEnd:()=>{C(null),_(null),y(null)}}),[v,E,F,j]);return t.jsxs(wa.Provider,{value:p,children:[t.jsxs(Za,{collapsible:"icon",children:[t.jsx(Xa,{children:t.jsx(Q,{children:t.jsx(pe,{children:t.jsxs(ae,{children:[t.jsx(ne,{asChild:!0,children:t.jsxs(ge,{size:"lg",className:"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground",children:[t.jsx("div",{className:"flex aspect-square size-8 items-center justify-center rounded-lg bg-primary text-primary-foreground",style:b?{backgroundColor:b}:void 0,children:g?t.jsx("img",{src:g,alt:Ue(u.label),className:"size-6 object-contain"}):i.createElement(Ee(u.icon),{className:"size-4"})}),t.jsxs("div",{className:"grid flex-1 text-left text-sm leading-tight",children:[t.jsx("span",{className:"truncate font-semibold",children:Ue(u.label)}),t.jsx("span",{className:"truncate text-xs",children:Ue(u.description)||`${x.length} Apps Available`})]}),t.jsx(St,{className:"ml-auto"})]})}),t.jsxs(se,{className:"w-[--radix-dropdown-menu-trigger-width] min-w-56 rounded-lg",align:"start",side:n?"bottom":"right",sideOffset:4,children:[t.jsx(yt,{className:"text-xs text-muted-foreground",children:"Switch Application"}),x.map(m=>t.jsxs(G,{onClick:()=>a(m.name),className:"gap-2 p-2",children:[t.jsx("div",{className:"flex size-6 items-center justify-center rounded-sm border",children:m.icon?i.createElement(Ee(m.icon),{className:"size-3"}):t.jsx(de,{className:"size-3"})}),m.label,u.name===m.name&&t.jsx("span",{className:"ml-auto text-xs",children:"✓"})]},m.name)),t.jsx(ke,{}),t.jsxs(G,{className:"gap-2 p-2",children:[t.jsx("div",{className:"flex size-6 items-center justify-center rounded-md border bg-background",children:t.jsx(je,{className:"size-4"})}),t.jsx("div",{className:"font-medium text-muted-foreground",children:"Add App"})]})]})]})})})}),t.jsxs(Qa,{children:[t.jsx(ys,{items:u.navigation||[],activeAppName:e,applyOrder:f}),c.length>0&&t.jsxs(xe,{children:[t.jsxs(Be,{className:"flex items-center gap-1.5",children:[t.jsx(ra,{className:"h-3.5 w-3.5"}),"Favorites"]}),t.jsx(be,{children:t.jsx(Q,{children:c.slice(0,8).map(m=>t.jsxs(pe,{children:[t.jsx(ge,{asChild:!0,tooltip:m.label,children:t.jsxs(te,{to:m.href,children:[t.jsx("span",{className:"text-muted-foreground",children:m.type==="dashboard"?"📊":m.type==="report"?"📈":m.type==="page"?"📄":"📋"}),t.jsx("span",{className:"truncate",children:m.label})]})}),t.jsx(en,{showOnHover:!0,onClick:D=>{D.stopPropagation(),l(m.id)},"aria-label":`Remove ${m.label} from favorites`,children:t.jsx(An,{className:"h-3 w-3"})})]},m.id))})})]}),r.length>0&&t.jsxs(xe,{children:[t.jsxs(Be,{className:"flex items-center gap-1.5",children:[t.jsx(Pn,{className:"h-3.5 w-3.5"}),"Recent"]}),t.jsx(be,{children:t.jsx(Q,{children:r.slice(0,5).map(m=>t.jsx(pe,{children:t.jsx(ge,{asChild:!0,tooltip:m.label,children:t.jsxs(te,{to:m.href,children:[t.jsx("span",{className:"text-muted-foreground",children:m.type==="dashboard"?"📊":m.type==="report"?"📈":"📄"}),t.jsx("span",{className:"truncate",children:m.label})]})})},m.id))})})]})]}),t.jsx(tn,{children:t.jsx(Q,{children:t.jsx(pe,{children:t.jsxs(ae,{children:[t.jsx(ne,{asChild:!0,children:t.jsxs(ge,{size:"lg",className:"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground",children:[t.jsxs(vt,{className:"h-8 w-8 rounded-lg",children:[t.jsx(wt,{src:o?.image??"/avatars/user.jpg",alt:o?.name??"User"}),t.jsx(Nt,{className:"rounded-lg bg-primary text-primary-foreground",children:Ct(o)})]}),t.jsxs("div",{className:"grid flex-1 text-left text-sm leading-tight",children:[t.jsx("span",{className:"truncate font-semibold",children:o?.name??"User"}),t.jsx("span",{className:"truncate text-xs text-muted-foreground",children:o?.email??""})]}),t.jsx(St,{className:"ml-auto size-4"})]})}),t.jsxs(se,{className:"w-[--radix-dropdown-menu-trigger-width] min-w-56 rounded-lg",side:n?"bottom":"right",align:"end",sideOffset:4,children:[t.jsx(yt,{className:"p-0 font-normal",children:t.jsxs("div",{className:"flex items-center gap-2 px-1 py-1.5 text-left text-sm",children:[t.jsxs(vt,{className:"h-8 w-8 rounded-lg",children:[t.jsx(wt,{src:o?.image??"/avatars/user.jpg",alt:o?.name??"User"}),t.jsx(Nt,{className:"rounded-lg bg-primary text-primary-foreground",children:Ct(o)})]}),t.jsxs("div",{className:"grid flex-1 text-left text-sm leading-tight",children:[t.jsx("span",{className:"truncate font-semibold",children:o?.name??"User"}),t.jsx("span",{className:"truncate text-xs text-muted-foreground",children:o?.email??""})]})]})}),t.jsx(ke,{}),t.jsx(an,{children:t.jsxs(G,{children:[t.jsx(In,{className:"mr-2 h-4 w-4"}),"Settings"]})}),t.jsx(ke,{}),t.jsxs(G,{className:"text-destructive focus:text-destructive",onClick:()=>s(),children:[t.jsx($n,{className:"mr-2 h-4 w-4"}),"Log out"]})]})]})})})})]}),n&&t.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-50 flex items-center justify-around border-t bg-background/95 backdrop-blur-sm px-2 py-1 sm:hidden safe-area-bottom",children:(u.navigation||[]).filter(m=>m.type!=="group").slice(0,5).map(m=>{const D=Ee(m.icon),N=`/apps/${e}`;let T="#";return m.type==="object"?T=`${N}/${m.objectName}`:m.type==="dashboard"?T=m.dashboardName?`${N}/dashboard/${m.dashboardName}`:"#":m.type==="page"&&(T=m.pageName?`${N}/page/${m.pageName}`:"#"),t.jsxs(te,{to:T,className:"flex flex-col items-center gap-0.5 px-2 py-1.5 text-muted-foreground hover:text-foreground transition-colors min-w-[44px] min-h-[44px] justify-center",children:[t.jsx(D,{className:"h-5 w-5"}),t.jsx("span",{className:"text-[10px] truncate max-w-[60px]",children:m.label})]},m.id)})})]})}function ys({items:e,activeAppName:a,applyOrder:n}){if(!e.some(l=>l.type==="group")){const l="__root__",d=n(l,e);return t.jsx(xe,{children:t.jsx(be,{children:t.jsx(Q,{children:d.map(h=>t.jsx(Te,{item:h,activeAppName:a,groupKey:l,groupItems:d,applyOrder:n},h.id))})})})}const s=[];let r=[];const c=l=>{if(r.length===0)return;const d=l,h=n(d,r);s.push(t.jsx(xe,{children:t.jsx(be,{children:t.jsx(Q,{children:h.map(x=>t.jsx(Te,{item:x,activeAppName:a,groupKey:d,groupItems:h,applyOrder:n},x.id))})})},`${l}-group`)),r=[]};return e.forEach((l,d)=>{l.type==="group"?(c(`auto-${d}`),s.push(t.jsx(Te,{item:l,activeAppName:a,groupKey:l.id,groupItems:[],applyOrder:n},l.id))):r.push(l)}),c("auto-end"),t.jsx(t.Fragment,{children:s})}function Te({item:e,activeAppName:a,groupKey:n,groupItems:o,applyOrder:s}){const r=Ee(e.icon),c=at(),[l,d]=i.useState(e.expanded!==!1),{evaluator:h}=ba(),x=i.useContext(wa),{can:u}=na();if(!_e(e.visible??e.visibleOn,h)||e.requiredPermissions?.length&&!e.requiredPermissions.every(_=>{const F=_.split(":"),[y,p]=F.length>=2?[F[0],F[1]]:[e.objectName||_,"read"];return u(y,p)}))return null;if(e.type==="group"){const E=e.children??[],_=s(n,E);return t.jsx(nn,{open:l,onOpenChange:d,children:t.jsxs(xe,{children:[t.jsx(Be,{asChild:!0,children:t.jsxs(sn,{className:"flex w-full items-center justify-between",children:[e.label,t.jsx(Pe,{className:`ml-auto transition-transform ${l?"rotate-90":""}`})]})}),t.jsx(rn,{children:t.jsx(be,{children:t.jsx(Q,{children:_.map(F=>t.jsx(Te,{item:F,activeAppName:a,groupKey:n,groupItems:_,applyOrder:s},F.id))})})})]})})}let b="#",f=!1;const j=`/apps/${a}`;if(e.type==="object")b=`${j}/${e.objectName}`,e.viewName&&(b+=`/view/${e.viewName}`);else if(e.type==="page"){if(b=e.pageName?`${j}/page/${e.pageName}`:"#",e.params){const E=new URLSearchParams(e.params);b+=`?${E.toString()}`}}else e.type==="dashboard"?b=e.dashboardName?`${j}/dashboard/${e.dashboardName}`:"#":e.type==="report"?b=e.reportName?`${j}/report/${e.reportName}`:"#":e.type==="url"&&(b=e.url||"#",f=e.target==="_blank");const v=c.pathname.startsWith(b)&&b!=="#",C=x?.dropTargetId===e.id&&x?.dragItemId!==e.id&&x?.dragGroupKey===n;return t.jsx(pe,{draggable:!0,onDragStart:E=>{E.dataTransfer.effectAllowed="move",x?.onDragStart(n,e.id)},onDragOver:E=>x?.onDragOver(E,e.id),onDrop:E=>x?.onDrop(E,n,o),onDragEnd:()=>x?.onDragEnd(),className:C?"border-t-2 border-primary":"",children:t.jsx(ge,{asChild:!0,isActive:v,tooltip:e.label,children:f?t.jsxs("a",{href:b,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(r,{className:"h-4 w-4"}),t.jsx("span",{children:e.label})]}):t.jsxs(te,{to:b,className:"py-2.5 sm:py-2",children:[t.jsx(r,{className:"h-4 w-4"}),t.jsx("span",{children:e.label})]})})})}const vs={theme:"system",setTheme:()=>null},Na=i.createContext(vs);function ws({children:e,defaultTheme:a="system",storageKey:n="vite-ui-theme",...o}){const[s,r]=i.useState(()=>localStorage.getItem(n)||a);i.useEffect(()=>{const l=window.document.documentElement;if(l.classList.remove("light","dark"),s==="system"){const d=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";l.classList.add(d);return}l.classList.add(s)},[s]);const c={theme:s,setTheme:l=>{localStorage.setItem(n,l),r(l)}};return t.jsx(Na.Provider,{...o,value:c,children:e})}const pt=()=>{const e=i.useContext(Na);if(e===void 0)throw new Error("useTheme must be used within a ThemeProvider");return e};function Ns(){const{theme:e,setTheme:a}=pt(),{t:n}=oe();return t.jsxs(ae,{children:[t.jsx(ne,{asChild:!0,children:t.jsxs($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:[t.jsx(We,{className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),t.jsx(He,{className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),t.jsx("span",{className:"sr-only",children:n("console.theme.toggle")})]})}),t.jsxs(se,{align:"end",children:[t.jsxs(G,{onClick:()=>a("light"),className:"gap-2",children:[t.jsx(We,{className:"h-4 w-4"}),n("console.theme.light"),e==="light"&&t.jsx("span",{className:"ml-auto text-xs",children:"✓"})]}),t.jsxs(G,{onClick:()=>a("dark"),className:"gap-2",children:[t.jsx(He,{className:"h-4 w-4"}),n("console.theme.dark"),e==="dark"&&t.jsx("span",{className:"ml-auto text-xs",children:"✓"})]}),t.jsxs(G,{onClick:()=>a("system"),className:"gap-2",children:[t.jsx(oa,{className:"h-4 w-4"}),n("console.theme.system"),e==="system"&&t.jsx("span",{className:"ml-auto text-xs",children:"✓"})]})]})]})}const Ds=[{code:"en",label:"English"},{code:"zh",label:"中文"},{code:"ja",label:"日本語"},{code:"ko",label:"한국어"},{code:"de",label:"Deutsch"},{code:"fr",label:"Français"},{code:"es",label:"Español"},{code:"pt",label:"Português"},{code:"ru",label:"Русский"},{code:"ar",label:"العربية"}];function Cs(){const{t:e,language:a,changeLanguage:n}=oe();return t.jsxs(ae,{children:[t.jsx(ne,{asChild:!0,children:t.jsxs($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:[t.jsx(zn,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:e("console.localeSwitcher.label")})]})}),t.jsx(se,{align:"end",className:"max-h-72 overflow-y-auto",children:Ds.map(o=>t.jsxs(G,{onClick:()=>n(o.code),className:"gap-2",children:[o.label,a===o.code&&t.jsx("span",{className:"ml-auto text-xs",children:"✓"})]},o.code))})]})}const Ss={connected:{label:"Connected",color:"text-green-500",icon:mt},connecting:{label:"Connecting...",color:"text-yellow-500",icon:Me},reconnecting:{label:"Reconnecting...",color:"text-yellow-500",icon:Me},disconnected:{label:"Disconnected",color:"text-muted-foreground",icon:kt},error:{label:"Connection Error",color:"text-destructive",icon:kt}};function ks({state:e,className:a}){const n=Ss[e],o=n.icon,[s,r]=i.useState(!1);return i.useEffect(()=>{if(e==="connected"){r(!0);const c=setTimeout(()=>r(!1),2e3);return()=>clearTimeout(c)}r(!1)},[e]),e==="connected"&&!s?null:t.jsxs("div",{className:P("flex items-center gap-1.5 text-xs font-medium px-2 py-1 rounded-md transition-opacity duration-300",n.color,e==="connected"&&"bg-green-500/10",e==="error"&&"bg-destructive/10",e==="reconnecting"&&"bg-yellow-500/10",a),title:n.label,children:[t.jsx(o,{className:P("h-3.5 w-3.5",(e==="connecting"||e==="reconnecting")&&"animate-spin")}),t.jsx("span",{className:"hidden sm:inline",children:n.label})]})}function he(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,a=>a.toUpperCase())}function Fs({appName:e,objects:a,connectionState:n}){const o=at(),s=ye(),{isOnline:r}=Fn(),c=o.pathname.split("/").filter(Boolean),l=s.appName||c[1],d=c[2],h=`/apps/${l}`,x=a.map(g=>({label:g.label||g.name,href:`${h}/${g.name}`})),u=[{label:e,href:h}];if(d==="dashboard")u.push({label:"Dashboards",href:`${u[0].href}`}),c[3]&&u.push({label:he(c[3])});else if(d==="page")u.push({label:"Pages",href:`${u[0].href}`}),c[3]&&u.push({label:he(c[3])});else if(d==="report")u.push({label:"Reports",href:`${u[0].href}`}),c[3]&&u.push({label:he(c[3])});else if(d==="system")u.push({label:"System"}),c[3]&&u.push({label:he(c[3])});else if(d){const g=a.find(b=>b.name===d);if(g)if(u.push({label:g.label||d,href:`/apps/${l}/${d}`,siblings:x}),c[3]==="record"&&c[4]){const b=c[4].length>12?`${c[4].slice(0,8)}…`:c[4];u.push({label:`#${b}`})}else c[3]==="view"&&c[4]&&u.push({label:he(c[4])})}return t.jsxs("div",{className:"flex items-center justify-between w-full h-full px-2 sm:px-3 md:px-4 gap-1.5 sm:gap-2",children:[t.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 min-w-0 flex-1",children:[t.jsx(on,{className:"md:hidden shrink-0"}),t.jsx(ln,{orientation:"vertical",className:"h-4 md:hidden shrink-0"}),t.jsx(cn,{className:"hidden sm:flex min-w-0",children:t.jsx(dn,{children:u.map((g,b)=>t.jsxs(i.Fragment,{children:[b>0&&t.jsx(un,{}),t.jsx(mn,{children:b===u.length-1||!g.href?g.siblings&&g.siblings.length>1?t.jsxs(ae,{children:[t.jsxs(ne,{className:"flex items-center gap-1 text-sm font-medium",children:[g.label,t.jsx(qe,{className:"h-3 w-3"})]}),t.jsx(se,{align:"start",className:"max-h-64 overflow-y-auto",children:g.siblings.map(f=>t.jsx(G,{asChild:!0,children:t.jsx(te,{to:f.href,className:"w-full",children:f.label})},f.href))})]}):t.jsx(fn,{className:"truncate max-w-[200px]",children:g.label}):g.siblings&&g.siblings.length>1?t.jsxs(ae,{children:[t.jsxs(ne,{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[g.label,t.jsx(qe,{className:"h-3 w-3"})]}),t.jsx(se,{align:"start",className:"max-h-64 overflow-y-auto",children:g.siblings.map(f=>t.jsx(G,{asChild:!0,children:t.jsx(te,{to:f.href,className:"w-full",children:f.label})},f.href))})]}):t.jsx(hn,{asChild:!0,children:t.jsx(te,{to:g.href,className:"truncate max-w-[150px]",children:g.label})})})]},b))})}),t.jsx("span",{className:"text-sm font-medium sm:hidden truncate min-w-0",children:u[u.length-1]?.label||e})]}),t.jsxs("div",{className:"flex items-center gap-0.5 sm:gap-1 md:gap-2 shrink-0",children:[!r&&t.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 rounded-full bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-200 text-xs font-medium",children:[t.jsx("span",{className:"h-2 w-2 rounded-full bg-yellow-500 animate-pulse"}),"Offline"]}),n&&t.jsx(ks,{state:n}),t.jsxs("button",{onClick:()=>document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0})),className:"hidden lg:flex relative items-center gap-2 w-50 xl:w-70 h-8 px-3 text-sm rounded-md border bg-muted/50 text-muted-foreground hover:bg-muted transition-colors",children:[t.jsx(Re,{className:"h-4 w-4"}),t.jsx("span",{className:"flex-1 text-left",children:"Search..."}),t.jsxs("kbd",{className:"pointer-events-none inline-flex h-5 items-center gap-0.5 rounded border bg-muted px-1.5 text-[10px] font-medium text-muted-foreground",children:[t.jsx("span",{className:"text-xs",children:"⌘"}),"K"]})]}),t.jsx($,{variant:"ghost",size:"icon",className:"lg:hidden h-8 w-8 shrink-0",onClick:()=>document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0})),children:t.jsx(Re,{className:"h-4 w-4"})}),t.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 hidden sm:flex shrink-0",children:t.jsx(Vn,{className:"h-4 w-4"})}),t.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 hidden md:flex shrink-0",children:t.jsx(Kn,{className:"h-4 w-4"})}),t.jsx("div",{className:"shrink-0",children:t.jsx(Ns,{})}),t.jsx("div",{className:"shrink-0",children:t.jsx(Cs,{})})]})]})}const Es=768,Ts=1024;function Ms(){const{setOpen:e,isMobile:a}=Zt();i.useEffect(()=>{function n(){const o=window.innerWidth;o>=Es&&o<Ts&&e(!1)}return n(),window.addEventListener("resize",n),()=>window.removeEventListener("resize",n)},[e,a])}function Rs({children:e}){return Ms(),t.jsx(t.Fragment,{children:e})}function _s({children:e,activeAppName:a,activeApp:n,onAppChange:o,objects:s,connectionState:r}){return t.jsx(Ln,{sidebar:t.jsx(js,{activeAppName:a,onAppChange:o}),navbar:t.jsx(Fs,{appName:n?.label||a,objects:s,connectionState:r}),className:"p-0 overflow-hidden bg-muted/5",branding:n?.branding?{primaryColor:n.branding.primaryColor,accentColor:n.branding.accentColor,favicon:n.branding.favicon,logo:n.branding.logo,title:n.label?`${n.label} — ObjectStack Console`:void 0}:void 0,children:t.jsx(Rs,{children:e})})}function Ot(e){if(!e)return de;if(Z[e])return Z[e];const a=e.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("");return Z[a]?Z[a]:de}function Os({apps:e,activeApp:a,objects:n,onAppChange:o}){const[s,r]=i.useState(!1),c=Oe(),{appName:l}=ye(),{setTheme:d}=pt(),{evaluator:h}=ba(),{t:x}=oe();i.useEffect(()=>{const f=j=>{j.key==="k"&&(j.metaKey||j.ctrlKey)&&(j.preventDefault(),r(v=>!v))};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[]);const u=`/apps/${l||a?.name}`,g=i.useCallback(f=>{r(!1),f()},[]),b=Da(a?.navigation||[]).filter(f=>_e(f.visible??f.visibleOn,h));return t.jsxs(pn,{open:s,onOpenChange:r,children:[t.jsx(gn,{placeholder:x("console.commandPalette.placeholder")}),t.jsxs(xn,{children:[t.jsx(bn,{children:x("console.commandPalette.noResults")}),b.filter(f=>f.type==="object").length>0&&t.jsx(X,{heading:x("console.commandPalette.objects"),children:b.filter(f=>f.type==="object").map(f=>{const j=Ot(f.icon);return t.jsxs(J,{value:`object ${f.label} ${f.objectName}`,onSelect:()=>g(()=>c(`${u}/${f.objectName}`)),children:[t.jsx(j,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:f.label})]},f.id)})}),b.filter(f=>f.type==="dashboard").length>0&&t.jsx(X,{heading:x("console.commandPalette.dashboards"),children:b.filter(f=>f.type==="dashboard").map(f=>t.jsxs(J,{value:`dashboard ${f.label} ${f.dashboardName}`,onSelect:()=>g(()=>c(`${u}/dashboard/${f.dashboardName}`)),children:[t.jsx(ia,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:f.label})]},f.id))}),b.filter(f=>f.type==="page").length>0&&t.jsx(X,{heading:x("console.commandPalette.pages"),children:b.filter(f=>f.type==="page").map(f=>t.jsxs(J,{value:`page ${f.label} ${f.pageName}`,onSelect:()=>g(()=>c(`${u}/page/${f.pageName}`)),children:[t.jsx(Un,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:f.label})]},f.id))}),b.filter(f=>f.type==="report").length>0&&t.jsx(X,{heading:x("console.commandPalette.reports"),children:b.filter(f=>f.type==="report").map(f=>t.jsxs(J,{value:`report ${f.label} ${f.reportName}`,onSelect:()=>g(()=>c(`${u}/report/${f.reportName}`)),children:[t.jsx(la,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:f.label})]},f.id))}),e.filter(f=>f.active!==!1).length>1&&t.jsxs(t.Fragment,{children:[t.jsx(ze,{}),t.jsx(X,{heading:x("console.commandPalette.switchApp"),children:e.filter(f=>f.active!==!1).map(f=>{const j=Ot(f.icon);return t.jsxs(J,{value:`app ${f.label} ${f.name}`,onSelect:()=>g(()=>o(f.name)),children:[t.jsx(j,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:f.label}),f.name===a?.name&&t.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:x("console.commandPalette.current")})]},f.name)})})]}),t.jsx(ze,{}),t.jsxs(X,{heading:x("console.commandPalette.preferences"),children:[t.jsxs(J,{value:"theme light",onSelect:()=>g(()=>d("light")),children:[t.jsx(We,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:x("console.commandPalette.lightTheme")})]}),t.jsxs(J,{value:"theme dark",onSelect:()=>g(()=>d("dark")),children:[t.jsx(He,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:x("console.commandPalette.darkTheme")})]}),t.jsxs(J,{value:"theme system",onSelect:()=>g(()=>d("system")),children:[t.jsx(oa,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:x("console.commandPalette.systemTheme")})]})]}),t.jsx(ze,{}),t.jsx(X,{heading:x("console.commandPalette.actions"),children:t.jsxs(J,{value:"search all results full page",onSelect:()=>g(()=>c(`${u}/search`)),children:[t.jsx(Re,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:x("console.commandPalette.openFullSearch")})]})})]})]})}function Da(e){const a=[];for(const n of e)n.type==="group"&&n.children?a.push(...Da(n.children)):a.push(n);return a}function Ls({error:e,onReset:a}){const{t:n}=oe();return t.jsx("div",{className:"flex h-full items-center justify-center p-8",children:t.jsxs("div",{className:"max-w-md text-center",children:[t.jsxs(Le,{children:[t.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-destructive/10",children:t.jsx(ca,{className:"h-6 w-6 text-destructive"})}),t.jsx(Ae,{children:n("console.errors.somethingWentWrong")}),t.jsx(st,{className:"mb-4",children:e.message||n("console.errors.unexpectedError")}),t.jsxs("div",{className:"flex items-center justify-center gap-2",children:[t.jsxs($,{variant:"outline",size:"sm",onClick:a,className:"gap-2",children:[t.jsx(Bn,{className:"h-4 w-4"}),n("console.errors.tryAgain")]}),t.jsxs($,{variant:"ghost",size:"sm",onClick:()=>{window.location.href="/"},className:"gap-2",children:[t.jsx(Gn,{className:"h-4 w-4"}),n("console.errors.goHome")]})]})]}),!1]})})}class As extends i.Component{constructor(a){super(a),this.state={hasError:!1,error:null}}static getDerivedStateFromError(a){return{hasError:!0,error:a}}componentDidCatch(a,n){console.error("[ErrorBoundary] Caught error:",a,n),this.props.onError?.(a,n)}resetErrorBoundary=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError&&this.state.error?this.props.fallback?typeof this.props.fallback=="function"?this.props.fallback({error:this.state.error,reset:this.resetErrorBoundary}):this.props.fallback:t.jsx(Ls,{error:this.state.error,onReset:this.resetErrorBoundary}):this.props.children}}function re({message:e}){const{t:a}=oe(),[n,o]=i.useState(0),s=i.useMemo(()=>[a("console.loadingSteps.connecting"),a("console.loadingSteps.loadingConfig"),a("console.loadingSteps.preparingWorkspace")],[a]);return i.useEffect(()=>{if(e)return;const r=setInterval(()=>{o(c=>Math.min(c+1,s.length-1))},1200);return()=>clearInterval(r)},[e,s.length]),t.jsx("div",{className:"flex flex-col items-center justify-center h-screen bg-background",children:t.jsxs("div",{className:"flex flex-col items-center gap-6",children:[t.jsxs("div",{className:"relative",children:[t.jsx("div",{className:"absolute inset-0 bg-primary/20 rounded-2xl blur-xl animate-pulse"}),t.jsx("div",{className:"relative bg-linear-to-br from-primary to-primary/80 p-4 rounded-2xl shadow-lg",children:t.jsx(de,{className:"h-10 w-10 text-primary-foreground"})})]}),t.jsxs("div",{className:"text-center space-y-2",children:[t.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:a("console.title")}),t.jsx("p",{className:"text-sm text-muted-foreground",children:a("console.initializing")})]}),e?t.jsxs("div",{className:"flex items-center gap-3 px-4 py-2 bg-muted/50 rounded-full",children:[t.jsx(jn,{className:"h-4 w-4 text-primary"}),t.jsx("span",{className:"text-sm text-muted-foreground",children:e})]}):t.jsx("div",{className:"flex flex-col gap-2 w-64",children:s.map((r,c)=>t.jsxs("div",{className:"flex items-center gap-2.5 text-sm transition-opacity duration-300",style:{opacity:c<=n?1:.3},children:[c<n?t.jsx(mt,{className:"h-4 w-4 text-primary shrink-0"}):c===n?t.jsx(Me,{className:"h-4 w-4 text-primary shrink-0 animate-spin"}):t.jsx("div",{className:"h-4 w-4 rounded-full border border-muted-foreground/30 shrink-0"}),t.jsx("span",{className:c<=n?"text-foreground":"text-muted-foreground",children:r})]},r))})]})})}const Ps=q.lazy(()=>K(()=>import("./ChartImpl-2ivTljUi.js"),__vite__mapDeps([0,1,2,3,4]))),Is=q.lazy(()=>K(()=>import("./AdvancedChartImpl-DAS1mU9o.js"),__vite__mapDeps([5,1,2,3,4]))),$s=({schema:e})=>t.jsx(i.Suspense,{fallback:t.jsx(ve,{className:"w-full h-48 sm:h-64 md:h-80 lg:h-[400px]"}),children:t.jsx(Ps,{data:e.data,dataKey:e.dataKey,xAxisKey:e.xAxisKey,height:e.height,className:e.className,color:e.color})}),ie=({schema:e})=>{const a=q.useMemo(()=>{let n=e.series,o=e.xAxisKey,s=e.config;if(o||(e.index?o=e.index:e.category&&(o=e.category)),n||(e.categories?n=e.categories.map(r=>({dataKey:r})):e.value&&(n=[{dataKey:e.value}])),!s&&n){const r=e.colors||["hsl(var(--chart-1))","hsl(var(--chart-2))","hsl(var(--chart-3))"],c={};n.forEach((l,d)=>{c[l.dataKey]={label:l.dataKey,color:r[d%r.length]}}),s=c}return{chartType:e.chartType,data:e.data,config:s,xAxisKey:o,series:n,className:e.className}},[e]);return t.jsx(i.Suspense,{fallback:t.jsx(ve,{className:"w-full h-48 sm:h-64 md:h-80 lg:h-[400px]"}),children:t.jsx(Is,{chartType:a.chartType,data:a.data,config:a.config,xAxisKey:a.xAxisKey,series:a.series,className:a.className})})},gt=e=>{const{schema:a}=e,n=me(),o=e.dataSource||n.dataSource,s=ut(a.bind),[r,c]=i.useState([]),[l,d]=i.useState(!1);i.useEffect(()=>{let u=!0;const g=async()=>{if(!(!o||!a.objectName)){u&&d(!0);try{const b=await o.find(a.objectName,{$filter:a.filter});let f=[];Array.isArray(b)?f=b:b&&typeof b=="object"&&Array.isArray(b.records)&&(f=b.records),u&&c(f)}catch(b){console.error("[ObjectChart] Fetch error:",b)}finally{u&&d(!1)}}};return a.objectName&&!s&&!a.data&&g(),()=>{u=!1}},[a.objectName,o,s,a.data,a.filter]);const h=s||a.data||r||[],x={...a,data:h};return l&&h.length,t.jsx(ie,{...e,schema:x})};z.register("object-chart",gt,{namespace:"plugin-charts",label:"Object Chart",category:"view",inputs:[{name:"objectName",type:"string",label:"Object Name",required:!0},{name:"data",type:"array",label:"Data",description:"Optional static data"},{name:"filter",type:"array",label:"Filter"}]});z.register("bar-chart",$s,{namespace:"plugin-charts",label:"Bar Chart",category:"plugin",inputs:[{name:"data",type:"array",label:"Data",required:!0},{name:"dataKey",type:"string",label:"Data Key",defaultValue:"value"},{name:"xAxisKey",type:"string",label:"X-Axis Key",defaultValue:"name"},{name:"height",type:"number",label:"Height",defaultValue:400},{name:"color",type:"color",label:"Color",defaultValue:"#8884d8"}],defaultProps:{data:[{name:"Jan",value:400},{name:"Feb",value:300},{name:"Mar",value:600},{name:"Apr",value:800},{name:"May",value:500}],dataKey:"value",xAxisKey:"name",height:400,color:"#8884d8"}});z.register("chart",gt,{namespace:"view",category:"view",label:"Chart",inputs:[{name:"objectName",type:"string",label:"Object Name",required:!0},{name:"type",type:"string",label:"Chart Type"},{name:"categoryField",type:"string",label:"Category Field"},{name:"valueField",type:"string",label:"Value Field"}]});z.register("chart",ie,{namespace:"plugin-charts",label:"Chart",category:"plugin",inputs:[{name:"chartType",type:"enum",label:"Chart Type",enum:[{label:"Bar",value:"bar"},{label:"Line",value:"line"},{label:"Area",value:"area"},{label:"Pie",value:"pie"},{label:"Donut",value:"donut"},{label:"Radar",value:"radar"},{label:"Scatter",value:"scatter"}],defaultValue:"bar"},{name:"data",type:"code",label:"Data (JSON)",required:!0},{name:"config",type:"code",label:"Config (JSON)"},{name:"xAxisKey",type:"string",label:"X Axis Key",defaultValue:"name"},{name:"series",type:"code",label:"Series (JSON Array)",required:!0},{name:"className",type:"string",label:"CSS Class"}],defaultProps:{chartType:"bar",data:[{name:"Jan",sales:400,revenue:240},{name:"Feb",sales:300,revenue:139},{name:"Mar",sales:600,revenue:380},{name:"Apr",sales:800,revenue:430},{name:"May",sales:500,revenue:220}],config:{sales:{label:"Sales",color:"#8884d8"},revenue:{label:"Revenue",color:"#82ca9d"}},xAxisKey:"name",series:[{dataKey:"sales"},{dataKey:"revenue"}]}});z.register("chart:bar",ie,{namespace:"plugin-charts",label:"Bar Chart (Alias)",category:"plugin",defaultProps:{chartType:"bar"}});z.register("pie-chart",ie,{namespace:"plugin-charts",label:"Pie Chart",category:"plugin",defaultProps:{chartType:"pie"}});z.register("donut-chart",ie,{namespace:"plugin-charts",label:"Donut Chart",category:"plugin",defaultProps:{chartType:"donut"}});z.register("radar-chart",ie,{namespace:"plugin-charts",label:"Radar Chart",category:"plugin",defaultProps:{chartType:"radar"}});z.register("scatter-chart",ie,{namespace:"plugin-charts",label:"Scatter Chart",category:"plugin",defaultProps:{chartType:"scatter"}});const zs=({schema:e,dataSource:a,className:n,onRowClick:o,onCardClick:s,...r})=>{const[c,l]=i.useState([]),[d,h]=i.useState(null),[x,u]=i.useState(!1),[g,b]=i.useState(null),f=ut(e.bind);i.useEffect(()=>{let y=!0;return(async()=>{if(!(!a||!e.objectName))try{const m=await a.getObjectSchema(e.objectName);y&&h(m)}catch(m){console.warn("Failed to fetch object def",m)}})(),()=>{y=!1}},[e.objectName,a]),i.useEffect(()=>{let y=!0;const p=async()=>{if(!(!a||!e.objectName)){y&&u(!0);try{const m=await a.find(e.objectName,{options:{$top:100},$filter:e.filter});let D=[];Array.isArray(m)?D=m:m&&typeof m=="object"&&(Array.isArray(m.value)?D=m.value:Array.isArray(m.data)&&(D=m.data)),console.log(`[ObjectKanban] Extracted data (length: ${D.length})`),y&&l(D)}catch(m){console.error("[ObjectKanban] Fetch error:",m),y&&b(m)}finally{y&&u(!1)}}};return e.objectName&&!f&&!e.data&&!r.data&&p(),()=>{y=!1}},[e.objectName,a,f,e.data,e.filter,r.data]);const j=r.data||f||e.data||c,v=i.useMemo(()=>{if(!Array.isArray(j))return[];let y=e.cardTitle||e.titleField;if(!y&&d){if(d.titleFormat){const m=/\{(.+?)\}/.exec(d.titleFormat);m&&(y=m[1])}!y&&d.NAME_FIELD_KEY&&(y=d.NAME_FIELD_KEY)}const p=y||"name";return j.map(m=>({...m,id:m.id||m._id,title:m[p]||m.title||"Untitled"}))},[j,e,d]),C=i.useMemo(()=>{if(e.columns&&e.columns.length>0)if(typeof e.columns[0]=="string"){if(!e.groupBy)return e.columns.map(y=>({id:y,title:y}))}else return e.columns;if(e.groupBy&&d?.fields?.[e.groupBy]?.options)return d.fields[e.groupBy].options.map(y=>({id:y.value,title:y.label}));if(e.groupBy&&v.length>0){const y=new Set(v.map(p=>p[e.groupBy]));return Array.from(y).map(p=>({id:String(p),title:String(p)}))}return[]},[e.columns,e.groupBy,v,d]),E={...e,data:v,columns:C,className:n||e.className},_=Ne({navigation:e.navigation,objectName:e.objectName,onRowClick:o??s});if(g)return t.jsxs("div",{className:"p-4 border border-destructive/50 rounded bg-destructive/10 text-destructive",children:["Error loading kanban data: ",g.message]});const F=e.objectName?`${e.objectName.charAt(0).toUpperCase()+e.objectName.slice(1).replace(/_/g," ")} Detail`:"Card Details";return t.jsxs(t.Fragment,{children:[t.jsx(Ca,{schema:{...E,onCardClick:y=>{_.handleClick(y),s?.(y)}}}),_.isOverlay&&t.jsx(we,{..._,title:F,children:y=>t.jsx("div",{className:"space-y-3",children:Object.entries(y).map(([p,m])=>t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:p.replace(/_/g," ")}),t.jsx("span",{className:"text-sm",children:String(m??"—")})]},p))})})]})},Vs=q.lazy(()=>K(()=>import("./KanbanImpl-BsMtStI7.js"),__vite__mapDeps([6,1,7,8,9,3,10,11,4,2,12]))),Ks=q.lazy(()=>K(()=>import("./KanbanEnhanced-ZOndyXyg.js"),__vite__mapDeps([13,1,14,8,9,3,10,11,4,2,12,15,16,7]))),Ca=({schema:e})=>{const a=q.useMemo(()=>{const{columns:n=[],data:o,groupBy:s}=e;if(o&&s&&Array.isArray(o)){const r={};n.forEach(l=>{l.id&&(r[String(l.id).toLowerCase()]=l.id),l.title&&(r[String(l.title).toLowerCase()]=l.id)});const c=o.reduce((l,d)=>{const h=String(d[s]??""),x=r[h.toLowerCase()]??h;return l[x]||(l[x]=[]),l[x].push(d),l},{});return n.map(l=>({...l,cards:[...l.cards||[],...c[l.id]||[]]}))}return n},[e]);return t.jsx(i.Suspense,{fallback:t.jsx(ve,{className:"w-full h-[600px]"}),children:t.jsx(Vs,{columns:a,onCardMove:e.onCardMove,onCardClick:e.onCardClick,className:e.className})})};z.register("kanban-ui",Ca,{namespace:"plugin-kanban",label:"Kanban Board",icon:"LayoutDashboard",category:"plugin",inputs:[{name:"columns",type:"array",label:"Columns",description:"Array of { id, title, cards, limit, className }",required:!0},{name:"onCardMove",type:"code",label:"On Card Move",description:"Callback when a card is moved",advanced:!0},{name:"className",type:"string",label:"CSS Class"}],defaultProps:{columns:[{id:"todo",title:"To Do",cards:[{id:"card-1",title:"Task 1",description:"This is the first task",badges:[{label:"High Priority",variant:"destructive"},{label:"Feature",variant:"default"}]},{id:"card-2",title:"Task 2",description:"This is the second task",badges:[{label:"Bug",variant:"destructive"}]}]},{id:"in-progress",title:"In Progress",limit:3,cards:[{id:"card-3",title:"Task 3",description:"Currently working on this",badges:[{label:"In Progress",variant:"default"}]}]},{id:"done",title:"Done",cards:[{id:"card-4",title:"Task 4",description:"This task is completed",badges:[{label:"Completed",variant:"outline"}]},{id:"card-5",title:"Task 5",description:"Another completed task",badges:[{label:"Completed",variant:"outline"}]}]}],className:"w-full"}});z.register("kanban-enhanced",({schema:e})=>{const a=q.useMemo(()=>{const{columns:n=[],data:o,groupBy:s}=e;if(o&&s&&Array.isArray(o)){const r=o.reduce((c,l)=>{const d=l[s];return c[d]||(c[d]=[]),c[d].push(l),c},{});return n.map(c=>({...c,cards:[...c.cards||[],...r[c.id]||[]]}))}return n},[e]);return t.jsx(i.Suspense,{fallback:t.jsx(ve,{className:"w-full h-[600px]"}),children:t.jsx(Ks,{columns:a,onCardMove:e.onCardMove,onColumnToggle:e.onColumnToggle,enableVirtualScrolling:e.enableVirtualScrolling,virtualScrollThreshold:e.virtualScrollThreshold,className:e.className})})},{namespace:"plugin-kanban",label:"Kanban Board (Enhanced)",icon:"LayoutGrid",category:"plugin",inputs:[{name:"columns",type:"array",label:"Columns",required:!0},{name:"enableVirtualScrolling",type:"boolean",label:"Virtual Scrolling",defaultValue:!1},{name:"virtualScrollThreshold",type:"number",label:"Virtual Scroll Threshold",defaultValue:50},{name:"onCardMove",type:"code",label:"On Card Move",advanced:!0},{name:"onColumnToggle",type:"code",label:"On Column Toggle",advanced:!0},{name:"className",type:"string",label:"CSS Class"}],defaultProps:{columns:[],enableVirtualScrolling:!1,virtualScrollThreshold:50,className:"w-full"}});const Sa=({schema:e,...a})=>{const{dataSource:n}=me()||{};return t.jsx(zs,{schema:e,dataSource:n,...a})};z.register("object-kanban",Sa,{namespace:"plugin-kanban",label:"Object Kanban",category:"view",inputs:[{name:"objectName",type:"string",label:"Object Name",required:!0},{name:"columns",type:"array",label:"Columns"}]});z.register("kanban",Sa,{namespace:"view",label:"Kanban Board",category:"view",inputs:[{name:"objectName",type:"string",label:"Object Name",required:!0},{name:"columns",type:"array",label:"Columns"}]});const xt="bg-blue-500 text-white";function ka({events:e=[],view:a="month",currentDate:n=new Date,locale:o="default",onEventClick:s,onDateClick:r,onViewChange:c,onNavigate:l,onAddClick:d,onEventDrop:h,className:x}){const[u,g]=i.useState(a),[b,f]=i.useState(n);i.useEffect(()=>{f(n)},[n]),i.useEffect(()=>{g(a)},[a]);const j=i.useRef(c);j.current=c,i.useEffect(()=>{const N=window.matchMedia("(max-width: 639px)"),T=O=>{O.matches&&(g("day"),j.current?.("day"))};return T(N),N.addEventListener("change",T),()=>N.removeEventListener("change",T)},[]);const v=()=>{const N=new Date(b);u==="month"?N.setMonth(N.getMonth()-1):u==="week"?N.setDate(N.getDate()-7):N.setDate(N.getDate()-1),f(N),l?.(N)},C=()=>{const N=new Date(b);u==="month"?N.setMonth(N.getMonth()+1):u==="week"?N.setDate(N.getDate()+7):N.setDate(N.getDate()+1),f(N),l?.(N)},E=()=>{const N=new Date;f(N),l?.(N)},_=N=>{g(N),c?.(N)},F=()=>{if(u==="month")return b.toLocaleDateString(o,{month:"long",year:"numeric"});if(u==="week"){const N=Fa(b),T=new Date(N);return T.setDate(T.getDate()+6),`${N.toLocaleDateString(o,{month:"short",day:"numeric"})} - ${T.toLocaleDateString(o,{month:"short",day:"numeric",year:"numeric"})}`}else return b.toLocaleDateString(o,{weekday:"long",month:"long",day:"numeric",year:"numeric"})},y=i.useRef(0),p=N=>{y.current=N.touches[0].clientX},m=N=>{const T=y.current-N.changedTouches[0].clientX;if(Math.abs(T)>50){const O=new Date(b);u==="day"?O.setDate(O.getDate()+(T>0?1:-1)):u==="week"?O.setDate(O.getDate()+(T>0?7:-7)):O.setMonth(O.getMonth()+(T>0?1:-1)),f(O),l?.(O)}},D=N=>{N&&(f(N),l?.(N))};return t.jsxs("div",{role:"region","aria-label":"Calendar",className:P("flex flex-col h-full bg-background",x),children:[t.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsxs("div",{className:"flex items-center bg-muted/50 rounded-lg p-1 gap-1",children:[t.jsx($,{variant:"ghost",size:"sm",onClick:E,className:"h-8","aria-label":"Go to today",children:"Today"}),t.jsx("div",{className:"h-4 w-px bg-border mx-1"}),t.jsx($,{variant:"ghost",size:"icon","aria-label":"Previous period",onClick:v,className:"h-8 w-8",children:t.jsx(da,{className:"h-4 w-4"})}),t.jsx($,{variant:"ghost",size:"icon","aria-label":"Next period",onClick:C,className:"h-8 w-8",children:t.jsx(Pe,{className:"h-4 w-4"})})]}),t.jsxs(yn,{children:[t.jsx(vn,{asChild:!0,children:t.jsxs($,{variant:"ghost","aria-label":`Current date: ${F()}`,className:P("text-xl font-semibold h-auto px-3 py-1 hover:bg-muted/50 transition-colors","flex items-center gap-2"),children:[t.jsx(ua,{className:"h-5 w-5 text-muted-foreground"}),t.jsx("span",{children:F()})]})}),t.jsx(wn,{className:"w-auto p-0",align:"start",children:t.jsx(Nn,{mode:"single",selected:b,onSelect:D,initialFocus:!0,fromYear:2e3,toYear:2050})})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs(Xt,{value:u,onValueChange:_,children:[t.jsx(Qt,{className:"w-32 bg-background",children:t.jsx(ea,{})}),t.jsxs(ta,{children:[t.jsx(ee,{value:"day",children:"Day"}),t.jsx(ee,{value:"week",children:"Week"}),t.jsx(ee,{value:"month",children:"Month"})]})]}),d&&t.jsxs($,{onClick:d,size:"sm",className:"gap-1",children:[t.jsx(je,{className:"h-4 w-4"}),"New"]})]})]}),t.jsxs("div",{className:"flex-1 overflow-auto",onTouchStart:p,onTouchEnd:m,children:[u==="month"&&t.jsx(Bs,{date:b,events:e,onEventClick:s,onDateClick:r,onEventDrop:h}),u==="week"&&t.jsx(Gs,{date:b,events:e,locale:o,onEventClick:s,onDateClick:r}),u==="day"&&t.jsx(Ws,{date:b,events:e,onEventClick:s,onDateClick:r})]})]})}function Fa(e){const a=new Date(e),n=a.getDay(),o=a.getDate()-n;return a.setDate(o),a}function Us(e){const a=e.getFullYear(),n=e.getMonth(),o=new Date(a,n,1),s=new Date(a,n+1,0),r=o.getDay(),c=[];for(let d=r-1;d>=0;d--){const h=new Date(o.getTime());h.setDate(h.getDate()-(d+1)),c.push(h)}for(let d=1;d<=s.getDate();d++)c.push(new Date(a,n,d));const l=42-c.length;for(let d=1;d<=l;d++){const h=new Date(s.getTime());h.setDate(h.getDate()+d),c.push(h)}return c}function Ea(e,a){return e.getFullYear()===a.getFullYear()&&e.getMonth()===a.getMonth()&&e.getDate()===a.getDate()}function bt(e,a){return a.filter(n=>{const o=new Date(n.start),s=n.end?new Date(n.end):new Date(o),r=new Date(e);r.setHours(0,0,0,0);const c=new Date(e);c.setHours(23,59,59,999);const l=new Date(o);l.setHours(0,0,0,0);const d=new Date(s);return d.setHours(23,59,59,999),r<=d&&c>=l})}function Bs({date:e,events:a,onEventClick:n,onDateClick:o,onEventDrop:s}){const r=Us(e),c=new Date,l=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],[d,h]=i.useState(null),[x,u]=i.useState(null),g=(C,E)=>{h(E.id),C.dataTransfer.effectAllowed="move",C.dataTransfer.setData("text/plain",String(E.id))},b=()=>{h(null),u(null)},f=(C,E)=>{C.preventDefault(),C.dataTransfer.dropEffect="move",u(E)},j=C=>{C.currentTarget.contains(C.relatedTarget)||u(null)},v=(C,E)=>{if(C.preventDefault(),u(null),h(null),!s)return;const _=C.dataTransfer.getData("text/plain"),F=a.find(O=>String(O.id)===_);if(!F)return;const y=new Date(F.start),p=new Date(y);p.setHours(0,0,0,0);const m=new Date(E);m.setHours(0,0,0,0);const D=m.getTime()-p.getTime();if(D===0)return;const N=new Date(y.getTime()+D);let T;F.end&&(T=new Date(new Date(F.end).getTime()+D)),s(F,N,T)};return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx("div",{role:"row",className:"grid grid-cols-7 border-b",children:l.map(C=>t.jsx("div",{role:"columnheader",className:"p-2 text-center text-sm font-medium text-muted-foreground border-r last:border-r-0",children:C},C))}),t.jsx("div",{role:"grid","aria-label":"Calendar grid",className:"grid grid-cols-7 flex-1 auto-rows-fr",children:r.map((C,E)=>{const _=bt(C,a),F=C.getMonth()===e.getMonth(),y=Ea(C,c);return t.jsxs("div",{role:"gridcell","aria-label":`${C.toLocaleDateString("default",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}${_.length>0?`, ${_.length} event${_.length>1?"s":""}`:""}`,className:P("border-b border-r last:border-r-0 p-2 min-h-[100px] cursor-pointer hover:bg-accent/50",!F&&"bg-muted/30 text-muted-foreground",x===E&&"ring-2 ring-primary"),onClick:()=>o?.(C),onDragOver:p=>f(p,E),onDragLeave:j,onDrop:p=>v(p,C),children:[t.jsx("div",{className:P("text-sm font-medium mb-1",y&&"inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground h-6 w-6"),...y?{"aria-current":"date"}:{},children:C.getDate()}),t.jsxs("div",{className:"space-y-1",children:[_.slice(0,3).map(p=>t.jsx("div",{role:"button","aria-label":p.title,draggable:!!s,onDragStart:m=>g(m,p),onDragEnd:b,className:P("text-xs px-2 py-1 rounded truncate cursor-pointer hover:opacity-80",p.color||xt,d===p.id&&"opacity-50"),style:p.color&&p.color.startsWith("#")?{backgroundColor:p.color}:void 0,onClick:m=>{m.stopPropagation(),n?.(p)},children:p.title},p.id)),_.length>3&&t.jsxs("div",{className:"text-xs text-muted-foreground px-2",children:["+",_.length-3," more"]})]})]},E)})})]})}function Gs({date:e,events:a,locale:n="default",onEventClick:o,onDateClick:s}){const r=i.useRef(null),c=u=>{s&&(r.current=setTimeout(()=>{s(u)},500))},l=()=>{r.current&&(clearTimeout(r.current),r.current=null)},d=Fa(e),h=Array.from({length:7},(u,g)=>{const b=new Date(d);return b.setDate(b.getDate()+g),b}),x=new Date;return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx("div",{className:"grid grid-cols-7 border-b",children:h.map(u=>{const g=Ea(u,x);return t.jsxs("div",{className:"p-3 text-center border-r last:border-r-0",children:[t.jsx("div",{className:"text-sm font-medium text-muted-foreground",children:u.toLocaleDateString(n,{weekday:"short"})}),t.jsx("div",{className:P("text-lg font-semibold mt-1",g&&"inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground h-8 w-8"),children:u.getDate()})]},u.toISOString())})}),t.jsx("div",{role:"grid",className:"grid grid-cols-7 flex-1",children:h.map(u=>{const g=bt(u,a);return t.jsx("div",{role:"gridcell","aria-label":`${u.toLocaleDateString("default",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}${g.length>0?`, ${g.length} event${g.length>1?"s":""}`:""}`,className:"border-r last:border-r-0 p-2 min-h-[400px] cursor-pointer hover:bg-accent/50",onClick:()=>s?.(u),onTouchStart:()=>c(u),onTouchEnd:l,children:t.jsx("div",{className:"space-y-2",children:g.map(b=>t.jsxs("div",{role:"button","aria-label":b.title,className:P("text-xs sm:text-sm px-2 sm:px-3 py-1.5 sm:py-2 rounded cursor-pointer hover:opacity-80",b.color||xt),style:b.color&&b.color.startsWith("#")?{backgroundColor:b.color}:void 0,onClick:f=>{f.stopPropagation(),o?.(b)},children:[t.jsx("div",{className:"font-medium truncate",children:b.title}),!b.allDay&&t.jsx("div",{className:"text-xs opacity-90 mt-1",children:b.start.toLocaleTimeString("default",{hour:"numeric",minute:"2-digit"})})]},b.id))})},u.toISOString())})})]})}function Ws({date:e,events:a,onEventClick:n,onDateClick:o}){const s=bt(e,a),r=Array.from({length:24},(h,x)=>x),c=i.useRef(null),l=h=>{o&&(c.current=setTimeout(()=>{const x=new Date(e);x.setHours(h,0,0,0),o(x)},500))},d=()=>{c.current&&(clearTimeout(c.current),c.current=null)};return t.jsx("div",{className:"flex flex-col h-full",children:t.jsx("div",{role:"list",className:"flex-1 overflow-auto",children:r.map(h=>{const x=s.filter(u=>u.allDay?h===0:u.start.getHours()===h);return t.jsxs("div",{role:"listitem",className:"flex border-b min-h-[60px]",children:[t.jsx("div",{className:"w-20 p-2 text-sm text-muted-foreground border-r",children:h===0?"12 AM":h<12?`${h} AM`:h===12?"12 PM":`${h-12} PM`}),t.jsx("div",{className:"flex-1 p-2 space-y-2",onTouchStart:()=>l(h),onTouchEnd:d,children:x.map(u=>t.jsxs("div",{"aria-label":u.title,className:P("px-2 sm:px-3 py-1.5 sm:py-2 rounded cursor-pointer hover:opacity-80",u.color||xt),style:u.color&&u.color.startsWith("#")?{backgroundColor:u.color}:void 0,onClick:()=>n?.(u),children:[t.jsx("div",{className:"font-medium truncate",children:u.title}),!u.allDay&&t.jsxs("div",{className:"text-xs opacity-90 mt-1",children:[u.start.toLocaleTimeString("default",{hour:"numeric",minute:"2-digit"}),u.end&&` - ${u.end.toLocaleTimeString("default",{hour:"numeric",minute:"2-digit"})}`]})]},u.id))})]},h)})})})}function Hs(e){return"data"in e&&e.data?e.data:"staticData"in e&&e.staticData?{provider:"value",items:e.staticData}:e.objectName?{provider:"object",object:e.objectName}:null}function qs(e){if(e){if(typeof e=="string"){const a=e.split(" "),n=a[0],o=a[1]?.toLowerCase()==="desc"?"desc":"asc";return{[n]:o}}if(Array.isArray(e))return e.reduce((a,n)=>(n.field&&n.order&&(a[n.field]=n.order),a),{})}}function Js(e){return"filter"in e&&e.filter&&typeof e.filter=="object"&&"calendar"in e.filter?e.filter.calendar:e.calendar?e.calendar:e.startDateField||e.dateField?{startDateField:e.startDateField||e.dateField,endDateField:e.endDateField||e.endField,titleField:e.titleField||"name",colorField:e.colorField,allDayField:e.allDayField}:null}const Ys=({schema:e,dataSource:a,className:n,onEventClick:o,onRowClick:s,onDateClick:r,onNavigate:c,onViewChange:l,...d})=>{const[h,x]=i.useState([]),[u,g]=i.useState(!0),[b,f]=i.useState(null),[j,v]=i.useState(null),[C,E]=i.useState(new Date),[_,F]=i.useState("month"),[y,p]=i.useState(0),m=i.useCallback(async()=>{p(L=>L+1)},[]),{ref:D,isRefreshing:N,pullDistance:T}=fa({onRefresh:m,enabled:!!a&&!!e.objectName}),O=i.useMemo(()=>Hs(e),[e.data,e.staticData,e.objectName]),S=i.useMemo(()=>Js(e),[e.filter,e.calendar,e.dateField,e.endField,e.titleField,e.colorField]),w=O?.provider==="value";i.useEffect(()=>{let L=!0;return(async()=>{try{if(!L)return;if(g(!0),w&&O?.provider==="value"){L&&(x(O.items),g(!1));return}if(e.data||d.data){const U=e.data||d.data;if(Array.isArray(U)){x(U),g(!1);return}}if(!a)throw new Error("DataSource required for object/api providers");if(O?.provider==="object"){const U=O.object,I=await a.find(U,{$filter:e.filter,$orderby:qs(e.sort)});let B=[];Array.isArray(I)?B=I:I&&typeof I=="object"&&(Array.isArray(I.data)?B=I.data:Array.isArray(I.value)&&(B=I.value)),L&&x(B)}else O?.provider==="api"&&(console.warn("API provider not yet implemented for ObjectCalendar"),L&&x([]));L&&g(!1)}catch(U){console.error("[ObjectCalendar] Error fetching data:",U),L&&(f(U),g(!1))}})(),()=>{L=!1}},[O,a,w,e.filter,e.sort,y]),i.useEffect(()=>{!w&&a&&(async()=>{try{if(!a)return;const R=O?.provider==="object"?O.object:e.objectName;if(!R)return;const U=await a.getObjectSchema(R);v(U)}catch(R){console.error("Failed to fetch object schema:",R)}})()},[e.objectName,a,w,O]);const k=i.useMemo(()=>{if(!S||!h.length)return[];const{startDateField:L,endDateField:R,titleField:U,colorField:I}=S;return h.map((B,ce)=>{const jt=B[L],$e=R?B[R]:null,Ha=B[U]||"Untitled",qa=I?B[I]:void 0;return{id:B.id||B._id||`event-${ce}`,title:Ha,start:jt?new Date(jt):new Date,end:$e?new Date($e):void 0,color:qa,allDay:!$e,data:B}}).filter(B=>!isNaN(B.start.getTime()))},[h,S]),M=i.useCallback(()=>{r?.(new Date)},[r]),A=Ne({navigation:e.navigation,objectName:e.objectName,onRowClick:s});return u?t.jsx("div",{className:n,children:t.jsx("div",{className:"flex items-center justify-center h-96",children:t.jsx("div",{className:"text-muted-foreground",children:"Loading calendar..."})})}):b?t.jsx("div",{className:n,children:t.jsx("div",{className:"flex items-center justify-center h-96",children:t.jsxs("div",{className:"text-destructive",children:["Error: ",b.message]})})}):S?t.jsxs("div",{ref:D,className:n,children:[T>0&&t.jsx("div",{className:"flex items-center justify-center text-xs text-muted-foreground",style:{height:T},children:N?"Refreshing…":"Pull to refresh"}),t.jsx("div",{className:"border rounded-lg bg-background h-[calc(100vh-120px)] sm:h-[calc(100vh-160px)] md:h-[calc(100vh-200px)] min-h-[400px] sm:min-h-[600px]",children:t.jsx(ka,{events:k,currentDate:C,view:e.defaultView||"month",onEventClick:L=>{A.handleClick(L.data),o?.(L.data)},onDateClick:r,onNavigate:L=>{E(L),c?.(L)},onViewChange:L=>{F(L),l?.(L)},onAddClick:M})}),A.isOverlay&&t.jsx(we,{...A,title:"Event Details",children:L=>t.jsx("div",{className:"space-y-3",children:Object.entries(L).map(([R,U])=>t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:R.replace(/_/g," ")}),t.jsx("span",{className:"text-sm",children:String(U??"—")})]},R))})})]}):t.jsx("div",{className:n,children:t.jsx("div",{className:"flex items-center justify-center h-96",children:t.jsx("div",{className:"text-muted-foreground",children:"Calendar configuration required. Please specify startDateField and titleField."})})})};z.register("calendar-view",({schema:e,className:a,onAction:n,...o})=>{const s=q.useMemo(()=>!e.data||!Array.isArray(e.data)?[]:e.data.map((l,d)=>{const h=e.titleField||"title",x=e.startDateField||"start",u=e.endDateField||"end",g=e.colorField||"color",b=e.allDayField||"allDay";return{id:l._id||l.id||d,title:l[h]||"Untitled Event",start:new Date(l[x]),end:l[u]?new Date(l[u]):void 0,allDay:l[b],color:l[g],data:l}}),[e.data,e.titleField,e.startDateField,e.endDateField,e.colorField,e.allDayField]),r=l=>{e.onEventClick&&n?.({type:"event-click",payload:l})},c=()=>{n?.({type:"create",payload:{}})};return t.jsx(ka,{className:a,events:s,onEventClick:r,onAddClick:c,...o})},{namespace:"plugin-calendar",label:"Calendar View",inputs:[{name:"data",type:"array",label:"Data",description:"Array of record objects to display as events"},{name:"titleField",type:"string",label:"Title Field",defaultValue:"title",description:"Field name to use for event title"},{name:"startDateField",type:"string",label:"Start Date Field",defaultValue:"start",description:"Field name for event start date"},{name:"endDateField",type:"string",label:"End Date Field",defaultValue:"end",description:"Field name for event end date (optional)"},{name:"allDayField",type:"string",label:"All Day Field",defaultValue:"allDay",description:"Field name for all-day flag"},{name:"colorField",type:"string",label:"Color Field",defaultValue:"color",description:"Field name for event color"},{name:"colorMapping",type:"object",label:"Color Mapping",description:'Map field values to colors (e.g., {meeting: "blue", deadline: "red"})'},{name:"view",type:"enum",enum:["month","week","day"],defaultValue:"month",label:"View Mode",description:"Calendar view mode (month, week, or day)"},{name:"currentDate",type:"string",label:"Current Date",description:"ISO date string for initial calendar date"},{name:"allowCreate",type:"boolean",label:"Allow Create",defaultValue:!1,description:"Allow creating events by clicking on dates"},{name:"className",type:"string",label:"CSS Class"}],defaultProps:{view:"month",titleField:"title",startDateField:"start",endDateField:"end",allDayField:"allDay",colorField:"color",allowCreate:!1,data:[{id:1,title:"Team Meeting",start:new Date(new Date().setHours(10,0,0,0)).toISOString(),end:new Date(new Date().setHours(11,0,0,0)).toISOString(),color:"#3b82f6",allDay:!1},{id:2,title:"Project Deadline",start:new Date(new Date().setDate(new Date().getDate()+3)).toISOString(),color:"#ef4444",allDay:!0},{id:3,title:"Conference",start:new Date(new Date().setDate(new Date().getDate()+7)).toISOString(),end:new Date(new Date().setDate(new Date().getDate()+9)).toISOString(),color:"#10b981",allDay:!0}],className:"h-[600px] border rounded-lg"}});const Ta=({schema:e})=>{const{dataSource:a}=me();return t.jsx(Ys,{schema:e,dataSource:a})};z.register("object-calendar",Ta,{namespace:"plugin-calendar",label:"Object Calendar",category:"view",inputs:[{name:"objectName",type:"string",label:"Object Name",required:!0},{name:"calendar",type:"object",label:"Calendar Config",description:"startDateField, endDateField, titleField, colorField"}]});z.register("calendar",Ta,{namespace:"view",label:"Calendar View",category:"view",inputs:[{name:"objectName",type:"string",label:"Object Name",required:!0},{name:"calendar",type:"object",label:"Calendar Config",description:"startDateField, endDateField, titleField, colorField"}]});function Zs({open:e,onToggle:a,className:n}){return t.jsxs($,{size:"sm",variant:e?"secondary":"outline",onClick:a,className:`shadow-none gap-2 ${n||""}`,title:"Toggle Metadata Inspector",children:[t.jsx(Wn,{className:"h-4 w-4"}),t.jsx("span",{className:"hidden lg:inline",children:"Metadata"})]})}function Xs({sections:e,open:a}){if(!a)return null;const[n,o]=i.useState(["0"]),[s,r]=i.useState(null),c=async(d,h)=>{try{await navigator.clipboard.writeText(JSON.stringify(d,null,2)),r(h),setTimeout(()=>r(null),2e3)}catch(x){console.error("Failed to copy:",x)}},l=d=>{o(h=>h.includes(d)?h.filter(x=>x!==d):[...h,d])};return t.jsxs("div",{className:"w-80 border-l bg-background p-0 overflow-hidden flex flex-col shrink-0 z-20 transition-all",children:[t.jsxs("div",{className:"px-4 py-3 border-b bg-muted/5 flex items-center justify-between",children:[t.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Metadata Inspector"}),t.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:"JSON"})]}),t.jsx("div",{className:"flex-1 overflow-auto",children:e.map((d,h)=>{const x=String(h),u=n.includes(x),g=s===h;return t.jsxs("div",{className:"border-b last:border-b-0",children:[t.jsxs("div",{className:"flex items-center justify-between px-4 py-3 hover:bg-muted/5 transition-colors",children:[t.jsxs("button",{onClick:()=>l(x),className:"flex-1 flex items-center justify-between text-left",children:[t.jsx("h4",{className:"text-xs font-semibold text-foreground",children:d.title}),u?t.jsx(qe,{className:"h-3 w-3 text-muted-foreground ml-2"}):t.jsx(Pe,{className:"h-3 w-3 text-muted-foreground ml-2"})]}),t.jsx("button",{onClick:()=>c(d.data,h),className:"p-1 hover:bg-muted rounded transition-colors ml-2",title:"Copy JSON",children:g?t.jsx(Hn,{className:"h-3 w-3 text-green-600"}):t.jsx(qn,{className:"h-3 w-3 text-muted-foreground"})})]}),u&&t.jsx("div",{className:"px-4 pb-4",children:t.jsx("div",{className:"relative rounded-md border border-border/50 bg-muted/5 overflow-hidden",children:t.jsx("pre",{className:"text-[11px] leading-relaxed p-3 overflow-auto max-h-96 font-mono text-foreground/90",children:JSON.stringify(d.data,null,2)})})})]},h)})})]})}function Qs(){const[e,a]=i.useState(!1);return{showDebug:e,toggleDebug:()=>a(n=>!n)}}function er({objectName:e,objectLabel:a,dataSource:n,onEdit:o,onRefresh:s}){const r=Oe(),{appName:c}=ye(),l=`/apps/${c}`,{execute:d,loading:h,error:x,runner:u}=En({context:{objectName:e,objectLabel:a||e,baseUrl:l}});i.useEffect(()=>{u.registerHandler("create",async()=>(o?.(null),{success:!0})),u.registerHandler("delete",async v=>{const C=v.params?.recordId||v.recordId;if(!C)return{success:!1,error:"No record ID provided"};try{return await n.delete(e,C),s?.(),Ge.success(`${a||e} deleted successfully`),{success:!0,reload:!0}}catch(E){return Ge.error(`Failed to delete ${a||e}`,{description:E.message}),{success:!1,error:E.message}}}),u.registerHandler("navigate",async v=>{const C=v.params?.url||v.url;return C&&r(C.startsWith("/")?C:`${l}/${C}`),{success:!0}}),u.registerHandler("refresh",async()=>(s?.(),{success:!0,reload:!0}))},[u,e,n,o,s,r,l]);const g=i.useCallback(()=>{o?.(null)},[o]),b=i.useCallback(async v=>d({type:"delete",confirmText:"Are you sure you want to delete this record?",params:{recordId:v}}),[d]),f=i.useCallback(v=>{r(`${l}/${e}/view/${v}`)},[r,l,e]),j=i.useCallback(v=>{r(`${l}/${e}/record/${v}`)},[r,l,e]);return{execute:d,create:g,deleteRecord:b,navigateToView:f,navigateToRecord:j,loading:h,error:x}}function tr(e){const{url:a,channel:n,autoReconnect:o=!0,reconnectInterval:s=1e3,maxReconnectAttempts:r=10,authToken:c}=e,[l,d]=i.useState("disconnected"),[h,x]=i.useState(null),[u,g]=i.useState([]),[b,f]=i.useState(null),j=i.useRef(null),v=i.useRef(0),C=i.useRef(null),E=i.useRef(new Map),_=i.useRef([]),F=i.useRef(!0),y=i.useRef(!1),p=i.useCallback(()=>{C.current!==null&&(clearTimeout(C.current),C.current=null)},[]),m=i.useCallback(w=>{for(;_.current.length>0;){const k=_.current.shift(),M={type:k.type,channel:n,data:k.data,timestamp:new Date().toISOString()};w.send(JSON.stringify(M))}},[n]),D=i.useCallback(()=>{if(typeof WebSocket>"u"){f(new Error("WebSocket is not available in this environment")),d("error");return}if(!a){f(new Error("WebSocket URL is required")),d("error");return}try{const M=new URL(a);if(M.protocol!=="ws:"&&M.protocol!=="wss:"){f(new Error("WebSocket URL must use ws: or wss: protocol")),d("error");return}}catch{f(new Error("Invalid WebSocket URL")),d("error");return}j.current&&(y.current=!0,j.current.close(),j.current=null),y.current=!1,d("connecting"),f(null);const w=c?`${a}?token=${encodeURIComponent(c)}&channel=${encodeURIComponent(n)}`:`${a}?channel=${encodeURIComponent(n)}`;let k;try{k=new WebSocket(w)}catch(M){if(!F.current)return;const A=M instanceof Error?M:new Error("Failed to create WebSocket connection");f(A),d("error");return}j.current=k,k.onopen=()=>{F.current&&(d("connected"),f(null),v.current=0,m(k))},k.onmessage=M=>{if(F.current)try{const A=JSON.parse(String(M.data));if(A.channel!==n)return;x(A),g(R=>[...R,A]);const L=E.current.get(A.type);L&&L.forEach(R=>R(A.data))}catch{}},k.onerror=()=>{F.current&&(f(new Error("WebSocket connection error")),d("error"))},k.onclose=()=>{if(F.current){if(j.current=null,y.current){d("disconnected");return}if(o&&v.current<r){d("reconnecting");const M=Math.min(s*Math.pow(2,v.current),3e4);v.current+=1,C.current=setTimeout(()=>{F.current&&D()},M)}else d("disconnected")}}},[a,n,c,o,s,r,m]),N=i.useCallback(()=>{p(),y.current=!0,v.current=0,j.current&&(j.current.close(),j.current=null),d("disconnected")},[p]),T=i.useCallback(()=>{p(),v.current=0,D()},[D,p]),O=i.useCallback((w,k)=>{const M=j.current;if(M&&M.readyState===WebSocket.OPEN){const A={type:w,channel:n,data:k,timestamp:new Date().toISOString()};M.send(JSON.stringify(A))}else _.current.push({type:w,data:k})},[n]),S=i.useCallback((w,k)=>(E.current.has(w)||E.current.set(w,new Set),E.current.get(w).add(k),()=>{const M=E.current.get(w);M&&(M.delete(k),M.size===0&&E.current.delete(w))}),[]);return i.useEffect(()=>(F.current=!0,a&&D(),()=>{F.current=!1,p(),y.current=!0,j.current&&(j.current.close(),j.current=null)}),[a,n,c]),{connectionState:l,isConnected:l==="connected",lastMessage:h,messages:u,send:O,subscribe:S,disconnect:N,reconnect:T,error:b}}const ar={grid:Fe,kanban:ts,calendar:ua,gallery:es,timeline:Qn,gantt:Xn,map:Zn,chart:la};function Lt({dataSource:e,objects:a,onEdit:n,onRowClick:o}){const s=Oe(),{objectName:r,viewId:c}=ye(),[l,d]=qt(),{showDebug:h,toggleDebug:x}=Qs(),{t:u}=oe(),[g,b]=i.useState(!1),{can:f}=na(),j=a.find(S=>S.name===r);if(!j)return t.jsx("div",{className:"h-full p-4 flex items-center justify-center",children:t.jsxs(Le,{children:[t.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:t.jsx(Fe,{className:"h-6 w-6 text-muted-foreground"})}),t.jsx(Ae,{children:u("console.objectView.objectNotFound")}),t.jsxs(st,{children:[u("console.objectView.objectNotFoundDescription",{objectName:r})," ",u("console.objectView.objectNotFoundHint")]})]})});const v=i.useMemo(()=>{const S=j.listViews||j.list_views||{},w=Object.entries(S).map(([k,M])=>({id:k,...M,type:M.type||"grid"}));return w.length===0&&w.push({id:"all",label:u("console.objectView.allRecords"),type:"grid",columns:j.fields?Object.keys(j.fields).slice(0,5):[]}),w},[j]),C=c||l.get("view")||v[0]?.id,E=v.find(S=>S.id===C)||v[0],_=S=>{const w=v.find(k=>k.id===S);w&&(c?s(`../${w.id}`,{relative:"path"}):s(`view/${w.id}`))},[F,y]=i.useState(0),p=er({objectName:j.name,objectLabel:j.label,dataSource:e,onEdit:n,onRefresh:()=>y(S=>S+1)}),{lastMessage:m}=tr({channel:`object:${j.name}`});i.useEffect(()=>{m&&y(S=>S+1)},[m]);const D=l.get("recordId"),N=()=>{const S=new URLSearchParams(l);S.delete("recordId"),d(S)},T=i.useCallback(({schema:S,dataSource:w,onEdit:k,onRowClick:M,className:A})=>{const L=`${r}-${E.id}-${F}`,R=E;if(R.type==="chart"){const I=R.chart||{};return t.jsx(gt,{dataSource:w,schema:{type:"object-chart",objectName:j.name,chartType:I.chartType,xAxisField:I.xAxisField,yAxisFields:I.yAxisFields,aggregation:I.aggregation,series:I.series,config:I.config,filter:I.filter}},L)}const U={...S,options:{kanban:{groupBy:R.kanban?.groupByField||R.kanban?.groupField||"status",groupField:R.kanban?.groupByField||R.kanban?.groupField||"status",titleField:R.kanban?.titleField||j.titleField||"name",cardFields:R.kanban?.columns},calendar:{startDateField:R.calendar?.startDateField||"due_date",endDateField:R.calendar?.endDateField,titleField:R.calendar?.titleField||"name",colorField:R.calendar?.colorField,allDayField:R.calendar?.allDayField,defaultView:R.calendar?.defaultView},timeline:{dateField:R.timeline?.dateField||"due_date",titleField:R.timeline?.titleField||j.titleField||"name",descriptionField:R.timeline?.descriptionField},map:{locationField:R.map?.locationField,titleField:R.map?.titleField||j.titleField||"name",latitudeField:R.map?.latitudeField,longitudeField:R.map?.longitudeField,zoom:R.map?.zoom,center:R.map?.center},gallery:{imageField:R.gallery?.imageField||"image",titleField:R.gallery?.titleField||j.titleField||"name",subtitleField:R.gallery?.subtitleField},gantt:{startDateField:R.gantt?.startDateField||"start_date",endDateField:R.gantt?.endDateField||"end_date",titleField:R.gantt?.titleField||"name",progressField:R.gantt?.progressField,dependenciesField:R.gantt?.dependenciesField,colorField:R.gantt?.colorField},chart:{chartType:R.chart?.chartType,xAxisField:R.chart?.xAxisField,yAxisFields:R.chart?.yAxisFields,aggregation:R.chart?.aggregation,series:R.chart?.series,config:R.chart?.config}}};return t.jsx(ls,{schema:U,className:A,onEdit:k,onRowClick:M||(I=>k?.(I)),dataSource:w},L)},[E,j,r,F]),O=i.useMemo(()=>({type:"object-view",objectName:j.name,layout:"page",showSearch:!0,showFilters:!0,showCreate:!1,showRefresh:!0,onNavigate:(S,w)=>{w==="edit"&&n?.({_id:S,id:S})}}),[j.name,n]);return t.jsxs("div",{className:"h-full flex flex-col bg-background",children:[t.jsxs("div",{className:"flex justify-between items-center py-2.5 sm:py-3 px-3 sm:px-4 border-b shrink-0 bg-background z-10",children:[t.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 min-w-0 flex-1",children:[t.jsx("div",{className:"bg-primary/10 p-1.5 sm:p-2 rounded-md shrink-0",children:t.jsx(Fe,{className:"h-4 w-4 text-primary"})}),t.jsx("div",{className:"min-w-0",children:t.jsx("h1",{className:"text-base sm:text-lg font-semibold tracking-tight text-foreground truncate",children:j.label})})]}),t.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 shrink-0",children:[f(j.name,"create")&&t.jsxs($,{size:"sm",onClick:p.create,className:"shadow-none gap-1.5 sm:gap-2 h-8 sm:h-9",children:[t.jsx(je,{className:"h-4 w-4"}),t.jsx("span",{className:"hidden sm:inline",children:u("console.objectView.new")})]}),j.actions?.filter(S=>S.location==="list_toolbar").map(S=>t.jsx($,{size:"sm",variant:S.variant||"outline",className:"shadow-none h-8 sm:h-9",onClick:()=>p.execute(S),children:S.label||S.name},S.name||S.label)),t.jsxs(ae,{children:[t.jsx(ne,{asChild:!0,children:t.jsx($,{size:"sm",variant:g?"secondary":"ghost",className:"shadow-none h-8 sm:h-9 px-2",title:u("console.objectView.designTools"),children:g?t.jsx(Ft,{className:"h-4 w-4"}):t.jsx(Jn,{className:"h-4 w-4"})})}),t.jsxs(se,{align:"end",className:"w-48",children:[t.jsxs(G,{onClick:()=>b(!g),children:[t.jsx(Ft,{className:"h-4 w-4 mr-2"}),u(g?"console.objectView.exitDesignMode":"console.objectView.enterDesignMode")]}),g&&t.jsxs(t.Fragment,{children:[t.jsx(ke,{}),t.jsxs(G,{onClick:x,children:[t.jsx(Zs,{open:h,onToggle:x,className:"hidden"}),u("console.objectView.metadataInspector")]}),t.jsxs(G,{onClick:()=>s(c?`../../views/${c}`:`views/${C}`),children:[t.jsx(Yn,{className:"h-4 w-4 mr-2"}),u("console.objectView.editView")]}),t.jsxs(G,{onClick:()=>s(c?"../../views/new":"views/new"),children:[t.jsx(je,{className:"h-4 w-4 mr-2"}),u("console.objectView.addView")]})]})]})]})]})]}),v.length>1&&t.jsx("div",{className:"border-b px-3 sm:px-4 bg-background overflow-x-auto shrink-0",children:t.jsx("div",{className:"flex items-center gap-0.5 -mb-px",children:v.map(S=>{const w=S.id===C,k=ar[S.type]||Fe;return t.jsxs("button",{onClick:()=>_(S.id),className:P("inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium border-b-2 transition-colors whitespace-nowrap",w?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground hover:border-border"),children:[t.jsx(k,{className:"h-3.5 w-3.5"}),S.label]},S.id)})})}),t.jsxs("div",{className:"flex-1 overflow-hidden relative flex flex-row",children:[t.jsx("div",{className:"flex-1 relative h-full",children:t.jsx("div",{className:"absolute inset-0 overflow-auto p-3 sm:p-4",children:t.jsx(Sn,{schema:O,dataSource:e,views:v,activeViewId:C,onViewChange:_,onEdit:S=>n?.(S),onRowClick:o||(S=>n?.(S)),renderListView:T},F)})}),t.jsx(Xs,{open:h&&g,sections:[{title:"View Configuration",data:E},{title:"Object Definition",data:j}]})]}),t.jsx(Dn,{open:!!D,onOpenChange:S=>!S&&N(),children:t.jsx(Cn,{side:"right",className:"w-[90vw] sm:w-150 sm:max-w-none p-0 overflow-hidden",children:D&&t.jsx("div",{className:"h-full bg-background overflow-auto p-3 sm:p-4 lg:p-6",children:t.jsx(cs,{schema:{type:"detail-view",objectName:j.name,resourceId:D,showBack:!1,showEdit:!0,title:j.label,sections:[{title:"Details",fields:Object.keys(j.fields||{}).map(S=>({name:S,label:j.fields[S].label||S,type:j.fields[S].type||"text"})),columns:1}]},dataSource:e,onEdit:()=>n({_id:D,id:D})})})})})]})}function nr({children:e,authUrl:a}){const[n,o]=i.useState(null),[s,r]=i.useState(void 0),[c,l]=i.useState(!0);return i.useEffect(()=>{let d=!1;async function h(){try{const x=new sa({baseUrl:"",autoReconnect:!1});await x.connect();const u=await x.getDiscovery();if(!d)if(u?.mode==="preview")r({autoLogin:u.previewMode?.autoLogin??!0,simulatedRole:u.previewMode?.simulatedRole??"admin",simulatedUserName:u.previewMode?.simulatedUserName??"Preview User",readOnly:u.previewMode?.readOnly??!1,expiresInSeconds:u.previewMode?.expiresInSeconds??0,bannerMessage:u.previewMode?.bannerMessage}),o(!1);else{const g=u?.services?.auth?.enabled??!0;o(g)}}catch(x){d||(console.warn("[ConditionalAuthWrapper] Failed to fetch discovery, defaulting to auth enabled:",x),o(!0))}finally{d||l(!1)}}return h(),()=>{d=!0}},[]),c?t.jsx(re,{}):s?t.jsx(Ve,{authUrl:a,previewMode:s,children:e}):n?t.jsx(Ve,{authUrl:a,children:e}):t.jsx(Ve,{authUrl:a,enabled:!1,children:e})}function sr(){const{t:e}=oe(),[a,n]=i.useState(!1),o=i.useMemo(()=>[{title:e("console.shortcuts.groups.general"),shortcuts:[{keys:["⌘","K"],description:e("console.shortcuts.openCommandPalette")},{keys:["?"],description:e("console.shortcuts.showShortcuts")},{keys:["Esc"],description:e("console.shortcuts.closeDialog")}]},{title:e("console.shortcuts.groups.navigation"),shortcuts:[{keys:["B"],description:e("console.shortcuts.toggleSidebar")},{keys:["⌘","/"],description:e("console.shortcuts.focusSearch")}]},{title:e("console.shortcuts.groups.dataViews"),shortcuts:[{keys:["N"],description:e("console.shortcuts.createRecord")},{keys:["R"],description:e("console.shortcuts.refreshData")},{keys:["⌘","E"],description:e("console.shortcuts.editRecord")}]},{title:e("console.shortcuts.groups.preferences"),shortcuts:[{keys:["⌘","D"],description:e("console.shortcuts.toggleDarkMode")}]}],[e]);return i.useEffect(()=>{function s(r){const c=r.target;c.tagName==="INPUT"||c.tagName==="TEXTAREA"||c.isContentEditable||r.key==="?"&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&(r.preventDefault(),n(l=>!l))}return document.addEventListener("keydown",s),()=>document.removeEventListener("keydown",s)},[]),t.jsx(rt,{open:a,onOpenChange:n,children:t.jsxs(ot,{className:"sm:max-w-lg max-h-[80vh] overflow-y-auto",children:[t.jsxs(it,{children:[t.jsx(lt,{children:e("console.shortcuts.title")}),t.jsx(ct,{children:e("console.shortcuts.description")})]}),t.jsx("div",{className:"space-y-6 pt-2",children:o.map(s=>t.jsxs("div",{children:[t.jsx("h3",{className:"text-sm font-medium text-muted-foreground mb-3",children:s.title}),t.jsx("div",{className:"space-y-2",children:s.shortcuts.map((r,c)=>t.jsxs("div",{className:"flex items-center justify-between py-1.5",children:[t.jsx("span",{className:"text-sm",children:r.description}),t.jsx("div",{className:"flex items-center gap-1",children:r.keys.map((l,d)=>t.jsx("kbd",{className:"inline-flex h-6 min-w-[24px] items-center justify-center rounded border bg-muted px-1.5 text-xs font-medium text-muted-foreground",children:l},d))})]},c))})]},s.title))})]})})}const At="objectui-onboarding-dismissed",Ce=[{icon:ia,title:"Navigate Your Apps",description:"Use the sidebar to browse objects, dashboards, pages, and reports. Switch between apps using the dropdown in the sidebar header."},{icon:Re,title:"Quick Search",description:"Press ⌘K (or Ctrl+K) to open the command palette and quickly jump to any object, dashboard, or page."},{icon:ra,title:"Favorites & Recent",description:"Star frequently used items to pin them in the sidebar. Recently visited items also appear for quick access."},{icon:ma,title:"Keyboard Shortcuts",description:"Press ? to view all keyboard shortcuts. Use them to speed up your workflow with CRUD operations and navigation."}];function rr(){const[e,a]=i.useState(!1),[n,o]=i.useState(0);i.useEffect(()=>{try{if(!localStorage.getItem(At)){const x=setTimeout(()=>a(!0),800);return()=>clearTimeout(x)}}catch{}},[]);const s=()=>{a(!1);try{localStorage.setItem(At,new Date().toISOString())}catch{}},r=()=>{n<Ce.length-1?o(h=>h+1):s()},c=Ce[n],l=c.icon,d=n===Ce.length-1;return t.jsx(rt,{open:e,onOpenChange:h=>{h||s()},children:t.jsxs(ot,{className:"sm:max-w-md",children:[t.jsxs(it,{children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs(lt,{className:"flex items-center gap-2",children:[t.jsx(ma,{className:"h-5 w-5 text-primary"}),"Welcome to ObjectUI"]}),t.jsxs($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:s,children:[t.jsx(as,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Close"})]})]}),t.jsx(ct,{children:"Let's get you started with a quick tour."})]}),t.jsxs("div",{className:"flex flex-col items-center gap-4 py-6 text-center",children:[t.jsx("div",{className:"flex h-16 w-16 items-center justify-center rounded-full bg-primary/10",children:t.jsx(l,{className:"h-8 w-8 text-primary"})}),t.jsxs("div",{className:"space-y-2",children:[t.jsx("h3",{className:"text-lg font-semibold",children:c.title}),t.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:c.description})]})]}),t.jsx("div",{className:"flex items-center justify-center gap-1.5",children:Ce.map((h,x)=>t.jsx("button",{className:`h-2 w-2 rounded-full transition-colors ${x===n?"bg-primary":"bg-muted-foreground/30"}`,onClick:()=>o(x),"aria-label":`Go to step ${x+1}`},x))}),t.jsxs("div",{className:"flex items-center justify-between pt-2",children:[t.jsx($,{variant:"ghost",size:"sm",onClick:s,children:"Skip"}),t.jsxs($,{size:"sm",onClick:r,children:[d?"Get Started":"Next",!d&&t.jsx(ns,{className:"ml-1 h-4 w-4"})]})]})]})})}function or(e){const{theme:a="system"}=pt();return t.jsx(Mn,{theme:a,className:"toaster group",icons:{success:t.jsx(mt,{className:"h-4 w-4"}),info:t.jsx(rs,{className:"h-4 w-4"}),warning:t.jsx(ca,{className:"h-4 w-4"}),error:t.jsx(ss,{className:"h-4 w-4"}),loading:t.jsx(Me,{className:"h-4 w-4 animate-spin"})},toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...e})}const ir=i.lazy(()=>K(()=>import("./RecordDetailView-Sm8_iQw_.js"),__vite__mapDeps([17,1,15,9,8,3,10,11,4,2,12,16,14,18,19,20,21,22])).then(e=>({default:e.RecordDetailView}))),lr=i.lazy(()=>K(()=>import("./DashboardView-DSh9LYBb.js"),__vite__mapDeps([23,1,15,9,8,3,10,11,4,2,12,16,14,18,19,20,21,22])).then(e=>({default:e.DashboardView}))),cr=i.lazy(()=>K(()=>import("./PageView-bHvRhycc.js"),__vite__mapDeps([24,1,9,8,3,10,11,4,2,12,14,15,16,18,19,20,21,22])).then(e=>({default:e.PageView}))),dr=i.lazy(()=>K(()=>import("./ReportView-B0D9jx4v.js"),__vite__mapDeps([25,1,15,9,8,3,10,11,4,2,12,16,14,18,19,20,21,22])).then(e=>({default:e.ReportView}))),Pt=i.lazy(()=>K(()=>import("./ViewDesignerPage-TCaXYb43.js"),__vite__mapDeps([26,1,9,3,10])).then(e=>({default:e.ViewDesignerPage}))),ur=i.lazy(()=>K(()=>import("./SearchResultsPage-wlC0eLLr.js"),__vite__mapDeps([27,1,8,9,3,10,11,4,2,12,14,15,16,18,19,20,21,22])).then(e=>({default:e.SearchResultsPage}))),mr=i.lazy(()=>K(()=>import("./LoginPage-2CoFvwsL.js"),__vite__mapDeps([28,1,18,4])).then(e=>({default:e.LoginPage}))),fr=i.lazy(()=>K(()=>import("./RegisterPage-B9itUVYp.js"),__vite__mapDeps([29,1,18,4])).then(e=>({default:e.RegisterPage}))),hr=i.lazy(()=>K(()=>import("./ForgotPasswordPage-DUfjj-wh.js"),__vite__mapDeps([30,1,18,4])).then(e=>({default:e.ForgotPasswordPage}))),pr=i.lazy(()=>K(()=>import("./UserManagementPage-DOH6ql6-.js"),__vite__mapDeps([31,1,18,4,8,9,3,10,11,2,12,32])).then(e=>({default:e.UserManagementPage}))),gr=i.lazy(()=>K(()=>import("./OrgManagementPage-BJt5Iiun.js"),__vite__mapDeps([33,1,18,4,8,9,3,10,11,2,12,32])).then(e=>({default:e.OrgManagementPage}))),xr=i.lazy(()=>K(()=>import("./RoleManagementPage-BRqaeF_L.js"),__vite__mapDeps([34,1,18,4,8,9,3,10,11,2,12,32])).then(e=>({default:e.RoleManagementPage}))),br=i.lazy(()=>K(()=>import("./AuditLogPage-CyY7VZJW.js"),__vite__mapDeps([35,1,8,9,3,10,11,4,2,12,32])).then(e=>({default:e.AuditLogPage}))),jr=i.lazy(()=>K(()=>import("./ProfilePage-MVUfKMrp.js"),__vite__mapDeps([36,1,18,4,8,9,3,10,11,2,12])).then(e=>({default:e.ProfilePage})));function It({children:e}){return t.jsx(hs,{children:t.jsx(yr,{children:e})})}function yr({children:e}){const a=ga();return a?t.jsx(fs,{adapter:a,children:e}):t.jsx(re,{})}function vr(){const[e,a]=i.useState("disconnected"),{user:n}=aa(),o=ga(),s=Oe(),r=at(),[,c]=qt(),{appName:l}=ye(),{apps:d,objects:h,loading:x}=ht(),u=d.filter(w=>w.active!==!1),g=d.find(w=>w.name===l)||u.find(w=>w.isDefault===!0)||u[0],[b,f]=i.useState(!1),[j,v]=i.useState(null),[C,E]=i.useState(0),{addRecentItem:_}=ya();i.useEffect(()=>{if(!o)return;const w=o.onConnectionStateChange(k=>{a(k.state),k.error&&console.error("[Console] Connection error:",k.error)});return a(o.getConnectionState()),w},[o]);let p=r.pathname.split("/").filter(w=>w)[2];(p==="view"||p==="record"||p==="page"||p==="dashboard")&&(p="");const m=h.find(w=>w.name===p);i.useEffect(()=>{if(!g)return;const w=r.pathname.split("/").filter(Boolean);let k=w[2];(k==="view"||k==="record"||k==="page"||k==="dashboard")&&(k="");const M=`/apps/${g.name}`,A=h;if(k){const L=A.find(R=>R.name===k);L&&_({id:`object:${L.name}`,label:L.label||L.name,href:`${M}/${L.name}`,type:"object"})}else w[2]==="dashboard"&&w[3]?_({id:`dashboard:${w[3]}`,label:w[3].replace(/[-_]/g," ").replace(/\b\w/g,L=>L.toUpperCase()),href:`${M}/dashboard/${w[3]}`,type:"dashboard"}):w[2]==="report"&&w[3]&&_({id:`report:${w[3]}`,label:w[3].replace(/[-_]/g," ").replace(/\b\w/g,L=>L.toUpperCase()),href:`${M}/report/${w[3]}`,type:"report"})},[r.pathname,_]);const D=w=>{v(w),f(!0)},N=w=>{const k=w._id||w.id;k&&c(M=>{const A=new URLSearchParams(M);return A.set("recordId",k),A})},T=w=>{s(`/apps/${w}`)},O=i.useMemo(()=>new dt({user:n?{name:n.name,email:n.email,role:n.role??"user"}:{},app:g||{},data:j||{}}),[n,g,j]);if(!o||x)return t.jsx(re,{});if(!g)return t.jsx("div",{className:"h-screen flex items-center justify-center",children:t.jsx(Le,{children:t.jsx(Ae,{children:"No Apps Configured"})})});const S=n?{name:n.name,email:n.email,role:n.role??"user"}:{name:"Anonymous",email:"",role:"guest"};return t.jsx(ps,{user:S,app:g,data:{},children:t.jsxs(_s,{activeAppName:g.name,activeApp:g,onAppChange:T,objects:h,connectionState:e,children:[t.jsx(Os,{apps:d,activeApp:g,objects:h,onAppChange:T}),t.jsx(sr,{}),t.jsx(rr,{}),t.jsxs(Tn,{dataSource:o||{},children:[t.jsx(As,{children:t.jsx(i.Suspense,{fallback:t.jsx(re,{}),children:t.jsxs(Jt,{children:[t.jsx(V,{path:"/",element:t.jsx(nt,{to:Ma(g.navigation||[]),replace:!0})}),t.jsx(V,{path:":objectName",element:t.jsx(Lt,{dataSource:o,objects:h,onEdit:D,onRowClick:N})}),t.jsx(V,{path:":objectName/view/:viewId",element:t.jsx(Lt,{dataSource:o,objects:h,onEdit:D,onRowClick:N})}),t.jsx(V,{path:":objectName/record/:recordId",element:t.jsx(ir,{dataSource:o,objects:h,onEdit:D},C)}),t.jsx(V,{path:":objectName/views/new",element:t.jsx(Pt,{objects:h})}),t.jsx(V,{path:":objectName/views/:viewId",element:t.jsx(Pt,{objects:h})}),t.jsx(V,{path:"dashboard/:dashboardName",element:t.jsx(lr,{dataSource:o})}),t.jsx(V,{path:"report/:reportName",element:t.jsx(dr,{dataSource:o})}),t.jsx(V,{path:"page/:pageName",element:t.jsx(cr,{})}),t.jsx(V,{path:"search",element:t.jsx(ur,{})}),t.jsx(V,{path:"system/users",element:t.jsx(pr,{})}),t.jsx(V,{path:"system/organizations",element:t.jsx(gr,{})}),t.jsx(V,{path:"system/roles",element:t.jsx(xr,{})}),t.jsx(V,{path:"system/audit-log",element:t.jsx(br,{})}),t.jsx(V,{path:"system/profile",element:t.jsx(jr,{})})]})})}),t.jsx(rt,{open:b,onOpenChange:f,children:t.jsxs(ot,{className:"h-[100dvh] sm:h-auto sm:max-w-xl sm:max-h-[90vh] flex flex-col gap-0 p-0 overflow-hidden w-[100vw] sm:w-full rounded-none sm:rounded-lg",children:[t.jsxs(it,{className:"p-4 sm:p-6 pb-3 sm:pb-4 border-b",children:[t.jsx("div",{className:"mx-auto w-12 h-1.5 rounded-full bg-muted mb-2 sm:hidden"}),t.jsxs(lt,{className:"text-lg sm:text-xl",children:[j?"Edit":"Create"," ",m?.label]}),t.jsx(ct,{className:"text-sm",children:j?`Update details for ${m?.label}`:`Add a new ${m?.label} to your database.`})]}),t.jsx("div",{className:"flex-1 overflow-y-auto p-4 sm:p-6",children:m&&t.jsx(kn,{schema:{type:"object-form",objectName:m.name,mode:j?"edit":"create",recordId:j?.id,layout:"vertical",columns:1,fields:m.fields?Array.isArray(m.fields)?m.fields.filter(w=>typeof w=="string"?!0:_e(w.visible,O)).map(w=>typeof w=="string"?w:w.name):Object.entries(m.fields).filter(([w,k])=>_e(k.visible,O)).map(([w])=>w):[],onSuccess:()=>{f(!1),E(w=>w+1),Ge.success(j?`${m?.label} updated successfully`:`${m?.label} created successfully`)},onCancel:()=>f(!1),showSubmit:!0,showCancel:!0,submitText:"Save Record",cancelText:"Cancel"},dataSource:o},j?.id||"new")})]})})]})]})})}function Ma(e){if(!e||e.length===0)return"";for(const a of e){if(a.type==="object")return`${a.objectName}`;if(a.type==="page")return a.pageName?`page/${a.pageName}`:"";if(a.type==="dashboard")return a.dashboardName?`dashboard/${a.dashboardName}`:"";if(a.type!=="url"&&a.type==="group"&&a.children){const n=Ma(a.children);if(n!=="")return n}}return""}function wr(){const{apps:e,loading:a,error:n}=ht(),o=e.filter(r=>r.active!==!1),s=o.find(r=>r.isDefault===!0)||o[0];return a?t.jsx(re,{}):s?t.jsx(nt,{to:`/apps/${s.name}`,replace:!0}):t.jsx("div",{className:"h-screen flex items-center justify-center",children:t.jsxs(Le,{children:[t.jsx(Ae,{children:n?"Failed to Load Configuration":"No Apps Configured"}),t.jsx(st,{children:n?n.message:"No applications have been registered. Check your ObjectStack configuration."})]})})}function Nr(){return t.jsxs(ws,{defaultTheme:"system",storageKey:"object-ui-theme",children:[t.jsx(or,{position:"bottom-right"}),t.jsxs(nr,{authUrl:"/api/auth",children:[t.jsx(Rn,{}),t.jsx(Ja,{basename:"/console/".replace(/\/$/,"")||"/",children:t.jsx(i.Suspense,{fallback:t.jsx(re,{}),children:t.jsxs(Jt,{children:[t.jsx(V,{path:"/login",element:t.jsx(mr,{})}),t.jsx(V,{path:"/register",element:t.jsx(fr,{})}),t.jsx(V,{path:"/forgot-password",element:t.jsx(hr,{})}),t.jsx(V,{path:"/apps/:appName/*",element:t.jsx(_n,{fallback:t.jsx(nt,{to:"/login"}),loadingFallback:t.jsx(re,{}),children:t.jsx(It,{children:t.jsx(vr,{})})})}),t.jsx(V,{path:"/",element:t.jsx(It,{children:t.jsx(wr,{})})})]})})})]})]})}function $t(){const e=typeof window<"u"?window.innerWidth:1024;return e<640?35:e<1024?50:60}function Dr({tasks:e,viewMode:a="month",startDate:n,endDate:o,onTaskClick:s,onViewChange:r,onAddClick:c,className:l}){const[d,h]=i.useState(new Date),[x,u]=i.useState(typeof window<"u"&&window.innerWidth<640?32:40),[g,b]=i.useState($t());i.useEffect(()=>{const p=()=>{u(window.innerWidth<640?32:40),b($t())};return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[]);const f=i.useMemo(()=>{let p=n?new Date(n):new Date,m=o?new Date(o):new Date;return!n&&e.length>0&&(p=new Date(Math.min(...e.map(D=>D.start.getTime()))),p.setDate(p.getDate()-7)),!o&&e.length>0&&(m=new Date(Math.max(...e.map(D=>D.end.getTime()))),m.setDate(m.getDate()+14)),p.setHours(0,0,0,0),m.setHours(23,59,59,999),{start:p,end:m}},[n,o,e]),j=i.useMemo(()=>{const p=[],m=new Date(f.start);for(;m<=f.end;)p.push({date:new Date(m),label:m.getDate().toString(),isWeekend:m.getDay()===0||m.getDay()===6}),m.setDate(m.getDate()+1);return p},[f]),v=300,C=i.useRef(null),E=i.useRef(null),_=i.useRef(null),F=p=>{C.current&&(C.current.scrollLeft=p.currentTarget.scrollLeft),E.current&&(E.current.scrollTop=p.currentTarget.scrollTop)},y=p=>{f.end.getTime()-f.start.getTime();const m=g,D=1e3*60*60*24,N=p.start.getTime()-f.start.getTime(),T=p.end.getTime()-p.start.getTime(),O=N/D*m,S=Math.max(T/D*m,m);return{left:O,width:S}};return t.jsxs("div",{className:P("flex flex-col h-full bg-background border rounded-lg overflow-hidden",l),children:[t.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 p-2 border-b bg-card",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs($,{variant:"outline",size:"sm",onClick:()=>c?.(),"aria-label":"Create new task",children:[t.jsx(je,{className:"h-4 w-4 mr-1 sm:mr-2"}),t.jsx("span",{className:"hidden sm:inline",children:"New Task"}),t.jsx("span",{className:"sm:hidden",children:"New"})]}),t.jsx("div",{className:"h-4 w-px bg-border mx-1 sm:mx-2"}),t.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:t.jsx(da,{className:"h-4 w-4"})}),t.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:t.jsx(Pe,{className:"h-4 w-4"})}),t.jsx("span",{className:"font-semibold text-xs sm:text-sm",children:f.start.toLocaleDateString(void 0,{month:"long",year:"numeric"})})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs(Xt,{value:a,onValueChange:p=>r?.(p),children:[t.jsx(Qt,{className:"w-[100px] sm:w-[120px] h-8",children:t.jsx(ea,{})}),t.jsxs(ta,{children:[t.jsx(ee,{value:"day",children:"Day View"}),t.jsx(ee,{value:"week",children:"Week View"}),t.jsx(ee,{value:"month",children:"Month View"}),t.jsx(ee,{value:"quarter",children:"Quarter View"})]})]}),t.jsxs("div",{className:"flex bg-muted rounded-md p-1",children:[t.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>b(p=>Math.max(15,p-10)),children:t.jsx(os,{className:"h-3 w-3"})}),t.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>b(p=>Math.min(120,p+10)),children:t.jsx(is,{className:"h-3 w-3"})})]})]})]}),t.jsxs("div",{className:"flex flex-col flex-1 overflow-hidden",children:[t.jsxs("div",{className:"flex border-b bg-muted/30 shrink-0 h-10 sm:h-[50px]",children:[t.jsxs("div",{className:"flex items-center font-medium text-xs text-muted-foreground px-2 sm:px-4 border-r bg-card z-20 shadow-sm",style:{width:v,minWidth:v},children:[t.jsx("div",{className:"flex-1",children:"Task Name"}),t.jsx("div",{className:"w-16 sm:w-20 text-right hidden sm:block",children:"Start"}),t.jsx("div",{className:"w-16 sm:w-20 text-right hidden sm:block",children:"End"})]}),t.jsx("div",{className:"flex-1 overflow-hidden",ref:C,children:t.jsx("div",{className:"flex h-full",style:{width:j.length*g},children:j.map((p,m)=>t.jsxs("div",{className:P("flex flex-col items-center justify-center border-r text-xs text-muted-foreground h-full",p.isWeekend&&"bg-muted/50"),style:{width:g,minWidth:g},children:[t.jsx("span",{className:"font-medium text-foreground",children:p.label}),t.jsx("span",{className:"text-[10px] opacity-70",children:p.date.toLocaleDateString(void 0,{weekday:"narrow"})})]},m))})})]}),t.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[t.jsx("div",{className:"overflow-hidden border-r bg-card z-10 shadow-sm",ref:E,style:{width:v,minWidth:v},children:e.map(p=>t.jsxs("div",{className:"flex items-center border-b px-2 sm:px-4 hover:bg-accent/50 cursor-pointer transition-colors touch-manipulation",style:{height:x},onClick:()=>s?.(p),children:[t.jsxs("div",{className:"flex-1 truncate font-medium text-xs sm:text-sm flex items-center gap-2",children:[t.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:p.color||"#3b82f6"}}),p.title]}),t.jsx("div",{className:"w-16 sm:w-20 text-right text-xs text-muted-foreground hidden sm:block",children:p.start.toLocaleDateString(void 0,{month:"numeric",day:"numeric"})}),t.jsx("div",{className:"w-16 sm:w-20 text-right text-xs text-muted-foreground hidden sm:block",children:p.end.toLocaleDateString(void 0,{month:"numeric",day:"numeric"})})]},p.id))}),t.jsx("div",{className:"flex-1 overflow-auto bg-background/50 relative [-webkit-overflow-scrolling:touch]",ref:_,onScroll:F,children:t.jsx("div",{style:{width:j.length*g},children:t.jsxs("div",{className:"relative",children:[t.jsx("div",{className:"absolute inset-0 flex pointer-events-none z-0",children:j.map((p,m)=>t.jsx("div",{className:P("border-r h-full",p.isWeekend&&"bg-muted/20"),style:{width:g,minWidth:g}},m))}),e.map(p=>{const m=y(p);return t.jsx("div",{className:"relative border-b hover:bg-black/5",style:{height:x},children:t.jsxs("div",{className:"absolute top-1 sm:top-2 h-[calc(100%-8px)] sm:h-[calc(100%-16px)] rounded-sm bg-primary border border-primary-foreground/20 shadow-sm cursor-pointer hover:brightness-110 flex items-center px-2 group",style:{left:m.left,width:m.width,backgroundColor:p.color||"#3b82f6"},onClick:()=>s?.(p),children:[p.progress>0&&t.jsx("div",{className:"absolute left-0 top-0 bottom-0 bg-black/20 rounded-l-sm",style:{width:`${p.progress}%`}}),t.jsxs("span",{className:"text-[10px] text-white font-medium truncate opacity-0 group-hover:opacity-100 transition-opacity",children:[Math.round(p.progress),"%"]})]})},p.id)}),t.jsx("div",{className:"absolute top-0 bottom-0 w-px bg-red-500 z-20 pointer-events-none",style:{left:(new Date().getTime()-f.start.getTime())/(1e3*60*60*24)*g},children:t.jsx("div",{className:"w-2 h-2 rounded-full bg-red-500 -ml-[3px]"})})]})})})]})]})]})}function Cr(e){return e.data?e.data:e.staticData?{provider:"value",items:e.staticData}:e.objectName?{provider:"object",object:e.objectName}:null}function Sr(e){if(e){if(typeof e=="string"){const a=e.split(" "),n=a[0],o=a[1]?.toLowerCase()==="desc"?"desc":"asc";return{[n]:o}}if(Array.isArray(e))return e.reduce((a,n)=>(n.field&&n.order&&(a[n.field]=n.order),a),{})}}function kr(e){let a=null;if(e.startDateField&&e.endDateField)return a={startDateField:e.startDateField,endDateField:e.endDateField,titleField:e.titleField||"name",progressField:e.progressField,dependenciesField:e.dependenciesField||e.dependencyField,colorField:e.colorField},a;if(e.gantt&&(a=e.gantt),a){const n=us.safeParse(a);return n.success||console.warn("[ObjectGantt] Invalid gantt configuration:",n.error.format()),a}return null}const Fr=({schema:e,dataSource:a,className:n,onTaskClick:o,onRowClick:s,...r})=>{const[c,l]=i.useState([]),[d,h]=i.useState(!0),[x,u]=i.useState(null),[g,b]=i.useState(null),f=Cr(e),j=i.useMemo(()=>f,[JSON.stringify(f)]),v=kr(e),C=j?.provider==="value";i.useEffect(()=>{(async()=>{try{if(h(!0),r.data&&Array.isArray(r.data)){l(r.data),h(!1);return}if(C&&j?.provider==="value"){l(j.items),h(!1);return}if(!a)throw new Error("DataSource required for object/api providers");if(j?.provider==="object"){const y=j.object,p=await a.find(y,{$filter:e.filter,$orderby:Sr(e.sort)});let m=[];Array.isArray(p)?m=p:p&&typeof p=="object"&&(Array.isArray(p.data)?m=p.data:Array.isArray(p.records)&&(m=p.records)),l(m)}else j?.provider==="api"&&(console.warn("API provider not yet implemented for ObjectGantt"),l([]));h(!1)}catch(y){u(y),h(!1)}})()},[j,a,C,e.filter,e.sort]),i.useEffect(()=>{!C&&a&&(async()=>{try{if(!a)return;const y=j?.provider==="object"?j.object:e.objectName;if(!y)return;const p=await a.getObjectSchema(y);b(p)}catch(y){console.error("Failed to fetch object schema:",y)}})()},[e.objectName,a,C,j]);const E=i.useMemo(()=>{if(!v||!c.length)return[];const{startDateField:F,endDateField:y,titleField:p,progressField:m,dependenciesField:D,colorField:N}=v;return c.map((T,O)=>{const S=T[F],w=T[y],k=T[p]||"Untitled Task",M=m?T[m]:0,A=D?T[D]:[],L=N?T[N]:void 0;return{id:T.id||T._id||`task-${O}`,title:k,start:S?new Date(S):new Date,end:w?new Date(w):new Date,progress:Math.min(100,Math.max(0,M||0)),dependencies:Array.isArray(A)?A:[],color:L,data:T}}).filter(T=>!isNaN(T.start.getTime())&&!isNaN(T.end.getTime()))},[c,v]),_=Ne({navigation:e.navigation,objectName:e.objectName,onRowClick:s});return d?t.jsx("div",{className:n,children:t.jsx("div",{className:"flex items-center justify-center h-96",children:t.jsx("div",{className:"text-muted-foreground",children:"Loading Gantt chart..."})})}):x?t.jsx("div",{className:n,children:t.jsx("div",{className:"flex items-center justify-center h-96",children:t.jsxs("div",{className:"text-destructive",children:["Error: ",x.message]})})}):v?t.jsxs("div",{className:n,children:[t.jsx("div",{className:"h-[calc(100vh-200px)] min-h-[600px]",children:t.jsx(Dr,{tasks:E,onTaskClick:F=>{_.handleClick(F.data),o?.(F.data)},onAddClick:()=>{}})}),_.isOverlay&&t.jsx(we,{..._,title:"Task Details",children:F=>t.jsx("div",{className:"space-y-3",children:Object.entries(F).map(([y,p])=>t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:y.replace(/_/g," ")}),t.jsx("span",{className:"text-sm",children:String(p??"—")})]},y))})})]}):t.jsx("div",{className:n,children:t.jsx("div",{className:"flex items-center justify-center h-96",children:t.jsx("div",{className:"text-muted-foreground",children:"Gantt configuration required. Please specify startDateField, endDateField, and titleField."})})})},Ra=({schema:e})=>{const{dataSource:a}=me();return t.jsx(Fr,{schema:e,dataSource:a})};z.register("object-gantt",Ra,{namespace:"plugin-gantt",label:"Object Gantt",category:"view",inputs:[{name:"objectName",type:"string",label:"Object Name",required:!0},{name:"gantt",type:"object",label:"Gantt Config",description:"startDateField, endDateField, titleField, progressField, percentageField, colorField, dependenciesField"}]});z.register("gantt",Ra,{namespace:"view",label:"Gantt View",category:"view",inputs:[{name:"objectName",type:"string",label:"Object Name",required:!0},{name:"gantt",type:"object",label:"Gantt Config",description:"startDateField, endDateField, titleField, progressField, percentageField, colorField, dependenciesField"}]});const Er=10080*60*1e3;function Tr(e){const a=e.flatMap(s=>(s.items||[]).flatMap(r=>[r.startDate,r.endDate])),n=Math.min(...a.map(s=>new Date(s).getTime())),o=Math.max(...a.map(s=>new Date(s).getTime()));return{minDate:new Date(n).toISOString().split("T")[0],maxDate:new Date(o).toISOString().split("T")[0]}}function Mr(e,a,n,o){const s=new Date(e).getTime(),r=new Date(a).getTime(),c=new Date(n).getTime(),d=new Date(o).getTime()-c,h=s-c,x=r-s;return{start:h/d*100,width:x/d*100}}function Se(e,a){const n=new Date(e);return a==="short"?n.toLocaleDateString():a==="long"?n.toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}):n.toISOString().split("T")[0]}const _a=({schema:e,className:a,...n})=>{const{variant:o="vertical",items:s=[],dateFormat:r="short",onItemClick:c}=e;if(o==="vertical")return t.jsx(Oa,{className:a,...n,children:s.map((l,d)=>t.jsxs(La,{className:P(l.className,c&&"cursor-pointer"),onClick:()=>c?.(l),children:[t.jsx(Je,{variant:l.variant||"default",children:l.icon&&t.jsx("span",{className:"text-xs",children:l.icon})}),t.jsxs(Aa,{children:[l.time&&t.jsx(Ze,{dateTime:l.time,children:Se(l.time,r)}),l.title&&t.jsx(Ye,{children:l.title}),l.description&&t.jsx(Xe,{className:"line-clamp-2 sm:line-clamp-none",children:l.description}),l.content&&Dt(l.content)]})]},d))});if(o==="horizontal")return t.jsx(Pa,{className:P("overflow-x-auto [-webkit-overflow-scrolling:touch]",a),...n,children:s.map((l,d)=>t.jsxs(Ia,{className:P(l.className,c&&"cursor-pointer"),onClick:()=>c?.(l),children:[t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx(Je,{variant:l.variant||"default",children:l.icon&&t.jsx("span",{className:"text-xs",children:l.icon})}),t.jsxs("div",{className:"mt-4 text-center",children:[l.time&&t.jsx(Ze,{dateTime:l.time,children:Se(l.time,r)}),l.title&&t.jsx(Ye,{children:l.title}),l.description&&t.jsx(Xe,{className:"text-center line-clamp-2 sm:line-clamp-none",children:l.description}),l.content&&Dt(l.content)]})]}),d<s.length-1&&t.jsx("div",{className:"absolute left-full w-16 border-t-2 border-gray-200 top-3"})]},d))});if(o==="gantt"){const l=Tr(s),d=e.minDate||l.minDate,h=e.maxDate||l.maxDate,x=e.timeScale||"month",g=(()=>{const b=[],f=new Date(d),j=new Date(h);if(x==="month"){const v=new Date(f);for(;v<=j;)b.push(v.toLocaleDateString("en-US",{month:"short",year:"numeric"})),v.setMonth(v.getMonth()+1)}else if(x==="week"){const v=new Date(f);for(;v<=j;)b.push(`Week ${Math.ceil((v.getTime()-f.getTime())/Er)+1}`),v.setDate(v.getDate()+7)}else if(x==="day"){const v=new Date(f);for(;v<=j;)b.push(v.toLocaleDateString("en-US",{month:"short",day:"numeric"})),v.setDate(v.getDate()+1)}return b})();return t.jsxs($a,{className:P("overflow-x-auto [-webkit-overflow-scrolling:touch]",a),...n,children:[t.jsxs(za,{children:[t.jsx(Qe,{className:"flex items-center px-2 sm:px-4 py-2 sm:py-3",children:t.jsx("span",{className:"font-semibold text-xs sm:text-sm",children:e.rowLabel||"Items"})}),t.jsx(et,{children:t.jsx("div",{className:"flex h-full",children:g.map((b,f)=>t.jsx("div",{className:"flex-1 px-1 sm:px-2 py-2 sm:py-3 border-r text-xs font-medium text-center",children:b},f))})})]}),t.jsx("div",{children:t.jsxs("div",{className:"flex",children:[t.jsx(Qe,{children:s.map((b,f)=>t.jsx(tt,{children:t.jsx(Va,{title:b.label,className:"truncate",children:b.label})},f))}),t.jsx(et,{className:"relative",children:s.map((b,f)=>t.jsx(tt,{className:"relative",children:(b.items||[]).map((j,v)=>{const C=Mr(j.startDate,j.endDate,d,h);return t.jsx(Ka,{start:C.start,width:C.width,variant:j.variant||"default",onClick:()=>c?.(j,b,f,v),title:`${j.title||""}
|
|
3
|
-
${Se(j.startDate,r)} - ${Se(j.endDate,r)}`,children:t.jsx(Ua,{children:j.title})},v)})},f))})]})})]})}return null};z.register("timeline",_a,{namespace:"plugin-timeline",label:"Timeline",category:"data-display",inputs:[{name:"variant",type:"enum",enum:["vertical","horizontal","gantt"],label:"Timeline Variant",defaultValue:"vertical"},{name:"items",type:"array",label:"Timeline Items",description:"For vertical/horizontal: Array of { time, title, description, variant, icon, content }. For gantt: Array of { label, items: [{ title, startDate, endDate, variant }] }"},{name:"dateFormat",type:"enum",enum:["short","long","iso"],label:"Date Format",defaultValue:"short"},{name:"timeScale",type:"enum",enum:["day","week","month"],label:"Time Scale (Gantt only)",defaultValue:"month"},{name:"rowLabel",type:"string",label:"Row Label (Gantt only)",defaultValue:"Items"},{name:"minDate",type:"string",label:"Min Date (Gantt only)",description:"Override auto-calculated min date (YYYY-MM-DD)"},{name:"maxDate",type:"string",label:"Max Date (Gantt only)",description:"Override auto-calculated max date (YYYY-MM-DD)"},{name:"className",type:"string",label:"CSS Class"}],defaultProps:{variant:"vertical",dateFormat:"short",items:[{time:"2024-01-15",title:"Project Started",description:"Kickoff meeting and initial planning",variant:"success",icon:"🚀"},{time:"2024-02-01",title:"First Milestone",description:"Completed initial design phase",variant:"info",icon:"🎨"},{time:"2024-03-15",title:"Beta Release",description:"Released beta version to testers",variant:"warning",icon:"⚡"},{time:"2024-04-01",title:"Launch",description:"Official product launch",variant:"success",icon:"🎉"}]},examples:{vertical:{variant:"vertical",dateFormat:"long",items:[{time:"2024-01-15",title:"Project Started",description:"Kickoff meeting and initial planning",variant:"success"},{time:"2024-02-01",title:"First Milestone",description:"Completed initial design phase",variant:"info"}]},horizontal:{variant:"horizontal",dateFormat:"short",items:[{time:"2024-01-01",title:"Q1",description:"First quarter",variant:"default"},{time:"2024-04-01",title:"Q2",description:"Second quarter",variant:"info"},{time:"2024-07-01",title:"Q3",description:"Third quarter",variant:"warning"},{time:"2024-10-01",title:"Q4",description:"Fourth quarter",variant:"success"}]},gantt:{variant:"gantt",dateFormat:"short",timeScale:"month",rowLabel:"Projects",items:[{label:"Backend Development",items:[{title:"API Design",startDate:"2024-01-01",endDate:"2024-01-31",variant:"success"},{title:"Implementation",startDate:"2024-02-01",endDate:"2024-03-31",variant:"info"}]},{label:"Frontend Development",items:[{title:"UI Design",startDate:"2024-01-15",endDate:"2024-02-15",variant:"warning"},{title:"Component Dev",startDate:"2024-02-15",endDate:"2024-04-15",variant:"default"}]},{label:"Testing",items:[{title:"QA Phase",startDate:"2024-03-01",endDate:"2024-04-30",variant:"danger"}]}]}}});const Rr=ft({title:W().optional(),date:W().optional(),description:W().optional(),variant:W().optional()}),_r=ft({mapping:Rr.optional(),objectName:W().optional(),titleField:W().optional(),dateField:W().optional(),descriptionField:W().optional()}),Or=({schema:e,dataSource:a,className:n,onRowClick:o,onItemClick:s,...r})=>{const[c,l]=i.useState([]),[d,h]=i.useState(!1),[x,u]=i.useState(null),[g,b]=i.useState(0);i.useEffect(()=>{const m=_r.safeParse(e);m.success||console.warn("[ObjectTimeline] Invalid timeline configuration:",m.error.format())},[e]);const f=ut(e.bind);i.useEffect(()=>{const m=async()=>{if(!(!a||!e.objectName)){h(!0);try{const D=await a.find(e.objectName,{options:{$top:100}});let N=D;D.records?N=D.records:D.data&&(N=D.data),Array.isArray(N)&&l(N)}catch(D){console.error(D),u(D)}finally{h(!1)}}};e.objectName&&!f&&!e.items&&!r.data&&m()},[e.objectName,a,f,e.items,r.data,g]);const j=r.data||f||c;let v=e.items;if(!v&&j&&Array.isArray(j)){const m=e.mapping?.title||e.titleField||"name",D=e.mapping?.date||e.dateField||"date",N=e.mapping?.description||e.descriptionField||"description",T=e.mapping?.variant||"variant";v=j.map(O=>({title:O[m],time:O[D],startDate:O[D],endDate:O[D],description:O[N],variant:O[T]||"default",_data:O}))}const C=i.useCallback(async()=>{b(m=>m+1)},[]),{ref:E,isRefreshing:_,pullDistance:F}=fa({onRefresh:C,enabled:!!e.objectName&&!!a}),y=Ne({navigation:e.navigation,objectName:e.objectName,onRowClick:o??s}),p={...e,items:v||[],className:n||e.className,onItemClick:m=>{const D=m._data||m;y.handleClick(D),s?.(D)}};return x?t.jsxs("div",{className:"p-4 text-red-500",children:["Error loading timeline: ",x.message]}):t.jsxs("div",{ref:E,className:"relative overflow-auto h-full",children:[F>0&&t.jsx("div",{className:"flex items-center justify-center text-xs text-muted-foreground",style:{height:F},children:_?"Refreshing…":"Pull to refresh"}),t.jsx(_a,{schema:p}),y.isOverlay&&t.jsx(we,{...y,title:"Timeline Item",children:m=>t.jsx("div",{className:"space-y-3",children:Object.entries(m).map(([D,N])=>t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:D.replace(/_/g," ")}),t.jsx("span",{className:"text-sm",children:String(N??"—")})]},D))})})]})},Oa=i.forwardRef(({className:e,...a},n)=>t.jsx("ol",{ref:n,className:P("relative border-l border-gray-200",e),...a}));Oa.displayName="Timeline";const La=i.forwardRef(({className:e,...a},n)=>t.jsx("li",{ref:n,className:P("mb-10 ml-6",e),...a}));La.displayName="TimelineItem";const Je=i.forwardRef(({className:e,variant:a="default",...n},o)=>{const s={default:"bg-gray-200 border-gray-300",success:"bg-green-200 border-green-500",warning:"bg-yellow-200 border-yellow-500",danger:"bg-red-200 border-red-500",info:"bg-blue-200 border-blue-500"};return t.jsx("div",{ref:o,className:P("absolute -left-3 w-6 h-6 rounded-full border-2 flex items-center justify-center",s[a],e),...n})});Je.displayName="TimelineMarker";const Aa=i.forwardRef(({className:e,...a},n)=>t.jsx("div",{ref:n,className:e,...a}));Aa.displayName="TimelineContent";const Ye=i.forwardRef(({className:e,...a},n)=>t.jsx("h3",{ref:n,className:P("font-semibold text-lg mb-1",e),...a}));Ye.displayName="TimelineTitle";const Ze=i.forwardRef(({className:e,...a},n)=>t.jsx("time",{ref:n,className:P("text-sm font-normal text-gray-500 mb-2 block",e),...a}));Ze.displayName="TimelineTime";const Xe=i.forwardRef(({className:e,...a},n)=>t.jsx("p",{ref:n,className:P("text-base text-gray-700",e),...a}));Xe.displayName="TimelineDescription";const Pa=i.forwardRef(({className:e,...a},n)=>t.jsx("div",{ref:n,className:P("relative flex overflow-x-auto py-8",e),...a}));Pa.displayName="TimelineHorizontal";const Ia=i.forwardRef(({className:e,...a},n)=>t.jsx("div",{ref:n,className:P("flex-shrink-0 w-64 relative",e),...a}));Ia.displayName="TimelineHorizontalItem";const $a=i.forwardRef(({className:e,...a},n)=>t.jsx("div",{ref:n,className:P("relative w-full border rounded-lg overflow-hidden",e),...a}));$a.displayName="TimelineGantt";const za=i.forwardRef(({className:e,...a},n)=>t.jsx("div",{ref:n,className:P("flex border-b bg-gray-50",e),...a}));za.displayName="TimelineGanttHeader";const Qe=i.forwardRef(({className:e,...a},n)=>t.jsx("div",{ref:n,className:P("w-48 border-r bg-white",e),...a}));Qe.displayName="TimelineGanttRowLabels";const et=i.forwardRef(({className:e,...a},n)=>t.jsx("div",{ref:n,className:P("flex-1 overflow-x-auto",e),...a}));et.displayName="TimelineGanttGrid";const tt=i.forwardRef(({className:e,...a},n)=>t.jsx("div",{ref:n,className:P("flex items-center border-b min-h-12",e),...a}));tt.displayName="TimelineGanttRow";const Va=i.forwardRef(({className:e,...a},n)=>t.jsx("div",{ref:n,className:P("px-4 py-2 font-medium text-sm truncate",e),...a}));Va.displayName="TimelineGanttLabel";const Ka=i.forwardRef(({className:e,start:a=0,width:n=100,variant:o="default",...s},r)=>{const c={default:"bg-blue-500 hover:bg-blue-600",success:"bg-green-500 hover:bg-green-600",warning:"bg-yellow-500 hover:bg-yellow-600",danger:"bg-red-500 hover:bg-red-600",info:"bg-purple-500 hover:bg-purple-600"};return t.jsx("div",{ref:r,className:P("absolute h-8 rounded-md transition-colors cursor-pointer",c[o],e),style:{left:`${a}%`,width:`${n}%`},...s})});Ka.displayName="TimelineGanttBar";const Ua=i.forwardRef(({className:e,...a},n)=>t.jsx("div",{ref:n,className:P("px-2 py-1 text-white text-xs font-medium truncate",e),...a}));Ua.displayName="TimelineGanttBarContent";const Ba=({schema:e,...a})=>{const{dataSource:n}=me();return t.jsx(Or,{schema:e,dataSource:n,...a})};z.register("object-timeline",Ba,{namespace:"plugin-timeline",label:"Object Timeline",category:"view",inputs:[{name:"objectName",type:"string",label:"Object Name",required:!0},{name:"variant",type:"enum",enum:["vertical","horizontal","gantt"],defaultValue:"vertical"}]});z.register("timeline",Ba,{namespace:"view",label:"Timeline View",category:"view",inputs:[{name:"objectName",type:"string",label:"Object Name",required:!0},{name:"variant",type:"enum",enum:["vertical","horizontal","gantt"],defaultValue:"vertical"}]});const Lr=i.createContext(null);function Ar(e,a){const n=Array.isArray(e)?e[0]:e?e.x:0,o=Array.isArray(e)?e[1]:e?e.y:0,s=Array.isArray(a)?a[0]:a?a.x:0,r=Array.isArray(a)?a[1]:a?a.y:0;return n===s&&o===r}function H(e,a){if(e===a)return!0;if(!e||!a)return!1;if(Array.isArray(e)){if(!Array.isArray(a)||e.length!==a.length)return!1;for(let n=0;n<e.length;n++)if(!H(e[n],a[n]))return!1;return!0}else if(Array.isArray(a))return!1;if(typeof e=="object"&&typeof a=="object"){const n=Object.keys(e),o=Object.keys(a);if(n.length!==o.length)return!1;for(const s of n)if(!a.hasOwnProperty(s)||!H(e[s],a[s]))return!1;return!0}return!1}function zt(e){return{longitude:e.center.lng,latitude:e.center.lat,zoom:e.zoom,pitch:e.pitch,bearing:e.bearing,padding:e.padding}}function Vt(e,a){const n=a.viewState||a,o={};if("longitude"in n&&"latitude"in n&&(n.longitude!==e.center.lng||n.latitude!==e.center.lat)){const s=e.center.constructor;o.center=new s(n.longitude,n.latitude)}return"zoom"in n&&n.zoom!==e.zoom&&(o.zoom=n.zoom),"bearing"in n&&n.bearing!==e.bearing&&(o.bearing=n.bearing),"pitch"in n&&n.pitch!==e.pitch&&(o.pitch=n.pitch),n.padding&&e.padding&&!H(n.padding,e.padding)&&(o.padding=n.padding),o}const Pr=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function Kt(e){if(!e)return null;if(typeof e=="string"||("toJS"in e&&(e=e.toJS()),!e.layers))return e;const a={};for(const o of e.layers)a[o.id]=o;const n=e.layers.map(o=>{let s=null;"interactive"in o&&(s=Object.assign({},o),delete s.interactive);const r=a[o.ref];if(r){s=s||Object.assign({},o),delete s.ref;for(const c of Pr)c in r&&(s[c]=r[c])}return s||o});return{...e,layers:n}}const Ut={version:8,sources:{},layers:[]},Bt={mousedown:"onMouseDown",mouseup:"onMouseUp",mouseover:"onMouseOver",mousemove:"onMouseMove",click:"onClick",dblclick:"onDblClick",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",mouseout:"onMouseOut",contextmenu:"onContextMenu",touchstart:"onTouchStart",touchend:"onTouchEnd",touchmove:"onTouchMove",touchcancel:"onTouchCancel"},Gt={movestart:"onMoveStart",move:"onMove",moveend:"onMoveEnd",dragstart:"onDragStart",drag:"onDrag",dragend:"onDragEnd",zoomstart:"onZoomStart",zoom:"onZoom",zoomend:"onZoomEnd",rotatestart:"onRotateStart",rotate:"onRotate",rotateend:"onRotateEnd",pitchstart:"onPitchStart",pitch:"onPitch",pitchend:"onPitchEnd"},Wt={wheel:"onWheel",boxzoomstart:"onBoxZoomStart",boxzoomend:"onBoxZoomEnd",boxzoomcancel:"onBoxZoomCancel",resize:"onResize",load:"onLoad",render:"onRender",idle:"onIdle",remove:"onRemove",data:"onData",styledata:"onStyleData",sourcedata:"onSourceData",error:"onError"},Ir=["minZoom","maxZoom","minPitch","maxPitch","maxBounds","projection","renderWorldCopies"],$r=["scrollZoom","boxZoom","dragRotate","dragPan","keyboard","doubleClickZoom","touchZoomRotate","touchPitch"];class ue{constructor(a,n,o){this._map=null,this._internalUpdate=!1,this._hoveredFeatures=null,this._propsedCameraUpdate=null,this._styleComponents={},this._onEvent=s=>{const r=this.props[Wt[s.type]];r?r(s):s.type==="error"&&console.error(s.error)},this._onCameraEvent=s=>{if(this._internalUpdate)return;s.viewState=this._propsedCameraUpdate||zt(this._map.transform);const r=this.props[Gt[s.type]];r&&r(s)},this._onCameraUpdate=s=>this._internalUpdate?s:(this._propsedCameraUpdate=zt(s),Vt(s,this.props)),this._onPointerEvent=s=>{(s.type==="mousemove"||s.type==="mouseout")&&this._updateHover(s);const r=this.props[Bt[s.type]];r&&(this.props.interactiveLayerIds&&s.type!=="mouseover"&&s.type!=="mouseout"&&(s.features=this._hoveredFeatures||this._queryRenderedFeatures(s.point)),r(s),delete s.features)},this._MapClass=a,this.props=n,this._initialize(o)}get map(){return this._map}setProps(a){const n=this.props;this.props=a;const o=this._updateSettings(a,n),s=this._updateSize(a),r=this._updateViewState(a);this._updateStyle(a,n),this._updateStyleComponents(a),this._updateHandlers(a,n),(o||s||r&&!this._map.isMoving())&&this.redraw()}static reuse(a,n){const o=ue.savedMaps.pop();if(!o)return null;const s=o.map,r=s.getContainer();for(n.className=r.className;r.childNodes.length>0;)n.appendChild(r.childNodes[0]);s._container=n;const c=s._resizeObserver;c&&(c.disconnect(),c.observe(n)),o.setProps({...a,styleDiffing:!1}),s.resize();const{initialViewState:l}=a;return l&&(l.bounds?s.fitBounds(l.bounds,{...l.fitBoundsOptions,duration:0}):o._updateViewState(l)),s.isStyleLoaded()?s.fire("load"):s.once("style.load",()=>s.fire("load")),s._update(),o}_initialize(a){const{props:n}=this,{mapStyle:o=Ut}=n,s={...n,...n.initialViewState,container:a,style:Kt(o)},r=s.initialViewState||s.viewState||s;if(Object.assign(s,{center:[r.longitude||0,r.latitude||0],zoom:r.zoom||0,pitch:r.pitch||0,bearing:r.bearing||0}),n.gl){const l=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=()=>(HTMLCanvasElement.prototype.getContext=l,n.gl)}const c=new this._MapClass(s);r.padding&&c.setPadding(r.padding),n.cursor&&(c.getCanvas().style.cursor=n.cursor),c.transformCameraUpdate=this._onCameraUpdate,c.on("style.load",()=>{this._styleComponents={light:c.getLight(),sky:c.getSky(),projection:c.getProjection?.(),terrain:c.getTerrain()},this._updateStyleComponents(this.props)}),c.on("sourcedata",()=>{this._updateStyleComponents(this.props)});for(const l in Bt)c.on(l,this._onPointerEvent);for(const l in Gt)c.on(l,this._onCameraEvent);for(const l in Wt)c.on(l,this._onEvent);this._map=c}recycle(){this.map.getContainer().querySelector("[mapboxgl-children]")?.remove(),ue.savedMaps.push(this)}destroy(){this._map.remove()}redraw(){const a=this._map;a.style&&(a._frame&&(a._frame.cancel(),a._frame=null),a._render())}_updateSize(a){const{viewState:n}=a;if(n){const o=this._map;if(n.width!==o.transform.width||n.height!==o.transform.height)return o.resize(),!0}return!1}_updateViewState(a){const n=this._map,o=n.transform;if(!n.isMoving()){const r=Vt(o,a);if(Object.keys(r).length>0)return this._internalUpdate=!0,n.jumpTo(r),this._internalUpdate=!1,!0}return!1}_updateSettings(a,n){const o=this._map;let s=!1;for(const r of Ir)r in a&&!H(a[r],n[r])&&(s=!0,o[`set${r[0].toUpperCase()}${r.slice(1)}`]?.call(o,a[r]));return s}_updateStyle(a,n){if(a.cursor!==n.cursor&&(this._map.getCanvas().style.cursor=a.cursor||""),a.mapStyle!==n.mapStyle){const{mapStyle:o=Ut,styleDiffing:s=!0}=a,r={diff:s};"localIdeographFontFamily"in a&&(r.localIdeographFontFamily=a.localIdeographFontFamily),this._map.setStyle(Kt(o),r)}}_updateStyleComponents({light:a,projection:n,sky:o,terrain:s}){const r=this._map,c=this._styleComponents;r.style._loaded&&(a&&!H(a,c.light)&&(c.light=a,r.setLight(a)),n&&!H(n,c.projection)&&n!==c.projection?.type&&(c.projection=typeof n=="string"?{type:n}:n,r.setProjection?.(c.projection)),o&&!H(o,c.sky)&&(c.sky=o,r.setSky(o)),s!==void 0&&!H(s,c.terrain)&&(!s||r.getSource(s.source))&&(c.terrain=s,r.setTerrain(s)))}_updateHandlers(a,n){const o=this._map;for(const s of $r){const r=a[s]??!0,c=n[s]??!0;H(r,c)||(r?o[s].enable(r):o[s].disable())}}_queryRenderedFeatures(a){const n=this._map,{interactiveLayerIds:o=[]}=this.props;try{return n.queryRenderedFeatures(a,{layers:o.filter(n.getLayer.bind(n))})}catch{return[]}}_updateHover(a){const{props:n}=this;if(n.interactiveLayerIds&&(n.onMouseMove||n.onMouseEnter||n.onMouseLeave)){const s=a.type,r=this._hoveredFeatures?.length>0,c=this._queryRenderedFeatures(a.point),l=c.length>0;!l&&r&&(a.type="mouseleave",this._onPointerEvent(a)),this._hoveredFeatures=c,l&&!r&&(a.type="mouseenter",this._onPointerEvent(a)),a.type=s}else this._hoveredFeatures=null}}ue.savedMaps=[];const zr=["setMaxBounds","setMinZoom","setMaxZoom","setMinPitch","setMaxPitch","setRenderWorldCopies","setProjection","setStyle","addSource","removeSource","addLayer","removeLayer","setLayerZoomRange","setFilter","setPaintProperty","setLayoutProperty","setLight","setTerrain","setFog","remove"];function Vr(e){if(!e)return null;const a=e.map,n={getMap:()=>a};for(const o of Kr(a))!(o in n)&&!zr.includes(o)&&(n[o]=a[o].bind(a));return n}function Kr(e){const a=new Set;let n=e;for(;n;){for(const o of Object.getOwnPropertyNames(n))o[0]!=="_"&&typeof e[o]=="function"&&o!=="fire"&&o!=="setEventedParent"&&a.add(o);n=Object.getPrototypeOf(n)}return Array.from(a)}const Ur=typeof document<"u"?i.useLayoutEffect:i.useEffect;function Br(e,a){const{RTLTextPlugin:n,maxParallelImageRequests:o,workerCount:s,workerUrl:r}=a;if(n&&e.getRTLTextPluginStatus&&e.getRTLTextPluginStatus()==="unavailable"){const{pluginUrl:c,lazy:l=!0}=typeof n=="string"?{pluginUrl:n}:n;e.setRTLTextPlugin(c,d=>{d&&console.error(d)},l)}o!==void 0&&e.setMaxParallelImageRequests(o),s!==void 0&&e.setWorkerCount(s),r!==void 0&&e.setWorkerUrl(r)}const Ie=i.createContext(null);function Gr(e,a){const n=i.useContext(Lr),[o,s]=i.useState(null),r=i.useRef(),{current:c}=i.useRef({mapLib:null,map:null});i.useEffect(()=>{const h=e.mapLib;let x=!0,u;return Promise.resolve(h||K(()=>import("./maplibre-gl-D2AsLM0J.js").then(g=>g.m),__vite__mapDeps([37,1]))).then(g=>{if(!x)return;if(!g)throw new Error("Invalid mapLib");const b="Map"in g?g:g.default;if(!b.Map)throw new Error("Invalid mapLib");Br(b,e),e.reuseMaps&&(u=ue.reuse(e,r.current)),u||(u=new ue(b.Map,e,r.current)),c.map=Vr(u),c.mapLib=b,s(u),n?.onMapMount(c.map,e.id)}).catch(g=>{const{onError:b}=e;b?b({type:"error",target:null,originalEvent:null,error:g}):console.error(g)}),()=>{x=!1,u&&(n?.onMapUnmount(e.id),e.reuseMaps?u.recycle():u.destroy())}},[]),Ur(()=>{o&&o.setProps(e)}),i.useImperativeHandle(a,()=>c.map,[o]);const l=i.useMemo(()=>({position:"relative",width:"100%",height:"100%",...e.style}),[e.style]),d={height:"100%"};return i.createElement("div",{id:e.id,ref:r,style:l},o&&i.createElement(Ie.Provider,{value:c},i.createElement("div",{"mapboxgl-children":"",style:d},e.children)))}const Wr=i.forwardRef(Gr),Hr=/box|flex|grid|column|lineHeight|fontWeight|opacity|order|tabSize|zIndex/;function Y(e,a){if(!e||!a)return;const n=e.style;for(const o in a){const s=a[o];Number.isFinite(s)&&!Hr.test(o)?n[o]=`${s}px`:n[o]=s}}function Ga(e,a){if(e===a)return null;const n=Ht(e),o=Ht(a),s=[];for(const r of o)n.has(r)||s.push(r);for(const r of n)o.has(r)||s.push(r);return s.length===0?null:s}function Ht(e){return new Set(e?e.trim().split(/\s+/):[])}const qr=i.memo(i.forwardRef((e,a)=>{const{map:n,mapLib:o}=i.useContext(Ie),s=i.useRef({props:e}),r=i.useMemo(()=>{let C=!1;i.Children.forEach(e.children,F=>{F&&(C=!0)});const E={...e,element:C?document.createElement("div"):void 0},_=new o.Marker(E);return _.setLngLat([e.longitude,e.latitude]),_.getElement().addEventListener("click",F=>{s.current.props.onClick?.({type:"click",target:_,originalEvent:F})}),_.on("dragstart",F=>{const y=F;y.lngLat=r.getLngLat(),s.current.props.onDragStart?.(y)}),_.on("drag",F=>{const y=F;y.lngLat=r.getLngLat(),s.current.props.onDrag?.(y)}),_.on("dragend",F=>{const y=F;y.lngLat=r.getLngLat(),s.current.props.onDragEnd?.(y)}),_},[]);i.useEffect(()=>(r.addTo(n.getMap()),()=>{r.remove()}),[]);const{longitude:c,latitude:l,offset:d,style:h,draggable:x=!1,popup:u=null,rotation:g=0,rotationAlignment:b="auto",pitchAlignment:f="auto"}=e;i.useEffect(()=>{Y(r.getElement(),h)},[h]),i.useImperativeHandle(a,()=>r,[]);const j=s.current.props;(r.getLngLat().lng!==c||r.getLngLat().lat!==l)&&r.setLngLat([c,l]),d&&!Ar(r.getOffset(),d)&&r.setOffset(d),r.isDraggable()!==x&&r.setDraggable(x),r.getRotation()!==g&&r.setRotation(g),r.getRotationAlignment()!==b&&r.setRotationAlignment(b),r.getPitchAlignment()!==f&&r.setPitchAlignment(f),r.getPopup()!==u&&r.setPopup(u);const v=Ga(j.className,e.className);if(v)for(const C of v)r.toggleClassName(C);return s.current.props=e,Yt.createPortal(e.children,r.getElement())})),Jr=i.memo(i.forwardRef((e,a)=>{const{map:n,mapLib:o}=i.useContext(Ie),s=i.useMemo(()=>document.createElement("div"),[]),r=i.useRef({props:e}),c=i.useMemo(()=>{const l={...e},d=new o.Popup(l);return d.setLngLat([e.longitude,e.latitude]),d.once("open",h=>{r.current.props.onOpen?.(h)}),d},[]);if(i.useEffect(()=>{const l=d=>{r.current.props.onClose?.(d)};return c.on("close",l),c.setDOMContent(s).addTo(n.getMap()),()=>{c.off("close",l),c.isOpen()&&c.remove()}},[]),i.useEffect(()=>{Y(c.getElement(),e.style)},[e.style]),i.useImperativeHandle(a,()=>c,[]),c.isOpen()){const l=r.current.props;(c.getLngLat().lng!==e.longitude||c.getLngLat().lat!==e.latitude)&&c.setLngLat([e.longitude,e.latitude]),e.offset&&!H(l.offset,e.offset)&&c.setOffset(e.offset),(l.anchor!==e.anchor||l.maxWidth!==e.maxWidth)&&(c.options.anchor=e.anchor,c.setMaxWidth(e.maxWidth));const d=Ga(l.className,e.className);if(d)for(const h of d)c.toggleClassName(h);r.current.props=e}return Yt.createPortal(e.children,s)}));function le(e,a,n,o){const s=i.useContext(Ie),r=i.useMemo(()=>e(s),[]);return i.useEffect(()=>{const c=a,l=null,d=typeof a=="function"?a:null,{map:h}=s;return h.hasControl(r)||(h.addControl(r,c?.position),l&&l(s)),()=>{d&&d(s),h.hasControl(r)&&h.removeControl(r)}},[]),r}function Yr(e){const a=le(({mapLib:n})=>new n.AttributionControl(e),{position:e.position});return i.useEffect(()=>{Y(a._container,e.style)},[e.style]),null}i.memo(Yr);function Zr(e){const a=le(({mapLib:n})=>new n.FullscreenControl({container:e.containerId&&document.getElementById(e.containerId)}),{position:e.position});return i.useEffect(()=>{Y(a._controlContainer,e.style)},[e.style]),null}i.memo(Zr);function Xr(e,a){const n=i.useRef({props:e}),o=le(({mapLib:s})=>{const r=new s.GeolocateControl(e),c=r._setupUI;return r._setupUI=()=>{r._container.hasChildNodes()||c()},r.on("geolocate",l=>{n.current.props.onGeolocate?.(l)}),r.on("error",l=>{n.current.props.onError?.(l)}),r.on("outofmaxbounds",l=>{n.current.props.onOutOfMaxBounds?.(l)}),r.on("trackuserlocationstart",l=>{n.current.props.onTrackUserLocationStart?.(l)}),r.on("trackuserlocationend",l=>{n.current.props.onTrackUserLocationEnd?.(l)}),r},{position:e.position});return n.current.props=e,i.useImperativeHandle(a,()=>o,[]),i.useEffect(()=>{Y(o._container,e.style)},[e.style]),null}i.memo(i.forwardRef(Xr));function Qr(e){const a=le(({mapLib:n})=>new n.NavigationControl(e),{position:e.position});return i.useEffect(()=>{Y(a._container,e.style)},[e.style]),null}const eo=i.memo(Qr);function to(e){const a=le(({mapLib:r})=>new r.ScaleControl(e),{position:e.position}),n=i.useRef(e),o=n.current;n.current=e;const{style:s}=e;return e.maxWidth!==void 0&&e.maxWidth!==o.maxWidth&&(a.options.maxWidth=e.maxWidth),e.unit!==void 0&&e.unit!==o.unit&&a.setUnit(e.unit),i.useEffect(()=>{Y(a._container,s)},[s]),null}i.memo(to);function ao(e){const a=le(({mapLib:n})=>new n.TerrainControl(e),{position:e.position});return i.useEffect(()=>{Y(a._container,e.style)},[e.style]),null}i.memo(ao);function no(e){const a=le(({mapLib:n})=>new n.LogoControl(e),{position:e.position});return i.useEffect(()=>{Y(a._container,e.style)},[e.style]),null}i.memo(no);const so=ft({latitudeField:W().optional(),longitudeField:W().optional(),locationField:W().optional(),titleField:W().optional(),descriptionField:W().optional(),zoom:Ke().optional(),center:ms([Ke(),Ke()]).optional()});function ro(e){return e.data?e.data:e.staticData?{provider:"value",items:e.staticData}:e.objectName?{provider:"object",object:e.objectName}:null}function oo(e){if(e){if(typeof e=="string"){const a=e.split(" "),n=a[0],o=a[1]?.toLowerCase()==="desc"?"desc":"asc";return{[n]:o}}if(Array.isArray(e))return e.reduce((a,n)=>(n.field&&n.order&&(a[n.field]=n.order),a),{})}}function io(e){if(e.locationField||e.latitudeField)return{locationField:e.locationField,latitudeField:e.latitudeField,longitudeField:e.longitudeField,titleField:e.titleField||"name",descriptionField:e.descriptionField,zoom:e.zoom,center:e.center};let a=null;if(e.filter&&typeof e.filter=="object"&&"map"in e.filter?a=e.filter.map:e.map&&(a=e.map),a){const n=so.safeParse(a);return n.success||console.warn("[ObjectMap] Invalid map configuration:",n.error.format()),a}return{latitudeField:"latitude",longitudeField:"longitude",locationField:"location",titleField:"name",descriptionField:"description",zoom:10,center:[0,0]}}function lo(e,a){if(a.latitudeField&&a.longitudeField){const n=e[a.latitudeField],o=e[a.longitudeField];if(typeof n=="number"&&typeof o=="number")return[n,o]}if(a.locationField){const n=e[a.locationField];if(typeof n=="object"&&n!==null){const o=n.lat||n.latitude,s=n.lng||n.lon||n.longitude;if(typeof o=="number"&&typeof s=="number")return[o,s]}if(typeof n=="string"){const o=n.split(",").map(s=>parseFloat(s.trim()));if(o.length===2&&!isNaN(o[0])&&!isNaN(o[1]))return[o[0],o[1]]}if(Array.isArray(n)&&n.length===2){const o=parseFloat(n[0]),s=parseFloat(n[1]);if(!isNaN(o)&&!isNaN(s))return[o,s]}}return null}const co=({schema:e,dataSource:a,className:n,onMarkerClick:o,onRowClick:s,onEdit:r,onDelete:c,...l})=>{const[d,h]=i.useState([]),[x,u]=i.useState(!0),[g,b]=i.useState(null),[f,j]=i.useState(null),[v,C]=i.useState(null),[E,_]=i.useState(""),F=ro(e),y=i.useMemo(()=>F,[JSON.stringify(F)]),p=io(e),m=y?.provider==="value";i.useEffect(()=>{(async()=>{try{if(u(!0),l.data){const M=l.data;if(Array.isArray(M)){h(M),u(!1);return}}if(e.data){const M=e.data;if(Array.isArray(M)){h(M),u(!1);return}}if(m&&y?.provider==="value"){h(y.items),u(!1);return}if(!a)throw new Error("DataSource required for object/api providers");if(y?.provider==="object"){const M=y.object,A=await a.find(M,{$filter:e.filter,$orderby:oo(e.sort)});let L=[];Array.isArray(A)?L=A:A&&typeof A=="object"&&(Array.isArray(A.data)?L=A.data:Array.isArray(A.records)&&(L=A.records)),h(L)}else y?.provider==="api"&&(console.warn("API provider not yet implemented for ObjectMap"),h([]));u(!1)}catch(M){b(M),u(!1)}})()},[y,a,m,e.filter,e.sort]),i.useEffect(()=>{!m&&a&&(async()=>{try{if(!a)return;const M=y?.provider==="object"?y.object:e.objectName;if(!M)return;const A=await a.getObjectSchema(M);j(A)}catch(M){console.error("Failed to fetch object schema:",M)}})()},[e.objectName,a,m,y]);const{markers:D,invalidCount:N}=i.useMemo(()=>{let k=0;return{markers:d.map((A,L)=>{const R=lo(A,p);if(!R)return k++,null;const U=p.titleField?A[p.titleField]:"Marker",I=p.descriptionField?A[p.descriptionField]:void 0,[B,ce]=R;return!isFinite(B)||!isFinite(ce)||B<-90||B>90||ce<-180||ce>180?(k++,null):{id:A.id||A._id||`marker-${L}`,title:U,description:I,coordinates:[ce,B],data:A}}).filter(A=>A!==null),invalidCount:k}},[d,p]),T=i.useMemo(()=>D.find(k=>k.id===v),[D,v]),O=Ne({navigation:e.navigation,objectName:e.objectName,onRowClick:s}),S=i.useMemo(()=>{if(!E.trim())return D;const k=E.toLowerCase();return D.filter(M=>M.title?.toLowerCase().includes(k)||M.description?.toLowerCase().includes(k))},[D,E]),w=i.useMemo(()=>{if(!S.length)return{longitude:p.center?.[1]||0,latitude:p.center?.[0]||0,zoom:p.zoom||2};const k=S.map(I=>I.coordinates[0]),M=S.map(I=>I.coordinates[1]),A=Math.min(...k),L=Math.max(...k),R=Math.min(...M),U=Math.max(...M);return{longitude:(A+L)/2,latitude:(R+U)/2,zoom:p.zoom||3}},[S,p]);return x?t.jsx("div",{className:n,children:t.jsx("div",{className:"flex items-center justify-center h-96 bg-muted rounded-lg border",children:t.jsx("div",{className:"text-muted-foreground",children:"Loading map..."})})}):g?t.jsx("div",{className:n,children:t.jsx("div",{className:"flex items-center justify-center h-96 bg-muted rounded-lg border",children:t.jsxs("div",{className:"text-destructive",children:["Error: ",g.message]})})}):t.jsxs("div",{className:n,children:[N>0&&t.jsx("div",{className:"mb-2 p-2 text-sm text-yellow-800 bg-yellow-50 border border-yellow-200 rounded",children:`${N} record${N!==1?"s":""} with missing or invalid coordinates excluded from the map.`}),D.length>0&&t.jsx("div",{className:"mb-2",children:t.jsx("input",{type:"text",value:E,onChange:k=>_(k.target.value),placeholder:"Search locations…",className:"w-full px-3 py-2 text-sm border rounded-md bg-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"})}),t.jsx("div",{className:"relative border rounded-lg overflow-hidden bg-muted h-[300px] sm:h-[400px] md:h-[500px] lg:h-[600px] w-full",children:t.jsxs(Wr,{initialViewState:w,style:{width:"100%",height:"100%"},mapStyle:"https://demotiles.maplibre.org/style.json",touchZoomRotate:!0,dragRotate:!0,touchPitch:!0,children:[t.jsx(eo,{position:"top-right",showCompass:!0,showZoom:!0}),S.map(k=>t.jsx(qr,{longitude:k.coordinates[0],latitude:k.coordinates[1],anchor:"bottom",onClick:M=>{M.originalEvent.stopPropagation(),C(k.id),O.handleClick(k.data),o?.(k.data)},children:t.jsx("div",{className:"text-2xl cursor-pointer hover:scale-110 transition-transform",children:"📍"})},k.id)),T&&t.jsx(Jr,{longitude:T.coordinates[0],latitude:T.coordinates[1],anchor:"top",onClose:()=>C(null),closeOnClick:!1,children:t.jsxs("div",{className:"p-2 min-w-[150px] sm:min-w-[200px]",children:[t.jsx("h3",{className:"font-bold text-sm mb-1",children:T.title}),T.description&&t.jsx("p",{className:"text-xs text-muted-foreground",children:T.description}),t.jsxs("div",{className:"mt-2 text-xs flex gap-2",children:[r&&t.jsx("button",{className:"text-blue-500 hover:underline",onClick:()=>r(T.data),children:"Edit"}),c&&t.jsx("button",{className:"text-red-500 hover:underline",onClick:()=>c(T.data),children:"Delete"})]})]})})]})}),O.isOverlay&&t.jsx(we,{...O,title:"Location Details",children:k=>t.jsx("div",{className:"space-y-3",children:Object.entries(k).map(([M,A])=>t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:M.replace(/_/g," ")}),t.jsx("span",{className:"text-sm",children:String(A??"—")})]},M))})})]})},Wa=({schema:e,...a})=>{const{dataSource:n}=me();return t.jsx(co,{schema:e,dataSource:n,...a})};console.log("Registering object-map...");z.register("object-map",Wa,{namespace:"plugin-map",label:"Object Map",category:"view",inputs:[{name:"objectName",type:"string",label:"Object Name",required:!0},{name:"map",type:"object",label:"Map Config",description:"latitudeField, longitudeField, titleField"}]});z.register("map",Wa,{namespace:"view",label:"Map View",category:"view",inputs:[{name:"objectName",type:"string",label:"Object Name",required:!0},{name:"map",type:"object",label:"Map Config",description:"latitudeField, longitudeField, titleField"}]});const uo=q.lazy(()=>K(()=>import("./MarkdownImpl-BshtTFK2.js"),__vite__mapDeps([38,1]))),mo=({schema:e})=>t.jsx(i.Suspense,{fallback:t.jsx(ve,{className:"w-full h-[200px]"}),children:t.jsx(uo,{content:e.content||"",className:e.className})});z.register("markdown",mo,{namespace:"plugin-markdown",label:"Markdown",category:"plugin",inputs:[{name:"content",type:"string",label:"Markdown Content",required:!0,inputType:"textarea"},{name:"className",type:"string",label:"CSS Class"}],defaultProps:{content:`# Hello World
|
|
4
|
-
|
|
5
|
-
This is a **markdown** component with *formatting* support.
|
|
6
|
-
|
|
7
|
-
- Item 1
|
|
8
|
-
- Item 2
|
|
9
|
-
- Item 3`}});async function fo(){Ya.createRoot(document.getElementById("root")).render(t.jsx(q.StrictMode,{children:t.jsx(ds,{pwa:{enabled:!0,name:"ObjectUI Console",shortName:"Console"},children:t.jsx(On,{children:t.jsx(Nr,{})})})}))}fo();export{Zs as M,Xs as a,ht as b,Ue as r,Qs as u};
|
|
Binary file
|
|
Binary file
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as n,R as F,j as e}from"./vendor-react-Dy_xkBQQ.js";import{i as z,I as q,u as I}from"./vendor-i18n-D5KbMT7w.js";const M={common:{loading:"Loading...",save:"Save",cancel:"Cancel",delete:"Delete",edit:"Edit",create:"Create",search:"Search",filter:"Filter",reset:"Reset",confirm:"Confirm",close:"Close",back:"Back",next:"Next",previous:"Previous",submit:"Submit",refresh:"Refresh",export:"Export",import:"Import",yes:"Yes",no:"No",ok:"OK",actions:"Actions",more:"More",selectAll:"Select All",clearAll:"Clear All",noData:"No data",noResults:"No results found",required:"Required",optional:"Optional"},validation:{required:"{{field}} is required",minLength:"{{field}} must be at least {{min}} characters",maxLength:"{{field}} must be at most {{max}} characters",min:"{{field}} must be at least {{min}}",max:"{{field}} must be at most {{max}}",email:"Please enter a valid email address",url:"Please enter a valid URL",pattern:"{{field}} format is invalid",unique:"{{field}} must be unique",type:"{{field}} must be a valid {{type}}"},form:{addItem:"Add item",removeItem:"Remove item",fieldRequired:"This field is required",invalidFormat:"Invalid format",saveSuccess:"Saved successfully",saveError:"Failed to save",unsavedChanges:"You have unsaved changes. Are you sure you want to leave?",stepOf:"Step {{current}} of {{total}}"},table:{rowsPerPage:"Rows per page",showing:"Showing {{from}} to {{to}} of {{total}}",noRows:"No rows to display",sortAsc:"Sort ascending",sortDesc:"Sort descending",filterColumn:"Filter {{column}}",columns:"Columns",exportCSV:"Export CSV",exportExcel:"Export Excel",selectRow:"Select row",selectAllRows:"Select all rows",expandRow:"Expand row",collapseRow:"Collapse row"},calendar:{today:"Today",month:"Month",week:"Week",day:"Day",agenda:"Agenda",allDay:"All Day",noEvents:"No events",newEvent:"New event"},kanban:{addCard:"Add card",addColumn:"Add column",moveCard:"Move card",deleteCard:"Delete card",deleteColumn:"Delete column"},chart:{noData:"No chart data available",loading:"Loading chart..."},dashboard:{addWidget:"Add widget",removeWidget:"Remove widget",editLayout:"Edit layout",saveLayout:"Save layout",resetLayout:"Reset layout"},console:{title:"ObjectStack Console",initializing:"Initializing application...",loadingSteps:{connecting:"Connecting to data source",loadingConfig:"Loading configuration",preparingWorkspace:"Preparing workspace"},shortcuts:{title:"Keyboard Shortcuts",description:"Quick reference for all available keyboard shortcuts.",groups:{general:"General",navigation:"Navigation",dataViews:"Data Views",preferences:"Preferences"},openCommandPalette:"Open command palette",showShortcuts:"Show keyboard shortcuts",closeDialog:"Close dialog / panel",toggleSidebar:"Toggle sidebar",focusSearch:"Focus search",createRecord:"Create new record",refreshData:"Refresh data",editRecord:"Edit selected record",toggleDarkMode:"Toggle dark mode"},commandPalette:{placeholder:"Type a command or search...",noResults:"No results found.",objects:"Objects",dashboards:"Dashboards",pages:"Pages",reports:"Reports",switchApp:"Switch App",current:"Current",preferences:"Preferences",lightTheme:"Light Theme",darkTheme:"Dark Theme",systemTheme:"System Theme",actions:"Actions",openFullSearch:"Open Full Search Page"},errors:{somethingWentWrong:"Something went wrong",unexpectedError:"An unexpected error occurred while rendering this view.",tryAgain:"Try Again",goHome:"Go Home",errorDetails:"Error Details (dev only)"},theme:{toggle:"Toggle theme",light:"Light",dark:"Dark",system:"System"},objectView:{objectNotFound:"Object Not Found",objectNotFoundDescription:'The object "{{objectName}}" does not exist in the current configuration.',objectNotFoundHint:"Check your app navigation settings or select a different object from the sidebar.",allRecords:"All Records",exitDesignMode:"Exit Design Mode",enterDesignMode:"Enter Design Mode",metadataInspector:"Metadata Inspector",editView:"Edit View",addView:"Add View",designTools:"Design tools",new:"New"},localeSwitcher:{label:"Language"}},errors:{networkError:"Network error. Please check your connection.",serverError:"Server error. Please try again later.",notFound:"Resource not found.",unauthorized:"You are not authorized to perform this action.",forbidden:"Access denied.",timeout:"Request timed out. Please try again.",unknown:"An unexpected error occurred."}},W={common:{loading:"加载中...",save:"保存",cancel:"取消",delete:"删除",edit:"编辑",create:"新建",search:"搜索",filter:"筛选",reset:"重置",confirm:"确认",close:"关闭",back:"返回",next:"下一步",previous:"上一步",submit:"提交",refresh:"刷新",export:"导出",import:"导入",yes:"是",no:"否",ok:"确定",actions:"操作",more:"更多",selectAll:"全选",clearAll:"清除全部",noData:"暂无数据",noResults:"未找到结果",required:"必填",optional:"选填"},validation:{required:"{{field}}不能为空",minLength:"{{field}}至少需要{{min}}个字符",maxLength:"{{field}}最多{{max}}个字符",min:"{{field}}不能小于{{min}}",max:"{{field}}不能大于{{max}}",email:"请输入有效的邮箱地址",url:"请输入有效的URL",pattern:"{{field}}格式不正确",unique:"{{field}}必须唯一",type:"{{field}}必须是有效的{{type}}"},form:{addItem:"添加项目",removeItem:"移除项目",fieldRequired:"此字段为必填项",invalidFormat:"格式不正确",saveSuccess:"保存成功",saveError:"保存失败",unsavedChanges:"您有未保存的更改,确定要离开吗?",stepOf:"第{{current}}步,共{{total}}步"},table:{rowsPerPage:"每页行数",showing:"显示第{{from}}到{{to}}条,共{{total}}条",noRows:"暂无数据",sortAsc:"升序排列",sortDesc:"降序排列",filterColumn:"筛选{{column}}",columns:"列",exportCSV:"导出CSV",exportExcel:"导出Excel",selectRow:"选择行",selectAllRows:"选择所有行",expandRow:"展开行",collapseRow:"折叠行"},calendar:{today:"今天",month:"月",week:"周",day:"日",agenda:"日程",allDay:"全天",noEvents:"暂无事件",newEvent:"新建事件"},kanban:{addCard:"添加卡片",addColumn:"添加列",moveCard:"移动卡片",deleteCard:"删除卡片",deleteColumn:"删除列"},chart:{noData:"暂无图表数据",loading:"图表加载中..."},dashboard:{addWidget:"添加组件",removeWidget:"移除组件",editLayout:"编辑布局",saveLayout:"保存布局",resetLayout:"重置布局"},console:{title:"ObjectStack 控制台",initializing:"正在初始化应用程序...",loadingSteps:{connecting:"正在连接数据源",loadingConfig:"正在加载配置",preparingWorkspace:"正在准备工作区"},shortcuts:{title:"键盘快捷键",description:"所有可用键盘快捷键的快速参考。",groups:{general:"通用",navigation:"导航",dataViews:"数据视图",preferences:"偏好设置"},openCommandPalette:"打开命令面板",showShortcuts:"显示键盘快捷键",closeDialog:"关闭对话框/面板",toggleSidebar:"切换侧边栏",focusSearch:"聚焦搜索",createRecord:"新建记录",refreshData:"刷新数据",editRecord:"编辑选中记录",toggleDarkMode:"切换深色模式"},commandPalette:{placeholder:"输入命令或搜索...",noResults:"未找到结果。",objects:"对象",dashboards:"仪表盘",pages:"页面",reports:"报表",switchApp:"切换应用",current:"当前",preferences:"偏好设置",lightTheme:"浅色主题",darkTheme:"深色主题",systemTheme:"系统主题",actions:"操作",openFullSearch:"打开完整搜索页面"},errors:{somethingWentWrong:"出错了",unexpectedError:"渲染此视图时发生意外错误。",tryAgain:"重试",goHome:"返回首页",errorDetails:"错误详情(仅开发模式)"},theme:{toggle:"切换主题",light:"浅色",dark:"深色",system:"系统"},objectView:{objectNotFound:"未找到对象",objectNotFoundDescription:'对象"{{objectName}}"在当前配置中不存在。',objectNotFoundHint:"请检查您的应用导航设置或从侧边栏选择其他对象。",allRecords:"所有记录",exitDesignMode:"退出设计模式",enterDesignMode:"进入设计模式",metadataInspector:"元数据检查器",editView:"编辑视图",addView:"添加视图",designTools:"设计工具",new:"新建"},localeSwitcher:{label:"语言"}},errors:{networkError:"网络错误,请检查网络连接。",serverError:"服务器错误,请稍后重试。",notFound:"资源未找到。",unauthorized:"您没有权限执行此操作。",forbidden:"访问被拒绝。",timeout:"请求超时,请重试。",unknown:"发生未知错误。"}},H={common:{loading:"読み込み中...",save:"保存",cancel:"キャンセル",delete:"削除",edit:"編集",create:"作成",search:"検索",filter:"フィルター",reset:"リセット",confirm:"確認",close:"閉じる",back:"戻る",next:"次へ",previous:"前へ",submit:"送信",refresh:"更新",export:"エクスポート",import:"インポート",yes:"はい",no:"いいえ",ok:"OK",actions:"操作",more:"もっと見る",selectAll:"すべて選択",clearAll:"すべてクリア",noData:"データがありません",noResults:"結果が見つかりません",required:"必須",optional:"任意"},validation:{required:"{{field}}は必須です",minLength:"{{field}}は{{min}}文字以上で入力してください",maxLength:"{{field}}は{{max}}文字以下で入力してください",min:"{{field}}は{{min}}以上にしてください",max:"{{field}}は{{max}}以下にしてください",email:"有効なメールアドレスを入力してください",url:"有効なURLを入力してください",pattern:"{{field}}の形式が正しくありません",unique:"{{field}}は一意である必要があります",type:"{{field}}は有効な{{type}}である必要があります"},form:{addItem:"項目を追加",removeItem:"項目を削除",fieldRequired:"この項目は必須です",invalidFormat:"形式が正しくありません",saveSuccess:"保存しました",saveError:"保存に失敗しました",unsavedChanges:"保存されていない変更があります。このページを離れますか?",stepOf:"ステップ {{current}} / {{total}}"},table:{rowsPerPage:"1ページの行数",showing:"{{total}}件中{{from}}〜{{to}}件を表示",noRows:"表示するデータがありません",sortAsc:"昇順",sortDesc:"降順",filterColumn:"{{column}}でフィルター",columns:"列",exportCSV:"CSVエクスポート",exportExcel:"Excelエクスポート",selectRow:"行を選択",selectAllRows:"すべての行を選択",expandRow:"行を展開",collapseRow:"行を折りたたむ"},calendar:{today:"今日",month:"月",week:"週",day:"日",agenda:"予定表",allDay:"終日",noEvents:"予定はありません",newEvent:"新しい予定"},kanban:{addCard:"カードを追加",addColumn:"カラムを追加",moveCard:"カードを移動",deleteCard:"カードを削除",deleteColumn:"カラムを削除"},chart:{noData:"チャートデータがありません",loading:"チャート読み込み中..."},dashboard:{addWidget:"ウィジェットを追加",removeWidget:"ウィジェットを削除",editLayout:"レイアウトを編集",saveLayout:"レイアウトを保存",resetLayout:"レイアウトをリセット"},console:{title:"ObjectStack コンソール",initializing:"アプリケーションを初期化中...",loadingSteps:{connecting:"データソースに接続中",loadingConfig:"設定を読み込み中",preparingWorkspace:"ワークスペースを準備中"},shortcuts:{title:"キーボードショートカット",description:"利用可能なすべてのキーボードショートカットのクイックリファレンス。",groups:{general:"一般",navigation:"ナビゲーション",dataViews:"データビュー",preferences:"設定"},openCommandPalette:"コマンドパレットを開く",showShortcuts:"キーボードショートカットを表示",closeDialog:"ダイアログ / パネルを閉じる",toggleSidebar:"サイドバーを切り替え",focusSearch:"検索にフォーカス",createRecord:"新しいレコードを作成",refreshData:"データを更新",editRecord:"選択したレコードを編集",toggleDarkMode:"ダークモードを切り替え"},commandPalette:{placeholder:"コマンドを入力または検索...",noResults:"結果が見つかりません。",objects:"オブジェクト",dashboards:"ダッシュボード",pages:"ページ",reports:"レポート",switchApp:"アプリを切り替え",current:"現在",preferences:"設定",lightTheme:"ライトテーマ",darkTheme:"ダークテーマ",systemTheme:"システムテーマ",actions:"アクション",openFullSearch:"完全な検索ページを開く"},errors:{somethingWentWrong:"問題が発生しました",unexpectedError:"このビューのレンダリング中に予期しないエラーが発生しました。",tryAgain:"再試行",goHome:"ホームに戻る",errorDetails:"エラー詳細(開発モードのみ)"},theme:{toggle:"テーマを切り替え",light:"ライト",dark:"ダーク",system:"システム"},objectView:{objectNotFound:"オブジェクトが見つかりません",objectNotFoundDescription:"オブジェクト「{{objectName}}」は現在の設定に存在しません。",objectNotFoundHint:"アプリのナビゲーション設定を確認するか、サイドバーから別のオブジェクトを選択してください。",allRecords:"すべてのレコード",exitDesignMode:"デザインモードを終了",enterDesignMode:"デザインモードに入る",metadataInspector:"メタデータインスペクター",editView:"ビューを編集",addView:"ビューを追加",designTools:"デザインツール",new:"新規"},localeSwitcher:{label:"言語"}},errors:{networkError:"ネットワークエラーです。接続を確認してください。",serverError:"サーバーエラーです。後でもう一度お試しください。",notFound:"リソースが見つかりません。",unauthorized:"この操作を実行する権限がありません。",forbidden:"アクセスが拒否されました。",timeout:"リクエストがタイムアウトしました。もう一度お試しください。",unknown:"予期しないエラーが発生しました。"}},U={common:{loading:"로딩 중...",save:"저장",cancel:"취소",delete:"삭제",edit:"편집",create:"생성",search:"검색",filter:"필터",reset:"초기화",confirm:"확인",close:"닫기",back:"뒤로",next:"다음",previous:"이전",submit:"제출",refresh:"새로고침",export:"내보내기",import:"가져오기",yes:"예",no:"아니오",ok:"확인",actions:"작업",more:"더보기",selectAll:"모두 선택",clearAll:"모두 지우기",noData:"데이터 없음",noResults:"결과를 찾을 수 없습니다",required:"필수",optional:"선택"},validation:{required:"{{field}}은(는) 필수입니다",minLength:"{{field}}은(는) 최소 {{min}}자 이상이어야 합니다",maxLength:"{{field}}은(는) 최대 {{max}}자까지 가능합니다",min:"{{field}}은(는) {{min}} 이상이어야 합니다",max:"{{field}}은(는) {{max}} 이하여야 합니다",email:"유효한 이메일 주소를 입력해주세요",url:"유효한 URL을 입력해주세요",pattern:"{{field}} 형식이 올바르지 않습니다",unique:"{{field}}은(는) 고유해야 합니다",type:"{{field}}은(는) 유효한 {{type}}이어야 합니다"},form:{addItem:"항목 추가",removeItem:"항목 제거",fieldRequired:"이 필드는 필수입니다",invalidFormat:"형식이 올바르지 않습니다",saveSuccess:"저장되었습니다",saveError:"저장에 실패했습니다",unsavedChanges:"저장하지 않은 변경사항이 있습니다. 페이지를 떠나시겠습니까?",stepOf:"{{total}}단계 중 {{current}}단계"},table:{rowsPerPage:"페이지당 행 수",showing:"{{total}}개 중 {{from}}~{{to}} 표시",noRows:"표시할 데이터가 없습니다",sortAsc:"오름차순 정렬",sortDesc:"내림차순 정렬",filterColumn:"{{column}} 필터",columns:"열",exportCSV:"CSV 내보내기",exportExcel:"Excel 내보내기",selectRow:"행 선택",selectAllRows:"모든 행 선택",expandRow:"행 펼치기",collapseRow:"행 접기"},calendar:{today:"오늘",month:"월",week:"주",day:"일",agenda:"일정",allDay:"종일",noEvents:"일정이 없습니다",newEvent:"새 일정"},kanban:{addCard:"카드 추가",addColumn:"열 추가",moveCard:"카드 이동",deleteCard:"카드 삭제",deleteColumn:"열 삭제"},chart:{noData:"차트 데이터가 없습니다",loading:"차트 로딩 중..."},dashboard:{addWidget:"위젯 추가",removeWidget:"위젯 제거",editLayout:"레이아웃 편집",saveLayout:"레이아웃 저장",resetLayout:"레이아웃 초기화"},console:{title:"ObjectStack 콘솔",initializing:"애플리케이션 초기화 중...",loadingSteps:{connecting:"데이터 소스에 연결 중",loadingConfig:"설정 로드 중",preparingWorkspace:"워크스페이스 준비 중"},shortcuts:{title:"키보드 단축키",description:"사용 가능한 모든 키보드 단축키 빠른 참조.",groups:{general:"일반",navigation:"탐색",dataViews:"데이터 뷰",preferences:"환경설정"},openCommandPalette:"명령 팔레트 열기",showShortcuts:"키보드 단축키 표시",closeDialog:"대화상자 / 패널 닫기",toggleSidebar:"사이드바 전환",focusSearch:"검색에 포커스",createRecord:"새 레코드 생성",refreshData:"데이터 새로고침",editRecord:"선택한 레코드 편집",toggleDarkMode:"다크 모드 전환"},commandPalette:{placeholder:"명령어를 입력하거나 검색...",noResults:"결과를 찾을 수 없습니다.",objects:"객체",dashboards:"대시보드",pages:"페이지",reports:"보고서",switchApp:"앱 전환",current:"현재",preferences:"환경설정",lightTheme:"라이트 테마",darkTheme:"다크 테마",systemTheme:"시스템 테마",actions:"작업",openFullSearch:"전체 검색 페이지 열기"},errors:{somethingWentWrong:"문제가 발생했습니다",unexpectedError:"이 뷰를 렌더링하는 중 예기치 않은 오류가 발생했습니다.",tryAgain:"다시 시도",goHome:"홈으로 이동",errorDetails:"오류 상세정보 (개발 모드 전용)"},theme:{toggle:"테마 전환",light:"라이트",dark:"다크",system:"시스템"},objectView:{objectNotFound:"객체를 찾을 수 없음",objectNotFoundDescription:'객체 "{{objectName}}"이(가) 현재 구성에 존재하지 않습니다.',objectNotFoundHint:"앱 탐색 설정을 확인하거나 사이드바에서 다른 객체를 선택하세요.",allRecords:"모든 레코드",exitDesignMode:"디자인 모드 종료",enterDesignMode:"디자인 모드 시작",metadataInspector:"메타데이터 인스펙터",editView:"뷰 편집",addView:"뷰 추가",designTools:"디자인 도구",new:"새로 만들기"},localeSwitcher:{label:"언어"}},errors:{networkError:"네트워크 오류입니다. 연결을 확인해주세요.",serverError:"서버 오류입니다. 나중에 다시 시도해주세요.",notFound:"리소스를 찾을 수 없습니다.",unauthorized:"이 작업을 수행할 권한이 없습니다.",forbidden:"접근이 거부되었습니다.",timeout:"요청 시간이 초과되었습니다. 다시 시도해주세요.",unknown:"예기치 않은 오류가 발생했습니다."}},B={common:{loading:"Wird geladen...",save:"Speichern",cancel:"Abbrechen",delete:"Löschen",edit:"Bearbeiten",create:"Erstellen",search:"Suchen",filter:"Filtern",reset:"Zurücksetzen",confirm:"Bestätigen",close:"Schließen",back:"Zurück",next:"Weiter",previous:"Zurück",submit:"Absenden",refresh:"Aktualisieren",export:"Exportieren",import:"Importieren",yes:"Ja",no:"Nein",ok:"OK",actions:"Aktionen",more:"Mehr",selectAll:"Alle auswählen",clearAll:"Alle löschen",noData:"Keine Daten",noResults:"Keine Ergebnisse gefunden",required:"Erforderlich",optional:"Optional"},validation:{required:"{{field}} ist erforderlich",minLength:"{{field}} muss mindestens {{min}} Zeichen lang sein",maxLength:"{{field}} darf höchstens {{max}} Zeichen lang sein",min:"{{field}} muss mindestens {{min}} sein",max:"{{field}} darf höchstens {{max}} sein",email:"Bitte geben Sie eine gültige E-Mail-Adresse ein",url:"Bitte geben Sie eine gültige URL ein",pattern:"{{field}} hat ein ungültiges Format",unique:"{{field}} muss eindeutig sein",type:"{{field}} muss ein gültiger {{type}} sein"},form:{addItem:"Element hinzufügen",removeItem:"Element entfernen",fieldRequired:"Dieses Feld ist erforderlich",invalidFormat:"Ungültiges Format",saveSuccess:"Erfolgreich gespeichert",saveError:"Speichern fehlgeschlagen",unsavedChanges:"Sie haben nicht gespeicherte Änderungen. Möchten Sie die Seite wirklich verlassen?",stepOf:"Schritt {{current}} von {{total}}"},table:{rowsPerPage:"Zeilen pro Seite",showing:"{{from}} bis {{to}} von {{total}} angezeigt",noRows:"Keine Zeilen vorhanden",sortAsc:"Aufsteigend sortieren",sortDesc:"Absteigend sortieren",filterColumn:"{{column}} filtern",columns:"Spalten",exportCSV:"CSV exportieren",exportExcel:"Excel exportieren",selectRow:"Zeile auswählen",selectAllRows:"Alle Zeilen auswählen",expandRow:"Zeile erweitern",collapseRow:"Zeile reduzieren"},calendar:{today:"Heute",month:"Monat",week:"Woche",day:"Tag",agenda:"Agenda",allDay:"Ganztägig",noEvents:"Keine Termine",newEvent:"Neuer Termin"},kanban:{addCard:"Karte hinzufügen",addColumn:"Spalte hinzufügen",moveCard:"Karte verschieben",deleteCard:"Karte löschen",deleteColumn:"Spalte löschen"},chart:{noData:"Keine Diagrammdaten verfügbar",loading:"Diagramm wird geladen..."},dashboard:{addWidget:"Widget hinzufügen",removeWidget:"Widget entfernen",editLayout:"Layout bearbeiten",saveLayout:"Layout speichern",resetLayout:"Layout zurücksetzen"},console:{title:"ObjectStack Konsole",initializing:"Anwendung wird initialisiert...",loadingSteps:{connecting:"Verbindung zur Datenquelle herstellen",loadingConfig:"Konfiguration laden",preparingWorkspace:"Arbeitsbereich vorbereiten"},shortcuts:{title:"Tastenkürzel",description:"Kurzreferenz für alle verfügbaren Tastenkürzel.",groups:{general:"Allgemein",navigation:"Navigation",dataViews:"Datenansichten",preferences:"Einstellungen"},openCommandPalette:"Befehlspalette öffnen",showShortcuts:"Tastenkürzel anzeigen",closeDialog:"Dialog / Panel schließen",toggleSidebar:"Seitenleiste umschalten",focusSearch:"Suche fokussieren",createRecord:"Neuen Datensatz erstellen",refreshData:"Daten aktualisieren",editRecord:"Ausgewählten Datensatz bearbeiten",toggleDarkMode:"Dunkelmodus umschalten"},commandPalette:{placeholder:"Befehl eingeben oder suchen...",noResults:"Keine Ergebnisse gefunden.",objects:"Objekte",dashboards:"Dashboards",pages:"Seiten",reports:"Berichte",switchApp:"App wechseln",current:"Aktuell",preferences:"Einstellungen",lightTheme:"Helles Design",darkTheme:"Dunkles Design",systemTheme:"Systemdesign",actions:"Aktionen",openFullSearch:"Vollständige Suchseite öffnen"},errors:{somethingWentWrong:"Etwas ist schiefgelaufen",unexpectedError:"Beim Rendern dieser Ansicht ist ein unerwarteter Fehler aufgetreten.",tryAgain:"Erneut versuchen",goHome:"Zur Startseite",errorDetails:"Fehlerdetails (nur Entwicklung)"},theme:{toggle:"Design umschalten",light:"Hell",dark:"Dunkel",system:"System"},objectView:{objectNotFound:"Objekt nicht gefunden",objectNotFoundDescription:'Das Objekt „{{objectName}}" existiert in der aktuellen Konfiguration nicht.',objectNotFoundHint:"Überprüfen Sie Ihre App-Navigationseinstellungen oder wählen Sie ein anderes Objekt aus der Seitenleiste.",allRecords:"Alle Datensätze",exitDesignMode:"Designmodus beenden",enterDesignMode:"Designmodus starten",metadataInspector:"Metadaten-Inspektor",editView:"Ansicht bearbeiten",addView:"Ansicht hinzufügen",designTools:"Design-Werkzeuge",new:"Neu"},localeSwitcher:{label:"Sprache"}},errors:{networkError:"Netzwerkfehler. Bitte überprüfen Sie Ihre Verbindung.",serverError:"Serverfehler. Bitte versuchen Sie es später erneut.",notFound:"Ressource nicht gefunden.",unauthorized:"Sie sind nicht berechtigt, diese Aktion auszuführen.",forbidden:"Zugriff verweigert.",timeout:"Zeitüberschreitung. Bitte versuchen Sie es erneut.",unknown:"Ein unerwarteter Fehler ist aufgetreten."}},K={common:{loading:"Chargement...",save:"Enregistrer",cancel:"Annuler",delete:"Supprimer",edit:"Modifier",create:"Créer",search:"Rechercher",filter:"Filtrer",reset:"Réinitialiser",confirm:"Confirmer",close:"Fermer",back:"Retour",next:"Suivant",previous:"Précédent",submit:"Soumettre",refresh:"Actualiser",export:"Exporter",import:"Importer",yes:"Oui",no:"Non",ok:"OK",actions:"Actions",more:"Plus",selectAll:"Tout sélectionner",clearAll:"Tout effacer",noData:"Aucune donnée",noResults:"Aucun résultat trouvé",required:"Obligatoire",optional:"Facultatif"},validation:{required:"{{field}} est obligatoire",minLength:"{{field}} doit contenir au moins {{min}} caractères",maxLength:"{{field}} doit contenir au plus {{max}} caractères",min:"{{field}} doit être au moins {{min}}",max:"{{field}} doit être au plus {{max}}",email:"Veuillez saisir une adresse e-mail valide",url:"Veuillez saisir une URL valide",pattern:"Le format de {{field}} est invalide",unique:"{{field}} doit être unique",type:"{{field}} doit être un {{type}} valide"},form:{addItem:"Ajouter un élément",removeItem:"Supprimer un élément",fieldRequired:"Ce champ est obligatoire",invalidFormat:"Format invalide",saveSuccess:"Enregistré avec succès",saveError:"Échec de l'enregistrement",unsavedChanges:"Vous avez des modifications non enregistrées. Voulez-vous vraiment quitter ?",stepOf:"Étape {{current}} sur {{total}}"},table:{rowsPerPage:"Lignes par page",showing:"Affichage de {{from}} à {{to}} sur {{total}}",noRows:"Aucune ligne à afficher",sortAsc:"Tri croissant",sortDesc:"Tri décroissant",filterColumn:"Filtrer {{column}}",columns:"Colonnes",exportCSV:"Exporter en CSV",exportExcel:"Exporter en Excel",selectRow:"Sélectionner la ligne",selectAllRows:"Sélectionner toutes les lignes",expandRow:"Développer la ligne",collapseRow:"Réduire la ligne"},calendar:{today:"Aujourd'hui",month:"Mois",week:"Semaine",day:"Jour",agenda:"Agenda",allDay:"Toute la journée",noEvents:"Aucun événement",newEvent:"Nouvel événement"},kanban:{addCard:"Ajouter une carte",addColumn:"Ajouter une colonne",moveCard:"Déplacer la carte",deleteCard:"Supprimer la carte",deleteColumn:"Supprimer la colonne"},chart:{noData:"Aucune donnée de graphique disponible",loading:"Chargement du graphique..."},dashboard:{addWidget:"Ajouter un widget",removeWidget:"Supprimer un widget",editLayout:"Modifier la mise en page",saveLayout:"Enregistrer la mise en page",resetLayout:"Réinitialiser la mise en page"},console:{title:"Console ObjectStack",initializing:"Initialisation de l'application...",loadingSteps:{connecting:"Connexion à la source de données",loadingConfig:"Chargement de la configuration",preparingWorkspace:"Préparation de l'espace de travail"},shortcuts:{title:"Raccourcis clavier",description:"Référence rapide de tous les raccourcis clavier disponibles.",groups:{general:"Général",navigation:"Navigation",dataViews:"Vues de données",preferences:"Préférences"},openCommandPalette:"Ouvrir la palette de commandes",showShortcuts:"Afficher les raccourcis clavier",closeDialog:"Fermer le dialogue / panneau",toggleSidebar:"Basculer la barre latérale",focusSearch:"Focus sur la recherche",createRecord:"Créer un nouvel enregistrement",refreshData:"Actualiser les données",editRecord:"Modifier l'enregistrement sélectionné",toggleDarkMode:"Basculer le mode sombre"},commandPalette:{placeholder:"Tapez une commande ou recherchez...",noResults:"Aucun résultat trouvé.",objects:"Objets",dashboards:"Tableaux de bord",pages:"Pages",reports:"Rapports",switchApp:"Changer d'application",current:"Actuel",preferences:"Préférences",lightTheme:"Thème clair",darkTheme:"Thème sombre",systemTheme:"Thème système",actions:"Actions",openFullSearch:"Ouvrir la page de recherche complète"},errors:{somethingWentWrong:"Quelque chose s'est mal passé",unexpectedError:"Une erreur inattendue est survenue lors du rendu de cette vue.",tryAgain:"Réessayer",goHome:"Retour à l'accueil",errorDetails:"Détails de l'erreur (développement uniquement)"},theme:{toggle:"Changer de thème",light:"Clair",dark:"Sombre",system:"Système"},objectView:{objectNotFound:"Objet introuvable",objectNotFoundDescription:"L'objet « {{objectName}} » n'existe pas dans la configuration actuelle.",objectNotFoundHint:"Vérifiez les paramètres de navigation de votre application ou sélectionnez un autre objet dans la barre latérale.",allRecords:"Tous les enregistrements",exitDesignMode:"Quitter le mode conception",enterDesignMode:"Entrer en mode conception",metadataInspector:"Inspecteur de métadonnées",editView:"Modifier la vue",addView:"Ajouter une vue",designTools:"Outils de conception",new:"Nouveau"},localeSwitcher:{label:"Langue"}},errors:{networkError:"Erreur réseau. Veuillez vérifier votre connexion.",serverError:"Erreur serveur. Veuillez réessayer plus tard.",notFound:"Ressource introuvable.",unauthorized:"Vous n'êtes pas autorisé à effectuer cette action.",forbidden:"Accès refusé.",timeout:"Délai d'attente dépassé. Veuillez réessayer.",unknown:"Une erreur inattendue s'est produite."}},G={common:{loading:"Cargando...",save:"Guardar",cancel:"Cancelar",delete:"Eliminar",edit:"Editar",create:"Crear",search:"Buscar",filter:"Filtrar",reset:"Restablecer",confirm:"Confirmar",close:"Cerrar",back:"Atrás",next:"Siguiente",previous:"Anterior",submit:"Enviar",refresh:"Actualizar",export:"Exportar",import:"Importar",yes:"Sí",no:"No",ok:"Aceptar",actions:"Acciones",more:"Más",selectAll:"Seleccionar todo",clearAll:"Borrar todo",noData:"Sin datos",noResults:"No se encontraron resultados",required:"Obligatorio",optional:"Opcional"},validation:{required:"{{field}} es obligatorio",minLength:"{{field}} debe tener al menos {{min}} caracteres",maxLength:"{{field}} debe tener como máximo {{max}} caracteres",min:"{{field}} debe ser al menos {{min}}",max:"{{field}} debe ser como máximo {{max}}",email:"Por favor, introduzca un correo electrónico válido",url:"Por favor, introduzca una URL válida",pattern:"El formato de {{field}} no es válido",unique:"{{field}} debe ser único",type:"{{field}} debe ser un {{type}} válido"},form:{addItem:"Añadir elemento",removeItem:"Eliminar elemento",fieldRequired:"Este campo es obligatorio",invalidFormat:"Formato no válido",saveSuccess:"Guardado correctamente",saveError:"Error al guardar",unsavedChanges:"Tiene cambios sin guardar. ¿Está seguro de que desea salir?",stepOf:"Paso {{current}} de {{total}}"},table:{rowsPerPage:"Filas por página",showing:"Mostrando {{from}} a {{to}} de {{total}}",noRows:"No hay filas para mostrar",sortAsc:"Ordenar ascendente",sortDesc:"Ordenar descendente",filterColumn:"Filtrar {{column}}",columns:"Columnas",exportCSV:"Exportar CSV",exportExcel:"Exportar Excel",selectRow:"Seleccionar fila",selectAllRows:"Seleccionar todas las filas",expandRow:"Expandir fila",collapseRow:"Contraer fila"},calendar:{today:"Hoy",month:"Mes",week:"Semana",day:"Día",agenda:"Agenda",allDay:"Todo el día",noEvents:"Sin eventos",newEvent:"Nuevo evento"},kanban:{addCard:"Añadir tarjeta",addColumn:"Añadir columna",moveCard:"Mover tarjeta",deleteCard:"Eliminar tarjeta",deleteColumn:"Eliminar columna"},chart:{noData:"No hay datos de gráfico disponibles",loading:"Cargando gráfico..."},dashboard:{addWidget:"Añadir widget",removeWidget:"Eliminar widget",editLayout:"Editar diseño",saveLayout:"Guardar diseño",resetLayout:"Restablecer diseño"},console:{title:"Consola ObjectStack",initializing:"Inicializando aplicación...",loadingSteps:{connecting:"Conectando a la fuente de datos",loadingConfig:"Cargando configuración",preparingWorkspace:"Preparando espacio de trabajo"},shortcuts:{title:"Atajos de teclado",description:"Referencia rápida de todos los atajos de teclado disponibles.",groups:{general:"General",navigation:"Navegación",dataViews:"Vistas de datos",preferences:"Preferencias"},openCommandPalette:"Abrir paleta de comandos",showShortcuts:"Mostrar atajos de teclado",closeDialog:"Cerrar diálogo / panel",toggleSidebar:"Alternar barra lateral",focusSearch:"Enfocar búsqueda",createRecord:"Crear nuevo registro",refreshData:"Actualizar datos",editRecord:"Editar registro seleccionado",toggleDarkMode:"Alternar modo oscuro"},commandPalette:{placeholder:"Escriba un comando o busque...",noResults:"No se encontraron resultados.",objects:"Objetos",dashboards:"Paneles",pages:"Páginas",reports:"Informes",switchApp:"Cambiar aplicación",current:"Actual",preferences:"Preferencias",lightTheme:"Tema claro",darkTheme:"Tema oscuro",systemTheme:"Tema del sistema",actions:"Acciones",openFullSearch:"Abrir página de búsqueda completa"},errors:{somethingWentWrong:"Algo salió mal",unexpectedError:"Ocurrió un error inesperado al renderizar esta vista.",tryAgain:"Intentar de nuevo",goHome:"Ir al inicio",errorDetails:"Detalles del error (solo desarrollo)"},theme:{toggle:"Cambiar tema",light:"Claro",dark:"Oscuro",system:"Sistema"},objectView:{objectNotFound:"Objeto no encontrado",objectNotFoundDescription:'El objeto "{{objectName}}" no existe en la configuración actual.',objectNotFoundHint:"Verifique la configuración de navegación de su aplicación o seleccione un objeto diferente en la barra lateral.",allRecords:"Todos los registros",exitDesignMode:"Salir del modo de diseño",enterDesignMode:"Entrar en modo de diseño",metadataInspector:"Inspector de metadatos",editView:"Editar vista",addView:"Agregar vista",designTools:"Herramientas de diseño",new:"Nuevo"},localeSwitcher:{label:"Idioma"}},errors:{networkError:"Error de red. Por favor, compruebe su conexión.",serverError:"Error del servidor. Por favor, inténtelo de nuevo más tarde.",notFound:"Recurso no encontrado.",unauthorized:"No está autorizado para realizar esta acción.",forbidden:"Acceso denegado.",timeout:"Tiempo de espera agotado. Por favor, inténtelo de nuevo.",unknown:"Ha ocurrido un error inesperado."}},Z={common:{loading:"Carregando...",save:"Salvar",cancel:"Cancelar",delete:"Excluir",edit:"Editar",create:"Criar",search:"Pesquisar",filter:"Filtrar",reset:"Redefinir",confirm:"Confirmar",close:"Fechar",back:"Voltar",next:"Próximo",previous:"Anterior",submit:"Enviar",refresh:"Atualizar",export:"Exportar",import:"Importar",yes:"Sim",no:"Não",ok:"OK",actions:"Ações",more:"Mais",selectAll:"Selecionar tudo",clearAll:"Limpar tudo",noData:"Sem dados",noResults:"Nenhum resultado encontrado",required:"Obrigatório",optional:"Opcional"},validation:{required:"{{field}} é obrigatório",minLength:"{{field}} deve ter pelo menos {{min}} caracteres",maxLength:"{{field}} deve ter no máximo {{max}} caracteres",min:"{{field}} deve ser pelo menos {{min}}",max:"{{field}} deve ser no máximo {{max}}",email:"Por favor, insira um endereço de e-mail válido",url:"Por favor, insira uma URL válida",pattern:"O formato de {{field}} é inválido",unique:"{{field}} deve ser único",type:"{{field}} deve ser um {{type}} válido"},form:{addItem:"Adicionar item",removeItem:"Remover item",fieldRequired:"Este campo é obrigatório",invalidFormat:"Formato inválido",saveSuccess:"Salvo com sucesso",saveError:"Falha ao salvar",unsavedChanges:"Você tem alterações não salvas. Tem certeza de que deseja sair?",stepOf:"Etapa {{current}} de {{total}}"},table:{rowsPerPage:"Linhas por página",showing:"Mostrando {{from}} a {{to}} de {{total}}",noRows:"Nenhuma linha para exibir",sortAsc:"Ordenar crescente",sortDesc:"Ordenar decrescente",filterColumn:"Filtrar {{column}}",columns:"Colunas",exportCSV:"Exportar CSV",exportExcel:"Exportar Excel",selectRow:"Selecionar linha",selectAllRows:"Selecionar todas as linhas",expandRow:"Expandir linha",collapseRow:"Recolher linha"},calendar:{today:"Hoje",month:"Mês",week:"Semana",day:"Dia",agenda:"Agenda",allDay:"Dia inteiro",noEvents:"Sem eventos",newEvent:"Novo evento"},kanban:{addCard:"Adicionar cartão",addColumn:"Adicionar coluna",moveCard:"Mover cartão",deleteCard:"Excluir cartão",deleteColumn:"Excluir coluna"},chart:{noData:"Nenhum dado de gráfico disponível",loading:"Carregando gráfico..."},dashboard:{addWidget:"Adicionar widget",removeWidget:"Remover widget",editLayout:"Editar layout",saveLayout:"Salvar layout",resetLayout:"Redefinir layout"},console:{title:"Console ObjectStack",initializing:"Inicializando aplicação...",loadingSteps:{connecting:"Conectando à fonte de dados",loadingConfig:"Carregando configuração",preparingWorkspace:"Preparando espaço de trabalho"},shortcuts:{title:"Atalhos de teclado",description:"Referência rápida de todos os atalhos de teclado disponíveis.",groups:{general:"Geral",navigation:"Navegação",dataViews:"Visualizações de dados",preferences:"Preferências"},openCommandPalette:"Abrir paleta de comandos",showShortcuts:"Mostrar atalhos de teclado",closeDialog:"Fechar diálogo / painel",toggleSidebar:"Alternar barra lateral",focusSearch:"Focar na pesquisa",createRecord:"Criar novo registro",refreshData:"Atualizar dados",editRecord:"Editar registro selecionado",toggleDarkMode:"Alternar modo escuro"},commandPalette:{placeholder:"Digite um comando ou pesquise...",noResults:"Nenhum resultado encontrado.",objects:"Objetos",dashboards:"Painéis",pages:"Páginas",reports:"Relatórios",switchApp:"Trocar aplicativo",current:"Atual",preferences:"Preferências",lightTheme:"Tema claro",darkTheme:"Tema escuro",systemTheme:"Tema do sistema",actions:"Ações",openFullSearch:"Abrir página de pesquisa completa"},errors:{somethingWentWrong:"Algo deu errado",unexpectedError:"Ocorreu um erro inesperado ao renderizar esta visualização.",tryAgain:"Tentar novamente",goHome:"Ir para início",errorDetails:"Detalhes do erro (somente desenvolvimento)"},theme:{toggle:"Alternar tema",light:"Claro",dark:"Escuro",system:"Sistema"},objectView:{objectNotFound:"Objeto não encontrado",objectNotFoundDescription:'O objeto "{{objectName}}" não existe na configuração atual.',objectNotFoundHint:"Verifique as configurações de navegação do seu aplicativo ou selecione um objeto diferente na barra lateral.",allRecords:"Todos os registros",exitDesignMode:"Sair do modo de design",enterDesignMode:"Entrar no modo de design",metadataInspector:"Inspetor de metadados",editView:"Editar visualização",addView:"Adicionar visualização",designTools:"Ferramentas de design",new:"Novo"},localeSwitcher:{label:"Idioma"}},errors:{networkError:"Erro de rede. Por favor, verifique sua conexão.",serverError:"Erro no servidor. Por favor, tente novamente mais tarde.",notFound:"Recurso não encontrado.",unauthorized:"Você não tem permissão para realizar esta ação.",forbidden:"Acesso negado.",timeout:"Tempo limite excedido. Por favor, tente novamente.",unknown:"Ocorreu um erro inesperado."}},J={common:{loading:"Загрузка...",save:"Сохранить",cancel:"Отмена",delete:"Удалить",edit:"Редактировать",create:"Создать",search:"Поиск",filter:"Фильтр",reset:"Сбросить",confirm:"Подтвердить",close:"Закрыть",back:"Назад",next:"Далее",previous:"Назад",submit:"Отправить",refresh:"Обновить",export:"Экспорт",import:"Импорт",yes:"Да",no:"Нет",ok:"ОК",actions:"Действия",more:"Ещё",selectAll:"Выбрать все",clearAll:"Очистить все",noData:"Нет данных",noResults:"Результаты не найдены",required:"Обязательно",optional:"Необязательно"},validation:{required:"Поле {{field}} обязательно для заполнения",minLength:"{{field}} должно содержать не менее {{min}} символов",maxLength:"{{field}} должно содержать не более {{max}} символов",min:"{{field}} должно быть не менее {{min}}",max:"{{field}} должно быть не более {{max}}",email:"Пожалуйста, введите корректный адрес электронной почты",url:"Пожалуйста, введите корректный URL",pattern:"Неверный формат поля {{field}}",unique:"{{field}} должно быть уникальным",type:"{{field}} должно быть допустимым {{type}}"},form:{addItem:"Добавить элемент",removeItem:"Удалить элемент",fieldRequired:"Это поле обязательно",invalidFormat:"Неверный формат",saveSuccess:"Успешно сохранено",saveError:"Ошибка сохранения",unsavedChanges:"У вас есть несохранённые изменения. Вы уверены, что хотите покинуть страницу?",stepOf:"Шаг {{current}} из {{total}}"},table:{rowsPerPage:"Строк на странице",showing:"Показано с {{from}} по {{to}} из {{total}}",noRows:"Нет строк для отображения",sortAsc:"Сортировка по возрастанию",sortDesc:"Сортировка по убыванию",filterColumn:"Фильтр по {{column}}",columns:"Столбцы",exportCSV:"Экспорт в CSV",exportExcel:"Экспорт в Excel",selectRow:"Выбрать строку",selectAllRows:"Выбрать все строки",expandRow:"Развернуть строку",collapseRow:"Свернуть строку"},calendar:{today:"Сегодня",month:"Месяц",week:"Неделя",day:"День",agenda:"Расписание",allDay:"Весь день",noEvents:"Нет событий",newEvent:"Новое событие"},kanban:{addCard:"Добавить карточку",addColumn:"Добавить колонку",moveCard:"Переместить карточку",deleteCard:"Удалить карточку",deleteColumn:"Удалить колонку"},chart:{noData:"Нет данных для графика",loading:"Загрузка графика..."},dashboard:{addWidget:"Добавить виджет",removeWidget:"Удалить виджет",editLayout:"Редактировать макет",saveLayout:"Сохранить макет",resetLayout:"Сбросить макет"},console:{title:"Консоль ObjectStack",initializing:"Инициализация приложения...",loadingSteps:{connecting:"Подключение к источнику данных",loadingConfig:"Загрузка конфигурации",preparingWorkspace:"Подготовка рабочего пространства"},shortcuts:{title:"Горячие клавиши",description:"Краткий справочник по всем доступным горячим клавишам.",groups:{general:"Общие",navigation:"Навигация",dataViews:"Представления данных",preferences:"Настройки"},openCommandPalette:"Открыть палитру команд",showShortcuts:"Показать горячие клавиши",closeDialog:"Закрыть диалог / панель",toggleSidebar:"Переключить боковую панель",focusSearch:"Фокус на поиске",createRecord:"Создать новую запись",refreshData:"Обновить данные",editRecord:"Редактировать выбранную запись",toggleDarkMode:"Переключить тёмный режим"},commandPalette:{placeholder:"Введите команду или поиск...",noResults:"Результаты не найдены.",objects:"Объекты",dashboards:"Панели мониторинга",pages:"Страницы",reports:"Отчёты",switchApp:"Переключить приложение",current:"Текущее",preferences:"Настройки",lightTheme:"Светлая тема",darkTheme:"Тёмная тема",systemTheme:"Системная тема",actions:"Действия",openFullSearch:"Открыть полную страницу поиска"},errors:{somethingWentWrong:"Что-то пошло не так",unexpectedError:"При отображении этого представления произошла непредвиденная ошибка.",tryAgain:"Попробовать снова",goHome:"На главную",errorDetails:"Подробности ошибки (только для разработки)"},theme:{toggle:"Переключить тему",light:"Светлая",dark:"Тёмная",system:"Системная"},objectView:{objectNotFound:"Объект не найден",objectNotFoundDescription:"Объект «{{objectName}}» не существует в текущей конфигурации.",objectNotFoundHint:"Проверьте настройки навигации приложения или выберите другой объект на боковой панели.",allRecords:"Все записи",exitDesignMode:"Выйти из режима дизайна",enterDesignMode:"Войти в режим дизайна",metadataInspector:"Инспектор метаданных",editView:"Редактировать представление",addView:"Добавить представление",designTools:"Инструменты дизайна",new:"Создать"},localeSwitcher:{label:"Язык"}},errors:{networkError:"Ошибка сети. Проверьте подключение к интернету.",serverError:"Ошибка сервера. Попробуйте позже.",notFound:"Ресурс не найден.",unauthorized:"У вас нет прав для выполнения этого действия.",forbidden:"Доступ запрещён.",timeout:"Время ожидания истекло. Попробуйте снова.",unknown:"Произошла непредвиденная ошибка."}},Y={common:{loading:"جاري التحميل...",save:"حفظ",cancel:"إلغاء",delete:"حذف",edit:"تعديل",create:"إنشاء",search:"بحث",filter:"تصفية",reset:"إعادة تعيين",confirm:"تأكيد",close:"إغلاق",back:"رجوع",next:"التالي",previous:"السابق",submit:"إرسال",refresh:"تحديث",export:"تصدير",import:"استيراد",yes:"نعم",no:"لا",ok:"موافق",actions:"إجراءات",more:"المزيد",selectAll:"تحديد الكل",clearAll:"مسح الكل",noData:"لا توجد بيانات",noResults:"لم يتم العثور على نتائج",required:"مطلوب",optional:"اختياري"},validation:{required:"{{field}} مطلوب",minLength:"{{field}} يجب أن يكون {{min}} حرفاً على الأقل",maxLength:"{{field}} يجب ألا يتجاوز {{max}} حرفاً",min:"{{field}} يجب أن يكون {{min}} على الأقل",max:"{{field}} يجب ألا يتجاوز {{max}}",email:"يرجى إدخال بريد إلكتروني صالح",url:"يرجى إدخال رابط صالح",pattern:"صيغة {{field}} غير صالحة",unique:"{{field}} يجب أن يكون فريداً",type:"{{field}} يجب أن يكون {{type}} صالحاً"},form:{addItem:"إضافة عنصر",removeItem:"إزالة عنصر",fieldRequired:"هذا الحقل مطلوب",invalidFormat:"صيغة غير صالحة",saveSuccess:"تم الحفظ بنجاح",saveError:"فشل في الحفظ",unsavedChanges:"لديك تغييرات غير محفوظة. هل أنت متأكد أنك تريد المغادرة؟",stepOf:"الخطوة {{current}} من {{total}}"},table:{rowsPerPage:"صفوف في الصفحة",showing:"عرض {{from}} إلى {{to}} من {{total}}",noRows:"لا توجد صفوف للعرض",sortAsc:"ترتيب تصاعدي",sortDesc:"ترتيب تنازلي",filterColumn:"تصفية {{column}}",columns:"الأعمدة",exportCSV:"تصدير CSV",exportExcel:"تصدير Excel",selectRow:"تحديد صف",selectAllRows:"تحديد جميع الصفوف",expandRow:"توسيع الصف",collapseRow:"طي الصف"},calendar:{today:"اليوم",month:"شهر",week:"أسبوع",day:"يوم",agenda:"جدول أعمال",allDay:"طوال اليوم",noEvents:"لا توجد أحداث",newEvent:"حدث جديد"},kanban:{addCard:"إضافة بطاقة",addColumn:"إضافة عمود",moveCard:"نقل بطاقة",deleteCard:"حذف بطاقة",deleteColumn:"حذف عمود"},chart:{noData:"لا تتوفر بيانات للرسم البياني",loading:"جاري تحميل الرسم البياني..."},dashboard:{addWidget:"إضافة أداة",removeWidget:"إزالة أداة",editLayout:"تعديل التخطيط",saveLayout:"حفظ التخطيط",resetLayout:"إعادة تعيين التخطيط"},console:{title:"وحدة تحكم ObjectStack",initializing:"جاري تهيئة التطبيق...",loadingSteps:{connecting:"جاري الاتصال بمصدر البيانات",loadingConfig:"جاري تحميل الإعدادات",preparingWorkspace:"جاري تجهيز مساحة العمل"},shortcuts:{title:"اختصارات لوحة المفاتيح",description:"مرجع سريع لجميع اختصارات لوحة المفاتيح المتاحة.",groups:{general:"عام",navigation:"التنقل",dataViews:"عروض البيانات",preferences:"التفضيلات"},openCommandPalette:"فتح لوحة الأوامر",showShortcuts:"عرض اختصارات لوحة المفاتيح",closeDialog:"إغلاق النافذة / اللوحة",toggleSidebar:"تبديل الشريط الجانبي",focusSearch:"التركيز على البحث",createRecord:"إنشاء سجل جديد",refreshData:"تحديث البيانات",editRecord:"تعديل السجل المحدد",toggleDarkMode:"تبديل الوضع الداكن"},commandPalette:{placeholder:"اكتب أمراً أو ابحث...",noResults:"لم يتم العثور على نتائج.",objects:"الكائنات",dashboards:"لوحات المعلومات",pages:"الصفحات",reports:"التقارير",switchApp:"تبديل التطبيق",current:"الحالي",preferences:"التفضيلات",lightTheme:"المظهر الفاتح",darkTheme:"المظهر الداكن",systemTheme:"مظهر النظام",actions:"الإجراءات",openFullSearch:"فتح صفحة البحث الكاملة"},errors:{somethingWentWrong:"حدث خطأ ما",unexpectedError:"حدث خطأ غير متوقع أثناء عرض هذا المحتوى.",tryAgain:"إعادة المحاولة",goHome:"العودة للرئيسية",errorDetails:"تفاصيل الخطأ (وضع التطوير فقط)"},theme:{toggle:"تبديل المظهر",light:"فاتح",dark:"داكن",system:"النظام"},objectView:{objectNotFound:"الكائن غير موجود",objectNotFoundDescription:'الكائن "{{objectName}}" غير موجود في الإعدادات الحالية.',objectNotFoundHint:"تحقق من إعدادات التنقل في تطبيقك أو اختر كائنًا آخر من الشريط الجانبي.",allRecords:"جميع السجلات",exitDesignMode:"الخروج من وضع التصميم",enterDesignMode:"الدخول إلى وضع التصميم",metadataInspector:"مفتش البيانات الوصفية",editView:"تعديل العرض",addView:"إضافة عرض",designTools:"أدوات التصميم",new:"جديد"},localeSwitcher:{label:"اللغة"}},errors:{networkError:"خطأ في الشبكة. يرجى التحقق من اتصالك.",serverError:"خطأ في الخادم. يرجى المحاولة مرة أخرى لاحقاً.",notFound:"المورد غير موجود.",unauthorized:"ليس لديك صلاحية لتنفيذ هذا الإجراء.",forbidden:"تم رفض الوصول.",timeout:"انتهت مهلة الطلب. يرجى المحاولة مرة أخرى.",unknown:"حدث خطأ غير متوقع."}},$={en:M,zh:W,ja:H,ko:U,de:B,fr:K,es:G,pt:Z,ru:J,ar:Y},Q=["ar","he","fa","ur"];function _(o){return Q.includes(o)}function X(o={}){const{defaultLanguage:s="en",fallbackLanguage:i="en",resources:l={},detectBrowserLanguage:r=!0,interpolation:g}=o,t={};for(const[a,m]of Object.entries($))t[a]={translation:{...m,...l[a]||{}}};for(const[a,m]of Object.entries(l))t[a]||(t[a]={translation:m});let d=s;if(r&&typeof navigator<"u"){const a=navigator.language?.split("-")[0];a&&t[a]&&(d=a)}const u=z.createInstance();return u.init({lng:d,fallbackLng:i,resources:t,interpolation:{escapeValue:!1,...g},returnNull:!1}),u}function L(o){return _(o)?"rtl":"ltr"}const T=n.createContext(null);function oe({config:o,instance:s,loadLanguage:i,children:l}){const r=n.useMemo(()=>s||X(o),[s,o]),[g,t]=n.useState(r.language||"en"),d=L(g);n.useEffect(()=>{const a=m=>{t(m),typeof document<"u"&&(document.documentElement.dir=L(m),document.documentElement.lang=m)};return r.on("languageChanged",a),()=>{r.off("languageChanged",a)}},[r]);const u=n.useMemo(()=>({language:g,changeLanguage:async a=>{if(i&&!r.hasResourceBundle(a,"translation")){const m=await i(a);r.addResourceBundle(a,"translation",m,!0,!0)}await r.changeLanguage(a)},direction:d,i18n:r}),[g,d,r,i]);return F.createElement(T.Provider,{value:u},F.createElement(q,{i18n:r},l))}function ae(o){const s=n.useContext(T),{t:i,i18n:l}=I();return{t:i,language:s?.language||l.language||"en",changeLanguage:s?.changeLanguage||(async r=>{await l.changeLanguage(r)}),direction:s?.direction||"ltr",i18n:l}}const D=n.createContext(null);D.displayName="AuthContext";function ee(o){const{baseURL:s,fetchFn:i=fetch}=o;async function l(r,g){const t=`${s}${r}`,d=await i(t,{...g,headers:{"Content-Type":"application/json",...g?.headers},credentials:"include"});if(!d.ok){const u=await d.json().catch(()=>null),a=u&&typeof u=="object"&&"message"in u?String(u.message):`Auth request failed with status ${d.status}`;throw new Error(a)}return d.json()}return{async signIn(r){return l("/sign-in/email",{method:"POST",body:JSON.stringify(r)})},async signUp(r){return l("/sign-up/email",{method:"POST",body:JSON.stringify(r)})},async signOut(){await l("/sign-out",{method:"POST"})},async getSession(){try{return await l("/get-session",{method:"GET"})}catch{return null}},async forgotPassword(r){await l("/forgot-password",{method:"POST",body:JSON.stringify({email:r})})},async resetPassword(r,g){await l("/reset-password",{method:"POST",body:JSON.stringify({token:r,newPassword:g})})},async updateUser(r){return(await l("/update-user",{method:"POST",body:JSON.stringify(r)})).user}}}function ne({authUrl:o,client:s,onAuthStateChange:i,enabled:l=!0,previewMode:r,children:g}){const t=n.useMemo(()=>s??ee({baseURL:o}),[s,o]),[d,u]=n.useState(null),[a,m]=n.useState(null),[y,v]=n.useState(!0),[S,p]=n.useState(null),f=r!=null,x=l&&!f?d!==null&&a!==null:!0;n.useEffect(()=>{if(f){const c=r.simulatedRole??"admin",w=r.simulatedUserName??"Preview User",j=r.expiresInSeconds??0;u({id:"preview-user",email:"preview@preview.local",name:w,role:c,roles:[c]}),m({token:"preview-token",expiresAt:j>0?new Date(Date.now()+j*1e3):new Date(Date.now()+365*24*60*60*1e3)}),v(!1);return}if(!l){u({id:"guest",email:"guest@local",name:"Guest User"}),m({token:"guest-token",expiresAt:new Date(Date.now()+365*24*60*60*1e3)}),v(!1);return}let h=!1;async function b(){try{const c=await t.getSession();if(h)return;c&&(u(c.user),m(c.session))}catch(c){if(h)return;p(c instanceof Error?c:new Error(String(c)))}finally{h||v(!1)}}return b(),()=>{h=!0}},[t,l,f,r]),n.useEffect(()=>{i?.({user:d,session:a,isAuthenticated:x,isLoading:y,error:S})},[d,a,x,y,S,i]);const C=n.useCallback(async(h,b)=>{v(!0),p(null);try{const c=await t.signIn({email:h,password:b});u(c.user),m(c.session)}catch(c){const w=c instanceof Error?c:new Error(String(c));throw p(w),w}finally{v(!1)}},[t]),E=n.useCallback(async(h,b,c)=>{v(!0),p(null);try{const w=await t.signUp({name:h,email:b,password:c});u(w.user),m(w.session)}catch(w){const j=w instanceof Error?w:new Error(String(w));throw p(j),j}finally{v(!1)}},[t]),k=n.useCallback(async()=>{v(!0);try{await t.signOut(),u(null),m(null),p(null)}catch(h){p(h instanceof Error?h:new Error(String(h)))}finally{v(!1)}},[t]),A=n.useCallback(async h=>{p(null);try{const b=await t.updateUser(h);u(b)}catch(b){const c=b instanceof Error?b:new Error(String(b));throw p(c),c}},[t]),N=n.useCallback(async h=>{p(null);try{await t.forgotPassword(h)}catch(b){const c=b instanceof Error?b:new Error(String(b));throw p(c),c}},[t]),P=n.useCallback(async(h,b)=>{p(null);try{await t.resetPassword(h,b)}catch(c){const w=c instanceof Error?c:new Error(String(c));throw p(w),w}},[t]),O=n.useMemo(()=>({user:d,session:a,isAuthenticated:x,isLoading:y,error:S,isPreviewMode:f,previewMode:f?r:null,signIn:C,signUp:E,signOut:k,updateUser:A,forgotPassword:N,resetPassword:P}),[d,a,x,y,S,f,r,C,E,k,A,N,P]);return e.jsx(D.Provider,{value:O,children:g})}function R(){const o=n.useContext(D);return o||{user:null,session:null,isAuthenticated:!1,isLoading:!1,error:null,isPreviewMode:!1,previewMode:null,signIn:async()=>{throw new Error("useAuth must be used within an AuthProvider")},signUp:async()=>{throw new Error("useAuth must be used within an AuthProvider")},signOut:async()=>{throw new Error("useAuth must be used within an AuthProvider")},updateUser:async()=>{throw new Error("useAuth must be used within an AuthProvider")},forgotPassword:async()=>{throw new Error("useAuth must be used within an AuthProvider")},resetPassword:async()=>{throw new Error("useAuth must be used within an AuthProvider")}}}function se({fallback:o=null,requiredRoles:s,loadingFallback:i,children:l}){const{isAuthenticated:r,isLoading:g,user:t}=R();if(g)return e.jsx(e.Fragment,{children:i??null});if(!r)return e.jsx(e.Fragment,{children:o});if(s&&s.length>0&&t){const d=t.roles??(t.role?[t.role]:[]);if(!s.some(a=>d.includes(a)))return e.jsx(e.Fragment,{children:o})}return e.jsx(e.Fragment,{children:l})}function ie({onSuccess:o,onError:s,registerUrl:i="/register",forgotPasswordUrl:l="/forgot-password",title:r="Sign in to your account",description:g="Enter your email and password to continue"}){const{signIn:t,isLoading:d}=R(),[u,a]=n.useState(""),[m,y]=n.useState(""),[v,S]=n.useState(null),p=async f=>{f.preventDefault(),S(null);try{await t(u,m),o?.()}catch(x){const C=x instanceof Error?x:new Error(String(x));S(C.message),s?.(C)}};return e.jsxs("div",{className:"mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]",children:[e.jsxs("div",{className:"flex flex-col space-y-2 text-center",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:r}),e.jsx("p",{className:"text-sm text-muted-foreground",children:g})]}),e.jsxs("form",{onSubmit:p,className:"space-y-4",children:[v&&e.jsx("div",{className:"rounded-md bg-destructive/15 p-3 text-sm text-destructive",role:"alert",children:v}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"login-email",className:"text-sm font-medium leading-none",children:"Email"}),e.jsx("input",{id:"login-email",type:"email",placeholder:"name@example.com",value:u,onChange:f=>a(f.target.value),required:!0,autoComplete:"email",disabled:d,className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{htmlFor:"login-password",className:"text-sm font-medium leading-none",children:"Password"}),l&&e.jsx("a",{href:l,className:"text-sm text-primary underline-offset-4 hover:underline",children:"Forgot password?"})]}),e.jsx("input",{id:"login-password",type:"password",placeholder:"Enter your password",value:m,onChange:f=>y(f.target.value),required:!0,autoComplete:"current-password",disabled:d,className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"})]}),e.jsx("button",{type:"submit",disabled:d,className:"inline-flex h-10 w-full items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",children:d?"Signing in...":"Sign In"})]}),i&&e.jsxs("p",{className:"px-8 text-center text-sm text-muted-foreground",children:["Don't have an account?"," ",e.jsx("a",{href:i,className:"text-primary underline-offset-4 hover:underline",children:"Sign up"})]})]})}function le({onSuccess:o,onError:s,loginUrl:i="/login",title:l="Create an account",description:r="Enter your information to get started"}){const{signUp:g,isLoading:t}=R(),[d,u]=n.useState(""),[a,m]=n.useState(""),[y,v]=n.useState(""),[S,p]=n.useState(""),[f,x]=n.useState(null),C=async E=>{if(E.preventDefault(),x(null),y!==S){x("Passwords do not match");return}if(y.length<8){x("Password must be at least 8 characters");return}try{await g(d,a,y),o?.()}catch(k){const A=k instanceof Error?k:new Error(String(k));x(A.message),s?.(A)}};return e.jsxs("div",{className:"mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]",children:[e.jsxs("div",{className:"flex flex-col space-y-2 text-center",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:l}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r})]}),e.jsxs("form",{onSubmit:C,className:"space-y-4",children:[f&&e.jsx("div",{className:"rounded-md bg-destructive/15 p-3 text-sm text-destructive",role:"alert",children:f}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"register-name",className:"text-sm font-medium leading-none",children:"Name"}),e.jsx("input",{id:"register-name",type:"text",placeholder:"John Doe",value:d,onChange:E=>u(E.target.value),required:!0,autoComplete:"name",disabled:t,className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"register-email",className:"text-sm font-medium leading-none",children:"Email"}),e.jsx("input",{id:"register-email",type:"email",placeholder:"name@example.com",value:a,onChange:E=>m(E.target.value),required:!0,autoComplete:"email",disabled:t,className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"register-password",className:"text-sm font-medium leading-none",children:"Password"}),e.jsx("input",{id:"register-password",type:"password",placeholder:"Create a password (min. 8 characters)",value:y,onChange:E=>v(E.target.value),required:!0,minLength:8,autoComplete:"new-password",disabled:t,className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"register-confirm-password",className:"text-sm font-medium leading-none",children:"Confirm Password"}),e.jsx("input",{id:"register-confirm-password",type:"password",placeholder:"Confirm your password",value:S,onChange:E=>p(E.target.value),required:!0,minLength:8,autoComplete:"new-password",disabled:t,className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"})]}),e.jsx("button",{type:"submit",disabled:t,className:"inline-flex h-10 w-full items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",children:t?"Creating account...":"Create Account"})]}),i&&e.jsxs("p",{className:"px-8 text-center text-sm text-muted-foreground",children:["Already have an account?"," ",e.jsx("a",{href:i,className:"text-primary underline-offset-4 hover:underline",children:"Sign in"})]})]})}function de({onSuccess:o,onError:s,loginUrl:i="/login",title:l="Reset your password",description:r="Enter your email address and we'll send you a link to reset your password"}){const{forgotPassword:g,isLoading:t}=R(),[d,u]=n.useState(""),[a,m]=n.useState(null),[y,v]=n.useState(!1),S=async p=>{p.preventDefault(),m(null);try{await g(d),v(!0),o?.()}catch(f){const x=f instanceof Error?f:new Error(String(f));m(x.message),s?.(x)}};return y?e.jsxs("div",{className:"mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]",children:[e.jsxs("div",{className:"flex flex-col space-y-2 text-center",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Check your email"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["We've sent a password reset link to ",e.jsx("strong",{children:d}),". Please check your inbox and follow the instructions."]})]}),i&&e.jsx("p",{className:"px-8 text-center text-sm text-muted-foreground",children:e.jsx("a",{href:i,className:"text-primary underline-offset-4 hover:underline",children:"Back to sign in"})})]}):e.jsxs("div",{className:"mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]",children:[e.jsxs("div",{className:"flex flex-col space-y-2 text-center",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:l}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r})]}),e.jsxs("form",{onSubmit:S,className:"space-y-4",children:[a&&e.jsx("div",{className:"rounded-md bg-destructive/15 p-3 text-sm text-destructive",role:"alert",children:a}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"forgot-email",className:"text-sm font-medium leading-none",children:"Email"}),e.jsx("input",{id:"forgot-email",type:"email",placeholder:"name@example.com",value:d,onChange:p=>u(p.target.value),required:!0,autoComplete:"email",disabled:t,className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"})]}),e.jsx("button",{type:"submit",disabled:t,className:"inline-flex h-10 w-full items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",children:t?"Sending...":"Send Reset Link"})]}),i&&e.jsxs("p",{className:"px-8 text-center text-sm text-muted-foreground",children:["Remember your password?"," ",e.jsx("a",{href:i,className:"text-primary underline-offset-4 hover:underline",children:"Sign in"})]})]})}function ce(o){return o?o.name?o.name.split(" ").map(s=>s[0]).join("").toUpperCase().slice(0,2):o.email?.[0]?.toUpperCase()??"?":"?"}function ue({className:o}){const{isPreviewMode:s,previewMode:i}=R();if(!s)return null;const l=i?.bannerMessage??"You are in preview mode.";return e.jsx("div",{role:"status",className:o,style:{padding:"8px 16px",backgroundColor:"#fef3c7",color:"#92400e",textAlign:"center",fontSize:"14px",borderBottom:"1px solid #fcd34d"},children:l})}const V=n.createContext(null);V.displayName="PermissionContext";function me(){const o=n.useContext(V);return o?{...o,can:(s,i)=>o.check(s,i).allowed,cannot:(s,i)=>!o.check(s,i).allowed}:{check:()=>({allowed:!0}),checkField:()=>!0,getFieldPermissions:()=>[],getRowFilter:()=>{},roles:[],isLoaded:!1,can:()=>!0,cannot:()=>!1}}export{ne as A,de as F,oe as I,ie as L,ue as P,le as R,me as a,ae as b,se as c,ce as g,R as u};
|