@augmentd-labs/canvas-web 2.26.36 → 2.26.38

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.
Files changed (38) hide show
  1. package/dist/assets/{CalendarApplet-CI650A38.js → CalendarApplet-7wqNCpcs.js} +1 -1
  2. package/dist/assets/{FiltersApplet-Ia3RTHqt.js → FiltersApplet-Dh4SUfjN.js} +1 -1
  3. package/dist/assets/HomeFab-W7y591CD.js +3 -0
  4. package/dist/assets/{LensApplet-DxqrTTvu.js → LensApplet-CddpZXRw.js} +1 -1
  5. package/dist/assets/{NotesApplet-ALnJx1R5.js → NotesApplet-Cyuirnp1.js} +1 -1
  6. package/dist/assets/{_agentId_-DiuSEd4O.js → _agentId_-Dy7lgkJK.js} +0 -0
  7. package/dist/assets/_contextId_-BBpL3f_T.js +1 -0
  8. package/dist/assets/_workspaceName_-CU-hpvv7.js +1 -0
  9. package/dist/assets/{about-CIz-eZ-8.js → about-Cns4GXCX.js} +1 -1
  10. package/dist/assets/{add-Cf7qavr8.js → add-jGjbB0x1.js} +1 -1
  11. package/dist/assets/{agents-t82sp0lw.js → agents-DsaNiZJc.js} +1 -1
  12. package/dist/assets/{appearance-Ba1GYZ_J.js → appearance-C1xkguK7.js} +1 -1
  13. package/dist/assets/{apps-uPsYOOCl.js → apps-BCy4q37-.js} +1 -1
  14. package/dist/assets/{home-CsrwkvZX.js → home-C8Wq8hsp.js} +1 -1
  15. package/dist/assets/index-Cp75myNf.js +16 -0
  16. package/dist/assets/index-_0FSwEvG.css +2 -0
  17. package/dist/assets/{key-bindings-CnvBrNMZ.js → key-bindings-CA_ePKGA.js} +1 -1
  18. package/dist/assets/{registry-9MElXU-U.js → registry-QDfCL8gg.js} +2 -2
  19. package/dist/assets/{settings-DxEF5yL8.js → settings-Bz400KLm.js} +3 -3
  20. package/dist/assets/{settings-Dkb35vRa.js → settings-aOogFA9n.js} +1 -1
  21. package/dist/assets/{settings-B9-XHGdl.js → settings-jIm9JVC-.js} +1 -1
  22. package/dist/assets/settings-tgfewl6I.js +1 -0
  23. package/dist/assets/{share-target-DJICHfZZ.js → share-target-cRZICq5X.js} +1 -1
  24. package/dist/assets/{shared-DmdHUnl7.js → shared-eIOEFQRM.js} +1 -1
  25. package/dist/assets/tree-folders-cmsIS19Z.js +1 -0
  26. package/dist/assets/{useAgentModels-BjT4oN4e.js → useAgentModels-B10Tbl6D.js} +1 -1
  27. package/dist/assets/workspaces-DC19HlpI.js +1 -0
  28. package/dist/index.html +3 -3
  29. package/dist/sw.js +1 -1
  30. package/package.json +2 -2
  31. package/dist/assets/HomeFab-CXuEjvlA.js +0 -3
  32. package/dist/assets/_contextId_-Bovrvd2T.js +0 -1
  33. package/dist/assets/_workspaceName_-DXYHTbna.js +0 -1
  34. package/dist/assets/content-app-view-DfmmWQ_z.js +0 -1
  35. package/dist/assets/index-C51Jk0Xq.css +0 -2
  36. package/dist/assets/index-DRHEGJ8I.js +0 -16
  37. package/dist/assets/settings-CUxtVfMx.js +0 -1
  38. package/dist/assets/workspaces-DpVuDD1E.js +0 -1
@@ -1,2 +1,2 @@
1
- import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{g as r,r as i}from"./chunk-62JRHF6Z-vspAGgtK.js";import{Fr as a,Hr as o,Jr as s,L as c,Ot as l,Pt as u,Vr as d,X as f,ct as p,et as m,fr as h,jr as g,mr as _,pn as v,qr as y,vn as b}from"./ui-CDoK3F3U.js";import{t as x}from"./utils-2pl1SbIp.js";import{h as S}from"./LinkToCard-BQ1yoFDr.js";import{Hn as C,In as w,St as T,jt as E,rt as D,vn as O,w as k,wn as A}from"./workspace-BJELPCNs.js";import{o as ee,t as j}from"./useAddTarget-B3b6TyZr.js";import{a as M,o as N}from"./context-DZ1Hn7tt.js";import{n as P,o as F,s as I,t as L}from"./date-time-picker-txVhlNO0.js";import{n as te}from"./use-applet-target-ffIGaAqT.js";import{y as R}from"./index-DRHEGJ8I.js";import{r as ne,t as re}from"./shared-BnpwVpxG.js";var z=e(n(),1),ie=864e5,ae=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function B(e){return String(e).padStart(2,`0`)}function V(e){return`${e.getFullYear()}-${B(e.getMonth()+1)}-${B(e.getDate())}`}function H(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(t,n-1,r)}function oe(e){return`${V(e)}T${B(e.getHours())}:${B(e.getMinutes())}`}function U(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function W(e,t){return new Date(e.getFullYear(),e.getMonth(),e.getDate()+t,e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}function se(e,t){return new Date(e.getFullYear(),e.getMonth()+t,1)}function ce(e){let t=U(e);return W(t,-((t.getDay()+6)%7))}function le(e){return new Date(e.getFullYear(),e.getMonth(),1)}function G(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function K(e){let t=ce(le(e));return Array.from({length:42},(e,n)=>W(t,n))}function q(e,t){let n=[],r=t.getTime()>e.getTime()?new Date(t.getTime()-1):e;for(let t=U(e);t.getTime()<=r.getTime();t=W(t,1))n.push(t);return n}function J(e,t){let n=e.getTime()-U(t).getTime();return Math.max(0,Math.min(ie,n))/6e4}var ue=new Intl.DateTimeFormat(void 0,{month:`long`,year:`numeric`}),Y=new Intl.DateTimeFormat(void 0,{month:`short`}),de=new Intl.DateTimeFormat(void 0,{weekday:`long`,day:`numeric`,month:`long`,year:`numeric`}),X=new Intl.DateTimeFormat(void 0,{weekday:`short`,day:`numeric`,month:`short`}),fe=new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`});function pe(e){return ue.format(e)}function me(e){return Y.format(e)}function he(e){return de.format(e)}function ge(e){return X.format(e)}function Z(e){return fe.format(e)}function _e(e,t){return G(e,t)?he(e):e.getFullYear()===t.getFullYear()?e.getMonth()===t.getMonth()?`${e.getDate()} – ${t.getDate()} ${Y.format(e)} ${e.getFullYear()}`:`${e.getDate()} ${Y.format(e)} – ${t.getDate()} ${Y.format(t)} ${t.getFullYear()}`:`${e.getDate()} ${Y.format(e)} ${e.getFullYear()} – ${t.getDate()} ${Y.format(t)} ${t.getFullYear()}`}function ve(e){return _e(e,W(e,6))}function ye(e){return fe.format(new Date(2e3,0,1,e,0)).replace(/:00(?=\s|$)/,``)}var be={SU:0,MO:1,TU:2,WE:3,TH:4,FR:5,SA:6},xe=new Set([`FREQ`,`INTERVAL`,`COUNT`,`UNTIL`,`BYDAY`,`BYMONTHDAY`,`BYMONTH`,`WKST`]);function Se(e){let t={};for(let n of e.replace(/^RRULE:/i,``).split(`;`)){let e=n.trim();if(!e)continue;let r=e.indexOf(`=`);if(r<1)return null;t[e.slice(0,r).toUpperCase()]=e.slice(r+1).toUpperCase()}if(Object.keys(t).some(e=>!xe.has(e)))return null;let n=t.FREQ;if(n!==`DAILY`&&n!==`WEEKLY`&&n!==`MONTHLY`&&n!==`YEARLY`)return null;let r=t.INTERVAL?Number(t.INTERVAL):1;if(!Number.isInteger(r)||r<1)return null;let i=t.COUNT?Number(t.COUNT):null;if(i!==null&&(!Number.isInteger(i)||i<1))return null;let a=null;if(t.UNTIL){let e=/^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z?))?$/.exec(t.UNTIL);if(!e)return null;let[,n,r,i,o,s,c,l]=e;if(a=o===void 0?new Date(Number(n),Number(r)-1,Number(i),23,59,59,999):l?new Date(Date.UTC(Number(n),Number(r)-1,Number(i),Number(o),Number(s),Number(c))):new Date(Number(n),Number(r)-1,Number(i),Number(o),Number(s),Number(c)),Number.isNaN(a.getTime()))return null}let o=[];if(t.BYDAY)for(let e of t.BYDAY.split(`,`)){let t=/^([+-]?\d{1,2})?(SU|MO|TU|WE|TH|FR|SA)$/.exec(e.trim());if(!t)return null;o.push({day:be[t[2]],ordinal:t[1]?Number(t[1]):null})}let s=t.BYMONTHDAY?t.BYMONTHDAY.split(`,`).map(Number):[];if(s.some(e=>!Number.isInteger(e)||e===0||e<-31||e>31))return null;let c=t.BYMONTH?t.BYMONTH.split(`,`).map(Number):[];return c.some(e=>!Number.isInteger(e)||e<1||e>12)||o.some(e=>e.ordinal!==null)&&n!==`MONTHLY`&&n!==`YEARLY`?null:{freq:n,interval:r,count:i,until:a,byDay:o,byMonthDay:s,byMonth:c}}function Ce(e,t){return new Date(e.getFullYear(),e.getMonth(),e.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds())}function we(e,t){return new Date(e,t+1,0).getDate()}function Te(e,t,n,r){let i=we(e,t),a=new Set;if(n.byMonthDay.length)for(let e of n.byMonthDay){let t=e>0?e:i+1+e;t>=1&&t<=i&&a.add(t)}if(n.byDay.length){let r=new Set;for(let{day:a,ordinal:o}of n.byDay){let n=[];for(let r=1;r<=i;r++)new Date(e,t,r).getDay()===a&&n.push(r);if(o===null)n.forEach(e=>r.add(e));else{let e=o>0?n[o-1]:n[n.length+o];e&&r.add(e)}}if(n.byMonthDay.length)for(let e of[...a])r.has(e)||a.delete(e);else r.forEach(e=>a.add(e))}return!n.byMonthDay.length&&!n.byDay.length&&r.getDate()<=i&&a.add(r.getDate()),[...a].sort((e,t)=>e-t).map(n=>Ce(new Date(e,t,n),r))}function Ee(e,t,n,r,i=0,a=5e3){let o=[],s=n.getTime()-Math.max(0,i),c=r.getTime(),l=0,u=t=>{let n=t.getTime();return e.until&&n>e.until.getTime()||(l++,n>=s&&n<c&&o.push(t),e.count!==null&&l>=e.count)?!1:l<a};if(!u(t))return o;let d=t.getTime();if(e.freq===`DAILY`){for(let n=e.interval,r=0;r<a*12;n+=e.interval,r++){let r=Ce(new Date(t.getFullYear(),t.getMonth(),t.getDate()+n),t);if(r.getTime()>=c&&e.count===null||!(e.byMonth.length&&!e.byMonth.includes(r.getMonth()+1))&&!u(r))break}return o}if(e.freq===`WEEKLY`){let n=e.byDay.length?[...new Set(e.byDay.map(e=>e.day))]:[t.getDay()],r=new Date(t.getFullYear(),t.getMonth(),t.getDate()-(t.getDay()+6)%7);for(let i=0;;i+=e.interval){let a=new Date(r.getFullYear(),r.getMonth(),r.getDate()+i*7);if(a.getTime()>=c+6048e5&&e.count===null)break;let o=!1;for(let e=0;e<7;e++){let r=new Date(a.getFullYear(),a.getMonth(),a.getDate()+e);if(!n.includes(r.getDay()))continue;let i=Ce(r,t);if(!(i.getTime()<=d)&&!u(i)){o=!0;break}}if(o)break}return o}let f=e.freq===`MONTHLY`?e.interval:12*e.interval;for(let n=0;;n+=f){let r=t.getFullYear()+Math.floor((t.getMonth()+n)/12),i=(t.getMonth()+n)%12;if(new Date(r,i,1).getTime()>=c&&e.count===null)break;if(e.freq===`YEARLY`&&e.byMonth.length&&!e.byMonth.includes(i+1)){let n=!1;for(let i of e.byMonth){for(let a of Te(r,i-1,e,t))if(!(a.getTime()<=d)&&!u(a)){n=!0;break}if(n)break}if(n)break;continue}if(e.freq===`MONTHLY`&&e.byMonth.length&&!e.byMonth.includes(i+1))continue;let a=!1;for(let n of Te(r,i,e,t))if(!(n.getTime()<=d)&&!u(n)){a=!0;break}if(a||n>4800)break}return o}function De(e){let t={DAILY:`day`,WEEKLY:`week`,MONTHLY:`month`,YEARLY:`year`}[e.freq],n=e.interval===1?`Every ${t}`:`Every ${e.interval} ${t}s`,r=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];return e.byDay.length?n+=` on `+e.byDay.map(({day:e,ordinal:t})=>t===null?r[e]:`${t===-1?`last`:`${t}.`} ${r[e]}`).join(`, `):e.byMonthDay.length&&(n+=` on day `+e.byMonthDay.join(`, `)),e.count!==null&&(n+=`, ${e.count} times`),e.until&&(n+=` until ${e.until.toLocaleDateString(void 0,{day:`numeric`,month:`short`,year:`numeric`})}`),n}function Oe(e){if(!e)return`none`;let t=Se(e);return!t||t.interval!==1||t.byMonthDay.length||t.byMonth.length?`custom`:t.freq===`WEEKLY`&&t.byDay.length===5&&t.byDay.every(e=>e.ordinal===null&&e.day>=1&&e.day<=5)?`weekdays`:t.byDay.length?`custom`:{DAILY:`daily`,WEEKLY:`weekly`,MONTHLY:`monthly`,YEARLY:`yearly`}[t.freq]}function ke(e,t){let n={daily:`FREQ=DAILY`,weekly:`FREQ=WEEKLY`,monthly:`FREQ=MONTHLY`,yearly:`FREQ=YEARLY`,weekdays:`FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR`}[e];if(n)return t?.until?`${n};UNTIL=${t.until.replace(/-/g,``)}`:t?.count?`${n};COUNT=${t.count}`:n}function Ae(e){let t=e?Se(e):null;if(!t)return{until:``,count:null};let n=t.until,r=e=>String(e).padStart(2,`0`);return{until:n?`${n.getFullYear()}-${r(n.getMonth()+1)}-${r(n.getDate())}`:``,count:t.count}}var je=`tasks`,Me=`data/schema/event`,Ne=`data/schema/task`;function Pe(e){if(typeof e!=`string`||!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}function Fe(e){return new Date(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())}function Ie(e){return e.schema.startsWith(Me)}function Le(e){return e.schema===Ne}function Re(e,t,n){let r=e.data??{};if(Le(e)){let i=Pe(r.dueDate);if(!i||i<t||i>=n)return[];let a=String(r.status??`pending`);return[{key:`${e.id}@${i.getTime()}`,doc:e,kind:`task`,title:String(r.title??`Untitled`),start:i,end:i,allDay:!1,calendar:je,recurring:!1,unsupportedRule:!1,done:a===`completed`||a===`cancelled`}]}if(!Ie(e))return[];let i=Pe(r.start);if(!i)return[];let a=r.allDay===!0,o=r.end===null?null:Pe(r.end),s=a?Fe(i):i,c=a?o?Fe(o):W(s,1):o??(r.end===null?n:s),l=Math.max(0,c.getTime()-s.getTime()),u={doc:e,kind:`event`,title:String(r.title??`Untitled`),allDay:a,calendar:typeof r.calendar==`string`?r.calendar:``,done:!1},d=typeof r.recurrence==`string`?r.recurrence:``;if(!d)return c.getTime()<=t.getTime()&&!(c.getTime()===s.getTime()&&s>=t)||s>=n?[]:[{...u,key:`${e.id}@${s.getTime()}`,start:s,end:c,recurring:!1,unsupportedRule:!1}];let f=Se(d);return f?Ee(f,s,t,n,l).map(t=>({...u,key:`${e.id}@${t.getTime()}`,start:t,end:new Date(t.getTime()+l),recurring:!0,unsupportedRule:!1})):c<=t||s>=n?[]:[{...u,key:`${e.id}@${s.getTime()}`,start:s,end:c,recurring:!0,unsupportedRule:!0}]}function ze(e,t,n){return e.flatMap(e=>Re(e,t,n)).sort((e,t)=>e.start.getTime()-t.start.getTime()||t.end.getTime()-e.end.getTime()||e.title.localeCompare(t.title))}function Be(e){let t=new Map;for(let n of e)for(let e of q(n.start,n.end)){let r=`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`,i=t.get(r);i?i.push(n):t.set(r,[n])}return t}function Ve(e){return e.allDay||e.end.getTime()-e.start.getTime()>=864e5||!G(e.start,new Date(e.end.getTime()-1))&&e.end.getTime()>e.start.getTime()}function He(e,t,n=30){let r=U(e),i=t.filter(e=>!Ve(e)).map(e=>{let t=J(e.start,r),i=Math.max(n,J(e.end,r)-t);return{occurrence:e,top:t,height:Math.min(i,1440-t),column:0,columns:1}}).sort((e,t)=>e.top-t.top||t.height-e.height),a=[],o=-1,s=()=>{let e=[];for(let t of a){let n=e.findIndex(e=>e<=t.top);n<0&&(n=e.length,e.push(0)),e[n]=t.top+t.height,t.column=n}for(let t of a)t.columns=e.length;a=[]};for(let e of i)a.length&&e.top>=o&&s(),a.push(e),o=Math.max(o,e.top+e.height);return a.length&&s(),i}function Ue(e,t,n,r){if(t.kind===`task`)return{...e,dueDate:n.toISOString()};if(t.allDay)return{...e,start:`${V(n)}T00:00:00.000Z`,end:`${V(r)}T00:00:00.000Z`};let i={...e,start:n.toISOString()};return e.end===null||(r.getTime()>n.getTime()?i.end=r.toISOString():delete i.end),i}var We=[{id:`day`,label:`Day`,key:`d`},{id:`week`,label:`Week`,key:`w`},{id:`month`,label:`Month`,key:`m`},{id:`year`,label:`Year`,key:`y`},{id:`schedule`,label:`Schedule`,key:`s`}],Ge={view:`week`,hidden:[],showTasks:!0,defaultCalendar:`Personal`},Ke=`canvas:calendar:prefs`;function qe(e){return`${Ke}:${e??`global`}`}function Je(e){try{let t=JSON.parse(localStorage.getItem(qe(e))||`null`);if(!t||typeof t!=`object`)return Ge;let n=t;return{view:We.some(e=>e.id===n.view)?n.view:Ge.view,hidden:Array.isArray(n.hidden)?n.hidden.filter(e=>typeof e==`string`):[],showTasks:n.showTasks!==!1,defaultCalendar:typeof n.defaultCalendar==`string`&&n.defaultCalendar.trim()?n.defaultCalendar:Ge.defaultCalendar}}catch{return Ge}}function Ye(e,t){try{localStorage.setItem(qe(e),JSON.stringify(t))}catch{}}function Xe(e,t){let n=V(W(U(e),-1)),r=V(W(U(t),1));return{events:`t:events:${n}..${r}`,tasks:`t:tasks:${n}..${r}`}}var Ze=5e3;function Qe(e){return!!e&&!e.includes(`:`)&&![`content`,`events`,`tasks`].includes(e.toLowerCase())}function $e(e){return e?e.mode===`context`?`ctx:${e.contextId}`:`${e.workspaceName}:${e.treeName}:${e.treeType}:${e.path}`:``}function et(e,t,n,r){let[i,a]=(0,z.useState)([]),[o,s]=(0,z.useState)(!1),[c,l]=(0,z.useState)(null),[u,d]=(0,z.useState)(null),[f,p]=(0,z.useState)([]),m=t.getTime(),h=n.getTime(),g=(0,z.useCallback)(()=>{if(!e)return Promise.resolve();let t=Xe(new Date(m),new Date(h));return(e.mode===`context`?Promise.all([N(e.contextId,[w],[t.events],{limit:Ze}),r?N(e.contextId,[C],[t.tasks],{limit:Ze}):Promise.resolve([]),M(e.contextId)]).then(([e,t,n])=>{a([...e,...t]);let r=n.workspaceName||n.workspaceId;d(r?{workspaceName:r,path:n.path||`/`,treeName:n.treeId||`context`,treeType:`context`}:null)}):(()=>{let{workspaceName:n,path:i,treeName:o,treeType:s}=e,c={treeName:o,treeType:s,limit:0};return Promise.all([D(n,i,[w],{...c,filters:[t.events]}),r?D(n,i,[C],{...c,filters:[t.tasks]}):Promise.resolve({payload:[]})]).then(([e,t])=>{a([...e.payload||[],...t.payload||[]]),d({workspaceName:n,path:i,treeName:o,treeType:s})})})()).catch(e=>l(e instanceof Error?e.message:`Failed to load calendar`)).finally(()=>s(!1))},[e,m,h,r]),_=(0,z.useCallback)(async()=>{if(!e){a([]),d(null);return}s(!0),l(null),await g()},[e,g]),[v,y]=(0,z.useState)(null),b=`${$e(e)}|${m}|${h}|${r}`;v!==b&&(y(b),e?(s(!0),l(null)):(a([]),d(null))),(0,z.useEffect)(()=>{g()},[g]),(0,z.useEffect)(()=>{let e=()=>{_()};return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[_]);let x=u?.workspaceName??null,S=(0,z.useCallback)(()=>x?Promise.all([T(x),E(x)]).then(([e,t])=>{let n=new Set;for(let t of e)t.startsWith(`data/calendar/`)&&t.length>14&&n.add(t.slice(14));for(let e of t)Qe(e.name)&&n.add(e.name);p([...n].sort())}).catch(()=>{}):Promise.resolve(),[x]);(0,z.useEffect)(()=>{S()},[S,i.length]),(0,z.useEffect)(()=>{let e=()=>{S()};return window.addEventListener(`workspace:timelines:changed`,e),()=>window.removeEventListener(`workspace:timelines:changed`,e)},[S]);let O=(0,z.useCallback)(async e=>{if(!u)throw Error(`No workspace scope resolved`);await k(u.workspaceName,[e],u.path,[],u.treeName,u.treeType),a(t=>t.filter(t=>t.id!==e))},[u]),A=(0,z.useCallback)(e=>{a(t=>t.some(t=>t.id===e.id)?t.map(t=>t.id===e.id?e:t):[...t,e])},[]);return(0,z.useMemo)(()=>({docs:i,loading:o,error:c,scope:u,knownCalendars:f,reload:_,removeDoc:O,patchDoc:A}),[i,o,c,u,f,_,O,A])}function tt(e){return R(e?e.toLowerCase():`events`)}function nt(e){return e.kind===`task`?R(je):tt(e.calendar)}function rt(e,t=18){return`color-mix(in oklch, ${e} ${t}%, transparent)`}function it(e,t,n,r,i,a=30){let o=Math.max(0,Math.min(e.length-1,t)),s=Math.max(0,Math.min(e.length-1,r));if(o!==s){let[t,n]=o<s?[o,s]:[s,o];return{start:U(e[t]),end:W(U(e[n]),1),allDay:!0}}let c=e=>Math.floor(e/a)*a,l=c(Math.min(n,i)),u=c(Math.max(n,i))+a;l=Math.max(0,Math.min(1440-a,l)),u=Math.max(l+a,Math.min(1440,u));let d=U(e[o]);return{start:new Date(d.getTime()+l*6e4),end:new Date(d.getTime()+u*6e4),allDay:!1}}function at(e,t){let[n,r]=e.getTime()<=t.getTime()?[e,t]:[t,e];return{start:U(n),end:W(U(r),1),allDay:!0}}function ot(e,t,n,r,i,a,o=15){let s=t=>Math.max(0,Math.min(e.length-1,t)),c=s(i)-s(n),l=Math.round((a-r)/o)*o,u=t.end.getTime()-t.start.getTime(),d=W(t.start,c),f=U(d),p=Math.max(0,Math.min(1440-o,(d.getTime()-f.getTime())/6e4+l)),m=new Date(f.getTime()+p*6e4);return{start:m,end:new Date(m.getTime()+u)}}function st(e,t,n,r,i=15){let a=U(e[Math.max(0,Math.min(e.length-1,n))]),o=Math.min(1440,Math.ceil(r/i)*i),s=new Date(a.getTime()+o*6e4);return{start:t.start,end:s.getTime()<t.start.getTime()+i*6e4?new Date(t.start.getTime()+i*6e4):s}}function ct(e,t){return{start:W(e.start,t),end:W(e.end,t)}}var Q=t();function lt({month:e,selection:t,marks:n,onPick:r,onPickRange:i,onPrev:a,onNext:s,onTitle:c,onDayMenu:l,title:u,className:f}){let p=new Date,m=K(e),h=u??pe(e),[g,_]=(0,z.useState)(null),v=(0,z.useRef)(g);(0,z.useEffect)(()=>{v.current=g});let y=e=>(document.elementFromPoint(e.clientX,e.clientY)?.closest(`[data-day]`))?.dataset.day??null,b=e=>{if(!i||e.button!==0)return;let t=y(e);t&&(e.currentTarget.setPointerCapture(e.pointerId),_({from:t,to:t}))},S=e=>{if(!v.current)return;let t=y(e);t&&t!==v.current.to&&_({...v.current,to:t})},C=e=>{let t=v.current;if(!t)return;if(e.currentTarget.releasePointerCapture(e.pointerId),_(null),t.from===t.to){w(e,H(t.from));return}let n=at(H(t.from),H(t.to));i?.(n.start,n.end)},w=(e,n)=>{if(e.shiftKey&&i&&t){let e=at(t.start,n);i(e.start,e.end)}else r(n)},T=g?at(H(g.from),H(g.to)):t;return(0,Q.jsxs)(`div`,{className:x(`select-none`,f),children:[(0,Q.jsxs)(`div`,{className:`mb-1 flex items-center justify-between`,children:[a?(0,Q.jsx)(`button`,{type:`button`,onClick:a,className:`rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground`,"aria-label":`Previous month`,children:(0,Q.jsx)(o,{className:`h-3.5 w-3.5`})}):(0,Q.jsx)(`span`,{}),c?(0,Q.jsx)(`button`,{type:`button`,onClick:c,className:`text-xs font-semibold hover:underline`,children:h}):(0,Q.jsx)(`span`,{className:`text-xs font-semibold`,children:h}),s?(0,Q.jsx)(`button`,{type:`button`,onClick:s,className:`rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground`,"aria-label":`Next month`,children:(0,Q.jsx)(d,{className:`h-3.5 w-3.5`})}):(0,Q.jsx)(`span`,{})]}),(0,Q.jsx)(`div`,{className:`grid grid-cols-7 text-center text-[10px] text-muted-foreground`,children:ae.map(e=>(0,Q.jsx)(`span`,{children:e[0]},e))}),(0,Q.jsx)(`div`,{className:x(`grid grid-cols-7 gap-y-px text-center text-[11px]`,g&&`cursor-crosshair`),onPointerDown:b,onPointerMove:S,onPointerUp:C,onPointerCancel:()=>_(null),children:m.map(t=>{let r=V(t),a=t.getMonth()===e.getMonth(),o=G(t,p),s=!!T&&t>=T.start&&t<T.end,c=!!T&&s&&G(t,T.start),u=!!T&&s&&G(t,new Date(T.end.getTime()-1)),d=n?.get(r)??[],f=[...new Set(d.map(nt))].slice(0,3);return(0,Q.jsxs)(`button`,{type:`button`,"data-day":r,onClick:e=>{(e.detail===0||!i)&&w(e,t)},onContextMenu:l?e=>{e.preventDefault(),l(e,t)}:void 0,"aria-label":d.length?`${t.toDateString()}, ${d.length} ${d.length===1?`entry`:`entries`}`:t.toDateString(),title:d.length?d.slice(0,6).map(e=>e.title).join(`
1
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{g as r,r as i}from"./chunk-62JRHF6Z-vspAGgtK.js";import{Fr as a,Hr as o,Jr as s,L as c,Ot as l,Pt as u,Vr as d,X as f,ct as p,et as m,fr as h,jr as g,mr as _,pn as v,qr as y,vn as b}from"./ui-CDoK3F3U.js";import{t as x}from"./utils-2pl1SbIp.js";import{h as S}from"./LinkToCard-BQ1yoFDr.js";import{Hn as C,In as w,St as T,jt as E,rt as D,vn as O,w as k,wn as A}from"./workspace-BJELPCNs.js";import{o as ee,t as j}from"./useAddTarget-B3b6TyZr.js";import{a as M,o as N}from"./context-DZ1Hn7tt.js";import{n as P,o as F,s as I,t as L}from"./date-time-picker-txVhlNO0.js";import{n as te}from"./use-applet-target-ffIGaAqT.js";import{y as R}from"./index-Cp75myNf.js";import{r as ne,t as re}from"./shared-BnpwVpxG.js";var z=e(n(),1),ie=864e5,ae=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function B(e){return String(e).padStart(2,`0`)}function V(e){return`${e.getFullYear()}-${B(e.getMonth()+1)}-${B(e.getDate())}`}function H(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(t,n-1,r)}function oe(e){return`${V(e)}T${B(e.getHours())}:${B(e.getMinutes())}`}function U(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function W(e,t){return new Date(e.getFullYear(),e.getMonth(),e.getDate()+t,e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}function se(e,t){return new Date(e.getFullYear(),e.getMonth()+t,1)}function ce(e){let t=U(e);return W(t,-((t.getDay()+6)%7))}function le(e){return new Date(e.getFullYear(),e.getMonth(),1)}function G(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function K(e){let t=ce(le(e));return Array.from({length:42},(e,n)=>W(t,n))}function q(e,t){let n=[],r=t.getTime()>e.getTime()?new Date(t.getTime()-1):e;for(let t=U(e);t.getTime()<=r.getTime();t=W(t,1))n.push(t);return n}function J(e,t){let n=e.getTime()-U(t).getTime();return Math.max(0,Math.min(ie,n))/6e4}var ue=new Intl.DateTimeFormat(void 0,{month:`long`,year:`numeric`}),Y=new Intl.DateTimeFormat(void 0,{month:`short`}),de=new Intl.DateTimeFormat(void 0,{weekday:`long`,day:`numeric`,month:`long`,year:`numeric`}),X=new Intl.DateTimeFormat(void 0,{weekday:`short`,day:`numeric`,month:`short`}),fe=new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`});function pe(e){return ue.format(e)}function me(e){return Y.format(e)}function he(e){return de.format(e)}function ge(e){return X.format(e)}function Z(e){return fe.format(e)}function _e(e,t){return G(e,t)?he(e):e.getFullYear()===t.getFullYear()?e.getMonth()===t.getMonth()?`${e.getDate()} – ${t.getDate()} ${Y.format(e)} ${e.getFullYear()}`:`${e.getDate()} ${Y.format(e)} – ${t.getDate()} ${Y.format(t)} ${t.getFullYear()}`:`${e.getDate()} ${Y.format(e)} ${e.getFullYear()} – ${t.getDate()} ${Y.format(t)} ${t.getFullYear()}`}function ve(e){return _e(e,W(e,6))}function ye(e){return fe.format(new Date(2e3,0,1,e,0)).replace(/:00(?=\s|$)/,``)}var be={SU:0,MO:1,TU:2,WE:3,TH:4,FR:5,SA:6},xe=new Set([`FREQ`,`INTERVAL`,`COUNT`,`UNTIL`,`BYDAY`,`BYMONTHDAY`,`BYMONTH`,`WKST`]);function Se(e){let t={};for(let n of e.replace(/^RRULE:/i,``).split(`;`)){let e=n.trim();if(!e)continue;let r=e.indexOf(`=`);if(r<1)return null;t[e.slice(0,r).toUpperCase()]=e.slice(r+1).toUpperCase()}if(Object.keys(t).some(e=>!xe.has(e)))return null;let n=t.FREQ;if(n!==`DAILY`&&n!==`WEEKLY`&&n!==`MONTHLY`&&n!==`YEARLY`)return null;let r=t.INTERVAL?Number(t.INTERVAL):1;if(!Number.isInteger(r)||r<1)return null;let i=t.COUNT?Number(t.COUNT):null;if(i!==null&&(!Number.isInteger(i)||i<1))return null;let a=null;if(t.UNTIL){let e=/^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z?))?$/.exec(t.UNTIL);if(!e)return null;let[,n,r,i,o,s,c,l]=e;if(a=o===void 0?new Date(Number(n),Number(r)-1,Number(i),23,59,59,999):l?new Date(Date.UTC(Number(n),Number(r)-1,Number(i),Number(o),Number(s),Number(c))):new Date(Number(n),Number(r)-1,Number(i),Number(o),Number(s),Number(c)),Number.isNaN(a.getTime()))return null}let o=[];if(t.BYDAY)for(let e of t.BYDAY.split(`,`)){let t=/^([+-]?\d{1,2})?(SU|MO|TU|WE|TH|FR|SA)$/.exec(e.trim());if(!t)return null;o.push({day:be[t[2]],ordinal:t[1]?Number(t[1]):null})}let s=t.BYMONTHDAY?t.BYMONTHDAY.split(`,`).map(Number):[];if(s.some(e=>!Number.isInteger(e)||e===0||e<-31||e>31))return null;let c=t.BYMONTH?t.BYMONTH.split(`,`).map(Number):[];return c.some(e=>!Number.isInteger(e)||e<1||e>12)||o.some(e=>e.ordinal!==null)&&n!==`MONTHLY`&&n!==`YEARLY`?null:{freq:n,interval:r,count:i,until:a,byDay:o,byMonthDay:s,byMonth:c}}function Ce(e,t){return new Date(e.getFullYear(),e.getMonth(),e.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds())}function we(e,t){return new Date(e,t+1,0).getDate()}function Te(e,t,n,r){let i=we(e,t),a=new Set;if(n.byMonthDay.length)for(let e of n.byMonthDay){let t=e>0?e:i+1+e;t>=1&&t<=i&&a.add(t)}if(n.byDay.length){let r=new Set;for(let{day:a,ordinal:o}of n.byDay){let n=[];for(let r=1;r<=i;r++)new Date(e,t,r).getDay()===a&&n.push(r);if(o===null)n.forEach(e=>r.add(e));else{let e=o>0?n[o-1]:n[n.length+o];e&&r.add(e)}}if(n.byMonthDay.length)for(let e of[...a])r.has(e)||a.delete(e);else r.forEach(e=>a.add(e))}return!n.byMonthDay.length&&!n.byDay.length&&r.getDate()<=i&&a.add(r.getDate()),[...a].sort((e,t)=>e-t).map(n=>Ce(new Date(e,t,n),r))}function Ee(e,t,n,r,i=0,a=5e3){let o=[],s=n.getTime()-Math.max(0,i),c=r.getTime(),l=0,u=t=>{let n=t.getTime();return e.until&&n>e.until.getTime()||(l++,n>=s&&n<c&&o.push(t),e.count!==null&&l>=e.count)?!1:l<a};if(!u(t))return o;let d=t.getTime();if(e.freq===`DAILY`){for(let n=e.interval,r=0;r<a*12;n+=e.interval,r++){let r=Ce(new Date(t.getFullYear(),t.getMonth(),t.getDate()+n),t);if(r.getTime()>=c&&e.count===null||!(e.byMonth.length&&!e.byMonth.includes(r.getMonth()+1))&&!u(r))break}return o}if(e.freq===`WEEKLY`){let n=e.byDay.length?[...new Set(e.byDay.map(e=>e.day))]:[t.getDay()],r=new Date(t.getFullYear(),t.getMonth(),t.getDate()-(t.getDay()+6)%7);for(let i=0;;i+=e.interval){let a=new Date(r.getFullYear(),r.getMonth(),r.getDate()+i*7);if(a.getTime()>=c+6048e5&&e.count===null)break;let o=!1;for(let e=0;e<7;e++){let r=new Date(a.getFullYear(),a.getMonth(),a.getDate()+e);if(!n.includes(r.getDay()))continue;let i=Ce(r,t);if(!(i.getTime()<=d)&&!u(i)){o=!0;break}}if(o)break}return o}let f=e.freq===`MONTHLY`?e.interval:12*e.interval;for(let n=0;;n+=f){let r=t.getFullYear()+Math.floor((t.getMonth()+n)/12),i=(t.getMonth()+n)%12;if(new Date(r,i,1).getTime()>=c&&e.count===null)break;if(e.freq===`YEARLY`&&e.byMonth.length&&!e.byMonth.includes(i+1)){let n=!1;for(let i of e.byMonth){for(let a of Te(r,i-1,e,t))if(!(a.getTime()<=d)&&!u(a)){n=!0;break}if(n)break}if(n)break;continue}if(e.freq===`MONTHLY`&&e.byMonth.length&&!e.byMonth.includes(i+1))continue;let a=!1;for(let n of Te(r,i,e,t))if(!(n.getTime()<=d)&&!u(n)){a=!0;break}if(a||n>4800)break}return o}function De(e){let t={DAILY:`day`,WEEKLY:`week`,MONTHLY:`month`,YEARLY:`year`}[e.freq],n=e.interval===1?`Every ${t}`:`Every ${e.interval} ${t}s`,r=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];return e.byDay.length?n+=` on `+e.byDay.map(({day:e,ordinal:t})=>t===null?r[e]:`${t===-1?`last`:`${t}.`} ${r[e]}`).join(`, `):e.byMonthDay.length&&(n+=` on day `+e.byMonthDay.join(`, `)),e.count!==null&&(n+=`, ${e.count} times`),e.until&&(n+=` until ${e.until.toLocaleDateString(void 0,{day:`numeric`,month:`short`,year:`numeric`})}`),n}function Oe(e){if(!e)return`none`;let t=Se(e);return!t||t.interval!==1||t.byMonthDay.length||t.byMonth.length?`custom`:t.freq===`WEEKLY`&&t.byDay.length===5&&t.byDay.every(e=>e.ordinal===null&&e.day>=1&&e.day<=5)?`weekdays`:t.byDay.length?`custom`:{DAILY:`daily`,WEEKLY:`weekly`,MONTHLY:`monthly`,YEARLY:`yearly`}[t.freq]}function ke(e,t){let n={daily:`FREQ=DAILY`,weekly:`FREQ=WEEKLY`,monthly:`FREQ=MONTHLY`,yearly:`FREQ=YEARLY`,weekdays:`FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR`}[e];if(n)return t?.until?`${n};UNTIL=${t.until.replace(/-/g,``)}`:t?.count?`${n};COUNT=${t.count}`:n}function Ae(e){let t=e?Se(e):null;if(!t)return{until:``,count:null};let n=t.until,r=e=>String(e).padStart(2,`0`);return{until:n?`${n.getFullYear()}-${r(n.getMonth()+1)}-${r(n.getDate())}`:``,count:t.count}}var je=`tasks`,Me=`data/schema/event`,Ne=`data/schema/task`;function Pe(e){if(typeof e!=`string`||!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}function Fe(e){return new Date(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())}function Ie(e){return e.schema.startsWith(Me)}function Le(e){return e.schema===Ne}function Re(e,t,n){let r=e.data??{};if(Le(e)){let i=Pe(r.dueDate);if(!i||i<t||i>=n)return[];let a=String(r.status??`pending`);return[{key:`${e.id}@${i.getTime()}`,doc:e,kind:`task`,title:String(r.title??`Untitled`),start:i,end:i,allDay:!1,calendar:je,recurring:!1,unsupportedRule:!1,done:a===`completed`||a===`cancelled`}]}if(!Ie(e))return[];let i=Pe(r.start);if(!i)return[];let a=r.allDay===!0,o=r.end===null?null:Pe(r.end),s=a?Fe(i):i,c=a?o?Fe(o):W(s,1):o??(r.end===null?n:s),l=Math.max(0,c.getTime()-s.getTime()),u={doc:e,kind:`event`,title:String(r.title??`Untitled`),allDay:a,calendar:typeof r.calendar==`string`?r.calendar:``,done:!1},d=typeof r.recurrence==`string`?r.recurrence:``;if(!d)return c.getTime()<=t.getTime()&&!(c.getTime()===s.getTime()&&s>=t)||s>=n?[]:[{...u,key:`${e.id}@${s.getTime()}`,start:s,end:c,recurring:!1,unsupportedRule:!1}];let f=Se(d);return f?Ee(f,s,t,n,l).map(t=>({...u,key:`${e.id}@${t.getTime()}`,start:t,end:new Date(t.getTime()+l),recurring:!0,unsupportedRule:!1})):c<=t||s>=n?[]:[{...u,key:`${e.id}@${s.getTime()}`,start:s,end:c,recurring:!0,unsupportedRule:!0}]}function ze(e,t,n){return e.flatMap(e=>Re(e,t,n)).sort((e,t)=>e.start.getTime()-t.start.getTime()||t.end.getTime()-e.end.getTime()||e.title.localeCompare(t.title))}function Be(e){let t=new Map;for(let n of e)for(let e of q(n.start,n.end)){let r=`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`,i=t.get(r);i?i.push(n):t.set(r,[n])}return t}function Ve(e){return e.allDay||e.end.getTime()-e.start.getTime()>=864e5||!G(e.start,new Date(e.end.getTime()-1))&&e.end.getTime()>e.start.getTime()}function He(e,t,n=30){let r=U(e),i=t.filter(e=>!Ve(e)).map(e=>{let t=J(e.start,r),i=Math.max(n,J(e.end,r)-t);return{occurrence:e,top:t,height:Math.min(i,1440-t),column:0,columns:1}}).sort((e,t)=>e.top-t.top||t.height-e.height),a=[],o=-1,s=()=>{let e=[];for(let t of a){let n=e.findIndex(e=>e<=t.top);n<0&&(n=e.length,e.push(0)),e[n]=t.top+t.height,t.column=n}for(let t of a)t.columns=e.length;a=[]};for(let e of i)a.length&&e.top>=o&&s(),a.push(e),o=Math.max(o,e.top+e.height);return a.length&&s(),i}function Ue(e,t,n,r){if(t.kind===`task`)return{...e,dueDate:n.toISOString()};if(t.allDay)return{...e,start:`${V(n)}T00:00:00.000Z`,end:`${V(r)}T00:00:00.000Z`};let i={...e,start:n.toISOString()};return e.end===null||(r.getTime()>n.getTime()?i.end=r.toISOString():delete i.end),i}var We=[{id:`day`,label:`Day`,key:`d`},{id:`week`,label:`Week`,key:`w`},{id:`month`,label:`Month`,key:`m`},{id:`year`,label:`Year`,key:`y`},{id:`schedule`,label:`Schedule`,key:`s`}],Ge={view:`week`,hidden:[],showTasks:!0,defaultCalendar:`Personal`},Ke=`canvas:calendar:prefs`;function qe(e){return`${Ke}:${e??`global`}`}function Je(e){try{let t=JSON.parse(localStorage.getItem(qe(e))||`null`);if(!t||typeof t!=`object`)return Ge;let n=t;return{view:We.some(e=>e.id===n.view)?n.view:Ge.view,hidden:Array.isArray(n.hidden)?n.hidden.filter(e=>typeof e==`string`):[],showTasks:n.showTasks!==!1,defaultCalendar:typeof n.defaultCalendar==`string`&&n.defaultCalendar.trim()?n.defaultCalendar:Ge.defaultCalendar}}catch{return Ge}}function Ye(e,t){try{localStorage.setItem(qe(e),JSON.stringify(t))}catch{}}function Xe(e,t){let n=V(W(U(e),-1)),r=V(W(U(t),1));return{events:`t:events:${n}..${r}`,tasks:`t:tasks:${n}..${r}`}}var Ze=5e3;function Qe(e){return!!e&&!e.includes(`:`)&&![`content`,`events`,`tasks`].includes(e.toLowerCase())}function $e(e){return e?e.mode===`context`?`ctx:${e.contextId}`:`${e.workspaceName}:${e.treeName}:${e.treeType}:${e.path}`:``}function et(e,t,n,r){let[i,a]=(0,z.useState)([]),[o,s]=(0,z.useState)(!1),[c,l]=(0,z.useState)(null),[u,d]=(0,z.useState)(null),[f,p]=(0,z.useState)([]),m=t.getTime(),h=n.getTime(),g=(0,z.useCallback)(()=>{if(!e)return Promise.resolve();let t=Xe(new Date(m),new Date(h));return(e.mode===`context`?Promise.all([N(e.contextId,[w],[t.events],{limit:Ze}),r?N(e.contextId,[C],[t.tasks],{limit:Ze}):Promise.resolve([]),M(e.contextId)]).then(([e,t,n])=>{a([...e,...t]);let r=n.workspaceName||n.workspaceId;d(r?{workspaceName:r,path:n.path||`/`,treeName:n.treeId||`context`,treeType:`context`}:null)}):(()=>{let{workspaceName:n,path:i,treeName:o,treeType:s}=e,c={treeName:o,treeType:s,limit:0};return Promise.all([D(n,i,[w],{...c,filters:[t.events]}),r?D(n,i,[C],{...c,filters:[t.tasks]}):Promise.resolve({payload:[]})]).then(([e,t])=>{a([...e.payload||[],...t.payload||[]]),d({workspaceName:n,path:i,treeName:o,treeType:s})})})()).catch(e=>l(e instanceof Error?e.message:`Failed to load calendar`)).finally(()=>s(!1))},[e,m,h,r]),_=(0,z.useCallback)(async()=>{if(!e){a([]),d(null);return}s(!0),l(null),await g()},[e,g]),[v,y]=(0,z.useState)(null),b=`${$e(e)}|${m}|${h}|${r}`;v!==b&&(y(b),e?(s(!0),l(null)):(a([]),d(null))),(0,z.useEffect)(()=>{g()},[g]),(0,z.useEffect)(()=>{let e=()=>{_()};return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[_]);let x=u?.workspaceName??null,S=(0,z.useCallback)(()=>x?Promise.all([T(x),E(x)]).then(([e,t])=>{let n=new Set;for(let t of e)t.startsWith(`data/calendar/`)&&t.length>14&&n.add(t.slice(14));for(let e of t)Qe(e.name)&&n.add(e.name);p([...n].sort())}).catch(()=>{}):Promise.resolve(),[x]);(0,z.useEffect)(()=>{S()},[S,i.length]),(0,z.useEffect)(()=>{let e=()=>{S()};return window.addEventListener(`workspace:timelines:changed`,e),()=>window.removeEventListener(`workspace:timelines:changed`,e)},[S]);let O=(0,z.useCallback)(async e=>{if(!u)throw Error(`No workspace scope resolved`);await k(u.workspaceName,[e],u.path,[],u.treeName,u.treeType),a(t=>t.filter(t=>t.id!==e))},[u]),A=(0,z.useCallback)(e=>{a(t=>t.some(t=>t.id===e.id)?t.map(t=>t.id===e.id?e:t):[...t,e])},[]);return(0,z.useMemo)(()=>({docs:i,loading:o,error:c,scope:u,knownCalendars:f,reload:_,removeDoc:O,patchDoc:A}),[i,o,c,u,f,_,O,A])}function tt(e){return R(e?e.toLowerCase():`events`)}function nt(e){return e.kind===`task`?R(je):tt(e.calendar)}function rt(e,t=18){return`color-mix(in oklch, ${e} ${t}%, transparent)`}function it(e,t,n,r,i,a=30){let o=Math.max(0,Math.min(e.length-1,t)),s=Math.max(0,Math.min(e.length-1,r));if(o!==s){let[t,n]=o<s?[o,s]:[s,o];return{start:U(e[t]),end:W(U(e[n]),1),allDay:!0}}let c=e=>Math.floor(e/a)*a,l=c(Math.min(n,i)),u=c(Math.max(n,i))+a;l=Math.max(0,Math.min(1440-a,l)),u=Math.max(l+a,Math.min(1440,u));let d=U(e[o]);return{start:new Date(d.getTime()+l*6e4),end:new Date(d.getTime()+u*6e4),allDay:!1}}function at(e,t){let[n,r]=e.getTime()<=t.getTime()?[e,t]:[t,e];return{start:U(n),end:W(U(r),1),allDay:!0}}function ot(e,t,n,r,i,a,o=15){let s=t=>Math.max(0,Math.min(e.length-1,t)),c=s(i)-s(n),l=Math.round((a-r)/o)*o,u=t.end.getTime()-t.start.getTime(),d=W(t.start,c),f=U(d),p=Math.max(0,Math.min(1440-o,(d.getTime()-f.getTime())/6e4+l)),m=new Date(f.getTime()+p*6e4);return{start:m,end:new Date(m.getTime()+u)}}function st(e,t,n,r,i=15){let a=U(e[Math.max(0,Math.min(e.length-1,n))]),o=Math.min(1440,Math.ceil(r/i)*i),s=new Date(a.getTime()+o*6e4);return{start:t.start,end:s.getTime()<t.start.getTime()+i*6e4?new Date(t.start.getTime()+i*6e4):s}}function ct(e,t){return{start:W(e.start,t),end:W(e.end,t)}}var Q=t();function lt({month:e,selection:t,marks:n,onPick:r,onPickRange:i,onPrev:a,onNext:s,onTitle:c,onDayMenu:l,title:u,className:f}){let p=new Date,m=K(e),h=u??pe(e),[g,_]=(0,z.useState)(null),v=(0,z.useRef)(g);(0,z.useEffect)(()=>{v.current=g});let y=e=>(document.elementFromPoint(e.clientX,e.clientY)?.closest(`[data-day]`))?.dataset.day??null,b=e=>{if(!i||e.button!==0)return;let t=y(e);t&&(e.currentTarget.setPointerCapture(e.pointerId),_({from:t,to:t}))},S=e=>{if(!v.current)return;let t=y(e);t&&t!==v.current.to&&_({...v.current,to:t})},C=e=>{let t=v.current;if(!t)return;if(e.currentTarget.releasePointerCapture(e.pointerId),_(null),t.from===t.to){w(e,H(t.from));return}let n=at(H(t.from),H(t.to));i?.(n.start,n.end)},w=(e,n)=>{if(e.shiftKey&&i&&t){let e=at(t.start,n);i(e.start,e.end)}else r(n)},T=g?at(H(g.from),H(g.to)):t;return(0,Q.jsxs)(`div`,{className:x(`select-none`,f),children:[(0,Q.jsxs)(`div`,{className:`mb-1 flex items-center justify-between`,children:[a?(0,Q.jsx)(`button`,{type:`button`,onClick:a,className:`rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground`,"aria-label":`Previous month`,children:(0,Q.jsx)(o,{className:`h-3.5 w-3.5`})}):(0,Q.jsx)(`span`,{}),c?(0,Q.jsx)(`button`,{type:`button`,onClick:c,className:`text-xs font-semibold hover:underline`,children:h}):(0,Q.jsx)(`span`,{className:`text-xs font-semibold`,children:h}),s?(0,Q.jsx)(`button`,{type:`button`,onClick:s,className:`rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground`,"aria-label":`Next month`,children:(0,Q.jsx)(d,{className:`h-3.5 w-3.5`})}):(0,Q.jsx)(`span`,{})]}),(0,Q.jsx)(`div`,{className:`grid grid-cols-7 text-center text-[10px] text-muted-foreground`,children:ae.map(e=>(0,Q.jsx)(`span`,{children:e[0]},e))}),(0,Q.jsx)(`div`,{className:x(`grid grid-cols-7 gap-y-px text-center text-[11px]`,g&&`cursor-crosshair`),onPointerDown:b,onPointerMove:S,onPointerUp:C,onPointerCancel:()=>_(null),children:m.map(t=>{let r=V(t),a=t.getMonth()===e.getMonth(),o=G(t,p),s=!!T&&t>=T.start&&t<T.end,c=!!T&&s&&G(t,T.start),u=!!T&&s&&G(t,new Date(T.end.getTime()-1)),d=n?.get(r)??[],f=[...new Set(d.map(nt))].slice(0,3);return(0,Q.jsxs)(`button`,{type:`button`,"data-day":r,onClick:e=>{(e.detail===0||!i)&&w(e,t)},onContextMenu:l?e=>{e.preventDefault(),l(e,t)}:void 0,"aria-label":d.length?`${t.toDateString()}, ${d.length} ${d.length===1?`entry`:`entries`}`:t.toDateString(),title:d.length?d.slice(0,6).map(e=>e.title).join(`
2
2
  `)+(d.length>6?`\n+${d.length-6} more`:``):void 0,className:x(`relative mx-auto flex h-6 w-full items-center justify-center transition-colors hover:bg-muted`,c&&u?`rounded-full`:c?`rounded-l-full`:u?`rounded-r-full`:s?``:`rounded-full`,!a&&`text-muted-foreground/40`,o&&!s&&`font-bold text-primary`,s&&`bg-primary text-primary-foreground hover:bg-primary`,d.length>0&&!s&&`font-semibold`),style:d.length&&!s?{background:`color-mix(in srgb, ${f[0]} 22%, transparent)`}:void 0,children:[t.getDate(),d.length>0&&!s&&(0,Q.jsx)(`span`,{className:`absolute bottom-0 left-1/2 flex -translate-x-1/2 gap-px`,children:f.map(e=>(0,Q.jsx)(`span`,{className:`h-1 w-1 rounded-full`,style:{background:e}},e))})]},r)})})]})}function ut({occurrence:e,selected:t,moving:n,showTime:r=!0,onSelect:i,className:o,...s}){let c=nt(e),u=!e.allDay&&e.kind===`event`&&e.end.getTime()>e.start.getTime();return(0,Q.jsxs)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),i(e)},title:`${e.title}${e.calendar?` · ${e.calendar}`:``}`,className:x(`flex w-full min-w-0 items-center gap-1 truncate rounded px-1 py-px text-left text-[11px] leading-4 text-foreground transition-colors hover:brightness-110`,!e.recurring&&`touch-none`,t&&`ring-1 ring-ring`,n&&`cursor-grabbing ring-2 ring-primary shadow-elevation-2`,e.done&&`line-through opacity-60`,o),style:{background:rt(c,e.allDay||e.kind===`task`?28:14),borderLeft:`3px solid ${c}`},...s,children:[e.kind===`task`&&(0,Q.jsx)(a,{className:`h-3 w-3 shrink-0`,style:{color:c}}),r&&u&&(0,Q.jsx)(`span`,{className:`shrink-0 tabular-nums text-muted-foreground`,children:Z(e.start)}),(0,Q.jsx)(`span`,{className:`truncate`,children:e.title}),e.recurring&&(0,Q.jsx)(l,{className:`ml-auto h-2.5 w-2.5 shrink-0 text-muted-foreground`})]})}function dt(e){let[t,n]=(0,z.useState)(null),r=(0,z.useRef)(e);(0,z.useEffect)(()=>{r.current=e});let i=(0,z.useRef)(null),a=(0,z.useRef)(!1);(0,z.useEffect)(()=>()=>i.current?.stop(),[]);let o=e=>(document.elementFromPoint(e.clientX,e.clientY)?.closest(`[data-day]`))?.dataset.day??null;return{moving:t,handlers:e=>e.recurring?{}:{onPointerDown:t=>{if(t.button!==0||i.current)return;let s=o(t);if(!s)return;let c=e=>{let t=i.current;if(!t)return;let r=o(e);if(!r)return;let a=Math.round((H(r).getTime()-H(t.fromKey).getTime())/ie);a!==t.delta&&(t.delta=a,n(a?{key:t.o.key,...ct(t.o,a)}:null))},l=()=>{let e=i.current;if(!e||(e.stop(),n(null),!e.delta))return;a.current=!0,setTimeout(()=>{a.current=!1},0);let t=ct(e.o,e.delta);r.current(e.o,t.start,t.end)},u=()=>{i.current?.stop(),n(null)};window.addEventListener(`pointermove`,c),window.addEventListener(`pointerup`,l),window.addEventListener(`pointercancel`,u),i.current={o:e,fromKey:s,delta:0,stop:()=>{i.current=null,window.removeEventListener(`pointermove`,c),window.removeEventListener(`pointerup`,l),window.removeEventListener(`pointercancel`,u)}}},onClickCapture:e=>{a.current&&(a.current=!1,e.stopPropagation(),e.preventDefault())}},apply:e=>t?e.map(e=>e.key===t.key?{...e,start:t.start,end:t.end}:e):e}}var $=48,ft=30,pt=15,mt=`w-12`,ht=48;function gt({days:e,occurrences:t,selectedKey:n,pending:r,onSelect:i,onCreate:a,onMove:o,onPickDay:s,onEntryMenu:c,onSlotMenu:l,compact:u}){let d=(0,z.useRef)(null),f=(0,z.useRef)(null),[p,m]=(0,z.useState)(null),h=(0,z.useRef)(p);(0,z.useEffect)(()=>{h.current=p});let g=t=>{let n=f.current;if(!n)return null;let r=n.getBoundingClientRect(),i=(r.width-ht)/e.length,a=Math.floor((t.clientX-r.left-ht)/i),o=Math.max(0,Math.min(1439,(t.clientY-r.top)/$*60));return a<0||a>=e.length?null:{day:a,min:o}},_=e=>{if(e.button!==0||e.target.closest(`button`))return;let t=g(e);t&&(e.currentTarget.setPointerCapture(e.pointerId),m({fromDay:t.day,fromMin:t.min,toDay:t.day,toMin:t.min}))},v=e=>{if(!h.current)return;let t=g(e);t&&m({...h.current,toDay:t.day,toMin:t.min})},y=t=>{let n=h.current;if(!n)return;t.currentTarget.releasePointerCapture(t.pointerId),m(null);let r=it(e,n.fromDay,n.fromMin,n.toDay,n.toMin,ft);a(r.start,r.allDay,r.end)},b=t=>{let n=g(t);n&&(t.preventDefault(),l(t,it(e,n.day,n.min,n.day,n.min,ft).start,!1))},S=p?it(e,p.fromDay,p.fromMin,p.toDay,p.toMin,ft):r,[C,w]=(0,z.useState)(null),T=(0,z.useRef)(o);(0,z.useEffect)(()=>{T.current=o});let E=(0,z.useRef)(null);(0,z.useEffect)(()=>()=>E.current?.stop(),[]);let D=(0,z.useRef)(!1),O=(t,n)=>{if(t.button!==0||n.recurring||E.current)return;let r=g(t);if(!r)return;let i=t.target.dataset.resize?`resize`:`move`,a=null,o=t=>{let o=g(t);if(!o)return;let s=i===`move`?ot(e,n,r.day,r.min,o.day,o.min,pt):st(e,n,o.day,o.min,pt);a=s.start.getTime()===n.start.getTime()&&s.end.getTime()===n.end.getTime()?null:s,w(a?{key:n.key,...a,mode:i}:null)},s=()=>{l(),w(null),a&&(D.current=!0,setTimeout(()=>{D.current=!1},0),T.current(n,a.start,a.end))},c=()=>{l(),w(null)},l=()=>{E.current=null,window.removeEventListener(`pointermove`,o),window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,c)};window.addEventListener(`pointermove`,o),window.addEventListener(`pointerup`,s),window.addEventListener(`pointercancel`,c),E.current={stop:l}},k=dt(o),A=k.apply(t),ee=(0,z.useMemo)(()=>C?A.map(e=>e.key===C.key?{...e,start:C.start,end:C.end}:e):A,[A,C]),j=(0,z.useMemo)(()=>Be(ee),[ee]),[M,N]=(0,z.useState)(()=>new Date);(0,z.useEffect)(()=>{let e=setInterval(()=>N(new Date),6e4);return()=>clearInterval(e)},[]);let P=V(e[0]);(0,z.useEffect)(()=>{let t=d.current;t&&(t.scrollTop=(e.some(e=>G(e,M))?Math.max(0,M.getHours()-1):7)*$)},[P,e.length]);let F=Array.from({length:24},(e,t)=>t),I=e.map(e=>(j.get(V(e))??[]).filter(Ve)),L=Math.max(0,...I.map(e=>e.length)),te=!!p||!!C||!!k.moving;return(0,Q.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Q.jsxs)(`div`,{className:`flex shrink-0 border-b border-border`,children:[(0,Q.jsx)(`div`,{className:x(mt,`shrink-0`)}),e.map(e=>{let t=G(e,M);return(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>s(e),className:`flex min-w-0 flex-1 flex-col items-center border-l border-border/60 py-1 hover:bg-muted/50`,title:`Open day`,children:[(0,Q.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground`,children:ae[(e.getDay()+6)%7]}),(0,Q.jsx)(`span`,{className:x(`flex h-7 w-7 items-center justify-center rounded-full text-sm font-semibold`,t&&`bg-primary text-primary-foreground`),children:e.getDate()})]},V(e))})]}),L>0&&(0,Q.jsxs)(`div`,{className:x(`flex shrink-0 border-b border-border bg-muted/20`,k.moving&&`select-none`),children:[(0,Q.jsx)(`div`,{className:x(mt,`shrink-0 py-1 pr-1 text-right text-[10px] text-muted-foreground`),children:u?``:`all day`}),e.map((e,t)=>(0,Q.jsx)(`div`,{"data-day":V(e),className:`flex min-w-0 flex-1 flex-col gap-0.5 border-l border-border/60 p-0.5`,onClick:t=>{t.target===t.currentTarget&&a(U(e),!0)},onContextMenu:t=>{t.preventDefault(),l(t,U(e),!0)},children:I[t].map(e=>(0,Q.jsx)(ut,{occurrence:e,selected:e.key===n,moving:k.moving?.key===e.key,showTime:!1,onSelect:i,onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),c(t,e)},...k.handlers(e)},e.key))},V(e)))]}),(0,Q.jsx)(`div`,{ref:d,className:`min-h-0 flex-1 overflow-y-auto`,children:(0,Q.jsxs)(`div`,{ref:f,className:x(`relative flex select-none`,p&&`cursor-crosshair`,C?.mode===`move`&&`cursor-grabbing`,C?.mode===`resize`&&`cursor-ns-resize`),style:{height:1152},onPointerDown:_,onPointerMove:v,onPointerUp:y,onPointerCancel:()=>m(null),onContextMenu:b,children:[(0,Q.jsx)(`div`,{className:x(mt,`relative shrink-0`),children:F.map(e=>(0,Q.jsx)(`div`,{className:`absolute right-1 -translate-y-1/2 text-[10px] tabular-nums text-muted-foreground`,style:{top:e*$},children:e===0?``:ye(e)},e))}),e.map(e=>{let t=He(e,j.get(V(e))??[]),r=G(e,M)?(M.getHours()*60+M.getMinutes())/60*$:null;return(0,Q.jsxs)(`div`,{"data-day":V(e),className:`relative min-w-0 flex-1 cursor-cell border-l border-border/60`,role:`presentation`,children:[S&&S.end>e&&S.start<U(new Date(e.getTime()+864e5))&&(0,Q.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0.5 z-[5] rounded-md border border-primary bg-primary/15`,style:{top:J(S.start,e)/60*$,height:Math.max(8,(J(S.end,e)-J(S.start,e))/60*$)},children:(0,Q.jsx)(`span`,{className:`absolute left-1 top-0.5 text-[10px] font-medium text-primary`,children:S.allDay?`All day`:`${Z(S.start)} – ${Z(S.end)}`})}),F.map(e=>(0,Q.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 border-t border-border/50`,style:{top:e*$}},e)),t.map(e=>{let t=e.occurrence,r=nt(t),a=100/e.columns,o=e.height<45,s=C?.key===t.key,l=!t.recurring;return(0,Q.jsxs)(`button`,{type:`button`,onClick:e=>{if(e.stopPropagation(),D.current){D.current=!1;return}i(t)},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),c(e,t)},onPointerDown:e=>O(e,t),title:`${t.title} · ${Z(t.start)}${t.end>t.start?` – ${Z(t.end)}`:``}`,className:x(`absolute overflow-hidden rounded-md border-l-[3px] px-1.5 text-left text-[11px] leading-tight text-foreground shadow-elevation-1 transition-[filter] hover:brightness-110`,l&&`touch-none`,s?`z-20 ring-2 ring-primary shadow-elevation-2`:te&&`pointer-events-none`,t.key===n&&!s&&`ring-1 ring-ring`,t.done&&`line-through opacity-60`),style:{top:e.top/60*$,height:Math.max(18,e.height/60*$-2),left:`calc(${e.column*a}% + 2px)`,width:`calc(${a}% - 4px)`,background:rt(r,24),borderLeftColor:r,paddingTop:o?1:3},children:[(0,Q.jsx)(`span`,{className:x(`font-medium`,o?`inline`:`block truncate`),children:t.title}),!o&&(0,Q.jsxs)(`span`,{className:`block truncate text-[10px] text-muted-foreground`,children:[Z(t.start),t.end>t.start?` – ${Z(t.end)}`:``,t.calendar&&!u?` · ${t.calendar}`:``]}),l&&t.kind===`event`&&(0,Q.jsx)(`span`,{"data-resize":`1`,className:`absolute inset-x-0 bottom-0 h-1.5 cursor-ns-resize`})]},t.key)}),r!==null&&(0,Q.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 z-10 border-t-2 border-destructive`,style:{top:r},children:(0,Q.jsx)(`span`,{className:`absolute -left-1 -top-[5px] h-2 w-2 rounded-full bg-destructive`})})]},V(e))})]})})]})}var _t=3;function vt({month:e,occurrences:t,selectedKey:n,pending:r,onSelect:i,onCreate:a,onMove:o,onPickDay:s,onEntryMenu:c,onSlotMenu:l,narrow:u}){let d=K(e),f=dt(o),p=f.apply(t),m=(0,z.useMemo)(()=>Be(p),[p]),h=new Date,[g,_]=(0,z.useState)(null),v=(0,z.useRef)(g);(0,z.useEffect)(()=>{v.current=g});let y=e=>(document.elementFromPoint(e.clientX,e.clientY)?.closest(`[data-day]`))?.dataset.day??null,b=e=>{if(u||e.button!==0||e.target.closest(`button`))return;let t=y(e);t&&(e.currentTarget.setPointerCapture(e.pointerId),_({from:t,to:t}))},S=e=>{if(!v.current)return;let t=y(e);t&&t!==v.current.to&&_({...v.current,to:t})},C=e=>{let t=v.current;if(!t)return;e.currentTarget.releasePointerCapture(e.pointerId),_(null);let n=at(H(t.from),H(t.to));a(n.start,!0,n.end)},w=e=>{let t=y(e);t&&(e.preventDefault(),l(e,H(t),!0))},T=g?at(H(g.from),H(g.to)):r;return(0,Q.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Q.jsx)(`div`,{className:`grid shrink-0 grid-cols-7 border-b border-border text-center text-[10px] uppercase tracking-wide text-muted-foreground`,children:ae.map(e=>(0,Q.jsx)(`span`,{className:`py-1`,children:u?e[0]:e},e))}),(0,Q.jsx)(`div`,{className:x(`grid min-h-0 flex-1 grid-cols-7 grid-rows-6 overflow-y-auto`,g&&`cursor-crosshair select-none`,f.moving&&`select-none`),onPointerDown:b,onPointerMove:S,onPointerUp:C,onPointerCancel:()=>_(null),onContextMenu:w,children:d.map(t=>{let r=V(t),a=m.get(r)??[],o=t.getMonth()===e.getMonth(),l=G(t,h),d=a.length-_t;return(0,Q.jsxs)(`div`,{role:`presentation`,"data-day":r,onClick:e=>{u&&e.target===e.currentTarget&&s(t)},className:x(`flex min-h-[3.5rem] min-w-0 flex-col gap-0.5 border-b border-r border-border/60 p-0.5`,!o&&`bg-muted/20 text-muted-foreground/60`,!u&&`cursor-cell`,T&&t>=T.start&&t<T.end&&`bg-primary/15 ring-1 ring-inset ring-primary`),children:[(0,Q.jsx)(`button`,{type:`button`,onClick:()=>s(t),className:x(`mx-auto flex h-5 w-5 items-center justify-center rounded-full text-[11px] hover:bg-muted sm:mx-0`,l&&`bg-primary font-bold text-primary-foreground hover:bg-primary`),title:`Open day`,children:t.getDate()}),u?(0,Q.jsx)(`div`,{className:`flex flex-wrap justify-center gap-0.5 px-0.5`,children:a.slice(0,4).map(e=>(0,Q.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full`,style:{background:nt(e)}},e.key))}):(0,Q.jsxs)(Q.Fragment,{children:[a.slice(0,_t).map(e=>(0,Q.jsx)(ut,{occurrence:e,selected:e.key===n,moving:f.moving?.key===e.key,onSelect:i,onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),c(t,e)},...f.handlers(e)},e.key)),d>0&&(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>s(t),className:`px-1 text-left text-[10px] text-muted-foreground hover:text-foreground`,children:[`+`,d,` more`]})]})]},r)})})]})}function yt({year:e,occurrences:t,onPickDay:n,onPickRange:r,onPickMonth:i,onSlotMenu:a}){let o=(0,z.useMemo)(()=>Be(t),[t]),s=Array.from({length:12},(t,n)=>new Date(e,n,1));return(0,Q.jsx)(`div`,{className:`grid h-full min-h-0 grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-x-4 gap-y-5 overflow-y-auto p-3`,children:s.map(e=>(0,Q.jsx)(lt,{month:e,marks:o,title:e.toLocaleDateString(void 0,{month:`long`}),onTitle:()=>i(e),onPick:n,onPickRange:r,onDayMenu:(e,t)=>a(e,t,!0)},V(e)))})}function bt({occurrences:e,selectedKey:t,onSelect:n,onEntryMenu:r,onEarlier:i,onLater:a,onPickDay:o,loading:s}){let c=(0,z.useMemo)(()=>[...Be(e).entries()].sort(([e],[t])=>e.localeCompare(t)),[e]),l=new Date;return(0,Q.jsxs)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:[(0,Q.jsx)(`div`,{className:`flex justify-center py-2`,children:(0,Q.jsx)(`button`,{type:`button`,onClick:i,className:`rounded-md border border-border px-3 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground`,children:`Earlier`})}),!s&&!c.length&&(0,Q.jsx)(`p`,{className:`py-10 text-center text-sm text-muted-foreground`,children:`Nothing scheduled in this range.`}),c.map(([e,i])=>{let a=H(e),s=G(a,l);return(0,Q.jsxs)(`div`,{className:`flex border-t border-border/60 px-2 py-2`,children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>o(a),className:`flex w-14 shrink-0 flex-col items-start`,title:`Open day`,children:[(0,Q.jsx)(`span`,{className:x(`flex h-8 w-8 items-center justify-center rounded-full text-lg font-semibold`,s&&`bg-primary text-primary-foreground`),children:a.getDate()}),(0,Q.jsxs)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground`,children:[me(a),`, `,ae[(a.getDay()+6)%7]]})]}),(0,Q.jsx)(`div`,{className:`min-w-0 flex-1 space-y-0.5`,children:i.map(e=>{let i=nt(e),a=!Ve(e)&&e.kind===`event`;return(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>n(e),onContextMenu:t=>{t.preventDefault(),r(t,e)},className:x(`flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm hover:bg-muted`,e.key===t&&`bg-muted ring-1 ring-ring`,e.done&&`line-through opacity-60`),children:[(0,Q.jsx)(`span`,{className:`h-2.5 w-2.5 shrink-0 rounded-full`,style:{background:i}}),(0,Q.jsx)(`span`,{className:`w-[7.5rem] shrink-0 text-xs tabular-nums text-muted-foreground`,children:a?`${Z(e.start)}${e.end>e.start?` – ${Z(e.end)}`:``}`:e.kind===`task`?`due ${Z(e.start)}`:`All day`}),(0,Q.jsx)(`span`,{className:`truncate`,children:e.title}),e.calendar&&e.kind===`event`&&(0,Q.jsx)(`span`,{className:`ml-auto shrink-0 text-[10px] text-muted-foreground`,children:e.calendar})]},e.key)})})]},e)}),(0,Q.jsx)(`div`,{className:`flex justify-center py-2`,children:(0,Q.jsx)(`button`,{type:`button`,onClick:a,className:`rounded-md border border-border px-3 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground`,children:`Later`})})]})}var xt=`3.0`,St=[{id:`none`,label:`Does not repeat`},{id:`daily`,label:`Every day`},{id:`weekdays`,label:`Every weekday`},{id:`weekly`,label:`Every week`},{id:`monthly`,label:`Every month`},{id:`yearly`,label:`Every year`},{id:`custom`,label:`Custom (RRULE)…`}];function Ct(e,t){let n=e.data??{},r=n.allDay===!0,i=String(n.start??``),a=typeof n.end==`string`?n.end:``,o=typeof n.recurrence==`string`?n.recurrence:``,s=Oe(o||void 0),c=Ae(o||void 0);return{title:String(n.title??``),calendar:typeof n.calendar==`string`?n.calendar:Et(e)?``:t,allDay:r,start:r?i.slice(0,10):F(i),end:r?Dt(i.slice(0,10),a):F(a),location:String(n.location??``),description:String(n.description??``),repeat:s,until:c.until,count:c.count===null?``:String(c.count),rrule:o}}function wt(e,t){let n=e.end??new Date(e.start.getTime()+36e5);return{title:``,calendar:t,allDay:e.allDay,start:e.allDay?V(e.start):oe(e.start),end:e.allDay?V(W(n,-1)<e.start?e.start:W(n,-1)):oe(n),location:``,description:``,repeat:`none`,until:``,count:``,rrule:``}}function Tt(e){if(e.repeat===`custom`)return e.rrule.trim();let t=Number(e.count);return ke(e.repeat,{until:e.until,count:Number.isInteger(t)&&t>0?t:null})}function Et(e){let t=e.metadata;return typeof t?.source==`string`&&t.source?{source:t.source,connector:typeof t.connector==`string`?t.connector:``}:null}function Dt(e,t){if(!t)return``;let[n,r,i]=t.slice(0,10).split(`-`).map(Number),a=V(new Date(n,r-1,i-1));return a<e?e:a}function Ot(e){return`${V(W(H(e),1))}T00:00:00.000Z`}function kt(e,t){let n={...e,title:t.title.trim()},r=(e,t)=>{t===void 0||t===``||t===!1?delete n[e]:n[e]=t};return r(`calendar`,t.calendar.trim()),r(`allDay`,t.allDay),r(`location`,t.location.trim()),r(`description`,t.description.trim()),r(`recurrence`,Tt(t)),t.allDay?(n.start=`${t.start}T00:00:00.000Z`,r(`end`,t.end?Ot(t.end):void 0)):(n.start=I(t.start),r(`end`,I(t.end))),n}function At(e){return e.title.trim()?e.start?e.end&&e.end<e.start?`The end is before the start.`:e.calendar.includes(`:`)?`A calendar name cannot contain ":".`:e.repeat===`custom`&&(!e.rrule.trim()||!Se(e.rrule))?`Enter a supported RRULE (FREQ=…, INTERVAL, COUNT, UNTIL, BYDAY, BYMONTHDAY, BYMONTH).`:e.repeat!==`none`&&e.repeat!==`custom`&&e.until&&e.until<e.start.slice(0,10)?`The series ends before it starts.`:e.repeat!==`none`&&e.repeat!==`custom`&&e.count&&!(Number.isInteger(Number(e.count))&&Number(e.count)>0)?`The number of occurrences must be a whole number above zero.`:null:`Pick a start.`:`Give the event a title.`}function jt({subject:e,target:t,workspaceName:n,calendars:r,defaultCalendar:a,onClose:o,onSaved:s,onDelete:u}){let d=e.kind===`occurrence`?e.occurrence.doc:null,p=e.kind===`occurrence`&&e.occurrence.kind===`task`,[m,h]=(0,z.useState)(()=>d?Ct(d,a):wt(e.draft,a)),[g,y]=(0,z.useState)(!1),[S,C]=(0,z.useState)(null),[T,E]=(0,z.useState)(!1),D=e.kind===`draft`?`draft:${e.draft.start.getTime()}:${e.draft.end?.getTime()??``}:${e.draft.allDay}`:e.occurrence.key,[k,A]=(0,z.useState)(D);k!==D&&(A(D),h(d?Ct(d,a):wt(e.draft,a)),C(null)),(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]);let j=e=>h(t=>({...t,...e})),M=d?Et(d):null,N=typeof d?.data?.htmlLink==`string`?d.data.htmlLink:null,F=async()=>{let e=At(m);if(e){C(e);return}y(!0),C(null);try{if(d){if(!n)throw Error(`No workspace resolved for this calendar`);await O(n,{id:d.id,schema:d.schema,schemaVersion:d.schemaVersion||xt,data:kt(d.data??{},m),metadata:d.metadata})}else await ee(t,[{schema:w,schemaVersion:xt,data:kt({},m),metadata:{features:[]}}]);s(m.calendar.trim())}catch(e){C(e instanceof Error?e.message:`Failed to save the event`)}finally{y(!1)}},I=p?`Task`:d?`Event`:`New event`;return(0,Q.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Q.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,Q.jsx)(`span`,{className:`h-3 w-3 rounded-full`,style:{background:tt(p?`tasks`:m.calendar)}}),(0,Q.jsx)(`span`,{className:`text-sm font-semibold`,children:I}),d&&(0,Q.jsxs)(`span`,{className:`text-[10px] text-muted-foreground`,children:[`#`,d.id]}),(0,Q.jsx)(`span`,{className:`flex-1`}),d&&n&&(0,Q.jsx)(i,{to:`/workspaces/${encodeURIComponent(n)}/documents/${d.id}`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,title:`Open document`,"aria-label":`Open document`,children:(0,Q.jsx)(_,{className:`h-3.5 w-3.5`})}),d&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>E(!0),className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,title:`Link to…`,"aria-label":`Link to…`,children:(0,Q.jsx)(b,{className:`h-3.5 w-3.5`})}),d&&!p&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>{u(d)},className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-destructive`,title:`Delete (moves to trash)`,"aria-label":`Delete`,children:(0,Q.jsx)(f,{className:`h-3.5 w-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:o,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,"aria-label":`Close`,children:(0,Q.jsx)(c,{className:`h-4 w-4`})})]}),p&&d?(0,Q.jsx)(Ft,{doc:d,occurrence:e.occurrence,workspaceName:n,onSaved:()=>s(``)}):(0,Q.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-3 overflow-y-auto p-3`,children:[(0,Q.jsx)(`input`,{value:m.title,onChange:e=>j({title:e.target.value}),placeholder:`Title`,autoFocus:!d,spellCheck:!1,className:`w-full border-0 border-b border-border bg-transparent px-0 py-1 text-base font-semibold outline-none placeholder:text-muted-foreground/60 focus:border-ring`}),(0,Q.jsx)(Nt,{value:m.calendar,calendars:r,onChange:e=>j({calendar:e})}),(0,Q.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:m.allDay,onChange:e=>{let t=e.target.checked;if(t)j({allDay:t,start:m.start.slice(0,10),end:(m.end||m.start).slice(0,10)});else{let e=m.start.slice(0,10)||V(new Date),n=(m.end||e).slice(0,10);j(n>e?{allDay:t,start:`${e}T09:00`,end:`${e}T10:00`,repeat:m.repeat===`none`?`daily`:m.repeat,until:n,count:``}:{allDay:t,start:`${e}T09:00`,end:`${e}T10:00`})}},className:`h-4 w-4 accent-primary`}),`All day`]}),(0,Q.jsxs)(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[(0,Q.jsxs)(`label`,{className:`block text-xs`,children:[(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`Start`}),m.allDay?(0,Q.jsx)(`div`,{className:`mt-1`,children:(0,Q.jsx)(L,{value:m.start,onChange:e=>j({start:e,end:m.end&&m.end<e?e:m.end})})}):(0,Q.jsx)(`div`,{className:`mt-1`,children:(0,Q.jsx)(P,{value:m.start,onChange:e=>j({start:e}),clearable:!1})})]}),(0,Q.jsxs)(`label`,{className:`block text-xs`,children:[(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`End`}),m.allDay?(0,Q.jsx)(`div`,{className:`mt-1`,children:(0,Q.jsx)(L,{value:m.end,min:m.start,placeholder:`Same day`,onChange:e=>j({end:e})})}):(0,Q.jsx)(`div`,{className:`mt-1`,children:(0,Q.jsx)(P,{value:m.end,onChange:e=>j({end:e}),placeholder:`No end`})})]})]}),(0,Q.jsxs)(`label`,{className:`block text-xs`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-1 text-muted-foreground`,children:[(0,Q.jsx)(l,{className:`h-3 w-3`}),` Repeat`]}),(0,Q.jsx)(`select`,{value:m.repeat,onChange:e=>j({repeat:e.target.value,rrule:e.target.value===`custom`?m.rrule||ke(m.repeat)||`FREQ=WEEKLY`:m.rrule}),className:`mt-1 h-8 w-full rounded-md border border-input bg-transparent px-2 text-sm`,children:St.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))}),m.repeat===`custom`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{value:m.rrule,onChange:e=>j({rrule:e.target.value}),placeholder:`FREQ=WEEKLY;INTERVAL=2;BYDAY=TU,TH`,spellCheck:!1,className:`mt-1 h-8 w-full rounded-md border border-input bg-transparent px-2 font-mono text-xs`}),(0,Q.jsx)(`span`,{className:`mt-0.5 block text-[11px] text-muted-foreground`,children:Se(m.rrule)?De(Se(m.rrule)):`RFC 5545 RRULE value`})]})]}),m.repeat!==`none`&&m.repeat!==`custom`&&(0,Q.jsx)(Mt,{fields:m,patch:j}),(0,Q.jsxs)(`label`,{className:`block text-xs`,children:[(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`Location`}),(0,Q.jsx)(`input`,{value:m.location,onChange:e=>j({location:e.target.value}),spellCheck:!1,className:`mt-1 h-8 w-full rounded-md border border-input bg-transparent px-2 text-sm`})]}),(0,Q.jsxs)(`div`,{className:`text-xs`,children:[(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`Description`}),(0,Q.jsx)(`div`,{className:`mt-1 rounded-md border border-input px-2 py-1.5`,children:(0,Q.jsx)(re,{value:m.description,onChange:e=>j({description:e}),placeholder:`Notes, agenda, links…`})})]}),M&&(0,Q.jsxs)(`p`,{className:`rounded-md bg-muted/50 px-2 py-1.5 text-[11px] text-muted-foreground`,children:[`Synced from `,M.connector||M.source,`. Edits stay in Canvas unless the connector supports write-back.`,N&&(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(`a`,{href:N,target:`_blank`,rel:`noopener noreferrer`,className:`underline hover:text-foreground`,children:`Open at source`})]})]}),e.kind===`occurrence`&&e.occurrence.unsupportedRule&&(0,Q.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`This series uses RRULE parts the calendar cannot expand; only its first occurrence is shown.`}),S&&(0,Q.jsx)(`p`,{className:`text-xs text-destructive`,role:`alert`,children:S})]}),!p&&(0,Q.jsxs)(`div`,{className:`flex shrink-0 items-center justify-end gap-2 border-t border-border px-3 py-2`,children:[(0,Q.jsx)(Pt,{doc:d}),(0,Q.jsx)(`button`,{type:`button`,onClick:o,className:`rounded-md border border-border px-3 py-1.5 text-xs hover:bg-muted`,children:`Cancel`}),(0,Q.jsxs)(`button`,{type:`button`,onClick:F,disabled:g,className:x(`flex items-center gap-1 rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground disabled:opacity-50`),children:[g&&(0,Q.jsx)(v,{className:`h-3 w-3 animate-spin`}),d?`Save`:`Create`]})]}),T&&d&&(0,Q.jsx)(ne,{documentId:d.id,workspaceName:n??void 0,onClose:()=>E(!1)})]})}function Mt({fields:e,patch:t}){let n=e.until?`until`:e.count?`count`:`never`,r=e.start.slice(0,10),i=Tt(e),a=i?Se(i):null;return(0,Q.jsxs)(`div`,{className:`text-xs`,children:[(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`Ends`}),(0,Q.jsxs)(`div`,{className:`mt-1 flex items-center gap-1.5`,children:[(0,Q.jsxs)(`select`,{value:n,onChange:n=>{let i=n.target.value;t(i===`never`?{until:``,count:``}:i===`until`?{until:e.until||r,count:``}:{until:``,count:e.count||`10`})},className:`h-8 w-28 shrink-0 rounded-md border border-input bg-transparent px-2 text-sm`,children:[(0,Q.jsx)(`option`,{value:`never`,children:`Never`}),(0,Q.jsx)(`option`,{value:`until`,children:`On date`}),(0,Q.jsx)(`option`,{value:`count`,children:`After`})]}),n===`until`&&(0,Q.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Q.jsx)(L,{value:e.until,min:r,onChange:e=>t({until:e})})}),n===`count`&&(0,Q.jsxs)(`label`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`input`,{type:`number`,min:1,step:1,value:e.count,onChange:e=>t({count:e.target.value}),className:`h-8 w-20 rounded-md border border-input bg-transparent px-2 text-sm tabular-nums`}),(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`occurrences`})]})]}),a&&(0,Q.jsx)(`span`,{className:`mt-0.5 block text-[11px] text-muted-foreground`,children:De(a)})]})}function Nt({value:e,calendars:t,onChange:n}){let r=t.some(t=>t.toLowerCase()===e.toLowerCase()),[i,a]=(0,z.useState)(!r&&!e&&t.length===0),o=r||!e?t:[e,...t];return(0,Q.jsxs)(`label`,{className:`block text-xs`,children:[(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`Calendar`}),i?(0,Q.jsxs)(`span`,{className:`mt-1 flex gap-1`,children:[(0,Q.jsx)(`input`,{autoFocus:!0,value:e,onChange:e=>n(e.target.value),placeholder:`New calendar name`,spellCheck:!1,className:`h-8 min-w-0 flex-1 rounded-md border border-input bg-transparent px-2 text-sm outline-none focus-visible:ring-1 focus-visible:ring-ring`}),t.length>0&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>{a(!1),n(t[0])},className:`rounded-md border border-border px-2 text-xs text-muted-foreground hover:bg-muted`,"aria-label":`Pick an existing calendar`,children:(0,Q.jsx)(c,{className:`h-3 w-3`})})]}):(0,Q.jsxs)(`select`,{value:e,onChange:e=>{e.target.value===`\0new`?(a(!0),n(``)):n(e.target.value)},className:`mt-1 h-8 w-full rounded-md border border-input bg-transparent px-2 text-sm`,children:[!e&&(0,Q.jsx)(`option`,{value:``,children:`No calendar`}),o.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e)),(0,Q.jsx)(`option`,{value:`\0new`,children:`New calendar…`})]})]})}function Pt({doc:e}){let t=A(e??{id:-1,locations:[]});return!e||!t.replicating?null:(0,Q.jsx)(`span`,{className:`mr-auto text-[10px] text-muted-foreground`,children:t.label})}function Ft({doc:e,occurrence:t,workspaceName:n,onSaved:r}){let[i,o]=(0,z.useState)(!1),s=t.done;return(0,Q.jsxs)(`div`,{className:`space-y-3 p-3 text-sm`,children:[(0,Q.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:async()=>{if(n){o(!0);try{let t=s?`pending`:`completed`;await O(n,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...e.data??{},status:t,completed:t===`completed`},metadata:e.metadata}),r()}finally{o(!1)}}},disabled:i,className:`mt-0.5 text-muted-foreground hover:text-foreground`,"aria-label":s?`Mark as pending`:`Mark as completed`,children:s?(0,Q.jsx)(a,{className:`h-4 w-4 text-success`}):(0,Q.jsx)(g,{className:`h-4 w-4`})}),(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:x(`font-semibold`,s&&`line-through text-muted-foreground`),children:t.title}),(0,Q.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Due `,t.start.toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`})]})]})]}),typeof e.data?.description==`string`&&e.data.description&&(0,Q.jsx)(`p`,{className:`whitespace-pre-wrap text-xs text-muted-foreground`,children:e.data.description}),(0,Q.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Edit the task in the Todos app or on its document page.`})]})}function It({menu:e,onClose:t,onOpen:n,onOpenDocument:r,onToggleDone:i,onDelete:o,onCreate:s,onPickDay:c}){let l=e=>()=>{t(),e()};return(0,Q.jsx)(S,{x:e.x,y:e.y,onClose:t,className:`min-w-44 rounded-md border bg-popover p-1 text-xs shadow-elevation-3`,children:e.kind===`entry`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`truncate px-3 py-1.5 text-[11px] text-muted-foreground`,title:e.occurrence.title,children:e.occurrence.title}),(0,Q.jsx)(Lt,{icon:(0,Q.jsx)(h,{className:`h-3.5 w-3.5`}),onClick:l(()=>n(e.occurrence)),children:`Open`}),r&&(0,Q.jsx)(Lt,{icon:(0,Q.jsx)(_,{className:`h-3.5 w-3.5`}),onClick:l(()=>r(e.occurrence)),children:`Open document`}),e.occurrence.kind===`task`&&(0,Q.jsx)(Lt,{icon:e.occurrence.done?(0,Q.jsx)(g,{className:`h-3.5 w-3.5`}):(0,Q.jsx)(a,{className:`h-3.5 w-3.5`}),onClick:l(()=>i(e.occurrence)),children:e.occurrence.done?`Mark as pending`:`Mark as completed`}),e.occurrence.kind===`event`&&(0,Q.jsx)(Lt,{icon:(0,Q.jsx)(f,{className:`h-3.5 w-3.5`}),className:`text-destructive`,onClick:l(()=>o(e.occurrence)),children:`Delete…`})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`p`,{className:`px-3 py-1.5 text-[11px] text-muted-foreground`,children:[ge(e.start),e.allDay?``:`, ${Z(e.start)}`]}),(0,Q.jsx)(Lt,{icon:(0,Q.jsx)(y,{className:`h-3.5 w-3.5`}),onClick:l(()=>s(e.start,e.allDay)),children:e.allDay?`New event`:`New event at ${Z(e.start)}`}),!e.allDay&&(0,Q.jsx)(Lt,{icon:(0,Q.jsx)(m,{className:`h-3.5 w-3.5`}),onClick:l(()=>s(e.start,!0)),children:`New all-day event`}),(0,Q.jsx)(Lt,{icon:(0,Q.jsx)(h,{className:`h-3.5 w-3.5`}),onClick:l(()=>c(e.start)),children:`Open day`})]})})}function Lt({icon:e,onClick:t,className:n,children:r}){return(0,Q.jsxs)(`button`,{type:`button`,onClick:t,className:x(`flex w-full items-center gap-2 rounded px-3 py-1.5 text-left hover:bg-accent`,n),children:[(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:e}),r]})}var Rt=640,zt=420,Bt=30,Vt=14;function Ht(e,t,n,r){switch(e){case`day`:{let e=U(t);return{start:e,end:W(e,n)}}case`week`:{let e=ce(t);return{start:e,end:W(e,7)}}case`month`:{let e=K(t);return{start:e[0],end:W(e[41],1)}}case`year`:return{start:new Date(t.getFullYear(),0,1),end:new Date(t.getFullYear()+1,0,1)};case`schedule`:{let e=U(t);return{start:W(e,-r.before),end:W(e,r.after)}}}}function Ut(e,t,n,r){switch(e){case`day`:return W(t,n*r);case`week`:return W(t,7*r);case`month`:return se(t,r);case`year`:return new Date(t.getFullYear()+r,t.getMonth(),1);case`schedule`:return W(t,Bt*r)}}function Wt(e,t,n,r){switch(e){case`day`:return n>1?_e(t,W(t,n-1)):r?ge(t):he(t);case`week`:return ve(ce(t));case`month`:return pe(t);case`year`:return String(t.getFullYear());case`schedule`:return r?ge(t):`From ${he(t)}`}}function Gt({autoAdd:e=!1}){let t=te(),n=t?.mode===`workspace`?t.workspaceName:t?.mode===`context`?`ctx:${t.contextId}`:null,[i,a]=(0,z.useState)(()=>Je(n)),c=(0,z.useCallback)(e=>{a(t=>{let r={...t,...e};return Ye(n,r),r})},[n]),l=i.view,[f,m]=(0,z.useState)(()=>U(new Date)),[h,g]=(0,z.useState)(1),[_,y]=(0,z.useState)(null),b=r(),[S,C]=(0,z.useState)({before:0,after:Bt}),[w,T]=(0,z.useState)(()=>e?{kind:`draft`,draft:{start:Kt(),allDay:!1}}:null),[E,D]=(0,z.useState)(!1),k=(0,z.useRef)(null),[A,ee]=(0,z.useState)(1024);(0,z.useEffect)(()=>{let e=k.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e)ee(t.contentRect.width)});return t.observe(e),()=>t.disconnect()},[]);let M=A<Rt,N=A<zt,P=(0,z.useMemo)(()=>Ht(l,f,h,S),[l,f,h,S]),{docs:F,loading:I,error:L,scope:R,knownCalendars:ne,reload:re,removeDoc:ae,patchDoc:B}=et(t,P.start,P.end,i.showTasks),V=(0,z.useMemo)(()=>{let e=new Map;for(let t of ne)e.set(t,t);for(let t of F){let n=t.data?.calendar;typeof n==`string`&&n.trim()&&e.set(n.trim().toLowerCase(),n.trim())}return i.defaultCalendar&&e.set(i.defaultCalendar.toLowerCase(),e.get(i.defaultCalendar.toLowerCase())??i.defaultCalendar),[...e.values()].sort((e,t)=>e.localeCompare(t))},[ne,F,i.defaultCalendar]),H=(0,z.useMemo)(()=>new Set(i.hidden),[i.hidden]),oe=(0,z.useMemo)(()=>F.some(e=>e.schema.startsWith(`data/schema/event`)&&!(typeof e.data?.calendar==`string`&&e.data.calendar.trim())),[F]),G=(0,z.useMemo)(()=>ze(F.filter(e=>{let t=typeof e.data?.calendar==`string`?e.data.calendar.trim().toLowerCase():``;return!H.has(t||``)}),P.start,P.end),[F,H,P]),K=w?.kind===`occurrence`?w.occurrence.key:null,q=(0,z.useCallback)((e,t)=>{m(U(e)),g(1),C({before:0,after:Bt}),t&&c({view:t})},[c]),J=(0,z.useCallback)((e,t)=>{let n=Math.round((U(t).getTime()-U(e).getTime())/ie);if(n>Vt){q(e,`month`);return}q(e,`day`),g(Math.max(1,n))},[q]),ue=(0,z.useCallback)(e=>{g(1),c({view:e})},[c]),Y=(0,z.useMemo)(()=>l===`day`||l===`week`?{start:P.start,end:P.end}:{start:f,end:W(f,1)},[l,P,f]),de=(0,z.useMemo)(()=>{if(w?.kind!==`draft`)return null;let{start:e,allDay:t,end:n}=w.draft;return{start:e,allDay:t,end:n??(t?W(U(e),1):new Date(e.getTime()+36e5))}},[w]),X=(0,z.useCallback)((e,t,n)=>T({kind:`draft`,draft:{start:e,allDay:t,end:n}}),[]),fe=(0,z.useCallback)(e=>T({kind:`occurrence`,occurrence:e}),[]),pe=(0,z.useCallback)(async(e,t,n)=>{if(!R)return;let r=e.doc,i=Ue(r.data??{},e,t,n);B({...r,data:i});try{await O(R.workspaceName,{id:r.id,schema:r.schema,schemaVersion:r.schemaVersion||`3.0`,data:i,metadata:r.metadata})}catch{B(r)}},[R,B]),me=(0,z.useCallback)(async e=>{if(!R)return;let t=e.doc,n=e.done?`pending`:`completed`,r={...t.data??{},status:n,completed:n===`completed`};B({...t,data:r});try{await O(R.workspaceName,{id:t.id,schema:t.schema,schemaVersion:t.schemaVersion,data:r,metadata:t.metadata})}catch{B(t)}},[R,B]),he=(0,z.useCallback)((e,t)=>y({x:e.clientX,y:e.clientY,kind:`entry`,occurrence:t}),[]),ge=(0,z.useCallback)((e,t,n)=>y({x:e.clientX,y:e.clientY,kind:`slot`,start:t,allDay:n}),[]),Z=(0,z.useCallback)(async e=>{let t=e.data?.title?`"${e.data.title}"`:`#${e.id}`;if(window.confirm(`Delete event ${t}?\n\nIt is removed from this path and moves to the workspace trash if nothing else links it.`))try{await ae(e.id),T(null)}catch{}},[ae]),_e=e=>{let t=e.target;if(!([`INPUT`,`TEXTAREA`,`SELECT`].includes(t.tagName)||t.isContentEditable)){if(e.key===`ArrowLeft`)ve(-1),e.preventDefault();else if(e.key===`ArrowRight`)ve(1),e.preventDefault();else if(e.key===`t`)q(new Date);else if(e.key===`n`)X(Kt(f),!1);else if(e.key===`Escape`)T(null),D(!1);else{let t=We.find(t=>t.key===e.key);t&&ue(t.id)}}},ve=e=>{let t=h;q(Ut(l,f,h,e)),g(t)};if(!t)return(0,Q.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:j(t)});let ye=e=>{let t=e.toLowerCase();c({hidden:H.has(t)?i.hidden.filter(e=>e!==t):[...i.hidden,t]})},be=(0,Q.jsxs)(`div`,{className:`space-y-1 text-xs`,children:[(0,Q.jsx)(`p`,{className:`px-1 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`Calendars`}),V.map(e=>(0,Q.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded px-1 py-0.5 hover:bg-muted`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:!H.has(e.toLowerCase()),onChange:()=>ye(e),className:`h-3.5 w-3.5 accent-primary`,style:{accentColor:tt(e)}}),(0,Q.jsx)(`span`,{className:`h-2.5 w-2.5 shrink-0 rounded-sm`,style:{background:tt(e)}}),(0,Q.jsx)(`span`,{className:`truncate`,children:e})]},e)),oe&&(0,Q.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded px-1 py-0.5 hover:bg-muted`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:!H.has(``),onChange:()=>ye(``),className:`h-3.5 w-3.5 accent-primary`}),(0,Q.jsx)(`span`,{className:`h-2.5 w-2.5 shrink-0 rounded-sm`,style:{background:tt(``)}}),(0,Q.jsx)(`span`,{className:`truncate text-muted-foreground`,children:`Other events`})]}),(0,Q.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded px-1 py-0.5 hover:bg-muted`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:i.showTasks,onChange:e=>c({showTasks:e.target.checked}),className:`h-3.5 w-3.5 accent-primary`}),(0,Q.jsx)(`span`,{className:`h-2.5 w-2.5 shrink-0 rounded-sm`,style:{background:tt(je)}}),(0,Q.jsx)(`span`,{className:`truncate`,children:`Tasks (due dates)`})]})]}),xe=(()=>{switch(l){case`day`:return(0,Q.jsx)(gt,{days:Array.from({length:h},(e,t)=>W(U(f),t)),occurrences:G,selectedKey:K,pending:de,onSelect:fe,onCreate:X,onMove:pe,onPickDay:e=>q(e,`day`),onEntryMenu:he,onSlotMenu:ge,compact:N||h>3});case`week`:return(0,Q.jsx)(gt,{days:Array.from({length:7},(e,t)=>W(ce(f),t)),occurrences:G,selectedKey:K,pending:de,onSelect:fe,onCreate:X,onMove:pe,onPickDay:e=>q(e,`day`),onEntryMenu:he,onSlotMenu:ge,compact:M});case`month`:return(0,Q.jsx)(vt,{month:le(f),occurrences:G,selectedKey:K,pending:de,onSelect:fe,onCreate:X,onMove:pe,onPickDay:e=>q(e,`day`),onEntryMenu:he,onSlotMenu:ge,narrow:M});case`year`:return(0,Q.jsx)(yt,{year:f.getFullYear(),occurrences:G,onPickDay:e=>q(e,`day`),onPickRange:J,onPickMonth:e=>q(e,`month`),onSlotMenu:ge});case`schedule`:return(0,Q.jsx)(bt,{occurrences:G,selectedKey:K,onSelect:fe,onEntryMenu:he,loading:I,onEarlier:()=>C(e=>({...e,before:e.before+Bt})),onLater:()=>C(e=>({...e,after:e.after+Bt})),onPickDay:e=>q(e,`day`)})}})();return(0,Q.jsxs)(`div`,{ref:k,tabIndex:0,onKeyDown:_e,className:`relative flex h-full min-h-0 flex-col outline-none`,children:[(0,Q.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-1.5 border-b border-border px-2 py-1.5`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:()=>q(new Date),className:`rounded-md border border-border px-2 py-1 text-xs hover:bg-muted`,title:`Today (t)`,children:`Today`}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>ve(-1),className:`rounded-md p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,"aria-label":`Previous`,title:`Previous (←)`,children:(0,Q.jsx)(o,{className:`h-4 w-4`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>ve(1),className:`rounded-md p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,"aria-label":`Next`,title:`Next (→)`,children:(0,Q.jsx)(d,{className:`h-4 w-4`})}),(0,Q.jsx)(`span`,{className:`min-w-0 truncate text-sm font-semibold`,children:Wt(l,f,h,N)}),I&&(0,Q.jsx)(v,{className:`h-3.5 w-3.5 animate-spin text-muted-foreground`}),(0,Q.jsx)(`span`,{className:`flex-1`}),N?(0,Q.jsx)(`select`,{value:l,onChange:e=>ue(e.target.value),"aria-label":`View`,className:`h-7 rounded-md border border-input bg-transparent px-1.5 text-xs`,children:We.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))}):(0,Q.jsx)(`div`,{className:`flex overflow-hidden rounded-md border border-border`,role:`tablist`,"aria-label":`View`,children:We.map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":l===e.id,onClick:()=>ue(e.id),title:`${e.label} (${e.key})`,className:x(`px-2 py-1 text-xs transition-colors`,l===e.id?`bg-foreground text-background`:`text-muted-foreground hover:bg-muted hover:text-foreground`),children:e.label},e.id))}),M&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>D(e=>!e),className:x(`rounded-md border p-1.5`,E?`border-foreground text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),"aria-label":`Calendars`,title:`Calendars`,children:(0,Q.jsx)(p,{className:`h-3.5 w-3.5`})}),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>X(Kt(f),!1),className:`flex items-center gap-1 rounded-md bg-primary px-2 py-1.5 text-xs text-primary-foreground`,title:`New event (n)`,children:[(0,Q.jsx)(u,{className:`h-3.5 w-3.5`}),!N&&`Event`]})]}),L&&(0,Q.jsx)(`p`,{className:`border-b border-border px-3 py-2 text-xs text-destructive`,children:L}),(0,Q.jsxs)(`div`,{className:`flex min-h-0 flex-1`,children:[!M&&(0,Q.jsxs)(`aside`,{className:`flex w-52 shrink-0 flex-col gap-4 overflow-y-auto border-r border-border p-3`,children:[(0,Q.jsx)(lt,{month:le(f),selection:Y,onPick:e=>q(e,l===`year`||l===`month`?`day`:l),onPickRange:J,onPrev:()=>m(e=>se(e,-1)),onNext:()=>m(e=>se(e,1))}),be]}),(0,Q.jsxs)(`div`,{className:`relative min-w-0 flex-1`,children:[xe,M&&E&&(0,Q.jsx)(`div`,{className:`absolute right-2 top-2 z-20 w-56 rounded-md border border-border bg-popover p-2 text-popover-foreground shadow-elevation-2`,children:be})]}),w&&!M&&(0,Q.jsx)(`aside`,{className:`w-80 shrink-0 border-l border-border bg-card`,children:(0,Q.jsx)(jt,{subject:w,target:t,workspaceName:R?.workspaceName??null,calendars:V,defaultCalendar:i.defaultCalendar,onClose:()=>T(null),onSaved:e=>{e&&c({defaultCalendar:e}),T(null),re()},onDelete:Z})})]}),w&&M&&(0,Q.jsx)(`div`,{className:`absolute inset-0 z-30 flex flex-col bg-card`,children:(0,Q.jsx)(jt,{subject:w,target:t,workspaceName:R?.workspaceName??null,calendars:V,defaultCalendar:i.defaultCalendar,onClose:()=>T(null),onSaved:e=>{e&&c({defaultCalendar:e}),T(null),re()},onDelete:Z})}),_&&(0,Q.jsx)(It,{menu:_,onClose:()=>y(null),onOpen:fe,onOpenDocument:R?e=>b(`/workspaces/${encodeURIComponent(R.workspaceName)}/documents/${e.doc.id}`):null,onToggleDone:e=>{me(e)},onDelete:e=>{Z(e.doc)},onCreate:(e,t)=>X(e,t),onPickDay:e=>q(e,`day`)}),!I&&!L&&!F.length&&l!==`schedule`&&(0,Q.jsxs)(`p`,{className:`pointer-events-none absolute bottom-2 left-1/2 -translate-x-1/2 rounded-full bg-muted/80 px-3 py-1 text-[11px] text-muted-foreground`,children:[(0,Q.jsx)(s,{className:`mr-1 inline h-3 w-3`}),`Nothing here yet — click or drag a slot to add an event.`]})]})}function Kt(e){let t=new Date,n=e&&!qt(e,t)?new Date(e.getFullYear(),e.getMonth(),e.getDate(),9,0):new Date(t);return(!e||qt(e,t))&&n.setMinutes(t.getMinutes()<30?30:60,0,0),n}function qt(e,t){return e.toDateString()===t.toDateString()}export{Gt as CalendarApplet};
@@ -1 +1 @@
1
- import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{t as r}from"./socket-CtH3EU9m.js";import{r as i}from"./use-toolbox-Ck_cLGgf.js";import{n as a}from"./use-applet-target-ffIGaAqT.js";import{C as o,M as s,v as c}from"./index-DRHEGJ8I.js";var l=e(n(),1),u=t();function d(){let e=a(),t=i()?.state,n=!!t&&(e?.mode===`context`?t.activeContextType===`context`&&t.activeContextId===e.contextId:e?.mode===`workspace`?t.activeContextType!==`context`&&t.activeWorkspaceName===e.workspaceName&&t.activeTreeName===e.treeName&&t.activeContextPath===e.path:!t.activeWorkspaceName&&!t.activeContextId),d=!n&&e?.mode===`context`?e.contextId:null;return(0,l.useEffect)(()=>{if(!d)return;let e=`context:${d}`,t=()=>r.emit(`subscribe`,{channel:e}),n=r.on(`connect`,t);return t(),()=>{n(),r.emit(`unsubscribe`,{channel:e})}},[d]),n?(0,u.jsx)(c,{}):(0,u.jsx)(s,{target:e,children:(0,u.jsx)(o,{children:(0,u.jsx)(c,{})})})}export{d as FiltersApplet};
1
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{t as r}from"./socket-CtH3EU9m.js";import{r as i}from"./use-toolbox-Ck_cLGgf.js";import{n as a}from"./use-applet-target-ffIGaAqT.js";import{C as o,N as s,v as c}from"./index-Cp75myNf.js";var l=e(n(),1),u=t();function d(){let e=a(),t=i()?.state,n=!!t&&(e?.mode===`context`?t.activeContextType===`context`&&t.activeContextId===e.contextId:e?.mode===`workspace`?t.activeContextType!==`context`&&t.activeWorkspaceName===e.workspaceName&&t.activeTreeName===e.treeName&&t.activeContextPath===e.path:!t.activeWorkspaceName&&!t.activeContextId),d=!n&&e?.mode===`context`?e.contextId:null;return(0,l.useEffect)(()=>{if(!d)return;let e=`context:${d}`,t=()=>r.emit(`subscribe`,{channel:e}),n=r.on(`connect`,t);return t(),()=>{n(),r.emit(`unsubscribe`,{channel:e})}},[d]),n?(0,u.jsx)(c,{}):(0,u.jsx)(s,{target:e,children:(0,u.jsx)(o,{children:(0,u.jsx)(c,{})})})}export{d as FiltersApplet};
@@ -0,0 +1,3 @@
1
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{yt as r}from"./react-BHzhHVTZ.js";import{g as i}from"./chunk-62JRHF6Z-vspAGgtK.js";import{Gr as a,L as o,Pt as s,U as c,W as l,_n as u,ar as d,hn as f,tt as p}from"./ui-CDoK3F3U.js";import{t as m}from"./utils-2pl1SbIp.js";import{t as h}from"./input-BOtCd4HP.js";import{t as g}from"./label-BSTdjCWU.js";import{t as _}from"./LinkToCard-BQ1yoFDr.js";import{zt as v}from"./workspace-BJELPCNs.js";import{t as ee}from"./use-mobile-Db-vWu9Y.js";import{a as y,i as b,s as x,t as te}from"./IdentityFields-DZRqtnIG.js";import{n as S,r as ne}from"./use-toolbox-Ck_cLGgf.js";import{l as re}from"./date-time-picker-txVhlNO0.js";import{n as C,t as ie}from"./PickDocumentsCard-CFDQL70e.js";import{t as w}from"./useToastHelpers-CRrpIIdY.js";import{r as T,t as E}from"./note-save-status-DPz4VzL6.js";import{t as D}from"./DocumentBodyEditor-CVO5KPCs.js";import{a as O,i as k,n as A,o as j,r as M,s as N,t as P}from"./UploadProgressList-Ci1akl_D.js";import{A as F,M as I,O as L,j as R,k as z}from"./index-Cp75myNf.js";var B=e(r(),1),V=e(n(),1),H=t();function U({onClose:e,initialData:t,draftId:n}){let r=F(void 0,void 0,`home-card:${n}`);return(0,V.useEffect)(()=>{t?.title&&r.setTitle(t.title),t?.content&&r.setContent(t.content)},[]),(0,H.jsx)(C,{title:`New Note`,icon:p,onClose:e,onSave:async e=>{let t=await r.save({mode:`workspace`,...e});return r.finish(),t},canSave:r.canSave,saving:r.saving,successMessage:`Note created`,children:(0,H.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsx)(g,{htmlFor:`qa-note-title`,children:`Title`}),(0,H.jsx)(h,{id:`qa-note-title`,value:r.title,onChange:e=>r.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,H.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,H.jsx)(g,{children:`Body`}),(0,H.jsx)(`div`,{className:`flex-1`,children:(0,H.jsx)(D,{kind:`markdown`,value:r.content,onChange:r.setContent,placeholder:`Write your note…`})})]}),(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsx)(g,{children:`Tags`}),(0,H.jsx)(x,{tags:r.tags,onChange:r.setTags})]}),(0,H.jsx)(E,{...r,onRetry:r.retry}),(0,H.jsx)(N,{geotag:r.geotag,idPrefix:`qa-note-geotag`})]})})}function W({onClose:e,initialData:t}){let n=L();return(0,V.useEffect)(()=>{t?.url&&n.setUrl(t.url),t?.title&&n.setTitle(t.title)},[]),(0,H.jsx)(C,{title:`New Link`,icon:u,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Link created`,children:(0,H.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsx)(g,{htmlFor:`qa-link-url`,children:`URL`}),(0,H.jsx)(h,{id:`qa-link-url`,value:n.url,onChange:e=>n.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),n.showUrlError&&(0,H.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsx)(g,{htmlFor:`qa-link-title`,children:`Title`}),(0,H.jsx)(h,{id:`qa-link-title`,value:n.title,onChange:e=>n.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsx)(g,{children:`Tags`}),(0,H.jsx)(x,{tags:n.tags,onChange:n.setTags})]}),(0,H.jsx)(z,{webapp:n.webapp,setWebapp:n.setWebapp,category:n.category,setCategory:n.setCategory,idPrefix:`qa-link`}),(0,H.jsx)(N,{geotag:n.geotag,idPrefix:`qa-link-geotag`})]})})}function G({onClose:e,initialData:t}){let n=re();return(0,V.useEffect)(()=>{t?.title&&n.setTitle(t.title),t?.content&&n.setDescription(t.content)},[]),(0,H.jsx)(C,{title:`New Todo`,icon:f,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Todo created`,children:(0,H.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,H.jsx)(y,{...n,idPrefix:`qa-todo`}),(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsx)(g,{children:`Tags`}),(0,H.jsx)(x,{tags:n.tags,onChange:n.setTags})]}),(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsx)(g,{htmlFor:`qa-todo-comment`,children:`Comment`}),(0,H.jsx)(`textarea`,{id:`qa-todo-comment`,value:n.comment,onChange:e=>n.setComment(e.target.value),rows:3,placeholder:`Optional context`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]}),(0,H.jsx)(N,{geotag:n.geotag,idPrefix:`qa-todo-geotag`})]})})}function K({onClose:e,initialData:t}){let n=b();return(0,V.useEffect)(()=>{t?.title&&n.setDisplayName(t.title)},[]),(0,H.jsx)(C,{title:`New Identity`,icon:c,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Identity created`,children:(0,H.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,H.jsx)(te,{idPrefix:`qa-identity`,...n,emailValid:n.emailValid}),(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsx)(g,{children:`Tags`}),(0,H.jsx)(x,{tags:n.tags,onChange:n.setTags})]}),(0,H.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,H.jsx)(g,{htmlFor:`qa-identity-comment`,children:`Comment`}),(0,H.jsx)(`textarea`,{id:`qa-identity-comment`,value:n.comment,onChange:e=>n.setComment(e.target.value),rows:3,placeholder:`How you know them, where they came from…`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]})]})})}var q={jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,heic:`image/heic`,heif:`image/heif`,bmp:`image/bmp`,tif:`image/tiff`,tiff:`image/tiff`,svg:`image/svg+xml`,mp4:`video/mp4`,mov:`video/quicktime`,webm:`video/webm`,"3gp":`video/3gpp`};function J(e){return/^(image|video)\//.test(e.type)}async function ae(e){let t=await Promise.all(e.map(async e=>{let t=new Uint8Array(await e.slice(0,64).arrayBuffer()),n=(e,n)=>String.fromCharCode(...t.slice(e,e+n)),r=``;if(t[0]===255&&t[1]===216&&t[2]===255)r=`image/jpeg`;else if(n(0,8)===`‰PNG\r
2
+ 
3
+ `)r=`image/png`;else if([`GIF87a`,`GIF89a`].includes(n(0,6)))r=`image/gif`;else if(n(0,4)===`RIFF`&&n(8,4)===`WEBP`)r=`image/webp`;else if(n(0,5)===`%PDF-`)r=`application/pdf`;else if(n(0,4)===`PK`)r=`application/zip`;else if(n(4,4)===`ftyp`){let e=[n(8,4)],i=new DataView(t.buffer).getUint32(0);for(let r=16;r+4<=Math.min(t.length,i);r+=4)e.push(n(r,4));e.some(e=>[`avif`,`avis`].includes(e))?r=`image/avif`:e.some(e=>[`heic`,`heix`,`hevc`,`hevx`].includes(e))?r=`image/heic`:e.some(e=>[`mif1`,`msf1`].includes(e))?r=`image/heif`:e.includes(`qt `)?r=`video/quicktime`:e.some(e=>[`isom`,`iso2`,`mp41`,`mp42`,`avc1`,`M4V `].includes(e))&&(r=`video/mp4`)}let i=e.type.toLowerCase().split(`;`)[0].trim(),a=!i||[`application/octet-stream`,`binary/octet-stream`,`*/*`].includes(i),o=e.name.split(`.`).pop()?.toLowerCase()??``,s=r||a&&q[o]||i;return s===e.type?e:new File([e],e.name,{type:s,lastModified:e.lastModified})}));return{kind:t.length>0&&t.every(J)?`photo`:`file`,files:t}}function Y({file:e}){let t=(0,V.useRef)(null),[n,r]=(0,V.useState)(!1);return(0,V.useEffect)(()=>{let n=t.current;if(!n)return;let r=URL.createObjectURL(e);return n.src=r,()=>{n.removeAttribute(`src`),URL.revokeObjectURL(r)}},[e]),(0,H.jsx)(`div`,{className:`flex min-h-24 items-center justify-center overflow-hidden rounded-md border border-input bg-muted/30`,children:n?(0,H.jsxs)(`p`,{className:`p-4 text-center text-sm text-muted-foreground`,children:[`Preview unavailable for `,e.name,`. You can still save the original.`]}):e.type.startsWith(`video/`)?(0,H.jsx)(`video`,{ref:t,controls:!0,preload:`metadata`,"aria-label":e.name,onError:()=>r(!0),className:`max-h-64 max-w-full`}):(0,H.jsx)(`img`,{ref:t,alt:e.name,onError:()=>r(!0),className:`max-h-64 max-w-full object-contain`})})}function oe({onClose:e,initialData:t}){let n=(0,V.useRef)(null),r=M(t?.files),i=r.items.map(e=>e.file),[a,o]=(0,V.useState)(!1),[s,c]=(0,V.useState)(!1),{state:u}=S(),d=j(u.activeWorkspaceName),f=e=>{e&&(s||r.addFiles(Array.from(e)))},p=e=>{e.preventDefault(),o(!1),f(e.dataTransfer.files)},h=i.length>0;return(0,H.jsx)(C,{title:`Upload File`,icon:l,onClose:e,onSave:async e=>{c(!0);try{let t={mode:`workspace`,...e},n=await d.geotag.capture(),i=await r.start(t,(e,t)=>O(e,t,{tags:d.tags,comment:d.comment,geo:n}));if(i.failed)throw Error(`${i.failed} file(s) failed or cancelled. Retry keeps completed uploads.`);return i.docIds}finally{c(!1)}},navigateAfterSave:!0,canSave:h,saving:s,saveProgress:(0,H.jsx)(A,{items:r.items,running:r.running,onCancel:r.cancel}),successMessage:`File(s) uploaded`,children:(0,H.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,H.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),o(!0)},onDragLeave:()=>o(!1),onDrop:p,onClick:()=>n.current?.click(),className:m(`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-dashed px-4 py-8 text-center transition-colors`,a?`border-primary bg-primary/5`:`border-input hover:bg-muted/40`),children:[(0,H.jsx)(l,{className:`h-6 w-6 text-muted-foreground touch-target`}),(0,H.jsx)(`p`,{className:`text-sm`,children:`Drag & drop files here`}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`or click to browse`}),(0,H.jsx)(`input`,{ref:n,type:`file`,multiple:!0,disabled:s,className:`hidden`,onChange:e=>{f(e.target.files),e.target.value=``}})]}),r.items.filter(e=>J(e.file)).map(e=>(0,H.jsx)(Y,{file:e.file},e.id)),(0,H.jsx)(P,{items:r.items,running:s,onRemove:r.removeItem}),(0,H.jsx)(k,{fields:d,idPrefix:`qa-file`,multiple:i.length>1})]})})}function se({onClose:e,initialData:t}){let n=M(t?.files),r=(0,V.useRef)(null),i=n.items.length>0,[s,c]=(0,V.useState)(!1),{state:l}=S(),u=j(l.activeWorkspaceName),f=e=>{!s&&e&&n.addFiles([e])};return(0,H.jsx)(C,{title:`Photo/Video`,icon:a,onClose:e,onSave:async e=>{if(!i)return[];c(!0);try{let t=await u.geotag.capture(),r={mode:`workspace`,...e},i=await n.start(r,(e,n)=>O(e,n,{tags:u.tags,comment:u.comment,geo:t}));if(i.failed)throw Error(`Upload failed or cancelled. You can retry.`);return i.docIds}finally{c(!1)}},navigateAfterSave:!0,canSave:i,saving:s,saveProgress:(0,H.jsx)(A,{items:n.items,running:n.running,onCancel:n.cancel}),successMessage:`Upload saved`,children:(0,H.jsxs)(`div`,{className:m(`flex h-full flex-col gap-4 p-4`,!i&&`items-center justify-center`),children:[i?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:`flex min-h-0 w-full flex-1 flex-col gap-3 overflow-y-auto`,children:n.items.map(({id:e,file:t,status:r})=>(0,H.jsxs)(`div`,{className:`space-y-2`,children:[(0,H.jsx)(Y,{file:t}),(0,H.jsxs)(`div`,{className:`flex w-full items-center gap-2 rounded border border-input px-3 py-2 text-sm`,children:[(0,H.jsx)(d,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,H.jsx)(`span`,{className:`flex-1 truncate`,children:t.name}),(0,H.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[(t.size/1024/1024).toFixed(1),` MB`]}),(0,H.jsx)(`button`,{type:`button`,disabled:s||r===`done`,onClick:()=>n.removeItem(e),"aria-label":`Remove ${t.name}`,className:`text-muted-foreground hover:text-foreground disabled:opacity-40`,children:(0,H.jsx)(o,{className:`h-3.5 w-3.5`})})]})]},e))}),(0,H.jsx)(`div`,{className:`w-full shrink-0 space-y-4`,children:(0,H.jsx)(k,{fields:u,idPrefix:`qa-photo`,multiple:n.items.length>1})})]}):(0,H.jsxs)(`button`,{type:`button`,onClick:()=>r.current?.click(),className:`flex flex-col items-center gap-2 rounded-md border border-dashed border-input px-6 py-10 text-center transition-colors hover:bg-muted/40`,children:[(0,H.jsx)(a,{className:`h-8 w-8 text-muted-foreground`}),(0,H.jsx)(`span`,{className:`text-sm`,children:`Open camera`})]}),(0,H.jsx)(`input`,{ref:r,type:`file`,accept:`image/*,video/*`,capture:`environment`,className:`hidden`,disabled:s,onChange:e=>{f(e.target.files?.[0]??null),e.target.value=``}})]})})}var X=`shrink-0 h-viewport-card w-[min(380px,90vw)] max-md:fixed max-md:inset-2 max-md:z-40 max-md:h-auto max-md:w-auto max-md:shadow-elevation-5`;function ce({onClose:e}){let{showSuccessToast:t,showErrorToast:n}=w(),[r,i]=(0,V.useState)(null),[a,o]=(0,V.useState)(!1);return r?(0,H.jsx)(_,{sizeClassName:X,documentCount:r.length,saving:a,onClose:e,onConfirm:async(i,a)=>{o(!0);try{await Promise.all(i.map(e=>v(a.workspaceName,e,r,a.treeName,a.treeType))),t(`${r.length} document${r.length===1?``:`s`} linked`),e()}catch(e){n(e instanceof Error?e.message:`Failed to link documents`)}finally{o(!1)}}}):(0,H.jsx)(ie,{sizeClassName:X,onConfirm:e=>{e.length&&i(e)},onClose:e})}function Z(){let e=T(`new:home-card:`);try{return Object.keys(localStorage).filter(t=>t.startsWith(e)&&t.endsWith(`:home`)).filter(e=>{let t=JSON.parse(localStorage.getItem(e)||`null`)?.value;return t&&(t.title||t.content||t.comment||t.tags?.length)}).map(t=>t.slice(e.length,-5))}catch{return[]}}var Q=0;function le(){return Q+=1,`card-${Q}`}function $({initialKind:e,initialData:t,onInitialCardClose:n,onCardsOpenChange:r}){let[a,c]=(0,V.useState)(!1),l=ee(),u=ne(),d=!!(u?.state.t1Open||u?.state.addOpen),[f,p]=(0,V.useState)(()=>e?[{id:`initial`,kind:e,initialData:t,noteDraftId:crypto.randomUUID()}]:Z().map(e=>({id:e,kind:`note`,noteDraftId:e}))),h=f.length>0,g=(0,V.useRef)(r);(0,V.useEffect)(()=>{g.current=r},[r]),(0,V.useEffect)(()=>{g.current?.(h)},[h]),d&&a&&c(!1);let _=i(),v=e=>{if(e===`sketch`){c(!1),_(I.createUrl(null));return}let t=e===`note`?Z().find(e=>!f.some(t=>t.noteDraftId===e))||crypto.randomUUID():void 0;p(n=>[...n,{id:le(),kind:e,noteDraftId:t}]),c(!1)},y=e=>{p(t=>t.filter(t=>t.id!==e)),e===`initial`&&n?.()},b=(0,H.jsxs)(`div`,{className:m(`pointer-events-none fixed right-6 z-40 flex flex-col items-end gap-2`,`bottom-fab-inset md:bottom-[calc(var(--spacing-fab-inset)+5rem)]`,f.length>0&&`max-md:hidden`,d&&`hidden`),children:[(0,H.jsx)(`div`,{className:m(`flex flex-col items-end gap-2 transition-all duration-fast`,a?`pointer-events-auto opacity-100`:`pointer-events-none translate-y-2 opacity-0`),children:(0,H.jsx)(R,{variant:`stack`,omit:[`plaintext`,`folder`,`message`],onSelect:v})}),(0,H.jsx)(`div`,{className:`pointer-events-none flex w-16 justify-center`,children:(0,H.jsx)(`button`,{type:`button`,onClick:()=>c(e=>!e),"aria-label":a?`Close quick add`:`Quick add`,className:`pointer-events-auto flex h-11 w-11 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-elevation-3 transition-transform hover:scale-105`,children:a?(0,H.jsx)(o,{className:`h-5 w-5`}):(0,H.jsx)(s,{className:`h-5 w-5`})})})]});return(0,H.jsxs)(`div`,{className:`relative flex h-full w-full flex-col`,children:[f.length>0&&(0,H.jsx)(`div`,{className:`pointer-events-auto flex flex-1 items-center gap-4 overflow-x-auto p-6 md:pr-28`,children:f.map(e=>{let t=()=>y(e.id);switch(e.kind){case`note`:return(0,H.jsx)(U,{draftId:e.noteDraftId,onClose:t,initialData:e.initialData},e.id);case`link`:return(0,H.jsx)(W,{onClose:t,initialData:e.initialData},e.id);case`todo`:return(0,H.jsx)(G,{onClose:t,initialData:e.initialData},e.id);case`identity`:return(0,H.jsx)(K,{onClose:t,initialData:e.initialData},e.id);case`file`:return(0,H.jsx)(oe,{onClose:t,initialData:e.initialData},e.id);case`photo`:return(0,H.jsx)(se,{onClose:t,initialData:e.initialData},e.id);case`existing`:return(0,H.jsx)(ce,{onClose:t},e.id);case`sketch`:return null;case`folder`:case`message`:return null}})}),l?(0,B.createPortal)(b,document.body):b]})}export{ae as n,$ as t};
@@ -1 +1 @@
1
- import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{$n as r,Gr as i,Nr as a,Xt as o}from"./ui-CDoK3F3U.js";import{t as s}from"./utils-2pl1SbIp.js";import{An as c,Nn as l}from"./workspace-BJELPCNs.js";import{t as u}from"./useDocumentThumbnail-wW0lSOEy.js";import{t as d}from"./DocumentIcon-9i1uCMQa.js";import{n as f}from"./use-document-modal-PG8bQyIB.js";import{n as p}from"./use-applet-target-ffIGaAqT.js";import{D as m,E as h,S as g,T as _,b as v,w as y,x as b}from"./index-DRHEGJ8I.js";var x=e(n(),1),S=t(),C=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring`,w=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`;function T({workspaceRef:e,doc:t,distance:n,onOpen:r}){let i=l(t),{blobUrl:a}=u(e,t.id,256,{enabled:i}),o=c(t);return(0,S.jsxs)(`button`,{type:`button`,onClick:()=>r(t),title:`Open ${o.title}`,className:`rounded-(--card-radius) border border-border bg-card overflow-hidden flex flex-col text-left cursor-pointer transition-colors hover:border-foreground/30 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,S.jsx)(`div`,{className:`aspect-square bg-muted/40 flex items-center justify-center overflow-hidden`,children:i&&a?(0,S.jsx)(`img`,{src:a,alt:o.title,className:`h-full w-full object-cover`}):(0,S.jsx)(d,{document:t,size:10})}),(0,S.jsxs)(`div`,{className:`p-2 min-w-0`,children:[(0,S.jsx)(`div`,{className:`text-xs font-medium truncate`,title:o.title,children:o.title}),(0,S.jsxs)(`div`,{className:`text-[10px] text-muted-foreground truncate`,children:[o.schemaLabel,n==null?``:` · d=${n.toFixed(3)}`]})]})]})}function E(){let e=p(),t=f(),n=h(),{rateMs:c,setRateMs:l,text:u,setText:d,maxDistance:E,setMaxDistance:D,latencyMs:O,error:k}=n,A=e?.mode===`workspace`?e.workspaceName:``,j=e?.mode===`workspace`&&e.path!==`/`?e.path:null,M=n.running&&n.consumer===`applet`,N=n.running&&n.consumer!==`applet`,P=M?n.hits:[];m(M);let F=M?n.snapshotSize??n.camera?.size:null,I=!!F&&F.height>F.width,L=e=>{A&&n.start(e,`applet`,{workspaceRef:A,contextPath:j})},{setContextPath:R}=n;return(0,x.useEffect)(()=>{M&&R(j)},[M,j,R]),e?.mode===`workspace`?(0,S.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3`,children:[(0,S.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2`,children:[(0,S.jsx)(`select`,{className:C,value:c,onChange:e=>l(Number(e.target.value)),title:`Frame rate. High rates (10–30 fps) are experimental; the loop never overlaps requests, so the effective rate is capped by search latency.`,children:_.map(e=>(0,S.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,S.jsx)(`input`,{className:s(w,`w-44`),placeholder:`Optional text (fused mode)`,value:u,onChange:e=>d(e.target.value)}),(0,S.jsx)(`input`,{className:s(w,`w-28`),placeholder:`max distance`,inputMode:`decimal`,value:E,onChange:e=>D(e.target.value),title:`Cosine-distance floor (0 = identical). Empty = top-K.`}),M?(0,S.jsxs)(`button`,{type:`button`,onClick:n.stop,className:`flex h-8 items-center gap-1 rounded-md bg-destructive px-3 text-xs font-medium text-destructive-foreground transition-colors hover:bg-destructive/90`,children:[(0,S.jsx)(a,{className:`h-3.5 w-3.5`}),` `,n.source===`photo`?`Close photo`:`Stop`]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`button`,{type:`button`,onClick:()=>L(`camera`),disabled:N,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,S.jsx)(i,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,S.jsxs)(`button`,{type:`button`,onClick:()=>L(`screen`),disabled:N,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,S.jsx)(o,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,S.jsx)(b,{consumer:`applet`,workspaceRef:A,contextPath:j,disabled:N,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`})]}),(0,S.jsxs)(`div`,{className:s(`relative shrink-0 overflow-hidden rounded-xl border border-border bg-black/80`,I?`aspect-[3/4] max-h-[60vh]`:`aspect-video max-h-80`),children:[M&&(0,S.jsx)(y,{className:`h-full w-full`,interactive:!0}),M&&(0,S.jsx)(g,{}),!M&&(0,S.jsxs)(`div`,{className:`absolute inset-0 flex items-center justify-center text-sm text-muted-foreground`,children:[(0,S.jsx)(r,{className:`mr-2 h-4 w-4`}),` camera off · or pick a photo`]})]}),M&&(0,S.jsx)(v,{className:`shrink-0`}),(0,S.jsx)(`div`,{className:`shrink-0 text-xs text-muted-foreground`,children:k?(0,S.jsx)(`span`,{className:`text-destructive`,children:k}):M?(0,S.jsxs)(S.Fragment,{children:[n.snapshot?`snapshot`:`live`,` · `,O==null?`searching…`:`${O} ms/frame`,` · `,P.length,` match`,P.length===1?``:`es`,j?` · scoped to ${j}`:``]}):N?`The Lens filter is using the camera. Stop it there first.`:`Frames are ephemeral: embedded for the query, never stored or indexed.`}),P.length===0?(0,S.jsx)(`div`,{className:`flex min-h-24 flex-1 items-center justify-center rounded-xl border border-dashed border-border text-sm text-muted-foreground`,children:M?n.snapshot?`Nothing similar in the snapshot`:`Nothing matching in view`:`Matches appear here`}):(0,S.jsx)(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4`,children:P.map(e=>(0,S.jsx)(T,{workspaceRef:A,doc:e.doc,distance:e.distance,onOpen:e=>t.open(e,A)},e.doc.id))})]}):(0,S.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:`Lens searches a workspace. Bind it to a workspace path to start.`})}export{E as LensApplet};
1
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{$n as r,Gr as i,Nr as a,Xt as o}from"./ui-CDoK3F3U.js";import{t as s}from"./utils-2pl1SbIp.js";import{An as c,Nn as l}from"./workspace-BJELPCNs.js";import{t as u}from"./useDocumentThumbnail-wW0lSOEy.js";import{t as d}from"./DocumentIcon-9i1uCMQa.js";import{n as f}from"./use-document-modal-PG8bQyIB.js";import{n as p}from"./use-applet-target-ffIGaAqT.js";import{D as m,E as h,S as g,T as _,b as v,w as y,x as b}from"./index-Cp75myNf.js";var x=e(n(),1),S=t(),C=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring`,w=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`;function T({workspaceRef:e,doc:t,distance:n,onOpen:r}){let i=l(t),{blobUrl:a}=u(e,t.id,256,{enabled:i}),o=c(t);return(0,S.jsxs)(`button`,{type:`button`,onClick:()=>r(t),title:`Open ${o.title}`,className:`rounded-(--card-radius) border border-border bg-card overflow-hidden flex flex-col text-left cursor-pointer transition-colors hover:border-foreground/30 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,S.jsx)(`div`,{className:`aspect-square bg-muted/40 flex items-center justify-center overflow-hidden`,children:i&&a?(0,S.jsx)(`img`,{src:a,alt:o.title,className:`h-full w-full object-cover`}):(0,S.jsx)(d,{document:t,size:10})}),(0,S.jsxs)(`div`,{className:`p-2 min-w-0`,children:[(0,S.jsx)(`div`,{className:`text-xs font-medium truncate`,title:o.title,children:o.title}),(0,S.jsxs)(`div`,{className:`text-[10px] text-muted-foreground truncate`,children:[o.schemaLabel,n==null?``:` · d=${n.toFixed(3)}`]})]})]})}function E(){let e=p(),t=f(),n=h(),{rateMs:c,setRateMs:l,text:u,setText:d,maxDistance:E,setMaxDistance:D,latencyMs:O,error:k}=n,A=e?.mode===`workspace`?e.workspaceName:``,j=e?.mode===`workspace`&&e.path!==`/`?e.path:null,M=n.running&&n.consumer===`applet`,N=n.running&&n.consumer!==`applet`,P=M?n.hits:[];m(M);let F=M?n.snapshotSize??n.camera?.size:null,I=!!F&&F.height>F.width,L=e=>{A&&n.start(e,`applet`,{workspaceRef:A,contextPath:j})},{setContextPath:R}=n;return(0,x.useEffect)(()=>{M&&R(j)},[M,j,R]),e?.mode===`workspace`?(0,S.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3`,children:[(0,S.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2`,children:[(0,S.jsx)(`select`,{className:C,value:c,onChange:e=>l(Number(e.target.value)),title:`Frame rate. High rates (10–30 fps) are experimental; the loop never overlaps requests, so the effective rate is capped by search latency.`,children:_.map(e=>(0,S.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,S.jsx)(`input`,{className:s(w,`w-44`),placeholder:`Optional text (fused mode)`,value:u,onChange:e=>d(e.target.value)}),(0,S.jsx)(`input`,{className:s(w,`w-28`),placeholder:`max distance`,inputMode:`decimal`,value:E,onChange:e=>D(e.target.value),title:`Cosine-distance floor (0 = identical). Empty = top-K.`}),M?(0,S.jsxs)(`button`,{type:`button`,onClick:n.stop,className:`flex h-8 items-center gap-1 rounded-md bg-destructive px-3 text-xs font-medium text-destructive-foreground transition-colors hover:bg-destructive/90`,children:[(0,S.jsx)(a,{className:`h-3.5 w-3.5`}),` `,n.source===`photo`?`Close photo`:`Stop`]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`button`,{type:`button`,onClick:()=>L(`camera`),disabled:N,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,S.jsx)(i,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,S.jsxs)(`button`,{type:`button`,onClick:()=>L(`screen`),disabled:N,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,S.jsx)(o,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,S.jsx)(b,{consumer:`applet`,workspaceRef:A,contextPath:j,disabled:N,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`})]}),(0,S.jsxs)(`div`,{className:s(`relative shrink-0 overflow-hidden rounded-xl border border-border bg-black/80`,I?`aspect-[3/4] max-h-[60vh]`:`aspect-video max-h-80`),children:[M&&(0,S.jsx)(y,{className:`h-full w-full`,interactive:!0}),M&&(0,S.jsx)(g,{}),!M&&(0,S.jsxs)(`div`,{className:`absolute inset-0 flex items-center justify-center text-sm text-muted-foreground`,children:[(0,S.jsx)(r,{className:`mr-2 h-4 w-4`}),` camera off · or pick a photo`]})]}),M&&(0,S.jsx)(v,{className:`shrink-0`}),(0,S.jsx)(`div`,{className:`shrink-0 text-xs text-muted-foreground`,children:k?(0,S.jsx)(`span`,{className:`text-destructive`,children:k}):M?(0,S.jsxs)(S.Fragment,{children:[n.snapshot?`snapshot`:`live`,` · `,O==null?`searching…`:`${O} ms/frame`,` · `,P.length,` match`,P.length===1?``:`es`,j?` · scoped to ${j}`:``]}):N?`The Lens filter is using the camera. Stop it there first.`:`Frames are ephemeral: embedded for the query, never stored or indexed.`}),P.length===0?(0,S.jsx)(`div`,{className:`flex min-h-24 flex-1 items-center justify-center rounded-xl border border-dashed border-border text-sm text-muted-foreground`,children:M?n.snapshot?`Nothing similar in the snapshot`:`Nothing matching in view`:`Matches appear here`}):(0,S.jsx)(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4`,children:P.map(e=>(0,S.jsx)(T,{workspaceRef:A,doc:e.doc,distance:e.distance,onOpen:e=>t.open(e,A)},e.doc.id))})]}):(0,S.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:`Lens searches a workspace. Bind it to a workspace path to start.`})}export{E as LensApplet};
@@ -1 +1 @@
1
- import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{L as r,Pt as i,hi as a,li as o,pn as s,yt as c}from"./ui-CDoK3F3U.js";import{t as l}from"./utils-2pl1SbIp.js";import{Bn as u}from"./workspace-BJELPCNs.js";import{t as d}from"./useAddTarget-B3b6TyZr.js";import{t as f}from"./note-save-status-DPz4VzL6.js";import{t as p}from"./useEditNoteFields-DXLTFEqL.js";import{n as m}from"./use-applet-target-ffIGaAqT.js";import{k as h}from"./index-DRHEGJ8I.js";import{n as g,r as _,t as v}from"./shared-BnpwVpxG.js";import{n as y,r as b}from"./use-applet-docs-B2dk__vk.js";var x=e(n(),1),S=t();function C({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o}){let s=p(e,t||``,!!t),{title:c,content:u,setTitle:d,setContent:m}=s,h=()=>{s.save().catch(()=>{})};return(0,S.jsxs)(`div`,{ref:t=>n(e.id,t),className:l(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,S.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,S.jsxs)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[y(e.createdAt),` · #`,e.id]}),(0,S.jsxs)(`div`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[(0,S.jsx)(f,{...s,onRetry:s.save}),(0,S.jsx)(g,{onLinkTo:a,onDelete:o})]})]}),(0,S.jsx)(`input`,{value:c,onChange:e=>d(e.target.value),onBlur:h,placeholder:`Untitled`,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,S.jsx)(v,{value:u,onChange:m,onBlur:h,innerRef:t=>r(e.id,t)})]})}function w({target:e,onCreated:t,onCancel:n}){let i=h(e,void 0,`applet`),{title:a,content:o,setTitle:s,setContent:c,saving:l}=i,[u,d]=(0,x.useState)(null),p=async()=>{try{await i.save(e),i.finish(),t()}catch(e){d(e instanceof Error?e.message:`Failed to save note`)}};return(0,S.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,S.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,S.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New note`}),(0,S.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Close note`,children:(0,S.jsx)(r,{className:`h-3 w-3`})})]}),(0,S.jsx)(`input`,{value:a,onChange:e=>s(e.target.value),placeholder:`Untitled`,autoFocus:!0,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,S.jsx)(v,{value:o,onChange:c,placeholder:`Write your note…`}),(0,S.jsx)(f,{...i,onRetry:i.retry}),u&&(0,S.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:u}),(0,S.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,S.jsx)(`button`,{type:`button`,onClick:p,disabled:!o.trim()||l,className:`rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground disabled:opacity-50`,children:l?`Saving…`:`Done`})})]})}function T({autoAdd:e=!1}){let t=m(),{docs:n,loading:r,error:l,scope:f,reload:p,removeDoc:h}=b(t,u),[g,v]=(0,x.useState)(``),[y,T]=(0,x.useState)(0),[E,D]=(0,x.useState)(`desc`),[O,k]=(0,x.useState)(e),[A,j]=(0,x.useState)(null),M=(0,x.useRef)(new Map),N=(0,x.useRef)(new Map),P=(0,x.useCallback)((e,t)=>{t?M.current.set(e,t):M.current.delete(e)},[]),F=(0,x.useCallback)((e,t)=>{t?N.current.set(e,t):N.current.delete(e)},[]),I=(0,x.useCallback)(async e=>{let t=e.data?.title?`"${e.data.title}"`:`#${e.id}`;if(window.confirm(`Delete note ${t}?\n\nIt is removed from this path and moves to the workspace trash if nothing else links it.`))try{await h(e.id)}catch{}},[h]),L=(0,x.useMemo)(()=>{let e=[...n];return e.sort((e,t)=>{let n=new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime();return E===`asc`?n:-n}),e},[n,E]),R=(0,x.useMemo)(()=>{let e=g.trim().toLowerCase();if(!e)return[];let t=[];for(let n of L){let r=String(n.data?.content??``),i=String(n.data?.title??``),a=r.toLowerCase().indexOf(e);a>=0?t.push({docId:n.id,offset:a}):i.toLowerCase().includes(e)&&t.push({docId:n.id,offset:-1})}return t},[g,L]),z=R.length?R[Math.min(y,R.length-1)]:null;(0,x.useEffect)(()=>{z&&M.current.get(z.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[z]);let B=(0,x.useCallback)(e=>{if(!R.length)return;let t=e?(y+1)%R.length:y;e&&T(t);let n=R[t],r=N.current.get(n.docId);r&&n.offset>=0&&(r.focus(),r.setSelectionRange(n.offset,n.offset+g.trim().length)),M.current.get(n.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[R,y,g]);return t?(0,S.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,S.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,S.jsxs)(`div`,{className:`relative flex-1`,children:[(0,S.jsx)(c,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,S.jsx)(`input`,{value:g,onChange:e=>{v(e.target.value),T(0)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),B(!0))},placeholder:`Search notes…`,spellCheck:!1,className:`w-full rounded-md border border-input bg-transparent py-1 pl-7 pr-14 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`}),g.trim()&&(0,S.jsx)(`span`,{className:`absolute right-2 top-1/2 -translate-y-1/2 text-[10px] tabular-nums text-muted-foreground`,children:R.length?`${Math.min(y+1,R.length)}/${R.length}`:`0/0`})]}),(0,S.jsx)(`button`,{type:`button`,onClick:()=>D(e=>e===`desc`?`asc`:`desc`),className:`rounded-md border border-border p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:E===`desc`?`Newest first (click for oldest first)`:`Oldest first (click for newest first)`,"aria-label":`Toggle sort order`,children:E===`desc`?(0,S.jsx)(a,{className:`h-3.5 w-3.5`}):(0,S.jsx)(o,{className:`h-3.5 w-3.5`})}),(0,S.jsxs)(`button`,{type:`button`,onClick:()=>k(!0),className:`flex items-center gap-1 rounded-md bg-primary px-2 py-1.5 text-xs text-primary-foreground`,title:`Add a note`,children:[(0,S.jsx)(i,{className:`h-3.5 w-3.5`}),`Note`]})]}),(0,S.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[O&&(0,S.jsx)(w,{target:t,onCreated:()=>{k(!1),p()},onCancel:()=>k(!1)},JSON.stringify(t)),r&&!n.length&&(0,S.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,S.jsx)(s,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),l&&(0,S.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:l}),!r&&!l&&!L.length&&!O&&(0,S.jsx)(`p`,{className:`px-4 py-10 text-center text-sm text-muted-foreground`,children:`No notes here yet - add the first one.`}),L.map(e=>(0,S.jsx)(C,{doc:e,updateWorkspace:f?.workspaceName??null,registerEl:P,registerBody:F,highlighted:z?.docId===e.id,onLinkTo:()=>j(e.id),onDelete:()=>I(e)},e.id))]}),A!==null&&(0,S.jsx)(_,{documentId:A,workspaceName:f?.workspaceName,onClose:()=>j(null)})]}):(0,S.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:d(t)})}export{T as NotesApplet};
1
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{L as r,Pt as i,hi as a,li as o,pn as s,yt as c}from"./ui-CDoK3F3U.js";import{t as l}from"./utils-2pl1SbIp.js";import{Bn as u}from"./workspace-BJELPCNs.js";import{t as d}from"./useAddTarget-B3b6TyZr.js";import{t as f}from"./note-save-status-DPz4VzL6.js";import{t as p}from"./useEditNoteFields-DXLTFEqL.js";import{n as m}from"./use-applet-target-ffIGaAqT.js";import{A as h}from"./index-Cp75myNf.js";import{n as g,r as _,t as v}from"./shared-BnpwVpxG.js";import{n as y,r as b}from"./use-applet-docs-B2dk__vk.js";var x=e(n(),1),S=t();function C({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o}){let s=p(e,t||``,!!t),{title:c,content:u,setTitle:d,setContent:m}=s,h=()=>{s.save().catch(()=>{})};return(0,S.jsxs)(`div`,{ref:t=>n(e.id,t),className:l(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,S.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,S.jsxs)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[y(e.createdAt),` · #`,e.id]}),(0,S.jsxs)(`div`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[(0,S.jsx)(f,{...s,onRetry:s.save}),(0,S.jsx)(g,{onLinkTo:a,onDelete:o})]})]}),(0,S.jsx)(`input`,{value:c,onChange:e=>d(e.target.value),onBlur:h,placeholder:`Untitled`,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,S.jsx)(v,{value:u,onChange:m,onBlur:h,innerRef:t=>r(e.id,t)})]})}function w({target:e,onCreated:t,onCancel:n}){let i=h(e,void 0,`applet`),{title:a,content:o,setTitle:s,setContent:c,saving:l}=i,[u,d]=(0,x.useState)(null),p=async()=>{try{await i.save(e),i.finish(),t()}catch(e){d(e instanceof Error?e.message:`Failed to save note`)}};return(0,S.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,S.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,S.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New note`}),(0,S.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Close note`,children:(0,S.jsx)(r,{className:`h-3 w-3`})})]}),(0,S.jsx)(`input`,{value:a,onChange:e=>s(e.target.value),placeholder:`Untitled`,autoFocus:!0,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,S.jsx)(v,{value:o,onChange:c,placeholder:`Write your note…`}),(0,S.jsx)(f,{...i,onRetry:i.retry}),u&&(0,S.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:u}),(0,S.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,S.jsx)(`button`,{type:`button`,onClick:p,disabled:!o.trim()||l,className:`rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground disabled:opacity-50`,children:l?`Saving…`:`Done`})})]})}function T({autoAdd:e=!1}){let t=m(),{docs:n,loading:r,error:l,scope:f,reload:p,removeDoc:h}=b(t,u),[g,v]=(0,x.useState)(``),[y,T]=(0,x.useState)(0),[E,D]=(0,x.useState)(`desc`),[O,k]=(0,x.useState)(e),[A,j]=(0,x.useState)(null),M=(0,x.useRef)(new Map),N=(0,x.useRef)(new Map),P=(0,x.useCallback)((e,t)=>{t?M.current.set(e,t):M.current.delete(e)},[]),F=(0,x.useCallback)((e,t)=>{t?N.current.set(e,t):N.current.delete(e)},[]),I=(0,x.useCallback)(async e=>{let t=e.data?.title?`"${e.data.title}"`:`#${e.id}`;if(window.confirm(`Delete note ${t}?\n\nIt is removed from this path and moves to the workspace trash if nothing else links it.`))try{await h(e.id)}catch{}},[h]),L=(0,x.useMemo)(()=>{let e=[...n];return e.sort((e,t)=>{let n=new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime();return E===`asc`?n:-n}),e},[n,E]),R=(0,x.useMemo)(()=>{let e=g.trim().toLowerCase();if(!e)return[];let t=[];for(let n of L){let r=String(n.data?.content??``),i=String(n.data?.title??``),a=r.toLowerCase().indexOf(e);a>=0?t.push({docId:n.id,offset:a}):i.toLowerCase().includes(e)&&t.push({docId:n.id,offset:-1})}return t},[g,L]),z=R.length?R[Math.min(y,R.length-1)]:null;(0,x.useEffect)(()=>{z&&M.current.get(z.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[z]);let B=(0,x.useCallback)(e=>{if(!R.length)return;let t=e?(y+1)%R.length:y;e&&T(t);let n=R[t],r=N.current.get(n.docId);r&&n.offset>=0&&(r.focus(),r.setSelectionRange(n.offset,n.offset+g.trim().length)),M.current.get(n.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[R,y,g]);return t?(0,S.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,S.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,S.jsxs)(`div`,{className:`relative flex-1`,children:[(0,S.jsx)(c,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,S.jsx)(`input`,{value:g,onChange:e=>{v(e.target.value),T(0)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),B(!0))},placeholder:`Search notes…`,spellCheck:!1,className:`w-full rounded-md border border-input bg-transparent py-1 pl-7 pr-14 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`}),g.trim()&&(0,S.jsx)(`span`,{className:`absolute right-2 top-1/2 -translate-y-1/2 text-[10px] tabular-nums text-muted-foreground`,children:R.length?`${Math.min(y+1,R.length)}/${R.length}`:`0/0`})]}),(0,S.jsx)(`button`,{type:`button`,onClick:()=>D(e=>e===`desc`?`asc`:`desc`),className:`rounded-md border border-border p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:E===`desc`?`Newest first (click for oldest first)`:`Oldest first (click for newest first)`,"aria-label":`Toggle sort order`,children:E===`desc`?(0,S.jsx)(a,{className:`h-3.5 w-3.5`}):(0,S.jsx)(o,{className:`h-3.5 w-3.5`})}),(0,S.jsxs)(`button`,{type:`button`,onClick:()=>k(!0),className:`flex items-center gap-1 rounded-md bg-primary px-2 py-1.5 text-xs text-primary-foreground`,title:`Add a note`,children:[(0,S.jsx)(i,{className:`h-3.5 w-3.5`}),`Note`]})]}),(0,S.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[O&&(0,S.jsx)(w,{target:t,onCreated:()=>{k(!1),p()},onCancel:()=>k(!1)},JSON.stringify(t)),r&&!n.length&&(0,S.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,S.jsx)(s,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),l&&(0,S.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:l}),!r&&!l&&!L.length&&!O&&(0,S.jsx)(`p`,{className:`px-4 py-10 text-center text-sm text-muted-foreground`,children:`No notes here yet - add the first one.`}),L.map(e=>(0,S.jsx)(C,{doc:e,updateWorkspace:f?.workspaceName??null,registerEl:P,registerBody:F,highlighted:z?.docId===e.id,onLinkTo:()=>j(e.id),onDelete:()=>I(e)},e.id))]}),A!==null&&(0,S.jsx)(_,{documentId:A,workspaceName:f?.workspaceName,onClose:()=>j(null)})]}):(0,S.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:d(t)})}export{T as NotesApplet};
@@ -0,0 +1 @@
1
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{_ as r,g as i,h as a}from"./chunk-62JRHF6Z-vspAGgtK.js";import{t as o}from"./socket-CtH3EU9m.js";import{n as s}from"./use-toast-BlLDqSUO.js";import{o as c,s as ee}from"./LinkToCard-BQ1yoFDr.js";import{G as l,Sn as u,V as te,bn as ne,zt as re}from"./workspace-BJELPCNs.js";import{r as ie}from"./document-list-CQ1_7Sja.js";import{n as ae}from"./use-toolbox-Ck_cLGgf.js";import{E as oe,_ as se,a as ce,b as le,i as ue,l as de,o as fe}from"./context-DZ1Hn7tt.js";import{i as pe}from"./color-DFEH4BfK.js";import{t as me}from"./geo-CZfs0E-x.js";import{a as he,i as ge,o as _e}from"./workspace-BydSRtST.js";import{i as ve}from"./use-menu-DIP1zh7I.js";import{a as ye,c as be,i as xe,l as Se,n as Ce,o as we,r as Te,s as Ee,t as De,u as Oe}from"./tree-folders-cmsIS19Z.js";import{t as ke}from"./use-workspace-identity-B8gOMGj4.js";var d=e(n(),1),f=t();function Ae(e,t){if(!e||!t)return`/`;let n=`${t}://`;if(!e.startsWith(n))return`/`;let r=e.slice(n.length).replace(/^\/+/,``).replace(/\/+$/,``);return r?`/${r}`:`/`}function p(){let{contextId:e}=r(),t=a(),n=i(),p=new URLSearchParams(t.search).get(`ownerId`)||void 0,m=(0,d.useMemo)(()=>{let e=new URLSearchParams(t.search),n=e.getAll(`q`).map(e=>e.trim()).filter(Boolean),r=(e.get(`search`)||``).trim();return n.length?n:r?[r]:[]},[t.search]),{showToast:h,showProgress:je}=s(),{state:g,saveFilters:Me,setSort:Ne,setAccentColor:_,setMapDocuments:v}=ae(),{openM1Drawer:Pe,openM2Drawer:Fe,goBack:Ie}=ve(),y=g.filters.features.allOf,Le=g.filters.features.anyOf,Re=g.filters.features.noneOf,ze=[...ge(g.filters.timeline),...he(g.filters.geo),..._e(g.filters.lens,g.filters.geo.includeUnlocated)],b=JSON.stringify({a:y,b:Le,c:Re,d:ze,ids:g.filters.lens.ids,sort:g.filters.sort,geoSelection:g.geoSelection,includeUnlocated:g.filters.geo.includeUnlocated}),x=(0,d.useMemo)(()=>JSON.parse(b),[b]),[S,C]=(0,d.useState)(null),[Be,Ve]=(0,d.useState)(!0),[He,Ue]=(0,d.useState)(null),[w,T]=(0,d.useState)([]),[We,Ge]=(0,d.useState)(!1),[Ke,E]=(0,d.useState)(0),[qe,Je]=(0,d.useState)([]),[D,O]=(0,d.useState)(1),[k,Ye]=(0,d.useState)(50),[A,j]=(0,d.useState)(m),[M,N]=(0,d.useState)(!1),[P,F]=(0,d.useState)(null),[Xe,Ze]=(0,d.useState)(!1),I=(0,d.useRef)(!1),L=P?.id===S?.id&&P?.url===S?.url?P?.path:null,R=new URLSearchParams(t.search).get(`layer`),z=!!p,Qe=ke(z?void 0:S?.workspaceName||S?.workspaceId),B=S?Ae(S.url,S.workspaceName):`/`,$e=R?`context-layer`:`context`,V=!g.liveEnabled&&typeof S?.metadata?.toolboxSearchQuery==`string`?S.metadata.toolboxSearchQuery:``,H=z?null:S?.workspaceName??null,[et,tt]=(0,d.useState)(null);(0,d.useEffect)(()=>{if(!H)return;let e=!1;return l(H,u).then(t=>{e||tt({key:H,tree:t})}).catch(()=>{e||tt({key:H,tree:null})}),()=>{e=!0}},[H]);let U=H&&et?.key===H?et.tree:null,W=!R&&!z&&U?B===`/`?U:te(U,B):null,nt=!R&&!z&&A.length===0,rt=(0,d.useMemo)(()=>nt?De(U,B):[],[nt,U,B]),G=`${S?.workspaceName??``}\0${B}`,[K,it]=(0,d.useState)(null),q=K?.key===G?K.views:Ee(W?.metadata),J=K?.key===G?K.activeId:q[0]?.id??ye.id,Y=q.find(e=>e.id===J)??q[0]??ye,X=we(Y);Oe(Se({workspace:S?.workspaceName||S?.workspaceId||null,treeNameOrId:g.activeTreeName,path:B,contextId:e??null,scope:`context`},{...g.filters,features:{...g.filters.features,allOf:X?[...y,X]:y}},g.geoSelection,A));let at=e=>{O(1),it({key:G,views:q,activeId:e})},ot=(e,t)=>{t&&t!==J&&O(1),it({key:G,views:e,activeId:t??J}),S?.workspaceName&&ne(S.workspaceName,B,{metadata:{...W?.metadata??{},views:e}},u).catch(()=>{h({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},Z=(0,d.useRef)(null);(0,d.useEffect)(()=>()=>Z.current?.abort(),[]);let Q=(0,d.useCallback)(async()=>{if(!e)return;Z.current?.abort();let t=new AbortController;Z.current=t,Ge(!0);try{let n=await fe(e,X?[...x.a,X]:x.a,x.d,{...x.sort,geoSelection:x.geoSelection,includeUnlocated:x.includeUnlocated,ids:x.ids,signal:t.signal,limit:k,page:D,queries:A.length?A:void 0,anyOf:x.b,noneOf:x.c,applyContextSpec:!1},p);if(t.signal.aborted)return;T(n),E(n.totalCount||n.count||n.length)}catch(e){if(t.signal.aborted)return;h({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch documents`,variant:`destructive`}),T([]),E(0)}finally{t.signal.aborted||Ge(!1)}},[e,D,k,p,A,x,h,X]),st=(0,d.useCallback)(async()=>{if(e){Ve(!0);try{let t=z?await ce(e,p):await ce(e);if(!t)throw Error(`No context data received.`);let n=t.workspace,r=t.workspaceId||(typeof n==`string`?n:n?.id)||``,i=t.workspaceName||(typeof n==`string`?n:n?.name)||``;C({id:t.id,userId:t.userId,url:t.url,baseUrl:t.baseUrl||null,path:t.path||null,pathArray:t.pathArray||[],workspaceId:r,workspaceName:i,acl:t.acl||{},createdAt:t.createdAt,updatedAt:t.updatedAt,locked:t.locked||!1,serverContextArray:t.serverContextArray||[],clientContextArray:t.clientContextArray||[],contextBitmapArray:t.contextBitmapArray||[],featureBitmapArray:t.featureBitmapArray||[],filterArray:t.filterArray||[],pendingUrl:t.pendingUrl||null,description:t.description||null,metadata:t.metadata||{},name:t.name??null,color:t.color??null,icon:t.icon??null}),Ue(null)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch context ${e}`;Ue(n),C(null),h({title:`Error`,description:n,variant:`destructive`})}Ve(!1)}},[e,p,z,h]);(0,d.useEffect)(()=>{st()},[st]);let ct=pe(S?.color)||null;(0,d.useEffect)(()=>(_(ct),()=>_(null)),[ct,_]);let lt=g.geoSelection,ut=S?.workspaceName||S?.workspaceId||null;(0,d.useEffect)(()=>{v(w,ut)},[w,ut,v]),(0,d.useEffect)(()=>()=>v([]),[v]);let dt=(0,d.useMemo)(()=>lt?w.filter(e=>me(e,lt,g.filters.geo.includeUnlocated)):w,[w,lt,g.filters.geo.includeUnlocated]),ft=S?.id,pt=S?.url;(0,d.useEffect)(()=>{ft&&Q()},[ft,pt,Q]),(0,d.useEffect)(()=>{let e=()=>Q();return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[Q]);let[mt,ht]=(0,d.useState)(b);mt!==b&&(ht(b),O(1));let[gt,_t]=(0,d.useState)(e);gt!==e&&(_t(e),O(1),N(!1));let[vt,yt]=(0,d.useState)(m);vt!==m&&(yt(m),j(m),O(1));let[bt,xt]=(0,d.useState)({urlSearchQueries:m,ignoreSavedSearch:M,savedContextSearchQuery:V});(bt.urlSearchQueries!==m||bt.ignoreSavedSearch!==M||bt.savedContextSearchQuery!==V)&&(xt({urlSearchQueries:m,ignoreSavedSearch:M,savedContextSearchQuery:V}),!new URLSearchParams(t.search).has(`q`)&&!m.length&&!M&&(j(V?[V]:[]),O(1)));let $=(0,d.useCallback)(e=>{let r=new URLSearchParams(t.search);r.delete(`q`),r.delete(`search`);for(let t of e)r.append(`q`,t);let i=r.toString();n(`${t.pathname}${i?`?${i}`:``}${t.hash}`)},[t.pathname,t.search,t.hash,n]),St=(0,d.useCallback)(e=>{let t=e.trim();if(!t)return;N(!1);let n=A.includes(t)?A:[...A,t];j(n),$(n)},[A,$]),Ct=(0,d.useCallback)(e=>{let t=e<0?[]:A.filter((t,n)=>n!==e);t.length===0&&N(!0),j(t),$(t)},[A,$]),wt=(A[0]||``).trim(),Tt=!!g.activeContextType&&(g.isDirty||wt!==(g.savedSearchQuery||V||``));(0,d.useEffect)(()=>{if(!e)return;let t=`context:${p?`${p}/`:``}${e}`,n=()=>o.emit(`subscribe`,{channel:t}),r=()=>o.emit(`unsubscribe`,{channel:t}),i=o.on(`connect`,n);n();let a=new Map,s=(t,n)=>{let r=Date.now(),i=`${t}:${n?.id||n?.contextId||e}`;return(a.get(i)||0)+1e3>r?!1:(a.set(i,r),!0)},c=t=>{let n=t,r=n?.context||n;(r?.id===e||r?.contextId===e)&&s(`ctx:updated`,r)&&(C(e=>e?{...e,...r}:null),r.url&&Q())},ee=t=>{let n=t,r=n?.id||n?.contextId||n?.context?.id,i=n?.url||n?.context?.url;r===e&&typeof i==`string`&&s(`ctx:url`,n)&&(C(e=>e?{...e,url:i}:null),Q())},l=t=>{let n=t;(n?.contextId||n?.id||n?.context?.id)===e&&s(`doc:changed`,n)&&Q()},u=[[`context.updated`,c],[`context:updated`,c],[`context.url.set`,ee],[`context:url:set`,ee],[`document.inserted`,l],[`document.updated`,l],[`document.removed`,l],[`document.removed.batch`,l],[`document.linked`,l],[`document.unlinked`,l],[`document.linked.batch`,l],[`document.unlinked.batch`,l],[`document.deleted`,l],[`document.deleted.batch`,l]];return u.forEach(([e,t])=>o.on(e,t)),()=>{i(),r(),u.forEach(([e,t])=>o.off(e,t))}},[e,p,Q]);let Et=async e=>{if(S)try{await le(S.id,[e],p,B),T(t=>t.filter(t=>t.id!==e)),E(e=>Math.max(0,e-1)),h({title:`Success`,description:`Document removed from context.`})}catch(e){h({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},Dt=async e=>{if(S)try{await ue(S.id,[e],p,B),T(t=>t.filter(t=>t.id!==e)),E(e=>Math.max(0,e-1)),h({title:`Success`,description:`Document deleted.`})}catch(e){h({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},Ot=async e=>{if(S)try{await le(S.id,e,p,B),T(t=>t.filter(t=>!e.includes(t.id))),E(t=>Math.max(0,t-e.length)),h({title:`Success`,description:`${e.length} document(s) removed.`})}catch(e){h({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},kt=async e=>{if(S)try{await ue(S.id,e,p,B),T(t=>t.filter(t=>!e.includes(t.id))),E(t=>Math.max(0,t-e.length)),h({title:`Success`,description:`${e.length} document(s) deleted.`})}catch(e){h({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},At=e=>{Je(e),h({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},jt=async(e,t,n={})=>{if(!S)return!1;let r=je({title:`Pasting…`,description:`${t.length} document(s) → "${e}"`});try{let i=n.targetTreeName&&!z?await re(S.workspaceName||S.workspaceId,e,t,n.targetTreeName,n.targetTreeType):await se(S.id,e,t,p);return r.done(i?{title:`Success`,description:`${t.length} document(s) pasted to "${e}"`}:void 0),i&&(Je([]),await Q()),i}catch(e){return r.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},Mt=async(e,t)=>{if(!S)return!1;try{let n=await de(S.workspaceId,t,e);return n&&(ie(S.workspaceName||S.workspaceId,`context`,t),h({title:`Success`,description:`Imported ${e.length} document(s) to "${t}"`})),n}catch(e){return h({title:`Error`,description:e instanceof Error?e.message:`Failed to import documents`,variant:`destructive`}),!1}},Nt=async()=>{if(!S||!L||z||I.current)return;let e={id:S.id,url:S.url,path:L};I.current=!0,Ze(!0);try{let t=await oe(e.id,`${S.workspaceName}://${e.path.replace(/^\/+/,``)}`);C(n=>n?.id===e.id&&n.url===e.url?{...n,url:t.url,path:e.path}:n),F(null),O(1),window.dispatchEvent(new CustomEvent(`contexts:refresh`,{detail:{contextId:e.id}})),h({title:`Saved`,description:`Context path updated`})}catch(e){h({title:`Error`,description:e instanceof Error?e.message:`Could not update context path`,variant:`destructive`})}finally{I.current=!1,Ze(!1)}};if(Be)return(0,f.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,f.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,f.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading context...`})]})});if(He&&!S)return(0,f.jsxs)(`div`,{className:`flex items-center justify-center h-full text-destructive`,children:[`Error: `,He]});if(!S)return(0,f.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Context not found.`});let Pt=pe(S.color);return(0,f.jsx)(`div`,{className:`flex flex-col h-full min-h-0`,children:(0,f.jsx)(be,{onBack:Ie,accentColor:Pt,navigationTabs:W?(0,f.jsx)(xe,{views:q,activeId:J,onSelect:at,onSave:ot,accentColor:Pt}):void 0,workspaceLabel:Qe?.label||S.workspaceName||S.workspaceId,workspaceIcon:Qe?.icon,treeName:u,urlType:$e,urlDisplay:S.url,contextPath:B,workspaceId:S.workspaceName||S.workspaceId,documentSchema:X,linkTree:U,documents:dt,isLoading:We,totalCount:Ke,currentPage:D,pageSize:k,onPageChange:O,onPageSizeChange:e=>{Ye(e),O(1)},onRemoveDocument:B===`/`?void 0:Et,onDeleteDocument:Dt,onRemoveDocuments:B===`/`?void 0:Ot,onDeleteDocuments:kt,onCopyDocuments:At,onPasteDocuments:jt,onImportDocuments:z?void 0:Mt,pastedDocumentIds:qe,backendSearchQueries:A,onBackendSearch:St,serverSort:g.filters.sort,onServerSortChange:Ne,onRemoveBackendQuery:Ct,canSaveChanges:Tt,isSavingChanges:g.isSaving,onSaveChanges:Me,onBrowseTree:!z&&e?()=>Fe(`contexts`,`detail`,e):void 0,onBrowseWorkspaces:()=>Pe(`workspaces`),folders:rt,onOpenFolder:e=>{I.current||F({id:S.id,url:S.url,path:e})},onNavigatePath:z?void 0:e=>{I.current||F({id:S.id,url:S.url,path:e})},contentBanner:L?(0,f.jsxs)(`div`,{className:`border-b bg-warning/10 px-4 py-2`,role:`status`,children:[(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Set this context to the selected path? Contents stay at the current path until you apply it.`}),(0,f.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,f.jsx)(ee,{items:c(L,S.workspaceName),label:`Selected context path`}),(0,f.jsx)(`button`,{type:`button`,disabled:Xe,onClick:()=>void Nt(),className:`shrink-0 rounded border px-3 py-1 text-sm hover:bg-accent disabled:opacity-50`,children:Xe?`Setting…`:`Set`}),(0,f.jsx)(`button`,{type:`button`,disabled:Xe,onClick:()=>F(null),className:`shrink-0 rounded px-2 py-1 text-sm hover:bg-accent disabled:opacity-50`,children:`Cancel`})]})]}):void 0,children:Y.kind===`columns`?(0,f.jsx)(Te,{documents:dt,workspaceId:S.workspaceName||S.workspaceId,columns:Y.columns??[],onColumnsChange:e=>ot(q.map(t=>t.id===Y.id?{...t,columns:e}:t))}):Y.kind===`app`&&Y.app&&Y.app!==`notes`?(0,f.jsx)(Ce,{app:Y.app,contextId:e,workspaceId:S.workspaceName||S.workspaceId,treeName:u,path:B}):null})})}export{p as default};
@@ -0,0 +1 @@
1
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{_ as r,g as i,h as a}from"./chunk-62JRHF6Z-vspAGgtK.js";import{L as o,Ur as s,Vr as c,pn as l}from"./ui-CDoK3F3U.js";import{t as u}from"./utils-2pl1SbIp.js";import{t as d}from"./button-SeUZ_Pvi.js";import{c as f,t as p}from"./api-CA6WiiYM.js";import{t as m}from"./socket-CtH3EU9m.js";import{n as h}from"./use-toast-BlLDqSUO.js";import{Cn as g,D as ee,G as te,Jt as _,K as v,Mt as ne,Vt as y,X as re,_ as ie,_t as b,a as ae,bn as oe,ht as se,it as ce,on as le,qt as ue,rt as de,u as fe,ut as pe,w as me,x,y as he,yt as ge,zt as _e}from"./workspace-BJELPCNs.js";import{n as ve,r as ye}from"./use-canvas-pins-DkWN9oEd.js";import{u as be}from"./ObjectPropertiesCard-BTTwYnN9.js";import{h as xe,i as S,r as Se}from"./document-list-CQ1_7Sja.js";import{n as Ce}from"./use-toolbox-Ck_cLGgf.js";import{i as we}from"./color-DFEH4BfK.js";import{t as Te}from"./geo-CZfs0E-x.js";import{c as Ee}from"./backend-sync-progress-tUU2XWtW.js";import{a as De,i as Oe,n as ke,o as Ae}from"./workspace-BydSRtST.js";import{n as je,r as Me,t as Ne}from"./url-params-n7kU_WZ-.js";import{i as Pe}from"./use-menu-DIP1zh7I.js";import{n as Fe}from"./last-path-BbXWC3b3.js";import{t as Ie}from"./workspace-area-menu-BFw2yUHk.js";import{t as Le}from"./workspace-content-gate-NLuRPvbm.js";import{t as Re}from"./form-panel-3p-ncEVK.js";import{a as ze,c as Be,i as Ve,l as He,n as Ue,o as We,r as Ge,s as Ke,t as qe,u as Je}from"./tree-folders-cmsIS19Z.js";import{i as Ye,o as Xe,r as Ze}from"./query-debug-CQ0I3cXX.js";var C=`session.open`,Qe=`session.set`,$e=`session.ids`,et=`session.materialize`,tt=`session.close`,w=`session.delta`,T=e(n(),1),E=t();function nt({workspaceId:e,workspaceName:t}){let[n,r]=(0,T.useState)([]),[i,a]=(0,T.useState)(new Set),s=t=>`${e}:${t.address}:${t.resyncStartedAt||``}`;(0,T.useEffect)(()=>{let t=!1,n=!1,i=!1,a=0,o=new Map,s=new Map,c=(e,t)=>{let n=e.filter(e=>e.address!==t.backend);if(!t.resyncing)return n;let r=e.find(e=>e.address===t.backend)||s.get(t.backend);return[...n,{address:t.backend,config:r?.config,resyncStartedAt:r?.resyncStartedAt||new Date().toISOString(),progress:t.progress??r?.progress}]},l=async()=>{if(n){i=!0;return}n=!0;let u=a;try{let n=await ge(e);if(!t){s=new Map(n.map(e=>[e.address,e]));let e=n.filter(e=>e.resyncing);for(let t of o.values())t.version>u&&(e=c(e,t.event));r(e)}}catch{}finally{n=!1,i&&!t&&(i=!1,l())}},u=t=>{t.workspaceId!==e||!t.backend||typeof t.resyncing!=`boolean`||(o.set(t.backend,{version:++a,event:t}),r(e=>c(e,t)))},d=t=>{t.workspaceId===e&&l()};l();let f=m.on(`connect`,l);return m.on(`backend.resync.changed`,u),m.on(`backend.changed`,d),window.addEventListener(`focus`,l),()=>{t=!0,f?.(),m.off(`backend.resync.changed`,u),m.off(`backend.changed`,d),window.removeEventListener(`focus`,l)}},[e]);let c=n.filter(e=>!i.has(s(e)));return c.length?(0,E.jsxs)(`aside`,{"aria-label":`Storage scans for ${t}`,className:`absolute bottom-5 right-5 z-50 w-72 max-w-[calc(100vw-2.5rem)] rounded-lg border bg-popover/95 p-3 text-popover-foreground shadow-lg backdrop-blur`,children:[(0,E.jsxs)(`div`,{role:`status`,className:`mb-2 flex items-center gap-2 text-sm font-medium`,children:[(0,E.jsx)(l,{"aria-hidden":`true`,className:`h-4 w-4 animate-spin`}),(0,E.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,E.jsx)(`span`,{className:`block`,children:`Scanning storage`}),(0,E.jsx)(`span`,{className:`block truncate text-xs font-normal text-muted-foreground`,title:t,children:t})]}),(0,E.jsx)(`button`,{type:`button`,"aria-label":`Hide scan progress for ${t}`,title:`Hide progress; scanning continues`,className:`rounded p-1 hover:bg-muted focus-visible:outline focus-visible:outline-2`,onClick:()=>a(e=>new Set([...e,...c.map(s)])),children:(0,E.jsx)(o,{"aria-hidden":`true`,className:`h-4 w-4`})})]}),(0,E.jsx)(`div`,{className:`max-h-48 space-y-3 overflow-y-auto`,children:c.map(e=>{let{scanned:t=0,total:n=null}=e.progress||{},r=n&&n>0?Math.min(100,Math.round(t/n*100)):null,i=typeof e.config?.label==`string`?e.config.label:e.address;return(0,E.jsxs)(`div`,{children:[(0,E.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs`,children:[(0,E.jsx)(`span`,{className:`truncate`,children:i}),(0,E.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:n===null?`${t} files`:`${t} / ${n}`})]}),(0,E.jsx)(`div`,{role:`progressbar`,"aria-label":`Scanning ${i}`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":r??void 0,className:`mt-1.5 h-1 overflow-hidden rounded-full bg-muted`,children:(0,E.jsx)(`div`,{className:`h-full rounded-full bg-primary ${r===null?`animate-pulse`:`transition-all`}`,style:{width:r===null?`35%`:`${r}%`}})})]},e.address)})})]}):null}var rt=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:null;function D(e){return`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`}function it(e,t,n){if(e==null)return[];if(Array.isArray(e))return e.flatMap(e=>it(e,t,n));if(typeof e==`string`)return[{tree:null,kind:t,path:D(e)}];let r=rt(e);if(!r)return[];let i=r.tree??r.treeId,a=typeof i==`string`?n.get(i)??null:null;return[].concat(r.paths??r.path??`/`).filter(e=>typeof e==`string`).map(e=>({tree:a,kind:t,path:D(e)}))}function O(e){let t=[],n=e=>{let n=Number(e);Number.isSafeInteger(n)&&n>0&&t.push(n)};return Array.isArray(e.ids)&&e.ids.forEach(n),Array.isArray(e.documentIds)&&e.documentIds.forEach(n),e.id!=null&&n(e.id),e.documentId!=null&&n(e.documentId),t}function at(e){let t=new Map;for(let n of e)t.set(n.id,n.name),t.set(n.name,n.name);return t}function ot(e,t,n=new Map){let r=rt(t);if(!r)return{targets:[],ids:[],unknown:!0};if(e.startsWith(`tree.`)){let e=typeof r.treeName==`string`?r.treeName:null,t=r.treeType===`directory`||r.treeType===`context`?r.treeType:null,n=r.contextSpec??r.path;return typeof n==`string`?{targets:[{tree:e,kind:t,path:D(n)}],ids:O(r),unknown:!1}:{targets:[],ids:[],unknown:!0}}let i=[...it(r.context,`context`,n),...it(r.directory,`directory`,n)],a=rt(r.changed);a&&i.push(...it(a.context,`context`,n),...it(a.directory,`directory`,n));let o=O(r);if(i.length)return{targets:i,ids:o,unknown:!1};let s=r.reason===`content`||r.reason===`relations`;return e.startsWith(`document.updated`)&&s&&o.length?{targets:[],ids:o,unknown:!1}:{targets:[],ids:o,unknown:!0}}function k(e,t){return e===t||e===`/`||t===`/`||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}function st(e,t){if(e.kind&&e.kind!==t.kind||e.tree&&e.tree!==t.tree)return!1;if(t.kind===`context`){let n=e=>D(e).split(`/`).filter(Boolean).map(e=>e.normalize(`NFKC`).trim().replace(/\s+/g,` `).replace(/[^\p{L}\p{N}\p{M} .+_@-]/gu,`_`).replace(/_+/g,`_`).toLowerCase()||`_`),r=new Set(n(e.path)),i=n(t.path);return r.size===0||i.length===0||i.some(e=>r.has(e))}return k(e.path,t.path)}function ct(e){return ot(`tree.refresh`,{treeName:e?.treeName,path:e?.path||`/`})}function lt(e,t,n){if(e.unknown||e.targets.length&&(t.wholeWorkspace||e.targets.some(e=>st(e,t))))return!0;if(e.ids.length&&n){let t=n instanceof Set?n:new Set(n);if(e.ids.some(e=>t.has(e)))return!0}return!1}function ut(e,t,n={}){return m.request(C,{workspace:e,specs:t,opts:n})}function dt(e,t,n){return m.request(Qe,{sessionId:e,label:t,spec:n})}function ft(e){return m.request($e,{sessionId:e})}function A(e,t={}){return m.request(et,{sessionId:e,...t})}function pt(e){return m.request(tt,{sessionId:e})}function mt(e){return m.on(w,e)}var ht=100;function gt({workspaceRef:e,specs:t,opts:n,enabled:r=!0}){let[i,a]=(0,T.useState)([]),[o,s]=(0,T.useState)(0),[c,l]=(0,T.useState)(null),[u,d]=(0,T.useState)(null),f=(0,T.useRef)([]),p=(0,T.useRef)(new Map),h=(0,T.useRef)(null),g=(0,T.useRef)(null),ee=(0,T.useRef)(null),te=(0,T.useRef)({}),_=(0,T.useRef)(null),v=(0,T.useMemo)(()=>JSON.stringify(t),[t]),ne=(0,T.useMemo)(()=>JSON.stringify(n??{}),[n]),y=(0,T.useCallback)(()=>{let e=p.current;a(f.current.map(t=>e.get(t)).filter(Boolean))},[]),re=(0,T.useCallback)(async e=>{let t=g.current;if(!t||e.length===0)return[];let n=[];for(let r=0;r<e.length;r+=ht){let i=e.slice(r,r+ht),a=await de(t,`/`,[],{ids:i,scope:`workspace`,limit:i.length});n.push(...a.payload||[])}return n},[]),ie=(0,T.useCallback)(async(e,t,n)=>{if(t.length>0){let e=new Set(t);f.current=f.current.filter(t=>!e.has(t));for(let t of e)p.current.delete(t)}let r=e.filter(e=>!p.current.has(e)),i=new Set(f.current);for(let t of e)i.has(t)||(f.current.push(t),i.add(t));if(n!==null&&s(n),y(),r.length===0)return;let a=await re(r);for(let e of a)p.current.set(e.id,e);let o=new Set(a.map(e=>e.id)),c=r.filter(e=>!o.has(e));if(c.length>0){let e=new Set(c);f.current=f.current.filter(t=>!e.has(t))}y()},[re,y]),b=(0,T.useCallback)(async(e,t)=>{let n=e??[],r=new Set(n);f.current=f.current.filter(e=>r.has(e));for(let e of p.current.keys())r.has(e)||p.current.delete(e);let i=new Set(f.current),a=n.filter(e=>!i.has(e));await ie(a,[],t)},[ie]);(0,T.useEffect)(()=>{if(g.current=e??null,!r||!e)return;let t=!1,n=null,i=async()=>{try{let r=await ut(e,JSON.parse(v),JSON.parse(ne));if(t){pt(r.sessionId).catch(()=>{});return}n=r.sessionId,h.current=r.sessionId,l(r.sessionId),d(null),f.current=[],p.current=new Map,await b(r.ids,r.count)}catch(e){if(t)return;d(e instanceof Error?e.message:`Failed to open query session`),l(null),h.current=null}};i();let o=m.on(`connect`,()=>{i()});return()=>{t=!0,o?.();let e=n??h.current;e&&pt(e).catch(()=>{}),h.current=null,f.current=[],p.current=new Map,l(null),a([]),s(0)}},[e,v,ne,r]),(0,T.useEffect)(()=>{if(!c)return;let e=mt(e=>{if(e.sessionId===c){if(ee.current!==null){_.current?.(ee.current,te.current);return}e.ids===void 0?ie(e.added??[],e.removed??[],e.count):b(e.ids,e.count)}});return()=>{e?.()}},[c,ie,b]);let ae=(0,T.useCallback)(async()=>{let e=h.current;if(e)try{let t=await ft(e);await b(t.ids,t.count)}catch{}},[b]),oe=(0,T.useCallback)(async(e,t)=>{let n=h.current;if(!n)throw Error(`No open query session`);let r=await dt(n,e,t);if(ee.current!==null){await _.current?.(ee.current,te.current);return}await b(r.ids,r.count)},[b]),se=(0,T.useCallback)(async(e,t={})=>{let n=h.current;if(!n)throw Error(`No open query session`);if(ee.current=e,te.current=t,e===null){await ae();return}let r=await A(n,{match:e,...t});for(let e of r.documents)p.current.set(e.id,e);f.current=r.ids,s(r.totalCount),y()},[y,ae]);(0,T.useEffect)(()=>{_.current=se},[se]);let ce=(0,T.useCallback)(async(e,t,n={})=>{let r=h.current;if(!r)throw Error(`No open query session`);let i=await A(r,{match:t,limit:n.limit??100,...n.mode?{mode:n.mode}:{}});for(let e of i.documents)p.current.set(e.id,e);let a=await dt(r,e,{ids:i.ids});return await b(a.ids,a.count),i.ids},[b]);return{documents:i,count:o,ready:c!==null,error:u,setCue:oe,resync:ae,rank:se,rankAndPin:ce}}function _t({data:e,className:t}){let[n,r]=(0,T.useState)(!0),{rows:i,gapIndex:a,span:o}=(0,T.useMemo)(()=>{let t=[...e.distances].sort((e,t)=>e.distance-t.distance),n=[];for(let e=1;e<t.length;e++)n.push(t[e].distance-t[e-1].distance);let r=n.length?[...n].sort((e,t)=>e-t)[Math.floor(n.length/2)]:0,i=-1,a=0;for(let e=0;e<n.length;e++)n[e]>a&&(a=n[e],i=e+1);let o=i>0&&a>=Math.max(r*4,1e-6),s=t[0]?.distance??0,c=t[t.length-1]?.distance??0;return{rows:t,gapIndex:o?i:-1,span:{first:s,last:c,biggest:a,median:r}}},[e.distances]);if(i.length===0)return(0,E.jsxs)(`div`,{className:u(`rounded-md border border-dashed border-border px-3 py-2 text-xs text-muted-foreground`,t),children:[`Query debug: no image distances for “`,e.query,`”. The dense side returned nothing: either no photos are embedded in this scope, or the image space is not ready.`]});let l=a>0?i[a].distance:null;return(0,E.jsxs)(`div`,{className:u(`rounded-md border border-border bg-muted/30 text-xs`,t),children:[(0,E.jsxs)(`button`,{type:`button`,onClick:()=>r(e=>!e),className:`flex w-full items-center gap-1.5 px-3 py-2 text-left font-medium`,children:[n?(0,E.jsx)(s,{className:`h-3.5 w-3.5`}):(0,E.jsx)(c,{className:`h-3.5 w-3.5`}),`Query debug`,(0,E.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`: image distances for “`,e.query,`” (`,i.length,` nearest, unfloored)`]})]}),n&&(0,E.jsxs)(`div`,{className:`space-y-2 border-t border-border px-3 py-2`,children:[(0,E.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Best-first cosine distance (0 = identical). Scroll to where the photos stop being relevant and set the image relevance floor just above that value in Settings → Database → Search tuning.`,l===null?(0,E.jsxs)(E.Fragment,{children:[` `,(0,E.jsx)(`span`,{className:`text-amber-600 dark:text-amber-500`,children:`No boundary in this window`}),`; the distances step evenly (typical Δ`,o.median.toFixed(4),`), so there is nothing here to set a floor from. Relevance probably ends further down the list than this window reaches, or the model is not separating this query at all.`]}):(0,E.jsxs)(E.Fragment,{children:[` A jump at `,(0,E.jsx)(`span`,{className:`font-mono`,children:l.toFixed(4)}),` (Δ`,o.biggest.toFixed(4),`, vs typical Δ`,o.median.toFixed(4),`) stands out (a likely boundary).`]})]}),(0,E.jsx)(`div`,{className:`max-h-56 overflow-y-auto`,children:(0,E.jsx)(`table`,{className:`w-full font-mono text-[11px]`,children:(0,E.jsx)(`tbody`,{children:i.map((e,t)=>(0,E.jsxs)(`tr`,{className:u(`border-b border-border/40 last:border-0`,t===a&&`border-t-2 border-t-amber-500/70`),children:[(0,E.jsx)(`td`,{className:`py-0.5 pr-3 text-muted-foreground`,children:t+1}),(0,E.jsxs)(`td`,{className:`py-0.5 pr-3`,children:[`#`,e.id]}),(0,E.jsx)(`td`,{className:`py-0.5 tabular-nums`,children:e.distance.toFixed(4)}),t===a&&(0,E.jsx)(`td`,{className:`py-0.5 pl-2 font-sans text-[10px] text-amber-600 dark:text-amber-500`,children:`← biggest gap`})]},e.id))})})}),(0,E.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Range `,o.first.toFixed(4),` – `,o.last.toFixed(4),` (spread `,(o.last-o.first).toFixed(4),`) over `,i.length,` rows. Absolute values shift with the model and are not comparable across models. After a re-embed every floor has to be picked again. A spread this narrow relative to the range means ranking is doing the work, not distance.`]})]})]})}var vt=new Map;function yt(e,t,n){return`${e}\0${t}\0${n}`}function bt(e,t,n,r,i,a,o=``,s=``,c=`path`){return`${yt(e,t,n)}\0${r}\0${i}\0${a}\0${o}\0${s}\0${c}`}function j(e,t,n){let r=yt(e,t,n);for(let e of vt.keys())e.startsWith(r)&&vt.delete(e)}function xt(e,t){let n=`${e}\0`;for(let[e,r]of vt){if(!e.startsWith(n))continue;let[,i,a,,,,,,o=`path`]=e.split(`\0`);lt(t,{tree:i,kind:g(i),path:a,wholeWorkspace:o.startsWith(`workspace`)},r.documents.map(e=>Number(e.id)))&&vt.delete(e)}}function St(e,t){xt(t?.workspaceName??e,ct(t))}function Ct(){let{workspaceName:e}=r();return e?(0,E.jsx)(Le,{workspaceName:e,children:(0,E.jsx)(M,{})}):null}function M(){let{workspaceName:e,treeName:t}=r(),n=a(),o=i(),{showToast:s,showProgress:c}=h(),l=new URLSearchParams(n.search),Le=(()=>{let e=l.getAll(`q`).map(e=>e.trim()).filter(Boolean);if(e.length>0)return e;let t=(l.get(`search`)||``).trim();return t?[t]:[]})(),[C,Qe]=(0,T.useState)(null),[$e,et]=(0,T.useState)(!0),[tt,w]=(0,T.useState)([]),[rt,D]=(0,T.useState)(!1),[it,O]=(0,T.useState)(0),k=Ze(),[st,ut]=(0,T.useState)(null),[dt,ft]=(0,T.useState)(k);dt!==k&&(ft(k),k||ut(null));let[A,pt]=(0,T.useState)(`path`),[mt,ht]=(0,T.useState)(!1),[yt,Ct]=(0,T.useState)(null),[M,wt]=(0,T.useState)(null),[Et,Dt]=(0,T.useState)(``),[Ot,kt]=(0,T.useState)(!1),[At,jt]=(0,T.useState)(!1),[Mt,Nt]=(0,T.useState)(!1),[N,Pt]=(0,T.useState)(null),[P,F]=(0,T.useState)(1),[I,Ft]=(0,T.useState)(50),[L,It]=(0,T.useState)(Le),[Lt,Rt]=(0,T.useState)(null),{state:R,saveFilters:zt,setSort:Bt,setAccentColor:Vt,setMapDocuments:Ht}=Ce(),Ut=R.filters.features.allOf,z=R.filters.features.anyOf,Wt=R.filters.features.noneOf,Gt=Oe(R.filters.timeline),Kt=De(R.filters.geo),qt=Ae(R.filters.lens,R.filters.geo.includeUnlocated),B=R.filters.lens.ids,Jt=[...Gt,...Kt,...qt],Yt=R.filters.sort??ke,Xt=JSON.stringify({a:Ut,b:z,c:Wt,d:Jt,i:B,s:Yt}),Zt=JSON.stringify({a:Ut,b:z,c:Wt,d:Jt,s:Yt}),V=je(n.pathname).path,H=t??`context`,U=H===`backends`,[Qt,$t]=(0,T.useState)([]);(0,T.useEffect)(()=>{!U||!e||ge(e).then($t).catch(()=>$t([]))},[U,e]);let en=U?ae(V,Qt):null,[tn,nn]=(0,T.useState)(!1),rn=`${H}\0${V}`,[an,on]=(0,T.useState)(rn);an!==rn&&(on(rn),nn(!1));let W=l.get(`layer`)===`1`,G=l.get(`layerId`)||null,[K,sn]=(0,T.useState)(null),[q,cn]=(0,T.useState)(null),ln=(0,T.useRef)(null);(0,T.useEffect)(()=>{ln.current=q},[q]);let[un,dn]=(0,T.useState)(`left`),[fn,pn]=(0,T.useState)([]),{openM1Drawer:mn,openM2Drawer:hn,goBack:gn}=Pe(),[_n,vn]=(0,T.useState)([]),J=(0,T.useMemo)(()=>{if(!K||V===`/`||W)return null;let e=V.split(`/`).filter(Boolean),t=K;for(let n of e)if(t=t?.children?.find(e=>e.name===n)??null,!t)return null;return t},[K,V,W]),Y=J?.type===`canvas`?`canvas`:null,yn=(0,T.useRef)(null);(0,T.useEffect)(()=>{!e||!K||W||yn.current===`${e}/${H}`&&(V!==`/`&&!J||Fe(e,H,V))},[e,K,W,V,J,H]);let bn=(0,T.useMemo)(()=>W||A===`workspace`||L.length>0?[]:qe(K,V),[K,V,W,A,L]),xn=W?null:V===`/`?K:J,X=xe(),Sn=`${H}\0${V}`,[Cn,wn]=(0,T.useState)(null),Tn=Cn?.key===Sn?Cn.views:Ke(xn?.metadata),En=X?.pinned&&X.view?[X.view,...Tn.filter(e=>e.id!==X.view.id)]:Tn,Dn=X?.pinned&&X.view?X.view.id:Cn?.key===Sn?Cn.activeId:En[0]?.id??ze.id,Z=En.find(e=>e.id===Dn)??En[0]??ze;(0,T.useEffect)(()=>{X?.selectView(Z)},[Z,X]);let On=U?void 0:X?.schema??We(Z),kn=On?[...Ut,On]:Ut;Je(He({workspace:e??null,treeNameOrId:H,treeType:g(H),path:V,scope:A===`workspace`?`workspace`:W?`layer`:`path`,layerId:W?G:void 0,unfiledOnly:tn},{...R.filters,features:{...R.filters.features,allOf:kn}},R.geoSelection,L));let An=e=>{let t=En.find(t=>t.id===e);t&&X?.selectView(t),F(1),pn([]),wn({key:Sn,views:En,activeId:e})},jn=(t,n)=>{n&&n!==Dn&&(F(1),pn([]));let r=t.find(e=>e.id===(n??Dn));r&&X?.selectView(r),wn({key:Sn,views:t,activeId:n??Dn}),oe(e,V,{metadata:{...xn?.metadata??{},views:t}},H).catch(()=>{s({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},Mn=Y===`canvas`&&typeof J?.querySpec?.query==`string`?J.querySpec.query:``,Nn=Y===`canvas`?{label:J?.label,description:J?.description,color:J?.color}:null,{isPinned:Pn,pin:Fn,unpin:In,pins:Ln}=ve(),Rn=C?.name,Q=(0,T.useMemo)(()=>Rn&&Y===`canvas`&&!W?{workspaceName:Rn,treeName:H,path:V}:null,[Rn,Y,W,H,V]),zn=Q?Pn(Q):!1,Bn=J?.id,Vn=J?.label,Hn=(0,T.useCallback)(async()=>{if(Q)try{let e=Ln.find(e=>e.workspaceName===Q.workspaceName&&e.treeName===Q.treeName&&e.path===Q.path);e?await In(e.id):await Fn({...Q,layerId:Bn,label:Vn})}catch(e){console.error(`Failed to update home pins:`,e)}},[Q,Ln,Fn,In,Bn,Vn]),Un=e?`${e}://${V===`/`?``:V.replace(/^\//,``)}`:``,Wn=we(C?.color)||null;(0,T.useEffect)(()=>(Vt(Wn),()=>Vt(null)),[Wn,Vt]);let Gn=(0,T.useCallback)(async t=>{let n=B;if(t?.anyOf?.length&&z.length&&(n=((await v(e,V,H,{limit:0,anyOf:z,ids:B,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!n.length))return{payload:[],count:0,totalCount:0};let r=await v(e,V,H,{limit:t?.limit,offset:t?.offset,page:t?.page,sortBy:t?.sortBy,order:t?.order,allOf:[...Ut,...t?.allOf??[]],anyOf:t?.anyOf?.length?t.anyOf:z,noneOf:Wt,filters:Jt,ids:n,queries:[...L,...t?.queries??[],...t?.q?[t.q]:[]],applyCanvasSpec:!1});return{payload:r.payload||[],count:r.count??void 0,totalCount:r.totalCount??void 0}},[e,V,H,Xt,L]);(0,T.useEffect)(()=>{e&&(async()=>{et(!0);try{let t=await p.get(`${f.workspaces}/${e}`),n;n=t&&`workspace`in t?t.workspace:t,Qe(n)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch workspace ${e}`;s({title:`Error`,description:n,variant:`destructive`}),Qe(null)}finally{et(!1)}})()},[e,s]),(0,T.useEffect)(()=>{let e=e=>{let t=e.detail?.workspace;t&&Qe(e=>e&&(t===e.name||t===e.id)&&e.status!==`active`?{...e,status:`active`}:e)};return window.addEventListener(`workspace:autostarted`,e),()=>window.removeEventListener(`workspace:autostarted`,e)},[]);let Kn=(B?.length??0)>0&&!W&&!(tn&&en)&&L.length<=1,{documents:qn,count:Jn,ready:Yn,setCue:Xn,resync:Zn,rank:Qn}=gt({workspaceRef:e,specs:(0,T.useMemo)(()=>{let e={features:{allOf:kn,anyOf:z,noneOf:Wt},filters:Jt};return A!==`workspace`&&(g(H)===`directory`?e.directory={tree:H,path:V}:e.context=V),[{label:`scope`,spec:e}]},[Zt,V,H,A,On]),opts:(0,T.useMemo)(()=>({mode:`live`,debounceMs:150}),[]),enabled:Kn}),$n=Kn&&Yn,er=(0,T.useRef)(!1);(0,T.useEffect)(()=>{er.current=$n},[$n]);let tr=L.length===1?L[0].trim():``;(0,T.useEffect)(()=>{Yn&&Qn(tr?{text:tr}:null,{limit:I,offset:(P-1)*I}).catch(()=>{})},[Yn,tr,I,P,Qn]);let nr=(B??[]).join(`,`);(0,T.useEffect)(()=>{Yn&&Xn(`lens`,{ids:B??[]}).catch(()=>{})},[Yn,nr,Xn,B]);let rr=$n?qn:tt,ir=$n?Jn:it,ar=(0,T.useRef)(new Set);(0,T.useEffect)(()=>{ar.current=new Set(rr.map(e=>Number(e.id)))},[rr]);let or=R.geoSelection;(0,T.useEffect)(()=>{Ht(rr,C?.name??null)},[rr,C?.name,Ht]),(0,T.useEffect)(()=>()=>Ht([]),[Ht]);let sr=(0,T.useMemo)(()=>or?rr.filter(e=>Te(e,or,R.filters.geo.includeUnlocated)):rr,[rr,or,R.filters.geo.includeUnlocated]),cr=fe(V,kn,{treeName:H,treeType:g(H),scope:A,queries:L,anyOf:z,noneOf:Wt,filters:Jt,ids:B,layerId:W&&G?G:void 0}),lr=JSON.stringify([e,cr]),[ur,dr]=(0,T.useState)(``),[fr,pr]=(0,T.useState)(!1),mr=(0,T.useRef)(!1),hr=rt||fr||ur!==lr||$n||!!or,gr=(0,T.useRef)(0),_r=(0,T.useRef)(null);(0,T.useEffect)(()=>()=>{gr.current++,_r.current=null},[]);let vr=(0,T.useRef)(``),$=(0,T.useCallback)(async t=>{if(!e)return;if(Ee(H,V)){gr.current++,_r.current=null,vr.current=``,w([]),O(0),D(!1);return}if(er.current)return;let n=`${tn&&en?`${A}:unfiled`:A}:${On??``}`,r=(B?.length??0)>0,i=bt(e,H,V,P,I,L.join(`␟`),Zt,W&&G?G:``,n),a=r&&i===vr.current;vr.current=i;let o=bt(e,H,V,P,I,L.join(`␟`),Xt,W&&G?G:``,n),c=`${o}\0${k}`;if(t?.silent&&_r.current?.key===c){_r.current.refreshPending=!0;return}let l=++gr.current,u=t?.silent||r||k?void 0:vt.get(o);u&&(w(u.documents),O(u.totalCount),dr(lr),D(!1)),(t?.silent??(a||!!u))||D(!0);let d={key:c,refreshPending:!1};_r.current=d;try{let t;if(tn&&en)t=await b(e,en.driver,en.address,{linked:!1,limit:I,offset:(P-1)*I});else if(W&&G&&A!==`workspace`)t=await ce(e,H,G,{limit:I,page:P,queries:L,allOf:kn,anyOf:z,noneOf:Wt,filters:Jt,ids:B,sortBy:Yt.sortBy||void 0,order:Yt.order});else{let n=g(H);t=await de(e,V,kn,{limit:I,page:P,treeName:H,treeType:n,queries:L,anyOf:z,noneOf:Wt,filters:Jt,ids:B,sortBy:Yt.sortBy||void 0,order:Yt.order,scope:A,debug:k&&L.length>0,debugLimit:200})}let n=t.payload||[],i=t.totalCount||t.count||0;if(!r&&!d.refreshPending&&vt.set(o,{documents:n,totalCount:i}),l!==gr.current)return;let s=t.debug,c=s?.imageDistances??s?.distances??null;ut(c?{query:L[L.length-1]??``,distances:c}:null),w(a?e=>e.length===n.length&&e.every((e,t)=>e.id===n[t].id)?e:n:n),O(i),dr(lr)}catch(e){if(l!==gr.current)return;let t=e instanceof Error?e.message:`Failed to fetch documents`;s({title:`Error`,description:t,variant:`destructive`}),w([]),O(0)}finally{_r.current===d&&(_r.current=null),l===gr.current&&D(!1),l===gr.current&&d.refreshPending&&$({silent:!0})}},[e,V,H,G,W,P,I,C?.status,L,Xt,A,tn,k,On]);(0,T.useEffect)(()=>{$()},[$]),(0,T.useEffect)(()=>{let t=t=>{let n=t.detail;!n||n.workspaceName!==e||(cn({treeName:n.treeName||`context`,path:Me(n.path||`/`)}),dn(`left`))};return window.addEventListener(`workspace:open-to-side`,t),()=>window.removeEventListener(`workspace:open-to-side`,t)},[e,H,V]),(0,T.useEffect)(()=>{let t=t=>{let n=t.detail;if(!(n?.workspaceName&&n.workspaceName!==e)&&(e&&St(e,n),lt(ct(n),{tree:H,kind:g(H),path:V,wholeWorkspace:A===`workspace`}))){if(e&&j(e,H,V),er.current){Zn();return}$({silent:!0})}};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[$,e,V,H,A,Zn]);let yr=C?.name,br=C?.id;(0,T.useEffect)(()=>{if(!e||!yr&&!br)return;let t=[yr,br].filter(Boolean).map(e=>`workspace:${e}`),n=()=>t.forEach(e=>m.emit(`subscribe`,{channel:e}));n();let r=m.on(`connect`,n),i=new Map,a=!1,o=()=>{ne(e).then(e=>{a||(i=at(e))}).catch(()=>{})};o();let s=null,c=0,l=!1,u=null,d=()=>{if(s=null,c=Date.now(),u){let{treeName:t,path:n}=u;u=null,window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,treeName:t,path:n}}))}if(l){if(l=!1,er.current){Zn();return}$({silent:!0})}},f=t=>n=>{(t.startsWith(`tree.created`)||t.startsWith(`tree.renamed`))&&o();let r=ot(t,n,i);xt(e,r);let a={tree:H,kind:g(H),path:V,wholeWorkspace:A===`workspace`},f=ln.current;f&&lt(r,{tree:f.treeName,kind:g(f.treeName),path:f.path})&&(u=f),lt(r,a,ar.current)&&(l=!0),!(!l&&!u)&&(s||=setTimeout(d,Math.max(200,c+1500-Date.now())))},p=[`document.inserted`,`document.inserted.batch`,`document.updated`,`document.removed`,`document.deleted`,`document.removed.batch`,`document.deleted.batch`,`document.linked`,`document.unlinked`,`document.linked.batch`,`document.unlinked.batch`,`tree.document.inserted`,`tree.document.inserted.batch`,`tree.document.removed`,`tree.document.removed.batch`,`tree.document.deleted`,`tree.document.deleted.batch`,`tree.layer.merged`,`tree.layer.subtracted`,`tree.created`,`tree.renamed`].map(e=>[e,f(e)]);return p.forEach(([e,t])=>m.on(e,t)),()=>{a=!0,s&&clearTimeout(s),r?.(),p.forEach(([e,t])=>m.off(e,t))}},[e,br,yr,H,V,A,$,Zn]);let xr=`${V}\0${H}\0${G??``}\0${A}`,[Sr,Cr]=(0,T.useState)(xr);Sr!==xr&&(Cr(xr),F(1),Rt(null));let wr=`${V}\0${H}\0${G??``}`,[Tr,Er]=(0,T.useState)(wr);Tr!==wr&&(Er(wr),pt(`path`));let Dr=(e,t)=>{let n=e===`/`?`canvas`:e.split(`/`).pop()||`canvas`;Dt(n),wt({parentPath:e,captureView:t})},Or=l.get(`createCanvas`)===`1`,[kr,Ar]=(0,T.useState)(!1);kr!==Or&&(Ar(Or),Or&&Dr(V,!1)),(0,T.useEffect)(()=>{if(!Or)return;let e=new URLSearchParams(n.search);e.delete(`createCanvas`);let t=e.toString();o(`${n.pathname}${t?`?${t}`:``}${n.hash}`,{replace:!0})},[Or,V]);let jr=(0,T.useCallback)(e=>{let t=new URLSearchParams(n.search);t.delete(`q`),t.delete(`search`);for(let n of e)t.append(`q`,n);let r=t.toString();o(`${n.pathname}${r?`?${r}`:``}${n.hash}`)},[n.pathname,n.search,n.hash,o]),Mr=JSON.stringify([l.has(`q`),...Le]),[Nr,Pr]=(0,T.useState)(Mr);Nr!==Mr&&(Pr(Mr),It(Le),F(1));let Fr=`${Mr}\0${Y??``}\0${Mn}\0${V}\0${Lt??``}`,[Ir,Lr]=(0,T.useState)(Fr);Ir!==Fr&&(Lr(Fr),l.has(`q`)||Le.length>0||Y!==`canvas`||Lt===V||(It(Mn?[Mn]:[]),F(1)));let Rr=(0,T.useCallback)(e=>{let t=e.trim();t&&(Rt(null),It(e=>{if(e.includes(t))return e;let n=[...e,t];return jr(n),F(1),n}))},[jr,Rt,It,F]),zr=(0,T.useCallback)(e=>{It(t=>{let n=e<0?[]:t.filter((t,n)=>n!==e);return n.length===0&&Rt(V),jr(n),F(1),n})},[jr,V,Rt,It,F]),Br=L.join(` `).trim(),Vr=!!R.activeContextType&&(R.isDirty||Br!==(Y===`canvas`?Mn:R.savedSearchQuery||``));!e&&K!==null&&sn(null),(0,T.useEffect)(()=>{let t=!1;if(!e)return;let n=0,r=!1,i=(i=!1)=>{let a=++n;i&&se(e,H),te(e,H).then(i=>{!t&&a===n&&(r=!0,yn.current=`${e}/${H}`,sn(i))}).catch(()=>{!t&&a===n&&!r&&sn(null)})};i(!1);let a=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==H||i(!n?.cacheInvalidated)};window.addEventListener(`workspace:tree:refresh`,a);let o=S(e,br);return()=>{t=!0,o(),window.removeEventListener(`workspace:tree:refresh`,a)}},[e,H,br]),!(e&&Y===`canvas`&&!W)&&N!==null&&Pt(null),(0,T.useEffect)(()=>{let t=!1;if(!(!e||Y!==`canvas`||W))return re(e,V,H).then(e=>{t||Pt(e)}).catch(()=>{t||Pt(null)}),()=>{t=!0}},[e,V,H,Y,W]);let Hr=async()=>{if(C){ht(!0);try{let t=await le(e||C.id);Qe(t),s({title:`Success`,description:`Workspace started successfully`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){let t=e instanceof Error?e.message:`Failed to start workspace`;s({title:`Error`,description:t,variant:`destructive`})}finally{ht(!1)}}},Ur=async t=>{if(!C)return;let n=c({title:`Removing…`,description:`Document from "${V}"`});try{await ue(e||C.id,[t],V,[],H,Zr,{trashIfOrphaned:!0}),j(e||C.id,H,V),w(e=>e.filter(e=>e.id!==t)),O(e=>Math.max(0,e-1)),n.done({title:`Success`,description:`Document removed from workspace path.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},Wr=async t=>{if(!C)return;let n=c({title:`Deleting…`,description:`Document from "${V}"`});try{await me(e||C.id,[t],V,[],H,Zr),j(e||C.id,H,V),w(e=>e.filter(e=>e.id!==t)),O(e=>Math.max(0,e-1)),n.done({title:`Success`,description:`Document deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},Gr=async t=>{if(!C)return;let n=c({title:`Removing…`,description:`${t.length} document(s) from "${V}"`});try{await ue(e||C.id,t,V,[],H,Zr,{trashIfOrphaned:!0}),j(e||C.id,H,V),w(e=>e.filter(e=>!t.includes(e.id))),O(e=>Math.max(0,e-t.length)),n.done({title:`Success`,description:`${t.length} document(s) removed.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},Kr=async t=>{if(!C)return;let n=c({title:`Deleting…`,description:`${t.length} document(s)`});try{await me(e||C.id,t,V,[],H,Zr),j(e||C.id,H,V),w(e=>e.filter(e=>!t.includes(e.id))),O(e=>Math.max(0,e-t.length)),n.done({title:`Success`,description:`${t.length} document(s) deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},qr=async t=>{if(!C)return;let n=c({title:`Destroying…`,description:`Document and its backend copies`});try{let r=await ee(e||C.id,[t]);if(r.failed?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}w(e=>e.filter(e=>e.id!==t)),O(e=>Math.max(0,e-1)),n.done({title:`Destroyed`,description:`Document removed from all backends.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy document`,variant:`destructive`})}},Jr=async t=>{if(!C)return;let n=c({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await ee(e||C.id,t),i=new Set(r.successful?.filter(e=>e.docDeleted).map(e=>e.id)??[]);w(e=>e.filter(e=>!i.has(e.id))),O(e=>Math.max(0,e-i.size));let a=[r.successful?.length?`${r.successful.length} destroyed`:null,r.failed?.length?`${r.failed.length} failed`:null].filter(Boolean).join(`, `);r.failed?.length?n.fail({title:`Destroy incomplete`,description:a,variant:`destructive`}):n.done({title:`Destroyed`,description:a||`No documents destroyed`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},Yr=e=>{Ct({documentIds:e,operation:`copy`,sourcePath:V,sourceTreeName:H}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}})),s({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},Xr=e=>{Ct({documentIds:e,operation:`cut`,sourcePath:V,sourceTreeName:H}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}})),s({title:`Cut`,description:`${e.length} document(s) cut to clipboard`})},Zr=g(H),Qr=async(t,n,r={})=>{if(!e)return!1;let i=r.targetTreeName??H,a=r.targetTreeType??Zr,o=r.move??yt?.operation===`cut`,s=c({title:o?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let c=await _e(e,t,n,i,a);if(c){j(e,i,t);let a=r.sourceTreeName||yt?.sourceTreeName,c=r.sourcePath||yt?.sourcePath;if((r.move??yt?.operation===`cut`)&&c&&a){let t=g(a);await ue(e,n,c,[],a,t),j(e,a,c),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:c,treeName:a}}))}s.done({title:`Success`,description:`${n.length} document(s) ${o?`moved`:`pasted`} to "${t}"`}),Ct(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}));let l=performance.now();await $(),console.info(`[paste] list refresh ${Math.round(performance.now()-l)} ms`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:i}}))}else s.done();return c}catch(e){return s.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},$r=async(t,n)=>{if(!e)return!1;try{let r=(await pe(e,n,t,H,Zr)).length>0;return r&&(Se(e,H,n),s({title:`Success`,description:`Imported ${t.length} document(s) to "${n}"`})),r}catch(e){return s({title:`Error`,description:e instanceof Error?e.message:`Failed to import documents`,variant:`destructive`}),!1}},ei=async()=>{if(!C||ir===0||hr||mr.current||window.prompt(`Type PURGE to permanently delete all ${ir} matching documents across all pages.`)!==`PURGE`)return;mr.current=!0,pr(!0);let t=c({title:`Purging…`,description:`${ir} matching document(s)`});try{let n=await y(e||C.id,cr,ir);n.deleted===n.requested?t.done({title:`Success`,description:`${n.deleted} document(s) purged.`}):t.fail({title:`Purge incomplete`,description:`${n.deleted} of ${n.requested} document(s) purged. Refresh and review the remaining results before retrying.`})}catch(e){t.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to purge documents`,variant:`destructive`})}finally{j(e||C.id,H,V),await $({silent:!0}),mr.current=!1,pr(!1)}},ti=()=>Dr(V,!0),ni=async()=>{if(!(!e||!M||!Et.trim())){kt(!0);try{let t=Et.trim(),n=M.parentPath,r=n===`/`?`/${t}`:`${n}/${t}`,i={...R.filters,features:{...R.filters.features,allOf:kn}};await he(e,r,H,M.captureView?{metadata:{toolbox:i},querySpec:{features:i.features,filters:[...Oe(R.filters.timeline),...De(R.filters.geo)],query:Br||void 0,sort:R.filters.sort?.sortBy?R.filters.sort:null}}:{}),wt(null),se(e,H);try{let t=await te(e,H,{force:!0});sn(t)}catch{}window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),o(Ne(e,r,H))}catch(e){s({title:`Error`,description:e instanceof Error?e.message:`Failed to create canvas`,variant:`destructive`})}finally{kt(!1)}}},ri=async()=>{if(!(!e||Y!==`canvas`)){jt(!0);try{let t=N||await ie(e,V,H);Pt(t);let n=`${window.location.origin}${t.url}`;await navigator.clipboard?.writeText(n),s({title:`Public canvas link copied`,description:n})}catch(e){s({title:`Error`,description:e instanceof Error?e.message:`Failed to share canvas`,variant:`destructive`})}finally{jt(!1)}}},ii=async()=>{if(N){jt(!0);try{await x(N.code),Pt(null),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:H}})),s({title:`Canvas unshared`,description:`The public link no longer works.`})}catch(e){s({title:`Error`,description:e instanceof Error?e.message:`Failed to unshare canvas`,variant:`destructive`})}finally{jt(!1)}}},ai=async()=>{if(!e||Y!==`canvas`||V===`/`)return;let t=Nn?.label||V.split(`/`).pop()||`canvas`,n=N?` Its public link will stop working.`:``;if(window.confirm(`Delete canvas "${t}"? This cannot be undone.${n}`)){Nt(!0);try{if(N)await x(N.code),Pt(null);else if(J?.locked){s({title:`Canvas is locked`,description:`Unlock it before deleting.`,variant:`destructive`});return}await _(e,V,!1,H);let n=V.split(`/`).filter(Boolean);n.pop();let r=n.length?`/${n.join(`/`)}`:`/`;window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:H}})),o(Ne(e,r,H)),s({title:`Canvas deleted`,description:`"${t}" was removed.`})}catch(e){s({title:`Error`,description:e instanceof Error?e.message:`Failed to delete canvas`,variant:`destructive`})}finally{Nt(!1)}}},oi=(0,T.useCallback)(async t=>{if(!e||!q)return;let n={treeName:H,path:V},r=un===`left`?n:q,i=un===`left`?q:n,a=un===`left`?fn:_n;if(a.length===0){s({title:`Nothing selected`,description:`Tick documents in the focused pane first.`});return}let o=g(i.treeName),l=c({title:t?`Moving…`:`Copying…`,description:`${a.length} document(s) → "${i.path}"`});try{if(!await _e(e,i.path,a,i.treeName,o)){l.done();return}if(j(e,i.treeName,i.path),t){let t=g(r.treeName);await ue(e,a,r.path,[],r.treeName,t),j(e,r.treeName,r.path)}[r,i].forEach(t=>window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t.path,treeName:t.treeName}}))),l.done({title:t?`Moved`:`Copied`,description:`${a.length} document(s) → "${i.path}"`})}catch(e){l.fail({title:`Error`,description:e instanceof Error?e.message:`Transfer failed`,variant:`destructive`})}},[e,q,un,H,V,fn,_n,s,c]);if((0,T.useEffect)(()=>{if(!q)return;let e=e=>{if(e.key!==`F5`&&e.key!==`F6`)return;let t=e.target;t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&(e.preventDefault(),oi(e.key===`F6`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[q,oi]),$e)return(0,E.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,E.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,E.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,E.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading workspace...`})]})});if(!C)return(0,E.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Workspace not found.`});let si=Y===`canvas`&&!W&&!!J,ci=!si&&!U&&xn?(0,E.jsx)(Ve,{views:En,activeId:Dn,onSelect:An,onSave:jn,accentColor:we(C.color),onOpenToSide:e=>{cn({treeName:H,path:V,viewId:e}),dn(`right`)}}):void 0,li=en||C.status!==`active`?(0,E.jsxs)(E.Fragment,{children:[en&&(0,E.jsx)(`button`,{type:`button`,onClick:()=>{nn(!tn),F(1)},"aria-pressed":tn,className:u(`min-h-10 rounded-md border px-2 text-xs`,tn&&`bg-warning/15 text-warning`),children:`Unfiled only`}),C.status!==`active`&&(0,E.jsx)(`button`,{type:`button`,onClick:Hr,disabled:mt,className:`min-h-10 rounded-md border px-2 text-xs`,children:mt?`Starting…`:`Start`})]}):void 0,ui=Ee(H,V)?V===`/Trash`?(0,E.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,E.jsx)(Ye,{workspaceName:e||C.id})}):(0,E.jsx)(Xe,{workspace:e||C.id,path:V,onNavigate:t=>o(Ne(e,t,`backends`))},e):(0,E.jsx)(Be,{navigationTabs:ci,navigationActions:li,onBack:gn,accentColor:we(C.color),urlType:W?g(H)===`directory`?`${H}-layer`:`context-layer`:Y===`canvas`?`canvas`:g(H)===`directory`?H:`context`,urlDisplay:Un,contextPath:V,treeName:H,workspaceId:e||C.id,workspaceLabel:C.label||C.name,workspaceIcon:C.icon,documentSchema:On,documents:sr,isLoading:rt,totalCount:ir,currentPage:P,pageSize:I,onPageChange:F,onPageSizeChange:e=>{Ft(e),F(1)},onRemoveDocument:V===`/`?void 0:Ur,onDeleteDocument:Wr,onDestroyDocument:qr,onRemoveDocuments:V===`/`?void 0:Gr,onDeleteDocuments:Kr,onDestroyDocuments:Jr,onCopyDocuments:Yr,onCutDocuments:Xr,onPasteDocuments:U?void 0:Qr,onImportDocuments:U?void 0:$r,onSelectionChange:pn,onBrowseTree:()=>hn(`workspaces`,`detail`,e??null),onBrowseWorkspaces:()=>mn(`workspaces`),onNavigatePath:t=>o(Ne(e,t,H)),folders:bn,onOpenFolder:t=>o(Ne(e,Me(t),H)),scope:A,onScopeChange:pt,pastedDocumentIds:yt?.documentIds,linkTree:K,onPurgeDocuments:U?void 0:ei,disablePurgeDocuments:hr,canvasInfo:Nn??void 0,isCanvasPinned:zn,onTogglePinCanvas:Q?Hn:void 0,onSaveAsCanvas:K&&Y!==`canvas`&&!W&&!U?ti:void 0,onShareCanvas:Y===`canvas`&&!W?ri:void 0,onUnshareCanvas:N?ii:void 0,onDeleteCanvas:Y===`canvas`&&!W?ai:void 0,isSharingCanvas:At,isDeletingCanvas:Mt,isCanvasShared:!!N,isCanvasLocked:!!J?.locked,backendSearchQueries:L,onBackendSearch:Rr,serverSort:R.filters.sort,onServerSortChange:Bt,onRemoveBackendQuery:zr,canSaveChanges:Vr,isSavingChanges:R.isSaving,onSaveChanges:zt,contentBanner:k&&st?(0,E.jsx)(_t,{data:st,className:`mb-3`}):null,children:si&&J?(0,E.jsx)(ye,{workspaceId:e||C.id,treeName:H,path:V,layerId:J.id,querySpec:J.querySpec,metadata:J.metadata,isLocked:!!J.locked,fetchDocuments:R.isDirty?Gn:void 0}):!U&&Z.kind===`columns`?(0,E.jsx)(Ge,{documents:sr,workspaceId:e||C.id,columns:Z.columns??[],onColumnsChange:e=>jn(En.map(t=>t.id===Z.id?{...t,columns:e}:t))}):!U&&Z.kind===`app`&&Z.app&&Z.app!==`notes`?(0,E.jsx)(Ue,{app:Z.app,workspaceId:e||C.id,treeName:H,path:V}):null});return(0,E.jsxs)(Ie,{workspaceId:e||C.id,treeName:H,path:V,headerOnly:!0,className:`relative flex flex-col h-full min-h-0`,children:[(0,E.jsx)(nt,{workspaceId:C.id,workspaceName:C.label||C.name},C.id),Ee(H,V)&&(0,E.jsx)(be,{workspace:C.label||C.name,workspaceIcon:C.icon,tree:H,path:V,onBack:gn,onBrowseTree:()=>hn(`workspaces`,`detail`,e||C.id),onBrowseWorkspaces:()=>mn(`workspaces`),onNavigatePath:t=>o(Ne(e,t,H)),accentColor:we(C.color)}),M&&(0,E.jsx)(`div`,{className:`shrink-0 px-2 pt-2`,children:(0,E.jsx)(Re,{title:`New canvas`,onClose:()=>wt(null),children:(0,E.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),ni()},className:`space-y-4`,children:[(0,E.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,E.jsxs)(`div`,{children:[(0,E.jsx)(`label`,{htmlFor:`canvas-name`,className:`mb-1 block text-sm font-medium`,children:`Name`}),(0,E.jsx)(`input`,{id:`canvas-name`,className:`w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary`,placeholder:`Canvas name…`,value:Et,onChange:e=>Dt(e.target.value),onKeyDown:e=>{e.key===`Escape`&&wt(null)},autoFocus:!0})]}),(0,E.jsxs)(`div`,{children:[(0,E.jsx)(`span`,{className:`mb-1 block text-sm font-medium`,children:`Parent path`}),(0,E.jsx)(`div`,{className:`flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:M.parentPath===`/`?`/`:M.parentPath})]})]}),(0,E.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,E.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:M.captureView,onChange:e=>wt({...M,captureView:e.target.checked})}),(0,E.jsxs)(`span`,{children:[`Capture the current view`,(0,E.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:`Freezes the active filters, search and sort into the canvas.`})]})]}),(0,E.jsxs)(`div`,{className:`flex gap-2`,children:[(0,E.jsx)(d,{type:`submit`,disabled:!Et.trim()||Ot,children:Ot?`Creating…`:`Create canvas`}),(0,E.jsx)(d,{type:`button`,variant:`outline`,onClick:()=>wt(null),children:`Cancel`})]})]})})}),(0,E.jsxs)(`div`,{"data-canvas-panes":!0,className:`flex-1 min-h-0 flex gap-2`,children:[(0,E.jsx)(`div`,{"data-canvas-pane":!0,className:u(`flex-1 min-w-0 bg-background overflow-hidden`,q&&(un===`left`?`ring-2 ring-primary`:`ring-1 ring-primary/20`)),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||dn(`left`)},children:ui}),q&&e&&(0,E.jsx)(Tt,{workspaceName:e,workspaceLabel:C.label||C.name,workspaceIcon:C.icon,pane:q,isFocused:un===`right`,clipboard:yt,setClipboard:Ct,onFocus:()=>dn(`right`),onSelectionChange:vn,onNavigate:e=>cn(t=>t&&{...t,path:e,viewId:void 0}),onClose:()=>{cn(null),dn(`left`),vn([])}})]})]})}function wt(e,t){if(!e||t===`/`)return e;let n=e;for(let e of t.split(`/`).filter(Boolean))if(n=n?.children?.find(t=>t.name===e)??null,!n)return null;return n}function Tt({workspaceName:e,workspaceLabel:t,workspaceIcon:n,pane:r,isFocused:i=!1,clipboard:a,setClipboard:o,onFocus:s,onSelectionChange:c,onNavigate:l,onClose:d}){let{openM1Drawer:f,openM2Drawer:p}=Pe(),{showToast:m,showProgress:_}=h(),[v,ne]=(0,T.useState)(null),[y,re]=(0,T.useState)([]),[ie,b]=(0,T.useState)(!1),[ae,oe]=(0,T.useState)(0),[ce,le]=(0,T.useState)(1),[fe,pe]=(0,T.useState)(50),x=g(r.treeName),he=wt(v,r.path),ge=he?.type===`canvas`,ve=(0,T.useMemo)(()=>qe(v,r.path),[v,r.path]),ye=r.viewId?Ke(he?.metadata).find(e=>e.id===r.viewId)??null:null,be=`${e}://${r.path===`/`?``:r.path.replace(/^\//,``)}`,xe=We(ye),S=(0,T.useCallback)(async()=>{if(Ee(r.treeName,r.path)){re([]),oe(0),b(!1);return}let t=bt(e,r.treeName,r.path,ce,fe,``,xe??``),n=vt.get(t);if(n){re(n.documents),oe(n.totalCount);return}b(!0);try{let n=await de(e,r.path,xe?[xe]:[],{limit:fe,page:ce,treeName:r.treeName,treeType:x}),i=n.payload||[],a=n.totalCount||n.count||0;re(i),oe(a),vt.set(t,{documents:i,totalCount:a})}catch(e){m({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch side pane documents`,variant:`destructive`}),re([]),oe(0)}finally{b(!1)}},[e,r.path,r.treeName,x,fe,ce,m,xe]);(0,T.useEffect)(()=>{let t=!1,n=0,i=!1,a=(a=!1)=>{let o=++n;a&&se(e,r.treeName),te(e,r.treeName).then(e=>{!t&&o===n&&(i=!0,ne(e))}).catch(()=>{!t&&o===n&&!i&&ne(null)})};a(!1);let o=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==r.treeName||a(!n?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,o),()=>{t=!0,window.removeEventListener(`workspace:tree:refresh`,o)}},[e,r.treeName]),(0,T.useEffect)(()=>{S()},[S]),(0,T.useEffect)(()=>{let t=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||(St(e,n),lt(ct(n),{tree:r.treeName,kind:g(r.treeName),path:r.path})&&(j(e,r.treeName,r.path),S()))};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[S,e,r.treeName,r.path]);let Se=(0,T.useCallback)(async(t,n,i={})=>{let s=i.targetTreeName??r.treeName,c=i.targetTreeType??x,l=i.move??a?.operation===`cut`,u=_({title:l?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let r=await _e(e,t,n,s,c);if(r){j(e,s,t);let r=i.sourcePath||a?.sourcePath,c=i.sourceTreeName||a?.sourceTreeName;if((i.move??a?.operation===`cut`)&&r&&c){let t=g(c);await ue(e,n,r,[],c,t),j(e,c,r),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:r,treeName:c}}))}u.done({title:`Success`,description:`${n.length} document(s) ${l?`moved`:`pasted`} to "${t}"`}),o(null),await S(),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:s}}))}else u.done();return r}catch(e){return u.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},[e,r.treeName,x,S,_,a,o]),Ce=(0,T.useCallback)(()=>{j(e,r.treeName,r.path),S()},[e,r.treeName,r.path,S]),we=(0,T.useCallback)(async t=>{let n=_({title:`Removing…`,description:`${t.length} document(s) from "${r.path}"`});try{await ue(e,t,r.path,[],r.treeName,x),Ce(),n.done({title:`Removed`,description:`${t.length} document(s) removed from "${r.path}"`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},[e,r.path,r.treeName,x,Ce,_]),Te=(0,T.useCallback)(async t=>{let n=_({title:`Deleting…`,description:`${t.length} document(s)`});try{await me(e,t,r.path,[],r.treeName,x),Ce(),n.done({title:`Deleted`,description:`${t.length} document(s) deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},[e,r.path,r.treeName,x,Ce,_]),De=(0,T.useCallback)(async t=>{let n=_({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await ee(e,t);if(r.failed?.length&&!r.successful?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}Ce();let i=`${r.successful?.length??0} document(s) destroyed${r.failed?.length?` · ${r.failed.length} failed`:``}.`;r.failed?.length?n.fail({title:`Destroy incomplete`,description:i,variant:`destructive`}):n.done({title:`Destroyed`,description:i})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},[e,Ce,_]);return(0,E.jsxs)(`div`,{className:u(`relative flex-1 min-w-0 rounded-(--sheet-radius) border bg-background overflow-hidden`,i?`ring-2 ring-primary`:`ring-1 ring-primary/20`),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||s()},children:[d&&(0,E.jsx)(`button`,{type:`button`,onClick:d,className:`absolute right-2 top-2 z-10 px-2 py-1 text-xs rounded-md border bg-background/90 hover:bg-accent`,children:`Close`}),Ee(r.treeName,r.path)?r.path===`/Trash`?(0,E.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,E.jsx)(Ye,{workspaceName:e})}):(0,E.jsx)(Xe,{workspace:e,path:r.path,onNavigate:l||(()=>{})}):(0,E.jsx)(Be,{frameContent:!1,onBrowseWorkspaces:()=>f(`workspaces`),onBrowseTree:()=>p(`workspaces`,`detail`,e),urlType:ge?`canvas`:x===`directory`?r.treeName:`context`,urlDisplay:be,contextPath:r.path,treeName:r.treeName,workspaceId:e,workspaceLabel:t,workspaceIcon:n,documentSchema:xe,documents:y,isLoading:ie,totalCount:ae,currentPage:ce,pageSize:fe,onPageChange:le,onPageSizeChange:e=>{pe(e),le(1)},onRemoveDocument:r.path===`/`?void 0:e=>we([e]),onRemoveDocuments:r.path===`/`?void 0:we,onDeleteDocument:e=>Te([e]),onDeleteDocuments:Te,onDestroyDocument:e=>De([e]),onDestroyDocuments:De,onCopyDocuments:e=>{o({documentIds:e,operation:`copy`,sourcePath:r.path,sourceTreeName:r.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}}))},onCutDocuments:e=>{o({documentIds:e,operation:`cut`,sourcePath:r.path,sourceTreeName:r.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}}))},onPasteDocuments:r.treeName===`backends`?void 0:Se,onSelectionChange:c,pastedDocumentIds:a?.documentIds,linkTree:v,folders:ve,onOpenFolder:l,onNavigatePath:l,canvasInfo:ge?{label:he?.label,description:he?.description,color:he?.color}:void 0,children:ye?.kind===`columns`?(0,E.jsx)(Ge,{documents:y,workspaceId:e,columns:ye.columns??[],onColumnsChange:()=>{},readOnly:!0}):ye?.kind===`app`&&ye.app&&ye.app!==`notes`?(0,E.jsx)(Ue,{app:ye.app,workspaceId:e,treeName:r.treeName,path:r.path}):null})]})}export{Ct as default};
@@ -1 +1 @@
1
- import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{t as r}from"./api-CA6WiiYM.js";import{n as i}from"./page-header-DrDt1sQ2.js";import{t as a}from"./use-settings-back-DGmLAD63.js";var o=e(n(),1),s=t();function c(e){let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?`${t}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`}function l({name:e,version:t,detail:n}){return(0,s.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,s.jsxs)(`div`,{className:`min-w-0`,children:[(0,s.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,s.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,s.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function u(){let[e,t]=(0,o.useState)(null),[n,u]=(0,o.useState)(null);(0,o.useEffect)(()=>{let e=!0;return r.get(`/ping`,{skipAuth:!0}).then(n=>{e&&t(n??{})}).catch(t=>{e&&u(t instanceof Error?t.message:`Failed to reach the server`)}),()=>{e=!1}},[]);let d=[e?.commit?`commit ${e.commit.slice(0,7)}`:null,typeof e?.uptime==`number`?`up ${c(e.uptime)}`:null].filter(Boolean).join(` · `),f=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,s.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,s.jsx)(i,{className:`mb-6`,title:`About`,onBack:a(),description:`Versions of every Canvas component this installation is running.`}),(0,s.jsxs)(`div`,{className:`space-y-6`,children:[(0,s.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,s.jsx)(l,{name:`Canvas Web`,detail:`this interface`,version:`v2.26.36`}),e?.version&&(0,s.jsx)(l,{name:e.productName||e.appName||`Canvas Server`,detail:d||void 0,version:`v${e.version}`})]}),f.length>0&&(0,s.jsxs)(`section`,{children:[(0,s.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,s.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:f.map(([e,t])=>(0,s.jsx)(l,{name:e,version:`v${t}`},e))})]}),n&&(0,s.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,s.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,s.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}export{u as default};
1
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{t as r}from"./api-CA6WiiYM.js";import{n as i}from"./page-header-DrDt1sQ2.js";import{t as a}from"./use-settings-back-DGmLAD63.js";var o=e(n(),1),s=t();function c(e){let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?`${t}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`}function l({name:e,version:t,detail:n}){return(0,s.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,s.jsxs)(`div`,{className:`min-w-0`,children:[(0,s.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,s.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,s.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function u(){let[e,t]=(0,o.useState)(null),[n,u]=(0,o.useState)(null);(0,o.useEffect)(()=>{let e=!0;return r.get(`/ping`,{skipAuth:!0}).then(n=>{e&&t(n??{})}).catch(t=>{e&&u(t instanceof Error?t.message:`Failed to reach the server`)}),()=>{e=!1}},[]);let d=[e?.commit?`commit ${e.commit.slice(0,7)}`:null,typeof e?.uptime==`number`?`up ${c(e.uptime)}`:null].filter(Boolean).join(` · `),f=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,s.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,s.jsx)(i,{className:`mb-6`,title:`About`,onBack:a(),description:`Versions of every Canvas component this installation is running.`}),(0,s.jsxs)(`div`,{className:`space-y-6`,children:[(0,s.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,s.jsx)(l,{name:`Canvas Web`,detail:`this interface`,version:`v2.26.38`}),e?.version&&(0,s.jsx)(l,{name:e.productName||e.appName||`Canvas Server`,detail:d||void 0,version:`v${e.version}`})]}),f.length>0&&(0,s.jsxs)(`section`,{children:[(0,s.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,s.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:f.map(([e,t])=>(0,s.jsx)(l,{name:e,version:`v${t}`},e))})]}),n&&(0,s.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,s.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,s.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}export{u as default};
@@ -1 +1 @@
1
- import{l as e}from"./code-editor-BOIngd5F.js";import{_ as t,a as n,g as r}from"./chunk-62JRHF6Z-vspAGgtK.js";import{t as i}from"./HomeFab-CXuEjvlA.js";var a=e(),o=[`note`,`todo`,`link`,`file`,`photo`];function s(){let{kind:e}=t(),s=r();return e===`sketch`?(0,a.jsx)(n,{to:`/apps/sketch?add=1`,replace:!0}):!e||!o.includes(e)?(0,a.jsx)(n,{to:`/home`,replace:!0}):(0,a.jsx)(i,{initialKind:e,onInitialCardClose:()=>s(`/home`)})}export{s as default};
1
+ import{l as e}from"./code-editor-BOIngd5F.js";import{_ as t,a as n,g as r}from"./chunk-62JRHF6Z-vspAGgtK.js";import{t as i}from"./HomeFab-W7y591CD.js";var a=e(),o=[`note`,`todo`,`link`,`file`,`photo`];function s(){let{kind:e}=t(),s=r();return e===`sketch`?(0,a.jsx)(n,{to:`/apps/sketch?add=1`,replace:!0}):!e||!o.includes(e)?(0,a.jsx)(n,{to:`/home`,replace:!0}):(0,a.jsx)(i,{initialKind:e,onInitialCardClose:()=>s(`/home`)})}export{s as default};
@@ -1 +1 @@
1
- import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{g as r}from"./chunk-62JRHF6Z-vspAGgtK.js";import{I as i,It as a,Pt as o,Qr as s,Sr as c,rn as l,rt as u}from"./ui-CDoK3F3U.js";import{t as d}from"./button-SeUZ_Pvi.js";import{t as f}from"./input-BOtCd4HP.js";import{n as p}from"./use-toast-BlLDqSUO.js";import{t as m}from"./color-DFEH4BfK.js";import{J as h,L as g,Ot as _,et as v,tt as y}from"./index-DRHEGJ8I.js";import{n as b}from"./page-header-DrDt1sQ2.js";import{n as ee,r as x,t as te}from"./useAgentModels-BjT4oN4e.js";import{t as ne}from"./form-panel-3p-ncEVK.js";import{t as re}from"./use-create-panel-DhSNIGtr.js";import{n as ie,t as ae}from"./useSocketSubscription-ifW-vnlb.js";var S=e(n(),1),C=t();function w({agent:e,onStart:t,onStop:n,onEnter:r}){let[o,f]=(0,S.useState)(!1),p=async()=>{f(!0);try{await t(e.name)}finally{f(!1)}},m=async()=>{f(!0);try{await n(e.name)}finally{f(!1)}},h=()=>{switch(e.status){case`active`:return(0,C.jsx)(c,{className:`h-4 w-4 text-success`});case`inactive`:return(0,C.jsx)(c,{className:`h-4 w-4 text-warning`});case`error`:return(0,C.jsx)(c,{className:`h-4 w-4 text-destructive`});default:return(0,C.jsx)(c,{className:`h-4 w-4 text-muted-foreground`})}},g=()=>{switch(e.llmProvider){case`anthropic`:return(0,C.jsx)(s,{className:`h-4 w-4 text-warning`});case`openai`:return(0,C.jsx)(s,{className:`h-4 w-4 text-success`});case`ollama`:return(0,C.jsx)(i,{className:`h-4 w-4 text-info`});default:return(0,C.jsx)(s,{className:`h-4 w-4 text-muted-foreground`})}},_=()=>{switch(e.status){case`active`:return`text-success bg-success-subtle border-success`;case`inactive`:return`text-warning bg-warning-subtle border-warning`;case`error`:return`text-destructive bg-destructive-subtle border-destructive`;case`available`:return`text-info bg-info-subtle border-info`;default:return`text-foreground bg-muted border-border`}},v=e.status===`available`||e.status===`inactive`,y=e.status===`active`;return(0,C.jsxs)(`div`,{className:`border rounded-lg p-4 space-y-4 hover:shadow-elevation-2 transition-shadow bg-card`,children:[(0,C.jsxs)(`div`,{className:`flex items-start justify-between`,children:[(0,C.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,C.jsxs)(`div`,{className:`flex items-center gap-2 mb-1`,children:[g(),(0,C.jsx)(`h3`,{className:`text-lg font-semibold truncate`,children:e.label||e.name}),e.color&&(0,C.jsx)(`div`,{className:`w-4 h-4 rounded border flex-shrink-0`,style:{backgroundColor:e.color},title:`Color: ${e.color}`})]}),(0,C.jsx)(`p`,{className:`text-sm text-muted-foreground font-mono`,children:e.name}),e.description&&(0,C.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1 line-clamp-2`,children:e.description})]}),(0,C.jsxs)(`div`,{className:`flex items-center gap-2 flex-shrink-0`,children:[h(),(0,C.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs font-medium border ${_()}`,children:e.status})]})]}),(0,C.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 text-sm`,children:[(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`span`,{className:`text-muted-foreground`,children:`Provider:`}),(0,C.jsx)(`div`,{className:`font-medium capitalize`,children:e.llmProvider})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`span`,{className:`text-muted-foreground`,children:`Model:`}),(0,C.jsx)(`div`,{className:`font-mono text-xs`,children:e.model})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`span`,{className:`text-muted-foreground`,children:`Created:`}),(0,C.jsx)(`div`,{children:new Date(e.createdAt).toLocaleDateString()})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`span`,{className:`text-muted-foreground`,children:`Last Access:`}),(0,C.jsx)(`div`,{children:e.lastAccessed?new Date(e.lastAccessed).toLocaleDateString():`Never`})]})]}),e.config.mcp?.servers&&e.config.mcp.servers.length>0&&(0,C.jsxs)(`div`,{className:`text-sm`,children:[(0,C.jsx)(`span`,{className:`text-muted-foreground`,children:`MCP Servers:`}),(0,C.jsx)(`div`,{className:`flex flex-wrap gap-1 mt-1`,children:e.config.mcp.servers.map((e,t)=>(0,C.jsx)(`span`,{className:`px-2 py-1 bg-secondary text-secondary-foreground rounded text-xs`,children:e.name},t))})]}),(0,C.jsxs)(`div`,{className:`flex gap-2 pt-2 border-t`,children:[v&&(0,C.jsxs)(d,{onClick:p,disabled:o,size:`sm`,variant:`outline`,className:`flex-1`,children:[(0,C.jsx)(a,{className:`mr-2 h-4 w-4`}),`Start`]}),y&&(0,C.jsxs)(d,{onClick:m,disabled:o,size:`sm`,variant:`outline`,className:`flex-1`,children:[(0,C.jsx)(u,{className:`mr-2 h-4 w-4`}),`Stop`]}),(0,C.jsxs)(d,{onClick:()=>r(e.name),size:`sm`,className:`flex-1`,children:[(0,C.jsx)(l,{className:`mr-2 h-4 w-4`}),`Chat`]})]})]})}function T(){let e={anthropic:`https://api.anthropic.com`,openai:`https://api.openai.com/v1`,ollama:`http://localhost:11434/v1`},t={anthropic:`claude-3-5-sonnet-20241022`,openai:`gpt-4o`,ollama:`qwen2.5-coder:latest`},[n,i]=(0,S.useState)([]),[a,s]=(0,S.useState)(!0),[c,l]=(0,S.useState)(null),[u,T]=(0,S.useState)(``),[E,D]=(0,S.useState)(``),[O,k]=(0,S.useState)(m()),[A,j]=(0,S.useState)(``),[M,oe]=(0,S.useState)(`anthropic`),[N,P]=(0,S.useState)(t.anthropic),[F,I]=(0,S.useState)({apiKey:``,baseUrl:e.anthropic,maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096}),L=te(M,F.apiKey,F.baseUrl),R=L.models.find(e=>e.id===N),[z,B]=(0,S.useState)(``),[V,H]=(0,S.useState)(``),[U,W]=(0,S.useState)(``),[G,K]=(0,S.useState)(``),[q,J]=(0,S.useState)(!1),Y=_(),[X,Z]=re(),{showToast:Q}=p(),se=r(),$=ie();ae($,`agent`,{"agent:status:changed":e=>{i(t=>t.map(t=>t.id===e.agentId?{...t,status:e.status,isActive:e.isActive}:t))},"agent:created":e=>{i(t=>[...t,e.agent])},"agent:deleted":e=>{i(t=>t.filter(t=>t.id!==e.agentId))}});let ce=n=>{oe(n),P(t[n]),I({apiKey:``,baseUrl:e[n],maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096})};(0,S.useEffect)(()=>((async()=>{try{s(!0);let e=await h();i(e),l(null)}catch(e){console.error(`Agent fetch error:`,e);let t=`Failed to fetch agents`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to fetch agents`}l(t),Q({title:`Error`,description:t,variant:`destructive`})}finally{s(!1)}})(),()=>{}),[$,Q]);let le=async t=>{if(t.preventDefault(),u.trim()){J(!0);try{let t=G.trim()||x(z,V,U),n={name:u,label:A||u,description:E||void 0,color:O,llmProvider:M,model:N,apiKey:F.apiKey.trim()||void 0,baseUrl:F.baseUrl.trim()||void 0,config:{type:M,model:N,identity:{role:z.trim()||void 0,identity:V.trim()||void 0,instructions:U.trim()||void 0},prompts:t?{system:t}:void 0,connectors:{[M]:{maxTokens:F.maxTokens,...M===`anthropic`?{}:{temperature:F.temperature},topP:F.topP,frequencyPenalty:F.frequencyPenalty,presencePenalty:F.presencePenalty,...M===`ollama`?{numCtx:F.numCtx}:{}}}},mcp:{enabled:!0,servers:[{name:`weather`,command:`node`,args:[`src/managers/agent/mcp-servers/weather.js`]}]}},r=await g(n);i(e=>[...e,r]),T(``),D(``),k(m()),j(``),K(``),B(``),H(``),W(``),I({apiKey:``,baseUrl:e[M],maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096}),Q({title:`Success`,description:`Agent '${r.label||r.name}' created.`}),Z(!1)}catch(e){console.error(`Agent creation error:`,e);let t=`Failed to create agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to create agent`}Q({title:`Error`,description:t,variant:`destructive`})}finally{J(!1)}}},ue=async e=>{try{let t=await v(e);i(e=>e.map(e=>e.name===t.name?t:e)),Q({title:`Success`,description:`Agent '${t.label||t.name}' started.`})}catch(e){console.error(`Agent start error:`,e);let t=`Failed to start agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to start agent`}Q({title:`Error`,description:t,variant:`destructive`})}},de=async e=>{try{await y(e),i(t=>t.map(t=>t.name===e?{...t,status:`inactive`,isActive:!1}:t)),Q({title:`Success`,description:`Agent '${e}' stopped.`})}catch(e){console.error(`Agent stop error:`,e);let t=`Failed to stop agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to stop agent`}Q({title:`Error`,description:t,variant:`destructive`})}},fe=e=>{se(`/agents/${e}`)};return(0,C.jsxs)(`div`,{className:`space-y-6`,children:[(0,C.jsx)(b,{title:`AI Agents`,description:`Create and manage your AI agents with multiple LLM providers`,actions:!Y.local&&!X&&(0,C.jsxs)(d,{onClick:()=>Z(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create agent`,title:`Create agent`,children:[(0,C.jsx)(o,{className:`h-4 w-4 sm:mr-2`}),(0,C.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Agent`})]})}),!Y.local&&X&&(0,C.jsx)(ne,{title:`Create New Agent`,onClose:()=>Z(!1),children:(0,C.jsxs)(`form`,{onSubmit:le,className:`space-y-4`,children:[(0,C.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,C.jsx)(f,{value:u,onChange:e=>T(e.target.value),placeholder:`Agent Name (e.g., 'my-assistant')`,disabled:q}),(0,C.jsx)(f,{value:A,onChange:e=>j(e.target.value),placeholder:`Agent Label (display name, optional)`,disabled:q})]}),(0,C.jsx)(f,{value:E,onChange:e=>D(e.target.value),placeholder:`Description (optional)`,disabled:q}),(0,C.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`agent-provider`,className:`text-sm font-medium`,children:`LLM Provider`}),(0,C.jsxs)(`select`,{id:`agent-provider`,value:M,onChange:e=>ce(e.target.value),className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring`,disabled:q,children:[(0,C.jsx)(`option`,{value:`anthropic`,children:`Anthropic Claude`}),(0,C.jsx)(`option`,{value:`openai`,children:`OpenAI GPT`}),(0,C.jsx)(`option`,{value:`ollama`,children:`Ollama (Local)`})]})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`agent-model`,className:`text-sm font-medium`,children:`Model`}),(0,C.jsx)(ee,{id:`agent-model`,value:N,onChange:(e,t)=>{P(e),t?.maxTokens&&I(e=>({...e,maxTokens:t.maxTokens}))},...L,disabled:q})]})]}),(0,C.jsxs)(`div`,{className:`space-y-4`,children:[(0,C.jsx)(`h3`,{className:`text-lg font-medium`,children:`Persona`}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`agent-role`,className:`text-sm font-medium`,children:`Role`}),(0,C.jsx)(f,{id:`agent-role`,value:z,onChange:e=>B(e.target.value),placeholder:`e.g. Software Engineer`,disabled:q})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`agent-identity`,className:`text-sm font-medium`,children:`Identity`}),(0,C.jsx)(`textarea`,{id:`agent-identity`,value:V,onChange:e=>H(e.target.value),placeholder:`Who this agent is…`,disabled:q,className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm min-h-[80px] resize-y`})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`agent-instructions`,className:`text-sm font-medium`,children:`Instructions`}),(0,C.jsx)(`textarea`,{id:`agent-instructions`,value:U,onChange:e=>W(e.target.value),placeholder:`Behavioral instructions…`,disabled:q,className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm min-h-[80px] resize-y`})]})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`system-prompt`,className:`text-sm font-medium`,children:`System Prompt (Optional Override)`}),(0,C.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Built from Role, Identity and Instructions unless you enter an override.`}),(0,C.jsx)(`textarea`,{id:`system-prompt`,value:G,onChange:e=>K(e.target.value),placeholder:x(z,V,U)||`System prompt sent to the LLM…`,className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring min-h-[80px] resize-y`,disabled:q})]}),(0,C.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`api-key`,className:`text-sm font-medium`,children:`API Key (Optional)`}),(0,C.jsx)(f,{id:`api-key`,type:`password`,value:F.apiKey,onChange:e=>I(t=>({...t,apiKey:e.target.value})),placeholder:`Enter your API key`,disabled:q})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`baseUrl`,className:`text-sm font-medium`,children:`Base URL (Optional)`}),(0,C.jsx)(f,{id:`baseUrl`,value:F.baseUrl,onChange:e=>I(t=>({...t,baseUrl:e.target.value})),placeholder:e[M],disabled:q})]})]}),(0,C.jsxs)(`div`,{className:`space-y-4`,children:[(0,C.jsx)(`h3`,{className:`text-lg font-medium`,children:`LLM Parameters`}),(0,C.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2 lg:grid-cols-4`,children:[(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`max-tokens`,className:`text-sm font-medium`,children:`Max Output Tokens`}),(0,C.jsx)(f,{id:`max-tokens`,type:`number`,min:`1`,max:R?.maxTokens,value:F.maxTokens,onChange:e=>I(t=>({...t,maxTokens:parseInt(e.target.value)||4096})),disabled:q})]}),M!==`anthropic`&&(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`temperature`,className:`text-sm font-medium`,children:`Temperature`}),(0,C.jsx)(f,{id:`temperature`,type:`number`,min:`0`,max:`2`,step:`0.1`,value:F.temperature,onChange:e=>I(t=>({...t,temperature:Number.isNaN(e.target.valueAsNumber)?.7:e.target.valueAsNumber})),disabled:q})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`top-p`,className:`text-sm font-medium`,children:`Top P`}),(0,C.jsx)(f,{id:`top-p`,type:`number`,min:`0`,max:`1`,step:`0.1`,value:F.topP,onChange:e=>I(t=>({...t,topP:Number.isNaN(e.target.valueAsNumber)?1:e.target.valueAsNumber})),disabled:q})]}),M===`ollama`&&(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`num-ctx`,className:`text-sm font-medium`,children:`Context Length`}),(0,C.jsx)(f,{id:`num-ctx`,type:`number`,min:`1024`,max:R?.contextWindow,value:F.numCtx,onChange:e=>I(t=>({...t,numCtx:parseInt(e.target.value)||4096})),disabled:q})]})]}),M!==`ollama`&&(0,C.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`frequency-penalty`,className:`text-sm font-medium`,children:`Frequency Penalty`}),(0,C.jsx)(f,{id:`frequency-penalty`,type:`number`,min:`-2`,max:`2`,step:`0.1`,value:F.frequencyPenalty,onChange:e=>I(t=>({...t,frequencyPenalty:parseFloat(e.target.value)||0})),disabled:q})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`presence-penalty`,className:`text-sm font-medium`,children:`Presence Penalty`}),(0,C.jsx)(f,{id:`presence-penalty`,type:`number`,min:`-2`,max:`2`,step:`0.1`,value:F.presencePenalty,onChange:e=>I(t=>({...t,presencePenalty:parseFloat(e.target.value)||0})),disabled:q})]})]})]}),(0,C.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,C.jsx)(`label`,{htmlFor:`agent-color`,className:`text-sm font-medium`,children:`Agent Color`}),(0,C.jsx)(f,{id:`agent-color`,type:`color`,value:O,onChange:e=>k(e.target.value),className:`h-10 w-16 p-1`,disabled:q}),(0,C.jsx)(d,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>k(m()),disabled:q,children:`Randomize`})]}),(0,C.jsxs)(d,{type:`submit`,disabled:q||!u.trim(),children:[(0,C.jsx)(o,{className:`mr-2 h-4 w-4`}),`Create Agent`]})]})}),(0,C.jsxs)(`div`,{className:`space-y-4`,children:[(0,C.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Agents`}),a&&(0,C.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading agents...`}),c&&(0,C.jsx)(`div`,{className:`text-center text-destructive`,children:(0,C.jsx)(`p`,{children:c})}),!a&&!c&&n.length===0&&(0,C.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No agents found`}),n.length>0&&(0,C.jsx)(`div`,{className:`grid gap-4`,children:n.map(e=>(0,C.jsx)(w,{agent:e,onStart:ue,onStop:de,onEnter:fe},e.id))})]})]})}export{T as default};
1
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{g as r}from"./chunk-62JRHF6Z-vspAGgtK.js";import{I as i,It as a,Pt as o,Qr as s,Sr as c,rn as l,rt as u}from"./ui-CDoK3F3U.js";import{t as d}from"./button-SeUZ_Pvi.js";import{t as f}from"./input-BOtCd4HP.js";import{n as p}from"./use-toast-BlLDqSUO.js";import{t as m}from"./color-DFEH4BfK.js";import{R as h,Y as g,kt as _,nt as v,tt as y}from"./index-Cp75myNf.js";import{n as b}from"./page-header-DrDt1sQ2.js";import{n as ee,r as x,t as te}from"./useAgentModels-B10Tbl6D.js";import{t as ne}from"./form-panel-3p-ncEVK.js";import{t as re}from"./use-create-panel-DhSNIGtr.js";import{n as ie,t as ae}from"./useSocketSubscription-ifW-vnlb.js";var S=e(n(),1),C=t();function w({agent:e,onStart:t,onStop:n,onEnter:r}){let[o,f]=(0,S.useState)(!1),p=async()=>{f(!0);try{await t(e.name)}finally{f(!1)}},m=async()=>{f(!0);try{await n(e.name)}finally{f(!1)}},h=()=>{switch(e.status){case`active`:return(0,C.jsx)(c,{className:`h-4 w-4 text-success`});case`inactive`:return(0,C.jsx)(c,{className:`h-4 w-4 text-warning`});case`error`:return(0,C.jsx)(c,{className:`h-4 w-4 text-destructive`});default:return(0,C.jsx)(c,{className:`h-4 w-4 text-muted-foreground`})}},g=()=>{switch(e.llmProvider){case`anthropic`:return(0,C.jsx)(s,{className:`h-4 w-4 text-warning`});case`openai`:return(0,C.jsx)(s,{className:`h-4 w-4 text-success`});case`ollama`:return(0,C.jsx)(i,{className:`h-4 w-4 text-info`});default:return(0,C.jsx)(s,{className:`h-4 w-4 text-muted-foreground`})}},_=()=>{switch(e.status){case`active`:return`text-success bg-success-subtle border-success`;case`inactive`:return`text-warning bg-warning-subtle border-warning`;case`error`:return`text-destructive bg-destructive-subtle border-destructive`;case`available`:return`text-info bg-info-subtle border-info`;default:return`text-foreground bg-muted border-border`}},v=e.status===`available`||e.status===`inactive`,y=e.status===`active`;return(0,C.jsxs)(`div`,{className:`border rounded-lg p-4 space-y-4 hover:shadow-elevation-2 transition-shadow bg-card`,children:[(0,C.jsxs)(`div`,{className:`flex items-start justify-between`,children:[(0,C.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,C.jsxs)(`div`,{className:`flex items-center gap-2 mb-1`,children:[g(),(0,C.jsx)(`h3`,{className:`text-lg font-semibold truncate`,children:e.label||e.name}),e.color&&(0,C.jsx)(`div`,{className:`w-4 h-4 rounded border flex-shrink-0`,style:{backgroundColor:e.color},title:`Color: ${e.color}`})]}),(0,C.jsx)(`p`,{className:`text-sm text-muted-foreground font-mono`,children:e.name}),e.description&&(0,C.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1 line-clamp-2`,children:e.description})]}),(0,C.jsxs)(`div`,{className:`flex items-center gap-2 flex-shrink-0`,children:[h(),(0,C.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs font-medium border ${_()}`,children:e.status})]})]}),(0,C.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 text-sm`,children:[(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`span`,{className:`text-muted-foreground`,children:`Provider:`}),(0,C.jsx)(`div`,{className:`font-medium capitalize`,children:e.llmProvider})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`span`,{className:`text-muted-foreground`,children:`Model:`}),(0,C.jsx)(`div`,{className:`font-mono text-xs`,children:e.model})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`span`,{className:`text-muted-foreground`,children:`Created:`}),(0,C.jsx)(`div`,{children:new Date(e.createdAt).toLocaleDateString()})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`span`,{className:`text-muted-foreground`,children:`Last Access:`}),(0,C.jsx)(`div`,{children:e.lastAccessed?new Date(e.lastAccessed).toLocaleDateString():`Never`})]})]}),e.config.mcp?.servers&&e.config.mcp.servers.length>0&&(0,C.jsxs)(`div`,{className:`text-sm`,children:[(0,C.jsx)(`span`,{className:`text-muted-foreground`,children:`MCP Servers:`}),(0,C.jsx)(`div`,{className:`flex flex-wrap gap-1 mt-1`,children:e.config.mcp.servers.map((e,t)=>(0,C.jsx)(`span`,{className:`px-2 py-1 bg-secondary text-secondary-foreground rounded text-xs`,children:e.name},t))})]}),(0,C.jsxs)(`div`,{className:`flex gap-2 pt-2 border-t`,children:[v&&(0,C.jsxs)(d,{onClick:p,disabled:o,size:`sm`,variant:`outline`,className:`flex-1`,children:[(0,C.jsx)(a,{className:`mr-2 h-4 w-4`}),`Start`]}),y&&(0,C.jsxs)(d,{onClick:m,disabled:o,size:`sm`,variant:`outline`,className:`flex-1`,children:[(0,C.jsx)(u,{className:`mr-2 h-4 w-4`}),`Stop`]}),(0,C.jsxs)(d,{onClick:()=>r(e.name),size:`sm`,className:`flex-1`,children:[(0,C.jsx)(l,{className:`mr-2 h-4 w-4`}),`Chat`]})]})]})}function T(){let e={anthropic:`https://api.anthropic.com`,openai:`https://api.openai.com/v1`,ollama:`http://localhost:11434/v1`},t={anthropic:`claude-3-5-sonnet-20241022`,openai:`gpt-4o`,ollama:`qwen2.5-coder:latest`},[n,i]=(0,S.useState)([]),[a,s]=(0,S.useState)(!0),[c,l]=(0,S.useState)(null),[u,T]=(0,S.useState)(``),[E,D]=(0,S.useState)(``),[O,k]=(0,S.useState)(m()),[A,j]=(0,S.useState)(``),[M,oe]=(0,S.useState)(`anthropic`),[N,P]=(0,S.useState)(t.anthropic),[F,I]=(0,S.useState)({apiKey:``,baseUrl:e.anthropic,maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096}),L=te(M,F.apiKey,F.baseUrl),R=L.models.find(e=>e.id===N),[z,B]=(0,S.useState)(``),[V,H]=(0,S.useState)(``),[U,W]=(0,S.useState)(``),[G,K]=(0,S.useState)(``),[q,J]=(0,S.useState)(!1),Y=_(),[X,Z]=re(),{showToast:Q}=p(),se=r(),$=ie();ae($,`agent`,{"agent:status:changed":e=>{i(t=>t.map(t=>t.id===e.agentId?{...t,status:e.status,isActive:e.isActive}:t))},"agent:created":e=>{i(t=>[...t,e.agent])},"agent:deleted":e=>{i(t=>t.filter(t=>t.id!==e.agentId))}});let ce=n=>{oe(n),P(t[n]),I({apiKey:``,baseUrl:e[n],maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096})};(0,S.useEffect)(()=>((async()=>{try{s(!0);let e=await g();i(e),l(null)}catch(e){console.error(`Agent fetch error:`,e);let t=`Failed to fetch agents`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to fetch agents`}l(t),Q({title:`Error`,description:t,variant:`destructive`})}finally{s(!1)}})(),()=>{}),[$,Q]);let le=async t=>{if(t.preventDefault(),u.trim()){J(!0);try{let t=G.trim()||x(z,V,U),n={name:u,label:A||u,description:E||void 0,color:O,llmProvider:M,model:N,apiKey:F.apiKey.trim()||void 0,baseUrl:F.baseUrl.trim()||void 0,config:{type:M,model:N,identity:{role:z.trim()||void 0,identity:V.trim()||void 0,instructions:U.trim()||void 0},prompts:t?{system:t}:void 0,connectors:{[M]:{maxTokens:F.maxTokens,...M===`anthropic`?{}:{temperature:F.temperature},topP:F.topP,frequencyPenalty:F.frequencyPenalty,presencePenalty:F.presencePenalty,...M===`ollama`?{numCtx:F.numCtx}:{}}}},mcp:{enabled:!0,servers:[{name:`weather`,command:`node`,args:[`src/managers/agent/mcp-servers/weather.js`]}]}},r=await h(n);i(e=>[...e,r]),T(``),D(``),k(m()),j(``),K(``),B(``),H(``),W(``),I({apiKey:``,baseUrl:e[M],maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096}),Q({title:`Success`,description:`Agent '${r.label||r.name}' created.`}),Z(!1)}catch(e){console.error(`Agent creation error:`,e);let t=`Failed to create agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to create agent`}Q({title:`Error`,description:t,variant:`destructive`})}finally{J(!1)}}},ue=async e=>{try{let t=await y(e);i(e=>e.map(e=>e.name===t.name?t:e)),Q({title:`Success`,description:`Agent '${t.label||t.name}' started.`})}catch(e){console.error(`Agent start error:`,e);let t=`Failed to start agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to start agent`}Q({title:`Error`,description:t,variant:`destructive`})}},de=async e=>{try{await v(e),i(t=>t.map(t=>t.name===e?{...t,status:`inactive`,isActive:!1}:t)),Q({title:`Success`,description:`Agent '${e}' stopped.`})}catch(e){console.error(`Agent stop error:`,e);let t=`Failed to stop agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to stop agent`}Q({title:`Error`,description:t,variant:`destructive`})}},fe=e=>{se(`/agents/${e}`)};return(0,C.jsxs)(`div`,{className:`space-y-6`,children:[(0,C.jsx)(b,{title:`AI Agents`,description:`Create and manage your AI agents with multiple LLM providers`,actions:!Y.local&&!X&&(0,C.jsxs)(d,{onClick:()=>Z(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create agent`,title:`Create agent`,children:[(0,C.jsx)(o,{className:`h-4 w-4 sm:mr-2`}),(0,C.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Agent`})]})}),!Y.local&&X&&(0,C.jsx)(ne,{title:`Create New Agent`,onClose:()=>Z(!1),children:(0,C.jsxs)(`form`,{onSubmit:le,className:`space-y-4`,children:[(0,C.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,C.jsx)(f,{value:u,onChange:e=>T(e.target.value),placeholder:`Agent Name (e.g., 'my-assistant')`,disabled:q}),(0,C.jsx)(f,{value:A,onChange:e=>j(e.target.value),placeholder:`Agent Label (display name, optional)`,disabled:q})]}),(0,C.jsx)(f,{value:E,onChange:e=>D(e.target.value),placeholder:`Description (optional)`,disabled:q}),(0,C.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`agent-provider`,className:`text-sm font-medium`,children:`LLM Provider`}),(0,C.jsxs)(`select`,{id:`agent-provider`,value:M,onChange:e=>ce(e.target.value),className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring`,disabled:q,children:[(0,C.jsx)(`option`,{value:`anthropic`,children:`Anthropic Claude`}),(0,C.jsx)(`option`,{value:`openai`,children:`OpenAI GPT`}),(0,C.jsx)(`option`,{value:`ollama`,children:`Ollama (Local)`})]})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`agent-model`,className:`text-sm font-medium`,children:`Model`}),(0,C.jsx)(ee,{id:`agent-model`,value:N,onChange:(e,t)=>{P(e),t?.maxTokens&&I(e=>({...e,maxTokens:t.maxTokens}))},...L,disabled:q})]})]}),(0,C.jsxs)(`div`,{className:`space-y-4`,children:[(0,C.jsx)(`h3`,{className:`text-lg font-medium`,children:`Persona`}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`agent-role`,className:`text-sm font-medium`,children:`Role`}),(0,C.jsx)(f,{id:`agent-role`,value:z,onChange:e=>B(e.target.value),placeholder:`e.g. Software Engineer`,disabled:q})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`agent-identity`,className:`text-sm font-medium`,children:`Identity`}),(0,C.jsx)(`textarea`,{id:`agent-identity`,value:V,onChange:e=>H(e.target.value),placeholder:`Who this agent is…`,disabled:q,className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm min-h-[80px] resize-y`})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`agent-instructions`,className:`text-sm font-medium`,children:`Instructions`}),(0,C.jsx)(`textarea`,{id:`agent-instructions`,value:U,onChange:e=>W(e.target.value),placeholder:`Behavioral instructions…`,disabled:q,className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm min-h-[80px] resize-y`})]})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`system-prompt`,className:`text-sm font-medium`,children:`System Prompt (Optional Override)`}),(0,C.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Built from Role, Identity and Instructions unless you enter an override.`}),(0,C.jsx)(`textarea`,{id:`system-prompt`,value:G,onChange:e=>K(e.target.value),placeholder:x(z,V,U)||`System prompt sent to the LLM…`,className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring min-h-[80px] resize-y`,disabled:q})]}),(0,C.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`api-key`,className:`text-sm font-medium`,children:`API Key (Optional)`}),(0,C.jsx)(f,{id:`api-key`,type:`password`,value:F.apiKey,onChange:e=>I(t=>({...t,apiKey:e.target.value})),placeholder:`Enter your API key`,disabled:q})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`baseUrl`,className:`text-sm font-medium`,children:`Base URL (Optional)`}),(0,C.jsx)(f,{id:`baseUrl`,value:F.baseUrl,onChange:e=>I(t=>({...t,baseUrl:e.target.value})),placeholder:e[M],disabled:q})]})]}),(0,C.jsxs)(`div`,{className:`space-y-4`,children:[(0,C.jsx)(`h3`,{className:`text-lg font-medium`,children:`LLM Parameters`}),(0,C.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2 lg:grid-cols-4`,children:[(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`max-tokens`,className:`text-sm font-medium`,children:`Max Output Tokens`}),(0,C.jsx)(f,{id:`max-tokens`,type:`number`,min:`1`,max:R?.maxTokens,value:F.maxTokens,onChange:e=>I(t=>({...t,maxTokens:parseInt(e.target.value)||4096})),disabled:q})]}),M!==`anthropic`&&(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`temperature`,className:`text-sm font-medium`,children:`Temperature`}),(0,C.jsx)(f,{id:`temperature`,type:`number`,min:`0`,max:`2`,step:`0.1`,value:F.temperature,onChange:e=>I(t=>({...t,temperature:Number.isNaN(e.target.valueAsNumber)?.7:e.target.valueAsNumber})),disabled:q})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`top-p`,className:`text-sm font-medium`,children:`Top P`}),(0,C.jsx)(f,{id:`top-p`,type:`number`,min:`0`,max:`1`,step:`0.1`,value:F.topP,onChange:e=>I(t=>({...t,topP:Number.isNaN(e.target.valueAsNumber)?1:e.target.valueAsNumber})),disabled:q})]}),M===`ollama`&&(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`num-ctx`,className:`text-sm font-medium`,children:`Context Length`}),(0,C.jsx)(f,{id:`num-ctx`,type:`number`,min:`1024`,max:R?.contextWindow,value:F.numCtx,onChange:e=>I(t=>({...t,numCtx:parseInt(e.target.value)||4096})),disabled:q})]})]}),M!==`ollama`&&(0,C.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`frequency-penalty`,className:`text-sm font-medium`,children:`Frequency Penalty`}),(0,C.jsx)(f,{id:`frequency-penalty`,type:`number`,min:`-2`,max:`2`,step:`0.1`,value:F.frequencyPenalty,onChange:e=>I(t=>({...t,frequencyPenalty:parseFloat(e.target.value)||0})),disabled:q})]}),(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`label`,{htmlFor:`presence-penalty`,className:`text-sm font-medium`,children:`Presence Penalty`}),(0,C.jsx)(f,{id:`presence-penalty`,type:`number`,min:`-2`,max:`2`,step:`0.1`,value:F.presencePenalty,onChange:e=>I(t=>({...t,presencePenalty:parseFloat(e.target.value)||0})),disabled:q})]})]})]}),(0,C.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,C.jsx)(`label`,{htmlFor:`agent-color`,className:`text-sm font-medium`,children:`Agent Color`}),(0,C.jsx)(f,{id:`agent-color`,type:`color`,value:O,onChange:e=>k(e.target.value),className:`h-10 w-16 p-1`,disabled:q}),(0,C.jsx)(d,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>k(m()),disabled:q,children:`Randomize`})]}),(0,C.jsxs)(d,{type:`submit`,disabled:q||!u.trim(),children:[(0,C.jsx)(o,{className:`mr-2 h-4 w-4`}),`Create Agent`]})]})}),(0,C.jsxs)(`div`,{className:`space-y-4`,children:[(0,C.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Agents`}),a&&(0,C.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading agents...`}),c&&(0,C.jsx)(`div`,{className:`text-center text-destructive`,children:(0,C.jsx)(`p`,{children:c})}),!a&&!c&&n.length===0&&(0,C.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No agents found`}),n.length>0&&(0,C.jsx)(`div`,{className:`grid gap-4`,children:n.map(e=>(0,C.jsx)(w,{agent:e,onStart:ue,onStop:de,onEnter:fe},e.id))})]})]})}export{T as default};