aitu-app 0.9.2 → 0.9.3

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 (60) hide show
  1. package/README.md +3 -3
  2. package/assets/{CanvasAudioPlayer-C_USx5uz.js → CanvasAudioPlayer-BKMfe-GO.js} +2 -2
  3. package/assets/{ComicCreator-qGQaXp7h.js → ComicCreator-D5HnnPYu.js} +3 -3
  4. package/assets/DeferredAIInputBar-CVXfAbVO.css +1 -0
  5. package/assets/DeferredAIInputBar-Ce250DxA.js +107 -0
  6. package/assets/{DrawnixDeferredFeatures-Hy_-quZ1.js → DrawnixDeferredFeatures-ue9KjDJ6.js} +2 -2
  7. package/assets/{KnowledgeBaseContent-DSKNA70H.js → KnowledgeBaseContent-YCNU2vP8.js} +5 -5
  8. package/assets/{MVCreator-C3iClDLU.js → MVCreator-uWWF5q7x.js} +4 -4
  9. package/assets/{ModelBenchmarkWorkbench-BxwdcZ0q.js → ModelBenchmarkWorkbench-Bm75hOT0.js} +2 -2
  10. package/assets/{MusicAnalyzer-f_T6_YPJ.js → MusicAnalyzer-BXe6y3_p.js} +1 -1
  11. package/assets/ParametersDropdown-BE58BbHs.css +1 -0
  12. package/assets/{ParametersDropdown-CTSN3ClD.js → ParametersDropdown-wKdOCk_p.js} +1 -1
  13. package/assets/{PromptHistoryTool-DV-8RSdz.js → PromptHistoryTool-BRMlnlE1.js} +2 -2
  14. package/assets/{ResizableDivider-CUQBmPpx.js → ResizableDivider-tAq9KErj.js} +1 -1
  15. package/assets/{TaskQueuePanel-CtjY1W4t.js → TaskQueuePanel-D4PA4azU.js} +1 -1
  16. package/assets/{VideoAnalyzer-BBVBSONO.js → VideoAnalyzer-CVqV3zd3.js} +3 -3
  17. package/assets/{VideoAnalyzer-BmAjGvN8.js → VideoAnalyzer-gVfFvd5A.js} +1 -1
  18. package/assets/{ai-chat-BO5vbKZW.js → ai-chat-D_s8vs6j.js} +45 -45
  19. package/assets/{ai-chat-DyV67c_f.css → ai-chat-_KImIteT.css} +1 -1
  20. package/assets/{ai-generation-preferences-service-ZmPTR-wz.js → ai-generation-preferences-service-rBqGBu1Z.js} +1 -1
  21. package/assets/{batch-image-generation-BLBSv-t6.js → batch-image-generation-BHunNwyR.js} +6 -6
  22. package/assets/{diagram-engines-CSzW_-6N.js → diagram-engines-y0JSIEUO.js} +3 -3
  23. package/assets/{editor-engines-C573k8UM.js → editor-engines-Cc9_gvTn.js} +1 -1
  24. package/assets/{index-BT-rxxI3.js → index-BECJnoIM.js} +1 -1
  25. package/assets/{index-jxwTv7c1.js → index-BOOKwIS8.js} +1 -1
  26. package/assets/{index-N8asYyaz.js → index-Co0sFz6V.js} +2 -2
  27. package/assets/{index-IHNaVKGH.js → index-CrsvRs42.js} +1 -1
  28. package/assets/{index-Dw_8lcIi.js → index-Dthb4yKS.js} +1 -1
  29. package/assets/{index.es-BLXvmueB.js → index.es-l6CUS7uC.js} +1 -1
  30. package/assets/{jspdf.es.min-DxWvbkh4.js → jspdf.es.min-vSonSXg8.js} +3 -3
  31. package/assets/{markdown-to-drawnix-BVFYnimo.js → markdown-to-drawnix-CkXxETO6.js} +3 -3
  32. package/assets/{mermaid-to-drawnix-nGs2aeZ7.js → mermaid-to-drawnix-CiiYHL53.js} +3 -3
  33. package/assets/{model-benchmark-launcher-DAWoSySc.js → model-benchmark-launcher-EfxZ9z3O.js} +1 -1
  34. package/assets/{photo-wall-splitter-CCUURzGk.js → photo-wall-splitter-BJ5RLX6n.js} +1 -1
  35. package/assets/{prompt-utils-MF_LILNU.js → prompt-utils-7NlWAivq.js} +1 -1
  36. package/assets/{settings-dialog-Ac7R-_CG.js → settings-dialog-CBNPo-wJ.js} +1 -1
  37. package/assets/{skill-dsl-parser-Do9iAYbB.js → skill-dsl-parser-9CW3IgX7.js} +1 -1
  38. package/assets/{startup-app-CKHrOmQ0.css → startup-app-BJH8E5sr.css} +1 -1
  39. package/assets/{startup-app-eD_rQhSh.js → startup-app-M6vjXkRC.js} +509 -504
  40. package/assets/{task-sync-BJVOunRa.js → task-sync-B01Tbv7m.js} +1 -1
  41. package/assets/{tool-windows-CmgL3thd.js → tool-windows-Cf62DjP-.js} +21 -21
  42. package/assets/ttd-dialog-O1oaoYry.js +6 -0
  43. package/assets/{ttd-dialog-submit-shortcut-C2lJygXA.js → ttd-dialog-submit-shortcut-rkvbdHF7.js} +1 -1
  44. package/assets/{useCharacters-BAKE4TeJ.js → useCharacters-BVPiqeuF.js} +1 -1
  45. package/assets/{useMediaViewer-BGw5RkSR.js → useMediaViewer-Be0fy5RZ.js} +1 -1
  46. package/assets/{useWorkflowSubmission-iAPmKke9.js → useWorkflowSubmission-BwYRubj-.js} +9 -9
  47. package/assets/{video-recovery-service-CW7bErP2.js → video-recovery-service-CUmfssNZ.js} +1 -1
  48. package/assets/{workflow-generation-utils-DhIVnOHO.js → workflow-generation-utils-362XEGgT.js} +3 -3
  49. package/assets/{workflow-submission-service-Ce0cpj8E.js → workflow-submission-service-Dk47OkGu.js} +2 -2
  50. package/changelog.json +18 -13
  51. package/idle-prefetch-manifest.json +286 -286
  52. package/manifest.json +3 -3
  53. package/package.json +1 -1
  54. package/precache-manifest.json +6 -6
  55. package/sw.js +1 -1
  56. package/version.json +3 -4
  57. package/assets/DeferredAIInputBar-CPykEFYX.css +0 -1
  58. package/assets/DeferredAIInputBar-LmZGQCLT.js +0 -107
  59. package/assets/ParametersDropdown-b2oWAycj.css +0 -1
  60. package/assets/ttd-dialog-B12v0SVY.js +0 -6
@@ -1,7 +1,7 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-CKHrOmQ0.css"])))=>i.map(i=>d[i]);
2
- import{_ as Oe}from"./startup-runtime-DTmhLESk.js";import{r as n,j as e,_ as vs,v as pe,X as je,a0 as Ns,eH as Ve,m as Tt,dq as ye,aK as Ie,$ as De,lM as Cs,lN as Ss,E as G,l as Le,iG as Xe,lO as Ms,lP as qe,lQ as fe,iP as Ae,kH as Rt,lR as be,lS as ve,lT as at,lU as zt,lV as Es,lW as Pt,lX as $t,lY as Ut,ef as se,R as Bt,n as Ye,lZ as Ge,l_ as rt,l$ as _t,m0 as As,m1 as Is,V as Ds,N as Ls,m2 as Ts,eK as Ft,eU as Rs,aF as O,eS as zs,ek as Ps,m3 as $s,aJ as Us,k1 as Bs,gq as Fs,D as it,m4 as Ws,ev as Qe,m5 as Ze,ey as Os,c7 as Te,aH as Wt,er as Ne,m6 as Hs,m7 as Ks,ee as Ot,cu as Vs,eG as Xs,M as q,m8 as Ht,m9 as Kt,ce as qs,av as Ys,al as jt,ba as Gs,az as Je,iQ as Qs,ma as Zs,mb as Js,iO as en,am as tn,y as sn,mc as yt,md as vt,f4 as Vt,j3 as nn,me as an,mf as rn,mg as Nt,iB as on,ew as cn,mh as ln,mi as dn}from"./startup-app-eD_rQhSh.js";import{S as Ct}from"./skill-dsl-parser-Do9iAYbB.js";import{$ as un,a as Xt,b as qt,i as hn,M as mn,c as fn,e as gn,d as pn,f as St,g as bn,C as xn,h as re}from"./editor-engines-C573k8UM.js";import{M as Yt,x as kn,y as wn,z as _n,C as jn,D as yn}from"./tool-windows-CmgL3thd.js";/* empty css */import{V as vn,N as Gt,O as Nn,Q as Cn}from"./ai-chat-BO5vbKZW.js";import"./diagram-engines-CSzW_-6N.js";const ge="__system_skill__";function Sn(t){const s=new Date(t),a=new Date;return s.getFullYear()===a.getFullYear()&&s.getMonth()===a.getMonth()&&s.getDate()===a.getDate()?s.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"}):s.getFullYear()===a.getFullYear()?s.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"}):s.toLocaleDateString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit"})}const Mn=({directories:t,notesByDir:s,noteTagsMap:a,noteCounts:r,selectedDirId:c,selectedNoteId:o,expandedDirIds:d,isCreatingDir:u,skillDirName:p="Skill",onSelectDir:v,onToggleExpand:j,onCreateDir:N,onCancelCreateDir:m,onRenameDir:k,onDeleteDir:l,onSelectNote:S,onCreateNote:b,onDeleteNote:g,onDuplicateDir:z,onDuplicateNote:P,onInsertNoteToCanvas:$})=>{const[H,f]=n.useState(""),[T,F]=n.useState(null),[R,J]=n.useState(""),[W,U]=n.useState(null);n.useEffect(()=>{const w=()=>U(null),B=()=>U(null);return document.addEventListener("click",w),document.addEventListener("scroll",B,!0),()=>{document.removeEventListener("click",w),document.removeEventListener("scroll",B,!0)}},[]);const te=n.useCallback((w,B,_,A=!1)=>{w.preventDefault(),w.stopPropagation(),U({x:w.clientX,y:w.clientY,type:B,id:_,isDefault:A})},[]),y=n.useCallback(async()=>{const w=H.trim();if(w)try{await N(w),f(""),m()}catch{}},[H,N,m]),D=n.useCallback(async w=>{const B=R.trim();if(B)try{await k(w,B),F(null)}catch{}},[R,k]);return e.jsxs("div",{className:"kb-tree",children:[u&&e.jsxs("div",{className:"kb-tree__create-row",children:[e.jsx("input",{className:"kb-tree__input",value:H,onChange:w=>f(w.target.value),onKeyDown:w=>{w.key==="Enter"&&y(),w.key==="Escape"&&m()},placeholder:"目录名称",autoFocus:!0}),e.jsx("button",{className:"kb-tree__icon-btn",onClick:y,children:e.jsx(pe,{size:14})}),e.jsx("button",{className:"kb-tree__icon-btn",onClick:m,children:e.jsx(je,{size:14})})]}),e.jsx("div",{className:"kb-tree__list",children:t.map(w=>e.jsx(En,{dir:w,isSelected:c===w.id,isExpanded:d.has(w.id),notes:s[w.id]||[],noteCount:r[w.id]||0,noteTagsMap:a,selectedNoteId:o,isRenaming:T===w.id,renameValue:R,onSelectDir:()=>{v(w.id),d.has(w.id)||j(w.id)},onToggleExpand:()=>{j(w.id),U(null)},onStartRename:()=>{F(w.id),J(w.name),U(null)},onRenameChange:J,onRenameConfirm:()=>D(w.id),onRenameCancel:()=>F(null),onDeleteDir:()=>{l(w.id),U(null)},onCreateNote:()=>{b(w.id),U(null)},onSelectNote:S,onDeleteNote:B=>{g(B),U(null)},onContextMenu:B=>te(B,"directory",w.id,w.isDefault),onNoteContextMenu:(B,_)=>te(B,"note",_),isSkillDir:w.name===p},w.id))}),W&&vs.createPortal(e.jsx("div",{className:"kb-context-menu",style:{top:W.y,left:W.x,zIndex:Ns.DROPDOWN_PORTAL},onClick:w=>w.stopPropagation(),children:W.type==="directory"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"kb-context-menu__item",onClick:()=>{z(W.id),U(null)},children:[e.jsx(Ve,{size:14}),e.jsx("span",{children:"复制目录"})]}),e.jsxs("div",{className:"kb-context-menu__item",onClick:()=>{var w;F(W.id),J(((w=t.find(B=>B.id===W.id))==null?void 0:w.name)||""),U(null)},children:[e.jsx(Tt,{size:14}),e.jsx("span",{children:"重命名"})]}),e.jsxs("div",{className:"kb-context-menu__item kb-context-menu__item--danger",onClick:()=>{l(W.id),U(null)},children:[e.jsx(ye,{size:14}),e.jsx("span",{children:"删除"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"kb-context-menu__item",onClick:()=>{P(W.id),U(null)},children:[e.jsx(Ve,{size:14}),e.jsx("span",{children:"创建副本"})]}),$&&e.jsxs("div",{className:"kb-context-menu__item",onClick:()=>{const B=Object.values(s).flat().find(_=>_.id===W.id);B&&$(B),U(null)},children:[e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"16"}),e.jsx("line",{x1:"8",y1:"12",x2:"16",y2:"12"})]}),e.jsx("span",{children:"插入到画布"})]}),e.jsxs("div",{className:"kb-context-menu__item kb-context-menu__item--danger",onClick:()=>{g(W.id),U(null)},children:[e.jsx(ye,{size:14}),e.jsx("span",{children:"删除"})]})]})}),document.body)]})},En=({dir:t,isSelected:s,isExpanded:a,notes:r,noteCount:c,noteTagsMap:o,selectedNoteId:d,isRenaming:u,renameValue:p,isSkillDir:v=!1,onSelectDir:j,onToggleExpand:N,onStartRename:m,onRenameChange:k,onRenameConfirm:l,onRenameCancel:S,onDeleteDir:b,onCreateNote:g,onSelectNote:z,onDeleteNote:P,onContextMenu:$,onNoteContextMenu:H})=>e.jsxs("div",{className:`kb-tree__dir ${s?"kb-tree__dir--selected":""}`,children:[e.jsxs("div",{className:"kb-tree__dir-row",onClick:j,onContextMenu:$,children:[e.jsx("button",{className:"kb-tree__expand-btn",onClick:f=>{f.stopPropagation(),N()},children:a?e.jsx(Ie,{size:14}):e.jsx(De,{size:14})}),a?e.jsx(Cs,{size:16}):e.jsx(Ss,{size:16}),u?e.jsx("input",{className:"kb-tree__input kb-tree__input--inline",value:p,onChange:f=>k(f.target.value),onKeyDown:f=>{f.key==="Enter"&&l(),f.key==="Escape"&&S()},onClick:f=>f.stopPropagation(),autoFocus:!0}):e.jsx("span",{className:"kb-tree__dir-name",children:t.name}),e.jsx("span",{className:"kb-tree__dir-count",children:c}),e.jsxs("div",{className:"kb-tree__dir-actions",children:[e.jsx(G,{content:"新建笔记",showArrow:!1,children:e.jsx("button",{className:"kb-tree__icon-btn",onClick:f=>{f.stopPropagation(),g()},children:e.jsx(Le,{size:12})})}),e.jsxs(e.Fragment,{children:[e.jsx(G,{content:"重命名",showArrow:!1,children:e.jsx("button",{className:"kb-tree__icon-btn",onClick:f=>{f.stopPropagation(),m()},children:e.jsx(Tt,{size:12})})}),e.jsx(G,{content:"删除",showArrow:!1,children:e.jsx("button",{className:"kb-tree__icon-btn kb-tree__icon-btn--danger",onClick:f=>{f.stopPropagation(),b()},children:e.jsx(ye,{size:12})})})]})]})]}),a&&e.jsxs("div",{className:"kb-tree__notes",children:[v&&Xe.map(f=>{const T=`${ge}${f.id}`,F=d===T;return e.jsxs("div",{className:`kb-tree__note-row kb-tree__note-row--system ${F?"kb-tree__note-row--selected":""}`,onClick:()=>z(T),children:[e.jsx("div",{className:"kb-tree__note-icon",children:e.jsx(qe,{size:14})}),e.jsx("div",{className:"kb-tree__note-content",children:e.jsxs("div",{className:"kb-tree__note-title",children:[f.name,e.jsx("span",{className:"kb-tree__system-badge",children:"系统"})]})})]},T)}),v&&Ms().map(f=>{const T=`${fe}${f.id}`,F=d===T;return e.jsxs("div",{className:`kb-tree__note-row kb-tree__note-row--system ${F?"kb-tree__note-row--selected":""}`,onClick:()=>z(T),children:[e.jsx("div",{className:"kb-tree__note-icon",children:e.jsx(qe,{size:14})}),e.jsx("div",{className:"kb-tree__note-content",children:e.jsxs("div",{className:"kb-tree__note-title",children:[f.name,e.jsx("span",{className:"kb-tree__system-badge",children:"系统"})]})})]},T)}),r.length===0&&!v&&e.jsx("div",{className:"kb-tree__notes-empty",children:"暂无笔记"}),r.length===0&&v&&Xe.length===0&&e.jsx("div",{className:"kb-tree__notes-empty",children:"暂无笔记"}),Array.from(new Map(r.map(f=>[f.id,f])).values()).map(f=>{const T=d===f.id,F=o[f.id]||[],R=f.metadata;return e.jsx(An,{note:f,isSelected:T,tags:F,metadata:R,onSelect:()=>z(f.id),onDelete:()=>P(f.id),onContextMenu:J=>H(J,f.id)},f.id)})]})]}),An=({note:t,isSelected:s,tags:a,metadata:r,onSelect:c,onDelete:o,onContextMenu:d})=>e.jsxs("div",{className:`kb-tree__note-row ${s?"kb-tree__note-row--selected":""}`,onClick:c,onContextMenu:d,children:[e.jsx("div",{className:"kb-tree__note-icon",children:e.jsx(Ae,{size:14})}),e.jsxs("div",{className:"kb-tree__note-content",children:[e.jsx("div",{className:"kb-tree__note-title",children:t.title||"无标题"}),(r==null?void 0:r.domain)&&e.jsxs("div",{className:"kb-tree__note-domain",children:[r.faviconUrl?e.jsx("img",{src:r.faviconUrl,alt:"",className:"kb-tree__favicon",onError:u=>{u.target.style.display="none"}}):e.jsx(Rt,{size:10}),e.jsx("span",{children:r.domain})]}),e.jsxs("div",{className:"kb-tree__note-meta",children:[a.length>0&&e.jsxs("div",{className:"kb-tree__note-tags",children:[a.slice(0,2).map(u=>e.jsx("span",{className:"kb-tree__tag-badge",style:{backgroundColor:`${u.color}20`,color:u.color},children:u.name},u.id)),a.length>2&&e.jsxs("span",{className:"kb-tree__tag-more",children:["+",a.length-2]})]}),a.length===0&&!(r!=null&&r.domain)&&e.jsx("span",{className:"kb-tree__note-time",children:Sn(t.updatedAt)})]})]}),e.jsx(G,{content:"删除笔记",showArrow:!1,children:e.jsx("button",{className:"kb-tree__note-delete",onClick:u=>{u.stopPropagation(),o()},children:e.jsx(ye,{size:12})})})]});function He(t){const s=t.url;if(!(s!=null&&s.startsWith(be)))return null;const a=s.slice(be.length),r=ve(t.alt||""),c=r.assetType||"image";if(c==="image")return null;const o=at(t.title),d=r.label||"";return{type:"assetEmbed",assetId:a,assetType:c,label:d,width:o.width,height:o.height}}function Qt(t){if(t.children)for(let s=0;s<t.children.length;s++){const a=t.children[s];if(a.type==="image-block"){const r=He(a);if(r){t.children[s]=r;continue}}if(a.type==="paragraph"&&a.children){const r=[],c=[];for(const o of a.children){if(o.type==="image"){const d=He(o);if(d){r.push(d);continue}}c.push(o)}if(r.length>0){const o=[];c.length>0&&o.push({...a,children:c}),o.push(...r),t.children.splice(s,1,...o),s+=o.length-1;continue}}if(a.type==="image"){const r=He(a);if(r){t.children[s]=r;continue}}Qt(a)}}const In=un("remarkAssetEmbed",()=>()=>Qt);function le(t){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return Math.round(t);if(typeof t=="string"&&t.trim()){const s=Number.parseInt(t,10);if(Number.isFinite(s)&&s>0)return s}return null}const et=Xt("assetEmbed",()=>({inline:!1,group:"block",selectable:!0,draggable:!0,atom:!0,attrs:{assetId:{default:""},assetType:{default:"image"},label:{default:""},width:{default:null},height:{default:null}},parseMarkdown:{match:t=>{var s;if(t.type==="assetEmbed")return!0;if(t.type==="image-block"&&((s=t.url)!=null&&s.startsWith(be))){const a=ve(t.alt);if(a.assetType&&a.assetType!=="image")return!0}return!1},runner:(t,s,a)=>{if(s.type==="assetEmbed"){t.addNode(a,{assetId:s.assetId,assetType:s.assetType,label:s.label,width:le(s.width),height:le(s.height)});return}const r=s.url.slice(be.length),c=ve(s.alt),o=at(s.title);t.addNode(a,{assetId:r,assetType:c.assetType||"video",label:c.label||"",width:le(o.width),height:le(o.height)})}},toMarkdown:{match:t=>t.type.name==="assetEmbed",runner:(t,s)=>{const{assetId:a,assetType:r,label:c}=s.attrs,o=c?`${r}|${c}`:r,d=zt({width:le(s.attrs.width),height:le(s.attrs.height)});t.openNode("paragraph"),t.addNode("image",void 0,void 0,{url:`${be}${a}`,alt:o,title:d}),t.closeNode()}},toDOM:t=>["div",{"data-type":"asset-embed","data-asset-id":t.attrs.assetId,"data-asset-type":t.attrs.assetType,"data-label":t.attrs.label,"data-width":t.attrs.width??"","data-height":t.attrs.height??""}],parseDOM:[{tag:'div[data-type="asset-embed"]',getAttrs:t=>({assetId:t.getAttribute("data-asset-id")||"",assetType:t.getAttribute("data-asset-type")||"image",label:t.getAttribute("data-label")||"",width:le(t.getAttribute("data-width")),height:le(t.getAttribute("data-height"))})}]})),Dn=({asset:t,style:s})=>{const a=n.useMemo(()=>({id:`markdown-audio-${t.id}`,type:"audio",points:[[0,0],[340,128]],children:[],audioUrl:t.url,title:t.name,previewImageUrl:t.thumbnail,prompt:t.prompt,createdAt:t.createdAt}),[t]),r=n.useMemo(()=>[{elementId:a.id,audioUrl:t.url,title:t.name,previewImageUrl:t.thumbnail}],[t.name,t.thumbnail,t.url,a.id]);return e.jsx("div",{className:"collimind-markdown-audio-card",style:s,children:e.jsx(Es,{element:a,selected:!1,canvasQueue:r})})};function ae(t,s,a){return Math.min(Math.max(t,s),a)}function Re(t){if(!(typeof t!="number"||!Number.isFinite(t)||t<=0))return Math.round(t)}function ze(t,s,a){let r=ae(t,a.minWidth,a.maxWidth),c=r/s;return(c<a.minHeight||c>a.maxHeight)&&(c=ae(c,a.minHeight,a.maxHeight),r=c*s),{width:ae(r,a.minWidth,a.maxWidth),height:ae(c,a.minHeight,a.maxHeight)}}function Pe(t,s,a){let r=ae(t,a.minHeight,a.maxHeight),c=r*s;return(c<a.minWidth||c>a.maxWidth)&&(c=ae(c,a.minWidth,a.maxWidth),r=c/s),{width:ae(c,a.minWidth,a.maxWidth),height:ae(r,a.minHeight,a.maxHeight)}}const tt=Math.round(rt*1.15);function Mt(t){return ae(Math.round(t*rt/Ge),96,tt)}const Ln=({assetId:t,assetType:s,label:a,width:r,height:c,selected:o,readonly:d,updateAttrs:u})=>{const p=n.useSyncExternalStore($t,Ut),v=p.get(t),j=n.useRef(null),[N,m]=n.useState(null);n.useEffect(()=>{m(null)},[r,c]);const k=(N==null?void 0:N.width)??Re(r),l=(N==null?void 0:N.height)??Re(c),S=k??Ge,b=Mt(S),g=s===se.AUDIO&&typeof l=="number"&&(l>240||l>S*.75),z=s===se.AUDIO?ae(g?b:l??b,96,tt):l,P=n.useMemo(()=>{const f={};return k?f.width=`${k}px`:s===se.AUDIO?f.width="min(100%, 560px)":f.maxWidth=s===se.AUDIO?"min(100%, 560px)":"min(100%, 520px)",s===se.AUDIO?f.height=`${z}px`:l&&(f.height=`${l}px`),f},[s,l,k,z]),$=n.useCallback(f=>T=>{if(d)return;const F=j.current;if(!F)return;T.preventDefault(),T.stopPropagation();const R=F.getBoundingClientRect();if(!R.width||!R.height)return;const J=F.closest(".ProseMirror"),W=Math.max(160,((J==null?void 0:J.getBoundingClientRect().width)??R.width)-32),U=s===se.AUDIO?tt:1600,te=120,y=s===se.AUDIO?96:80,D={x:T.clientX,y:T.clientY,width:R.width,height:R.height};let w={width:Math.round(R.width),height:Math.round(R.height)};const B=A=>{const L=A.clientX-D.x,V=A.clientY-D.y,E=s!==se.AUDIO&&A.shiftKey&&D.width>0&&D.height>0,Y=f==="bottom"?D.width:ae(D.width+L,te,W),Q=f==="right"?D.height:ae(D.height+V,y,U);if(s===se.AUDIO){const Z=f==="bottom"?ae(Math.round(Q*(Ge/rt)),120,W):Math.round(Y),ie=Mt(Z);w={width:Z,height:ie},m(w);return}if(E){const Z=D.width/D.height,ie={minWidth:te,maxWidth:W,minHeight:y,maxHeight:U};if(f==="right")w=ze(Y,Z,ie);else if(f==="bottom")w=Pe(Q,Z,ie);else{const Ce=Y/D.width,xe=Q/D.height;w=Math.abs(Ce-1)>=Math.abs(xe-1)?ze(Y,Z,ie):Pe(Q,Z,ie)}w={width:Math.round(w.width),height:Math.round(w.height)},m(w);return}w={width:Math.round(Y),height:Math.round(Q)},m(w)},_=()=>{document.removeEventListener("pointermove",B),document.removeEventListener("pointerup",_),m(w),u({width:w.width,height:w.height})};document.addEventListener("pointermove",B),document.addEventListener("pointerup",_,{once:!0})},[s,d,u]),H=(f,T)=>e.jsxs("div",{className:`collimind-asset-embed__shell ${o?"is-selected":""}`,"data-asset-type":s,"data-asset-id":t,children:[e.jsxs("div",{ref:j,className:"collimind-asset-embed__frame",style:P,children:[f,!d&&o&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button","data-resize-handle":"right",className:"collimind-asset-embed__handle collimind-asset-embed__handle--right",onPointerDown:$("right"),"aria-label":`调整${s===se.AUDIO?"音频":"视频"}宽度`}),e.jsx("button",{type:"button","data-resize-handle":"bottom",className:"collimind-asset-embed__handle collimind-asset-embed__handle--bottom",onPointerDown:$("bottom"),"aria-label":`调整${s===se.AUDIO?"音频":"视频"}高度`}),e.jsx("button",{type:"button","data-resize-handle":"corner",className:"collimind-asset-embed__handle collimind-asset-embed__handle--corner",onPointerDown:$("corner"),"aria-label":`同时调整${s===se.AUDIO?"音频":"视频"}宽高`})]})]}),T&&e.jsx("div",{className:"collimind-asset-embed__caption",children:T})]});return v?v.type===se.IMAGE?e.jsx(Bt,{className:"collimind-asset-embed__image",src:Ye(v.url),alt:a||v.name||"素材图片",showSkeleton:!1,eager:!0}):v.type===se.VIDEO?H(e.jsx("div",{className:"collimind-asset-embed__video-wrap",children:e.jsx(vn,{className:"collimind-asset-embed__video",src:v.url,poster:v.thumbnail,alt:a||v.name||"素材视频",thumbnailSize:"large",activateVideoOnClick:!0,playOnActivate:!0,videoProps:{controls:!0,preload:"metadata",playsInline:!0}})}),a||v.name):v.type===se.AUDIO?H(e.jsx(Dn,{asset:v,style:{width:"100%",maxHeight:"100%"}}),a||v.name):null:p.size===0?e.jsx("div",{className:"collimind-asset-embed__loading",style:P}):e.jsxs("div",{className:"collimind-asset-embed__missing",style:P,children:["素材不存在或已删除 (",t.slice(0,8),"…)"]})},Tn=qt(et.node,()=>(t,s,a)=>{const r=document.createElement("div");r.className="collimind-asset-embed",r.setAttribute("data-asset-id",t.attrs.assetId);let c=t,o=!1,d=Pt.createRoot(r);const u=v=>{if(!s.editable)return;const j=a();j!=null&&s.dispatch(s.state.tr.setNodeMarkup(j,void 0,{...c.attrs,...v}))},p=()=>{d==null||d.render(e.jsx(Ln,{assetId:c.attrs.assetId,assetType:c.attrs.assetType,label:c.attrs.label,width:c.attrs.width??null,height:c.attrs.height??null,selected:o,readonly:!s.editable,updateAttrs:u}))};return p(),{dom:r,update:v=>v.type!==t.type?!1:(c=v,p(),!0),stopEvent:v=>{const j=v.target;return j instanceof HTMLElement?!!j.closest("[data-resize-handle]"):!1},selectNode:()=>{o=!0,r.classList.add("selected"),p()},deselectNode:()=>{o=!1,r.classList.remove("selected"),p()},destroy:()=>{if(d){const v=d;d=null,setTimeout(()=>v.unmount(),0)}}}}),Rn=[In,et.ctx,et.node,Tn].flat();function Ee(t){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return Math.round(t);if(typeof t=="string"&&t.trim()){const s=Number.parseInt(t,10);if(Number.isFinite(s)&&s>0)return s}return null}const st=Xt("image-block",()=>({inline:!1,group:"block",selectable:!0,draggable:!0,isolating:!0,marks:"",atom:!0,priority:100,attrs:{src:{default:""},alt:{default:""},caption:{default:""},ratio:{default:1},width:{default:null},height:{default:null}},parseMarkdown:{match:t=>{var s;if(t.type!=="image-block")return!1;if((s=t.url)!=null&&s.startsWith(be)){const a=ve(t.alt);if(a.assetType&&a.assetType!=="image")return!1}return!0},runner:(t,s,a)=>{const r=typeof s.alt=="string"?s.alt:"",c=at(s.title),o=_t(r)?Number.parseFloat(r):1;t.addNode(a,{src:s.url,alt:_t(r)?"":r,caption:c.caption,ratio:Number.isFinite(o)&&o>0?o:1,width:c.width??null,height:c.height??null})}},toMarkdown:{match:t=>t.type.name==="image-block",runner:(t,s)=>{const a=zt({width:Ee(s.attrs.width),height:Ee(s.attrs.height),caption:s.attrs.caption}),r=s.attrs.alt||(!s.attrs.width&&!s.attrs.height&&s.attrs.ratio&&s.attrs.ratio!==1?`${Number.parseFloat(String(s.attrs.ratio)).toFixed(2)}`:"");t.openNode("paragraph"),t.addNode("image",void 0,void 0,{title:a,url:s.attrs.src,alt:r}),t.closeNode()}},toDOM:t=>["div",{"data-type":"opentu-image-block","data-src":t.attrs.src,"data-alt":t.attrs.alt,"data-caption":t.attrs.caption,"data-ratio":t.attrs.ratio,"data-width":t.attrs.width??"","data-height":t.attrs.height??""}],parseDOM:[{tag:'div[data-type="opentu-image-block"]',getAttrs:t=>({src:t.getAttribute("data-src")||"",alt:t.getAttribute("data-alt")||"",caption:t.getAttribute("data-caption")||"",ratio:Number(t.getAttribute("data-ratio")??1)||1,width:Ee(t.getAttribute("data-width")),height:Ee(t.getAttribute("data-height"))})},{tag:'img[data-type="image-block"]',getAttrs:t=>({src:t.getAttribute("src")||"",alt:"",caption:t.getAttribute("caption")||"",ratio:Number(t.getAttribute("ratio")??1)||1,width:null,height:null})}]}));function zn({attrs:t,readonly:s,config:a,updateAttrs:r}){const c=n.useRef(null),[o,d]=n.useState(t.src||""),[u,p]=n.useState(!1);n.useEffect(()=>{d(t.src||"")},[t.src]);const v=n.useCallback(()=>{r({src:o.trim()})},[o,r]),j=n.useCallback(async N=>{var k;const m=(k=N.target.files)==null?void 0:k[0];if(m)try{const l=await a.onUpload(m);if(!l)return;d(l),r({src:l})}catch(l){console.error("Failed to upload image block file",l)}finally{N.target.value=""}},[a,r]);return e.jsxs("div",{className:"image-edit collimind-markdown-image-block__edit",children:[e.jsx("div",{className:"image-icon",children:a.imageIcon||"🌌"}),e.jsxs("div",{className:`link-importer ${u?"focus":""}`,children:[e.jsx("input",{className:"link-input-area",value:o,disabled:s,onChange:N=>d(N.target.value),onFocus:()=>p(!0),onBlur:()=>p(!1),onKeyDown:N=>{N.key==="Enter"&&(N.preventDefault(),v())}}),!o&&e.jsxs("div",{className:"placeholder",children:[e.jsx("input",{ref:c,className:"hidden",type:"file",accept:"image/*",disabled:s,onChange:j}),e.jsx("button",{type:"button",className:"uploader",disabled:s,onMouseDown:N=>N.preventDefault(),onClick:()=>{var N;return(N=c.current)==null?void 0:N.click()},children:a.uploadButton||"Upload"}),e.jsx("span",{className:"text",children:a.uploadPlaceholderText})]})]}),!!o&&e.jsx("button",{type:"button",className:"confirm",disabled:s,onMouseDown:N=>N.preventDefault(),onClick:v,children:a.confirmButton||"Confirm"})]})}function Pn({attrs:t,selected:s,readonly:a,updateAttrs:r}){const c=n.useRef(null),o=n.useSyncExternalStore($t,Ut),[d,u]=n.useState(null);n.useEffect(()=>{u(null)},[t.width,t.height]);const p=n.useMemo(()=>As(t.src),[t.src]),v=p?o.get(p):void 0,j=n.useMemo(()=>ve(t.alt),[t.alt]),N=p?j.label||(v==null?void 0:v.name)||"素材图片":t.alt||"图片",m=n.useMemo(()=>p?!v||v.type!==se.IMAGE?null:Ye(v.url):Ye(t.src),[v,p,t.src]),k=(d==null?void 0:d.width)??Re(t.width),l=(d==null?void 0:d.height)??Re(t.height),S=n.useMemo(()=>{const z={};return k?z.width=`${k}px`:z.maxWidth="min(100%, 420px)",l&&(z.height=`${l}px`),z},[l,k]),b=n.useMemo(()=>k&&l?{width:"100%",height:"100%",objectFit:"fill"}:k?{width:"100%",height:"auto"}:l?{width:"auto",height:"100%"}:{width:"100%",height:"auto"},[l,k]),g=n.useCallback(z=>P=>{if(a)return;const $=c.current;if(!$)return;P.preventDefault(),P.stopPropagation();const H=$.getBoundingClientRect();if(!H.width||!H.height)return;const f=$.closest(".ProseMirror"),T=Math.max(120,((f==null?void 0:f.getBoundingClientRect().width)??H.width)-32),F=80,R=80,J=1600,W={x:P.clientX,y:P.clientY,width:H.width,height:H.height};let U={width:Math.round(H.width),height:Math.round(H.height)};const te=D=>{const w=D.clientX-W.x,B=D.clientY-W.y,_=D.shiftKey&&W.width>0&&W.height>0,A=z==="bottom"?W.width:ae(W.width+w,F,T),L=z==="right"?W.height:ae(W.height+B,R,J);if(_){const V=W.width/W.height,E={minWidth:F,maxWidth:T,minHeight:R,maxHeight:J};if(z==="right")U=ze(A,V,E);else if(z==="bottom")U=Pe(L,V,E);else{const Y=A/W.width,Q=L/W.height;U=Math.abs(Y-1)>=Math.abs(Q-1)?ze(A,V,E):Pe(L,V,E)}U={width:Math.round(U.width),height:Math.round(U.height)},u(U);return}U={width:Math.round(A),height:Math.round(L)},u(U)},y=()=>{document.removeEventListener("pointermove",te),document.removeEventListener("pointerup",y),u(U),r({width:U.width,height:U.height})};document.addEventListener("pointermove",te),document.addEventListener("pointerup",y,{once:!0})},[a,r]);return p&&!v&&o.size===0?e.jsx("div",{className:"collimind-markdown-image-block__loading"}):m?e.jsxs("div",{className:`collimind-markdown-image-block__shell ${s?"is-selected":""}`,"data-asset-id":p||void 0,children:[e.jsxs("div",{ref:c,className:"collimind-markdown-image-block__frame",style:S,children:[e.jsx(Bt,{className:"collimind-markdown-image-block__image",src:m,alt:N,draggable:!1,style:b,showSkeleton:!1,eager:!0}),!a&&s&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button","data-resize-handle":"right",className:"collimind-markdown-image-block__handle collimind-markdown-image-block__handle--right",onPointerDown:g("right"),"aria-label":"调整图片宽度"}),e.jsx("button",{type:"button","data-resize-handle":"bottom",className:"collimind-markdown-image-block__handle collimind-markdown-image-block__handle--bottom",onPointerDown:g("bottom"),"aria-label":"调整图片高度"}),e.jsx("button",{type:"button","data-resize-handle":"corner",className:"collimind-markdown-image-block__handle collimind-markdown-image-block__handle--corner",onPointerDown:g("corner"),"aria-label":"同时调整图片宽高"})]})]}),t.caption&&e.jsx("div",{className:"collimind-markdown-image-block__caption",children:t.caption})]}):e.jsx("div",{className:"collimind-markdown-image-block__missing",children:p?`图片素材不存在或已删除 (${p.slice(0,8)}…)`:"图片地址无效"})}function $n(t){return t.attrs.src?e.jsx(Pn,{...t}):e.jsx(zn,{...t})}const Un=qt(st.node,t=>{const s=t.get(hn.key);return(a,r,c)=>{const o=document.createElement("div");o.className="milkdown-image-block collimind-markdown-image-block",o.draggable=!0;let d=a,u=!1,p=Pt.createRoot(o);const v=m=>{if(!r.editable)return;const k=c();k!=null&&r.dispatch(r.state.tr.setNodeMarkup(k,void 0,{...d.attrs,...m}))},j=()=>{p==null||p.render(e.jsx($n,{attrs:d.attrs,selected:u,readonly:!r.editable,config:s,updateAttrs:v}))};j();const N=m=>{var l;const k=(l=m.detail)==null?void 0:l.src;k&&typeof k=="string"&&v({src:k})};return o.addEventListener("asset-commit",N),{dom:o,update:m=>m.type!==a.type?!1:(d=m,j(),!0),stopEvent:m=>{const k=m.target;return k instanceof HTMLElement?!!(k.closest(".image-edit")||k.closest("[data-resize-handle]")):!1},selectNode:()=>{u=!0,o.classList.add("selected"),j()},deselectNode:()=>{u=!1,o.classList.remove("selected"),j()},destroy:()=>{if(o.removeEventListener("asset-commit",N),p){const m=p;p=null,setTimeout(()=>m.unmount(),0)}}}}}),Bn=[st.ctx,st.node,Un].flat();function Ke(t){return new Promise((s,a)=>{const r=new FileReader;r.onload=()=>s(typeof r.result=="string"?r.result:""),r.onerror=()=>a(r.error),r.readAsDataURL(t)})}function Fn({markdown:t,onChange:s,placeholder:a,readOnly:r,editorRef:c,enableAssetEmbeds:o}){const d=n.useRef(s);n.useEffect(()=>{d.current=s},[s]);const u=n.useRef(t),p=n.useRef(null),v=n.useRef(null),j=n.useRef(null),{get:N,loading:m}=fn(k=>{const l=new xn({root:k,defaultValue:t,features:{[re.CodeMirror]:!0,[re.ListItem]:!0,[re.LinkTooltip]:!0,[re.Cursor]:!0,[re.ImageBlock]:!0,[re.BlockEdit]:!0,[re.Toolbar]:!0,[re.Placeholder]:!0,[re.Table]:!0,[re.Latex]:!0},featureConfigs:{[re.Placeholder]:{text:a||"开始编辑..."},[re.Cursor]:{color:"#3b82f6",width:4},[re.ImageBlock]:{onUpload:Ke,inlineOnUpload:Ke,blockOnUpload:Ke},[re.Latex]:{katexOptions:{strict:"ignore"}}}});return l.editor.use(Bn),o&&l.editor.use(Rn),d.current&&l.on(S=>{S.markdownUpdated((b,g)=>{if(p.current&&clearTimeout(p.current),g!==u.current){u.current=g;const z=d.current,P=()=>{v.current=null,z==null||z(g)};v.current=P,p.current=setTimeout(P,50)}})}),j.current=l,l},[]);return n.useEffect(()=>{if(m)return;const k=j.current;if(k){if(r)try{k.setReadonly(!0)}catch{}return c.current={getMarkdown:()=>u.current,setMarkdown:l=>{var S;try{u.current=l,(S=k.editor)==null||S.action(St(l))}catch{}},insertMarkdown:l=>{var S;try{(S=k.editor)==null||S.action(pn(l))}catch{}},focus:()=>{var l,S;try{(S=(l=k.editor)==null?void 0:l.ctx.get(gn))==null||S.focus()}catch{}}},()=>{var l;p.current&&(clearTimeout(p.current),p.current=null),(l=v.current)==null||l.call(v),v.current=null,c.current=null}}},[N,r,c,m]),n.useEffect(()=>{if(m)return;const k=j.current;if(k)try{k.setReadonly(!!r)}catch{}},[r,m]),n.useEffect(()=>{var l,S;if(m)return;const k=j.current;if(k)try{const b=u.current;t!==b&&(p.current&&(clearTimeout(p.current),p.current=null),(l=v.current)==null||l.call(v),u.current=t,(S=k.editor)==null||S.action(St(t)))}catch{}},[t,m]),e.jsx(bn,{})}const ot=n.memo(n.forwardRef(function({markdown:s,sourceMarkdown:a,onChange:r,placeholder:c="开始编辑...",readOnly:o=!1,className:d="",showModeSwitch:u=!0,initialMode:p="wysiwyg",enableAssetEmbeds:v=!1,enableAssetLibraryImagePicker:j=!1},N){const m=n.useContext(Is),k=n.useRef(null),l=n.useRef(null),S=n.useRef(null),b=n.useRef(null),[g,z]=n.useState(p),[P,$]=n.useState(a||s),[H,f]=n.useState(!1),[T,F]=n.useState(!1),[R,J]=n.useState(p!=="wysiwyg"),W=n.useRef(a||s),U=j&&!!m;n.useEffect(()=>{W.current=P},[P]),n.useEffect(()=>{if(g!=="wysiwyg"){J(!1);return}let _=0,A=!1;const L=()=>{const V=S.current;if(!A){if(V!=null&&V.isConnected){J(!0);return}_=requestAnimationFrame(L)}};return L(),()=>{A=!0,_&&cancelAnimationFrame(_)}},[g]);const te=n.useCallback(_=>{var A,L;_!==g&&(_==="source"?$(a||((A=k.current)==null?void 0:A.getMarkdown())||s):a||((L=k.current)==null||L.setMarkdown(P),r==null||r(P)),z(_))},[g,s,P,a,r]),y=n.useCallback(_=>{const A=_.target.value;$(A),r==null||r(A)},[r]),D=n.useCallback(_=>{var L,V;if(!_)return;const A=g==="source"?W.current:a||((L=k.current)==null?void 0:L.getMarkdown())||W.current||s;if(g==="source"&&l.current){const E=l.current,Y=E.selectionStart??A.length,Q=E.selectionEnd??A.length,Z=`${A.slice(0,Y)}${_}${A.slice(Q)}`;$(Z),r==null||r(Z),requestAnimationFrame(()=>{E.focus();const ie=Y+_.length;E.setSelectionRange(ie,ie)});return}(V=k.current)==null||V.insertMarkdown(_),requestAnimationFrame(()=>{var Y;const E=(Y=k.current)==null?void 0:Y.getMarkdown();typeof E=="string"&&$(E)})},[s,g,r,a]);n.useImperativeHandle(N,()=>({getMarkdown:()=>{var _;return g==="source"?P:((_=k.current)==null?void 0:_.getMarkdown())||P},setMarkdown:_=>{var A;$(_),(A=k.current)==null||A.setMarkdown(_)},insertMarkdown:D,focus:()=>{var _,A;g==="source"?(_=l.current)==null||_.focus():(A=k.current)==null||A.focus()},getMode:()=>g,setMode:te}),[te,D,g,P]),n.useEffect(()=>{const _=a||s;_!==P&&$(_)},[s,P,a]);const w=n.useCallback(()=>{const _=S.current;if(!_){b.current=null,F(!1);return}const A=_.ownerDocument.activeElement,L=A instanceof HTMLElement?A.closest(".image-edit"):null,V=L&&_.contains(L)?L:_.querySelector(".image-edit");b.current=V??null,F(!!V)},[]),B=n.useCallback((_,A)=>{if(!_)return!1;const L=_.closest(".milkdown-image-block");return L?(L.dispatchEvent(new CustomEvent("asset-commit",{detail:{src:`asset://${A}`}})),!0):!1},[]);return n.useEffect(()=>{if(!U||o||g!=="wysiwyg"||!S.current){b.current=null,F(!1);return}const _=S.current;let A=0;const L=()=>{cancelAnimationFrame(A),A=requestAnimationFrame(w)},V=Y=>{const Q=Y.target;if(!(Q instanceof HTMLElement))return;const Z=Q.closest(".image-edit");if(Z&&_.contains(Z)){b.current=Z,F(!0);return}L()};L(),_.addEventListener("focusin",V),_.addEventListener("click",V,!0);const E=new MutationObserver(L);return E.observe(_,{childList:!0,subtree:!0}),()=>{cancelAnimationFrame(A),E.disconnect(),_.removeEventListener("focusin",V),_.removeEventListener("click",V,!0)}},[U,g,o,w]),e.jsxs("div",{className:`collimind-markdown-editor ${d}`,"data-readonly":o,"data-mode":g,"data-asset-embeds":v,children:[U&&T&&e.jsxs("button",{type:"button",className:"collimind-markdown-image-library-overlay",style:{right:u?68:8},onClick:()=>{w(),b.current&&f(!0)},children:[e.jsx(Ds,{className:"collimind-icon-sm"}),e.jsx("span",{children:"从素材库插图"})]}),u&&e.jsxs("div",{className:"collimind-markdown-editor-mode-switch",children:[e.jsx(G,{content:"所见即所得模式",showArrow:!1,children:e.jsx("button",{type:"button",className:`collimind-markdown-editor-mode-btn ${g==="wysiwyg"?"active":""}`,onClick:()=>te("wysiwyg"),children:e.jsx(Ls,{className:"collimind-icon-sm"})})}),e.jsx(G,{content:"Markdown 源码模式",showArrow:!1,children:e.jsx("button",{type:"button",className:`collimind-markdown-editor-mode-btn ${g==="source"?"active":""}`,onClick:()=>te("source"),children:e.jsx(Ts,{className:"collimind-icon-sm"})})})]}),e.jsx("div",{ref:S,style:{display:g==="wysiwyg"?"contents":"none"},children:R&&e.jsx(mn,{children:e.jsx(Fn,{markdown:s,onChange:r,placeholder:c,readOnly:o,editorRef:k,enableAssetEmbeds:v})})}),g==="source"&&e.jsx("textarea",{ref:l,className:"collimind-markdown-editor-source",value:P,onChange:y,placeholder:c,readOnly:o||!!a,spellCheck:!1}),U&&H&&e.jsx(Yt,{isOpen:H,onClose:()=>{f(!1),w()},mode:Ft.SELECT,filterType:se.IMAGE,onSelect:_=>{var L;const A=b.current??((L=S.current)==null?void 0:L.querySelector(".image-edit"))??null;if(!B(A,_.id)){f(!1);return}f(!1),requestAnimationFrame(w)},selectButtonText:"插入素材库图片"})]})})),Et=({allTags:t,selectedTagIds:s,onSelectedChange:a,onCreateTag:r,showCount:c=!1})=>{const[o,d]=n.useState(!1),[u,p]=n.useState(""),[v,j]=n.useState(!1),N=n.useRef(null);n.useEffect(()=>{if(!o)return;const b=g=>{N.current&&!N.current.contains(g.target)&&(d(!1),j(!1),p(""))};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[o]);const m=n.useCallback(b=>{const g=s.includes(b)?s.filter(z=>z!==b):[...s,b];a(g)},[s,a]),k=n.useCallback((b,g)=>{g.stopPropagation(),a(s.filter(z=>z!==b))},[s,a]),l=n.useCallback(async()=>{const b=u.trim();if(b)try{const g=await r(b);a([...s,g.id]),p(""),j(!1)}catch{}},[u,r,s,a]),S=t.filter(b=>s.includes(b.id));return e.jsxs("div",{className:"kb-tag-selector",ref:N,children:[e.jsxs("div",{className:"kb-tag-selector__selected",children:[S.map(b=>e.jsxs("span",{className:"kb-tag-selector__tag kb-tag-selector__tag--selected",style:{"--tag-color":b.color,borderColor:b.color,backgroundColor:`${b.color}15`},children:[e.jsx("span",{className:"kb-tag-selector__dot",style:{backgroundColor:b.color}}),e.jsx("span",{children:b.name}),e.jsx("button",{className:"kb-tag-selector__remove",onClick:g=>k(b.id,g),children:e.jsx(G,{content:"移除标签",showArrow:!1,children:e.jsx("span",{children:e.jsx(je,{size:11})})})})]},b.id)),e.jsxs("button",{className:"kb-tag-selector__add-btn",onClick:()=>d(b=>!b),children:[e.jsx(Le,{size:13}),e.jsx("span",{children:"标签"})]})]}),o&&e.jsxs("div",{className:"kb-tag-selector__dropdown",children:[e.jsxs("div",{className:"kb-tag-selector__tags",children:[t.length===0&&e.jsx("span",{className:"kb-tag-selector__empty",children:"暂无标签"}),t.map(b=>{const g=s.includes(b.id);return e.jsxs("button",{className:`kb-tag-selector__tag ${g?"kb-tag-selector__tag--selected":""}`,style:{"--tag-color":b.color,borderColor:g?b.color:void 0,backgroundColor:g?`${b.color}15`:void 0},onClick:()=>m(b.id),children:[e.jsx("span",{className:"kb-tag-selector__dot",style:{backgroundColor:b.color}}),e.jsx("span",{children:b.name}),c&&e.jsxs("span",{className:"kb-tag-selector__count",children:["(",b.count,")"]}),g&&e.jsx(je,{size:12})]},b.id)})]}),v?e.jsxs("div",{className:"kb-tag-selector__create",children:[e.jsx("input",{className:"kb-tag-selector__input",value:u,onChange:b=>p(b.target.value),onKeyDown:b=>{b.key==="Enter"&&l(),b.key==="Escape"&&(j(!1),p(""))},placeholder:"标签名称",autoFocus:!0}),e.jsx("button",{className:"kb-tag-selector__create-btn",onClick:l,children:"确定"})]}):e.jsxs("button",{className:"kb-tag-selector__new-btn",onClick:()=>j(!0),children:[e.jsx(Le,{size:13}),e.jsx("span",{children:"新建标签"})]})]})]})},Wn=({outputType:t,onOutputTypeChange:s,readOnly:a=!1})=>e.jsx("div",{className:"mcp-tool-selector",children:e.jsxs("div",{className:"mcp-tool-selector__output-type",children:[e.jsx("span",{className:"mcp-tool-selector__output-type-label",children:"输出类型"}),e.jsx("div",{className:"mcp-tool-selector__output-type-options",children:a?e.jsx("span",{className:"mcp-tool-selector__output-type-value",children:t==="image"?"图片":t==="video"?"视频":t==="audio"?"音频":t==="ppt"?"PPT":"文本"}):e.jsxs(e.Fragment,{children:[e.jsx("button",{className:`mcp-tool-selector__output-type-btn ${!t||t==="text"?"mcp-tool-selector__output-type-btn--active":""}`,onClick:()=>s==null?void 0:s(void 0),children:"文本"}),e.jsx("button",{className:`mcp-tool-selector__output-type-btn ${t==="image"?"mcp-tool-selector__output-type-btn--active":""}`,onClick:()=>s==null?void 0:s("image"),children:"图片"}),e.jsx("button",{className:`mcp-tool-selector__output-type-btn ${t==="video"?"mcp-tool-selector__output-type-btn--active":""}`,onClick:()=>s==null?void 0:s("video"),children:"视频"}),e.jsx("button",{className:`mcp-tool-selector__output-type-btn ${t==="audio"?"mcp-tool-selector__output-type-btn--active":""}`,onClick:()=>s==null?void 0:s("audio"),children:"音频"}),e.jsx("button",{className:`mcp-tool-selector__output-type-btn ${t==="ppt"?"mcp-tool-selector__output-type-btn--active":""}`,onClick:()=>s==null?void 0:s("ppt"),children:"PPT"})]})})]})}),On=({note:t,allTags:s,noteTags:a,readOnly:r=!1,isSkillDirectory:c=!1,onUpdateNote:o,onSetNoteTags:d,onCreateTag:u})=>{var V;const[p,v]=n.useState(""),[j,N]=n.useState(!1),[m,k]=n.useState(!1),[l,S]=n.useState(null),b=n.useRef(null),g=n.useRef(null),z=n.useRef(null),P=n.useRef(null),$=Rs(),H=typeof window<"u"&&"speechSynthesis"in window,f=n.useMemo(()=>a.map(E=>E.id),[a]),[T,F]=n.useState(void 0);n.useEffect(()=>{var E;F(t&&c&&((E=t.metadata)==null?void 0:E.outputType)||void 0)},[t==null?void 0:t.id,c]);const R=t==null?void 0:t.metadata,J=R&&(R.sourceUrl||R.author||R.domain);n.useEffect(()=>{var Y;const E=t?`kb-note:${t.id}`:null;if(g.current&&(clearTimeout(g.current),g.current=null),b.current&&(clearTimeout(b.current),b.current=null),t)if(v(t.title),P.current=t.id,c&&!r){const Q=t.content||"";S(Q.trim()?Ct.isDSLContent(Q):null)}else S(null);else v(""),P.current=null,S(null);$.mediaType==="reading"&&E&&((Y=$.activeReadingSourceId)!=null&&Y.startsWith(E))&&$.stopPlayback()},[t==null?void 0:t.id,c,r]);const W=n.useCallback(E=>{v(E),t&&(g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{o(t.id,{title:E})},500))},[t,o]),U=n.useCallback(E=>{t&&(g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{o(t.id,{content:E})},500),c&&!r&&(b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{E.trim()?S(Ct.isDSLContent(E)):S(null)},500)))},[t,o,c,r]),te=n.useCallback(E=>{if(!t)return;F(E);const Y={...t.metadata,outputType:E};E||delete Y.outputType,O.updateNote(t.id,{metadata:Y})},[t]),y=n.useCallback(E=>{t&&d(t.id,E)},[t,d]),D=n.useCallback(()=>{var Z;if(!t)return;const E=`kb-note:${t.id}`;if($.mediaType==="reading"&&((Z=$.activeReadingSourceId)==null?void 0:Z.startsWith(E))){$.playing?$.pausePlayback():$.resumePlayback();return}const Q=zs({elementId:E,title:t.title||"知识库笔记",content:[t.title,t.content].filter(Boolean).join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-BJH8E5sr.css"])))=>i.map(i=>d[i]);
2
+ import{_ as Oe}from"./startup-runtime-DTmhLESk.js";import{r as n,j as e,_ as vs,v as pe,X as je,a0 as Ns,eH as Ve,m as Tt,dq as ye,aK as Ie,$ as De,lN as Cs,lO as Ss,E as G,l as Le,iH as Xe,lP as Es,lQ as qe,lR as fe,iQ as Ae,kI as Rt,lS as be,lT as ve,lU as at,lV as zt,lW as Ms,lX as Pt,lY as $t,lZ as Ut,ef as se,R as Bt,n as Ye,l_ as Ge,l$ as rt,m0 as _t,m1 as As,m2 as Is,V as Ds,N as Ls,m3 as Ts,eK as Ft,eU as Rs,aF as O,eS as zs,ek as Ps,m4 as $s,aJ as Us,k2 as Bs,gr as Fs,D as it,m5 as Ws,ev as Qe,m6 as Ze,ey as Os,c7 as Te,aH as Wt,er as Ne,m7 as Hs,m8 as Ks,ee as Ot,cu as Vs,eG as Xs,M as q,m9 as Ht,ma as Kt,ce as qs,av as Ys,al as jt,ba as Gs,az as Je,iR as Qs,mb as Zs,mc as Js,iP as en,am as tn,y as sn,md as yt,me as vt,f4 as Vt,j4 as nn,mf as an,mg as rn,mh as Nt,iC as on,ew as cn,mi as ln,mj as dn}from"./startup-app-M6vjXkRC.js";import{S as Ct}from"./skill-dsl-parser-9CW3IgX7.js";import{$ as un,a as Xt,b as qt,i as hn,M as mn,c as fn,e as gn,d as pn,f as St,g as bn,C as xn,h as re}from"./editor-engines-Cc9_gvTn.js";import{M as Yt,x as kn,y as wn,z as _n,C as jn,D as yn}from"./tool-windows-Cf62DjP-.js";/* empty css */import{V as vn,N as Gt,O as Nn,Q as Cn}from"./ai-chat-D_s8vs6j.js";import"./diagram-engines-y0JSIEUO.js";const ge="__system_skill__";function Sn(t){const s=new Date(t),a=new Date;return s.getFullYear()===a.getFullYear()&&s.getMonth()===a.getMonth()&&s.getDate()===a.getDate()?s.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"}):s.getFullYear()===a.getFullYear()?s.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"}):s.toLocaleDateString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit"})}const En=({directories:t,notesByDir:s,noteTagsMap:a,noteCounts:r,selectedDirId:c,selectedNoteId:o,expandedDirIds:d,isCreatingDir:u,skillDirName:p="Skill",onSelectDir:v,onToggleExpand:j,onCreateDir:N,onCancelCreateDir:m,onRenameDir:k,onDeleteDir:l,onSelectNote:S,onCreateNote:b,onDeleteNote:g,onDuplicateDir:z,onDuplicateNote:P,onInsertNoteToCanvas:$})=>{const[H,f]=n.useState(""),[T,F]=n.useState(null),[R,J]=n.useState(""),[W,U]=n.useState(null);n.useEffect(()=>{const w=()=>U(null),B=()=>U(null);return document.addEventListener("click",w),document.addEventListener("scroll",B,!0),()=>{document.removeEventListener("click",w),document.removeEventListener("scroll",B,!0)}},[]);const te=n.useCallback((w,B,_,A=!1)=>{w.preventDefault(),w.stopPropagation(),U({x:w.clientX,y:w.clientY,type:B,id:_,isDefault:A})},[]),y=n.useCallback(async()=>{const w=H.trim();if(w)try{await N(w),f(""),m()}catch{}},[H,N,m]),D=n.useCallback(async w=>{const B=R.trim();if(B)try{await k(w,B),F(null)}catch{}},[R,k]);return e.jsxs("div",{className:"kb-tree",children:[u&&e.jsxs("div",{className:"kb-tree__create-row",children:[e.jsx("input",{className:"kb-tree__input",value:H,onChange:w=>f(w.target.value),onKeyDown:w=>{w.key==="Enter"&&y(),w.key==="Escape"&&m()},placeholder:"目录名称",autoFocus:!0}),e.jsx("button",{className:"kb-tree__icon-btn",onClick:y,children:e.jsx(pe,{size:14})}),e.jsx("button",{className:"kb-tree__icon-btn",onClick:m,children:e.jsx(je,{size:14})})]}),e.jsx("div",{className:"kb-tree__list",children:t.map(w=>e.jsx(Mn,{dir:w,isSelected:c===w.id,isExpanded:d.has(w.id),notes:s[w.id]||[],noteCount:r[w.id]||0,noteTagsMap:a,selectedNoteId:o,isRenaming:T===w.id,renameValue:R,onSelectDir:()=>{v(w.id),d.has(w.id)||j(w.id)},onToggleExpand:()=>{j(w.id),U(null)},onStartRename:()=>{F(w.id),J(w.name),U(null)},onRenameChange:J,onRenameConfirm:()=>D(w.id),onRenameCancel:()=>F(null),onDeleteDir:()=>{l(w.id),U(null)},onCreateNote:()=>{b(w.id),U(null)},onSelectNote:S,onDeleteNote:B=>{g(B),U(null)},onContextMenu:B=>te(B,"directory",w.id,w.isDefault),onNoteContextMenu:(B,_)=>te(B,"note",_),isSkillDir:w.name===p},w.id))}),W&&vs.createPortal(e.jsx("div",{className:"kb-context-menu",style:{top:W.y,left:W.x,zIndex:Ns.DROPDOWN_PORTAL},onClick:w=>w.stopPropagation(),children:W.type==="directory"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"kb-context-menu__item",onClick:()=>{z(W.id),U(null)},children:[e.jsx(Ve,{size:14}),e.jsx("span",{children:"复制目录"})]}),e.jsxs("div",{className:"kb-context-menu__item",onClick:()=>{var w;F(W.id),J(((w=t.find(B=>B.id===W.id))==null?void 0:w.name)||""),U(null)},children:[e.jsx(Tt,{size:14}),e.jsx("span",{children:"重命名"})]}),e.jsxs("div",{className:"kb-context-menu__item kb-context-menu__item--danger",onClick:()=>{l(W.id),U(null)},children:[e.jsx(ye,{size:14}),e.jsx("span",{children:"删除"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"kb-context-menu__item",onClick:()=>{P(W.id),U(null)},children:[e.jsx(Ve,{size:14}),e.jsx("span",{children:"创建副本"})]}),$&&e.jsxs("div",{className:"kb-context-menu__item",onClick:()=>{const B=Object.values(s).flat().find(_=>_.id===W.id);B&&$(B),U(null)},children:[e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"16"}),e.jsx("line",{x1:"8",y1:"12",x2:"16",y2:"12"})]}),e.jsx("span",{children:"插入到画布"})]}),e.jsxs("div",{className:"kb-context-menu__item kb-context-menu__item--danger",onClick:()=>{g(W.id),U(null)},children:[e.jsx(ye,{size:14}),e.jsx("span",{children:"删除"})]})]})}),document.body)]})},Mn=({dir:t,isSelected:s,isExpanded:a,notes:r,noteCount:c,noteTagsMap:o,selectedNoteId:d,isRenaming:u,renameValue:p,isSkillDir:v=!1,onSelectDir:j,onToggleExpand:N,onStartRename:m,onRenameChange:k,onRenameConfirm:l,onRenameCancel:S,onDeleteDir:b,onCreateNote:g,onSelectNote:z,onDeleteNote:P,onContextMenu:$,onNoteContextMenu:H})=>e.jsxs("div",{className:`kb-tree__dir ${s?"kb-tree__dir--selected":""}`,children:[e.jsxs("div",{className:"kb-tree__dir-row",onClick:j,onContextMenu:$,children:[e.jsx("button",{className:"kb-tree__expand-btn",onClick:f=>{f.stopPropagation(),N()},children:a?e.jsx(Ie,{size:14}):e.jsx(De,{size:14})}),a?e.jsx(Cs,{size:16}):e.jsx(Ss,{size:16}),u?e.jsx("input",{className:"kb-tree__input kb-tree__input--inline",value:p,onChange:f=>k(f.target.value),onKeyDown:f=>{f.key==="Enter"&&l(),f.key==="Escape"&&S()},onClick:f=>f.stopPropagation(),autoFocus:!0}):e.jsx("span",{className:"kb-tree__dir-name",children:t.name}),e.jsx("span",{className:"kb-tree__dir-count",children:c}),e.jsxs("div",{className:"kb-tree__dir-actions",children:[e.jsx(G,{content:"新建笔记",showArrow:!1,children:e.jsx("button",{className:"kb-tree__icon-btn",onClick:f=>{f.stopPropagation(),g()},children:e.jsx(Le,{size:12})})}),e.jsxs(e.Fragment,{children:[e.jsx(G,{content:"重命名",showArrow:!1,children:e.jsx("button",{className:"kb-tree__icon-btn",onClick:f=>{f.stopPropagation(),m()},children:e.jsx(Tt,{size:12})})}),e.jsx(G,{content:"删除",showArrow:!1,children:e.jsx("button",{className:"kb-tree__icon-btn kb-tree__icon-btn--danger",onClick:f=>{f.stopPropagation(),b()},children:e.jsx(ye,{size:12})})})]})]})]}),a&&e.jsxs("div",{className:"kb-tree__notes",children:[v&&Xe.map(f=>{const T=`${ge}${f.id}`,F=d===T;return e.jsxs("div",{className:`kb-tree__note-row kb-tree__note-row--system ${F?"kb-tree__note-row--selected":""}`,onClick:()=>z(T),children:[e.jsx("div",{className:"kb-tree__note-icon",children:e.jsx(qe,{size:14})}),e.jsx("div",{className:"kb-tree__note-content",children:e.jsxs("div",{className:"kb-tree__note-title",children:[f.name,e.jsx("span",{className:"kb-tree__system-badge",children:"系统"})]})})]},T)}),v&&Es().map(f=>{const T=`${fe}${f.id}`,F=d===T;return e.jsxs("div",{className:`kb-tree__note-row kb-tree__note-row--system ${F?"kb-tree__note-row--selected":""}`,onClick:()=>z(T),children:[e.jsx("div",{className:"kb-tree__note-icon",children:e.jsx(qe,{size:14})}),e.jsx("div",{className:"kb-tree__note-content",children:e.jsxs("div",{className:"kb-tree__note-title",children:[f.name,e.jsx("span",{className:"kb-tree__system-badge",children:"系统"})]})})]},T)}),r.length===0&&!v&&e.jsx("div",{className:"kb-tree__notes-empty",children:"暂无笔记"}),r.length===0&&v&&Xe.length===0&&e.jsx("div",{className:"kb-tree__notes-empty",children:"暂无笔记"}),Array.from(new Map(r.map(f=>[f.id,f])).values()).map(f=>{const T=d===f.id,F=o[f.id]||[],R=f.metadata;return e.jsx(An,{note:f,isSelected:T,tags:F,metadata:R,onSelect:()=>z(f.id),onDelete:()=>P(f.id),onContextMenu:J=>H(J,f.id)},f.id)})]})]}),An=({note:t,isSelected:s,tags:a,metadata:r,onSelect:c,onDelete:o,onContextMenu:d})=>e.jsxs("div",{className:`kb-tree__note-row ${s?"kb-tree__note-row--selected":""}`,onClick:c,onContextMenu:d,children:[e.jsx("div",{className:"kb-tree__note-icon",children:e.jsx(Ae,{size:14})}),e.jsxs("div",{className:"kb-tree__note-content",children:[e.jsx("div",{className:"kb-tree__note-title",children:t.title||"无标题"}),(r==null?void 0:r.domain)&&e.jsxs("div",{className:"kb-tree__note-domain",children:[r.faviconUrl?e.jsx("img",{src:r.faviconUrl,alt:"",className:"kb-tree__favicon",onError:u=>{u.target.style.display="none"}}):e.jsx(Rt,{size:10}),e.jsx("span",{children:r.domain})]}),e.jsxs("div",{className:"kb-tree__note-meta",children:[a.length>0&&e.jsxs("div",{className:"kb-tree__note-tags",children:[a.slice(0,2).map(u=>e.jsx("span",{className:"kb-tree__tag-badge",style:{backgroundColor:`${u.color}20`,color:u.color},children:u.name},u.id)),a.length>2&&e.jsxs("span",{className:"kb-tree__tag-more",children:["+",a.length-2]})]}),a.length===0&&!(r!=null&&r.domain)&&e.jsx("span",{className:"kb-tree__note-time",children:Sn(t.updatedAt)})]})]}),e.jsx(G,{content:"删除笔记",showArrow:!1,children:e.jsx("button",{className:"kb-tree__note-delete",onClick:u=>{u.stopPropagation(),o()},children:e.jsx(ye,{size:12})})})]});function He(t){const s=t.url;if(!(s!=null&&s.startsWith(be)))return null;const a=s.slice(be.length),r=ve(t.alt||""),c=r.assetType||"image";if(c==="image")return null;const o=at(t.title),d=r.label||"";return{type:"assetEmbed",assetId:a,assetType:c,label:d,width:o.width,height:o.height}}function Qt(t){if(t.children)for(let s=0;s<t.children.length;s++){const a=t.children[s];if(a.type==="image-block"){const r=He(a);if(r){t.children[s]=r;continue}}if(a.type==="paragraph"&&a.children){const r=[],c=[];for(const o of a.children){if(o.type==="image"){const d=He(o);if(d){r.push(d);continue}}c.push(o)}if(r.length>0){const o=[];c.length>0&&o.push({...a,children:c}),o.push(...r),t.children.splice(s,1,...o),s+=o.length-1;continue}}if(a.type==="image"){const r=He(a);if(r){t.children[s]=r;continue}}Qt(a)}}const In=un("remarkAssetEmbed",()=>()=>Qt);function le(t){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return Math.round(t);if(typeof t=="string"&&t.trim()){const s=Number.parseInt(t,10);if(Number.isFinite(s)&&s>0)return s}return null}const et=Xt("assetEmbed",()=>({inline:!1,group:"block",selectable:!0,draggable:!0,atom:!0,attrs:{assetId:{default:""},assetType:{default:"image"},label:{default:""},width:{default:null},height:{default:null}},parseMarkdown:{match:t=>{var s;if(t.type==="assetEmbed")return!0;if(t.type==="image-block"&&((s=t.url)!=null&&s.startsWith(be))){const a=ve(t.alt);if(a.assetType&&a.assetType!=="image")return!0}return!1},runner:(t,s,a)=>{if(s.type==="assetEmbed"){t.addNode(a,{assetId:s.assetId,assetType:s.assetType,label:s.label,width:le(s.width),height:le(s.height)});return}const r=s.url.slice(be.length),c=ve(s.alt),o=at(s.title);t.addNode(a,{assetId:r,assetType:c.assetType||"video",label:c.label||"",width:le(o.width),height:le(o.height)})}},toMarkdown:{match:t=>t.type.name==="assetEmbed",runner:(t,s)=>{const{assetId:a,assetType:r,label:c}=s.attrs,o=c?`${r}|${c}`:r,d=zt({width:le(s.attrs.width),height:le(s.attrs.height)});t.openNode("paragraph"),t.addNode("image",void 0,void 0,{url:`${be}${a}`,alt:o,title:d}),t.closeNode()}},toDOM:t=>["div",{"data-type":"asset-embed","data-asset-id":t.attrs.assetId,"data-asset-type":t.attrs.assetType,"data-label":t.attrs.label,"data-width":t.attrs.width??"","data-height":t.attrs.height??""}],parseDOM:[{tag:'div[data-type="asset-embed"]',getAttrs:t=>({assetId:t.getAttribute("data-asset-id")||"",assetType:t.getAttribute("data-asset-type")||"image",label:t.getAttribute("data-label")||"",width:le(t.getAttribute("data-width")),height:le(t.getAttribute("data-height"))})}]})),Dn=({asset:t,style:s})=>{const a=n.useMemo(()=>({id:`markdown-audio-${t.id}`,type:"audio",points:[[0,0],[340,128]],children:[],audioUrl:t.url,title:t.name,previewImageUrl:t.thumbnail,prompt:t.prompt,createdAt:t.createdAt}),[t]),r=n.useMemo(()=>[{elementId:a.id,audioUrl:t.url,title:t.name,previewImageUrl:t.thumbnail}],[t.name,t.thumbnail,t.url,a.id]);return e.jsx("div",{className:"collimind-markdown-audio-card",style:s,children:e.jsx(Ms,{element:a,selected:!1,canvasQueue:r})})};function ae(t,s,a){return Math.min(Math.max(t,s),a)}function Re(t){if(!(typeof t!="number"||!Number.isFinite(t)||t<=0))return Math.round(t)}function ze(t,s,a){let r=ae(t,a.minWidth,a.maxWidth),c=r/s;return(c<a.minHeight||c>a.maxHeight)&&(c=ae(c,a.minHeight,a.maxHeight),r=c*s),{width:ae(r,a.minWidth,a.maxWidth),height:ae(c,a.minHeight,a.maxHeight)}}function Pe(t,s,a){let r=ae(t,a.minHeight,a.maxHeight),c=r*s;return(c<a.minWidth||c>a.maxWidth)&&(c=ae(c,a.minWidth,a.maxWidth),r=c/s),{width:ae(c,a.minWidth,a.maxWidth),height:ae(r,a.minHeight,a.maxHeight)}}const tt=Math.round(rt*1.15);function Et(t){return ae(Math.round(t*rt/Ge),96,tt)}const Ln=({assetId:t,assetType:s,label:a,width:r,height:c,selected:o,readonly:d,updateAttrs:u})=>{const p=n.useSyncExternalStore($t,Ut),v=p.get(t),j=n.useRef(null),[N,m]=n.useState(null);n.useEffect(()=>{m(null)},[r,c]);const k=(N==null?void 0:N.width)??Re(r),l=(N==null?void 0:N.height)??Re(c),S=k??Ge,b=Et(S),g=s===se.AUDIO&&typeof l=="number"&&(l>240||l>S*.75),z=s===se.AUDIO?ae(g?b:l??b,96,tt):l,P=n.useMemo(()=>{const f={};return k?f.width=`${k}px`:s===se.AUDIO?f.width="min(100%, 560px)":f.maxWidth=s===se.AUDIO?"min(100%, 560px)":"min(100%, 520px)",s===se.AUDIO?f.height=`${z}px`:l&&(f.height=`${l}px`),f},[s,l,k,z]),$=n.useCallback(f=>T=>{if(d)return;const F=j.current;if(!F)return;T.preventDefault(),T.stopPropagation();const R=F.getBoundingClientRect();if(!R.width||!R.height)return;const J=F.closest(".ProseMirror"),W=Math.max(160,((J==null?void 0:J.getBoundingClientRect().width)??R.width)-32),U=s===se.AUDIO?tt:1600,te=120,y=s===se.AUDIO?96:80,D={x:T.clientX,y:T.clientY,width:R.width,height:R.height};let w={width:Math.round(R.width),height:Math.round(R.height)};const B=A=>{const L=A.clientX-D.x,V=A.clientY-D.y,M=s!==se.AUDIO&&A.shiftKey&&D.width>0&&D.height>0,Y=f==="bottom"?D.width:ae(D.width+L,te,W),Q=f==="right"?D.height:ae(D.height+V,y,U);if(s===se.AUDIO){const Z=f==="bottom"?ae(Math.round(Q*(Ge/rt)),120,W):Math.round(Y),ie=Et(Z);w={width:Z,height:ie},m(w);return}if(M){const Z=D.width/D.height,ie={minWidth:te,maxWidth:W,minHeight:y,maxHeight:U};if(f==="right")w=ze(Y,Z,ie);else if(f==="bottom")w=Pe(Q,Z,ie);else{const Ce=Y/D.width,xe=Q/D.height;w=Math.abs(Ce-1)>=Math.abs(xe-1)?ze(Y,Z,ie):Pe(Q,Z,ie)}w={width:Math.round(w.width),height:Math.round(w.height)},m(w);return}w={width:Math.round(Y),height:Math.round(Q)},m(w)},_=()=>{document.removeEventListener("pointermove",B),document.removeEventListener("pointerup",_),m(w),u({width:w.width,height:w.height})};document.addEventListener("pointermove",B),document.addEventListener("pointerup",_,{once:!0})},[s,d,u]),H=(f,T)=>e.jsxs("div",{className:`collimind-asset-embed__shell ${o?"is-selected":""}`,"data-asset-type":s,"data-asset-id":t,children:[e.jsxs("div",{ref:j,className:"collimind-asset-embed__frame",style:P,children:[f,!d&&o&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button","data-resize-handle":"right",className:"collimind-asset-embed__handle collimind-asset-embed__handle--right",onPointerDown:$("right"),"aria-label":`调整${s===se.AUDIO?"音频":"视频"}宽度`}),e.jsx("button",{type:"button","data-resize-handle":"bottom",className:"collimind-asset-embed__handle collimind-asset-embed__handle--bottom",onPointerDown:$("bottom"),"aria-label":`调整${s===se.AUDIO?"音频":"视频"}高度`}),e.jsx("button",{type:"button","data-resize-handle":"corner",className:"collimind-asset-embed__handle collimind-asset-embed__handle--corner",onPointerDown:$("corner"),"aria-label":`同时调整${s===se.AUDIO?"音频":"视频"}宽高`})]})]}),T&&e.jsx("div",{className:"collimind-asset-embed__caption",children:T})]});return v?v.type===se.IMAGE?e.jsx(Bt,{className:"collimind-asset-embed__image",src:Ye(v.url),alt:a||v.name||"素材图片",showSkeleton:!1,eager:!0}):v.type===se.VIDEO?H(e.jsx("div",{className:"collimind-asset-embed__video-wrap",children:e.jsx(vn,{className:"collimind-asset-embed__video",src:v.url,poster:v.thumbnail,alt:a||v.name||"素材视频",thumbnailSize:"large",activateVideoOnClick:!0,playOnActivate:!0,videoProps:{controls:!0,preload:"metadata",playsInline:!0}})}),a||v.name):v.type===se.AUDIO?H(e.jsx(Dn,{asset:v,style:{width:"100%",maxHeight:"100%"}}),a||v.name):null:p.size===0?e.jsx("div",{className:"collimind-asset-embed__loading",style:P}):e.jsxs("div",{className:"collimind-asset-embed__missing",style:P,children:["素材不存在或已删除 (",t.slice(0,8),"…)"]})},Tn=qt(et.node,()=>(t,s,a)=>{const r=document.createElement("div");r.className="collimind-asset-embed",r.setAttribute("data-asset-id",t.attrs.assetId);let c=t,o=!1,d=Pt.createRoot(r);const u=v=>{if(!s.editable)return;const j=a();j!=null&&s.dispatch(s.state.tr.setNodeMarkup(j,void 0,{...c.attrs,...v}))},p=()=>{d==null||d.render(e.jsx(Ln,{assetId:c.attrs.assetId,assetType:c.attrs.assetType,label:c.attrs.label,width:c.attrs.width??null,height:c.attrs.height??null,selected:o,readonly:!s.editable,updateAttrs:u}))};return p(),{dom:r,update:v=>v.type!==t.type?!1:(c=v,p(),!0),stopEvent:v=>{const j=v.target;return j instanceof HTMLElement?!!j.closest("[data-resize-handle]"):!1},selectNode:()=>{o=!0,r.classList.add("selected"),p()},deselectNode:()=>{o=!1,r.classList.remove("selected"),p()},destroy:()=>{if(d){const v=d;d=null,setTimeout(()=>v.unmount(),0)}}}}),Rn=[In,et.ctx,et.node,Tn].flat();function Me(t){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return Math.round(t);if(typeof t=="string"&&t.trim()){const s=Number.parseInt(t,10);if(Number.isFinite(s)&&s>0)return s}return null}const st=Xt("image-block",()=>({inline:!1,group:"block",selectable:!0,draggable:!0,isolating:!0,marks:"",atom:!0,priority:100,attrs:{src:{default:""},alt:{default:""},caption:{default:""},ratio:{default:1},width:{default:null},height:{default:null}},parseMarkdown:{match:t=>{var s;if(t.type!=="image-block")return!1;if((s=t.url)!=null&&s.startsWith(be)){const a=ve(t.alt);if(a.assetType&&a.assetType!=="image")return!1}return!0},runner:(t,s,a)=>{const r=typeof s.alt=="string"?s.alt:"",c=at(s.title),o=_t(r)?Number.parseFloat(r):1;t.addNode(a,{src:s.url,alt:_t(r)?"":r,caption:c.caption,ratio:Number.isFinite(o)&&o>0?o:1,width:c.width??null,height:c.height??null})}},toMarkdown:{match:t=>t.type.name==="image-block",runner:(t,s)=>{const a=zt({width:Me(s.attrs.width),height:Me(s.attrs.height),caption:s.attrs.caption}),r=s.attrs.alt||(!s.attrs.width&&!s.attrs.height&&s.attrs.ratio&&s.attrs.ratio!==1?`${Number.parseFloat(String(s.attrs.ratio)).toFixed(2)}`:"");t.openNode("paragraph"),t.addNode("image",void 0,void 0,{title:a,url:s.attrs.src,alt:r}),t.closeNode()}},toDOM:t=>["div",{"data-type":"opentu-image-block","data-src":t.attrs.src,"data-alt":t.attrs.alt,"data-caption":t.attrs.caption,"data-ratio":t.attrs.ratio,"data-width":t.attrs.width??"","data-height":t.attrs.height??""}],parseDOM:[{tag:'div[data-type="opentu-image-block"]',getAttrs:t=>({src:t.getAttribute("data-src")||"",alt:t.getAttribute("data-alt")||"",caption:t.getAttribute("data-caption")||"",ratio:Number(t.getAttribute("data-ratio")??1)||1,width:Me(t.getAttribute("data-width")),height:Me(t.getAttribute("data-height"))})},{tag:'img[data-type="image-block"]',getAttrs:t=>({src:t.getAttribute("src")||"",alt:"",caption:t.getAttribute("caption")||"",ratio:Number(t.getAttribute("ratio")??1)||1,width:null,height:null})}]}));function zn({attrs:t,readonly:s,config:a,updateAttrs:r}){const c=n.useRef(null),[o,d]=n.useState(t.src||""),[u,p]=n.useState(!1);n.useEffect(()=>{d(t.src||"")},[t.src]);const v=n.useCallback(()=>{r({src:o.trim()})},[o,r]),j=n.useCallback(async N=>{var k;const m=(k=N.target.files)==null?void 0:k[0];if(m)try{const l=await a.onUpload(m);if(!l)return;d(l),r({src:l})}catch(l){console.error("Failed to upload image block file",l)}finally{N.target.value=""}},[a,r]);return e.jsxs("div",{className:"image-edit collimind-markdown-image-block__edit",children:[e.jsx("div",{className:"image-icon",children:a.imageIcon||"🌌"}),e.jsxs("div",{className:`link-importer ${u?"focus":""}`,children:[e.jsx("input",{className:"link-input-area",value:o,disabled:s,onChange:N=>d(N.target.value),onFocus:()=>p(!0),onBlur:()=>p(!1),onKeyDown:N=>{N.key==="Enter"&&(N.preventDefault(),v())}}),!o&&e.jsxs("div",{className:"placeholder",children:[e.jsx("input",{ref:c,className:"hidden",type:"file",accept:"image/*",disabled:s,onChange:j}),e.jsx("button",{type:"button",className:"uploader",disabled:s,onMouseDown:N=>N.preventDefault(),onClick:()=>{var N;return(N=c.current)==null?void 0:N.click()},children:a.uploadButton||"Upload"}),e.jsx("span",{className:"text",children:a.uploadPlaceholderText})]})]}),!!o&&e.jsx("button",{type:"button",className:"confirm",disabled:s,onMouseDown:N=>N.preventDefault(),onClick:v,children:a.confirmButton||"Confirm"})]})}function Pn({attrs:t,selected:s,readonly:a,updateAttrs:r}){const c=n.useRef(null),o=n.useSyncExternalStore($t,Ut),[d,u]=n.useState(null);n.useEffect(()=>{u(null)},[t.width,t.height]);const p=n.useMemo(()=>As(t.src),[t.src]),v=p?o.get(p):void 0,j=n.useMemo(()=>ve(t.alt),[t.alt]),N=p?j.label||(v==null?void 0:v.name)||"素材图片":t.alt||"图片",m=n.useMemo(()=>p?!v||v.type!==se.IMAGE?null:Ye(v.url):Ye(t.src),[v,p,t.src]),k=(d==null?void 0:d.width)??Re(t.width),l=(d==null?void 0:d.height)??Re(t.height),S=n.useMemo(()=>{const z={};return k?z.width=`${k}px`:z.maxWidth="min(100%, 420px)",l&&(z.height=`${l}px`),z},[l,k]),b=n.useMemo(()=>k&&l?{width:"100%",height:"100%",objectFit:"fill"}:k?{width:"100%",height:"auto"}:l?{width:"auto",height:"100%"}:{width:"100%",height:"auto"},[l,k]),g=n.useCallback(z=>P=>{if(a)return;const $=c.current;if(!$)return;P.preventDefault(),P.stopPropagation();const H=$.getBoundingClientRect();if(!H.width||!H.height)return;const f=$.closest(".ProseMirror"),T=Math.max(120,((f==null?void 0:f.getBoundingClientRect().width)??H.width)-32),F=80,R=80,J=1600,W={x:P.clientX,y:P.clientY,width:H.width,height:H.height};let U={width:Math.round(H.width),height:Math.round(H.height)};const te=D=>{const w=D.clientX-W.x,B=D.clientY-W.y,_=D.shiftKey&&W.width>0&&W.height>0,A=z==="bottom"?W.width:ae(W.width+w,F,T),L=z==="right"?W.height:ae(W.height+B,R,J);if(_){const V=W.width/W.height,M={minWidth:F,maxWidth:T,minHeight:R,maxHeight:J};if(z==="right")U=ze(A,V,M);else if(z==="bottom")U=Pe(L,V,M);else{const Y=A/W.width,Q=L/W.height;U=Math.abs(Y-1)>=Math.abs(Q-1)?ze(A,V,M):Pe(L,V,M)}U={width:Math.round(U.width),height:Math.round(U.height)},u(U);return}U={width:Math.round(A),height:Math.round(L)},u(U)},y=()=>{document.removeEventListener("pointermove",te),document.removeEventListener("pointerup",y),u(U),r({width:U.width,height:U.height})};document.addEventListener("pointermove",te),document.addEventListener("pointerup",y,{once:!0})},[a,r]);return p&&!v&&o.size===0?e.jsx("div",{className:"collimind-markdown-image-block__loading"}):m?e.jsxs("div",{className:`collimind-markdown-image-block__shell ${s?"is-selected":""}`,"data-asset-id":p||void 0,children:[e.jsxs("div",{ref:c,className:"collimind-markdown-image-block__frame",style:S,children:[e.jsx(Bt,{className:"collimind-markdown-image-block__image",src:m,alt:N,draggable:!1,style:b,showSkeleton:!1,eager:!0}),!a&&s&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button","data-resize-handle":"right",className:"collimind-markdown-image-block__handle collimind-markdown-image-block__handle--right",onPointerDown:g("right"),"aria-label":"调整图片宽度"}),e.jsx("button",{type:"button","data-resize-handle":"bottom",className:"collimind-markdown-image-block__handle collimind-markdown-image-block__handle--bottom",onPointerDown:g("bottom"),"aria-label":"调整图片高度"}),e.jsx("button",{type:"button","data-resize-handle":"corner",className:"collimind-markdown-image-block__handle collimind-markdown-image-block__handle--corner",onPointerDown:g("corner"),"aria-label":"同时调整图片宽高"})]})]}),t.caption&&e.jsx("div",{className:"collimind-markdown-image-block__caption",children:t.caption})]}):e.jsx("div",{className:"collimind-markdown-image-block__missing",children:p?`图片素材不存在或已删除 (${p.slice(0,8)}…)`:"图片地址无效"})}function $n(t){return t.attrs.src?e.jsx(Pn,{...t}):e.jsx(zn,{...t})}const Un=qt(st.node,t=>{const s=t.get(hn.key);return(a,r,c)=>{const o=document.createElement("div");o.className="milkdown-image-block collimind-markdown-image-block",o.draggable=!0;let d=a,u=!1,p=Pt.createRoot(o);const v=m=>{if(!r.editable)return;const k=c();k!=null&&r.dispatch(r.state.tr.setNodeMarkup(k,void 0,{...d.attrs,...m}))},j=()=>{p==null||p.render(e.jsx($n,{attrs:d.attrs,selected:u,readonly:!r.editable,config:s,updateAttrs:v}))};j();const N=m=>{var l;const k=(l=m.detail)==null?void 0:l.src;k&&typeof k=="string"&&v({src:k})};return o.addEventListener("asset-commit",N),{dom:o,update:m=>m.type!==a.type?!1:(d=m,j(),!0),stopEvent:m=>{const k=m.target;return k instanceof HTMLElement?!!(k.closest(".image-edit")||k.closest("[data-resize-handle]")):!1},selectNode:()=>{u=!0,o.classList.add("selected"),j()},deselectNode:()=>{u=!1,o.classList.remove("selected"),j()},destroy:()=>{if(o.removeEventListener("asset-commit",N),p){const m=p;p=null,setTimeout(()=>m.unmount(),0)}}}}}),Bn=[st.ctx,st.node,Un].flat();function Ke(t){return new Promise((s,a)=>{const r=new FileReader;r.onload=()=>s(typeof r.result=="string"?r.result:""),r.onerror=()=>a(r.error),r.readAsDataURL(t)})}function Fn({markdown:t,onChange:s,placeholder:a,readOnly:r,editorRef:c,enableAssetEmbeds:o}){const d=n.useRef(s);n.useEffect(()=>{d.current=s},[s]);const u=n.useRef(t),p=n.useRef(null),v=n.useRef(null),j=n.useRef(null),{get:N,loading:m}=fn(k=>{const l=new xn({root:k,defaultValue:t,features:{[re.CodeMirror]:!0,[re.ListItem]:!0,[re.LinkTooltip]:!0,[re.Cursor]:!0,[re.ImageBlock]:!0,[re.BlockEdit]:!0,[re.Toolbar]:!0,[re.Placeholder]:!0,[re.Table]:!0,[re.Latex]:!0},featureConfigs:{[re.Placeholder]:{text:a||"开始编辑..."},[re.Cursor]:{color:"#3b82f6",width:4},[re.ImageBlock]:{onUpload:Ke,inlineOnUpload:Ke,blockOnUpload:Ke},[re.Latex]:{katexOptions:{strict:"ignore"}}}});return l.editor.use(Bn),o&&l.editor.use(Rn),d.current&&l.on(S=>{S.markdownUpdated((b,g)=>{if(p.current&&clearTimeout(p.current),g!==u.current){u.current=g;const z=d.current,P=()=>{v.current=null,z==null||z(g)};v.current=P,p.current=setTimeout(P,50)}})}),j.current=l,l},[]);return n.useEffect(()=>{if(m)return;const k=j.current;if(k){if(r)try{k.setReadonly(!0)}catch{}return c.current={getMarkdown:()=>u.current,setMarkdown:l=>{var S;try{u.current=l,(S=k.editor)==null||S.action(St(l))}catch{}},insertMarkdown:l=>{var S;try{(S=k.editor)==null||S.action(pn(l))}catch{}},focus:()=>{var l,S;try{(S=(l=k.editor)==null?void 0:l.ctx.get(gn))==null||S.focus()}catch{}}},()=>{var l;p.current&&(clearTimeout(p.current),p.current=null),(l=v.current)==null||l.call(v),v.current=null,c.current=null}}},[N,r,c,m]),n.useEffect(()=>{if(m)return;const k=j.current;if(k)try{k.setReadonly(!!r)}catch{}},[r,m]),n.useEffect(()=>{var l,S;if(m)return;const k=j.current;if(k)try{const b=u.current;t!==b&&(p.current&&(clearTimeout(p.current),p.current=null),(l=v.current)==null||l.call(v),u.current=t,(S=k.editor)==null||S.action(St(t)))}catch{}},[t,m]),e.jsx(bn,{})}const ot=n.memo(n.forwardRef(function({markdown:s,sourceMarkdown:a,onChange:r,placeholder:c="开始编辑...",readOnly:o=!1,className:d="",showModeSwitch:u=!0,initialMode:p="wysiwyg",enableAssetEmbeds:v=!1,enableAssetLibraryImagePicker:j=!1},N){const m=n.useContext(Is),k=n.useRef(null),l=n.useRef(null),S=n.useRef(null),b=n.useRef(null),[g,z]=n.useState(p),[P,$]=n.useState(a||s),[H,f]=n.useState(!1),[T,F]=n.useState(!1),[R,J]=n.useState(p!=="wysiwyg"),W=n.useRef(a||s),U=j&&!!m;n.useEffect(()=>{W.current=P},[P]),n.useEffect(()=>{if(g!=="wysiwyg"){J(!1);return}let _=0,A=!1;const L=()=>{const V=S.current;if(!A){if(V!=null&&V.isConnected){J(!0);return}_=requestAnimationFrame(L)}};return L(),()=>{A=!0,_&&cancelAnimationFrame(_)}},[g]);const te=n.useCallback(_=>{var A,L;_!==g&&(_==="source"?$(a||((A=k.current)==null?void 0:A.getMarkdown())||s):a||((L=k.current)==null||L.setMarkdown(P),r==null||r(P)),z(_))},[g,s,P,a,r]),y=n.useCallback(_=>{const A=_.target.value;$(A),r==null||r(A)},[r]),D=n.useCallback(_=>{var L,V;if(!_)return;const A=g==="source"?W.current:a||((L=k.current)==null?void 0:L.getMarkdown())||W.current||s;if(g==="source"&&l.current){const M=l.current,Y=M.selectionStart??A.length,Q=M.selectionEnd??A.length,Z=`${A.slice(0,Y)}${_}${A.slice(Q)}`;$(Z),r==null||r(Z),requestAnimationFrame(()=>{M.focus();const ie=Y+_.length;M.setSelectionRange(ie,ie)});return}(V=k.current)==null||V.insertMarkdown(_),requestAnimationFrame(()=>{var Y;const M=(Y=k.current)==null?void 0:Y.getMarkdown();typeof M=="string"&&$(M)})},[s,g,r,a]);n.useImperativeHandle(N,()=>({getMarkdown:()=>{var _;return g==="source"?P:((_=k.current)==null?void 0:_.getMarkdown())||P},setMarkdown:_=>{var A;$(_),(A=k.current)==null||A.setMarkdown(_)},insertMarkdown:D,focus:()=>{var _,A;g==="source"?(_=l.current)==null||_.focus():(A=k.current)==null||A.focus()},getMode:()=>g,setMode:te}),[te,D,g,P]),n.useEffect(()=>{const _=a||s;_!==P&&$(_)},[s,P,a]);const w=n.useCallback(()=>{const _=S.current;if(!_){b.current=null,F(!1);return}const A=_.ownerDocument.activeElement,L=A instanceof HTMLElement?A.closest(".image-edit"):null,V=L&&_.contains(L)?L:_.querySelector(".image-edit");b.current=V??null,F(!!V)},[]),B=n.useCallback((_,A)=>{if(!_)return!1;const L=_.closest(".milkdown-image-block");return L?(L.dispatchEvent(new CustomEvent("asset-commit",{detail:{src:`asset://${A}`}})),!0):!1},[]);return n.useEffect(()=>{if(!U||o||g!=="wysiwyg"||!S.current){b.current=null,F(!1);return}const _=S.current;let A=0;const L=()=>{cancelAnimationFrame(A),A=requestAnimationFrame(w)},V=Y=>{const Q=Y.target;if(!(Q instanceof HTMLElement))return;const Z=Q.closest(".image-edit");if(Z&&_.contains(Z)){b.current=Z,F(!0);return}L()};L(),_.addEventListener("focusin",V),_.addEventListener("click",V,!0);const M=new MutationObserver(L);return M.observe(_,{childList:!0,subtree:!0}),()=>{cancelAnimationFrame(A),M.disconnect(),_.removeEventListener("focusin",V),_.removeEventListener("click",V,!0)}},[U,g,o,w]),e.jsxs("div",{className:`collimind-markdown-editor ${d}`,"data-readonly":o,"data-mode":g,"data-asset-embeds":v,children:[U&&T&&e.jsxs("button",{type:"button",className:"collimind-markdown-image-library-overlay",style:{right:u?68:8},onClick:()=>{w(),b.current&&f(!0)},children:[e.jsx(Ds,{className:"collimind-icon-sm"}),e.jsx("span",{children:"从素材库插图"})]}),u&&e.jsxs("div",{className:"collimind-markdown-editor-mode-switch",children:[e.jsx(G,{content:"所见即所得模式",showArrow:!1,children:e.jsx("button",{type:"button",className:`collimind-markdown-editor-mode-btn ${g==="wysiwyg"?"active":""}`,onClick:()=>te("wysiwyg"),children:e.jsx(Ls,{className:"collimind-icon-sm"})})}),e.jsx(G,{content:"Markdown 源码模式",showArrow:!1,children:e.jsx("button",{type:"button",className:`collimind-markdown-editor-mode-btn ${g==="source"?"active":""}`,onClick:()=>te("source"),children:e.jsx(Ts,{className:"collimind-icon-sm"})})})]}),e.jsx("div",{ref:S,style:{display:g==="wysiwyg"?"contents":"none"},children:R&&e.jsx(mn,{children:e.jsx(Fn,{markdown:s,onChange:r,placeholder:c,readOnly:o,editorRef:k,enableAssetEmbeds:v})})}),g==="source"&&e.jsx("textarea",{ref:l,className:"collimind-markdown-editor-source",value:P,onChange:y,placeholder:c,readOnly:o||!!a,spellCheck:!1}),U&&H&&e.jsx(Yt,{isOpen:H,onClose:()=>{f(!1),w()},mode:Ft.SELECT,filterType:se.IMAGE,onSelect:_=>{var L;const A=b.current??((L=S.current)==null?void 0:L.querySelector(".image-edit"))??null;if(!B(A,_.id)){f(!1);return}f(!1),requestAnimationFrame(w)},selectButtonText:"插入素材库图片"})]})})),Mt=({allTags:t,selectedTagIds:s,onSelectedChange:a,onCreateTag:r,showCount:c=!1})=>{const[o,d]=n.useState(!1),[u,p]=n.useState(""),[v,j]=n.useState(!1),N=n.useRef(null);n.useEffect(()=>{if(!o)return;const b=g=>{N.current&&!N.current.contains(g.target)&&(d(!1),j(!1),p(""))};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[o]);const m=n.useCallback(b=>{const g=s.includes(b)?s.filter(z=>z!==b):[...s,b];a(g)},[s,a]),k=n.useCallback((b,g)=>{g.stopPropagation(),a(s.filter(z=>z!==b))},[s,a]),l=n.useCallback(async()=>{const b=u.trim();if(b)try{const g=await r(b);a([...s,g.id]),p(""),j(!1)}catch{}},[u,r,s,a]),S=t.filter(b=>s.includes(b.id));return e.jsxs("div",{className:"kb-tag-selector",ref:N,children:[e.jsxs("div",{className:"kb-tag-selector__selected",children:[S.map(b=>e.jsxs("span",{className:"kb-tag-selector__tag kb-tag-selector__tag--selected",style:{"--tag-color":b.color,borderColor:b.color,backgroundColor:`${b.color}15`},children:[e.jsx("span",{className:"kb-tag-selector__dot",style:{backgroundColor:b.color}}),e.jsx("span",{children:b.name}),e.jsx("button",{className:"kb-tag-selector__remove",onClick:g=>k(b.id,g),children:e.jsx(G,{content:"移除标签",showArrow:!1,children:e.jsx("span",{children:e.jsx(je,{size:11})})})})]},b.id)),e.jsxs("button",{className:"kb-tag-selector__add-btn",onClick:()=>d(b=>!b),children:[e.jsx(Le,{size:13}),e.jsx("span",{children:"标签"})]})]}),o&&e.jsxs("div",{className:"kb-tag-selector__dropdown",children:[e.jsxs("div",{className:"kb-tag-selector__tags",children:[t.length===0&&e.jsx("span",{className:"kb-tag-selector__empty",children:"暂无标签"}),t.map(b=>{const g=s.includes(b.id);return e.jsxs("button",{className:`kb-tag-selector__tag ${g?"kb-tag-selector__tag--selected":""}`,style:{"--tag-color":b.color,borderColor:g?b.color:void 0,backgroundColor:g?`${b.color}15`:void 0},onClick:()=>m(b.id),children:[e.jsx("span",{className:"kb-tag-selector__dot",style:{backgroundColor:b.color}}),e.jsx("span",{children:b.name}),c&&e.jsxs("span",{className:"kb-tag-selector__count",children:["(",b.count,")"]}),g&&e.jsx(je,{size:12})]},b.id)})]}),v?e.jsxs("div",{className:"kb-tag-selector__create",children:[e.jsx("input",{className:"kb-tag-selector__input",value:u,onChange:b=>p(b.target.value),onKeyDown:b=>{b.key==="Enter"&&l(),b.key==="Escape"&&(j(!1),p(""))},placeholder:"标签名称",autoFocus:!0}),e.jsx("button",{className:"kb-tag-selector__create-btn",onClick:l,children:"确定"})]}):e.jsxs("button",{className:"kb-tag-selector__new-btn",onClick:()=>j(!0),children:[e.jsx(Le,{size:13}),e.jsx("span",{children:"新建标签"})]})]})]})},Wn=({outputType:t,onOutputTypeChange:s,readOnly:a=!1})=>e.jsx("div",{className:"mcp-tool-selector",children:e.jsxs("div",{className:"mcp-tool-selector__output-type",children:[e.jsx("span",{className:"mcp-tool-selector__output-type-label",children:"输出类型"}),e.jsx("div",{className:"mcp-tool-selector__output-type-options",children:a?e.jsx("span",{className:"mcp-tool-selector__output-type-value",children:t==="image"?"图片":t==="video"?"视频":t==="audio"?"音频":t==="ppt"?"PPT":"文本"}):e.jsxs(e.Fragment,{children:[e.jsx("button",{className:`mcp-tool-selector__output-type-btn ${!t||t==="text"?"mcp-tool-selector__output-type-btn--active":""}`,onClick:()=>s==null?void 0:s(void 0),children:"文本"}),e.jsx("button",{className:`mcp-tool-selector__output-type-btn ${t==="image"?"mcp-tool-selector__output-type-btn--active":""}`,onClick:()=>s==null?void 0:s("image"),children:"图片"}),e.jsx("button",{className:`mcp-tool-selector__output-type-btn ${t==="video"?"mcp-tool-selector__output-type-btn--active":""}`,onClick:()=>s==null?void 0:s("video"),children:"视频"}),e.jsx("button",{className:`mcp-tool-selector__output-type-btn ${t==="audio"?"mcp-tool-selector__output-type-btn--active":""}`,onClick:()=>s==null?void 0:s("audio"),children:"音频"}),e.jsx("button",{className:`mcp-tool-selector__output-type-btn ${t==="ppt"?"mcp-tool-selector__output-type-btn--active":""}`,onClick:()=>s==null?void 0:s("ppt"),children:"PPT"})]})})]})}),On=({note:t,allTags:s,noteTags:a,readOnly:r=!1,isSkillDirectory:c=!1,onUpdateNote:o,onSetNoteTags:d,onCreateTag:u})=>{var V;const[p,v]=n.useState(""),[j,N]=n.useState(!1),[m,k]=n.useState(!1),[l,S]=n.useState(null),b=n.useRef(null),g=n.useRef(null),z=n.useRef(null),P=n.useRef(null),$=Rs(),H=typeof window<"u"&&"speechSynthesis"in window,f=n.useMemo(()=>a.map(M=>M.id),[a]),[T,F]=n.useState(void 0);n.useEffect(()=>{var M;F(t&&c&&((M=t.metadata)==null?void 0:M.outputType)||void 0)},[t==null?void 0:t.id,c]);const R=t==null?void 0:t.metadata,J=R&&(R.sourceUrl||R.author||R.domain);n.useEffect(()=>{var Y;const M=t?`kb-note:${t.id}`:null;if(g.current&&(clearTimeout(g.current),g.current=null),b.current&&(clearTimeout(b.current),b.current=null),t)if(v(t.title),P.current=t.id,c&&!r){const Q=t.content||"";S(Q.trim()?Ct.isDSLContent(Q):null)}else S(null);else v(""),P.current=null,S(null);$.mediaType==="reading"&&M&&((Y=$.activeReadingSourceId)!=null&&Y.startsWith(M))&&$.stopPlayback()},[t==null?void 0:t.id,c,r]);const W=n.useCallback(M=>{v(M),t&&(g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{o(t.id,{title:M})},500))},[t,o]),U=n.useCallback(M=>{t&&(g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{o(t.id,{content:M})},500),c&&!r&&(b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{M.trim()?S(Ct.isDSLContent(M)):S(null)},500)))},[t,o,c,r]),te=n.useCallback(M=>{if(!t)return;F(M);const Y={...t.metadata,outputType:M};M||delete Y.outputType,O.updateNote(t.id,{metadata:Y})},[t]),y=n.useCallback(M=>{t&&d(t.id,M)},[t,d]),D=n.useCallback(()=>{var Z;if(!t)return;const M=`kb-note:${t.id}`;if($.mediaType==="reading"&&((Z=$.activeReadingSourceId)==null?void 0:Z.startsWith(M))){$.playing?$.pausePlayback():$.resumePlayback();return}const Q=zs({elementId:M,title:t.title||"知识库笔记",content:[t.title,t.content].filter(Boolean).join(`
3
3
 
4
- `),origin:{kind:"kb-note",id:t.id}});Q&&Ps({source:Q,queue:[Q]})},[t,$]),w=n.useCallback(async()=>{if(!t)return;const E=await kn(t.id);if(!E)return;const Y=new Blob([E.content],{type:"text/markdown;charset=utf-8"}),Q=URL.createObjectURL(Y),Z=document.createElement("a");Z.href=Q,Z.download=E.filename,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(Q)},[t]),B=n.useCallback(()=>{r||k(!0)},[r]),_=n.useCallback(E=>{var Y;(Y=z.current)==null||Y.insertMarkdown($s(E)),k(!1)},[]);if(n.useEffect(()=>()=>{g.current&&clearTimeout(g.current),b.current&&clearTimeout(b.current)},[]),!t)return e.jsx("div",{className:"kb-note-editor kb-note-editor--empty",children:e.jsxs("div",{className:"kb-note-editor__placeholder",children:[e.jsx("div",{className:"kb-note-editor__placeholder-icon",children:e.jsx(Us,{size:64,strokeWidth:1})}),e.jsx("h3",{className:"kb-note-editor__placeholder-title",children:"无笔记选中"}),e.jsx("p",{className:"kb-note-editor__placeholder-text",children:"选择左侧的一篇笔记开始编辑,或者创建一个新笔记"})]})});const A=`kb-note:${t.id}`,L=$.mediaType==="reading"&&((V=$.activeReadingSourceId)==null?void 0:V.startsWith(A));return e.jsxs("div",{className:`kb-note-editor ${r?"kb-note-editor--readonly":""}`,children:[r&&e.jsxs("div",{className:"kb-note-editor__readonly-banner",children:[e.jsx(qe,{size:14}),e.jsx("span",{children:"系统内置 Skill,不可修改"})]}),e.jsxs("div",{className:"kb-note-editor__title-row",children:[e.jsx("input",{className:"kb-note-editor__title",value:p,onChange:E=>!r&&W(E.target.value),placeholder:"笔记标题",readOnly:r}),e.jsxs("div",{className:"kb-note-editor__actions",children:[H&&e.jsx(G,{content:L?$.playing?"暂停朗读":"继续朗读":"语音朗读",showArrow:!1,children:e.jsx("button",{className:`kb-note-editor__action-btn ${L?"kb-note-editor__action-btn--active":""}`,onClick:D,children:L&&$.playing?e.jsx(Bs,{size:14}):e.jsx(Fs,{size:14})})}),H&&L&&e.jsx(G,{content:"停止朗读",showArrow:!1,children:e.jsx("button",{className:"kb-note-editor__action-btn kb-note-editor__action-btn--danger",onClick:$.stopPlayback,children:"■"})}),e.jsx(G,{content:"导出 Markdown",showArrow:!1,children:e.jsx("button",{className:"kb-note-editor__action-btn",onClick:w,children:e.jsx(it,{size:14})})}),!r&&e.jsx(G,{content:"插入素材",showArrow:!1,children:e.jsx("button",{className:"kb-note-editor__action-btn",onClick:B,children:e.jsx(Ws,{size:14})})})]})]}),J&&e.jsxs("div",{className:`kb-note-editor__metadata-section ${j?"kb-note-editor__metadata-section--collapsed":""}`,children:[e.jsx(G,{content:j?"展开来源信息":"收起来源信息",showArrow:!1,children:e.jsxs("button",{className:"kb-note-editor__metadata-toggle",onClick:()=>N(!j),children:[j?e.jsx(De,{size:14}):e.jsx(Ie,{size:14}),e.jsx("span",{children:"来源信息"})]})}),j&&e.jsxs("div",{className:"kb-note-editor__metadata-collapsed",children:[R.author&&e.jsxs("span",{className:"kb-note-editor__metadata-collapsed-item",children:[e.jsx(Qe,{size:10}),e.jsx("span",{children:R.author})]}),R.sourceUrl&&e.jsx(G,{content:R.sourceUrl,showArrow:!1,children:e.jsxs("a",{href:R.sourceUrl,target:"_blank",rel:"noopener noreferrer",className:"kb-note-editor__metadata-collapsed-link",onClick:E=>E.stopPropagation(),children:[e.jsx(Ze,{size:10}),e.jsx("span",{children:R.domain||R.sourceUrl})]})})]}),!j&&e.jsxs("div",{className:"kb-note-editor__metadata-body",children:[e.jsx("div",{className:"kb-note-editor__tags",children:e.jsx(Et,{allTags:s,selectedTagIds:f,onSelectedChange:y,onCreateTag:u})}),e.jsxs("div",{className:"kb-note-editor__metadata-info",children:[R.domain&&e.jsxs("span",{className:"kb-note-editor__metadata-item",children:[R.faviconUrl?e.jsx("img",{src:R.faviconUrl,alt:"",className:"kb-note-editor__favicon",onError:E=>{E.currentTarget.style.display="none"}}):e.jsx(Rt,{size:12}),e.jsx("span",{children:R.domain})]}),R.author&&e.jsxs("span",{className:"kb-note-editor__metadata-item",children:[e.jsx(Qe,{size:12}),e.jsx("span",{children:R.author})]}),R.publishedAt&&e.jsxs("span",{className:"kb-note-editor__metadata-item",children:[e.jsx(Os,{size:12}),e.jsx("span",{children:R.publishedAt})]})]}),R.sourceUrl&&e.jsx("a",{href:R.sourceUrl,target:"_blank",rel:"noopener noreferrer",className:"kb-note-editor__source-link",children:R.sourceUrl}),R.description&&e.jsx("p",{className:"kb-note-editor__metadata-desc",children:R.description})]})]}),!J&&e.jsx("div",{className:"kb-note-editor__tags",children:e.jsx(Et,{allTags:s,selectedTagIds:f,onSelectedChange:y,onCreateTag:u})}),c&&e.jsx("div",{className:"kb-note-editor__mcp-tools",children:e.jsx(Wn,{outputType:T,onOutputTypeChange:te,readOnly:r})}),e.jsx("div",{className:"kb-note-editor__content",children:e.jsx(ot,{ref:z,markdown:t.content,onChange:r?void 0:U,placeholder:"开始写点什么...",showModeSwitch:!r,readOnly:r,enableAssetEmbeds:!0,enableAssetLibraryImagePicker:!r,className:"kb-note-markdown"},t.id)}),c&&!r&&l!==null&&e.jsx("div",{className:`kb-note-editor__dsl-status ${l?"kb-note-editor__dsl-status--valid":"kb-note-editor__dsl-status--fallback"}`,children:l?"✓ 已识别为工作流 DSL(正则解析),将直接执行":"⚡ 将由 AI 解析为工作流(大模型解析)"}),m&&e.jsx(Yt,{isOpen:m,onClose:()=>k(!1),mode:Ft.SELECT,onSelect:_,selectButtonText:"插入到笔记"})]})},Hn=({allTags:t,selectedTagIds:s,onSelectedChange:a})=>{const[r,c]=n.useState(""),[o,d]=n.useState(!1),u=n.useMemo(()=>{if(!r)return t;const N=r.toLowerCase();return t.filter(m=>m.name.toLowerCase().includes(N))},[t,r]),p=N=>{const m=s.includes(N)?s.filter(k=>k!==N):[...s,N];a(m)},v=()=>{a([]),d(!1)},j=e.jsxs("div",{className:"kb-filter-dropdown__content",children:[e.jsx("div",{className:"kb-filter-dropdown__search",children:e.jsx(Te,{value:r,onChange:N=>c(N),placeholder:"搜索标签...",prefixIcon:e.jsx(Wt,{size:14}),size:"small",clearable:!0})}),e.jsx("div",{className:"kb-filter-dropdown__list",children:u.length>0?u.map(N=>{const m=s.includes(N.id);return e.jsxs("div",{className:`kb-filter-dropdown__item ${m?"is-selected":""}`,onClick:()=>p(N.id),children:[e.jsx("span",{className:"kb-filter-dropdown__item-dot",style:{backgroundColor:N.color}}),e.jsx("span",{className:"kb-filter-dropdown__item-name",children:N.name}),e.jsxs("span",{className:"kb-filter-dropdown__item-count",children:["(",N.count||0,")"]}),m&&e.jsx(pe,{size:14,className:"kb-filter-dropdown__item-check"})]},N.id)}):e.jsx("div",{className:"kb-filter-dropdown__empty",children:"无匹配标签"})}),s.length>0&&e.jsx("div",{className:"kb-filter-dropdown__footer",children:e.jsxs(Ne,{theme:"default",variant:"text",size:"small",onClick:v,className:"kb-filter-dropdown__clear-btn",children:[e.jsx(je,{size:14,style:{marginRight:4}}),"清除标签过滤"]})})]});return e.jsx(Hs,{content:j,visible:o,onVisibleChange:N=>d(N),trigger:"click",placement:"bottom-left",overlayClassName:"kb-filter-dropdown__popup",children:e.jsxs(Ne,{variant:s.length>0?"base":"outline",theme:s.length>0?"primary":"default",size:"small",className:`kb-filter-trigger ${s.length>0?"is-active":""}`,children:[e.jsx(Ks,{size:14,style:{marginRight:4}}),"标签",s.length>0&&` (${s.length})`]})})},Kn=({visible:t,onClose:s,allTags:a,onCreateTag:r,onUpdateTag:c,onDeleteTag:o,onSelectTag:d})=>{const{confirm:u,confirmDialog:p}=Ot(),[v,j]=n.useState(!1),[N,m]=n.useState(""),[k,l]=n.useState(null),[S,b]=n.useState(""),g=n.useRef(null);n.useEffect(()=>{v&&g.current&&setTimeout(()=>{var f;(f=g.current)==null||f.focus()},100)},[v]);const z=async()=>{if(!N.trim()){j(!1);return}try{await r(N.trim()),m(""),j(!1),q.success("标签创建成功")}catch{q.error("标签创建失败")}},P=async f=>{if(!S.trim()){l(null);return}try{await c(f,S.trim()),l(null),q.success("标签更新成功")}catch{q.error("标签更新失败")}},$=async(f,T)=>{f.stopPropagation();try{const F=a.find(J=>J.id===T);if(!await u({title:"确认删除标签",description:`确定要删除标签「${(F==null?void 0:F.name)||"未命名标签"}」吗?此操作不可撤销。`,confirmText:"删除",cancelText:"取消",danger:!0}))return;await o(T),q.success("标签删除成功")}catch{q.error("标签删除失败")}},H=(f,T)=>{f.stopPropagation(),l(T.id),b(T.name)};return e.jsxs(Vs,{header:"管理标签",visible:t,onClose:s,footer:null,width:400,className:"kb-tag-management-dialog",children:[e.jsxs("div",{className:"kb-tag-list",children:[v?e.jsx("div",{className:"kb-tag-item kb-tag-item--creating",children:e.jsx(Te,{ref:g,value:N,onChange:f=>m(f),onEnter:z,onBlur:z,placeholder:"输入标签名称...",size:"small"})}):e.jsxs("div",{className:"kb-tag-item kb-tag-item--create-btn",onClick:()=>j(!0),children:[e.jsx(Le,{size:16}),e.jsx("span",{children:"新建标签"})]}),a.map(f=>e.jsx("div",{className:"kb-tag-item",onClick:()=>{d&&!k&&(d(f.id),s())},children:k===f.id?e.jsxs("div",{className:"kb-tag-item__editing",onClick:T=>T.stopPropagation(),children:[e.jsx(Te,{value:S,onChange:T=>b(T),onEnter:()=>P(f.id),size:"small",autofocus:!0}),e.jsx(Ne,{shape:"circle",variant:"text",size:"small",onClick:()=>P(f.id),children:e.jsx(pe,{size:14})}),e.jsx(Ne,{shape:"circle",variant:"text",size:"small",onClick:()=>l(null),children:e.jsx(je,{size:14})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"kb-tag-item__dot",style:{backgroundColor:f.color}}),e.jsx("span",{className:"kb-tag-item__name",children:f.name}),e.jsx("span",{className:"kb-tag-item__count",children:f.count?`(${f.count} 个笔记)`:"(0 个笔记)"}),e.jsxs("div",{className:"kb-tag-item__actions",children:[e.jsx(G,{content:"重命名",showArrow:!1,children:e.jsx("button",{className:"kb-tag-item__action-btn",onClick:T=>H(T,f),children:e.jsx(Xs,{size:12})})}),e.jsx(G,{content:"删除",showArrow:!1,children:e.jsx("button",{className:"kb-tag-item__action-btn kb-tag-item__action-btn--delete",onClick:T=>$(T,f.id),children:e.jsx(ye,{size:12})})})]})]})},f.id))]}),p]})},At=10,Vn=({currentNoteId:t,allNotes:s,noteTagsMap:a,onSelectNote:r})=>{const[c,o]=n.useState([]),[d,u]=n.useState(!1),[p,v]=n.useState(!1);n.useEffect(()=>{let l=!1;return(async()=>{try{const b=await Gt().getRelatedNotes(t,At);l||o(b)}catch{l||o([])}})(),()=>{l=!0}},[t]);const j=n.useMemo(()=>s.find(l=>l.id===t),[s,t]),N=n.useMemo(()=>{var S;const l=(S=j==null?void 0:j.metadata)==null?void 0:S.sourceUrl;return l?s.filter(b=>{var g;return b.id!==t&&((g=b==null?void 0:b.metadata)==null?void 0:g.sourceUrl)===l}):[]},[s,t,j]),m=n.useMemo(()=>new Set(N.map(l=>l.id)),[N]),k=n.useMemo(()=>{if(c.length>0){const g=new Set;return c.filter(z=>m.has(z.id)||g.has(z.id)?!1:(g.add(z.id),!0))}const l=a[t]||[],S=new Set(l.map(g=>g.id));if(!j)return[];const b=[];for(const g of s){if(g.id===t||m.has(g.id))continue;const P=(a[g.id]||[]).map(R=>R.id),$=P.filter(R=>S.has(R)).length,H=new Set([...S,...P]).size,f=H>0?$/H:0,T=Xn(j.title,g.title),F=f*.7+T*.3;F>.05&&b.push({id:g.id,title:g.title||"无标题",score:F})}return b.sort((g,z)=>z.score-g.score).slice(0,At)},[c,m,s,t,a,j]);return N.length===0&&k.length===0?null:e.jsxs("div",{className:"kb-related-notes",children:[N.length>0&&e.jsxs("div",{className:"kb-related-notes__section",children:[e.jsxs("button",{className:"kb-related-notes__section-header",onClick:()=>u(!d),children:[d?e.jsx(De,{size:12}):e.jsx(Ie,{size:12}),e.jsx(Ht,{size:12}),e.jsx("span",{children:"相关笔记"}),e.jsx("span",{className:"kb-related-notes__count",children:N.length})]}),!d&&e.jsx("div",{className:"kb-related-notes__list",children:N.map(l=>e.jsxs("div",{className:"kb-related-notes__item",onClick:()=>r(l.id),children:[e.jsx(Ae,{size:12,className:"kb-related-notes__icon"}),e.jsx("span",{className:"kb-related-notes__name",children:l.title||"无标题"}),e.jsx(G,{content:"跳转",showArrow:!1,children:e.jsx("button",{className:"kb-related-notes__goto-btn",onClick:S=>{S.stopPropagation(),r(l.id)},children:e.jsx(Ze,{size:10})})})]},`related-${l.id}`))})]}),k.length>0&&e.jsxs("div",{className:"kb-related-notes__section",children:[e.jsxs("button",{className:"kb-related-notes__section-header",onClick:()=>v(!p),children:[p?e.jsx(De,{size:12}):e.jsx(Ie,{size:12}),e.jsx(Ae,{size:12}),e.jsx("span",{children:"相似笔记"}),e.jsx("span",{className:"kb-related-notes__count",children:k.length})]}),!p&&e.jsx("div",{className:"kb-related-notes__list",children:k.map(l=>{const S="score"in l?l.score:void 0;return e.jsxs("div",{className:"kb-related-notes__item",onClick:()=>r(l.id),children:[e.jsx(Ae,{size:12,className:"kb-related-notes__icon"}),e.jsx("span",{className:"kb-related-notes__name",children:l.title}),S!==void 0&&e.jsxs("span",{className:"kb-related-notes__similarity",children:[Math.round(S*100),"%"]}),e.jsx(G,{content:"跳转",showArrow:!1,children:e.jsx("button",{className:"kb-related-notes__goto-btn",onClick:b=>{b.stopPropagation(),r(l.id)},children:e.jsx(Ze,{size:10})})})]},`similar-${l.id}`)})})]})]})};function Xn(t,s){if(!t||!s)return 0;const a=t.toLowerCase(),r=s.toLowerCase(),c=new Set;for(let p=0;p<a.length-1;p++)c.add(a.substring(p,p+2));const o=new Set;for(let p=0;p<r.length-1;p++)o.add(r.substring(p,p+2));let d=0;for(const p of c)o.has(p)&&d++;const u=c.size+o.size;return u===0?0:2*d/u}const qn=`你是一个专业的知识提取助手,擅长从文本中识别和提取关键知识点。你的任务是分析给定的文本内容,提取出有价值的知识点,并以结构化的 Markdown 格式返回。
4
+ `),origin:{kind:"kb-note",id:t.id}});Q&&Ps({source:Q,queue:[Q]})},[t,$]),w=n.useCallback(async()=>{if(!t)return;const M=await kn(t.id);if(!M)return;const Y=new Blob([M.content],{type:"text/markdown;charset=utf-8"}),Q=URL.createObjectURL(Y),Z=document.createElement("a");Z.href=Q,Z.download=M.filename,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(Q)},[t]),B=n.useCallback(()=>{r||k(!0)},[r]),_=n.useCallback(M=>{var Y;(Y=z.current)==null||Y.insertMarkdown($s(M)),k(!1)},[]);if(n.useEffect(()=>()=>{g.current&&clearTimeout(g.current),b.current&&clearTimeout(b.current)},[]),!t)return e.jsx("div",{className:"kb-note-editor kb-note-editor--empty",children:e.jsxs("div",{className:"kb-note-editor__placeholder",children:[e.jsx("div",{className:"kb-note-editor__placeholder-icon",children:e.jsx(Us,{size:64,strokeWidth:1})}),e.jsx("h3",{className:"kb-note-editor__placeholder-title",children:"无笔记选中"}),e.jsx("p",{className:"kb-note-editor__placeholder-text",children:"选择左侧的一篇笔记开始编辑,或者创建一个新笔记"})]})});const A=`kb-note:${t.id}`,L=$.mediaType==="reading"&&((V=$.activeReadingSourceId)==null?void 0:V.startsWith(A));return e.jsxs("div",{className:`kb-note-editor ${r?"kb-note-editor--readonly":""}`,children:[r&&e.jsxs("div",{className:"kb-note-editor__readonly-banner",children:[e.jsx(qe,{size:14}),e.jsx("span",{children:"系统内置 Skill,不可修改"})]}),e.jsxs("div",{className:"kb-note-editor__title-row",children:[e.jsx("input",{className:"kb-note-editor__title",value:p,onChange:M=>!r&&W(M.target.value),placeholder:"笔记标题",readOnly:r}),e.jsxs("div",{className:"kb-note-editor__actions",children:[H&&e.jsx(G,{content:L?$.playing?"暂停朗读":"继续朗读":"语音朗读",showArrow:!1,children:e.jsx("button",{className:`kb-note-editor__action-btn ${L?"kb-note-editor__action-btn--active":""}`,onClick:D,children:L&&$.playing?e.jsx(Bs,{size:14}):e.jsx(Fs,{size:14})})}),H&&L&&e.jsx(G,{content:"停止朗读",showArrow:!1,children:e.jsx("button",{className:"kb-note-editor__action-btn kb-note-editor__action-btn--danger",onClick:$.stopPlayback,children:"■"})}),e.jsx(G,{content:"导出 Markdown",showArrow:!1,children:e.jsx("button",{className:"kb-note-editor__action-btn",onClick:w,children:e.jsx(it,{size:14})})}),!r&&e.jsx(G,{content:"插入素材",showArrow:!1,children:e.jsx("button",{className:"kb-note-editor__action-btn",onClick:B,children:e.jsx(Ws,{size:14})})})]})]}),J&&e.jsxs("div",{className:`kb-note-editor__metadata-section ${j?"kb-note-editor__metadata-section--collapsed":""}`,children:[e.jsx(G,{content:j?"展开来源信息":"收起来源信息",showArrow:!1,children:e.jsxs("button",{className:"kb-note-editor__metadata-toggle",onClick:()=>N(!j),children:[j?e.jsx(De,{size:14}):e.jsx(Ie,{size:14}),e.jsx("span",{children:"来源信息"})]})}),j&&e.jsxs("div",{className:"kb-note-editor__metadata-collapsed",children:[R.author&&e.jsxs("span",{className:"kb-note-editor__metadata-collapsed-item",children:[e.jsx(Qe,{size:10}),e.jsx("span",{children:R.author})]}),R.sourceUrl&&e.jsx(G,{content:R.sourceUrl,showArrow:!1,children:e.jsxs("a",{href:R.sourceUrl,target:"_blank",rel:"noopener noreferrer",className:"kb-note-editor__metadata-collapsed-link",onClick:M=>M.stopPropagation(),children:[e.jsx(Ze,{size:10}),e.jsx("span",{children:R.domain||R.sourceUrl})]})})]}),!j&&e.jsxs("div",{className:"kb-note-editor__metadata-body",children:[e.jsx("div",{className:"kb-note-editor__tags",children:e.jsx(Mt,{allTags:s,selectedTagIds:f,onSelectedChange:y,onCreateTag:u})}),e.jsxs("div",{className:"kb-note-editor__metadata-info",children:[R.domain&&e.jsxs("span",{className:"kb-note-editor__metadata-item",children:[R.faviconUrl?e.jsx("img",{src:R.faviconUrl,alt:"",className:"kb-note-editor__favicon",onError:M=>{M.currentTarget.style.display="none"}}):e.jsx(Rt,{size:12}),e.jsx("span",{children:R.domain})]}),R.author&&e.jsxs("span",{className:"kb-note-editor__metadata-item",children:[e.jsx(Qe,{size:12}),e.jsx("span",{children:R.author})]}),R.publishedAt&&e.jsxs("span",{className:"kb-note-editor__metadata-item",children:[e.jsx(Os,{size:12}),e.jsx("span",{children:R.publishedAt})]})]}),R.sourceUrl&&e.jsx("a",{href:R.sourceUrl,target:"_blank",rel:"noopener noreferrer",className:"kb-note-editor__source-link",children:R.sourceUrl}),R.description&&e.jsx("p",{className:"kb-note-editor__metadata-desc",children:R.description})]})]}),!J&&e.jsx("div",{className:"kb-note-editor__tags",children:e.jsx(Mt,{allTags:s,selectedTagIds:f,onSelectedChange:y,onCreateTag:u})}),c&&e.jsx("div",{className:"kb-note-editor__mcp-tools",children:e.jsx(Wn,{outputType:T,onOutputTypeChange:te,readOnly:r})}),e.jsx("div",{className:"kb-note-editor__content",children:e.jsx(ot,{ref:z,markdown:t.content,onChange:r?void 0:U,placeholder:"开始写点什么...",showModeSwitch:!r,readOnly:r,enableAssetEmbeds:!0,enableAssetLibraryImagePicker:!r,className:"kb-note-markdown"},t.id)}),c&&!r&&l!==null&&e.jsx("div",{className:`kb-note-editor__dsl-status ${l?"kb-note-editor__dsl-status--valid":"kb-note-editor__dsl-status--fallback"}`,children:l?"✓ 已识别为工作流 DSL(正则解析),将直接执行":"⚡ 将由 AI 解析为工作流(大模型解析)"}),m&&e.jsx(Yt,{isOpen:m,onClose:()=>k(!1),mode:Ft.SELECT,onSelect:_,selectButtonText:"插入到笔记"})]})},Hn=({allTags:t,selectedTagIds:s,onSelectedChange:a})=>{const[r,c]=n.useState(""),[o,d]=n.useState(!1),u=n.useMemo(()=>{if(!r)return t;const N=r.toLowerCase();return t.filter(m=>m.name.toLowerCase().includes(N))},[t,r]),p=N=>{const m=s.includes(N)?s.filter(k=>k!==N):[...s,N];a(m)},v=()=>{a([]),d(!1)},j=e.jsxs("div",{className:"kb-filter-dropdown__content",children:[e.jsx("div",{className:"kb-filter-dropdown__search",children:e.jsx(Te,{value:r,onChange:N=>c(N),placeholder:"搜索标签...",prefixIcon:e.jsx(Wt,{size:14}),size:"small",clearable:!0})}),e.jsx("div",{className:"kb-filter-dropdown__list",children:u.length>0?u.map(N=>{const m=s.includes(N.id);return e.jsxs("div",{className:`kb-filter-dropdown__item ${m?"is-selected":""}`,onClick:()=>p(N.id),children:[e.jsx("span",{className:"kb-filter-dropdown__item-dot",style:{backgroundColor:N.color}}),e.jsx("span",{className:"kb-filter-dropdown__item-name",children:N.name}),e.jsxs("span",{className:"kb-filter-dropdown__item-count",children:["(",N.count||0,")"]}),m&&e.jsx(pe,{size:14,className:"kb-filter-dropdown__item-check"})]},N.id)}):e.jsx("div",{className:"kb-filter-dropdown__empty",children:"无匹配标签"})}),s.length>0&&e.jsx("div",{className:"kb-filter-dropdown__footer",children:e.jsxs(Ne,{theme:"default",variant:"text",size:"small",onClick:v,className:"kb-filter-dropdown__clear-btn",children:[e.jsx(je,{size:14,style:{marginRight:4}}),"清除标签过滤"]})})]});return e.jsx(Hs,{content:j,visible:o,onVisibleChange:N=>d(N),trigger:"click",placement:"bottom-left",overlayClassName:"kb-filter-dropdown__popup",children:e.jsxs(Ne,{variant:s.length>0?"base":"outline",theme:s.length>0?"primary":"default",size:"small",className:`kb-filter-trigger ${s.length>0?"is-active":""}`,children:[e.jsx(Ks,{size:14,style:{marginRight:4}}),"标签",s.length>0&&` (${s.length})`]})})},Kn=({visible:t,onClose:s,allTags:a,onCreateTag:r,onUpdateTag:c,onDeleteTag:o,onSelectTag:d})=>{const{confirm:u,confirmDialog:p}=Ot(),[v,j]=n.useState(!1),[N,m]=n.useState(""),[k,l]=n.useState(null),[S,b]=n.useState(""),g=n.useRef(null);n.useEffect(()=>{v&&g.current&&setTimeout(()=>{var f;(f=g.current)==null||f.focus()},100)},[v]);const z=async()=>{if(!N.trim()){j(!1);return}try{await r(N.trim()),m(""),j(!1),q.success("标签创建成功")}catch{q.error("标签创建失败")}},P=async f=>{if(!S.trim()){l(null);return}try{await c(f,S.trim()),l(null),q.success("标签更新成功")}catch{q.error("标签更新失败")}},$=async(f,T)=>{f.stopPropagation();try{const F=a.find(J=>J.id===T);if(!await u({title:"确认删除标签",description:`确定要删除标签「${(F==null?void 0:F.name)||"未命名标签"}」吗?此操作不可撤销。`,confirmText:"删除",cancelText:"取消",danger:!0}))return;await o(T),q.success("标签删除成功")}catch{q.error("标签删除失败")}},H=(f,T)=>{f.stopPropagation(),l(T.id),b(T.name)};return e.jsxs(Vs,{header:"管理标签",visible:t,onClose:s,footer:null,width:400,className:"kb-tag-management-dialog",children:[e.jsxs("div",{className:"kb-tag-list",children:[v?e.jsx("div",{className:"kb-tag-item kb-tag-item--creating",children:e.jsx(Te,{ref:g,value:N,onChange:f=>m(f),onEnter:z,onBlur:z,placeholder:"输入标签名称...",size:"small"})}):e.jsxs("div",{className:"kb-tag-item kb-tag-item--create-btn",onClick:()=>j(!0),children:[e.jsx(Le,{size:16}),e.jsx("span",{children:"新建标签"})]}),a.map(f=>e.jsx("div",{className:"kb-tag-item",onClick:()=>{d&&!k&&(d(f.id),s())},children:k===f.id?e.jsxs("div",{className:"kb-tag-item__editing",onClick:T=>T.stopPropagation(),children:[e.jsx(Te,{value:S,onChange:T=>b(T),onEnter:()=>P(f.id),size:"small",autofocus:!0}),e.jsx(Ne,{shape:"circle",variant:"text",size:"small",onClick:()=>P(f.id),children:e.jsx(pe,{size:14})}),e.jsx(Ne,{shape:"circle",variant:"text",size:"small",onClick:()=>l(null),children:e.jsx(je,{size:14})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"kb-tag-item__dot",style:{backgroundColor:f.color}}),e.jsx("span",{className:"kb-tag-item__name",children:f.name}),e.jsx("span",{className:"kb-tag-item__count",children:f.count?`(${f.count} 个笔记)`:"(0 个笔记)"}),e.jsxs("div",{className:"kb-tag-item__actions",children:[e.jsx(G,{content:"重命名",showArrow:!1,children:e.jsx("button",{className:"kb-tag-item__action-btn",onClick:T=>H(T,f),children:e.jsx(Xs,{size:12})})}),e.jsx(G,{content:"删除",showArrow:!1,children:e.jsx("button",{className:"kb-tag-item__action-btn kb-tag-item__action-btn--delete",onClick:T=>$(T,f.id),children:e.jsx(ye,{size:12})})})]})]})},f.id))]}),p]})},At=10,Vn=({currentNoteId:t,allNotes:s,noteTagsMap:a,onSelectNote:r})=>{const[c,o]=n.useState([]),[d,u]=n.useState(!1),[p,v]=n.useState(!1);n.useEffect(()=>{let l=!1;return(async()=>{try{const b=await Gt().getRelatedNotes(t,At);l||o(b)}catch{l||o([])}})(),()=>{l=!0}},[t]);const j=n.useMemo(()=>s.find(l=>l.id===t),[s,t]),N=n.useMemo(()=>{var S;const l=(S=j==null?void 0:j.metadata)==null?void 0:S.sourceUrl;return l?s.filter(b=>{var g;return b.id!==t&&((g=b==null?void 0:b.metadata)==null?void 0:g.sourceUrl)===l}):[]},[s,t,j]),m=n.useMemo(()=>new Set(N.map(l=>l.id)),[N]),k=n.useMemo(()=>{if(c.length>0){const g=new Set;return c.filter(z=>m.has(z.id)||g.has(z.id)?!1:(g.add(z.id),!0))}const l=a[t]||[],S=new Set(l.map(g=>g.id));if(!j)return[];const b=[];for(const g of s){if(g.id===t||m.has(g.id))continue;const P=(a[g.id]||[]).map(R=>R.id),$=P.filter(R=>S.has(R)).length,H=new Set([...S,...P]).size,f=H>0?$/H:0,T=Xn(j.title,g.title),F=f*.7+T*.3;F>.05&&b.push({id:g.id,title:g.title||"无标题",score:F})}return b.sort((g,z)=>z.score-g.score).slice(0,At)},[c,m,s,t,a,j]);return N.length===0&&k.length===0?null:e.jsxs("div",{className:"kb-related-notes",children:[N.length>0&&e.jsxs("div",{className:"kb-related-notes__section",children:[e.jsxs("button",{className:"kb-related-notes__section-header",onClick:()=>u(!d),children:[d?e.jsx(De,{size:12}):e.jsx(Ie,{size:12}),e.jsx(Ht,{size:12}),e.jsx("span",{children:"相关笔记"}),e.jsx("span",{className:"kb-related-notes__count",children:N.length})]}),!d&&e.jsx("div",{className:"kb-related-notes__list",children:N.map(l=>e.jsxs("div",{className:"kb-related-notes__item",onClick:()=>r(l.id),children:[e.jsx(Ae,{size:12,className:"kb-related-notes__icon"}),e.jsx("span",{className:"kb-related-notes__name",children:l.title||"无标题"}),e.jsx(G,{content:"跳转",showArrow:!1,children:e.jsx("button",{className:"kb-related-notes__goto-btn",onClick:S=>{S.stopPropagation(),r(l.id)},children:e.jsx(Ze,{size:10})})})]},`related-${l.id}`))})]}),k.length>0&&e.jsxs("div",{className:"kb-related-notes__section",children:[e.jsxs("button",{className:"kb-related-notes__section-header",onClick:()=>v(!p),children:[p?e.jsx(De,{size:12}):e.jsx(Ie,{size:12}),e.jsx(Ae,{size:12}),e.jsx("span",{children:"相似笔记"}),e.jsx("span",{className:"kb-related-notes__count",children:k.length})]}),!p&&e.jsx("div",{className:"kb-related-notes__list",children:k.map(l=>{const S="score"in l?l.score:void 0;return e.jsxs("div",{className:"kb-related-notes__item",onClick:()=>r(l.id),children:[e.jsx(Ae,{size:12,className:"kb-related-notes__icon"}),e.jsx("span",{className:"kb-related-notes__name",children:l.title}),S!==void 0&&e.jsxs("span",{className:"kb-related-notes__similarity",children:[Math.round(S*100),"%"]}),e.jsx(G,{content:"跳转",showArrow:!1,children:e.jsx("button",{className:"kb-related-notes__goto-btn",onClick:b=>{b.stopPropagation(),r(l.id)},children:e.jsx(Ze,{size:10})})})]},`similar-${l.id}`)})})]})]})};function Xn(t,s){if(!t||!s)return 0;const a=t.toLowerCase(),r=s.toLowerCase(),c=new Set;for(let p=0;p<a.length-1;p++)c.add(a.substring(p,p+2));const o=new Set;for(let p=0;p<r.length-1;p++)o.add(r.substring(p,p+2));let d=0;for(const p of c)o.has(p)&&d++;const u=c.size+o.size;return u===0?0:2*d/u}const qn=`你是一个专业的知识提取助手,擅长从文本中识别和提取关键知识点。你的任务是分析给定的文本内容,提取出有价值的知识点,并以结构化的 Markdown 格式返回。
5
5
 
6
6
  提取规则:
7
7
  1. **核心概念**: 文中出现的重要概念、术语及其解释
@@ -48,6 +48,6 @@ ${t}
48
48
  `).trim()}const oa=({noteId:t,noteContent:s,noteTitle:a,onInsertToNote:r,onSaved:c})=>{const o=Ys("text"),[d,u]=n.useState([]),[p,v]=n.useState(""),[j,N]=n.useState(o.modelId||It),[m,k]=n.useState(()=>jt(o.profileId,o.modelId||It)),[l,S]=n.useState(!1),[b,g]=n.useState(null),[z,P]=n.useState(null),$=n.useRef(!1),H=n.useRef(null),f=n.useRef(null);n.useEffect(()=>{let y=!0;return(async()=>{u([]);try{const w=await sa(t);y&&(w&&w.messages.length>0?u(w.messages):u([{id:"init",role:"model",content:"我已经阅读了这篇笔记。你可以让我提取摘要、关键点,或者直接与我讨论笔记内容。",type:"text",timestamp:Date.now()}]))}catch(w){console.error("Failed to load chat history",w)}})(),()=>{y=!1}},[t]),n.useEffect(()=>{d.length>0&&na(t,d).catch(console.error)},[d,t]),n.useEffect(()=>{H.current&&(H.current.scrollTop=H.current.scrollHeight)},[d]),n.useEffect(()=>{f.current&&(f.current.style.height="auto",f.current.style.height=`${Math.min(f.current.scrollHeight,120)}px`)},[p]);const T=n.useCallback(()=>{z&&(ne("stop_generation",{status:"cancelled",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length}),z.abort(),P(null),$.current=!1,S(!1),u(y=>[...y,{id:Date.now().toString(),role:"model",content:"🚫 已停止生成",type:"text",timestamp:Date.now()}]))},[z,s.length,j,m]),F=n.useCallback(async()=>{const y=p.trim();if(!y||$.current||l)return;$.current=!0;const D=Date.now();ne("chat",{status:"start",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length,inputLength:y.length});const w={id:Date.now().toString(),role:"user",content:y,type:"text",timestamp:Date.now()};u(_=>[..._,w]),v(""),S(!0),f.current&&(f.current.style.height="auto");const B=new AbortController;P(B);try{const _=d.concat(w).map(L=>({role:L.role==="model"?"assistant":"user",content:[{type:"text",text:L.content}]}));if(_.length<=2){const L=`Context:
49
49
  ${s}
50
50
 
51
- Task: ${w.content}`,V=_.length-1;_[V].content=[{type:"text",text:L}]}const A=(Date.now()+1).toString();g(A),u(L=>[...L,{id:A,role:"model",content:"正在思考...",type:"text",timestamp:Date.now()}]),await Zn(_,{model:m||j,onProgress:L=>{u(V=>V.map(E=>E.id===A?{...E,content:L}:E))},signal:B.signal}),ne("chat",{status:"success",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length,inputLength:y.length,durationMs:Date.now()-D})}catch(_){_.name!=="AbortError"?(ne("chat",{status:"failed",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length,inputLength:y.length,durationMs:Date.now()-D,error:_.message||"chat_failed"}),u(A=>[...A,{id:Date.now().toString(),role:"model",content:`Error: ${_.message||"Something went wrong"}`,type:"text",timestamp:Date.now()}])):ne("chat",{status:"cancelled",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length,inputLength:y.length,durationMs:Date.now()-D})}finally{$.current=!1,S(!1),P(null),g(null)}},[p,l,d,s,j,m]),R=n.useCallback(async()=>{if($.current||l)return;$.current=!0;const y=Date.now();ne("quick_extract",{status:"start",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length}),S(!0);const D={id:Date.now().toString(),role:"user",content:"提取知识点",type:"text",timestamp:Date.now()};u(_=>[..._,D]);const w=new AbortController;P(w);const B=(Date.now()+1).toString();u(_=>[..._,{id:B,role:"model",content:"正在分析笔记内容并提取知识点...",type:"text",timestamp:Date.now()}]);try{const _=await Jn(s,{title:a,model:m||j,signal:w.signal}),A=nt(_);ne("quick_extract",{status:"success",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length,resultLength:A.length,knowledgePointCount:_.knowledgePoints.length,durationMs:Date.now()-y}),u(L=>L.map(V=>V.id===B?{...V,content:"知识点提取完成:",type:"extraction-result",data:_}:V))}catch(_){_.name!=="AbortError"?(ne("quick_extract",{status:"failed",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length,durationMs:Date.now()-y,error:_.message||"extract_failed"}),u(A=>A.map(L=>L.id===B?{...L,content:`提取失败: ${_.message}`}:L))):ne("quick_extract",{status:"cancelled",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length,durationMs:Date.now()-y})}finally{$.current=!1,S(!1),P(null)}},[l,s,a,j,m]),J=y=>{y.key==="Enter"&&!y.shiftKey&&(y.preventDefault(),F())},W=n.useCallback(y=>{if(!y){q.warning("没有可复制的内容");return}ne("copy_result",{status:"start",resultLength:y.length}),Gs(y).then(()=>{ne("copy_result",{status:"success",resultLength:y.length}),q.success("复制成功")}).catch(()=>{ne("copy_result",{status:"failed",resultLength:y.length}),q.error("复制失败")})},[]),U=n.useCallback(y=>y.type==="text"?y.content:y.type==="extraction-result"&&y.data?nt(y.data):"",[]),te=n.useCallback(y=>{if(y.type==="extraction-result"&&y.data)try{const D=ra(y.data,{format:"markdown",includeSource:!0,includeTags:!0});ia(D.content,D.filename,D.mimeType),ne("download_markdown",{status:"success",resultLength:D.content.length,knowledgePointCount:y.data.knowledgePoints.length})}catch(D){console.error("Failed to export",D),ne("download_markdown",{status:"failed",knowledgePointCount:y.data.knowledgePoints.length,error:D instanceof Error?D.message:"export_failed"}),q.error("导出失败")}},[]);return e.jsxs("div",{className:"kb-extraction-chat",children:[e.jsx("div",{className:"kb-extraction-chat__header",children:e.jsxs("div",{className:"kb-extraction-chat__title",children:[e.jsx(Je,{size:18}),e.jsx("span",{children:"知识提取 & 对话"})]})}),e.jsx("div",{className:"kb-extraction-chat__messages",ref:H,children:d.map(y=>e.jsxs("div",{className:`kb-message kb-message--${y.role}`,children:[e.jsx("div",{className:"kb-message__avatar",children:y.role==="user"?e.jsx(Qe,{}):e.jsx(Qs,{})}),e.jsxs("div",{className:"kb-message__body",children:[e.jsx("div",{className:"kb-message__content",children:y.role==="model"?e.jsx("div",{className:"kb-message__content-scroll",children:y.type==="text"?y.id===b&&(y.content==="正在思考..."||y.content==="正在分析笔记内容并提取知识点...")?e.jsxs("div",{className:"kb-message__thinking","aria-label":"思考中",children:[e.jsx("span",{className:"kb-message__thinking-text",children:y.content.replace(/\.+$/,"")}),e.jsxs("span",{className:"kb-message__thinking-dots",children:[e.jsx("span",{children:"."}),e.jsx("span",{children:"."}),e.jsx("span",{children:"."})]})]}):y.content?e.jsx("div",{className:"kb-message__markdown-wrap",children:e.jsx(ot,{markdown:y.content,readOnly:!0,showModeSwitch:!1,initialMode:"wysiwyg",className:"kb-extraction-markdown"})}):null:e.jsx(Dt,{result:y.data})}):y.type==="text"?e.jsx("div",{className:"kb-message__text",children:y.content}):e.jsx(Dt,{result:y.data})}),y.role==="model"&&e.jsxs("div",{className:"kb-message__actions",children:[e.jsx(G,{content:"复制",showArrow:!1,children:e.jsx("button",{className:"kb-message__action-btn",onClick:()=>W(U(y)),children:e.jsx(Ve,{size:14})})}),e.jsx(G,{content:"插入到笔记",showArrow:!1,children:e.jsx("button",{className:"kb-message__action-btn",onClick:()=>{var w;const D=U(y);D&&(ne("insert_to_note",{status:"success",resultLength:D.length,knowledgePointCount:y.type==="extraction-result"?(w=y.data)==null?void 0:w.knowledgePoints.length:void 0}),r==null||r(D))},children:e.jsx(Zs,{size:14})})}),y.type==="extraction-result"&&e.jsx(G,{content:"导出 Markdown",showArrow:!1,children:e.jsx("button",{className:"kb-message__action-btn",onClick:()=>te(y),children:e.jsx(it,{size:14})})})]})]})]},y.id))}),e.jsxs("div",{className:"kb-extraction-chat__input-area",children:[e.jsx("div",{className:"kb-extraction-chat__input-wrapper",children:e.jsx("textarea",{ref:f,className:"kb-extraction-chat__textarea",value:p,onChange:y=>v(y.target.value),onKeyDown:J,placeholder:"输入问题,与 AI 讨论笔记内容...",disabled:l,rows:1})}),e.jsxs("div",{className:"kb-extraction-chat__input-actions",children:[e.jsx("div",{className:"kb-extraction-chat__model-selector",children:e.jsx(Nn,{value:j,valueRef:m,onChange:(y,D)=>{ne("change_model",{status:"success",model:y,profileId:D==null?void 0:D.profileId,noteLength:s.length}),N(y),k(D||jt(null,y))},variant:"capsule"})}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(G,{content:"一键提取知识点",showArrow:!1,children:e.jsx("span",{children:e.jsx("button",{className:"kb-extraction-chat__icon-btn",onClick:R,disabled:l,children:e.jsx(Je,{size:16})})})}),e.jsx(G,{content:l?"停止生成":"发送",showArrow:!1,children:e.jsx("span",{children:e.jsx("button",{className:`kb-extraction-chat__send-btn ${p.trim()||l?"kb-extraction-chat__send-btn--active":""}`,onClick:l?T:F,disabled:!p.trim()&&!l,children:l?e.jsx(Js,{size:18}):e.jsx(en,{size:18})})})})]})]})]})]})},Dt=({result:t})=>{const s=sn.useMemo(()=>nt(t),[t]);return e.jsx("div",{className:"kb-extraction-result-view",children:e.jsx(ot,{markdown:s,readOnly:!0,showModeSwitch:!1,initialMode:"wysiwyg",className:"kb-extraction-markdown"})})},Lt=[{label:"更新时间",value:"updatedAt"},{label:"创建时间",value:"createdAt"},{label:"标题",value:"title"}],ca=({value:t,onChange:s})=>{var o;const a=((o=Lt.find(d=>d.value===t.field))==null?void 0:o.label)||"排序",r=d=>{const u=d.value;["asc","desc"].includes(u)?s({...t,order:u}):u===t.field?s({...t,order:t.order==="asc"?"desc":"asc"}):s({...t,field:u,order:u==="title"?"asc":"desc"})},c=[{content:"排序字段",disabled:!0,className:"kb-sort-dropdown__header"},...Lt.map(d=>({content:d.label,value:d.value,prefixIcon:t.field===d.value?e.jsx(pe,{size:14}):e.jsx("div",{style:{width:14}})})),{divider:!0},{content:"排序方式",disabled:!0,className:"kb-sort-dropdown__header"},{content:"升序",value:"asc",prefixIcon:t.order==="asc"?e.jsx(pe,{size:14}):e.jsx("div",{style:{width:14}}),suffixIcon:e.jsx(yt,{size:14})},{content:"降序",value:"desc",prefixIcon:t.order==="desc"?e.jsx(pe,{size:14}):e.jsx("div",{style:{width:14}}),suffixIcon:e.jsx(vt,{size:14})}];return e.jsx(Vt,{options:c,onClick:r,trigger:"click",minColumnWidth:120,children:e.jsxs(Ne,{variant:"outline",size:"small",className:"kb-sort-trigger",children:[t.order==="asc"?e.jsx(yt,{size:14,style:{marginRight:4}}):e.jsx(vt,{size:14,style:{marginRight:4}}),a]})})},xa=({initialNoteId:t})=>{var bt;const[s,a]=n.useState([]),[r,c]=n.useState([]),[o,d]=n.useState([]),[u,p]=n.useState(null),[v,j]=n.useState([]),[N,m]=n.useState({}),[k,l]=n.useState(null),[S,b]=n.useState(new Set),[g,z]=n.useState(null),[P,$]=n.useState(""),[H,f]=n.useState(O.loadSortPreference?O.loadSortPreference():{field:"updatedAt",order:"desc"}),[T,F]=n.useState([]),[R,J]=n.useState(!1),[W,U]=n.useState(!1),[te,y]=n.useState(!1),[D,w]=n.useState(null),B=n.useRef(null),_=n.useRef(0),A=n.useRef(null),{confirm:L,confirmDialog:V}=Ot(),[E,Y]=n.useState(!1),[Q,Z]=n.useState("related"),[ie,Ce]=n.useState(280),[xe,ct]=n.useState(300),ke=n.useRef(!1),we=n.useRef(!1),$e=n.useRef(null);n.useEffect(()=>{const i=localStorage.getItem("kb-sidebar-width");if(i){const h=parseInt(i,10);!isNaN(h)&&h>100&&h<800&&Ce(h)}const x=localStorage.getItem("kb-right-sidebar-width");if(x){const h=parseInt(x,10);!isNaN(h)&&h>100&&h<800&&ct(h)}},[]),n.useEffect(()=>{const i=h=>{if(!$e.current)return;const M=$e.current.getBoundingClientRect();if(ke.current){h.preventDefault();const C=Math.max(200,Math.min(600,h.clientX-M.left));Ce(C)}else if(we.current){h.preventDefault();const C=Math.max(200,Math.min(600,M.right-h.clientX));ct(C)}},x=()=>{ke.current&&(ke.current=!1,localStorage.setItem("kb-sidebar-width",ie.toString()),document.body.style.cursor=""),we.current&&(we.current=!1,localStorage.setItem("kb-right-sidebar-width",xe.toString()),document.body.style.cursor="")};return ke.current||we.current?(document.addEventListener("mousemove",i),document.addEventListener("mouseup",x)):document.addEventListener("mousemove",i),document.addEventListener("mousemove",i),document.addEventListener("mouseup",x),()=>{document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",x)}},[ie,xe]);const es=i=>{i.preventDefault(),ke.current=!0,document.body.style.cursor="col-resize"},ts=i=>{i.preventDefault(),we.current=!0,document.body.style.cursor="col-resize"},[lt,ss]=n.useState(null),dt=n.useRef(!1),ut=n.useRef(!1);n.useEffect(()=>{if(dt.current)return;dt.current=!0,(async()=>{await O.initialize();try{await Cn()}catch(h){console.warn("[KnowledgeBaseContent] 提示词优化模板初始化失败:",h)}await ee();try{const h=await O.getStorageUsage();ss(h)}catch{}if(t){oe(t);return}const x=window.__kbPendingNavigation;if(x){window.__kbPendingNavigation=null;const{directoryName:h,autoCreateNote:M}=x;if(h){const I=(await O.getAllDirectories()).find(K=>K.name===h);if(I&&(l(I.id),b(K=>{const X=new Set(K);return X.add(I.id),X}),M)){const K=h==="Skill"?"新Skill":"新笔记",X=await O.createNote(K,I.id);await ee(),b(ue=>{const _e=new Set(ue);return _e.add(I.id),_e}),z(X.id);const ce=await O.getNoteById(X.id);p(ce),j([])}}}})()},[]);const ee=n.useCallback(async()=>{const[i,x,h]=await Promise.all([O.getAllDirectories(),O.getAllNoteMetas(),O.getAllTags()]),M=Array.from(new Map(i.map(K=>[K.id,K])).values());a(M);const C=Array.from(new Map(x.map(K=>[K.id,K])).values());c(C);const I=Array.from(new Map(h.map(K=>[K.id,K])).values());d(I),!k&&!g&&M.length>0&&(l(M[0].id),b(new Set([M[0].id]))),await ns(C)},[k,g]),ns=n.useCallback(async i=>{try{const[x,h]=await Promise.all([O.getAllTags(),O.getAllNoteTags()]),M=new Map(x.map(I=>[I.id,I])),C={};for(const I of i)C[I.id]=[];for(const I of h)if(C[I.noteId]&&M.has(I.tagId)){const K=M.get(I.tagId);K&&(C[I.noteId].some(X=>X.id===K.id)||C[I.noteId].push(K))}for(const I in C)C[I].sort((K,X)=>K.name.localeCompare(X.name));m(C)}catch(x){console.error("Failed to refresh note tags map:",x)}},[]);n.useEffect(()=>{if(!P.trim()){w(null);return}return B.current&&clearTimeout(B.current),B.current=setTimeout(async()=>{try{const x=await Gt().search(P,{limit:50,filter:k?{directoryId:k}:{}});w(x)}catch{w(null)}},300),()=>{B.current&&clearTimeout(B.current)}},[P,k]);const de=n.useMemo(()=>{if(D&&P.trim()){const x=new Set(D.map(C=>C.id)),h=new Map(D.map((C,I)=>[C.id,I]));let M=r.filter(C=>x.has(C.id));if(T.length>0){const C=new Set(T);M=M.filter(I=>(N[I.id]||[]).some(X=>C.has(X.id)))}return M.sort((C,I)=>(h.get(C.id)??0)-(h.get(I.id)??0))}let i=r;if(T.length>0){const x=new Set(T);i=i.filter(h=>(N[h.id]||[]).some(C=>x.has(C.id)))}return O.sortNoteMetas(i,H)},[r,k,P,T,H,N,D]),as=n.useMemo(()=>{const i={},x=new Set;for(const h of de)x.has(h.id)||(x.add(h.id),i[h.directoryId]=(i[h.directoryId]||0)+1);return i},[de]),rs=n.useMemo(()=>{var x;const i={};for(const h of de){const M=i[x=h.directoryId]??(i[x]=[]);M.some(C=>C.id===h.id)||M.push(h)}return i},[de]),Ue=n.useCallback(async i=>{await O.createDirectory(i),await ee()},[ee]),is=n.useCallback(async(i,x)=>{await O.updateDirectory(i,{name:x}),await ee()},[ee]),os=n.useCallback(async i=>{var M;const x=s.find(C=>C.id===i);if(!(!x||!await L({title:"确认删除目录",description:`确定要删除目录 "${x.name}" 及其下的所有笔记吗?此操作不可撤销。`,confirmText:"删除",cancelText:"取消",danger:!0})))try{await O.deleteDirectory(i),k===i&&(l(((M=s[0])==null?void 0:M.id)||null),z(null),p(null)),await ee(),q.success("目录已删除")}catch(C){q.error(`删除失败: ${C.message}`)}},[ee,k,s]),cs=n.useCallback(async i=>{try{await O.duplicateDirectory(i),await ee(),q.success("目录复制成功")}catch(x){q.error(`复制目录失败: ${x.message}`)}},[ee]),ls=n.useCallback(i=>{b(x=>{const h=new Set(x);return h.has(i)?h.delete(i):h.add(i),h})},[]),oe=n.useCallback(async i=>{const x=++_.current;if(z(i),l(null),j(N[i]||[]),i.startsWith(ge)){const M=i.slice(ge.length),C=Xe.find(I=>I.id===M);if(C){const I=["image","inspiration","grid_image"],K=["ppt"],X=C.mcpTool&&I.some(ue=>C.mcpTool.includes(ue))?"image":C.mcpTool&&K.some(ue=>C.mcpTool.includes(ue))?"ppt":void 0,ce={id:i,title:C.name,content:C.description||"",directoryId:"",createdAt:0,updatedAt:0,metadata:{...X?{outputType:X}:{}}};x===_.current&&(p(ce),j([]))}return}if(i.startsWith(fe)){const M=i.slice(fe.length),C=nn(M);if(C){const I={id:i,title:C.name,content:C.content||C.description||"",directoryId:"",createdAt:0,updatedAt:0,metadata:{...C.outputType?{outputType:C.outputType}:{},...C.category?{category:C.category}:{}}};x===_.current&&(p(I),j([]))}return}const h=await O.getNoteById(i);if(x===_.current&&(p(h),h)){const M=await O.getTagsForNote(h.id);if(x!==_.current)return;j(M),b(C=>{const I=new Set(C);return I.add(h.directoryId),I})}},[s,N]),Be=n.useCallback(async i=>{const x=new Set(r.filter(X=>X.directoryId===i).map(X=>X.title)),h=s.find(X=>X.id===i),M=(h==null?void 0:h.name)==="Skill"?"新Skill":"新笔记";let C=M,I=1;for(;x.has(C);)C=`${M} ${I}`,I++;const K=await O.createNote(C,i);await ee(),b(X=>{const ce=new Set(X);return ce.add(i),ce}),oe(K.id)},[ee,oe,r,s]),Fe=n.useCallback(async(i,x)=>{await O.updateNote(i,x),c(h=>h.map(M=>M.id===i?{...M,...x,updatedAt:Date.now()}:M)),(u==null?void 0:u.id)===i&&p(h=>h&&{...h,...x,updatedAt:Date.now()});try{const h=window.__drawnixBoard;if(h&&h.children){const{Transforms:M}=await Oe(async()=>{const{Transforms:C}=await import("./startup-app-eD_rQhSh.js").then(I=>I.nM);return{Transforms:C}},__vite__mapDeps([0]),import.meta.url);h.children.forEach((C,I)=>{if(C.noteId===i){const K={};x.title!==void 0&&(K.title=x.title),x.content!==void 0&&(K.body=x.content),Object.keys(K).length>0&&M.setNode(h,K,[I])}})}}catch(h){console.warn("[KB] Failed to sync note update to canvas card:",h)}},[u]),ds=n.useCallback(async i=>{if(!u)return;const x=u.content?`
51
+ Task: ${w.content}`,V=_.length-1;_[V].content=[{type:"text",text:L}]}const A=(Date.now()+1).toString();g(A),u(L=>[...L,{id:A,role:"model",content:"正在思考...",type:"text",timestamp:Date.now()}]),await Zn(_,{model:m||j,onProgress:L=>{u(V=>V.map(M=>M.id===A?{...M,content:L}:M))},signal:B.signal}),ne("chat",{status:"success",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length,inputLength:y.length,durationMs:Date.now()-D})}catch(_){_.name!=="AbortError"?(ne("chat",{status:"failed",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length,inputLength:y.length,durationMs:Date.now()-D,error:_.message||"chat_failed"}),u(A=>[...A,{id:Date.now().toString(),role:"model",content:`Error: ${_.message||"Something went wrong"}`,type:"text",timestamp:Date.now()}])):ne("chat",{status:"cancelled",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length,inputLength:y.length,durationMs:Date.now()-D})}finally{$.current=!1,S(!1),P(null),g(null)}},[p,l,d,s,j,m]),R=n.useCallback(async()=>{if($.current||l)return;$.current=!0;const y=Date.now();ne("quick_extract",{status:"start",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length}),S(!0);const D={id:Date.now().toString(),role:"user",content:"提取知识点",type:"text",timestamp:Date.now()};u(_=>[..._,D]);const w=new AbortController;P(w);const B=(Date.now()+1).toString();u(_=>[..._,{id:B,role:"model",content:"正在分析笔记内容并提取知识点...",type:"text",timestamp:Date.now()}]);try{const _=await Jn(s,{title:a,model:m||j,signal:w.signal}),A=nt(_);ne("quick_extract",{status:"success",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length,resultLength:A.length,knowledgePointCount:_.knowledgePoints.length,durationMs:Date.now()-y}),u(L=>L.map(V=>V.id===B?{...V,content:"知识点提取完成:",type:"extraction-result",data:_}:V))}catch(_){_.name!=="AbortError"?(ne("quick_extract",{status:"failed",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length,durationMs:Date.now()-y,error:_.message||"extract_failed"}),u(A=>A.map(L=>L.id===B?{...L,content:`提取失败: ${_.message}`}:L))):ne("quick_extract",{status:"cancelled",model:j,profileId:m==null?void 0:m.profileId,noteLength:s.length,durationMs:Date.now()-y})}finally{$.current=!1,S(!1),P(null)}},[l,s,a,j,m]),J=y=>{y.key==="Enter"&&!y.shiftKey&&(y.preventDefault(),F())},W=n.useCallback(y=>{if(!y){q.warning("没有可复制的内容");return}ne("copy_result",{status:"start",resultLength:y.length}),Gs(y).then(()=>{ne("copy_result",{status:"success",resultLength:y.length}),q.success("复制成功")}).catch(()=>{ne("copy_result",{status:"failed",resultLength:y.length}),q.error("复制失败")})},[]),U=n.useCallback(y=>y.type==="text"?y.content:y.type==="extraction-result"&&y.data?nt(y.data):"",[]),te=n.useCallback(y=>{if(y.type==="extraction-result"&&y.data)try{const D=ra(y.data,{format:"markdown",includeSource:!0,includeTags:!0});ia(D.content,D.filename,D.mimeType),ne("download_markdown",{status:"success",resultLength:D.content.length,knowledgePointCount:y.data.knowledgePoints.length})}catch(D){console.error("Failed to export",D),ne("download_markdown",{status:"failed",knowledgePointCount:y.data.knowledgePoints.length,error:D instanceof Error?D.message:"export_failed"}),q.error("导出失败")}},[]);return e.jsxs("div",{className:"kb-extraction-chat",children:[e.jsx("div",{className:"kb-extraction-chat__header",children:e.jsxs("div",{className:"kb-extraction-chat__title",children:[e.jsx(Je,{size:18}),e.jsx("span",{children:"知识提取 & 对话"})]})}),e.jsx("div",{className:"kb-extraction-chat__messages",ref:H,children:d.map(y=>e.jsxs("div",{className:`kb-message kb-message--${y.role}`,children:[e.jsx("div",{className:"kb-message__avatar",children:y.role==="user"?e.jsx(Qe,{}):e.jsx(Qs,{})}),e.jsxs("div",{className:"kb-message__body",children:[e.jsx("div",{className:"kb-message__content",children:y.role==="model"?e.jsx("div",{className:"kb-message__content-scroll",children:y.type==="text"?y.id===b&&(y.content==="正在思考..."||y.content==="正在分析笔记内容并提取知识点...")?e.jsxs("div",{className:"kb-message__thinking","aria-label":"思考中",children:[e.jsx("span",{className:"kb-message__thinking-text",children:y.content.replace(/\.+$/,"")}),e.jsxs("span",{className:"kb-message__thinking-dots",children:[e.jsx("span",{children:"."}),e.jsx("span",{children:"."}),e.jsx("span",{children:"."})]})]}):y.content?e.jsx("div",{className:"kb-message__markdown-wrap",children:e.jsx(ot,{markdown:y.content,readOnly:!0,showModeSwitch:!1,initialMode:"wysiwyg",className:"kb-extraction-markdown"})}):null:e.jsx(Dt,{result:y.data})}):y.type==="text"?e.jsx("div",{className:"kb-message__text",children:y.content}):e.jsx(Dt,{result:y.data})}),y.role==="model"&&e.jsxs("div",{className:"kb-message__actions",children:[e.jsx(G,{content:"复制",showArrow:!1,children:e.jsx("button",{className:"kb-message__action-btn",onClick:()=>W(U(y)),children:e.jsx(Ve,{size:14})})}),e.jsx(G,{content:"插入到笔记",showArrow:!1,children:e.jsx("button",{className:"kb-message__action-btn",onClick:()=>{var w;const D=U(y);D&&(ne("insert_to_note",{status:"success",resultLength:D.length,knowledgePointCount:y.type==="extraction-result"?(w=y.data)==null?void 0:w.knowledgePoints.length:void 0}),r==null||r(D))},children:e.jsx(Zs,{size:14})})}),y.type==="extraction-result"&&e.jsx(G,{content:"导出 Markdown",showArrow:!1,children:e.jsx("button",{className:"kb-message__action-btn",onClick:()=>te(y),children:e.jsx(it,{size:14})})})]})]})]},y.id))}),e.jsxs("div",{className:"kb-extraction-chat__input-area",children:[e.jsx("div",{className:"kb-extraction-chat__input-wrapper",children:e.jsx("textarea",{ref:f,className:"kb-extraction-chat__textarea",value:p,onChange:y=>v(y.target.value),onKeyDown:J,placeholder:"输入问题,与 AI 讨论笔记内容...",disabled:l,rows:1})}),e.jsxs("div",{className:"kb-extraction-chat__input-actions",children:[e.jsx("div",{className:"kb-extraction-chat__model-selector",children:e.jsx(Nn,{value:j,valueRef:m,onChange:(y,D)=>{ne("change_model",{status:"success",model:y,profileId:D==null?void 0:D.profileId,noteLength:s.length}),N(y),k(D||jt(null,y))},variant:"capsule"})}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(G,{content:"一键提取知识点",showArrow:!1,children:e.jsx("span",{children:e.jsx("button",{className:"kb-extraction-chat__icon-btn",onClick:R,disabled:l,children:e.jsx(Je,{size:16})})})}),e.jsx(G,{content:l?"停止生成":"发送",showArrow:!1,children:e.jsx("span",{children:e.jsx("button",{className:`kb-extraction-chat__send-btn ${p.trim()||l?"kb-extraction-chat__send-btn--active":""}`,onClick:l?T:F,disabled:!p.trim()&&!l,children:l?e.jsx(Js,{size:18}):e.jsx(en,{size:18})})})})]})]})]})]})},Dt=({result:t})=>{const s=sn.useMemo(()=>nt(t),[t]);return e.jsx("div",{className:"kb-extraction-result-view",children:e.jsx(ot,{markdown:s,readOnly:!0,showModeSwitch:!1,initialMode:"wysiwyg",className:"kb-extraction-markdown"})})},Lt=[{label:"更新时间",value:"updatedAt"},{label:"创建时间",value:"createdAt"},{label:"标题",value:"title"}],ca=({value:t,onChange:s})=>{var o;const a=((o=Lt.find(d=>d.value===t.field))==null?void 0:o.label)||"排序",r=d=>{const u=d.value;["asc","desc"].includes(u)?s({...t,order:u}):u===t.field?s({...t,order:t.order==="asc"?"desc":"asc"}):s({...t,field:u,order:u==="title"?"asc":"desc"})},c=[{content:"排序字段",disabled:!0,className:"kb-sort-dropdown__header"},...Lt.map(d=>({content:d.label,value:d.value,prefixIcon:t.field===d.value?e.jsx(pe,{size:14}):e.jsx("div",{style:{width:14}})})),{divider:!0},{content:"排序方式",disabled:!0,className:"kb-sort-dropdown__header"},{content:"升序",value:"asc",prefixIcon:t.order==="asc"?e.jsx(pe,{size:14}):e.jsx("div",{style:{width:14}}),suffixIcon:e.jsx(yt,{size:14})},{content:"降序",value:"desc",prefixIcon:t.order==="desc"?e.jsx(pe,{size:14}):e.jsx("div",{style:{width:14}}),suffixIcon:e.jsx(vt,{size:14})}];return e.jsx(Vt,{options:c,onClick:r,trigger:"click",minColumnWidth:120,children:e.jsxs(Ne,{variant:"outline",size:"small",className:"kb-sort-trigger",children:[t.order==="asc"?e.jsx(yt,{size:14,style:{marginRight:4}}):e.jsx(vt,{size:14,style:{marginRight:4}}),a]})})},xa=({initialNoteId:t})=>{var bt;const[s,a]=n.useState([]),[r,c]=n.useState([]),[o,d]=n.useState([]),[u,p]=n.useState(null),[v,j]=n.useState([]),[N,m]=n.useState({}),[k,l]=n.useState(null),[S,b]=n.useState(new Set),[g,z]=n.useState(null),[P,$]=n.useState(""),[H,f]=n.useState(O.loadSortPreference?O.loadSortPreference():{field:"updatedAt",order:"desc"}),[T,F]=n.useState([]),[R,J]=n.useState(!1),[W,U]=n.useState(!1),[te,y]=n.useState(!1),[D,w]=n.useState(null),B=n.useRef(null),_=n.useRef(0),A=n.useRef(null),{confirm:L,confirmDialog:V}=Ot(),[M,Y]=n.useState(!1),[Q,Z]=n.useState("related"),[ie,Ce]=n.useState(280),[xe,ct]=n.useState(300),ke=n.useRef(!1),we=n.useRef(!1),$e=n.useRef(null);n.useEffect(()=>{const i=localStorage.getItem("kb-sidebar-width");if(i){const h=parseInt(i,10);!isNaN(h)&&h>100&&h<800&&Ce(h)}const x=localStorage.getItem("kb-right-sidebar-width");if(x){const h=parseInt(x,10);!isNaN(h)&&h>100&&h<800&&ct(h)}},[]),n.useEffect(()=>{const i=h=>{if(!$e.current)return;const E=$e.current.getBoundingClientRect();if(ke.current){h.preventDefault();const C=Math.max(200,Math.min(600,h.clientX-E.left));Ce(C)}else if(we.current){h.preventDefault();const C=Math.max(200,Math.min(600,E.right-h.clientX));ct(C)}},x=()=>{ke.current&&(ke.current=!1,localStorage.setItem("kb-sidebar-width",ie.toString()),document.body.style.cursor=""),we.current&&(we.current=!1,localStorage.setItem("kb-right-sidebar-width",xe.toString()),document.body.style.cursor="")};return ke.current||we.current?(document.addEventListener("mousemove",i),document.addEventListener("mouseup",x)):document.addEventListener("mousemove",i),document.addEventListener("mousemove",i),document.addEventListener("mouseup",x),()=>{document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",x)}},[ie,xe]);const es=i=>{i.preventDefault(),ke.current=!0,document.body.style.cursor="col-resize"},ts=i=>{i.preventDefault(),we.current=!0,document.body.style.cursor="col-resize"},[lt,ss]=n.useState(null),dt=n.useRef(!1),ut=n.useRef(!1);n.useEffect(()=>{if(dt.current)return;dt.current=!0,(async()=>{await O.initialize();try{await Cn()}catch(h){console.warn("[KnowledgeBaseContent] 提示词优化模板初始化失败:",h)}await ee();try{const h=await O.getStorageUsage();ss(h)}catch{}if(t){oe(t);return}const x=window.__kbPendingNavigation;if(x){window.__kbPendingNavigation=null;const{directoryName:h,autoCreateNote:E}=x;if(h){const I=(await O.getAllDirectories()).find(K=>K.name===h);if(I&&(l(I.id),b(K=>{const X=new Set(K);return X.add(I.id),X}),E)){const K=h==="Skill"?"新Skill":"新笔记",X=await O.createNote(K,I.id);await ee(),b(ue=>{const _e=new Set(ue);return _e.add(I.id),_e}),z(X.id);const ce=await O.getNoteById(X.id);p(ce),j([])}}}})()},[]);const ee=n.useCallback(async()=>{const[i,x,h]=await Promise.all([O.getAllDirectories(),O.getAllNoteMetas(),O.getAllTags()]),E=Array.from(new Map(i.map(K=>[K.id,K])).values());a(E);const C=Array.from(new Map(x.map(K=>[K.id,K])).values());c(C);const I=Array.from(new Map(h.map(K=>[K.id,K])).values());d(I),!k&&!g&&E.length>0&&(l(E[0].id),b(new Set([E[0].id]))),await ns(C)},[k,g]),ns=n.useCallback(async i=>{try{const[x,h]=await Promise.all([O.getAllTags(),O.getAllNoteTags()]),E=new Map(x.map(I=>[I.id,I])),C={};for(const I of i)C[I.id]=[];for(const I of h)if(C[I.noteId]&&E.has(I.tagId)){const K=E.get(I.tagId);K&&(C[I.noteId].some(X=>X.id===K.id)||C[I.noteId].push(K))}for(const I in C)C[I].sort((K,X)=>K.name.localeCompare(X.name));m(C)}catch(x){console.error("Failed to refresh note tags map:",x)}},[]);n.useEffect(()=>{if(!P.trim()){w(null);return}return B.current&&clearTimeout(B.current),B.current=setTimeout(async()=>{try{const x=await Gt().search(P,{limit:50,filter:k?{directoryId:k}:{}});w(x)}catch{w(null)}},300),()=>{B.current&&clearTimeout(B.current)}},[P,k]);const de=n.useMemo(()=>{if(D&&P.trim()){const x=new Set(D.map(C=>C.id)),h=new Map(D.map((C,I)=>[C.id,I]));let E=r.filter(C=>x.has(C.id));if(T.length>0){const C=new Set(T);E=E.filter(I=>(N[I.id]||[]).some(X=>C.has(X.id)))}return E.sort((C,I)=>(h.get(C.id)??0)-(h.get(I.id)??0))}let i=r;if(T.length>0){const x=new Set(T);i=i.filter(h=>(N[h.id]||[]).some(C=>x.has(C.id)))}return O.sortNoteMetas(i,H)},[r,k,P,T,H,N,D]),as=n.useMemo(()=>{const i={},x=new Set;for(const h of de)x.has(h.id)||(x.add(h.id),i[h.directoryId]=(i[h.directoryId]||0)+1);return i},[de]),rs=n.useMemo(()=>{var x;const i={};for(const h of de){const E=i[x=h.directoryId]??(i[x]=[]);E.some(C=>C.id===h.id)||E.push(h)}return i},[de]),Ue=n.useCallback(async i=>{await O.createDirectory(i),await ee()},[ee]),is=n.useCallback(async(i,x)=>{await O.updateDirectory(i,{name:x}),await ee()},[ee]),os=n.useCallback(async i=>{var E;const x=s.find(C=>C.id===i);if(!(!x||!await L({title:"确认删除目录",description:`确定要删除目录 "${x.name}" 及其下的所有笔记吗?此操作不可撤销。`,confirmText:"删除",cancelText:"取消",danger:!0})))try{await O.deleteDirectory(i),k===i&&(l(((E=s[0])==null?void 0:E.id)||null),z(null),p(null)),await ee(),q.success("目录已删除")}catch(C){q.error(`删除失败: ${C.message}`)}},[ee,k,s]),cs=n.useCallback(async i=>{try{await O.duplicateDirectory(i),await ee(),q.success("目录复制成功")}catch(x){q.error(`复制目录失败: ${x.message}`)}},[ee]),ls=n.useCallback(i=>{b(x=>{const h=new Set(x);return h.has(i)?h.delete(i):h.add(i),h})},[]),oe=n.useCallback(async i=>{const x=++_.current;if(z(i),l(null),j(N[i]||[]),i.startsWith(ge)){const E=i.slice(ge.length),C=Xe.find(I=>I.id===E);if(C){const I=["image","inspiration","grid_image"],K=["ppt"],X=C.mcpTool&&I.some(ue=>C.mcpTool.includes(ue))?"image":C.mcpTool&&K.some(ue=>C.mcpTool.includes(ue))?"ppt":void 0,ce={id:i,title:C.name,content:C.description||"",directoryId:"",createdAt:0,updatedAt:0,metadata:{...X?{outputType:X}:{}}};x===_.current&&(p(ce),j([]))}return}if(i.startsWith(fe)){const E=i.slice(fe.length),C=nn(E);if(C){const I={id:i,title:C.name,content:C.content||C.description||"",directoryId:"",createdAt:0,updatedAt:0,metadata:{...C.outputType?{outputType:C.outputType}:{},...C.category?{category:C.category}:{}}};x===_.current&&(p(I),j([]))}return}const h=await O.getNoteById(i);if(x===_.current&&(p(h),h)){const E=await O.getTagsForNote(h.id);if(x!==_.current)return;j(E),b(C=>{const I=new Set(C);return I.add(h.directoryId),I})}},[s,N]),Be=n.useCallback(async i=>{const x=new Set(r.filter(X=>X.directoryId===i).map(X=>X.title)),h=s.find(X=>X.id===i),E=(h==null?void 0:h.name)==="Skill"?"新Skill":"新笔记";let C=E,I=1;for(;x.has(C);)C=`${E} ${I}`,I++;const K=await O.createNote(C,i);await ee(),b(X=>{const ce=new Set(X);return ce.add(i),ce}),oe(K.id)},[ee,oe,r,s]),Fe=n.useCallback(async(i,x)=>{await O.updateNote(i,x),c(h=>h.map(E=>E.id===i?{...E,...x,updatedAt:Date.now()}:E)),(u==null?void 0:u.id)===i&&p(h=>h&&{...h,...x,updatedAt:Date.now()});try{const h=window.__drawnixBoard;if(h&&h.children){const{Transforms:E}=await Oe(async()=>{const{Transforms:C}=await import("./startup-app-M6vjXkRC.js").then(I=>I.nN);return{Transforms:C}},__vite__mapDeps([0]),import.meta.url);h.children.forEach((C,I)=>{if(C.noteId===i){const K={};x.title!==void 0&&(K.title=x.title),x.content!==void 0&&(K.body=x.content),Object.keys(K).length>0&&E.setNode(h,K,[I])}})}}catch(h){console.warn("[KB] Failed to sync note update to canvas card:",h)}},[u]),ds=n.useCallback(async i=>{if(!u)return;const x=u.content?`
52
52
 
53
- `:"",h=(u.content||"")+x+i;await Fe(u.id,{content:h}),q.success("已插入到笔记末尾")},[u,Fe]),us=n.useCallback(async i=>{var h,M;const x=window.__drawnixBoard;if(!x){q.warning("请先打开画布");return}try{if(x.children.find(he=>he.noteId===i.id)&&!await L({title:"重复插入提醒",description:"画布中已存在关联该笔记的卡片,是否再次插入?",confirmText:"继续插入",cancelText:"取消"}))return;const I=await O.getNoteById(i.id);if(!I){q.error("获取笔记内容失败");return}const{getViewportOrigination:K}=await Oe(async()=>{const{getViewportOrigination:he}=await import("./startup-app-eD_rQhSh.js").then(We=>We.nM);return{getViewportOrigination:he}},__vite__mapDeps([0]),import.meta.url),X=K(x),ce=((h=x.host)==null?void 0:h.clientWidth)||800,ue=((M=x.host)==null?void 0:M.clientHeight)||600,_e=Math.round(window.innerWidth*.5),xt=180,kt=((X==null?void 0:X[0])??0)+ce/2-_e/2,wt=((X==null?void 0:X[1])??0)+ue/2-xt/2,{Transforms:js}=await Oe(async()=>{const{Transforms:he}=await import("./startup-app-eD_rQhSh.js").then(We=>We.nM);return{Transforms:he}},__vite__mapDeps([0]),import.meta.url),ys={type:"card",id:`card-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,title:I.title||"无标题",body:I.content||"",noteId:I.id,fillColor:"#FA8C16",points:[[kt,wt],[kt+_e,wt+xt]]};js.insertNode(x,ys,[x.children.length]),q.success("已插入到画布")}catch(C){console.error("[KB] Failed to insert note to canvas:",C),q.error(`插入失败: ${C.message}`)}},[]),hs=n.useCallback(async i=>{try{await O.duplicateNote(i),await ee(),q.success("笔记复制成功")}catch(x){q.error(`复制笔记失败: ${x.message}`)}},[ee]),ms=n.useCallback(async i=>{if(i.startsWith(ge)){q.warning("系统内置 Skill,不可删除");return}if(i.startsWith(fe)){q.warning("外部 Skill,不可在此删除(请在设置中管理外部 Skill 包)");return}const x=r.find(M=>M.id===i);if(!(!x||!await L({title:"确认删除笔记",description:`确定要删除笔记 "${x.title||"无标题"}" 吗?此操作不可撤销。`,confirmText:"删除",cancelText:"取消",danger:!0})))try{await O.deleteNote(i),g===i&&(z(null),p(null),j([])),await ee(),q.success("笔记已删除")}catch(M){q.error(`删除失败: ${M.message}`)}},[g,ee,r]);n.useEffect(()=>{!ut.current&&de.length>0&&(oe(de[0].id),ut.current=!0)},[de,oe]),n.useEffect(()=>{const i=x=>{const{noteId:h}=x.detail;h&&oe(h)};return window.addEventListener("kb:open-note",i),()=>window.removeEventListener("kb:open-note",i)},[oe]),n.useEffect(()=>{const i=async x=>{const{directoryName:h,autoCreateNote:M}=x.detail;if(!h)return;window.__kbPendingNavigation&&(window.__kbPendingNavigation=null);const I=(await O.getAllDirectories()).find(K=>K.name===h);I&&(l(I.id),b(K=>{const X=new Set(K);return X.add(I.id),X}),M&&await Be(I.id))};return window.addEventListener("kb:navigate",i),()=>window.removeEventListener("kb:navigate",i)},[Be]);const fs=n.useCallback(async(i,x)=>{await O.setNoteTags(i,x);const h=await O.getTagsForNote(i);j(h),m(C=>({...C,[i]:h}));const M=await O.getAllTags();d(M)},[]),ht=n.useCallback(async i=>{const x=await O.createTag(i),h=await O.getAllTags();return d(h),x},[]),gs=n.useCallback(async(i,x)=>{await O.updateTag(i,{name:x});const h=await O.getAllTags();d(h)},[]),ps=n.useCallback(async i=>{await O.deleteTag(i);const x=await O.getAllTags();if(d(x),u){const h=await O.getTagsForNote(u.id);j(h),m(M=>({...M,[u.id]:h}))}},[u]),bs=n.useCallback(i=>{f(i),O.saveSortPreference&&O.saveSortPreference(i)},[]);n.useEffect(()=>{if(!W)return;const i=x=>{A.current&&!A.current.contains(x.target)&&U(!1)};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[W]);const Se=n.useRef(null),mt=n.useCallback(()=>{var i;(i=Se.current)==null||i.click()},[]),xs=n.useCallback(async i=>{const x=i.target.files;if(!(!x||!k)){for(const h of Array.from(x)){if(!h.name.endsWith(".md")&&!h.name.endsWith(".markdown"))continue;const M=await h.text();await wn(M,k,h.name)}await ee(),Se.current&&(Se.current.value="")}},[k,ee]),ft=n.useCallback(async()=>{try{const i=await _n(),x=URL.createObjectURL(i),h=document.createElement("a");h.href=x,h.download=`knowledge-base-${new Date().toISOString().slice(0,10)}.zip`,document.body.appendChild(h),h.click(),document.body.removeChild(h),URL.revokeObjectURL(x)}catch(i){console.error("Export failed:",i),q.error("导出失败")}},[]),Me=n.useRef(null),gt=n.useCallback(()=>{var i;(i=Me.current)==null||i.click()},[]),ks=n.useCallback(async i=>{var h;const x=(h=i.target.files)==null?void 0:h[0];if(x){try{if(x.name.toLowerCase().endsWith(".zip")){const M=await jn(x);M.noteCount===0&&M.dirCount===0?q.warning("导入完成:没有新增内容(可能已存在重复内容)"):q.success(`导入完成:${M.dirCount} 个新目录、${M.noteCount} 篇笔记`)}else{const M=await x.text(),C=JSON.parse(M);if(C.version!==1&&C.version!==2){q.error("不支持的导入格式");return}const I=await yn(C);q.success(`导入完成:${I.dirCount} 个目录、${I.noteCount} 篇笔记、${I.tagCount} 个标签`)}await ee()}catch(M){console.error(M),q.error("导入失败,请确认文件格式正确")}Me.current&&(Me.current.value="")}},[ee]),pt=n.useCallback(()=>{const i=window.prompt("请输入目录名称","新建目录");i&&Ue(i)},[Ue]),ws=n.useCallback(i=>{switch(i.value){case"create-dir":pt();break;case"manage-tags":J(!0);break;case"import-md":mt();break;case"import-zip":gt();break;case"export-zip":ft();break}},[pt,mt,gt,ft]),_s=n.useMemo(()=>[{content:"新建目录",value:"create-dir",prefixIcon:e.jsx(an,{size:14})},{content:"管理标签",value:"manage-tags",prefixIcon:e.jsx(rn,{size:14})},{content:"导入 Markdown",value:"import-md",prefixIcon:e.jsx(Nt,{size:14})},{content:"导入 ZIP",value:"import-zip",prefixIcon:e.jsx(Nt,{size:14})},{content:"导出 ZIP",value:"export-zip",prefixIcon:e.jsx(it,{size:14})}],[]);return e.jsxs("div",{className:"kb-drawer",children:[e.jsx("input",{ref:Se,type:"file",accept:".md,.markdown",multiple:!0,style:{display:"none"},onChange:xs}),e.jsx("input",{ref:Me,type:"file",accept:".json,.zip",style:{display:"none"},onChange:ks}),e.jsxs("div",{className:"kb-drawer__body",ref:$e,children:[e.jsxs("div",{className:"kb-drawer__sidebar",style:{width:ie},children:[e.jsxs("div",{className:"kb-drawer__toolbar",children:[e.jsxs("div",{className:"kb-drawer__search",style:{display:"flex",gap:"8px",alignItems:"center",marginBottom:"8px"},children:[e.jsx(Te,{size:"small",prefixIcon:e.jsx(Wt,{size:14}),placeholder:"搜索笔记...",value:P,onChange:i=>$(i),clearable:!0,style:{flex:1}}),e.jsx(Vt,{trigger:"click",options:_s,onClick:ws,minColumnWidth:120,maxColumnWidth:200,popupProps:{overlayStyle:{width:200}},children:e.jsx(G,{content:"更多操作",showArrow:!1,children:e.jsx("button",{style:{background:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:"4px",color:"var(--td-text-color-secondary)",borderRadius:"4px"},onMouseEnter:i=>i.currentTarget.style.backgroundColor="var(--td-bg-color-container-hover)",onMouseLeave:i=>i.currentTarget.style.backgroundColor="transparent",children:e.jsx(on,{size:18})})})})]}),e.jsxs("div",{className:"kb-drawer__filters",style:{display:"flex",gap:"8px",alignItems:"center"},children:[e.jsx(Hn,{allTags:o,selectedTagIds:T,onSelectedChange:F}),e.jsx("div",{style:{flex:1}}),e.jsx(ca,{value:H,onChange:bs})]})]}),e.jsx(Mn,{directories:s,notesByDir:rs,noteTagsMap:N,noteCounts:as,selectedDirId:k,selectedNoteId:g,expandedDirIds:S,onSelectDir:i=>{l(i),z(null),p(null)},onToggleExpand:ls,onCreateDir:Ue,onRenameDir:is,onDeleteDir:os,onDuplicateDir:cs,onSelectNote:oe,onCreateNote:Be,onDeleteNote:ms,onDuplicateNote:hs,isCreatingDir:te,onCancelCreateDir:()=>y(!1),onInsertNoteToCanvas:us}),lt&&e.jsxs("div",{className:"kb-drawer__storage-bar",children:[e.jsx(cn,{size:12}),e.jsxs("span",{className:"kb-drawer__storage-text",children:["已用 ",la(lt.used)]})]})]}),e.jsx("div",{className:"kb-resizer",onMouseDown:es}),e.jsx("div",{className:"kb-drawer__editor",children:e.jsx(On,{note:u,allTags:o,noteTags:v,readOnly:!!(g&&(g.startsWith(ge)||g.startsWith(fe))),isSkillDirectory:!!(u&&(((bt=s.find(i=>i.id===u.directoryId))==null?void 0:bt.name)==="Skill"||g&&g.startsWith(ge)||g&&g.startsWith(fe))),onUpdateNote:Fe,onSetNoteTags:fs,onCreateTag:ht})}),u&&e.jsx(e.Fragment,{children:E?e.jsx(G,{content:"展开侧边栏",showArrow:!1,children:e.jsx("button",{className:"kb-drawer__right-toggle",onClick:()=>Y(!1),children:e.jsx(ln,{size:14})})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"kb-resizer",onMouseDown:ts}),e.jsxs("div",{className:"kb-drawer__right-sidebar",style:{width:xe},children:[e.jsxs("div",{className:"kb-drawer__right-header",children:[e.jsxs("div",{className:"kb-drawer__right-tabs",children:[e.jsx(G,{content:"相似笔记",showArrow:!1,children:e.jsx("button",{className:`kb-drawer__right-tab ${Q==="related"?"kb-drawer__right-tab--active":""}`,onClick:()=>Z("related"),children:e.jsx(Ht,{size:14})})}),e.jsx(G,{content:"知识提取",showArrow:!1,children:e.jsx("button",{className:`kb-drawer__right-tab ${Q==="extraction"?"kb-drawer__right-tab--active":""}`,onClick:()=>Z("extraction"),children:e.jsx(Je,{size:14})})})]}),e.jsx(G,{content:"收起侧边栏",showArrow:!1,children:e.jsx("button",{className:"kb-drawer__right-collapse-btn",onClick:()=>Y(!0),children:e.jsx(dn,{size:14})})})]}),e.jsx("div",{className:"kb-drawer__right-content",children:Q==="related"?e.jsx(Vn,{currentNoteId:u.id,allNotes:r,noteTagsMap:N,onSelectNote:oe}):e.jsx(oa,{noteId:u.id,noteContent:u.content,noteTitle:u.title,onSaved:()=>ee(),onInsertToNote:ds},u.id)})]})]})})]}),e.jsx(Kn,{visible:R,onClose:()=>J(!1),allTags:o,onCreateTag:ht,onUpdateTag:gs,onDeleteTag:ps}),V]})};function la(t){if(t===0)return"0 B";const s=["B","KB","MB","GB"],a=Math.floor(Math.log(t)/Math.log(1024));return`${(t/Math.pow(1024,a)).toFixed(1)} ${s[a]}`}export{xa as default};
53
+ `:"",h=(u.content||"")+x+i;await Fe(u.id,{content:h}),q.success("已插入到笔记末尾")},[u,Fe]),us=n.useCallback(async i=>{var h,E;const x=window.__drawnixBoard;if(!x){q.warning("请先打开画布");return}try{if(x.children.find(he=>he.noteId===i.id)&&!await L({title:"重复插入提醒",description:"画布中已存在关联该笔记的卡片,是否再次插入?",confirmText:"继续插入",cancelText:"取消"}))return;const I=await O.getNoteById(i.id);if(!I){q.error("获取笔记内容失败");return}const{getViewportOrigination:K}=await Oe(async()=>{const{getViewportOrigination:he}=await import("./startup-app-M6vjXkRC.js").then(We=>We.nN);return{getViewportOrigination:he}},__vite__mapDeps([0]),import.meta.url),X=K(x),ce=((h=x.host)==null?void 0:h.clientWidth)||800,ue=((E=x.host)==null?void 0:E.clientHeight)||600,_e=Math.round(window.innerWidth*.5),xt=180,kt=((X==null?void 0:X[0])??0)+ce/2-_e/2,wt=((X==null?void 0:X[1])??0)+ue/2-xt/2,{Transforms:js}=await Oe(async()=>{const{Transforms:he}=await import("./startup-app-M6vjXkRC.js").then(We=>We.nN);return{Transforms:he}},__vite__mapDeps([0]),import.meta.url),ys={type:"card",id:`card-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,title:I.title||"无标题",body:I.content||"",noteId:I.id,fillColor:"#FA8C16",points:[[kt,wt],[kt+_e,wt+xt]]};js.insertNode(x,ys,[x.children.length]),q.success("已插入到画布")}catch(C){console.error("[KB] Failed to insert note to canvas:",C),q.error(`插入失败: ${C.message}`)}},[]),hs=n.useCallback(async i=>{try{await O.duplicateNote(i),await ee(),q.success("笔记复制成功")}catch(x){q.error(`复制笔记失败: ${x.message}`)}},[ee]),ms=n.useCallback(async i=>{if(i.startsWith(ge)){q.warning("系统内置 Skill,不可删除");return}if(i.startsWith(fe)){q.warning("外部 Skill,不可在此删除(请在设置中管理外部 Skill 包)");return}const x=r.find(E=>E.id===i);if(!(!x||!await L({title:"确认删除笔记",description:`确定要删除笔记 "${x.title||"无标题"}" 吗?此操作不可撤销。`,confirmText:"删除",cancelText:"取消",danger:!0})))try{await O.deleteNote(i),g===i&&(z(null),p(null),j([])),await ee(),q.success("笔记已删除")}catch(E){q.error(`删除失败: ${E.message}`)}},[g,ee,r]);n.useEffect(()=>{!ut.current&&de.length>0&&(oe(de[0].id),ut.current=!0)},[de,oe]),n.useEffect(()=>{const i=x=>{const{noteId:h}=x.detail;h&&oe(h)};return window.addEventListener("kb:open-note",i),()=>window.removeEventListener("kb:open-note",i)},[oe]),n.useEffect(()=>{const i=async x=>{const{directoryName:h,autoCreateNote:E}=x.detail;if(!h)return;window.__kbPendingNavigation&&(window.__kbPendingNavigation=null);const I=(await O.getAllDirectories()).find(K=>K.name===h);I&&(l(I.id),b(K=>{const X=new Set(K);return X.add(I.id),X}),E&&await Be(I.id))};return window.addEventListener("kb:navigate",i),()=>window.removeEventListener("kb:navigate",i)},[Be]);const fs=n.useCallback(async(i,x)=>{await O.setNoteTags(i,x);const h=await O.getTagsForNote(i);j(h),m(C=>({...C,[i]:h}));const E=await O.getAllTags();d(E)},[]),ht=n.useCallback(async i=>{const x=await O.createTag(i),h=await O.getAllTags();return d(h),x},[]),gs=n.useCallback(async(i,x)=>{await O.updateTag(i,{name:x});const h=await O.getAllTags();d(h)},[]),ps=n.useCallback(async i=>{await O.deleteTag(i);const x=await O.getAllTags();if(d(x),u){const h=await O.getTagsForNote(u.id);j(h),m(E=>({...E,[u.id]:h}))}},[u]),bs=n.useCallback(i=>{f(i),O.saveSortPreference&&O.saveSortPreference(i)},[]);n.useEffect(()=>{if(!W)return;const i=x=>{A.current&&!A.current.contains(x.target)&&U(!1)};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[W]);const Se=n.useRef(null),mt=n.useCallback(()=>{var i;(i=Se.current)==null||i.click()},[]),xs=n.useCallback(async i=>{const x=i.target.files;if(!(!x||!k)){for(const h of Array.from(x)){if(!h.name.endsWith(".md")&&!h.name.endsWith(".markdown"))continue;const E=await h.text();await wn(E,k,h.name)}await ee(),Se.current&&(Se.current.value="")}},[k,ee]),ft=n.useCallback(async()=>{try{const i=await _n(),x=URL.createObjectURL(i),h=document.createElement("a");h.href=x,h.download=`knowledge-base-${new Date().toISOString().slice(0,10)}.zip`,document.body.appendChild(h),h.click(),document.body.removeChild(h),URL.revokeObjectURL(x)}catch(i){console.error("Export failed:",i),q.error("导出失败")}},[]),Ee=n.useRef(null),gt=n.useCallback(()=>{var i;(i=Ee.current)==null||i.click()},[]),ks=n.useCallback(async i=>{var h;const x=(h=i.target.files)==null?void 0:h[0];if(x){try{if(x.name.toLowerCase().endsWith(".zip")){const E=await jn(x);E.noteCount===0&&E.dirCount===0?q.warning("导入完成:没有新增内容(可能已存在重复内容)"):q.success(`导入完成:${E.dirCount} 个新目录、${E.noteCount} 篇笔记`)}else{const E=await x.text(),C=JSON.parse(E);if(C.version!==1&&C.version!==2){q.error("不支持的导入格式");return}const I=await yn(C);q.success(`导入完成:${I.dirCount} 个目录、${I.noteCount} 篇笔记、${I.tagCount} 个标签`)}await ee()}catch(E){console.error(E),q.error("导入失败,请确认文件格式正确")}Ee.current&&(Ee.current.value="")}},[ee]),pt=n.useCallback(()=>{const i=window.prompt("请输入目录名称","新建目录");i&&Ue(i)},[Ue]),ws=n.useCallback(i=>{switch(i.value){case"create-dir":pt();break;case"manage-tags":J(!0);break;case"import-md":mt();break;case"import-zip":gt();break;case"export-zip":ft();break}},[pt,mt,gt,ft]),_s=n.useMemo(()=>[{content:"新建目录",value:"create-dir",prefixIcon:e.jsx(an,{size:14})},{content:"管理标签",value:"manage-tags",prefixIcon:e.jsx(rn,{size:14})},{content:"导入 Markdown",value:"import-md",prefixIcon:e.jsx(Nt,{size:14})},{content:"导入 ZIP",value:"import-zip",prefixIcon:e.jsx(Nt,{size:14})},{content:"导出 ZIP",value:"export-zip",prefixIcon:e.jsx(it,{size:14})}],[]);return e.jsxs("div",{className:"kb-drawer",children:[e.jsx("input",{ref:Se,type:"file",accept:".md,.markdown",multiple:!0,style:{display:"none"},onChange:xs}),e.jsx("input",{ref:Ee,type:"file",accept:".json,.zip",style:{display:"none"},onChange:ks}),e.jsxs("div",{className:"kb-drawer__body",ref:$e,children:[e.jsxs("div",{className:"kb-drawer__sidebar",style:{width:ie},children:[e.jsxs("div",{className:"kb-drawer__toolbar",children:[e.jsxs("div",{className:"kb-drawer__search",style:{display:"flex",gap:"8px",alignItems:"center",marginBottom:"8px"},children:[e.jsx(Te,{size:"small",prefixIcon:e.jsx(Wt,{size:14}),placeholder:"搜索笔记...",value:P,onChange:i=>$(i),clearable:!0,style:{flex:1}}),e.jsx(Vt,{trigger:"click",options:_s,onClick:ws,minColumnWidth:120,maxColumnWidth:200,popupProps:{overlayStyle:{width:200}},children:e.jsx(G,{content:"更多操作",showArrow:!1,children:e.jsx("button",{style:{background:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:"4px",color:"var(--td-text-color-secondary)",borderRadius:"4px"},onMouseEnter:i=>i.currentTarget.style.backgroundColor="var(--td-bg-color-container-hover)",onMouseLeave:i=>i.currentTarget.style.backgroundColor="transparent",children:e.jsx(on,{size:18})})})})]}),e.jsxs("div",{className:"kb-drawer__filters",style:{display:"flex",gap:"8px",alignItems:"center"},children:[e.jsx(Hn,{allTags:o,selectedTagIds:T,onSelectedChange:F}),e.jsx("div",{style:{flex:1}}),e.jsx(ca,{value:H,onChange:bs})]})]}),e.jsx(En,{directories:s,notesByDir:rs,noteTagsMap:N,noteCounts:as,selectedDirId:k,selectedNoteId:g,expandedDirIds:S,onSelectDir:i=>{l(i),z(null),p(null)},onToggleExpand:ls,onCreateDir:Ue,onRenameDir:is,onDeleteDir:os,onDuplicateDir:cs,onSelectNote:oe,onCreateNote:Be,onDeleteNote:ms,onDuplicateNote:hs,isCreatingDir:te,onCancelCreateDir:()=>y(!1),onInsertNoteToCanvas:us}),lt&&e.jsxs("div",{className:"kb-drawer__storage-bar",children:[e.jsx(cn,{size:12}),e.jsxs("span",{className:"kb-drawer__storage-text",children:["已用 ",la(lt.used)]})]})]}),e.jsx("div",{className:"kb-resizer",onMouseDown:es}),e.jsx("div",{className:"kb-drawer__editor",children:e.jsx(On,{note:u,allTags:o,noteTags:v,readOnly:!!(g&&(g.startsWith(ge)||g.startsWith(fe))),isSkillDirectory:!!(u&&(((bt=s.find(i=>i.id===u.directoryId))==null?void 0:bt.name)==="Skill"||g&&g.startsWith(ge)||g&&g.startsWith(fe))),onUpdateNote:Fe,onSetNoteTags:fs,onCreateTag:ht})}),u&&e.jsx(e.Fragment,{children:M?e.jsx(G,{content:"展开侧边栏",showArrow:!1,children:e.jsx("button",{className:"kb-drawer__right-toggle",onClick:()=>Y(!1),children:e.jsx(ln,{size:14})})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"kb-resizer",onMouseDown:ts}),e.jsxs("div",{className:"kb-drawer__right-sidebar",style:{width:xe},children:[e.jsxs("div",{className:"kb-drawer__right-header",children:[e.jsxs("div",{className:"kb-drawer__right-tabs",children:[e.jsx(G,{content:"相似笔记",showArrow:!1,children:e.jsx("button",{className:`kb-drawer__right-tab ${Q==="related"?"kb-drawer__right-tab--active":""}`,onClick:()=>Z("related"),children:e.jsx(Ht,{size:14})})}),e.jsx(G,{content:"知识提取",showArrow:!1,children:e.jsx("button",{className:`kb-drawer__right-tab ${Q==="extraction"?"kb-drawer__right-tab--active":""}`,onClick:()=>Z("extraction"),children:e.jsx(Je,{size:14})})})]}),e.jsx(G,{content:"收起侧边栏",showArrow:!1,children:e.jsx("button",{className:"kb-drawer__right-collapse-btn",onClick:()=>Y(!0),children:e.jsx(dn,{size:14})})})]}),e.jsx("div",{className:"kb-drawer__right-content",children:Q==="related"?e.jsx(Vn,{currentNoteId:u.id,allNotes:r,noteTagsMap:N,onSelectNote:oe}):e.jsx(oa,{noteId:u.id,noteContent:u.content,noteTitle:u.title,onSaved:()=>ee(),onInsertToNote:ds},u.id)})]})]})})]}),e.jsx(Kn,{visible:R,onClose:()=>J(!1),allTags:o,onCreateTag:ht,onUpdateTag:gs,onDeleteTag:ps}),V]})};function la(t){if(t===0)return"0 B";const s=["B","KB","MB","GB"],a=Math.floor(Math.log(t)/Math.log(1024));return`${(t/Math.pow(1024,a)).toFixed(1)} ${s[a]}`}export{xa as default};