@flexkit/studio 0.2.24 → 0.2.26

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 (73) hide show
  1. package/dist/{chat-page-A7FG7WTN.js → chat-page-U46RRUKG.js} +3 -3
  2. package/dist/{chat-page-A7FG7WTN.js.map → chat-page-U46RRUKG.js.map} +1 -1
  3. package/dist/{chunk-3COXA5QH.js → chunk-3L4LYXSR.js} +2 -2
  4. package/dist/{chunk-3COXA5QH.js.map → chunk-3L4LYXSR.js.map} +1 -1
  5. package/dist/{chunk-JSJZKPXU.js → chunk-3YL7XGH5.js} +3 -3
  6. package/dist/{chunk-JSJZKPXU.js.map → chunk-3YL7XGH5.js.map} +1 -1
  7. package/dist/{chunk-L3GBAK54.js → chunk-7QHGKOAB.js} +3 -3
  8. package/dist/{chunk-L3GBAK54.js.map → chunk-7QHGKOAB.js.map} +1 -1
  9. package/dist/{chunk-NO3AH2M3.js → chunk-BCFG4FXM.js} +3 -3
  10. package/dist/{chunk-NO3AH2M3.js.map → chunk-BCFG4FXM.js.map} +1 -1
  11. package/dist/chunk-HE7I5LVU.js +2 -0
  12. package/dist/chunk-HE7I5LVU.js.map +1 -0
  13. package/dist/{chunk-SZOEW2TL.js → chunk-HPLIQBUP.js} +7 -7
  14. package/dist/chunk-HPLIQBUP.js.map +1 -0
  15. package/dist/{chunk-HTSMODQB.js → chunk-NAUY7EN3.js} +2 -2
  16. package/dist/{chunk-HTSMODQB.js.map → chunk-NAUY7EN3.js.map} +1 -1
  17. package/dist/{chunk-3IUKXOKF.js → chunk-P5YGMKPO.js} +2 -2
  18. package/dist/{chunk-3IUKXOKF.js.map → chunk-P5YGMKPO.js.map} +1 -1
  19. package/dist/chunk-QSTWBKPN.js +2 -0
  20. package/dist/chunk-QSTWBKPN.js.map +1 -0
  21. package/dist/{chunk-XV2B3W6Z.js → chunk-RARRMN5A.js} +3 -3
  22. package/dist/{chunk-XV2B3W6Z.js.map → chunk-RARRMN5A.js.map} +1 -1
  23. package/dist/{chunk-IQ2F2FFF.js → chunk-V45Z7U6J.js} +2 -2
  24. package/dist/{chunk-IQ2F2FFF.js.map → chunk-V45Z7U6J.js.map} +1 -1
  25. package/dist/{chunk-NSVX6HEN.js → chunk-WFJICDCL.js} +3 -3
  26. package/dist/{chunk-NSVX6HEN.js.map → chunk-WFJICDCL.js.map} +1 -1
  27. package/dist/{chunk-UBFBXBPG.js → chunk-Z6WDRVBW.js} +2 -2
  28. package/dist/{chunk-UBFBXBPG.js.map → chunk-Z6WDRVBW.js.map} +1 -1
  29. package/dist/{chunk-AKW7EKYI.js → chunk-ZI22345U.js} +3 -3
  30. package/dist/{chunk-AKW7EKYI.js.map → chunk-ZI22345U.js.map} +1 -1
  31. package/dist/{entry-RMRLV3NM.js → entry-TFSFZ6FA.js} +2 -2
  32. package/dist/{entry-RMRLV3NM.js.map → entry-TFSFZ6FA.js.map} +1 -1
  33. package/dist/index.js +7 -7
  34. package/dist/index.js.map +1 -1
  35. package/dist/{list-GVATECOW.js → list-ORNZB5HP.js} +2 -2
  36. package/dist/{list-GVATECOW.js.map → list-ORNZB5HP.js.map} +1 -1
  37. package/dist/{list-HR55TZQX.js → list-Q5R3QLQU.js} +3 -3
  38. package/dist/{list-HR55TZQX.js.map → list-Q5R3QLQU.js.map} +1 -1
  39. package/dist/pages-IYR7KLDW.js +5 -0
  40. package/dist/pages-IYR7KLDW.js.map +1 -0
  41. package/dist/plugin-pages-QVUZRBF7.js +2 -0
  42. package/dist/{plugin-pages-BS2IMNRU.js.map → plugin-pages-QVUZRBF7.js.map} +1 -1
  43. package/dist/record-links-XNRXCW3Y.js +2 -0
  44. package/dist/{record-links-2QWJFFZF.js.map → record-links-XNRXCW3Y.js.map} +1 -1
  45. package/dist/{root-E35GZ7SV.js → root-2BTH6M5K.js} +3 -3
  46. package/dist/{root-E35GZ7SV.js.map → root-2BTH6M5K.js.map} +1 -1
  47. package/dist/{root-ZCXGZCUT.js → root-5T3UQRUT.js} +2 -2
  48. package/dist/{root-ZCXGZCUT.js.map → root-5T3UQRUT.js.map} +1 -1
  49. package/dist/{root-54BI6S4V.js → root-A76E3Z35.js} +3 -3
  50. package/dist/{root-54BI6S4V.js.map → root-A76E3Z35.js.map} +1 -1
  51. package/dist/root-LGCOXNRR.js +2 -0
  52. package/dist/{root-U52KZQSD.js.map → root-LGCOXNRR.js.map} +1 -1
  53. package/dist/{root-GAB2SFFF.js → root-TOTFZUJI.js} +2 -2
  54. package/dist/{root-GAB2SFFF.js.map → root-TOTFZUJI.js.map} +1 -1
  55. package/dist/{root-JWXXF653.js → root-XPFHRGVP.js} +3 -3
  56. package/dist/{root-JWXXF653.js.map → root-XPFHRGVP.js.map} +1 -1
  57. package/dist/{search-IOYOKT6M.js → search-4UVG2IJ5.js} +2 -2
  58. package/dist/{search-IOYOKT6M.js.map → search-4UVG2IJ5.js.map} +1 -1
  59. package/dist/skills-pages-3RFTYQ2K.js +2 -0
  60. package/dist/skills-pages-3RFTYQ2K.js.map +1 -0
  61. package/dist/{source-3YZNNITL.js → source-P5W56BKA.js} +2 -2
  62. package/dist/{source-3YZNNITL.js.map → source-P5W56BKA.js.map} +1 -1
  63. package/package.json +2 -2
  64. package/dist/chunk-I6Z3WLAX.js +0 -2
  65. package/dist/chunk-I6Z3WLAX.js.map +0 -1
  66. package/dist/chunk-SZOEW2TL.js.map +0 -1
  67. package/dist/pages-OJYYLSI3.js +0 -5
  68. package/dist/pages-OJYYLSI3.js.map +0 -1
  69. package/dist/plugin-pages-BS2IMNRU.js +0 -2
  70. package/dist/record-links-2QWJFFZF.js +0 -2
  71. package/dist/root-U52KZQSD.js +0 -2
  72. package/dist/skills-pages-MA6JLBB4.js +0 -2
  73. package/dist/skills-pages-MA6JLBB4.js.map +0 -1
@@ -1,2 +1,2 @@
1
- import'./index.css';import {e,c,b,a,g,h as h$1,m as m$1,k as k$2,n}from'./chunk-HTSMODQB.js';import {m as m$2,s as s$2}from'./chunk-XV2B3W6Z.js';import {b as b$3}from'./chunk-V7C4EHK3.js';import {j}from'./chunk-AKW7EKYI.js';import {c as c$3}from'./chunk-XMOSCJOI.js';import {t,s,u,q as q$1,v,k as k$1,i as i$1,o as o$1,r as r$2,p as p$2}from'./chunk-7KLXWCDS.js';import {a as a$2}from'./chunk-ERDARDGB.js';import {f}from'./chunk-NSVX6HEN.js';import {na,p,q,r,t as t$2,u as u$1,v as v$1,qa,s as s$1}from'./chunk-DGIY4SKN.js';import {t as t$1}from'./chunk-SZEGGBOC.js';import {b as b$2,c as c$1,h,i,k,l,m,o,p as p$1,q as q$2,r as r$1,t as t$3}from'./chunk-32ZU4MLE.js';import {a as a$1,b as b$4,c as c$2,e as e$1}from'./chunk-USNXQOMJ.js';import {b as b$1}from'./chunk-6NRQMG26.js';import {useState,useMemo,useDeferredValue}from'react';import {BookOpenTextIcon,PaperclipIcon,ChevronRightIcon,LayersIcon,XIcon,PlusIcon,Unlink2Icon,LoaderCircle,SearchIcon}from'lucide-react';import {Link}from'react-router-dom';import H from'swr';import Qe from'swr/infinite';import {jsxs,Fragment,jsx}from'react/jsx-runtime';var Be=50;function fe({disabled:n,label:l,onClick:o}){return jsxs(b$4,{children:[jsx(c$2,{asChild:true,children:jsx(b$1,{"aria-label":l,className:"fk:size-7 fk:shrink-0",disabled:n,size:"icon",variant:"ghost",onClick:o,children:jsx(Unlink2Icon,{className:"fk:size-4"})})}),jsx(e$1,{children:l})]})}function Xe({api:n$1,attachedIds:l$1,onAttached:o,onOpenChange:a,open:s,projectId:u,target:r,targetLabel:c$2}){let[p,h$2]=useState(""),m=useDeferredValue(p.trim()),[y,f]=useState(null),b$1=(k,K)=>!s||K&&!K.hasMore?null:c(u).sources({limit:Be,offset:k*Be,search:m||void 0}),{data:v,error:w,isLoading:x,setSize:i$2,size:d}=Qe(b$1,b,{keepPreviousData:true}),g=useMemo(()=>r$2(v?.flatMap(k=>k.sources)??[],l$1),[l$1,v]),L=v?.[v.length-1]?.hasMore??false,C=v!==void 0&&d>v.length;async function A(k){f(k.id);try{let K=await n$1.linkSource(k.id,r);qa.success(K.linked?`Attached "${k.title}".`:`"${k.title}" was already attached.`),o(k),a(!1);}catch(K){qa.error(h$1(K,"The document could not be attached."));}finally{f(null);}}let R;return w?R=jsx("p",{className:"fk:py-6 fk:text-center fk:text-sm fk:text-destructive",children:"The documents could not be loaded."}):x&&!v?R=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-3 fk:py-2",children:[jsx(t$1,{className:"fk:h-10 fk:w-full"}),jsx(t$1,{className:"fk:h-10 fk:w-full"}),jsx(t$1,{className:"fk:h-10 fk:w-full"})]}):g.length===0&&!L?R=jsx("p",{className:"fk:py-6 fk:text-center fk:text-sm fk:text-muted-foreground",children:m?"No documents match your search.":"Every document is attached already, or there are none yet. Add documents in Knowledge first."}):R=jsxs("ul",{className:"fk:flex fk:max-h-80 fk:flex-col fk:overflow-y-auto fk:-mx-2",children:[g.map(k=>{let K=k$1(k),B=y===k.id;return jsx("li",{children:jsxs("button",{className:"fk:flex fk:w-full fk:min-w-0 fk:items-center fk:gap-3 fk:rounded-lg fk:px-2 fk:py-2 fk:text-left fk:transition-colors fk:hover:bg-accent fk:focus-visible:bg-accent fk:focus-visible:outline-none fk:disabled:opacity-60 fk:corner-squircle",disabled:y!==null,type:"button",onClick:()=>{A(k);},children:[jsx(m$1,{source:k}),jsxs("span",{className:"fk:min-w-0 fk:flex-1",children:[jsx("span",{className:"fk:block fk:truncate fk:text-sm fk:font-medium",children:k.title}),jsxs("span",{className:"fk:block fk:truncate fk:text-xs fk:text-muted-foreground",children:[i$1(k)," \xB7 ",K.detail]})]}),B?jsx(LoaderCircle,{className:"fk:size-4 fk:shrink-0 fk:animate-spin fk:text-muted-foreground"}):jsx(k$2,{label:K.label,tone:K.tone})]})},k.id)}),L&&!C?jsx("li",{"aria-hidden":true,children:jsx(n,{onVisible:()=>{i$2(k=>k+1);}})}):null,C?jsx("li",{className:"fk:flex fk:justify-center fk:py-2",children:jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin fk:text-muted-foreground"})}):null]}),jsx(c$1,{open:s,onOpenChange:a,children:jsxs(h,{className:"fk:sm:max-w-lg",children:[jsxs(i,{children:[jsx(k,{children:"Attach a document"}),jsx(l,{children:r.recordId===void 0?`Documents attached to every ${c$2} are searched before the rest of Knowledge when a question is about one of them, or about ${c$2} in general.`:`Documents attached to ${c$2} are searched before the rest of Knowledge when a question is about it.`})]}),jsxs("div",{className:"fk:relative",children:[jsx(SearchIcon,{className:"fk:pointer-events-none fk:absolute fk:left-2.5 fk:top-1/2 fk:size-4 fk:-translate-y-1/2 fk:text-muted-foreground"}),jsx(s$1,{"aria-label":"Search documents",autoFocus:true,className:"fk:pl-8",placeholder:"Search documents by title",value:p,onChange:k=>h$2(k.target.value)})]}),R]})})}function re({projectId:n,renderAction:l,sources:o}){return jsx("ul",{className:"fk:flex fk:flex-col fk:gap-1 fk:-mx-2",children:o.map(a=>{let s=k$1(a);return jsxs("li",{className:"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1.5 fk:corner-squircle",children:[jsxs(Link,{className:"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-3 fk:rounded-md fk:hover:underline fk:underline-offset-2",to:o$1(n,a.id),children:[jsx(m$1,{source:a}),jsxs("span",{className:"fk:min-w-0 fk:flex-1",children:[jsx("span",{className:"fk:block fk:truncate fk:text-sm fk:font-medium",children:a.title}),jsxs("span",{className:"fk:block fk:truncate fk:text-xs fk:text-muted-foreground",children:[i$1(a)," \xB7 ",s.detail]})]})]}),jsx(k$2,{label:s.label,tone:s.tone}),l?.(a)]},a.id)})})}function yt({entityName:n}){let{api:l,projectId:o}=e(),{currentProject:a$1}=f(),[s$1,u$1]=useState(false),r=t(a$1?.schema??[],n),c$1=!!r&&s(n),{data:p,error:h}=H(o&&c$1?c(o).entitySources(n):null,b);if(!l||!o||!r||!c$1||h instanceof a&&h.status===404)return null;let m=p?.sources.length??0;return jsxs(Fragment,{children:[jsxs(b$1,{"aria-label":`Knowledge for every ${u(r)}`,className:"fk:mr-2 fk:h-8","data-knowledge-entity-button":true,size:"sm",variant:"outline",onClick:()=>u$1(true),children:[jsx(BookOpenTextIcon,{}),"Knowledge",m>0?jsx(b$2,{className:"fk:corner-squircle",variant:"secondary",children:m}):null]}),jsx(Ue,{api:l,entityLabel:u(r),entityName:n,open:s$1,projectId:o,onOpenChange:u$1})]})}function Ue({api:n,entityLabel:l$1,entityName:o,onOpenChange:a,open:s,projectId:u}){let r=b$3(),[c$2,p]=useState(false),[h$2,m]=useState(null),{data:y,error:f,isLoading:b$4,mutate:v}=H(c(u).entitySources(o),b),w=y?.sources??[],x=useMemo(()=>({entity:o}),[o]);async function i$1(g$1){m(g$1.id);try{await n.unlinkSource(g$1.id,x),qa.success(`"${g$1.title}" no longer applies to every ${l$1}.`),await v({sources:w.filter(L=>L.id!==g$1.id)},{revalidate:!1}),g();}catch(L){qa.error(h$1(L,"The document could not be detached."));}finally{m(null);}}let d;return f?d=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The documents could not be loaded."}):b$4&&!y?d=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-9 fk:w-full"}),jsx(t$1,{className:"fk:h-9 fk:w-2/3"})]}):w.length===0?d=jsxs("p",{className:"fk:text-sm fk:text-muted-foreground",children:["No documents apply to every ",l$1," yet. Attach a guide, a policy or a spec that holds for all of them and the agent searches it first when asked about any ",l$1,", or about ",l$1," in general."]}):d=jsx(re,{projectId:u,sources:w,renderAction:g=>r?jsx(fe,{disabled:h$2!==null,label:`Detach ${g.title}`,onClick:()=>{i$1(g);}}):null}),jsx(c$1,{open:s,onOpenChange:a,children:jsxs(h,{className:"fk:sm:max-w-lg","data-knowledge-entity-dialog":true,children:[jsxs(i,{children:[jsxs(k,{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(BookOpenTextIcon,{className:"fk:size-4 fk:text-muted-foreground"}),"Knowledge for every ",l$1,y?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:w.length}):null]}),jsxs(l,{children:["Documents attached here apply to every ",l$1,"; each record can hold its own on top."]})]}),jsx("div",{className:"fk:max-h-80 fk:overflow-y-auto",children:d}),jsx("div",{className:"fk:flex fk:justify-end",children:jsx(na,{disabled:!r,children:jsxs(b$1,{disabled:!r,size:"sm",variant:"outline",onClick:()=>p(true),children:[jsx(PaperclipIcon,{}),"Attach document"]})})}),jsx(Xe,{api:n,attachedIds:w.map(g=>g.id),open:c$2,projectId:u,target:x,targetLabel:l$1,onAttached:g$1=>{v({sources:w.some(L=>L.id===g$1.id)?w:[...w,g$1]},{revalidate:false}),g();},onOpenChange:p})]})})}function bt({entityName:n,recordId:l,recordLabel:o}){let{api:a$2,projectId:s$1}=e(),{currentProject:u$1}=f(),r$1=b$3(),[c$1,p$1]=useState(false),[h,m]=useState(false),[y,f$1]=useState(null),b$4=useMemo(()=>({entity:n,recordId:l}),[n,l]),v=t(u$1?.schema??[],n),w=v?u(v):n,x=s(n),{data:i,error:d,isLoading:g$1,mutate:L}=H(s$1&&x?c(s$1).recordSources(b$4):null,b);if(!a$2||!s$1||!x||d instanceof a&&d.status===404)return null;let C=i?.sources??[],A=i?.inherited??[],R=C.map(N=>N.id),k=a$2;async function K(N){f$1(N.id);try{await k.unlinkSource(N.id,b$4),qa.success(`Detached "${N.title}".`),await L({sources:C.filter($=>$.id!==N.id),inherited:A},{revalidate:!1}),g();}catch($){qa.error(h$1($,"The document could not be detached."));}finally{f$1(null);}}let B;return d?B=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The attached documents could not be loaded."}):g$1&&!i?B=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-9 fk:w-full"}),jsx(t$1,{className:"fk:h-9 fk:w-2/3"})]}):B=jsxs("div",{className:"fk:flex fk:flex-col fk:gap-4",children:[C.length===0?jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:A.length>0?"No documents attached to this record itself; the ones below apply to every record of its type.":"No documents attached. Attach a manual, spec or contract and the agent will use it alongside the record's data when asked about this record."}):jsx(re,{projectId:s$1,sources:C,renderAction:N=>r$1?jsx(fe,{disabled:y!==null,label:`Detach ${N.title}`,onClick:()=>{K(N);}}):null}),A.length>0?jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1","data-knowledge-inherited":true,children:[jsxs("span",{className:"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground",children:["Applies to every ",w]}),jsx(re,{projectId:s$1,sources:A})]}):null]}),jsx(a$1,{children:jsxs(p,{className:`fk:z-10 fk:flex fk:shrink-0 fk:flex-col fk:border-t fk:bg-background ${c$1?"fk:h-1/2":""}`,"data-knowledge-record-panel":true,open:c$1,onOpenChange:p$1,children:[jsxs("div",{className:"fk:flex fk:shrink-0 fk:items-center fk:gap-2 fk:pl-4 fk:pr-10 fk:py-2",children:[jsx(q,{asChild:true,children:jsxs("button",{className:"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-2 fk:rounded-md fk:py-1 fk:text-left fk:text-sm fk:font-semibold fk:tracking-tight fk:hover:text-foreground/80 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring",type:"button",children:[jsx(ChevronRightIcon,{className:`fk:size-4 fk:shrink-0 fk:text-muted-foreground fk:transition-transform ${c$1?"fk:rotate-90":""}`}),jsx(BookOpenTextIcon,{className:"fk:size-4 fk:shrink-0 fk:text-muted-foreground"}),"Knowledge",i?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:C.length+A.length}):null]})}),c$1?jsx(na,{disabled:!r$1,children:jsxs(b$1,{disabled:!r$1,size:"sm",variant:"outline",onClick:()=>m(true),children:[jsx(PaperclipIcon,{}),"Attach document"]})}):null]}),jsx(r,{className:"fk:min-h-0 fk:flex-1 fk:overflow-y-auto fk:px-10 fk:pb-6",children:B}),jsx(Xe,{api:a$2,attachedIds:R,open:h,projectId:s$1,target:b$4,targetLabel:o||`this ${n}`,onAttached:N=>{L({sources:C.some($=>$.id===N.id)?C:[...C,N],inherited:A.filter($=>$.id!==N.id)},{revalidate:false}),g();},onOpenChange:m})]})})}function Ze(n,l,o){let{scope:a}=c$3(),s=n.links.map(r=>r.recordId),{data:u}=s$2({entityNamePlural:n.entityPlural,schema:l,scope:a,selection:"display",includeCount:false,variables:{where:{_id:{in:s}},limit:s.length}});return useMemo(()=>{let r={};for(let c of u??[]){let p=c[o.name];typeof p=="string"&&p.trim()&&(r[c._id]=p);}return r},[u,o])}function Ye(n){let{currentProject:l}=f(),o=useMemo(()=>l?.schema??[],[l]),a=m$2(o,n.group.entityPlural),s=a$2(a);return !a||!s?jsx(Je,{...n,entityLabel:a?u(a):n.group.entityPlural,labels:{}}):jsx(et,{...n,displayAttribute:s,schema:o,entityLabel:u(a)})}function et({displayAttribute:n,entityLabel:l,schema:o,...a}){let s=Ze(a.group,o,n);return jsx(Je,{...a,entityLabel:l,labels:s})}function Je({canMutate:n,detachingKey:l,entityLabel:o,group:a,labels:s,onDetach:u}){let r=j();return jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1",children:[jsx("span",{className:"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground",children:o}),jsx("ul",{className:"fk:flex fk:flex-col fk:-mx-2",children:a.links.map(c=>{let p=p$2(c,s[c.recordId]),h=`${c.entity}:${c.recordId}`;return jsxs("li",{className:"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1 fk:corner-squircle",children:[jsx("button",{className:"fk:min-w-0 fk:flex-1 fk:truncate fk:text-left fk:text-sm fk:hover:underline fk:underline-offset-2",title:c.recordId,type:"button",onClick:()=>r({type:"EditEntity",payload:{entityId:c.recordId,entityNamePlural:a.entityPlural}}),children:p}),n?jsx(fe,{disabled:l!==null,label:`Detach from ${p}`,onClick:()=>u(c)}):null]},h)})})]})}function vt({api:n,projectId:l,source:o}){let a=b$3(),[s,u$1]=useState(null),{data:r,error:c$1,isLoading:p,mutate:h}=H(c(l).links(o.id),b),m=useMemo(()=>r?.links??[],[r]),y=useMemo(()=>r?.entities??[],[r]),f=useMemo(()=>q$1(m),[m]);async function b$1(i){u$1(`${i.entity}:${i.recordId}`);try{await n.unlinkSource(o.id,{entity:i.entity,recordId:i.recordId}),qa.success("Detached."),await h({links:m.filter(d=>d.entity!==i.entity||d.recordId!==i.recordId),entities:y},{revalidate:!1}),g();}catch(d){qa.error(h$1(d,"The document could not be detached."));}finally{u$1(null);}}async function v(i){u$1(`${i.entity}:*`);try{await n.unlinkSource(o.id,{entity:i.entity}),qa.success("Detached."),await h({links:m,entities:y.filter(d=>d.entity!==i.entity)},{revalidate:!1}),g();}catch(d){qa.error(h$1(d,"The document could not be detached."));}finally{u$1(null);}}async function w(i){u$1(`${i.name}:+`);try{let d=await n.linkSource(o.id,{entity:i.name});qa.success(d.linked?`Applies to every ${u(i)} now.`:`Already applied to every ${u(i)}.`),await h({links:m,entities:y.some(g=>g.entity===i.name)?y:[...y,{entity:i.name,entityPlural:i.plural}]},{revalidate:!1}),g();}catch(d){qa.error(h$1(d,"The document could not be attached."));}finally{u$1(null);}}let x;return c$1?x=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The linked records could not be loaded."}):p&&!r?x=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-6 fk:w-1/2"}),jsx(t$1,{className:"fk:h-6 fk:w-1/3"})]}):f.length===0?x=jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:'Not attached to any record. Open a record in the Desk and use "Attach document" so the agent searches this document before the rest of Knowledge when asked about that record.'}):x=jsx("div",{className:"fk:flex fk:flex-col fk:gap-4",children:f.map(i=>jsx(Ye,{canMutate:a,detachingKey:s,group:i,onDetach:d=>{b$1(d);}},i.entityPlural))}),jsxs(Fragment,{children:[jsx(tt,{busy:s!==null,canMutate:a,entities:y,isLoading:p&&!r,onAttach:i=>{w(i);},onDetach:i=>{v(i);}}),jsxs("div",{className:"fk:mt-2 fk:flex fk:items-center fk:gap-2",children:[jsx(PaperclipIcon,{className:"fk:size-4 fk:text-muted-foreground"}),jsx("h3",{className:"fk:text-sm fk:font-semibold fk:tracking-tight",children:"Linked records"}),m.length>0?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:m.length}):null]}),jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"When a question is about one of these records, the agent searches this document before the rest."}),x]})}function tt({busy:n,canMutate:l,entities:o$1,isLoading:a,onAttach:s,onDetach:u$2}){let{currentProject:r}=f(),c=useMemo(()=>r?.schema??[],[r]),[p,h]=useState(false),m$1=useMemo(()=>v(c,o$1),[o$1,c]),y=f=>{let b=t(c,f.entity);return b?u(b):f.entityPlural};return jsxs("div",{className:"fk:flex fk:flex-col fk:gap-3","data-knowledge-applies-to":true,children:[jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(LayersIcon,{className:"fk:size-4 fk:text-muted-foreground"}),jsx("h3",{className:"fk:text-sm fk:font-semibold fk:tracking-tight",children:"Applies to"}),o$1.length>0?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:o$1.length}):null]}),jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"Attach this document to a whole entity type and the agent searches it before the rest of Knowledge for every record of that type, and for questions about the type in general."}),a?jsx(t$1,{className:"fk:h-7 fk:w-1/3"}):jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[o$1.map(f=>{let b=y(f);return jsxs(b$2,{className:"fk:gap-1 fk:py-1 fk:pl-2.5 fk:pr-1 fk:corner-squircle",variant:"secondary",children:[jsx("span",{className:"fk:capitalize",children:b}),l?jsxs(b$4,{children:[jsx(c$2,{asChild:true,children:jsx("button",{"aria-label":`No longer apply to every ${b}`,className:"fk:rounded-sm fk:p-0.5 fk:text-muted-foreground fk:hover:text-foreground fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring fk:disabled:opacity-50",disabled:n,type:"button",onClick:()=>u$2(f),children:jsx(XIcon,{className:"fk:size-3"})})}),jsxs(e$1,{children:["No longer apply to every ",b]})]}):null]},f.entity)}),jsxs(t$2,{open:p,onOpenChange:h,children:[jsx(na,{disabled:!l,children:jsx(u$1,{asChild:true,children:jsxs(b$1,{className:"fk:h-7",disabled:!l||m$1.length===0,size:"sm",variant:"outline",children:[jsx(PlusIcon,{}),"Add entity type"]})})}),jsx(v$1,{align:"start",className:"fk:w-64 fk:p-0",children:jsxs(m,{children:[jsx(o,{placeholder:"Search entity types"}),jsxs(p$1,{children:[jsx(q$2,{children:"No entity type matches."}),jsx(r$1,{children:m$1.map(f=>jsx(t$3,{keywords:[u(f),f.name,f.plural],value:f.name,onSelect:()=>{h(false),s(f);},children:jsx("span",{className:"fk:capitalize",children:u(f)})},f.name))})]})]})})]})]})]})}export{yt as a,bt as b,vt as c};//# sourceMappingURL=chunk-3COXA5QH.js.map
2
- //# sourceMappingURL=chunk-3COXA5QH.js.map
1
+ import'./index.css';import {e,c,b,a,g,h as h$1,m as m$1,k as k$2,n}from'./chunk-NAUY7EN3.js';import {m as m$2,s as s$2}from'./chunk-RARRMN5A.js';import {b as b$3}from'./chunk-V7C4EHK3.js';import {j}from'./chunk-ZI22345U.js';import {c as c$3}from'./chunk-XMOSCJOI.js';import {t,s,u,q as q$1,v,k as k$1,i as i$1,o as o$1,r as r$2,p as p$2}from'./chunk-7KLXWCDS.js';import {a as a$2}from'./chunk-ERDARDGB.js';import {f}from'./chunk-WFJICDCL.js';import {na,p,q,r,t as t$2,u as u$1,v as v$1,qa,s as s$1}from'./chunk-DGIY4SKN.js';import {t as t$1}from'./chunk-SZEGGBOC.js';import {b as b$2,c as c$1,h,i,k,l,m,o,p as p$1,q as q$2,r as r$1,t as t$3}from'./chunk-32ZU4MLE.js';import {a as a$1,b as b$4,c as c$2,e as e$1}from'./chunk-USNXQOMJ.js';import {b as b$1}from'./chunk-6NRQMG26.js';import {useState,useMemo,useDeferredValue}from'react';import {BookOpenTextIcon,PaperclipIcon,ChevronRightIcon,LayersIcon,XIcon,PlusIcon,Unlink2Icon,LoaderCircle,SearchIcon}from'lucide-react';import {Link}from'react-router-dom';import H from'swr';import Qe from'swr/infinite';import {jsxs,Fragment,jsx}from'react/jsx-runtime';var Be=50;function fe({disabled:n,label:l,onClick:o}){return jsxs(b$4,{children:[jsx(c$2,{asChild:true,children:jsx(b$1,{"aria-label":l,className:"fk:size-7 fk:shrink-0",disabled:n,size:"icon",variant:"ghost",onClick:o,children:jsx(Unlink2Icon,{className:"fk:size-4"})})}),jsx(e$1,{children:l})]})}function Xe({api:n$1,attachedIds:l$1,onAttached:o,onOpenChange:a,open:s,projectId:u,target:r,targetLabel:c$2}){let[p,h$2]=useState(""),m=useDeferredValue(p.trim()),[y,f]=useState(null),b$1=(k,K)=>!s||K&&!K.hasMore?null:c(u).sources({limit:Be,offset:k*Be,search:m||void 0}),{data:v,error:w,isLoading:x,setSize:i$2,size:d}=Qe(b$1,b,{keepPreviousData:true}),g=useMemo(()=>r$2(v?.flatMap(k=>k.sources)??[],l$1),[l$1,v]),L=v?.[v.length-1]?.hasMore??false,C=v!==void 0&&d>v.length;async function A(k){f(k.id);try{let K=await n$1.linkSource(k.id,r);qa.success(K.linked?`Attached "${k.title}".`:`"${k.title}" was already attached.`),o(k),a(!1);}catch(K){qa.error(h$1(K,"The document could not be attached."));}finally{f(null);}}let R;return w?R=jsx("p",{className:"fk:py-6 fk:text-center fk:text-sm fk:text-destructive",children:"The documents could not be loaded."}):x&&!v?R=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-3 fk:py-2",children:[jsx(t$1,{className:"fk:h-10 fk:w-full"}),jsx(t$1,{className:"fk:h-10 fk:w-full"}),jsx(t$1,{className:"fk:h-10 fk:w-full"})]}):g.length===0&&!L?R=jsx("p",{className:"fk:py-6 fk:text-center fk:text-sm fk:text-muted-foreground",children:m?"No documents match your search.":"Every document is attached already, or there are none yet. Add documents in Knowledge first."}):R=jsxs("ul",{className:"fk:flex fk:max-h-80 fk:flex-col fk:overflow-y-auto fk:-mx-2",children:[g.map(k=>{let K=k$1(k),B=y===k.id;return jsx("li",{children:jsxs("button",{className:"fk:flex fk:w-full fk:min-w-0 fk:items-center fk:gap-3 fk:rounded-lg fk:px-2 fk:py-2 fk:text-left fk:transition-colors fk:hover:bg-accent fk:focus-visible:bg-accent fk:focus-visible:outline-none fk:disabled:opacity-60 fk:corner-squircle",disabled:y!==null,type:"button",onClick:()=>{A(k);},children:[jsx(m$1,{source:k}),jsxs("span",{className:"fk:min-w-0 fk:flex-1",children:[jsx("span",{className:"fk:block fk:truncate fk:text-sm fk:font-medium",children:k.title}),jsxs("span",{className:"fk:block fk:truncate fk:text-xs fk:text-muted-foreground",children:[i$1(k)," \xB7 ",K.detail]})]}),B?jsx(LoaderCircle,{className:"fk:size-4 fk:shrink-0 fk:animate-spin fk:text-muted-foreground"}):jsx(k$2,{label:K.label,tone:K.tone})]})},k.id)}),L&&!C?jsx("li",{"aria-hidden":true,children:jsx(n,{onVisible:()=>{i$2(k=>k+1);}})}):null,C?jsx("li",{className:"fk:flex fk:justify-center fk:py-2",children:jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin fk:text-muted-foreground"})}):null]}),jsx(c$1,{open:s,onOpenChange:a,children:jsxs(h,{className:"fk:sm:max-w-lg",children:[jsxs(i,{children:[jsx(k,{children:"Attach a document"}),jsx(l,{children:r.recordId===void 0?`Documents attached to every ${c$2} are searched before the rest of Knowledge when a question is about one of them, or about ${c$2} in general.`:`Documents attached to ${c$2} are searched before the rest of Knowledge when a question is about it.`})]}),jsxs("div",{className:"fk:relative",children:[jsx(SearchIcon,{className:"fk:pointer-events-none fk:absolute fk:left-2.5 fk:top-1/2 fk:size-4 fk:-translate-y-1/2 fk:text-muted-foreground"}),jsx(s$1,{"aria-label":"Search documents",autoFocus:true,className:"fk:pl-8",placeholder:"Search documents by title",value:p,onChange:k=>h$2(k.target.value)})]}),R]})})}function re({projectId:n,renderAction:l,sources:o}){return jsx("ul",{className:"fk:flex fk:flex-col fk:gap-1 fk:-mx-2",children:o.map(a=>{let s=k$1(a);return jsxs("li",{className:"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1.5 fk:corner-squircle",children:[jsxs(Link,{className:"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-3 fk:rounded-md fk:hover:underline fk:underline-offset-2",to:o$1(n,a.id),children:[jsx(m$1,{source:a}),jsxs("span",{className:"fk:min-w-0 fk:flex-1",children:[jsx("span",{className:"fk:block fk:truncate fk:text-sm fk:font-medium",children:a.title}),jsxs("span",{className:"fk:block fk:truncate fk:text-xs fk:text-muted-foreground",children:[i$1(a)," \xB7 ",s.detail]})]})]}),jsx(k$2,{label:s.label,tone:s.tone}),l?.(a)]},a.id)})})}function yt({entityName:n}){let{api:l,projectId:o}=e(),{currentProject:a$1}=f(),[s$1,u$1]=useState(false),r=t(a$1?.schema??[],n),c$1=!!r&&s(n),{data:p,error:h}=H(o&&c$1?c(o).entitySources(n):null,b);if(!l||!o||!r||!c$1||h instanceof a&&h.status===404)return null;let m=p?.sources.length??0;return jsxs(Fragment,{children:[jsxs(b$1,{"aria-label":`Knowledge for every ${u(r)}`,className:"fk:mr-2 fk:h-8","data-knowledge-entity-button":true,size:"sm",variant:"outline",onClick:()=>u$1(true),children:[jsx(BookOpenTextIcon,{}),"Knowledge",m>0?jsx(b$2,{className:"fk:corner-squircle",variant:"secondary",children:m}):null]}),jsx(Ue,{api:l,entityLabel:u(r),entityName:n,open:s$1,projectId:o,onOpenChange:u$1})]})}function Ue({api:n,entityLabel:l$1,entityName:o,onOpenChange:a,open:s,projectId:u}){let r=b$3(),[c$2,p]=useState(false),[h$2,m]=useState(null),{data:y,error:f,isLoading:b$4,mutate:v}=H(c(u).entitySources(o),b),w=y?.sources??[],x=useMemo(()=>({entity:o}),[o]);async function i$1(g$1){m(g$1.id);try{await n.unlinkSource(g$1.id,x),qa.success(`"${g$1.title}" no longer applies to every ${l$1}.`),await v({sources:w.filter(L=>L.id!==g$1.id)},{revalidate:!1}),g();}catch(L){qa.error(h$1(L,"The document could not be detached."));}finally{m(null);}}let d;return f?d=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The documents could not be loaded."}):b$4&&!y?d=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-9 fk:w-full"}),jsx(t$1,{className:"fk:h-9 fk:w-2/3"})]}):w.length===0?d=jsxs("p",{className:"fk:text-sm fk:text-muted-foreground",children:["No documents apply to every ",l$1," yet. Attach a guide, a policy or a spec that holds for all of them and the agent searches it first when asked about any ",l$1,", or about ",l$1," in general."]}):d=jsx(re,{projectId:u,sources:w,renderAction:g=>r?jsx(fe,{disabled:h$2!==null,label:`Detach ${g.title}`,onClick:()=>{i$1(g);}}):null}),jsx(c$1,{open:s,onOpenChange:a,children:jsxs(h,{className:"fk:sm:max-w-lg","data-knowledge-entity-dialog":true,children:[jsxs(i,{children:[jsxs(k,{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(BookOpenTextIcon,{className:"fk:size-4 fk:text-muted-foreground"}),"Knowledge for every ",l$1,y?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:w.length}):null]}),jsxs(l,{children:["Documents attached here apply to every ",l$1,"; each record can hold its own on top."]})]}),jsx("div",{className:"fk:max-h-80 fk:overflow-y-auto",children:d}),jsx("div",{className:"fk:flex fk:justify-end",children:jsx(na,{disabled:!r,children:jsxs(b$1,{disabled:!r,size:"sm",variant:"outline",onClick:()=>p(true),children:[jsx(PaperclipIcon,{}),"Attach document"]})})}),jsx(Xe,{api:n,attachedIds:w.map(g=>g.id),open:c$2,projectId:u,target:x,targetLabel:l$1,onAttached:g$1=>{v({sources:w.some(L=>L.id===g$1.id)?w:[...w,g$1]},{revalidate:false}),g();},onOpenChange:p})]})})}function bt({entityName:n,recordId:l,recordLabel:o}){let{api:a$2,projectId:s$1}=e(),{currentProject:u$1}=f(),r$1=b$3(),[c$1,p$1]=useState(false),[h,m]=useState(false),[y,f$1]=useState(null),b$4=useMemo(()=>({entity:n,recordId:l}),[n,l]),v=t(u$1?.schema??[],n),w=v?u(v):n,x=s(n),{data:i,error:d,isLoading:g$1,mutate:L}=H(s$1&&x?c(s$1).recordSources(b$4):null,b);if(!a$2||!s$1||!x||d instanceof a&&d.status===404)return null;let C=i?.sources??[],A=i?.inherited??[],R=C.map(N=>N.id),k=a$2;async function K(N){f$1(N.id);try{await k.unlinkSource(N.id,b$4),qa.success(`Detached "${N.title}".`),await L({sources:C.filter($=>$.id!==N.id),inherited:A},{revalidate:!1}),g();}catch($){qa.error(h$1($,"The document could not be detached."));}finally{f$1(null);}}let B;return d?B=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The attached documents could not be loaded."}):g$1&&!i?B=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-9 fk:w-full"}),jsx(t$1,{className:"fk:h-9 fk:w-2/3"})]}):B=jsxs("div",{className:"fk:flex fk:flex-col fk:gap-4",children:[C.length===0?jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:A.length>0?"No documents attached to this record itself; the ones below apply to every record of its type.":"No documents attached. Attach a manual, spec or contract and the agent will use it alongside the record's data when asked about this record."}):jsx(re,{projectId:s$1,sources:C,renderAction:N=>r$1?jsx(fe,{disabled:y!==null,label:`Detach ${N.title}`,onClick:()=>{K(N);}}):null}),A.length>0?jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1","data-knowledge-inherited":true,children:[jsxs("span",{className:"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground",children:["Applies to every ",w]}),jsx(re,{projectId:s$1,sources:A})]}):null]}),jsx(a$1,{children:jsxs(p,{className:`fk:z-10 fk:flex fk:shrink-0 fk:flex-col fk:border-t fk:bg-background ${c$1?"fk:h-1/2":""}`,"data-knowledge-record-panel":true,open:c$1,onOpenChange:p$1,children:[jsxs("div",{className:"fk:flex fk:shrink-0 fk:items-center fk:gap-2 fk:pl-4 fk:pr-10 fk:py-2",children:[jsx(q,{asChild:true,children:jsxs("button",{className:"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-2 fk:rounded-md fk:py-1 fk:text-left fk:text-sm fk:font-semibold fk:tracking-tight fk:hover:text-foreground/80 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring",type:"button",children:[jsx(ChevronRightIcon,{className:`fk:size-4 fk:shrink-0 fk:text-muted-foreground fk:transition-transform ${c$1?"fk:rotate-90":""}`}),jsx(BookOpenTextIcon,{className:"fk:size-4 fk:shrink-0 fk:text-muted-foreground"}),"Knowledge",i?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:C.length+A.length}):null]})}),c$1?jsx(na,{disabled:!r$1,children:jsxs(b$1,{disabled:!r$1,size:"sm",variant:"outline",onClick:()=>m(true),children:[jsx(PaperclipIcon,{}),"Attach document"]})}):null]}),jsx(r,{className:"fk:min-h-0 fk:flex-1 fk:overflow-y-auto fk:px-10 fk:pb-6",children:B}),jsx(Xe,{api:a$2,attachedIds:R,open:h,projectId:s$1,target:b$4,targetLabel:o||`this ${n}`,onAttached:N=>{L({sources:C.some($=>$.id===N.id)?C:[...C,N],inherited:A.filter($=>$.id!==N.id)},{revalidate:false}),g();},onOpenChange:m})]})})}function Ze(n,l,o){let{scope:a}=c$3(),s=n.links.map(r=>r.recordId),{data:u}=s$2({entityNamePlural:n.entityPlural,schema:l,scope:a,selection:"display",includeCount:false,variables:{where:{_id:{in:s}},limit:s.length}});return useMemo(()=>{let r={};for(let c of u??[]){let p=c[o.name];typeof p=="string"&&p.trim()&&(r[c._id]=p);}return r},[u,o])}function Ye(n){let{currentProject:l}=f(),o=useMemo(()=>l?.schema??[],[l]),a=m$2(o,n.group.entityPlural),s=a$2(a);return !a||!s?jsx(Je,{...n,entityLabel:a?u(a):n.group.entityPlural,labels:{}}):jsx(et,{...n,displayAttribute:s,schema:o,entityLabel:u(a)})}function et({displayAttribute:n,entityLabel:l,schema:o,...a}){let s=Ze(a.group,o,n);return jsx(Je,{...a,entityLabel:l,labels:s})}function Je({canMutate:n,detachingKey:l,entityLabel:o,group:a,labels:s,onDetach:u}){let r=j();return jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1",children:[jsx("span",{className:"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground",children:o}),jsx("ul",{className:"fk:flex fk:flex-col fk:-mx-2",children:a.links.map(c=>{let p=p$2(c,s[c.recordId]),h=`${c.entity}:${c.recordId}`;return jsxs("li",{className:"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1 fk:corner-squircle",children:[jsx("button",{className:"fk:min-w-0 fk:flex-1 fk:truncate fk:text-left fk:text-sm fk:hover:underline fk:underline-offset-2",title:c.recordId,type:"button",onClick:()=>r({type:"EditEntity",payload:{entityId:c.recordId,entityNamePlural:a.entityPlural}}),children:p}),n?jsx(fe,{disabled:l!==null,label:`Detach from ${p}`,onClick:()=>u(c)}):null]},h)})})]})}function vt({api:n,projectId:l,source:o}){let a=b$3(),[s,u$1]=useState(null),{data:r,error:c$1,isLoading:p,mutate:h}=H(c(l).links(o.id),b),m=useMemo(()=>r?.links??[],[r]),y=useMemo(()=>r?.entities??[],[r]),f=useMemo(()=>q$1(m),[m]);async function b$1(i){u$1(`${i.entity}:${i.recordId}`);try{await n.unlinkSource(o.id,{entity:i.entity,recordId:i.recordId}),qa.success("Detached."),await h({links:m.filter(d=>d.entity!==i.entity||d.recordId!==i.recordId),entities:y},{revalidate:!1}),g();}catch(d){qa.error(h$1(d,"The document could not be detached."));}finally{u$1(null);}}async function v(i){u$1(`${i.entity}:*`);try{await n.unlinkSource(o.id,{entity:i.entity}),qa.success("Detached."),await h({links:m,entities:y.filter(d=>d.entity!==i.entity)},{revalidate:!1}),g();}catch(d){qa.error(h$1(d,"The document could not be detached."));}finally{u$1(null);}}async function w(i){u$1(`${i.name}:+`);try{let d=await n.linkSource(o.id,{entity:i.name});qa.success(d.linked?`Applies to every ${u(i)} now.`:`Already applied to every ${u(i)}.`),await h({links:m,entities:y.some(g=>g.entity===i.name)?y:[...y,{entity:i.name,entityPlural:i.plural}]},{revalidate:!1}),g();}catch(d){qa.error(h$1(d,"The document could not be attached."));}finally{u$1(null);}}let x;return c$1?x=jsx("p",{className:"fk:text-sm fk:text-destructive",children:"The linked records could not be loaded."}):p&&!r?x=jsxs("div",{"aria-busy":"true",className:"fk:flex fk:flex-col fk:gap-2",children:[jsx(t$1,{className:"fk:h-6 fk:w-1/2"}),jsx(t$1,{className:"fk:h-6 fk:w-1/3"})]}):f.length===0?x=jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:'Not attached to any record. Open a record in the Desk and use "Attach document" so the agent searches this document before the rest of Knowledge when asked about that record.'}):x=jsx("div",{className:"fk:flex fk:flex-col fk:gap-4",children:f.map(i=>jsx(Ye,{canMutate:a,detachingKey:s,group:i,onDetach:d=>{b$1(d);}},i.entityPlural))}),jsxs(Fragment,{children:[jsx(tt,{busy:s!==null,canMutate:a,entities:y,isLoading:p&&!r,onAttach:i=>{w(i);},onDetach:i=>{v(i);}}),jsxs("div",{className:"fk:mt-2 fk:flex fk:items-center fk:gap-2",children:[jsx(PaperclipIcon,{className:"fk:size-4 fk:text-muted-foreground"}),jsx("h3",{className:"fk:text-sm fk:font-semibold fk:tracking-tight",children:"Linked records"}),m.length>0?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:m.length}):null]}),jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"When a question is about one of these records, the agent searches this document before the rest."}),x]})}function tt({busy:n,canMutate:l,entities:o$1,isLoading:a,onAttach:s,onDetach:u$2}){let{currentProject:r}=f(),c=useMemo(()=>r?.schema??[],[r]),[p,h]=useState(false),m$1=useMemo(()=>v(c,o$1),[o$1,c]),y=f=>{let b=t(c,f.entity);return b?u(b):f.entityPlural};return jsxs("div",{className:"fk:flex fk:flex-col fk:gap-3","data-knowledge-applies-to":true,children:[jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(LayersIcon,{className:"fk:size-4 fk:text-muted-foreground"}),jsx("h3",{className:"fk:text-sm fk:font-semibold fk:tracking-tight",children:"Applies to"}),o$1.length>0?jsx(b$2,{className:"fk:corner-squircle",variant:"outline",children:o$1.length}):null]}),jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"Attach this document to a whole entity type and the agent searches it before the rest of Knowledge for every record of that type, and for questions about the type in general."}),a?jsx(t$1,{className:"fk:h-7 fk:w-1/3"}):jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[o$1.map(f=>{let b=y(f);return jsxs(b$2,{className:"fk:gap-1 fk:py-1 fk:pl-2.5 fk:pr-1 fk:corner-squircle",variant:"secondary",children:[jsx("span",{className:"fk:capitalize",children:b}),l?jsxs(b$4,{children:[jsx(c$2,{asChild:true,children:jsx("button",{"aria-label":`No longer apply to every ${b}`,className:"fk:rounded-sm fk:p-0.5 fk:text-muted-foreground fk:hover:text-foreground fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring fk:disabled:opacity-50",disabled:n,type:"button",onClick:()=>u$2(f),children:jsx(XIcon,{className:"fk:size-3"})})}),jsxs(e$1,{children:["No longer apply to every ",b]})]}):null]},f.entity)}),jsxs(t$2,{open:p,onOpenChange:h,children:[jsx(na,{disabled:!l,children:jsx(u$1,{asChild:true,children:jsxs(b$1,{className:"fk:h-7",disabled:!l||m$1.length===0,size:"sm",variant:"outline",children:[jsx(PlusIcon,{}),"Add entity type"]})})}),jsx(v$1,{align:"start",className:"fk:w-64 fk:p-0",children:jsxs(m,{children:[jsx(o,{placeholder:"Search entity types"}),jsxs(p$1,{children:[jsx(q$2,{children:"No entity type matches."}),jsx(r$1,{children:m$1.map(f=>jsx(t$3,{keywords:[u(f),f.name,f.plural],value:f.name,onSelect:()=>{h(false),s(f);},children:jsx("span",{className:"fk:capitalize",children:u(f)})},f.name))})]})]})})]})]})]})}export{yt as a,bt as b,vt as c};//# sourceMappingURL=chunk-3L4LYXSR.js.map
2
+ //# sourceMappingURL=chunk-3L4LYXSR.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/apps/knowledge/record-links.tsx"],"names":["PICKER_PAGE_SIZE","DetachButton","disabled","label","onClick","jsxs","Tooltip","jsx","TooltipTrigger","Button","Unlink2Icon","TooltipContent","AttachDocumentDialog","api","attachedIds","onAttached","onOpenChange","open","projectId","target","targetLabel","search","setSearch","useState","deferredSearch","useDeferredValue","attachingId","setAttachingId","getPageKey","pageIndex","previousPage","knowledgePaths","pages","error","isLoading","setSize","size","useSWRInfinite","fetcher","candidates","useMemo","getAttachableSources","page","hasMore","isLoadingMore","attach","source","result","toast","attachError","describeApiError","body","Skeleton","status","summarizeKnowledgeStatus","isAttaching","SourceIcon","getKnowledgeKindLabel","LoaderCircle","StatusBadge","InfiniteScrollSentinel","current","Dialog","DialogContent","DialogHeader","DialogTitle","DialogDescription","SearchIcon","Input","event","SourceRows","renderAction","sources","Link","getKnowledgeSourcePath","EntityKnowledgeButton","entityName","useProjectKnowledge","currentProject","useConfig","isOpen","setIsOpen","entitySchema","findEntityByName","isLinkable","isKnowledgeLinkableEntity","data","useSWR","FetcherError","count","Fragment","getEntityLinkLabel","BookOpenTextIcon","Badge","EntityKnowledgeDialog","entityLabel","canMutate","useCanMutate","isPickerOpen","setIsPickerOpen","detachingId","setDetachingId","mutate","detach","entry","invalidateKnowledgeLinks","detachError","PermissionTooltip","PaperclipIcon","RecordKnowledgePanel","recordId","recordLabel","record","inherited","knowledgeApi","TooltipProvider","Collapsible","CollapsibleTrigger","ChevronRightIcon","CollapsibleContent","useRecordLabels","group","schema","displayAttribute","scope","useAppContext","ids","link","useEntityQuery","labels","item","value","LinkedRecordGroup","props","getEntitySchema","getDisplayAttribute","LinkedRecordRows","ResolvedLinkedRecordGroup","detachingKey","onDetach","dispatch","useDispatch","getKnowledgeLinkLabel","key","LinkedRecordsSection","setDetachingKey","links","entities","groups","groupKnowledgeLinks","detachEntity","attachEntity","entity","AppliesToEntities","busy","onAttach","getLinkableEntities","labelOf","LayersIcon","XIcon","Popover","PopoverTrigger","PlusIcon","PopoverContent","Command","CommandInput","CommandList","CommandEmpty","CommandGroup","CommandItem"],"mappings":"ilCAsFA,IAAMA,EAAAA,CAAmB,EAAA,CAEzB,SAASC,EAAAA,CAAa,CACpB,QAAA,CAAAC,CAAAA,CACA,MAAAC,CAAAA,CACA,OAAA,CAAAC,CACF,CAAA,CAIgB,CACd,OACEC,IAAAA,CAACC,GAAAA,CAAA,CACC,QAAA,CAAA,CAAAC,IAACC,GAAAA,CAAA,CAAe,QAAO,IAAA,CACrB,QAAA,CAAAD,IAACE,GAAAA,CAAA,CACC,YAAA,CAAYN,CAAAA,CACZ,UAAU,uBAAA,CACV,QAAA,CAAUD,EACV,IAAA,CAAK,MAAA,CACL,QAAQ,OAAA,CACR,OAAA,CAASE,CAAAA,CAET,QAAA,CAAAG,IAACG,WAAAA,CAAA,CAAY,SAAA,CAAU,WAAA,CAAY,EACrC,CAAA,CACF,CAAA,CACAH,GAAAA,CAACI,GAAAA,CAAA,CAAgB,QAAA,CAAAR,CAAAA,CAAM,GACzB,CAEJ,CAMA,SAASS,EAAAA,CAAqB,CAC5B,GAAA,CAAAC,GAAAA,CACA,YAAAC,GAAAA,CACA,UAAA,CAAAC,EACA,YAAA,CAAAC,CAAAA,CACA,KAAAC,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,MAAA,CAAAC,EACA,WAAA,CAAAC,GACF,EAWgB,CACd,GAAM,CAACC,CAAAA,CAAQC,GAAS,CAAA,CAAIC,QAAAA,CAAS,EAAE,CAAA,CACjCC,CAAAA,CAAiBC,gBAAAA,CAAiBJ,CA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AAC4J,GAAAA,CAAA,CAAe,KAAA,CAAM,OAAA,CAAQ,SAAA,CAAU,gBAAA,CACtC,SAAA9J,IAAAA,CAAC+J,CAAAA,CAAA,CACC,QAAA,CAAA,CAAA7J,GAAAA,CAAC8J,EAAA,CAAa,WAAA,CAAY,qBAAA,CAAsB,CAAA,CAChDhK,KAACiK,GAAAA,CAAA,CACC,UAAA/J,GAAAA,CAACgK,GAAAA,CAAA,CAAa,QAAA,CAAA,yBAAA,CAAuB,CAAA,CACrChK,GAAAA,CAACiK,GAAAA,CAAA,CACE,QAAA,CAAAjI,GAAAA,CAAW,IAAKiH,CAAAA,EACfjJ,GAAAA,CAACkK,IAAA,CAEC,QAAA,CAAU,CAAC9E,CAAAA,CAAmB6D,CAAM,CAAA,CAAGA,CAAAA,CAAO,KAAMA,CAAAA,CAAO,MAAM,EACjE,KAAA,CAAOA,CAAAA,CAAO,IAAA,CACd,QAAA,CAAU,IAAM,CACdrD,CAAAA,CAAgB,KAAK,CAAA,CACrBwD,CAAAA,CAASH,CAAM,EACjB,CAAA,CAEA,QAAA,CAAAjJ,GAAAA,CAAC,QAAK,SAAA,CAAU,eAAA,CAAiB,SAAAoF,CAAAA,CAAmB6D,CAAM,EAAE,CAAA,CAAA,CARvDA,CAAAA,CAAO,IASd,CACD,EACH,CAAA,CAAA,CACF,CAAA,CAAA,CACF,EACF,CAAA,CAAA,CACF,CAAA,CAAA,CACF,GAEJ,CAEJ","file":"chunk-3COXA5QH.js","sourcesContent":["import type { JSX } from 'react';\nimport { useDeferredValue, useMemo, useState } from 'react';\nimport {\n BookOpenTextIcon,\n ChevronRightIcon,\n LayersIcon,\n LoaderCircle,\n PaperclipIcon,\n PlusIcon,\n SearchIcon,\n Unlink2Icon,\n XIcon,\n} from 'lucide-react';\nimport { Link } from 'react-router-dom';\nimport useSWR from 'swr';\nimport useSWRInfinite from 'swr/infinite';\nimport { useAppContext } from '../../core/app-context';\nimport { useConfig } from '../../core/config/config-context';\nimport { getDisplayAttribute } from '../../core/get-display-attribute';\nimport type { Attribute, Entity } from '../../core/types';\nimport { useCanMutate } from '../../core/permissions';\nimport { useDispatch } from '../../entities/actions-context';\nimport { getEntitySchema } from '../../graphql-client/queries';\nimport type { MappedEntityItem } from '../../graphql-client/types';\nimport { useEntityQuery } from '../../graphql-client/use-entity-query';\nimport {\n Badge,\n Button,\n Collapsible,\n CollapsibleContent,\n CollapsibleTrigger,\n Command,\n CommandEmpty,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n Input,\n PermissionTooltip,\n Popover,\n PopoverContent,\n PopoverTrigger,\n Skeleton,\n toast,\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from '../../ui';\nimport { fetcher, FetcherError, knowledgePaths, type KnowledgeApi } from './api';\nimport {\n findEntityByName,\n getAttachableSources,\n getEntityLinkLabel,\n getKnowledgeKindLabel,\n getKnowledgeLinkLabel,\n getKnowledgeSourcePath,\n getLinkableEntities,\n groupKnowledgeLinks,\n isKnowledgeLinkableEntity,\n summarizeKnowledgeStatus,\n type KnowledgeEntityLink,\n type KnowledgeEntitySources,\n type KnowledgeLink,\n type KnowledgeLinkGroup,\n type KnowledgeLinksList,\n type KnowledgeLinkTarget,\n type KnowledgeRecordRef,\n type KnowledgeRecordSources,\n type KnowledgeSource,\n type KnowledgeSourcesList,\n} from './knowledge';\nimport {\n describeApiError,\n InfiniteScrollSentinel,\n invalidateKnowledgeLinks,\n SourceIcon,\n StatusBadge,\n useProjectKnowledge,\n} from './shared';\n\nconst PICKER_PAGE_SIZE = 50;\n\nfunction DetachButton({\n disabled,\n label,\n onClick,\n}: {\n disabled: boolean;\n label: string;\n onClick: () => void;\n}): JSX.Element {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n aria-label={label}\n className=\"fk:size-7 fk:shrink-0\"\n disabled={disabled}\n size=\"icon\"\n variant=\"ghost\"\n onClick={onClick}\n >\n <Unlink2Icon className=\"fk:size-4\" />\n </Button>\n </TooltipTrigger>\n <TooltipContent>{label}</TooltipContent>\n </Tooltip>\n );\n}\n\n/**\n * The picker behind \"Attach document\": the project's documents, searched by\n * title, minus the ones already attached. Picking one links it right away.\n */\nfunction AttachDocumentDialog({\n api,\n attachedIds,\n onAttached,\n onOpenChange,\n open,\n projectId,\n target,\n targetLabel,\n}: {\n api: KnowledgeApi;\n attachedIds: string[];\n onAttached: (_source: KnowledgeSource) => void;\n onOpenChange: (_open: boolean) => void;\n open: boolean;\n projectId: string;\n /** A record, or an entity type when it names no record. */\n target: KnowledgeLinkTarget;\n /** How the target is called in the dialog copy: a record title, or an entity label. */\n targetLabel: string;\n}): JSX.Element {\n const [search, setSearch] = useState('');\n const deferredSearch = useDeferredValue(search.trim());\n const [attachingId, setAttachingId] = useState<string | null>(null);\n const getPageKey = (pageIndex: number, previousPage: KnowledgeSourcesList | null): string | null => {\n if (!open || (previousPage && !previousPage.hasMore)) {\n return null;\n }\n\n return knowledgePaths(projectId).sources({\n limit: PICKER_PAGE_SIZE,\n offset: pageIndex * PICKER_PAGE_SIZE,\n search: deferredSearch || undefined,\n });\n };\n // Paged like the document list: the attached ones are hidden client-side,\n // so a record with many documents attached must be able to reach the next page.\n const {\n data: pages,\n error,\n isLoading,\n setSize,\n size,\n } = useSWRInfinite<KnowledgeSourcesList>(getPageKey, fetcher, { keepPreviousData: true });\n const candidates = useMemo(\n () => getAttachableSources(pages?.flatMap((page) => page.sources) ?? [], attachedIds),\n [attachedIds, pages]\n );\n const hasMore = pages?.[pages.length - 1]?.hasMore ?? false;\n const isLoadingMore = pages !== undefined && size > pages.length;\n\n async function attach(source: KnowledgeSource): Promise<void> {\n setAttachingId(source.id);\n\n try {\n const result = await api.linkSource(source.id, target);\n\n toast.success(result.linked ? `Attached \"${source.title}\".` : `\"${source.title}\" was already attached.`);\n onAttached(source);\n onOpenChange(false);\n } catch (attachError) {\n toast.error(describeApiError(attachError, 'The document could not be attached.'));\n } finally {\n setAttachingId(null);\n }\n }\n\n let body: JSX.Element;\n\n if (error) {\n body = <p className=\"fk:py-6 fk:text-center fk:text-sm fk:text-destructive\">The documents could not be loaded.</p>;\n } else if (isLoading && !pages) {\n body = (\n <div aria-busy=\"true\" className=\"fk:flex fk:flex-col fk:gap-3 fk:py-2\">\n <Skeleton className=\"fk:h-10 fk:w-full\" />\n <Skeleton className=\"fk:h-10 fk:w-full\" />\n <Skeleton className=\"fk:h-10 fk:w-full\" />\n </div>\n );\n } else if (candidates.length === 0 && !hasMore) {\n body = (\n <p className=\"fk:py-6 fk:text-center fk:text-sm fk:text-muted-foreground\">\n {deferredSearch\n ? 'No documents match your search.'\n : 'Every document is attached already, or there are none yet. Add documents in Knowledge first.'}\n </p>\n );\n } else {\n body = (\n <ul className=\"fk:flex fk:max-h-80 fk:flex-col fk:overflow-y-auto fk:-mx-2\">\n {candidates.map((source) => {\n const status = summarizeKnowledgeStatus(source);\n const isAttaching = attachingId === source.id;\n\n return (\n <li key={source.id}>\n <button\n className=\"fk:flex fk:w-full fk:min-w-0 fk:items-center fk:gap-3 fk:rounded-lg fk:px-2 fk:py-2 fk:text-left fk:transition-colors fk:hover:bg-accent fk:focus-visible:bg-accent fk:focus-visible:outline-none fk:disabled:opacity-60 fk:corner-squircle\"\n disabled={attachingId !== null}\n type=\"button\"\n onClick={() => void attach(source)}\n >\n <SourceIcon source={source} />\n <span className=\"fk:min-w-0 fk:flex-1\">\n <span className=\"fk:block fk:truncate fk:text-sm fk:font-medium\">{source.title}</span>\n <span className=\"fk:block fk:truncate fk:text-xs fk:text-muted-foreground\">\n {getKnowledgeKindLabel(source)} · {status.detail}\n </span>\n </span>\n {isAttaching ? (\n <LoaderCircle className=\"fk:size-4 fk:shrink-0 fk:animate-spin fk:text-muted-foreground\" />\n ) : (\n <StatusBadge label={status.label} tone={status.tone} />\n )}\n </button>\n </li>\n );\n })}\n {hasMore && !isLoadingMore ? (\n <li aria-hidden>\n <InfiniteScrollSentinel onVisible={() => void setSize((current) => current + 1)} />\n </li>\n ) : null}\n {isLoadingMore ? (\n <li className=\"fk:flex fk:justify-center fk:py-2\">\n <LoaderCircle className=\"fk:size-4 fk:animate-spin fk:text-muted-foreground\" />\n </li>\n ) : null}\n </ul>\n );\n }\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"fk:sm:max-w-lg\">\n <DialogHeader>\n <DialogTitle>Attach a document</DialogTitle>\n <DialogDescription>\n {target.recordId === undefined\n ? `Documents attached to every ${targetLabel} are searched before the rest of Knowledge when a question is about one of them, or about ${targetLabel} in general.`\n : `Documents attached to ${targetLabel} are searched before the rest of Knowledge when a question is about it.`}\n </DialogDescription>\n </DialogHeader>\n <div className=\"fk:relative\">\n <SearchIcon className=\"fk:pointer-events-none fk:absolute fk:left-2.5 fk:top-1/2 fk:size-4 fk:-translate-y-1/2 fk:text-muted-foreground\" />\n <Input\n aria-label=\"Search documents\"\n autoFocus\n className=\"fk:pl-8\"\n placeholder=\"Search documents by title\"\n value={search}\n onChange={(event) => setSearch(event.target.value)}\n />\n </div>\n {body}\n </DialogContent>\n </Dialog>\n );\n}\n\n/** Document rows shared by the record panel and the entity dialog: icon, title, kind and status, plus an optional action. */\nfunction SourceRows({\n projectId,\n renderAction,\n sources,\n}: {\n projectId: string;\n renderAction?: (_source: KnowledgeSource) => JSX.Element | null;\n sources: KnowledgeSource[];\n}): JSX.Element {\n return (\n <ul className=\"fk:flex fk:flex-col fk:gap-1 fk:-mx-2\">\n {sources.map((source) => {\n const status = summarizeKnowledgeStatus(source);\n\n return (\n <li\n className=\"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1.5 fk:corner-squircle\"\n key={source.id}\n >\n <Link\n className=\"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-3 fk:rounded-md fk:hover:underline fk:underline-offset-2\"\n to={getKnowledgeSourcePath(projectId, source.id)}\n >\n <SourceIcon source={source} />\n <span className=\"fk:min-w-0 fk:flex-1\">\n <span className=\"fk:block fk:truncate fk:text-sm fk:font-medium\">{source.title}</span>\n <span className=\"fk:block fk:truncate fk:text-xs fk:text-muted-foreground\">\n {getKnowledgeKindLabel(source)} · {status.detail}\n </span>\n </span>\n </Link>\n <StatusBadge label={status.label} tone={status.tone} />\n {renderAction?.(source)}\n </li>\n );\n })}\n </ul>\n );\n}\n\n/**\n * The documents attached to every record of an entity type, behind a button\n * in the Desk list toolbar: open them, attach another, detach one. Only the\n * project's own entities qualify, and the button stays out while the schema\n * is unknown.\n */\nexport function EntityKnowledgeButton({ entityName }: { entityName: string }): JSX.Element | null {\n const { api, projectId } = useProjectKnowledge();\n const { currentProject } = useConfig();\n const [isOpen, setIsOpen] = useState(false);\n const entitySchema = findEntityByName(currentProject?.schema ?? [], entityName);\n const isLinkable = Boolean(entitySchema) && isKnowledgeLinkableEntity(entityName);\n const { data, error } = useSWR<KnowledgeEntitySources>(\n projectId && isLinkable ? knowledgePaths(projectId).entitySources(entityName) : null,\n fetcher\n );\n\n if (!api || !projectId || !entitySchema || !isLinkable || (error instanceof FetcherError && error.status === 404)) {\n return null;\n }\n\n const count = data?.sources.length ?? 0;\n\n return (\n <>\n <Button\n aria-label={`Knowledge for every ${getEntityLinkLabel(entitySchema)}`}\n className=\"fk:mr-2 fk:h-8\"\n data-knowledge-entity-button\n size=\"sm\"\n variant=\"outline\"\n onClick={() => setIsOpen(true)}\n >\n <BookOpenTextIcon />\n Knowledge\n {count > 0 ? (\n <Badge className=\"fk:corner-squircle\" variant=\"secondary\">\n {count}\n </Badge>\n ) : null}\n </Button>\n <EntityKnowledgeDialog\n api={api}\n entityLabel={getEntityLinkLabel(entitySchema)}\n entityName={entityName}\n open={isOpen}\n projectId={projectId}\n onOpenChange={setIsOpen}\n />\n </>\n );\n}\n\nfunction EntityKnowledgeDialog({\n api,\n entityLabel,\n entityName,\n onOpenChange,\n open,\n projectId,\n}: {\n api: KnowledgeApi;\n entityLabel: string;\n entityName: string;\n onOpenChange: (_open: boolean) => void;\n open: boolean;\n projectId: string;\n}): JSX.Element {\n const canMutate = useCanMutate();\n const [isPickerOpen, setIsPickerOpen] = useState(false);\n const [detachingId, setDetachingId] = useState<string | null>(null);\n const { data, error, isLoading, mutate } = useSWR<KnowledgeEntitySources>(\n knowledgePaths(projectId).entitySources(entityName),\n fetcher\n );\n const sources = data?.sources ?? [];\n const target = useMemo<KnowledgeLinkTarget>(() => ({ entity: entityName }), [entityName]);\n\n async function detach(source: KnowledgeSource): Promise<void> {\n setDetachingId(source.id);\n\n try {\n await api.unlinkSource(source.id, target);\n toast.success(`\"${source.title}\" no longer applies to every ${entityLabel}.`);\n await mutate({ sources: sources.filter((entry) => entry.id !== source.id) }, { revalidate: false });\n void invalidateKnowledgeLinks();\n } catch (detachError) {\n toast.error(describeApiError(detachError, 'The document could not be detached.'));\n } finally {\n setDetachingId(null);\n }\n }\n\n let body: JSX.Element;\n\n if (error) {\n body = <p className=\"fk:text-sm fk:text-destructive\">The documents could not be loaded.</p>;\n } else if (isLoading && !data) {\n body = (\n <div aria-busy=\"true\" className=\"fk:flex fk:flex-col fk:gap-2\">\n <Skeleton className=\"fk:h-9 fk:w-full\" />\n <Skeleton className=\"fk:h-9 fk:w-2/3\" />\n </div>\n );\n } else if (sources.length === 0) {\n body = (\n <p className=\"fk:text-sm fk:text-muted-foreground\">\n No documents apply to every {entityLabel} yet. Attach a guide, a policy or a spec that holds for all of them and\n the agent searches it first when asked about any {entityLabel}, or about {entityLabel} in general.\n </p>\n );\n } else {\n body = (\n <SourceRows\n projectId={projectId}\n sources={sources}\n renderAction={(source) =>\n canMutate ? (\n <DetachButton\n disabled={detachingId !== null}\n label={`Detach ${source.title}`}\n onClick={() => void detach(source)}\n />\n ) : null\n }\n />\n );\n }\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"fk:sm:max-w-lg\" data-knowledge-entity-dialog>\n <DialogHeader>\n <DialogTitle className=\"fk:flex fk:items-center fk:gap-2\">\n <BookOpenTextIcon className=\"fk:size-4 fk:text-muted-foreground\" />\n Knowledge for every {entityLabel}\n {data ? (\n <Badge className=\"fk:corner-squircle\" variant=\"outline\">\n {sources.length}\n </Badge>\n ) : null}\n </DialogTitle>\n <DialogDescription>\n Documents attached here apply to every {entityLabel}; each record can hold its own on top.\n </DialogDescription>\n </DialogHeader>\n <div className=\"fk:max-h-80 fk:overflow-y-auto\">{body}</div>\n <div className=\"fk:flex fk:justify-end\">\n <PermissionTooltip disabled={!canMutate}>\n <Button disabled={!canMutate} size=\"sm\" variant=\"outline\" onClick={() => setIsPickerOpen(true)}>\n <PaperclipIcon />\n Attach document\n </Button>\n </PermissionTooltip>\n </div>\n <AttachDocumentDialog\n api={api}\n attachedIds={sources.map((source) => source.id)}\n open={isPickerOpen}\n projectId={projectId}\n target={target}\n targetLabel={entityLabel}\n onAttached={(source) => {\n // \"Already attached\" (a stale picker in another tab) must not list the document twice.\n void mutate(\n { sources: sources.some((entry) => entry.id === source.id) ? sources : [...sources, source] },\n { revalidate: false }\n );\n void invalidateKnowledgeLinks();\n }}\n onOpenChange={setIsPickerOpen}\n />\n </DialogContent>\n </Dialog>\n );\n}\n\n/**\n * The documents attached to one record, pinned under the record form in the\n * Desk as a collapsible panel: open them, attach another, detach one. The\n * agent searches these before the rest of Knowledge when a question is about this record.\n */\nexport function RecordKnowledgePanel({\n entityName,\n recordId,\n recordLabel,\n}: {\n entityName: string;\n recordId: string;\n recordLabel: string;\n}): JSX.Element | null {\n const { api, projectId } = useProjectKnowledge();\n const { currentProject } = useConfig();\n const canMutate = useCanMutate();\n const [isOpen, setIsOpen] = useState(false);\n const [isPickerOpen, setIsPickerOpen] = useState(false);\n const [detachingId, setDetachingId] = useState<string | null>(null);\n const record = useMemo<KnowledgeRecordRef>(() => ({ entity: entityName, recordId }), [entityName, recordId]);\n const entitySchema = findEntityByName(currentProject?.schema ?? [], entityName);\n const entityLabel = entitySchema ? getEntityLinkLabel(entitySchema) : entityName;\n // Built-in entities (assets, tags) are not something a document is about, so they are not even asked.\n const isLinkable = isKnowledgeLinkableEntity(entityName);\n const { data, error, isLoading, mutate } = useSWR<KnowledgeRecordSources>(\n projectId && isLinkable ? knowledgePaths(projectId).recordSources(record) : null,\n fetcher\n );\n\n if (!api || !projectId || !isLinkable) {\n return null;\n }\n\n // The platform answers 404 for an entity it does not know, which can\n // happen while a schema change is still deploying; the panel then stays out of the way.\n if (error instanceof FetcherError && error.status === 404) {\n return null;\n }\n\n const sources = data?.sources ?? [];\n const inherited = data?.inherited ?? [];\n const attachedIds = sources.map((source) => source.id);\n const knowledgeApi = api;\n\n async function detach(source: KnowledgeSource): Promise<void> {\n setDetachingId(source.id);\n\n try {\n await knowledgeApi.unlinkSource(source.id, record);\n toast.success(`Detached \"${source.title}\".`);\n // The global invalidation below revalidates this key too; one refetch is enough.\n await mutate({ sources: sources.filter((entry) => entry.id !== source.id), inherited }, { revalidate: false });\n void invalidateKnowledgeLinks();\n } catch (detachError) {\n toast.error(describeApiError(detachError, 'The document could not be detached.'));\n } finally {\n setDetachingId(null);\n }\n }\n\n let body: JSX.Element;\n\n if (error) {\n body = <p className=\"fk:text-sm fk:text-destructive\">The attached documents could not be loaded.</p>;\n } else if (isLoading && !data) {\n body = (\n <div aria-busy=\"true\" className=\"fk:flex fk:flex-col fk:gap-2\">\n <Skeleton className=\"fk:h-9 fk:w-full\" />\n <Skeleton className=\"fk:h-9 fk:w-2/3\" />\n </div>\n );\n } else {\n body = (\n <div className=\"fk:flex fk:flex-col fk:gap-4\">\n {sources.length === 0 ? (\n <p className=\"fk:text-sm fk:text-muted-foreground\">\n {inherited.length > 0\n ? 'No documents attached to this record itself; the ones below apply to every record of its type.'\n : \"No documents attached. Attach a manual, spec or contract and the agent will use it alongside the record's data when asked about this record.\"}\n </p>\n ) : (\n <SourceRows\n projectId={projectId}\n sources={sources}\n renderAction={(source) =>\n canMutate ? (\n <DetachButton\n disabled={detachingId !== null}\n label={`Detach ${source.title}`}\n onClick={() => void detach(source)}\n />\n ) : null\n }\n />\n )}\n {inherited.length > 0 ? (\n <div className=\"fk:flex fk:flex-col fk:gap-1\" data-knowledge-inherited>\n <span className=\"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground\">\n Applies to every {entityLabel}\n </span>\n <SourceRows projectId={projectId} sources={inherited} />\n </div>\n ) : null}\n </div>\n );\n }\n\n // The record drawer is mounted by the actions manager outside any app, so\n // it carries no tooltip provider of its own. The panel is a flex child of\n // the drawer: collapsed it is one row, open it claims half the height and\n // scrolls inside, so the form above stays visible and scrollable.\n return (\n <TooltipProvider>\n <Collapsible\n className={`fk:z-10 fk:flex fk:shrink-0 fk:flex-col fk:border-t fk:bg-background ${isOpen ? 'fk:h-1/2' : ''}`}\n data-knowledge-record-panel\n open={isOpen}\n onOpenChange={setIsOpen}\n >\n <div className=\"fk:flex fk:shrink-0 fk:items-center fk:gap-2 fk:pl-4 fk:pr-10 fk:py-2\">\n <CollapsibleTrigger asChild>\n <button\n className=\"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-2 fk:rounded-md fk:py-1 fk:text-left fk:text-sm fk:font-semibold fk:tracking-tight fk:hover:text-foreground/80 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring\"\n type=\"button\"\n >\n <ChevronRightIcon\n className={`fk:size-4 fk:shrink-0 fk:text-muted-foreground fk:transition-transform ${isOpen ? 'fk:rotate-90' : ''}`}\n />\n <BookOpenTextIcon className=\"fk:size-4 fk:shrink-0 fk:text-muted-foreground\" />\n Knowledge\n {data ? (\n <Badge className=\"fk:corner-squircle\" variant=\"outline\">\n {sources.length + inherited.length}\n </Badge>\n ) : null}\n </button>\n </CollapsibleTrigger>\n {isOpen ? (\n <PermissionTooltip disabled={!canMutate}>\n <Button disabled={!canMutate} size=\"sm\" variant=\"outline\" onClick={() => setIsPickerOpen(true)}>\n <PaperclipIcon />\n Attach document\n </Button>\n </PermissionTooltip>\n ) : null}\n </div>\n <CollapsibleContent className=\"fk:min-h-0 fk:flex-1 fk:overflow-y-auto fk:px-10 fk:pb-6\">\n {body}\n </CollapsibleContent>\n <AttachDocumentDialog\n api={api}\n attachedIds={attachedIds}\n open={isPickerOpen}\n projectId={projectId}\n target={record}\n targetLabel={recordLabel || `this ${entityName}`}\n onAttached={(source) => {\n // A document that applied to the whole type now hangs on the record itself; one that\n // was already attached (a stale picker in another tab) is not listed twice.\n void mutate(\n {\n sources: sources.some((entry) => entry.id === source.id) ? sources : [...sources, source],\n inherited: inherited.filter((entry) => entry.id !== source.id),\n },\n { revalidate: false }\n );\n void invalidateKnowledgeLinks();\n }}\n onOpenChange={setIsPickerOpen}\n />\n </Collapsible>\n </TooltipProvider>\n );\n}\n\ntype RecordLabels = { [recordId: string]: string };\n\n/**\n * Resolves the labels of one entity's linked records with a single display\n * query. The platform only names records whose display attribute it can read\n * from the node; a space-scoped one lives on other nodes, so the Studio asks\n * the data itself, the way the Desk grid does. Only called for a deployed entity.\n */\nfunction useRecordLabels(group: KnowledgeLinkGroup, schema: Entity[], displayAttribute: Attribute): RecordLabels {\n const { scope } = useAppContext();\n const ids = group.links.map((link) => link.recordId);\n const { data } = useEntityQuery({\n entityNamePlural: group.entityPlural,\n schema,\n scope,\n selection: 'display',\n includeCount: false,\n variables: { where: { _id: { in: ids } }, limit: ids.length },\n });\n\n return useMemo(() => {\n const labels: RecordLabels = {};\n\n for (const item of (data ?? []) as MappedEntityItem[]) {\n const value = item[displayAttribute.name];\n\n if (typeof value === 'string' && value.trim()) {\n labels[item._id] = value;\n }\n }\n\n return labels;\n }, [data, displayAttribute]);\n}\n\ninterface LinkedRecordGroupProps {\n canMutate: boolean;\n detachingKey: string | null;\n group: KnowledgeLinkGroup;\n onDetach: (_link: KnowledgeLink) => void;\n}\n\nfunction LinkedRecordGroup(props: LinkedRecordGroupProps): JSX.Element {\n const { currentProject } = useConfig();\n const schema = useMemo(() => currentProject?.schema ?? [], [currentProject]);\n const entitySchema = getEntitySchema(schema, props.group.entityPlural);\n const displayAttribute = getDisplayAttribute(entitySchema);\n\n // The query builder throws for an entity it does not know or that has no\n // attributes yet, which can happen between a deploy and the next schema\n // load; such a group shows what the platform knew.\n if (!entitySchema || !displayAttribute) {\n return (\n <LinkedRecordRows\n {...props}\n entityLabel={entitySchema ? getEntityLinkLabel(entitySchema) : props.group.entityPlural}\n labels={{}}\n />\n );\n }\n\n return (\n <ResolvedLinkedRecordGroup\n {...props}\n displayAttribute={displayAttribute}\n schema={schema}\n entityLabel={getEntityLinkLabel(entitySchema)}\n />\n );\n}\n\nfunction ResolvedLinkedRecordGroup({\n displayAttribute,\n entityLabel,\n schema,\n ...props\n}: LinkedRecordGroupProps & { displayAttribute: Attribute; entityLabel: string; schema: Entity[] }): JSX.Element {\n const labels = useRecordLabels(props.group, schema, displayAttribute);\n\n return <LinkedRecordRows {...props} entityLabel={entityLabel} labels={labels} />;\n}\n\nfunction LinkedRecordRows({\n canMutate,\n detachingKey,\n entityLabel,\n group,\n labels,\n onDetach,\n}: LinkedRecordGroupProps & { entityLabel: string; labels: RecordLabels }): JSX.Element {\n const dispatch = useDispatch();\n\n return (\n <div className=\"fk:flex fk:flex-col fk:gap-1\">\n <span className=\"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground\">\n {entityLabel}\n </span>\n <ul className=\"fk:flex fk:flex-col fk:-mx-2\">\n {group.links.map((link) => {\n const label = getKnowledgeLinkLabel(link, labels[link.recordId]);\n const key = `${link.entity}:${link.recordId}`;\n\n return (\n <li\n className=\"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1 fk:corner-squircle\"\n key={key}\n >\n <button\n className=\"fk:min-w-0 fk:flex-1 fk:truncate fk:text-left fk:text-sm fk:hover:underline fk:underline-offset-2\"\n title={link.recordId}\n type=\"button\"\n onClick={() =>\n dispatch({\n type: 'EditEntity',\n payload: { entityId: link.recordId, entityNamePlural: group.entityPlural },\n })\n }\n >\n {label}\n </button>\n {canMutate ? (\n <DetachButton\n disabled={detachingKey !== null}\n label={`Detach from ${label}`}\n onClick={() => onDetach(link)}\n />\n ) : null}\n </li>\n );\n })}\n </ul>\n </div>\n );\n}\n\n/**\n * The records a document is attached to, on the document page. Attaching\n * happens from the record's side in the Desk, where the record is in view.\n */\nexport function LinkedRecordsSection({\n api,\n projectId,\n source,\n}: {\n api: KnowledgeApi;\n projectId: string;\n source: KnowledgeSource;\n}): JSX.Element {\n const canMutate = useCanMutate();\n const [detachingKey, setDetachingKey] = useState<string | null>(null);\n const { data, error, isLoading, mutate } = useSWR<KnowledgeLinksList>(\n knowledgePaths(projectId).links(source.id),\n fetcher\n );\n const links = useMemo(() => data?.links ?? [], [data]);\n const entities = useMemo(() => data?.entities ?? [], [data]);\n const groups = useMemo(() => groupKnowledgeLinks(links), [links]);\n\n async function detach(link: KnowledgeLink): Promise<void> {\n setDetachingKey(`${link.entity}:${link.recordId}`);\n\n try {\n await api.unlinkSource(source.id, { entity: link.entity, recordId: link.recordId });\n toast.success('Detached.');\n await mutate(\n {\n links: links.filter((entry) => entry.entity !== link.entity || entry.recordId !== link.recordId),\n entities,\n },\n { revalidate: false }\n );\n void invalidateKnowledgeLinks();\n } catch (detachError) {\n toast.error(describeApiError(detachError, 'The document could not be detached.'));\n } finally {\n setDetachingKey(null);\n }\n }\n\n async function detachEntity(link: KnowledgeEntityLink): Promise<void> {\n setDetachingKey(`${link.entity}:*`);\n\n try {\n await api.unlinkSource(source.id, { entity: link.entity });\n toast.success('Detached.');\n await mutate(\n { links, entities: entities.filter((entry) => entry.entity !== link.entity) },\n { revalidate: false }\n );\n void invalidateKnowledgeLinks();\n } catch (detachError) {\n toast.error(describeApiError(detachError, 'The document could not be detached.'));\n } finally {\n setDetachingKey(null);\n }\n }\n\n async function attachEntity(entity: Entity): Promise<void> {\n setDetachingKey(`${entity.name}:+`);\n\n try {\n const result = await api.linkSource(source.id, { entity: entity.name });\n\n toast.success(\n result.linked\n ? `Applies to every ${getEntityLinkLabel(entity)} now.`\n : `Already applied to every ${getEntityLinkLabel(entity)}.`\n );\n await mutate(\n {\n links,\n entities: entities.some((entry) => entry.entity === entity.name)\n ? entities\n : [...entities, { entity: entity.name, entityPlural: entity.plural }],\n },\n { revalidate: false }\n );\n void invalidateKnowledgeLinks();\n } catch (attachError) {\n toast.error(describeApiError(attachError, 'The document could not be attached.'));\n } finally {\n setDetachingKey(null);\n }\n }\n\n let body: JSX.Element;\n\n if (error) {\n body = <p className=\"fk:text-sm fk:text-destructive\">The linked records could not be loaded.</p>;\n } else if (isLoading && !data) {\n body = (\n <div aria-busy=\"true\" className=\"fk:flex fk:flex-col fk:gap-2\">\n <Skeleton className=\"fk:h-6 fk:w-1/2\" />\n <Skeleton className=\"fk:h-6 fk:w-1/3\" />\n </div>\n );\n } else if (groups.length === 0) {\n body = (\n <p className=\"fk:text-sm fk:text-muted-foreground\">\n Not attached to any record. Open a record in the Desk and use \"Attach document\" so the agent searches this\n document before the rest of Knowledge when asked about that record.\n </p>\n );\n } else {\n body = (\n <div className=\"fk:flex fk:flex-col fk:gap-4\">\n {groups.map((group) => (\n <LinkedRecordGroup\n canMutate={canMutate}\n detachingKey={detachingKey}\n group={group}\n key={group.entityPlural}\n onDetach={(link) => void detach(link)}\n />\n ))}\n </div>\n );\n }\n\n return (\n <>\n <AppliesToEntities\n busy={detachingKey !== null}\n canMutate={canMutate}\n entities={entities}\n isLoading={isLoading && !data}\n onAttach={(entity) => void attachEntity(entity)}\n onDetach={(link) => void detachEntity(link)}\n />\n <div className=\"fk:mt-2 fk:flex fk:items-center fk:gap-2\">\n <PaperclipIcon className=\"fk:size-4 fk:text-muted-foreground\" />\n <h3 className=\"fk:text-sm fk:font-semibold fk:tracking-tight\">Linked records</h3>\n {links.length > 0 ? (\n <Badge className=\"fk:corner-squircle\" variant=\"outline\">\n {links.length}\n </Badge>\n ) : null}\n </div>\n <p className=\"fk:text-sm fk:text-muted-foreground\">\n When a question is about one of these records, the agent searches this document before the rest.\n </p>\n {body}\n </>\n );\n}\n\n/**\n * The entity types a document applies to, on the document page: chips for\n * the current ones, and a picker over the project's remaining entities. A\n * document attached to a type is searched first for any record of it.\n */\nfunction AppliesToEntities({\n busy,\n canMutate,\n entities,\n isLoading,\n onAttach,\n onDetach,\n}: {\n /** An attach or detach is in flight: no second one until it answers. */\n busy: boolean;\n canMutate: boolean;\n entities: KnowledgeEntityLink[];\n isLoading: boolean;\n onAttach: (_entity: Entity) => void;\n onDetach: (_link: KnowledgeEntityLink) => void;\n}): JSX.Element {\n const { currentProject } = useConfig();\n const schema = useMemo(() => currentProject?.schema ?? [], [currentProject]);\n const [isPickerOpen, setIsPickerOpen] = useState(false);\n const candidates = useMemo(() => getLinkableEntities(schema, entities), [entities, schema]);\n const labelOf = (link: KnowledgeEntityLink): string => {\n const entity = findEntityByName(schema, link.entity);\n\n return entity ? getEntityLinkLabel(entity) : link.entityPlural;\n };\n\n return (\n <div className=\"fk:flex fk:flex-col fk:gap-3\" data-knowledge-applies-to>\n <div className=\"fk:flex fk:items-center fk:gap-2\">\n <LayersIcon className=\"fk:size-4 fk:text-muted-foreground\" />\n <h3 className=\"fk:text-sm fk:font-semibold fk:tracking-tight\">Applies to</h3>\n {entities.length > 0 ? (\n <Badge className=\"fk:corner-squircle\" variant=\"outline\">\n {entities.length}\n </Badge>\n ) : null}\n </div>\n <p className=\"fk:text-sm fk:text-muted-foreground\">\n Attach this document to a whole entity type and the agent searches it before the rest of Knowledge for every\n record of that type, and for questions about the type in general.\n </p>\n {isLoading ? (\n <Skeleton className=\"fk:h-7 fk:w-1/3\" />\n ) : (\n <div className=\"fk:flex fk:flex-wrap fk:items-center fk:gap-2\">\n {entities.map((link) => {\n const label = labelOf(link);\n\n return (\n <Badge\n className=\"fk:gap-1 fk:py-1 fk:pl-2.5 fk:pr-1 fk:corner-squircle\"\n key={link.entity}\n variant=\"secondary\"\n >\n <span className=\"fk:capitalize\">{label}</span>\n {canMutate ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <button\n aria-label={`No longer apply to every ${label}`}\n className=\"fk:rounded-sm fk:p-0.5 fk:text-muted-foreground fk:hover:text-foreground fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring fk:disabled:opacity-50\"\n disabled={busy}\n type=\"button\"\n onClick={() => onDetach(link)}\n >\n <XIcon className=\"fk:size-3\" />\n </button>\n </TooltipTrigger>\n <TooltipContent>No longer apply to every {label}</TooltipContent>\n </Tooltip>\n ) : null}\n </Badge>\n );\n })}\n <Popover open={isPickerOpen} onOpenChange={setIsPickerOpen}>\n <PermissionTooltip disabled={!canMutate}>\n <PopoverTrigger asChild>\n <Button className=\"fk:h-7\" disabled={!canMutate || candidates.length === 0} size=\"sm\" variant=\"outline\">\n <PlusIcon />\n Add entity type\n </Button>\n </PopoverTrigger>\n </PermissionTooltip>\n <PopoverContent align=\"start\" className=\"fk:w-64 fk:p-0\">\n <Command>\n <CommandInput placeholder=\"Search entity types\" />\n <CommandList>\n <CommandEmpty>No entity type matches.</CommandEmpty>\n <CommandGroup>\n {candidates.map((entity) => (\n <CommandItem\n key={entity.name}\n keywords={[getEntityLinkLabel(entity), entity.name, entity.plural]}\n value={entity.name}\n onSelect={() => {\n setIsPickerOpen(false);\n onAttach(entity);\n }}\n >\n <span className=\"fk:capitalize\">{getEntityLinkLabel(entity)}</span>\n </CommandItem>\n ))}\n </CommandGroup>\n </CommandList>\n </Command>\n </PopoverContent>\n </Popover>\n </div>\n )}\n </div>\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/apps/knowledge/record-links.tsx"],"names":["PICKER_PAGE_SIZE","DetachButton","disabled","label","onClick","jsxs","Tooltip","jsx","TooltipTrigger","Button","Unlink2Icon","TooltipContent","AttachDocumentDialog","api","attachedIds","onAttached","onOpenChange","open","projectId","target","targetLabel","search","setSearch","useState","deferredSearch","useDeferredValue","attachingId","setAttachingId","getPageKey","pageIndex","previousPage","knowledgePaths","pages","error","isLoading","setSize","size","useSWRInfinite","fetcher","candidates","useMemo","getAttachableSources","page","hasMore","isLoadingMore","attach","source","result","toast","attachError","describeApiError","body","Skeleton","status","summarizeKnowledgeStatus","isAttaching","SourceIcon","getKnowledgeKindLabel","LoaderCircle","StatusBadge","InfiniteScrollSentinel","current","Dialog","DialogContent","DialogHeader","DialogTitle","DialogDescription","SearchIcon","Input","event","SourceRows","renderAction","sources","Link","getKnowledgeSourcePath","EntityKnowledgeButton","entityName","useProjectKnowledge","currentProject","useConfig","isOpen","setIsOpen","entitySchema","findEntityByName","isLinkable","isKnowledgeLinkableEntity","data","useSWR","FetcherError","count","Fragment","getEntityLinkLabel","BookOpenTextIcon","Badge","EntityKnowledgeDialog","entityLabel","canMutate","useCanMutate","isPickerOpen","setIsPickerOpen","detachingId","setDetachingId","mutate","detach","entry","invalidateKnowledgeLinks","detachError","PermissionTooltip","PaperclipIcon","RecordKnowledgePanel","recordId","recordLabel","record","inherited","knowledgeApi","TooltipProvider","Collapsible","CollapsibleTrigger","ChevronRightIcon","CollapsibleContent","useRecordLabels","group","schema","displayAttribute","scope","useAppContext","ids","link","useEntityQuery","labels","item","value","LinkedRecordGroup","props","getEntitySchema","getDisplayAttribute","LinkedRecordRows","ResolvedLinkedRecordGroup","detachingKey","onDetach","dispatch","useDispatch","getKnowledgeLinkLabel","key","LinkedRecordsSection","setDetachingKey","links","entities","groups","groupKnowledgeLinks","detachEntity","attachEntity","entity","AppliesToEntities","busy","onAttach","getLinkableEntities","labelOf","LayersIcon","XIcon","Popover","PopoverTrigger","PlusIcon","PopoverContent","Command","CommandInput","CommandList","CommandEmpty","CommandGroup","CommandItem"],"mappings":"ilCAsFA,IAAMA,EAAAA,CAAmB,EAAA,CAEzB,SAASC,EAAAA,CAAa,CACpB,QAAA,CAAAC,CAAAA,CACA,MAAAC,CAAAA,CACA,OAAA,CAAAC,CACF,CAAA,CAIgB,CACd,OACEC,IAAAA,CAACC,GAAAA,CAAA,CACC,QAAA,CAAA,CAAAC,IAACC,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AOA,CAAAA,CAAO,IAAA,CACd,QAAA,CAAU,IAAM,CACdrD,CAAAA,CAAgB,KAAK,CAAA,CACrBwD,CAAAA,CAASH,CAAM,EACjB,CAAA,CAEA,QAAA,CAAAjJ,GAAAA,CAAC,QAAK,SAAA,CAAU,eAAA,CAAiB,SAAAoF,CAAAA,CAAmB6D,CAAM,EAAE,CAAA,CAAA,CARvDA,CAAAA,CAAO,IASd,CACD,EACH,CAAA,CAAA,CACF,CAAA,CAAA,CACF,EACF,CAAA,CAAA,CACF,CAAA,CAAA,CACF,GAEJ,CAEJ","file":"chunk-3L4LYXSR.js","sourcesContent":["import type { JSX } from 'react';\nimport { useDeferredValue, useMemo, useState } from 'react';\nimport {\n BookOpenTextIcon,\n ChevronRightIcon,\n LayersIcon,\n LoaderCircle,\n PaperclipIcon,\n PlusIcon,\n SearchIcon,\n Unlink2Icon,\n XIcon,\n} from 'lucide-react';\nimport { Link } from 'react-router-dom';\nimport useSWR from 'swr';\nimport useSWRInfinite from 'swr/infinite';\nimport { useAppContext } from '../../core/app-context';\nimport { useConfig } from '../../core/config/config-context';\nimport { getDisplayAttribute } from '../../core/get-display-attribute';\nimport type { Attribute, Entity } from '../../core/types';\nimport { useCanMutate } from '../../core/permissions';\nimport { useDispatch } from '../../entities/actions-context';\nimport { getEntitySchema } from '../../graphql-client/queries';\nimport type { MappedEntityItem } from '../../graphql-client/types';\nimport { useEntityQuery } from '../../graphql-client/use-entity-query';\nimport {\n Badge,\n Button,\n Collapsible,\n CollapsibleContent,\n CollapsibleTrigger,\n Command,\n CommandEmpty,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n Input,\n PermissionTooltip,\n Popover,\n PopoverContent,\n PopoverTrigger,\n Skeleton,\n toast,\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from '../../ui';\nimport { fetcher, FetcherError, knowledgePaths, type KnowledgeApi } from './api';\nimport {\n findEntityByName,\n getAttachableSources,\n getEntityLinkLabel,\n getKnowledgeKindLabel,\n getKnowledgeLinkLabel,\n getKnowledgeSourcePath,\n getLinkableEntities,\n groupKnowledgeLinks,\n isKnowledgeLinkableEntity,\n summarizeKnowledgeStatus,\n type KnowledgeEntityLink,\n type KnowledgeEntitySources,\n type KnowledgeLink,\n type KnowledgeLinkGroup,\n type KnowledgeLinksList,\n type KnowledgeLinkTarget,\n type KnowledgeRecordRef,\n type KnowledgeRecordSources,\n type KnowledgeSource,\n type KnowledgeSourcesList,\n} from './knowledge';\nimport {\n describeApiError,\n InfiniteScrollSentinel,\n invalidateKnowledgeLinks,\n SourceIcon,\n StatusBadge,\n useProjectKnowledge,\n} from './shared';\n\nconst PICKER_PAGE_SIZE = 50;\n\nfunction DetachButton({\n disabled,\n label,\n onClick,\n}: {\n disabled: boolean;\n label: string;\n onClick: () => void;\n}): JSX.Element {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n aria-label={label}\n className=\"fk:size-7 fk:shrink-0\"\n disabled={disabled}\n size=\"icon\"\n variant=\"ghost\"\n onClick={onClick}\n >\n <Unlink2Icon className=\"fk:size-4\" />\n </Button>\n </TooltipTrigger>\n <TooltipContent>{label}</TooltipContent>\n </Tooltip>\n );\n}\n\n/**\n * The picker behind \"Attach document\": the project's documents, searched by\n * title, minus the ones already attached. Picking one links it right away.\n */\nfunction AttachDocumentDialog({\n api,\n attachedIds,\n onAttached,\n onOpenChange,\n open,\n projectId,\n target,\n targetLabel,\n}: {\n api: KnowledgeApi;\n attachedIds: string[];\n onAttached: (_source: KnowledgeSource) => void;\n onOpenChange: (_open: boolean) => void;\n open: boolean;\n projectId: string;\n /** A record, or an entity type when it names no record. */\n target: KnowledgeLinkTarget;\n /** How the target is called in the dialog copy: a record title, or an entity label. */\n targetLabel: string;\n}): JSX.Element {\n const [search, setSearch] = useState('');\n const deferredSearch = useDeferredValue(search.trim());\n const [attachingId, setAttachingId] = useState<string | null>(null);\n const getPageKey = (pageIndex: number, previousPage: KnowledgeSourcesList | null): string | null => {\n if (!open || (previousPage && !previousPage.hasMore)) {\n return null;\n }\n\n return knowledgePaths(projectId).sources({\n limit: PICKER_PAGE_SIZE,\n offset: pageIndex * PICKER_PAGE_SIZE,\n search: deferredSearch || undefined,\n });\n };\n // Paged like the document list: the attached ones are hidden client-side,\n // so a record with many documents attached must be able to reach the next page.\n const {\n data: pages,\n error,\n isLoading,\n setSize,\n size,\n } = useSWRInfinite<KnowledgeSourcesList>(getPageKey, fetcher, { keepPreviousData: true });\n const candidates = useMemo(\n () => getAttachableSources(pages?.flatMap((page) => page.sources) ?? [], attachedIds),\n [attachedIds, pages]\n );\n const hasMore = pages?.[pages.length - 1]?.hasMore ?? false;\n const isLoadingMore = pages !== undefined && size > pages.length;\n\n async function attach(source: KnowledgeSource): Promise<void> {\n setAttachingId(source.id);\n\n try {\n const result = await api.linkSource(source.id, target);\n\n toast.success(result.linked ? `Attached \"${source.title}\".` : `\"${source.title}\" was already attached.`);\n onAttached(source);\n onOpenChange(false);\n } catch (attachError) {\n toast.error(describeApiError(attachError, 'The document could not be attached.'));\n } finally {\n setAttachingId(null);\n }\n }\n\n let body: JSX.Element;\n\n if (error) {\n body = <p className=\"fk:py-6 fk:text-center fk:text-sm fk:text-destructive\">The documents could not be loaded.</p>;\n } else if (isLoading && !pages) {\n body = (\n <div aria-busy=\"true\" className=\"fk:flex fk:flex-col fk:gap-3 fk:py-2\">\n <Skeleton className=\"fk:h-10 fk:w-full\" />\n <Skeleton className=\"fk:h-10 fk:w-full\" />\n <Skeleton className=\"fk:h-10 fk:w-full\" />\n </div>\n );\n } else if (candidates.length === 0 && !hasMore) {\n body = (\n <p className=\"fk:py-6 fk:text-center fk:text-sm fk:text-muted-foreground\">\n {deferredSearch\n ? 'No documents match your search.'\n : 'Every document is attached already, or there are none yet. Add documents in Knowledge first.'}\n </p>\n );\n } else {\n body = (\n <ul className=\"fk:flex fk:max-h-80 fk:flex-col fk:overflow-y-auto fk:-mx-2\">\n {candidates.map((source) => {\n const status = summarizeKnowledgeStatus(source);\n const isAttaching = attachingId === source.id;\n\n return (\n <li key={source.id}>\n <button\n className=\"fk:flex fk:w-full fk:min-w-0 fk:items-center fk:gap-3 fk:rounded-lg fk:px-2 fk:py-2 fk:text-left fk:transition-colors fk:hover:bg-accent fk:focus-visible:bg-accent fk:focus-visible:outline-none fk:disabled:opacity-60 fk:corner-squircle\"\n disabled={attachingId !== null}\n type=\"button\"\n onClick={() => void attach(source)}\n >\n <SourceIcon source={source} />\n <span className=\"fk:min-w-0 fk:flex-1\">\n <span className=\"fk:block fk:truncate fk:text-sm fk:font-medium\">{source.title}</span>\n <span className=\"fk:block fk:truncate fk:text-xs fk:text-muted-foreground\">\n {getKnowledgeKindLabel(source)} · {status.detail}\n </span>\n </span>\n {isAttaching ? (\n <LoaderCircle className=\"fk:size-4 fk:shrink-0 fk:animate-spin fk:text-muted-foreground\" />\n ) : (\n <StatusBadge label={status.label} tone={status.tone} />\n )}\n </button>\n </li>\n );\n })}\n {hasMore && !isLoadingMore ? (\n <li aria-hidden>\n <InfiniteScrollSentinel onVisible={() => void setSize((current) => current + 1)} />\n </li>\n ) : null}\n {isLoadingMore ? (\n <li className=\"fk:flex fk:justify-center fk:py-2\">\n <LoaderCircle className=\"fk:size-4 fk:animate-spin fk:text-muted-foreground\" />\n </li>\n ) : null}\n </ul>\n );\n }\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"fk:sm:max-w-lg\">\n <DialogHeader>\n <DialogTitle>Attach a document</DialogTitle>\n <DialogDescription>\n {target.recordId === undefined\n ? `Documents attached to every ${targetLabel} are searched before the rest of Knowledge when a question is about one of them, or about ${targetLabel} in general.`\n : `Documents attached to ${targetLabel} are searched before the rest of Knowledge when a question is about it.`}\n </DialogDescription>\n </DialogHeader>\n <div className=\"fk:relative\">\n <SearchIcon className=\"fk:pointer-events-none fk:absolute fk:left-2.5 fk:top-1/2 fk:size-4 fk:-translate-y-1/2 fk:text-muted-foreground\" />\n <Input\n aria-label=\"Search documents\"\n autoFocus\n className=\"fk:pl-8\"\n placeholder=\"Search documents by title\"\n value={search}\n onChange={(event) => setSearch(event.target.value)}\n />\n </div>\n {body}\n </DialogContent>\n </Dialog>\n );\n}\n\n/** Document rows shared by the record panel and the entity dialog: icon, title, kind and status, plus an optional action. */\nfunction SourceRows({\n projectId,\n renderAction,\n sources,\n}: {\n projectId: string;\n renderAction?: (_source: KnowledgeSource) => JSX.Element | null;\n sources: KnowledgeSource[];\n}): JSX.Element {\n return (\n <ul className=\"fk:flex fk:flex-col fk:gap-1 fk:-mx-2\">\n {sources.map((source) => {\n const status = summarizeKnowledgeStatus(source);\n\n return (\n <li\n className=\"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1.5 fk:corner-squircle\"\n key={source.id}\n >\n <Link\n className=\"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-3 fk:rounded-md fk:hover:underline fk:underline-offset-2\"\n to={getKnowledgeSourcePath(projectId, source.id)}\n >\n <SourceIcon source={source} />\n <span className=\"fk:min-w-0 fk:flex-1\">\n <span className=\"fk:block fk:truncate fk:text-sm fk:font-medium\">{source.title}</span>\n <span className=\"fk:block fk:truncate fk:text-xs fk:text-muted-foreground\">\n {getKnowledgeKindLabel(source)} · {status.detail}\n </span>\n </span>\n </Link>\n <StatusBadge label={status.label} tone={status.tone} />\n {renderAction?.(source)}\n </li>\n );\n })}\n </ul>\n );\n}\n\n/**\n * The documents attached to every record of an entity type, behind a button\n * in the Desk list toolbar: open them, attach another, detach one. Only the\n * project's own entities qualify, and the button stays out while the schema\n * is unknown.\n */\nexport function EntityKnowledgeButton({ entityName }: { entityName: string }): JSX.Element | null {\n const { api, projectId } = useProjectKnowledge();\n const { currentProject } = useConfig();\n const [isOpen, setIsOpen] = useState(false);\n const entitySchema = findEntityByName(currentProject?.schema ?? [], entityName);\n const isLinkable = Boolean(entitySchema) && isKnowledgeLinkableEntity(entityName);\n const { data, error } = useSWR<KnowledgeEntitySources>(\n projectId && isLinkable ? knowledgePaths(projectId).entitySources(entityName) : null,\n fetcher\n );\n\n if (!api || !projectId || !entitySchema || !isLinkable || (error instanceof FetcherError && error.status === 404)) {\n return null;\n }\n\n const count = data?.sources.length ?? 0;\n\n return (\n <>\n <Button\n aria-label={`Knowledge for every ${getEntityLinkLabel(entitySchema)}`}\n className=\"fk:mr-2 fk:h-8\"\n data-knowledge-entity-button\n size=\"sm\"\n variant=\"outline\"\n onClick={() => setIsOpen(true)}\n >\n <BookOpenTextIcon />\n Knowledge\n {count > 0 ? (\n <Badge className=\"fk:corner-squircle\" variant=\"secondary\">\n {count}\n </Badge>\n ) : null}\n </Button>\n <EntityKnowledgeDialog\n api={api}\n entityLabel={getEntityLinkLabel(entitySchema)}\n entityName={entityName}\n open={isOpen}\n projectId={projectId}\n onOpenChange={setIsOpen}\n />\n </>\n );\n}\n\nfunction EntityKnowledgeDialog({\n api,\n entityLabel,\n entityName,\n onOpenChange,\n open,\n projectId,\n}: {\n api: KnowledgeApi;\n entityLabel: string;\n entityName: string;\n onOpenChange: (_open: boolean) => void;\n open: boolean;\n projectId: string;\n}): JSX.Element {\n const canMutate = useCanMutate();\n const [isPickerOpen, setIsPickerOpen] = useState(false);\n const [detachingId, setDetachingId] = useState<string | null>(null);\n const { data, error, isLoading, mutate } = useSWR<KnowledgeEntitySources>(\n knowledgePaths(projectId).entitySources(entityName),\n fetcher\n );\n const sources = data?.sources ?? [];\n const target = useMemo<KnowledgeLinkTarget>(() => ({ entity: entityName }), [entityName]);\n\n async function detach(source: KnowledgeSource): Promise<void> {\n setDetachingId(source.id);\n\n try {\n await api.unlinkSource(source.id, target);\n toast.success(`\"${source.title}\" no longer applies to every ${entityLabel}.`);\n await mutate({ sources: sources.filter((entry) => entry.id !== source.id) }, { revalidate: false });\n void invalidateKnowledgeLinks();\n } catch (detachError) {\n toast.error(describeApiError(detachError, 'The document could not be detached.'));\n } finally {\n setDetachingId(null);\n }\n }\n\n let body: JSX.Element;\n\n if (error) {\n body = <p className=\"fk:text-sm fk:text-destructive\">The documents could not be loaded.</p>;\n } else if (isLoading && !data) {\n body = (\n <div aria-busy=\"true\" className=\"fk:flex fk:flex-col fk:gap-2\">\n <Skeleton className=\"fk:h-9 fk:w-full\" />\n <Skeleton className=\"fk:h-9 fk:w-2/3\" />\n </div>\n );\n } else if (sources.length === 0) {\n body = (\n <p className=\"fk:text-sm fk:text-muted-foreground\">\n No documents apply to every {entityLabel} yet. Attach a guide, a policy or a spec that holds for all of them and\n the agent searches it first when asked about any {entityLabel}, or about {entityLabel} in general.\n </p>\n );\n } else {\n body = (\n <SourceRows\n projectId={projectId}\n sources={sources}\n renderAction={(source) =>\n canMutate ? (\n <DetachButton\n disabled={detachingId !== null}\n label={`Detach ${source.title}`}\n onClick={() => void detach(source)}\n />\n ) : null\n }\n />\n );\n }\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"fk:sm:max-w-lg\" data-knowledge-entity-dialog>\n <DialogHeader>\n <DialogTitle className=\"fk:flex fk:items-center fk:gap-2\">\n <BookOpenTextIcon className=\"fk:size-4 fk:text-muted-foreground\" />\n Knowledge for every {entityLabel}\n {data ? (\n <Badge className=\"fk:corner-squircle\" variant=\"outline\">\n {sources.length}\n </Badge>\n ) : null}\n </DialogTitle>\n <DialogDescription>\n Documents attached here apply to every {entityLabel}; each record can hold its own on top.\n </DialogDescription>\n </DialogHeader>\n <div className=\"fk:max-h-80 fk:overflow-y-auto\">{body}</div>\n <div className=\"fk:flex fk:justify-end\">\n <PermissionTooltip disabled={!canMutate}>\n <Button disabled={!canMutate} size=\"sm\" variant=\"outline\" onClick={() => setIsPickerOpen(true)}>\n <PaperclipIcon />\n Attach document\n </Button>\n </PermissionTooltip>\n </div>\n <AttachDocumentDialog\n api={api}\n attachedIds={sources.map((source) => source.id)}\n open={isPickerOpen}\n projectId={projectId}\n target={target}\n targetLabel={entityLabel}\n onAttached={(source) => {\n // \"Already attached\" (a stale picker in another tab) must not list the document twice.\n void mutate(\n { sources: sources.some((entry) => entry.id === source.id) ? sources : [...sources, source] },\n { revalidate: false }\n );\n void invalidateKnowledgeLinks();\n }}\n onOpenChange={setIsPickerOpen}\n />\n </DialogContent>\n </Dialog>\n );\n}\n\n/**\n * The documents attached to one record, pinned under the record form in the\n * Desk as a collapsible panel: open them, attach another, detach one. The\n * agent searches these before the rest of Knowledge when a question is about this record.\n */\nexport function RecordKnowledgePanel({\n entityName,\n recordId,\n recordLabel,\n}: {\n entityName: string;\n recordId: string;\n recordLabel: string;\n}): JSX.Element | null {\n const { api, projectId } = useProjectKnowledge();\n const { currentProject } = useConfig();\n const canMutate = useCanMutate();\n const [isOpen, setIsOpen] = useState(false);\n const [isPickerOpen, setIsPickerOpen] = useState(false);\n const [detachingId, setDetachingId] = useState<string | null>(null);\n const record = useMemo<KnowledgeRecordRef>(() => ({ entity: entityName, recordId }), [entityName, recordId]);\n const entitySchema = findEntityByName(currentProject?.schema ?? [], entityName);\n const entityLabel = entitySchema ? getEntityLinkLabel(entitySchema) : entityName;\n // Built-in entities (assets, tags) are not something a document is about, so they are not even asked.\n const isLinkable = isKnowledgeLinkableEntity(entityName);\n const { data, error, isLoading, mutate } = useSWR<KnowledgeRecordSources>(\n projectId && isLinkable ? knowledgePaths(projectId).recordSources(record) : null,\n fetcher\n );\n\n if (!api || !projectId || !isLinkable) {\n return null;\n }\n\n // The platform answers 404 for an entity it does not know, which can\n // happen while a schema change is still deploying; the panel then stays out of the way.\n if (error instanceof FetcherError && error.status === 404) {\n return null;\n }\n\n const sources = data?.sources ?? [];\n const inherited = data?.inherited ?? [];\n const attachedIds = sources.map((source) => source.id);\n const knowledgeApi = api;\n\n async function detach(source: KnowledgeSource): Promise<void> {\n setDetachingId(source.id);\n\n try {\n await knowledgeApi.unlinkSource(source.id, record);\n toast.success(`Detached \"${source.title}\".`);\n // The global invalidation below revalidates this key too; one refetch is enough.\n await mutate({ sources: sources.filter((entry) => entry.id !== source.id), inherited }, { revalidate: false });\n void invalidateKnowledgeLinks();\n } catch (detachError) {\n toast.error(describeApiError(detachError, 'The document could not be detached.'));\n } finally {\n setDetachingId(null);\n }\n }\n\n let body: JSX.Element;\n\n if (error) {\n body = <p className=\"fk:text-sm fk:text-destructive\">The attached documents could not be loaded.</p>;\n } else if (isLoading && !data) {\n body = (\n <div aria-busy=\"true\" className=\"fk:flex fk:flex-col fk:gap-2\">\n <Skeleton className=\"fk:h-9 fk:w-full\" />\n <Skeleton className=\"fk:h-9 fk:w-2/3\" />\n </div>\n );\n } else {\n body = (\n <div className=\"fk:flex fk:flex-col fk:gap-4\">\n {sources.length === 0 ? (\n <p className=\"fk:text-sm fk:text-muted-foreground\">\n {inherited.length > 0\n ? 'No documents attached to this record itself; the ones below apply to every record of its type.'\n : \"No documents attached. Attach a manual, spec or contract and the agent will use it alongside the record's data when asked about this record.\"}\n </p>\n ) : (\n <SourceRows\n projectId={projectId}\n sources={sources}\n renderAction={(source) =>\n canMutate ? (\n <DetachButton\n disabled={detachingId !== null}\n label={`Detach ${source.title}`}\n onClick={() => void detach(source)}\n />\n ) : null\n }\n />\n )}\n {inherited.length > 0 ? (\n <div className=\"fk:flex fk:flex-col fk:gap-1\" data-knowledge-inherited>\n <span className=\"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground\">\n Applies to every {entityLabel}\n </span>\n <SourceRows projectId={projectId} sources={inherited} />\n </div>\n ) : null}\n </div>\n );\n }\n\n // The record drawer is mounted by the actions manager outside any app, so\n // it carries no tooltip provider of its own. The panel is a flex child of\n // the drawer: collapsed it is one row, open it claims half the height and\n // scrolls inside, so the form above stays visible and scrollable.\n return (\n <TooltipProvider>\n <Collapsible\n className={`fk:z-10 fk:flex fk:shrink-0 fk:flex-col fk:border-t fk:bg-background ${isOpen ? 'fk:h-1/2' : ''}`}\n data-knowledge-record-panel\n open={isOpen}\n onOpenChange={setIsOpen}\n >\n <div className=\"fk:flex fk:shrink-0 fk:items-center fk:gap-2 fk:pl-4 fk:pr-10 fk:py-2\">\n <CollapsibleTrigger asChild>\n <button\n className=\"fk:flex fk:min-w-0 fk:flex-1 fk:items-center fk:gap-2 fk:rounded-md fk:py-1 fk:text-left fk:text-sm fk:font-semibold fk:tracking-tight fk:hover:text-foreground/80 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring\"\n type=\"button\"\n >\n <ChevronRightIcon\n className={`fk:size-4 fk:shrink-0 fk:text-muted-foreground fk:transition-transform ${isOpen ? 'fk:rotate-90' : ''}`}\n />\n <BookOpenTextIcon className=\"fk:size-4 fk:shrink-0 fk:text-muted-foreground\" />\n Knowledge\n {data ? (\n <Badge className=\"fk:corner-squircle\" variant=\"outline\">\n {sources.length + inherited.length}\n </Badge>\n ) : null}\n </button>\n </CollapsibleTrigger>\n {isOpen ? (\n <PermissionTooltip disabled={!canMutate}>\n <Button disabled={!canMutate} size=\"sm\" variant=\"outline\" onClick={() => setIsPickerOpen(true)}>\n <PaperclipIcon />\n Attach document\n </Button>\n </PermissionTooltip>\n ) : null}\n </div>\n <CollapsibleContent className=\"fk:min-h-0 fk:flex-1 fk:overflow-y-auto fk:px-10 fk:pb-6\">\n {body}\n </CollapsibleContent>\n <AttachDocumentDialog\n api={api}\n attachedIds={attachedIds}\n open={isPickerOpen}\n projectId={projectId}\n target={record}\n targetLabel={recordLabel || `this ${entityName}`}\n onAttached={(source) => {\n // A document that applied to the whole type now hangs on the record itself; one that\n // was already attached (a stale picker in another tab) is not listed twice.\n void mutate(\n {\n sources: sources.some((entry) => entry.id === source.id) ? sources : [...sources, source],\n inherited: inherited.filter((entry) => entry.id !== source.id),\n },\n { revalidate: false }\n );\n void invalidateKnowledgeLinks();\n }}\n onOpenChange={setIsPickerOpen}\n />\n </Collapsible>\n </TooltipProvider>\n );\n}\n\ntype RecordLabels = { [recordId: string]: string };\n\n/**\n * Resolves the labels of one entity's linked records with a single display\n * query. The platform only names records whose display attribute it can read\n * from the node; a space-scoped one lives on other nodes, so the Studio asks\n * the data itself, the way the Desk grid does. Only called for a deployed entity.\n */\nfunction useRecordLabels(group: KnowledgeLinkGroup, schema: Entity[], displayAttribute: Attribute): RecordLabels {\n const { scope } = useAppContext();\n const ids = group.links.map((link) => link.recordId);\n const { data } = useEntityQuery({\n entityNamePlural: group.entityPlural,\n schema,\n scope,\n selection: 'display',\n includeCount: false,\n variables: { where: { _id: { in: ids } }, limit: ids.length },\n });\n\n return useMemo(() => {\n const labels: RecordLabels = {};\n\n for (const item of (data ?? []) as MappedEntityItem[]) {\n const value = item[displayAttribute.name];\n\n if (typeof value === 'string' && value.trim()) {\n labels[item._id] = value;\n }\n }\n\n return labels;\n }, [data, displayAttribute]);\n}\n\ninterface LinkedRecordGroupProps {\n canMutate: boolean;\n detachingKey: string | null;\n group: KnowledgeLinkGroup;\n onDetach: (_link: KnowledgeLink) => void;\n}\n\nfunction LinkedRecordGroup(props: LinkedRecordGroupProps): JSX.Element {\n const { currentProject } = useConfig();\n const schema = useMemo(() => currentProject?.schema ?? [], [currentProject]);\n const entitySchema = getEntitySchema(schema, props.group.entityPlural);\n const displayAttribute = getDisplayAttribute(entitySchema);\n\n // The query builder throws for an entity it does not know or that has no\n // attributes yet, which can happen between a deploy and the next schema\n // load; such a group shows what the platform knew.\n if (!entitySchema || !displayAttribute) {\n return (\n <LinkedRecordRows\n {...props}\n entityLabel={entitySchema ? getEntityLinkLabel(entitySchema) : props.group.entityPlural}\n labels={{}}\n />\n );\n }\n\n return (\n <ResolvedLinkedRecordGroup\n {...props}\n displayAttribute={displayAttribute}\n schema={schema}\n entityLabel={getEntityLinkLabel(entitySchema)}\n />\n );\n}\n\nfunction ResolvedLinkedRecordGroup({\n displayAttribute,\n entityLabel,\n schema,\n ...props\n}: LinkedRecordGroupProps & { displayAttribute: Attribute; entityLabel: string; schema: Entity[] }): JSX.Element {\n const labels = useRecordLabels(props.group, schema, displayAttribute);\n\n return <LinkedRecordRows {...props} entityLabel={entityLabel} labels={labels} />;\n}\n\nfunction LinkedRecordRows({\n canMutate,\n detachingKey,\n entityLabel,\n group,\n labels,\n onDetach,\n}: LinkedRecordGroupProps & { entityLabel: string; labels: RecordLabels }): JSX.Element {\n const dispatch = useDispatch();\n\n return (\n <div className=\"fk:flex fk:flex-col fk:gap-1\">\n <span className=\"fk:text-xs fk:font-medium fk:uppercase fk:tracking-wide fk:text-muted-foreground\">\n {entityLabel}\n </span>\n <ul className=\"fk:flex fk:flex-col fk:-mx-2\">\n {group.links.map((link) => {\n const label = getKnowledgeLinkLabel(link, labels[link.recordId]);\n const key = `${link.entity}:${link.recordId}`;\n\n return (\n <li\n className=\"fk:flex fk:min-w-0 fk:items-center fk:gap-2 fk:rounded-lg fk:px-2 fk:py-1 fk:corner-squircle\"\n key={key}\n >\n <button\n className=\"fk:min-w-0 fk:flex-1 fk:truncate fk:text-left fk:text-sm fk:hover:underline fk:underline-offset-2\"\n title={link.recordId}\n type=\"button\"\n onClick={() =>\n dispatch({\n type: 'EditEntity',\n payload: { entityId: link.recordId, entityNamePlural: group.entityPlural },\n })\n }\n >\n {label}\n </button>\n {canMutate ? (\n <DetachButton\n disabled={detachingKey !== null}\n label={`Detach from ${label}`}\n onClick={() => onDetach(link)}\n />\n ) : null}\n </li>\n );\n })}\n </ul>\n </div>\n );\n}\n\n/**\n * The records a document is attached to, on the document page. Attaching\n * happens from the record's side in the Desk, where the record is in view.\n */\nexport function LinkedRecordsSection({\n api,\n projectId,\n source,\n}: {\n api: KnowledgeApi;\n projectId: string;\n source: KnowledgeSource;\n}): JSX.Element {\n const canMutate = useCanMutate();\n const [detachingKey, setDetachingKey] = useState<string | null>(null);\n const { data, error, isLoading, mutate } = useSWR<KnowledgeLinksList>(\n knowledgePaths(projectId).links(source.id),\n fetcher\n );\n const links = useMemo(() => data?.links ?? [], [data]);\n const entities = useMemo(() => data?.entities ?? [], [data]);\n const groups = useMemo(() => groupKnowledgeLinks(links), [links]);\n\n async function detach(link: KnowledgeLink): Promise<void> {\n setDetachingKey(`${link.entity}:${link.recordId}`);\n\n try {\n await api.unlinkSource(source.id, { entity: link.entity, recordId: link.recordId });\n toast.success('Detached.');\n await mutate(\n {\n links: links.filter((entry) => entry.entity !== link.entity || entry.recordId !== link.recordId),\n entities,\n },\n { revalidate: false }\n );\n void invalidateKnowledgeLinks();\n } catch (detachError) {\n toast.error(describeApiError(detachError, 'The document could not be detached.'));\n } finally {\n setDetachingKey(null);\n }\n }\n\n async function detachEntity(link: KnowledgeEntityLink): Promise<void> {\n setDetachingKey(`${link.entity}:*`);\n\n try {\n await api.unlinkSource(source.id, { entity: link.entity });\n toast.success('Detached.');\n await mutate(\n { links, entities: entities.filter((entry) => entry.entity !== link.entity) },\n { revalidate: false }\n );\n void invalidateKnowledgeLinks();\n } catch (detachError) {\n toast.error(describeApiError(detachError, 'The document could not be detached.'));\n } finally {\n setDetachingKey(null);\n }\n }\n\n async function attachEntity(entity: Entity): Promise<void> {\n setDetachingKey(`${entity.name}:+`);\n\n try {\n const result = await api.linkSource(source.id, { entity: entity.name });\n\n toast.success(\n result.linked\n ? `Applies to every ${getEntityLinkLabel(entity)} now.`\n : `Already applied to every ${getEntityLinkLabel(entity)}.`\n );\n await mutate(\n {\n links,\n entities: entities.some((entry) => entry.entity === entity.name)\n ? entities\n : [...entities, { entity: entity.name, entityPlural: entity.plural }],\n },\n { revalidate: false }\n );\n void invalidateKnowledgeLinks();\n } catch (attachError) {\n toast.error(describeApiError(attachError, 'The document could not be attached.'));\n } finally {\n setDetachingKey(null);\n }\n }\n\n let body: JSX.Element;\n\n if (error) {\n body = <p className=\"fk:text-sm fk:text-destructive\">The linked records could not be loaded.</p>;\n } else if (isLoading && !data) {\n body = (\n <div aria-busy=\"true\" className=\"fk:flex fk:flex-col fk:gap-2\">\n <Skeleton className=\"fk:h-6 fk:w-1/2\" />\n <Skeleton className=\"fk:h-6 fk:w-1/3\" />\n </div>\n );\n } else if (groups.length === 0) {\n body = (\n <p className=\"fk:text-sm fk:text-muted-foreground\">\n Not attached to any record. Open a record in the Desk and use \"Attach document\" so the agent searches this\n document before the rest of Knowledge when asked about that record.\n </p>\n );\n } else {\n body = (\n <div className=\"fk:flex fk:flex-col fk:gap-4\">\n {groups.map((group) => (\n <LinkedRecordGroup\n canMutate={canMutate}\n detachingKey={detachingKey}\n group={group}\n key={group.entityPlural}\n onDetach={(link) => void detach(link)}\n />\n ))}\n </div>\n );\n }\n\n return (\n <>\n <AppliesToEntities\n busy={detachingKey !== null}\n canMutate={canMutate}\n entities={entities}\n isLoading={isLoading && !data}\n onAttach={(entity) => void attachEntity(entity)}\n onDetach={(link) => void detachEntity(link)}\n />\n <div className=\"fk:mt-2 fk:flex fk:items-center fk:gap-2\">\n <PaperclipIcon className=\"fk:size-4 fk:text-muted-foreground\" />\n <h3 className=\"fk:text-sm fk:font-semibold fk:tracking-tight\">Linked records</h3>\n {links.length > 0 ? (\n <Badge className=\"fk:corner-squircle\" variant=\"outline\">\n {links.length}\n </Badge>\n ) : null}\n </div>\n <p className=\"fk:text-sm fk:text-muted-foreground\">\n When a question is about one of these records, the agent searches this document before the rest.\n </p>\n {body}\n </>\n );\n}\n\n/**\n * The entity types a document applies to, on the document page: chips for\n * the current ones, and a picker over the project's remaining entities. A\n * document attached to a type is searched first for any record of it.\n */\nfunction AppliesToEntities({\n busy,\n canMutate,\n entities,\n isLoading,\n onAttach,\n onDetach,\n}: {\n /** An attach or detach is in flight: no second one until it answers. */\n busy: boolean;\n canMutate: boolean;\n entities: KnowledgeEntityLink[];\n isLoading: boolean;\n onAttach: (_entity: Entity) => void;\n onDetach: (_link: KnowledgeEntityLink) => void;\n}): JSX.Element {\n const { currentProject } = useConfig();\n const schema = useMemo(() => currentProject?.schema ?? [], [currentProject]);\n const [isPickerOpen, setIsPickerOpen] = useState(false);\n const candidates = useMemo(() => getLinkableEntities(schema, entities), [entities, schema]);\n const labelOf = (link: KnowledgeEntityLink): string => {\n const entity = findEntityByName(schema, link.entity);\n\n return entity ? getEntityLinkLabel(entity) : link.entityPlural;\n };\n\n return (\n <div className=\"fk:flex fk:flex-col fk:gap-3\" data-knowledge-applies-to>\n <div className=\"fk:flex fk:items-center fk:gap-2\">\n <LayersIcon className=\"fk:size-4 fk:text-muted-foreground\" />\n <h3 className=\"fk:text-sm fk:font-semibold fk:tracking-tight\">Applies to</h3>\n {entities.length > 0 ? (\n <Badge className=\"fk:corner-squircle\" variant=\"outline\">\n {entities.length}\n </Badge>\n ) : null}\n </div>\n <p className=\"fk:text-sm fk:text-muted-foreground\">\n Attach this document to a whole entity type and the agent searches it before the rest of Knowledge for every\n record of that type, and for questions about the type in general.\n </p>\n {isLoading ? (\n <Skeleton className=\"fk:h-7 fk:w-1/3\" />\n ) : (\n <div className=\"fk:flex fk:flex-wrap fk:items-center fk:gap-2\">\n {entities.map((link) => {\n const label = labelOf(link);\n\n return (\n <Badge\n className=\"fk:gap-1 fk:py-1 fk:pl-2.5 fk:pr-1 fk:corner-squircle\"\n key={link.entity}\n variant=\"secondary\"\n >\n <span className=\"fk:capitalize\">{label}</span>\n {canMutate ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <button\n aria-label={`No longer apply to every ${label}`}\n className=\"fk:rounded-sm fk:p-0.5 fk:text-muted-foreground fk:hover:text-foreground fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring fk:disabled:opacity-50\"\n disabled={busy}\n type=\"button\"\n onClick={() => onDetach(link)}\n >\n <XIcon className=\"fk:size-3\" />\n </button>\n </TooltipTrigger>\n <TooltipContent>No longer apply to every {label}</TooltipContent>\n </Tooltip>\n ) : null}\n </Badge>\n );\n })}\n <Popover open={isPickerOpen} onOpenChange={setIsPickerOpen}>\n <PermissionTooltip disabled={!canMutate}>\n <PopoverTrigger asChild>\n <Button className=\"fk:h-7\" disabled={!canMutate || candidates.length === 0} size=\"sm\" variant=\"outline\">\n <PlusIcon />\n Add entity type\n </Button>\n </PopoverTrigger>\n </PermissionTooltip>\n <PopoverContent align=\"start\" className=\"fk:w-64 fk:p-0\">\n <Command>\n <CommandInput placeholder=\"Search entity types\" />\n <CommandList>\n <CommandEmpty>No entity type matches.</CommandEmpty>\n <CommandGroup>\n {candidates.map((entity) => (\n <CommandItem\n key={entity.name}\n keywords={[getEntityLinkLabel(entity), entity.name, entity.plural]}\n value={entity.name}\n onSelect={() => {\n setIsPickerOpen(false);\n onAttach(entity);\n }}\n >\n <span className=\"fk:capitalize\">{getEntityLinkLabel(entity)}</span>\n </CommandItem>\n ))}\n </CommandGroup>\n </CommandList>\n </Command>\n </PopoverContent>\n </Popover>\n </div>\n )}\n </div>\n );\n}\n"]}
@@ -1,7 +1,7 @@
1
- import'./index.css';import {b}from'./chunk-CAZ6EUR2.js';import {b as b$3}from'./chunk-2DXR5NJV.js';import {e,a as a$2,b as b$2}from'./chunk-AKW7EKYI.js';import {g as g$1,b as b$6}from'./chunk-WPCPL2TQ.js';import {Tc,Uc,Vc,$,aa,da,ea,ba,fa,o}from'./chunk-DGIY4SKN.js';import {e as e$1,g,h,j}from'./chunk-SZEGGBOC.js';import {c as c$1,h as h$1,i,k,l,b as b$5}from'./chunk-32ZU4MLE.js';import {a,b as b$4,c,d,e as e$2}from'./chunk-USNXQOMJ.js';import {b as b$1}from'./chunk-6NRQMG26.js';import {a as a$1}from'./chunk-O2QMYUPS.js';import {AlertCircle,X,ChevronDown,ArrowUp,ArrowDown,Star,CircleCheck,CircleX,Check,Copy}from'lucide-react';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {useRef,useState,useEffect,useCallback,useMemo}from'react';import {useReactTable,getSortedRowModel,getPaginationRowModel,getFilteredRowModel,getCoreRowModel,flexRender}from'@tanstack/react-table';import {useVirtualizer}from'@tanstack/react-virtual';import {gql}from'@apollo/client';import {useMutation}from'@apollo/client/react';import {getText,getSchema,getTextSerializersFromSchema}from'@tiptap/core';import {Node}from'@tiptap/pm/model';import {TiptapLink,TiptapImage,UploadImagesPlugin,TaskList,TaskItem,HorizontalRule,StarterKit,CodeBlockLowlight,Youtube,Twitter,Mathematics,CharacterCount,Placeholder,AIHighlight,TiptapUnderline,HighlightExtension,TextStyle,Color,CustomKeymap,GlobalDragHandle}from'novel';import {Markdown}from'tiptap-markdown';import {cx}from'class-variance-authority';import {createLowlight,common}from'lowlight';import {defaultStyles,FileIcon}from'react-file-icon';import {isValid,format}from'date-fns';function Xr(){return jsxs(Tc,{variant:"destructive",children:[jsx(AlertCircle,{className:"fk:h-4 fk:w-4"}),jsx(Uc,{children:"Project Paused"}),jsxs(Vc,{children:["This project has been paused. To troubleshoot this error, please"," ",jsx("a",{className:"fk:text-blue-500 fk:underline",href:"https://flexkit.io/docs/errors/project-paused",target:"_blank",rel:"noopener noreferrer",children:"follow these steps"}),"."]})]})}function Kr(){let{schemaErrorMessage:e$1}=e();if(!e$1)return jsx(Fragment,{});let[t,n,...r]=e$1.split(`
1
+ import'./index.css';import {b}from'./chunk-CAZ6EUR2.js';import {b as b$3}from'./chunk-2DXR5NJV.js';import {e,a as a$2,b as b$2}from'./chunk-ZI22345U.js';import {g as g$1,b as b$6}from'./chunk-WPCPL2TQ.js';import {Tc,Uc,Vc,$,aa,da,ea,ba,fa,o}from'./chunk-DGIY4SKN.js';import {e as e$1,g,h,j}from'./chunk-SZEGGBOC.js';import {c as c$1,h as h$1,i,k,l,b as b$5}from'./chunk-32ZU4MLE.js';import {a,b as b$4,c,d,e as e$2}from'./chunk-USNXQOMJ.js';import {b as b$1}from'./chunk-6NRQMG26.js';import {a as a$1}from'./chunk-O2QMYUPS.js';import {AlertCircle,X,ChevronDown,ArrowUp,ArrowDown,Star,CircleCheck,CircleX,Check,Copy}from'lucide-react';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {useRef,useState,useEffect,useCallback,useMemo}from'react';import {useReactTable,getSortedRowModel,getPaginationRowModel,getFilteredRowModel,getCoreRowModel,flexRender}from'@tanstack/react-table';import {useVirtualizer}from'@tanstack/react-virtual';import {gql}from'@apollo/client';import {useMutation}from'@apollo/client/react';import {getText,getSchema,getTextSerializersFromSchema}from'@tiptap/core';import {Node}from'@tiptap/pm/model';import {TiptapLink,TiptapImage,UploadImagesPlugin,TaskList,TaskItem,HorizontalRule,StarterKit,CodeBlockLowlight,Youtube,Twitter,Mathematics,CharacterCount,Placeholder,AIHighlight,TiptapUnderline,HighlightExtension,TextStyle,Color,CustomKeymap,GlobalDragHandle}from'novel';import {Markdown}from'tiptap-markdown';import {cx}from'class-variance-authority';import {createLowlight,common}from'lowlight';import {defaultStyles,FileIcon}from'react-file-icon';import {isValid,format}from'date-fns';function Xr(){return jsxs(Tc,{variant:"destructive",children:[jsx(AlertCircle,{className:"fk:h-4 fk:w-4"}),jsx(Uc,{children:"Project Paused"}),jsxs(Vc,{children:["This project has been paused. To troubleshoot this error, please"," ",jsx("a",{className:"fk:text-blue-500 fk:underline",href:"https://flexkit.io/docs/errors/project-paused",target:"_blank",rel:"noopener noreferrer",children:"follow these steps"}),"."]})]})}function Kr(){let{schemaErrorMessage:e$1}=e();if(!e$1)return jsx(Fragment,{});let[t,n,...r]=e$1.split(`
2
2
  `);return jsxs(Tc,{className:"fk:mb-4",variant:"destructive",children:[jsx(AlertCircle,{className:"fk:h-4 fk:w-4"}),jsx(Uc,{children:"Schema mismatch"}),jsxs(Vc,{children:[jsx("p",{children:t}),n?jsx("p",{className:"fk:mt-1",children:n}):null,r.length>0?jsx("ul",{className:"fk:mt-2 fk:list-disc fk:pl-4",children:r.map(o=>jsx("li",{children:o.replace(/^- /,"")},o))}):null]})]})}function lt({scrollHeight:e,scrollTop:t,clientHeight:n}){if(n<=0)return false;let r=t>0?Math.max(600,n):1;return e-t-n<r}var ln=36,cn=15,fn=2,ut=40;function pt(e){if(!e)return;let t=e.split(/\s+/);if(t.includes("fk:h-20"))return 80;if(t.includes("fk:h-10"))return 40;if(t.includes("fk:h-9"))return 36}function un(e,t){return e??pt(t)??ln}function lo({classNames:e$1,columns:t,data:n,entityName:r,hasMore:o=false,initialSelectionState:l,isLoadingMore:s=false,onEntitySelectionChange:b$1,onLoadMore:u,onScroll:k,onSortingChange:S,pageSize:M,rowHeightEstimate:g,rowAdditionState:i,rowDeletionState:T,scrollToTopKey:X,sorting:de,toolbarComponent:j}){let y=useRef(null),{schemaErrorMessage:N}=e(),[C,me]=useState(l??{}),[Ot,Ut]=useState({}),[zt,Bt]=useState([]),[Xt,jt]=useState([]),$t=de??Xt;useEffect(()=>{y.current?.scrollTo({top:0,left:0});},[r,X]),useEffect(()=>{if(!l)return;let a=Object.keys(C).sort().join(","),c=Object.keys(l).sort().join(",");a!==c&&me(l);},[l,C]);function Jt(a){if(S){S(a);return}jt(a);}let V=useReactTable({data:n,columns:t,state:{sorting:$t,columnVisibility:Ot,rowSelection:C,columnFilters:zt},initialState:{pagination:{pageSize:M??50}},enableRowSelection:true,onRowSelectionChange:Kt,onSortingChange:Jt,onColumnFiltersChange:Bt,onColumnVisibilityChange:Ut,getCoreRowModel:getCoreRowModel(),getFilteredRowModel:getFilteredRowModel(),getPaginationRowModel:getPaginationRowModel(),getSortedRowModel:getSortedRowModel(),getRowId:a=>a._id,manualFiltering:true,manualPagination:true,manualSorting:true,meta:{getRowBackground:a=>mn(a,T,i)}}),{rows:$$1}=V.getRowModel(),Pe=un(g,e$1?.row),qt=pt(e$1?.row)!=null,Le=useVirtualizer({count:$$1.length,estimateSize:()=>Pe,getItemKey:a=>$$1[a]?.id??a,getScrollElement:()=>y.current,overscan:cn,scrollMargin:ut}),F=V.getVisibleLeafColumns(),Ie=V.getHeaderGroups(),R=Ie.length===1,K=useVirtualizer({horizontal:true,count:F.length,estimateSize:a=>F[a].getSize(),getItemKey:a=>F[a].id,getScrollElement:()=>y.current,overscan:fn,enabled:R}),Gt=JSON.stringify(F.map(a=>[a.id,a.getSize()]));useEffect(()=>{K.measure();},[Gt,K]);let H=K.getVirtualItems(),W=R?H[0]?.index??0:0,_e=R?(H[H.length-1]?.index??-1)+1:F.length,Y=R?H[0]?.start??0:0,Q=R?Math.max(0,K.getTotalSize()-(H[H.length-1]?.end??0)):0,Ve=Le.getVirtualItems(),{paddingTop:Fe,paddingBottom:He}=dn(Ve,Le.getTotalSize(),ut),pe=useRef(u),Oe=useRef(o),ge=useRef(s);pe.current=u,Oe.current=o,ge.current=s;let ke=useCallback(a=>{if(!pe.current||!Oe.current||ge.current)return;let c=a??y.current;c&&lt(c)&&(ge.current=true,pe.current());},[]),Ue=b();useEffect(()=>{Ue&&ke();},[ke,$$1.length,o,s,Ue]);function Kt(a){let c=Object.keys(typeof a=="function"?a(C):a);me(a),b$1?.(c);}function Wt(a){k?.(a),ke(a.currentTarget);}return N?jsx(Fragment,{}):jsxs("div",{className:a$1("fk:flex fk:h-full fk:min-h-0 fk:w-full fk:min-w-0 fk:flex-col fk:gap-4",e$1?.wrapper),children:[j&&j(V),jsx("div",{className:"fk:relative fk:min-h-0 fk:min-w-0 fk:flex-1 fk:-mb-px",children:jsx(a,{delayDuration:400,children:jsxs($,{className:a$1("fk:grid fk:pb-20",e$1?.table),"aria-colcount":F.length,style:{minWidth:V.getTotalSize()},containerClassName:e$1?.tableContainer,onScroll:Wt,ref:y,children:[jsx(aa,{className:"fk:sticky fk:top-0 fk:z-20 fk:grid",children:Ie.map(a=>jsxs(da,{className:"fk:flex fk:w-full",children:[Y>0?jsx(le,{width:Y,header:true}):null,(R?a.headers.slice(W,_e):a.headers).map((c,P)=>jsxs(ea,{"aria-colindex":R?W+P+1:void 0,className:a$1("fk:flex fk:shrink-0 fk:items-center",c.column.id==="actions"&&"fk:pl-0"),colSpan:c.colSpan,style:c.getSize()?{width:`${c.getSize().toString()}px`}:{},children:[c.isPlaceholder?null:flexRender(c.column.columnDef.header,c.getContext()),s?jsx("div",{"aria-hidden":true,className:"fk:pointer-events-none fk:absolute fk:top-10.25 fk:right-px fk:left-px fk:z-20 fk:h-0.5 fk:overflow-hidden fk:opacity-4",children:jsx("div",{className:"fk:animate-progress fk:h-full fk:w-full fk:bg-foreground"})}):null]},c.id)),Q>0?jsx(le,{width:Q,header:true}):null]},a.id))}),jsx(ba,{className:"fk:grid fk:relative",children:$$1.length===0?jsx(da,{children:jsx(fa,{className:"fk:h-24 fk:text-center",colSpan:t.length,children:"No results."})}):jsxs(Fragment,{children:[Fe>0?jsx(dt,{height:Fe}):null,Ve.map(a=>{let c=$$1[a.index];return jsxs(da,{className:a$1(V.options.meta.getRowBackground(c),"fk:flex fk:w-full fk:overflow-hidden fk:transition-none",!qt&&g==null&&"fk:h-9",e$1?.row),"data-index":a.index,"data-state":c.getIsSelected()&&"selected",style:{height:`${Pe.toString()}px`},children:[Y>0?jsx(le,{width:Y}):null,c.getVisibleCells().slice(W,_e).map((P,Yt)=>jsx(fa,{className:a$1("fk:flex fk:shrink-0 fk:items-center fk:truncate",P.column.id==="actions"&&"fk:pl-1!"),"aria-colindex":W+Yt+1,style:{width:P.column.getSize()},children:flexRender(P.column.columnDef.cell,P.getContext())},P.id)),Q>0?jsx(le,{width:Q}):null]},a.key)}),He>0?jsx(dt,{height:He}):null]})})]})})})]})}function dn(e,t,n){if(e.length===0)return {paddingTop:0,paddingBottom:0};let r=e[0]?.start??0,o=e[e.length-1]?.end??0;return {paddingTop:Math.max(0,r-n),paddingBottom:Math.max(0,t-(o-n))}}function le({width:e,header:t=false}){return jsx(t?"th":"td",{"aria-hidden":true,style:{width:e,flexShrink:0,padding:0,border:0}})}function dt({height:e}){return jsx("tr",{"aria-hidden":true,className:"fk:pointer-events-none fk:border-0",style:{display:"block",height:`${e.toString()}px`},children:jsx("td",{className:"fk:p-0 fk:border-0"})})}function mn(e,t,n){return t?.includes(e.original._id)?"fk:bg-row-removed fk:hover:bg-row-removed-hover":n?.some(r=>r._id===e.original._id)?"fk:bg-row-added fk:hover:bg-row-added-hover":""}function po({table:e}){let[t]=e.getState().sorting;if(!t)return null;let r=e.getColumn(t.id)?.columnDef.meta?.label??t.id,o=t.desc?"desc":"asc";return jsxs(b$1,{"aria-label":`Clear sorting by ${r}`,className:"fk:h-8 fk:px-2 fk:lg:px-3 fk:text-success fk:border-none",onClick:()=>{e.resetSorting();},size:"sm",variant:"outline",children:["Sorted by ",r," ",o,jsx(X,{className:"fk:ml-1 fk:h-4 fk:w-4"})]})}function So(){let[e,t]=useState(false),[n,r]=useState(gql`
3
3
  mutation updateEntity($any: Any) {
4
4
  any
5
5
  }
6
- `),[o,l]=useState({}),[s,{data:b,loading:u,error:k}]=useMutation(n,o),S=a$2(k),{isProjectDisabled:M,isProjectReadOnly:g}=(()=>{if(S?.statusCode===403){let i=b$2(S.bodyText);if(i&&typeof i.code=="string"){if(i.code==="PROJECT_PAUSED")return {isProjectDisabled:true,isProjectReadOnly:false};if(i.code==="READ_ONLY_MODE")return {isProjectDisabled:false,isProjectReadOnly:true}}return {isProjectDisabled:true,isProjectReadOnly:false}}return {isProjectDisabled:false,isProjectReadOnly:false}})();return useEffect(()=>{e&&(s(),t(false));},[e,s]),[t,r,l,{data:b,loading:u,error:k,isProjectDisabled:M,isProjectReadOnly:g}]}function Se({column:e,title:t,className:n}){if(!e.getCanSort())return jsx("div",{className:a$1("fk:flex fk:items-center",n),children:t});let r=e.getIsSorted()==="asc",o=e.getIsSorted()==="desc";return jsxs("div",{className:a$1("fk:flex fk:w-full fk:items-center fk:justify-between fk:gap-1",n),children:[jsx("span",{className:"fk:truncate",children:t}),jsxs(e$1,{children:[jsx(g,{asChild:true,children:jsx("button",{"aria-label":`Sort ${t}`,className:"fk:inline-flex fk:shrink-0 fk:items-center fk:justify-center fk:rounded-sm fk:p-0.5 fk:text-muted-foreground fk:outline-hidden fk:hover:bg-accent fk:hover:text-accent-foreground fk:focus-visible:ring-1 fk:focus-visible:ring-ring fk:corner-squircle",type:"button",children:jsx(ChevronDown,{className:"fk:h-3.5 fk:w-3.5"})})}),jsxs(h,{align:"end",className:"fk:w-44",children:[jsxs(j,{"aria-checked":r,className:a$1(r&&"fk:bg-accent fk:text-accent-foreground"),onSelect:()=>{if(r){e.clearSorting();return}e.toggleSorting(false);},role:"menuitemcheckbox",children:[jsx(ArrowUp,{className:a$1("fk:h-4 fk:w-4",r&&"fk:text-white")}),"Sort Ascending"]}),jsxs(j,{"aria-checked":o,className:a$1(o&&"fk:bg-accent fk:text-accent-foreground"),onSelect:()=>{if(o){e.clearSorting();return}e.toggleSorting(true);},role:"menuitemcheckbox",children:[jsx(ArrowDown,{className:a$1("fk:h-4 fk:w-4",o&&"fk:text-white")}),"Sort Descending"]})]})]})]})}function xe({value:e}){return jsx("div",{className:"fk:flex fk:w-full fk:justify-center",children:e?jsx(CircleCheck,{className:"fk:w-4 fk:h-4 fk:text-emerald-500"}):jsx(CircleX,{className:"fk:w-4 fk:h-4 fk:text-muted-foreground"})})}var ht=500,En=3e3;function w({value:e}){let t=useRef(null),n=useRef(null),[r,o]=useState(false),[l,s]=useState(false);useEffect(()=>()=>{n.current&&clearTimeout(n.current);},[]);function b(){let g=t.current;return g?g.scrollWidth>g.clientWidth:false}async function u(g){if(g.preventDefault(),g.stopPropagation(),!!e){try{await navigator.clipboard.writeText(e);}catch{return}o(true),s(true),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>{o(false),s(false);},En);}}function k(){b();}function S(g){if(!r){if(g){s(b());return}s(false);}}if(!e)return jsx("div",{className:"fk:truncate"});let M=e.length>ht?`${e.slice(0,ht)}\u2026`:e;return jsxs(b$4,{open:l,onOpenChange:S,children:[jsx(c,{asChild:true,children:jsxs("button",{"aria-label":"Copy value",className:a$1("fk:group/copyable fk:relative fk:flex fk:w-full fk:min-w-0 fk:items-center fk:rounded-sm fk:border-0 fk:bg-transparent fk:px-0.5 fk:-mx-0.5 fk:py-0.5 fk:text-left fk:text-inherit fk:font-inherit fk:corner-squircle","fk:cursor-pointer fk:transition-[transform,background-color] fk:duration-75 fk:ease-out","fk:hover:bg-muted/50 fk:active:translate-y-px fk:active:scale-[0.98] fk:active:bg-muted/70","fk:focus-visible:outline-hidden fk:focus-visible:ring-1 fk:focus-visible:ring-ring"),onClick:u,onPointerEnter:k,type:"button",children:[jsx("span",{className:"fk:min-w-0 fk:flex-1 fk:truncate fk:pr-4",ref:t,children:e}),jsx("span",{"aria-hidden":true,className:a$1("fk:pointer-events-none fk:absolute fk:right-0.5 fk:top-1/2 fk:flex fk:-translate-y-1/2 fk:items-center fk:justify-center","fk:rounded-sm fk:bg-muted/80 fk:p-0.5 fk:text-muted-foreground fk:shadow-sm fk:ring-1 fk:ring-border/60 fk:corner-squircle","fk:transition-opacity fk:duration-100",r?"fk:opacity-100 fk:text-foreground":"fk:opacity-0 fk:group-hover/copyable:opacity-100 fk:group-focus-visible/copyable:opacity-100"),children:r?jsx(Check,{className:"fk:size-3"}):jsx(Copy,{className:"fk:size-3"})})]})}),jsx(e$2,{className:"fk:max-w-xs fk:wrap-break-word",children:r?"Copied to clipboard":M})]})}function B({value:e}){let t=typeof e=="object"||Array.isArray(e)?JSON.stringify(e):e;return t=t==="null"||t==null?"":String(t),jsx(w,{value:t})}var Zn=AIHighlight,er=Placeholder,tr=TiptapLink.configure({HTMLAttributes:{class:cx("fk:text-muted-foreground fk:underline fk:underline-offset-[3px] fk:hover:text-primary fk:transition-colors fk:cursor-pointer")}}),nr=Markdown.configure({html:true,tightLists:true,tightListClass:"tight",bulletListMarker:"-",linkify:false,breaks:false,transformPastedText:false,transformCopiedText:false}),rr=TiptapImage.extend({addProseMirrorPlugins(){return [UploadImagesPlugin({imageClass:cx("fk:opacity-40 fk:rounded-lg fk:border fk:border-stone-200 fk:corner-squircle")})]}}).configure({allowBase64:true,HTMLAttributes:{class:cx("fk:rounded-lg fk:border fk:border-muted fk:corner-squircle")}}),or=TaskList.configure({HTMLAttributes:{class:cx("fk:not-prose fk:pl-2 ")}}),ir=TaskItem.configure({HTMLAttributes:{class:cx("fk:flex gap-2 fk:items-start fk:my-2")},nested:true}),ar=HorizontalRule.configure({HTMLAttributes:{class:cx("mt-4 mb-6 border-t border-muted-foreground")}}),sr=StarterKit.configure({bulletList:{HTMLAttributes:{class:cx("fk:list-disc fk:list-outside fk:leading-3 fk:-mt-2")}},orderedList:{HTMLAttributes:{class:cx("fk:list-decimal fk:list-outside fk:leading-3 fk:-mt-2")}},listItem:{HTMLAttributes:{class:cx("fk:leading-normal fk:-mb-2")}},blockquote:{HTMLAttributes:{class:cx("fk:border-l-4 fk:border-primary")}},codeBlock:false,code:{HTMLAttributes:{class:cx("fk:rounded-md fk:bg-muted fk:px-1.5 fk:py-1 fk:font-mono fk:font-medium fk:corner-squircle"),spellcheck:"false"}},horizontalRule:false,dropcursor:{color:"#DBEAFE",width:4},gapcursor:false}),lr=CodeBlockLowlight.configure({lowlight:createLowlight(common)}),cr=Youtube.configure({HTMLAttributes:{class:cx("fk:rounded-lg fk:border fk:border-muted fk:corner-squircle")},inline:false}),fr=Twitter.configure({HTMLAttributes:{class:cx("fk:not-prose")},inline:false}),ur=Mathematics.configure({HTMLAttributes:{class:cx("fk:text-foreground fk:rounded-sm fk:p-1 fk:hover:bg-muted fk:cursor-pointer fk:corner-squircle")},katexOptions:{throwOnError:false}}),dr=CharacterCount.configure(),Tt=[sr,er,tr,rr,or,ir,ar,Zn,lr,cr,fr,ur,dr,TiptapUnderline,nr,HighlightExtension,TextStyle,Color,CustomKeymap,GlobalDragHandle];var ve;function hr(){let e=getSchema(Tt);return {schema:e,textSerializers:getTextSerializersFromSchema(e)}}function yt(e,t=100){if(!e)return "";try{let n=JSON.parse(e);return ve??=hr(),getText(Node.fromJSON(ve.schema,n),{textSerializers:ve.textSerializers}).substring(0,t)}catch{return e.substring(0,t)}}function St({value:e}){let t=useMemo(()=>yt(e),[e]);return jsx(w,{value:t})}var wt=250,xr=25e5,v=new Map,Ce=new Map,Ae=new Set,xt=new Map;function ce(e){if(xt.has(e))return;let t=new Image;t.decoding="async",t.src=e,xt.set(e,t);}function fe(e){let t=v.get(e);t&&v.set(e,{...t,lastUsedAt:Date.now()});}function vr(){if(v.size<=wt)return;let e=Array.from(v.entries()).sort((n,r)=>n[1].lastUsedAt-r[1].lastUsedAt),t=Math.max(1,Math.ceil(wt*.1));for(let n=0;n<t&&n<e.length;n+=1){let[r,o]=e[n];v.delete(r),URL.revokeObjectURL(o.objectUrl);}}async function Cr(e){if(Ae.has(e)){ce(e);return}if(v.has(e)){fe(e);return}let t=Ce.get(e);if(t){await t;return}let n=(async()=>{try{let r=await fetch(e,{mode:"cors",cache:"force-cache"});if(!r.ok){ce(e);return}let o=await r.blob();if(o.size>xr)return;let l=URL.createObjectURL(o);v.set(e,{objectUrl:l,byteSize:o.size,lastUsedAt:Date.now()}),vr();}catch(r){r instanceof TypeError&&Ae.add(e),ce(e);}})();Ce.set(e,n),await n,Ce.delete(e);}function vt(e){let t=useMemo(()=>{if(!e)return null;let o=v.get(e);return o?(fe(e),o.objectUrl):null},[e]),[n,r]=useState(t);return useEffect(()=>{if(!e){r(null);return}if(Ae.has(e)){ce(e),r(null);return}let o=v.get(e);if(o){fe(e),r(o.objectUrl);return}r(null);let l=false;return Cr(e).then(()=>{let s=v.get(e);s&&(l||(fe(e),r(s.objectUrl)));}),()=>{l=true;}},[e]),n}var De="fk:bg-[#fafafa] [--asset-checker:#f0f0f0] [background-image:linear-gradient(45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(-45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(45deg,transparent_75%,var(--asset-checker)_75%),linear-gradient(-45deg,transparent_75%,var(--asset-checker)_75%)] [background-position:0_0,0_4px,4px_-4px,-4px_0px] [background-size:8px_8px] fk:dark:bg-[#222] dark:[--asset-checker:#2a2a2a]";function Ct({value:e}){return Array.isArray(e)?jsx(Mr,{value:e}):jsx(Er,{value:e})}function Er({value:e}){let t=e?.path??"",n=!!t,r=n&&/\.(png|jpe?g|gif|webp|avif|svg)$/i.test(t),o=u=>{let[k]=u.split("?"),S=k.split(".");return S.length>1?S.pop().toLowerCase():"file"},l=n?t.endsWith(".svg")?`${b$6}${t}`:`${b$6}${t}?w=84&h=84&f=webp`:null,s=n?t.endsWith(".svg")?`${b$6}${t}`:`${b$6}${t}?w=624&h=624&f=webp`:"",b=vt(l);return n?jsx("div",{className:"fk:z-10",children:r?jsxs(b$4,{children:[jsx(c,{asChild:true,children:jsx("img",{alt:"asset",className:`fk:w-7 fk:h-7 fk:cursor-zoom-in fk:overflow-hidden fk:rounded-md fk:object-contain ${De} fk:corner-squircle`,decoding:"async",src:b??void 0})}),jsx(d,{children:jsx(e$2,{children:jsx("img",{alt:"asset",className:`fk:w-52 fk:h-52 fk:overflow-hidden fk:rounded-md fk:object-contain ${De} fk:corner-squircle`,decoding:"async",src:s})})})]}):jsxs(b$4,{children:[jsx(c,{asChild:true,children:jsx("div",{className:"fk:w-7 fk:h-7 fk:rounded-sm fk:bg-transparent fk:flex fk:items-center fk:justify-center fk:[&>svg]:h-full fk:[&>svg]:w-auto fk:corner-squircle",children:(()=>{let u=o(t),k=defaultStyles[u];return jsx(FileIcon,{extension:u,...k||{}})})()})}),jsx(d,{children:jsx(e$2,{children:jsx("div",{className:"fk:text-sm fk:text-muted-foreground",children:"Preview not available"})})})]})}):null}function Mr({value:e}){let t=e.filter(o=>!!o.path).slice(0,3),n=Math.max(e[0]?.totalCount??0,e.length);if(t.length===0)return n>0?jsx("div",{className:"fk:flex fk:items-center",children:jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:n===1?"1 asset":`${n} assets`})}):null;let r=n-t.length;return jsxs("div",{className:"fk:flex fk:items-center",children:[jsx("div",{className:"fk:flex fk:-space-x-2",children:t.map(o=>jsx("img",{alt:"asset",className:`fk:h-7 fk:w-7 fk:overflow-hidden fk:rounded-md fk:object-contain ${De} fk:corner-squircle`,decoding:"async",src:`${b$6}${o.path}?w=84&h=84&f=webp`},o._id))}),r>0?jsxs("span",{className:"fk:ml-2 fk:text-xs fk:text-muted-foreground",children:["+",r]}):null]})}function Me({value:e}){if(e==null||e===""||typeof e!="string")return jsx(w,{value:""});let t=new Date(e);if(!isValid(t))return jsx(w,{value:""});let n=format(t,"MMM d, yyyy")+" at "+format(t,"HH:mm");return jsx(w,{value:n})}function Rr(e){return "groupLabel"in e}function Pr(e){return e.flatMap(t=>Rr(t)?t.items:[t])}function Lr(e,t){if(!t)return e;let n=Pr(t).find(r=>String(r.value)===e);return n?n.label:e}function Et({value:e,options:t}){if(e==null)return jsx(w,{value:""});let n=String(e),r=Lr(n,t?.list);return jsx(w,{value:r})}function Nt({value:e}){return !e||!e.split(",").length?null:jsx("div",{className:"fk:flex fk:flex-wrap fk:gap-1 fk:max-w-full truncate",children:e.split(",").map(t=>jsx(b$5,{className:"fk:px-2.5 fk:py-0 fk:font-normal fk:text-[0.6875rem] fk:leading-4",variant:"secondary",children:t},t))})}function Rt(e,t=5){let n=Number.isFinite(t)&&t>=1?Math.floor(t):5,r=typeof e=="string"&&e.trim()!==""?Number(e):e;if(typeof r!="number"||!Number.isFinite(r))return null;let o=Math.min(n,Math.max(0,Math.round(r)));return {filled:o,max:n,label:`${String(o)} out of ${String(n)} stars`}}function Pt({value:e,options:t}){let n=Rt(e,t?.max);return n?jsx("span",{"aria-label":n.label,className:"fk:inline-flex fk:items-center fk:gap-0.5",role:"img",title:n.label,children:Array.from({length:n.max},(r,o)=>jsx(Star,{"aria-hidden":true,className:o<n.filled?"fk:h-3.5 fk:w-3.5 fk:fill-amber-400 fk:text-amber-400":"fk:h-3.5 fk:w-3.5 fk:fill-transparent fk:text-muted-foreground/40",strokeWidth:1.5},o))}):jsx("span",{})}var _r=/\.(png|jpe?g|gif|webp|avif|svg)$/i;function Lt(e){try{let{pathname:t}=new URL(e);return t.split("/").pop()||t}catch{let[t]=e.split("?");return t}}function It(e){return e.originalFilename?e.originalFilename:e.path?e.path:e.url?Lt(e.url):""}function _t(e){let t=It(e),[n]=t.split("?"),r=n.split(".");return r.length>1?r.pop().toLowerCase():"file"}function Vt(e){return e.mimeType?e.mimeType.startsWith("image/"):_r.test(It(e))}function Re(e,t){if(!e||!t||Lt(e).toLowerCase().endsWith(".svg"))return e;let n=new URLSearchParams({f:"webp",h:String(t.height),w:String(t.width)}),r=e.includes("?")?"&":"?";return `${e}${r}${n.toString()}`}var Or=FileIcon,Ft="fk:bg-[#fafafa] [--asset-checker:#f0f0f0] [background-image:linear-gradient(45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(-45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(45deg,transparent_75%,var(--asset-checker)_75%),linear-gradient(-45deg,transparent_75%,var(--asset-checker)_75%)] [background-position:0_0,0_4px,4px_-4px,-4px_0px] [background-size:8px_8px] fk:dark:bg-[#222] dark:[--asset-checker:#2a2a2a]";function Ht({value:e}){let[t,n]=useState(false),r=e?.url??"";if(!e||!r&&!e.path&&!e.originalFilename)return null;if(!(Vt(e)&&!!r)){let u=_t(e),k=defaultStyles[u];return jsx("div",{className:"fk:z-10",children:jsx(a,{children:jsxs(b$4,{children:[jsx(c,{asChild:true,children:jsx("div",{className:"fk:w-7 fk:h-7 fk:rounded-sm fk:bg-transparent fk:flex fk:items-center fk:justify-center fk:[&>svg]:h-full fk:[&>svg]:w-auto fk:corner-squircle",children:jsx(Or,{extension:u,...k||{}})})}),jsx(d,{children:jsx(e$2,{children:jsx("div",{className:"fk:text-sm fk:text-muted-foreground",children:"Preview not available"})})})]})})})}let l$1=Re(r,{width:84,height:84}),s=Re(r,{width:624,height:624});function b(u){u.stopPropagation(),n(true);}return jsx("div",{className:"fk:z-10",children:jsxs(a,{children:[jsxs(b$4,{children:[jsx(c,{asChild:true,children:jsx("img",{src:l$1,alt:"asset",className:`fk:w-12 fk:h-12 fk:cursor-zoom-in fk:overflow-hidden fk:rounded-md fk:object-contain ${Ft} fk:corner-squircle`,onClick:b})}),jsx(d,{children:jsx(e$2,{children:jsx("img",{src:s,alt:"asset",className:`fk:w-52 fk:h-52 fk:overflow-hidden fk:rounded-md fk:object-contain ${Ft} fk:corner-squircle`})})})]}),jsx(c$1,{open:t,onOpenChange:n,children:jsxs(h$1,{className:"fk:sm:max-w-4xl fk:p-3",children:[jsxs(i,{children:[jsx(k,{className:"fk:sr-only",children:"Asset preview"}),jsx(l,{className:"fk:sr-only",children:"Enlarged asset preview"})]}),jsx("img",{src:r,alt:"asset",className:"fk:max-h-[85vh] fk:w-full fk:overflow-hidden fk:rounded-md fk:object-contain fk:corner-squircle"})]})})]})})}var Ur=new Set(["text","number","datetime","switch","select"]);function Xi({attributesSchema:e,checkboxSelect:t,actionsComponent:n,enableColumnSorting:r=false}){let[,o$1]=g$1(),l=b$3(e,o$1.user?.spaces),s={datetime:"datetime",editor:"editor",asset:"asset",number:"text",relationship:"text",select:"select",switch:"boolean",text:"text",textarea:"text"},b={boolean:xe,date:B,datetime:Me,editor:St,asset:Ct,number:B,relationship:B,select:Et,switch:xe,text:B,textarea:B,tags:Nt,rating:Pt,assetPreviewField:Ht},u=l.map(i=>{if(i.name==="_updatedAt")return null;let T=(i.inputType==="relationship"&&i.relationship?.entity==="_asset"?"asset":void 0)??i.previewType??s[i.inputType],X=b[T]??b.text;if(i.hidden===true)return null;let de=T==="tags",j=r&&i.scope==="global"&&Ur.has(i.inputType);return {accessorKey:i.name,filterFn:(y,N,C)=>de?true:(Array.isArray(C)?C:[C]).includes(y.getValue(N)),header:({column:y})=>j?jsx(Se,{column:y,title:i.label}):jsx("div",{className:"fk:flex fk:items-center",children:i.label}),cell:({row:y})=>{let N=X;return T==="select"||T==="rating"?jsx(N,{value:y.getValue(i.name),options:i.options}):T==="assetPreviewField"?jsx(N,{value:y.original}):jsx(N,{value:y.getValue(i.name)})},enableSorting:j,enableHiding:true,meta:{label:i.label},size:i.options?.size??150}}).filter(i=>i!==null),k={id:"actions",cell:({row:i})=>n?n(i):null,size:80},S={accessorKey:"_updatedAt",header:({column:i})=>r?jsx(Se,{column:i,title:"Updated At"}):jsx("div",{className:"fk:flex fk:items-center",children:"Updated At"}),cell:({row:i})=>jsx(Me,{value:i.getValue("_updatedAt")}),enableSorting:r,enableHiding:false,meta:{label:"Updated At"},size:220},M={id:"select",cell:({row:i,table:T})=>jsx(o,{"aria-label":"Select row",checked:i.getIsSelected(),onCheckedChange:X=>{T.toggleAllPageRowsSelected(false),i.toggleSelected(!!X);}}),enableSorting:false,enableHiding:false,size:50},g={id:"select",header:({table:i})=>jsx(o,{className:"fk:dark:bg-white/15","aria-label":"Select all",checked:i.getIsAllPageRowsSelected()||i.getIsSomePageRowsSelected()&&"indeterminate",onCheckedChange:T=>{i.toggleAllPageRowsSelected(!!T);}}),cell:({row:i})=>jsx(o,{"aria-label":"Select row",checked:i.getIsSelected(),onCheckedChange:T=>{i.toggleSelected(!!T);}}),enableSorting:false,enableHiding:false,size:50};return [...t==="single"?[M]:[],...t==="multiple"?[g]:[],...n?[k]:[],...u,S]}export{Xr as a,Kr as b,lt as c,lo as d,po as e,So as f,Tt as g,It as h,_t as i,Vt as j,Re as k,Se as l,Xi as m};//# sourceMappingURL=chunk-JSJZKPXU.js.map
7
- //# sourceMappingURL=chunk-JSJZKPXU.js.map
6
+ `),[o,l]=useState({}),[s,{data:b,loading:u,error:k}]=useMutation(n,o),S=a$2(k),{isProjectDisabled:M,isProjectReadOnly:g}=(()=>{if(S?.statusCode===403){let i=b$2(S.bodyText);if(i&&typeof i.code=="string"){if(i.code==="PROJECT_PAUSED")return {isProjectDisabled:true,isProjectReadOnly:false};if(i.code==="READ_ONLY_MODE")return {isProjectDisabled:false,isProjectReadOnly:true}}return {isProjectDisabled:true,isProjectReadOnly:false}}return {isProjectDisabled:false,isProjectReadOnly:false}})();return useEffect(()=>{e&&(s(),t(false));},[e,s]),[t,r,l,{data:b,loading:u,error:k,isProjectDisabled:M,isProjectReadOnly:g}]}function Se({column:e,title:t,className:n}){if(!e.getCanSort())return jsx("div",{className:a$1("fk:flex fk:items-center",n),children:t});let r=e.getIsSorted()==="asc",o=e.getIsSorted()==="desc";return jsxs("div",{className:a$1("fk:flex fk:w-full fk:items-center fk:justify-between fk:gap-1",n),children:[jsx("span",{className:"fk:truncate",children:t}),jsxs(e$1,{children:[jsx(g,{asChild:true,children:jsx("button",{"aria-label":`Sort ${t}`,className:"fk:inline-flex fk:shrink-0 fk:items-center fk:justify-center fk:rounded-sm fk:p-0.5 fk:text-muted-foreground fk:outline-hidden fk:hover:bg-accent fk:hover:text-accent-foreground fk:focus-visible:ring-1 fk:focus-visible:ring-ring fk:corner-squircle",type:"button",children:jsx(ChevronDown,{className:"fk:h-3.5 fk:w-3.5"})})}),jsxs(h,{align:"end",className:"fk:w-44",children:[jsxs(j,{"aria-checked":r,className:a$1(r&&"fk:bg-accent fk:text-accent-foreground"),onSelect:()=>{if(r){e.clearSorting();return}e.toggleSorting(false);},role:"menuitemcheckbox",children:[jsx(ArrowUp,{className:a$1("fk:h-4 fk:w-4",r&&"fk:text-white")}),"Sort Ascending"]}),jsxs(j,{"aria-checked":o,className:a$1(o&&"fk:bg-accent fk:text-accent-foreground"),onSelect:()=>{if(o){e.clearSorting();return}e.toggleSorting(true);},role:"menuitemcheckbox",children:[jsx(ArrowDown,{className:a$1("fk:h-4 fk:w-4",o&&"fk:text-white")}),"Sort Descending"]})]})]})]})}function xe({value:e}){return jsx("div",{className:"fk:flex fk:w-full fk:justify-center",children:e?jsx(CircleCheck,{className:"fk:w-4 fk:h-4 fk:text-emerald-500"}):jsx(CircleX,{className:"fk:w-4 fk:h-4 fk:text-muted-foreground"})})}var ht=500,En=3e3;function w({value:e}){let t=useRef(null),n=useRef(null),[r,o]=useState(false),[l,s]=useState(false);useEffect(()=>()=>{n.current&&clearTimeout(n.current);},[]);function b(){let g=t.current;return g?g.scrollWidth>g.clientWidth:false}async function u(g){if(g.preventDefault(),g.stopPropagation(),!!e){try{await navigator.clipboard.writeText(e);}catch{return}o(true),s(true),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>{o(false),s(false);},En);}}function k(){b();}function S(g){if(!r){if(g){s(b());return}s(false);}}if(!e)return jsx("div",{className:"fk:truncate"});let M=e.length>ht?`${e.slice(0,ht)}\u2026`:e;return jsxs(b$4,{open:l,onOpenChange:S,children:[jsx(c,{asChild:true,children:jsxs("button",{"aria-label":"Copy value",className:a$1("fk:group/copyable fk:relative fk:flex fk:w-full fk:min-w-0 fk:items-center fk:rounded-sm fk:border-0 fk:bg-transparent fk:px-0.5 fk:-mx-0.5 fk:py-0.5 fk:text-left fk:text-inherit fk:font-inherit fk:corner-squircle","fk:cursor-pointer fk:transition-[transform,background-color] fk:duration-75 fk:ease-out","fk:hover:bg-muted/50 fk:active:translate-y-px fk:active:scale-[0.98] fk:active:bg-muted/70","fk:focus-visible:outline-hidden fk:focus-visible:ring-1 fk:focus-visible:ring-ring"),onClick:u,onPointerEnter:k,type:"button",children:[jsx("span",{className:"fk:min-w-0 fk:flex-1 fk:truncate fk:pr-4",ref:t,children:e}),jsx("span",{"aria-hidden":true,className:a$1("fk:pointer-events-none fk:absolute fk:right-0.5 fk:top-1/2 fk:flex fk:-translate-y-1/2 fk:items-center fk:justify-center","fk:rounded-sm fk:bg-muted/80 fk:p-0.5 fk:text-muted-foreground fk:shadow-sm fk:ring-1 fk:ring-border/60 fk:corner-squircle","fk:transition-opacity fk:duration-100",r?"fk:opacity-100 fk:text-foreground":"fk:opacity-0 fk:group-hover/copyable:opacity-100 fk:group-focus-visible/copyable:opacity-100"),children:r?jsx(Check,{className:"fk:size-3"}):jsx(Copy,{className:"fk:size-3"})})]})}),jsx(e$2,{className:"fk:max-w-xs fk:wrap-break-word",children:r?"Copied to clipboard":M})]})}function B({value:e}){let t=typeof e=="object"||Array.isArray(e)?JSON.stringify(e):e;return t=t==="null"||t==null?"":String(t),jsx(w,{value:t})}var Zn=AIHighlight,er=Placeholder,tr=TiptapLink.configure({HTMLAttributes:{class:cx("fk:text-muted-foreground fk:underline fk:underline-offset-[3px] fk:hover:text-primary fk:transition-colors fk:cursor-pointer")}}),nr=Markdown.configure({html:true,tightLists:true,tightListClass:"tight",bulletListMarker:"-",linkify:false,breaks:false,transformPastedText:false,transformCopiedText:false}),rr=TiptapImage.extend({addProseMirrorPlugins(){return [UploadImagesPlugin({imageClass:cx("fk:opacity-40 fk:rounded-lg fk:border fk:border-stone-200 fk:corner-squircle")})]}}).configure({allowBase64:true,HTMLAttributes:{class:cx("fk:rounded-lg fk:border fk:border-muted fk:corner-squircle")}}),or=TaskList.configure({HTMLAttributes:{class:cx("fk:not-prose fk:pl-2 ")}}),ir=TaskItem.configure({HTMLAttributes:{class:cx("fk:flex gap-2 fk:items-start fk:my-2")},nested:true}),ar=HorizontalRule.configure({HTMLAttributes:{class:cx("mt-4 mb-6 border-t border-muted-foreground")}}),sr=StarterKit.configure({bulletList:{HTMLAttributes:{class:cx("fk:list-disc fk:list-outside fk:leading-3 fk:-mt-2")}},orderedList:{HTMLAttributes:{class:cx("fk:list-decimal fk:list-outside fk:leading-3 fk:-mt-2")}},listItem:{HTMLAttributes:{class:cx("fk:leading-normal fk:-mb-2")}},blockquote:{HTMLAttributes:{class:cx("fk:border-l-4 fk:border-primary")}},codeBlock:false,code:{HTMLAttributes:{class:cx("fk:rounded-md fk:bg-muted fk:px-1.5 fk:py-1 fk:font-mono fk:font-medium fk:corner-squircle"),spellcheck:"false"}},horizontalRule:false,dropcursor:{color:"#DBEAFE",width:4},gapcursor:false}),lr=CodeBlockLowlight.configure({lowlight:createLowlight(common)}),cr=Youtube.configure({HTMLAttributes:{class:cx("fk:rounded-lg fk:border fk:border-muted fk:corner-squircle")},inline:false}),fr=Twitter.configure({HTMLAttributes:{class:cx("fk:not-prose")},inline:false}),ur=Mathematics.configure({HTMLAttributes:{class:cx("fk:text-foreground fk:rounded-sm fk:p-1 fk:hover:bg-muted fk:cursor-pointer fk:corner-squircle")},katexOptions:{throwOnError:false}}),dr=CharacterCount.configure(),Tt=[sr,er,tr,rr,or,ir,ar,Zn,lr,cr,fr,ur,dr,TiptapUnderline,nr,HighlightExtension,TextStyle,Color,CustomKeymap,GlobalDragHandle];var ve;function hr(){let e=getSchema(Tt);return {schema:e,textSerializers:getTextSerializersFromSchema(e)}}function yt(e,t=100){if(!e)return "";try{let n=JSON.parse(e);return ve??=hr(),getText(Node.fromJSON(ve.schema,n),{textSerializers:ve.textSerializers}).substring(0,t)}catch{return e.substring(0,t)}}function St({value:e}){let t=useMemo(()=>yt(e),[e]);return jsx(w,{value:t})}var wt=250,xr=25e5,v=new Map,Ce=new Map,Ae=new Set,xt=new Map;function ce(e){if(xt.has(e))return;let t=new Image;t.decoding="async",t.src=e,xt.set(e,t);}function fe(e){let t=v.get(e);t&&v.set(e,{...t,lastUsedAt:Date.now()});}function vr(){if(v.size<=wt)return;let e=Array.from(v.entries()).sort((n,r)=>n[1].lastUsedAt-r[1].lastUsedAt),t=Math.max(1,Math.ceil(wt*.1));for(let n=0;n<t&&n<e.length;n+=1){let[r,o]=e[n];v.delete(r),URL.revokeObjectURL(o.objectUrl);}}async function Cr(e){if(Ae.has(e)){ce(e);return}if(v.has(e)){fe(e);return}let t=Ce.get(e);if(t){await t;return}let n=(async()=>{try{let r=await fetch(e,{mode:"cors",cache:"force-cache"});if(!r.ok){ce(e);return}let o=await r.blob();if(o.size>xr)return;let l=URL.createObjectURL(o);v.set(e,{objectUrl:l,byteSize:o.size,lastUsedAt:Date.now()}),vr();}catch(r){r instanceof TypeError&&Ae.add(e),ce(e);}})();Ce.set(e,n),await n,Ce.delete(e);}function vt(e){let t=useMemo(()=>{if(!e)return null;let o=v.get(e);return o?(fe(e),o.objectUrl):null},[e]),[n,r]=useState(t);return useEffect(()=>{if(!e){r(null);return}if(Ae.has(e)){ce(e),r(null);return}let o=v.get(e);if(o){fe(e),r(o.objectUrl);return}r(null);let l=false;return Cr(e).then(()=>{let s=v.get(e);s&&(l||(fe(e),r(s.objectUrl)));}),()=>{l=true;}},[e]),n}var De="fk:bg-[#fafafa] [--asset-checker:#f0f0f0] [background-image:linear-gradient(45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(-45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(45deg,transparent_75%,var(--asset-checker)_75%),linear-gradient(-45deg,transparent_75%,var(--asset-checker)_75%)] [background-position:0_0,0_4px,4px_-4px,-4px_0px] [background-size:8px_8px] fk:dark:bg-[#222] dark:[--asset-checker:#2a2a2a]";function Ct({value:e}){return Array.isArray(e)?jsx(Mr,{value:e}):jsx(Er,{value:e})}function Er({value:e}){let t=e?.path??"",n=!!t,r=n&&/\.(png|jpe?g|gif|webp|avif|svg)$/i.test(t),o=u=>{let[k]=u.split("?"),S=k.split(".");return S.length>1?S.pop().toLowerCase():"file"},l=n?t.endsWith(".svg")?`${b$6}${t}`:`${b$6}${t}?w=84&h=84&f=webp`:null,s=n?t.endsWith(".svg")?`${b$6}${t}`:`${b$6}${t}?w=624&h=624&f=webp`:"",b=vt(l);return n?jsx("div",{className:"fk:z-10",children:r?jsxs(b$4,{children:[jsx(c,{asChild:true,children:jsx("img",{alt:"asset",className:`fk:w-7 fk:h-7 fk:cursor-zoom-in fk:overflow-hidden fk:rounded-md fk:object-contain ${De} fk:corner-squircle`,decoding:"async",src:b??void 0})}),jsx(d,{children:jsx(e$2,{children:jsx("img",{alt:"asset",className:`fk:w-52 fk:h-52 fk:overflow-hidden fk:rounded-md fk:object-contain ${De} fk:corner-squircle`,decoding:"async",src:s})})})]}):jsxs(b$4,{children:[jsx(c,{asChild:true,children:jsx("div",{className:"fk:w-7 fk:h-7 fk:rounded-sm fk:bg-transparent fk:flex fk:items-center fk:justify-center fk:[&>svg]:h-full fk:[&>svg]:w-auto fk:corner-squircle",children:(()=>{let u=o(t),k=defaultStyles[u];return jsx(FileIcon,{extension:u,...k||{}})})()})}),jsx(d,{children:jsx(e$2,{children:jsx("div",{className:"fk:text-sm fk:text-muted-foreground",children:"Preview not available"})})})]})}):null}function Mr({value:e}){let t=e.filter(o=>!!o.path).slice(0,3),n=Math.max(e[0]?.totalCount??0,e.length);if(t.length===0)return n>0?jsx("div",{className:"fk:flex fk:items-center",children:jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:n===1?"1 asset":`${n} assets`})}):null;let r=n-t.length;return jsxs("div",{className:"fk:flex fk:items-center",children:[jsx("div",{className:"fk:flex fk:-space-x-2",children:t.map(o=>jsx("img",{alt:"asset",className:`fk:h-7 fk:w-7 fk:overflow-hidden fk:rounded-md fk:object-contain ${De} fk:corner-squircle`,decoding:"async",src:`${b$6}${o.path}?w=84&h=84&f=webp`},o._id))}),r>0?jsxs("span",{className:"fk:ml-2 fk:text-xs fk:text-muted-foreground",children:["+",r]}):null]})}function Me({value:e}){if(e==null||e===""||typeof e!="string")return jsx(w,{value:""});let t=new Date(e);if(!isValid(t))return jsx(w,{value:""});let n=format(t,"MMM d, yyyy")+" at "+format(t,"HH:mm");return jsx(w,{value:n})}function Rr(e){return "groupLabel"in e}function Pr(e){return e.flatMap(t=>Rr(t)?t.items:[t])}function Lr(e,t){if(!t)return e;let n=Pr(t).find(r=>String(r.value)===e);return n?n.label:e}function Et({value:e,options:t}){if(e==null)return jsx(w,{value:""});let n=String(e),r=Lr(n,t?.list);return jsx(w,{value:r})}function Nt({value:e}){return !e||!e.split(",").length?null:jsx("div",{className:"fk:flex fk:flex-wrap fk:gap-1 fk:max-w-full truncate",children:e.split(",").map(t=>jsx(b$5,{className:"fk:px-2.5 fk:py-0 fk:font-normal fk:text-[0.6875rem] fk:leading-4",variant:"secondary",children:t},t))})}function Rt(e,t=5){let n=Number.isFinite(t)&&t>=1?Math.floor(t):5,r=typeof e=="string"&&e.trim()!==""?Number(e):e;if(typeof r!="number"||!Number.isFinite(r))return null;let o=Math.min(n,Math.max(0,Math.round(r)));return {filled:o,max:n,label:`${String(o)} out of ${String(n)} stars`}}function Pt({value:e,options:t}){let n=Rt(e,t?.max);return n?jsx("span",{"aria-label":n.label,className:"fk:inline-flex fk:items-center fk:gap-0.5",role:"img",title:n.label,children:Array.from({length:n.max},(r,o)=>jsx(Star,{"aria-hidden":true,className:o<n.filled?"fk:h-3.5 fk:w-3.5 fk:fill-amber-400 fk:text-amber-400":"fk:h-3.5 fk:w-3.5 fk:fill-transparent fk:text-muted-foreground/40",strokeWidth:1.5},o))}):jsx("span",{})}var _r=/\.(png|jpe?g|gif|webp|avif|svg)$/i;function Lt(e){try{let{pathname:t}=new URL(e);return t.split("/").pop()||t}catch{let[t]=e.split("?");return t}}function It(e){return e.originalFilename?e.originalFilename:e.path?e.path:e.url?Lt(e.url):""}function _t(e){let t=It(e),[n]=t.split("?"),r=n.split(".");return r.length>1?r.pop().toLowerCase():"file"}function Vt(e){return e.mimeType?e.mimeType.startsWith("image/"):_r.test(It(e))}function Re(e,t){if(!e||!t||Lt(e).toLowerCase().endsWith(".svg"))return e;let n=new URLSearchParams({f:"webp",h:String(t.height),w:String(t.width)}),r=e.includes("?")?"&":"?";return `${e}${r}${n.toString()}`}var Or=FileIcon,Ft="fk:bg-[#fafafa] [--asset-checker:#f0f0f0] [background-image:linear-gradient(45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(-45deg,var(--asset-checker)_25%,transparent_25%),linear-gradient(45deg,transparent_75%,var(--asset-checker)_75%),linear-gradient(-45deg,transparent_75%,var(--asset-checker)_75%)] [background-position:0_0,0_4px,4px_-4px,-4px_0px] [background-size:8px_8px] fk:dark:bg-[#222] dark:[--asset-checker:#2a2a2a]";function Ht({value:e}){let[t,n]=useState(false),r=e?.url??"";if(!e||!r&&!e.path&&!e.originalFilename)return null;if(!(Vt(e)&&!!r)){let u=_t(e),k=defaultStyles[u];return jsx("div",{className:"fk:z-10",children:jsx(a,{children:jsxs(b$4,{children:[jsx(c,{asChild:true,children:jsx("div",{className:"fk:w-7 fk:h-7 fk:rounded-sm fk:bg-transparent fk:flex fk:items-center fk:justify-center fk:[&>svg]:h-full fk:[&>svg]:w-auto fk:corner-squircle",children:jsx(Or,{extension:u,...k||{}})})}),jsx(d,{children:jsx(e$2,{children:jsx("div",{className:"fk:text-sm fk:text-muted-foreground",children:"Preview not available"})})})]})})})}let l$1=Re(r,{width:84,height:84}),s=Re(r,{width:624,height:624});function b(u){u.stopPropagation(),n(true);}return jsx("div",{className:"fk:z-10",children:jsxs(a,{children:[jsxs(b$4,{children:[jsx(c,{asChild:true,children:jsx("img",{src:l$1,alt:"asset",className:`fk:w-12 fk:h-12 fk:cursor-zoom-in fk:overflow-hidden fk:rounded-md fk:object-contain ${Ft} fk:corner-squircle`,onClick:b})}),jsx(d,{children:jsx(e$2,{children:jsx("img",{src:s,alt:"asset",className:`fk:w-52 fk:h-52 fk:overflow-hidden fk:rounded-md fk:object-contain ${Ft} fk:corner-squircle`})})})]}),jsx(c$1,{open:t,onOpenChange:n,children:jsxs(h$1,{className:"fk:sm:max-w-4xl fk:p-3",children:[jsxs(i,{children:[jsx(k,{className:"fk:sr-only",children:"Asset preview"}),jsx(l,{className:"fk:sr-only",children:"Enlarged asset preview"})]}),jsx("img",{src:r,alt:"asset",className:"fk:max-h-[85vh] fk:w-full fk:overflow-hidden fk:rounded-md fk:object-contain fk:corner-squircle"})]})})]})})}var Ur=new Set(["text","number","datetime","switch","select"]);function Xi({attributesSchema:e,checkboxSelect:t,actionsComponent:n,enableColumnSorting:r=false}){let[,o$1]=g$1(),l=b$3(e,o$1.user?.spaces),s={datetime:"datetime",editor:"editor",asset:"asset",number:"text",relationship:"text",select:"select",switch:"boolean",text:"text",textarea:"text"},b={boolean:xe,date:B,datetime:Me,editor:St,asset:Ct,number:B,relationship:B,select:Et,switch:xe,text:B,textarea:B,tags:Nt,rating:Pt,assetPreviewField:Ht},u=l.map(i=>{if(i.name==="_updatedAt")return null;let T=(i.inputType==="relationship"&&i.relationship?.entity==="_asset"?"asset":void 0)??i.previewType??s[i.inputType],X=b[T]??b.text;if(i.hidden===true)return null;let de=T==="tags",j=r&&i.scope==="global"&&Ur.has(i.inputType);return {accessorKey:i.name,filterFn:(y,N,C)=>de?true:(Array.isArray(C)?C:[C]).includes(y.getValue(N)),header:({column:y})=>j?jsx(Se,{column:y,title:i.label}):jsx("div",{className:"fk:flex fk:items-center",children:i.label}),cell:({row:y})=>{let N=X;return T==="select"||T==="rating"?jsx(N,{value:y.getValue(i.name),options:i.options}):T==="assetPreviewField"?jsx(N,{value:y.original}):jsx(N,{value:y.getValue(i.name)})},enableSorting:j,enableHiding:true,meta:{label:i.label},size:i.options?.size??150}}).filter(i=>i!==null),k={id:"actions",cell:({row:i})=>n?n(i):null,size:80},S={accessorKey:"_updatedAt",header:({column:i})=>r?jsx(Se,{column:i,title:"Updated At"}):jsx("div",{className:"fk:flex fk:items-center",children:"Updated At"}),cell:({row:i})=>jsx(Me,{value:i.getValue("_updatedAt")}),enableSorting:r,enableHiding:false,meta:{label:"Updated At"},size:220},M={id:"select",cell:({row:i,table:T})=>jsx(o,{"aria-label":"Select row",checked:i.getIsSelected(),onCheckedChange:X=>{T.toggleAllPageRowsSelected(false),i.toggleSelected(!!X);}}),enableSorting:false,enableHiding:false,size:50},g={id:"select",header:({table:i})=>jsx(o,{className:"fk:dark:bg-white/15","aria-label":"Select all",checked:i.getIsAllPageRowsSelected()||i.getIsSomePageRowsSelected()&&"indeterminate",onCheckedChange:T=>{i.toggleAllPageRowsSelected(!!T);}}),cell:({row:i})=>jsx(o,{"aria-label":"Select row",checked:i.getIsSelected(),onCheckedChange:T=>{i.toggleSelected(!!T);}}),enableSorting:false,enableHiding:false,size:50};return [...t==="single"?[M]:[],...t==="multiple"?[g]:[],...n?[k]:[],...u,S]}export{Xr as a,Kr as b,lt as c,lo as d,po as e,So as f,Tt as g,It as h,_t as i,Vt as j,Re as k,Se as l,Xi as m};//# sourceMappingURL=chunk-3YL7XGH5.js.map
7
+ //# sourceMappingURL=chunk-3YL7XGH5.js.map