@promptowl/contextnest-community 1.26.0 → 1.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/API.md +34 -1
  2. package/CONFIGURATION.md +32 -1
  3. package/dist/{chunk-TRSGPS27.js → chunk-H3W72HN3.js} +28 -0
  4. package/dist/{chunk-DGPTJXIV.js → chunk-MB52DWWP.js} +4 -4
  5. package/dist/{chunk-IEAWRHMV.js → chunk-NFFUZF2B.js} +23 -2
  6. package/dist/{chunk-PICUHQEM.js → chunk-O3JEI33N.js} +2 -2
  7. package/dist/{chunk-SWA5M5XX.js → chunk-QMQDWRHN.js} +128 -22
  8. package/dist/{chunk-I5EDEZBQ.js → chunk-RXCVXG34.js} +1 -1
  9. package/dist/{chunk-2QOJE7A5.js → chunk-SE5U4J4T.js} +4 -4
  10. package/dist/{chunk-RPGFHESR.js → chunk-VHEMGQ3I.js} +1 -1
  11. package/dist/{chunk-M6PGYMBD.js → chunk-VRLAP4HB.js} +33 -15
  12. package/dist/{engine-QNMFDIBV.js → engine-HLYQLP5T.js} +3 -3
  13. package/dist/{external-edit-service-4MEGPT4D.js → external-edit-service-3DFQ4EZZ.js} +4 -4
  14. package/dist/{grants-service-24GLUBY4.js → grants-service-WICV4Y2J.js} +2 -2
  15. package/dist/index.js +804 -304
  16. package/dist/{invited-user-AM6A3WGO.js → invited-user-XEBX6BM4.js} +3 -3
  17. package/dist/{review-service-2EWN7WWO.js → review-service-GB43UQVH.js} +7 -7
  18. package/dist/{stewardship-service-TDZUC2Q6.js → stewardship-service-KDBPWRZI.js} +4 -4
  19. package/dist/{version-service-C3JTZLJH.js → version-service-JYHFPSYP.js} +8 -4
  20. package/dist/web3/assets/{ActivityTracePage-DzwWIjjx.js → ActivityTracePage-CkRoyIc-.js} +1 -1
  21. package/dist/web3/assets/AgentDocsPage-BTRXmliv.js +1 -0
  22. package/dist/web3/assets/CollaboratorManager-CqJIkvs-.js +1 -0
  23. package/dist/web3/assets/CollaboratorsTab-JcO1P-qm.js +1 -0
  24. package/dist/web3/assets/DocumentEditor-D1GLeeEP.js +36 -0
  25. package/dist/web3/assets/DocumentsTab-BAgSxTX1.js +6 -0
  26. package/dist/web3/assets/ExternalEditsTab-DuuTXZap.js +1 -0
  27. package/dist/web3/assets/{MarkdownEditor-CKh4WSn-.js → MarkdownEditor-BELFww9q.js} +116 -126
  28. package/dist/web3/assets/{NestPageHeader-Cizo8nUi.js → NestPageHeader-Bbje2ncY.js} +1 -1
  29. package/dist/web3/assets/NestView-D4OMXPQ7.js +73 -0
  30. package/dist/web3/assets/OverviewTab-FIDGjR3Q.js +6 -0
  31. package/dist/web3/assets/{PersonCombobox-BKI7dff4.js → PersonCombobox-D52m_jhc.js} +1 -1
  32. package/dist/web3/assets/{ReviewActions-CS8JXgXF.js → ReviewActions-DYqBcWlv.js} +2 -2
  33. package/dist/web3/assets/ReviewTab-DoxfygOb.js +1 -0
  34. package/dist/web3/assets/StewardsTab-CFsYjbEn.js +1 -0
  35. package/dist/web3/assets/{SubmitForReviewModal-Biq3m79i.js → SubmitForReviewModal-AW2OLNAE.js} +1 -1
  36. package/dist/web3/assets/{alert-dialog-BvF3NFr7.js → alert-dialog-p-fBLSWx.js} +2 -2
  37. package/dist/web3/assets/{arrow-left-CWIsv-sG.js → arrow-left-CiErCCTG.js} +1 -1
  38. package/dist/web3/assets/{backlinks-Cqcn7n1J.js → backlinks-DaVSYvhV.js} +2 -2
  39. package/dist/web3/assets/{boxes-ClbgQqG2.js → boxes-VWrCCMzW.js} +1 -1
  40. package/dist/web3/assets/{chevron-left-CK_ZPFm9.js → chevron-left-CsD8gZwL.js} +1 -1
  41. package/dist/web3/assets/{circle-check-Bw_aTXiH.js → circle-check-BBCXd9LI.js} +1 -1
  42. package/dist/web3/assets/{circle-x-DkIG68H7.js → circle-x-C9LsnORQ.js} +1 -1
  43. package/dist/web3/assets/{code-xml-BlR7EN6l.js → code-xml-BaoV7HiQ.js} +1 -1
  44. package/dist/web3/assets/{corner-down-right-DSVxK3tf.js → corner-down-right-DgiTXrtw.js} +1 -1
  45. package/dist/web3/assets/{count-skeleton-DToLM74B.js → count-skeleton-CnEE4uF-.js} +1 -1
  46. package/dist/web3/assets/{earth-BXhVPvCR.js → earth-BmMbVt9k.js} +1 -1
  47. package/dist/web3/assets/{file-exclamation-point-BevGZgtj.js → file-exclamation-point-qJeca9-A.js} +1 -1
  48. package/dist/web3/assets/{folder-input-m8UBV4fA.js → folder-input-D7R93LJ6.js} +1 -1
  49. package/dist/web3/assets/index-DNmWTxN7.css +1 -0
  50. package/dist/web3/assets/index-DvuUIUP6.js +451 -0
  51. package/dist/web3/assets/{page-DzKwP5Ds.js → page-BJQuaTRW.js} +2 -2
  52. package/dist/web3/assets/{page-B6pkc9cd.js → page-Bb8xGOPQ.js} +2 -2
  53. package/dist/web3/assets/{page-Deq6IKiN.js → page-BtM-qDzr.js} +2 -2
  54. package/dist/web3/assets/{page-DPY01SOj.js → page-Bxd0EG25.js} +1 -1
  55. package/dist/web3/assets/page-C3QCO6IR.js +1 -0
  56. package/dist/web3/assets/{page-CptuAPJc.js → page-CfoR0khy.js} +2 -2
  57. package/dist/web3/assets/page-D7Zr5tAI.js +1 -0
  58. package/dist/web3/assets/{page-Dwbp4Seu.js → page-DATSlHCW.js} +2 -2
  59. package/dist/web3/assets/page-DTjPQizZ.js +45 -0
  60. package/dist/web3/assets/{page-Bgy9Ng9p.js → page-DspptlWr.js} +1 -1
  61. package/dist/web3/assets/{page-Dh57L0RG.js → page-I6vAFJOj.js} +4 -4
  62. package/dist/web3/assets/page-QxI4Ud2s.js +9 -0
  63. package/dist/web3/assets/{page-BJrFCKXB.js → page-YcNNg-dX.js} +1 -1
  64. package/dist/web3/assets/page-kM7eO5Kj.js +1 -0
  65. package/dist/web3/assets/{page-title-DVq4qvMR.js → page-title-Dn5jANiU.js} +1 -1
  66. package/dist/web3/assets/{play-CXhS6Pgq.js → play-B2k_Ix-L.js} +1 -1
  67. package/dist/web3/assets/{send-DdfwnIrj.js → send-DPNxv3As.js} +1 -1
  68. package/dist/web3/assets/{settings-DKX0Q4gO.js → settings-DZjq-OQA.js} +1 -1
  69. package/dist/web3/assets/{share-2-CxmXRt58.js → share-2-C-OnE2ru.js} +1 -1
  70. package/dist/web3/assets/{tag-DeYC_mRv.js → tag-CwJl7FdI.js} +1 -1
  71. package/dist/web3/assets/{trash-2-B0HyPTnI.js → trash-2-aljmIff4.js} +1 -1
  72. package/dist/web3/assets/{user-plus-Ckm_Isyc.js → user-plus-DPerZexX.js} +1 -1
  73. package/dist/web3/assets/{zap-D2ifcnYb.js → zap-CHZtiN7P.js} +1 -1
  74. package/dist/web3/index.html +2 -2
  75. package/package.json +6 -2
  76. package/dist/web3/assets/AgentDocsPage-ixP2UdAE.js +0 -1
  77. package/dist/web3/assets/CollaboratorManager-C9VAXZ0h.js +0 -1
  78. package/dist/web3/assets/CollaboratorsTab-tq4ZTexH.js +0 -1
  79. package/dist/web3/assets/DocumentEditor-C2CP2fiE.js +0 -36
  80. package/dist/web3/assets/DocumentsTab-Mh7KxUoB.js +0 -6
  81. package/dist/web3/assets/ExternalEditsTab-B_CWKXZ_.js +0 -1
  82. package/dist/web3/assets/NestView-EW-sraEb.js +0 -73
  83. package/dist/web3/assets/OverviewTab-CjidsMX_.js +0 -6
  84. package/dist/web3/assets/ReviewTab-CwVrXzw5.js +0 -1
  85. package/dist/web3/assets/StewardsTab-C-iP6gnh.js +0 -1
  86. package/dist/web3/assets/index-BOVYgMvj.js +0 -29
  87. package/dist/web3/assets/index-DVnaYqj9.css +0 -1
  88. package/dist/web3/assets/index-WYDmEOfO.js +0 -404
  89. package/dist/web3/assets/page-C2zoxumw.js +0 -1
  90. package/dist/web3/assets/page-CJWO06dN.js +0 -1
  91. package/dist/web3/assets/page-Dea2SblF.js +0 -9
  92. package/dist/web3/assets/page-Dfjg8p7Z.js +0 -1
  93. package/dist/web3/assets/page-YxjrE5b5.js +0 -45
  94. package/dist/web3/assets/x-mNtADYHc.js +0 -6
@@ -1,36 +0,0 @@
1
- import{c as $s,r as n,j as e,A as $e,a as Ee,f as Cs,B as y,L as te,T as bi,b as wi,g as vi,d as ji,I as er,e as Nt,t as yi,h as Ni,i as N,u as Es,k as ki,l as pe,m as tr,n as Rs,o as Si,p as sr,q as ar,s as nr,v as rr,E as Ci,w as ma,R as Is,F as ea,U as Ls,x as Ri,C as Pt,y as ta,D as bt,z as wt,G as vt,H as jt,J as sa,K as yt,M as Ti,N as Fe,O as $i,P as Ei,Q as ha,S as Li,V as Ai,W as bn,X as wn,Y as ir,Z as lr,_ as Di,$ as Mi,a0 as Fi,a1 as Pi,a2 as Vi,a3 as Oi,a4 as zi,a5 as aa,a6 as vn,a7 as qi,a8 as Xs,a9 as jn,aa as yn,ab as _i,ac as Hi,ad as Bi,ae as Wi,af as Ui,ag as Gi,ah as Qi,ai as Ki,aj as Xi,ak as Yi,al as Nn,am as Zi,an as Ji,ao as Ys,ap as Ii,aq as kn,ar as Sn,as as or,at as cr,au as dr,av as ur,aw as mr,ax as es,ay as hr,az as el,aA as tl,aB as sl,aC as al,aD as nl,aE as Cn,aF as rl,aG as il,aH as ll,aI as ol,aJ as Rn,aK as cl,aL as dl,aM as Tn,aN as ul,aO as ml}from"./index-WYDmEOfO.js";import{T as na,p as hl,t as xl,U as fl,a as pl,r as gl,u as bl,b as Zs,l as wl,c as vl,H as jl,O as xr,R as xa,D as ra,d as yl,g as Nl,S as kl,i as Sl,e as fr,m as Cl,Q as $n,f as Rl,h as Tl,W as En,j as $l,k as El,n as Ll,P as Al,o as Dl,M as Ml,q as Fl,L as Pl,F as Vl,s as Ol}from"./MarkdownEditor-CKh4WSn-.js";import{N as pr,C as zl}from"./CollaboratorManager-C9VAXZ0h.js";import{D as gr,H as br,V as wr,e as ia,f as ql,s as _l,i as Hl,S as Bl,P as Wl,r as Ul,A as Gl,u as Ql,d as Kl}from"./backlinks-Cqcn7n1J.js";import{P as Xl}from"./play-CXhS6Pgq.js";import{A as la}from"./arrow-left-CWIsv-sG.js";import{C as ts}from"./code-xml-BlR7EN6l.js";import{M as Ts,R as Yl}from"./ReviewActions-CS8JXgXF.js";import{X as et}from"./x-mNtADYHc.js";import{S as oa}from"./send-DdfwnIrj.js";import{T as ca}from"./trash-2-B0HyPTnI.js";import{S as da}from"./share-2-CxmXRt58.js";import{C as Zl}from"./circle-check-Bw_aTXiH.js";import{C as Jl}from"./corner-down-right-DSVxK3tf.js";import{A as Il,a as eo,b as to,c as so,d as ao,e as no,f as ro,g as io}from"./alert-dialog-BvF3NFr7.js";import{S as lo}from"./SubmitForReviewModal-Biq3m79i.js";import{F as vr}from"./file-exclamation-point-BevGZgtj.js";import{Z as Ln}from"./zap-D2ifcnYb.js";import{F as An}from"./folder-input-m8UBV4fA.js";import"./index-BOVYgMvj.js";import"./PersonCombobox-BKI7dff4.js";import"./user-plus-Ckm_Isyc.js";import"./client-attribution-BraarYaP.js";import"./circle-x-DkIG68H7.js";/**
2
- * @license lucide-react v0.577.0 - ISC
3
- *
4
- * This source code is licensed under the ISC license.
5
- * See the LICENSE file in the root directory of this source tree.
6
- */const oo=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["path",{d:"M11 18H8a2 2 0 0 1-2-2V9",key:"19pyzm"}]],Dn=$s("git-compare",oo);/**
7
- * @license lucide-react v0.577.0 - ISC
8
- *
9
- * This source code is licensed under the ISC license.
10
- * See the LICENSE file in the root directory of this source tree.
11
- */const co=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],jr=$s("message-square-plus",co);/**
12
- * @license lucide-react v0.577.0 - ISC
13
- *
14
- * This source code is licensed under the ISC license.
15
- * See the LICENSE file in the root directory of this source tree.
16
- */const uo=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],Mn=$s("save",uo);/**
17
- * @license lucide-react v0.577.0 - ISC
18
- *
19
- * This source code is licensed under the ISC license.
20
- * See the LICENSE file in the root directory of this source tree.
21
- */const mo=[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]],Fn=$s("undo-2",mo);function ho({nestId:s,nodeId:r,pending:a,onResolved:o}){const[l,u]=n.useState(null),[h,m]=n.useState(!1),[x,f]=n.useState(""),[v,R]=n.useState(null),[j,g]=n.useState(null),w=async()=>{u("approve"),g(null);try{await wi(s,r,a.suggestion_id),o()}catch(D){g(D.message||"Approval failed")}finally{u(null)}},z=async()=>{if(!x.trim()){g("Rejection reason is required");return}u("reject"),g(null);try{await ji(s,r,a.suggestion_id,x.trim()),o()}catch(D){g(D.message||"Rejection failed")}finally{u(null)}},V=async()=>{if(v){R(null);return}u("view"),g(null);try{const{entry:D}=await vi(s,r,a.suggestion_id);R(D)}catch(D){g(D.message||"Failed to load diff")}finally{u(null)}};return e.jsxs($e,{className:"border-orange-300 bg-orange-50 dark:bg-orange-950/30",children:[e.jsx(vr,{className:"h-4 w-4 text-orange-700 dark:text-orange-400"}),e.jsxs(Ee,{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("strong",{className:"text-orange-900 dark:text-orange-200",children:"This file was edited outside the app."})," ",e.jsxs("span",{className:"text-sm text-orange-800/90 dark:text-orange-300/90",children:["Detected ",Cs(a.detected_at)," ·"," ",e.jsx("code",{className:"text-xs",children:a.source}),". The displayed content is the last approved version; the on-disk change is staged for review."]})]}),j&&e.jsx("div",{className:"text-sm text-red-700 dark:text-red-400",children:j}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(y,{size:"sm",onClick:w,disabled:l!==null,"data-testid":"external-edit-approve",children:[l==="approve"?e.jsx(te,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Approve change"]}),e.jsx(y,{size:"sm",variant:"outline",onClick:()=>m(D=>!D),disabled:l!==null,"data-testid":"external-edit-reject-toggle",children:"Reject"}),e.jsxs(y,{size:"sm",variant:"ghost",onClick:V,disabled:l!==null,"data-testid":"external-edit-view-diff",children:[l==="view"?e.jsx(te,{className:"h-4 w-4 mr-2 animate-spin"}):null,v?"Hide diff":"View diff"]})]}),h&&e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsx(bi,{value:x,onChange:D=>f(D.target.value),placeholder:"Reason for rejecting this external edit (required, kept in audit log)",rows:2,"data-testid":"external-edit-reject-reason"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(y,{size:"sm",variant:"destructive",onClick:z,disabled:l!==null||!x.trim(),"data-testid":"external-edit-reject-confirm",children:[l==="reject"?e.jsx(te,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Confirm reject"]}),e.jsx(y,{size:"sm",variant:"ghost",onClick:()=>{m(!1),f("")},disabled:l!==null,children:"Cancel"})]})]}),(v==null?void 0:v.patch)&&e.jsx("div",{className:"pt-2",children:e.jsx(gr,{patch:v.patch})})]})]})}const Ss=40,xo=120,fo=/[^a-zA-Z0-9_:-]+/g,po=s=>s.normalize("NFD").replace(new RegExp("\\p{Diacritic}","gu"),"");function Pn(s,r){const a=new Set(s.map(ua)),o=[];for(const l of r){const u=ua(l);a.has(u)||(a.add(u),o.push(l))}return o}function ua(s){return yr(s).tag??s.trim().toLowerCase()}function yr(s){const r=s.trim().replace(/^#+/,"");if(!r)return{tag:null,note:null};const a=po(r).replace(fo,"").replace(/^[^a-zA-Z]+|[_:-]+$/g,"").toLowerCase();return a?a.length>Ss?{tag:a.slice(0,Ss),note:`Tags are capped at ${Ss} characters — "${r}" was shortened.`}:a!==r.toLowerCase()?{tag:a,note:`"${r}" was adjusted to "${a}".`}:{tag:a,note:null}:{tag:null,note:`"${r}" has no usable characters — a tag starts with a letter and is built from letters a-z, digits, and _ : -`}}function go(s){return s.replace(/[^\s,]+/g,r=>{const a=/^#*/.exec(r)[0];return a+r.slice(a.length,a.length+Ss)})}function bo(s){const{isNew:r,isOwner:a,isAdmin:o,permission:l,nestStewards:u,nodeRoles:h,grant:m,isArchived:x}=s,f=a||o||l==="owner"||l==="admin"||l==="write"||u.some(w=>w.role==="editor"&&w.scope==="nest"),v=o||l==="admin"||h.includes("admin"),R=h.includes("editor")||h.includes("admin"),j=x?!0:r?!f:!(f||m==="write"||R),g=!a&&h.length>0&&!h.includes("editor")&&!v;return{canAuthorNew:f,hasAdminApprove:v,isViewOnly:j,isReviewerOnly:g,canEditContent:!j&&!g}}function Vn(s){const r=[];let a="",o=!1;for(let l=0;l<s.length;l++){const u=s[l];o?u==='"'?s[l+1]==='"'?(a+='"',l++):o=!1:a+=u:u==='"'?o=!0:u===","?(r.push(a),a=""):a+=u}return r.push(a),r.map(l=>l.trim())}function wo({nestId:s,nodeId:r,csv:a}){const[o,l]=n.useState(""),[u,h]=n.useState(null),[m,x]=n.useState(null),[f,v]=n.useState(!1),R=n.useMemo(()=>{const w=a.split(/\r?\n/).filter(D=>D.trim()!==""&&!D.trim().startsWith("#"));if(!w.length)return{header:[],rows:[]};const z=Vn(w[0]),V=w.slice(1).map(Vn);return{header:z,rows:V}},[a]),j=async()=>{v(!0),x(null);try{h(await yi(s,r,o))}catch(w){h(null),x(w instanceof Error?w.message:"Query failed")}finally{v(!1)}},g=u??{columns:R.header.map(w=>w.split(":")[0]),rows:R.rows,matched:R.rows.length,returned:R.rows.length,total:R.rows.length};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(na,{className:"h-4 w-4 text-cyan-500 shrink-0"}),e.jsx(er,{value:o,onChange:w=>l(w.target.value),onKeyDown:w=>w.key==="Enter"&&void j(),placeholder:'where region = "EU" and price > 100 select sku, price limit 5 — empty = all rows',className:"h-8 text-xs font-mono flex-1","data-testid":"table-query-input"}),e.jsxs(y,{size:"sm",className:"h-8",disabled:f,onClick:()=>void j(),children:[e.jsx(Xl,{className:"h-3.5 w-3.5 mr-1"})," Query"]}),u&&e.jsx(y,{size:"sm",variant:"ghost",className:"h-8 text-muted-foreground",onClick:()=>{h(null),x(null)},children:"Show all"})]}),m&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:m}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsxs(Nt,{variant:"secondary",className:"text-[10px]",children:[g.returned," row",g.returned===1?"":"s",u?` of ${g.matched} matching`:""," · ",g.total," total"]}),R.header.filter(w=>w.includes(":")).map(w=>e.jsx(Nt,{variant:"outline",className:"text-[10px] font-mono",children:w},w))]}),e.jsx(fa,{columns:g.columns,rows:g.rows})]})}function fa({columns:s,rows:r,limit:a=500,rowClassName:o}){return e.jsxs("div",{className:"overflow-x-auto rounded-lg border",children:[e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsx("tr",{className:"bg-muted/50 text-left text-muted-foreground",children:s.map(l=>e.jsx("th",{className:"px-3 py-2 font-semibold whitespace-nowrap",children:l},l))})}),e.jsx("tbody",{children:r.slice(0,a).map((l,u)=>e.jsx("tr",{className:`border-t align-top hover:bg-muted/30 ${(o==null?void 0:o(u))??""}`,children:l.map((h,m)=>e.jsx("td",{className:"px-3 py-1.5 whitespace-nowrap font-mono",children:h},m))},u))})]}),r.length>a&&e.jsxs("p",{className:"px-3 py-2 text-[11px] text-muted-foreground border-t",children:["Showing first ",a.toLocaleString()," rows."]})]})}function vo({value:s,onChange:r,onBlur:a,readOnly:o=!1}){const l=n.useRef(null),[u,h]=n.useState(!1),m=o||u,x=n.useMemo(()=>{const j=hl(s,",").filter(g=>!(g[0]??"").trimStart().startsWith("#")&&g.some(w=>w.trim()!==""));return{columns:(j[0]??[]).map(g=>g.split(":")[0].trim()),rows:j.slice(1),issues:xl(j)}},[s]),f=(j,g)=>{const w=s;r(j),N(g,w.trim()?{action:{label:"Undo",onClick:()=>r(w)}}:void 0)},v=async j=>{var w;if(m)return;const g=(w=j.target.files)==null?void 0:w[0];if(j.target.value="",!!g){h(!0);try{const z=N.loading("Processing file…");await new Promise(B=>requestAnimationFrame(()=>requestAnimationFrame(()=>B(null))));const V=await gl(g);if(!V.ok){N.error(bl(V.error,g),{id:z});return}const D=V.delimiter===","?V.text:Zs(V.rows),d=Math.max(0,V.rows.filter(B=>!(B[0]??"").trimStart().startsWith("#")).length-1);N.dismiss(z),f(D,`Table replaced from ${g.name} — ${d.toLocaleString()} data row${d===1?"":"s"}.`)}finally{h(!1)}}},R=j=>{if(m)return;const g=j.clipboardData.getData("text/plain"),w=wl(g);if(w&&w.delimiter!==","){j.preventDefault(),f(Zs(w.rows),`Pasted grid converted to CSV — table body replaced (${w.rows.length.toLocaleString()} rows).`);return}if(w)return;const z=vl(g);if(!z)return;j.preventDefault();const V=j.currentTarget,D=V.selectionStart??s.length,d=V.selectionEnd??D,B=Zs(z.rows);r(s.slice(0,D)+B+s.slice(d));const k=D+B.length;requestAnimationFrame(()=>V.setSelectionRange(k,k))};return e.jsxs("div",{"data-testid":"table-source-editor",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground min-w-0",children:["CSV — header first; directives welcome (",e.jsx("code",{children:"sku:key, price:number"}),"). Pasting a spreadsheet/TSV grid converts it to CSV."]}),e.jsxs(y,{type:"button",variant:"outline",size:"sm",className:"h-7 shrink-0",disabled:m,onClick:()=>{var j;return(j=l.current)==null?void 0:j.click()},"data-testid":"table-source-upload",children:[e.jsx(fl,{className:"h-3.5 w-3.5 mr-1.5"}),"Replace from CSV / TSV"]}),e.jsx("input",{ref:l,type:"file",accept:".csv,.tsv,text/csv,text/tab-separated-values",className:"hidden",onChange:v})]}),e.jsxs("div",{className:x.columns.length>0?"grid gap-3 lg:grid-cols-2":"",children:[e.jsx("textarea",{value:s,onChange:j=>{m||r(j.target.value)},onBlur:a,onPaste:R,readOnly:m,spellCheck:!1,placeholder:`sku:key, price:number, region
22
- OWL-100, 149, EU`,className:"w-full min-h-[360px] border rounded-lg bg-background shadow-sm p-4 font-mono text-sm leading-relaxed resize-y focus:outline-none focus:ring-2 focus:ring-ring","data-testid":"table-source-textarea"}),x.columns.length>0&&e.jsxs("div",{className:"min-w-0","data-testid":"table-source-preview",children:[e.jsxs("p",{className:"mb-1 text-xs font-medium text-muted-foreground",children:["Preview — ",x.rows.length.toLocaleString()," data row",x.rows.length===1?"":"s"]}),x.issues.length>0&&e.jsx("div",{className:"mb-2 rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-900 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-200","data-testid":"table-source-issues",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ni,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("b",{children:[x.issues.length," column",x.issues.length===1?"":"s"," disagree with the header"]})," ","— table-query trusts these types.",e.jsx("ul",{className:"mt-1 list-disc space-y-0.5 pl-4",children:x.issues.slice(0,5).map((j,g)=>e.jsx("li",{children:pl(j)},`${j.column}-${j.kind}-${g}`))})]})]})}),e.jsx(fa,{columns:x.columns,rows:x.rows,limit:50})]})]})]})}const On=250,jo=new Set(["P","DIV","SECTION","ARTICLE","HEADER","FOOTER","LI","TR","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","TABLE","UL","OL","BR","HR"]);function yo(s){if(!s)return"";if(typeof DOMParser>"u")return s.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/gi," ").replace(/<[^>]*>/g," ").replace(/[<>]/g," ").replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
23
-
24
- `).trim();const r=new DOMParser().parseFromString(s,"text/html");if(r.querySelectorAll("script,style,noscript,template").forEach(l=>l.remove()),!r.body.querySelector("*"))return(r.body.textContent||"").replace(/[ \t]+/g," ").replace(/[ \t]+\n/g,`
25
- `).replace(/\n{3,}/g,`
26
-
27
- `).trim();let a="";const o=(l,u)=>{if(l.nodeType===Node.TEXT_NODE){const x=l.textContent||"";a+=u?x:x.replace(/\s+/g," ");return}if(l.nodeType!==Node.ELEMENT_NODE)return;const h=l.tagName,m=jo.has(h);m&&a&&!a.endsWith(`
28
- `)&&(a+=`
29
- `),l.childNodes.forEach(x=>o(x,u||h==="PRE")),m&&!a.endsWith(`
30
- `)&&(a+=`
31
- `)};return o(r.body,!1),a.replace(/[ \t]+\n/g,`
32
- `).replace(/\n{3,}/g,`
33
-
34
- `).trim()}function No(s,r,a){if(r<0||a>s.length||r>=a)return null;const o=s.slice(r,a).trim();return o?{quote:o,before:s.slice(Math.max(0,r-On),r),after:s.slice(a,a+On),line:s.slice(0,r).split(`
35
- `).length}:null}const ko="artifact";function So(s){return(s==null?void 0:s.replace("T"," ").replace(/\.\d+Z?$/,"").slice(0,16))||s}function Co({nestId:s,nodeId:r,title:a,snapshotVersion:o,currentEmail:l,viewOnly:u=!1,reviewerOnly:h=!1,initialThreadId:m,onBack:x,onTurnedInto:f,actions:v,visibilityControl:R,onShareNest:j}){var Ae;const[g,w]=n.useState("preview"),[z,V]=n.useState(!!m);n.useEffect(()=>{g==="annotate"&&V(!0)},[g]);const[D,d]=n.useState(!1),[B,k]=n.useState(!1),Y=async()=>{k(!0);try{await Rs(s,r,{type:"document"}),N.success("Turned into a document"),d(!1),f==null||f()}catch(c){N.error(c instanceof Error?c.message:"Failed to convert")}finally{k(!1)}},ae=Es(),[ne,S]=n.useState([]),[F,Z]=n.useState(!0),[ce,Ne]=n.useState(""),[tt,ke]=n.useState(null),kt=tt==null||/^s*</.test(tt),[Qe,b]=n.useState(!1),[M,J]=n.useState(o??null),[Ke,Pe]=n.useState(0),[ss,st]=n.useState(!1),[St,as]=n.useState(null),[de,C]=n.useState(null),[Se,Ce]=n.useState(null),[Ve,$]=n.useState(!1),[q,W]=n.useState(null),[Oe,ge]=n.useState(!1),[Re,re]=n.useState(""),[Xe,at]=n.useState(!1),Vt=!u,ue=!u&&!h,nt=(q==null?void 0:q.status)==="pending_review",be=q!=null&&Re!==q.content,Ot=nt||St!=null&&((Ae=St.versions.find(c=>c.version===St.currentVersion))==null?void 0:Ae.status)==="pending_review",[U,ze]=n.useState(null),[Ct,zt]=n.useState(""),[I,qt]=n.useState(!1),[Rt,rt]=n.useState(null),[Le,qe]=n.useState(""),_e=n.useRef(null),_t=ki(s,r,de??M,Ke),ie=n.useCallback(async()=>{try{as(await ae.fetchQuery(pe.nodeVersions(s,r)))}catch(c){as(null),N.error((c==null?void 0:c.message)||"Failed to load version history")}},[s,r]),Te=n.useCallback(c=>{if(g==="edit"&&be){if(!window.confirm("Discard unsaved source changes?"))return;q&&re(q.content)}c()},[g,be,q]),He=n.useCallback(()=>{Te(()=>{st(!0),ie()})},[Te,ie]);n.useEffect(()=>{if(!be)return;const c=E=>{E.preventDefault(),E.returnValue=""};return window.addEventListener("beforeunload",c),()=>window.removeEventListener("beforeunload",c)},[be]);const As=n.useCallback(c=>{Te(()=>{st(!1),C(c),w("preview"),Ne(""),ke(null),Pe(E=>E+1)})},[Te]),Tt=n.useCallback(()=>{C(null),Ne(""),ke(null),Pe(c=>c+1)},[]),$t=n.useCallback(async c=>{await tr(s,r,c),N.success(`Restored from version ${c}`),C(null),st(!1),w("preview"),J(null),Ne(""),ke(null),W(null),re(""),Pe(E=>E+1),await ie()},[s,r,ie]),it=n.useCallback(async()=>{if(Se!=null){$(!0);try{await $t(Se),Ce(null)}catch(c){N.error((c==null?void 0:c.message)||"Restore failed")}finally{$(!1)}}},[Se,$t]),Ds=n.useCallback(async()=>{if(C(null),w("edit"),!(q||Oe)){ge(!0);try{const{node:c}=await ae.fetchQuery(pe.node(s,r)),E=(c==null?void 0:c.content)==null?"":String(c.content);W({content:E,version:c==null?void 0:c.version,status:(c==null?void 0:c.status)??null}),re(E)}catch(c){N.error((c==null?void 0:c.message)||"Failed to load artifact source"),w("preview")}finally{ge(!1)}}},[q,Oe,s,r]),ns=n.useCallback(async()=>{var c,E;if(!(!q||!be||Xe)){at(!0);try{const P=await Rs(s,r,{content:Re},q.version),H=(P==null?void 0:P.version)??((c=P==null?void 0:P.node)==null?void 0:c.version);W({content:Re,version:typeof H=="number"?H:q.version,status:((E=P==null?void 0:P.node)==null?void 0:E.status)??q.status}),J(null),Ne(""),ke(null),Pe(Lt=>Lt+1),w("preview"),N.success(typeof H=="number"?`Saved as version ${H}`:"Artifact saved")}catch(P){N.error((P==null?void 0:P.message)||"Save failed")}finally{at(!1)}}},[q,be,Xe,s,r,Re]),rs=n.useCallback(()=>{Te(()=>w("preview"))},[Te]),we=n.useCallback(async()=>{Z(!0);try{const{threads:c}=await ae.fetchQuery(pe.nodeAnnotations(s,r));S(c)}catch(c){N.error((c==null?void 0:c.message)||"Failed to load annotations")}finally{Z(!1)}},[s,r]);n.useEffect(()=>{we()},[we]);const is=n.useRef(!1);n.useEffect(()=>{!m||is.current||F||ne.some(c=>c.id===m)&&(is.current=!0,requestAnimationFrame(()=>{var c;(c=document.getElementById(`annotation-thread-${m}`))==null||c.scrollIntoView({behavior:"smooth",block:"center"})}))},[ne,F,m]);const lt=n.useCallback(async()=>{if(!(ce||Qe)){b(!0);try{const{html:c,snapshot:E}=await Si(s,r,de??M,Ke);Ne(yo(c)),ke(c),E!=null&&de==null&&J(E)}catch(c){N.error((c==null?void 0:c.message)||"Failed to load artifact text")}finally{b(!1)}}},[ce,Qe,s,r,M,de,Ke]);n.useEffect(()=>{(g==="annotate"||g==="preview")&&lt()},[g,lt]);const Ht=n.useCallback(()=>{const c=window.getSelection(),E=_e.current;if(!c||c.isCollapsed||!E){ze(null);return}const P=c.getRangeAt(0);if(!E.contains(P.startContainer)||!E.contains(P.endContainer))return;const H=Math.min(P.startOffset,P.endOffset),Lt=Math.max(P.startOffset,P.endOffset),ls=ce.slice(H,Lt).trim();if(!ls){ze(null);return}ze({start:H,end:Lt,quote:ls})},[ce]),Et=n.useCallback(async()=>{var E,P;const c=Ct.trim();if(c){qt(!0);try{const H=U!=null?No(ce,U.start,U.end):null;await sr(s,r,{body:c,anchor:H,snapshotVersion:M}),zt(""),ze(null),(P=(E=window.getSelection)==null?void 0:E.call(window))==null||P.removeAllRanges(),await we(),N.success("Comment added")}catch(H){N.error((H==null?void 0:H.message)||"Failed to add comment")}finally{qt(!1)}}},[Ct,U,ce,s,r,M,we]),ve=n.useCallback(async c=>{const E=Le.trim();if(E)try{await ar(s,r,c,E),qe(""),rt(null),await we()}catch(P){N.error((P==null?void 0:P.message)||"Failed to reply")}},[Le,s,r,we]),Bt=n.useCallback(async c=>{try{c.status==="open"?await nr(s,r,c.id):await rr(s,r,c.id),await we()}catch(E){N.error((E==null?void 0:E.message)||"Failed to update thread")}},[s,r,we]),{openThreads:ee,resolvedThreads:G}=n.useMemo(()=>{const c=ne.filter(P=>P.status==="open"),E=ne.filter(P=>P.status==="resolved");return{openThreads:c,resolvedThreads:E}},[ne]);return e.jsxs("div",{className:"flex min-h-full flex-col",children:[e.jsxs("div",{className:"sticky top-16 z-30 flex h-12 items-center justify-between gap-3 border-b bg-background/95 px-2 backdrop-blur supports-[backdrop-filter]:bg-background/80 sm:px-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(y,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Te(x),children:e.jsx(la,{className:"h-4 w-4"})}),e.jsx("h1",{className:"text-sm font-medium truncate",children:a||r}),e.jsx(Nt,{variant:"secondary",className:"shrink-0 gap-1",children:"Artifact"}),de!=null?e.jsxs(Nt,{variant:"outline",className:"shrink-0 border-amber-300 bg-amber-50 text-amber-800",title:"Read-only view of a historical version.",children:["Viewing v",de]}):M!=null?e.jsxs(Nt,{variant:"outline",className:"shrink-0",title:"Annotations are anchored to this frozen snapshot.",children:["Snapshot v",M]}):null]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("div",{className:"flex items-center rounded-md border h-9",children:[e.jsxs("button",{type:"button",className:`px-3 h-full rounded-l-md inline-flex items-center gap-1.5 text-sm ${g==="preview"?"bg-muted":"hover:bg-muted/50"}`,onClick:()=>Te(()=>w("preview")),children:[e.jsx(Ci,{className:"h-4 w-4"})," Preview"]}),e.jsxs("button",{type:"button",className:ma("px-3 h-full inline-flex items-center gap-1.5 text-sm disabled:opacity-50",!ue&&"rounded-r-md",g==="annotate"?"bg-muted":"hover:bg-muted/50"),disabled:de!=null,title:de!=null?"Return to the current version to annotate":void 0,onClick:()=>Te(()=>w("annotate")),children:[e.jsx(jl,{className:"h-4 w-4"})," Annotate"]}),ue&&e.jsxs("button",{type:"button",className:`px-3 h-full rounded-r-md inline-flex items-center gap-1.5 text-sm ${g==="edit"?"bg-muted":"hover:bg-muted/50"}`,title:"Edit the artifact's raw HTML source",onClick:()=>void Ds(),children:[e.jsx(ts,{className:"h-4 w-4"})," Edit source"]})]}),e.jsx(y,{variant:"outline",size:"icon",title:"Version history",onClick:He,children:e.jsx(br,{className:"h-4 w-4"})}),e.jsx(y,{variant:"outline",size:"icon",title:"Reload artifact",onClick:()=>Pe(c=>c+1),children:e.jsx(Is,{className:"h-4 w-4"})}),!u&&!h&&f&&e.jsx(y,{variant:"outline",size:"icon",title:be?"Save or discard the source edits first":"Turn into a document",disabled:be,onClick:()=>d(!0),"data-testid":"artifact-turn-into-document",children:e.jsx(ea,{className:"h-4 w-4"})}),R,j&&e.jsx(y,{variant:"outline",size:"icon",title:"Share this nest — people, teams, visibility",onClick:j,"data-testid":"artifact-share-nest",children:e.jsx(Ls,{className:"h-4 w-4"})}),e.jsxs(y,{variant:z?"secondary":"outline",size:"icon",title:z?"Hide annotations":"Show annotations","aria-pressed":z,onClick:()=>V(c=>!c),"data-testid":"artifact-comments-toggle",className:"relative",children:[e.jsx(Ts,{className:"h-4 w-4"}),ee.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 rounded-full bg-primary px-1 text-[10px] font-semibold leading-4 text-primary-foreground",children:ee.length})]}),e.jsx("a",{href:_t,target:"_blank",rel:"noopener noreferrer",children:e.jsx(y,{variant:"outline",size:"icon",title:"Open in new tab",children:e.jsx(Ri,{className:"h-4 w-4"})})}),v&&v.length>0&&e.jsx(xr,{actions:v,variant:"outline",testId:"artifact-viewer-more"})]})]}),e.jsxs("div",{className:"flex flex-1 flex-col items-stretch lg:flex-row lg:items-start",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col px-5 py-6 sm:px-10 sm:py-8 min-h-[calc(100vh-7rem)]",children:[de!=null&&e.jsxs("div",{className:"px-3 py-2 border-b bg-amber-50 text-xs text-amber-900 flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium",children:["Viewing version ",de]})," ","— read-only historical snapshot."]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[Vt&&e.jsxs(y,{size:"sm",variant:"outline",className:"h-6 px-2 text-xs border-amber-300 text-amber-900 hover:bg-amber-100",disabled:Ot,title:Ot?"Locked while awaiting steward review — resolve the review first":void 0,onClick:()=>Ce(de),children:[e.jsx(xa,{className:"h-3 w-3 mr-1"}),Ot?"Locked — review pending":"Restore this version"]}),e.jsxs(y,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-amber-900 hover:bg-amber-100",onClick:Tt,children:[e.jsx(et,{className:"h-3 w-3 mr-1"})," Back to current"]})]})]}),g==="edit"?e.jsxs("div",{className:"flex-1 flex flex-col",children:[e.jsx("div",{className:"mb-3 text-xs text-muted-foreground",children:nt?"Locked while awaiting steward review — resolve the review before editing.":"Editing raw HTML source. Saving creates a new version, like any document edit."}),Oe?e.jsxs("div",{className:"flex items-center justify-center flex-1 text-muted-foreground",children:[e.jsx(te,{className:"h-5 w-5 animate-spin mr-2"})," Loading source…"]}):e.jsxs(e.Fragment,{children:[e.jsx("textarea",{value:Re,onChange:c=>re(c.target.value),readOnly:nt,spellCheck:!1,placeholder:"Paste the artifact's HTML (a self-contained slide deck, dashboard, infographic)…",className:"flex-1 w-full min-h-[60vh] rounded-lg border bg-background p-4 font-mono text-sm leading-relaxed resize-y shadow-sm focus:outline-none focus:ring-2 focus:ring-ring"}),e.jsxs("div",{className:"sticky bottom-0 z-20 mt-auto -mx-5 flex items-center justify-between gap-2 border-t bg-background/95 px-4 py-2 backdrop-blur supports-[backdrop-filter]:bg-background/80 sm:-mx-10",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(q==null?void 0:q.version)!=null?`Editing v${q.version}`:"",be?" · unsaved changes":""]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(y,{variant:"ghost",size:"sm",onClick:rs,disabled:Xe,children:"Cancel"}),e.jsxs(y,{size:"sm",onClick:()=>void ns(),disabled:nt||Xe||!be||!Re.trim(),title:nt?"Locked while awaiting steward review":void 0,children:[Xe?e.jsx(te,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Pt,{className:"h-4 w-4 mr-1.5"}),"Save"]})]})]})]})]}):g==="preview"&&!kt?e.jsx(ra,{content:tt??"",className:"flex-1 min-h-[70vh] max-h-none overflow-visible rounded-lg border bg-background"}):g==="preview"?e.jsx("iframe",{src:_t,title:a||r,sandbox:"allow-scripts allow-popups allow-modals",className:"w-full flex-1 min-h-[70vh] rounded-lg border bg-white"},Ke):e.jsxs("div",{className:"flex-1 flex flex-col min-h-[70vh] rounded-lg border bg-background",children:[e.jsx("div",{className:"px-3 py-2 border-b bg-muted/30 text-xs text-muted-foreground",children:"Select text below to anchor a comment to it. This is the artifact's extracted text — the same text the nest indexes."}),Qe?e.jsxs("div",{className:"flex items-center justify-center flex-1 text-muted-foreground",children:[e.jsx(te,{className:"h-5 w-5 animate-spin mr-2"})," Loading text…"]}):e.jsx("pre",{ref:_e,onMouseUp:Ht,className:"flex-1 overflow-auto whitespace-pre-wrap break-words p-4 text-sm leading-relaxed font-sans selection:bg-amber-200",children:ce||"(no extractable text)"})]})]}),e.jsxs("aside",{className:`w-full shrink-0 border-t lg:w-80 lg:border-t-0 lg:border-l lg:sticky lg:top-28 lg:self-start lg:max-h-[calc(100vh-7rem)] flex flex-col min-h-0 max-h-[70vh]${z?"":" hidden"}`,"data-testid":"artifact-comments-rail","aria-hidden":!z,children:[e.jsxs("div",{className:"px-3 py-2 border-b flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium",children:["Annotations",e.jsxs("span",{className:"text-muted-foreground font-normal",children:[" ","· ",ee.length," open"]})]}),e.jsx(y,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Refresh",onClick:we,children:e.jsx(Is,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"p-3 border-b space-y-2",children:[U?e.jsxs("div",{className:"text-xs rounded border-l-2 border-amber-400 bg-amber-50 px-2 py-1 text-amber-900",children:[e.jsx("span",{className:"font-medium",children:"Anchored to:"})," ",'"',U.quote.length>80?U.quote.slice(0,80)+"…":U.quote,'"',e.jsx("button",{type:"button",className:"ml-2 underline text-amber-700",onClick:()=>{var c,E;ze(null),(E=(c=window.getSelection)==null?void 0:c.call(window))==null||E.removeAllRanges()},children:"clear"})]}):e.jsx("div",{className:"text-xs text-muted-foreground",children:g==="annotate"?"No selection — this will be a whole-artifact comment.":"Switch to Annotate to highlight text, or comment on the whole artifact below."}),e.jsx("textarea",{value:Ct,onChange:c=>zt(c.target.value),placeholder:"Add a comment…",rows:3,className:"w-full text-sm rounded border px-2 py-1.5 resize-y focus:outline-none focus:ring-1 focus:ring-primary"}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(y,{size:"sm",onClick:Et,disabled:I||!Ct.trim(),children:[I?e.jsx(te,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(jr,{className:"h-4 w-4 mr-1.5"}),"Comment"]})})]}),e.jsx("div",{className:"flex-1 overflow-auto p-3 space-y-3",children:F?e.jsxs("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:[e.jsx(te,{className:"h-4 w-4 animate-spin mr-2"})," Loading…"]}):ne.length===0?e.jsx("div",{className:"text-sm text-muted-foreground text-center py-8",children:"No annotations yet. Highlight text and leave the first comment."}):e.jsxs(e.Fragment,{children:[ee.map(c=>e.jsx(zn,{thread:c,currentEmail:l,replyOpen:Rt===c.id,replyBody:Le,onReplyOpen:()=>{rt(c.id),qe("")},onReplyChange:qe,onReplySubmit:()=>ve(c.id),onToggleResolved:()=>Bt(c)},c.id)),G.length>0&&e.jsx("div",{className:"pt-2 text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Resolved"}),G.map(c=>e.jsx(zn,{thread:c,currentEmail:l,replyOpen:Rt===c.id,replyBody:Le,onReplyOpen:()=>{rt(c.id),qe("")},onReplyChange:qe,onReplySubmit:()=>ve(c.id),onToggleResolved:()=>Bt(c)},c.id))]})})]})]}),ss&&e.jsx(wr,{open:!0,onClose:()=>st(!1),title:a||r,versionData:St,previewAs:"source",onView:As,onLoadContent:async c=>(await ta(s,r,c)).content,onRestore:Vt?async c=>{try{await $t(c)}catch(E){N.error((E==null?void 0:E.message)||"Restore failed")}}:void 0}),e.jsx(bt,{open:D,onOpenChange:c=>{B||d(c)},children:e.jsxs(wt,{className:"sm:max-w-[440px]",children:[e.jsxs(vt,{children:[e.jsx(jt,{children:"Turn into a document?"}),e.jsx(sa,{children:"The HTML stays as the body, opened in the markdown editor's source view for you to rework. It stops being hosted as a page until it is turned back into an artifact."})]}),e.jsxs(yt,{children:[e.jsx(y,{variant:"outline",onClick:()=>d(!1),disabled:B,children:"Cancel"}),e.jsxs(y,{onClick:()=>void Y(),disabled:B,"data-testid":"artifact-turn-into-confirm",children:[B?e.jsx(te,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Turn into document"]})]})]})}),e.jsx(bt,{open:Se!=null,onOpenChange:c=>!c&&Ce(null),children:e.jsxs(wt,{children:[e.jsxs(vt,{children:[e.jsxs(jt,{children:["Restore version ",Se,"?"]}),e.jsxs(sa,{children:["This writes version ",Se,"'s HTML as a new version through the normal save path — review rules still apply and the current content stays in history."]})]}),e.jsxs(yt,{children:[e.jsx(y,{variant:"outline",onClick:()=>Ce(null),disabled:Ve,children:"Cancel"}),e.jsx(y,{onClick:()=>void it(),disabled:Ve,children:Ve?"Restoring…":"Restore"})]})]})})]})}function zn({thread:s,replyOpen:r,replyBody:a,onReplyOpen:o,onReplyChange:l,onReplySubmit:u,onToggleResolved:h}){const m=s.status==="resolved";return e.jsxs("div",{id:`annotation-thread-${s.id}`,className:`rounded-lg border p-2.5 text-sm ${m?"bg-muted/40 opacity-80":"bg-background"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx(Nt,{variant:"outline",className:m?"border-emerald-200 bg-emerald-50 text-emerald-700":"border-amber-200 bg-amber-50 text-amber-700",children:m?"Resolved":"Open"}),e.jsx("button",{type:"button",className:"text-xs inline-flex items-center gap-1 text-muted-foreground hover:text-foreground",onClick:h,title:m?"Reopen thread":"Mark resolved",children:m?e.jsxs(e.Fragment,{children:[e.jsx(xa,{className:"h-3 w-3"})," Reopen"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pt,{className:"h-3 w-3"})," Resolve"]})})]}),s.anchor?e.jsxs("div",{className:"mb-1.5 text-xs rounded border-l-2 border-amber-300 bg-amber-50/60 px-2 py-1 text-amber-900",children:['"',s.anchor.quote.length>100?s.anchor.quote.slice(0,100)+"…":s.anchor.quote,'"']}):e.jsx("div",{className:"mb-1.5 text-xs text-muted-foreground italic",children:"Whole-artifact comment"}),e.jsx("ul",{className:"space-y-1.5",children:s.comments.map(x=>e.jsxs("li",{children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"font-medium text-xs",children:x.author}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:So(x.createdAt)})]}),e.jsx("div",{className:"whitespace-pre-wrap break-words",children:x.body})]},x.id))}),r?e.jsxs("div",{className:"mt-2 space-y-1.5",children:[e.jsx("textarea",{value:a,onChange:x=>l(x.target.value),placeholder:"Reply…",rows:2,className:"w-full text-sm rounded border px-2 py-1 resize-y focus:outline-none focus:ring-1 focus:ring-primary",autoFocus:!0}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(y,{size:"sm",onClick:u,disabled:!a.trim(),children:[e.jsx(oa,{className:"h-3.5 w-3.5 mr-1.5"})," Reply"]})})]}):e.jsx("button",{type:"button",className:"mt-1.5 text-xs text-primary hover:underline",onClick:o,children:"Reply"})]})}const Ro=yl(Nl);function Nr(s){return s.map((r,a)=>{var l;if(r.type==="text")return r.value;const o=(((l=r.properties)==null?void 0:l.className)??[]).join(" ");return e.jsx("span",{className:o,children:Nr(r.children??[])},a)})}function qn({code:s,className:r="",...a}){const o=n.useMemo(()=>{if(!s.trim())return null;try{return Nr(Ro.highlightAuto(s).children)}catch{return null}},[s]);return e.jsx("pre",{className:`overflow-x-auto p-4 font-mono text-xs leading-relaxed whitespace-pre ${r}`,...a,children:e.jsx("code",{children:o??s})})}function To({nestId:s,onChanged:r}){const[a,o]=n.useState([]),[l,u]=n.useState([]),[h,m]=n.useState(""),[x,f]=n.useState(!0),v=Es(),[R,j]=n.useState(!1),[g,w]=n.useState(null),z=async()=>{f(!0),w(null);try{const[k,Y]=await Promise.all([v.fetchQuery(pe.nestTeams(s)),v.fetchQuery(pe.teamList()).catch(()=>({teams:[]}))]);o(k.teams),u(Y.teams)}catch(k){w((k==null?void 0:k.message)||"Failed to load teams")}finally{f(!1)}};n.useEffect(()=>{z()},[s]);const V=new Set(a.map(k=>k.teamId)),D=l.filter(k=>!V.has(k.id)),d=async()=>{if(h){j(!0);try{await Ei(s,h),m(""),N.success("Team shared"),await z(),r()}catch(k){N.error((k==null?void 0:k.message)||"Failed to share team")}finally{j(!1)}}},B=async(k,Y)=>{j(!0);try{await $i(s,k),N.success(`"${Y}" unshared`),await z(),r()}catch(ae){N.error((ae==null?void 0:ae.message)||"Failed to unshare team")}finally{j(!1)}};return e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsxs(Ti,{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Ls,{className:"h-4 w-4"}),"Teams"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Share a whole team at once. Each member gets the role you gave them on the Teams page. Manage members there."}),g&&e.jsxs($e,{variant:"destructive",children:[e.jsx(Fe,{className:"h-4 w-4"}),e.jsx(Ee,{children:g})]}),x?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx(te,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[a.length>0&&e.jsx("div",{className:"space-y-2",children:a.map(k=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm flex-1 truncate",children:k.teamName}),e.jsxs(Nt,{variant:"secondary",children:[k.members.length," member",k.members.length===1?"":"s"]}),e.jsx(y,{size:"icon",variant:"ghost",className:"h-8 w-8",disabled:R,onClick:()=>B(k.teamId,k.teamName),"aria-label":`Unshare ${k.teamName}`,children:e.jsx(ca,{className:"h-3.5 w-3.5"})})]},k.teamId))}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx("div",{className:"flex-1",children:e.jsx(kl,{value:h,onChange:m,options:D.map(k=>({value:k.id,label:k.name})),disabled:D.length===0,placeholder:D.length===0?"No more teams to share":"Select a team…",searchPlaceholder:"Search teams…",emptyText:"No teams match.",testId:"team-share-select"})}),e.jsxs(y,{size:"sm",onClick:d,disabled:R||!h,children:[e.jsx(da,{className:"h-4 w-4 mr-1"}),"Share"]})]})]})]})}function $o({nestId:s,nestName:r,onClose:a,onChanged:o,stewardshipEnabled:l=!1}){var f,v;const{adminStatus:u}=ha(),h=((v=(f=u==null?void 0:u.me)==null?void 0:f.email)==null?void 0:v.toLowerCase())??"",[m,x]=n.useState(null);return e.jsx(bt,{open:!0,onOpenChange:a,children:e.jsxs(wt,{className:"sm:max-w-[560px]",children:[e.jsxs(vt,{children:[e.jsxs(jt,{className:"flex items-center gap-2",children:[e.jsx(Ls,{className:"h-4 w-4"}),"Share nest: ",r]}),e.jsxs(sa,{children:["Sharing applies to the ",e.jsx("strong",{children:"whole nest"})," — every document in it. Sharing grants plain access; it does not make anyone a steward."," ",l?e.jsx(e.Fragment,{children:"To restrict who can touch an individual document, assign stewards on the nest's Stewards tab instead."}):e.jsx(e.Fragment,{children:"Per-document control comes from stewards, which need Stewardship & Approval Workflow turned on in Nest settings."})]})]}),e.jsxs("div",{className:"space-y-4 py-1",children:[m&&e.jsxs($e,{variant:"destructive",children:[e.jsx(Fe,{className:"h-4 w-4"}),e.jsx(Ee,{children:m})]}),e.jsx(pr,{nestId:s,onChanged:o,onError:x}),e.jsxs(Li,{defaultValue:"people",children:[e.jsxs(Ai,{className:"grid grid-cols-2 w-full",children:[e.jsx(bn,{value:"people",children:"People"}),e.jsx(bn,{value:"teams",children:"Teams"})]}),e.jsx(wn,{value:"people",className:"mt-3 max-h-[52vh] overflow-y-auto pr-1",children:e.jsx(zl,{nestId:s,nestName:r,onChanged:o,currentUserEmail:h})}),e.jsx(wn,{value:"teams",className:"mt-3 max-h-[52vh] overflow-y-auto pr-1",children:e.jsx(To,{nestId:s,onChanged:o})})]})]}),e.jsx(yt,{children:e.jsx(y,{variant:"outline",onClick:a,children:"Done"})})]})})}function Eo(s,r,a){const o=s.slice(0,r),l=fr(o);if(!l||l.kind!=="mention")return null;const u=r-l.length,h=`@${a} `,m=s.slice(r),x=m.startsWith(" ")?m.slice(1):m;return{value:s.slice(0,u)+h+x,caret:u+h.length}}const _n=/((?:```[\s\S]*?```)|(?:`[^`\n]*`))|(?:(^|\s)@(?:\(([^)]+)\)|([a-zA-Z0-9._@-]+)))/g;function Lo(s,r){const a=[],o=s||"",l=r.length>0;let u=0;const h=x=>{if(!x)return;const f=a[a.length-1];(f==null?void 0:f.kind)==="text"?f.text+=x:a.push({kind:"text",text:x})};_n.lastIndex=0;let m;for(;(m=_n.exec(o))!==null;){const[x,f,v,R,j]=m;if(f){h(o.slice(u,m.index+x.length)),u=m.index+x.length;continue}const g=(R||j||"").trim(),w=m.index+(v?v.length:0);h(o.slice(u,w)),a.push({kind:"mention",text:o.slice(w,m.index+x.length),name:g,resolved:!l||Sl(r,g)}),u=m.index+x.length}return h(o.slice(u)),a}const Hn=n.forwardRef(function({value:r,onValueChange:a,members:o,className:l,onKeyDown:u,...h},m){var Y,ae,ne;const x=n.useRef(null),[f,v]=n.useState(0),[R,j]=n.useState(!1),[g,w]=n.useState(0),z=S=>{x.current=S,typeof m=="function"?m(S):m&&(m.current=S)},V=n.useMemo(()=>{if(!R)return null;const S=fr(r.slice(0,f));return(S==null?void 0:S.kind)==="mention"?S:null},[R,r,f]),D=(ne=(ae=(Y=ha().adminStatus)==null?void 0:Y.me)==null?void 0:ae.email)==null?void 0:ne.toLowerCase(),d=n.useMemo(()=>V?Cl(o.filter(S=>S.email.toLowerCase()!==D),V.query):[],[V,o,D]);n.useEffect(()=>w(0),[V==null?void 0:V.query,d.length]);const B=S=>{const F=x.current,Z=Eo(r,f,S);Z&&(a(Z.value),j(!1),requestAnimationFrame(()=>{F&&(F.focus(),F.setSelectionRange(Z.caret,Z.caret),v(Z.caret))}))},k=!!V&&d.length>0;return e.jsxs("div",{className:"relative",children:[e.jsx("textarea",{...h,ref:z,value:r,className:l,onChange:S=>{a(S.target.value),v(S.target.selectionStart??S.target.value.length),j(!0)},onKeyUp:S=>v(S.target.selectionStart??0),onPaste:S=>{const F=S.currentTarget;requestAnimationFrame(()=>v(F.selectionStart??0))},onClick:S=>v(S.target.selectionStart??0),onBlur:()=>j(!1),onKeyDown:S=>{if(k){if(S.key==="ArrowDown"){S.preventDefault(),w(F=>(F+1)%d.length);return}if(S.key==="ArrowUp"){S.preventDefault(),w(F=>F<=0?d.length-1:F-1);return}if(S.key==="Enter"||S.key==="Tab"){S.preventDefault();const F=d[g]??d[0];F&&B(F.email);return}if(S.key==="Escape"){S.stopPropagation(),j(!1);return}}u==null||u(S)}}),k&&e.jsx("ul",{role:"listbox",className:"absolute left-0 right-0 top-full z-50 mt-1 max-h-48 overflow-auto rounded-md border bg-popover py-1 text-popover-foreground shadow-md","data-testid":"mention-picker",children:d.map((S,F)=>e.jsx("li",{children:e.jsxs("button",{type:"button",role:"option","aria-selected":F===g,onMouseDown:Z=>{Z.preventDefault(),B(S.email)},onMouseEnter:()=>w(F),className:ma("flex w-full flex-col items-start px-3 py-1.5 text-left text-sm",F===g?"bg-accent text-accent-foreground":""),children:[e.jsx("span",{className:"truncate font-medium",children:S.name||S.email.split("@")[0]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:S.email})]})},S.email))})]})});function Bn({body:s,members:r,className:a}){const o=n.useMemo(()=>Lo(s,r),[s,r]);return e.jsx("div",{className:ma("whitespace-pre-wrap",a),children:o.map((l,u)=>l.kind==="text"?e.jsx("span",{children:l.text},u):e.jsx("span",{className:l.resolved?"rounded bg-primary/10 px-0.5 font-medium text-primary":"rounded bg-muted px-0.5 text-muted-foreground line-through decoration-dotted",title:l.resolved?l.name:`No member named "${l.name}" in this nest`,children:l.text},u))})}function Js(s){return Cs(s)||s}function Wn(s,r=80){const a=s.replace(/\s+/g," ").trim();return a.length>r?a.slice(0,r)+"…":a}function Ao({nestId:s,nodeId:r,readOnly:a,pendingAnchor:o,onClearAnchor:l,onFocusAnchor:u,onThreadsChange:h,activeThreadId:m,commentMode:x,onSetCommentMode:f}){const v=typeof f=="function",R=!v||!!x,[j,g]=n.useState(null),[w,z]=n.useState(""),[V,D]=n.useState(null),[d,B]=n.useState(""),[k,Y]=n.useState(!1),ae=Es(),ne=n.useRef(null),{data:S}=ir({...pe.mentionable(s),enabled:!!s&&!a}),F=n.useMemo(()=>((S==null?void 0:S.people)??[]).filter(b=>!!b.email),[S]),Z=n.useRef({}),ce=async()=>{try{const{threads:b}=await ae.fetchQuery(pe.nodeAnnotations(s,r));g(b),h==null||h(b)}catch{g([]),h==null||h([])}};n.useEffect(()=>{g(null),ce()},[s,r]),n.useEffect(()=>{var b;o&&((b=ne.current)==null||b.focus())},[o]),n.useEffect(()=>{var b;m&&Z.current[m]&&((b=Z.current[m])==null||b.scrollIntoView({behavior:"smooth",block:"nearest"}))},[m]);const Ne=async()=>{const b=w.trim();if(b){Y(!0);try{await sr(s,r,{body:b,anchor:o??null}),z(""),l==null||l(),await ce()}catch(M){N.error((M==null?void 0:M.message)||"Failed to add comment")}finally{Y(!1)}}},tt=async b=>{const M=d.trim();if(M){Y(!0);try{await ar(s,r,b,M),B(""),D(null),await ce()}catch(J){N.error((J==null?void 0:J.message)||"Failed to reply")}finally{Y(!1)}}},ke=async b=>{Y(!0);try{b.status==="open"?await nr(s,r,b.id):await rr(s,r,b.id),await ce()}catch(M){N.error((M==null?void 0:M.message)||"Failed to update thread")}finally{Y(!1)}},kt=(j==null?void 0:j.length)??0,Qe=j&&[...j].sort((b,M)=>M.createdAt.localeCompare(b.createdAt));return e.jsxs("section",{className:"flex flex-col flex-1 min-h-0 max-h-[calc(100vh-2rem)] rounded-lg border border-border bg-card p-5","data-testid":"annotations-panel",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4 border-b pb-3 shrink-0",children:[e.jsx(Ts,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("h3",{className:"text-sm font-semibold whitespace-nowrap",children:["Comments",j?` (${kt})`:""]}),!a&&v&&e.jsxs("label",{className:"ml-auto flex shrink-0 items-center gap-1.5 whitespace-nowrap text-xs text-muted-foreground cursor-pointer",children:["Comment mode",e.jsx(lr,{checked:!!x,onCheckedChange:b=>f==null?void 0:f(b),"data-testid":"annotations-comment-mode"})]})]}),!a&&e.jsxs("div",{className:"mb-4 shrink-0",children:[R&&(o?e.jsx("div",{className:"mb-2 rounded-md border border-amber-200 bg-amber-50/60 dark:bg-amber-950/20 px-2 py-1.5 text-xs","data-testid":"annotations-pending-anchor",children:e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx($n,{className:"h-3 w-3 mt-0.5 shrink-0 text-amber-700"}),e.jsxs("span",{className:"flex-1 italic text-foreground/80",children:["“",Wn(o.quote),"”"]}),e.jsx("button",{type:"button",className:"shrink-0 text-muted-foreground hover:text-foreground",title:"Comment on the whole document instead",onClick:()=>l==null?void 0:l(),children:e.jsx(et,{className:"h-3 w-3"})})]})}):e.jsx("p",{className:"mb-2 text-[11px] text-muted-foreground",children:"Tip: select text in the document to pin a comment to it."})),e.jsx(Hn,{ref:ne,members:F,value:R?w:"",onValueChange:z,readOnly:!R,onMouseDown:R?void 0:b=>{b.preventDefault(),f==null||f(!0)},onFocus:R?void 0:()=>f==null?void 0:f(!0),placeholder:R?o?"Comment on the highlighted text…":"Add a comment… use @ to tag someone":"Click here to start commenting…",title:R?void 0:"Click to turn on comment mode",rows:2,className:`w-full rounded-md border px-3 py-2 text-sm resize-y ${R?"border-input bg-background":"border-dashed border-input bg-muted/50 text-muted-foreground cursor-pointer"}`,"data-testid":"annotations-new"}),R&&e.jsx("div",{className:"flex justify-end mt-2",children:e.jsx(y,{size:"sm",onClick:Ne,disabled:k||!w.trim(),children:o?"Comment on selection":"Comment"})})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto -mr-2 pr-2",children:j===null?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-4",children:[e.jsx(te,{className:"h-4 w-4 animate-spin"})," Loading comments…"]}):kt===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No comments yet."}):e.jsx("ul",{className:"space-y-3",children:Qe.map(b=>{var M;return e.jsxs("li",{ref:J=>{Z.current[b.id]=J},className:`rounded-md border p-3 transition-shadow ${m===b.id?"border-amber-400 ring-2 ring-amber-300/60":b.status==="resolved"?"border-emerald-200 bg-emerald-50/40 dark:bg-emerald-950/20":"border-border"}`,children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded ${b.status==="resolved"?"bg-emerald-100 text-emerald-800":"bg-amber-100 text-amber-800"}`,children:b.status})}),((M=b.anchor)==null?void 0:M.quote)&&e.jsxs("button",{type:"button",onClick:()=>u==null?void 0:u(b.anchor),className:"group mb-2 block w-full text-left rounded border-l-2 border-amber-400 bg-amber-50/50 dark:bg-amber-950/20 px-2 py-1 text-xs italic text-foreground/75 hover:bg-amber-100/70",title:"Jump to this text in the document",children:[e.jsx($n,{className:"inline h-3 w-3 mr-1 text-amber-600 align-[-1px]"}),Wn(b.anchor.quote)]}),b.comments.length>0&&e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:b.comments[0].author})," ","· ",Js(b.comments[0].createdAt)]}),e.jsx(Bn,{body:b.comments[0].body,members:F})]}),b.comments.length>1&&e.jsx("ul",{className:"mt-2 ml-2 space-y-2 border-l-2 border-border pl-3",children:b.comments.slice(1).map(J=>e.jsxs("li",{className:"text-sm",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:J.author})," ","replied · ",Js(J.createdAt)]}),e.jsx(Bn,{body:J.body,members:F})]},J.id))}),b.status==="resolved"&&b.resolvedBy&&e.jsxs("div",{className:"mt-2 flex items-center gap-1 text-xs text-emerald-700 dark:text-emerald-400",children:[e.jsx(Zl,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{children:["Resolved by"," ",e.jsx("span",{className:"font-medium",children:b.resolvedBy}),b.resolvedAt&&e.jsxs(e.Fragment,{children:[" · ",Js(b.resolvedAt)]})]})]}),!a&&(V===b.id?e.jsxs("div",{className:"mt-2",children:[e.jsx(Hn,{members:F,value:d,onValueChange:B,placeholder:"Reply… use @ to tag someone",rows:2,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm resize-y",autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2 mt-1",children:[e.jsx(y,{variant:"ghost",size:"sm",onClick:()=>{D(null),B("")},children:"Cancel"}),e.jsx(y,{size:"sm",onClick:()=>tt(b.id),disabled:k||!d.trim(),children:"Reply"})]})]}):e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 rounded-md border px-2.5 py-1 text-xs font-medium text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>{D(b.id),B("")},children:[e.jsx(Jl,{className:"h-3 w-3"})," Reply"]}),b.status==="open"?e.jsxs("button",{type:"button",disabled:k,className:"inline-flex items-center gap-1 rounded-md border border-emerald-600 bg-emerald-600 px-2.5 py-1 text-xs font-semibold text-white shadow-sm hover:bg-emerald-700 disabled:opacity-50",onClick:()=>ke(b),children:[e.jsx(Pt,{className:"h-3.5 w-3.5"})," Resolve"]}):e.jsxs("button",{type:"button",disabled:k,className:"inline-flex items-center gap-1 rounded-md border px-2.5 py-1 text-xs font-medium text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",onClick:()=>ke(b),children:[e.jsx(xa,{className:"h-3 w-3"})," Reopen"]})]}))]},b.id)})})})]})}function Do(s){const r=document.createTreeWalker(s,NodeFilter.SHOW_TEXT),a=[];let o="",l;for(;l=r.nextNode();){const u=l;a.push({node:u,start:o.length}),o+=u.data}return{text:o,segs:a}}function Un(s,r){if(!s.segs.length)return null;for(let a=s.segs.length-1;a>=0;a--){const o=s.segs[a];if(r>=o.start)return{node:o.node,offset:Math.min(r-o.start,o.node.data.length)}}return{node:s.segs[0].node,offset:0}}function Mo(s,r){const a=r.quote;if(!a)return null;const o=[];let l=s.text.indexOf(a);for(;l!==-1;)o.push(l),l=s.text.indexOf(a,l+1);if(!o.length)return null;let u=o[0];if(o.length>1&&r.before){const h=r.before.slice(-24),m=o.find(x=>s.text.slice(Math.max(0,x-h.length),x).endsWith(h));m!==void 0&&(u=m)}return{start:u,end:u+a.length}}function Fo(s,r,a){const o=Mo(r,a);if(!o)return null;const l=Un(r,o.start),u=Un(r,o.end);if(!l||!u)return null;try{const h=document.createRange();return h.setStart(l.node,l.offset),h.setEnd(u.node,u.offset),h}catch{return null}}function kr(){return typeof CSS<"u"&&"highlights"in CSS}function Gn(s,r){if(!kr())return;const a=window.Highlight;if(a){if(!r.length){CSS.highlights.delete(s);return}CSS.highlights.set(s,new a(...r))}}function Qn(s){kr()&&CSS.highlights.delete(s)}function Kn(s,r){const a=document;if(a.caretPositionFromPoint){const o=a.caretPositionFromPoint(s,r);return o?{node:o.offsetNode,offset:o.offset}:null}if(a.caretRangeFromPoint){const o=a.caretRangeFromPoint(s,r);return o?{node:o.startContainer,offset:o.startOffset}:null}return null}function Po(s,r=[]){var o;const a=s.toLowerCase();return((o=r.find(l=>l.email.toLowerCase()===a))==null?void 0:o.name)||s}function Xn(s){return s.replace(/^#/,"").toLowerCase()}const Vo=2,Oo=1;function zo(s,r,a=5){const o=s.id.toLowerCase(),l=new Set((s.tags??[]).map(Xn)),u=new Set(ia(s.content??"").map(m=>m.toLowerCase())),h=[];for(const m of r){if(m.id.toLowerCase()===o)continue;const x=[];for(const R of m.tags??[])l.has(Xn(R))&&x.push(R);let f=0;for(const R of ia(m.content??""))u.has(R.toLowerCase())&&f++;const v=x.length*Vo+f*Oo;v>0&&h.push({id:m.id,title:m.title,score:v,sharedTags:x})}return h.sort((m,x)=>x.score-m.score||m.title.localeCompare(x.title)).slice(0,a)}function Yn(s){const r=s.lastIndexOf("/");return r>=0?s.slice(r+1):s}function qo(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _o(s){return(s??"").replace(/\[\[[^\]]*\]\]/g," ")}function Ho(s,r){const a=s.id.toLowerCase(),o=(s.title??"").trim();if(!o)return[];const l=o.toLowerCase(),u=Yn(s.id).toLowerCase(),h=new RegExp(`\\b${qo(l)}\\b`),m=f=>ia(f).some(v=>{const R=v.toLowerCase();return R===a||R===l||Yn(v).toLowerCase()===u}),x=[];for(const f of r){if(f.id.toLowerCase()===a)continue;const v=f.content??"";m(v)||h.test(_o(v).toLowerCase())&&x.push({id:f.id,title:f.title})}return x}const Bo={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *"},Wo=[{label:"minute",min:0,max:59},{label:"hour",min:0,max:23},{label:"day of month",min:1,max:31},{label:"month",min:1,max:12},{label:"day of week",min:0,max:7}],Uo=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Go=["","January","February","March","April","May","June","July","August","September","October","November","December"],Zn=s=>s.padStart(2,"0"),Ie=s=>/^\d+$/.test(s);function Qo(s,r){for(const a of s.split(",")){const o=/^(\*|\d+(?:-\d+)?)(?:\/(\d+))?$/.exec(a);if(!o)return`"${a}" isn't a valid ${r.label} (use a number, a range like 1-5, \`*\`, or \`*/n\`)`;const[,l,u]=o;if(u!==void 0&&Number(u)<=0)return`the step in "${a}" must be greater than zero`;if(l!=="*"){const h=l.split("-").map(Number);for(const m of h)if(m<r.min||m>r.max)return`${r.label} must be between ${r.min} and ${r.max} (got ${m} in "${a}")`;if(h.length===2&&h[0]>h[1])return`the range "${a}" is backwards — ${h[0]} is after ${h[1]}`}}return null}function Ko(s){const[r,a,o,l,u]=s,h=o==="*"&&l==="*"&&u==="*";if(r==="*"&&a==="*"&&h)return"Runs every minute";if(Ie(r)&&Ie(a)){const m=`${Zn(a)}:${Zn(r)}`;if(h)return`Runs daily at ${m}`;if(o==="*"&&l==="*"&&Ie(u))return`Runs weekly on ${Uo[Number(u)%7]} at ${m}`;if(Ie(o)&&l==="*"&&u==="*")return`Runs monthly on day ${o} at ${m}`;if(Ie(o)&&Ie(l)&&u==="*")return`Runs yearly on ${Go[Number(l)]} ${o} at ${m}`}return r.startsWith("*/")&&a==="*"&&h?`Runs every ${r.slice(2)} minutes`:Ie(r)&&a==="*"&&h?r==="0"?"Runs hourly, on the hour":`Runs hourly at minute ${r}`:Ie(r)&&a.startsWith("*/")&&h?`Runs at minute ${r} past every ${a.slice(2)} hours`:"Runs on a custom schedule (minute hour day-of-month month day-of-week)"}function Xo(s){const a=(Bo[s.toLowerCase()]??s).trim().split(/\s+/);if(a.length!==5)return{kind:"invalid",error:`A cron schedule needs 5 space-separated fields (minute hour day month weekday) — got ${a.length}`};for(let o=0;o<5;o++){const l=Qo(a[o],Wo[o]);if(l)return{kind:"invalid",error:l}}return{kind:"valid",description:Ko(a)}}const Yo={s:1,m:60,h:3600,d:86400};function Zo(s){const r=s.slice(6).trim(),a=/(\d+)(s|m|h|d)/gi;let o,l=0,u=0;for(;o=a.exec(r);)l+=Number(o[1])*Yo[o[2].toLowerCase()],u+=o[0].length;if(u===0||u!==r.replace(/\s+/g,"").length)return{kind:"invalid",error:`"${r}" isn't a valid duration — use a number plus s/m/h/d, e.g. "15m" or "1h30m"`};if(l<=0)return{kind:"invalid",error:"the interval must be greater than zero"};const h=[],m=Math.floor(l/86400),x=Math.floor(l%86400/3600),f=Math.floor(l%3600/60),v=l%60;return m&&h.push(`${m} day${m===1?"":"s"}`),x&&h.push(`${x} hour${x===1?"":"s"}`),f&&h.push(`${f} minute${f===1?"":"s"}`),v&&h.push(`${v} second${v===1?"":"s"}`),{kind:"valid",description:`Runs every ${h.join(" ")}`}}function Jo(s){const r=s.trim();return r?r.toLowerCase().startsWith("@every")?Zo(r):Xo(r):{kind:"empty"}}function ks(s){return s?/^\s*</.test(s):!1}function Jn(s){switch(s){case"html":return"raw HTML (served as a sandboxed page)";case"csv":return"CSV data";case"code":return"code (tool source)";default:return"formatted document prose"}}function In(s){if(!s)return"";if(typeof DOMParser>"u")return s.trim();try{return(new DOMParser().parseFromString(s,"text/html").body.innerHTML||"").replace(/\s+/g," ").trim()}catch{return s.trim()}}function Rc({nestId:s,nestName:r,nodeId:a,initialFolder:o,initialThreadId:l,isOwner:u=!1,onBack:h,onSaved:m,onNavigateDocument:x,onTagClick:f,onOpenNest:v,onOpenFolder:R,onCreateDocument:j,initialTitle:g,breadcrumb:w,onJumpBreadcrumb:z,sidebarCollapsed:V=!1,onToggleSidebar:D}){var an,nn,rn,ln,on,cn,dn,un,mn,hn,xn,fn,pn;const d=a==="new",B=Rl(),{adminStatus:k,isAdmin:Y,workflowPlaneEnabled:ae,typeArtifactEnabled:ne,typeTableEnabled:S}=ha(),F=((nn=(an=k==null?void 0:k.me)==null?void 0:an.email)==null?void 0:nn.toLowerCase())??"",Z=u||Y,[ce,Ne]=n.useState(!1),[tt,ke]=n.useState(!1),[kt,Qe]=n.useState(!1),b=Es(),M=Di(s),J=Mi(s),Ke=Fi(s,d?void 0:a),Pe=n.useMemo(()=>{var t;return(((t=Ke.data)==null?void 0:t.stewards)??[]).filter(i=>(i.email||"").toLowerCase()===F).map(i=>String(i.role))},[Ke.data,F]),ss=d||!Ke.isLoading,[st,St]=n.useState(null),as=st==="write",de=((rn=M.data)==null?void 0:rn.myStewards)??[],[C,Se]=n.useState(d&&g?g:"");Pi([{label:d?"New document":C.trim()||"Untitled"}]);const[Ce,Ve]=n.useState(o??""),[$,q]=n.useState(""),[W,Oe]=n.useState([]),[ge,Re]=n.useState(""),[re,Xe]=n.useState(null),at=n.useRef(null),Vt=((ln=J.data)==null?void 0:ln.prime_tags)??[],[ue,nt]=n.useState(null),[be,Ot]=n.useState(null),[U,ze]=n.useState(null),[Ct,zt]=n.useState(!1),[I,qt]=n.useState(null),[Rt,rt]=n.useState(!1),[Le,qe]=n.useState(""),[_e,_t]=n.useState(void 0),[ie,Te]=n.useState(null),[He,As]=n.useState(null),[Tt,$t]=n.useState(null),[it,Ds]=n.useState([]),[ns,rs]=n.useState(null),[we,is]=n.useState(null),lt=!!((on=J.data)!=null&&on.stewardship_enabled),Ht=!!((cn=J.data)!=null&&cn.allow_self_approve),Et=((dn=M.data)==null?void 0:dn.permission)??null,ve=Vi((un=M.data)==null?void 0:un.nest),{hasAdminApprove:Bt,isViewOnly:ee,isReviewerOnly:G,canEditContent:Ae}=bo({isNew:d,isOwner:u,isAdmin:Y,permission:Et,nestStewards:de,nodeRoles:Pe,grant:st,isArchived:ve}),{data:c}=ir({...pe.mentionable(s),enabled:!!s&&!d&&!!(k!=null&&k.me)}),E=He?Po(He,c==null?void 0:c.people):null,P=!!He&&!!((mn=k==null?void 0:k.me)!=null&&mn.email)&&He.toLowerCase()===k.me.email.toLowerCase(),H=!ve&&(u||Y||Et==="owner"||Et==="admin"||P),Lt=!ve&&(H||Et==="write"||as||Pe.includes("editor")||de.some(t=>t.role==="editor"&&t.scope==="nest")),[ls,os]=n.useState(!1),[Sr,pa]=n.useState(!1),[me,Ms]=n.useState(null),Fs=(me==null?void 0:me.status)==="pending",[Cr,ga]=n.useState(!1),[Q,ot]=n.useState(d?"edit":"view"),[Ps,ba]=n.useState(!1),[je,wa]=n.useState("document"),[cs,ds]=n.useState(null),ct=d&&je==="artifact",us=t=>t==="artifact"?"html":t==="table"?"csv":t==="tool"?"code":"markdown",Rr=(t,i)=>{if(t!==je&&$.trim()&&us(t)!==us(je)){ds({value:t,label:i});return}wa(t)},De=d?je:ue??"document",dt=!d&&ue==="pdf",Vs=De==="tool"||De==="table",Wt=d?je==="agent"||je==="skill":ue==="agent"||ue==="skill",va=`${typeof window<"u"?window.location.origin:""}/nests/${s}/runnables`,[Tr,ja]=n.useState(!1),$r=async()=>{await Cn(va)&&(ja(!0),setTimeout(()=>ja(!1),1500))},[he,Ut]=n.useState(!1),[Os,zs]=n.useState(null),[Gt,Be]=n.useState(null),ya=n.useRef(null),Qt=n.useRef(null),Na=n.useRef(null),[ut,Er]=n.useState([]),[Kt,At]=n.useState(null),[We,ka]=n.useState(()=>Oi(localStorage).commentsOpen),Lr=t=>{ka(t),ll(localStorage,{commentsOpen:t})},Sa=n.useMemo(()=>Q==="view"&&!ks($)?Tl($):[],[Q,$]),qs=!d&&Sa.length>=3,ms=n.useRef(!1);n.useEffect(()=>{ka(t=>zi(t,{initialThreadId:ms.current?null:l,commentMode:he,pendingAnchor:!!Os,activeThreadId:Kt}))},[l,he,Os,Kt]);const Ca=ut.filter(t=>t.status==="open").length,Ye=n.useRef([]),Xt=n.useRef(null);n.useEffect(()=>{var i;if(!l||ms.current)return;const t=ut.find(p=>p.id===l);t&&(ms.current=!0,Ut(!0),ot("view"),At(t.id),(i=t.anchor)!=null&&i.quote&&(Xt.current=t.id))},[ut,l]);const Ar=n.useCallback(()=>{const t=window.getSelection();if(!t||t.isCollapsed||t.rangeCount===0){Be(null);return}const i=t.getRangeAt(0),p=Qt.current;if(!p||!p.contains(i.commonAncestorContainer)){Be(null);return}if(!t.toString().trim()){Be(null);return}const T=(pi,gi)=>{const Ks=document.createRange();return Ks.setStart(p,0),Ks.setEnd(pi,gi),Ks.toString().length},O=document.createRange();O.selectNodeContents(p);const _=O.toString();let L=T(i.startContainer,i.startOffset),A=T(i.endContainer,i.endOffset);for(L>A&&([L,A]=[A,L]);L<A&&/\s/.test(_[L]);)L++;for(;A>L&&/\s/.test(_[A-1]);)A--;const K=_.slice(L,A);if(!K){Be(null);return}const Ns=_.slice(Math.max(0,L-250),L),xi=_.slice(A,A+250),gn=$.indexOf(K),fi=gn>=0?$.slice(0,gn).split(`
36
- `).length:void 0;ya.current={quote:K,before:Ns,after:xi,line:fi};const Qs=i.getBoundingClientRect();Be({x:Qs.left+Qs.width/2,y:Qs.top})},[$]),Dr=n.useCallback(()=>{var i;const t=ya.current;t&&(zs(t),Be(null),(i=window.getSelection())==null||i.removeAllRanges())},[]);n.useEffect(()=>{const t=Qt.current,i=!d&&(he||Q==="view")&&!Ps&&I==null&&!ks($);if(!t||!i){Ye.current=[],Qn("comment-anchor"),Qn("comment-anchor-active");return}const p=requestAnimationFrame(()=>{var _,L;const T=Do(t),O=[];for(const A of ut){if(!((_=A.anchor)!=null&&_.quote))continue;const K=Fo(t,T,A.anchor);K&&O.push({id:A.id,range:K})}if(Ye.current=O,Gn("comment-anchor",O.map(A=>A.range)),Xt.current){const A=O.find(K=>K.id===Xt.current);A&&((L=A.range.startContainer.parentElement)==null||L.scrollIntoView({behavior:"smooth",block:"center"}),At(A.id)),Xt.current=null}});return()=>cancelAnimationFrame(p)},[ut,$,Q,Ps,I,d,he]),n.useEffect(()=>{const t=Ye.current.find(i=>i.id===Kt);Gn("comment-anchor-active",t?[t.range]:[])},[Kt]);const Mr=n.useCallback(t=>{var O,_;const i=ut.find(L=>{var A,K;return((A=L.anchor)==null?void 0:A.quote)===t.quote&&((K=L.anchor)==null?void 0:K.before)===t.before});i&&At(i.id);const p=(O=Ye.current.find(L=>L.id===(i==null?void 0:i.id)))==null?void 0:O.range;if(p){(_=p.startContainer.parentElement)==null||_.scrollIntoView({behavior:"smooth",block:"center"});return}if(!(he||Q==="view")&&!ks($)){Xt.current=(i==null?void 0:i.id)??null,Ut(!0),ot("view");return}N.message("That highlighted text isn't in the current version.")},[ut,he,Q,$]),Fr=n.useCallback(t=>{if(!Ye.current.length)return;const i=Kn(t.clientX,t.clientY);if(i)for(const{id:p,range:T}of Ye.current)try{if(T.isPointInRange(i.node,i.offset)){At(p);return}}catch{}},[]),Pr=n.useCallback(t=>{const i=Qt.current;if(!i)return;if(!Ye.current.length){i.style.cursor="";return}const p=Kn(t.clientX,t.clientY);let T=!1;if(p)for(const{range:O}of Ye.current)try{if(O.isPointInRange(p.node,p.offset)){T=!0;break}}catch{}i.style.cursor=T?"pointer":""},[]);n.useEffect(()=>{if(!Gt)return;const t=i=>{var T;const p=i.target;p.closest('[data-testid="selection-comment-button"]')||(T=Qt.current)!=null&&T.contains(p)||Be(null)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[Gt]);const hs=n.useRef(null),Ra=n.useRef(null);n.useEffect(()=>{var t;d&&((t=Ra.current)==null||t.focus())},[]);const xs=n.useRef({title:d&&g?g:"",content:"",tags:[],schedule:""}),_s=n.useRef(""),[ye,Ta]=n.useState(!d),[xe,Vr]=n.useState([]),[$a,Or]=n.useState([]);n.useEffect(()=>{if(ye)return;let t=!1;return(async()=>{try{const{census:i}=await b.fetchQuery(pe.census(s));t||Or(i.folders.map(p=>p.path))}catch{}})(),()=>{t=!0}},[ye,s,b]),n.useEffect(()=>{if(ye)return;let t=!1;return(async()=>{try{const{nodes:i}=await b.fetchQuery(pe.nodes(s));t||Vr(i)}catch{}})(),()=>{t=!0}},[d,ye,s]);const Ea=n.useMemo(()=>{const t=new Set($a);for(const i of xe){const T=(i.id.startsWith("nodes/")?i.id.slice(6):i.id).split("/").slice(0,-1);for(let O=1;O<=T.length;O++)t.add(T.slice(0,O).join("/"))}return[...t].sort()},[xe,$a]),zr=n.useMemo(()=>{if(d||!a)return[];const i=(a.startsWith("nodes/")?a.slice(6):a).split("/").slice(0,-1);return i.map((p,T)=>({path:i.slice(0,T+1).join("/"),label:aa(p)}))},[d,a]),[Ue,Yt]=n.useState(null),[Ze,fs]=n.useState(null),[ps,La]=n.useState(!1),gs=n.useMemo(()=>[{value:"document",label:"Document",Icon:ea,expects:"Markdown prose."},...ne?[{value:"artifact",label:"Artifact",Icon:ts,expects:"An HTML page — the body is hosted and rendered as-is."}]:[],...S?[{value:"table",label:"Table",Icon:na,expects:"CSV — one header row, then data rows."}]:[],...ae?[{value:"agent",label:"Agent",Icon:vn,expects:"Markdown instructions an orchestrator runs; can carry a schedule."},{value:"skill",label:"Skill",Icon:Ln,expects:"Markdown instructions with a trigger (defaulted from the title)."},{value:"tool",label:"Tool",Icon:En,expects:"Source code, shown and edited as code."}]:[]].filter(i=>i.value!==(ue??"document")),[ne,S,ae,ue]),qr=async()=>{var t;if(!(!Ze||d)){La(!0);try{await Rs(s,a,{type:Ze}),Ys(b,`/nests/${s}/nodes/${a}`),N.success(`Turned into ${((t=gs.find(i=>i.value===Ze))==null?void 0:t.label)??Ze}`),fs(null),await oe()}catch(i){N.error(i instanceof Error?i.message:"Failed to convert")}finally{La(!1)}}},[bs,Aa]=n.useState(!1),Da=n.useMemo(()=>d||!a?"":(a.startsWith("nodes/")?a.slice(6):a).split("/").slice(0,-1).join("/"),[d,a]),Zt=n.useMemo(()=>d?[]:ql(xe,{id:a,title:C}),[d,xe,a,C]),Ma=n.useMemo(()=>d?[]:zo({id:a,tags:W,content:$},xe),[d,xe,a,C,W,$]),ws=n.useMemo(()=>d?[]:Ho({id:a,title:C},xe),[d,xe,a,C]),Dt=n.useMemo(()=>d?[]:_l($,xe),[d,$,xe]),_r=n.useCallback(t=>{const i=$l(xe,t);return i?{title:i.title,snippet:El(i.content??"")}:null},[xe]),[Ge,Fa]=n.useState(!1),[Jt,It]=n.useState(null),[Hr,Pa]=n.useState(!1),[Mt,X]=n.useState(!1),[Hs,Va]=n.useState(!1),[Br,Wr]=n.useState(!1),[Oa,vs]=n.useState(null),oe=n.useCallback(async()=>{if(!d){Ta(!0),Pa(!1);try{const{node:t}=await b.fetchQuery(pe.node(s,a)),i=(t==null?void 0:t.title)==null?"":String(t.title),p=(t==null?void 0:t.content)==null?"":String(t.content),T=Array.isArray(t==null?void 0:t.tags)?Pn([],t.tags.map(A=>ua(String(A)))):[];Se(i),q(p),Oe(T),nt((t==null?void 0:t.type)??null),Ot((t==null?void 0:t.type)==="pdf"&&(t!=null&&t.pdf)?t.pdf:null);const O=(t==null?void 0:t.schedule)==null?"":String(t.schedule);Re(O);const _=typeof(t==null?void 0:t.prime)=="boolean"?t.prime:null;Xe(_),at.current=_,_t(t==null?void 0:t.version),Te((t==null?void 0:t.status)??null),As((t==null?void 0:t.author)??null),$t((t==null?void 0:t.updated_at)??null),Ds(Array.isArray(t==null?void 0:t.collaborators)?t.collaborators.map(A=>String(A)):[]),rs((t==null?void 0:t.pendingChange)??null),is((t==null?void 0:t.pendingReviewBy)??null),Ms((t==null?void 0:t.deletionRequest)??null),St((t==null?void 0:t.myGrant)??null),xs.current={title:i,content:p,tags:T,schedule:O},_s.current=i,X(!1);const L=qi(s,a);vs(null),L&&(L.baseVersion!==(t==null?void 0:t.version)?Xs(s,a):(Se(L.title),q(L.content),Oe(L.tags),Re(L.schedule),X(!0),vs(L.savedAt??Date.now())))}catch(t){It(t.message),Pa(!0)}finally{Ta(!1)}}},[d,s,a]),Je=n.useCallback(async()=>{if(d){ze(null);return}try{ze(await b.fetchQuery(pe.nodeVersions(s,a)))}catch(t){console.error("[DocumentEditor] getNodeVersions failed",s,a,t),ze(null),N.error((t==null?void 0:t.message)||"Failed to load version history")}},[d,s,a]);n.useEffect(()=>{d||oe()},[d,oe]);const Ur=n.useCallback(async()=>{zt(!0),await Je()},[Je]),[za,qa]=n.useState(!1),[Gr,Bs]=n.useState(!1),Qr=n.useCallback(async()=>{Bs(!1),qa(!0);try{const t=await jn(s,a);if(t.deleted){N.success("Never approved — document deleted"),h();return}N.success(`Draft discarded — back to version ${t.version}`),await Promise.all([oe(),Je()])}catch(t){N.error((t==null?void 0:t.message)||"Discard failed")}finally{qa(!1)}},[s,a,C,h,oe,Je]),Kr=n.useCallback(async()=>{U||await Je()},[U,Je]),[Ws,_a]=n.useState(null),Us=n.useCallback(async t=>{if(qt(t),rt(!1),_a(null),t!=null)try{const{content:i}=await ta(s,a,t);_a({version:t,content:i??""})}catch(i){N.error((i==null?void 0:i.message)||`Failed to load version ${t}`),qt(null)}},[s,a]),Gs=ie==="pending_review"&&!!we&&!!F&&we.toLowerCase()===F,fe=ie==="pending_review"&&!Gs,Ha=!d&&!fe&&!dt&&gs.length>0,mt=d?je:ue??"document",le=fe||Q!=="edit",Xr=n.useMemo(()=>C.trim().length>0&&$.trim().length>0&&!Ge,[C,$,Ge]),se=n.useMemo(()=>{if(!Mt)return!1;const t=xs.current;if(C.trim()!==t.title.trim()||In($)!==In(t.content)||W.length!==t.tags.length)return!0;for(let i=0;i<W.length;i++)if(W[i]!==t.tags[i])return!0;return ge.trim()!==t.schedule.trim()||re!==at.current},[Mt,C,$,W,ge,re]),Ba=Xr&&(d||se),js=n.useRef(!1),ht=n.useRef(0);n.useEffect(()=>{if(!se||G)return;const t=i=>{js.current||i.preventDefault()};return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[se,G]),n.useEffect(()=>(yn(t=>!se||G?!1:(pt({label:"leave this document",run:t}),!0)),()=>yn(null)),[se,G]),n.useEffect(()=>{if(!se||G)return;js.current=!1,ht.current=0;const t=()=>{window.history.pushState({cnLeaveGuard:!0},""),ht.current++};t();const i=()=>{ht.current=Math.max(0,ht.current-1),t(),pt(p=>p??{label:"leave this page",run:()=>{js.current=!0,window.history.go(-(ht.current+1))}})};return window.addEventListener("popstate",i),()=>{var p;window.removeEventListener("popstate",i),!js.current&&ht.current>0&&((p=window.history.state)!=null&&p.cnLeaveGuard)&&window.history.go(-ht.current)}},[se,G]);const xt=n.useMemo(()=>Jo(ge),[ge]),[Wa,Yr]=n.useState("");n.useEffect(()=>{if(!ct)return;const t=setTimeout(()=>Yr($),400);return()=>clearTimeout(t)},[$,ct]);const Zr=n.useDeferredValue($),Ft=n.useMemo(()=>{const t=Le.split(/[\s,]+/).map(yr),i=t.map(p=>p.tag).filter(p=>!!p);return{tags:Pn(W,i),notes:t.map(p=>p.note).filter(Boolean)}},[Le,W]),Ua=n.useCallback(()=>{const{tags:t,notes:i}=Ft;if(i.length===1?N.warning(i[0]):i.length>1&&N.warning(`${i.length} tags normalized`,{description:i.join(" "),duration:8e3}),t.length===0){qe("");return}Oe([...W,...t]),qe(""),X(!0),N.success(t.length===1?`Tag "${t[0]}" added`:`${t.length} tags added`,{id:"tag-added",description:"Save the document to keep it."})},[Ft,W]),Jr=t=>{Oe(W.filter(i=>i!==t)),X(!0)},Ir=async()=>{var T,O,_,L;if(!d&&!se)return X(!1),N.message("Not saved — no changes were made. Edit the document, then save again."),{ok:!0,savedId:a,noop:!0};const t={title:C.trim(),content:$,tags:W};let i,p;if(d){const A=await ml(s,{...t,type:je,...Ce.trim()?{folder:Ce.trim()}:{},...Wt?{schedule:ge.trim()}:{},...re===null?{}:{prime:re}});i=(T=A==null?void 0:A.node)==null?void 0:T.id,p=(O=A==null?void 0:A.node)==null?void 0:O.status}else{const A=re===at.current?{}:{prime:re},K=await Rs(s,a,Wt?{...t,...A,schedule:ge.trim()}:{...t,...A},_e);at.current=re;const Ns=(K==null?void 0:K.version)??((_=K==null?void 0:K.node)==null?void 0:_.version);typeof Ns=="number"&&_t(Ns),$t(((L=K==null?void 0:K.node)==null?void 0:L.updated_at)??new Date().toISOString()),i=a}return xs.current={title:t.title,content:$,tags:[...W],schedule:ge.trim()},d||Xs(s,a),X(!1),vs(null),{ok:!0,savedId:i,...d?{createdStatus:p}:{}}},[ft,pt]=n.useState(null),Ga=async t=>{if(!Ba){It(d?"Add a title and content before saving.":"Current document can't be saved — fix errors before leaving.");return}Fa(!0),It(null);try{const{savedId:i,noop:p,createdStatus:T}=await Ir();p||Va(!0),d&&i?N.success(T==="published"?`"${C.trim()||"Untitled"}" published — it's now live and available for use.`:`"${C.trim()||"Untitled"}" saved as a draft.`):!d&&!p&&N.success(`"${C.trim()||"Untitled"}" saved.`),Tn(()=>t(i??""))}catch(i){It(i.message)}finally{Fa(!1)}},Qa=()=>Ga(t=>m==null?void 0:m(t));n.useEffect(()=>{se&&Va(!1)},[se]);const Ka=n.useRef(()=>{});Ka.current=()=>{if(d||fe||G||ee||!se)return;const t=_i(s,a,{title:C,content:$,tags:[...W],schedule:ge.trim(),baseVersion:_e});Wr(!t)};const gt=n.useCallback(()=>{Ka.current()},[]),Me=(t,i)=>{if(!se||G){i();return}pt({label:t,run:i})},ei=()=>Ga(()=>{const t=ft==null?void 0:ft.run;pt(null),t==null||t()}),Xa=()=>{d||Xs(s,a);const t=xs.current;Se(t.title),q(t.content),Oe([...t.tags]),Re(t.schedule),X(!1),vs(null)},ti=()=>{if(!ft)return;const t=ft.run;Xa(),pt(null),Tn(t)},si=async(t,i)=>{d||(await dl(s,a,t,i),os(!1),await oe())},ai=async t=>{d||(await il(s,a,t),await oe())},ni=async t=>{d||(await rl(s,a,t),await oe())},ri=async()=>{if(!d)try{await ol(s,a),N.success("Submission withdrawn — back to Draft"),await oe()}catch(t){console.error("[DocumentEditor] cancelReview failed",s,a,t),N.error((t==null?void 0:t.message)||"Failed to withdraw submission")}},ii=async t=>{if(d)return;const{request:i}=await al(s,a,t);Ms(i),N.success("Deletion requested — a nest admin will review it")},li=async()=>{d||(await sl(s,a),N.success(`Deleted "${C||a}"`),h())},oi=Pe.includes("reviewer"),ci=Gs,ys=Vt.length>0&&W.some(t=>Vt.includes(t.trim().replace(/^#+/,"").toLowerCase())),Ya=re===null?ys:re,di=u||Bt,ui=!d&&ie==="pending_review"&&(Bt||oi||u&&Ht)&&(!ci||u&&Ht),Za=n.useRef(!1);n.useEffect(()=>{Za.current||ye||!ss||(Za.current=!0,ie==="pending_review"&&G&&Ut(!0))},[ye,ss,ie,G]),n.useEffect(()=>{ye||Q==="edit"||he||dt||!ee&&!fe&&!G&&ot("edit")},[ye,ee,fe,G,Q,he,dt]),n.useEffect(()=>{fe&&Q==="edit"&&ot("view")},[fe,Q]);const Ja=!d&&lt&&ie==="draft"&&!G,mi=t=>{var i;(i=hs.current)==null||i.insertWikiLink(t.id,t.title)},Ia=async(t,i,p)=>{try{const{nodes:T}=await b.fetchQuery(pe.nodes(s)),L=Ol(T,t,!G&&!ee,p);L.kind==="navigate"?Me(`open "${L.node.title}"`,()=>x==null?void 0:x(s,L.node.id,C)):L.kind==="create"?Me(`create "${L.title}"`,()=>j==null?void 0:j(s,L.title)):It(`"${L.title}" doesn't exist in this nest. You only have view access — ask someone with edit rights to add it.`)}catch{}},hi=Fs&&((hn=me==null?void 0:me.requestedBy)==null?void 0:hn.toLowerCase())===F,en=t=>Kl({isNew:d,canShare:Z,isArchived:ve,canEditContent:Ae,isPdf:dt,isLocked:fe,canRequestDeletion:Lt,canDeleteDirectly:H,deletionRequested:Fs,isOwnDeletionRequest:hi,includeVersionHistory:t.includeVersionHistory}).map(i=>{const p={label:i.label,testId:i.testId,separatorBefore:i.separatorBefore,destructive:i.destructive};switch(i.key){case"history":return{...p,icon:br,onSelect:Ur};case"copy-link":return{...p,icon:Pl,onSelect:()=>{const T=`${window.location.origin}${ul(s)}?doc=${encodeURIComponent(a)}`;Cn(T,"Link copied — recipient needs access to this nest")}};case"move":return{...p,icon:An,onSelect:()=>Yt(Da)};case"share-doc":return{...p,icon:da,onSelect:()=>Qe(!0)};case"publish":return{...p,icon:da,onSelect:()=>ke(!0)};case"delete":case"request-deletion":return{...p,icon:ca,onSelect:()=>pa(!0)};case"withdraw-deletion":return{...p,icon:et,onSelect:async()=>{try{await nl(s,me.id),Ms(null),N.success("Deletion request withdrawn")}catch(T){N.error(T instanceof Error?T.message:"Failed to withdraw request")}}}}}),tn=e.jsx(e.Fragment,{children:!d&&(Z&&!ve?e.jsx(pr,{nestId:s,variant:"compact",onChanged:()=>void b.invalidateQueries({queryKey:Hi.nest(s)}),onError:t=>{t&&N.error(t)}}):((fn=(xn=M.data)==null?void 0:xn.nest)==null?void 0:fn.visibility)&&e.jsxs("span",{className:"hidden sm:inline-flex items-center gap-1 px-1.5 text-xs text-muted-foreground",title:M.data.nest.visibility==="public"?"Public — anyone with the URL can read":M.data.nest.visibility==="org"?"Organization — everyone signed in here can read":"Private","data-testid":"document-editor-visibility",children:[M.data.nest.visibility==="public"?e.jsx(Bi,{className:"h-3.5 w-3.5"}):M.data.nest.visibility==="org"?e.jsx(Wi,{className:"h-3.5 w-3.5"}):e.jsx(Ui,{className:"h-3.5 w-3.5"}),M.data.nest.visibility==="public"?"Public":M.data.nest.visibility==="org"?"Organization":"Private"]}))}),sn=e.jsxs(e.Fragment,{children:[!d&&e.jsx(Gi,{open:Sr,onOpenChange:pa,title:H?`Delete "${C||a}"?`:`Request deletion of "${C||a}"`,description:H?"This removes the document, its version history, comments and annotations. It cannot be undone.":"A nest admin reviews this and either deletes the document or rejects with a note. Nothing is removed yet.",warning:H?Hl(Zt.length):void 0,label:H?void 0:"Why should it be deleted?",placeholder:"e.g. superseded by the new runbook",confirmLabel:H?"Delete document":"Request deletion",destructive:H,priorDecline:!H&&(me==null?void 0:me.status)==="declined"?me:null,onConfirm:H?li:ii}),e.jsx(bt,{open:Ue!==null,onOpenChange:t=>{!t&&!bs&&Yt(null)},children:e.jsxs(wt,{className:"sm:max-w-[440px]",children:[e.jsx(vt,{children:e.jsx(jt,{children:"Move to folder"})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Move ",e.jsx("strong",{children:C||a})," to another folder. Version history, review state, and [[wiki links]] follow the document."]}),e.jsxs(Qi,{value:Ue===""?"__root__":Ue??"__root__",onValueChange:t=>Yt(t==="__root__"?"":t),children:[e.jsx(Ki,{"data-testid":"document-editor-move-select",children:e.jsx(Xi,{placeholder:"Choose a folder"})}),e.jsxs(Yi,{children:[e.jsx(Nn,{value:"__root__",children:"Nest root"}),Ea.map(t=>e.jsx(Nn,{value:t,children:Zi(t)},t))]})]}),e.jsxs(yt,{children:[e.jsx(y,{variant:"ghost",disabled:bs,onClick:()=>Yt(null),children:"Cancel"}),e.jsxs(y,{disabled:bs||Ue===null||Ue===Da,"data-testid":"document-editor-move-confirm",onClick:async()=>{if(Ue!==null){Aa(!0);try{const{node:t}=await Ji(s,a,Ue);N.success(Ue?`Moved to ${Ue}`:"Moved to nest root"),Yt(null),m==null||m(t.id)}catch(t){N.error((t==null?void 0:t.message)||"Move failed")}finally{Aa(!1)}}},children:[bs?e.jsx(te,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(An,{className:"h-4 w-4 mr-2"}),"Move"]})]})]})}),kt&&e.jsx(Bl,{nestId:s,targetType:"document",target:a,label:C||a,archived:ve,onClose:()=>Qe(!1)}),ce&&e.jsx($o,{nestId:s,nestName:r,stewardshipEnabled:lt,onClose:()=>Ne(!1),onChanged:()=>{}}),tt&&e.jsx(Wl,{nestId:s,nodeId:a,nodeTitle:C||a,onClose:()=>ke(!1)})]});return!d&&!ye&&Hr?e.jsx("div",{className:"mt-14 md:mt-0","data-testid":"document-not-found",children:e.jsxs("div",{className:"max-w-xl mx-auto py-16 text-center space-y-4",children:[e.jsx(vr,{className:"h-10 w-10 mx-auto text-muted-foreground"}),e.jsx("h2",{className:"text-xl font-semibold",children:"Document not found"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Jt??`Nothing lives at ${a} in this nest — the link may be stale or the document may have been moved or deleted.`}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsxs(y,{variant:"outline",onClick:()=>void oe(),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Try again"]}),e.jsxs(y,{onClick:h,children:[e.jsx(la,{className:"h-4 w-4 mr-2"}),"Back to documents"]})]})]})}):!d&&!ye&&ue===ko?e.jsxs(e.Fragment,{children:[e.jsx(Co,{nestId:s,nodeId:a,title:C,snapshotVersion:null,currentEmail:F,viewOnly:ee,reviewerOnly:G,initialThreadId:l,onBack:h,onTurnedInto:()=>{Ys(b,`/nests/${s}/nodes/${a}`),oe()},onShareNest:Z&&!ve?()=>Ne(!0):void 0,visibilityControl:tn,actions:en({includeVersionHistory:!1})}),sn]}):e.jsxs("div",{className:"flex min-h-full flex-col","data-testid":"document-page",children:[e.jsxs("div",{className:"sticky top-16 z-30 flex h-12 items-center gap-2 border-b bg-background/95 px-2 backdrop-blur supports-[backdrop-filter]:bg-background/80 sm:px-3","data-testid":"document-editor-topbar",children:[e.jsxs("div",{className:"flex items-center gap-1 min-w-0 flex-1",children:[V&&D&&e.jsx(y,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:D,title:"Show sidebar","aria-label":"Show sidebar","data-testid":"document-sidebar-expand",children:e.jsx(Ii,{className:"h-4 w-4"})}),e.jsx(y,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>Me("go back",h),title:"Back to documents","data-testid":"document-editor-back",children:e.jsx(la,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-nowrap overflow-hidden",children:[e.jsx("button",{type:"button",onClick:()=>v&&Me("go to the nest",v),disabled:!v,className:"text-sm text-muted-foreground truncate hover:text-foreground hover:underline underline-offset-2 disabled:no-underline disabled:hover:text-muted-foreground disabled:cursor-default",title:v?`Open ${r}`:r,children:r}),w==null?void 0:w.map((t,i)=>e.jsxs(n.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground shrink-0",children:"›"}),e.jsx("button",{type:"button",onClick:()=>Me(`go to "${t.title}"`,()=>z==null?void 0:z(i)),className:"text-sm text-muted-foreground hover:text-foreground hover:underline underline-offset-2 truncate max-w-[160px]",title:t.title,"data-testid":`document-editor-breadcrumb-${i}`,children:t.title})]},`${t.nestId}/${t.nodeId}/${i}`)),zr.map((t,i)=>e.jsxs(n.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground shrink-0",children:"›"}),e.jsx("button",{type:"button",onClick:()=>R&&Me(`open "${t.label}"`,()=>R(t.path)),disabled:!R,className:"text-sm text-muted-foreground truncate max-w-[160px] hover:text-foreground hover:underline underline-offset-2 disabled:no-underline disabled:hover:text-muted-foreground disabled:cursor-default",title:t.path,children:t.label})]},`folder-${i}`)),!d&&ie&&e.jsx(Io,{status:ie}),!d&&Fs&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs border bg-red-50 text-red-700 border-red-200 whitespace-nowrap",title:`${me.requestedBy} asked for this to be deleted: "${me.reason}". A nest admin decides.`,"data-testid":"deletion-requested-badge",children:[e.jsx(ca,{className:"h-3 w-3"}),"Deletion requested"]}),!d&&!lt&&ie==="published"&&e.jsx("span",{className:"hidden sm:inline px-1.5 py-0.5 rounded text-xs bg-green-50 text-green-700 border border-green-200 whitespace-nowrap",title:"Stewardship off — saving auto-publishes.",children:"Auto-published"})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0","data-testid":"document-editor-actions",children:[(()=>{if(se)return e.jsxs("span",{className:"hidden sm:inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs border bg-amber-50 text-amber-800 border-amber-200 dark:bg-amber-950/40 dark:text-amber-300 dark:border-amber-900",title:"These edits are parked locally and not yet saved to the nest.","data-testid":"document-editor-dirty-badge",children:[e.jsx(kn,{className:"h-3 w-3"}),"Unsaved changes"]});const t=Ge?"Saving…":Hs?"Saved":Tt?`Edited ${Sn(Tt)}`:null;return t?e.jsx("span",{className:"hidden sm:inline px-1.5 text-xs text-muted-foreground",title:Tt?Cs(Tt):void 0,children:t}):null})(),ui&&e.jsx(Yl,{documentTitle:C,version:_e??1,onApprove:ai,onReject:ni}),tn,Z&&!ve&&e.jsxs(y,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>Ne(!0),title:"Share this nest — people, teams, visibility","data-testid":"document-editor-share",children:[e.jsx(Ls,{className:"h-4 w-4 sm:mr-1.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Share"})]}),!d&&e.jsxs(y,{variant:We?"secondary":"ghost",size:"sm",className:"h-8","aria-pressed":We,onClick:()=>{We&&(ms.current=!0,Ut(!1),At(null),zs(null),Be(null)),Lr(!We)},title:We?"Hide comments":"Show comments","data-testid":"document-editor-comments-toggle",children:[e.jsx(Ts,{className:"h-4 w-4"}),Ca>0&&e.jsx("span",{className:"ml-1 text-xs tabular-nums",children:Ca})]}),!d&&e.jsxs(or,{onOpenChange:t=>{t&&Kr()},children:[e.jsx(cr,{asChild:!0,children:e.jsxs(y,{variant:I!=null?"secondary":"ghost",size:"sm",className:"h-8",title:"Compare with a past version","data-testid":"document-editor-compare",children:[e.jsx(Dn,{className:"h-4 w-4"}),e.jsx("span",{className:I!=null?"ml-1":"hidden xl:inline ml-1",children:I!=null?`Comparing v${I}`:"Compare"}),e.jsx(dr,{className:"h-3.5 w-3.5 ml-0.5 opacity-60"})]})}),e.jsxs(ur,{align:"end",className:"w-56 max-h-80 overflow-y-auto",children:[e.jsx(mr,{children:"Diff current against…"}),I!=null&&e.jsxs(e.Fragment,{children:[e.jsxs(es,{onClick:()=>void Us(null),children:[e.jsx(et,{className:"h-4 w-4 mr-2"})," Exit compare"]}),e.jsx(hr,{})]}),U?U.versions.filter(t=>t.version!==U.currentVersion).length===0?e.jsx(es,{disabled:!0,children:"No earlier versions"}):U.versions.filter(t=>t.version!==U.currentVersion).map(t=>{var i;return e.jsxs(es,{onClick:()=>void Us(t.version),children:[I===t.version?e.jsx(Pt,{className:"h-4 w-4 mr-2"}):e.jsx("span",{className:"w-4 mr-2"}),"v",t.version,e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",title:t.editedAt?Cs(t.editedAt):void 0,children:[(i=t.editedBy)==null?void 0:i.split("@")[0],Sn(t.editedAt)].filter(Boolean).join(" · ")})]},t.version)}):e.jsxs(es,{disabled:!0,children:[e.jsx(te,{className:"h-4 w-4 mr-2 animate-spin"})," Loading…"]})]})]}),(()=>{const t=en({includeVersionHistory:!0});return t.length?e.jsx(xr,{actions:t,variant:"ghost",testId:"document-editor-more"}):null})(),Q!=="edit"&&e.jsxs(e.Fragment,{children:[!ee&&Ja&&e.jsxs(y,{variant:"outline",size:"sm",className:"h-8",onClick:()=>os(!0),"data-testid":"document-editor-submit",title:"Requires steward approval — with stewardship on, publishing in this nest submits the document for steward review.",children:[e.jsx(oa,{className:"h-4 w-4 sm:mr-1.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Submit for review"})]}),!ee&&!G&&!fe&&!dt&&e.jsxs(y,{size:"sm",className:"h-8",onClick:()=>ot("edit"),"data-testid":"document-editor-start-edit",children:[e.jsx(kn,{className:"h-4 w-4 mr-1.5"}),"Edit"]})]})]})]}),e.jsxs("div",{className:"flex flex-1 flex-col items-stretch lg:flex-row lg:items-start",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col min-h-[calc(100vh-7rem)]",children:[e.jsxs("div",{className:"w-full px-5 py-6 sm:px-10 sm:py-8",children:[Jt&&e.jsxs($e,{variant:"destructive",className:"mb-4",children:[e.jsx(Fe,{className:"h-4 w-4"}),e.jsx(Ee,{children:Jt})]}),Oa!==null&&e.jsxs($e,{className:"mb-4 border-amber-300 bg-amber-50 text-amber-800",children:[e.jsx(Fe,{className:"h-4 w-4 text-amber-600"}),e.jsxs(Ee,{className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-amber-800",children:[e.jsxs("span",{children:["Unsaved edits from this browser"," (",new Date(Oa).toLocaleString(),") ","were restored — the saved document still says something else."]}),e.jsx("button",{type:"button",onClick:Xa,className:"font-medium underline underline-offset-2 hover:no-underline","data-testid":"discard-restored-draft",children:"Discard them"})]})]}),Br&&se&&e.jsxs($e,{className:"mb-4 border-amber-300 bg-amber-50 text-amber-800",children:[e.jsx(Fe,{className:"h-4 w-4 text-amber-600"}),e.jsx(Ee,{className:"text-amber-800",children:"This browser couldn't store a local backup of your unsaved edits (storage is full or blocked). Save the document — a page reload would lose them."})]}),ye?e.jsxs("div",{className:"flex items-center justify-center py-20 text-muted-foreground",children:[e.jsx(te,{className:"h-5 w-5 animate-spin mr-2"}),"Loading document..."]}):e.jsxs("div",{className:"space-y-4",children:[!d&&ns&&e.jsx(ho,{nestId:s,nodeId:a,pending:ns,onResolved:()=>{rs(null),oe()}}),fe&&e.jsxs($e,{children:[e.jsx(Fe,{className:"h-4 w-4"}),e.jsx(Ee,{children:"This document is locked while it awaits steward review. Editing is disabled until the review is approved or rejected."})]}),Gs&&e.jsxs($e,{children:[e.jsx(Fe,{className:"h-4 w-4"}),e.jsxs(Ee,{className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:[e.jsx("span",{className:"flex-1 min-w-[16rem]",children:"This is still under review. Your edits update the same pending submission — no need to withdraw and resubmit — and the steward reviews your latest version."}),e.jsxs(y,{size:"sm",variant:"outline",className:"shrink-0",onClick:()=>void ri(),"data-testid":"document-editor-withdraw",title:"Withdraw this submission and return the document to Draft",children:[e.jsx(Fn,{className:"h-3.5 w-3.5 mr-1.5"}),"Withdraw"]})]})]}),e.jsxs("div",{children:[Q==="view"&&!d?e.jsx("h1",{className:"text-4xl font-bold leading-tight tracking-tight text-foreground","data-testid":"document-editor-title",children:C||(ye?"Loading…":"Untitled")}):e.jsxs(e.Fragment,{children:[e.jsx("input",{id:"document-editor-title",ref:Ra,value:C,onChange:t=>{Se(t.target.value),X(!0)},onBlur:gt,onKeyDown:t=>{var i,p;t.key==="Enter"&&(t.preventDefault(),hs.current?hs.current.focus():(p=(i=Na.current)==null?void 0:i.querySelector('textarea, [contenteditable="true"], input'))==null||p.focus())},placeholder:"Untitled",maxLength:120,disabled:le,required:!0,"aria-required":"true","aria-label":"Title","aria-invalid":Mt&&!C.trim()?!0:void 0,"data-testid":"document-editor-title",className:`block w-full bg-transparent text-4xl font-bold leading-tight tracking-tight text-foreground outline-none border-b border-border pb-1 focus:border-primary placeholder:text-muted-foreground/50 disabled:opacity-100${Mt&&!C.trim()?" placeholder:text-destructive/60":""}`}),(Mt&&!C.trim()||C.length>=90)&&e.jsxs("div",{className:"mt-1 flex items-start justify-between gap-2 text-xs",children:[e.jsx("span",{className:"text-destructive",children:Mt&&!C.trim()?"Title is required":""}),e.jsx("span",{className:"text-muted-foreground tabular-nums",children:C.length>=90?`${C.length}/120`:""})]})]}),!d&&Q==="edit"&&C.trim()!==_s.current.trim()&&(()=>{const t=Ul(xe,{id:a,title:_s.current});return t.length===0?null:e.jsx($e,{className:"mt-2 border-amber-300 bg-amber-50 text-amber-800",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{className:"h-4 w-4 shrink-0 text-amber-600"}),e.jsxs(Ee,{className:"text-amber-800",children:["Renaming affects ",t.length," wiki link",t.length!==1?"s":""," in other documents that reference this one by its old title (",t.slice(0,3).map(i=>i.title).join(", "),t.length>3?", …":"","). Links by slug still resolve, but their visible label keeps the old name; plain [[title]] links break."]})]})})})()]}),!d&&Dt.length>0&&e.jsx($e,{className:"border-amber-300 bg-amber-50 text-amber-800",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{className:"h-4 w-4 shrink-0 text-amber-600"}),e.jsxs(Ee,{className:"text-amber-800",children:[Dt.length," link",Dt.length!==1?"s":""," in this document show an outdated name — the target document",Dt.length!==1?"s were":" was"," renamed (",Dt.slice(0,3).map(t=>`"${t.shownAs}" → "${t.currentTitle}"`).join(", "),Dt.length>3?", …":"","). The links still work; only the visible label is out of date."]})]})}),d&&e.jsxs("div",{children:[e.jsx("label",{className:"block mb-1 text-sm font-medium",children:"Folder"}),e.jsxs("div",{className:"flex items-center flex-wrap gap-1 rounded-md border px-2 py-1.5 min-h-9","data-testid":"document-editor-folder-input",children:[e.jsx("button",{type:"button",disabled:le,onClick:()=>{Ve(""),X(!0)},className:`text-sm rounded px-1.5 py-0.5 ${Ce?"text-primary hover:bg-muted":"font-medium bg-muted"}`,title:"File directly under the nest root",children:"Root"}),Ce.split("/").filter(Boolean).map((t,i,p)=>{const T=p.slice(0,i+1).join("/"),O=p.slice(0,i).join("/"),_=i===p.length-1;return e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-muted-foreground/50 text-sm",children:"/"}),e.jsxs("span",{className:`flex items-center rounded ${_?"bg-muted":""}`,children:[e.jsx("button",{type:"button",disabled:le,onClick:()=>{Ve(T),X(!0)},className:`text-sm rounded px-1.5 py-0.5 ${_?"font-medium":"text-primary hover:bg-muted"}`,title:`Scope to ${T}`,children:aa(t)}),_&&e.jsx("button",{type:"button",disabled:le,onClick:()=>{Ve(O),X(!0)},className:"mr-0.5 rounded p-0.5 text-muted-foreground hover:text-foreground hover:bg-background",title:O?`Go up to ${O}`:"Go up to the nest root","data-testid":"folder-step-up",children:e.jsx(et,{className:"h-3 w-3"})})]})]},T)}),e.jsx(ec,{folder:Ce,folderOptions:Ea,disabled:le,onPick:t=>{Ve(t),X(!0)}}),Ce&&e.jsx("button",{type:"button",disabled:le,onClick:()=>{Ve(""),X(!0)},className:"ml-auto text-muted-foreground hover:text-foreground",title:"Clear folder (file under the nest root)",children:e.jsx(et,{className:"h-3.5 w-3.5"})})]})]}),(Ae||W.length>0)&&e.jsxs("div",{children:[e.jsxs("div",{className:"space-y-2",children:[Ae&&!le&&e.jsx("input",{value:Le,onChange:t=>qe(go(t.target.value)),onKeyDown:t=>{(t.key==="Enter"||t.key===","||t.key===" ")&&(t.preventDefault(),Ua())},onBlur:()=>{Le.trim()&&Ua()},placeholder:W.length?"Add a tag":"Add a tag…",maxLength:xo,"aria-label":"Add a tag",className:"block h-8 w-full border-b border-border bg-transparent px-1 text-sm outline-none focus:border-primary placeholder:text-muted-foreground/70 focus:placeholder:text-muted-foreground","data-testid":"document-editor-tag-input"}),W.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:W.map(t=>{const i=Q==="view"&&!!f;return e.jsxs("span",{onClick:i?p=>{p.stopPropagation(),f(t)}:void 0,className:"inline-flex items-center gap-1 rounded bg-secondary px-2 py-0.5 text-xs"+(i?" cursor-pointer hover:bg-secondary/80":""),title:i?`Filter nest by ${t}`:t,children:[e.jsx("span",{className:"truncate max-w-[16rem]",children:t}),!le&&e.jsx("button",{type:"button",onClick:p=>{p.stopPropagation(),Jr(t)},className:"hover:text-destructive","aria-label":`Remove ${t}`,children:e.jsx(et,{className:"h-3 w-3"})})]},t)})})]}),Le.trim()&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground","data-testid":"document-editor-tag-preview",children:[Ft.tags.length>0?`Will add: ${Ft.tags.join(", ")}`:"Nothing new to add",Ft.notes.length>0&&` — ${Ft.notes.join(" ")}`]})]}),lt&&di&&e.jsxs("div",{className:"flex items-start justify-between gap-4 rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-sm font-medium",children:[e.jsx(Ll,{className:"h-4 w-4"}),"Prime document"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ys&&re===null?"Inherited from a prime tag on this document — it always needs steward approval.":"Always require steward approval for this document, even from an owner or admin with auto-publish on."}),ys&&re===!1&&e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:"Exempted from its prime tag."}),Ya&&Ht&&e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:"Overrides auto-publish — your edits here queue for review like everyone else’s."})]}),e.jsx(lr,{checked:Ya,disabled:le,onCheckedChange:t=>{Xe(t===ys?null:t),X(!0)},"aria-label":"Prime document","data-testid":"document-editor-prime"})]}),!d&&(He||it.length>0)&&e.jsxs("div",{className:"flex flex-col items-start gap-1 text-xs text-muted-foreground",children:[He&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:["Created by ",e.jsx("span",{className:"font-medium text-foreground/80",title:He,children:E})]}),it.length>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",title:it.join(", "),children:["Collaborators:",e.jsx(Gl,{collaborators:it,max:5,size:"md"}),e.jsx("span",{className:"font-medium text-foreground/80",children:it.length})]})]}),Ae&&(d||Wt||Ha)&&e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 w-full",children:[(d||Ha)&&e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Type"}),e.jsx("div",{className:"inline-flex rounded-md border overflow-hidden",role:"radiogroup","aria-label":"Document type","data-testid":"document-editor-type",...B,children:[{value:"document",label:"Document",Icon:ea,on:"bg-slate-500/15 text-slate-700 dark:text-slate-300"},...ne?[{value:"artifact",label:"Artifact",Icon:ts,on:"bg-amber-500/15 text-amber-700 dark:text-amber-300"}]:[],...S?[{value:"table",label:"Table",Icon:na,on:"bg-cyan-500/15 text-cyan-700 dark:text-cyan-300"}]:[],...ae?[{value:"agent",label:"Agent",Icon:vn,on:"bg-violet-500/15 text-violet-700 dark:text-violet-300"},{value:"skill",label:"Skill",Icon:Ln,on:"bg-blue-500/15 text-blue-700 dark:text-blue-300"},{value:"tool",label:"Tool",Icon:En,on:"bg-teal-500/15 text-teal-700 dark:text-teal-300"}]:[]].map(({value:t,label:i,Icon:p,on:T},O)=>{const _=mt===t;return e.jsxs("button",{type:"button",role:"radio","aria-checked":_,title:t==="document"?"Markdown document":t==="artifact"?"Hosted HTML artifact":t==="table"?"Table — CSV fact store, queryable deterministically":t==="tool"?"Tool — the body is code an agent can call":`${i} (runnable)`,onClick:()=>{if(d){Rr(t,i);return}t!==mt&&Me("turn it into another kind",()=>fs(t))},className:`flex items-center gap-1.5 px-3 py-1.5 text-sm transition-colors ${O>0?"border-l":""} ${_?`${T} font-medium`:"text-muted-foreground hover:bg-muted/60"}`,"data-testid":`document-editor-type-${t}`,children:[e.jsx(p,{className:"h-4 w-4"}),i]},t)})}),mt==="artifact"&&e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"Hosted HTML — the body is served as a sandboxed page."}),(mt==="agent"||mt==="skill")&&e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"The body is the instructions. Add flow edges from it in the Workflows tab, then trigger a run."}),mt==="table"&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:["The body is CSV — header first, directives welcome (",e.jsx("code",{children:"sku:key, price:number, region"}),"). Agents fetch exact rows with table-query instead of reading it whole."]}),mt==="tool"&&e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"The body is code. Wire it to an agent on the canvas and the runner ships it (plus the nest's env vars) in the run bundle."})]}),Wt&&e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("label",{htmlFor:"document-editor-schedule",className:"block text-sm font-medium mb-1",children:["Schedule"," ",e.jsx("span",{className:"font-normal text-muted-foreground",children:"(cron / interval — optional)"})]}),e.jsx("input",{id:"document-editor-schedule","data-testid":"document-editor-schedule",type:"text",value:ge,placeholder:"e.g. 0 6 * * * or @daily or @every 15m","aria-invalid":xt.kind==="invalid",onChange:t=>{Re(t.target.value),X(!0)},onBlur:gt,className:`w-full rounded-md border bg-background px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-ring ${xt.kind==="invalid"?"border-destructive focus:ring-destructive":""}`}),e.jsx("p",{"data-testid":"document-editor-schedule-feedback",className:`mt-1 text-xs ${xt.kind==="invalid"?"text-destructive":"text-muted-foreground"}`,children:xt.kind==="invalid"?e.jsxs(e.Fragment,{children:["Doesn't look like a cron/interval schedule — ",xt.error,"."]}):xt.kind==="valid"?e.jsxs(e.Fragment,{children:[xt.description,". Opaque to this server — an external orchestrator parses it and runs the"," ",je==="skill"||ue==="skill"?"skill":"agent","."]}):e.jsxs(e.Fragment,{children:["Opaque to this server — an external orchestrator parses it and runs the"," ",je==="skill"||ue==="skill"?"skill":"agent",". Leave blank for none."]})})]})]}),Wt&&e.jsxs("div",{className:"w-full rounded-md border border-dashed bg-muted/40 px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:["Orchestrator fetch — this ",ue==="skill"||je==="skill"?"skill":"agent"," appears here"]}),e.jsx(y,{variant:"ghost",size:"sm",className:"h-6 px-2 shrink-0",onClick:$r,title:"Copy URL",children:Tr?e.jsx(Pt,{className:"h-3 w-3 text-green-600"}):e.jsx(el,{className:"h-3 w-3"})})]}),e.jsxs("code",{className:"block text-[11px] font-mono break-all text-foreground/80",children:["GET ",va]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"Returns every runnable node (approved agent/skill) with its schedule + content, so an external scheduler can discover what to run and when."})]}),e.jsx("div",{className:"flex flex-col lg:flex-row gap-6 items-start",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[he&&I==null&&e.jsxs("div",{className:"mb-2 flex items-center gap-2 rounded-md border border-amber-300 bg-amber-50/70 dark:bg-amber-950/20 px-3 py-1.5 text-xs text-amber-900 dark:text-amber-200",children:[e.jsx(Ts,{className:"h-3.5 w-3.5 shrink-0"}),"Comment mode — select any text to pin a comment, or click a highlighted phrase to open its thread. Editing is paused."]}),e.jsxs("div",{ref:Na,onClick:()=>{he||ee||fe||ct||De!=="table"&&(dt||Q==="view"&&!G&&ot("edit"))},children:[dt&&e.jsx(Al,{nestId:s,nodeId:a,title:C,pdf:be,canReplace:!ee&&!G&&!fe&&!ve,onReplaced:()=>{Ys(b,`/nests/${s}/nodes/${a}`),oe()}}),(ct||De==="tool"||De==="table")&&e.jsx("div",{className:"mb-1 text-xs font-medium text-muted-foreground",children:ct?"Artifact HTML":De==="tool"?"Tool source (code)":"Table data (CSV)"}),I!=null?e.jsxs("div",{"data-testid":"document-editor-inline-diff",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Dn,{className:"h-4 w-4"}),"Diff: v",I," → current (v",(U==null?void 0:U.currentVersion)??_e??"?",")",se&&e.jsx("span",{className:"rounded bg-amber-100 text-amber-800 dark:bg-amber-950/40 dark:text-amber-300 px-1.5 py-px text-[10px] font-semibold uppercase",children:"incl. unsaved edits"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("div",{className:"flex rounded-md border overflow-hidden text-xs",children:[e.jsx("button",{type:"button",className:`px-2 py-1 ${Rt?"text-muted-foreground hover:bg-muted/50":"bg-secondary font-medium"}`,onClick:()=>rt(!1),children:"Source"}),e.jsx("button",{type:"button",className:`px-2 py-1 ${Rt?"bg-secondary font-medium":"text-muted-foreground hover:bg-muted/50"}`,onClick:()=>rt(!0),children:"Rendered"})]}),e.jsxs(y,{variant:"ghost",size:"sm",className:"h-7",onClick:()=>void Us(null),children:[e.jsx(et,{className:"h-4 w-4 mr-1"})," Exit diff"]})]})]}),(()=>{const t=Ws&&Ws.version===I?Ws:null;if(!t)return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground p-4 border rounded-lg",children:[e.jsx(te,{className:"h-4 w-4 animate-spin"})," Loading version"," ",I,"…"]});if(Rt){const i=De==="table"?Dl(t.content||"",$):null,p=(T,O)=>i?e.jsx(fa,{columns:i[T].columns,rows:i[T].rows,rowClassName:_=>i[T].changed[_]?T==="past"?"bg-red-50 dark:bg-red-950/30":"bg-emerald-50 dark:bg-emerald-950/30":""}):e.jsx(ra,{content:O,className:"px-4 py-3"});return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"bg-muted px-3 py-1.5 text-xs font-medium text-muted-foreground border-b",children:["v",I]}),p("past",t.content||"")]}),e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"bg-muted px-3 py-1.5 text-xs font-medium text-muted-foreground border-b",children:["current (v",(U==null?void 0:U.currentVersion)??_e??"?",")"]}),p("current",$)]})]})}return e.jsx(gr,{patch:Ql(t.content||"",$),className:"max-h-none border rounded-lg"})})()]}):Vs&&Q==="edit"&&!he?De==="table"?e.jsx(vo,{value:$,onChange:t=>{le||(q(t),X(!0))},onBlur:gt,readOnly:le}):e.jsxs("div",{className:$.trim()?"grid gap-3 lg:grid-cols-2":"",children:[e.jsx("textarea",{value:$,onChange:t=>{le||(q(t.target.value),X(!0))},onBlur:gt,readOnly:le,spellCheck:!1,placeholder:"The body is code — paste or write the tool's source.",className:"w-full min-h-[400px] border rounded-lg bg-background shadow-sm p-4 font-mono text-sm leading-relaxed resize-y focus:outline-none focus:ring-2 focus:ring-ring","data-testid":"tool-source-editor"}),$.trim()&&e.jsxs("div",{className:"min-w-0 flex flex-col min-h-[400px] rounded-lg border bg-background shadow-sm overflow-hidden",children:[e.jsx("div",{className:"bg-muted px-3 py-1.5 text-xs font-medium text-muted-foreground border-b",children:"Preview"}),e.jsx(qn,{code:Zr,className:"flex-1 text-sm","data-testid":"tool-source-preview"})]})]}):Ps?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(y,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>ba(!1),title:"Back to the rich editor","data-testid":"document-editor-rich-toggle",children:[e.jsx(ts,{className:"h-3.5 w-3.5 mr-1.5"}),"Rich editor"]})}),e.jsx("textarea",{value:$,onChange:t=>{le||(q(t.target.value),X(!0))},onBlur:gt,readOnly:le,spellCheck:!1,placeholder:"# Raw markdown",className:"w-full min-h-[400px] border rounded-lg bg-background shadow-sm p-4 font-mono text-sm leading-relaxed resize-y focus:outline-none focus:ring-2 focus:ring-ring","data-testid":"document-editor-raw-markdown"})]}):ct?e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsx("textarea",{value:$,onChange:t=>{q(t.target.value),X(!0)},onBlur:gt,placeholder:"Paste the artifact's HTML (a self-contained slide deck, dashboard, infographic)…",spellCheck:!1,className:"w-full min-h-[360px] rounded-lg border bg-background p-3 font-mono text-xs leading-relaxed shadow-sm focus:outline-none focus:ring-1 focus:ring-primary"}),e.jsxs("div",{className:"rounded-lg border overflow-hidden flex flex-col min-h-[360px]",children:[e.jsx("div",{className:"bg-muted px-3 py-1.5 text-xs font-medium text-muted-foreground border-b",children:"Preview"}),Wa.trim()?e.jsx("iframe",{srcDoc:Wa,title:"Artifact preview",sandbox:"allow-scripts allow-popups allow-modals",className:"w-full flex-1 bg-white","data-testid":"artifact-draft-preview"}):e.jsx("p",{className:"flex-1 flex items-center justify-center text-xs text-muted-foreground",children:"Paste HTML to see it render here."})]})]}):(he||Q==="view")&&(Vs||!ks($))?e.jsx("div",{ref:Qt,onMouseUp:d?void 0:Ar,onClick:d?void 0:Fr,onMouseMove:d?void 0:Pr,className:"min-h-[300px] cursor-text","data-testid":"document-view-surface",children:De==="table"&&!d?e.jsx("div",{className:"p-4",children:e.jsx(wo,{nestId:s,nodeId:a,csv:$})}):De==="tool"?e.jsx(qn,{code:$,"data-testid":"tool-source-view"}):e.jsx(ra,{content:$,onWikiLinkClick:(t,i)=>Ia(t,null,i),previewFor:_r})}):e.jsx(Ml,{ref:hs,content:$,onChange:t=>{q(t),X(!0)},onSave:Qa,onBlur:gt,nestId:s,currentNodeId:d?void 0:a,editable:!le,onRequestDocLink:()=>ga(!0),onUploadImage:async t=>{const{url:i}=await tl(s,t);return i},onWikiLinkClick:Ia,placeholder:"Start writing, or select text to format it…",autofocus:!1,variant:"page",toolbarEnd:e.jsx(e.Fragment,{children:!Vs&&I==null&&!ct&&e.jsxs(y,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>ba(!0),title:"Edit the raw markdown","data-testid":"document-editor-markdown-toggle",children:[e.jsx(ts,{className:"h-3.5 w-3.5 sm:mr-1.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Markdown"})]})})})]})]})}),Gt&&!ee&&e.jsxs("button",{type:"button","data-testid":"selection-comment-button",onMouseDown:t=>t.preventDefault(),onClick:Dr,style:{position:"fixed",left:Gt.x,top:Gt.y-40,transform:"translateX(-50%)",zIndex:50},className:"flex items-center gap-1 rounded-md bg-foreground text-background px-2.5 py-1.5 text-xs font-medium shadow-lg hover:opacity-90",children:[e.jsx(jr,{className:"h-3.5 w-3.5"})," Comment"]}),Q==="view"&&Zt.length>0&&e.jsxs("div",{className:"border rounded-lg bg-muted/20 p-3",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground mb-2",children:["Linked from ",Zt.length," document",Zt.length!==1?"s":""]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Zt.map(t=>e.jsx("button",{type:"button",className:"text-sm text-primary hover:underline text-left",onClick:()=>Me(`open "${t.title}"`,()=>x==null?void 0:x(s,t.id,C)),children:t.title},t.id))})]}),Q==="view"&&Ma.length>0&&e.jsxs("div",{className:"border rounded-lg bg-muted/20 p-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Related documents"}),e.jsx("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:Ma.map((t,i)=>e.jsxs(n.Fragment,{children:[i>0&&e.jsx("span",{"aria-hidden":!0,className:"text-muted-foreground/50",children:"·"}),e.jsx("button",{type:"button",className:"text-sm text-primary hover:underline text-left",title:t.sharedTags.length?`Shared tags: ${t.sharedTags.join(", ")}`:"Shared links",onClick:()=>Me(`open "${t.title}"`,()=>x==null?void 0:x(s,t.id,C)),children:t.title})]},t.id))})]}),Q==="view"&&ws.length>0&&e.jsxs("div",{className:"border rounded-lg bg-muted/20 p-3",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground mb-2",children:["Mentioned in ",ws.length," document",ws.length!==1?"s":""," without a link"]}),e.jsx("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:ws.map((t,i)=>e.jsxs(n.Fragment,{children:[i>0&&e.jsx("span",{"aria-hidden":!0,className:"text-muted-foreground/50",children:"·"}),e.jsx("button",{type:"button",className:"text-sm text-primary hover:underline text-left",onClick:()=>Me(`open "${t.title}"`,()=>x==null?void 0:x(s,t.id,C)),children:t.title})]},t.id))})]})]})]}),Q==="edit"&&e.jsx("div",{className:"sticky bottom-0 z-20 mt-auto flex items-center justify-center gap-2 border-t bg-background/95 px-4 py-2 backdrop-blur supports-[backdrop-filter]:bg-background/80","data-testid":"document-editor-actions-bottom",children:(()=>{const t=!ee&&!G&&!fe,i=!ee&&Ja;return e.jsxs(e.Fragment,{children:[t&&!d&&Ae&&(ie==="draft"||ie==="rejected")&&e.jsxs(y,{variant:"ghost",size:"sm",className:"h-8 text-muted-foreground",disabled:za,onClick:()=>Bs(!0),"data-testid":"document-editor-discard",children:[e.jsx(Fn,{className:"h-4 w-4 sm:mr-1.5"}),e.jsx("span",{className:"hidden sm:inline",children:za?"Discarding…":"Discard draft"})]}),i&&e.jsxs(y,{variant:"outline",size:"sm",className:"h-8",onClick:()=>os(!0),"data-testid":"document-editor-submit",title:"Requires steward approval — with stewardship on, publishing in this nest submits the document for steward review.",children:[e.jsx(oa,{className:"h-4 w-4 sm:mr-1.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Submit for review"})]}),t&&e.jsxs(y,{size:"sm",className:"h-8",onMouseDown:p=>p.preventDefault(),onClick:Qa,disabled:!Ba,"data-testid":"document-editor-save",children:[Ge?e.jsx(te,{className:"h-4 w-4 mr-1.5 animate-spin"}):Hs&&!se?e.jsx(Pt,{className:"h-4 w-4 mr-1.5"}):e.jsx(Mn,{className:"h-4 w-4 mr-1.5"}),Ge?"Saving…":Hs&&!se?"Saved":d?"Create":"Save"]})]})})()})]}),!d&&e.jsxs("aside",{className:`w-full shrink-0 border-t lg:w-80 lg:border-t-0 lg:border-l lg:sticky lg:top-28 lg:self-start lg:max-h-[calc(100vh-7rem)] flex flex-col min-h-0 max-h-[70vh] px-4 py-4${We||qs?"":" hidden"}`,"data-testid":"document-comments-rail","aria-hidden":!We&&!qs,children:[!We&&qs&&e.jsxs("nav",{className:"flex flex-col min-h-0 rounded-lg border border-border bg-card p-5","aria-label":"Outline",children:[e.jsx("div",{className:"mb-4 border-b pb-3 text-sm font-semibold",children:"Outline"}),e.jsx("div",{className:"space-y-0.5 overflow-y-auto min-h-0",children:Sa.map(t=>e.jsx("button",{type:"button",className:"block w-full text-left text-sm text-primary hover:underline truncate",style:{paddingLeft:`${(t.level-1)*12}px`},title:t.text,onClick:i=>{var p;i.stopPropagation(),(p=document.getElementById(t.id))==null||p.scrollIntoView({behavior:"smooth",block:"start"})},children:t.text},t.id))})]}),e.jsx("div",{className:We?"flex flex-col flex-1 min-h-0":"hidden",children:e.jsx(Ao,{nestId:s,nodeId:a,readOnly:ee,pendingAnchor:Os,onClearAnchor:()=>zs(null),onFocusAnchor:Mr,onThreadsChange:Er,activeThreadId:Kt,commentMode:he,onSetCommentMode:t=>{Ut(t),t&&ot("view"),Be(null),t||At(null)}})})]})]}),Ct&&!d&&e.jsx(wr,{open:!0,onClose:()=>zt(!1),title:C||a,versionData:U,onLoadContent:async t=>(await ta(s,a,t)).content,onRestore:Ae?async t=>{try{await tr(s,a,t),N.success(`Reverted to version ${t}`),await Promise.all([oe(),Je()])}catch(i){N.error((i==null?void 0:i.message)||"Revert failed")}}:void 0,onDiscard:Ae?async()=>{try{const{version:t}=await jn(s,a);N.success(`Draft discarded — back to version ${t}`),await Promise.all([oe(),Je()])}catch(t){N.error((t==null?void 0:t.message)||"Discard failed")}}:void 0}),!d&&e.jsx(lo,{isOpen:ls,onClose:()=>os(!1),documentTitle:C,currentVersion:_e??1,onSubmit:si}),e.jsx(Fl,{isOpen:Cr,onClose:()=>ga(!1),nestId:s,excludeNodeId:d?void 0:a,onSelect:mi}),e.jsx(bt,{open:Ze!==null,onOpenChange:t=>{!t&&!ps&&fs(null)},children:e.jsxs(wt,{className:"sm:max-w-[480px]",children:[(()=>{const t=gs.find(p=>p.value===Ze),i=t==null?void 0:t.Icon;return e.jsxs(e.Fragment,{children:[e.jsx(vt,{children:e.jsxs(jt,{children:["Turn into ",(t==null?void 0:t.label)??"","?"]})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Changes what kind of node this is. The body is kept as it is — edit it afterwards if the new kind expects something else."}),t&&i&&e.jsxs("div",{className:"flex items-start gap-3 rounded-md border bg-muted/40 px-3 py-2 text-sm","data-testid":`document-editor-turn-into-${t.value}`,children:[e.jsx(i,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsxs("span",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:t.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:t.expects})]})]})]})})(),e.jsxs(yt,{children:[e.jsx(y,{variant:"outline",onClick:()=>fs(null),disabled:ps,children:"Cancel"}),e.jsxs(y,{onClick:()=>void qr(),disabled:ps||!Ze,"data-testid":"document-editor-turn-into-confirm",children:[ps?e.jsx(te,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Turn into ",((pn=gs.find(t=>t.value===Ze))==null?void 0:pn.label)??""]})]})]})}),sn,ft&&e.jsx(bt,{open:!0,onOpenChange:()=>pt(null),children:e.jsxs(wt,{className:"sm:max-w-[460px]",children:[e.jsx(vt,{children:e.jsx(jt,{children:"Unsaved changes"})}),e.jsxs("p",{className:"text-sm text-muted-foreground py-2",children:["You have unsaved changes in this document. Save them before you ",ft.label,", or discard to leave without saving."]}),Jt&&e.jsxs($e,{variant:"destructive",children:[e.jsx(Fe,{className:"h-4 w-4"}),e.jsx(Ee,{children:Jt})]}),e.jsxs(yt,{children:[e.jsx(y,{variant:"outline",onClick:()=>pt(null),disabled:Ge,children:"Cancel"}),e.jsx(y,{variant:"outline",onClick:ti,disabled:Ge,children:"Discard"}),e.jsxs(y,{onClick:ei,disabled:Ge,children:[Ge?e.jsx(te,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Mn,{className:"h-4 w-4 mr-2"}),"Save & leave"]})]})]})}),cs&&e.jsx(bt,{open:!0,onOpenChange:()=>ds(null),children:e.jsxs(wt,{className:"sm:max-w-[460px]",children:[e.jsx(vt,{children:e.jsxs(jt,{children:["Switch to ",cs.label,"?"]})}),e.jsxs("p",{className:"text-sm text-muted-foreground py-2",children:["Your existing content will stay as-is, but it will now be interpreted as ",Jn(us(cs.value))," ","instead of ",Jn(us(je)),". Nothing is converted automatically — review the body after switching."]}),e.jsxs(yt,{children:[e.jsx(y,{variant:"outline",onClick:()=>ds(null),children:"Cancel"}),e.jsx(y,{onClick:()=>{wa(cs.value),ds(null)},children:"Switch anyway"})]})]})}),e.jsx(Il,{open:Gr,onOpenChange:Bs,children:e.jsxs(eo,{children:[e.jsxs(to,{children:[e.jsxs(so,{children:['Discard the draft of "',C||a,'"?']}),e.jsx(ao,{children:"The document goes back to its last approved version. If it was never approved, it is deleted instead. This can't be undone."})]}),e.jsxs(no,{children:[e.jsx(ro,{children:"Cancel"}),e.jsx(io,{onClick:()=>void Qr(),"data-testid":"document-editor-discard-confirm",children:"Discard draft"})]})]})})]})}function Io({status:s}){const a={draft:{label:"Draft",cls:"bg-muted text-muted-foreground"},pending_review:{label:"Pending review",cls:"bg-amber-100 text-amber-800 dark:bg-amber-950 dark:text-amber-300"},approved:{label:"Approved",cls:"bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-300"},published:{label:"Published",cls:"bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-300"},rejected:{label:"Rejected",cls:"bg-red-100 text-red-800 dark:bg-red-950 dark:text-red-300"},external_edit_pending:{label:"External edit",cls:"bg-orange-100 text-orange-800 dark:bg-orange-950 dark:text-orange-300"}}[s];return a?e.jsx("span",{className:`shrink-0 inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${a.cls}`,"data-testid":`document-status-${s}`,children:a.label}):null}function ec({folder:s,folderOptions:r,disabled:a,onPick:o}){const[l,u]=n.useState(""),h=s.split("/").filter(Boolean).length>=Rn,m=n.useMemo(()=>{const f=new Set;for(const v of r)if(s){if(v===s||!v.startsWith(`${s}/`))continue;f.add(v.slice(s.length+1).split("/")[0])}else f.add(v.split("/")[0]);return[...f].sort()},[s,r]),x=()=>{if(h)return;const f=l.trim().replace(/\/+/g,"-");f&&(o(s?`${s}/${f}`:f),u(""))};return e.jsxs(or,{modal:!1,children:[e.jsx(cr,{asChild:!0,children:e.jsx(y,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-1.5 text-muted-foreground",disabled:a,title:"Open a subfolder or create a new one","data-testid":"folder-step-picker",children:e.jsx(dr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ur,{align:"start",className:"min-w-56",children:[m.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(mr,{children:s?"Subfolders":"Existing folders"}),m.map(f=>e.jsxs(es,{onSelect:()=>o(s?`${s}/${f}`:f),children:[e.jsx(cl,{className:"h-3.5 w-3.5 mr-2 text-blue-500"}),aa(f)]},f)),e.jsx(hr,{})]}),h?e.jsxs("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:["Max folder depth (",Rn,") reached — can't nest deeper."]}):e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1.5",onKeyDown:f=>f.stopPropagation(),children:[e.jsx(Vl,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsx(er,{value:l,onChange:f=>u(f.target.value),onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),x())},placeholder:"New subfolder…",className:"h-7 text-sm"})]})]})]})}export{Rc as DocumentEditor,Rc as default};
@@ -1,6 +0,0 @@
1
- import{c as Gs,j as e,e as Ye,w as Et,u as Qs,Y as He,l as ke,r as n,co as Ys,b_ as Js,b$ as Xs,c1 as Zs,bJ as ea,I as Ie,ah as ee,ai as te,aj as se,ak as ae,al as f,c_ as ta,c2 as sa,bK as Rt,aK as Vt,a5 as We,B as j,a_ as Bt,L as Ke,am as H,bN as aa,D as Ot,z as qt,G as zt,H as Ht,K as It,eh as ra,ag as Ue,a9 as la,i as b,m as oa,y as na,ei as ia,aq as Wt,an as Kt,aL as ca,ej as da,c5 as ua,aB as ma,aC as ha,as as pa,at as xa,av as ga,ax as I,ay as fa}from"./index-WYDmEOfO.js";import{e as va,f as ya,S as ja,P as ba,i as Na,V as wa,n as Ca,A as Sa,H as Ut}from"./backlinks-Cqcn7n1J.js";import{j as ka,z as Da,n as Ge,U as Ta,F as Fa,E as $a}from"./MarkdownEditor-CKh4WSn-.js";import{S as Ma}from"./SubmitForReviewModal-Biq3m79i.js";import{F as Pa}from"./file-exclamation-point-BevGZgtj.js";import{C as _a}from"./circle-x-DkIG68H7.js";import{C as Je}from"./circle-check-Bw_aTXiH.js";import{C as La,g as Aa,h as Gt,i as S,S as Qt,T as Yt,D as Jt,F as Ea,N as Xt,t as Ra}from"./NestView-EW-sraEb.js";import{f as Va}from"./folder-target-CUSWqImF.js";import{X as de}from"./x-mNtADYHc.js";import{F as De}from"./folder-input-m8UBV4fA.js";import{S as Zt}from"./share-2-CxmXRt58.js";import{T as ue}from"./trash-2-B0HyPTnI.js";import{S as es}from"./send-DdfwnIrj.js";import"./client-attribution-BraarYaP.js";import"./arrow-left-CWIsv-sG.js";import"./zap-D2ifcnYb.js";import"./index-BOVYgMvj.js";import"./chevron-left-CK_ZPFm9.js";import"./alert-dialog-BvF3NFr7.js";import"./NestPageHeader-Cizo8nUi.js";import"./count-skeleton-DToLM74B.js";import"./PersonCombobox-BKI7dff4.js";import"./tag-DeYC_mRv.js";import"./user-plus-Ckm_Isyc.js";import"./ReviewActions-CS8JXgXF.js";import"./settings-DKX0Q4gO.js";/**
2
- * @license lucide-react v0.577.0 - ISC
3
- *
4
- * This source code is licensed under the ISC license.
5
- * See the LICENSE file in the root directory of this source tree.
6
- */const Ba=[["path",{d:"M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34",key:"o6klzx"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z",key:"zhnas1"}]],Oa=Gs("file-pen",Ba),ts={draft:{label:"Draft",icon:Oa,className:"bg-gray-100 text-gray-700 border-gray-200"},pending_review:{label:"Pending Review",icon:La,className:"bg-amber-100 text-amber-700 border-amber-200"},approved:{label:"Approved",icon:Je,className:"bg-green-100 text-green-700 border-green-200"},published:{label:"Published",icon:Je,className:"bg-green-100 text-green-700 border-green-200"},rejected:{label:"Rejected",icon:_a,className:"bg-red-100 text-red-700 border-red-200"},external_edit_pending:{label:"External Edit",icon:Pa,className:"bg-orange-100 text-orange-700 border-orange-200"}};function qa({status:a,approvedVersion:m,currentVersion:l,showIcon:h=!0,size:v="default",className:i}){const u=ts[a]||ts.draft,w=u.icon,D=(a==="approved"||a==="published")&&m&&l&&m<l;return e.jsxs(Ye,{variant:"outline",className:Et("!rounded-sm",u.className,v==="sm"&&"text-[10px] px-1.5 py-0",i),children:[h&&e.jsx(w,{className:Et("mr-1",v==="sm"?"h-3 w-3":"h-3.5 w-3.5")}),u.label,D&&e.jsxs("span",{className:"ml-1 text-[10px] opacity-75",children:["(v",m,")"]})]})}function ss(a){return a.replace(/^#/,"").toLowerCase()}function as(a,m){var D;const{search:l,status:h,tags:v,author:i,updatedAfter:u,type:w}=m;if(h&&h!=="all"&&a.status!==h||w&&w!=="all"&&(a.type||"document")!==w||i&&i!=="all"&&(a.author??"").toLowerCase()!==i.toLowerCase())return!1;if(u!=null){const T=a.updated_at?Date.parse(a.updated_at):NaN;if(Number.isNaN(T)||T<u)return!1}if(l){const T=l.toLowerCase(),re=((D=a.title)==null?void 0:D.toLowerCase().includes(T))??!1,me=Array.isArray(a.tags)?a.tags.some(Te=>Te.toLowerCase().includes(T)):!1;if(!re&&!me)return!1}if(v&&v.length>0){const T=new Set((a.tags??[]).map(ss));if(!v.every(re=>T.has(ss(re))))return!1}return!0}function za(a){const m=a.startsWith("nodes/")?a.slice(6):a,l=m.lastIndexOf("/");return l>0?m.slice(0,l):""}function ls(a){return!!a.search||a.status!=="all"||a.type!=="all"||a.tags.length>0||a.author!=="all"||a.datePreset!=="any"}function Ha(a){return(ls({search:a.search,status:a.status,type:a.type,author:a.author,tags:a.tags,datePreset:a.updatedAfter?"on":"any"})?a.fullNodes??a.levelNodes:a.levelNodes).filter(h=>{if(a.folderFilter!==null){const v=za(h.id||"");if(v!==a.folderFilter&&!v.startsWith(`${a.folderFilter}/`))return!1}return as(h,{status:a.status,tags:a.tags,author:a.author,updatedAfter:a.updatedAfter,type:a.type})?a.search?as(h,{search:a.search})||a.contentHits.has(h.id):!0:!1})}function Ia(a){return a.visibleCount>0?!1:a.filtering||a.folderCount===0}const Wa=3;function Ka(a,m=Wa){const l=new Map;for(const i of a)for(const u of new Set(i.tags??[]))l.set(u,(l.get(u)??0)+1);const h=[...l.entries()].sort((i,u)=>u[1]-i[1]||i[0].localeCompare(u[0])).map(([i,u])=>({tag:i,count:u})),v=a.filter(i=>i.updated_at).sort((i,u)=>String(u.updated_at).localeCompare(String(i.updated_at))).slice(0,m).map(i=>({id:i.id,title:i.title??i.id,type:i.type||"document",updated_at:i.updated_at}));return{tags:h,recent:v}}function rs(a,m){const l=a||"",h=m||"";return l>h?l:h}function Ua(a){const m=new Set,l=[];let h=!1;for(const i of a)for(const u of va(i.content??"")){h=!0;const w=ka(a,u);w?w.id!==i.id&&m.add(w.id):l.push({sourceId:i.id,sourceTitle:i.title,target:u})}return{orphans:h?a.filter(i=>!m.has(i.id)).map(i=>({id:i.id,title:i.title})):[],broken:l}}const Ga={"7d":7,"30d":30,"90d":90,"1y":365};function Qa(a,m){if(!(!a||a==="any"))return m-Ga[a]*24*60*60*1e3}function Ya(a,m){const l=m.name.toLowerCase();return[...a.filter(h=>h.name.toLowerCase()!==l),m]}function Ja(a,m){const l=m.toLowerCase();return a.filter(h=>h.name.toLowerCase()!==l)}function Xa(a){if(!a)return[];try{const m=JSON.parse(a);return Array.isArray(m)?m.filter(l=>l&&typeof l.name=="string"&&l.name.trim()).map(l=>({name:String(l.name),search:typeof l.search=="string"?l.search:void 0,status:typeof l.status=="string"?l.status:void 0,tags:Array.isArray(l.tags)?l.tags.filter(h=>typeof h=="string"):void 0,author:typeof l.author=="string"?l.author:void 0,datePreset:typeof l.datePreset=="string"?l.datePreset:void 0})):[]}catch{return[]}}function Za(a){return JSON.stringify(a)}const Qe={search:"",tags:[],status:"all",type:"all",author:"all",datePreset:"any"};function Fr({nestId:a,initialSearch:m,initialTags:l,initialLoad:h,loading:v,nodes:i,census:u,knownFolders:w,folderFilter:D,setFolderFilter:T,expandedFolders:re,loadingFolders:me,toggleFolderExpanded:Te,expandFolder:os,caps:ns,isAdmin:is,isOwner:Xe,roles:cs,permission:er,currentEmail:le,myStewards:ds,stewardshipEnabled:Fe,allowSelfApprove:us,primeTags:ms,visibility:tr,hasRoleOnNode:hs,canReviewNode:ps,reviewQueue:xs,reviewableQueue:gs,deletionRequests:W,stats:fs,onOpenDocument:A,onReview:Ze,onRefresh:vs,onWithdrawDeletion:et,importInputRef:ys}){var kt,Dt,Tt,Ft;const{canManage:g,collabCanWrite:js,canEditDocs:he,isReadOnly:tt}=ns,bs=Qs(),K=((kt=He(ke.commentCounts(a)).data)==null?void 0:kt.counts)??{},E=vs,[oe,st]=n.useState(null),[U,at]=n.useState(null),Ns=He({...ke.nodes(a),enabled:!!U}),ws=U?ya(((Dt=Ns.data)==null?void 0:Dt.nodes)??[],U).length:0,[M,rt]=n.useState(null),[$e,lt]=n.useState(null),Me=n.useMemo(()=>{const s=new Map;for(const t of W)(t.targetType??"document")==="document"&&!s.has(t.nodeId)&&s.set(t.nodeId,t);return s},[W]),Cs=n.useMemo(()=>new Set(W.filter(s=>s.targetType==="folder"&&s.status==="pending").map(s=>s.nodeId)),[W]),ot=s=>Cs.has(s),Ss=n.useMemo(()=>{const s=new Map;for(const t of W)t.targetType==="folder"&&t.status==="pending"&&!s.has(t.nodeId)&&s.set(t.nodeId,t);return s},[W]),[pe,nt]=n.useState(null),[P,xe]=n.useState(null),[_,it]=n.useState(null),[ks,Ds]=n.useState({versions:[],approvedVersion:null,currentVersion:0}),Ts=s=>{const t=i.find(r=>{const d=S(r.id||"");return d===s||d.startsWith(`${s}/`)});return Va(s,(t==null?void 0:t.id)??null)},ct=async(s,t)=>{if(S(s)===t)return!0;const r=t?H(t):"nest root",d=b.loading(`Moving to ${r}…`);try{const{node:x,previousId:y}=await Kt(a,s,t),L=S(y);return b.success(t?`Moved to ${r}`:"Moved to nest root",{id:d,action:{label:"Undo",onClick:async()=>{try{await Kt(a,x.id,L),b.success("Move undone"),E()}catch(c){console.error("[NestView] undo move failed",a,x.id,c),b.error((c==null?void 0:c.message)||"Undo failed")}}},duration:6e3}),E(),!0}catch(x){return console.error("[NestView] moveNode failed",a,s,t,x),b.error((x==null?void 0:x.message)||"Move failed",{id:d}),!1}},[R,ge]=n.useState(null),[Pe,dt]=n.useState(""),[fe,ut]=n.useState(!1),[G,ve]=n.useState(null),V=Aa(G??""),mt=G===null?Pe:V.path,Fs=n.useMemo(()=>((u==null?void 0:u.folders)??[]).map(s=>s.path).sort(Gt),[u]),ht=new Map;for(const s of xs)ht.set(s.nodeId,s.requestedBy.toLowerCase());const ye=s=>s?s.myGrant==="write"?!0:tt?!1:g||js?!0:ds.some(t=>{if(t.role!=="editor")return!1;if(t.scope==="nest")return!0;if(t.scope==="document")return t.nodePattern===s.id;if(t.scope==="tag"){const r=(t.tagName||"").toLowerCase().replace(/^#+/,"");return(s.tags||[]).map(d=>d.toLowerCase().replace(/^#+/,"")).includes(r)}return!1}):!1,$s=new Set(gs.map(s=>s.nodeId)),je=async s=>{it(s);try{const t=await bs.fetchQuery(ke.nodeVersions(a,s.id));Ds(t)}catch(t){console.error("[NestView] getNodeVersions failed",a,s==null?void 0:s.id,t)}},Ms=async(s,t)=>{if(P)try{await ca(a,P.id,s,t),b.success("Submitted for review"),xe(null),E()}catch(r){console.error("[NestView] submitForReview failed",a,P==null?void 0:P.id,r),b.error((r==null?void 0:r.message)||"Submit failed")}},Ps=async()=>{const s=U;try{await ma(a,s.id),E()}catch(t){throw console.error("[NestView] deleteNode failed",a,s==null?void 0:s.id,t),t}},_s=async s=>{await ha(a,oe.id,s),b.success("Deletion requested — a nest admin will review it"),E()},Ls=async s=>{const t=M;if(g){const{deleted:r}=await da(a,t.path);b.success(r===0?`Deleted ${t.label}`:`Deleted ${t.label} — ${r} document${r===1?"":"s"}`)}else await ua(a,"folder",t.path,s),b.success("Deletion requested — a nest admin will review it");E()},k=D??"",As=k?k.split("/").length:0,[_e,Es]=n.useState(!1),pt=He({...ke.nodes(a),enabled:_e}),Q=_e?((Tt=pt.data)==null?void 0:Tt.nodes)??null:null,Rs=_e&&pt.isLoading,Le=n.useCallback(()=>Es(!0),[]),[o,be]=n.useState({...Qe,search:m??"",tags:l??[]}),C=(s,t)=>be(r=>({...r,[s]:t})),xt=s=>be(t=>({...t,tags:t.tags.includes(s)?t.tags.filter(r=>r!==s):[...t.tags,s]})),[Ne,Vs]=n.useState("activity"),[B,gt]=n.useState(()=>{try{return localStorage.getItem("nest:viewMode")==="cards"?"cards":"list"}catch{return"list"}});n.useEffect(()=>{try{localStorage.setItem("nest:viewMode",B)}catch{}},[B]);const Ae=`nest:${a}:savedFilters`,[we,Ee]=n.useState([]);n.useEffect(()=>{try{Ee(Xa(localStorage.getItem(Ae)))}catch{Ee([])}},[Ae]);const ft=s=>{Ee(s);try{localStorage.setItem(Ae,Za(s))}catch{}},[Bs,Ce]=n.useState(!1),[Re,vt]=n.useState(""),yt=()=>{const s=Re.trim();s&&(ft(Ya(we,{name:s,search:o.search||void 0,status:o.status!=="all"?o.status:void 0,tags:o.tags.length?o.tags:void 0,author:o.author!=="all"?o.author:void 0,datePreset:o.datePreset!=="any"?o.datePreset:void 0,type:o.type!=="all"?o.type:void 0})),vt(""),Ce(!1))},Os=({name:s,...t})=>be({...Qe,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))}),[qs,jt]=n.useState(new Set);n.useEffect(()=>{const s=o.search.trim();if(s.length<2){jt(new Set);return}let t=!1;const r=setTimeout(async()=>{try{const{nodes:d}=await Ys(a,s);t||jt(new Set(d.map(x=>x.id)))}catch{}},300);return()=>{t=!0,clearTimeout(r)}},[a,o.search]);const O=ls(o);n.useEffect(()=>{O&&Le()},[O,Le]);const zs=Qa(o.datePreset,Date.now()),ne=Ha({...o,levelNodes:i,fullNodes:Q,folderFilter:D,updatedAfter:zs,contentHits:qs}),Y=[...ne];Ne==="activity"?Y.sort((s,t)=>{var r,d;return rs(t.updated_at,(r=K[t.id])==null?void 0:r.lastAt).localeCompare(rs(s.updated_at,(d=K[s.id])==null?void 0:d.lastAt))}):Ne==="edited"?Y.sort((s,t)=>String(t.updated_at||"").localeCompare(String(s.updated_at||""))):Ne==="comments"?Y.sort((s,t)=>{var L,c,N,X;const r=((L=K[t.id])==null?void 0:L.count)||0,d=((c=K[s.id])==null?void 0:c.count)||0;if(r!==d)return r-d;const x=((N=K[t.id])==null?void 0:N.lastAt)||"",y=((X=K[s.id])==null?void 0:X.lastAt)||"";return x!==y?String(x).localeCompare(String(y)):String(s.title||"").localeCompare(String(t.title||""))}):Y.sort((s,t)=>String(s.title||"").localeCompare(String(t.title||"")));const Hs=(()=>{const s=new Map;for(const t of Y){const r=S(t.id||"");s.has(r)||s.set(r,[]),s.get(r).push(t)}return[...s.entries()].map(([t,r])=>({folder:t,depth:t?t.split("/").length-As:0,items:r})).sort((t,r)=>t.folder===""?-1:r.folder===""?1:Gt(t.folder,r.folder))})(),Is=Ia({visibleCount:ne.length,folderCount:w.length,filtering:O}),F=n.useMemo(()=>Q?Ua(Q):{orphans:[],broken:[]},[Q]),bt=(u==null?void 0:u.authors)??[],Nt=n.useMemo(()=>Object.keys((u==null?void 0:u.types)??{}).sort((s,t)=>s.localeCompare(t)),[u]),Ws=()=>{be({...Qe})},J=[];o.search&&J.push({label:`Search: ${o.search}`,clear:()=>C("search","")}),o.status!=="all"&&J.push({label:`Status: ${Qt[o.status]??o.status}`,clear:()=>C("status","all")}),o.type!=="all"&&J.push({label:`Type: ${Yt[o.type]??o.type}`,clear:()=>C("type","all")}),o.author!=="all"&&J.push({label:`Author: ${o.author}`,clear:()=>C("author","all")}),o.datePreset!=="any"&&J.push({label:`Edited: ${Jt[o.datePreset]??o.datePreset}`,clear:()=>C("datePreset","any")});const wt=n.useMemo(()=>Ka(ne),[ne]),Se=wt.tags,Ct=wt.recent,[$,Ve]=n.useState(null),[St,q]=n.useState(null),ie=n.useRef(null),ce=()=>{ie.current&&(clearTimeout(ie.current),ie.current=null)};n.useEffect(()=>ce,[]);const Ks=s=>{ce(),ie.current=setTimeout(()=>{ie.current=null,os(s)},600)},Be=s=>{const t=$;Ve(null),q(null),ce(),t&&setTimeout(()=>void ct(t,s),0)};return e.jsxs(e.Fragment,{children:[e.jsxs(Js,{children:[e.jsx(Xs,{children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(Zs,{className:"text-lg",children:"Documents"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 w-full",children:[e.jsxs("div",{className:"relative flex-1 min-w-[12rem] sm:flex-none sm:w-80",children:[e.jsx(ea,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"}),e.jsx(Ie,{placeholder:"Search title, tags, content…",value:o.search,onChange:s=>C("search",s.target.value),className:"pl-9 pr-12 w-full h-8"}),e.jsx("kbd",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-[10px] text-muted-foreground border rounded px-1 pointer-events-none",title:"Quick open",children:"⌘K"})]}),Fe&&e.jsxs(ee,{value:o.status,onValueChange:s=>C("status",s),children:[e.jsx(te,{className:"w-[140px] h-8",children:e.jsx(se,{})}),e.jsxs(ae,{children:[e.jsx(f,{value:"all",children:"All Status"}),Object.entries(Qt).map(([s,t])=>e.jsx(f,{value:s,children:t},s))]})]}),Nt.length>1&&e.jsxs(ee,{value:o.type,onValueChange:s=>C("type",s),children:[e.jsx(te,{className:"w-[130px] h-8",title:"Filter by type",children:e.jsx(se,{})}),e.jsxs(ae,{children:[e.jsx(f,{value:"all",children:"All types"}),Nt.map(s=>e.jsx(f,{value:s,children:Yt[s]??s},s))]})]}),bt.length>1&&e.jsxs(ee,{value:o.author,onValueChange:s=>C("author",s),children:[e.jsx(te,{className:"w-[150px] h-8",title:"Filter by author",children:e.jsx(se,{})}),e.jsxs(ae,{children:[e.jsx(f,{value:"all",children:"All authors"}),bt.map(s=>e.jsx(f,{value:s,children:s},s))]})]}),e.jsxs(ee,{value:o.datePreset,onValueChange:s=>C("datePreset",s),children:[e.jsx(te,{className:"w-[140px] h-8",title:"Filter by last edited",children:e.jsx(se,{})}),e.jsxs(ae,{children:[e.jsx(f,{value:"any",children:"Any time"}),Object.entries(Jt).map(([s,t])=>e.jsx(f,{value:s,children:t},s))]})]}),e.jsxs(ee,{value:Ne,onValueChange:s=>Vs(s),children:[e.jsx(te,{className:"w-[150px] h-8",title:"Sort documents",children:e.jsx(se,{})}),e.jsxs(ae,{children:[e.jsx(f,{value:"activity",children:"Recent activity"}),e.jsx(f,{value:"name",children:"Name (A–Z)"}),e.jsx(f,{value:"edited",children:"Recently edited"}),e.jsx(f,{value:"comments",children:"Most comments"})]})]}),e.jsxs("div",{className:"flex items-center rounded-md border h-8",children:[e.jsx("button",{type:"button",title:"List view","aria-pressed":B==="list",className:`px-2 h-full rounded-l-md ${B==="list"?"bg-muted":"hover:bg-muted/50"}`,onClick:()=>gt("list"),children:e.jsx(Da,{className:"h-4 w-4"})}),e.jsx("button",{type:"button",title:"Card view","aria-pressed":B==="cards",className:`px-2 h-full rounded-r-md ${B==="cards"?"bg-muted":"hover:bg-muted/50"}`,onClick:()=>gt("cards"),children:e.jsx(ta,{className:"h-4 w-4"})})]})]})]})}),e.jsxs(sa,{children:[D!==null&&e.jsxs("div",{className:"flex items-center flex-wrap gap-1 mb-3 text-sm",children:[e.jsx("button",{type:"button",className:"text-primary hover:underline",onClick:()=>T(null),children:"All documents"}),D.split("/").map((s,t,r)=>{const d=r.slice(0,t+1).join("/"),x=t===r.length-1;return e.jsxs(n.Fragment,{children:[e.jsx(Rt,{className:"h-3.5 w-3.5 text-muted-foreground/50"}),x?e.jsxs("span",{className:"font-medium flex items-center gap-1",children:[e.jsx(Vt,{className:"h-4 w-4 text-blue-500"}),We(s)]}):e.jsx("button",{type:"button",className:"text-primary hover:underline",onClick:()=>T(d),children:We(s)})]},d)}),e.jsx(Ye,{variant:"secondary",className:"ml-1 text-[10px] px-1.5 py-0 h-5",children:ne.length}),he&&e.jsxs(j,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs text-muted-foreground ml-1",onClick:()=>A("new",{folder:D}),title:"New document in this folder",children:[e.jsx(Bt,{className:"h-3.5 w-3.5 mr-1"})," New here"]})]}),we.length>0&&e.jsxs("div",{className:"flex items-center flex-wrap gap-1.5 mb-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Saved:"}),we.map(s=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border px-2 py-0.5 hover:bg-muted",children:[e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1",onClick:()=>Os(s),title:`Apply saved filter "${s.name}"`,children:[e.jsx(Ge,{className:"h-3 w-3 text-amber-500"}),s.name]}),e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>ft(Ja(we,s.name)),title:`Delete saved filter "${s.name}"`,children:e.jsx(de,{className:"h-3 w-3"})})]},s.name))]}),O&&e.jsxs("div",{className:"flex items-center flex-wrap gap-1.5 mb-3 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Active filters:"}),J.map(s=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5",children:[s.label,e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:s.clear,title:"Remove this filter",children:e.jsx(de,{className:"h-3 w-3"})})]},s.label)),o.tags.length>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5",children:["Tags: ",o.tags.join(", "),e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>C("tags",[]),title:"Remove tag filters",children:e.jsx(de,{className:"h-3 w-3"})})]}),e.jsxs(j,{variant:"outline",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>Ce(!0),children:[e.jsx(Ge,{className:"h-3 w-3 mr-1"}),"Save filter"]}),e.jsx(j,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs text-muted-foreground",onClick:Ws,children:"Clear all"})]}),Se.length>0&&e.jsxs("div",{className:"flex items-center flex-wrap gap-1.5 mb-3 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Tags:"}),Se.slice(0,14).map(({tag:s,count:t})=>{const r=o.tags.includes(s);return e.jsxs("button",{type:"button",className:`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 transition-colors ${r?"bg-primary text-primary-foreground border-primary":"text-foreground/80 hover:bg-muted"}`,onClick:()=>xt(s),title:r?`Remove filter ${s}`:`Filter by ${s}`,children:[s,e.jsx("span",{className:r?"text-primary-foreground/80":"text-muted-foreground",children:r?"×":t})]},s)}),Se.length>14&&e.jsxs("span",{className:"text-muted-foreground",children:["+",Se.length-14," more"]}),o.tags.length>0&&e.jsx("button",{type:"button",className:"text-muted-foreground hover:underline ml-1",onClick:()=>C("tags",[]),children:"clear"})]}),Ct.length>0&&e.jsxs("div",{className:"flex items-center flex-wrap gap-1.5 mb-3 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Recently edited:"}),Ct.map(s=>e.jsxs("button",{type:"button",className:`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 hover:bg-muted truncate max-w-[180px] ${s.type==="artifact"?"border-amber-300 text-amber-700 dark:text-amber-300":"text-primary"}`,onClick:()=>A(s.id),children:[s.type==="artifact"&&e.jsx(Ea,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:s.title})]},s.id))]}),h||me.has(k)?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ke,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):Is?O||!he?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:O?"No matching documents":"No documents yet"}):e.jsxs("button",{type:"button",onClick:()=>{var s;return(s=ys.current)==null?void 0:s.click()},className:"w-full flex flex-col items-center gap-2 rounded-lg border-2 border-dashed border-border py-10 text-muted-foreground hover:border-primary hover:text-primary transition-colors",children:[e.jsx(Ta,{className:"h-7 w-7"}),e.jsx("div",{className:"text-sm font-medium",children:"Drag files here, or click to import"}),e.jsx("div",{className:"text-xs",children:".md → document · .html → hosted artifact"})]}):(()=>{const s=(t,r=0)=>{var Lt,At;const d=B==="cards",x=t.type||"document",y=Ra(x),L=Fe&&t.status==="draft"&&ye(t),c=$s.has(t.id)?!0:t.status==="pending_review"&&ps(t)&&(ht.get(t.id)!==le||Xe&&us),N=t.status!=="pending_review"&&ye(t),X=!!t.author&&!!le&&t.author.toLowerCase()===le,Z=g||X,z=Me.get(t.id),$t=(z==null?void 0:z.status)==="pending",Mt=!tt&&(Z||ye(t))&&(Z||!$t),Pt=()=>Z?at(t):st(t),Oe=ye(t)&&Ca(x)&&(t.status!=="pending_review"||Xe||is||cs.includes("admin")||hs(t,"reviewer")),_t=()=>{dt(S(t.id)),ve(null),ge(t)},qe=()=>!d&&!!$&&$!==t.id&&S($)!==S(t.id),Us=e.jsx("div",{onClick:p=>p.stopPropagation(),children:e.jsxs(pa,{modal:!1,children:[e.jsx(xa,{asChild:!0,children:e.jsx(j,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 flex-shrink-0",title:"Actions",children:e.jsx($a,{className:"h-4 w-4"})})}),e.jsxs(ga,{align:"end",className:"min-w-40",children:[N&&e.jsxs(I,{onSelect:()=>A(t.id),children:[e.jsx(Wt,{className:"h-3.5 w-3.5 mr-2"}),"Edit"]}),Oe&&e.jsxs(I,{onSelect:_t,children:[e.jsx(De,{className:"h-3.5 w-3.5 mr-2"}),"Move to folder"]}),L&&e.jsxs(I,{onSelect:()=>xe(t),children:[e.jsx(es,{className:"h-3.5 w-3.5 mr-2"}),"Submit for review"]}),c&&e.jsxs(I,{onSelect:()=>Ze(t),children:[e.jsx(Je,{className:"h-3.5 w-3.5 mr-2"}),"Review"]}),e.jsxs(I,{onSelect:()=>je(t),children:[e.jsx(Ut,{className:"h-3.5 w-3.5 mr-2"}),"History"]}),g&&e.jsxs(I,{onSelect:()=>nt(t),children:[e.jsx(Zt,{className:"h-3.5 w-3.5 mr-2"}),"Publish"]}),e.jsx(fa,{}),Mt&&e.jsxs(I,{onSelect:Pt,className:Z?"text-destructive focus:text-destructive":void 0,children:[e.jsx(ue,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})});return e.jsxs("div",{onClick:()=>A(t.id),className:`${d?"flex flex-col gap-2":"flex items-center gap-3"} p-3 rounded-lg border hover:bg-muted/50 transition-colors group cursor-pointer ${$===t.id?"opacity-40":""}`,style:!d&&r?{marginLeft:`${r*1.25}rem`}:void 0,draggable:!d&&Oe,onDragStart:p=>{p.dataTransfer.setData("text/plain",t.id),p.dataTransfer.effectAllowed="move",Ve(t.id)},onDragEnd:()=>{Ve(null),q(null),ce()},onDragOver:p=>{qe()&&(p.preventDefault(),p.dataTransfer.dropEffect="move")},onDragEnter:()=>{qe()&&q(S(t.id))},onDrop:p=>{qe()&&(p.preventDefault(),p.stopPropagation(),Be(S(t.id)))},"data-testid":`document-row-${t.id}`,children:[!d&&e.jsx(Xt,{type:t.type,className:"h-5 w-5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx(Xt,{type:t.type,className:"h-4 w-4"}),e.jsx("span",{className:"font-medium truncate min-w-0",title:t.title,children:t.title}),y&&e.jsx("span",{className:`shrink-0 rounded px-1.5 py-px text-[10px] font-semibold uppercase tracking-wide ${y.cls}`,title:y.title,children:y.label}),e.jsx(qa,{status:t.status||"draft",size:"sm",className:"shrink-0 whitespace-nowrap"}),Fe&&ia(t,ms)&&e.jsxs("span",{className:"shrink-0 inline-flex items-center gap-1 rounded px-1.5 py-px text-[10px] font-semibold uppercase tracking-wide border bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-500/10 dark:text-amber-400 dark:border-amber-500/30",title:typeof t.prime=="boolean"?"Prime: flagged on this document. Always requires steward approval.":"Prime: inherited from a prime tag. Always requires steward approval.","data-testid":`prime-badge-${t.id}`,children:[e.jsx(Ge,{className:"h-3 w-3"}),"Prime"]}),$t&&(()=>{const p=z.requestedBy.toLowerCase()===le;return e.jsxs("span",{className:`shrink-0 inline-flex items-center gap-1 rounded px-1.5 py-px text-[10px] font-semibold uppercase tracking-wide border bg-red-50 text-red-700 border-red-200 ${p?"cursor-pointer hover:bg-red-100":""}`,title:p?"Click to withdraw your deletion request":`${z.requestedBy} asked for this to be deleted: "${z.reason}". A nest admin decides.`,"data-testid":`deletion-flag-${t.id}`,onClick:p?ze=>{ze.stopPropagation(),et(z)}:void 0,children:[e.jsx(ue,{className:"h-3 w-3"}),"Deletion requested",p&&e.jsx(de,{className:"h-3 w-3 ml-0.5"})]})})(),d&&e.jsx("div",{className:"ml-auto",children:Us})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1",children:[e.jsxs("span",{children:["v",t.version||1]}),((Lt=t.tags)==null?void 0:Lt.length)>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{className:"flex items-center gap-1 truncate",children:t.tags.slice(0,3).map(p=>e.jsx("button",{type:"button",title:o.tags.includes(p)?`Remove filter ${p}`:`Filter by ${p}`,className:`rounded-full border px-1.5 py-px transition-colors ${o.tags.includes(p)?"bg-primary text-primary-foreground border-primary":"hover:bg-muted"}`,onClick:ze=>{ze.stopPropagation(),xt(p)},children:p},p))})]}),(t.author||((At=t.collaborators)==null?void 0:At.length)>0)&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx(Sa,{author:t.author,collaborators:t.collaborators})]})]})]}),!d&&e.jsxs("div",{className:"flex items-center gap-1 transition-opacity opacity-0 group-hover:opacity-100",onClick:p=>p.stopPropagation(),children:[L&&e.jsxs(j,{variant:"outline",size:"sm",onClick:()=>xe(t),children:[e.jsx(es,{className:"h-3.5 w-3.5 mr-1"}),"Submit"]}),c&&e.jsx(j,{variant:"outline",size:"sm",onClick:()=>Ze(t),className:"border-green-200 text-green-700 hover:bg-green-50",children:"Review"}),N&&e.jsx(j,{variant:"ghost",size:"sm",onClick:()=>A(t.id),title:"Edit",children:e.jsx(Wt,{className:"h-3.5 w-3.5"})}),Oe&&e.jsx(j,{variant:"ghost",size:"sm",onClick:_t,title:"Move to folder","data-testid":`move-node-${t.id}`,children:e.jsx(De,{className:"h-3.5 w-3.5"})}),e.jsx(j,{variant:"ghost",size:"sm",onClick:()=>je(t),title:"History",children:e.jsx(Ut,{className:"h-3.5 w-3.5"})}),Mt&&e.jsx(j,{variant:"ghost",size:"sm",onClick:Pt,title:Z?"Delete":"Delete (needs admin approval)","data-testid":`delete-node-${t.id}`,className:Z?"text-destructive hover:text-destructive hover:bg-destructive/10":void 0,children:e.jsx(ue,{className:"h-3.5 w-3.5"})})]})]},t.id)};return B==="cards"?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2",children:Y.map(t=>s(t))}):e.jsxs("div",{className:"space-y-1",children:[$&&S($)!==k&&e.jsxs("div",{className:`flex items-center gap-2 rounded-md border-2 border-dashed px-3 py-2 text-sm ${St===k?"border-primary bg-primary/10 text-primary":"border-border text-muted-foreground"}`,onDragOver:t=>{t.preventDefault(),t.dataTransfer.dropEffect="move"},onDragEnter:()=>q(k),onDragLeave:()=>q(t=>t===k?null:t),onDrop:t=>{t.preventDefault(),Be(k)},children:[e.jsx(De,{className:"h-4 w-4"}),"Move to ",k?H(k):"nest root"]}),e.jsx(aa,{className:"space-y-1",groups:Hs,baseFolder:k,known:O?void 0:w,isCollapsed:t=>O?!1:!re.has(t),renderFolder:(t,{collapsed:r})=>{const d=!!$&&S($)!==t.path,x=d&&St===t.path,y=t.total>0,L=me.has(t.path);return e.jsxs("div",{className:`group/fh flex items-center gap-1.5 py-1.5 px-2 rounded-md select-none transition-colors ${y?"cursor-pointer":""} ${x?"bg-primary/10 ring-1 ring-primary":"hover:bg-muted/50"}`,onClick:y?()=>Te(t.path):void 0,onDragOver:c=>{d&&(c.preventDefault(),c.dataTransfer.dropEffect="move")},onDragEnter:c=>{c.currentTarget.contains(c.relatedTarget)||($&&y&&r&&Ks(t.path),d&&q(t.path))},onDragLeave:c=>{c.currentTarget.contains(c.relatedTarget)||(q(N=>N===t.path?null:N),ce())},onDrop:c=>{d&&(c.preventDefault(),Be(t.path))},"data-testid":`folder-header-${t.path}`,children:[L?e.jsx(Ke,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"}):y?e.jsx(Rt,{className:`h-3.5 w-3.5 text-muted-foreground transition-transform ${r?"":"rotate-90"}`}):e.jsx("span",{className:"h-3.5 w-3.5 shrink-0"}),e.jsx(Vt,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-sm font-medium",children:t.label}),t.total>0&&e.jsx(Ye,{variant:"secondary",className:"text-[10px] px-1.5 py-0 h-5",title:t.count!==t.total?`${t.count} here · ${t.total} in this folder`:void 0,children:t.total}),he&&e.jsx("button",{type:"button",className:"ml-1 rounded p-0.5 text-muted-foreground opacity-0 group-hover/fh:opacity-100 hover:text-primary hover:bg-primary/10",title:`New document in ${H(t.path)}`,onClick:c=>{c.stopPropagation(),A("new",{folder:t.path})},children:e.jsx(Bt,{className:"h-3.5 w-3.5"})}),g&&e.jsx("button",{type:"button",className:"rounded p-0.5 text-muted-foreground opacity-0 group-hover/fh:opacity-100 hover:text-primary hover:bg-primary/10",title:`Share ${H(t.path)} with someone`,"data-testid":`share-folder-${t.path}`,onClick:c=>{c.stopPropagation(),lt({path:Ts(t.path),label:t.label||We(t.name)})},children:e.jsx(Zt,{className:"h-3.5 w-3.5"})}),(g||he)&&(g||!ot(t.path))&&e.jsx("button",{type:"button",className:`rounded p-0.5 ${t.total===0?"":"opacity-0"} group-hover/fh:opacity-100 focus-visible:opacity-100 ${g?"text-muted-foreground hover:text-destructive hover:bg-destructive/10":"text-muted-foreground hover:text-primary hover:bg-primary/10"}`,title:g?`Delete ${H(t.path)} and everything in it`:"Delete (needs admin approval)","data-testid":`delete-folder-${t.path}`,onClick:c=>{c.stopPropagation(),rt({path:t.path,label:H(t.path),total:t.total})},children:e.jsx(ue,{className:"h-3.5 w-3.5"})}),ot(t.path)&&(()=>{const c=Ss.get(t.path),N=(c==null?void 0:c.requestedBy.toLowerCase())===le;return e.jsxs("span",{className:`inline-flex items-center gap-1 rounded px-1.5 py-px text-[10px] font-semibold uppercase tracking-wide bg-red-50 text-red-700 border border-red-200 ${N?"cursor-pointer hover:bg-red-100":""}`,title:N?"Click to withdraw your deletion request":"Someone asked for this folder to be deleted. A nest admin decides.",onClick:N&&c?X=>{X.stopPropagation(),et(c)}:void 0,children:[e.jsx(ue,{className:"h-3 w-3"}),"Deletion requested",N&&e.jsx(de,{className:"h-3 w-3 ml-0.5"})]})})()]})},renderDoc:t=>s(t,0)})]})})(),!v&&fs.total>0&&e.jsxs("details",{className:"mt-4 text-xs text-muted-foreground",onToggle:s=>{s.currentTarget.open&&Le()},children:[e.jsx("summary",{className:"cursor-pointer select-none",children:Rs?"Link health: checking the whole nest…":Q?`Link health: ${F.broken.length} broken link${F.broken.length!==1?"s":""} · ${F.orphans.length} orphan doc${F.orphans.length!==1?"s":""}`:"Link health — check the whole nest"}),e.jsxs("div",{className:"mt-2 space-y-2 pl-1",children:[Q&&F.broken.length===0&&F.orphans.length===0&&e.jsx("div",{children:"No broken links or orphan documents."}),F.broken.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"font-medium mb-1",children:"Broken links (target doesn't exist):"}),F.broken.slice(0,10).map((s,t)=>e.jsxs("div",{children:[e.jsx("button",{type:"button",className:"text-primary hover:underline",onClick:()=>A(s.sourceId),children:s.sourceTitle})," ","→ [[",s.target,"]]"]},t))]}),F.orphans.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"font-medium mb-1",children:"Orphans (nothing links to them):"}),e.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1",children:F.orphans.slice(0,15).map(s=>e.jsx("button",{type:"button",className:"text-primary hover:underline",onClick:()=>A(s.id),children:s.title},s.id))})]})]})]})]})]}),e.jsx(Ot,{open:Bs,onOpenChange:Ce,children:e.jsxs(qt,{className:"max-w-md",children:[e.jsx(zt,{children:e.jsx(Ht,{children:"Save this filter"})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Saved filters remember your current search, tags, status, author and date range. Pick one from the ",e.jsx("strong",{children:"Saved"})," row to re-apply the whole set in one click — handy for views you return to, like “My drafts” or “Edited this week”."]}),e.jsx(Ie,{autoFocus:!0,placeholder:"Filter name (e.g. My drafts)",value:Re,onChange:s=>vt(s.target.value),onKeyDown:s=>{s.key==="Enter"&&yt()}}),e.jsxs(It,{children:[e.jsx(j,{variant:"ghost",onClick:()=>Ce(!1),children:"Cancel"}),e.jsx(j,{onClick:yt,disabled:!Re.trim(),children:"Save filter"})]})]})}),$e&&e.jsx(ja,{nestId:a,targetType:"folder",target:$e.path,label:$e.label,onClose:()=>lt(null)}),e.jsx(Ot,{open:!!R,onOpenChange:s=>{!s&&!fe&&ge(null)},children:e.jsxs(qt,{className:"max-w-md",children:[e.jsx(zt,{children:e.jsx(Ht,{children:"Move to folder"})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Move ",e.jsx("strong",{children:R==null?void 0:R.title})," to another folder. Version history, review state, and [[wiki links]] follow the document."]}),e.jsxs(ee,{value:G!==null?"__new__":Pe===""?"__root__":Pe,onValueChange:s=>{if(s==="__new__"){ve("");return}ve(null),dt(s==="__root__"?"":s)},children:[e.jsx(te,{"data-testid":"move-folder-select",children:e.jsx(se,{placeholder:"Choose a folder"})}),e.jsxs(ae,{children:[e.jsx(f,{value:"__root__",children:"Nest root"}),Fs.map(s=>e.jsx(f,{value:s,children:H(s)},s)),e.jsx(ra,{}),e.jsx(f,{value:"__new__",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Fa,{className:"h-3.5 w-3.5"}),"New folder…"]})})]})]}),G!==null&&e.jsxs(e.Fragment,{children:[e.jsx(Ie,{autoFocus:!0,value:G,onChange:s=>ve(s.target.value),placeholder:"e.g. gtm/deals",className:"font-mono","data-testid":"move-folder-new-path"}),V.error?e.jsx("p",{className:"text-xs text-destructive",children:V.error}):V.rewritten&&V.path?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Will be created as"," ",e.jsx("code",{className:"font-mono",children:V.path})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"The folder is created by the move — nest it with a slash."})]}),e.jsxs(It,{children:[e.jsx(j,{variant:"ghost",disabled:fe,onClick:()=>ge(null),children:"Cancel"}),e.jsxs(j,{disabled:fe||!R||S(R.id)===mt||G!==null&&(!V.path||!!V.error),onClick:async()=>{if(!R)return;ut(!0);const s=await ct(R.id,mt);ut(!1),s&&ge(null)},"data-testid":"move-folder-confirm",children:[fe?e.jsx(Ke,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(De,{className:"h-4 w-4 mr-2"}),"Move"]})]})]})}),P&&e.jsx(Ma,{isOpen:!!P,onClose:()=>xe(null),documentTitle:P.title,currentVersion:P.version||1,onSubmit:Ms}),pe&&e.jsx(ba,{nestId:a,nodeId:pe.id,nodeTitle:pe.title||pe.id,onClose:()=>nt(null)}),M&&e.jsx(Ue,{open:!0,onOpenChange:s=>!s&&rt(null),title:g?`Delete "${M.label}"?`:`Request deletion of "${M.label}"`,description:M.total===0?g?"This folder is empty — deleting it just removes it from the tree.":"A nest admin reviews this. The folder is empty, so nothing else is removed.":g?`This deletes all ${M.total} document${M.total===1?"":"s"} in this folder and its subfolders, with their history, comments and annotations. It cannot be undone.`:`A nest admin reviews this. Honouring it deletes all ${M.total} document${M.total===1?"":"s"} in this folder. Nothing is removed yet.`,label:g?void 0:"Why should it be deleted?",placeholder:"e.g. superseded by the new API docs",confirmLabel:g?"Delete folder":"Request deletion",destructive:g,onConfirm:Ls}),U&&e.jsx(Ue,{open:!0,onOpenChange:s=>!s&&at(null),title:`Delete "${U.title}"?`,description:"This removes the document, its version history, comments and annotations. It cannot be undone.",warning:Na(ws),confirmLabel:"Delete document",destructive:!0,onConfirm:Ps}),oe&&e.jsx(Ue,{open:!0,onOpenChange:s=>!s&&st(null),title:`Request deletion of "${oe.title}"`,description:"A nest admin reviews this and either deletes the document or rejects with a note. Nothing is removed yet.",label:"Why should it be deleted?",placeholder:"e.g. superseded by the new runbook",confirmLabel:"Request deletion",priorDecline:((Ft=Me.get(oe.id))==null?void 0:Ft.status)==="declined"?Me.get(oe.id):null,onConfirm:_s}),_&&e.jsx(wa,{open:!0,onClose:()=>it(null),title:_.title,versionData:ks,onLoadContent:async s=>(await na(a,_.id,s)).content,onRestore:async s=>{if(_)try{await oa(a,_.id,s),b.success(`Reverted to version ${s}`),await je(_),E()}catch(t){b.error((t==null?void 0:t.message)||"Revert failed")}},onDiscard:async()=>{if(_)try{const{version:s}=await la(a,_.id);b.success(`Draft discarded — back to version ${s}`),await je(_),E()}catch(s){b.error((s==null?void 0:s.message)||"Discard failed")}}})]})}export{Fr as DocumentsTab};
@@ -1 +0,0 @@
1
- import{u as j,r as g,j as e,b_ as N,b$ as E,c1 as v,c0 as C,B as w,L as o,R as b,c2 as y,e as k,f as _,Y as F,l as T,ee as B,ac as L}from"./index-WYDmEOfO.js";import{F as d}from"./file-exclamation-point-BevGZgtj.js";import{C as Q}from"./circle-check-Bw_aTXiH.js";import{C as R}from"./NestView-EW-sraEb.js";import"./MarkdownEditor-CKh4WSn-.js";import"./zap-D2ifcnYb.js";import"./index-BOVYgMvj.js";import"./arrow-left-CWIsv-sG.js";import"./trash-2-B0HyPTnI.js";import"./x-mNtADYHc.js";import"./chevron-left-CK_ZPFm9.js";import"./alert-dialog-BvF3NFr7.js";import"./NestPageHeader-Cizo8nUi.js";import"./count-skeleton-DToLM74B.js";import"./folder-input-m8UBV4fA.js";import"./PersonCombobox-BKI7dff4.js";import"./tag-DeYC_mRv.js";import"./user-plus-Ckm_Isyc.js";import"./ReviewActions-CS8JXgXF.js";import"./circle-x-DkIG68H7.js";import"./settings-DKX0Q4gO.js";function S(t,a=!0){return F({...T.externalEdits(t),enabled:a})}function te({nestId:t,enabled:a,onOpenDocument:m,titleOf:x}){var l;const p=j(),i=S(t,a),r=((l=i.data)==null?void 0:l.entries)??[],[u,n]=g.useState(!1),h=async()=>{n(!0);try{await B(t).catch(s=>(console.error("[ExternalEditsTab] scanExternalEdits failed",t,s),null)),await p.invalidateQueries({queryKey:L.externalEdits(t)})}finally{n(!1)}},c=u||i.isFetching;return e.jsxs(N,{children:[e.jsx(E,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(v,{className:"text-lg flex items-center gap-2",children:[e.jsx(d,{className:"h-4 w-4 text-orange-600"}),"External Edits"]}),e.jsx(C,{children:"Files edited directly on disk, awaiting your approval."})]}),e.jsx(w,{variant:"ghost",size:"icon",onClick:h,disabled:c,className:"h-8 w-8","data-testid":"external-edits-refresh",children:c?e.jsx(o,{className:"h-4 w-4 animate-spin"}):e.jsx(b,{className:"h-4 w-4"})})]})}),e.jsx(y,{children:i.isLoading?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(o,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):r.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(Q,{className:"h-10 w-10 text-green-500 mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No pending external edits"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All files on disk match their last approved state."})]}):e.jsx("div",{className:"space-y-2",children:r.map(s=>{const f=x(s.document_id)||s.document_id.split("/").pop();return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border hover:bg-muted/50 cursor-pointer transition-colors",onClick:()=>m(s.document_id),"data-testid":`external-edit-row-${s.suggestion_id}`,children:[e.jsx(d,{className:"h-5 w-5 text-orange-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium truncate",children:f}),e.jsx(k,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-orange-100 text-orange-700",children:s.source})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1",children:[e.jsx(R,{className:"h-3 w-3"}),e.jsx("span",{children:_(s.detected_at)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:["by ",s.actor]})]})]})]},s.suggestion_id)})})})]})}export{te as ExternalEditsTab,S as useExternalEdits};