aitu-app 0.6.82 → 0.6.84
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/assets/CanvasAudioPlayer-gM4XBulx.js +2 -0
- package/assets/DeferredAIInputBar-CkIQvkAP.js +8 -0
- package/assets/DrawnixDeferredFeatures-DOYT5K9I.js +2 -0
- package/assets/KnowledgeBaseContent-CR4sCS_q.js +53 -0
- package/assets/KnowledgeBaseContent-CsR955E7.css +1 -0
- package/assets/{MVCreator-DM_I1mJr.js → MVCreator-DWZarSib.js} +14 -14
- package/assets/ModelBenchmarkWorkbench-D_JegnOw.js +2 -0
- package/assets/MusicAnalyzer--pkUbVUY.js +6 -0
- package/assets/MusicAnalyzer-2TwnYliW.js +1 -0
- package/assets/PromptHistoryTool-COvv-WAi.js +2 -0
- package/assets/ResizableDivider-BcF9sgog.js +1 -0
- package/assets/TaskQueuePanel-BN5vhhcR.js +1 -0
- package/assets/{VideoAnalyzer-D2uuXL5i.js → VideoAnalyzer-B3hECnW5.js} +2 -2
- package/assets/ai-chat-CQtdTiRy.css +1 -0
- package/assets/ai-chat-xhQ4iSkg.js +644 -0
- package/assets/ai-generation-preferences-service-pUo0JH7-.js +1 -0
- package/assets/{batch-image-generation-CNNwXxgK.js → batch-image-generation-CJRei7dG.js} +5 -6
- package/assets/{clipper-Cb0TKfsP.js → clipper-p8ORpTD7.js} +1 -1
- package/assets/diagram-engines-puSIfQIz.js +2088 -0
- package/assets/{editor-engines-DGOT7Xqo.js → editor-engines-I3xq4bkN.js} +10 -10
- package/assets/index-B5Iaq2Jv.js +1 -0
- package/assets/{index-Bgp2wxvA.js → index-D1QPxDht.js} +2 -2
- package/assets/{index-o5qBH2kC.js → index-DO7Nobpm.js} +8 -8
- package/assets/index-DUdnXgdV.js +1 -0
- package/assets/index-OIQy1nnY.js +2 -0
- package/assets/markdown-to-drawnix-DHjoxbFu.js +90 -0
- package/assets/mermaid-to-drawnix-BAiFmlOA.js +7 -0
- package/assets/model-benchmark-launcher-B254WgwG.js +1 -0
- package/assets/{office-data-2Ik8Wb2D.js → office-data-CVQuXBMb.js} +5 -5
- package/assets/photo-wall-splitter-BWp2PNKr.js +1 -0
- package/assets/{retry-image-BMMnhw_0.js → retry-image--4gDpgwV.js} +2 -2
- package/assets/settings-dialog-DcZ75Ajq.js +1 -0
- package/assets/skill-dsl-parser-Dce8urAe.js +3 -0
- package/assets/startup-app-5CxI1j1O.css +1 -0
- package/assets/startup-app-CiOE0Z0l.js +2377 -0
- package/assets/startup-runtime-DTmhLESk.js +1 -0
- package/assets/tool-windows-D6a2KkKR.css +1 -0
- package/assets/tool-windows-FtjXnyoK.js +95 -0
- package/assets/ttd-dialog-2g8Y0JD3.js +6 -0
- package/assets/ttd-dialog-DZBNihVL.css +1 -0
- package/assets/ttd-dialog-submit-shortcut-Dg-i-eXP.js +1 -0
- package/assets/ttd-dialog-submit-shortcut-DyioEoKX.css +1 -0
- package/assets/{useCharacters-D3PdMQMn.js → useCharacters-Dnlv8nJK.js} +2 -2
- package/assets/useWorkflowSubmission-BYltYlBW.js +44 -0
- package/assets/video-recovery-service-BOWBlc-F.js +1 -0
- package/assets/workflow-generation-utils-HlvBBTPr.js +3 -0
- package/assets/workflow-submission-service-C32hiHZv.js +4 -0
- package/changelog.json +26 -0
- package/idle-prefetch-manifest.json +485 -242
- package/manifest.json +3 -3
- package/package.json +1 -1
- package/precache-manifest.json +6 -6
- package/sw.js +1 -1
- package/version.json +5 -3
- package/assets/CanvasAudioPlayer-EQjMjqlc.js +0 -2
- package/assets/ChatDrawer-CWZQP5R5.css +0 -1
- package/assets/ChatDrawer-CbBhCIU_.js +0 -11
- package/assets/ChatMessagesArea-DatNDD1n.js +0 -7
- package/assets/ChatMessagesArea-PlF5AwzD.css +0 -1
- package/assets/DeferredAIInputBar-rIx0c8Qv.js +0 -8
- package/assets/DrawnixDeferredFeatures-C8aKfyQG.js +0 -2
- package/assets/KnowledgeBaseContent-t0hs8RQl.css +0 -1
- package/assets/KnowledgeBaseContent-vj5G-Ele.js +0 -53
- package/assets/ModelBenchmarkWorkbench-CfgAcLzz.js +0 -3
- package/assets/MusicAnalyzer-C-ZI5UZd.js +0 -6
- package/assets/MusicAnalyzer-DcDwJ88i.js +0 -1
- package/assets/PromptHistoryTool-DtvW3bCO.js +0 -2
- package/assets/ResizableDivider-DYCCpuYw.js +0 -1
- package/assets/TaskQueuePanel-DE2L1_EL.js +0 -1
- package/assets/ai-generation-preferences-service-BZMqxTjU.js +0 -1
- package/assets/canvas-insertion-C-BRaM5S.js +0 -15
- package/assets/diagram-engines-CGOhfK6V.css +0 -1
- package/assets/diagram-engines-DmAewdsu.js +0 -6462
- package/assets/index-BDFn0Sob.js +0 -1
- package/assets/index-BVyqBBIM.js +0 -1
- package/assets/index-BbDNsPPx.js +0 -5
- package/assets/index-DDzCo7oj.js +0 -195
- package/assets/index-DQQV1ik6.js +0 -2
- package/assets/index-Da_CCXZb.css +0 -1
- package/assets/index-DmlAaIoR.css +0 -1
- package/assets/index-I7GscWS1.css +0 -1
- package/assets/index-mUUunEI1.js +0 -1
- package/assets/main-B2ZrUywM.js +0 -37
- package/assets/main-CRPCRx46.css +0 -1
- package/assets/model-benchmark-launcher-QpuZmCET.js +0 -1
- package/assets/photo-wall-splitter-BD8mt52h.js +0 -1
- package/assets/ppt-generation-BLs-dVnA.js +0 -48
- package/assets/settings-dialog-xu3d4MX_.js +0 -1
- package/assets/shared-runtime-DBavnB0U.js +0 -5
- package/assets/skill-dsl-parser-BAv2yCP9.js +0 -68
- package/assets/startup-runtime-BbuNXj6O.js +0 -1
- package/assets/tool-windows-CqSDeXz5.css +0 -1
- package/assets/tool-windows-DV-j2p51.js +0 -499
- package/assets/ttd-dialog-BVnF62mS.css +0 -1
- package/assets/ttd-dialog-CwkEQ_6x.js +0 -6
- package/assets/useWorkflowSubmission-BIFN-qvq.js +0 -70
- package/assets/video-analyze-BeuyAh9W.js +0 -1
- package/assets/video-generation-C2GITib6.js +0 -13
- package/assets/video-recovery-service-BBDuz2L1.js +0 -1
- package/assets/workflow-generation-utils-Vh2FVA3M.js +0 -3
- package/assets/workflow-submission-service-BRb6CPDr.js +0 -4
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
# Opentu CDN Assets v0.6.
|
|
1
|
+
# Opentu CDN Assets v0.6.84
|
|
2
2
|
|
|
3
3
|
> 静态资源包,不含 HTML 文件
|
|
4
4
|
|
|
5
|
-
- unpkg: https://unpkg.com/aitu-app@0.6.
|
|
6
|
-
- jsdelivr: https://cdn.jsdelivr.net/npm/aitu-app@0.6.
|
|
5
|
+
- unpkg: https://unpkg.com/aitu-app@0.6.84/
|
|
6
|
+
- jsdelivr: https://cdn.jsdelivr.net/npm/aitu-app@0.6.84/
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-5CxI1j1O.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as ke}from"./startup-runtime-DTmhLESk.js";import{r as n,j as t,d1 as he,y as N,iW as Ae,fM as Se,dJ as Te,dK as Ee,d5 as ue,d3 as J,eu as U,ek as Le,m as de,c7 as Ce,bT as Ne,dM as Me,eo as Re,ew as oe,ex as pe,Y as ie,ep as _e,A as De,av as ze,ey as $e,en as Oe,l as Ue,ez as Fe,eA as fe,eB as Ye,ev as le,iX as qe,iY as Ve,iZ as Be,X as He,eD as We,eE as Xe,eF as Qe,eG as Ke,eH as Ge}from"./startup-app-CiOE0Z0l.js";import{u as Je,a as Ze,b as ye,d as Z,e as et}from"./tool-windows-FtjXnyoK.js";import{b as tt}from"./ai-chat-xhQ4iSkg.js";const me=5;function ve(e,i,s){const c=Math.max(0,window.innerWidth-i),f=Math.max(0,window.innerHeight-s);return{x:Math.max(0,Math.min(e.x,c)),y:Math.max(0,Math.min(e.y,f))}}function at(e){try{const i=localStorage.getItem(e);if(!i)return null;const s=JSON.parse(i);if(typeof s.x=="number"&&typeof s.y=="number")return s}catch{}return null}function nt(e,i){try{localStorage.setItem(e,JSON.stringify(i))}catch{}}function st(e){const{storageKey:i,enabled:s=!0}=e,[c,f]=n.useState(()=>s?at(i):null),[v,b]=n.useState(!1),w=n.useRef(!1),h=n.useRef(null),j=n.useRef(null),_=n.useCallback(y=>{if(!s||y.button!==0)return;const m=j.current;if(!m)return;const p=m.getBoundingClientRect();h.current={startPointerX:y.clientX,startPointerY:y.clientY,startElX:p.left,startElY:p.top,activated:!1,frameId:0}},[s]);n.useEffect(()=>{if(!s)return;const y=p=>{const u=h.current;if(!u)return;const g=p.clientX-u.startPointerX,M=p.clientY-u.startPointerY;if(!u.activated){if(Math.abs(g)<me&&Math.abs(M)<me)return;u.activated=!0,b(!0)}cancelAnimationFrame(u.frameId),u.frameId=requestAnimationFrame(()=>{const S=j.current;if(!S)return;const d=ve({x:u.startElX+g,y:u.startElY+M},S.offsetWidth,S.offsetHeight);f(d)})},m=()=>{const p=h.current;if(!p)return;cancelAnimationFrame(p.frameId);const u=p.activated;h.current=null,b(!1),u&&(w.current=!0,requestAnimationFrame(()=>{w.current=!1}),f(g=>(g&&nt(i,g),g)))};return window.addEventListener("pointermove",y),window.addEventListener("pointerup",m),()=>{window.removeEventListener("pointermove",y),window.removeEventListener("pointerup",m)}},[s,i]),n.useEffect(()=>{if(!s||!c)return;const y=()=>{const m=j.current;m&&f(p=>p&&ve(p,m.offsetWidth,m.offsetHeight))};return window.addEventListener("resize",y),()=>window.removeEventListener("resize",y)},[s,!!c]);const P=n.useCallback(()=>{f(null);try{localStorage.removeItem(i)}catch{}},[i]);return{position:c,isDragging:v,wasDraggedRef:w,elementRef:j,handlePointerDown:_,resetPosition:P}}const ot=({volume:e,onVolumeChange:i})=>{const s=n.useRef(null),c=n.useRef(null),f=n.useRef(!1),v=n.useRef(!1),b=n.useRef(!1),[w,h]=n.useState(!1),[j,_]=n.useState(!1),[P,y]=n.useState(!1),m=Math.round(e*100),p={"--canvas-audio-progress":`${e*100}%`},u=()=>{c.current!==null&&(window.clearTimeout(c.current),c.current=null)},g=()=>{u(),h(!0)},M=()=>{u(),h(d=>!d)},S=()=>{u(),!(v.current||b.current)&&(c.current=window.setTimeout(()=>{h(!1)},180))};return n.useEffect(()=>{v.current=j},[j]),n.useEffect(()=>{b.current=P},[P]),n.useEffect(()=>()=>u(),[]),n.useEffect(()=>{if(!w)return;const d=x=>{var k;(k=s.current)!=null&&k.contains(x.target)||(u(),h(!1),y(!1),_(!1),f.current=!1)};return document.addEventListener("pointerdown",d,!0),()=>document.removeEventListener("pointerdown",d,!0)},[w]),n.useEffect(()=>{if(!P)return;const d=()=>{b.current=!1,y(!1),v.current||(u(),c.current=window.setTimeout(()=>{h(!1)},180))};return window.addEventListener("pointerup",d),()=>window.removeEventListener("pointerup",d)},[P]),t.jsx("div",{ref:s,className:he("canvas-audio-player__volume",{"canvas-audio-player__volume--expanded":w}),onPointerDown:d=>d.stopPropagation(),onMouseEnter:()=>{v.current=!0,_(!0),u()},onMouseLeave:()=>{v.current=!1,_(!1),S()},onBlur:d=>{var k;const x=d.relatedTarget;x&&((k=s.current)!=null&&k.contains(x))||S()},children:t.jsxs("div",{className:"canvas-audio-player__volume-shell",children:[t.jsx("div",{className:"canvas-audio-player__volume-slider-wrap",children:t.jsx("input",{type:"range",min:0,max:1,step:.01,value:e,onFocus:g,onPointerDown:d=>{d.stopPropagation(),b.current=!0,y(!0),g()},onChange:d=>i(Number(d.target.value)),className:"canvas-audio-player__slider canvas-audio-player__slider--volume",style:p,"aria-label":"Playback volume","aria-valuetext":`${m}%`})}),t.jsxs("span",{className:"canvas-audio-player__volume-value",children:[m,"%"]}),t.jsx(N,{content:"音量",children:t.jsx("button",{type:"button",className:"canvas-audio-player__volume-toggle",onPointerDown:d=>{d.stopPropagation(),f.current=!0},onClick:()=>{f.current=!1,M()},onFocus:()=>{f.current||g()},onBlur:()=>{f.current=!1},"aria-label":"Volume controls","aria-expanded":w,children:e<=.01?t.jsx(Ae,{size:16}):t.jsx(Se,{size:16})})})]})})},ge="asset:";function it(e){var i;return(i=e==null?void 0:e.elementId)!=null&&i.startsWith(ge)?e.elementId.slice(ge.length):null}function xe(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return"--:--";const i=Math.floor(e),s=Math.floor(i/60),c=i%60;return`${s}:${String(c).padStart(2,"0")}`}function lt(e){var s;const i=((s=e.segments[e.segments.length-1])==null?void 0:s.endMs)||0;return xe(i/1e3)}const rt=({queue:e,activeQueueIndex:i,queueSource:s,activePlaylistId:c,playing:f=!1,activeReadingSourceId:v,onSelect:b,onPlayAllTracksItem:w})=>{const{assets:h}=Te(),{playlists:j,playlistItems:_,favoriteAssetIds:P,createPlaylist:y,addAssetToPlaylist:m,removeAssetFromPlaylist:p,toggleFavorite:u}=Ee(),{contextMenu:g,openAt:M,close:S}=tt(),[d,x]=n.useState(!1),[k,L]=n.useState(""),[F,T]=n.useState(null),{noteMetas:z,loadReadingSource:X,buildReadingQueue:Q}=Je(),[Y,q]=n.useState(s==="reading"?ue:J),V=Y===ue,R=s==="playlist"&&c?c:J,E=e.filter(a=>!U(a)),ee=Ze(E),K=a=>{const o=it(a);if(o)return o;if(!(a!=null&&a.audioUrl))return null;const r=h.find(I=>I.type===Me.AUDIO&&I.url===a.audioUrl);return(r==null?void 0:r.id)||null},B=n.useMemo(()=>new Set(R!==J?(_[R]||[]).map(a=>a.assetId?Le({kind:"asset",assetId:a.assetId}):null).filter(a=>!!a):[]),[_,R]),D=n.useCallback(async a=>{if(w){w(a);return}const o=await X(a);o&&(await Q(a),b(o))},[w,X,Q,b]),$=n.useMemo(()=>z.map(a=>({id:a.id,title:a.title||"未命名笔记",subtitle:new Date(a.updatedAt).toLocaleDateString("zh-CN"),canFavorite:!1,isActive:(v==null?void 0:v.includes(a.id))===!0,isPlaying:f&&(v==null?void 0:v.includes(a.id))===!0})),[z,v,f]);return s==="reading"?t.jsxs("div",{className:"canvas-audio-player__playlist",children:[t.jsx(ye,{className:"canvas-audio-player__playlist-tabs",selectedPlaylistId:Y,allCount:E.length,allTracksCount:z.length,playlists:j,playlistItems:_,onSelect:q,onCreate:()=>{L(""),x(!0)}}),V?$.length===0?t.jsxs("div",{className:"canvas-audio-player__playlist-empty",children:[t.jsx(de,{size:16}),t.jsx("span",{children:"知识库还没有笔记"})]}):t.jsx(Z,{className:"canvas-audio-player__playlist-list",items:$,onSelect:a=>void D(a.id),onTogglePlayback:a=>void D(a.id),showPlaybackIndicator:!0}):t.jsx(Z,{className:"canvas-audio-player__playlist-list audio-track-list--queue",items:e.map((a,o)=>{const r=a;return{id:r.readingSourceId,title:r.title||"朗读轨道",subtitle:lt(r),previewImageUrl:r.previewImageUrl,isActive:o===i,isPlaying:o===i,canFavorite:!1}}),onSelect:a=>{const o=e.find(r=>U(r)&&r.readingSourceId===a.id);o&&b(o)},onTogglePlayback:a=>{const o=e.find(r=>U(r)&&r.readingSourceId===a.id);o&&b(o)},showPlaybackIndicator:!0})]}):t.jsxs("div",{className:"canvas-audio-player__playlist",children:[t.jsx(ye,{className:"canvas-audio-player__playlist-tabs",selectedPlaylistId:Y,allCount:E.length,allTracksCount:z.length,playlists:j,playlistItems:_,onSelect:q,onCreate:()=>{L(""),x(!0)}}),V?$.length===0?t.jsxs("div",{className:"canvas-audio-player__playlist-empty",children:[t.jsx(de,{size:16}),t.jsx("span",{children:"知识库还没有笔记"})]}):t.jsx(Z,{className:"canvas-audio-player__playlist-list",items:$,onSelect:a=>void D(a.id),onTogglePlayback:a=>void D(a.id),showPlaybackIndicator:!0}):t.jsx(Z,{className:"canvas-audio-player__playlist-list audio-track-list--queue",items:E.map((a,o)=>{const r=K(a);return{id:`${a.audioUrl}-${o}`,title:a.title||"未命名音频",subtitle:xe(ee.get(a.audioUrl)??a.duration),previewImageUrl:a.previewImageUrl,isActive:o===i,isPlaying:o===i,isFavorite:r?P.has(r):!1,canFavorite:!!r}}),onSelect:a=>{const o=E.find((r,I)=>`${r.audioUrl}-${I}`===a.id);o&&b(o)},onContextMenu:(a,o)=>{const r=E.find((H,te)=>`${H.audioUrl}-${te}`===a.id),I=K(r);I&&(o.preventDefault(),o.stopPropagation(),M(o.clientX,o.clientY,{kind:"asset",assetId:I}))},onToggleFavorite:a=>{const o=E.find((I,H)=>`${I.audioUrl}-${H}`===a.id),r=K(o);r&&u(r)},onTogglePlayback:a=>{const o=E.find((r,I)=>`${r.audioUrl}-${I}`===a.id);o&&b(o)},showFavoriteButton:!0,showPlaybackIndicator:!0}),t.jsx(et,{contextMenu:g?{x:g.x,y:g.y,item:g.payload}:null,playlists:j,playlistItems:_,favoriteAssetIds:P,selectedPlaylistId:R===J?null:R,currentPlaylistItemKeys:B,onClose:S,onToggleFavorite:a=>void u(a),onAddToPlaylist:(a,o)=>{a.kind==="asset"&&m(a.assetId,o)},onRemoveFromPlaylist:(a,o)=>{a.kind==="asset"&&p(a.assetId,o)},onCreatePlaylistAndAdd:a=>{a.kind==="asset"&&(T(a.assetId),L(""),x(!0))}}),t.jsx(Ce,{visible:d,header:"新建播放列表",onClose:()=>x(!1),onConfirm:async()=>{const a=await y(k);F&&await m(F,a.id),x(!1),L(""),T(null)},onCancel:()=>{x(!1),T(null)},confirmBtn:"确定",cancelBtn:"取消",children:t.jsx(Ne,{value:k,onChange:a=>L(String(a)),placeholder:"请输入播放列表名称"})})]})},we={sequential:t.jsx(Ge,{size:14}),"list-loop":t.jsx(Ke,{size:14}),"single-loop":t.jsx(Qe,{size:14}),shuffle:t.jsx(Xe,{size:14})},ct=Object.keys(le).map(e=>({value:e,content:le[e],prefixIcon:we[e]}));function ut(e,i){return We(i).map(s=>{const c=_e(s),f=Math.abs(s-e)<.001;return{value:s,content:f?`✓ ${c}`:c}})}function be(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return"--:--";const i=Math.floor(e),s=Math.floor(i/60),c=i%60;return`${s}:${String(c).padStart(2,"0")}`}const vt=()=>{const e=Re(),i=n.useRef(null),[s,c]=n.useState(!1),[f,v]=n.useState(()=>{const l=oe.getToolState(pe);return(l==null?void 0:l.status)==="open"}),[b,w]=n.useState(()=>{try{return localStorage.getItem(ie.AUDIO_PLAYER_LAYOUT)==="vertical"?"vertical":"horizontal"}catch{return"horizontal"}}),[h,j]=n.useState(()=>typeof window<"u"?window.innerWidth:1024);n.useEffect(()=>{const l=()=>j(window.innerWidth);return window.addEventListener("resize",l),window.addEventListener("orientationchange",l),()=>{window.removeEventListener("resize",l),window.removeEventListener("orientationchange",l)}},[]);const _=h<=768?"vertical":b,[P,y]=n.useState(null),m=h<=768,{position:p,isDragging:u,wasDraggedRef:g,elementRef:M,handlePointerDown:S}=st({storageKey:ie.AUDIO_PLAYER_POSITION,enabled:!m}),d=n.useMemo(()=>!e.duration||e.duration<=0?0:Math.max(0,Math.min(100,e.currentTime/e.duration*100)),[e.currentTime,e.duration]),x=Number.isFinite(e.currentTime)?e.currentTime:0,k=Number.isFinite(e.duration)?e.duration:0,L=be(x),F=be(k),T=e.activeQueueIndex>=0?e.queue[e.activeQueueIndex]:null,z=e.activeTitle||(U(T)?T.title:void 0),X=e.activePreviewImageUrl||(U(T)?T.previewImageUrl:void 0),Q=e.activeQueueIndex>0,Y=e.activeQueueIndex>=0&&e.activeQueueIndex<e.queue.length-1,q=e.queue.length>1&&e.activeQueueIndex>=0,V=q?`${e.activeQueueIndex+1}/${e.queue.length}`:null,R=e.queueSource==="playlist"?e.activePlaylistName||"播放列表":e.activePlaylistName||(e.queueSource==="reading"?"朗读轨道":"画布音频"),E=q?`${R} ${e.activeQueueIndex+1} / ${e.queue.length}`:R,ee=V?`${V} · ${L} / ${F}`:`${L} / ${F}`,B=e.queueSource==="reading"&&(!!e.activeReadingSourceId||T!==null&&U(T))||!!e.activeAudioUrl,D=e.mediaType==="audio",$=e.mediaType==="reading"?"reading":"audio",a=le[e.playbackMode],o=we[e.playbackMode],r=n.useMemo(()=>ut(e.effectivePlaybackRate,$),[e.effectivePlaybackRate,$]),I=_e(e.effectivePlaybackRate),H=`${e.mediaType==="reading"?"语音速度":"播放速度"} ${I}`,te={"--canvas-audio-progress":`${d}%`},Pe=n.useCallback(()=>{w(l=>{const A=l==="horizontal"?"vertical":"horizontal";try{localStorage.setItem(ie.AUDIO_PLAYER_LAYOUT,A)}catch{}return A})},[]),Ie=n.useCallback(async()=>{try{e.playing?e.pausePlayback():await e.resumePlayback()}catch{}},[e]);if(n.useEffect(()=>{if(!B){c(!1),y(null);return}let l=0;const A=()=>{const ce=document.querySelector(".ai-input-bar__container");if(!(ce instanceof HTMLElement)){y(null);return}const se=ce.getBoundingClientRect(),G={left:Math.round(se.left),width:Math.round(se.width),bottom:Math.max(0,Math.round(window.innerHeight-se.top))};y(W=>W&&W.left===G.left&&W.width===G.width&&W.bottom===G.bottom?W:G)},C=()=>{window.cancelAnimationFrame(l),l=window.requestAnimationFrame(A)},ae=document.querySelector(".ai-input-bar__container"),ne=document.querySelector(".ai-input-bar"),O=typeof ResizeObserver<"u"?new ResizeObserver(()=>C()):null;return O&&ae instanceof HTMLElement&&O.observe(ae),O&&ne instanceof HTMLElement&&ne!==ae&&O.observe(ne),C(),window.addEventListener("resize",C),window.addEventListener("orientationchange",C),()=>{window.cancelAnimationFrame(l),window.removeEventListener("resize",C),window.removeEventListener("orientationchange",C),O==null||O.disconnect()}},[B]),n.useEffect(()=>{if(!s)return;const l=A=>{var C;(C=i.current)!=null&&C.contains(A.target)||c(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[s]),n.useEffect(()=>{M.current=i.current}),n.useEffect(()=>{const l=oe.observeToolStates().subscribe(()=>{const A=oe.getToolState(pe);v((A==null?void 0:A.status)==="open")});return()=>l.unsubscribe()},[]),!B||f)return null;const je=p&&!m?{left:p.x,top:p.y}:{},re={...P?{"--canvas-audio-mobile-left":`${P.left}px`,"--canvas-audio-mobile-width":`${P.width}px`,"--canvas-audio-mobile-offset":`${P.bottom}px`}:{},...je};return t.jsxs("div",{ref:i,className:he("canvas-audio-player",{"canvas-audio-player--playlist-open":s,"canvas-audio-player--positioned":!!p,"canvas-audio-player--dragging":u,"canvas-audio-player--vertical":_==="vertical"}),style:Object.keys(re).length>0?re:void 0,children:[t.jsxs("button",{type:"button",className:"canvas-audio-player__queue-trigger",onPointerDown:S,onClick:()=>{g.current||c(l=>!l)},"aria-expanded":s,"aria-label":"切换播放列表",children:[t.jsx("div",{className:"canvas-audio-player__cover",children:t.jsx(De,{src:X,alt:z||"Audio cover",fallbackClassName:"canvas-audio-player__cover-fallback",iconSize:16})}),t.jsxs("div",{className:"canvas-audio-player__meta",children:[t.jsx("div",{className:"canvas-audio-player__title",children:z||"未命名音频"}),t.jsxs("div",{className:"canvas-audio-player__subtitle",children:[t.jsx("span",{className:"canvas-audio-player__subtitle-text canvas-audio-player__subtitle-text--desktop",children:E}),t.jsx("span",{className:"canvas-audio-player__subtitle-text canvas-audio-player__subtitle-text--mobile",children:ee})]})]}),t.jsx("span",{className:"canvas-audio-player__queue-indicator","aria-hidden":"true",children:t.jsx(ze,{size:14})})]}),t.jsxs("div",{className:"canvas-audio-player__controls",children:[t.jsx(N,{content:"上一首",children:t.jsx("button",{type:"button",className:"canvas-audio-player__action canvas-audio-player__action--previous",onClick:()=>void e.playPrevious(),disabled:!Q,children:t.jsx($e,{size:14})})}),t.jsx(N,{content:e.playing?"暂停":"播放",children:t.jsx("button",{type:"button",className:"canvas-audio-player__action canvas-audio-player__action--primary",onClick:()=>void Ie(),children:e.playing?t.jsx(Oe,{size:14}):t.jsx(Ue,{size:14})})}),t.jsx(N,{content:"下一首",children:t.jsx("button",{type:"button",className:"canvas-audio-player__action canvas-audio-player__action--next",onClick:()=>void e.playNext(),disabled:!Y,children:t.jsx(Fe,{size:14})})})]}),t.jsxs("div",{className:"canvas-audio-player__progress",children:[t.jsx("span",{className:"canvas-audio-player__time",children:L}),t.jsx("input",{type:"range",min:0,max:k||0,step:.1,value:Math.min(x,k||x),onChange:l=>{D&&e.seekTo(Number(l.target.value))},className:"canvas-audio-player__slider canvas-audio-player__slider--progress",style:te,"aria-label":D?"Audio progress":"Reading progress",disabled:!D}),t.jsx("span",{className:"canvas-audio-player__time",children:F})]}),t.jsx(ot,{volume:e.volume,onVolumeChange:e.setVolume}),t.jsx(fe,{options:r,trigger:"click",placement:"bottom",minColumnWidth:112,onClick:l=>e.setPlaybackRate(Number(l.value)),children:t.jsx(N,{content:H,children:t.jsx("button",{type:"button",className:"canvas-audio-player__toggle canvas-audio-player__speed-toggle","aria-label":`切换播放速度,当前${I}`,children:t.jsx(Ye,{size:14})})})}),t.jsx(fe,{options:ct,trigger:"click",placement:"bottom",minColumnWidth:132,onClick:l=>e.setPlaybackMode(l.value),children:t.jsx(N,{content:a,children:t.jsx("button",{type:"button",className:"canvas-audio-player__toggle canvas-audio-player__mode-toggle","aria-label":`切换播放模式,当前${a}`,children:o})})}),t.jsx(N,{content:"打开播放器工具",children:t.jsx("button",{type:"button",className:"canvas-audio-player__toggle canvas-audio-player__player-switch canvas-audio-player__switch-toggle",onClick:()=>{ke(async()=>{const{openMusicPlayerTool:l}=await import("./startup-app-CiOE0Z0l.js").then(A=>A.mg);return{openMusicPlayerTool:l}},__vite__mapDeps([0]),import.meta.url).then(({openMusicPlayerTool:l})=>{l()})},"aria-label":"打开播放器工具",children:t.jsx(qe,{size:14})})}),t.jsx(N,{content:_==="horizontal"?"切换为垂直布局":"切换为水平布局",children:t.jsx("button",{type:"button",className:"canvas-audio-player__toggle canvas-audio-player__layout-toggle",onClick:Pe,style:{display:h<=768?"none":""},children:_==="horizontal"?t.jsx(Ve,{size:14}):t.jsx(Be,{size:14})})}),t.jsx(N,{content:"关闭播放器",children:t.jsx("button",{type:"button",className:"canvas-audio-player__close",onClick:e.stopPlayback,children:t.jsx(He,{size:14})})}),s?t.jsx(rt,{queue:e.queue,activeQueueIndex:e.activeQueueIndex,queueSource:e.queueSource,activePlaylistId:e.activePlaylistId,playing:e.playing,activeReadingSourceId:e.activeReadingSourceId,onSelect:l=>{U(l)?e.toggleReadingPlayback(l):e.togglePlayback(l),c(!1)}}):null]})};export{vt as CanvasAudioPlayer};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-5CxI1j1O.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{aI as fs,dL as cr,r,hJ as qt,a7 as Ae,hK as Zn,ew as tn,j as p,hL as lr,br as gs,db as Tt,bb as dr,hM as ur,hN as pr,ae as mr,n as hr,dy as Oo,fm as fr,aT as gr,ao as Ve,hO as Hn,a6 as Cn,bh as qn,b6 as Pt,bg as Et,bi as pt,hP as Jn,hQ as eo,hR as et,Q as to,hS as Wo,av as no,$ as oo,at as Tn,cS as ws,b5 as Is,gz as wr,cR as Ir,q as so,h as yr,hT as xr,X as _r,a2 as br,bQ as vr,gX as Sr,f3 as ro,aN as kr,m as Mr,hU as Cr,hV as Tr,bj as kn,hW as Qn,v as ys,hX as Pr,dJ as Er,fn as lt,fC as $n,ab as mt,aJ as kt,hY as Lo,hZ as Fo,h_ as Ar,fx as je,fl as Un,bF as Dr,M as Je,dM as Bo,dN as Rr,h$ as Nr,i0 as jr,i1 as zr,i2 as Or,i3 as Vn,i4 as Ho,gF as xs,g as Gn,dz as $o,i5 as Wr,bG as _s,i6 as Uo,a as Vo,i7 as Go,i8 as Ko,d1 as gn,d$ as Lr,cX as Fr,i9 as Br,ee as Hr,ia as $r,ib as Ur}from"./startup-app-CiOE0Z0l.js";import{u as Vr,a as Gr,c as wn,b as Mt,W as Kr}from"./useWorkflowSubmission-BYltYlBW.js";import{P as Yr,r as In,G as yn,q as Xr,o as Mn,L as ao,N as Zr,O as qr,y as xn,E as dt,Q as Jr,R as Yo,M as _n,S as Qr,T as ea,X as ta,Y as Xo,Z as Zo,$ as qo,a0 as na}from"./ai-chat-xhQ4iSkg.js";import{_ as Jo}from"./startup-runtime-DTmhLESk.js";import{c as oa,q as sa,A as Qo,M as ra}from"./tool-windows-FtjXnyoK.js";import{u as aa,r as ia,g as ca,a as la,b as da,l as ua,c as Kn,s as pa,d as ma,P as ha}from"./ai-generation-preferences-service-pUo0JH7-.js";import{s as es}from"./workflow-submission-service-C32hiHZv.js";import"./skill-dsl-parser-Dce8urAe.js";const fa=({generationType:e,onSelectPrompt:n,language:t,extraActions:s,onBeforeOpenMyPrompts:d})=>{const{history:c,removeHistory:a,refreshHistory:h}=fs({deduplicateWithPresets:!1,modelTypeFilter:e==="image"||e==="video"?void 0:e}),{imageHistory:u,videoHistory:l}=aa(),{confirm:v,confirmDialog:k}=cr(),[S,I]=r.useState(!1),[,f]=r.useState(0),D=r.useRef(null),y=r.useRef(null),C=r.useRef(null),E=t==="zh"?"我的提示词":"My Prompts",P=e==="image"||e==="video"?ia({generationType:e,language:t,promptContents:ca(e,t,e==="image"?u:l),imageHistory:u,videoHistory:l}):la({generationType:e,language:t,aiInputHistory:c,imageHistory:u,videoHistory:l});r.useEffect(()=>qt.subscribeChanges(()=>{h(),f(H=>H+1)}),[h]),r.useEffect(()=>()=>{y.current&&clearTimeout(y.current),C.current&&clearTimeout(C.current)},[]);const g=r.useCallback(()=>{C.current&&(clearTimeout(C.current),C.current=null),y.current=setTimeout(()=>{h(),f(H=>H+1),S||Ae.trackPromptAction({action:"open_panel",surface:"ai_input_prompt_popover",promptType:e,itemCount:P.length}),I(!0)},150)},[e,S,P.length,h]),N=r.useCallback(()=>{y.current&&(clearTimeout(y.current),y.current=null),C.current=setTimeout(()=>{I(!1)},200)},[]),U=r.useCallback(H=>{n({content:H.content,modelType:H.modelType,scene:H.scene}),I(!1)},[n]),ee=r.useCallback(async H=>{const _=P.find($=>$.id===H);!_||!await v({title:t==="zh"?"确认删除提示词":"Delete Prompt",description:t==="zh"?"确定要删除这条提示词吗?此操作不可撤销。":"Are you sure you want to delete this prompt? This action cannot be undone.",confirmText:t==="zh"?"删除":"Delete",cancelText:t==="zh"?"取消":"Cancel",danger:!0})||(qt.deletePrompt(e,_.content),_.historyId&&e!=="image"&&e!=="video"?a(_.historyId):f($=>$+1))},[v,e,t,P,a]),ne=r.useCallback(H=>{const _=P.find(R=>R.id===H);_&&(qt.isPinned(e,_.content)?qt.unpinPrompt(e,_.content):qt.pinPrompt(e,_.content),f(R=>R+1))},[e,P]),ae=r.useCallback(()=>{const H=Zn.find($=>$.id==="prompt-history");if(!H){Ae.trackPromptAction({action:"open_tool",surface:"ai_input_prompt_popover",promptType:e,status:"failed",metadata:{tool_id:"prompt-history",reason:"tool_not_found"}});return}d==null||d();const _=tn.getToolState("prompt-history");console.info("[PromptHistoryPopover] open my prompts",{generationType:e,beforeStatus:_==null?void 0:_.status,beforeInstanceId:_==null?void 0:_.instanceId,beforeIsLauncher:_==null?void 0:_.isLauncher,beforeIsPinned:_==null?void 0:_.isPinned}),Ae.trackPromptAction({action:"open_tool",surface:"ai_input_prompt_popover",promptType:e,status:"success",metadata:{tool_id:H.id}}),I(!1),tn.openTool(H,{componentProps:{initialCategory:e}});const R=tn.getToolState("prompt-history");console.info("[PromptHistoryPopover] requested my prompts open",{generationType:e,afterStatus:R==null?void 0:R.status,afterInstanceId:R==null?void 0:R.instanceId,afterIsLauncher:R==null?void 0:R.isLauncher,afterIsPinned:R==null?void 0:R.isPinned})},[e,d]);return p.jsxs("div",{ref:D,className:"prompt-history-popover",children:[p.jsxs("div",{className:"prompt-history-popover__actions",children:[p.jsx("button",{className:"prompt-history-popover__trigger",title:E,"data-track":"ai_input_click_history",onMouseEnter:g,onMouseLeave:N,children:p.jsx(lr,{size:18})}),s]}),S&&p.jsx("div",{className:"prompt-history-popover__panel-wrapper",onMouseEnter:g,onMouseLeave:N,children:p.jsx(Yr,{title:E,items:P,onSelect:U,onTogglePin:ne,onDelete:ee,onTitleClick:ae,language:t,showCount:!0,analyticsSurface:"ai_input_prompt_popover",analyticsPromptType:e})}),k]})};function ga(e){var n;return!!((n=e.params)!=null&&n.longVideoMeta)}function wa(e){var n;return((n=e.params)==null?void 0:n.longVideoMeta)||null}class At{constructor(){this.isInitialized=!1,this.batches=new Map,this.initTimestamp=0}static getInstance(){return At.instance||(At.instance=new At),At.instance}initialize(){this.isInitialized||(this.isInitialized=!0,this.initTimestamp=Date.now(),gs.observeTaskUpdates().subscribe(n=>{if(n.type==="taskUpdated"&&n.task.status===Tt.COMPLETED&&n.task.type===dr.VIDEO&&ga(n.task)){if((n.task.completedAt||0)<this.initTimestamp)return;this.handleSegmentCompleted(n.task).catch(s=>{console.error("[LongVideoChain] Error handling completed segment:",s)})}}))}async handleSegmentCompleted(n){var l;const t=wa(n);if(!t)return;const{segmentIndex:s,totalSegments:d,scripts:c,batchId:a}=t,h=(l=n.result)==null?void 0:l.url;let u=this.batches.get(a);if(u||(u={batchId:a,totalSegments:d,completedSegments:new Map,processedSegments:new Set,creatingNextFor:null,isMerging:!1,mergeCompleted:!1,scripts:c||[],characterReferenceUrls:t.characterReferenceUrls,characterDescription:t.characterDescription},this.batches.set(a,u)),!u.processedSegments.has(s)){if(u.processedSegments.add(s),h&&u.completedSegments.set(s,h),u.completedSegments.size===d){await this.mergeAndInsert(u);return}if(u.creatingNextFor!==s&&s<d){u.creatingNextFor=s;try{await this.createNextSegment(n,t,c,h,u.characterReferenceUrls,u.characterDescription)}finally{u.creatingNextFor=null}}}}async createNextSegment(n,t,s,d,c,a){const h=t.segmentIndex+1,u=s.find(k=>k.index===h);if(!u){console.error(`[LongVideoChain] Script not found for segment ${h}`);return}let l;if(d)try{l=(await ur(d)).dataUrl}catch(k){console.error("[LongVideoChain] Failed to extract last frame:",k)}const v={...t,segmentIndex:h,needsLastFrame:h<t.totalSegments,characterReferenceUrls:c??t.characterReferenceUrls,characterDescription:a??t.characterDescription};oa(u,v,l)}async mergeAndInsert(n){if(!(n.isMerging||n.mergeCompleted)){n.isMerging=!0;try{const t=[];for(let a=1;a<=n.totalSegments;a++){const h=n.completedSegments.get(a);h&&t.push(h)}if(t.length===0){console.error("[LongVideoChain] No video URLs to merge");return}const s=this.extractTransitions(n),c=await pr(t,(a,h,u)=>{const l=u||`${h} ${a.toFixed(1)}%`},{transitions:s,transitionDuration:.5});await this.insertMergedVideo(c.url),n.mergeCompleted=!0,this.cleanupBatch(n.batchId)}catch(t){console.error("[LongVideoChain] Merge failed:",t),this.cleanupBatch(n.batchId)}finally{n.isMerging=!1}}}async insertMergedVideo(n){try{await sa("video",n)}catch(t){console.error("[LongVideoChain] Failed to insert video to canvas:",t)}}extractTransitions(n){return!n.scripts||n.scripts.length===0?[]:n.scripts.sort((t,s)=>t.index-s.index).slice(0,-1).map(t=>t.transition_hint||"cut")}cleanupBatch(n){const t=this.batches.get(n);t&&(t.completedSegments.clear(),t.processedSegments.clear(),this.batches.delete(n))}getBatchStatus(n){const t=this.batches.get(n);return t?{completed:t.completedSegments.size,total:t.totalSegments,isMerging:t.isMerging,mergeCompleted:t.mergeCompleted}:null}}const Ia=At.getInstance();function ya(){Ia.initialize()}function ts(){return`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}async function ns(e){return new Promise((n,t)=>{const s=new Image,d=e.startsWith("http")&&!e.startsWith(location.origin);s.crossOrigin="anonymous",s.onload=()=>n(s),s.onerror=()=>{t(d?new Error("无法加载外部图片,可能是跨域 (CORS) 限制。请先下载图片到本地后再操作。"):new Error("图片加载失败,请检查图片是否有效"))},s.src=e})}function xa(e,n=.92){return e.toDataURL("image/jpeg",n)}class _a{async split(n,t){const{rows:s,cols:d}=t;if(s<1||d<1)throw new Error("Grid rows and cols must be at least 1");const c=await ns(n),a=c.naturalWidth,h=c.naturalHeight,u=Math.floor(a/d),l=Math.floor(h/s),v=[];for(let k=0;k<s;k++)for(let S=0;S<d;S++){const I=k*d+S,f=S*u,D=k*l,y=document.createElement("canvas");y.width=u,y.height=l;const C=y.getContext("2d");if(!C)throw new Error("Failed to get canvas 2d context");C.drawImage(c,f,D,u,l,0,0,u,l);const E=xa(y);v.push({id:ts(),imageData:E,originalIndex:I,width:u,height:l})}return v}async splitToBlob(n,t){const{rows:s,cols:d}=t;if(s<1||d<1)throw new Error("Grid rows and cols must be at least 1");const c=await ns(n),a=c.naturalWidth,h=c.naturalHeight,u=Math.floor(a/d),l=Math.floor(h/s),v=[];for(let k=0;k<s;k++)for(let S=0;S<d;S++){const I=k*d+S,f=S*u,D=k*l,y=document.createElement("canvas");y.width=u,y.height=l;const C=y.getContext("2d");if(!C)throw new Error("Failed to get canvas 2d context");C.drawImage(c,f,D,u,l,0,0,u,l);const E=await new Promise((g,N)=>{y.toBlob(U=>{U?g(U):N(new Error("Failed to create blob"))},"image/png",.92)}),P=URL.createObjectURL(E);v.push({id:ts(),imageData:P,originalIndex:I,width:u,height:l})}return v}revokeBlobUrls(n){for(const t of n)t.imageData.startsWith("blob:")&&URL.revokeObjectURL(t.imageData)}}const os=new _a;function Ee(e,n){return Math.random()*(n-e)+e}function bn(e){const n=[...e];for(let t=n.length-1;t>0;t--){const s=Math.floor(Math.random()*(t+1));[n[t],n[s]]=[n[s],n[t]]}return n}class ba{calculate(n,t,s,d){switch(t){case"scattered":return this.scatteredLayout(n,s,d);case"grid":return this.gridLayout(n,s);case"circular":return this.circularLayout(n,s,d);case"inspiration-board":return this.inspirationBoardLayout(n,s,d);default:return console.warn(`[LayoutEngine] Unknown layout style: ${t}, falling back to grid`),this.gridLayout(n,s)}}scatteredLayout(n,t,s){const{maxRotation:d=15,minScale:c=.85,maxScale:a=1.15,positionJitter:h=40}=s||{},{canvasWidth:u,canvasHeight:l,startX:v,startY:k,gap:S=20}=t,I=n.length,f=Math.ceil(Math.sqrt(I)),D=Math.ceil(I/f),y=Math.max(...n.map(ne=>ne.width)),C=Math.max(...n.map(ne=>ne.height)),E=u-S*2,P=l-S*2,g=E/f,N=P/D,U=Math.min((g-S)/y,(N-S)/C,1),ee=bn(n.map((ne,ae)=>ae));return n.map((ne,ae)=>{const H=Math.floor(ae/f),_=ae%f,R=v+S+_*g+g/2,$=k+S+H*N+N/2,Q=Ee(-h,h),V=Ee(-h,h),ie=Ee(-d,d),Se=Ee(c,a),Me=U*Se,Dt=ne.width*Me,nn=ne.height*Me;return{...ne,x:R+Q-Dt/2,y:$+V-nn/2,rotation:ie,scale:Me,zIndex:ee[ae]}})}gridLayout(n,t){const{canvasWidth:s,canvasHeight:d,startX:c,startY:a,gap:h=20}=t,u=n.length,l=Math.ceil(Math.sqrt(u)),v=Math.ceil(u/l),k=Math.max(...n.map(E=>E.width)),S=Math.max(...n.map(E=>E.height)),I=s-h*(l+1),f=d-h*(v+1),D=I/l,y=f/v,C=Math.min(D/k,y/S,1);return n.map((E,P)=>{const g=Math.floor(P/l),N=P%l,U=E.width*C,ee=E.height*C,ne=c+h+N*(D+h),ae=a+h+g*(y+h),H=ne+(D-U)/2,_=ae+(y-ee)/2;return{...E,x:H,y:_,rotation:0,scale:C,zIndex:P}})}circularLayout(n,t,s){const{centerIndex:d=-1,radius:c,startAngle:a=-90}=s||{},{canvasWidth:h,canvasHeight:u,startX:l,startY:v}=t,k=l+h/2,S=v+u/2,I=d>=0&&d<n.length?n.filter((_,R)=>R!==d):n,f=d>=0&&d<n.length?n[d]:null,D=Math.max(...n.map(_=>_.width)),y=Math.max(...n.map(_=>_.height)),C=Math.max(D,y),E=I.length,P=C*.8,g=E*C*1.2,N=Math.max(P,g/(2*Math.PI)),U=c||Math.min(N,Math.min(h,u)/2-C/2),ee=Math.min(h,u),ne=Math.min(ee*.25/C,1),ae=[];if(f){const _=f.width*ne*1.2,R=f.height*ne*1.2;ae.push({...f,x:k-_/2,y:S-R/2,rotation:0,scale:ne*1.2,zIndex:E})}const H=360/E;return I.forEach((_,R)=>{const Q=(a+R*H)*Math.PI/180,V=_.width*ne,ie=_.height*ne,Se=k+U*Math.cos(Q)-V/2,Me=S+U*Math.sin(Q)-ie/2;ae.push({..._,x:Se,y:Me,rotation:0,scale:ne,zIndex:R})}),ae}inspirationBoardLayout(n,t,s){const{minWidthRatio:d=In.minWidthRatio,maxWidthRatio:c=In.maxWidthRatio,maxRotation:a=In.maxRotation,gap:h=In.gap}=s||{},{canvasWidth:u,canvasHeight:l,startX:v,startY:k}=t,S=n.length,I=this.assignSizeCategories(S),f=n.reduce((N,U)=>N+U.width,0)/S,D=n.reduce((N,U)=>N+U.height,0)/S,y=u||1200,C=l||600,E=Math.min(y*.25/f,C*.4/D,1),P=this.calculateInspirationBoardPositions(S,y,C,h),g=bn(n.map((N,U)=>U));return n.map((N,U)=>{const ee=P[U],ne=I[U];let ae;switch(ne){case"large":ae=Ee(1.2,c);break;case"medium":ae=Ee(.9,1.1);break;case"small":ae=Ee(d,.85);break;default:ae=1}const H=E*ae,_=Ee(-a,a),R=Ee(-20,20),$=Ee(-15,15),Q=N.width*H,V=N.height*H;return{...N,x:v+ee.x+R-Q/2,y:k+ee.y+$-V/2,rotation:_,scale:H,zIndex:g[U]}})}assignSizeCategories(n){const t=[],s=Math.max(2,Math.floor(n*.25)),d=Math.max(2,Math.floor(n*.25)),c=n-s-d;for(let a=0;a<s;a++)t.push("large");for(let a=0;a<c;a++)t.push("medium");for(let a=0;a<d;a++)t.push("small");return bn(t)}calculateInspirationBoardPositions(n,t,s,d){const c=[],a=Math.ceil(n/4),h=Math.ceil(n/a),u=(t-d*2)/h,l=(s-d*2)/a;for(let v=0;v<n;v++){const k=Math.floor(v/h),S=v%h,I=d+S*u+u/2,f=d+k*l+l/2,D=Ee(-u*.3,u*.3),y=Ee(-l*.2,l*.2);c.push({x:I+D,y:f+y})}return bn(c)}calculateRequiredSize(n,t,s=.5){const d=n.length,c=Math.ceil(Math.sqrt(d)),a=Math.ceil(d/c),h=Math.max(...n.map(I=>I.width)),u=Math.max(...n.map(I=>I.height)),l=20,v=t==="scattered"?60:40,k=c*h*s+(c+1)*l+v*2,S=a*u*s+(a+1)*l+v*2;return{width:k,height:S}}}const ss=new ba;class va{constructor(){this.board=null}setBoard(n){this.board=n}getBoard(){return this.board}async generate(n){const{theme:t,gridConfig:s=yn.gridConfig,layoutStyle:d=yn.layoutStyle,imageSize:c=yn.imageSize,imageQuality:a=yn.imageQuality}=n;try{const h=this.buildPrompt(t,s),u=await mr.generateImage(h,{size:c,quality:a,response_format:"url"});if(!u.data||u.data.length===0)throw new Error("AI 生成图片失败:未返回图片数据");const l=u.data[0].url||u.data[0].b64_json,v=l&&hr(String(l));if(!v)throw new Error("AI 生成图片失败:未返回图片 URL");const k=await Oo.getImageForAI(v),S=k.type==="base64"?k.value:v,I=await os.split(S,s),f=this.calculateLayoutParams(I),D=ss.calculate(I,d,f);return{success:!0,originalImageUrl:v,elements:D}}catch(h){return console.error("[GridImageService] Generation failed:",h),{success:!1,error:h.message||"宫格图生成失败"}}}async processExistingImage(n,t,s="scattered"){try{const d=await Oo.getImageForAI(n),c=d.type==="base64"?d.value:n,a=await os.split(c,t),h=this.calculateLayoutParams(a),u=ss.calculate(a,s,h);return{success:!0,originalImageUrl:n,elements:u}}catch(d){return console.error("[GridImageService] Processing failed:",d),{success:!1,error:d.message||"宫格图处理失败"}}}async insertToBoard(n,t){if(!this.board)throw new Error("画板未初始化,请先调用 setBoard");let s=(t==null?void 0:t[0])??100,d=t==null?void 0:t[1];if(d===void 0){const a=fr(this.board);d=(a==null?void 0:a[1])??100,s=(a==null?void 0:a[0])??s}const c=[...n].sort((a,h)=>a.zIndex-h.zIndex);for(const a of c){const h=s+a.x,u=d+a.y,l={url:a.imageData,width:a.width*a.scale,height:a.height*a.scale};gr.insertImage(this.board,l,[h,u])}}async generateAndInsert(n,t){const s=await this.generate(n);return s.success&&s.elements&&await this.insertToBoard(s.elements,t),s}buildPrompt(n,t){const s=Xr.zh;return s(n,t.rows,t.cols)}calculateLayoutParams(n){const t=n.reduce((I,f)=>I+f.width,0),s=n.reduce((I,f)=>I+f.height,0),d=n.length,c=Math.ceil(Math.sqrt(d)),a=Math.ceil(d/c),h=t/d,u=s/d,l=30,v=50,k=c*h+(c+1)*l+v*2,S=a*u+(a+1)*l+v*2;return{canvasWidth:k,canvasHeight:S,startX:0,startY:0,gap:l}}}const rs=new va;function Sa(e){return{cleanText:e,selectedAudioModel:null,selectedImageModel:null,selectedVideoModel:null,selectedParams:[],selectedCount:null}}function ka(){const e=Cn.get();return(e==null?void 0:e.imageModelName)||pt()}function Ma(){const e=Cn.get();return(e==null?void 0:e.videoModelName)||Pt()}function Ca(){const e=Cn.get();return(e==null?void 0:e.audioModelName)||Et()}function as(){const e=Cn.get();return(e==null?void 0:e.textModelName)||qn()}function Ta(e,n,t){if(n.length>0)return n.join(`
|
|
3
|
+
`);if(e){if(t===1)return"请仔细分析这张图片的内容、风格、构图、色调和艺术特点,推测生成这张图片可能使用的原始提示词,然后基于你推测的提示词重新生成一张全新的、风格相似但内容不完全相同的图片。不要直接复制原图。";if(t>1)return"请分析这些图片的主题、风格和视觉元素,找出它们之间的共同点或关联性,然后创造性地将它们融合成一张全新的、和谐统一的图片。融合时请保持各图片的精华元素,确保最终作品在构图、色调和风格上协调一致。"}return""}function Jt(e){return e.replace(":","x").toLowerCase()}function Pa(e,n,t){const s=n.texts.length>0||n.images.length>0||n.videos.length>0||n.graphics.length>0,d=n.texts,c=n.images.length+n.graphics.length,a=Sa(e),h=a.cleanText.trim().length>0;let u=(t==null?void 0:t.generationType)||"image",l,v=!1;if(t!=null&&t.modelId){const g=Ve(t.modelId);t.generationType||((g==null?void 0:g.type)==="video"?u="video":(g==null?void 0:g.type)==="audio"?u="audio":(g==null?void 0:g.type)==="text"?u="text":u="image"),l=t.modelId,v=!0}else a.selectedAudioModel?(u="audio",l=a.selectedAudioModel,v=!0):a.selectedVideoModel?(u="video",l=a.selectedVideoModel,v=!0):a.selectedImageModel?(u="image",l=a.selectedImageModel,v=!0):!s&&h&&!(t!=null&&t.generationType)?(u="agent",l=as()):u==="video"?l=Ma():u==="audio"?l=Ca():u==="text"||u==="agent"?l=as():l=ka();let k;(t==null?void 0:t.generationType)==="image"||(t==null?void 0:t.generationType)==="video"||(t==null?void 0:t.generationType)==="audio"||(t==null?void 0:t.generationType)==="text"?k="direct_generation":(t==null?void 0:t.generationType)==="agent"?k="agent_flow":k=h?"agent_flow":"direct_generation";const S=a.cleanText.trim(),I=d.join(`
|
|
4
|
+
`).trim();let f;if(I&&S?f=`${I}
|
|
5
|
+
|
|
6
|
+
${S}`:S?f=S:I?f=I:s&&c>0?f=u==="text"?"":Ta(s,[],c):f="",l.startsWith("mj")&&(t!=null&&t.params)){const g=da(t.params);g&&(f=[f,g].filter(Boolean).join(" "))}const D=(t==null?void 0:t.count)||a.selectedCount||1;let y,C,E;if(t!=null&&t.params){u!=="audio"&&u!=="text"&&u!=="agent"&&!l.startsWith("mj")&&t.params.size&&(y=Jt(t.params.size)),t.params.duration&&(C=t.params.duration);const g={};for(const[N,U]of Object.entries(t.params))N!=="size"&&N!=="duration"&&U&&(g[N]=U);Object.keys(g).length>0&&(E=g)}if(!y&&(t!=null&&t.size)&&t.size!=="auto"&&(y=Jt(t.size)),!y&&(t==null?void 0:t.size)!=="auto"){for(const g of a.selectedParams)if(g.id==="size"){y=Jt(g.value);break}}if(!C){for(const g of a.selectedParams)if(g.id==="duration"){C=g.value;break}}if(!y&&(t==null?void 0:t.size)!=="auto"&&u!=="text"&&u!=="agent"&&u!=="audio"){const g=Ve(l);if((g==null?void 0:g.type)==="image"&&g.imageDefaults)y="1x1";else if((g==null?void 0:g.type)==="video"&&g.videoDefaults){const N=Hn(l,(t==null?void 0:t.modelRef)||l,t==null?void 0:t.params);y=Jt(N.size||g.videoDefaults.size),C||(C=N.duration||g.videoDefaults.duration)}else if(u==="image")y="1x1";else if(u==="video"){const N=Hn(l,(t==null?void 0:t.modelRef)||l,t==null?void 0:t.params);y=Jt(N.size),C||(C=N.duration)}}!C&&u==="video"&&(C=Hn(l,(t==null?void 0:t.modelRef)||l,t==null?void 0:t.params).duration);const P=a.cleanText.trim();return{scenario:k,generationType:u,modelId:l,modelRef:(t==null?void 0:t.modelRef)||null,defaultModels:t==null?void 0:t.defaultModels,defaultModelRefs:t==null?void 0:t.defaultModelRefs,isModelExplicit:v,prompt:f,userInstruction:P,rawInput:e,count:D,size:y,duration:C,extraParams:E,parseResult:a,hasExtraContent:h,selection:n}}const Yn={id:et,name:"自动"},is=Jn.map(e=>({id:e.id,name:e.name,isSystem:!0,mcpTool:e.mcpTool,outputType:e.outputType})),Ea=({value:e,onSelect:n,onSelectSkill:t,onAddSkill:s,disabled:d=!1})=>{const[c,a]=r.useState(!1),[h,u]=r.useState([]),[l,v]=r.useState([]),[k,S]=r.useState(""),[I,f]=r.useState(0),D=r.useRef(null),y=r.useRef(null),C=r.useCallback(async()=>{try{const R=(await Mn.getAllDirectories()).find(ie=>ie.name==="Skill");if(!R)return;const $=await Mn.getNoteMetasByDirectory(R.id),Q=new Set(Jn.map(ie=>ie.id)),V=$.filter(ie=>!Q.has(ie.id)).map(ie=>{var Se;return{id:ie.id,name:ie.title,outputType:((Se=ie.metadata)==null?void 0:Se.outputType)||void 0}});u(V)}catch{}},[]),E=r.useCallback(async()=>{try{const _=await eo.getAllExternalSkillsMeta(),R=new Set(Jn.map(Q=>Q.id)),$=_.filter(Q=>!R.has(Q.id)).map(Q=>({id:Q.id,name:Q.name,isExternal:!0,source:Q.source,outputType:Q.outputType}));v($)}catch{}},[]);r.useEffect(()=>{if(c){C(),E(),S("");const R=[Yn,...is,...l,...h].findIndex($=>$.id===e);f(R>=0?R:0),setTimeout(()=>{var $;return($=y.current)==null?void 0:$.focus()},50)}},[c,e]),r.useEffect(()=>{if(c&&D.current){const _=D.current.children[I];_&&_.scrollIntoView({block:"nearest"})}},[I,c]);const P=r.useCallback(_=>{_.preventDefault(),!d&&a(R=>!R)},[d]),g=r.useCallback(_=>{n(_.id),t==null||t(_),a(!1)},[n,t]),N=r.useCallback(_=>{_.stopPropagation(),a(!1),s()},[s]),U=[Yn,...is,...l,...h],ee=k.trim()?U.filter(_=>_.name.toLowerCase().includes(k.toLowerCase())||_.id.toLowerCase().includes(k.toLowerCase())):U,ne=U.length>15,ae=r.useCallback(_=>_==="Escape"?(a(!1),!0):_==="ArrowDown"?(f(R=>R<ee.length-1?R+1:0),!0):_==="ArrowUp"?(f(R=>R>0?R-1:ee.length-1),!0):_==="Enter"||_===" "||_==="Tab"?(I<ee.length&&g(ee[I]),!0):!1,[I,ee,g]),H=ee.find(_=>_.id===e)||Yn;return p.jsx(ao,{isOpen:c,setIsOpen:a,disabled:d,openKeys:["Enter"," ","ArrowDown","ArrowUp"],onOpenKey:ae,children:({containerRef:_,menuRef:R,portalPosition:$,handleTriggerKeyDown:Q})=>p.jsxs("div",{className:"skill-dropdown",ref:_,children:[p.jsxs("button",{className:`skill-dropdown__trigger ${c?"skill-dropdown__trigger--open":""}`,onMouseDown:P,onKeyDown:Q,disabled:d,type:"button",title:`Skill: ${H.name}`,children:[p.jsx("span",{className:"skill-dropdown__icon-prefix",children:p.jsx(Wo,{size:14})}),p.jsx("span",{className:"skill-dropdown__label",children:H.name}),p.jsx(no,{size:14,className:`skill-dropdown__chevron ${c?"skill-dropdown__chevron--open":""}`})]}),c&&to.createPortal(p.jsxs("div",{ref:R,className:`skill-dropdown__menu ${Tn}`,style:{position:"fixed",zIndex:oo.DROPDOWN_PORTAL,left:$.left,bottom:window.innerHeight-$.top+8},onMouseDown:V=>V.stopPropagation(),onClick:V=>V.stopPropagation(),children:[p.jsxs("div",{className:"skill-dropdown__header",children:[p.jsx(Wo,{size:14}),p.jsx("span",{children:"Skill"})]}),ne&&p.jsx("div",{className:"skill-dropdown__search",children:p.jsx("input",{ref:y,type:"text",className:"skill-dropdown__search-input",placeholder:"搜索 Skill...",value:k,onChange:V=>{S(V.target.value),f(0)},onMouseDown:V=>V.stopPropagation(),onKeyDown:V=>V.stopPropagation()})}),p.jsx("div",{ref:D,className:"skill-dropdown__list",children:ee.map((V,ie)=>{const Se=V.id===e,Me=ie===I;return p.jsxs("div",{className:`skill-dropdown__item ${Se?"skill-dropdown__item--selected":""} ${Me?"skill-dropdown__item--highlighted":""}`,onClick:()=>g(V),onMouseEnter:()=>f(ie),children:[p.jsx("span",{className:"skill-dropdown__item-label",children:V.name}),V.outputType==="image"&&p.jsx(ws,{size:12,className:"skill-dropdown__item-image-icon"}),V.outputType==="video"&&p.jsx(Is,{size:12,className:"skill-dropdown__item-image-icon"}),V.outputType==="ppt"&&p.jsx(wr,{size:12,className:"skill-dropdown__item-image-icon"}),V.outputType==="audio"&&p.jsx(Ir,{size:12,className:"skill-dropdown__item-image-icon"}),V.isSystem&&p.jsx("span",{className:"skill-dropdown__item-badge",children:"系统"}),V.isExternal&&p.jsx("span",{className:"skill-dropdown__item-badge",children:"系统"}),Se&&p.jsx(so,{size:14,className:"skill-dropdown__item-check"})]},V.id)})}),p.jsx("div",{className:"skill-dropdown__divider"}),p.jsxs("div",{className:"skill-dropdown__add-btn",onClick:N,onMouseDown:V=>V.preventDefault(),children:[p.jsx(yr,{size:14}),p.jsx("span",{children:"添加 Skill"})]})]}),document.body)]})})},cs=["image","video","audio"];function Aa(e){if(e==="image"||e==="video"||e==="audio")return e}function Ct(e){if(!e)return[];const n=Aa(e.outputType);if(n)return[n];if(e.outputType==="text")return[];const t=new Set,s=Zr(e.mcpTool);s&&t.add(s);const d=[e.id,e.name,e.description,e.content].filter(Boolean).join(`
|
|
7
|
+
`);if(d)for(const c of cs)Da(c).some(h=>d.includes(h))&&t.add(c);return cs.filter(c=>t.has(c))}function Da(e){switch(e){case"image":return["generate_image","generate_grid_image","generate_photo_wall","generate_inspiration_board"];case"video":return["generate_video","generate_long_video"];case"audio":return["generate_audio"]}}var We=(e=>(e.VIDEO="视频创作",e.IMAGE="图片生成",e.MINDMAP="思维导图",e.FLOWCHART="流程图",e.GRID="宫格图",e.SVG="SVG矢量图",e))(We||{});const Qt=3,ls=[{id:"grid-emoji",title:"智能拆分宫格图",description:"宫格图,风格统一",prompt:"生成16宫格猫咪表情包",category:We.GRID,imageUrl:"https://tuziphoto.codernote.club/aitu/gonggetu.jpg",badgeColor:"badge--grid"},{id:"flowchart-process",title:"业务流程图",description:"使用 Mermaid 语法生成清晰的流程图",prompt:"绘制一个用户注册登录的流程图,包含邮箱验证、密码校验、短信验证码、登录成功/失败等节点",category:We.FLOWCHART,imageUrl:"https://tuziphoto.codernote.club/aitu/liuchengtu.png",badgeColor:"badge--flowchart"},{id:"mindmap-project",title:"项目规划脑图",description:"快速生成结构化的思维导图,梳理项目计划",prompt:"创建一个关于「移动应用开发」的思维导图,包含需求分析、UI设计、前端开发、后端开发、测试上线等主要分支",category:We.MINDMAP,imageUrl:"https://tuziphoto.codernote.club/aitu/siweidaotu.png",badgeColor:"badge--mindmap"}],Ra={[We.VIDEO]:{bg:"#fce7f3",text:"#be185d"},[We.IMAGE]:{bg:"#dbeafe",text:"#1d4ed8"},[We.MINDMAP]:{bg:"#dcfce7",text:"#15803d"},[We.FLOWCHART]:{bg:"#fef3c7",text:"#b45309"},[We.GRID]:{bg:"#f3e8ff",text:"#7c3aed"},[We.SVG]:{bg:"#e0e7ff",text:"#4338ca"}},Na=({template:e,onClick:n})=>{const t=Ra[e.category],s=d=>{d.preventDefault()};return p.jsxs("div",{className:"inspiration-card",onMouseDown:s,onClick:n,"data-track":`inspiration_click_${e.id}`,children:[p.jsxs("div",{className:"inspiration-card__image-wrapper",children:[p.jsx("img",{src:e.imageUrl,alt:e.title,className:"inspiration-card__image",loading:"lazy"}),p.jsx("span",{className:"inspiration-card__badge",style:{backgroundColor:t.bg,color:t.text},children:e.category}),p.jsx("div",{className:"inspiration-card__hover-overlay",children:p.jsx("div",{className:"inspiration-card__arrow",children:p.jsx(xr,{size:16})})})]}),p.jsxs("div",{className:"inspiration-card__content",children:[p.jsx("h3",{className:"inspiration-card__title",children:e.title}),p.jsx("p",{className:"inspiration-card__description",children:e.description})]})]})},ds="aitu_hide_inspiration_board",ja=({isCanvasEmpty:e,onSelectPrompt:n,onOpenPromptTool:t,visible:s=!0,className:d=""})=>{const[c,a]=r.useState(0),[h,u]=r.useState(!1);r.useEffect(()=>{localStorage.getItem(ds)==="true"&&u(!0)},[]);const l=Math.ceil(ls.length/Qt),v=l>1,k=ls.slice(c*Qt,(c+1)*Qt),S=r.useCallback(y=>{y.preventDefault(),y.stopPropagation(),a(C=>(C-1+l)%l)},[l]),I=r.useCallback(y=>{y.preventDefault(),y.stopPropagation(),a(C=>(C+1)%l)},[l]),f=r.useCallback(y=>{n({prompt:y,modelType:"agent"})},[n]),D=r.useCallback(y=>{y.preventDefault(),y.stopPropagation(),u(!0),localStorage.setItem(ds,"true")},[]);return!e||!s||h?null:p.jsxs("div",{className:`inspiration-board ${d}`,children:[p.jsxs("div",{className:"inspiration-board__header",children:[p.jsx("h3",{className:"inspiration-board__title",children:"灵感创意"}),p.jsxs("button",{className:"inspiration-board__hide-btn",onClick:D,onMouseDown:y=>y.preventDefault(),title:"不再提示","data-track":"inspiration_click_hide",children:[p.jsx(_r,{size:14}),p.jsx("span",{children:"不再提示"})]}),t&&p.jsxs("button",{className:"inspiration-board__prompt-btn",onClick:t,onMouseDown:y=>y.preventDefault(),title:"提示词工具","data-track":"inspiration_click_prompt_tool",children:[p.jsx(br,{size:14}),p.jsx("span",{children:"提示词"})]}),v&&p.jsxs("div",{className:"inspiration-board__pagination",children:[p.jsxs("span",{className:"inspiration-board__page-indicator",children:[c+1," / ",l]}),p.jsxs("div",{className:"inspiration-board__nav-buttons",children:[p.jsx("button",{className:"inspiration-board__nav-btn",onMouseDown:y=>y.preventDefault(),onClick:S,"aria-label":"上一页","data-track":"inspiration_click_prev",children:p.jsx(vr,{size:16})}),p.jsx("button",{className:"inspiration-board__nav-btn",onMouseDown:y=>y.preventDefault(),onClick:I,"aria-label":"下一页","data-track":"inspiration_click_next",children:p.jsx(Sr,{size:16})})]})]})]}),p.jsxs("div",{className:"inspiration-board__grid",children:[k.map(y=>p.jsx(Na,{template:y,onClick:()=>f(y.prompt)},y.id)),k.length<Qt&&Array.from({length:Qt-k.length}).map((y,C)=>p.jsx("div",{className:"inspiration-card inspiration-card--placeholder"},`placeholder-${C}`))]})]})},ut=[{value:"image",label:"图片",icon:p.jsx(ws,{size:14}),zh:"图片",en:"Image"},{value:"video",label:"视频",icon:p.jsx(Is,{size:14}),zh:"视频",en:"Video"},{value:"audio",label:"音频",icon:p.jsx(Mr,{size:14}),zh:"音频",en:"Audio"},{value:"text",label:"文本",icon:p.jsx(Cr,{size:14}),zh:"文本",en:"Text"},{value:"agent",label:"Agent",icon:p.jsx(Tr,{size:14}),zh:"Agent",en:"Agent"}],za=({value:e,onSelect:n,disabled:t=!1})=>{const[s,d]=r.useState(!1),{language:c}=ro(),[a,h]=r.useState(0),u=r.useRef(null);r.useEffect(()=>{if(s){const I=ut.findIndex(f=>f.value===e);h(I>=0?I:0)}},[s,e]),r.useEffect(()=>{if(s&&u.current){const I=u.current.children[a];I&&I.scrollIntoView({block:"nearest"})}},[a,s]);const l=r.useCallback(I=>{I.preventDefault(),!t&&d(f=>!f)},[t]),v=r.useCallback(I=>{n(I),d(!1)},[n]),k=r.useCallback(I=>I==="Escape"?(d(!1),!0):I==="ArrowDown"?(h(f=>f<ut.length-1?f+1:0),!0):I==="ArrowUp"?(h(f=>f>0?f-1:ut.length-1),!0):I==="Enter"||I===" "||I==="Tab"?(v(ut[a].value),!0):!1,[a,v]),S=ut.find(I=>I.value===e)||ut[0];return p.jsx(ao,{isOpen:s,setIsOpen:d,disabled:t,openKeys:["Enter"," ","ArrowDown","ArrowUp"],onOpenKey:k,children:({containerRef:I,menuRef:f,portalPosition:D,handleTriggerKeyDown:y})=>p.jsxs("div",{className:"generation-type-dropdown",ref:I,children:[p.jsxs("button",{className:`generation-type-dropdown__trigger ${s?"generation-type-dropdown__trigger--open":""}`,onMouseDown:l,onKeyDown:y,disabled:t,type:"button",title:`${c==="zh"?"生成类型":"Type"}: ${c==="zh"?S.zh:S.en} (↑↓ Tab)`,children:[p.jsx("span",{className:"generation-type-dropdown__icon-prefix",children:S.icon}),p.jsx("span",{className:"generation-type-dropdown__label",children:c==="zh"?S.zh:S.en}),p.jsx(no,{size:14,className:`generation-type-dropdown__chevron ${s?"generation-type-dropdown__chevron--open":""}`})]}),s&&to.createPortal(p.jsxs("div",{ref:f,className:`generation-type-dropdown__menu ${Tn}`,style:{position:"fixed",zIndex:oo.DROPDOWN_PORTAL,left:D.left,bottom:window.innerHeight-D.top+8},onMouseDown:C=>C.stopPropagation(),onClick:C=>C.stopPropagation(),children:[p.jsxs("div",{className:"generation-type-dropdown__header",children:[p.jsx(kr,{size:14}),p.jsx("span",{children:c==="zh"?"生成类型 (↑↓ Tab)":"Generation type (↑↓ Tab)"})]}),p.jsx("div",{ref:u,className:"generation-type-dropdown__list",children:ut.map((C,E)=>{const P=C.value===e,g=E===a;return p.jsxs("div",{className:`generation-type-dropdown__item ${P?"generation-type-dropdown__item--selected":""} ${g?"generation-type-dropdown__item--highlighted":""}`,onClick:()=>v(C.value),onMouseEnter:()=>h(E),children:[p.jsx("span",{className:"generation-type-dropdown__item-icon",children:C.icon}),p.jsx("span",{className:"generation-type-dropdown__item-label",children:c==="zh"?C.zh:C.en}),P&&p.jsx(so,{size:14,className:"generation-type-dropdown__item-check"})]},C.value)})})]}),document.body)]})})},en=[1,2,3,4,5,10,20],Oa=({value:e,onSelect:n,disabled:t=!1,isOpen:s,onOpenChange:d})=>{const{value:c,setValue:a}=qr({controlledValue:s,defaultValue:!1,onChange:d}),{language:h}=ro(),[u,l]=r.useState(0),v=r.useRef(null);r.useEffect(()=>{if(c){const f=en.indexOf(e);l(f>=0?f:0)}},[c,e]),r.useEffect(()=>{if(c&&v.current){const f=v.current.children[u];f&&f.scrollIntoView({block:"nearest"})}},[u,c]);const k=r.useCallback(f=>{f.preventDefault(),!t&&a(!c)},[t,c,a]),S=r.useCallback(f=>{n(f),a(!1)},[n]),I=r.useCallback(f=>f==="Escape"?(a(!1),!0):f==="ArrowDown"?(l(D=>D<en.length-1?D+1:0),!0):f==="ArrowUp"?(l(D=>D>0?D-1:en.length-1),!0):f==="Enter"||f===" "||f==="Tab"?(S(en[u]),!0):!1,[u,S]);return p.jsx(ao,{isOpen:c,setIsOpen:a,disabled:t,openKeys:["Enter"," ","ArrowDown","ArrowUp"],onOpenKey:I,children:({containerRef:f,menuRef:D,portalPosition:y,handleTriggerKeyDown:C})=>p.jsxs("div",{className:"count-dropdown",ref:f,children:[p.jsxs("button",{className:`count-dropdown__trigger ${c?"count-dropdown__trigger--open":""}`,onMouseDown:k,onKeyDown:C,disabled:t,type:"button",title:`${h==="zh"?"生成数量":"Count"}: ${e} (↑↓ Tab)`,children:[p.jsxs("span",{className:"count-dropdown__label",children:[e,h==="zh"?"个":""]}),p.jsx(no,{size:14,className:`count-dropdown__chevron ${c?"count-dropdown__chevron--open":""}`})]}),c&&to.createPortal(p.jsxs("div",{ref:D,className:`count-dropdown__menu ${Tn}`,style:{position:"fixed",zIndex:oo.DROPDOWN_PORTAL,left:y.left,bottom:window.innerHeight-y.top+8},onMouseDown:E=>E.stopPropagation(),onClick:E=>E.stopPropagation(),children:[p.jsx("div",{className:"count-dropdown__header",children:p.jsx("span",{children:h==="zh"?"生成数量 (↑↓ Tab)":"Count (↑↓ Tab)"})}),p.jsx("div",{ref:v,className:"count-dropdown__list",children:en.map((E,P)=>{const g=E===e,N=P===u;return p.jsxs("div",{className:`count-dropdown__item ${g?"count-dropdown__item--selected":""} ${N?"count-dropdown__item--highlighted":""}`,onClick:()=>S(E),onMouseEnter:()=>l(P),children:[p.jsxs("span",{className:"count-dropdown__item-label",children:[E,h==="zh"?"个":E>1?" items":" item"]}),g&&p.jsx(so,{size:14,className:"count-dropdown__item-check"})]},E)})})]}),document.body)]})})},bs=["right","bottom","left","top"],vn=4;function Wa(e,n,t,s,d=32){const c=s<=2?s:s<=4?2:3,a=Math.floor(t/c),h=t%c;return[e[0]+h*(n.width+d),e[1]+a*(n.height+d)]}function vs(e,n){const{ignoreElementIds:t=[],ignoreTypes:s=["workzone"],extraOccupiedRects:d=[]}=n;return[...e.children.filter(La).filter(c=>!s.includes(c.type??"")&&!t.includes(c.id??"")).map(c=>({...kn.getRectangleByPoints(c.points),id:c.id,type:c.type})),...d]}function La(e){return typeof e=="object"&&e!==null&&Array.isArray(e.points)&&e.points.length===2}function Ss(e,n,t){return e.x<n.x+n.width+t&&e.x+e.width+t>n.x&&e.y<n.y+n.height+t&&e.y+e.height+t>n.y}function Fa(e,n,t,s){const d=[e];for(let c=1;c<=s;c+=1)d.push([e[0]+n*c,e[1]],[e[0],e[1]+t*c],[e[0]+n*c,e[1]+t*c],[e[0]-n*c,e[1]],[e[0]-n*c,e[1]+t*c],[e[0],e[1]-t*c],[e[0]+n*c,e[1]-t*c],[e[0]-n*c,e[1]-t*c]);return d}function Ba(e,n,t,s,d){const c=Math.max(d,32),a=Math.max(Math.round(Math.min(n.width,n.height)*.16),28),h=Math.max(Math.round(Math.min(n.width,n.height)*.12),18),u=n.width+a,l=n.height+a,v=[];for(let k=0;k<t;k+=1){const S=Math.floor(k/vn),I=k%vn,f=Math.min(vn,t-S*vn),D=I-(f-1)/2,y=e.x+e.width/2-n.width/2,C=e.y+e.height/2-n.height/2,E=Math.abs(D)*h;let P=y,g=C;switch(s){case"right":P=e.x+e.width+c+S*u+E,g=C+D*(n.height+a);break;case"left":P=e.x-c-n.width-S*u-E,g=C+D*(n.height+a);break;case"top":P=y+D*(n.width+a),g=e.y-c-n.height-S*l-E;break;case"bottom":default:P=y+D*(n.width+a),g=e.y+e.height+c+S*l+E;break}v.push([Math.round(P),Math.round(g)])}return v}function us(e,n,t,s,d){return e.reduce((a,h)=>{const u={x:h[0],y:h[1],width:n.width,height:n.height};return a+t.filter(l=>Ss(u,l,s)).length},0)*1e3+bs.indexOf(d)*10}function Ha(e,n,t,s,d){var l;const{gap:c=40,padding:a=16}=d,h=vs(e,d),u=bs.map(v=>({side:v,positions:Ba(n,t,s,v,c)}));return u.sort((v,k)=>us(v.positions,t,h,a,v.side)-us(k.positions,t,h,a,k.side)),((l=u[0])==null?void 0:l.positions)??[]}function $a(e,n,t,s,d={}){const{frameRect:c,extraOccupiedRects:a=[],...h}=d,u={...h,extraOccupiedRects:a},l=c?Ha(e,c,t,s,u):Array.from({length:s},(k,S)=>Wa(n,t,S,s,u.gap)),v=[...a];return l.map(k=>{const S=Ua(e,k,t,{...u,extraOccupiedRects:v});return v.push({x:S[0],y:S[1],width:t.width,height:t.height}),S})}function Ua(e,n,t,s={}){const{gap:d=40,padding:c=16,maxSearchRadius:a=6}=s,h=vs(e,s),u=t.width+d,l=t.height+d,v=Fa(n,u,l,a);for(const k of v){const S={x:k[0],y:k[1],width:t.width,height:t.height};if(!h.some(f=>Ss(S,f,c)))return k}return[n[0],n[1]+l*(a+1)]}function ht(e){return typeof e=="string"&&e.trim()?e.trim():null}function Va(e){return e==="image"||e==="video"||e==="audio"||e==="text"||e==="agent"}function Ga(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.modelId=="string"&&n.modelId.trim().length>0&&(n.profileId===null||typeof n.profileId=="string")&&(n.providerIdHint===null||typeof n.providerIdHint=="string")&&(n.vendorHint===null||typeof n.vendorHint=="string")&&typeof n.updatedAt=="number"&&Number.isFinite(n.updatedAt)}function io(){try{const e=window.localStorage.getItem(Qn);if(!e)return{};const n=JSON.parse(e);if(!n||typeof n!="object")return{};const t={};return Object.entries(n).forEach(([s,d])=>{Va(s)&&Ga(d)&&(t[s]={modelId:d.modelId.trim(),profileId:ht(d.profileId),providerIdHint:ht(d.providerIdHint),vendorHint:ht(d.vendorHint),updatedAt:d.updatedAt})}),t}catch{return{}}}function ks(e){try{if(!Object.values(e).some(Boolean)){window.localStorage.removeItem(Qn);return}window.localStorage.setItem(Qn,JSON.stringify(e))}catch{}}function Ka(e){const n=io();return n[e]?n[e]||null:e==="agent"&&n.text||null}function ps(e,n){var d;const t=ht(n.modelId);if(!t){Ms(e);return}const s=io();s[e]={modelId:t,profileId:ht((d=n.modelRef)==null?void 0:d.profileId),providerIdHint:ht(n.providerIdHint),vendorHint:ht(n.vendorHint),updatedAt:Date.now()},ks(s)}function Ms(e){const n=io();n[e]&&(delete n[e],ks(n))}function Qe(e,n,t,s){var c;const d=e.metadata||{};return{id:e.id,name:e.name,generationType:e.generationType,prompt:d.prompt||((c=n==null?void 0:n.aiContext)==null?void 0:c.finalPrompt)||"",aiAnalysis:e.aiAnalysis,count:d.count,createdAt:e.createdAt,status:e.status,steps:e.steps.map(a=>({id:a.id,description:a.description,status:a.status,mcp:a.mcp,args:a.args,result:a.result,error:a.error,duration:a.duration,options:a.options})),retryContext:n,postProcessingStatus:t,insertedCount:s}}function Ya(e,n){return e==="generate_image"?"image":e==="generate_video"||e==="generate_long_video"?"video":e==="generate_audio"?"audio":e==="generate_text"?"text":n.scenarioType==="skill_flow"||n.generationType==="agent"?"agent":n.generationType==="image"||n.generationType==="video"||n.generationType==="audio"||n.generationType==="text"?n.generationType:"agent"}function Xa(e,n){const t=typeof n.args.prompt=="string"?n.args.prompt.trim():e.metadata.prompt.trim(),s=(e.metadata.rawInput||e.metadata.userInstruction||e.metadata.prompt||t).trim().slice(0,2e3),d=e.scenarioType==="skill_flow"?e.name.trim():void 0,c=Ya(n.mcp,e);return{initialPrompt:s,sentPrompt:t.slice(0,2e3),category:c,skillId:e.skillId,skillName:d,tags:[c,d].filter(Boolean)}}function Sn(e,n){return n.args.promptMeta||!["generate_image","generate_video","generate_long_video","generate_audio","generate_text"].includes(n.mcp)?n:{...n,args:{...n.args,promptMeta:Xa(e,n)}}}let ms=!1;ms||(ta(),ya(),eo.initialize().catch(e=>{console.warn("[AIInputBar] 外部 Skill 服务初始化失败(非致命):",e)}),ms=!0);function Cs(e){return e.selectionKey||(e.sourceProfileId?`${e.sourceProfileId}::${e.id}`:e.id)}function ze(e,n){return n!=null&&n.profileId?`${n.profileId}::${e}`:e}function Oe(e){return e?mt(e.sourceProfileId||null,e.id):null}function Xn(e){return e<=0?"0":e<=20?"1-20":e<=100?"21-100":e<=300?"101-300":e<=800?"301-800":"800+"}const Za=1,Ts=4,qa=6,Ja=1.5;function hs(e,n){const t=window.getComputedStyle(e),s=Number.parseFloat(t.fontSize)||15,d=Number.parseFloat(t.lineHeight)||s*Ja,c=Number.parseFloat(t.paddingTop)+Number.parseFloat(t.paddingBottom),a=Number.parseFloat(t.borderTopWidth)+Number.parseFloat(t.borderBottomWidth);return Math.ceil(d*n+c+a)}function Qa(e,n){if(!e)return;if(!n){e.style.height="",e.style.overflowY="";return}const t=hs(e,Ts),s=hs(e,qa);e.style.height="auto";const d=e.scrollHeight,c=Math.min(Math.max(d,t),s);e.style.height=`${c}px`,e.style.overflowY=d>s?"auto":"hidden"}function xe(e,n,t){if(!n)return;const s=ze(n,t),d=(t==null?void 0:t.profileId)||null;return e.find(c=>Cs(c)===s)||e.find(c=>c.id===n&&(c.sourceProfileId||null)===d)||(d===null?e.find(c=>c.id===n&&!c.sourceProfileId):void 0)||e.find(c=>c.id===n)}function ei(e,n){return e==="agent"&&n==="text"?"agent":n}function ti(e){if(!e)return!1;const n=e.toLowerCase();return n.includes("#video")?!0:[".mp4",".webm",".mov",".avi",".mkv",".m4v",".flv",".wmv"].some(s=>n.includes(s))}const Ps=ys.memo(({language:e,onSelectionChange:n,externalBoardRef:t,onCanvasEmptyChange:s,isDataReady:d,onFrameSelected:c})=>{const a=$r(),h=r.useRef(a);h.current=a,r.useEffect(()=>(Xo(a),Zo(a),qo(a),es(a),rs.setBoard(a),t&&(t.current=a),()=>{Xo(null),Zo(null),qo(null),es(null),rs.setBoard(null),t&&(t.current=null)}),[a,t]);const u=r.useRef(s);u.current=s,r.useEffect(()=>{if(!a||!u.current||!d)return;const S=setInterval(()=>{var f;const I=a.children||[];(f=u.current)==null||f.call(u,I.length===0)},500);return()=>{clearInterval(S)}},[a,d]);const l=r.useRef(n);l.current=n;const v=r.useRef(c);return v.current=c,r.useEffect(()=>{const k=async()=>{var D,y,C,E;const I=h.current;if(!I)return;const f=xs(I);if(f.length===1&&_s(f[0])){const P=f[0],g=kn.getRectangleByPoints(P.points);(D=v.current)==null||D.call(v,{id:P.id,width:g.width,height:g.height})}else(y=v.current)==null||y.call(v,null);if(f.length===0){l.current([]);return}try{const P=await Ur(I),g=[];P.graphicsImage&&g.push({url:P.graphicsImage,name:e==="zh"?"图形元素":"Graphics",type:"graphics",width:(C=P.graphicsImageDimensions)==null?void 0:C.width,height:(E=P.graphicsImageDimensions)==null?void 0:E.height});for(const N of P.remainingImages){const U=N.url||"",ee=ti(U);g.push({url:U,name:N.name||(ee?`video-${Date.now()}`:`image-${Date.now()}`),type:ee?"video":"image",width:N.width,height:N.height})}P.remainingText&&P.remainingText.trim()&&g.push({type:"text",text:P.remainingText.trim(),name:e==="zh"?"文字内容":"Text Content"}),l.current(g)}catch(P){console.error("Failed to process selected content:",P),l.current([])}};k();const S=()=>{setTimeout(k,50)};return document.addEventListener("mouseup",S),()=>{document.removeEventListener("mouseup",S)}},[e]),null});Ps.displayName="SelectionWatcher";const Es=ys.memo(({className:e,isDataReady:n,onEnableToolWindows:t})=>{const{language:s}=ro(),d=xn("image"),c=xn("video"),a=xn("audio"),h=xn("text"),u=Pr(),l=Vr(),{addHistory:v}=fs(),{addAsset:k}=Er(),S=r.useRef(u.sendWorkflowMessage);S.current=u.sendWorkflowMessage;const I=r.useRef(u.updateWorkflowMessage);I.current=u.updateWorkflowMessage;const f=r.useRef(u.appendAgentLog);f.current=u.appendAgentLog;const D=r.useRef(u.updateThinkingContent);D.current=u.updateThinkingContent;const y=r.useRef(u.setSelectedContent);y.current=u.setSelectedContent;const C=r.useRef(u.registerRetryHandler);C.current=u.registerRetryHandler;const E=r.useRef(null),P=r.useRef([]),g=r.useRef(null),N=ua(),U=r.useCallback((o,i,m)=>{if(!o)return;const w=P.current,b=(m!=null&&m.workflowId&&(m!=null&&m.batchId)&&typeof m.batchIndex=="number"?lt.getAnchorByBatchSlot(o,{workflowId:m.workflowId,batchId:m.batchId,batchIndex:m.batchIndex}):null)||(m!=null&&m.workflowId?lt.getAnchorByWorkflowId(o,m.workflowId):null)||(w[0]?lt.getAnchorById(o,w[0]):null);if(!b)return;const T=b.taskIds.includes(i)?b.taskIds:[...b.taskIds,i];lt.updateAnchor(o,b.id,{taskIds:T,primaryTaskId:b.primaryTaskId||i})},[]),ee=r.useCallback((o,i,m)=>{const w=P.current;w.length===0||!o||w.forEach(b=>{lt.updateAnchor(o,b,$n(i,m))})},[]),ne=r.useCallback(o=>{const i=P.current;i.length===0||!o||(i.forEach(m=>{lt.removeAnchor(o,m)}),P.current=[])},[]),ae=r.useCallback((o,i)=>{const m=Ka(o);if(!m)return;const w=xe(i,m.modelId,mt(m.profileId,m.modelId));if(w)return w;Ms(o)},[]),H=r.useCallback((o,i)=>{const m=ae(o,i);if(m)return m;const b=kt(o==="video"?"video":o==="audio"?"audio":o==="text"||o==="agent"?"text":"image"),T=xe(i,b.modelId,mt(b.profileId,b.modelId));if(T)return T;const F=o==="video"?Pt():o==="audio"?Et():o==="text"||o==="agent"?qn():pt();return xe(i,F,null)||i[0]},[ae]),_=N.generationType,$=H(_,_==="video"?c:_==="audio"?a:_==="text"||_==="agent"?h:d)||Ve(N.selectedModel)||Ve(_==="video"?Pt():_==="audio"?Et():_==="text"||_==="agent"?qn():pt()),Q=H("image",d)||Ve(pt()),V=H("video",c)||Ve(Pt()),ie=H("audio",a)||Ve(Et()),Se=kt("image"),Me=(Q==null?void 0:Q.id)||Se.modelId||pt(),Dt=Oe(Q)||mt(Se.profileId,Se.modelId),nn=ze(($==null?void 0:$.id)||Me,Oe($)||Dt),co=_==="agent"?{}:Kn(_,($==null?void 0:$.id)||Me,nn,N.selectedParams),[fe,tt]=r.useState(""),[As,Ds]=r.useState(!1),[Pn,En]=r.useState([]),[Rt,ft]=r.useState([]),[Le,nt]=r.useState(!1),we=r.useRef(null),[Nt,ot]=r.useState(!1),[Rs,Ns]=r.useState(null),[x,Fe]=r.useState(_),[Ie,An]=r.useState(N.selectedSkillId||et),[O,lo]=r.useState(($==null?void 0:$.id)||Me),[L,uo]=r.useState(Oe($)||Dt),[Be,po]=r.useState((Q==null?void 0:Q.id)||pt()),[Ge,mo]=r.useState(Oe(Q)),[He,ho]=r.useState((V==null?void 0:V.id)||Pt()),[Ke,fo]=r.useState(Oe(V)),[$e,go]=r.useState((ie==null?void 0:ie.id)||Et()),[Ye,wo]=r.useState(Oe(ie)),[Dn,Xe]=r.useState([]),on=r.useMemo(()=>{if(x!=="image"||xe(d,O,L))return d;const i=dt("image",O,L);return i?[i,...d]:d},[x,d,O,L]),sn=r.useMemo(()=>{if(x!=="video"||xe(c,O,L))return c;const i=dt("video",O,L);return i?[i,...c]:c},[x,O,L,c]),rn=r.useMemo(()=>{if(x!=="audio"||xe(a,O,L))return a;const i=dt("audio",O,L);return i?[i,...a]:a},[a,x,O,L]),an=r.useMemo(()=>{if(x!=="text"&&x!=="agent"||xe(h,O,L))return h;const i=dt("text",O,L);return i?[i,...h]:h},[x,O,L,h]),jt=r.useMemo(()=>{if(xe(d,Be,Ge))return d;const i=dt("image",Be,Ge);return i?[i,...d]:d},[d,Be,Ge]),zt=r.useMemo(()=>{if(xe(c,He,Ke))return c;const i=dt("video",He,Ke);return i?[i,...c]:c},[He,Ke,c]),Ot=r.useMemo(()=>{if(xe(a,$e,Ye))return a;const i=dt("audio",$e,Ye);return i?[i,...a]:a},[a,$e,Ye]),[Ce,cn]=r.useState(()=>{if(_==="agent")return{};const o=($==null?void 0:$.id)||Me,i=Lo(o).find(m=>m.id==="size");return{...co,...o.startsWith("mj")||!i?{}:{size:co.size||Fo(o)}}}),Wt=r.useRef(Ce),Io=r.useRef(_==="agent"?"agent":`${_}:${nn}`);r.useEffect(()=>{Wt.current=Ce},[Ce]);const[Lt,yo]=r.useState(N.selectedCount),[xo,Rn]=r.useState(!1),[_o,Nn]=r.useState(!1),[bo,jn]=r.useState(!1),st=r.useRef(null),js=r.useCallback(o=>{Rn(o),o||(st.current=null)},[]),zs=r.useCallback(o=>{Nn(o),o||(st.current=null)},[]),Os=r.useCallback(o=>{jn(o),o||(st.current=null)},[]),[vo,Ft]=r.useState(!1),ce=r.useMemo(()=>[...Rt,...Pn],[Rt,Pn]),rt=r.useMemo(()=>({invalidFile:s==="zh"?"请上传图片文件":"Please upload image files",fileTooLarge:s==="zh"?"图片大小不能超过 25MB":"Image size cannot exceed 25MB",loadFailed:s==="zh"?"加载图片失败":"Failed to load image",compressionFailed:s==="zh"?"图片压缩失败":"Image compression failed",compressing:o=>s==="zh"?`正在压缩图片 (${o.toFixed(1)}MB)...`:`Compressing image (${o.toFixed(1)}MB)...`,compressed:(o,i)=>s==="zh"?`压缩完成: ${o.toFixed(1)}MB → ${i.toFixed(1)}MB`:`Compressed: ${o.toFixed(1)}MB → ${i.toFixed(1)}MB`}),[s]);r.useEffect(()=>{const o=x==="video"?sn:x==="audio"?rn:x==="text"||x==="agent"?an:on,m=xe(o,O,L)||H(x,o);if(m){const w=ze(O,L),b=Cs(m);w!==b&&(lo(m.id),uo(Oe(m)))}x!=="agent"&&An(et),(x==="agent"||x==="text"||x==="audio")&&yo(1)},[rn,x,on,H,O,L,an,sn]),r.useEffect(()=>{const o=(i,m,w,b,T,F)=>{if(xe(m,w,b))return;const z=H(i,m);z&&(T(z.id),F(Oe(z)))};o("image",jt,Be,Ge,po,mo),o("video",zt,He,Ke,ho,fo),o("audio",Ot,$e,Ye,go,wo)},[H,$e,Ye,Be,Ge,He,Ke,Ot,jt,zt]);const ln=r.useMemo(()=>x==="video"?sn:x==="audio"?rn:x==="text"||x==="agent"?an:on,[rn,x,on,an,sn]);r.useEffect(()=>{let o=!1;return(async()=>{var F;if(x!=="agent"||Ie===et){Xe([]);return}const m=Vn(Ie);if(m){Xe(Ct(m));return}const w=Ho(Ie);if(w){Xe(Ct(w));return}const b=await eo.getSkillById(Ie);if(o)return;if(b){Xe(Ct(b));return}const T=await Mn.getNoteById(Ie);o||Xe(T?Ct({id:T.id,name:T.title,content:T.content,outputType:(F=T.metadata)==null?void 0:F.outputType}):[])})().catch(()=>{o||Xe([])}),()=>{o=!0}},[x,Ie]);const Bt=r.useMemo(()=>{var m;if(x==="agent")return[];if(x==="video")return Ar(O,L||O,Ce);const o=Lo(O);return x!=="audio"?o:(Ce.sunoAction||((m=o.find(w=>w.id==="sunoAction"))==null?void 0:m.defaultValue)||"music")==="lyrics"?o.filter(w=>w.id==="sunoAction"||w.id==="mv"||w.id==="title"||w.id==="tags"):o},[x,O,L,Ce]);r.useEffect(()=>{if(!Nt)return;const o=i=>{const m=i.target;un.current&&!un.current.contains(m)&&ot(!1)};return document.addEventListener("mousedown",o),()=>document.removeEventListener("mousedown",o)},[Nt]),r.useEffect(()=>()=>{we.current&&clearTimeout(we.current)},[]),r.useEffect(()=>{const o=i=>{var m;((m=i.detail)==null?void 0:m.type)!=="image"&&(we.current&&(clearTimeout(we.current),we.current=null),nt(!1))};return window.addEventListener("ai-generation-complete",o),()=>{window.removeEventListener("ai-generation-complete",o)}},[]),r.useEffect(()=>{const o=gs.observeTaskUpdates().subscribe(i=>{var z,Y;const m=i.task,w=l.getWorkflow();if(!w)return;const b=w.steps.find(B=>{const q=B.result;return(q==null?void 0:q.taskId)===m.id});if(!b)return;let T=b.status,F=b.result,Z=b.error;switch(m.status){case Tt.PENDING:case Tt.PROCESSING:T="running";break;case Tt.COMPLETED:T="completed",F={...typeof F=="object"?F:{},taskId:m.id,result:m.result};break;case Tt.FAILED:T="failed",Z=((z=m.error)==null?void 0:z.message)||"任务执行失败";break;case Tt.CANCELLED:T="skipped";break}if(T!==b.status){if(l.updateStep(b.id,T,F,Z),T==="failed"){const q=(Y=b.options)==null?void 0:Y.batchId;q&&w.steps.forEach(oe=>{var ye;oe.id!==b.id&&((ye=oe.options)==null?void 0:ye.batchId)===q&&oe.status==="running"&&l.updateStep(oe.id,"skipped",void 0,"前置任务失败")})}const B=l.getWorkflow();if(B){const q=Qe(B,E.current||void 0);I.current(q);const oe=g.current,ye=De.current;oe&&ye&&je.updateWorkflow(ye,oe,q)}}});return()=>o.unsubscribe()},[l]);const So=r.useRef(void 0),dn=r.useRef(void 0);r.useEffect(()=>{const o=Un.observeCompletionEvents().subscribe(i=>{const m=l.getWorkflow(),w=m==null?void 0:m.steps.find(F=>{const Z=F.result;return(Z==null?void 0:Z.taskId)===i.taskId});let b,T;switch(i.type){case"postProcessingStarted":b="processing";break;case"postProcessingCompleted":b="completed",T=i.result.insertedCount;break;case"postProcessingFailed":b="failed";break}if(So.current=b,T!==void 0&&(dn.current=(dn.current||0)+T),m&&w){const F=l.getWorkflow();if(F){const Z=Qe(F,E.current||void 0,b,dn.current);I.current(Z);const z=g.current,Y=De.current;z&&Y&&je.updateWorkflow(Y,z,Z)}}if(i.type==="postProcessingCompleted"){const F=i.result.firstElementPosition;we.current&&(clearTimeout(we.current),we.current=null),nt(!1),setTimeout(async()=>{var Y;u.closeChatDrawer();const Z=g.current,z=De.current;if(Z&&z){const B=l.getWorkflow();if(B==null?void 0:B.steps.every(oe=>oe.status==="completed"||oe.status==="failed"||oe.status==="skipped")){const{workflowCompletionService:oe}=await Jo(async()=>{const{workflowCompletionService:te}=await import("./startup-app-CiOE0Z0l.js").then(ke=>ke.mh);return{workflowCompletionService:te}},__vite__mapDeps([0]),import.meta.url);(B==null?void 0:B.steps.every(te=>{const ke=te.result;return ke!=null&&ke.taskId?oe.isPostProcessingCompleted(ke.taskId):!0}))&&(je.removeWorkZone(z,Z),g.current=null)}}if(F&&z){const B=(Y=z.host)==null?void 0:Y.getBoundingClientRect();if(B){const q=z.viewport.zoom,oe=F[0]-B.width/(2*q),ye=F[1]-B.height/(2*q);Dr.updateViewport(z,[oe,ye],q)}}},500),So.current=void 0,dn.current=void 0}});return()=>o.unsubscribe()},[l,u]);const De=r.useRef(null),{submitWorkflow:ko}=Gr({boardRef:De,workZoneIdRef:g}),Te=r.useRef(null),un=r.useRef(null),Mo=r.useRef(null);Jr(Te,{enableCopy:!0,stopPropagation:!0}),r.useEffect(()=>{const o=i=>{const m=i.detail;if(m!=null&&m.generationType&&Fe(m.generationType),m!=null&&m.skillId){An(m.skillId);const w=Vn(m.skillId);w&&Xe(Ct(w))}ot(!0),requestAnimationFrame(()=>{var w;(w=Te.current)==null||w.focus()})};return window.addEventListener(Qo,o),()=>{window.removeEventListener(Qo,o)}},[]);const Ws=r.useCallback(o=>{var i;tt(o.prompt),Fe("agent"),(i=Te.current)==null||i.focus(),Ae.track("inspiration_selected",{promptLength:o.prompt.length,modelType:o.modelType})},[]),Ls=r.useCallback(o=>{var i;tt(o.content),o.modelType&&(o.modelType==="image"?Fe("image"):o.modelType==="video"?Fe("video"):o.modelType==="audio"?Fe("audio"):o.modelType==="text"?Fe("text"):o.modelType==="agent"&&Fe("agent")),(i=Te.current)==null||i.focus()},[]),Fs=r.useCallback(()=>{const o=Zn.find(i=>i.id==="knowledge-base");o&&(window.__kbPendingNavigation={directoryName:"Skill",autoCreateNote:!0},tn.openTool(o),setTimeout(()=>{window.dispatchEvent(new CustomEvent("kb:navigate",{detail:{directoryName:"Skill",autoCreateNote:!0}}))},300))},[]),Co=r.useCallback((o="ai_input_bar")=>{const i=Zn.find(m=>m.id==="banana-prompt");if(!i){console.warn("[AIInputBar] Banana prompt tool not found"),Ae.trackPromptAction({action:"open_tool",surface:o,promptType:x,prompt:fe,source:o,status:"failed",metadata:{tool_id:"banana-prompt",reason:"tool_not_found"}});return}Ae.trackPromptAction({action:"open_tool",surface:o,promptType:x,prompt:fe,source:o,status:"success",metadata:{tool_id:i.id,tool_type:"external_prompt_library"}}),tn.openTool(i)},[x,fe]),Bs=r.useCallback(()=>{Co("inspiration_board")},[Co]),Hs=r.useCallback(async o=>{try{const i=new Image;i.onload=()=>{const m={type:"image",url:o.url,name:o.name||`素材-${Date.now()}`,width:i.naturalWidth||void 0,height:i.naturalHeight||void 0};ft(w=>[...w,m]),Ft(!1)},i.onerror=()=>{const m={type:"image",url:o.url,name:o.name||`素材-${Date.now()}`};ft(w=>[...w,m]),Ft(!1)},i.src=o.url}catch(i){console.error("Failed to select asset from library:",i),Ft(!1)}},[]),$s=r.useCallback(()=>{var o;(o=Mo.current)==null||o.click()},[]),To=r.useCallback(o=>new Promise((i,m)=>{const w=new FileReader;w.onload=()=>{const b=w.result,T=new Image;T.onload=()=>{i({url:b,width:T.naturalWidth,height:T.naturalHeight})},T.onerror=()=>{i({url:b,width:0,height:0})},T.src=b},w.onerror=m,w.readAsDataURL(o)}),[]),pn=r.useCallback(async o=>{const i=Array.from(o);if(i.length===0)return;const m=[];for(const[w,b]of i.entries()){if(!b.type.startsWith("image/")){Je.error(rt.invalidFile);continue}if(b.size>25*1024*1024){Je.error(rt.fileTooLarge);continue}try{let T=b;if(b.size>10*1024*1024){const{compressImageBlob:B,getCompressionStrategy:q}=await Jo(async()=>{const{compressImageBlob:te,getCompressionStrategy:ke}=await import("./startup-app-CiOE0Z0l.js").then(Ue=>Ue.m0);return{compressImageBlob:te,getCompressionStrategy:ke}},__vite__mapDeps([0]),import.meta.url),oe=q(b.size/(1024*1024)),ye=Je.loading({content:rt.compressing(b.size/(1024*1024)),duration:0,placement:"top"});try{T=await B(b,oe.targetSizeMB),Je.close(ye),Je.success({content:rt.compressed(b.size/(1024*1024),T.size/(1024*1024)),duration:2})}catch(te){Je.close(ye),console.error("[AIInputBar] Failed to compress image:",te),Je.error(rt.compressionFailed);continue}}const F=T instanceof File?T:new File([T],b.name||`pasted-image-${Date.now()}.png`,{type:T.type||b.type||"image/png"});k(F,Bo.IMAGE,Rr.LOCAL,F.name).catch(B=>{console.warn("[AIInputBar] Failed to add asset to library:",B)});const{url:Z,width:z,height:Y}=await To(F);m.push({type:"image",url:Z,name:F.name||`上传图片 ${w+1}`,width:z||void 0,height:Y||void 0})}catch(T){console.error("[AIInputBar] Failed to import local image:",T),Je.error(rt.loadFailed)}}m.length>0&&ft(w=>[...w,...m])},[k,To,rt]),Us=r.useCallback(async o=>{const i=o.target.files;!i||i.length===0||(await pn(i),o.target.value="")},[pn]),Vs=r.useCallback(o=>{En(o)},[]),Po=r.useRef(null),Gs=r.useCallback(o=>{if(Po.current=o,!o)return;const i=Nr(o.width,o.height,O);i&&cn(m=>({...m,size:i}))},[O]),Ks=r.useCallback(o=>{o<Rt.length&&ft(i=>i.filter((m,w)=>w!==o))},[Rt.length]);r.useEffect(()=>{y.current(ce.map(o=>({type:o.type,url:o.url,text:o.text,name:o.name})))},[ce]),r.useEffect(()=>{const o=i=>{var z,Y;const m=(z=i.clipboardData)==null?void 0:z.items;if(!m||m.length===0||!Array.from(m).some(B=>B.type.startsWith("image/")))return;const b=document.activeElement,T=un.current;if(!(!!T&&(T.contains(b)||Nt&&(b===document.body||(b==null?void 0:b.tagName)==="BODY"))))return;const Z=[];for(const B of Array.from(m)){if(!B.type.startsWith("image/"))continue;const q=B.getAsFile();q&&Z.push(q)}Z.length!==0&&(i.preventDefault(),pn(Z),(Y=Te.current)==null||Y.focus())};return document.addEventListener("paste",o),()=>{document.removeEventListener("paste",o)}},[pn,Nt]);const gt=r.useCallback(()=>{if(st.current!==null){const o=st.current;tt(i=>i.substring(0,o)+i.substring(o+1)),st.current=null}},[]),mn=r.useCallback(o=>{const i=ei(x,o.type);Ae.track("ai_input_change_model",{model:o.id,type:o.type,profileId:o.sourceProfileId||null}),gt(),Fe(i),lo(o.id);const m=Oe(o);uo(m),ps(i,{modelId:o.id,modelRef:m,providerIdHint:o.sourceProfileId||(m==null?void 0:m.profileId),vendorHint:o.vendor}),cn(i==="agent"?{}:Kn(i,o.id,ze(o.id,m))),Rn(!1),setTimeout(()=>{var w;return(w=Te.current)==null?void 0:w.focus()},0)},[gt,x]),Ys=r.useCallback(o=>{const i=xe(ln,o,L)||xe(ln,o,null)||Ve(o);i&&mn(i)},[mn,ln,L]),Xs=r.useCallback(o=>{mn(o)},[mn]),hn=r.useCallback((o,i)=>{const m=Oe(i);o==="image"?(po(i.id),mo(m)):o==="video"?(ho(i.id),fo(m)):(go(i.id),wo(m)),ps(o,{modelId:i.id,modelRef:m,providerIdHint:i.sourceProfileId||(m==null?void 0:m.profileId),vendorHint:i.vendor}),Ae.track("ai_input_change_agent_media_model",{model:i.id,type:o,profileId:i.sourceProfileId||null})},[]),zn=r.useCallback((o,i,m)=>{const w=o==="image"?jt:o==="video"?zt:Ot,b=xe(w,i,m||null)||xe(w,i,null)||Ve(i);b&&hn(o,b)},[hn,Ot,jt,zt]),On=r.useCallback((o,i)=>{hn(o,i)},[hn]),Zs=r.useCallback(o=>{Xe(Ct(o))},[]),Eo=r.useMemo(()=>({image:Be,video:He,audio:$e}),[$e,Be,He]),Ao=r.useMemo(()=>({image:Ge,video:Ke,audio:Ye}),[Ye,Ge,Ke]);r.useEffect(()=>{const o=(z,Y)=>{const B=Object.keys(z),q=Object.keys(Y);return B.length!==q.length?!1:B.every(oe=>z[oe]===Y[oe])},i=x==="agent"?"agent":`${x}:${ze(O,L)}`,m=x==="agent"?{}:Io.current===i?Wt.current||{}:Kn(x,O,ze(O,L),Wt.current),w={},b=Bt.find(z=>z.id==="size"),T=m.size,F=!T||!(b!=null&&b.options)||b.options.some(z=>z.value===T);!O.startsWith("mj")&&b&&(w.size=T&&F?T:b.defaultValue||Fo(O)),Bt.forEach(z=>{if(z.id==="size")return;const Y=m[z.id],B=!Y||z.valueType!=="enum"||!z.options||z.options.some(q=>q.value===Y);Y&&B?w[z.id]=Y:z.defaultValue&&(w[z.id]=z.defaultValue)});const Z=jr(O,w);o(Wt.current||{},Z)||(cn(Z),Wt.current=Z),Io.current=i},[x,O,L,Bt]),r.useEffect(()=>{pa({generationType:x,selectedModel:O,selectedParams:Ce,selectedCount:Lt,selectedSkillId:Ie}),x!=="agent"&&ma(x,O,Ce,ze(O,L))},[x,O,L,Ce,Lt,Ie]);const qs=r.useCallback((o,i,m)=>{gt(),cn(w=>{const b={...w};return i===void 0||i===""?delete b[o]:b[o]=i,b}),m!=null&&m.keepOpen||(Nn(!1),setTimeout(()=>{var w;return(w=Te.current)==null?void 0:w.focus()},0))},[gt]),Js=r.useCallback(o=>{gt(),yo(o),jn(!1),setTimeout(()=>{var i;return(i=Te.current)==null?void 0:i.focus()},0)},[gt]),Wn=r.useCallback(async o=>{var F,Z,z,Y,B,q,oe,ye;const i=fe.trim();if(!i&&ce.length===0||Le)return;const m=Date.now(),w=i.length,b={trigger:o,source:"ai_input_bar",generationType:x,generation_type:x,model:O,profileId:(L==null?void 0:L.profileId)||null,profile_id:(L==null?void 0:L.profileId)||null,hasAttachedContent:ce.length>0,has_attached_content:ce.length>0,attachedCount:ce.length,attached_count:ce.length,promptLength:w,prompt_length:w,promptLengthBucket:Xn(w),prompt_length_bucket:Xn(w)},T=(te,ke={})=>{const Ue=Date.now()-m;Ae.track("ai_input_submit",{...b,status:te,durationMs:Ue,duration_ms:Ue,...ke})};T("start"),nt(!0);try{if(!zr(x==="video"?"video":x==="audio"?"audio":x==="text"||x==="agent"?"text":"image",L||O)&&!await Or()){T("cancelled",{reason:"missing_api_key",submitMode:"preflight",submit_mode:"preflight"}),nt(!1);return}const Ue=ce.filter(M=>M.type==="image"&&M.url),Ht=ce.filter(M=>M.type==="graphics"&&M.url),A=[...Ue,...Ht].map(M=>{if(M.width&&M.height)return{width:M.width,height:M.height}}).filter(M=>M!==void 0),J={texts:ce.filter(M=>M.type==="text"&&M.text).map(M=>M.text),images:Ue.map(M=>M.url),videos:ce.filter(M=>M.type==="video"&&M.url).map(M=>M.url),graphics:Ht.map(M=>M.url),imageDimensions:A},W=Pa(fe,J,{modelId:O,modelRef:L,params:Ce,generationType:x,count:Lt,defaultModels:x==="agent"?Eo:void 0,defaultModelRefs:x==="agent"?Ao:void 0}),se=[...J.images,...J.graphics];let j;if(x==="agent"&&Ie!==et){const M=Vn(Ie);if(M)try{j=await wn(W,M,se)}catch(X){console.warn("[AIInputBar] 系统 Skill 工作流转换失败,降级到通用工作流:",X),j=Mt(W,se)}else{const X=Ho(Ie);if(X)try{j=await wn(W,{id:X.id,name:X.name,type:"external",content:X.content,outputType:X.outputType},se)}catch(K){console.warn("[AIInputBar] 外部 Skill 工作流转换失败,降级到角色扮演:",K),j=await wn(W,{id:X.id,name:X.name,type:"external",content:X.content,outputType:X.outputType},se).catch(()=>Mt(W,se))}else try{const K=await Mn.getNoteById(Ie);if(K){const le=((F=K.metadata)==null?void 0:F.outputType)||void 0;j=await wn(W,{id:K.id,name:K.title,type:"user",content:K.content,outputType:le},se)}else j=Mt(W,se)}catch{j=Mt(W,se)}}j||(console.warn("[AIInputBar] Skill 工作流未能生成,降级到通用工作流"),j=Mt(W,se))}else j=Mt(W,se);const G=De.current;if(G){const le=(Z=G.host)==null?void 0:Z.getBoundingClientRect(),me=((z=G.viewport)==null?void 0:z.zoom)||1,he=((B=(Y=G.viewport)==null?void 0:Y.origination)==null?void 0:B[0])||0,Re=((oe=(q=G.viewport)==null?void 0:q.origination)==null?void 0:oe[1])||0,Gt=G.children.filter(ge=>ge.type!=="workzone"),fn=he+((le==null?void 0:le.width)||0)/2/me,_t=Re+((le==null?void 0:le.height)||0)/2/me;let be=fn-200,re=_t,bt=be,qe=_t-240/2;if(Gt.length>0){const ge=xs(G);let de=!1;if(ge.length>0)try{const ue=Gn(G,ge,!1);ge.every(ve=>$o.isDrawElement(ve)&&$o.isImage(ve)||Wr(ve))&&ue.width>ue.height?(be=ue.x+ue.width+50,re=ue.y):(be=ue.x,re=ue.y+ue.height+50),bt=be,qe=re,de=!0}catch(ue){console.warn("[AIInputBar] Failed to calculate position for selected elements:",ue)}if(!de){let ue=null,Yt=-1/0;for(const ve of Gt)try{const St=Gn(G,[ve],!1),Xt=St.y+St.height;Xt>Yt&&(Yt=Xt,ue=ve)}catch(St){console.warn("[AIInputBar] Failed to get rectangle for element:",St)}if(ue){const ve=Gn(G,[ue],!1);be=ve.x,re=ve.y+ve.height+50,bt=be,qe=re}}}const it=Qe(j),vt=Po.current;let Kt,ct,No;if(vt){const ge=G.children.find(de=>de.id===vt.id);if(ge&&_s(ge)){Kt=vt.id,ct={width:vt.width,height:vt.height};const de=kn.getRectangleByPoints(ge.points);No=de,be=de.x,re=de.y}}if(W.generationType==="image"){const ge=Math.max(W.count??1,1),de=ge>1,ue=de?void 0:Kt,Yt=de?void 0:ct,ve=[],St=`wf_batch_${j.id}`,Xt=ue?null:$a(G,[be,re],Uo({workflowId:j.id,expectedInsertPosition:[be,re],requestedSize:W.size,requestedCount:1,zoom:me,title:it.name||"图片生成",...$n("submitted")}).size??{width:320,height:180},ge,{frameRect:de?No:void 0});for(let Ne=0;Ne<ge;Ne+=1){let Zt=Uo({workflowId:j.id,expectedInsertPosition:[be,re],targetFrameId:ue,targetFrameDimensions:Yt,frameAffinityId:de?Kt:void 0,frameAffinityDimensions:de?ct:void 0,requestedSize:W.size,requestedCount:de?1:ge,batchId:de?St:void 0,batchIndex:de?Ne+1:void 0,batchTotal:de?ge:void 0,zoom:me,title:it.name||"图片生成",...$n("submitted")});if(!ue){const zo=Xt?Xt[Ne]??Zt.position:Zt.position;Zt={...Zt,position:zo,expectedInsertPosition:zo}}const ir=lt.insertAnchor(G,Zt);ve.push(ir)}P.current=ve.map(Ne=>Ne.id),g.current=null;const[jo]=ve;jo&&setTimeout(()=>{const Ne=kn.getRectangleByPoints(jo.points);Vo(G,[Ne.x+Ne.width/2,Ne.y+Ne.height/2],100)},100)}else{const ge=je.insertWorkZone(G,{workflow:it,position:[bt,qe],size:{width:360,height:240},expectedInsertPosition:[be,re],targetFrameId:Kt,targetFrameDimensions:ct,zoom:me});g.current=ge.id,P.current=[],setTimeout(()=>{const de=bt+180,ue=qe+240/2;Vo(G,[de,ue],100)},100)}}const wt=kt("image"),It=kt("video"),yt=kt("audio"),xt={rawInput:fe,userInstruction:W.userInstruction,model:{id:W.modelId,type:W.generationType,isExplicit:W.isModelExplicit},modelRef:W.modelRef,defaultModels:W.defaultModels||{audio:yt.modelId||Et(),image:wt.modelId||pt(),video:It.modelId||Pt()},defaultModelRefs:W.defaultModelRefs||{audio:mt(yt.profileId,yt.modelId),image:mt(wt.profileId,wt.modelId),video:mt(It.profileId,It.modelId)},params:{count:W.count,size:W.size,duration:W.duration},selection:J,finalPrompt:W.prompt},Fn=kt("text").modelId,$t={aiContext:xt,referenceImages:se,textModel:Fn};E.current=$t;try{const M=Date.now(),{usedSW:X}=await ko(W,se,$t,j);if(X){if(T("success",{submitMode:"service_worker",submit_mode:"service_worker",workflowId:j.id,workflow_id:j.id,stepCount:j.steps.length,step_count:j.steps.length}),x==="image"&&ee(G,"accepted"),fe.trim()){const K=fe.trim(),le=ce.length>0;v(K,le,x),x==="image"?Go(K):x==="video"&&Ko(K)}tt(""),En([]),ft([]),we.current&&clearTimeout(we.current),we.current=setTimeout(()=>{nt(!1),we.current=null},1e3);return}}catch(M){console.warn("[AIInputBar] SW execution failed, falling back to main thread:",M)}if(x==="image"&&ee(G,"handoff"),fe.trim()){const M=fe.trim(),X=ce.length>0;v(M,X,x),x==="image"?Go(M):x==="video"&&Ko(M)}tt(""),En([]),ft([]),we.current&&clearTimeout(we.current),we.current=setTimeout(()=>{nt(!1),we.current=null},1e3);const pe=[],Ze=[],Ut=(M,X)=>({onChunk:K=>{D.current(K)},onAddSteps:K=>{l.updateStep(M.id,"completed",{analysis:"completed"},void 0,Date.now()-X);const le=K.map((he,Re)=>Sn(j,{...he,status:he.status==="completed"?"completed":"pending",options:{mode:"queue",batchId:`agent_${Date.now()}`,batchIndex:Re+1,batchTotal:K.length,globalIndex:Re+1}}));l.addSteps(le),Ze.push(...le),K.forEach(he=>{f.current({type:"tool_call",timestamp:Date.now(),toolName:he.mcp,args:he.args})});const me=Qe(l.getWorkflow(),E.current||void 0);I.current(me),g.current&&G&&je.updateWorkflow(G,g.current,me)},onUpdateStep:(K,le,me,he)=>{l.updateStep(K,le,me,he),f.current({type:"tool_result",timestamp:Date.now(),toolName:K,success:le==="completed",data:me,error:he});const Re=Qe(l.getWorkflow(),E.current||void 0);I.current(Re),g.current&&G&&je.updateWorkflow(G,g.current,Re)}});let Pe=!1;const Vt=()=>{const M=Qe(l.getWorkflow(),E.current||void 0);I.current(M),g.current&&G&&je.updateWorkflow(G,g.current,M)},Bn=async M=>{var le,me,he,Re,Gt,fn;const X=Date.now(),K=Ze.length;l.updateStep(M.id,"running"),Vt();try{const _t={...M.options,...Ut(M,X)},be=Sn(j,M),re=await Yo.executeTool({name:be.mcp,arguments:be.args},_t),bt=(me=(le=l.getWorkflow())==null?void 0:le.steps.find(qe=>qe.id===M.id))==null?void 0:me.status;if(re.success){if(re.taskId)pe.push(re.taskId),l.updateStep(M.id,"running",{taskId:re.taskId}),U(G,re.taskId,{workflowId:j.id,batchId:(he=M.options)==null?void 0:he.batchId,batchIndex:(Re=M.options)==null?void 0:Re.batchIndex});else if(bt==="running"){const qe=re.type==="text"&&re.data&&typeof re.data=="object"&&"content"in re.data?{content:re.data.content}:re.data;l.updateStep(M.id,"completed",qe,void 0,Date.now()-X);const it=M.mcp==="generate_text"?(Gt=re.data)==null?void 0:Gt.content:M.mcp==="ai_analyze"?(fn=re.data)==null?void 0:fn.response:void 0;if((M.mcp==="generate_text"||M.mcp==="ai_analyze")&&it&&it.trim()&&Ze.length===K){const ct={id:`${M.id}-insert-text`,mcp:"insert_to_canvas",args:{items:[{type:"text",content:it}]},description:M.mcp==="generate_text"?"将生成文本插入画布":"将 AI 回复插入画布",status:"pending"};l.addSteps([ct]),Ze.push(ct)}}}else return l.updateStep(M.id,"failed",void 0,re.error||"执行失败",Date.now()-X),!1;return!0}catch(_t){return l.updateStep(M.id,"failed",void 0,String(_t)),!1}finally{Vt()}};for(const M of j.steps){if(Pe){l.updateStep(M.id,"skipped"),Vt();continue}await Bn(M)||(Pe=!0)}if(!Pe&&Ze.length>0){const M=l.getWorkflow();for(const X of Ze){if(Pe){l.updateStep(X.id,"skipped"),Vt();continue}const K=(ye=l.getWorkflow())==null?void 0:ye.steps.find(me=>me.id===X.id);if(!K){console.warn(`[AIInputBar] Step ${X.id} not found in workflow!`);continue}if(K.status==="completed")continue;await Bn(K)||(Pe=!0)}}const _e=l.getWorkflow(),rr=_e==null?void 0:_e.steps.every(M=>M.status==="completed"||M.status==="failed"||M.status==="skipped"),ar=pe.length>0;if(rr&&!ar){const M=g.current,X=P.current,K=De.current;(M||X.length>0)&&K&&(_e!=null&&_e.steps.every(me=>{const he=me.result;return he!=null&&he.taskId?Un.isPostProcessingCompleted(he.taskId):!0}))&&setTimeout(()=>{M&&(je.removeWorkZone(K,M),g.current=null),X.length>0&&(ee(K,"completed"),ne(K))},1500)}T(Pe?"failed":"success",{submitMode:"main_thread",submit_mode:"main_thread",workflowId:j.id,workflow_id:j.id,stepCount:(_e==null?void 0:_e.steps.length)||j.steps.length,step_count:(_e==null?void 0:_e.steps.length)||j.steps.length,createdTaskCount:pe.length,created_task_count:pe.length,failureReason:Pe?"workflow_step_failed":void 0,failure_reason:Pe?"workflow_step_failed":void 0})}catch(te){console.error("Failed to create generation task:",te),T("failed",{submitMode:"setup",submit_mode:"setup",error:te instanceof Error?te.message:String(te)}),x==="image"&&ee(De.current,"failed",{error:te instanceof Error?te.message:"创建图片任务失败"}),l.abortWorkflow(),nt(!1)}},[fe,ce,Le,O,L,l,ko,v,Ce,Eo,Ao,x,Lt,U,ee,ne]),Ln=r.useCallback(async(o,i,m)=>{var Ht;const w=o.retryContext;if(!w){console.error("[AIInputBar] No retry context available for workflow");return}m&&(g.current=m);const b={id:o.id,name:o.name,description:`重试: ${o.name}`,scenarioType:o.steps.some(A=>A.mcp==="ai_analyze")?"agent_flow":"direct_generation",generationType:o.generationType,steps:o.steps.map((A,J)=>({id:A.id,mcp:A.mcp,args:A.args,description:A.description,status:J<i?A.status:"pending",result:J<i?A.result:void 0,error:J<i?A.error:void 0,duration:J<i?A.duration:void 0,options:A.options})),metadata:{prompt:o.prompt,userInstruction:w.aiContext.userInstruction,rawInput:w.aiContext.rawInput,modelId:w.aiContext.model.id,modelRef:w.aiContext.modelRef,defaultModels:w.aiContext.defaultModels,defaultModelRefs:w.aiContext.defaultModelRefs,isModelExplicit:w.aiContext.model.isExplicit,count:o.count,size:w.aiContext.params.size,duration:w.aiContext.params.duration,referenceImages:w.referenceImages,selection:w.aiContext.selection},createdAt:Date.now()};l.startWorkflow(b),f.current({type:"retry",timestamp:Date.now(),reason:`从步骤 ${i+1} 开始重试`,attempt:1});const T=De.current,F=()=>{const A=Qe(l.getWorkflow(),w);I.current(A),g.current&&T&&je.updateWorkflow(T,g.current,A)},Z=Qe(b,w);I.current(Z),g.current&&T&&je.updateWorkflow(T,g.current,Z);const z=(A,J)=>({onChunk:W=>{D.current(W)},onAddSteps:W=>{l.updateStep(A.id,"completed",{analysis:"completed"},void 0,Date.now()-J);const se=W.map((j,G)=>Sn(b,{...j,status:j.status==="completed"?"completed":"pending",options:{mode:"queue",batchId:`agent_${Date.now()}`,batchIndex:G+1,batchTotal:W.length,globalIndex:G+1}}));l.addSteps(se),Y.push(...se),W.forEach(j=>{f.current({type:"tool_call",timestamp:Date.now(),toolName:j.mcp,args:j.args})}),F()},onUpdateStep:(W,se,j,G)=>{l.updateStep(W,se,j,G),f.current({type:"tool_result",timestamp:Date.now(),toolName:W,success:se==="completed",data:j,error:G}),F()}}),Y=[];let B=!1;const q=new Map;o.steps.forEach(A=>{var W;const J=(W=A.result)==null?void 0:W.taskId;J&&q.set(A.id,J)});const oe=async A=>{var se,j,G,wt,It,yt;const J=Date.now(),W=Y.length;l.updateStep(A.id,"running"),F();try{const xt=q.get(A.id),Fn={...A.options,...z(A,J),...xt?{retryTaskId:xt}:{}},$t=Sn(b,A),pe=await Yo.executeTool({name:$t.mcp,arguments:$t.args},Fn),Ze=(j=(se=l.getWorkflow())==null?void 0:se.steps.find(Ut=>Ut.id===A.id))==null?void 0:j.status;if(pe.success){if(pe.taskId)l.updateStep(A.id,"running",{taskId:pe.taskId}),U(T,pe.taskId,{workflowId:o.id,batchId:(G=A.options)==null?void 0:G.batchId,batchIndex:(wt=A.options)==null?void 0:wt.batchIndex});else if(Ze==="running"){const Ut=pe.type==="text"&&pe.data&&typeof pe.data=="object"&&"content"in pe.data?{content:pe.data.content}:pe.data;l.updateStep(A.id,"completed",Ut,void 0,Date.now()-J);const Pe=A.mcp==="generate_text"?(It=pe.data)==null?void 0:It.content:A.mcp==="ai_analyze"?(yt=pe.data)==null?void 0:yt.response:void 0;if((A.mcp==="generate_text"||A.mcp==="ai_analyze")&&Pe&&Pe.trim()&&Y.length===W){const _e={id:`${A.id}-insert-text`,mcp:"insert_to_canvas",args:{items:[{type:"text",content:Pe}]},description:A.mcp==="generate_text"?"将生成文本插入画布":"将 AI 回复插入画布",status:"pending"};l.addSteps([_e]),Y.push(_e)}}}else return l.updateStep(A.id,"failed",void 0,pe.error||"执行失败",Date.now()-J),!1;return!0}catch(xt){return l.updateStep(A.id,"failed",void 0,String(xt)),!1}finally{F()}},ye=b.steps.slice(i);for(const A of ye){if(B){l.updateStep(A.id,"skipped"),F();continue}await oe(A)||(B=!0)}if(!B&&Y.length>0)for(const A of Y){if(B){l.updateStep(A.id,"skipped"),F();continue}const J=(Ht=l.getWorkflow())==null?void 0:Ht.steps.find(se=>se.id===A.id);if(!J||J.status==="completed")continue;await oe(J)||(B=!0)}const te=l.getWorkflow(),ke=te==null?void 0:te.steps.every(A=>A.status==="completed"||A.status==="failed"||A.status==="skipped"),Ue=te==null?void 0:te.steps.some(A=>{var J;return(J=A.result)==null?void 0:J.taskId});if(ke&&!Ue){const A=g.current,J=De.current;A&&J&&(te!=null&&te.steps.every(se=>{const j=se.result;return j!=null&&j.taskId?Un.isPostProcessingCompleted(j.taskId):!0}))&&setTimeout(()=>{je.removeWorkZone(J,A),g.current=null},1500)}},[l,U]);r.useEffect(()=>{C.current(Ln);const o=De.current;o&&(o.__executeWorkflowRetry=Ln)},[Ln]);const Qs=r.useCallback(o=>{var i;if(!o.nativeEvent.isComposing&&!(o.key==="Enter"&&(o.shiftKey||o.altKey))){if((xo||_o||bo)&&(o.key==="Enter"||o.key==="Tab")){o.preventDefault();return}if(o.key==="Enter"){o.preventDefault(),Ae.track("ai_input_submit_keyboard"),Wn("keyboard");return}if(o.key==="Escape"){ot(!1),(i=Te.current)==null||i.blur();return}}},[Wn]),er=r.useCallback(()=>{Ae.track("ai_input_focus_textarea"),ot(!0)},[]),tr=r.useCallback(()=>{Ae.track("ai_input_blur_textarea"),ot(!1)},[]),nr=r.useCallback(o=>{const i=o.target.value,m=o.target.selectionStart||i.length;if(tt(i),m>0){const w=i[m-1],b=m>1?i[m-2]:" ";w==="#"&&(b===" "||b===`
|
|
8
|
+
`||m===1)&&(st.current=m-1,Rn(!0),Nn(!1),jn(!1))}},[]),or=r.useMemo(()=>JSON.stringify({generationType:x,model:O,profileId:(L==null?void 0:L.profileId)||null,hasAttachedContent:ce.length>0,attachedCount:ce.length,promptLengthBucket:Xn(fe.trim().length)}),[ce.length,x,fe,O,L==null?void 0:L.profileId]),Do=fe.trim().length>0||ce.length>0,Ro=Rs===!0,sr=Pn.some(o=>{var i;return o.type==="text"&&((i=o.text)==null?void 0:i.trim())}),at=Nt||ce.length>0||As;return r.useLayoutEffect(()=>{Qa(Te.current,at)},[at,fe]),p.jsxs("div",{ref:un,className:gn("ai-input-bar",Tn,e,{"ai-input-bar--with-inspiration":Ro}),"data-testid":"ai-input-bar",children:[p.jsx(Ps,{language:s,onSelectionChange:Vs,externalBoardRef:De,onCanvasEmptyChange:Ns,isDataReady:n,onFrameSelected:Gs}),p.jsx(ja,{isCanvasEmpty:Ro,onSelectPrompt:Ws,onOpenPromptTool:Bs}),p.jsxs("div",{className:gn("ai-input-bar__container",{"ai-input-bar__container--expanded":at}),children:[p.jsxs("div",{className:"ai-input-bar__bottom-bar",children:[p.jsx("input",{ref:Mo,type:"file",accept:"image/*",multiple:!0,onChange:Us,style:{display:"none"}}),p.jsx("button",{className:"ai-input-bar__upload-btn",onMouseDown:o=>{o.preventDefault(),o.stopPropagation()},onClick:$s,title:s==="zh"?"上传图片":"Upload images","data-track":"ai_input_click_upload",children:p.jsx(Lr,{size:18})}),p.jsx("button",{className:"ai-input-bar__library-btn",onMouseDown:o=>{o.preventDefault(),o.stopPropagation()},onClick:()=>Ft(!0),title:s==="zh"?"从素材库选择":"Select from library","data-track":"ai_input_click_library",children:p.jsx(Fr,{size:18})}),p.jsx(za,{value:x,onSelect:Fe,disabled:Le}),x==="agent"&&p.jsx(Ea,{value:Ie,onSelect:An,onSelectSkill:Zs,onAddSkill:Fs,disabled:Le}),p.jsx(_n,{selectedModel:O,selectedSelectionKey:ze(O,L),onSelect:Ys,onSelectModel:Xs,language:s,models:ln,header:s==="zh"?x==="agent"?"选择文本模型 (↑↓ Tab)":"选择模型 (↑↓ Tab)":x==="agent"?"Select text model (↑↓ Tab)":"Select model (↑↓ Tab)",isOpen:xo,onOpenChange:js}),x==="agent"&&Ie!==et&&Dn.includes("image")&&p.jsx(_n,{selectedModel:Be,selectedSelectionKey:ze(Be,Ge),onSelect:(o,i)=>zn("image",o,i),onSelectModel:o=>On("image",o),language:s,models:jt,header:s==="zh"?"选择图片模型 (↑↓ Tab)":"Select image model (↑↓ Tab)"}),x==="agent"&&Ie!==et&&Dn.includes("video")&&p.jsx(_n,{selectedModel:He,selectedSelectionKey:ze(He,Ke),onSelect:(o,i)=>zn("video",o,i),onSelectModel:o=>On("video",o),language:s,models:zt,header:s==="zh"?"选择视频模型 (↑↓ Tab)":"Select video model (↑↓ Tab)"}),x==="agent"&&Ie!==et&&Dn.includes("audio")&&p.jsx(_n,{selectedModel:$e,selectedSelectionKey:ze($e,Ye),onSelect:(o,i)=>zn("audio",o,i),onSelectModel:o=>On("audio",o),language:s,models:Ot,header:s==="zh"?"选择音频模型 (↑↓ Tab)":"Select audio model (↑↓ Tab)"}),x!=="agent"&&Bt.length>0&&p.jsx(ha,{selectedParams:Ce,onParamChange:qs,compatibleParams:Bt,modelId:O,language:s,isOpen:_o,onOpenChange:zs},O),x!=="agent"&&x!=="text"&&x!=="audio"&&p.jsx(Oa,{value:Lt,onSelect:Js,disabled:Le,isOpen:bo,onOpenChange:Os}),p.jsx("div",{className:"ai-input-bar__bottom-spacer"}),p.jsx("button",{className:`ai-input-bar__send-btn ${Do?"active":""} ${Le?"loading":""}`,onMouseDown:o=>{o.preventDefault(),o.stopPropagation()},onClick:()=>Wn("button"),disabled:!Do||Le,"data-track":"ai_input_click_send","data-track-params":or,"data-testid":"ai-send-btn",children:p.jsx(Br,{size:18})})]}),p.jsxs("div",{className:gn("ai-input-bar__input-area",{"ai-input-bar__input-area--expanded":at}),children:[ce.length>0&&p.jsx("div",{className:"ai-input-bar__content-preview",children:p.jsx(Qr,{items:ce,language:s,enableHoverPreview:!0,onRemove:Ks,removableStartIndex:Rt.length})}),p.jsxs("div",{className:"ai-input-bar__prompt-row",children:[p.jsx("div",{className:"ai-input-bar__rich-input",children:p.jsx("textarea",{ref:Te,className:gn("ai-input-bar__input",{"ai-input-bar__input--focused":at}),value:fe,onChange:nr,onKeyDown:Qs,onFocus:er,onBlur:tr,placeholder:x==="agent"?s==="zh"?"输入指令,让 Agent 为你工作...":"Type instructions for Agent...":x==="text"?s==="zh"?"输入你想生成的文本内容、文章、摘要或 Markdown":"Describe the text, article, summary, or markdown you want":x==="audio"?sr?s==="zh"?"已有文本,无需额外提示词,直接发送":"Text already selected. No extra prompt needed, just send":s==="zh"?"描述你想要生成的音乐、风格、歌词或情绪":"Describe the music, style, lyrics, or mood you want":s==="zh"?`描述你想要创建的${x==="image"?"图片":"视频"}`:`Describe the ${x==="image"?"image":"video"} you want to create`,rows:at?Ts:Za,disabled:Le,"data-testid":"ai-input-textarea"})}),p.jsx(fa,{generationType:x,onSelectPrompt:Ls,language:s,onBeforeOpenMyPrompts:t,extraActions:at?p.jsx(ea,{className:"prompt-history-popover__action-btn",originalPrompt:fe,language:s,scenarioId:`ai-input.${x}`,disabled:Le,allowStructuredMode:!0,onOpenChange:Ds,onMouseDown:o=>{o.preventDefault(),o.stopPropagation(),ot(!0)},onApply:o=>{tt(o),ot(!0),requestAnimationFrame(()=>{var i;(i=Te.current)==null||i.focus()})}}):null})]})]})]}),vo&&p.jsx(ra,{isOpen:vo,onClose:()=>Ft(!1),mode:Hr.SELECT,filterType:Bo.IMAGE,onSelect:Hs})]})});Es.displayName="AIInputBar";function ui({isDataReady:e,activationKey:n,onEnableToolWindows:t}){const s=r.useRef(null);return r.useEffect(()=>{if(n<=0)return;const d=window.setTimeout(()=>{var a;const c=(a=s.current)==null?void 0:a.querySelector('[data-testid="ai-input-textarea"]');c==null||c.focus()},0);return()=>{window.clearTimeout(d)}},[n]),p.jsx(Kr,{children:p.jsx(na,{children:p.jsx("div",{ref:s,children:p.jsx(Es,{isDataReady:e,onEnableToolWindows:t})})})})}export{ui as DeferredAIInputBar,ui as default};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-5CxI1j1O.css","./ai-chat-CQtdTiRy.css","./tool-windows-D6a2KkKR.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as a}from"./startup-runtime-DTmhLESk.js";import{am as M,j as t,r as n}from"./startup-app-CiOE0Z0l.js";const F=n.lazy(()=>a(()=>import("./tool-windows-FtjXnyoK.js").then(e=>e.a1),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.ProjectDrawer}))),U=n.lazy(()=>a(()=>import("./tool-windows-FtjXnyoK.js").then(e=>e.a2),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.ToolboxDrawer}))),W=n.lazy(()=>a(()=>import("./tool-windows-FtjXnyoK.js").then(e=>e.a3),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.DeferredMediaLibraryModal}))),q=n.lazy(()=>a(()=>import("./tool-windows-FtjXnyoK.js").then(e=>e.a4),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.BackupRestoreDialog}))),G=n.lazy(()=>a(()=>import("./tool-windows-FtjXnyoK.js").then(e=>e.a5),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.VersionUpdatePrompt}))),H=n.lazy(()=>a(()=>import("./tool-windows-FtjXnyoK.js").then(e=>e.a6),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.PerformancePanel}))),J=n.lazy(()=>a(()=>import("./tool-windows-FtjXnyoK.js").then(e=>e.a7),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.DeferredSyncSettings}))),K=n.lazy(()=>a(()=>import("./tool-windows-FtjXnyoK.js").then(e=>e.a8),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.CommandPalette}))),N=n.lazy(()=>a(()=>import("./tool-windows-FtjXnyoK.js").then(e=>e.a9),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.CanvasSearch}))),Q=n.lazy(()=>a(()=>import("./tool-windows-FtjXnyoK.js").then(e=>e.aa),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.ToolWinBoxManager})));function Z({board:e,value:S,containerRef:o,versionUpdateEnabled:v,performancePanelEnabled:D,toolWindowManagerEnabled:f,projectDrawerOpen:u,toolboxDrawerOpen:p,mediaLibraryOpen:_,mediaLibraryConfig:l,backupRestoreOpen:h,cloudSyncOpen:m,onBoardSwitch:r,setProjectDrawerOpen:T,setToolboxDrawerOpen:O,setMediaLibraryOpen:k,setBackupRestoreOpen:V,setCloudSyncOpen:A,handleOpenMediaLibrary:I,handleBeforeSwitch:x,onCreateProjectForMemory:R}){const{appState:P,setAppState:d}=M(),j=P.openCommandPalette||!1,i=P.openCanvasSearch||!1;return t.jsxs(t.Fragment,{children:[_&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(W,{isOpen:_,onClose:()=>k(!1),mode:l==null?void 0:l.mode,filterType:l==null?void 0:l.filterType,onSelect:l==null?void 0:l.onSelect,selectButtonText:l==null?void 0:l.selectButtonText})}),h&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(q,{open:h,onOpenChange:V,container:o.current,onBeforeImport:async()=>{await x()},onSwitchBoard:async(s,E)=>{const{workspaceService:w}=await a(async()=>{const{workspaceService:z}=await import("./startup-app-CiOE0Z0l.js").then(B=>B.mi);return{workspaceService:z}},__vite__mapDeps([0]),import.meta.url),c=await w.switchBoard(s);c&&r&&(E&&(c.viewport=E),r(c))}})}),m&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(J,{visible:m,onClose:()=>A(!1)})}),v&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(G,{})}),f&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(Q,{})}),j&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(K,{open:j,onClose:()=>{d(s=>({...s,openCommandPalette:!1}))},board:e,container:o.current})}),i&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(N,{open:i,onClose:()=>{d(s=>({...s,openCanvasSearch:!1}))},board:e})}),D&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(H,{container:o.current,onCreateProject:R,elements:(e==null?void 0:e.children)||S})}),u&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(F,{isOpen:u,onOpenChange:T,onBeforeSwitch:x,onBoardSwitch:r,onOpenMediaLibrary:I})}),p&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(U,{isOpen:p,onOpenChange:O})})]})}export{Z as DrawnixDeferredFeatures,Z as default};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-5CxI1j1O.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as Be}from"./startup-runtime-DTmhLESk.js";import{r as a,j as e,Q as Ss,q as xe,X as ye,$ as Ms,ar as Oe,k as Pt,c$ as ve,av as De,T as Le,ks as Es,kt as Is,y as te,h as Te,hP as Ke,ku as As,kv as Ve,kw as ge,hU as Ae,e0 as Ut,kx as be,ky as Ne,kz as st,kA as Wt,kB as Ds,kC as Bt,kD as Ft,kE as Ht,dM as se,n as Xe,kF as qe,kG as nt,kH as kt,kI as Ls,kJ as Ts,O as zs,I as Rs,kK as $s,ee as Ot,eo as Ps,em as Us,dR as Ws,kL as Bs,d4 as Fs,iW as Hs,fM as Os,D as at,kM as Ks,e1 as Ye,as as Ge,e3 as Vs,bT as ze,au as Kt,dY as Ce,kN as Xs,kO as qs,dL as Vt,c7 as Ys,eb as Gs,M as q,kP as Xt,kQ as qt,V as Qs,aJ as Zs,ab as wt,aq as Js,aN as Qe,hV as en,kR as tn,kS as sn,i9 as nn,a7 as an,v as rn,kT as _t,kU as jt,eA as Yt,i4 as on,kV as cn,kW as ln,kX as yt,hL as dn,e9 as un,kY as hn,kZ as mn}from"./startup-app-CiOE0Z0l.js";import{V as fn,o as K,ap as Gt,aq as gn,ar as pn}from"./ai-chat-xhQ4iSkg.js";import{S as vt}from"./skill-dsl-parser-Dce8urAe.js";import{$ as xn,a as Qt,b as Zt,i as bn,M as kn,c as wn,e as _n,d as jn,f as Nt,g as yn,C as vn,h as ae}from"./editor-engines-I3xq4bkN.js";import{M as Jt,y as Nn,z as Cn,C as Sn,D as Mn,E as En}from"./tool-windows-FtjXnyoK.js";/* empty css */import"./diagram-engines-puSIfQIz.js";const pe="__system_skill__";function In(t){const s=new Date(t),n=new Date;return s.getFullYear()===n.getFullYear()&&s.getMonth()===n.getMonth()&&s.getDate()===n.getDate()?s.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"}):s.getFullYear()===n.getFullYear()?s.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"}):s.toLocaleDateString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit"})}const An=({directories:t,notesByDir:s,noteTagsMap:n,noteCounts:i,selectedDirId:r,selectedNoteId:c,expandedDirIds:d,isCreatingDir:u,skillDirName:g="Skill",onSelectDir:j,onToggleExpand:w,onCreateDir:y,onCancelCreateDir:m,onRenameDir:k,onDeleteDir:l,onSelectNote:S,onCreateNote:x,onDeleteNote:f,onDuplicateDir:z,onDuplicateNote:R,onInsertNoteToCanvas:P})=>{const[H,p]=a.useState(""),[L,O]=a.useState(null),[T,J]=a.useState(""),[B,W]=a.useState(null);a.useEffect(()=>{const v=()=>W(null),I=()=>W(null);return document.addEventListener("click",v),document.addEventListener("scroll",I,!0),()=>{document.removeEventListener("click",v),document.removeEventListener("scroll",I,!0)}},[]);const _=a.useCallback((v,I,N,E=!1)=>{v.preventDefault(),v.stopPropagation(),W({x:v.clientX,y:v.clientY,type:I,id:N,isDefault:E})},[]),F=a.useCallback(async()=>{const v=H.trim();if(v)try{await y(v),p(""),m()}catch{}},[H,y,m]),U=a.useCallback(async v=>{const I=T.trim();if(I)try{await k(v,I),O(null)}catch{}},[T,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:v=>p(v.target.value),onKeyDown:v=>{v.key==="Enter"&&F(),v.key==="Escape"&&m()},placeholder:"目录名称",autoFocus:!0}),e.jsx("button",{className:"kb-tree__icon-btn",onClick:F,children:e.jsx(xe,{size:14})}),e.jsx("button",{className:"kb-tree__icon-btn",onClick:m,children:e.jsx(ye,{size:14})})]}),e.jsx("div",{className:"kb-tree__list",children:t.map(v=>e.jsx(Dn,{dir:v,isSelected:r===v.id,isExpanded:d.has(v.id),notes:s[v.id]||[],noteCount:i[v.id]||0,noteTagsMap:n,selectedNoteId:c,isRenaming:L===v.id,renameValue:T,onSelectDir:()=>{j(v.id),d.has(v.id)||w(v.id)},onToggleExpand:()=>{w(v.id),W(null)},onStartRename:()=>{O(v.id),J(v.name),W(null)},onRenameChange:J,onRenameConfirm:()=>U(v.id),onRenameCancel:()=>O(null),onDeleteDir:()=>{l(v.id),W(null)},onCreateNote:()=>{x(v.id),W(null)},onSelectNote:S,onDeleteNote:I=>{f(I),W(null)},onContextMenu:I=>_(I,"directory",v.id,v.isDefault),onNoteContextMenu:(I,N)=>_(I,"note",N),isSkillDir:v.name===g},v.id))}),B&&Ss.createPortal(e.jsx("div",{className:"kb-context-menu",style:{top:B.y,left:B.x,zIndex:Ms.DROPDOWN_PORTAL},onClick:v=>v.stopPropagation(),children:B.type==="directory"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"kb-context-menu__item",onClick:()=>{z(B.id),W(null)},children:[e.jsx(Oe,{size:14}),e.jsx("span",{children:"复制目录"})]}),e.jsxs("div",{className:"kb-context-menu__item",onClick:()=>{var v;O(B.id),J(((v=t.find(I=>I.id===B.id))==null?void 0:v.name)||""),W(null)},children:[e.jsx(Pt,{size:14}),e.jsx("span",{children:"重命名"})]}),e.jsxs("div",{className:"kb-context-menu__item kb-context-menu__item--danger",onClick:()=>{l(B.id),W(null)},children:[e.jsx(ve,{size:14}),e.jsx("span",{children:"删除"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"kb-context-menu__item",onClick:()=>{R(B.id),W(null)},children:[e.jsx(Oe,{size:14}),e.jsx("span",{children:"创建副本"})]}),P&&e.jsxs("div",{className:"kb-context-menu__item",onClick:()=>{const I=Object.values(s).flat().find(N=>N.id===B.id);I&&P(I),W(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:()=>{f(B.id),W(null)},children:[e.jsx(ve,{size:14}),e.jsx("span",{children:"删除"})]})]})}),document.body)]})},Dn=({dir:t,isSelected:s,isExpanded:n,notes:i,noteCount:r,noteTagsMap:c,selectedNoteId:d,isRenaming:u,renameValue:g,isSkillDir:j=!1,onSelectDir:w,onToggleExpand:y,onStartRename:m,onRenameChange:k,onRenameConfirm:l,onRenameCancel:S,onDeleteDir:x,onCreateNote:f,onSelectNote:z,onDeleteNote:R,onContextMenu:P,onNoteContextMenu:H})=>e.jsxs("div",{className:`kb-tree__dir ${s?"kb-tree__dir--selected":""}`,children:[e.jsxs("div",{className:"kb-tree__dir-row",onClick:w,onContextMenu:P,children:[e.jsx("button",{className:"kb-tree__expand-btn",onClick:p=>{p.stopPropagation(),y()},children:n?e.jsx(De,{size:14}):e.jsx(Le,{size:14})}),n?e.jsx(Es,{size:16}):e.jsx(Is,{size:16}),u?e.jsx("input",{className:"kb-tree__input kb-tree__input--inline",value:g,onChange:p=>k(p.target.value),onKeyDown:p=>{p.key==="Enter"&&l(),p.key==="Escape"&&S()},onClick:p=>p.stopPropagation(),autoFocus:!0}):e.jsx("span",{className:"kb-tree__dir-name",children:t.name}),e.jsx("span",{className:"kb-tree__dir-count",children:r}),e.jsxs("div",{className:"kb-tree__dir-actions",children:[e.jsx(te,{content:"新建笔记",showArrow:!1,children:e.jsx("button",{className:"kb-tree__icon-btn",onClick:p=>{p.stopPropagation(),f()},children:e.jsx(Te,{size:12})})}),e.jsxs(e.Fragment,{children:[e.jsx(te,{content:"重命名",showArrow:!1,children:e.jsx("button",{className:"kb-tree__icon-btn",onClick:p=>{p.stopPropagation(),m()},children:e.jsx(Pt,{size:12})})}),e.jsx(te,{content:"删除",showArrow:!1,children:e.jsx("button",{className:"kb-tree__icon-btn kb-tree__icon-btn--danger",onClick:p=>{p.stopPropagation(),x()},children:e.jsx(ve,{size:12})})})]})]})]}),n&&e.jsxs("div",{className:"kb-tree__notes",children:[j&&Ke.map(p=>{const L=`${pe}${p.id}`,O=d===L;return e.jsxs("div",{className:`kb-tree__note-row kb-tree__note-row--system ${O?"kb-tree__note-row--selected":""}`,onClick:()=>z(L),children:[e.jsx("div",{className:"kb-tree__note-icon",children:e.jsx(Ve,{size:14})}),e.jsx("div",{className:"kb-tree__note-content",children:e.jsxs("div",{className:"kb-tree__note-title",children:[p.name,e.jsx("span",{className:"kb-tree__system-badge",children:"系统"})]})})]},L)}),j&&As().map(p=>{const L=`${ge}${p.id}`,O=d===L;return e.jsxs("div",{className:`kb-tree__note-row kb-tree__note-row--system ${O?"kb-tree__note-row--selected":""}`,onClick:()=>z(L),children:[e.jsx("div",{className:"kb-tree__note-icon",children:e.jsx(Ve,{size:14})}),e.jsx("div",{className:"kb-tree__note-content",children:e.jsxs("div",{className:"kb-tree__note-title",children:[p.name,e.jsx("span",{className:"kb-tree__system-badge",children:"系统"})]})})]},L)}),i.length===0&&!j&&e.jsx("div",{className:"kb-tree__notes-empty",children:"暂无笔记"}),i.length===0&&j&&Ke.length===0&&e.jsx("div",{className:"kb-tree__notes-empty",children:"暂无笔记"}),Array.from(new Map(i.map(p=>[p.id,p])).values()).map(p=>{const L=d===p.id,O=c[p.id]||[],T=p.metadata;return e.jsx(Ln,{note:p,isSelected:L,tags:O,metadata:T,onSelect:()=>z(p.id),onDelete:()=>R(p.id),onContextMenu:J=>H(J,p.id)},p.id)})]})]}),Ln=({note:t,isSelected:s,tags:n,metadata:i,onSelect:r,onDelete:c,onContextMenu:d})=>e.jsxs("div",{className:`kb-tree__note-row ${s?"kb-tree__note-row--selected":""}`,onClick:r,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||"无标题"}),(i==null?void 0:i.domain)&&e.jsxs("div",{className:"kb-tree__note-domain",children:[i.faviconUrl?e.jsx("img",{src:i.faviconUrl,alt:"",className:"kb-tree__favicon",onError:u=>{u.target.style.display="none"}}):e.jsx(Ut,{size:10}),e.jsx("span",{children:i.domain})]}),e.jsxs("div",{className:"kb-tree__note-meta",children:[n.length>0&&e.jsxs("div",{className:"kb-tree__note-tags",children:[n.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)),n.length>2&&e.jsxs("span",{className:"kb-tree__tag-more",children:["+",n.length-2]})]}),n.length===0&&!(i!=null&&i.domain)&&e.jsx("span",{className:"kb-tree__note-time",children:In(t.updatedAt)})]})]}),e.jsx("button",{className:"kb-tree__note-delete",onClick:u=>{u.stopPropagation(),c()},title:"删除笔记",children:e.jsx(ve,{size:12})})]});function Fe(t){const s=t.url;if(!(s!=null&&s.startsWith(be)))return null;const n=s.slice(be.length),i=Ne(t.alt||""),r=i.assetType||"image";if(r==="image")return null;const c=st(t.title),d=i.label||"";return{type:"assetEmbed",assetId:n,assetType:r,label:d,width:c.width,height:c.height}}function es(t){if(t.children)for(let s=0;s<t.children.length;s++){const n=t.children[s];if(n.type==="image-block"){const i=Fe(n);if(i){t.children[s]=i;continue}}if(n.type==="paragraph"&&n.children){const i=[],r=[];for(const c of n.children){if(c.type==="image"){const d=Fe(c);if(d){i.push(d);continue}}r.push(c)}if(i.length>0){const c=[];r.length>0&&c.push({...n,children:r}),c.push(...i),t.children.splice(s,1,...c),s+=c.length-1;continue}}if(n.type==="image"){const i=Fe(n);if(i){t.children[s]=i;continue}}es(n)}}const Tn=xn("remarkAssetEmbed",()=>()=>es);function de(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 Ze=Qt("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 n=Ne(t.alt);if(n.assetType&&n.assetType!=="image")return!0}return!1},runner:(t,s,n)=>{if(s.type==="assetEmbed"){t.addNode(n,{assetId:s.assetId,assetType:s.assetType,label:s.label,width:de(s.width),height:de(s.height)});return}const i=s.url.slice(be.length),r=Ne(s.alt),c=st(s.title);t.addNode(n,{assetId:i,assetType:r.assetType||"video",label:r.label||"",width:de(c.width),height:de(c.height)})}},toMarkdown:{match:t=>t.type.name==="assetEmbed",runner:(t,s)=>{const{assetId:n,assetType:i,label:r}=s.attrs,c=r?`${i}|${r}`:i,d=Wt({width:de(s.attrs.width),height:de(s.attrs.height)});t.openNode("paragraph"),t.addNode("image",void 0,void 0,{url:`${be}${n}`,alt:c,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:de(t.getAttribute("data-width")),height:de(t.getAttribute("data-height"))})}]})),zn=({asset:t,style:s})=>{const n=a.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]),i=a.useMemo(()=>[{elementId:n.id,audioUrl:t.url,title:t.name,previewImageUrl:t.thumbnail}],[t.name,t.thumbnail,t.url,n.id]);return e.jsx("div",{className:"collimind-markdown-audio-card",style:s,children:e.jsx(Ds,{element:n,selected:!1,canvasQueue:i})})};function re(t,s,n){return Math.min(Math.max(t,s),n)}function Ct(t){if(!(typeof t!="number"||!Number.isFinite(t)||t<=0))return Math.round(t)}const Je=Math.round(nt*1.15);function St(t,s,n){let i=re(t,n.minWidth,n.maxWidth),r=i/s;return(r<n.minHeight||r>n.maxHeight)&&(r=re(r,n.minHeight,n.maxHeight),i=r*s),{width:re(i,n.minWidth,n.maxWidth),height:re(r,n.minHeight,n.maxHeight)}}function Mt(t,s,n){let i=re(t,n.minHeight,n.maxHeight),r=i*s;return(r<n.minWidth||r>n.maxWidth)&&(r=re(r,n.minWidth,n.maxWidth),i=r/s),{width:re(r,n.minWidth,n.maxWidth),height:re(i,n.minHeight,n.maxHeight)}}function Et(t){return re(Math.round(t*nt/qe),96,Je)}const Rn=({assetId:t,assetType:s,label:n,width:i,height:r,selected:c,readonly:d,updateAttrs:u})=>{const g=a.useSyncExternalStore(Ft,Ht),j=g.get(t),w=a.useRef(null),[y,m]=a.useState(null);a.useEffect(()=>{m(null)},[i,r]);const k=(y==null?void 0:y.width)??Ct(i),l=(y==null?void 0:y.height)??Ct(r),S=k??qe,x=Et(S),f=s===se.AUDIO&&typeof l=="number"&&(l>240||l>S*.75),z=s===se.AUDIO?re(f?x:l??x,96,Je):l,R=a.useMemo(()=>{const p={};return k?p.width=`${k}px`:s===se.AUDIO?p.width="min(100%, 560px)":p.maxWidth=s===se.AUDIO?"min(100%, 560px)":"min(100%, 520px)",s===se.AUDIO?p.height=`${z}px`:l&&(p.height=`${l}px`),p},[s,l,k,z]),P=a.useCallback(p=>L=>{if(d)return;const O=w.current;if(!O)return;L.preventDefault(),L.stopPropagation();const T=O.getBoundingClientRect();if(!T.width||!T.height)return;const J=O.closest(".ProseMirror"),B=Math.max(160,((J==null?void 0:J.getBoundingClientRect().width)??T.width)-32),W=s===se.AUDIO?Je:1600,_=120,F=s===se.AUDIO?96:80,U={x:L.clientX,y:L.clientY,width:T.width,height:T.height};let v={width:Math.round(T.width),height:Math.round(T.height)};const I=E=>{const $=E.clientX-U.x,Y=E.clientY-U.y,D=s!==se.AUDIO&&E.shiftKey&&U.width>0&&U.height>0,G=p==="bottom"?U.width:re(U.width+$,_,B),Q=p==="right"?U.height:re(U.height+Y,F,W);if(s===se.AUDIO){const Z=p==="bottom"?re(Math.round(Q*(qe/nt)),120,B):Math.round(G),ie=Et(Z);v={width:Z,height:ie},m(v);return}if(D){const Z=U.width/U.height,ie={minWidth:_,maxWidth:B,minHeight:F,maxHeight:W};if(p==="right")v=St(G,Z,ie);else if(p==="bottom")v=Mt(Q,Z,ie);else{const Se=G/U.width,ke=Q/U.height;v=Math.abs(Se-1)>=Math.abs(ke-1)?St(G,Z,ie):Mt(Q,Z,ie)}v={width:Math.round(v.width),height:Math.round(v.height)},m(v);return}v={width:Math.round(G),height:Math.round(Q)},m(v)},N=()=>{document.removeEventListener("pointermove",I),document.removeEventListener("pointerup",N),m(v),u({width:v.width,height:v.height})};document.addEventListener("pointermove",I),document.addEventListener("pointerup",N,{once:!0})},[s,d,u]),H=(p,L)=>e.jsxs("div",{className:`collimind-asset-embed__shell ${c?"is-selected":""}`,"data-asset-type":s,"data-asset-id":t,children:[e.jsxs("div",{ref:w,className:"collimind-asset-embed__frame",style:R,children:[p,!d&&c&&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:P("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:P("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:P("corner"),"aria-label":`同时调整${s===se.AUDIO?"音频":"视频"}宽高`})]})]}),L&&e.jsx("div",{className:"collimind-asset-embed__caption",children:L})]});return j?j.type===se.IMAGE?e.jsx("img",{className:"collimind-asset-embed__image",src:Xe(j.url),alt:n||j.name||"素材图片"}):j.type===se.VIDEO?H(e.jsx("div",{className:"collimind-asset-embed__video-wrap",children:e.jsx(fn,{className:"collimind-asset-embed__video",src:j.url,poster:j.thumbnail,alt:n||j.name||"素材视频",thumbnailSize:"large",activateVideoOnClick:!0,playOnActivate:!0,videoProps:{controls:!0,preload:"metadata",playsInline:!0}})}),n||j.name):j.type===se.AUDIO?H(e.jsx(zn,{asset:j,style:{width:"100%",maxHeight:"100%"}}),n||j.name):null:g.size===0?e.jsx("div",{className:"collimind-asset-embed__loading",style:R}):e.jsxs("div",{className:"collimind-asset-embed__missing",style:R,children:["素材不存在或已删除 (",t.slice(0,8),"…)"]})},$n=Zt(Ze.node,()=>(t,s,n)=>{const i=document.createElement("div");i.className="collimind-asset-embed",i.setAttribute("data-asset-id",t.attrs.assetId);let r=t,c=!1,d=Bt.createRoot(i);const u=j=>{if(!s.editable)return;const w=n();w!=null&&s.dispatch(s.state.tr.setNodeMarkup(w,void 0,{...r.attrs,...j}))},g=()=>{d==null||d.render(e.jsx(Rn,{assetId:r.attrs.assetId,assetType:r.attrs.assetType,label:r.attrs.label,width:r.attrs.width??null,height:r.attrs.height??null,selected:c,readonly:!s.editable,updateAttrs:u}))};return g(),{dom:i,update:j=>j.type!==t.type?!1:(r=j,g(),!0),stopEvent:j=>{const w=j.target;return w instanceof HTMLElement?!!w.closest("[data-resize-handle]"):!1},selectNode:()=>{c=!0,i.classList.add("selected"),g()},deselectNode:()=>{c=!1,i.classList.remove("selected"),g()},destroy:()=>{if(d){const j=d;d=null,setTimeout(()=>j.unmount(),0)}}}}),Pn=[Tn,Ze.node,Ze.ctx,$n].flat();function Ie(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=Qt("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 n=Ne(t.alt);if(n.assetType&&n.assetType!=="image")return!1}return!0},runner:(t,s,n)=>{const i=typeof s.alt=="string"?s.alt:"",r=st(s.title),c=kt(i)?Number.parseFloat(i):1;t.addNode(n,{src:s.url,alt:kt(i)?"":i,caption:r.caption,ratio:Number.isFinite(c)&&c>0?c:1,width:r.width??null,height:r.height??null})}},toMarkdown:{match:t=>t.type.name==="image-block",runner:(t,s)=>{const n=Wt({width:Ie(s.attrs.width),height:Ie(s.attrs.height),caption:s.attrs.caption}),i=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:n,url:s.attrs.src,alt:i}),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:Ie(t.getAttribute("data-width")),height:Ie(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 oe(t,s,n){return Math.min(Math.max(t,s),n)}function It(t){if(!(typeof t!="number"||!Number.isFinite(t)||t<=0))return Math.round(t)}function At(t,s,n){let i=oe(t,n.minWidth,n.maxWidth),r=i/s;return(r<n.minHeight||r>n.maxHeight)&&(r=oe(r,n.minHeight,n.maxHeight),i=r*s),{width:oe(i,n.minWidth,n.maxWidth),height:oe(r,n.minHeight,n.maxHeight)}}function Dt(t,s,n){let i=oe(t,n.minHeight,n.maxHeight),r=i*s;return(r<n.minWidth||r>n.maxWidth)&&(r=oe(r,n.minWidth,n.maxWidth),i=r/s),{width:oe(r,n.minWidth,n.maxWidth),height:oe(i,n.minHeight,n.maxHeight)}}function Un({attrs:t,readonly:s,config:n,updateAttrs:i}){const r=a.useRef(null),[c,d]=a.useState(t.src||""),[u,g]=a.useState(!1);a.useEffect(()=>{d(t.src||"")},[t.src]);const j=a.useCallback(()=>{i({src:c.trim()})},[c,i]),w=a.useCallback(async y=>{var k;const m=(k=y.target.files)==null?void 0:k[0];if(m)try{const l=await n.onUpload(m);if(!l)return;d(l),i({src:l})}catch(l){console.error("Failed to upload image block file",l)}finally{y.target.value=""}},[n,i]);return e.jsxs("div",{className:"image-edit collimind-markdown-image-block__edit",children:[e.jsx("div",{className:"image-icon",children:n.imageIcon||"🌌"}),e.jsxs("div",{className:`link-importer ${u?"focus":""}`,children:[e.jsx("input",{className:"link-input-area",value:c,disabled:s,onChange:y=>d(y.target.value),onFocus:()=>g(!0),onBlur:()=>g(!1),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),j())}}),!c&&e.jsxs("div",{className:"placeholder",children:[e.jsx("input",{ref:r,className:"hidden",type:"file",accept:"image/*",disabled:s,onChange:w}),e.jsx("button",{type:"button",className:"uploader",disabled:s,onMouseDown:y=>y.preventDefault(),onClick:()=>{var y;return(y=r.current)==null?void 0:y.click()},children:n.uploadButton||"Upload"}),e.jsx("span",{className:"text",children:n.uploadPlaceholderText})]})]}),!!c&&e.jsx("button",{type:"button",className:"confirm",disabled:s,onMouseDown:y=>y.preventDefault(),onClick:j,children:n.confirmButton||"Confirm"})]})}function Wn({attrs:t,selected:s,readonly:n,updateAttrs:i}){const r=a.useRef(null),c=a.useSyncExternalStore(Ft,Ht),[d,u]=a.useState(null);a.useEffect(()=>{u(null)},[t.width,t.height]);const g=a.useMemo(()=>Ls(t.src),[t.src]),j=g?c.get(g):void 0,w=a.useMemo(()=>Ne(t.alt),[t.alt]),y=g?w.label||(j==null?void 0:j.name)||"素材图片":t.alt||"图片",m=a.useMemo(()=>g?!j||j.type!==se.IMAGE?null:Xe(j.url):Xe(t.src),[j,g,t.src]),k=(d==null?void 0:d.width)??It(t.width),l=(d==null?void 0:d.height)??It(t.height),S=a.useMemo(()=>{const z={};return k?z.width=`${k}px`:z.maxWidth="min(100%, 420px)",l&&(z.height=`${l}px`),z},[l,k]),x=a.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]),f=a.useCallback(z=>R=>{if(n)return;const P=r.current;if(!P)return;R.preventDefault(),R.stopPropagation();const H=P.getBoundingClientRect();if(!H.width||!H.height)return;const p=P.closest(".ProseMirror"),L=Math.max(120,((p==null?void 0:p.getBoundingClientRect().width)??H.width)-32),O=80,T=80,J=1600,B={x:R.clientX,y:R.clientY,width:H.width,height:H.height};let W={width:Math.round(H.width),height:Math.round(H.height)};const _=U=>{const v=U.clientX-B.x,I=U.clientY-B.y,N=U.shiftKey&&B.width>0&&B.height>0,E=z==="bottom"?B.width:oe(B.width+v,O,L),$=z==="right"?B.height:oe(B.height+I,T,J);if(N){const Y=B.width/B.height,D={minWidth:O,maxWidth:L,minHeight:T,maxHeight:J};if(z==="right")W=At(E,Y,D);else if(z==="bottom")W=Dt($,Y,D);else{const G=E/B.width,Q=$/B.height;W=Math.abs(G-1)>=Math.abs(Q-1)?At(E,Y,D):Dt($,Y,D)}W={width:Math.round(W.width),height:Math.round(W.height)},u(W);return}W={width:Math.round(E),height:Math.round($)},u(W)},F=()=>{document.removeEventListener("pointermove",_),document.removeEventListener("pointerup",F),u(W),i({width:W.width,height:W.height})};document.addEventListener("pointermove",_),document.addEventListener("pointerup",F,{once:!0})},[n,i]);return g&&!j&&c.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":g||void 0,children:[e.jsxs("div",{ref:r,className:"collimind-markdown-image-block__frame",style:S,children:[e.jsx("img",{className:"collimind-markdown-image-block__image",src:m,alt:y,draggable:!1,style:x}),!n&&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:f("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:f("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:f("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:g?`图片素材不存在或已删除 (${g.slice(0,8)}…)`:"图片地址无效"})}function Bn(t){return t.attrs.src?e.jsx(Wn,{...t}):e.jsx(Un,{...t})}const Fn=Zt(et.node,t=>{const s=t.get(bn.key);return(n,i,r)=>{const c=document.createElement("div");c.className="milkdown-image-block collimind-markdown-image-block",c.draggable=!0;let d=n,u=!1,g=Bt.createRoot(c);const j=m=>{if(!i.editable)return;const k=r();k!=null&&i.dispatch(i.state.tr.setNodeMarkup(k,void 0,{...d.attrs,...m}))},w=()=>{g==null||g.render(e.jsx(Bn,{attrs:d.attrs,selected:u,readonly:!i.editable,config:s,updateAttrs:j}))};w();const y=m=>{var l;const k=(l=m.detail)==null?void 0:l.src;k&&typeof k=="string"&&j({src:k})};return c.addEventListener("asset-commit",y),{dom:c,update:m=>m.type!==n.type?!1:(d=m,w(),!0),stopEvent:m=>{const k=m.target;return k instanceof HTMLElement?!!(k.closest(".image-edit")||k.closest("[data-resize-handle]")):!1},selectNode:()=>{u=!0,c.classList.add("selected"),w()},deselectNode:()=>{u=!1,c.classList.remove("selected"),w()},destroy:()=>{if(c.removeEventListener("asset-commit",y),g){const m=g;g=null,setTimeout(()=>m.unmount(),0)}}}}}),Hn=[et.node,et.ctx,Fn].flat();function He(t){return new Promise((s,n)=>{const i=new FileReader;i.onload=()=>s(typeof i.result=="string"?i.result:""),i.onerror=()=>n(i.error),i.readAsDataURL(t)})}function On({markdown:t,onChange:s,placeholder:n,readOnly:i,editorRef:r,enableAssetEmbeds:c}){const d=a.useRef(s);a.useEffect(()=>{d.current=s},[s]);const u=a.useRef(t),g=a.useRef(null),j=a.useRef(null),w=a.useRef(null),{get:y,loading:m}=wn(k=>{const l=new vn({root:k,defaultValue:t,features:{[ae.CodeMirror]:!0,[ae.ListItem]:!0,[ae.LinkTooltip]:!0,[ae.Cursor]:!0,[ae.ImageBlock]:!0,[ae.BlockEdit]:!0,[ae.Toolbar]:!0,[ae.Placeholder]:!0,[ae.Table]:!0,[ae.Latex]:!0},featureConfigs:{[ae.Placeholder]:{text:n||"开始编辑..."},[ae.Cursor]:{color:"#3b82f6",width:4},[ae.ImageBlock]:{onUpload:He,inlineOnUpload:He,blockOnUpload:He},[ae.Latex]:{katexOptions:{strict:"ignore"}}}});return l.editor.use(Hn),c&&l.editor.use(Pn),d.current&&l.on(S=>{S.markdownUpdated((x,f)=>{if(g.current&&clearTimeout(g.current),f!==u.current){u.current=f;const z=d.current,R=()=>{j.current=null,z==null||z(f)};j.current=R,g.current=setTimeout(R,50)}})}),w.current=l,l},[]);return a.useEffect(()=>{if(m)return;const k=w.current;if(k){if(i)try{k.setReadonly(!0)}catch{}return r.current={getMarkdown:()=>u.current,setMarkdown:l=>{var S;try{u.current=l,(S=k.editor)==null||S.action(Nt(l))}catch{}},insertMarkdown:l=>{var S;try{(S=k.editor)==null||S.action(jn(l))}catch{}},focus:()=>{var l,S;try{(S=(l=k.editor)==null?void 0:l.ctx.get(_n))==null||S.focus()}catch{}}},()=>{var l;g.current&&(clearTimeout(g.current),g.current=null),(l=j.current)==null||l.call(j),j.current=null,r.current=null}}},[y,i,r,m]),a.useEffect(()=>{if(m)return;const k=w.current;if(k)try{k.setReadonly(!!i)}catch{}},[i,m]),a.useEffect(()=>{var l,S;if(m)return;const k=w.current;if(k)try{const x=u.current;t!==x&&(g.current&&(clearTimeout(g.current),g.current=null),(l=j.current)==null||l.call(j),u.current=t,(S=k.editor)==null||S.action(Nt(t)))}catch{}},[t,m]),e.jsx(yn,{})}const it=a.memo(a.forwardRef(function({markdown:s,sourceMarkdown:n,onChange:i,placeholder:r="开始编辑...",readOnly:c=!1,className:d="",showModeSwitch:u=!0,initialMode:g="wysiwyg",enableAssetEmbeds:j=!1,enableAssetLibraryImagePicker:w=!1},y){const m=a.useContext(Ts),k=a.useRef(null),l=a.useRef(null),S=a.useRef(null),x=a.useRef(null),[f,z]=a.useState(g),[R,P]=a.useState(n||s),[H,p]=a.useState(!1),[L,O]=a.useState(!1),[T,J]=a.useState(g!=="wysiwyg"),B=a.useRef(n||s),W=w&&!!m;a.useEffect(()=>{B.current=R},[R]),a.useEffect(()=>{if(f!=="wysiwyg"){J(!1);return}let N=0,E=!1;const $=()=>{const Y=S.current;if(!E){if(Y!=null&&Y.isConnected){J(!0);return}N=requestAnimationFrame($)}};return $(),()=>{E=!0,N&&cancelAnimationFrame(N)}},[f]);const _=a.useCallback(N=>{var E,$;N!==f&&(N==="source"?P(n||((E=k.current)==null?void 0:E.getMarkdown())||s):n||(($=k.current)==null||$.setMarkdown(R),i==null||i(R)),z(N))},[f,s,R,n,i]),F=a.useCallback(N=>{const E=N.target.value;P(E),i==null||i(E)},[i]),U=a.useCallback(N=>{var $,Y;if(!N)return;const E=f==="source"?B.current:n||(($=k.current)==null?void 0:$.getMarkdown())||B.current||s;if(f==="source"&&l.current){const D=l.current,G=D.selectionStart??E.length,Q=D.selectionEnd??E.length,Z=`${E.slice(0,G)}${N}${E.slice(Q)}`;P(Z),i==null||i(Z),requestAnimationFrame(()=>{D.focus();const ie=G+N.length;D.setSelectionRange(ie,ie)});return}(Y=k.current)==null||Y.insertMarkdown(N),requestAnimationFrame(()=>{var G;const D=(G=k.current)==null?void 0:G.getMarkdown();typeof D=="string"&&P(D)})},[s,f,i,n]);a.useImperativeHandle(y,()=>({getMarkdown:()=>{var N;return f==="source"?R:((N=k.current)==null?void 0:N.getMarkdown())||R},setMarkdown:N=>{var E;P(N),(E=k.current)==null||E.setMarkdown(N)},insertMarkdown:U,focus:()=>{var N,E;f==="source"?(N=l.current)==null||N.focus():(E=k.current)==null||E.focus()},getMode:()=>f,setMode:_}),[_,U,f,R]),a.useEffect(()=>{const N=n||s;N!==R&&P(N)},[s,R,n]);const v=a.useCallback(()=>{const N=S.current;if(!N){x.current=null,O(!1);return}const E=N.ownerDocument.activeElement,$=E instanceof HTMLElement?E.closest(".image-edit"):null,Y=$&&N.contains($)?$:N.querySelector(".image-edit");x.current=Y??null,O(!!Y)},[]),I=a.useCallback((N,E)=>{if(!N)return!1;const $=N.closest(".milkdown-image-block");return $?($.dispatchEvent(new CustomEvent("asset-commit",{detail:{src:`asset://${E}`}})),!0):!1},[]);return a.useEffect(()=>{if(!W||c||f!=="wysiwyg"||!S.current){x.current=null,O(!1);return}const N=S.current;let E=0;const $=()=>{cancelAnimationFrame(E),E=requestAnimationFrame(v)},Y=G=>{const Q=G.target;if(!(Q instanceof HTMLElement))return;const Z=Q.closest(".image-edit");if(Z&&N.contains(Z)){x.current=Z,O(!0);return}$()};$(),N.addEventListener("focusin",Y),N.addEventListener("click",Y,!0);const D=new MutationObserver($);return D.observe(N,{childList:!0,subtree:!0}),()=>{cancelAnimationFrame(E),D.disconnect(),N.removeEventListener("focusin",Y),N.removeEventListener("click",Y,!0)}},[W,f,c,v]),e.jsxs("div",{className:`collimind-markdown-editor ${d}`,"data-readonly":c,"data-mode":f,"data-asset-embeds":j,children:[W&&L&&e.jsxs("button",{type:"button",className:"collimind-markdown-image-library-overlay",style:{right:u?68:8},onClick:()=>{v(),x.current&&p(!0)},children:[e.jsx(zs,{className:"collimind-icon-sm"}),e.jsx("span",{children:"从素材库插图"})]}),u&&e.jsxs("div",{className:"collimind-markdown-editor-mode-switch",children:[e.jsx("button",{type:"button",className:`collimind-markdown-editor-mode-btn ${f==="wysiwyg"?"active":""}`,onClick:()=>_("wysiwyg"),title:"所见即所得模式",children:e.jsx(Rs,{className:"collimind-icon-sm"})}),e.jsx("button",{type:"button",className:`collimind-markdown-editor-mode-btn ${f==="source"?"active":""}`,onClick:()=>_("source"),title:"Markdown 源码模式",children:e.jsx($s,{className:"collimind-icon-sm"})})]}),e.jsx("div",{ref:S,style:{display:f==="wysiwyg"?"contents":"none"},children:T&&e.jsx(kn,{children:e.jsx(On,{markdown:s,onChange:i,placeholder:r,readOnly:c,editorRef:k,enableAssetEmbeds:j})})}),f==="source"&&e.jsx("textarea",{ref:l,className:"collimind-markdown-editor-source",value:R,onChange:F,placeholder:r,readOnly:c||!!n,spellCheck:!1}),W&&H&&e.jsx(Jt,{isOpen:H,onClose:()=>{p(!1),v()},mode:Ot.SELECT,filterType:se.IMAGE,onSelect:N=>{var $;const E=x.current??(($=S.current)==null?void 0:$.querySelector(".image-edit"))??null;if(!I(E,N.id)){p(!1);return}p(!1),requestAnimationFrame(v)},selectButtonText:"插入素材库图片"})]})})),Lt=({allTags:t,selectedTagIds:s,onSelectedChange:n,onCreateTag:i,showCount:r=!1})=>{const[c,d]=a.useState(!1),[u,g]=a.useState(""),[j,w]=a.useState(!1),y=a.useRef(null);a.useEffect(()=>{if(!c)return;const x=f=>{y.current&&!y.current.contains(f.target)&&(d(!1),w(!1),g(""))};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[c]);const m=a.useCallback(x=>{const f=s.includes(x)?s.filter(z=>z!==x):[...s,x];n(f)},[s,n]),k=a.useCallback((x,f)=>{f.stopPropagation(),n(s.filter(z=>z!==x))},[s,n]),l=a.useCallback(async()=>{const x=u.trim();if(x)try{const f=await i(x);n([...s,f.id]),g(""),w(!1)}catch{}},[u,i,s,n]),S=t.filter(x=>s.includes(x.id));return e.jsxs("div",{className:"kb-tag-selector",ref:y,children:[e.jsxs("div",{className:"kb-tag-selector__selected",children:[S.map(x=>e.jsxs("span",{className:"kb-tag-selector__tag kb-tag-selector__tag--selected",style:{"--tag-color":x.color,borderColor:x.color,backgroundColor:`${x.color}15`},children:[e.jsx("span",{className:"kb-tag-selector__dot",style:{backgroundColor:x.color}}),e.jsx("span",{children:x.name}),e.jsx("button",{className:"kb-tag-selector__remove",onClick:f=>k(x.id,f),children:e.jsx(te,{content:"移除标签",showArrow:!1,children:e.jsx("span",{children:e.jsx(ye,{size:11})})})})]},x.id)),e.jsxs("button",{className:"kb-tag-selector__add-btn",onClick:()=>d(x=>!x),children:[e.jsx(Te,{size:13}),e.jsx("span",{children:"标签"})]})]}),c&&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(x=>{const f=s.includes(x.id);return e.jsxs("button",{className:`kb-tag-selector__tag ${f?"kb-tag-selector__tag--selected":""}`,style:{"--tag-color":x.color,borderColor:f?x.color:void 0,backgroundColor:f?`${x.color}15`:void 0},onClick:()=>m(x.id),children:[e.jsx("span",{className:"kb-tag-selector__dot",style:{backgroundColor:x.color}}),e.jsx("span",{children:x.name}),r&&e.jsxs("span",{className:"kb-tag-selector__count",children:["(",x.count,")"]}),f&&e.jsx(ye,{size:12})]},x.id)})]}),j?e.jsxs("div",{className:"kb-tag-selector__create",children:[e.jsx("input",{className:"kb-tag-selector__input",value:u,onChange:x=>g(x.target.value),onKeyDown:x=>{x.key==="Enter"&&l(),x.key==="Escape"&&(w(!1),g(""))},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:()=>w(!0),children:[e.jsx(Te,{size:13}),e.jsx("span",{children:"新建标签"})]})]})]})},Kn=({outputType:t,onOutputTypeChange:s,readOnly:n=!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:n?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"})]})})]})}),Vn=({note:t,allTags:s,noteTags:n,readOnly:i=!1,isSkillDirectory:r=!1,onUpdateNote:c,onSetNoteTags:d,onCreateTag:u})=>{var Y;const[g,j]=a.useState(""),[w,y]=a.useState(!1),[m,k]=a.useState(!1),[l,S]=a.useState(null),x=a.useRef(null),f=a.useRef(null),z=a.useRef(null),R=a.useRef(null),P=Ps(),H=typeof window<"u"&&"speechSynthesis"in window,p=a.useMemo(()=>n.map(D=>D.id),[n]),[L,O]=a.useState(void 0);a.useEffect(()=>{var D;O(t&&r&&((D=t.metadata)==null?void 0:D.outputType)||void 0)},[t==null?void 0:t.id,r]);const T=t==null?void 0:t.metadata,J=T&&(T.sourceUrl||T.author||T.domain);a.useEffect(()=>{var G;const D=t?`kb-note:${t.id}`:null;if(f.current&&(clearTimeout(f.current),f.current=null),x.current&&(clearTimeout(x.current),x.current=null),t)if(j(t.title),R.current=t.id,r&&!i){const Q=t.content||"";S(Q.trim()?vt.isDSLContent(Q):null)}else S(null);else j(""),R.current=null,S(null);P.mediaType==="reading"&&D&&((G=P.activeReadingSourceId)!=null&&G.startsWith(D))&&P.stopPlayback()},[t==null?void 0:t.id,r,i]);const B=a.useCallback(D=>{j(D),t&&(f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{c(t.id,{title:D})},500))},[t,c]),W=a.useCallback(D=>{t&&(f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{c(t.id,{content:D})},500),r&&!i&&(x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{D.trim()?S(vt.isDSLContent(D)):S(null)},500)))},[t,c,r,i]),_=a.useCallback(D=>{if(!t)return;O(D);const G={...t.metadata,outputType:D};D||delete G.outputType,K.updateNote(t.id,{metadata:G})},[t]),F=a.useCallback(D=>{t&&d(t.id,D)},[t,d]),U=a.useCallback(()=>{var Z;if(!t)return;const D=`kb-note:${t.id}`;if(P.mediaType==="reading"&&((Z=P.activeReadingSourceId)==null?void 0:Z.startsWith(D))){P.playing?P.pausePlayback():P.resumePlayback();return}const Q=Us({elementId:D,title:t.title||"知识库笔记",content:[t.title,t.content].filter(Boolean).join(`
|
|
3
|
+
|
|
4
|
+
`),origin:{kind:"kb-note",id:t.id}});Q&&Ws({source:Q,queue:[Q]})},[t,P]),v=a.useCallback(async()=>{if(!t)return;const D=await Nn(t.id);if(!D)return;const G=new Blob([D.content],{type:"text/markdown;charset=utf-8"}),Q=URL.createObjectURL(G),Z=document.createElement("a");Z.href=Q,Z.download=D.filename,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(Q)},[t]),I=a.useCallback(()=>{i||k(!0)},[i]),N=a.useCallback(D=>{var G;(G=z.current)==null||G.insertMarkdown(Bs(D)),k(!1)},[]);if(a.useEffect(()=>()=>{f.current&&clearTimeout(f.current),x.current&&clearTimeout(x.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(Fs,{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 E=`kb-note:${t.id}`,$=P.mediaType==="reading"&&((Y=P.activeReadingSourceId)==null?void 0:Y.startsWith(E));return e.jsxs("div",{className:`kb-note-editor ${i?"kb-note-editor--readonly":""}`,children:[i&&e.jsxs("div",{className:"kb-note-editor__readonly-banner",children:[e.jsx(Ve,{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:g,onChange:D=>!i&&B(D.target.value),placeholder:"笔记标题",readOnly:i}),e.jsxs("div",{className:"kb-note-editor__actions",children:[H&&e.jsx(te,{content:$?P.playing?"暂停朗读":"继续朗读":"语音朗读",showArrow:!1,children:e.jsx("button",{className:`kb-note-editor__action-btn ${$?"kb-note-editor__action-btn--active":""}`,onClick:U,children:$&&P.playing?e.jsx(Hs,{size:14}):e.jsx(Os,{size:14})})}),H&&$&&e.jsx(te,{content:"停止朗读",showArrow:!1,children:e.jsx("button",{className:"kb-note-editor__action-btn kb-note-editor__action-btn--danger",onClick:P.stopPlayback,children:"■"})}),e.jsx(te,{content:"导出 Markdown",showArrow:!1,children:e.jsx("button",{className:"kb-note-editor__action-btn",onClick:v,children:e.jsx(at,{size:14})})}),!i&&e.jsx(te,{content:"插入素材",showArrow:!1,children:e.jsx("button",{className:"kb-note-editor__action-btn",onClick:I,children:e.jsx(Ks,{size:14})})})]})]}),J&&e.jsxs("div",{className:`kb-note-editor__metadata-section ${w?"kb-note-editor__metadata-section--collapsed":""}`,children:[e.jsxs("button",{className:"kb-note-editor__metadata-toggle",onClick:()=>y(!w),title:w?"展开来源信息":"收起来源信息",children:[w?e.jsx(Le,{size:14}):e.jsx(De,{size:14}),e.jsx("span",{children:"来源信息"})]}),w&&e.jsxs("div",{className:"kb-note-editor__metadata-collapsed",children:[T.author&&e.jsxs("span",{className:"kb-note-editor__metadata-collapsed-item",children:[e.jsx(Ye,{size:10}),e.jsx("span",{children:T.author})]}),T.sourceUrl&&e.jsxs("a",{href:T.sourceUrl,target:"_blank",rel:"noopener noreferrer",className:"kb-note-editor__metadata-collapsed-link",onClick:D=>D.stopPropagation(),title:T.sourceUrl,children:[e.jsx(Ge,{size:10}),e.jsx("span",{children:T.domain||T.sourceUrl})]})]}),!w&&e.jsxs("div",{className:"kb-note-editor__metadata-body",children:[e.jsx("div",{className:"kb-note-editor__tags",children:e.jsx(Lt,{allTags:s,selectedTagIds:p,onSelectedChange:F,onCreateTag:u})}),e.jsxs("div",{className:"kb-note-editor__metadata-info",children:[T.domain&&e.jsxs("span",{className:"kb-note-editor__metadata-item",children:[T.faviconUrl?e.jsx("img",{src:T.faviconUrl,alt:"",className:"kb-note-editor__favicon",onError:D=>{D.currentTarget.style.display="none"}}):e.jsx(Ut,{size:12}),e.jsx("span",{children:T.domain})]}),T.author&&e.jsxs("span",{className:"kb-note-editor__metadata-item",children:[e.jsx(Ye,{size:12}),e.jsx("span",{children:T.author})]}),T.publishedAt&&e.jsxs("span",{className:"kb-note-editor__metadata-item",children:[e.jsx(Vs,{size:12}),e.jsx("span",{children:T.publishedAt})]})]}),T.sourceUrl&&e.jsx("a",{href:T.sourceUrl,target:"_blank",rel:"noopener noreferrer",className:"kb-note-editor__source-link",children:T.sourceUrl}),T.description&&e.jsx("p",{className:"kb-note-editor__metadata-desc",children:T.description})]})]}),!J&&e.jsx("div",{className:"kb-note-editor__tags",children:e.jsx(Lt,{allTags:s,selectedTagIds:p,onSelectedChange:F,onCreateTag:u})}),r&&e.jsx("div",{className:"kb-note-editor__mcp-tools",children:e.jsx(Kn,{outputType:L,onOutputTypeChange:_,readOnly:i})}),e.jsx("div",{className:"kb-note-editor__content",children:e.jsx(it,{ref:z,markdown:t.content,onChange:i?void 0:W,placeholder:"开始写点什么...",showModeSwitch:!i,readOnly:i,enableAssetEmbeds:!0,enableAssetLibraryImagePicker:!i,className:"kb-note-markdown"},t.id)}),r&&!i&&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(Jt,{isOpen:m,onClose:()=>k(!1),mode:Ot.SELECT,onSelect:N,selectButtonText:"插入到笔记"})]})},Xn=({allTags:t,selectedTagIds:s,onSelectedChange:n})=>{const[i,r]=a.useState(""),[c,d]=a.useState(!1),u=a.useMemo(()=>{if(!i)return t;const y=i.toLowerCase();return t.filter(m=>m.name.toLowerCase().includes(y))},[t,i]),g=y=>{const m=s.includes(y)?s.filter(k=>k!==y):[...s,y];n(m)},j=()=>{n([]),d(!1)},w=e.jsxs("div",{className:"kb-filter-dropdown__content",children:[e.jsx("div",{className:"kb-filter-dropdown__search",children:e.jsx(ze,{value:i,onChange:y=>r(y),placeholder:"搜索标签...",prefixIcon:e.jsx(Kt,{size:14}),size:"small",clearable:!0})}),e.jsx("div",{className:"kb-filter-dropdown__list",children:u.length>0?u.map(y=>{const m=s.includes(y.id);return e.jsxs("div",{className:`kb-filter-dropdown__item ${m?"is-selected":""}`,onClick:()=>g(y.id),children:[e.jsx("span",{className:"kb-filter-dropdown__item-dot",style:{backgroundColor:y.color}}),e.jsx("span",{className:"kb-filter-dropdown__item-name",children:y.name}),e.jsxs("span",{className:"kb-filter-dropdown__item-count",children:["(",y.count||0,")"]}),m&&e.jsx(xe,{size:14,className:"kb-filter-dropdown__item-check"})]},y.id)}):e.jsx("div",{className:"kb-filter-dropdown__empty",children:"无匹配标签"})}),s.length>0&&e.jsx("div",{className:"kb-filter-dropdown__footer",children:e.jsxs(Ce,{theme:"default",variant:"text",size:"small",onClick:j,className:"kb-filter-dropdown__clear-btn",children:[e.jsx(ye,{size:14,style:{marginRight:4}}),"清除标签过滤"]})})]});return e.jsx(Xs,{content:w,visible:c,onVisibleChange:y=>d(y),trigger:"click",placement:"bottom-left",overlayClassName:"kb-filter-dropdown__popup",children:e.jsxs(Ce,{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(qs,{size:14,style:{marginRight:4}}),"标签",s.length>0&&` (${s.length})`]})})},qn=({visible:t,onClose:s,allTags:n,onCreateTag:i,onUpdateTag:r,onDeleteTag:c,onSelectTag:d})=>{const{confirm:u,confirmDialog:g}=Vt(),[j,w]=a.useState(!1),[y,m]=a.useState(""),[k,l]=a.useState(null),[S,x]=a.useState(""),f=a.useRef(null);a.useEffect(()=>{j&&f.current&&setTimeout(()=>{var p;(p=f.current)==null||p.focus()},100)},[j]);const z=async()=>{if(!y.trim()){w(!1);return}try{await i(y.trim()),m(""),w(!1),q.success("标签创建成功")}catch{q.error("标签创建失败")}},R=async p=>{if(!S.trim()){l(null);return}try{await r(p,S.trim()),l(null),q.success("标签更新成功")}catch{q.error("标签更新失败")}},P=async(p,L)=>{p.stopPropagation();try{const O=n.find(J=>J.id===L);if(!await u({title:"确认删除标签",description:`确定要删除标签「${(O==null?void 0:O.name)||"未命名标签"}」吗?此操作不可撤销。`,confirmText:"删除",cancelText:"取消",danger:!0}))return;await c(L),q.success("标签删除成功")}catch{q.error("标签删除失败")}},H=(p,L)=>{p.stopPropagation(),l(L.id),x(L.name)};return e.jsxs(Ys,{header:"管理标签",visible:t,onClose:s,footer:null,width:400,className:"kb-tag-management-dialog",children:[e.jsxs("div",{className:"kb-tag-list",children:[j?e.jsx("div",{className:"kb-tag-item kb-tag-item--creating",children:e.jsx(ze,{ref:f,value:y,onChange:p=>m(p),onEnter:z,onBlur:z,placeholder:"输入标签名称...",size:"small"})}):e.jsxs("div",{className:"kb-tag-item kb-tag-item--create-btn",onClick:()=>w(!0),children:[e.jsx(Te,{size:16}),e.jsx("span",{children:"新建标签"})]}),n.map(p=>e.jsx("div",{className:"kb-tag-item",onClick:()=>{d&&!k&&(d(p.id),s())},children:k===p.id?e.jsxs("div",{className:"kb-tag-item__editing",onClick:L=>L.stopPropagation(),children:[e.jsx(ze,{value:S,onChange:L=>x(L),onEnter:()=>R(p.id),size:"small",autofocus:!0}),e.jsx(Ce,{shape:"circle",variant:"text",size:"small",onClick:()=>R(p.id),children:e.jsx(xe,{size:14})}),e.jsx(Ce,{shape:"circle",variant:"text",size:"small",onClick:()=>l(null),children:e.jsx(ye,{size:14})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"kb-tag-item__dot",style:{backgroundColor:p.color}}),e.jsx("span",{className:"kb-tag-item__name",children:p.name}),e.jsx("span",{className:"kb-tag-item__count",children:p.count?`(${p.count} 个笔记)`:"(0 个笔记)"}),e.jsxs("div",{className:"kb-tag-item__actions",children:[e.jsx(te,{content:"重命名",showArrow:!1,children:e.jsx("button",{className:"kb-tag-item__action-btn",onClick:L=>H(L,p),children:e.jsx(Gs,{size:12})})}),e.jsx(te,{content:"删除",showArrow:!1,children:e.jsx("button",{className:"kb-tag-item__action-btn kb-tag-item__action-btn--delete",onClick:L=>P(L,p.id),children:e.jsx(ve,{size:12})})})]})]})},p.id))]}),g]})},Tt=10,Yn=({currentNoteId:t,allNotes:s,noteTagsMap:n,onSelectNote:i})=>{const[r,c]=a.useState([]),[d,u]=a.useState(!1),[g,j]=a.useState(!1);a.useEffect(()=>{let l=!1;return(async()=>{try{const x=await Gt().getRelatedNotes(t,Tt);l||c(x)}catch{l||c([])}})(),()=>{l=!0}},[t]);const w=a.useMemo(()=>s.find(l=>l.id===t),[s,t]),y=a.useMemo(()=>{var S;const l=(S=w==null?void 0:w.metadata)==null?void 0:S.sourceUrl;return l?s.filter(x=>{var f;return x.id!==t&&((f=x==null?void 0:x.metadata)==null?void 0:f.sourceUrl)===l}):[]},[s,t,w]),m=a.useMemo(()=>new Set(y.map(l=>l.id)),[y]),k=a.useMemo(()=>{if(r.length>0){const f=new Set;return r.filter(z=>m.has(z.id)||f.has(z.id)?!1:(f.add(z.id),!0))}const l=n[t]||[],S=new Set(l.map(f=>f.id));if(!w)return[];const x=[];for(const f of s){if(f.id===t||m.has(f.id))continue;const R=(n[f.id]||[]).map(T=>T.id),P=R.filter(T=>S.has(T)).length,H=new Set([...S,...R]).size,p=H>0?P/H:0,L=Gn(w.title,f.title),O=p*.7+L*.3;O>.05&&x.push({id:f.id,title:f.title||"无标题",score:O})}return x.sort((f,z)=>z.score-f.score).slice(0,Tt)},[r,m,s,t,n,w]);return y.length===0&&k.length===0?null:e.jsxs("div",{className:"kb-related-notes",children:[y.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(Le,{size:12}):e.jsx(De,{size:12}),e.jsx(Xt,{size:12}),e.jsx("span",{children:"相关笔记"}),e.jsx("span",{className:"kb-related-notes__count",children:y.length})]}),!d&&e.jsx("div",{className:"kb-related-notes__list",children:y.map(l=>e.jsxs("div",{className:"kb-related-notes__item",onClick:()=>i(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(te,{content:"跳转",showArrow:!1,children:e.jsx("button",{className:"kb-related-notes__goto-btn",onClick:S=>{S.stopPropagation(),i(l.id)},children:e.jsx(Ge,{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:()=>j(!g),children:[g?e.jsx(Le,{size:12}):e.jsx(De,{size:12}),e.jsx(Ae,{size:12}),e.jsx("span",{children:"相似笔记"}),e.jsx("span",{className:"kb-related-notes__count",children:k.length})]}),!g&&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:()=>i(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(te,{content:"跳转",showArrow:!1,children:e.jsx("button",{className:"kb-related-notes__goto-btn",onClick:x=>{x.stopPropagation(),i(l.id)},children:e.jsx(Ge,{size:10})})})]},`similar-${l.id}`)})})]})]})};function Gn(t,s){if(!t||!s)return 0;const n=t.toLowerCase(),i=s.toLowerCase(),r=new Set;for(let g=0;g<n.length-1;g++)r.add(n.substring(g,g+2));const c=new Set;for(let g=0;g<i.length-1;g++)c.add(i.substring(g,g+2));let d=0;for(const g of r)c.has(g)&&d++;const u=r.size+c.size;return u===0?0:2*d/u}const Qn=`你是一个专业的知识提取助手,擅长从文本中识别和提取关键知识点。你的任务是分析给定的文本内容,提取出有价值的知识点,并以结构化的 Markdown 格式返回。
|
|
5
|
+
|
|
6
|
+
提取规则:
|
|
7
|
+
1. **核心概念**: 文中出现的重要概念、术语及其解释
|
|
8
|
+
2. **重要定义**: 明确的定义性内容,如"XX是指..."、"XX定义为..."
|
|
9
|
+
3. **关键步骤**: 操作流程、方法步骤、实施要点
|
|
10
|
+
4. **要点总结**: 核心观点、结论、重要发现
|
|
11
|
+
|
|
12
|
+
提取要求:
|
|
13
|
+
- 每个知识点必须有清晰的标题和详细的内容描述
|
|
14
|
+
- 确保提取的知识点具有独立性和完整性
|
|
15
|
+
- 避免重复提取相同的知识点
|
|
16
|
+
- 知识点数量控制在 3-10 个之间
|
|
17
|
+
- 内容要精炼、易于理解
|
|
18
|
+
|
|
19
|
+
输出格式要求:
|
|
20
|
+
- 必须返回 Markdown 格式
|
|
21
|
+
- 每个知识点使用二级标题(##)
|
|
22
|
+
- 内容使用正常段落或列表`;function Zn(t,s){return`请分析以下文本内容,提取关键知识点并以 Markdown 格式返回:
|
|
23
|
+
${s?`
|
|
24
|
+
文章标题:${s}`:""}
|
|
25
|
+
---
|
|
26
|
+
${t}
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
请按以下 Markdown 格式返回提取结果:
|
|
30
|
+
|
|
31
|
+
## 知识点标题1
|
|
32
|
+
|
|
33
|
+
知识点的详细内容描述,完整解释该知识点。可以使用列表、加粗等 Markdown 语法。
|
|
34
|
+
|
|
35
|
+
## 知识点标题2
|
|
36
|
+
|
|
37
|
+
另一个知识点的内容...
|
|
38
|
+
|
|
39
|
+
注意:
|
|
40
|
+
1. 每个知识点使用二级标题(##)
|
|
41
|
+
2. 标题要简洁明了,概括知识点核心
|
|
42
|
+
3. 内容要详细完整,可使用列表、加粗等格式
|
|
43
|
+
4. 不要添加"知识点1"、"知识点2"这样的序号前缀
|
|
44
|
+
5. 直接返回 Markdown 内容,不要使用代码块包裹`}function Jn(t){try{let s=t.trim();s.startsWith("```markdown")?s=s.slice(11):s.startsWith("```md")?s=s.slice(5):s.startsWith("```")&&(s=s.slice(3)),s.endsWith("```")&&(s=s.slice(0,-3)),s=s.trim();const n=s.split(/^##\s+/gm).filter(r=>r.trim());if(n.length===0)return null;const i=n.map(r=>{const c=r.split(`
|
|
45
|
+
`);return{title:c[0].trim(),content:c.slice(1).join(`
|
|
46
|
+
`).trim(),sourceContext:"",type:"summary",tags:[]}}).filter(r=>r.title&&r.content);return i.length>0?{knowledgePoints:i}:null}catch{return null}}function ea(){return`kp_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}async function ta(t,s){var d,u,g;const{model:n,onProgress:i,signal:r}=s;return((g=(u=(d=(await qt(t,j=>i==null?void 0:i(j),r,n)).choices)==null?void 0:d[0])==null?void 0:u.message)==null?void 0:g.content)||""}async function sa(t,s){var m,k,l;const{title:n,sourceUrl:i,model:r,onProgress:c,signal:d}=s,u=[{role:"system",content:[{type:"text",text:Qn}]},{role:"user",content:[{type:"text",text:Zn(t,n)}]}],j=((l=(k=(m=(await qt(u,S=>c==null?void 0:c(S),d,r)).choices)==null?void 0:m[0])==null?void 0:k.message)==null?void 0:l.content)||"",w=Jn(j);if(!w||w.knowledgePoints.length===0)throw new Error("无法从内容中提取知识点,请确保内容包含有价值的信息");return{knowledgePoints:w.knowledgePoints.map(S=>({id:ea(),title:S.title,content:S.content,sourceContext:S.sourceContext,tags:S.tags,type:S.type,selected:!0})),rawResponse:j,sourceUrl:i,sourceTitle:n,extractedAt:Date.now()}}const na="kb-chat-storage",aa="sessions",ts=Qs.createInstance({name:na,storeName:aa});async function ia(t){return ts.getItem(t)}async function ra(t,s){const n={noteId:t,messages:s,updatedAt:Date.now()};await ts.setItem(t,n)}const ss={concept:"核心概念",definition:"重要定义",step:"关键步骤",summary:"要点总结"};function oa(t,s){const n=[];n.push(`# ${s.title||"知识提炼"}`),n.push(""),s.sourceUrl&&(n.push(`> 来源: ${s.sourceUrl}`),n.push("")),n.push(`> 导出时间: ${new Date().toLocaleString("zh-CN")}`),n.push(""),n.push("---"),n.push("");const i=["concept","definition","step","summary"];for(const r of i){const c=t.filter(d=>d.type===r);if(c.length!==0){n.push(`## ${ss[r]}`),n.push("");for(const d of c)n.push(`### ${d.title}`),n.push(""),n.push(d.content),d.sourceContext&&(n.push(""),n.push(`> ${d.sourceContext}`)),d.tags.length>0&&(n.push(""),n.push(`**标签**: ${d.tags.map(u=>`\`${u}\``).join(" ")}`)),n.push("")}}return n.join(`
|
|
47
|
+
`)}function ca(t,s){const n=t.knowledgePoints.filter(d=>d.selected!==!1);if(n.length===0)throw new Error("没有选中的知识点");const i={title:t.sourceTitle||"知识提炼",sourceUrl:t.sourceUrl},r=new Date().toISOString().slice(0,10),c=t.sourceTitle?`${t.sourceTitle.slice(0,30).replace(/[/\\?%*:|"<>]/g,"-")}_知识提炼_${r}`:`知识提炼_${r}`;return{content:oa(n,i),filename:`${c}.md`,mimeType:"text/markdown"}}function la(t,s,n){const i=new Blob([t],{type:n}),r=URL.createObjectURL(i),c=document.createElement("a");c.href=r,c.download=s,document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(r)}const zt="gemini-3.1-pro-preview";function fe(t){return t<=0?"0":t<=200?"1-200":t<=1e3?"201-1000":t<=5e3?"1001-5000":t<=2e4?"5001-20000":"20000+"}function ne(t,s={}){an.trackUIInteraction({area:"knowledge_base",action:t,control:"knowledge_extraction",source:"knowledge_base_extraction",metadata:{status:s.status,model:s.model,profileId:s.profileId,profile_id:s.profileId,noteLength:s.noteLength,note_length:s.noteLength,noteLengthBucket:s.noteLength===void 0?void 0:fe(s.noteLength),note_length_bucket:s.noteLength===void 0?void 0:fe(s.noteLength),inputLength:s.inputLength,input_length:s.inputLength,inputLengthBucket:s.inputLength===void 0?void 0:fe(s.inputLength),input_length_bucket:s.inputLength===void 0?void 0:fe(s.inputLength),resultLength:s.resultLength,result_length:s.resultLength,resultLengthBucket:s.resultLength===void 0?void 0:fe(s.resultLength),result_length_bucket:s.resultLength===void 0?void 0:fe(s.resultLength),knowledgePointCount:s.knowledgePointCount,knowledge_point_count:s.knowledgePointCount,durationMs:s.durationMs,duration_ms:s.durationMs,error:s.error}})}function tt(t){const s=[],n=["concept","definition","step","summary"];for(const i of n){const r=t.knowledgePoints.filter(c=>c.type===i);if(r.length!==0){s.push(`## ${ss[i]}`),s.push("");for(const c of r)s.push(`### ${c.title}`),s.push(""),s.push(c.content),c.sourceContext&&(s.push(""),s.push(`> ${c.sourceContext}`)),c.tags&&c.tags.length>0&&(s.push(""),s.push(`**标签**: ${c.tags.map(d=>`\`${d}\``).join(" ")}`)),s.push("")}}return s.join(`
|
|
48
|
+
`).trim()}const da=({noteId:t,noteContent:s,noteTitle:n,onInsertToNote:i,onSaved:r})=>{const c=Zs("text"),[d,u]=a.useState([]),[g,j]=a.useState(""),[w,y]=a.useState(c.modelId||zt),[m,k]=a.useState(()=>wt(c.profileId,c.modelId||zt)),[l,S]=a.useState(!1),[x,f]=a.useState(null),[z,R]=a.useState(null),P=a.useRef(null),H=a.useRef(null);a.useEffect(()=>{let _=!0;return(async()=>{u([]);try{const U=await ia(t);_&&(U&&U.messages.length>0?u(U.messages):u([{id:"init",role:"model",content:"我已经阅读了这篇笔记。你可以让我提取摘要、关键点,或者直接与我讨论笔记内容。",type:"text",timestamp:Date.now()}]))}catch(U){console.error("Failed to load chat history",U)}})(),()=>{_=!1}},[t]),a.useEffect(()=>{d.length>0&&ra(t,d).catch(console.error)},[d,t]),a.useEffect(()=>{P.current&&(P.current.scrollTop=P.current.scrollHeight)},[d]),a.useEffect(()=>{H.current&&(H.current.style.height="auto",H.current.style.height=`${Math.min(H.current.scrollHeight,120)}px`)},[g]);const p=a.useCallback(()=>{z&&(ne("stop_generation",{status:"cancelled",model:w,profileId:m==null?void 0:m.profileId,noteLength:s.length}),z.abort(),R(null),S(!1),u(_=>[..._,{id:Date.now().toString(),role:"model",content:"🚫 已停止生成",type:"text",timestamp:Date.now()}]))},[z,s.length,w,m]),L=a.useCallback(async()=>{const _=g.trim();if(!_||l)return;const F=Date.now();ne("chat",{status:"start",model:w,profileId:m==null?void 0:m.profileId,noteLength:s.length,inputLength:_.length});const U={id:Date.now().toString(),role:"user",content:_,type:"text",timestamp:Date.now()};u(I=>[...I,U]),j(""),S(!0),H.current&&(H.current.style.height="auto");const v=new AbortController;R(v);try{const I=d.concat(U).map(E=>({role:E.role==="model"?"assistant":"user",content:[{type:"text",text:E.content}]}));if(I.length<=2){const E=`Context:
|
|
49
|
+
${s}
|
|
50
|
+
|
|
51
|
+
Task: ${U.content}`,$=I.length-1;I[$].content=[{type:"text",text:E}]}const N=(Date.now()+1).toString();f(N),u(E=>[...E,{id:N,role:"model",content:"正在思考...",type:"text",timestamp:Date.now()}]),await ta(I,{model:m||w,onProgress:E=>{u($=>$.map(Y=>Y.id===N?{...Y,content:E}:Y))},signal:v.signal}),ne("chat",{status:"success",model:w,profileId:m==null?void 0:m.profileId,noteLength:s.length,inputLength:_.length,durationMs:Date.now()-F})}catch(I){I.name!=="AbortError"?(ne("chat",{status:"failed",model:w,profileId:m==null?void 0:m.profileId,noteLength:s.length,inputLength:_.length,durationMs:Date.now()-F,error:I.message||"chat_failed"}),u(N=>[...N,{id:Date.now().toString(),role:"model",content:`Error: ${I.message||"Something went wrong"}`,type:"text",timestamp:Date.now()}])):ne("chat",{status:"cancelled",model:w,profileId:m==null?void 0:m.profileId,noteLength:s.length,inputLength:_.length,durationMs:Date.now()-F})}finally{S(!1),R(null),f(null)}},[g,l,d,s,w,m]),O=a.useCallback(async()=>{if(l)return;const _=Date.now();ne("quick_extract",{status:"start",model:w,profileId:m==null?void 0:m.profileId,noteLength:s.length}),S(!0);const F={id:Date.now().toString(),role:"user",content:"提取知识点",type:"text",timestamp:Date.now()};u(I=>[...I,F]);const U=new AbortController;R(U);const v=(Date.now()+1).toString();u(I=>[...I,{id:v,role:"model",content:"正在分析笔记内容并提取知识点...",type:"text",timestamp:Date.now()}]);try{const I=await sa(s,{title:n,model:m||w,signal:U.signal}),N=tt(I);ne("quick_extract",{status:"success",model:w,profileId:m==null?void 0:m.profileId,noteLength:s.length,resultLength:N.length,knowledgePointCount:I.knowledgePoints.length,durationMs:Date.now()-_}),u(E=>E.map($=>$.id===v?{...$,content:"知识点提取完成:",type:"extraction-result",data:I}:$))}catch(I){I.name!=="AbortError"?(ne("quick_extract",{status:"failed",model:w,profileId:m==null?void 0:m.profileId,noteLength:s.length,durationMs:Date.now()-_,error:I.message||"extract_failed"}),u(N=>N.map(E=>E.id===v?{...E,content:`提取失败: ${I.message}`}:E))):ne("quick_extract",{status:"cancelled",model:w,profileId:m==null?void 0:m.profileId,noteLength:s.length,durationMs:Date.now()-_})}finally{S(!1),R(null)}},[l,s,n,w,m]),T=_=>{_.key==="Enter"&&!_.shiftKey&&(_.preventDefault(),L())},J=a.useCallback(_=>{if(!_){q.warning("没有可复制的内容");return}ne("copy_result",{status:"start",resultLength:_.length}),Js(_).then(()=>{ne("copy_result",{status:"success",resultLength:_.length}),q.success("复制成功")}).catch(()=>{ne("copy_result",{status:"failed",resultLength:_.length}),q.error("复制失败")})},[]),B=a.useCallback(_=>_.type==="text"?_.content:_.type==="extraction-result"&&_.data?tt(_.data):"",[]),W=a.useCallback(_=>{if(_.type==="extraction-result"&&_.data)try{const F=ca(_.data,{format:"markdown",includeSource:!0,includeTags:!0});la(F.content,F.filename,F.mimeType),ne("download_markdown",{status:"success",resultLength:F.content.length,knowledgePointCount:_.data.knowledgePoints.length})}catch(F){console.error("Failed to export",F),ne("download_markdown",{status:"failed",knowledgePointCount:_.data.knowledgePoints.length,error:F instanceof Error?F.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(Qe,{size:18}),e.jsx("span",{children:"知识提取 & 对话"})]})}),e.jsx("div",{className:"kb-extraction-chat__messages",ref:P,children:d.map(_=>e.jsxs("div",{className:`kb-message kb-message--${_.role}`,children:[e.jsx("div",{className:"kb-message__avatar",children:_.role==="user"?e.jsx(Ye,{}):e.jsx(en,{})}),e.jsxs("div",{className:"kb-message__body",children:[e.jsx("div",{className:"kb-message__content",children:_.role==="model"?e.jsx("div",{className:"kb-message__content-scroll",children:_.type==="text"?_.id===x&&(_.content==="正在思考..."||_.content==="正在分析笔记内容并提取知识点...")?e.jsxs("div",{className:"kb-message__thinking","aria-label":"思考中",children:[e.jsx("span",{className:"kb-message__thinking-text",children:_.content.replace(/\.+$/,"")}),e.jsxs("span",{className:"kb-message__thinking-dots",children:[e.jsx("span",{children:"."}),e.jsx("span",{children:"."}),e.jsx("span",{children:"."})]})]}):_.content?e.jsx("div",{className:"kb-message__markdown-wrap",children:e.jsx(it,{markdown:_.content,readOnly:!0,showModeSwitch:!1,initialMode:"wysiwyg",className:"kb-extraction-markdown"})}):null:e.jsx(Rt,{result:_.data})}):_.type==="text"?e.jsx("div",{className:"kb-message__text",children:_.content}):e.jsx(Rt,{result:_.data})}),_.role==="model"&&e.jsxs("div",{className:"kb-message__actions",children:[e.jsx(te,{content:"复制",showArrow:!1,children:e.jsx("button",{className:"kb-message__action-btn",onClick:()=>J(B(_)),children:e.jsx(Oe,{size:14})})}),e.jsx(te,{content:"插入到笔记",showArrow:!1,children:e.jsx("button",{className:"kb-message__action-btn",onClick:()=>{var U;const F=B(_);F&&(ne("insert_to_note",{status:"success",resultLength:F.length,knowledgePointCount:_.type==="extraction-result"?(U=_.data)==null?void 0:U.knowledgePoints.length:void 0}),i==null||i(F))},children:e.jsx(tn,{size:14})})}),_.type==="extraction-result"&&e.jsx(te,{content:"导出 Markdown",showArrow:!1,children:e.jsx("button",{className:"kb-message__action-btn",onClick:()=>W(_),children:e.jsx(at,{size:14})})})]})]})]},_.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:H,className:"kb-extraction-chat__textarea",value:g,onChange:_=>j(_.target.value),onKeyDown:T,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(gn,{value:w,valueRef:m,onChange:(_,F)=>{ne("change_model",{status:"success",model:_,profileId:F==null?void 0:F.profileId,noteLength:s.length}),y(_),k(F||wt(null,_))},variant:"capsule"})}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx(te,{content:"一键提取知识点",showArrow:!1,children:e.jsx("span",{children:e.jsx("button",{className:"kb-extraction-chat__icon-btn",onClick:O,disabled:l,children:e.jsx(Qe,{size:16})})})}),e.jsx("button",{className:`kb-extraction-chat__send-btn ${g.trim()||l?"kb-extraction-chat__send-btn--active":""}`,onClick:l?p:L,disabled:!g.trim()&&!l,title:l?"停止生成":"发送",children:l?e.jsx(sn,{size:18}):e.jsx(nn,{size:18})})]})]})]})]})},Rt=({result:t})=>{const s=rn.useMemo(()=>tt(t),[t]);return e.jsx("div",{className:"kb-extraction-result-view",children:e.jsx(it,{markdown:s,readOnly:!0,showModeSwitch:!1,initialMode:"wysiwyg",className:"kb-extraction-markdown"})})},$t=[{label:"更新时间",value:"updatedAt"},{label:"创建时间",value:"createdAt"},{label:"标题",value:"title"}],ua=({value:t,onChange:s})=>{var c;const n=((c=$t.find(d=>d.value===t.field))==null?void 0:c.label)||"排序",i=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"})},r=[{content:"排序字段",disabled:!0,className:"kb-sort-dropdown__header"},...$t.map(d=>({content:d.label,value:d.value,prefixIcon:t.field===d.value?e.jsx(xe,{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(xe,{size:14}):e.jsx("div",{style:{width:14}}),suffixIcon:e.jsx(_t,{size:14})},{content:"降序",value:"desc",prefixIcon:t.order==="desc"?e.jsx(xe,{size:14}):e.jsx("div",{style:{width:14}}),suffixIcon:e.jsx(jt,{size:14})}];return e.jsx(Yt,{options:r,onClick:i,trigger:"click",minColumnWidth:120,children:e.jsxs(Ce,{variant:"outline",size:"small",className:"kb-sort-trigger",children:[t.order==="asc"?e.jsx(_t,{size:14,style:{marginRight:4}}):e.jsx(jt,{size:14,style:{marginRight:4}}),n]})})},_a=({initialNoteId:t})=>{var gt;const[s,n]=a.useState([]),[i,r]=a.useState([]),[c,d]=a.useState([]),[u,g]=a.useState(null),[j,w]=a.useState([]),[y,m]=a.useState({}),[k,l]=a.useState(null),[S,x]=a.useState(new Set),[f,z]=a.useState(null),[R,P]=a.useState(""),[H,p]=a.useState(K.loadSortPreference?K.loadSortPreference():{field:"updatedAt",order:"desc"}),[L,O]=a.useState([]),[T,J]=a.useState(!1),[B,W]=a.useState(!1),[_,F]=a.useState(!1),[U,v]=a.useState(null),I=a.useRef(null),N=a.useRef(0),E=a.useRef(null),{confirm:$,confirmDialog:Y}=Vt(),[D,G]=a.useState(!1),[Q,Z]=a.useState("related"),[ie,Se]=a.useState(280),[ke,rt]=a.useState(300),we=a.useRef(!1),_e=a.useRef(!1),Re=a.useRef(null);a.useEffect(()=>{const o=localStorage.getItem("kb-sidebar-width");if(o){const h=parseInt(o,10);!isNaN(h)&&h>100&&h<800&&Se(h)}const b=localStorage.getItem("kb-right-sidebar-width");if(b){const h=parseInt(b,10);!isNaN(h)&&h>100&&h<800&&rt(h)}},[]),a.useEffect(()=>{const o=h=>{if(!Re.current)return;const M=Re.current.getBoundingClientRect();if(we.current){h.preventDefault();const C=Math.max(200,Math.min(600,h.clientX-M.left));Se(C)}else if(_e.current){h.preventDefault();const C=Math.max(200,Math.min(600,M.right-h.clientX));rt(C)}},b=()=>{we.current&&(we.current=!1,localStorage.setItem("kb-sidebar-width",ie.toString()),document.body.style.cursor=""),_e.current&&(_e.current=!1,localStorage.setItem("kb-right-sidebar-width",ke.toString()),document.body.style.cursor="")};return we.current||_e.current?(document.addEventListener("mousemove",o),document.addEventListener("mouseup",b)):document.addEventListener("mousemove",o),document.addEventListener("mousemove",o),document.addEventListener("mouseup",b),()=>{document.removeEventListener("mousemove",o),document.removeEventListener("mouseup",b)}},[ie,ke]);const ns=o=>{o.preventDefault(),we.current=!0,document.body.style.cursor="col-resize"},as=o=>{o.preventDefault(),_e.current=!0,document.body.style.cursor="col-resize"},[ot,is]=a.useState(null),ct=a.useRef(!1),lt=a.useRef(!1);a.useEffect(()=>{if(ct.current)return;ct.current=!0,(async()=>{await K.initialize();try{await pn()}catch(h){console.warn("[KnowledgeBaseContent] 提示词优化模板初始化失败:",h)}await ee();try{const h=await K.getStorageUsage();is(h)}catch{}if(t){ce(t);return}const b=window.__kbPendingNavigation;if(b){window.__kbPendingNavigation=null;const{directoryName:h,autoCreateNote:M}=b;if(h){const A=(await K.getAllDirectories()).find(V=>V.name===h);if(A&&(l(A.id),x(V=>{const X=new Set(V);return X.add(A.id),X}),M)){const V=h==="Skill"?"新Skill":"新笔记",X=await K.createNote(V,A.id);await ee(),x(he=>{const je=new Set(he);return je.add(A.id),je}),z(X.id);const le=await K.getNoteById(X.id);g(le),w([])}}}})()},[]);const ee=a.useCallback(async()=>{const[o,b,h]=await Promise.all([K.getAllDirectories(),K.getAllNoteMetas(),K.getAllTags()]),M=Array.from(new Map(o.map(V=>[V.id,V])).values());n(M);const C=Array.from(new Map(b.map(V=>[V.id,V])).values());r(C);const A=Array.from(new Map(h.map(V=>[V.id,V])).values());d(A),!k&&!f&&M.length>0&&(l(M[0].id),x(new Set([M[0].id]))),await rs(C)},[k,f]),rs=a.useCallback(async o=>{try{const[b,h]=await Promise.all([K.getAllTags(),K.getAllNoteTags()]),M=new Map(b.map(A=>[A.id,A])),C={};for(const A of o)C[A.id]=[];for(const A of h)if(C[A.noteId]&&M.has(A.tagId)){const V=M.get(A.tagId);V&&(C[A.noteId].some(X=>X.id===V.id)||C[A.noteId].push(V))}for(const A in C)C[A].sort((V,X)=>V.name.localeCompare(X.name));m(C)}catch(b){console.error("Failed to refresh note tags map:",b)}},[]);a.useEffect(()=>{if(!R.trim()){v(null);return}return I.current&&clearTimeout(I.current),I.current=setTimeout(async()=>{try{const b=await Gt().search(R,{limit:50,filter:k?{directoryId:k}:{}});v(b)}catch{v(null)}},300),()=>{I.current&&clearTimeout(I.current)}},[R,k]);const ue=a.useMemo(()=>{if(U&&R.trim()){const b=new Set(U.map(C=>C.id)),h=new Map(U.map((C,A)=>[C.id,A]));let M=i.filter(C=>b.has(C.id));if(L.length>0){const C=new Set(L);M=M.filter(A=>(y[A.id]||[]).some(X=>C.has(X.id)))}return M.sort((C,A)=>(h.get(C.id)??0)-(h.get(A.id)??0))}let o=i;if(L.length>0){const b=new Set(L);o=o.filter(h=>(y[h.id]||[]).some(C=>b.has(C.id)))}return K.sortNoteMetas(o,H)},[i,k,R,L,H,y,U]),os=a.useMemo(()=>{const o={},b=new Set;for(const h of ue)b.has(h.id)||(b.add(h.id),o[h.directoryId]=(o[h.directoryId]||0)+1);return o},[ue]),cs=a.useMemo(()=>{var b;const o={};for(const h of ue){const M=o[b=h.directoryId]??(o[b]=[]);M.some(C=>C.id===h.id)||M.push(h)}return o},[ue]),$e=a.useCallback(async o=>{await K.createDirectory(o),await ee()},[ee]),ls=a.useCallback(async(o,b)=>{await K.updateDirectory(o,{name:b}),await ee()},[ee]),ds=a.useCallback(async o=>{var M;const b=s.find(C=>C.id===o);if(!(!b||!await $({title:"确认删除目录",description:`确定要删除目录 "${b.name}" 及其下的所有笔记吗?此操作不可撤销。`,confirmText:"删除",cancelText:"取消",danger:!0})))try{await K.deleteDirectory(o),k===o&&(l(((M=s[0])==null?void 0:M.id)||null),z(null),g(null)),await ee(),q.success("目录已删除")}catch(C){q.error(`删除失败: ${C.message}`)}},[ee,k,s]),us=a.useCallback(async o=>{try{await K.duplicateDirectory(o),await ee(),q.success("目录复制成功")}catch(b){q.error(`复制目录失败: ${b.message}`)}},[ee]),hs=a.useCallback(o=>{x(b=>{const h=new Set(b);return h.has(o)?h.delete(o):h.add(o),h})},[]),ce=a.useCallback(async o=>{const b=++N.current;if(z(o),l(null),w(y[o]||[]),o.startsWith(pe)){const M=o.slice(pe.length),C=Ke.find(A=>A.id===M);if(C){const A=["image","inspiration","grid_image"],V=["ppt"],X=C.mcpTool&&A.some(he=>C.mcpTool.includes(he))?"image":C.mcpTool&&V.some(he=>C.mcpTool.includes(he))?"ppt":void 0,le={id:o,title:C.name,content:C.description||"",directoryId:"",createdAt:0,updatedAt:0,metadata:{...X?{outputType:X}:{}}};b===N.current&&(g(le),w([]))}return}if(o.startsWith(ge)){const M=o.slice(ge.length),C=on(M);if(C){const A={id:o,title:C.name,content:C.content||C.description||"",directoryId:"",createdAt:0,updatedAt:0,metadata:{...C.outputType?{outputType:C.outputType}:{},...C.category?{category:C.category}:{}}};b===N.current&&(g(A),w([]))}return}const h=await K.getNoteById(o);if(b===N.current&&(g(h),h)){const M=await K.getTagsForNote(h.id);if(b!==N.current)return;w(M),x(C=>{const A=new Set(C);return A.add(h.directoryId),A})}},[s,y]),Pe=a.useCallback(async o=>{const b=new Set(i.filter(X=>X.directoryId===o).map(X=>X.title)),h=s.find(X=>X.id===o),M=(h==null?void 0:h.name)==="Skill"?"新Skill":"新笔记";let C=M,A=1;for(;b.has(C);)C=`${M} ${A}`,A++;const V=await K.createNote(C,o);await ee(),x(X=>{const le=new Set(X);return le.add(o),le}),ce(V.id)},[ee,ce,i,s]),Ue=a.useCallback(async(o,b)=>{await K.updateNote(o,b),r(h=>h.map(M=>M.id===o?{...M,...b,updatedAt:Date.now()}:M)),(u==null?void 0:u.id)===o&&g(h=>h&&{...h,...b,updatedAt:Date.now()});try{const h=window.__drawnixBoard;if(h&&h.children){const{Transforms:M}=await Be(async()=>{const{Transforms:C}=await import("./startup-app-CiOE0Z0l.js").then(A=>A.l$);return{Transforms:C}},__vite__mapDeps([0]),import.meta.url);h.children.forEach((C,A)=>{if(C.noteId===o){const V={};b.title!==void 0&&(V.title=b.title),b.content!==void 0&&(V.body=b.content),Object.keys(V).length>0&&M.setNode(h,V,[A])}})}}catch(h){console.warn("[KB] Failed to sync note update to canvas card:",h)}},[u]),ms=a.useCallback(async o=>{if(!u)return;const b=u.content?`
|
|
52
|
+
|
|
53
|
+
`:"",h=(u.content||"")+b+o;await Ue(u.id,{content:h}),q.success("已插入到笔记末尾")},[u,Ue]),fs=a.useCallback(async o=>{var h,M;const b=window.__drawnixBoard;if(!b){q.warning("请先打开画布");return}try{if(b.children.find(me=>me.noteId===o.id)&&!await $({title:"重复插入提醒",description:"画布中已存在关联该笔记的卡片,是否再次插入?",confirmText:"继续插入",cancelText:"取消"}))return;const A=await K.getNoteById(o.id);if(!A){q.error("获取笔记内容失败");return}const{getViewportOrigination:V}=await Be(async()=>{const{getViewportOrigination:me}=await import("./startup-app-CiOE0Z0l.js").then(We=>We.l$);return{getViewportOrigination:me}},__vite__mapDeps([0]),import.meta.url),X=V(b),le=((h=b.host)==null?void 0:h.clientWidth)||800,he=((M=b.host)==null?void 0:M.clientHeight)||600,je=Math.round(window.innerWidth*.5),pt=180,xt=((X==null?void 0:X[0])??0)+le/2-je/2,bt=((X==null?void 0:X[1])??0)+he/2-pt/2,{Transforms:Ns}=await Be(async()=>{const{Transforms:me}=await import("./startup-app-CiOE0Z0l.js").then(We=>We.l$);return{Transforms:me}},__vite__mapDeps([0]),import.meta.url),Cs={type:"card",id:`card-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,title:A.title||"无标题",body:A.content||"",noteId:A.id,fillColor:"#FA8C16",points:[[xt,bt],[xt+je,bt+pt]]};Ns.insertNode(b,Cs,[b.children.length]),q.success("已插入到画布")}catch(C){console.error("[KB] Failed to insert note to canvas:",C),q.error(`插入失败: ${C.message}`)}},[]),gs=a.useCallback(async o=>{try{await K.duplicateNote(o),await ee(),q.success("笔记复制成功")}catch(b){q.error(`复制笔记失败: ${b.message}`)}},[ee]),ps=a.useCallback(async o=>{if(o.startsWith(pe)){q.warning("系统内置 Skill,不可删除");return}if(o.startsWith(ge)){q.warning("外部 Skill,不可在此删除(请在设置中管理外部 Skill 包)");return}const b=i.find(M=>M.id===o);if(!(!b||!await $({title:"确认删除笔记",description:`确定要删除笔记 "${b.title||"无标题"}" 吗?此操作不可撤销。`,confirmText:"删除",cancelText:"取消",danger:!0})))try{await K.deleteNote(o),f===o&&(z(null),g(null),w([])),await ee(),q.success("笔记已删除")}catch(M){q.error(`删除失败: ${M.message}`)}},[f,ee,i]);a.useEffect(()=>{!lt.current&&ue.length>0&&(ce(ue[0].id),lt.current=!0)},[ue,ce]),a.useEffect(()=>{const o=b=>{const{noteId:h}=b.detail;h&&ce(h)};return window.addEventListener("kb:open-note",o),()=>window.removeEventListener("kb:open-note",o)},[ce]),a.useEffect(()=>{const o=async b=>{const{directoryName:h,autoCreateNote:M}=b.detail;if(!h)return;window.__kbPendingNavigation&&(window.__kbPendingNavigation=null);const A=(await K.getAllDirectories()).find(V=>V.name===h);A&&(l(A.id),x(V=>{const X=new Set(V);return X.add(A.id),X}),M&&await Pe(A.id))};return window.addEventListener("kb:navigate",o),()=>window.removeEventListener("kb:navigate",o)},[Pe]);const xs=a.useCallback(async(o,b)=>{await K.setNoteTags(o,b);const h=await K.getTagsForNote(o);w(h),m(C=>({...C,[o]:h}));const M=await K.getAllTags();d(M)},[]),dt=a.useCallback(async o=>{const b=await K.createTag(o),h=await K.getAllTags();return d(h),b},[]),bs=a.useCallback(async(o,b)=>{await K.updateTag(o,{name:b});const h=await K.getAllTags();d(h)},[]),ks=a.useCallback(async o=>{await K.deleteTag(o);const b=await K.getAllTags();if(d(b),u){const h=await K.getTagsForNote(u.id);w(h),m(M=>({...M,[u.id]:h}))}},[u]),ws=a.useCallback(o=>{p(o),K.saveSortPreference&&K.saveSortPreference(o)},[]);a.useEffect(()=>{if(!B)return;const o=b=>{E.current&&!E.current.contains(b.target)&&W(!1)};return document.addEventListener("mousedown",o),()=>document.removeEventListener("mousedown",o)},[B]);const Me=a.useRef(null),ut=a.useCallback(()=>{var o;(o=Me.current)==null||o.click()},[]),_s=a.useCallback(async o=>{const b=o.target.files;if(!(!b||!k)){for(const h of Array.from(b)){if(!h.name.endsWith(".md")&&!h.name.endsWith(".markdown"))continue;const M=await h.text();await Cn(M,k,h.name)}await ee(),Me.current&&(Me.current.value="")}},[k,ee]),ht=a.useCallback(async()=>{try{const o=await Sn(),b=URL.createObjectURL(o),h=document.createElement("a");h.href=b,h.download=`knowledge-base-${new Date().toISOString().slice(0,10)}.zip`,document.body.appendChild(h),h.click(),document.body.removeChild(h),URL.revokeObjectURL(b)}catch(o){console.error("Export failed:",o),q.error("导出失败")}},[]),Ee=a.useRef(null),mt=a.useCallback(()=>{var o;(o=Ee.current)==null||o.click()},[]),js=a.useCallback(async o=>{var h;const b=(h=o.target.files)==null?void 0:h[0];if(b){try{if(b.name.toLowerCase().endsWith(".zip")){const M=await Mn(b);M.noteCount===0&&M.dirCount===0?q.warning("导入完成:没有新增内容(可能已存在重复内容)"):q.success(`导入完成:${M.dirCount} 个新目录、${M.noteCount} 篇笔记`)}else{const M=await b.text(),C=JSON.parse(M);if(C.version!==1&&C.version!==2){q.error("不支持的导入格式");return}const A=await En(C);q.success(`导入完成:${A.dirCount} 个目录、${A.noteCount} 篇笔记、${A.tagCount} 个标签`)}await ee()}catch(M){console.error(M),q.error("导入失败,请确认文件格式正确")}Ee.current&&(Ee.current.value="")}},[ee]),ft=a.useCallback(()=>{const o=window.prompt("请输入目录名称","新建目录");o&&$e(o)},[$e]),ys=a.useCallback(o=>{switch(o.value){case"create-dir":ft();break;case"manage-tags":J(!0);break;case"import-md":ut();break;case"import-zip":mt();break;case"export-zip":ht();break}},[ft,ut,mt,ht]),vs=a.useMemo(()=>[{content:"新建目录",value:"create-dir",prefixIcon:e.jsx(cn,{size:14})},{content:"管理标签",value:"manage-tags",prefixIcon:e.jsx(ln,{size:14})},{content:"导入 Markdown",value:"import-md",prefixIcon:e.jsx(yt,{size:14})},{content:"导入 ZIP",value:"import-zip",prefixIcon:e.jsx(yt,{size:14})},{content:"导出 ZIP",value:"export-zip",prefixIcon:e.jsx(at,{size:14})}],[]);return e.jsxs("div",{className:"kb-drawer",children:[e.jsx("input",{ref:Me,type:"file",accept:".md,.markdown",multiple:!0,style:{display:"none"},onChange:_s}),e.jsx("input",{ref:Ee,type:"file",accept:".json,.zip",style:{display:"none"},onChange:js}),e.jsxs("div",{className:"kb-drawer__body",ref:Re,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(ze,{size:"small",prefixIcon:e.jsx(Kt,{size:14}),placeholder:"搜索笔记...",value:R,onChange:o=>P(o),clearable:!0,style:{flex:1}}),e.jsx(Yt,{trigger:"click",options:vs,onClick:ys,minColumnWidth:120,maxColumnWidth:200,popupProps:{overlayStyle:{width:200}},children:e.jsx(te,{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:o=>o.currentTarget.style.backgroundColor="var(--td-bg-color-container-hover)",onMouseLeave:o=>o.currentTarget.style.backgroundColor="transparent",children:e.jsx(dn,{size:18})})})})]}),e.jsxs("div",{className:"kb-drawer__filters",style:{display:"flex",gap:"8px",alignItems:"center"},children:[e.jsx(Xn,{allTags:c,selectedTagIds:L,onSelectedChange:O}),e.jsx("div",{style:{flex:1}}),e.jsx(ua,{value:H,onChange:ws})]})]}),e.jsx(An,{directories:s,notesByDir:cs,noteTagsMap:y,noteCounts:os,selectedDirId:k,selectedNoteId:f,expandedDirIds:S,onSelectDir:o=>{l(o),z(null),g(null)},onToggleExpand:hs,onCreateDir:$e,onRenameDir:ls,onDeleteDir:ds,onDuplicateDir:us,onSelectNote:ce,onCreateNote:Pe,onDeleteNote:ps,onDuplicateNote:gs,isCreatingDir:_,onCancelCreateDir:()=>F(!1),onInsertNoteToCanvas:fs}),ot&&e.jsxs("div",{className:"kb-drawer__storage-bar",children:[e.jsx(un,{size:12}),e.jsxs("span",{className:"kb-drawer__storage-text",children:["已用 ",ha(ot.used)]})]})]}),e.jsx("div",{className:"kb-resizer",onMouseDown:ns}),e.jsx("div",{className:"kb-drawer__editor",children:e.jsx(Vn,{note:u,allTags:c,noteTags:j,readOnly:!!(f&&(f.startsWith(pe)||f.startsWith(ge))),isSkillDirectory:!!(u&&(((gt=s.find(o=>o.id===u.directoryId))==null?void 0:gt.name)==="Skill"||f&&f.startsWith(pe)||f&&f.startsWith(ge))),onUpdateNote:Ue,onSetNoteTags:xs,onCreateTag:dt})}),u&&e.jsx(e.Fragment,{children:D?e.jsx(te,{content:"展开侧边栏",showArrow:!1,children:e.jsx("button",{className:"kb-drawer__right-toggle",onClick:()=>G(!1),children:e.jsx(hn,{size:14})})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"kb-resizer",onMouseDown:as}),e.jsxs("div",{className:"kb-drawer__right-sidebar",style:{width:ke},children:[e.jsxs("div",{className:"kb-drawer__right-header",children:[e.jsxs("div",{className:"kb-drawer__right-tabs",children:[e.jsx(te,{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(Xt,{size:14})})}),e.jsx(te,{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(Qe,{size:14})})})]}),e.jsx(te,{content:"收起侧边栏",showArrow:!1,children:e.jsx("button",{className:"kb-drawer__right-collapse-btn",onClick:()=>G(!0),children:e.jsx(mn,{size:14})})})]}),e.jsx("div",{className:"kb-drawer__right-content",children:Q==="related"?e.jsx(Yn,{currentNoteId:u.id,allNotes:i,noteTagsMap:y,onSelectNote:ce}):e.jsx(da,{noteId:u.id,noteContent:u.content,noteTitle:u.title,onSaved:()=>ee(),onInsertToNote:ms},u.id)})]})]})})]}),e.jsx(qn,{visible:T,onClose:()=>J(!1),allTags:c,onCreateTag:dt,onUpdateTag:bs,onDeleteTag:ks}),Y]})};function ha(t){if(t===0)return"0 B";const s=["B","KB","MB","GB"],n=Math.floor(Math.log(t)/Math.log(1024));return`${(t/Math.pow(1024,n)).toFixed(1)} ${s[n]}`}export{_a as default};
|