aitu-app 1.0.0 → 1.0.2
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-DyUPmMV6.js → CanvasAudioPlayer-HtUs8HDj.js} +2 -2
- package/assets/ComicCreator-DhxXCyJR.js +43 -0
- package/assets/{DeferredAIInputBar-Cq0t7wNK.js → DeferredAIInputBar-B2R2-2RU.js} +3 -3
- package/assets/{DrawnixDeferredFeatures-B9y0GPYR.js → DrawnixDeferredFeatures-DHTr0c-V.js} +2 -2
- package/assets/{KnowledgeBaseContent-C8zmce09.js → KnowledgeBaseContent-CAq5kXdt.js} +6 -6
- package/assets/{MVCreator-Bl8GH4mR.js → MVCreator-B9uaRsGE.js} +16 -16
- package/assets/{ModelBenchmarkWorkbench-BwfeZDt-.js → ModelBenchmarkWorkbench-CK33zizl.js} +1 -1
- package/assets/{MusicAnalyzer-CdMhl-kU.js → MusicAnalyzer-D2NTonEA.js} +1 -1
- package/assets/{PromptHistoryTool-CCxoST3H.js → PromptHistoryTool-q6vOxFr6.js} +1 -1
- package/assets/{ResizableDivider-D1jgqdmh.js → ResizableDivider-BvT-DCEo.js} +2 -2
- package/assets/{TaskQueuePanel-WF6aq1G7.js → TaskQueuePanel-PayswYlG.js} +1 -1
- package/assets/{VideoAnalyzer-BOqRFjZ9.js → VideoAnalyzer-DnowtohS.js} +1 -1
- package/assets/{VideoAnalyzer-BrEKSLeh.js → VideoAnalyzer-DoaGlK92.js} +2 -2
- package/assets/{ai-chat-DbjmzngX.css → ai-chat-BlxYfB4O.css} +1 -1
- package/assets/ai-chat-BnWVpTEI.js +2977 -0
- package/assets/{batch-image-generation-DyWeiTsw.js → batch-image-generation-CkmX4dem.js} +5 -5
- package/assets/{bootstrap-DadYvnge.js → bootstrap-CQRLkOtk.js} +7 -7
- package/assets/{clean-confirm-CpWpcTF5.js → clean-confirm-CIViVQ8s.js} +1 -1
- package/assets/{diagram-engines-C0Ljec4Z.js → diagram-engines-DpAsX7pc.js} +3 -3
- package/assets/{editor-engines-Dz5Mk5YB.js → editor-engines-9_72Ghfn.js} +1 -1
- package/assets/{external-skill-service-BQUJLLLc.js → external-skill-service-BN8ZCtPn.js} +1 -1
- package/assets/{frame-size-matcher-2sxA9X-P.js → frame-size-matcher-9rxQ-bAY.js} +1 -1
- package/assets/{index-CRuDVxTu.js → index-291TeU7i.js} +1 -1
- package/assets/{index-BNtKpMlh.js → index-BJ-vS89P.js} +1 -1
- package/assets/{index-Ct7MFvFo.js → index-BSZAS0wO.js} +1 -1
- package/assets/{index-BfdBtWT6.js → index-C7DAD_xK.js} +1 -1
- package/assets/{index-o8hm5yhT.js → index-CIgiIDgZ.js} +1 -1
- package/assets/{index-BwW4Qp-A.js → index-CpHWUe__.js} +1 -1
- package/assets/{index-D7UBK5T7.js → index-D1LQ9eQM.js} +1 -1
- package/assets/{index-D_Yn26AT.js → index-DRGxmFyd.js} +1 -1
- package/assets/{index-CBMgStgL.js → index-DmtcRYr8.js} +1 -1
- package/assets/{index.es-CYBRnsv6.js → index.es-Ch45-H39.js} +1 -1
- package/assets/{jspdf.es.min-I7TkFvGI.js → jspdf.es.min-bNprb1JY.js} +3 -3
- package/assets/{link-popup-fCfgZp17.js → link-popup-B6ReK6iq.js} +1 -1
- package/assets/{markdown-to-drawnix-3yksNvbU.js → markdown-to-drawnix-BqT-3zQO.js} +3 -3
- package/assets/{mermaid-to-drawnix-C7rF-30X.js → mermaid-to-drawnix-CSctnpU0.js} +3 -3
- package/assets/{model-benchmark-launcher-uYoranwQ.js → model-benchmark-launcher-DNMp2MLQ.js} +1 -1
- package/assets/{photo-wall-splitter-CfRBAwCy.js → photo-wall-splitter-DhBTEpdG.js} +1 -1
- package/assets/{popup-toolbar-tKtYPGvw.js → popup-toolbar-BChsudwW.js} +7 -7
- package/assets/{prompt-utils-C_mjEqkz.js → prompt-utils-BX0pRV-Z.js} +1 -1
- package/assets/quick-creation-toolbar-3-AYFpEF.js +2 -0
- package/assets/{settings-dialog-DfK6bcBd.js → settings-dialog-Ccemaout.js} +1 -1
- package/assets/{size-picker-DvMt8S3Z.js → size-picker-DTrdjyLh.js} +1 -1
- package/assets/{skill-dsl-parser-CTM4hEIp.js → skill-dsl-parser-ZR--uu5h.js} +1 -1
- package/assets/{startup-app-9gZEGv85.js → startup-app-CH3QzBb4.js} +2 -2
- package/assets/{task-sync-D7bw59_K.js → task-sync-C5XXOQ5m.js} +1 -1
- package/assets/{tool-windows-BnDZa9FH.js → tool-windows-Bf_pMml-.js} +6 -6
- package/assets/ttd-dialog-CohjwODB.js +6 -0
- package/assets/{ttd-dialog-submit-shortcut-UfHT9Z9k.js → ttd-dialog-submit-shortcut-BVB8O_wE.js} +1 -1
- package/assets/{useCharacters-6u0Wuwt4.js → useCharacters-CFlPvydq.js} +1 -1
- package/assets/{useWorkflowSubmission-DTWha6Vn.js → useWorkflowSubmission-CKkOEcAT.js} +3 -3
- package/assets/{video-merge-webcodecs-Cwy2df91.js → video-merge-webcodecs-BInWo9HA.js} +2 -2
- package/assets/{video-recovery-service-CgZ3pA_1.js → video-recovery-service-DITdD0pC.js} +1 -1
- package/assets/{workflow-generation-utils-BPT49S-Z.js → workflow-generation-utils-e0nRpAgJ.js} +3 -3
- package/assets/{workflow-submission-service-C-6Uf9FA.js → workflow-submission-service-BqiL_5Cj.js} +3 -3
- package/changelog.json +105 -6
- package/idle-prefetch-manifest.json +136 -288
- package/manifest.json +3 -3
- package/package.json +1 -1
- package/precache-manifest.json +6 -6
- package/sw.js +1 -1
- package/version.json +63 -3
- package/.DS_Store +0 -0
- package/assets/ComicCreator-DjOhYrZt.js +0 -43
- package/assets/ai-chat-B-XdoWBQ.js +0 -2976
- package/assets/quick-creation-toolbar-CrQ0g0kO.js +0 -2
- package/assets/ttd-dialog-DS6KiOOa.js +0 -6
- package/assets/useMediaViewer-BrBFopM-.js +0 -1
- package/user-manual/gifs//346/200/235/347/273/264/345/257/274/345/233/276/345/210/233/345/273/272/346/274/224/347/244/272.gif +0 -0
- package/user-manual/screenshots/ai-step-0.png +0 -0
- package/user-manual/screenshots/ai-step-1.png +0 -0
- package/user-manual/screenshots/ai-step-2.png +0 -0
- package/user-manual/screenshots/ai-step-3.png +0 -0
- package/user-manual/screenshots/app-menu.png +0 -0
- package/user-manual/screenshots/backup-restore.png +0 -0
- package/user-manual/screenshots/canvas-tools.png +0 -0
- package/user-manual/screenshots/debug-panel.png +0 -0
- package/user-manual/screenshots/drawing-step-0.png +0 -0
- package/user-manual/screenshots/drawing-step-1.png +0 -0
- package/user-manual/screenshots/drawing-step-2.png +0 -0
- package/user-manual/screenshots/edit-selected.png +0 -0
- package/user-manual/screenshots/element-selected.png +0 -0
- package/user-manual/screenshots/flowchart-step-1.png +0 -0
- package/user-manual/screenshots/flowchart-step-2.png +0 -0
- package/user-manual/screenshots/flowchart-step-3.png +0 -0
- package/user-manual/screenshots/image-preview-empty.png +0 -0
- package/user-manual/screenshots/insert-from-library.png +0 -0
- package/user-manual/screenshots/insert-tools.png +0 -0
- package/user-manual/screenshots/inspiration-step-1.png +0 -0
- package/user-manual/screenshots/inspiration-step-2.png +0 -0
- package/user-manual/screenshots/media-library.png +0 -0
- package/user-manual/screenshots/mindmap-step-1.png +0 -0
- package/user-manual/screenshots/mindmap-step-2.png +0 -0
- package/user-manual/screenshots/mindmap-toolbar-menu.png +0 -0
- package/user-manual/screenshots/project-drawer.png +0 -0
- package/user-manual/screenshots/settings-dialog.png +0 -0
- package/user-manual/screenshots/shape-step-1.png +0 -0
- package/user-manual/screenshots/shape-step-2.png +0 -0
- package/user-manual/screenshots/text-step-1.png +0 -0
- package/user-manual/screenshots/text-step-2.png +0 -0
- package/user-manual/screenshots/toolbox-drawer.png +0 -0
- package/user-manual/screenshots/toolbox-entry.png +0 -0
- package/user-manual/screenshots/video-entry.png +0 -0
- package/user-manual/screenshots/view-navigation.png +0 -0
- package/user-manual/screenshots/zoom-menu.png +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ai-chat-
|
|
2
|
-
import{Q as xe,T as ve,S as rt,U as et,V as Be,W as Y,X as Ps,Y as rn,Z as Je,_ as Es,$ as st,a0 as wt,a1 as As,a2 as cn,P as m,a3 as Hg,R as Ie,a4 as Xo,a5 as Gg,a6 as Zc,a7 as Xc,a8 as o,a9 as Wg,aa as St,ab as Le,ac as Vg,ad as wf,ae as xf,af as ql,ag as Yl,ah as Kg,ai as qg,aj as Yg,ak as Tt,al as Zg,am as Xg,an as Jg,ao as ee,ap as Qg,aq as ey,ar as ty,as as bf,at as Fe,au as ny,av as ry,aw as Jn,ax as sy,ay as Zl,az as Qa,aA as _f,aB as Xl,aC as ls,aD as He,aE as ln,aF as jr,aG as Jl,aH as ay,aI as Jc,aJ as iy,aK as oy,aL as ly,aM as cy,aN as dy,aO as uy,aP as hy,aQ as fy,aR as my,aS as Gt,aT as py,aU as on,aV as gy,aW as yy,aX as vy,aY as vs,aZ as wy,a_ as xy,a$ as by,b0 as _y,b1 as Ql,b2 as Tf,b3 as Sf,b4 as If,b5 as kf,b6 as Cf,b7 as Qc,b8 as Pf,b9 as Ty,ba as ed,bb as Ef,bc as Sy,bd as kt,be as Iy,bf as ns,bg as Jo,bh as Qo,bi as td,bj as ht,bk as at,bl as dt,bm as ei,bn as ky,bo as Gn,bp as Ln,bq as It,br as Cy,bs as ta,bt as rs,bu as Py,bv as Ey,bw as Ay,bx as jy,by as Oy,bz as My,bA as Dy,bB as ti,bC as ni,bD as ri,bE as Af,bF as jf,bG as Of,bH as Mf,bI as Df,bJ as Ny,bK as ec,bL as Nf,bM as tc,bN as si,bO as Ry,bP as _e,bQ as nc,bR as rc,bS as sc,bT as Rf,bU as Ly,bV as Fy,bW as By,bX as zy,bY as $y,bZ as Uy,b_ as nd,b$ as pn,c0 as Lr,c1 as pr,c2 as Hy,c3 as Gy,c4 as Wy,c5 as Kr,c6 as nn,c7 as ct,c8 as Xt,c9 as mt,ca as na,cb as Vy,cc as Ky,cd as qy,ce as Yy,cf as Zy,cg as Xy,ch as Jy,ci as Qy,cj as ev,ck as tv,cl as nv,cm as ss,cn as qr,co as Me,cp as Lf,cq as Ff,cr as Bf,cs as rv,ct as Fr,cu as Ma,cv as ac,cw as zf,cx as sv,cy as rd,cz as av,cA as iv,cB as ws,cC as $f,cD as ov,cE as lv,cF as sd,cG as Uf,cH as cv,cI as Hf,cJ as ic,cK as dv,cL as uv,cM as kn,cN as hn,cO as Br,cP as Gf,cQ as ad,cR as hv,cS as id,cT as fv,cU as er,cV as mv,cW as pv,cX as gv,cY as el,cZ as yv,c_ as vv,c$ as $t,d0 as oc,d1 as Zn,d2 as wv,d3 as xv,d4 as bv,d5 as _v,d6 as Tv,d7 as Yt,d8 as js,d9 as Bi,da as zi,db as cs,dc as Sv,dd as Mn,de as Iv,df as $i,dg as kv,dh as Ui,di as Hi,dj as od,dk as Cv,dl as Pv,dm as Ev,dn as tl,dp as nl,dq as Av,dr as Wf,ds as ld,dt as jv,du as Ov,dv as Vf,dw as xs,dx as qt,dy as cd,dz as dd,dA as zr,dB as Da,dC as Mv,dD as Dv,dE as Nv,dF as ra,dG as Rv,dH as Lv,dI as Fv,dJ as Bv,dK as bs,dL as zv,dM as $v,dN as Uv,dO as Or,dP as Pn,dQ as fn,dR as vn,dS as Hv,dT as Gv,dU as Wv,dV as Kf,dW as Vv,dX as Kv,dY as qv,dZ as Yv,d_ as Na,d$ as Zv,e0 as Xv,e1 as Jv,e2 as Qv,e3 as Nt,e4 as rl,e5 as ai,e6 as Kn,e7 as ud,e8 as Dn,e9 as ew,ea as tw,eb as qf,ec as nw,ed as rw,ee as $r,ef as sw,eg as Ra,eh as aw,ei as iw,ej as ow,ek as lw,el as sa,em as cw,en as dw,eo as hd,ep as aa,eq as Yf,er as uw,es as hw,et as fd,eu as fw,ev as ii,ew as Gi,ex as md,ey as mw,ez as Wi,eA as Vi,eB as Zf,eC as pw,eD as sl,eE as Ki,eF as yr,eG as ds,eH as gw,eI as yw,eJ as _s,eK as al,eL as vw,eM as Pr,eN as sn,eO as ww,eP as xw,eQ as pd,eR as bw,eS as _w,eT as Tw,eU as Os,eV as il,eW as gd,eX as Sw,eY as _n,eZ as Iw,e_ as kw,e$ as Cw,f0 as ol,f1 as En,f2 as Pw,f3 as Ew,f4 as Aw,f5 as Xf,f6 as jw,f7 as Ow,f8 as yd,f9 as Mw,fa as Dw,fb as Jf,fc as Qf,fd as Nw,fe as Rw,ff as Lw,fg as Fw,fh as Bw,fi as em,fj as tm,fk as ll,fl as nm,fm as zw,fn as rm,fo as $w,fp as cl,fq as lc,fr as Uw,fs as Hw,ft as vd,fu as Gw,fv as Ww,fw as sm,fx as am,fy as im,fz as om,fA as Vw,fB as wd,fC as Kw,fD as qw,fE as Yw,fF as Ms,fG as lm,fH as Tn,fI as Sn,fJ as Ti,fK as Ds,fL as Zw,fM as Xw,fN as Jw,fO as Qw,fP as cm,fQ as dm,fR as um,fS as hm,fT as ex,fU as fm,fV as tx,fW as xd,fX as nx,fY as rx,fZ as sx,f_ as ax,f$ as ix,g0 as qi,g1 as ox,g2 as Yi,g3 as lx,g4 as cx,g5 as bd,g6 as dx,g7 as ux,g8 as da,g9 as _d,ga as hx,gb as cc,gc as fx,gd as mx,ge as Td,gf as oi,gg as us,gh as mm,gi as px,gj as gx,gk as yx,gl as vx,gm as wx,gn as Sd,go as Id,gp as xx,gq as bx,gr as _x,gs as kd,gt as vr,gu as Cd,gv as Pd,gw as Tx,gx as Sx,gy as Ix,gz as kx,gA as Cx,gB as Px,gC as Ex}from"./ai-chat-B-XdoWBQ.js";import{_ as Xe,g as dc,a as ua}from"./startup-runtime-BrfuwjQS.js";let La=null;async function Ax(){if(xe.getAllTasks().some(s=>s.status===ve.PENDING||s.status===ve.PROCESSING))return!0;const{workflowSubmissionService:n}=await Xe(async()=>{const{workflowSubmissionService:s}=await import("./workflow-submission-service-C-6Uf9FA.js").then(a=>a.a);return{workflowSubmissionService:s}},__vite__mapDeps([0]),import.meta.url);return La=n,n.getRunningWorkflows().length>0}function jx(){return xe.getAllTasks().some(n=>n.status===ve.PENDING||n.status===ve.PROCESSING)?!0:((La==null?void 0:La.getRunningWorkflows().length)||0)>0}async function Yr(){return await Ax()&&!window.confirm("当前有正在进行的 AI 生成任务,刷新页面会中断这些任务。确定要刷新吗?")?!1:(window.location.reload(),!0)}const Fa=7,Ox=["hand","selection","freehand","shape","text","image","media-library","ai-image","ai-video"],dl=["hand","selection","freehand","shape","text","image","media-library","ai-image","ai-video","lasso","mind","arrow","theme","mermaid-to-drawnix","markdown-to-drawnix","undo","redo"];function Er(){return{buttons:dl.map((e,n)=>({id:e,visible:Ox.includes(e),order:n})),version:Fa,updatedAt:Date.now()}}function uc(t){return t.buttons.filter(e=>e.visible).sort((e,n)=>e.order-n.order)}function pm(t){return t.buttons.filter(e=>!e.visible).sort((e,n)=>e.order-n.order)}function Mx(t,e,n){const r=t.buttons.map(s=>s.id===e?{...s,visible:n}:s);return{...t,buttons:r,updatedAt:Date.now()}}function Dx(t,e,n,r){const s=uc(t),a=pm(t),i=r?s:a,[l]=i.splice(e,1);i.splice(n,0,l);const d=t.buttons.map(c=>{const h=s.findIndex(p=>p.id===c.id),u=a.findIndex(p=>p.id===c.id);return h!==-1?{...c,order:h}:u!==-1?{...c,order:s.length+u}:c});return{...t,buttons:d,updatedAt:Date.now()}}function Nx(t,e,n){const r=uc(t),s=n??r.length;let a=t.buttons.map(c=>c.id===e?{...c,visible:!0}:c);const i=a.filter(c=>c.visible&&c.id!==e).sort((c,h)=>c.order-h.order),l=a.find(c=>c.id===e);i.splice(s,0,l);const d=a.filter(c=>!c.visible).sort((c,h)=>c.order-h.order);return a=a.map(c=>{const h=i.findIndex(p=>p.id===c.id),u=d.findIndex(p=>p.id===c.id);return h!==-1?{...c,order:h}:u!==-1?{...c,order:i.length+u}:c}),{...t,buttons:a,updatedAt:Date.now()}}function Rx(t,e){let n=t.buttons.map(a=>a.id===e?{...a,visible:!1}:a);const r=n.filter(a=>a.visible).sort((a,i)=>a.order-i.order),s=n.filter(a=>!a.visible).sort((a,i)=>a.order-i.order);return n=n.map(a=>{const i=r.findIndex(d=>d.id===a.id),l=s.findIndex(d=>d.id===a.id);return i!==-1?{...a,order:i}:l!==-1?{...a,order:r.length+l}:a}),{...t,buttons:n,updatedAt:Date.now()}}const Zi=et.TOOLBAR_CONFIG,Ed=["hand","selection","text","media-library","ai-image","ai-video","mind","freehand","arrow","shape","image","theme","mermaid-to-drawnix","markdown-to-drawnix","undo","redo","zoom"],Lx=["hand","selection","text","media-library","ai-image","ai-video"];class Fx{constructor(){this.config=null,this.initialized=!1,this.initPromise=null}async initializeAsync(){return this.initialized&&this.config?this.config:this.initPromise?this.initPromise:(this.initPromise=this.doInitialize(),this.initPromise)}async doInitialize(){try{const e=await rt.get(Zi);e?this.config=this.migrateConfig(e):(this.config=Er(),await this.saveToStorageAsync(this.config))}catch(e){console.warn("[ToolbarConfigService] Failed to load from IndexedDB:",e),this.config=Er()}return this.initialized=!0,this.config}initialize(){return this.initialized&&this.config?this.config:(this.config||(this.config=Er(),this.initializeAsync().then(e=>{this.config&&e&&(this.config=e)})),this.initialized=!0,this.config)}getConfig(){return this.config?this.config:this.initialize()}setButtonVisibility(e,n){return this.config||this.initialize(),this.config=Mx(this.config,e,n),this.saveToStorage(this.config),this.config}reorderButton(e,n,r){return this.config||this.initialize(),this.config=Dx(this.config,e,n,r),this.saveToStorage(this.config),this.config}showButton(e,n){return this.config||this.initialize(),this.config=Nx(this.config,e,n),this.saveToStorage(this.config),this.config}hideButton(e){return this.config||this.initialize(),this.config=Rx(this.config,e),this.saveToStorage(this.config),this.config}updateConfig(e){return this.config||this.initialize(),this.config={...this.config,...e,updatedAt:Date.now()},this.saveToStorage(this.config),this.config}resetToDefault(){return this.config=Er(),this.saveToStorage(this.config),this.config}saveToStorage(e){rt.set(Zi,e).catch(n=>{console.error("[ToolbarConfigService] Failed to save config:",n)})}async saveToStorageAsync(e){try{await rt.set(Zi,e)}catch(n){console.error("[ToolbarConfigService] Failed to save config:",n)}}migrateConfig(e){const r=(e.version??1)<Fa&&this.matchesLegacyDefaultLayout(e),s=new Set(e.buttons.map(d=>d.id)),a=[];dl.forEach(d=>{s.has(d)||a.push({id:d,visible:!1,order:e.buttons.length+a.length})}),a.length>0&&(e={...e,buttons:[...e.buttons,...a],updatedAt:Date.now()});const i=new Set(dl),l=e.buttons.filter(d=>i.has(d.id));return l.length!==e.buttons.length&&(e={...e,buttons:l,updatedAt:Date.now()}),r&&(e=Er()),e.version!==Fa&&(e={...e,version:Fa}),e}matchesLegacyDefaultLayout(e){return e.buttons.length!==Ed.length?!1:Ed.every((n,r)=>{const s=e.buttons.find(i=>i.id===n);if(!s)return!1;const a=Lx.includes(n);return s.order===r&&s.visible===a})}}const wr=new Fx,Bx=.75,zx=.9,$x=6e4;class Ux{constructor(){this.checkTimer=null,this.cleanupHandlers=[],this.lastCleanupTime=0,this.cleanupCooldown=6e4}getMemoryStats(){const e=performance;if(!e.memory)return null;const{usedJSHeapSize:n,totalJSHeapSize:r,jsHeapSizeLimit:s}=e.memory,a=n/s*100;return{usedJSHeapSize:n,totalJSHeapSize:r,jsHeapSizeLimit:s,usagePercent:a,isUnderPressure:a>Bx*100,formatted:{used:this.formatBytes(n),total:this.formatBytes(r),limit:this.formatBytes(s)}}}formatBytes(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}registerCleanupHandler(e){this.cleanupHandlers.push(e),this.cleanupHandlers.sort((n,r)=>n.priority-r.priority)}unregisterCleanupHandler(e){this.cleanupHandlers=this.cleanupHandlers.filter(n=>n.name!==e)}async triggerCleanup(e=!1){const n=Date.now();if(!e&&n-this.lastCleanupTime<this.cleanupCooldown)return;this.lastCleanupTime=n;const r=this.getMemoryStats();for(const a of this.cleanupHandlers)try{await a.cleanup()}catch(i){console.error(`[MemoryMonitor] Cleanup failed: ${a.name}`,i)}typeof globalThis.gc=="function"&&globalThis.gc();const s=this.getMemoryStats();r&&s&&r.usedJSHeapSize-s.usedJSHeapSize}checkMemory(){const e=this.getMemoryStats();if(e){if(e.usagePercent>zx*100){console.warn(`[MemoryMonitor] Critical memory pressure: ${e.usagePercent.toFixed(1)}%`),this.triggerCleanup(!0);return}e.isUnderPressure&&(console.warn(`[MemoryMonitor] Memory pressure: ${e.usagePercent.toFixed(1)}%`),this.triggerCleanup())}}start(){this.checkTimer||!this.getMemoryStats()||(this.checkTimer=setInterval(()=>this.checkMemory(),$x),this.checkMemory())}stop(){this.checkTimer&&(clearInterval(this.checkTimer),this.checkTimer=null)}logMemoryStatus(){this.getMemoryStats()}}const gm=new Ux;gm.registerCleanupHandler({name:"idle-gc-hint",priority:10,cleanup:async()=>new Promise(t=>{"requestIdleCallback"in window?window.requestIdleCallback(()=>{t()},{timeout:1e3}):setTimeout(t,0)})});var Xi,Ad;function Hx(){if(Ad)return Xi;Ad=1,Xi=s;var t="֑-߿יִ-﷽ﹰ-ﻼ",e="A-Za-zÀ-ÖØ-öø-ʸ̀-ࠀ-Ⰰ-︀--",n=new RegExp("^[^"+e+"]*["+t+"]"),r=new RegExp("^[^"+t+"]*["+e+"]");function s(a){return a=String(a||""),n.test(a)?"rtl":r.test(a)?"ltr":"neutral"}return Xi}var Gx=Hx();const ym=dc(Gx);var Ji,jd;function hc(){if(jd)return Ji;jd=1;function t(e){var n=typeof e;return e!=null&&(n=="object"||n=="function")}return Ji=t,Ji}var Qi,Od;function Wx(){if(Od)return Qi;Od=1;var t=typeof ua=="object"&&ua&&ua.Object===Object&&ua;return Qi=t,Qi}var eo,Md;function vm(){if(Md)return eo;Md=1;var t=Wx(),e=typeof self=="object"&&self&&self.Object===Object&&self,n=t||e||Function("return this")();return eo=n,eo}var to,Dd;function Vx(){if(Dd)return to;Dd=1;var t=vm(),e=function(){return t.Date.now()};return to=e,to}var no,Nd;function Kx(){if(Nd)return no;Nd=1;var t=/\s/;function e(n){for(var r=n.length;r--&&t.test(n.charAt(r)););return r}return no=e,no}var ro,Rd;function qx(){if(Rd)return ro;Rd=1;var t=Kx(),e=/^\s+/;function n(r){return r&&r.slice(0,t(r)+1).replace(e,"")}return ro=n,ro}var so,Ld;function wm(){if(Ld)return so;Ld=1;var t=vm(),e=t.Symbol;return so=e,so}var ao,Fd;function Yx(){if(Fd)return ao;Fd=1;var t=wm(),e=Object.prototype,n=e.hasOwnProperty,r=e.toString,s=t?t.toStringTag:void 0;function a(i){var l=n.call(i,s),d=i[s];try{i[s]=void 0;var c=!0}catch{}var h=r.call(i);return c&&(l?i[s]=d:delete i[s]),h}return ao=a,ao}var io,Bd;function Zx(){if(Bd)return io;Bd=1;var t=Object.prototype,e=t.toString;function n(r){return e.call(r)}return io=n,io}var oo,zd;function Xx(){if(zd)return oo;zd=1;var t=wm(),e=Yx(),n=Zx(),r="[object Null]",s="[object Undefined]",a=t?t.toStringTag:void 0;function i(l){return l==null?l===void 0?s:r:a&&a in Object(l)?e(l):n(l)}return oo=i,oo}var lo,$d;function Jx(){if($d)return lo;$d=1;function t(e){return e!=null&&typeof e=="object"}return lo=t,lo}var co,Ud;function Qx(){if(Ud)return co;Ud=1;var t=Xx(),e=Jx(),n="[object Symbol]";function r(s){return typeof s=="symbol"||e(s)&&t(s)==n}return co=r,co}var uo,Hd;function eb(){if(Hd)return uo;Hd=1;var t=qx(),e=hc(),n=Qx(),r=NaN,s=/^[-+]0x[0-9a-f]+$/i,a=/^0b[01]+$/i,i=/^0o[0-7]+$/i,l=parseInt;function d(c){if(typeof c=="number")return c;if(n(c))return r;if(e(c)){var h=typeof c.valueOf=="function"?c.valueOf():c;c=e(h)?h+"":h}if(typeof c!="string")return c===0?c:+c;c=t(c);var u=a.test(c);return u||i.test(c)?l(c.slice(2),u?2:8):s.test(c)?r:+c}return uo=d,uo}var ho,Gd;function xm(){if(Gd)return ho;Gd=1;var t=hc(),e=Vx(),n=eb(),r="Expected a function",s=Math.max,a=Math.min;function i(l,d,c){var h,u,p,y,f,g,w=0,x=!1,v=!1,_=!0;if(typeof l!="function")throw new TypeError(r);d=n(d)||0,t(c)&&(x=!!c.leading,v="maxWait"in c,p=v?s(n(c.maxWait)||0,d):p,_="trailing"in c?!!c.trailing:_);function T(O){var G=h,C=u;return h=u=void 0,w=O,y=l.apply(C,G),y}function b(O){return w=O,f=setTimeout(k,d),x?T(O):y}function I(O){var G=O-g,C=O-w,P=d-G;return v?a(P,p-C):P}function A(O){var G=O-g,C=O-w;return g===void 0||G>=d||G<0||v&&C>=p}function k(){var O=e();if(A(O))return U(O);f=setTimeout(k,I(O))}function U(O){return f=void 0,_&&h?T(O):(h=u=void 0,y)}function D(){f!==void 0&&clearTimeout(f),w=0,h=g=u=f=void 0}function X(){return f===void 0?y:U(e())}function L(){var O=e(),G=A(O);if(h=arguments,u=this,g=O,G){if(f===void 0)return b(g);if(v)return clearTimeout(f),f=setTimeout(k,d),T(g)}return f===void 0&&(f=setTimeout(k,d)),y}return L.cancel=D,L.flush=X,L}return ho=i,ho}var tb=xm();const nb=dc(tb);var fo,Wd;function rb(){if(Wd)return fo;Wd=1;var t=xm(),e=hc(),n="Expected a function";function r(s,a,i){var l=!0,d=!0;if(typeof s!="function")throw new TypeError(n);return e(i)&&(l="leading"in i?!!i.leading:l,d="trailing"in i?!!i.trailing:d),t(s,a,{leading:l,maxWait:a,trailing:d})}return fo=r,fo}var sb=rb();const ab=dc(sb),Vd=t=>typeof t=="object"&&t!=null&&t.nodeType===1,Kd=(t,e)=>(!e||t!=="hidden")&&t!=="visible"&&t!=="clip",ha=(t,e)=>{if(t.clientHeight<t.scrollHeight||t.clientWidth<t.scrollWidth){const n=getComputedStyle(t,null);return Kd(n.overflowY,e)||Kd(n.overflowX,e)||(r=>{const s=(a=>{if(!a.ownerDocument||!a.ownerDocument.defaultView)return null;try{return a.ownerDocument.defaultView.frameElement}catch{return null}})(r);return!!s&&(s.clientHeight<r.scrollHeight||s.clientWidth<r.scrollWidth)})(t)}return!1},fa=(t,e,n,r,s,a,i,l)=>a<t&&i>e||a>t&&i<e?0:a<=t&&l<=n||i>=e&&l>=n?a-t-r:i>e&&l<n||a<t&&l>n?i-e+s:0,ib=t=>{const e=t.parentElement;return e??(t.getRootNode().host||null)},qd=(t,e)=>{var n,r,s,a;if(typeof document>"u")return[];const{scrollMode:i,block:l,inline:d,boundary:c,skipOverflowHiddenElements:h}=e,u=typeof c=="function"?c:P=>P!==c;if(!Vd(t))throw new TypeError("Invalid target");const p=document.scrollingElement||document.documentElement,y=[];let f=t;for(;Vd(f)&&u(f);){if(f=ib(f),f===p){y.push(f);break}f!=null&&f===document.body&&ha(f)&&!ha(document.documentElement)||f!=null&&ha(f,h)&&y.push(f)}const g=(r=(n=window.visualViewport)==null?void 0:n.width)!=null?r:innerWidth,w=(a=(s=window.visualViewport)==null?void 0:s.height)!=null?a:innerHeight,{scrollX:x,scrollY:v}=window,{height:_,width:T,top:b,right:I,bottom:A,left:k}=t.getBoundingClientRect(),{top:U,right:D,bottom:X,left:L}=(P=>{const j=window.getComputedStyle(P);return{top:parseFloat(j.scrollMarginTop)||0,right:parseFloat(j.scrollMarginRight)||0,bottom:parseFloat(j.scrollMarginBottom)||0,left:parseFloat(j.scrollMarginLeft)||0}})(t);let O=l==="start"||l==="nearest"?b-U:l==="end"?A+X:b+_/2-U+X,G=d==="center"?k+T/2-L+D:d==="end"?I+D:k-L;const C=[];for(let P=0;P<y.length;P++){const j=y[P],{height:N,width:B,top:K,right:fe,bottom:ae,left:te}=j.getBoundingClientRect();if(i==="if-needed"&&b>=0&&k>=0&&A<=w&&I<=g&&(j===p&&!ha(j)||b>=K&&A<=ae&&k>=te&&I<=fe))return C;const Se=getComputedStyle(j),Ee=parseInt(Se.borderLeftWidth,10),Te=parseInt(Se.borderTopWidth,10),ke=parseInt(Se.borderRightWidth,10),ne=parseInt(Se.borderBottomWidth,10);let M=0,q=0;const R="offsetWidth"in j?j.offsetWidth-j.clientWidth-Ee-ke:0,J="offsetHeight"in j?j.offsetHeight-j.clientHeight-Te-ne:0,Ce="offsetWidth"in j?j.offsetWidth===0?0:B/j.offsetWidth:0,re="offsetHeight"in j?j.offsetHeight===0?0:N/j.offsetHeight:0;if(p===j)M=l==="start"?O:l==="end"?O-w:l==="nearest"?fa(v,v+w,w,Te,ne,v+O,v+O+_,_):O-w/2,q=d==="start"?G:d==="center"?G-g/2:d==="end"?G-g:fa(x,x+g,g,Ee,ke,x+G,x+G+T,T),M=Math.max(0,M+v),q=Math.max(0,q+x);else{M=l==="start"?O-K-Te:l==="end"?O-ae+ne+J:l==="nearest"?fa(K,ae,N,Te,ne+J,O,O+_,_):O-(K+N/2)+J/2,q=d==="start"?G-te-Ee:d==="center"?G-(te+B/2)+R/2:d==="end"?G-fe+ke+R:fa(te,fe,B,Ee,ke+R,G,G+T,T);const{scrollLeft:ze,scrollTop:V}=j;M=re===0?0:Math.max(0,Math.min(V+M/re,j.scrollHeight-N/re+J)),q=Ce===0?0:Math.max(0,Math.min(ze+q/Ce,j.scrollWidth-B/Ce+R)),O+=V-M,G+=ze-q}C.push({el:j,top:M,left:q})}return C},ob=t=>t===!1?{block:"end",inline:"nearest"}:(e=>e===Object(e)&&Object.keys(e).length!==0)(t)?t:{block:"start",inline:"nearest"};function lb(t,e){if(!t.isConnected||!(s=>{let a=s;for(;a&&a.parentNode;){if(a.parentNode===document)return!0;a=a.parentNode instanceof ShadowRoot?a.parentNode.host:a.parentNode}return!1})(t))return;const n=(s=>{const a=window.getComputedStyle(s);return{top:parseFloat(a.scrollMarginTop)||0,right:parseFloat(a.scrollMarginRight)||0,bottom:parseFloat(a.scrollMarginBottom)||0,left:parseFloat(a.scrollMarginLeft)||0}})(t);if((s=>typeof s=="object"&&typeof s.behavior=="function")(e))return e.behavior(qd(t,e));const r=typeof e=="boolean"||e==null?void 0:e.behavior;for(const{el:s,top:a,left:i}of qd(t,ob(e))){const l=a-n.top+n.bottom,d=i-n.left+n.right;s.scroll({top:l,left:d,behavior:r})}}var bm=globalThis.Node,cb=globalThis.Text,fc=t=>t&&t.ownerDocument&&t.ownerDocument.defaultView||null,db=t=>Xn(t)&&t.nodeType===8,an=t=>Xn(t)&&t.nodeType===1,Xn=t=>{var e=fc(t);return!!e&&t instanceof e.Node},ul=t=>{var e=t&&t.anchorNode&&fc(t.anchorNode);return!!e&&t instanceof e.Selection},_m=t=>Xn(t)&&t.nodeType===3,ub=t=>t.clipboardData&&t.clipboardData.getData("text/plain")!==""&&t.clipboardData.types.length===1,hb=t=>{var[e,n]=t;if(an(e)&&e.childNodes.length){var r=n===e.childNodes.length,s=r?n-1:n;for([e,s]=Tm(e,s,r?"backward":"forward"),r=s<n;an(e)&&e.childNodes.length;){var a=r?e.childNodes.length-1:0;e=mb(e,a,r?"backward":"forward")}n=r&&e.textContent!=null?e.textContent.length:0}return[e,n]},fb=t=>{for(var e=t&&t.parentNode;e;){if(e.toString()==="[object ShadowRoot]")return!0;e=e.parentNode}return!1},Tm=(t,e,n)=>{for(var{childNodes:r}=t,s=r[e],a=e,i=!1,l=!1;(db(s)||an(s)&&s.childNodes.length===0||an(s)&&s.getAttribute("contenteditable")==="false")&&!(i&&l);){if(a>=r.length){i=!0,a=e-1,n="backward";continue}if(a<0){l=!0,a=e+1,n="forward";continue}s=r[a],e=a,a+=n==="forward"?1:-1}return[s,e]},mb=(t,e,n)=>{var[r]=Tm(t,e,n);return r},Sm=t=>{var e="";if(_m(t)&&t.nodeValue)return t.nodeValue;if(an(t)){for(var n of Array.from(t.childNodes))e+=Sm(n);var r=getComputedStyle(t).getPropertyValue("display");(r==="block"||r==="list"||t.tagName==="BR")&&(e+=`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ai-chat-BlxYfB4O.css","./bootstrap-5wOMkP8H.css","./batch-image-generation-DuPmleAE.css","./ModelBenchmarkWorkbench-CC2lNbTT.css","./PromptHistoryTool-BH7hq916.css","./editor-engines-B8u8agiX.css","./KnowledgeBaseContent-CsR955E7.css","./MediaLibrarySidebar-CcSibzET.css","./VideoAnalyzer-DvF56ngj.css","./MusicAnalyzer-DHa6anV5.css","./ResizableDivider-ClzYJk-6.css","./character-Bo9jcTNu.css","./MVCreator-CDzLxh5R.css","./ComicCreator-DjAR34b-.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{Q as xe,T as ve,S as rt,U as et,V as Be,W as Y,X as Ps,Y as rn,Z as Je,_ as Es,$ as st,a0 as wt,a1 as As,a2 as cn,P as m,a3 as Hg,R as Ie,a4 as Xo,a5 as Gg,a6 as Zc,a7 as Xc,a8 as o,a9 as Wg,aa as St,ab as Le,ac as Vg,ad as wf,ae as xf,af as ql,ag as Yl,ah as Kg,ai as qg,aj as Yg,ak as Tt,al as Zg,am as Xg,an as Jg,ao as ee,ap as Qg,aq as ey,ar as ty,as as bf,at as Fe,au as ny,av as ry,aw as Jn,ax as sy,ay as Zl,az as Qa,aA as _f,aB as Xl,aC as ls,aD as He,aE as ln,aF as jr,aG as Jl,aH as ay,aI as Jc,aJ as iy,aK as oy,aL as ly,aM as cy,aN as dy,aO as uy,aP as hy,aQ as fy,aR as my,aS as Gt,aT as py,aU as on,aV as gy,aW as yy,aX as vy,aY as vs,aZ as wy,a_ as xy,a$ as by,b0 as _y,b1 as Ql,b2 as Tf,b3 as Sf,b4 as If,b5 as kf,b6 as Cf,b7 as Qc,b8 as Pf,b9 as Ty,ba as ed,bb as Ef,bc as Sy,bd as kt,be as Iy,bf as ns,bg as Jo,bh as Qo,bi as td,bj as ht,bk as at,bl as dt,bm as ei,bn as ky,bo as Gn,bp as Ln,bq as It,br as Cy,bs as ta,bt as rs,bu as Py,bv as Ey,bw as Ay,bx as jy,by as Oy,bz as My,bA as Dy,bB as ti,bC as ni,bD as ri,bE as Af,bF as jf,bG as Of,bH as Mf,bI as Df,bJ as Ny,bK as ec,bL as Nf,bM as tc,bN as si,bO as Ry,bP as _e,bQ as nc,bR as rc,bS as sc,bT as Rf,bU as Ly,bV as Fy,bW as By,bX as zy,bY as $y,bZ as Uy,b_ as nd,b$ as pn,c0 as Lr,c1 as pr,c2 as Hy,c3 as Gy,c4 as Wy,c5 as Kr,c6 as nn,c7 as ct,c8 as Xt,c9 as mt,ca as na,cb as Vy,cc as Ky,cd as qy,ce as Yy,cf as Zy,cg as Xy,ch as Jy,ci as Qy,cj as ev,ck as tv,cl as nv,cm as ss,cn as qr,co as Me,cp as Lf,cq as Ff,cr as Bf,cs as rv,ct as Fr,cu as Ma,cv as ac,cw as zf,cx as sv,cy as rd,cz as av,cA as iv,cB as ws,cC as $f,cD as ov,cE as lv,cF as sd,cG as Uf,cH as cv,cI as Hf,cJ as ic,cK as dv,cL as uv,cM as kn,cN as hn,cO as Br,cP as Gf,cQ as ad,cR as hv,cS as id,cT as fv,cU as er,cV as mv,cW as pv,cX as gv,cY as el,cZ as yv,c_ as vv,c$ as $t,d0 as oc,d1 as Zn,d2 as wv,d3 as xv,d4 as bv,d5 as _v,d6 as Tv,d7 as Yt,d8 as js,d9 as Bi,da as zi,db as cs,dc as Sv,dd as Mn,de as Iv,df as $i,dg as kv,dh as Ui,di as Hi,dj as od,dk as Cv,dl as Pv,dm as Ev,dn as tl,dp as nl,dq as Av,dr as Wf,ds as ld,dt as jv,du as Ov,dv as Vf,dw as xs,dx as qt,dy as cd,dz as dd,dA as zr,dB as Da,dC as Mv,dD as Dv,dE as Nv,dF as ra,dG as Rv,dH as Lv,dI as Fv,dJ as Bv,dK as bs,dL as zv,dM as $v,dN as Uv,dO as Or,dP as Pn,dQ as fn,dR as vn,dS as Hv,dT as Gv,dU as Wv,dV as Kf,dW as Vv,dX as Kv,dY as qv,dZ as Yv,d_ as Na,d$ as Zv,e0 as Xv,e1 as Jv,e2 as Qv,e3 as Nt,e4 as rl,e5 as ai,e6 as Kn,e7 as ud,e8 as Dn,e9 as ew,ea as tw,eb as qf,ec as nw,ed as rw,ee as $r,ef as sw,eg as Ra,eh as aw,ei as iw,ej as ow,ek as lw,el as sa,em as cw,en as dw,eo as hd,ep as aa,eq as Yf,er as uw,es as hw,et as fd,eu as fw,ev as ii,ew as Gi,ex as md,ey as mw,ez as Wi,eA as Vi,eB as Zf,eC as pw,eD as sl,eE as Ki,eF as yr,eG as ds,eH as gw,eI as yw,eJ as _s,eK as al,eL as vw,eM as Pr,eN as sn,eO as ww,eP as xw,eQ as pd,eR as bw,eS as _w,eT as Tw,eU as Os,eV as il,eW as gd,eX as Sw,eY as _n,eZ as Iw,e_ as kw,e$ as Cw,f0 as ol,f1 as En,f2 as Pw,f3 as Ew,f4 as Aw,f5 as Xf,f6 as jw,f7 as Ow,f8 as yd,f9 as Mw,fa as Dw,fb as Jf,fc as Qf,fd as Nw,fe as Rw,ff as Lw,fg as Fw,fh as Bw,fi as em,fj as tm,fk as ll,fl as nm,fm as zw,fn as rm,fo as $w,fp as cl,fq as lc,fr as Uw,fs as Hw,ft as vd,fu as Gw,fv as Ww,fw as sm,fx as am,fy as im,fz as om,fA as Vw,fB as wd,fC as Kw,fD as qw,fE as Yw,fF as Ms,fG as lm,fH as Tn,fI as Sn,fJ as Ti,fK as Ds,fL as Zw,fM as Xw,fN as Jw,fO as Qw,fP as cm,fQ as dm,fR as um,fS as hm,fT as ex,fU as fm,fV as tx,fW as xd,fX as nx,fY as rx,fZ as sx,f_ as ax,f$ as ix,g0 as qi,g1 as ox,g2 as Yi,g3 as lx,g4 as cx,g5 as bd,g6 as dx,g7 as ux,g8 as da,g9 as _d,ga as hx,gb as cc,gc as fx,gd as mx,ge as Td,gf as oi,gg as us,gh as mm,gi as px,gj as gx,gk as yx,gl as vx,gm as wx,gn as Sd,go as Id,gp as xx,gq as bx,gr as _x,gs as kd,gt as vr,gu as Cd,gv as Pd,gw as Tx,gx as Sx,gy as Ix,gz as kx,gA as Cx,gB as Px,gC as Ex}from"./ai-chat-BnWVpTEI.js";import{_ as Xe,g as dc,a as ua}from"./startup-runtime-BrfuwjQS.js";let La=null;async function Ax(){if(xe.getAllTasks().some(s=>s.status===ve.PENDING||s.status===ve.PROCESSING))return!0;const{workflowSubmissionService:n}=await Xe(async()=>{const{workflowSubmissionService:s}=await import("./workflow-submission-service-BqiL_5Cj.js").then(a=>a.a);return{workflowSubmissionService:s}},__vite__mapDeps([0]),import.meta.url);return La=n,n.getRunningWorkflows().length>0}function jx(){return xe.getAllTasks().some(n=>n.status===ve.PENDING||n.status===ve.PROCESSING)?!0:((La==null?void 0:La.getRunningWorkflows().length)||0)>0}async function Yr(){return await Ax()&&!window.confirm("当前有正在进行的 AI 生成任务,刷新页面会中断这些任务。确定要刷新吗?")?!1:(window.location.reload(),!0)}const Fa=7,Ox=["hand","selection","freehand","shape","text","image","media-library","ai-image","ai-video"],dl=["hand","selection","freehand","shape","text","image","media-library","ai-image","ai-video","lasso","mind","arrow","theme","mermaid-to-drawnix","markdown-to-drawnix","undo","redo"];function Er(){return{buttons:dl.map((e,n)=>({id:e,visible:Ox.includes(e),order:n})),version:Fa,updatedAt:Date.now()}}function uc(t){return t.buttons.filter(e=>e.visible).sort((e,n)=>e.order-n.order)}function pm(t){return t.buttons.filter(e=>!e.visible).sort((e,n)=>e.order-n.order)}function Mx(t,e,n){const r=t.buttons.map(s=>s.id===e?{...s,visible:n}:s);return{...t,buttons:r,updatedAt:Date.now()}}function Dx(t,e,n,r){const s=uc(t),a=pm(t),i=r?s:a,[l]=i.splice(e,1);i.splice(n,0,l);const d=t.buttons.map(c=>{const h=s.findIndex(p=>p.id===c.id),u=a.findIndex(p=>p.id===c.id);return h!==-1?{...c,order:h}:u!==-1?{...c,order:s.length+u}:c});return{...t,buttons:d,updatedAt:Date.now()}}function Nx(t,e,n){const r=uc(t),s=n??r.length;let a=t.buttons.map(c=>c.id===e?{...c,visible:!0}:c);const i=a.filter(c=>c.visible&&c.id!==e).sort((c,h)=>c.order-h.order),l=a.find(c=>c.id===e);i.splice(s,0,l);const d=a.filter(c=>!c.visible).sort((c,h)=>c.order-h.order);return a=a.map(c=>{const h=i.findIndex(p=>p.id===c.id),u=d.findIndex(p=>p.id===c.id);return h!==-1?{...c,order:h}:u!==-1?{...c,order:i.length+u}:c}),{...t,buttons:a,updatedAt:Date.now()}}function Rx(t,e){let n=t.buttons.map(a=>a.id===e?{...a,visible:!1}:a);const r=n.filter(a=>a.visible).sort((a,i)=>a.order-i.order),s=n.filter(a=>!a.visible).sort((a,i)=>a.order-i.order);return n=n.map(a=>{const i=r.findIndex(d=>d.id===a.id),l=s.findIndex(d=>d.id===a.id);return i!==-1?{...a,order:i}:l!==-1?{...a,order:r.length+l}:a}),{...t,buttons:n,updatedAt:Date.now()}}const Zi=et.TOOLBAR_CONFIG,Ed=["hand","selection","text","media-library","ai-image","ai-video","mind","freehand","arrow","shape","image","theme","mermaid-to-drawnix","markdown-to-drawnix","undo","redo","zoom"],Lx=["hand","selection","text","media-library","ai-image","ai-video"];class Fx{constructor(){this.config=null,this.initialized=!1,this.initPromise=null}async initializeAsync(){return this.initialized&&this.config?this.config:this.initPromise?this.initPromise:(this.initPromise=this.doInitialize(),this.initPromise)}async doInitialize(){try{const e=await rt.get(Zi);e?this.config=this.migrateConfig(e):(this.config=Er(),await this.saveToStorageAsync(this.config))}catch(e){console.warn("[ToolbarConfigService] Failed to load from IndexedDB:",e),this.config=Er()}return this.initialized=!0,this.config}initialize(){return this.initialized&&this.config?this.config:(this.config||(this.config=Er(),this.initializeAsync().then(e=>{this.config&&e&&(this.config=e)})),this.initialized=!0,this.config)}getConfig(){return this.config?this.config:this.initialize()}setButtonVisibility(e,n){return this.config||this.initialize(),this.config=Mx(this.config,e,n),this.saveToStorage(this.config),this.config}reorderButton(e,n,r){return this.config||this.initialize(),this.config=Dx(this.config,e,n,r),this.saveToStorage(this.config),this.config}showButton(e,n){return this.config||this.initialize(),this.config=Nx(this.config,e,n),this.saveToStorage(this.config),this.config}hideButton(e){return this.config||this.initialize(),this.config=Rx(this.config,e),this.saveToStorage(this.config),this.config}updateConfig(e){return this.config||this.initialize(),this.config={...this.config,...e,updatedAt:Date.now()},this.saveToStorage(this.config),this.config}resetToDefault(){return this.config=Er(),this.saveToStorage(this.config),this.config}saveToStorage(e){rt.set(Zi,e).catch(n=>{console.error("[ToolbarConfigService] Failed to save config:",n)})}async saveToStorageAsync(e){try{await rt.set(Zi,e)}catch(n){console.error("[ToolbarConfigService] Failed to save config:",n)}}migrateConfig(e){const r=(e.version??1)<Fa&&this.matchesLegacyDefaultLayout(e),s=new Set(e.buttons.map(d=>d.id)),a=[];dl.forEach(d=>{s.has(d)||a.push({id:d,visible:!1,order:e.buttons.length+a.length})}),a.length>0&&(e={...e,buttons:[...e.buttons,...a],updatedAt:Date.now()});const i=new Set(dl),l=e.buttons.filter(d=>i.has(d.id));return l.length!==e.buttons.length&&(e={...e,buttons:l,updatedAt:Date.now()}),r&&(e=Er()),e.version!==Fa&&(e={...e,version:Fa}),e}matchesLegacyDefaultLayout(e){return e.buttons.length!==Ed.length?!1:Ed.every((n,r)=>{const s=e.buttons.find(i=>i.id===n);if(!s)return!1;const a=Lx.includes(n);return s.order===r&&s.visible===a})}}const wr=new Fx,Bx=.75,zx=.9,$x=6e4;class Ux{constructor(){this.checkTimer=null,this.cleanupHandlers=[],this.lastCleanupTime=0,this.cleanupCooldown=6e4}getMemoryStats(){const e=performance;if(!e.memory)return null;const{usedJSHeapSize:n,totalJSHeapSize:r,jsHeapSizeLimit:s}=e.memory,a=n/s*100;return{usedJSHeapSize:n,totalJSHeapSize:r,jsHeapSizeLimit:s,usagePercent:a,isUnderPressure:a>Bx*100,formatted:{used:this.formatBytes(n),total:this.formatBytes(r),limit:this.formatBytes(s)}}}formatBytes(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}registerCleanupHandler(e){this.cleanupHandlers.push(e),this.cleanupHandlers.sort((n,r)=>n.priority-r.priority)}unregisterCleanupHandler(e){this.cleanupHandlers=this.cleanupHandlers.filter(n=>n.name!==e)}async triggerCleanup(e=!1){const n=Date.now();if(!e&&n-this.lastCleanupTime<this.cleanupCooldown)return;this.lastCleanupTime=n;const r=this.getMemoryStats();for(const a of this.cleanupHandlers)try{await a.cleanup()}catch(i){console.error(`[MemoryMonitor] Cleanup failed: ${a.name}`,i)}typeof globalThis.gc=="function"&&globalThis.gc();const s=this.getMemoryStats();r&&s&&r.usedJSHeapSize-s.usedJSHeapSize}checkMemory(){const e=this.getMemoryStats();if(e){if(e.usagePercent>zx*100){console.warn(`[MemoryMonitor] Critical memory pressure: ${e.usagePercent.toFixed(1)}%`),this.triggerCleanup(!0);return}e.isUnderPressure&&(console.warn(`[MemoryMonitor] Memory pressure: ${e.usagePercent.toFixed(1)}%`),this.triggerCleanup())}}start(){this.checkTimer||!this.getMemoryStats()||(this.checkTimer=setInterval(()=>this.checkMemory(),$x),this.checkMemory())}stop(){this.checkTimer&&(clearInterval(this.checkTimer),this.checkTimer=null)}logMemoryStatus(){this.getMemoryStats()}}const gm=new Ux;gm.registerCleanupHandler({name:"idle-gc-hint",priority:10,cleanup:async()=>new Promise(t=>{"requestIdleCallback"in window?window.requestIdleCallback(()=>{t()},{timeout:1e3}):setTimeout(t,0)})});var Xi,Ad;function Hx(){if(Ad)return Xi;Ad=1,Xi=s;var t="֑-߿יִ-﷽ﹰ-ﻼ",e="A-Za-zÀ-ÖØ-öø-ʸ̀-ࠀ-Ⰰ-︀--",n=new RegExp("^[^"+e+"]*["+t+"]"),r=new RegExp("^[^"+t+"]*["+e+"]");function s(a){return a=String(a||""),n.test(a)?"rtl":r.test(a)?"ltr":"neutral"}return Xi}var Gx=Hx();const ym=dc(Gx);var Ji,jd;function hc(){if(jd)return Ji;jd=1;function t(e){var n=typeof e;return e!=null&&(n=="object"||n=="function")}return Ji=t,Ji}var Qi,Od;function Wx(){if(Od)return Qi;Od=1;var t=typeof ua=="object"&&ua&&ua.Object===Object&&ua;return Qi=t,Qi}var eo,Md;function vm(){if(Md)return eo;Md=1;var t=Wx(),e=typeof self=="object"&&self&&self.Object===Object&&self,n=t||e||Function("return this")();return eo=n,eo}var to,Dd;function Vx(){if(Dd)return to;Dd=1;var t=vm(),e=function(){return t.Date.now()};return to=e,to}var no,Nd;function Kx(){if(Nd)return no;Nd=1;var t=/\s/;function e(n){for(var r=n.length;r--&&t.test(n.charAt(r)););return r}return no=e,no}var ro,Rd;function qx(){if(Rd)return ro;Rd=1;var t=Kx(),e=/^\s+/;function n(r){return r&&r.slice(0,t(r)+1).replace(e,"")}return ro=n,ro}var so,Ld;function wm(){if(Ld)return so;Ld=1;var t=vm(),e=t.Symbol;return so=e,so}var ao,Fd;function Yx(){if(Fd)return ao;Fd=1;var t=wm(),e=Object.prototype,n=e.hasOwnProperty,r=e.toString,s=t?t.toStringTag:void 0;function a(i){var l=n.call(i,s),d=i[s];try{i[s]=void 0;var c=!0}catch{}var h=r.call(i);return c&&(l?i[s]=d:delete i[s]),h}return ao=a,ao}var io,Bd;function Zx(){if(Bd)return io;Bd=1;var t=Object.prototype,e=t.toString;function n(r){return e.call(r)}return io=n,io}var oo,zd;function Xx(){if(zd)return oo;zd=1;var t=wm(),e=Yx(),n=Zx(),r="[object Null]",s="[object Undefined]",a=t?t.toStringTag:void 0;function i(l){return l==null?l===void 0?s:r:a&&a in Object(l)?e(l):n(l)}return oo=i,oo}var lo,$d;function Jx(){if($d)return lo;$d=1;function t(e){return e!=null&&typeof e=="object"}return lo=t,lo}var co,Ud;function Qx(){if(Ud)return co;Ud=1;var t=Xx(),e=Jx(),n="[object Symbol]";function r(s){return typeof s=="symbol"||e(s)&&t(s)==n}return co=r,co}var uo,Hd;function eb(){if(Hd)return uo;Hd=1;var t=qx(),e=hc(),n=Qx(),r=NaN,s=/^[-+]0x[0-9a-f]+$/i,a=/^0b[01]+$/i,i=/^0o[0-7]+$/i,l=parseInt;function d(c){if(typeof c=="number")return c;if(n(c))return r;if(e(c)){var h=typeof c.valueOf=="function"?c.valueOf():c;c=e(h)?h+"":h}if(typeof c!="string")return c===0?c:+c;c=t(c);var u=a.test(c);return u||i.test(c)?l(c.slice(2),u?2:8):s.test(c)?r:+c}return uo=d,uo}var ho,Gd;function xm(){if(Gd)return ho;Gd=1;var t=hc(),e=Vx(),n=eb(),r="Expected a function",s=Math.max,a=Math.min;function i(l,d,c){var h,u,p,y,f,g,w=0,x=!1,v=!1,_=!0;if(typeof l!="function")throw new TypeError(r);d=n(d)||0,t(c)&&(x=!!c.leading,v="maxWait"in c,p=v?s(n(c.maxWait)||0,d):p,_="trailing"in c?!!c.trailing:_);function T(O){var G=h,C=u;return h=u=void 0,w=O,y=l.apply(C,G),y}function b(O){return w=O,f=setTimeout(k,d),x?T(O):y}function I(O){var G=O-g,C=O-w,P=d-G;return v?a(P,p-C):P}function A(O){var G=O-g,C=O-w;return g===void 0||G>=d||G<0||v&&C>=p}function k(){var O=e();if(A(O))return U(O);f=setTimeout(k,I(O))}function U(O){return f=void 0,_&&h?T(O):(h=u=void 0,y)}function D(){f!==void 0&&clearTimeout(f),w=0,h=g=u=f=void 0}function X(){return f===void 0?y:U(e())}function L(){var O=e(),G=A(O);if(h=arguments,u=this,g=O,G){if(f===void 0)return b(g);if(v)return clearTimeout(f),f=setTimeout(k,d),T(g)}return f===void 0&&(f=setTimeout(k,d)),y}return L.cancel=D,L.flush=X,L}return ho=i,ho}var tb=xm();const nb=dc(tb);var fo,Wd;function rb(){if(Wd)return fo;Wd=1;var t=xm(),e=hc(),n="Expected a function";function r(s,a,i){var l=!0,d=!0;if(typeof s!="function")throw new TypeError(n);return e(i)&&(l="leading"in i?!!i.leading:l,d="trailing"in i?!!i.trailing:d),t(s,a,{leading:l,maxWait:a,trailing:d})}return fo=r,fo}var sb=rb();const ab=dc(sb),Vd=t=>typeof t=="object"&&t!=null&&t.nodeType===1,Kd=(t,e)=>(!e||t!=="hidden")&&t!=="visible"&&t!=="clip",ha=(t,e)=>{if(t.clientHeight<t.scrollHeight||t.clientWidth<t.scrollWidth){const n=getComputedStyle(t,null);return Kd(n.overflowY,e)||Kd(n.overflowX,e)||(r=>{const s=(a=>{if(!a.ownerDocument||!a.ownerDocument.defaultView)return null;try{return a.ownerDocument.defaultView.frameElement}catch{return null}})(r);return!!s&&(s.clientHeight<r.scrollHeight||s.clientWidth<r.scrollWidth)})(t)}return!1},fa=(t,e,n,r,s,a,i,l)=>a<t&&i>e||a>t&&i<e?0:a<=t&&l<=n||i>=e&&l>=n?a-t-r:i>e&&l<n||a<t&&l>n?i-e+s:0,ib=t=>{const e=t.parentElement;return e??(t.getRootNode().host||null)},qd=(t,e)=>{var n,r,s,a;if(typeof document>"u")return[];const{scrollMode:i,block:l,inline:d,boundary:c,skipOverflowHiddenElements:h}=e,u=typeof c=="function"?c:P=>P!==c;if(!Vd(t))throw new TypeError("Invalid target");const p=document.scrollingElement||document.documentElement,y=[];let f=t;for(;Vd(f)&&u(f);){if(f=ib(f),f===p){y.push(f);break}f!=null&&f===document.body&&ha(f)&&!ha(document.documentElement)||f!=null&&ha(f,h)&&y.push(f)}const g=(r=(n=window.visualViewport)==null?void 0:n.width)!=null?r:innerWidth,w=(a=(s=window.visualViewport)==null?void 0:s.height)!=null?a:innerHeight,{scrollX:x,scrollY:v}=window,{height:_,width:T,top:b,right:I,bottom:A,left:k}=t.getBoundingClientRect(),{top:U,right:D,bottom:X,left:L}=(P=>{const j=window.getComputedStyle(P);return{top:parseFloat(j.scrollMarginTop)||0,right:parseFloat(j.scrollMarginRight)||0,bottom:parseFloat(j.scrollMarginBottom)||0,left:parseFloat(j.scrollMarginLeft)||0}})(t);let O=l==="start"||l==="nearest"?b-U:l==="end"?A+X:b+_/2-U+X,G=d==="center"?k+T/2-L+D:d==="end"?I+D:k-L;const C=[];for(let P=0;P<y.length;P++){const j=y[P],{height:N,width:B,top:K,right:fe,bottom:ae,left:te}=j.getBoundingClientRect();if(i==="if-needed"&&b>=0&&k>=0&&A<=w&&I<=g&&(j===p&&!ha(j)||b>=K&&A<=ae&&k>=te&&I<=fe))return C;const Se=getComputedStyle(j),Ee=parseInt(Se.borderLeftWidth,10),Te=parseInt(Se.borderTopWidth,10),ke=parseInt(Se.borderRightWidth,10),ne=parseInt(Se.borderBottomWidth,10);let M=0,q=0;const R="offsetWidth"in j?j.offsetWidth-j.clientWidth-Ee-ke:0,J="offsetHeight"in j?j.offsetHeight-j.clientHeight-Te-ne:0,Ce="offsetWidth"in j?j.offsetWidth===0?0:B/j.offsetWidth:0,re="offsetHeight"in j?j.offsetHeight===0?0:N/j.offsetHeight:0;if(p===j)M=l==="start"?O:l==="end"?O-w:l==="nearest"?fa(v,v+w,w,Te,ne,v+O,v+O+_,_):O-w/2,q=d==="start"?G:d==="center"?G-g/2:d==="end"?G-g:fa(x,x+g,g,Ee,ke,x+G,x+G+T,T),M=Math.max(0,M+v),q=Math.max(0,q+x);else{M=l==="start"?O-K-Te:l==="end"?O-ae+ne+J:l==="nearest"?fa(K,ae,N,Te,ne+J,O,O+_,_):O-(K+N/2)+J/2,q=d==="start"?G-te-Ee:d==="center"?G-(te+B/2)+R/2:d==="end"?G-fe+ke+R:fa(te,fe,B,Ee,ke+R,G,G+T,T);const{scrollLeft:ze,scrollTop:V}=j;M=re===0?0:Math.max(0,Math.min(V+M/re,j.scrollHeight-N/re+J)),q=Ce===0?0:Math.max(0,Math.min(ze+q/Ce,j.scrollWidth-B/Ce+R)),O+=V-M,G+=ze-q}C.push({el:j,top:M,left:q})}return C},ob=t=>t===!1?{block:"end",inline:"nearest"}:(e=>e===Object(e)&&Object.keys(e).length!==0)(t)?t:{block:"start",inline:"nearest"};function lb(t,e){if(!t.isConnected||!(s=>{let a=s;for(;a&&a.parentNode;){if(a.parentNode===document)return!0;a=a.parentNode instanceof ShadowRoot?a.parentNode.host:a.parentNode}return!1})(t))return;const n=(s=>{const a=window.getComputedStyle(s);return{top:parseFloat(a.scrollMarginTop)||0,right:parseFloat(a.scrollMarginRight)||0,bottom:parseFloat(a.scrollMarginBottom)||0,left:parseFloat(a.scrollMarginLeft)||0}})(t);if((s=>typeof s=="object"&&typeof s.behavior=="function")(e))return e.behavior(qd(t,e));const r=typeof e=="boolean"||e==null?void 0:e.behavior;for(const{el:s,top:a,left:i}of qd(t,ob(e))){const l=a-n.top+n.bottom,d=i-n.left+n.right;s.scroll({top:l,left:d,behavior:r})}}var bm=globalThis.Node,cb=globalThis.Text,fc=t=>t&&t.ownerDocument&&t.ownerDocument.defaultView||null,db=t=>Xn(t)&&t.nodeType===8,an=t=>Xn(t)&&t.nodeType===1,Xn=t=>{var e=fc(t);return!!e&&t instanceof e.Node},ul=t=>{var e=t&&t.anchorNode&&fc(t.anchorNode);return!!e&&t instanceof e.Selection},_m=t=>Xn(t)&&t.nodeType===3,ub=t=>t.clipboardData&&t.clipboardData.getData("text/plain")!==""&&t.clipboardData.types.length===1,hb=t=>{var[e,n]=t;if(an(e)&&e.childNodes.length){var r=n===e.childNodes.length,s=r?n-1:n;for([e,s]=Tm(e,s,r?"backward":"forward"),r=s<n;an(e)&&e.childNodes.length;){var a=r?e.childNodes.length-1:0;e=mb(e,a,r?"backward":"forward")}n=r&&e.textContent!=null?e.textContent.length:0}return[e,n]},fb=t=>{for(var e=t&&t.parentNode;e;){if(e.toString()==="[object ShadowRoot]")return!0;e=e.parentNode}return!1},Tm=(t,e,n)=>{for(var{childNodes:r}=t,s=r[e],a=e,i=!1,l=!1;(db(s)||an(s)&&s.childNodes.length===0||an(s)&&s.getAttribute("contenteditable")==="false")&&!(i&&l);){if(a>=r.length){i=!0,a=e-1,n="backward";continue}if(a<0){l=!0,a=e+1,n="forward";continue}s=r[a],e=a,a+=n==="forward"?1:-1}return[s,e]},mb=(t,e,n)=>{var[r]=Tm(t,e,n);return r},Sm=t=>{var e="";if(_m(t)&&t.nodeValue)return t.nodeValue;if(an(t)){for(var n of Array.from(t.childNodes))e+=Sm(n);var r=getComputedStyle(t).getPropertyValue("display");(r==="block"||r==="list"||t.tagName==="BR")&&(e+=`
|
|
3
3
|
`)}return e},pb=/data-slate-fragment="(.+?)"/m,gb=t=>{var e=t.getData("text/html"),[,n]=e.match(pb)||[];return n},Ns=t=>t.getSelection!=null?t.getSelection():document.getSelection(),mc=(t,e,n)=>{var{target:r}=e;if(an(r)&&r.matches('[contentEditable="false"]'))return!1;var{document:s}=qe.getWindow(t);if(s.contains(r))return qe.hasDOMNode(t,r,{editable:!0});var a=n.find(i=>{var{addedNodes:l,removedNodes:d}=i;for(var c of l)if(c===r||c.contains(r))return!0;for(var h of d)if(h===r||h.contains(r))return!0});return!a||a===e?!1:mc(t,a,n)},yb=()=>{for(var t=document.activeElement;(e=t)!==null&&e!==void 0&&e.shadowRoot&&(n=t.shadowRoot)!==null&&n!==void 0&&n.activeElement;){var e,n,r;t=(r=t)===null||r===void 0||(r=r.shadowRoot)===null||r===void 0?void 0:r.activeElement}return t},Yd=(t,e)=>!!(t.compareDocumentPosition(e)&bm.DOCUMENT_POSITION_PRECEDING),vb=(t,e)=>!!(t.compareDocumentPosition(e)&bm.DOCUMENT_POSITION_FOLLOWING),mo,po,wb=typeof navigator<"u"&&typeof window<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,Zd=typeof navigator<"u"&&/Mac OS X/.test(navigator.userAgent),zt=typeof navigator<"u"&&/Android/.test(navigator.userAgent),Mr=typeof navigator<"u"&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent),ar=typeof navigator<"u"&&/AppleWebKit(?!.*Chrome)/i.test(navigator.userAgent),xb=typeof navigator<"u"&&/Edge?\/(?:[0-6][0-9]|[0-7][0-8])(?:\.)/i.test(navigator.userAgent),Im=typeof navigator<"u"&&/Chrome/i.test(navigator.userAgent),bb=typeof navigator<"u"&&/Chrome?\/(?:[0-7][0-5]|[0-6][0-9])(?:\.)/i.test(navigator.userAgent),_b=zt&&typeof navigator<"u"&&/Chrome?\/(?:[0-5]?\d)(?:\.)/i.test(navigator.userAgent),Tb=typeof navigator<"u"&&/^(?!.*Seamonkey)(?=.*Firefox\/(?:[0-7][0-9]|[0-8][0-6])(?:\.)).*/i.test(navigator.userAgent),Sb=typeof navigator<"u"&&/.*UCBrowser/.test(navigator.userAgent),Ib=typeof navigator<"u"&&/.*Wechat/.test(navigator.userAgent)&&!/.*MacWechat/.test(navigator.userAgent),Ba=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&/Version\/(\d+)/.test(navigator.userAgent)&&((mo=navigator.userAgent.match(/Version\/(\d+)/))!==null&&mo!==void 0&&mo[1]&&parseInt((po=navigator.userAgent.match(/Version\/(\d+)/))===null||po===void 0?void 0:po[1],10)<17);var Bn=(!bb||!_b)&&!xb&&typeof globalThis<"u"&&globalThis.InputEvent&&typeof globalThis.InputEvent.prototype.getTargetRanges=="function";function Ws(t){"@babel/helpers - typeof";return Ws=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ws(t)}function kb(t,e){if(Ws(t)!=="object"||t===null)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(Ws(r)!=="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Cb(t){var e=kb(t,"string");return Ws(e)==="symbol"?e:String(e)}function pc(t,e,n){return e=Cb(e),e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var Pb=0;class km{constructor(){pc(this,"id",void 0),this.id="".concat(Pb++)}}var Ur=new WeakMap,Dr=new WeakMap,Rs=new WeakMap,Cm=new WeakMap,za=new WeakMap,hl=new WeakMap,Vs=new WeakMap,dr=new WeakMap,li=new WeakMap,Si=new WeakMap,fl=new WeakMap,qn=new WeakMap,or=new WeakMap,Ls=new WeakMap,ml=new WeakMap,gc=new WeakMap,gn=new WeakMap,On=new WeakMap,Ht=new WeakMap,$n=new WeakMap,Un=new WeakMap,Pm=new WeakMap,Zr=Symbol("placeholder"),Em=Symbol("mark-placeholder"),qe={androidPendingDiffs:t=>Ht.get(t),androidScheduleFlush:t=>{var e;(e=gc.get(t))===null||e===void 0||e()},blur:t=>{var e=qe.toDOMNode(t,t),n=qe.findDocumentOrShadowRoot(t);qn.set(t,!1),n.activeElement===e&&e.blur()},deselect:t=>{var{selection:e}=t,n=qe.findDocumentOrShadowRoot(t),r=Ns(n);r&&r.rangeCount>0&&r.removeAllRanges(),e&&Je.deselect(t)},findDocumentOrShadowRoot:t=>{var e=qe.toDOMNode(t,t),n=e.getRootNode();return n instanceof Document||n instanceof ShadowRoot?n:e.ownerDocument},findEventRange:(t,e)=>{"nativeEvent"in e&&(e=e.nativeEvent);var{clientX:n,clientY:r,target:s}=e;if(n==null||r==null)throw new Error("Cannot resolve a Slate range from a DOM event: ".concat(e));var a=qe.toSlateNode(t,e.target),i=qe.findPath(t,a);if(rn.isElement(a)&&Y.isVoid(t,a)){var l=s.getBoundingClientRect(),d=t.isInline(a)?n-l.left<l.left+l.width-n:r-l.top<l.top+l.height-r,c=Y.point(t,i,{edge:d?"start":"end"}),h=d?Y.before(t,c):Y.after(t,c);if(h){var u=Y.range(t,h);return u}}var p,{document:y}=qe.getWindow(t);if(y.caretRangeFromPoint)p=y.caretRangeFromPoint(n,r);else{var f=y.caretPositionFromPoint(n,r);f&&(p=y.createRange(),p.setStart(f.offsetNode,f.offset),p.setEnd(f.offsetNode,f.offset))}if(!p)throw new Error("Cannot resolve a Slate range from a DOM event: ".concat(e));var g=qe.toSlateRange(t,p,{exactMatch:!1,suppressThrow:!1});return g},findKey:(t,e)=>{var n=li.get(e);return n||(n=new km,li.set(e,n)),n},findPath:(t,e)=>{for(var n=[],r=e;;){var s=Rs.get(r);if(s==null){if(Y.isEditor(r))return n;break}var a=Dr.get(r);if(a==null)break;n.unshift(a),r=s}throw new Error("Unable to find the path for Slate node: ".concat(Ps.stringify(e)))},focus:function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{retries:5};if(!qn.get(e)){if(n.retries<=0)throw new Error("Could not set focus, editor seems stuck with pending operations");if(e.operations.length>0){setTimeout(()=>{qe.focus(e,{retries:n.retries-1})},10);return}var r=qe.toDOMNode(e,e),s=qe.findDocumentOrShadowRoot(e);if(s.activeElement!==r){if(e.selection&&s instanceof Document){var a=Ns(s),i=qe.toDOMRange(e,e.selection);a==null||a.removeAllRanges(),a==null||a.addRange(i)}e.selection||Je.select(e,Y.start(e,[])),qn.set(e,!0),r.focus({preventScroll:!0})}}},getWindow:t=>{var e=Cm.get(t);if(!e)throw new Error("Unable to find a host window element for this editor");return e},hasDOMNode:function(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},{editable:s=!1}=r,a=qe.toDOMNode(e,e),i;try{i=an(n)?n:n.parentElement}catch(l){if(l instanceof Error&&!l.message.includes('Permission denied to access property "nodeType"'))throw l}return i?i.closest("[data-slate-editor]")===a&&(!s||i.isContentEditable?!0:typeof i.isContentEditable=="boolean"&&i.closest('[contenteditable="false"]')===a||!!i.getAttribute("data-slate-zero-width")):!1},hasEditableTarget:(t,e)=>Xn(e)&&qe.hasDOMNode(t,e,{editable:!0}),hasRange:(t,e)=>{var{anchor:n,focus:r}=e;return Y.hasPath(t,n.path)&&Y.hasPath(t,r.path)},hasSelectableTarget:(t,e)=>qe.hasEditableTarget(t,e)||qe.isTargetInsideNonReadonlyVoid(t,e),hasTarget:(t,e)=>Xn(e)&&qe.hasDOMNode(t,e),insertData:(t,e)=>{t.insertData(e)},insertFragmentData:(t,e)=>t.insertFragmentData(e),insertTextData:(t,e)=>t.insertTextData(e),isComposing:t=>!!or.get(t),isFocused:t=>!!qn.get(t),isReadOnly:t=>!!fl.get(t),isTargetInsideNonReadonlyVoid:(t,e)=>{if(fl.get(t))return!1;var n=qe.hasTarget(t,e)&&qe.toSlateNode(t,e);return rn.isElement(n)&&Y.isVoid(t,n)},setFragmentData:(t,e,n)=>t.setFragmentData(e,n),toDOMNode:(t,e)=>{var n=Si.get(t),r=Y.isEditor(e)?za.get(t):n==null?void 0:n.get(qe.findKey(t,e));if(!r)throw new Error("Cannot resolve a DOM node from Slate node: ".concat(Ps.stringify(e)));return r},toDOMPoint:(t,e)=>{var[n]=Y.node(t,e.path),r=qe.toDOMNode(t,n),s;Y.void(t,{at:e})&&(e={path:e.path,offset:0});for(var a="[data-slate-string], [data-slate-zero-width]",i=Array.from(r.querySelectorAll(a)),l=0,d=0;d<i.length;d++){var c=i[d],h=c.childNodes[0];if(!(h==null||h.textContent==null)){var{length:u}=h.textContent,p=c.getAttribute("data-slate-length"),y=p==null?u:parseInt(p,10),f=l+y,g=i[d+1];if(e.offset===f&&g!==null&&g!==void 0&&g.hasAttribute("data-slate-mark-placeholder")){var w,x=g.childNodes[0];s=[x instanceof cb?x:g,(w=g.textContent)!==null&&w!==void 0&&w.startsWith("\uFEFF")?1:0];break}if(e.offset<=f){var v=Math.min(u,Math.max(0,e.offset-l));s=[h,v];break}l=f}}if(!s)throw new Error("Cannot resolve a DOM point from Slate point: ".concat(Ps.stringify(e)));return s},toDOMRange:(t,e)=>{var{anchor:n,focus:r}=e,s=Be.isBackward(e),a=qe.toDOMPoint(t,n),i=Be.isCollapsed(e)?a:qe.toDOMPoint(t,r),l=qe.getWindow(t),d=l.document.createRange(),[c,h]=s?i:a,[u,p]=s?a:i,y=an(c)?c:c.parentElement,f=!!y.getAttribute("data-slate-zero-width"),g=an(u)?u:u.parentElement,w=!!g.getAttribute("data-slate-zero-width");return d.setStart(c,f?1:h),d.setEnd(u,w?1:p),d},toSlateNode:(t,e)=>{var n=an(e)?e:e.parentElement;n&&!n.hasAttribute("data-slate-node")&&(n=n.closest("[data-slate-node]"));var r=n?Vs.get(n):null;if(!r)throw new Error("Cannot resolve a Slate node from DOM node: ".concat(n));return r},toSlatePoint:(t,e,n)=>{var{exactMatch:r,suppressThrow:s,searchDirection:a="backward"}=n,[i,l]=r?e:hb(e),d=i.parentNode,c=null,h=0;if(d){var u,p,y=qe.toDOMNode(t,t),f=d.closest('[data-slate-void="true"]'),g=f&&y.contains(f)?f:null,w=d.closest('[contenteditable="false"]'),x=w&&y.contains(w)?w:null,v=d.closest("[data-slate-leaf]"),_=null;if(v){if(c=v.closest('[data-slate-node="text"]'),c){var T=qe.getWindow(t),b=T.document.createRange();b.setStart(c,0),b.setEnd(i,l);var I=b.cloneContents(),A=[...Array.prototype.slice.call(I.querySelectorAll("[data-slate-zero-width]")),...Array.prototype.slice.call(I.querySelectorAll("[contenteditable=false]"))];A.forEach(te=>{if(zt&&!r&&te.hasAttribute("data-slate-zero-width")&&te.textContent.length>0&&te.textContext!=="\uFEFF"){te.textContent.startsWith("\uFEFF")&&(te.textContent=te.textContent.slice(1));return}te.parentNode.removeChild(te)}),h=I.textContent.length,_=c}}else if(g){for(var k=g.querySelectorAll("[data-slate-leaf]"),U=0;U<k.length;U++){var D=k[U];if(qe.hasDOMNode(t,D)){v=D;break}}v?(c=v.closest('[data-slate-node="text"]'),_=v,h=_.textContent.length,_.querySelectorAll("[data-slate-zero-width]").forEach(te=>{h-=te.textContent.length})):h=1}else if(x){var X=te=>te?te.querySelectorAll("[data-slate-leaf]:not(:scope [data-slate-editor] [data-slate-leaf])"):[],L=x.closest('[data-slate-node="element"]');if(a==="forward"){var O,G=[...X(L),...X(L==null?void 0:L.nextElementSibling)];v=(O=G.find(te=>vb(x,te)))!==null&&O!==void 0?O:null}else{var C,P=[...X(L==null?void 0:L.previousElementSibling),...X(L)];v=(C=P.findLast(te=>Yd(x,te)))!==null&&C!==void 0?C:null}v&&(c=v.closest('[data-slate-node="text"]'),_=v,a==="forward"?h=0:(h=_.textContent.length,_.querySelectorAll("[data-slate-zero-width]").forEach(te=>{h-=te.textContent.length})))}_&&h===_.textContent.length&&zt&&_.getAttribute("data-slate-zero-width")==="z"&&(u=_.textContent)!==null&&u!==void 0&&u.startsWith("\uFEFF")&&(d.hasAttribute("data-slate-zero-width")||Mr&&(p=_.textContent)!==null&&p!==void 0&&p.endsWith(`
|
|
4
4
|
|
|
5
5
|
`))&&h--}if(zt&&!c&&!r){var j=d.hasAttribute("data-slate-node")?d:d.closest("[data-slate-node]");if(j&&qe.hasDOMNode(t,j,{editable:!0})){var N=qe.toSlateNode(t,j),{path:B,offset:K}=Y.start(t,qe.findPath(t,N));return j.querySelector("[data-slate-leaf]")||(K=l),{path:B,offset:K}}}if(!c){if(s)return null;throw new Error("Cannot resolve a Slate point from DOM point: ".concat(e))}var fe=qe.toSlateNode(t,c),ae=qe.findPath(t,fe);return{path:ae,offset:h}},toSlateRange:(t,e,n)=>{var r,{exactMatch:s,suppressThrow:a}=n,i=ul(e)?e.anchorNode:e.startContainer,l,d,c,h,u;if(i)if(ul(e)){if(Mr&&e.rangeCount>1){c=e.focusNode;var p=e.getRangeAt(0),y=e.getRangeAt(e.rangeCount-1);if(c instanceof HTMLTableRowElement&&p.startContainer instanceof HTMLTableRowElement&&y.startContainer instanceof HTMLTableRowElement){let I=function(A){return A.childElementCount>0?I(A.children[0]):A};var f=p.startContainer,g=y.startContainer,w=I(f.children[p.startOffset]),x=I(g.children[y.startOffset]);h=0,x.childNodes.length>0?l=x.childNodes[0]:l=x,w.childNodes.length>0?c=w.childNodes[0]:c=w,x instanceof HTMLElement?d=x.innerHTML.length:d=0}else p.startContainer===c?(l=y.endContainer,d=y.endOffset,h=p.startOffset):(l=p.startContainer,d=p.endOffset,h=y.startOffset)}else l=e.anchorNode,d=e.anchorOffset,c=e.focusNode,h=e.focusOffset;Im&&fb(l)||Mr?u=e.anchorNode===e.focusNode&&e.anchorOffset===e.focusOffset:u=e.isCollapsed}else l=e.startContainer,d=e.startOffset,c=e.endContainer,h=e.endOffset,u=e.collapsed;if(l==null||c==null||d==null||h==null)throw new Error("Cannot resolve a Slate range from DOM range: ".concat(e));Mr&&(r=c.textContent)!==null&&r!==void 0&&r.endsWith(`
|
|
@@ -69,7 +69,7 @@ The error may be correlated with this previous error:
|
|
|
69
69
|
`),(v=e==null?void 0:e.onChunk)==null||v.call(e,`- 每段视频生成完成后,系统会自动提取尾帧作为下一段的首帧,确保画面连贯
|
|
70
70
|
`),(_=e==null?void 0:e.onChunk)==null||_.call(e,`- 所有片段生成完成后会自动合并并插入画布
|
|
71
71
|
`),(T=e==null?void 0:e.onChunk)==null||T.call(e,`- 您可以在任务队列中查看实时进度
|
|
72
|
-
`),{success:!0,data:{batchId:A,taskId:D.id,segmentCount:I.length,totalDuration:r,scripts:I},type:"video",taskId:D.id}}catch(b){return console.error("[LongVideo] Generation failed:",b),{success:!1,error:b.message||"长视频生成失败",type:"error"}}}const RO=Object.freeze(Object.defineProperty({__proto__:null,createLongVideoSegmentTask:lp,createLongVideoTask:AT},Symbol.toStringTag,{value:"Module"}));function Ys(t,e=400){if(!t)return{width:e,height:e};const n=t.match(/^(\d+)x(\d+)$/);if(!n)return{width:e,height:e};const r=parseInt(n[1],10),s=parseInt(n[2],10);return r<=0||s<=0?{width:e,height:e}:{width:e,height:Math.round(e*(s/r))}}async function jT(t,e,n,r,s=If(t)){if(r)return Qc(t,[{title:r,body:e}],n,s),{width:s,height:120};const a=kf(e);if(a&&a.length>0){Qc(t,a,n,s);const i=Math.min(a.length,3),l=Math.ceil(a.length/3);return{width:i*(s+20)-20,height:l*140-20}}return Pf.insertText(t,n,e),Cf(e)}function OT(t,e,n){const r=If(t);if(n)return{width:r,height:120};const s=kf(e);if(s&&s.length>0){const a=Math.min(s.length,3),i=Math.ceil(s.length/3);return{width:a*(r+20)-20,height:i*140-20}}return Cf(e)}function cp(t,e){var n,r;if(e.type==="text")return OT(t,e.content,e.label);if(e.type==="video")return e.dimensions||{width:Gt.MEDIA_DEFAULT_SIZE,height:Math.round(Gt.MEDIA_DEFAULT_SIZE*(9/16))};if(e.type==="audio")return Ql({...e.metadata,width:(n=e.dimensions)==null?void 0:n.width,height:(r=e.dimensions)==null?void 0:r.height});if(e.type==="svg"){const s=Tf(Sf(e.content)),a=Math.min(s.width,Gt.MEDIA_DEFAULT_SIZE),i=s.height/s.width;return{width:a,height:a*i}}return e.dimensions||{width:Gt.MEDIA_DEFAULT_SIZE,height:Gt.MEDIA_DEFAULT_SIZE}}async function MT(t,e,n,r){const s=r||{width:Gt.MEDIA_DEFAULT_SIZE,height:Gt.MEDIA_DEFAULT_SIZE};return vs("[CanvasInsertion][Service] image insert with size",{point:n,size:s,lockReferenceDimensions:!1,skipImageLoad:!0}),await Ty(t,e,n,!1,s,!0,!0,!1,!0),s}async function DT(t,e,n,r){if(r)return await ed(t,e,n,!1,r,!0,!0),r;const s={width:Gt.MEDIA_DEFAULT_SIZE,height:Math.round(Gt.MEDIA_DEFAULT_SIZE*(9/16))};return await ed(t,e,n,!1,s,!0,!0),s}async function NT(t,e,n,r,s){const a=Ql({...s,width:r==null?void 0:r.width,height:r==null?void 0:r.height});return await Ef(t,e,{...s,width:a.width,height:a.height},n,!1,!0),a}async function RT(t,e,n){const r=Sf(e),s=Tf(r),a=Math.min(s.width,Gt.MEDIA_DEFAULT_SIZE),i=s.height/s.width,l=a*i,c={url:Sy(r),width:a,height:l};return Pf.insertImage(t,c,n),{width:a,height:l}}async function LT(t,e,n){const r=t.children.length;let s;e.type==="text"?s=await jT(t,e.content,n,e.label):e.type==="image"?s=await MT(t,e.content,n,e.dimensions):e.type==="video"?s=await DT(t,e.content,n,e.dimensions):e.type==="audio"?s=await NT(t,e.content,n,e.dimensions,e.metadata):e.type==="svg"&&(s=await RT(t,e.content,n));const a=t.children[r];return{elementId:a==null?void 0:a.id,size:s||cp(t,e)}}async function An(t){const e=on();if(!e)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};const{items:n,verticalGap:r=Gt.DEFAULT_VERTICAL_GAP,horizontalGap:s=Gt.DEFAULT_HORIZONTAL_GAP}=t;if(!n||n.length===0)return{success:!1,error:"没有要插入的内容",type:"error"};try{if(!t.startPoint&&n.length===1){const u=n[0];if(u.type==="image"||u.type==="video"){const p=await py(e,u.content,u.type,u.dimensions);if(p)return{success:!0,data:{insertedCount:1,items:[{type:u.type,point:p.point,elementId:p.elementId,size:p.size}],firstElementId:p.elementId,firstElementPosition:p.point,firstElementSize:p.size},type:"text"}}}const a=gy(e);let i=t.startPoint;i||(i=yy(e,{verticalGap:r,logPrefix:"CanvasInsertion"})),i||(i=vy(e,{verticalGap:r,emptyPoint:Gt.DEFAULT_POINT})||Gt.DEFAULT_POINT),vs("[CanvasInsertion][Service] batch begin",{itemsCount:n.length,inputStartPoint:t.startPoint||null,resolvedStartPoint:i,viewport:a,verticalGap:r,horizontalGap:s});const l=wy(e,i,{horizontalGap:s,verticalGap:r});vs("[CanvasInsertion][Service] flow initialized",{startX:l.startX,startY:l.startY,rowRightLimit:l.rowRightLimit,zoom:a.zoom});const d=n.map(u=>cp(e,u)),c=xy(i,d,{canvasWidth:a.width,horizontalGap:s,verticalGap:r});l.bounds=c.bounds;const h=[];for(const[u,p]of n.entries()){const y=c.positions[u];vs("[CanvasInsertion][Service] item layout",{index:u,type:p.type,groupId:p.groupId||null,estimatedSize:d[u],point:y});const f=await LT(e,p,y);h.push({type:p.type,point:y,elementId:f.elementId,size:f.size})}if(h.length>0){const u=by(l)||[h[0].point[0],h[0].point[1]];vs("[CanvasInsertion][Service] batch complete",{insertedCount:h.length,centerPoint:u,bounds:l.bounds}),requestAnimationFrame(()=>{_y(e,u)})}return{success:!0,data:{insertedCount:h.length,items:h,firstElementId:h.length>0?h[0].elementId:void 0,firstElementPosition:h.length>0?h[0].point:void 0,firstElementSize:h.length>0?h[0].size:void 0},type:"text"}}catch(a){return console.error("[CanvasInsertion] Failed to insert content:",a),{success:!1,error:`插入失败: ${a.message||"未知错误"}`,type:"error"}}}async function Mu(t,e,n,r,s){return An({items:[{type:t,content:e,dimensions:r,metadata:s}],startPoint:n})}async function Du(t,e,n){const r=`img-group-${Date.now()}`;return An({items:t.map(s=>({type:"image",content:s,groupId:r,dimensions:n})),startPoint:e})}async function Nu(t,e,n){const r=[{type:"text",content:t,label:"Prompt"}];if(e.length===1)r.push({type:e[0].type,content:e[0].url,dimensions:e[0].dimensions,metadata:e[0].metadata});else{const s=`result-group-${Date.now()}`;e.forEach(a=>{r.push({type:a.type,content:a.url,groupId:s,dimensions:a.dimensions,metadata:a.metadata})})}return An({items:r,startPoint:n})}const bl="lasso",FT=3,BT="#6698FF",zT="rgba(102, 152, 255, 0.08)",$T=1.5,UT="6 4",HT="0.4s";function _l(t,e){if(t.length<=2)return t;let n=0,r=0;const s=t[0],a=t[t.length-1];for(let i=1;i<t.length-1;i++){const l=GT(t[i],s,a);l>n&&(n=l,r=i)}if(n>e){const i=_l(t.slice(0,r+1),e),l=_l(t.slice(r),e);return i.slice(0,-1).concat(l)}return[s,a]}function GT(t,e,n){const r=n[0]-e[0],s=n[1]-e[1],a=r*r+s*s;if(a===0)return Math.hypot(t[0]-e[0],t[1]-e[1]);const i=Math.max(0,Math.min(1,((t[0]-e[0])*r+(t[1]-e[1])*s)/a)),l=e[0]+i*r,d=e[1]+i*s;return Math.hypot(t[0]-l,t[1]-d)}function WT(t,e,n){let r=0;const s=n.length;for(let a=0;a<s;a++){const[i,l]=n[a],[d,c]=n[(a+1)%s];l<=e?c>e&&Nr(i,l,d,c,t,e)>0&&r++:c<=e&&Nr(i,l,d,c,t,e)<0&&r--}return r!==0}function Nr(t,e,n,r,s,a){return(n-t)*(a-e)-(s-t)*(r-e)}function VT(t,e,n,r){const s=Nr(t[0],t[1],e[0],e[1],n[0],n[1]),a=Nr(t[0],t[1],e[0],e[1],r[0],r[1]),i=Nr(n[0],n[1],r[0],r[1],t[0],t[1]),l=Nr(n[0],n[1],r[0],r[1],e[0],e[1]);return(s>0&&a<0||s<0&&a>0)&&(i>0&&l<0||i<0&&l>0)}function KT(t,e){const n=t.getRectangle(e);return n?[[n.x,n.y],[n.x+n.width,n.y],[n.x+n.width,n.y+n.height],[n.x,n.y+n.height]]:null}function qT(t){return[t.x+t.width/2,t.y+t.height/2]}function YT(t,e,n,r){const s=t.getRectangle(e);if(!s)return!1;const a={x:s.x,y:s.y,width:s.width,height:s.height};if(!Fe.isHit(r,a))return!1;const i=KT(t,e);if(!i)return!1;const l=qT(s),d=[...i,l];for(const h of d)if(WT(h[0],h[1],n))return!0;const c=[[i[0],i[1]],[i[1],i[2]],[i[2],i[3]],[i[3],i[0]]];for(let h=0;h<n.length;h++){const u=n[h],p=n[(h+1)%n.length];for(const[y,f]of c)if(VT(u,p,y,f))return!0}return!1}function ZT(t,e){if(t.length===0)return"";const n=[],r=td(e,t[0]);n.push(`M ${r[0]} ${r[1]}`);for(let s=1;s<t.length;s++){const a=td(e,t[s]);n.push(`L ${a[0]} ${a[1]}`)}return n.push("Z"),n.join(" ")}function XT(){const t="http://www.w3.org/2000/svg",e=document.createElementNS(t,"g");e.setAttribute("class","lasso-selection-overlay");const n=document.createElementNS(t,"path");n.setAttribute("fill",zT),n.setAttribute("stroke",BT),n.setAttribute("stroke-width",String($T)),n.setAttribute("stroke-dasharray",UT),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.style.pointerEvents="none";const r=document.createElementNS(t,"animate");return r.setAttribute("attributeName","stroke-dashoffset"),r.setAttribute("from","0"),r.setAttribute("to","20"),r.setAttribute("dur",HT),r.setAttribute("repeatCount","indefinite"),n.appendChild(r),e.appendChild(n),{g:e,path:n}}const LO=t=>{const{pointerDown:e,pointerMove:n,globalPointerUp:r}=t;let s=!1,a=[],i=null,l=null,d=!1,c=[];const h=()=>{i&&i.parentNode&&i.parentNode.removeChild(i),i=null,l=null,a=[],s=!1,d=!1,c=[]};return t.pointerDown=u=>{if(kt.isPointer(t,bl)&&Iy(u)&&!u.ctrlKey&&!u.metaKey){s=!0,d=u.shiftKey,d?c=Tt(t):(c=[],ns(t));const p=Jo(t,u.x,u.y);a=[Qo(t,p)];const f=kt.getActiveHost(t),g=XT();i=g.g,l=g.path,f.appendChild(i);return}e(u)},t.pointerMove=u=>{if(s&&l){const p=Jo(t,u.x,u.y),y=Qo(t,p);a.push(y);const f=ZT(a,t);l.setAttribute("d",f),Ru(t,a,c);return}n(u)},t.globalPointerUp=u=>{if(s){const p=t.viewport.zoom,y=_l(a,FT/p);y.length>=3&&Ru(t,y,c,!0),h();return}r(u)},t};function Ru(t,e,n,r=!1){if(e.length<3)return;const s=Fe.getRectangleByPoints(e),a=[];for(const l of t.children)YT(t,l,e,s)&&a.push(l);const i=n.length>0?JT(n,a):a;r&&i.length>0&&ht.addSelectionWithTemporaryElements(t,i)}function JT(t,e){const n=new Set(t.map(s=>s.id)),r=[...t];for(const s of e)n.has(s.id)||(r.push(s),n.add(s.id));return r}const QT=58,eS=80,Lu=50,xa=40;function tS(t){const e=document.querySelector(".unified-toolbar"),n=document.querySelector(".side-drawer--open.side-drawer--toolbar-right"),r=document.documentElement.classList.contains("aitu-toolbar-dock-right");let s=e?0:QT,a=0;if(e){const i=e.getBoundingClientRect();r?a=Math.max(a,t-i.left):s=Math.max(s,i.right)}if(n){const i=n.getBoundingClientRect();r?a=Math.max(a,t-i.left):s=Math.max(s,i.right)}return{left:Math.max(0,Math.round(s)),right:Math.max(0,Math.round(a))}}function dp(t,e){if(e.width<=0||e.height<=0)return!1;const n=kt.getBoardContainer(t),r=n.clientWidth,s=n.clientHeight,a=tS(r),i=a.left,l=document.querySelector(".chat-drawer--open"),d=Math.max(a.right,l?l.offsetWidth:0),c=r-i-d-xa*2,h=s-Lu-eS-xa*2;if(c<=0||h<=0)return!1;const u=Math.min(c/e.width,h/e.height,3),p=i+xa+c/2,y=Lu+xa+h/2,f=e.x+e.width/2,g=e.y+e.height/2,w=[f-p/u,g-y/u];return dt.updateViewport(t,w,u),!0}function nS(t){let e=1/0,n=1/0,r=-1/0,s=-1/0;for(const a of t.children){if(!at(a))continue;const i=Fe.getRectangleByPoints(a.points);i.width<=0||i.height<=0||(e=Math.min(e,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x+i.width),s=Math.max(s,i.y+i.height))}return!Number.isFinite(e)||!Number.isFinite(n)?null:{x:e,y:n,width:r-e,height:s-n}}function rS(t){const e=Tt(t);let n=null;for(const s of e)if(at(s)){n=s;break}if(!n){for(const s of t.children)if(at(s)){n=s;break}}if(!n)return!1;const r=Fe.getRectangleByPoints(n.points);return dp(t,r)}function FO(t){const e=nS(t);return e?dp(t,e):!1}function sS({items:t,getId:e,onReorder:n,enabled:r=!0}){const[s,a]=m.useState({draggingId:null,dragOverId:null,dragOverPosition:null}),i=m.useRef(null),l=m.useCallback((f,g,w)=>{if(!r)return;f.dataTransfer.effectAllowed="move",f.dataTransfer.setData("text/plain",g);const x=f.currentTarget;x&&f.dataTransfer.setDragImage(x,x.offsetWidth/2,x.offsetHeight/2),i.current=w,requestAnimationFrame(()=>{a({draggingId:g,dragOverId:null,dragOverPosition:null})})},[r]),d=m.useCallback(()=>{i.current=null,a({draggingId:null,dragOverId:null,dragOverPosition:null})},[]),c=m.useCallback((f,g,w)=>{if(!r||s.draggingId===null||s.draggingId===g)return;f.preventDefault(),f.dataTransfer.dropEffect="move";const x=f.currentTarget.getBoundingClientRect(),v=x.top+x.height/2,_=f.clientY<v?"before":"after";(s.dragOverId!==g||s.dragOverPosition!==_)&&a(T=>({...T,dragOverId:g,dragOverPosition:_}))},[r,s.draggingId,s.dragOverId,s.dragOverPosition]),h=m.useCallback((f,g)=>{!r||s.draggingId===null||s.draggingId===g||f.preventDefault()},[r,s.draggingId]),u=m.useCallback((f,g)=>{if(!r)return;const w=f.relatedTarget;f.currentTarget.contains(w)||s.dragOverId===g&&a(v=>({...v,dragOverId:null,dragOverPosition:null}))},[r,s.dragOverId]),p=m.useCallback((f,g,w)=>{if(!r||i.current===null)return;f.preventDefault();const x=i.current;let v=w;s.dragOverPosition==="after"&&(v=w+1),x<v&&(v-=1),x!==v&&n(x,v),d()},[r,s.dragOverPosition,n,d]),y=m.useCallback((f,g)=>({draggable:r,onDragStart:w=>l(w,f,g),onDragEnd:d,onDragOver:w=>c(w,f,g),onDragEnter:w=>h(w,f),onDragLeave:w=>u(w,f),onDrop:w=>p(w,f,g),"data-dragging":s.draggingId===f,"data-drag-over":s.dragOverId===f,"data-drag-position":s.dragOverId===f&&s.dragOverPosition||void 0}),[r,l,d,c,h,u,p,s.draggingId,s.dragOverId,s.dragOverPosition]);return{dragState:s,getDragProps:y,isDragging:s.draggingId!==null}}const bn={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_VERSION:"1.0.0"};function up(t){return"init"in t}function Tl(t){return!!t.write}function Fu(t){return"v"in t||"e"in t}function fi(t){if("e"in t)throw t.e;if((bn?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v}function mi(t){return typeof(t==null?void 0:t.then)=="function"}function hp(t,e,n){if(!n.p.has(t)){n.p.add(t);const r=()=>n.p.delete(t);e.then(r,r)}}function fp(t,e,n){var r;const s=new Set;for(const a of((r=n.get(t))==null?void 0:r.t)||[])s.add(a);for(const a of e.p)s.add(a);return s}const aS=(t,e,...n)=>e.read(...n),iS=(t,e,...n)=>e.write(...n),oS=(t,e)=>{var n;return(n=e.INTERNAL_onInit)==null?void 0:n.call(e,t)},lS=(t,e,n)=>{var r;return(r=e.onMount)==null?void 0:r.call(e,n)},cS=(t,e)=>{var n;const r=Ct(t),s=r[0],a=r[6],i=r[9];if((bn?"production":void 0)!=="production"&&!e)throw new Error("Atom is undefined or null");let l=s.get(e);return l||(l={d:new Map,p:new Set,n:0},s.set(e,l),(n=a.i)==null||n.call(a,e),i==null||i(t,e)),l},dS=t=>{const e=Ct(t),n=e[1],r=e[3],s=e[4],a=e[5],i=e[6],l=e[13],d=[],c=h=>{try{h()}catch(u){d.push(u)}};do{i.f&&c(i.f);const h=new Set,u=h.add.bind(h);r.forEach(p=>{var y;return(y=n.get(p))==null?void 0:y.l.forEach(u)}),r.clear(),a.forEach(u),a.clear(),s.forEach(u),s.clear(),h.forEach(c),r.size&&l(t)}while(r.size||a.size||s.size);if(d.length)throw new AggregateError(d)},uS=t=>{const e=Ct(t),n=e[1],r=e[2],s=e[3],a=e[11],i=e[14],l=e[17],d=[],c=new WeakSet,h=new WeakSet,u=Array.from(s);for(;u.length;){const p=u[u.length-1],y=a(t,p);if(h.has(p)){u.pop();continue}if(c.has(p)){if(r.get(p)===y.n)d.push([p,y]);else if((bn?"production":void 0)!=="production"&&r.has(p))throw new Error("[Bug] invalidated atom exists");h.add(p),u.pop();continue}c.add(p);for(const f of fp(p,y,n))c.has(f)||u.push(f)}for(let p=d.length-1;p>=0;--p){const[y,f]=d[p];let g=!1;for(const w of f.d.keys())if(w!==y&&s.has(w)){g=!0;break}g&&(i(t,y),l(t,y)),r.delete(y)}},Sl=new WeakSet,hS=(t,e)=>{var n,r;const s=Ct(t),a=s[1],i=s[2],l=s[3],d=s[6],c=s[7],h=s[11],u=s[12],p=s[13],y=s[14],f=s[16],g=s[17],w=s[20],x=s[26],v=h(t,e);if(Fu(v)){if(a.has(e)&&i.get(e)!==v.n)return v;let O=!1;for(const[G,C]of v.d)if(y(t,G).n!==C){O=!0;break}if(!O)return v}let _=!0;const T=new Set(v.d.keys()),b=new Map,I=()=>{for(const O of T)b.has(O)||v.d.delete(O)},A=()=>{if(a.has(e)){const O=!l.size;g(t,e),O&&(p(t),u(t))}},k=O=>{var G;if(O===e){const P=h(t,O);if(!Fu(P))if(up(O))w(t,O,O.init);else throw new Error("no atom init");return fi(P)}const C=y(t,O);try{return fi(C)}finally{b.set(O,C.n),v.d.set(O,C.n),mi(v.v)&&hp(e,v.v,C),a.has(e)&&((G=a.get(O))==null||G.t.add(e)),_||A()}};let U,D;const X={get signal(){return U||(U=new AbortController),U.signal},get setSelf(){return(bn?"production":void 0)!=="production"&&console.warn("[DEPRECATED] setSelf is deprecated and will be removed in v3."),(bn?"production":void 0)!=="production"&&!Tl(e)&&console.warn("setSelf function cannot be used with read-only atom"),!D&&Tl(e)&&(D=(...O)=>{if((bn?"production":void 0)!=="production"&&_&&console.warn("setSelf function cannot be called in sync"),!_)try{return f(t,e,...O)}finally{p(t),u(t)}}),D}},L=v.n;try{(bn?"production":void 0)!=="production"&&Sl.delete(t);const O=c(t,e,k,X);if((bn?"production":void 0)!=="production"&&Sl.has(t)&&console.warn("Detected store mutation during atom read. This is not supported."),w(t,e,O),mi(O)){x(t,O,()=>U==null?void 0:U.abort());const G=()=>{I(),A()};O.then(G,G)}else I();return(n=d.r)==null||n.call(d,e),v}catch(O){return delete v.v,v.e=O,++v.n,v}finally{_=!1,L!==v.n&&i.get(e)===L&&(i.set(e,v.n),l.add(e),(r=d.c)==null||r.call(d,e))}},fS=(t,e)=>{const n=Ct(t),r=n[1],s=n[2],a=n[11],i=[e];for(;i.length;){const l=i.pop(),d=a(t,l);for(const c of fp(l,d,r)){const h=a(t,c);s.get(c)!==h.n&&(s.set(c,h.n),i.push(c))}}},mS=(t,e,...n)=>{const r=Ct(t),s=r[3],a=r[6],i=r[8],l=r[11],d=r[12],c=r[13],h=r[14],u=r[15],p=r[16],y=r[17],f=r[20];let g=!0;const w=v=>fi(h(t,v)),x=(v,..._)=>{var T;const b=l(t,v);try{if(v===e){if(!up(v))throw new Error("atom not writable");(bn?"production":void 0)!=="production"&&Sl.add(t);const I=b.n,A=_[0];f(t,v,A),y(t,v),I!==b.n&&(s.add(v),u(t,v),(T=a.c)==null||T.call(a,v));return}else return p(t,v,..._)}finally{g||(c(t),d(t))}};try{return i(t,e,w,x,...n)}finally{g=!1}},pS=(t,e)=>{var n;const r=Ct(t),s=r[1],a=r[3],i=r[6],l=r[11],d=r[15],c=r[18],h=r[19],u=l(t,e),p=s.get(e);if(p){for(const[y,f]of u.d)if(!p.d.has(y)){const g=l(t,y);c(t,y).t.add(e),p.d.add(y),f!==g.n&&(a.add(y),d(t,y),(n=i.c)==null||n.call(i,y))}for(const y of p.d)if(!u.d.has(y)){p.d.delete(y);const f=h(t,y);f==null||f.t.delete(e)}}},gS=(t,e)=>{var n;const r=Ct(t),s=r[1],a=r[4],i=r[6],l=r[10],d=r[11],c=r[12],h=r[13],u=r[14],p=r[16],y=r[18],f=d(t,e);let g=s.get(e);if(!g){u(t,e);for(const w of f.d.keys())y(t,w).t.add(e);if(g={l:new Set,d:new Set(f.d.keys()),t:new Set},s.set(e,g),Tl(e)){const w=()=>{let x=!0;const v=(..._)=>{try{return p(t,e,..._)}finally{x||(h(t),c(t))}};try{const _=l(t,e,v);_&&(g.u=()=>{x=!0;try{_()}finally{x=!1}})}finally{x=!1}};a.add(w)}(n=i.m)==null||n.call(i,e)}return g},yS=(t,e)=>{var n,r;const s=Ct(t),a=s[1],i=s[5],l=s[6],d=s[11],c=s[19],h=d(t,e);let u=a.get(e);if(!u||u.l.size)return u;let p=!1;for(const y of u.t)if((n=a.get(y))!=null&&n.d.has(e)){p=!0;break}if(!p){u.u&&i.add(u.u),u=void 0,a.delete(e);for(const y of h.d.keys()){const f=c(t,y);f==null||f.t.delete(e)}(r=l.u)==null||r.call(l,e);return}return u},vS=(t,e,n)=>{const r=Ct(t),s=r[11],a=r[27],i=s(t,e),l="v"in i,d=i.v;if(mi(n))for(const c of i.d.keys())hp(e,n,s(t,c));i.v=n,delete i.e,(!l||!Object.is(d,i.v))&&(++i.n,mi(d)&&a(t,d))},wS=(t,e)=>{const n=Ct(t)[14];return fi(n(t,e))},xS=(t,e,...n)=>{const r=Ct(t),s=r[12],a=r[13],i=r[16];try{return i(t,e,...n)}finally{a(t),s(t)}},bS=(t,e,n)=>{const r=Ct(t),s=r[12],a=r[18],i=r[19],d=a(t,e).l;return d.add(n),s(t),()=>{d.delete(n),i(t,e),s(t)}},_S=(t,e,n)=>{const s=Ct(t)[25];let a=s.get(e);if(!a){a=new Set,s.set(e,a);const i=()=>s.delete(e);e.then(i,i)}a.add(n)},TS=(t,e)=>{const s=Ct(t)[25].get(e);s==null||s.forEach(a=>a())},mp=new WeakMap,Ct=t=>{const e=mp.get(t);if((bn?"production":void 0)!=="production"&&!e)throw new Error("Store must be created by buildStore to read its building blocks");return e};function SS(t){const e=Ct(t),n=e[24];return n?n(e):e}function IS(...t){const e={get(r){const s=Ct(e)[21];return s(e,r)},set(r,...s){const a=Ct(e)[22];return a(e,r,...s)},sub(r,s){const a=Ct(e)[23];return a(e,r,s)}},n=[new WeakMap,new WeakMap,new WeakMap,new Set,new Set,new Set,{},aS,iS,oS,lS,cS,dS,uS,hS,fS,mS,pS,gS,yS,vS,wS,xS,bS,void 0,new WeakMap,_S,TS].map((r,s)=>t[s]||r);return mp.set(e,Object.freeze(n)),e}const pp={};let kS=0;function Vt(t,e){const n=`atom${++kS}`,r={toString(){return(pp?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?r.read=t:(r.init=t,r.read=CS,r.write=PS),e&&(r.write=e),r}function CS(t){return t(this)}function PS(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}function ES(){return IS()}let hs;function gp(){return hs||(hs=ES(),(pp?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=hs),globalThis.__JOTAI_DEFAULT_STORE__!==hs&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),hs}const AS={},jS=m.createContext(void 0);function yp(t){return m.useContext(jS)||gp()}const Il=t=>typeof(t==null?void 0:t.then)=="function",kl=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},OS=Ie.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(kl(t),t)}),bo=new WeakMap,Bu=(t,e,n)=>{const s=SS(t)[26];let a=bo.get(e);return a||(a=new Promise((i,l)=>{let d=e;const c=p=>y=>{d===p&&i(y)},h=p=>y=>{d===p&&l(y)},u=()=>{try{const p=n();Il(p)?(bo.set(p,a),d=p,p.then(c(p),h(p)),s(t,p,u)):i(p)}catch(p){l(p)}};e.then(c(e),h(e)),s(t,e,u)}),bo.set(e,a)),a};function Hn(t,e){const{delay:n,unstable_promiseStatus:r=!Ie.use}={},s=yp(),[[a,i,l],d]=m.useReducer(h=>{const u=s.get(t);return Object.is(h[0],u)&&h[1]===s&&h[2]===t?h:[u,s,t]},void 0,()=>[s.get(t),s,t]);let c=a;if((i!==s||l!==t)&&(d(),c=s.get(t)),m.useEffect(()=>{const h=s.sub(t,()=>{if(r)try{const u=s.get(t);Il(u)&&kl(Bu(s,u,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(d,n);return}d()});return d(),h},[s,t,n,r]),m.useDebugValue(c),Il(c)){const h=Bu(s,c,()=>s.get(t));return r&&kl(h),OS(h)}return c}function br(t,e){const n=yp();return m.useCallback((...s)=>{if((AS?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...s)},[n,t])}const At=Vt([]),dn=Vt(!0),MS=Vt(t=>t(At).filter(e=>e.status===ve.PENDING||e.status===ve.PROCESSING)),DS=Vt(t=>t(At).filter(e=>e.status===ve.COMPLETED)),NS=Vt(t=>t(At).filter(e=>e.status===ve.FAILED)),RS=Vt(t=>t(At).filter(e=>e.status===ve.CANCELLED)),LS=Vt(t=>t(At).length),FS=Vt(t=>t(At).length),BS=Vt(null,(t,e,n)=>{try{const r=xe.createTask(n.params,n.type);return e(At,xe.getAllTasks()),e(dn,!1),r}catch{return null}}),zS=Vt(null,(t,e,n)=>{xe.cancelTask(n),e(At,xe.getAllTasks()),e(dn,!1)}),$S=Vt(null,(t,e,n)=>{xe.retryTask(n),e(At,xe.getAllTasks()),e(dn,!1)}),US=Vt(null,(t,e,n)=>{xe.deleteTask(n),e(At,xe.getAllTasks()),e(dn,!1)}),HS=Vt(null,(t,e)=>{xe.clearCompletedTasks(),e(At,xe.getAllTasks()),e(dn,!1)}),GS=Vt(null,(t,e)=>{xe.clearFailedTasks(),e(At,xe.getAllTasks()),e(dn,!1)});let zu=!1,$u=!1;const Nn=gp();function WS(t){const e=Nn.get(At);let n;switch(t.type){case"taskCreated":e.some(r=>r.id===t.task.id)?n=e.map(r=>r.id===t.task.id?t.task:r):n=[t.task,...e];break;case"taskDeleted":n=e.filter(r=>r.id!==t.task.id);break;default:e.some(r=>r.id===t.task.id)?n=e.map(r=>r.id===t.task.id?t.task:r):n=[t.task,...e];break}Nn.set(At,n),Nn.set(dn,!1)}function Uu(){const t=xe.getAllTasks();Nn.set(At,t),Nn.set(dn,!1)}async function VS(){if(await new Promise(r=>setTimeout(r,500)),xe.getAllTasks().length>0){Uu();return}if(!await ei.isAvailable()){Nn.set(dn,!1);return}const n=await ei.getAllTasks({limit:ky.MAX_RETAINED_TASKS});n.length>0&&xe.restoreTasks(n),Uu()}function KS(){if(zu)return;zu=!0;const t=xe.getAllTasks();Nn.set(At,t),Nn.set(dn,t.length===0),xe.observeTaskUpdates().subscribe(e=>{WS(e)}),t.length===0&&!$u&&($u=!0,VS().catch(()=>{Nn.set(dn,!1)}))}function vp(){m.useEffect(()=>{KS()},[]);const t=Hn(At),e=Hn(dn);return{tasks:t,isLoading:e}}function qS(){const t=br(BS),e=br(zS),n=br($S),r=br(US),s=br(HS),a=br(GS),i=m.useCallback((p,y)=>t({params:p,type:y}),[t]),l=m.useCallback(p=>e(p),[e]),d=m.useCallback(p=>n(p),[n]),c=m.useCallback(p=>r(p),[r]),h=m.useCallback(()=>s(),[s]),u=m.useCallback(()=>a(),[a]);return{createTask:i,cancelTask:l,retryTask:d,deleteTask:c,clearCompletedTasks:h,clearFailedTasks:u}}function YS(){const{tasks:t,isLoading:e}=vp(),n=Hn(MS),r=Hn(DS),s=Hn(NS),a=Hn(RS),i=Hn(LS),l=Hn(FS),d=!1,c=!1,{createTask:h,cancelTask:u,retryTask:p,deleteTask:y,clearCompletedTasks:f,clearFailedTasks:g}=qS(),w=m.useCallback(async()=>{},[]),x=m.useCallback(b=>xe.getTask(b),[]),v=m.useCallback(b=>{b.forEach(I=>{y(I)})},[y]),_=m.useCallback(b=>{b.forEach(I=>{p(I)})},[p]),T=m.useCallback(b=>{b.forEach(I=>{u(I)})},[u]);return{tasks:t,activeTasks:n,completedTasks:r,failedTasks:s,cancelledTasks:a,isLoading:e,isLoadingMore:d,hasMore:c,totalCount:i,loadedCount:l,loadMore:w,createTask:h,cancelTask:u,retryTask:p,deleteTask:y,clearCompleted:f,clearFailed:g,getTask:x,batchDeleteTasks:v,batchRetryTasks:_,batchCancelTasks:T}}function Xr(t,e){const n=new Set(e.filter(at).map(a=>a.id));if(n.size===0)return{primaryElements:e,relatedByFrameId:new Map};const r=e.filter(a=>{if(at(a))return!0;const i=Gn.getAssociatedFrameId(t,a);return!i||!n.has(i)}),s=new Map;for(const a of t.children){if(at(a))continue;const i=Gn.getAssociatedFrameId(t,a);if(!i||!n.has(i))continue;const l=s.get(i)??[];l.push(a),s.set(i,l)}return{primaryElements:r,relatedByFrameId:s}}function Hu(t,e,n,r){if(n===0&&r===0)return;const s=t.children.findIndex(l=>l.id===e.id);if(s<0)return;const a=t.children[s],i=[s];if(a.points&&Array.isArray(a.points)){const l=a.points.map(d=>[d[0]+n,d[1]+r]);ht.setNode(t,{points:l},i);return}typeof a.x=="number"&&typeof a.y=="number"&&ht.setNode(t,{x:a.x+n,y:a.y+r},i)}function Jr(t,e,n,r,s,a){if(a.has(e.id)||(Hu(t,e,n,r),a.add(e.id),!at(e)))return;const i=s.get(e.id)??[];for(const l of i)a.has(l.id)||(Hu(t,l,n,r),a.add(l.id))}const ZS=(t,e)=>Ln(t,[e],!1),_r=(t,e)=>{const n=Tt(t);if(n.length<2)return;const{primaryElements:r,relatedByFrameId:s}=Xr(t,n);if(r.length<2)return;const a=Ln(t,r,!1),i=new Set;r.forEach(l=>{const d=ZS(t,l);let c=0,h=0;switch(e){case"left":c=a.x-d.x;break;case"center":const u=a.x+a.width/2,p=d.x+d.width/2;c=u-p;break;case"right":const y=a.x+a.width,f=d.x+d.width;c=y-f;break;case"top":h=a.y-d.y;break;case"middle":const g=a.y+a.height/2,w=d.y+d.height/2;h=g-w;break;case"bottom":const x=a.y+a.height,v=d.y+d.height;h=x-v;break}c===0&&h===0||Jr(t,l,c,h,s,i)})},Tr={alignLeft:t=>{_r(t,"left")},alignCenter:t=>{_r(t,"center")},alignRight:t=>{_r(t,"right")},alignTop:t=>{_r(t,"top")},alignMiddle:t=>{_r(t,"middle")},alignBottom:t=>{_r(t,"bottom")}},Tc=(t,e)=>Ln(t,[e],!1),XS=t=>{const e=Tt(t);if(e.length<3)return;const{primaryElements:n,relatedByFrameId:r}=Xr(t,e);if(n.length<3)return;const s=n.map(f=>({element:f,rect:Tc(t,f)}));s.sort((f,g)=>f.rect.x-g.rect.x);const a=s[0].rect,i=s[s.length-1].rect,l=i.x+i.width-a.x,d=s.reduce((f,g)=>f+g.rect.width,0),c=l-d,h=s.length-1,u=h>0?c/h:0;let p=a.x+a.width+u;const y=new Set;for(let f=1;f<s.length-1;f++){const{element:g,rect:w}=s[f],x=p-w.x;Math.abs(x)>.01&&Jr(t,g,x,0,r,y),p+=w.width+u}},JS=t=>{const e=Tt(t);if(e.length<3)return;const{primaryElements:n,relatedByFrameId:r}=Xr(t,e);if(n.length<3)return;const s=n.map(f=>({element:f,rect:Tc(t,f)}));s.sort((f,g)=>f.rect.y-g.rect.y);const a=s[0].rect,i=s[s.length-1].rect,l=i.y+i.height-a.y,d=s.reduce((f,g)=>f+g.rect.height,0),c=l-d,h=s.length-1,u=h>0?c/h:0;let p=a.y+a.height+u;const y=new Set;for(let f=1;f<s.length-1;f++){const{element:g,rect:w}=s[f],x=p-w.y;Math.abs(x)>.01&&Jr(t,g,0,x,r,y),p+=w.height+u}},QS=t=>{const e=Tt(t);if(e.length<2)return;const{primaryElements:n,relatedByFrameId:r}=Xr(t,e);if(n.length<2)return;const s=Ln(t,n,!1),a=n.map(w=>({element:w,rect:Tc(t,w)})),i=a.reduce((w,x)=>w+x.rect.width,0)/a.length,l=a.reduce((w,x)=>w+x.rect.height,0)/a.length,d=a.length,c=s.width/s.height;let h;c>1.5?h=Math.ceil(Math.sqrt(d*c)):c<.67?h=Math.ceil(Math.sqrt(d/c)):h=Math.ceil(Math.sqrt(d)),h=Math.max(1,Math.min(h,d));const u=i*.2,p=l*.2;a.sort((w,x)=>{const v=Math.floor(w.rect.y/(l+p)),_=Math.floor(x.rect.y/(l+p));return v!==_?v-_:w.rect.x-x.rect.x});const y=s.x,f=s.y,g=new Set;a.forEach((w,x)=>{const v=x%h,_=Math.floor(x/h),T=y+v*(i+u),b=f+_*(l+p),I=T-w.rect.x,A=b-w.rect.y;(Math.abs(I)>.01||Math.abs(A)>.01)&&Jr(t,w.element,I,A,r,g)})},_o={distributeHorizontal:XS,distributeVertical:JS,autoArrange:QS},pi=1e3;function Gu(t){return t.map(e=>({X:Math.round(e[0]*pi),Y:Math.round(e[1]*pi)}))}function eI(t){return t.map(e=>[e.X/pi,e.Y/pi])}function tI(t,e,n,r,s,a=16){const i=Math.min(s,n/2,r/2);if(i<=0)return[[t,e],[t+n,e],[t+n,e+r],[t,e+r]];const l=[];for(let d=0;d<=a;d++){const c=-Math.PI/2+Math.PI/2*(d/a);l.push([t+n-i+i*Math.cos(c),e+i+i*Math.sin(c)])}for(let d=0;d<=a;d++){const c=0+Math.PI/2*(d/a);l.push([t+n-i+i*Math.cos(c),e+r-i+i*Math.sin(c)])}for(let d=0;d<=a;d++){const c=Math.PI/2+Math.PI/2*(d/a);l.push([t+i+i*Math.cos(c),e+r-i+i*Math.sin(c)])}for(let d=0;d<=a;d++){const c=Math.PI+Math.PI/2*(d/a);l.push([t+i+i*Math.cos(c),e+i+i*Math.sin(c)])}return l}function nI(t,e,n,r,s=32){const a=[],i=r/2;if(n<=r){const l=t+n/2,d=e+r/2,c=n/2,h=r/2,u=s*4;for(let p=0;p<u;p++){const y=2*Math.PI*p/u;a.push([l+c*Math.cos(y),d+h*Math.sin(y)])}return a}a.push([t+i,e]),a.push([t+n-i,e]);for(let l=0;l<=s;l++){const d=-Math.PI/2+Math.PI*(l/s);a.push([t+n-i+i*Math.cos(d),e+i+i*Math.sin(d)])}a.push([t+n-i,e+r]),a.push([t+i,e+r]);for(let l=0;l<=s;l++){const d=Math.PI/2+Math.PI*(l/s);a.push([t+i+i*Math.cos(d),e+i+i*Math.sin(d)])}return a}function rI(t,e=20){const n=t.points;if(!n||n.length<2)return[];const[r,s]=n,a=Math.min(r[0],s[0]),i=Math.min(r[1],s[1]),l=Math.abs(s[0]-r[0]),d=Math.abs(s[1]-r[1]),c=t.shape;if(c==="ellipse"||c==="circle"){const h=a+l/2,u=i+d/2,p=l/2,y=d/2,f=[],g=Math.PI*(3*(p+y)-Math.sqrt((3*p+y)*(p+3*y))),w=Math.max(180,Math.ceil(g/2));for(let x=0;x<w;x++){const v=2*Math.PI*x/w;f.push([h+p*Math.cos(v),u+y*Math.sin(v)])}return f}else if(c==="roundRectangle"){const h=Math.min(l,d)*.15;return tI(a,i,l,d,h,16)}else{if(c==="terminal"||c==="stadium"||c==="capsule")return nI(a,i,l,d,32);if(c==="triangle")return[[a+l/2,i],[a+l,i+d],[a,i+d]];if(c==="diamond"||c==="rhombus")return[[a+l/2,i],[a+l,i+d/2],[a+l/2,i+d],[a,i+d/2]];if(c==="pentagon"){const h=a+l/2,u=i+d/2,p=Math.min(l,d)/2,y=[];for(let f=0;f<5;f++){const g=2*Math.PI*f/5-Math.PI/2;y.push([h+p*Math.cos(g),u+p*Math.sin(g)])}return y}else if(c==="hexagon"){const h=a+l/2,u=i+d/2,p=Math.min(l,d)/2,y=[];for(let f=0;f<6;f++){const g=2*Math.PI*f/6;y.push([h+p*Math.cos(g),u+p*Math.sin(g)])}return y}else if(c==="octagon"){const h=a+l/2,u=i+d/2,p=Math.min(l,d)/2,y=[];for(let f=0;f<8;f++){const g=2*Math.PI*f/8-Math.PI/8;y.push([h+p*Math.cos(g),u+p*Math.sin(g)])}return y}else if(c==="star"){const h=a+l/2,u=i+d/2,p=Math.min(l,d)/2,y=p*.38,f=[];for(let g=0;g<10;g++){const w=Math.PI*g/5-Math.PI/2,x=g%2===0?p:y;f.push([h+x*Math.cos(w),u+x*Math.sin(w)])}return f}else if(c==="cross"){const h=Math.min(l,d)*.33,u=a+l/2,p=i+d/2;return[[u-h/2,i],[u+h/2,i],[u+h/2,p-h/2],[a+l,p-h/2],[a+l,p+h/2],[u+h/2,p+h/2],[u+h/2,i+d],[u-h/2,i+d],[u-h/2,p+h/2],[a,p+h/2],[a,p-h/2],[u-h/2,p-h/2]]}else if(c==="parallelogram"){const h=l*.2;return[[a+h,i],[a+l,i],[a+l-h,i+d],[a,i+d]]}else if(c==="trapezoid"){const h=l*.15;return[[a+h,i],[a+l-h,i],[a+l,i+d],[a,i+d]]}else return[[a,i],[a+l,i],[a+l,i+d],[a,i+d]]}}function sI(t,e,n=20){if(Jn.isPenPath(e)){if(!e.closed)return null;const r=ia(e);return ki(r,!0,n)}if(rs.isFreehand(e)){const r=e.points;if(!r||r.length<3)return null;const s=r[0],a=r[r.length-1];return Math.hypot(a[0]-s[0],a[1]-s[1])>10?null:r}return It.isDrawElement(e)&&It.isShapeElement(e)?It.isImage(e)||It.isText(e)?null:rI(e,n):null}function Cl(t,e){if(t.length<=2)return t;const n=t[0],r=t[t.length-1];let s=0,a=0;for(let i=1;i<t.length-1;i++){const l=aI(t[i],n,r);l>s&&(s=l,a=i)}if(s>e){const i=Cl(t.slice(0,a+1),e),l=Cl(t.slice(a),e);return[...i.slice(0,-1),...l]}return[n,r]}function aI(t,e,n){const r=n[0]-e[0],s=n[1]-e[1],a=r*r+s*s;if(a===0)return Math.hypot(t[0]-e[0],t[1]-e[1]);const i=Math.max(0,Math.min(1,((t[0]-e[0])*r+(t[1]-e[1])*s)/a)),l=e[0]+i*r,d=e[1]+i*s;return Math.hypot(t[0]-l,t[1]-d)}function iI(t,e){const n=t[0]*e[0]+t[1]*e[1],r=t[0]*e[1]-t[1]*e[0];return Math.atan2(r,n)}function oI(t,e,n){const r=[e[0]-t[0],e[1]-t[1]],s=[n[0]-e[0],n[1]-e[1]];return Math.abs(iI(r,s))}function lI(t,e,n,r=.25){const s=n[0]-t[0],a=n[1]-t[1],i=Math.hypot(s,a);if(i===0)return{handleIn:e,handleOut:e};const l=s/i,d=a/i,c=Math.hypot(e[0]-t[0],e[1]-t[1]),h=Math.hypot(n[0]-e[0],n[1]-e[1]),u=c*r,p=h*r,y=[e[0]-l*u,e[1]-d*u],f=[e[0]+l*p,e[1]+d*p];return{handleIn:y,handleOut:f}}function cI(t,e="#333333",n="#FFFFFF",r=2){if(t.length<3)throw new Error("Polygon must have at least 3 points");const s=Cl(t,.3);let a=1/0,i=1/0,l=-1/0,d=-1/0;for(const f of s)a=Math.min(a,f[0]),i=Math.min(i,f[1]),l=Math.max(l,f[0]),d=Math.max(d,f[1]);const c=[a,i],h=s.length,u=Math.PI*.4,p=s.map((f,g)=>{const w=[f[0]-c[0],f[1]-c[1]],x=s[(g-1+h)%h],v=s[(g+1)%h];if(oI(x,f,v)<u){const{handleIn:T,handleOut:b}=lI(x,f,v,.3);return{point:w,handleIn:[T[0]-c[0],T[1]-c[1]],handleOut:[b[0]-c[0],b[1]-c[1]],type:"smooth"}}return{point:w,type:"corner"}});return{id:Xl(),type:_f,shape:Qa.pen,points:[c,[l,d]],anchors:p,closed:!0,strokeColor:e,fill:n,strokeWidth:r}}async function as(){const t=await Xe(()=>import("./clipper-CpI1VJRD.js").then(e=>e.c),[],import.meta.url);return t.default||t}async function oa(t,e,n){const r=Tt(t);if(r.length<2){ee.warning(n==="zh"?"请选择至少2个闭合图形":"Please select at least 2 closed shapes");return}const s=[];for(const i of r){const l=sI(t,i);l&&l.length>=3&&s.push({element:i,polygon:l})}if(s.length<2){ee.warning(n==="zh"?"请确保选中的图形都是闭合的(如矩形、椭圆、闭合钢笔路径等)":"Please make sure all selected shapes are closed (rectangles, ellipses, closed pen paths, etc.)");return}const a=ee.loading(n==="zh"?"正在处理...":"Processing...",0);try{const i=await as(),l=new i.Clipper,d=[],c=Gu(s[0].polygon);l.AddPath(c,i.PolyType.ptSubject,!0);for(let v=1;v<s.length;v++){const _=Gu(s[v].polygon);l.AddPath(_,i.PolyType.ptClip,!0)}if(!l.Execute(e,d,i.PolyFillType.pftNonZero,i.PolyFillType.pftNonZero)||d.length===0){ee.close(a),ee.warning(n==="zh"?"布尔运算无结果(图形可能不相交)":"No result (shapes may not intersect)");return}const u=s[0].element;let p="#333333",y="#FFFFFF",f=2;(Jn.isPenPath(u)||It.isDrawElement(u))&&(p=u.strokeColor||p,y=u.fill||y,f=u.strokeWidth||f),Cy(t);const g=[];for(const v of d){const _=eI(v);if(_.length>=3){const T=cI(_,p,y,f);g.push(T)}}const w=[];for(const v of g){const _=t.children.length;ht.insertNode(t,v,[_]),w.push(v.id)}ns(t);for(const v of w){const _=t.children.find(T=>T.id===v);if(_)try{ta(t,_)}catch{}}ee.close(a);const x={[i.ClipType.ctUnion]:n==="zh"?"合并":"Union",[i.ClipType.ctDifference]:n==="zh"?"减去":"Subtract",[i.ClipType.ctIntersection]:n==="zh"?"相交":"Intersect",[i.ClipType.ctXor]:n==="zh"?"排除":"Exclude"};ee.success(n==="zh"?`${x[e]}完成,生成 ${g.length} 个图形`:`${x[e]} completed, ${g.length} shape(s) created`)}catch(i){ee.close(a),console.error("Boolean operation error:",i),ee.error(i.message||(n==="zh"?"操作失败":"Operation failed"))}}const dI=async(t,e="zh")=>{const n=await as();await oa(t,n.ClipType.ctUnion,e)},uI=async(t,e="zh")=>{const n=await as();await oa(t,n.ClipType.ctDifference,e)},hI=async(t,e="zh")=>{const n=await as();await oa(t,n.ClipType.ctIntersection,e)},fI=async(t,e="zh")=>{const n=await as();await oa(t,n.ClipType.ctXor,e)},mI=async(t,e="zh")=>{const n=await as();await oa(t,n.ClipType.ctUnion,e)},pI={union:dI,subtract:uI,intersect:hI,exclude:fI,flatten:mI};var zn=(t=>(t.LOAD_FAILED="load-failed",t.CORS_BLOCKED="cors-blocked",t.PERMISSION_DENIED="permission-denied",t.TIMEOUT="timeout",t))(zn||{});function gI(t){const{h:e,s:n,v:r}=t,s=e/360,a=n/100,i=r/100;let l=0,d=0,c=0;const h=Math.floor(s*6),u=s*6-h,p=i*(1-a),y=i*(1-u*a),f=i*(1-(1-u)*a);switch(h%6){case 0:l=i,d=f,c=p;break;case 1:l=y,d=i,c=p;break;case 2:l=p,d=i,c=f;break;case 3:l=p,d=y,c=i;break;case 4:l=f,d=p,c=i;break;case 5:l=i,d=p,c=y;break}return{r:Math.round(l*255),g:Math.round(d*255),b:Math.round(c*255)}}function yI(t){const{r:e,g:n,b:r}=t,s=e/255,a=n/255,i=r/255,l=Math.max(s,a,i),d=Math.min(s,a,i),c=l-d;let h=0,u=0;const p=l;return c!==0&&(u=c/l,l===s?h=(a-i)/c%6:l===a?h=(i-s)/c+2:h=(s-a)/c+4,h*=60,h<0&&(h+=360)),{h:Math.round(h),s:Math.round(u*100),v:Math.round(p*100)}}function vI(t,e=!1){const{r:n,g:r,b:s}=t,a=`#${Ts(n)}${Ts(r)}${Ts(s)}`;if(e&&"a"in t){const i=Math.round(t.a*255);return`${a}${Ts(i)}`}return a}function Sc(t){const e=t.replace(/^#/,"");let n=0,r=0,s=0,a=1;if(e.length===3)n=parseInt(e[0]+e[0],16),r=parseInt(e[1]+e[1],16),s=parseInt(e[2]+e[2],16);else if(e.length===6)n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),s=parseInt(e.substring(4,6),16);else if(e.length===8)n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),s=parseInt(e.substring(4,6),16),a=parseInt(e.substring(6,8),16)/255;else return null;return isNaN(n)||isNaN(r)||isNaN(s)||isNaN(a)?null:{r:n,g:r,b:s,a}}function Ha(t,e){const n=gI(t);return vI(n)}function fs(t){const e=Sc(t);return e?yI(e):{h:0,s:100,v:100}}function To(t){const e=Sc(t);return e?Math.round(e.a*100):100}function Wu(t,e){const n=t.replace(/^#/,"").substring(0,6),r=Ts(Math.round(e/100*255));return`#${n}${r}`}function Zs(t){const e=t.replace(/^#/,"");return e.length===8?`#${e.substring(0,6)}`:e.length===3?`#${e[0]}${e[0]}${e[1]}${e[1]}${e[2]}${e[2]}`:t.startsWith("#")?t:`#${t}`}function Ar(t){return/^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/.test(t)}function wI(t){const e=t.replace(/^#/,"").toUpperCase();return e.length===3?`#${e[0]}${e[0]}${e[1]}${e[1]}${e[2]}${e[2]}`:e.length===6||e.length===8?`#${e}`:t}function Ts(t){const e=Math.max(0,Math.min(255,Math.round(t))).toString(16);return e.length===1?"0"+e:e}function xI(t){const e=Sc(t);return e?.299*e.r+.587*e.g+.114*e.b:0}function wp(t){return xI(t)>186}function Ic({disabled:t=!1,onDrag:e}){const[n,r]=m.useState(!1),s=m.useRef(e);m.useEffect(()=>{s.current=e},[e]);const a=m.useCallback(d=>{t||(r(!0),s.current(d))},[t]),i=m.useCallback(d=>{t||(d.preventDefault(),a({clientX:d.clientX,clientY:d.clientY}))},[t,a]),l=m.useCallback(d=>{if(t)return;d.preventDefault();const c=d.touches[0];c&&a({clientX:c.clientX,clientY:c.clientY})},[t,a]);return m.useEffect(()=>{if(!n)return;const d=u=>{u.preventDefault(),s.current({clientX:u.clientX,clientY:u.clientY})},c=()=>{r(!1)},h=u=>{u.preventDefault();const p=u.touches[0];p&&s.current({clientX:p.clientX,clientY:p.clientY})};return document.addEventListener("mousemove",d),document.addEventListener("mouseup",c),document.addEventListener("touchmove",h,{passive:!1}),document.addEventListener("touchend",c),()=>{document.removeEventListener("mousemove",d),document.removeEventListener("mouseup",c),document.removeEventListener("touchmove",h),document.removeEventListener("touchend",c)}},[n]),{onMouseDown:i,onTouchStart:l}}const bI=({hue:t,saturation:e,value:n,onChange:r,disabled:s=!1})=>{const a=m.useRef(null),i={left:`${e}%`,top:`${100-n}%`},l=Ha({h:t,s:100,v:100}),d=m.useCallback((u,p)=>{if(!a.current)return;const y=a.current.getBoundingClientRect(),f=Math.max(0,Math.min(u-y.left,y.width)),g=Math.max(0,Math.min(p-y.top,y.height)),w=Math.round(f/y.width*100),x=Math.round(100-g/y.height*100);r(w,x)},[r]),c=m.useCallback(({clientX:u,clientY:p})=>{d(u,p)},[d]),h=Ic({disabled:s,onDrag:c});return o.jsxs("div",{ref:a,className:"ucp-hs-panel",style:{backgroundColor:l},onMouseDown:h.onMouseDown,onTouchStart:h.onTouchStart,children:[o.jsx("div",{className:"ucp-hs-panel__white-gradient"}),o.jsx("div",{className:"ucp-hs-panel__black-gradient"}),o.jsx("div",{className:"ucp-hs-panel__indicator",style:i})]})},_I=({hue:t,onChange:e,disabled:n=!1})=>{const r=m.useRef(null),s=t/360*100,a=m.useCallback(d=>{if(!r.current)return;const c=r.current.getBoundingClientRect(),h=Math.max(0,Math.min(d-c.left,c.width)),u=Math.round(h/c.width*360);e(u)},[e]),i=m.useCallback(({clientX:d})=>{a(d)},[a]),l=Ic({disabled:n,onDrag:i});return o.jsxs("div",{ref:r,className:"ucp-hue-slider",onMouseDown:l.onMouseDown,onTouchStart:l.onTouchStart,children:[o.jsx("div",{className:"ucp-hue-slider__track"}),o.jsx("div",{className:"ucp-hue-slider__indicator",style:{left:`${s}%`}})]})},TI=({alpha:t,color:e,onChange:n,disabled:r=!1})=>{const s=m.useRef(null),a=t,l={background:`linear-gradient(to right, transparent 0%, ${Zs(e)} 100%)`},d=m.useCallback(u=>{if(!s.current)return;const p=s.current.getBoundingClientRect(),y=Math.max(0,Math.min(u-p.left,p.width)),f=Math.round(y/p.width*100);n(f)},[n]),c=m.useCallback(({clientX:u})=>{d(u)},[d]),h=Ic({disabled:r,onDrag:c});return o.jsxs("div",{ref:s,className:"ucp-alpha-slider",onMouseDown:h.onMouseDown,onTouchStart:h.onTouchStart,children:[o.jsx("div",{className:"ucp-alpha-slider__checkerboard"}),o.jsx("div",{className:"ucp-alpha-slider__gradient",style:l}),o.jsx("div",{className:"ucp-alpha-slider__indicator",style:{left:`${a}%`}})]})},SI=({colors:t,selectedColor:e,onSelect:n,disabled:r=!1})=>{const s=e?Zs(e).toUpperCase():"";return o.jsx("div",{className:"ucp-preset-colors",children:t.map((a,i)=>{const l=Py(a.value),d=Zs(a.value).toUpperCase(),c=s===d,h=!l&&wp(a.value);return o.jsx(Le,{content:a.name,showArrow:!1,children:o.jsxs("button",{className:St("ucp-preset-colors__item",{"ucp-preset-colors__item--selected":c,"ucp-preset-colors__item--no-color":l,"ucp-preset-colors__item--light":h}),style:{backgroundColor:l?"transparent":a.value},disabled:r,onClick:()=>n(a.value),children:[l&&o.jsx("svg",{className:"ucp-preset-colors__no-color-icon",viewBox:"0 0 24 24",children:o.jsx("line",{x1:"4",y1:"4",x2:"20",y2:"20",stroke:"currentColor",strokeWidth:"2"})}),c&&!l&&o.jsx("svg",{className:"ucp-preset-colors__check-icon",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z",fill:"currentColor"})})]})},`${a.value}-${i}`)})})},II=({value:t,alpha:e,onColorChange:n,onAlphaChange:r,showAlpha:s=!0,disabled:a=!1})=>{const[i,l]=m.useState(t.replace("#","")),[d,c]=m.useState(String(e));m.useEffect(()=>{l(t.replace("#",""))},[t]),m.useEffect(()=>{c(String(e))},[e]);const h=m.useCallback(w=>{const v=w.target.value.replace("#","").toUpperCase().replace(/[^0-9A-F]/gi,"").substring(0,6);l(v)},[]),u=m.useCallback(()=>{const w=`#${i}`;if(Ar(w)){const x=wI(w);n(x),l(x.replace("#",""))}else l(t.replace("#",""))},[i,t,n]),p=m.useCallback(w=>{w.key==="Enter"&&u()},[u]),y=m.useCallback(w=>{const v=w.target.value.replace(/[^0-9]/g,"");c(v)},[]),f=m.useCallback(()=>{let w=parseInt(d,10);isNaN(w)?w=e:w=Math.max(0,Math.min(100,w)),c(String(w)),r(w)},[d,e,r]),g=m.useCallback(w=>{w.key==="Enter"&&f()},[f]);return o.jsxs("div",{className:"ucp-hex-input",children:[o.jsxs("div",{className:"ucp-hex-input__hex-group",children:[o.jsx("span",{className:"ucp-hex-input__prefix",children:"#"}),o.jsx("input",{type:"text",className:"ucp-hex-input__input",value:i,onChange:h,onBlur:u,onKeyDown:p,disabled:a,maxLength:6,placeholder:"000000"})]}),s&&o.jsxs("div",{className:"ucp-hex-input__alpha-group",children:[o.jsx("input",{type:"text",className:"ucp-hex-input__alpha-input",value:d,onChange:y,onBlur:f,onKeyDown:g,disabled:a,maxLength:3,placeholder:"100"}),o.jsx("span",{className:"ucp-hex-input__suffix",children:"%"})]})]})},Vu=()=>typeof window<"u"&&"EyeDropper"in window,kI=({onPick:t,disabled:e=!1})=>{const[n,r]=m.useState(!1),s=m.useCallback(async()=>{if(!(e||!Vu()||n))try{r(!0);const i=await new window.EyeDropper().open();i!=null&&i.sRGBHex&&t(i.sRGBHex.toUpperCase())}catch{}finally{r(!1)}},[e,n,t]);return Vu()?o.jsx(Le,{content:"拾取屏幕颜色",showArrow:!1,children:o.jsx("span",{children:o.jsx("button",{type:"button",className:St("ucp-eyedropper",{"ucp-eyedropper--picking":n}),onClick:s,disabled:e||n,children:o.jsx("svg",{className:"ucp-eyedropper__icon",viewBox:"0 0 24 24",fill:"currentColor",children:o.jsx("path",{d:"M20.71 5.63l-2.34-2.34a1 1 0 0 0-1.41 0l-3.12 3.12-1.42-1.42-1.41 1.42 1.41 1.41-8.42 8.42V20h3.75l8.42-8.42 1.41 1.41 1.42-1.41-1.42-1.42 3.12-3.12a1 1 0 0 0 .01-1.41zM6.92 18H5v-1.92l8.42-8.42 1.92 1.92L6.92 18z"})})})})}):null},So="aitu-recent-colors-unified",CI=10,PI={recentColors:[],addRecentColor:()=>{},clearRecentColors:()=>{}},xp=m.createContext(PI),EI=({children:t})=>{const[e,n]=m.useState([]),r=m.useRef(!1);m.useEffect(()=>{r.current||(r.current=!0,rt.get(So).then(l=>{if(l&&Array.isArray(l)){const d=new Set,c=l.filter(h=>{const u=h.toUpperCase().replace(/\s/g,"");return d.has(u)?!1:(d.add(u),!0)});n(c)}}).catch(l=>{console.warn("[RecentColorsProvider] Failed to load recent colors:",l)}))},[]);const s=m.useCallback(l=>{if(!l)return;const d=l.toUpperCase().replace(/\s/g,"");n(c=>{const h=c.filter(p=>p.toUpperCase().replace(/\s/g,"")!==d),u=[d,...h].slice(0,CI);return rt.set(So,u).catch(p=>{console.warn("[RecentColorsProvider] Failed to save recent colors:",p)}),u})},[]),a=m.useCallback(()=>{n([]),rt.remove(So).catch(l=>{console.warn("[RecentColorsProvider] Failed to clear recent colors:",l)})},[]),i={recentColors:e,addRecentColor:s,clearRecentColors:a};return o.jsx(xp.Provider,{value:i,children:t})},AI=()=>m.useContext(xp),jI=[{name:"无色",value:Ey},{name:"Basic Black",value:bf},{name:"White",value:Ay},{name:"Gray",value:"#808080"},{name:"Deep Blue",value:"#1E90FF"},{name:"Red",value:"#FF4500"},{name:"Green",value:"#2ECC71"},{name:"Yellow",value:"#FFD700"},{name:"Purple",value:"#8A2BE2"},{name:"Orange",value:"#FFA500"},{name:"Pastel Pink",value:"#FFB3BA"},{name:"Cyan",value:"#00CED1"},{name:"Brown",value:"#8B4513"},{name:"Forest Green",value:"#228B22"},{name:"Light Gray",value:"#D3D3D3"}],Ku="#000000",BO=({value:t,onChange:e,onOpacityChange:n,showAlpha:r=!0,showEyeDropper:s=!0,showPresets:a=!0,showRecentColors:i=!0,showHexInput:l=!0,presetColors:d,className:c,disabled:h=!1})=>{const{recentColors:u,addRecentColor:p}=AI(),[y]=m.useState(()=>[...u]),f=t&&Ar(t)?t:Ku,g=fs(f),w=To(f),[x,v]=m.useState(g),[_,T]=m.useState(w);m.useEffect(()=>{if(t&&Ar(t)){const P=fs(t),j=To(t);v(P),T(j)}},[t]);const b=m.useMemo(()=>Ha(x),[x]);m.useMemo(()=>_<100?Wu(b,_):b,[b,_]);const I=d||jI,A=Ie.useRef(w),k=m.useCallback((P,j,N=!1)=>{const B=j<100?Wu(P,j):P;e==null||e(B),(N||j!==A.current)&&(n==null||n(j),A.current=j)},[e,n]),U=m.useCallback((P,j)=>{const N={...x,s:P,v:j};v(N);const B=Ha(N);k(B,_)},[x,_,k]),D=m.useCallback(P=>{const j={...x,h:P};v(j);const N=Ha(j);k(N,_)},[x,_,k]),X=m.useCallback(P=>{T(P),k(b,P,!0)},[b,k]),L=m.useCallback(P=>{if(Ar(P)){const j=fs(P);v(j),k(P,_)}},[_,k]),O=m.useCallback(P=>{if(Ar(P)){const j=fs(P),N=To(P);v(j),T(N),k(Zs(P),N)}else e==null||e(P)},[k,e]),G=m.useCallback(P=>{O(P)},[O]),C=m.useCallback(P=>{if(Ar(P)){const j=fs(P);v(j),T(100),k(P,100),p(P)}},[k,p]);return m.useEffect(()=>{const P=setTimeout(()=>{b&&b!==Ku&&p(b)},500);return()=>clearTimeout(P)},[b,p]),o.jsxs("div",{className:St("unified-color-picker",c,{disabled:h}),children:[o.jsx(bI,{hue:x.h,saturation:x.s,value:x.v,onChange:U,disabled:h}),o.jsx(_I,{hue:x.h,onChange:D,disabled:h}),r&&o.jsx(TI,{alpha:_,color:b,onChange:X,disabled:h}),a&&o.jsx(SI,{colors:I,selectedColor:b,onSelect:O,disabled:h}),i&&y.length>0&&o.jsxs("div",{className:"unified-color-picker__recent",children:[o.jsx("div",{className:"unified-color-picker__recent-label",children:"最近使用"}),o.jsx("div",{className:"unified-color-picker__recent-colors",children:y.map((P,j)=>{const N=wp(P);return o.jsx(Le,{disabled:h,content:P,showArrow:!1,children:o.jsx("button",{className:St("unified-color-picker__recent-item",{"unified-color-picker__recent-item--selected":Zs(P).toUpperCase()===b.toUpperCase(),"unified-color-picker__recent-item--light":N}),style:{backgroundColor:P},onClick:()=>G(P),disabled:h})},`${P}-${j}`)})})]}),o.jsxs("div",{className:"unified-color-picker__footer",children:[s&&o.jsx(kI,{onPick:C,disabled:h}),l&&o.jsx(II,{value:b,alpha:_,onColorChange:L,onAlphaChange:X,showAlpha:r,disabled:h})]})]})},Pl=({children:t,board:e})=>{const n=e.appState,r=e.__setAppState||(()=>{console.warn("setAppState is not available in ToolProviderWrapper")}),s={appState:n,setAppState:r,board:e};return o.jsx(jy,{children:o.jsx(EI,{children:o.jsx(Oy,{children:o.jsx(My,{children:o.jsx(iT,{children:o.jsx(Dy.Provider,{value:s,children:t})})})})})})};function Zt(t){return t&&t.type==="tool"}function OI(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}const Xs={insertTool(t,e,n,r,s,a){(!r||r.length!==2)&&(console.error("Invalid position:",r),r=[0,0]),(!s||typeof s.width!="number"||typeof s.height!="number")&&(console.error("Invalid size:",s),s={width:400,height:300});const i={id:OI(),type:"tool",toolId:e,url:n,component:a==null?void 0:a.component,points:[r,[r[0]+s.width,r[1]+s.height]],angle:0,metadata:a};return ht.insertNode(t,i,[t.children.length]),i},resizeTool(t,e,n){const[r]=e.points,s={points:[r,[r[0]+n.width,r[1]+n.height]]},a=t.children.findIndex(i=>i.id===e.id);a>=0&&ht.setNode(t,s,[a])},moveTool(t,e,n){const[r,s]=e.points,a=Math.abs(s[0]-r[0]),i=Math.abs(s[1]-r[1]),l={points:[n,[n[0]+a,n[1]+i]]},d=t.children.findIndex(c=>c.id===e.id);d>=0&&ht.setNode(t,l,[d])},rotateTool(t,e,n){const r={angle:n},s=t.children.findIndex(a=>a.id===e.id);s>=0&&ht.setNode(t,r,[s])},removeTool(t,e){const n=t.children.findIndex(r=>r.id===e);n>=0&&ht.removeNode(t,[n])},updateToolUrl(t,e,n){const r=t.children.findIndex(s=>s.id===e);r>=0&&ht.setNode(t,{url:n},[r])},updateToolMetadata(t,e,n){const r=t.children.find(s=>s.id===e);if(r&&r.type==="tool"){const s={...r.metadata,...n},a=t.children.findIndex(i=>i.id===e);a>=0&&ht.setNode(t,{metadata:s},[a])}},getAllTools(t){return t.children.filter(e=>e.type==="tool")},getToolById(t,e){const n=t.children.find(r=>r.id===e);return n&&Zt(n)?n:null}};var tt=(t=>(t.AI_TOOLS="ai-tools",t.CONTENT_TOOLS="content-tools",t.UTILITIES="utilities",t.CUSTOM="custom",t))(tt||{});const Io=["allow-scripts","allow-same-origin","allow-popups","allow-forms","allow-top-navigation-by-user-activation"],MI=[{id:ti,name:"多图生成",description:"适合故事分镜、教程步骤、产品手册、营销图文等多页图片,一键规划提示词、批量出图并导出 ZIP/PPTX/PDF",icon:o.jsx(Af,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:ti,supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:720,defaultHeight:760},{id:"video-analyzer",name:"爆款视频生成",description:"AI 分析视频内容,提取镜头、脚本、风格等结构化数据",icon:o.jsx(jf,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:"video-analyzer",supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:680,defaultHeight:700},{id:"mv-creator",name:"爆款MV生成",description:"输入创意,AI 生成音乐和分镜视频,一站式 MV 创作",icon:o.jsx(Of,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:"mv-creator",supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:680,defaultHeight:700},{id:"batch-image",name:"批量出图工具",description:"Excel式批量AI图片生成,支持批量编辑、图片参考和历史追踪",icon:Ie.createElement(Mf),category:tt.AI_TOOLS,component:"batch-image",defaultWidth:1200,defaultHeight:800},{id:"music-analyzer",name:"爆款音乐生成",description:"分析音频、改写歌词,并一键送入 Suno 生成音乐",icon:o.jsx(Df,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:"music-analyzer",supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:520,defaultHeight:700},{id:"chat-mj",name:"Chat-MJ",description:"ChatGPT Web 聊天界面,支持 Midjourney 绘图代理;外部工具暂不支持知识库上下文",icon:Ie.createElement(Ny),category:tt.AI_TOOLS,url:'https://vercel.ddaiai.com/#/?settings={"key":"${apiKey}","url":"https://api.tu-zi.com"}',defaultWidth:1e3,defaultHeight:700,permissions:[...Io]},{id:ni,name:"模型测试",description:"批量比较图、文、视频、音频模型的速度与主观效果",icon:"🧪",category:tt.AI_TOOLS,component:ni,defaultWidth:1280,defaultHeight:860},{id:"prompt-history",name:"我的提示词",description:"按任务分类管理初始提示词、发送提示词和生成结果预览",icon:o.jsx(ec,{size:18,strokeWidth:1.75}),category:tt.CONTENT_TOOLS,component:"prompt-history",defaultWidth:1120,defaultHeight:680},{id:"banana-prompt",name:"香蕉提示词",description:"查看和复制优质 AI 提示词",icon:"🍌",category:tt.CONTENT_TOOLS,url:"https://www.aiwind.org",defaultWidth:800,defaultHeight:600,permissions:[...Io]},{id:"pose-library",name:"动作场景库",description:"专业人体姿态参考素材库,提供多角度动作姿势",icon:"🧘",category:tt.CONTENT_TOOLS,url:"https://www.posemaniacs.com/zh-Hans/poses",defaultWidth:900,defaultHeight:700,permissions:[...Io]},{id:"knowledge-base",name:"知识库",description:"个人知识管理工具,支持目录分类、标签管理和 Markdown 编辑",icon:Ie.createElement(Nf),category:tt.UTILITIES,component:"knowledge-base",defaultWidth:900,defaultHeight:700},{id:ri,name:"音乐播放器",description:"从素材库选择音频并后台播放,可与画布播放控件联动",icon:o.jsx(tc,{size:18,strokeWidth:1.75}),category:tt.UTILITIES,component:ri,defaultWidth:520,defaultHeight:640}],DI=new Map([["batch-image",()=>Xe(()=>Promise.resolve().then(()=>nC),void 0,import.meta.url).then(t=>({default:t.BatchImageToolComponent}))],["model-benchmark",()=>Xe(()=>Promise.resolve().then(()=>oC),void 0,import.meta.url).then(t=>({default:t.ModelBenchmarkToolComponent}))],["prompt-history",()=>Xe(()=>Promise.resolve().then(()=>hC),void 0,import.meta.url).then(t=>({default:t.PromptHistoryToolComponent}))],["knowledge-base",()=>Xe(()=>Promise.resolve().then(()=>gC),void 0,import.meta.url).then(t=>({default:t.KnowledgeBaseToolComponent}))],["music-player",()=>Xe(()=>Promise.resolve().then(()=>MC),void 0,import.meta.url).then(t=>({default:t.MusicPlayerToolComponent}))],["music-analyzer",()=>Xe(()=>Promise.resolve().then(()=>FC),void 0,import.meta.url).then(t=>({default:t.MusicAnalyzerToolComponent}))],["video-analyzer",()=>Xe(()=>Promise.resolve().then(()=>HC),void 0,import.meta.url).then(t=>({default:t.VideoAnalyzerToolComponent}))],["mv-creator",()=>Xe(()=>Promise.resolve().then(()=>qC),void 0,import.meta.url).then(t=>({default:t.MVCreatorToolComponent}))],["comic-creator",()=>Xe(()=>Promise.resolve().then(()=>QC),void 0,import.meta.url).then(t=>({default:t.ComicCreatorToolComponent}))]]);class NI{constructor(){this.builtInTools=MI,this.internalComponentLoaders=DI,this.internalComponents=new Map}getBuiltInTools(){return this.builtInTools.map(e=>({...e}))}getBuiltInToolIds(){return this.builtInTools.map(e=>e.id)}isBuiltInTool(e){return this.builtInTools.some(n=>n.id===e)}getManifestById(e){const n=this.builtInTools.find(r=>r.id===e);return n?{...n}:null}resolveInternalComponent(e){if(!e)return null;const n=this.internalComponents.get(e);if(n)return n;const r=this.internalComponentLoaders.get(e);if(!r)return null;const s=Ie.lazy(r);return this.internalComponents.set(e,s),s}}const Wt=new NI,zO=Object.freeze(Object.defineProperty({__proto__:null,toolRegistry:Wt},Symbol.toStringTag,{value:"Module"})),qu="aitu-pinned-tools",Yu="aitu-tool-pin-preferences",Zu="launcher:",Xu=36,Ju=28,RI=96,LI=72,Sr="prompt-history";function Ir(t,e){console.info(`[ToolWindowService] ${t}`,e||{})}function FI(t,e={}){const n=!Wt.isBuiltInTool(t.id);return{toolId:t.id,tool_id:t.id,toolName:t.name,tool_name:t.name,category:t.category,isCustomTool:n,is_custom_tool:n,...e}}function kr(t,e,n={}){_e.trackUIInteraction({area:"toolbox_window",action:t,control:"tool_window",source:"tool_window_service",metadata:FI(e,n)})}class Rr{constructor(){this.toolStates=new Map,this.pinnedToolIds=new Set,this.pinnedToolInfos=new Map,this.pinPreferences=new Map,this.toolStatesSubject=new si([]),this.openToolsSubject=new si([]),this.activationOrderCounter=0,this.instanceCounters=new Map,this.loadPinPreferences(),this.loadPinnedTools(),this.reconcilePinnedToolsWithPreferences(),setTimeout(()=>this.notify(),0)}static getInstance(){return Rr.instance||(Rr.instance=new Rr),Rr.instance}loadPinnedTools(){try{const e=localStorage.getItem(qu);if(!e)return;const n=JSON.parse(e);if(!Array.isArray(n)||n.length===0)return;if(typeof n[0]=="string"){n.forEach(r=>{this.pinnedToolIds.add(r)});return}n.forEach(r=>{this.pinnedToolIds.add(r.id),this.pinnedToolInfos.set(r.id,r)})}catch(e){console.warn("Failed to load pinned tools:",e)}}loadPinPreferences(){try{const e=localStorage.getItem(Yu);if(!e)return;const n=JSON.parse(e);if(!n||typeof n!="object")return;Object.entries(n).forEach(([r,s])=>{typeof s=="boolean"&&this.pinPreferences.set(r,s)})}catch(e){console.warn("Failed to load tool pin preferences:",e)}}savePinnedTools(){try{const e=[];this.pinnedToolIds.forEach(n=>{const r=this.pinnedToolInfos.get(n);r&&e.push(r)}),localStorage.setItem(qu,JSON.stringify(e))}catch(e){console.warn("Failed to save pinned tools:",e)}}savePinPreferences(){try{const e=Object.fromEntries(this.pinPreferences.entries());localStorage.setItem(Yu,JSON.stringify(e))}catch(e){console.warn("Failed to save tool pin preferences:",e)}}reconcilePinnedToolsWithPreferences(){this.pinPreferences.forEach((e,n)=>{e||(this.pinnedToolIds.delete(n),this.pinnedToolInfos.delete(n))})}observeToolStates(){return this.toolStatesSubject.asObservable()}observeOpenTools(){return this.openToolsSubject.asObservable()}getToolStates(){return Array.from(this.toolStates.values())}getToolbarTools(){const e=this.getToolStates().map((i,l)=>({state:i,originalIndex:l})),n=new Map,r=[];e.forEach(i=>{if(this.pinnedToolIds.has(i.state.toolId)){const l=n.get(i.state.toolId)||[];l.push(i.state),n.set(i.state.toolId,l);return}r.push(i)});const s=Array.from(this.pinnedToolIds).flatMap(i=>{const l=n.get(i);if(l&&l.length>0)return[...l].sort((c,h)=>c.instanceIndex!==h.instanceIndex?c.instanceIndex-h.instanceIndex:c.activationOrder-h.activationOrder);const d=this.createLauncherState(i);return d?[d]:[]}),a=r.sort((i,l)=>i.state.toolId===l.state.toolId?i.state.instanceIndex-l.state.instanceIndex:i.originalIndex-l.originalIndex).map(i=>i.state);return[...s,...a]}getToolInstances(e){return this.getToolStates().filter(n=>n.toolId===e).sort((n,r)=>n.instanceIndex!==r.instanceIndex?n.instanceIndex-r.instanceIndex:n.activationOrder-r.activationOrder)}getToolInstance(e){return this.toolStates.get(e)}getToolState(e){return this.resolveState(e)||this.createLauncherState(e)}getPrimaryToolState(e){const n=this.getToolInstances(e);if(n.length===0)return;const r=n.filter(s=>s.status==="open");return r.length>0?r.reduce((s,a)=>s.activationOrder>=a.activationOrder?s:a):n.reduce((s,a)=>s.activationOrder>=a.activationOrder?s:a)}canOpenMultiple(e){return typeof e.supportsMultipleWindows=="boolean"?e.supportsMultipleWindows:!!e.url}openTool(e,n){const r=this.resolveLaunchMode(e,n==null?void 0:n.launchMode);if(e.id===Sr&&Ir("openTool:start",{toolId:e.id,launchMode:r,isPinned:this.pinnedToolIds.has(e.id),componentProps:n==null?void 0:n.componentProps,instances:this.getToolInstances(e.id).map(a=>({instanceId:a.instanceId,status:a.status,isLauncher:a.isLauncher,activationOrder:a.activationOrder}))}),this.applyAutoPinBehavior(e,n),this.pinnedToolIds.has(e.id)&&(this.updatePinnedToolInfo(e),this.savePinnedTools()),r==="reuse"){const a=this.getPrimaryToolState(e.id);if(a)return e.id===Sr&&Ir("openTool:reuse",{instanceId:a.instanceId,status:a.status,isLauncher:a.isLauncher}),this.applyOpenToExistingState(a,e,n),kr("open_reuse",e,{launchMode:r,launch_mode:r,instanceId:a.instanceId,instance_id:a.instanceId,instanceIndex:a.instanceIndex,instance_index:a.instanceIndex,autoMaximize:!!(n!=null&&n.autoMaximize),auto_maximize:!!(n!=null&&n.autoMaximize),autoPin:!!(n!=null&&n.autoPin),auto_pin:!!(n!=null&&n.autoPin)}),this.notify(),e.id===Sr&&Ir("openTool:reused-after-notify",{instanceId:a.instanceId,status:a.status,isLauncher:a.isLauncher,componentProps:a.componentProps}),a.instanceId}const s=this.openNewToolInstance(e,n);if(e.id===Sr){const a=this.getToolInstance(s);Ir("openTool:new-instance",{instanceId:s,status:a==null?void 0:a.status,isLauncher:a==null?void 0:a.isLauncher,componentProps:a==null?void 0:a.componentProps})}return s}openNewToolInstance(e,n){this.applyAutoPinBehavior(e,n);const r=this.generateInstanceId(e.id),s=this.nextInstanceIndex(e.id),a={instanceId:r,toolId:e.id,instanceIndex:s,tool:e,status:"open",position:(n==null?void 0:n.position)||this.getCascadedPosition(e.id),activationOrder:this.nextActivationOrder(),isPinned:this.pinnedToolIds.has(e.id),isLauncher:!1,autoMaximize:n==null?void 0:n.autoMaximize,componentProps:n==null?void 0:n.componentProps};return a.isPinned&&(this.updatePinnedToolInfo(e),this.savePinnedTools()),this.toolStates.set(r,a),this.notify(),kr("open_new",e,{instanceId:r,instance_id:r,instanceIndex:s,instance_index:s,isPinned:a.isPinned,is_pinned:a.isPinned,autoMaximize:!!(n!=null&&n.autoMaximize),auto_maximize:!!(n!=null&&n.autoMaximize),autoPin:!!(n!=null&&n.autoPin),auto_pin:!!(n!=null&&n.autoPin)}),r}closeTool(e){const n=this.resolveState(e);n&&(kr("close",n.tool,{instanceId:n.instanceId,instance_id:n.instanceId,instanceIndex:n.instanceIndex,instance_index:n.instanceIndex,previousStatus:n.status,previous_status:n.status}),this.toolStates.delete(n.instanceId),this.getToolInstances(n.toolId).length===0&&this.instanceCounters.delete(n.toolId),this.notify())}minimizeTool(e,n,r){var a,i;const s=this.resolveState(e);s&&(kr("minimize",s.tool,{instanceId:s.instanceId,instance_id:s.instanceId,instanceIndex:s.instanceIndex,instance_index:s.instanceIndex,width:(r==null?void 0:r.width)??((a=s.size)==null?void 0:a.width),height:(r==null?void 0:r.height)??((i=s.size)==null?void 0:i.height)}),s.status="minimized",n&&(s.position=n),r&&(s.size=r),this.notify())}restoreTool(e){const n=this.resolveState(e);n&&(kr("restore",n.tool,{instanceId:n.instanceId,instance_id:n.instanceId,instanceIndex:n.instanceIndex,instance_index:n.instanceIndex,previousStatus:n.status,previous_status:n.status}),n.status="open",n.activationOrder=this.nextActivationOrder(),this.notify())}toggleToolVisibility(e){const n=this.resolveState(e);if(n)switch(n.status){case"open":this.minimizeTool(n.instanceId);break;case"minimized":this.restoreTool(n.instanceId);break}}setPinned(e,n){const r=this.getPrimaryToolState(e);this.setPinnedState(e,n,{tool:r==null?void 0:r.tool,persistPreference:!0}),r!=null&&r.tool&&kr(n?"pin":"unpin",r.tool,{isPinned:n,is_pinned:n}),this.getToolInstances(e).forEach(s=>{s.isPinned=n}),this.notify()}isPinned(e){return this.pinnedToolIds.has(e)}getPinnedToolIds(){return Array.from(this.pinnedToolIds)}updateToolPosition(e,n,r){const s=this.resolveState(e);s&&(s.position=n,r&&(s.size=r))}updateToolSize(e,n){const r=this.resolveState(e);r&&(r.size=n,this.notify())}markToolActivated(e){const n=this.resolveState(e);!n||n.status!=="open"||n.activationOrder>this.getTopOpenActivationOrder(n.instanceId)||(n.activationOrder=this.nextActivationOrder(),this.notify())}isToolOpen(e){return this.getToolInstances(e).some(n=>n.status==="open")}isToolMinimized(e){return this.getToolInstances(e).some(n=>n.status==="minimized")}resolveLaunchMode(e,n){return n&&n!=="auto"?n:this.canOpenMultiple(e)?"new":"reuse"}applyOpenToExistingState(e,n,r){const s=e.status,a=e.isLauncher;if(e.tool=n,e.toolId=n.id,e.isPinned=this.pinnedToolIds.has(n.id),e.isLauncher=!1,(r==null?void 0:r.componentProps)!==void 0&&(e.componentProps=r.componentProps),e.status!=="open"){e.status="open",e.activationOrder=this.nextActivationOrder(),r!=null&&r.autoMaximize&&(e.autoMaximize=!0),n.id===Sr&&Ir("applyOpenToExistingState:opened",{instanceId:e.instanceId,previousStatus:s,nextStatus:e.status,previousIsLauncher:a,nextIsLauncher:e.isLauncher,componentProps:e.componentProps});return}r!=null&&r.autoMaximize&&(e.autoMaximize=!0),e.activationOrder=this.nextActivationOrder(),n.id===Sr&&Ir("applyOpenToExistingState:already-open",{instanceId:e.instanceId,previousStatus:s,nextStatus:e.status,previousIsLauncher:a,nextIsLauncher:e.isLauncher,componentProps:e.componentProps})}resolveState(e){return this.toolStates.get(e)||this.getPrimaryToolState(e)}shouldAutoPinOnOpen(e,n){var s;if(n&&Object.prototype.hasOwnProperty.call(n,"autoPin"))return n.autoPin===!0;const r=this.pinPreferences.get(e.id);return typeof r=="boolean"?r:((s=e.defaultWindowBehavior)==null?void 0:s.autoPinOnOpen)===!0}applyAutoPinBehavior(e,n){if(!this.shouldAutoPinOnOpen(e,n))return;const r=n&&Object.prototype.hasOwnProperty.call(n,"autoPin");this.setPinnedState(e.id,!0,{tool:e,persistPreference:r})}updatePinnedToolInfo(e){this.pinnedToolInfos.set(e.id,{id:e.id,name:e.name,category:e.category})}setPinnedState(e,n,r){var s;if(n){this.pinnedToolIds.add(e);const a=(r==null?void 0:r.tool)||((s=this.getPrimaryToolState(e))==null?void 0:s.tool);a&&this.updatePinnedToolInfo(a)}else this.pinnedToolIds.delete(e),this.pinnedToolInfos.delete(e);r!=null&&r.persistPreference&&(this.pinPreferences.set(e,n),this.savePinPreferences()),this.savePinnedTools()}createLauncherState(e){if(!this.pinnedToolIds.has(e))return;const n=Wt.getManifestById(e);if(n)return{instanceId:`${Zu}${e}`,toolId:e,instanceIndex:0,tool:n,status:"closed",activationOrder:0,isPinned:!0,isLauncher:!0};const r=this.pinnedToolInfos.get(e);if(r)return{instanceId:`${Zu}${e}`,toolId:e,instanceIndex:0,tool:{id:r.id,name:r.name,category:r.category},status:"closed",activationOrder:0,isPinned:!0,isLauncher:!0}}nextActivationOrder(){return this.activationOrderCounter+=1,this.activationOrderCounter}nextInstanceIndex(e){const n=(this.instanceCounters.get(e)||0)+1;return this.instanceCounters.set(e,n),n}getTopOpenActivationOrder(e){let n=0;return this.toolStates.forEach((r,s)=>{s===e||r.status!=="open"||r.activationOrder>n&&(n=r.activationOrder)}),n}getCascadedPosition(e){var a,i;const n=this.getToolInstances(e);if(n.length===0)return;const r=n.reduce((l,d)=>l.activationOrder>=d.activationOrder?l:d),s=n.length;return{x:(((a=r.position)==null?void 0:a.x)??RI+s*Xu)+Xu,y:(((i=r.position)==null?void 0:i.y)??LI+s*Ju)+Ju}}generateInstanceId(e){return`${e}:${Ry()}`}notify(){const e=this.getToolStates();this.toolStatesSubject.next(e);const n=e.filter(r=>r.status==="open").map(r=>r.tool);this.openToolsSubject.next(n)}}const pt=Rr.getInstance(),$O=Object.freeze(Object.defineProperty({__proto__:null,toolWindowService:pt},Symbol.toStringTag,{value:"Module"})),bp={apiKey:()=>ln.get().apiKey||"",baseUrl:()=>ln.get().baseUrl||""};function kc(t){return/\$\{(\w+)\}/.test(t)}function BI(t){const e=t.matchAll(/\$\{(\w+)\}/g),n=[];for(const r of e)n.includes(r[1])||n.push(r[1]);return n}function _p(t){const e=BI(t),n=[];for(const r of e){const s=bp[r];s&&s()||n.push(r)}return n}function zI(t){return t.replace(/\$\{(\w+)\}/g,(e,n)=>{const r=bp[n];return r&&r()||e})}function El(t){if(!t||!kc(t))return{url:t,missingVariables:[]};const e=_p(t);return{url:zI(t),missingVariables:e}}function Qu(t){return t?_p(t).includes("apiKey"):!1}const _i=class _i{constructor(e){this.iframeCache=new Map,this.reactRoots=new Map,this.loadStates=new Map,this.loadTimeouts=new Map,this.canvasClickHandler=null,this.settingsChangeHandler=null,this.board=e,this.setupCanvasClickHandler(),this.setupSettingsChangeHandler()}scheduleRootUnmount(e){setTimeout(()=>{try{e.unmount()}catch{}},0)}setupSettingsChangeHandler(){this.settingsChangeHandler=()=>{this.refreshTemplateIframes()},window.addEventListener("gemini-settings-changed",this.settingsChangeHandler)}refreshTemplateIframes(){this.iframeCache.forEach((e,n)=>{const r=e.__templateUrl;if(r&&kc(r)){const{url:s}=El(r),a=new URL(s,window.location.origin);a.searchParams.set("toolId",n),e.src=a.toString()}})}setupCanvasClickHandler(){this.canvasClickHandler=e=>{const n=e.target;if(n.tagName==="IFRAME"||n.closest("iframe")||n.classList.contains("iframe-protection-overlay")||n.closest(".plait-tool-content")||n.closest(".plait-tool-react-content"))return;document.querySelectorAll(".iframe-protection-overlay").forEach(s=>{s.style.display="flex"})},document.addEventListener("click",this.canvasClickHandler)}canDraw(e){return!!(e&&e.type==="tool"&&(e.url||e.component))}draw(e){const n=document.createElementNS("http://www.w3.org/2000/svg","g");n.setAttribute("data-element-id",e.id),n.classList.add("plait-tool-element");const r=this.createForeignObject(e);return n.appendChild(r),this.applyRotation(n,e),n}updateImage(e,n,r){if(r.component){if(n.component!==r.component){this.recreateContent(e,r);return}this.renderReactContent(r)}else if(n.url!==r.url){this.recreateContent(e,r);return}const s=e.querySelector("foreignObject");if(s){const a=this.getRectangle(r);s.setAttribute("x",a.x.toString()),s.setAttribute("y",a.y.toString()),s.setAttribute("width",a.width.toString()),s.setAttribute("height",a.height.toString())}this.applyRotation(e,r)}recreateContent(e,n){const r=this.reactRoots.get(n.id);r&&(this.reactRoots.delete(n.id),this.scheduleRootUnmount(r)),e.innerHTML="";const s=this.createForeignObject(n);e.appendChild(s),this.applyRotation(e,n)}createForeignObject(e){const n=this.getRectangle(e),r=document.createElementNS("http://www.w3.org/2000/svg","foreignObject");r.setAttribute("x",n.x.toString()),r.setAttribute("y",n.y.toString()),r.setAttribute("width",n.width.toString()),r.setAttribute("height",n.height.toString()),r.classList.add("plait-tool-foreign-object"),r.style.outline="none",r.style.background="transparent";const s=document.createElement("div");s.className="plait-tool-container",s.style.cssText=`
|
|
72
|
+
`),{success:!0,data:{batchId:A,taskId:D.id,segmentCount:I.length,totalDuration:r,scripts:I},type:"video",taskId:D.id}}catch(b){return console.error("[LongVideo] Generation failed:",b),{success:!1,error:b.message||"长视频生成失败",type:"error"}}}const RO=Object.freeze(Object.defineProperty({__proto__:null,createLongVideoSegmentTask:lp,createLongVideoTask:AT},Symbol.toStringTag,{value:"Module"}));function Ys(t,e=400){if(!t)return{width:e,height:e};const n=t.match(/^(\d+)x(\d+)$/);if(!n)return{width:e,height:e};const r=parseInt(n[1],10),s=parseInt(n[2],10);return r<=0||s<=0?{width:e,height:e}:{width:e,height:Math.round(e*(s/r))}}async function jT(t,e,n,r,s=If(t)){if(r)return Qc(t,[{title:r,body:e}],n,s),{width:s,height:120};const a=kf(e);if(a&&a.length>0){Qc(t,a,n,s);const i=Math.min(a.length,3),l=Math.ceil(a.length/3);return{width:i*(s+20)-20,height:l*140-20}}return Pf.insertText(t,n,e),Cf(e)}function OT(t,e,n){const r=If(t);if(n)return{width:r,height:120};const s=kf(e);if(s&&s.length>0){const a=Math.min(s.length,3),i=Math.ceil(s.length/3);return{width:a*(r+20)-20,height:i*140-20}}return Cf(e)}function cp(t,e){var n,r;if(e.type==="text")return OT(t,e.content,e.label);if(e.type==="video")return e.dimensions||{width:Gt.MEDIA_DEFAULT_SIZE,height:Math.round(Gt.MEDIA_DEFAULT_SIZE*(9/16))};if(e.type==="audio")return Ql({...e.metadata,width:(n=e.dimensions)==null?void 0:n.width,height:(r=e.dimensions)==null?void 0:r.height});if(e.type==="svg"){const s=Tf(Sf(e.content)),a=Math.min(s.width,Gt.MEDIA_DEFAULT_SIZE),i=s.height/s.width;return{width:a,height:a*i}}return e.dimensions||{width:Gt.MEDIA_DEFAULT_SIZE,height:Gt.MEDIA_DEFAULT_SIZE}}async function MT(t,e,n,r){const s=r||{width:Gt.MEDIA_DEFAULT_SIZE,height:Gt.MEDIA_DEFAULT_SIZE};return vs("[CanvasInsertion][Service] image insert with size",{point:n,size:s,lockReferenceDimensions:!1,skipImageLoad:!0}),await Ty(t,e,n,!1,s,!0,!0,!1,!0),s}async function DT(t,e,n,r){if(r)return await ed(t,e,n,!1,r,!0,!0),r;const s={width:Gt.MEDIA_DEFAULT_SIZE,height:Math.round(Gt.MEDIA_DEFAULT_SIZE*(9/16))};return await ed(t,e,n,!1,s,!0,!0),s}async function NT(t,e,n,r,s){const a=Ql({...s,width:r==null?void 0:r.width,height:r==null?void 0:r.height});return await Ef(t,e,{...s,width:a.width,height:a.height},n,!1,!0),a}async function RT(t,e,n){const r=Sf(e),s=Tf(r),a=Math.min(s.width,Gt.MEDIA_DEFAULT_SIZE),i=s.height/s.width,l=a*i,c={url:Sy(r),width:a,height:l};return Pf.insertImage(t,c,n),{width:a,height:l}}async function LT(t,e,n){const r=t.children.length;let s;e.type==="text"?s=await jT(t,e.content,n,e.label):e.type==="image"?s=await MT(t,e.content,n,e.dimensions):e.type==="video"?s=await DT(t,e.content,n,e.dimensions):e.type==="audio"?s=await NT(t,e.content,n,e.dimensions,e.metadata):e.type==="svg"&&(s=await RT(t,e.content,n));const a=t.children[r];return{elementId:a==null?void 0:a.id,size:s||cp(t,e)}}async function An(t){const e=on();if(!e)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};const{items:n,verticalGap:r=Gt.DEFAULT_VERTICAL_GAP,horizontalGap:s=Gt.DEFAULT_HORIZONTAL_GAP}=t;if(!n||n.length===0)return{success:!1,error:"没有要插入的内容",type:"error"};try{if(!t.startPoint&&n.length===1){const u=n[0];if(u.type==="image"||u.type==="video"){const p=await py(e,u.content,u.type,u.dimensions);if(p)return{success:!0,data:{insertedCount:1,items:[{type:u.type,point:p.point,elementId:p.elementId,size:p.size}],firstElementId:p.elementId,firstElementPosition:p.point,firstElementSize:p.size},type:"text"}}}const a=gy(e);let i=t.startPoint;i||(i=yy(e,{verticalGap:r,logPrefix:"CanvasInsertion"})),i||(i=vy(e,{verticalGap:r,emptyPoint:Gt.DEFAULT_POINT})||Gt.DEFAULT_POINT),vs("[CanvasInsertion][Service] batch begin",{itemsCount:n.length,inputStartPoint:t.startPoint||null,resolvedStartPoint:i,viewport:a,verticalGap:r,horizontalGap:s});const l=wy(e,i,{horizontalGap:s,verticalGap:r});vs("[CanvasInsertion][Service] flow initialized",{startX:l.startX,startY:l.startY,rowRightLimit:l.rowRightLimit,zoom:a.zoom});const d=n.map(u=>cp(e,u)),c=xy(i,n,d,{canvasWidth:a.width,horizontalGap:s,verticalGap:r});l.bounds=c.bounds;const h=[];for(const[u,p]of n.entries()){const y=c.positions[u];vs("[CanvasInsertion][Service] item layout",{index:u,type:p.type,groupId:p.groupId||null,estimatedSize:d[u],point:y});const f=await LT(e,p,y);h.push({type:p.type,point:y,elementId:f.elementId,size:f.size})}if(h.length>0){const u=by(l)||[h[0].point[0],h[0].point[1]];vs("[CanvasInsertion][Service] batch complete",{insertedCount:h.length,centerPoint:u,bounds:l.bounds}),requestAnimationFrame(()=>{_y(e,u)})}return{success:!0,data:{insertedCount:h.length,items:h,firstElementId:h.length>0?h[0].elementId:void 0,firstElementPosition:h.length>0?h[0].point:void 0,firstElementSize:h.length>0?h[0].size:void 0},type:"text"}}catch(a){return console.error("[CanvasInsertion] Failed to insert content:",a),{success:!1,error:`插入失败: ${a.message||"未知错误"}`,type:"error"}}}async function Mu(t,e,n,r,s){return An({items:[{type:t,content:e,dimensions:r,metadata:s}],startPoint:n})}async function Du(t,e,n){const r=`img-group-${Date.now()}`;return An({items:t.map(s=>({type:"image",content:s,groupId:r,dimensions:n})),startPoint:e})}async function Nu(t,e,n){const r=[{type:"text",content:t,label:"Prompt"}];if(e.length===1)r.push({type:e[0].type,content:e[0].url,dimensions:e[0].dimensions,metadata:e[0].metadata});else{const s=`result-group-${Date.now()}`;e.forEach(a=>{r.push({type:a.type,content:a.url,groupId:s,dimensions:a.dimensions,metadata:a.metadata})})}return An({items:r,startPoint:n})}const bl="lasso",FT=3,BT="#6698FF",zT="rgba(102, 152, 255, 0.08)",$T=1.5,UT="6 4",HT="0.4s";function _l(t,e){if(t.length<=2)return t;let n=0,r=0;const s=t[0],a=t[t.length-1];for(let i=1;i<t.length-1;i++){const l=GT(t[i],s,a);l>n&&(n=l,r=i)}if(n>e){const i=_l(t.slice(0,r+1),e),l=_l(t.slice(r),e);return i.slice(0,-1).concat(l)}return[s,a]}function GT(t,e,n){const r=n[0]-e[0],s=n[1]-e[1],a=r*r+s*s;if(a===0)return Math.hypot(t[0]-e[0],t[1]-e[1]);const i=Math.max(0,Math.min(1,((t[0]-e[0])*r+(t[1]-e[1])*s)/a)),l=e[0]+i*r,d=e[1]+i*s;return Math.hypot(t[0]-l,t[1]-d)}function WT(t,e,n){let r=0;const s=n.length;for(let a=0;a<s;a++){const[i,l]=n[a],[d,c]=n[(a+1)%s];l<=e?c>e&&Nr(i,l,d,c,t,e)>0&&r++:c<=e&&Nr(i,l,d,c,t,e)<0&&r--}return r!==0}function Nr(t,e,n,r,s,a){return(n-t)*(a-e)-(s-t)*(r-e)}function VT(t,e,n,r){const s=Nr(t[0],t[1],e[0],e[1],n[0],n[1]),a=Nr(t[0],t[1],e[0],e[1],r[0],r[1]),i=Nr(n[0],n[1],r[0],r[1],t[0],t[1]),l=Nr(n[0],n[1],r[0],r[1],e[0],e[1]);return(s>0&&a<0||s<0&&a>0)&&(i>0&&l<0||i<0&&l>0)}function KT(t,e){const n=t.getRectangle(e);return n?[[n.x,n.y],[n.x+n.width,n.y],[n.x+n.width,n.y+n.height],[n.x,n.y+n.height]]:null}function qT(t){return[t.x+t.width/2,t.y+t.height/2]}function YT(t,e,n,r){const s=t.getRectangle(e);if(!s)return!1;const a={x:s.x,y:s.y,width:s.width,height:s.height};if(!Fe.isHit(r,a))return!1;const i=KT(t,e);if(!i)return!1;const l=qT(s),d=[...i,l];for(const h of d)if(WT(h[0],h[1],n))return!0;const c=[[i[0],i[1]],[i[1],i[2]],[i[2],i[3]],[i[3],i[0]]];for(let h=0;h<n.length;h++){const u=n[h],p=n[(h+1)%n.length];for(const[y,f]of c)if(VT(u,p,y,f))return!0}return!1}function ZT(t,e){if(t.length===0)return"";const n=[],r=td(e,t[0]);n.push(`M ${r[0]} ${r[1]}`);for(let s=1;s<t.length;s++){const a=td(e,t[s]);n.push(`L ${a[0]} ${a[1]}`)}return n.push("Z"),n.join(" ")}function XT(){const t="http://www.w3.org/2000/svg",e=document.createElementNS(t,"g");e.setAttribute("class","lasso-selection-overlay");const n=document.createElementNS(t,"path");n.setAttribute("fill",zT),n.setAttribute("stroke",BT),n.setAttribute("stroke-width",String($T)),n.setAttribute("stroke-dasharray",UT),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.style.pointerEvents="none";const r=document.createElementNS(t,"animate");return r.setAttribute("attributeName","stroke-dashoffset"),r.setAttribute("from","0"),r.setAttribute("to","20"),r.setAttribute("dur",HT),r.setAttribute("repeatCount","indefinite"),n.appendChild(r),e.appendChild(n),{g:e,path:n}}const LO=t=>{const{pointerDown:e,pointerMove:n,globalPointerUp:r}=t;let s=!1,a=[],i=null,l=null,d=!1,c=[];const h=()=>{i&&i.parentNode&&i.parentNode.removeChild(i),i=null,l=null,a=[],s=!1,d=!1,c=[]};return t.pointerDown=u=>{if(kt.isPointer(t,bl)&&Iy(u)&&!u.ctrlKey&&!u.metaKey){s=!0,d=u.shiftKey,d?c=Tt(t):(c=[],ns(t));const p=Jo(t,u.x,u.y);a=[Qo(t,p)];const f=kt.getActiveHost(t),g=XT();i=g.g,l=g.path,f.appendChild(i);return}e(u)},t.pointerMove=u=>{if(s&&l){const p=Jo(t,u.x,u.y),y=Qo(t,p);a.push(y);const f=ZT(a,t);l.setAttribute("d",f),Ru(t,a,c);return}n(u)},t.globalPointerUp=u=>{if(s){const p=t.viewport.zoom,y=_l(a,FT/p);y.length>=3&&Ru(t,y,c,!0),h();return}r(u)},t};function Ru(t,e,n,r=!1){if(e.length<3)return;const s=Fe.getRectangleByPoints(e),a=[];for(const l of t.children)YT(t,l,e,s)&&a.push(l);const i=n.length>0?JT(n,a):a;r&&i.length>0&&ht.addSelectionWithTemporaryElements(t,i)}function JT(t,e){const n=new Set(t.map(s=>s.id)),r=[...t];for(const s of e)n.has(s.id)||(r.push(s),n.add(s.id));return r}const QT=58,eS=80,Lu=50,xa=40;function tS(t){const e=document.querySelector(".unified-toolbar"),n=document.querySelector(".side-drawer--open.side-drawer--toolbar-right"),r=document.documentElement.classList.contains("aitu-toolbar-dock-right");let s=e?0:QT,a=0;if(e){const i=e.getBoundingClientRect();r?a=Math.max(a,t-i.left):s=Math.max(s,i.right)}if(n){const i=n.getBoundingClientRect();r?a=Math.max(a,t-i.left):s=Math.max(s,i.right)}return{left:Math.max(0,Math.round(s)),right:Math.max(0,Math.round(a))}}function dp(t,e){if(e.width<=0||e.height<=0)return!1;const n=kt.getBoardContainer(t),r=n.clientWidth,s=n.clientHeight,a=tS(r),i=a.left,l=document.querySelector(".chat-drawer--open"),d=Math.max(a.right,l?l.offsetWidth:0),c=r-i-d-xa*2,h=s-Lu-eS-xa*2;if(c<=0||h<=0)return!1;const u=Math.min(c/e.width,h/e.height,3),p=i+xa+c/2,y=Lu+xa+h/2,f=e.x+e.width/2,g=e.y+e.height/2,w=[f-p/u,g-y/u];return dt.updateViewport(t,w,u),!0}function nS(t){let e=1/0,n=1/0,r=-1/0,s=-1/0;for(const a of t.children){if(!at(a))continue;const i=Fe.getRectangleByPoints(a.points);i.width<=0||i.height<=0||(e=Math.min(e,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x+i.width),s=Math.max(s,i.y+i.height))}return!Number.isFinite(e)||!Number.isFinite(n)?null:{x:e,y:n,width:r-e,height:s-n}}function rS(t){const e=Tt(t);let n=null;for(const s of e)if(at(s)){n=s;break}if(!n){for(const s of t.children)if(at(s)){n=s;break}}if(!n)return!1;const r=Fe.getRectangleByPoints(n.points);return dp(t,r)}function FO(t){const e=nS(t);return e?dp(t,e):!1}function sS({items:t,getId:e,onReorder:n,enabled:r=!0}){const[s,a]=m.useState({draggingId:null,dragOverId:null,dragOverPosition:null}),i=m.useRef(null),l=m.useCallback((f,g,w)=>{if(!r)return;f.dataTransfer.effectAllowed="move",f.dataTransfer.setData("text/plain",g);const x=f.currentTarget;x&&f.dataTransfer.setDragImage(x,x.offsetWidth/2,x.offsetHeight/2),i.current=w,requestAnimationFrame(()=>{a({draggingId:g,dragOverId:null,dragOverPosition:null})})},[r]),d=m.useCallback(()=>{i.current=null,a({draggingId:null,dragOverId:null,dragOverPosition:null})},[]),c=m.useCallback((f,g,w)=>{if(!r||s.draggingId===null||s.draggingId===g)return;f.preventDefault(),f.dataTransfer.dropEffect="move";const x=f.currentTarget.getBoundingClientRect(),v=x.top+x.height/2,_=f.clientY<v?"before":"after";(s.dragOverId!==g||s.dragOverPosition!==_)&&a(T=>({...T,dragOverId:g,dragOverPosition:_}))},[r,s.draggingId,s.dragOverId,s.dragOverPosition]),h=m.useCallback((f,g)=>{!r||s.draggingId===null||s.draggingId===g||f.preventDefault()},[r,s.draggingId]),u=m.useCallback((f,g)=>{if(!r)return;const w=f.relatedTarget;f.currentTarget.contains(w)||s.dragOverId===g&&a(v=>({...v,dragOverId:null,dragOverPosition:null}))},[r,s.dragOverId]),p=m.useCallback((f,g,w)=>{if(!r||i.current===null)return;f.preventDefault();const x=i.current;let v=w;s.dragOverPosition==="after"&&(v=w+1),x<v&&(v-=1),x!==v&&n(x,v),d()},[r,s.dragOverPosition,n,d]),y=m.useCallback((f,g)=>({draggable:r,onDragStart:w=>l(w,f,g),onDragEnd:d,onDragOver:w=>c(w,f,g),onDragEnter:w=>h(w,f),onDragLeave:w=>u(w,f),onDrop:w=>p(w,f,g),"data-dragging":s.draggingId===f,"data-drag-over":s.dragOverId===f,"data-drag-position":s.dragOverId===f&&s.dragOverPosition||void 0}),[r,l,d,c,h,u,p,s.draggingId,s.dragOverId,s.dragOverPosition]);return{dragState:s,getDragProps:y,isDragging:s.draggingId!==null}}const bn={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_VERSION:"1.0.2"};function up(t){return"init"in t}function Tl(t){return!!t.write}function Fu(t){return"v"in t||"e"in t}function fi(t){if("e"in t)throw t.e;if((bn?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v}function mi(t){return typeof(t==null?void 0:t.then)=="function"}function hp(t,e,n){if(!n.p.has(t)){n.p.add(t);const r=()=>n.p.delete(t);e.then(r,r)}}function fp(t,e,n){var r;const s=new Set;for(const a of((r=n.get(t))==null?void 0:r.t)||[])s.add(a);for(const a of e.p)s.add(a);return s}const aS=(t,e,...n)=>e.read(...n),iS=(t,e,...n)=>e.write(...n),oS=(t,e)=>{var n;return(n=e.INTERNAL_onInit)==null?void 0:n.call(e,t)},lS=(t,e,n)=>{var r;return(r=e.onMount)==null?void 0:r.call(e,n)},cS=(t,e)=>{var n;const r=Ct(t),s=r[0],a=r[6],i=r[9];if((bn?"production":void 0)!=="production"&&!e)throw new Error("Atom is undefined or null");let l=s.get(e);return l||(l={d:new Map,p:new Set,n:0},s.set(e,l),(n=a.i)==null||n.call(a,e),i==null||i(t,e)),l},dS=t=>{const e=Ct(t),n=e[1],r=e[3],s=e[4],a=e[5],i=e[6],l=e[13],d=[],c=h=>{try{h()}catch(u){d.push(u)}};do{i.f&&c(i.f);const h=new Set,u=h.add.bind(h);r.forEach(p=>{var y;return(y=n.get(p))==null?void 0:y.l.forEach(u)}),r.clear(),a.forEach(u),a.clear(),s.forEach(u),s.clear(),h.forEach(c),r.size&&l(t)}while(r.size||a.size||s.size);if(d.length)throw new AggregateError(d)},uS=t=>{const e=Ct(t),n=e[1],r=e[2],s=e[3],a=e[11],i=e[14],l=e[17],d=[],c=new WeakSet,h=new WeakSet,u=Array.from(s);for(;u.length;){const p=u[u.length-1],y=a(t,p);if(h.has(p)){u.pop();continue}if(c.has(p)){if(r.get(p)===y.n)d.push([p,y]);else if((bn?"production":void 0)!=="production"&&r.has(p))throw new Error("[Bug] invalidated atom exists");h.add(p),u.pop();continue}c.add(p);for(const f of fp(p,y,n))c.has(f)||u.push(f)}for(let p=d.length-1;p>=0;--p){const[y,f]=d[p];let g=!1;for(const w of f.d.keys())if(w!==y&&s.has(w)){g=!0;break}g&&(i(t,y),l(t,y)),r.delete(y)}},Sl=new WeakSet,hS=(t,e)=>{var n,r;const s=Ct(t),a=s[1],i=s[2],l=s[3],d=s[6],c=s[7],h=s[11],u=s[12],p=s[13],y=s[14],f=s[16],g=s[17],w=s[20],x=s[26],v=h(t,e);if(Fu(v)){if(a.has(e)&&i.get(e)!==v.n)return v;let O=!1;for(const[G,C]of v.d)if(y(t,G).n!==C){O=!0;break}if(!O)return v}let _=!0;const T=new Set(v.d.keys()),b=new Map,I=()=>{for(const O of T)b.has(O)||v.d.delete(O)},A=()=>{if(a.has(e)){const O=!l.size;g(t,e),O&&(p(t),u(t))}},k=O=>{var G;if(O===e){const P=h(t,O);if(!Fu(P))if(up(O))w(t,O,O.init);else throw new Error("no atom init");return fi(P)}const C=y(t,O);try{return fi(C)}finally{b.set(O,C.n),v.d.set(O,C.n),mi(v.v)&&hp(e,v.v,C),a.has(e)&&((G=a.get(O))==null||G.t.add(e)),_||A()}};let U,D;const X={get signal(){return U||(U=new AbortController),U.signal},get setSelf(){return(bn?"production":void 0)!=="production"&&console.warn("[DEPRECATED] setSelf is deprecated and will be removed in v3."),(bn?"production":void 0)!=="production"&&!Tl(e)&&console.warn("setSelf function cannot be used with read-only atom"),!D&&Tl(e)&&(D=(...O)=>{if((bn?"production":void 0)!=="production"&&_&&console.warn("setSelf function cannot be called in sync"),!_)try{return f(t,e,...O)}finally{p(t),u(t)}}),D}},L=v.n;try{(bn?"production":void 0)!=="production"&&Sl.delete(t);const O=c(t,e,k,X);if((bn?"production":void 0)!=="production"&&Sl.has(t)&&console.warn("Detected store mutation during atom read. This is not supported."),w(t,e,O),mi(O)){x(t,O,()=>U==null?void 0:U.abort());const G=()=>{I(),A()};O.then(G,G)}else I();return(n=d.r)==null||n.call(d,e),v}catch(O){return delete v.v,v.e=O,++v.n,v}finally{_=!1,L!==v.n&&i.get(e)===L&&(i.set(e,v.n),l.add(e),(r=d.c)==null||r.call(d,e))}},fS=(t,e)=>{const n=Ct(t),r=n[1],s=n[2],a=n[11],i=[e];for(;i.length;){const l=i.pop(),d=a(t,l);for(const c of fp(l,d,r)){const h=a(t,c);s.get(c)!==h.n&&(s.set(c,h.n),i.push(c))}}},mS=(t,e,...n)=>{const r=Ct(t),s=r[3],a=r[6],i=r[8],l=r[11],d=r[12],c=r[13],h=r[14],u=r[15],p=r[16],y=r[17],f=r[20];let g=!0;const w=v=>fi(h(t,v)),x=(v,..._)=>{var T;const b=l(t,v);try{if(v===e){if(!up(v))throw new Error("atom not writable");(bn?"production":void 0)!=="production"&&Sl.add(t);const I=b.n,A=_[0];f(t,v,A),y(t,v),I!==b.n&&(s.add(v),u(t,v),(T=a.c)==null||T.call(a,v));return}else return p(t,v,..._)}finally{g||(c(t),d(t))}};try{return i(t,e,w,x,...n)}finally{g=!1}},pS=(t,e)=>{var n;const r=Ct(t),s=r[1],a=r[3],i=r[6],l=r[11],d=r[15],c=r[18],h=r[19],u=l(t,e),p=s.get(e);if(p){for(const[y,f]of u.d)if(!p.d.has(y)){const g=l(t,y);c(t,y).t.add(e),p.d.add(y),f!==g.n&&(a.add(y),d(t,y),(n=i.c)==null||n.call(i,y))}for(const y of p.d)if(!u.d.has(y)){p.d.delete(y);const f=h(t,y);f==null||f.t.delete(e)}}},gS=(t,e)=>{var n;const r=Ct(t),s=r[1],a=r[4],i=r[6],l=r[10],d=r[11],c=r[12],h=r[13],u=r[14],p=r[16],y=r[18],f=d(t,e);let g=s.get(e);if(!g){u(t,e);for(const w of f.d.keys())y(t,w).t.add(e);if(g={l:new Set,d:new Set(f.d.keys()),t:new Set},s.set(e,g),Tl(e)){const w=()=>{let x=!0;const v=(..._)=>{try{return p(t,e,..._)}finally{x||(h(t),c(t))}};try{const _=l(t,e,v);_&&(g.u=()=>{x=!0;try{_()}finally{x=!1}})}finally{x=!1}};a.add(w)}(n=i.m)==null||n.call(i,e)}return g},yS=(t,e)=>{var n,r;const s=Ct(t),a=s[1],i=s[5],l=s[6],d=s[11],c=s[19],h=d(t,e);let u=a.get(e);if(!u||u.l.size)return u;let p=!1;for(const y of u.t)if((n=a.get(y))!=null&&n.d.has(e)){p=!0;break}if(!p){u.u&&i.add(u.u),u=void 0,a.delete(e);for(const y of h.d.keys()){const f=c(t,y);f==null||f.t.delete(e)}(r=l.u)==null||r.call(l,e);return}return u},vS=(t,e,n)=>{const r=Ct(t),s=r[11],a=r[27],i=s(t,e),l="v"in i,d=i.v;if(mi(n))for(const c of i.d.keys())hp(e,n,s(t,c));i.v=n,delete i.e,(!l||!Object.is(d,i.v))&&(++i.n,mi(d)&&a(t,d))},wS=(t,e)=>{const n=Ct(t)[14];return fi(n(t,e))},xS=(t,e,...n)=>{const r=Ct(t),s=r[12],a=r[13],i=r[16];try{return i(t,e,...n)}finally{a(t),s(t)}},bS=(t,e,n)=>{const r=Ct(t),s=r[12],a=r[18],i=r[19],d=a(t,e).l;return d.add(n),s(t),()=>{d.delete(n),i(t,e),s(t)}},_S=(t,e,n)=>{const s=Ct(t)[25];let a=s.get(e);if(!a){a=new Set,s.set(e,a);const i=()=>s.delete(e);e.then(i,i)}a.add(n)},TS=(t,e)=>{const s=Ct(t)[25].get(e);s==null||s.forEach(a=>a())},mp=new WeakMap,Ct=t=>{const e=mp.get(t);if((bn?"production":void 0)!=="production"&&!e)throw new Error("Store must be created by buildStore to read its building blocks");return e};function SS(t){const e=Ct(t),n=e[24];return n?n(e):e}function IS(...t){const e={get(r){const s=Ct(e)[21];return s(e,r)},set(r,...s){const a=Ct(e)[22];return a(e,r,...s)},sub(r,s){const a=Ct(e)[23];return a(e,r,s)}},n=[new WeakMap,new WeakMap,new WeakMap,new Set,new Set,new Set,{},aS,iS,oS,lS,cS,dS,uS,hS,fS,mS,pS,gS,yS,vS,wS,xS,bS,void 0,new WeakMap,_S,TS].map((r,s)=>t[s]||r);return mp.set(e,Object.freeze(n)),e}const pp={};let kS=0;function Vt(t,e){const n=`atom${++kS}`,r={toString(){return(pp?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?r.read=t:(r.init=t,r.read=CS,r.write=PS),e&&(r.write=e),r}function CS(t){return t(this)}function PS(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}function ES(){return IS()}let hs;function gp(){return hs||(hs=ES(),(pp?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=hs),globalThis.__JOTAI_DEFAULT_STORE__!==hs&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),hs}const AS={},jS=m.createContext(void 0);function yp(t){return m.useContext(jS)||gp()}const Il=t=>typeof(t==null?void 0:t.then)=="function",kl=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},OS=Ie.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(kl(t),t)}),bo=new WeakMap,Bu=(t,e,n)=>{const s=SS(t)[26];let a=bo.get(e);return a||(a=new Promise((i,l)=>{let d=e;const c=p=>y=>{d===p&&i(y)},h=p=>y=>{d===p&&l(y)},u=()=>{try{const p=n();Il(p)?(bo.set(p,a),d=p,p.then(c(p),h(p)),s(t,p,u)):i(p)}catch(p){l(p)}};e.then(c(e),h(e)),s(t,e,u)}),bo.set(e,a)),a};function Hn(t,e){const{delay:n,unstable_promiseStatus:r=!Ie.use}={},s=yp(),[[a,i,l],d]=m.useReducer(h=>{const u=s.get(t);return Object.is(h[0],u)&&h[1]===s&&h[2]===t?h:[u,s,t]},void 0,()=>[s.get(t),s,t]);let c=a;if((i!==s||l!==t)&&(d(),c=s.get(t)),m.useEffect(()=>{const h=s.sub(t,()=>{if(r)try{const u=s.get(t);Il(u)&&kl(Bu(s,u,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(d,n);return}d()});return d(),h},[s,t,n,r]),m.useDebugValue(c),Il(c)){const h=Bu(s,c,()=>s.get(t));return r&&kl(h),OS(h)}return c}function br(t,e){const n=yp();return m.useCallback((...s)=>{if((AS?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...s)},[n,t])}const At=Vt([]),dn=Vt(!0),MS=Vt(t=>t(At).filter(e=>e.status===ve.PENDING||e.status===ve.PROCESSING)),DS=Vt(t=>t(At).filter(e=>e.status===ve.COMPLETED)),NS=Vt(t=>t(At).filter(e=>e.status===ve.FAILED)),RS=Vt(t=>t(At).filter(e=>e.status===ve.CANCELLED)),LS=Vt(t=>t(At).length),FS=Vt(t=>t(At).length),BS=Vt(null,(t,e,n)=>{try{const r=xe.createTask(n.params,n.type);return e(At,xe.getAllTasks()),e(dn,!1),r}catch{return null}}),zS=Vt(null,(t,e,n)=>{xe.cancelTask(n),e(At,xe.getAllTasks()),e(dn,!1)}),$S=Vt(null,(t,e,n)=>{xe.retryTask(n),e(At,xe.getAllTasks()),e(dn,!1)}),US=Vt(null,(t,e,n)=>{xe.deleteTask(n),e(At,xe.getAllTasks()),e(dn,!1)}),HS=Vt(null,(t,e)=>{xe.clearCompletedTasks(),e(At,xe.getAllTasks()),e(dn,!1)}),GS=Vt(null,(t,e)=>{xe.clearFailedTasks(),e(At,xe.getAllTasks()),e(dn,!1)});let zu=!1,$u=!1;const Nn=gp();function WS(t){const e=Nn.get(At);let n;switch(t.type){case"taskCreated":e.some(r=>r.id===t.task.id)?n=e.map(r=>r.id===t.task.id?t.task:r):n=[t.task,...e];break;case"taskDeleted":n=e.filter(r=>r.id!==t.task.id);break;default:e.some(r=>r.id===t.task.id)?n=e.map(r=>r.id===t.task.id?t.task:r):n=[t.task,...e];break}Nn.set(At,n),Nn.set(dn,!1)}function Uu(){const t=xe.getAllTasks();Nn.set(At,t),Nn.set(dn,!1)}async function VS(){if(await new Promise(r=>setTimeout(r,500)),xe.getAllTasks().length>0){Uu();return}if(!await ei.isAvailable()){Nn.set(dn,!1);return}const n=await ei.getAllTasks({limit:ky.MAX_RETAINED_TASKS});n.length>0&&xe.restoreTasks(n),Uu()}function KS(){if(zu)return;zu=!0;const t=xe.getAllTasks();Nn.set(At,t),Nn.set(dn,t.length===0),xe.observeTaskUpdates().subscribe(e=>{WS(e)}),t.length===0&&!$u&&($u=!0,VS().catch(()=>{Nn.set(dn,!1)}))}function vp(){m.useEffect(()=>{KS()},[]);const t=Hn(At),e=Hn(dn);return{tasks:t,isLoading:e}}function qS(){const t=br(BS),e=br(zS),n=br($S),r=br(US),s=br(HS),a=br(GS),i=m.useCallback((p,y)=>t({params:p,type:y}),[t]),l=m.useCallback(p=>e(p),[e]),d=m.useCallback(p=>n(p),[n]),c=m.useCallback(p=>r(p),[r]),h=m.useCallback(()=>s(),[s]),u=m.useCallback(()=>a(),[a]);return{createTask:i,cancelTask:l,retryTask:d,deleteTask:c,clearCompletedTasks:h,clearFailedTasks:u}}function YS(){const{tasks:t,isLoading:e}=vp(),n=Hn(MS),r=Hn(DS),s=Hn(NS),a=Hn(RS),i=Hn(LS),l=Hn(FS),d=!1,c=!1,{createTask:h,cancelTask:u,retryTask:p,deleteTask:y,clearCompletedTasks:f,clearFailedTasks:g}=qS(),w=m.useCallback(async()=>{},[]),x=m.useCallback(b=>xe.getTask(b),[]),v=m.useCallback(b=>{b.forEach(I=>{y(I)})},[y]),_=m.useCallback(b=>{b.forEach(I=>{p(I)})},[p]),T=m.useCallback(b=>{b.forEach(I=>{u(I)})},[u]);return{tasks:t,activeTasks:n,completedTasks:r,failedTasks:s,cancelledTasks:a,isLoading:e,isLoadingMore:d,hasMore:c,totalCount:i,loadedCount:l,loadMore:w,createTask:h,cancelTask:u,retryTask:p,deleteTask:y,clearCompleted:f,clearFailed:g,getTask:x,batchDeleteTasks:v,batchRetryTasks:_,batchCancelTasks:T}}function Xr(t,e){const n=new Set(e.filter(at).map(a=>a.id));if(n.size===0)return{primaryElements:e,relatedByFrameId:new Map};const r=e.filter(a=>{if(at(a))return!0;const i=Gn.getAssociatedFrameId(t,a);return!i||!n.has(i)}),s=new Map;for(const a of t.children){if(at(a))continue;const i=Gn.getAssociatedFrameId(t,a);if(!i||!n.has(i))continue;const l=s.get(i)??[];l.push(a),s.set(i,l)}return{primaryElements:r,relatedByFrameId:s}}function Hu(t,e,n,r){if(n===0&&r===0)return;const s=t.children.findIndex(l=>l.id===e.id);if(s<0)return;const a=t.children[s],i=[s];if(a.points&&Array.isArray(a.points)){const l=a.points.map(d=>[d[0]+n,d[1]+r]);ht.setNode(t,{points:l},i);return}typeof a.x=="number"&&typeof a.y=="number"&&ht.setNode(t,{x:a.x+n,y:a.y+r},i)}function Jr(t,e,n,r,s,a){if(a.has(e.id)||(Hu(t,e,n,r),a.add(e.id),!at(e)))return;const i=s.get(e.id)??[];for(const l of i)a.has(l.id)||(Hu(t,l,n,r),a.add(l.id))}const ZS=(t,e)=>Ln(t,[e],!1),_r=(t,e)=>{const n=Tt(t);if(n.length<2)return;const{primaryElements:r,relatedByFrameId:s}=Xr(t,n);if(r.length<2)return;const a=Ln(t,r,!1),i=new Set;r.forEach(l=>{const d=ZS(t,l);let c=0,h=0;switch(e){case"left":c=a.x-d.x;break;case"center":const u=a.x+a.width/2,p=d.x+d.width/2;c=u-p;break;case"right":const y=a.x+a.width,f=d.x+d.width;c=y-f;break;case"top":h=a.y-d.y;break;case"middle":const g=a.y+a.height/2,w=d.y+d.height/2;h=g-w;break;case"bottom":const x=a.y+a.height,v=d.y+d.height;h=x-v;break}c===0&&h===0||Jr(t,l,c,h,s,i)})},Tr={alignLeft:t=>{_r(t,"left")},alignCenter:t=>{_r(t,"center")},alignRight:t=>{_r(t,"right")},alignTop:t=>{_r(t,"top")},alignMiddle:t=>{_r(t,"middle")},alignBottom:t=>{_r(t,"bottom")}},Tc=(t,e)=>Ln(t,[e],!1),XS=t=>{const e=Tt(t);if(e.length<3)return;const{primaryElements:n,relatedByFrameId:r}=Xr(t,e);if(n.length<3)return;const s=n.map(f=>({element:f,rect:Tc(t,f)}));s.sort((f,g)=>f.rect.x-g.rect.x);const a=s[0].rect,i=s[s.length-1].rect,l=i.x+i.width-a.x,d=s.reduce((f,g)=>f+g.rect.width,0),c=l-d,h=s.length-1,u=h>0?c/h:0;let p=a.x+a.width+u;const y=new Set;for(let f=1;f<s.length-1;f++){const{element:g,rect:w}=s[f],x=p-w.x;Math.abs(x)>.01&&Jr(t,g,x,0,r,y),p+=w.width+u}},JS=t=>{const e=Tt(t);if(e.length<3)return;const{primaryElements:n,relatedByFrameId:r}=Xr(t,e);if(n.length<3)return;const s=n.map(f=>({element:f,rect:Tc(t,f)}));s.sort((f,g)=>f.rect.y-g.rect.y);const a=s[0].rect,i=s[s.length-1].rect,l=i.y+i.height-a.y,d=s.reduce((f,g)=>f+g.rect.height,0),c=l-d,h=s.length-1,u=h>0?c/h:0;let p=a.y+a.height+u;const y=new Set;for(let f=1;f<s.length-1;f++){const{element:g,rect:w}=s[f],x=p-w.y;Math.abs(x)>.01&&Jr(t,g,0,x,r,y),p+=w.height+u}},QS=t=>{const e=Tt(t);if(e.length<2)return;const{primaryElements:n,relatedByFrameId:r}=Xr(t,e);if(n.length<2)return;const s=Ln(t,n,!1),a=n.map(w=>({element:w,rect:Tc(t,w)})),i=a.reduce((w,x)=>w+x.rect.width,0)/a.length,l=a.reduce((w,x)=>w+x.rect.height,0)/a.length,d=a.length,c=s.width/s.height;let h;c>1.5?h=Math.ceil(Math.sqrt(d*c)):c<.67?h=Math.ceil(Math.sqrt(d/c)):h=Math.ceil(Math.sqrt(d)),h=Math.max(1,Math.min(h,d));const u=i*.2,p=l*.2;a.sort((w,x)=>{const v=Math.floor(w.rect.y/(l+p)),_=Math.floor(x.rect.y/(l+p));return v!==_?v-_:w.rect.x-x.rect.x});const y=s.x,f=s.y,g=new Set;a.forEach((w,x)=>{const v=x%h,_=Math.floor(x/h),T=y+v*(i+u),b=f+_*(l+p),I=T-w.rect.x,A=b-w.rect.y;(Math.abs(I)>.01||Math.abs(A)>.01)&&Jr(t,w.element,I,A,r,g)})},_o={distributeHorizontal:XS,distributeVertical:JS,autoArrange:QS},pi=1e3;function Gu(t){return t.map(e=>({X:Math.round(e[0]*pi),Y:Math.round(e[1]*pi)}))}function eI(t){return t.map(e=>[e.X/pi,e.Y/pi])}function tI(t,e,n,r,s,a=16){const i=Math.min(s,n/2,r/2);if(i<=0)return[[t,e],[t+n,e],[t+n,e+r],[t,e+r]];const l=[];for(let d=0;d<=a;d++){const c=-Math.PI/2+Math.PI/2*(d/a);l.push([t+n-i+i*Math.cos(c),e+i+i*Math.sin(c)])}for(let d=0;d<=a;d++){const c=0+Math.PI/2*(d/a);l.push([t+n-i+i*Math.cos(c),e+r-i+i*Math.sin(c)])}for(let d=0;d<=a;d++){const c=Math.PI/2+Math.PI/2*(d/a);l.push([t+i+i*Math.cos(c),e+r-i+i*Math.sin(c)])}for(let d=0;d<=a;d++){const c=Math.PI+Math.PI/2*(d/a);l.push([t+i+i*Math.cos(c),e+i+i*Math.sin(c)])}return l}function nI(t,e,n,r,s=32){const a=[],i=r/2;if(n<=r){const l=t+n/2,d=e+r/2,c=n/2,h=r/2,u=s*4;for(let p=0;p<u;p++){const y=2*Math.PI*p/u;a.push([l+c*Math.cos(y),d+h*Math.sin(y)])}return a}a.push([t+i,e]),a.push([t+n-i,e]);for(let l=0;l<=s;l++){const d=-Math.PI/2+Math.PI*(l/s);a.push([t+n-i+i*Math.cos(d),e+i+i*Math.sin(d)])}a.push([t+n-i,e+r]),a.push([t+i,e+r]);for(let l=0;l<=s;l++){const d=Math.PI/2+Math.PI*(l/s);a.push([t+i+i*Math.cos(d),e+i+i*Math.sin(d)])}return a}function rI(t,e=20){const n=t.points;if(!n||n.length<2)return[];const[r,s]=n,a=Math.min(r[0],s[0]),i=Math.min(r[1],s[1]),l=Math.abs(s[0]-r[0]),d=Math.abs(s[1]-r[1]),c=t.shape;if(c==="ellipse"||c==="circle"){const h=a+l/2,u=i+d/2,p=l/2,y=d/2,f=[],g=Math.PI*(3*(p+y)-Math.sqrt((3*p+y)*(p+3*y))),w=Math.max(180,Math.ceil(g/2));for(let x=0;x<w;x++){const v=2*Math.PI*x/w;f.push([h+p*Math.cos(v),u+y*Math.sin(v)])}return f}else if(c==="roundRectangle"){const h=Math.min(l,d)*.15;return tI(a,i,l,d,h,16)}else{if(c==="terminal"||c==="stadium"||c==="capsule")return nI(a,i,l,d,32);if(c==="triangle")return[[a+l/2,i],[a+l,i+d],[a,i+d]];if(c==="diamond"||c==="rhombus")return[[a+l/2,i],[a+l,i+d/2],[a+l/2,i+d],[a,i+d/2]];if(c==="pentagon"){const h=a+l/2,u=i+d/2,p=Math.min(l,d)/2,y=[];for(let f=0;f<5;f++){const g=2*Math.PI*f/5-Math.PI/2;y.push([h+p*Math.cos(g),u+p*Math.sin(g)])}return y}else if(c==="hexagon"){const h=a+l/2,u=i+d/2,p=Math.min(l,d)/2,y=[];for(let f=0;f<6;f++){const g=2*Math.PI*f/6;y.push([h+p*Math.cos(g),u+p*Math.sin(g)])}return y}else if(c==="octagon"){const h=a+l/2,u=i+d/2,p=Math.min(l,d)/2,y=[];for(let f=0;f<8;f++){const g=2*Math.PI*f/8-Math.PI/8;y.push([h+p*Math.cos(g),u+p*Math.sin(g)])}return y}else if(c==="star"){const h=a+l/2,u=i+d/2,p=Math.min(l,d)/2,y=p*.38,f=[];for(let g=0;g<10;g++){const w=Math.PI*g/5-Math.PI/2,x=g%2===0?p:y;f.push([h+x*Math.cos(w),u+x*Math.sin(w)])}return f}else if(c==="cross"){const h=Math.min(l,d)*.33,u=a+l/2,p=i+d/2;return[[u-h/2,i],[u+h/2,i],[u+h/2,p-h/2],[a+l,p-h/2],[a+l,p+h/2],[u+h/2,p+h/2],[u+h/2,i+d],[u-h/2,i+d],[u-h/2,p+h/2],[a,p+h/2],[a,p-h/2],[u-h/2,p-h/2]]}else if(c==="parallelogram"){const h=l*.2;return[[a+h,i],[a+l,i],[a+l-h,i+d],[a,i+d]]}else if(c==="trapezoid"){const h=l*.15;return[[a+h,i],[a+l-h,i],[a+l,i+d],[a,i+d]]}else return[[a,i],[a+l,i],[a+l,i+d],[a,i+d]]}}function sI(t,e,n=20){if(Jn.isPenPath(e)){if(!e.closed)return null;const r=ia(e);return ki(r,!0,n)}if(rs.isFreehand(e)){const r=e.points;if(!r||r.length<3)return null;const s=r[0],a=r[r.length-1];return Math.hypot(a[0]-s[0],a[1]-s[1])>10?null:r}return It.isDrawElement(e)&&It.isShapeElement(e)?It.isImage(e)||It.isText(e)?null:rI(e,n):null}function Cl(t,e){if(t.length<=2)return t;const n=t[0],r=t[t.length-1];let s=0,a=0;for(let i=1;i<t.length-1;i++){const l=aI(t[i],n,r);l>s&&(s=l,a=i)}if(s>e){const i=Cl(t.slice(0,a+1),e),l=Cl(t.slice(a),e);return[...i.slice(0,-1),...l]}return[n,r]}function aI(t,e,n){const r=n[0]-e[0],s=n[1]-e[1],a=r*r+s*s;if(a===0)return Math.hypot(t[0]-e[0],t[1]-e[1]);const i=Math.max(0,Math.min(1,((t[0]-e[0])*r+(t[1]-e[1])*s)/a)),l=e[0]+i*r,d=e[1]+i*s;return Math.hypot(t[0]-l,t[1]-d)}function iI(t,e){const n=t[0]*e[0]+t[1]*e[1],r=t[0]*e[1]-t[1]*e[0];return Math.atan2(r,n)}function oI(t,e,n){const r=[e[0]-t[0],e[1]-t[1]],s=[n[0]-e[0],n[1]-e[1]];return Math.abs(iI(r,s))}function lI(t,e,n,r=.25){const s=n[0]-t[0],a=n[1]-t[1],i=Math.hypot(s,a);if(i===0)return{handleIn:e,handleOut:e};const l=s/i,d=a/i,c=Math.hypot(e[0]-t[0],e[1]-t[1]),h=Math.hypot(n[0]-e[0],n[1]-e[1]),u=c*r,p=h*r,y=[e[0]-l*u,e[1]-d*u],f=[e[0]+l*p,e[1]+d*p];return{handleIn:y,handleOut:f}}function cI(t,e="#333333",n="#FFFFFF",r=2){if(t.length<3)throw new Error("Polygon must have at least 3 points");const s=Cl(t,.3);let a=1/0,i=1/0,l=-1/0,d=-1/0;for(const f of s)a=Math.min(a,f[0]),i=Math.min(i,f[1]),l=Math.max(l,f[0]),d=Math.max(d,f[1]);const c=[a,i],h=s.length,u=Math.PI*.4,p=s.map((f,g)=>{const w=[f[0]-c[0],f[1]-c[1]],x=s[(g-1+h)%h],v=s[(g+1)%h];if(oI(x,f,v)<u){const{handleIn:T,handleOut:b}=lI(x,f,v,.3);return{point:w,handleIn:[T[0]-c[0],T[1]-c[1]],handleOut:[b[0]-c[0],b[1]-c[1]],type:"smooth"}}return{point:w,type:"corner"}});return{id:Xl(),type:_f,shape:Qa.pen,points:[c,[l,d]],anchors:p,closed:!0,strokeColor:e,fill:n,strokeWidth:r}}async function as(){const t=await Xe(()=>import("./clipper-CpI1VJRD.js").then(e=>e.c),[],import.meta.url);return t.default||t}async function oa(t,e,n){const r=Tt(t);if(r.length<2){ee.warning(n==="zh"?"请选择至少2个闭合图形":"Please select at least 2 closed shapes");return}const s=[];for(const i of r){const l=sI(t,i);l&&l.length>=3&&s.push({element:i,polygon:l})}if(s.length<2){ee.warning(n==="zh"?"请确保选中的图形都是闭合的(如矩形、椭圆、闭合钢笔路径等)":"Please make sure all selected shapes are closed (rectangles, ellipses, closed pen paths, etc.)");return}const a=ee.loading(n==="zh"?"正在处理...":"Processing...",0);try{const i=await as(),l=new i.Clipper,d=[],c=Gu(s[0].polygon);l.AddPath(c,i.PolyType.ptSubject,!0);for(let v=1;v<s.length;v++){const _=Gu(s[v].polygon);l.AddPath(_,i.PolyType.ptClip,!0)}if(!l.Execute(e,d,i.PolyFillType.pftNonZero,i.PolyFillType.pftNonZero)||d.length===0){ee.close(a),ee.warning(n==="zh"?"布尔运算无结果(图形可能不相交)":"No result (shapes may not intersect)");return}const u=s[0].element;let p="#333333",y="#FFFFFF",f=2;(Jn.isPenPath(u)||It.isDrawElement(u))&&(p=u.strokeColor||p,y=u.fill||y,f=u.strokeWidth||f),Cy(t);const g=[];for(const v of d){const _=eI(v);if(_.length>=3){const T=cI(_,p,y,f);g.push(T)}}const w=[];for(const v of g){const _=t.children.length;ht.insertNode(t,v,[_]),w.push(v.id)}ns(t);for(const v of w){const _=t.children.find(T=>T.id===v);if(_)try{ta(t,_)}catch{}}ee.close(a);const x={[i.ClipType.ctUnion]:n==="zh"?"合并":"Union",[i.ClipType.ctDifference]:n==="zh"?"减去":"Subtract",[i.ClipType.ctIntersection]:n==="zh"?"相交":"Intersect",[i.ClipType.ctXor]:n==="zh"?"排除":"Exclude"};ee.success(n==="zh"?`${x[e]}完成,生成 ${g.length} 个图形`:`${x[e]} completed, ${g.length} shape(s) created`)}catch(i){ee.close(a),console.error("Boolean operation error:",i),ee.error(i.message||(n==="zh"?"操作失败":"Operation failed"))}}const dI=async(t,e="zh")=>{const n=await as();await oa(t,n.ClipType.ctUnion,e)},uI=async(t,e="zh")=>{const n=await as();await oa(t,n.ClipType.ctDifference,e)},hI=async(t,e="zh")=>{const n=await as();await oa(t,n.ClipType.ctIntersection,e)},fI=async(t,e="zh")=>{const n=await as();await oa(t,n.ClipType.ctXor,e)},mI=async(t,e="zh")=>{const n=await as();await oa(t,n.ClipType.ctUnion,e)},pI={union:dI,subtract:uI,intersect:hI,exclude:fI,flatten:mI};var zn=(t=>(t.LOAD_FAILED="load-failed",t.CORS_BLOCKED="cors-blocked",t.PERMISSION_DENIED="permission-denied",t.TIMEOUT="timeout",t))(zn||{});function gI(t){const{h:e,s:n,v:r}=t,s=e/360,a=n/100,i=r/100;let l=0,d=0,c=0;const h=Math.floor(s*6),u=s*6-h,p=i*(1-a),y=i*(1-u*a),f=i*(1-(1-u)*a);switch(h%6){case 0:l=i,d=f,c=p;break;case 1:l=y,d=i,c=p;break;case 2:l=p,d=i,c=f;break;case 3:l=p,d=y,c=i;break;case 4:l=f,d=p,c=i;break;case 5:l=i,d=p,c=y;break}return{r:Math.round(l*255),g:Math.round(d*255),b:Math.round(c*255)}}function yI(t){const{r:e,g:n,b:r}=t,s=e/255,a=n/255,i=r/255,l=Math.max(s,a,i),d=Math.min(s,a,i),c=l-d;let h=0,u=0;const p=l;return c!==0&&(u=c/l,l===s?h=(a-i)/c%6:l===a?h=(i-s)/c+2:h=(s-a)/c+4,h*=60,h<0&&(h+=360)),{h:Math.round(h),s:Math.round(u*100),v:Math.round(p*100)}}function vI(t,e=!1){const{r:n,g:r,b:s}=t,a=`#${Ts(n)}${Ts(r)}${Ts(s)}`;if(e&&"a"in t){const i=Math.round(t.a*255);return`${a}${Ts(i)}`}return a}function Sc(t){const e=t.replace(/^#/,"");let n=0,r=0,s=0,a=1;if(e.length===3)n=parseInt(e[0]+e[0],16),r=parseInt(e[1]+e[1],16),s=parseInt(e[2]+e[2],16);else if(e.length===6)n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),s=parseInt(e.substring(4,6),16);else if(e.length===8)n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),s=parseInt(e.substring(4,6),16),a=parseInt(e.substring(6,8),16)/255;else return null;return isNaN(n)||isNaN(r)||isNaN(s)||isNaN(a)?null:{r:n,g:r,b:s,a}}function Ha(t,e){const n=gI(t);return vI(n)}function fs(t){const e=Sc(t);return e?yI(e):{h:0,s:100,v:100}}function To(t){const e=Sc(t);return e?Math.round(e.a*100):100}function Wu(t,e){const n=t.replace(/^#/,"").substring(0,6),r=Ts(Math.round(e/100*255));return`#${n}${r}`}function Zs(t){const e=t.replace(/^#/,"");return e.length===8?`#${e.substring(0,6)}`:e.length===3?`#${e[0]}${e[0]}${e[1]}${e[1]}${e[2]}${e[2]}`:t.startsWith("#")?t:`#${t}`}function Ar(t){return/^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/.test(t)}function wI(t){const e=t.replace(/^#/,"").toUpperCase();return e.length===3?`#${e[0]}${e[0]}${e[1]}${e[1]}${e[2]}${e[2]}`:e.length===6||e.length===8?`#${e}`:t}function Ts(t){const e=Math.max(0,Math.min(255,Math.round(t))).toString(16);return e.length===1?"0"+e:e}function xI(t){const e=Sc(t);return e?.299*e.r+.587*e.g+.114*e.b:0}function wp(t){return xI(t)>186}function Ic({disabled:t=!1,onDrag:e}){const[n,r]=m.useState(!1),s=m.useRef(e);m.useEffect(()=>{s.current=e},[e]);const a=m.useCallback(d=>{t||(r(!0),s.current(d))},[t]),i=m.useCallback(d=>{t||(d.preventDefault(),a({clientX:d.clientX,clientY:d.clientY}))},[t,a]),l=m.useCallback(d=>{if(t)return;d.preventDefault();const c=d.touches[0];c&&a({clientX:c.clientX,clientY:c.clientY})},[t,a]);return m.useEffect(()=>{if(!n)return;const d=u=>{u.preventDefault(),s.current({clientX:u.clientX,clientY:u.clientY})},c=()=>{r(!1)},h=u=>{u.preventDefault();const p=u.touches[0];p&&s.current({clientX:p.clientX,clientY:p.clientY})};return document.addEventListener("mousemove",d),document.addEventListener("mouseup",c),document.addEventListener("touchmove",h,{passive:!1}),document.addEventListener("touchend",c),()=>{document.removeEventListener("mousemove",d),document.removeEventListener("mouseup",c),document.removeEventListener("touchmove",h),document.removeEventListener("touchend",c)}},[n]),{onMouseDown:i,onTouchStart:l}}const bI=({hue:t,saturation:e,value:n,onChange:r,disabled:s=!1})=>{const a=m.useRef(null),i={left:`${e}%`,top:`${100-n}%`},l=Ha({h:t,s:100,v:100}),d=m.useCallback((u,p)=>{if(!a.current)return;const y=a.current.getBoundingClientRect(),f=Math.max(0,Math.min(u-y.left,y.width)),g=Math.max(0,Math.min(p-y.top,y.height)),w=Math.round(f/y.width*100),x=Math.round(100-g/y.height*100);r(w,x)},[r]),c=m.useCallback(({clientX:u,clientY:p})=>{d(u,p)},[d]),h=Ic({disabled:s,onDrag:c});return o.jsxs("div",{ref:a,className:"ucp-hs-panel",style:{backgroundColor:l},onMouseDown:h.onMouseDown,onTouchStart:h.onTouchStart,children:[o.jsx("div",{className:"ucp-hs-panel__white-gradient"}),o.jsx("div",{className:"ucp-hs-panel__black-gradient"}),o.jsx("div",{className:"ucp-hs-panel__indicator",style:i})]})},_I=({hue:t,onChange:e,disabled:n=!1})=>{const r=m.useRef(null),s=t/360*100,a=m.useCallback(d=>{if(!r.current)return;const c=r.current.getBoundingClientRect(),h=Math.max(0,Math.min(d-c.left,c.width)),u=Math.round(h/c.width*360);e(u)},[e]),i=m.useCallback(({clientX:d})=>{a(d)},[a]),l=Ic({disabled:n,onDrag:i});return o.jsxs("div",{ref:r,className:"ucp-hue-slider",onMouseDown:l.onMouseDown,onTouchStart:l.onTouchStart,children:[o.jsx("div",{className:"ucp-hue-slider__track"}),o.jsx("div",{className:"ucp-hue-slider__indicator",style:{left:`${s}%`}})]})},TI=({alpha:t,color:e,onChange:n,disabled:r=!1})=>{const s=m.useRef(null),a=t,l={background:`linear-gradient(to right, transparent 0%, ${Zs(e)} 100%)`},d=m.useCallback(u=>{if(!s.current)return;const p=s.current.getBoundingClientRect(),y=Math.max(0,Math.min(u-p.left,p.width)),f=Math.round(y/p.width*100);n(f)},[n]),c=m.useCallback(({clientX:u})=>{d(u)},[d]),h=Ic({disabled:r,onDrag:c});return o.jsxs("div",{ref:s,className:"ucp-alpha-slider",onMouseDown:h.onMouseDown,onTouchStart:h.onTouchStart,children:[o.jsx("div",{className:"ucp-alpha-slider__checkerboard"}),o.jsx("div",{className:"ucp-alpha-slider__gradient",style:l}),o.jsx("div",{className:"ucp-alpha-slider__indicator",style:{left:`${a}%`}})]})},SI=({colors:t,selectedColor:e,onSelect:n,disabled:r=!1})=>{const s=e?Zs(e).toUpperCase():"";return o.jsx("div",{className:"ucp-preset-colors",children:t.map((a,i)=>{const l=Py(a.value),d=Zs(a.value).toUpperCase(),c=s===d,h=!l&&wp(a.value);return o.jsx(Le,{content:a.name,showArrow:!1,children:o.jsxs("button",{className:St("ucp-preset-colors__item",{"ucp-preset-colors__item--selected":c,"ucp-preset-colors__item--no-color":l,"ucp-preset-colors__item--light":h}),style:{backgroundColor:l?"transparent":a.value},disabled:r,onClick:()=>n(a.value),children:[l&&o.jsx("svg",{className:"ucp-preset-colors__no-color-icon",viewBox:"0 0 24 24",children:o.jsx("line",{x1:"4",y1:"4",x2:"20",y2:"20",stroke:"currentColor",strokeWidth:"2"})}),c&&!l&&o.jsx("svg",{className:"ucp-preset-colors__check-icon",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z",fill:"currentColor"})})]})},`${a.value}-${i}`)})})},II=({value:t,alpha:e,onColorChange:n,onAlphaChange:r,showAlpha:s=!0,disabled:a=!1})=>{const[i,l]=m.useState(t.replace("#","")),[d,c]=m.useState(String(e));m.useEffect(()=>{l(t.replace("#",""))},[t]),m.useEffect(()=>{c(String(e))},[e]);const h=m.useCallback(w=>{const v=w.target.value.replace("#","").toUpperCase().replace(/[^0-9A-F]/gi,"").substring(0,6);l(v)},[]),u=m.useCallback(()=>{const w=`#${i}`;if(Ar(w)){const x=wI(w);n(x),l(x.replace("#",""))}else l(t.replace("#",""))},[i,t,n]),p=m.useCallback(w=>{w.key==="Enter"&&u()},[u]),y=m.useCallback(w=>{const v=w.target.value.replace(/[^0-9]/g,"");c(v)},[]),f=m.useCallback(()=>{let w=parseInt(d,10);isNaN(w)?w=e:w=Math.max(0,Math.min(100,w)),c(String(w)),r(w)},[d,e,r]),g=m.useCallback(w=>{w.key==="Enter"&&f()},[f]);return o.jsxs("div",{className:"ucp-hex-input",children:[o.jsxs("div",{className:"ucp-hex-input__hex-group",children:[o.jsx("span",{className:"ucp-hex-input__prefix",children:"#"}),o.jsx("input",{type:"text",className:"ucp-hex-input__input",value:i,onChange:h,onBlur:u,onKeyDown:p,disabled:a,maxLength:6,placeholder:"000000"})]}),s&&o.jsxs("div",{className:"ucp-hex-input__alpha-group",children:[o.jsx("input",{type:"text",className:"ucp-hex-input__alpha-input",value:d,onChange:y,onBlur:f,onKeyDown:g,disabled:a,maxLength:3,placeholder:"100"}),o.jsx("span",{className:"ucp-hex-input__suffix",children:"%"})]})]})},Vu=()=>typeof window<"u"&&"EyeDropper"in window,kI=({onPick:t,disabled:e=!1})=>{const[n,r]=m.useState(!1),s=m.useCallback(async()=>{if(!(e||!Vu()||n))try{r(!0);const i=await new window.EyeDropper().open();i!=null&&i.sRGBHex&&t(i.sRGBHex.toUpperCase())}catch{}finally{r(!1)}},[e,n,t]);return Vu()?o.jsx(Le,{content:"拾取屏幕颜色",showArrow:!1,children:o.jsx("span",{children:o.jsx("button",{type:"button",className:St("ucp-eyedropper",{"ucp-eyedropper--picking":n}),onClick:s,disabled:e||n,children:o.jsx("svg",{className:"ucp-eyedropper__icon",viewBox:"0 0 24 24",fill:"currentColor",children:o.jsx("path",{d:"M20.71 5.63l-2.34-2.34a1 1 0 0 0-1.41 0l-3.12 3.12-1.42-1.42-1.41 1.42 1.41 1.41-8.42 8.42V20h3.75l8.42-8.42 1.41 1.41 1.42-1.41-1.42-1.42 3.12-3.12a1 1 0 0 0 .01-1.41zM6.92 18H5v-1.92l8.42-8.42 1.92 1.92L6.92 18z"})})})})}):null},So="aitu-recent-colors-unified",CI=10,PI={recentColors:[],addRecentColor:()=>{},clearRecentColors:()=>{}},xp=m.createContext(PI),EI=({children:t})=>{const[e,n]=m.useState([]),r=m.useRef(!1);m.useEffect(()=>{r.current||(r.current=!0,rt.get(So).then(l=>{if(l&&Array.isArray(l)){const d=new Set,c=l.filter(h=>{const u=h.toUpperCase().replace(/\s/g,"");return d.has(u)?!1:(d.add(u),!0)});n(c)}}).catch(l=>{console.warn("[RecentColorsProvider] Failed to load recent colors:",l)}))},[]);const s=m.useCallback(l=>{if(!l)return;const d=l.toUpperCase().replace(/\s/g,"");n(c=>{const h=c.filter(p=>p.toUpperCase().replace(/\s/g,"")!==d),u=[d,...h].slice(0,CI);return rt.set(So,u).catch(p=>{console.warn("[RecentColorsProvider] Failed to save recent colors:",p)}),u})},[]),a=m.useCallback(()=>{n([]),rt.remove(So).catch(l=>{console.warn("[RecentColorsProvider] Failed to clear recent colors:",l)})},[]),i={recentColors:e,addRecentColor:s,clearRecentColors:a};return o.jsx(xp.Provider,{value:i,children:t})},AI=()=>m.useContext(xp),jI=[{name:"无色",value:Ey},{name:"Basic Black",value:bf},{name:"White",value:Ay},{name:"Gray",value:"#808080"},{name:"Deep Blue",value:"#1E90FF"},{name:"Red",value:"#FF4500"},{name:"Green",value:"#2ECC71"},{name:"Yellow",value:"#FFD700"},{name:"Purple",value:"#8A2BE2"},{name:"Orange",value:"#FFA500"},{name:"Pastel Pink",value:"#FFB3BA"},{name:"Cyan",value:"#00CED1"},{name:"Brown",value:"#8B4513"},{name:"Forest Green",value:"#228B22"},{name:"Light Gray",value:"#D3D3D3"}],Ku="#000000",BO=({value:t,onChange:e,onOpacityChange:n,showAlpha:r=!0,showEyeDropper:s=!0,showPresets:a=!0,showRecentColors:i=!0,showHexInput:l=!0,presetColors:d,className:c,disabled:h=!1})=>{const{recentColors:u,addRecentColor:p}=AI(),[y]=m.useState(()=>[...u]),f=t&&Ar(t)?t:Ku,g=fs(f),w=To(f),[x,v]=m.useState(g),[_,T]=m.useState(w);m.useEffect(()=>{if(t&&Ar(t)){const P=fs(t),j=To(t);v(P),T(j)}},[t]);const b=m.useMemo(()=>Ha(x),[x]);m.useMemo(()=>_<100?Wu(b,_):b,[b,_]);const I=d||jI,A=Ie.useRef(w),k=m.useCallback((P,j,N=!1)=>{const B=j<100?Wu(P,j):P;e==null||e(B),(N||j!==A.current)&&(n==null||n(j),A.current=j)},[e,n]),U=m.useCallback((P,j)=>{const N={...x,s:P,v:j};v(N);const B=Ha(N);k(B,_)},[x,_,k]),D=m.useCallback(P=>{const j={...x,h:P};v(j);const N=Ha(j);k(N,_)},[x,_,k]),X=m.useCallback(P=>{T(P),k(b,P,!0)},[b,k]),L=m.useCallback(P=>{if(Ar(P)){const j=fs(P);v(j),k(P,_)}},[_,k]),O=m.useCallback(P=>{if(Ar(P)){const j=fs(P),N=To(P);v(j),T(N),k(Zs(P),N)}else e==null||e(P)},[k,e]),G=m.useCallback(P=>{O(P)},[O]),C=m.useCallback(P=>{if(Ar(P)){const j=fs(P);v(j),T(100),k(P,100),p(P)}},[k,p]);return m.useEffect(()=>{const P=setTimeout(()=>{b&&b!==Ku&&p(b)},500);return()=>clearTimeout(P)},[b,p]),o.jsxs("div",{className:St("unified-color-picker",c,{disabled:h}),children:[o.jsx(bI,{hue:x.h,saturation:x.s,value:x.v,onChange:U,disabled:h}),o.jsx(_I,{hue:x.h,onChange:D,disabled:h}),r&&o.jsx(TI,{alpha:_,color:b,onChange:X,disabled:h}),a&&o.jsx(SI,{colors:I,selectedColor:b,onSelect:O,disabled:h}),i&&y.length>0&&o.jsxs("div",{className:"unified-color-picker__recent",children:[o.jsx("div",{className:"unified-color-picker__recent-label",children:"最近使用"}),o.jsx("div",{className:"unified-color-picker__recent-colors",children:y.map((P,j)=>{const N=wp(P);return o.jsx(Le,{disabled:h,content:P,showArrow:!1,children:o.jsx("button",{className:St("unified-color-picker__recent-item",{"unified-color-picker__recent-item--selected":Zs(P).toUpperCase()===b.toUpperCase(),"unified-color-picker__recent-item--light":N}),style:{backgroundColor:P},onClick:()=>G(P),disabled:h})},`${P}-${j}`)})})]}),o.jsxs("div",{className:"unified-color-picker__footer",children:[s&&o.jsx(kI,{onPick:C,disabled:h}),l&&o.jsx(II,{value:b,alpha:_,onColorChange:L,onAlphaChange:X,showAlpha:r,disabled:h})]})]})},Pl=({children:t,board:e})=>{const n=e.appState,r=e.__setAppState||(()=>{console.warn("setAppState is not available in ToolProviderWrapper")}),s={appState:n,setAppState:r,board:e};return o.jsx(jy,{children:o.jsx(EI,{children:o.jsx(Oy,{children:o.jsx(My,{children:o.jsx(iT,{children:o.jsx(Dy.Provider,{value:s,children:t})})})})})})};function Zt(t){return t&&t.type==="tool"}function OI(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}const Xs={insertTool(t,e,n,r,s,a){(!r||r.length!==2)&&(console.error("Invalid position:",r),r=[0,0]),(!s||typeof s.width!="number"||typeof s.height!="number")&&(console.error("Invalid size:",s),s={width:400,height:300});const i={id:OI(),type:"tool",toolId:e,url:n,component:a==null?void 0:a.component,points:[r,[r[0]+s.width,r[1]+s.height]],angle:0,metadata:a};return ht.insertNode(t,i,[t.children.length]),i},resizeTool(t,e,n){const[r]=e.points,s={points:[r,[r[0]+n.width,r[1]+n.height]]},a=t.children.findIndex(i=>i.id===e.id);a>=0&&ht.setNode(t,s,[a])},moveTool(t,e,n){const[r,s]=e.points,a=Math.abs(s[0]-r[0]),i=Math.abs(s[1]-r[1]),l={points:[n,[n[0]+a,n[1]+i]]},d=t.children.findIndex(c=>c.id===e.id);d>=0&&ht.setNode(t,l,[d])},rotateTool(t,e,n){const r={angle:n},s=t.children.findIndex(a=>a.id===e.id);s>=0&&ht.setNode(t,r,[s])},removeTool(t,e){const n=t.children.findIndex(r=>r.id===e);n>=0&&ht.removeNode(t,[n])},updateToolUrl(t,e,n){const r=t.children.findIndex(s=>s.id===e);r>=0&&ht.setNode(t,{url:n},[r])},updateToolMetadata(t,e,n){const r=t.children.find(s=>s.id===e);if(r&&r.type==="tool"){const s={...r.metadata,...n},a=t.children.findIndex(i=>i.id===e);a>=0&&ht.setNode(t,{metadata:s},[a])}},getAllTools(t){return t.children.filter(e=>e.type==="tool")},getToolById(t,e){const n=t.children.find(r=>r.id===e);return n&&Zt(n)?n:null}};var tt=(t=>(t.AI_TOOLS="ai-tools",t.CONTENT_TOOLS="content-tools",t.UTILITIES="utilities",t.CUSTOM="custom",t))(tt||{});const Io=["allow-scripts","allow-same-origin","allow-popups","allow-forms","allow-top-navigation-by-user-activation"],MI=[{id:ti,name:"多图生成",description:"适合故事分镜、教程步骤、产品手册、营销图文等多页图片,一键规划提示词、批量出图并导出 ZIP/PPTX/PDF",icon:o.jsx(Af,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:ti,supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:720,defaultHeight:760},{id:"video-analyzer",name:"爆款视频生成",description:"AI 分析视频内容,提取镜头、脚本、风格等结构化数据",icon:o.jsx(jf,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:"video-analyzer",supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:680,defaultHeight:700},{id:"mv-creator",name:"爆款MV生成",description:"输入创意,AI 生成音乐和分镜视频,一站式 MV 创作",icon:o.jsx(Of,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:"mv-creator",supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:680,defaultHeight:700},{id:"batch-image",name:"批量出图工具",description:"Excel式批量AI图片生成,支持批量编辑、图片参考和历史追踪",icon:Ie.createElement(Mf),category:tt.AI_TOOLS,component:"batch-image",defaultWidth:1200,defaultHeight:800},{id:"music-analyzer",name:"爆款音乐生成",description:"分析音频、改写歌词,并一键送入 Suno 生成音乐",icon:o.jsx(Df,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:"music-analyzer",supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:520,defaultHeight:700},{id:"chat-mj",name:"Chat-MJ",description:"ChatGPT Web 聊天界面,支持 Midjourney 绘图代理;外部工具暂不支持知识库上下文",icon:Ie.createElement(Ny),category:tt.AI_TOOLS,url:'https://vercel.ddaiai.com/#/?settings={"key":"${apiKey}","url":"https://api.tu-zi.com"}',defaultWidth:1e3,defaultHeight:700,permissions:[...Io]},{id:ni,name:"模型测试",description:"批量比较图、文、视频、音频模型的速度与主观效果",icon:"🧪",category:tt.AI_TOOLS,component:ni,defaultWidth:1280,defaultHeight:860},{id:"prompt-history",name:"我的提示词",description:"按任务分类管理初始提示词、发送提示词和生成结果预览",icon:o.jsx(ec,{size:18,strokeWidth:1.75}),category:tt.CONTENT_TOOLS,component:"prompt-history",defaultWidth:1120,defaultHeight:680},{id:"banana-prompt",name:"香蕉提示词",description:"查看和复制优质 AI 提示词",icon:"🍌",category:tt.CONTENT_TOOLS,url:"https://www.aiwind.org",defaultWidth:800,defaultHeight:600,permissions:[...Io]},{id:"pose-library",name:"动作场景库",description:"专业人体姿态参考素材库,提供多角度动作姿势",icon:"🧘",category:tt.CONTENT_TOOLS,url:"https://www.posemaniacs.com/zh-Hans/poses",defaultWidth:900,defaultHeight:700,permissions:[...Io]},{id:"knowledge-base",name:"知识库",description:"个人知识管理工具,支持目录分类、标签管理和 Markdown 编辑",icon:Ie.createElement(Nf),category:tt.UTILITIES,component:"knowledge-base",defaultWidth:900,defaultHeight:700},{id:ri,name:"音乐播放器",description:"从素材库选择音频并后台播放,可与画布播放控件联动",icon:o.jsx(tc,{size:18,strokeWidth:1.75}),category:tt.UTILITIES,component:ri,defaultWidth:520,defaultHeight:640}],DI=new Map([["batch-image",()=>Xe(()=>Promise.resolve().then(()=>nC),void 0,import.meta.url).then(t=>({default:t.BatchImageToolComponent}))],["model-benchmark",()=>Xe(()=>Promise.resolve().then(()=>oC),void 0,import.meta.url).then(t=>({default:t.ModelBenchmarkToolComponent}))],["prompt-history",()=>Xe(()=>Promise.resolve().then(()=>hC),void 0,import.meta.url).then(t=>({default:t.PromptHistoryToolComponent}))],["knowledge-base",()=>Xe(()=>Promise.resolve().then(()=>gC),void 0,import.meta.url).then(t=>({default:t.KnowledgeBaseToolComponent}))],["music-player",()=>Xe(()=>Promise.resolve().then(()=>MC),void 0,import.meta.url).then(t=>({default:t.MusicPlayerToolComponent}))],["music-analyzer",()=>Xe(()=>Promise.resolve().then(()=>FC),void 0,import.meta.url).then(t=>({default:t.MusicAnalyzerToolComponent}))],["video-analyzer",()=>Xe(()=>Promise.resolve().then(()=>HC),void 0,import.meta.url).then(t=>({default:t.VideoAnalyzerToolComponent}))],["mv-creator",()=>Xe(()=>Promise.resolve().then(()=>qC),void 0,import.meta.url).then(t=>({default:t.MVCreatorToolComponent}))],["comic-creator",()=>Xe(()=>Promise.resolve().then(()=>QC),void 0,import.meta.url).then(t=>({default:t.ComicCreatorToolComponent}))]]);class NI{constructor(){this.builtInTools=MI,this.internalComponentLoaders=DI,this.internalComponents=new Map}getBuiltInTools(){return this.builtInTools.map(e=>({...e}))}getBuiltInToolIds(){return this.builtInTools.map(e=>e.id)}isBuiltInTool(e){return this.builtInTools.some(n=>n.id===e)}getManifestById(e){const n=this.builtInTools.find(r=>r.id===e);return n?{...n}:null}resolveInternalComponent(e){if(!e)return null;const n=this.internalComponents.get(e);if(n)return n;const r=this.internalComponentLoaders.get(e);if(!r)return null;const s=Ie.lazy(r);return this.internalComponents.set(e,s),s}}const Wt=new NI,zO=Object.freeze(Object.defineProperty({__proto__:null,toolRegistry:Wt},Symbol.toStringTag,{value:"Module"})),qu="aitu-pinned-tools",Yu="aitu-tool-pin-preferences",Zu="launcher:",Xu=36,Ju=28,RI=96,LI=72,Sr="prompt-history";function Ir(t,e){console.info(`[ToolWindowService] ${t}`,e||{})}function FI(t,e={}){const n=!Wt.isBuiltInTool(t.id);return{toolId:t.id,tool_id:t.id,toolName:t.name,tool_name:t.name,category:t.category,isCustomTool:n,is_custom_tool:n,...e}}function kr(t,e,n={}){_e.trackUIInteraction({area:"toolbox_window",action:t,control:"tool_window",source:"tool_window_service",metadata:FI(e,n)})}class Rr{constructor(){this.toolStates=new Map,this.pinnedToolIds=new Set,this.pinnedToolInfos=new Map,this.pinPreferences=new Map,this.toolStatesSubject=new si([]),this.openToolsSubject=new si([]),this.activationOrderCounter=0,this.instanceCounters=new Map,this.loadPinPreferences(),this.loadPinnedTools(),this.reconcilePinnedToolsWithPreferences(),setTimeout(()=>this.notify(),0)}static getInstance(){return Rr.instance||(Rr.instance=new Rr),Rr.instance}loadPinnedTools(){try{const e=localStorage.getItem(qu);if(!e)return;const n=JSON.parse(e);if(!Array.isArray(n)||n.length===0)return;if(typeof n[0]=="string"){n.forEach(r=>{this.pinnedToolIds.add(r)});return}n.forEach(r=>{this.pinnedToolIds.add(r.id),this.pinnedToolInfos.set(r.id,r)})}catch(e){console.warn("Failed to load pinned tools:",e)}}loadPinPreferences(){try{const e=localStorage.getItem(Yu);if(!e)return;const n=JSON.parse(e);if(!n||typeof n!="object")return;Object.entries(n).forEach(([r,s])=>{typeof s=="boolean"&&this.pinPreferences.set(r,s)})}catch(e){console.warn("Failed to load tool pin preferences:",e)}}savePinnedTools(){try{const e=[];this.pinnedToolIds.forEach(n=>{const r=this.pinnedToolInfos.get(n);r&&e.push(r)}),localStorage.setItem(qu,JSON.stringify(e))}catch(e){console.warn("Failed to save pinned tools:",e)}}savePinPreferences(){try{const e=Object.fromEntries(this.pinPreferences.entries());localStorage.setItem(Yu,JSON.stringify(e))}catch(e){console.warn("Failed to save tool pin preferences:",e)}}reconcilePinnedToolsWithPreferences(){this.pinPreferences.forEach((e,n)=>{e||(this.pinnedToolIds.delete(n),this.pinnedToolInfos.delete(n))})}observeToolStates(){return this.toolStatesSubject.asObservable()}observeOpenTools(){return this.openToolsSubject.asObservable()}getToolStates(){return Array.from(this.toolStates.values())}getToolbarTools(){const e=this.getToolStates().map((i,l)=>({state:i,originalIndex:l})),n=new Map,r=[];e.forEach(i=>{if(this.pinnedToolIds.has(i.state.toolId)){const l=n.get(i.state.toolId)||[];l.push(i.state),n.set(i.state.toolId,l);return}r.push(i)});const s=Array.from(this.pinnedToolIds).flatMap(i=>{const l=n.get(i);if(l&&l.length>0)return[...l].sort((c,h)=>c.instanceIndex!==h.instanceIndex?c.instanceIndex-h.instanceIndex:c.activationOrder-h.activationOrder);const d=this.createLauncherState(i);return d?[d]:[]}),a=r.sort((i,l)=>i.state.toolId===l.state.toolId?i.state.instanceIndex-l.state.instanceIndex:i.originalIndex-l.originalIndex).map(i=>i.state);return[...s,...a]}getToolInstances(e){return this.getToolStates().filter(n=>n.toolId===e).sort((n,r)=>n.instanceIndex!==r.instanceIndex?n.instanceIndex-r.instanceIndex:n.activationOrder-r.activationOrder)}getToolInstance(e){return this.toolStates.get(e)}getToolState(e){return this.resolveState(e)||this.createLauncherState(e)}getPrimaryToolState(e){const n=this.getToolInstances(e);if(n.length===0)return;const r=n.filter(s=>s.status==="open");return r.length>0?r.reduce((s,a)=>s.activationOrder>=a.activationOrder?s:a):n.reduce((s,a)=>s.activationOrder>=a.activationOrder?s:a)}canOpenMultiple(e){return typeof e.supportsMultipleWindows=="boolean"?e.supportsMultipleWindows:!!e.url}openTool(e,n){const r=this.resolveLaunchMode(e,n==null?void 0:n.launchMode);if(e.id===Sr&&Ir("openTool:start",{toolId:e.id,launchMode:r,isPinned:this.pinnedToolIds.has(e.id),componentProps:n==null?void 0:n.componentProps,instances:this.getToolInstances(e.id).map(a=>({instanceId:a.instanceId,status:a.status,isLauncher:a.isLauncher,activationOrder:a.activationOrder}))}),this.applyAutoPinBehavior(e,n),this.pinnedToolIds.has(e.id)&&(this.updatePinnedToolInfo(e),this.savePinnedTools()),r==="reuse"){const a=this.getPrimaryToolState(e.id);if(a)return e.id===Sr&&Ir("openTool:reuse",{instanceId:a.instanceId,status:a.status,isLauncher:a.isLauncher}),this.applyOpenToExistingState(a,e,n),kr("open_reuse",e,{launchMode:r,launch_mode:r,instanceId:a.instanceId,instance_id:a.instanceId,instanceIndex:a.instanceIndex,instance_index:a.instanceIndex,autoMaximize:!!(n!=null&&n.autoMaximize),auto_maximize:!!(n!=null&&n.autoMaximize),autoPin:!!(n!=null&&n.autoPin),auto_pin:!!(n!=null&&n.autoPin)}),this.notify(),e.id===Sr&&Ir("openTool:reused-after-notify",{instanceId:a.instanceId,status:a.status,isLauncher:a.isLauncher,componentProps:a.componentProps}),a.instanceId}const s=this.openNewToolInstance(e,n);if(e.id===Sr){const a=this.getToolInstance(s);Ir("openTool:new-instance",{instanceId:s,status:a==null?void 0:a.status,isLauncher:a==null?void 0:a.isLauncher,componentProps:a==null?void 0:a.componentProps})}return s}openNewToolInstance(e,n){this.applyAutoPinBehavior(e,n);const r=this.generateInstanceId(e.id),s=this.nextInstanceIndex(e.id),a={instanceId:r,toolId:e.id,instanceIndex:s,tool:e,status:"open",position:(n==null?void 0:n.position)||this.getCascadedPosition(e.id),activationOrder:this.nextActivationOrder(),isPinned:this.pinnedToolIds.has(e.id),isLauncher:!1,autoMaximize:n==null?void 0:n.autoMaximize,componentProps:n==null?void 0:n.componentProps};return a.isPinned&&(this.updatePinnedToolInfo(e),this.savePinnedTools()),this.toolStates.set(r,a),this.notify(),kr("open_new",e,{instanceId:r,instance_id:r,instanceIndex:s,instance_index:s,isPinned:a.isPinned,is_pinned:a.isPinned,autoMaximize:!!(n!=null&&n.autoMaximize),auto_maximize:!!(n!=null&&n.autoMaximize),autoPin:!!(n!=null&&n.autoPin),auto_pin:!!(n!=null&&n.autoPin)}),r}closeTool(e){const n=this.resolveState(e);n&&(kr("close",n.tool,{instanceId:n.instanceId,instance_id:n.instanceId,instanceIndex:n.instanceIndex,instance_index:n.instanceIndex,previousStatus:n.status,previous_status:n.status}),this.toolStates.delete(n.instanceId),this.getToolInstances(n.toolId).length===0&&this.instanceCounters.delete(n.toolId),this.notify())}minimizeTool(e,n,r){var a,i;const s=this.resolveState(e);s&&(kr("minimize",s.tool,{instanceId:s.instanceId,instance_id:s.instanceId,instanceIndex:s.instanceIndex,instance_index:s.instanceIndex,width:(r==null?void 0:r.width)??((a=s.size)==null?void 0:a.width),height:(r==null?void 0:r.height)??((i=s.size)==null?void 0:i.height)}),s.status="minimized",n&&(s.position=n),r&&(s.size=r),this.notify())}restoreTool(e){const n=this.resolveState(e);n&&(kr("restore",n.tool,{instanceId:n.instanceId,instance_id:n.instanceId,instanceIndex:n.instanceIndex,instance_index:n.instanceIndex,previousStatus:n.status,previous_status:n.status}),n.status="open",n.activationOrder=this.nextActivationOrder(),this.notify())}toggleToolVisibility(e){const n=this.resolveState(e);if(n)switch(n.status){case"open":this.minimizeTool(n.instanceId);break;case"minimized":this.restoreTool(n.instanceId);break}}setPinned(e,n){const r=this.getPrimaryToolState(e);this.setPinnedState(e,n,{tool:r==null?void 0:r.tool,persistPreference:!0}),r!=null&&r.tool&&kr(n?"pin":"unpin",r.tool,{isPinned:n,is_pinned:n}),this.getToolInstances(e).forEach(s=>{s.isPinned=n}),this.notify()}isPinned(e){return this.pinnedToolIds.has(e)}getPinnedToolIds(){return Array.from(this.pinnedToolIds)}updateToolPosition(e,n,r){const s=this.resolveState(e);s&&(s.position=n,r&&(s.size=r))}updateToolSize(e,n){const r=this.resolveState(e);r&&(r.size=n,this.notify())}markToolActivated(e){const n=this.resolveState(e);!n||n.status!=="open"||n.activationOrder>this.getTopOpenActivationOrder(n.instanceId)||(n.activationOrder=this.nextActivationOrder(),this.notify())}isToolOpen(e){return this.getToolInstances(e).some(n=>n.status==="open")}isToolMinimized(e){return this.getToolInstances(e).some(n=>n.status==="minimized")}resolveLaunchMode(e,n){return n&&n!=="auto"?n:this.canOpenMultiple(e)?"new":"reuse"}applyOpenToExistingState(e,n,r){const s=e.status,a=e.isLauncher;if(e.tool=n,e.toolId=n.id,e.isPinned=this.pinnedToolIds.has(n.id),e.isLauncher=!1,(r==null?void 0:r.componentProps)!==void 0&&(e.componentProps=r.componentProps),e.status!=="open"){e.status="open",e.activationOrder=this.nextActivationOrder(),r!=null&&r.autoMaximize&&(e.autoMaximize=!0),n.id===Sr&&Ir("applyOpenToExistingState:opened",{instanceId:e.instanceId,previousStatus:s,nextStatus:e.status,previousIsLauncher:a,nextIsLauncher:e.isLauncher,componentProps:e.componentProps});return}r!=null&&r.autoMaximize&&(e.autoMaximize=!0),e.activationOrder=this.nextActivationOrder(),n.id===Sr&&Ir("applyOpenToExistingState:already-open",{instanceId:e.instanceId,previousStatus:s,nextStatus:e.status,previousIsLauncher:a,nextIsLauncher:e.isLauncher,componentProps:e.componentProps})}resolveState(e){return this.toolStates.get(e)||this.getPrimaryToolState(e)}shouldAutoPinOnOpen(e,n){var s;if(n&&Object.prototype.hasOwnProperty.call(n,"autoPin"))return n.autoPin===!0;const r=this.pinPreferences.get(e.id);return typeof r=="boolean"?r:((s=e.defaultWindowBehavior)==null?void 0:s.autoPinOnOpen)===!0}applyAutoPinBehavior(e,n){if(!this.shouldAutoPinOnOpen(e,n))return;const r=n&&Object.prototype.hasOwnProperty.call(n,"autoPin");this.setPinnedState(e.id,!0,{tool:e,persistPreference:r})}updatePinnedToolInfo(e){this.pinnedToolInfos.set(e.id,{id:e.id,name:e.name,category:e.category})}setPinnedState(e,n,r){var s;if(n){this.pinnedToolIds.add(e);const a=(r==null?void 0:r.tool)||((s=this.getPrimaryToolState(e))==null?void 0:s.tool);a&&this.updatePinnedToolInfo(a)}else this.pinnedToolIds.delete(e),this.pinnedToolInfos.delete(e);r!=null&&r.persistPreference&&(this.pinPreferences.set(e,n),this.savePinPreferences()),this.savePinnedTools()}createLauncherState(e){if(!this.pinnedToolIds.has(e))return;const n=Wt.getManifestById(e);if(n)return{instanceId:`${Zu}${e}`,toolId:e,instanceIndex:0,tool:n,status:"closed",activationOrder:0,isPinned:!0,isLauncher:!0};const r=this.pinnedToolInfos.get(e);if(r)return{instanceId:`${Zu}${e}`,toolId:e,instanceIndex:0,tool:{id:r.id,name:r.name,category:r.category},status:"closed",activationOrder:0,isPinned:!0,isLauncher:!0}}nextActivationOrder(){return this.activationOrderCounter+=1,this.activationOrderCounter}nextInstanceIndex(e){const n=(this.instanceCounters.get(e)||0)+1;return this.instanceCounters.set(e,n),n}getTopOpenActivationOrder(e){let n=0;return this.toolStates.forEach((r,s)=>{s===e||r.status!=="open"||r.activationOrder>n&&(n=r.activationOrder)}),n}getCascadedPosition(e){var a,i;const n=this.getToolInstances(e);if(n.length===0)return;const r=n.reduce((l,d)=>l.activationOrder>=d.activationOrder?l:d),s=n.length;return{x:(((a=r.position)==null?void 0:a.x)??RI+s*Xu)+Xu,y:(((i=r.position)==null?void 0:i.y)??LI+s*Ju)+Ju}}generateInstanceId(e){return`${e}:${Ry()}`}notify(){const e=this.getToolStates();this.toolStatesSubject.next(e);const n=e.filter(r=>r.status==="open").map(r=>r.tool);this.openToolsSubject.next(n)}}const pt=Rr.getInstance(),$O=Object.freeze(Object.defineProperty({__proto__:null,toolWindowService:pt},Symbol.toStringTag,{value:"Module"})),bp={apiKey:()=>ln.get().apiKey||"",baseUrl:()=>ln.get().baseUrl||""};function kc(t){return/\$\{(\w+)\}/.test(t)}function BI(t){const e=t.matchAll(/\$\{(\w+)\}/g),n=[];for(const r of e)n.includes(r[1])||n.push(r[1]);return n}function _p(t){const e=BI(t),n=[];for(const r of e){const s=bp[r];s&&s()||n.push(r)}return n}function zI(t){return t.replace(/\$\{(\w+)\}/g,(e,n)=>{const r=bp[n];return r&&r()||e})}function El(t){if(!t||!kc(t))return{url:t,missingVariables:[]};const e=_p(t);return{url:zI(t),missingVariables:e}}function Qu(t){return t?_p(t).includes("apiKey"):!1}const _i=class _i{constructor(e){this.iframeCache=new Map,this.reactRoots=new Map,this.loadStates=new Map,this.loadTimeouts=new Map,this.canvasClickHandler=null,this.settingsChangeHandler=null,this.board=e,this.setupCanvasClickHandler(),this.setupSettingsChangeHandler()}scheduleRootUnmount(e){setTimeout(()=>{try{e.unmount()}catch{}},0)}setupSettingsChangeHandler(){this.settingsChangeHandler=()=>{this.refreshTemplateIframes()},window.addEventListener("gemini-settings-changed",this.settingsChangeHandler)}refreshTemplateIframes(){this.iframeCache.forEach((e,n)=>{const r=e.__templateUrl;if(r&&kc(r)){const{url:s}=El(r),a=new URL(s,window.location.origin);a.searchParams.set("toolId",n),e.src=a.toString()}})}setupCanvasClickHandler(){this.canvasClickHandler=e=>{const n=e.target;if(n.tagName==="IFRAME"||n.closest("iframe")||n.classList.contains("iframe-protection-overlay")||n.closest(".plait-tool-content")||n.closest(".plait-tool-react-content"))return;document.querySelectorAll(".iframe-protection-overlay").forEach(s=>{s.style.display="flex"})},document.addEventListener("click",this.canvasClickHandler)}canDraw(e){return!!(e&&e.type==="tool"&&(e.url||e.component))}draw(e){const n=document.createElementNS("http://www.w3.org/2000/svg","g");n.setAttribute("data-element-id",e.id),n.classList.add("plait-tool-element");const r=this.createForeignObject(e);return n.appendChild(r),this.applyRotation(n,e),n}updateImage(e,n,r){if(r.component){if(n.component!==r.component){this.recreateContent(e,r);return}this.renderReactContent(r)}else if(n.url!==r.url){this.recreateContent(e,r);return}const s=e.querySelector("foreignObject");if(s){const a=this.getRectangle(r);s.setAttribute("x",a.x.toString()),s.setAttribute("y",a.y.toString()),s.setAttribute("width",a.width.toString()),s.setAttribute("height",a.height.toString())}this.applyRotation(e,r)}recreateContent(e,n){const r=this.reactRoots.get(n.id);r&&(this.reactRoots.delete(n.id),this.scheduleRootUnmount(r)),e.innerHTML="";const s=this.createForeignObject(n);e.appendChild(s),this.applyRotation(e,n)}createForeignObject(e){const n=this.getRectangle(e),r=document.createElementNS("http://www.w3.org/2000/svg","foreignObject");r.setAttribute("x",n.x.toString()),r.setAttribute("y",n.y.toString()),r.setAttribute("width",n.width.toString()),r.setAttribute("height",n.height.toString()),r.classList.add("plait-tool-foreign-object"),r.style.outline="none",r.style.background="transparent";const s=document.createElement("div");s.className="plait-tool-container",s.style.cssText=`
|
|
73
73
|
width: 100%;
|
|
74
74
|
height: 100%;
|
|
75
75
|
display: flex;
|
|
@@ -187,19 +187,19 @@ The error may be correlated with this previous error:
|
|
|
187
187
|
height: 100%;
|
|
188
188
|
pointer-events: auto;
|
|
189
189
|
overflow: visible;
|
|
190
|
-
`,this.foreignObject.appendChild(this.htmlContainer),n.appendChild(this.foreignObject)}updateForeignObject(e){if(!this.foreignObject)return;const n=Fe.getRectangleByPoints(e.points);this.foreignObject.setAttribute("x",String(n.x)),this.foreignObject.setAttribute("y",String(n.y)),this.foreignObject.setAttribute("width",String(n.width)),this.foreignObject.setAttribute("height",String(n.height))}renderReact(e,n){this.htmlContainer&&(this.reactRoot||(this.reactRoot=nc.createRoot(this.htmlContainer)),this.reactRoot.render(Ie.createElement(Ek,{board:this.board,element:e,selected:n})))}destroy(){if(this.reactRoot){const e=this.reactRoot;this.reactRoot=null,setTimeout(()=>{try{e.unmount()}catch{}},0)}this.foreignObject=null,this.htmlContainer=null}}class jk extends rc{initializeGenerator(){this.activeGenerator=sc(this.board,{getRectangle:e=>Fe.getRectangleByPoints(e.points),getStrokeWidth:()=>Rf,getStrokeOpacity:()=>.9,hasResizeHandle:()=>!1}),this.anchorGenerator=new Ak(this.board)}initialize(){super.initialize(),this.initializeGenerator();const e=this.getElementG();this.renderedG=this.anchorGenerator.processDrawing(this.element,e,this.selected),this.activeGenerator.processDrawing(this.element,kt.getActiveHost(this.board),{selected:this.selected})}onContextChanged(e,n){const r=e.board.viewport.zoom!==n.board.viewport.zoom||e.board.viewport.offsetX!==n.board.viewport.offsetX||e.board.viewport.offsetY!==n.board.viewport.offsetY;if(e.element!==n.element||e.hasThemeChanged)this.renderedG&&this.anchorGenerator.updateDrawing(this.element,this.renderedG,this.selected),this.activeGenerator.processDrawing(this.element,kt.getActiveHost(this.board),{selected:this.selected});else if(r&&e.selected)this.activeGenerator.processDrawing(this.element,kt.getActiveHost(this.board),{selected:this.selected});else{const s=e.selected!==n.selected;s&&this.renderedG&&this.anchorGenerator.updateDrawing(this.element,this.renderedG,this.selected),(s||e.selected)&&this.activeGenerator.processDrawing(this.element,kt.getActiveHost(this.board),{selected:this.selected})}}destroy(){super.destroy(),this.activeGenerator&&this.activeGenerator.destroy(),this.anchorGenerator&&this.anchorGenerator.destroy(),this.renderedG=void 0}}function Ok(t,e){return t.x<e.x+e.width&&t.x+t.width>e.x&&t.y<e.y+e.height&&t.y+t.height>e.y}const KO=t=>{const{drawElement:e,getRectangle:n,isHit:r,isRectangleHit:s,isMovable:a,isAlign:i,getDeletedFragment:l}=t;return t.drawElement=d=>Dt(d.element)?jk:e(d),t.getRectangle=d=>Dt(d)?Fe.getRectangleByPoints(d.points):n(d),t.isHit=(d,c,h)=>{if(Dt(d)){const u=Fe.getRectangleByPoints(d.points);return c[0]>=u.x&&c[0]<=u.x+u.width&&c[1]>=u.y&&c[1]<=u.y+u.height}return r(d,c,h)},t.isRectangleHit=(d,c)=>{if(Dt(d)){const h=Fe.getRectangleByPoints(d.points),u=Fe.getRectangleByPoints([c.anchor,c.focus]);return Ok(h,u)}return s(d,c)},t.isMovable=d=>Dt(d)?!0:a(d),t.isAlign=d=>Dt(d)?!0:i(d),t.getDeletedFragment=d=>{const c=Tt(t).filter(Dt);return c.length>0&&d.push(...c),l(d)},t},Mk={pending:"○",running:"◉",completed:"✓",failed:"✗",skipped:"⊘"},ah=new Set,ih=({workflow:t,className:e="",onDelete:n,onWorkflowStateChange:r,onRetry:s,onHideForever:a})=>{var A;const i=m.useRef(!1),[l,d]=m.useState(!1),[c,h]=m.useState(!1);m.useEffect(()=>{var P;const k=t.id;if(t.createdAt&&Date.now()-t.createdAt<6e4)return;const D=(P=t.steps)==null?void 0:P.some(j=>j.status==="running"||j.status==="pending"),X=t.status==="completed"||t.status==="failed"||t.status==="cancelled";!(t.status==="running"||t.status==="pending"||D&&!X||X&&D)||i.current||ah.has(k)||(i.current=!0,ah.add(k),(async()=>{var j,N;try{const{workflowSubmissionService:B}=await Xe(async()=>{const{workflowSubmissionService:ae}=await import("./workflow-submission-service-C-6Uf9FA.js").then(te=>te.a);return{workflowSubmissionService:ae}},__vite__mapDeps([0]),import.meta.url);if(B.isWorkflowManagedByFallback(k)){const ae=B.getWorkflowFromFallback(k);if(ae){const te=ae.status;(te==="completed"||te==="failed"||te==="cancelled")&&(r==null||r(k,te==="completed"?"completed":"failed",ae.error));return}}const{swChannelClient:K}=await Xe(async()=>{const{swChannelClient:ae}=await import("./ai-chat-B-XdoWBQ.js").then(te=>te.sI);return{swChannelClient:ae}},__vite__mapDeps([0]),import.meta.url);if(!K.isInitialized()){if(await B.resumeWorkflowWithFallback(k))return;const te=B.getWorkflow(k);if(te){const Se=te.status;(Se==="completed"||Se==="failed"||Se==="cancelled")&&(r==null||r(k,Se==="completed"?"completed":"failed",te.error))}else r==null||r(k,"failed","工作流已丢失,请重试");return}const fe=await K.claimWorkflow(k);if(fe.success){const ae=(j=fe.workflow)==null?void 0:j.status;(ae==="completed"||ae==="failed"||ae==="cancelled")&&(r==null||r(k,ae==="completed"?"completed":"failed",(N=fe.workflow)==null?void 0:N.error))}else{const ae=B.getWorkflow(k);if(ae&&(ae.status==="running"||ae.status==="pending")||await B.resumeWorkflowWithFallback(k))return;r==null||r(k,"failed",fe.error||"工作流已丢失,请重试")}}catch{r==null||r(k,"failed","恢复工作流失败,请重试")}})())},[t.id,t.status,t.createdAt,r]);const u=m.useMemo(()=>{const k=t.steps,U=k.length,D=k.filter(G=>G.status==="completed").length,X=k.filter(G=>G.status==="failed").length,L=k.filter(G=>G.status==="running").length;let O="pending";return X>0?O="failed":D===U&&U>0?O="completed":(L>0||D>0)&&(O="running"),{status:O,totalSteps:U,completedSteps:D}},[t.steps]),p=u.totalSteps>0?u.completedSteps/u.totalSteps*100:0,y=m.useMemo(()=>({pending:"待开始",running:"执行中",completed:"已完成",failed:"执行失败"})[u.status],[u.status]),f=m.useMemo(()=>t.steps.find(k=>k.status==="running"),[t.steps]),g=t.generationType==="image"?"🖼️":t.generationType==="video"?"🎬":t.generationType==="audio"?"🎵":"📝",w=m.useMemo(()=>t.steps.findIndex(k=>k.status==="failed"),[t.steps]),x=u.status==="failed"&&s&&t.retryContext&&w>=0,v=m.useCallback(async()=>{if(!(!s||w<0||l)){d(!0);try{await s(t,w)}finally{d(!1)}}},[s,t,w,l]),_=m.useCallback(()=>{h(!0)},[]),T=m.useCallback(()=>{h(!1),a==null||a()},[a]),b=m.useCallback(k=>{k.stopPropagation()},[]),I=m.useCallback(k=>{k.stopPropagation(),k.preventDefault()},[]);return o.jsxs("div",{className:`workzone-content workzone-content--${u.status} ${e}`,children:[o.jsxs("div",{className:"workzone-content__header",children:[o.jsx("span",{className:"workzone-content__icon",children:g}),o.jsx("span",{className:"workzone-content__title",children:t.name}),o.jsx("span",{className:`workzone-content__status workzone-content__status--${u.status}`,children:y}),a&&o.jsx(Le,{content:"不再显示",showArrow:!1,children:o.jsx("button",{type:"button","aria-label":"不再显示",className:"workzone-content__hide-btn",onPointerDownCapture:b,onPointerDown:b,onPointerUp:b,onMouseDownCapture:b,onMouseDown:b,onClick:k=>{I(k),_()},children:o.jsx(Hy,{size:14})})}),n&&o.jsx(Le,{content:"删除",showArrow:!1,children:o.jsx("button",{type:"button","aria-label":"删除",className:"workzone-content__delete-btn",onPointerDownCapture:b,onPointerDown:b,onPointerUp:b,onMouseDownCapture:b,onMouseDown:b,onClick:k=>{I(k),n()},children:o.jsx(Gy,{size:14})})})]}),o.jsx("div",{className:"workzone-content__progress",children:o.jsx("div",{className:`workzone-content__progress-bar workzone-content__progress-bar--${u.status}`,style:{width:`${p}%`}})}),o.jsxs("div",{className:"workzone-content__progress-info",children:[o.jsxs("span",{children:[u.completedSteps,"/",u.totalSteps," 步骤"]}),f&&o.jsx("span",{className:"workzone-content__current-step",children:f.description})]}),o.jsx("div",{className:"workzone-content__steps",children:t.steps.map(k=>o.jsxs("div",{className:`workzone-content__step workzone-content__step--${k.status}`,children:[o.jsx("span",{className:"workzone-content__step-status",children:k.status==="running"?o.jsx("span",{className:"workzone-content__spinner"}):Mk[k.status]}),o.jsx("span",{className:"workzone-content__step-desc",children:k.description})]},k.id))}),u.status==="failed"&&o.jsxs("div",{className:"workzone-content__error",children:[o.jsxs("span",{children:["❌"," ",((A=t.steps.find(k=>k.status==="failed"))==null?void 0:A.error)||"执行失败"]}),x&&o.jsxs("button",{type:"button",className:"workzone-content__retry-btn",disabled:l,onPointerDownCapture:b,onPointerDown:b,onPointerUp:b,onMouseDownCapture:b,onMouseDown:b,onClick:k=>{I(k),v()},children:[o.jsx(Wy,{size:12}),o.jsx("span",{children:l?"重试中...":"从失败步骤重试"})]})]}),u.status==="completed"&&o.jsx("div",{className:"workzone-content__success",children:"✨ 已完成"}),o.jsx(Kr,{open:c,title:"隐藏进度卡片",description:"确定不再显示进度卡片?\\n\\n任务仍会在后台执行,可在设置中恢复显示。",confirmText:"确定",cancelText:"取消",onOpenChange:h,onConfirm:T})]})},Dk={width:360,height:240};function lr(t){return t&&t.type==="workzone"}function Dl(t){return Number.isFinite(t.zoom)&&t.zoom>0?1/t.zoom:1}function Wr(t){const e=Fe.getRectangleByPoints(t.points),n=Dl(t);return{...e,width:e.width*n,height:e.height*n}}function Nk(){return`workzone_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}const fr={insertWorkZone(t,e){const{workflow:n,position:r,size:s=Dk,expectedInsertPosition:a,targetFrameId:i,targetFrameDimensions:l,zoom:d}=e,c={id:Nk(),type:"workzone",points:[r,[r[0]+s.width,r[1]+s.height]],angle:0,workflow:n,createdAt:Date.now(),expectedInsertPosition:a,targetFrameId:i,targetFrameDimensions:l,zoom:d};return Lr.withoutSaving(t,()=>{ht.insertNode(t,c,[t.children.length])}),c},updateWorkflow(t,e,n){const r=t.children.findIndex(i=>i.id===e);if(r<0)return;const a={...t.children[r].workflow,...n};Lr.withoutSaving(t,()=>{ht.setNode(t,{workflow:a},[r])})},removeWorkZone(t,e){const n=t.children.findIndex(r=>r.id===e);n<0||Lr.withoutSaving(t,()=>{ht.removeNode(t,[n])})},getWorkZoneById(t,e){const n=t.children.find(r=>r.id===e);return n&&lr(n)?n:null},getAllWorkZones(t){return t.children.filter(lr)}},Co="workzone-visibility-changed";function oh(){try{return localStorage.getItem(nn.WORKZONE_CARD_VISIBLE)!=="false"}catch{return!0}}class Op extends rc{constructor(){super(...arguments),this.g=null,this.container=null,this.reactRoot=null,this.handleDelete=()=>{fr.removeWorkZone(this.board,this.element.id)},this.handleWorkflowStateChange=(e,n,r)=>{if(n==="failed"){setTimeout(()=>{fr.removeWorkZone(this.board,this.element.id)},1500);return}const s={...this.element.workflow,status:n};fr.updateWorkflow(this.board,this.element.id,s)},this.handleHideForever=()=>{try{localStorage.setItem(nn.WORKZONE_CARD_VISIBLE,"false")}catch{}window.dispatchEvent(new CustomEvent(Co))},this.handleVisibilityChange=()=>{this.container&&(this.container.style.display=oh()?"":"none")},this.handleRetry=async(e,n)=>{const r=this.board.__executeWorkflowRetry;r?await r(e,n,this.element.id):console.warn("[WorkZone] No retry handler registered on board")}}initialize(){super.initialize(),this.activeGenerator=sc(this.board,{getRectangle:e=>Wr(e),getStrokeWidth:()=>2,getStrokeOpacity:()=>1,hasResizeHandle:()=>!1}),this.createSVGStructure(),this.renderContent(),window.addEventListener(Co,this.handleVisibilityChange)}createSVGStructure(){const e=Fe.getRectangleByPoints(this.element.points),n=Wr(this.element);this.g=document.createElementNS("http://www.w3.org/2000/svg","g"),this.g.setAttribute("data-element-id",this.element.id),this.g.classList.add("plait-workzone-element"),this.g.style.pointerEvents="auto";const r=document.createElementNS("http://www.w3.org/2000/svg","foreignObject");r.setAttribute("x",String(e.x)),r.setAttribute("y",String(e.y)),r.setAttribute("width",String(n.width)),r.setAttribute("height",String(n.height)),r.style.overflow="visible",r.style.pointerEvents="auto",this.container=document.createElementNS("http://www.w3.org/1999/xhtml","div"),this.container.style.width="100%",this.container.style.height="100%",this.container.style.pointerEvents="auto",this.container.style.cursor="default",this.container.style.position="relative",this.container.classList.add("plait-workzone-container"),this.container.style.width=`${e.width}px`,this.container.style.height=`${e.height}px`,this.container.style.transform=`scale(${Dl(this.element)})`,this.container.style.transformOrigin="top left",r.appendChild(this.container),this.g.appendChild(r),this.getElementG().appendChild(this.g)}updateForeignObjectLayout(e){if(!this.g)return;const n=Fe.getRectangleByPoints(e.points),r=Wr(e),s=this.g.querySelector("foreignObject");s&&(s.setAttribute("x",String(n.x)),s.setAttribute("y",String(n.y)),s.setAttribute("width",String(r.width)),s.setAttribute("height",String(r.height))),this.container&&(this.container.style.width=`${n.width}px`,this.container.style.height=`${n.height}px`,this.container.style.transform=`scale(${Dl(e)})`)}renderContent(){this.container&&(this.container.style.display=oh()?"":"none",this.reactRoot=nc.createRoot(this.container),this.reactRoot.render(Ie.createElement(Pl,{board:this.board},Ie.createElement(ih,{workflow:this.element.workflow,onDelete:this.handleDelete,onWorkflowStateChange:this.handleWorkflowStateChange,onRetry:this.handleRetry,onHideForever:this.handleHideForever}))))}onContextChanged(e,n){e.element!==n.element&&this.g&&(this.updateForeignObjectLayout(e.element),this.reactRoot&&this.reactRoot.render(Ie.createElement(Pl,{board:this.board},Ie.createElement(ih,{workflow:e.element.workflow,onDelete:this.handleDelete,onWorkflowStateChange:this.handleWorkflowStateChange,onRetry:this.handleRetry,onHideForever:this.handleHideForever})))),this.activeGenerator.processDrawing(this.element,kt.getActiveHost(this.board),{selected:this.selected})}destroy(){window.removeEventListener(Co,this.handleVisibilityChange),this.g&&this.g.parentNode&&this.g.parentNode.removeChild(this.g),this.activeGenerator&&this.activeGenerator.destroy();const e=this.reactRoot;e&&(this.reactRoot=null,setTimeout(()=>{e.unmount()},0)),this.g=null,this.container=null,super.destroy()}}const lh=t=>{const{drawElement:e,getRectangle:n,isHit:r,isRectangleHit:s,isMovable:a}=t;return t.drawElement=i=>i.element.type==="workzone"?Op:e(i),t.getRectangle=i=>lr(i)?Wr(i):n(i),t.isHit=(i,l)=>{if(lr(i)){const d=Wr(i),[c,h]=l;return c>=d.x&&c<=d.x+d.width&&h>=d.y&&h<=d.y+d.height}return r(i,l)},t.isRectangleHit=(i,l)=>{if(lr(i)){const d=Wr(i),c=Fe.getRectangleByPoints([l.anchor,l.focus]);return Fe.isHit(d,c)}return s(i,l)},t.isMovable=i=>lr(i)?!0:a(i),t},Po=Object.freeze(Object.defineProperty({__proto__:null,WorkZoneComponent:Op,WorkZoneTransforms:fr,default:lh,isWorkZoneElement:lr,withWorkZone:lh},Symbol.toStringTag,{value:"Module"}));function Rk(){const[t,e]=m.useState(!0),[n,r]=m.useState(null),[s,a]=m.useState([]),[i,l]=m.useState(null),[d,c]=m.useState(ct.getState()),[h,u]=m.useState(0),p=m.useCallback(()=>{a(ct.getTree()),l(ct.getCurrentBoard()),c(ct.getState())},[]);m.useEffect(()=>{let P=!0;(async()=>{try{e(!0),await ct.initialize(),P&&(p(),r(null))}catch(B){P&&r(B instanceof Error?B.message:"Failed to initialize")}finally{P&&e(!1)}})();const N=ct.observeEvents().subscribe(()=>{P&&(p(),u(B=>B+1))});return()=>{P=!1,N.unsubscribe()}},[p]);const y=m.useMemo(()=>ct.hasBoards(),[h]),f=m.useCallback(async P=>{try{return r(null),await ct.createFolder(P)}catch(j){return r(j instanceof Error?j.message:"Failed to create folder"),null}},[]),g=m.useCallback(async(P,j)=>{try{return r(null),await ct.renameFolder(P,j),!0}catch(N){throw r(N instanceof Error?N.message:"Failed to rename folder"),N}},[]),w=m.useCallback(async P=>{try{return r(null),await ct.deleteFolder(P),!0}catch(j){return r(j instanceof Error?j.message:"Failed to delete folder"),!1}},[]),x=m.useCallback(async P=>{try{return r(null),await ct.deleteFolderWithContents(P),!0}catch(j){return r(j instanceof Error?j.message:"Failed to delete folder with contents"),!1}},[]),v=m.useCallback(async(P,j,N,B)=>{try{return r(null),await ct.moveFolder(P,j,N,B),!0}catch(K){throw r(K instanceof Error?K.message:"Failed to move folder"),K}},[]),_=m.useCallback(P=>{ct.toggleFolderExpanded(P)},[]),T=m.useCallback(async P=>{try{return r(null),await ct.createBoard(P)}catch(j){return r(j instanceof Error?j.message:"Failed to create board"),null}},[]),b=m.useCallback(async(P,j)=>{try{return r(null),await ct.renameBoard(P,j),!0}catch(N){throw r(N instanceof Error?N.message:"Failed to rename board"),N}},[]),I=m.useCallback(async P=>{try{return r(null),await ct.deleteBoard(P),!0}catch(j){return r(j instanceof Error?j.message:"Failed to delete board"),!1}},[]),A=m.useCallback(async(P,j,N,B)=>{try{return r(null),await ct.moveBoard(P,j,N,B),!0}catch(K){throw r(K instanceof Error?K.message:"Failed to move board"),K}},[]),k=m.useCallback(async P=>{try{return r(null),await ct.switchBoard(P)}catch(j){return r(j instanceof Error?j.message:"Failed to switch board"),null}},[]),U=m.useCallback(async P=>{const j=ct.getCurrentBoard();if(!j)return!1;try{await ct.saveBoard(j.id,P);const{markTabSyncVersion:N}=await Xe(async()=>{const{markTabSyncVersion:B}=await import("./bootstrap-DadYvnge.js").then(K=>K.y);return{markTabSyncVersion:B}},__vite__mapDeps([0,1]),import.meta.url);return N(j.id),!0}catch(N){return console.error("[useWorkspace] Failed to save board:",N),!1}},[]),D=m.useCallback(async P=>{try{return r(null),await ct.copyBoard(P)}catch(j){return r(j instanceof Error?j.message:"Failed to copy board"),null}},[]),X=m.useCallback(async P=>{try{return r(null),await ct.deleteBoardsBatch(P),!0}catch(j){return r(j instanceof Error?j.message:"Failed to delete boards"),!1}},[]),L=m.useCallback(async(P,j)=>{try{return r(null),await ct.moveBoardsBatch(P,j),!0}catch(N){return r(N instanceof Error?N.message:"Failed to move boards"),!1}},[]),O=m.useCallback(async P=>{try{return r(null),await ct.reorderItems(P),!0}catch(j){return r(j instanceof Error?j.message:"Failed to reorder items"),!1}},[]),G=m.useCallback(P=>{ct.setSidebarWidth(P),c(ct.getState())},[]),C=m.useCallback(P=>{ct.setSidebarCollapsed(P),c(ct.getState())},[]);return{isLoading:t,error:n,tree:s,currentBoard:i,workspaceState:d,hasBoards:y,createFolder:f,renameFolder:g,deleteFolder:w,deleteFolderWithContents:x,moveFolder:v,toggleFolderExpanded:_,createBoard:T,renameBoard:b,deleteBoard:I,moveBoard:A,copyBoard:D,switchBoard:k,saveBoard:U,deleteBoardsBatch:X,moveBoardsBatch:L,reorderItems:O,setSidebarWidth:G,setSidebarCollapsed:C,refresh:p}}const Mt=class Mt{constructor(){this.customTools=[],this.isInitialized=!1,this.initialize()}static getInstance(){return Mt.instance||(Mt.instance=new Mt),Mt.instance}getAvailableTools(){return[...Wt.getBuiltInTools(),...this.customTools]}getToolById(e){return Wt.getManifestById(e)||this.customTools.find(n=>n.id===e)||null}async initialize(){if(!this.isInitialized)try{const e=await Xt.getItem(Mt.STORAGE_KEY);e&&(this.isCompatibleVersion(e.version)?this.customTools=e.tools:(console.warn("[Toolbox] Incompatible version, resetting custom tools"),await this.resetCustomTools()))}catch(e){console.error("[Toolbox] Failed to load custom tools:",e)}finally{this.isInitialized=!0}}async saveCustomTools(){try{const e={version:Mt.STORAGE_VERSION,tools:this.customTools,updatedAt:Date.now()};await Xt.setItem(Mt.STORAGE_KEY,e)}catch(e){throw console.error("[Toolbox] Failed to save custom tools:",e),e}}async addCustomTool(e){if(this.customTools.length>=Mt.MAX_CUSTOM_TOOLS)throw new Error(`Maximum ${Mt.MAX_CUSTOM_TOOLS} custom tools allowed`);if(this.validateToolDefinition(e),this.customTools.some(s=>s.id===e.id))throw new Error(`Tool with id "${e.id}" already exists`);const r={...e,id:e.id||`custom-${Date.now()}`,category:e.category||tt.CUSTOM,defaultWidth:e.defaultWidth||800,defaultHeight:e.defaultHeight||600,permissions:e.permissions||["allow-scripts","allow-same-origin","allow-popups","allow-forms","allow-top-navigation-by-user-activation"]};this.customTools.push(r),await this.saveCustomTools()}async removeCustomTool(e){const n=this.customTools.length;this.customTools=this.customTools.filter(s=>s.id!==e);const r=this.customTools.length<n;return r&&await this.saveCustomTools(),r}async updateCustomTool(e,n){const r=this.customTools.findIndex(a=>a.id===e);if(r===-1)return!1;const s={...this.customTools[r],...n,id:e};return this.validateToolDefinition(s),this.customTools[r]=s,await this.saveCustomTools(),!0}getToolsByCategory(){const e=this.getAvailableTools(),n={};return e.forEach(r=>{const s=r.category||"utilities";n[s]||(n[s]=[]),n[s].push(r)}),n}searchTools(e){if(!e.trim())return this.getAvailableTools();const n=e.toLowerCase().trim();return this.getAvailableTools().filter(r=>{var s;return r.name.toLowerCase().includes(n)||((s=r.description)==null?void 0:s.toLowerCase().includes(n))||r.id.toLowerCase().includes(n)})}getCustomTools(){return[...this.customTools]}async clearCustomTools(){this.customTools=[],await this.saveCustomTools()}async getUpdatedAt(){try{const e=await Xt.getItem(Mt.STORAGE_KEY);return(e==null?void 0:e.updatedAt)||0}catch{return 0}}async importTools(e){let n=0,r=0;for(const s of e)this.customTools.findIndex(i=>i.id===s.id)===-1?(this.customTools.push(s),n++):r++;return n>0&&await this.saveCustomTools(),{imported:n,skipped:r}}exportTools(){return{tools:[...this.customTools],updatedAt:Date.now()}}validateToolDefinition(e){if(!e.name)throw new Error("Tool name is required");const n=!!e.url,r=!!e.component;if(!n&&!r)throw new Error("Tool must have either a URL or an internal component");if(n&&r)throw new Error("Tool cannot have both a URL and an internal component");if(e.url&&e.url.startsWith("http"))try{const s=new URL(e.url);if(!["https:","http:"].includes(s.protocol))throw new Error("Only HTTP/HTTPS URLs are allowed")}catch{throw new Error("Invalid URL format")}if(e.name.length>50)throw new Error("Tool name too long (max 50 characters)");if(e.description&&e.description.length>200)throw new Error("Tool description too long (max 200 characters)")}isCompatibleVersion(e){return e===Mt.STORAGE_VERSION}async resetCustomTools(){this.customTools=[],await this.saveCustomTools()}};Mt.STORAGE_KEY="aitu:custom-tools",Mt.STORAGE_VERSION="1.0",Mt.MAX_CUSTOM_TOOLS=50;let Nl=Mt;const jn=Nl.getInstance(),qO=Object.freeze(Object.defineProperty({__proto__:null,toolboxService:jn},Symbol.toStringTag,{value:"Module"})),ch={defaultWidth:600,defaultHeight:400},Mp={[tt.AI_TOOLS]:"AI 工具",[tt.CONTENT_TOOLS]:"内容工具",[tt.UTILITIES]:"实用工具",[tt.CUSTOM]:"自定义工具"},dh=[tt.AI_TOOLS,tt.CONTENT_TOOLS,tt.UTILITIES,tt.CUSTOM];function uh(t){const e=dh.findIndex(n=>n===t);return e>=0?e:dh.length}function Dp(t){return[...t].sort((e,n)=>uh(e)-uh(n)||e.localeCompare(n))}function YO(t){return m.useSyncExternalStore(mt.subscribe.bind(mt),()=>t(mt.getState()),()=>t(mt.getState()))}function Lk(){return m.useMemo(()=>({setQueue:(t,e)=>mt.setQueue(t,e),setReadingQueue:t=>mt.setReadingQueue(t),setPlaylistQueue:(t,e)=>mt.setQueue(t,{queueSource:"playlist",playlistId:e.playlistId,playlistName:e.playlistName}),togglePlaybackInQueue:(t,e,n)=>mt.togglePlaybackInQueue(t,e,n),togglePlayback:t=>mt.togglePlayback(t),toggleReadingPlayback:t=>mt.toggleReadingPlayback(t),toggleReadingPlaybackInQueue:(t,e,n)=>mt.toggleReadingPlaybackInQueue(t,e,n),pausePlayback:()=>mt.pausePlayback(),resumePlayback:()=>mt.resumePlayback(),playPrevious:()=>mt.playPrevious(),playNext:()=>mt.playNext(),setPlaybackMode:t=>mt.setPlaybackMode(t),setPlaybackRate:(t,e)=>mt.setPlaybackRate(t,e),seekTo:t=>mt.seekTo(t),seekToReadingSegment:t=>mt.seekToReadingSegment(t),setVolume:t=>mt.setVolume(t),stopPlayback:()=>mt.stopAndClear()}),[])}function Fk(){const t=m.useSyncExternalStore(mt.subscribe.bind(mt),mt.getState.bind(mt),mt.getState.bind(mt)),e=Lk();return{...t,...e}}const ZO=(t,e)=>na.isMindElement(t,e)||It.isDrawElement(e)&&Vy(e)||Ky(t,e)||rs.isFreehand(e)||Jn.isPenPath(e)&&e.closed,Bk=(t,e)=>{if(e.fill){if(qy(e.fill))return Yy(e.fill);if(typeof e.fill=="string")return e.fill}let n=null;if(na.isMindElement(t,e))n=Zy(t,e);else if(rs.isFreehand(e))n=Xy(t,e);else if(Jn.isPenPath(e)){const r=Zl[t.theme.themeColorMode];n=(e.closed?r==null?void 0:r.fill:"none")||"#FFFFFF"}else(It.isDrawElement(e)||It.isCustomGeometryElement(t,e))&&(n=Jy(t,e));return n},Wa=(t,e)=>{let n=e.strokeColor;if(!n)if(na.isMindElement(t,e)&&(n=Qy(t,e)),rs.isFreehand(e))n=ev(t,e);else if(Jn.isPenPath(e)){const r=Zl[t.theme.themeColorMode];n=e.strokeColor||(r==null?void 0:r.strokeColor)||"#000000"}else(It.isDrawElement(e)||It.isCustomGeometryElement(t,e))&&(n=tv(t,e));return n},XO=(t,e)=>nv(e).color,Np={project:"drawnix-drawer-pin-project",toolbox:"drawnix-drawer-pin-toolbox",task:"drawnix-drawer-pin-task"};function hh(t){try{return localStorage.getItem(t)==="true"}catch{return!1}}function zk(t,e){try{localStorage.setItem(t,String(e))}catch{}}const $k=(t,e=20)=>{if(!t)return o.jsx("span",{role:"img","aria-label":"tool",style:{fontSize:e},children:"🔧"});if(typeof t=="function"){const n=t;return o.jsx(n,{size:e})}return typeof t=="string"?o.jsx("span",{style:{fontSize:e},children:t}):Ie.isValidElement(t)?t:null},fh=({ensureToolWindowsEnabled:t})=>{const[e,n]=m.useState([]),[r,s]=m.useState(null),{language:a,t:i}=ss(),l=m.useMemo(()=>{const u=new Map,p=new Map;e.forEach(f=>{f.isLauncher||u.set(f.toolId,(u.get(f.toolId)||0)+1)});const y=new Map;return e.forEach(f=>{if(f.isLauncher)return;const g=(p.get(f.toolId)||0)+1;p.set(f.toolId,g),y.set(f.instanceId,{displayIndex:g,showBadge:(u.get(f.toolId)||0)>1})}),y},[e]);m.useEffect(()=>{const u=pt.observeToolStates().subscribe(()=>{n(pt.getToolbarTools())});return n(pt.getToolbarTools()),()=>u.unsubscribe()},[]);const d=m.useCallback((u,p)=>{if(t==null||t(),p.id==="prompt-history"&&console.info("[MinimizedToolsBar] click prompt-history",{instanceId:u.instanceId,status:u.status,isLauncher:u.isLauncher,isPinned:u.isPinned}),u.isLauncher||u.status==="closed"){const y=jn.getToolById(p.id);y?pt.openTool(y):console.warn("[MinimizedToolsBar] Tool not found:",p.id)}else pt.toggleToolVisibility(u.instanceId)},[t]),c=m.useCallback((u,p,y)=>{switch(y){case"toggle-pin":{const f=pt.isPinned(u.toolId);pt.setPinned(u.toolId,!f);break}case"close":pt.closeTool(u.instanceId);break;case"new-window":t==null||t(),pt.openNewToolInstance(p);break}},[t]),h=m.useCallback((u,p)=>{const y=u.isPinned,f=[...pt.canOpenMultiple(p)?[{content:i("toolbar.openNewWindow"),value:"new-window"}]:[],{content:y?a==="zh"?"取消常驻":"Unpin from toolbar":a==="zh"?"常驻工具栏":"Pin to toolbar",value:"toggle-pin"}];return u.isLauncher||f.push({content:a==="zh"?"关闭":"Close",value:"close",theme:"error"}),f},[a,i]);return e.length===0?null:o.jsx("div",{className:"minimized-tools-bar",children:e.map(u=>{const{tool:p}=u,y=jn.getToolById(p.id)||p,f=l.get(u.instanceId),g=u.isLauncher||!(f!=null&&f.showBadge)?y.name:`${y.name} #${f.displayIndex}`;return o.jsx(qr,{options:h(u,y),trigger:"context-menu",popupProps:{onVisibleChange:w=>{s(w?u.instanceId:null)}},onClick:w=>{c(u,y,w.value)},children:o.jsxs("div",{className:"minimized-tools-bar__item","data-minimize-target":u.instanceId,onClick:w=>{w.button===0&&(w.stopPropagation(),d(u,y))},children:[o.jsx(Xm,{type:"icon",visible:!0,selected:u.status==="open",icon:$k(y.icon),tooltip:r===u.instanceId?void 0:g,"aria-label":g,"data-track":"toolbar_click_minimized_tool","data-tool-id":y.id}),!u.isLauncher&&(f==null?void 0:f.showBadge)&&o.jsx("span",{className:"minimized-tools-bar__badge","aria-hidden":"true",children:f.displayIndex}),u.status!=="closed"&&o.jsx("div",{className:St("minimized-tools-bar__indicator",{"minimized-tools-bar__indicator--active":u.status==="open"})})]})},u.instanceId)})})},JO=Object.freeze(Object.defineProperty({__proto__:null,MinimizedToolsBar:fh,default:fh},Symbol.toStringTag,{value:"Module"}));function QO(t,e){return`${t},${e}`}function e1(t){return t?t==="sora-2"||t==="sora-2-pro":!1}function t1(t){return t?t.startsWith("sora-2:")||t.startsWith("sora-2-pro:"):!1}function Uk(t){return t==="sora-2-pro"?"sora-2-pro-character":"sora-2-character"}const Hk=({isOpen:t,onClose:e,title:n,subtitle:r,headerActions:s,pinnable:a=!1,pinned:i=!1,onPinnedChange:l,filterSection:d,children:c,footer:h,position:u="toolbar-right",width:p="narrow",customWidth:y,showBackdrop:f=!1,closeOnBackdropClick:g=!0,closeOnEsc:w=!0,zIndex:x,className:v="",headerClassName:_="",contentClassName:T="",footerClassName:b="",showCloseButton:I=!0,closeButtonSize:A="small",resizable:k=!1,minWidth:U=280,maxWidth:D=800,onWidthChange:X,"data-testid":L})=>{const[O,G]=m.useState(null),[C,P]=m.useState(!1),j=m.useRef(null),N=m.useRef(0),B=m.useRef(0),K=m.useRef("right");m.useEffect(()=>{if(!t||!w)return;const Te=ke=>{ke.key==="Escape"&&(ke.preventDefault(),e())};return window.addEventListener("keydown",Te),()=>window.removeEventListener("keydown",Te)},[t,w,e]);const fe=m.useCallback(()=>{g&&e()},[g,e]),ae=m.useCallback(()=>{l==null||l(!i)},[l,i]),te=m.useCallback(Te=>{if(Te.preventDefault(),!j.current)return;P(!0);const ke="touches"in Te?Te.touches[0].clientX:Te.clientX;N.current=ke,B.current=j.current.offsetWidth,K.current=u==="toolbar-right"&&document.documentElement.classList.contains("aitu-toolbar-dock-right")?"left":"right"},[u]);m.useEffect(()=>{if(!C)return;const Te=ne=>{const M="touches"in ne?ne.touches[0].clientX:ne.clientX,q=K.current==="left"?N.current-M:M-N.current,R=Math.min(D,Math.max(U,B.current+q));G(R)},ke=()=>{P(!1),O!==null&&(X==null||X(O))};return document.addEventListener("mousemove",Te),document.addEventListener("mouseup",ke),document.addEventListener("touchmove",Te,{passive:!1}),document.addEventListener("touchend",ke),document.addEventListener("touchcancel",ke),()=>{document.removeEventListener("mousemove",Te),document.removeEventListener("mouseup",ke),document.removeEventListener("touchmove",Te),document.removeEventListener("touchend",ke),document.removeEventListener("touchcancel",ke)}},[C,O,U,D,X]);const Se=["side-drawer",`side-drawer--${u}`,`side-drawer--${p}`,t?"side-drawer--open":"",C?"side-drawer--dragging":"",k?"side-drawer--resizable":"",v].filter(Boolean).join(" "),Ee={};return O!==null?Ee.width=`${O}px`:y&&(Ee.width=typeof y=="number"?`${y}px`:y),x!==void 0&&(Ee.zIndex=x),o.jsxs(o.Fragment,{children:[o.jsxs("div",{ref:j,className:Se,style:Ee,"data-testid":L,children:[o.jsxs("div",{className:`side-drawer__header ${_}`,children:[o.jsxs("div",{className:"side-drawer__header-left",children:[o.jsx("h3",{className:"side-drawer__title",children:n}),r&&o.jsx("span",{className:"side-drawer__subtitle",children:r})]}),o.jsxs("div",{className:"side-drawer__header-right",children:[s,a&&o.jsx(Le,{content:i?"取消固定":"固定,不自动收起",showArrow:!1,children:o.jsx(Me,{variant:"text",size:A,icon:i?o.jsx(Lf,{}):o.jsx(Ff,{}),onClick:ae,className:`side-drawer__pin-btn${i?" side-drawer__pin-btn--active":""}`,"aria-label":i?"取消固定抽屉":"固定抽屉"})}),I&&o.jsx(Le,{content:"关闭",showArrow:!1,children:o.jsx(Me,{variant:"text",size:A,icon:o.jsx(Bf,{}),onClick:e,className:"side-drawer__close-btn"})})]})]}),d&&o.jsx("div",{className:"side-drawer__filter",children:d}),o.jsx("div",{className:`side-drawer__content ${T}`,children:c}),h&&o.jsx("div",{className:`side-drawer__footer ${b}`,children:h}),k&&o.jsx("div",{className:"side-drawer__resize-handle",onMouseDown:te,onTouchStart:te})]}),f&&t&&o.jsx("div",{className:"side-drawer__backdrop",onClick:fe,style:x!==void 0?{zIndex:x-1}:void 0})]})},Rp=({storageKey:t,pinStorageKey:e,defaultWidth:n,minWidth:r=300,maxWidth:s=1024,resizable:a=!0,pinnable:i,...l})=>{const[d,c]=m.useState(()=>{if(t)try{const f=localStorage.getItem(t);if(f){const g=parseInt(f,10);if(!isNaN(g)&&g>=r&&g<=s)return g}}catch{}}),[h,u]=m.useState(()=>e?hh(e):!1),p=m.useCallback(f=>{if(c(f),t)try{localStorage.setItem(t,String(f))}catch{}},[t]);m.useEffect(()=>{if(t)try{const f=localStorage.getItem(t);if(f){const g=parseInt(f,10);!isNaN(g)&&g>=r&&g<=s&&c(g)}}catch{}},[t,r,s]),m.useEffect(()=>{e&&u(hh(e))},[e]);const y=m.useCallback(f=>{u(f),e&&zk(e,f)},[e]);return o.jsx(Hk,{...l,pinnable:i||!!e,pinned:h,onPinnedChange:y,resizable:a,minWidth:r,maxWidth:s,customWidth:d||n,onWidthChange:p})},Eo="avatar-",Cr=Xt.createInstance({name:"drawnix",storeName:"character-avatars",description:"Character avatar cache"});class Gk{constructor(){this.objectUrlCache=new Map}async cacheAvatar(e,n){try{if(await this.getCachedAvatar(e))return!0;const s=await this.fetchImageAsBlob(n);if(!s)throw new Error("Failed to fetch avatar image");const a=s.type||"image/png",i={characterId:e,blob:s,mimeType:a,size:s.size,cachedAt:Date.now(),originalUrl:n};return await Cr.setItem(`${Eo}${e}`,i),!0}catch(r){return console.error("[AvatarCache] Failed to cache avatar:",e,r),!1}}async fetchImageAsBlob(e){return new Promise(n=>{const r=new Image;r.crossOrigin="anonymous",r.onload=()=>{try{const s=document.createElement("canvas");s.width=r.naturalWidth,s.height=r.naturalHeight;const a=s.getContext("2d");if(!a){n(null);return}a.drawImage(r,0,0),s.toBlob(i=>{n(i)},"image/png")}catch(s){console.warn("[AvatarCache] Canvas draw failed:",s),n(null)}},r.onerror=()=>{console.warn("[AvatarCache] Image load failed for:",e),n(null)},r.src=e})}async getCachedAvatar(e){try{return await Cr.getItem(`${Eo}${e}`)||null}catch(n){return console.error("[AvatarCache] Failed to get cached avatar:",e,n),null}}async getCachedUrl(e){const n=this.objectUrlCache.get(e);if(n)return n;const r=await this.getCachedAvatar(e);if(r!=null&&r.blob){if(this.objectUrlCache.size>=50){const i=this.objectUrlCache.keys().next().value;i&&(URL.revokeObjectURL(this.objectUrlCache.get(i)),this.objectUrlCache.delete(i))}const a=URL.createObjectURL(r.blob);return this.objectUrlCache.set(e,a),a}return null}async getAvatarUrl(e,n){const r=await this.getCachedUrl(e);return r||(this.cacheAvatar(e,n).catch(()=>{}),n)}async isCached(e){return await this.getCachedAvatar(e)!==null}async deleteCache(e){try{const n=this.objectUrlCache.get(e);return n&&(URL.revokeObjectURL(n),this.objectUrlCache.delete(e)),await Cr.removeItem(`${Eo}${e}`),!0}catch(n){return console.error("[AvatarCache] Failed to delete avatar cache:",e,n),!1}}async clearAll(){try{return this.objectUrlCache.forEach(e=>{URL.revokeObjectURL(e)}),this.objectUrlCache.clear(),await Cr.clear(),!0}catch(e){return console.error("[AvatarCache] Failed to clear all caches:",e),!1}}async getTotalCacheSize(){try{let e=0;return await Cr.iterate(n=>{n!=null&&n.size&&(e+=n.size)}),e}catch(e){return console.error("[AvatarCache] Failed to get cache size:",e),0}}async getCacheCount(){try{return await Cr.length()}catch(e){return console.error("[AvatarCache] Failed to get cache count:",e),0}}cleanup(){this.objectUrlCache.forEach(e=>{URL.revokeObjectURL(e)}),this.objectUrlCache.clear()}}const Va=new Gk,mh="sora-characters",ph=Xt.createInstance({name:"drawnix",storeName:"characters",description:"Sora character storage"});class Wk{constructor(){this.characters$=new si([]),this.initialized=!1,this.init()}async init(){if(!this.initialized)try{const e=await this.loadFromStorage();this.characters$.next(e),this.initialized=!0}catch(e){console.error("[CharacterStorage] Failed to initialize:",e),this.characters$.next([]),this.initialized=!0}}getCharacters$(){return this.characters$.asObservable()}getCharacters(){return this.characters$.getValue()}getCharactersByStatus(e){return this.getCharacters().filter(n=>n.status===e)}getCharacterById(e){return this.getCharacters().find(n=>n.id===e)}getCharactersBySourceTask(e){return this.getCharacters().filter(n=>n.sourceTaskId===e)}async saveCharacter(e){const n=this.getCharacters(),r=n.findIndex(s=>s.id===e.id);r>=0?n[r]=e:n.push(e),await this.saveToStorage(n),this.characters$.next([...n]),e.status==="completed"&&e.profilePictureUrl&&Va.cacheAvatar(e.id,e.profilePictureUrl).catch(s=>console.warn("[CharacterStorage] Failed to cache avatar:",s))}async updateCharacter(e,n){const r=this.getCharacters(),s=r.findIndex(i=>i.id===e);if(s<0)return console.warn("[CharacterStorage] Character not found:",e),null;const a={...r[s],...n};return r[s]=a,await this.saveToStorage(r),this.characters$.next([...r]),a.status==="completed"&&a.profilePictureUrl&&Va.cacheAvatar(e,a.profilePictureUrl).catch(i=>console.warn("[CharacterStorage] Failed to cache avatar:",i)),a}async updateCharacterStatus(e,n,r){const s={status:n};return n==="completed"&&(s.completedAt=Date.now()),r&&(s.error=r),this.updateCharacter(e,s)}async deleteCharacter(e){const n=this.getCharacters(),r=n.findIndex(s=>s.id===e);return r<0?(console.warn("[CharacterStorage] Character not found for deletion:",e),!1):(n.splice(r,1),await this.saveToStorage(n),this.characters$.next([...n]),Va.deleteCache(e).catch(s=>console.warn("[CharacterStorage] Failed to delete avatar cache:",s)),!0)}async deleteCharactersBySourceTask(e){const n=this.getCharacters(),r=n.length,s=n.filter(i=>i.sourceTaskId!==e);return s.length===r?0:(await this.saveToStorage(s),this.characters$.next(s),r-s.length)}async clearAll(){await this.saveToStorage([]),this.characters$.next([])}getPendingCharacters(){return this.getCharacters().filter(e=>e.status==="pending"||e.status==="processing")}async loadFromStorage(){try{return await ph.getItem(mh)||[]}catch(e){return console.error("[CharacterStorage] Load error:",e),[]}}async saveToStorage(e){try{await ph.setItem(mh,e)}catch(n){throw console.error("[CharacterStorage] Save error:",n),n}}}const Qs=new Wk,Et=rv("CharacterAPI"),gh={ACCEPTED:202,NOT_FOUND:404};class Vk{get baseUrl(){return(ln.get().baseUrl||"https://api.tu-zi.com/v1").replace(/\/v1\/?$/,"")}async createCharacter(e){const r=ln.get().apiKey;if(!r)throw new Error("API Key 未配置,请先配置 API Key");const s=Uk(e.sourceModel);Et.debug("Creating character from video:",e.videoTaskId),Et.debug("Source model:",e.sourceModel,"-> Character model:",s),Et.debug("Timestamps:",e.characterTimestamps||"default");const a=new FormData;a.append("character_from_task",e.videoTaskId),a.append("model",s),e.characterTimestamps&&a.append("character_timestamps",e.characterTimestamps);const i=await fetch(`${this.baseUrl}/v1/videos`,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:a});if(!i.ok){const d=await i.text();Et.error("Create failed:",i.status,d);const c=new Error(`角色创建失败: ${i.status} - ${d}`);throw c.apiErrorBody=d,c.httpStatus=i.status,c}const l=await i.json();return Et.debug("Character created:",l),l}async queryCharacter(e){const r=ln.get().apiKey;if(!r)throw new Error("API Key 未配置");const s=await fetch(`${this.baseUrl}/v1/videos/${e}`,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!s.ok){const i=await s.text();if(Et.error("Query failed:",s.status,i),s.status===gh.NOT_FOUND||s.status===gh.ACCEPTED)throw new Error("CHARACTER_PROCESSING");const l=new Error(`角色查询失败: ${s.status} - ${i}`);throw l.apiErrorBody=i,l.httpStatus=s.status,l}const a=await s.json();return Et.debug("Character query result:",a),a}async createCharacterWithPolling(e,n={}){const{interval:r=3e3,maxAttempts:s=60,onStatusChange:a}=n;Et.debug("Submitting character creation...");const l=(await this.createCharacter(e)).id;Et.debug("Character creation submitted:",l),a&&a("processing");let d=0;for(;d<s;){await this.sleep(r),d++;try{Et.debug(`Polling attempt ${d}/${s}...`);const c=await this.queryCharacter(l);if(c.username&&c.profile_picture_url)return Et.debug("Character ready:",c.username),a&&a("completed"),{...c,characterId:l}}catch(c){if(c.message==="CHARACTER_PROCESSING"){Et.debug("Character still processing...");continue}if(Et.warn("Query error:",c.message),d>=s)throw a&&a("failed"),c}}throw a&&a("failed"),new Error("角色创建超时,请稍后重试")}async resumePolling(e,n={}){const{onStatusChange:r}=n;Et.debug("Resuming poll for character:",e);try{const s=await this.queryCharacter(e);if(s.username&&s.profile_picture_url)return Et.debug("Character already ready:",s.username),r&&r("completed"),s}catch(s){if(s.message!=="CHARACTER_PROCESSING")throw s}return this.pollUntilComplete(e,n)}async pollUntilComplete(e,n={}){const{interval:r=3e3,maxAttempts:s=60,onStatusChange:a}=n;let i=0;for(;i<s;){await this.sleep(r),i++;try{Et.debug(`Poll attempt ${i}/${s}...`);const l=await this.queryCharacter(e);if(l.username&&l.profile_picture_url)return Et.debug("Character ready:",l.username),a&&a("completed"),l}catch(l){if(l.message==="CHARACTER_PROCESSING")continue;if(i>=s)throw a&&a("failed"),l}}throw a&&a("failed"),new Error("角色创建超时,请稍后重试")}sleep(e){return new Promise(n=>setTimeout(n,e))}}const Kk=new Vk;function Ao(t){var n;const e=((n=t==null?void 0:t.clips)==null?void 0:n.map(r=>typeof r.audioUrl=="string"?r.audioUrl.trim():"").filter(r=>!!r))||[];return e.length>0?e:Array.isArray(t==null?void 0:t.urls)&&t.urls.length>0?t.urls.filter(r=>typeof r=="string"&&r.trim().length>0):typeof(t==null?void 0:t.url)=="string"&&t.url.trim().length>0?[t.url]:[]}const qk="aitu:ai-input-focus",Yk="aitu:ai-input-prefill";function Zk(t={}){typeof window>"u"||window.dispatchEvent(new CustomEvent(qk,{detail:t}))}function n1(t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Yk,{detail:t}))}const Xk=m.lazy(()=>Xe(()=>import("./batch-image-generation-DyWeiTsw.js"),__vite__mapDeps([0,2]),import.meta.url)),Jk={width:"100%",height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",boxSizing:"border-box"},Qk=({message:t="加载中..."})=>o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:200,color:"#999",fontSize:14},children:t}),eC=()=>o.jsx("style",{children:`
|
|
190
|
+
`,this.foreignObject.appendChild(this.htmlContainer),n.appendChild(this.foreignObject)}updateForeignObject(e){if(!this.foreignObject)return;const n=Fe.getRectangleByPoints(e.points);this.foreignObject.setAttribute("x",String(n.x)),this.foreignObject.setAttribute("y",String(n.y)),this.foreignObject.setAttribute("width",String(n.width)),this.foreignObject.setAttribute("height",String(n.height))}renderReact(e,n){this.htmlContainer&&(this.reactRoot||(this.reactRoot=nc.createRoot(this.htmlContainer)),this.reactRoot.render(Ie.createElement(Ek,{board:this.board,element:e,selected:n})))}destroy(){if(this.reactRoot){const e=this.reactRoot;this.reactRoot=null,setTimeout(()=>{try{e.unmount()}catch{}},0)}this.foreignObject=null,this.htmlContainer=null}}class jk extends rc{initializeGenerator(){this.activeGenerator=sc(this.board,{getRectangle:e=>Fe.getRectangleByPoints(e.points),getStrokeWidth:()=>Rf,getStrokeOpacity:()=>.9,hasResizeHandle:()=>!1}),this.anchorGenerator=new Ak(this.board)}initialize(){super.initialize(),this.initializeGenerator();const e=this.getElementG();this.renderedG=this.anchorGenerator.processDrawing(this.element,e,this.selected),this.activeGenerator.processDrawing(this.element,kt.getActiveHost(this.board),{selected:this.selected})}onContextChanged(e,n){const r=e.board.viewport.zoom!==n.board.viewport.zoom||e.board.viewport.offsetX!==n.board.viewport.offsetX||e.board.viewport.offsetY!==n.board.viewport.offsetY;if(e.element!==n.element||e.hasThemeChanged)this.renderedG&&this.anchorGenerator.updateDrawing(this.element,this.renderedG,this.selected),this.activeGenerator.processDrawing(this.element,kt.getActiveHost(this.board),{selected:this.selected});else if(r&&e.selected)this.activeGenerator.processDrawing(this.element,kt.getActiveHost(this.board),{selected:this.selected});else{const s=e.selected!==n.selected;s&&this.renderedG&&this.anchorGenerator.updateDrawing(this.element,this.renderedG,this.selected),(s||e.selected)&&this.activeGenerator.processDrawing(this.element,kt.getActiveHost(this.board),{selected:this.selected})}}destroy(){super.destroy(),this.activeGenerator&&this.activeGenerator.destroy(),this.anchorGenerator&&this.anchorGenerator.destroy(),this.renderedG=void 0}}function Ok(t,e){return t.x<e.x+e.width&&t.x+t.width>e.x&&t.y<e.y+e.height&&t.y+t.height>e.y}const KO=t=>{const{drawElement:e,getRectangle:n,isHit:r,isRectangleHit:s,isMovable:a,isAlign:i,getDeletedFragment:l}=t;return t.drawElement=d=>Dt(d.element)?jk:e(d),t.getRectangle=d=>Dt(d)?Fe.getRectangleByPoints(d.points):n(d),t.isHit=(d,c,h)=>{if(Dt(d)){const u=Fe.getRectangleByPoints(d.points);return c[0]>=u.x&&c[0]<=u.x+u.width&&c[1]>=u.y&&c[1]<=u.y+u.height}return r(d,c,h)},t.isRectangleHit=(d,c)=>{if(Dt(d)){const h=Fe.getRectangleByPoints(d.points),u=Fe.getRectangleByPoints([c.anchor,c.focus]);return Ok(h,u)}return s(d,c)},t.isMovable=d=>Dt(d)?!0:a(d),t.isAlign=d=>Dt(d)?!0:i(d),t.getDeletedFragment=d=>{const c=Tt(t).filter(Dt);return c.length>0&&d.push(...c),l(d)},t},Mk={pending:"○",running:"◉",completed:"✓",failed:"✗",skipped:"⊘"},ah=new Set,ih=({workflow:t,className:e="",onDelete:n,onWorkflowStateChange:r,onRetry:s,onHideForever:a})=>{var A;const i=m.useRef(!1),[l,d]=m.useState(!1),[c,h]=m.useState(!1);m.useEffect(()=>{var P;const k=t.id;if(t.createdAt&&Date.now()-t.createdAt<6e4)return;const D=(P=t.steps)==null?void 0:P.some(j=>j.status==="running"||j.status==="pending"),X=t.status==="completed"||t.status==="failed"||t.status==="cancelled";!(t.status==="running"||t.status==="pending"||D&&!X||X&&D)||i.current||ah.has(k)||(i.current=!0,ah.add(k),(async()=>{var j,N;try{const{workflowSubmissionService:B}=await Xe(async()=>{const{workflowSubmissionService:ae}=await import("./workflow-submission-service-BqiL_5Cj.js").then(te=>te.a);return{workflowSubmissionService:ae}},__vite__mapDeps([0]),import.meta.url);if(B.isWorkflowManagedByFallback(k)){const ae=B.getWorkflowFromFallback(k);if(ae){const te=ae.status;(te==="completed"||te==="failed"||te==="cancelled")&&(r==null||r(k,te==="completed"?"completed":"failed",ae.error));return}}const{swChannelClient:K}=await Xe(async()=>{const{swChannelClient:ae}=await import("./ai-chat-BnWVpTEI.js").then(te=>te.sJ);return{swChannelClient:ae}},__vite__mapDeps([0]),import.meta.url);if(!K.isInitialized()){if(await B.resumeWorkflowWithFallback(k))return;const te=B.getWorkflow(k);if(te){const Se=te.status;(Se==="completed"||Se==="failed"||Se==="cancelled")&&(r==null||r(k,Se==="completed"?"completed":"failed",te.error))}else r==null||r(k,"failed","工作流已丢失,请重试");return}const fe=await K.claimWorkflow(k);if(fe.success){const ae=(j=fe.workflow)==null?void 0:j.status;(ae==="completed"||ae==="failed"||ae==="cancelled")&&(r==null||r(k,ae==="completed"?"completed":"failed",(N=fe.workflow)==null?void 0:N.error))}else{const ae=B.getWorkflow(k);if(ae&&(ae.status==="running"||ae.status==="pending")||await B.resumeWorkflowWithFallback(k))return;r==null||r(k,"failed",fe.error||"工作流已丢失,请重试")}}catch{r==null||r(k,"failed","恢复工作流失败,请重试")}})())},[t.id,t.status,t.createdAt,r]);const u=m.useMemo(()=>{const k=t.steps,U=k.length,D=k.filter(G=>G.status==="completed").length,X=k.filter(G=>G.status==="failed").length,L=k.filter(G=>G.status==="running").length;let O="pending";return X>0?O="failed":D===U&&U>0?O="completed":(L>0||D>0)&&(O="running"),{status:O,totalSteps:U,completedSteps:D}},[t.steps]),p=u.totalSteps>0?u.completedSteps/u.totalSteps*100:0,y=m.useMemo(()=>({pending:"待开始",running:"执行中",completed:"已完成",failed:"执行失败"})[u.status],[u.status]),f=m.useMemo(()=>t.steps.find(k=>k.status==="running"),[t.steps]),g=t.generationType==="image"?"🖼️":t.generationType==="video"?"🎬":t.generationType==="audio"?"🎵":"📝",w=m.useMemo(()=>t.steps.findIndex(k=>k.status==="failed"),[t.steps]),x=u.status==="failed"&&s&&t.retryContext&&w>=0,v=m.useCallback(async()=>{if(!(!s||w<0||l)){d(!0);try{await s(t,w)}finally{d(!1)}}},[s,t,w,l]),_=m.useCallback(()=>{h(!0)},[]),T=m.useCallback(()=>{h(!1),a==null||a()},[a]),b=m.useCallback(k=>{k.stopPropagation()},[]),I=m.useCallback(k=>{k.stopPropagation(),k.preventDefault()},[]);return o.jsxs("div",{className:`workzone-content workzone-content--${u.status} ${e}`,children:[o.jsxs("div",{className:"workzone-content__header",children:[o.jsx("span",{className:"workzone-content__icon",children:g}),o.jsx("span",{className:"workzone-content__title",children:t.name}),o.jsx("span",{className:`workzone-content__status workzone-content__status--${u.status}`,children:y}),a&&o.jsx(Le,{content:"不再显示",showArrow:!1,children:o.jsx("button",{type:"button","aria-label":"不再显示",className:"workzone-content__hide-btn",onPointerDownCapture:b,onPointerDown:b,onPointerUp:b,onMouseDownCapture:b,onMouseDown:b,onClick:k=>{I(k),_()},children:o.jsx(Hy,{size:14})})}),n&&o.jsx(Le,{content:"删除",showArrow:!1,children:o.jsx("button",{type:"button","aria-label":"删除",className:"workzone-content__delete-btn",onPointerDownCapture:b,onPointerDown:b,onPointerUp:b,onMouseDownCapture:b,onMouseDown:b,onClick:k=>{I(k),n()},children:o.jsx(Gy,{size:14})})})]}),o.jsx("div",{className:"workzone-content__progress",children:o.jsx("div",{className:`workzone-content__progress-bar workzone-content__progress-bar--${u.status}`,style:{width:`${p}%`}})}),o.jsxs("div",{className:"workzone-content__progress-info",children:[o.jsxs("span",{children:[u.completedSteps,"/",u.totalSteps," 步骤"]}),f&&o.jsx("span",{className:"workzone-content__current-step",children:f.description})]}),o.jsx("div",{className:"workzone-content__steps",children:t.steps.map(k=>o.jsxs("div",{className:`workzone-content__step workzone-content__step--${k.status}`,children:[o.jsx("span",{className:"workzone-content__step-status",children:k.status==="running"?o.jsx("span",{className:"workzone-content__spinner"}):Mk[k.status]}),o.jsx("span",{className:"workzone-content__step-desc",children:k.description})]},k.id))}),u.status==="failed"&&o.jsxs("div",{className:"workzone-content__error",children:[o.jsxs("span",{children:["❌"," ",((A=t.steps.find(k=>k.status==="failed"))==null?void 0:A.error)||"执行失败"]}),x&&o.jsxs("button",{type:"button",className:"workzone-content__retry-btn",disabled:l,onPointerDownCapture:b,onPointerDown:b,onPointerUp:b,onMouseDownCapture:b,onMouseDown:b,onClick:k=>{I(k),v()},children:[o.jsx(Wy,{size:12}),o.jsx("span",{children:l?"重试中...":"从失败步骤重试"})]})]}),u.status==="completed"&&o.jsx("div",{className:"workzone-content__success",children:"✨ 已完成"}),o.jsx(Kr,{open:c,title:"隐藏进度卡片",description:"确定不再显示进度卡片?\\n\\n任务仍会在后台执行,可在设置中恢复显示。",confirmText:"确定",cancelText:"取消",onOpenChange:h,onConfirm:T})]})},Dk={width:360,height:240};function lr(t){return t&&t.type==="workzone"}function Dl(t){return Number.isFinite(t.zoom)&&t.zoom>0?1/t.zoom:1}function Wr(t){const e=Fe.getRectangleByPoints(t.points),n=Dl(t);return{...e,width:e.width*n,height:e.height*n}}function Nk(){return`workzone_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}const fr={insertWorkZone(t,e){const{workflow:n,position:r,size:s=Dk,expectedInsertPosition:a,targetFrameId:i,targetFrameDimensions:l,zoom:d}=e,c={id:Nk(),type:"workzone",points:[r,[r[0]+s.width,r[1]+s.height]],angle:0,workflow:n,createdAt:Date.now(),expectedInsertPosition:a,targetFrameId:i,targetFrameDimensions:l,zoom:d};return Lr.withoutSaving(t,()=>{ht.insertNode(t,c,[t.children.length])}),c},updateWorkflow(t,e,n){const r=t.children.findIndex(i=>i.id===e);if(r<0)return;const a={...t.children[r].workflow,...n};Lr.withoutSaving(t,()=>{ht.setNode(t,{workflow:a},[r])})},removeWorkZone(t,e){const n=t.children.findIndex(r=>r.id===e);n<0||Lr.withoutSaving(t,()=>{ht.removeNode(t,[n])})},getWorkZoneById(t,e){const n=t.children.find(r=>r.id===e);return n&&lr(n)?n:null},getAllWorkZones(t){return t.children.filter(lr)}},Co="workzone-visibility-changed";function oh(){try{return localStorage.getItem(nn.WORKZONE_CARD_VISIBLE)!=="false"}catch{return!0}}class Op extends rc{constructor(){super(...arguments),this.g=null,this.container=null,this.reactRoot=null,this.handleDelete=()=>{fr.removeWorkZone(this.board,this.element.id)},this.handleWorkflowStateChange=(e,n,r)=>{if(n==="failed"){setTimeout(()=>{fr.removeWorkZone(this.board,this.element.id)},1500);return}const s={...this.element.workflow,status:n};fr.updateWorkflow(this.board,this.element.id,s)},this.handleHideForever=()=>{try{localStorage.setItem(nn.WORKZONE_CARD_VISIBLE,"false")}catch{}window.dispatchEvent(new CustomEvent(Co))},this.handleVisibilityChange=()=>{this.container&&(this.container.style.display=oh()?"":"none")},this.handleRetry=async(e,n)=>{const r=this.board.__executeWorkflowRetry;r?await r(e,n,this.element.id):console.warn("[WorkZone] No retry handler registered on board")}}initialize(){super.initialize(),this.activeGenerator=sc(this.board,{getRectangle:e=>Wr(e),getStrokeWidth:()=>2,getStrokeOpacity:()=>1,hasResizeHandle:()=>!1}),this.createSVGStructure(),this.renderContent(),window.addEventListener(Co,this.handleVisibilityChange)}createSVGStructure(){const e=Fe.getRectangleByPoints(this.element.points),n=Wr(this.element);this.g=document.createElementNS("http://www.w3.org/2000/svg","g"),this.g.setAttribute("data-element-id",this.element.id),this.g.classList.add("plait-workzone-element"),this.g.style.pointerEvents="auto";const r=document.createElementNS("http://www.w3.org/2000/svg","foreignObject");r.setAttribute("x",String(e.x)),r.setAttribute("y",String(e.y)),r.setAttribute("width",String(n.width)),r.setAttribute("height",String(n.height)),r.style.overflow="visible",r.style.pointerEvents="auto",this.container=document.createElementNS("http://www.w3.org/1999/xhtml","div"),this.container.style.width="100%",this.container.style.height="100%",this.container.style.pointerEvents="auto",this.container.style.cursor="default",this.container.style.position="relative",this.container.classList.add("plait-workzone-container"),this.container.style.width=`${e.width}px`,this.container.style.height=`${e.height}px`,this.container.style.transform=`scale(${Dl(this.element)})`,this.container.style.transformOrigin="top left",r.appendChild(this.container),this.g.appendChild(r),this.getElementG().appendChild(this.g)}updateForeignObjectLayout(e){if(!this.g)return;const n=Fe.getRectangleByPoints(e.points),r=Wr(e),s=this.g.querySelector("foreignObject");s&&(s.setAttribute("x",String(n.x)),s.setAttribute("y",String(n.y)),s.setAttribute("width",String(r.width)),s.setAttribute("height",String(r.height))),this.container&&(this.container.style.width=`${n.width}px`,this.container.style.height=`${n.height}px`,this.container.style.transform=`scale(${Dl(e)})`)}renderContent(){this.container&&(this.container.style.display=oh()?"":"none",this.reactRoot=nc.createRoot(this.container),this.reactRoot.render(Ie.createElement(Pl,{board:this.board},Ie.createElement(ih,{workflow:this.element.workflow,onDelete:this.handleDelete,onWorkflowStateChange:this.handleWorkflowStateChange,onRetry:this.handleRetry,onHideForever:this.handleHideForever}))))}onContextChanged(e,n){e.element!==n.element&&this.g&&(this.updateForeignObjectLayout(e.element),this.reactRoot&&this.reactRoot.render(Ie.createElement(Pl,{board:this.board},Ie.createElement(ih,{workflow:e.element.workflow,onDelete:this.handleDelete,onWorkflowStateChange:this.handleWorkflowStateChange,onRetry:this.handleRetry,onHideForever:this.handleHideForever})))),this.activeGenerator.processDrawing(this.element,kt.getActiveHost(this.board),{selected:this.selected})}destroy(){window.removeEventListener(Co,this.handleVisibilityChange),this.g&&this.g.parentNode&&this.g.parentNode.removeChild(this.g),this.activeGenerator&&this.activeGenerator.destroy();const e=this.reactRoot;e&&(this.reactRoot=null,setTimeout(()=>{e.unmount()},0)),this.g=null,this.container=null,super.destroy()}}const lh=t=>{const{drawElement:e,getRectangle:n,isHit:r,isRectangleHit:s,isMovable:a}=t;return t.drawElement=i=>i.element.type==="workzone"?Op:e(i),t.getRectangle=i=>lr(i)?Wr(i):n(i),t.isHit=(i,l)=>{if(lr(i)){const d=Wr(i),[c,h]=l;return c>=d.x&&c<=d.x+d.width&&h>=d.y&&h<=d.y+d.height}return r(i,l)},t.isRectangleHit=(i,l)=>{if(lr(i)){const d=Wr(i),c=Fe.getRectangleByPoints([l.anchor,l.focus]);return Fe.isHit(d,c)}return s(i,l)},t.isMovable=i=>lr(i)?!0:a(i),t},Po=Object.freeze(Object.defineProperty({__proto__:null,WorkZoneComponent:Op,WorkZoneTransforms:fr,default:lh,isWorkZoneElement:lr,withWorkZone:lh},Symbol.toStringTag,{value:"Module"}));function Rk(){const[t,e]=m.useState(!0),[n,r]=m.useState(null),[s,a]=m.useState([]),[i,l]=m.useState(null),[d,c]=m.useState(ct.getState()),[h,u]=m.useState(0),p=m.useCallback(()=>{a(ct.getTree()),l(ct.getCurrentBoard()),c(ct.getState())},[]);m.useEffect(()=>{let P=!0;(async()=>{try{e(!0),await ct.initialize(),P&&(p(),r(null))}catch(B){P&&r(B instanceof Error?B.message:"Failed to initialize")}finally{P&&e(!1)}})();const N=ct.observeEvents().subscribe(()=>{P&&(p(),u(B=>B+1))});return()=>{P=!1,N.unsubscribe()}},[p]);const y=m.useMemo(()=>ct.hasBoards(),[h]),f=m.useCallback(async P=>{try{return r(null),await ct.createFolder(P)}catch(j){return r(j instanceof Error?j.message:"Failed to create folder"),null}},[]),g=m.useCallback(async(P,j)=>{try{return r(null),await ct.renameFolder(P,j),!0}catch(N){throw r(N instanceof Error?N.message:"Failed to rename folder"),N}},[]),w=m.useCallback(async P=>{try{return r(null),await ct.deleteFolder(P),!0}catch(j){return r(j instanceof Error?j.message:"Failed to delete folder"),!1}},[]),x=m.useCallback(async P=>{try{return r(null),await ct.deleteFolderWithContents(P),!0}catch(j){return r(j instanceof Error?j.message:"Failed to delete folder with contents"),!1}},[]),v=m.useCallback(async(P,j,N,B)=>{try{return r(null),await ct.moveFolder(P,j,N,B),!0}catch(K){throw r(K instanceof Error?K.message:"Failed to move folder"),K}},[]),_=m.useCallback(P=>{ct.toggleFolderExpanded(P)},[]),T=m.useCallback(async P=>{try{return r(null),await ct.createBoard(P)}catch(j){return r(j instanceof Error?j.message:"Failed to create board"),null}},[]),b=m.useCallback(async(P,j)=>{try{return r(null),await ct.renameBoard(P,j),!0}catch(N){throw r(N instanceof Error?N.message:"Failed to rename board"),N}},[]),I=m.useCallback(async P=>{try{return r(null),await ct.deleteBoard(P),!0}catch(j){return r(j instanceof Error?j.message:"Failed to delete board"),!1}},[]),A=m.useCallback(async(P,j,N,B)=>{try{return r(null),await ct.moveBoard(P,j,N,B),!0}catch(K){throw r(K instanceof Error?K.message:"Failed to move board"),K}},[]),k=m.useCallback(async P=>{try{return r(null),await ct.switchBoard(P)}catch(j){return r(j instanceof Error?j.message:"Failed to switch board"),null}},[]),U=m.useCallback(async P=>{const j=ct.getCurrentBoard();if(!j)return!1;try{await ct.saveBoard(j.id,P);const{markTabSyncVersion:N}=await Xe(async()=>{const{markTabSyncVersion:B}=await import("./bootstrap-CQRLkOtk.js").then(K=>K.y);return{markTabSyncVersion:B}},__vite__mapDeps([0,1]),import.meta.url);return N(j.id),!0}catch(N){return console.error("[useWorkspace] Failed to save board:",N),!1}},[]),D=m.useCallback(async P=>{try{return r(null),await ct.copyBoard(P)}catch(j){return r(j instanceof Error?j.message:"Failed to copy board"),null}},[]),X=m.useCallback(async P=>{try{return r(null),await ct.deleteBoardsBatch(P),!0}catch(j){return r(j instanceof Error?j.message:"Failed to delete boards"),!1}},[]),L=m.useCallback(async(P,j)=>{try{return r(null),await ct.moveBoardsBatch(P,j),!0}catch(N){return r(N instanceof Error?N.message:"Failed to move boards"),!1}},[]),O=m.useCallback(async P=>{try{return r(null),await ct.reorderItems(P),!0}catch(j){return r(j instanceof Error?j.message:"Failed to reorder items"),!1}},[]),G=m.useCallback(P=>{ct.setSidebarWidth(P),c(ct.getState())},[]),C=m.useCallback(P=>{ct.setSidebarCollapsed(P),c(ct.getState())},[]);return{isLoading:t,error:n,tree:s,currentBoard:i,workspaceState:d,hasBoards:y,createFolder:f,renameFolder:g,deleteFolder:w,deleteFolderWithContents:x,moveFolder:v,toggleFolderExpanded:_,createBoard:T,renameBoard:b,deleteBoard:I,moveBoard:A,copyBoard:D,switchBoard:k,saveBoard:U,deleteBoardsBatch:X,moveBoardsBatch:L,reorderItems:O,setSidebarWidth:G,setSidebarCollapsed:C,refresh:p}}const Mt=class Mt{constructor(){this.customTools=[],this.isInitialized=!1,this.initialize()}static getInstance(){return Mt.instance||(Mt.instance=new Mt),Mt.instance}getAvailableTools(){return[...Wt.getBuiltInTools(),...this.customTools]}getToolById(e){return Wt.getManifestById(e)||this.customTools.find(n=>n.id===e)||null}async initialize(){if(!this.isInitialized)try{const e=await Xt.getItem(Mt.STORAGE_KEY);e&&(this.isCompatibleVersion(e.version)?this.customTools=e.tools:(console.warn("[Toolbox] Incompatible version, resetting custom tools"),await this.resetCustomTools()))}catch(e){console.error("[Toolbox] Failed to load custom tools:",e)}finally{this.isInitialized=!0}}async saveCustomTools(){try{const e={version:Mt.STORAGE_VERSION,tools:this.customTools,updatedAt:Date.now()};await Xt.setItem(Mt.STORAGE_KEY,e)}catch(e){throw console.error("[Toolbox] Failed to save custom tools:",e),e}}async addCustomTool(e){if(this.customTools.length>=Mt.MAX_CUSTOM_TOOLS)throw new Error(`Maximum ${Mt.MAX_CUSTOM_TOOLS} custom tools allowed`);if(this.validateToolDefinition(e),this.customTools.some(s=>s.id===e.id))throw new Error(`Tool with id "${e.id}" already exists`);const r={...e,id:e.id||`custom-${Date.now()}`,category:e.category||tt.CUSTOM,defaultWidth:e.defaultWidth||800,defaultHeight:e.defaultHeight||600,permissions:e.permissions||["allow-scripts","allow-same-origin","allow-popups","allow-forms","allow-top-navigation-by-user-activation"]};this.customTools.push(r),await this.saveCustomTools()}async removeCustomTool(e){const n=this.customTools.length;this.customTools=this.customTools.filter(s=>s.id!==e);const r=this.customTools.length<n;return r&&await this.saveCustomTools(),r}async updateCustomTool(e,n){const r=this.customTools.findIndex(a=>a.id===e);if(r===-1)return!1;const s={...this.customTools[r],...n,id:e};return this.validateToolDefinition(s),this.customTools[r]=s,await this.saveCustomTools(),!0}getToolsByCategory(){const e=this.getAvailableTools(),n={};return e.forEach(r=>{const s=r.category||"utilities";n[s]||(n[s]=[]),n[s].push(r)}),n}searchTools(e){if(!e.trim())return this.getAvailableTools();const n=e.toLowerCase().trim();return this.getAvailableTools().filter(r=>{var s;return r.name.toLowerCase().includes(n)||((s=r.description)==null?void 0:s.toLowerCase().includes(n))||r.id.toLowerCase().includes(n)})}getCustomTools(){return[...this.customTools]}async clearCustomTools(){this.customTools=[],await this.saveCustomTools()}async getUpdatedAt(){try{const e=await Xt.getItem(Mt.STORAGE_KEY);return(e==null?void 0:e.updatedAt)||0}catch{return 0}}async importTools(e){let n=0,r=0;for(const s of e)this.customTools.findIndex(i=>i.id===s.id)===-1?(this.customTools.push(s),n++):r++;return n>0&&await this.saveCustomTools(),{imported:n,skipped:r}}exportTools(){return{tools:[...this.customTools],updatedAt:Date.now()}}validateToolDefinition(e){if(!e.name)throw new Error("Tool name is required");const n=!!e.url,r=!!e.component;if(!n&&!r)throw new Error("Tool must have either a URL or an internal component");if(n&&r)throw new Error("Tool cannot have both a URL and an internal component");if(e.url&&e.url.startsWith("http"))try{const s=new URL(e.url);if(!["https:","http:"].includes(s.protocol))throw new Error("Only HTTP/HTTPS URLs are allowed")}catch{throw new Error("Invalid URL format")}if(e.name.length>50)throw new Error("Tool name too long (max 50 characters)");if(e.description&&e.description.length>200)throw new Error("Tool description too long (max 200 characters)")}isCompatibleVersion(e){return e===Mt.STORAGE_VERSION}async resetCustomTools(){this.customTools=[],await this.saveCustomTools()}};Mt.STORAGE_KEY="aitu:custom-tools",Mt.STORAGE_VERSION="1.0",Mt.MAX_CUSTOM_TOOLS=50;let Nl=Mt;const jn=Nl.getInstance(),qO=Object.freeze(Object.defineProperty({__proto__:null,toolboxService:jn},Symbol.toStringTag,{value:"Module"})),ch={defaultWidth:600,defaultHeight:400},Mp={[tt.AI_TOOLS]:"AI 工具",[tt.CONTENT_TOOLS]:"内容工具",[tt.UTILITIES]:"实用工具",[tt.CUSTOM]:"自定义工具"},dh=[tt.AI_TOOLS,tt.CONTENT_TOOLS,tt.UTILITIES,tt.CUSTOM];function uh(t){const e=dh.findIndex(n=>n===t);return e>=0?e:dh.length}function Dp(t){return[...t].sort((e,n)=>uh(e)-uh(n)||e.localeCompare(n))}function YO(t){return m.useSyncExternalStore(mt.subscribe.bind(mt),()=>t(mt.getState()),()=>t(mt.getState()))}function Lk(){return m.useMemo(()=>({setQueue:(t,e)=>mt.setQueue(t,e),setReadingQueue:t=>mt.setReadingQueue(t),setPlaylistQueue:(t,e)=>mt.setQueue(t,{queueSource:"playlist",playlistId:e.playlistId,playlistName:e.playlistName}),togglePlaybackInQueue:(t,e,n)=>mt.togglePlaybackInQueue(t,e,n),togglePlayback:t=>mt.togglePlayback(t),toggleReadingPlayback:t=>mt.toggleReadingPlayback(t),toggleReadingPlaybackInQueue:(t,e,n)=>mt.toggleReadingPlaybackInQueue(t,e,n),pausePlayback:()=>mt.pausePlayback(),resumePlayback:()=>mt.resumePlayback(),playPrevious:()=>mt.playPrevious(),playNext:()=>mt.playNext(),setPlaybackMode:t=>mt.setPlaybackMode(t),setPlaybackRate:(t,e)=>mt.setPlaybackRate(t,e),seekTo:t=>mt.seekTo(t),seekToReadingSegment:t=>mt.seekToReadingSegment(t),setVolume:t=>mt.setVolume(t),stopPlayback:()=>mt.stopAndClear()}),[])}function Fk(){const t=m.useSyncExternalStore(mt.subscribe.bind(mt),mt.getState.bind(mt),mt.getState.bind(mt)),e=Lk();return{...t,...e}}const ZO=(t,e)=>na.isMindElement(t,e)||It.isDrawElement(e)&&Vy(e)||Ky(t,e)||rs.isFreehand(e)||Jn.isPenPath(e)&&e.closed,Bk=(t,e)=>{if(e.fill){if(qy(e.fill))return Yy(e.fill);if(typeof e.fill=="string")return e.fill}let n=null;if(na.isMindElement(t,e))n=Zy(t,e);else if(rs.isFreehand(e))n=Xy(t,e);else if(Jn.isPenPath(e)){const r=Zl[t.theme.themeColorMode];n=(e.closed?r==null?void 0:r.fill:"none")||"#FFFFFF"}else(It.isDrawElement(e)||It.isCustomGeometryElement(t,e))&&(n=Jy(t,e));return n},Wa=(t,e)=>{let n=e.strokeColor;if(!n)if(na.isMindElement(t,e)&&(n=Qy(t,e)),rs.isFreehand(e))n=ev(t,e);else if(Jn.isPenPath(e)){const r=Zl[t.theme.themeColorMode];n=e.strokeColor||(r==null?void 0:r.strokeColor)||"#000000"}else(It.isDrawElement(e)||It.isCustomGeometryElement(t,e))&&(n=tv(t,e));return n},XO=(t,e)=>nv(e).color,Np={project:"drawnix-drawer-pin-project",toolbox:"drawnix-drawer-pin-toolbox",task:"drawnix-drawer-pin-task"};function hh(t){try{return localStorage.getItem(t)==="true"}catch{return!1}}function zk(t,e){try{localStorage.setItem(t,String(e))}catch{}}const $k=(t,e=20)=>{if(!t)return o.jsx("span",{role:"img","aria-label":"tool",style:{fontSize:e},children:"🔧"});if(typeof t=="function"){const n=t;return o.jsx(n,{size:e})}return typeof t=="string"?o.jsx("span",{style:{fontSize:e},children:t}):Ie.isValidElement(t)?t:null},fh=({ensureToolWindowsEnabled:t})=>{const[e,n]=m.useState([]),[r,s]=m.useState(null),{language:a,t:i}=ss(),l=m.useMemo(()=>{const u=new Map,p=new Map;e.forEach(f=>{f.isLauncher||u.set(f.toolId,(u.get(f.toolId)||0)+1)});const y=new Map;return e.forEach(f=>{if(f.isLauncher)return;const g=(p.get(f.toolId)||0)+1;p.set(f.toolId,g),y.set(f.instanceId,{displayIndex:g,showBadge:(u.get(f.toolId)||0)>1})}),y},[e]);m.useEffect(()=>{const u=pt.observeToolStates().subscribe(()=>{n(pt.getToolbarTools())});return n(pt.getToolbarTools()),()=>u.unsubscribe()},[]);const d=m.useCallback((u,p)=>{if(t==null||t(),p.id==="prompt-history"&&console.info("[MinimizedToolsBar] click prompt-history",{instanceId:u.instanceId,status:u.status,isLauncher:u.isLauncher,isPinned:u.isPinned}),u.isLauncher||u.status==="closed"){const y=jn.getToolById(p.id);y?pt.openTool(y):console.warn("[MinimizedToolsBar] Tool not found:",p.id)}else pt.toggleToolVisibility(u.instanceId)},[t]),c=m.useCallback((u,p,y)=>{switch(y){case"toggle-pin":{const f=pt.isPinned(u.toolId);pt.setPinned(u.toolId,!f);break}case"close":pt.closeTool(u.instanceId);break;case"new-window":t==null||t(),pt.openNewToolInstance(p);break}},[t]),h=m.useCallback((u,p)=>{const y=u.isPinned,f=[...pt.canOpenMultiple(p)?[{content:i("toolbar.openNewWindow"),value:"new-window"}]:[],{content:y?a==="zh"?"取消常驻":"Unpin from toolbar":a==="zh"?"常驻工具栏":"Pin to toolbar",value:"toggle-pin"}];return u.isLauncher||f.push({content:a==="zh"?"关闭":"Close",value:"close",theme:"error"}),f},[a,i]);return e.length===0?null:o.jsx("div",{className:"minimized-tools-bar",children:e.map(u=>{const{tool:p}=u,y=jn.getToolById(p.id)||p,f=l.get(u.instanceId),g=u.isLauncher||!(f!=null&&f.showBadge)?y.name:`${y.name} #${f.displayIndex}`;return o.jsx(qr,{options:h(u,y),trigger:"context-menu",popupProps:{onVisibleChange:w=>{s(w?u.instanceId:null)}},onClick:w=>{c(u,y,w.value)},children:o.jsxs("div",{className:"minimized-tools-bar__item","data-minimize-target":u.instanceId,onClick:w=>{w.button===0&&(w.stopPropagation(),d(u,y))},children:[o.jsx(Xm,{type:"icon",visible:!0,selected:u.status==="open",icon:$k(y.icon),tooltip:r===u.instanceId?void 0:g,"aria-label":g,"data-track":"toolbar_click_minimized_tool","data-tool-id":y.id}),!u.isLauncher&&(f==null?void 0:f.showBadge)&&o.jsx("span",{className:"minimized-tools-bar__badge","aria-hidden":"true",children:f.displayIndex}),u.status!=="closed"&&o.jsx("div",{className:St("minimized-tools-bar__indicator",{"minimized-tools-bar__indicator--active":u.status==="open"})})]})},u.instanceId)})})},JO=Object.freeze(Object.defineProperty({__proto__:null,MinimizedToolsBar:fh,default:fh},Symbol.toStringTag,{value:"Module"}));function QO(t,e){return`${t},${e}`}function e1(t){return t?t==="sora-2"||t==="sora-2-pro":!1}function t1(t){return t?t.startsWith("sora-2:")||t.startsWith("sora-2-pro:"):!1}function Uk(t){return t==="sora-2-pro"?"sora-2-pro-character":"sora-2-character"}const Hk=({isOpen:t,onClose:e,title:n,subtitle:r,headerActions:s,pinnable:a=!1,pinned:i=!1,onPinnedChange:l,filterSection:d,children:c,footer:h,position:u="toolbar-right",width:p="narrow",customWidth:y,showBackdrop:f=!1,closeOnBackdropClick:g=!0,closeOnEsc:w=!0,zIndex:x,className:v="",headerClassName:_="",contentClassName:T="",footerClassName:b="",showCloseButton:I=!0,closeButtonSize:A="small",resizable:k=!1,minWidth:U=280,maxWidth:D=800,onWidthChange:X,"data-testid":L})=>{const[O,G]=m.useState(null),[C,P]=m.useState(!1),j=m.useRef(null),N=m.useRef(0),B=m.useRef(0),K=m.useRef("right");m.useEffect(()=>{if(!t||!w)return;const Te=ke=>{ke.key==="Escape"&&(ke.preventDefault(),e())};return window.addEventListener("keydown",Te),()=>window.removeEventListener("keydown",Te)},[t,w,e]);const fe=m.useCallback(()=>{g&&e()},[g,e]),ae=m.useCallback(()=>{l==null||l(!i)},[l,i]),te=m.useCallback(Te=>{if(Te.preventDefault(),!j.current)return;P(!0);const ke="touches"in Te?Te.touches[0].clientX:Te.clientX;N.current=ke,B.current=j.current.offsetWidth,K.current=u==="toolbar-right"&&document.documentElement.classList.contains("aitu-toolbar-dock-right")?"left":"right"},[u]);m.useEffect(()=>{if(!C)return;const Te=ne=>{const M="touches"in ne?ne.touches[0].clientX:ne.clientX,q=K.current==="left"?N.current-M:M-N.current,R=Math.min(D,Math.max(U,B.current+q));G(R)},ke=()=>{P(!1),O!==null&&(X==null||X(O))};return document.addEventListener("mousemove",Te),document.addEventListener("mouseup",ke),document.addEventListener("touchmove",Te,{passive:!1}),document.addEventListener("touchend",ke),document.addEventListener("touchcancel",ke),()=>{document.removeEventListener("mousemove",Te),document.removeEventListener("mouseup",ke),document.removeEventListener("touchmove",Te),document.removeEventListener("touchend",ke),document.removeEventListener("touchcancel",ke)}},[C,O,U,D,X]);const Se=["side-drawer",`side-drawer--${u}`,`side-drawer--${p}`,t?"side-drawer--open":"",C?"side-drawer--dragging":"",k?"side-drawer--resizable":"",v].filter(Boolean).join(" "),Ee={};return O!==null?Ee.width=`${O}px`:y&&(Ee.width=typeof y=="number"?`${y}px`:y),x!==void 0&&(Ee.zIndex=x),o.jsxs(o.Fragment,{children:[o.jsxs("div",{ref:j,className:Se,style:Ee,"data-testid":L,children:[o.jsxs("div",{className:`side-drawer__header ${_}`,children:[o.jsxs("div",{className:"side-drawer__header-left",children:[o.jsx("h3",{className:"side-drawer__title",children:n}),r&&o.jsx("span",{className:"side-drawer__subtitle",children:r})]}),o.jsxs("div",{className:"side-drawer__header-right",children:[s,a&&o.jsx(Le,{content:i?"取消固定":"固定,不自动收起",showArrow:!1,children:o.jsx(Me,{variant:"text",size:A,icon:i?o.jsx(Lf,{}):o.jsx(Ff,{}),onClick:ae,className:`side-drawer__pin-btn${i?" side-drawer__pin-btn--active":""}`,"aria-label":i?"取消固定抽屉":"固定抽屉"})}),I&&o.jsx(Le,{content:"关闭",showArrow:!1,children:o.jsx(Me,{variant:"text",size:A,icon:o.jsx(Bf,{}),onClick:e,className:"side-drawer__close-btn"})})]})]}),d&&o.jsx("div",{className:"side-drawer__filter",children:d}),o.jsx("div",{className:`side-drawer__content ${T}`,children:c}),h&&o.jsx("div",{className:`side-drawer__footer ${b}`,children:h}),k&&o.jsx("div",{className:"side-drawer__resize-handle",onMouseDown:te,onTouchStart:te})]}),f&&t&&o.jsx("div",{className:"side-drawer__backdrop",onClick:fe,style:x!==void 0?{zIndex:x-1}:void 0})]})},Rp=({storageKey:t,pinStorageKey:e,defaultWidth:n,minWidth:r=300,maxWidth:s=1024,resizable:a=!0,pinnable:i,...l})=>{const[d,c]=m.useState(()=>{if(t)try{const f=localStorage.getItem(t);if(f){const g=parseInt(f,10);if(!isNaN(g)&&g>=r&&g<=s)return g}}catch{}}),[h,u]=m.useState(()=>e?hh(e):!1),p=m.useCallback(f=>{if(c(f),t)try{localStorage.setItem(t,String(f))}catch{}},[t]);m.useEffect(()=>{if(t)try{const f=localStorage.getItem(t);if(f){const g=parseInt(f,10);!isNaN(g)&&g>=r&&g<=s&&c(g)}}catch{}},[t,r,s]),m.useEffect(()=>{e&&u(hh(e))},[e]);const y=m.useCallback(f=>{u(f),e&&zk(e,f)},[e]);return o.jsx(Hk,{...l,pinnable:i||!!e,pinned:h,onPinnedChange:y,resizable:a,minWidth:r,maxWidth:s,customWidth:d||n,onWidthChange:p})},Eo="avatar-",Cr=Xt.createInstance({name:"drawnix",storeName:"character-avatars",description:"Character avatar cache"});class Gk{constructor(){this.objectUrlCache=new Map}async cacheAvatar(e,n){try{if(await this.getCachedAvatar(e))return!0;const s=await this.fetchImageAsBlob(n);if(!s)throw new Error("Failed to fetch avatar image");const a=s.type||"image/png",i={characterId:e,blob:s,mimeType:a,size:s.size,cachedAt:Date.now(),originalUrl:n};return await Cr.setItem(`${Eo}${e}`,i),!0}catch(r){return console.error("[AvatarCache] Failed to cache avatar:",e,r),!1}}async fetchImageAsBlob(e){return new Promise(n=>{const r=new Image;r.crossOrigin="anonymous",r.onload=()=>{try{const s=document.createElement("canvas");s.width=r.naturalWidth,s.height=r.naturalHeight;const a=s.getContext("2d");if(!a){n(null);return}a.drawImage(r,0,0),s.toBlob(i=>{n(i)},"image/png")}catch(s){console.warn("[AvatarCache] Canvas draw failed:",s),n(null)}},r.onerror=()=>{console.warn("[AvatarCache] Image load failed for:",e),n(null)},r.src=e})}async getCachedAvatar(e){try{return await Cr.getItem(`${Eo}${e}`)||null}catch(n){return console.error("[AvatarCache] Failed to get cached avatar:",e,n),null}}async getCachedUrl(e){const n=this.objectUrlCache.get(e);if(n)return n;const r=await this.getCachedAvatar(e);if(r!=null&&r.blob){if(this.objectUrlCache.size>=50){const i=this.objectUrlCache.keys().next().value;i&&(URL.revokeObjectURL(this.objectUrlCache.get(i)),this.objectUrlCache.delete(i))}const a=URL.createObjectURL(r.blob);return this.objectUrlCache.set(e,a),a}return null}async getAvatarUrl(e,n){const r=await this.getCachedUrl(e);return r||(this.cacheAvatar(e,n).catch(()=>{}),n)}async isCached(e){return await this.getCachedAvatar(e)!==null}async deleteCache(e){try{const n=this.objectUrlCache.get(e);return n&&(URL.revokeObjectURL(n),this.objectUrlCache.delete(e)),await Cr.removeItem(`${Eo}${e}`),!0}catch(n){return console.error("[AvatarCache] Failed to delete avatar cache:",e,n),!1}}async clearAll(){try{return this.objectUrlCache.forEach(e=>{URL.revokeObjectURL(e)}),this.objectUrlCache.clear(),await Cr.clear(),!0}catch(e){return console.error("[AvatarCache] Failed to clear all caches:",e),!1}}async getTotalCacheSize(){try{let e=0;return await Cr.iterate(n=>{n!=null&&n.size&&(e+=n.size)}),e}catch(e){return console.error("[AvatarCache] Failed to get cache size:",e),0}}async getCacheCount(){try{return await Cr.length()}catch(e){return console.error("[AvatarCache] Failed to get cache count:",e),0}}cleanup(){this.objectUrlCache.forEach(e=>{URL.revokeObjectURL(e)}),this.objectUrlCache.clear()}}const Va=new Gk,mh="sora-characters",ph=Xt.createInstance({name:"drawnix",storeName:"characters",description:"Sora character storage"});class Wk{constructor(){this.characters$=new si([]),this.initialized=!1,this.init()}async init(){if(!this.initialized)try{const e=await this.loadFromStorage();this.characters$.next(e),this.initialized=!0}catch(e){console.error("[CharacterStorage] Failed to initialize:",e),this.characters$.next([]),this.initialized=!0}}getCharacters$(){return this.characters$.asObservable()}getCharacters(){return this.characters$.getValue()}getCharactersByStatus(e){return this.getCharacters().filter(n=>n.status===e)}getCharacterById(e){return this.getCharacters().find(n=>n.id===e)}getCharactersBySourceTask(e){return this.getCharacters().filter(n=>n.sourceTaskId===e)}async saveCharacter(e){const n=this.getCharacters(),r=n.findIndex(s=>s.id===e.id);r>=0?n[r]=e:n.push(e),await this.saveToStorage(n),this.characters$.next([...n]),e.status==="completed"&&e.profilePictureUrl&&Va.cacheAvatar(e.id,e.profilePictureUrl).catch(s=>console.warn("[CharacterStorage] Failed to cache avatar:",s))}async updateCharacter(e,n){const r=this.getCharacters(),s=r.findIndex(i=>i.id===e);if(s<0)return console.warn("[CharacterStorage] Character not found:",e),null;const a={...r[s],...n};return r[s]=a,await this.saveToStorage(r),this.characters$.next([...r]),a.status==="completed"&&a.profilePictureUrl&&Va.cacheAvatar(e,a.profilePictureUrl).catch(i=>console.warn("[CharacterStorage] Failed to cache avatar:",i)),a}async updateCharacterStatus(e,n,r){const s={status:n};return n==="completed"&&(s.completedAt=Date.now()),r&&(s.error=r),this.updateCharacter(e,s)}async deleteCharacter(e){const n=this.getCharacters(),r=n.findIndex(s=>s.id===e);return r<0?(console.warn("[CharacterStorage] Character not found for deletion:",e),!1):(n.splice(r,1),await this.saveToStorage(n),this.characters$.next([...n]),Va.deleteCache(e).catch(s=>console.warn("[CharacterStorage] Failed to delete avatar cache:",s)),!0)}async deleteCharactersBySourceTask(e){const n=this.getCharacters(),r=n.length,s=n.filter(i=>i.sourceTaskId!==e);return s.length===r?0:(await this.saveToStorage(s),this.characters$.next(s),r-s.length)}async clearAll(){await this.saveToStorage([]),this.characters$.next([])}getPendingCharacters(){return this.getCharacters().filter(e=>e.status==="pending"||e.status==="processing")}async loadFromStorage(){try{return await ph.getItem(mh)||[]}catch(e){return console.error("[CharacterStorage] Load error:",e),[]}}async saveToStorage(e){try{await ph.setItem(mh,e)}catch(n){throw console.error("[CharacterStorage] Save error:",n),n}}}const Qs=new Wk,Et=rv("CharacterAPI"),gh={ACCEPTED:202,NOT_FOUND:404};class Vk{get baseUrl(){return(ln.get().baseUrl||"https://api.tu-zi.com/v1").replace(/\/v1\/?$/,"")}async createCharacter(e){const r=ln.get().apiKey;if(!r)throw new Error("API Key 未配置,请先配置 API Key");const s=Uk(e.sourceModel);Et.debug("Creating character from video:",e.videoTaskId),Et.debug("Source model:",e.sourceModel,"-> Character model:",s),Et.debug("Timestamps:",e.characterTimestamps||"default");const a=new FormData;a.append("character_from_task",e.videoTaskId),a.append("model",s),e.characterTimestamps&&a.append("character_timestamps",e.characterTimestamps);const i=await fetch(`${this.baseUrl}/v1/videos`,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:a});if(!i.ok){const d=await i.text();Et.error("Create failed:",i.status,d);const c=new Error(`角色创建失败: ${i.status} - ${d}`);throw c.apiErrorBody=d,c.httpStatus=i.status,c}const l=await i.json();return Et.debug("Character created:",l),l}async queryCharacter(e){const r=ln.get().apiKey;if(!r)throw new Error("API Key 未配置");const s=await fetch(`${this.baseUrl}/v1/videos/${e}`,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!s.ok){const i=await s.text();if(Et.error("Query failed:",s.status,i),s.status===gh.NOT_FOUND||s.status===gh.ACCEPTED)throw new Error("CHARACTER_PROCESSING");const l=new Error(`角色查询失败: ${s.status} - ${i}`);throw l.apiErrorBody=i,l.httpStatus=s.status,l}const a=await s.json();return Et.debug("Character query result:",a),a}async createCharacterWithPolling(e,n={}){const{interval:r=3e3,maxAttempts:s=60,onStatusChange:a}=n;Et.debug("Submitting character creation...");const l=(await this.createCharacter(e)).id;Et.debug("Character creation submitted:",l),a&&a("processing");let d=0;for(;d<s;){await this.sleep(r),d++;try{Et.debug(`Polling attempt ${d}/${s}...`);const c=await this.queryCharacter(l);if(c.username&&c.profile_picture_url)return Et.debug("Character ready:",c.username),a&&a("completed"),{...c,characterId:l}}catch(c){if(c.message==="CHARACTER_PROCESSING"){Et.debug("Character still processing...");continue}if(Et.warn("Query error:",c.message),d>=s)throw a&&a("failed"),c}}throw a&&a("failed"),new Error("角色创建超时,请稍后重试")}async resumePolling(e,n={}){const{onStatusChange:r}=n;Et.debug("Resuming poll for character:",e);try{const s=await this.queryCharacter(e);if(s.username&&s.profile_picture_url)return Et.debug("Character already ready:",s.username),r&&r("completed"),s}catch(s){if(s.message!=="CHARACTER_PROCESSING")throw s}return this.pollUntilComplete(e,n)}async pollUntilComplete(e,n={}){const{interval:r=3e3,maxAttempts:s=60,onStatusChange:a}=n;let i=0;for(;i<s;){await this.sleep(r),i++;try{Et.debug(`Poll attempt ${i}/${s}...`);const l=await this.queryCharacter(e);if(l.username&&l.profile_picture_url)return Et.debug("Character ready:",l.username),a&&a("completed"),l}catch(l){if(l.message==="CHARACTER_PROCESSING")continue;if(i>=s)throw a&&a("failed"),l}}throw a&&a("failed"),new Error("角色创建超时,请稍后重试")}sleep(e){return new Promise(n=>setTimeout(n,e))}}const Kk=new Vk;function Ao(t){var n;const e=((n=t==null?void 0:t.clips)==null?void 0:n.map(r=>typeof r.audioUrl=="string"?r.audioUrl.trim():"").filter(r=>!!r))||[];return e.length>0?e:Array.isArray(t==null?void 0:t.urls)&&t.urls.length>0?t.urls.filter(r=>typeof r=="string"&&r.trim().length>0):typeof(t==null?void 0:t.url)=="string"&&t.url.trim().length>0?[t.url]:[]}const qk="aitu:ai-input-focus",Yk="aitu:ai-input-prefill";function Zk(t={}){typeof window>"u"||window.dispatchEvent(new CustomEvent(qk,{detail:t}))}function n1(t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Yk,{detail:t}))}const Xk=m.lazy(()=>Xe(()=>import("./batch-image-generation-CkmX4dem.js"),__vite__mapDeps([0,2]),import.meta.url)),Jk={width:"100%",height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",boxSizing:"border-box"},Qk=({message:t="加载中..."})=>o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:200,color:"#999",fontSize:14},children:t}),eC=()=>o.jsx("style",{children:`
|
|
191
191
|
.tool-adapter-container .batch-image-generation {
|
|
192
192
|
height: 100% !important;
|
|
193
193
|
max-height: 100% !important;
|
|
194
194
|
overflow: auto !important;
|
|
195
195
|
}
|
|
196
|
-
`}),Lp=t=>o.jsxs("div",{className:"tool-adapter-container",style:Jk,children:[o.jsx(eC,{}),o.jsx(m.Suspense,{fallback:o.jsx(Qk,{}),children:o.jsx(Xk,{...t})})]}),tC={manifest:{id:"batch-image",name:"批量出图工具",description:"Excel式批量AI图片生成,支持批量编辑、图片参考和历史追踪",icon:Ie.createElement(Mf),category:tt.AI_TOOLS,component:"batch-image",defaultWidth:1200,defaultHeight:800},Component:Lp},nC=Object.freeze(Object.defineProperty({__proto__:null,BatchImageToolComponent:Lp,batchImageTool:tC},Symbol.toStringTag,{value:"Module"})),rC=m.lazy(()=>Xe(()=>import("./ModelBenchmarkWorkbench-
|
|
196
|
+
`}),Lp=t=>o.jsxs("div",{className:"tool-adapter-container",style:Jk,children:[o.jsx(eC,{}),o.jsx(m.Suspense,{fallback:o.jsx(Qk,{}),children:o.jsx(Xk,{...t})})]}),tC={manifest:{id:"batch-image",name:"批量出图工具",description:"Excel式批量AI图片生成,支持批量编辑、图片参考和历史追踪",icon:Ie.createElement(Mf),category:tt.AI_TOOLS,component:"batch-image",defaultWidth:1200,defaultHeight:800},Component:Lp},nC=Object.freeze(Object.defineProperty({__proto__:null,BatchImageToolComponent:Lp,batchImageTool:tC},Symbol.toStringTag,{value:"Module"})),rC=m.lazy(()=>Xe(()=>import("./ModelBenchmarkWorkbench-CK33zizl.js"),__vite__mapDeps([0,3]),import.meta.url)),sC={width:"100%",height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",boxSizing:"border-box"},aC=()=>o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:200,color:"#999",fontSize:14},children:"加载中..."}),Fp=t=>o.jsx("div",{style:sC,children:o.jsx(m.Suspense,{fallback:o.jsx(aC,{}),children:o.jsx(rC,{...t})})}),iC={manifest:{id:ni,name:"模型测试",description:"批量比较图、文、视频、音频模型的速度与主观效果",icon:"🧪",category:tt.AI_TOOLS,component:ni,defaultWidth:1280,defaultHeight:860},Component:Fp},oC=Object.freeze(Object.defineProperty({__proto__:null,ModelBenchmarkToolComponent:Fp,modelBenchmarkTool:iC},Symbol.toStringTag,{value:"Module"})),lC=m.lazy(()=>Xe(()=>import("./PromptHistoryTool-q6vOxFr6.js"),__vite__mapDeps([0,4]),import.meta.url)),cC={width:"100%",height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",boxSizing:"border-box"},dC=()=>o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:200,color:"#999",fontSize:14},children:"加载中..."}),Bp=({initialCategory:t})=>o.jsx("div",{style:cC,children:o.jsx(m.Suspense,{fallback:o.jsx(dC,{}),children:o.jsx(lC,{initialCategory:t})})}),uC={manifest:{id:"prompt-history",name:"我的提示词",description:"按任务分类管理初始提示词、发送提示词和生成结果预览",icon:o.jsx(ec,{size:18,strokeWidth:1.75}),category:tt.CONTENT_TOOLS,component:"prompt-history",defaultWidth:1120,defaultHeight:680},Component:Bp},hC=Object.freeze(Object.defineProperty({__proto__:null,PromptHistoryToolComponent:Bp,promptHistoryTool:uC},Symbol.toStringTag,{value:"Module"})),fC=m.lazy(()=>Xe(()=>import("./KnowledgeBaseContent-CAq5kXdt.js"),__vite__mapDeps([0,5,1,6,7]),import.meta.url)),mC=({message:t="加载中..."})=>o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:200,color:"#999",fontSize:14},children:t}),zp=({initialNoteId:t})=>o.jsx("div",{className:"tool-adapter-container",style:{width:"100%",height:"100%"},children:o.jsx(m.Suspense,{fallback:o.jsx(mC,{message:"加载知识库..."}),children:o.jsx(fC,{initialNoteId:t})})}),pC={manifest:{id:"knowledge-base",name:"知识库",description:"个人知识管理工具,支持目录分类、标签管理和 Markdown 编辑",icon:Ie.createElement(Nf),category:tt.UTILITIES,component:"knowledge-base",defaultWidth:900,defaultHeight:700},Component:zp},gC=Object.freeze(Object.defineProperty({__proto__:null,KnowledgeBaseToolComponent:zp,knowledgeBaseTool:pC},Symbol.toStringTag,{value:"Module"})),yC=({contextMenu:t,playlists:e,playlistItems:n,favoriteAssetIds:r,selectedPlaylistId:s,currentPlaylistItemKeys:a,onClose:i,onToggleFavorite:l,onAddToPlaylist:d,onRemoveFromPlaylist:c,onCreatePlaylistAndAdd:h})=>{if(!t)return null;const u=[];return Fr(t.item)&&u.push({key:"favorite",label:p=>Fr(p)&&r.has(p.assetId)?"取消收藏":"加入收藏",icon:o.jsx(zf,{size:14}),onSelect:p=>{Fr(p)&&l(p.assetId)}}),u.push({key:"playlist-actions",type:"submenu",label:"添加到播放列表",icon:o.jsx(rd,{size:14}),children:p=>e.map(y=>{const f=(n[y.id]||[]).map(g=>sv(g)).some(g=>g?Ma(g)===Ma(p):!1);return{key:`playlist-${y.id}`,label:f?`已在 ${y.name}`:`添加到 ${y.name}`,icon:o.jsx(rd,{size:14}),disabled:f,onSelect:()=>d(p,y.id)}})}),s&&(a!=null&&a.has(Ma(t.item)))&&c&&u.push({key:"remove-from-current",label:"从当前播放列表移除",icon:o.jsx(av,{size:14}),danger:!0,onSelect:p=>c(p,s)}),u.push({key:"create-playlist",label:"新建播放列表并添加",icon:o.jsx(iv,{size:14}),onSelect:p=>h(p)}),o.jsx(ac,{state:{x:t.x,y:t.y,payload:t.item},items:u,onClose:i})};function $p(t){return lv(t).replace(/\u00a0/g," ").replace(/[ \t]+\n/g,`
|
|
197
197
|
`).replace(/\n{3,}/g,`
|
|
198
198
|
|
|
199
199
|
`).trim()}function vC(t){const e=t.trim();return e?e.split(new RegExp("(?<=[。!?!?;;])","u")).map(r=>r.trim()).filter(Boolean).flatMap(r=>r.length<=56?[r]:r.split(new RegExp("(?<=[,、,::])","u")).map(s=>s.trim()).filter(Boolean).flatMap(s=>{if(s.length<=56)return[s];const a=[];for(let i=0;i<s.length;i+=56)a.push(s.slice(i,i+56).trim());return a.filter(Boolean)})):[]}function wC(t,e){const n=Math.max(.5,Math.min(e||1,2)),r=(t.match(/[\u4e00-\u9fff]/gu)||[]).length,s=(t.match(/[A-Za-z]+(?:'[A-Za-z]+)*/g)||[]).length,a=(t.match(/\d/g)||[]).length,i=(t.match(/[,。!?!?;;、,::]/gu)||[]).length,l=Math.max(0,t.replace(/\s+/g,"").length-r-a-t.replace(/[^A-Za-z]/g,"").length),d=r*210+s*320+a*140+l*90+i*180+420;return Math.max(900,Math.min(12e3,Math.round(d/n)))}function xC(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return Math.abs(e>>>0).toString(36)}function bC(t,e=$f.rate){const n=$p(t);if(!n)return[];const s=n.split(/\n{2,}/).map(d=>d.trim()).filter(Boolean).flatMap(d=>vC(d)),a=(s.length>0?s:[n]).filter(Boolean);let i=0,l=0;return a.map((d,c)=>{const h=d.trim(),u=wC(h,e),p=i;i+=h.length;const y={id:`segment-${c+1}`,text:h,startMs:l,endMs:l+u,charStart:p,charEnd:i};return l+=u,y})}function _C(t){var i;const e=$p(t.content);if(!e)return null;const n={...$f,...ws.get()||{}},r=((i=t.title)==null?void 0:i.trim())||"朗读轨道",s=bC(e,n.rate),a=xC(`${r}
|
|
200
200
|
${e}`);return{elementId:t.elementId,readingSourceId:`${t.origin.kind}:${t.origin.id}:${a}`,title:r,plainText:e,segments:s,preferredLanguage:t.preferredLanguage||ov(e),previewImageUrl:t.previewImageUrl,origin:t.origin}}function TC(){const[t,e]=m.useState([]),n=m.useRef(new Map),r=m.useCallback(async()=>{const i=await sd.getAllNoteMetas();e(i.sort((l,d)=>d.updatedAt-l.updatedAt))},[]);m.useEffect(()=>{r()},[r]);const s=m.useCallback(async i=>{var h;const l=n.current.get(i);if(l)return l;const d=await sd.getNoteById(i);if(!d||!((h=d.content)!=null&&h.trim()))return null;const c=_C({elementId:`kb-note:${d.id}`,title:d.title||"知识库笔记",content:[d.title,d.content].filter(Boolean).join(`
|
|
201
201
|
|
|
202
|
-
`),origin:{kind:"kb-note",id:d.id}});return c&&n.current.set(i,c),c},[]),a=m.useCallback(async i=>{const l=[];if(i){const d=await s(i);d&&l.push(d)}for(const d of t){if(d.id===i)continue;const c=await s(d.id);c&&l.push(c)}return l},[t,s]);return{noteMetas:t,refresh:r,loadReadingSource:s,buildReadingQueue:a}}const Ka=new Map,jo=new Map;function Up(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function SC(t){const e=jo.get(t);if(e)return e;const n=new Promise(r=>{const s=new Audio;s.preload="metadata";const a=()=>{s.removeEventListener("loadedmetadata",i),s.removeEventListener("error",l),s.src="",s.load(),jo.delete(t),r()},i=()=>{Up(s.duration)&&Ka.set(t,s.duration),a()},l=()=>{a()};s.addEventListener("loadedmetadata",i),s.addEventListener("error",l),s.src=t});return jo.set(t,n),n}function yh(t){const e=m.useRef(Ka),[,n]=m.useState(0);return m.useEffect(()=>{let r=!1;const s=[];return t.forEach(a=>{if(a.audioUrl){if(Up(a.duration)){Ka.set(a.audioUrl,a.duration);return}Ka.has(a.audioUrl)||s.push(SC(a.audioUrl).then(()=>{r||n(i=>i+1)}))}}),()=>{r=!0}},[t]),e.current}const vh=({items:t,onSelect:e,onContextMenu:n,onToggleFavorite:r,onTogglePlayback:s,showFavoriteButton:a=!1,showPlaybackIndicator:i=!1,className:l,itemClassName:d,onOpenKnowledgeBase:c})=>o.jsx("div",{className:St("audio-track-list",l),children:t.map(h=>o.jsxs("div",{role:"button",tabIndex:0,className:St("audio-track-list__item",d,{"audio-track-list__item--active":h.isActive}),onClick:()=>e(h),onContextMenu:u=>n==null?void 0:n(h,u),onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),e(h))},children:[o.jsx("div",{className:"audio-track-list__cover",children:o.jsx(Uf,{src:h.previewImageUrl,alt:h.title,fallbackClassName:"audio-track-list__cover audio-track-list__cover--fallback",iconSize:16,loading:"lazy"})}),o.jsxs("div",{className:"audio-track-list__meta",children:[o.jsx("div",{className:"audio-track-list__title",children:h.title}),o.jsx("div",{className:"audio-track-list__subtitle",children:h.subtitle||"--:--"})]}),a||i?o.jsxs("div",{className:"audio-track-list__trailing",onClick:u=>u.stopPropagation(),onPointerDown:u=>u.stopPropagation(),children:[h.noteId&&c?o.jsx(Le,{content:"打开知识库笔记",showArrow:!1,children:o.jsx("button",{type:"button",className:"audio-track-list__action-btn",onClick:()=>c(h.noteId),"aria-label":"打开知识库笔记",children:o.jsx(cv,{size:14})})}):null,a&&h.canFavorite!==!1?o.jsx("button",{type:"button",className:St("audio-track-list__favorite-btn",{"audio-track-list__favorite-btn--active":h.isFavorite}),onClick:()=>r==null?void 0:r(h),"aria-label":h.isFavorite?"取消收藏":"加入收藏",children:o.jsx(zf,{size:14,fill:h.isFavorite?"currentColor":"none"})}):null,i?o.jsx("button",{type:"button",className:"audio-track-list__status",onClick:()=>s==null?void 0:s(h),"aria-label":h.isPlaying?"暂停播放":"开始播放",children:h.isPlaying?o.jsx(Hf,{size:16}):o.jsx(ic,{size:16})}):null]}):null]},h.id))}),IC=({showPlaybackQueue:t,queueListItems:e,listItems:n,emptyLabel:r,onPlayQueueItem:s,onPlayListItem:a,onContextMenu:i,onToggleFavorite:l,onOpenKnowledgeBase:d})=>t?o.jsx(vh,{className:"audio-track-list--queue",items:e,onSelect:c=>s(c.id),onContextMenu:(c,h)=>{c.playlistItemRef&&(h.preventDefault(),h.stopPropagation(),i(c.playlistItemRef,h.clientX,h.clientY))},onToggleFavorite:c=>{c.assetId&&l(c.assetId)},onTogglePlayback:c=>s(c.id),onOpenKnowledgeBase:d,showFavoriteButton:!0,showPlaybackIndicator:!0}):n.length===0?o.jsxs("div",{className:"music-player-tool__empty",children:[o.jsx(tc,{size:18}),o.jsx("span",{children:r})]}):o.jsx(vh,{items:n,onSelect:a,onContextMenu:(c,h)=>{c.playlistItemRef&&(h.preventDefault(),h.stopPropagation(),i(c.playlistItemRef,h.clientX,h.clientY))},onToggleFavorite:c=>{c.assetId&&l(c.assetId)},onTogglePlayback:a,onOpenKnowledgeBase:d,showFavoriteButton:!0,showPlaybackIndicator:!0}),Oo={width:520,height:640},wh={width:860,height:640},Hp={sequential:o.jsx(Tv,{size:16}),"list-loop":o.jsx(_v,{size:16}),"single-loop":o.jsx(bv,{size:16}),shuffle:o.jsx(xv,{size:16})},kC=Object.keys(el).map(t=>({value:t,content:el[t],prefixIcon:Hp[t]}));function CC(t,e){return wv(e).map(n=>{const r=Gf(n),s=Math.abs(n-t)<.001;return{value:n,content:s?`✓ ${r}`:r}})}function qa(t){if(typeof t!="number"||!Number.isFinite(t)||t<=0)return"--:--";const e=Math.floor(t),n=Math.floor(e/60),r=e%60;return`${n}:${String(r).padStart(2,"0")}`}function PC(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?"--:--":new Date(t).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})}function Mo(t,e){const n=qa(t);return n!=="--:--"?n:PC(e)}function EC(t){window.dispatchEvent(new CustomEvent("kb:open",{detail:{noteId:t}}))}function AC(t){return t!=null}const jC=({toolInstanceId:t})=>{var Ot;const e=t||ri,{assets:n,loadAssets:r}=dv(),{playlists:s,playlistItems:a,favoriteAssetIds:i,createPlaylist:l,renamePlaylist:d,deletePlaylist:c,addItemToPlaylist:h,removeItemFromPlaylist:u,toggleFavorite:p,getPlaylistItemRefs:y}=uv(),f=Fk(),g=f.queueSource==="reading",{noteMetas:w,loadReadingSource:x,buildReadingQueue:v}=TC(),[_,T]=m.useState(""),[b,I]=m.useState(()=>f.activePlaylistId?f.activePlaylistId:f.queueSource==="reading"?kn:hn),A=b===kn,[k,U]=m.useState(!1),[D,X]=m.useState(""),[L,O]=m.useState(null),[G,C]=m.useState(null),[P,j]=m.useState("create"),[N,B]=m.useState(null),K=m.useRef(f.activePlaylistId||(f.queueSource==="reading"?kn:hn));m.useEffect(()=>{r()},[r]),m.useEffect(()=>{const $=()=>{O(null)};return document.addEventListener("click",$),document.addEventListener("scroll",$,!0),()=>{document.removeEventListener("click",$),document.removeEventListener("scroll",$,!0)}},[]);const fe=_.trim().toLowerCase(),ae=m.useMemo(()=>n.filter($=>$.type===Br.AUDIO),[n]),te=m.useMemo(()=>new Map(ae.map($=>[$.id,$])),[ae]),Se=m.useMemo(()=>new Map(w.map($=>[$.id,$])),[w]),Ee=m.useMemo(()=>ae.filter($=>fe.length===0?!0:$.name.toLowerCase().includes(fe)).sort(($,Oe)=>Oe.createdAt-$.createdAt),[fe,ae]),Te=m.useMemo(()=>b!==hn&&b!==kn?y(b):[],[y,b]),ke=f.queue.length>0&&(g||!!f.activeAudioUrl),ne=f.mediaType==="reading"?"reading":"audio",M=f.activePlaylistId||(g?kn:f.queueSource==="playlist"?f.activePlaylistId||hn:hn),q=ke&&b===M,R=m.useMemo(()=>CC(f.effectivePlaybackRate,ne),[f.effectivePlaybackRate,ne]),J=Gf(f.effectivePlaybackRate),Ce=`${f.mediaType==="reading"?"语音速度":"播放速度"} ${J}`,re=m.useMemo(()=>ke?M===ad?[{id:ad,label:f.activePlaylistName||hv,count:f.queue.length,type:"audio"}]:M===id?[{id,label:f.activePlaylistName||fv,count:f.queue.length,type:"reading"}]:[]:[],[f.activePlaylistName,f.queue.length,M,ke]);m.useEffect(()=>{if(!ke){K.current=M;return}I($=>$===M?$:K.current!==M?M:$),K.current=M},[M,ke]);const ze=m.useMemo(()=>f.queue.filter($=>!er($)),[f.queue]),V=yh(ze),z=m.useMemo(()=>ae.map($=>({audioUrl:$.url})),[ae]),F=yh(z),pe=($,Oe)=>er($)?$.readingSourceId:`${$.audioUrl}-${Oe}`,ce=$=>{const Oe=te.get($);return Oe?{elementId:`asset:${Oe.id}`,audioUrl:Oe.url,title:Oe.name,duration:Oe.duration,previewImageUrl:Oe.thumbnail,clipId:Oe.clipId,providerTaskId:Oe.providerTaskId}:null},Z=m.useMemo(()=>f.queue.map(($,Oe)=>{var Qe,Pt,Ft,la;if(er($)){const Qn=((Qe=$.segments[$.segments.length-1])==null?void 0:Qe.endMs)||0,un=$.origin.kind==="kb-note"?$.origin.id:void 0;return{id:pe($,Oe),title:$.title||"朗读轨道",subtitle:qa(Qn/1e3),previewImageUrl:$.previewImageUrl,isActive:Oe===f.activeQueueIndex,isPlaying:Oe===f.activeQueueIndex&&f.playing,canFavorite:!1,noteId:un,playlistItemRef:un?{kind:"reading",noteId:un}:void 0}}const Ze=(Pt=$.elementId)!=null&&Pt.startsWith("asset:")?$.elementId.slice(6):((Ft=n.find(Qn=>Qn.type===Br.AUDIO&&Qn.url===$.audioUrl))==null?void 0:Ft.id)||null;return{id:pe($,Oe),title:$.title||"未命名音频",subtitle:Mo(V.get($.audioUrl)??$.duration,Ze?(la=te.get(Ze))==null?void 0:la.createdAt:void 0),previewImageUrl:$.previewImageUrl,isActive:Oe===f.activeQueueIndex,isPlaying:Oe===f.activeQueueIndex&&f.playing,isFavorite:Ze?i.has(Ze):!1,canFavorite:!!Ze,assetId:Ze||void 0,playlistItemRef:Ze?{kind:"asset",assetId:Ze}:void 0}}),[te,n,i,f.activeQueueIndex,f.playing,f.queue,V]),ue=async $=>{const Oe=f.queue.find((Ze,Qe)=>pe(Ze,Qe)===$);if(Oe){if(er(Oe)){f.toggleReadingPlayback(Oe);return}await f.togglePlayback(Oe)}},ye=s.find($=>$.id===b)||null,ie=m.useMemo(()=>new Set(Te.map($=>Ma($))),[Te]),Ae=m.useMemo(()=>{var Ze;const $=(Ze=f.activeElementId)!=null&&Ze.startsWith("asset:")?f.activeElementId.slice(6):null;if($)return te.get($)||null;const Oe=ae.find(Qe=>Qe.url===f.activeAudioUrl&&Qe.name===f.activeTitle);return Oe||ae.find(Qe=>Qe.url===f.activeAudioUrl)||null},[te,ae,f.activeAudioUrl,f.activeElementId,f.activeTitle]),Q=((Ot=f.activeReadingOrigin)==null?void 0:Ot.kind)==="kb-note"?f.activeReadingOrigin.id:null,Pe=m.useMemo(()=>g&&f.activeQueueIndex>=0?f.queue[f.activeQueueIndex]:null,[g,f.activeQueueIndex,f.queue]),$e=(Ae==null?void 0:Ae.id)||null,de=m.useMemo(()=>w.map($=>({id:`reading:${$.id}`,title:$.title||"未命名笔记",subtitle:new Date($.updatedAt).toLocaleDateString("zh-CN"),canFavorite:!1,noteId:$.id,playlistItemRef:{kind:"reading",noteId:$.id},isActive:Q===$.id,isPlaying:Q===$.id&&f.playing&&f.mediaType==="reading"})),[Q,w,f.mediaType,f.playing]),Ge=m.useMemo(()=>Ee.map($=>({id:`asset:${$.id}`,title:$.name,subtitle:Mo(F.get($.url)??$.duration,$.createdAt),previewImageUrl:$.thumbnail,isActive:$e===$.id,isPlaying:$e===$.id&&f.playing&&f.mediaType==="audio",isFavorite:i.has($.id),canFavorite:!0,assetId:$.id,playlistItemRef:{kind:"asset",assetId:$.id}})),[$e,Ee,i,f.mediaType,f.playing,F]),it=m.useMemo(()=>Te.reduce(($,Oe)=>{if(Fr(Oe)){const Qe=te.get(Oe.assetId);return!Qe||fe.length>0&&!Qe.name.toLowerCase().includes(fe)||$.push({id:`asset:${Qe.id}`,title:Qe.name,subtitle:Mo(F.get(Qe.url)??Qe.duration,Qe.createdAt),previewImageUrl:Qe.thumbnail,isActive:$e===Qe.id,isPlaying:$e===Qe.id&&f.playing&&f.mediaType==="audio",isFavorite:i.has(Qe.id),canFavorite:!0,assetId:Qe.id,playlistItemRef:Oe}),$}const Ze=Se.get(Oe.noteId);return!Ze||fe.length>0&&!(Ze.title||"").toLowerCase().includes(fe)||$.push({id:`reading:${Ze.id}`,title:Ze.title||"未命名笔记",subtitle:new Date(Ze.updatedAt).toLocaleDateString("zh-CN"),previewImageUrl:void 0,isFavorite:!1,canFavorite:!1,noteId:Ze.id,playlistItemRef:Oe,isActive:Q===Ze.id,isPlaying:Q===Ze.id&&f.playing&&f.mediaType==="reading"}),$},[]),[$e,Q,te,i,fe,Se,f.mediaType,f.playing,F,Te]),Ye=m.useMemo(()=>b===kn?de:b===hn?Ge:it,[Ge,de,it,b]),Ue=Ye[0]||null,oe=Ue!=null&&Ue.assetId&&te.get(Ue.assetId)||null,ft=g?null:Ae||oe,je=g?er(Pe)?Pe.previewImageUrl:f.activePreviewImageUrl:f.activePreviewImageUrl||(ft==null?void 0:ft.thumbnail),ge=f.queueSource==="playlist"?f.activePlaylistName||"播放列表":f.activePlaylistName||(g?"朗读队列":"当前播放队列"),De=q?ge:A?"全部语音":(ye==null?void 0:ye.name)||"素材库音频",We=q?`${f.queue.length} 项内容`:A?`${Ye.length} 篇笔记`:b===hn?`${Ye.length} 首音频`:`${Ye.length} 项内容`,Re=el[f.playbackMode],gt=Hp[f.playbackMode],ut=async $=>(await Promise.all($.map(async Ze=>Fr(Ze)?ce(Ze.assetId):x(Ze.noteId)))).filter(AC),lt=async $=>{const Oe=$.playlistItemRef;if(!Oe)return;if(Fr(Oe)){const Qe=ce(Oe.assetId);if(!Qe)return;if(b===hn)f.setQueue(Ee.flatMap(Pt=>{const Ft=ce(Pt.id);return Ft?[Ft]:[]}));else{const Pt=await ut(Te);f.setQueue(Pt,{queueSource:"playlist",playlistId:ye==null?void 0:ye.id,playlistName:ye==null?void 0:ye.name})}await f.togglePlayback(Qe);return}let Ze=await x(Oe.noteId);if(Ze){if(b===kn){const Qe=await v(Oe.noteId);f.setReadingQueue(Qe),Ze=Qe.find(Pt=>Pt.origin.kind==="kb-note"&&Pt.origin.id===Oe.noteId)||Ze}else{const Qe=await ut(Te);f.setQueue(Qe,{queueSource:"playlist",playlistId:ye==null?void 0:ye.id,playlistName:ye==null?void 0:ye.name}),Ze=Qe.find(Ft=>er(Ft)&&Ft.origin.kind==="kb-note"&&Ft.origin.id===Oe.noteId)||Ze}f.toggleReadingPlayback(Ze)}},Rt=()=>{U(!1),X(""),C(null),B(null),j("create")},Ut=$=>{C($||null),X(""),j("create"),B(null),U(!0),O(null)},Jt=($,Oe)=>{C(null),j("rename"),B($),X(Oe),U(!0)},Lt=g?f.readingSegments:[],Qt=g?f.activeReadingSegmentIndex:-1,jt=g&&Lt.length>0,en=b!==kn;return m.useEffect(()=>{var Pt,Ft;const $=pt.getToolState(e);if(!$||$.status!=="open")return;const Oe=jt?wh:Oo,Ze=((Pt=$.size)==null?void 0:Pt.width)??Oo.width,Qe=((Ft=$.size)==null?void 0:Ft.height)??Oo.height;if(!(Ze===Oe.width&&Qe===Oe.height)){if(jt){pt.updateToolSize(e,Oe);return}Ze<=wh.width&&pt.updateToolSize(e,Oe)}},[jt,e]),o.jsxs("div",{className:`music-player-tool ${jt?"music-player-tool--with-subtitle":""}`,children:[o.jsxs("div",{className:"music-player-tool__layout",children:[o.jsxs("div",{className:"music-player-tool__main-column",children:[o.jsxs("div",{className:"music-player-tool__now-playing",children:[o.jsx("div",{className:"music-player-tool__now-playing-cover",children:o.jsx(Uf,{src:je,alt:g?"当前朗读":(ft==null?void 0:ft.name)||(Ue==null?void 0:Ue.title)||"当前音频",fallbackClassName:"music-player-tool__now-playing-cover music-player-tool__now-playing-cover--fallback",iconSize:22})}),o.jsxs("div",{className:"music-player-tool__now-playing-meta",children:[o.jsx("div",{className:"music-player-tool__eyebrow",children:"当前播放"}),o.jsx("div",{className:"music-player-tool__title",children:g?f.activeTitle||(er(Pe)?Pe.title:"未选择朗读"):f.activeTitle||(ft==null?void 0:ft.name)||(Ue==null?void 0:Ue.title)||"未选择音频"}),o.jsxs("div",{className:"music-player-tool__subtitle",children:[f.activePlaylistName||(f.queueSource==="playlist"?"播放列表":g?"朗读轨道":"画布音频")," · ",qa(f.currentTime)," / ",qa(f.duration)]})]}),o.jsxs("div",{className:"music-player-tool__now-playing-actions",children:[o.jsx(Le,{content:"上一首",showArrow:!1,children:o.jsx("button",{type:"button",className:"music-player-tool__action-btn",onClick:()=>void f.playPrevious(),disabled:f.activeQueueIndex<=0,"aria-label":"上一首",children:o.jsx(mv,{size:16})})}),o.jsx(Le,{content:f.playing?"暂停":"播放",showArrow:!1,children:o.jsx("button",{type:"button",className:"music-player-tool__action-btn music-player-tool__action-btn--primary",onClick:()=>{if(f.playing)f.pausePlayback();else if(g)f.resumePlayback();else if(f.activeAudioUrl)f.resumePlayback();else if(Ue)lt(Ue);else return},disabled:g?!f.activeReadingSourceId:!f.activeAudioUrl&&!Ue,"aria-label":f.playing?"暂停":"播放",children:f.playing?o.jsx(Hf,{size:16}):o.jsx(ic,{size:16})})}),o.jsx(Le,{content:"下一首",showArrow:!1,children:o.jsx("button",{type:"button",className:"music-player-tool__action-btn",onClick:()=>void f.playNext(),disabled:f.activeQueueIndex<0||f.activeQueueIndex>=f.queue.length-1,"aria-label":"下一首",children:o.jsx(pv,{size:16})})}),o.jsx(Le,{content:Ce,showArrow:!1,children:o.jsx("span",{children:o.jsx(qr,{options:R,trigger:"click",placement:"bottom-right",minColumnWidth:112,onClick:$=>f.setPlaybackRate(Number($.value)),children:o.jsx("button",{type:"button",className:"music-player-tool__action-btn","aria-label":`切换播放速度,当前${J}`,children:o.jsx(gv,{size:16})})})})}),o.jsx(Le,{content:Re,showArrow:!1,children:o.jsx("span",{children:o.jsx(qr,{options:kC,trigger:"click",placement:"bottom-right",minColumnWidth:132,onClick:$=>f.setPlaybackMode($.value),children:o.jsx("button",{type:"button",className:"music-player-tool__action-btn","aria-label":`切换播放模式,当前${Re}`,children:gt})})})}),o.jsx(Le,{content:"切回播放控件",showArrow:!1,children:o.jsx("button",{type:"button",className:"music-player-tool__action-btn music-player-tool__action-btn--ghost",onPointerDown:$=>{$.preventDefault(),$.stopPropagation()},onClick:$=>{$.preventDefault(),$.stopPropagation(),requestAnimationFrame(()=>{pt.minimizeTool(e)})},"aria-label":"切回播放控件",children:o.jsx(yv,{size:16})})})]})]}),o.jsx(vv,{className:"music-player-tool__playlists",selectedPlaylistId:b,allCount:n.filter($=>$.type===Br.AUDIO).length,allTracksCount:w.length,tempTabs:re,playlists:s,playlistItems:a,onSelect:I,onCreate:()=>Ut(),onRename:$=>Jt($.id,$.name),onDelete:$=>void c($.id)}),en&&!q?o.jsx("div",{className:"music-player-tool__search",children:o.jsx($t,{value:_,onChange:$=>T(String($)),prefixIcon:o.jsx(oc,{size:14}),placeholder:b===hn?"搜索素材库音频":"搜索当前播放列表",clearable:!0})}):null,o.jsxs("div",{className:"music-player-tool__list-header",children:[o.jsx("span",{children:De}),o.jsx("span",{children:We})]}),o.jsx("div",{className:"music-player-tool__list",children:o.jsx(IC,{showPlaybackQueue:q,queueListItems:Z,listItems:Ye,emptyLabel:b===kn?"知识库还没有笔记":b===hn?"当前列表里还没有音频":"当前播放列表里还没有内容",onPlayQueueItem:$=>void ue($),onPlayListItem:$=>void lt($),onContextMenu:($,Oe,Ze)=>O({x:Oe,y:Ze,item:$}),onToggleFavorite:$=>void p($),onOpenKnowledgeBase:EC})})]}),jt?o.jsxs("aside",{className:"music-player-tool__subtitle-column",children:[o.jsxs("div",{className:"music-player-tool__subtitle-header",children:[o.jsx("span",{children:"字幕"}),o.jsxs("span",{children:[Lt.length," 段"]})]}),o.jsx("div",{className:"music-player-tool__subtitle-panel",children:Lt.map(($,Oe)=>{const Ze=Oe===Qt;return o.jsx("button",{type:"button",className:`music-player-tool__subtitle-line ${Ze?"music-player-tool__subtitle-line--active":""}`,onClick:()=>f.seekToReadingSegment(Oe),children:$.text},$.id)})})]}):null]}),o.jsx(Zn,{visible:k,header:P==="rename"?"重命名播放列表":"新建播放列表",onClose:Rt,onConfirm:async()=>{if(P==="rename"&&N)await d(N,D);else{const $=await l(D);G&&await h(G,$.id),I($.id)}Rt()},onCancel:Rt,confirmBtn:"确定",cancelBtn:"取消",children:o.jsx($t,{value:D,onChange:$=>X(String($)),placeholder:"请输入播放列表名称",autofocus:!0})}),o.jsx(yC,{contextMenu:L,playlists:s,playlistItems:a,favoriteAssetIds:i,selectedPlaylistId:b===hn?null:b,currentPlaylistItemKeys:ie,onClose:()=>O(null),onToggleFavorite:$=>void p($),onAddToPlaylist:($,Oe)=>void h($,Oe),onRemoveFromPlaylist:($,Oe)=>void u($,Oe),onCreatePlaylistAndAdd:$=>Ut($)})]})},Gp=jC,OC={manifest:{id:ri,name:"音乐播放器",description:"从素材库选择音频并后台播放,可与画布播放控件联动",icon:o.jsx(tc,{size:18,strokeWidth:1.75}),category:tt.UTILITIES,component:"music-player",defaultWidth:520,defaultHeight:640},Component:Gp},MC=Object.freeze(Object.defineProperty({__proto__:null,MusicPlayerToolComponent:Gp,musicPlayerTool:OC},Symbol.toStringTag,{value:"Module"})),DC=m.lazy(()=>Xe(()=>import("./MusicAnalyzer-CdMhl-kU.js"),__vite__mapDeps([0,8,9]),import.meta.url)),NC={width:"100%",height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",boxSizing:"border-box"},RC=()=>o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:200,color:"#999",fontSize:14},children:"加载中..."}),Wp=t=>o.jsx("div",{style:NC,children:o.jsx(m.Suspense,{fallback:o.jsx(RC,{}),children:o.jsx(DC,{...t})})}),LC={manifest:{id:"music-analyzer",name:"爆款音乐生成",description:"分析音频、改写歌词,并一键送入 Suno 生成音乐",icon:o.jsx(Df,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:"music-analyzer",supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:520,defaultHeight:700},Component:Wp},FC=Object.freeze(Object.defineProperty({__proto__:null,MusicAnalyzerToolComponent:Wp,musicAnalyzerTool:LC},Symbol.toStringTag,{value:"Module"})),BC=m.lazy(()=>Xe(()=>import("./VideoAnalyzer-BrEKSLeh.js"),__vite__mapDeps([0,10,8,7,11]),import.meta.url)),zC={width:"100%",height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",boxSizing:"border-box"},$C=()=>o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:200,color:"#999",fontSize:14},children:"加载中..."}),Vp=t=>o.jsx("div",{style:zC,children:o.jsx(m.Suspense,{fallback:o.jsx($C,{}),children:o.jsx(BC,{...t})})}),UC={manifest:{id:"video-analyzer",name:"爆款视频生成",description:"AI 分析视频内容,提取镜头、脚本、风格等结构化数据",icon:o.jsx(jf,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:"video-analyzer",supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:680,defaultHeight:700},Component:Vp},HC=Object.freeze(Object.defineProperty({__proto__:null,VideoAnalyzerToolComponent:Vp,videoAnalyzerTool:UC},Symbol.toStringTag,{value:"Module"})),GC=m.lazy(()=>Xe(()=>import("./MVCreator-Bl8GH4mR.js"),__vite__mapDeps([0,10,8,12,11,7,9]),import.meta.url)),WC={width:"100%",height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",boxSizing:"border-box"},VC=()=>o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:200,color:"#999",fontSize:14},children:"加载中..."}),Kp=t=>o.jsx("div",{style:WC,children:o.jsx(m.Suspense,{fallback:o.jsx(VC,{}),children:o.jsx(GC,{...t})})}),KC={manifest:{id:"mv-creator",name:"爆款MV生成",description:"输入创意,AI 生成音乐和分镜视频,一站式 MV 创作",icon:o.jsx(Of,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:"mv-creator",supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:680,defaultHeight:700},Component:Kp},qC=Object.freeze(Object.defineProperty({__proto__:null,MVCreatorToolComponent:Kp,mvCreatorTool:KC},Symbol.toStringTag,{value:"Module"})),YC=m.lazy(()=>Xe(()=>import("./ComicCreator-DjOhYrZt.js"),__vite__mapDeps([0,8,10,13,7,11,9]),import.meta.url)),ZC={width:"100%",height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",boxSizing:"border-box"},XC=()=>o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:200,color:"#999",fontSize:14},children:"加载中..."}),qp=t=>o.jsx("div",{style:ZC,children:o.jsx(m.Suspense,{fallback:o.jsx(XC,{}),children:o.jsx(YC,{...t})})}),JC={manifest:{id:ti,name:"多图生成",description:"适合故事分镜、教程步骤、产品手册、营销图文等多页图片,一键规划提示词、批量出图并导出 ZIP/PPTX/PDF",icon:o.jsx(Af,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:ti,supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:720,defaultHeight:760},Component:qp},QC=Object.freeze(Object.defineProperty({__proto__:null,ComicCreatorToolComponent:qp,comicCreatorTool:JC},Symbol.toStringTag,{value:"Module"})),eP=[{category:"演示文稿",categoryEn:"Presentation",items:[{label:"PPT 16:9",labelEn:"PPT 16:9",width:1920,height:1080},{label:"PPT 4:3",labelEn:"PPT 4:3",width:1024,height:768}]},{category:"手机屏幕",categoryEn:"Phone",items:[{label:"iPhone 15 Pro",labelEn:"iPhone 15 Pro",width:393,height:852},{label:"iPhone SE",labelEn:"iPhone SE",width:375,height:667},{label:"Android",labelEn:"Android",width:360,height:800}]},{category:"平板",categoryEn:"Tablet",items:[{label:"iPad",labelEn:"iPad",width:768,height:1024},{label:'iPad Pro 12.9"',labelEn:'iPad Pro 12.9"',width:1024,height:1366}]},{category:"社交媒体",categoryEn:"Social Media",items:[{label:"正方形 1:1",labelEn:"Square 1:1",width:1080,height:1080},{label:"竖版 9:16",labelEn:"Portrait 9:16",width:1080,height:1920},{label:"横版 16:9",labelEn:"Landscape 16:9",width:1920,height:1080}]},{category:"照片 / 海报",categoryEn:"Photo / Poster",items:[{label:"A4 竖版",labelEn:"A4 Portrait",width:595,height:842},{label:"A4 横版",labelEn:"A4 Landscape",width:842,height:595},{label:"照片 4:3",labelEn:"Photo 4:3",width:1200,height:900},{label:"照片 3:2",labelEn:"Photo 3:2",width:1200,height:800}]},{category:"桌面",categoryEn:"Desktop",items:[{label:"Full HD",labelEn:"Full HD",width:1920,height:1080},{label:"MacBook",labelEn:"MacBook",width:1440,height:900},{label:"4K UHD",labelEn:"4K UHD",width:3840,height:2160}]}],xh=[{family:"PingFang SC",source:"system",displayName:"苹方",previewText:"元旦快乐"},{family:"Microsoft YaHei",source:"system",displayName:"微软雅黑",previewText:"元旦快乐"},{family:"SimHei",source:"system",displayName:"黑体",previewText:"元旦快乐"},{family:"SimSun",source:"system",displayName:"宋体",previewText:"元旦快乐"},{family:"KaiTi",source:"system",displayName:"楷体",previewText:"元旦快乐"},{family:"FangSong",source:"system",displayName:"仿宋",previewText:"元旦快乐"},{family:"STXingkai",source:"system",displayName:"华文行楷",previewText:"元旦快乐"},{family:"STCaiyun",source:"system",displayName:"华文彩云",previewText:"元旦快乐"},{family:"STHupo",source:"system",displayName:"华文琥珀",previewText:"元旦快乐"},{family:"LiSu",source:"system",displayName:"隶书",previewText:"元旦快乐"},{family:"YouYuan",source:"system",displayName:"幼圆",previewText:"元旦快乐"},{family:"Arial",source:"system",displayName:"Arial",previewText:"Happy New Year"},{family:"Georgia",source:"system",displayName:"Georgia",previewText:"Happy New Year"},{family:"Times New Roman",source:"system",displayName:"Times New Roman",previewText:"Happy New Year"}],Do=[{family:"Noto Sans SC",source:"google",displayName:"Noto Sans 简体",previewText:"元旦快乐"},{family:"Noto Serif SC",source:"google",displayName:"Noto Serif 简体",previewText:"元旦快乐"},{family:"ZCOOL XiaoWei",source:"google",displayName:"站酷小薇",previewText:"元旦快乐"},{family:"ZCOOL QingKe HuangYou",source:"google",displayName:"站酷庆科黄油体",previewText:"元旦快乐"},{family:"Ma Shan Zheng",source:"google",displayName:"马善政毛笔楷书",previewText:"元旦快乐"},{family:"Zhi Mang Xing",source:"google",displayName:"芝麻行",previewText:"元旦快乐"},{family:"Liu Jian Mao Cao",source:"google",displayName:"刘建毛草",previewText:"元旦快乐"},{family:"Long Cang",source:"google",displayName:"龙藏",previewText:"元旦快乐"},{family:"Lobster",source:"google",displayName:"Lobster",previewText:"Happy New Year"},{family:"Pacifico",source:"google",displayName:"Pacifico",previewText:"Happy New Year"},{family:"Dancing Script",source:"google",displayName:"Dancing Script",previewText:"Happy New Year"},{family:"Satisfy",source:"google",displayName:"Satisfy",previewText:"Happy New Year"}],r1=[{id:"gold",name:"Golden",nameZh:"金色",category:"festival",config:{type:"linear",angle:135,stops:[{color:"#FFD700",position:0},{color:"#FFA500",position:50},{color:"#FF8C00",position:100}],target:"text"}},{id:"red-gold",name:"Red Gold",nameZh:"红金",category:"festival",config:{type:"linear",angle:135,stops:[{color:"#FF0000",position:0},{color:"#FFD700",position:50},{color:"#FF4500",position:100}],target:"text"}},{id:"new-year",name:"New Year",nameZh:"新年红",category:"festival",config:{type:"linear",angle:180,stops:[{color:"#DC143C",position:0},{color:"#B22222",position:50},{color:"#8B0000",position:100}],target:"text"}},{id:"spring-festival",name:"Spring Festival",nameZh:"春节",category:"festival",config:{type:"linear",angle:135,stops:[{color:"#C41E3A",position:0},{color:"#FFD700",position:30},{color:"#C41E3A",position:70},{color:"#FFD700",position:100}],target:"text"}},{id:"silver",name:"Silver",nameZh:"银色",category:"metal",config:{type:"linear",angle:135,stops:[{color:"#C0C0C0",position:0},{color:"#FFFFFF",position:50},{color:"#A9A9A9",position:100}],target:"text"}},{id:"bronze",name:"Bronze",nameZh:"青铜",category:"metal",config:{type:"linear",angle:135,stops:[{color:"#CD7F32",position:0},{color:"#DAA520",position:50},{color:"#8B4513",position:100}],target:"text"}},{id:"rose-gold",name:"Rose Gold",nameZh:"玫瑰金",category:"metal",config:{type:"linear",angle:135,stops:[{color:"#B76E79",position:0},{color:"#E8B4B8",position:50},{color:"#B76E79",position:100}],target:"text"}},{id:"rainbow",name:"Rainbow",nameZh:"彩虹",category:"nature",config:{type:"linear",angle:90,stops:[{color:"#FF0000",position:0},{color:"#FF7F00",position:17},{color:"#FFFF00",position:33},{color:"#00FF00",position:50},{color:"#0000FF",position:67},{color:"#4B0082",position:83},{color:"#9400D3",position:100}],target:"text"}},{id:"sunset",name:"Sunset",nameZh:"日落",category:"nature",config:{type:"linear",angle:180,stops:[{color:"#FF6B6B",position:0},{color:"#FFE66D",position:50},{color:"#4ECDC4",position:100}],target:"text"}},{id:"ocean",name:"Ocean",nameZh:"海洋",category:"nature",config:{type:"linear",angle:180,stops:[{color:"#667eea",position:0},{color:"#764ba2",position:100}],target:"text"}},{id:"forest",name:"Forest",nameZh:"森林",category:"nature",config:{type:"linear",angle:135,stops:[{color:"#134E5E",position:0},{color:"#71B280",position:100}],target:"text"}}],s1={textShadow:{subtle:{type:"text",enabled:!0,color:"rgba(0, 0, 0, 0.3)",offsetX:1,offsetY:1,blur:2},medium:{type:"text",enabled:!0,color:"rgba(0, 0, 0, 0.5)",offsetX:2,offsetY:2,blur:4},strong:{type:"text",enabled:!0,color:"rgba(0, 0, 0, 0.7)",offsetX:4,offsetY:4,blur:8},longShadow:{type:"text",enabled:!0,color:"rgba(0, 0, 0, 0.4)",offsetX:6,offsetY:6,blur:0}}};class tP{constructor(){this.fontLoadStates=new Map,this.loadedFonts=new Set,this.fontPreviewUrls=new Map}async loadGoogleFont(e,n=[400,700]){const r=this.fontLoadStates.get(e);if(r){if(r.status==="loaded")return Promise.resolve();if(r.status==="loading"&&r.promise)return r.promise;if(r.status==="error"&&r.error)throw r.error}const s=this._loadGoogleFontInternal(e,n);this.fontLoadStates.set(e,{status:"loading",promise:s});try{await s,this.fontLoadStates.set(e,{status:"loaded"}),this.loadedFonts.add(e)}catch(a){const i=a;throw this.fontLoadStates.set(e,{status:"error",error:i}),i}}_loadGoogleFontInternal(e,n){return new Promise((r,s)=>{const a=`google-font-${e.replace(/\s+/g,"-").toLowerCase()}`;if(document.getElementById(a)){r();return}const l=document.createElement("link");l.id=a,l.rel="stylesheet",l.href=`https://fonts.googleapis.com/css2?family=${encodeURIComponent(e)}:wght@${n.join(";")}&display=swap`,l.onload=()=>{document.fonts&&document.fonts.ready?document.fonts.ready.then(()=>r()):setTimeout(()=>r(),100)},l.onerror=()=>s(new Error(`Failed to load font: ${e}`)),document.head.appendChild(l)})}isFontLoaded(e){return this.loadedFonts.has(e)}getFontLoadStatus(e){var n;return((n=this.fontLoadStates.get(e))==null?void 0:n.status)||"pending"}extractFontsFromBoard(e){const n=new Set,r=s=>{if(s){if(s["font-family"]&&n.add(s["font-family"]),typeof s.style=="string"){const a=s.style.match(/font-family:\s*["']?([^;"']+)["']?/);if(a&&a[1]){const i=a[1].trim().replace(/['"]/g,"");n.add(i)}}s.text&&Array.isArray(s.text.children)&&s.text.children.forEach(a=>{a["font-family"]&&n.add(a["font-family"]),r(a)}),Array.isArray(s.children)&&s.children.forEach(a=>{if(a["font-family"]&&n.add(a["font-family"]),typeof a.style=="string"){const i=a.style.match(/font-family:\s*["']?([^;"']+)["']?/);if(i&&i[1]){const l=i[1].trim().replace(/['"]/g,"");n.add(l)}}r(a)})}};return Array.isArray(e)?e.forEach(r):r(e),Array.from(n)}async preloadBoardFonts(e){const r=this.extractFontsFromBoard(e).filter(s=>Do.some(a=>a.family===s));await Promise.allSettled(r.map(s=>this.loadGoogleFont(s)))}getFontPreviewUrl(e){return this.fontPreviewUrls.get(e)||null}setFontPreviewUrl(e,n){this.fontPreviewUrls.set(e,n)}async generateFontPreview(e,n="元旦快乐 Happy New Year",r={}){const{width:s=200,height:a=60,fontSize:i=24,backgroundColor:l="#ffffff",textColor:d="#000000"}=r,c=this.fontPreviewUrls.get(e);if(c)return c;const h=[...Do,...xh].find(f=>f.family===e);(h==null?void 0:h.source)==="google"&&!this.isFontLoaded(e)&&await this.loadGoogleFont(e);const u=document.createElement("canvas");u.width=s,u.height=a;const p=u.getContext("2d");if(!p)throw new Error("Failed to get canvas context");p.fillStyle=l,p.fillRect(0,0,s,a),p.fillStyle=d,p.font=`${i}px '${e}', sans-serif`,p.textAlign="center",p.textBaseline="middle",p.fillText(n,s/2,a/2);const y=u.toDataURL("image/png");return this.fontPreviewUrls.set(e,y),y}async generateAllFontPreviews(){const e=[...Do,...xh],n=e.filter(r=>r.source==="google");await Promise.allSettled(n.map(r=>this.loadGoogleFont(r.family))),await Promise.allSettled(e.map(r=>this.generateFontPreview(r.family,r.previewText)))}clearCache(){this.fontLoadStates.clear(),this.loadedFonts.clear(),this.fontPreviewUrls.clear()}getLoadedFonts(){return Array.from(this.loadedFonts)}}const nP=new tP;function Rl(t){const e={...t};return e.id=Xl(),e.children&&Array.isArray(e.children)&&(e.children=e.children.map(n=>Rl(n))),e}function bh(t,e){let n=null;return t.points?n=Fe.getRectangleByPoints(t.points):t.x!==void 0&&t.y!==void 0&&(n={x:t.x,y:t.y,width:t.width||0,height:t.height||0}),n?!(n.x+n.width<e.x||n.x>e.x+e.width||n.y+n.height<e.y||n.y>e.y+e.height):!1}function Ss(t,e,n){const r={...t};return r.points?r.points=r.points.map(s=>[s[0]+e,s[1]+n]):r.x!==void 0&&r.y!==void 0&&(r.x+=e,r.y+=n),r.children&&Array.isArray(r.children)&&(r.children=r.children.map(s=>Ss(s,e,n))),r}function _h(t,e){return t.y<e.y+e.height&&e.y<t.y+t.height}function rP(t,e,n){for(const{frame:r}of e){if(r.id===n)continue;const s=Fe.getRectangleByPoints(r.points);if(t.x<s.x+s.width&&t.x+t.width>s.x&&t.y<s.y+s.height&&t.y+t.height>s.y)return!0}return!1}function sP(t,e,n="zh"){const r=t.children.findIndex(f=>f.id===e.id);if(r===-1)return ee.warning(n==="zh"?"PPT 页面不存在":"PPT page not found"),null;if(!(t.children[r]===e))return ee.warning(n==="zh"?"暂不支持复制嵌套 PPT 页面":"Nested PPT page duplication not supported"),null;const a=Fe.getRectangleByPoints(e.points),i=[];t.children.forEach((f,g)=>{at(f)&&i.push({frame:f,index:g})});const l=i.findIndex(f=>f.index===r);let d=0,c=0,h=!1;if(l<i.length-1){const f=i[l+1].frame,g=Fe.getRectangleByPoints(f.points);if(_h(a,g))d=g.x-a.x,c=g.y-a.y,h=!0;else{const v={x:a.x+a.width+100,y:a.y,width:a.width,height:a.height};rP(v,i,e.id)?(d=0,c=a.height+100):(d=a.width+100,c=0),h=!1}}else d=a.width+100,c=0,h=!1;const u=[];t.children.forEach((f,g)=>{!at(f)&&bh(f,a)&&u.push({element:f,index:g})});let p=Rl(e);p.name=`${Yt(e)} (${n==="zh"?"副本":"Copy"})`,p=Ss(p,d,c);const y=u.map(f=>{let g=Rl(f.element);return g=Ss(g,d,c),g});if(h){const f=i.slice(l+1).filter(({frame:w})=>{const x=Fe.getRectangleByPoints(w.points);return _h(a,x)}),g=[];t.children.forEach((w,x)=>{if(!at(w))for(const{frame:v}of f){const _=Fe.getRectangleByPoints(v.points);if(bh(w,_)){g.push({element:w,index:x});break}}});for(const{frame:w,index:x}of f){const v=Ss(w,d,c);ht.setNode(t,v,[x])}for(const{element:w,index:x}of g){const v=Ss(w,d,c);ht.setNode(t,v,[x])}}return ht.insertNode(t,p,[r+1]),y.forEach((f,g)=>{ht.insertNode(t,f,[r+2+g])}),ee.success(n==="zh"?`已复制 PPT 页面及 ${y.length} 个元素`:`Duplicated PPT page with ${y.length} elements`),p}function Th(t,e){ns(t),ta(t,e);const n=Fe.getRectangleByPoints(e.points),r=80,s=kt.getBoardContainer(t);let a=s.clientWidth,i=s.clientHeight;const l=document.querySelector(".project-drawer"),d=l?l.offsetWidth:0,c=document.querySelector(".ai-input-bar"),h=c?c.offsetHeight:0,u=a-d,p=i-h,y=u/(n.width+r*2),f=p/(n.height+r*2),g=Math.min(y,f,2),w=n.x+n.width/2,x=n.y+n.height/2,v=d+u/2,_=p/2,T=[w-v/g,x-_/g];dt.updateViewport(t,T,g)}let Sh=!1,No=null;function aP(t=100){return new Promise(e=>{"requestIdleCallback"in window?window.requestIdleCallback(()=>e(),{timeout:t}):setTimeout(e,0)})}function iP(){const[t,e]=m.useState(!1);return m.useEffect(()=>{let n=!0;const r=async()=>{await aP(50),console.warn("[useTaskStorage] Idle callback fired, starting init");try{const{migrateFromLegacyDB:s}=await Xe(async()=>{const{migrateFromLegacyDB:i}=await import("./ai-chat-B-XdoWBQ.js").then(l=>l.sH);return{migrateFromLegacyDB:i}},__vite__mapDeps([0]),import.meta.url);await s();const a=await ei.getAllTasks();if(console.warn(`[useTaskStorage] Loaded ${a.length} tasks from IndexedDB`),a.length>0){xe.restoreTasks(a),console.warn(`[useTaskStorage] Restored ${a.length} tasks to memory`);const i=a.filter(y=>y.status==="processing");i.length>0&&(console.warn(`[useTaskStorage] Found ${i.length} interrupted processing tasks`),i.forEach(y=>{const f=js(y),g=y.type===He.VIDEO&&!!y.remoteId,w=y.type===He.AUDIO&&!!y.remoteId;if(console.warn(`[useTaskStorage] task=${y.id} type=${y.type} phase=${y.executionPhase||"unknown"} remoteId=${y.remoteId||"none"} → ${g||w||f?"KEEP":"MARK_FAILED"}`),!(g||w||f)){let x="任务被中断(页面刷新)",v="INTERRUPTED";y.type===He.VIDEO&&y.executionPhase===pn.SUBMITTING&&(x="任务在提交过程中被中断,可能已在后台执行",v="INTERRUPTED_DURING_SUBMISSION"),xe.updateTaskStatus(y.id,ve.FAILED,{startedAt:void 0,executionPhase:void 0,error:{code:v,message:x,details:{originalError:`Task interrupted by page refresh before completion (phase: ${y.executionPhase||"unknown"})`,timestamp:Date.now()}}})}}));const l=a.filter(y=>y.status==="failed"&&y.remoteId&&(y.type===He.VIDEO||y.type===He.AUDIO||js(y))),d=a.filter(y=>y.status==="failed"&&y.type===He.VIDEO).length,c=a.filter(y=>y.status==="failed"&&y.type===He.VIDEO&&y.remoteId).length,h=a.filter(y=>y.status==="failed"&&y.type===He.AUDIO).length,u=a.filter(y=>y.status==="failed"&&y.type===He.AUDIO&&y.remoteId).length;if(console.warn(`[useTaskStorage] Recovery check: ${i.length} processing, ${d} failed video (${c} with remoteId), ${h} failed audio (${u} with remoteId), ${l.length} recoverable`),l.length>0){const y=new Set(["INTERRUPTED","INTERRUPTED_DURING_SUBMISSION","RESUME_FAILED"]);l.forEach(f=>{var w;const g=((w=f.error)==null?void 0:w.code)||"";if(!y.has(g)){console.warn(`[useTaskStorage] Skip recovery for task ${f.id}: terminal failure (${g||"no error code"})`);return}console.warn(`[useTaskStorage] Recovering interrupted task ${f.id} (error: ${g}, remoteId: ${f.remoteId})`),xe.updateTaskStatus(f.id,ve.PROCESSING,{error:void 0,executionPhase:pn.POLLING})})}a.filter(y=>y.status==="processing"||y.status==="pending").length>0}}catch(s){console.error("[useTaskStorage] Failed to initialize storage:",s)}};return No||(No=(async()=>{Sh||(Sh=!0,await r())})()),No.then(()=>{n&&e(!0)}),()=>{n=!1}},[]),t}function Ih(t,e){return typeof t=="string"&&t?t:t&&typeof t=="object"&&typeof t.modelId=="string"&&t.modelId?t.modelId:e}function Ro(t,e){const n=xe.getTask(t);n&&tl(n)&&nl(e,n)}function oP(t,e,n,r){var a;const s=r.binding;(a=s==null?void 0:s.metadata)==null||a.image}function Yp(t,e){const n=t,r=n.params&&typeof n.params=="object"?n.params:void 0;for(const s of e){if(n[s]!==void 0)return n[s];if((r==null?void 0:r[s])!==void 0)return r[s]}}function vi(t,e){const n=Yp(t,e);return typeof n=="string"&&n.trim()?n.trim():void 0}function lP(t,e){const n=Yp(t,e);return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ya(t,e,n){const r=vi(t,e);return r&&n.includes(r)?r:void 0}function cP(t,e){const n=vi(t,["generationMode","generation_mode"]);return e.length>0||n==="image_edit"||n==="image_to_image"||!!vi(t,["maskImage","mask_image"])}function dP(t,e){const n=Ya(t,["generationMode","generation_mode"],["text_to_image","image_to_image","image_edit"]);return n||(e?"image_to_image":"text_to_image")}class uP{constructor(){this.abortControllers=new Map}async generate(e,n,r){const s=new AbortController;this.abortControllers.set(e,s);const a=Date.now(),i=r===He.IMAGE?"image":r===He.VIDEO?"video":"audio",l=n.model||(i==="image"?Bi:i==="video"?"gemini-video":zi),d=!!n.uploadedImage||!!n.uploadedImages||!!n.referenceImages;_e.trackModelCall({taskId:e,taskType:i,model:l,promptLength:n.prompt.length,hasUploadedImage:d,startTime:a,aspectRatio:n.size,duration:n.duration,resolution:n.width&&n.height?`${n.width}x${n.height}`:void 0,batchCount:n.count||1,hasReferenceImage:d});let c;try{const h=cs[r.toUpperCase()]??cs.IMAGE,u=new Promise((g,w)=>{c=setTimeout(()=>{s.abort(),w(new Error("TIMEOUT"))},h)}),p=r===He.IMAGE?this.generateImage(e,n,s.signal):r===He.VIDEO?this.generateVideo(e,n,s.signal):this.generateAudio(e,n,s.signal),y=await Promise.race([p,u]),f=Date.now()-a;return _e.trackModelSuccess({taskId:e,taskType:i,model:l,duration:f,resultSize:y.size}),y}catch(h){const u=Date.now()-a;throw console.error(`[GenerationAPI] Generation failed for task ${e}:`,h),h.message==="TIMEOUT"?(_e.trackModelFailure({taskId:e,taskType:i,model:l,duration:u,error:"TIMEOUT"}),new Error(`${r===He.IMAGE?"图片":r===He.VIDEO?"视频":"音频"}生成超时`)):h.name==="AbortError"?(_e.trackTaskCancellation({taskId:e,taskType:i,duration:u}),new Error("任务已取消")):(_e.trackModelFailure({taskId:e,taskType:i,model:l,duration:u,error:h.message||"UNKNOWN_ERROR"}),h)}finally{c&&clearTimeout(c),this.abortControllers.delete(e)}}convertAspectRatioToSize(e){return Sv(e)}deriveAspectRatio(e){const n=r=>{if(!r.includes("x"))return;const[s,a]=r.split("x"),i=Number(s),l=Number(a);if(!i||!l)return;const d=(h,u)=>u===0?h:d(u,h%u),c=d(i,l);return`${i/c}:${l/c}`};if(e.size){const r=n(e.size);if(r)return r}if(e.width&&e.height){const r=(a,i)=>i===0?a:r(i,a%i),s=r(e.width,e.height);return`${e.width/s}:${e.height/s}`}}async extractReferenceImages(e){var s;const n=[],r=e.uploadedImages;if(Array.isArray(r)){for(const a of r)if(a!=null&&a.url)if(a.type==="url"){const i=await Mn.getImageForAI(a.url);n.push(i.value)}else n.push(a.url)}return(s=e.uploadedImage)!=null&&s.url&&n.push(e.uploadedImage.url),Array.isArray(e.referenceImages)&&n.push(...e.referenceImages),n}async generateImage(e,n,r){try{const s=n.model,a=n.modelRef,i=await this.extractReferenceImages(n),l=cP(n,i),d={preferredRequestSchema:l?Iv:void 0},c=$i("image",s||Bi,a||null,d);if(!c||c.kind!=="image")throw new Error(`No image adapter for model: ${s}`);let h=n.size;h||(h=this.convertAspectRatioToSize(n.aspectRatio)),!h&&kv(s)&&(h=this.deriveAspectRatio(n)||"1:1");const u=Ui("image",a||s,d);oP(e,c,s,u);const p=await c.generateImage(u,{prompt:n.prompt,model:s,modelRef:a||null,size:h,generationMode:dP(n,l),referenceImages:i.length>0?i:void 0,maskImage:vi(n,["maskImage","mask_image"]),inputFidelity:Ya(n,["inputFidelity","input_fidelity"],["high","low"]),background:Ya(n,["background"],["transparent","opaque","auto"]),outputFormat:Ya(n,["outputFormat","output_format"],["png","jpeg","webp"]),outputCompression:lP(n,["outputCompression","output_compression"]),params:{resolution:n.resolution,quality:n.quality,response_format:n.response_format,...n.params,onProgress:y=>{xe.updateTaskProgress(e,y),xe.updateTaskStatus(e,ve.PROCESSING,{executionPhase:pn.POLLING})},onSubmitted:y=>{xe.updateTaskStatus(e,ve.PROCESSING,{remoteId:y,invocationRoute:Hi("image",a||s||Bi),executionPhase:pn.POLLING})}}});return{url:p.url,urls:p.urls,format:p.format||"png",size:0}}catch(s){console.error("[GenerationAPI] Image generation error:",s);const a=new Error(s.message||"图片生成失败");throw s.apiErrorBody&&(a.apiErrorBody=s.apiErrorBody),s.httpStatus&&(a.httpStatus=s.httpStatus),s.fullResponse&&(a.fullResponse=s.fullResponse),a}}async resumeAsyncImageGeneration(e,n,r){const s=cs.IMAGE,a=new AbortController;this.abortControllers.set(e,a);let i;const l=new Promise((d,c)=>{i=setTimeout(()=>{a.abort(),c(new Error("TIMEOUT"))},s)});try{Ro(e,"image");const d=await Promise.race([od.resumePolling(n,{interval:5e3,routeModel:r,signal:a.signal,onProgress:u=>{xe.updateTaskProgress(e,u)}}),l]),{url:c,format:h}=od.extractUrlAndFormat(d);return{url:c,format:h,size:0}}catch(d){const c=new Error(d.message||"图片生成失败");throw d.apiErrorBody&&(c.apiErrorBody=d.apiErrorBody),d.httpStatus&&(c.httpStatus=d.httpStatus),c}finally{i&&clearTimeout(i),this.abortControllers.get(e)===a&&this.abortControllers.delete(e)}}async generateVideo(e,n,r){try{const s=n.model,a=n.modelRef,i=$i("video",s||"veo3",a||null);if(!i||i.kind!=="video")throw new Error(`No video adapter for model: ${s}`);xe.updateTaskStatus(e,"processing",{executionPhase:pn.SUBMITTING});const l=await this.extractReferenceImages(n),d=n.duration??n.seconds,c=await i.generateVideo(Ui("video",a||s),{prompt:n.prompt,model:s,modelRef:a||null,size:n.size,duration:d!==void 0?Number(d):void 0,referenceImages:l.length>0?l:void 0,params:{...n.params,onProgress:h=>{xe.updateTaskProgress(e,h)},onSubmitted:h=>{xe.updateTaskStatus(e,"processing",{remoteId:h,invocationRoute:Hi("video",a||s),executionPhase:pn.POLLING})}}});return{url:c.url,format:c.format||"mp4",size:0,duration:c.duration||0}}catch(s){console.error("[GenerationAPI] Video generation error:",s);const a=new Error(s.message||"视频生成失败");throw s.apiErrorBody&&(a.apiErrorBody=s.apiErrorBody),s.httpStatus&&(a.httpStatus=s.httpStatus),a}}async generateAudio(e,n,r){try{const s=n.model,a=n.modelRef,i=$i("audio",s||zi,a||null);if(!i||i.kind!=="audio")throw new Error(`No audio adapter for model: ${s}`);xe.updateTaskStatus(e,ve.PROCESSING,{executionPhase:pn.SUBMITTING});const l=await i.generateAudio(Ui("audio",a||s),{prompt:n.prompt,model:s,modelRef:a||null,title:n.title,tags:n.tags,mv:n.mv,sunoAction:n.sunoAction,notifyHook:n.notifyHook,continueClipId:n.continueClipId,continueTaskId:n.continueTaskId,continueAt:n.continueAt,infillStartS:n.infillStartS,infillEndS:n.infillEndS,params:{...n.params,signal:r,onProgress:d=>{xe.updateTaskProgress(e,d),xe.updateTaskStatus(e,ve.PROCESSING,{executionPhase:pn.POLLING})},onSubmitted:d=>{xe.updateTaskStatus(e,ve.PROCESSING,{remoteId:d,invocationRoute:Hi("audio",a||s),executionPhase:pn.POLLING})}}});return{url:l.url,urls:l.urls,format:l.format||(l.resultKind==="lyrics"?"lyrics":"mp3"),size:0,resultKind:l.resultKind,duration:typeof l.duration=="number"?l.duration:void 0,previewImageUrl:l.imageUrl,title:l.title,lyricsText:l.lyricsText,lyricsTitle:l.lyricsTitle,lyricsTags:l.lyricsTags,providerTaskId:l.providerTaskId,primaryClipId:l.primaryClipId,clipIds:l.clipIds,clips:l.clips}}catch(s){console.error("[GenerationAPI] Audio generation error:",s);const a=new Error(s.message||"音频生成失败");throw s.apiErrorBody&&(a.apiErrorBody=s.apiErrorBody),s.httpStatus&&(a.httpStatus=s.httpStatus),a}}async resumeVideoGeneration(e,n,r){var i;const s=Date.now(),a=Ih(r,"gemini-video");_e.trackModelCall({taskId:e,taskType:"video",model:a,promptLength:0,hasUploadedImage:!1,startTime:s});try{Ro(e,"video");const l=cs.VIDEO,d=new Promise((y,f)=>{setTimeout(()=>{f(new Error("TIMEOUT"))},l)}),c=Cv.resumePolling(n,{interval:5e3,routeModel:r,params:(i=xe.getTask(e))==null?void 0:i.params.params,onProgress:(y,f)=>{xe.updateTaskProgress(e,y)}}),h=await Promise.race([c,d]),u=Date.now()-s;_e.trackModelSuccess({taskId:e,taskType:"video",model:a,duration:u,resultSize:0});const p=h.video_url||h.url;if(!p)throw new Error("API 未返回有效的视频 URL");return{url:p,format:"mp4",size:0,duration:parseInt(h.seconds)||8}}catch(l){const d=Date.now()-s;throw console.error(`[GenerationAPI] Resumed video generation failed for task ${e}:`,l),_e.trackModelFailure({taskId:e,taskType:"video",model:a,duration:d,error:l.message||"UNKNOWN_ERROR"}),l}}async resumeAudioGeneration(e,n,r){const s=Date.now(),a=Ih(r,zi);_e.trackModelCall({taskId:e,taskType:"audio",model:a,promptLength:0,hasUploadedImage:!1,startTime:s});try{Ro(e,"audio");const i=cs.AUDIO,l=new Promise((p,y)=>{setTimeout(()=>{y(new Error("TIMEOUT"))},i)}),d=Pv.resumePolling(n,{interval:5e3,routeModel:r,onProgress:p=>{xe.updateTaskProgress(e,p)}}),c=await Promise.race([d,l]),h=Ev(c),u=Date.now()-s;return _e.trackModelSuccess({taskId:e,taskType:"audio",model:a,duration:u,resultSize:0}),{url:h.url,urls:h.urls,format:h.format||(h.resultKind==="lyrics"?"lyrics":"mp3"),size:0,resultKind:h.resultKind,duration:typeof h.duration=="number"?h.duration:void 0,previewImageUrl:h.imageUrl,title:h.title,lyricsText:h.lyricsText,lyricsTitle:h.lyricsTitle,lyricsTags:h.lyricsTags,providerTaskId:h.providerTaskId,primaryClipId:h.primaryClipId,clipIds:h.clipIds,clips:h.clips}}catch(i){const l=Date.now()-s;throw console.error(`[GenerationAPI] Resumed audio generation failed for task ${e}:`,i),_e.trackModelFailure({taskId:e,taskType:"audio",model:a,duration:l,error:i.message||"UNKNOWN_ERROR"}),i}}cancelRequest(e){const n=this.abortControllers.get(e);n&&(n.abort(),this.abortControllers.delete(e))}hasActiveRequest(e){return this.abortControllers.has(e)}}const ps=new uP;function hP(t){var e;if(!t)return null;try{const n=JSON.parse(t);if((e=n.error)!=null&&e.message)return n.error.message;if(n.message)return n.message;if(n.error&&typeof n.error=="string")return n.error;if(n.detail)return n.detail;if(n.msg)return n.msg}catch{return t}return null}function ba(t){const e=(t==null?void 0:t.message)||String(t),n=(t==null?void 0:t.apiErrorBody)||"",r=t==null?void 0:t.httpStatus,s=jv(t),a=hP(n),i=`${e} ${n}`;return i.includes("insufficient_user_quota")||i.includes("预扣费额度失败")?"账户额度不足,请充值后重试":e.includes("PROHIBITED_CONTENT")||e.includes("has been blocked by Google Gemini")?e:e.includes("cannot")||e.includes("I cannot")||e.includes("I can't")?"AI 拒绝生成此内容":e.includes("unable to")||e.includes("not able to")?"AI 无法处理此请求":e.includes("signal")&&e.includes("timed out")?"请求超时,服务器响应过慢,正在自动重试":e.includes("TIMEOUT")||e.includes("超时")?"生成超时,请稍后重试":e.includes("network")||e.includes("Network")||e.includes("fetch")||e.includes("Failed to fetch")?"网络连接失败,请检查网络后重试":e.includes("rate limit")||e.includes("429")||r===429?"请求过于频繁,请稍后重试":s==="invalid"?"API Key 无效或已过期,请重新配置":s==="missing"?"缺少 API Key,请先在设置中配置":e.includes("401")||r===401?"接口返回 401,请检查鉴权方式、账号权限或服务端策略":(e.includes("403")||r===403)&&!n.includes("quota")?"API 访问被拒绝,请检查配置":e.includes("500")||r===500?a?`AI 服务器内部错误: ${a}`:"AI 服务器内部错误,正在自动重试":e.includes("502")||r===502?a?`AI 服务暂时不可用: ${a}`:"AI 服务暂时不可用(502),正在自动重试":e.includes("503")||r===503?a?`AI 服务繁忙: ${a}`:"AI 服务繁忙(503),正在自动重试":e.includes("504")||r===504?a?`AI 服务响应超时: ${a}`:"AI 服务响应超时(504),正在自动重试":a||e}const kh=Wf,fP=2e3;function mP(){const t=m.useRef(new Set),e=m.useRef([]),n=m.useRef(null);m.useEffect(()=>{let r=!0;const s=()=>{if(r)for(;e.current.length>0&&t.current.size<kh;){const g=e.current.shift();g&&!t.current.has(g.id)&&c(g)}},a=g=>{t.current.delete(g),s()},i=async g=>{const w=g.id,x=g.remoteId;if(!t.current.has(w)){t.current.add(w);try{tl(g)&&nl("audio",g);const v=await ps.resumeAudioGeneration(w,x,ld(g));if(!r)return;xe.updateTaskStatus(w,ve.COMPLETED,{result:v})}catch(v){if(!r)return;const _=v.httpStatus?`HTTP_${v.httpStatus}`:v.name||"ERROR",T=ba(v),b=v.fullResponse||v.apiErrorBody||v.message||String(v);xe.updateTaskStatus(w,ve.FAILED,{error:{code:_,message:T,details:{originalError:b,timestamp:Date.now()}}})}finally{a(w)}}},l=async g=>{const w=g.id,x=g.remoteId;if(!t.current.has(w)){t.current.add(w);try{tl(g)&&nl("image",g);const v=await ps.resumeAsyncImageGeneration(w,x,ld(g));if(!r)return;if(xe.updateTaskStatus(w,ve.COMPLETED,{result:v}),v.url)try{await Mn.registerImageMetadata(v.url,{taskId:g.id,model:g.params.model,prompt:g.params.prompt,params:g.params})}catch(_){console.error(`[TaskExecutor] Failed to register metadata for resumed async image task ${w}:`,_)}}catch(v){if(!r)return;const _=v.httpStatus?`HTTP_${v.httpStatus}`:v.name||"ERROR",T=ba(v),b=v.fullResponse||v.apiErrorBody||v.message||String(v);xe.updateTaskStatus(w,ve.FAILED,{error:{code:_,message:T,details:{originalError:b,timestamp:Date.now()}}})}finally{a(w)}}},d=async g=>{const w=g.id;if(!t.current.has(w)){t.current.add(w);try{xe.updateTaskStatus(w,ve.PROCESSING);const{sourceVideoTaskId:x,characterTimestamps:v,model:_,prompt:T}=g.params;if(!x)throw new Error("缺少源视频任务ID");const b=await Kk.createCharacterWithPolling({videoTaskId:x,characterTimestamps:v,localTaskId:g.params.sourceLocalTaskId,sourcePrompt:T,sourceModel:_},{onStatusChange:I=>{}});if(!r)return;await Qs.saveCharacter({id:b.characterId,username:b.username,profilePictureUrl:b.profile_picture_url,permalink:b.permalink,sourceTaskId:g.params.sourceLocalTaskId||"",sourceVideoId:x,sourcePrompt:T,characterTimestamps:v,status:"completed",createdAt:g.createdAt,completedAt:Date.now()}),xe.updateTaskStatus(w,ve.COMPLETED,{result:{url:b.profile_picture_url,format:"character",size:0,characterUsername:b.username,characterProfileUrl:b.profile_picture_url,characterPermalink:b.permalink},remoteId:b.characterId})}catch(x){if(!r||(console.error(`[TaskExecutor] Character task ${w} failed:`,x),!xe.getTask(w)))return;const _=x.httpStatus?`HTTP_${x.httpStatus}`:x.name||"ERROR",T=ba(x),I={originalError:x.fullResponse||x.apiErrorBody||x.message||String(x),timestamp:Date.now()};xe.updateTaskStatus(w,ve.FAILED,{error:{code:_,message:T,details:I}})}finally{a(w)}}},c=async g=>{const w=g.id;if(g.type===He.CHARACTER)return d(g);if(g.status===ve.PROCESSING&&js(g))return l(g);if(!(g.type===He.VIDEO&&g.remoteId&&g.status===ve.PROCESSING)){if(g.type===He.AUDIO&&g.remoteId&&g.status===ve.PROCESSING)return i(g);if(!t.current.has(w)){t.current.add(w);try{xe.updateTaskStatus(w,ve.PROCESSING);const x=await ps.generate(w,g.params,g.type);if(!r)return;if(xe.updateTaskStatus(w,ve.COMPLETED,{result:x}),x.url)try{await Mn.registerImageMetadata(x.url,{taskId:g.id,model:g.params.model,prompt:g.params.prompt,params:g.params})}catch(v){console.error(`[TaskExecutor] Failed to register metadata for task ${w}:`,v)}}catch(x){if(!r||(console.error(`[TaskExecutor] Task ${w} failed:`,x),!xe.getTask(w)))return;const _=x.httpStatus?`HTTP_${x.httpStatus}`:x.name||"ERROR",T=ba(x),I={originalError:x.fullResponse||x.apiErrorBody||x.message||String(x),timestamp:Date.now()};xe.updateTaskStatus(w,ve.FAILED,{error:{code:_,message:T,details:I}})}finally{a(w)}}}},h=g=>{t.current.has(g.id)||e.current.some(w=>w.id===g.id)||(t.current.size<kh?c(g):e.current.push(g))},u=()=>{if(!r)return;const g=xe.getAllTasks(),w=g.filter(_=>_.status===ve.PENDING),x=g.filter(_=>_.status===ve.PROCESSING&&js(_)),v=g.filter(_=>_.type===He.AUDIO&&_.remoteId&&_.status===ve.PROCESSING);console.warn(`[TaskExecutor] processPendingTasks: ${g.length} total, ${w.length} pending, ${x.length} resumable-image, ${v.length} resumable-audio, ${t.current.size} executing`),w.forEach(_=>{h(_)}),x.forEach(_=>{h(_)}),v.forEach(_=>{h(_)})},p=()=>{if(!r)return;xe.getAllTasks().filter(x=>x.status===ve.PROCESSING).forEach(x=>{if(Av(x)){console.warn(`[TaskExecutor] Task ${x.id} timed out`),ps.cancelRequest(x.id);const v={originalError:`Task ${x.id} timed out after processing`,timestamp:Date.now()};xe.updateTaskStatus(x.id,ve.FAILED,{error:{code:"TIMEOUT",message:"任务执行超时",details:v}})}})},y=xe.observeTaskUpdates().subscribe(g=>{if(r&&(g.type==="taskCreated"||g.type==="taskUpdated")){const w=g.task;(w.status===ve.PENDING||!t.current.has(w.id)&&w.remoteId&&w.status===ve.PROCESSING&&js(w)||!t.current.has(w.id)&&w.remoteId&&w.type===He.AUDIO&&w.status===ve.PROCESSING)&&h(w)}}),f=setTimeout(u,fP);return n.current=setInterval(p,1e4),()=>{r=!1,y.unsubscribe(),clearTimeout(f),e.current=[],n.current&&clearInterval(n.current),t.current.forEach(g=>{ps.cancelRequest(g)}),t.current.clear()}},[])}function pP(t){return!!(t.gridImageRows&&t.gridImageCols)}function gP(t){return!!(t.isInspirationBoard&&t.inspirationBoardLayoutStyle==="inspiration-board")}function yP(t=800){const e=on();if(e)return Vf(e)}async function vP(t,e,n,r={}){const s=on();if(!s)return{success:!1,count:0,error:"Board not available"};Ve.registerTask(t,n.batchId),Ve.startPostProcessing(t,"split_and_insert");try{const a=await Ov(s,e,{scrollToResult:r.scrollToResult??!0}),i=r.insertionPoint||yP();return a.success?(Ve.completePostProcessing(t,a.count,i),{success:!0,count:a.count}):(console.warn(`[MediaResultHandler] Split failed: ${a.error}, falling back to direct insert`),(await An({items:[{type:"image",content:e}],startPoint:i})).success?(Ve.completePostProcessing(t,1,i),{success:!0,count:1}):(Ve.failPostProcessing(t,a.error||"Split and insert failed"),{success:!1,count:0,error:a.error}))}catch(a){const i=String(a);return console.error("[MediaResultHandler] Split and insert error:",a),Ve.failPostProcessing(t,i),{success:!1,count:0,error:i}}}function Ll(t){return Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number"}function wP(t,e){return!t||!e?t===e:t[0]===e[0]&&t[1]===e[1]}function Zp(t){var e;return Ll((e=t==null?void 0:t.points)==null?void 0:e[0])?t.points[0]:void 0}function xP(t){const{anchor:e,workzoneExpectedInsertPosition:n}=t,r=Zp(e);if(r)return r;if(Ll(n))return n;if(Ll(e==null?void 0:e.expectedInsertPosition))return e.expectedInsertPosition}function bP(t,e){if(typeof e=="string")return xt.getAnchorByTaskId(t,e);const n=xt.getAnchorByTaskId(t,e.id);if(n)return n;const r=Ci(e),s=Pi(e),a=Ei(e);if(s&&typeof a=="number"){const i=xt.getAnchorByBatchSlot(t,{workflowId:r,batchId:s,batchIndex:a});if(i)return i;const l=xt.getAllAnchors(t).find(d=>d.anchorType!=="stack"&&d.batchId===s&&d.batchIndex===a&&(!r||d.workflowId===r));if(l)return l}if(r){const i=xt.getAnchorsByWorkflowId(t,r);return i.find(d=>!Ac(d))||i[0]||null}return null}const _P={enabled:!0,insertPrompt:!1,groupSimilarTasks:!0,groupTimeWindow:5e3},TP=500,Vn=new Set;function wi(t){var r;const e=on();if(!e)return null;const n=fr.getAllWorkZones(e);for(const s of n)if((r=s.workflow.steps)==null?void 0:r.some(i=>{const l=i.result;return(l==null?void 0:l.taskId)===t}))return s;return null}function Za(t){const e=on();return e?bP(e,t):null}function SP(t,e){const n=on();if(!n)return;const r=t.taskIds.includes(e.id)?t.taskIds:[...t.taskIds,e.id];xt.updateAnchor(n,t.id,{taskIds:r,primaryTaskId:t.primaryTaskId||e.id})}function IP(t){Vn.add(t)}function Kt(t){Vn.delete(t)}function _a(t){Vn.add(t),xs().markAsInserted(t,"auto_insert")}function Lo(t,e,n,r={}){if(!e||!n)return;const s=on(),a=r.targetFrameId||t.params.targetFrameId;!s||!a||Da(s,a,e,n,{replaceElementId:r.replaceElementId||t.params.pptReplaceElementId,prompt:r.prompt||t.params.prompt,slidePrompt:typeof t.params.pptSlidePrompt=="string"?t.params.pptSlidePrompt:void 0,historyItems:r.historyItems,imageCreatedAt:r.imageCreatedAt||Fl(t)})}function Fl(t){const e=t.completedAt||t.updatedAt||t.createdAt;return Number.isFinite(e)&&e>0?e:Date.now()}function kP(t){var e,n,r;return(n=(e=t.result)==null?void 0:e.urls)!=null&&n.length?t.result.urls.filter(s=>!!s):(r=t.result)!=null&&r.url?[t.result.url]:[]}function Ch(t){return typeof t.params.batchIndex=="number"?t.params.batchIndex:Number.MAX_SAFE_INTEGER}function Ph(t,e,n){return t.map(r=>({imageUrl:r,...e?{prompt:e}:{},...n?{createdAt:n}:{}}))}function Bl(t){return Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number"}function Eh(t){return typeof t=="object"&&t!==null&&typeof t.width=="number"&&typeof t.height=="number"}function Ah(t,e){const n=t.result;return typeof(n==null?void 0:n.width)=="number"&&typeof(n==null?void 0:n.height)=="number"&&n.width>0&&n.height>0?{width:n.width,height:n.height}:e||Ys(t.params.size)}function jh(t,e){if(!t||t.anchorType!=="stack")return e}function nr(t,e,n){if(!t||!e)return;const r={};n.position&&(r.expectedInsertPosition=n.position),n.transitionMode&&n.transitionMode!==e.transitionMode&&(r.transitionMode=n.transitionMode),Object.keys(r).length>0&&xt.updateAnchor(t,e.id,r),(n.position||n.size)&&xt.updateGeometry(t,e.id,{position:n.position,size:n.size})}function rr(t,e){const n=t==null?void 0:t.data;return Bl(n==null?void 0:n.firstElementPosition)?n.firstElementPosition:e}function gs(t,e,n,r){const s=t==null?void 0:t.data,a=(s==null?void 0:s.items.find(d=>r==null?void 0:r.includes(d.type)))??(s==null?void 0:s.items[0]),i=Bl(a==null?void 0:a.point)?a.point:Bl(s==null?void 0:s.firstElementPosition)?s.firstElementPosition:e,l=Eh(a==null?void 0:a.size)?a.size:Eh(s==null?void 0:s.firstElementSize)?s.firstElementSize:n;return{elementId:(a==null?void 0:a.elementId)??(s==null?void 0:s.firstElementId),position:i,size:l}}function CP(t,e){var d;const n=wi(e.id),r=Za(e);let s=xP({anchor:r,workzoneExpectedInsertPosition:n==null?void 0:n.expectedInsertPosition}),a,i;const l=Zp(r);return r&&l&&!wP(r.expectedInsertPosition,l)&&xt.updateAnchor(t,r.id,{expectedInsertPosition:l}),n!=null&&n.targetFrameId&&(n!=null&&n.targetFrameDimensions)&&(a=n.targetFrameId,i=n.targetFrameDimensions),!a&&(r!=null&&r.targetFrameId)&&(r!=null&&r.targetFrameDimensions)&&(a=r.targetFrameId,i=r.targetFrameDimensions),!a&&((d=e.params)!=null&&d.targetFrameId)&&(a=e.params.targetFrameId,i=e.params.targetFrameDimensions),r&&(SP(r,e),xt.updateAnchor(t,r.id,yi("inserting"))),s||(s=Vf(t)),{insertionPoint:s,targetFrameId:a,targetFrameDimensions:i,imageAnchor:r}}function Fo(t,e,n,r){var l;const s=on();if(!s)return;const a=wi(t);if(!a)return;const i=(l=a.workflow.steps)==null?void 0:l.map(d=>{const c=d.result;return(c==null?void 0:c.taskId)===t?(typeof d.result=="object"&&d.result!==null&&d.result,{...d,status:e,result:d.result,error:r}):d});i&&fr.updateWorkflow(s,a.id,{steps:i})}function PP(t={}){const e={..._P,...t},n=m.useRef(new Map),r=m.useRef(null);m.useEffect(()=>{if(!e.enabled)return;let s=!0;function a(g=e.groupTimeWindow){r.current&&clearTimeout(r.current),r.current=setTimeout(()=>{r.current=null,i().catch(w=>{console.error("[AutoInsert] Failed to flush pending inserts:",w)})},g)}async function i(){var v,_,T,b,I,A,k,U,D,X,L,O,G,C,P,j,N,B,K,fe,ae,te;const g=n.current;if(g.size===0)return;const w=on();if(!w||!s){!w&&s&&a(TP);return}const x=new Map(g);g.clear();for(const[Se,Ee]of x){if(!s){for(const{task:R}of Ee)Kt(R.id);continue}const Te=(v=Ee[0])==null?void 0:v.task;if(!Te)continue;const{insertionPoint:ke,targetFrameId:ne,targetFrameDimensions:M,imageAnchor:q}=CP(w,Te);if(!ke){for(const{task:R}of Ee)Kt(R.id),Ve.failPostProcessing(R.id,"No insertion point available");continue}for(const{task:R}of Ee){const J=R.params.batchId;Ve.registerTask(R.id,J),Ve.startPostProcessing(R.id,Ee.length===1?"direct_insert":"group_insert")}try{if(Ee.length===1){const{task:R}=Ee[0],J=Ga(R),Ce=(_=R.result)==null?void 0:_.url,re=typeof Ce=="string"&&Ce.length>0,ze=Array.isArray((T=R.result)==null?void 0:T.urls)&&R.result.urls.length>0;if(!re&&!ze&&!J){Kt(R.id),Ve.failPostProcessing(R.id,"No result URL");continue}const V=J?"text":R.type===He.VIDEO?"video":R.type===He.AUDIO?"audio":"image",z=V==="audio"?{width:dd,height:cd}:V==="text"?void 0:Ys(R.params.size),F=V==="audio"?{title:((b=R.result)==null?void 0:b.title)||R.params.title,duration:typeof((k=(A=(I=R.result)==null?void 0:I.clips)==null?void 0:A[0])==null?void 0:k.duration)=="number"?R.result.clips[0].duration||void 0:(U=R.result)==null?void 0:U.duration,previewImageUrl:(D=R.result)==null?void 0:D.previewImageUrl,tags:typeof R.params.tags=="string"?R.params.tags:void 0,mv:typeof R.params.mv=="string"?R.params.mv:void 0,prompt:R.params.prompt,providerTaskId:((X=R.result)==null?void 0:X.providerTaskId)||R.remoteId,clipId:((L=R.result)==null?void 0:L.primaryClipId)||((C=(G=(O=R.result)==null?void 0:O.clips)==null?void 0:G[0])==null?void 0:C.clipId)||((N=(j=(P=R.result)==null?void 0:P.clips)==null?void 0:j[0])==null?void 0:N.id)||((K=(B=R.result)==null?void 0:B.clipIds)==null?void 0:K[0]),clipIds:(fe=R.result)==null?void 0:fe.clipIds}:void 0,pe=V==="audio"?F:void 0,ce=V==="text"?[ko(R)]:V==="audio"?Ao(R.result):(te=(ae=R.result)==null?void 0:ae.urls)!=null&&te.length?R.result.urls:[Ce],Z=ne||R.params.targetFrameId,ue=M||R.params.targetFrameDimensions,ye=V==="image"?q??Za(R):null,ie=V==="image"?Ah(R,z):void 0;let Ae=ke,Q,Pe=ie,$e=!1;if(R.params.pptSlideImage&&Z&&ue&&w&&V==="image"&&ce.length>0){const de=ce[ce.length-1],Ge=await zr(w,de,V,Z,ue,void 0);Ge&&(Ae=Ge.point,Q=Ge.elementId,Pe=Ge.size,nr(w,ye,{position:Ge.point,size:Ge.size,transitionMode:(ye==null?void 0:ye.anchorType)==="ghost"?"morph":"hold"}),Lo(R,Q,de,{targetFrameId:Z,replaceElementId:R.params.pptReplaceElementId,historyItems:Ph(ce.slice(0,-1),R.params.prompt,Fl(R))}),$e=!0)}else if(Z&&ue&&w&&V!=="audio"&&V!=="text"&&ce.length===1){const de=await zr(w,ce[0],V,Z,ue,R.params.pptSlideImage&&V==="image"?void 0:z);de&&(Ae=de.point,Q=de.elementId,Pe=de.size,nr(w,ye,{position:de.point,size:de.size,transitionMode:(ye==null?void 0:ye.anchorType)==="ghost"?"morph":"hold"}))}else if(e.insertPrompt&&V!=="text"){const de=await Nu(R.params.prompt,ce.map((it,Ye)=>{var Ue,oe,ft,je,ge,De,We,Re,gt,ut,lt,Rt,Ut,Jt,Lt,Qt,jt,en,Ot,$;return{type:V,url:it,dimensions:z,metadata:V==="audio"?{...F,title:((ft=(oe=(Ue=R.result)==null?void 0:Ue.clips)==null?void 0:oe[Ye])==null?void 0:ft.title)||(ce.length>1?`${(F==null?void 0:F.title)||R.params.title||"Audio"} ${Ye+1}`:F==null?void 0:F.title),previewImageUrl:((De=(ge=(je=R.result)==null?void 0:je.clips)==null?void 0:ge[Ye])==null?void 0:De.imageLargeUrl)||((gt=(Re=(We=R.result)==null?void 0:We.clips)==null?void 0:Re[Ye])==null?void 0:gt.imageUrl)||(F==null?void 0:F.previewImageUrl),duration:typeof((Rt=(lt=(ut=R.result)==null?void 0:ut.clips)==null?void 0:lt[Ye])==null?void 0:Rt.duration)=="number"?R.result.clips[Ye].duration||void 0:F==null?void 0:F.duration,clipId:((Lt=(Jt=(Ut=R.result)==null?void 0:Ut.clips)==null?void 0:Jt[Ye])==null?void 0:Lt.clipId)||((en=(jt=(Qt=R.result)==null?void 0:Qt.clips)==null?void 0:jt[Ye])==null?void 0:en.id)||(($=(Ot=R.result)==null?void 0:Ot.clipIds)==null?void 0:$[Ye])||(F==null?void 0:F.clipId)}:void 0}}),ke),Ge=gs(de,ke,ie,["image"]);Ae=Ge.position,Q=Ge.elementId,Pe=Ge.size}else if(V==="image"&&ce.length>1){ye&&nr(w,ye,{position:ke,size:jh(ye,ie),transitionMode:"morph"});const de=await Du(ce,ke,z),Ge=gs(de,ke,ie,["image"]);Ae=Ge.position,Q=Ge.elementId,Pe=Ge.size}else if(V==="text"){const de=Ml(R.result,R.params.title||R.params.prompt)||(R.params.prompt||"").slice(0,20)||void 0,Ge=await An({items:[{type:"text",content:ce[0],label:de}],startPoint:ke});Ae=rr(Ge,ke)}else if(V==="audio"&&ce.length>1){const de=`audio-group-${R.id}`,Ge=await An({items:ce.map((it,Ye)=>{var Ue,oe,ft,je,ge,De,We,Re,gt,ut,lt,Rt,Ut,Jt,Lt,Qt,jt,en,Ot,$;return{type:"audio",content:it,groupId:de,dimensions:z,metadata:{...F,title:((ft=(oe=(Ue=R.result)==null?void 0:Ue.clips)==null?void 0:oe[Ye])==null?void 0:ft.title)||(ce.length>1?`${(F==null?void 0:F.title)||R.params.title||"Audio"} ${Ye+1}`:F==null?void 0:F.title),previewImageUrl:((De=(ge=(je=R.result)==null?void 0:je.clips)==null?void 0:ge[Ye])==null?void 0:De.imageLargeUrl)||((gt=(Re=(We=R.result)==null?void 0:We.clips)==null?void 0:Re[Ye])==null?void 0:gt.imageUrl)||(F==null?void 0:F.previewImageUrl),duration:typeof((Rt=(lt=(ut=R.result)==null?void 0:ut.clips)==null?void 0:lt[Ye])==null?void 0:Rt.duration)=="number"?R.result.clips[Ye].duration||void 0:F==null?void 0:F.duration,clipId:((Lt=(Jt=(Ut=R.result)==null?void 0:Ut.clips)==null?void 0:Jt[Ye])==null?void 0:Lt.clipId)||((en=(jt=(Qt=R.result)==null?void 0:Qt.clips)==null?void 0:jt[Ye])==null?void 0:en.id)||(($=(Ot=R.result)==null?void 0:Ot.clipIds)==null?void 0:$[Ye])||(F==null?void 0:F.clipId)}}}),startPoint:ke});Ae=rr(Ge,ke)}else{V==="image"&&ye&&!e.insertPrompt&&ie&&nr(w,ye,{position:ke,size:ie,transitionMode:ye.anchorType==="ghost"?"morph":"hold"});const de=await Mu(V,ce[0],ke,z,pe);if(V==="image"){const Ge=gs(de,ke,ie,["image"]);Ae=Ge.position,Q=Ge.elementId,Pe=Ge.size}else Ae=rr(de,ke)}V==="image"&&ye&&Pe&&nr(w,ye,{position:Ae,size:Pe,transitionMode:ye.anchorType==="ghost"?"morph":"hold"}),V==="image"&&!$e&&Lo(R,Q,ce[0],{targetFrameId:Z,replaceElementId:R.params.pptReplaceElementId}),Ve.completePostProcessing(R.id,ce.length,Ae,V==="image"?Q:void 0,V==="image"?Pe:void 0),_a(R.id)}else{const R=Ga(Te),J=R?Ee.map(({task:Z})=>ko(Z)):Ee.flatMap(({task:Z})=>{var ue,ye,ie;return Te.type===He.AUDIO?Ao(Z.result):(ye=(ue=Z.result)==null?void 0:ue.urls)!=null&&ye.length?Z.result.urls:[(ie=Z.result)==null?void 0:ie.url]}).filter(Z=>!!Z),Ce=Te.type===He.AUDIO?Ee.flatMap(({task:Z})=>{var ie,Ae,Q,Pe,$e,de,Ge,it;const ue=Ao(Z.result),ye={title:((ie=Z.result)==null?void 0:ie.title)||Z.params.title,duration:typeof((Pe=(Q=(Ae=Z.result)==null?void 0:Ae.clips)==null?void 0:Q[0])==null?void 0:Pe.duration)=="number"?Z.result.clips[0].duration||void 0:($e=Z.result)==null?void 0:$e.duration,previewImageUrl:(de=Z.result)==null?void 0:de.previewImageUrl,tags:typeof Z.params.tags=="string"?Z.params.tags:void 0,mv:typeof Z.params.mv=="string"?Z.params.mv:void 0,prompt:Z.params.prompt,providerTaskId:((Ge=Z.result)==null?void 0:Ge.providerTaskId)||Z.remoteId,clipIds:(it=Z.result)==null?void 0:it.clipIds};return ue.map((Ye,Ue)=>{var oe,ft,je,ge,De,We,Re,gt,ut,lt,Rt,Ut,Jt,Lt,Qt,jt,en,Ot,$,Oe;return{url:Ye,metadata:{...ye,title:((je=(ft=(oe=Z.result)==null?void 0:oe.clips)==null?void 0:ft[Ue])==null?void 0:je.title)||(ue.length>1?`${ye.title||Z.params.title||"Audio"} ${Ue+1}`:ye.title),previewImageUrl:((We=(De=(ge=Z.result)==null?void 0:ge.clips)==null?void 0:De[Ue])==null?void 0:We.imageLargeUrl)||((ut=(gt=(Re=Z.result)==null?void 0:Re.clips)==null?void 0:gt[Ue])==null?void 0:ut.imageUrl)||ye.previewImageUrl,duration:typeof((Ut=(Rt=(lt=Z.result)==null?void 0:lt.clips)==null?void 0:Rt[Ue])==null?void 0:Ut.duration)=="number"?Z.result.clips[Ue].duration||void 0:ye.duration,clipId:((Qt=(Lt=(Jt=Z.result)==null?void 0:Jt.clips)==null?void 0:Lt[Ue])==null?void 0:Qt.clipId)||((Ot=(en=(jt=Z.result)==null?void 0:jt.clips)==null?void 0:en[Ue])==null?void 0:Ot.id)||((Oe=($=Z.result)==null?void 0:$.clipIds)==null?void 0:Oe[Ue])}}})}):[];if(J.length===0){for(const{task:Z}of Ee)Kt(Z.id),Ve.failPostProcessing(Z.id,"No result URL");continue}const re=R?"text":Te.type===He.VIDEO?"video":Te.type===He.AUDIO?"audio":"image",ze=re==="audio"?{width:dd,height:cd}:re==="text"?void 0:Ys(Te.params.size),V=re==="image"?q??Za(Te):null,z=re==="image"?Ah(Te,ze):void 0;let F=ke,pe,ce=z;if(Te.params.pptSlideImage&&ne&&M&&re==="image"){const ue=Ee.map((Ae,Q)=>({insert:Ae,sourceIndex:Q})).sort((Ae,Q)=>Ch(Ae.insert.task)-Ch(Q.insert.task)||Ae.sourceIndex-Q.sourceIndex).map(({insert:Ae})=>Ae).flatMap(({task:Ae})=>Ph(kP(Ae),Ae.params.prompt,Fl(Ae))),ye=ue[ue.length-1];if(!ye){for(const{task:Ae}of Ee)Kt(Ae.id),Ve.failPostProcessing(Ae.id,"No result URL");continue}const ie=await zr(w,ye.imageUrl,re,ne,M,void 0);ie&&(F=ie.point,pe=ie.elementId,ce=ie.size,Lo(Te,pe,ye.imageUrl,{targetFrameId:ne,replaceElementId:Te.params.pptReplaceElementId,prompt:ye.prompt,imageCreatedAt:ye.createdAt,historyItems:ue.slice(0,-1)}))}else if(e.insertPrompt&&re!=="text"){const Z=await Nu(Te.params.prompt,J.map((ue,ye)=>{var ie;return{type:re,url:ue,dimensions:ze,metadata:re==="audio"?{...(ie=Ce[ye])==null?void 0:ie.metadata}:void 0}}),ke);if(re==="image"){const ue=gs(Z,ke,z,["image"]);F=ue.position,pe=ue.elementId,ce=ue.size}else F=rr(Z,ke)}else if(re==="image"){V&&nr(w,V,{position:ke,size:jh(V,z),transitionMode:"morph"});const Z=await Du(J,ke,ze),ue=gs(Z,ke,z,["image"]);F=ue.position,pe=ue.elementId,ce=ue.size}else if(re==="text"){const Z=await An({items:Ee.map(({task:ue})=>({type:"text",content:ko(ue),label:Ml(ue.result,ue.params.title||ue.params.prompt)||(ue.params.prompt||"").slice(0,20)||void 0,groupId:`lyrics-group-${Te.id}`})),startPoint:ke});F=rr(Z,ke)}else if(re==="audio"){const Z=`audio-group-${Te.id}`,ue=await An({items:Ce.map(ye=>({type:"audio",content:ye.url,groupId:Z,dimensions:ze,metadata:ye.metadata})),startPoint:ke});F=rr(ue,ke)}else for(const Z of J){const ue=await Mu("video",Z,ke,ze);F=rr(ue,ke)}re==="image"&&V&&ce&&nr(w,V,{position:F,size:ce,transitionMode:"morph"});for(const{task:Z}of Ee)Ve.completePostProcessing(Z.id,1,F,re==="image"?pe:void 0,re==="image"?ce:void 0),_a(Z.id)}}catch(R){console.error(`[AutoInsert] Failed to insert for prompt ${Se}:`,R);for(const{task:J}of Ee)Kt(J.id),Ve.failPostProcessing(J.id,String(R))}}}const l=async g=>{var v;const w=(v=g.result)==null?void 0:v.url;if(!w){console.error("[AutoInsert] Split task has no result URL"),Kt(g.id),Ve.failPostProcessing(g.id,"No result URL"),Fo(g.id,"failed",void 0,"No result URL");return}const x=g.params;try{const _=await vP(g.id,w,x,{scrollToResult:!0});if(_.success){_a(g.id);return}Kt(g.id),Fo(g.id,"failed",void 0,_.error||"拆分失败")}catch(_){const T=String(_);Kt(g.id),Ve.failPostProcessing(g.id,T),Fo(g.id,"failed",void 0,T)}},d=g=>{var A,k,U,D,X,L;const w=wi(g.id),x=Za(g);if(!(g.params.autoInsertToCanvas||!!w||!!x)||Vn.has(g.id))return;if(g.insertedToCanvas){Vn.add(g.id);return}const _=(A=Ve.getPostProcessingStatus(g.id))==null?void 0:A.status;if(_==="completed"){Vn.add(g.id);return}if(_==="processing"||g.type!==He.IMAGE&&g.type!==He.VIDEO&&g.type!==He.AUDIO&&g.type!==He.CHAT||!((k=g.result)!=null&&k.url)&&!((D=(U=g.result)==null?void 0:U.urls)!=null&&D.length)&&!Ga(g)&&!((X=g.result)!=null&&X.chatResponse))return;IP(g.id);const T=g.params;if(g.type===He.CHAT){const O=(g.params.prompt||"").slice(0,20)||void 0;An({items:[{type:"text",content:((L=g.result)==null?void 0:L.chatResponse)||"",label:O}]}).then(()=>{Ve.completePostProcessing(g.id,1),_a(g.id)}).catch(G=>{Kt(g.id),Ve.failPostProcessing(g.id,String(G))});return}if(gP(T)){l(g);return}if(pP(T)){l(g);return}const b=pk(g,x),I=n.current.get(b)||[];I.push({task:g,completedAt:Date.now()}),n.current.set(b,I),e.groupSimilarTasks?a():i().catch(O=>{console.error("[AutoInsert] Failed to flush pending inserts:",O)})},c=()=>{xs().getAllTasks().forEach(g=>{g.status===ve.COMPLETED&&d(g)})},h=g=>{var w,x;if((w=g.params)!=null&&w.pptSlideImage&&((x=g.params)!=null&&x.targetFrameId)){const v=on();v&&qt(v,g.params.targetFrameId,{slideImageStatus:"failed",imageStatus:"failed"})}},p=xs().observeTaskUpdates().subscribe(g=>{s&&(g.type==="taskUpdated"||g.type==="taskCompleted"?g.task.status===ve.COMPLETED?d(g.task):(g.task.status===ve.FAILED||g.task.status===ve.CANCELLED)&&h(g.task):g.type==="taskFailed"?h(g.task):g.type==="taskSynced"?g.task.status===ve.COMPLETED&&d(g.task):g.type==="taskCreated"&&c())});c();const y=Ve.observeCompletionEvents().subscribe(g=>{var w,x;if(g.type==="postProcessingCompleted"||g.type==="postProcessingFailed"){const v=on();if(!v)return;const _=wi(g.taskId);_&&((w=_.workflow.steps)!=null&&w.every(b=>b.status==="completed"||b.status==="failed"||b.status==="skipped"))&&(x=_.workflow.steps)!=null&&x.every(I=>{const A=I.result;return A!=null&&A.taskId?Ve.isPostProcessingCompleted(A.taskId):!0})&&setTimeout(()=>{fr.removeWorkZone(v,_.id)},1500)}}),f=g=>{var A,k,U;const w=g,x=(A=w.detail)==null?void 0:A.taskId,v=(k=w.detail)==null?void 0:k.anchorId,_=(D,X)=>{if(!v)return;const L=on();L&&xt.updateAnchor(L,v,yi(D,X))};if(!x){_("failed",{error:"任务未绑定,无法重试"});return}const T=xs().getTask(x);if(!T){_("failed",{error:"任务已丢失,无法重试"});return}const b=(U=Ve.getPostProcessingStatus(x))==null?void 0:U.status;if(T.status===ve.COMPLETED){if(T.insertedToCanvas||b==="completed"){Vn.add(x),_("completed");return}if(Vn.has(x)||b==="processing")return}if(T.status===ve.PENDING||T.status===ve.PROCESSING){_("accepted",{subtitle:"任务仍在执行,请稍候"});return}const I=T.status===ve.COMPLETED&&b==="failed";if(T.status===ve.FAILED||T.status===ve.CANCELLED||I){_("retrying"),Kt(x),Ve.clearTask(x),xs().retryTask(x,I?{allowCompleted:!0}:void 0);return}T.status===ve.COMPLETED&&(Kt(x),Ve.clearTask(x),d(T))};return window.addEventListener(gi,f),()=>{s=!1,p.unsubscribe(),y.unsubscribe(),window.removeEventListener(gi,f),r.current&&(clearTimeout(r.current),r.current=null);const g=n.current;for(const[,w]of g)for(const{task:x}of w)Kt(x.id);g.clear()}},[e.enabled,e.insertPrompt,e.groupSimilarTasks,e.groupTimeWindow])}const EP=1600,AP=1e4,jP=45e3;function OP(t){return t.type===He.IMAGE}function MP(t,e){return t.length!==e.length?!1:t.every((n,r)=>n===e[r])}function DP(t,e){if(e.length===0)return;const n=e.map(i=>Ve.getPostProcessingStatus(i.id)).filter(i=>!!i),r=n.some(i=>i.status==="failed"),s=e.some(i=>{const l=Ve.getPostProcessingStatus(i.id);return i.status!==ve.FAILED&&(l==null?void 0:l.status)!=="failed"});if(r&&!s)return"failed";if(n.some(i=>i.status==="processing"))return"processing";if(Js(t,e)&&e.every(i=>{var l;return!!i.insertedToCanvas||((l=Ve.getPostProcessingStatus(i.id))==null?void 0:l.status)==="completed"}))return"completed"}function NP(t,e,n){var s,a,i;const r=n.map(l=>Ve.getPostProcessingStatus(l.id)).find(l=>(l==null?void 0:l.status)==="failed");return(r==null?void 0:r.error)||((s=e==null?void 0:e.error)==null?void 0:s.message)||((i=(a=e==null?void 0:e.error)==null?void 0:a.details)==null?void 0:i.originalError)||t.error}function RP(t,e){var r;const n=e==null?void 0:e.result;return(n==null?void 0:n.previewImageUrl)||(n==null?void 0:n.url)||((r=n==null?void 0:n.urls)==null?void 0:r.find(s=>typeof s=="string"&&s.length>0))||t.previewImageUrl}function LP(t,e){const n=Ai(t,e),r=ji(t,n),s=t.primaryTaskId||(r==null?void 0:r.id)||t.taskIds[0];if(!(!s||n.length>0&&Js(t,n)&&n.every(i=>{var l;return!!i.insertedToCanvas||((l=Ve.getPostProcessingStatus(i.id))==null?void 0:l.status)==="completed"})))return s}function Bo(t,e){return!t||!e?t===e:t[0]===e[0]&&t[1]===e[1]}function FP(t){return typeof t=="object"&&t!==null&&Array.isArray(t.points)&&t.points.length===2}function BP(t,e){if(!(e!=null&&e.firstElementId))return;const n=t.children.find(s=>s.id===e.firstElementId);if(!FP(n))return;const r=Fe.getRectangleByPoints(n.points);return{position:n.points[0],size:{width:r.width,height:r.height}}}function zP(t,e,n){var s,a;if(t.anchorType==="stack")return;if(typeof((s=n==null?void 0:n.firstElementSize)==null?void 0:s.width)=="number"&&typeof((a=n==null?void 0:n.firstElementSize)==null?void 0:a.height)=="number"&&n.firstElementSize.width>0&&n.firstElementSize.height>0)return{width:n.firstElementSize.width,height:n.firstElementSize.height};const r=e==null?void 0:e.result;return typeof(r==null?void 0:r.width)=="number"&&typeof(r==null?void 0:r.height)=="number"&&r.width>0&&r.height>0?{width:r.width,height:r.height}:t.targetFrameDimensions||Ys(t.requestedSize)}function $P(t,e,n){const r={};if(e&&!Bo(t.expectedInsertPosition,e)&&(r.expectedInsertPosition=e),e&&n){const s=[e,[e[0]+n.width,e[1]+n.height]],[a,i]=t.points;Bo(a,s[0])&&Bo(i,s[1])||(r.points=s)}return r}function UP(t,e,n){if(n.current.has(e))return;const r=setTimeout(()=>{n.current.delete(e);const s=xt.getAnchorById(t,e);!s||s.phase!=="completed"||xt.removeAnchor(t,e)},EP);n.current.set(e,r)}function Oh(t,e){const n=e.current.get(t);n&&(clearTimeout(n),e.current.delete(t))}function HP({board:t,enabled:e=!0}){const n=m.useRef(new Map);m.useEffect(()=>{if(!t||!e)return;const r=n.current,s=u=>{const p=xt.getAnchorById(t,u);if(!p){Oh(u,n);return}const y=xe.getAllTasks(),f=Ai(p,y),g=ji(p,f),w=yk(p,f),x=p.primaryTaskId||(g==null?void 0:g.id),v=DP(p,f),_=(x?Ve.getPostProcessingStatus(x):void 0)||f.map(O=>Ve.getPostProcessingStatus(O.id)).find(O=>!!O),T=f.length>0&&Js(p,f)&&f.every(O=>{var G;return!!O.insertedToCanvas||((G=Ve.getPostProcessingStatus(O.id))==null?void 0:G.status)==="completed"}),b=NP(p,g,f),I=RP(p,g),A=BP(t,_),k=Ep({anchor:{...p,taskIds:w,primaryTaskId:x,error:b},task:g??void 0,tasks:f,postProcessingStatus:v,isInserting:p.phase==="inserting"&&v==="processing",hasInserted:T}),{viewModel:U,nextPatch:D}=k,X={};MP(p.taskIds,w)||(X.taskIds=w),x&&x!==p.primaryTaskId&&(X.primaryTaskId=x),p.phase!==D.phase&&(X.phase=D.phase),(p.progress??null)!==(D.progress??null)&&(X.progress=D.progress),(p.subtitle??"")!==(D.subtitle??"")&&(X.subtitle=D.subtitle),(p.error??void 0)!==(D.error??void 0)&&(X.error=D.error),(p.previewImageUrl??"")!==(I??"")&&(X.previewImageUrl=I);const L=$P(p,(A==null?void 0:A.position)??(_==null?void 0:_.firstElementPosition),(A==null?void 0:A.size)??zP(p,g,_));Object.assign(X,L),_!=null&&_.firstElementPosition&&p.transitionMode!==(p.anchorType==="frame"?"hold":"morph")&&(X.transitionMode=p.anchorType==="frame"?"hold":"morph"),Object.keys(X).length>0&&xt.updateAnchor(t,p.id,X),U.phase==="completed"&&T?UP(t,p.id,n):Oh(p.id,n)},a=()=>{xt.getAllAnchors(t).forEach(u=>{s(u.id)})},i=u=>{const p=new Set,y=xt.getAnchorByTaskId(t,u.id);y&&p.add(y.id);const f=Ci(u),g=Pi(u),w=Ei(u);let x=!1;if(f&&g&&typeof w=="number"){const v=xt.getAnchorByBatchSlot(t,{workflowId:f,batchId:g,batchIndex:w});v&&(p.add(v.id),x=!0)}if(f&&!x&&xt.getAnchorsByWorkflowId(t,f).forEach(v=>{p.add(v.id)}),p.size===0){a();return}p.forEach(v=>s(v))};a();const l=xe.observeTaskUpdates().subscribe(u=>{OP(u.task)&&i(u.task)}),d=Ve.observeCompletionEvents().subscribe(u=>{const p=xt.getAnchorByTaskId(t,u.taskId);if(p){s(p.id);return}a()}),c=new Map,h=setInterval(()=>{const u=xt.getAllAnchors(t),p=Date.now();for(const y of u)if(y.phase==="developing"||y.phase==="inserting"){const f=c.get(y.id);if(!f)c.set(y.id,p);else if(p-f>jP){c.delete(y.id),s(y.id);const g=xt.getAnchorById(t,y.id);if(!g||g.phase!=="developing"&&g.phase!=="inserting")continue;const w=LP(g,xe.getAllTasks());w&&window.dispatchEvent(new CustomEvent(gi,{detail:{taskId:w}}))}}else c.delete(y.id)},AP);return()=>{l.unsubscribe(),d.unsubscribe(),clearInterval(h),r.forEach(u=>clearTimeout(u)),r.clear()}},[t,e])}function GP(){m.useEffect(()=>{const t=e=>{if(jx())return e.preventDefault(),e.returnValue="",""};return window.onbeforeunload=t,()=>{window.onbeforeunload=null}},[])}function WP(){return()=>{}}const VP=6e4;function Ta(t,e){const n=window.requestIdleCallback;if(typeof n=="function"){const s=n(t,{timeout:e});return()=>{var a;(a=window.cancelIdleCallback)==null||a.call(window,s)}}const r=window.setTimeout(t,Math.min(e,500));return()=>window.clearTimeout(r)}function Mh({board:t,value:e}){const n=iP(),r=Mv();return m.useEffect(()=>{if(r.length===0)return;const s=window.setTimeout(()=>{Dv.warmupProfiles(r)},0);return()=>{window.clearTimeout(s)}},[r]),m.useEffect(()=>WP(),[]),m.useEffect(()=>{if(!(!e||e.length===0))return Ta(()=>{nP.preloadBoardFonts(e).catch(s=>{console.warn("[DrawnixDeferredRuntime] Failed to preload board fonts:",s)})},2e3)},[e]),m.useEffect(()=>{if(t)return Ta(()=>{Xe(()=>import("./video-recovery-service-CgZ3pA_1.js"),__vite__mapDeps([0]),import.meta.url).then(s=>{const a=s==null?void 0:s.initVideoRecoveryService;if(typeof a!="function"){console.warn("[DrawnixDeferredRuntime] Video recovery service unavailable.");return}a(t)}).catch(s=>{console.warn("[DrawnixDeferredRuntime] Failed to load video recovery service:",s)})},3e3)},[t]),m.useEffect(()=>{if(n)return Ta(()=>{(async()=>{try{const{workflowRecoveryPromise:d}=await Xe(async()=>{const{workflowRecoveryPromise:c}=await import("./useWorkflowSubmission-DTWha6Vn.js").then(h=>h.d);return{workflowRecoveryPromise:c}},__vite__mapDeps([0]),import.meta.url);await Promise.race([d,new Promise(c=>window.setTimeout(c,5e3))])}catch{}const[{fallbackMediaExecutor:a},{taskQueueService:i}]=await Promise.all([Xe(()=>import("./ai-chat-B-XdoWBQ.js").then(d=>d.sK),__vite__mapDeps([0]),import.meta.url),Xe(()=>import("./ai-chat-B-XdoWBQ.js").then(d=>d.sN),__vite__mapDeps([0]),import.meta.url)]),l=i.getAllTasks();a.resumePendingTasks((d,c,h)=>{i.updateTaskStatus(d,c,h)},l)})().catch(a=>{console.error("[DrawnixDeferredRuntime] Failed to resume tasks:",a)})},5e3)},[n]),m.useEffect(()=>{if(!(!n||!t||!e||e.length===0))return Ta(()=>{(async()=>{const[{WorkZoneTransforms:a},{TaskStatus:i},{taskQueueService:l}]=await Promise.all([Xe(()=>Promise.resolve().then(()=>Po),void 0,import.meta.url),Xe(()=>import("./ai-chat-B-XdoWBQ.js").then(c=>c.sF),__vite__mapDeps([0]),import.meta.url),Xe(()=>import("./ai-chat-B-XdoWBQ.js").then(c=>c.sN),__vite__mapDeps([0]),import.meta.url)]),d=a.getAllWorkZones(t);for(const c of d){if(c.createdAt&&Date.now()-c.createdAt<VP)continue;const h={...c.workflow,steps:[...c.workflow.steps]},u=h.steps.some(f=>f.status==="running"||f.status==="pending");if(h.status==="completed"&&!u){a.removeWorkZone(t,c.id);continue}if(!u)continue;const p=h.steps.map(f=>{var x,v;if(f.status!=="running"&&f.status!=="pending")return f;const g=(x=f.result)==null?void 0:x.taskId;if(!g){const _=["generate_image","generate_video","generate_grid_image","generate_inspiration_board","generate_ppt"];return f.mcp==="ai_analyze"||_.includes(f.mcp)?f:f.status==="running"?{...f,status:"failed",error:"页面刷新导致中断,请删除后重新发起"}:f}const w=l.getTask(g);if(!w)return{...f,status:"failed",error:"任务未找到,请重试"};switch(w.status){case i.COMPLETED:return{...f,status:"completed",result:{taskId:g,result:w.result}};case i.FAILED:return{...f,status:"failed",error:((v=w.error)==null?void 0:v.message)||"任务执行失败"};case i.CANCELLED:return{...f,status:"skipped"};default:return f}});p.some((f,g)=>{var w;return f.status!==((w=h.steps[g])==null?void 0:w.status)})&&a.updateWorkflow(t,c.id,{steps:p})}})().catch(a=>{console.error("[DrawnixDeferredRuntime] Failed to restore WorkZones:",a)})},2e3)},[t,n,e]),m.useEffect(()=>{if(!t)return;let s=null;return(async()=>{const i=await Xe(()=>import("./workflow-submission-service-C-6Uf9FA.js").then(c=>c.a),__vite__mapDeps([0]),import.meta.url),{WorkZoneTransforms:l}=await Xe(async()=>{const{WorkZoneTransforms:c}=await Promise.resolve().then(()=>Po);return{WorkZoneTransforms:c}},void 0,import.meta.url),{workflowSubmissionService:d}=i;s=d.subscribeToAllEvents(c=>{const h=c,p=l.getAllWorkZones(t).find(y=>y.workflow.id===h.workflowId);if(p)switch(h.type){case"step":{const y=p.workflow.steps.map(f=>f.id===h.stepId?{...f,status:h.status||f.status,result:h.result??f.result,error:h.error??f.error,duration:h.duration??f.duration}:f);l.updateWorkflow(t,p.id,{steps:y});break}case"steps_added":{const y=(h.steps||[]).map(f=>({id:f.id,mcp:f.mcp,args:f.args,description:f.description,status:f.status}));l.updateWorkflow(t,p.id,{steps:[...p.workflow.steps,...y]});break}case"completed":case"failed":{const y=h.type==="completed"?"completed":"failed",f=p.workflow.steps.map(g=>{if(g.status!=="running"&&g.status!=="pending")return g;const w=g.result;return w!=null&&w.taskId?g:{...g,status:y,error:h.type==="failed"?h.error:void 0}});l.updateWorkflow(t,p.id,{steps:f});break}case"recovered":{h.workflow&&l.updateWorkflow(t,p.id,{steps:h.workflow.steps,status:h.workflow.status});break}}})})().catch(i=>{console.error("[DrawnixDeferredRuntime] Failed to setup workflow sync:",i)}),()=>{s==null||s.unsubscribe()}},[t]),m.useEffect(()=>{if(!n||!t)return;let s=null;return(async()=>{const{taskQueueService:i}=await Xe(async()=>{const{taskQueueService:c}=await import("./ai-chat-B-XdoWBQ.js").then(h=>h.sN);return{taskQueueService:c}},__vite__mapDeps([0]),import.meta.url),{WorkZoneTransforms:l}=await Xe(async()=>{const{WorkZoneTransforms:c}=await Promise.resolve().then(()=>Po);return{WorkZoneTransforms:c}},void 0,import.meta.url),{TaskStatus:d}=await Xe(async()=>{const{TaskStatus:c}=await import("./ai-chat-B-XdoWBQ.js").then(h=>h.sF);return{TaskStatus:c}},__vite__mapDeps([0]),import.meta.url);s=i.observeTaskUpdates().subscribe(c=>{if(c.type!=="taskUpdated"&&c.type!=="taskCompleted"&&c.type!=="taskFailed")return;const h=c.task;if(!h)return;const u=l.getAllWorkZones(t);for(const p of u){const y={...p.workflow,steps:[...p.workflow.steps]};let f=!1;const g=y.steps.map(w=>{var b;const x=w.result;if((x==null?void 0:x.taskId)!==h.id)return w;let v=w.status,_=w.error,T=w.result;switch(h.status){case d.COMPLETED:v="completed",T={taskId:h.id,result:h.result};break;case d.FAILED:v="failed",_=((b=h.error)==null?void 0:b.message)||"任务失败";break;case d.PROCESSING:v="running";break;case d.PENDING:v="pending";break;case d.CANCELLED:v="skipped";break}return v!==w.status||_!==w.error?(f=!0,{...w,status:v,error:_,result:T}):w});f&&l.updateWorkflow(t,p.id,{steps:g})}})})().catch(i=>{console.error("[DrawnixDeferredRuntime] Failed to sync task queue:",i)}),()=>{s==null||s.unsubscribe()}},[t,n]),mP(),PP({enabled:!0,insertPrompt:!1,groupSimilarTasks:!0}),HP({board:t,enabled:n}),GP(),null}const a1=Object.freeze(Object.defineProperty({__proto__:null,DrawnixDeferredRuntime:Mh,default:Mh},Symbol.toStringTag,{value:"Module"})),KP={selectedVoice:"",rate:1,pitch:1,volume:1,voicesByLanguage:{}},Dh={zh:"你好,这是一段测试语音。",en:"Hello, this is a test speech.",ja:"こんにちは、これはテスト音声です。",ko:"안녕하세요. 이것은 테스트 음성입니다.",fr:"Bonjour, ceci est un test vocal.",de:"Hallo, dies ist eine Sprachprobe.",es:"Hola, esta es una prueba de voz.",ru:"Привет, это тестовый голос."};function Nh(t){return{...KP,...t||{},voicesByLanguage:(t==null?void 0:t.voicesByLanguage)||{}}}function Rh(t){let e=0;t.localService&&(e+=20),t.default&&(e+=8);const n=t.name.toLowerCase();return(n.includes("tingting")||n.includes("婷婷")||n.includes("samantha")||n.includes("alex")||n.includes("victoria")||n.includes("daniel")||n.includes("kyoko")||n.includes("otoya"))&&(e+=24),(n.includes("whisper")||n.includes("zarvox")||n.includes("bells")||n.includes("boing")||n.includes("bubbles"))&&(e-=30),e}function zl(t){return t.trim().toLowerCase().split("-")[0]||"zh"}function Lh(t){return{all:"全局默认",zh:"中文",en:"英语",ja:"日语",ko:"韩语",fr:"法语",de:"德语",es:"西语",ru:"俄语",it:"意语",pt:"葡语",ar:"阿拉伯语"}[t]||t.toUpperCase()}function qP(t){const e=zl(t);return Dh[e]||Dh.en}function YP(t,e){const n=["zh","en"],r=n.indexOf(t),s=n.indexOf(e);return r!==-1||s!==-1?r===-1?1:s===-1?-1:r-s:t.localeCompare(e)}function zo(t,e,n){if(n<=e)return"0%";const r=(t-e)/(n-e)*100;return`${Math.min(100,Math.max(0,r))}%`}const i1=()=>{var _;const[t,e]=m.useState(()=>Nh(ws.get())),[n,r]=m.useState([]),[s,a]=m.useState(""),[i,l]=m.useState("all"),[d,c]=m.useState(!1),h=m.useCallback(()=>{if(typeof window>"u"||!("speechSynthesis"in window)){r([]);return}const T=window.speechSynthesis.getVoices(),b=T.map(I=>({uri:I.voiceURI,name:I.name,lang:I.lang,localService:I.localService,default:I.default})).sort((I,A)=>{const k=Rh(T.find(U=>U.voiceURI===A.uri)||T[0])-Rh(T.find(U=>U.voiceURI===I.uri)||T[0]);return k!==0?k:I.name.localeCompare(A.name)});r(b)},[]);m.useEffect(()=>{if(typeof window>"u"||!("speechSynthesis"in window))return;let T=0,b=null;const I=6,A=()=>{h(),window.speechSynthesis.getVoices().length===0&&T<I&&(T+=1,b=window.setTimeout(A,120))};A(),window.speechSynthesis.onvoiceschanged=A;const k=U=>{e(Nh(U))};return ws.addListener(k),()=>{ws.removeListener(k),window.speechSynthesis.onvoiceschanged=null,b!==null&&window.clearTimeout(b),window.speechSynthesis.cancel()}},[h]);const u=m.useMemo(()=>{const T=new Set;return n.forEach(b=>{T.add(zl(b.lang))}),["all",...Array.from(T).sort(YP)]},[n]),p=m.useMemo(()=>{const T=s.trim().toLowerCase();return n.filter(b=>{const I=i==="all"||zl(b.lang)===i,A=!T||b.name.toLowerCase().includes(T)||b.lang.toLowerCase().includes(T);return I&&A})},[s,i,n]),y=i==="all"?t.selectedVoice||"":((_=t.voicesByLanguage)==null?void 0:_[i])||"",f=m.useCallback(async T=>{e(T),await ws.update(T)},[]),g=m.useCallback(async T=>{if(i==="all"){await f({...t,selectedVoice:T});return}await f({...t,voicesByLanguage:{...t.voicesByLanguage||{},[i]:T}})},[f,i,t]),w=m.useCallback(async(T,b)=>{await f({...t,[T]:b})},[f,t]),x=m.useCallback(async()=>{if(i==="all"){await f({...t,selectedVoice:""});return}const T={...t.voicesByLanguage||{}};delete T[i],await f({...t,voicesByLanguage:T})},[f,i,t]),v=m.useCallback((T,b)=>{if(typeof window>"u"||!("speechSynthesis"in window))return;if(d){window.speechSynthesis.cancel(),c(!1);return}const I=window.speechSynthesis.getVoices().find(k=>k.voiceURI===T);if(!I)return;const A=new SpeechSynthesisUtterance(qP(b));A.voice=I,A.lang=I.lang,A.rate=t.rate,A.pitch=t.pitch,A.volume=t.volume,A.onstart=()=>c(!0),A.onend=()=>c(!1),A.onerror=()=>c(!1),window.speechSynthesis.cancel(),window.speechSynthesis.speak(A)},[d,t.pitch,t.rate,t.volume]);return typeof window>"u"||!("speechSynthesis"in window)?o.jsx("div",{className:"project-drawer-tts project-drawer-tts--empty",children:"当前环境不支持浏览器语音播报。"}):o.jsxs("div",{className:"project-drawer-tts",children:[o.jsxs("div",{className:"project-drawer-tts__section",children:[o.jsxs("div",{className:"project-drawer-tts__section-title",children:[o.jsx(Nv,{size:16}),o.jsx("span",{children:"播报参数"})]}),o.jsx("div",{className:"project-drawer-tts__hint",children:"使用浏览器自带能力,免费。"}),o.jsxs("label",{className:"project-drawer-tts__slider",children:[o.jsx("span",{className:"project-drawer-tts__slider-label",children:"语速"}),o.jsx("input",{className:"project-drawer-tts__range",style:{"--slider-progress":zo(t.rate,.5,10)},type:"range",min:"0.5",max:"10",step:"0.1",value:t.rate,onChange:T=>void w("rate",Number(T.target.value))}),o.jsxs("strong",{className:"project-drawer-tts__slider-value",children:[t.rate.toFixed(1),"x"]})]}),o.jsxs("label",{className:"project-drawer-tts__slider",children:[o.jsx("span",{className:"project-drawer-tts__slider-label",children:"音调"}),o.jsx("input",{className:"project-drawer-tts__range",style:{"--slider-progress":zo(t.pitch,.5,2)},type:"range",min:"0.5",max:"2",step:"0.1",value:t.pitch,onChange:T=>void w("pitch",Number(T.target.value))}),o.jsx("strong",{className:"project-drawer-tts__slider-value",children:t.pitch.toFixed(1)})]}),o.jsxs("label",{className:"project-drawer-tts__slider",children:[o.jsx("span",{className:"project-drawer-tts__slider-label",children:"音量"}),o.jsx("input",{className:"project-drawer-tts__range",style:{"--slider-progress":zo(t.volume,0,1)},type:"range",min:"0",max:"1",step:"0.05",value:t.volume,onChange:T=>void w("volume",Number(T.target.value))}),o.jsxs("strong",{className:"project-drawer-tts__slider-value",children:[Math.round(t.volume*100),"%"]})]})]}),o.jsxs("div",{className:"project-drawer-tts__section",children:[o.jsxs("div",{className:"project-drawer-tts__toolbar",children:[o.jsxs("div",{className:"project-drawer-tts__filters",children:[o.jsx("div",{className:"project-drawer-tts__chips",children:u.map(T=>o.jsx("button",{type:"button",className:`project-drawer-tts__chip${i===T?" project-drawer-tts__chip--active":""}`,onClick:()=>l(T),children:Lh(T)},T))}),o.jsx($t,{value:s,size:"small",placeholder:"搜索音色或语言",onChange:a})]}),o.jsxs("div",{className:"project-drawer-tts__toolbar-actions",children:[o.jsx(Me,{size:"small",variant:"outline",icon:o.jsx(ra,{}),onClick:h,children:"刷新"}),o.jsx(Me,{size:"small",variant:"text",onClick:()=>void x(),children:i==="all"?"清空默认音色":"改回全局默认"})]})]}),o.jsx("div",{className:"project-drawer-tts__hint",children:i==="all"?"全局默认会作为所有 TTS 入口的首选音色。":`${Lh(i)} 可单独覆盖音色,未设置时回退到全局默认。`}),p.length===0?o.jsx("div",{className:"project-drawer-tts__empty",children:"未找到可用音色,请确认系统已安装语音包。"}):o.jsx("div",{className:"project-drawer-tts__voice-list",children:p.map(T=>{const b=y===T.uri;return o.jsxs("div",{className:`project-drawer-tts__voice${b?" project-drawer-tts__voice--active":""}`,role:"button",tabIndex:0,onClick:()=>void g(T.uri),onKeyDown:I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),g(T.uri))},children:[o.jsxs("div",{className:"project-drawer-tts__voice-main",children:[o.jsxs("div",{className:"project-drawer-tts__voice-title",children:[o.jsx("span",{children:T.name}),b&&o.jsx(Rv,{size:"12px"})]}),o.jsxs("div",{className:"project-drawer-tts__voice-meta",children:[o.jsx("span",{children:T.lang}),T.localService&&o.jsx("span",{children:"本地"}),T.default&&o.jsx("span",{children:"系统默认"})]})]}),o.jsx(Me,{size:"small",variant:"text",theme:"default",icon:d?o.jsx(Lv,{size:14}):o.jsx(ic,{size:14}),onClick:I=>{I.stopPropagation(),v(T.uri,T.lang)},children:"试听"})]},T.uri)})})]})]})},Fh=60,Bh="slideshow-active";function Sa(t){t?document.documentElement.classList.add(Bh):document.documentElement.classList.remove(Bh)}function ZP(t){const e=[];for(const n of t.children)at(n)&&e.push(n);return e}function XP(){var t;return!!((t=window.matchMedia)!=null&&t.call(window,"(prefers-reduced-motion: reduce)").matches)}function JP(t){var e;return Na((e=t==null?void 0:t.pptMeta)==null?void 0:e.transition)}function QP(t,e){const n=Fe.getRectangleByPoints(e.points),r=kt.getBoardContainer(t),s=r.clientWidth,a=r.clientHeight,i=(s-Fh*2)/n.width,l=(a-Fh*2)/n.height,d=Math.min(i,l,3),c=n.x+n.width/2,h=n.y+n.height/2,u=[c-s/2/d,h-a/2/d];dt.updateViewport(t,u,d);const p=r.getBoundingClientRect(),y=p.left+(n.x-u[0])*d,f=p.top+(n.y-u[1])*d,g=n.width*d,w=n.height*d;return{left:y,top:f,width:g,height:w}}function eE(t){const e=window.innerWidth,n=window.innerHeight,r={top:0,left:0,width:e,height:Math.max(0,t.top)},s={top:t.top+t.height,left:0,width:e,height:Math.max(0,n-t.top-t.height)},a={top:t.top,left:0,width:Math.max(0,t.left),height:t.height},i={top:t.top,left:t.left+t.width,width:Math.max(0,e-t.left-t.width),height:t.height};return[r,s,a,i]}const tE=["#000000","#e91e63","#f39c12","#4caf50","#2196f3","#9c27b0","#ffffff"],nE=[{style:bs.solid,icon:o.jsx(Zv,{})},{style:bs.dashed,icon:o.jsx(Xv,{})},{style:bs.dotted,icon:o.jsx(Jv,{})},{style:bs.double,icon:o.jsx(Qv,{})}],rE=[1,2,4,8],Xp=({visible:t,board:e,onClose:n,initialFrameId:r})=>{const[s,a]=m.useState(0),[i,l]=m.useState(null),[d,c]=m.useState(!0),[h,u]=m.useState("select"),p=Fv(),y=m.useRef(),f=m.useRef(null),g=m.useRef(!1),w=m.useRef(null),x=m.useRef(null),v=m.useRef([]),_=m.useRef(0),T=m.useRef(0),b=m.useRef(),[I,A]=m.useState(null),k=t?Bv(e):null,[U,D]=m.useState((k==null?void 0:k.strokeColor)??"#000000"),[X,L]=m.useState((k==null?void 0:k.strokeStyle)??bs.solid),[O,G]=m.useState((k==null?void 0:k.strokeWidth)??2),C=m.useCallback(ne=>{D(ne),zv(e,ne)},[e]),P=m.useCallback(ne=>{L(ne),$v(e,ne)},[e]),j=m.useCallback(ne=>{G(ne),Uv(e,ne)},[e]),N=m.useCallback(()=>{c(!0),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{c(!1)},3e3)},[]),B=m.useCallback(ne=>{if(u(ne),N(),ne==="select")dt.updatePointerType(e,Or.selection),p(Or.selection);else{const q={pen:Pn.feltTipPen,eraser:Pn.eraser,laser:Pn.laserPointer}[ne];fn(e,vn.drawing),dt.updatePointerType(e,q),p(q)}},[e,N,p]),K=m.useCallback((ne,M={})=>{const q=v.current;if(!e||ne<0||ne>=q.length)return;const R=q[ne],J=QP(e,R),Ce=JP(R),re=M.animate!==!1&&_.current!==ne&&Ce.type!=="none"&&!XP();if(b.current&&clearTimeout(b.current),re&&Ce.type!=="none"){const ze=T.current+1;T.current=ze;const V=Ce.durationMs||700,z=Ce.type;A({key:ze,rect:J,type:z,durationMs:V}),b.current=setTimeout(()=>{A(F=>(F==null?void 0:F.key)===ze?null:F)},V+120)}else A(null);l(J),a(ne),_.current=ne,N()},[e,N]);m.useEffect(()=>{if(!t)return;const ne=ZP(e);if(ne.length===0){n();return}v.current=ne;const M=e.viewport;w.current={origination:M!=null&&M.origination?[M.origination[0],M.origination[1]]:null,zoom:(M==null?void 0:M.zoom)??1},x.current=e.pointer,Sa(!0);let q=0;if(r){const J=ne.findIndex(Ce=>Ce.id===r);J>=0&&(q=J)}K(q,{animate:!1});const R=Hv(document.documentElement);return R==null||R.then(()=>{setTimeout(()=>K(q,{animate:!1}),300)}).catch(()=>{}),()=>{Sa(!1),y.current&&clearTimeout(y.current),b.current&&clearTimeout(b.current)}},[t]);const fe=m.useCallback(()=>{var M;Sa(!1);const ne=w.current;if(ne&&e){const q=ne.origination??[0,0];dt.updateViewport(e,q,ne.zoom)}x.current!==null&&(dt.updatePointerType(e,x.current),p(x.current)),(M=Gv())==null||M.catch(()=>{}),l(null),A(null),u("select"),n()},[e,n,p]),ae=m.useCallback(()=>{const ne=v.current;if(s<ne.length-1){K(s+1);return}fe()},[s,K,fe]);m.useEffect(()=>{if(!t)return;const ne=()=>{if(!document.fullscreenElement&&t){Sa(!1);const M=w.current;if(M&&e){const q=M.origination??[0,0];dt.updateViewport(e,q,M.zoom)}x.current!==null&&(dt.updatePointerType(e,x.current),p(x.current)),l(null),A(null),u("select"),n()}};return document.addEventListener("fullscreenchange",ne),()=>{document.removeEventListener("fullscreenchange",ne)}},[t,e,n,p]),m.useEffect(()=>{if(!t)return;const ne=()=>{K(s)};return window.addEventListener("resize",ne),()=>window.removeEventListener("resize",ne)},[t,s,K]),m.useEffect(()=>{if(!t)return;const ne=v.current;if(ne.length===0)return;const M=q=>{switch(N(),q.key){case"ArrowRight":case" ":case"Enter":case"PageDown":case"ArrowDown":{q.preventDefault(),a(R=>{const J=Math.min(R+1,ne.length-1);return J!==R&&K(J),J});break}case"ArrowLeft":case"Backspace":case"PageUp":case"ArrowUp":{q.preventDefault(),a(R=>{const J=Math.max(R-1,0);return J!==R&&K(J),J});break}case"Escape":{q.preventDefault(),fe();break}case"Home":{q.preventDefault(),K(0);break}case"End":{q.preventDefault(),K(ne.length-1);break}}};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[t,K,fe,N]);const te=m.useCallback(ne=>{if(h!=="select")return;const M=ne.target;M.closest(".frame-slideshow__controls")||M.closest(".frame-slideshow__nav")||M.closest("[data-slideshow-media-control]")||ae()},[h,ae]);if(m.useEffect(()=>{if(!t||!i||h!=="select"){f.current=null,g.current=!1;return}const ne=z=>z.clientX>=i.left&&z.clientX<=i.left+i.width&&z.clientY>=i.top&&z.clientY<=i.top+i.height,M=z=>z instanceof Element&&!!z.closest(".frame-slideshow__controls, .frame-slideshow__nav"),q=z=>z instanceof Element&&!!z.closest("[data-slideshow-media-control], video, audio"),R=z=>z instanceof Element&&!!z.closest("[data-slideshow-legacy-audio]"),J=z=>{const F=z.target;return ne(z)&&!M(F)&&!q(F)&&!R(F)},Ce=z=>{z.preventDefault(),z.stopPropagation()},re=z=>{if(z.button===0&&ne(z)&&R(z.target)){f.current=null,z.stopPropagation();return}if(z.button!==0||!J(z)){f.current=null;return}f.current={x:z.clientX,y:z.clientY},Ce(z)},ze=z=>{if(z.button===0&&ne(z)&&R(z.target)){f.current=null,z.stopPropagation();return}const F=f.current;!F||(f.current=null,!J(z))||(Ce(z),g.current=!0,Math.hypot(z.clientX-F.x,z.clientY-F.y)>5)||ae()},V=z=>{if(g.current){g.current=!1,Ce(z);return}J(z)&&Ce(z)};return document.addEventListener("pointerdown",re,!0),document.addEventListener("pointerup",ze,!0),document.addEventListener("click",V,!0),()=>{document.removeEventListener("pointerdown",re,!0),document.removeEventListener("pointerup",ze,!0),document.removeEventListener("click",V,!0)}},[h,i,ae,t]),m.useEffect(()=>{if(!t)return;const ne=()=>N();return window.addEventListener("mousemove",ne),()=>window.removeEventListener("mousemove",ne)},[t,N]),!t||!i)return null;const Se=v.current,Ee=Se[s],Te=eE(i),ke=I?{left:I.rect.left,top:I.rect.top,width:I.rect.width,height:I.rect.height,animationDuration:`${I.durationMs}ms`}:void 0;return Wv.createPortal(o.jsxs("div",{className:"frame-slideshow",style:{zIndex:Kf.SLIDESHOW},onMouseMove:N,onClick:te,children:[o.jsx("div",{className:"frame-slideshow__mask",children:Te.map((ne,M)=>o.jsx("div",{className:"frame-slideshow__mask-block",style:ne},M))}),I?o.jsx("div",{className:`frame-slideshow__transition frame-slideshow__transition--${I.type}`,style:ke},I.key):null,o.jsxs("div",{className:"frame-slideshow__controls",style:{opacity:d?1:0},children:[o.jsxs("div",{className:"frame-slideshow__controls-left",children:[Ee&&o.jsx("div",{className:"frame-slideshow__title",children:Yt(Ee,s+1)}),o.jsxs("div",{className:"frame-slideshow__esc-hint",children:["按 ",o.jsx("kbd",{children:"ESC"})," 退出"]})]}),Se.length>0&&o.jsxs("div",{className:"frame-slideshow__indicator",children:[o.jsx("span",{className:"frame-slideshow__indicator-current",children:s+1}),o.jsx("span",{className:"frame-slideshow__indicator-sep",children:"/"}),o.jsx("span",{className:"frame-slideshow__indicator-total",children:Se.length})]}),o.jsxs("div",{className:"frame-slideshow__controls-right",children:[h==="pen"&&o.jsxs("div",{className:"frame-slideshow__settings-panel",children:[o.jsx("div",{className:"frame-slideshow__pen-colors",children:tE.map(ne=>o.jsx("button",{className:`frame-slideshow__pen-color ${U===ne?"frame-slideshow__pen-color--active":""}`,style:{backgroundColor:ne},onClick:()=>C(ne)},ne))}),o.jsx("div",{className:"frame-slideshow__pen-divider"}),o.jsx("div",{className:"frame-slideshow__pen-styles",children:nE.map(({style:ne,icon:M})=>o.jsx("button",{className:`frame-slideshow__pen-style ${X===ne?"frame-slideshow__pen-style--active":""}`,onClick:()=>P(ne),children:M},ne))}),o.jsx("div",{className:"frame-slideshow__pen-divider"}),o.jsx("div",{className:"frame-slideshow__pen-widths",children:rE.map(ne=>o.jsx("button",{className:`frame-slideshow__pen-width ${O===ne?"frame-slideshow__pen-width--active":""}`,onClick:()=>j(ne),children:o.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",children:o.jsx("line",{x1:"3",y1:"10",x2:"17",y2:"10",stroke:"currentColor",strokeWidth:ne,strokeLinecap:"round"})})},ne))})]}),o.jsx(Le,{content:"选择工具",showArrow:!1,children:o.jsx("button",{className:`frame-slideshow__tool-btn ${h==="select"?"frame-slideshow__tool-btn--active":""}`,onClick:()=>B("select"),children:o.jsx(Vv,{size:20})})}),o.jsx(Le,{content:"画笔",showArrow:!1,children:o.jsx("button",{className:`frame-slideshow__tool-btn ${h==="pen"?"frame-slideshow__tool-btn--active":""}`,onClick:()=>B("pen"),children:o.jsx(Kv,{size:20})})}),o.jsx(Le,{content:"橡皮擦",showArrow:!1,children:o.jsx("button",{className:`frame-slideshow__tool-btn ${h==="eraser"?"frame-slideshow__tool-btn--active":""}`,onClick:()=>B("eraser"),children:o.jsx(qv,{size:20})})}),o.jsx(Le,{content:"激光笔",showArrow:!1,children:o.jsx("button",{className:`frame-slideshow__tool-btn ${h==="laser"?"frame-slideshow__tool-btn--active":""}`,onClick:()=>B("laser"),children:o.jsx(Yv,{size:20})})})]})]}),s>0&&o.jsx(Le,{content:"上一页",showArrow:!1,children:o.jsx("button",{className:"frame-slideshow__nav frame-slideshow__nav--prev",style:{opacity:d?1:0},onClick:()=>K(s-1),children:o.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",children:o.jsx("path",{d:"M15 18l-6-6 6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})}),s<Se.length-1&&o.jsx(Le,{content:"下一页",showArrow:!1,children:o.jsx("button",{className:"frame-slideshow__nav frame-slideshow__nav--next",style:{opacity:d?1:0},onClick:()=>K(s+1),children:o.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",children:o.jsx("path",{d:"M9 18l6-6-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})})]}),document.body)},o1=Object.freeze(Object.defineProperty({__proto__:null,FrameSlideshow:Xp},Symbol.toStringTag,{value:"Module"}));class sE{async exportToZip(e){const{onProgress:n}=e||{},{default:r}=await Xe(async()=>{const{default:p}=await import("./office-data-DMEex_0S.js").then(y=>y.j);return{default:p}},[],import.meta.url),s=new r;n==null||n(5,"正在加载数据...");const[a,i]=await Promise.all([Nt.loadAllFolders(),Nt.loadAllBoards()]);n==null||n(15,"正在构建目录结构...");const l=this.buildFolderPathMap(a),d=this.collectAssetIds(i);n==null||n(20,"正在加载素材...");const c=await this.loadAssets(d);n==null||n(30,"正在创建文件夹...");for(const p of a){const y=l.get(p.id)||p.name;s.folder(y)}n==null||n(40,"正在导出画板...");const h=i.length;for(let p=0;p<i.length;p++){const y=i[p],f=y.folderId?l.get(y.folderId):null,g=this.sanitizeFileName(y.name),w=f?`${f}/${g}.drawnix`:`${g}.drawnix`,x={type:ql.drawnix,version:Yl.drawnix,source:"web",elements:y.elements||[],viewport:y.viewport||{zoom:1},theme:y.theme,boardMeta:{id:y.id,name:y.name,order:y.order,createdAt:y.createdAt,updatedAt:y.updatedAt}};if(s.file(w,JSON.stringify(x,null,2)),h>0){const v=40+Math.round((p+1)/h*20);n==null||n(v,`正在导出画板 (${p+1}/${h})...`)}}if(n==null||n(60,"正在导出素材..."),c.length>0){const p=s.folder("_assets");if(p){const y=c.length;for(let f=0;f<c.length;f++){const g=c[f],{blobData:w,...x}=g;p.file(`${g.id}.meta.json`,JSON.stringify(x,null,2)),w&&p.file(`${g.id}.blob`,w);const v=60+Math.round((f+1)/y*20);n==null||n(v,`正在导出素材 (${f+1}/${y})...`)}}}n==null||n(85,"正在压缩文件...");const u=await s.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:6}},p=>{const y=85+Math.round(p.percent*.14),f=p.currentFile||"",g=f.length>30?"..."+f.slice(-27):f;n==null||n(y,`正在压缩: ${g||"..."}`)});return n==null||n(100,"导出完成"),u}buildFolderPathMap(e){const n=new Map,r=new Map;for(const a of e)r.set(a.id,a);const s=a=>{if(n.has(a))return n.get(a);const i=r.get(a);if(!i)return"";const l=this.sanitizeFileName(i.name);if(i.parentId){const d=s(i.parentId),c=d?`${d}/${l}`:l;return n.set(a,c),c}return n.set(a,l),l};for(const a of e)s(a.id);return n}sanitizeFileName(e){return e.replace(/[<>:"/\\|?*]/g,"_").replace(/\s+/g," ").trim()||"unnamed"}async importFromZip(e,n={}){var c;const{merge:r=!1,onProgress:s}=n,a=[];let i=0,l=0,d=0;try{s==null||s(5,"正在读取文件...");const{default:h}=await Xe(async()=>{const{default:x}=await import("./office-data-DMEex_0S.js").then(v=>v.j);return{default:x}},[],import.meta.url),u=await h.loadAsync(e);s==null||s(10,"正在验证文件格式...");const p=Object.keys(u.files).filter(x=>x.endsWith(".drawnix")&&!x.startsWith("_"));if(p.length===0)throw new Error("无效的导出文件:未找到画板文件");r||(s==null||s(15,"正在清理现有数据..."),await Nt.clearAll(),await rl.clearAll(),await Nt.saveState({currentBoardId:null,expandedFolderIds:[],sidebarWidth:ai.SIDEBAR_WIDTH,sidebarCollapsed:!1,migrationCompleted:!0})),s==null||s(20,"正在导入素材...");const y=Object.keys(u.files).filter(x=>x.startsWith("_assets/")&&x.endsWith(".meta.json"));for(let x=0;x<y.length;x++){const v=y[x],_=v.replace("_assets/","").replace(".meta.json",""),T=v.replace(".meta.json",".blob");try{const b=u.file(v),I=u.file(T);if(b&&I){const A=await b.async("string"),k=JSON.parse(A),U=await I.async("blob"),D={...k,blobData:U};await this.saveStoredAsset(D),d++}}catch(b){const I=b instanceof Error?b.message:String(b);a.push(`素材 ${_} 导入失败: ${I}`)}if(y.length>0){const b=20+(x+1)/y.length*30;s==null||s(b,`正在导入素材 (${x+1}/${y.length})...`)}}s==null||s(55,"正在分析目录结构...");const f=new Set,g=new Map;for(const x of p){const v=x.split("/");if(v.length>1){let _="";for(let T=0;T<v.length-1;T++)_=_?`${_}/${v[T]}`:v[T],f.add(_)}}const w=Array.from(f).sort((x,v)=>{const _=x.split("/").length,T=v.split("/").length;return _-T||x.localeCompare(v)});s==null||s(60,"正在导入文件夹...");for(let x=0;x<w.length;x++){const v=w[x],_=v.split("/"),T=_[_.length-1],b=_.length>1?_.slice(0,-1).join("/"):null,I=b&&g.get(b)||null;try{const A=this.generateId();g.set(v,A);const k={id:A,name:T,parentId:I,order:x,isExpanded:!0,createdAt:Date.now(),updatedAt:Date.now()};await Nt.saveFolder(k),i++}catch(A){const k=A instanceof Error?A.message:String(A);a.push(`文件夹 "${T}" 导入失败: ${k}`)}}s==null||s(70,"正在导入画板...");for(let x=0;x<p.length;x++){const v=p[x];try{const T=u.file(v);if(T){const b=await T.async("string"),I=JSON.parse(b),A=v.split("/").pop()||"unnamed.drawnix",k=((c=I.boardMeta)==null?void 0:c.name)||A.replace(".drawnix",""),U=v.split("/"),D=U.length>1?U.slice(0,-1).join("/"):null,X=D&&g.get(D)||null,L=I.boardMeta,O={id:(L==null?void 0:L.id)||this.generateId(),name:k,folderId:X,order:(L==null?void 0:L.order)??x,elements:I.elements||[],viewport:I.viewport,theme:I.theme,createdAt:(L==null?void 0:L.createdAt)||Date.now(),updatedAt:(L==null?void 0:L.updatedAt)||Date.now()};await Nt.saveBoard(O),l++}}catch(T){const b=v.split("/").pop()||v,I=T instanceof Error?T.message:String(T);a.push(`画板 "${b}" 导入失败: ${I}`)}const _=70+(x+1)/p.length*25;s==null||s(_,`正在导入画板 (${x+1}/${p.length})...`)}return s==null||s(100,"导入完成"),{success:a.length===0,folders:i,boards:l,assets:d,errors:a}}catch(h){const u=h instanceof Error?h.message:String(h);return{success:!1,folders:i,boards:l,assets:d,errors:[...a,u]}}}generateId(){return`${Date.now().toString(36)}-${Math.random().toString(36).substring(2,11)}`}collectAssetIds(e){const n=new Set;for(const r of e)r.elements&&this.findAssetIdsInElements(r.elements,n);return n}findAssetIdsInElements(e,n){for(const r of e)r.assetId&&n.add(r.assetId),r.imageAssetId&&n.add(r.imageAssetId),r.videoAssetId&&n.add(r.videoAssetId),r.children&&Array.isArray(r.children)&&this.findAssetIdsInElements(r.children,n)}async loadAssets(e){const n=[],r=Xt.createInstance({name:Kn.STORAGE_NAME,storeName:Kn.STORE_NAME});for(const s of e)try{const a=await r.getItem(s);a&&n.push(a)}catch(a){console.warn(`[WorkspaceExport] Failed to load asset ${s}:`,a)}return n}async saveStoredAsset(e){await Xt.createInstance({name:Kn.STORAGE_NAME,storeName:Kn.STORE_NAME}).setItem(e.id,e)}downloadZip(e,n){const r=new Date,s=r.toISOString().split("T")[0],a=r.toTimeString().split(" ")[0].replace(/:/g,""),i=`aitu_workspace_${s}_${a}.zip`,l=URL.createObjectURL(e),d=document.createElement("a");d.href=l,d.download=n||i,document.body.appendChild(d),d.click(),document.body.removeChild(d),URL.revokeObjectURL(l)}}const $o=new sE,zh=60;function aE(t,e,n){var a,i;const r=[];for(const l of t.children)at(l)&&r.push(Fe.getRectangleByPoints(l.points));if(r.length===0){const l=kt.getBoardContainer(t),d=l.clientWidth,c=l.clientHeight,h=((a=t.viewport)==null?void 0:a.zoom)??1,u=(i=t.viewport)==null?void 0:i.origination,p=u?u[0]:0,y=u?u[1]:0,f=p+d/2/h,g=y+c/2/h;return[f-e/2,g-n/2]}if(e>=n){let l=-1/0,d=0;for(const c of r){const h=c.x+c.width;h>l&&(l=h,d=c.y)}return[l+zh,d]}else{let l=-1/0,d=0;for(const c of r){const h=c.y+c.height;h>l&&(l=h,d=c.x)}return[d,l+zh]}}const iE=({visible:t,board:e,onClose:n,onFrameAdded:r})=>{const[s,a]=m.useState(null),[i,l]=m.useState(1920),[d,c]=m.useState(1080),h=m.useCallback((g,w)=>{if(!e||g<=0||w<=0)return;const x=aE(e,g,w),v=[x,[x[0]+g,x[1]+w]],_=Gn.insertFrame(e,v);ns(e);const T=e.children.find(C=>C.id===_.id);T&&ta(e,T);const b=kt.getBoardContainer(e),I=b.clientWidth,A=b.clientHeight,k=80,U=I/(g+k*2),D=A/(w+k*2),X=Math.min(U,D,2),L=x[0]+g/2,O=x[1]+w/2,G=[L-I/2/X,O-A/2/X];dt.updateViewport(e,G,X),r==null||r(_),n()},[e,r,n]),u=m.useCallback(g=>{h(g.width,g.height)},[h]),p=m.useCallback(()=>{h(i,d)},[h,i,d]),y=m.useCallback(()=>{a(null)},[]),f=m.useMemo(()=>s?`${s.width}x${s.height}`:"",[s]);return o.jsx(Zn,{header:"添加 PPT 页面",visible:t,onClose:n,footer:null,width:480,destroyOnClose:!0,children:o.jsxs("div",{className:"add-frame-dialog",children:[o.jsx("div",{className:"add-frame-dialog__presets",children:eP.map(g=>o.jsxs("div",{className:"add-frame-dialog__category",children:[o.jsx("div",{className:"add-frame-dialog__category-label",children:g.category}),o.jsx("div",{className:"add-frame-dialog__category-items",children:g.items.map(w=>{const x=`${w.width}x${w.height}`,v=f===x;return o.jsxs("button",{className:`add-frame-dialog__preset-item${v?" add-frame-dialog__preset-item--active":""}`,onClick:()=>u(w),children:[o.jsx("span",{className:"add-frame-dialog__preset-label",children:w.label}),o.jsxs("span",{className:"add-frame-dialog__preset-size",children:[w.width," × ",w.height]})]},x)})})]},g.category))}),o.jsxs("div",{className:"add-frame-dialog__footer",children:[o.jsxs("div",{className:"add-frame-dialog__custom-section",children:[o.jsx("span",{className:"add-frame-dialog__custom-label",children:"自定义"}),o.jsxs("div",{className:"add-frame-dialog__input-group",children:[o.jsx("span",{className:"add-frame-dialog__input-label",children:"W"}),o.jsx(ud,{value:i,onChange:g=>{l(g),y()},onEnter:p,min:10,max:1e4,theme:"normal",size:"small",style:{width:68}})]}),o.jsx("span",{className:"add-frame-dialog__input-sep",children:"×"}),o.jsxs("div",{className:"add-frame-dialog__input-group",children:[o.jsx("span",{className:"add-frame-dialog__input-label",children:"H"}),o.jsx(ud,{value:d,onChange:g=>{c(g),y()},onEnter:p,min:10,max:1e4,theme:"normal",size:"small",style:{width:68}})]}),o.jsx(Me,{theme:"primary",variant:"text",shape:"square",size:"small",icon:o.jsx(Dn,{}),onClick:p,title:"添加自定义尺寸 PPT 页面"})]}),o.jsxs("div",{className:"add-frame-dialog__hint",children:[o.jsx("kbd",{children:"F"})," 直接绘制 PPT 页面"]})]})]})})},mr=10,xi=5.625,oE=50*1024*1024,$l="application/vnd.openxmlformats-officedocument.presentationml.presentation",$h=1280,Uo=5e3,lE=mr*72,mn="PingFang SC",cE=14;function Xa(t,e){const n=Math.max(e,1),r=t*(lE/n);return Math.max(.1,r)}function cr(t){if(!t)return;const e=t.trim();if(e==="transparent"||e==="none"||e==="")return;if(e.startsWith("#")){const r=e.slice(1);return r.length===3?r.split("").map(s=>s+s).join("").toUpperCase():r.substring(0,6).toUpperCase()}const n=e.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(n){const[,r,s,a]=n;return[r,s,a].map(i=>parseInt(i).toString(16).padStart(2,"0")).join("").toUpperCase()}}function dE(t){return t.toLowerCase().endsWith(".pptx")?t:`${t}.pptx`}function uE(t){var e;return ow((e=t.pptMeta)==null?void 0:e.transition)}function hE(t){return t instanceof Blob?t:new Blob([t],{type:$l})}function fE(t,e){const n=document.createElement("a");n.setAttribute("style","display:none;"),n.dataset.interception="off",document.body.appendChild(n);const r=window.URL.createObjectURL(t.type===$l?t:new Blob([t],{type:$l}));n.href=r,n.download=e,n.click(),setTimeout(()=>{window.URL.revokeObjectURL(r),document.body.removeChild(n)},100)}class $s extends Error{constructor(e,n){super(`媒体文件超过导出上限 (${Gl(e)} / ${Gl(n)})`),this.size=e,this.limit=n,this.name="ExportMediaTooLargeError"}}function mE(t){return t&&typeof t=="object"&&typeof t.text=="string"}function Vr(t){if(mE(t))return[t];const e=[],n=t==null?void 0:t.children;if(Array.isArray(n))for(const r of n)e.push(...Vr(r));return e}function Jp(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){const e=Number.parseFloat(t);if(Number.isFinite(e))return e}}function pE(t,e,n,r){const s={},a=Jp(t["font-size"]),i=a?Math.max(6,Math.round(a*n)):r;s.fontSize=i;const l=t["font-weight"],d=l?Number(l):NaN;(l==="bold"||t.bold||!Number.isNaN(d)&&d>=500)&&(s.bold=!0);const c=cr(t.color);return c&&(s.color=c),t.italic&&(s.italic=!0),t.underline&&(s.underline={style:"sng"}),e&&(s.breakLine=!0),{text:t.text,options:s}}function Uh(t,e){const n=[],r=Math.max(6,Math.round(cE*e));for(let s=0;s<t.length;s++){const a=s===t.length-1,i=Vr(t[s]);if(i.length===0){a||n.push({text:"",options:{breakLine:!0}});continue}for(let l=0;l<i.length;l++){const c=l===i.length-1&&!a;n.push(pE(i[l],c,e,r))}}return n.length===0?null:n.some(s=>{var a;return(a=s.text)==null?void 0:a.trim()})?n:null}function Ia(t,e){const n=t.data;if(n&&Array.isArray(n)){const s=Uh(n,e);if(s){const a=Ul(n[0]);return{rows:s,align:a}}}const r=t.text;if(r&&typeof r=="object"&&"children"in r){const s=Uh([r],e);if(s){const a=Ul(r);return{rows:s,align:a}}}return null}function Ul(t){if(!t||typeof t!="object")return;const e=t.align;if(e==="center"||e==="right"||e==="left")return e}function gE(t,e,n,r){const s=t.text,a=t.data;let i=r,l=n;const d=[];Array.isArray(a)&&d.push(...a),s&&typeof s=="object"&&d.push(s);for(const c of d){const h=Ul(c);if(h){i=h;break}}for(const c of d){const h=Vr(c);for(const u of h){const p=Jp(u["font-size"]);if(p&&p>0)return l=Math.max(6,Math.round(p*e)),{align:i,fontSizePt:l}}}return{align:i,fontSizePt:l}}function yE(t,e){const n=t.data;if(Array.isArray(n)&&n.length>0){const s=n.map(a=>Vr(a).map(l=>l.text||"").join("")).filter(a=>a.length>0);if(s.length>0)return s.join(`
|
|
202
|
+
`),origin:{kind:"kb-note",id:d.id}});return c&&n.current.set(i,c),c},[]),a=m.useCallback(async i=>{const l=[];if(i){const d=await s(i);d&&l.push(d)}for(const d of t){if(d.id===i)continue;const c=await s(d.id);c&&l.push(c)}return l},[t,s]);return{noteMetas:t,refresh:r,loadReadingSource:s,buildReadingQueue:a}}const Ka=new Map,jo=new Map;function Up(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function SC(t){const e=jo.get(t);if(e)return e;const n=new Promise(r=>{const s=new Audio;s.preload="metadata";const a=()=>{s.removeEventListener("loadedmetadata",i),s.removeEventListener("error",l),s.src="",s.load(),jo.delete(t),r()},i=()=>{Up(s.duration)&&Ka.set(t,s.duration),a()},l=()=>{a()};s.addEventListener("loadedmetadata",i),s.addEventListener("error",l),s.src=t});return jo.set(t,n),n}function yh(t){const e=m.useRef(Ka),[,n]=m.useState(0);return m.useEffect(()=>{let r=!1;const s=[];return t.forEach(a=>{if(a.audioUrl){if(Up(a.duration)){Ka.set(a.audioUrl,a.duration);return}Ka.has(a.audioUrl)||s.push(SC(a.audioUrl).then(()=>{r||n(i=>i+1)}))}}),()=>{r=!0}},[t]),e.current}const vh=({items:t,onSelect:e,onContextMenu:n,onToggleFavorite:r,onTogglePlayback:s,showFavoriteButton:a=!1,showPlaybackIndicator:i=!1,className:l,itemClassName:d,onOpenKnowledgeBase:c})=>o.jsx("div",{className:St("audio-track-list",l),children:t.map(h=>o.jsxs("div",{role:"button",tabIndex:0,className:St("audio-track-list__item",d,{"audio-track-list__item--active":h.isActive}),onClick:()=>e(h),onContextMenu:u=>n==null?void 0:n(h,u),onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),e(h))},children:[o.jsx("div",{className:"audio-track-list__cover",children:o.jsx(Uf,{src:h.previewImageUrl,alt:h.title,fallbackClassName:"audio-track-list__cover audio-track-list__cover--fallback",iconSize:16,loading:"lazy"})}),o.jsxs("div",{className:"audio-track-list__meta",children:[o.jsx("div",{className:"audio-track-list__title",children:h.title}),o.jsx("div",{className:"audio-track-list__subtitle",children:h.subtitle||"--:--"})]}),a||i?o.jsxs("div",{className:"audio-track-list__trailing",onClick:u=>u.stopPropagation(),onPointerDown:u=>u.stopPropagation(),children:[h.noteId&&c?o.jsx(Le,{content:"打开知识库笔记",showArrow:!1,children:o.jsx("button",{type:"button",className:"audio-track-list__action-btn",onClick:()=>c(h.noteId),"aria-label":"打开知识库笔记",children:o.jsx(cv,{size:14})})}):null,a&&h.canFavorite!==!1?o.jsx("button",{type:"button",className:St("audio-track-list__favorite-btn",{"audio-track-list__favorite-btn--active":h.isFavorite}),onClick:()=>r==null?void 0:r(h),"aria-label":h.isFavorite?"取消收藏":"加入收藏",children:o.jsx(zf,{size:14,fill:h.isFavorite?"currentColor":"none"})}):null,i?o.jsx("button",{type:"button",className:"audio-track-list__status",onClick:()=>s==null?void 0:s(h),"aria-label":h.isPlaying?"暂停播放":"开始播放",children:h.isPlaying?o.jsx(Hf,{size:16}):o.jsx(ic,{size:16})}):null]}):null]},h.id))}),IC=({showPlaybackQueue:t,queueListItems:e,listItems:n,emptyLabel:r,onPlayQueueItem:s,onPlayListItem:a,onContextMenu:i,onToggleFavorite:l,onOpenKnowledgeBase:d})=>t?o.jsx(vh,{className:"audio-track-list--queue",items:e,onSelect:c=>s(c.id),onContextMenu:(c,h)=>{c.playlistItemRef&&(h.preventDefault(),h.stopPropagation(),i(c.playlistItemRef,h.clientX,h.clientY))},onToggleFavorite:c=>{c.assetId&&l(c.assetId)},onTogglePlayback:c=>s(c.id),onOpenKnowledgeBase:d,showFavoriteButton:!0,showPlaybackIndicator:!0}):n.length===0?o.jsxs("div",{className:"music-player-tool__empty",children:[o.jsx(tc,{size:18}),o.jsx("span",{children:r})]}):o.jsx(vh,{items:n,onSelect:a,onContextMenu:(c,h)=>{c.playlistItemRef&&(h.preventDefault(),h.stopPropagation(),i(c.playlistItemRef,h.clientX,h.clientY))},onToggleFavorite:c=>{c.assetId&&l(c.assetId)},onTogglePlayback:a,onOpenKnowledgeBase:d,showFavoriteButton:!0,showPlaybackIndicator:!0}),Oo={width:520,height:640},wh={width:860,height:640},Hp={sequential:o.jsx(Tv,{size:16}),"list-loop":o.jsx(_v,{size:16}),"single-loop":o.jsx(bv,{size:16}),shuffle:o.jsx(xv,{size:16})},kC=Object.keys(el).map(t=>({value:t,content:el[t],prefixIcon:Hp[t]}));function CC(t,e){return wv(e).map(n=>{const r=Gf(n),s=Math.abs(n-t)<.001;return{value:n,content:s?`✓ ${r}`:r}})}function qa(t){if(typeof t!="number"||!Number.isFinite(t)||t<=0)return"--:--";const e=Math.floor(t),n=Math.floor(e/60),r=e%60;return`${n}:${String(r).padStart(2,"0")}`}function PC(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?"--:--":new Date(t).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})}function Mo(t,e){const n=qa(t);return n!=="--:--"?n:PC(e)}function EC(t){window.dispatchEvent(new CustomEvent("kb:open",{detail:{noteId:t}}))}function AC(t){return t!=null}const jC=({toolInstanceId:t})=>{var Ot;const e=t||ri,{assets:n,loadAssets:r}=dv(),{playlists:s,playlistItems:a,favoriteAssetIds:i,createPlaylist:l,renamePlaylist:d,deletePlaylist:c,addItemToPlaylist:h,removeItemFromPlaylist:u,toggleFavorite:p,getPlaylistItemRefs:y}=uv(),f=Fk(),g=f.queueSource==="reading",{noteMetas:w,loadReadingSource:x,buildReadingQueue:v}=TC(),[_,T]=m.useState(""),[b,I]=m.useState(()=>f.activePlaylistId?f.activePlaylistId:f.queueSource==="reading"?kn:hn),A=b===kn,[k,U]=m.useState(!1),[D,X]=m.useState(""),[L,O]=m.useState(null),[G,C]=m.useState(null),[P,j]=m.useState("create"),[N,B]=m.useState(null),K=m.useRef(f.activePlaylistId||(f.queueSource==="reading"?kn:hn));m.useEffect(()=>{r()},[r]),m.useEffect(()=>{const $=()=>{O(null)};return document.addEventListener("click",$),document.addEventListener("scroll",$,!0),()=>{document.removeEventListener("click",$),document.removeEventListener("scroll",$,!0)}},[]);const fe=_.trim().toLowerCase(),ae=m.useMemo(()=>n.filter($=>$.type===Br.AUDIO),[n]),te=m.useMemo(()=>new Map(ae.map($=>[$.id,$])),[ae]),Se=m.useMemo(()=>new Map(w.map($=>[$.id,$])),[w]),Ee=m.useMemo(()=>ae.filter($=>fe.length===0?!0:$.name.toLowerCase().includes(fe)).sort(($,Oe)=>Oe.createdAt-$.createdAt),[fe,ae]),Te=m.useMemo(()=>b!==hn&&b!==kn?y(b):[],[y,b]),ke=f.queue.length>0&&(g||!!f.activeAudioUrl),ne=f.mediaType==="reading"?"reading":"audio",M=f.activePlaylistId||(g?kn:f.queueSource==="playlist"?f.activePlaylistId||hn:hn),q=ke&&b===M,R=m.useMemo(()=>CC(f.effectivePlaybackRate,ne),[f.effectivePlaybackRate,ne]),J=Gf(f.effectivePlaybackRate),Ce=`${f.mediaType==="reading"?"语音速度":"播放速度"} ${J}`,re=m.useMemo(()=>ke?M===ad?[{id:ad,label:f.activePlaylistName||hv,count:f.queue.length,type:"audio"}]:M===id?[{id,label:f.activePlaylistName||fv,count:f.queue.length,type:"reading"}]:[]:[],[f.activePlaylistName,f.queue.length,M,ke]);m.useEffect(()=>{if(!ke){K.current=M;return}I($=>$===M?$:K.current!==M?M:$),K.current=M},[M,ke]);const ze=m.useMemo(()=>f.queue.filter($=>!er($)),[f.queue]),V=yh(ze),z=m.useMemo(()=>ae.map($=>({audioUrl:$.url})),[ae]),F=yh(z),pe=($,Oe)=>er($)?$.readingSourceId:`${$.audioUrl}-${Oe}`,ce=$=>{const Oe=te.get($);return Oe?{elementId:`asset:${Oe.id}`,audioUrl:Oe.url,title:Oe.name,duration:Oe.duration,previewImageUrl:Oe.thumbnail,clipId:Oe.clipId,providerTaskId:Oe.providerTaskId}:null},Z=m.useMemo(()=>f.queue.map(($,Oe)=>{var Qe,Pt,Ft,la;if(er($)){const Qn=((Qe=$.segments[$.segments.length-1])==null?void 0:Qe.endMs)||0,un=$.origin.kind==="kb-note"?$.origin.id:void 0;return{id:pe($,Oe),title:$.title||"朗读轨道",subtitle:qa(Qn/1e3),previewImageUrl:$.previewImageUrl,isActive:Oe===f.activeQueueIndex,isPlaying:Oe===f.activeQueueIndex&&f.playing,canFavorite:!1,noteId:un,playlistItemRef:un?{kind:"reading",noteId:un}:void 0}}const Ze=(Pt=$.elementId)!=null&&Pt.startsWith("asset:")?$.elementId.slice(6):((Ft=n.find(Qn=>Qn.type===Br.AUDIO&&Qn.url===$.audioUrl))==null?void 0:Ft.id)||null;return{id:pe($,Oe),title:$.title||"未命名音频",subtitle:Mo(V.get($.audioUrl)??$.duration,Ze?(la=te.get(Ze))==null?void 0:la.createdAt:void 0),previewImageUrl:$.previewImageUrl,isActive:Oe===f.activeQueueIndex,isPlaying:Oe===f.activeQueueIndex&&f.playing,isFavorite:Ze?i.has(Ze):!1,canFavorite:!!Ze,assetId:Ze||void 0,playlistItemRef:Ze?{kind:"asset",assetId:Ze}:void 0}}),[te,n,i,f.activeQueueIndex,f.playing,f.queue,V]),ue=async $=>{const Oe=f.queue.find((Ze,Qe)=>pe(Ze,Qe)===$);if(Oe){if(er(Oe)){f.toggleReadingPlayback(Oe);return}await f.togglePlayback(Oe)}},ye=s.find($=>$.id===b)||null,ie=m.useMemo(()=>new Set(Te.map($=>Ma($))),[Te]),Ae=m.useMemo(()=>{var Ze;const $=(Ze=f.activeElementId)!=null&&Ze.startsWith("asset:")?f.activeElementId.slice(6):null;if($)return te.get($)||null;const Oe=ae.find(Qe=>Qe.url===f.activeAudioUrl&&Qe.name===f.activeTitle);return Oe||ae.find(Qe=>Qe.url===f.activeAudioUrl)||null},[te,ae,f.activeAudioUrl,f.activeElementId,f.activeTitle]),Q=((Ot=f.activeReadingOrigin)==null?void 0:Ot.kind)==="kb-note"?f.activeReadingOrigin.id:null,Pe=m.useMemo(()=>g&&f.activeQueueIndex>=0?f.queue[f.activeQueueIndex]:null,[g,f.activeQueueIndex,f.queue]),$e=(Ae==null?void 0:Ae.id)||null,de=m.useMemo(()=>w.map($=>({id:`reading:${$.id}`,title:$.title||"未命名笔记",subtitle:new Date($.updatedAt).toLocaleDateString("zh-CN"),canFavorite:!1,noteId:$.id,playlistItemRef:{kind:"reading",noteId:$.id},isActive:Q===$.id,isPlaying:Q===$.id&&f.playing&&f.mediaType==="reading"})),[Q,w,f.mediaType,f.playing]),Ge=m.useMemo(()=>Ee.map($=>({id:`asset:${$.id}`,title:$.name,subtitle:Mo(F.get($.url)??$.duration,$.createdAt),previewImageUrl:$.thumbnail,isActive:$e===$.id,isPlaying:$e===$.id&&f.playing&&f.mediaType==="audio",isFavorite:i.has($.id),canFavorite:!0,assetId:$.id,playlistItemRef:{kind:"asset",assetId:$.id}})),[$e,Ee,i,f.mediaType,f.playing,F]),it=m.useMemo(()=>Te.reduce(($,Oe)=>{if(Fr(Oe)){const Qe=te.get(Oe.assetId);return!Qe||fe.length>0&&!Qe.name.toLowerCase().includes(fe)||$.push({id:`asset:${Qe.id}`,title:Qe.name,subtitle:Mo(F.get(Qe.url)??Qe.duration,Qe.createdAt),previewImageUrl:Qe.thumbnail,isActive:$e===Qe.id,isPlaying:$e===Qe.id&&f.playing&&f.mediaType==="audio",isFavorite:i.has(Qe.id),canFavorite:!0,assetId:Qe.id,playlistItemRef:Oe}),$}const Ze=Se.get(Oe.noteId);return!Ze||fe.length>0&&!(Ze.title||"").toLowerCase().includes(fe)||$.push({id:`reading:${Ze.id}`,title:Ze.title||"未命名笔记",subtitle:new Date(Ze.updatedAt).toLocaleDateString("zh-CN"),previewImageUrl:void 0,isFavorite:!1,canFavorite:!1,noteId:Ze.id,playlistItemRef:Oe,isActive:Q===Ze.id,isPlaying:Q===Ze.id&&f.playing&&f.mediaType==="reading"}),$},[]),[$e,Q,te,i,fe,Se,f.mediaType,f.playing,F,Te]),Ye=m.useMemo(()=>b===kn?de:b===hn?Ge:it,[Ge,de,it,b]),Ue=Ye[0]||null,oe=Ue!=null&&Ue.assetId&&te.get(Ue.assetId)||null,ft=g?null:Ae||oe,je=g?er(Pe)?Pe.previewImageUrl:f.activePreviewImageUrl:f.activePreviewImageUrl||(ft==null?void 0:ft.thumbnail),ge=f.queueSource==="playlist"?f.activePlaylistName||"播放列表":f.activePlaylistName||(g?"朗读队列":"当前播放队列"),De=q?ge:A?"全部语音":(ye==null?void 0:ye.name)||"素材库音频",We=q?`${f.queue.length} 项内容`:A?`${Ye.length} 篇笔记`:b===hn?`${Ye.length} 首音频`:`${Ye.length} 项内容`,Re=el[f.playbackMode],gt=Hp[f.playbackMode],ut=async $=>(await Promise.all($.map(async Ze=>Fr(Ze)?ce(Ze.assetId):x(Ze.noteId)))).filter(AC),lt=async $=>{const Oe=$.playlistItemRef;if(!Oe)return;if(Fr(Oe)){const Qe=ce(Oe.assetId);if(!Qe)return;if(b===hn)f.setQueue(Ee.flatMap(Pt=>{const Ft=ce(Pt.id);return Ft?[Ft]:[]}));else{const Pt=await ut(Te);f.setQueue(Pt,{queueSource:"playlist",playlistId:ye==null?void 0:ye.id,playlistName:ye==null?void 0:ye.name})}await f.togglePlayback(Qe);return}let Ze=await x(Oe.noteId);if(Ze){if(b===kn){const Qe=await v(Oe.noteId);f.setReadingQueue(Qe),Ze=Qe.find(Pt=>Pt.origin.kind==="kb-note"&&Pt.origin.id===Oe.noteId)||Ze}else{const Qe=await ut(Te);f.setQueue(Qe,{queueSource:"playlist",playlistId:ye==null?void 0:ye.id,playlistName:ye==null?void 0:ye.name}),Ze=Qe.find(Ft=>er(Ft)&&Ft.origin.kind==="kb-note"&&Ft.origin.id===Oe.noteId)||Ze}f.toggleReadingPlayback(Ze)}},Rt=()=>{U(!1),X(""),C(null),B(null),j("create")},Ut=$=>{C($||null),X(""),j("create"),B(null),U(!0),O(null)},Jt=($,Oe)=>{C(null),j("rename"),B($),X(Oe),U(!0)},Lt=g?f.readingSegments:[],Qt=g?f.activeReadingSegmentIndex:-1,jt=g&&Lt.length>0,en=b!==kn;return m.useEffect(()=>{var Pt,Ft;const $=pt.getToolState(e);if(!$||$.status!=="open")return;const Oe=jt?wh:Oo,Ze=((Pt=$.size)==null?void 0:Pt.width)??Oo.width,Qe=((Ft=$.size)==null?void 0:Ft.height)??Oo.height;if(!(Ze===Oe.width&&Qe===Oe.height)){if(jt){pt.updateToolSize(e,Oe);return}Ze<=wh.width&&pt.updateToolSize(e,Oe)}},[jt,e]),o.jsxs("div",{className:`music-player-tool ${jt?"music-player-tool--with-subtitle":""}`,children:[o.jsxs("div",{className:"music-player-tool__layout",children:[o.jsxs("div",{className:"music-player-tool__main-column",children:[o.jsxs("div",{className:"music-player-tool__now-playing",children:[o.jsx("div",{className:"music-player-tool__now-playing-cover",children:o.jsx(Uf,{src:je,alt:g?"当前朗读":(ft==null?void 0:ft.name)||(Ue==null?void 0:Ue.title)||"当前音频",fallbackClassName:"music-player-tool__now-playing-cover music-player-tool__now-playing-cover--fallback",iconSize:22})}),o.jsxs("div",{className:"music-player-tool__now-playing-meta",children:[o.jsx("div",{className:"music-player-tool__eyebrow",children:"当前播放"}),o.jsx("div",{className:"music-player-tool__title",children:g?f.activeTitle||(er(Pe)?Pe.title:"未选择朗读"):f.activeTitle||(ft==null?void 0:ft.name)||(Ue==null?void 0:Ue.title)||"未选择音频"}),o.jsxs("div",{className:"music-player-tool__subtitle",children:[f.activePlaylistName||(f.queueSource==="playlist"?"播放列表":g?"朗读轨道":"画布音频")," · ",qa(f.currentTime)," / ",qa(f.duration)]})]}),o.jsxs("div",{className:"music-player-tool__now-playing-actions",children:[o.jsx(Le,{content:"上一首",showArrow:!1,children:o.jsx("button",{type:"button",className:"music-player-tool__action-btn",onClick:()=>void f.playPrevious(),disabled:f.activeQueueIndex<=0,"aria-label":"上一首",children:o.jsx(mv,{size:16})})}),o.jsx(Le,{content:f.playing?"暂停":"播放",showArrow:!1,children:o.jsx("button",{type:"button",className:"music-player-tool__action-btn music-player-tool__action-btn--primary",onClick:()=>{if(f.playing)f.pausePlayback();else if(g)f.resumePlayback();else if(f.activeAudioUrl)f.resumePlayback();else if(Ue)lt(Ue);else return},disabled:g?!f.activeReadingSourceId:!f.activeAudioUrl&&!Ue,"aria-label":f.playing?"暂停":"播放",children:f.playing?o.jsx(Hf,{size:16}):o.jsx(ic,{size:16})})}),o.jsx(Le,{content:"下一首",showArrow:!1,children:o.jsx("button",{type:"button",className:"music-player-tool__action-btn",onClick:()=>void f.playNext(),disabled:f.activeQueueIndex<0||f.activeQueueIndex>=f.queue.length-1,"aria-label":"下一首",children:o.jsx(pv,{size:16})})}),o.jsx(Le,{content:Ce,showArrow:!1,children:o.jsx("span",{children:o.jsx(qr,{options:R,trigger:"click",placement:"bottom-right",minColumnWidth:112,onClick:$=>f.setPlaybackRate(Number($.value)),children:o.jsx("button",{type:"button",className:"music-player-tool__action-btn","aria-label":`切换播放速度,当前${J}`,children:o.jsx(gv,{size:16})})})})}),o.jsx(Le,{content:Re,showArrow:!1,children:o.jsx("span",{children:o.jsx(qr,{options:kC,trigger:"click",placement:"bottom-right",minColumnWidth:132,onClick:$=>f.setPlaybackMode($.value),children:o.jsx("button",{type:"button",className:"music-player-tool__action-btn","aria-label":`切换播放模式,当前${Re}`,children:gt})})})}),o.jsx(Le,{content:"切回播放控件",showArrow:!1,children:o.jsx("button",{type:"button",className:"music-player-tool__action-btn music-player-tool__action-btn--ghost",onPointerDown:$=>{$.preventDefault(),$.stopPropagation()},onClick:$=>{$.preventDefault(),$.stopPropagation(),requestAnimationFrame(()=>{pt.minimizeTool(e)})},"aria-label":"切回播放控件",children:o.jsx(yv,{size:16})})})]})]}),o.jsx(vv,{className:"music-player-tool__playlists",selectedPlaylistId:b,allCount:n.filter($=>$.type===Br.AUDIO).length,allTracksCount:w.length,tempTabs:re,playlists:s,playlistItems:a,onSelect:I,onCreate:()=>Ut(),onRename:$=>Jt($.id,$.name),onDelete:$=>void c($.id)}),en&&!q?o.jsx("div",{className:"music-player-tool__search",children:o.jsx($t,{value:_,onChange:$=>T(String($)),prefixIcon:o.jsx(oc,{size:14}),placeholder:b===hn?"搜索素材库音频":"搜索当前播放列表",clearable:!0})}):null,o.jsxs("div",{className:"music-player-tool__list-header",children:[o.jsx("span",{children:De}),o.jsx("span",{children:We})]}),o.jsx("div",{className:"music-player-tool__list",children:o.jsx(IC,{showPlaybackQueue:q,queueListItems:Z,listItems:Ye,emptyLabel:b===kn?"知识库还没有笔记":b===hn?"当前列表里还没有音频":"当前播放列表里还没有内容",onPlayQueueItem:$=>void ue($),onPlayListItem:$=>void lt($),onContextMenu:($,Oe,Ze)=>O({x:Oe,y:Ze,item:$}),onToggleFavorite:$=>void p($),onOpenKnowledgeBase:EC})})]}),jt?o.jsxs("aside",{className:"music-player-tool__subtitle-column",children:[o.jsxs("div",{className:"music-player-tool__subtitle-header",children:[o.jsx("span",{children:"字幕"}),o.jsxs("span",{children:[Lt.length," 段"]})]}),o.jsx("div",{className:"music-player-tool__subtitle-panel",children:Lt.map(($,Oe)=>{const Ze=Oe===Qt;return o.jsx("button",{type:"button",className:`music-player-tool__subtitle-line ${Ze?"music-player-tool__subtitle-line--active":""}`,onClick:()=>f.seekToReadingSegment(Oe),children:$.text},$.id)})})]}):null]}),o.jsx(Zn,{visible:k,header:P==="rename"?"重命名播放列表":"新建播放列表",onClose:Rt,onConfirm:async()=>{if(P==="rename"&&N)await d(N,D);else{const $=await l(D);G&&await h(G,$.id),I($.id)}Rt()},onCancel:Rt,confirmBtn:"确定",cancelBtn:"取消",children:o.jsx($t,{value:D,onChange:$=>X(String($)),placeholder:"请输入播放列表名称",autofocus:!0})}),o.jsx(yC,{contextMenu:L,playlists:s,playlistItems:a,favoriteAssetIds:i,selectedPlaylistId:b===hn?null:b,currentPlaylistItemKeys:ie,onClose:()=>O(null),onToggleFavorite:$=>void p($),onAddToPlaylist:($,Oe)=>void h($,Oe),onRemoveFromPlaylist:($,Oe)=>void u($,Oe),onCreatePlaylistAndAdd:$=>Ut($)})]})},Gp=jC,OC={manifest:{id:ri,name:"音乐播放器",description:"从素材库选择音频并后台播放,可与画布播放控件联动",icon:o.jsx(tc,{size:18,strokeWidth:1.75}),category:tt.UTILITIES,component:"music-player",defaultWidth:520,defaultHeight:640},Component:Gp},MC=Object.freeze(Object.defineProperty({__proto__:null,MusicPlayerToolComponent:Gp,musicPlayerTool:OC},Symbol.toStringTag,{value:"Module"})),DC=m.lazy(()=>Xe(()=>import("./MusicAnalyzer-D2NTonEA.js"),__vite__mapDeps([0,8,9]),import.meta.url)),NC={width:"100%",height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",boxSizing:"border-box"},RC=()=>o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:200,color:"#999",fontSize:14},children:"加载中..."}),Wp=t=>o.jsx("div",{style:NC,children:o.jsx(m.Suspense,{fallback:o.jsx(RC,{}),children:o.jsx(DC,{...t})})}),LC={manifest:{id:"music-analyzer",name:"爆款音乐生成",description:"分析音频、改写歌词,并一键送入 Suno 生成音乐",icon:o.jsx(Df,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:"music-analyzer",supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:520,defaultHeight:700},Component:Wp},FC=Object.freeze(Object.defineProperty({__proto__:null,MusicAnalyzerToolComponent:Wp,musicAnalyzerTool:LC},Symbol.toStringTag,{value:"Module"})),BC=m.lazy(()=>Xe(()=>import("./VideoAnalyzer-DoaGlK92.js"),__vite__mapDeps([0,10,8,7,11]),import.meta.url)),zC={width:"100%",height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",boxSizing:"border-box"},$C=()=>o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:200,color:"#999",fontSize:14},children:"加载中..."}),Vp=t=>o.jsx("div",{style:zC,children:o.jsx(m.Suspense,{fallback:o.jsx($C,{}),children:o.jsx(BC,{...t})})}),UC={manifest:{id:"video-analyzer",name:"爆款视频生成",description:"AI 分析视频内容,提取镜头、脚本、风格等结构化数据",icon:o.jsx(jf,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:"video-analyzer",supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:680,defaultHeight:700},Component:Vp},HC=Object.freeze(Object.defineProperty({__proto__:null,VideoAnalyzerToolComponent:Vp,videoAnalyzerTool:UC},Symbol.toStringTag,{value:"Module"})),GC=m.lazy(()=>Xe(()=>import("./MVCreator-B9uaRsGE.js"),__vite__mapDeps([0,10,8,12,11,7,9]),import.meta.url)),WC={width:"100%",height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",boxSizing:"border-box"},VC=()=>o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:200,color:"#999",fontSize:14},children:"加载中..."}),Kp=t=>o.jsx("div",{style:WC,children:o.jsx(m.Suspense,{fallback:o.jsx(VC,{}),children:o.jsx(GC,{...t})})}),KC={manifest:{id:"mv-creator",name:"爆款MV生成",description:"输入创意,AI 生成音乐和分镜视频,一站式 MV 创作",icon:o.jsx(Of,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:"mv-creator",supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:680,defaultHeight:700},Component:Kp},qC=Object.freeze(Object.defineProperty({__proto__:null,MVCreatorToolComponent:Kp,mvCreatorTool:KC},Symbol.toStringTag,{value:"Module"})),YC=m.lazy(()=>Xe(()=>import("./ComicCreator-DhxXCyJR.js"),__vite__mapDeps([0,8,10,13,7,11,9]),import.meta.url)),ZC={width:"100%",height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",boxSizing:"border-box"},XC=()=>o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:200,color:"#999",fontSize:14},children:"加载中..."}),qp=t=>o.jsx("div",{style:ZC,children:o.jsx(m.Suspense,{fallback:o.jsx(XC,{}),children:o.jsx(YC,{...t})})}),JC={manifest:{id:ti,name:"多图生成",description:"适合故事分镜、教程步骤、产品手册、营销图文等多页图片,一键规划提示词、批量出图并导出 ZIP/PPTX/PDF",icon:o.jsx(Af,{size:18,strokeWidth:1.75}),category:tt.AI_TOOLS,component:ti,supportsMultipleWindows:!0,defaultWindowBehavior:{autoPinOnOpen:!0},defaultWidth:720,defaultHeight:760},Component:qp},QC=Object.freeze(Object.defineProperty({__proto__:null,ComicCreatorToolComponent:qp,comicCreatorTool:JC},Symbol.toStringTag,{value:"Module"})),eP=[{category:"演示文稿",categoryEn:"Presentation",items:[{label:"PPT 16:9",labelEn:"PPT 16:9",width:1920,height:1080},{label:"PPT 4:3",labelEn:"PPT 4:3",width:1024,height:768}]},{category:"手机屏幕",categoryEn:"Phone",items:[{label:"iPhone 15 Pro",labelEn:"iPhone 15 Pro",width:393,height:852},{label:"iPhone SE",labelEn:"iPhone SE",width:375,height:667},{label:"Android",labelEn:"Android",width:360,height:800}]},{category:"平板",categoryEn:"Tablet",items:[{label:"iPad",labelEn:"iPad",width:768,height:1024},{label:'iPad Pro 12.9"',labelEn:'iPad Pro 12.9"',width:1024,height:1366}]},{category:"社交媒体",categoryEn:"Social Media",items:[{label:"正方形 1:1",labelEn:"Square 1:1",width:1080,height:1080},{label:"竖版 9:16",labelEn:"Portrait 9:16",width:1080,height:1920},{label:"横版 16:9",labelEn:"Landscape 16:9",width:1920,height:1080}]},{category:"照片 / 海报",categoryEn:"Photo / Poster",items:[{label:"A4 竖版",labelEn:"A4 Portrait",width:595,height:842},{label:"A4 横版",labelEn:"A4 Landscape",width:842,height:595},{label:"照片 4:3",labelEn:"Photo 4:3",width:1200,height:900},{label:"照片 3:2",labelEn:"Photo 3:2",width:1200,height:800}]},{category:"桌面",categoryEn:"Desktop",items:[{label:"Full HD",labelEn:"Full HD",width:1920,height:1080},{label:"MacBook",labelEn:"MacBook",width:1440,height:900},{label:"4K UHD",labelEn:"4K UHD",width:3840,height:2160}]}],xh=[{family:"PingFang SC",source:"system",displayName:"苹方",previewText:"元旦快乐"},{family:"Microsoft YaHei",source:"system",displayName:"微软雅黑",previewText:"元旦快乐"},{family:"SimHei",source:"system",displayName:"黑体",previewText:"元旦快乐"},{family:"SimSun",source:"system",displayName:"宋体",previewText:"元旦快乐"},{family:"KaiTi",source:"system",displayName:"楷体",previewText:"元旦快乐"},{family:"FangSong",source:"system",displayName:"仿宋",previewText:"元旦快乐"},{family:"STXingkai",source:"system",displayName:"华文行楷",previewText:"元旦快乐"},{family:"STCaiyun",source:"system",displayName:"华文彩云",previewText:"元旦快乐"},{family:"STHupo",source:"system",displayName:"华文琥珀",previewText:"元旦快乐"},{family:"LiSu",source:"system",displayName:"隶书",previewText:"元旦快乐"},{family:"YouYuan",source:"system",displayName:"幼圆",previewText:"元旦快乐"},{family:"Arial",source:"system",displayName:"Arial",previewText:"Happy New Year"},{family:"Georgia",source:"system",displayName:"Georgia",previewText:"Happy New Year"},{family:"Times New Roman",source:"system",displayName:"Times New Roman",previewText:"Happy New Year"}],Do=[{family:"Noto Sans SC",source:"google",displayName:"Noto Sans 简体",previewText:"元旦快乐"},{family:"Noto Serif SC",source:"google",displayName:"Noto Serif 简体",previewText:"元旦快乐"},{family:"ZCOOL XiaoWei",source:"google",displayName:"站酷小薇",previewText:"元旦快乐"},{family:"ZCOOL QingKe HuangYou",source:"google",displayName:"站酷庆科黄油体",previewText:"元旦快乐"},{family:"Ma Shan Zheng",source:"google",displayName:"马善政毛笔楷书",previewText:"元旦快乐"},{family:"Zhi Mang Xing",source:"google",displayName:"芝麻行",previewText:"元旦快乐"},{family:"Liu Jian Mao Cao",source:"google",displayName:"刘建毛草",previewText:"元旦快乐"},{family:"Long Cang",source:"google",displayName:"龙藏",previewText:"元旦快乐"},{family:"Lobster",source:"google",displayName:"Lobster",previewText:"Happy New Year"},{family:"Pacifico",source:"google",displayName:"Pacifico",previewText:"Happy New Year"},{family:"Dancing Script",source:"google",displayName:"Dancing Script",previewText:"Happy New Year"},{family:"Satisfy",source:"google",displayName:"Satisfy",previewText:"Happy New Year"}],r1=[{id:"gold",name:"Golden",nameZh:"金色",category:"festival",config:{type:"linear",angle:135,stops:[{color:"#FFD700",position:0},{color:"#FFA500",position:50},{color:"#FF8C00",position:100}],target:"text"}},{id:"red-gold",name:"Red Gold",nameZh:"红金",category:"festival",config:{type:"linear",angle:135,stops:[{color:"#FF0000",position:0},{color:"#FFD700",position:50},{color:"#FF4500",position:100}],target:"text"}},{id:"new-year",name:"New Year",nameZh:"新年红",category:"festival",config:{type:"linear",angle:180,stops:[{color:"#DC143C",position:0},{color:"#B22222",position:50},{color:"#8B0000",position:100}],target:"text"}},{id:"spring-festival",name:"Spring Festival",nameZh:"春节",category:"festival",config:{type:"linear",angle:135,stops:[{color:"#C41E3A",position:0},{color:"#FFD700",position:30},{color:"#C41E3A",position:70},{color:"#FFD700",position:100}],target:"text"}},{id:"silver",name:"Silver",nameZh:"银色",category:"metal",config:{type:"linear",angle:135,stops:[{color:"#C0C0C0",position:0},{color:"#FFFFFF",position:50},{color:"#A9A9A9",position:100}],target:"text"}},{id:"bronze",name:"Bronze",nameZh:"青铜",category:"metal",config:{type:"linear",angle:135,stops:[{color:"#CD7F32",position:0},{color:"#DAA520",position:50},{color:"#8B4513",position:100}],target:"text"}},{id:"rose-gold",name:"Rose Gold",nameZh:"玫瑰金",category:"metal",config:{type:"linear",angle:135,stops:[{color:"#B76E79",position:0},{color:"#E8B4B8",position:50},{color:"#B76E79",position:100}],target:"text"}},{id:"rainbow",name:"Rainbow",nameZh:"彩虹",category:"nature",config:{type:"linear",angle:90,stops:[{color:"#FF0000",position:0},{color:"#FF7F00",position:17},{color:"#FFFF00",position:33},{color:"#00FF00",position:50},{color:"#0000FF",position:67},{color:"#4B0082",position:83},{color:"#9400D3",position:100}],target:"text"}},{id:"sunset",name:"Sunset",nameZh:"日落",category:"nature",config:{type:"linear",angle:180,stops:[{color:"#FF6B6B",position:0},{color:"#FFE66D",position:50},{color:"#4ECDC4",position:100}],target:"text"}},{id:"ocean",name:"Ocean",nameZh:"海洋",category:"nature",config:{type:"linear",angle:180,stops:[{color:"#667eea",position:0},{color:"#764ba2",position:100}],target:"text"}},{id:"forest",name:"Forest",nameZh:"森林",category:"nature",config:{type:"linear",angle:135,stops:[{color:"#134E5E",position:0},{color:"#71B280",position:100}],target:"text"}}],s1={textShadow:{subtle:{type:"text",enabled:!0,color:"rgba(0, 0, 0, 0.3)",offsetX:1,offsetY:1,blur:2},medium:{type:"text",enabled:!0,color:"rgba(0, 0, 0, 0.5)",offsetX:2,offsetY:2,blur:4},strong:{type:"text",enabled:!0,color:"rgba(0, 0, 0, 0.7)",offsetX:4,offsetY:4,blur:8},longShadow:{type:"text",enabled:!0,color:"rgba(0, 0, 0, 0.4)",offsetX:6,offsetY:6,blur:0}}};class tP{constructor(){this.fontLoadStates=new Map,this.loadedFonts=new Set,this.fontPreviewUrls=new Map}async loadGoogleFont(e,n=[400,700]){const r=this.fontLoadStates.get(e);if(r){if(r.status==="loaded")return Promise.resolve();if(r.status==="loading"&&r.promise)return r.promise;if(r.status==="error"&&r.error)throw r.error}const s=this._loadGoogleFontInternal(e,n);this.fontLoadStates.set(e,{status:"loading",promise:s});try{await s,this.fontLoadStates.set(e,{status:"loaded"}),this.loadedFonts.add(e)}catch(a){const i=a;throw this.fontLoadStates.set(e,{status:"error",error:i}),i}}_loadGoogleFontInternal(e,n){return new Promise((r,s)=>{const a=`google-font-${e.replace(/\s+/g,"-").toLowerCase()}`;if(document.getElementById(a)){r();return}const l=document.createElement("link");l.id=a,l.rel="stylesheet",l.href=`https://fonts.googleapis.com/css2?family=${encodeURIComponent(e)}:wght@${n.join(";")}&display=swap`,l.onload=()=>{document.fonts&&document.fonts.ready?document.fonts.ready.then(()=>r()):setTimeout(()=>r(),100)},l.onerror=()=>s(new Error(`Failed to load font: ${e}`)),document.head.appendChild(l)})}isFontLoaded(e){return this.loadedFonts.has(e)}getFontLoadStatus(e){var n;return((n=this.fontLoadStates.get(e))==null?void 0:n.status)||"pending"}extractFontsFromBoard(e){const n=new Set,r=s=>{if(s){if(s["font-family"]&&n.add(s["font-family"]),typeof s.style=="string"){const a=s.style.match(/font-family:\s*["']?([^;"']+)["']?/);if(a&&a[1]){const i=a[1].trim().replace(/['"]/g,"");n.add(i)}}s.text&&Array.isArray(s.text.children)&&s.text.children.forEach(a=>{a["font-family"]&&n.add(a["font-family"]),r(a)}),Array.isArray(s.children)&&s.children.forEach(a=>{if(a["font-family"]&&n.add(a["font-family"]),typeof a.style=="string"){const i=a.style.match(/font-family:\s*["']?([^;"']+)["']?/);if(i&&i[1]){const l=i[1].trim().replace(/['"]/g,"");n.add(l)}}r(a)})}};return Array.isArray(e)?e.forEach(r):r(e),Array.from(n)}async preloadBoardFonts(e){const r=this.extractFontsFromBoard(e).filter(s=>Do.some(a=>a.family===s));await Promise.allSettled(r.map(s=>this.loadGoogleFont(s)))}getFontPreviewUrl(e){return this.fontPreviewUrls.get(e)||null}setFontPreviewUrl(e,n){this.fontPreviewUrls.set(e,n)}async generateFontPreview(e,n="元旦快乐 Happy New Year",r={}){const{width:s=200,height:a=60,fontSize:i=24,backgroundColor:l="#ffffff",textColor:d="#000000"}=r,c=this.fontPreviewUrls.get(e);if(c)return c;const h=[...Do,...xh].find(f=>f.family===e);(h==null?void 0:h.source)==="google"&&!this.isFontLoaded(e)&&await this.loadGoogleFont(e);const u=document.createElement("canvas");u.width=s,u.height=a;const p=u.getContext("2d");if(!p)throw new Error("Failed to get canvas context");p.fillStyle=l,p.fillRect(0,0,s,a),p.fillStyle=d,p.font=`${i}px '${e}', sans-serif`,p.textAlign="center",p.textBaseline="middle",p.fillText(n,s/2,a/2);const y=u.toDataURL("image/png");return this.fontPreviewUrls.set(e,y),y}async generateAllFontPreviews(){const e=[...Do,...xh],n=e.filter(r=>r.source==="google");await Promise.allSettled(n.map(r=>this.loadGoogleFont(r.family))),await Promise.allSettled(e.map(r=>this.generateFontPreview(r.family,r.previewText)))}clearCache(){this.fontLoadStates.clear(),this.loadedFonts.clear(),this.fontPreviewUrls.clear()}getLoadedFonts(){return Array.from(this.loadedFonts)}}const nP=new tP;function Rl(t){const e={...t};return e.id=Xl(),e.children&&Array.isArray(e.children)&&(e.children=e.children.map(n=>Rl(n))),e}function bh(t,e){let n=null;return t.points?n=Fe.getRectangleByPoints(t.points):t.x!==void 0&&t.y!==void 0&&(n={x:t.x,y:t.y,width:t.width||0,height:t.height||0}),n?!(n.x+n.width<e.x||n.x>e.x+e.width||n.y+n.height<e.y||n.y>e.y+e.height):!1}function Ss(t,e,n){const r={...t};return r.points?r.points=r.points.map(s=>[s[0]+e,s[1]+n]):r.x!==void 0&&r.y!==void 0&&(r.x+=e,r.y+=n),r.children&&Array.isArray(r.children)&&(r.children=r.children.map(s=>Ss(s,e,n))),r}function _h(t,e){return t.y<e.y+e.height&&e.y<t.y+t.height}function rP(t,e,n){for(const{frame:r}of e){if(r.id===n)continue;const s=Fe.getRectangleByPoints(r.points);if(t.x<s.x+s.width&&t.x+t.width>s.x&&t.y<s.y+s.height&&t.y+t.height>s.y)return!0}return!1}function sP(t,e,n="zh"){const r=t.children.findIndex(f=>f.id===e.id);if(r===-1)return ee.warning(n==="zh"?"PPT 页面不存在":"PPT page not found"),null;if(!(t.children[r]===e))return ee.warning(n==="zh"?"暂不支持复制嵌套 PPT 页面":"Nested PPT page duplication not supported"),null;const a=Fe.getRectangleByPoints(e.points),i=[];t.children.forEach((f,g)=>{at(f)&&i.push({frame:f,index:g})});const l=i.findIndex(f=>f.index===r);let d=0,c=0,h=!1;if(l<i.length-1){const f=i[l+1].frame,g=Fe.getRectangleByPoints(f.points);if(_h(a,g))d=g.x-a.x,c=g.y-a.y,h=!0;else{const v={x:a.x+a.width+100,y:a.y,width:a.width,height:a.height};rP(v,i,e.id)?(d=0,c=a.height+100):(d=a.width+100,c=0),h=!1}}else d=a.width+100,c=0,h=!1;const u=[];t.children.forEach((f,g)=>{!at(f)&&bh(f,a)&&u.push({element:f,index:g})});let p=Rl(e);p.name=`${Yt(e)} (${n==="zh"?"副本":"Copy"})`,p=Ss(p,d,c);const y=u.map(f=>{let g=Rl(f.element);return g=Ss(g,d,c),g});if(h){const f=i.slice(l+1).filter(({frame:w})=>{const x=Fe.getRectangleByPoints(w.points);return _h(a,x)}),g=[];t.children.forEach((w,x)=>{if(!at(w))for(const{frame:v}of f){const _=Fe.getRectangleByPoints(v.points);if(bh(w,_)){g.push({element:w,index:x});break}}});for(const{frame:w,index:x}of f){const v=Ss(w,d,c);ht.setNode(t,v,[x])}for(const{element:w,index:x}of g){const v=Ss(w,d,c);ht.setNode(t,v,[x])}}return ht.insertNode(t,p,[r+1]),y.forEach((f,g)=>{ht.insertNode(t,f,[r+2+g])}),ee.success(n==="zh"?`已复制 PPT 页面及 ${y.length} 个元素`:`Duplicated PPT page with ${y.length} elements`),p}function Th(t,e){ns(t),ta(t,e);const n=Fe.getRectangleByPoints(e.points),r=80,s=kt.getBoardContainer(t);let a=s.clientWidth,i=s.clientHeight;const l=document.querySelector(".project-drawer"),d=l?l.offsetWidth:0,c=document.querySelector(".ai-input-bar"),h=c?c.offsetHeight:0,u=a-d,p=i-h,y=u/(n.width+r*2),f=p/(n.height+r*2),g=Math.min(y,f,2),w=n.x+n.width/2,x=n.y+n.height/2,v=d+u/2,_=p/2,T=[w-v/g,x-_/g];dt.updateViewport(t,T,g)}let Sh=!1,No=null;function aP(t=100){return new Promise(e=>{"requestIdleCallback"in window?window.requestIdleCallback(()=>e(),{timeout:t}):setTimeout(e,0)})}function iP(){const[t,e]=m.useState(!1);return m.useEffect(()=>{let n=!0;const r=async()=>{await aP(50),console.warn("[useTaskStorage] Idle callback fired, starting init");try{const{migrateFromLegacyDB:s}=await Xe(async()=>{const{migrateFromLegacyDB:i}=await import("./ai-chat-BnWVpTEI.js").then(l=>l.sI);return{migrateFromLegacyDB:i}},__vite__mapDeps([0]),import.meta.url);await s();const a=await ei.getAllTasks();if(console.warn(`[useTaskStorage] Loaded ${a.length} tasks from IndexedDB`),a.length>0){xe.restoreTasks(a),console.warn(`[useTaskStorage] Restored ${a.length} tasks to memory`);const i=a.filter(y=>y.status==="processing");i.length>0&&(console.warn(`[useTaskStorage] Found ${i.length} interrupted processing tasks`),i.forEach(y=>{const f=js(y),g=y.type===He.VIDEO&&!!y.remoteId,w=y.type===He.AUDIO&&!!y.remoteId;if(console.warn(`[useTaskStorage] task=${y.id} type=${y.type} phase=${y.executionPhase||"unknown"} remoteId=${y.remoteId||"none"} → ${g||w||f?"KEEP":"MARK_FAILED"}`),!(g||w||f)){let x="任务被中断(页面刷新)",v="INTERRUPTED";y.type===He.VIDEO&&y.executionPhase===pn.SUBMITTING&&(x="任务在提交过程中被中断,可能已在后台执行",v="INTERRUPTED_DURING_SUBMISSION"),xe.updateTaskStatus(y.id,ve.FAILED,{startedAt:void 0,executionPhase:void 0,error:{code:v,message:x,details:{originalError:`Task interrupted by page refresh before completion (phase: ${y.executionPhase||"unknown"})`,timestamp:Date.now()}}})}}));const l=a.filter(y=>y.status==="failed"&&y.remoteId&&(y.type===He.VIDEO||y.type===He.AUDIO||js(y))),d=a.filter(y=>y.status==="failed"&&y.type===He.VIDEO).length,c=a.filter(y=>y.status==="failed"&&y.type===He.VIDEO&&y.remoteId).length,h=a.filter(y=>y.status==="failed"&&y.type===He.AUDIO).length,u=a.filter(y=>y.status==="failed"&&y.type===He.AUDIO&&y.remoteId).length;if(console.warn(`[useTaskStorage] Recovery check: ${i.length} processing, ${d} failed video (${c} with remoteId), ${h} failed audio (${u} with remoteId), ${l.length} recoverable`),l.length>0){const y=new Set(["INTERRUPTED","INTERRUPTED_DURING_SUBMISSION","RESUME_FAILED"]);l.forEach(f=>{var w;const g=((w=f.error)==null?void 0:w.code)||"";if(!y.has(g)){console.warn(`[useTaskStorage] Skip recovery for task ${f.id}: terminal failure (${g||"no error code"})`);return}console.warn(`[useTaskStorage] Recovering interrupted task ${f.id} (error: ${g}, remoteId: ${f.remoteId})`),xe.updateTaskStatus(f.id,ve.PROCESSING,{error:void 0,executionPhase:pn.POLLING})})}a.filter(y=>y.status==="processing"||y.status==="pending").length>0}}catch(s){console.error("[useTaskStorage] Failed to initialize storage:",s)}};return No||(No=(async()=>{Sh||(Sh=!0,await r())})()),No.then(()=>{n&&e(!0)}),()=>{n=!1}},[]),t}function Ih(t,e){return typeof t=="string"&&t?t:t&&typeof t=="object"&&typeof t.modelId=="string"&&t.modelId?t.modelId:e}function Ro(t,e){const n=xe.getTask(t);n&&tl(n)&&nl(e,n)}function oP(t,e,n,r){var a;const s=r.binding;(a=s==null?void 0:s.metadata)==null||a.image}function Yp(t,e){const n=t,r=n.params&&typeof n.params=="object"?n.params:void 0;for(const s of e){if(n[s]!==void 0)return n[s];if((r==null?void 0:r[s])!==void 0)return r[s]}}function vi(t,e){const n=Yp(t,e);return typeof n=="string"&&n.trim()?n.trim():void 0}function lP(t,e){const n=Yp(t,e);return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ya(t,e,n){const r=vi(t,e);return r&&n.includes(r)?r:void 0}function cP(t,e){const n=vi(t,["generationMode","generation_mode"]);return e.length>0||n==="image_edit"||n==="image_to_image"||!!vi(t,["maskImage","mask_image"])}function dP(t,e){const n=Ya(t,["generationMode","generation_mode"],["text_to_image","image_to_image","image_edit"]);return n||(e?"image_to_image":"text_to_image")}class uP{constructor(){this.abortControllers=new Map}async generate(e,n,r){const s=new AbortController;this.abortControllers.set(e,s);const a=Date.now(),i=r===He.IMAGE?"image":r===He.VIDEO?"video":"audio",l=n.model||(i==="image"?Bi:i==="video"?"gemini-video":zi),d=!!n.uploadedImage||!!n.uploadedImages||!!n.referenceImages;_e.trackModelCall({taskId:e,taskType:i,model:l,promptLength:n.prompt.length,hasUploadedImage:d,startTime:a,aspectRatio:n.size,duration:n.duration,resolution:n.width&&n.height?`${n.width}x${n.height}`:void 0,batchCount:n.count||1,hasReferenceImage:d});let c;try{const h=cs[r.toUpperCase()]??cs.IMAGE,u=new Promise((g,w)=>{c=setTimeout(()=>{s.abort(),w(new Error("TIMEOUT"))},h)}),p=r===He.IMAGE?this.generateImage(e,n,s.signal):r===He.VIDEO?this.generateVideo(e,n,s.signal):this.generateAudio(e,n,s.signal),y=await Promise.race([p,u]),f=Date.now()-a;return _e.trackModelSuccess({taskId:e,taskType:i,model:l,duration:f,resultSize:y.size}),y}catch(h){const u=Date.now()-a;throw console.error(`[GenerationAPI] Generation failed for task ${e}:`,h),h.message==="TIMEOUT"?(_e.trackModelFailure({taskId:e,taskType:i,model:l,duration:u,error:"TIMEOUT"}),new Error(`${r===He.IMAGE?"图片":r===He.VIDEO?"视频":"音频"}生成超时`)):h.name==="AbortError"?(_e.trackTaskCancellation({taskId:e,taskType:i,duration:u}),new Error("任务已取消")):(_e.trackModelFailure({taskId:e,taskType:i,model:l,duration:u,error:h.message||"UNKNOWN_ERROR"}),h)}finally{c&&clearTimeout(c),this.abortControllers.delete(e)}}convertAspectRatioToSize(e){return Sv(e)}deriveAspectRatio(e){const n=r=>{if(!r.includes("x"))return;const[s,a]=r.split("x"),i=Number(s),l=Number(a);if(!i||!l)return;const d=(h,u)=>u===0?h:d(u,h%u),c=d(i,l);return`${i/c}:${l/c}`};if(e.size){const r=n(e.size);if(r)return r}if(e.width&&e.height){const r=(a,i)=>i===0?a:r(i,a%i),s=r(e.width,e.height);return`${e.width/s}:${e.height/s}`}}async extractReferenceImages(e){var s;const n=[],r=e.uploadedImages;if(Array.isArray(r)){for(const a of r)if(a!=null&&a.url)if(a.type==="url"){const i=await Mn.getImageForAI(a.url);n.push(i.value)}else n.push(a.url)}return(s=e.uploadedImage)!=null&&s.url&&n.push(e.uploadedImage.url),Array.isArray(e.referenceImages)&&n.push(...e.referenceImages),n}async generateImage(e,n,r){try{const s=n.model,a=n.modelRef,i=await this.extractReferenceImages(n),l=cP(n,i),d={preferredRequestSchema:l?Iv:void 0},c=$i("image",s||Bi,a||null,d);if(!c||c.kind!=="image")throw new Error(`No image adapter for model: ${s}`);let h=n.size;h||(h=this.convertAspectRatioToSize(n.aspectRatio)),!h&&kv(s)&&(h=this.deriveAspectRatio(n)||"1:1");const u=Ui("image",a||s,d);oP(e,c,s,u);const p=await c.generateImage(u,{prompt:n.prompt,model:s,modelRef:a||null,size:h,generationMode:dP(n,l),referenceImages:i.length>0?i:void 0,maskImage:vi(n,["maskImage","mask_image"]),inputFidelity:Ya(n,["inputFidelity","input_fidelity"],["high","low"]),background:Ya(n,["background"],["transparent","opaque","auto"]),outputFormat:Ya(n,["outputFormat","output_format"],["png","jpeg","webp"]),outputCompression:lP(n,["outputCompression","output_compression"]),params:{resolution:n.resolution,quality:n.quality,response_format:n.response_format,...n.params,onProgress:y=>{xe.updateTaskProgress(e,y),xe.updateTaskStatus(e,ve.PROCESSING,{executionPhase:pn.POLLING})},onSubmitted:y=>{xe.updateTaskStatus(e,ve.PROCESSING,{remoteId:y,invocationRoute:Hi("image",a||s||Bi),executionPhase:pn.POLLING})}}});return{url:p.url,urls:p.urls,format:p.format||"png",size:0}}catch(s){console.error("[GenerationAPI] Image generation error:",s);const a=new Error(s.message||"图片生成失败");throw s.apiErrorBody&&(a.apiErrorBody=s.apiErrorBody),s.httpStatus&&(a.httpStatus=s.httpStatus),s.fullResponse&&(a.fullResponse=s.fullResponse),a}}async resumeAsyncImageGeneration(e,n,r){const s=cs.IMAGE,a=new AbortController;this.abortControllers.set(e,a);let i;const l=new Promise((d,c)=>{i=setTimeout(()=>{a.abort(),c(new Error("TIMEOUT"))},s)});try{Ro(e,"image");const d=await Promise.race([od.resumePolling(n,{interval:5e3,routeModel:r,signal:a.signal,onProgress:u=>{xe.updateTaskProgress(e,u)}}),l]),{url:c,format:h}=od.extractUrlAndFormat(d);return{url:c,format:h,size:0}}catch(d){const c=new Error(d.message||"图片生成失败");throw d.apiErrorBody&&(c.apiErrorBody=d.apiErrorBody),d.httpStatus&&(c.httpStatus=d.httpStatus),c}finally{i&&clearTimeout(i),this.abortControllers.get(e)===a&&this.abortControllers.delete(e)}}async generateVideo(e,n,r){try{const s=n.model,a=n.modelRef,i=$i("video",s||"veo3",a||null);if(!i||i.kind!=="video")throw new Error(`No video adapter for model: ${s}`);xe.updateTaskStatus(e,"processing",{executionPhase:pn.SUBMITTING});const l=await this.extractReferenceImages(n),d=n.duration??n.seconds,c=await i.generateVideo(Ui("video",a||s),{prompt:n.prompt,model:s,modelRef:a||null,size:n.size,duration:d!==void 0?Number(d):void 0,referenceImages:l.length>0?l:void 0,params:{...n.params,onProgress:h=>{xe.updateTaskProgress(e,h)},onSubmitted:h=>{xe.updateTaskStatus(e,"processing",{remoteId:h,invocationRoute:Hi("video",a||s),executionPhase:pn.POLLING})}}});return{url:c.url,format:c.format||"mp4",size:0,duration:c.duration||0}}catch(s){console.error("[GenerationAPI] Video generation error:",s);const a=new Error(s.message||"视频生成失败");throw s.apiErrorBody&&(a.apiErrorBody=s.apiErrorBody),s.httpStatus&&(a.httpStatus=s.httpStatus),a}}async generateAudio(e,n,r){try{const s=n.model,a=n.modelRef,i=$i("audio",s||zi,a||null);if(!i||i.kind!=="audio")throw new Error(`No audio adapter for model: ${s}`);xe.updateTaskStatus(e,ve.PROCESSING,{executionPhase:pn.SUBMITTING});const l=await i.generateAudio(Ui("audio",a||s),{prompt:n.prompt,model:s,modelRef:a||null,title:n.title,tags:n.tags,mv:n.mv,sunoAction:n.sunoAction,notifyHook:n.notifyHook,continueClipId:n.continueClipId,continueTaskId:n.continueTaskId,continueAt:n.continueAt,infillStartS:n.infillStartS,infillEndS:n.infillEndS,params:{...n.params,signal:r,onProgress:d=>{xe.updateTaskProgress(e,d),xe.updateTaskStatus(e,ve.PROCESSING,{executionPhase:pn.POLLING})},onSubmitted:d=>{xe.updateTaskStatus(e,ve.PROCESSING,{remoteId:d,invocationRoute:Hi("audio",a||s),executionPhase:pn.POLLING})}}});return{url:l.url,urls:l.urls,format:l.format||(l.resultKind==="lyrics"?"lyrics":"mp3"),size:0,resultKind:l.resultKind,duration:typeof l.duration=="number"?l.duration:void 0,previewImageUrl:l.imageUrl,title:l.title,lyricsText:l.lyricsText,lyricsTitle:l.lyricsTitle,lyricsTags:l.lyricsTags,providerTaskId:l.providerTaskId,primaryClipId:l.primaryClipId,clipIds:l.clipIds,clips:l.clips}}catch(s){console.error("[GenerationAPI] Audio generation error:",s);const a=new Error(s.message||"音频生成失败");throw s.apiErrorBody&&(a.apiErrorBody=s.apiErrorBody),s.httpStatus&&(a.httpStatus=s.httpStatus),a}}async resumeVideoGeneration(e,n,r){var i;const s=Date.now(),a=Ih(r,"gemini-video");_e.trackModelCall({taskId:e,taskType:"video",model:a,promptLength:0,hasUploadedImage:!1,startTime:s});try{Ro(e,"video");const l=cs.VIDEO,d=new Promise((y,f)=>{setTimeout(()=>{f(new Error("TIMEOUT"))},l)}),c=Cv.resumePolling(n,{interval:5e3,routeModel:r,params:(i=xe.getTask(e))==null?void 0:i.params.params,onProgress:(y,f)=>{xe.updateTaskProgress(e,y)}}),h=await Promise.race([c,d]),u=Date.now()-s;_e.trackModelSuccess({taskId:e,taskType:"video",model:a,duration:u,resultSize:0});const p=h.video_url||h.url;if(!p)throw new Error("API 未返回有效的视频 URL");return{url:p,format:"mp4",size:0,duration:parseInt(h.seconds)||8}}catch(l){const d=Date.now()-s;throw console.error(`[GenerationAPI] Resumed video generation failed for task ${e}:`,l),_e.trackModelFailure({taskId:e,taskType:"video",model:a,duration:d,error:l.message||"UNKNOWN_ERROR"}),l}}async resumeAudioGeneration(e,n,r){const s=Date.now(),a=Ih(r,zi);_e.trackModelCall({taskId:e,taskType:"audio",model:a,promptLength:0,hasUploadedImage:!1,startTime:s});try{Ro(e,"audio");const i=cs.AUDIO,l=new Promise((p,y)=>{setTimeout(()=>{y(new Error("TIMEOUT"))},i)}),d=Pv.resumePolling(n,{interval:5e3,routeModel:r,onProgress:p=>{xe.updateTaskProgress(e,p)}}),c=await Promise.race([d,l]),h=Ev(c),u=Date.now()-s;return _e.trackModelSuccess({taskId:e,taskType:"audio",model:a,duration:u,resultSize:0}),{url:h.url,urls:h.urls,format:h.format||(h.resultKind==="lyrics"?"lyrics":"mp3"),size:0,resultKind:h.resultKind,duration:typeof h.duration=="number"?h.duration:void 0,previewImageUrl:h.imageUrl,title:h.title,lyricsText:h.lyricsText,lyricsTitle:h.lyricsTitle,lyricsTags:h.lyricsTags,providerTaskId:h.providerTaskId,primaryClipId:h.primaryClipId,clipIds:h.clipIds,clips:h.clips}}catch(i){const l=Date.now()-s;throw console.error(`[GenerationAPI] Resumed audio generation failed for task ${e}:`,i),_e.trackModelFailure({taskId:e,taskType:"audio",model:a,duration:l,error:i.message||"UNKNOWN_ERROR"}),i}}cancelRequest(e){const n=this.abortControllers.get(e);n&&(n.abort(),this.abortControllers.delete(e))}hasActiveRequest(e){return this.abortControllers.has(e)}}const ps=new uP;function hP(t){var e;if(!t)return null;try{const n=JSON.parse(t);if((e=n.error)!=null&&e.message)return n.error.message;if(n.message)return n.message;if(n.error&&typeof n.error=="string")return n.error;if(n.detail)return n.detail;if(n.msg)return n.msg}catch{return t}return null}function ba(t){const e=(t==null?void 0:t.message)||String(t),n=(t==null?void 0:t.apiErrorBody)||"",r=t==null?void 0:t.httpStatus,s=jv(t),a=hP(n),i=`${e} ${n}`;return i.includes("insufficient_user_quota")||i.includes("预扣费额度失败")?"账户额度不足,请充值后重试":e.includes("PROHIBITED_CONTENT")||e.includes("has been blocked by Google Gemini")?e:e.includes("cannot")||e.includes("I cannot")||e.includes("I can't")?"AI 拒绝生成此内容":e.includes("unable to")||e.includes("not able to")?"AI 无法处理此请求":e.includes("signal")&&e.includes("timed out")?"请求超时,服务器响应过慢,正在自动重试":e.includes("TIMEOUT")||e.includes("超时")?"生成超时,请稍后重试":e.includes("network")||e.includes("Network")||e.includes("fetch")||e.includes("Failed to fetch")?"网络连接失败,请检查网络后重试":e.includes("rate limit")||e.includes("429")||r===429?"请求过于频繁,请稍后重试":s==="invalid"?"API Key 无效或已过期,请重新配置":s==="missing"?"缺少 API Key,请先在设置中配置":e.includes("401")||r===401?"接口返回 401,请检查鉴权方式、账号权限或服务端策略":(e.includes("403")||r===403)&&!n.includes("quota")?"API 访问被拒绝,请检查配置":e.includes("500")||r===500?a?`AI 服务器内部错误: ${a}`:"AI 服务器内部错误,正在自动重试":e.includes("502")||r===502?a?`AI 服务暂时不可用: ${a}`:"AI 服务暂时不可用(502),正在自动重试":e.includes("503")||r===503?a?`AI 服务繁忙: ${a}`:"AI 服务繁忙(503),正在自动重试":e.includes("504")||r===504?a?`AI 服务响应超时: ${a}`:"AI 服务响应超时(504),正在自动重试":a||e}const kh=Wf,fP=2e3;function mP(){const t=m.useRef(new Set),e=m.useRef([]),n=m.useRef(null);m.useEffect(()=>{let r=!0;const s=()=>{if(r)for(;e.current.length>0&&t.current.size<kh;){const g=e.current.shift();g&&!t.current.has(g.id)&&c(g)}},a=g=>{t.current.delete(g),s()},i=async g=>{const w=g.id,x=g.remoteId;if(!t.current.has(w)){t.current.add(w);try{tl(g)&&nl("audio",g);const v=await ps.resumeAudioGeneration(w,x,ld(g));if(!r)return;xe.updateTaskStatus(w,ve.COMPLETED,{result:v})}catch(v){if(!r)return;const _=v.httpStatus?`HTTP_${v.httpStatus}`:v.name||"ERROR",T=ba(v),b=v.fullResponse||v.apiErrorBody||v.message||String(v);xe.updateTaskStatus(w,ve.FAILED,{error:{code:_,message:T,details:{originalError:b,timestamp:Date.now()}}})}finally{a(w)}}},l=async g=>{const w=g.id,x=g.remoteId;if(!t.current.has(w)){t.current.add(w);try{tl(g)&&nl("image",g);const v=await ps.resumeAsyncImageGeneration(w,x,ld(g));if(!r)return;if(xe.updateTaskStatus(w,ve.COMPLETED,{result:v}),v.url)try{await Mn.registerImageMetadata(v.url,{taskId:g.id,model:g.params.model,prompt:g.params.prompt,params:g.params})}catch(_){console.error(`[TaskExecutor] Failed to register metadata for resumed async image task ${w}:`,_)}}catch(v){if(!r)return;const _=v.httpStatus?`HTTP_${v.httpStatus}`:v.name||"ERROR",T=ba(v),b=v.fullResponse||v.apiErrorBody||v.message||String(v);xe.updateTaskStatus(w,ve.FAILED,{error:{code:_,message:T,details:{originalError:b,timestamp:Date.now()}}})}finally{a(w)}}},d=async g=>{const w=g.id;if(!t.current.has(w)){t.current.add(w);try{xe.updateTaskStatus(w,ve.PROCESSING);const{sourceVideoTaskId:x,characterTimestamps:v,model:_,prompt:T}=g.params;if(!x)throw new Error("缺少源视频任务ID");const b=await Kk.createCharacterWithPolling({videoTaskId:x,characterTimestamps:v,localTaskId:g.params.sourceLocalTaskId,sourcePrompt:T,sourceModel:_},{onStatusChange:I=>{}});if(!r)return;await Qs.saveCharacter({id:b.characterId,username:b.username,profilePictureUrl:b.profile_picture_url,permalink:b.permalink,sourceTaskId:g.params.sourceLocalTaskId||"",sourceVideoId:x,sourcePrompt:T,characterTimestamps:v,status:"completed",createdAt:g.createdAt,completedAt:Date.now()}),xe.updateTaskStatus(w,ve.COMPLETED,{result:{url:b.profile_picture_url,format:"character",size:0,characterUsername:b.username,characterProfileUrl:b.profile_picture_url,characterPermalink:b.permalink},remoteId:b.characterId})}catch(x){if(!r||(console.error(`[TaskExecutor] Character task ${w} failed:`,x),!xe.getTask(w)))return;const _=x.httpStatus?`HTTP_${x.httpStatus}`:x.name||"ERROR",T=ba(x),I={originalError:x.fullResponse||x.apiErrorBody||x.message||String(x),timestamp:Date.now()};xe.updateTaskStatus(w,ve.FAILED,{error:{code:_,message:T,details:I}})}finally{a(w)}}},c=async g=>{const w=g.id;if(g.type===He.CHARACTER)return d(g);if(g.status===ve.PROCESSING&&js(g))return l(g);if(!(g.type===He.VIDEO&&g.remoteId&&g.status===ve.PROCESSING)){if(g.type===He.AUDIO&&g.remoteId&&g.status===ve.PROCESSING)return i(g);if(!t.current.has(w)){t.current.add(w);try{xe.updateTaskStatus(w,ve.PROCESSING);const x=await ps.generate(w,g.params,g.type);if(!r)return;if(xe.updateTaskStatus(w,ve.COMPLETED,{result:x}),x.url)try{await Mn.registerImageMetadata(x.url,{taskId:g.id,model:g.params.model,prompt:g.params.prompt,params:g.params})}catch(v){console.error(`[TaskExecutor] Failed to register metadata for task ${w}:`,v)}}catch(x){if(!r||(console.error(`[TaskExecutor] Task ${w} failed:`,x),!xe.getTask(w)))return;const _=x.httpStatus?`HTTP_${x.httpStatus}`:x.name||"ERROR",T=ba(x),I={originalError:x.fullResponse||x.apiErrorBody||x.message||String(x),timestamp:Date.now()};xe.updateTaskStatus(w,ve.FAILED,{error:{code:_,message:T,details:I}})}finally{a(w)}}}},h=g=>{t.current.has(g.id)||e.current.some(w=>w.id===g.id)||(t.current.size<kh?c(g):e.current.push(g))},u=()=>{if(!r)return;const g=xe.getAllTasks(),w=g.filter(_=>_.status===ve.PENDING),x=g.filter(_=>_.status===ve.PROCESSING&&js(_)),v=g.filter(_=>_.type===He.AUDIO&&_.remoteId&&_.status===ve.PROCESSING);console.warn(`[TaskExecutor] processPendingTasks: ${g.length} total, ${w.length} pending, ${x.length} resumable-image, ${v.length} resumable-audio, ${t.current.size} executing`),w.forEach(_=>{h(_)}),x.forEach(_=>{h(_)}),v.forEach(_=>{h(_)})},p=()=>{if(!r)return;xe.getAllTasks().filter(x=>x.status===ve.PROCESSING).forEach(x=>{if(Av(x)){console.warn(`[TaskExecutor] Task ${x.id} timed out`),ps.cancelRequest(x.id);const v={originalError:`Task ${x.id} timed out after processing`,timestamp:Date.now()};xe.updateTaskStatus(x.id,ve.FAILED,{error:{code:"TIMEOUT",message:"任务执行超时",details:v}})}})},y=xe.observeTaskUpdates().subscribe(g=>{if(r&&(g.type==="taskCreated"||g.type==="taskUpdated")){const w=g.task;(w.status===ve.PENDING||!t.current.has(w.id)&&w.remoteId&&w.status===ve.PROCESSING&&js(w)||!t.current.has(w.id)&&w.remoteId&&w.type===He.AUDIO&&w.status===ve.PROCESSING)&&h(w)}}),f=setTimeout(u,fP);return n.current=setInterval(p,1e4),()=>{r=!1,y.unsubscribe(),clearTimeout(f),e.current=[],n.current&&clearInterval(n.current),t.current.forEach(g=>{ps.cancelRequest(g)}),t.current.clear()}},[])}function pP(t){return!!(t.gridImageRows&&t.gridImageCols)}function gP(t){return!!(t.isInspirationBoard&&t.inspirationBoardLayoutStyle==="inspiration-board")}function yP(t=800){const e=on();if(e)return Vf(e)}async function vP(t,e,n,r={}){const s=on();if(!s)return{success:!1,count:0,error:"Board not available"};Ve.registerTask(t,n.batchId),Ve.startPostProcessing(t,"split_and_insert");try{const a=await Ov(s,e,{scrollToResult:r.scrollToResult??!0}),i=r.insertionPoint||yP();return a.success?(Ve.completePostProcessing(t,a.count,i),{success:!0,count:a.count}):(console.warn(`[MediaResultHandler] Split failed: ${a.error}, falling back to direct insert`),(await An({items:[{type:"image",content:e}],startPoint:i})).success?(Ve.completePostProcessing(t,1,i),{success:!0,count:1}):(Ve.failPostProcessing(t,a.error||"Split and insert failed"),{success:!1,count:0,error:a.error}))}catch(a){const i=String(a);return console.error("[MediaResultHandler] Split and insert error:",a),Ve.failPostProcessing(t,i),{success:!1,count:0,error:i}}}function Ll(t){return Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number"}function wP(t,e){return!t||!e?t===e:t[0]===e[0]&&t[1]===e[1]}function Zp(t){var e;return Ll((e=t==null?void 0:t.points)==null?void 0:e[0])?t.points[0]:void 0}function xP(t){const{anchor:e,workzoneExpectedInsertPosition:n}=t,r=Zp(e);if(r)return r;if(Ll(n))return n;if(Ll(e==null?void 0:e.expectedInsertPosition))return e.expectedInsertPosition}function bP(t,e){if(typeof e=="string")return xt.getAnchorByTaskId(t,e);const n=xt.getAnchorByTaskId(t,e.id);if(n)return n;const r=Ci(e),s=Pi(e),a=Ei(e);if(s&&typeof a=="number"){const i=xt.getAnchorByBatchSlot(t,{workflowId:r,batchId:s,batchIndex:a});if(i)return i;const l=xt.getAllAnchors(t).find(d=>d.anchorType!=="stack"&&d.batchId===s&&d.batchIndex===a&&(!r||d.workflowId===r));if(l)return l}if(r){const i=xt.getAnchorsByWorkflowId(t,r);return i.find(d=>!Ac(d))||i[0]||null}return null}const _P={enabled:!0,insertPrompt:!1,groupSimilarTasks:!0,groupTimeWindow:5e3},TP=500,Vn=new Set;function wi(t){var r;const e=on();if(!e)return null;const n=fr.getAllWorkZones(e);for(const s of n)if((r=s.workflow.steps)==null?void 0:r.some(i=>{const l=i.result;return(l==null?void 0:l.taskId)===t}))return s;return null}function Za(t){const e=on();return e?bP(e,t):null}function SP(t,e){const n=on();if(!n)return;const r=t.taskIds.includes(e.id)?t.taskIds:[...t.taskIds,e.id];xt.updateAnchor(n,t.id,{taskIds:r,primaryTaskId:t.primaryTaskId||e.id})}function IP(t){Vn.add(t)}function Kt(t){Vn.delete(t)}function _a(t){Vn.add(t),xs().markAsInserted(t,"auto_insert")}function Lo(t,e,n,r={}){if(!e||!n)return;const s=on(),a=r.targetFrameId||t.params.targetFrameId;!s||!a||Da(s,a,e,n,{replaceElementId:r.replaceElementId||t.params.pptReplaceElementId,prompt:r.prompt||t.params.prompt,slidePrompt:typeof t.params.pptSlidePrompt=="string"?t.params.pptSlidePrompt:void 0,historyItems:r.historyItems,imageCreatedAt:r.imageCreatedAt||Fl(t)})}function Fl(t){const e=t.completedAt||t.updatedAt||t.createdAt;return Number.isFinite(e)&&e>0?e:Date.now()}function kP(t){var e,n,r;return(n=(e=t.result)==null?void 0:e.urls)!=null&&n.length?t.result.urls.filter(s=>!!s):(r=t.result)!=null&&r.url?[t.result.url]:[]}function Ch(t){return typeof t.params.batchIndex=="number"?t.params.batchIndex:Number.MAX_SAFE_INTEGER}function Ph(t,e,n){return t.map(r=>({imageUrl:r,...e?{prompt:e}:{},...n?{createdAt:n}:{}}))}function Bl(t){return Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number"}function Eh(t){return typeof t=="object"&&t!==null&&typeof t.width=="number"&&typeof t.height=="number"}function Ah(t,e){const n=t.result;return typeof(n==null?void 0:n.width)=="number"&&typeof(n==null?void 0:n.height)=="number"&&n.width>0&&n.height>0?{width:n.width,height:n.height}:e||Ys(t.params.size)}function jh(t,e){if(!t||t.anchorType!=="stack")return e}function nr(t,e,n){if(!t||!e)return;const r={};n.position&&(r.expectedInsertPosition=n.position),n.transitionMode&&n.transitionMode!==e.transitionMode&&(r.transitionMode=n.transitionMode),Object.keys(r).length>0&&xt.updateAnchor(t,e.id,r),(n.position||n.size)&&xt.updateGeometry(t,e.id,{position:n.position,size:n.size})}function rr(t,e){const n=t==null?void 0:t.data;return Bl(n==null?void 0:n.firstElementPosition)?n.firstElementPosition:e}function gs(t,e,n,r){const s=t==null?void 0:t.data,a=(s==null?void 0:s.items.find(d=>r==null?void 0:r.includes(d.type)))??(s==null?void 0:s.items[0]),i=Bl(a==null?void 0:a.point)?a.point:Bl(s==null?void 0:s.firstElementPosition)?s.firstElementPosition:e,l=Eh(a==null?void 0:a.size)?a.size:Eh(s==null?void 0:s.firstElementSize)?s.firstElementSize:n;return{elementId:(a==null?void 0:a.elementId)??(s==null?void 0:s.firstElementId),position:i,size:l}}function CP(t,e){var d;const n=wi(e.id),r=Za(e);let s=xP({anchor:r,workzoneExpectedInsertPosition:n==null?void 0:n.expectedInsertPosition}),a,i;const l=Zp(r);return r&&l&&!wP(r.expectedInsertPosition,l)&&xt.updateAnchor(t,r.id,{expectedInsertPosition:l}),n!=null&&n.targetFrameId&&(n!=null&&n.targetFrameDimensions)&&(a=n.targetFrameId,i=n.targetFrameDimensions),!a&&(r!=null&&r.targetFrameId)&&(r!=null&&r.targetFrameDimensions)&&(a=r.targetFrameId,i=r.targetFrameDimensions),!a&&((d=e.params)!=null&&d.targetFrameId)&&(a=e.params.targetFrameId,i=e.params.targetFrameDimensions),r&&(SP(r,e),xt.updateAnchor(t,r.id,yi("inserting"))),s||(s=Vf(t)),{insertionPoint:s,targetFrameId:a,targetFrameDimensions:i,imageAnchor:r}}function Fo(t,e,n,r){var l;const s=on();if(!s)return;const a=wi(t);if(!a)return;const i=(l=a.workflow.steps)==null?void 0:l.map(d=>{const c=d.result;return(c==null?void 0:c.taskId)===t?(typeof d.result=="object"&&d.result!==null&&d.result,{...d,status:e,result:d.result,error:r}):d});i&&fr.updateWorkflow(s,a.id,{steps:i})}function PP(t={}){const e={..._P,...t},n=m.useRef(new Map),r=m.useRef(null);m.useEffect(()=>{if(!e.enabled)return;let s=!0;function a(g=e.groupTimeWindow){r.current&&clearTimeout(r.current),r.current=setTimeout(()=>{r.current=null,i().catch(w=>{console.error("[AutoInsert] Failed to flush pending inserts:",w)})},g)}async function i(){var v,_,T,b,I,A,k,U,D,X,L,O,G,C,P,j,N,B,K,fe,ae,te;const g=n.current;if(g.size===0)return;const w=on();if(!w||!s){!w&&s&&a(TP);return}const x=new Map(g);g.clear();for(const[Se,Ee]of x){if(!s){for(const{task:R}of Ee)Kt(R.id);continue}const Te=(v=Ee[0])==null?void 0:v.task;if(!Te)continue;const{insertionPoint:ke,targetFrameId:ne,targetFrameDimensions:M,imageAnchor:q}=CP(w,Te);if(!ke){for(const{task:R}of Ee)Kt(R.id),Ve.failPostProcessing(R.id,"No insertion point available");continue}for(const{task:R}of Ee){const J=R.params.batchId;Ve.registerTask(R.id,J),Ve.startPostProcessing(R.id,Ee.length===1?"direct_insert":"group_insert")}try{if(Ee.length===1){const{task:R}=Ee[0],J=Ga(R),Ce=(_=R.result)==null?void 0:_.url,re=typeof Ce=="string"&&Ce.length>0,ze=Array.isArray((T=R.result)==null?void 0:T.urls)&&R.result.urls.length>0;if(!re&&!ze&&!J){Kt(R.id),Ve.failPostProcessing(R.id,"No result URL");continue}const V=J?"text":R.type===He.VIDEO?"video":R.type===He.AUDIO?"audio":"image",z=V==="audio"?{width:dd,height:cd}:V==="text"?void 0:Ys(R.params.size),F=V==="audio"?{title:((b=R.result)==null?void 0:b.title)||R.params.title,duration:typeof((k=(A=(I=R.result)==null?void 0:I.clips)==null?void 0:A[0])==null?void 0:k.duration)=="number"?R.result.clips[0].duration||void 0:(U=R.result)==null?void 0:U.duration,previewImageUrl:(D=R.result)==null?void 0:D.previewImageUrl,tags:typeof R.params.tags=="string"?R.params.tags:void 0,mv:typeof R.params.mv=="string"?R.params.mv:void 0,prompt:R.params.prompt,providerTaskId:((X=R.result)==null?void 0:X.providerTaskId)||R.remoteId,clipId:((L=R.result)==null?void 0:L.primaryClipId)||((C=(G=(O=R.result)==null?void 0:O.clips)==null?void 0:G[0])==null?void 0:C.clipId)||((N=(j=(P=R.result)==null?void 0:P.clips)==null?void 0:j[0])==null?void 0:N.id)||((K=(B=R.result)==null?void 0:B.clipIds)==null?void 0:K[0]),clipIds:(fe=R.result)==null?void 0:fe.clipIds}:void 0,pe=V==="audio"?F:void 0,ce=V==="text"?[ko(R)]:V==="audio"?Ao(R.result):(te=(ae=R.result)==null?void 0:ae.urls)!=null&&te.length?R.result.urls:[Ce],Z=ne||R.params.targetFrameId,ue=M||R.params.targetFrameDimensions,ye=V==="image"?q??Za(R):null,ie=V==="image"?Ah(R,z):void 0;let Ae=ke,Q,Pe=ie,$e=!1;if(R.params.pptSlideImage&&Z&&ue&&w&&V==="image"&&ce.length>0){const de=ce[ce.length-1],Ge=await zr(w,de,V,Z,ue,void 0);Ge&&(Ae=Ge.point,Q=Ge.elementId,Pe=Ge.size,nr(w,ye,{position:Ge.point,size:Ge.size,transitionMode:(ye==null?void 0:ye.anchorType)==="ghost"?"morph":"hold"}),Lo(R,Q,de,{targetFrameId:Z,replaceElementId:R.params.pptReplaceElementId,historyItems:Ph(ce.slice(0,-1),R.params.prompt,Fl(R))}),$e=!0)}else if(Z&&ue&&w&&V!=="audio"&&V!=="text"&&ce.length===1){const de=await zr(w,ce[0],V,Z,ue,R.params.pptSlideImage&&V==="image"?void 0:z);de&&(Ae=de.point,Q=de.elementId,Pe=de.size,nr(w,ye,{position:de.point,size:de.size,transitionMode:(ye==null?void 0:ye.anchorType)==="ghost"?"morph":"hold"}))}else if(e.insertPrompt&&V!=="text"){const de=await Nu(R.params.prompt,ce.map((it,Ye)=>{var Ue,oe,ft,je,ge,De,We,Re,gt,ut,lt,Rt,Ut,Jt,Lt,Qt,jt,en,Ot,$;return{type:V,url:it,dimensions:z,metadata:V==="audio"?{...F,title:((ft=(oe=(Ue=R.result)==null?void 0:Ue.clips)==null?void 0:oe[Ye])==null?void 0:ft.title)||(ce.length>1?`${(F==null?void 0:F.title)||R.params.title||"Audio"} ${Ye+1}`:F==null?void 0:F.title),previewImageUrl:((De=(ge=(je=R.result)==null?void 0:je.clips)==null?void 0:ge[Ye])==null?void 0:De.imageLargeUrl)||((gt=(Re=(We=R.result)==null?void 0:We.clips)==null?void 0:Re[Ye])==null?void 0:gt.imageUrl)||(F==null?void 0:F.previewImageUrl),duration:typeof((Rt=(lt=(ut=R.result)==null?void 0:ut.clips)==null?void 0:lt[Ye])==null?void 0:Rt.duration)=="number"?R.result.clips[Ye].duration||void 0:F==null?void 0:F.duration,clipId:((Lt=(Jt=(Ut=R.result)==null?void 0:Ut.clips)==null?void 0:Jt[Ye])==null?void 0:Lt.clipId)||((en=(jt=(Qt=R.result)==null?void 0:Qt.clips)==null?void 0:jt[Ye])==null?void 0:en.id)||(($=(Ot=R.result)==null?void 0:Ot.clipIds)==null?void 0:$[Ye])||(F==null?void 0:F.clipId)}:void 0}}),ke),Ge=gs(de,ke,ie,["image"]);Ae=Ge.position,Q=Ge.elementId,Pe=Ge.size}else if(V==="image"&&ce.length>1){ye&&nr(w,ye,{position:ke,size:jh(ye,ie),transitionMode:"morph"});const de=await Du(ce,ke,z),Ge=gs(de,ke,ie,["image"]);Ae=Ge.position,Q=Ge.elementId,Pe=Ge.size}else if(V==="text"){const de=Ml(R.result,R.params.title||R.params.prompt)||(R.params.prompt||"").slice(0,20)||void 0,Ge=await An({items:[{type:"text",content:ce[0],label:de}],startPoint:ke});Ae=rr(Ge,ke)}else if(V==="audio"&&ce.length>1){const de=`audio-group-${R.id}`,Ge=await An({items:ce.map((it,Ye)=>{var Ue,oe,ft,je,ge,De,We,Re,gt,ut,lt,Rt,Ut,Jt,Lt,Qt,jt,en,Ot,$;return{type:"audio",content:it,groupId:de,dimensions:z,metadata:{...F,title:((ft=(oe=(Ue=R.result)==null?void 0:Ue.clips)==null?void 0:oe[Ye])==null?void 0:ft.title)||(ce.length>1?`${(F==null?void 0:F.title)||R.params.title||"Audio"} ${Ye+1}`:F==null?void 0:F.title),previewImageUrl:((De=(ge=(je=R.result)==null?void 0:je.clips)==null?void 0:ge[Ye])==null?void 0:De.imageLargeUrl)||((gt=(Re=(We=R.result)==null?void 0:We.clips)==null?void 0:Re[Ye])==null?void 0:gt.imageUrl)||(F==null?void 0:F.previewImageUrl),duration:typeof((Rt=(lt=(ut=R.result)==null?void 0:ut.clips)==null?void 0:lt[Ye])==null?void 0:Rt.duration)=="number"?R.result.clips[Ye].duration||void 0:F==null?void 0:F.duration,clipId:((Lt=(Jt=(Ut=R.result)==null?void 0:Ut.clips)==null?void 0:Jt[Ye])==null?void 0:Lt.clipId)||((en=(jt=(Qt=R.result)==null?void 0:Qt.clips)==null?void 0:jt[Ye])==null?void 0:en.id)||(($=(Ot=R.result)==null?void 0:Ot.clipIds)==null?void 0:$[Ye])||(F==null?void 0:F.clipId)}}}),startPoint:ke});Ae=rr(Ge,ke)}else{V==="image"&&ye&&!e.insertPrompt&&ie&&nr(w,ye,{position:ke,size:ie,transitionMode:ye.anchorType==="ghost"?"morph":"hold"});const de=await Mu(V,ce[0],ke,z,pe);if(V==="image"){const Ge=gs(de,ke,ie,["image"]);Ae=Ge.position,Q=Ge.elementId,Pe=Ge.size}else Ae=rr(de,ke)}V==="image"&&ye&&Pe&&nr(w,ye,{position:Ae,size:Pe,transitionMode:ye.anchorType==="ghost"?"morph":"hold"}),V==="image"&&!$e&&Lo(R,Q,ce[0],{targetFrameId:Z,replaceElementId:R.params.pptReplaceElementId}),Ve.completePostProcessing(R.id,ce.length,Ae,V==="image"?Q:void 0,V==="image"?Pe:void 0),_a(R.id)}else{const R=Ga(Te),J=R?Ee.map(({task:Z})=>ko(Z)):Ee.flatMap(({task:Z})=>{var ue,ye,ie;return Te.type===He.AUDIO?Ao(Z.result):(ye=(ue=Z.result)==null?void 0:ue.urls)!=null&&ye.length?Z.result.urls:[(ie=Z.result)==null?void 0:ie.url]}).filter(Z=>!!Z),Ce=Te.type===He.AUDIO?Ee.flatMap(({task:Z})=>{var ie,Ae,Q,Pe,$e,de,Ge,it;const ue=Ao(Z.result),ye={title:((ie=Z.result)==null?void 0:ie.title)||Z.params.title,duration:typeof((Pe=(Q=(Ae=Z.result)==null?void 0:Ae.clips)==null?void 0:Q[0])==null?void 0:Pe.duration)=="number"?Z.result.clips[0].duration||void 0:($e=Z.result)==null?void 0:$e.duration,previewImageUrl:(de=Z.result)==null?void 0:de.previewImageUrl,tags:typeof Z.params.tags=="string"?Z.params.tags:void 0,mv:typeof Z.params.mv=="string"?Z.params.mv:void 0,prompt:Z.params.prompt,providerTaskId:((Ge=Z.result)==null?void 0:Ge.providerTaskId)||Z.remoteId,clipIds:(it=Z.result)==null?void 0:it.clipIds};return ue.map((Ye,Ue)=>{var oe,ft,je,ge,De,We,Re,gt,ut,lt,Rt,Ut,Jt,Lt,Qt,jt,en,Ot,$,Oe;return{url:Ye,metadata:{...ye,title:((je=(ft=(oe=Z.result)==null?void 0:oe.clips)==null?void 0:ft[Ue])==null?void 0:je.title)||(ue.length>1?`${ye.title||Z.params.title||"Audio"} ${Ue+1}`:ye.title),previewImageUrl:((We=(De=(ge=Z.result)==null?void 0:ge.clips)==null?void 0:De[Ue])==null?void 0:We.imageLargeUrl)||((ut=(gt=(Re=Z.result)==null?void 0:Re.clips)==null?void 0:gt[Ue])==null?void 0:ut.imageUrl)||ye.previewImageUrl,duration:typeof((Ut=(Rt=(lt=Z.result)==null?void 0:lt.clips)==null?void 0:Rt[Ue])==null?void 0:Ut.duration)=="number"?Z.result.clips[Ue].duration||void 0:ye.duration,clipId:((Qt=(Lt=(Jt=Z.result)==null?void 0:Jt.clips)==null?void 0:Lt[Ue])==null?void 0:Qt.clipId)||((Ot=(en=(jt=Z.result)==null?void 0:jt.clips)==null?void 0:en[Ue])==null?void 0:Ot.id)||((Oe=($=Z.result)==null?void 0:$.clipIds)==null?void 0:Oe[Ue])}}})}):[];if(J.length===0){for(const{task:Z}of Ee)Kt(Z.id),Ve.failPostProcessing(Z.id,"No result URL");continue}const re=R?"text":Te.type===He.VIDEO?"video":Te.type===He.AUDIO?"audio":"image",ze=re==="audio"?{width:dd,height:cd}:re==="text"?void 0:Ys(Te.params.size),V=re==="image"?q??Za(Te):null,z=re==="image"?Ah(Te,ze):void 0;let F=ke,pe,ce=z;if(Te.params.pptSlideImage&&ne&&M&&re==="image"){const ue=Ee.map((Ae,Q)=>({insert:Ae,sourceIndex:Q})).sort((Ae,Q)=>Ch(Ae.insert.task)-Ch(Q.insert.task)||Ae.sourceIndex-Q.sourceIndex).map(({insert:Ae})=>Ae).flatMap(({task:Ae})=>Ph(kP(Ae),Ae.params.prompt,Fl(Ae))),ye=ue[ue.length-1];if(!ye){for(const{task:Ae}of Ee)Kt(Ae.id),Ve.failPostProcessing(Ae.id,"No result URL");continue}const ie=await zr(w,ye.imageUrl,re,ne,M,void 0);ie&&(F=ie.point,pe=ie.elementId,ce=ie.size,Lo(Te,pe,ye.imageUrl,{targetFrameId:ne,replaceElementId:Te.params.pptReplaceElementId,prompt:ye.prompt,imageCreatedAt:ye.createdAt,historyItems:ue.slice(0,-1)}))}else if(e.insertPrompt&&re!=="text"){const Z=await Nu(Te.params.prompt,J.map((ue,ye)=>{var ie;return{type:re,url:ue,dimensions:ze,metadata:re==="audio"?{...(ie=Ce[ye])==null?void 0:ie.metadata}:void 0}}),ke);if(re==="image"){const ue=gs(Z,ke,z,["image"]);F=ue.position,pe=ue.elementId,ce=ue.size}else F=rr(Z,ke)}else if(re==="image"){V&&nr(w,V,{position:ke,size:jh(V,z),transitionMode:"morph"});const Z=await Du(J,ke,ze),ue=gs(Z,ke,z,["image"]);F=ue.position,pe=ue.elementId,ce=ue.size}else if(re==="text"){const Z=await An({items:Ee.map(({task:ue})=>({type:"text",content:ko(ue),label:Ml(ue.result,ue.params.title||ue.params.prompt)||(ue.params.prompt||"").slice(0,20)||void 0,groupId:`lyrics-group-${Te.id}`})),startPoint:ke});F=rr(Z,ke)}else if(re==="audio"){const Z=`audio-group-${Te.id}`,ue=await An({items:Ce.map(ye=>({type:"audio",content:ye.url,groupId:Z,dimensions:ze,metadata:ye.metadata})),startPoint:ke});F=rr(ue,ke)}else for(const Z of J){const ue=await Mu("video",Z,ke,ze);F=rr(ue,ke)}re==="image"&&V&&ce&&nr(w,V,{position:F,size:ce,transitionMode:"morph"});for(const{task:Z}of Ee)Ve.completePostProcessing(Z.id,1,F,re==="image"?pe:void 0,re==="image"?ce:void 0),_a(Z.id)}}catch(R){console.error(`[AutoInsert] Failed to insert for prompt ${Se}:`,R);for(const{task:J}of Ee)Kt(J.id),Ve.failPostProcessing(J.id,String(R))}}}const l=async g=>{var v;const w=(v=g.result)==null?void 0:v.url;if(!w){console.error("[AutoInsert] Split task has no result URL"),Kt(g.id),Ve.failPostProcessing(g.id,"No result URL"),Fo(g.id,"failed",void 0,"No result URL");return}const x=g.params;try{const _=await vP(g.id,w,x,{scrollToResult:!0});if(_.success){_a(g.id);return}Kt(g.id),Fo(g.id,"failed",void 0,_.error||"拆分失败")}catch(_){const T=String(_);Kt(g.id),Ve.failPostProcessing(g.id,T),Fo(g.id,"failed",void 0,T)}},d=g=>{var A,k,U,D,X,L;const w=wi(g.id),x=Za(g);if(!(g.params.autoInsertToCanvas||!!w||!!x)||Vn.has(g.id))return;if(g.insertedToCanvas){Vn.add(g.id);return}const _=(A=Ve.getPostProcessingStatus(g.id))==null?void 0:A.status;if(_==="completed"){Vn.add(g.id);return}if(_==="processing"||g.type!==He.IMAGE&&g.type!==He.VIDEO&&g.type!==He.AUDIO&&g.type!==He.CHAT||!((k=g.result)!=null&&k.url)&&!((D=(U=g.result)==null?void 0:U.urls)!=null&&D.length)&&!Ga(g)&&!((X=g.result)!=null&&X.chatResponse))return;IP(g.id);const T=g.params;if(g.type===He.CHAT){const O=(g.params.prompt||"").slice(0,20)||void 0;An({items:[{type:"text",content:((L=g.result)==null?void 0:L.chatResponse)||"",label:O}]}).then(()=>{Ve.completePostProcessing(g.id,1),_a(g.id)}).catch(G=>{Kt(g.id),Ve.failPostProcessing(g.id,String(G))});return}if(gP(T)){l(g);return}if(pP(T)){l(g);return}const b=pk(g,x),I=n.current.get(b)||[];I.push({task:g,completedAt:Date.now()}),n.current.set(b,I),e.groupSimilarTasks?a():i().catch(O=>{console.error("[AutoInsert] Failed to flush pending inserts:",O)})},c=()=>{xs().getAllTasks().forEach(g=>{g.status===ve.COMPLETED&&d(g)})},h=g=>{var w,x;if((w=g.params)!=null&&w.pptSlideImage&&((x=g.params)!=null&&x.targetFrameId)){const v=on();v&&qt(v,g.params.targetFrameId,{slideImageStatus:"failed",imageStatus:"failed"})}},p=xs().observeTaskUpdates().subscribe(g=>{s&&(g.type==="taskUpdated"||g.type==="taskCompleted"?g.task.status===ve.COMPLETED?d(g.task):(g.task.status===ve.FAILED||g.task.status===ve.CANCELLED)&&h(g.task):g.type==="taskFailed"?h(g.task):g.type==="taskSynced"?g.task.status===ve.COMPLETED&&d(g.task):g.type==="taskCreated"&&c())});c();const y=Ve.observeCompletionEvents().subscribe(g=>{var w,x;if(g.type==="postProcessingCompleted"||g.type==="postProcessingFailed"){const v=on();if(!v)return;const _=wi(g.taskId);_&&((w=_.workflow.steps)!=null&&w.every(b=>b.status==="completed"||b.status==="failed"||b.status==="skipped"))&&(x=_.workflow.steps)!=null&&x.every(I=>{const A=I.result;return A!=null&&A.taskId?Ve.isPostProcessingCompleted(A.taskId):!0})&&setTimeout(()=>{fr.removeWorkZone(v,_.id)},1500)}}),f=g=>{var A,k,U;const w=g,x=(A=w.detail)==null?void 0:A.taskId,v=(k=w.detail)==null?void 0:k.anchorId,_=(D,X)=>{if(!v)return;const L=on();L&&xt.updateAnchor(L,v,yi(D,X))};if(!x){_("failed",{error:"任务未绑定,无法重试"});return}const T=xs().getTask(x);if(!T){_("failed",{error:"任务已丢失,无法重试"});return}const b=(U=Ve.getPostProcessingStatus(x))==null?void 0:U.status;if(T.status===ve.COMPLETED){if(T.insertedToCanvas||b==="completed"){Vn.add(x),_("completed");return}if(Vn.has(x)||b==="processing")return}if(T.status===ve.PENDING||T.status===ve.PROCESSING){_("accepted",{subtitle:"任务仍在执行,请稍候"});return}const I=T.status===ve.COMPLETED&&b==="failed";if(T.status===ve.FAILED||T.status===ve.CANCELLED||I){_("retrying"),Kt(x),Ve.clearTask(x),xs().retryTask(x,I?{allowCompleted:!0}:void 0);return}T.status===ve.COMPLETED&&(Kt(x),Ve.clearTask(x),d(T))};return window.addEventListener(gi,f),()=>{s=!1,p.unsubscribe(),y.unsubscribe(),window.removeEventListener(gi,f),r.current&&(clearTimeout(r.current),r.current=null);const g=n.current;for(const[,w]of g)for(const{task:x}of w)Kt(x.id);g.clear()}},[e.enabled,e.insertPrompt,e.groupSimilarTasks,e.groupTimeWindow])}const EP=1600,AP=1e4,jP=45e3;function OP(t){return t.type===He.IMAGE}function MP(t,e){return t.length!==e.length?!1:t.every((n,r)=>n===e[r])}function DP(t,e){if(e.length===0)return;const n=e.map(i=>Ve.getPostProcessingStatus(i.id)).filter(i=>!!i),r=n.some(i=>i.status==="failed"),s=e.some(i=>{const l=Ve.getPostProcessingStatus(i.id);return i.status!==ve.FAILED&&(l==null?void 0:l.status)!=="failed"});if(r&&!s)return"failed";if(n.some(i=>i.status==="processing"))return"processing";if(Js(t,e)&&e.every(i=>{var l;return!!i.insertedToCanvas||((l=Ve.getPostProcessingStatus(i.id))==null?void 0:l.status)==="completed"}))return"completed"}function NP(t,e,n){var s,a,i;const r=n.map(l=>Ve.getPostProcessingStatus(l.id)).find(l=>(l==null?void 0:l.status)==="failed");return(r==null?void 0:r.error)||((s=e==null?void 0:e.error)==null?void 0:s.message)||((i=(a=e==null?void 0:e.error)==null?void 0:a.details)==null?void 0:i.originalError)||t.error}function RP(t,e){var r;const n=e==null?void 0:e.result;return(n==null?void 0:n.previewImageUrl)||(n==null?void 0:n.url)||((r=n==null?void 0:n.urls)==null?void 0:r.find(s=>typeof s=="string"&&s.length>0))||t.previewImageUrl}function LP(t,e){const n=Ai(t,e),r=ji(t,n),s=t.primaryTaskId||(r==null?void 0:r.id)||t.taskIds[0];if(!(!s||n.length>0&&Js(t,n)&&n.every(i=>{var l;return!!i.insertedToCanvas||((l=Ve.getPostProcessingStatus(i.id))==null?void 0:l.status)==="completed"})))return s}function Bo(t,e){return!t||!e?t===e:t[0]===e[0]&&t[1]===e[1]}function FP(t){return typeof t=="object"&&t!==null&&Array.isArray(t.points)&&t.points.length===2}function BP(t,e){if(!(e!=null&&e.firstElementId))return;const n=t.children.find(s=>s.id===e.firstElementId);if(!FP(n))return;const r=Fe.getRectangleByPoints(n.points);return{position:n.points[0],size:{width:r.width,height:r.height}}}function zP(t,e,n){var s,a;if(t.anchorType==="stack")return;if(typeof((s=n==null?void 0:n.firstElementSize)==null?void 0:s.width)=="number"&&typeof((a=n==null?void 0:n.firstElementSize)==null?void 0:a.height)=="number"&&n.firstElementSize.width>0&&n.firstElementSize.height>0)return{width:n.firstElementSize.width,height:n.firstElementSize.height};const r=e==null?void 0:e.result;return typeof(r==null?void 0:r.width)=="number"&&typeof(r==null?void 0:r.height)=="number"&&r.width>0&&r.height>0?{width:r.width,height:r.height}:t.targetFrameDimensions||Ys(t.requestedSize)}function $P(t,e,n){const r={};if(e&&!Bo(t.expectedInsertPosition,e)&&(r.expectedInsertPosition=e),e&&n){const s=[e,[e[0]+n.width,e[1]+n.height]],[a,i]=t.points;Bo(a,s[0])&&Bo(i,s[1])||(r.points=s)}return r}function UP(t,e,n){if(n.current.has(e))return;const r=setTimeout(()=>{n.current.delete(e);const s=xt.getAnchorById(t,e);!s||s.phase!=="completed"||xt.removeAnchor(t,e)},EP);n.current.set(e,r)}function Oh(t,e){const n=e.current.get(t);n&&(clearTimeout(n),e.current.delete(t))}function HP({board:t,enabled:e=!0}){const n=m.useRef(new Map);m.useEffect(()=>{if(!t||!e)return;const r=n.current,s=u=>{const p=xt.getAnchorById(t,u);if(!p){Oh(u,n);return}const y=xe.getAllTasks(),f=Ai(p,y),g=ji(p,f),w=yk(p,f),x=p.primaryTaskId||(g==null?void 0:g.id),v=DP(p,f),_=(x?Ve.getPostProcessingStatus(x):void 0)||f.map(O=>Ve.getPostProcessingStatus(O.id)).find(O=>!!O),T=f.length>0&&Js(p,f)&&f.every(O=>{var G;return!!O.insertedToCanvas||((G=Ve.getPostProcessingStatus(O.id))==null?void 0:G.status)==="completed"}),b=NP(p,g,f),I=RP(p,g),A=BP(t,_),k=Ep({anchor:{...p,taskIds:w,primaryTaskId:x,error:b},task:g??void 0,tasks:f,postProcessingStatus:v,isInserting:p.phase==="inserting"&&v==="processing",hasInserted:T}),{viewModel:U,nextPatch:D}=k,X={};MP(p.taskIds,w)||(X.taskIds=w),x&&x!==p.primaryTaskId&&(X.primaryTaskId=x),p.phase!==D.phase&&(X.phase=D.phase),(p.progress??null)!==(D.progress??null)&&(X.progress=D.progress),(p.subtitle??"")!==(D.subtitle??"")&&(X.subtitle=D.subtitle),(p.error??void 0)!==(D.error??void 0)&&(X.error=D.error),(p.previewImageUrl??"")!==(I??"")&&(X.previewImageUrl=I);const L=$P(p,(A==null?void 0:A.position)??(_==null?void 0:_.firstElementPosition),(A==null?void 0:A.size)??zP(p,g,_));Object.assign(X,L),_!=null&&_.firstElementPosition&&p.transitionMode!==(p.anchorType==="frame"?"hold":"morph")&&(X.transitionMode=p.anchorType==="frame"?"hold":"morph"),Object.keys(X).length>0&&xt.updateAnchor(t,p.id,X),U.phase==="completed"&&T?UP(t,p.id,n):Oh(p.id,n)},a=()=>{xt.getAllAnchors(t).forEach(u=>{s(u.id)})},i=u=>{const p=new Set,y=xt.getAnchorByTaskId(t,u.id);y&&p.add(y.id);const f=Ci(u),g=Pi(u),w=Ei(u);let x=!1;if(f&&g&&typeof w=="number"){const v=xt.getAnchorByBatchSlot(t,{workflowId:f,batchId:g,batchIndex:w});v&&(p.add(v.id),x=!0)}if(f&&!x&&xt.getAnchorsByWorkflowId(t,f).forEach(v=>{p.add(v.id)}),p.size===0){a();return}p.forEach(v=>s(v))};a();const l=xe.observeTaskUpdates().subscribe(u=>{OP(u.task)&&i(u.task)}),d=Ve.observeCompletionEvents().subscribe(u=>{const p=xt.getAnchorByTaskId(t,u.taskId);if(p){s(p.id);return}a()}),c=new Map,h=setInterval(()=>{const u=xt.getAllAnchors(t),p=Date.now();for(const y of u)if(y.phase==="developing"||y.phase==="inserting"){const f=c.get(y.id);if(!f)c.set(y.id,p);else if(p-f>jP){c.delete(y.id),s(y.id);const g=xt.getAnchorById(t,y.id);if(!g||g.phase!=="developing"&&g.phase!=="inserting")continue;const w=LP(g,xe.getAllTasks());w&&window.dispatchEvent(new CustomEvent(gi,{detail:{taskId:w}}))}}else c.delete(y.id)},AP);return()=>{l.unsubscribe(),d.unsubscribe(),clearInterval(h),r.forEach(u=>clearTimeout(u)),r.clear()}},[t,e])}function GP(){m.useEffect(()=>{const t=e=>{if(jx())return e.preventDefault(),e.returnValue="",""};return window.onbeforeunload=t,()=>{window.onbeforeunload=null}},[])}function WP(){return()=>{}}const VP=6e4;function Ta(t,e){const n=window.requestIdleCallback;if(typeof n=="function"){const s=n(t,{timeout:e});return()=>{var a;(a=window.cancelIdleCallback)==null||a.call(window,s)}}const r=window.setTimeout(t,Math.min(e,500));return()=>window.clearTimeout(r)}function Mh({board:t,value:e}){const n=iP(),r=Mv();return m.useEffect(()=>{if(r.length===0)return;const s=window.setTimeout(()=>{Dv.warmupProfiles(r)},0);return()=>{window.clearTimeout(s)}},[r]),m.useEffect(()=>WP(),[]),m.useEffect(()=>{if(!(!e||e.length===0))return Ta(()=>{nP.preloadBoardFonts(e).catch(s=>{console.warn("[DrawnixDeferredRuntime] Failed to preload board fonts:",s)})},2e3)},[e]),m.useEffect(()=>{if(t)return Ta(()=>{Xe(()=>import("./video-recovery-service-DITdD0pC.js"),__vite__mapDeps([0]),import.meta.url).then(s=>{const a=s==null?void 0:s.initVideoRecoveryService;if(typeof a!="function"){console.warn("[DrawnixDeferredRuntime] Video recovery service unavailable.");return}a(t)}).catch(s=>{console.warn("[DrawnixDeferredRuntime] Failed to load video recovery service:",s)})},3e3)},[t]),m.useEffect(()=>{if(n)return Ta(()=>{(async()=>{try{const{workflowRecoveryPromise:d}=await Xe(async()=>{const{workflowRecoveryPromise:c}=await import("./useWorkflowSubmission-CKkOEcAT.js").then(h=>h.d);return{workflowRecoveryPromise:c}},__vite__mapDeps([0]),import.meta.url);await Promise.race([d,new Promise(c=>window.setTimeout(c,5e3))])}catch{}const[{fallbackMediaExecutor:a},{taskQueueService:i}]=await Promise.all([Xe(()=>import("./ai-chat-BnWVpTEI.js").then(d=>d.sL),__vite__mapDeps([0]),import.meta.url),Xe(()=>import("./ai-chat-BnWVpTEI.js").then(d=>d.sO),__vite__mapDeps([0]),import.meta.url)]),l=i.getAllTasks();a.resumePendingTasks((d,c,h)=>{i.updateTaskStatus(d,c,h)},l)})().catch(a=>{console.error("[DrawnixDeferredRuntime] Failed to resume tasks:",a)})},5e3)},[n]),m.useEffect(()=>{if(!(!n||!t||!e||e.length===0))return Ta(()=>{(async()=>{const[{WorkZoneTransforms:a},{TaskStatus:i},{taskQueueService:l}]=await Promise.all([Xe(()=>Promise.resolve().then(()=>Po),void 0,import.meta.url),Xe(()=>import("./ai-chat-BnWVpTEI.js").then(c=>c.sG),__vite__mapDeps([0]),import.meta.url),Xe(()=>import("./ai-chat-BnWVpTEI.js").then(c=>c.sO),__vite__mapDeps([0]),import.meta.url)]),d=a.getAllWorkZones(t);for(const c of d){if(c.createdAt&&Date.now()-c.createdAt<VP)continue;const h={...c.workflow,steps:[...c.workflow.steps]},u=h.steps.some(f=>f.status==="running"||f.status==="pending");if(h.status==="completed"&&!u){a.removeWorkZone(t,c.id);continue}if(!u)continue;const p=h.steps.map(f=>{var x,v;if(f.status!=="running"&&f.status!=="pending")return f;const g=(x=f.result)==null?void 0:x.taskId;if(!g){const _=["generate_image","generate_video","generate_grid_image","generate_inspiration_board","generate_ppt"];return f.mcp==="ai_analyze"||_.includes(f.mcp)?f:f.status==="running"?{...f,status:"failed",error:"页面刷新导致中断,请删除后重新发起"}:f}const w=l.getTask(g);if(!w)return{...f,status:"failed",error:"任务未找到,请重试"};switch(w.status){case i.COMPLETED:return{...f,status:"completed",result:{taskId:g,result:w.result}};case i.FAILED:return{...f,status:"failed",error:((v=w.error)==null?void 0:v.message)||"任务执行失败"};case i.CANCELLED:return{...f,status:"skipped"};default:return f}});p.some((f,g)=>{var w;return f.status!==((w=h.steps[g])==null?void 0:w.status)})&&a.updateWorkflow(t,c.id,{steps:p})}})().catch(a=>{console.error("[DrawnixDeferredRuntime] Failed to restore WorkZones:",a)})},2e3)},[t,n,e]),m.useEffect(()=>{if(!t)return;let s=null;return(async()=>{const i=await Xe(()=>import("./workflow-submission-service-BqiL_5Cj.js").then(c=>c.a),__vite__mapDeps([0]),import.meta.url),{WorkZoneTransforms:l}=await Xe(async()=>{const{WorkZoneTransforms:c}=await Promise.resolve().then(()=>Po);return{WorkZoneTransforms:c}},void 0,import.meta.url),{workflowSubmissionService:d}=i;s=d.subscribeToAllEvents(c=>{const h=c,p=l.getAllWorkZones(t).find(y=>y.workflow.id===h.workflowId);if(p)switch(h.type){case"step":{const y=p.workflow.steps.map(f=>f.id===h.stepId?{...f,status:h.status||f.status,result:h.result??f.result,error:h.error??f.error,duration:h.duration??f.duration}:f);l.updateWorkflow(t,p.id,{steps:y});break}case"steps_added":{const y=(h.steps||[]).map(f=>({id:f.id,mcp:f.mcp,args:f.args,description:f.description,status:f.status}));l.updateWorkflow(t,p.id,{steps:[...p.workflow.steps,...y]});break}case"completed":case"failed":{const y=h.type==="completed"?"completed":"failed",f=p.workflow.steps.map(g=>{if(g.status!=="running"&&g.status!=="pending")return g;const w=g.result;return w!=null&&w.taskId?g:{...g,status:y,error:h.type==="failed"?h.error:void 0}});l.updateWorkflow(t,p.id,{steps:f});break}case"recovered":{h.workflow&&l.updateWorkflow(t,p.id,{steps:h.workflow.steps,status:h.workflow.status});break}}})})().catch(i=>{console.error("[DrawnixDeferredRuntime] Failed to setup workflow sync:",i)}),()=>{s==null||s.unsubscribe()}},[t]),m.useEffect(()=>{if(!n||!t)return;let s=null;return(async()=>{const{taskQueueService:i}=await Xe(async()=>{const{taskQueueService:c}=await import("./ai-chat-BnWVpTEI.js").then(h=>h.sO);return{taskQueueService:c}},__vite__mapDeps([0]),import.meta.url),{WorkZoneTransforms:l}=await Xe(async()=>{const{WorkZoneTransforms:c}=await Promise.resolve().then(()=>Po);return{WorkZoneTransforms:c}},void 0,import.meta.url),{TaskStatus:d}=await Xe(async()=>{const{TaskStatus:c}=await import("./ai-chat-BnWVpTEI.js").then(h=>h.sG);return{TaskStatus:c}},__vite__mapDeps([0]),import.meta.url);s=i.observeTaskUpdates().subscribe(c=>{if(c.type!=="taskUpdated"&&c.type!=="taskCompleted"&&c.type!=="taskFailed")return;const h=c.task;if(!h)return;const u=l.getAllWorkZones(t);for(const p of u){const y={...p.workflow,steps:[...p.workflow.steps]};let f=!1;const g=y.steps.map(w=>{var b;const x=w.result;if((x==null?void 0:x.taskId)!==h.id)return w;let v=w.status,_=w.error,T=w.result;switch(h.status){case d.COMPLETED:v="completed",T={taskId:h.id,result:h.result};break;case d.FAILED:v="failed",_=((b=h.error)==null?void 0:b.message)||"任务失败";break;case d.PROCESSING:v="running";break;case d.PENDING:v="pending";break;case d.CANCELLED:v="skipped";break}return v!==w.status||_!==w.error?(f=!0,{...w,status:v,error:_,result:T}):w});f&&l.updateWorkflow(t,p.id,{steps:g})}})})().catch(i=>{console.error("[DrawnixDeferredRuntime] Failed to sync task queue:",i)}),()=>{s==null||s.unsubscribe()}},[t,n]),mP(),PP({enabled:!0,insertPrompt:!1,groupSimilarTasks:!0}),HP({board:t,enabled:n}),GP(),null}const a1=Object.freeze(Object.defineProperty({__proto__:null,DrawnixDeferredRuntime:Mh,default:Mh},Symbol.toStringTag,{value:"Module"})),KP={selectedVoice:"",rate:1,pitch:1,volume:1,voicesByLanguage:{}},Dh={zh:"你好,这是一段测试语音。",en:"Hello, this is a test speech.",ja:"こんにちは、これはテスト音声です。",ko:"안녕하세요. 이것은 테스트 음성입니다.",fr:"Bonjour, ceci est un test vocal.",de:"Hallo, dies ist eine Sprachprobe.",es:"Hola, esta es una prueba de voz.",ru:"Привет, это тестовый голос."};function Nh(t){return{...KP,...t||{},voicesByLanguage:(t==null?void 0:t.voicesByLanguage)||{}}}function Rh(t){let e=0;t.localService&&(e+=20),t.default&&(e+=8);const n=t.name.toLowerCase();return(n.includes("tingting")||n.includes("婷婷")||n.includes("samantha")||n.includes("alex")||n.includes("victoria")||n.includes("daniel")||n.includes("kyoko")||n.includes("otoya"))&&(e+=24),(n.includes("whisper")||n.includes("zarvox")||n.includes("bells")||n.includes("boing")||n.includes("bubbles"))&&(e-=30),e}function zl(t){return t.trim().toLowerCase().split("-")[0]||"zh"}function Lh(t){return{all:"全局默认",zh:"中文",en:"英语",ja:"日语",ko:"韩语",fr:"法语",de:"德语",es:"西语",ru:"俄语",it:"意语",pt:"葡语",ar:"阿拉伯语"}[t]||t.toUpperCase()}function qP(t){const e=zl(t);return Dh[e]||Dh.en}function YP(t,e){const n=["zh","en"],r=n.indexOf(t),s=n.indexOf(e);return r!==-1||s!==-1?r===-1?1:s===-1?-1:r-s:t.localeCompare(e)}function zo(t,e,n){if(n<=e)return"0%";const r=(t-e)/(n-e)*100;return`${Math.min(100,Math.max(0,r))}%`}const i1=()=>{var _;const[t,e]=m.useState(()=>Nh(ws.get())),[n,r]=m.useState([]),[s,a]=m.useState(""),[i,l]=m.useState("all"),[d,c]=m.useState(!1),h=m.useCallback(()=>{if(typeof window>"u"||!("speechSynthesis"in window)){r([]);return}const T=window.speechSynthesis.getVoices(),b=T.map(I=>({uri:I.voiceURI,name:I.name,lang:I.lang,localService:I.localService,default:I.default})).sort((I,A)=>{const k=Rh(T.find(U=>U.voiceURI===A.uri)||T[0])-Rh(T.find(U=>U.voiceURI===I.uri)||T[0]);return k!==0?k:I.name.localeCompare(A.name)});r(b)},[]);m.useEffect(()=>{if(typeof window>"u"||!("speechSynthesis"in window))return;let T=0,b=null;const I=6,A=()=>{h(),window.speechSynthesis.getVoices().length===0&&T<I&&(T+=1,b=window.setTimeout(A,120))};A(),window.speechSynthesis.onvoiceschanged=A;const k=U=>{e(Nh(U))};return ws.addListener(k),()=>{ws.removeListener(k),window.speechSynthesis.onvoiceschanged=null,b!==null&&window.clearTimeout(b),window.speechSynthesis.cancel()}},[h]);const u=m.useMemo(()=>{const T=new Set;return n.forEach(b=>{T.add(zl(b.lang))}),["all",...Array.from(T).sort(YP)]},[n]),p=m.useMemo(()=>{const T=s.trim().toLowerCase();return n.filter(b=>{const I=i==="all"||zl(b.lang)===i,A=!T||b.name.toLowerCase().includes(T)||b.lang.toLowerCase().includes(T);return I&&A})},[s,i,n]),y=i==="all"?t.selectedVoice||"":((_=t.voicesByLanguage)==null?void 0:_[i])||"",f=m.useCallback(async T=>{e(T),await ws.update(T)},[]),g=m.useCallback(async T=>{if(i==="all"){await f({...t,selectedVoice:T});return}await f({...t,voicesByLanguage:{...t.voicesByLanguage||{},[i]:T}})},[f,i,t]),w=m.useCallback(async(T,b)=>{await f({...t,[T]:b})},[f,t]),x=m.useCallback(async()=>{if(i==="all"){await f({...t,selectedVoice:""});return}const T={...t.voicesByLanguage||{}};delete T[i],await f({...t,voicesByLanguage:T})},[f,i,t]),v=m.useCallback((T,b)=>{if(typeof window>"u"||!("speechSynthesis"in window))return;if(d){window.speechSynthesis.cancel(),c(!1);return}const I=window.speechSynthesis.getVoices().find(k=>k.voiceURI===T);if(!I)return;const A=new SpeechSynthesisUtterance(qP(b));A.voice=I,A.lang=I.lang,A.rate=t.rate,A.pitch=t.pitch,A.volume=t.volume,A.onstart=()=>c(!0),A.onend=()=>c(!1),A.onerror=()=>c(!1),window.speechSynthesis.cancel(),window.speechSynthesis.speak(A)},[d,t.pitch,t.rate,t.volume]);return typeof window>"u"||!("speechSynthesis"in window)?o.jsx("div",{className:"project-drawer-tts project-drawer-tts--empty",children:"当前环境不支持浏览器语音播报。"}):o.jsxs("div",{className:"project-drawer-tts",children:[o.jsxs("div",{className:"project-drawer-tts__section",children:[o.jsxs("div",{className:"project-drawer-tts__section-title",children:[o.jsx(Nv,{size:16}),o.jsx("span",{children:"播报参数"})]}),o.jsx("div",{className:"project-drawer-tts__hint",children:"使用浏览器自带能力,免费。"}),o.jsxs("label",{className:"project-drawer-tts__slider",children:[o.jsx("span",{className:"project-drawer-tts__slider-label",children:"语速"}),o.jsx("input",{className:"project-drawer-tts__range",style:{"--slider-progress":zo(t.rate,.5,10)},type:"range",min:"0.5",max:"10",step:"0.1",value:t.rate,onChange:T=>void w("rate",Number(T.target.value))}),o.jsxs("strong",{className:"project-drawer-tts__slider-value",children:[t.rate.toFixed(1),"x"]})]}),o.jsxs("label",{className:"project-drawer-tts__slider",children:[o.jsx("span",{className:"project-drawer-tts__slider-label",children:"音调"}),o.jsx("input",{className:"project-drawer-tts__range",style:{"--slider-progress":zo(t.pitch,.5,2)},type:"range",min:"0.5",max:"2",step:"0.1",value:t.pitch,onChange:T=>void w("pitch",Number(T.target.value))}),o.jsx("strong",{className:"project-drawer-tts__slider-value",children:t.pitch.toFixed(1)})]}),o.jsxs("label",{className:"project-drawer-tts__slider",children:[o.jsx("span",{className:"project-drawer-tts__slider-label",children:"音量"}),o.jsx("input",{className:"project-drawer-tts__range",style:{"--slider-progress":zo(t.volume,0,1)},type:"range",min:"0",max:"1",step:"0.05",value:t.volume,onChange:T=>void w("volume",Number(T.target.value))}),o.jsxs("strong",{className:"project-drawer-tts__slider-value",children:[Math.round(t.volume*100),"%"]})]})]}),o.jsxs("div",{className:"project-drawer-tts__section",children:[o.jsxs("div",{className:"project-drawer-tts__toolbar",children:[o.jsxs("div",{className:"project-drawer-tts__filters",children:[o.jsx("div",{className:"project-drawer-tts__chips",children:u.map(T=>o.jsx("button",{type:"button",className:`project-drawer-tts__chip${i===T?" project-drawer-tts__chip--active":""}`,onClick:()=>l(T),children:Lh(T)},T))}),o.jsx($t,{value:s,size:"small",placeholder:"搜索音色或语言",onChange:a})]}),o.jsxs("div",{className:"project-drawer-tts__toolbar-actions",children:[o.jsx(Me,{size:"small",variant:"outline",icon:o.jsx(ra,{}),onClick:h,children:"刷新"}),o.jsx(Me,{size:"small",variant:"text",onClick:()=>void x(),children:i==="all"?"清空默认音色":"改回全局默认"})]})]}),o.jsx("div",{className:"project-drawer-tts__hint",children:i==="all"?"全局默认会作为所有 TTS 入口的首选音色。":`${Lh(i)} 可单独覆盖音色,未设置时回退到全局默认。`}),p.length===0?o.jsx("div",{className:"project-drawer-tts__empty",children:"未找到可用音色,请确认系统已安装语音包。"}):o.jsx("div",{className:"project-drawer-tts__voice-list",children:p.map(T=>{const b=y===T.uri;return o.jsxs("div",{className:`project-drawer-tts__voice${b?" project-drawer-tts__voice--active":""}`,role:"button",tabIndex:0,onClick:()=>void g(T.uri),onKeyDown:I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),g(T.uri))},children:[o.jsxs("div",{className:"project-drawer-tts__voice-main",children:[o.jsxs("div",{className:"project-drawer-tts__voice-title",children:[o.jsx("span",{children:T.name}),b&&o.jsx(Rv,{size:"12px"})]}),o.jsxs("div",{className:"project-drawer-tts__voice-meta",children:[o.jsx("span",{children:T.lang}),T.localService&&o.jsx("span",{children:"本地"}),T.default&&o.jsx("span",{children:"系统默认"})]})]}),o.jsx(Me,{size:"small",variant:"text",theme:"default",icon:d?o.jsx(Lv,{size:14}):o.jsx(ic,{size:14}),onClick:I=>{I.stopPropagation(),v(T.uri,T.lang)},children:"试听"})]},T.uri)})})]})]})},Fh=60,Bh="slideshow-active";function Sa(t){t?document.documentElement.classList.add(Bh):document.documentElement.classList.remove(Bh)}function ZP(t){const e=[];for(const n of t.children)at(n)&&e.push(n);return e}function XP(){var t;return!!((t=window.matchMedia)!=null&&t.call(window,"(prefers-reduced-motion: reduce)").matches)}function JP(t){var e;return Na((e=t==null?void 0:t.pptMeta)==null?void 0:e.transition)}function QP(t,e){const n=Fe.getRectangleByPoints(e.points),r=kt.getBoardContainer(t),s=r.clientWidth,a=r.clientHeight,i=(s-Fh*2)/n.width,l=(a-Fh*2)/n.height,d=Math.min(i,l,3),c=n.x+n.width/2,h=n.y+n.height/2,u=[c-s/2/d,h-a/2/d];dt.updateViewport(t,u,d);const p=r.getBoundingClientRect(),y=p.left+(n.x-u[0])*d,f=p.top+(n.y-u[1])*d,g=n.width*d,w=n.height*d;return{left:y,top:f,width:g,height:w}}function eE(t){const e=window.innerWidth,n=window.innerHeight,r={top:0,left:0,width:e,height:Math.max(0,t.top)},s={top:t.top+t.height,left:0,width:e,height:Math.max(0,n-t.top-t.height)},a={top:t.top,left:0,width:Math.max(0,t.left),height:t.height},i={top:t.top,left:t.left+t.width,width:Math.max(0,e-t.left-t.width),height:t.height};return[r,s,a,i]}const tE=["#000000","#e91e63","#f39c12","#4caf50","#2196f3","#9c27b0","#ffffff"],nE=[{style:bs.solid,icon:o.jsx(Zv,{})},{style:bs.dashed,icon:o.jsx(Xv,{})},{style:bs.dotted,icon:o.jsx(Jv,{})},{style:bs.double,icon:o.jsx(Qv,{})}],rE=[1,2,4,8],Xp=({visible:t,board:e,onClose:n,initialFrameId:r})=>{const[s,a]=m.useState(0),[i,l]=m.useState(null),[d,c]=m.useState(!0),[h,u]=m.useState("select"),p=Fv(),y=m.useRef(),f=m.useRef(null),g=m.useRef(!1),w=m.useRef(null),x=m.useRef(null),v=m.useRef([]),_=m.useRef(0),T=m.useRef(0),b=m.useRef(),[I,A]=m.useState(null),k=t?Bv(e):null,[U,D]=m.useState((k==null?void 0:k.strokeColor)??"#000000"),[X,L]=m.useState((k==null?void 0:k.strokeStyle)??bs.solid),[O,G]=m.useState((k==null?void 0:k.strokeWidth)??2),C=m.useCallback(ne=>{D(ne),zv(e,ne)},[e]),P=m.useCallback(ne=>{L(ne),$v(e,ne)},[e]),j=m.useCallback(ne=>{G(ne),Uv(e,ne)},[e]),N=m.useCallback(()=>{c(!0),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{c(!1)},3e3)},[]),B=m.useCallback(ne=>{if(u(ne),N(),ne==="select")dt.updatePointerType(e,Or.selection),p(Or.selection);else{const q={pen:Pn.feltTipPen,eraser:Pn.eraser,laser:Pn.laserPointer}[ne];fn(e,vn.drawing),dt.updatePointerType(e,q),p(q)}},[e,N,p]),K=m.useCallback((ne,M={})=>{const q=v.current;if(!e||ne<0||ne>=q.length)return;const R=q[ne],J=QP(e,R),Ce=JP(R),re=M.animate!==!1&&_.current!==ne&&Ce.type!=="none"&&!XP();if(b.current&&clearTimeout(b.current),re&&Ce.type!=="none"){const ze=T.current+1;T.current=ze;const V=Ce.durationMs||700,z=Ce.type;A({key:ze,rect:J,type:z,durationMs:V}),b.current=setTimeout(()=>{A(F=>(F==null?void 0:F.key)===ze?null:F)},V+120)}else A(null);l(J),a(ne),_.current=ne,N()},[e,N]);m.useEffect(()=>{if(!t)return;const ne=ZP(e);if(ne.length===0){n();return}v.current=ne;const M=e.viewport;w.current={origination:M!=null&&M.origination?[M.origination[0],M.origination[1]]:null,zoom:(M==null?void 0:M.zoom)??1},x.current=e.pointer,Sa(!0);let q=0;if(r){const J=ne.findIndex(Ce=>Ce.id===r);J>=0&&(q=J)}K(q,{animate:!1});const R=Hv(document.documentElement);return R==null||R.then(()=>{setTimeout(()=>K(q,{animate:!1}),300)}).catch(()=>{}),()=>{Sa(!1),y.current&&clearTimeout(y.current),b.current&&clearTimeout(b.current)}},[t]);const fe=m.useCallback(()=>{var M;Sa(!1);const ne=w.current;if(ne&&e){const q=ne.origination??[0,0];dt.updateViewport(e,q,ne.zoom)}x.current!==null&&(dt.updatePointerType(e,x.current),p(x.current)),(M=Gv())==null||M.catch(()=>{}),l(null),A(null),u("select"),n()},[e,n,p]),ae=m.useCallback(()=>{const ne=v.current;if(s<ne.length-1){K(s+1);return}fe()},[s,K,fe]);m.useEffect(()=>{if(!t)return;const ne=()=>{if(!document.fullscreenElement&&t){Sa(!1);const M=w.current;if(M&&e){const q=M.origination??[0,0];dt.updateViewport(e,q,M.zoom)}x.current!==null&&(dt.updatePointerType(e,x.current),p(x.current)),l(null),A(null),u("select"),n()}};return document.addEventListener("fullscreenchange",ne),()=>{document.removeEventListener("fullscreenchange",ne)}},[t,e,n,p]),m.useEffect(()=>{if(!t)return;const ne=()=>{K(s)};return window.addEventListener("resize",ne),()=>window.removeEventListener("resize",ne)},[t,s,K]),m.useEffect(()=>{if(!t)return;const ne=v.current;if(ne.length===0)return;const M=q=>{switch(N(),q.key){case"ArrowRight":case" ":case"Enter":case"PageDown":case"ArrowDown":{q.preventDefault(),a(R=>{const J=Math.min(R+1,ne.length-1);return J!==R&&K(J),J});break}case"ArrowLeft":case"Backspace":case"PageUp":case"ArrowUp":{q.preventDefault(),a(R=>{const J=Math.max(R-1,0);return J!==R&&K(J),J});break}case"Escape":{q.preventDefault(),fe();break}case"Home":{q.preventDefault(),K(0);break}case"End":{q.preventDefault(),K(ne.length-1);break}}};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[t,K,fe,N]);const te=m.useCallback(ne=>{if(h!=="select")return;const M=ne.target;M.closest(".frame-slideshow__controls")||M.closest(".frame-slideshow__nav")||M.closest("[data-slideshow-media-control]")||ae()},[h,ae]);if(m.useEffect(()=>{if(!t||!i||h!=="select"){f.current=null,g.current=!1;return}const ne=z=>z.clientX>=i.left&&z.clientX<=i.left+i.width&&z.clientY>=i.top&&z.clientY<=i.top+i.height,M=z=>z instanceof Element&&!!z.closest(".frame-slideshow__controls, .frame-slideshow__nav"),q=z=>z instanceof Element&&!!z.closest("[data-slideshow-media-control], video, audio"),R=z=>z instanceof Element&&!!z.closest("[data-slideshow-legacy-audio]"),J=z=>{const F=z.target;return ne(z)&&!M(F)&&!q(F)&&!R(F)},Ce=z=>{z.preventDefault(),z.stopPropagation()},re=z=>{if(z.button===0&&ne(z)&&R(z.target)){f.current=null,z.stopPropagation();return}if(z.button!==0||!J(z)){f.current=null;return}f.current={x:z.clientX,y:z.clientY},Ce(z)},ze=z=>{if(z.button===0&&ne(z)&&R(z.target)){f.current=null,z.stopPropagation();return}const F=f.current;!F||(f.current=null,!J(z))||(Ce(z),g.current=!0,Math.hypot(z.clientX-F.x,z.clientY-F.y)>5)||ae()},V=z=>{if(g.current){g.current=!1,Ce(z);return}J(z)&&Ce(z)};return document.addEventListener("pointerdown",re,!0),document.addEventListener("pointerup",ze,!0),document.addEventListener("click",V,!0),()=>{document.removeEventListener("pointerdown",re,!0),document.removeEventListener("pointerup",ze,!0),document.removeEventListener("click",V,!0)}},[h,i,ae,t]),m.useEffect(()=>{if(!t)return;const ne=()=>N();return window.addEventListener("mousemove",ne),()=>window.removeEventListener("mousemove",ne)},[t,N]),!t||!i)return null;const Se=v.current,Ee=Se[s],Te=eE(i),ke=I?{left:I.rect.left,top:I.rect.top,width:I.rect.width,height:I.rect.height,animationDuration:`${I.durationMs}ms`}:void 0;return Wv.createPortal(o.jsxs("div",{className:"frame-slideshow",style:{zIndex:Kf.SLIDESHOW},onMouseMove:N,onClick:te,children:[o.jsx("div",{className:"frame-slideshow__mask",children:Te.map((ne,M)=>o.jsx("div",{className:"frame-slideshow__mask-block",style:ne},M))}),I?o.jsx("div",{className:`frame-slideshow__transition frame-slideshow__transition--${I.type}`,style:ke},I.key):null,o.jsxs("div",{className:"frame-slideshow__controls",style:{opacity:d?1:0},children:[o.jsxs("div",{className:"frame-slideshow__controls-left",children:[Ee&&o.jsx("div",{className:"frame-slideshow__title",children:Yt(Ee,s+1)}),o.jsxs("div",{className:"frame-slideshow__esc-hint",children:["按 ",o.jsx("kbd",{children:"ESC"})," 退出"]})]}),Se.length>0&&o.jsxs("div",{className:"frame-slideshow__indicator",children:[o.jsx("span",{className:"frame-slideshow__indicator-current",children:s+1}),o.jsx("span",{className:"frame-slideshow__indicator-sep",children:"/"}),o.jsx("span",{className:"frame-slideshow__indicator-total",children:Se.length})]}),o.jsxs("div",{className:"frame-slideshow__controls-right",children:[h==="pen"&&o.jsxs("div",{className:"frame-slideshow__settings-panel",children:[o.jsx("div",{className:"frame-slideshow__pen-colors",children:tE.map(ne=>o.jsx("button",{className:`frame-slideshow__pen-color ${U===ne?"frame-slideshow__pen-color--active":""}`,style:{backgroundColor:ne},onClick:()=>C(ne)},ne))}),o.jsx("div",{className:"frame-slideshow__pen-divider"}),o.jsx("div",{className:"frame-slideshow__pen-styles",children:nE.map(({style:ne,icon:M})=>o.jsx("button",{className:`frame-slideshow__pen-style ${X===ne?"frame-slideshow__pen-style--active":""}`,onClick:()=>P(ne),children:M},ne))}),o.jsx("div",{className:"frame-slideshow__pen-divider"}),o.jsx("div",{className:"frame-slideshow__pen-widths",children:rE.map(ne=>o.jsx("button",{className:`frame-slideshow__pen-width ${O===ne?"frame-slideshow__pen-width--active":""}`,onClick:()=>j(ne),children:o.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",children:o.jsx("line",{x1:"3",y1:"10",x2:"17",y2:"10",stroke:"currentColor",strokeWidth:ne,strokeLinecap:"round"})})},ne))})]}),o.jsx(Le,{content:"选择工具",showArrow:!1,children:o.jsx("button",{className:`frame-slideshow__tool-btn ${h==="select"?"frame-slideshow__tool-btn--active":""}`,onClick:()=>B("select"),children:o.jsx(Vv,{size:20})})}),o.jsx(Le,{content:"画笔",showArrow:!1,children:o.jsx("button",{className:`frame-slideshow__tool-btn ${h==="pen"?"frame-slideshow__tool-btn--active":""}`,onClick:()=>B("pen"),children:o.jsx(Kv,{size:20})})}),o.jsx(Le,{content:"橡皮擦",showArrow:!1,children:o.jsx("button",{className:`frame-slideshow__tool-btn ${h==="eraser"?"frame-slideshow__tool-btn--active":""}`,onClick:()=>B("eraser"),children:o.jsx(qv,{size:20})})}),o.jsx(Le,{content:"激光笔",showArrow:!1,children:o.jsx("button",{className:`frame-slideshow__tool-btn ${h==="laser"?"frame-slideshow__tool-btn--active":""}`,onClick:()=>B("laser"),children:o.jsx(Yv,{size:20})})})]})]}),s>0&&o.jsx(Le,{content:"上一页",showArrow:!1,children:o.jsx("button",{className:"frame-slideshow__nav frame-slideshow__nav--prev",style:{opacity:d?1:0},onClick:()=>K(s-1),children:o.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",children:o.jsx("path",{d:"M15 18l-6-6 6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})}),s<Se.length-1&&o.jsx(Le,{content:"下一页",showArrow:!1,children:o.jsx("button",{className:"frame-slideshow__nav frame-slideshow__nav--next",style:{opacity:d?1:0},onClick:()=>K(s+1),children:o.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",children:o.jsx("path",{d:"M9 18l6-6-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})})]}),document.body)},o1=Object.freeze(Object.defineProperty({__proto__:null,FrameSlideshow:Xp},Symbol.toStringTag,{value:"Module"}));class sE{async exportToZip(e){const{onProgress:n}=e||{},{default:r}=await Xe(async()=>{const{default:p}=await import("./office-data-DMEex_0S.js").then(y=>y.j);return{default:p}},[],import.meta.url),s=new r;n==null||n(5,"正在加载数据...");const[a,i]=await Promise.all([Nt.loadAllFolders(),Nt.loadAllBoards()]);n==null||n(15,"正在构建目录结构...");const l=this.buildFolderPathMap(a),d=this.collectAssetIds(i);n==null||n(20,"正在加载素材...");const c=await this.loadAssets(d);n==null||n(30,"正在创建文件夹...");for(const p of a){const y=l.get(p.id)||p.name;s.folder(y)}n==null||n(40,"正在导出画板...");const h=i.length;for(let p=0;p<i.length;p++){const y=i[p],f=y.folderId?l.get(y.folderId):null,g=this.sanitizeFileName(y.name),w=f?`${f}/${g}.drawnix`:`${g}.drawnix`,x={type:ql.drawnix,version:Yl.drawnix,source:"web",elements:y.elements||[],viewport:y.viewport||{zoom:1},theme:y.theme,boardMeta:{id:y.id,name:y.name,order:y.order,createdAt:y.createdAt,updatedAt:y.updatedAt}};if(s.file(w,JSON.stringify(x,null,2)),h>0){const v=40+Math.round((p+1)/h*20);n==null||n(v,`正在导出画板 (${p+1}/${h})...`)}}if(n==null||n(60,"正在导出素材..."),c.length>0){const p=s.folder("_assets");if(p){const y=c.length;for(let f=0;f<c.length;f++){const g=c[f],{blobData:w,...x}=g;p.file(`${g.id}.meta.json`,JSON.stringify(x,null,2)),w&&p.file(`${g.id}.blob`,w);const v=60+Math.round((f+1)/y*20);n==null||n(v,`正在导出素材 (${f+1}/${y})...`)}}}n==null||n(85,"正在压缩文件...");const u=await s.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:6}},p=>{const y=85+Math.round(p.percent*.14),f=p.currentFile||"",g=f.length>30?"..."+f.slice(-27):f;n==null||n(y,`正在压缩: ${g||"..."}`)});return n==null||n(100,"导出完成"),u}buildFolderPathMap(e){const n=new Map,r=new Map;for(const a of e)r.set(a.id,a);const s=a=>{if(n.has(a))return n.get(a);const i=r.get(a);if(!i)return"";const l=this.sanitizeFileName(i.name);if(i.parentId){const d=s(i.parentId),c=d?`${d}/${l}`:l;return n.set(a,c),c}return n.set(a,l),l};for(const a of e)s(a.id);return n}sanitizeFileName(e){return e.replace(/[<>:"/\\|?*]/g,"_").replace(/\s+/g," ").trim()||"unnamed"}async importFromZip(e,n={}){var c;const{merge:r=!1,onProgress:s}=n,a=[];let i=0,l=0,d=0;try{s==null||s(5,"正在读取文件...");const{default:h}=await Xe(async()=>{const{default:x}=await import("./office-data-DMEex_0S.js").then(v=>v.j);return{default:x}},[],import.meta.url),u=await h.loadAsync(e);s==null||s(10,"正在验证文件格式...");const p=Object.keys(u.files).filter(x=>x.endsWith(".drawnix")&&!x.startsWith("_"));if(p.length===0)throw new Error("无效的导出文件:未找到画板文件");r||(s==null||s(15,"正在清理现有数据..."),await Nt.clearAll(),await rl.clearAll(),await Nt.saveState({currentBoardId:null,expandedFolderIds:[],sidebarWidth:ai.SIDEBAR_WIDTH,sidebarCollapsed:!1,migrationCompleted:!0})),s==null||s(20,"正在导入素材...");const y=Object.keys(u.files).filter(x=>x.startsWith("_assets/")&&x.endsWith(".meta.json"));for(let x=0;x<y.length;x++){const v=y[x],_=v.replace("_assets/","").replace(".meta.json",""),T=v.replace(".meta.json",".blob");try{const b=u.file(v),I=u.file(T);if(b&&I){const A=await b.async("string"),k=JSON.parse(A),U=await I.async("blob"),D={...k,blobData:U};await this.saveStoredAsset(D),d++}}catch(b){const I=b instanceof Error?b.message:String(b);a.push(`素材 ${_} 导入失败: ${I}`)}if(y.length>0){const b=20+(x+1)/y.length*30;s==null||s(b,`正在导入素材 (${x+1}/${y.length})...`)}}s==null||s(55,"正在分析目录结构...");const f=new Set,g=new Map;for(const x of p){const v=x.split("/");if(v.length>1){let _="";for(let T=0;T<v.length-1;T++)_=_?`${_}/${v[T]}`:v[T],f.add(_)}}const w=Array.from(f).sort((x,v)=>{const _=x.split("/").length,T=v.split("/").length;return _-T||x.localeCompare(v)});s==null||s(60,"正在导入文件夹...");for(let x=0;x<w.length;x++){const v=w[x],_=v.split("/"),T=_[_.length-1],b=_.length>1?_.slice(0,-1).join("/"):null,I=b&&g.get(b)||null;try{const A=this.generateId();g.set(v,A);const k={id:A,name:T,parentId:I,order:x,isExpanded:!0,createdAt:Date.now(),updatedAt:Date.now()};await Nt.saveFolder(k),i++}catch(A){const k=A instanceof Error?A.message:String(A);a.push(`文件夹 "${T}" 导入失败: ${k}`)}}s==null||s(70,"正在导入画板...");for(let x=0;x<p.length;x++){const v=p[x];try{const T=u.file(v);if(T){const b=await T.async("string"),I=JSON.parse(b),A=v.split("/").pop()||"unnamed.drawnix",k=((c=I.boardMeta)==null?void 0:c.name)||A.replace(".drawnix",""),U=v.split("/"),D=U.length>1?U.slice(0,-1).join("/"):null,X=D&&g.get(D)||null,L=I.boardMeta,O={id:(L==null?void 0:L.id)||this.generateId(),name:k,folderId:X,order:(L==null?void 0:L.order)??x,elements:I.elements||[],viewport:I.viewport,theme:I.theme,createdAt:(L==null?void 0:L.createdAt)||Date.now(),updatedAt:(L==null?void 0:L.updatedAt)||Date.now()};await Nt.saveBoard(O),l++}}catch(T){const b=v.split("/").pop()||v,I=T instanceof Error?T.message:String(T);a.push(`画板 "${b}" 导入失败: ${I}`)}const _=70+(x+1)/p.length*25;s==null||s(_,`正在导入画板 (${x+1}/${p.length})...`)}return s==null||s(100,"导入完成"),{success:a.length===0,folders:i,boards:l,assets:d,errors:a}}catch(h){const u=h instanceof Error?h.message:String(h);return{success:!1,folders:i,boards:l,assets:d,errors:[...a,u]}}}generateId(){return`${Date.now().toString(36)}-${Math.random().toString(36).substring(2,11)}`}collectAssetIds(e){const n=new Set;for(const r of e)r.elements&&this.findAssetIdsInElements(r.elements,n);return n}findAssetIdsInElements(e,n){for(const r of e)r.assetId&&n.add(r.assetId),r.imageAssetId&&n.add(r.imageAssetId),r.videoAssetId&&n.add(r.videoAssetId),r.children&&Array.isArray(r.children)&&this.findAssetIdsInElements(r.children,n)}async loadAssets(e){const n=[],r=Xt.createInstance({name:Kn.STORAGE_NAME,storeName:Kn.STORE_NAME});for(const s of e)try{const a=await r.getItem(s);a&&n.push(a)}catch(a){console.warn(`[WorkspaceExport] Failed to load asset ${s}:`,a)}return n}async saveStoredAsset(e){await Xt.createInstance({name:Kn.STORAGE_NAME,storeName:Kn.STORE_NAME}).setItem(e.id,e)}downloadZip(e,n){const r=new Date,s=r.toISOString().split("T")[0],a=r.toTimeString().split(" ")[0].replace(/:/g,""),i=`aitu_workspace_${s}_${a}.zip`,l=URL.createObjectURL(e),d=document.createElement("a");d.href=l,d.download=n||i,document.body.appendChild(d),d.click(),document.body.removeChild(d),URL.revokeObjectURL(l)}}const $o=new sE,zh=60;function aE(t,e,n){var a,i;const r=[];for(const l of t.children)at(l)&&r.push(Fe.getRectangleByPoints(l.points));if(r.length===0){const l=kt.getBoardContainer(t),d=l.clientWidth,c=l.clientHeight,h=((a=t.viewport)==null?void 0:a.zoom)??1,u=(i=t.viewport)==null?void 0:i.origination,p=u?u[0]:0,y=u?u[1]:0,f=p+d/2/h,g=y+c/2/h;return[f-e/2,g-n/2]}if(e>=n){let l=-1/0,d=0;for(const c of r){const h=c.x+c.width;h>l&&(l=h,d=c.y)}return[l+zh,d]}else{let l=-1/0,d=0;for(const c of r){const h=c.y+c.height;h>l&&(l=h,d=c.x)}return[d,l+zh]}}const iE=({visible:t,board:e,onClose:n,onFrameAdded:r})=>{const[s,a]=m.useState(null),[i,l]=m.useState(1920),[d,c]=m.useState(1080),h=m.useCallback((g,w)=>{if(!e||g<=0||w<=0)return;const x=aE(e,g,w),v=[x,[x[0]+g,x[1]+w]],_=Gn.insertFrame(e,v);ns(e);const T=e.children.find(C=>C.id===_.id);T&&ta(e,T);const b=kt.getBoardContainer(e),I=b.clientWidth,A=b.clientHeight,k=80,U=I/(g+k*2),D=A/(w+k*2),X=Math.min(U,D,2),L=x[0]+g/2,O=x[1]+w/2,G=[L-I/2/X,O-A/2/X];dt.updateViewport(e,G,X),r==null||r(_),n()},[e,r,n]),u=m.useCallback(g=>{h(g.width,g.height)},[h]),p=m.useCallback(()=>{h(i,d)},[h,i,d]),y=m.useCallback(()=>{a(null)},[]),f=m.useMemo(()=>s?`${s.width}x${s.height}`:"",[s]);return o.jsx(Zn,{header:"添加 PPT 页面",visible:t,onClose:n,footer:null,width:480,destroyOnClose:!0,children:o.jsxs("div",{className:"add-frame-dialog",children:[o.jsx("div",{className:"add-frame-dialog__presets",children:eP.map(g=>o.jsxs("div",{className:"add-frame-dialog__category",children:[o.jsx("div",{className:"add-frame-dialog__category-label",children:g.category}),o.jsx("div",{className:"add-frame-dialog__category-items",children:g.items.map(w=>{const x=`${w.width}x${w.height}`,v=f===x;return o.jsxs("button",{className:`add-frame-dialog__preset-item${v?" add-frame-dialog__preset-item--active":""}`,onClick:()=>u(w),children:[o.jsx("span",{className:"add-frame-dialog__preset-label",children:w.label}),o.jsxs("span",{className:"add-frame-dialog__preset-size",children:[w.width," × ",w.height]})]},x)})})]},g.category))}),o.jsxs("div",{className:"add-frame-dialog__footer",children:[o.jsxs("div",{className:"add-frame-dialog__custom-section",children:[o.jsx("span",{className:"add-frame-dialog__custom-label",children:"自定义"}),o.jsxs("div",{className:"add-frame-dialog__input-group",children:[o.jsx("span",{className:"add-frame-dialog__input-label",children:"W"}),o.jsx(ud,{value:i,onChange:g=>{l(g),y()},onEnter:p,min:10,max:1e4,theme:"normal",size:"small",style:{width:68}})]}),o.jsx("span",{className:"add-frame-dialog__input-sep",children:"×"}),o.jsxs("div",{className:"add-frame-dialog__input-group",children:[o.jsx("span",{className:"add-frame-dialog__input-label",children:"H"}),o.jsx(ud,{value:d,onChange:g=>{c(g),y()},onEnter:p,min:10,max:1e4,theme:"normal",size:"small",style:{width:68}})]}),o.jsx(Me,{theme:"primary",variant:"text",shape:"square",size:"small",icon:o.jsx(Dn,{}),onClick:p,title:"添加自定义尺寸 PPT 页面"})]}),o.jsxs("div",{className:"add-frame-dialog__hint",children:[o.jsx("kbd",{children:"F"})," 直接绘制 PPT 页面"]})]})]})})},mr=10,xi=5.625,oE=50*1024*1024,$l="application/vnd.openxmlformats-officedocument.presentationml.presentation",$h=1280,Uo=5e3,lE=mr*72,mn="PingFang SC",cE=14;function Xa(t,e){const n=Math.max(e,1),r=t*(lE/n);return Math.max(.1,r)}function cr(t){if(!t)return;const e=t.trim();if(e==="transparent"||e==="none"||e==="")return;if(e.startsWith("#")){const r=e.slice(1);return r.length===3?r.split("").map(s=>s+s).join("").toUpperCase():r.substring(0,6).toUpperCase()}const n=e.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(n){const[,r,s,a]=n;return[r,s,a].map(i=>parseInt(i).toString(16).padStart(2,"0")).join("").toUpperCase()}}function dE(t){return t.toLowerCase().endsWith(".pptx")?t:`${t}.pptx`}function uE(t){var e;return ow((e=t.pptMeta)==null?void 0:e.transition)}function hE(t){return t instanceof Blob?t:new Blob([t],{type:$l})}function fE(t,e){const n=document.createElement("a");n.setAttribute("style","display:none;"),n.dataset.interception="off",document.body.appendChild(n);const r=window.URL.createObjectURL(t.type===$l?t:new Blob([t],{type:$l}));n.href=r,n.download=e,n.click(),setTimeout(()=>{window.URL.revokeObjectURL(r),document.body.removeChild(n)},100)}class $s extends Error{constructor(e,n){super(`媒体文件超过导出上限 (${Gl(e)} / ${Gl(n)})`),this.size=e,this.limit=n,this.name="ExportMediaTooLargeError"}}function mE(t){return t&&typeof t=="object"&&typeof t.text=="string"}function Vr(t){if(mE(t))return[t];const e=[],n=t==null?void 0:t.children;if(Array.isArray(n))for(const r of n)e.push(...Vr(r));return e}function Jp(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){const e=Number.parseFloat(t);if(Number.isFinite(e))return e}}function pE(t,e,n,r){const s={},a=Jp(t["font-size"]),i=a?Math.max(6,Math.round(a*n)):r;s.fontSize=i;const l=t["font-weight"],d=l?Number(l):NaN;(l==="bold"||t.bold||!Number.isNaN(d)&&d>=500)&&(s.bold=!0);const c=cr(t.color);return c&&(s.color=c),t.italic&&(s.italic=!0),t.underline&&(s.underline={style:"sng"}),e&&(s.breakLine=!0),{text:t.text,options:s}}function Uh(t,e){const n=[],r=Math.max(6,Math.round(cE*e));for(let s=0;s<t.length;s++){const a=s===t.length-1,i=Vr(t[s]);if(i.length===0){a||n.push({text:"",options:{breakLine:!0}});continue}for(let l=0;l<i.length;l++){const c=l===i.length-1&&!a;n.push(pE(i[l],c,e,r))}}return n.length===0?null:n.some(s=>{var a;return(a=s.text)==null?void 0:a.trim()})?n:null}function Ia(t,e){const n=t.data;if(n&&Array.isArray(n)){const s=Uh(n,e);if(s){const a=Ul(n[0]);return{rows:s,align:a}}}const r=t.text;if(r&&typeof r=="object"&&"children"in r){const s=Uh([r],e);if(s){const a=Ul(r);return{rows:s,align:a}}}return null}function Ul(t){if(!t||typeof t!="object")return;const e=t.align;if(e==="center"||e==="right"||e==="left")return e}function gE(t,e,n,r){const s=t.text,a=t.data;let i=r,l=n;const d=[];Array.isArray(a)&&d.push(...a),s&&typeof s=="object"&&d.push(s);for(const c of d){const h=Ul(c);if(h){i=h;break}}for(const c of d){const h=Vr(c);for(const u of h){const p=Jp(u["font-size"]);if(p&&p>0)return l=Math.max(6,Math.round(p*e)),{align:i,fontSizePt:l}}}return{align:i,fontSizePt:l}}function yE(t,e){const n=t.data;if(Array.isArray(n)&&n.length>0){const s=n.map(a=>Vr(a).map(l=>l.text||"").join("")).filter(a=>a.length>0);if(s.length>0)return s.join(`
|
|
203
203
|
`)}const r=t.text;if(r&&typeof r=="object"&&"children"in r){const s=r.children;if(Array.isArray(s)){const a=[];if(s.some(l=>l&&typeof l=="object"&&Array.isArray(l.children)))for(const l of s){const c=Vr(l).map(h=>h.text||"").join("");c.length>0&&a.push(c)}else{const l=Vr(r).map(d=>d.text||"").join("");l.length>0&&a.push(l)}if(a.length>0)return a.join(`
|
|
204
204
|
`)}}return $r(t,e)}function Is(t,e){return t.split(`
|
|
205
205
|
`).map((n,r,s)=>({text:n,options:{fontSize:e,...r<s.length-1?{breakLine:!0}:{}}}))}function ka(t){const e=t.replace(/\s+/g,"");return e?!t.includes(`
|