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,22 +1,22 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ai-chat-
|
|
2
|
-
import{_ as re}from"./startup-runtime-BrfuwjQS.js";import{c8 as yi,gD as wu,e3 as Vi,gE as yt,gF as $a,P as p,c7 as Va,bP as tt,gG as Wa,c6 as ii,U as qe,S as Mo,gH as Ae,gI as Nt,gJ as yu,a8 as d,R as on,ao as Ne,gK as tr,bd as F,gL as vu,gM as Ua,gN as nr,gO as vi,bh as Xe,bg as Ze,gP as Su,br as xu,ak as Te,ff as vn,fy as si,gQ as ku,bl as ee,gR as Eu,gS as bs,gT as ri,gU as ai,gV as bu,gW as to,gX as _u,gY as Pu,gZ as or,g_ as ir,g$ as sr,h0 as rr,h1 as Tu,h2 as ar,h3 as cr,h4 as Cu,h5 as Wi,h6 as Ui,aa as me,h7 as Iu,h8 as Au,h9 as Mu,ha as Ru,bQ as mo,a0 as pn,Z as Du,hb as lr,hc as Bo,hd as Lu,he as ju,hf as cn,hg as Ou,hh as Nu,hi as zu,hj as ur,bf as At,hk as Fu,hl as Bu,hm as Hu,hn as $u,ho as Vu,hp as Wu,hq as Uu,hr as Gu,hs as Ku,ht as qu,hu as Yu,hv as Xu,hw as Zu,hx as Ju,hy as Qu,hz as ed,hA as td,hB as nd,hC as Ga,hD as od,hE as Si,hF as ko,hG as id,eH as sd,at as de,hH as rd,dA as ad,eY as cd,hI as Sn,hJ as ld,hK as ud,bR as wo,hL as Gi,hM as ci,bS as _s,bT as no,bU as li,hN as Ka,hO as oo,hP as yo,hQ as dd,hR as hd,hS as fd,hT as gd,hU as pd,hV as qa,aq as Ya,bZ as md,hW as Xa,hX as Ki,hY as qi,ca as dr,hZ as wd,h_ as yd,h$ as vd,e4 as Ho,i0 as Za,cO as Yt,ba as Ja,dd as hr,i1 as Sd,i2 as xd,bb as Qa,b5 as kd,b7 as Ed,b8 as ec,i3 as bd,i4 as Ps,i5 as Mt,i6 as Rt,i7 as Dt,cm as Oe,i8 as _d,i9 as Pd,ia as Td,el as Ht,ib as Cd,bq as K,ic as Yi,bj as Se,id as Id,ie as Ad,ig as Md,ih as Rd,ii as Dd,ij as Ld,bL as jd,ik as Kt,il as tc,dU as nc,dV as ht,im as oc,io as ic,ip as Od,iq as En,ce as Nd,ar as Gn,ir as zd,ax as Fd,is as Bd,it as Ts,az as zt,bs as Pn,a1 as ve,dP as ie,iu as sc,dQ as Re,dR as He,dX as ui,iv as Hd,iw as $d,dY as Vd,dZ as Wd,gt as ge,ix as rc,iy as Ud,iz as Gd,iA as Kd,iB as qd,iC as Yd,iD as Xd,iE as Zd,gu as xt,iF as Jd,iG as Qd,iH as eh,dO as Le,iI as th,dI as ac,gs as io,eP as dt,iJ as cc,ab as Tt,iK as lc,iL as uc,iM as dc,iN as hc,iO as Cs,f5 as Is,f6 as fc,iP as gc,iQ as pc,iR as mc,iS as wc,iT as Xi,iU as yc,iV as vc,dW as Sc,b9 as nh,aY as oh,eI as $o,iW as ih,iX as sh,iY as rh,iZ as ah,i_ as ch,gA as lh,i$ as uh,gx as dh,gy as hh,dJ as bn,j0 as so,j1 as xc,gv as fr,j2 as fh,dN as gh,eg as ph,cj as mh,cg as wh,j3 as yh,j4 as kc,dK as Ec,j5 as As,j6 as vh,j7 as Sh,eh as di,j8 as Ms,j9 as Zi,ja as gr,bV as bc,bW as Rs,bX as Ds,bt as De,bY as _c,jb as sn,jc as Tn,jd as vo,je as rn,jf as pr,jg as Ji,aw as $e,aB as Pc,aA as Tc,jh as xh,bk as So,ji as kh,jj as Eh,jk as bh,jl as Cc,jm as Ic,jn as _h,jo as mr,jp as Qi,bN as Ph,bp as Ft,jq as Ac,jr as Th,js as Ch,jt as Ih,fq as Ah,ju as Mh,jv as Mc,jw as Rh,e8 as Dh,gh as Lh,ep as jh,jx as Oh,jy as Rc,jz as Nh,jA as zh,jB as Fh,jC as Bh,jD as Ls,jE as ro,jF as ao,jG as Dc,jH as Hh,jI as Pe,jJ as Vo,jK as Lc,b0 as jc,jL as xi,jM as wr,cG as $h,cI as Vh,cJ as Wh,c9 as Ro,cR as Oc,cQ as Nc,jN as Kn,jO as Uh,jP as Gh,jQ as yr,jR as rt,jS as zc,cd as vr,jT as Kh,bo as qh,jU as Fc,ev as Sr,jV as xr,bx as Yh,by as Xh,bz as Zh,jW as Jh,bA as Qh,jX as ef,jY as tf,jZ as nf,j_ as of,j$ as sf,k0 as rf,k1 as af,k2 as cf,dt as lf,k3 as uf,k4 as ki,k5 as df,k6 as hf,k7 as ff,fP as gf,k8 as pf}from"./ai-chat-B-XdoWBQ.js";import{s as co,T as kr,R as mn,l as mf,a as Bc,b as Do,u as hi,c as je,g as Hc,d as $c,i as wf,e as Vc,f as yf,h as vf,j as Sf,L as lo,k as js,m as Os,n as xf,o as kf,p as Ef,A as ln,D as Ei,B as Cn,q as bf,r as _f,t as fi,v as Er,w as Pf,x as Tf,y as Wc,z as Eo,C as un,E as dn,F as Cf,G as If,H as vt,I as Jt,J as Af,K as Mf,M as Rf,N as Df,O as Lf,P as jf,Q as Of,S as Nf,U as Ns,V as zf,W as zs,X as Ff,Y as br}from"./tool-windows-BnDZa9FH.js";import{t as Bf}from"./startup-app-9gZEGv85.js";const Uc="main_board_content",Gc=yi.createInstance({name:"Drawnix",storeName:wu,driver:[yi.INDEXEDDB,yi.LOCALSTORAGE]});async function Kc(){try{const e=await Vi.loadState();return(e==null?void 0:e.migrationCompleted)===!0}catch(e){return console.error("[WorkspaceMigration] Failed to check migration status:",e),!1}}async function _r(){try{const e=await Vi.loadState();e.migrationCompleted=!0,await Vi.saveState(e)}catch(e){console.error("[WorkspaceMigration] Failed to mark migration completed:",e)}}async function Hf(){try{const e=await Gc.getItem(Uc);if(e&&e.children&&e.children.length>0)return e;const t=localStorage.getItem($a);if(t){const n=JSON.parse(t);if(Array.isArray(n)&&n.length>0)return{children:n}}return null}catch(e){return console.error("[WorkspaceMigration] Failed to get legacy data:",e),null}}async function $f(){try{if(await Kc())return null;const t=await Hf();if(!t||!t.children||t.children.length===0)return await _r(),null;const n=yt.getInstance();await n.initialize();const o=await n.createBoard({name:"迁移的画板",elements:t.children,viewport:t.viewport,theme:t.theme});return o?(await n.switchBoard(o.id),await _r(),await Vf(),o.id):(console.error("[WorkspaceMigration] Failed to create board"),null)}catch(e){return console.error("[WorkspaceMigration] Migration failed:",e),null}}async function Vf(){try{await Gc.removeItem(Uc),localStorage.removeItem($a)}catch(e){console.error("[WorkspaceMigration] Failed to clear legacy data:",e)}}const Je={LOADING_STATE:"aitu_page_loading_state",CRASH_COUNT:"aitu_crash_count",LAST_SUCCESS_LOAD:"aitu_last_success_load",SAFE_MODE:"aitu_safe_mode",CRASH_HISTORY:"aitu_crash_history"};class Wf{constructor(){this.state={crashDetected:!1,crashCount:0,isSafeMode:!1,crashHistory:[]}}markLoadingStart(){try{localStorage.getItem(Je.LOADING_STATE)==="loading"&&(this.state.crashDetected=!0,this.incrementCrashCount(),this.recordCrash()),localStorage.setItem(Je.LOADING_STATE,"loading"),this.state.isSafeMode=localStorage.getItem(Je.SAFE_MODE)==="true",this.loadCrashHistory()}catch(t){console.warn("[CrashRecovery] Failed to mark loading start:",t)}}markLoadingComplete(){try{localStorage.setItem(Je.LOADING_STATE,"complete"),localStorage.setItem(Je.LAST_SUCCESS_LOAD,Date.now().toString()),this.state.isSafeMode||(localStorage.setItem(Je.CRASH_COUNT,"0"),this.state.crashCount=0)}catch(t){console.warn("[CrashRecovery] Failed to mark loading complete:",t)}}incrementCrashCount(){try{const t=parseInt(localStorage.getItem(Je.CRASH_COUNT)||"0",10);this.state.crashCount=t+1,localStorage.setItem(Je.CRASH_COUNT,this.state.crashCount.toString())}catch{}}recordCrash(){try{const t=performance,n={timestamp:Date.now(),url:window.location.href,memoryStats:t.memory?{usedJSHeapSize:t.memory.usedJSHeapSize,totalJSHeapSize:t.memory.totalJSHeapSize,jsHeapSizeLimit:t.memory.jsHeapSizeLimit}:null};this.state.crashHistory.unshift(n),this.state.crashHistory=this.state.crashHistory.slice(0,10),this.saveCrashHistory()}catch{}}loadCrashHistory(){try{const t=localStorage.getItem(Je.CRASH_HISTORY);t&&(this.state.crashHistory=JSON.parse(t))}catch{this.state.crashHistory=[]}}saveCrashHistory(){try{localStorage.setItem(Je.CRASH_HISTORY,JSON.stringify(this.state.crashHistory))}catch{}}getState(){return{...this.state}}isCrashDetected(){return this.state.crashDetected}getCrashCount(){return this.state.crashCount}isSafeMode(){return this.state.isSafeMode}shouldShowSafeModePrompt(){return this.state.crashDetected&&this.state.crashCount>=2}enableSafeMode(){try{localStorage.setItem(Je.SAFE_MODE,"true"),this.state.isSafeMode=!0}catch{}}disableSafeMode(){try{localStorage.removeItem(Je.SAFE_MODE),this.state.isSafeMode=!1,localStorage.setItem(Je.CRASH_COUNT,"0"),this.state.crashCount=0}catch{}}clearCrashState(){try{localStorage.setItem(Je.CRASH_COUNT,"0"),this.state.crashCount=0,this.state.crashDetected=!1}catch{}}checkUrlSafeMode(){try{const t=new URLSearchParams(window.location.search);if(t.get("safe")==="1"||t.get("safe_mode")==="1")return this.enableSafeMode(),!0}catch{}return!1}getMemoryInfo(){try{const t=performance;if(!t.memory)return null;const n=o=>o<1024*1024?`${(o/1024).toFixed(1)} KB`:o<1024*1024*1024?`${(o/1024/1024).toFixed(1)} MB`:`${(o/1024/1024/1024).toFixed(2)} GB`;return{used:n(t.memory.usedJSHeapSize),limit:n(t.memory.jsHeapSizeLimit),percent:t.memory.usedJSHeapSize/t.memory.jsHeapSizeLimit*100}}catch{return null}}}const et=new Wf,Uf="Opentu",Gf="Opentu - AI应用平台";function qn(e){e&&e.trim()?document.title=`${Uf} - ${e.trim()}`:document.title=Gf}function Kf(e){if(!e){qn();return}const t=Va.getBoard(e);qn(t==null?void 0:t.name)}function qf(e,t){return p.useEffect(()=>{t!==void 0?qn(t):Kf(e)},[e,t]),p.useEffect(()=>{const o=Va.observeEvents().subscribe(i=>{if(i.type==="boardUpdated"){const s=i.payload;s&&s.id===e&&qn(s.name)}});return()=>{o.unsubscribe()}},[e]),{updateTitle:p.useCallback(o=>{qn(o)},[])}}const es="aitu-tab-sync-version",Yf=500,ts=`tab-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;function qc({onSyncNeeded:e,enabled:t=!0,currentBoardId:n}){const o=p.useRef(-1),i=p.useRef();p.useEffect(()=>{if(!t)return;const s=localStorage.getItem(es);if(s)try{const r=JSON.parse(s);o.current=r.version}catch{o.current=parseInt(s,10)||Date.now()}else o.current=Date.now()},[t]),p.useEffect(()=>{if(!t)return;const s=()=>{const a=localStorage.getItem(es);if(a)try{const c=JSON.parse(a);if(c.version>o.current&&c.tabId!==ts){const u=n&&c.boardId&&c.boardId===n;o.current=c.version,u&&e()}else c.version>o.current&&c.tabId===ts&&(o.current=c.version)}catch{const c=parseInt(a,10);c>o.current&&(o.current=c)}};i.current=setInterval(()=>{document.hidden||s()},Yf);const r=()=>{document.hidden||s()};return document.addEventListener("visibilitychange",r),()=>{i.current&&clearInterval(i.current),document.removeEventListener("visibilitychange",r)}},[t,e,n])}function Yc(e){try{const n={version:Date.now(),tabId:ts,boardId:e};localStorage.setItem(es,JSON.stringify(n))}catch{}}const fS=Object.freeze(Object.defineProperty({__proto__:null,markTabSyncVersion:Yc,useTabSync:qc},Symbol.toStringTag,{value:"Module"}));function In(e){if(!tt.isAnalyticsEnabled())return;const t=Xf(e.name,e.value),n=document.referrer,o={[`$web_vitals_${e.name}_value`]:e.value,[`$web_vitals_${e.name}_event`]:{id:e.id,delta:e.delta,rating:t,navigationType:e.navigationType},page_path:window.location.pathname,referrer:n.length>200?n.slice(0,200):n,timestamp:Date.now()};setTimeout(()=>{tt.track("$web_vitals",o)},0)}function Xf(e,t){const o={LCP:{good:2500,poor:4e3},FID:{good:100,poor:300},CLS:{good:.1,poor:.25},FCP:{good:1800,poor:3e3},TTFB:{good:800,poor:1800},INP:{good:200,poor:500}}[e];return o?t<=o.good?"good":t<=o.poor?"needs-improvement":"poor":"needs-improvement"}async function Zf(){try{const e=await re(()=>import("./web-vitals-DcvjKPr-.js"),[],import.meta.url),{onCLS:t,onFCP:n,onLCP:o,onTTFB:i,onINP:s}=e;t(In),n(In),o(In),i(In),s(In)}catch(e){console.error("[Web Vitals] Failed to initialize monitoring:",e)}}const uo="page_report",Jf="app_page_view";let Pr=!1,Tr="";function Qf(){const e=window.innerWidth;return e<768?"mobile":e<1024?"tablet":"desktop"}const Cr=200;function eg(){const e=navigator.userAgent;return{page_url:window.location.href,page_path:window.location.pathname,page_title:document.title,referrer:document.referrer,viewport_width:window.innerWidth,viewport_height:window.innerHeight,screen_width:window.screen.width,screen_height:window.screen.height,device_type:Qf(),user_agent:e.length>Cr?e.slice(0,Cr):e,language:navigator.language,timestamp:Date.now()}}function tg(){if(!window.performance)return null;const e={page_url:window.location.pathname,page_path:window.location.pathname,timestamp:Date.now()};if(window.performance.getEntriesByType){const t=window.performance.getEntriesByType("navigation");if(t&&t.length>0){const n=t[0];n.domainLookupEnd&&n.domainLookupStart&&(e.dns_time=n.domainLookupEnd-n.domainLookupStart),n.connectEnd&&n.connectStart&&(e.tcp_time=n.connectEnd-n.connectStart),n.responseStart&&n.requestStart&&(e.request_time=n.responseStart-n.requestStart),n.responseEnd&&n.responseStart&&(e.response_time=n.responseEnd-n.responseStart),n.domComplete&&n.domInteractive&&(e.dom_processing_time=n.domComplete-n.domInteractive),n.domInteractive&&n.fetchStart&&(e.dom_interactive_time=n.domInteractive-n.fetchStart),n.domComplete&&n.fetchStart&&(e.dom_complete_time=n.domComplete-n.fetchStart),n.loadEventEnd&&n.fetchStart&&(e.load_time=n.loadEventEnd-n.fetchStart)}}if(window.performance.getEntriesByType){const t=window.performance.getEntriesByType("resource");e.total_resources=t.length,e.total_size=t.reduce((n,o)=>n+(o.transferSize||0),0)}return e}function bi(){if(!tt.isAnalyticsEnabled())return;const e=eg();e.page_url!==Tr&&(Tr=e.page_url,tt.track(Jf,{category:uo,...e}))}function Ir(){if(!tt.isAnalyticsEnabled())return;const e=tg();if(!e){console.warn("[Page Report] Performance data not available");return}tt.track("page_performance",{category:uo,...e})}function ng(){if(!tt.isAnalyticsEnabled())return;const e=Math.round(performance.now());tt.track("page_unload",{category:uo,page_url:window.location.href,page_path:window.location.pathname,time_on_page:e,timestamp:Date.now()})}function og(){try{if(Pr)return;Pr=!0,bi(),document.readyState==="complete"?Ir():window.addEventListener("load",()=>{setTimeout(()=>{Ir()},0)}),window.addEventListener("beforeunload",()=>{ng()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?tt.track("page_hidden",{category:uo,page_url:window.location.href,page_path:window.location.pathname,timestamp:Date.now()}):document.visibilityState==="visible"&&tt.track("page_visible",{category:uo,page_url:window.location.href,page_path:window.location.pathname,timestamp:Date.now()})}),window.addEventListener("popstate",()=>{setTimeout(()=>{bi()},100)});const e=history.pushState;history.pushState=function(...t){e.apply(this,t),setTimeout(()=>{bi()},100)}}catch(e){console.error("[Page Report] Failed to initialize monitoring:",e)}}function Ar(e){if(!e||!(e instanceof Element))return!1;const t=e,n=["input","textarea","select","button",".unified-toolbar",".chat-drawer",".side-drawer",".toolbox-drawer",".project-drawer",".popup-toolbar",".t-dialog",".t-drawer",".t-popup",".t-popover",".Dialog",".winbox",".ai-input-bar",".view-navigation",".minimap",".task-queue-panel",".t-slider",".unified-color-picker",".media-library",".viewer-container",".viewer-canvas",".viewer-footer",".viewer-toolbar",".unified-viewer",".media-viewport",".thumbnail-queue",'[role="button"]','[role="slider"]','[role="menu"]','[role="menuitem"]','[role="dialog"]',"[data-allow-touch]"];for(const o of n)if(t.matches(o)||t.closest(o))return!0;if(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth){const o=window.getComputedStyle(t);if(o.overflowY==="auto"||o.overflowY==="scroll"||o.overflowX==="auto"||o.overflowX==="scroll")return!0}return!1}function Mr(e){if(!e||!(e instanceof Element))return!1;const t=e,n=[".plait-board-container",".plait-board","[plait-board]","svg.rough-svg"];for(const o of n)if(t.matches(o)||t.closest(o))return!0;return!1}function ig(){if(typeof window>"u")return()=>{};const e=o=>{if(o.touches.length>1){const i=o.target;if(Ar(i))return;Mr(i)&&(o.preventDefault(),o.stopPropagation())}},t=o=>{const i=o.target;Ar(i)||Mr(i)&&(o.preventDefault(),o.stopPropagation())},n=o=>{(o.ctrlKey||o.metaKey)&&o.preventDefault()};return document.addEventListener("touchstart",e,{passive:!1,capture:!0}),document.addEventListener("touchmove",e,{passive:!1,capture:!0}),document.addEventListener("touchend",e,{passive:!1,capture:!0}),document.addEventListener("gesturestart",t,{passive:!1,capture:!0}),document.addEventListener("gesturechange",t,{passive:!1,capture:!0}),document.addEventListener("gestureend",t,{passive:!1,capture:!0}),window.addEventListener("wheel",n,{passive:!1}),()=>{document.removeEventListener("touchstart",e,!0),document.removeEventListener("touchmove",e,!0),document.removeEventListener("touchend",e,!0),document.removeEventListener("gesturestart",t,!0),document.removeEventListener("gesturechange",t,!0),document.removeEventListener("gestureend",t,!0),window.removeEventListener("wheel",n)}}const ns=ii.DB_CLEANUP_DONE;function Xc(){let e=0;for(const t of Wa)try{localStorage.getItem(t)!==null&&(localStorage.removeItem(t),e++)}catch(n){console.warn(`[DBCleanup] Failed to remove LocalStorage key ${t}:`,n)}return e}async function Zc(){localStorage.getItem(ns)||(Xc(),localStorage.setItem(ns,Date.now().toString()))}function sg(){localStorage.removeItem(ns)}typeof window<"u"&&(window.__dbCleanup={run:Zc,reset:sg,cleanupLS:Xc,LS_KEYS_DEPRECATED:Wa});const Fs=[{lsKey:qe.PROMPT_HISTORY,idbKey:qe.PROMPT_HISTORY,deleteAfterMigration:!0},{lsKey:qe.VIDEO_PROMPT_HISTORY,idbKey:qe.VIDEO_PROMPT_HISTORY,deleteAfterMigration:!0},{lsKey:qe.PRESET_SETTINGS,idbKey:qe.PRESET_SETTINGS,deleteAfterMigration:!0},{lsKey:qe.BATCH_IMAGE_CACHE,idbKey:qe.BATCH_IMAGE_CACHE,deleteAfterMigration:!0},{lsKey:qe.RECENT_TEXT_COLORS,idbKey:qe.RECENT_TEXT_COLORS,deleteAfterMigration:!0},{lsKey:qe.CUSTOM_GRADIENTS,idbKey:qe.CUSTOM_GRADIENTS,deleteAfterMigration:!0},{lsKey:qe.CUSTOM_FONTS,idbKey:qe.CUSTOM_FONTS,deleteAfterMigration:!0},{lsKey:qe.TOOLBAR_CONFIG,idbKey:qe.TOOLBAR_CONFIG,deleteAfterMigration:!0}];function Bs(){try{return localStorage.getItem(ii.LS_TO_IDB_MIGRATION_DONE)!==null}catch{return!1}}function rg(){try{localStorage.setItem(ii.LS_TO_IDB_MIGRATION_DONE,Date.now().toString())}catch(e){console.error("[StorageMigration] Failed to mark migration done:",e)}}function ag(e){try{const t=localStorage.getItem(e);return t===null?null:JSON.parse(t)}catch(t){return console.warn(`[StorageMigration] Failed to read ${e} from LocalStorage:`,t),null}}function Rr(e){try{localStorage.removeItem(e)}catch(t){console.warn(`[StorageMigration] Failed to delete ${e} from LocalStorage:`,t)}}async function cg(e){const{lsKey:t,idbKey:n,deleteAfterMigration:o}=e;try{const i=ag(t);return i===null?{key:t,success:!0}:await Mo.get(n)!==null?(o&&Rr(t),{key:t,success:!0}):(await Mo.set(n,i),await Mo.get(n)===null?{key:t,success:!1,error:"Verification failed: data not found after write"}:(o&&Rr(t),{key:t,success:!0}))}catch(i){const s=i instanceof Error?i.message:String(i);return console.error(`[StorageMigration] Failed to migrate ${t}:`,i),{key:t,success:!1,error:s}}}async function Jc(){if(!Mo.isAvailable())return console.warn("[StorageMigration] IndexedDB not available, skipping migration"),[];if(Bs())return[];const e=[];for(const n of Fs){const o=await cg(n);e.push(o),o.success||console.warn(`[StorageMigration] Failed: ${o.key} - ${o.error}`)}return e.filter(n=>n.success).length,e.filter(n=>!n.success).length===0&&rg(),e}function Qc(){try{localStorage.removeItem(ii.LS_TO_IDB_MIGRATION_DONE)}catch(e){console.error("[StorageMigration] Failed to reset migration status:",e)}}const lg={isMigrationDone:Bs,runMigration:Jc,resetMigration:Qc,MIGRATION_CONFIGS:Fs};typeof window<"u"&&(window.__storageMigration={run:Jc,reset:Qc,isDone:Bs,configs:Fs});const os=new Set,Dr=4,Lr=1e3;function jr(e){e.forEach(t=>os.delete(t))}function Or(){const e=typeof navigator<"u"?navigator.connection:void 0;return e?e.saveData?!1:e.effectiveType!=="slow-2g"&&e.effectiveType!=="2g":!0}function el(e){if(typeof window>"u"||!("serviceWorker"in navigator)||e.length===0||!Or()){e.length,Or();return}const t=e.filter(s=>os.has(s)?!1:(os.add(s),!0));if(t.length===0)return;const n={type:"SW_PREFETCH_GROUPS",groups:t},o=(s=1)=>{const r=navigator.serviceWorker.controller;if(r){r.postMessage(n);return}navigator.serviceWorker.ready.then(a=>{if(a.active){a.active.postMessage(n);return}if(s>=Dr){jr(t),console.warn("[StartupPrefetch] idle prefetch request dropped: no active service worker",{groups:t,attempt:s});return}window.setTimeout(()=>o(s+1),Lr)}).catch(a=>{if(s>=Dr){jr(t),console.warn("[StartupPrefetch] idle prefetch request failed after retries",{groups:t,attempt:s,error:a});return}window.setTimeout(()=>o(s+1),Lr)})},i=window.requestIdleCallback;typeof i=="function"?i(()=>o(),{timeout:1500}):window.setTimeout(o,400)}const ug=3e4,dg=800,hg=.6,fg=3,Hs="aitu_last_snapshot",gg=50,Yn=[],pg=20,mg=2e3;let Xn=null;const Nr=3e3,wg=1e4,yg=200,vg=5e3,Sg=10,xg=5e3,kg=30,Eg=20,zr=20,bg=100,_g=30,Pg=240;function Tg(e){if(e&&typeof e=="object"&&"name"in e){const t=e.name;return typeof t=="string"?t:""}return""}function Cg(e,t=""){if(e&&typeof e=="object"&&"message"in e){const n=e.message;if(typeof n=="string")return n}return typeof e=="string"?e:t}function Fr(e,t=""){const n=Tg(e),o=Cg(e,t),i=n==="AbortError"||o.startsWith("AbortError:")||o.includes("AbortError"),s=n==="NotAllowedError"||o.startsWith("NotAllowedError:"),r=n==="DataError"||o.startsWith("DataError:");return o.includes("ResizeObserver loop completed with undelivered notifications")||o.includes("ResizeObserver loop limit exceeded")||o.includes("WebCodecs API")&&(o.includes("Chrome 94+")||o.includes("Edge 94+"))||i&&(o.includes("The user aborted a request")||o.includes("Failed to execute 'showOpenFilePicker'")||o.includes("Failed to execute 'showSaveFilePicker'"))||s&&o.includes("Failed to execute 'write' on 'Clipboard'")&&o.includes("permissions policy")?!0:r&&o.includes("No key or key range specified")}let Br=null,Hr=!1,$r=null,Vr=null,_i=null,Pi=0,Zt=60,Hn=!1,Ti=!1;const Qt=[],en=[],St=[];function Ig(e){const t=Ue(),n=Date.now();return()=>{const o=Ue();if(!t||!o)return;const i=(o.usedJSHeapSize-t.usedJSHeapSize)/(1024*1024),s=Date.now()-n;if(Math.abs(i)>=gg){const r=i>=0?"+":"";console.warn(`[MemoryLog] ${e}: ${r}${i.toFixed(0)} MB (${s}ms)`)}}}function mt(e){if(e)return e.slice(0,Pg)}function Ag(){return"1.0.0"}function Mg(){if(typeof navigator>"u"||typeof window>"u"||!("serviceWorker"in navigator))return{supported:!1,readyState:document.readyState,visibilityState:document.visibilityState};const e=navigator.serviceWorker.controller;return{supported:!0,controller:e?{scriptURL:mt(e.scriptURL),state:e.state}:null,readyState:document.readyState,visibilityState:document.visibilityState}}function Rg(){const e=Array.from(document.scripts).map(o=>mt(Nt(o.src))).filter(Boolean).slice(-8),t=Array.from(document.querySelectorAll('link[rel="stylesheet"]')).map(o=>mt(Nt(o.href))).filter(Boolean).slice(-8),n=Array.from(document.querySelectorAll('link[rel="modulepreload"]')).map(o=>mt(Nt(o.href))).filter(Boolean).slice(-8);return{scripts:e,stylesheets:t,modulePreloads:n}}function tl(e){if(!(e instanceof HTMLElement))return;const t=e;return{tagName:e.tagName.toLowerCase(),id:mt(e.id||void 0),className:typeof e.className=="string"?mt(e.className):void 0,src:mt(t.currentSrc||t.src?Nt(t.currentSrc||t.src||""):void 0),href:mt(t.href?Nt(t.href):void 0),rel:mt(t.rel),crossOrigin:mt(t.crossOrigin||void 0)}}function is(e){return{appVersion:Ag(),recentActions:Qt.slice(-10),recentErrors:en.slice(-5),recentNetworkErrors:St.slice(-5),serviceWorker:Mg(),loadedResources:Rg(),...e}}function Ue(){if(typeof performance<"u"&&"memory"in performance){const e=performance.memory;return{usedJSHeapSize:e.usedJSHeapSize,totalJSHeapSize:e.totalJSHeapSize,jsHeapSizeLimit:e.jsHeapSizeLimit}}}function _n(){try{const e={domNodeCount:document.getElementsByTagName("*").length,canvasCount:document.getElementsByTagName("canvas").length,imageCount:document.getElementsByTagName("img").length,videoCount:document.getElementsByTagName("video").length,iframeCount:document.getElementsByTagName("iframe").length,plaitBoardExists:!!document.querySelector(".plait-board-container")},t=document.querySelector(".plait-board-container");if(t){const n=t.querySelectorAll("svg > g > g");e.plaitElementCount=n.length}return window.getEventListeners,e}catch{return{domNodeCount:0,canvasCount:0,imageCount:0,videoCount:0,iframeCount:0,plaitBoardExists:!1}}}function nl(){if(!Ae.isInitialized()||Yn.length===0)return;const e=Yn.splice(0,Yn.length);for(const t of e)Ae.reportCrashSnapshot(t).catch(()=>{});Xn&&(clearInterval(Xn),Xn=null)}function Dg(){Xn||(Xn=setInterval(()=>{Ae.isInitialized()&&nl()},mg))}function at(e){try{Ae.isInitialized()?(nl(),Ae.reportCrashSnapshot(e).catch(()=>{})):Yn.length<pg&&(Yn.push(e),Dg())}catch(t){console.warn("[MemoryLog] Failed to send snapshot to SW:",t)}}function Lg(e){try{localStorage.setItem(Hs,JSON.stringify(e))}catch{}}function jg(){try{const e=localStorage.getItem(Hs);if(e)return JSON.parse(e)}catch{}return null}function Og(){try{localStorage.removeItem(Hs)}catch{}}function Ng(){const e={id:`startup-${Date.now()}`,timestamp:Date.now(),type:"startup",userAgent:navigator.userAgent,url:location.href,memory:Ue()};at(e)}function zg(){if(Br!==null)return;let e=0;Br=window.setInterval(()=>{const t=Ue();if(!t)return;const n=t.usedJSHeapSize/(1024*1024),o=t.jsHeapSizeLimit/(1024*1024),i=n/o;if(n>dg||i>hg){e++;const a=e>=fg?_n():void 0,c={id:`periodic-${Date.now()}`,timestamp:Date.now(),type:"periodic",memory:t,pageStats:a,userAgent:navigator.userAgent,url:location.href};at(c)}else e=0},ug)}function Fg(){window.addEventListener("error",e=>{var n;if(Fr(e.error,e.message))return;const t={id:`error-${Date.now()}`,timestamp:Date.now(),type:"error",error:{message:e.message||"Unknown error",stack:(n=e.error)==null?void 0:n.stack,type:"uncaughtError"},memory:Ue(),userAgent:navigator.userAgent,url:location.href,customData:is({filename:e.filename,lineno:e.lineno,colno:e.colno,eventTarget:tl(e.target)})};at(t),console.error("[MemoryLog] Uncaught error captured:",e.message)}),window.addEventListener("unhandledrejection",e=>{const t=e.reason,n=(t==null?void 0:t.message)||String(t)||"",o=(t==null?void 0:t.stack)||"";if(Fr(t,n)||n.includes("posthog.com")||o.includes("posthog"))return;const i={id:`rejection-${Date.now()}`,timestamp:Date.now(),type:"error",error:{message:n||"Unhandled Promise rejection",stack:o,type:"unhandledRejection"},memory:Ue(),userAgent:navigator.userAgent,url:location.href,customData:is()};at(i),console.error("[MemoryLog] Unhandled rejection captured:",t)}),window.addEventListener("beforeunload",()=>{const e=Ue();if(e){const t={id:`beforeunload-${Date.now()}`,timestamp:Date.now(),type:"beforeunload",memory:e,userAgent:navigator.userAgent,url:location.href};Lg(t),at(t)}})}function Bg(){if($r!==null)return;let e=Date.now();document.addEventListener("visibilitychange",()=>{document.hidden?Ti=!0:(e=Date.now(),setTimeout(()=>{Ti=!1},Nr+100))}),$r=window.setInterval(()=>{const t=Date.now(),n=t-e;if(n>wg&&!Ti&&!document.hidden){const o={id:`freeze-${Date.now()}`,timestamp:Date.now(),type:"freeze",memory:Ue(),pageStats:_n(),performance:{freezeDuration:n,lastHeartbeat:e,fps:Zt},userAgent:navigator.userAgent,url:location.href,customData:{recentActions:Qt.slice(-10),recentErrors:en.slice(-5),recentNetworkErrors:St.slice(-5)}};at(o)}e=t,Ae.isInitialized()&&Ae.sendHeartbeat(t).catch(()=>{})},Nr)}function Hg(){if(_i===null&&!(typeof PerformanceObserver>"u"))try{_i=new PerformanceObserver(e=>{for(const t of e.getEntries())if(t.duration>yg){const o=t.attribution;let i;if(o&&o.length>0){const r=o[0];i={name:r.name,containerType:r.containerType,containerSrc:r.containerSrc,containerId:r.containerId,containerName:r.containerName}}const s={id:`longtask-${Date.now()}`,timestamp:Date.now(),type:"longtask",memory:Ue(),performance:{longTaskDuration:t.duration,fps:Zt},userAgent:navigator.userAgent,url:location.href,customData:{taskName:t.name,startTime:t.startTime,attribution:i,debugTip:"Use Chrome DevTools Performance panel to record and analyze the call stack"}};at(s)}}),_i.observe({entryTypes:["longtask"]})}catch{}}function $g(){if(Vr!==null)return;let e=0;const t=()=>{if(e++,e>=_g){const n=performance.now(),o=n-Pi;o>0&&(Zt=Math.round(e*1e3/o)),e=0,Pi=n}requestAnimationFrame(t)};Pi=performance.now(),requestAnimationFrame(t),Vr=window.setInterval(()=>{if(Zt<Sg&&Zt>0){const n={id:`lowfps-${Date.now()}`,timestamp:Date.now(),type:"freeze",memory:Ue(),performance:{fps:Zt},userAgent:navigator.userAgent,url:location.href};at(n)}},vg)}function Vg(){setTimeout(()=>{Wr()},xg),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&!Hn&&setTimeout(Wr,1e3)})}function Wr(){if(Hn)return;const e=document.getElementById("root"),t=e&&e.children.length>0,o=!!document.querySelector(".plait-board-container");if(document.body.children.length>1,e&&!t){Hn=!0;const i={id:`whitescreen-${Date.now()}`,timestamp:Date.now(),type:"whitescreen",memory:Ue(),pageStats:{domNodeCount:document.getElementsByTagName("*").length,canvasCount:0,imageCount:0,videoCount:0,iframeCount:0,plaitBoardExists:o},userAgent:navigator.userAgent,url:location.href,customData:{rootExists:!!e,rootChildCount:(e==null?void 0:e.children.length)||0,bodyChildCount:document.body.children.length,hasPlaitBoard:o}};at(i),console.error("[MemoryLog] 白屏检测: React 未渲染内容")}t&&!o&&location.pathname==="/"&&setTimeout(()=>{if(!document.querySelector(".plait-board-container")&&!Hn){Hn=!0;const i={id:`whitescreen-noboard-${Date.now()}`,timestamp:Date.now(),type:"whitescreen",memory:Ue(),pageStats:_n(),userAgent:navigator.userAgent,url:location.href,customData:{reason:"画板未加载",rootChildCount:(e==null?void 0:e.children.length)||0}};at(i),console.error("[MemoryLog] 白屏检测: 画板组件未加载")}},5e3)}function $n(e,t,n){Qt.push({time:Date.now(),action:e,target:t,detail:n}),Qt.length>kg&&Qt.shift()}function Wg(){let e=0;document.addEventListener("click",t=>{const n=Date.now();if(n-e<bg)return;e=n;const o=t.target;if(!o)return;const i=()=>{var a,c,u,l,h,f,g,y,m,w,S,v,E,C,D;let s="";const r=(c=(a=o.closest)==null?void 0:a.call(o,"[data-track]"))==null?void 0:c.getAttribute("data-track");if(r)s=r;else if(o.tagName==="BUTTON"||(u=o.closest)!=null&&u.call(o,"button")){const P=((l=o.closest)==null?void 0:l.call(o,"button"))||o,H=(h=P.textContent)==null?void 0:h.trim().slice(0,20),B=(m=(y=(g=(f=P.className)==null?void 0:f.split)==null?void 0:g.call(f," "))==null?void 0:y[0])==null?void 0:m.slice(0,20);s=`btn:${H||B||"unknown"}`}else if(o.tagName==="A")s=`link:${((w=o.pathname)==null?void 0:w.slice(0,30))||""}`;else if(o.tagName==="INPUT"||o.tagName==="TEXTAREA"){const P=o;s=`input:${P.name||P.type||((S=P.placeholder)==null?void 0:S.slice(0,15))||""}`}else if(o.id)s=`#${o.id}`;else{const P=(C=(E=(v=o.className)==null?void 0:v.split)==null?void 0:E.call(v," "))==null?void 0:C[0];s=P?`.${P.slice(0,20)}`:((D=o.tagName)==null?void 0:D.toLowerCase())||"unknown"}$n("click",s)};"requestIdleCallback"in window?window.requestIdleCallback(i,{timeout:100}):setTimeout(i,0)},{capture:!0,passive:!0}),document.addEventListener("keydown",t=>{if(t.ctrlKey||t.metaKey||t.altKey){const n=[];(t.ctrlKey||t.metaKey)&&n.push("Cmd"),t.altKey&&n.push("Alt"),t.shiftKey&&n.push("Shift"),n.push(t.key),$n("shortcut",n.join("+"))}},{capture:!0,passive:!0}),window.addEventListener("popstate",()=>{$n("navigate",location.pathname)}),window.addEventListener("hashchange",()=>{$n("navigate",location.hash)})}function Ug(){const e=window.fetch;window.fetch=async function(t,n){const o=Date.now();try{const i=await e.call(this,t,n);if(!i.ok){const s=typeof t=="string"?t:t.url,r=Date.now()-o,a=Nt(s).slice(0,300);St.push({time:Date.now(),url:a,method:(n==null?void 0:n.method)||"GET",status:i.status,statusText:i.statusText,duration:r}),St.length>zr&&St.shift()}return i}catch(i){const s=typeof t=="string"?t:t.url,r=Date.now()-o,a=Nt(s).slice(0,300);throw St.push({time:Date.now(),url:a,method:(n==null?void 0:n.method)||"GET",error:i.message,duration:r}),St.length>zr&&St.shift(),i}}}function Gg(){window.addEventListener("error",e=>{var n;const t=e.target;if(t&&t!==window&&t instanceof HTMLElement&&("src"in t||"href"in t)){const o=t.src||t.href,i=(n=t.tagName)==null?void 0:n.toLowerCase();$n("resource_error",i,o==null?void 0:o.slice(0,100));const s={id:`resource-error-${Date.now()}`,timestamp:Date.now(),type:"error",error:{message:`Resource load failed: ${i||"unknown"}`,type:"resourceError"},memory:Ue(),userAgent:navigator.userAgent,url:location.href,customData:is({resourceUrl:mt(o?Nt(o):void 0),eventTarget:tl(t)})};at(s)}},{capture:!0})}function Kg(){const e=console.error;console.error=function(...t){e.apply(this,t);const n=t[0];if(typeof n=="string"&&n.includes("[MemoryLog]"))return;const o=[...t];setTimeout(()=>{var r;let i="",s;for(let a=0;a<Math.min(o.length,5);a++){const c=o[a];if(typeof c=="string")i+=c+" ";else if(typeof c=="number"||typeof c=="boolean")i+=String(c)+" ";else if(c instanceof Error)i+=`Error: ${c.message} `,s=c.stack;else if(c&&typeof c=="object")try{const l=Object.keys(c).slice(0,5).map(h=>{const f=c[h];return`${h}:${typeof f=="string"?f.slice(0,20):typeof f}`}).join(",");i+=`{${l}} `}catch{i+=`[${((r=c.constructor)==null?void 0:r.name)||"Object"}] `}}en.push({time:Date.now(),message:i.trim().slice(0,500),stack:s}),en.length>Eg&&en.shift()},0)}}function ol(){return{userActions:[...Qt],consoleErrors:[...en],networkErrors:[...St],memory:Ue(),pageStats:_n(),fps:Zt}}function qg(){typeof window>"u"||(window.__memoryLog={getMemory:()=>{const e=Ue();return e?{usedMB:(e.usedJSHeapSize/1024/1024).toFixed(1),limitMB:(e.jsHeapSizeLimit/1024/1024).toFixed(0),percent:(e.usedJSHeapSize/e.jsHeapSizeLimit*100).toFixed(1)}:null},track:Ig,diagnose:()=>{const e=Ue(),t=_n();return t.imageCount>50&&console.warn("图片较多,考虑懒加载"),t.domNodeCount>5e3&&console.warn("DOM 节点较多"),{memory:e,pageStats:t}},snapshot:()=>{const e={id:`manual-${Date.now()}`,timestamp:Date.now(),type:"periodic",memory:Ue(),pageStats:_n(),userAgent:navigator.userAgent,url:location.href};at(e)},getDiagnostics:ol,getActions:()=>Qt,getNetworkErrors:()=>St,getConsoleErrors:()=>en})}function Yg(){if(Hr)return;Hr=!0,Ng(),Fg(),zg(),Bg(),Hg(),$g(),Vg(),Wg(),Ug(),Gg(),Kg(),qg();const e=jg();e&&(e.customData={...e.customData,recovered:!0,recoveredAt:Date.now()},at(e),Og())}function ss(e,t){try{const n=Xg(e,t),o=JSON.stringify(n,null,2),i=new Blob([o],{type:"application/json"}),s=URL.createObjectURL(i),r=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),a=document.createElement("a");a.href=s,a.download=`opentu-error-log-${r}.json`,a.style.display="none",document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(s)},100)}catch(n){console.error("[ErrorLogExporter] Failed to export:",n)}}function Xg(e,t){const n={exportTime:new Date().toISOString(),version:"1.0",environment:{userAgent:navigator.userAgent,url:window.location.href,timestamp:Date.now(),language:navigator.language,platform:navigator.platform,screenSize:`${window.screen.width}x${window.screen.height}`},crashRecovery:et.getState(),diagnostics:ol(),unifiedLogs:yu.getMemoryLogs()};return e&&(n.currentError={message:e.message,stack:e.stack,componentStack:(t==null?void 0:t.componentStack)??void 0}),n}class Zg extends p.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null,errorInfo:null,recoveringFromChunkError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){const o=Bf(t);this.setState({errorInfo:n,recoveringFromChunkError:o}),!o&&console.error("[ErrorBoundary] React render error:",t,n)}render(){var t,n,o,i,s,r;return this.state.hasError?this.state.recoveringFromChunkError?d.jsx(Uo,{variant:"error",title:"检测到静态资源已更新",description:"当前页面引用的懒加载资源已失效,正在自动刷新一次以恢复工作台。若长时间未恢复,可手动点击安全模式。",errorMessage:((t=this.state.error)==null?void 0:t.message)||"动态资源加载失败",errorStack:(n=this.state.error)==null?void 0:n.stack,componentStack:((o=this.state.errorInfo)==null?void 0:o.componentStack)??void 0,onExportLog:()=>ss(this.state.error,this.state.errorInfo),onSafeModeReload:rs,onGoToDebug:Wo}):d.jsx(Uo,{variant:"error",errorMessage:((i=this.state.error)==null?void 0:i.message)||"未知错误",errorStack:(s=this.state.error)==null?void 0:s.stack,componentStack:((r=this.state.errorInfo)==null?void 0:r.componentStack)??void 0,onExportLog:()=>ss(this.state.error,this.state.errorInfo),onSafeModeReload:rs,onGoToDebug:Wo}):this.props.children}}function rs(){try{localStorage.setItem("aitu_safe_mode","true")}catch{}window.location.reload()}function Wo(){const e="/sw-debug.html";window.location.href=e}const Jg={crash:{iconBg:"#FFF3E0",iconStroke:"#F57C00",iconPath:d.jsxs(d.Fragment,{children:[d.jsx("circle",{cx:"12",cy:"12",r:"10"}),d.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),d.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),defaultTitle:"检测到页面异常退出",defaultDesc:""},error:{iconBg:"#FFEBEE",iconStroke:"#E53935",iconPath:d.jsxs(d.Fragment,{children:[d.jsx("circle",{cx:"12",cy:"12",r:"10"}),d.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),d.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}),defaultTitle:"应用渲染出错",defaultDesc:"页面遇到了意外错误,可能是画布数据异常或浏览器内存不足。"}},Uo=e=>{const{variant:t,crashCount:n,memoryInfo:o,onIgnore:i,title:s,description:r,errorMessage:a,errorStack:c,componentStack:u,onExportLog:l,onSafeModeReload:h,onGoToDebug:f}=e,[g,y]=on.useState(!1),m=Jg[t],w=s||m.defaultTitle,S=r||m.defaultDesc;return d.jsx("div",{style:Me.overlay,children:d.jsxs("div",{style:Me.card,children:[d.jsx("div",{style:{...Me.iconWrap,backgroundColor:m.iconBg},children:d.jsx("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:m.iconStroke,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:m.iconPath})}),d.jsx("h2",{style:Me.title,children:w}),t==="crash"&&n!=null&&d.jsxs("p",{style:Me.desc,children:["页面已连续 ",n," 次未能正常加载,可能是因为:",d.jsx("br",{}),"• 画布元素过多导致内存不足",d.jsx("br",{}),"• 浏览器内存限制",d.jsx("br",{}),d.jsx("br",{}),"建议使用「安全模式」创建空白画布,稍后可从侧边栏切换到其他画布。"]}),t==="error"&&S&&d.jsx("p",{style:Me.desc,children:S}),o&&d.jsx(Qg,{info:o}),t==="error"&&a&&d.jsxs("div",{style:Me.errorBox,children:[d.jsx("div",{style:Me.errorMsg,children:a}),(c||u)&&d.jsx("button",{onClick:()=>y(v=>!v),style:Me.detailToggle,children:g?"收起详情":"展开详情"}),g&&d.jsxs("pre",{style:Me.errorDetail,children:[c,u&&`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ai-chat-BlxYfB4O.css","./tool-windows-DW-CDfPc.css","./media-viewer-DoEpBmJL.css","./useCharacters-DRBoWvvj.css","./character-Bo9jcTNu.css","./popup-toolbar-Dloei_m7.css","./link-popup-By5ld_Sx.css","./index-DWIHW2I-.css","./index-BUD4zoiJ.css","./quick-creation-toolbar-bpZffpTF.css","./index-BBR2ncNs.css","./DeferredAIInputBar-DUkSo7tK.css","./ResizableDivider-ClzYJk-6.css","./ttd-dialog-DaiCKXiC.css","./settings-dialog-Dcm1G4kx.css","./CanvasAudioPlayer-QLXKZ5KP.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as re}from"./startup-runtime-BrfuwjQS.js";import{c8 as yi,gD as wu,e3 as Vi,gE as yt,gF as $a,P as p,c7 as Va,bP as tt,gG as Wa,c6 as ii,U as qe,S as Mo,gH as Ae,gI as Nt,gJ as yu,a8 as d,R as on,ao as Ne,gK as tr,bd as F,gL as vu,gM as Ua,gN as nr,gO as vi,bh as Xe,bg as Ze,gP as Su,br as xu,ak as Te,ff as vn,fy as si,gQ as ku,bl as ee,gR as Eu,gS as bs,gT as ri,gU as ai,gV as bu,gW as to,gX as _u,gY as Pu,gZ as or,g_ as ir,g$ as sr,h0 as rr,h1 as Tu,h2 as ar,h3 as cr,h4 as Cu,h5 as Wi,h6 as Ui,aa as me,h7 as Iu,h8 as Au,h9 as Mu,ha as Ru,bQ as mo,a0 as pn,Z as Du,hb as lr,hc as Bo,hd as Lu,he as ju,hf as cn,hg as Ou,hh as Nu,hi as zu,hj as ur,bf as At,hk as Fu,hl as Bu,hm as Hu,hn as $u,ho as Vu,hp as Wu,hq as Uu,hr as Gu,hs as Ku,ht as qu,hu as Yu,hv as Xu,hw as Zu,hx as Ju,hy as Qu,hz as ed,hA as td,hB as nd,hC as Ga,hD as od,hE as Si,hF as ko,hG as id,eH as sd,at as de,hH as rd,dA as ad,eY as cd,hI as Sn,hJ as ld,hK as ud,bR as wo,hL as Gi,hM as ci,bS as _s,bT as no,bU as li,hN as Ka,hO as oo,hP as yo,hQ as dd,hR as hd,hS as fd,hT as gd,hU as pd,hV as qa,aq as Ya,bZ as md,hW as Xa,hX as Ki,hY as qi,ca as dr,hZ as wd,h_ as yd,h$ as vd,e4 as Ho,i0 as Za,cO as Yt,ba as Ja,dd as hr,i1 as Sd,i2 as xd,bb as Qa,b5 as kd,b7 as Ed,b8 as ec,i3 as bd,i4 as Ps,i5 as Mt,i6 as Rt,i7 as Dt,cm as Oe,i8 as _d,i9 as Pd,ia as Td,el as Ht,ib as Cd,bq as K,ic as Yi,bj as Se,id as Id,ie as Ad,ig as Md,ih as Rd,ii as Dd,ij as Ld,bL as jd,ik as Kt,il as tc,dU as nc,dV as ht,im as oc,io as ic,ip as Od,iq as En,ce as Nd,ar as Gn,ir as zd,ax as Fd,is as Bd,it as Ts,az as zt,bs as Pn,a1 as ve,dP as ie,iu as sc,dQ as Re,dR as He,dX as ui,iv as Hd,iw as $d,dY as Vd,dZ as Wd,gt as ge,ix as rc,iy as Ud,iz as Gd,iA as Kd,iB as qd,iC as Yd,iD as Xd,iE as Zd,gu as xt,iF as Jd,iG as Qd,iH as eh,dO as Le,iI as th,dI as ac,gs as io,eP as dt,iJ as cc,ab as Tt,iK as lc,iL as uc,iM as dc,iN as hc,iO as Cs,f5 as Is,f6 as fc,iP as gc,iQ as pc,iR as mc,iS as wc,iT as Xi,iU as yc,iV as vc,dW as Sc,b9 as nh,aY as oh,eI as $o,iW as ih,iX as sh,iY as rh,iZ as ah,i_ as ch,gA as lh,i$ as uh,gx as dh,gy as hh,dJ as bn,j0 as so,j1 as xc,gv as fr,j2 as fh,dN as gh,eg as ph,cj as mh,cg as wh,j3 as yh,j4 as kc,dK as Ec,j5 as As,j6 as vh,j7 as Sh,eh as di,j8 as Ms,j9 as Zi,ja as gr,bV as bc,bW as Rs,bX as Ds,bt as De,bY as _c,jb as sn,jc as Tn,jd as vo,je as rn,jf as pr,jg as Ji,aw as $e,aB as Pc,aA as Tc,jh as xh,bk as So,ji as kh,jj as Eh,jk as bh,jl as Cc,jm as Ic,jn as _h,jo as mr,jp as Qi,bN as Ph,bp as Ft,jq as Ac,jr as Th,js as Ch,jt as Ih,fq as Ah,ju as Mh,jv as Mc,jw as Rh,e8 as Dh,gh as Lh,ep as jh,jx as Oh,jy as Rc,jz as Nh,jA as zh,jB as Fh,jC as Bh,jD as Ls,jE as ro,jF as ao,jG as Dc,jH as Hh,jI as Pe,jJ as Vo,jK as Lc,b0 as jc,jL as xi,jM as wr,cG as $h,cI as Vh,cJ as Wh,c9 as Ro,cR as Oc,cQ as Nc,jN as Kn,jO as Uh,jP as Gh,jQ as yr,jR as rt,jS as zc,cd as vr,jT as Kh,bo as qh,jU as Fc,ev as Sr,jV as xr,bx as Yh,by as Xh,bz as Zh,jW as Jh,bA as Qh,jX as ef,jY as tf,jZ as nf,j_ as of,j$ as sf,k0 as rf,k1 as af,k2 as cf,dt as lf,k3 as uf,k4 as ki,k5 as df,k6 as hf,k7 as ff,fP as gf,k8 as pf}from"./ai-chat-BnWVpTEI.js";import{s as co,T as kr,R as mn,l as mf,a as Bc,b as Do,u as hi,c as je,g as Hc,d as $c,i as wf,e as Vc,f as yf,h as vf,j as Sf,L as lo,k as js,m as Os,n as xf,o as kf,p as Ef,A as ln,D as Ei,B as Cn,q as bf,r as _f,t as fi,v as Er,w as Pf,x as Tf,y as Wc,z as Eo,C as un,E as dn,F as Cf,G as If,H as vt,I as Jt,J as Af,K as Mf,M as Rf,N as Df,O as Lf,P as jf,Q as Of,S as Nf,U as Ns,V as zf,W as zs,X as Ff,Y as br}from"./tool-windows-Bf_pMml-.js";import{t as Bf}from"./startup-app-CH3QzBb4.js";const Uc="main_board_content",Gc=yi.createInstance({name:"Drawnix",storeName:wu,driver:[yi.INDEXEDDB,yi.LOCALSTORAGE]});async function Kc(){try{const e=await Vi.loadState();return(e==null?void 0:e.migrationCompleted)===!0}catch(e){return console.error("[WorkspaceMigration] Failed to check migration status:",e),!1}}async function _r(){try{const e=await Vi.loadState();e.migrationCompleted=!0,await Vi.saveState(e)}catch(e){console.error("[WorkspaceMigration] Failed to mark migration completed:",e)}}async function Hf(){try{const e=await Gc.getItem(Uc);if(e&&e.children&&e.children.length>0)return e;const t=localStorage.getItem($a);if(t){const n=JSON.parse(t);if(Array.isArray(n)&&n.length>0)return{children:n}}return null}catch(e){return console.error("[WorkspaceMigration] Failed to get legacy data:",e),null}}async function $f(){try{if(await Kc())return null;const t=await Hf();if(!t||!t.children||t.children.length===0)return await _r(),null;const n=yt.getInstance();await n.initialize();const o=await n.createBoard({name:"迁移的画板",elements:t.children,viewport:t.viewport,theme:t.theme});return o?(await n.switchBoard(o.id),await _r(),await Vf(),o.id):(console.error("[WorkspaceMigration] Failed to create board"),null)}catch(e){return console.error("[WorkspaceMigration] Migration failed:",e),null}}async function Vf(){try{await Gc.removeItem(Uc),localStorage.removeItem($a)}catch(e){console.error("[WorkspaceMigration] Failed to clear legacy data:",e)}}const Je={LOADING_STATE:"aitu_page_loading_state",CRASH_COUNT:"aitu_crash_count",LAST_SUCCESS_LOAD:"aitu_last_success_load",SAFE_MODE:"aitu_safe_mode",CRASH_HISTORY:"aitu_crash_history"};class Wf{constructor(){this.state={crashDetected:!1,crashCount:0,isSafeMode:!1,crashHistory:[]}}markLoadingStart(){try{localStorage.getItem(Je.LOADING_STATE)==="loading"&&(this.state.crashDetected=!0,this.incrementCrashCount(),this.recordCrash()),localStorage.setItem(Je.LOADING_STATE,"loading"),this.state.isSafeMode=localStorage.getItem(Je.SAFE_MODE)==="true",this.loadCrashHistory()}catch(t){console.warn("[CrashRecovery] Failed to mark loading start:",t)}}markLoadingComplete(){try{localStorage.setItem(Je.LOADING_STATE,"complete"),localStorage.setItem(Je.LAST_SUCCESS_LOAD,Date.now().toString()),this.state.isSafeMode||(localStorage.setItem(Je.CRASH_COUNT,"0"),this.state.crashCount=0)}catch(t){console.warn("[CrashRecovery] Failed to mark loading complete:",t)}}incrementCrashCount(){try{const t=parseInt(localStorage.getItem(Je.CRASH_COUNT)||"0",10);this.state.crashCount=t+1,localStorage.setItem(Je.CRASH_COUNT,this.state.crashCount.toString())}catch{}}recordCrash(){try{const t=performance,n={timestamp:Date.now(),url:window.location.href,memoryStats:t.memory?{usedJSHeapSize:t.memory.usedJSHeapSize,totalJSHeapSize:t.memory.totalJSHeapSize,jsHeapSizeLimit:t.memory.jsHeapSizeLimit}:null};this.state.crashHistory.unshift(n),this.state.crashHistory=this.state.crashHistory.slice(0,10),this.saveCrashHistory()}catch{}}loadCrashHistory(){try{const t=localStorage.getItem(Je.CRASH_HISTORY);t&&(this.state.crashHistory=JSON.parse(t))}catch{this.state.crashHistory=[]}}saveCrashHistory(){try{localStorage.setItem(Je.CRASH_HISTORY,JSON.stringify(this.state.crashHistory))}catch{}}getState(){return{...this.state}}isCrashDetected(){return this.state.crashDetected}getCrashCount(){return this.state.crashCount}isSafeMode(){return this.state.isSafeMode}shouldShowSafeModePrompt(){return this.state.crashDetected&&this.state.crashCount>=2}enableSafeMode(){try{localStorage.setItem(Je.SAFE_MODE,"true"),this.state.isSafeMode=!0}catch{}}disableSafeMode(){try{localStorage.removeItem(Je.SAFE_MODE),this.state.isSafeMode=!1,localStorage.setItem(Je.CRASH_COUNT,"0"),this.state.crashCount=0}catch{}}clearCrashState(){try{localStorage.setItem(Je.CRASH_COUNT,"0"),this.state.crashCount=0,this.state.crashDetected=!1}catch{}}checkUrlSafeMode(){try{const t=new URLSearchParams(window.location.search);if(t.get("safe")==="1"||t.get("safe_mode")==="1")return this.enableSafeMode(),!0}catch{}return!1}getMemoryInfo(){try{const t=performance;if(!t.memory)return null;const n=o=>o<1024*1024?`${(o/1024).toFixed(1)} KB`:o<1024*1024*1024?`${(o/1024/1024).toFixed(1)} MB`:`${(o/1024/1024/1024).toFixed(2)} GB`;return{used:n(t.memory.usedJSHeapSize),limit:n(t.memory.jsHeapSizeLimit),percent:t.memory.usedJSHeapSize/t.memory.jsHeapSizeLimit*100}}catch{return null}}}const et=new Wf,Uf="Opentu",Gf="Opentu - AI应用平台";function qn(e){e&&e.trim()?document.title=`${Uf} - ${e.trim()}`:document.title=Gf}function Kf(e){if(!e){qn();return}const t=Va.getBoard(e);qn(t==null?void 0:t.name)}function qf(e,t){return p.useEffect(()=>{t!==void 0?qn(t):Kf(e)},[e,t]),p.useEffect(()=>{const o=Va.observeEvents().subscribe(i=>{if(i.type==="boardUpdated"){const s=i.payload;s&&s.id===e&&qn(s.name)}});return()=>{o.unsubscribe()}},[e]),{updateTitle:p.useCallback(o=>{qn(o)},[])}}const es="aitu-tab-sync-version",Yf=500,ts=`tab-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;function qc({onSyncNeeded:e,enabled:t=!0,currentBoardId:n}){const o=p.useRef(-1),i=p.useRef();p.useEffect(()=>{if(!t)return;const s=localStorage.getItem(es);if(s)try{const r=JSON.parse(s);o.current=r.version}catch{o.current=parseInt(s,10)||Date.now()}else o.current=Date.now()},[t]),p.useEffect(()=>{if(!t)return;const s=()=>{const a=localStorage.getItem(es);if(a)try{const c=JSON.parse(a);if(c.version>o.current&&c.tabId!==ts){const u=n&&c.boardId&&c.boardId===n;o.current=c.version,u&&e()}else c.version>o.current&&c.tabId===ts&&(o.current=c.version)}catch{const c=parseInt(a,10);c>o.current&&(o.current=c)}};i.current=setInterval(()=>{document.hidden||s()},Yf);const r=()=>{document.hidden||s()};return document.addEventListener("visibilitychange",r),()=>{i.current&&clearInterval(i.current),document.removeEventListener("visibilitychange",r)}},[t,e,n])}function Yc(e){try{const n={version:Date.now(),tabId:ts,boardId:e};localStorage.setItem(es,JSON.stringify(n))}catch{}}const fS=Object.freeze(Object.defineProperty({__proto__:null,markTabSyncVersion:Yc,useTabSync:qc},Symbol.toStringTag,{value:"Module"}));function In(e){if(!tt.isAnalyticsEnabled())return;const t=Xf(e.name,e.value),n=document.referrer,o={[`$web_vitals_${e.name}_value`]:e.value,[`$web_vitals_${e.name}_event`]:{id:e.id,delta:e.delta,rating:t,navigationType:e.navigationType},page_path:window.location.pathname,referrer:n.length>200?n.slice(0,200):n,timestamp:Date.now()};setTimeout(()=>{tt.track("$web_vitals",o)},0)}function Xf(e,t){const o={LCP:{good:2500,poor:4e3},FID:{good:100,poor:300},CLS:{good:.1,poor:.25},FCP:{good:1800,poor:3e3},TTFB:{good:800,poor:1800},INP:{good:200,poor:500}}[e];return o?t<=o.good?"good":t<=o.poor?"needs-improvement":"poor":"needs-improvement"}async function Zf(){try{const e=await re(()=>import("./web-vitals-DcvjKPr-.js"),[],import.meta.url),{onCLS:t,onFCP:n,onLCP:o,onTTFB:i,onINP:s}=e;t(In),n(In),o(In),i(In),s(In)}catch(e){console.error("[Web Vitals] Failed to initialize monitoring:",e)}}const uo="page_report",Jf="app_page_view";let Pr=!1,Tr="";function Qf(){const e=window.innerWidth;return e<768?"mobile":e<1024?"tablet":"desktop"}const Cr=200;function eg(){const e=navigator.userAgent;return{page_url:window.location.href,page_path:window.location.pathname,page_title:document.title,referrer:document.referrer,viewport_width:window.innerWidth,viewport_height:window.innerHeight,screen_width:window.screen.width,screen_height:window.screen.height,device_type:Qf(),user_agent:e.length>Cr?e.slice(0,Cr):e,language:navigator.language,timestamp:Date.now()}}function tg(){if(!window.performance)return null;const e={page_url:window.location.pathname,page_path:window.location.pathname,timestamp:Date.now()};if(window.performance.getEntriesByType){const t=window.performance.getEntriesByType("navigation");if(t&&t.length>0){const n=t[0];n.domainLookupEnd&&n.domainLookupStart&&(e.dns_time=n.domainLookupEnd-n.domainLookupStart),n.connectEnd&&n.connectStart&&(e.tcp_time=n.connectEnd-n.connectStart),n.responseStart&&n.requestStart&&(e.request_time=n.responseStart-n.requestStart),n.responseEnd&&n.responseStart&&(e.response_time=n.responseEnd-n.responseStart),n.domComplete&&n.domInteractive&&(e.dom_processing_time=n.domComplete-n.domInteractive),n.domInteractive&&n.fetchStart&&(e.dom_interactive_time=n.domInteractive-n.fetchStart),n.domComplete&&n.fetchStart&&(e.dom_complete_time=n.domComplete-n.fetchStart),n.loadEventEnd&&n.fetchStart&&(e.load_time=n.loadEventEnd-n.fetchStart)}}if(window.performance.getEntriesByType){const t=window.performance.getEntriesByType("resource");e.total_resources=t.length,e.total_size=t.reduce((n,o)=>n+(o.transferSize||0),0)}return e}function bi(){if(!tt.isAnalyticsEnabled())return;const e=eg();e.page_url!==Tr&&(Tr=e.page_url,tt.track(Jf,{category:uo,...e}))}function Ir(){if(!tt.isAnalyticsEnabled())return;const e=tg();if(!e){console.warn("[Page Report] Performance data not available");return}tt.track("page_performance",{category:uo,...e})}function ng(){if(!tt.isAnalyticsEnabled())return;const e=Math.round(performance.now());tt.track("page_unload",{category:uo,page_url:window.location.href,page_path:window.location.pathname,time_on_page:e,timestamp:Date.now()})}function og(){try{if(Pr)return;Pr=!0,bi(),document.readyState==="complete"?Ir():window.addEventListener("load",()=>{setTimeout(()=>{Ir()},0)}),window.addEventListener("beforeunload",()=>{ng()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?tt.track("page_hidden",{category:uo,page_url:window.location.href,page_path:window.location.pathname,timestamp:Date.now()}):document.visibilityState==="visible"&&tt.track("page_visible",{category:uo,page_url:window.location.href,page_path:window.location.pathname,timestamp:Date.now()})}),window.addEventListener("popstate",()=>{setTimeout(()=>{bi()},100)});const e=history.pushState;history.pushState=function(...t){e.apply(this,t),setTimeout(()=>{bi()},100)}}catch(e){console.error("[Page Report] Failed to initialize monitoring:",e)}}function Ar(e){if(!e||!(e instanceof Element))return!1;const t=e,n=["input","textarea","select","button",".unified-toolbar",".chat-drawer",".side-drawer",".toolbox-drawer",".project-drawer",".popup-toolbar",".t-dialog",".t-drawer",".t-popup",".t-popover",".Dialog",".winbox",".ai-input-bar",".view-navigation",".minimap",".task-queue-panel",".t-slider",".unified-color-picker",".media-library",".viewer-container",".viewer-canvas",".viewer-footer",".viewer-toolbar",".unified-viewer",".media-viewport",".thumbnail-queue",'[role="button"]','[role="slider"]','[role="menu"]','[role="menuitem"]','[role="dialog"]',"[data-allow-touch]"];for(const o of n)if(t.matches(o)||t.closest(o))return!0;if(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth){const o=window.getComputedStyle(t);if(o.overflowY==="auto"||o.overflowY==="scroll"||o.overflowX==="auto"||o.overflowX==="scroll")return!0}return!1}function Mr(e){if(!e||!(e instanceof Element))return!1;const t=e,n=[".plait-board-container",".plait-board","[plait-board]","svg.rough-svg"];for(const o of n)if(t.matches(o)||t.closest(o))return!0;return!1}function ig(){if(typeof window>"u")return()=>{};const e=o=>{if(o.touches.length>1){const i=o.target;if(Ar(i))return;Mr(i)&&(o.preventDefault(),o.stopPropagation())}},t=o=>{const i=o.target;Ar(i)||Mr(i)&&(o.preventDefault(),o.stopPropagation())},n=o=>{(o.ctrlKey||o.metaKey)&&o.preventDefault()};return document.addEventListener("touchstart",e,{passive:!1,capture:!0}),document.addEventListener("touchmove",e,{passive:!1,capture:!0}),document.addEventListener("touchend",e,{passive:!1,capture:!0}),document.addEventListener("gesturestart",t,{passive:!1,capture:!0}),document.addEventListener("gesturechange",t,{passive:!1,capture:!0}),document.addEventListener("gestureend",t,{passive:!1,capture:!0}),window.addEventListener("wheel",n,{passive:!1}),()=>{document.removeEventListener("touchstart",e,!0),document.removeEventListener("touchmove",e,!0),document.removeEventListener("touchend",e,!0),document.removeEventListener("gesturestart",t,!0),document.removeEventListener("gesturechange",t,!0),document.removeEventListener("gestureend",t,!0),window.removeEventListener("wheel",n)}}const ns=ii.DB_CLEANUP_DONE;function Xc(){let e=0;for(const t of Wa)try{localStorage.getItem(t)!==null&&(localStorage.removeItem(t),e++)}catch(n){console.warn(`[DBCleanup] Failed to remove LocalStorage key ${t}:`,n)}return e}async function Zc(){localStorage.getItem(ns)||(Xc(),localStorage.setItem(ns,Date.now().toString()))}function sg(){localStorage.removeItem(ns)}typeof window<"u"&&(window.__dbCleanup={run:Zc,reset:sg,cleanupLS:Xc,LS_KEYS_DEPRECATED:Wa});const Fs=[{lsKey:qe.PROMPT_HISTORY,idbKey:qe.PROMPT_HISTORY,deleteAfterMigration:!0},{lsKey:qe.VIDEO_PROMPT_HISTORY,idbKey:qe.VIDEO_PROMPT_HISTORY,deleteAfterMigration:!0},{lsKey:qe.PRESET_SETTINGS,idbKey:qe.PRESET_SETTINGS,deleteAfterMigration:!0},{lsKey:qe.BATCH_IMAGE_CACHE,idbKey:qe.BATCH_IMAGE_CACHE,deleteAfterMigration:!0},{lsKey:qe.RECENT_TEXT_COLORS,idbKey:qe.RECENT_TEXT_COLORS,deleteAfterMigration:!0},{lsKey:qe.CUSTOM_GRADIENTS,idbKey:qe.CUSTOM_GRADIENTS,deleteAfterMigration:!0},{lsKey:qe.CUSTOM_FONTS,idbKey:qe.CUSTOM_FONTS,deleteAfterMigration:!0},{lsKey:qe.TOOLBAR_CONFIG,idbKey:qe.TOOLBAR_CONFIG,deleteAfterMigration:!0}];function Bs(){try{return localStorage.getItem(ii.LS_TO_IDB_MIGRATION_DONE)!==null}catch{return!1}}function rg(){try{localStorage.setItem(ii.LS_TO_IDB_MIGRATION_DONE,Date.now().toString())}catch(e){console.error("[StorageMigration] Failed to mark migration done:",e)}}function ag(e){try{const t=localStorage.getItem(e);return t===null?null:JSON.parse(t)}catch(t){return console.warn(`[StorageMigration] Failed to read ${e} from LocalStorage:`,t),null}}function Rr(e){try{localStorage.removeItem(e)}catch(t){console.warn(`[StorageMigration] Failed to delete ${e} from LocalStorage:`,t)}}async function cg(e){const{lsKey:t,idbKey:n,deleteAfterMigration:o}=e;try{const i=ag(t);return i===null?{key:t,success:!0}:await Mo.get(n)!==null?(o&&Rr(t),{key:t,success:!0}):(await Mo.set(n,i),await Mo.get(n)===null?{key:t,success:!1,error:"Verification failed: data not found after write"}:(o&&Rr(t),{key:t,success:!0}))}catch(i){const s=i instanceof Error?i.message:String(i);return console.error(`[StorageMigration] Failed to migrate ${t}:`,i),{key:t,success:!1,error:s}}}async function Jc(){if(!Mo.isAvailable())return console.warn("[StorageMigration] IndexedDB not available, skipping migration"),[];if(Bs())return[];const e=[];for(const n of Fs){const o=await cg(n);e.push(o),o.success||console.warn(`[StorageMigration] Failed: ${o.key} - ${o.error}`)}return e.filter(n=>n.success).length,e.filter(n=>!n.success).length===0&&rg(),e}function Qc(){try{localStorage.removeItem(ii.LS_TO_IDB_MIGRATION_DONE)}catch(e){console.error("[StorageMigration] Failed to reset migration status:",e)}}const lg={isMigrationDone:Bs,runMigration:Jc,resetMigration:Qc,MIGRATION_CONFIGS:Fs};typeof window<"u"&&(window.__storageMigration={run:Jc,reset:Qc,isDone:Bs,configs:Fs});const os=new Set,Dr=4,Lr=1e3;function jr(e){e.forEach(t=>os.delete(t))}function Or(){const e=typeof navigator<"u"?navigator.connection:void 0;return e?e.saveData?!1:e.effectiveType!=="slow-2g"&&e.effectiveType!=="2g":!0}function el(e){if(typeof window>"u"||!("serviceWorker"in navigator)||e.length===0||!Or()){e.length,Or();return}const t=e.filter(s=>os.has(s)?!1:(os.add(s),!0));if(t.length===0)return;const n={type:"SW_PREFETCH_GROUPS",groups:t},o=(s=1)=>{const r=navigator.serviceWorker.controller;if(r){r.postMessage(n);return}navigator.serviceWorker.ready.then(a=>{if(a.active){a.active.postMessage(n);return}if(s>=Dr){jr(t),console.warn("[StartupPrefetch] idle prefetch request dropped: no active service worker",{groups:t,attempt:s});return}window.setTimeout(()=>o(s+1),Lr)}).catch(a=>{if(s>=Dr){jr(t),console.warn("[StartupPrefetch] idle prefetch request failed after retries",{groups:t,attempt:s,error:a});return}window.setTimeout(()=>o(s+1),Lr)})},i=window.requestIdleCallback;typeof i=="function"?i(()=>o(),{timeout:1500}):window.setTimeout(o,400)}const ug=3e4,dg=800,hg=.6,fg=3,Hs="aitu_last_snapshot",gg=50,Yn=[],pg=20,mg=2e3;let Xn=null;const Nr=3e3,wg=1e4,yg=200,vg=5e3,Sg=10,xg=5e3,kg=30,Eg=20,zr=20,bg=100,_g=30,Pg=240;function Tg(e){if(e&&typeof e=="object"&&"name"in e){const t=e.name;return typeof t=="string"?t:""}return""}function Cg(e,t=""){if(e&&typeof e=="object"&&"message"in e){const n=e.message;if(typeof n=="string")return n}return typeof e=="string"?e:t}function Fr(e,t=""){const n=Tg(e),o=Cg(e,t),i=n==="AbortError"||o.startsWith("AbortError:")||o.includes("AbortError"),s=n==="NotAllowedError"||o.startsWith("NotAllowedError:"),r=n==="DataError"||o.startsWith("DataError:");return o.includes("ResizeObserver loop completed with undelivered notifications")||o.includes("ResizeObserver loop limit exceeded")||o.includes("WebCodecs API")&&(o.includes("Chrome 94+")||o.includes("Edge 94+"))||i&&(o.includes("The user aborted a request")||o.includes("Failed to execute 'showOpenFilePicker'")||o.includes("Failed to execute 'showSaveFilePicker'"))||s&&o.includes("Failed to execute 'write' on 'Clipboard'")&&o.includes("permissions policy")?!0:r&&o.includes("No key or key range specified")}let Br=null,Hr=!1,$r=null,Vr=null,_i=null,Pi=0,Zt=60,Hn=!1,Ti=!1;const Qt=[],en=[],St=[];function Ig(e){const t=Ue(),n=Date.now();return()=>{const o=Ue();if(!t||!o)return;const i=(o.usedJSHeapSize-t.usedJSHeapSize)/(1024*1024),s=Date.now()-n;if(Math.abs(i)>=gg){const r=i>=0?"+":"";console.warn(`[MemoryLog] ${e}: ${r}${i.toFixed(0)} MB (${s}ms)`)}}}function mt(e){if(e)return e.slice(0,Pg)}function Ag(){return"1.0.2"}function Mg(){if(typeof navigator>"u"||typeof window>"u"||!("serviceWorker"in navigator))return{supported:!1,readyState:document.readyState,visibilityState:document.visibilityState};const e=navigator.serviceWorker.controller;return{supported:!0,controller:e?{scriptURL:mt(e.scriptURL),state:e.state}:null,readyState:document.readyState,visibilityState:document.visibilityState}}function Rg(){const e=Array.from(document.scripts).map(o=>mt(Nt(o.src))).filter(Boolean).slice(-8),t=Array.from(document.querySelectorAll('link[rel="stylesheet"]')).map(o=>mt(Nt(o.href))).filter(Boolean).slice(-8),n=Array.from(document.querySelectorAll('link[rel="modulepreload"]')).map(o=>mt(Nt(o.href))).filter(Boolean).slice(-8);return{scripts:e,stylesheets:t,modulePreloads:n}}function tl(e){if(!(e instanceof HTMLElement))return;const t=e;return{tagName:e.tagName.toLowerCase(),id:mt(e.id||void 0),className:typeof e.className=="string"?mt(e.className):void 0,src:mt(t.currentSrc||t.src?Nt(t.currentSrc||t.src||""):void 0),href:mt(t.href?Nt(t.href):void 0),rel:mt(t.rel),crossOrigin:mt(t.crossOrigin||void 0)}}function is(e){return{appVersion:Ag(),recentActions:Qt.slice(-10),recentErrors:en.slice(-5),recentNetworkErrors:St.slice(-5),serviceWorker:Mg(),loadedResources:Rg(),...e}}function Ue(){if(typeof performance<"u"&&"memory"in performance){const e=performance.memory;return{usedJSHeapSize:e.usedJSHeapSize,totalJSHeapSize:e.totalJSHeapSize,jsHeapSizeLimit:e.jsHeapSizeLimit}}}function _n(){try{const e={domNodeCount:document.getElementsByTagName("*").length,canvasCount:document.getElementsByTagName("canvas").length,imageCount:document.getElementsByTagName("img").length,videoCount:document.getElementsByTagName("video").length,iframeCount:document.getElementsByTagName("iframe").length,plaitBoardExists:!!document.querySelector(".plait-board-container")},t=document.querySelector(".plait-board-container");if(t){const n=t.querySelectorAll("svg > g > g");e.plaitElementCount=n.length}return window.getEventListeners,e}catch{return{domNodeCount:0,canvasCount:0,imageCount:0,videoCount:0,iframeCount:0,plaitBoardExists:!1}}}function nl(){if(!Ae.isInitialized()||Yn.length===0)return;const e=Yn.splice(0,Yn.length);for(const t of e)Ae.reportCrashSnapshot(t).catch(()=>{});Xn&&(clearInterval(Xn),Xn=null)}function Dg(){Xn||(Xn=setInterval(()=>{Ae.isInitialized()&&nl()},mg))}function at(e){try{Ae.isInitialized()?(nl(),Ae.reportCrashSnapshot(e).catch(()=>{})):Yn.length<pg&&(Yn.push(e),Dg())}catch(t){console.warn("[MemoryLog] Failed to send snapshot to SW:",t)}}function Lg(e){try{localStorage.setItem(Hs,JSON.stringify(e))}catch{}}function jg(){try{const e=localStorage.getItem(Hs);if(e)return JSON.parse(e)}catch{}return null}function Og(){try{localStorage.removeItem(Hs)}catch{}}function Ng(){const e={id:`startup-${Date.now()}`,timestamp:Date.now(),type:"startup",userAgent:navigator.userAgent,url:location.href,memory:Ue()};at(e)}function zg(){if(Br!==null)return;let e=0;Br=window.setInterval(()=>{const t=Ue();if(!t)return;const n=t.usedJSHeapSize/(1024*1024),o=t.jsHeapSizeLimit/(1024*1024),i=n/o;if(n>dg||i>hg){e++;const a=e>=fg?_n():void 0,c={id:`periodic-${Date.now()}`,timestamp:Date.now(),type:"periodic",memory:t,pageStats:a,userAgent:navigator.userAgent,url:location.href};at(c)}else e=0},ug)}function Fg(){window.addEventListener("error",e=>{var n;if(Fr(e.error,e.message))return;const t={id:`error-${Date.now()}`,timestamp:Date.now(),type:"error",error:{message:e.message||"Unknown error",stack:(n=e.error)==null?void 0:n.stack,type:"uncaughtError"},memory:Ue(),userAgent:navigator.userAgent,url:location.href,customData:is({filename:e.filename,lineno:e.lineno,colno:e.colno,eventTarget:tl(e.target)})};at(t),console.error("[MemoryLog] Uncaught error captured:",e.message)}),window.addEventListener("unhandledrejection",e=>{const t=e.reason,n=(t==null?void 0:t.message)||String(t)||"",o=(t==null?void 0:t.stack)||"";if(Fr(t,n)||n.includes("posthog.com")||o.includes("posthog"))return;const i={id:`rejection-${Date.now()}`,timestamp:Date.now(),type:"error",error:{message:n||"Unhandled Promise rejection",stack:o,type:"unhandledRejection"},memory:Ue(),userAgent:navigator.userAgent,url:location.href,customData:is()};at(i),console.error("[MemoryLog] Unhandled rejection captured:",t)}),window.addEventListener("beforeunload",()=>{const e=Ue();if(e){const t={id:`beforeunload-${Date.now()}`,timestamp:Date.now(),type:"beforeunload",memory:e,userAgent:navigator.userAgent,url:location.href};Lg(t),at(t)}})}function Bg(){if($r!==null)return;let e=Date.now();document.addEventListener("visibilitychange",()=>{document.hidden?Ti=!0:(e=Date.now(),setTimeout(()=>{Ti=!1},Nr+100))}),$r=window.setInterval(()=>{const t=Date.now(),n=t-e;if(n>wg&&!Ti&&!document.hidden){const o={id:`freeze-${Date.now()}`,timestamp:Date.now(),type:"freeze",memory:Ue(),pageStats:_n(),performance:{freezeDuration:n,lastHeartbeat:e,fps:Zt},userAgent:navigator.userAgent,url:location.href,customData:{recentActions:Qt.slice(-10),recentErrors:en.slice(-5),recentNetworkErrors:St.slice(-5)}};at(o)}e=t,Ae.isInitialized()&&Ae.sendHeartbeat(t).catch(()=>{})},Nr)}function Hg(){if(_i===null&&!(typeof PerformanceObserver>"u"))try{_i=new PerformanceObserver(e=>{for(const t of e.getEntries())if(t.duration>yg){const o=t.attribution;let i;if(o&&o.length>0){const r=o[0];i={name:r.name,containerType:r.containerType,containerSrc:r.containerSrc,containerId:r.containerId,containerName:r.containerName}}const s={id:`longtask-${Date.now()}`,timestamp:Date.now(),type:"longtask",memory:Ue(),performance:{longTaskDuration:t.duration,fps:Zt},userAgent:navigator.userAgent,url:location.href,customData:{taskName:t.name,startTime:t.startTime,attribution:i,debugTip:"Use Chrome DevTools Performance panel to record and analyze the call stack"}};at(s)}}),_i.observe({entryTypes:["longtask"]})}catch{}}function $g(){if(Vr!==null)return;let e=0;const t=()=>{if(e++,e>=_g){const n=performance.now(),o=n-Pi;o>0&&(Zt=Math.round(e*1e3/o)),e=0,Pi=n}requestAnimationFrame(t)};Pi=performance.now(),requestAnimationFrame(t),Vr=window.setInterval(()=>{if(Zt<Sg&&Zt>0){const n={id:`lowfps-${Date.now()}`,timestamp:Date.now(),type:"freeze",memory:Ue(),performance:{fps:Zt},userAgent:navigator.userAgent,url:location.href};at(n)}},vg)}function Vg(){setTimeout(()=>{Wr()},xg),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&!Hn&&setTimeout(Wr,1e3)})}function Wr(){if(Hn)return;const e=document.getElementById("root"),t=e&&e.children.length>0,o=!!document.querySelector(".plait-board-container");if(document.body.children.length>1,e&&!t){Hn=!0;const i={id:`whitescreen-${Date.now()}`,timestamp:Date.now(),type:"whitescreen",memory:Ue(),pageStats:{domNodeCount:document.getElementsByTagName("*").length,canvasCount:0,imageCount:0,videoCount:0,iframeCount:0,plaitBoardExists:o},userAgent:navigator.userAgent,url:location.href,customData:{rootExists:!!e,rootChildCount:(e==null?void 0:e.children.length)||0,bodyChildCount:document.body.children.length,hasPlaitBoard:o}};at(i),console.error("[MemoryLog] 白屏检测: React 未渲染内容")}t&&!o&&location.pathname==="/"&&setTimeout(()=>{if(!document.querySelector(".plait-board-container")&&!Hn){Hn=!0;const i={id:`whitescreen-noboard-${Date.now()}`,timestamp:Date.now(),type:"whitescreen",memory:Ue(),pageStats:_n(),userAgent:navigator.userAgent,url:location.href,customData:{reason:"画板未加载",rootChildCount:(e==null?void 0:e.children.length)||0}};at(i),console.error("[MemoryLog] 白屏检测: 画板组件未加载")}},5e3)}function $n(e,t,n){Qt.push({time:Date.now(),action:e,target:t,detail:n}),Qt.length>kg&&Qt.shift()}function Wg(){let e=0;document.addEventListener("click",t=>{const n=Date.now();if(n-e<bg)return;e=n;const o=t.target;if(!o)return;const i=()=>{var a,c,u,l,h,f,g,y,m,w,S,v,E,C,D;let s="";const r=(c=(a=o.closest)==null?void 0:a.call(o,"[data-track]"))==null?void 0:c.getAttribute("data-track");if(r)s=r;else if(o.tagName==="BUTTON"||(u=o.closest)!=null&&u.call(o,"button")){const P=((l=o.closest)==null?void 0:l.call(o,"button"))||o,H=(h=P.textContent)==null?void 0:h.trim().slice(0,20),B=(m=(y=(g=(f=P.className)==null?void 0:f.split)==null?void 0:g.call(f," "))==null?void 0:y[0])==null?void 0:m.slice(0,20);s=`btn:${H||B||"unknown"}`}else if(o.tagName==="A")s=`link:${((w=o.pathname)==null?void 0:w.slice(0,30))||""}`;else if(o.tagName==="INPUT"||o.tagName==="TEXTAREA"){const P=o;s=`input:${P.name||P.type||((S=P.placeholder)==null?void 0:S.slice(0,15))||""}`}else if(o.id)s=`#${o.id}`;else{const P=(C=(E=(v=o.className)==null?void 0:v.split)==null?void 0:E.call(v," "))==null?void 0:C[0];s=P?`.${P.slice(0,20)}`:((D=o.tagName)==null?void 0:D.toLowerCase())||"unknown"}$n("click",s)};"requestIdleCallback"in window?window.requestIdleCallback(i,{timeout:100}):setTimeout(i,0)},{capture:!0,passive:!0}),document.addEventListener("keydown",t=>{if(t.ctrlKey||t.metaKey||t.altKey){const n=[];(t.ctrlKey||t.metaKey)&&n.push("Cmd"),t.altKey&&n.push("Alt"),t.shiftKey&&n.push("Shift"),n.push(t.key),$n("shortcut",n.join("+"))}},{capture:!0,passive:!0}),window.addEventListener("popstate",()=>{$n("navigate",location.pathname)}),window.addEventListener("hashchange",()=>{$n("navigate",location.hash)})}function Ug(){const e=window.fetch;window.fetch=async function(t,n){const o=Date.now();try{const i=await e.call(this,t,n);if(!i.ok){const s=typeof t=="string"?t:t.url,r=Date.now()-o,a=Nt(s).slice(0,300);St.push({time:Date.now(),url:a,method:(n==null?void 0:n.method)||"GET",status:i.status,statusText:i.statusText,duration:r}),St.length>zr&&St.shift()}return i}catch(i){const s=typeof t=="string"?t:t.url,r=Date.now()-o,a=Nt(s).slice(0,300);throw St.push({time:Date.now(),url:a,method:(n==null?void 0:n.method)||"GET",error:i.message,duration:r}),St.length>zr&&St.shift(),i}}}function Gg(){window.addEventListener("error",e=>{var n;const t=e.target;if(t&&t!==window&&t instanceof HTMLElement&&("src"in t||"href"in t)){const o=t.src||t.href,i=(n=t.tagName)==null?void 0:n.toLowerCase();$n("resource_error",i,o==null?void 0:o.slice(0,100));const s={id:`resource-error-${Date.now()}`,timestamp:Date.now(),type:"error",error:{message:`Resource load failed: ${i||"unknown"}`,type:"resourceError"},memory:Ue(),userAgent:navigator.userAgent,url:location.href,customData:is({resourceUrl:mt(o?Nt(o):void 0),eventTarget:tl(t)})};at(s)}},{capture:!0})}function Kg(){const e=console.error;console.error=function(...t){e.apply(this,t);const n=t[0];if(typeof n=="string"&&n.includes("[MemoryLog]"))return;const o=[...t];setTimeout(()=>{var r;let i="",s;for(let a=0;a<Math.min(o.length,5);a++){const c=o[a];if(typeof c=="string")i+=c+" ";else if(typeof c=="number"||typeof c=="boolean")i+=String(c)+" ";else if(c instanceof Error)i+=`Error: ${c.message} `,s=c.stack;else if(c&&typeof c=="object")try{const l=Object.keys(c).slice(0,5).map(h=>{const f=c[h];return`${h}:${typeof f=="string"?f.slice(0,20):typeof f}`}).join(",");i+=`{${l}} `}catch{i+=`[${((r=c.constructor)==null?void 0:r.name)||"Object"}] `}}en.push({time:Date.now(),message:i.trim().slice(0,500),stack:s}),en.length>Eg&&en.shift()},0)}}function ol(){return{userActions:[...Qt],consoleErrors:[...en],networkErrors:[...St],memory:Ue(),pageStats:_n(),fps:Zt}}function qg(){typeof window>"u"||(window.__memoryLog={getMemory:()=>{const e=Ue();return e?{usedMB:(e.usedJSHeapSize/1024/1024).toFixed(1),limitMB:(e.jsHeapSizeLimit/1024/1024).toFixed(0),percent:(e.usedJSHeapSize/e.jsHeapSizeLimit*100).toFixed(1)}:null},track:Ig,diagnose:()=>{const e=Ue(),t=_n();return t.imageCount>50&&console.warn("图片较多,考虑懒加载"),t.domNodeCount>5e3&&console.warn("DOM 节点较多"),{memory:e,pageStats:t}},snapshot:()=>{const e={id:`manual-${Date.now()}`,timestamp:Date.now(),type:"periodic",memory:Ue(),pageStats:_n(),userAgent:navigator.userAgent,url:location.href};at(e)},getDiagnostics:ol,getActions:()=>Qt,getNetworkErrors:()=>St,getConsoleErrors:()=>en})}function Yg(){if(Hr)return;Hr=!0,Ng(),Fg(),zg(),Bg(),Hg(),$g(),Vg(),Wg(),Ug(),Gg(),Kg(),qg();const e=jg();e&&(e.customData={...e.customData,recovered:!0,recoveredAt:Date.now()},at(e),Og())}function ss(e,t){try{const n=Xg(e,t),o=JSON.stringify(n,null,2),i=new Blob([o],{type:"application/json"}),s=URL.createObjectURL(i),r=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),a=document.createElement("a");a.href=s,a.download=`opentu-error-log-${r}.json`,a.style.display="none",document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(s)},100)}catch(n){console.error("[ErrorLogExporter] Failed to export:",n)}}function Xg(e,t){const n={exportTime:new Date().toISOString(),version:"1.0",environment:{userAgent:navigator.userAgent,url:window.location.href,timestamp:Date.now(),language:navigator.language,platform:navigator.platform,screenSize:`${window.screen.width}x${window.screen.height}`},crashRecovery:et.getState(),diagnostics:ol(),unifiedLogs:yu.getMemoryLogs()};return e&&(n.currentError={message:e.message,stack:e.stack,componentStack:(t==null?void 0:t.componentStack)??void 0}),n}class Zg extends p.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null,errorInfo:null,recoveringFromChunkError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){const o=Bf(t);this.setState({errorInfo:n,recoveringFromChunkError:o}),!o&&console.error("[ErrorBoundary] React render error:",t,n)}render(){var t,n,o,i,s,r;return this.state.hasError?this.state.recoveringFromChunkError?d.jsx(Uo,{variant:"error",title:"检测到静态资源已更新",description:"当前页面引用的懒加载资源已失效,正在自动刷新一次以恢复工作台。若长时间未恢复,可手动点击安全模式。",errorMessage:((t=this.state.error)==null?void 0:t.message)||"动态资源加载失败",errorStack:(n=this.state.error)==null?void 0:n.stack,componentStack:((o=this.state.errorInfo)==null?void 0:o.componentStack)??void 0,onExportLog:()=>ss(this.state.error,this.state.errorInfo),onSafeModeReload:rs,onGoToDebug:Wo}):d.jsx(Uo,{variant:"error",errorMessage:((i=this.state.error)==null?void 0:i.message)||"未知错误",errorStack:(s=this.state.error)==null?void 0:s.stack,componentStack:((r=this.state.errorInfo)==null?void 0:r.componentStack)??void 0,onExportLog:()=>ss(this.state.error,this.state.errorInfo),onSafeModeReload:rs,onGoToDebug:Wo}):this.props.children}}function rs(){try{localStorage.setItem("aitu_safe_mode","true")}catch{}window.location.reload()}function Wo(){const e="/sw-debug.html";window.location.href=e}const Jg={crash:{iconBg:"#FFF3E0",iconStroke:"#F57C00",iconPath:d.jsxs(d.Fragment,{children:[d.jsx("circle",{cx:"12",cy:"12",r:"10"}),d.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),d.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),defaultTitle:"检测到页面异常退出",defaultDesc:""},error:{iconBg:"#FFEBEE",iconStroke:"#E53935",iconPath:d.jsxs(d.Fragment,{children:[d.jsx("circle",{cx:"12",cy:"12",r:"10"}),d.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),d.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}),defaultTitle:"应用渲染出错",defaultDesc:"页面遇到了意外错误,可能是画布数据异常或浏览器内存不足。"}},Uo=e=>{const{variant:t,crashCount:n,memoryInfo:o,onIgnore:i,title:s,description:r,errorMessage:a,errorStack:c,componentStack:u,onExportLog:l,onSafeModeReload:h,onGoToDebug:f}=e,[g,y]=on.useState(!1),m=Jg[t],w=s||m.defaultTitle,S=r||m.defaultDesc;return d.jsx("div",{style:Me.overlay,children:d.jsxs("div",{style:Me.card,children:[d.jsx("div",{style:{...Me.iconWrap,backgroundColor:m.iconBg},children:d.jsx("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:m.iconStroke,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:m.iconPath})}),d.jsx("h2",{style:Me.title,children:w}),t==="crash"&&n!=null&&d.jsxs("p",{style:Me.desc,children:["页面已连续 ",n," 次未能正常加载,可能是因为:",d.jsx("br",{}),"• 画布元素过多导致内存不足",d.jsx("br",{}),"• 浏览器内存限制",d.jsx("br",{}),d.jsx("br",{}),"建议使用「安全模式」创建空白画布,稍后可从侧边栏切换到其他画布。"]}),t==="error"&&S&&d.jsx("p",{style:Me.desc,children:S}),o&&d.jsx(Qg,{info:o}),t==="error"&&a&&d.jsxs("div",{style:Me.errorBox,children:[d.jsx("div",{style:Me.errorMsg,children:a}),(c||u)&&d.jsx("button",{onClick:()=>y(v=>!v),style:Me.detailToggle,children:g?"收起详情":"展开详情"}),g&&d.jsxs("pre",{style:Me.errorDetail,children:[c,u&&`
|
|
3
3
|
|
|
4
|
-
Component Stack:${u}`]})]}),d.jsxs("div",{style:Me.btnRow,children:[t==="crash"&&i&&d.jsx(bo,{label:"继续加载",onClick:i,bg:"#f5f5f5",bgHover:"#e8e8e8",color:"#666"}),t==="error"&&l&&d.jsx(bo,{label:"导出错误日志",onClick:l,bg:"#f5f5f5",bgHover:"#e8e8e8",color:"#333"}),d.jsx(bo,{label:"安全模式",onClick:h,bg:"#F39C12",bgHover:"#E67E22",color:"#fff"})]}),d.jsx("div",{style:Me.divider}),d.jsx("div",{style:Me.helpSection,children:d.jsxs("div",{style:Me.helpRow,children:[d.jsx("img",{src:"https://nav.ourzhishi.top/api/dynamic-image/qr-code",alt:"企业微信二维码",style:Me.qrcode,referrerPolicy:"no-referrer"}),d.jsxs("div",{style:Me.helpText,children:[d.jsx("p",{style:Me.helpTitle,children:"需要帮助?"}),d.jsx("p",{style:Me.helpDesc,children:"扫码联系客服,或前往调试页面导出完整日志与备份数据"}),d.jsx(bo,{label:"打开调试页面",onClick:f,bg:"#f0eefa",bgHover:"#e2ddf7",color:"#5A4FCF",small:!0})]})]})})]})})},Qg=({info:e})=>{const t=e.percent>75?"#E53935":e.percent>50?"#FB8C00":"#43A047";return d.jsxs("div",{style:Me.memoryBox,children:[d.jsx("div",{style:{fontSize:12,color:"#888",marginBottom:8},children:"当前内存使用情况"}),d.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[d.jsxs("span",{style:{fontSize:14,color:"#333"},children:[e.used," / ",e.limit]}),d.jsxs("span",{style:{fontSize:14,fontWeight:500,color:t},children:[e.percent.toFixed(0),"%"]})]}),d.jsx("div",{style:{height:4,backgroundColor:"#e0e0e0",borderRadius:2,marginTop:8,overflow:"hidden"},children:d.jsx("div",{style:{height:"100%",width:`${Math.min(e.percent,100)}%`,backgroundColor:t,transition:"width 0.3s ease"}})})]})},bo=({label:e,onClick:t,bg:n,bgHover:o,color:i,small:s})=>{const[r,a]=on.useState(!1),c=s?{...Me.btnSmall,backgroundColor:r?o:n,color:i}:{...Me.btn,backgroundColor:r?o:n,color:i};return d.jsx("button",{onClick:t,onMouseOver:()=>a(!0),onMouseOut:()=>a(!1),style:c,children:e})},Me={overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:99999},card:{backgroundColor:"#fff",borderRadius:12,padding:32,maxWidth:520,width:"90%",maxHeight:"90vh",overflowY:"auto",boxShadow:"0 20px 60px rgba(0,0,0,0.3)"},iconWrap:{width:64,height:64,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 24px"},title:{margin:"0 0 12px",fontSize:20,fontWeight:600,textAlign:"center",color:"#1a1a1a"},desc:{margin:"0 0 20px",fontSize:14,color:"#666",textAlign:"center",lineHeight:1.6},memoryBox:{backgroundColor:"#f5f5f5",borderRadius:8,padding:"12px 16px",marginBottom:24},errorBox:{backgroundColor:"#f5f5f5",borderRadius:8,padding:"12px 16px",marginBottom:24},errorMsg:{fontSize:13,color:"#E53935",wordBreak:"break-word"},detailToggle:{marginTop:8,padding:0,border:"none",background:"none",color:"#888",fontSize:12,cursor:"pointer",textDecoration:"underline"},errorDetail:{marginTop:8,padding:8,backgroundColor:"#eee",borderRadius:4,fontSize:11,color:"#555",maxHeight:150,overflow:"auto",whiteSpace:"pre-wrap",wordBreak:"break-all"},btnRow:{display:"flex",gap:12},btn:{flex:1,padding:"12px 24px",fontSize:14,fontWeight:500,border:"none",borderRadius:8,cursor:"pointer",transition:"background-color 0.2s ease"},btnSmall:{padding:"8px 16px",fontSize:13,fontWeight:500,border:"none",borderRadius:6,cursor:"pointer",transition:"background-color 0.2s ease"},divider:{height:1,backgroundColor:"#eee",margin:"24px 0"},helpSection:{padding:0},helpRow:{display:"flex",gap:16,alignItems:"center"},qrcode:{width:96,height:96,borderRadius:8,flexShrink:0},helpText:{flex:1,minWidth:0},helpTitle:{margin:"0 0 4px",fontSize:14,fontWeight:500,color:"#333"},helpDesc:{margin:"0 0 12px",fontSize:12,color:"#999",lineHeight:1.5}},ep=p.lazy(()=>re(()=>import("./index-CBMgStgL.js"),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.Drawnix}))),tp=500,as="board",$s="aitu_board_close_snapshot_v1";let Ci=!1;async function np(e){const{initializeViewBox:t,updateViewBox:n,updateViewportOffset:o}=await re(async()=>{const{initializeViewBox:i,updateViewBox:s,updateViewportOffset:r}=await import("./ai-chat-B-XdoWBQ.js").then(a=>a.sL);return{initializeViewBox:i,updateViewBox:s,updateViewportOffset:r}},__vite__mapDeps([0]),import.meta.url);t(e),n(e),o(e)}function op(){if(!(typeof window>"u"))return window.__OPENTU_BOOT__}function Ur(){return new URLSearchParams(window.location.search).get(as)}function Gr(e,t=!1){const n=new URL(window.location.href);e?n.searchParams.set(as,e):n.searchParams.delete(as),t?window.history.replaceState({boardId:e},"",n.toString()):window.history.pushState({boardId:e},"",n.toString())}function ip(e){try{localStorage.setItem($s,JSON.stringify(e))}catch(t){console.warn("[App] Failed to save board close snapshot:",t)}}function il(){try{const e=localStorage.getItem($s);if(!e)return null;const t=JSON.parse(e);return!t||typeof t.boardId!="string"||typeof t.updatedAt!="number"||!Array.isArray(t.children)?null:t}catch(e){return console.warn("[App] Failed to load board close snapshot:",e),null}}function _o(e){try{const t=il();if(!t)return;(!e||t.boardId===e)&&localStorage.removeItem($s)}catch(t){console.warn("[App] Failed to clear board close snapshot:",t)}}function sp(){const[e,t]=p.useState(!0),[n,o]=p.useState(!1),i=p.useRef(!1),[s,r]=p.useState(!1),[a,c]=p.useState(null),[u,l]=p.useState({children:[]}),[h,f]=p.useState(null),g=p.useRef(null),y=p.useRef(),m=p.useRef(null),w=p.useRef(null),S=p.useRef(!1),v=p.useRef(null),E=p.useRef(!1),C=p.useRef(!1),D=p.useRef(!1);qf(h),p.useEffect(()=>{g.current=h},[h]);const P=p.useCallback((k,T,M=Date.now())=>{y.current=T.viewport,m.current={boardId:k,children:T.children,viewport:T.viewport,theme:T.theme,updatedAt:M}},[]),H=p.useCallback(k=>{const T=m.current,M=g.current;if(!T||!M||T.boardId!==M||!D.current)return;ip({...T,updatedAt:Date.now()}),yt.getInstance().saveCurrentBoard({children:T.children,viewport:T.viewport,theme:T.theme}).catch(q=>{console.warn(`[App] Failed to flush board on ${k}:`,q)})},[]);p.useEffect(()=>{const k=op();k&&(s||a||!e)&&k.markReady()},[a,e,s]),p.useEffect(()=>{s||a||e||el(["offline-static-assets"])},[a,e,s]),p.useEffect(()=>{(async()=>{if(et.shouldShowSafeModePrompt()&&!et.isSafeMode()){r(!0),t(!1);return}if(Ci){const T=yt.getInstance();t(!1),await T.waitForInitialization();const M=T.getState().currentBoardId;if(M&&T.getBoardMetadata(M)){const O=await T.switchBoard(M),q={children:O.elements||[],viewport:O.viewport,theme:O.theme};P(O.id,q,O.updatedAt),D.current=!1,l(q)}t(!1),et.markLoadingComplete();return}Ci=!0;try{const T=yt.getInstance();if(t(!1),await T.initialize(),await Kc()||await $f(),et.isSafeMode()){const Y=T.getAllBoards().find(ue=>ue.name.startsWith("安全模式")&&(!ue.elements||ue.elements.length===0));if(Y)await T.switchBoard(Y.id),f(Y.id);else{const ue=new Date().toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).replace(/\//g,"-"),_e=await T.createBoard({name:`安全模式 ${ue}`,elements:[]});_e&&(await T.switchBoard(_e.id),f(_e.id))}const he={children:[]},be=(Y==null?void 0:Y.id)||g.current||"safe-mode";P(be,he,Date.now()),l(he),i.current=!0,o(!0),t(!1),et.markLoadingComplete(),et.disableSafeMode(),setTimeout(()=>{Ne.warning({content:"当前处于安全模式,已创建空白画布。可从侧边栏切换到其他画布。",duration:8e3,closeBtn:!0})},500);return}let O=null;const q=Ur(),le=T.getState().currentBoardId;let R=null;if(q&&T.getBoardMetadata(q)?R=q:le&&T.getBoardMetadata(le)&&(R=le),R)O=await T.switchBoard(R);else if(T.hasBoards()){const L=T.getTree(),Y=sl(L);Y&&(O=await T.switchBoard(Y.id))}else{const L=await T.createBoard({name:"我的画板1",elements:[]});L&&(O=await T.switchBoard(L.id))}if(O&&(Gr(O.id,!0),f(O.id),T.persistCurrentBoardId(O.id),D.current=!1),O){const L=il();let Y={children:O.elements||[],viewport:O.viewport,theme:O.theme};if(L&&L.boardId===O.id&&L.updatedAt>O.updatedAt){Y={children:L.children,viewport:L.viewport,theme:L.theme},O={...O,...Y,updatedAt:L.updatedAt};const he=O.id;T.saveBoard(he,Y).then(()=>{D.current=!1,_o(he)}).catch(be=>{console.warn("[App] Failed to rehydrate board from close snapshot:",be)}),Ne.warning({content:"检测到上次关闭前的未落盘画布,已自动恢复",duration:5e3,closeBtn:!0})}else L&&L.boardId&&!T.getBoardMetadata(L.boardId)&&_o(L.boardId);P(O.id,Y,O.updatedAt),D.current=!1,l(Y),Ii(Y.children).then(he=>{if(he!==Y.children){const be={...Y,children:he};P(O.id,be,Date.now()),l(be)}}).catch(he=>{console.error("[App] Video URL recovery failed:",he)})}}catch(T){console.error("[App] Initialization failed:",T),c(T instanceof Error?T:new Error(String(T)))}finally{i.current=!0,o(!0),t(!1),et.markLoadingComplete()}})()},[P]);const B=p.useCallback(async(k,T=!1)=>{try{T||(Gr(k.id),yt.getInstance().persistCurrentBoardId(k.id)),f(k.id),C.current=!1,D.current=!1;const O={children:await Ii(k.elements||[]),viewport:k.viewport,theme:k.theme};P(k.id,O,k.updatedAt),l(O),setTimeout(()=>{v.current&&np(v.current).catch(q=>{console.warn("[App] Failed to refresh board bounds:",q)})},0)}catch(M){console.error("[App] Board switch failed:",M),Ne.error({content:`切换画板失败: ${M instanceof Error?M.message:"未知错误"}`,duration:5e3,closeBtn:!0})}},[P]);p.useEffect(()=>{const k=async()=>{if(!S.current){S.current=!0;try{const T=Ur();if(T&&T!==h){const M=yt.getInstance(),O=await M.switchBoard(T);O&&(await B(O,!0),M.persistCurrentBoardId(O.id))}}catch(T){console.error("[App] Failed to handle browser navigation:",T)}finally{S.current=!1}}};return window.addEventListener("popstate",k),()=>{window.removeEventListener("popstate",k)}},[h,B]);const j=p.useCallback(async()=>{E.current=!0;try{const k=yt.getInstance();let T=k.getCurrentBoard();if(!T){const O=k.getState().currentBoardId;if(!O){console.warn("[App] handleTabSyncNeeded: no current board ID");return}if(!k.getBoardMetadata(O)){console.warn("[App] handleTabSyncNeeded: board not found",O);return}try{T=await k.switchBoard(O)}catch(q){console.error("[App] handleTabSyncNeeded: failed to load board",q);return}}const M=await k.reloadBoard(T.id);if(M){const q={children:await Ii(M.elements||[]),viewport:M.viewport,theme:M.theme};P(M.id,q,M.updatedAt),D.current=!1,l(q)}}catch(k){console.error("[App] Failed to sync board data:",k),co()}finally{setTimeout(()=>{E.current=!1},100)}},[P]),U=p.useCallback(k=>{if(l(k),y.current=k.viewport,!i.current||E.current)return;C.current=!0,D.current=!0;const T=yt.getInstance(),M=T.getCurrentBoard();if(!M){console.warn("[App] handleBoardChange: board not fully loaded, skipping save");return}P(M.id,k),T.saveCurrentBoard(k).then(()=>{D.current=!1,_o(M.id),Yc(M.id)}).catch(O=>{console.error("[App] Failed to save board:",O)})},[P]),A=p.useCallback(k=>{y.current=k;const T=m.current;T&&(m.current={...T,viewport:k,updatedAt:Date.now()}),!E.current&&(D.current=!0,w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{if(E.current)return;const M=yt.getInstance(),O=M.getCurrentBoard();O&&M.saveCurrentBoard({children:O.elements,viewport:k,theme:O.theme}).then(()=>{D.current=!1,_o(O.id)}).catch(q=>{console.error("[App] Failed to save viewport:",q)})},tp))},[P]);p.useEffect(()=>{const k=q=>{if(w.current&&(clearTimeout(w.current),w.current=null),E.current)return;const R=yt.getInstance().getCurrentBoard(),L=m.current,Y=y.current,he=g.current;R&&he&&(!L||L.boardId!==he)&&P(R.id,{children:R.elements,viewport:Y??R.viewport,theme:R.theme},Date.now()),!(q==="visibilitychange"&&!C.current)&&H(q)},T=()=>{k("beforeunload")},M=()=>{document.visibilityState==="hidden"&&k("visibilitychange")},O=()=>{k("pagehide")};return window.addEventListener("beforeunload",T),window.addEventListener("pagehide",O),document.addEventListener("visibilitychange",M),()=>{window.removeEventListener("beforeunload",T),window.removeEventListener("pagehide",O),document.removeEventListener("visibilitychange",M),w.current&&clearTimeout(w.current)}},[H,P]);const I=p.useCallback(k=>{r(!1),k?et.enableSafeMode():et.clearCrashState(),t(!0),Ci=!1,setTimeout(()=>{co()},100)},[]);return s?d.jsx(Uo,{variant:"crash",crashCount:et.getCrashCount(),memoryInfo:et.getMemoryInfo(),onIgnore:()=>I(!1),onSafeModeReload:()=>I(!0),onGoToDebug:Wo}):a?d.jsx(Uo,{variant:"error",title:"应用初始化失败",description:"无法加载画板数据,可能是存储损坏或浏览器限制。",errorMessage:a.message,errorStack:a.stack,onExportLog:()=>ss(a),onSafeModeReload:rs,onGoToDebug:Wo}):e?d.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100vh"},children:"加载中..."}):d.jsx("div",{style:{height:"100vh"},children:d.jsx(p.Suspense,{fallback:null,children:d.jsx(ep,{value:u.children,viewport:u.viewport,theme:u.theme,onChange:U,onViewportChange:A,onBoardSwitch:B,onTabSyncNeeded:j,isDataReady:n,currentBoardId:h,afterInit:k=>{v.current=k,window.__drawnix__web__console=T=>{rp(k,T)}}})})})}const rp=async(e,t)=>{const{PlaitBoard:n}=await re(async()=>{const{PlaitBoard:r}=await import("./ai-chat-B-XdoWBQ.js").then(a=>a.sL);return{PlaitBoard:r}},__vite__mapDeps([0]),import.meta.url),o=n.getBoardContainer(e).closest(".drawnix");if(!o)return;let i=o.querySelector(".drawnix-console");i||(i=document.createElement("div"),i.classList.add("drawnix-console"),o.append(i));const s=document.createElement("div");s.innerHTML=t,i.append(s)};async function Ii(e){return e.map(t=>{const n=t.url;if(n!=null&&n.startsWith("/__aitu_cache__/video/"))return t;if(n!=null&&n.startsWith("blob:")&&n.includes("#merged-video-")){const o=n.indexOf("#merged-video-");if(o!==-1){const i=n.substring(o+1),s=i.indexOf("#",1),a=`/__aitu_cache__/video/${s>0?i.substring(0,s):i}.mp4`;return{...t,url:a}}}return t})}function sl(e){for(const t of e){if(t.type==="board")return t.data;if(t.type==="folder"&&t.children){const n=sl(t.children);if(n)return n}}return null}function cs(e,t,n){if(e&&e.length){const[o,i]=t,s=Math.PI/180*n,r=Math.cos(s),a=Math.sin(s);for(const c of e){const[u,l]=c;c[0]=(u-o)*r-(l-i)*a+o,c[1]=(u-o)*a+(l-i)*r+i}}}function ap(e,t,n){const o=[];e.forEach(i=>o.push(...i)),cs(o,t,n)}function cp(e,t){return e[0]===t[0]&&e[1]===t[1]}function lp(e,t,n,o=1){const i=n,s=Math.max(t,.1),r=e[0]&&e[0][0]&&typeof e[0][0]=="number"?[e]:e,a=[0,0];if(i)for(const u of r)cs(u,a,i);const c=up(r,s,o);if(i){for(const u of r)cs(u,a,-i);ap(c,a,-i)}return c}function up(e,t,n){const o=[];for(const u of e){const l=[...u];cp(l[0],l[l.length-1])||l.push([l[0][0],l[0][1]]),l.length>2&&o.push(l)}const i=[];t=Math.max(t,.1);const s=[];for(const u of o)for(let l=0;l<u.length-1;l++){const h=u[l],f=u[l+1];if(h[1]!==f[1]){const g=Math.min(h[1],f[1]);s.push({ymin:g,ymax:Math.max(h[1],f[1]),x:g===h[1]?h[0]:f[0],islope:(f[0]-h[0])/(f[1]-h[1])})}}if(s.sort((u,l)=>u.ymin<l.ymin?-1:u.ymin>l.ymin?1:u.x<l.x?-1:u.x>l.x?1:u.ymax===l.ymax?0:(u.ymax-l.ymax)/Math.abs(u.ymax-l.ymax)),!s.length)return i;let r=[],a=s[0].ymin,c=0;for(;r.length||s.length;){if(s.length){let u=-1;for(let h=0;h<s.length&&!(s[h].ymin>a);h++)u=h;s.splice(0,u+1).forEach(h=>{r.push({s:a,edge:h})})}if(r=r.filter(u=>!(u.edge.ymax<=a)),r.sort((u,l)=>u.edge.x===l.edge.x?0:(u.edge.x-l.edge.x)/Math.abs(u.edge.x-l.edge.x)),(n!==1||c%t===0)&&r.length>1)for(let u=0;u<r.length;u=u+2){const l=u+1;if(l>=r.length)break;const h=r[u].edge,f=r[l].edge;i.push([[Math.round(h.x),a],[Math.round(f.x),a]])}a+=n,r.forEach(u=>{u.edge.x=u.edge.x+n*u.edge.islope}),c++}return i}function xo(e,t){var n;const o=t.hachureAngle+90;let i=t.hachureGap;i<0&&(i=t.strokeWidth*4),i=Math.round(Math.max(i,.1));let s=1;return t.roughness>=1&&(((n=t.randomizer)===null||n===void 0?void 0:n.next())||Math.random())>.7&&(s=i),lp(e,i,o,s||1)}class Vs{constructor(t){this.helper=t}fillPolygons(t,n){return this._fillPolygons(t,n)}_fillPolygons(t,n){const o=xo(t,n);return{type:"fillSketch",ops:this.renderLines(o,n)}}renderLines(t,n){const o=[];for(const i of t)o.push(...this.helper.doubleLineOps(i[0][0],i[0][1],i[1][0],i[1][1],n));return o}}function gi(e){const t=e[0],n=e[1];return Math.sqrt(Math.pow(t[0]-n[0],2)+Math.pow(t[1]-n[1],2))}class dp extends Vs{fillPolygons(t,n){let o=n.hachureGap;o<0&&(o=n.strokeWidth*4),o=Math.max(o,.1);const i=Object.assign({},n,{hachureGap:o}),s=xo(t,i),r=Math.PI/180*n.hachureAngle,a=[],c=o*.5*Math.cos(r),u=o*.5*Math.sin(r);for(const[h,f]of s)gi([h,f])&&a.push([[h[0]-c,h[1]+u],[...f]],[[h[0]+c,h[1]-u],[...f]]);return{type:"fillSketch",ops:this.renderLines(a,n)}}}class hp extends Vs{fillPolygons(t,n){const o=this._fillPolygons(t,n),i=Object.assign({},n,{hachureAngle:n.hachureAngle+90}),s=this._fillPolygons(t,i);return o.ops=o.ops.concat(s.ops),o}}class fp{constructor(t){this.helper=t}fillPolygons(t,n){n=Object.assign({},n,{hachureAngle:0});const o=xo(t,n);return this.dotsOnLines(o,n)}dotsOnLines(t,n){const o=[];let i=n.hachureGap;i<0&&(i=n.strokeWidth*4),i=Math.max(i,.1);let s=n.fillWeight;s<0&&(s=n.strokeWidth/2);const r=i/4;for(const a of t){const c=gi(a),u=c/i,l=Math.ceil(u)-1,h=c-l*i,f=(a[0][0]+a[1][0])/2-i/4,g=Math.min(a[0][1],a[1][1]);for(let y=0;y<l;y++){const m=g+h+y*i,w=f-r+Math.random()*2*r,S=m-r+Math.random()*2*r,v=this.helper.ellipse(w,S,s,s,n);o.push(...v.ops)}}return{type:"fillSketch",ops:o}}}class gp{constructor(t){this.helper=t}fillPolygons(t,n){const o=xo(t,n);return{type:"fillSketch",ops:this.dashedLine(o,n)}}dashedLine(t,n){const o=n.dashOffset<0?n.hachureGap<0?n.strokeWidth*4:n.hachureGap:n.dashOffset,i=n.dashGap<0?n.hachureGap<0?n.strokeWidth*4:n.hachureGap:n.dashGap,s=[];return t.forEach(r=>{const a=gi(r),c=Math.floor(a/(o+i)),u=(a+i-c*(o+i))/2;let l=r[0],h=r[1];l[0]>h[0]&&(l=r[1],h=r[0]);const f=Math.atan((h[1]-l[1])/(h[0]-l[0]));for(let g=0;g<c;g++){const y=g*(o+i),m=y+o,w=[l[0]+y*Math.cos(f)+u*Math.cos(f),l[1]+y*Math.sin(f)+u*Math.sin(f)],S=[l[0]+m*Math.cos(f)+u*Math.cos(f),l[1]+m*Math.sin(f)+u*Math.sin(f)];s.push(...this.helper.doubleLineOps(w[0],w[1],S[0],S[1],n))}}),s}}class pp{constructor(t){this.helper=t}fillPolygons(t,n){const o=n.hachureGap<0?n.strokeWidth*4:n.hachureGap,i=n.zigzagOffset<0?o:n.zigzagOffset;n=Object.assign({},n,{hachureGap:o+i});const s=xo(t,n);return{type:"fillSketch",ops:this.zigzagLines(s,i,n)}}zigzagLines(t,n,o){const i=[];return t.forEach(s=>{const r=gi(s),a=Math.round(r/(2*n));let c=s[0],u=s[1];c[0]>u[0]&&(c=s[1],u=s[0]);const l=Math.atan((u[1]-c[1])/(u[0]-c[0]));for(let h=0;h<a;h++){const f=h*2*n,g=(h+1)*2*n,y=Math.sqrt(2*Math.pow(n,2)),m=[c[0]+f*Math.cos(l),c[1]+f*Math.sin(l)],w=[c[0]+g*Math.cos(l),c[1]+g*Math.sin(l)],S=[m[0]+y*Math.cos(l+Math.PI/4),m[1]+y*Math.sin(l+Math.PI/4)];i.push(...this.helper.doubleLineOps(m[0],m[1],S[0],S[1],o),...this.helper.doubleLineOps(S[0],S[1],w[0],w[1],o))}}),i}}const Qe={};function mp(e,t){let n=e.fillStyle||"hachure";if(!Qe[n])switch(n){case"zigzag":Qe[n]||(Qe[n]=new dp(t));break;case"cross-hatch":Qe[n]||(Qe[n]=new hp(t));break;case"dots":Qe[n]||(Qe[n]=new fp(t));break;case"dashed":Qe[n]||(Qe[n]=new gp(t));break;case"zigzag-line":Qe[n]||(Qe[n]=new pp(t));break;case"hachure":default:n="hachure",Qe[n]||(Qe[n]=new Vs(t));break}return Qe[n]}function wp(){return Math.floor(Math.random()*2**31)}class yp{constructor(t){this.seed=t}next(){return this.seed?(2**31-1&(this.seed=Math.imul(48271,this.seed)))/2**31:Math.random()}}const vp=0,ls=1,rl=2,Po={A:7,a:7,C:6,c:6,H:1,h:1,L:2,l:2,M:2,m:2,Q:4,q:4,S:4,s:4,T:2,t:2,V:1,v:1,Z:0,z:0};function Sp(e){const t=new Array;for(;e!=="";)if(e.match(/^([ \t\r\n,]+)/))e=e.substr(RegExp.$1.length);else if(e.match(/^([aAcChHlLmMqQsStTvVzZ])/))t[t.length]={type:vp,text:RegExp.$1},e=e.substr(RegExp.$1.length);else if(e.match(/^(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)/))t[t.length]={type:ls,text:`${parseFloat(RegExp.$1)}`},e=e.substr(RegExp.$1.length);else return[];return t[t.length]={type:rl,text:""},t}function Ai(e,t){return e.type===t}function Ws(e){const t=[],n=Sp(e);let o="BOD",i=0,s=n[i];for(;!Ai(s,rl);){let r=0;const a=[];if(o==="BOD")if(s.text==="M"||s.text==="m")i++,r=Po[s.text],o=s.text;else return Ws("M0,0"+e);else Ai(s,ls)?r=Po[o]:(i++,r=Po[s.text],o=s.text);if(i+r<n.length){for(let c=i;c<i+r;c++){const u=n[c];if(Ai(u,ls))a[a.length]=+u.text;else throw new Error("Param not a number: "+o+","+u.text)}if(typeof Po[o]=="number"){const c={key:o,data:a};t.push(c),i+=r,s=n[i],o==="M"&&(o="L"),o==="m"&&(o="l")}else throw new Error("Bad segment: "+o)}else throw new Error("Path data ended short")}return t}function al(e){let t=0,n=0,o=0,i=0;const s=[];for(const{key:r,data:a}of e)switch(r){case"M":s.push({key:"M",data:[...a]}),[t,n]=a,[o,i]=a;break;case"m":t+=a[0],n+=a[1],s.push({key:"M",data:[t,n]}),o=t,i=n;break;case"L":s.push({key:"L",data:[...a]}),[t,n]=a;break;case"l":t+=a[0],n+=a[1],s.push({key:"L",data:[t,n]});break;case"C":s.push({key:"C",data:[...a]}),t=a[4],n=a[5];break;case"c":{const c=a.map((u,l)=>l%2?u+n:u+t);s.push({key:"C",data:c}),t=c[4],n=c[5];break}case"Q":s.push({key:"Q",data:[...a]}),t=a[2],n=a[3];break;case"q":{const c=a.map((u,l)=>l%2?u+n:u+t);s.push({key:"Q",data:c}),t=c[2],n=c[3];break}case"A":s.push({key:"A",data:[...a]}),t=a[5],n=a[6];break;case"a":t+=a[5],n+=a[6],s.push({key:"A",data:[a[0],a[1],a[2],a[3],a[4],t,n]});break;case"H":s.push({key:"H",data:[...a]}),t=a[0];break;case"h":t+=a[0],s.push({key:"H",data:[t]});break;case"V":s.push({key:"V",data:[...a]}),n=a[0];break;case"v":n+=a[0],s.push({key:"V",data:[n]});break;case"S":s.push({key:"S",data:[...a]}),t=a[2],n=a[3];break;case"s":{const c=a.map((u,l)=>l%2?u+n:u+t);s.push({key:"S",data:c}),t=c[2],n=c[3];break}case"T":s.push({key:"T",data:[...a]}),t=a[0],n=a[1];break;case"t":t+=a[0],n+=a[1],s.push({key:"T",data:[t,n]});break;case"Z":case"z":s.push({key:"Z",data:[]}),t=o,n=i;break}return s}function cl(e){const t=[];let n="",o=0,i=0,s=0,r=0,a=0,c=0;for(const{key:u,data:l}of e){switch(u){case"M":t.push({key:"M",data:[...l]}),[o,i]=l,[s,r]=l;break;case"C":t.push({key:"C",data:[...l]}),o=l[4],i=l[5],a=l[2],c=l[3];break;case"L":t.push({key:"L",data:[...l]}),[o,i]=l;break;case"H":o=l[0],t.push({key:"L",data:[o,i]});break;case"V":i=l[0],t.push({key:"L",data:[o,i]});break;case"S":{let h=0,f=0;n==="C"||n==="S"?(h=o+(o-a),f=i+(i-c)):(h=o,f=i),t.push({key:"C",data:[h,f,...l]}),a=l[0],c=l[1],o=l[2],i=l[3];break}case"T":{const[h,f]=l;let g=0,y=0;n==="Q"||n==="T"?(g=o+(o-a),y=i+(i-c)):(g=o,y=i);const m=o+2*(g-o)/3,w=i+2*(y-i)/3,S=h+2*(g-h)/3,v=f+2*(y-f)/3;t.push({key:"C",data:[m,w,S,v,h,f]}),a=g,c=y,o=h,i=f;break}case"Q":{const[h,f,g,y]=l,m=o+2*(h-o)/3,w=i+2*(f-i)/3,S=g+2*(h-g)/3,v=y+2*(f-y)/3;t.push({key:"C",data:[m,w,S,v,g,y]}),a=h,c=f,o=g,i=y;break}case"A":{const h=Math.abs(l[0]),f=Math.abs(l[1]),g=l[2],y=l[3],m=l[4],w=l[5],S=l[6];h===0||f===0?(t.push({key:"C",data:[o,i,w,S,w,S]}),o=w,i=S):(o!==w||i!==S)&&(ll(o,i,w,S,h,f,g,y,m).forEach(function(E){t.push({key:"C",data:E})}),o=w,i=S);break}case"Z":t.push({key:"Z",data:[]}),o=s,i=r;break}n=u}return t}function xp(e){return Math.PI*e/180}function An(e,t,n){const o=e*Math.cos(n)-t*Math.sin(n),i=e*Math.sin(n)+t*Math.cos(n);return[o,i]}function ll(e,t,n,o,i,s,r,a,c,u){const l=xp(r);let h=[],f=0,g=0,y=0,m=0;if(u)[f,g,y,m]=u;else{[e,t]=An(e,t,-l),[n,o]=An(n,o,-l);const I=(e-n)/2,k=(t-o)/2;let T=I*I/(i*i)+k*k/(s*s);T>1&&(T=Math.sqrt(T),i=T*i,s=T*s);const M=a===c?-1:1,O=i*i,q=s*s,le=O*q-O*k*k-q*I*I,R=O*k*k+q*I*I,L=M*Math.sqrt(Math.abs(le/R));y=L*i*k/s+(e+n)/2,m=L*-s*I/i+(t+o)/2,f=Math.asin(parseFloat(((t-m)/s).toFixed(9))),g=Math.asin(parseFloat(((o-m)/s).toFixed(9))),e<y&&(f=Math.PI-f),n<y&&(g=Math.PI-g),f<0&&(f=Math.PI*2+f),g<0&&(g=Math.PI*2+g),c&&f>g&&(f=f-Math.PI*2),!c&&g>f&&(g=g-Math.PI*2)}let w=g-f;if(Math.abs(w)>Math.PI*120/180){const I=g,k=n,T=o;c&&g>f?g=f+Math.PI*120/180*1:g=f+Math.PI*120/180*-1,n=y+i*Math.cos(g),o=m+s*Math.sin(g),h=ll(n,o,k,T,i,s,r,0,c,[g,I,y,m])}w=g-f;const S=Math.cos(f),v=Math.sin(f),E=Math.cos(g),C=Math.sin(g),D=Math.tan(w/4),P=4/3*i*D,H=4/3*s*D,B=[e,t],j=[e+P*v,t-H*S],U=[n+P*C,o-H*E],A=[n,o];if(j[0]=2*B[0]-j[0],j[1]=2*B[1]-j[1],u)return[j,U,A].concat(h);{h=[j,U,A].concat(h);const I=[];for(let k=0;k<h.length;k+=3){const T=An(h[k][0],h[k][1],l),M=An(h[k+1][0],h[k+1][1],l),O=An(h[k+2][0],h[k+2][1],l);I.push([T[0],T[1],M[0],M[1],O[0],O[1]])}return I}}const kp={randOffset:Tp,randOffsetWithRange:Cp,ellipse:_p,doubleLineOps:Ip};function ul(e,t,n,o,i){return{type:"path",ops:Bt(e,t,n,o,i)}}function Lo(e,t,n){const o=(e||[]).length;if(o>2){const i=[];for(let s=0;s<o-1;s++)i.push(...Bt(e[s][0],e[s][1],e[s+1][0],e[s+1][1],n));return t&&i.push(...Bt(e[o-1][0],e[o-1][1],e[0][0],e[0][1],n)),{type:"path",ops:i}}else if(o===2)return ul(e[0][0],e[0][1],e[1][0],e[1][1],n);return{type:"path",ops:[]}}function Ep(e,t){return Lo(e,!0,t)}function bp(e,t,n,o,i){const s=[[e,t],[e+n,t],[e+n,t+o],[e,t+o]];return Ep(s,i)}function Kr(e,t){if(e.length){const o=typeof e[0][0]=="number"?[e]:e,i=To(o[0],1*(1+t.roughness*.2),t),s=t.disableMultiStroke?[]:To(o[0],1.5*(1+t.roughness*.22),Xr(t));for(let r=1;r<o.length;r++){const a=o[r];if(a.length){const c=To(a,1*(1+t.roughness*.2),t),u=t.disableMultiStroke?[]:To(a,1.5*(1+t.roughness*.22),Xr(t));for(const l of c)l.op!=="move"&&i.push(l);for(const l of u)l.op!=="move"&&s.push(l)}}return{type:"path",ops:i.concat(s)}}return{type:"path",ops:[]}}function _p(e,t,n,o,i){const s=dl(n,o,i);return us(e,t,i,s).opset}function dl(e,t,n){const o=Math.sqrt(Math.PI*2*Math.sqrt((Math.pow(e/2,2)+Math.pow(t/2,2))/2)),i=Math.ceil(Math.max(n.curveStepCount,n.curveStepCount/Math.sqrt(200)*o)),s=Math.PI*2/i;let r=Math.abs(e/2),a=Math.abs(t/2);const c=1-n.curveFitting;return r+=J(r*c,n),a+=J(a*c,n),{increment:s,rx:r,ry:a}}function us(e,t,n,o){const[i,s]=Zr(o.increment,e,t,o.rx,o.ry,1,o.increment*Go(.1,Go(.4,1,n),n),n);let r=Ko(i,null,n);if(!n.disableMultiStroke&&n.roughness!==0){const[a]=Zr(o.increment,e,t,o.rx,o.ry,1.5,0,n),c=Ko(a,null,n);r=r.concat(c)}return{estimatedPoints:s,opset:{type:"path",ops:r}}}function qr(e,t,n,o,i,s,r,a,c){const u=e,l=t;let h=Math.abs(n/2),f=Math.abs(o/2);h+=J(h*.01,c),f+=J(f*.01,c);let g=i,y=s;for(;g<0;)g+=Math.PI*2,y+=Math.PI*2;y-g>Math.PI*2&&(g=0,y=Math.PI*2);const m=Math.PI*2/c.curveStepCount,w=Math.min(m/2,(y-g)/2),S=Jr(w,u,l,h,f,g,y,1,c);if(!c.disableMultiStroke){const v=Jr(w,u,l,h,f,g,y,1.5,c);S.push(...v)}return r&&(a?S.push(...Bt(u,l,u+h*Math.cos(g),l+f*Math.sin(g),c),...Bt(u,l,u+h*Math.cos(y),l+f*Math.sin(y),c)):S.push({op:"lineTo",data:[u,l]},{op:"lineTo",data:[u+h*Math.cos(g),l+f*Math.sin(g)]})),{type:"path",ops:S}}function Yr(e,t){const n=cl(al(Ws(e))),o=[];let i=[0,0],s=[0,0];for(const{key:r,data:a}of n)switch(r){case"M":{s=[a[0],a[1]],i=[a[0],a[1]];break}case"L":o.push(...Bt(s[0],s[1],a[0],a[1],t)),s=[a[0],a[1]];break;case"C":{const[c,u,l,h,f,g]=a;o.push(...Ap(c,u,l,h,f,g,s,t)),s=[f,g];break}case"Z":o.push(...Bt(s[0],s[1],i[0],i[1],t)),s=[i[0],i[1]];break}return{type:"path",ops:o}}function Mi(e,t){const n=[];for(const o of e)if(o.length){const i=t.maxRandomnessOffset||0,s=o.length;if(s>2){n.push({op:"move",data:[o[0][0]+J(i,t),o[0][1]+J(i,t)]});for(let r=1;r<s;r++)n.push({op:"lineTo",data:[o[r][0]+J(i,t),o[r][1]+J(i,t)]})}}return{type:"fillPath",ops:n}}function hn(e,t){return mp(t,kp).fillPolygons(e,t)}function Pp(e,t,n,o,i,s,r){const a=e,c=t;let u=Math.abs(n/2),l=Math.abs(o/2);u+=J(u*.01,r),l+=J(l*.01,r);let h=i,f=s;for(;h<0;)h+=Math.PI*2,f+=Math.PI*2;f-h>Math.PI*2&&(h=0,f=Math.PI*2);const g=(f-h)/r.curveStepCount,y=[];for(let m=h;m<=f;m=m+g)y.push([a+u*Math.cos(m),c+l*Math.sin(m)]);return y.push([a+u*Math.cos(f),c+l*Math.sin(f)]),y.push([a,c]),hn([y],r)}function Tp(e,t){return J(e,t)}function Cp(e,t,n){return Go(e,t,n)}function Ip(e,t,n,o,i){return Bt(e,t,n,o,i,!0)}function Xr(e){const t=Object.assign({},e);return t.randomizer=void 0,e.seed&&(t.seed=e.seed+1),t}function hl(e){return e.randomizer||(e.randomizer=new yp(e.seed||0)),e.randomizer.next()}function Go(e,t,n,o=1){return n.roughness*o*(hl(n)*(t-e)+e)}function J(e,t,n=1){return Go(-e,e,t,n)}function Bt(e,t,n,o,i,s=!1){const r=s?i.disableMultiStrokeFill:i.disableMultiStroke,a=ds(e,t,n,o,i,!0,!1);if(r)return a;const c=ds(e,t,n,o,i,!0,!0);return a.concat(c)}function ds(e,t,n,o,i,s,r){const a=Math.pow(e-n,2)+Math.pow(t-o,2),c=Math.sqrt(a);let u=1;c<200?u=1:c>500?u=.4:u=-.0016668*c+1.233334;let l=i.maxRandomnessOffset||0;l*l*100>a&&(l=c/10);const h=l/2,f=.2+hl(i)*.2;let g=i.bowing*i.maxRandomnessOffset*(o-t)/200,y=i.bowing*i.maxRandomnessOffset*(e-n)/200;g=J(g,i,u),y=J(y,i,u);const m=[],w=()=>J(h,i,u),S=()=>J(l,i,u),v=i.preserveVertices;return r?m.push({op:"move",data:[e+(v?0:w()),t+(v?0:w())]}):m.push({op:"move",data:[e+(v?0:J(l,i,u)),t+(v?0:J(l,i,u))]}),r?m.push({op:"bcurveTo",data:[g+e+(n-e)*f+w(),y+t+(o-t)*f+w(),g+e+2*(n-e)*f+w(),y+t+2*(o-t)*f+w(),n+(v?0:w()),o+(v?0:w())]}):m.push({op:"bcurveTo",data:[g+e+(n-e)*f+S(),y+t+(o-t)*f+S(),g+e+2*(n-e)*f+S(),y+t+2*(o-t)*f+S(),n+(v?0:S()),o+(v?0:S())]}),m}function To(e,t,n){if(!e.length)return[];const o=[];o.push([e[0][0]+J(t,n),e[0][1]+J(t,n)]),o.push([e[0][0]+J(t,n),e[0][1]+J(t,n)]);for(let i=1;i<e.length;i++)o.push([e[i][0]+J(t,n),e[i][1]+J(t,n)]),i===e.length-1&&o.push([e[i][0]+J(t,n),e[i][1]+J(t,n)]);return Ko(o,null,n)}function Ko(e,t,n){const o=e.length,i=[];if(o>3){const s=[],r=1-n.curveTightness;i.push({op:"move",data:[e[1][0],e[1][1]]});for(let a=1;a+2<o;a++){const c=e[a];s[0]=[c[0],c[1]],s[1]=[c[0]+(r*e[a+1][0]-r*e[a-1][0])/6,c[1]+(r*e[a+1][1]-r*e[a-1][1])/6],s[2]=[e[a+1][0]+(r*e[a][0]-r*e[a+2][0])/6,e[a+1][1]+(r*e[a][1]-r*e[a+2][1])/6],s[3]=[e[a+1][0],e[a+1][1]],i.push({op:"bcurveTo",data:[s[1][0],s[1][1],s[2][0],s[2][1],s[3][0],s[3][1]]})}}else o===3?(i.push({op:"move",data:[e[1][0],e[1][1]]}),i.push({op:"bcurveTo",data:[e[1][0],e[1][1],e[2][0],e[2][1],e[2][0],e[2][1]]})):o===2&&i.push(...ds(e[0][0],e[0][1],e[1][0],e[1][1],n,!0,!0));return i}function Zr(e,t,n,o,i,s,r,a){const c=a.roughness===0,u=[],l=[];if(c){e=e/4,l.push([t+o*Math.cos(-e),n+i*Math.sin(-e)]);for(let h=0;h<=Math.PI*2;h=h+e){const f=[t+o*Math.cos(h),n+i*Math.sin(h)];u.push(f),l.push(f)}l.push([t+o*Math.cos(0),n+i*Math.sin(0)]),l.push([t+o*Math.cos(e),n+i*Math.sin(e)])}else{const h=J(.5,a)-Math.PI/2;l.push([J(s,a)+t+.9*o*Math.cos(h-e),J(s,a)+n+.9*i*Math.sin(h-e)]);const f=Math.PI*2+h-.01;for(let g=h;g<f;g=g+e){const y=[J(s,a)+t+o*Math.cos(g),J(s,a)+n+i*Math.sin(g)];u.push(y),l.push(y)}l.push([J(s,a)+t+o*Math.cos(h+Math.PI*2+r*.5),J(s,a)+n+i*Math.sin(h+Math.PI*2+r*.5)]),l.push([J(s,a)+t+.98*o*Math.cos(h+r),J(s,a)+n+.98*i*Math.sin(h+r)]),l.push([J(s,a)+t+.9*o*Math.cos(h+r*.5),J(s,a)+n+.9*i*Math.sin(h+r*.5)])}return[l,u]}function Jr(e,t,n,o,i,s,r,a,c){const u=s+J(.1,c),l=[];l.push([J(a,c)+t+.9*o*Math.cos(u-e),J(a,c)+n+.9*i*Math.sin(u-e)]);for(let h=u;h<=r;h=h+e)l.push([J(a,c)+t+o*Math.cos(h),J(a,c)+n+i*Math.sin(h)]);return l.push([t+o*Math.cos(r),n+i*Math.sin(r)]),l.push([t+o*Math.cos(r),n+i*Math.sin(r)]),Ko(l,null,c)}function Ap(e,t,n,o,i,s,r,a){const c=[],u=[a.maxRandomnessOffset||1,(a.maxRandomnessOffset||1)+.3];let l=[0,0];const h=a.disableMultiStroke?1:2,f=a.preserveVertices;for(let g=0;g<h;g++)g===0?c.push({op:"move",data:[r[0],r[1]]}):c.push({op:"move",data:[r[0]+(f?0:J(u[0],a)),r[1]+(f?0:J(u[0],a))]}),l=f?[i,s]:[i+J(u[g],a),s+J(u[g],a)],c.push({op:"bcurveTo",data:[e+J(u[g],a),t+J(u[g],a),n+J(u[g],a),o+J(u[g],a),l[0],l[1]]});return c}function Mn(e){return[...e]}function Qr(e,t=0){const n=e.length;if(n<3)throw new Error("A curve must have at least three points.");const o=[];if(n===3)o.push(Mn(e[0]),Mn(e[1]),Mn(e[2]),Mn(e[2]));else{const i=[];i.push(e[0],e[0]);for(let a=1;a<e.length;a++)i.push(e[a]),a===e.length-1&&i.push(e[a]);const s=[],r=1-t;o.push(Mn(i[0]));for(let a=1;a+2<i.length;a++){const c=i[a];s[0]=[c[0],c[1]],s[1]=[c[0]+(r*i[a+1][0]-r*i[a-1][0])/6,c[1]+(r*i[a+1][1]-r*i[a-1][1])/6],s[2]=[i[a+1][0]+(r*i[a][0]-r*i[a+2][0])/6,i[a+1][1]+(r*i[a][1]-r*i[a+2][1])/6],s[3]=[i[a+1][0],i[a+1][1]],o.push(s[1],s[2],s[3])}}return o}function Mp(e,t){return Math.sqrt(jo(e,t))}function jo(e,t){return Math.pow(e[0]-t[0],2)+Math.pow(e[1]-t[1],2)}function Rp(e,t,n){const o=jo(t,n);if(o===0)return jo(e,t);let i=((e[0]-t[0])*(n[0]-t[0])+(e[1]-t[1])*(n[1]-t[1]))/o;return i=Math.max(0,Math.min(1,i)),jo(e,qt(t,n,i))}function qt(e,t,n){return[e[0]+(t[0]-e[0])*n,e[1]+(t[1]-e[1])*n]}function Dp(e,t){const n=e[t+0],o=e[t+1],i=e[t+2],s=e[t+3];let r=3*o[0]-2*n[0]-s[0];r*=r;let a=3*o[1]-2*n[1]-s[1];a*=a;let c=3*i[0]-2*s[0]-n[0];c*=c;let u=3*i[1]-2*s[1]-n[1];return u*=u,r<c&&(r=c),a<u&&(a=u),r+a}function hs(e,t,n,o){const i=o||[];if(Dp(e,t)<n){const s=e[t+0];i.length?Mp(i[i.length-1],s)>1&&i.push(s):i.push(s),i.push(e[t+3])}else{const r=e[t+0],a=e[t+1],c=e[t+2],u=e[t+3],l=qt(r,a,.5),h=qt(a,c,.5),f=qt(c,u,.5),g=qt(l,h,.5),y=qt(h,f,.5),m=qt(g,y,.5);hs([r,l,g,m],0,n,i),hs([m,y,f,u],0,n,i)}return i}function Lp(e,t){return qo(e,0,e.length,t)}function qo(e,t,n,o,i){const s=i||[],r=e[t],a=e[n-1];let c=0,u=1;for(let l=t+1;l<n-1;++l){const h=Rp(e[l],r,a);h>c&&(c=h,u=l)}return Math.sqrt(c)>o?(qo(e,t,u+1,o,s),qo(e,u,n,o,s)):(s.length||s.push(r),s.push(a)),s}function fs(e,t=.15,n){const o=[],i=(e.length-1)/3;for(let s=0;s<i;s++){const r=s*3;hs(e,r,t,o)}return n&&n>0?qo(o,0,o.length,n):o}function jp(e,t,n){const o=Ws(e),i=cl(al(o)),s=[];let r=[],a=[0,0],c=[];const u=()=>{c.length>=4&&r.push(...fs(c,t)),c=[]},l=()=>{u(),r.length&&(s.push(r),r=[])};for(const{key:f,data:g}of i)switch(f){case"M":l(),a=[g[0],g[1]],r.push(a);break;case"L":u(),r.push([g[0],g[1]]);break;case"C":if(!c.length){const y=r.length?r[r.length-1]:a;c.push([y[0],y[1]])}c.push([g[0],g[1]]),c.push([g[2],g[3]]),c.push([g[4],g[5]]);break;case"Z":u(),r.push([a[0],a[1]]);break}if(l(),!n)return s;const h=[];for(const f of s){const g=Lp(f,n);g.length&&h.push(g)}return h}const it="none";class Yo{constructor(t){this.defaultOptions={maxRandomnessOffset:2,roughness:1,bowing:1,stroke:"#000",strokeWidth:1,curveTightness:0,curveFitting:.95,curveStepCount:9,fillStyle:"hachure",fillWeight:-1,hachureAngle:-41,hachureGap:-1,dashOffset:-1,dashGap:-1,zigzagOffset:-1,seed:0,disableMultiStroke:!1,disableMultiStrokeFill:!1,preserveVertices:!1,fillShapeRoughnessGain:.8},this.config=t||{},this.config.options&&(this.defaultOptions=this._o(this.config.options))}static newSeed(){return wp()}_o(t){return t?Object.assign({},this.defaultOptions,t):this.defaultOptions}_d(t,n,o){return{shape:t,sets:n||[],options:o||this.defaultOptions}}line(t,n,o,i,s){const r=this._o(s);return this._d("line",[ul(t,n,o,i,r)],r)}rectangle(t,n,o,i,s){const r=this._o(s),a=[],c=bp(t,n,o,i,r);if(r.fill){const u=[[t,n],[t+o,n],[t+o,n+i],[t,n+i]];r.fillStyle==="solid"?a.push(Mi([u],r)):a.push(hn([u],r))}return r.stroke!==it&&a.push(c),this._d("rectangle",a,r)}ellipse(t,n,o,i,s){const r=this._o(s),a=[],c=dl(o,i,r),u=us(t,n,r,c);if(r.fill)if(r.fillStyle==="solid"){const l=us(t,n,r,c).opset;l.type="fillPath",a.push(l)}else a.push(hn([u.estimatedPoints],r));return r.stroke!==it&&a.push(u.opset),this._d("ellipse",a,r)}circle(t,n,o,i){const s=this.ellipse(t,n,o,o,i);return s.shape="circle",s}linearPath(t,n){const o=this._o(n);return this._d("linearPath",[Lo(t,!1,o)],o)}arc(t,n,o,i,s,r,a=!1,c){const u=this._o(c),l=[],h=qr(t,n,o,i,s,r,a,!0,u);if(a&&u.fill)if(u.fillStyle==="solid"){const f=Object.assign({},u);f.disableMultiStroke=!0;const g=qr(t,n,o,i,s,r,!0,!1,f);g.type="fillPath",l.push(g)}else l.push(Pp(t,n,o,i,s,r,u));return u.stroke!==it&&l.push(h),this._d("arc",l,u)}curve(t,n){const o=this._o(n),i=[],s=Kr(t,o);if(o.fill&&o.fill!==it)if(o.fillStyle==="solid"){const r=Kr(t,Object.assign(Object.assign({},o),{disableMultiStroke:!0,roughness:o.roughness?o.roughness+o.fillShapeRoughnessGain:0}));i.push({type:"fillPath",ops:this._mergedShape(r.ops)})}else{const r=[],a=t;if(a.length){const u=typeof a[0][0]=="number"?[a]:a;for(const l of u)l.length<3?r.push(...l):l.length===3?r.push(...fs(Qr([l[0],l[0],l[1],l[2]]),10,(1+o.roughness)/2)):r.push(...fs(Qr(l),10,(1+o.roughness)/2))}r.length&&i.push(hn([r],o))}return o.stroke!==it&&i.push(s),this._d("curve",i,o)}polygon(t,n){const o=this._o(n),i=[],s=Lo(t,!0,o);return o.fill&&(o.fillStyle==="solid"?i.push(Mi([t],o)):i.push(hn([t],o))),o.stroke!==it&&i.push(s),this._d("polygon",i,o)}path(t,n){const o=this._o(n),i=[];if(!t)return this._d("path",i,o);t=(t||"").replace(/\n/g," ").replace(/(-\s)/g,"-").replace("/(ss)/g"," ");const s=o.fill&&o.fill!=="transparent"&&o.fill!==it,r=o.stroke!==it,a=!!(o.simplification&&o.simplification<1),c=a?4-4*(o.simplification||1):(1+o.roughness)/2,u=jp(t,1,c),l=Yr(t,o);if(s)if(o.fillStyle==="solid")if(u.length===1){const h=Yr(t,Object.assign(Object.assign({},o),{disableMultiStroke:!0,roughness:o.roughness?o.roughness+o.fillShapeRoughnessGain:0}));i.push({type:"fillPath",ops:this._mergedShape(h.ops)})}else i.push(Mi(u,o));else i.push(hn(u,o));return r&&(a?u.forEach(h=>{i.push(Lo(h,!1,o))}):i.push(l)),this._d("path",i,o)}opsToPath(t,n){let o="";for(const i of t.ops){const s=typeof n=="number"&&n>=0?i.data.map(r=>+r.toFixed(n)):i.data;switch(i.op){case"move":o+=`M${s[0]} ${s[1]} `;break;case"bcurveTo":o+=`C${s[0]} ${s[1]}, ${s[2]} ${s[3]}, ${s[4]} ${s[5]} `;break;case"lineTo":o+=`L${s[0]} ${s[1]} `;break}}return o.trim()}toPaths(t){const n=t.sets||[],o=t.options||this.defaultOptions,i=[];for(const s of n){let r=null;switch(s.type){case"path":r={d:this.opsToPath(s),stroke:o.stroke,strokeWidth:o.strokeWidth,fill:it};break;case"fillPath":r={d:this.opsToPath(s),stroke:it,strokeWidth:0,fill:o.fill||it};break;case"fillSketch":r=this.fillSketch(s,o);break}r&&i.push(r)}return i}fillSketch(t,n){let o=n.fillWeight;return o<0&&(o=n.strokeWidth/2),{d:this.opsToPath(t),stroke:n.fill||it,strokeWidth:o,fill:it}}_mergedShape(t){return t.filter((n,o)=>o===0?!0:n.op!=="move")}}class Op{constructor(t,n){this.canvas=t,this.ctx=this.canvas.getContext("2d"),this.gen=new Yo(n)}draw(t){const n=t.sets||[],o=t.options||this.getDefaultOptions(),i=this.ctx,s=t.options.fixedDecimalPlaceDigits;for(const r of n)switch(r.type){case"path":i.save(),i.strokeStyle=o.stroke==="none"?"transparent":o.stroke,i.lineWidth=o.strokeWidth,o.strokeLineDash&&i.setLineDash(o.strokeLineDash),o.strokeLineDashOffset&&(i.lineDashOffset=o.strokeLineDashOffset),this._drawToContext(i,r,s),i.restore();break;case"fillPath":{i.save(),i.fillStyle=o.fill||"";const a=t.shape==="curve"||t.shape==="polygon"||t.shape==="path"?"evenodd":"nonzero";this._drawToContext(i,r,s,a),i.restore();break}case"fillSketch":this.fillSketch(i,r,o);break}}fillSketch(t,n,o){let i=o.fillWeight;i<0&&(i=o.strokeWidth/2),t.save(),o.fillLineDash&&t.setLineDash(o.fillLineDash),o.fillLineDashOffset&&(t.lineDashOffset=o.fillLineDashOffset),t.strokeStyle=o.fill||"",t.lineWidth=i,this._drawToContext(t,n,o.fixedDecimalPlaceDigits),t.restore()}_drawToContext(t,n,o,i="nonzero"){t.beginPath();for(const s of n.ops){const r=typeof o=="number"&&o>=0?s.data.map(a=>+a.toFixed(o)):s.data;switch(s.op){case"move":t.moveTo(r[0],r[1]);break;case"bcurveTo":t.bezierCurveTo(r[0],r[1],r[2],r[3],r[4],r[5]);break;case"lineTo":t.lineTo(r[0],r[1]);break}}n.type==="fillPath"?t.fill(i):t.stroke()}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}line(t,n,o,i,s){const r=this.gen.line(t,n,o,i,s);return this.draw(r),r}rectangle(t,n,o,i,s){const r=this.gen.rectangle(t,n,o,i,s);return this.draw(r),r}ellipse(t,n,o,i,s){const r=this.gen.ellipse(t,n,o,i,s);return this.draw(r),r}circle(t,n,o,i){const s=this.gen.circle(t,n,o,i);return this.draw(s),s}linearPath(t,n){const o=this.gen.linearPath(t,n);return this.draw(o),o}polygon(t,n){const o=this.gen.polygon(t,n);return this.draw(o),o}arc(t,n,o,i,s,r,a=!1,c){const u=this.gen.arc(t,n,o,i,s,r,a,c);return this.draw(u),u}curve(t,n){const o=this.gen.curve(t,n);return this.draw(o),o}path(t,n){const o=this.gen.path(t,n);return this.draw(o),o}}const Co="http://www.w3.org/2000/svg";class Np{constructor(t,n){this.svg=t,this.gen=new Yo(n)}draw(t){const n=t.sets||[],o=t.options||this.getDefaultOptions(),i=this.svg.ownerDocument||window.document,s=i.createElementNS(Co,"g"),r=t.options.fixedDecimalPlaceDigits;for(const a of n){let c=null;switch(a.type){case"path":{c=i.createElementNS(Co,"path"),c.setAttribute("d",this.opsToPath(a,r)),c.setAttribute("stroke",o.stroke),c.setAttribute("stroke-width",o.strokeWidth+""),c.setAttribute("fill","none"),o.strokeLineDash&&c.setAttribute("stroke-dasharray",o.strokeLineDash.join(" ").trim()),o.strokeLineDashOffset&&c.setAttribute("stroke-dashoffset",`${o.strokeLineDashOffset}`);break}case"fillPath":{c=i.createElementNS(Co,"path"),c.setAttribute("d",this.opsToPath(a,r)),c.setAttribute("stroke","none"),c.setAttribute("stroke-width","0"),c.setAttribute("fill",o.fill||""),(t.shape==="curve"||t.shape==="polygon")&&c.setAttribute("fill-rule","evenodd");break}case"fillSketch":{c=this.fillSketch(i,a,o);break}}c&&s.appendChild(c)}return s}fillSketch(t,n,o){let i=o.fillWeight;i<0&&(i=o.strokeWidth/2);const s=t.createElementNS(Co,"path");return s.setAttribute("d",this.opsToPath(n,o.fixedDecimalPlaceDigits)),s.setAttribute("stroke",o.fill||""),s.setAttribute("stroke-width",i+""),s.setAttribute("fill","none"),o.fillLineDash&&s.setAttribute("stroke-dasharray",o.fillLineDash.join(" ").trim()),o.fillLineDashOffset&&s.setAttribute("stroke-dashoffset",`${o.fillLineDashOffset}`),s}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}opsToPath(t,n){return this.gen.opsToPath(t,n)}line(t,n,o,i,s){const r=this.gen.line(t,n,o,i,s);return this.draw(r)}rectangle(t,n,o,i,s){const r=this.gen.rectangle(t,n,o,i,s);return this.draw(r)}ellipse(t,n,o,i,s){const r=this.gen.ellipse(t,n,o,i,s);return this.draw(r)}circle(t,n,o,i){const s=this.gen.circle(t,n,o,i);return this.draw(s)}linearPath(t,n){const o=this.gen.linearPath(t,n);return this.draw(o)}polygon(t,n){const o=this.gen.polygon(t,n);return this.draw(o)}arc(t,n,o,i,s,r,a=!1,c){const u=this.gen.arc(t,n,o,i,s,r,a,c);return this.draw(u)}curve(t,n){const o=this.gen.curve(t,n);return this.draw(o)}path(t,n){const o=this.gen.path(t,n);return this.draw(o)}}const zp={canvas(e,t){return new Op(e,t)},svg(e,t){return new Np(e,t)},generator(e){return new Yo(e)},newSeed(){return Yo.newSeed()}};function Fp(e){return e?"current"in e?e.current||null:e:typeof window>"u"?null:window}function We(e,t,n={}){const o=p.useRef(t),{target:i,capture:s,passive:r,once:a}=n;p.useEffect(()=>{o.current=t},[t]),p.useEffect(()=>{const c=Fp(i);if(!c)return;const u=h=>{o.current(h)},l={capture:s,passive:r,once:a};return c.addEventListener(e,u,l),()=>{c.removeEventListener(e,u,l)}},[e,i,s,r,a])}const Ri=e=>Ua(e)?!0:e instanceof Element&&!!e.closest('[contenteditable="true"]'),Bp=(e,t,n)=>{We("pointerdown",o=>{e.pointerDown(o)},{target:n}),We("pointermove",o=>{tr.set(e,[o.x,o.y]),e.pointerMove(o)},{target:t}),We("pointerleave",o=>{tr.delete(e),e.pointerLeave(o)},{target:t}),We("pointerup",o=>{e.pointerUp(o)},{target:t}),We("dblclick",o=>{F.isFocus(e)&&!F.hasBeenTextEditing(e)&&e.dblClick(o)},{target:n}),We("pointermove",o=>{vu.set(e,[o.x,o.y]),e.globalPointerMove(o)}),We("pointerup",o=>{e.globalPointerUp(o)}),We("keydown",o=>{e.globalKeyDown(o),F.isFocus(e)&&!F.hasBeenTextEditing(e)&&!Ua(o.target)&&e.keyDown(o)}),We("keyup",o=>{F.isFocus(e)&&!F.hasBeenTextEditing(e)&&(e==null||e.keyUp(o))}),We("copy",o=>{F.isFocus(e)&&!F.hasBeenTextEditing(e)&&!Ri(o.target)&&(o.preventDefault(),nr(e,vi.copy,o.clipboardData))}),We("paste",async o=>{if(F.isFocus(e)&&!F.isReadonly(e)&&!F.hasBeenTextEditing(e)&&!Ri(o.target)){const i=F.getMovingPointInBoard(e);if(i){const s=Xe(e,Ze(e,i[0],i[1])),r=await Su(o.clipboardData);e.insertFragment(r,s,vi.paste)}}}),We("cut",o=>{F.isFocus(e)&&!F.isReadonly(e)&&!F.hasBeenTextEditing(e)&&!Ri(o.target)&&(o.preventDefault(),nr(e,vi.cut,o.clipboardData),xu(e))}),We("drop",o=>{F.isReadonly(e)||(o.preventDefault(),e.drop(o))},{target:t}),We("dragover",o=>{o.preventDefault()},{target:t})},Zn=new WeakMap,Jn=new WeakMap,Di=new WeakMap,fl=e=>{const t=Up(e);return t||si(e)||e.viewport.origination||[0,0]},Hp=(e,t,n)=>{const o=e.viewport.zoom,i=fl(e),s=F.getBoardContainer(e).getBoundingClientRect(),r=Gp(s,n),a=Eu(t),c=i[0]+r[0]/o,u=i[1]+r[1]/o;ee.updateViewport(e,[c-r[0]/a,u-r[1]/a],a)},$p=(e,t=1,n=120)=>{Zn.set(e,t);const o=Jn.get(e);o&&clearTimeout(o),Jn.set(e,setTimeout(()=>{Zn.delete(e),Jn.delete(e)},n))},Vp=e=>{const t=Zn.get(e)??0;if(t<=0)return!1;if(t===1){Zn.delete(e);const n=Jn.get(e);n&&(clearTimeout(n),Jn.delete(e))}else Zn.set(e,t-1);return!0},Us=e=>{const t=Te(e);return t.forEach(n=>{const o=vn.getElementRef(n);o==null||o.updateActiveSection()}),t.length},Wp=e=>Di.get(e)||Te(e).length===0?!1:(Di.set(e,!0),qp(()=>{Di.delete(e),Us(e)}),!0),tn=e=>{const t=Us(e);return t>0&&Wp(e),t},Up=e=>{const t=e.viewport.zoom;if(!Number.isFinite(t)||t<=0)return null;try{const n=F.getViewportContainer(e),o=ku(e);return!o||!Number.isFinite(o.x)||!Number.isFinite(o.y)||!Number.isFinite(o.width)||!Number.isFinite(o.height)||o.width<=0||o.height<=0?null:[n.scrollLeft/t+o.x,n.scrollTop/t+o.y]}catch{return null}},Gp=(e,t)=>t&&Kp(t,e)?[t[0]-e.x,t[1]-e.y]:[e.width/2,e.height/2],Kp=(e,t)=>e[0]>=t.left&&e[0]<=t.right&&e[1]>=t.top&&e[1]<=t.bottom,qp=e=>{if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(e);return}setTimeout(e,0)},Yp=(e,t)=>{We("scroll",o=>{if(Vp(e)||bu(e))to(e,!1);else{const i=o.target;if(!i)return;const{scrollLeft:s,scrollTop:r}=i;_u(e,s,r)}},{target:t}),We("touchstart",o=>{o.preventDefault()},{target:t,passive:!1}),We("wheel",o=>{if(o.metaKey||o.ctrlKey){o.preventDefault();const{deltaX:i,deltaY:s}=o,r=e.viewport.zoom,a=Math.sign(s),c=Pu*100,u=Math.abs(s);let l=s;u>c&&(l=c*a);let h=r-l/100;h+=Math.log10(Math.max(1,r))*-a*Math.min(1,u/20),Hp(e,h,F.getMovingPointInBoard(e))}},{target:t,passive:!1});const n=p.useRef(!1);p.useEffect(()=>{const o=new ResizeObserver(()=>{if(!n.current){n.current=!0;return}bs(e),ri(e),ai(e),tn(e)});return o.observe(F.getBoardContainer(e)),()=>{o&&o.disconnect()}},[])},Gs=p.createContext(null),Ye=()=>{const e=p.useContext(Gs);if(!e)throw new Error("The `useBoard` hook must be used inside the <Plait> component's context.");const{board:t}=e;return t},gl=()=>{const e=p.useContext(Gs);if(!e)throw new Error("The `useBoard` hook must be used inside the <Plait> component's context.");const{listRender:t}=e;return t},Xp=({style:e,className:t,children:n,afterInit:o})=>{var y,m;const i=p.useRef(null),s=p.useRef(null),r=p.useRef(null),a=p.useRef(null),c=p.useRef(null),u=p.useRef(null),l=p.useRef(null),h=p.useRef(null),f=Ye(),g=gl();return p.useEffect(()=>{const w=zp.svg(i.current,{options:{roughness:0,strokeWidth:1}});or.set(f,w),ir.set(f,i.current),sr.set(f,!0),rr.set(f,{lowerHost:s.current,host:r.current,upperHost:a.current,topHost:c.current,activeHost:u.current,container:h.current,viewportContainer:l.current});const S=new Tu;return ar.set(f,S),cr.set(f,new Map),g.initialized||(g.initialize(f.children,{board:f,parent:f,parentG:F.getElementHost(f)}),o&&o(f)),bs(f),ri(f),Cu(f),()=>{ar.delete(f),Wi.delete(f),Ui.delete(f),rr.delete(f),sr.delete(f),ir.delete(f),or.delete(f),cr.delete(f)}},[]),Bp(f,l,i),Yp(f,l),d.jsx("div",{className:me(t,Iu,`${Zp()}`,`theme-${(y=f.theme)==null?void 0:y.themeColorMode}`,`pointer-${f.pointer}`,{focused:F.isFocus(f),readonly:F.isReadonly(f),"disabled-scroll":((m=f.options)==null?void 0:m.disabledScrollOnNonFocus)&&!F.isFocus(f)}),ref:h,style:e,children:d.jsxs("div",{className:"viewport-container",ref:l,style:{width:"100%",height:"100%",overflow:"auto"},children:[d.jsxs("svg",{ref:i,width:"100%",height:"100%",style:{position:"relative"},className:"board-host-svg",children:[d.jsx("g",{className:"element-lower-host",ref:s}),d.jsx("g",{className:"element-host",ref:r}),d.jsx("g",{className:"element-upper-host",ref:a}),d.jsx("g",{className:"element-top-host",ref:c})]}),d.jsx("svg",{width:"100%",height:"100%",className:"board-active-svg",children:d.jsx("g",{className:"active-host-g",ref:u})}),n]})})},Zp=()=>Au?"safari":Mu?"chrome":Ru?"firefox":"",Jp=e=>{const t=e;return t.renderText=(n,o)=>{const i=mo.createRoot(n);let s,r=!1,a;const c=()=>{a&&(clearTimeout(a),a=void 0)},u=d.jsx(kr,{...o,afterInit:f=>{s=f,o.afterInit&&o.afterInit(s)}});i.render(u);let l={...o};return{destroy:()=>{r||(r=!0,c(),setTimeout(()=>{i.unmount()},0))},update:f=>{if(r||!(f&&l&&!Object.keys(f).every(m=>f[m]===l[m])))return;const y=mn.isReadOnly(s);l={...l,...f},i.render(d.jsx(kr,{...l})),y===!0&&l.readonly===!1?(c(),a=setTimeout(()=>{a=void 0,!r&&(Qp(s),mn.focus(s))},0)):y===!1&&l.readonly===!0&&(c(),mn.blur(s),mn.deselect(s))}}},t},Qp=e=>{const{selection:t}=e;t&&(pn.has(e,t.anchor.path)&&pn.has(e,t.focus.path)||Du.deselect(e))},em=e=>{const{pointerDown:t,pointerMove:n,pointerUp:o,globalPointerUp:i}=e,s=[];let r=!1;return e.pointerDown=a=>{const c=[a.clientX,a.clientY];s.length<2&&(e.viewport.zoom,s.push({pointerId:a.pointerId,lastPoint:c,currentPoint:c,hasMoved:!1})),t(a)},e.pointerMove=a=>{const c=[a.clientX,a.clientY];if(s.length>=2){const u=s.find(l=>l.pointerId===a.pointerId);if(u&&(u.currentPoint=c,u.hasMoved=!0,s.length===2&&s.every(l=>l.hasMoved))){const l=s[0],h=s[1],f=lr(...l.lastPoint,...h.lastPoint),g=lr(...l.currentPoint,...h.currentPoint),y=g[0]-f[0],m=g[1]-f[1],w=F.getBoardContainer(e).getBoundingClientRect(),S=w.width/2,v=w.height/2,E=e.viewport.zoom,C=fl(e);let D=C[0]+S/E-y/E,P=C[1]+v/E-m/E,H=[D-w.width/2/E,P-w.height/2/E],B=E;const j=Bo(...l.lastPoint,...h.lastPoint),A=Bo(...l.currentPoint,...h.currentPoint)/j,I=[l.currentPoint[0]-l.lastPoint[0],l.currentPoint[1]-l.lastPoint[1]],k=[h.currentPoint[0]-h.lastPoint[0],h.currentPoint[1]-h.lastPoint[1]],T=I[0]*k[0]+I[1]*k[1],M=Math.sqrt(I[0]*I[0]+I[1]*I[1]),O=Math.sqrt(k[0]*k[0]+k[1]*k[1]),q=T/(M*O||1);if(q<-.7||q<=.8&&r&&A>=.01?r=!0:r=!1,r){B=Math.min(Math.max(e.viewport.zoom*A,Lu),ju);const R=F.getBoardContainer(e).getBoundingClientRect(),L=g[0]-R.x,Y=g[1]-R.y;D=H[0]+L/E,P=H[1]+Y/E,H=[D-L/B,P-Y/B]}ee.updateViewport(e,H,B),s.forEach(le=>{le.lastPoint=le.currentPoint,le.hasMoved=!1})}return}n(a)},e.pointerUp=a=>{const c=s.findIndex(u=>u.pointerId===a.pointerId);c!==-1&&s.splice(c,1),o(a)},e.globalPointerUp=a=>{const c=s.findIndex(u=>u.pointerId===a.pointerId);c!==-1&&s.splice(c,1),i(a)},e},tm=({value:e,children:t,options:n,plugins:o,viewport:i,theme:s,onChange:r,onSelectionChange:a,onValueChange:c,onViewportChange:u,onThemeChange:l})=>{const[h,f]=p.useState(()=>{const v=nm(e,n,o,i,s),E=im(v);return{v:0,board:v,listRender:E}}),{board:g,listRender:y}=h,m=p.useCallback(()=>{if(r){const P={children:g.children,operations:g.operations,viewport:g.viewport,selection:g.selection,theme:g.theme};r(P)}const v=g.operations.some(P=>cn.isSetSelectionOperation(P)),E=g.operations.some(P=>cn.isSetViewportOperation(P)),C=g.operations.some(P=>cn.isSetThemeOperation(P)),D=g.operations.length>0&&!g.operations.every(P=>cn.isSetSelectionOperation(P)||cn.isSetViewportOperation(P)||cn.isSetThemeOperation(P));c&&D&&c(g.children),a&&v&&a(g.selection),u&&E&&u(g.viewport),l&&C&&l(g.theme.themeColorMode),f(P=>({v:P.v+1,board:g,listRender:y}))},[g,r,a,c,u,l]);p.useEffect(()=>(Ui.set(g,()=>{if(g.operations.length&&g.operations.every(C=>C.type==="set_selection")){y.update(g.children,{board:g,parent:g,parentG:F.getElementHost(g)});return}const E=g.operations.length&&g.operations.some(C=>C.type==="set_viewport");if(E&&Ou(g)){Nu(g,!1),y.update(g.children,{board:g,parent:g,parentG:F.getElementHost(g)}),tn(g);return}y.update(g.children,{board:g,parent:g,parentG:F.getElementHost(g)}),E?ri(g):zu(g),ai(g),E?tn(g):Us(g)}),Wi.set(g,()=>{m()}),()=>{Ui.delete(g),Wi.delete(g)}),[g]);const w=p.useRef(!0),S=p.useRef(i);return p.useEffect(()=>{const v=S.current;S.current=i;const E=e!==g.children;i&&!ur.get(g)&&!E&&(am(v,i)||(g.viewport=i,ea(g,"viewport-prop-change")))},[i,g,e]),p.useEffect(()=>{if(w.current){w.current=!1;return}e!==h.board.children&&!ur.get(g)&&(g.children=e,om(g),At(g),g.selection=null,y.update(g.children,{board:g,parent:g,parentG:F.getElementHost(g)}),i?(g.viewport=i,ea(g,"value-with-viewport-change")):ee.fitViewport(g))},[e,i]),d.jsx(Gs.Provider,{value:h,children:t})},nm=(e,t,n,o,i)=>{let s=Fu(Bu(Hu($u(Vu(Wu(Uu(Gu(Ku(Jp(qu(Yu(Xu(e,t)))))))))))));return n.forEach(r=>{s=r(s)}),em(s),o&&(s.viewport=o),i&&(s.theme=i),s},om=e=>{e.history.undos=[],e.history.redos=[]},im=e=>new Zu(e),sm=30,rm=6,wn=2,Qn=new WeakMap,gs=new WeakMap,ea=(e,t)=>{bs(e),ri(e),ai(e),tn(e),dm(e,t)},am=(e,t)=>{var n,o,i,s;return e===t?!0:!e||!t?!1:e.zoom===t.zoom&&e.offsetX===t.offsetX&&e.offsetY===t.offsetY&&((n=e.origination)==null?void 0:n[0])===((o=t.origination)==null?void 0:o[0])&&((i=e.origination)==null?void 0:i[1])===((s=t.origination)==null?void 0:s[1])},cm="aitu_debug_viewport",lm=()=>{if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("debugViewport")==="1"||window.localStorage.getItem(cm)==="true"}catch{return!1}},um=e=>{var t;try{const n=(t=e.viewport)==null?void 0:t.origination;if(!n)return null;const o=F.getHost(e).getAttribute("viewBox");if(!o)return null;const[i,s]=o.trim().split(/[\s,]+/).map(a=>Number(a));if(!Number.isFinite(i)||!Number.isFinite(s))return null;const r=e.viewport.zoom;return{targetScrollLeft:(n[0]-i)*r,targetScrollTop:(n[1]-s)*r}}catch{return null}},dm=(e,t)=>{if(typeof window>"u")return;const n=(Qn.get(e)??0)+1;Qn.set(e,n),fm(e,t);let o=0;const i=()=>{if(Qn.get(e)!==n)return;const s=um(e);if(!s){ps(),Xo(e),to(e,!1),tn(e);return}const r=F.getViewportContainer(e),a=Math.abs(r.scrollLeft-s.targetScrollLeft),c=Math.abs(r.scrollTop-s.targetScrollTop);(a>wn||c>wn)&&hm(e,s),tn(e);const l=Math.abs(r.scrollLeft-s.targetScrollLeft),h=Math.abs(r.scrollTop-s.targetScrollTop),f=l<=wn&&h<=wn;if(!(o+1<sm&&(!f||o+1<rm))){ps("wrapper:restore-scroll",e,{...s}),Xo(e),to(e,!1);return}o+=1,ta(i)};ta(i)},ta=e=>{if(typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(e);return}window.setTimeout(e,0)},hm=(e,t)=>{const n=F.getViewportContainer(e);to(e,!0),n.scrollLeft=t.targetScrollLeft,n.scrollTop=t.targetScrollTop;const o=Math.abs(n.scrollLeft-t.targetScrollLeft),i=Math.abs(n.scrollTop-t.targetScrollTop);(o>wn||i>wn)&&ai(e),tn(e)},fm=(e,t)=>{Xo(e);const n=i=>{gm(e,t,i)},o={capture:!0,passive:!0};window.addEventListener("wheel",n,o),window.addEventListener("pointerdown",n,o),window.addEventListener("touchstart",n,o),window.addEventListener("keydown",n,o),gs.set(e,()=>{window.removeEventListener("wheel",n,o),window.removeEventListener("pointerdown",n,o),window.removeEventListener("touchstart",n,o),window.removeEventListener("keydown",n,o)})},gm=(e,t,n)=>{Qn.set(e,(Qn.get(e)??0)+1),Xo(e),pm(n)&&$p(e,2),to(e,!1),ps()},pm=e=>typeof WheelEvent<"u"&&e instanceof WheelEvent&&(e.ctrlKey||e.metaKey),Xo=e=>{const t=gs.get(e);t&&(t(),gs.delete(e))},ps=(e,t,n)=>{lm()},na=e=>d.jsx("span",{className:"mind-node-emoji",style:{fontSize:`${e.fontSize}px`},children:e.emojiItem.name}),mm=e=>{const t=e;return e.setPluginOptions(Ju,{emojiPadding:0,spaceBetweenEmojis:4}),t.renderEmoji=(n,o)=>{const i=document.createElement("span");n.appendChild(i);const s=mo.createRoot(i);s.render(d.jsx(na,{...o}));let r={...o};return{destroy:()=>{setTimeout(()=>{s.unmount()},0)},update:c=>{r={...r,...c},s.render(d.jsx(na,{...r}))}}},t},wm=e=>{const t=p.useRef(null),[n,o]=p.useState(!1),[i,s]=p.useState(!0),{videoItem:r,isFocus:a=!1,isSelected:c=!1,readonly:u=!1}=e,{url:l,poster:h,videoType:f}=r,g=(l==null?void 0:l.replace("#video",""))||"";p.useEffect(()=>{const S=t.current;if(S){const v=()=>{s(!1),o(!1)},E=()=>{s(!1),o(!0)};return S.addEventListener("loadeddata",v),S.addEventListener("error",E),()=>{S.removeEventListener("loadeddata",v),S.removeEventListener("error",E)}}},[g]);const y=S=>{u&&S.stopPropagation()},m=S=>{u&&(S.stopPropagation(),S.preventDefault(),window.open(g,"_blank"))},w={position:"relative",width:"100%",height:"100%",backgroundColor:"#000",borderRadius:"4px",overflow:"hidden"};return n?d.jsx("div",{style:w,"data-slideshow-media-control":"true",onClick:m,onPointerDown:y,onPointerUp:y,children:d.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",color:"#666",backgroundColor:"#f5f5f5",cursor:u?"pointer":"default"},children:[d.jsx("div",{style:{fontSize:"48px",marginBottom:"8px"},children:"🎬"}),d.jsx("div",{style:{fontSize:"14px",textAlign:"center",padding:"0 16px"},children:"Video failed to load"}),u&&d.jsx("div",{style:{fontSize:"12px",color:"#999",marginTop:"4px"},children:"Click to open in new window"})]})}):d.jsxs("div",{style:w,"data-slideshow-media-control":"true",onClick:m,onPointerDown:y,onPointerUp:y,children:[i&&d.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0, 0, 0, 0.7)",color:"white",zIndex:1},children:d.jsxs("div",{style:{textAlign:"center"},children:[d.jsx("div",{style:{fontSize:"24px",marginBottom:"8px"},children:"⏳"}),d.jsx("div",{style:{fontSize:"14px"},children:"Loading video..."})]})}),d.jsx("video",{ref:t,"data-slideshow-media-control":"true",src:g,poster:h,width:"100%",height:"100%",controls:!u,muted:!0,playsInline:!0,draggable:!1,className:me("video-origin",{"video-origin--focus":a,"video-origin--selected":c}),style:{width:"100%",height:"100%",objectFit:"contain"},onPointerDown:y,onPointerUp:y,onError:()=>o(!0)}),u&&d.jsx("div",{style:{position:"absolute",top:"8px",right:"8px",backgroundColor:"rgba(0, 0, 0, 0.6)",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"12px",pointerEvents:"none"},children:"🎬 Video"})]})},Io="http://www.w3.org/2000/svg",ym="http://www.w3.org/1999/xlink",Rn=new WeakMap,Dn=new WeakMap;function vm(e){const t=Rn.get(e);if(t)return t.count+=1,e.style.overflow="visible",()=>{t.count-=1,t.count<=0&&(e.style.overflow=t.previousOverflow,Rn.delete(e))};const n=e.style.overflow;return Rn.set(e,{count:1,previousOverflow:n}),e.style.overflow="visible",()=>{const o=Rn.get(e);o&&(o.count-=1,o.count<=0&&(e.style.overflow=o.previousOverflow,Rn.delete(e)))}}function Sm(e){const t=Dn.get(e);if(t)return t.count+=1,e.style.visibility="hidden",e.style.pointerEvents="none",()=>{t.count-=1,t.count<=0&&(e.style.visibility=t.previousVisibility,e.style.pointerEvents=t.previousPointerEvents,Dn.delete(e))};const n=e.style.visibility,o=e.style.pointerEvents;return Dn.set(e,{count:1,previousVisibility:n,previousPointerEvents:o}),e.style.visibility="hidden",e.style.pointerEvents="none",()=>{const i=Dn.get(e);i&&(i.count-=1,i.count<=0&&(e.style.visibility=i.previousVisibility,e.style.pointerEvents=i.previousPointerEvents,Dn.delete(e)))}}const xm=e=>{if(e.isVideo===!0||e.videoType)return!0;const t=e.url||"";return t.includes("#video")||t.includes("#merged-video-")?!0:[".mp4",".avi",".mov",".wmv",".flv",".webm",".mkv"].some(o=>t.toLowerCase().includes(o))},oa=e=>{const t=p.useRef(e.imageItem.url),n=p.useRef(null),o=p.useRef(null),i=p.useRef(null),s=p.useRef(!1),r=p.useCallback(()=>{var j;(j=n.current)==null||j.call(n),n.current=null},[]);p.useEffect(()=>(t.current=e.imageItem.url,r),[e.imageItem.url,r]);const a=p.useCallback(j=>{if(typeof navigator>"u"||!("serviceWorker"in navigator)||navigator.serviceWorker.controller)return;r();let U=!1;const A=()=>{U||(U=!0,r(),!(!j.isConnected||t.current!==e.imageItem.url)&&(j.src=`${e.imageItem.url}${e.imageItem.url.includes("?")?"&":"?"}_sw_ready=${Date.now()}`))},I=window.setTimeout(()=>{U||(U=!0,r())},1e4),k=()=>{window.clearTimeout(I),navigator.serviceWorker.removeEventListener("controllerchange",A)};n.current=k,navigator.serviceWorker.addEventListener("controllerchange",A,{once:!0}),navigator.serviceWorker.ready.then(()=>{navigator.serviceWorker.controller&&A()}).catch(()=>{})},[r,e.imageItem.url]),c=p.useCallback(j=>{const U=j.currentTarget;U.style.visibility="hidden",a(U);const A=Qu(e.board,e.element,e.imageItem.url);A&&window.setTimeout(()=>{U.isConnected&&(U.src=A.retryUrl)},A.delay)},[e.board,e.element,e.imageItem.url,a]),u=p.useCallback(j=>{const U=j.currentTarget;U.style.visibility="",r(),ed(e.board,e.element,e.imageItem.url)},[r,e.board,e.element,e.imageItem.url]),l=e.element,h=l==null?void 0:l.pptImageStatus,f=l==null?void 0:l.pptImagePrompt,g=l==null?void 0:l.frameId,y=(l==null?void 0:l.isAudio)===!0||(l==null?void 0:l.audioType)==="music-card"||typeof(l==null?void 0:l.audioUrl)=="string"&&l.audioUrl.length>0,m=xm(e.imageItem),w=!y&&!m&&typeof(l==null?void 0:l.frameId)=="string",S=td(e.element)?nd(l==null?void 0:l.transform3d):void 0,v=!!S,E=S?Ga(e.element):void 0,C=S==null?void 0:S.rotateX,D=S==null?void 0:S.rotateY,P=S==null?void 0:S.perspective;p.useLayoutEffect(()=>{if(!v||!o.current)return;const j=o.current.closest("foreignObject");if(!j)return;const U=vm(j),A=j.parentElement;if(!A){U();return}const I=Sm(j),k=document.createElementNS(Io,"g"),T=document.createElementNS(Io,"clipPath"),M=document.createElementNS(Io,"polygon"),O=document.createElementNS(Io,"image"),q=`image-3d-clip-${(l==null?void 0:l.id)||"image"}-${Date.now()}`;return k.classList.add("image-3d-svg-overlay"),k.setAttribute("data-image-3d-overlay","true"),k.setAttribute("pointer-events","none"),T.setAttribute("id",q),T.append(M),O.setAttribute("clip-path",`url(#${q})`),O.setAttribute("preserveAspectRatio","none"),k.append(T,O),A.insertBefore(k,j.nextSibling),i.current={group:k,image:O,clipPath:T,clipPolygon:M},()=>{var le;((le=i.current)==null?void 0:le.group)===k&&(i.current=null),k.remove(),I(),U()}},[l==null?void 0:l.id,v,e.imageItem.url]),p.useLayoutEffect(()=>{if(C===void 0||D===void 0||P===void 0||!E||!o.current)return;const j=o.current.closest("foreignObject");if(!j)return;const U={rotateX:C,rotateY:D,perspective:P},A=i.current||(()=>{var q;const k=(q=j.parentElement)==null?void 0:q.querySelector('g[data-image-3d-overlay="true"]'),T=(k==null?void 0:k.querySelector("image"))||null,M=(k==null?void 0:k.querySelector("clipPath"))||null,O=(k==null?void 0:k.querySelector("clipPath polygon"))||null;return k&&T&&M&&O?{group:k,image:T,clipPath:M,clipPolygon:O}:null})();if(!A)return;i.current=A;const I=od(E,U);A.clipPolygon.setAttribute("points",I.pointsAttribute),A.image.setAttribute("href",e.imageItem.url),A.image.setAttributeNS(ym,"href",e.imageItem.url),A.image.setAttribute("x",String(I.boundingBox.x)),A.image.setAttribute("y",String(I.boundingBox.y)),A.image.setAttribute("width",String(I.boundingBox.width)),A.image.setAttribute("height",String(I.boundingBox.height)),I.textureTransform?A.image.setAttribute("transform",I.textureTransform):A.image.removeAttribute("transform")},[l==null?void 0:l.id,E==null?void 0:E.height,E==null?void 0:E.x,E==null?void 0:E.y,E==null?void 0:E.width,P,C,D,e.imageItem.url]);const H=p.useCallback(async()=>{var j;if(!(!e.board||!g||!f||h==="loading"||s.current)){s.current=!0,Si(e.board,g,"loading"),ko(e.board,g,"loading");try{const U=await id({prompt:f,size:"16x9"});if(U.success&&((j=U.data)!=null&&j.url)){sd(e.board,g);const A=e.board.children.find(I=>I.id===g);if(A){const I=de.getRectangleByPoints(A.points),k=rd({x:I.x,y:I.y,width:I.width,height:I.height});await ad(e.board,U.data.url,"image",g,{width:I.width,height:I.height},{width:800,height:450},k)}ko(e.board,g,"generated")}else Si(e.board,g,"placeholder"),ko(e.board,g,"placeholder"),Ne.error(U.error||"图片生成失败")}catch(U){Si(e.board,g,"placeholder"),ko(e.board,g,"placeholder"),Ne.error((U==null?void 0:U.message)||"图片生成失败")}finally{s.current=!1}}},[e.board,g,f,h]);if(l!=null&&l.pptImagePlaceholder){const j=h==="loading";return d.jsxs("div",{className:"ppt-image-placeholder",onClick:j?void 0:H,style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"8px",borderRadius:"8px",border:"1px dashed #d9d9d9",backgroundColor:"rgba(245,245,245,0.85)",color:"#999",fontSize:"13px",cursor:j?"default":"pointer",userSelect:"none"},children:[j?d.jsx(cd,{size:"small"}):null,d.jsx("span",{children:j?"生成配图中…":"点击生成配图"})]})}if(m)return d.jsx(wm,{videoItem:{url:e.imageItem.url,width:e.imageItem.width,height:e.imageItem.height,videoType:e.imageItem.videoType,poster:e.imageItem.poster},isFocus:e.isFocus,isSelected:e.isSelected,readonly:e.readonly});const B={src:e.imageItem.url,draggable:!1,...w?{style:{width:"100%",height:"100%",objectFit:"contain",display:"block"}}:{width:"100%",style:void 0}};return d.jsx("div",{ref:o,"data-slideshow-legacy-audio":y?"true":void 0,style:S||w?{width:"100%",height:"100%"}:void 0,children:d.jsx("img",{...B,className:me("image-origin",{"image-origin--focus":e.isFocus}),style:B.style,onError:c,onLoad:u})})},km="http://www.w3.org/1999/xlink";class Em extends ci{constructor(t){super(t),this.board=t,this.isFocus=!1,this.lastReactRenderKey="",this.activeGenerator=_s(this.board,{getStrokeWidth:()=>no,getStrokeOpacity:()=>{const n=Te(this.board);return n.length===1&&!oo(this.board)||!n.length?1:.5},getRectangle:n=>this.getActiveRectangle(n),hasResizeHandle:()=>{const n=li(this.board,this.element);return!!Ka(this.board)||n}})}canDraw(t){return!!Sn(t)}draw(t){this.element=t,this.lastReactRenderKey=this.getReactRenderKey(t,!0);const n=yo(),o=this.getSourceRectangle(t);return this.foreignObject=dd(o.x,o.y,o.width,o.height),this.foreignObject.classList.add(hd),n.append(this.foreignObject),this.imageComponentRef=this.board.renderImage(this.foreignObject,this.getImageProps(t)),n}updateImage(t){this.element=t;const n=Sn(t),o=n?this.syncSvgOverlay(t,n):!1,i=this.getReactRenderKey(t,!!n);if((i!==this.lastReactRenderKey||!!n&&!o)&&this.imageComponentRef&&this.imageComponentRef.update(this.getImageProps(t)),this.lastReactRenderKey=i,this.g){const r=this.getSourceRectangle(t);fd(this.g,r.width,r.height,r.x,r.y),t.angle!==void 0&&gd(this.g,de.getCenterPoint(r),t.angle)}}setFocus(t,n){var i;const o=this.isFocus!==n;this.isFocus=n,this.drawActive(t,n),o&&((i=this.imageComponentRef)==null||i.update({isFocus:n}))}destroy(){var t,n;super.destroy(),(t=this.imageComponentRef)==null||t.destroy(),(n=this.activeGenerator)==null||n.destroy()}drawActive(t,n){this.activeGenerator.processDrawing(t,F.getActiveHost(this.board),{selected:n})}getImageProps(t){const n=this.getSourceRectangle(t);return{board:this.board,imageItem:{url:t.url,width:n.width,height:n.height},element:t,getRectangle:()=>this.getSourceRectangle(t)}}getSourceRectangle(t){return Ga(t)||de.getRectangleByPoints(t.points)}getActiveRectangle(t){return pd(t)||this.getSourceRectangle(t)}getReactRenderKey(t,n){return[t.id,t.url,n?"3d":"flat"].join("|")}syncSvgOverlay(t,n=Sn(t)){if(!this.g||!n)return!1;const o=this.g.querySelector('g[data-image-3d-overlay="true"]'),i=(o==null?void 0:o.querySelector("image"))||null,s=(o==null?void 0:o.querySelector("clipPath polygon"))||null;return!o||!i||!s?!1:(s.setAttribute("points",n.pointsAttribute),i.setAttribute("href",t.url),i.setAttributeNS(km,"href",t.url),i.setAttribute("x",String(n.boundingBox.x)),i.setAttribute("y",String(n.boundingBox.y)),i.setAttribute("width",String(n.boundingBox.width)),i.setAttribute("height",String(n.boundingBox.height)),n.textureTransform?i.setAttribute("transform",n.textureTransform):i.removeAttribute("transform"),!0)}}class bm extends wo{initializeGenerator(){this.imageGenerator=new Em(this.board),this.lineAutoCompleteGenerator=new Gi(this.board),this.getRef().addGenerator(Gi.key,this.lineAutoCompleteGenerator),this.getRef().updateActiveSection=()=>this.updateActiveSection()}initialize(){super.initialize(),this.initializeGenerator(),this.imageGenerator.processDrawing(this.element,this.getElementG()),this.updateActiveSection()}onContextChanged(t,n){const o=t.board.viewport.zoom!==n.board.viewport.zoom||t.board.viewport.offsetX!==n.board.viewport.offsetX||t.board.viewport.offsetY!==n.board.viewport.offsetY;if(t.element!==n.element||t.hasThemeChanged||t.selected){this.imageGenerator.updateImage(t.element),this.updateActiveSection();return}if(o&&t.selected){this.updateActiveSection();return}(t.selected!==n.selected||t.selected)&&this.updateActiveSection()}destroy(){var t,n;super.destroy(),(t=this.imageGenerator)==null||t.destroy(),(n=this.lineAutoCompleteGenerator)==null||n.destroy()}updateActiveSection(){this.imageGenerator.setFocus(this.element,this.selected),this.lineAutoCompleteGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})}}const _m=e=>{const{drawElement:t,isHit:n,isRectangleHit:o}=e;return e.drawElement=i=>Sn(i.element)?bm:t(i),e.isHit=(i,s,r)=>{const a=Sn(i);return a?ld(s,a):n(i,s,r)},e.isRectangleHit=(i,s)=>{const r=Sn(i);if(r){const a=de.getRectangleByPoints([s.anchor,s.focus]);return ud(a,r)}return o(i,s)},e};let Li=null;function Pm(){return Li||(Li=Promise.all([re(()=>import("./media-viewer-xSaTD7_w.js").then(e=>e.v),__vite__mapDeps([2]),import.meta.url),re(()=>import("./media-viewer-xSaTD7_w.js").then(e=>e.a),__vite__mapDeps([2]),import.meta.url)]).then(([e])=>e.default)),Li}const Tm=()=>window.innerWidth<=768||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);class Cm{constructor(t={}){this.viewer=null,this.container=null,this.openVersion=0,this.options={zoomStep:t.zoomStep||.2,minZoom:t.minZoom||.1,maxZoom:t.maxZoom||5,enableKeyboard:t.enableKeyboard!==!1}}open(t,n=""){this.close();const o=++this.openVersion;this.container=document.createElement("div"),this.container.style.display="none";const i=document.createElement("img");i.src=t,i.alt=n,this.container.appendChild(i),document.body.appendChild(this.container);const s=Tm(),r=s?{zoomIn:1,zoomOut:1,oneToOne:0,reset:1,prev:0,play:0,next:0,rotateLeft:1,rotateRight:1,flipHorizontal:0,flipVertical:0}:{zoomIn:1,zoomOut:1,oneToOne:1,reset:1,prev:0,play:0,next:0,rotateLeft:1,rotateRight:1,flipHorizontal:1,flipVertical:1};Pm().then(a=>{o!==this.openVersion||!this.container||(this.viewer=new a(this.container,{inline:!1,button:!0,navbar:!1,title:!!n,toolbar:r,fullscreen:!s,keyboard:this.options.enableKeyboard,backdrop:!0,loading:!0,loop:!1,minZoomRatio:this.options.minZoom,maxZoomRatio:this.options.maxZoom,zoomRatio:this.options.zoomStep,hidden:()=>{this.cleanup()}}),this.viewer.show())}).catch(a=>{o===this.openVersion&&(console.warn("[ImageViewer] failed to load viewerjs:",a),this.cleanup())})}close(){if(this.openVersion+=1,this.viewer){this.viewer.hide();return}this.cleanup()}cleanup(){this.viewer&&(this.viewer.destroy(),this.viewer=null),this.container&&this.container.parentNode&&(this.container.parentNode.removeChild(this.container),this.container=null)}destroy(){this.close(),this.cleanup()}}const ia=3,Im=440,Am=300;function Mm(e){const t=[];for(let n=0;n<e.length;n++){const o=e[n];if(qa(o.type)){t.push({file:o,kind:"image",mimeType:o.type});continue}const i=yd(o);if(i){t.push({file:o,kind:"video",mimeType:i});continue}vd(o.type)&&t.push({file:o,kind:"audio",mimeType:o.type})}return t}function Rm(e,t){return Xe(e,Ze(e,t.x,t.y))}function Dm(e,t){const n=F.getBoardContainer(e).getBoundingClientRect(),o=[t.clientX-n.x,t.clientY-n.y];return{point:Rm(e,t),activePoint:o,zoom:e.viewport.zoom}}function Lm(e,t){const n=()=>{const o=Number.isFinite(e.viewport.zoom)&&e.viewport.zoom>0?e.viewport.zoom:t.zoom;ee.updateViewport(e,[t.point[0]-t.activePoint[0]/o,t.point[1]-t.activePoint[1]/o],o)};if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(()=>window.requestAnimationFrame(n));return}setTimeout(n,0)}function jm(e,t,n){if(n<=1)return e;const o=t%ia,i=Math.floor(t/ia);return[e[0]+o*Im,e[1]+i*Am]}function pl(e,t){var o;return((o=e.name)==null?void 0:o.trim())||`${t}-${Date.now()}`}async function Om(e,t,n,o){const i=t.type===n?t:t.slice(0,t.size,n);await Ho.initialize();const s=await Ho.addAsset({type:Yt.VIDEO,source:Za.LOCAL,name:pl(t,"video"),blob:i,mimeType:n});await Ja(e,s.url,o,!0,void 0,!0,!0)}async function Nm(e,t,n,o){const i=pl(t,"audio"),s=i.replace(/\.[^.]+$/,"");await Ho.initialize();const r=await Ho.addAsset({type:Yt.AUDIO,source:Za.LOCAL,name:i,blob:t,mimeType:n});await hr.updateCachedMedia(r.url,{metadata:{name:s}});const[a,c]=await Promise.all([Sd(t),xd(t)]);let u;if(c){const l=`/__aitu_cache__/image/${r.id}-cover.png`;await hr.cacheMediaFromBlob(l,c,"image",{taskId:`${r.id}-cover`,name:`${s}-cover`}),u=l}await Qa(e,r.url,{title:s,duration:a,previewImageUrl:u},o,!0)}async function zm(e,t,n,o){const i=t.length===1&&t[0].kind==="image";for(let s=0;s<t.length;s++){const r=t[s],a=jm(n,s,t.length);try{r.kind==="image"?await Ya(e,r.file,a,i,!i):r.kind==="video"?await Om(e,r.file,r.mimeType,a):await Nm(e,r.file,r.mimeType,a)}catch(c){console.error("[withImagePlugin] Failed to insert dropped media:",c)}}Lm(e,o)}function Fm(e){const t=e.getData("text/uri-list");if(t){const i=t.split(`
|
|
4
|
+
Component Stack:${u}`]})]}),d.jsxs("div",{style:Me.btnRow,children:[t==="crash"&&i&&d.jsx(bo,{label:"继续加载",onClick:i,bg:"#f5f5f5",bgHover:"#e8e8e8",color:"#666"}),t==="error"&&l&&d.jsx(bo,{label:"导出错误日志",onClick:l,bg:"#f5f5f5",bgHover:"#e8e8e8",color:"#333"}),d.jsx(bo,{label:"安全模式",onClick:h,bg:"#F39C12",bgHover:"#E67E22",color:"#fff"})]}),d.jsx("div",{style:Me.divider}),d.jsx("div",{style:Me.helpSection,children:d.jsxs("div",{style:Me.helpRow,children:[d.jsx("img",{src:"https://nav.ourzhishi.top/api/dynamic-image/qr-code",alt:"企业微信二维码",style:Me.qrcode,referrerPolicy:"no-referrer"}),d.jsxs("div",{style:Me.helpText,children:[d.jsx("p",{style:Me.helpTitle,children:"需要帮助?"}),d.jsx("p",{style:Me.helpDesc,children:"扫码联系客服,或前往调试页面导出完整日志与备份数据"}),d.jsx(bo,{label:"打开调试页面",onClick:f,bg:"#f0eefa",bgHover:"#e2ddf7",color:"#5A4FCF",small:!0})]})]})})]})})},Qg=({info:e})=>{const t=e.percent>75?"#E53935":e.percent>50?"#FB8C00":"#43A047";return d.jsxs("div",{style:Me.memoryBox,children:[d.jsx("div",{style:{fontSize:12,color:"#888",marginBottom:8},children:"当前内存使用情况"}),d.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[d.jsxs("span",{style:{fontSize:14,color:"#333"},children:[e.used," / ",e.limit]}),d.jsxs("span",{style:{fontSize:14,fontWeight:500,color:t},children:[e.percent.toFixed(0),"%"]})]}),d.jsx("div",{style:{height:4,backgroundColor:"#e0e0e0",borderRadius:2,marginTop:8,overflow:"hidden"},children:d.jsx("div",{style:{height:"100%",width:`${Math.min(e.percent,100)}%`,backgroundColor:t,transition:"width 0.3s ease"}})})]})},bo=({label:e,onClick:t,bg:n,bgHover:o,color:i,small:s})=>{const[r,a]=on.useState(!1),c=s?{...Me.btnSmall,backgroundColor:r?o:n,color:i}:{...Me.btn,backgroundColor:r?o:n,color:i};return d.jsx("button",{onClick:t,onMouseOver:()=>a(!0),onMouseOut:()=>a(!1),style:c,children:e})},Me={overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:99999},card:{backgroundColor:"#fff",borderRadius:12,padding:32,maxWidth:520,width:"90%",maxHeight:"90vh",overflowY:"auto",boxShadow:"0 20px 60px rgba(0,0,0,0.3)"},iconWrap:{width:64,height:64,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 24px"},title:{margin:"0 0 12px",fontSize:20,fontWeight:600,textAlign:"center",color:"#1a1a1a"},desc:{margin:"0 0 20px",fontSize:14,color:"#666",textAlign:"center",lineHeight:1.6},memoryBox:{backgroundColor:"#f5f5f5",borderRadius:8,padding:"12px 16px",marginBottom:24},errorBox:{backgroundColor:"#f5f5f5",borderRadius:8,padding:"12px 16px",marginBottom:24},errorMsg:{fontSize:13,color:"#E53935",wordBreak:"break-word"},detailToggle:{marginTop:8,padding:0,border:"none",background:"none",color:"#888",fontSize:12,cursor:"pointer",textDecoration:"underline"},errorDetail:{marginTop:8,padding:8,backgroundColor:"#eee",borderRadius:4,fontSize:11,color:"#555",maxHeight:150,overflow:"auto",whiteSpace:"pre-wrap",wordBreak:"break-all"},btnRow:{display:"flex",gap:12},btn:{flex:1,padding:"12px 24px",fontSize:14,fontWeight:500,border:"none",borderRadius:8,cursor:"pointer",transition:"background-color 0.2s ease"},btnSmall:{padding:"8px 16px",fontSize:13,fontWeight:500,border:"none",borderRadius:6,cursor:"pointer",transition:"background-color 0.2s ease"},divider:{height:1,backgroundColor:"#eee",margin:"24px 0"},helpSection:{padding:0},helpRow:{display:"flex",gap:16,alignItems:"center"},qrcode:{width:96,height:96,borderRadius:8,flexShrink:0},helpText:{flex:1,minWidth:0},helpTitle:{margin:"0 0 4px",fontSize:14,fontWeight:500,color:"#333"},helpDesc:{margin:"0 0 12px",fontSize:12,color:"#999",lineHeight:1.5}},ep=p.lazy(()=>re(()=>import("./index-DmtcRYr8.js"),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.Drawnix}))),tp=500,as="board",$s="aitu_board_close_snapshot_v1";let Ci=!1;async function np(e){const{initializeViewBox:t,updateViewBox:n,updateViewportOffset:o}=await re(async()=>{const{initializeViewBox:i,updateViewBox:s,updateViewportOffset:r}=await import("./ai-chat-BnWVpTEI.js").then(a=>a.sM);return{initializeViewBox:i,updateViewBox:s,updateViewportOffset:r}},__vite__mapDeps([0]),import.meta.url);t(e),n(e),o(e)}function op(){if(!(typeof window>"u"))return window.__OPENTU_BOOT__}function Ur(){return new URLSearchParams(window.location.search).get(as)}function Gr(e,t=!1){const n=new URL(window.location.href);e?n.searchParams.set(as,e):n.searchParams.delete(as),t?window.history.replaceState({boardId:e},"",n.toString()):window.history.pushState({boardId:e},"",n.toString())}function ip(e){try{localStorage.setItem($s,JSON.stringify(e))}catch(t){console.warn("[App] Failed to save board close snapshot:",t)}}function il(){try{const e=localStorage.getItem($s);if(!e)return null;const t=JSON.parse(e);return!t||typeof t.boardId!="string"||typeof t.updatedAt!="number"||!Array.isArray(t.children)?null:t}catch(e){return console.warn("[App] Failed to load board close snapshot:",e),null}}function _o(e){try{const t=il();if(!t)return;(!e||t.boardId===e)&&localStorage.removeItem($s)}catch(t){console.warn("[App] Failed to clear board close snapshot:",t)}}function sp(){const[e,t]=p.useState(!0),[n,o]=p.useState(!1),i=p.useRef(!1),[s,r]=p.useState(!1),[a,c]=p.useState(null),[u,l]=p.useState({children:[]}),[h,f]=p.useState(null),g=p.useRef(null),y=p.useRef(),m=p.useRef(null),w=p.useRef(null),S=p.useRef(!1),v=p.useRef(null),E=p.useRef(!1),C=p.useRef(!1),D=p.useRef(!1);qf(h),p.useEffect(()=>{g.current=h},[h]);const P=p.useCallback((k,T,M=Date.now())=>{y.current=T.viewport,m.current={boardId:k,children:T.children,viewport:T.viewport,theme:T.theme,updatedAt:M}},[]),H=p.useCallback(k=>{const T=m.current,M=g.current;if(!T||!M||T.boardId!==M||!D.current)return;ip({...T,updatedAt:Date.now()}),yt.getInstance().saveCurrentBoard({children:T.children,viewport:T.viewport,theme:T.theme}).catch(q=>{console.warn(`[App] Failed to flush board on ${k}:`,q)})},[]);p.useEffect(()=>{const k=op();k&&(s||a||!e)&&k.markReady()},[a,e,s]),p.useEffect(()=>{s||a||e||el(["offline-static-assets"])},[a,e,s]),p.useEffect(()=>{(async()=>{if(et.shouldShowSafeModePrompt()&&!et.isSafeMode()){r(!0),t(!1);return}if(Ci){const T=yt.getInstance();t(!1),await T.waitForInitialization();const M=T.getState().currentBoardId;if(M&&T.getBoardMetadata(M)){const O=await T.switchBoard(M),q={children:O.elements||[],viewport:O.viewport,theme:O.theme};P(O.id,q,O.updatedAt),D.current=!1,l(q)}t(!1),et.markLoadingComplete();return}Ci=!0;try{const T=yt.getInstance();if(t(!1),await T.initialize(),await Kc()||await $f(),et.isSafeMode()){const Y=T.getAllBoards().find(ue=>ue.name.startsWith("安全模式")&&(!ue.elements||ue.elements.length===0));if(Y)await T.switchBoard(Y.id),f(Y.id);else{const ue=new Date().toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).replace(/\//g,"-"),_e=await T.createBoard({name:`安全模式 ${ue}`,elements:[]});_e&&(await T.switchBoard(_e.id),f(_e.id))}const he={children:[]},be=(Y==null?void 0:Y.id)||g.current||"safe-mode";P(be,he,Date.now()),l(he),i.current=!0,o(!0),t(!1),et.markLoadingComplete(),et.disableSafeMode(),setTimeout(()=>{Ne.warning({content:"当前处于安全模式,已创建空白画布。可从侧边栏切换到其他画布。",duration:8e3,closeBtn:!0})},500);return}let O=null;const q=Ur(),le=T.getState().currentBoardId;let R=null;if(q&&T.getBoardMetadata(q)?R=q:le&&T.getBoardMetadata(le)&&(R=le),R)O=await T.switchBoard(R);else if(T.hasBoards()){const L=T.getTree(),Y=sl(L);Y&&(O=await T.switchBoard(Y.id))}else{const L=await T.createBoard({name:"我的画板1",elements:[]});L&&(O=await T.switchBoard(L.id))}if(O&&(Gr(O.id,!0),f(O.id),T.persistCurrentBoardId(O.id),D.current=!1),O){const L=il();let Y={children:O.elements||[],viewport:O.viewport,theme:O.theme};if(L&&L.boardId===O.id&&L.updatedAt>O.updatedAt){Y={children:L.children,viewport:L.viewport,theme:L.theme},O={...O,...Y,updatedAt:L.updatedAt};const he=O.id;T.saveBoard(he,Y).then(()=>{D.current=!1,_o(he)}).catch(be=>{console.warn("[App] Failed to rehydrate board from close snapshot:",be)}),Ne.warning({content:"检测到上次关闭前的未落盘画布,已自动恢复",duration:5e3,closeBtn:!0})}else L&&L.boardId&&!T.getBoardMetadata(L.boardId)&&_o(L.boardId);P(O.id,Y,O.updatedAt),D.current=!1,l(Y),Ii(Y.children).then(he=>{if(he!==Y.children){const be={...Y,children:he};P(O.id,be,Date.now()),l(be)}}).catch(he=>{console.error("[App] Video URL recovery failed:",he)})}}catch(T){console.error("[App] Initialization failed:",T),c(T instanceof Error?T:new Error(String(T)))}finally{i.current=!0,o(!0),t(!1),et.markLoadingComplete()}})()},[P]);const B=p.useCallback(async(k,T=!1)=>{try{T||(Gr(k.id),yt.getInstance().persistCurrentBoardId(k.id)),f(k.id),C.current=!1,D.current=!1;const O={children:await Ii(k.elements||[]),viewport:k.viewport,theme:k.theme};P(k.id,O,k.updatedAt),l(O),setTimeout(()=>{v.current&&np(v.current).catch(q=>{console.warn("[App] Failed to refresh board bounds:",q)})},0)}catch(M){console.error("[App] Board switch failed:",M),Ne.error({content:`切换画板失败: ${M instanceof Error?M.message:"未知错误"}`,duration:5e3,closeBtn:!0})}},[P]);p.useEffect(()=>{const k=async()=>{if(!S.current){S.current=!0;try{const T=Ur();if(T&&T!==h){const M=yt.getInstance(),O=await M.switchBoard(T);O&&(await B(O,!0),M.persistCurrentBoardId(O.id))}}catch(T){console.error("[App] Failed to handle browser navigation:",T)}finally{S.current=!1}}};return window.addEventListener("popstate",k),()=>{window.removeEventListener("popstate",k)}},[h,B]);const j=p.useCallback(async()=>{E.current=!0;try{const k=yt.getInstance();let T=k.getCurrentBoard();if(!T){const O=k.getState().currentBoardId;if(!O){console.warn("[App] handleTabSyncNeeded: no current board ID");return}if(!k.getBoardMetadata(O)){console.warn("[App] handleTabSyncNeeded: board not found",O);return}try{T=await k.switchBoard(O)}catch(q){console.error("[App] handleTabSyncNeeded: failed to load board",q);return}}const M=await k.reloadBoard(T.id);if(M){const q={children:await Ii(M.elements||[]),viewport:M.viewport,theme:M.theme};P(M.id,q,M.updatedAt),D.current=!1,l(q)}}catch(k){console.error("[App] Failed to sync board data:",k),co()}finally{setTimeout(()=>{E.current=!1},100)}},[P]),U=p.useCallback(k=>{if(l(k),y.current=k.viewport,!i.current||E.current)return;C.current=!0,D.current=!0;const T=yt.getInstance(),M=T.getCurrentBoard();if(!M){console.warn("[App] handleBoardChange: board not fully loaded, skipping save");return}P(M.id,k),T.saveCurrentBoard(k).then(()=>{D.current=!1,_o(M.id),Yc(M.id)}).catch(O=>{console.error("[App] Failed to save board:",O)})},[P]),A=p.useCallback(k=>{y.current=k;const T=m.current;T&&(m.current={...T,viewport:k,updatedAt:Date.now()}),!E.current&&(D.current=!0,w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{if(E.current)return;const M=yt.getInstance(),O=M.getCurrentBoard();O&&M.saveCurrentBoard({children:O.elements,viewport:k,theme:O.theme}).then(()=>{D.current=!1,_o(O.id)}).catch(q=>{console.error("[App] Failed to save viewport:",q)})},tp))},[P]);p.useEffect(()=>{const k=q=>{if(w.current&&(clearTimeout(w.current),w.current=null),E.current)return;const R=yt.getInstance().getCurrentBoard(),L=m.current,Y=y.current,he=g.current;R&&he&&(!L||L.boardId!==he)&&P(R.id,{children:R.elements,viewport:Y??R.viewport,theme:R.theme},Date.now()),!(q==="visibilitychange"&&!C.current)&&H(q)},T=()=>{k("beforeunload")},M=()=>{document.visibilityState==="hidden"&&k("visibilitychange")},O=()=>{k("pagehide")};return window.addEventListener("beforeunload",T),window.addEventListener("pagehide",O),document.addEventListener("visibilitychange",M),()=>{window.removeEventListener("beforeunload",T),window.removeEventListener("pagehide",O),document.removeEventListener("visibilitychange",M),w.current&&clearTimeout(w.current)}},[H,P]);const I=p.useCallback(k=>{r(!1),k?et.enableSafeMode():et.clearCrashState(),t(!0),Ci=!1,setTimeout(()=>{co()},100)},[]);return s?d.jsx(Uo,{variant:"crash",crashCount:et.getCrashCount(),memoryInfo:et.getMemoryInfo(),onIgnore:()=>I(!1),onSafeModeReload:()=>I(!0),onGoToDebug:Wo}):a?d.jsx(Uo,{variant:"error",title:"应用初始化失败",description:"无法加载画板数据,可能是存储损坏或浏览器限制。",errorMessage:a.message,errorStack:a.stack,onExportLog:()=>ss(a),onSafeModeReload:rs,onGoToDebug:Wo}):e?d.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100vh"},children:"加载中..."}):d.jsx("div",{style:{height:"100vh"},children:d.jsx(p.Suspense,{fallback:null,children:d.jsx(ep,{value:u.children,viewport:u.viewport,theme:u.theme,onChange:U,onViewportChange:A,onBoardSwitch:B,onTabSyncNeeded:j,isDataReady:n,currentBoardId:h,afterInit:k=>{v.current=k,window.__drawnix__web__console=T=>{rp(k,T)}}})})})}const rp=async(e,t)=>{const{PlaitBoard:n}=await re(async()=>{const{PlaitBoard:r}=await import("./ai-chat-BnWVpTEI.js").then(a=>a.sM);return{PlaitBoard:r}},__vite__mapDeps([0]),import.meta.url),o=n.getBoardContainer(e).closest(".drawnix");if(!o)return;let i=o.querySelector(".drawnix-console");i||(i=document.createElement("div"),i.classList.add("drawnix-console"),o.append(i));const s=document.createElement("div");s.innerHTML=t,i.append(s)};async function Ii(e){return e.map(t=>{const n=t.url;if(n!=null&&n.startsWith("/__aitu_cache__/video/"))return t;if(n!=null&&n.startsWith("blob:")&&n.includes("#merged-video-")){const o=n.indexOf("#merged-video-");if(o!==-1){const i=n.substring(o+1),s=i.indexOf("#",1),a=`/__aitu_cache__/video/${s>0?i.substring(0,s):i}.mp4`;return{...t,url:a}}}return t})}function sl(e){for(const t of e){if(t.type==="board")return t.data;if(t.type==="folder"&&t.children){const n=sl(t.children);if(n)return n}}return null}function cs(e,t,n){if(e&&e.length){const[o,i]=t,s=Math.PI/180*n,r=Math.cos(s),a=Math.sin(s);for(const c of e){const[u,l]=c;c[0]=(u-o)*r-(l-i)*a+o,c[1]=(u-o)*a+(l-i)*r+i}}}function ap(e,t,n){const o=[];e.forEach(i=>o.push(...i)),cs(o,t,n)}function cp(e,t){return e[0]===t[0]&&e[1]===t[1]}function lp(e,t,n,o=1){const i=n,s=Math.max(t,.1),r=e[0]&&e[0][0]&&typeof e[0][0]=="number"?[e]:e,a=[0,0];if(i)for(const u of r)cs(u,a,i);const c=up(r,s,o);if(i){for(const u of r)cs(u,a,-i);ap(c,a,-i)}return c}function up(e,t,n){const o=[];for(const u of e){const l=[...u];cp(l[0],l[l.length-1])||l.push([l[0][0],l[0][1]]),l.length>2&&o.push(l)}const i=[];t=Math.max(t,.1);const s=[];for(const u of o)for(let l=0;l<u.length-1;l++){const h=u[l],f=u[l+1];if(h[1]!==f[1]){const g=Math.min(h[1],f[1]);s.push({ymin:g,ymax:Math.max(h[1],f[1]),x:g===h[1]?h[0]:f[0],islope:(f[0]-h[0])/(f[1]-h[1])})}}if(s.sort((u,l)=>u.ymin<l.ymin?-1:u.ymin>l.ymin?1:u.x<l.x?-1:u.x>l.x?1:u.ymax===l.ymax?0:(u.ymax-l.ymax)/Math.abs(u.ymax-l.ymax)),!s.length)return i;let r=[],a=s[0].ymin,c=0;for(;r.length||s.length;){if(s.length){let u=-1;for(let h=0;h<s.length&&!(s[h].ymin>a);h++)u=h;s.splice(0,u+1).forEach(h=>{r.push({s:a,edge:h})})}if(r=r.filter(u=>!(u.edge.ymax<=a)),r.sort((u,l)=>u.edge.x===l.edge.x?0:(u.edge.x-l.edge.x)/Math.abs(u.edge.x-l.edge.x)),(n!==1||c%t===0)&&r.length>1)for(let u=0;u<r.length;u=u+2){const l=u+1;if(l>=r.length)break;const h=r[u].edge,f=r[l].edge;i.push([[Math.round(h.x),a],[Math.round(f.x),a]])}a+=n,r.forEach(u=>{u.edge.x=u.edge.x+n*u.edge.islope}),c++}return i}function xo(e,t){var n;const o=t.hachureAngle+90;let i=t.hachureGap;i<0&&(i=t.strokeWidth*4),i=Math.round(Math.max(i,.1));let s=1;return t.roughness>=1&&(((n=t.randomizer)===null||n===void 0?void 0:n.next())||Math.random())>.7&&(s=i),lp(e,i,o,s||1)}class Vs{constructor(t){this.helper=t}fillPolygons(t,n){return this._fillPolygons(t,n)}_fillPolygons(t,n){const o=xo(t,n);return{type:"fillSketch",ops:this.renderLines(o,n)}}renderLines(t,n){const o=[];for(const i of t)o.push(...this.helper.doubleLineOps(i[0][0],i[0][1],i[1][0],i[1][1],n));return o}}function gi(e){const t=e[0],n=e[1];return Math.sqrt(Math.pow(t[0]-n[0],2)+Math.pow(t[1]-n[1],2))}class dp extends Vs{fillPolygons(t,n){let o=n.hachureGap;o<0&&(o=n.strokeWidth*4),o=Math.max(o,.1);const i=Object.assign({},n,{hachureGap:o}),s=xo(t,i),r=Math.PI/180*n.hachureAngle,a=[],c=o*.5*Math.cos(r),u=o*.5*Math.sin(r);for(const[h,f]of s)gi([h,f])&&a.push([[h[0]-c,h[1]+u],[...f]],[[h[0]+c,h[1]-u],[...f]]);return{type:"fillSketch",ops:this.renderLines(a,n)}}}class hp extends Vs{fillPolygons(t,n){const o=this._fillPolygons(t,n),i=Object.assign({},n,{hachureAngle:n.hachureAngle+90}),s=this._fillPolygons(t,i);return o.ops=o.ops.concat(s.ops),o}}class fp{constructor(t){this.helper=t}fillPolygons(t,n){n=Object.assign({},n,{hachureAngle:0});const o=xo(t,n);return this.dotsOnLines(o,n)}dotsOnLines(t,n){const o=[];let i=n.hachureGap;i<0&&(i=n.strokeWidth*4),i=Math.max(i,.1);let s=n.fillWeight;s<0&&(s=n.strokeWidth/2);const r=i/4;for(const a of t){const c=gi(a),u=c/i,l=Math.ceil(u)-1,h=c-l*i,f=(a[0][0]+a[1][0])/2-i/4,g=Math.min(a[0][1],a[1][1]);for(let y=0;y<l;y++){const m=g+h+y*i,w=f-r+Math.random()*2*r,S=m-r+Math.random()*2*r,v=this.helper.ellipse(w,S,s,s,n);o.push(...v.ops)}}return{type:"fillSketch",ops:o}}}class gp{constructor(t){this.helper=t}fillPolygons(t,n){const o=xo(t,n);return{type:"fillSketch",ops:this.dashedLine(o,n)}}dashedLine(t,n){const o=n.dashOffset<0?n.hachureGap<0?n.strokeWidth*4:n.hachureGap:n.dashOffset,i=n.dashGap<0?n.hachureGap<0?n.strokeWidth*4:n.hachureGap:n.dashGap,s=[];return t.forEach(r=>{const a=gi(r),c=Math.floor(a/(o+i)),u=(a+i-c*(o+i))/2;let l=r[0],h=r[1];l[0]>h[0]&&(l=r[1],h=r[0]);const f=Math.atan((h[1]-l[1])/(h[0]-l[0]));for(let g=0;g<c;g++){const y=g*(o+i),m=y+o,w=[l[0]+y*Math.cos(f)+u*Math.cos(f),l[1]+y*Math.sin(f)+u*Math.sin(f)],S=[l[0]+m*Math.cos(f)+u*Math.cos(f),l[1]+m*Math.sin(f)+u*Math.sin(f)];s.push(...this.helper.doubleLineOps(w[0],w[1],S[0],S[1],n))}}),s}}class pp{constructor(t){this.helper=t}fillPolygons(t,n){const o=n.hachureGap<0?n.strokeWidth*4:n.hachureGap,i=n.zigzagOffset<0?o:n.zigzagOffset;n=Object.assign({},n,{hachureGap:o+i});const s=xo(t,n);return{type:"fillSketch",ops:this.zigzagLines(s,i,n)}}zigzagLines(t,n,o){const i=[];return t.forEach(s=>{const r=gi(s),a=Math.round(r/(2*n));let c=s[0],u=s[1];c[0]>u[0]&&(c=s[1],u=s[0]);const l=Math.atan((u[1]-c[1])/(u[0]-c[0]));for(let h=0;h<a;h++){const f=h*2*n,g=(h+1)*2*n,y=Math.sqrt(2*Math.pow(n,2)),m=[c[0]+f*Math.cos(l),c[1]+f*Math.sin(l)],w=[c[0]+g*Math.cos(l),c[1]+g*Math.sin(l)],S=[m[0]+y*Math.cos(l+Math.PI/4),m[1]+y*Math.sin(l+Math.PI/4)];i.push(...this.helper.doubleLineOps(m[0],m[1],S[0],S[1],o),...this.helper.doubleLineOps(S[0],S[1],w[0],w[1],o))}}),i}}const Qe={};function mp(e,t){let n=e.fillStyle||"hachure";if(!Qe[n])switch(n){case"zigzag":Qe[n]||(Qe[n]=new dp(t));break;case"cross-hatch":Qe[n]||(Qe[n]=new hp(t));break;case"dots":Qe[n]||(Qe[n]=new fp(t));break;case"dashed":Qe[n]||(Qe[n]=new gp(t));break;case"zigzag-line":Qe[n]||(Qe[n]=new pp(t));break;case"hachure":default:n="hachure",Qe[n]||(Qe[n]=new Vs(t));break}return Qe[n]}function wp(){return Math.floor(Math.random()*2**31)}class yp{constructor(t){this.seed=t}next(){return this.seed?(2**31-1&(this.seed=Math.imul(48271,this.seed)))/2**31:Math.random()}}const vp=0,ls=1,rl=2,Po={A:7,a:7,C:6,c:6,H:1,h:1,L:2,l:2,M:2,m:2,Q:4,q:4,S:4,s:4,T:2,t:2,V:1,v:1,Z:0,z:0};function Sp(e){const t=new Array;for(;e!=="";)if(e.match(/^([ \t\r\n,]+)/))e=e.substr(RegExp.$1.length);else if(e.match(/^([aAcChHlLmMqQsStTvVzZ])/))t[t.length]={type:vp,text:RegExp.$1},e=e.substr(RegExp.$1.length);else if(e.match(/^(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)/))t[t.length]={type:ls,text:`${parseFloat(RegExp.$1)}`},e=e.substr(RegExp.$1.length);else return[];return t[t.length]={type:rl,text:""},t}function Ai(e,t){return e.type===t}function Ws(e){const t=[],n=Sp(e);let o="BOD",i=0,s=n[i];for(;!Ai(s,rl);){let r=0;const a=[];if(o==="BOD")if(s.text==="M"||s.text==="m")i++,r=Po[s.text],o=s.text;else return Ws("M0,0"+e);else Ai(s,ls)?r=Po[o]:(i++,r=Po[s.text],o=s.text);if(i+r<n.length){for(let c=i;c<i+r;c++){const u=n[c];if(Ai(u,ls))a[a.length]=+u.text;else throw new Error("Param not a number: "+o+","+u.text)}if(typeof Po[o]=="number"){const c={key:o,data:a};t.push(c),i+=r,s=n[i],o==="M"&&(o="L"),o==="m"&&(o="l")}else throw new Error("Bad segment: "+o)}else throw new Error("Path data ended short")}return t}function al(e){let t=0,n=0,o=0,i=0;const s=[];for(const{key:r,data:a}of e)switch(r){case"M":s.push({key:"M",data:[...a]}),[t,n]=a,[o,i]=a;break;case"m":t+=a[0],n+=a[1],s.push({key:"M",data:[t,n]}),o=t,i=n;break;case"L":s.push({key:"L",data:[...a]}),[t,n]=a;break;case"l":t+=a[0],n+=a[1],s.push({key:"L",data:[t,n]});break;case"C":s.push({key:"C",data:[...a]}),t=a[4],n=a[5];break;case"c":{const c=a.map((u,l)=>l%2?u+n:u+t);s.push({key:"C",data:c}),t=c[4],n=c[5];break}case"Q":s.push({key:"Q",data:[...a]}),t=a[2],n=a[3];break;case"q":{const c=a.map((u,l)=>l%2?u+n:u+t);s.push({key:"Q",data:c}),t=c[2],n=c[3];break}case"A":s.push({key:"A",data:[...a]}),t=a[5],n=a[6];break;case"a":t+=a[5],n+=a[6],s.push({key:"A",data:[a[0],a[1],a[2],a[3],a[4],t,n]});break;case"H":s.push({key:"H",data:[...a]}),t=a[0];break;case"h":t+=a[0],s.push({key:"H",data:[t]});break;case"V":s.push({key:"V",data:[...a]}),n=a[0];break;case"v":n+=a[0],s.push({key:"V",data:[n]});break;case"S":s.push({key:"S",data:[...a]}),t=a[2],n=a[3];break;case"s":{const c=a.map((u,l)=>l%2?u+n:u+t);s.push({key:"S",data:c}),t=c[2],n=c[3];break}case"T":s.push({key:"T",data:[...a]}),t=a[0],n=a[1];break;case"t":t+=a[0],n+=a[1],s.push({key:"T",data:[t,n]});break;case"Z":case"z":s.push({key:"Z",data:[]}),t=o,n=i;break}return s}function cl(e){const t=[];let n="",o=0,i=0,s=0,r=0,a=0,c=0;for(const{key:u,data:l}of e){switch(u){case"M":t.push({key:"M",data:[...l]}),[o,i]=l,[s,r]=l;break;case"C":t.push({key:"C",data:[...l]}),o=l[4],i=l[5],a=l[2],c=l[3];break;case"L":t.push({key:"L",data:[...l]}),[o,i]=l;break;case"H":o=l[0],t.push({key:"L",data:[o,i]});break;case"V":i=l[0],t.push({key:"L",data:[o,i]});break;case"S":{let h=0,f=0;n==="C"||n==="S"?(h=o+(o-a),f=i+(i-c)):(h=o,f=i),t.push({key:"C",data:[h,f,...l]}),a=l[0],c=l[1],o=l[2],i=l[3];break}case"T":{const[h,f]=l;let g=0,y=0;n==="Q"||n==="T"?(g=o+(o-a),y=i+(i-c)):(g=o,y=i);const m=o+2*(g-o)/3,w=i+2*(y-i)/3,S=h+2*(g-h)/3,v=f+2*(y-f)/3;t.push({key:"C",data:[m,w,S,v,h,f]}),a=g,c=y,o=h,i=f;break}case"Q":{const[h,f,g,y]=l,m=o+2*(h-o)/3,w=i+2*(f-i)/3,S=g+2*(h-g)/3,v=y+2*(f-y)/3;t.push({key:"C",data:[m,w,S,v,g,y]}),a=h,c=f,o=g,i=y;break}case"A":{const h=Math.abs(l[0]),f=Math.abs(l[1]),g=l[2],y=l[3],m=l[4],w=l[5],S=l[6];h===0||f===0?(t.push({key:"C",data:[o,i,w,S,w,S]}),o=w,i=S):(o!==w||i!==S)&&(ll(o,i,w,S,h,f,g,y,m).forEach(function(E){t.push({key:"C",data:E})}),o=w,i=S);break}case"Z":t.push({key:"Z",data:[]}),o=s,i=r;break}n=u}return t}function xp(e){return Math.PI*e/180}function An(e,t,n){const o=e*Math.cos(n)-t*Math.sin(n),i=e*Math.sin(n)+t*Math.cos(n);return[o,i]}function ll(e,t,n,o,i,s,r,a,c,u){const l=xp(r);let h=[],f=0,g=0,y=0,m=0;if(u)[f,g,y,m]=u;else{[e,t]=An(e,t,-l),[n,o]=An(n,o,-l);const I=(e-n)/2,k=(t-o)/2;let T=I*I/(i*i)+k*k/(s*s);T>1&&(T=Math.sqrt(T),i=T*i,s=T*s);const M=a===c?-1:1,O=i*i,q=s*s,le=O*q-O*k*k-q*I*I,R=O*k*k+q*I*I,L=M*Math.sqrt(Math.abs(le/R));y=L*i*k/s+(e+n)/2,m=L*-s*I/i+(t+o)/2,f=Math.asin(parseFloat(((t-m)/s).toFixed(9))),g=Math.asin(parseFloat(((o-m)/s).toFixed(9))),e<y&&(f=Math.PI-f),n<y&&(g=Math.PI-g),f<0&&(f=Math.PI*2+f),g<0&&(g=Math.PI*2+g),c&&f>g&&(f=f-Math.PI*2),!c&&g>f&&(g=g-Math.PI*2)}let w=g-f;if(Math.abs(w)>Math.PI*120/180){const I=g,k=n,T=o;c&&g>f?g=f+Math.PI*120/180*1:g=f+Math.PI*120/180*-1,n=y+i*Math.cos(g),o=m+s*Math.sin(g),h=ll(n,o,k,T,i,s,r,0,c,[g,I,y,m])}w=g-f;const S=Math.cos(f),v=Math.sin(f),E=Math.cos(g),C=Math.sin(g),D=Math.tan(w/4),P=4/3*i*D,H=4/3*s*D,B=[e,t],j=[e+P*v,t-H*S],U=[n+P*C,o-H*E],A=[n,o];if(j[0]=2*B[0]-j[0],j[1]=2*B[1]-j[1],u)return[j,U,A].concat(h);{h=[j,U,A].concat(h);const I=[];for(let k=0;k<h.length;k+=3){const T=An(h[k][0],h[k][1],l),M=An(h[k+1][0],h[k+1][1],l),O=An(h[k+2][0],h[k+2][1],l);I.push([T[0],T[1],M[0],M[1],O[0],O[1]])}return I}}const kp={randOffset:Tp,randOffsetWithRange:Cp,ellipse:_p,doubleLineOps:Ip};function ul(e,t,n,o,i){return{type:"path",ops:Bt(e,t,n,o,i)}}function Lo(e,t,n){const o=(e||[]).length;if(o>2){const i=[];for(let s=0;s<o-1;s++)i.push(...Bt(e[s][0],e[s][1],e[s+1][0],e[s+1][1],n));return t&&i.push(...Bt(e[o-1][0],e[o-1][1],e[0][0],e[0][1],n)),{type:"path",ops:i}}else if(o===2)return ul(e[0][0],e[0][1],e[1][0],e[1][1],n);return{type:"path",ops:[]}}function Ep(e,t){return Lo(e,!0,t)}function bp(e,t,n,o,i){const s=[[e,t],[e+n,t],[e+n,t+o],[e,t+o]];return Ep(s,i)}function Kr(e,t){if(e.length){const o=typeof e[0][0]=="number"?[e]:e,i=To(o[0],1*(1+t.roughness*.2),t),s=t.disableMultiStroke?[]:To(o[0],1.5*(1+t.roughness*.22),Xr(t));for(let r=1;r<o.length;r++){const a=o[r];if(a.length){const c=To(a,1*(1+t.roughness*.2),t),u=t.disableMultiStroke?[]:To(a,1.5*(1+t.roughness*.22),Xr(t));for(const l of c)l.op!=="move"&&i.push(l);for(const l of u)l.op!=="move"&&s.push(l)}}return{type:"path",ops:i.concat(s)}}return{type:"path",ops:[]}}function _p(e,t,n,o,i){const s=dl(n,o,i);return us(e,t,i,s).opset}function dl(e,t,n){const o=Math.sqrt(Math.PI*2*Math.sqrt((Math.pow(e/2,2)+Math.pow(t/2,2))/2)),i=Math.ceil(Math.max(n.curveStepCount,n.curveStepCount/Math.sqrt(200)*o)),s=Math.PI*2/i;let r=Math.abs(e/2),a=Math.abs(t/2);const c=1-n.curveFitting;return r+=J(r*c,n),a+=J(a*c,n),{increment:s,rx:r,ry:a}}function us(e,t,n,o){const[i,s]=Zr(o.increment,e,t,o.rx,o.ry,1,o.increment*Go(.1,Go(.4,1,n),n),n);let r=Ko(i,null,n);if(!n.disableMultiStroke&&n.roughness!==0){const[a]=Zr(o.increment,e,t,o.rx,o.ry,1.5,0,n),c=Ko(a,null,n);r=r.concat(c)}return{estimatedPoints:s,opset:{type:"path",ops:r}}}function qr(e,t,n,o,i,s,r,a,c){const u=e,l=t;let h=Math.abs(n/2),f=Math.abs(o/2);h+=J(h*.01,c),f+=J(f*.01,c);let g=i,y=s;for(;g<0;)g+=Math.PI*2,y+=Math.PI*2;y-g>Math.PI*2&&(g=0,y=Math.PI*2);const m=Math.PI*2/c.curveStepCount,w=Math.min(m/2,(y-g)/2),S=Jr(w,u,l,h,f,g,y,1,c);if(!c.disableMultiStroke){const v=Jr(w,u,l,h,f,g,y,1.5,c);S.push(...v)}return r&&(a?S.push(...Bt(u,l,u+h*Math.cos(g),l+f*Math.sin(g),c),...Bt(u,l,u+h*Math.cos(y),l+f*Math.sin(y),c)):S.push({op:"lineTo",data:[u,l]},{op:"lineTo",data:[u+h*Math.cos(g),l+f*Math.sin(g)]})),{type:"path",ops:S}}function Yr(e,t){const n=cl(al(Ws(e))),o=[];let i=[0,0],s=[0,0];for(const{key:r,data:a}of n)switch(r){case"M":{s=[a[0],a[1]],i=[a[0],a[1]];break}case"L":o.push(...Bt(s[0],s[1],a[0],a[1],t)),s=[a[0],a[1]];break;case"C":{const[c,u,l,h,f,g]=a;o.push(...Ap(c,u,l,h,f,g,s,t)),s=[f,g];break}case"Z":o.push(...Bt(s[0],s[1],i[0],i[1],t)),s=[i[0],i[1]];break}return{type:"path",ops:o}}function Mi(e,t){const n=[];for(const o of e)if(o.length){const i=t.maxRandomnessOffset||0,s=o.length;if(s>2){n.push({op:"move",data:[o[0][0]+J(i,t),o[0][1]+J(i,t)]});for(let r=1;r<s;r++)n.push({op:"lineTo",data:[o[r][0]+J(i,t),o[r][1]+J(i,t)]})}}return{type:"fillPath",ops:n}}function hn(e,t){return mp(t,kp).fillPolygons(e,t)}function Pp(e,t,n,o,i,s,r){const a=e,c=t;let u=Math.abs(n/2),l=Math.abs(o/2);u+=J(u*.01,r),l+=J(l*.01,r);let h=i,f=s;for(;h<0;)h+=Math.PI*2,f+=Math.PI*2;f-h>Math.PI*2&&(h=0,f=Math.PI*2);const g=(f-h)/r.curveStepCount,y=[];for(let m=h;m<=f;m=m+g)y.push([a+u*Math.cos(m),c+l*Math.sin(m)]);return y.push([a+u*Math.cos(f),c+l*Math.sin(f)]),y.push([a,c]),hn([y],r)}function Tp(e,t){return J(e,t)}function Cp(e,t,n){return Go(e,t,n)}function Ip(e,t,n,o,i){return Bt(e,t,n,o,i,!0)}function Xr(e){const t=Object.assign({},e);return t.randomizer=void 0,e.seed&&(t.seed=e.seed+1),t}function hl(e){return e.randomizer||(e.randomizer=new yp(e.seed||0)),e.randomizer.next()}function Go(e,t,n,o=1){return n.roughness*o*(hl(n)*(t-e)+e)}function J(e,t,n=1){return Go(-e,e,t,n)}function Bt(e,t,n,o,i,s=!1){const r=s?i.disableMultiStrokeFill:i.disableMultiStroke,a=ds(e,t,n,o,i,!0,!1);if(r)return a;const c=ds(e,t,n,o,i,!0,!0);return a.concat(c)}function ds(e,t,n,o,i,s,r){const a=Math.pow(e-n,2)+Math.pow(t-o,2),c=Math.sqrt(a);let u=1;c<200?u=1:c>500?u=.4:u=-.0016668*c+1.233334;let l=i.maxRandomnessOffset||0;l*l*100>a&&(l=c/10);const h=l/2,f=.2+hl(i)*.2;let g=i.bowing*i.maxRandomnessOffset*(o-t)/200,y=i.bowing*i.maxRandomnessOffset*(e-n)/200;g=J(g,i,u),y=J(y,i,u);const m=[],w=()=>J(h,i,u),S=()=>J(l,i,u),v=i.preserveVertices;return r?m.push({op:"move",data:[e+(v?0:w()),t+(v?0:w())]}):m.push({op:"move",data:[e+(v?0:J(l,i,u)),t+(v?0:J(l,i,u))]}),r?m.push({op:"bcurveTo",data:[g+e+(n-e)*f+w(),y+t+(o-t)*f+w(),g+e+2*(n-e)*f+w(),y+t+2*(o-t)*f+w(),n+(v?0:w()),o+(v?0:w())]}):m.push({op:"bcurveTo",data:[g+e+(n-e)*f+S(),y+t+(o-t)*f+S(),g+e+2*(n-e)*f+S(),y+t+2*(o-t)*f+S(),n+(v?0:S()),o+(v?0:S())]}),m}function To(e,t,n){if(!e.length)return[];const o=[];o.push([e[0][0]+J(t,n),e[0][1]+J(t,n)]),o.push([e[0][0]+J(t,n),e[0][1]+J(t,n)]);for(let i=1;i<e.length;i++)o.push([e[i][0]+J(t,n),e[i][1]+J(t,n)]),i===e.length-1&&o.push([e[i][0]+J(t,n),e[i][1]+J(t,n)]);return Ko(o,null,n)}function Ko(e,t,n){const o=e.length,i=[];if(o>3){const s=[],r=1-n.curveTightness;i.push({op:"move",data:[e[1][0],e[1][1]]});for(let a=1;a+2<o;a++){const c=e[a];s[0]=[c[0],c[1]],s[1]=[c[0]+(r*e[a+1][0]-r*e[a-1][0])/6,c[1]+(r*e[a+1][1]-r*e[a-1][1])/6],s[2]=[e[a+1][0]+(r*e[a][0]-r*e[a+2][0])/6,e[a+1][1]+(r*e[a][1]-r*e[a+2][1])/6],s[3]=[e[a+1][0],e[a+1][1]],i.push({op:"bcurveTo",data:[s[1][0],s[1][1],s[2][0],s[2][1],s[3][0],s[3][1]]})}}else o===3?(i.push({op:"move",data:[e[1][0],e[1][1]]}),i.push({op:"bcurveTo",data:[e[1][0],e[1][1],e[2][0],e[2][1],e[2][0],e[2][1]]})):o===2&&i.push(...ds(e[0][0],e[0][1],e[1][0],e[1][1],n,!0,!0));return i}function Zr(e,t,n,o,i,s,r,a){const c=a.roughness===0,u=[],l=[];if(c){e=e/4,l.push([t+o*Math.cos(-e),n+i*Math.sin(-e)]);for(let h=0;h<=Math.PI*2;h=h+e){const f=[t+o*Math.cos(h),n+i*Math.sin(h)];u.push(f),l.push(f)}l.push([t+o*Math.cos(0),n+i*Math.sin(0)]),l.push([t+o*Math.cos(e),n+i*Math.sin(e)])}else{const h=J(.5,a)-Math.PI/2;l.push([J(s,a)+t+.9*o*Math.cos(h-e),J(s,a)+n+.9*i*Math.sin(h-e)]);const f=Math.PI*2+h-.01;for(let g=h;g<f;g=g+e){const y=[J(s,a)+t+o*Math.cos(g),J(s,a)+n+i*Math.sin(g)];u.push(y),l.push(y)}l.push([J(s,a)+t+o*Math.cos(h+Math.PI*2+r*.5),J(s,a)+n+i*Math.sin(h+Math.PI*2+r*.5)]),l.push([J(s,a)+t+.98*o*Math.cos(h+r),J(s,a)+n+.98*i*Math.sin(h+r)]),l.push([J(s,a)+t+.9*o*Math.cos(h+r*.5),J(s,a)+n+.9*i*Math.sin(h+r*.5)])}return[l,u]}function Jr(e,t,n,o,i,s,r,a,c){const u=s+J(.1,c),l=[];l.push([J(a,c)+t+.9*o*Math.cos(u-e),J(a,c)+n+.9*i*Math.sin(u-e)]);for(let h=u;h<=r;h=h+e)l.push([J(a,c)+t+o*Math.cos(h),J(a,c)+n+i*Math.sin(h)]);return l.push([t+o*Math.cos(r),n+i*Math.sin(r)]),l.push([t+o*Math.cos(r),n+i*Math.sin(r)]),Ko(l,null,c)}function Ap(e,t,n,o,i,s,r,a){const c=[],u=[a.maxRandomnessOffset||1,(a.maxRandomnessOffset||1)+.3];let l=[0,0];const h=a.disableMultiStroke?1:2,f=a.preserveVertices;for(let g=0;g<h;g++)g===0?c.push({op:"move",data:[r[0],r[1]]}):c.push({op:"move",data:[r[0]+(f?0:J(u[0],a)),r[1]+(f?0:J(u[0],a))]}),l=f?[i,s]:[i+J(u[g],a),s+J(u[g],a)],c.push({op:"bcurveTo",data:[e+J(u[g],a),t+J(u[g],a),n+J(u[g],a),o+J(u[g],a),l[0],l[1]]});return c}function Mn(e){return[...e]}function Qr(e,t=0){const n=e.length;if(n<3)throw new Error("A curve must have at least three points.");const o=[];if(n===3)o.push(Mn(e[0]),Mn(e[1]),Mn(e[2]),Mn(e[2]));else{const i=[];i.push(e[0],e[0]);for(let a=1;a<e.length;a++)i.push(e[a]),a===e.length-1&&i.push(e[a]);const s=[],r=1-t;o.push(Mn(i[0]));for(let a=1;a+2<i.length;a++){const c=i[a];s[0]=[c[0],c[1]],s[1]=[c[0]+(r*i[a+1][0]-r*i[a-1][0])/6,c[1]+(r*i[a+1][1]-r*i[a-1][1])/6],s[2]=[i[a+1][0]+(r*i[a][0]-r*i[a+2][0])/6,i[a+1][1]+(r*i[a][1]-r*i[a+2][1])/6],s[3]=[i[a+1][0],i[a+1][1]],o.push(s[1],s[2],s[3])}}return o}function Mp(e,t){return Math.sqrt(jo(e,t))}function jo(e,t){return Math.pow(e[0]-t[0],2)+Math.pow(e[1]-t[1],2)}function Rp(e,t,n){const o=jo(t,n);if(o===0)return jo(e,t);let i=((e[0]-t[0])*(n[0]-t[0])+(e[1]-t[1])*(n[1]-t[1]))/o;return i=Math.max(0,Math.min(1,i)),jo(e,qt(t,n,i))}function qt(e,t,n){return[e[0]+(t[0]-e[0])*n,e[1]+(t[1]-e[1])*n]}function Dp(e,t){const n=e[t+0],o=e[t+1],i=e[t+2],s=e[t+3];let r=3*o[0]-2*n[0]-s[0];r*=r;let a=3*o[1]-2*n[1]-s[1];a*=a;let c=3*i[0]-2*s[0]-n[0];c*=c;let u=3*i[1]-2*s[1]-n[1];return u*=u,r<c&&(r=c),a<u&&(a=u),r+a}function hs(e,t,n,o){const i=o||[];if(Dp(e,t)<n){const s=e[t+0];i.length?Mp(i[i.length-1],s)>1&&i.push(s):i.push(s),i.push(e[t+3])}else{const r=e[t+0],a=e[t+1],c=e[t+2],u=e[t+3],l=qt(r,a,.5),h=qt(a,c,.5),f=qt(c,u,.5),g=qt(l,h,.5),y=qt(h,f,.5),m=qt(g,y,.5);hs([r,l,g,m],0,n,i),hs([m,y,f,u],0,n,i)}return i}function Lp(e,t){return qo(e,0,e.length,t)}function qo(e,t,n,o,i){const s=i||[],r=e[t],a=e[n-1];let c=0,u=1;for(let l=t+1;l<n-1;++l){const h=Rp(e[l],r,a);h>c&&(c=h,u=l)}return Math.sqrt(c)>o?(qo(e,t,u+1,o,s),qo(e,u,n,o,s)):(s.length||s.push(r),s.push(a)),s}function fs(e,t=.15,n){const o=[],i=(e.length-1)/3;for(let s=0;s<i;s++){const r=s*3;hs(e,r,t,o)}return n&&n>0?qo(o,0,o.length,n):o}function jp(e,t,n){const o=Ws(e),i=cl(al(o)),s=[];let r=[],a=[0,0],c=[];const u=()=>{c.length>=4&&r.push(...fs(c,t)),c=[]},l=()=>{u(),r.length&&(s.push(r),r=[])};for(const{key:f,data:g}of i)switch(f){case"M":l(),a=[g[0],g[1]],r.push(a);break;case"L":u(),r.push([g[0],g[1]]);break;case"C":if(!c.length){const y=r.length?r[r.length-1]:a;c.push([y[0],y[1]])}c.push([g[0],g[1]]),c.push([g[2],g[3]]),c.push([g[4],g[5]]);break;case"Z":u(),r.push([a[0],a[1]]);break}if(l(),!n)return s;const h=[];for(const f of s){const g=Lp(f,n);g.length&&h.push(g)}return h}const it="none";class Yo{constructor(t){this.defaultOptions={maxRandomnessOffset:2,roughness:1,bowing:1,stroke:"#000",strokeWidth:1,curveTightness:0,curveFitting:.95,curveStepCount:9,fillStyle:"hachure",fillWeight:-1,hachureAngle:-41,hachureGap:-1,dashOffset:-1,dashGap:-1,zigzagOffset:-1,seed:0,disableMultiStroke:!1,disableMultiStrokeFill:!1,preserveVertices:!1,fillShapeRoughnessGain:.8},this.config=t||{},this.config.options&&(this.defaultOptions=this._o(this.config.options))}static newSeed(){return wp()}_o(t){return t?Object.assign({},this.defaultOptions,t):this.defaultOptions}_d(t,n,o){return{shape:t,sets:n||[],options:o||this.defaultOptions}}line(t,n,o,i,s){const r=this._o(s);return this._d("line",[ul(t,n,o,i,r)],r)}rectangle(t,n,o,i,s){const r=this._o(s),a=[],c=bp(t,n,o,i,r);if(r.fill){const u=[[t,n],[t+o,n],[t+o,n+i],[t,n+i]];r.fillStyle==="solid"?a.push(Mi([u],r)):a.push(hn([u],r))}return r.stroke!==it&&a.push(c),this._d("rectangle",a,r)}ellipse(t,n,o,i,s){const r=this._o(s),a=[],c=dl(o,i,r),u=us(t,n,r,c);if(r.fill)if(r.fillStyle==="solid"){const l=us(t,n,r,c).opset;l.type="fillPath",a.push(l)}else a.push(hn([u.estimatedPoints],r));return r.stroke!==it&&a.push(u.opset),this._d("ellipse",a,r)}circle(t,n,o,i){const s=this.ellipse(t,n,o,o,i);return s.shape="circle",s}linearPath(t,n){const o=this._o(n);return this._d("linearPath",[Lo(t,!1,o)],o)}arc(t,n,o,i,s,r,a=!1,c){const u=this._o(c),l=[],h=qr(t,n,o,i,s,r,a,!0,u);if(a&&u.fill)if(u.fillStyle==="solid"){const f=Object.assign({},u);f.disableMultiStroke=!0;const g=qr(t,n,o,i,s,r,!0,!1,f);g.type="fillPath",l.push(g)}else l.push(Pp(t,n,o,i,s,r,u));return u.stroke!==it&&l.push(h),this._d("arc",l,u)}curve(t,n){const o=this._o(n),i=[],s=Kr(t,o);if(o.fill&&o.fill!==it)if(o.fillStyle==="solid"){const r=Kr(t,Object.assign(Object.assign({},o),{disableMultiStroke:!0,roughness:o.roughness?o.roughness+o.fillShapeRoughnessGain:0}));i.push({type:"fillPath",ops:this._mergedShape(r.ops)})}else{const r=[],a=t;if(a.length){const u=typeof a[0][0]=="number"?[a]:a;for(const l of u)l.length<3?r.push(...l):l.length===3?r.push(...fs(Qr([l[0],l[0],l[1],l[2]]),10,(1+o.roughness)/2)):r.push(...fs(Qr(l),10,(1+o.roughness)/2))}r.length&&i.push(hn([r],o))}return o.stroke!==it&&i.push(s),this._d("curve",i,o)}polygon(t,n){const o=this._o(n),i=[],s=Lo(t,!0,o);return o.fill&&(o.fillStyle==="solid"?i.push(Mi([t],o)):i.push(hn([t],o))),o.stroke!==it&&i.push(s),this._d("polygon",i,o)}path(t,n){const o=this._o(n),i=[];if(!t)return this._d("path",i,o);t=(t||"").replace(/\n/g," ").replace(/(-\s)/g,"-").replace("/(ss)/g"," ");const s=o.fill&&o.fill!=="transparent"&&o.fill!==it,r=o.stroke!==it,a=!!(o.simplification&&o.simplification<1),c=a?4-4*(o.simplification||1):(1+o.roughness)/2,u=jp(t,1,c),l=Yr(t,o);if(s)if(o.fillStyle==="solid")if(u.length===1){const h=Yr(t,Object.assign(Object.assign({},o),{disableMultiStroke:!0,roughness:o.roughness?o.roughness+o.fillShapeRoughnessGain:0}));i.push({type:"fillPath",ops:this._mergedShape(h.ops)})}else i.push(Mi(u,o));else i.push(hn(u,o));return r&&(a?u.forEach(h=>{i.push(Lo(h,!1,o))}):i.push(l)),this._d("path",i,o)}opsToPath(t,n){let o="";for(const i of t.ops){const s=typeof n=="number"&&n>=0?i.data.map(r=>+r.toFixed(n)):i.data;switch(i.op){case"move":o+=`M${s[0]} ${s[1]} `;break;case"bcurveTo":o+=`C${s[0]} ${s[1]}, ${s[2]} ${s[3]}, ${s[4]} ${s[5]} `;break;case"lineTo":o+=`L${s[0]} ${s[1]} `;break}}return o.trim()}toPaths(t){const n=t.sets||[],o=t.options||this.defaultOptions,i=[];for(const s of n){let r=null;switch(s.type){case"path":r={d:this.opsToPath(s),stroke:o.stroke,strokeWidth:o.strokeWidth,fill:it};break;case"fillPath":r={d:this.opsToPath(s),stroke:it,strokeWidth:0,fill:o.fill||it};break;case"fillSketch":r=this.fillSketch(s,o);break}r&&i.push(r)}return i}fillSketch(t,n){let o=n.fillWeight;return o<0&&(o=n.strokeWidth/2),{d:this.opsToPath(t),stroke:n.fill||it,strokeWidth:o,fill:it}}_mergedShape(t){return t.filter((n,o)=>o===0?!0:n.op!=="move")}}class Op{constructor(t,n){this.canvas=t,this.ctx=this.canvas.getContext("2d"),this.gen=new Yo(n)}draw(t){const n=t.sets||[],o=t.options||this.getDefaultOptions(),i=this.ctx,s=t.options.fixedDecimalPlaceDigits;for(const r of n)switch(r.type){case"path":i.save(),i.strokeStyle=o.stroke==="none"?"transparent":o.stroke,i.lineWidth=o.strokeWidth,o.strokeLineDash&&i.setLineDash(o.strokeLineDash),o.strokeLineDashOffset&&(i.lineDashOffset=o.strokeLineDashOffset),this._drawToContext(i,r,s),i.restore();break;case"fillPath":{i.save(),i.fillStyle=o.fill||"";const a=t.shape==="curve"||t.shape==="polygon"||t.shape==="path"?"evenodd":"nonzero";this._drawToContext(i,r,s,a),i.restore();break}case"fillSketch":this.fillSketch(i,r,o);break}}fillSketch(t,n,o){let i=o.fillWeight;i<0&&(i=o.strokeWidth/2),t.save(),o.fillLineDash&&t.setLineDash(o.fillLineDash),o.fillLineDashOffset&&(t.lineDashOffset=o.fillLineDashOffset),t.strokeStyle=o.fill||"",t.lineWidth=i,this._drawToContext(t,n,o.fixedDecimalPlaceDigits),t.restore()}_drawToContext(t,n,o,i="nonzero"){t.beginPath();for(const s of n.ops){const r=typeof o=="number"&&o>=0?s.data.map(a=>+a.toFixed(o)):s.data;switch(s.op){case"move":t.moveTo(r[0],r[1]);break;case"bcurveTo":t.bezierCurveTo(r[0],r[1],r[2],r[3],r[4],r[5]);break;case"lineTo":t.lineTo(r[0],r[1]);break}}n.type==="fillPath"?t.fill(i):t.stroke()}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}line(t,n,o,i,s){const r=this.gen.line(t,n,o,i,s);return this.draw(r),r}rectangle(t,n,o,i,s){const r=this.gen.rectangle(t,n,o,i,s);return this.draw(r),r}ellipse(t,n,o,i,s){const r=this.gen.ellipse(t,n,o,i,s);return this.draw(r),r}circle(t,n,o,i){const s=this.gen.circle(t,n,o,i);return this.draw(s),s}linearPath(t,n){const o=this.gen.linearPath(t,n);return this.draw(o),o}polygon(t,n){const o=this.gen.polygon(t,n);return this.draw(o),o}arc(t,n,o,i,s,r,a=!1,c){const u=this.gen.arc(t,n,o,i,s,r,a,c);return this.draw(u),u}curve(t,n){const o=this.gen.curve(t,n);return this.draw(o),o}path(t,n){const o=this.gen.path(t,n);return this.draw(o),o}}const Co="http://www.w3.org/2000/svg";class Np{constructor(t,n){this.svg=t,this.gen=new Yo(n)}draw(t){const n=t.sets||[],o=t.options||this.getDefaultOptions(),i=this.svg.ownerDocument||window.document,s=i.createElementNS(Co,"g"),r=t.options.fixedDecimalPlaceDigits;for(const a of n){let c=null;switch(a.type){case"path":{c=i.createElementNS(Co,"path"),c.setAttribute("d",this.opsToPath(a,r)),c.setAttribute("stroke",o.stroke),c.setAttribute("stroke-width",o.strokeWidth+""),c.setAttribute("fill","none"),o.strokeLineDash&&c.setAttribute("stroke-dasharray",o.strokeLineDash.join(" ").trim()),o.strokeLineDashOffset&&c.setAttribute("stroke-dashoffset",`${o.strokeLineDashOffset}`);break}case"fillPath":{c=i.createElementNS(Co,"path"),c.setAttribute("d",this.opsToPath(a,r)),c.setAttribute("stroke","none"),c.setAttribute("stroke-width","0"),c.setAttribute("fill",o.fill||""),(t.shape==="curve"||t.shape==="polygon")&&c.setAttribute("fill-rule","evenodd");break}case"fillSketch":{c=this.fillSketch(i,a,o);break}}c&&s.appendChild(c)}return s}fillSketch(t,n,o){let i=o.fillWeight;i<0&&(i=o.strokeWidth/2);const s=t.createElementNS(Co,"path");return s.setAttribute("d",this.opsToPath(n,o.fixedDecimalPlaceDigits)),s.setAttribute("stroke",o.fill||""),s.setAttribute("stroke-width",i+""),s.setAttribute("fill","none"),o.fillLineDash&&s.setAttribute("stroke-dasharray",o.fillLineDash.join(" ").trim()),o.fillLineDashOffset&&s.setAttribute("stroke-dashoffset",`${o.fillLineDashOffset}`),s}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}opsToPath(t,n){return this.gen.opsToPath(t,n)}line(t,n,o,i,s){const r=this.gen.line(t,n,o,i,s);return this.draw(r)}rectangle(t,n,o,i,s){const r=this.gen.rectangle(t,n,o,i,s);return this.draw(r)}ellipse(t,n,o,i,s){const r=this.gen.ellipse(t,n,o,i,s);return this.draw(r)}circle(t,n,o,i){const s=this.gen.circle(t,n,o,i);return this.draw(s)}linearPath(t,n){const o=this.gen.linearPath(t,n);return this.draw(o)}polygon(t,n){const o=this.gen.polygon(t,n);return this.draw(o)}arc(t,n,o,i,s,r,a=!1,c){const u=this.gen.arc(t,n,o,i,s,r,a,c);return this.draw(u)}curve(t,n){const o=this.gen.curve(t,n);return this.draw(o)}path(t,n){const o=this.gen.path(t,n);return this.draw(o)}}const zp={canvas(e,t){return new Op(e,t)},svg(e,t){return new Np(e,t)},generator(e){return new Yo(e)},newSeed(){return Yo.newSeed()}};function Fp(e){return e?"current"in e?e.current||null:e:typeof window>"u"?null:window}function We(e,t,n={}){const o=p.useRef(t),{target:i,capture:s,passive:r,once:a}=n;p.useEffect(()=>{o.current=t},[t]),p.useEffect(()=>{const c=Fp(i);if(!c)return;const u=h=>{o.current(h)},l={capture:s,passive:r,once:a};return c.addEventListener(e,u,l),()=>{c.removeEventListener(e,u,l)}},[e,i,s,r,a])}const Ri=e=>Ua(e)?!0:e instanceof Element&&!!e.closest('[contenteditable="true"]'),Bp=(e,t,n)=>{We("pointerdown",o=>{e.pointerDown(o)},{target:n}),We("pointermove",o=>{tr.set(e,[o.x,o.y]),e.pointerMove(o)},{target:t}),We("pointerleave",o=>{tr.delete(e),e.pointerLeave(o)},{target:t}),We("pointerup",o=>{e.pointerUp(o)},{target:t}),We("dblclick",o=>{F.isFocus(e)&&!F.hasBeenTextEditing(e)&&e.dblClick(o)},{target:n}),We("pointermove",o=>{vu.set(e,[o.x,o.y]),e.globalPointerMove(o)}),We("pointerup",o=>{e.globalPointerUp(o)}),We("keydown",o=>{e.globalKeyDown(o),F.isFocus(e)&&!F.hasBeenTextEditing(e)&&!Ua(o.target)&&e.keyDown(o)}),We("keyup",o=>{F.isFocus(e)&&!F.hasBeenTextEditing(e)&&(e==null||e.keyUp(o))}),We("copy",o=>{F.isFocus(e)&&!F.hasBeenTextEditing(e)&&!Ri(o.target)&&(o.preventDefault(),nr(e,vi.copy,o.clipboardData))}),We("paste",async o=>{if(F.isFocus(e)&&!F.isReadonly(e)&&!F.hasBeenTextEditing(e)&&!Ri(o.target)){const i=F.getMovingPointInBoard(e);if(i){const s=Xe(e,Ze(e,i[0],i[1])),r=await Su(o.clipboardData);e.insertFragment(r,s,vi.paste)}}}),We("cut",o=>{F.isFocus(e)&&!F.isReadonly(e)&&!F.hasBeenTextEditing(e)&&!Ri(o.target)&&(o.preventDefault(),nr(e,vi.cut,o.clipboardData),xu(e))}),We("drop",o=>{F.isReadonly(e)||(o.preventDefault(),e.drop(o))},{target:t}),We("dragover",o=>{o.preventDefault()},{target:t})},Zn=new WeakMap,Jn=new WeakMap,Di=new WeakMap,fl=e=>{const t=Up(e);return t||si(e)||e.viewport.origination||[0,0]},Hp=(e,t,n)=>{const o=e.viewport.zoom,i=fl(e),s=F.getBoardContainer(e).getBoundingClientRect(),r=Gp(s,n),a=Eu(t),c=i[0]+r[0]/o,u=i[1]+r[1]/o;ee.updateViewport(e,[c-r[0]/a,u-r[1]/a],a)},$p=(e,t=1,n=120)=>{Zn.set(e,t);const o=Jn.get(e);o&&clearTimeout(o),Jn.set(e,setTimeout(()=>{Zn.delete(e),Jn.delete(e)},n))},Vp=e=>{const t=Zn.get(e)??0;if(t<=0)return!1;if(t===1){Zn.delete(e);const n=Jn.get(e);n&&(clearTimeout(n),Jn.delete(e))}else Zn.set(e,t-1);return!0},Us=e=>{const t=Te(e);return t.forEach(n=>{const o=vn.getElementRef(n);o==null||o.updateActiveSection()}),t.length},Wp=e=>Di.get(e)||Te(e).length===0?!1:(Di.set(e,!0),qp(()=>{Di.delete(e),Us(e)}),!0),tn=e=>{const t=Us(e);return t>0&&Wp(e),t},Up=e=>{const t=e.viewport.zoom;if(!Number.isFinite(t)||t<=0)return null;try{const n=F.getViewportContainer(e),o=ku(e);return!o||!Number.isFinite(o.x)||!Number.isFinite(o.y)||!Number.isFinite(o.width)||!Number.isFinite(o.height)||o.width<=0||o.height<=0?null:[n.scrollLeft/t+o.x,n.scrollTop/t+o.y]}catch{return null}},Gp=(e,t)=>t&&Kp(t,e)?[t[0]-e.x,t[1]-e.y]:[e.width/2,e.height/2],Kp=(e,t)=>e[0]>=t.left&&e[0]<=t.right&&e[1]>=t.top&&e[1]<=t.bottom,qp=e=>{if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(e);return}setTimeout(e,0)},Yp=(e,t)=>{We("scroll",o=>{if(Vp(e)||bu(e))to(e,!1);else{const i=o.target;if(!i)return;const{scrollLeft:s,scrollTop:r}=i;_u(e,s,r)}},{target:t}),We("touchstart",o=>{o.preventDefault()},{target:t,passive:!1}),We("wheel",o=>{if(o.metaKey||o.ctrlKey){o.preventDefault();const{deltaX:i,deltaY:s}=o,r=e.viewport.zoom,a=Math.sign(s),c=Pu*100,u=Math.abs(s);let l=s;u>c&&(l=c*a);let h=r-l/100;h+=Math.log10(Math.max(1,r))*-a*Math.min(1,u/20),Hp(e,h,F.getMovingPointInBoard(e))}},{target:t,passive:!1});const n=p.useRef(!1);p.useEffect(()=>{const o=new ResizeObserver(()=>{if(!n.current){n.current=!0;return}bs(e),ri(e),ai(e),tn(e)});return o.observe(F.getBoardContainer(e)),()=>{o&&o.disconnect()}},[])},Gs=p.createContext(null),Ye=()=>{const e=p.useContext(Gs);if(!e)throw new Error("The `useBoard` hook must be used inside the <Plait> component's context.");const{board:t}=e;return t},gl=()=>{const e=p.useContext(Gs);if(!e)throw new Error("The `useBoard` hook must be used inside the <Plait> component's context.");const{listRender:t}=e;return t},Xp=({style:e,className:t,children:n,afterInit:o})=>{var y,m;const i=p.useRef(null),s=p.useRef(null),r=p.useRef(null),a=p.useRef(null),c=p.useRef(null),u=p.useRef(null),l=p.useRef(null),h=p.useRef(null),f=Ye(),g=gl();return p.useEffect(()=>{const w=zp.svg(i.current,{options:{roughness:0,strokeWidth:1}});or.set(f,w),ir.set(f,i.current),sr.set(f,!0),rr.set(f,{lowerHost:s.current,host:r.current,upperHost:a.current,topHost:c.current,activeHost:u.current,container:h.current,viewportContainer:l.current});const S=new Tu;return ar.set(f,S),cr.set(f,new Map),g.initialized||(g.initialize(f.children,{board:f,parent:f,parentG:F.getElementHost(f)}),o&&o(f)),bs(f),ri(f),Cu(f),()=>{ar.delete(f),Wi.delete(f),Ui.delete(f),rr.delete(f),sr.delete(f),ir.delete(f),or.delete(f),cr.delete(f)}},[]),Bp(f,l,i),Yp(f,l),d.jsx("div",{className:me(t,Iu,`${Zp()}`,`theme-${(y=f.theme)==null?void 0:y.themeColorMode}`,`pointer-${f.pointer}`,{focused:F.isFocus(f),readonly:F.isReadonly(f),"disabled-scroll":((m=f.options)==null?void 0:m.disabledScrollOnNonFocus)&&!F.isFocus(f)}),ref:h,style:e,children:d.jsxs("div",{className:"viewport-container",ref:l,style:{width:"100%",height:"100%",overflow:"auto"},children:[d.jsxs("svg",{ref:i,width:"100%",height:"100%",style:{position:"relative"},className:"board-host-svg",children:[d.jsx("g",{className:"element-lower-host",ref:s}),d.jsx("g",{className:"element-host",ref:r}),d.jsx("g",{className:"element-upper-host",ref:a}),d.jsx("g",{className:"element-top-host",ref:c})]}),d.jsx("svg",{width:"100%",height:"100%",className:"board-active-svg",children:d.jsx("g",{className:"active-host-g",ref:u})}),n]})})},Zp=()=>Au?"safari":Mu?"chrome":Ru?"firefox":"",Jp=e=>{const t=e;return t.renderText=(n,o)=>{const i=mo.createRoot(n);let s,r=!1,a;const c=()=>{a&&(clearTimeout(a),a=void 0)},u=d.jsx(kr,{...o,afterInit:f=>{s=f,o.afterInit&&o.afterInit(s)}});i.render(u);let l={...o};return{destroy:()=>{r||(r=!0,c(),setTimeout(()=>{i.unmount()},0))},update:f=>{if(r||!(f&&l&&!Object.keys(f).every(m=>f[m]===l[m])))return;const y=mn.isReadOnly(s);l={...l,...f},i.render(d.jsx(kr,{...l})),y===!0&&l.readonly===!1?(c(),a=setTimeout(()=>{a=void 0,!r&&(Qp(s),mn.focus(s))},0)):y===!1&&l.readonly===!0&&(c(),mn.blur(s),mn.deselect(s))}}},t},Qp=e=>{const{selection:t}=e;t&&(pn.has(e,t.anchor.path)&&pn.has(e,t.focus.path)||Du.deselect(e))},em=e=>{const{pointerDown:t,pointerMove:n,pointerUp:o,globalPointerUp:i}=e,s=[];let r=!1;return e.pointerDown=a=>{const c=[a.clientX,a.clientY];s.length<2&&(e.viewport.zoom,s.push({pointerId:a.pointerId,lastPoint:c,currentPoint:c,hasMoved:!1})),t(a)},e.pointerMove=a=>{const c=[a.clientX,a.clientY];if(s.length>=2){const u=s.find(l=>l.pointerId===a.pointerId);if(u&&(u.currentPoint=c,u.hasMoved=!0,s.length===2&&s.every(l=>l.hasMoved))){const l=s[0],h=s[1],f=lr(...l.lastPoint,...h.lastPoint),g=lr(...l.currentPoint,...h.currentPoint),y=g[0]-f[0],m=g[1]-f[1],w=F.getBoardContainer(e).getBoundingClientRect(),S=w.width/2,v=w.height/2,E=e.viewport.zoom,C=fl(e);let D=C[0]+S/E-y/E,P=C[1]+v/E-m/E,H=[D-w.width/2/E,P-w.height/2/E],B=E;const j=Bo(...l.lastPoint,...h.lastPoint),A=Bo(...l.currentPoint,...h.currentPoint)/j,I=[l.currentPoint[0]-l.lastPoint[0],l.currentPoint[1]-l.lastPoint[1]],k=[h.currentPoint[0]-h.lastPoint[0],h.currentPoint[1]-h.lastPoint[1]],T=I[0]*k[0]+I[1]*k[1],M=Math.sqrt(I[0]*I[0]+I[1]*I[1]),O=Math.sqrt(k[0]*k[0]+k[1]*k[1]),q=T/(M*O||1);if(q<-.7||q<=.8&&r&&A>=.01?r=!0:r=!1,r){B=Math.min(Math.max(e.viewport.zoom*A,Lu),ju);const R=F.getBoardContainer(e).getBoundingClientRect(),L=g[0]-R.x,Y=g[1]-R.y;D=H[0]+L/E,P=H[1]+Y/E,H=[D-L/B,P-Y/B]}ee.updateViewport(e,H,B),s.forEach(le=>{le.lastPoint=le.currentPoint,le.hasMoved=!1})}return}n(a)},e.pointerUp=a=>{const c=s.findIndex(u=>u.pointerId===a.pointerId);c!==-1&&s.splice(c,1),o(a)},e.globalPointerUp=a=>{const c=s.findIndex(u=>u.pointerId===a.pointerId);c!==-1&&s.splice(c,1),i(a)},e},tm=({value:e,children:t,options:n,plugins:o,viewport:i,theme:s,onChange:r,onSelectionChange:a,onValueChange:c,onViewportChange:u,onThemeChange:l})=>{const[h,f]=p.useState(()=>{const v=nm(e,n,o,i,s),E=im(v);return{v:0,board:v,listRender:E}}),{board:g,listRender:y}=h,m=p.useCallback(()=>{if(r){const P={children:g.children,operations:g.operations,viewport:g.viewport,selection:g.selection,theme:g.theme};r(P)}const v=g.operations.some(P=>cn.isSetSelectionOperation(P)),E=g.operations.some(P=>cn.isSetViewportOperation(P)),C=g.operations.some(P=>cn.isSetThemeOperation(P)),D=g.operations.length>0&&!g.operations.every(P=>cn.isSetSelectionOperation(P)||cn.isSetViewportOperation(P)||cn.isSetThemeOperation(P));c&&D&&c(g.children),a&&v&&a(g.selection),u&&E&&u(g.viewport),l&&C&&l(g.theme.themeColorMode),f(P=>({v:P.v+1,board:g,listRender:y}))},[g,r,a,c,u,l]);p.useEffect(()=>(Ui.set(g,()=>{if(g.operations.length&&g.operations.every(C=>C.type==="set_selection")){y.update(g.children,{board:g,parent:g,parentG:F.getElementHost(g)});return}const E=g.operations.length&&g.operations.some(C=>C.type==="set_viewport");if(E&&Ou(g)){Nu(g,!1),y.update(g.children,{board:g,parent:g,parentG:F.getElementHost(g)}),tn(g);return}y.update(g.children,{board:g,parent:g,parentG:F.getElementHost(g)}),E?ri(g):zu(g),ai(g),E?tn(g):Us(g)}),Wi.set(g,()=>{m()}),()=>{Ui.delete(g),Wi.delete(g)}),[g]);const w=p.useRef(!0),S=p.useRef(i);return p.useEffect(()=>{const v=S.current;S.current=i;const E=e!==g.children;i&&!ur.get(g)&&!E&&(am(v,i)||(g.viewport=i,ea(g,"viewport-prop-change")))},[i,g,e]),p.useEffect(()=>{if(w.current){w.current=!1;return}e!==h.board.children&&!ur.get(g)&&(g.children=e,om(g),At(g),g.selection=null,y.update(g.children,{board:g,parent:g,parentG:F.getElementHost(g)}),i?(g.viewport=i,ea(g,"value-with-viewport-change")):ee.fitViewport(g))},[e,i]),d.jsx(Gs.Provider,{value:h,children:t})},nm=(e,t,n,o,i)=>{let s=Fu(Bu(Hu($u(Vu(Wu(Uu(Gu(Ku(Jp(qu(Yu(Xu(e,t)))))))))))));return n.forEach(r=>{s=r(s)}),em(s),o&&(s.viewport=o),i&&(s.theme=i),s},om=e=>{e.history.undos=[],e.history.redos=[]},im=e=>new Zu(e),sm=30,rm=6,wn=2,Qn=new WeakMap,gs=new WeakMap,ea=(e,t)=>{bs(e),ri(e),ai(e),tn(e),dm(e,t)},am=(e,t)=>{var n,o,i,s;return e===t?!0:!e||!t?!1:e.zoom===t.zoom&&e.offsetX===t.offsetX&&e.offsetY===t.offsetY&&((n=e.origination)==null?void 0:n[0])===((o=t.origination)==null?void 0:o[0])&&((i=e.origination)==null?void 0:i[1])===((s=t.origination)==null?void 0:s[1])},cm="aitu_debug_viewport",lm=()=>{if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("debugViewport")==="1"||window.localStorage.getItem(cm)==="true"}catch{return!1}},um=e=>{var t;try{const n=(t=e.viewport)==null?void 0:t.origination;if(!n)return null;const o=F.getHost(e).getAttribute("viewBox");if(!o)return null;const[i,s]=o.trim().split(/[\s,]+/).map(a=>Number(a));if(!Number.isFinite(i)||!Number.isFinite(s))return null;const r=e.viewport.zoom;return{targetScrollLeft:(n[0]-i)*r,targetScrollTop:(n[1]-s)*r}}catch{return null}},dm=(e,t)=>{if(typeof window>"u")return;const n=(Qn.get(e)??0)+1;Qn.set(e,n),fm(e,t);let o=0;const i=()=>{if(Qn.get(e)!==n)return;const s=um(e);if(!s){ps(),Xo(e),to(e,!1),tn(e);return}const r=F.getViewportContainer(e),a=Math.abs(r.scrollLeft-s.targetScrollLeft),c=Math.abs(r.scrollTop-s.targetScrollTop);(a>wn||c>wn)&&hm(e,s),tn(e);const l=Math.abs(r.scrollLeft-s.targetScrollLeft),h=Math.abs(r.scrollTop-s.targetScrollTop),f=l<=wn&&h<=wn;if(!(o+1<sm&&(!f||o+1<rm))){ps("wrapper:restore-scroll",e,{...s}),Xo(e),to(e,!1);return}o+=1,ta(i)};ta(i)},ta=e=>{if(typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(e);return}window.setTimeout(e,0)},hm=(e,t)=>{const n=F.getViewportContainer(e);to(e,!0),n.scrollLeft=t.targetScrollLeft,n.scrollTop=t.targetScrollTop;const o=Math.abs(n.scrollLeft-t.targetScrollLeft),i=Math.abs(n.scrollTop-t.targetScrollTop);(o>wn||i>wn)&&ai(e),tn(e)},fm=(e,t)=>{Xo(e);const n=i=>{gm(e,t,i)},o={capture:!0,passive:!0};window.addEventListener("wheel",n,o),window.addEventListener("pointerdown",n,o),window.addEventListener("touchstart",n,o),window.addEventListener("keydown",n,o),gs.set(e,()=>{window.removeEventListener("wheel",n,o),window.removeEventListener("pointerdown",n,o),window.removeEventListener("touchstart",n,o),window.removeEventListener("keydown",n,o)})},gm=(e,t,n)=>{Qn.set(e,(Qn.get(e)??0)+1),Xo(e),pm(n)&&$p(e,2),to(e,!1),ps()},pm=e=>typeof WheelEvent<"u"&&e instanceof WheelEvent&&(e.ctrlKey||e.metaKey),Xo=e=>{const t=gs.get(e);t&&(t(),gs.delete(e))},ps=(e,t,n)=>{lm()},na=e=>d.jsx("span",{className:"mind-node-emoji",style:{fontSize:`${e.fontSize}px`},children:e.emojiItem.name}),mm=e=>{const t=e;return e.setPluginOptions(Ju,{emojiPadding:0,spaceBetweenEmojis:4}),t.renderEmoji=(n,o)=>{const i=document.createElement("span");n.appendChild(i);const s=mo.createRoot(i);s.render(d.jsx(na,{...o}));let r={...o};return{destroy:()=>{setTimeout(()=>{s.unmount()},0)},update:c=>{r={...r,...c},s.render(d.jsx(na,{...r}))}}},t},wm=e=>{const t=p.useRef(null),[n,o]=p.useState(!1),[i,s]=p.useState(!0),{videoItem:r,isFocus:a=!1,isSelected:c=!1,readonly:u=!1}=e,{url:l,poster:h,videoType:f}=r,g=(l==null?void 0:l.replace("#video",""))||"";p.useEffect(()=>{const S=t.current;if(S){const v=()=>{s(!1),o(!1)},E=()=>{s(!1),o(!0)};return S.addEventListener("loadeddata",v),S.addEventListener("error",E),()=>{S.removeEventListener("loadeddata",v),S.removeEventListener("error",E)}}},[g]);const y=S=>{u&&S.stopPropagation()},m=S=>{u&&(S.stopPropagation(),S.preventDefault(),window.open(g,"_blank"))},w={position:"relative",width:"100%",height:"100%",backgroundColor:"#000",borderRadius:"4px",overflow:"hidden"};return n?d.jsx("div",{style:w,"data-slideshow-media-control":"true",onClick:m,onPointerDown:y,onPointerUp:y,children:d.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",color:"#666",backgroundColor:"#f5f5f5",cursor:u?"pointer":"default"},children:[d.jsx("div",{style:{fontSize:"48px",marginBottom:"8px"},children:"🎬"}),d.jsx("div",{style:{fontSize:"14px",textAlign:"center",padding:"0 16px"},children:"Video failed to load"}),u&&d.jsx("div",{style:{fontSize:"12px",color:"#999",marginTop:"4px"},children:"Click to open in new window"})]})}):d.jsxs("div",{style:w,"data-slideshow-media-control":"true",onClick:m,onPointerDown:y,onPointerUp:y,children:[i&&d.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0, 0, 0, 0.7)",color:"white",zIndex:1},children:d.jsxs("div",{style:{textAlign:"center"},children:[d.jsx("div",{style:{fontSize:"24px",marginBottom:"8px"},children:"⏳"}),d.jsx("div",{style:{fontSize:"14px"},children:"Loading video..."})]})}),d.jsx("video",{ref:t,"data-slideshow-media-control":"true",src:g,poster:h,width:"100%",height:"100%",controls:!u,muted:!0,playsInline:!0,draggable:!1,className:me("video-origin",{"video-origin--focus":a,"video-origin--selected":c}),style:{width:"100%",height:"100%",objectFit:"contain"},onPointerDown:y,onPointerUp:y,onError:()=>o(!0)}),u&&d.jsx("div",{style:{position:"absolute",top:"8px",right:"8px",backgroundColor:"rgba(0, 0, 0, 0.6)",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"12px",pointerEvents:"none"},children:"🎬 Video"})]})},Io="http://www.w3.org/2000/svg",ym="http://www.w3.org/1999/xlink",Rn=new WeakMap,Dn=new WeakMap;function vm(e){const t=Rn.get(e);if(t)return t.count+=1,e.style.overflow="visible",()=>{t.count-=1,t.count<=0&&(e.style.overflow=t.previousOverflow,Rn.delete(e))};const n=e.style.overflow;return Rn.set(e,{count:1,previousOverflow:n}),e.style.overflow="visible",()=>{const o=Rn.get(e);o&&(o.count-=1,o.count<=0&&(e.style.overflow=o.previousOverflow,Rn.delete(e)))}}function Sm(e){const t=Dn.get(e);if(t)return t.count+=1,e.style.visibility="hidden",e.style.pointerEvents="none",()=>{t.count-=1,t.count<=0&&(e.style.visibility=t.previousVisibility,e.style.pointerEvents=t.previousPointerEvents,Dn.delete(e))};const n=e.style.visibility,o=e.style.pointerEvents;return Dn.set(e,{count:1,previousVisibility:n,previousPointerEvents:o}),e.style.visibility="hidden",e.style.pointerEvents="none",()=>{const i=Dn.get(e);i&&(i.count-=1,i.count<=0&&(e.style.visibility=i.previousVisibility,e.style.pointerEvents=i.previousPointerEvents,Dn.delete(e)))}}const xm=e=>{if(e.isVideo===!0||e.videoType)return!0;const t=e.url||"";return t.includes("#video")||t.includes("#merged-video-")?!0:[".mp4",".avi",".mov",".wmv",".flv",".webm",".mkv"].some(o=>t.toLowerCase().includes(o))},oa=e=>{const t=p.useRef(e.imageItem.url),n=p.useRef(null),o=p.useRef(null),i=p.useRef(null),s=p.useRef(!1),r=p.useCallback(()=>{var j;(j=n.current)==null||j.call(n),n.current=null},[]);p.useEffect(()=>(t.current=e.imageItem.url,r),[e.imageItem.url,r]);const a=p.useCallback(j=>{if(typeof navigator>"u"||!("serviceWorker"in navigator)||navigator.serviceWorker.controller)return;r();let U=!1;const A=()=>{U||(U=!0,r(),!(!j.isConnected||t.current!==e.imageItem.url)&&(j.src=`${e.imageItem.url}${e.imageItem.url.includes("?")?"&":"?"}_sw_ready=${Date.now()}`))},I=window.setTimeout(()=>{U||(U=!0,r())},1e4),k=()=>{window.clearTimeout(I),navigator.serviceWorker.removeEventListener("controllerchange",A)};n.current=k,navigator.serviceWorker.addEventListener("controllerchange",A,{once:!0}),navigator.serviceWorker.ready.then(()=>{navigator.serviceWorker.controller&&A()}).catch(()=>{})},[r,e.imageItem.url]),c=p.useCallback(j=>{const U=j.currentTarget;U.style.visibility="hidden",a(U);const A=Qu(e.board,e.element,e.imageItem.url);A&&window.setTimeout(()=>{U.isConnected&&(U.src=A.retryUrl)},A.delay)},[e.board,e.element,e.imageItem.url,a]),u=p.useCallback(j=>{const U=j.currentTarget;U.style.visibility="",r(),ed(e.board,e.element,e.imageItem.url)},[r,e.board,e.element,e.imageItem.url]),l=e.element,h=l==null?void 0:l.pptImageStatus,f=l==null?void 0:l.pptImagePrompt,g=l==null?void 0:l.frameId,y=(l==null?void 0:l.isAudio)===!0||(l==null?void 0:l.audioType)==="music-card"||typeof(l==null?void 0:l.audioUrl)=="string"&&l.audioUrl.length>0,m=xm(e.imageItem),w=!y&&!m&&typeof(l==null?void 0:l.frameId)=="string",S=td(e.element)?nd(l==null?void 0:l.transform3d):void 0,v=!!S,E=S?Ga(e.element):void 0,C=S==null?void 0:S.rotateX,D=S==null?void 0:S.rotateY,P=S==null?void 0:S.perspective;p.useLayoutEffect(()=>{if(!v||!o.current)return;const j=o.current.closest("foreignObject");if(!j)return;const U=vm(j),A=j.parentElement;if(!A){U();return}const I=Sm(j),k=document.createElementNS(Io,"g"),T=document.createElementNS(Io,"clipPath"),M=document.createElementNS(Io,"polygon"),O=document.createElementNS(Io,"image"),q=`image-3d-clip-${(l==null?void 0:l.id)||"image"}-${Date.now()}`;return k.classList.add("image-3d-svg-overlay"),k.setAttribute("data-image-3d-overlay","true"),k.setAttribute("pointer-events","none"),T.setAttribute("id",q),T.append(M),O.setAttribute("clip-path",`url(#${q})`),O.setAttribute("preserveAspectRatio","none"),k.append(T,O),A.insertBefore(k,j.nextSibling),i.current={group:k,image:O,clipPath:T,clipPolygon:M},()=>{var le;((le=i.current)==null?void 0:le.group)===k&&(i.current=null),k.remove(),I(),U()}},[l==null?void 0:l.id,v,e.imageItem.url]),p.useLayoutEffect(()=>{if(C===void 0||D===void 0||P===void 0||!E||!o.current)return;const j=o.current.closest("foreignObject");if(!j)return;const U={rotateX:C,rotateY:D,perspective:P},A=i.current||(()=>{var q;const k=(q=j.parentElement)==null?void 0:q.querySelector('g[data-image-3d-overlay="true"]'),T=(k==null?void 0:k.querySelector("image"))||null,M=(k==null?void 0:k.querySelector("clipPath"))||null,O=(k==null?void 0:k.querySelector("clipPath polygon"))||null;return k&&T&&M&&O?{group:k,image:T,clipPath:M,clipPolygon:O}:null})();if(!A)return;i.current=A;const I=od(E,U);A.clipPolygon.setAttribute("points",I.pointsAttribute),A.image.setAttribute("href",e.imageItem.url),A.image.setAttributeNS(ym,"href",e.imageItem.url),A.image.setAttribute("x",String(I.boundingBox.x)),A.image.setAttribute("y",String(I.boundingBox.y)),A.image.setAttribute("width",String(I.boundingBox.width)),A.image.setAttribute("height",String(I.boundingBox.height)),I.textureTransform?A.image.setAttribute("transform",I.textureTransform):A.image.removeAttribute("transform")},[l==null?void 0:l.id,E==null?void 0:E.height,E==null?void 0:E.x,E==null?void 0:E.y,E==null?void 0:E.width,P,C,D,e.imageItem.url]);const H=p.useCallback(async()=>{var j;if(!(!e.board||!g||!f||h==="loading"||s.current)){s.current=!0,Si(e.board,g,"loading"),ko(e.board,g,"loading");try{const U=await id({prompt:f,size:"16x9"});if(U.success&&((j=U.data)!=null&&j.url)){sd(e.board,g);const A=e.board.children.find(I=>I.id===g);if(A){const I=de.getRectangleByPoints(A.points),k=rd({x:I.x,y:I.y,width:I.width,height:I.height});await ad(e.board,U.data.url,"image",g,{width:I.width,height:I.height},{width:800,height:450},k)}ko(e.board,g,"generated")}else Si(e.board,g,"placeholder"),ko(e.board,g,"placeholder"),Ne.error(U.error||"图片生成失败")}catch(U){Si(e.board,g,"placeholder"),ko(e.board,g,"placeholder"),Ne.error((U==null?void 0:U.message)||"图片生成失败")}finally{s.current=!1}}},[e.board,g,f,h]);if(l!=null&&l.pptImagePlaceholder){const j=h==="loading";return d.jsxs("div",{className:"ppt-image-placeholder",onClick:j?void 0:H,style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"8px",borderRadius:"8px",border:"1px dashed #d9d9d9",backgroundColor:"rgba(245,245,245,0.85)",color:"#999",fontSize:"13px",cursor:j?"default":"pointer",userSelect:"none"},children:[j?d.jsx(cd,{size:"small"}):null,d.jsx("span",{children:j?"生成配图中…":"点击生成配图"})]})}if(m)return d.jsx(wm,{videoItem:{url:e.imageItem.url,width:e.imageItem.width,height:e.imageItem.height,videoType:e.imageItem.videoType,poster:e.imageItem.poster},isFocus:e.isFocus,isSelected:e.isSelected,readonly:e.readonly});const B={src:e.imageItem.url,draggable:!1,...w?{style:{width:"100%",height:"100%",objectFit:"contain",display:"block"}}:{width:"100%",style:void 0}};return d.jsx("div",{ref:o,"data-slideshow-legacy-audio":y?"true":void 0,style:S||w?{width:"100%",height:"100%"}:void 0,children:d.jsx("img",{...B,className:me("image-origin",{"image-origin--focus":e.isFocus}),style:B.style,onError:c,onLoad:u})})},km="http://www.w3.org/1999/xlink";class Em extends ci{constructor(t){super(t),this.board=t,this.isFocus=!1,this.lastReactRenderKey="",this.activeGenerator=_s(this.board,{getStrokeWidth:()=>no,getStrokeOpacity:()=>{const n=Te(this.board);return n.length===1&&!oo(this.board)||!n.length?1:.5},getRectangle:n=>this.getActiveRectangle(n),hasResizeHandle:()=>{const n=li(this.board,this.element);return!!Ka(this.board)||n}})}canDraw(t){return!!Sn(t)}draw(t){this.element=t,this.lastReactRenderKey=this.getReactRenderKey(t,!0);const n=yo(),o=this.getSourceRectangle(t);return this.foreignObject=dd(o.x,o.y,o.width,o.height),this.foreignObject.classList.add(hd),n.append(this.foreignObject),this.imageComponentRef=this.board.renderImage(this.foreignObject,this.getImageProps(t)),n}updateImage(t){this.element=t;const n=Sn(t),o=n?this.syncSvgOverlay(t,n):!1,i=this.getReactRenderKey(t,!!n);if((i!==this.lastReactRenderKey||!!n&&!o)&&this.imageComponentRef&&this.imageComponentRef.update(this.getImageProps(t)),this.lastReactRenderKey=i,this.g){const r=this.getSourceRectangle(t);fd(this.g,r.width,r.height,r.x,r.y),t.angle!==void 0&&gd(this.g,de.getCenterPoint(r),t.angle)}}setFocus(t,n){var i;const o=this.isFocus!==n;this.isFocus=n,this.drawActive(t,n),o&&((i=this.imageComponentRef)==null||i.update({isFocus:n}))}destroy(){var t,n;super.destroy(),(t=this.imageComponentRef)==null||t.destroy(),(n=this.activeGenerator)==null||n.destroy()}drawActive(t,n){this.activeGenerator.processDrawing(t,F.getActiveHost(this.board),{selected:n})}getImageProps(t){const n=this.getSourceRectangle(t);return{board:this.board,imageItem:{url:t.url,width:n.width,height:n.height},element:t,getRectangle:()=>this.getSourceRectangle(t)}}getSourceRectangle(t){return Ga(t)||de.getRectangleByPoints(t.points)}getActiveRectangle(t){return pd(t)||this.getSourceRectangle(t)}getReactRenderKey(t,n){return[t.id,t.url,n?"3d":"flat"].join("|")}syncSvgOverlay(t,n=Sn(t)){if(!this.g||!n)return!1;const o=this.g.querySelector('g[data-image-3d-overlay="true"]'),i=(o==null?void 0:o.querySelector("image"))||null,s=(o==null?void 0:o.querySelector("clipPath polygon"))||null;return!o||!i||!s?!1:(s.setAttribute("points",n.pointsAttribute),i.setAttribute("href",t.url),i.setAttributeNS(km,"href",t.url),i.setAttribute("x",String(n.boundingBox.x)),i.setAttribute("y",String(n.boundingBox.y)),i.setAttribute("width",String(n.boundingBox.width)),i.setAttribute("height",String(n.boundingBox.height)),n.textureTransform?i.setAttribute("transform",n.textureTransform):i.removeAttribute("transform"),!0)}}class bm extends wo{initializeGenerator(){this.imageGenerator=new Em(this.board),this.lineAutoCompleteGenerator=new Gi(this.board),this.getRef().addGenerator(Gi.key,this.lineAutoCompleteGenerator),this.getRef().updateActiveSection=()=>this.updateActiveSection()}initialize(){super.initialize(),this.initializeGenerator(),this.imageGenerator.processDrawing(this.element,this.getElementG()),this.updateActiveSection()}onContextChanged(t,n){const o=t.board.viewport.zoom!==n.board.viewport.zoom||t.board.viewport.offsetX!==n.board.viewport.offsetX||t.board.viewport.offsetY!==n.board.viewport.offsetY;if(t.element!==n.element||t.hasThemeChanged||t.selected){this.imageGenerator.updateImage(t.element),this.updateActiveSection();return}if(o&&t.selected){this.updateActiveSection();return}(t.selected!==n.selected||t.selected)&&this.updateActiveSection()}destroy(){var t,n;super.destroy(),(t=this.imageGenerator)==null||t.destroy(),(n=this.lineAutoCompleteGenerator)==null||n.destroy()}updateActiveSection(){this.imageGenerator.setFocus(this.element,this.selected),this.lineAutoCompleteGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})}}const _m=e=>{const{drawElement:t,isHit:n,isRectangleHit:o}=e;return e.drawElement=i=>Sn(i.element)?bm:t(i),e.isHit=(i,s,r)=>{const a=Sn(i);return a?ld(s,a):n(i,s,r)},e.isRectangleHit=(i,s)=>{const r=Sn(i);if(r){const a=de.getRectangleByPoints([s.anchor,s.focus]);return ud(a,r)}return o(i,s)},e};let Li=null;function Pm(){return Li||(Li=Promise.all([re(()=>import("./media-viewer-xSaTD7_w.js").then(e=>e.v),__vite__mapDeps([2]),import.meta.url),re(()=>import("./media-viewer-xSaTD7_w.js").then(e=>e.a),__vite__mapDeps([2]),import.meta.url)]).then(([e])=>e.default)),Li}const Tm=()=>window.innerWidth<=768||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);class Cm{constructor(t={}){this.viewer=null,this.container=null,this.openVersion=0,this.options={zoomStep:t.zoomStep||.2,minZoom:t.minZoom||.1,maxZoom:t.maxZoom||5,enableKeyboard:t.enableKeyboard!==!1}}open(t,n=""){this.close();const o=++this.openVersion;this.container=document.createElement("div"),this.container.style.display="none";const i=document.createElement("img");i.src=t,i.alt=n,this.container.appendChild(i),document.body.appendChild(this.container);const s=Tm(),r=s?{zoomIn:1,zoomOut:1,oneToOne:0,reset:1,prev:0,play:0,next:0,rotateLeft:1,rotateRight:1,flipHorizontal:0,flipVertical:0}:{zoomIn:1,zoomOut:1,oneToOne:1,reset:1,prev:0,play:0,next:0,rotateLeft:1,rotateRight:1,flipHorizontal:1,flipVertical:1};Pm().then(a=>{o!==this.openVersion||!this.container||(this.viewer=new a(this.container,{inline:!1,button:!0,navbar:!1,title:!!n,toolbar:r,fullscreen:!s,keyboard:this.options.enableKeyboard,backdrop:!0,loading:!0,loop:!1,minZoomRatio:this.options.minZoom,maxZoomRatio:this.options.maxZoom,zoomRatio:this.options.zoomStep,hidden:()=>{this.cleanup()}}),this.viewer.show())}).catch(a=>{o===this.openVersion&&(console.warn("[ImageViewer] failed to load viewerjs:",a),this.cleanup())})}close(){if(this.openVersion+=1,this.viewer){this.viewer.hide();return}this.cleanup()}cleanup(){this.viewer&&(this.viewer.destroy(),this.viewer=null),this.container&&this.container.parentNode&&(this.container.parentNode.removeChild(this.container),this.container=null)}destroy(){this.close(),this.cleanup()}}const ia=3,Im=440,Am=300;function Mm(e){const t=[];for(let n=0;n<e.length;n++){const o=e[n];if(qa(o.type)){t.push({file:o,kind:"image",mimeType:o.type});continue}const i=yd(o);if(i){t.push({file:o,kind:"video",mimeType:i});continue}vd(o.type)&&t.push({file:o,kind:"audio",mimeType:o.type})}return t}function Rm(e,t){return Xe(e,Ze(e,t.x,t.y))}function Dm(e,t){const n=F.getBoardContainer(e).getBoundingClientRect(),o=[t.clientX-n.x,t.clientY-n.y];return{point:Rm(e,t),activePoint:o,zoom:e.viewport.zoom}}function Lm(e,t){const n=()=>{const o=Number.isFinite(e.viewport.zoom)&&e.viewport.zoom>0?e.viewport.zoom:t.zoom;ee.updateViewport(e,[t.point[0]-t.activePoint[0]/o,t.point[1]-t.activePoint[1]/o],o)};if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(()=>window.requestAnimationFrame(n));return}setTimeout(n,0)}function jm(e,t,n){if(n<=1)return e;const o=t%ia,i=Math.floor(t/ia);return[e[0]+o*Im,e[1]+i*Am]}function pl(e,t){var o;return((o=e.name)==null?void 0:o.trim())||`${t}-${Date.now()}`}async function Om(e,t,n,o){const i=t.type===n?t:t.slice(0,t.size,n);await Ho.initialize();const s=await Ho.addAsset({type:Yt.VIDEO,source:Za.LOCAL,name:pl(t,"video"),blob:i,mimeType:n});await Ja(e,s.url,o,!0,void 0,!0,!0)}async function Nm(e,t,n,o){const i=pl(t,"audio"),s=i.replace(/\.[^.]+$/,"");await Ho.initialize();const r=await Ho.addAsset({type:Yt.AUDIO,source:Za.LOCAL,name:i,blob:t,mimeType:n});await hr.updateCachedMedia(r.url,{metadata:{name:s}});const[a,c]=await Promise.all([Sd(t),xd(t)]);let u;if(c){const l=`/__aitu_cache__/image/${r.id}-cover.png`;await hr.cacheMediaFromBlob(l,c,"image",{taskId:`${r.id}-cover`,name:`${s}-cover`}),u=l}await Qa(e,r.url,{title:s,duration:a,previewImageUrl:u},o,!0)}async function zm(e,t,n,o){const i=t.length===1&&t[0].kind==="image";for(let s=0;s<t.length;s++){const r=t[s],a=jm(n,s,t.length);try{r.kind==="image"?await Ya(e,r.file,a,i,!i):r.kind==="video"?await Om(e,r.file,r.mimeType,a):await Nm(e,r.file,r.mimeType,a)}catch(c){console.error("[withImagePlugin] Failed to insert dropped media:",c)}}Lm(e,o)}function Fm(e){const t=e.getData("text/uri-list");if(t){const i=t.split(`
|
|
5
5
|
`).filter(s=>s&&!s.startsWith("#"));if(i.length>0&&sa(i[0]))return i[0].trim()}const n=e.getData("text/plain");if(n&&sa(n.trim()))return n.trim();const o=e.getData("text/html");if(o){const i=o.match(/<img[^>]+src=["']([^"']+)["']/i);if(i&&i[1])return i[1]}return null}function sa(e){if(!e)return!1;try{new URL(e)}catch{return!1}const t=[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"],n=e.toLowerCase();return t.some(i=>n.includes(i))?!0:[/\.(jpg|jpeg|png|gif|webp|svg|bmp)(\?|$)/i,/\/image\//i,/\/images\//i,/\/img\//i,/\/photo\//i,/data:image\//i,/blob:/i].some(i=>i.test(e))}const Bm=e=>{const t=e,{insertFragment:n,drop:o,pointerUp:i}=t,s=new Cm({zoomStep:.3,minZoom:.1,maxZoom:5,enableKeyboard:!0});return t.insertFragment=(r,a,c)=>{var u;if((u=r==null?void 0:r.files)!=null&&u.length&&qa(r.files[0].type)){const l=r.files[0];Ya(e,l,a,!1).catch(()=>{});return}n(r,a,c)},t.drop=r=>{var a,c;if((c=(a=r.dataTransfer)==null?void 0:a.files)!=null&&c.length){const u=Mm(r.dataTransfer.files);if(u.length>0){const l=Dm(e,r);return zm(e,u,l.point,l).catch(h=>{console.error("[withImagePlugin] Failed to insert dropped media files:",h)}),!0}}if(r.dataTransfer){const u=Fm(r.dataTransfer);if(u){const l=Xe(e,Ze(e,r.x,r.y));return md(e,u,l).catch(h=>{console.error("[withImagePlugin] Failed to insert image from URL:",h)}),!0}}return o(r)},t.pointerUp=r=>{if(document.documentElement.classList.contains("slideshow-active")){i(r);return}const a=Ka(e);if(a&&!Xa(e)&&!oo(e)&&!Ki(e)){const c=Xe(e,Ze(e,r.x,r.y)),u=qi(e,c);u&&dr.isMindElement(e,u)&&dr.hasImage(u)&&wd(e,u,c)&&a===u&&s.open(u.data.image.url)}i(r)},t},Ln={MAX_CHARS_PER_LINE:50};function Hm(e){const t=e.split(`
|
|
6
6
|
`),n=[];for(const o of t)if(o.length<=Ln.MAX_CHARS_PER_LINE)n.push(o);else{let i=o;for(;i.length>0;){let s=Ln.MAX_CHARS_PER_LINE;if(i.length>Ln.MAX_CHARS_PER_LINE){const r=i.lastIndexOf(" ",Ln.MAX_CHARS_PER_LINE);r>Ln.MAX_CHARS_PER_LINE*.7&&(s=r)}n.push(i.substring(0,s).trim()),i=i.substring(s).trim()}}return n.join(`
|
|
7
|
-
`)}function $m(e){var o,i;if(!e)return!1;const t=!!e.text||!!((o=e.data)!=null&&o.text),n=!!e.elements||!!((i=e.data)!=null&&i.elements);return t&&!n}function Vm(e){var n;const t=e;if(t.text)return t.text;if((n=t.data)!=null&&n.text)return t.data.text;if(typeof t.getData=="function"){const o=t.getData("text/plain");if(o)return o}return null}const Wm=e=>{const{insertFragment:t}=e;return e.insertFragment=(n,o,i)=>{if($m(n)){const s=Vm(n);if(s&&s.trim()){const r=s.trim(),a=kd(r);if(a&&a.length>0){const u=Math.round(window.innerWidth*.5);Ed(e,a,o,u);return}const c=Hm(r);ec.insertText(e,o,c);return}}t(n,o,i)},e},Um=e=>{const t=e;return t.renderImage=(n,o)=>{const i=mo.createRoot(n);i.render(d.jsx(oa,{...o}));let s={...o};return{destroy:()=>{setTimeout(()=>{i.unmount()},0)},update:a=>{s={...s,...a},i.render(d.jsx(oa,{...s}))}}},_m(Wm(Bm(t)))},Gm=p.forwardRef(({children:e,gap:t,align:n,justifyContent:o,className:i,style:s},r)=>d.jsx("div",{className:me("stack stack_horizontal",i),style:{"--gap":t,alignItems:n,justifyContent:o,...s},ref:r,children:e})),Km=p.forwardRef(({children:e,gap:t,align:n,justifyContent:o,className:i,style:s},r)=>d.jsx("div",{className:me("stack stack_vertical",i),style:{"--gap":t,justifyItems:n,justifyContent:o,...s},ref:r,children:e})),kt={Row:Gm,Col:Km},an=on.forwardRef(({children:e,padding:t,className:n,style:o,...i},s)=>d.jsx("div",{className:me("island",n),style:{"--padding":t,...o},ref:s,...i,children:e})),pi=on.createContext({}),ra=(e="",t=!1)=>`menu-item menu-item-base ${e} ${t?"menu-item--active":""}`.trim(),qm=(e,t)=>{const n=p.useContext(pi);return bd(e,o=>{var s;const i=new CustomEvent(Ps.MENU_ITEM_SELECT,{bubbles:!0,cancelable:!0});t==null||t(i),i.defaultPrevented||(s=n.onSelect)==null||s.call(n,i)})},Ym=({icon:e,shortcut:t,children:n})=>d.jsxs(d.Fragment,{children:[e&&d.jsx("div",{className:"menu-item__icon",children:e}),d.jsx("div",{className:"menu-item__text",children:n}),t&&d.jsx("div",{className:"menu-item__shortcut",children:t})]}),ce=({icon:e,onSelect:t,children:n,shortcut:o,className:i,selected:s,submenu:r,...a})=>{const[c,u]=p.useState(!1),l=p.useRef(),{title:h,...f}=a,g=f["aria-label"]??h,y=qm(f.onClick,t),m=d.jsx(Ym,{icon:e,shortcut:o,children:n}),w=()=>{l.current&&window.clearTimeout(l.current),u(!0)},S=()=>{l.current=window.setTimeout(()=>{u(!1)},100)};return r?d.jsxs(Mt,{open:c,onOpenChange:u,placement:"right-start",children:[d.jsx(Rt,{asChild:!0,children:d.jsx("button",{...f,type:"button",className:ra(i,s||c),"aria-label":g,onClick:y,onMouseEnter:w,onMouseLeave:S,role:"menuitem","aria-haspopup":"true","aria-expanded":c,children:m})}),d.jsx(Dt,{onMouseEnter:w,onMouseLeave:S,children:r})]}):d.jsx("button",{...f,onClick:y,type:"button",className:ra(i,s),"aria-label":g,role:"menuitem",children:m})};ce.displayName="MenuItem";const ml=({children:e})=>d.jsx("div",{style:{display:"inline-flex",marginLeft:"auto",padding:"2px 4px",background:"var(--color-promo)",color:"var(--color-surface-lowest)",borderRadius:6,fontSize:9,fontFamily:"Cascadia, monospace"},children:e});ml.displayName="MenuItemBadge";ce.Badge=ml;const Et=({children:e,className:t="",onSelect:n,style:o,onClose:i})=>{const s=me(`menu ${t}`).trim(),r=p.useRef(null),a=p.useCallback(()=>r.current?Array.from(r.current.querySelectorAll("button.menu-item:not([disabled])")):[],[]),c=p.useCallback(u=>{var f,g,y,m;const l=a();if(l.length===0)return;const h=l.findIndex(w=>w===document.activeElement);switch(u.key){case"ArrowDown":{u.preventDefault();const w=h<l.length-1?h+1:0;(f=l[w])==null||f.focus();break}case"ArrowUp":{u.preventDefault();const w=h>0?h-1:l.length-1;(g=l[w])==null||g.focus();break}case"Home":{u.preventDefault(),(y=l[0])==null||y.focus();break}case"End":{u.preventDefault(),(m=l[l.length-1])==null||m.focus();break}case"Escape":{u.preventDefault(),i==null||i();break}case"Enter":case" ":{h>=0&&l[h]&&(u.preventDefault(),l[h].click());break}}},[a,i]);return p.useEffect(()=>{const u=a();u.length>0&&requestAnimationFrame(()=>{var l;(l=u[0])==null||l.focus()})},[a]),d.jsx(pi.Provider,{value:{onSelect:n},children:d.jsx("div",{className:s,style:o,"data-testid":"menu",onKeyDown:c,ref:r,role:"menu",children:d.jsx(an,{className:"menu-container",padding:2,children:e})})})};Et.displayName="Menu";const wl=()=>{const e=Ye(),{t}=Oe();return d.jsx(ce,{"data-testid":"save-button","data-track":"toolbar_click_menu_save",onSelect:()=>{Bc(e)},icon:d.jsx(Pd,{}),"aria-label":t("menu.saveFile"),shortcut:"Cmd+S",children:t("menu.saveFile")})};wl.displayName="SaveToFile";const yl=()=>{const e=Ye(),t=gl(),{t:n}=Oe(),o=(i,s,r)=>{e.children=i,e.history.undos=[],e.history.redos=[],At(e),e.selection=null,e.viewport=s||{zoom:1},e.theme={themeColorMode:Kt.default},t.update(e.children,{board:e,parent:e,parentG:F.getElementHost(e)}),ee.fitViewport(e)};return d.jsx(ce,{"data-testid":"open-button","data-track":"toolbar_click_menu_open",onSelect:()=>{mf(e).then(i=>{i&&o(i.elements,i.viewport)})},icon:d.jsx(_d,{}),"aria-label":n("menu.open"),children:n("menu.open")})};yl.displayName="OpenFile";const vl=()=>{const e=Ye(),t=p.useContext(pi),{t:n}=Oe();return d.jsx(ce,{icon:d.jsx(Td,{}),"data-testid":"image-export-button","data-track":"toolbar_click_menu_export",onSelect:()=>{Do(e,!0)},submenu:d.jsxs(Et,{onSelect:()=>{var i;const o=new CustomEvent(Ps.MENU_ITEM_SELECT,{bubbles:!0,cancelable:!0});(i=t.onSelect)==null||i.call(t,o)},children:[d.jsx(ce,{"data-track":"toolbar_click_menu_export_png",onSelect:()=>{Do(e,!0)},"aria-label":n("menu.exportImage.png"),children:n("menu.exportImage.png")}),d.jsx(ce,{"data-track":"toolbar_click_menu_export_jpg",onSelect:()=>{Do(e,!1)},"aria-label":n("menu.exportImage.jpg"),children:n("menu.exportImage.jpg")})]}),shortcut:"Cmd+Shift+E","aria-label":n("menu.exportImage"),children:n("menu.exportImage")})};vl.displayName="SaveAsImage";const Sl=()=>{const{appState:e,setAppState:t}=Ht(),{t:n}=Oe();return d.jsx(ce,{icon:d.jsx(Cd,{}),"data-testid":"reset-button","data-track":"toolbar_click_menu_clean",onSelect:()=>{t({...e,openCleanConfirm:!0})},shortcut:"Cmd+Backspace","aria-label":n("menu.cleanBoard"),children:n("menu.cleanBoard")})};Sl.displayName="CleanBoard";const xl=({onOpenBackupRestore:e})=>{const{t}=Oe();return d.jsx(ce,{icon:d.jsx(Ad,{}),"data-track":"toolbar_click_menu_backup",onSelect:e,"aria-label":t("menu.backupRestore"),children:t("menu.backupRestore")})};xl.displayName="BackupRestore";const kl=({onOpenCloudSync:e})=>{const{t}=Oe();return d.jsx(ce,{icon:d.jsx(Rd,{}),"data-track":"toolbar_click_menu_cloud_sync",onSelect:e,"aria-label":t("menu.cloudSync"),children:t("menu.cloudSync")})};kl.displayName="CloudSync";const El=()=>{const{t:e}=Oe();return d.jsx(ce,{icon:d.jsx(Md,{}),"data-track":"toolbar_click_menu_debug",onSelect:()=>{window.location.href="./sw-debug.html"},"aria-label":e("menu.debugPanel"),children:e("menu.debugPanel")})};El.displayName="DebugPanel";const bl=()=>{const{appState:e,setAppState:t}=Ht(),{t:n}=Oe();return d.jsx(ce,{icon:d.jsx(Dd,{}),"data-track":"toolbar_click_menu_settings",onSelect:()=>{t({...e,openSettings:!0})},"aria-label":n("menu.settings"),children:n("menu.settings")})};bl.displayName="Settings";const _l=()=>{const{appState:e,setAppState:t}=Ht(),{t:n}=Oe();return d.jsx(ce,{icon:d.jsx(Ld,{}),"data-track":"toolbar_click_menu_commands",onSelect:()=>{t({...e,openCommandPalette:!0})},shortcut:"Cmd+K","aria-label":n("menu.commandPalette"),children:n("menu.commandPalette")})};_l.displayName="QuickCommands";const Pl=()=>{const{t:e}=Oe();return d.jsx(ce,{icon:d.jsx(jd,{}),"data-track":"toolbar_click_menu_manual",onSelect:()=>{window.open("./user-manual/index.html","_blank")},"aria-label":e("menu.userManual"),children:e("menu.userManual")})};Pl.displayName="UserManual";const Tl=()=>{var n;const{t:e}=Oe(),t=((n=document.querySelector('meta[name="app-version"]'))==null?void 0:n.getAttribute("content"))||"0.0.0";return d.jsx(ce,{"data-track":"toolbar_click_menu_version",onSelect:()=>{},"aria-label":e("menu.version"),children:d.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%"},children:[d.jsxs("span",{style:{color:"#666"},children:[e("menu.version"),":",t]}),d.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[d.jsx("span",{style:{color:"#1890ff",cursor:"pointer"},"data-track":"toolbar_click_menu_changelog",onClick:o=>{o.stopPropagation(),window.open("./versions.html","_blank")},children:e("menu.changelog")}),d.jsx("span",{style:{color:"#1890ff",cursor:"pointer"},"data-track":"toolbar_click_menu_more_versions",onClick:o=>{o.stopPropagation(),window.open("https://release.opentu.ai/","_blank")},children:e("menu.more")})]})]})})};Tl.displayName="VersionInfo";async function Xm(e){if(!e||typeof e!="string")return!1;if(e.startsWith("blob:")||e.startsWith("data:"))return!0;try{return(await fetch(e,{method:"HEAD",mode:"cors",cache:"no-cache"})).ok}catch{try{const t=await fetch(e,{method:"GET",mode:"no-cors",cache:"no-cache"});return t.type==="opaque"||t.ok}catch{return!1}}}const Cl=()=>{const e=Ye(),{t}=Oe(),[n,o]=p.useState(!1),i=p.useCallback(async()=>{if(n)return;o(!0);const s=Ne.loading(t("menu.cleanInvalidLinks.scanning"),0);try{const r=[];for(let u=0;u<e.children.length;u++){const l=e.children[u],h=l.url;if(!h||typeof h!="string")continue;const f=K.isDrawElement(l)&&K.isImage(l),g=Yi(l);(f||g)&&r.push({element:l,index:u,url:h})}const a=[];if(await Promise.all(r.map(async({element:u,index:l,url:h})=>{await Xm(h)||a.push({element:u,index:l})})),s.then(u=>{var l;return(l=u==null?void 0:u.close)==null?void 0:l.call(u)}),a.length===0){Ne.success(t("menu.cleanInvalidLinks.noInvalid")),o(!1);return}a.sort((u,l)=>l.index-u.index);for(const{index:u}of a)Se.removeNode(e,[u]);const c=t("menu.cleanInvalidLinks.success").replace("{count}",String(a.length));Ne.success(c)}catch(r){s.then(a=>{var c;return(c=a==null?void 0:a.close)==null?void 0:c.call(a)}),Ne.error(t("menu.cleanInvalidLinks.error")),console.error("[CleanInvalidLinks] Error:",r)}finally{o(!1)}},[e,t,n]);return d.jsx(ce,{icon:d.jsx(Id,{}),"data-track":"toolbar_click_menu_clean_invalid_links",onSelect:i,"aria-label":t("menu.cleanInvalidLinks"),disabled:n,children:t("menu.cleanInvalidLinks")})};Cl.displayName="CleanInvalidLinks";const Il=()=>{const{language:e,setLanguage:t,t:n}=Oe(),o=p.useContext(pi);return d.jsx(ce,{icon:d.jsx(tc,{}),"data-testid":"language-switcher-button",onSelect:()=>{},submenu:d.jsxs(Et,{onSelect:()=>{var s;const i=new CustomEvent(Ps.MENU_ITEM_SELECT,{bubbles:!0,cancelable:!0});(s=o.onSelect)==null||s.call(o,i)},children:[d.jsx(ce,{onSelect:()=>{t("zh")},"aria-label":n("language.chinese"),selected:e==="zh",children:n("language.chinese")}),d.jsx(ce,{onSelect:()=>{t("en")},"aria-label":n("language.english"),selected:e==="en",children:n("language.english")})]}),"aria-label":n("language.switcher"),children:n("language.switcher")})};Il.displayName="LanguageSwitcherMenu";const ho=()=>d.jsx("div",{style:{height:"1px",backgroundColor:"var(--color-gray-10)",margin:".5rem 0"}});ho.displayName="MenuSeparator";const ms=({children:e,buttonId:t,isVisible:n,visibleIndex:o=-1,disabled:i=!1})=>{const{t:s}=Oe(),{hideButton:r,showButton:a,resetToDefault:c,visibleButtons:u,reorderButton:l}=hi(),[h,f]=p.useState(!1),[g,y]=p.useState({x:0,y:0}),m=p.useRef(null),w=p.useRef(null);p.useEffect(()=>{const A=w.current;if(!A)return;const I=k=>{k.button===2&&k.stopPropagation()};return A.addEventListener("pointerdown",I,!0),()=>{A.removeEventListener("pointerdown",I,!0)}},[]);const S=p.useCallback(A=>{i||(A.preventDefault(),A.stopPropagation(),y({x:A.clientX,y:A.clientY}),f(!0))},[i]),v=p.useCallback(()=>{f(!1)},[]),E=p.useCallback(()=>{n?r(t):a(t),v()},[n,t,r,a,v]),C=p.useCallback(()=>{o>0&&l(o,o-1,!0),v()},[o,l,v]),D=p.useCallback(()=>{o>=0&&o<u.length-1&&l(o,o+1,!0),v()},[o,u.length,l,v]),P=p.useCallback(()=>{o>0&&l(o,0,!0),v()},[o,l,v]),H=p.useCallback(()=>{o>=0&&o<u.length-1&&l(o,u.length-1,!0),v()},[o,u.length,l,v]),B=p.useCallback(()=>{c(),v()},[c,v]);p.useEffect(()=>{if(!h)return;const A=k=>{m.current&&!m.current.contains(k.target)&&v()},I=k=>{k.key==="Escape"&&v()};return document.addEventListener("mousedown",A),document.addEventListener("keydown",I),()=>{document.removeEventListener("mousedown",A),document.removeEventListener("keydown",I)}},[h,v]),p.useEffect(()=>{if(!h||!m.current)return;const I=m.current.getBoundingClientRect(),k=window.innerWidth,T=window.innerHeight;let M=g.x,O=g.y;g.x+I.width>k&&(M=k-I.width-8),g.y+I.height>T&&(O=T-I.height-8),(M!==g.x||O!==g.y)&&y({x:M,y:O})},[h,g]);const j=n&&o>0,U=n&&o>=0&&o<u.length-1;return d.jsxs(d.Fragment,{children:[d.jsx("div",{ref:w,onContextMenu:S,children:e}),h&&nc.createPortal(d.jsx("div",{ref:m,className:"toolbar-context-menu",style:{position:"fixed",left:g.x,top:g.y,zIndex:ht.DROPDOWN_PORTAL},children:d.jsxs(Et,{children:[n&&d.jsxs(d.Fragment,{children:[d.jsx(ce,{onSelect:C,disabled:!j,children:s("toolbar.moveUp")}),d.jsx(ce,{onSelect:D,disabled:!U,children:s("toolbar.moveDown")}),d.jsx(ce,{onSelect:P,disabled:!j,children:s("toolbar.moveToTop")}),d.jsx(ce,{onSelect:H,disabled:!U,children:s("toolbar.moveToBottom")}),d.jsx(ho,{})]}),d.jsx(ce,{onSelect:E,children:s(n?"toolbar.rightClickToHide":"toolbar.doubleClickToShow")}),d.jsx(ho,{}),d.jsx(ce,{onSelect:B,children:s("toolbar.resetToDefault")})]})}),document.body)]})},Zm=({embedded:e=!1,iconMode:t=!1,onOpenBackupRestore:n,onOpenCloudSync:o})=>{const i=Ye(),{t:s}=Oe(),{isButtonVisible:r,visibleButtons:a}=hi(),c=F.getBoardContainer(i),[u,l]=p.useState(!1),h=i.history.undos.length<=0,f=i.history.redos.length<=0,g=r("undo"),y=r("redo"),m=a.findIndex(v=>v.id==="undo"),w=a.findIndex(v=>v.id==="redo"),S=d.jsxs(kt.Row,{gap:1,children:[d.jsxs(Mt,{sideOffset:12,open:u,onOpenChange:v=>{l(v)},placement:e?"right-start":"bottom-start",children:[d.jsx(Rt,{asChild:!0,children:d.jsx(je,{type:"icon",visible:!0,selected:u,icon:d.jsx(tc,{}),tooltip:u?void 0:s("general.menu"),tooltipPlacement:e?"right":"bottom","aria-label":s("general.menu"),"data-track":"toolbar_click_menu",onPointerDown:()=>{l(!u)}})}),d.jsx(Dt,{container:c,style:{zIndex:ht.POPOVER_APP},children:d.jsxs(Et,{onSelect:()=>{l(!1)},onClose:()=>{l(!1)},children:[d.jsx(yl,{}),d.jsx(wl,{}),d.jsx(vl,{}),d.jsx(Sl,{}),d.jsx(Cl,{}),d.jsx(ho,{}),d.jsx(Il,{}),d.jsx(xl,{onOpenBackupRestore:()=>{l(!1),n==null||n()}}),d.jsx(El,{}),d.jsx(kl,{onOpenCloudSync:()=>{l(!1),o==null||o()}}),d.jsx(bl,{}),d.jsx(ho,{}),d.jsx(_l,{}),d.jsx(Pl,{}),d.jsx(Tl,{})]})})]},0),g&&d.jsx(ms,{buttonId:"undo",isVisible:!0,visibleIndex:m,children:d.jsx(je,{type:"icon",icon:d.jsx(oc,{}),visible:!0,tooltip:s("general.undo"),tooltipPlacement:e?"right":"bottom","aria-label":s("general.undo"),"data-track":"toolbar_click_undo",onPointerUp:()=>{i.undo()},disabled:h},1)}),y&&d.jsx(ms,{buttonId:"redo",isVisible:!0,visibleIndex:w,children:d.jsx(je,{type:"icon",icon:d.jsx(ic,{}),visible:!0,tooltip:s("general.redo"),tooltipPlacement:e?"right":"bottom","aria-label":s("general.redo"),"data-track":"toolbar_click_redo",onPointerUp:()=>{i.redo()},disabled:f},2)})]});return e?d.jsxs("div",{className:me("app-toolbar",{"app-toolbar--embedded":e,"app-toolbar--icon-only":t}),children:[S,d.jsx(je,{type:"icon",icon:d.jsx(Od,{}),visible:!0,tooltip:s("menu.github"),tooltipPlacement:"right","aria-label":s("menu.github"),"data-track":"toolbar_click_github",onPointerUp:()=>{window.open("https://github.com/ljquan/aitu","_blank")}})]}):d.jsx(an,{padding:1,className:me("app-toolbar",En,{"app-toolbar--embedded":e,"app-toolbar--icon-only":t}),children:S})};function Jm(e,t){return!e||e===Gn.solid?null:e===Gn.dashed?`${t*3},${t*2}`:e===Gn.dotted?`${t},${t*2}`:null}function Ut(e){return e!==void 0&&!isNaN(e[0])&&!isNaN(e[1])&&isFinite(e[0])&&isFinite(e[1])}class Qm extends ci{constructor(t){super(t)}canDraw(t){return t.anchors&&t.anchors.length>0}draw(t){const n=yo();n.classList.add("pen-path");const o=Hc(t),i=t.cornerRadius||0,s=$c(o,t.closed,i),r=t.strokeWidth||2,a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("d",s),a.setAttribute("fill",Nd(t.fill)),a.setAttribute("stroke",t.strokeColor||"#000000"),a.setAttribute("stroke-width",String(r)),a.setAttribute("stroke-linecap","round"),a.setAttribute("stroke-linejoin","round");const c=Jm(t.strokeStyle,r);return c&&a.setAttribute("stroke-dasharray",c),n.appendChild(a),n}}function ew(e,t){const n=e.point,o=Fd;if(e.type==="corner"){const i=document.createElementNS("http://www.w3.org/2000/svg","rect");return i.setAttribute("x",String(n[0]-o/2)),i.setAttribute("y",String(n[1]-o/2)),i.setAttribute("width",String(o)),i.setAttribute("height",String(o)),i.setAttribute("fill",t?"#1890ff":"#ffffff"),i.setAttribute("stroke","#1890ff"),i.setAttribute("stroke-width","1.5"),i.classList.add("pen-anchor"),i}else{const i=document.createElementNS("http://www.w3.org/2000/svg","circle");return i.setAttribute("cx",String(n[0])),i.setAttribute("cy",String(n[1])),i.setAttribute("r",String(o/2)),i.setAttribute("fill",t?"#1890ff":"#ffffff"),i.setAttribute("stroke","#1890ff"),i.setAttribute("stroke-width","1.5"),i.classList.add("pen-anchor"),i}}function aa(e){const t=document.createElementNS("http://www.w3.org/2000/svg","circle");return t.setAttribute("cx",String(e[0])),t.setAttribute("cy",String(e[1])),t.setAttribute("r",String(zd/2)),t.setAttribute("fill","#ffffff"),t.setAttribute("stroke","#1890ff"),t.setAttribute("stroke-width","1"),t.classList.add("pen-handle"),t}function ca(e,t){const n=document.createElementNS("http://www.w3.org/2000/svg","line");return n.setAttribute("x1",String(e[0])),n.setAttribute("y1",String(e[1])),n.setAttribute("x2",String(t[0])),n.setAttribute("y2",String(t[1])),n.setAttribute("stroke","#1890ff"),n.setAttribute("stroke-width","1"),n.setAttribute("stroke-dasharray","3,3"),n.classList.add("pen-handle-line"),n}function tw(e,t,n){const o="#ff4d4f";if(n.vertical&&n.verticalRefPoint){const s=n.verticalRefPoint,r=document.createElementNS("http://www.w3.org/2000/svg","line");r.setAttribute("x1",String(t[0])),r.setAttribute("y1",String(Math.min(t[1],s[1])-50)),r.setAttribute("x2",String(t[0])),r.setAttribute("y2",String(Math.max(t[1],s[1])+50)),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(1)),r.setAttribute("stroke-dasharray","4,4"),r.classList.add("pen-alignment-guide"),e.appendChild(r);const a=document.createElementNS("http://www.w3.org/2000/svg","circle");a.setAttribute("cx",String(s[0])),a.setAttribute("cy",String(s[1])),a.setAttribute("r","3"),a.setAttribute("fill",o),a.setAttribute("opacity","0.6"),a.classList.add("pen-alignment-marker"),e.appendChild(a)}if(n.horizontal&&n.horizontalRefPoint){const s=n.horizontalRefPoint,r=document.createElementNS("http://www.w3.org/2000/svg","line");if(r.setAttribute("x1",String(Math.min(t[0],s[0])-50)),r.setAttribute("y1",String(t[1])),r.setAttribute("x2",String(Math.max(t[0],s[0])+50)),r.setAttribute("y2",String(t[1])),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(1)),r.setAttribute("stroke-dasharray","4,4"),r.classList.add("pen-alignment-guide"),e.appendChild(r),!n.verticalRefPoint||n.horizontalRefPoint[0]!==n.verticalRefPoint[0]||n.horizontalRefPoint[1]!==n.verticalRefPoint[1]){const a=document.createElementNS("http://www.w3.org/2000/svg","circle");a.setAttribute("cx",String(s[0])),a.setAttribute("cy",String(s[1])),a.setAttribute("r","3"),a.setAttribute("fill",o),a.setAttribute("opacity","0.6"),a.classList.add("pen-alignment-marker"),e.appendChild(a)}}}function nw(e,t,n="#1890ff",o=2,i){const s=yo();if(s.classList.add("pen-preview"),e.length===0)return s;if(t&&Ut(t)&&i&&(i.horizontal||i.vertical)&&tw(s,t,i),e.length>0){const r=$c(e,!1),a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("d",r),a.setAttribute("fill","none"),a.setAttribute("stroke",n),a.setAttribute("stroke-width",String(o)),a.setAttribute("stroke-linecap","round"),a.setAttribute("stroke-linejoin","round"),s.appendChild(a)}if(t&&Ut(t)&&e.length>0){const r=e[e.length-1];if(Ut(r.point)){const a=document.createElementNS("http://www.w3.org/2000/svg","line"),c=r.handleOut&&Ut(r.handleOut)?r.handleOut:r.point;a.setAttribute("x1",String(c[0])),a.setAttribute("y1",String(c[1])),a.setAttribute("x2",String(t[0])),a.setAttribute("y2",String(t[1])),a.setAttribute("stroke",n),a.setAttribute("stroke-width","1"),a.setAttribute("stroke-dasharray","5,5"),a.setAttribute("opacity","0.6"),s.appendChild(a)}}for(let r=0;r<e.length;r++){const a=e[r];if(!Ut(a.point))continue;if(a.handleIn&&Ut(a.handleIn)){const u=ca(a.point,a.handleIn);s.appendChild(u);const l=aa(a.handleIn);s.appendChild(l)}if(a.handleOut&&Ut(a.handleOut)){const u=ca(a.point,a.handleOut);s.appendChild(u);const l=aa(a.handleOut);s.appendChild(l)}const c=ew(a,r===e.length-1);s.appendChild(c)}return s}const ow=e=>F.getBoardContainer(e).classList.contains("viewport-moving"),mi=(e,t)=>ow(e)||Bd(t),iw=3,sw=3,la=8,ws=new WeakMap;function jt(e){let t=ws.get(e);return t||(t={isCreating:!1,anchors:[],isDraggingHandle:!1,dragStartPoint:null,currentPoint:null,previewG:null,alignment:{horizontal:!1,vertical:!1,horizontalRefPoint:null,verticalRefPoint:null,referencePoint:null}},ws.set(e,t)),t}function ua(e,t,n=!1){const o={horizontal:!1,vertical:!1,horizontalRefPoint:null,verticalRefPoint:null,referencePoint:null},i=[...e],s=n&&t.length>1?t.slice(0,-1):t;if(s.length===0)return{snappedPoint:e,alignment:o};let r=la,a=null,c=null,u=la,l=null,h=null;for(const f of s){const g=Math.abs(e[0]-f.point[0]),y=Math.abs(e[1]-f.point[1]);g<r&&(r=g,a=f.point[0],c=f.point),y<u&&(u=y,l=f.point[1],h=f.point)}return a!==null&&(i[0]=a,o.vertical=!0,o.verticalRefPoint=c),l!==null&&(i[1]=l,o.horizontal=!0,o.horizontalRefPoint=h),o.referencePoint=o.verticalRefPoint||o.horizontalRefPoint,{snappedPoint:i,alignment:o}}function xn(e){const t=jt(e);t.previewG&&t.previewG.remove(),Al(e),t.isCreating=!1,t.anchors=[],t.isDraggingHandle=!1,t.dragStartPoint=null,t.currentPoint=null,t.previewG=null,t.alignment={horizontal:!1,vertical:!1,horizontalRefPoint:null,verticalRefPoint:null,referencePoint:null}}function Al(e){F.getElementHost(e).querySelectorAll(".pen-preview").forEach(o=>o.remove())}function jn(e){const t=jt(e),n=F.getElementHost(e);t.previewG&&t.previewG.remove(),t.previewG=nw(t.anchors,t.currentPoint,"#1890ff",2,t.alignment),n.appendChild(t.previewG)}function Zo(e,t=!1){const n=jt(e),o=[...n.anchors];if(n.previewG&&(n.previewG.remove(),n.previewG=null),Al(e),o.length>=2){const i=Sf(e,o,t);n.isCreating=!1,n.anchors=[],n.isDraggingHandle=!1,n.dragStartPoint=null,n.currentPoint=null,Se.insertNode(e,i,[e.children.length]),t?(At(e),Pn(e,i)):At(e)}else xn(e)}function Vn(e){return F.getPointer(e)===zt.pen}function rw(e){const t=jt(e);t.isCreating&&(Vn(e)||(t.anchors.length>=2?Zo(e,!1):xn(e)))}const aw=e=>{const{pointerDown:t,pointerMove:n,pointerUp:o,globalPointerUp:i,keyDown:s,globalKeyDown:r}=e;let a=!1;const c=l=>l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLElement&&l.isContentEditable,u=l=>{if(l.defaultPrevented||!Vn(e)||c(l.target))return!1;const h=jt(e);return h.isCreating?l.key==="Enter"?(Zo(e,!1),l.preventDefault(),!0):l.key==="Escape"?(xn(e),l.preventDefault(),!0):ve.isHotkey(["mod+z"],{byKey:!0})(l)||l.key==="Backspace"||l.key==="Delete"?(h.anchors.length>0&&(h.anchors.pop(),jn(e)),h.anchors.length===0&&xn(e),l.preventDefault(),!0):!1:!1};return e.pointerDown=l=>{if(mi(e,l)){a=!0,t(l);return}if(rw(e),!Vn(e)){t(l);return}const h=jt(e);let f=Xe(e,Ze(e,l.x,l.y));if(h.isCreating&&h.anchors.length>=sw){const w={anchors:h.anchors};if(wf(w,f)){Zo(e,!0);return}}if(h.anchors.length>0){const{snappedPoint:w}=ua(f,h.anchors,!1);f=w}h.isCreating=!0,h.isDraggingHandle=!0,h.dragStartPoint=f;const y=Vc(e).defaultAnchorType,m={point:f,type:y};h.anchors.push(m),h.alignment={horizontal:!1,vertical:!1,horizontalRefPoint:null,verticalRefPoint:null,referencePoint:null},jn(e)},e.pointerMove=l=>{if(a){n(l);return}if(!Vn(e)){n(l);return}const h=jt(e);let f=Xe(e,Ze(e,l.x,l.y));const g=h.isDraggingHandle,{snappedPoint:y,alignment:m}=ua(f,h.anchors,g);if(h.currentPoint=y,h.alignment=m,h.isDraggingHandle&&h.dragStartPoint&&h.anchors.length>0&&yf(h.dragStartPoint,f)>iw){const S=h.anchors.length-1,v=h.anchors[S];if(v.type!=="corner"){if(v.type==="smooth"||v.type==="symmetric"){const E=vf(v.point,f);h.anchors[S]={...v,handleIn:E.handleIn,handleOut:E.handleOut}}}}h.isCreating&&Ts(e,"pen-preview",()=>{jn(e)}),n(l)},e.pointerUp=l=>{if(a){a=!1,o(l);return}if(!Vn(e)){o(l);return}const h=jt(e);h.isDraggingHandle=!1,h.dragStartPoint=null,jn(e),o(l)},e.globalPointerUp=l=>{a=!1,i(l)},e.globalKeyDown=l=>{u(l)||r(l)},e.keyDown=l=>{u(l)||s(l)},e};function nn(e){const t=ws.get(e);t!=null&&t.isCreating&&(t.anchors.length>=2?Zo(e,!1):xn(e))}const Ks=[{icon:d.jsx(ui,{}),pointer:ie.feltTipPen,titleKey:"toolbar.pen"},{icon:d.jsx(Hd,{}),pointer:zt.pen,titleKey:"toolbar.vectorPen"},{icon:d.jsx($d,{}),pointer:ie.mask,titleKey:"toolbar.maskBrush"},{icon:d.jsx(Vd,{}),pointer:ie.eraser,titleKey:"toolbar.eraser"},{icon:d.jsx(Wd,{}),pointer:ie.laserPointer,titleKey:"toolbar.laserPointer"}],cw=sc(Ks,5),Ml=({onPointerUp:e})=>{const{t}=Oe(),n=Ye();return d.jsx(an,{padding:1,children:d.jsx(kt.Row,{gap:1,align:"center",children:d.jsx(kt.Row,{gap:1,children:cw.map((o,i)=>o.map((s,r)=>d.jsx(je,{className:me({fillable:!1}),selected:n.pointer===s.pointer,type:"icon",size:"small",visible:!0,icon:s.icon,tooltip:t(s.titleKey),"aria-label":t(s.titleKey),"aria-keyshortcuts":s.pointer===ie.mask?"Shift+M":void 0,keyBindingLabel:s.pointer===ie.mask?"M":void 0,onPointerDown:()=>{s.pointer!==zt.pen&&nn(n),Re(n,He.dnd),ee.updatePointerType(n,s.pointer)},onPointerUp:()=>{Re(n,He.drawing),e(s.pointer)}},`${i}-${r}`)))})})})},lw=[{icon:d.jsx(Ud,{}),title:"Rectangle — R",pointer:ge.rectangle},{icon:d.jsx(Gd,{}),title:"Ellipse — O",pointer:ge.ellipse},{icon:d.jsx(Kd,{}),title:"Triangle",pointer:ge.triangle},{icon:d.jsx(qd,{}),title:"Terminal",pointer:rc.terminal},{icon:d.jsx(Yd,{}),title:"Diamond",pointer:ge.diamond},{icon:d.jsx(Xd,{}),title:"Parallelogram",pointer:ge.parallelogram},{icon:d.jsx(Zd,{}),title:"RoundRectangle",pointer:ge.roundRectangle}],uw=sc(lw,5),Rl=({onPointerUp:e})=>{const t=Ye();return d.jsx(an,{padding:1,children:d.jsx(kt.Col,{gap:1,children:uw.map((n,o)=>d.jsx(kt.Row,{gap:1,children:n.map((i,s)=>d.jsx(je,{className:me({fillable:!1}),type:"icon",size:"small",visible:!0,icon:i.icon,tooltip:i.title,"aria-label":i.title,onPointerDown:()=>{nn(t),Re(t,He.dnd),ee.updatePointerType(t,i.pointer)},onPointerUp:()=>{Re(t,He.drawing),e(i.pointer)}},s))},o))})})},dw=[{icon:d.jsx(Jd,{}),title:"Straight Arrow Line",pointer:xt.straight},{icon:d.jsx(Qd,{}),title:"Elbow Arrow Line",pointer:xt.elbow},{icon:d.jsx(eh,{}),title:"Curve Arrow Line",pointer:xt.curve}],Dl=({onPointerUp:e})=>{const t=Ye();return d.jsx(an,{padding:1,children:d.jsx(kt.Row,{gap:1,children:dw.map((n,o)=>d.jsx(je,{className:me({fillable:!1}),type:"icon",size:"small",visible:!0,icon:n.icon,tooltip:n.title,"aria-label":n.title,onPointerDown:()=>{nn(t),Re(t,He.drawing),ee.updatePointerType(t,n.pointer)},onPointerUp:()=>{e(n.pointer)}},o))})})},Ll=[{value:Kt.default,labelKey:"theme.default"},{value:Kt.colorful,labelKey:"theme.colorful"},{value:Kt.soft,labelKey:"theme.soft"},{value:Kt.retro,labelKey:"theme.retro"},{value:Kt.dark,labelKey:"theme.dark"},{value:Kt.starry,labelKey:"theme.starry"}],jl=d.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{width:"1rem",height:"1rem"},children:d.jsx("polyline",{points:"20 6 9 17 4 12"})}),Oo=e=>e===Le.hand||e===Le.selection||e===lo,Ol=d.jsx("span",{style:{width:"1rem",display:"inline-block"}}),da={hand:{icon:d.jsx(Sc,{}),titleKey:"toolbar.hand",pointer:Le.hand},selection:{icon:d.jsx(vc,{}),titleKey:"toolbar.selection",pointer:Le.selection},lasso:{icon:d.jsx(yc,{}),titleKey:"toolbar.lasso",pointer:lo},mind:{icon:d.jsx(Xi,{}),titleKey:"toolbar.mind",pointer:io.mind},text:{icon:d.jsx(wc,{}),titleKey:"toolbar.text",pointer:ge.text},freehand:{icon:d.jsx(ui,{}),titleKey:"toolbar.pen",pointer:ie.feltTipPen,hasPopup:!0,popupKey:"freehand"},arrow:{icon:d.jsx(mc,{}),titleKey:"toolbar.arrow",pointer:xt.straight,hasPopup:!0,popupKey:"arrow"},shape:{icon:d.jsx(pc,{}),titleKey:"toolbar.shape",pointer:ge.rectangle,hasPopup:!0,popupKey:"shape"},image:{icon:d.jsx(gc,{size:24}),titleKey:"toolbar.image"},"media-library":{icon:d.jsx(fc,{size:24}),titleKey:"toolbar.mediaLibrary"},"ai-image":{icon:d.jsx(Is,{}),titleKey:"toolbar.aiImage"},"ai-video":{icon:d.jsx(Cs,{}),titleKey:"toolbar.aiVideo"},theme:{icon:d.jsx(hc,{}),titleKey:"toolbar.theme",hasPopup:!0,popupKey:"theme"},"mermaid-to-drawnix":{icon:d.jsx(dc,{}),titleKey:"extraTools.mermaidToDrawnix"},"markdown-to-drawnix":{icon:d.jsx(uc,{}),titleKey:"extraTools.markdownToDrawnix"},undo:{icon:d.jsx(oc,{}),titleKey:"general.undo"},redo:{icon:d.jsx(ic,{}),titleKey:"general.redo"}},hw=({embedded:e=!1})=>{const{t}=Oe(),n=Ye(),o=F.getBoardContainer(n),{hiddenButtons:i,showButton:s}=hi(),[r,a]=p.useState(!1),[c,u]=p.useState(!1),l=p.useRef(null),h=p.useRef(null),f=p.useCallback(()=>{l.current&&(clearTimeout(l.current),l.current=null),h.current&&(clearTimeout(h.current),h.current=null)},[]),g=p.useCallback(()=>"ontouchstart"in window||navigator.maxTouchPoints>0,[]),y=p.useCallback(()=>{g()||(f(),u(!0),l.current=setTimeout(()=>{a(!0)},200))},[f,g]),m=p.useCallback(()=>{g()||(l.current&&(clearTimeout(l.current),l.current=null),h.current=setTimeout(()=>{u(!1),a(!1)},150))},[g]),w=p.useCallback(()=>{g()&&(a(E=>!E),u(!1))},[g]),S=p.useCallback(()=>{f(),u(!0)},[f]),v=p.useCallback(()=>{h.current=setTimeout(()=>{u(!1),a(!1)},150)},[]);return d.jsxs(Mt,{open:r,onOpenChange:E=>{!E&&(g()||!c)&&a(!1)},placement:e?"right-start":"bottom",sideOffset:12,children:[d.jsx(Rt,{asChild:!0,children:d.jsx("div",{onMouseEnter:y,onMouseLeave:m,onClick:w,children:d.jsx(je,{type:"icon",icon:d.jsx(th,{}),tooltip:r?void 0:t("toolbar.more"),tooltipPlacement:e?"right":"bottom","aria-label":t("toolbar.more"),selected:r,visible:!0,"data-testid":"toolbar-more","data-track":"toolbar_click_more"})})}),d.jsx(Dt,{container:o,style:{zIndex:ht.POPOVER},onMouseEnter:S,onMouseLeave:v,children:d.jsx(fw,{hiddenButtons:i,showButton:s})})]})},fw=({hiddenButtons:e,showButton:t})=>{const{t:n}=Oe(),o=Ye(),i=F.getBoardContainer(o),{openDialog:s}=Ht(),r=ac(),[a,c]=p.useState(null),[u,l]=p.useState(null),h=p.useRef({}),[f,g]=p.useState(null),y=p.useRef(null),[m,w]=p.useState(ie.feltTipPen),S=p.useCallback(()=>{c(null),l(null),Object.values(h.current).forEach(R=>{R&&clearTimeout(R)})},[]),v=p.useCallback(R=>{if(Object.values(h.current).forEach(L=>{L&&clearTimeout(L)}),u===R){l(null);return}a===R&&!u?c(null):(l(null),c(R))},[a,u]),E=p.useCallback(R=>{a&&!u||(h.current[R]&&clearTimeout(h.current[R]),Object.entries(h.current).forEach(([L,Y])=>{L!==R&&Y&&(clearTimeout(Y),h.current[L]=null)}),u&&u!==R?(c(R),l(R)):a||(h.current[R]=setTimeout(()=>{c(R),l(R)},300)))},[u,a]),C=p.useCallback(R=>{h.current[R]&&(clearTimeout(h.current[R]),h.current[R]=null),u===R&&(h.current[R]=setTimeout(()=>{c(null),l(null)},400))},[u]),D=p.useCallback(R=>{h.current[R]&&(clearTimeout(h.current[R]),h.current[R]=null)},[]),P=p.useCallback(R=>{u===R&&(c(null),l(null))},[u]),H=p.useCallback(R=>{nn(o),R===ge.text?Re(o,null):Re(o,He.dnd),ee.updatePointerType(o,R),r(R)},[o,r]),B=p.useCallback(R=>{R!==ge.text&&Re(o,He.drawing)},[o]),j=p.useCallback(R=>{const L=da[R];if(L){if(L.hasPopup&&L.popupKey){v(L.popupKey);return}switch(S(),nn(o),L.pointer&&(Oo(L.pointer)?(ee.updatePointerType(o,L.pointer),r(L.pointer)):(H(L.pointer),B(L.pointer))),R){case"image":js(o);break;case"ai-image":s(dt.aiImageGeneration);break;case"ai-video":s(dt.aiVideoGeneration);break;case"mermaid-to-drawnix":s(dt.mermaidToDrawnix);break;case"markdown-to-drawnix":s(dt.markdownToDrawnix);break;case"undo":o.undo();break;case"redo":o.redo();break}}},[o,s,H,B,S,r,v]),U=p.useCallback((R,L)=>{R.preventDefault(),R.stopPropagation(),g({buttonId:L,x:R.clientX,y:R.clientY})},[]),A=p.useCallback(()=>{g(null)},[]),I=p.useCallback(()=>{f&&(t(f.buttonId),A())},[f,t,A]);on.useEffect(()=>{if(!f)return;const R=Y=>{y.current&&!y.current.contains(Y.target)&&A()},L=Y=>{Y.key==="Escape"&&A()};return document.addEventListener("mousedown",R),document.addEventListener("keydown",L),()=>{document.removeEventListener("mousedown",R),document.removeEventListener("keydown",L)}},[f,A]);const k=p.useCallback(R=>{switch(R){case"freehand":return d.jsx(Ml,{onPointerUp:L=>{S(),r(L),w(L)}});case"shape":return d.jsx(Rl,{onPointerUp:L=>{S(),r(L)}});case"arrow":return d.jsx(Dl,{onPointerUp:L=>{S(),r(L)}});case"theme":return d.jsx(Et,{children:Ll.map(L=>{const Y=o.theme.themeColorMode===L.value;return d.jsx(ce,{icon:Y?jl:Ol,"data-track":`toolbar_click_theme_${L.value}`,onSelect:()=>{ee.updateThemeColor(o,L.value),S()},"aria-label":n(L.labelKey),selected:Y,children:n(L.labelKey)},L.value)})});default:return null}},[o,S,r,n]),T=p.useMemo(()=>{const R=Ks.find(L=>L.pointer===m);return(R==null?void 0:R.icon)||d.jsx(ui,{})},[m]),[M,O]=p.useState(!1),q=p.useCallback(()=>{var R;return d.jsx("div",{className:"more-tools-panel__zoom-row",onContextMenu:L=>U(L,"zoom"),children:d.jsxs(kt.Row,{gap:1,children:[d.jsx(je,{type:"button",icon:d.jsx(cc,{}),visible:!0,tooltip:n("zoom.out"),tooltipPlacement:"top","aria-label":n("zoom.out"),"data-track":"toolbar_click_zoom_out",onPointerUp:()=>{ee.updateZoom(o,o.viewport.zoom-.1)},className:"zoom-out-button"}),d.jsxs(Mt,{sideOffset:12,open:M,onOpenChange:L=>{O(L)},placement:"right-start",children:[d.jsx(Tt,{content:n("zoom.fit"),showArrow:!1,children:d.jsx(Rt,{asChild:!0,children:d.jsxs("div",{"aria-label":n("zoom.fit"),"data-track":"toolbar_click_zoom_menu",className:`zoom-menu-trigger ${M?"active":""}`,onPointerUp:()=>{O(!M)},children:[Number(((((R=o==null?void 0:o.viewport)==null?void 0:R.zoom)||1)*100).toFixed(0)),"%"]})})}),d.jsx(Dt,{container:i,style:{zIndex:ht.POPOVER+1},children:d.jsxs(Et,{onSelect:()=>{O(!1)},children:[d.jsx(ce,{"data-track":"toolbar_click_zoom_fit",onSelect:()=>{ee.fitViewport(o)},"aria-label":n("zoom.fit"),shortcut:"Cmd+Shift+=",children:n("zoom.fit")}),d.jsx(ce,{"data-track":"toolbar_click_zoom_fit_frame",onSelect:()=>{Os(o)},"aria-label":n("zoom.fitFrame"),children:n("zoom.fitFrame")}),d.jsx(ce,{"data-track":"toolbar_click_zoom_100",onSelect:()=>{ee.updateZoom(o,1)},"aria-label":n("zoom.100"),shortcut:"Cmd+0",children:n("zoom.100")})]})})]}),d.jsx(je,{type:"button",icon:d.jsx(lc,{}),visible:!0,tooltip:n("zoom.in"),tooltipPlacement:"top","aria-label":n("zoom.in"),"data-track":"toolbar_click_zoom_in",onPointerUp:()=>{ee.updateZoom(o,o.viewport.zoom+.1)},className:"zoom-in-button"})]})},"zoom")},[o,i,U,n,M]),le=p.useCallback(R=>{var Ce,ze,W,Q;if(R==="zoom")return q();const L=da[R];if(!L)return null;const Y=n(L.titleKey),he=R==="freehand"?T:L.icon,be=R==="undo"&&(((ze=(Ce=o.history)==null?void 0:Ce.undos)==null?void 0:ze.length)??0)<=0,ue=R==="redo"&&(((Q=(W=o.history)==null?void 0:W.redos)==null?void 0:Q.length)??0)<=0,_e=be||ue;if(L.hasPopup&&L.popupKey){const pe=L.popupKey;return d.jsx("div",{className:"more-tools-panel__item",onContextMenu:V=>U(V,R),children:d.jsxs(Mt,{open:a===pe,sideOffset:2,onOpenChange:V=>{V||S()},placement:"right-start",children:[d.jsx(Rt,{asChild:!0,children:d.jsx("div",{onMouseEnter:()=>E(pe),onMouseLeave:()=>C(pe),children:d.jsx(je,{type:"icon",icon:he,tooltip:Y,tooltipPlacement:"left","aria-label":Y,visible:!0,selected:a===pe,"data-track":`toolbar_click_${R}`,onPointerUp:()=>j(R)})})}),d.jsx(Dt,{container:i,style:{zIndex:ht.POPOVER+1},onMouseEnter:()=>D(pe),onMouseLeave:()=>P(pe),children:k(pe)})]})},R)}return d.jsx("div",{className:"more-tools-panel__item",onContextMenu:pe=>U(pe,R),children:d.jsx(je,{type:"icon",icon:he,tooltip:Y,tooltipPlacement:"right","aria-label":Y,visible:!0,selected:!1,disabled:_e,"data-track":`toolbar_click_${R}`,onPointerUp:()=>j(R)})},R)},[n,o,i,a,T,j,U,E,C,D,P,k,S,q]);return e.length===0?d.jsxs("div",{className:"more-tools-panel",children:[d.jsx("div",{className:"more-tools-panel__header",children:d.jsx("span",{className:"more-tools-panel__title",children:n("toolbar.moreTools")})}),d.jsx("div",{className:"more-tools-panel__empty",children:d.jsx("span",{className:"more-tools-panel__empty-text",children:n("toolbar.allToolsVisible")})})]}):d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"more-tools-panel",children:[d.jsx("div",{className:"more-tools-panel__header",children:d.jsx("span",{className:"more-tools-panel__title",children:n("toolbar.moreTools")})}),d.jsx("div",{className:"more-tools-panel__content",children:e.map(R=>le(R.id))}),d.jsx("div",{className:"more-tools-panel__footer",children:d.jsx("span",{className:"more-tools-panel__hint",children:n("toolbar.rightClickToAdd")})})]}),f&&nc.createPortal(d.jsx("div",{ref:y,className:"toolbar-context-menu",style:{position:"fixed",left:f.x,top:f.y,zIndex:ht.DROPDOWN_PORTAL},children:d.jsx(Et,{children:d.jsx(ce,{onSelect:I,children:n("toolbar.addToToolbar")})})}),document.body)]})},gw=p.lazy(()=>re(()=>import("./ai-chat-B-XdoWBQ.js").then(e=>e.sZ),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.MediaLibraryModal}))),pw=p.lazy(()=>re(()=>import("./tool-windows-BnDZa9FH.js").then(e=>e.b3),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.MinimizedToolsBar})));var Nl=(e=>(e.shape="shape",e.arrow="arrow",e.freehand="freehand",e.theme="theme",e))(Nl||{});const ha=[{icon:d.jsx(Sc,{}),pointer:Le.hand,titleKey:"toolbar.hand",visibilityKey:"hand"},{icon:d.jsx(vc,{}),pointer:Le.selection,titleKey:"toolbar.selection",visibilityKey:"selection"},{icon:d.jsx(yc,{}),pointer:lo,titleKey:"toolbar.lasso",visibilityKey:"lasso"},{icon:d.jsx(Xi,{}),pointer:io.mind,titleKey:"toolbar.mind",visibilityKey:"mind"},{icon:d.jsx(wc,{}),pointer:ge.text,titleKey:"toolbar.text",visibilityKey:"text"},{icon:d.jsx(gc,{size:24}),titleKey:"toolbar.image",key:"image",visibilityKey:"image"},{icon:d.jsx(fc,{size:24}),titleKey:"toolbar.mediaLibrary",key:"media-library",visibilityKey:"media-library"},{icon:d.jsx(Is,{}),titleKey:"toolbar.aiImage",key:"ai-image",visibilityKey:"ai-image"},{icon:d.jsx(Cs,{}),titleKey:"toolbar.aiVideo",key:"ai-video",visibilityKey:"ai-video"},{icon:d.jsx(Xi,{}),pointer:io.mind,titleKey:"toolbar.mind",visibilityKey:"mind"},{icon:d.jsx(ui,{}),pointer:ie.feltTipPen,titleKey:"toolbar.pen",key:"freehand",visibilityKey:"freehand"},{icon:d.jsx(mc,{}),titleKey:"toolbar.arrow",key:"arrow",pointer:xt.straight,visibilityKey:"arrow"},{icon:d.jsx(pc,{}),titleKey:"toolbar.shape",key:"shape",pointer:ge.rectangle,visibilityKey:"shape"},{icon:d.jsx(hc,{}),titleKey:"toolbar.theme",key:"theme",visibilityKey:"theme"},{icon:d.jsx(dc,{}),titleKey:"extraTools.mermaidToDrawnix",key:"mermaid-to-drawnix",visibilityKey:"mermaid-to-drawnix"},{icon:d.jsx(uc,{}),titleKey:"extraTools.markdownToDrawnix",key:"markdown-to-drawnix",visibilityKey:"markdown-to-drawnix"}],mw=e=>Object.keys(xt).includes(e.pointer),ww=e=>Object.keys(ge).includes(e.pointer)||Object.keys(rc).includes(e.pointer),yw=({embedded:e=!1,iconMode:t=!1,onOpenMediaLibrary:n,minimizedToolsBarEnabled:o=!1,onEnableToolWindows:i})=>{const s=Ye(),{appState:r,openDialog:a}=Ht(),{t:c}=Oe(),u=ac(),l=F.getBoardContainer(s),{visibleButtons:h,loading:f,reorderButton:g}=hi(),{getDragProps:y}=xf({items:h,getId:x=>x.id,onReorder:(x,_)=>{g(x,_,!0)},enabled:e}),[m,w]=p.useState({freehand:!1,arrow:!1,shape:!1,theme:!1}),[S,v]=p.useState(null),E=p.useRef({freehand:null,arrow:null,shape:null,theme:null}),[C,D]=p.useState(ha.find(x=>x.key==="freehand")),[P,H]=p.useState(!1),B=p.useCallback(async x=>{try{x.type===Yt.IMAGE?await nh(s,x.url):x.type===Yt.VIDEO?await Ja(s,x.url):x.type===Yt.AUDIO&&await Qa(s,x.url,{title:x.name,duration:x.duration,previewImageUrl:x.thumbnail,prompt:x.prompt,mv:x.modelName,clipId:x.clipId,providerTaskId:x.providerTaskId}),Ne.success("素材已插入到画板")}catch(_){console.error("Failed to insert asset:",_),Ne.error("插入素材失败")}},[s]),j=p.useCallback(async x=>{var z,G;if(x.length===0)return;oh("[CanvasInsertion][Toolbar] batch assets begin",{source:"creation-toolbar",strategy:"shared-batch-layout",assetsCount:x.length,assetTypes:x.map($=>$.type),zoom:((z=s==null?void 0:s.viewport)==null?void 0:z.zoom)||1});const _=await kf({items:x.map($=>$.type===Yt.IMAGE?{type:"image",content:$.url}:$.type===Yt.VIDEO?{type:"video",content:$.url}:{type:"audio",content:$.url,metadata:{title:$.name,duration:$.duration,previewImageUrl:$.thumbnail,prompt:$.prompt,mv:$.modelName,clipId:$.clipId,providerTaskId:$.providerTaskId}})});if(_.success){const $=((G=_.data)==null?void 0:G.insertedCount)??x.length;Ne.success(`已成功插入 ${$} 个素材到画板`)}else Ne.error(_.error||"插入素材失败")},[s]),U=p.useCallback(()=>{if(n){n({mode:$o.SELECT,onSelect:B,onSelectMultiple:j,selectButtonText:"插入",batchSelectButtonText:"批量插入画布"});return}H(!0)},[B,j,n]),A=p.useCallback(()=>{H(!1)},[]),I=()=>{w({freehand:!1,arrow:!1,shape:!1,theme:!1}),v(null),Object.values(E.current).forEach(x=>{x&&clearTimeout(x)})},k=x=>{v(null),Object.values(E.current).forEach(_=>{_&&clearTimeout(_)}),w({freehand:!1,arrow:!1,shape:!1,theme:!1,[x]:!0})},T=x=>{E.current[x]&&clearTimeout(E.current[x]),Object.entries(E.current).forEach(([_,z])=>{_!==x&&z&&(clearTimeout(z),E.current[_]=null)}),S&&S!==x?(w(_=>({..._,[S]:!1,[x]:!0})),v(x)):m[x]||(E.current[x]=setTimeout(()=>{w(_=>({..._,[x]:!0})),v(x)},300))},M=x=>{E.current[x]&&(clearTimeout(E.current[x]),E.current[x]=null),S===x&&(E.current[x]=setTimeout(()=>{w(_=>({..._,[x]:!1})),v(null)},200))},O=x=>{E.current[x]&&(clearTimeout(E.current[x]),E.current[x]=null)},q=x=>{S===x&&(w(_=>({..._,[x]:!1})),v(null))},le=x=>{nn(s),x===ge.text?(Re(s,null),ee.updatePointerType(s,x),u(x)):(Re(s,He.dnd),ee.updatePointerType(s,x),u(x))},R=x=>{x!==ge.text&&Re(s,He.drawing)},L=()=>Object.values(m).some(x=>x),Y=x=>F.isPointer(s,x.pointer)&&!L(),he=x=>F.isInPointer(x,[ie.feltTipPen,ie.mask,ie.eraser,ie.laserPointer,zt.pen]),be=x=>{I(),nn(s),x.pointer&&!Oo(x.pointer)?R(x.pointer):x.pointer&&Oo(x.pointer)&&(ee.updatePointerType(s,x.pointer),u(x.pointer)),x.key==="image"?js(s):x.key==="media-library"?U():x.key==="ai-image"?a(dt.aiImageGeneration):x.key==="ai-video"?a(dt.aiVideoGeneration):x.key==="mermaid-to-drawnix"?a(dt.mermaidToDrawnix):x.key==="markdown-to-drawnix"&&a(dt.markdownToDrawnix)},ue=(x,_,z)=>{const G=()=>{switch(z){case"freehand":return d.jsx(Ml,{onPointerUp:X=>{I(),u(X),D(Ks.find(oe=>oe.pointer===X))}});case"shape":return d.jsx(Rl,{onPointerUp:X=>{I(),u(X)}});case"arrow":return d.jsx(Dl,{onPointerUp:X=>{I(),u(X)}});case"theme":return d.jsx(Et,{children:Ll.map(X=>{const oe=s.theme.themeColorMode===X.value;return d.jsx(ce,{icon:oe?jl:Ol,"data-track":`toolbar_click_theme_${X.value}`,onSelect:()=>{ee.updateThemeColor(s,X.value),I()},"aria-label":c(X.labelKey),selected:oe,children:c(X.labelKey)},X.value)})})}},$=()=>{const X=m[z],oe=Object.entries(m).some(([Fe,Ve])=>Fe!==z&&Ve);switch(z){case"freehand":return X||he(s)&&!oe;case"shape":return X||ww(s)&&!F.isPointer(s,ge.text);case"arrow":return X||mw(s);default:return X}},ne=z==="freehand"?C.icon:x.icon,xe=z==="freehand"?C.titleKey?c(C.titleKey):"Freehand":x.titleKey?c(x.titleKey):"";return d.jsxs(Mt,{open:m[z],sideOffset:12,onOpenChange:X=>{X||I()},placement:e?"right-start":"bottom",children:[d.jsx(Rt,{asChild:!0,children:d.jsx("div",{onMouseEnter:()=>T(z),onMouseLeave:()=>M(z),children:d.jsx(je,{type:"icon",visible:!0,selected:$(),icon:ne,tooltip:xe,"aria-label":xe,"data-track":`toolbar_click_${z}`,onPointerDown:()=>{k(z),z==="freehand"&&C.pointer&&le(C.pointer)},onPointerUp:()=>{z==="freehand"&&R()}})})}),d.jsx(Dt,{container:l,style:{zIndex:ht.POPOVER},onMouseEnter:()=>O(z),onMouseLeave:()=>q(z),children:G()})]},_)},_e=(x,_)=>d.jsx(je,{type:"radio",icon:x.icon,checked:Y(x),tooltip:x.titleKey?c(x.titleKey):"",tooltipPlacement:e?"right":"bottom","aria-label":x.titleKey?c(x.titleKey):"","data-track":`toolbar_click_${x.pointer||x.key}`,onPointerDown:()=>{x.pointer&&!Oo(x.pointer)&&le(x.pointer)},onPointerUp:()=>{be(x)}},_),Ce=p.useMemo(()=>{const x=new Map;return ha.forEach(_=>{_.visibilityKey&&x.set(_.visibilityKey,_)}),x},[]),[ze,W]=p.useState(!1),Q=p.useCallback(x=>{var z;const _=e?kt.Col:kt.Row;return d.jsx("div",{className:me("creation-toolbar__zoom-inline",{"creation-toolbar__zoom-inline--vertical":e}),children:d.jsxs(_,{gap:0,children:[d.jsx(je,{type:"button",icon:d.jsx(cc,{}),visible:!0,tooltip:c("zoom.out"),tooltipPlacement:e?"right":"bottom","aria-label":c("zoom.out"),"data-track":"toolbar_click_zoom_out",onPointerUp:()=>{ee.updateZoom(s,s.viewport.zoom-.1)},className:"zoom-out-button"}),d.jsxs(Mt,{sideOffset:12,open:ze,onOpenChange:G=>{W(G)},placement:e?"right-start":"bottom",children:[d.jsx(Tt,{content:c("zoom.fit"),showArrow:!1,children:d.jsx(Rt,{asChild:!0,children:d.jsxs("div",{"aria-label":c("zoom.fit"),"data-track":"toolbar_click_zoom_menu",className:me("zoom-menu-trigger",{active:ze}),onPointerUp:()=>{W(!ze)},children:[Number(((((z=s==null?void 0:s.viewport)==null?void 0:z.zoom)||1)*100).toFixed(0)),"%"]})})}),d.jsx(Dt,{container:l,style:{zIndex:ht.POPOVER},children:d.jsxs(Et,{onSelect:()=>{W(!1)},children:[d.jsx(ce,{"data-track":"toolbar_click_zoom_fit",onSelect:()=>{ee.fitViewport(s)},"aria-label":c("zoom.fit"),shortcut:"Cmd+Shift+=",children:c("zoom.fit")}),d.jsx(ce,{"data-track":"toolbar_click_zoom_fit_frame",onSelect:()=>{Os(s)},"aria-label":c("zoom.fitFrame"),children:c("zoom.fitFrame")}),d.jsx(ce,{"data-track":"toolbar_click_zoom_100",onSelect:()=>{ee.updateZoom(s,1)},"aria-label":c("zoom.100"),shortcut:"Cmd+0",children:c("zoom.100")})]})})]}),d.jsx(je,{type:"button",icon:d.jsx(lc,{}),visible:!0,tooltip:c("zoom.in"),tooltipPlacement:e?"right":"bottom","aria-label":c("zoom.in"),"data-track":"toolbar_click_zoom_in",onPointerUp:()=>{ee.updateZoom(s,s.viewport.zoom+.1)},className:"zoom-in-button"})]})},`zoom-${x}`)},[s,l,e,c,ze]),pe=p.useCallback((x,_)=>{if(x==="zoom")return Q(_);const z=Ce.get(x);return!z||r.isMobile&&z.pointer===Le.hand?null:z.key&&Object.values(Nl).includes(z.key)?ue(z,_,z.key):_e(z,_)},[Ce,r.isMobile,ue,_e,Q]),V=p.useCallback((x,_,z=!0,G=-1)=>{const $=pe(x,_);if(!$)return null;const ne=y(x,_);return d.jsx(ms,{buttonId:x,isVisible:z,visibleIndex:G,children:d.jsx("div",{className:me("toolbar-button-wrapper",{"toolbar-button-wrapper--dragging":ne["data-dragging"],"toolbar-button-wrapper--drag-over":ne["data-drag-over"],"toolbar-button-wrapper--drag-before":ne["data-drag-position"]==="before","toolbar-button-wrapper--drag-after":ne["data-drag-position"]==="after"}),"data-button-id":x,...ne,children:$})},`ctx-${x}-${_}`)},[pe,y]),N=d.jsxs(kt.Row,{gap:1,children:[!f&&h.map((x,_)=>e?V(x.id,_,!0,_):pe(x.id,_)),d.jsx(hw,{embedded:e}),e&&o&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(pw,{ensureToolWindowsEnabled:i})})]}),b=P?d.jsx(p.Suspense,{fallback:null,children:d.jsx(gw,{isOpen:P,onClose:A,mode:$o.SELECT,onSelect:B,onSelectMultiple:j,selectButtonText:"插入",batchSelectButtonText:"批量插入画布"})}):null;return e?d.jsxs(d.Fragment,{children:[d.jsx("div",{className:me("draw-toolbar",{"draw-toolbar--embedded":e,"draw-toolbar--icon-only":t}),children:N}),b]}):d.jsxs(d.Fragment,{children:[d.jsx(an,{padding:1,className:me("draw-toolbar",En,{"draw-toolbar--embedded":e,"draw-toolbar--icon-only":t}),children:N}),b]})},fa="https://tuziai.oss-cn-shenzhen.aliyuncs.com/aitu/AiTu.png",vw="https://tuziai.oss-cn-shenzhen.aliyuncs.com/linkme.png",Sw=()=>{const e=Ye(),t=F.getBoardContainer(e),[n,o]=p.useState(!1);return p.useEffect(()=>{const i=new Image;i.src=fa;const s=new Image;s.src=vw},[]),d.jsxs(Mt,{placement:"right-end",sideOffset:12,open:n,onOpenChange:o,children:[d.jsx(Rt,{asChild:!0,children:d.jsx(je,{type:"icon",icon:d.jsx(ih,{}),"aria-label":"用户反馈群",tooltip:"用户反馈群",tooltipPlacement:"right",selected:n,visible:!0,"data-track":"toolbar_click_feedback",onPointerDown:i=>{i.event.stopPropagation()},onClick:()=>o(!n)})}),d.jsx(Dt,{container:t,style:{zIndex:ht.POPOVER_FEEDBACK},children:d.jsx("div",{className:"feedback-qrcode-content",children:d.jsx("div",{className:"feedback-qrcode-grid",children:d.jsxs("div",{className:"feedback-qrcode-item",children:[d.jsx("img",{src:fa,alt:"用户反馈群二维码",className:"feedback-qrcode-image"}),d.jsx("div",{className:"feedback-qrcode-text",children:"用户反馈群"})]})})})})]})},zl="aitu-task-queue-failed-ack-at";function xw(){if(typeof window>"u")return 0;try{const e=Number(window.localStorage.getItem(zl));return Number.isFinite(e)?e:0}catch{return 0}}function kw(e){typeof window>"u"||window.localStorage.setItem(zl,String(e))}function Ew(e){return e.completedAt||e.updatedAt||e.createdAt||0}const bw=({projectDrawerOpen:e,onProjectDrawerToggle:t,toolboxDrawerOpen:n=!1,onToolboxDrawerToggle:o,taskPanelExpanded:i,onTaskPanelToggle:s})=>{const{activeTasks:r,completedTasks:a,failedTasks:c}=Ef(),[u,l]=p.useState(xw),h=p.useMemo(()=>c.reduce((m,w)=>Math.max(m,Ew(w)),0),[c]),f=h>u;p.useEffect(()=>{if(!(!i||h<=u)){l(h);try{kw(h)}catch{}}},[u,h,i]);const y=r.length+a.length+c.length>0?`任务队列 (生成中: ${r.length}, 已完成: ${a.length}, 失败: ${c.length})`:"任务队列 (暂无任务)";return d.jsxs("div",{className:"bottom-actions-section",children:[d.jsx(Sw,{}),d.jsx(je,{type:"icon",icon:d.jsx(sh,{}),"aria-label":e?"关闭项目":"打开项目",tooltip:e?"关闭项目":"打开项目",tooltipPlacement:"right",selected:e,visible:!0,"data-track":"toolbar_click_project_drawer","data-testid":"toolbar-project",onPointerDown:m=>{m.event.stopPropagation()},onClick:t}),o&&d.jsx(je,{type:"icon",icon:d.jsx(rh,{}),"aria-label":n?"关闭工具箱":"打开工具箱",tooltip:n?"关闭工具箱":"打开工具箱",tooltipPlacement:"right",selected:n,visible:!0,"data-track":"toolbar_click_toolbox","data-testid":"toolbar-toolbox",onPointerDown:m=>{m.event.stopPropagation()},onClick:o}),d.jsxs("div",{className:"bottom-actions-section__task-wrapper",children:[d.jsx(ah,{count:r.length>0?r.length:0,showZero:!1,offset:[6,-6],children:d.jsx(je,{type:"icon",icon:d.jsx(ch,{}),"aria-label":"任务队列",tooltip:y,tooltipPlacement:"right",selected:i,visible:!0,"data-track":"toolbar_click_tasks","data-testid":"toolbar-tasks",onPointerDown:m=>{m.event.stopPropagation()},onClick:s})}),r.length>0&&d.jsx("div",{className:"bottom-actions-section__status bottom-actions-section__status--active"}),f&&r.length===0&&d.jsx("div",{className:"bottom-actions-section__status bottom-actions-section__status--failed"})]})]})},_w=p.lazy(()=>re(()=>import("./TaskQueuePanel-WF6aq1G7.js"),__vite__mapDeps([0,1,3,4]),import.meta.url).then(e=>({default:e.TaskQueuePanel}))),Pw=460,Tw=["ai-image","ai-video"],Fl="aitu-toolbar-left",Ct=0,Cw=8,Iw=0,fo=58;function ys(e,t=fo){const n=typeof window>"u"?t:window.innerWidth,o=Math.max(Ct,n-t-Iw);return Math.round(Math.max(Ct,Math.min(e,o)))}function Aw(e,t=fo){return typeof window>"u"?"left":e+t/2>window.innerWidth/2?"right":"left"}function Mw(){if(typeof window>"u")return Ct;try{const e=window.localStorage.getItem(Fl);if(!e)return Ct;const t=Number(e);return Number.isFinite(t)?ys(t):Ct}catch{return Ct}}function ga(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Fl,String(e))}catch{}}function pa(e,t){if(typeof document>"u")return;const n=t==null?void 0:t.getBoundingClientRect(),o=n&&n.width>0?n.width:fo,i=typeof window>"u"?e+o:window.innerWidth,s=Math.round(e+o),r=Aw(e,o),a=r==="right"?Math.max(0,i-e):0,c=r==="right"?e:Math.max(0,i-s),u=document.documentElement.style;u.setProperty("--aitu-toolbar-left",`${e}px`),u.setProperty("--aitu-toolbar-right-edge",`${s}px`),u.setProperty("--aitu-toolbar-right-dock-width",`${Math.round(a)}px`),u.setProperty("--aitu-toolbar-right-avoidance",`${Math.round(a?a+12:0)}px`),u.setProperty("--aitu-toolbar-side-panel-max-width",`${Math.max(0,Math.round(c))}px`);const l=document.documentElement;l.classList.toggle("aitu-toolbar-dock-right",r==="right"),l.classList.toggle("aitu-toolbar-dock-left",r==="left"),t==null||t.style.setProperty("--aitu-toolbar-left",`${e}px`)}const Rw=on.memo(({className:e,projectDrawerOpen:t=!1,onProjectDrawerToggle:n,toolboxDrawerOpen:o=!1,onToolboxDrawerToggle:i,taskPanelExpanded:s=!1,onTaskPanelToggle:r,onOpenBackupRestore:a,onOpenCloudSync:c,onOpenMediaLibrary:u,deferredFeaturesEnabled:l=!1,minimizedToolsBarEnabled:h=!1,onEnableToolWindows:f})=>{const[g,y]=p.useState(!1),[m,w]=p.useState(!0),[S,v]=p.useState(Mw),[E,C]=p.useState(!1),[D,P]=p.useState(!1),H=p.useRef(!1),B=p.useRef(null),j=p.useRef(null),U=p.useRef(!1),A=p.useRef(S),I=p.useRef(null),{isMobile:k,isTablet:T}=lh(),M=k||T,O=M?Cw:S;uh(B,{enablePositionTracking:!1,enableScaleCompensation:!0}),p.useEffect(()=>{A.current=O,pa(O,B.current)},[O]),p.useEffect(()=>()=>{document.documentElement.classList.remove("aitu-toolbar-dock-left","aitu-toolbar-dock-right")},[]),p.useEffect(()=>{if(typeof document>"u")return;const W=document.documentElement;return W.classList.toggle("aitu-toolbar-dragging",E),()=>{W.classList.remove("aitu-toolbar-dragging")}},[E]),p.useEffect(()=>{if(M)return;const W=()=>{var pe;const Q=((pe=B.current)==null?void 0:pe.getBoundingClientRect().width)||fo;v(V=>ys(V,Q))};return window.addEventListener("resize",W),()=>{window.removeEventListener("resize",W)}},[M]),p.useEffect(()=>{if(!s){P(!1);return}if(!H.current)return;const W=requestAnimationFrame(()=>{P(!0)});return()=>{cancelAnimationFrame(W)}},[s]);const q=p.useCallback(W=>{M||W.button!==0||(W.preventDefault(),W.stopPropagation(),I.current={pointerId:W.pointerId,startX:W.clientX,startLeft:A.current},document.documentElement.classList.add("aitu-toolbar-dragging"),W.currentTarget.setPointerCapture(W.pointerId),C(!0))},[M]),le=p.useCallback(W=>{var N;const Q=I.current;if(!Q||Q.pointerId!==W.pointerId)return;W.preventDefault();const pe=((N=B.current)==null?void 0:N.getBoundingClientRect().width)||fo,V=ys(Q.startLeft+W.clientX-Q.startX,pe);A.current=V,pa(V,B.current)},[]),R=p.useCallback(W=>{const Q=I.current;!Q||Q.pointerId!==W.pointerId||(I.current=null,document.documentElement.classList.remove("aitu-toolbar-dragging"),C(!1),v(A.current),ga(A.current),W.currentTarget.hasPointerCapture(W.pointerId)&&W.currentTarget.releasePointerCapture(W.pointerId))},[]),L=p.useCallback(W=>{M||(W.preventDefault(),W.stopPropagation(),A.current=Ct,v(Ct),ga(Ct))},[M]),Y=p.useCallback(W=>{if(W[0]){const Q=W[0].contentRect.height;y(Q<Pw)}},[]);p.useEffect(()=>{const W=B.current;if(!W)return;const Q=new ResizeObserver(Y);return Q.observe(W),()=>{Q.disconnect()}},[Y]),p.useEffect(()=>{if(U.current)return;const W=j.current;if(!W)return;const Q=()=>{U.current=!0;let V=null;for(const _ of Tw){const z=W.querySelector(`[data-button-id="${_}"]`);if(z){V=z;break}}if(!V)return;const N=W.getBoundingClientRect(),b=V.getBoundingClientRect();if(!(b.bottom<=N.bottom&&b.top>=N.top)&&N.height>0){const _=b.top-N.top;W.scrollTop+=_}},pe=setTimeout(()=>{requestAnimationFrame(Q)},100);return()=>{clearTimeout(pe)}},[]);const he=p.useCallback(()=>{!s&&!H.current&&(H.current=!0),s||P(!1),r==null||r()},[s,r]),be=p.useCallback(()=>{s&&(P(!1),r==null||r())},[s,r]),ue=p.useCallback(()=>{w(W=>!W)},[]),{openDialog:_e}=Ht(),Ce=p.useCallback(()=>{_e(dt.aiImageGeneration)},[_e]),ze=p.useCallback(()=>{_e(dt.aiVideoGeneration)},[_e]);return d.jsxs(d.Fragment,{children:[H.current&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(_w,{expanded:s&&D,onClose:be})}),d.jsxs(an,{ref:B,className:me("unified-toolbar",En,{"unified-toolbar--icon-only":g||M,"unified-toolbar--mobile-collapsed":M&&m,"unified-toolbar--dragging":E},e),style:{"--aitu-toolbar-left":`${O}px`},padding:0,"data-testid":"unified-toolbar",children:[!M&&d.jsx(Tt,{content:"拖动工具栏位置,双击复位",showArrow:!1,children:d.jsx("button",{type:"button",className:"unified-toolbar__drag-handle","aria-label":"拖动工具栏位置,双击复位","data-testid":"toolbar-drag-handle",onPointerDown:q,onPointerMove:le,onPointerUp:R,onPointerCancel:R,onDoubleClick:L})}),M&&m&&d.jsxs("div",{className:"unified-toolbar__collapsed-shortcuts",children:[d.jsx("button",{className:"unified-toolbar__collapsed-btn unified-toolbar__collapsed-btn--toggle",onClick:ue,"aria-label":"展开工具栏",children:d.jsx(dh,{size:18})}),d.jsx("button",{className:"unified-toolbar__collapsed-btn",onClick:Ce,"aria-label":"AI 图片生成",children:d.jsx(Is,{})}),d.jsx("button",{className:"unified-toolbar__collapsed-btn",onClick:ze,"aria-label":"AI 视频生成",children:d.jsx(Cs,{})})]}),M&&!m&&d.jsx("button",{className:"unified-toolbar__mobile-toggle unified-toolbar__mobile-toggle--expanded",onClick:ue,"aria-label":"收起工具栏",children:d.jsx(hh,{size:18})}),d.jsx("div",{className:"unified-toolbar__section unified-toolbar__section--fixed-top",children:d.jsx(Zm,{embedded:!0,iconMode:g||M,onOpenBackupRestore:a,onOpenCloudSync:c})}),d.jsx("div",{ref:j,className:"unified-toolbar__scrollable",children:d.jsx("div",{className:"unified-toolbar__section",children:d.jsx(yw,{embedded:!0,iconMode:g||M,onOpenMediaLibrary:u,deferredFeaturesEnabled:l,minimizedToolsBarEnabled:h,onEnableToolWindows:f})})}),d.jsx("div",{className:"unified-toolbar__section unified-toolbar__section--fixed-bottom",children:d.jsx(bw,{projectDrawerOpen:t,onProjectDrawerToggle:n||(()=>{}),toolboxDrawerOpen:o,onToolboxDrawerToggle:i,taskPanelExpanded:s,onTaskPanelToggle:he})})]})]})}),Dw="#f5f5f5",Lw="rgba(0, 0, 0, 0.6)";function jw(e,t){const n=Math.max(4,Math.min(256,t)),o=n+4,i=o/2,s=n/2,r=`<svg width="${o}" height="${o}" viewBox="0 0 ${o} ${o}" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
7
|
+
`)}function $m(e){var o,i;if(!e)return!1;const t=!!e.text||!!((o=e.data)!=null&&o.text),n=!!e.elements||!!((i=e.data)!=null&&i.elements);return t&&!n}function Vm(e){var n;const t=e;if(t.text)return t.text;if((n=t.data)!=null&&n.text)return t.data.text;if(typeof t.getData=="function"){const o=t.getData("text/plain");if(o)return o}return null}const Wm=e=>{const{insertFragment:t}=e;return e.insertFragment=(n,o,i)=>{if($m(n)){const s=Vm(n);if(s&&s.trim()){const r=s.trim(),a=kd(r);if(a&&a.length>0){const u=Math.round(window.innerWidth*.5);Ed(e,a,o,u);return}const c=Hm(r);ec.insertText(e,o,c);return}}t(n,o,i)},e},Um=e=>{const t=e;return t.renderImage=(n,o)=>{const i=mo.createRoot(n);i.render(d.jsx(oa,{...o}));let s={...o};return{destroy:()=>{setTimeout(()=>{i.unmount()},0)},update:a=>{s={...s,...a},i.render(d.jsx(oa,{...s}))}}},_m(Wm(Bm(t)))},Gm=p.forwardRef(({children:e,gap:t,align:n,justifyContent:o,className:i,style:s},r)=>d.jsx("div",{className:me("stack stack_horizontal",i),style:{"--gap":t,alignItems:n,justifyContent:o,...s},ref:r,children:e})),Km=p.forwardRef(({children:e,gap:t,align:n,justifyContent:o,className:i,style:s},r)=>d.jsx("div",{className:me("stack stack_vertical",i),style:{"--gap":t,justifyItems:n,justifyContent:o,...s},ref:r,children:e})),kt={Row:Gm,Col:Km},an=on.forwardRef(({children:e,padding:t,className:n,style:o,...i},s)=>d.jsx("div",{className:me("island",n),style:{"--padding":t,...o},ref:s,...i,children:e})),pi=on.createContext({}),ra=(e="",t=!1)=>`menu-item menu-item-base ${e} ${t?"menu-item--active":""}`.trim(),qm=(e,t)=>{const n=p.useContext(pi);return bd(e,o=>{var s;const i=new CustomEvent(Ps.MENU_ITEM_SELECT,{bubbles:!0,cancelable:!0});t==null||t(i),i.defaultPrevented||(s=n.onSelect)==null||s.call(n,i)})},Ym=({icon:e,shortcut:t,children:n})=>d.jsxs(d.Fragment,{children:[e&&d.jsx("div",{className:"menu-item__icon",children:e}),d.jsx("div",{className:"menu-item__text",children:n}),t&&d.jsx("div",{className:"menu-item__shortcut",children:t})]}),ce=({icon:e,onSelect:t,children:n,shortcut:o,className:i,selected:s,submenu:r,...a})=>{const[c,u]=p.useState(!1),l=p.useRef(),{title:h,...f}=a,g=f["aria-label"]??h,y=qm(f.onClick,t),m=d.jsx(Ym,{icon:e,shortcut:o,children:n}),w=()=>{l.current&&window.clearTimeout(l.current),u(!0)},S=()=>{l.current=window.setTimeout(()=>{u(!1)},100)};return r?d.jsxs(Mt,{open:c,onOpenChange:u,placement:"right-start",children:[d.jsx(Rt,{asChild:!0,children:d.jsx("button",{...f,type:"button",className:ra(i,s||c),"aria-label":g,onClick:y,onMouseEnter:w,onMouseLeave:S,role:"menuitem","aria-haspopup":"true","aria-expanded":c,children:m})}),d.jsx(Dt,{onMouseEnter:w,onMouseLeave:S,children:r})]}):d.jsx("button",{...f,onClick:y,type:"button",className:ra(i,s),"aria-label":g,role:"menuitem",children:m})};ce.displayName="MenuItem";const ml=({children:e})=>d.jsx("div",{style:{display:"inline-flex",marginLeft:"auto",padding:"2px 4px",background:"var(--color-promo)",color:"var(--color-surface-lowest)",borderRadius:6,fontSize:9,fontFamily:"Cascadia, monospace"},children:e});ml.displayName="MenuItemBadge";ce.Badge=ml;const Et=({children:e,className:t="",onSelect:n,style:o,onClose:i})=>{const s=me(`menu ${t}`).trim(),r=p.useRef(null),a=p.useCallback(()=>r.current?Array.from(r.current.querySelectorAll("button.menu-item:not([disabled])")):[],[]),c=p.useCallback(u=>{var f,g,y,m;const l=a();if(l.length===0)return;const h=l.findIndex(w=>w===document.activeElement);switch(u.key){case"ArrowDown":{u.preventDefault();const w=h<l.length-1?h+1:0;(f=l[w])==null||f.focus();break}case"ArrowUp":{u.preventDefault();const w=h>0?h-1:l.length-1;(g=l[w])==null||g.focus();break}case"Home":{u.preventDefault(),(y=l[0])==null||y.focus();break}case"End":{u.preventDefault(),(m=l[l.length-1])==null||m.focus();break}case"Escape":{u.preventDefault(),i==null||i();break}case"Enter":case" ":{h>=0&&l[h]&&(u.preventDefault(),l[h].click());break}}},[a,i]);return p.useEffect(()=>{const u=a();u.length>0&&requestAnimationFrame(()=>{var l;(l=u[0])==null||l.focus()})},[a]),d.jsx(pi.Provider,{value:{onSelect:n},children:d.jsx("div",{className:s,style:o,"data-testid":"menu",onKeyDown:c,ref:r,role:"menu",children:d.jsx(an,{className:"menu-container",padding:2,children:e})})})};Et.displayName="Menu";const wl=()=>{const e=Ye(),{t}=Oe();return d.jsx(ce,{"data-testid":"save-button","data-track":"toolbar_click_menu_save",onSelect:()=>{Bc(e)},icon:d.jsx(Pd,{}),"aria-label":t("menu.saveFile"),shortcut:"Cmd+S",children:t("menu.saveFile")})};wl.displayName="SaveToFile";const yl=()=>{const e=Ye(),t=gl(),{t:n}=Oe(),o=(i,s,r)=>{e.children=i,e.history.undos=[],e.history.redos=[],At(e),e.selection=null,e.viewport=s||{zoom:1},e.theme={themeColorMode:Kt.default},t.update(e.children,{board:e,parent:e,parentG:F.getElementHost(e)}),ee.fitViewport(e)};return d.jsx(ce,{"data-testid":"open-button","data-track":"toolbar_click_menu_open",onSelect:()=>{mf(e).then(i=>{i&&o(i.elements,i.viewport)})},icon:d.jsx(_d,{}),"aria-label":n("menu.open"),children:n("menu.open")})};yl.displayName="OpenFile";const vl=()=>{const e=Ye(),t=p.useContext(pi),{t:n}=Oe();return d.jsx(ce,{icon:d.jsx(Td,{}),"data-testid":"image-export-button","data-track":"toolbar_click_menu_export",onSelect:()=>{Do(e,!0)},submenu:d.jsxs(Et,{onSelect:()=>{var i;const o=new CustomEvent(Ps.MENU_ITEM_SELECT,{bubbles:!0,cancelable:!0});(i=t.onSelect)==null||i.call(t,o)},children:[d.jsx(ce,{"data-track":"toolbar_click_menu_export_png",onSelect:()=>{Do(e,!0)},"aria-label":n("menu.exportImage.png"),children:n("menu.exportImage.png")}),d.jsx(ce,{"data-track":"toolbar_click_menu_export_jpg",onSelect:()=>{Do(e,!1)},"aria-label":n("menu.exportImage.jpg"),children:n("menu.exportImage.jpg")})]}),shortcut:"Cmd+Shift+E","aria-label":n("menu.exportImage"),children:n("menu.exportImage")})};vl.displayName="SaveAsImage";const Sl=()=>{const{appState:e,setAppState:t}=Ht(),{t:n}=Oe();return d.jsx(ce,{icon:d.jsx(Cd,{}),"data-testid":"reset-button","data-track":"toolbar_click_menu_clean",onSelect:()=>{t({...e,openCleanConfirm:!0})},shortcut:"Cmd+Backspace","aria-label":n("menu.cleanBoard"),children:n("menu.cleanBoard")})};Sl.displayName="CleanBoard";const xl=({onOpenBackupRestore:e})=>{const{t}=Oe();return d.jsx(ce,{icon:d.jsx(Ad,{}),"data-track":"toolbar_click_menu_backup",onSelect:e,"aria-label":t("menu.backupRestore"),children:t("menu.backupRestore")})};xl.displayName="BackupRestore";const kl=({onOpenCloudSync:e})=>{const{t}=Oe();return d.jsx(ce,{icon:d.jsx(Rd,{}),"data-track":"toolbar_click_menu_cloud_sync",onSelect:e,"aria-label":t("menu.cloudSync"),children:t("menu.cloudSync")})};kl.displayName="CloudSync";const El=()=>{const{t:e}=Oe();return d.jsx(ce,{icon:d.jsx(Md,{}),"data-track":"toolbar_click_menu_debug",onSelect:()=>{window.location.href="./sw-debug.html"},"aria-label":e("menu.debugPanel"),children:e("menu.debugPanel")})};El.displayName="DebugPanel";const bl=()=>{const{appState:e,setAppState:t}=Ht(),{t:n}=Oe();return d.jsx(ce,{icon:d.jsx(Dd,{}),"data-track":"toolbar_click_menu_settings",onSelect:()=>{t({...e,openSettings:!0})},"aria-label":n("menu.settings"),children:n("menu.settings")})};bl.displayName="Settings";const _l=()=>{const{appState:e,setAppState:t}=Ht(),{t:n}=Oe();return d.jsx(ce,{icon:d.jsx(Ld,{}),"data-track":"toolbar_click_menu_commands",onSelect:()=>{t({...e,openCommandPalette:!0})},shortcut:"Cmd+K","aria-label":n("menu.commandPalette"),children:n("menu.commandPalette")})};_l.displayName="QuickCommands";const Pl=()=>{const{t:e}=Oe();return d.jsx(ce,{icon:d.jsx(jd,{}),"data-track":"toolbar_click_menu_manual",onSelect:()=>{window.open("./user-manual/index.html","_blank")},"aria-label":e("menu.userManual"),children:e("menu.userManual")})};Pl.displayName="UserManual";const Tl=()=>{var n;const{t:e}=Oe(),t=((n=document.querySelector('meta[name="app-version"]'))==null?void 0:n.getAttribute("content"))||"0.0.0";return d.jsx(ce,{"data-track":"toolbar_click_menu_version",onSelect:()=>{},"aria-label":e("menu.version"),children:d.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%"},children:[d.jsxs("span",{style:{color:"#666"},children:[e("menu.version"),":",t]}),d.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[d.jsx("span",{style:{color:"#1890ff",cursor:"pointer"},"data-track":"toolbar_click_menu_changelog",onClick:o=>{o.stopPropagation(),window.open("./versions.html","_blank")},children:e("menu.changelog")}),d.jsx("span",{style:{color:"#1890ff",cursor:"pointer"},"data-track":"toolbar_click_menu_more_versions",onClick:o=>{o.stopPropagation(),window.open("https://release.opentu.ai/","_blank")},children:e("menu.more")})]})]})})};Tl.displayName="VersionInfo";async function Xm(e){if(!e||typeof e!="string")return!1;if(e.startsWith("blob:")||e.startsWith("data:"))return!0;try{return(await fetch(e,{method:"HEAD",mode:"cors",cache:"no-cache"})).ok}catch{try{const t=await fetch(e,{method:"GET",mode:"no-cors",cache:"no-cache"});return t.type==="opaque"||t.ok}catch{return!1}}}const Cl=()=>{const e=Ye(),{t}=Oe(),[n,o]=p.useState(!1),i=p.useCallback(async()=>{if(n)return;o(!0);const s=Ne.loading(t("menu.cleanInvalidLinks.scanning"),0);try{const r=[];for(let u=0;u<e.children.length;u++){const l=e.children[u],h=l.url;if(!h||typeof h!="string")continue;const f=K.isDrawElement(l)&&K.isImage(l),g=Yi(l);(f||g)&&r.push({element:l,index:u,url:h})}const a=[];if(await Promise.all(r.map(async({element:u,index:l,url:h})=>{await Xm(h)||a.push({element:u,index:l})})),s.then(u=>{var l;return(l=u==null?void 0:u.close)==null?void 0:l.call(u)}),a.length===0){Ne.success(t("menu.cleanInvalidLinks.noInvalid")),o(!1);return}a.sort((u,l)=>l.index-u.index);for(const{index:u}of a)Se.removeNode(e,[u]);const c=t("menu.cleanInvalidLinks.success").replace("{count}",String(a.length));Ne.success(c)}catch(r){s.then(a=>{var c;return(c=a==null?void 0:a.close)==null?void 0:c.call(a)}),Ne.error(t("menu.cleanInvalidLinks.error")),console.error("[CleanInvalidLinks] Error:",r)}finally{o(!1)}},[e,t,n]);return d.jsx(ce,{icon:d.jsx(Id,{}),"data-track":"toolbar_click_menu_clean_invalid_links",onSelect:i,"aria-label":t("menu.cleanInvalidLinks"),disabled:n,children:t("menu.cleanInvalidLinks")})};Cl.displayName="CleanInvalidLinks";const Il=()=>{const{language:e,setLanguage:t,t:n}=Oe(),o=p.useContext(pi);return d.jsx(ce,{icon:d.jsx(tc,{}),"data-testid":"language-switcher-button",onSelect:()=>{},submenu:d.jsxs(Et,{onSelect:()=>{var s;const i=new CustomEvent(Ps.MENU_ITEM_SELECT,{bubbles:!0,cancelable:!0});(s=o.onSelect)==null||s.call(o,i)},children:[d.jsx(ce,{onSelect:()=>{t("zh")},"aria-label":n("language.chinese"),selected:e==="zh",children:n("language.chinese")}),d.jsx(ce,{onSelect:()=>{t("en")},"aria-label":n("language.english"),selected:e==="en",children:n("language.english")})]}),"aria-label":n("language.switcher"),children:n("language.switcher")})};Il.displayName="LanguageSwitcherMenu";const ho=()=>d.jsx("div",{style:{height:"1px",backgroundColor:"var(--color-gray-10)",margin:".5rem 0"}});ho.displayName="MenuSeparator";const ms=({children:e,buttonId:t,isVisible:n,visibleIndex:o=-1,disabled:i=!1})=>{const{t:s}=Oe(),{hideButton:r,showButton:a,resetToDefault:c,visibleButtons:u,reorderButton:l}=hi(),[h,f]=p.useState(!1),[g,y]=p.useState({x:0,y:0}),m=p.useRef(null),w=p.useRef(null);p.useEffect(()=>{const A=w.current;if(!A)return;const I=k=>{k.button===2&&k.stopPropagation()};return A.addEventListener("pointerdown",I,!0),()=>{A.removeEventListener("pointerdown",I,!0)}},[]);const S=p.useCallback(A=>{i||(A.preventDefault(),A.stopPropagation(),y({x:A.clientX,y:A.clientY}),f(!0))},[i]),v=p.useCallback(()=>{f(!1)},[]),E=p.useCallback(()=>{n?r(t):a(t),v()},[n,t,r,a,v]),C=p.useCallback(()=>{o>0&&l(o,o-1,!0),v()},[o,l,v]),D=p.useCallback(()=>{o>=0&&o<u.length-1&&l(o,o+1,!0),v()},[o,u.length,l,v]),P=p.useCallback(()=>{o>0&&l(o,0,!0),v()},[o,l,v]),H=p.useCallback(()=>{o>=0&&o<u.length-1&&l(o,u.length-1,!0),v()},[o,u.length,l,v]),B=p.useCallback(()=>{c(),v()},[c,v]);p.useEffect(()=>{if(!h)return;const A=k=>{m.current&&!m.current.contains(k.target)&&v()},I=k=>{k.key==="Escape"&&v()};return document.addEventListener("mousedown",A),document.addEventListener("keydown",I),()=>{document.removeEventListener("mousedown",A),document.removeEventListener("keydown",I)}},[h,v]),p.useEffect(()=>{if(!h||!m.current)return;const I=m.current.getBoundingClientRect(),k=window.innerWidth,T=window.innerHeight;let M=g.x,O=g.y;g.x+I.width>k&&(M=k-I.width-8),g.y+I.height>T&&(O=T-I.height-8),(M!==g.x||O!==g.y)&&y({x:M,y:O})},[h,g]);const j=n&&o>0,U=n&&o>=0&&o<u.length-1;return d.jsxs(d.Fragment,{children:[d.jsx("div",{ref:w,onContextMenu:S,children:e}),h&&nc.createPortal(d.jsx("div",{ref:m,className:"toolbar-context-menu",style:{position:"fixed",left:g.x,top:g.y,zIndex:ht.DROPDOWN_PORTAL},children:d.jsxs(Et,{children:[n&&d.jsxs(d.Fragment,{children:[d.jsx(ce,{onSelect:C,disabled:!j,children:s("toolbar.moveUp")}),d.jsx(ce,{onSelect:D,disabled:!U,children:s("toolbar.moveDown")}),d.jsx(ce,{onSelect:P,disabled:!j,children:s("toolbar.moveToTop")}),d.jsx(ce,{onSelect:H,disabled:!U,children:s("toolbar.moveToBottom")}),d.jsx(ho,{})]}),d.jsx(ce,{onSelect:E,children:s(n?"toolbar.rightClickToHide":"toolbar.doubleClickToShow")}),d.jsx(ho,{}),d.jsx(ce,{onSelect:B,children:s("toolbar.resetToDefault")})]})}),document.body)]})},Zm=({embedded:e=!1,iconMode:t=!1,onOpenBackupRestore:n,onOpenCloudSync:o})=>{const i=Ye(),{t:s}=Oe(),{isButtonVisible:r,visibleButtons:a}=hi(),c=F.getBoardContainer(i),[u,l]=p.useState(!1),h=i.history.undos.length<=0,f=i.history.redos.length<=0,g=r("undo"),y=r("redo"),m=a.findIndex(v=>v.id==="undo"),w=a.findIndex(v=>v.id==="redo"),S=d.jsxs(kt.Row,{gap:1,children:[d.jsxs(Mt,{sideOffset:12,open:u,onOpenChange:v=>{l(v)},placement:e?"right-start":"bottom-start",children:[d.jsx(Rt,{asChild:!0,children:d.jsx(je,{type:"icon",visible:!0,selected:u,icon:d.jsx(tc,{}),tooltip:u?void 0:s("general.menu"),tooltipPlacement:e?"right":"bottom","aria-label":s("general.menu"),"data-track":"toolbar_click_menu",onPointerDown:()=>{l(!u)}})}),d.jsx(Dt,{container:c,style:{zIndex:ht.POPOVER_APP},children:d.jsxs(Et,{onSelect:()=>{l(!1)},onClose:()=>{l(!1)},children:[d.jsx(yl,{}),d.jsx(wl,{}),d.jsx(vl,{}),d.jsx(Sl,{}),d.jsx(Cl,{}),d.jsx(ho,{}),d.jsx(Il,{}),d.jsx(xl,{onOpenBackupRestore:()=>{l(!1),n==null||n()}}),d.jsx(El,{}),d.jsx(kl,{onOpenCloudSync:()=>{l(!1),o==null||o()}}),d.jsx(bl,{}),d.jsx(ho,{}),d.jsx(_l,{}),d.jsx(Pl,{}),d.jsx(Tl,{})]})})]},0),g&&d.jsx(ms,{buttonId:"undo",isVisible:!0,visibleIndex:m,children:d.jsx(je,{type:"icon",icon:d.jsx(oc,{}),visible:!0,tooltip:s("general.undo"),tooltipPlacement:e?"right":"bottom","aria-label":s("general.undo"),"data-track":"toolbar_click_undo",onPointerUp:()=>{i.undo()},disabled:h},1)}),y&&d.jsx(ms,{buttonId:"redo",isVisible:!0,visibleIndex:w,children:d.jsx(je,{type:"icon",icon:d.jsx(ic,{}),visible:!0,tooltip:s("general.redo"),tooltipPlacement:e?"right":"bottom","aria-label":s("general.redo"),"data-track":"toolbar_click_redo",onPointerUp:()=>{i.redo()},disabled:f},2)})]});return e?d.jsxs("div",{className:me("app-toolbar",{"app-toolbar--embedded":e,"app-toolbar--icon-only":t}),children:[S,d.jsx(je,{type:"icon",icon:d.jsx(Od,{}),visible:!0,tooltip:s("menu.github"),tooltipPlacement:"right","aria-label":s("menu.github"),"data-track":"toolbar_click_github",onPointerUp:()=>{window.open("https://github.com/ljquan/aitu","_blank")}})]}):d.jsx(an,{padding:1,className:me("app-toolbar",En,{"app-toolbar--embedded":e,"app-toolbar--icon-only":t}),children:S})};function Jm(e,t){return!e||e===Gn.solid?null:e===Gn.dashed?`${t*3},${t*2}`:e===Gn.dotted?`${t},${t*2}`:null}function Ut(e){return e!==void 0&&!isNaN(e[0])&&!isNaN(e[1])&&isFinite(e[0])&&isFinite(e[1])}class Qm extends ci{constructor(t){super(t)}canDraw(t){return t.anchors&&t.anchors.length>0}draw(t){const n=yo();n.classList.add("pen-path");const o=Hc(t),i=t.cornerRadius||0,s=$c(o,t.closed,i),r=t.strokeWidth||2,a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("d",s),a.setAttribute("fill",Nd(t.fill)),a.setAttribute("stroke",t.strokeColor||"#000000"),a.setAttribute("stroke-width",String(r)),a.setAttribute("stroke-linecap","round"),a.setAttribute("stroke-linejoin","round");const c=Jm(t.strokeStyle,r);return c&&a.setAttribute("stroke-dasharray",c),n.appendChild(a),n}}function ew(e,t){const n=e.point,o=Fd;if(e.type==="corner"){const i=document.createElementNS("http://www.w3.org/2000/svg","rect");return i.setAttribute("x",String(n[0]-o/2)),i.setAttribute("y",String(n[1]-o/2)),i.setAttribute("width",String(o)),i.setAttribute("height",String(o)),i.setAttribute("fill",t?"#1890ff":"#ffffff"),i.setAttribute("stroke","#1890ff"),i.setAttribute("stroke-width","1.5"),i.classList.add("pen-anchor"),i}else{const i=document.createElementNS("http://www.w3.org/2000/svg","circle");return i.setAttribute("cx",String(n[0])),i.setAttribute("cy",String(n[1])),i.setAttribute("r",String(o/2)),i.setAttribute("fill",t?"#1890ff":"#ffffff"),i.setAttribute("stroke","#1890ff"),i.setAttribute("stroke-width","1.5"),i.classList.add("pen-anchor"),i}}function aa(e){const t=document.createElementNS("http://www.w3.org/2000/svg","circle");return t.setAttribute("cx",String(e[0])),t.setAttribute("cy",String(e[1])),t.setAttribute("r",String(zd/2)),t.setAttribute("fill","#ffffff"),t.setAttribute("stroke","#1890ff"),t.setAttribute("stroke-width","1"),t.classList.add("pen-handle"),t}function ca(e,t){const n=document.createElementNS("http://www.w3.org/2000/svg","line");return n.setAttribute("x1",String(e[0])),n.setAttribute("y1",String(e[1])),n.setAttribute("x2",String(t[0])),n.setAttribute("y2",String(t[1])),n.setAttribute("stroke","#1890ff"),n.setAttribute("stroke-width","1"),n.setAttribute("stroke-dasharray","3,3"),n.classList.add("pen-handle-line"),n}function tw(e,t,n){const o="#ff4d4f";if(n.vertical&&n.verticalRefPoint){const s=n.verticalRefPoint,r=document.createElementNS("http://www.w3.org/2000/svg","line");r.setAttribute("x1",String(t[0])),r.setAttribute("y1",String(Math.min(t[1],s[1])-50)),r.setAttribute("x2",String(t[0])),r.setAttribute("y2",String(Math.max(t[1],s[1])+50)),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(1)),r.setAttribute("stroke-dasharray","4,4"),r.classList.add("pen-alignment-guide"),e.appendChild(r);const a=document.createElementNS("http://www.w3.org/2000/svg","circle");a.setAttribute("cx",String(s[0])),a.setAttribute("cy",String(s[1])),a.setAttribute("r","3"),a.setAttribute("fill",o),a.setAttribute("opacity","0.6"),a.classList.add("pen-alignment-marker"),e.appendChild(a)}if(n.horizontal&&n.horizontalRefPoint){const s=n.horizontalRefPoint,r=document.createElementNS("http://www.w3.org/2000/svg","line");if(r.setAttribute("x1",String(Math.min(t[0],s[0])-50)),r.setAttribute("y1",String(t[1])),r.setAttribute("x2",String(Math.max(t[0],s[0])+50)),r.setAttribute("y2",String(t[1])),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(1)),r.setAttribute("stroke-dasharray","4,4"),r.classList.add("pen-alignment-guide"),e.appendChild(r),!n.verticalRefPoint||n.horizontalRefPoint[0]!==n.verticalRefPoint[0]||n.horizontalRefPoint[1]!==n.verticalRefPoint[1]){const a=document.createElementNS("http://www.w3.org/2000/svg","circle");a.setAttribute("cx",String(s[0])),a.setAttribute("cy",String(s[1])),a.setAttribute("r","3"),a.setAttribute("fill",o),a.setAttribute("opacity","0.6"),a.classList.add("pen-alignment-marker"),e.appendChild(a)}}}function nw(e,t,n="#1890ff",o=2,i){const s=yo();if(s.classList.add("pen-preview"),e.length===0)return s;if(t&&Ut(t)&&i&&(i.horizontal||i.vertical)&&tw(s,t,i),e.length>0){const r=$c(e,!1),a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("d",r),a.setAttribute("fill","none"),a.setAttribute("stroke",n),a.setAttribute("stroke-width",String(o)),a.setAttribute("stroke-linecap","round"),a.setAttribute("stroke-linejoin","round"),s.appendChild(a)}if(t&&Ut(t)&&e.length>0){const r=e[e.length-1];if(Ut(r.point)){const a=document.createElementNS("http://www.w3.org/2000/svg","line"),c=r.handleOut&&Ut(r.handleOut)?r.handleOut:r.point;a.setAttribute("x1",String(c[0])),a.setAttribute("y1",String(c[1])),a.setAttribute("x2",String(t[0])),a.setAttribute("y2",String(t[1])),a.setAttribute("stroke",n),a.setAttribute("stroke-width","1"),a.setAttribute("stroke-dasharray","5,5"),a.setAttribute("opacity","0.6"),s.appendChild(a)}}for(let r=0;r<e.length;r++){const a=e[r];if(!Ut(a.point))continue;if(a.handleIn&&Ut(a.handleIn)){const u=ca(a.point,a.handleIn);s.appendChild(u);const l=aa(a.handleIn);s.appendChild(l)}if(a.handleOut&&Ut(a.handleOut)){const u=ca(a.point,a.handleOut);s.appendChild(u);const l=aa(a.handleOut);s.appendChild(l)}const c=ew(a,r===e.length-1);s.appendChild(c)}return s}const ow=e=>F.getBoardContainer(e).classList.contains("viewport-moving"),mi=(e,t)=>ow(e)||Bd(t),iw=3,sw=3,la=8,ws=new WeakMap;function jt(e){let t=ws.get(e);return t||(t={isCreating:!1,anchors:[],isDraggingHandle:!1,dragStartPoint:null,currentPoint:null,previewG:null,alignment:{horizontal:!1,vertical:!1,horizontalRefPoint:null,verticalRefPoint:null,referencePoint:null}},ws.set(e,t)),t}function ua(e,t,n=!1){const o={horizontal:!1,vertical:!1,horizontalRefPoint:null,verticalRefPoint:null,referencePoint:null},i=[...e],s=n&&t.length>1?t.slice(0,-1):t;if(s.length===0)return{snappedPoint:e,alignment:o};let r=la,a=null,c=null,u=la,l=null,h=null;for(const f of s){const g=Math.abs(e[0]-f.point[0]),y=Math.abs(e[1]-f.point[1]);g<r&&(r=g,a=f.point[0],c=f.point),y<u&&(u=y,l=f.point[1],h=f.point)}return a!==null&&(i[0]=a,o.vertical=!0,o.verticalRefPoint=c),l!==null&&(i[1]=l,o.horizontal=!0,o.horizontalRefPoint=h),o.referencePoint=o.verticalRefPoint||o.horizontalRefPoint,{snappedPoint:i,alignment:o}}function xn(e){const t=jt(e);t.previewG&&t.previewG.remove(),Al(e),t.isCreating=!1,t.anchors=[],t.isDraggingHandle=!1,t.dragStartPoint=null,t.currentPoint=null,t.previewG=null,t.alignment={horizontal:!1,vertical:!1,horizontalRefPoint:null,verticalRefPoint:null,referencePoint:null}}function Al(e){F.getElementHost(e).querySelectorAll(".pen-preview").forEach(o=>o.remove())}function jn(e){const t=jt(e),n=F.getElementHost(e);t.previewG&&t.previewG.remove(),t.previewG=nw(t.anchors,t.currentPoint,"#1890ff",2,t.alignment),n.appendChild(t.previewG)}function Zo(e,t=!1){const n=jt(e),o=[...n.anchors];if(n.previewG&&(n.previewG.remove(),n.previewG=null),Al(e),o.length>=2){const i=Sf(e,o,t);n.isCreating=!1,n.anchors=[],n.isDraggingHandle=!1,n.dragStartPoint=null,n.currentPoint=null,Se.insertNode(e,i,[e.children.length]),t?(At(e),Pn(e,i)):At(e)}else xn(e)}function Vn(e){return F.getPointer(e)===zt.pen}function rw(e){const t=jt(e);t.isCreating&&(Vn(e)||(t.anchors.length>=2?Zo(e,!1):xn(e)))}const aw=e=>{const{pointerDown:t,pointerMove:n,pointerUp:o,globalPointerUp:i,keyDown:s,globalKeyDown:r}=e;let a=!1;const c=l=>l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLElement&&l.isContentEditable,u=l=>{if(l.defaultPrevented||!Vn(e)||c(l.target))return!1;const h=jt(e);return h.isCreating?l.key==="Enter"?(Zo(e,!1),l.preventDefault(),!0):l.key==="Escape"?(xn(e),l.preventDefault(),!0):ve.isHotkey(["mod+z"],{byKey:!0})(l)||l.key==="Backspace"||l.key==="Delete"?(h.anchors.length>0&&(h.anchors.pop(),jn(e)),h.anchors.length===0&&xn(e),l.preventDefault(),!0):!1:!1};return e.pointerDown=l=>{if(mi(e,l)){a=!0,t(l);return}if(rw(e),!Vn(e)){t(l);return}const h=jt(e);let f=Xe(e,Ze(e,l.x,l.y));if(h.isCreating&&h.anchors.length>=sw){const w={anchors:h.anchors};if(wf(w,f)){Zo(e,!0);return}}if(h.anchors.length>0){const{snappedPoint:w}=ua(f,h.anchors,!1);f=w}h.isCreating=!0,h.isDraggingHandle=!0,h.dragStartPoint=f;const y=Vc(e).defaultAnchorType,m={point:f,type:y};h.anchors.push(m),h.alignment={horizontal:!1,vertical:!1,horizontalRefPoint:null,verticalRefPoint:null,referencePoint:null},jn(e)},e.pointerMove=l=>{if(a){n(l);return}if(!Vn(e)){n(l);return}const h=jt(e);let f=Xe(e,Ze(e,l.x,l.y));const g=h.isDraggingHandle,{snappedPoint:y,alignment:m}=ua(f,h.anchors,g);if(h.currentPoint=y,h.alignment=m,h.isDraggingHandle&&h.dragStartPoint&&h.anchors.length>0&&yf(h.dragStartPoint,f)>iw){const S=h.anchors.length-1,v=h.anchors[S];if(v.type!=="corner"){if(v.type==="smooth"||v.type==="symmetric"){const E=vf(v.point,f);h.anchors[S]={...v,handleIn:E.handleIn,handleOut:E.handleOut}}}}h.isCreating&&Ts(e,"pen-preview",()=>{jn(e)}),n(l)},e.pointerUp=l=>{if(a){a=!1,o(l);return}if(!Vn(e)){o(l);return}const h=jt(e);h.isDraggingHandle=!1,h.dragStartPoint=null,jn(e),o(l)},e.globalPointerUp=l=>{a=!1,i(l)},e.globalKeyDown=l=>{u(l)||r(l)},e.keyDown=l=>{u(l)||s(l)},e};function nn(e){const t=ws.get(e);t!=null&&t.isCreating&&(t.anchors.length>=2?Zo(e,!1):xn(e))}const Ks=[{icon:d.jsx(ui,{}),pointer:ie.feltTipPen,titleKey:"toolbar.pen"},{icon:d.jsx(Hd,{}),pointer:zt.pen,titleKey:"toolbar.vectorPen"},{icon:d.jsx($d,{}),pointer:ie.mask,titleKey:"toolbar.maskBrush"},{icon:d.jsx(Vd,{}),pointer:ie.eraser,titleKey:"toolbar.eraser"},{icon:d.jsx(Wd,{}),pointer:ie.laserPointer,titleKey:"toolbar.laserPointer"}],cw=sc(Ks,5),Ml=({onPointerUp:e})=>{const{t}=Oe(),n=Ye();return d.jsx(an,{padding:1,children:d.jsx(kt.Row,{gap:1,align:"center",children:d.jsx(kt.Row,{gap:1,children:cw.map((o,i)=>o.map((s,r)=>d.jsx(je,{className:me({fillable:!1}),selected:n.pointer===s.pointer,type:"icon",size:"small",visible:!0,icon:s.icon,tooltip:t(s.titleKey),"aria-label":t(s.titleKey),"aria-keyshortcuts":s.pointer===ie.mask?"Shift+M":void 0,keyBindingLabel:s.pointer===ie.mask?"M":void 0,onPointerDown:()=>{s.pointer!==zt.pen&&nn(n),Re(n,He.dnd),ee.updatePointerType(n,s.pointer)},onPointerUp:()=>{Re(n,He.drawing),e(s.pointer)}},`${i}-${r}`)))})})})},lw=[{icon:d.jsx(Ud,{}),title:"Rectangle — R",pointer:ge.rectangle},{icon:d.jsx(Gd,{}),title:"Ellipse — O",pointer:ge.ellipse},{icon:d.jsx(Kd,{}),title:"Triangle",pointer:ge.triangle},{icon:d.jsx(qd,{}),title:"Terminal",pointer:rc.terminal},{icon:d.jsx(Yd,{}),title:"Diamond",pointer:ge.diamond},{icon:d.jsx(Xd,{}),title:"Parallelogram",pointer:ge.parallelogram},{icon:d.jsx(Zd,{}),title:"RoundRectangle",pointer:ge.roundRectangle}],uw=sc(lw,5),Rl=({onPointerUp:e})=>{const t=Ye();return d.jsx(an,{padding:1,children:d.jsx(kt.Col,{gap:1,children:uw.map((n,o)=>d.jsx(kt.Row,{gap:1,children:n.map((i,s)=>d.jsx(je,{className:me({fillable:!1}),type:"icon",size:"small",visible:!0,icon:i.icon,tooltip:i.title,"aria-label":i.title,onPointerDown:()=>{nn(t),Re(t,He.dnd),ee.updatePointerType(t,i.pointer)},onPointerUp:()=>{Re(t,He.drawing),e(i.pointer)}},s))},o))})})},dw=[{icon:d.jsx(Jd,{}),title:"Straight Arrow Line",pointer:xt.straight},{icon:d.jsx(Qd,{}),title:"Elbow Arrow Line",pointer:xt.elbow},{icon:d.jsx(eh,{}),title:"Curve Arrow Line",pointer:xt.curve}],Dl=({onPointerUp:e})=>{const t=Ye();return d.jsx(an,{padding:1,children:d.jsx(kt.Row,{gap:1,children:dw.map((n,o)=>d.jsx(je,{className:me({fillable:!1}),type:"icon",size:"small",visible:!0,icon:n.icon,tooltip:n.title,"aria-label":n.title,onPointerDown:()=>{nn(t),Re(t,He.drawing),ee.updatePointerType(t,n.pointer)},onPointerUp:()=>{e(n.pointer)}},o))})})},Ll=[{value:Kt.default,labelKey:"theme.default"},{value:Kt.colorful,labelKey:"theme.colorful"},{value:Kt.soft,labelKey:"theme.soft"},{value:Kt.retro,labelKey:"theme.retro"},{value:Kt.dark,labelKey:"theme.dark"},{value:Kt.starry,labelKey:"theme.starry"}],jl=d.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{width:"1rem",height:"1rem"},children:d.jsx("polyline",{points:"20 6 9 17 4 12"})}),Oo=e=>e===Le.hand||e===Le.selection||e===lo,Ol=d.jsx("span",{style:{width:"1rem",display:"inline-block"}}),da={hand:{icon:d.jsx(Sc,{}),titleKey:"toolbar.hand",pointer:Le.hand},selection:{icon:d.jsx(vc,{}),titleKey:"toolbar.selection",pointer:Le.selection},lasso:{icon:d.jsx(yc,{}),titleKey:"toolbar.lasso",pointer:lo},mind:{icon:d.jsx(Xi,{}),titleKey:"toolbar.mind",pointer:io.mind},text:{icon:d.jsx(wc,{}),titleKey:"toolbar.text",pointer:ge.text},freehand:{icon:d.jsx(ui,{}),titleKey:"toolbar.pen",pointer:ie.feltTipPen,hasPopup:!0,popupKey:"freehand"},arrow:{icon:d.jsx(mc,{}),titleKey:"toolbar.arrow",pointer:xt.straight,hasPopup:!0,popupKey:"arrow"},shape:{icon:d.jsx(pc,{}),titleKey:"toolbar.shape",pointer:ge.rectangle,hasPopup:!0,popupKey:"shape"},image:{icon:d.jsx(gc,{size:24}),titleKey:"toolbar.image"},"media-library":{icon:d.jsx(fc,{size:24}),titleKey:"toolbar.mediaLibrary"},"ai-image":{icon:d.jsx(Is,{}),titleKey:"toolbar.aiImage"},"ai-video":{icon:d.jsx(Cs,{}),titleKey:"toolbar.aiVideo"},theme:{icon:d.jsx(hc,{}),titleKey:"toolbar.theme",hasPopup:!0,popupKey:"theme"},"mermaid-to-drawnix":{icon:d.jsx(dc,{}),titleKey:"extraTools.mermaidToDrawnix"},"markdown-to-drawnix":{icon:d.jsx(uc,{}),titleKey:"extraTools.markdownToDrawnix"},undo:{icon:d.jsx(oc,{}),titleKey:"general.undo"},redo:{icon:d.jsx(ic,{}),titleKey:"general.redo"}},hw=({embedded:e=!1})=>{const{t}=Oe(),n=Ye(),o=F.getBoardContainer(n),{hiddenButtons:i,showButton:s}=hi(),[r,a]=p.useState(!1),[c,u]=p.useState(!1),l=p.useRef(null),h=p.useRef(null),f=p.useCallback(()=>{l.current&&(clearTimeout(l.current),l.current=null),h.current&&(clearTimeout(h.current),h.current=null)},[]),g=p.useCallback(()=>"ontouchstart"in window||navigator.maxTouchPoints>0,[]),y=p.useCallback(()=>{g()||(f(),u(!0),l.current=setTimeout(()=>{a(!0)},200))},[f,g]),m=p.useCallback(()=>{g()||(l.current&&(clearTimeout(l.current),l.current=null),h.current=setTimeout(()=>{u(!1),a(!1)},150))},[g]),w=p.useCallback(()=>{g()&&(a(E=>!E),u(!1))},[g]),S=p.useCallback(()=>{f(),u(!0)},[f]),v=p.useCallback(()=>{h.current=setTimeout(()=>{u(!1),a(!1)},150)},[]);return d.jsxs(Mt,{open:r,onOpenChange:E=>{!E&&(g()||!c)&&a(!1)},placement:e?"right-start":"bottom",sideOffset:12,children:[d.jsx(Rt,{asChild:!0,children:d.jsx("div",{onMouseEnter:y,onMouseLeave:m,onClick:w,children:d.jsx(je,{type:"icon",icon:d.jsx(th,{}),tooltip:r?void 0:t("toolbar.more"),tooltipPlacement:e?"right":"bottom","aria-label":t("toolbar.more"),selected:r,visible:!0,"data-testid":"toolbar-more","data-track":"toolbar_click_more"})})}),d.jsx(Dt,{container:o,style:{zIndex:ht.POPOVER},onMouseEnter:S,onMouseLeave:v,children:d.jsx(fw,{hiddenButtons:i,showButton:s})})]})},fw=({hiddenButtons:e,showButton:t})=>{const{t:n}=Oe(),o=Ye(),i=F.getBoardContainer(o),{openDialog:s}=Ht(),r=ac(),[a,c]=p.useState(null),[u,l]=p.useState(null),h=p.useRef({}),[f,g]=p.useState(null),y=p.useRef(null),[m,w]=p.useState(ie.feltTipPen),S=p.useCallback(()=>{c(null),l(null),Object.values(h.current).forEach(R=>{R&&clearTimeout(R)})},[]),v=p.useCallback(R=>{if(Object.values(h.current).forEach(L=>{L&&clearTimeout(L)}),u===R){l(null);return}a===R&&!u?c(null):(l(null),c(R))},[a,u]),E=p.useCallback(R=>{a&&!u||(h.current[R]&&clearTimeout(h.current[R]),Object.entries(h.current).forEach(([L,Y])=>{L!==R&&Y&&(clearTimeout(Y),h.current[L]=null)}),u&&u!==R?(c(R),l(R)):a||(h.current[R]=setTimeout(()=>{c(R),l(R)},300)))},[u,a]),C=p.useCallback(R=>{h.current[R]&&(clearTimeout(h.current[R]),h.current[R]=null),u===R&&(h.current[R]=setTimeout(()=>{c(null),l(null)},400))},[u]),D=p.useCallback(R=>{h.current[R]&&(clearTimeout(h.current[R]),h.current[R]=null)},[]),P=p.useCallback(R=>{u===R&&(c(null),l(null))},[u]),H=p.useCallback(R=>{nn(o),R===ge.text?Re(o,null):Re(o,He.dnd),ee.updatePointerType(o,R),r(R)},[o,r]),B=p.useCallback(R=>{R!==ge.text&&Re(o,He.drawing)},[o]),j=p.useCallback(R=>{const L=da[R];if(L){if(L.hasPopup&&L.popupKey){v(L.popupKey);return}switch(S(),nn(o),L.pointer&&(Oo(L.pointer)?(ee.updatePointerType(o,L.pointer),r(L.pointer)):(H(L.pointer),B(L.pointer))),R){case"image":js(o);break;case"ai-image":s(dt.aiImageGeneration);break;case"ai-video":s(dt.aiVideoGeneration);break;case"mermaid-to-drawnix":s(dt.mermaidToDrawnix);break;case"markdown-to-drawnix":s(dt.markdownToDrawnix);break;case"undo":o.undo();break;case"redo":o.redo();break}}},[o,s,H,B,S,r,v]),U=p.useCallback((R,L)=>{R.preventDefault(),R.stopPropagation(),g({buttonId:L,x:R.clientX,y:R.clientY})},[]),A=p.useCallback(()=>{g(null)},[]),I=p.useCallback(()=>{f&&(t(f.buttonId),A())},[f,t,A]);on.useEffect(()=>{if(!f)return;const R=Y=>{y.current&&!y.current.contains(Y.target)&&A()},L=Y=>{Y.key==="Escape"&&A()};return document.addEventListener("mousedown",R),document.addEventListener("keydown",L),()=>{document.removeEventListener("mousedown",R),document.removeEventListener("keydown",L)}},[f,A]);const k=p.useCallback(R=>{switch(R){case"freehand":return d.jsx(Ml,{onPointerUp:L=>{S(),r(L),w(L)}});case"shape":return d.jsx(Rl,{onPointerUp:L=>{S(),r(L)}});case"arrow":return d.jsx(Dl,{onPointerUp:L=>{S(),r(L)}});case"theme":return d.jsx(Et,{children:Ll.map(L=>{const Y=o.theme.themeColorMode===L.value;return d.jsx(ce,{icon:Y?jl:Ol,"data-track":`toolbar_click_theme_${L.value}`,onSelect:()=>{ee.updateThemeColor(o,L.value),S()},"aria-label":n(L.labelKey),selected:Y,children:n(L.labelKey)},L.value)})});default:return null}},[o,S,r,n]),T=p.useMemo(()=>{const R=Ks.find(L=>L.pointer===m);return(R==null?void 0:R.icon)||d.jsx(ui,{})},[m]),[M,O]=p.useState(!1),q=p.useCallback(()=>{var R;return d.jsx("div",{className:"more-tools-panel__zoom-row",onContextMenu:L=>U(L,"zoom"),children:d.jsxs(kt.Row,{gap:1,children:[d.jsx(je,{type:"button",icon:d.jsx(cc,{}),visible:!0,tooltip:n("zoom.out"),tooltipPlacement:"top","aria-label":n("zoom.out"),"data-track":"toolbar_click_zoom_out",onPointerUp:()=>{ee.updateZoom(o,o.viewport.zoom-.1)},className:"zoom-out-button"}),d.jsxs(Mt,{sideOffset:12,open:M,onOpenChange:L=>{O(L)},placement:"right-start",children:[d.jsx(Tt,{content:n("zoom.fit"),showArrow:!1,children:d.jsx(Rt,{asChild:!0,children:d.jsxs("div",{"aria-label":n("zoom.fit"),"data-track":"toolbar_click_zoom_menu",className:`zoom-menu-trigger ${M?"active":""}`,onPointerUp:()=>{O(!M)},children:[Number(((((R=o==null?void 0:o.viewport)==null?void 0:R.zoom)||1)*100).toFixed(0)),"%"]})})}),d.jsx(Dt,{container:i,style:{zIndex:ht.POPOVER+1},children:d.jsxs(Et,{onSelect:()=>{O(!1)},children:[d.jsx(ce,{"data-track":"toolbar_click_zoom_fit",onSelect:()=>{ee.fitViewport(o)},"aria-label":n("zoom.fit"),shortcut:"Cmd+Shift+=",children:n("zoom.fit")}),d.jsx(ce,{"data-track":"toolbar_click_zoom_fit_frame",onSelect:()=>{Os(o)},"aria-label":n("zoom.fitFrame"),children:n("zoom.fitFrame")}),d.jsx(ce,{"data-track":"toolbar_click_zoom_100",onSelect:()=>{ee.updateZoom(o,1)},"aria-label":n("zoom.100"),shortcut:"Cmd+0",children:n("zoom.100")})]})})]}),d.jsx(je,{type:"button",icon:d.jsx(lc,{}),visible:!0,tooltip:n("zoom.in"),tooltipPlacement:"top","aria-label":n("zoom.in"),"data-track":"toolbar_click_zoom_in",onPointerUp:()=>{ee.updateZoom(o,o.viewport.zoom+.1)},className:"zoom-in-button"})]})},"zoom")},[o,i,U,n,M]),le=p.useCallback(R=>{var Ce,ze,W,Q;if(R==="zoom")return q();const L=da[R];if(!L)return null;const Y=n(L.titleKey),he=R==="freehand"?T:L.icon,be=R==="undo"&&(((ze=(Ce=o.history)==null?void 0:Ce.undos)==null?void 0:ze.length)??0)<=0,ue=R==="redo"&&(((Q=(W=o.history)==null?void 0:W.redos)==null?void 0:Q.length)??0)<=0,_e=be||ue;if(L.hasPopup&&L.popupKey){const pe=L.popupKey;return d.jsx("div",{className:"more-tools-panel__item",onContextMenu:V=>U(V,R),children:d.jsxs(Mt,{open:a===pe,sideOffset:2,onOpenChange:V=>{V||S()},placement:"right-start",children:[d.jsx(Rt,{asChild:!0,children:d.jsx("div",{onMouseEnter:()=>E(pe),onMouseLeave:()=>C(pe),children:d.jsx(je,{type:"icon",icon:he,tooltip:Y,tooltipPlacement:"left","aria-label":Y,visible:!0,selected:a===pe,"data-track":`toolbar_click_${R}`,onPointerUp:()=>j(R)})})}),d.jsx(Dt,{container:i,style:{zIndex:ht.POPOVER+1},onMouseEnter:()=>D(pe),onMouseLeave:()=>P(pe),children:k(pe)})]})},R)}return d.jsx("div",{className:"more-tools-panel__item",onContextMenu:pe=>U(pe,R),children:d.jsx(je,{type:"icon",icon:he,tooltip:Y,tooltipPlacement:"right","aria-label":Y,visible:!0,selected:!1,disabled:_e,"data-track":`toolbar_click_${R}`,onPointerUp:()=>j(R)})},R)},[n,o,i,a,T,j,U,E,C,D,P,k,S,q]);return e.length===0?d.jsxs("div",{className:"more-tools-panel",children:[d.jsx("div",{className:"more-tools-panel__header",children:d.jsx("span",{className:"more-tools-panel__title",children:n("toolbar.moreTools")})}),d.jsx("div",{className:"more-tools-panel__empty",children:d.jsx("span",{className:"more-tools-panel__empty-text",children:n("toolbar.allToolsVisible")})})]}):d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"more-tools-panel",children:[d.jsx("div",{className:"more-tools-panel__header",children:d.jsx("span",{className:"more-tools-panel__title",children:n("toolbar.moreTools")})}),d.jsx("div",{className:"more-tools-panel__content",children:e.map(R=>le(R.id))}),d.jsx("div",{className:"more-tools-panel__footer",children:d.jsx("span",{className:"more-tools-panel__hint",children:n("toolbar.rightClickToAdd")})})]}),f&&nc.createPortal(d.jsx("div",{ref:y,className:"toolbar-context-menu",style:{position:"fixed",left:f.x,top:f.y,zIndex:ht.DROPDOWN_PORTAL},children:d.jsx(Et,{children:d.jsx(ce,{onSelect:I,children:n("toolbar.addToToolbar")})})}),document.body)]})},gw=p.lazy(()=>re(()=>import("./ai-chat-BnWVpTEI.js").then(e=>e.s_),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.MediaLibraryModal}))),pw=p.lazy(()=>re(()=>import("./tool-windows-Bf_pMml-.js").then(e=>e.b3),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.MinimizedToolsBar})));var Nl=(e=>(e.shape="shape",e.arrow="arrow",e.freehand="freehand",e.theme="theme",e))(Nl||{});const ha=[{icon:d.jsx(Sc,{}),pointer:Le.hand,titleKey:"toolbar.hand",visibilityKey:"hand"},{icon:d.jsx(vc,{}),pointer:Le.selection,titleKey:"toolbar.selection",visibilityKey:"selection"},{icon:d.jsx(yc,{}),pointer:lo,titleKey:"toolbar.lasso",visibilityKey:"lasso"},{icon:d.jsx(Xi,{}),pointer:io.mind,titleKey:"toolbar.mind",visibilityKey:"mind"},{icon:d.jsx(wc,{}),pointer:ge.text,titleKey:"toolbar.text",visibilityKey:"text"},{icon:d.jsx(gc,{size:24}),titleKey:"toolbar.image",key:"image",visibilityKey:"image"},{icon:d.jsx(fc,{size:24}),titleKey:"toolbar.mediaLibrary",key:"media-library",visibilityKey:"media-library"},{icon:d.jsx(Is,{}),titleKey:"toolbar.aiImage",key:"ai-image",visibilityKey:"ai-image"},{icon:d.jsx(Cs,{}),titleKey:"toolbar.aiVideo",key:"ai-video",visibilityKey:"ai-video"},{icon:d.jsx(Xi,{}),pointer:io.mind,titleKey:"toolbar.mind",visibilityKey:"mind"},{icon:d.jsx(ui,{}),pointer:ie.feltTipPen,titleKey:"toolbar.pen",key:"freehand",visibilityKey:"freehand"},{icon:d.jsx(mc,{}),titleKey:"toolbar.arrow",key:"arrow",pointer:xt.straight,visibilityKey:"arrow"},{icon:d.jsx(pc,{}),titleKey:"toolbar.shape",key:"shape",pointer:ge.rectangle,visibilityKey:"shape"},{icon:d.jsx(hc,{}),titleKey:"toolbar.theme",key:"theme",visibilityKey:"theme"},{icon:d.jsx(dc,{}),titleKey:"extraTools.mermaidToDrawnix",key:"mermaid-to-drawnix",visibilityKey:"mermaid-to-drawnix"},{icon:d.jsx(uc,{}),titleKey:"extraTools.markdownToDrawnix",key:"markdown-to-drawnix",visibilityKey:"markdown-to-drawnix"}],mw=e=>Object.keys(xt).includes(e.pointer),ww=e=>Object.keys(ge).includes(e.pointer)||Object.keys(rc).includes(e.pointer),yw=({embedded:e=!1,iconMode:t=!1,onOpenMediaLibrary:n,minimizedToolsBarEnabled:o=!1,onEnableToolWindows:i})=>{const s=Ye(),{appState:r,openDialog:a}=Ht(),{t:c}=Oe(),u=ac(),l=F.getBoardContainer(s),{visibleButtons:h,loading:f,reorderButton:g}=hi(),{getDragProps:y}=xf({items:h,getId:x=>x.id,onReorder:(x,_)=>{g(x,_,!0)},enabled:e}),[m,w]=p.useState({freehand:!1,arrow:!1,shape:!1,theme:!1}),[S,v]=p.useState(null),E=p.useRef({freehand:null,arrow:null,shape:null,theme:null}),[C,D]=p.useState(ha.find(x=>x.key==="freehand")),[P,H]=p.useState(!1),B=p.useCallback(async x=>{try{x.type===Yt.IMAGE?await nh(s,x.url):x.type===Yt.VIDEO?await Ja(s,x.url):x.type===Yt.AUDIO&&await Qa(s,x.url,{title:x.name,duration:x.duration,previewImageUrl:x.thumbnail,prompt:x.prompt,mv:x.modelName,clipId:x.clipId,providerTaskId:x.providerTaskId}),Ne.success("素材已插入到画板")}catch(_){console.error("Failed to insert asset:",_),Ne.error("插入素材失败")}},[s]),j=p.useCallback(async x=>{var z,G;if(x.length===0)return;oh("[CanvasInsertion][Toolbar] batch assets begin",{source:"creation-toolbar",strategy:"shared-batch-layout",assetsCount:x.length,assetTypes:x.map($=>$.type),zoom:((z=s==null?void 0:s.viewport)==null?void 0:z.zoom)||1});const _=await kf({items:x.map($=>$.type===Yt.IMAGE?{type:"image",content:$.url}:$.type===Yt.VIDEO?{type:"video",content:$.url}:{type:"audio",content:$.url,metadata:{title:$.name,duration:$.duration,previewImageUrl:$.thumbnail,prompt:$.prompt,mv:$.modelName,clipId:$.clipId,providerTaskId:$.providerTaskId}})});if(_.success){const $=((G=_.data)==null?void 0:G.insertedCount)??x.length;Ne.success(`已成功插入 ${$} 个素材到画板`)}else Ne.error(_.error||"插入素材失败")},[s]),U=p.useCallback(()=>{if(n){n({mode:$o.SELECT,onSelect:B,onSelectMultiple:j,selectButtonText:"插入",batchSelectButtonText:"批量插入画布"});return}H(!0)},[B,j,n]),A=p.useCallback(()=>{H(!1)},[]),I=()=>{w({freehand:!1,arrow:!1,shape:!1,theme:!1}),v(null),Object.values(E.current).forEach(x=>{x&&clearTimeout(x)})},k=x=>{v(null),Object.values(E.current).forEach(_=>{_&&clearTimeout(_)}),w({freehand:!1,arrow:!1,shape:!1,theme:!1,[x]:!0})},T=x=>{E.current[x]&&clearTimeout(E.current[x]),Object.entries(E.current).forEach(([_,z])=>{_!==x&&z&&(clearTimeout(z),E.current[_]=null)}),S&&S!==x?(w(_=>({..._,[S]:!1,[x]:!0})),v(x)):m[x]||(E.current[x]=setTimeout(()=>{w(_=>({..._,[x]:!0})),v(x)},300))},M=x=>{E.current[x]&&(clearTimeout(E.current[x]),E.current[x]=null),S===x&&(E.current[x]=setTimeout(()=>{w(_=>({..._,[x]:!1})),v(null)},200))},O=x=>{E.current[x]&&(clearTimeout(E.current[x]),E.current[x]=null)},q=x=>{S===x&&(w(_=>({..._,[x]:!1})),v(null))},le=x=>{nn(s),x===ge.text?(Re(s,null),ee.updatePointerType(s,x),u(x)):(Re(s,He.dnd),ee.updatePointerType(s,x),u(x))},R=x=>{x!==ge.text&&Re(s,He.drawing)},L=()=>Object.values(m).some(x=>x),Y=x=>F.isPointer(s,x.pointer)&&!L(),he=x=>F.isInPointer(x,[ie.feltTipPen,ie.mask,ie.eraser,ie.laserPointer,zt.pen]),be=x=>{I(),nn(s),x.pointer&&!Oo(x.pointer)?R(x.pointer):x.pointer&&Oo(x.pointer)&&(ee.updatePointerType(s,x.pointer),u(x.pointer)),x.key==="image"?js(s):x.key==="media-library"?U():x.key==="ai-image"?a(dt.aiImageGeneration):x.key==="ai-video"?a(dt.aiVideoGeneration):x.key==="mermaid-to-drawnix"?a(dt.mermaidToDrawnix):x.key==="markdown-to-drawnix"&&a(dt.markdownToDrawnix)},ue=(x,_,z)=>{const G=()=>{switch(z){case"freehand":return d.jsx(Ml,{onPointerUp:X=>{I(),u(X),D(Ks.find(oe=>oe.pointer===X))}});case"shape":return d.jsx(Rl,{onPointerUp:X=>{I(),u(X)}});case"arrow":return d.jsx(Dl,{onPointerUp:X=>{I(),u(X)}});case"theme":return d.jsx(Et,{children:Ll.map(X=>{const oe=s.theme.themeColorMode===X.value;return d.jsx(ce,{icon:oe?jl:Ol,"data-track":`toolbar_click_theme_${X.value}`,onSelect:()=>{ee.updateThemeColor(s,X.value),I()},"aria-label":c(X.labelKey),selected:oe,children:c(X.labelKey)},X.value)})})}},$=()=>{const X=m[z],oe=Object.entries(m).some(([Fe,Ve])=>Fe!==z&&Ve);switch(z){case"freehand":return X||he(s)&&!oe;case"shape":return X||ww(s)&&!F.isPointer(s,ge.text);case"arrow":return X||mw(s);default:return X}},ne=z==="freehand"?C.icon:x.icon,xe=z==="freehand"?C.titleKey?c(C.titleKey):"Freehand":x.titleKey?c(x.titleKey):"";return d.jsxs(Mt,{open:m[z],sideOffset:12,onOpenChange:X=>{X||I()},placement:e?"right-start":"bottom",children:[d.jsx(Rt,{asChild:!0,children:d.jsx("div",{onMouseEnter:()=>T(z),onMouseLeave:()=>M(z),children:d.jsx(je,{type:"icon",visible:!0,selected:$(),icon:ne,tooltip:xe,"aria-label":xe,"data-track":`toolbar_click_${z}`,onPointerDown:()=>{k(z),z==="freehand"&&C.pointer&&le(C.pointer)},onPointerUp:()=>{z==="freehand"&&R()}})})}),d.jsx(Dt,{container:l,style:{zIndex:ht.POPOVER},onMouseEnter:()=>O(z),onMouseLeave:()=>q(z),children:G()})]},_)},_e=(x,_)=>d.jsx(je,{type:"radio",icon:x.icon,checked:Y(x),tooltip:x.titleKey?c(x.titleKey):"",tooltipPlacement:e?"right":"bottom","aria-label":x.titleKey?c(x.titleKey):"","data-track":`toolbar_click_${x.pointer||x.key}`,onPointerDown:()=>{x.pointer&&!Oo(x.pointer)&&le(x.pointer)},onPointerUp:()=>{be(x)}},_),Ce=p.useMemo(()=>{const x=new Map;return ha.forEach(_=>{_.visibilityKey&&x.set(_.visibilityKey,_)}),x},[]),[ze,W]=p.useState(!1),Q=p.useCallback(x=>{var z;const _=e?kt.Col:kt.Row;return d.jsx("div",{className:me("creation-toolbar__zoom-inline",{"creation-toolbar__zoom-inline--vertical":e}),children:d.jsxs(_,{gap:0,children:[d.jsx(je,{type:"button",icon:d.jsx(cc,{}),visible:!0,tooltip:c("zoom.out"),tooltipPlacement:e?"right":"bottom","aria-label":c("zoom.out"),"data-track":"toolbar_click_zoom_out",onPointerUp:()=>{ee.updateZoom(s,s.viewport.zoom-.1)},className:"zoom-out-button"}),d.jsxs(Mt,{sideOffset:12,open:ze,onOpenChange:G=>{W(G)},placement:e?"right-start":"bottom",children:[d.jsx(Tt,{content:c("zoom.fit"),showArrow:!1,children:d.jsx(Rt,{asChild:!0,children:d.jsxs("div",{"aria-label":c("zoom.fit"),"data-track":"toolbar_click_zoom_menu",className:me("zoom-menu-trigger",{active:ze}),onPointerUp:()=>{W(!ze)},children:[Number(((((z=s==null?void 0:s.viewport)==null?void 0:z.zoom)||1)*100).toFixed(0)),"%"]})})}),d.jsx(Dt,{container:l,style:{zIndex:ht.POPOVER},children:d.jsxs(Et,{onSelect:()=>{W(!1)},children:[d.jsx(ce,{"data-track":"toolbar_click_zoom_fit",onSelect:()=>{ee.fitViewport(s)},"aria-label":c("zoom.fit"),shortcut:"Cmd+Shift+=",children:c("zoom.fit")}),d.jsx(ce,{"data-track":"toolbar_click_zoom_fit_frame",onSelect:()=>{Os(s)},"aria-label":c("zoom.fitFrame"),children:c("zoom.fitFrame")}),d.jsx(ce,{"data-track":"toolbar_click_zoom_100",onSelect:()=>{ee.updateZoom(s,1)},"aria-label":c("zoom.100"),shortcut:"Cmd+0",children:c("zoom.100")})]})})]}),d.jsx(je,{type:"button",icon:d.jsx(lc,{}),visible:!0,tooltip:c("zoom.in"),tooltipPlacement:e?"right":"bottom","aria-label":c("zoom.in"),"data-track":"toolbar_click_zoom_in",onPointerUp:()=>{ee.updateZoom(s,s.viewport.zoom+.1)},className:"zoom-in-button"})]})},`zoom-${x}`)},[s,l,e,c,ze]),pe=p.useCallback((x,_)=>{if(x==="zoom")return Q(_);const z=Ce.get(x);return!z||r.isMobile&&z.pointer===Le.hand?null:z.key&&Object.values(Nl).includes(z.key)?ue(z,_,z.key):_e(z,_)},[Ce,r.isMobile,ue,_e,Q]),V=p.useCallback((x,_,z=!0,G=-1)=>{const $=pe(x,_);if(!$)return null;const ne=y(x,_);return d.jsx(ms,{buttonId:x,isVisible:z,visibleIndex:G,children:d.jsx("div",{className:me("toolbar-button-wrapper",{"toolbar-button-wrapper--dragging":ne["data-dragging"],"toolbar-button-wrapper--drag-over":ne["data-drag-over"],"toolbar-button-wrapper--drag-before":ne["data-drag-position"]==="before","toolbar-button-wrapper--drag-after":ne["data-drag-position"]==="after"}),"data-button-id":x,...ne,children:$})},`ctx-${x}-${_}`)},[pe,y]),N=d.jsxs(kt.Row,{gap:1,children:[!f&&h.map((x,_)=>e?V(x.id,_,!0,_):pe(x.id,_)),d.jsx(hw,{embedded:e}),e&&o&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(pw,{ensureToolWindowsEnabled:i})})]}),b=P?d.jsx(p.Suspense,{fallback:null,children:d.jsx(gw,{isOpen:P,onClose:A,mode:$o.SELECT,onSelect:B,onSelectMultiple:j,selectButtonText:"插入",batchSelectButtonText:"批量插入画布"})}):null;return e?d.jsxs(d.Fragment,{children:[d.jsx("div",{className:me("draw-toolbar",{"draw-toolbar--embedded":e,"draw-toolbar--icon-only":t}),children:N}),b]}):d.jsxs(d.Fragment,{children:[d.jsx(an,{padding:1,className:me("draw-toolbar",En,{"draw-toolbar--embedded":e,"draw-toolbar--icon-only":t}),children:N}),b]})},fa="https://tuziai.oss-cn-shenzhen.aliyuncs.com/aitu/AiTu.png",vw="https://tuziai.oss-cn-shenzhen.aliyuncs.com/linkme.png",Sw=()=>{const e=Ye(),t=F.getBoardContainer(e),[n,o]=p.useState(!1);return p.useEffect(()=>{const i=new Image;i.src=fa;const s=new Image;s.src=vw},[]),d.jsxs(Mt,{placement:"right-end",sideOffset:12,open:n,onOpenChange:o,children:[d.jsx(Rt,{asChild:!0,children:d.jsx(je,{type:"icon",icon:d.jsx(ih,{}),"aria-label":"用户反馈群",tooltip:"用户反馈群",tooltipPlacement:"right",selected:n,visible:!0,"data-track":"toolbar_click_feedback",onPointerDown:i=>{i.event.stopPropagation()},onClick:()=>o(!n)})}),d.jsx(Dt,{container:t,style:{zIndex:ht.POPOVER_FEEDBACK},children:d.jsx("div",{className:"feedback-qrcode-content",children:d.jsx("div",{className:"feedback-qrcode-grid",children:d.jsxs("div",{className:"feedback-qrcode-item",children:[d.jsx("img",{src:fa,alt:"用户反馈群二维码",className:"feedback-qrcode-image"}),d.jsx("div",{className:"feedback-qrcode-text",children:"用户反馈群"})]})})})})]})},zl="aitu-task-queue-failed-ack-at";function xw(){if(typeof window>"u")return 0;try{const e=Number(window.localStorage.getItem(zl));return Number.isFinite(e)?e:0}catch{return 0}}function kw(e){typeof window>"u"||window.localStorage.setItem(zl,String(e))}function Ew(e){return e.completedAt||e.updatedAt||e.createdAt||0}const bw=({projectDrawerOpen:e,onProjectDrawerToggle:t,toolboxDrawerOpen:n=!1,onToolboxDrawerToggle:o,taskPanelExpanded:i,onTaskPanelToggle:s})=>{const{activeTasks:r,completedTasks:a,failedTasks:c}=Ef(),[u,l]=p.useState(xw),h=p.useMemo(()=>c.reduce((m,w)=>Math.max(m,Ew(w)),0),[c]),f=h>u;p.useEffect(()=>{if(!(!i||h<=u)){l(h);try{kw(h)}catch{}}},[u,h,i]);const y=r.length+a.length+c.length>0?`任务队列 (生成中: ${r.length}, 已完成: ${a.length}, 失败: ${c.length})`:"任务队列 (暂无任务)";return d.jsxs("div",{className:"bottom-actions-section",children:[d.jsx(Sw,{}),d.jsx(je,{type:"icon",icon:d.jsx(sh,{}),"aria-label":e?"关闭项目":"打开项目",tooltip:e?"关闭项目":"打开项目",tooltipPlacement:"right",selected:e,visible:!0,"data-track":"toolbar_click_project_drawer","data-testid":"toolbar-project",onPointerDown:m=>{m.event.stopPropagation()},onClick:t}),o&&d.jsx(je,{type:"icon",icon:d.jsx(rh,{}),"aria-label":n?"关闭工具箱":"打开工具箱",tooltip:n?"关闭工具箱":"打开工具箱",tooltipPlacement:"right",selected:n,visible:!0,"data-track":"toolbar_click_toolbox","data-testid":"toolbar-toolbox",onPointerDown:m=>{m.event.stopPropagation()},onClick:o}),d.jsxs("div",{className:"bottom-actions-section__task-wrapper",children:[d.jsx(ah,{count:r.length>0?r.length:0,showZero:!1,offset:[6,-6],children:d.jsx(je,{type:"icon",icon:d.jsx(ch,{}),"aria-label":"任务队列",tooltip:y,tooltipPlacement:"right",selected:i,visible:!0,"data-track":"toolbar_click_tasks","data-testid":"toolbar-tasks",onPointerDown:m=>{m.event.stopPropagation()},onClick:s})}),r.length>0&&d.jsx("div",{className:"bottom-actions-section__status bottom-actions-section__status--active"}),f&&r.length===0&&d.jsx("div",{className:"bottom-actions-section__status bottom-actions-section__status--failed"})]})]})},_w=p.lazy(()=>re(()=>import("./TaskQueuePanel-PayswYlG.js"),__vite__mapDeps([0,1,3,4]),import.meta.url).then(e=>({default:e.TaskQueuePanel}))),Pw=460,Tw=["ai-image","ai-video"],Fl="aitu-toolbar-left",Ct=0,Cw=8,Iw=0,fo=58;function ys(e,t=fo){const n=typeof window>"u"?t:window.innerWidth,o=Math.max(Ct,n-t-Iw);return Math.round(Math.max(Ct,Math.min(e,o)))}function Aw(e,t=fo){return typeof window>"u"?"left":e+t/2>window.innerWidth/2?"right":"left"}function Mw(){if(typeof window>"u")return Ct;try{const e=window.localStorage.getItem(Fl);if(!e)return Ct;const t=Number(e);return Number.isFinite(t)?ys(t):Ct}catch{return Ct}}function ga(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Fl,String(e))}catch{}}function pa(e,t){if(typeof document>"u")return;const n=t==null?void 0:t.getBoundingClientRect(),o=n&&n.width>0?n.width:fo,i=typeof window>"u"?e+o:window.innerWidth,s=Math.round(e+o),r=Aw(e,o),a=r==="right"?Math.max(0,i-e):0,c=r==="right"?e:Math.max(0,i-s),u=document.documentElement.style;u.setProperty("--aitu-toolbar-left",`${e}px`),u.setProperty("--aitu-toolbar-right-edge",`${s}px`),u.setProperty("--aitu-toolbar-right-dock-width",`${Math.round(a)}px`),u.setProperty("--aitu-toolbar-right-avoidance",`${Math.round(a?a+12:0)}px`),u.setProperty("--aitu-toolbar-side-panel-max-width",`${Math.max(0,Math.round(c))}px`);const l=document.documentElement;l.classList.toggle("aitu-toolbar-dock-right",r==="right"),l.classList.toggle("aitu-toolbar-dock-left",r==="left"),t==null||t.style.setProperty("--aitu-toolbar-left",`${e}px`)}const Rw=on.memo(({className:e,projectDrawerOpen:t=!1,onProjectDrawerToggle:n,toolboxDrawerOpen:o=!1,onToolboxDrawerToggle:i,taskPanelExpanded:s=!1,onTaskPanelToggle:r,onOpenBackupRestore:a,onOpenCloudSync:c,onOpenMediaLibrary:u,deferredFeaturesEnabled:l=!1,minimizedToolsBarEnabled:h=!1,onEnableToolWindows:f})=>{const[g,y]=p.useState(!1),[m,w]=p.useState(!0),[S,v]=p.useState(Mw),[E,C]=p.useState(!1),[D,P]=p.useState(!1),H=p.useRef(!1),B=p.useRef(null),j=p.useRef(null),U=p.useRef(!1),A=p.useRef(S),I=p.useRef(null),{isMobile:k,isTablet:T}=lh(),M=k||T,O=M?Cw:S;uh(B,{enablePositionTracking:!1,enableScaleCompensation:!0}),p.useEffect(()=>{A.current=O,pa(O,B.current)},[O]),p.useEffect(()=>()=>{document.documentElement.classList.remove("aitu-toolbar-dock-left","aitu-toolbar-dock-right")},[]),p.useEffect(()=>{if(typeof document>"u")return;const W=document.documentElement;return W.classList.toggle("aitu-toolbar-dragging",E),()=>{W.classList.remove("aitu-toolbar-dragging")}},[E]),p.useEffect(()=>{if(M)return;const W=()=>{var pe;const Q=((pe=B.current)==null?void 0:pe.getBoundingClientRect().width)||fo;v(V=>ys(V,Q))};return window.addEventListener("resize",W),()=>{window.removeEventListener("resize",W)}},[M]),p.useEffect(()=>{if(!s){P(!1);return}if(!H.current)return;const W=requestAnimationFrame(()=>{P(!0)});return()=>{cancelAnimationFrame(W)}},[s]);const q=p.useCallback(W=>{M||W.button!==0||(W.preventDefault(),W.stopPropagation(),I.current={pointerId:W.pointerId,startX:W.clientX,startLeft:A.current},document.documentElement.classList.add("aitu-toolbar-dragging"),W.currentTarget.setPointerCapture(W.pointerId),C(!0))},[M]),le=p.useCallback(W=>{var N;const Q=I.current;if(!Q||Q.pointerId!==W.pointerId)return;W.preventDefault();const pe=((N=B.current)==null?void 0:N.getBoundingClientRect().width)||fo,V=ys(Q.startLeft+W.clientX-Q.startX,pe);A.current=V,pa(V,B.current)},[]),R=p.useCallback(W=>{const Q=I.current;!Q||Q.pointerId!==W.pointerId||(I.current=null,document.documentElement.classList.remove("aitu-toolbar-dragging"),C(!1),v(A.current),ga(A.current),W.currentTarget.hasPointerCapture(W.pointerId)&&W.currentTarget.releasePointerCapture(W.pointerId))},[]),L=p.useCallback(W=>{M||(W.preventDefault(),W.stopPropagation(),A.current=Ct,v(Ct),ga(Ct))},[M]),Y=p.useCallback(W=>{if(W[0]){const Q=W[0].contentRect.height;y(Q<Pw)}},[]);p.useEffect(()=>{const W=B.current;if(!W)return;const Q=new ResizeObserver(Y);return Q.observe(W),()=>{Q.disconnect()}},[Y]),p.useEffect(()=>{if(U.current)return;const W=j.current;if(!W)return;const Q=()=>{U.current=!0;let V=null;for(const _ of Tw){const z=W.querySelector(`[data-button-id="${_}"]`);if(z){V=z;break}}if(!V)return;const N=W.getBoundingClientRect(),b=V.getBoundingClientRect();if(!(b.bottom<=N.bottom&&b.top>=N.top)&&N.height>0){const _=b.top-N.top;W.scrollTop+=_}},pe=setTimeout(()=>{requestAnimationFrame(Q)},100);return()=>{clearTimeout(pe)}},[]);const he=p.useCallback(()=>{!s&&!H.current&&(H.current=!0),s||P(!1),r==null||r()},[s,r]),be=p.useCallback(()=>{s&&(P(!1),r==null||r())},[s,r]),ue=p.useCallback(()=>{w(W=>!W)},[]),{openDialog:_e}=Ht(),Ce=p.useCallback(()=>{_e(dt.aiImageGeneration)},[_e]),ze=p.useCallback(()=>{_e(dt.aiVideoGeneration)},[_e]);return d.jsxs(d.Fragment,{children:[H.current&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(_w,{expanded:s&&D,onClose:be})}),d.jsxs(an,{ref:B,className:me("unified-toolbar",En,{"unified-toolbar--icon-only":g||M,"unified-toolbar--mobile-collapsed":M&&m,"unified-toolbar--dragging":E},e),style:{"--aitu-toolbar-left":`${O}px`},padding:0,"data-testid":"unified-toolbar",children:[!M&&d.jsx(Tt,{content:"拖动工具栏位置,双击复位",showArrow:!1,children:d.jsx("button",{type:"button",className:"unified-toolbar__drag-handle","aria-label":"拖动工具栏位置,双击复位","data-testid":"toolbar-drag-handle",onPointerDown:q,onPointerMove:le,onPointerUp:R,onPointerCancel:R,onDoubleClick:L})}),M&&m&&d.jsxs("div",{className:"unified-toolbar__collapsed-shortcuts",children:[d.jsx("button",{className:"unified-toolbar__collapsed-btn unified-toolbar__collapsed-btn--toggle",onClick:ue,"aria-label":"展开工具栏",children:d.jsx(dh,{size:18})}),d.jsx("button",{className:"unified-toolbar__collapsed-btn",onClick:Ce,"aria-label":"AI 图片生成",children:d.jsx(Is,{})}),d.jsx("button",{className:"unified-toolbar__collapsed-btn",onClick:ze,"aria-label":"AI 视频生成",children:d.jsx(Cs,{})})]}),M&&!m&&d.jsx("button",{className:"unified-toolbar__mobile-toggle unified-toolbar__mobile-toggle--expanded",onClick:ue,"aria-label":"收起工具栏",children:d.jsx(hh,{size:18})}),d.jsx("div",{className:"unified-toolbar__section unified-toolbar__section--fixed-top",children:d.jsx(Zm,{embedded:!0,iconMode:g||M,onOpenBackupRestore:a,onOpenCloudSync:c})}),d.jsx("div",{ref:j,className:"unified-toolbar__scrollable",children:d.jsx("div",{className:"unified-toolbar__section",children:d.jsx(yw,{embedded:!0,iconMode:g||M,onOpenMediaLibrary:u,deferredFeaturesEnabled:l,minimizedToolsBarEnabled:h,onEnableToolWindows:f})})}),d.jsx("div",{className:"unified-toolbar__section unified-toolbar__section--fixed-bottom",children:d.jsx(bw,{projectDrawerOpen:t,onProjectDrawerToggle:n||(()=>{}),toolboxDrawerOpen:o,onToolboxDrawerToggle:i,taskPanelExpanded:s,onTaskPanelToggle:he})})]})]})}),Dw="#f5f5f5",Lw="rgba(0, 0, 0, 0.6)";function jw(e,t){const n=Math.max(4,Math.min(256,t)),o=n+4,i=o/2,s=n/2,r=`<svg width="${o}" height="${o}" viewBox="0 0 ${o} ${o}" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
8
8
|
<circle cx="${i}" cy="${i}" r="${s}" fill="${e}" stroke="#fff" stroke-width="1"/>
|
|
9
9
|
<circle cx="${i}" cy="${i}" r="${s}" fill="none" stroke="#333" stroke-width="0.5" stroke-opacity="0.5"/>
|
|
10
10
|
</svg>`;return`url('data:image/svg+xml;base64,${btoa(r)}') ${i} ${i}, crosshair`}function Ow(e,t){const n=Math.max(4,Math.min(256,t)),o=n+4,i=o/2,s=n/2,r=`<svg width="${o}" height="${o}" viewBox="0 0 ${o} ${o}" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
11
11
|
<rect x="${i-s}" y="${i-s}" width="${n}" height="${n}" fill="${e}" stroke="#fff" stroke-width="1"/>
|
|
12
12
|
<rect x="${i-s}" y="${i-s}" width="${n}" height="${n}" fill="none" stroke="#333" stroke-width="0.5" stroke-opacity="0.5"/>
|
|
13
|
-
</svg>`;return`url('data:image/svg+xml;base64,${btoa(r)}') ${i} ${i}, crosshair`}function ma(e,t,n=so.circle){return n===so.square?Ow(e,t):jw(e,t)}function Bl(e){return xc().includes(e)&&e!==ie.eraser}function Hl(e){return e===ie.eraser}function eo(e,t){var r;const n=document.querySelector(".plait-board-container"),o=n==null?void 0:n.querySelector(".board-host-svg");if(!o)return;const i=bn(e),s=((r=e.viewport)==null?void 0:r.zoom)||1;if(Bl(t)){const a=i.strokeWidth*s,c=t===ie.mask?Lw:i.strokeColor,u=ma(c,a,i.pencilShape);o.style.cursor=u}else if(Hl(t)){const a=i.eraserWidth*s,c=ma(Dw,a,i.eraserShape);o.style.cursor=c}else t===ge.text?o.style.cursor="crosshair":o.style.cursor=""}function Nw({board:e,pointer:t}){const n=p.useRef(1),o=p.useRef(null);return p.useEffect(()=>{var r;if(!e)return;eo(e,t),n.current=((r=e.viewport)==null?void 0:r.zoom)||1;let s=null;return(Bl(t)||Hl(t))&&(s=setInterval(()=>{var c;const a=((c=e.viewport)==null?void 0:c.zoom)||1;Math.abs(a-n.current)>.01&&(n.current=a,eo(e,t))},100)),()=>{s&&clearInterval(s),o.current&&cancelAnimationFrame(o.current);const a=document.querySelector(".plait-board-container"),c=a==null?void 0:a.querySelector(".board-host-svg");c&&(c.style.cursor="")}},[e,t]),{updateCursor:p.useCallback(()=>{e&&eo(e,t)},[e,t])}}function zw(e,t){eo(e,t)}function Fw(e){eo(e,ie.eraser)}const ji=1,wa=100,Bw=256,ya=1;let Oi=0;function Ni(e,t,n){return Math.max(t,Math.min(n,e))}function Hw(e){return e.key==="-"||e.key==="+"||e.key==="ArrowUp"||e.key==="ArrowRight"||e.key==="ArrowDown"||e.key==="ArrowLeft"||e.code==="NumpadAdd"||e.code==="NumpadSubtract"}function $w(e){return e.key==="-"||e.key==="ArrowDown"||e.key==="ArrowLeft"||e.code==="NumpadSubtract"?-ya:ya}function zi(e,t){var o;const n=((o=e.appState)==null?void 0:o.toolSettingsVersion)??0;Oi=Math.max(Oi,n)+1,t({toolSettingsVersion:Oi})}function Vw(e,t,n){if(!Hw(t)||t.altKey||t.metaKey||t.ctrlKey)return!1;const o=$w(t);if(F.isInPointer(e,[ie.eraser])){const i=bn(e),s=Ni(i.eraserWidth+o,ji,Bw);return fh(e,s),Fw(e),zi(e,n),!0}if(F.isInPointer(e,[ie.feltTipPen,ie.mask])){const i=bn(e),s=Ni(i.strokeWidth+o,ji,wa);return gh(e,s),zw(e,e.pointer),zi(e,n),!0}if(F.isInPointer(e,[zt.pen])){const i=Vc(e),s=Ni(i.strokeWidth+o,ji,wa);return bf(e,s),zi(e,n),!0}return!1}const Ww=e=>n=>{const{globalKeyDown:o,keyDown:i}=n;return n.globalKeyDown=s=>{const r=s.target instanceof HTMLInputElement||s.target instanceof HTMLTextAreaElement||s.target instanceof HTMLElement&&s.target.isContentEditable;if(!r){if(ve.isHotkey(["mod+k"])(s)){e({openCommandPalette:!0}),s.preventDefault();return}if(ve.isHotkey(["mod+f"])(s)){e({openCanvasSearch:!0}),s.preventDefault();return}}if(!r&&(F.getMovingPointInBoard(n)||F.isMovingPointInBoard(n))&&!F.hasBeenTextEditing(n)){if(ve.isHotkey(["mod+shift+e"],{byKey:!0})(s)){Do(n,!0),s.preventDefault();return}if(ve.isHotkey(["mod+s"],{byKey:!0})(s)){Bc(n),s.preventDefault();return}if(ve.isHotkey(["mod+backspace"])(s)||ve.isHotkey(["mod+delete"])(s)){e({openCleanConfirm:!0}),s.preventDefault();return}if(ve.isHotkey(["mod+u"])(s)&&js(n),Te(n).length>1){if(ve.isHotkey(["alt+a"])(s)){ln.alignLeft(n),s.preventDefault();return}if(ve.isHotkey(["alt+h"])(s)){ln.alignCenter(n),s.preventDefault();return}if(ve.isHotkey(["alt+d"])(s)){ln.alignRight(n),s.preventDefault();return}if(ve.isHotkey(["alt+w"])(s)){ln.alignTop(n),s.preventDefault();return}if(ve.isHotkey(["alt+v"])(s)){ln.alignMiddle(n),s.preventDefault();return}if(ve.isHotkey(["alt+s"])(s)){ln.alignBottom(n),s.preventDefault();return}if(ve.isHotkey(["shift+h"])(s)){Ei.distributeHorizontal(n),s.preventDefault();return}if(ve.isHotkey(["shift+v"])(s)){Ei.distributeVertical(n),s.preventDefault();return}if(ve.isHotkey(["shift+a"])(s)){Ei.autoArrange(n),s.preventDefault();return}if(ve.isHotkey(["alt+shift+u"])(s)){Cn.union(n,"zh"),s.preventDefault();return}if(ve.isHotkey(["alt+shift+s"])(s)){Cn.subtract(n,"zh"),s.preventDefault();return}if(ve.isHotkey(["alt+shift+i"])(s)){Cn.intersect(n,"zh"),s.preventDefault();return}if(ve.isHotkey(["alt+shift+e"])(s)){Cn.exclude(n,"zh"),s.preventDefault();return}if(ve.isHotkey(["alt+shift+f"])(s)){Cn.flatten(n,"zh"),s.preventDefault();return}}if(!s.altKey&&!s.metaKey&&!s.ctrlKey&&ve.isHotkey(["shift+p"],{byKey:!0})(s)){Re(n,He.drawing),ee.updatePointerType(n,zt.pen),e({pointer:zt.pen}),s.preventDefault();return}if(!s.altKey&&!s.metaKey&&!s.ctrlKey&&ve.isHotkey(["shift+m"],{byKey:!0})(s)){Re(n,He.drawing),ee.updatePointerType(n,ie.mask),e({pointer:ie.mask}),s.preventDefault();return}if(Vw(n,s,e)){s.preventDefault();return}if(!s.altKey&&!s.metaKey&&!s.ctrlKey&&!s.shiftKey){if(s.key==="l"){Re(n,He.drawing),ee.updatePointerType(n,ie.laserPointer),e({pointer:ie.laserPointer}),s.preventDefault();return}const c=[ie.feltTipPen,ie.mask,ie.eraser,ie.laserPointer];if(s.key==="Escape"&&F.isInPointer(n,c)){ee.updatePointerType(n,Le.selection),e({pointer:Le.selection}),s.preventDefault();return}if(s.key==="Backspace"&&F.isInPointer(n,[ie.feltTipPen,ie.mask])){n.undo(),s.preventDefault();return}if(s.key==="h"&&(ee.updatePointerType(n,Le.hand),e({pointer:Le.hand})),s.key==="v"&&(ee.updatePointerType(n,Le.selection),e({pointer:Le.selection})),s.key==="q"&&(ee.updatePointerType(n,lo),e({pointer:lo})),s.key==="m"&&(Re(n,He.dnd),ee.updatePointerType(n,io.mind),e({pointer:io.mind})),s.key==="e"&&(Re(n,He.drawing),ee.updatePointerType(n,ie.eraser),e({pointer:ie.eraser})),s.key==="p"&&(Re(n,He.drawing),ee.updatePointerType(n,ie.feltTipPen),e({pointer:ie.feltTipPen})),s.key==="a"&&!ve.isHotkey(["mod+a"])(s)&&Te(n).length===0&&(Re(n,He.drawing),ee.updatePointerType(n,xt.straight),e({pointer:xt.straight})),s.key==="f"&&(Re(n,He.drawing),ee.updatePointerType(n,fr),e({pointer:fr})),s.key==="r"||s.key==="o"||s.key==="t"){const u={r:ge.rectangle,o:ge.ellipse,t:ge.text};u[s.key]===ge.text?Re(n,null):Re(n,He.drawing),ee.updatePointerType(n,u[s.key]),e({pointer:u[s.key]})}s.preventDefault();return}}o(s)},n.keyDown=s=>{if(ve.isHotkey(["mod+z"],{byKey:!0})(s)){n.undo(),s.preventDefault();return}if(ve.isHotkey(["mod+shift+z"],{byKey:!0})(s)){n.redo(),s.preventDefault();return}i(s)},n};function qs(e){return e===so.square?"square":"round"}function Ys(e,t){const n=Math.min(t/50,1),o=.2+n*.1,i=6-n*4,s=o+e*(i-o);return Math.max(.5,t*s)}function Uw(e,t,n,o,i,s){const r=document.createElementNS("http://www.w3.org/2000/svg","g"),a=qs(s);if(e.length<2){if(e.length===1){const f=Ys(t[0]??.5,n);if(s===so.square){const g=document.createElementNS("http://www.w3.org/2000/svg","rect");g.setAttribute("x",String(e[0][0]-f/2)),g.setAttribute("y",String(e[0][1]-f/2)),g.setAttribute("width",String(f)),g.setAttribute("height",String(f)),g.setAttribute("fill",o),r.appendChild(g)}else{const g=document.createElementNS("http://www.w3.org/2000/svg","circle");g.setAttribute("cx",String(e[0][0])),g.setAttribute("cy",String(e[0][1])),g.setAttribute("r",String(f/2)),g.setAttribute("fill",o),r.appendChild(g)}}return r}const c=As(e,1,3);if(i===Ec.double){const f=n*.8,g=n*.4,[y,m]=Kw(c,t,g,f);if(y){const w=document.createElementNS("http://www.w3.org/2000/svg","path");w.setAttribute("d",y),w.setAttribute("fill",o),w.setAttribute("stroke","none"),r.appendChild(w)}if(m){const w=document.createElementNS("http://www.w3.org/2000/svg","path");w.setAttribute("d",m),w.setAttribute("fill",o),w.setAttribute("stroke","none"),r.appendChild(w)}return r}const u=kc(i,n),l=i!==Gn.solid&&u?u.join(" "):"",h=qw(c,t,n);if(h.length>0){const f=document.createElementNS("http://www.w3.org/2000/svg","path");f.setAttribute("d",h),f.setAttribute("fill",o),f.setAttribute("stroke","none"),l&&(f.setAttribute("fill","none"),f.setAttribute("stroke",o),f.setAttribute("stroke-width",String(n)),f.setAttribute("stroke-dasharray",l),f.setAttribute("stroke-linecap",a),f.setAttribute("stroke-linejoin",a==="square"?"miter":"round")),r.appendChild(f)}return r}function Gw(e,t,n,o){const i=document.createElementNS("http://www.w3.org/2000/svg","g"),s=qs(o);if(e.length<2){if(e.length===1){const m=t*.8,w=t*.4;if(o===so.square){const S=document.createElementNS("http://www.w3.org/2000/svg","rect");S.setAttribute("x",String(e[0][0]-w/2)),S.setAttribute("y",String(e[0][1]-m/2-w/2)),S.setAttribute("width",String(w)),S.setAttribute("height",String(w)),S.setAttribute("fill",n),i.appendChild(S);const v=document.createElementNS("http://www.w3.org/2000/svg","rect");v.setAttribute("x",String(e[0][0]-w/2)),v.setAttribute("y",String(e[0][1]+m/2-w/2)),v.setAttribute("width",String(w)),v.setAttribute("height",String(w)),v.setAttribute("fill",n),i.appendChild(v)}else{const S=document.createElementNS("http://www.w3.org/2000/svg","circle");S.setAttribute("cx",String(e[0][0])),S.setAttribute("cy",String(e[0][1]-m/2)),S.setAttribute("r",String(w/2)),S.setAttribute("fill",n),i.appendChild(S);const v=document.createElementNS("http://www.w3.org/2000/svg","circle");v.setAttribute("cx",String(e[0][0])),v.setAttribute("cy",String(e[0][1]+m/2)),v.setAttribute("r",String(w/2)),v.setAttribute("fill",n),i.appendChild(v)}}return i}const r=As(e,1,3),a=t*.8,c=t*.4,u=[],l=[];for(let m=0;m<r.length;m++){let w,S;m===0?(w=r[1][0]-r[0][0],S=r[1][1]-r[0][1]):m===r.length-1?(w=r[m][0]-r[m-1][0],S=r[m][1]-r[m-1][1]):(w=r[m+1][0]-r[m-1][0],S=r[m+1][1]-r[m-1][1]);const v=Math.sqrt(w*w+S*S);if(v>0){const E=-S/v,C=w/v,D=a/2;u.push([r[m][0]+E*D,r[m][1]+C*D]),l.push([r[m][0]-E*D,r[m][1]-C*D])}else u.push(r[m]),l.push(r[m])}const h=document.createElementNS("http://www.w3.org/2000/svg","path");let f=`M ${u[0][0]} ${u[0][1]}`;for(let m=1;m<u.length;m++){const w=u[m-1],S=u[m],v=(w[0]+S[0])/2,E=(w[1]+S[1])/2;f+=` Q ${w[0]} ${w[1]} ${v} ${E}`}f+=` L ${u[u.length-1][0]} ${u[u.length-1][1]}`,h.setAttribute("d",f),h.setAttribute("fill","none"),h.setAttribute("stroke",n),h.setAttribute("stroke-width",String(c)),h.setAttribute("stroke-linecap",s),h.setAttribute("stroke-linejoin",s==="square"?"miter":"round"),i.appendChild(h);const g=document.createElementNS("http://www.w3.org/2000/svg","path");let y=`M ${l[0][0]} ${l[0][1]}`;for(let m=1;m<l.length;m++){const w=l[m-1],S=l[m],v=(w[0]+S[0])/2,E=(w[1]+S[1])/2;y+=` Q ${w[0]} ${w[1]} ${v} ${E}`}return y+=` L ${l[l.length-1][0]} ${l[l.length-1][1]}`,g.setAttribute("d",y),g.setAttribute("fill","none"),g.setAttribute("stroke",n),g.setAttribute("stroke-width",String(c)),g.setAttribute("stroke-linecap",s),g.setAttribute("stroke-linejoin",s==="square"?"miter":"round"),i.appendChild(g),i}function Kw(e,t,n,o){if(e.length<2)return["",""];const i=[],s=[];for(let c=0;c<e.length;c++){let u,l;c===0?(u=e[1][0]-e[0][0],l=e[1][1]-e[0][1]):c===e.length-1?(u=e[c][0]-e[c-1][0],l=e[c][1]-e[c-1][1]):(u=e[c+1][0]-e[c-1][0],l=e[c+1][1]-e[c-1][1]);const h=Math.sqrt(u*u+l*l);if(h>0){const f=-l/h,g=u/h,y=o/2;i.push([e[c][0]+f*y,e[c][1]+g*y]),s.push([e[c][0]-f*y,e[c][1]-g*y])}else i.push(e[c]),s.push(e[c])}const r=va(i,t,n),a=va(s,t,n);return[r,a]}function va(e,t,n){if(e.length<2)return"";const o=[],i=[];for(let r=0;r<e.length;r++){const a=t[r]??.5,u=Ys(a,n)/2;let l,h;r===0?(l=e[1][0]-e[0][0],h=e[1][1]-e[0][1]):r===e.length-1?(l=e[r][0]-e[r-1][0],h=e[r][1]-e[r-1][1]):(l=e[r+1][0]-e[r-1][0],h=e[r+1][1]-e[r-1][1]);const f=Math.sqrt(l*l+h*h);if(f>0){const g=-h/f,y=l/f;o.push([e[r][0]+g*u,e[r][1]+y*u]),i.push([e[r][0]-g*u,e[r][1]-y*u])}else o.push(e[r]),i.push(e[r])}let s=`M ${o[0][0]} ${o[0][1]}`;for(let r=1;r<o.length;r++){const a=o[r-1],c=o[r],u=(a[0]+c[0])/2,l=(a[1]+c[1])/2;s+=` Q ${a[0]} ${a[1]} ${u} ${l}`}s+=` L ${o[o.length-1][0]} ${o[o.length-1][1]}`,s+=` L ${i[i.length-1][0]} ${i[i.length-1][1]}`;for(let r=i.length-2;r>=0;r--){const a=i[r+1],c=i[r],u=(a[0]+c[0])/2,l=(a[1]+c[1])/2;s+=` Q ${a[0]} ${a[1]} ${u} ${l}`}return s+=` L ${i[0][0]} ${i[0][1]}`,s+=" Z",s}function qw(e,t,n){if(e.length<2)return"";const o=[],i=[];for(let r=0;r<e.length;r++){const a=t[r]??.5,u=Ys(a,n)/2;let l,h;r===0?(l=e[1][0]-e[0][0],h=e[1][1]-e[0][1]):r===e.length-1?(l=e[r][0]-e[r-1][0],h=e[r][1]-e[r-1][1]):(l=e[r+1][0]-e[r-1][0],h=e[r+1][1]-e[r-1][1]);const f=Math.sqrt(l*l+h*h);if(f>0){const g=-h/f,y=l/f;o.push([e[r][0]+g*u,e[r][1]+y*u]),i.push([e[r][0]-g*u,e[r][1]-y*u])}else o.push(e[r]),i.push(e[r])}let s=`M ${o[0][0]} ${o[0][1]}`;for(let r=1;r<o.length;r++){const a=o[r-1],c=o[r],u=(a[0]+c[0])/2,l=(a[1]+c[1])/2;s+=` Q ${a[0]} ${a[1]} ${u} ${l}`}s+=` L ${o[o.length-1][0]} ${o[o.length-1][1]}`,s+=` L ${i[i.length-1][0]} ${i[i.length-1][1]}`;for(let r=i.length-2;r>=0;r--){const a=i[r+1],c=i[r],u=(a[0]+c[0])/2,l=(a[1]+c[1])/2;s+=` Q ${a[0]} ${a[1]} ${u} ${l}`}return s+=` L ${i[0][0]} ${i[0][1]}`,s+=" Z",s}class Xs extends ci{draw(t){const n=ph(t),o=mh(this.board,t),i=wh(this.board,t),s=yh(this.board,t),r=kc(s,n),a=t.brushShape,c=qs(a),u=f=>(f&&t.shape===ie.mask&&f.setAttribute("opacity",String(Sh)),f);if(t.pressures&&t.pressures.length>0)return u(Uw(t.points,t.pressures,n,o,s,a));if(s===Ec.double)return u(Gw(t.points,n,o,a));const l={strokeWidth:n,stroke:o,fill:i,fillStyle:"solid",strokeLineDash:s!==Gn.solid?r:void 0},h=F.getRoughSVG(this.board).curve(As(t.points,1,3),l);return vh(h,c),u(h)}canDraw(t){return!0}}class Yw extends wo{constructor(){super()}initializeGenerator(){this.activeGenerator=_s(this.board,{getRectangle:t=>di(t),getStrokeWidth:()=>no,getStrokeOpacity:()=>1,hasResizeHandle:()=>li(this.board,this.element)}),this.generator=new Xs(this.board)}initialize(){super.initialize(),this.initializeGenerator(),this.generator.processDrawing(this.element,this.getElementG())}onContextChanged(t,n){const o=t.board.viewport.zoom!==n.board.viewport.zoom||t.board.viewport.offsetX!==n.board.viewport.offsetX||t.board.viewport.offsetY!==n.board.viewport.offsetY;t.element!==n.element||t.hasThemeChanged?(this.generator.processDrawing(this.element,this.getElementG()),this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})):o&&t.selected?this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected}):(t.selected!==n.selected||t.selected)&&this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})}destroy(){var t;super.destroy(),(t=this.activeGenerator)==null||t.destroy()}}class $l{constructor(t={}){this.defaultOptions={smoothing:.65,velocityWeight:.2,curvatureWeight:.3,minDistance:.2,maxPoints:8,pressureSensitivity:.5,tiltSensitivity:.3,velocityThreshold:800,samplingRate:5},this.points=[],this.lastProcessedTime=0,this.movingAverageVelocity=[],this.velocityWindowSize=3,this.options={...this.defaultOptions,...t}}process(t,n={}){const o=n.timestamp??Date.now();if(this.points.length===0){const c={point:t,timestamp:o,...n};return this.points.push(c),this.lastProcessedTime=o,t}if(o-this.lastProcessedTime<this.options.samplingRate&&o-this.lastProcessedTime<2)return null;const i={point:t,timestamp:o,...n};if(!this.checkDistance(t)&&this.points.length>1&&o-this.lastProcessedTime<32)return null;this.updatePoints(i);const r=this.calculateDynamicParameters(i),a=this.smooth(t,r);return this.lastProcessedTime=o,a}reset(){this.points=[],this.lastProcessedTime=0,this.movingAverageVelocity=[]}updatePoints(t){this.points.push(t),this.points.length>this.options.maxPoints&&this.points.shift()}checkDistance(t){if(this.points.length===0)return!0;const n=this.points[this.points.length-1].point,o=this.getDistance(n,t);let i=this.options.minDistance;if(this.movingAverageVelocity.length>0){const s=this.getAverageVelocity();i*=Math.max(.5,Math.min(1.5,s/200))}return o>=i}calculateDynamicParameters(t){const n=this.calculateVelocity(t);this.updateMovingAverage(n);const o=this.getAverageVelocity(),i={...this.options};if(t.pressure!==void 0){const r=Math.pow(t.pressure,1.2);i.smoothing*=1-r*i.pressureSensitivity*.8}const s=Math.min(o/i.velocityThreshold,1);if(i.velocityWeight=.2+s*.3,i.smoothing*=1+s*.2,t.tiltX!==void 0&&t.tiltY!==void 0){const r=Math.sqrt(t.tiltX**2+t.tiltY**2)/90;i.smoothing*=1+r*i.tiltSensitivity*.7}return i}smooth(t,n){if(this.points.length<2)return t;const o=this.calculateWeights(n),i=o.reduce((r,a)=>r+a,0);if(i===0)return t;const s=[0,0];for(let r=0;r<this.points.length;r++){const a=o[r]/i;s[0]+=this.points[r].point[0]*a,s[1]+=this.points[r].point[1]*a}return s}calculateWeights(t){const n=[],o=this.points.length-1;for(let i=0;i<this.points.length;i++){let s=Math.pow(t.smoothing,(o-i)*.8);if(i<o){const r=this.getPointVelocity(i);s*=1+r*t.velocityWeight*.8}if(i>0&&i<o){const r=this.getPointCurvature(i);s*=1+r*t.curvatureWeight*.7}n.push(s)}return n}getDistance(t,n){return Bo(t[0],t[1],n[0],n[1])}calculateVelocity(t){if(this.points.length<2)return 0;const n=this.points[this.points.length-1],o=this.getDistance(n.point,t.point),i=t.timestamp-n.timestamp;return i>0?o/i:0}updateMovingAverage(t){this.movingAverageVelocity.push(t),this.movingAverageVelocity.length>this.velocityWindowSize&&this.movingAverageVelocity.shift()}getAverageVelocity(){return this.movingAverageVelocity.length===0?0:this.movingAverageVelocity.reduce((t,n)=>t+n)/this.movingAverageVelocity.length}getPointVelocity(t){if(t>=this.points.length-1)return 0;const n=this.points[t],o=this.points[t+1],i=this.getDistance(n.point,o.point),s=o.timestamp-n.timestamp;return s>0?i/s:0}getPointCurvature(t){if(t<=0||t>=this.points.length-1)return 0;const n=this.points[t-1].point,o=this.points[t].point,i=this.points[t+1].point,s=this.getDistance(n,o),r=this.getDistance(o,i),a=this.getDistance(n,i),c=(s+r+a)/2;return 4*Math.sqrt(Math.max(0,c*(c-s)*(c-r)*(c-a)))/(s*r*a+1e-4)}}const Xw=e=>{const{pointerDown:t,pointerMove:n,pointerUp:o,globalPointerUp:i}=e;let s=!1,r=!1,a=[],c=[],u=null;const l=new Xs(e),h=new $l({smoothing:.7,pressureSensitivity:.6});let f=null,g=!1,y=null,m=null,w=0;const S=(C=!1)=>{if(!y||C){const D=bn(e);y={strokeWidth:D.strokeWidth,strokeColor:D.strokeColor,strokeStyle:D.strokeStyle,pencilShape:D.pencilShape,pressureEnabled:D.pressureEnabled}}return y},v=(C,D)=>{if(!D)return 1;if(C.pointerType==="pen"&&C.pressure>0&&C.pressure!==.5)return C.pressure;const H=[C.x,C.y],B=performance.now();if(m&&w>0){const j=H[0]-m[0],U=H[1]-m[1],A=Math.sqrt(j*j+U*U),I=B-w;if(I>0){const k=A/I,T=.2,M=1,q=Math.min(k/1.5,1),le=M-q*(M-T);return m=H,w=B,le}}return m=H,w=B,.6},E=C=>{if(s){const D=F.getPointer(e);r&&(a.push(a[0]),c.length>0&&c.push(c[0]));const P=S();f=Zi(D,a,{strokeWidth:P.strokeWidth,strokeColor:P.strokeColor,strokeStyle:P.strokeStyle,brushShape:P.pencilShape,pressures:P.pressureEnabled?c:void 0})}f&&!C&&Se.insertNode(e,f,[e.children.length]),l==null||l.destroy(),f=null,s=!1,a=[],c=[],m=null,w=0,y=null,h.reset()};return e.pointerDown=C=>{if(mi(e,C)){g=!0,t(C);return}const D=xc();if(F.isInPointer(e,D)&&Ms(e)){s=!0;const H=S(!0);u=[C.x,C.y];const B=h.process(u);if(B){const j=Xe(e,Ze(e,B[0],B[1]));a.push(j),c.push(v(C,H.pressureEnabled))}}t(C)},e.pointerMove=C=>{if(g){n(C);return}if(s){const D=[C.x,C.y];u&&Bo(u[0],u[1],D[0],D[1])<8?r=!0:r=!1;const P=h.process(D);if(P){l==null||l.destroy();const H=Xe(e,Ze(e,P[0],P[1]));a.push(H);const B=S();c.push(v(C,B.pressureEnabled));const j=F.getPointer(e);f=Zi(j,a,{strokeWidth:B.strokeWidth,strokeColor:B.strokeColor,strokeStyle:B.strokeStyle,brushShape:B.pencilShape,pressures:B.pressureEnabled?c:void 0}),l.processDrawing(f,F.getElementTopHost(e))}return}n(C)},e.pointerUp=C=>{if(g){g=!1,o(C);return}E(),o(C)},e.globalPointerUp=C=>{g=!1,E(!0),i(C)},e},Zw=e=>{const t=e,{getDeletedFragment:n,buildFragment:o,insertFragment:i}=t;return t.getDeletedFragment=s=>{const r=gr(t);return r.length&&s.push(...r),n(s)},t.buildFragment=(s,r,a,c)=>{const u=gr(t);if(u.length){const l=bc(t,u,r?[r.x,r.y]:[0,0]);s=Rs(s,{text:"",type:Ds.elements,elements:l})}return o(s,r,a,c)},t.insertFragment=(s,r,a)=>{var u;const c=(u=s==null?void 0:s.elements)==null?void 0:u.filter(l=>De.isFreehand(l));c&&c.length>0&&_c(t,c,r),i(s,r,a)},t};function Vl(e){const t=Te(e);return t.length===1&&De.isFreehand(t[0])?t[0]:null}function Jw(e){return Vl(e)!==null}function Qw(e,t){const n=Vl(e);if(!n)return null;const o=di(n),i=n.angle||0,s=rn(o,t,i);return s?{element:n,rectangle:o,handle:s.handle,cursorClass:s.cursorClass}:null}function e0(e,t,n){const o=n.width/t.width,i=n.height/t.height;return e.map(s=>{const r=s[0]-t.x,a=s[1]-t.y;return[n.x+r*o,n.y+a*i]})}function t0(e,t,n){const{element:o,rectangle:i,handle:s}=t,{startPoint:r,endPoint:a}=n;if(!i)return;const c=a[0]-r[0],u=a[1]-r[1],l=Tn(i,s,c,u,vo(),10),h=e0(o.points,i,l),f=e.children.findIndex(g=>g.id===o.id);f>=0&&Se.setNode(e,{points:h},[f])}const n0=e=>sn(e,{key:"freehand",canResize:()=>Jw(e),hitTest:(t=>Qw(e,t)),onResize:(t,n)=>t0(e,t,n)}),go=1e3;async function Zs(){const e=await re(()=>import("./clipper-CpI1VJRD.js").then(t=>t.c),[],import.meta.url);return e.default||e}function po(e){return e.map(t=>({X:Math.round(t[0]*go),Y:Math.round(t[1]*go)}))}function Wl(e){return e.map(t=>[t.X/go,t.Y/go])}async function o0(e,t,n=pr.circle){if(e.length<2)return[];const o=await Zs(),i=po(e),s=new o.ClipperOffset;n===pr.square?s.AddPath(i,o.JoinType.jtMiter,o.EndType.etOpenSquare):s.AddPath(i,o.JoinType.jtRound,o.EndType.etOpenRound);const r=[];return s.Execute(r,t/2*go),r.length===0?[]:Wl(r[0])}function Js(e){const t=e.points;if(!t||t.length<3)return!1;const n=t[0],o=t[t.length-1];return Math.hypot(o[0]-n[0],o[1]-n[1])<=10}function i0(e,t=20){if($e.isPenPath(e)){if(!e.closed)return null;const n=Hc(e);return _f(n,!0,t)}if(De.isFreehand(e)){const n=e.points;return!n||n.length<3||!Js(e)?null:n}return K.isDrawElement(e)&&K.isShapeElement(e)?K.isImage(e)||K.isText(e)?null:s0(e,t):null}function s0(e,t=20){const n=e.points;if(!n||n.length<2)return[];const[o,i]=n,s=Math.min(o[0],i[0]),r=Math.min(o[1],i[1]),a=Math.abs(i[0]-o[0]),c=Math.abs(i[1]-o[1]),u=e.shape;if(u==="ellipse"||u==="circle"){const l=s+a/2,h=r+c/2,f=a/2,g=c/2,y=[],m=Math.PI*(3*(f+g)-Math.sqrt((3*f+g)*(f+3*g))),w=Math.max(180,Math.ceil(m/2));for(let S=0;S<w;S++){const v=2*Math.PI*S/w;y.push([l+f*Math.cos(v),h+g*Math.sin(v)])}return y}return[[s,r],[s+a,r],[s+a,r+c],[s,r+c]]}function r0(e,t,n,o){if(e.length<3)throw new Error("Polygon must have at least 3 points");let i=1/0,s=1/0,r=-1/0,a=-1/0;for(const h of e)i=Math.min(i,h[0]),s=Math.min(s,h[1]),r=Math.max(r,h[0]),a=Math.max(a,h[1]);const c=[i,s],u=e.map(h=>({point:[h[0]-c[0],h[1]-c[1]],type:"corner"}));return{id:Pc(),type:Tc,shape:zt.pen,points:[c,[r,a]],anchors:u,closed:!0,strokeColor:t,fill:n,strokeWidth:o}}function a0(e){let t="#333333",n="#FFFFFF",o=2;return $e.isPenPath(e)?(t=e.strokeColor||t,n=e.fill||n,o=e.strokeWidth||o):De.isFreehand(e)?(t=e.strokeColor||t,o=e.strokeWidth||o):K.isDrawElement(e)&&(t=e.strokeColor||t,n=e.fill||n,o=e.strokeWidth||o),{strokeColor:t,fill:n,strokeWidth:o}}async function c0(e,t){const n=await Zs(),o=new n.Clipper,i=[];return o.AddPath(po(e),n.PolyType.ptSubject,!0),o.AddPath(po(t),n.PolyType.ptClip,!0),o.Execute(n.ClipType.ctIntersection,i,n.PolyFillType.pftNonZero,n.PolyFillType.pftNonZero),i.length>0}async function l0(e,t,n){const o=i0(t);if(!o||o.length<3||!await c0(o,n))return null;const s=await Zs(),r=new s.Clipper,a=[];if(r.AddPath(po(o),s.PolyType.ptSubject,!0),r.AddPath(po(n),s.PolyType.ptClip,!0),!r.Execute(s.ClipType.ctDifference,a,s.PolyFillType.pftNonZero,s.PolyFillType.pftNonZero))return null;const{strokeColor:u,fill:l,strokeWidth:h}=a0(t),f=[];for(const v of a)if(v.length>=3){let E=0;for(let C=0;C<v.length;C++){const D=(C+1)%v.length;E+=v[C].X*v[D].Y,E-=v[D].X*v[C].Y}E=E/2,f.push({path:v,signedArea:E,absArea:Math.abs(E)})}if(f.length===0)return[];const g=[...f].sort((v,E)=>E.absArea-v.absArea),y=g[0],m=g.slice(1);let w;m.length>0?w=u0(y.path,m.map(v=>v.path)):w=y.path;const S=Wl(w);try{return[r0(S,u,l,h)]}catch{return[]}}function u0(e,t){let n=[...e];for(const o of t){let i=1/0,s=0,r=0;for(let c=0;c<n.length;c++)for(let u=0;u<o.length;u++){const l=n[c].X-o[u].X,h=n[c].Y-o[u].Y,f=l*l+h*h;f<i&&(i=f,s=c,r=u)}const a=[];for(let c=0;c<=s;c++)a.push(n[c]);for(let c=0;c<o.length;c++){const u=(r+c)%o.length;a.push(o[u])}a.push(o[r]);for(let c=s;c<n.length;c++)a.push(n[c]);n=a}return n}function Ul(e){if(De.isFreehand(e)){const i=e.points;if(!i||i.length<2)return null;const s=de.getRectangleByPoints(i),r=e.strokeWidth??2,a=r/2;return{x:s.x-a,y:s.y-a,width:s.width+r,height:s.height+r}}if($e.isPenPath(e)){const i=e.points;if(!i||i.length<2)return null;const[s,r]=i;return{x:Math.min(s[0],r[0]),y:Math.min(s[1],r[1]),width:Math.abs(r[0]-s[0]),height:Math.abs(r[1]-s[1])}}const t=e.points;if(!t||t.length<2)return null;const[n,o]=t;return{x:Math.min(n[0],o[0]),y:Math.min(n[1],o[1]),width:Math.abs(o[0]-n[0]),height:Math.abs(o[1]-n[1])}}function d0(e,t,n){if(t.length<2)return[];let o=1/0,i=1/0,s=-1/0,r=-1/0;for(const c of t)o=Math.min(o,c[0]-n),i=Math.min(i,c[1]-n),s=Math.max(s,c[0]+n),r=Math.max(r,c[1]+n);const a=[];for(const c of e.children){if(!h0(c))continue;const u=Ul(c);if(!u)continue;const{x:l,y:h,width:f,height:g}=u;l+f>=o&&l<=s&&h+g>=i&&h<=r&&a.push(c)}return a}function h0(e){return $e.isPenPath(e)?e.closed:De.isFreehand(e)?Js(e):K.isDrawElement(e)?K.isImage(e)||K.isText(e)||K.isArrowLine(e)||K.isVectorLine(e)?!1:K.isShapeElement(e):!1}function f0(e){if($e.isPenPath(e))return e.closed?null:"openPath";if(De.isFreehand(e))return Js(e)?null:"openPath";if(K.isDrawElement(e)){if(K.isImage(e))return"image";if(K.isText(e))return"text";if(K.isArrowLine(e))return"arrowLine";if(K.isVectorLine(e))return"vectorLine";if(K.isShapeElement(e))return null}return"unsupported"}function g0(e,t,n){if(t.length<2)return[];let o=1/0,i=1/0,s=-1/0,r=-1/0;for(const c of t)o=Math.min(o,c[0]-n),i=Math.min(i,c[1]-n),s=Math.max(s,c[0]+n),r=Math.max(r,c[1]+n);const a=[];for(const c of e.children){const u=Ul(c);if(!u)continue;const{x:l,y:h,width:f,height:g}=u;l+f>=o&&l<=s&&h+g>=i&&h<=r&&f0(c)&&a.push(c)}return a}async function p0(e,t,n,o,i){if(i.length===0)return;const s=await o0(t,n,o);if(s.length<3)return;const r=[],a=[];for(const c of i){const u=await l0(e,c,s);u!==null&&(r.push(c),a.push(...u))}r.length>0&&Ji.removeElements(e,r);for(const c of a)Se.insertNode(e,c,[e.children.length])}const m0=e=>{const{pointerDown:t,pointerMove:n,pointerUp:o,globalPointerUp:i}=e;let s=!1,r=!1;const a=new Set;let c=[];const u=f=>{const g=Xe(e,Ze(e,f[0],f[1])),m=bn(e).eraserWidth/2;e.children.filter(S=>De.isFreehand(S)).forEach(S=>{!a.has(S.id)&&xh(e,S,g,m)&&(vn.getElementG(S).style.opacity="0.2",a.add(S.id))})},l=()=>{if(a.size>0){const f=e.children.filter(g=>a.has(g.id));f.length>0&&Ji.removeElements(e,f)}},h=async()=>{if(s){if(l(),c.length>=2){const f=bn(e),g=d0(e,c,f.eraserWidth).filter(m=>!De.isFreehand(m));if(g.length>0)try{await p0(e,c,f.eraserWidth,f.eraserShape,g)}catch(m){console.error("Precise erase error:",m)}const y=g0(e,c,f.eraserWidth).filter(m=>!De.isFreehand(m)&&!So(m)&&!kh(m)&&!(K.isDrawElement(m)&&K.isImage(m)));y.length>0&&Ji.removeElements(e,y)}s=!1,a.clear(),c=[]}};return e.pointerDown=f=>{if(mi(e,f)){r=!0,t(f);return}if(F.isInPointer(e,[ie.eraser])&&Ms(e)){s=!0,a.clear(),c=[];const y=[f.x,f.y],m=Xe(e,Ze(e,y[0],y[1]));c.push(m),u(y);return}t(f)},e.pointerMove=f=>{if(r){n(f);return}if(s){Ts(e,"with-freehand-erase",()=>{const g=[f.x,f.y],y=Xe(e,Ze(e,g[0],g[1]));c.push(y),u(g)});return}n(f)},e.pointerUp=f=>{if(r){r=!1,o(f);return}if(s){h();return}o(f)},e.globalPointerUp=f=>{if(r=!1,s){h();return}i(f)},e},w0="#e91e63",y0=3,Sa=2e3,v0=e=>{const{pointerDown:t,pointerMove:n,pointerUp:o,globalPointerUp:i}=e;let s=!1,r=[];const a=new Xs(e),c=new $l({smoothing:.7,pressureSensitivity:0});let u=null;const l=[],h=()=>F.isPointer(e,ie.laserPointer),f=()=>{if(!s)return;s=!1;const y=a.g;y?(a.g=void 0,g(y)):a.destroy(),u=null,r=[],c.reset()},g=y=>{y.style.transition=`opacity ${Sa}ms ease-out`,y.style.opacity="1",y.getBoundingClientRect(),y.style.opacity="0";const m=window.setTimeout(()=>{y.remove();const w=l.findIndex(S=>S.g===y);w>=0&&l.splice(w,1)},Sa);l.push({g:y,timer:m})};return e.pointerDown=y=>{if(h()&&Ms(e)){s=!0;const m=[y.x,y.y],w=c.process(m);if(w){const S=Xe(e,Ze(e,w[0],w[1]));r.push(S)}return}t(y)},e.pointerMove=y=>{if(s){const m=[y.x,y.y],w=c.process(m);if(w){a.destroy();const S=Xe(e,Ze(e,w[0],w[1]));r.push(S),u=Zi(ie.laserPointer,r,{strokeWidth:y0,strokeColor:w0}),a.processDrawing(u,F.getElementTopHost(e))}return}n(y)},e.pointerUp=y=>{s&&f(),o(y)},e.globalPointerUp=y=>{s&&f(),i(y)},e},S0=e=>{const{getRectangle:t,drawElement:n,isHit:o,isRectangleHit:i,getOneHitElement:s,isMovable:r,isAlign:a}=e;return e.drawElement=c=>De.isFreehand(c.element)?Yw:n(c),e.getRectangle=c=>De.isFreehand(c)?di(c):t(c),e.isRectangleHit=(c,u)=>De.isFreehand(c)?Eh(e,c,u):i(c,u),e.isHit=(c,u,l)=>De.isFreehand(c)?bh(e,c,u):o(c,u,l),e.getOneHitElement=c=>c.every(l=>De.isFreehand(l))?Cc(e,c):s(c),e.isMovable=c=>De.isFreehand(c)?!0:r(c),e.isAlign=c=>De.isFreehand(c)?!0:a(c),e.setPluginOptions(Ic,{customGeometryTypes:[_h]}),v0(n0(m0(Zw(Xw(e)))))};class x0 extends wo{constructor(){super()}initializeGenerator(){this.activeGenerator=_s(this.board,{getRectangle:t=>fi(t),getStrokeWidth:()=>no,getStrokeOpacity:()=>1,hasResizeHandle:()=>li(this.board,this.element)}),this.generator=new Qm(this.board)}initialize(){super.initialize(),this.initializeGenerator(),this.generator.processDrawing(this.element,this.getElementG()),this.selected&&this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})}onContextChanged(t,n){const o=t.board.viewport.zoom!==n.board.viewport.zoom||t.board.viewport.offsetX!==n.board.viewport.offsetX||t.board.viewport.offsetY!==n.board.viewport.offsetY;t.element!==n.element||t.hasThemeChanged?(this.generator.processDrawing(this.element,this.getElementG()),this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})):o&&t.selected?this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected}):(t.selected!==n.selected||t.selected)&&this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})}destroy(){var t;super.destroy(),(t=this.activeGenerator)==null||t.destroy()}}const k0=e=>e,E0=e=>{const t=e,{getDeletedFragment:n,buildFragment:o,insertFragment:i}=t;return t.getDeletedFragment=s=>{const r=Er(t);return r.length&&s.push(...r),n(s)},t.buildFragment=(s,r,a,c)=>{const u=Er(t);if(u.length){const l=bc(t,u,r?[r.x,r.y]:[0,0]);s=Rs(s,{text:"",type:Ds.elements,elements:l})}return o(s,r,a,c)},t.insertFragment=(s,r,a)=>{var u;const c=(u=s==null?void 0:s.elements)==null?void 0:u.filter(l=>$e.isPenPath(l));c&&c.length>0&&_c(t,c,r),i(s,r,a)},t};function Gl(e){const t=Te(e);return t.length===1&&$e.isPenPath(t[0])?t[0]:null}function b0(e){return Gl(e)!==null}function _0(e,t){const n=Gl(e);if(!n)return null;const o=fi(n),i=n.angle||0,s=rn(o,t,i);return s?{element:n,rectangle:o,handle:s.handle,cursorClass:s.cursorClass}:null}function P0(e,t,n){return e.map(o=>({...o,point:[o.point[0]*t,o.point[1]*n],handleIn:o.handleIn?[o.handleIn[0]*t,o.handleIn[1]*n]:void 0,handleOut:o.handleOut?[o.handleOut[0]*t,o.handleOut[1]*n]:void 0}))}function T0(e,t,n){const{element:o,rectangle:i,handle:s}=t,{startPoint:r,endPoint:a}=n;if(!i)return;const c=a[0]-r[0],u=a[1]-r[1],l=Tn(i,s,c,u,vo(),10),h=l.width/i.width,f=l.height/i.height,g=P0(o.anchors,h,f),m=[[l.x,l.y],[l.x+l.width,l.y+l.height]],w=e.children.findIndex(S=>S.id===o.id);w>=0&&Se.setNode(e,{points:m,anchors:g},[w])}const C0=e=>sn(e,{key:"pen-path",canResize:()=>b0(e),hitTest:(t=>_0(e,t)),onResize:(t,n)=>T0(e,t,n)}),I0=e=>{const{getRectangle:t,drawElement:n,isHit:o,isRectangleHit:i,getOneHitElement:s,isMovable:r,isAlign:a}=e;return e.drawElement=c=>$e.isPenPath(c.element)?x0:n(c),e.getRectangle=c=>$e.isPenPath(c)?fi(c):t(c),e.isRectangleHit=(c,u)=>$e.isPenPath(c)?Pf(e,c,u):i(c,u),e.isHit=(c,u,l)=>$e.isPenPath(c)?Tf(e,c,u):o(c,u,l),e.getOneHitElement=c=>c.every(l=>$e.isPenPath(l))?Cc(e,c):s(c),e.isMovable=c=>$e.isPenPath(c)?!0:r(c),e.isAlign=c=>$e.isPenPath(c)?!0:a(c),e.setPluginOptions(Ic,{customGeometryTypes:[Tc]}),C0(E0(k0(aw(e))))},Kl=new WeakMap,xa=e=>!!Kl.get(e),ql=(e,t)=>{Kl.set(e,t)},A0=e=>n=>{const{pointerDown:o}=n;return n.pointerDown=i=>{mr(i)&&!xa(n)&&(ql(n,!0),e({isPencilMode:!0})),!(xa(n)&&!mr(i)&&!mi(n,i))&&o(i)},n},M0=()=>{const e=Ye(),{appState:t,setAppState:n}=Ht();return d.jsx(d.Fragment,{children:t.isPencilMode&&d.jsx("div",{className:"pencil-mode-toolbar",children:d.jsx(je,{type:"button",visible:!0,tooltip:"X Pencil","aria-label":"Arrow",label:"Pencil X",onPointerDown:()=>{n({...t,isPencilMode:!1}),ql(e,!1)}})})})},ka=e=>{const{appState:t}=e;return t&&t.linkState&&t.linkState.isHovering},Ea=e=>{const{appState:t}=e;return t&&t.linkState&&t.linkState.isEditing},R0=e=>n=>{const{pointerMove:o}=n;let i=null,s=null;return n.pointerMove=r=>{(F.isPointer(n,Le.selection)||F.isPointer(n,Le.hand))&&!Qi(n)&&!Xa(n)&&!ka(n)&&!Ea(n)&&Ts(n,"with-text-link",()=>{const a=r.target.closest(".plait-board-link");if(a&&a!==i){const c=a.closest(".plait-text-container"),u=mn.toSlateNode(void 0,c),l=mn.toSlateNode(void 0,a);i=a,e({linkState:{targetDom:a,targetElement:l,editor:u,isEditing:!1,isHovering:!1,isHoveringOrigin:!0}}),clearTimeout(s)}else!a&&i&&(s=setTimeout(()=>{!ka(n)&&!Ea(n)&&e({linkState:null})},300),i=null)}),o(r)},n},Wn={autoTrack:!1,debounceTime:500,retryPolicy:{maxRetries:3,retryInterval:2e3,exponentialBackoff:!0},cacheConfig:{maxCacheSize:100,cacheTTL:3600*1e3,storageKey:"tracking_cache"},logLevel:"error",batchConfig:{batchSize:10,batchTimeout:5e3,enabled:!0},excludedSelectors:["nav","header","footer","[data-track-ignore]"],devMode:!1};function D0(){return"1.0.0"}function ba(e){return{...Wn,...e,retryPolicy:{...Wn.retryPolicy,...e.retryPolicy||{}},cacheConfig:{...Wn.cacheConfig,...e.cacheConfig||{}},batchConfig:{...Wn.batchConfig,...e.batchConfig||{}}}}class L0{isAvailable(){return tt.isAnalyticsEnabled()}async track(t){if(!this.isAvailable())return;const n={...t.params,version:t.metadata.version,url:t.metadata.url,timestamp:t.metadata.timestamp,sessionId:t.metadata.sessionId,eventType:t.metadata.eventType};t.metadata.viewport&&(n.viewport=`${t.metadata.viewport.width}x${t.metadata.viewport.height}`);try{tt.track(t.eventName,n)}catch(o){throw console.error("[Tracking] PostHog track failed:",o),o}}async trackBatch(t){const n=[];for(const o of t)try{await this.track(o),n.push({success:!0})}catch(i){n.push({success:!1,error:i})}return n}getSDKInfo(){return{available:this.isAvailable(),version:this.isAvailable()?"PostHog JS":void 0}}}const _a=new L0;class j0{constructor(t){this.queue=[],this.timer=null,this.uploading=!1,this.config=t}enqueue(t){if(!this.config.enabled){this.uploadImmediate(t);return}this.queue.push(t),this.timer||(this.timer=setTimeout(()=>{this.flush()},this.config.batchTimeout)),this.queue.length>=this.config.batchSize&&this.flush()}async flush(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),this.queue.length===0||this.uploading)return;this.uploading=!0;const t=[...this.queue];this.queue=[];try{const n=await _a.trackBatch(t),o=n.filter(i=>!i.success);if(o.length>0){console.error(`Batch upload: ${o.length}/${t.length} events failed`);const i=t.filter((s,r)=>!n[r].success);this.requeueFailedEvents(i)}}catch(n){console.error("Batch upload failed:",n),this.requeueFailedEvents(t)}finally{this.uploading=!1}}async uploadImmediate(t){try{await _a.track(t)}catch(n){console.error("Immediate upload failed:",n)}}requeueFailedEvents(t){this.queue=[...t,...this.queue]}getQueueSize(){return this.queue.length}isUploading(){return this.uploading}updateConfig(t){this.config={...this.config,...t},!this.config.enabled&&this.queue.length>0&&this.flush()}clear(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.queue=[],this.uploading=!1}flushOnUnload(){this.queue.length!==0&&this.flush()}}class O0{constructor(t=500){this.debounceMap=new WeakMap,this.globalDebounceMap=new Map,this.globalDebounceTime=200,this.debounceTime=t}shouldTrack(t,n,o=!1){const i=Date.now(),s=this.globalDebounceMap.get(n);if(s&&i-s<this.globalDebounceTime)return o&&console.warn(`[Tracking] 🚫 Global debounce: ${n} (${i-s}ms ago)`),!1;const r=this.debounceMap.get(t);if(!r){const c=new Map;return c.set(n,i),this.debounceMap.set(t,c),this.globalDebounceMap.set(n,i),!0}const a=r.get(n);return!a||i-a>this.debounceTime?(r.set(n,i),this.globalDebounceMap.set(n,i),!0):(o&&console.warn(`[Tracking] 🚫 Element debounce: ${n} (${i-a}ms ago)`),!1)}clear(t){this.debounceMap.delete(t)}setDebounceTime(t){this.debounceTime=t}}const N0=["button:not([data-track-ignore])","a:not([data-track-ignore])",'input[type="button"]:not([data-track-ignore])','input[type="submit"]:not([data-track-ignore])','[role="button"]:not([data-track-ignore])','[role="link"]:not([data-track-ignore])'].join(", ");function z0(e,t){if(!e.matches(N0))return!1;for(const o of t)if(e.matches(o)||e.closest(o))return!1;return e.hasAttribute("data-track-ignore")?!1:(e.onclick!==null,!0)}function F0(e,t="click"){var a;const n=`auto_${t}_`;if(e.id)return`${n}${e.id}`;const o=e.getAttribute("aria-label");if(o)return`${n}${Pa(o)}`;const i=(a=e.textContent)==null?void 0:a.trim();if(i&&i.length>0){const c=Pa(i.substring(0,20));return`${n}${c}`}const s=e.tagName.toLowerCase(),r=e.className?`.${e.className.split(" ")[0]}`:"";return`${n}${s}${r}`}function Pa(e){return e.toLowerCase().trim().replace(/\s+/g,"_").replace(/[^a-z0-9_-]/g,"").substring(0,50)}function B0(e){if(e.id)return`#${e.id}`;const t=[];let n=e;for(;n&&n!==document.body;){let o=n.tagName.toLowerCase();if(n.className){const i=n.className.split(" ").filter(Boolean);i.length>0&&(o+=`.${i[0]}`)}t.unshift(o),n=n.parentElement}return t.join(" > ")}function Fi(e){const t=e.getAttribute("data-track-params")||e.getAttribute("track-params");if(!t)return null;try{return JSON.parse(t)}catch(n){return console.warn("Invalid track params JSON on element:",e,n),null}}function Yl(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function H0(){if(typeof window>"u")return"server-side";const e="tracking_session_id";let t=sessionStorage.getItem(e);return t||(t=Yl(),sessionStorage.setItem(e,t)),t}function $0(){return typeof window>"u"?{width:0,height:0}:{width:window.innerWidth||0,height:window.innerHeight||0}}class V0{constructor(t={}){this.state$=new Ph({initialized:!1,config:Wn,pendingEvents:[],uploading:!1,cachedEventCount:0,stats:{totalEvents:0,successfulUploads:0,failedUploads:0,batchUploadCount:0,debouncedEvents:0}}),this.clickListener=null,this.mutationObserver=null,this.attachedListeners=new WeakMap,this.config=ba(t),this.batchService=new j0(this.config.batchConfig),this.debouncer=new O0(this.config.debounceTime),this.updateState({config:this.config,initialized:!1})}initialize(){if(this.state$.value.initialized){this.log("debug","Tracking service already initialized");return}this.setupClickDelegation(),this.setupMultiEventListeners(),this.setupMutationObserver(),this.setupBeforeUnload(),this.updateState({initialized:!0}),this.log("debug","Tracking service initialized")}setupClickDelegation(){typeof window>"u"||typeof document>"u"||(this.clickListener=t=>{const n=t.target;if(!n)return;const o=n.closest("[data-track]");if(o){const i=o.getAttribute("data-track");if(i){if(this.isElementExcluded(o))return;this.trackClick(o,i);return}}if(this.config.autoTrack&&z0(n,this.config.excludedSelectors)){if(this.isElementExcluded(n))return;const i=F0(n,"click");this.trackClick(n,i)}},document.body.addEventListener("click",this.clickListener,!0))}setupMultiEventListeners(){if(typeof document>"u")return;document.querySelectorAll("[track-hover]").forEach(o=>{this.attachHoverListener(o)}),document.querySelectorAll("[track-focus]").forEach(o=>{this.attachFocusListener(o)})}attachHoverListener(t){const n=t.getAttribute("track-hover");if(!n||this.hasAttachedListener(t,"hover"))return;const o=()=>{if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents");return}const i=Fi(t),s=this.createTrackEvent(n,i,"hover",t);this.track(s)};t.addEventListener("mouseenter",o),this.markListenerAttached(t,"hover")}attachFocusListener(t){const n=t.getAttribute("track-focus");if(!n||this.hasAttachedListener(t,"focus"))return;const o=()=>{if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents");return}const i=Fi(t),s=this.createTrackEvent(n,i,"focus",t);this.track(s)};t.addEventListener("focus",o,!0),this.markListenerAttached(t,"focus")}hasAttachedListener(t,n){const o=this.attachedListeners.get(t);return o?o.has(n):!1}markListenerAttached(t,n){let o=this.attachedListeners.get(t);o||(o=new Set,this.attachedListeners.set(t,o)),o.add(n)}setupMutationObserver(){typeof window>"u"||typeof MutationObserver>"u"||(this.mutationObserver=new MutationObserver(t=>{t.forEach(n=>{n.addedNodes.forEach(o=>{if(o.nodeType===Node.ELEMENT_NODE){const i=o;i.hasAttribute("track-hover")&&this.attachHoverListener(i),i.hasAttribute("track-focus")&&this.attachFocusListener(i),i.querySelectorAll("[track-hover]").forEach(a=>this.attachHoverListener(a)),i.querySelectorAll("[track-focus]").forEach(a=>this.attachFocusListener(a))}})})}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}))}trackClick(t,n){if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents"),this.log("debug",`Event debounced: ${n}`);return}const o=Fi(t),i=this.createTrackEvent(n,o,"click",t);this.track(i)}createTrackEvent(t,n,o,i){const s={timestamp:Date.now(),url:typeof window<"u"?window.location.href:"",version:D0(),sessionId:H0(),userAgent:typeof navigator<"u"?navigator.userAgent:void 0,viewport:$0(),eventType:o},r={eventName:t,params:n||void 0,metadata:s,id:Yl(),createdAt:Date.now()};return this.config.devMode&&this.log("debug",`Event created: ${t}`,{params:n,element:i?B0(i):void 0}),r}track(t){this.incrementStat("totalEvents"),this.batchService.enqueue(t),this.log("debug",`Event tracked: ${t.eventName}`)}isElementExcluded(t){if(t.hasAttribute("data-track-ignore"))return!0;for(const n of this.config.excludedSelectors)if(t.matches(n)||t.closest(n))return!0;return!1}setupBeforeUnload(){typeof window>"u"||window.addEventListener("beforeunload",()=>{this.batchService.flushOnUnload()})}getState(){return this.state$.asObservable()}getStats(){return this.state$.value.stats}updateConfig(t){this.config=ba({...this.config,...t}),t.batchConfig&&this.batchService.updateConfig(t.batchConfig),t.debounceTime&&this.debouncer.setDebounceTime(t.debounceTime),this.updateState({config:this.config}),this.log("debug","Configuration updated",t)}destroy(){this.clickListener&&typeof document<"u"&&(document.body.removeEventListener("click",this.clickListener,!0),this.clickListener=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.attachedListeners=new WeakMap,this.batchService.flush(),this.updateState({initialized:!1}),this.log("debug","Tracking service destroyed")}updateState(t){this.state$.next({...this.state$.value,...t})}incrementStat(t){const n={...this.state$.value.stats};n[t]++,this.updateState({stats:n})}log(t,n,o){this.config.logLevel!=="silent"&&(t==="error"||t==="debug"&&this.config.devMode)}}let Pt=null;function W0(){Pt&&(Pt.destroy(),Pt=null)}function U0(e,t){return Pt||(Pt=new V0(t),typeof window<"u"&&setTimeout(()=>{Pt==null||Pt.initialize()},0),typeof module<"u"&&module.hot&&module.hot.dispose(()=>{W0()})),e.trackingService=Pt,e}class G0 extends wo{initialize(){super.initialize()}}const K0=e=>{const{drawElement:t}=e;return e.drawElement=n=>{try{return t(n)}catch{return console.warn(`[Drawnix] Unknown element type "${n.element.type}" — may be from a newer version, hidden but preserved.`),G0}},e};function q0(e){const t=Te(e);return t.length!==1?!1:Wc(t[0])}function Y0(e,t){const n=Te(e);if(n.length!==1||!Wc(n[0]))return null;const o=n[0],i=de.getRectangleByPoints(o.points),s=o.angle||0,r=rn(i,t,s);return r?{element:o,rectangle:i,handle:r.handle,cursorClass:r.cursorClass}:null}function X0(e,t,n){const{element:o,rectangle:i,handle:s}=t,{startPoint:r,endPoint:a}=n;if(!i){console.warn("startRectangle is undefined");return}const c=a[0]-r[0],u=a[1]-r[1],l=Tn(i,s,c,u,vo(),100),h=[[l.x,l.y],[l.x+l.width,l.y+l.height]],f=e.children.findIndex(g=>g.id===o.id);f>=0&&Se.setNode(e,{points:h},[f])}const Z0=e=>sn(e,{key:"tool-elements",canResize:()=>q0(e),hitTest:(t=>Y0(e,t)),onResize:(t,n)=>X0(e,t,n)});let Jo=null;function J0(e,t){return De.isFreehand(t)?di(t):$e.isPenPath(t)?fi(t):e.getRectangle(t)}function Qs(e){return e.some(t=>De.isFreehand(t)||$e.isPenPath(t)||K.isText(t))}function Q0(e){return e.some(t=>K.isText(t))}function Xl(e){const t=Te(e);if(t.length<2||!Qs(t))return null;try{const n=Ft(e,t,!1);return{elements:t,rectangle:n}}catch{return null}}function ey(e){return Xl(e)!==null}function ty(e,t){const n=Xl(e);if(!n)return null;const o=rn(n.rectangle,t);if(o){Jo=new Map;for(const i of n.elements){const s=J0(e,i);s&&Jo.set(i.id,{element:JSON.parse(JSON.stringify(i)),rectangle:{...s}})}return{element:n.elements,rectangle:n.rectangle,handle:o.handle,cursorClass:o.cursorClass}}return null}function ny(e,t,n,o,i,s){const r=s.width/i.width,a=s.height/i.height,c=o.x-i.x,u=o.y-i.y,l=s.x+c*r,h=s.y+u*a,f=n.points.map(y=>{const m=y[0]-o.x,w=y[1]-o.y,S=m*r,v=w*a;return[l+S,h+v]}),g=e.children.findIndex(y=>y.id===t);g>=0&&Se.setNode(e,{points:f},[g])}function oy(e,t,n,o,i,s){const r=s.width/i.width,a=s.height/i.height,c=o.x-i.x,u=o.y-i.y,l=s.x+c*r,h=s.y+u*a,f=n.anchors.map(v=>({...v,point:[v.point[0]*r,v.point[1]*a],handleIn:v.handleIn?[v.handleIn[0]*r,v.handleIn[1]*a]:void 0,handleOut:v.handleOut?[v.handleOut[0]*r,v.handleOut[1]*a]:void 0})),g=o.width*r,y=o.height*a,w=[[l,h],[l+g,h+y]],S=e.children.findIndex(v=>v.id===t);S>=0&&Se.setNode(e,{points:w,anchors:f},[S])}const Zl=14;function Jl(e,t){const n={...e};if("text"in e&&typeof e.text=="string"){const o=e["font-size"]?parseFloat(e["font-size"]):Zl,i=Math.max(1,Math.round(o*t*10)/10);n["font-size"]=`${i}`}return Array.isArray(e.children)&&(n.children=e.children.map(o=>Jl(o,t))),n}function iy(e,t,n,o,i,s){const r=s.width/i.width,a=s.height/i.height,c=o.x-i.x,u=o.y-i.y,l=s.x+c*r,h=s.y+u*a,f=o.width*r,g=o.height*a,y=[[l,h],[l+f,h+g]],m=e.children.findIndex(w=>w.id===t);if(m>=0)if(K.isDrawElement(n)&&K.isImage(n))Se.setNode(e,{points:y,width:f,height:g},[m]);else if(K.isText(n)){const w=n,S=Jl(w.text,r),v=w.textHeight||Zl*1.4;Se.setNode(e,{points:y,text:S,textHeight:v*r,autoSize:!1},[m])}else Se.setNode(e,{points:y},[m])}function sy(e,t,n){const{element:o,rectangle:i,handle:s}=t,{startPoint:r,endPoint:a}=n;if(!i||!Array.isArray(o)||!Jo)return;const c=a[0]-r[0],u=a[1]-r[1],l=vo()||Q0(o),h=Tn(i,s,c,u,l);for(const f of o){const g=Jo.get(f.id);if(!g)continue;const{element:y,rectangle:m}=g;De.isFreehand(y)?ny(e,f.id,y,m,i,h):$e.isPenPath(y)?oy(e,f.id,y,m,i,h):iy(e,f.id,y,m,i,h)}}function ry(e){const t=Te(e);if(t.length<2||!Qs(t))return null;try{const n=yo(),o=Ft(e,t,!1),i=Ac(e,o);return de.getCornerPoints(i).forEach(r=>{const a=Th(e,r);n.append(a)}),n}catch{return null}}const ay=e=>{const{afterChange:t}=e;let n=null;return e.afterChange=()=>{t(),n&&(n.remove(),n=null);const o=Te(e);o.length>1&&Qs(o)&&!oo(e)&&(n=ry(e),n&&F.getActiveHost(e).append(n))},sn(e,{key:"multi-resize",canResize:()=>ey(e),hitTest:(o=>ty(e,o)),onResize:(o,i)=>sy(e,o,i)})},Ql=14;let No=null,vs=null;function eu(e,t){const n={...e};if("text"in e&&typeof e.text=="string"){const o=e["font-size"]?parseFloat(e["font-size"]):Ql,i=Math.max(1,Math.round(o*t*10)/10);n["font-size"]=`${i}`}return Array.isArray(e.children)&&(n.children=e.children.map(o=>eu(o,t))),n}function cy(e){const t=Te(e);return t.length!==1?!1:K.isText(t[0])}function ly(e,t){const n=Te(e);if(n.length!==1||!K.isText(n[0]))return null;const o=n[0],i=de.getRectangleByPoints(o.points),s=rn(i,t);return s?(No=JSON.parse(JSON.stringify(o)),vs={...i},{element:o,rectangle:i,handle:s.handle,cursorClass:s.cursorClass}):null}function uy(e,t,n){const{element:o,rectangle:i,handle:s}=t,{startPoint:r,endPoint:a}=n;if(!i||!No||!vs)return;const c=a[0]-r[0],u=a[1]-r[1],l=Tn(i,s,c,u,!0,20),h=l.width/vs.width;if(h<=0)return;const f=eu(No.text,h),y=(No.textHeight||Ql*1.4)*h,m=[[l.x,l.y],[l.x+l.width,l.y+l.height]],w=e.children.findIndex(S=>S.id===o.id);w>=0&&Se.setNode(e,{points:m,text:f,textHeight:y,autoSize:!1},[w])}const dy=e=>sn(e,{key:"text-resize",canResize:()=>cy(e),hitTest:t=>ly(e,t),onResize:(t,n)=>uy(e,t,n)});function hy(e){return e.some(n=>De.isFreehand(n)||$e.isPenPath(n))}function fy(e){const t=Te(e);if(t.length<2||!hy(t))return null;try{return Ft(e,t,!1)}catch{return null}}const gy=()=>{const e=Ye(),[t,n]=p.useState([]),[o,i]=p.useState(!1),[s,r]=p.useState(!1),a=p.useRef(!1),c=p.useCallback(()=>{const h=Ki(e)||Qi(e)||oo(e);if(r(h),h)return;Te(e);const f=fy(e);if(!f){i(!1);return}const y=[{x:f.x,y:f.y,cursor:"nwse-resize"},{x:f.x+f.width,y:f.y,cursor:"nesw-resize"},{x:f.x+f.width,y:f.y+f.height,cursor:"nwse-resize"},{x:f.x,y:f.y+f.height,cursor:"nesw-resize"}].map(m=>{const w=Ch(e,[m.x,m.y]);return{x:w[0],y:w[1],cursor:m.cursor}});n(y),i(!0)},[e]);if(p.useEffect(()=>{a.current=s},[s]),p.useEffect(()=>{c();let h,f=JSON.stringify(e.viewport),g=JSON.stringify(e.selection),y=e.children.length;const m=()=>{const w=JSON.stringify(e.viewport),S=JSON.stringify(e.selection),v=e.children.length,E=Ki(e)||Qi(e)||oo(e);(w!==f||S!==g||v!==y||E!==a.current)&&(f=w,g=S,y=v,c()),h=requestAnimationFrame(m)};return h=requestAnimationFrame(m),()=>{cancelAnimationFrame(h)}},[e,c]),!o||t.length===0||s)return null;const u=Ih,l=u/2;return d.jsx("div",{className:me("multi-selection-handles",En),children:t.map((h,f)=>d.jsx("div",{className:"multi-selection-handle",style:{left:h.x-l,top:h.y-l,width:u,height:u,cursor:h.cursor}},f))})};class py{constructor(){this.board=null}setBoard(t){this.board=t}getBoard(){return this.board||console.error("❌ Board instance not set. Call testToolbox.setBoard(board) first"),this.board}insertBananaPrompt(){const t=this.getBoard();if(!t)return;const n=Eo.getToolById("banana-prompt");if(!n){console.error('❌ Tool "banana-prompt" not found');return}un.insertTool(t,n.id,n.url,[100,100],{width:n.defaultWidth||dn.defaultWidth,height:n.defaultHeight||dn.defaultHeight},{name:n.name,category:n.category,permissions:n.permissions})}insertXiaohongshuTool(){const t=this.getBoard();if(!t)return;const n=Eo.getToolById("xiaohongshu-tool");if(!n){console.error('❌ Tool "xiaohongshu-tool" not found');return}un.insertTool(t,n.id,n.url,[300,300],{width:n.defaultWidth||dn.defaultWidth,height:n.defaultHeight||dn.defaultHeight},{name:n.name,category:n.category,permissions:n.permissions})}insertToolById(t,n=200,o=200){const i=this.getBoard();if(!i)return;const s=Eo.getToolById(t);if(!s){console.error(`❌ Tool "${t}" not found`);return}un.insertTool(i,s.id,s.url,[n,o],{width:s.defaultWidth||dn.defaultWidth,height:s.defaultHeight||dn.defaultHeight},{name:s.name,category:s.category,permissions:s.permissions})}listAllTools(){Eo.getAvailableTools().forEach((n,o)=>{})}getAllToolElements(){const t=this.getBoard();if(!t)return;un.getAllTools(t).forEach((o,i)=>{})}removeAllTools(){const t=this.getBoard();if(!t)return;un.getAllTools(t).forEach(o=>{un.removeTool(t,o.id)})}help(){}}const my=new py;typeof window<"u"&&(window.testToolbox=my);const wy={width:200,height:150,position:"bottom-right",margin:16,collapsible:!0,defaultExpanded:!1,backgroundColor:"rgba(255, 255, 255, 0.95)",borderColor:"rgba(0, 0, 0, 0.1)",viewportColor:"rgba(90, 79, 207, 0.3)",elementColor:"rgba(0, 0, 0, 0.5)"},yy={autoHideDelay:3e3},vy=e=>{if(!e)return null;const[t,n]=e.trim().split(/[\s,]+/).map(o=>Number(o));return!Number.isFinite(t)||!Number.isFinite(n)?null:{x:t,y:n}},Sy=e=>{const t=e.viewport.zoom;if(!Number.isFinite(t)||t<=0)return null;try{const n=F.getViewportContainer(e),o=F.getHost(e),i=vy(o.getAttribute("viewBox"));return i?[n.scrollLeft/t+i.x,n.scrollTop/t+i.y]:null}catch{return null}},tu=e=>{const t=Sy(e);return t||si(e)||e.viewport.origination||[0,0]},xy=e=>{const[t,n]=tu(e);return{zoom:e.viewport.zoom,originX:t,originY:n}},ky=({board:e,config:t,className:n,displayMode:o="auto",autoTriggerConfig:i})=>{const s=p.useRef(null),r=p.useRef(null);p.useRef(null);const a={...wy,...t},c={...yy,...i},[u,l]=p.useState(()=>({expanded:o==="always"?!0:a.defaultExpanded,dragging:!1,autoMode:o==="auto",manuallyExpanded:!1})),h=p.useRef({isDragging:!1,startPoint:null}),f=p.useRef(null),[g,y]=p.useState(null),m=p.useRef(null),[w,S]=p.useState(!1),v=120,E=p.useRef(0),C=p.useRef(null),D=p.useCallback(()=>{if(!e||!e.children)return[];const N=[];return e.children.forEach(b=>{try{let x=null;b.points&&Array.isArray(b.points)?x=de.getRectangleByPoints(b.points):b.x!==void 0&&b.y!==void 0&&(x={x:b.x,y:b.y,width:b.width||100,height:b.height||100}),x&&x.width>0&&x.height>0&&N.push({id:b.id,bounds:x,type:b.type})}catch(x){console.warn("Failed to get bounds for element:",b.id,x)}}),N},[e]),P=p.useCallback(()=>{const b=F.getBoardContainer(e).getBoundingClientRect(),x=e.viewport.zoom,_=tu(e),z=_[0],G=_[1],$=b.width/x,ne=b.height/x;return{x:z,y:G,width:$,height:ne}},[e]),H=p.useRef(u.expanded);H.current=u.expanded;const B=p.useRef(null),j=p.useRef(1);p.useEffect(()=>{if(o==="always"){H.current||l(b=>({...b,expanded:!0}));return}if(o!=="auto")return;const N=setInterval(()=>{const b=xy(e),x=C.current;if(!x){C.current=b;return}const _=Math.abs(b.zoom-x.zoom)>.001,z=Math.abs(b.originX-x.originX)>.5||Math.abs(b.originY-x.originY)>.5;(_||z)&&(C.current=b,E.current=Date.now(),H.current||l($=>({...$,expanded:!0,manuallyExpanded:!1})))},100);return()=>{clearInterval(N)}},[o,e]),p.useEffect(()=>{if(o!=="auto"||!u.expanded||u.manuallyExpanded||u.dragging)return;const N=setTimeout(()=>{l(b=>!b.autoMode||b.manuallyExpanded||b.dragging?b:{...b,expanded:!1})},c.autoHideDelay);return()=>{clearTimeout(N)}},[o,u.expanded,u.manuallyExpanded,u.dragging,c.autoHideDelay]);const U=p.useCallback((N,b)=>{if(N.length===0)return{x:b.x-200,y:b.y-200,width:b.width+400,height:b.height+400};let x=b.x,_=b.y,z=b.x+b.width,G=b.y+b.height;N.forEach(ne=>{const{x:xe,y:X,width:oe,height:Fe}=ne.bounds;x=Math.min(x,xe),_=Math.min(_,X),z=Math.max(z,xe+oe),G=Math.max(G,X+Fe)});const $=100;return{x:x-$,y:_-$,width:z-x+$*2,height:G-_+$*2}},[]),A=p.useCallback(N=>{const x=(a.width-20)/N.width,_=(a.height-20)/N.height;return Math.min(x,_)},[a.width,a.height]),I=p.useCallback((N,b,x,_)=>{const G=(N-x.x)*_+10,$=(b-x.y)*_+10;return[G,$]},[]),k=p.useCallback((N,b,x,_)=>{const G=(N-10)/_+x.x,$=(b-10)/_+x.y;return[G,$]},[]),T=p.useCallback((N,b,x)=>{if(100*x<5)return;N.strokeStyle="rgba(0, 0, 0, 0.05)",N.lineWidth=.5;const G=Math.floor(b.x/100)*100,$=Math.floor(b.y/100)*100,ne=b.x+b.width,xe=b.y+b.height;for(let X=G;X<=ne;X+=100){const[oe]=I(X,0,b,x);N.beginPath(),N.moveTo(oe,0),N.lineTo(oe,a.height),N.stroke()}for(let X=$;X<=xe;X+=100){const[,oe]=I(0,X,b,x);N.beginPath(),N.moveTo(0,oe),N.lineTo(a.width,oe),N.stroke()}},[I,a.width,a.height]),M=p.useCallback(()=>{const N=s.current;if(!N)return;const b=N.getContext("2d");if(!b)return;b.clearRect(0,0,a.width,a.height);const x=D(),_=P();if(x.length===0&&!_){b.fillStyle="#999",b.font="12px sans-serif",b.textAlign="center",b.textBaseline="middle",b.fillText("空画布",a.width/2,a.height/2);return}const z=U(x,_),G=A(z);B.current=z,j.current=G,T(b,z,G),b.fillStyle=a.elementColor,b.strokeStyle="rgba(0, 0, 0, 0.1)",b.lineWidth=.5,x.forEach(Ve=>{const{x:Ie,y:wt,width:Ge,height:Lt}=Ve.bounds,[bt,Z]=I(Ie,wt,z,G),ke=Ge*G,se=Lt*G;b.fillRect(bt,Z,ke,se),b.strokeRect(bt,Z,ke,se)});const[$,ne]=I(_.x,_.y,z,G),xe=_.width*G,X=_.height*G;b.fillStyle=a.viewportColor,b.fillRect($,ne,xe,X),b.strokeStyle=a.viewportColor.replace("0.3","1"),b.lineWidth=2,b.strokeRect($,ne,xe,X);const oe=8;b.fillStyle=a.viewportColor.replace("0.3","0.8"),b.fillRect($,ne,oe,2),b.fillRect($,ne,2,oe),b.fillRect($+xe-oe,ne,oe,2),b.fillRect($+xe-2,ne,2,oe),b.fillRect($,ne+X-2,oe,2),b.fillRect($,ne+X-oe,2,oe),b.fillRect($+xe-oe,ne+X-2,oe,2),b.fillRect($+xe-2,ne+X-oe,2,oe);const Fe=m.current;if(Fe){const Ve=Fe.x-xe/2,Ie=Fe.y-X/2;b.fillStyle="rgba(243, 156, 18, 0.15)",b.fillRect(Ve,Ie,xe,X),b.strokeStyle="rgba(243, 156, 18, 0.8)",b.lineWidth=2,b.strokeRect(Ve,Ie,xe,X)}},[e,a,D,P,U,A,I,T]),O=p.useCallback(N=>{N.preventDefault(),N.stopPropagation();const b=s.current;if(!b||!B.current)return;const x=b.getBoundingClientRect(),_=N.clientX-x.left,z=N.clientY-x.top;tt.track("minimap_navigate",{action:"click",displayMode:o});const[G,$]=k(_,z,B.current,j.current);h.current={isDragging:!0,startPoint:[_,z]},l(ne=>({...ne,dragging:!0})),q(G,$)},[k,e]),q=p.useCallback((N,b)=>{const _=F.getBoardContainer(e).getBoundingClientRect(),z=e.viewport.zoom,G=N-_.width/(2*z),$=b-_.height/(2*z);ee.updateViewport(e,[G,$],z),requestAnimationFrame(()=>M())},[e,M]),le=p.useCallback(N=>{if(!h.current.isDragging||!B.current)return;N.preventDefault(),N.stopPropagation();const b=s.current;if(!b)return;const x=b.getBoundingClientRect(),_=N.clientX-x.left,z=N.clientY-x.top,[G,$]=k(_,z,B.current,j.current);q(G,$)},[k,q]),R=p.useCallback(()=>{h.current.isDragging&&tt.track("minimap_navigate",{action:"drag",displayMode:o}),h.current={isDragging:!1,startPoint:null},l(N=>({...N,dragging:!1}))},[o]),L=p.useCallback((N,b)=>{const x=f.current;if(!x||!B.current)return;const _=x.getContext("2d");if(!_)return;const[z,G]=k(N,b,B.current,j.current),$=P(),ne=$.width,xe=$.height,X=ne,oe=xe;_.clearRect(0,0,v,v),_.fillStyle="#fff",_.fillRect(0,0,v,v);const Fe=z-X/2,Ve=G-oe/2,Ie=v/X,wt=v/oe,Ge=Math.min(Ie,wt),Lt=(v-X*Ge)/2,bt=(v-oe*Ge)/2;D().forEach(ke=>{const{bounds:se}=ke;if(se.x+se.width>=Fe&&se.x<=Fe+X&&se.y+se.height>=Ve&&se.y<=Ve+oe){const we=(se.x-Fe)*Ge+Lt,nt=(se.y-Ve)*Ge+bt,ct=se.width*Ge,lt=se.height*Ge;_.fillStyle="rgba(0, 0, 0, 0.6)",_.fillRect(we,nt,ct,lt)}}),_.strokeStyle="rgba(90, 79, 207, 0.6)",_.lineWidth=1,_.setLineDash([4,4]),_.beginPath(),_.moveTo(0,v/2),_.lineTo(v,v/2),_.stroke(),_.beginPath(),_.moveTo(v/2,0),_.lineTo(v/2,v),_.stroke(),_.setLineDash([]),_.strokeStyle="rgba(90, 79, 207, 0.3)",_.lineWidth=2,_.strokeRect(0,0,v,v)},[D,P,k]),Y=p.useCallback(()=>{u.dragging||S(!0)},[u.dragging]),he=p.useCallback(()=>{S(!1),y(null),m.current=null},[]),be=p.useCallback(N=>{if(u.dragging){S(!1),m.current=null;return}const b=s.current;if(!b)return;const x=b.getBoundingClientRect(),_=N.clientX-x.left,z=N.clientY-x.top,G={x:_,y:z};y(G),m.current=G,S(!0),L(_,z),M()},[u.dragging,L,M]),ue=p.useRef(!1),_e=p.useCallback(N=>{ue.current=!0;const b=s.current;if(!b)return;const x=N.touches[0],_=b.getBoundingClientRect(),z=x.clientX-_.left,G=x.clientY-_.top,$={x:z,y:G};y($),m.current=$,S(!0),L(z,G),M()},[L,M]),Ce=p.useCallback(N=>{const b=s.current;if(!b)return;const x=N.touches[0],_=b.getBoundingClientRect(),z=x.clientX-_.left,G=x.clientY-_.top,$={x:z,y:G};y($),m.current=$,S(!0),L(z,G),M()},[L,M]),ze=p.useCallback(()=>{ue.current=!1,setTimeout(()=>{ue.current||(S(!1),y(null),m.current=null,M())},500)},[M]);p.useEffect(()=>{if(!u.expanded)return;M();const N=setInterval(()=>{M()},100);return()=>{clearInterval(N)}},[e,u.expanded,M]);const W=p.useCallback(()=>{l(N=>{const b=!N.expanded;return{...N,expanded:b,manuallyExpanded:b}})},[]),Q={bottom:a.position.includes("bottom")?a.margin:void 0,top:a.position.includes("top")?a.margin:void 0,right:a.position.includes("right")?a.margin:void 0,left:a.position.includes("left")?a.margin:void 0},pe=w&&(ue.current||!u.dragging),V=g?{position:"absolute",right:a.width+8,top:Math.max(0,Math.min(g.y-v/2,a.height-v)),width:v,height:v,opacity:pe?1:0,pointerEvents:"none",transition:"opacity 0.15s ease-out, top 0.1s ease-out"}:{display:"none"};return d.jsxs("div",{ref:r,className:`minimap ${u.expanded?"minimap--expanded":"minimap--collapsed"} ${o==="auto"?"minimap--auto":""} ${n||""}`,style:{...Q,zIndex:ht.MINIMAP},"data-track":"minimap_container",children:[u.expanded&&d.jsxs("div",{className:"minimap__content",children:[d.jsx("canvas",{ref:s,width:a.width,height:a.height,className:"minimap__canvas",onPointerDown:O,onPointerMove:le,onPointerUp:R,onPointerLeave:R,onMouseEnter:Y,onMouseLeave:he,onMouseMove:be,onTouchStart:_e,onTouchMove:Ce,onTouchEnd:ze,style:{cursor:u.dragging?"grabbing":"pointer"}}),d.jsx("div",{className:"minimap__preview",style:V,children:d.jsx("canvas",{ref:f,width:v,height:v,className:"minimap__preview-canvas"})})]}),a.collapsible&&d.jsx(Tt,{content:u.expanded?"折叠小地图":"展开小地图",showArrow:!1,children:d.jsx("button",{className:`minimap__toggle ${u.expanded?"minimap__toggle--expanded":""}`,onClick:W,"data-track":"minimap_click_toggle",children:d.jsx(Ah,{})})})]})},Bi=10,Ey=3e3,by=e=>{var n;const t=e?si(e)||e.viewport.origination:void 0;return{zoom:((n=e==null?void 0:e.viewport)==null?void 0:n.zoom)||1,originX:(t==null?void 0:t[0])||0,originY:(t==null?void 0:t[1])||0}},_y=({showMinimap:e=!0,container:t})=>{var U;const n=Ye(),{t:o}=Oe(),{isDrawerOpen:i,drawerWidth:s}=Mh(),[r,a]=p.useState(!1),[c,u]=p.useState(!0),[l,h]=p.useState(!1),f=p.useRef(null),g=p.useRef(null),y=p.useRef(null),m=p.useMemo(()=>{if(i)return`calc(var(--aitu-toolbar-right-dock-width, 0px) + ${s+Bi}px)`;const A="var(--aitu-toolbar-right-avoidance, 0px)";return typeof CSS<"u"&&CSS.supports("right","max(1px, 2px)")?`max(${Bi}px, ${A})`:Bi},[i,s]),w=p.useCallback(()=>{ee.updateZoom(n,n.viewport.zoom-.1)},[n]),S=p.useCallback(()=>{ee.updateZoom(n,n.viewport.zoom+.1)},[n]),v=p.useCallback(()=>{ee.fitViewport(n),a(!1)},[n]),E=p.useCallback(()=>{ee.updateZoom(n,1),a(!1)},[n]),C=p.useCallback(()=>n.children.some(So)?!1:(Mc({viewMode:"slides"}),!0),[n]),D=p.useCallback(()=>{a(!1),!C()&&Os(n)},[n,C]),P=p.useCallback(()=>{a(!1),!C()&&Cf(n)},[n,C]),H=p.useCallback(()=>{u(A=>{const I=!A;return h(I),I})},[]);p.useEffect(()=>{if(!c||!n)return;const A=F.getBoardContainer(n);if(!A)return;const I=k=>{var M;const T=k.target;(M=f.current)!=null&&M.contains(T)||(u(!1),h(!1))};return A.addEventListener("mousedown",I),()=>{A.removeEventListener("mousedown",I)}},[c,n]),p.useEffect(()=>{if(!e||!n)return;const A=setInterval(()=>{const I=by(n),k=g.current;if(!k){g.current=I;return}const T=Math.abs(I.zoom-k.zoom)>.001,M=Math.abs(I.originX-k.originX)>.5||Math.abs(I.originY-k.originY)>.5;(T||M)&&(g.current=I,c||(u(!0),h(!1)),y.current&&clearTimeout(y.current))},100);return()=>{clearInterval(A)}},[e,n,c]),p.useEffect(()=>{if(!(!c||l))return y.current=setTimeout(()=>{u(!1)},Ey),()=>{y.current&&clearTimeout(y.current)}},[c,l]);const B=p.useCallback(()=>{a(A=>!A)},[]),j=Math.round((((U=n==null?void 0:n.viewport)==null?void 0:U.zoom)||1)*100);return d.jsxs("div",{className:`view-navigation ${En}`,style:{right:m,zIndex:ht.VIEW_NAVIGATION},ref:f,"data-testid":"view-navigation",children:[d.jsxs("div",{className:"view-navigation__zoom",children:[d.jsx(Tt,{content:o("zoom.out"),showArrow:!1,children:d.jsx("button",{className:"view-navigation__zoom-btn",onClick:w,"aria-label":o("zoom.out"),"data-track":"view_nav_zoom_out","data-testid":"zoom-out",children:d.jsx(Rh,{})})}),d.jsxs(Mt,{sideOffset:8,open:r,onOpenChange:a,placement:"bottom",children:[d.jsx(Tt,{content:o("zoom.fit"),showArrow:!1,children:d.jsx(Rt,{asChild:!0,children:d.jsxs("button",{className:"view-navigation__zoom-percent",onClick:B,"aria-label":o("zoom.fit"),"data-track":"view_nav_zoom_menu","data-testid":"zoom-display",children:[j,"%"]})})}),d.jsx(Dt,{className:En,container:t,style:{zIndex:ht.POPOVER},children:d.jsxs("div",{className:"view-navigation-zoom-menu",children:[d.jsxs("button",{className:"zoom-menu-item",onClick:v,"data-track":"view_nav_zoom_fit",children:[d.jsx("span",{className:"zoom-menu-item__label",children:o("zoom.fit")}),d.jsx("span",{className:"zoom-menu-item__shortcut",children:"⌘⇧="})]}),d.jsx("button",{className:"zoom-menu-item",onClick:D,"data-track":"view_nav_zoom_fit_frame",children:d.jsx("span",{className:"zoom-menu-item__label",children:o("zoom.fitFrame")})}),d.jsx("button",{className:"zoom-menu-item",onClick:P,"data-track":"view_nav_zoom_fit_ppt_global",children:d.jsx("span",{className:"zoom-menu-item__label",children:o("zoom.fitPPTGlobal")})}),d.jsxs("button",{className:"zoom-menu-item",onClick:E,"data-track":"view_nav_zoom_100",children:[d.jsx("span",{className:"zoom-menu-item__label",children:o("zoom.100")}),d.jsx("span",{className:"zoom-menu-item__shortcut",children:"⌘0"})]})]})})]}),d.jsx(Tt,{content:o("zoom.in"),showArrow:!1,children:d.jsx("button",{className:"view-navigation__zoom-btn",onClick:S,"aria-label":o("zoom.in"),"data-track":"view_nav_zoom_in","data-testid":"zoom-in",children:d.jsx(Dh,{})})}),e&&d.jsx(Tt,{content:c?"折叠小地图":"展开小地图",showArrow:!1,children:d.jsx("button",{className:`view-navigation__minimap-toggle ${c?"view-navigation__minimap-toggle--expanded":""}`,onClick:H,"aria-label":c?"折叠小地图":"展开小地图","data-track":"view_nav_minimap_toggle",children:d.jsx(Lh,{})})})]}),e&&c&&d.jsx("div",{className:"view-navigation__minimap",children:d.jsx(ky,{board:n,displayMode:"always",config:{width:180,height:120,position:"top-right",margin:0,collapsible:!1,defaultExpanded:!0}})})]})},Py=({children:e,onOpenMediaLibrary:t})=>{const[n,o]=p.useState(!1),{confirm:i,confirmDialog:s}=jh(),r=p.useCallback(()=>{n||(o(!0),i({title:"缓存空间已满",description:"图片缓存空间已满,无法继续缓存新图片。是否打开素材库清理缓存?",confirmText:"打开素材库",cancelText:"稍后处理",confirmTheme:"warning"}).then(a=>{o(!1),a&&(t==null||t())}))},[i,n,t]);return Oh(r),d.jsxs(d.Fragment,{children:[e,s]})},Qo={visible:!1,position:{x:0,y:0},sourceElement:null,currentShape:null,hitIndex:-1,hitPoint:null,mode:"hover",arrowLineElement:null,arrowLineEndPoint:null},nu=new WeakMap,Ss=new WeakMap;function ei(e){return nu.get(e)||Qo}function Un(e,t){nu.set(e,t);const n=Ss.get(e);n&&n(t)}function Ty(e,t){return Ss.set(e,t),()=>{Ss.delete(e)}}function er(e){Un(e,Qo)}const On=100;function Cy(e,t,n,o,i){const s=Hh(n),r=de.getRectangleByPoints(t.points),a=r.width,c=r.height,u=r.x+a/2,l=r.y+c/2,f=de.getEdgeCenterPoints(r)[n];let g,y;switch(s){case Pe.right:g=u+a/2+On+a/2,y=l;break;case Pe.bottom:g=u,y=l+c/2+On+c/2;break;case Pe.left:g=u-a/2-On-a/2,y=l;break;case Pe.top:g=u,y=l-c/2-On-c/2;break;default:g=u+a/2+On+a/2,y=l}const m=[[g-a/2,y-c/2],[g+a/2,y+c/2]],w=Ls(e,m,i);if(w.fill="#ffffff",K.isShapeElement(t)&&!K.isText(t)){const A=t;A.angle!==void 0&&(w.angle=A.angle),A.fill&&A.fill!=="none"&&(w.fill=A.fill),A.strokeColor!==void 0&&(w.strokeColor=A.strokeColor),A.strokeStyle!==void 0&&(w.strokeStyle=A.strokeStyle),A.strokeWidth!==void 0&&(w.strokeWidth=A.strokeWidth)}const S=Vo(f,t)||f,v=K.isShapeElement(t)?ro(e,S,t):void 0;let E;switch(s){case Pe.right:E=3;break;case Pe.bottom:E=0;break;case Pe.left:E=1;break;case Pe.top:E=2;break;default:E=3}const C=de.getRectangleByPoints(w.points),P=de.getEdgeCenterPoints(C)[E],H=Vo(P,w)||P,B=ro(e,H,w),j=Lc(xt.straight,[S,H],{marker:ao.none,connection:v,boundId:t.id},{marker:ao.arrow,connection:B,boundId:w.id},[],{});Se.insertNode(e,j,[e.children.length]),Dc(e,w),er(e);const U=w.id;setTimeout(()=>{const A=e.children.findIndex(k=>k.id===U),I=A>=0?e.children[A]:null;I&&(At(e),Pn(e,I),ee.updatePointerType(e,Le.selection),Se.setNode(e,{_forceRender:Date.now()},[A]),Se.setNode(e,{_forceRender:void 0},[A]))},50)}function Iy(e,t,n,o){var y;let i=100,s=100;const r=t,a=(y=r.source)==null?void 0:y.boundId;if(a){const m=e.children.find(w=>w.id===a);if(m&&K.isShapeElement(m)){const w=de.getRectangleByPoints(m.points);i=w.width,s=w.height}}const c=[[n[0]-i/2,n[1]-s/2],[n[0]+i/2,n[1]+s/2]],u=Ls(e,c,o);u.fill="#ffffff";const l=de.getRectangleByPoints(u.points),h=de.getEdgeCenterPoints(l),f=r.points||[];if(f.length>=2){const m=f[0],w=f[f.length-1],S=w[0]-m[0],v=w[1]-m[1];let E;Math.abs(S)>Math.abs(v)?E=S>0?3:1:E=v>0?0:2;const C=h[E],D=ro(e,C,u),P=e.children.findIndex(H=>H.id===t.id);P!==-1&&Se.setNode(e,{target:{marker:ao.arrow,connection:D,boundId:u.id},points:[m,C]},[P])}Dc(e,u),er(e);const g=u.id;setTimeout(()=>{const m=e.children.findIndex(S=>S.id===g),w=m>=0?e.children[m]:null;w&&(At(e),Pn(e,w),ee.updatePointerType(e,Le.selection),Se.setNode(e,{_forceRender:Date.now()},[m]),Se.setNode(e,{_forceRender:void 0},[m]))},50)}const Ay=e=>{const{pointerMove:t,pointerLeave:n,globalPointerUp:o}=e;let i=null,s=-1,r=e.children.length,a={x:0,y:0};return e.pointerMove=c=>{var C;a={x:c.clientX,y:c.clientY},i&&(clearTimeout(i),i=null);const u=Rc(e),l=u.length===1&&u[0],h=ei(e);if(!l||!K.isShapeElement(l)||K.isText(l)){if(h.visible&&h.mode==="hover"&&Un(e,{...Qo}),s=-1,l&&K.isShapeElement(l)&&!vn.getElementRef(l))return;t(c);return}if(!vn.getElementRef(l)){s=-1;return}const g=Nh(e,c.x,c.y),y=zh(e,l,!0),m=Fh(e,g,l,!0)||g,w=Bh(m,y),S=y[w];if(S){if(w!==s||!h.visible){s=w;const D=c.clientX,P=c.clientY;i=setTimeout(()=>{const H=K.isImage(l)?ge.rectangle:l.shape||ge.rectangle;Un(e,{visible:!0,position:{x:D-140,y:P+20},sourceElement:l,currentShape:H,hitIndex:w,hitPoint:S,mode:"hover"})},50)}}else s=-1,h.visible&&h.mode==="hover"&&(i=setTimeout(()=>{const D=ei(e);D.visible&&D.mode==="hover"&&Un(e,{...Qo})},300));const v=vn.getElementRef(l);(C=v==null?void 0:v.getGenerator)!=null&&C.call(v,Gi.key)&&t(c)},e.pointerLeave=c=>{i&&(clearTimeout(i),i=null),n(c)},e.globalPointerUp=c=>{var l;o(c);const u=e.children.length;if(u>r){const h=e.children[u-1];if(K.isArrowLine(h)){const f=h;if(!((l=f.target)==null?void 0:l.boundId)){const y=f.points||[];if(y.length>=2){const m=y[y.length-1];setTimeout(()=>{Un(e,{visible:!0,position:{x:a.x-140,y:a.y+20},sourceElement:null,currentShape:ge.rectangle,hitIndex:-1,hitPoint:null,mode:"arrowLine",arrowLineElement:h,arrowLineEndPoint:m})},50)}}}}r=e.children.length},e},Nn=100;function My(e){switch(e){case"ArrowRight":return Pe.right;case"ArrowDown":return Pe.bottom;case"ArrowLeft":return Pe.left;case"ArrowUp":return Pe.top;default:return null}}function Ry(e){switch(e){case Pe.top:return 0;case Pe.right:return 1;case Pe.bottom:return 2;case Pe.left:return 3;default:return 1}}function Dy(e){return(e+2)%4}function Ly(e,t,n,o,i,s){const r={x:t-o/2,y:n-i/2,width:o,height:i};for(const a of e.children)if(a.id!==s&&K.isDrawElement(a)&&!K.isArrowLine(a))try{const c=de.getRectangleByPoints(a.points);if(r.x<c.x+c.width&&r.x+r.width>c.x&&r.y<c.y+c.height&&r.y+r.height>c.y)return!0}catch{}return!1}function jy(e,t,n){const o=de.getRectangleByPoints(t.points),i=o.width,s=o.height,r=o.x+i/2,a=o.y+s/2;let c,u;switch(n){case Pe.right:c=r+i/2+Nn+i/2,u=a;break;case Pe.bottom:c=r,u=a+s/2+Nn+s/2;break;case Pe.left:c=r-i/2-Nn-i/2,u=a;break;case Pe.top:c=r,u=a-s/2-Nn-s/2;break;default:c=r+i/2+Nn+i/2,u=a}let l=0;const h=n===Pe.right||n===Pe.left?s+20:i+20;for(;Ly(e,c,u,i,s,t.id)&&(l+=h,n===Pe.right||n===Pe.left?u=a+l:c=r+l,!(l>1e3)););const f=[[c-i/2,u-s/2],[c+i/2,u+s/2]],y=t.shape||"rectangle",m=Ls(e,f,y);if(m.fill="#ffffff",K.isShapeElement(t)&&!K.isText(t)){const k=t;k.fill&&k.fill!=="none"&&(m.fill=k.fill),k.strokeColor!==void 0&&(m.strokeColor=k.strokeColor),k.strokeWidth!==void 0&&(m.strokeWidth=k.strokeWidth)}const w=Ry(n),S=Dy(w),E=de.getEdgeCenterPoints(o)[w],C=Vo(E,t)||E,D=K.isShapeElement(t)?ro(e,C,t):void 0,P=de.getRectangleByPoints(m.points),B=de.getEdgeCenterPoints(P)[S],j=Vo(B,m)||B,U=ro(e,j,m),A=Lc(xt.elbow,[C,j],{marker:ao.none,connection:D,boundId:t.id},{marker:ao.arrow,connection:U,boundId:m.id},[],{});Se.insertNode(e,A,[e.children.length]),Se.insertNode(e,m,[e.children.length]);const I=m.id;setTimeout(()=>{const k=e.children.find(T=>T.id===I);k&&(At(e),Pn(e,k),ee.updatePointerType(e,Le.selection),jc(e,[c,u]))},50)}function Oy(e,t){var i,s,r,a;const n=[],o=[];for(const c of e.children){if(!K.isArrowLine(c))continue;const u=c;if(((i=u.source)==null?void 0:i.boundId)===t.id&&((s=u.target)!=null&&s.boundId)){const l=e.children.find(h=>h.id===u.target.boundId);l&&o.push(l)}if(((r=u.target)==null?void 0:r.boundId)===t.id&&((a=u.source)!=null&&a.boundId)){const l=e.children.find(h=>h.id===u.source.boundId);l&&n.push(l)}}return{incoming:n,outgoing:o}}function Ny(e,t,n){const{incoming:o,outgoing:i}=Oy(e,t),s=n?[...i,...o]:[...o,...i];if(s.length===0)return!1;const r=s[0];At(e),Pn(e,r);try{const a=Ft(e,[r],!1),c=a.x+a.width/2,u=a.y+a.height/2;jc(e,[c,u])}catch{}return!0}const zy=e=>{const{keyDown:t}=e;return e.keyDown=n=>{if(!n.altKey&&!n.metaKey&&!n.ctrlKey){if(!n.shiftKey){const o=My(n.key);if(o!==null){const i=Rc(e);if(i.length===1){const s=i[0];if(K.isShapeElement(s)&&!K.isText(s)&&!K.isImage(s)){jy(e,s,o),n.preventDefault();return}}}}if(n.key==="Tab"){const o=Te(e);if(o.length===1){const i=o[0];if(K.isDrawElement(i)&&K.isShapeElement(i)&&Ny(e,i,!n.shiftKey)){n.preventDefault();return}}}}t(n)},e};function Fy(e){let t=0;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)|0;return Math.abs(t)}function Ta(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return"--:--";const t=Math.floor(e),n=Math.floor(t/60),o=t%60;return`${n}:${String(o).padStart(2,"0")}`}function Ca(e,t){return e?e.length<=t?e:`${e.slice(0,Math.max(0,t-3))}...`:""}function By(e,t){if(e){const n=e.split(/[,,]/).map(o=>o.trim()).filter(Boolean).slice(0,2);if(n.length>0)return n.join(" · ")}if(t){const n=t.split(`
|
|
13
|
+
</svg>`;return`url('data:image/svg+xml;base64,${btoa(r)}') ${i} ${i}, crosshair`}function ma(e,t,n=so.circle){return n===so.square?Ow(e,t):jw(e,t)}function Bl(e){return xc().includes(e)&&e!==ie.eraser}function Hl(e){return e===ie.eraser}function eo(e,t){var r;const n=document.querySelector(".plait-board-container"),o=n==null?void 0:n.querySelector(".board-host-svg");if(!o)return;const i=bn(e),s=((r=e.viewport)==null?void 0:r.zoom)||1;if(Bl(t)){const a=i.strokeWidth*s,c=t===ie.mask?Lw:i.strokeColor,u=ma(c,a,i.pencilShape);o.style.cursor=u}else if(Hl(t)){const a=i.eraserWidth*s,c=ma(Dw,a,i.eraserShape);o.style.cursor=c}else t===ge.text?o.style.cursor="crosshair":o.style.cursor=""}function Nw({board:e,pointer:t}){const n=p.useRef(1),o=p.useRef(null);return p.useEffect(()=>{var r;if(!e)return;eo(e,t),n.current=((r=e.viewport)==null?void 0:r.zoom)||1;let s=null;return(Bl(t)||Hl(t))&&(s=setInterval(()=>{var c;const a=((c=e.viewport)==null?void 0:c.zoom)||1;Math.abs(a-n.current)>.01&&(n.current=a,eo(e,t))},100)),()=>{s&&clearInterval(s),o.current&&cancelAnimationFrame(o.current);const a=document.querySelector(".plait-board-container"),c=a==null?void 0:a.querySelector(".board-host-svg");c&&(c.style.cursor="")}},[e,t]),{updateCursor:p.useCallback(()=>{e&&eo(e,t)},[e,t])}}function zw(e,t){eo(e,t)}function Fw(e){eo(e,ie.eraser)}const ji=1,wa=100,Bw=256,ya=1;let Oi=0;function Ni(e,t,n){return Math.max(t,Math.min(n,e))}function Hw(e){return e.key==="-"||e.key==="+"||e.key==="ArrowUp"||e.key==="ArrowRight"||e.key==="ArrowDown"||e.key==="ArrowLeft"||e.code==="NumpadAdd"||e.code==="NumpadSubtract"}function $w(e){return e.key==="-"||e.key==="ArrowDown"||e.key==="ArrowLeft"||e.code==="NumpadSubtract"?-ya:ya}function zi(e,t){var o;const n=((o=e.appState)==null?void 0:o.toolSettingsVersion)??0;Oi=Math.max(Oi,n)+1,t({toolSettingsVersion:Oi})}function Vw(e,t,n){if(!Hw(t)||t.altKey||t.metaKey||t.ctrlKey)return!1;const o=$w(t);if(F.isInPointer(e,[ie.eraser])){const i=bn(e),s=Ni(i.eraserWidth+o,ji,Bw);return fh(e,s),Fw(e),zi(e,n),!0}if(F.isInPointer(e,[ie.feltTipPen,ie.mask])){const i=bn(e),s=Ni(i.strokeWidth+o,ji,wa);return gh(e,s),zw(e,e.pointer),zi(e,n),!0}if(F.isInPointer(e,[zt.pen])){const i=Vc(e),s=Ni(i.strokeWidth+o,ji,wa);return bf(e,s),zi(e,n),!0}return!1}const Ww=e=>n=>{const{globalKeyDown:o,keyDown:i}=n;return n.globalKeyDown=s=>{const r=s.target instanceof HTMLInputElement||s.target instanceof HTMLTextAreaElement||s.target instanceof HTMLElement&&s.target.isContentEditable;if(!r){if(ve.isHotkey(["mod+k"])(s)){e({openCommandPalette:!0}),s.preventDefault();return}if(ve.isHotkey(["mod+f"])(s)){e({openCanvasSearch:!0}),s.preventDefault();return}}if(!r&&(F.getMovingPointInBoard(n)||F.isMovingPointInBoard(n))&&!F.hasBeenTextEditing(n)){if(ve.isHotkey(["mod+shift+e"],{byKey:!0})(s)){Do(n,!0),s.preventDefault();return}if(ve.isHotkey(["mod+s"],{byKey:!0})(s)){Bc(n),s.preventDefault();return}if(ve.isHotkey(["mod+backspace"])(s)||ve.isHotkey(["mod+delete"])(s)){e({openCleanConfirm:!0}),s.preventDefault();return}if(ve.isHotkey(["mod+u"])(s)&&js(n),Te(n).length>1){if(ve.isHotkey(["alt+a"])(s)){ln.alignLeft(n),s.preventDefault();return}if(ve.isHotkey(["alt+h"])(s)){ln.alignCenter(n),s.preventDefault();return}if(ve.isHotkey(["alt+d"])(s)){ln.alignRight(n),s.preventDefault();return}if(ve.isHotkey(["alt+w"])(s)){ln.alignTop(n),s.preventDefault();return}if(ve.isHotkey(["alt+v"])(s)){ln.alignMiddle(n),s.preventDefault();return}if(ve.isHotkey(["alt+s"])(s)){ln.alignBottom(n),s.preventDefault();return}if(ve.isHotkey(["shift+h"])(s)){Ei.distributeHorizontal(n),s.preventDefault();return}if(ve.isHotkey(["shift+v"])(s)){Ei.distributeVertical(n),s.preventDefault();return}if(ve.isHotkey(["shift+a"])(s)){Ei.autoArrange(n),s.preventDefault();return}if(ve.isHotkey(["alt+shift+u"])(s)){Cn.union(n,"zh"),s.preventDefault();return}if(ve.isHotkey(["alt+shift+s"])(s)){Cn.subtract(n,"zh"),s.preventDefault();return}if(ve.isHotkey(["alt+shift+i"])(s)){Cn.intersect(n,"zh"),s.preventDefault();return}if(ve.isHotkey(["alt+shift+e"])(s)){Cn.exclude(n,"zh"),s.preventDefault();return}if(ve.isHotkey(["alt+shift+f"])(s)){Cn.flatten(n,"zh"),s.preventDefault();return}}if(!s.altKey&&!s.metaKey&&!s.ctrlKey&&ve.isHotkey(["shift+p"],{byKey:!0})(s)){Re(n,He.drawing),ee.updatePointerType(n,zt.pen),e({pointer:zt.pen}),s.preventDefault();return}if(!s.altKey&&!s.metaKey&&!s.ctrlKey&&ve.isHotkey(["shift+m"],{byKey:!0})(s)){Re(n,He.drawing),ee.updatePointerType(n,ie.mask),e({pointer:ie.mask}),s.preventDefault();return}if(Vw(n,s,e)){s.preventDefault();return}if(!s.altKey&&!s.metaKey&&!s.ctrlKey&&!s.shiftKey){if(s.key==="l"){Re(n,He.drawing),ee.updatePointerType(n,ie.laserPointer),e({pointer:ie.laserPointer}),s.preventDefault();return}const c=[ie.feltTipPen,ie.mask,ie.eraser,ie.laserPointer];if(s.key==="Escape"&&F.isInPointer(n,c)){ee.updatePointerType(n,Le.selection),e({pointer:Le.selection}),s.preventDefault();return}if(s.key==="Backspace"&&F.isInPointer(n,[ie.feltTipPen,ie.mask])){n.undo(),s.preventDefault();return}if(s.key==="h"&&(ee.updatePointerType(n,Le.hand),e({pointer:Le.hand})),s.key==="v"&&(ee.updatePointerType(n,Le.selection),e({pointer:Le.selection})),s.key==="q"&&(ee.updatePointerType(n,lo),e({pointer:lo})),s.key==="m"&&(Re(n,He.dnd),ee.updatePointerType(n,io.mind),e({pointer:io.mind})),s.key==="e"&&(Re(n,He.drawing),ee.updatePointerType(n,ie.eraser),e({pointer:ie.eraser})),s.key==="p"&&(Re(n,He.drawing),ee.updatePointerType(n,ie.feltTipPen),e({pointer:ie.feltTipPen})),s.key==="a"&&!ve.isHotkey(["mod+a"])(s)&&Te(n).length===0&&(Re(n,He.drawing),ee.updatePointerType(n,xt.straight),e({pointer:xt.straight})),s.key==="f"&&(Re(n,He.drawing),ee.updatePointerType(n,fr),e({pointer:fr})),s.key==="r"||s.key==="o"||s.key==="t"){const u={r:ge.rectangle,o:ge.ellipse,t:ge.text};u[s.key]===ge.text?Re(n,null):Re(n,He.drawing),ee.updatePointerType(n,u[s.key]),e({pointer:u[s.key]})}s.preventDefault();return}}o(s)},n.keyDown=s=>{if(ve.isHotkey(["mod+z"],{byKey:!0})(s)){n.undo(),s.preventDefault();return}if(ve.isHotkey(["mod+shift+z"],{byKey:!0})(s)){n.redo(),s.preventDefault();return}i(s)},n};function qs(e){return e===so.square?"square":"round"}function Ys(e,t){const n=Math.min(t/50,1),o=.2+n*.1,i=6-n*4,s=o+e*(i-o);return Math.max(.5,t*s)}function Uw(e,t,n,o,i,s){const r=document.createElementNS("http://www.w3.org/2000/svg","g"),a=qs(s);if(e.length<2){if(e.length===1){const f=Ys(t[0]??.5,n);if(s===so.square){const g=document.createElementNS("http://www.w3.org/2000/svg","rect");g.setAttribute("x",String(e[0][0]-f/2)),g.setAttribute("y",String(e[0][1]-f/2)),g.setAttribute("width",String(f)),g.setAttribute("height",String(f)),g.setAttribute("fill",o),r.appendChild(g)}else{const g=document.createElementNS("http://www.w3.org/2000/svg","circle");g.setAttribute("cx",String(e[0][0])),g.setAttribute("cy",String(e[0][1])),g.setAttribute("r",String(f/2)),g.setAttribute("fill",o),r.appendChild(g)}}return r}const c=As(e,1,3);if(i===Ec.double){const f=n*.8,g=n*.4,[y,m]=Kw(c,t,g,f);if(y){const w=document.createElementNS("http://www.w3.org/2000/svg","path");w.setAttribute("d",y),w.setAttribute("fill",o),w.setAttribute("stroke","none"),r.appendChild(w)}if(m){const w=document.createElementNS("http://www.w3.org/2000/svg","path");w.setAttribute("d",m),w.setAttribute("fill",o),w.setAttribute("stroke","none"),r.appendChild(w)}return r}const u=kc(i,n),l=i!==Gn.solid&&u?u.join(" "):"",h=qw(c,t,n);if(h.length>0){const f=document.createElementNS("http://www.w3.org/2000/svg","path");f.setAttribute("d",h),f.setAttribute("fill",o),f.setAttribute("stroke","none"),l&&(f.setAttribute("fill","none"),f.setAttribute("stroke",o),f.setAttribute("stroke-width",String(n)),f.setAttribute("stroke-dasharray",l),f.setAttribute("stroke-linecap",a),f.setAttribute("stroke-linejoin",a==="square"?"miter":"round")),r.appendChild(f)}return r}function Gw(e,t,n,o){const i=document.createElementNS("http://www.w3.org/2000/svg","g"),s=qs(o);if(e.length<2){if(e.length===1){const m=t*.8,w=t*.4;if(o===so.square){const S=document.createElementNS("http://www.w3.org/2000/svg","rect");S.setAttribute("x",String(e[0][0]-w/2)),S.setAttribute("y",String(e[0][1]-m/2-w/2)),S.setAttribute("width",String(w)),S.setAttribute("height",String(w)),S.setAttribute("fill",n),i.appendChild(S);const v=document.createElementNS("http://www.w3.org/2000/svg","rect");v.setAttribute("x",String(e[0][0]-w/2)),v.setAttribute("y",String(e[0][1]+m/2-w/2)),v.setAttribute("width",String(w)),v.setAttribute("height",String(w)),v.setAttribute("fill",n),i.appendChild(v)}else{const S=document.createElementNS("http://www.w3.org/2000/svg","circle");S.setAttribute("cx",String(e[0][0])),S.setAttribute("cy",String(e[0][1]-m/2)),S.setAttribute("r",String(w/2)),S.setAttribute("fill",n),i.appendChild(S);const v=document.createElementNS("http://www.w3.org/2000/svg","circle");v.setAttribute("cx",String(e[0][0])),v.setAttribute("cy",String(e[0][1]+m/2)),v.setAttribute("r",String(w/2)),v.setAttribute("fill",n),i.appendChild(v)}}return i}const r=As(e,1,3),a=t*.8,c=t*.4,u=[],l=[];for(let m=0;m<r.length;m++){let w,S;m===0?(w=r[1][0]-r[0][0],S=r[1][1]-r[0][1]):m===r.length-1?(w=r[m][0]-r[m-1][0],S=r[m][1]-r[m-1][1]):(w=r[m+1][0]-r[m-1][0],S=r[m+1][1]-r[m-1][1]);const v=Math.sqrt(w*w+S*S);if(v>0){const E=-S/v,C=w/v,D=a/2;u.push([r[m][0]+E*D,r[m][1]+C*D]),l.push([r[m][0]-E*D,r[m][1]-C*D])}else u.push(r[m]),l.push(r[m])}const h=document.createElementNS("http://www.w3.org/2000/svg","path");let f=`M ${u[0][0]} ${u[0][1]}`;for(let m=1;m<u.length;m++){const w=u[m-1],S=u[m],v=(w[0]+S[0])/2,E=(w[1]+S[1])/2;f+=` Q ${w[0]} ${w[1]} ${v} ${E}`}f+=` L ${u[u.length-1][0]} ${u[u.length-1][1]}`,h.setAttribute("d",f),h.setAttribute("fill","none"),h.setAttribute("stroke",n),h.setAttribute("stroke-width",String(c)),h.setAttribute("stroke-linecap",s),h.setAttribute("stroke-linejoin",s==="square"?"miter":"round"),i.appendChild(h);const g=document.createElementNS("http://www.w3.org/2000/svg","path");let y=`M ${l[0][0]} ${l[0][1]}`;for(let m=1;m<l.length;m++){const w=l[m-1],S=l[m],v=(w[0]+S[0])/2,E=(w[1]+S[1])/2;y+=` Q ${w[0]} ${w[1]} ${v} ${E}`}return y+=` L ${l[l.length-1][0]} ${l[l.length-1][1]}`,g.setAttribute("d",y),g.setAttribute("fill","none"),g.setAttribute("stroke",n),g.setAttribute("stroke-width",String(c)),g.setAttribute("stroke-linecap",s),g.setAttribute("stroke-linejoin",s==="square"?"miter":"round"),i.appendChild(g),i}function Kw(e,t,n,o){if(e.length<2)return["",""];const i=[],s=[];for(let c=0;c<e.length;c++){let u,l;c===0?(u=e[1][0]-e[0][0],l=e[1][1]-e[0][1]):c===e.length-1?(u=e[c][0]-e[c-1][0],l=e[c][1]-e[c-1][1]):(u=e[c+1][0]-e[c-1][0],l=e[c+1][1]-e[c-1][1]);const h=Math.sqrt(u*u+l*l);if(h>0){const f=-l/h,g=u/h,y=o/2;i.push([e[c][0]+f*y,e[c][1]+g*y]),s.push([e[c][0]-f*y,e[c][1]-g*y])}else i.push(e[c]),s.push(e[c])}const r=va(i,t,n),a=va(s,t,n);return[r,a]}function va(e,t,n){if(e.length<2)return"";const o=[],i=[];for(let r=0;r<e.length;r++){const a=t[r]??.5,u=Ys(a,n)/2;let l,h;r===0?(l=e[1][0]-e[0][0],h=e[1][1]-e[0][1]):r===e.length-1?(l=e[r][0]-e[r-1][0],h=e[r][1]-e[r-1][1]):(l=e[r+1][0]-e[r-1][0],h=e[r+1][1]-e[r-1][1]);const f=Math.sqrt(l*l+h*h);if(f>0){const g=-h/f,y=l/f;o.push([e[r][0]+g*u,e[r][1]+y*u]),i.push([e[r][0]-g*u,e[r][1]-y*u])}else o.push(e[r]),i.push(e[r])}let s=`M ${o[0][0]} ${o[0][1]}`;for(let r=1;r<o.length;r++){const a=o[r-1],c=o[r],u=(a[0]+c[0])/2,l=(a[1]+c[1])/2;s+=` Q ${a[0]} ${a[1]} ${u} ${l}`}s+=` L ${o[o.length-1][0]} ${o[o.length-1][1]}`,s+=` L ${i[i.length-1][0]} ${i[i.length-1][1]}`;for(let r=i.length-2;r>=0;r--){const a=i[r+1],c=i[r],u=(a[0]+c[0])/2,l=(a[1]+c[1])/2;s+=` Q ${a[0]} ${a[1]} ${u} ${l}`}return s+=` L ${i[0][0]} ${i[0][1]}`,s+=" Z",s}function qw(e,t,n){if(e.length<2)return"";const o=[],i=[];for(let r=0;r<e.length;r++){const a=t[r]??.5,u=Ys(a,n)/2;let l,h;r===0?(l=e[1][0]-e[0][0],h=e[1][1]-e[0][1]):r===e.length-1?(l=e[r][0]-e[r-1][0],h=e[r][1]-e[r-1][1]):(l=e[r+1][0]-e[r-1][0],h=e[r+1][1]-e[r-1][1]);const f=Math.sqrt(l*l+h*h);if(f>0){const g=-h/f,y=l/f;o.push([e[r][0]+g*u,e[r][1]+y*u]),i.push([e[r][0]-g*u,e[r][1]-y*u])}else o.push(e[r]),i.push(e[r])}let s=`M ${o[0][0]} ${o[0][1]}`;for(let r=1;r<o.length;r++){const a=o[r-1],c=o[r],u=(a[0]+c[0])/2,l=(a[1]+c[1])/2;s+=` Q ${a[0]} ${a[1]} ${u} ${l}`}s+=` L ${o[o.length-1][0]} ${o[o.length-1][1]}`,s+=` L ${i[i.length-1][0]} ${i[i.length-1][1]}`;for(let r=i.length-2;r>=0;r--){const a=i[r+1],c=i[r],u=(a[0]+c[0])/2,l=(a[1]+c[1])/2;s+=` Q ${a[0]} ${a[1]} ${u} ${l}`}return s+=` L ${i[0][0]} ${i[0][1]}`,s+=" Z",s}class Xs extends ci{draw(t){const n=ph(t),o=mh(this.board,t),i=wh(this.board,t),s=yh(this.board,t),r=kc(s,n),a=t.brushShape,c=qs(a),u=f=>(f&&t.shape===ie.mask&&f.setAttribute("opacity",String(Sh)),f);if(t.pressures&&t.pressures.length>0)return u(Uw(t.points,t.pressures,n,o,s,a));if(s===Ec.double)return u(Gw(t.points,n,o,a));const l={strokeWidth:n,stroke:o,fill:i,fillStyle:"solid",strokeLineDash:s!==Gn.solid?r:void 0},h=F.getRoughSVG(this.board).curve(As(t.points,1,3),l);return vh(h,c),u(h)}canDraw(t){return!0}}class Yw extends wo{constructor(){super()}initializeGenerator(){this.activeGenerator=_s(this.board,{getRectangle:t=>di(t),getStrokeWidth:()=>no,getStrokeOpacity:()=>1,hasResizeHandle:()=>li(this.board,this.element)}),this.generator=new Xs(this.board)}initialize(){super.initialize(),this.initializeGenerator(),this.generator.processDrawing(this.element,this.getElementG())}onContextChanged(t,n){const o=t.board.viewport.zoom!==n.board.viewport.zoom||t.board.viewport.offsetX!==n.board.viewport.offsetX||t.board.viewport.offsetY!==n.board.viewport.offsetY;t.element!==n.element||t.hasThemeChanged?(this.generator.processDrawing(this.element,this.getElementG()),this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})):o&&t.selected?this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected}):(t.selected!==n.selected||t.selected)&&this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})}destroy(){var t;super.destroy(),(t=this.activeGenerator)==null||t.destroy()}}class $l{constructor(t={}){this.defaultOptions={smoothing:.65,velocityWeight:.2,curvatureWeight:.3,minDistance:.2,maxPoints:8,pressureSensitivity:.5,tiltSensitivity:.3,velocityThreshold:800,samplingRate:5},this.points=[],this.lastProcessedTime=0,this.movingAverageVelocity=[],this.velocityWindowSize=3,this.options={...this.defaultOptions,...t}}process(t,n={}){const o=n.timestamp??Date.now();if(this.points.length===0){const c={point:t,timestamp:o,...n};return this.points.push(c),this.lastProcessedTime=o,t}if(o-this.lastProcessedTime<this.options.samplingRate&&o-this.lastProcessedTime<2)return null;const i={point:t,timestamp:o,...n};if(!this.checkDistance(t)&&this.points.length>1&&o-this.lastProcessedTime<32)return null;this.updatePoints(i);const r=this.calculateDynamicParameters(i),a=this.smooth(t,r);return this.lastProcessedTime=o,a}reset(){this.points=[],this.lastProcessedTime=0,this.movingAverageVelocity=[]}updatePoints(t){this.points.push(t),this.points.length>this.options.maxPoints&&this.points.shift()}checkDistance(t){if(this.points.length===0)return!0;const n=this.points[this.points.length-1].point,o=this.getDistance(n,t);let i=this.options.minDistance;if(this.movingAverageVelocity.length>0){const s=this.getAverageVelocity();i*=Math.max(.5,Math.min(1.5,s/200))}return o>=i}calculateDynamicParameters(t){const n=this.calculateVelocity(t);this.updateMovingAverage(n);const o=this.getAverageVelocity(),i={...this.options};if(t.pressure!==void 0){const r=Math.pow(t.pressure,1.2);i.smoothing*=1-r*i.pressureSensitivity*.8}const s=Math.min(o/i.velocityThreshold,1);if(i.velocityWeight=.2+s*.3,i.smoothing*=1+s*.2,t.tiltX!==void 0&&t.tiltY!==void 0){const r=Math.sqrt(t.tiltX**2+t.tiltY**2)/90;i.smoothing*=1+r*i.tiltSensitivity*.7}return i}smooth(t,n){if(this.points.length<2)return t;const o=this.calculateWeights(n),i=o.reduce((r,a)=>r+a,0);if(i===0)return t;const s=[0,0];for(let r=0;r<this.points.length;r++){const a=o[r]/i;s[0]+=this.points[r].point[0]*a,s[1]+=this.points[r].point[1]*a}return s}calculateWeights(t){const n=[],o=this.points.length-1;for(let i=0;i<this.points.length;i++){let s=Math.pow(t.smoothing,(o-i)*.8);if(i<o){const r=this.getPointVelocity(i);s*=1+r*t.velocityWeight*.8}if(i>0&&i<o){const r=this.getPointCurvature(i);s*=1+r*t.curvatureWeight*.7}n.push(s)}return n}getDistance(t,n){return Bo(t[0],t[1],n[0],n[1])}calculateVelocity(t){if(this.points.length<2)return 0;const n=this.points[this.points.length-1],o=this.getDistance(n.point,t.point),i=t.timestamp-n.timestamp;return i>0?o/i:0}updateMovingAverage(t){this.movingAverageVelocity.push(t),this.movingAverageVelocity.length>this.velocityWindowSize&&this.movingAverageVelocity.shift()}getAverageVelocity(){return this.movingAverageVelocity.length===0?0:this.movingAverageVelocity.reduce((t,n)=>t+n)/this.movingAverageVelocity.length}getPointVelocity(t){if(t>=this.points.length-1)return 0;const n=this.points[t],o=this.points[t+1],i=this.getDistance(n.point,o.point),s=o.timestamp-n.timestamp;return s>0?i/s:0}getPointCurvature(t){if(t<=0||t>=this.points.length-1)return 0;const n=this.points[t-1].point,o=this.points[t].point,i=this.points[t+1].point,s=this.getDistance(n,o),r=this.getDistance(o,i),a=this.getDistance(n,i),c=(s+r+a)/2;return 4*Math.sqrt(Math.max(0,c*(c-s)*(c-r)*(c-a)))/(s*r*a+1e-4)}}const Xw=e=>{const{pointerDown:t,pointerMove:n,pointerUp:o,globalPointerUp:i}=e;let s=!1,r=!1,a=[],c=[],u=null;const l=new Xs(e),h=new $l({smoothing:.7,pressureSensitivity:.6});let f=null,g=!1,y=null,m=null,w=0;const S=(C=!1)=>{if(!y||C){const D=bn(e);y={strokeWidth:D.strokeWidth,strokeColor:D.strokeColor,strokeStyle:D.strokeStyle,pencilShape:D.pencilShape,pressureEnabled:D.pressureEnabled}}return y},v=(C,D)=>{if(!D)return 1;if(C.pointerType==="pen"&&C.pressure>0&&C.pressure!==.5)return C.pressure;const H=[C.x,C.y],B=performance.now();if(m&&w>0){const j=H[0]-m[0],U=H[1]-m[1],A=Math.sqrt(j*j+U*U),I=B-w;if(I>0){const k=A/I,T=.2,M=1,q=Math.min(k/1.5,1),le=M-q*(M-T);return m=H,w=B,le}}return m=H,w=B,.6},E=C=>{if(s){const D=F.getPointer(e);r&&(a.push(a[0]),c.length>0&&c.push(c[0]));const P=S();f=Zi(D,a,{strokeWidth:P.strokeWidth,strokeColor:P.strokeColor,strokeStyle:P.strokeStyle,brushShape:P.pencilShape,pressures:P.pressureEnabled?c:void 0})}f&&!C&&Se.insertNode(e,f,[e.children.length]),l==null||l.destroy(),f=null,s=!1,a=[],c=[],m=null,w=0,y=null,h.reset()};return e.pointerDown=C=>{if(mi(e,C)){g=!0,t(C);return}const D=xc();if(F.isInPointer(e,D)&&Ms(e)){s=!0;const H=S(!0);u=[C.x,C.y];const B=h.process(u);if(B){const j=Xe(e,Ze(e,B[0],B[1]));a.push(j),c.push(v(C,H.pressureEnabled))}}t(C)},e.pointerMove=C=>{if(g){n(C);return}if(s){const D=[C.x,C.y];u&&Bo(u[0],u[1],D[0],D[1])<8?r=!0:r=!1;const P=h.process(D);if(P){l==null||l.destroy();const H=Xe(e,Ze(e,P[0],P[1]));a.push(H);const B=S();c.push(v(C,B.pressureEnabled));const j=F.getPointer(e);f=Zi(j,a,{strokeWidth:B.strokeWidth,strokeColor:B.strokeColor,strokeStyle:B.strokeStyle,brushShape:B.pencilShape,pressures:B.pressureEnabled?c:void 0}),l.processDrawing(f,F.getElementTopHost(e))}return}n(C)},e.pointerUp=C=>{if(g){g=!1,o(C);return}E(),o(C)},e.globalPointerUp=C=>{g=!1,E(!0),i(C)},e},Zw=e=>{const t=e,{getDeletedFragment:n,buildFragment:o,insertFragment:i}=t;return t.getDeletedFragment=s=>{const r=gr(t);return r.length&&s.push(...r),n(s)},t.buildFragment=(s,r,a,c)=>{const u=gr(t);if(u.length){const l=bc(t,u,r?[r.x,r.y]:[0,0]);s=Rs(s,{text:"",type:Ds.elements,elements:l})}return o(s,r,a,c)},t.insertFragment=(s,r,a)=>{var u;const c=(u=s==null?void 0:s.elements)==null?void 0:u.filter(l=>De.isFreehand(l));c&&c.length>0&&_c(t,c,r),i(s,r,a)},t};function Vl(e){const t=Te(e);return t.length===1&&De.isFreehand(t[0])?t[0]:null}function Jw(e){return Vl(e)!==null}function Qw(e,t){const n=Vl(e);if(!n)return null;const o=di(n),i=n.angle||0,s=rn(o,t,i);return s?{element:n,rectangle:o,handle:s.handle,cursorClass:s.cursorClass}:null}function e0(e,t,n){const o=n.width/t.width,i=n.height/t.height;return e.map(s=>{const r=s[0]-t.x,a=s[1]-t.y;return[n.x+r*o,n.y+a*i]})}function t0(e,t,n){const{element:o,rectangle:i,handle:s}=t,{startPoint:r,endPoint:a}=n;if(!i)return;const c=a[0]-r[0],u=a[1]-r[1],l=Tn(i,s,c,u,vo(),10),h=e0(o.points,i,l),f=e.children.findIndex(g=>g.id===o.id);f>=0&&Se.setNode(e,{points:h},[f])}const n0=e=>sn(e,{key:"freehand",canResize:()=>Jw(e),hitTest:(t=>Qw(e,t)),onResize:(t,n)=>t0(e,t,n)}),go=1e3;async function Zs(){const e=await re(()=>import("./clipper-CpI1VJRD.js").then(t=>t.c),[],import.meta.url);return e.default||e}function po(e){return e.map(t=>({X:Math.round(t[0]*go),Y:Math.round(t[1]*go)}))}function Wl(e){return e.map(t=>[t.X/go,t.Y/go])}async function o0(e,t,n=pr.circle){if(e.length<2)return[];const o=await Zs(),i=po(e),s=new o.ClipperOffset;n===pr.square?s.AddPath(i,o.JoinType.jtMiter,o.EndType.etOpenSquare):s.AddPath(i,o.JoinType.jtRound,o.EndType.etOpenRound);const r=[];return s.Execute(r,t/2*go),r.length===0?[]:Wl(r[0])}function Js(e){const t=e.points;if(!t||t.length<3)return!1;const n=t[0],o=t[t.length-1];return Math.hypot(o[0]-n[0],o[1]-n[1])<=10}function i0(e,t=20){if($e.isPenPath(e)){if(!e.closed)return null;const n=Hc(e);return _f(n,!0,t)}if(De.isFreehand(e)){const n=e.points;return!n||n.length<3||!Js(e)?null:n}return K.isDrawElement(e)&&K.isShapeElement(e)?K.isImage(e)||K.isText(e)?null:s0(e,t):null}function s0(e,t=20){const n=e.points;if(!n||n.length<2)return[];const[o,i]=n,s=Math.min(o[0],i[0]),r=Math.min(o[1],i[1]),a=Math.abs(i[0]-o[0]),c=Math.abs(i[1]-o[1]),u=e.shape;if(u==="ellipse"||u==="circle"){const l=s+a/2,h=r+c/2,f=a/2,g=c/2,y=[],m=Math.PI*(3*(f+g)-Math.sqrt((3*f+g)*(f+3*g))),w=Math.max(180,Math.ceil(m/2));for(let S=0;S<w;S++){const v=2*Math.PI*S/w;y.push([l+f*Math.cos(v),h+g*Math.sin(v)])}return y}return[[s,r],[s+a,r],[s+a,r+c],[s,r+c]]}function r0(e,t,n,o){if(e.length<3)throw new Error("Polygon must have at least 3 points");let i=1/0,s=1/0,r=-1/0,a=-1/0;for(const h of e)i=Math.min(i,h[0]),s=Math.min(s,h[1]),r=Math.max(r,h[0]),a=Math.max(a,h[1]);const c=[i,s],u=e.map(h=>({point:[h[0]-c[0],h[1]-c[1]],type:"corner"}));return{id:Pc(),type:Tc,shape:zt.pen,points:[c,[r,a]],anchors:u,closed:!0,strokeColor:t,fill:n,strokeWidth:o}}function a0(e){let t="#333333",n="#FFFFFF",o=2;return $e.isPenPath(e)?(t=e.strokeColor||t,n=e.fill||n,o=e.strokeWidth||o):De.isFreehand(e)?(t=e.strokeColor||t,o=e.strokeWidth||o):K.isDrawElement(e)&&(t=e.strokeColor||t,n=e.fill||n,o=e.strokeWidth||o),{strokeColor:t,fill:n,strokeWidth:o}}async function c0(e,t){const n=await Zs(),o=new n.Clipper,i=[];return o.AddPath(po(e),n.PolyType.ptSubject,!0),o.AddPath(po(t),n.PolyType.ptClip,!0),o.Execute(n.ClipType.ctIntersection,i,n.PolyFillType.pftNonZero,n.PolyFillType.pftNonZero),i.length>0}async function l0(e,t,n){const o=i0(t);if(!o||o.length<3||!await c0(o,n))return null;const s=await Zs(),r=new s.Clipper,a=[];if(r.AddPath(po(o),s.PolyType.ptSubject,!0),r.AddPath(po(n),s.PolyType.ptClip,!0),!r.Execute(s.ClipType.ctDifference,a,s.PolyFillType.pftNonZero,s.PolyFillType.pftNonZero))return null;const{strokeColor:u,fill:l,strokeWidth:h}=a0(t),f=[];for(const v of a)if(v.length>=3){let E=0;for(let C=0;C<v.length;C++){const D=(C+1)%v.length;E+=v[C].X*v[D].Y,E-=v[D].X*v[C].Y}E=E/2,f.push({path:v,signedArea:E,absArea:Math.abs(E)})}if(f.length===0)return[];const g=[...f].sort((v,E)=>E.absArea-v.absArea),y=g[0],m=g.slice(1);let w;m.length>0?w=u0(y.path,m.map(v=>v.path)):w=y.path;const S=Wl(w);try{return[r0(S,u,l,h)]}catch{return[]}}function u0(e,t){let n=[...e];for(const o of t){let i=1/0,s=0,r=0;for(let c=0;c<n.length;c++)for(let u=0;u<o.length;u++){const l=n[c].X-o[u].X,h=n[c].Y-o[u].Y,f=l*l+h*h;f<i&&(i=f,s=c,r=u)}const a=[];for(let c=0;c<=s;c++)a.push(n[c]);for(let c=0;c<o.length;c++){const u=(r+c)%o.length;a.push(o[u])}a.push(o[r]);for(let c=s;c<n.length;c++)a.push(n[c]);n=a}return n}function Ul(e){if(De.isFreehand(e)){const i=e.points;if(!i||i.length<2)return null;const s=de.getRectangleByPoints(i),r=e.strokeWidth??2,a=r/2;return{x:s.x-a,y:s.y-a,width:s.width+r,height:s.height+r}}if($e.isPenPath(e)){const i=e.points;if(!i||i.length<2)return null;const[s,r]=i;return{x:Math.min(s[0],r[0]),y:Math.min(s[1],r[1]),width:Math.abs(r[0]-s[0]),height:Math.abs(r[1]-s[1])}}const t=e.points;if(!t||t.length<2)return null;const[n,o]=t;return{x:Math.min(n[0],o[0]),y:Math.min(n[1],o[1]),width:Math.abs(o[0]-n[0]),height:Math.abs(o[1]-n[1])}}function d0(e,t,n){if(t.length<2)return[];let o=1/0,i=1/0,s=-1/0,r=-1/0;for(const c of t)o=Math.min(o,c[0]-n),i=Math.min(i,c[1]-n),s=Math.max(s,c[0]+n),r=Math.max(r,c[1]+n);const a=[];for(const c of e.children){if(!h0(c))continue;const u=Ul(c);if(!u)continue;const{x:l,y:h,width:f,height:g}=u;l+f>=o&&l<=s&&h+g>=i&&h<=r&&a.push(c)}return a}function h0(e){return $e.isPenPath(e)?e.closed:De.isFreehand(e)?Js(e):K.isDrawElement(e)?K.isImage(e)||K.isText(e)||K.isArrowLine(e)||K.isVectorLine(e)?!1:K.isShapeElement(e):!1}function f0(e){if($e.isPenPath(e))return e.closed?null:"openPath";if(De.isFreehand(e))return Js(e)?null:"openPath";if(K.isDrawElement(e)){if(K.isImage(e))return"image";if(K.isText(e))return"text";if(K.isArrowLine(e))return"arrowLine";if(K.isVectorLine(e))return"vectorLine";if(K.isShapeElement(e))return null}return"unsupported"}function g0(e,t,n){if(t.length<2)return[];let o=1/0,i=1/0,s=-1/0,r=-1/0;for(const c of t)o=Math.min(o,c[0]-n),i=Math.min(i,c[1]-n),s=Math.max(s,c[0]+n),r=Math.max(r,c[1]+n);const a=[];for(const c of e.children){const u=Ul(c);if(!u)continue;const{x:l,y:h,width:f,height:g}=u;l+f>=o&&l<=s&&h+g>=i&&h<=r&&f0(c)&&a.push(c)}return a}async function p0(e,t,n,o,i){if(i.length===0)return;const s=await o0(t,n,o);if(s.length<3)return;const r=[],a=[];for(const c of i){const u=await l0(e,c,s);u!==null&&(r.push(c),a.push(...u))}r.length>0&&Ji.removeElements(e,r);for(const c of a)Se.insertNode(e,c,[e.children.length])}const m0=e=>{const{pointerDown:t,pointerMove:n,pointerUp:o,globalPointerUp:i}=e;let s=!1,r=!1;const a=new Set;let c=[];const u=f=>{const g=Xe(e,Ze(e,f[0],f[1])),m=bn(e).eraserWidth/2;e.children.filter(S=>De.isFreehand(S)).forEach(S=>{!a.has(S.id)&&xh(e,S,g,m)&&(vn.getElementG(S).style.opacity="0.2",a.add(S.id))})},l=()=>{if(a.size>0){const f=e.children.filter(g=>a.has(g.id));f.length>0&&Ji.removeElements(e,f)}},h=async()=>{if(s){if(l(),c.length>=2){const f=bn(e),g=d0(e,c,f.eraserWidth).filter(m=>!De.isFreehand(m));if(g.length>0)try{await p0(e,c,f.eraserWidth,f.eraserShape,g)}catch(m){console.error("Precise erase error:",m)}const y=g0(e,c,f.eraserWidth).filter(m=>!De.isFreehand(m)&&!So(m)&&!kh(m)&&!(K.isDrawElement(m)&&K.isImage(m)));y.length>0&&Ji.removeElements(e,y)}s=!1,a.clear(),c=[]}};return e.pointerDown=f=>{if(mi(e,f)){r=!0,t(f);return}if(F.isInPointer(e,[ie.eraser])&&Ms(e)){s=!0,a.clear(),c=[];const y=[f.x,f.y],m=Xe(e,Ze(e,y[0],y[1]));c.push(m),u(y);return}t(f)},e.pointerMove=f=>{if(r){n(f);return}if(s){Ts(e,"with-freehand-erase",()=>{const g=[f.x,f.y],y=Xe(e,Ze(e,g[0],g[1]));c.push(y),u(g)});return}n(f)},e.pointerUp=f=>{if(r){r=!1,o(f);return}if(s){h();return}o(f)},e.globalPointerUp=f=>{if(r=!1,s){h();return}i(f)},e},w0="#e91e63",y0=3,Sa=2e3,v0=e=>{const{pointerDown:t,pointerMove:n,pointerUp:o,globalPointerUp:i}=e;let s=!1,r=[];const a=new Xs(e),c=new $l({smoothing:.7,pressureSensitivity:0});let u=null;const l=[],h=()=>F.isPointer(e,ie.laserPointer),f=()=>{if(!s)return;s=!1;const y=a.g;y?(a.g=void 0,g(y)):a.destroy(),u=null,r=[],c.reset()},g=y=>{y.style.transition=`opacity ${Sa}ms ease-out`,y.style.opacity="1",y.getBoundingClientRect(),y.style.opacity="0";const m=window.setTimeout(()=>{y.remove();const w=l.findIndex(S=>S.g===y);w>=0&&l.splice(w,1)},Sa);l.push({g:y,timer:m})};return e.pointerDown=y=>{if(h()&&Ms(e)){s=!0;const m=[y.x,y.y],w=c.process(m);if(w){const S=Xe(e,Ze(e,w[0],w[1]));r.push(S)}return}t(y)},e.pointerMove=y=>{if(s){const m=[y.x,y.y],w=c.process(m);if(w){a.destroy();const S=Xe(e,Ze(e,w[0],w[1]));r.push(S),u=Zi(ie.laserPointer,r,{strokeWidth:y0,strokeColor:w0}),a.processDrawing(u,F.getElementTopHost(e))}return}n(y)},e.pointerUp=y=>{s&&f(),o(y)},e.globalPointerUp=y=>{s&&f(),i(y)},e},S0=e=>{const{getRectangle:t,drawElement:n,isHit:o,isRectangleHit:i,getOneHitElement:s,isMovable:r,isAlign:a}=e;return e.drawElement=c=>De.isFreehand(c.element)?Yw:n(c),e.getRectangle=c=>De.isFreehand(c)?di(c):t(c),e.isRectangleHit=(c,u)=>De.isFreehand(c)?Eh(e,c,u):i(c,u),e.isHit=(c,u,l)=>De.isFreehand(c)?bh(e,c,u):o(c,u,l),e.getOneHitElement=c=>c.every(l=>De.isFreehand(l))?Cc(e,c):s(c),e.isMovable=c=>De.isFreehand(c)?!0:r(c),e.isAlign=c=>De.isFreehand(c)?!0:a(c),e.setPluginOptions(Ic,{customGeometryTypes:[_h]}),v0(n0(m0(Zw(Xw(e)))))};class x0 extends wo{constructor(){super()}initializeGenerator(){this.activeGenerator=_s(this.board,{getRectangle:t=>fi(t),getStrokeWidth:()=>no,getStrokeOpacity:()=>1,hasResizeHandle:()=>li(this.board,this.element)}),this.generator=new Qm(this.board)}initialize(){super.initialize(),this.initializeGenerator(),this.generator.processDrawing(this.element,this.getElementG()),this.selected&&this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})}onContextChanged(t,n){const o=t.board.viewport.zoom!==n.board.viewport.zoom||t.board.viewport.offsetX!==n.board.viewport.offsetX||t.board.viewport.offsetY!==n.board.viewport.offsetY;t.element!==n.element||t.hasThemeChanged?(this.generator.processDrawing(this.element,this.getElementG()),this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})):o&&t.selected?this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected}):(t.selected!==n.selected||t.selected)&&this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})}destroy(){var t;super.destroy(),(t=this.activeGenerator)==null||t.destroy()}}const k0=e=>e,E0=e=>{const t=e,{getDeletedFragment:n,buildFragment:o,insertFragment:i}=t;return t.getDeletedFragment=s=>{const r=Er(t);return r.length&&s.push(...r),n(s)},t.buildFragment=(s,r,a,c)=>{const u=Er(t);if(u.length){const l=bc(t,u,r?[r.x,r.y]:[0,0]);s=Rs(s,{text:"",type:Ds.elements,elements:l})}return o(s,r,a,c)},t.insertFragment=(s,r,a)=>{var u;const c=(u=s==null?void 0:s.elements)==null?void 0:u.filter(l=>$e.isPenPath(l));c&&c.length>0&&_c(t,c,r),i(s,r,a)},t};function Gl(e){const t=Te(e);return t.length===1&&$e.isPenPath(t[0])?t[0]:null}function b0(e){return Gl(e)!==null}function _0(e,t){const n=Gl(e);if(!n)return null;const o=fi(n),i=n.angle||0,s=rn(o,t,i);return s?{element:n,rectangle:o,handle:s.handle,cursorClass:s.cursorClass}:null}function P0(e,t,n){return e.map(o=>({...o,point:[o.point[0]*t,o.point[1]*n],handleIn:o.handleIn?[o.handleIn[0]*t,o.handleIn[1]*n]:void 0,handleOut:o.handleOut?[o.handleOut[0]*t,o.handleOut[1]*n]:void 0}))}function T0(e,t,n){const{element:o,rectangle:i,handle:s}=t,{startPoint:r,endPoint:a}=n;if(!i)return;const c=a[0]-r[0],u=a[1]-r[1],l=Tn(i,s,c,u,vo(),10),h=l.width/i.width,f=l.height/i.height,g=P0(o.anchors,h,f),m=[[l.x,l.y],[l.x+l.width,l.y+l.height]],w=e.children.findIndex(S=>S.id===o.id);w>=0&&Se.setNode(e,{points:m,anchors:g},[w])}const C0=e=>sn(e,{key:"pen-path",canResize:()=>b0(e),hitTest:(t=>_0(e,t)),onResize:(t,n)=>T0(e,t,n)}),I0=e=>{const{getRectangle:t,drawElement:n,isHit:o,isRectangleHit:i,getOneHitElement:s,isMovable:r,isAlign:a}=e;return e.drawElement=c=>$e.isPenPath(c.element)?x0:n(c),e.getRectangle=c=>$e.isPenPath(c)?fi(c):t(c),e.isRectangleHit=(c,u)=>$e.isPenPath(c)?Pf(e,c,u):i(c,u),e.isHit=(c,u,l)=>$e.isPenPath(c)?Tf(e,c,u):o(c,u,l),e.getOneHitElement=c=>c.every(l=>$e.isPenPath(l))?Cc(e,c):s(c),e.isMovable=c=>$e.isPenPath(c)?!0:r(c),e.isAlign=c=>$e.isPenPath(c)?!0:a(c),e.setPluginOptions(Ic,{customGeometryTypes:[Tc]}),C0(E0(k0(aw(e))))},Kl=new WeakMap,xa=e=>!!Kl.get(e),ql=(e,t)=>{Kl.set(e,t)},A0=e=>n=>{const{pointerDown:o}=n;return n.pointerDown=i=>{mr(i)&&!xa(n)&&(ql(n,!0),e({isPencilMode:!0})),!(xa(n)&&!mr(i)&&!mi(n,i))&&o(i)},n},M0=()=>{const e=Ye(),{appState:t,setAppState:n}=Ht();return d.jsx(d.Fragment,{children:t.isPencilMode&&d.jsx("div",{className:"pencil-mode-toolbar",children:d.jsx(je,{type:"button",visible:!0,tooltip:"X Pencil","aria-label":"Arrow",label:"Pencil X",onPointerDown:()=>{n({...t,isPencilMode:!1}),ql(e,!1)}})})})},ka=e=>{const{appState:t}=e;return t&&t.linkState&&t.linkState.isHovering},Ea=e=>{const{appState:t}=e;return t&&t.linkState&&t.linkState.isEditing},R0=e=>n=>{const{pointerMove:o}=n;let i=null,s=null;return n.pointerMove=r=>{(F.isPointer(n,Le.selection)||F.isPointer(n,Le.hand))&&!Qi(n)&&!Xa(n)&&!ka(n)&&!Ea(n)&&Ts(n,"with-text-link",()=>{const a=r.target.closest(".plait-board-link");if(a&&a!==i){const c=a.closest(".plait-text-container"),u=mn.toSlateNode(void 0,c),l=mn.toSlateNode(void 0,a);i=a,e({linkState:{targetDom:a,targetElement:l,editor:u,isEditing:!1,isHovering:!1,isHoveringOrigin:!0}}),clearTimeout(s)}else!a&&i&&(s=setTimeout(()=>{!ka(n)&&!Ea(n)&&e({linkState:null})},300),i=null)}),o(r)},n},Wn={autoTrack:!1,debounceTime:500,retryPolicy:{maxRetries:3,retryInterval:2e3,exponentialBackoff:!0},cacheConfig:{maxCacheSize:100,cacheTTL:3600*1e3,storageKey:"tracking_cache"},logLevel:"error",batchConfig:{batchSize:10,batchTimeout:5e3,enabled:!0},excludedSelectors:["nav","header","footer","[data-track-ignore]"],devMode:!1};function D0(){return"1.0.2"}function ba(e){return{...Wn,...e,retryPolicy:{...Wn.retryPolicy,...e.retryPolicy||{}},cacheConfig:{...Wn.cacheConfig,...e.cacheConfig||{}},batchConfig:{...Wn.batchConfig,...e.batchConfig||{}}}}class L0{isAvailable(){return tt.isAnalyticsEnabled()}async track(t){if(!this.isAvailable())return;const n={...t.params,version:t.metadata.version,url:t.metadata.url,timestamp:t.metadata.timestamp,sessionId:t.metadata.sessionId,eventType:t.metadata.eventType};t.metadata.viewport&&(n.viewport=`${t.metadata.viewport.width}x${t.metadata.viewport.height}`);try{tt.track(t.eventName,n)}catch(o){throw console.error("[Tracking] PostHog track failed:",o),o}}async trackBatch(t){const n=[];for(const o of t)try{await this.track(o),n.push({success:!0})}catch(i){n.push({success:!1,error:i})}return n}getSDKInfo(){return{available:this.isAvailable(),version:this.isAvailable()?"PostHog JS":void 0}}}const _a=new L0;class j0{constructor(t){this.queue=[],this.timer=null,this.uploading=!1,this.config=t}enqueue(t){if(!this.config.enabled){this.uploadImmediate(t);return}this.queue.push(t),this.timer||(this.timer=setTimeout(()=>{this.flush()},this.config.batchTimeout)),this.queue.length>=this.config.batchSize&&this.flush()}async flush(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),this.queue.length===0||this.uploading)return;this.uploading=!0;const t=[...this.queue];this.queue=[];try{const n=await _a.trackBatch(t),o=n.filter(i=>!i.success);if(o.length>0){console.error(`Batch upload: ${o.length}/${t.length} events failed`);const i=t.filter((s,r)=>!n[r].success);this.requeueFailedEvents(i)}}catch(n){console.error("Batch upload failed:",n),this.requeueFailedEvents(t)}finally{this.uploading=!1}}async uploadImmediate(t){try{await _a.track(t)}catch(n){console.error("Immediate upload failed:",n)}}requeueFailedEvents(t){this.queue=[...t,...this.queue]}getQueueSize(){return this.queue.length}isUploading(){return this.uploading}updateConfig(t){this.config={...this.config,...t},!this.config.enabled&&this.queue.length>0&&this.flush()}clear(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.queue=[],this.uploading=!1}flushOnUnload(){this.queue.length!==0&&this.flush()}}class O0{constructor(t=500){this.debounceMap=new WeakMap,this.globalDebounceMap=new Map,this.globalDebounceTime=200,this.debounceTime=t}shouldTrack(t,n,o=!1){const i=Date.now(),s=this.globalDebounceMap.get(n);if(s&&i-s<this.globalDebounceTime)return o&&console.warn(`[Tracking] 🚫 Global debounce: ${n} (${i-s}ms ago)`),!1;const r=this.debounceMap.get(t);if(!r){const c=new Map;return c.set(n,i),this.debounceMap.set(t,c),this.globalDebounceMap.set(n,i),!0}const a=r.get(n);return!a||i-a>this.debounceTime?(r.set(n,i),this.globalDebounceMap.set(n,i),!0):(o&&console.warn(`[Tracking] 🚫 Element debounce: ${n} (${i-a}ms ago)`),!1)}clear(t){this.debounceMap.delete(t)}setDebounceTime(t){this.debounceTime=t}}const N0=["button:not([data-track-ignore])","a:not([data-track-ignore])",'input[type="button"]:not([data-track-ignore])','input[type="submit"]:not([data-track-ignore])','[role="button"]:not([data-track-ignore])','[role="link"]:not([data-track-ignore])'].join(", ");function z0(e,t){if(!e.matches(N0))return!1;for(const o of t)if(e.matches(o)||e.closest(o))return!1;return e.hasAttribute("data-track-ignore")?!1:(e.onclick!==null,!0)}function F0(e,t="click"){var a;const n=`auto_${t}_`;if(e.id)return`${n}${e.id}`;const o=e.getAttribute("aria-label");if(o)return`${n}${Pa(o)}`;const i=(a=e.textContent)==null?void 0:a.trim();if(i&&i.length>0){const c=Pa(i.substring(0,20));return`${n}${c}`}const s=e.tagName.toLowerCase(),r=e.className?`.${e.className.split(" ")[0]}`:"";return`${n}${s}${r}`}function Pa(e){return e.toLowerCase().trim().replace(/\s+/g,"_").replace(/[^a-z0-9_-]/g,"").substring(0,50)}function B0(e){if(e.id)return`#${e.id}`;const t=[];let n=e;for(;n&&n!==document.body;){let o=n.tagName.toLowerCase();if(n.className){const i=n.className.split(" ").filter(Boolean);i.length>0&&(o+=`.${i[0]}`)}t.unshift(o),n=n.parentElement}return t.join(" > ")}function Fi(e){const t=e.getAttribute("data-track-params")||e.getAttribute("track-params");if(!t)return null;try{return JSON.parse(t)}catch(n){return console.warn("Invalid track params JSON on element:",e,n),null}}function Yl(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function H0(){if(typeof window>"u")return"server-side";const e="tracking_session_id";let t=sessionStorage.getItem(e);return t||(t=Yl(),sessionStorage.setItem(e,t)),t}function $0(){return typeof window>"u"?{width:0,height:0}:{width:window.innerWidth||0,height:window.innerHeight||0}}class V0{constructor(t={}){this.state$=new Ph({initialized:!1,config:Wn,pendingEvents:[],uploading:!1,cachedEventCount:0,stats:{totalEvents:0,successfulUploads:0,failedUploads:0,batchUploadCount:0,debouncedEvents:0}}),this.clickListener=null,this.mutationObserver=null,this.attachedListeners=new WeakMap,this.config=ba(t),this.batchService=new j0(this.config.batchConfig),this.debouncer=new O0(this.config.debounceTime),this.updateState({config:this.config,initialized:!1})}initialize(){if(this.state$.value.initialized){this.log("debug","Tracking service already initialized");return}this.setupClickDelegation(),this.setupMultiEventListeners(),this.setupMutationObserver(),this.setupBeforeUnload(),this.updateState({initialized:!0}),this.log("debug","Tracking service initialized")}setupClickDelegation(){typeof window>"u"||typeof document>"u"||(this.clickListener=t=>{const n=t.target;if(!n)return;const o=n.closest("[data-track]");if(o){const i=o.getAttribute("data-track");if(i){if(this.isElementExcluded(o))return;this.trackClick(o,i);return}}if(this.config.autoTrack&&z0(n,this.config.excludedSelectors)){if(this.isElementExcluded(n))return;const i=F0(n,"click");this.trackClick(n,i)}},document.body.addEventListener("click",this.clickListener,!0))}setupMultiEventListeners(){if(typeof document>"u")return;document.querySelectorAll("[track-hover]").forEach(o=>{this.attachHoverListener(o)}),document.querySelectorAll("[track-focus]").forEach(o=>{this.attachFocusListener(o)})}attachHoverListener(t){const n=t.getAttribute("track-hover");if(!n||this.hasAttachedListener(t,"hover"))return;const o=()=>{if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents");return}const i=Fi(t),s=this.createTrackEvent(n,i,"hover",t);this.track(s)};t.addEventListener("mouseenter",o),this.markListenerAttached(t,"hover")}attachFocusListener(t){const n=t.getAttribute("track-focus");if(!n||this.hasAttachedListener(t,"focus"))return;const o=()=>{if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents");return}const i=Fi(t),s=this.createTrackEvent(n,i,"focus",t);this.track(s)};t.addEventListener("focus",o,!0),this.markListenerAttached(t,"focus")}hasAttachedListener(t,n){const o=this.attachedListeners.get(t);return o?o.has(n):!1}markListenerAttached(t,n){let o=this.attachedListeners.get(t);o||(o=new Set,this.attachedListeners.set(t,o)),o.add(n)}setupMutationObserver(){typeof window>"u"||typeof MutationObserver>"u"||(this.mutationObserver=new MutationObserver(t=>{t.forEach(n=>{n.addedNodes.forEach(o=>{if(o.nodeType===Node.ELEMENT_NODE){const i=o;i.hasAttribute("track-hover")&&this.attachHoverListener(i),i.hasAttribute("track-focus")&&this.attachFocusListener(i),i.querySelectorAll("[track-hover]").forEach(a=>this.attachHoverListener(a)),i.querySelectorAll("[track-focus]").forEach(a=>this.attachFocusListener(a))}})})}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}))}trackClick(t,n){if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents"),this.log("debug",`Event debounced: ${n}`);return}const o=Fi(t),i=this.createTrackEvent(n,o,"click",t);this.track(i)}createTrackEvent(t,n,o,i){const s={timestamp:Date.now(),url:typeof window<"u"?window.location.href:"",version:D0(),sessionId:H0(),userAgent:typeof navigator<"u"?navigator.userAgent:void 0,viewport:$0(),eventType:o},r={eventName:t,params:n||void 0,metadata:s,id:Yl(),createdAt:Date.now()};return this.config.devMode&&this.log("debug",`Event created: ${t}`,{params:n,element:i?B0(i):void 0}),r}track(t){this.incrementStat("totalEvents"),this.batchService.enqueue(t),this.log("debug",`Event tracked: ${t.eventName}`)}isElementExcluded(t){if(t.hasAttribute("data-track-ignore"))return!0;for(const n of this.config.excludedSelectors)if(t.matches(n)||t.closest(n))return!0;return!1}setupBeforeUnload(){typeof window>"u"||window.addEventListener("beforeunload",()=>{this.batchService.flushOnUnload()})}getState(){return this.state$.asObservable()}getStats(){return this.state$.value.stats}updateConfig(t){this.config=ba({...this.config,...t}),t.batchConfig&&this.batchService.updateConfig(t.batchConfig),t.debounceTime&&this.debouncer.setDebounceTime(t.debounceTime),this.updateState({config:this.config}),this.log("debug","Configuration updated",t)}destroy(){this.clickListener&&typeof document<"u"&&(document.body.removeEventListener("click",this.clickListener,!0),this.clickListener=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.attachedListeners=new WeakMap,this.batchService.flush(),this.updateState({initialized:!1}),this.log("debug","Tracking service destroyed")}updateState(t){this.state$.next({...this.state$.value,...t})}incrementStat(t){const n={...this.state$.value.stats};n[t]++,this.updateState({stats:n})}log(t,n,o){this.config.logLevel!=="silent"&&(t==="error"||t==="debug"&&this.config.devMode)}}let Pt=null;function W0(){Pt&&(Pt.destroy(),Pt=null)}function U0(e,t){return Pt||(Pt=new V0(t),typeof window<"u"&&setTimeout(()=>{Pt==null||Pt.initialize()},0),typeof module<"u"&&module.hot&&module.hot.dispose(()=>{W0()})),e.trackingService=Pt,e}class G0 extends wo{initialize(){super.initialize()}}const K0=e=>{const{drawElement:t}=e;return e.drawElement=n=>{try{return t(n)}catch{return console.warn(`[Drawnix] Unknown element type "${n.element.type}" — may be from a newer version, hidden but preserved.`),G0}},e};function q0(e){const t=Te(e);return t.length!==1?!1:Wc(t[0])}function Y0(e,t){const n=Te(e);if(n.length!==1||!Wc(n[0]))return null;const o=n[0],i=de.getRectangleByPoints(o.points),s=o.angle||0,r=rn(i,t,s);return r?{element:o,rectangle:i,handle:r.handle,cursorClass:r.cursorClass}:null}function X0(e,t,n){const{element:o,rectangle:i,handle:s}=t,{startPoint:r,endPoint:a}=n;if(!i){console.warn("startRectangle is undefined");return}const c=a[0]-r[0],u=a[1]-r[1],l=Tn(i,s,c,u,vo(),100),h=[[l.x,l.y],[l.x+l.width,l.y+l.height]],f=e.children.findIndex(g=>g.id===o.id);f>=0&&Se.setNode(e,{points:h},[f])}const Z0=e=>sn(e,{key:"tool-elements",canResize:()=>q0(e),hitTest:(t=>Y0(e,t)),onResize:(t,n)=>X0(e,t,n)});let Jo=null;function J0(e,t){return De.isFreehand(t)?di(t):$e.isPenPath(t)?fi(t):e.getRectangle(t)}function Qs(e){return e.some(t=>De.isFreehand(t)||$e.isPenPath(t)||K.isText(t))}function Q0(e){return e.some(t=>K.isText(t))}function Xl(e){const t=Te(e);if(t.length<2||!Qs(t))return null;try{const n=Ft(e,t,!1);return{elements:t,rectangle:n}}catch{return null}}function ey(e){return Xl(e)!==null}function ty(e,t){const n=Xl(e);if(!n)return null;const o=rn(n.rectangle,t);if(o){Jo=new Map;for(const i of n.elements){const s=J0(e,i);s&&Jo.set(i.id,{element:JSON.parse(JSON.stringify(i)),rectangle:{...s}})}return{element:n.elements,rectangle:n.rectangle,handle:o.handle,cursorClass:o.cursorClass}}return null}function ny(e,t,n,o,i,s){const r=s.width/i.width,a=s.height/i.height,c=o.x-i.x,u=o.y-i.y,l=s.x+c*r,h=s.y+u*a,f=n.points.map(y=>{const m=y[0]-o.x,w=y[1]-o.y,S=m*r,v=w*a;return[l+S,h+v]}),g=e.children.findIndex(y=>y.id===t);g>=0&&Se.setNode(e,{points:f},[g])}function oy(e,t,n,o,i,s){const r=s.width/i.width,a=s.height/i.height,c=o.x-i.x,u=o.y-i.y,l=s.x+c*r,h=s.y+u*a,f=n.anchors.map(v=>({...v,point:[v.point[0]*r,v.point[1]*a],handleIn:v.handleIn?[v.handleIn[0]*r,v.handleIn[1]*a]:void 0,handleOut:v.handleOut?[v.handleOut[0]*r,v.handleOut[1]*a]:void 0})),g=o.width*r,y=o.height*a,w=[[l,h],[l+g,h+y]],S=e.children.findIndex(v=>v.id===t);S>=0&&Se.setNode(e,{points:w,anchors:f},[S])}const Zl=14;function Jl(e,t){const n={...e};if("text"in e&&typeof e.text=="string"){const o=e["font-size"]?parseFloat(e["font-size"]):Zl,i=Math.max(1,Math.round(o*t*10)/10);n["font-size"]=`${i}`}return Array.isArray(e.children)&&(n.children=e.children.map(o=>Jl(o,t))),n}function iy(e,t,n,o,i,s){const r=s.width/i.width,a=s.height/i.height,c=o.x-i.x,u=o.y-i.y,l=s.x+c*r,h=s.y+u*a,f=o.width*r,g=o.height*a,y=[[l,h],[l+f,h+g]],m=e.children.findIndex(w=>w.id===t);if(m>=0)if(K.isDrawElement(n)&&K.isImage(n))Se.setNode(e,{points:y,width:f,height:g},[m]);else if(K.isText(n)){const w=n,S=Jl(w.text,r),v=w.textHeight||Zl*1.4;Se.setNode(e,{points:y,text:S,textHeight:v*r,autoSize:!1},[m])}else Se.setNode(e,{points:y},[m])}function sy(e,t,n){const{element:o,rectangle:i,handle:s}=t,{startPoint:r,endPoint:a}=n;if(!i||!Array.isArray(o)||!Jo)return;const c=a[0]-r[0],u=a[1]-r[1],l=vo()||Q0(o),h=Tn(i,s,c,u,l);for(const f of o){const g=Jo.get(f.id);if(!g)continue;const{element:y,rectangle:m}=g;De.isFreehand(y)?ny(e,f.id,y,m,i,h):$e.isPenPath(y)?oy(e,f.id,y,m,i,h):iy(e,f.id,y,m,i,h)}}function ry(e){const t=Te(e);if(t.length<2||!Qs(t))return null;try{const n=yo(),o=Ft(e,t,!1),i=Ac(e,o);return de.getCornerPoints(i).forEach(r=>{const a=Th(e,r);n.append(a)}),n}catch{return null}}const ay=e=>{const{afterChange:t}=e;let n=null;return e.afterChange=()=>{t(),n&&(n.remove(),n=null);const o=Te(e);o.length>1&&Qs(o)&&!oo(e)&&(n=ry(e),n&&F.getActiveHost(e).append(n))},sn(e,{key:"multi-resize",canResize:()=>ey(e),hitTest:(o=>ty(e,o)),onResize:(o,i)=>sy(e,o,i)})},Ql=14;let No=null,vs=null;function eu(e,t){const n={...e};if("text"in e&&typeof e.text=="string"){const o=e["font-size"]?parseFloat(e["font-size"]):Ql,i=Math.max(1,Math.round(o*t*10)/10);n["font-size"]=`${i}`}return Array.isArray(e.children)&&(n.children=e.children.map(o=>eu(o,t))),n}function cy(e){const t=Te(e);return t.length!==1?!1:K.isText(t[0])}function ly(e,t){const n=Te(e);if(n.length!==1||!K.isText(n[0]))return null;const o=n[0],i=de.getRectangleByPoints(o.points),s=rn(i,t);return s?(No=JSON.parse(JSON.stringify(o)),vs={...i},{element:o,rectangle:i,handle:s.handle,cursorClass:s.cursorClass}):null}function uy(e,t,n){const{element:o,rectangle:i,handle:s}=t,{startPoint:r,endPoint:a}=n;if(!i||!No||!vs)return;const c=a[0]-r[0],u=a[1]-r[1],l=Tn(i,s,c,u,!0,20),h=l.width/vs.width;if(h<=0)return;const f=eu(No.text,h),y=(No.textHeight||Ql*1.4)*h,m=[[l.x,l.y],[l.x+l.width,l.y+l.height]],w=e.children.findIndex(S=>S.id===o.id);w>=0&&Se.setNode(e,{points:m,text:f,textHeight:y,autoSize:!1},[w])}const dy=e=>sn(e,{key:"text-resize",canResize:()=>cy(e),hitTest:t=>ly(e,t),onResize:(t,n)=>uy(e,t,n)});function hy(e){return e.some(n=>De.isFreehand(n)||$e.isPenPath(n))}function fy(e){const t=Te(e);if(t.length<2||!hy(t))return null;try{return Ft(e,t,!1)}catch{return null}}const gy=()=>{const e=Ye(),[t,n]=p.useState([]),[o,i]=p.useState(!1),[s,r]=p.useState(!1),a=p.useRef(!1),c=p.useCallback(()=>{const h=Ki(e)||Qi(e)||oo(e);if(r(h),h)return;Te(e);const f=fy(e);if(!f){i(!1);return}const y=[{x:f.x,y:f.y,cursor:"nwse-resize"},{x:f.x+f.width,y:f.y,cursor:"nesw-resize"},{x:f.x+f.width,y:f.y+f.height,cursor:"nwse-resize"},{x:f.x,y:f.y+f.height,cursor:"nesw-resize"}].map(m=>{const w=Ch(e,[m.x,m.y]);return{x:w[0],y:w[1],cursor:m.cursor}});n(y),i(!0)},[e]);if(p.useEffect(()=>{a.current=s},[s]),p.useEffect(()=>{c();let h,f=JSON.stringify(e.viewport),g=JSON.stringify(e.selection),y=e.children.length;const m=()=>{const w=JSON.stringify(e.viewport),S=JSON.stringify(e.selection),v=e.children.length,E=Ki(e)||Qi(e)||oo(e);(w!==f||S!==g||v!==y||E!==a.current)&&(f=w,g=S,y=v,c()),h=requestAnimationFrame(m)};return h=requestAnimationFrame(m),()=>{cancelAnimationFrame(h)}},[e,c]),!o||t.length===0||s)return null;const u=Ih,l=u/2;return d.jsx("div",{className:me("multi-selection-handles",En),children:t.map((h,f)=>d.jsx("div",{className:"multi-selection-handle",style:{left:h.x-l,top:h.y-l,width:u,height:u,cursor:h.cursor}},f))})};class py{constructor(){this.board=null}setBoard(t){this.board=t}getBoard(){return this.board||console.error("❌ Board instance not set. Call testToolbox.setBoard(board) first"),this.board}insertBananaPrompt(){const t=this.getBoard();if(!t)return;const n=Eo.getToolById("banana-prompt");if(!n){console.error('❌ Tool "banana-prompt" not found');return}un.insertTool(t,n.id,n.url,[100,100],{width:n.defaultWidth||dn.defaultWidth,height:n.defaultHeight||dn.defaultHeight},{name:n.name,category:n.category,permissions:n.permissions})}insertXiaohongshuTool(){const t=this.getBoard();if(!t)return;const n=Eo.getToolById("xiaohongshu-tool");if(!n){console.error('❌ Tool "xiaohongshu-tool" not found');return}un.insertTool(t,n.id,n.url,[300,300],{width:n.defaultWidth||dn.defaultWidth,height:n.defaultHeight||dn.defaultHeight},{name:n.name,category:n.category,permissions:n.permissions})}insertToolById(t,n=200,o=200){const i=this.getBoard();if(!i)return;const s=Eo.getToolById(t);if(!s){console.error(`❌ Tool "${t}" not found`);return}un.insertTool(i,s.id,s.url,[n,o],{width:s.defaultWidth||dn.defaultWidth,height:s.defaultHeight||dn.defaultHeight},{name:s.name,category:s.category,permissions:s.permissions})}listAllTools(){Eo.getAvailableTools().forEach((n,o)=>{})}getAllToolElements(){const t=this.getBoard();if(!t)return;un.getAllTools(t).forEach((o,i)=>{})}removeAllTools(){const t=this.getBoard();if(!t)return;un.getAllTools(t).forEach(o=>{un.removeTool(t,o.id)})}help(){}}const my=new py;typeof window<"u"&&(window.testToolbox=my);const wy={width:200,height:150,position:"bottom-right",margin:16,collapsible:!0,defaultExpanded:!1,backgroundColor:"rgba(255, 255, 255, 0.95)",borderColor:"rgba(0, 0, 0, 0.1)",viewportColor:"rgba(90, 79, 207, 0.3)",elementColor:"rgba(0, 0, 0, 0.5)"},yy={autoHideDelay:3e3},vy=e=>{if(!e)return null;const[t,n]=e.trim().split(/[\s,]+/).map(o=>Number(o));return!Number.isFinite(t)||!Number.isFinite(n)?null:{x:t,y:n}},Sy=e=>{const t=e.viewport.zoom;if(!Number.isFinite(t)||t<=0)return null;try{const n=F.getViewportContainer(e),o=F.getHost(e),i=vy(o.getAttribute("viewBox"));return i?[n.scrollLeft/t+i.x,n.scrollTop/t+i.y]:null}catch{return null}},tu=e=>{const t=Sy(e);return t||si(e)||e.viewport.origination||[0,0]},xy=e=>{const[t,n]=tu(e);return{zoom:e.viewport.zoom,originX:t,originY:n}},ky=({board:e,config:t,className:n,displayMode:o="auto",autoTriggerConfig:i})=>{const s=p.useRef(null),r=p.useRef(null);p.useRef(null);const a={...wy,...t},c={...yy,...i},[u,l]=p.useState(()=>({expanded:o==="always"?!0:a.defaultExpanded,dragging:!1,autoMode:o==="auto",manuallyExpanded:!1})),h=p.useRef({isDragging:!1,startPoint:null}),f=p.useRef(null),[g,y]=p.useState(null),m=p.useRef(null),[w,S]=p.useState(!1),v=120,E=p.useRef(0),C=p.useRef(null),D=p.useCallback(()=>{if(!e||!e.children)return[];const N=[];return e.children.forEach(b=>{try{let x=null;b.points&&Array.isArray(b.points)?x=de.getRectangleByPoints(b.points):b.x!==void 0&&b.y!==void 0&&(x={x:b.x,y:b.y,width:b.width||100,height:b.height||100}),x&&x.width>0&&x.height>0&&N.push({id:b.id,bounds:x,type:b.type})}catch(x){console.warn("Failed to get bounds for element:",b.id,x)}}),N},[e]),P=p.useCallback(()=>{const b=F.getBoardContainer(e).getBoundingClientRect(),x=e.viewport.zoom,_=tu(e),z=_[0],G=_[1],$=b.width/x,ne=b.height/x;return{x:z,y:G,width:$,height:ne}},[e]),H=p.useRef(u.expanded);H.current=u.expanded;const B=p.useRef(null),j=p.useRef(1);p.useEffect(()=>{if(o==="always"){H.current||l(b=>({...b,expanded:!0}));return}if(o!=="auto")return;const N=setInterval(()=>{const b=xy(e),x=C.current;if(!x){C.current=b;return}const _=Math.abs(b.zoom-x.zoom)>.001,z=Math.abs(b.originX-x.originX)>.5||Math.abs(b.originY-x.originY)>.5;(_||z)&&(C.current=b,E.current=Date.now(),H.current||l($=>({...$,expanded:!0,manuallyExpanded:!1})))},100);return()=>{clearInterval(N)}},[o,e]),p.useEffect(()=>{if(o!=="auto"||!u.expanded||u.manuallyExpanded||u.dragging)return;const N=setTimeout(()=>{l(b=>!b.autoMode||b.manuallyExpanded||b.dragging?b:{...b,expanded:!1})},c.autoHideDelay);return()=>{clearTimeout(N)}},[o,u.expanded,u.manuallyExpanded,u.dragging,c.autoHideDelay]);const U=p.useCallback((N,b)=>{if(N.length===0)return{x:b.x-200,y:b.y-200,width:b.width+400,height:b.height+400};let x=b.x,_=b.y,z=b.x+b.width,G=b.y+b.height;N.forEach(ne=>{const{x:xe,y:X,width:oe,height:Fe}=ne.bounds;x=Math.min(x,xe),_=Math.min(_,X),z=Math.max(z,xe+oe),G=Math.max(G,X+Fe)});const $=100;return{x:x-$,y:_-$,width:z-x+$*2,height:G-_+$*2}},[]),A=p.useCallback(N=>{const x=(a.width-20)/N.width,_=(a.height-20)/N.height;return Math.min(x,_)},[a.width,a.height]),I=p.useCallback((N,b,x,_)=>{const G=(N-x.x)*_+10,$=(b-x.y)*_+10;return[G,$]},[]),k=p.useCallback((N,b,x,_)=>{const G=(N-10)/_+x.x,$=(b-10)/_+x.y;return[G,$]},[]),T=p.useCallback((N,b,x)=>{if(100*x<5)return;N.strokeStyle="rgba(0, 0, 0, 0.05)",N.lineWidth=.5;const G=Math.floor(b.x/100)*100,$=Math.floor(b.y/100)*100,ne=b.x+b.width,xe=b.y+b.height;for(let X=G;X<=ne;X+=100){const[oe]=I(X,0,b,x);N.beginPath(),N.moveTo(oe,0),N.lineTo(oe,a.height),N.stroke()}for(let X=$;X<=xe;X+=100){const[,oe]=I(0,X,b,x);N.beginPath(),N.moveTo(0,oe),N.lineTo(a.width,oe),N.stroke()}},[I,a.width,a.height]),M=p.useCallback(()=>{const N=s.current;if(!N)return;const b=N.getContext("2d");if(!b)return;b.clearRect(0,0,a.width,a.height);const x=D(),_=P();if(x.length===0&&!_){b.fillStyle="#999",b.font="12px sans-serif",b.textAlign="center",b.textBaseline="middle",b.fillText("空画布",a.width/2,a.height/2);return}const z=U(x,_),G=A(z);B.current=z,j.current=G,T(b,z,G),b.fillStyle=a.elementColor,b.strokeStyle="rgba(0, 0, 0, 0.1)",b.lineWidth=.5,x.forEach(Ve=>{const{x:Ie,y:wt,width:Ge,height:Lt}=Ve.bounds,[bt,Z]=I(Ie,wt,z,G),ke=Ge*G,se=Lt*G;b.fillRect(bt,Z,ke,se),b.strokeRect(bt,Z,ke,se)});const[$,ne]=I(_.x,_.y,z,G),xe=_.width*G,X=_.height*G;b.fillStyle=a.viewportColor,b.fillRect($,ne,xe,X),b.strokeStyle=a.viewportColor.replace("0.3","1"),b.lineWidth=2,b.strokeRect($,ne,xe,X);const oe=8;b.fillStyle=a.viewportColor.replace("0.3","0.8"),b.fillRect($,ne,oe,2),b.fillRect($,ne,2,oe),b.fillRect($+xe-oe,ne,oe,2),b.fillRect($+xe-2,ne,2,oe),b.fillRect($,ne+X-2,oe,2),b.fillRect($,ne+X-oe,2,oe),b.fillRect($+xe-oe,ne+X-2,oe,2),b.fillRect($+xe-2,ne+X-oe,2,oe);const Fe=m.current;if(Fe){const Ve=Fe.x-xe/2,Ie=Fe.y-X/2;b.fillStyle="rgba(243, 156, 18, 0.15)",b.fillRect(Ve,Ie,xe,X),b.strokeStyle="rgba(243, 156, 18, 0.8)",b.lineWidth=2,b.strokeRect(Ve,Ie,xe,X)}},[e,a,D,P,U,A,I,T]),O=p.useCallback(N=>{N.preventDefault(),N.stopPropagation();const b=s.current;if(!b||!B.current)return;const x=b.getBoundingClientRect(),_=N.clientX-x.left,z=N.clientY-x.top;tt.track("minimap_navigate",{action:"click",displayMode:o});const[G,$]=k(_,z,B.current,j.current);h.current={isDragging:!0,startPoint:[_,z]},l(ne=>({...ne,dragging:!0})),q(G,$)},[k,e]),q=p.useCallback((N,b)=>{const _=F.getBoardContainer(e).getBoundingClientRect(),z=e.viewport.zoom,G=N-_.width/(2*z),$=b-_.height/(2*z);ee.updateViewport(e,[G,$],z),requestAnimationFrame(()=>M())},[e,M]),le=p.useCallback(N=>{if(!h.current.isDragging||!B.current)return;N.preventDefault(),N.stopPropagation();const b=s.current;if(!b)return;const x=b.getBoundingClientRect(),_=N.clientX-x.left,z=N.clientY-x.top,[G,$]=k(_,z,B.current,j.current);q(G,$)},[k,q]),R=p.useCallback(()=>{h.current.isDragging&&tt.track("minimap_navigate",{action:"drag",displayMode:o}),h.current={isDragging:!1,startPoint:null},l(N=>({...N,dragging:!1}))},[o]),L=p.useCallback((N,b)=>{const x=f.current;if(!x||!B.current)return;const _=x.getContext("2d");if(!_)return;const[z,G]=k(N,b,B.current,j.current),$=P(),ne=$.width,xe=$.height,X=ne,oe=xe;_.clearRect(0,0,v,v),_.fillStyle="#fff",_.fillRect(0,0,v,v);const Fe=z-X/2,Ve=G-oe/2,Ie=v/X,wt=v/oe,Ge=Math.min(Ie,wt),Lt=(v-X*Ge)/2,bt=(v-oe*Ge)/2;D().forEach(ke=>{const{bounds:se}=ke;if(se.x+se.width>=Fe&&se.x<=Fe+X&&se.y+se.height>=Ve&&se.y<=Ve+oe){const we=(se.x-Fe)*Ge+Lt,nt=(se.y-Ve)*Ge+bt,ct=se.width*Ge,lt=se.height*Ge;_.fillStyle="rgba(0, 0, 0, 0.6)",_.fillRect(we,nt,ct,lt)}}),_.strokeStyle="rgba(90, 79, 207, 0.6)",_.lineWidth=1,_.setLineDash([4,4]),_.beginPath(),_.moveTo(0,v/2),_.lineTo(v,v/2),_.stroke(),_.beginPath(),_.moveTo(v/2,0),_.lineTo(v/2,v),_.stroke(),_.setLineDash([]),_.strokeStyle="rgba(90, 79, 207, 0.3)",_.lineWidth=2,_.strokeRect(0,0,v,v)},[D,P,k]),Y=p.useCallback(()=>{u.dragging||S(!0)},[u.dragging]),he=p.useCallback(()=>{S(!1),y(null),m.current=null},[]),be=p.useCallback(N=>{if(u.dragging){S(!1),m.current=null;return}const b=s.current;if(!b)return;const x=b.getBoundingClientRect(),_=N.clientX-x.left,z=N.clientY-x.top,G={x:_,y:z};y(G),m.current=G,S(!0),L(_,z),M()},[u.dragging,L,M]),ue=p.useRef(!1),_e=p.useCallback(N=>{ue.current=!0;const b=s.current;if(!b)return;const x=N.touches[0],_=b.getBoundingClientRect(),z=x.clientX-_.left,G=x.clientY-_.top,$={x:z,y:G};y($),m.current=$,S(!0),L(z,G),M()},[L,M]),Ce=p.useCallback(N=>{const b=s.current;if(!b)return;const x=N.touches[0],_=b.getBoundingClientRect(),z=x.clientX-_.left,G=x.clientY-_.top,$={x:z,y:G};y($),m.current=$,S(!0),L(z,G),M()},[L,M]),ze=p.useCallback(()=>{ue.current=!1,setTimeout(()=>{ue.current||(S(!1),y(null),m.current=null,M())},500)},[M]);p.useEffect(()=>{if(!u.expanded)return;M();const N=setInterval(()=>{M()},100);return()=>{clearInterval(N)}},[e,u.expanded,M]);const W=p.useCallback(()=>{l(N=>{const b=!N.expanded;return{...N,expanded:b,manuallyExpanded:b}})},[]),Q={bottom:a.position.includes("bottom")?a.margin:void 0,top:a.position.includes("top")?a.margin:void 0,right:a.position.includes("right")?a.margin:void 0,left:a.position.includes("left")?a.margin:void 0},pe=w&&(ue.current||!u.dragging),V=g?{position:"absolute",right:a.width+8,top:Math.max(0,Math.min(g.y-v/2,a.height-v)),width:v,height:v,opacity:pe?1:0,pointerEvents:"none",transition:"opacity 0.15s ease-out, top 0.1s ease-out"}:{display:"none"};return d.jsxs("div",{ref:r,className:`minimap ${u.expanded?"minimap--expanded":"minimap--collapsed"} ${o==="auto"?"minimap--auto":""} ${n||""}`,style:{...Q,zIndex:ht.MINIMAP},"data-track":"minimap_container",children:[u.expanded&&d.jsxs("div",{className:"minimap__content",children:[d.jsx("canvas",{ref:s,width:a.width,height:a.height,className:"minimap__canvas",onPointerDown:O,onPointerMove:le,onPointerUp:R,onPointerLeave:R,onMouseEnter:Y,onMouseLeave:he,onMouseMove:be,onTouchStart:_e,onTouchMove:Ce,onTouchEnd:ze,style:{cursor:u.dragging?"grabbing":"pointer"}}),d.jsx("div",{className:"minimap__preview",style:V,children:d.jsx("canvas",{ref:f,width:v,height:v,className:"minimap__preview-canvas"})})]}),a.collapsible&&d.jsx(Tt,{content:u.expanded?"折叠小地图":"展开小地图",showArrow:!1,children:d.jsx("button",{className:`minimap__toggle ${u.expanded?"minimap__toggle--expanded":""}`,onClick:W,"data-track":"minimap_click_toggle",children:d.jsx(Ah,{})})})]})},Bi=10,Ey=3e3,by=e=>{var n;const t=e?si(e)||e.viewport.origination:void 0;return{zoom:((n=e==null?void 0:e.viewport)==null?void 0:n.zoom)||1,originX:(t==null?void 0:t[0])||0,originY:(t==null?void 0:t[1])||0}},_y=({showMinimap:e=!0,container:t})=>{var U;const n=Ye(),{t:o}=Oe(),{isDrawerOpen:i,drawerWidth:s}=Mh(),[r,a]=p.useState(!1),[c,u]=p.useState(!0),[l,h]=p.useState(!1),f=p.useRef(null),g=p.useRef(null),y=p.useRef(null),m=p.useMemo(()=>{if(i)return`calc(var(--aitu-toolbar-right-dock-width, 0px) + ${s+Bi}px)`;const A="var(--aitu-toolbar-right-avoidance, 0px)";return typeof CSS<"u"&&CSS.supports("right","max(1px, 2px)")?`max(${Bi}px, ${A})`:Bi},[i,s]),w=p.useCallback(()=>{ee.updateZoom(n,n.viewport.zoom-.1)},[n]),S=p.useCallback(()=>{ee.updateZoom(n,n.viewport.zoom+.1)},[n]),v=p.useCallback(()=>{ee.fitViewport(n),a(!1)},[n]),E=p.useCallback(()=>{ee.updateZoom(n,1),a(!1)},[n]),C=p.useCallback(()=>n.children.some(So)?!1:(Mc({viewMode:"slides"}),!0),[n]),D=p.useCallback(()=>{a(!1),!C()&&Os(n)},[n,C]),P=p.useCallback(()=>{a(!1),!C()&&Cf(n)},[n,C]),H=p.useCallback(()=>{u(A=>{const I=!A;return h(I),I})},[]);p.useEffect(()=>{if(!c||!n)return;const A=F.getBoardContainer(n);if(!A)return;const I=k=>{var M;const T=k.target;(M=f.current)!=null&&M.contains(T)||(u(!1),h(!1))};return A.addEventListener("mousedown",I),()=>{A.removeEventListener("mousedown",I)}},[c,n]),p.useEffect(()=>{if(!e||!n)return;const A=setInterval(()=>{const I=by(n),k=g.current;if(!k){g.current=I;return}const T=Math.abs(I.zoom-k.zoom)>.001,M=Math.abs(I.originX-k.originX)>.5||Math.abs(I.originY-k.originY)>.5;(T||M)&&(g.current=I,c||(u(!0),h(!1)),y.current&&clearTimeout(y.current))},100);return()=>{clearInterval(A)}},[e,n,c]),p.useEffect(()=>{if(!(!c||l))return y.current=setTimeout(()=>{u(!1)},Ey),()=>{y.current&&clearTimeout(y.current)}},[c,l]);const B=p.useCallback(()=>{a(A=>!A)},[]),j=Math.round((((U=n==null?void 0:n.viewport)==null?void 0:U.zoom)||1)*100);return d.jsxs("div",{className:`view-navigation ${En}`,style:{right:m,zIndex:ht.VIEW_NAVIGATION},ref:f,"data-testid":"view-navigation",children:[d.jsxs("div",{className:"view-navigation__zoom",children:[d.jsx(Tt,{content:o("zoom.out"),showArrow:!1,children:d.jsx("button",{className:"view-navigation__zoom-btn",onClick:w,"aria-label":o("zoom.out"),"data-track":"view_nav_zoom_out","data-testid":"zoom-out",children:d.jsx(Rh,{})})}),d.jsxs(Mt,{sideOffset:8,open:r,onOpenChange:a,placement:"bottom",children:[d.jsx(Tt,{content:o("zoom.fit"),showArrow:!1,children:d.jsx(Rt,{asChild:!0,children:d.jsxs("button",{className:"view-navigation__zoom-percent",onClick:B,"aria-label":o("zoom.fit"),"data-track":"view_nav_zoom_menu","data-testid":"zoom-display",children:[j,"%"]})})}),d.jsx(Dt,{className:En,container:t,style:{zIndex:ht.POPOVER},children:d.jsxs("div",{className:"view-navigation-zoom-menu",children:[d.jsxs("button",{className:"zoom-menu-item",onClick:v,"data-track":"view_nav_zoom_fit",children:[d.jsx("span",{className:"zoom-menu-item__label",children:o("zoom.fit")}),d.jsx("span",{className:"zoom-menu-item__shortcut",children:"⌘⇧="})]}),d.jsx("button",{className:"zoom-menu-item",onClick:D,"data-track":"view_nav_zoom_fit_frame",children:d.jsx("span",{className:"zoom-menu-item__label",children:o("zoom.fitFrame")})}),d.jsx("button",{className:"zoom-menu-item",onClick:P,"data-track":"view_nav_zoom_fit_ppt_global",children:d.jsx("span",{className:"zoom-menu-item__label",children:o("zoom.fitPPTGlobal")})}),d.jsxs("button",{className:"zoom-menu-item",onClick:E,"data-track":"view_nav_zoom_100",children:[d.jsx("span",{className:"zoom-menu-item__label",children:o("zoom.100")}),d.jsx("span",{className:"zoom-menu-item__shortcut",children:"⌘0"})]})]})})]}),d.jsx(Tt,{content:o("zoom.in"),showArrow:!1,children:d.jsx("button",{className:"view-navigation__zoom-btn",onClick:S,"aria-label":o("zoom.in"),"data-track":"view_nav_zoom_in","data-testid":"zoom-in",children:d.jsx(Dh,{})})}),e&&d.jsx(Tt,{content:c?"折叠小地图":"展开小地图",showArrow:!1,children:d.jsx("button",{className:`view-navigation__minimap-toggle ${c?"view-navigation__minimap-toggle--expanded":""}`,onClick:H,"aria-label":c?"折叠小地图":"展开小地图","data-track":"view_nav_minimap_toggle",children:d.jsx(Lh,{})})})]}),e&&c&&d.jsx("div",{className:"view-navigation__minimap",children:d.jsx(ky,{board:n,displayMode:"always",config:{width:180,height:120,position:"top-right",margin:0,collapsible:!1,defaultExpanded:!0}})})]})},Py=({children:e,onOpenMediaLibrary:t})=>{const[n,o]=p.useState(!1),{confirm:i,confirmDialog:s}=jh(),r=p.useCallback(()=>{n||(o(!0),i({title:"缓存空间已满",description:"图片缓存空间已满,无法继续缓存新图片。是否打开素材库清理缓存?",confirmText:"打开素材库",cancelText:"稍后处理",confirmTheme:"warning"}).then(a=>{o(!1),a&&(t==null||t())}))},[i,n,t]);return Oh(r),d.jsxs(d.Fragment,{children:[e,s]})},Qo={visible:!1,position:{x:0,y:0},sourceElement:null,currentShape:null,hitIndex:-1,hitPoint:null,mode:"hover",arrowLineElement:null,arrowLineEndPoint:null},nu=new WeakMap,Ss=new WeakMap;function ei(e){return nu.get(e)||Qo}function Un(e,t){nu.set(e,t);const n=Ss.get(e);n&&n(t)}function Ty(e,t){return Ss.set(e,t),()=>{Ss.delete(e)}}function er(e){Un(e,Qo)}const On=100;function Cy(e,t,n,o,i){const s=Hh(n),r=de.getRectangleByPoints(t.points),a=r.width,c=r.height,u=r.x+a/2,l=r.y+c/2,f=de.getEdgeCenterPoints(r)[n];let g,y;switch(s){case Pe.right:g=u+a/2+On+a/2,y=l;break;case Pe.bottom:g=u,y=l+c/2+On+c/2;break;case Pe.left:g=u-a/2-On-a/2,y=l;break;case Pe.top:g=u,y=l-c/2-On-c/2;break;default:g=u+a/2+On+a/2,y=l}const m=[[g-a/2,y-c/2],[g+a/2,y+c/2]],w=Ls(e,m,i);if(w.fill="#ffffff",K.isShapeElement(t)&&!K.isText(t)){const A=t;A.angle!==void 0&&(w.angle=A.angle),A.fill&&A.fill!=="none"&&(w.fill=A.fill),A.strokeColor!==void 0&&(w.strokeColor=A.strokeColor),A.strokeStyle!==void 0&&(w.strokeStyle=A.strokeStyle),A.strokeWidth!==void 0&&(w.strokeWidth=A.strokeWidth)}const S=Vo(f,t)||f,v=K.isShapeElement(t)?ro(e,S,t):void 0;let E;switch(s){case Pe.right:E=3;break;case Pe.bottom:E=0;break;case Pe.left:E=1;break;case Pe.top:E=2;break;default:E=3}const C=de.getRectangleByPoints(w.points),P=de.getEdgeCenterPoints(C)[E],H=Vo(P,w)||P,B=ro(e,H,w),j=Lc(xt.straight,[S,H],{marker:ao.none,connection:v,boundId:t.id},{marker:ao.arrow,connection:B,boundId:w.id},[],{});Se.insertNode(e,j,[e.children.length]),Dc(e,w),er(e);const U=w.id;setTimeout(()=>{const A=e.children.findIndex(k=>k.id===U),I=A>=0?e.children[A]:null;I&&(At(e),Pn(e,I),ee.updatePointerType(e,Le.selection),Se.setNode(e,{_forceRender:Date.now()},[A]),Se.setNode(e,{_forceRender:void 0},[A]))},50)}function Iy(e,t,n,o){var y;let i=100,s=100;const r=t,a=(y=r.source)==null?void 0:y.boundId;if(a){const m=e.children.find(w=>w.id===a);if(m&&K.isShapeElement(m)){const w=de.getRectangleByPoints(m.points);i=w.width,s=w.height}}const c=[[n[0]-i/2,n[1]-s/2],[n[0]+i/2,n[1]+s/2]],u=Ls(e,c,o);u.fill="#ffffff";const l=de.getRectangleByPoints(u.points),h=de.getEdgeCenterPoints(l),f=r.points||[];if(f.length>=2){const m=f[0],w=f[f.length-1],S=w[0]-m[0],v=w[1]-m[1];let E;Math.abs(S)>Math.abs(v)?E=S>0?3:1:E=v>0?0:2;const C=h[E],D=ro(e,C,u),P=e.children.findIndex(H=>H.id===t.id);P!==-1&&Se.setNode(e,{target:{marker:ao.arrow,connection:D,boundId:u.id},points:[m,C]},[P])}Dc(e,u),er(e);const g=u.id;setTimeout(()=>{const m=e.children.findIndex(S=>S.id===g),w=m>=0?e.children[m]:null;w&&(At(e),Pn(e,w),ee.updatePointerType(e,Le.selection),Se.setNode(e,{_forceRender:Date.now()},[m]),Se.setNode(e,{_forceRender:void 0},[m]))},50)}const Ay=e=>{const{pointerMove:t,pointerLeave:n,globalPointerUp:o}=e;let i=null,s=-1,r=e.children.length,a={x:0,y:0};return e.pointerMove=c=>{var C;a={x:c.clientX,y:c.clientY},i&&(clearTimeout(i),i=null);const u=Rc(e),l=u.length===1&&u[0],h=ei(e);if(!l||!K.isShapeElement(l)||K.isText(l)){if(h.visible&&h.mode==="hover"&&Un(e,{...Qo}),s=-1,l&&K.isShapeElement(l)&&!vn.getElementRef(l))return;t(c);return}if(!vn.getElementRef(l)){s=-1;return}const g=Nh(e,c.x,c.y),y=zh(e,l,!0),m=Fh(e,g,l,!0)||g,w=Bh(m,y),S=y[w];if(S){if(w!==s||!h.visible){s=w;const D=c.clientX,P=c.clientY;i=setTimeout(()=>{const H=K.isImage(l)?ge.rectangle:l.shape||ge.rectangle;Un(e,{visible:!0,position:{x:D-140,y:P+20},sourceElement:l,currentShape:H,hitIndex:w,hitPoint:S,mode:"hover"})},50)}}else s=-1,h.visible&&h.mode==="hover"&&(i=setTimeout(()=>{const D=ei(e);D.visible&&D.mode==="hover"&&Un(e,{...Qo})},300));const v=vn.getElementRef(l);(C=v==null?void 0:v.getGenerator)!=null&&C.call(v,Gi.key)&&t(c)},e.pointerLeave=c=>{i&&(clearTimeout(i),i=null),n(c)},e.globalPointerUp=c=>{var l;o(c);const u=e.children.length;if(u>r){const h=e.children[u-1];if(K.isArrowLine(h)){const f=h;if(!((l=f.target)==null?void 0:l.boundId)){const y=f.points||[];if(y.length>=2){const m=y[y.length-1];setTimeout(()=>{Un(e,{visible:!0,position:{x:a.x-140,y:a.y+20},sourceElement:null,currentShape:ge.rectangle,hitIndex:-1,hitPoint:null,mode:"arrowLine",arrowLineElement:h,arrowLineEndPoint:m})},50)}}}}r=e.children.length},e},Nn=100;function My(e){switch(e){case"ArrowRight":return Pe.right;case"ArrowDown":return Pe.bottom;case"ArrowLeft":return Pe.left;case"ArrowUp":return Pe.top;default:return null}}function Ry(e){switch(e){case Pe.top:return 0;case Pe.right:return 1;case Pe.bottom:return 2;case Pe.left:return 3;default:return 1}}function Dy(e){return(e+2)%4}function Ly(e,t,n,o,i,s){const r={x:t-o/2,y:n-i/2,width:o,height:i};for(const a of e.children)if(a.id!==s&&K.isDrawElement(a)&&!K.isArrowLine(a))try{const c=de.getRectangleByPoints(a.points);if(r.x<c.x+c.width&&r.x+r.width>c.x&&r.y<c.y+c.height&&r.y+r.height>c.y)return!0}catch{}return!1}function jy(e,t,n){const o=de.getRectangleByPoints(t.points),i=o.width,s=o.height,r=o.x+i/2,a=o.y+s/2;let c,u;switch(n){case Pe.right:c=r+i/2+Nn+i/2,u=a;break;case Pe.bottom:c=r,u=a+s/2+Nn+s/2;break;case Pe.left:c=r-i/2-Nn-i/2,u=a;break;case Pe.top:c=r,u=a-s/2-Nn-s/2;break;default:c=r+i/2+Nn+i/2,u=a}let l=0;const h=n===Pe.right||n===Pe.left?s+20:i+20;for(;Ly(e,c,u,i,s,t.id)&&(l+=h,n===Pe.right||n===Pe.left?u=a+l:c=r+l,!(l>1e3)););const f=[[c-i/2,u-s/2],[c+i/2,u+s/2]],y=t.shape||"rectangle",m=Ls(e,f,y);if(m.fill="#ffffff",K.isShapeElement(t)&&!K.isText(t)){const k=t;k.fill&&k.fill!=="none"&&(m.fill=k.fill),k.strokeColor!==void 0&&(m.strokeColor=k.strokeColor),k.strokeWidth!==void 0&&(m.strokeWidth=k.strokeWidth)}const w=Ry(n),S=Dy(w),E=de.getEdgeCenterPoints(o)[w],C=Vo(E,t)||E,D=K.isShapeElement(t)?ro(e,C,t):void 0,P=de.getRectangleByPoints(m.points),B=de.getEdgeCenterPoints(P)[S],j=Vo(B,m)||B,U=ro(e,j,m),A=Lc(xt.elbow,[C,j],{marker:ao.none,connection:D,boundId:t.id},{marker:ao.arrow,connection:U,boundId:m.id},[],{});Se.insertNode(e,A,[e.children.length]),Se.insertNode(e,m,[e.children.length]);const I=m.id;setTimeout(()=>{const k=e.children.find(T=>T.id===I);k&&(At(e),Pn(e,k),ee.updatePointerType(e,Le.selection),jc(e,[c,u]))},50)}function Oy(e,t){var i,s,r,a;const n=[],o=[];for(const c of e.children){if(!K.isArrowLine(c))continue;const u=c;if(((i=u.source)==null?void 0:i.boundId)===t.id&&((s=u.target)!=null&&s.boundId)){const l=e.children.find(h=>h.id===u.target.boundId);l&&o.push(l)}if(((r=u.target)==null?void 0:r.boundId)===t.id&&((a=u.source)!=null&&a.boundId)){const l=e.children.find(h=>h.id===u.source.boundId);l&&n.push(l)}}return{incoming:n,outgoing:o}}function Ny(e,t,n){const{incoming:o,outgoing:i}=Oy(e,t),s=n?[...i,...o]:[...o,...i];if(s.length===0)return!1;const r=s[0];At(e),Pn(e,r);try{const a=Ft(e,[r],!1),c=a.x+a.width/2,u=a.y+a.height/2;jc(e,[c,u])}catch{}return!0}const zy=e=>{const{keyDown:t}=e;return e.keyDown=n=>{if(!n.altKey&&!n.metaKey&&!n.ctrlKey){if(!n.shiftKey){const o=My(n.key);if(o!==null){const i=Rc(e);if(i.length===1){const s=i[0];if(K.isShapeElement(s)&&!K.isText(s)&&!K.isImage(s)){jy(e,s,o),n.preventDefault();return}}}}if(n.key==="Tab"){const o=Te(e);if(o.length===1){const i=o[0];if(K.isDrawElement(i)&&K.isShapeElement(i)&&Ny(e,i,!n.shiftKey)){n.preventDefault();return}}}}t(n)},e};function Fy(e){let t=0;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)|0;return Math.abs(t)}function Ta(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return"--:--";const t=Math.floor(e),n=Math.floor(t/60),o=t%60;return`${n}:${String(o).padStart(2,"0")}`}function Ca(e,t){return e?e.length<=t?e:`${e.slice(0,Math.max(0,t-3))}...`:""}function By(e,t){if(e){const n=e.split(/[,,]/).map(o=>o.trim()).filter(Boolean).slice(0,2);if(n.length>0)return n.join(" · ")}if(t){const n=t.split(`
|
|
14
14
|
`).map(o=>o.trim()).find(Boolean);if(n)return n.replace(/[【】]/g,"")}return"画布音频"}function Hy(e){if(e)return e.split(/[,,]/).map(t=>t.trim()).find(Boolean)}function Ia(e,t){return t<=0?[]:e.length===0?Array.from({length:t},()=>0):e.length===1?Array.from({length:t},()=>e[0]??0):Array.from({length:t},(n,o)=>{const i=o/Math.max(1,t-1)*(e.length-1),s=Math.floor(i),r=Math.min(e.length-1,Math.ceil(i)),a=i-s,c=e[s]??0,u=e[r]??c;return c*(1-a)+u*a})}function xs(e){if(e.length<2)return"";let t="";for(let o=0;o<e.length-1;o++){const i=e[o],s=e[o+1];if(!i||!s)continue;const r=(i.x+s.x)/2,a=(i.y+s.y)/2;o===0?t+=`Q ${i.x} ${i.y} ${r} ${a} `:t+=`T ${r} ${a} `}const n=e[e.length-1];return n&&(t+=`T ${n.x} ${n.y}`),t.trim()}function Aa(e,t,n){if(e.length===0)return"";const o=e.map((u,l)=>({x:l*t+t/2,y:n+u.offset-u.thickness/2})),i=e.map((u,l)=>({x:l*t+t/2,y:n+u.offset+u.thickness/2})).reverse(),s=xs(o),r=xs(i),a=o[0],c=i[0];return!a||!c?"":[`M ${a.x} ${a.y}`,s,`L ${c.x} ${c.y}`,r,"Z"].filter(Boolean).join(" ")}function $y(e,t){if(e.length===0)return[];const n=Math.max(1,e.length-1),o=t%2048/2048*Math.PI*2;return e.map((i,s)=>{const r=s/n,a=.56+Math.sin(r*Math.PI)*.44,c=Math.sin(r*Math.PI*4.3+o)*.74,u=Math.sin(r*Math.PI*8.9+o*.62)*.24,l=Math.max(-.24,Math.min(.24,(i.thickness-12)/18));return Math.max(-1,Math.min(1,(c+u)*a+l))})}function Ma(e,t,n,o,i=1){if(e.length===0)return"";const s=e.map((c,u)=>({x:u*n+n/2,y:(()=>{const l=t[u]??0,h=t[u-1]??l,f=t[u+1]??l,g=h*.22+l*.56+f*.22,y=u/Math.max(1,e.length-1),m=.82+Math.sin(y*Math.PI)*.18,w=(c.thickness*.36+3.1)*i*m,S=o+c.offset*.72+g*w;return Math.max(2,Math.min(o*2-2,S))})()})),r=xs(s),a=s[0];return a?[`M ${a.x} ${a.y}`,r].filter(Boolean).join(" "):""}const Vy=({element:e,selected:t,canvasQueue:n=[]})=>{const o=If(),i=vt(V=>V.activeElementId===e.id),s=vt(V=>V.activeElementId===e.id&&V.playing),r=vt(V=>V.activeElementId===e.id?V.currentTime:0),a=vt(V=>V.activeElementId===e.id?V.duration:0),c=vt(V=>V.activeElementId===e.id&&V.analysisAvailable),u=vt(V=>V.activeElementId===e.id&&V.analysisAvailable?V.spectrumLevels:xi),l=vt(V=>V.activeElementId===e.id&&V.analysisAvailable?V.waveformLevels:wr),h=vt(V=>V.activeElementId===e.id?V.pulseLevel:0),f=i&&a>0?a:e.duration,g=i&&f?Math.max(0,Math.min(100,r/f*100)):0,y=i?Ta(r):"0:00",m=Ta(f),w=i?y:m,S=i?m:void 0,v=Math.abs(e.points[1][0]-e.points[0][0]),E=v>=420?38:v>=320?28:20,C=v>=420?72:v>=320?42:24,D=p.useMemo(()=>Fy(`${e.id}-${e.title||""}-${e.clipId||""}`),[e.clipId,e.id,e.title]),P=p.useMemo(()=>{const V=v>=420?40:v>=320?34:28,N=D%4096/4096*Math.PI*2;return Array.from({length:V},(b,x)=>{const _=x/Math.max(1,V-1),z=.26+Math.sin(_*Math.PI)*.74,G=(D>>x%12&15)/15,$=(D>>(x+5)%14&15)/15-.5,ne=Math.sin(_*Math.PI*3.8+N)*(1.05+z*2.2),xe=Math.sin(_*Math.PI*8.6+N*.56)*.92,X=Number((8+z*7.8+G*1.8+Math.abs(ne)*1.16).toFixed(2)),oe=Number(($*(1.2+z*2.4)).toFixed(2)),Fe=Number((oe+ne*.72+xe*.34).toFixed(2)),Ve=(D+x*17)%10*.06,Ie=1.12+(D>>x%7&7)*.07;return{id:`${e.id}-bar-${x}`,thickness:X,offset:Fe,delay:Ve,duration:Ie}})},[e.id,v,D]),H=s&&c&&u!==xi,B=s&&c&&l!==wr,j=p.useMemo(()=>{const V=Ia(H?u:xi,P.length);return H?P.map((N,b)=>{const x=V[b]??0,_=((V[b-1]??x)+x+(V[b+1]??x))/3,z=Number(Math.max(7.4,Math.min(18.5,N.thickness*.76+_*8.2)).toFixed(2)),G=Number(Math.max(-5,Math.min(5,N.offset*.65+(_-.5)*4.8)).toFixed(2));return{...N,liveThickness:z,liveOffset:G}}):P.map(N=>({...N,liveThickness:N.thickness,liveOffset:N.offset}))},[P,u,H]),U=p.useMemo(()=>$y(P,D),[P,D]),A=p.useMemo(()=>{if(!B)return U;const V=Ia(l,P.length);return P.map((N,b)=>{var G;const x=U[b]??0,_=V[b]??0,z=((((G=j[b])==null?void 0:G.liveThickness)??N.thickness)-N.thickness)/22;return Math.max(-1,Math.min(1,x*.2+_*(.92+h*.26)+z*.08))})},[P,U,l,h,B,j]),I=4,k=18,T=async V=>{V.preventDefault(),V.stopPropagation();try{const N={elementId:e.id,audioUrl:e.audioUrl,title:e.title,duration:e.duration,previewImageUrl:e.previewImageUrl,clipId:e.clipId,providerTaskId:e.providerTaskId,clipIds:e.clipIds},b=Ro.getCanvasQueue(),x=n.length>=b.length?n:b;await o.togglePlaybackInQueue(N,x,{queueSource:"canvas",queueId:Nc,queueName:Oc})}catch{}},M=Ca(By(e.tags,e.prompt),C),O=Hy(e.tags)||"音频",q=s?{"--audio-node-pulse-scale":`${1+h*.038}`,"--audio-node-pulse-glow":`${.12+h*.22}`}:void 0,le=Math.max(1,j.length*I-1),R=p.useMemo(()=>`audio-node-ribbon-gradient-${e.id.replace(/[^a-zA-Z0-9_-]/g,"-")}`,[e.id]),L=p.useMemo(()=>`audio-node-ribbon-glow-${e.id.replace(/[^a-zA-Z0-9_-]/g,"-")}`,[e.id]),Y=p.useMemo(()=>`audio-node-ribbon-aura-${e.id.replace(/[^a-zA-Z0-9_-]/g,"-")}`,[e.id]),he=p.useMemo(()=>`audio-node-ribbon-core-${e.id.replace(/[^a-zA-Z0-9_-]/g,"-")}`,[e.id]),be=p.useMemo(()=>`audio-node-ribbon-progress-${e.id.replace(/[^a-zA-Z0-9_-]/g,"-")}`,[e.id]),ue=p.useMemo(()=>`audio-node-ribbon-progress-clip-${e.id.replace(/[^a-zA-Z0-9_-]/g,"-")}`,[e.id]),_e=p.useMemo(()=>Aa(P,I,k),[P]),Ce=p.useMemo(()=>Aa(j.map(V=>({thickness:V.liveThickness??V.thickness,offset:V.liveOffset??V.offset})),I,k),[j]),ze=p.useMemo(()=>Ma(P.map(V=>({thickness:V.thickness,offset:V.offset})),U,I,k,.78),[P,U]),W=p.useMemo(()=>Ma(j.map(V=>({thickness:V.liveThickness??V.thickness,offset:V.liveOffset??V.offset})),A,I,k,B?1.08+h*.34:.94),[A,h,B,j]),Q=le*g/100,pe={"--audio-node-progress":`${g}%`};return d.jsxs("div",{className:me("audio-node",{"audio-node--selected":t,"audio-node--active":i,"audio-node--playing":s}),style:q,children:[d.jsx("div",{className:"audio-node__media",children:d.jsx(Tt,{content:s?"Pause audio":"Play audio",showArrow:!1,children:d.jsxs("button",{type:"button",className:"audio-node__artwork","data-slideshow-media-control":"true",onClick:T,onPointerDown:V=>V.stopPropagation(),children:[d.jsx($h,{src:e.previewImageUrl,alt:e.title||"Audio artwork",fallbackClassName:"audio-node__artwork-fallback",iconSize:22}),d.jsx("div",{className:"audio-node__artwork-overlay",children:s?d.jsx(Vh,{size:18,className:"audio-node__artwork-icon audio-node__artwork-icon--pause"}):d.jsx(Wh,{size:28,fill:"currentColor",strokeWidth:0,className:"audio-node__artwork-icon audio-node__artwork-icon--play"})})]})})}),d.jsxs("div",{className:"audio-node__body",children:[d.jsxs("div",{className:"audio-node__title-row",children:[d.jsxs("div",{className:"audio-node__title-group",children:[d.jsx("div",{className:"audio-node__title",children:Ca(e.title||"未命名音频",E)}),d.jsx("div",{className:"audio-node__subtitle",children:M})]}),d.jsx("div",{className:me("audio-node__badge",{"audio-node__badge--playing":s}),children:O})]}),d.jsx("div",{className:"audio-node__wave-shell",children:d.jsx("div",{className:me("audio-node__waveform",{"audio-node__waveform--active":i,"audio-node__waveform--reactive":H||B,"audio-node__waveform--fallback":s&&!H&&!B}),"aria-hidden":"true",style:pe,children:d.jsxs("svg",{className:"audio-node__waveform-svg",viewBox:`0 0 ${le} 36`,preserveAspectRatio:"none",children:[d.jsxs("defs",{children:[d.jsxs("linearGradient",{id:R,x1:"0%",y1:"0%",x2:"100%",y2:"0%",children:[d.jsx("stop",{offset:"0%",stopColor:"rgba(96, 165, 250, 0.42)"}),d.jsx("stop",{offset:"52%",stopColor:"rgba(59, 130, 246, 0.86)"}),d.jsx("stop",{offset:"100%",stopColor:"rgba(125, 211, 252, 0.58)"})]}),d.jsxs("linearGradient",{id:L,x1:"0%",y1:"0%",x2:"100%",y2:"0%",children:[d.jsx("stop",{offset:"0%",stopColor:"rgba(191, 219, 254, 0)"}),d.jsx("stop",{offset:"42%",stopColor:"rgba(147, 197, 253, 0.86)"}),d.jsx("stop",{offset:"100%",stopColor:"rgba(186, 230, 253, 0)"})]}),d.jsxs("linearGradient",{id:Y,x1:"0%",y1:"0%",x2:"100%",y2:"0%",children:[d.jsx("stop",{offset:"0%",stopColor:"rgba(191, 219, 254, 0)"}),d.jsx("stop",{offset:"28%",stopColor:"rgba(147, 197, 253, 0.42)"}),d.jsx("stop",{offset:"58%",stopColor:"rgba(96, 165, 250, 0.72)"}),d.jsx("stop",{offset:"100%",stopColor:"rgba(186, 230, 253, 0)"})]}),d.jsxs("linearGradient",{id:he,x1:"0%",y1:"0%",x2:"100%",y2:"0%",children:[d.jsx("stop",{offset:"0%",stopColor:"rgba(255, 255, 255, 0.84)"}),d.jsx("stop",{offset:"52%",stopColor:"rgba(240, 249, 255, 0.98)"}),d.jsx("stop",{offset:"100%",stopColor:"rgba(207, 250, 254, 0.86)"})]}),d.jsxs("linearGradient",{id:be,x1:"0%",y1:"0%",x2:"100%",y2:"0%",children:[d.jsx("stop",{offset:"0%",stopColor:"rgba(59, 130, 246, 0.84)"}),d.jsx("stop",{offset:"58%",stopColor:"rgba(14, 165, 233, 0.98)"}),d.jsx("stop",{offset:"100%",stopColor:"rgba(103, 232, 249, 0.9)"})]}),d.jsx("clipPath",{id:ue,children:d.jsx("rect",{x:"0",y:"0",width:Math.max(0,Q),height:"36",rx:"18",ry:"18"})})]}),d.jsx("path",{className:"audio-node__wave-area audio-node__wave-area--base",d:_e}),d.jsx("path",{className:me("audio-node__wave-aura audio-node__wave-aura--live",{"audio-node__wave-aura--animated":s&&!H&&!B,"audio-node__wave-aura--reactive":H||B}),d:Ce,style:{fill:`url(#${Y})`}}),d.jsx("path",{className:me("audio-node__wave-area audio-node__wave-area--live",{"audio-node__wave-area--animated":s&&!H,"audio-node__wave-area--reactive":H}),d:Ce,style:{fill:`url(#${R})`}}),d.jsx("path",{className:"audio-node__wave-line audio-node__wave-line--base",d:ze}),d.jsx("path",{className:me("audio-node__wave-line audio-node__wave-line--glow",{"audio-node__wave-line--animated":s&&!H&&!B,"audio-node__wave-line--reactive":H||B}),d:W,style:{stroke:`url(#${L})`}}),d.jsx("path",{className:me("audio-node__wave-line audio-node__wave-line--live",{"audio-node__wave-line--animated":s&&!H&&!B,"audio-node__wave-line--reactive":H||B}),d:W,style:{stroke:`url(#${R})`}}),d.jsx("path",{className:me("audio-node__wave-line audio-node__wave-line--core",{"audio-node__wave-line--animated":s&&!H&&!B,"audio-node__wave-line--reactive":H||B}),d:W,style:{stroke:`url(#${he})`}}),i&&Q>.5?d.jsxs(d.Fragment,{children:[d.jsx("path",{className:"audio-node__wave-aura audio-node__wave-aura--progress",d:Ce,clipPath:`url(#${ue})`,style:{fill:`url(#${Y})`}}),d.jsx("path",{className:"audio-node__wave-area audio-node__wave-area--progress",d:Ce,clipPath:`url(#${ue})`,style:{fill:`url(#${be})`}}),d.jsx("path",{className:"audio-node__wave-line audio-node__wave-line--progress-glow",d:W,clipPath:`url(#${ue})`,style:{stroke:`url(#${L})`}}),d.jsx("path",{className:"audio-node__wave-line audio-node__wave-line--progress",d:W,clipPath:`url(#${ue})`,style:{stroke:`url(#${be})`}}),d.jsx("path",{className:"audio-node__wave-line audio-node__wave-line--progress-core",d:W,clipPath:`url(#${ue})`,style:{stroke:`url(#${he})`}})]}):null]})})}),d.jsxs("div",{className:me("audio-node__time-cluster",{"audio-node__time-cluster--active":i}),children:[d.jsx("span",{className:me("audio-node__time audio-node__time--primary",{"audio-node__time--active":i}),children:w}),S?d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"audio-node__time-divider",children:"/"}),d.jsx("span",{className:"audio-node__time",children:S})]}):null]})]})]})};class Wy{constructor(){this.foreignObject=null,this.htmlContainer=null,this.reactRoot=null}processDrawing(t,n,o,i){const s=document.createElementNS("http://www.w3.org/2000/svg","g");return s.setAttribute("class","audio-node-element"),n.appendChild(s),this.createForeignObject(t,s),this.renderReact(t,o,i),s}updateDrawing(t,n,o,i){this.updateForeignObject(t),this.renderReact(t,o,i)}createForeignObject(t,n){const o=de.getRectangleByPoints(t.points);this.foreignObject=document.createElementNS("http://www.w3.org/2000/svg","foreignObject"),this.foreignObject.setAttribute("x",String(o.x)),this.foreignObject.setAttribute("y",String(o.y)),this.foreignObject.setAttribute("width",String(o.width)),this.foreignObject.setAttribute("height",String(o.height)),this.foreignObject.style.overflow="visible",this.foreignObject.style.pointerEvents="auto",this.htmlContainer=document.createElementNS("http://www.w3.org/1999/xhtml","div"),this.htmlContainer.style.cssText=`
|
|
15
15
|
width: 100%;
|
|
16
16
|
height: 100%;
|
|
17
17
|
pointer-events: auto;
|
|
18
18
|
overflow: visible;
|
|
19
|
-
`,this.foreignObject.appendChild(this.htmlContainer),n.appendChild(this.foreignObject)}updateForeignObject(t){if(!this.foreignObject)return;const n=de.getRectangleByPoints(t.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(t,n,o){this.htmlContainer&&(this.reactRoot||(this.reactRoot=mo.createRoot(this.htmlContainer)),this.reactRoot.render(on.createElement(Vy,{element:t,selected:n,canvasQueue:o})))}destroy(){if(this.reactRoot){const t=this.reactRoot;this.reactRoot=null,setTimeout(()=>{try{t.unmount()}catch{}},0)}this.foreignObject=null,this.htmlContainer=null}}class Uy extends ci{canDraw(t,n){return!!(n!=null&&n.selected)}draw(t){var a;const n=yo(),o=de.getRectangleByPoints(t.points),i=Ac(this.board,o),s=de.inflate(i,no),r=Uh(this.board,s,{stroke:"#2563eb",strokeWidth:no});if(r&&(r.classList.add(Gh),r.style.opacity="0.9",n.append(r)),(a=this.options)!=null&&a.active&&li(this.board,t)){const c=s.y+s.height/2,u=yr(this.board,[s.x,c]),l=yr(this.board,[s.x+s.width,c]);n.append(u,l)}return n}}class Gy extends wo{initializeGenerator(){this.activeGenerator=new Uy(this.board,{active:!0}),this.audioNodeGenerator=new Wy}initialize(){super.initialize(),this.initializeGenerator();const t=this.getElementG();this.renderedG=this.audioNodeGenerator.processDrawing(this.element,t,this.selected,Kn(this.board.children)),this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})}onContextChanged(t,n){const o=t.board.viewport.zoom!==n.board.viewport.zoom||t.board.viewport.offsetX!==n.board.viewport.offsetX||t.board.viewport.offsetY!==n.board.viewport.offsetY;if(t.element!==n.element||t.hasThemeChanged)this.renderedG&&this.audioNodeGenerator.updateDrawing(this.element,this.renderedG,this.selected,Kn(this.board.children)),this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected});else if(o&&t.selected)this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected});else{const i=t.selected!==n.selected;i&&this.renderedG&&this.audioNodeGenerator.updateDrawing(this.element,this.renderedG,this.selected,Kn(this.board.children)),(i||t.selected)&&this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})}}destroy(){super.destroy(),this.activeGenerator&&this.activeGenerator.destroy(),this.audioNodeGenerator&&this.audioNodeGenerator.destroy(),this.renderedG=void 0}}function Ky(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}const qy=e=>{const{drawElement:t,getRectangle:n,isHit:o,isRectangleHit:i,isMovable:s,isAlign:r,getDeletedFragment:a,buildFragment:c,insertFragment:u}=e;return e.drawElement=l=>rt(l.element)?Gy:t(l),e.getRectangle=l=>rt(l)?de.getRectangleByPoints(l.points):n(l),e.isHit=(l,h,f)=>{if(rt(l)){const g=de.getRectangleByPoints(l.points);return h[0]>=g.x&&h[0]<=g.x+g.width&&h[1]>=g.y&&h[1]<=g.y+g.height}return o(l,h,f)},e.isRectangleHit=(l,h)=>{if(rt(l)){const f=de.getRectangleByPoints(l.points),g=de.getRectangleByPoints([h.anchor,h.focus]);return Ky(f,g)}return i(l,h)},e.isMovable=l=>rt(l)?!0:s(l),e.isAlign=l=>rt(l)?!0:r(l),e.getDeletedFragment=l=>{const h=Te(e).filter(rt);return h.length>0&&l.push(...h),a(l)},e.buildFragment=(l,h,f,g)=>{const m=(g!=null&&g.length?g:Te(e)).filter(rt);if(m.length>0&&h){const w=m.map(S=>({...S,points:S.points.map(v=>[v[0]-h.x,v[1]-h.y])}));l=Rs(l,{text:"",type:Ds.elements,elements:w})}return c(l,h,f,g)},e.insertFragment=(l,h,f)=>{var y,m;if((y=l==null?void 0:l.elements)!=null&&y.length){const w=l.elements.filter(rt);if(w.length>0){const S=[];w.forEach(v=>{const E={...v,id:Pc(),points:v.points.map(C=>[h[0]+C[0],h[1]+C[1]])};Se.insertNode(e,E,[e.children.length]),S.push(E)}),S.length>0&&(At(e),S.forEach(v=>Pn(e,v)))}}const g=(m=l==null?void 0:l.elements)!=null&&m.length?{...l,elements:l.elements.filter(w=>!rt(w))}:l;u(g,h,f)},e},Yy=240,Xy=new Set(["5","7"]);function Zy(e){const t=Te(e);return t.length===1&&rt(t[0])}function Jy(e,t){const n=Te(e);if(n.length!==1||!rt(n[0]))return null;const o=n[0],i=de.getRectangleByPoints(o.points),s=rn(i,t,0,Xy);return s?{element:o,rectangle:i,handle:s.handle,cursorClass:s.cursorClass}:null}function Qy(e,t,n,o){const i=e.width/e.height,s=t==="7",r=s?-n:n,a=Math.max(Yy,e.width+r),c=a/i,u=(e.height-c)/2;return{x:s?e.x+(e.width-a):e.x,y:e.y+u,width:a,height:c}}function ev(e,t,n){const{element:o,rectangle:i,handle:s}=t,{startPoint:r,endPoint:a}=n;if(!i)return;const c=a[0]-r[0];a[1]-r[1];const u=Qy(i,s,c),l=[[u.x,u.y],[u.x+u.width,u.y+u.height]],h=e.children.findIndex(f=>f.id===o.id);h>=0&&Se.setNode(e,{points:l},[h])}const tv=e=>sn(e,{key:"audio-nodes",canResize:()=>Zy(e),hitTest:(t=>Jy(e,t)),onResize:(t,n)=>ev(e,t,n)}),nv={visible:!1,position:{x:0,y:0},sourceElement:null,currentShape:null,hitIndex:-1,hitPoint:null,mode:"hover"};function ov(e){const[t,n]=p.useState(nv);p.useEffect(()=>{if(!e)return;n(ei(e));const s=Ty(e,r=>{n(r)});return()=>{s()}},[e]);const o=p.useCallback(s=>{if(!e)return;const r=ei(e);r.mode==="arrowLine"?r.arrowLineElement&&r.arrowLineEndPoint&&Iy(e,r.arrowLineElement,r.arrowLineEndPoint,s):r.sourceElement&&r.hitPoint&&r.hitIndex>=0&&Cy(e,r.sourceElement,r.hitIndex,r.hitPoint,s)},[e]),i=p.useCallback(()=>{e&&er(e)},[e]);return{state:t,selectShape:o,closePicker:i}}const iv="#ffffff",sv=[ge.rectangle,ge.ellipse,ge.triangle,ge.diamond,ge.parallelogram,ge.roundRectangle];function Ra(e){if(!K.isGeometry(e)||K.isText(e)||K.isImage(e))return!1;const t=e;return!(!t.shape||!sv.includes(t.shape)||t.fill&&t.fill!=="none")}const rv=e=>{const{afterChange:t}=e,n=new Set;return e.afterChange=()=>{t();const o=[];e.children.forEach((i,s)=>{Ra(i)&&!n.has(i.id)&&(o.push({path:[s],element:i}),n.add(i.id))}),o.length>0&&setTimeout(()=>{o.forEach(({path:i})=>{const s=e.children[i[0]];s&&Ra(s)&&Se.setNode(e,{fill:iv},i)})},0)},e},ti=new WeakMap;let Hi=null,_t=null;function ou(e,t){try{const n=vn.getElementG(t);if(n)return n}catch{}if(t!=null&&t.id){const n=F.getElementHost(e);if(n){const o=n.querySelector(`g[id="${t.id}"]`);if(o)return o}}return null}function iu(e){return e.querySelector("path, rect, ellipse, polygon, circle")}function su(e){let t=e.querySelector("defs");return t||(t=Kh(),e.insertBefore(t,e.firstChild)),t}function av(e,t){const n=ti.get(t);if(n){const o=e.querySelector(`#${n}`);o&&o.remove()}}function ni(e,t,n){const o=ou(e,t);if(!o)return;const i=iu(o);if(!i)return;const s=o.closest("svg");if(!s)return;const r=Ft(e,[t],!1),a=(r==null?void 0:r.width)||100,c=(r==null?void 0:r.height)||100,u=zc(n,t.id,a,c),l=su(s);if(u.defElement){const h=u.defElement.id,f=l.querySelector(`#${h}`);f?f.replaceWith(u.defElement):l.appendChild(u.defElement),i.setAttribute("fill",u.fillValue),ti.set(t,h);const g=ti.get(t);if(g&&g!==h){const y=l.querySelector(`#${g}`);y&&y.remove()}}else i.setAttribute("fill",u.fillValue),av(s,t)}function zo(e,t){return e.children.find(n=>n.id===t)||null}function It(e){const t=e.fillConfig;return t&&vr(t)?t:e.fill&&vr(e.fill)?e.fill:null}function ru(e,t){if(!e)return!1;if(e==="[object Object]")return!0;if(e.startsWith("url(#")){const n=e.match(/url\(#([^)]+)\)/);if(n){const o=n[1];if(!document.getElementById(o))return!0}return!1}if(t){const n=It(t);if(n&&(n.type==="gradient"||n.type==="image"))return!0}return!1}function cv(e){if(!_t)return;const t=new Set;e.forEach(n=>{if(n.type==="attributes"&&n.attributeName==="fill"){const o=n.target,i=o.getAttribute("fill"),s=o.closest("g[id]");if(s){const r=s.getAttribute("id");if(r){const a=zo(_t,r),c=a?It(a):null;a&&c&&Jt(_t,a)&&ru(i,a)&&t.add(a)}}}n.type==="childList"&&n.addedNodes.forEach(o=>{if(o instanceof SVGGElement&&o.hasAttribute("id")){const i=o.getAttribute("id");if(i){const s=zo(_t,i),r=s?It(s):null;s&&r&&Jt(_t,s)&&t.add(s)}}if(o instanceof Element){const i=o.closest("g[id]");if(i){const s=i.getAttribute("id");if(s){const r=zo(_t,s),a=r?It(r):null;r&&a&&Jt(_t,r)&&t.add(r)}}}})}),t.size>0&&t.forEach(n=>{const o=It(n);o&&ni(_t,n,o)})}function lv(e){if(Hi)return;const t=F.getElementHost(e);t&&(_t=e,Hi=new MutationObserver(cv),Hi.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["fill"]}))}function uv(e){const t=F.getElementHost(e);if(!t)return;t.querySelectorAll("path[fill], rect[fill], ellipse[fill], polygon[fill], circle[fill]").forEach(o=>{const i=o.getAttribute("fill"),s=o.closest("g[id]");if(s){const r=s.getAttribute("id");if(r){const a=zo(e,r),c=a?It(a):null;a&&c&&Jt(e,a)&&ru(i,a)&&ni(e,a,c)}}})}function ks(e,t=!1){e.children.forEach(n=>{const o=It(n);o&&Jt(e,n)&&(t?ni(e,n,o):requestAnimationFrame(()=>{ni(e,n,o)}))}),t&&uv(e)}let Da=!0;const La=new WeakSet;function au(e){const t=F.getElementHost(e);if(!t)return;const n=t.closest("svg")||t.querySelector("svg");n&&e.children.forEach(o=>{const i=It(o);if(i&&(i.type==="gradient"||i.type==="image")&&Jt(e,o)){const s=Ft(e,[o],!1),r=(s==null?void 0:s.width)||100,a=(s==null?void 0:s.height)||100,c=zc(i,o.id,r,a);if(c.defElement){const u=su(n);u.querySelector(`#${c.defElement.id}`)||(u.appendChild(c.defElement),ti.set(o,c.defElement.id))}}})}function dv(e){let t=0;return e.children.forEach(n=>{const o=It(n);if(o&&(o.type==="gradient"||o.type==="image")&&Jt(e,n)){const i=ou(e,n);(i?iu(i):null)||t++}}),t}function hv(e){if(La.has(e))return;La.add(e);const t=15,n=16;let o=0;const i=()=>{o++;try{if(!F.getElementHost(e))return;if(au(e),ks(e,!0),dv(e)>0&&o<t){const a=Math.min(n*Math.pow(1.5,o),500);setTimeout(i,a)}}catch{}};requestAnimationFrame(()=>{i(),setTimeout(i,0)})}const fv=e=>{const{afterChange:t}=e;return e.afterChange=()=>{t(),lv(e),au(e),Da?(Da=!1,ks(e,!0),hv(e)):ks(e,!0)},e};function gv(e){const t=Te(e);return t.length!==1?!1:So(t[0])}function pv(e,t){const n=Te(e);if(n.length!==1||!So(n[0]))return null;const o=n[0],i=de.getRectangleByPoints(o.points),s=rn(i,t);return s?{element:o,rectangle:i,handle:s.handle,cursorClass:s.cursorClass}:null}function mv(e,t,n){const{element:o,rectangle:i,handle:s}=t;if(!i)return;const{startPoint:r,endPoint:a}=n,c=a[0]-r[0],u=a[1]-r[1],l=Tn(i,s,c,u,vo(),60),h=[[l.x,l.y],[l.x+l.width,l.y+l.height]],f=e.children.findIndex(g=>g.id===o.id);f>=0&&Se.setNode(e,{points:h},[f])}function wv(e,t){const{element:n}=t,o=e.children.find(i=>i.id===n.id);o&&qh.updateFrameMembers(e,o)}const yv=e=>sn(e,{key:"frame-elements",canResize:()=>gv(e),hitTest:t=>pv(e,t),onResize:(t,n)=>mv(e,t,n),afterResize:t=>wv(e,t)});function $i(e){return!!e.locked}const vv=e=>{const{isHit:t,isRectangleHit:n,isMovable:o}=e;return e.isHit=(i,s,r)=>$i(i)?!1:t(i,s,r),e.isRectangleHit=(i,s)=>$i(i)?!1:n(i,s),e.isMovable=i=>$i(i)?!1:o(i),e},ja="笔记",Sv="新笔记",xv=24;function kv(e){var t;return((t=e.title)==null?void 0:t.trim())||Sv}function Ev(e){return(e.body||"").trim()}async function bv(){const{knowledgeBaseService:e}=await re(async()=>{const{knowledgeBaseService:i}=await import("./ai-chat-B-XdoWBQ.js").then(s=>s.sM);return{knowledgeBaseService:i}},__vite__mapDeps([0]),import.meta.url);await e.initialize();const n=(await e.getAllDirectories()).find(i=>i.name===ja);if(n)return{knowledgeBaseService:e,directory:n};const o=await e.createDirectory(ja);return{knowledgeBaseService:e,directory:o}}function _v(e,t,n){const o=e.children.findIndex(i=>i.id===t);o<0||Se.setNode(e,{noteId:n},[o])}function gS(e){var n,o;if(Fc(e)){const i=(n=e.title)!=null&&n.trim()?`# ${e.title.trim()}`:"",s=((o=e.body)==null?void 0:o.trim())||"";return[i,s].filter(Boolean).join(`
|
|
19
|
+
`,this.foreignObject.appendChild(this.htmlContainer),n.appendChild(this.foreignObject)}updateForeignObject(t){if(!this.foreignObject)return;const n=de.getRectangleByPoints(t.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(t,n,o){this.htmlContainer&&(this.reactRoot||(this.reactRoot=mo.createRoot(this.htmlContainer)),this.reactRoot.render(on.createElement(Vy,{element:t,selected:n,canvasQueue:o})))}destroy(){if(this.reactRoot){const t=this.reactRoot;this.reactRoot=null,setTimeout(()=>{try{t.unmount()}catch{}},0)}this.foreignObject=null,this.htmlContainer=null}}class Uy extends ci{canDraw(t,n){return!!(n!=null&&n.selected)}draw(t){var a;const n=yo(),o=de.getRectangleByPoints(t.points),i=Ac(this.board,o),s=de.inflate(i,no),r=Uh(this.board,s,{stroke:"#2563eb",strokeWidth:no});if(r&&(r.classList.add(Gh),r.style.opacity="0.9",n.append(r)),(a=this.options)!=null&&a.active&&li(this.board,t)){const c=s.y+s.height/2,u=yr(this.board,[s.x,c]),l=yr(this.board,[s.x+s.width,c]);n.append(u,l)}return n}}class Gy extends wo{initializeGenerator(){this.activeGenerator=new Uy(this.board,{active:!0}),this.audioNodeGenerator=new Wy}initialize(){super.initialize(),this.initializeGenerator();const t=this.getElementG();this.renderedG=this.audioNodeGenerator.processDrawing(this.element,t,this.selected,Kn(this.board.children)),this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})}onContextChanged(t,n){const o=t.board.viewport.zoom!==n.board.viewport.zoom||t.board.viewport.offsetX!==n.board.viewport.offsetX||t.board.viewport.offsetY!==n.board.viewport.offsetY;if(t.element!==n.element||t.hasThemeChanged)this.renderedG&&this.audioNodeGenerator.updateDrawing(this.element,this.renderedG,this.selected,Kn(this.board.children)),this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected});else if(o&&t.selected)this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected});else{const i=t.selected!==n.selected;i&&this.renderedG&&this.audioNodeGenerator.updateDrawing(this.element,this.renderedG,this.selected,Kn(this.board.children)),(i||t.selected)&&this.activeGenerator.processDrawing(this.element,F.getActiveHost(this.board),{selected:this.selected})}}destroy(){super.destroy(),this.activeGenerator&&this.activeGenerator.destroy(),this.audioNodeGenerator&&this.audioNodeGenerator.destroy(),this.renderedG=void 0}}function Ky(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}const qy=e=>{const{drawElement:t,getRectangle:n,isHit:o,isRectangleHit:i,isMovable:s,isAlign:r,getDeletedFragment:a,buildFragment:c,insertFragment:u}=e;return e.drawElement=l=>rt(l.element)?Gy:t(l),e.getRectangle=l=>rt(l)?de.getRectangleByPoints(l.points):n(l),e.isHit=(l,h,f)=>{if(rt(l)){const g=de.getRectangleByPoints(l.points);return h[0]>=g.x&&h[0]<=g.x+g.width&&h[1]>=g.y&&h[1]<=g.y+g.height}return o(l,h,f)},e.isRectangleHit=(l,h)=>{if(rt(l)){const f=de.getRectangleByPoints(l.points),g=de.getRectangleByPoints([h.anchor,h.focus]);return Ky(f,g)}return i(l,h)},e.isMovable=l=>rt(l)?!0:s(l),e.isAlign=l=>rt(l)?!0:r(l),e.getDeletedFragment=l=>{const h=Te(e).filter(rt);return h.length>0&&l.push(...h),a(l)},e.buildFragment=(l,h,f,g)=>{const m=(g!=null&&g.length?g:Te(e)).filter(rt);if(m.length>0&&h){const w=m.map(S=>({...S,points:S.points.map(v=>[v[0]-h.x,v[1]-h.y])}));l=Rs(l,{text:"",type:Ds.elements,elements:w})}return c(l,h,f,g)},e.insertFragment=(l,h,f)=>{var y,m;if((y=l==null?void 0:l.elements)!=null&&y.length){const w=l.elements.filter(rt);if(w.length>0){const S=[];w.forEach(v=>{const E={...v,id:Pc(),points:v.points.map(C=>[h[0]+C[0],h[1]+C[1]])};Se.insertNode(e,E,[e.children.length]),S.push(E)}),S.length>0&&(At(e),S.forEach(v=>Pn(e,v)))}}const g=(m=l==null?void 0:l.elements)!=null&&m.length?{...l,elements:l.elements.filter(w=>!rt(w))}:l;u(g,h,f)},e},Yy=240,Xy=new Set(["5","7"]);function Zy(e){const t=Te(e);return t.length===1&&rt(t[0])}function Jy(e,t){const n=Te(e);if(n.length!==1||!rt(n[0]))return null;const o=n[0],i=de.getRectangleByPoints(o.points),s=rn(i,t,0,Xy);return s?{element:o,rectangle:i,handle:s.handle,cursorClass:s.cursorClass}:null}function Qy(e,t,n,o){const i=e.width/e.height,s=t==="7",r=s?-n:n,a=Math.max(Yy,e.width+r),c=a/i,u=(e.height-c)/2;return{x:s?e.x+(e.width-a):e.x,y:e.y+u,width:a,height:c}}function ev(e,t,n){const{element:o,rectangle:i,handle:s}=t,{startPoint:r,endPoint:a}=n;if(!i)return;const c=a[0]-r[0];a[1]-r[1];const u=Qy(i,s,c),l=[[u.x,u.y],[u.x+u.width,u.y+u.height]],h=e.children.findIndex(f=>f.id===o.id);h>=0&&Se.setNode(e,{points:l},[h])}const tv=e=>sn(e,{key:"audio-nodes",canResize:()=>Zy(e),hitTest:(t=>Jy(e,t)),onResize:(t,n)=>ev(e,t,n)}),nv={visible:!1,position:{x:0,y:0},sourceElement:null,currentShape:null,hitIndex:-1,hitPoint:null,mode:"hover"};function ov(e){const[t,n]=p.useState(nv);p.useEffect(()=>{if(!e)return;n(ei(e));const s=Ty(e,r=>{n(r)});return()=>{s()}},[e]);const o=p.useCallback(s=>{if(!e)return;const r=ei(e);r.mode==="arrowLine"?r.arrowLineElement&&r.arrowLineEndPoint&&Iy(e,r.arrowLineElement,r.arrowLineEndPoint,s):r.sourceElement&&r.hitPoint&&r.hitIndex>=0&&Cy(e,r.sourceElement,r.hitIndex,r.hitPoint,s)},[e]),i=p.useCallback(()=>{e&&er(e)},[e]);return{state:t,selectShape:o,closePicker:i}}const iv="#ffffff",sv=[ge.rectangle,ge.ellipse,ge.triangle,ge.diamond,ge.parallelogram,ge.roundRectangle];function Ra(e){if(!K.isGeometry(e)||K.isText(e)||K.isImage(e))return!1;const t=e;return!(!t.shape||!sv.includes(t.shape)||t.fill&&t.fill!=="none")}const rv=e=>{const{afterChange:t}=e,n=new Set;return e.afterChange=()=>{t();const o=[];e.children.forEach((i,s)=>{Ra(i)&&!n.has(i.id)&&(o.push({path:[s],element:i}),n.add(i.id))}),o.length>0&&setTimeout(()=>{o.forEach(({path:i})=>{const s=e.children[i[0]];s&&Ra(s)&&Se.setNode(e,{fill:iv},i)})},0)},e},ti=new WeakMap;let Hi=null,_t=null;function ou(e,t){try{const n=vn.getElementG(t);if(n)return n}catch{}if(t!=null&&t.id){const n=F.getElementHost(e);if(n){const o=n.querySelector(`g[id="${t.id}"]`);if(o)return o}}return null}function iu(e){return e.querySelector("path, rect, ellipse, polygon, circle")}function su(e){let t=e.querySelector("defs");return t||(t=Kh(),e.insertBefore(t,e.firstChild)),t}function av(e,t){const n=ti.get(t);if(n){const o=e.querySelector(`#${n}`);o&&o.remove()}}function ni(e,t,n){const o=ou(e,t);if(!o)return;const i=iu(o);if(!i)return;const s=o.closest("svg");if(!s)return;const r=Ft(e,[t],!1),a=(r==null?void 0:r.width)||100,c=(r==null?void 0:r.height)||100,u=zc(n,t.id,a,c),l=su(s);if(u.defElement){const h=u.defElement.id,f=l.querySelector(`#${h}`);f?f.replaceWith(u.defElement):l.appendChild(u.defElement),i.setAttribute("fill",u.fillValue),ti.set(t,h);const g=ti.get(t);if(g&&g!==h){const y=l.querySelector(`#${g}`);y&&y.remove()}}else i.setAttribute("fill",u.fillValue),av(s,t)}function zo(e,t){return e.children.find(n=>n.id===t)||null}function It(e){const t=e.fillConfig;return t&&vr(t)?t:e.fill&&vr(e.fill)?e.fill:null}function ru(e,t){if(!e)return!1;if(e==="[object Object]")return!0;if(e.startsWith("url(#")){const n=e.match(/url\(#([^)]+)\)/);if(n){const o=n[1];if(!document.getElementById(o))return!0}return!1}if(t){const n=It(t);if(n&&(n.type==="gradient"||n.type==="image"))return!0}return!1}function cv(e){if(!_t)return;const t=new Set;e.forEach(n=>{if(n.type==="attributes"&&n.attributeName==="fill"){const o=n.target,i=o.getAttribute("fill"),s=o.closest("g[id]");if(s){const r=s.getAttribute("id");if(r){const a=zo(_t,r),c=a?It(a):null;a&&c&&Jt(_t,a)&&ru(i,a)&&t.add(a)}}}n.type==="childList"&&n.addedNodes.forEach(o=>{if(o instanceof SVGGElement&&o.hasAttribute("id")){const i=o.getAttribute("id");if(i){const s=zo(_t,i),r=s?It(s):null;s&&r&&Jt(_t,s)&&t.add(s)}}if(o instanceof Element){const i=o.closest("g[id]");if(i){const s=i.getAttribute("id");if(s){const r=zo(_t,s),a=r?It(r):null;r&&a&&Jt(_t,r)&&t.add(r)}}}})}),t.size>0&&t.forEach(n=>{const o=It(n);o&&ni(_t,n,o)})}function lv(e){if(Hi)return;const t=F.getElementHost(e);t&&(_t=e,Hi=new MutationObserver(cv),Hi.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["fill"]}))}function uv(e){const t=F.getElementHost(e);if(!t)return;t.querySelectorAll("path[fill], rect[fill], ellipse[fill], polygon[fill], circle[fill]").forEach(o=>{const i=o.getAttribute("fill"),s=o.closest("g[id]");if(s){const r=s.getAttribute("id");if(r){const a=zo(e,r),c=a?It(a):null;a&&c&&Jt(e,a)&&ru(i,a)&&ni(e,a,c)}}})}function ks(e,t=!1){e.children.forEach(n=>{const o=It(n);o&&Jt(e,n)&&(t?ni(e,n,o):requestAnimationFrame(()=>{ni(e,n,o)}))}),t&&uv(e)}let Da=!0;const La=new WeakSet;function au(e){const t=F.getElementHost(e);if(!t)return;const n=t.closest("svg")||t.querySelector("svg");n&&e.children.forEach(o=>{const i=It(o);if(i&&(i.type==="gradient"||i.type==="image")&&Jt(e,o)){const s=Ft(e,[o],!1),r=(s==null?void 0:s.width)||100,a=(s==null?void 0:s.height)||100,c=zc(i,o.id,r,a);if(c.defElement){const u=su(n);u.querySelector(`#${c.defElement.id}`)||(u.appendChild(c.defElement),ti.set(o,c.defElement.id))}}})}function dv(e){let t=0;return e.children.forEach(n=>{const o=It(n);if(o&&(o.type==="gradient"||o.type==="image")&&Jt(e,n)){const i=ou(e,n);(i?iu(i):null)||t++}}),t}function hv(e){if(La.has(e))return;La.add(e);const t=15,n=16;let o=0;const i=()=>{o++;try{if(!F.getElementHost(e))return;if(au(e),ks(e,!0),dv(e)>0&&o<t){const a=Math.min(n*Math.pow(1.5,o),500);setTimeout(i,a)}}catch{}};requestAnimationFrame(()=>{i(),setTimeout(i,0)})}const fv=e=>{const{afterChange:t}=e;return e.afterChange=()=>{t(),lv(e),au(e),Da?(Da=!1,ks(e,!0),hv(e)):ks(e,!0)},e};function gv(e){const t=Te(e);return t.length!==1?!1:So(t[0])}function pv(e,t){const n=Te(e);if(n.length!==1||!So(n[0]))return null;const o=n[0],i=de.getRectangleByPoints(o.points),s=rn(i,t);return s?{element:o,rectangle:i,handle:s.handle,cursorClass:s.cursorClass}:null}function mv(e,t,n){const{element:o,rectangle:i,handle:s}=t;if(!i)return;const{startPoint:r,endPoint:a}=n,c=a[0]-r[0],u=a[1]-r[1],l=Tn(i,s,c,u,vo(),60),h=[[l.x,l.y],[l.x+l.width,l.y+l.height]],f=e.children.findIndex(g=>g.id===o.id);f>=0&&Se.setNode(e,{points:h},[f])}function wv(e,t){const{element:n}=t,o=e.children.find(i=>i.id===n.id);o&&qh.updateFrameMembers(e,o)}const yv=e=>sn(e,{key:"frame-elements",canResize:()=>gv(e),hitTest:t=>pv(e,t),onResize:(t,n)=>mv(e,t,n),afterResize:t=>wv(e,t)});function $i(e){return!!e.locked}const vv=e=>{const{isHit:t,isRectangleHit:n,isMovable:o}=e;return e.isHit=(i,s,r)=>$i(i)?!1:t(i,s,r),e.isRectangleHit=(i,s)=>$i(i)?!1:n(i,s),e.isMovable=i=>$i(i)?!1:o(i),e},ja="笔记",Sv="新笔记",xv=24;function kv(e){var t;return((t=e.title)==null?void 0:t.trim())||Sv}function Ev(e){return(e.body||"").trim()}async function bv(){const{knowledgeBaseService:e}=await re(async()=>{const{knowledgeBaseService:i}=await import("./ai-chat-BnWVpTEI.js").then(s=>s.sN);return{knowledgeBaseService:i}},__vite__mapDeps([0]),import.meta.url);await e.initialize();const n=(await e.getAllDirectories()).find(i=>i.name===ja);if(n)return{knowledgeBaseService:e,directory:n};const o=await e.createDirectory(ja);return{knowledgeBaseService:e,directory:o}}function _v(e,t,n){const o=e.children.findIndex(i=>i.id===t);o<0||Se.setNode(e,{noteId:n},[o])}function gS(e){var n,o;if(Fc(e)){const i=(n=e.title)!=null&&n.trim()?`# ${e.title.trim()}`:"",s=((o=e.body)==null?void 0:o.trim())||"";return[i,s].filter(Boolean).join(`
|
|
20
20
|
|
|
21
21
|
`).trim()}const t=[];if("data"in e&&Array.isArray(e.data)){for(const i of e.data)if(pn.isNode(i)){const s=pn.string(i).trim();s&&t.push(s)}}if("text"in e){if(typeof e.text=="string"){const i=e.text.trim();i&&t.push(i)}else if(e.text&&typeof e.text=="object"&&pn.isNode(e.text)){const i=pn.string(e.text).trim();i&&t.push(i)}}if("textContent"in e&&typeof e.textContent=="string"){const i=e.textContent.trim();i&&t.push(i)}return t.join(`
|
|
22
|
-
`).trim()}function pS(e){return K.isDrawElement(e)&&K.isText(e)}function mS(e,t){return[...t].sort((n,o)=>{const i=Ft(e,[n],!1),s=Ft(e,[o],!1);return Math.abs(i.x-s.x)<=xv&&Math.abs(i.y-s.y)>.5?i.y-s.y:i.x-s.x})}async function Pv(e,t,n="zh"){if(!t)return null;if(t.noteId)return t.noteId;try{const{knowledgeBaseService:o,directory:i}=await bv(),s=await o.createNote(kv(t),i.id),r=Ev(t);return r&&await o.updateNote(s.id,{content:r}),_v(e,t.id,s.id),s.id}catch(o){return console.error("Failed to create note for card:",o),Ne.error(n==="zh"?"保存到知识库失败":"Failed to save to knowledge base"),null}}async function wS(e,t){const n=[...new Set(e.filter(Boolean))];if(n.length===0)return;const{knowledgeBaseService:o}=await re(async()=>{const{knowledgeBaseService:s}=await import("./ai-chat-B-XdoWBQ.js").then(r=>r.sM);return{knowledgeBaseService:s}},__vite__mapDeps([0]),import.meta.url);await o.initialize();const i=n[0];await o.updateNote(i,{content:t});for(const s of n.slice(1))await o.deleteNote(s);return i}const Tv=async(e,t,n="zh")=>{if(t){if(t.noteId){window.dispatchEvent(new CustomEvent("kb:open",{detail:{noteId:t.noteId}}));return}try{const o=await Pv(e,t,n);if(!o)return;window.dispatchEvent(new CustomEvent("kb:open",{detail:{noteId:o}}))}catch(o){console.error("Failed to create note for card:",o),Ne.error(n==="zh"?"无法打开知识库笔记":"Failed to open knowledge base note")}}},Cv=p.lazy(()=>re(()=>import("./popup-toolbar-tKtYPGvw.js"),__vite__mapDeps([0,1,5]),import.meta.url).then(e=>({default:e.PopupToolbar}))),Iv=p.lazy(()=>re(()=>import("./link-popup-fCfgZp17.js"),__vite__mapDeps([0,1,6]),import.meta.url).then(e=>({default:e.LinkPopup}))),Av=p.lazy(()=>re(()=>import("./index-D7UBK5T7.js"),__vite__mapDeps([0,1,7]),import.meta.url).then(e=>({default:e.PencilSettingsToolbar}))),Mv=p.lazy(()=>re(()=>import("./index-D7UBK5T7.js"),__vite__mapDeps([0,1,7]),import.meta.url).then(e=>({default:e.EraserSettingsToolbar}))),Rv=p.lazy(()=>re(()=>import("./index-Ct7MFvFo.js"),__vite__mapDeps([0,1,8]),import.meta.url).then(e=>({default:e.PenSettingsToolbar}))),Dv=p.lazy(()=>re(()=>import("./clean-confirm-CpWpcTF5.js"),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.CleanConfirm}))),Lv=p.lazy(()=>re(()=>import("./quick-creation-toolbar-CrQ0g0kO.js"),__vite__mapDeps([0,1,9]),import.meta.url).then(e=>({default:e.QuickCreationToolbar}))),jv=p.lazy(()=>re(()=>import("./index-o8hm5yhT.js"),__vite__mapDeps([0,1,10]),import.meta.url).then(e=>({default:e.AutoCompleteShapePicker}))),Ov=p.lazy(()=>re(()=>import("./DeferredAIInputBar-Cq0t7wNK.js"),__vite__mapDeps([0,1,11]),import.meta.url).then(e=>({default:e.DeferredAIInputBar}))),Nv=p.lazy(()=>re(()=>import("./ai-chat-B-XdoWBQ.js").then(e=>e.t3),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.ChatDrawer}))),st=["tool-windows","runtime-static-assets"],zv=p.lazy(()=>re(()=>import("./DrawnixDeferredFeatures-B9y0GPYR.js"),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.DrawnixDeferredFeatures}))),Fv=p.lazy(()=>re(()=>import("./tool-windows-BnDZa9FH.js").then(e=>e.b4),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.DrawnixDeferredRuntime}))),Bv=p.lazy(()=>re(()=>import("./ttd-dialog-DS6KiOOa.js"),__vite__mapDeps([0,1,3,4,12,13]),import.meta.url).then(e=>({default:e.TTDDialog}))),Hv=p.lazy(()=>re(()=>import("./settings-dialog-DfK6bcBd.js"),__vite__mapDeps([0,1,14]),import.meta.url).then(e=>({default:e.SettingsDialog}))),$v=p.lazy(()=>re(()=>import("./ai-chat-B-XdoWBQ.js").then(e=>e.sW),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.UnifiedMediaViewer}))),Vv=p.lazy(()=>re(()=>import("./CanvasAudioPlayer-DyUPmMV6.js"),__vite__mapDeps([0,1,15]),import.meta.url).then(e=>({default:e.CanvasAudioPlayer}))),Wv=[],Uv="project-drawer-active-tab",Gv="frames",cu=()=>{try{return localStorage.getItem(Uv)===Gv}catch{return!1}},Fo=()=>!Ns(zs.project),Kv=()=>Fo()&&!cu(),fn=()=>!Ns(zs.toolbox),gn=()=>!Ns(zs.task);function qv(){var o,i;if(typeof window>"u")return!1;const e=((o=window.matchMedia)==null?void 0:o.call(window,"(pointer: coarse)").matches)??!1,t=((i=window.matchMedia)==null?void 0:i.call(window,"(max-width: 768px)").matches)??!1,n=navigator.maxTouchPoints>0||"ontouchstart"in window;return t||e&&n}const yS=({value:e,viewport:t,theme:n,onChange:o,onSelectionChange:i,onViewportChange:s,onThemeChange:r,onValueChange:a,afterInit:c,onBoardSwitch:u,onTabSyncNeeded:l,isDataReady:h=!1,currentBoardId:f})=>{const g={readonly:!1,hideScrollbar:!1,disabledScrollOnNonFocus:!1,themeColors:cf},[y,m]=p.useState(()=>({pointer:Le.hand,isMobile:qv(),isPencilMode:!1,openDialogTypes:new Set,dialogInitialData:null,dialogInitialDataByType:{},openCleanConfirm:!1,openSettings:!1})),[w,S]=p.useState(null),[v,E]=p.useState(!1),[C,D]=p.useState(!1),[P,H]=p.useState(!1),[B,j]=p.useState(!1),[U,A]=p.useState({mode:$o.BROWSE}),[I,k]=p.useState(!1),[T,M]=p.useState(!1),[O,q]=p.useState(!1),[le,R]=p.useState(!1),[L,Y]=p.useState(!1),[he,be]=p.useState(!1),[ue,_e]=p.useState(!1),Ce=p.useRef(null),ze=p.useCallback(()=>{Fo()&&E(!1),fn()&&D(!1),gn()&&H(!1),j(!1)},[]),W=p.useCallback((Z=Wv)=>{el(Z),q(!0)},[]),Q=p.useCallback((Z=st)=>{W(Z),_e(!0),be(!0)},[W]),pe=p.useCallback(()=>{W(st)},[W]);p.useEffect(()=>{(y.openDialogTypes.has(dt.aiImageGeneration)||y.openDialogTypes.has(dt.aiVideoGeneration))&&pe()},[y.openDialogTypes,pe]);const V=p.useCallback(()=>{Q(st),Promise.all([re(()=>import("./tool-windows-BnDZa9FH.js").then(Z=>Z.b0),__vite__mapDeps([0,1]),import.meta.url),re(()=>import("./tool-windows-BnDZa9FH.js").then(Z=>Z.a$),__vite__mapDeps([0,1]),import.meta.url)]).then(([{toolWindowService:Z},{toolRegistry:ke}])=>{const se=ke.getManifestById("knowledge-base");if(!se)return;const we=Z.getToolState(se.id);we&&we.status==="open"?Z.closeTool(se.id):Z.openTool(se)})},[Q]);p.useEffect(()=>{const Z=ke=>{const{noteId:se}=ke.detail;Q(st),Promise.all([re(()=>import("./tool-windows-BnDZa9FH.js").then(we=>we.b0),__vite__mapDeps([0,1]),import.meta.url),re(()=>import("./tool-windows-BnDZa9FH.js").then(we=>we.a$),__vite__mapDeps([0,1]),import.meta.url)]).then(([{toolWindowService:we},{toolRegistry:nt}])=>{const ct=nt.getManifestById("knowledge-base");if(!ct)return;const lt=we.isToolOpen(ct.id);we.openTool(ct,{componentProps:se?{initialNoteId:se}:{}}),lt&&se&&window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("kb:open-note",{detail:{noteId:se}}))},50)})};return window.addEventListener("kb:open",Z),()=>window.removeEventListener("kb:open",Z)},[Q]);const N=p.useCallback(()=>{if(Q(st),v){E(!1);return}fn()&&D(!1),gn()&&H(!1),j(!1),E(!0)},[Q,v]);p.useEffect(()=>{const Z=()=>{Q(st),fn()&&D(!1),gn()&&H(!1),j(!1),E(!0)};return window.addEventListener(Sr,Z),()=>window.removeEventListener(Sr,Z)},[Q]);const b=p.useCallback(()=>{if(Q(st),C){D(!1);return}Fo()&&E(!1),gn()&&H(!1),j(!1),D(!0)},[Q,C]),x=p.useCallback(()=>{if(W(st),P){H(!1);return}Fo()&&E(!1),fn()&&D(!1),j(!1),H(!0)},[W,P]),_=p.useCallback(Z=>{Q(st);const{keepProjectDrawerOpen:ke,...se}=Z||{};ke?(fn()&&D(!1),gn()&&H(!1),j(!1)):ze(),A({mode:$o.BROWSE,...se}),j(!0)},[ze,Q]),z=p.useCallback(()=>{W(st),k(!0)},[W]),G=p.useCallback(()=>{W(st),M(!0)},[W]),$=p.useCallback(Z=>{m(Z)},[]),ne=p.useCallback(Z=>{m(ke=>({...ke,...Z}))},[]);p.useEffect(()=>{w&&(w.appState=y,w.__setAppState=$,Ce.current=w)},[w,y,$]),p.useEffect(()=>{if(new URLSearchParams(window.location.search).has("tool")){Q(st);return}},[Q]),p.useEffect(()=>{if(typeof window>"u"||!("serviceWorker"in navigator))return;let Z=!1;const ke=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1",se=lt=>{var $t;(($t=lt.data)==null?void 0:$t.type)==="SW_IDLE_PREFETCH_STATUS"&&st.every(wi=>{var Vt;return(Vt=lt.data.completedGroups)==null?void 0:Vt.includes(wi)})&&(Z=!0,_e(!0))};navigator.serviceWorker.addEventListener("message",se);const we={type:"SW_IDLE_PREFETCH_STATUS_GET"},nt=navigator.serviceWorker.controller;nt?nt.postMessage(we):navigator.serviceWorker.ready.then(lt=>{var $t;($t=lt.active)==null||$t.postMessage(we)}).catch(()=>{});const ct=window.setTimeout(()=>{Z||ue||(ke||console.warn("[Drawnix] SW idle prefetch status unresolved, enabling minimized tools bar fallback"),_e(!0))},2200);return()=>{window.clearTimeout(ct),navigator.serviceWorker.removeEventListener("message",se)}},[ue]),p.useEffect(()=>{const Z=window.requestIdleCallback;let ke;const se=window.setTimeout(()=>{const we=()=>{R(!0),Y(!0)};if(typeof Z=="function"){ke=Z(we,{timeout:2500});return}we()},5e3);return()=>{var we;window.clearTimeout(se),typeof ke=="number"&&((we=window.cancelIdleCallback)==null||we.call(window,ke))}},[]),p.useEffect(()=>{const Z=ke=>{const se=ke,{message:we,reason:nt}=se.detail,ct=nt||lf(we);Ne.error({content:ct==="missing"?"缺少 API Key,请先在设置中配置":"API Key 无效或已过期,请重新配置",duration:5e3}),console.error("[Drawnix] API auth error:",we),m(lt=>({...lt,openSettings:!0}))};return window.addEventListener(xr,Z),()=>{window.removeEventListener(xr,Z)}},[]);const xe=[ef,tf,nf,mm,Um,Ww(ne),S0,I0,dy,ay,A0(ne),R0(ne),of,Df,Z0,Lf,jf,Of,Ay,zy,sf,yv,rf,af,qy,tv,rv,fv,Nf,vv,U0,K0],X=p.useRef(null),{saveBoard:oe,createBoard:Fe,switchBoard:Ve}=Af(),Ie=p.useCallback(async()=>{if(o&&Ce.current){const Z={children:Ce.current.children||[],viewport:Ce.current.viewport,theme:Ce.current.theme};await oe(Z)}},[o,oe]),wt=p.useCallback(async()=>{await Ie();const Z=await Fe({name:"新画布"});Z&&(await Ve(Z.id),setTimeout(()=>{co()},500))},[Ie,Fe,Ve]),Ge=p.useCallback(Z=>{const ke=Ce.current;if(ke&&Z){const se=Te(ke),we=se.map(nt=>nt.id).filter(Boolean);se.some(So)&&(!v||!cu())&&Mc(),ne({lastSelectedElementIds:we})}i&&i(Z)},[i,v,ne]),Lt=p.useMemo(()=>({appState:y,setAppState:$,board:w}),[y,$,w]),bt=le||L||he||y.openCommandPalette||y.openCanvasSearch||v||C||B||I||T;return d.jsx(Yh,{children:d.jsx(Mf,{children:d.jsx(Xh,{children:d.jsx(Zh,{children:d.jsx(Rf,{children:d.jsx(Py,{onOpenMediaLibrary:_,children:d.jsx(Jh,{children:d.jsx(Qh.Provider,{value:Lt,children:d.jsx(Yv,{value:e,viewport:t,theme:n,options:g,plugins:xe,containerRef:X,appState:y,board:w,setBoard:S,projectDrawerOpen:v,toolboxDrawerOpen:C,taskPanelExpanded:P,mediaLibraryOpen:B,mediaLibraryConfig:U,backupRestoreOpen:I,onChange:o,onSelectionChange:Ge,onViewportChange:s,onThemeChange:r,onValueChange:a,afterInit:c,onBoardSwitch:u,onTabSyncNeeded:l,handleProjectDrawerToggle:N,handleToolboxDrawerToggle:b,handleKnowledgeBaseToggle:V,handleTaskPanelToggle:x,handleOpenMediaLibrary:_,handleOpenBackupRestore:z,handleOpenCloudSync:G,setProjectDrawerOpen:E,setToolboxDrawerOpen:D,setTaskPanelExpanded:H,setMediaLibraryOpen:j,setBackupRestoreOpen:k,cloudSyncOpen:T,setCloudSyncOpen:M,handleBeforeSwitch:Ie,isDataReady:h,onCreateProjectForMemory:wt,currentBoardId:f,deferredRuntimeEnabled:O,shouldRenderDeferredFeatures:bt,versionUpdateEnabled:le,performancePanelEnabled:L,toolWindowManagerEnabled:he,minimizedToolsBarEnabled:ue,enableToolWindows:Q,enableGenerationRuntime:pe})})})})})})})})})},Yv=({value:e,viewport:t,theme:n,options:o,plugins:i,containerRef:s,appState:r,board:a,setBoard:c,projectDrawerOpen:u,toolboxDrawerOpen:l,taskPanelExpanded:h,mediaLibraryOpen:f,mediaLibraryConfig:g,backupRestoreOpen:y,deferredRuntimeEnabled:m,shouldRenderDeferredFeatures:w,versionUpdateEnabled:S,performancePanelEnabled:v,toolWindowManagerEnabled:E,minimizedToolsBarEnabled:C,enableToolWindows:D,enableGenerationRuntime:P,cloudSyncOpen:H,onChange:B,onSelectionChange:j,onViewportChange:U,onThemeChange:A,onValueChange:I,afterInit:k,onBoardSwitch:T,onTabSyncNeeded:M,handleProjectDrawerToggle:O,handleToolboxDrawerToggle:q,handleKnowledgeBaseToggle:le,handleTaskPanelToggle:R,handleOpenMediaLibrary:L,handleOpenBackupRestore:Y,handleOpenCloudSync:he,setProjectDrawerOpen:be,setToolboxDrawerOpen:ue,setTaskPanelExpanded:_e,setMediaLibraryOpen:Ce,setBackupRestoreOpen:ze,setCloudSyncOpen:W,handleBeforeSwitch:Q,isDataReady:pe,onCreateProjectForMemory:V,currentBoardId:N})=>{const{setAppState:b}=Ht(),{chatDrawerRef:x}=uf(),{language:_}=Oe(),z=vt(ae=>ae.error),G=vt(ae=>ae.playing||!!ae.activeAudioUrl||!!ae.activeReadingSourceId),$=p.useRef(void 0),[ne,xe]=p.useState(G);Nw({board:a,pointer:r.pointer}),qc({onSyncNeeded:p.useCallback(()=>{M?M():co()},[M]),enabled:!0,currentBoardId:N});const[X,oe]=p.useState(!1),[Fe,Ve]=p.useState(null),[Ie,wt]=p.useState(null),Ge=p.useRef(null),[Lt,bt]=p.useState(!1),[Z,ke]=p.useState([]),[se,we]=p.useState(0);p.useEffect(()=>{if(!z){$.current=void 0;return}z!==$.current&&($.current=z,Ne.error(z))},[z]),p.useEffect(()=>{G&&xe(!0)},[G]),p.useEffect(()=>{Ro.setCanvasQueue(Kn(e))},[e]),p.useEffect(()=>()=>{Ro.stopAndClear()},[]);const nt=p.useCallback(()=>{if(!a||!a.children)return{items:[],elementIds:[]};const ae=[],ye=[];for(const te of a.children){const fe=te.url;if(!fe||typeof fe!="string"||ki(te))continue;const ft=K.isDrawElement(te)&&K.isImage(te),Ke=Yi(te);(ft||Ke)&&(ae.push({id:te.id,url:fe,type:Ke?"video":"image",title:te.name||void 0}),ye.push(te.id))}return{items:ae,elementIds:ye}},[a]),ct=p.useCallback(ae=>{const{items:ye,elementIds:te}=nt();if(ye.length===0)return;const fe=te.indexOf(ae);fe!==-1&&(ke(ye),we(fe),bt(!0))},[nt]),lt=p.useCallback(()=>{bt(!1)},[]),$t=p.useCallback(async(ae,ye)=>{const te=ye.id;if(!(!te||!a))try{const{unifiedCacheService:fe}=await re(async()=>{const{unifiedCacheService:Be}=await import("./ai-chat-B-XdoWBQ.js").then(Wt=>Wt.sJ);return{unifiedCacheService:Be}},__vite__mapDeps([0]),import.meta.url),{Transforms:ft}=await re(async()=>{const{Transforms:Be}=await import("./ai-chat-B-XdoWBQ.js").then(Wt=>Wt.sL);return{Transforms:Be}},__vite__mapDeps([0]),import.meta.url),Ke=`edited-image-${Date.now()}`,Ee=`/__aitu_cache__/image/${Ke}.png`,ot=await(await fetch(ae)).blob();await fe.cacheMediaFromBlob(Ee,ot,"image",{taskId:Ke});const gt=new Image;await new Promise((Be,Wt)=>{gt.onload=()=>Be(),gt.onerror=()=>Wt(new Error("Failed to load edited image")),gt.src=ae});const pt=a.children.findIndex(Be=>Be.id===te);if(pt>=0){const Be=a.children[pt],{newPoints:Wt}=await zf({url:Be.url,width:Be.width,height:Be.height,points:Be.points||[[0,0],[0,0]]},gt.naturalWidth,gt.naturalHeight);ft.setNode(a,{url:Ee,width:gt.naturalWidth,height:gt.naturalHeight,points:Wt},[pt]),df(a,te,Ee)}}catch(fe){console.error("Failed to update image:",fe),Ne.error("更新失败")}},[a]),wi=p.useCallback(async ae=>{if(a)try{const{unifiedCacheService:ye}=await re(async()=>{const{unifiedCacheService:pt}=await import("./ai-chat-B-XdoWBQ.js").then(Be=>Be.sJ);return{unifiedCacheService:pt}},__vite__mapDeps([0]),import.meta.url),{insertImageFromUrl:te}=await re(async()=>{const{insertImageFromUrl:pt}=await import("./ai-chat-B-XdoWBQ.js").then(Be=>Be.sR);return{insertImageFromUrl:pt}},__vite__mapDeps([0]),import.meta.url),fe=`edited-image-${Date.now()}`,ft=`/__aitu_cache__/image/${fe}.png`,Ee=await(await fetch(ae)).blob();await ye.cacheMediaFromBlob(ft,Ee,"image",{taskId:fe});const ut=new Image;await new Promise((pt,Be)=>{ut.onload=()=>pt(),ut.onerror=()=>Be(new Error("Failed to load edited image")),ut.src=ae});const ot=si(a),gt=[((ot==null?void 0:ot[0])??0)+100,((ot==null?void 0:ot[1])??0)+100];await te(a,ft,gt,!1,{width:ut.naturalWidth,height:ut.naturalHeight},!1,!0)}catch(ye){console.error("Failed to insert image:",ye),Ne.error("插入失败")}},[a]),{state:Vt,selectShape:gu,closePicker:pu}=ov(a);p.useEffect(()=>{Ie&&Ge.current&&Ge.current.focus()},[Ie]);const mu=p.useCallback(()=>{if(!a||!Ie||!Ge.current){wt(null);return}const ae=Ge.current.innerText||"";if(ae.trim()){ec.insertText(a,Ie.worldPoint,ae);const ye=a.children[a.children.length-1],te=ye&&K.isText(ye)?ye.id:null;requestAnimationFrame(()=>{if(!te)return;const fe=a.children.findIndex(Ke=>Ke.id===te);if(fe===-1)return;const ft=a.children[fe];if(K.isText(ft)){const Ke=ft;if(!isFinite(Ke.textHeight)){const Ee=de.getRectangleByPoints(Ke.points);Se.setNode(a,{textHeight:Ee.height},[fe])}}})}wt(null),ee.updatePointerType(a,Le.selection),b(ye=>({...ye,pointer:Le.selection}))},[a,Ie,b]);return p.useEffect(()=>{if(!a)return;const ae=te=>{const fe=te.target;if(!(fe.closest(".board-host-svg")||fe.closest(".plait-board-container")))return;if(document.documentElement.classList.contains("slideshow-active")){te.preventDefault(),te.stopPropagation();return}const Ke=Xe(a,Ze(a,te.clientX,te.clientY)),Ee=qi(a,Ke);if(Ee&&Fc(Ee)){Tv(a,Ee,_),te.preventDefault(),te.stopPropagation();return}if(Ee){if(ki(Ee)){te.preventDefault(),te.stopPropagation();return}const ot=Ee.url;if(ot&&typeof ot=="string"){const gt=K.isDrawElement(Ee)&&K.isImage(Ee),pt=Yi(Ee);if(gt||pt){ct(Ee.id),te.preventDefault(),te.stopPropagation();return}}}const ut=fe.closest(".plait-tool-container")||fe.closest(".plait-workzone-container")||fe.closest("foreignObject");if(!Ee&&!ut){const ot=[te.clientX,te.clientY];Ve(ot),oe(!0)}},ye=s.current;return ye&&ye.addEventListener("dblclick",ae),()=>{ye&&ye.removeEventListener("dblclick",ae)}},[a,s,ct,_]),p.useEffect(()=>{if(!a)return;const ae=te=>{const fe=te.target;if(fe.closest(".side-drawer")||fe.closest(".project-drawer")||!(fe.closest(".board-host-svg")||fe.closest(".plait-board-container")))return;const Ke=Xe(a,Ze(a,te.clientX,te.clientY)),Ee=qi(a,Ke);if(Ee&&ki(Ee)&&!rt(Ee)){xe(!0);const ut=hf(Ee);if(ut){te.preventDefault(),te.stopPropagation(),Ro.togglePlaybackInQueue(ut,Kn(a.children),{queueSource:"canvas",queueId:Nc,queueName:Oc}).catch(()=>{});return}}if(F.isPointer(a,ge.text)&&!(fe.closest(".plait-tool-container")||fe.closest(".plait-workzone-container")||fe.closest("foreignObject"))&&!Ee){wt({screenX:te.clientX,screenY:te.clientY,worldPoint:Ke,zoom:a.viewport.zoom}),te.preventDefault(),te.stopPropagation();return}u&&Kv()&&be(!1),l&&fn()&&ue(!1),h&&gn()&&_e(!1)},ye=s.current;return ye&&ye.addEventListener("click",ae),()=>{ye&&ye.removeEventListener("click",ae)}},[a,s,u,l,h,be,ue,_e]),d.jsx("div",{className:me("drawnix",{"drawnix--mobile":r.isMobile}),ref:s,children:d.jsxs("div",{className:"drawnix__main",children:[d.jsxs(tm,{value:e,viewport:t,theme:n,options:o,plugins:i,onChange:ae=>{B&&B(ae)},onSelectionChange:j,onViewportChange:U,onThemeChange:A,onValueChange:I,children:[d.jsx(Xp,{afterInit:ae=>{c(ae),window.__drawnixBoard=ae,k&&k(ae),ae.afterChange&&ae.afterChange()}}),d.jsx(gy,{}),d.jsx(Rw,{projectDrawerOpen:u,onProjectDrawerToggle:O,toolboxDrawerOpen:l,onToolboxDrawerToggle:q,taskPanelExpanded:h,onTaskPanelToggle:R,onOpenBackupRestore:Y,onOpenCloudSync:he,onKnowledgeBaseToggle:le,onOpenMediaLibrary:L,deferredFeaturesEnabled:E,minimizedToolsBarEnabled:C,onEnableToolWindows:D}),ne&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(Vv,{})}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Cv,{})}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Iv,{})}),d.jsx(M0,{}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Av,{})}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Rv,{})}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Mv,{})}),r.openDialogTypes.size>0&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(Bv,{container:s.current})}),r.openSettings&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(Hv,{container:s.current})}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Dv,{container:s.current})}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Ov,{isDataReady:pe,activationKey:0,onEnableToolWindows:D,onEnableRuntime:P})}),X&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(Lv,{position:Fe,visible:X,onClose:()=>oe(!1),onOpenMediaLibrary:L})}),Ie&&d.jsx("div",{ref:Ge,contentEditable:!0,suppressContentEditableWarning:!0,style:{position:"fixed",left:Ie.screenX,top:Ie.screenY-14*Ie.zoom/2,minWidth:"2px",minHeight:"1.5em",outline:"none",border:"none",background:"transparent",fontSize:`${14*Ie.zoom}px`,lineHeight:"1.5",color:"#333",caretColor:"#333",zIndex:1e4,whiteSpace:"pre-wrap",fontFamily:"inherit"},onBlur:mu,onKeyDown:ae=>{ae.key==="Escape"&&wt(null),ae.stopPropagation()}}),Lt&&d.jsx(p.Suspense,{fallback:null,children:d.jsx($v,{visible:Lt,items:Z,initialIndex:se,onClose:lt,showThumbnails:!0,useBuiltInEditor:!0,showEditOverwrite:!0,onEditOverwrite:$t,onEditInsert:wi})}),Vt.visible&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(jv,{visible:Vt.visible,position:Vt.position,currentShape:Vt.currentShape||void 0,onSelectShape:gu,onClose:pu,container:s.current})}),d.jsx(_y,{})]}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Nv,{ref:x})}),m&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(Fv,{board:a,value:e})}),w&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(zv,{board:a,value:e,containerRef:s,versionUpdateEnabled:S,performancePanelEnabled:v,toolWindowManagerEnabled:E,projectDrawerOpen:u,toolboxDrawerOpen:l,mediaLibraryOpen:f,mediaLibraryConfig:g,backupRestoreOpen:y,cloudSyncOpen:H,onBoardSwitch:T,setProjectDrawerOpen:be,setToolboxDrawerOpen:ue,setMediaLibraryOpen:Ce,setBackupRestoreOpen:ze,setCloudSyncOpen:W,handleOpenMediaLibrary:L,handleBeforeSwitch:Q,onCreateProjectForMemory:V})})]})})};let Oa=!1;const lu="sw-debug-enabled";function Xv(){try{return sessionStorage.getItem(lu)==="true"}catch{return!1}}function Na(e){try{sessionStorage.setItem(lu,e===!0?"true":"false")}catch{}}let zn=Xv();const Xt=[];let kn=null,Ot=0;const oi=15e3,Zv=200,Fn={error:console.error,warn:console.warn,info:console.info,log:console.log,debug:console.debug};function Es(e){return(e.includes("AbortError")||e.includes("The user aborted a request"))&&(e.includes("Failed to execute 'showOpenFilePicker'")||e.includes("Failed to execute 'showSaveFilePicker'")||e.includes("The user aborted a request"))}function Gt(e,t,n){if(t.includes("[SW]")||t.includes("[SWTaskQueue]")||t.includes("[SWChannelManager]")||t.includes("[SWChannelClient]")||t.includes("[ServiceWorkerChannel]")||t.includes("Invalid message structure")||t.includes("posthog.com")||n&&n.includes("posthog")||Es(t)||t.includes("ResizeObserver loop completed with undelivered notifications")||t.includes("ResizeObserver loop limit exceeded"))return;const o=()=>{Ae.isInitialized()&&Ae.reportConsoleLog(e,[{message:t,stack:n||"",source:window.location.href}],Date.now()).catch(()=>{})},i=()=>{for(;Xt.length>0&&Ae.isInitialized();){const r=Xt.shift();r&&Ae.reportConsoleLog(r.level,[{message:r.message,stack:r.stack||"",source:window.location.href}],Date.now()).catch(()=>{})}},s=()=>{const r=Date.now();kn||r<Ot||(kn=Ae.initialize().then(a=>{if(!a){Ot=Date.now()+oi;return}Ot=0,i()}).catch(()=>{Ot=Date.now()+oi}).finally(()=>{kn=null}))};Ae.isInitialized()?o():(Xt.length>=Zv&&Xt.shift(),Xt.push({level:e,message:t,stack:n}),s())}function Bn(e){return e.map(t=>{if(t instanceof Error)return t.message;if(typeof t=="object")try{return JSON.stringify(t)}catch{return String(t)}return String(t)}).join(" ")}function za(e){for(const t of e)if(t instanceof Error&&t.stack)return t.stack;return""}function Jv(){if(Oa||!("serviceWorker"in navigator))return;Oa=!0;const e=()=>{if(Ae.isInitialized())Ae.subscribeToEvent("debug:statusChanged",t=>{const n=t,o=n.enabled??n.debugModeEnabled??!1;zn=o,Na(o)}),Ae.getDebugStatus().then(t=>{const n=t.enabled??t.debugModeEnabled??!1;zn=n,Na(n)});else{const t=Date.now();!kn&&t>=Ot&&(kn=Ae.initialize().then(n=>{if(!n){Ot=Date.now()+oi;return}for(Ot=0;Xt.length>0&&Ae.isInitialized();){const o=Xt.shift();o&&Ae.reportConsoleLog(o.level,[{message:o.message,stack:o.stack||"",source:window.location.href}],Date.now()).catch(()=>{})}}).catch(()=>{Ot=Date.now()+oi}).finally(()=>{kn=null})),setTimeout(e,500)}};e(),console.error=function(...t){Fn.error.apply(console,t),Gt("error",Bn(t),za(t))},console.warn=function(...t){Fn.warn.apply(console,t),Gt("warn",Bn(t),za(t))},console.log=function(...t){Fn.log.apply(console,t),zn&&Gt("log",Bn(t),"")},console.info=function(...t){Fn.info.apply(console,t),zn&&Gt("info",Bn(t),"")},console.debug=function(...t){Fn.debug.apply(console,t),zn&&Gt("debug",Bn(t),"")},window.addEventListener("error",t=>{var o;const n=`${t.message} at ${t.filename}:${t.lineno}:${t.colno}`;Es(n)||Gt("error",n,((o=t.error)==null?void 0:o.stack)||"")}),window.addEventListener("unhandledrejection",t=>{const n=t.reason,o=n instanceof Error?n.message:`Unhandled Promise: ${String(n)}`,i=n instanceof Error&&n.stack||"";Es(o)||Gt("error",o,i)})}const Qv=typeof window<"u"&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),eS=typeof window<"u"?new URLSearchParams(window.location.search).get("sw"):null,uu=eS==="0",du=typeof navigator<"u"&&"serviceWorker"in navigator,hu=du&&!uu;hu&&Jv();et.markLoadingStart();et.checkUrlSafeMode();Yg();const tS="1.0.0",nS=ff(),Fa="_lazy_chunk_retry",oS="_t";function iS(){if(typeof window>"u")return;const e=new URL(window.location.href);if(e.searchParams.has(Fa)){e.searchParams.delete(Fa),e.searchParams.delete(oS);try{window.history.replaceState(window.history.state,"",e.toString())}catch{}}}iS();function fu(e){return e==="jsdelivr"||e==="unpkg"||e==="local"}function sS(){return window.__OPENTU_BOOT__||null}function yn(e){var t,n;(n=(t=sS())==null?void 0:t.setProgress)==null||n.call(t,e==null?void 0:e.progress,e)}function rS(){const e=window.__OPENTU_CDN__||window.__AITU_CDN__;return!e||!fu(e.cdn)?null:{cdn:e.cdn,latency:Number.isFinite(e.latency)&&e.latency>=0?e.latency:0,timestamp:Number.isFinite(e.timestamp)&&e.timestamp>0?e.timestamp:Date.now()}}function Ba(e){const t=rS();if(!t)return;const n={type:"SW_CDN_SET_PREFERENCE",...t,version:tS},o=new Set,i=[navigator.serviceWorker.controller,e==null?void 0:e.active,e==null?void 0:e.waiting,e==null?void 0:e.installing];for(const s of i)s&&o.add(s);o.forEach(s=>{s.postMessage(n)})}function Ha(e){Ba(e);const t=window.__OPENTU_CDN_API__||window.__AITU_CDN_API__;t!=null&&t.selectBestCDN&&t.selectBestCDN().then(n=>{n&&fu(n.cdn)&&(window.__OPENTU_CDN__=n),Ba(e)}).catch(n=>{console.warn("[Main] Failed to sync CDN preference to Service Worker:",n)})}function aS(){navigator.serviceWorker.getRegistration().then(e=>e==null?void 0:e.unregister()).catch(e=>{console.warn("[Main] Disabled service worker cleanup failed:",e)})}function Ao(e,t={}){if(typeof window>"u")return;const{delay:n=0,timeout:o=2e3}=t,i=()=>{const r=window.requestIdleCallback;if(typeof r=="function"){r(e,{timeout:o});return}window.setTimeout(e,Math.min(o,500))},s=()=>{if(n>0){window.setTimeout(i,n);return}i()};window.requestAnimationFrame(()=>{window.requestAnimationFrame(s)})}yn({tip:"正在初始化启动服务...",source:"phase",progress:12});if(typeof window<"u"){ig();const e=()=>{if(window.posthog){pf(nS),og();return}setTimeout(e,300)};Ao(e,{delay:0,timeout:1e3}),Ao(()=>{Zc().catch(n=>{console.warn("[Main] Database cleanup failed:",n)}),lg.runMigration().then(()=>Promise.all([gf(),Ff.initializeAsync()])).catch(n=>{console.warn("[Main] Storage migration/init failed:",n)})},{delay:400,timeout:2500}),Ao(()=>{br.start(),br.logMemoryStatus()},{delay:5e3,timeout:2500});const t=()=>{window.posthog?Zf():setTimeout(t,500)};Ao(t,{delay:1500,timeout:3e3})}du&&uu&&aS();if(hu){const e=Qv;let t=null,n=!1,o=!1,i=null,s=null;const r=m=>{i!==m&&(i=m,window.dispatchEvent(new CustomEvent("sw-update-available",{detail:{version:m}})))},a=m=>{if(m.pendingVersion&&m.pendingVersion!==m.committedVersion&&(m.upgradeState==="ready"||m.upgradeState==="committing")){r(m.pendingVersion);return}m.pendingVersion||(i=null)},c=m=>{const w=m||t||(s==null?void 0:s.waiting)||navigator.serviceWorker.controller||(s==null?void 0:s.active)||null;w&&w.postMessage({type:"GET_VERSION_STATE"})},u=m=>{navigator.serviceWorker.controller||!(m!=null&&m.active)||m.active.postMessage({type:"CLAIM_CLIENTS"})},l=m=>{!n||o||(o=!0,setTimeout(()=>{co()},1e3))},h=async()=>{const m=[t,s==null?void 0:s.waiting];try{const w=await navigator.serviceWorker.getRegistration()||null;w&&(s=w,m.push(w.waiting))}catch(w){console.warn("[Main] Failed to get live service worker registration:",w)}try{const w=await navigator.serviceWorker.ready;m.push(w.waiting)}catch(w){console.warn("[Main] Failed to inspect ready service worker registration:",w)}for(const w of m)if(!(!w||w.state==="redundant")&&w!==navigator.serviceWorker.controller)return t=w,w;return null},f=window.__OPENTU_SW_REGISTRATION_PROMISE__||navigator.serviceWorker.register("./sw.js").catch(m=>(console.warn("[Main] Service worker registration failed:",m),null));window.__OPENTU_SW_REGISTRATION_PROMISE__=f,f.then(m=>{if(!m){yn({tip:"离线加速未启用,正在直接启动工作台...",source:"phase",progress:70});return}s=m,u(m),navigator.serviceWorker.ready.then(u).catch(w=>{console.warn("[Main] Service worker ready check failed:",w)}),yn({tip:"启动缓存服务已连接,正在准备资源清单...",source:"phase",progress:72}),Ha(m),e?(m.update().catch(w=>console.warn("Forced update check failed:",w)),m.waiting&&m.waiting.postMessage({type:"FORCE_UPGRADE"})):m.waiting&&navigator.serviceWorker.controller&&(t=m.waiting,c(m.waiting)),m.addEventListener("updatefound",()=>{const w=m.installing;w&&w.addEventListener("statechange",()=>{w.state==="installed"&&navigator.serviceWorker.controller&&(t=w,e?w.postMessage({type:"FORCE_UPGRADE"}):(c(w),setTimeout(()=>c(w),5e3)))})}),m.active&&!m.installing&&!m.waiting&&yn({tip:"启动缓存服务已就绪,正在恢复工作台状态...",source:"phase",progress:78}),c(),setInterval(()=>{m.update().catch(w=>{console.warn("Update check failed:",w)})},300*1e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&c()})}).catch(m=>{yn({tip:"离线加速未启用,正在直接启动工作台...",source:"phase",progress:70})});const g=()=>{if(!Ae.isInitialized()){setTimeout(g,500);return}Ae.setEventHandlers({onSWUpdated:m=>{c()},onSWNewVersionReady:m=>{r(m.version),c()},onSWActivated:m=>{if(n){l();return}t=null,c()}}),s!=null&&s.waiting&&navigator.serviceWorker.controller&&(t=s.waiting,c(s.waiting))};setTimeout(g,1e3);const y=async()=>{if(!Ae.isInitialized()){setTimeout(y,500);return}Ae.registerVideoThumbnailHandler(async(m,w)=>{try{const{generateVideoThumbnailFromBlob:S}=await re(async()=>{const{generateVideoThumbnailFromBlob:H}=await import("./ai-chat-B-XdoWBQ.js").then(B=>B.sG);return{generateVideoThumbnailFromBlob:H}},__vite__mapDeps([0]),import.meta.url);let v=null;const C=await(await caches.open("drawnix-images")).match(m);if(C&&(v=await C.blob()),!v&&(m.startsWith("http://")||m.startsWith("https://")))try{const H=await fetch(m);H.ok&&(v=await H.blob())}catch{v=null}if(!v)return{error:"Video not found in cache or network"};const D=await S(v,w||400);return{thumbnailUrl:await new Promise((H,B)=>{const j=new FileReader;j.onloadend=()=>H(j.result),j.onerror=B,j.readAsDataURL(D)})}}catch(S){return{error:S instanceof Error?S.message:String(S)}}})};y(),navigator.serviceWorker.addEventListener("message",m=>{var w;((w=m.data)==null?void 0:w.type)==="SW_VERSION_STATE"&&a(m.data)}),navigator.serviceWorker.addEventListener("controllerchange",()=>{Ha(s),c(),l()}),window.addEventListener("user-confirmed-upgrade",()=>{(async()=>{const m=await h();if(!m){console.warn("[Main] No waiting service worker available for COMMIT_UPGRADE"),c(),s==null||s.update().catch(w=>{console.warn("[Main] Update check after missing waiting worker failed:",w)});return}n=!0,m.postMessage({type:"COMMIT_UPGRADE"})})()})}yn({tip:"正在挂载工作台界面...",source:"phase",progress:88});const cS=mo.createRoot(document.getElementById("root"));cS.render(d.jsx(p.StrictMode,{children:d.jsx(Zg,{children:d.jsx(sp,{})})}));const vS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{Dl as A,Xp as B,yS as D,Ml as F,an as I,kt as S,tm as W,og as a,ig as b,et as c,Kc as d,$f as e,Vf as f,Ye as g,pS as h,Zf as i,Pv as j,mS as k,gS as l,Yc as m,wS as n,Tv as o,zw as p,Fw as q,Zc as r,lg as s,nn as t,qf as u,Rl as v,Um as w,Vy as x,fS as y,vS as z};
|
|
22
|
+
`).trim()}function pS(e){return K.isDrawElement(e)&&K.isText(e)}function mS(e,t){return[...t].sort((n,o)=>{const i=Ft(e,[n],!1),s=Ft(e,[o],!1);return Math.abs(i.x-s.x)<=xv&&Math.abs(i.y-s.y)>.5?i.y-s.y:i.x-s.x})}async function Pv(e,t,n="zh"){if(!t)return null;if(t.noteId)return t.noteId;try{const{knowledgeBaseService:o,directory:i}=await bv(),s=await o.createNote(kv(t),i.id),r=Ev(t);return r&&await o.updateNote(s.id,{content:r}),_v(e,t.id,s.id),s.id}catch(o){return console.error("Failed to create note for card:",o),Ne.error(n==="zh"?"保存到知识库失败":"Failed to save to knowledge base"),null}}async function wS(e,t){const n=[...new Set(e.filter(Boolean))];if(n.length===0)return;const{knowledgeBaseService:o}=await re(async()=>{const{knowledgeBaseService:s}=await import("./ai-chat-BnWVpTEI.js").then(r=>r.sN);return{knowledgeBaseService:s}},__vite__mapDeps([0]),import.meta.url);await o.initialize();const i=n[0];await o.updateNote(i,{content:t});for(const s of n.slice(1))await o.deleteNote(s);return i}const Tv=async(e,t,n="zh")=>{if(t){if(t.noteId){window.dispatchEvent(new CustomEvent("kb:open",{detail:{noteId:t.noteId}}));return}try{const o=await Pv(e,t,n);if(!o)return;window.dispatchEvent(new CustomEvent("kb:open",{detail:{noteId:o}}))}catch(o){console.error("Failed to create note for card:",o),Ne.error(n==="zh"?"无法打开知识库笔记":"Failed to open knowledge base note")}}},Cv=p.lazy(()=>re(()=>import("./popup-toolbar-BChsudwW.js"),__vite__mapDeps([0,1,5]),import.meta.url).then(e=>({default:e.PopupToolbar}))),Iv=p.lazy(()=>re(()=>import("./link-popup-B6ReK6iq.js"),__vite__mapDeps([0,1,6]),import.meta.url).then(e=>({default:e.LinkPopup}))),Av=p.lazy(()=>re(()=>import("./index-D1LQ9eQM.js"),__vite__mapDeps([0,1,7]),import.meta.url).then(e=>({default:e.PencilSettingsToolbar}))),Mv=p.lazy(()=>re(()=>import("./index-D1LQ9eQM.js"),__vite__mapDeps([0,1,7]),import.meta.url).then(e=>({default:e.EraserSettingsToolbar}))),Rv=p.lazy(()=>re(()=>import("./index-BSZAS0wO.js"),__vite__mapDeps([0,1,8]),import.meta.url).then(e=>({default:e.PenSettingsToolbar}))),Dv=p.lazy(()=>re(()=>import("./clean-confirm-CIViVQ8s.js"),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.CleanConfirm}))),Lv=p.lazy(()=>re(()=>import("./quick-creation-toolbar-3-AYFpEF.js"),__vite__mapDeps([0,1,9]),import.meta.url).then(e=>({default:e.QuickCreationToolbar}))),jv=p.lazy(()=>re(()=>import("./index-CIgiIDgZ.js"),__vite__mapDeps([0,1,10]),import.meta.url).then(e=>({default:e.AutoCompleteShapePicker}))),Ov=p.lazy(()=>re(()=>import("./DeferredAIInputBar-B2R2-2RU.js"),__vite__mapDeps([0,1,11]),import.meta.url).then(e=>({default:e.DeferredAIInputBar}))),Nv=p.lazy(()=>re(()=>import("./ai-chat-BnWVpTEI.js").then(e=>e.t4),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.ChatDrawer}))),st=["tool-windows","runtime-static-assets"],zv=p.lazy(()=>re(()=>import("./DrawnixDeferredFeatures-DHTr0c-V.js"),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.DrawnixDeferredFeatures}))),Fv=p.lazy(()=>re(()=>import("./tool-windows-Bf_pMml-.js").then(e=>e.b4),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.DrawnixDeferredRuntime}))),Bv=p.lazy(()=>re(()=>import("./ttd-dialog-CohjwODB.js"),__vite__mapDeps([0,1,3,4,12,13]),import.meta.url).then(e=>({default:e.TTDDialog}))),Hv=p.lazy(()=>re(()=>import("./settings-dialog-Ccemaout.js"),__vite__mapDeps([0,1,14]),import.meta.url).then(e=>({default:e.SettingsDialog}))),$v=p.lazy(()=>re(()=>import("./ai-chat-BnWVpTEI.js").then(e=>e.sX),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.UnifiedMediaViewer}))),Vv=p.lazy(()=>re(()=>import("./CanvasAudioPlayer-HtUs8HDj.js"),__vite__mapDeps([0,1,15]),import.meta.url).then(e=>({default:e.CanvasAudioPlayer}))),Wv=[],Uv="project-drawer-active-tab",Gv="frames",cu=()=>{try{return localStorage.getItem(Uv)===Gv}catch{return!1}},Fo=()=>!Ns(zs.project),Kv=()=>Fo()&&!cu(),fn=()=>!Ns(zs.toolbox),gn=()=>!Ns(zs.task);function qv(){var o,i;if(typeof window>"u")return!1;const e=((o=window.matchMedia)==null?void 0:o.call(window,"(pointer: coarse)").matches)??!1,t=((i=window.matchMedia)==null?void 0:i.call(window,"(max-width: 768px)").matches)??!1,n=navigator.maxTouchPoints>0||"ontouchstart"in window;return t||e&&n}const yS=({value:e,viewport:t,theme:n,onChange:o,onSelectionChange:i,onViewportChange:s,onThemeChange:r,onValueChange:a,afterInit:c,onBoardSwitch:u,onTabSyncNeeded:l,isDataReady:h=!1,currentBoardId:f})=>{const g={readonly:!1,hideScrollbar:!1,disabledScrollOnNonFocus:!1,themeColors:cf},[y,m]=p.useState(()=>({pointer:Le.hand,isMobile:qv(),isPencilMode:!1,openDialogTypes:new Set,dialogInitialData:null,dialogInitialDataByType:{},openCleanConfirm:!1,openSettings:!1})),[w,S]=p.useState(null),[v,E]=p.useState(!1),[C,D]=p.useState(!1),[P,H]=p.useState(!1),[B,j]=p.useState(!1),[U,A]=p.useState({mode:$o.BROWSE}),[I,k]=p.useState(!1),[T,M]=p.useState(!1),[O,q]=p.useState(!1),[le,R]=p.useState(!1),[L,Y]=p.useState(!1),[he,be]=p.useState(!1),[ue,_e]=p.useState(!1),Ce=p.useRef(null),ze=p.useCallback(()=>{Fo()&&E(!1),fn()&&D(!1),gn()&&H(!1),j(!1)},[]),W=p.useCallback((Z=Wv)=>{el(Z),q(!0)},[]),Q=p.useCallback((Z=st)=>{W(Z),_e(!0),be(!0)},[W]),pe=p.useCallback(()=>{W(st)},[W]);p.useEffect(()=>{(y.openDialogTypes.has(dt.aiImageGeneration)||y.openDialogTypes.has(dt.aiVideoGeneration))&&pe()},[y.openDialogTypes,pe]);const V=p.useCallback(()=>{Q(st),Promise.all([re(()=>import("./tool-windows-Bf_pMml-.js").then(Z=>Z.b0),__vite__mapDeps([0,1]),import.meta.url),re(()=>import("./tool-windows-Bf_pMml-.js").then(Z=>Z.a$),__vite__mapDeps([0,1]),import.meta.url)]).then(([{toolWindowService:Z},{toolRegistry:ke}])=>{const se=ke.getManifestById("knowledge-base");if(!se)return;const we=Z.getToolState(se.id);we&&we.status==="open"?Z.closeTool(se.id):Z.openTool(se)})},[Q]);p.useEffect(()=>{const Z=ke=>{const{noteId:se}=ke.detail;Q(st),Promise.all([re(()=>import("./tool-windows-Bf_pMml-.js").then(we=>we.b0),__vite__mapDeps([0,1]),import.meta.url),re(()=>import("./tool-windows-Bf_pMml-.js").then(we=>we.a$),__vite__mapDeps([0,1]),import.meta.url)]).then(([{toolWindowService:we},{toolRegistry:nt}])=>{const ct=nt.getManifestById("knowledge-base");if(!ct)return;const lt=we.isToolOpen(ct.id);we.openTool(ct,{componentProps:se?{initialNoteId:se}:{}}),lt&&se&&window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("kb:open-note",{detail:{noteId:se}}))},50)})};return window.addEventListener("kb:open",Z),()=>window.removeEventListener("kb:open",Z)},[Q]);const N=p.useCallback(()=>{if(Q(st),v){E(!1);return}fn()&&D(!1),gn()&&H(!1),j(!1),E(!0)},[Q,v]);p.useEffect(()=>{const Z=()=>{Q(st),fn()&&D(!1),gn()&&H(!1),j(!1),E(!0)};return window.addEventListener(Sr,Z),()=>window.removeEventListener(Sr,Z)},[Q]);const b=p.useCallback(()=>{if(Q(st),C){D(!1);return}Fo()&&E(!1),gn()&&H(!1),j(!1),D(!0)},[Q,C]),x=p.useCallback(()=>{if(W(st),P){H(!1);return}Fo()&&E(!1),fn()&&D(!1),j(!1),H(!0)},[W,P]),_=p.useCallback(Z=>{Q(st);const{keepProjectDrawerOpen:ke,...se}=Z||{};ke?(fn()&&D(!1),gn()&&H(!1),j(!1)):ze(),A({mode:$o.BROWSE,...se}),j(!0)},[ze,Q]),z=p.useCallback(()=>{W(st),k(!0)},[W]),G=p.useCallback(()=>{W(st),M(!0)},[W]),$=p.useCallback(Z=>{m(Z)},[]),ne=p.useCallback(Z=>{m(ke=>({...ke,...Z}))},[]);p.useEffect(()=>{w&&(w.appState=y,w.__setAppState=$,Ce.current=w)},[w,y,$]),p.useEffect(()=>{if(new URLSearchParams(window.location.search).has("tool")){Q(st);return}},[Q]),p.useEffect(()=>{if(typeof window>"u"||!("serviceWorker"in navigator))return;let Z=!1;const ke=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1",se=lt=>{var $t;(($t=lt.data)==null?void 0:$t.type)==="SW_IDLE_PREFETCH_STATUS"&&st.every(wi=>{var Vt;return(Vt=lt.data.completedGroups)==null?void 0:Vt.includes(wi)})&&(Z=!0,_e(!0))};navigator.serviceWorker.addEventListener("message",se);const we={type:"SW_IDLE_PREFETCH_STATUS_GET"},nt=navigator.serviceWorker.controller;nt?nt.postMessage(we):navigator.serviceWorker.ready.then(lt=>{var $t;($t=lt.active)==null||$t.postMessage(we)}).catch(()=>{});const ct=window.setTimeout(()=>{Z||ue||(ke||console.warn("[Drawnix] SW idle prefetch status unresolved, enabling minimized tools bar fallback"),_e(!0))},2200);return()=>{window.clearTimeout(ct),navigator.serviceWorker.removeEventListener("message",se)}},[ue]),p.useEffect(()=>{const Z=window.requestIdleCallback;let ke;const se=window.setTimeout(()=>{const we=()=>{R(!0),Y(!0)};if(typeof Z=="function"){ke=Z(we,{timeout:2500});return}we()},5e3);return()=>{var we;window.clearTimeout(se),typeof ke=="number"&&((we=window.cancelIdleCallback)==null||we.call(window,ke))}},[]),p.useEffect(()=>{const Z=ke=>{const se=ke,{message:we,reason:nt}=se.detail,ct=nt||lf(we);Ne.error({content:ct==="missing"?"缺少 API Key,请先在设置中配置":"API Key 无效或已过期,请重新配置",duration:5e3}),console.error("[Drawnix] API auth error:",we),m(lt=>({...lt,openSettings:!0}))};return window.addEventListener(xr,Z),()=>{window.removeEventListener(xr,Z)}},[]);const xe=[ef,tf,nf,mm,Um,Ww(ne),S0,I0,dy,ay,A0(ne),R0(ne),of,Df,Z0,Lf,jf,Of,Ay,zy,sf,yv,rf,af,qy,tv,rv,fv,Nf,vv,U0,K0],X=p.useRef(null),{saveBoard:oe,createBoard:Fe,switchBoard:Ve}=Af(),Ie=p.useCallback(async()=>{if(o&&Ce.current){const Z={children:Ce.current.children||[],viewport:Ce.current.viewport,theme:Ce.current.theme};await oe(Z)}},[o,oe]),wt=p.useCallback(async()=>{await Ie();const Z=await Fe({name:"新画布"});Z&&(await Ve(Z.id),setTimeout(()=>{co()},500))},[Ie,Fe,Ve]),Ge=p.useCallback(Z=>{const ke=Ce.current;if(ke&&Z){const se=Te(ke),we=se.map(nt=>nt.id).filter(Boolean);se.some(So)&&(!v||!cu())&&Mc(),ne({lastSelectedElementIds:we})}i&&i(Z)},[i,v,ne]),Lt=p.useMemo(()=>({appState:y,setAppState:$,board:w}),[y,$,w]),bt=le||L||he||y.openCommandPalette||y.openCanvasSearch||v||C||B||I||T;return d.jsx(Yh,{children:d.jsx(Mf,{children:d.jsx(Xh,{children:d.jsx(Zh,{children:d.jsx(Rf,{children:d.jsx(Py,{onOpenMediaLibrary:_,children:d.jsx(Jh,{children:d.jsx(Qh.Provider,{value:Lt,children:d.jsx(Yv,{value:e,viewport:t,theme:n,options:g,plugins:xe,containerRef:X,appState:y,board:w,setBoard:S,projectDrawerOpen:v,toolboxDrawerOpen:C,taskPanelExpanded:P,mediaLibraryOpen:B,mediaLibraryConfig:U,backupRestoreOpen:I,onChange:o,onSelectionChange:Ge,onViewportChange:s,onThemeChange:r,onValueChange:a,afterInit:c,onBoardSwitch:u,onTabSyncNeeded:l,handleProjectDrawerToggle:N,handleToolboxDrawerToggle:b,handleKnowledgeBaseToggle:V,handleTaskPanelToggle:x,handleOpenMediaLibrary:_,handleOpenBackupRestore:z,handleOpenCloudSync:G,setProjectDrawerOpen:E,setToolboxDrawerOpen:D,setTaskPanelExpanded:H,setMediaLibraryOpen:j,setBackupRestoreOpen:k,cloudSyncOpen:T,setCloudSyncOpen:M,handleBeforeSwitch:Ie,isDataReady:h,onCreateProjectForMemory:wt,currentBoardId:f,deferredRuntimeEnabled:O,shouldRenderDeferredFeatures:bt,versionUpdateEnabled:le,performancePanelEnabled:L,toolWindowManagerEnabled:he,minimizedToolsBarEnabled:ue,enableToolWindows:Q,enableGenerationRuntime:pe})})})})})})})})})},Yv=({value:e,viewport:t,theme:n,options:o,plugins:i,containerRef:s,appState:r,board:a,setBoard:c,projectDrawerOpen:u,toolboxDrawerOpen:l,taskPanelExpanded:h,mediaLibraryOpen:f,mediaLibraryConfig:g,backupRestoreOpen:y,deferredRuntimeEnabled:m,shouldRenderDeferredFeatures:w,versionUpdateEnabled:S,performancePanelEnabled:v,toolWindowManagerEnabled:E,minimizedToolsBarEnabled:C,enableToolWindows:D,enableGenerationRuntime:P,cloudSyncOpen:H,onChange:B,onSelectionChange:j,onViewportChange:U,onThemeChange:A,onValueChange:I,afterInit:k,onBoardSwitch:T,onTabSyncNeeded:M,handleProjectDrawerToggle:O,handleToolboxDrawerToggle:q,handleKnowledgeBaseToggle:le,handleTaskPanelToggle:R,handleOpenMediaLibrary:L,handleOpenBackupRestore:Y,handleOpenCloudSync:he,setProjectDrawerOpen:be,setToolboxDrawerOpen:ue,setTaskPanelExpanded:_e,setMediaLibraryOpen:Ce,setBackupRestoreOpen:ze,setCloudSyncOpen:W,handleBeforeSwitch:Q,isDataReady:pe,onCreateProjectForMemory:V,currentBoardId:N})=>{const{setAppState:b}=Ht(),{chatDrawerRef:x}=uf(),{language:_}=Oe(),z=vt(ae=>ae.error),G=vt(ae=>ae.playing||!!ae.activeAudioUrl||!!ae.activeReadingSourceId),$=p.useRef(void 0),[ne,xe]=p.useState(G);Nw({board:a,pointer:r.pointer}),qc({onSyncNeeded:p.useCallback(()=>{M?M():co()},[M]),enabled:!0,currentBoardId:N});const[X,oe]=p.useState(!1),[Fe,Ve]=p.useState(null),[Ie,wt]=p.useState(null),Ge=p.useRef(null),[Lt,bt]=p.useState(!1),[Z,ke]=p.useState([]),[se,we]=p.useState(0);p.useEffect(()=>{if(!z){$.current=void 0;return}z!==$.current&&($.current=z,Ne.error(z))},[z]),p.useEffect(()=>{G&&xe(!0)},[G]),p.useEffect(()=>{Ro.setCanvasQueue(Kn(e))},[e]),p.useEffect(()=>()=>{Ro.stopAndClear()},[]);const nt=p.useCallback(()=>{if(!a||!a.children)return{items:[],elementIds:[]};const ae=[],ye=[];for(const te of a.children){const fe=te.url;if(!fe||typeof fe!="string"||ki(te))continue;const ft=K.isDrawElement(te)&&K.isImage(te),Ke=Yi(te);(ft||Ke)&&(ae.push({id:te.id,url:fe,type:Ke?"video":"image",title:te.name||void 0}),ye.push(te.id))}return{items:ae,elementIds:ye}},[a]),ct=p.useCallback(ae=>{const{items:ye,elementIds:te}=nt();if(ye.length===0)return;const fe=te.indexOf(ae);fe!==-1&&(ke(ye),we(fe),bt(!0))},[nt]),lt=p.useCallback(()=>{bt(!1)},[]),$t=p.useCallback(async(ae,ye)=>{const te=ye.id;if(!(!te||!a))try{const{unifiedCacheService:fe}=await re(async()=>{const{unifiedCacheService:Be}=await import("./ai-chat-BnWVpTEI.js").then(Wt=>Wt.sK);return{unifiedCacheService:Be}},__vite__mapDeps([0]),import.meta.url),{Transforms:ft}=await re(async()=>{const{Transforms:Be}=await import("./ai-chat-BnWVpTEI.js").then(Wt=>Wt.sM);return{Transforms:Be}},__vite__mapDeps([0]),import.meta.url),Ke=`edited-image-${Date.now()}`,Ee=`/__aitu_cache__/image/${Ke}.png`,ot=await(await fetch(ae)).blob();await fe.cacheMediaFromBlob(Ee,ot,"image",{taskId:Ke});const gt=new Image;await new Promise((Be,Wt)=>{gt.onload=()=>Be(),gt.onerror=()=>Wt(new Error("Failed to load edited image")),gt.src=ae});const pt=a.children.findIndex(Be=>Be.id===te);if(pt>=0){const Be=a.children[pt],{newPoints:Wt}=await zf({url:Be.url,width:Be.width,height:Be.height,points:Be.points||[[0,0],[0,0]]},gt.naturalWidth,gt.naturalHeight);ft.setNode(a,{url:Ee,width:gt.naturalWidth,height:gt.naturalHeight,points:Wt},[pt]),df(a,te,Ee)}}catch(fe){console.error("Failed to update image:",fe),Ne.error("更新失败")}},[a]),wi=p.useCallback(async ae=>{if(a)try{const{unifiedCacheService:ye}=await re(async()=>{const{unifiedCacheService:pt}=await import("./ai-chat-BnWVpTEI.js").then(Be=>Be.sK);return{unifiedCacheService:pt}},__vite__mapDeps([0]),import.meta.url),{insertImageFromUrl:te}=await re(async()=>{const{insertImageFromUrl:pt}=await import("./ai-chat-BnWVpTEI.js").then(Be=>Be.sS);return{insertImageFromUrl:pt}},__vite__mapDeps([0]),import.meta.url),fe=`edited-image-${Date.now()}`,ft=`/__aitu_cache__/image/${fe}.png`,Ee=await(await fetch(ae)).blob();await ye.cacheMediaFromBlob(ft,Ee,"image",{taskId:fe});const ut=new Image;await new Promise((pt,Be)=>{ut.onload=()=>pt(),ut.onerror=()=>Be(new Error("Failed to load edited image")),ut.src=ae});const ot=si(a),gt=[((ot==null?void 0:ot[0])??0)+100,((ot==null?void 0:ot[1])??0)+100];await te(a,ft,gt,!1,{width:ut.naturalWidth,height:ut.naturalHeight},!1,!0)}catch(ye){console.error("Failed to insert image:",ye),Ne.error("插入失败")}},[a]),{state:Vt,selectShape:gu,closePicker:pu}=ov(a);p.useEffect(()=>{Ie&&Ge.current&&Ge.current.focus()},[Ie]);const mu=p.useCallback(()=>{if(!a||!Ie||!Ge.current){wt(null);return}const ae=Ge.current.innerText||"";if(ae.trim()){ec.insertText(a,Ie.worldPoint,ae);const ye=a.children[a.children.length-1],te=ye&&K.isText(ye)?ye.id:null;requestAnimationFrame(()=>{if(!te)return;const fe=a.children.findIndex(Ke=>Ke.id===te);if(fe===-1)return;const ft=a.children[fe];if(K.isText(ft)){const Ke=ft;if(!isFinite(Ke.textHeight)){const Ee=de.getRectangleByPoints(Ke.points);Se.setNode(a,{textHeight:Ee.height},[fe])}}})}wt(null),ee.updatePointerType(a,Le.selection),b(ye=>({...ye,pointer:Le.selection}))},[a,Ie,b]);return p.useEffect(()=>{if(!a)return;const ae=te=>{const fe=te.target;if(!(fe.closest(".board-host-svg")||fe.closest(".plait-board-container")))return;if(document.documentElement.classList.contains("slideshow-active")){te.preventDefault(),te.stopPropagation();return}const Ke=Xe(a,Ze(a,te.clientX,te.clientY)),Ee=qi(a,Ke);if(Ee&&Fc(Ee)){Tv(a,Ee,_),te.preventDefault(),te.stopPropagation();return}if(Ee){if(ki(Ee)){te.preventDefault(),te.stopPropagation();return}const ot=Ee.url;if(ot&&typeof ot=="string"){const gt=K.isDrawElement(Ee)&&K.isImage(Ee),pt=Yi(Ee);if(gt||pt){ct(Ee.id),te.preventDefault(),te.stopPropagation();return}}}const ut=fe.closest(".plait-tool-container")||fe.closest(".plait-workzone-container")||fe.closest("foreignObject");if(!Ee&&!ut){const ot=[te.clientX,te.clientY];Ve(ot),oe(!0)}},ye=s.current;return ye&&ye.addEventListener("dblclick",ae),()=>{ye&&ye.removeEventListener("dblclick",ae)}},[a,s,ct,_]),p.useEffect(()=>{if(!a)return;const ae=te=>{const fe=te.target;if(fe.closest(".side-drawer")||fe.closest(".project-drawer")||!(fe.closest(".board-host-svg")||fe.closest(".plait-board-container")))return;const Ke=Xe(a,Ze(a,te.clientX,te.clientY)),Ee=qi(a,Ke);if(Ee&&ki(Ee)&&!rt(Ee)){xe(!0);const ut=hf(Ee);if(ut){te.preventDefault(),te.stopPropagation(),Ro.togglePlaybackInQueue(ut,Kn(a.children),{queueSource:"canvas",queueId:Nc,queueName:Oc}).catch(()=>{});return}}if(F.isPointer(a,ge.text)&&!(fe.closest(".plait-tool-container")||fe.closest(".plait-workzone-container")||fe.closest("foreignObject"))&&!Ee){wt({screenX:te.clientX,screenY:te.clientY,worldPoint:Ke,zoom:a.viewport.zoom}),te.preventDefault(),te.stopPropagation();return}u&&Kv()&&be(!1),l&&fn()&&ue(!1),h&&gn()&&_e(!1)},ye=s.current;return ye&&ye.addEventListener("click",ae),()=>{ye&&ye.removeEventListener("click",ae)}},[a,s,u,l,h,be,ue,_e]),d.jsx("div",{className:me("drawnix",{"drawnix--mobile":r.isMobile}),ref:s,children:d.jsxs("div",{className:"drawnix__main",children:[d.jsxs(tm,{value:e,viewport:t,theme:n,options:o,plugins:i,onChange:ae=>{B&&B(ae)},onSelectionChange:j,onViewportChange:U,onThemeChange:A,onValueChange:I,children:[d.jsx(Xp,{afterInit:ae=>{c(ae),window.__drawnixBoard=ae,k&&k(ae),ae.afterChange&&ae.afterChange()}}),d.jsx(gy,{}),d.jsx(Rw,{projectDrawerOpen:u,onProjectDrawerToggle:O,toolboxDrawerOpen:l,onToolboxDrawerToggle:q,taskPanelExpanded:h,onTaskPanelToggle:R,onOpenBackupRestore:Y,onOpenCloudSync:he,onKnowledgeBaseToggle:le,onOpenMediaLibrary:L,deferredFeaturesEnabled:E,minimizedToolsBarEnabled:C,onEnableToolWindows:D}),ne&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(Vv,{})}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Cv,{})}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Iv,{})}),d.jsx(M0,{}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Av,{})}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Rv,{})}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Mv,{})}),r.openDialogTypes.size>0&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(Bv,{container:s.current})}),r.openSettings&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(Hv,{container:s.current})}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Dv,{container:s.current})}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Ov,{isDataReady:pe,activationKey:0,onEnableToolWindows:D,onEnableRuntime:P})}),X&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(Lv,{position:Fe,visible:X,onClose:()=>oe(!1),onOpenMediaLibrary:L})}),Ie&&d.jsx("div",{ref:Ge,contentEditable:!0,suppressContentEditableWarning:!0,style:{position:"fixed",left:Ie.screenX,top:Ie.screenY-14*Ie.zoom/2,minWidth:"2px",minHeight:"1.5em",outline:"none",border:"none",background:"transparent",fontSize:`${14*Ie.zoom}px`,lineHeight:"1.5",color:"#333",caretColor:"#333",zIndex:1e4,whiteSpace:"pre-wrap",fontFamily:"inherit"},onBlur:mu,onKeyDown:ae=>{ae.key==="Escape"&&wt(null),ae.stopPropagation()}}),Lt&&d.jsx(p.Suspense,{fallback:null,children:d.jsx($v,{visible:Lt,items:Z,initialIndex:se,onClose:lt,showThumbnails:!0,useBuiltInEditor:!0,showEditOverwrite:!0,onEditOverwrite:$t,onEditInsert:wi})}),Vt.visible&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(jv,{visible:Vt.visible,position:Vt.position,currentShape:Vt.currentShape||void 0,onSelectShape:gu,onClose:pu,container:s.current})}),d.jsx(_y,{})]}),d.jsx(p.Suspense,{fallback:null,children:d.jsx(Nv,{ref:x})}),m&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(Fv,{board:a,value:e})}),w&&d.jsx(p.Suspense,{fallback:null,children:d.jsx(zv,{board:a,value:e,containerRef:s,versionUpdateEnabled:S,performancePanelEnabled:v,toolWindowManagerEnabled:E,projectDrawerOpen:u,toolboxDrawerOpen:l,mediaLibraryOpen:f,mediaLibraryConfig:g,backupRestoreOpen:y,cloudSyncOpen:H,onBoardSwitch:T,setProjectDrawerOpen:be,setToolboxDrawerOpen:ue,setMediaLibraryOpen:Ce,setBackupRestoreOpen:ze,setCloudSyncOpen:W,handleOpenMediaLibrary:L,handleBeforeSwitch:Q,onCreateProjectForMemory:V})})]})})};let Oa=!1;const lu="sw-debug-enabled";function Xv(){try{return sessionStorage.getItem(lu)==="true"}catch{return!1}}function Na(e){try{sessionStorage.setItem(lu,e===!0?"true":"false")}catch{}}let zn=Xv();const Xt=[];let kn=null,Ot=0;const oi=15e3,Zv=200,Fn={error:console.error,warn:console.warn,info:console.info,log:console.log,debug:console.debug};function Es(e){return(e.includes("AbortError")||e.includes("The user aborted a request"))&&(e.includes("Failed to execute 'showOpenFilePicker'")||e.includes("Failed to execute 'showSaveFilePicker'")||e.includes("The user aborted a request"))}function Gt(e,t,n){if(t.includes("[SW]")||t.includes("[SWTaskQueue]")||t.includes("[SWChannelManager]")||t.includes("[SWChannelClient]")||t.includes("[ServiceWorkerChannel]")||t.includes("Invalid message structure")||t.includes("posthog.com")||n&&n.includes("posthog")||Es(t)||t.includes("ResizeObserver loop completed with undelivered notifications")||t.includes("ResizeObserver loop limit exceeded"))return;const o=()=>{Ae.isInitialized()&&Ae.reportConsoleLog(e,[{message:t,stack:n||"",source:window.location.href}],Date.now()).catch(()=>{})},i=()=>{for(;Xt.length>0&&Ae.isInitialized();){const r=Xt.shift();r&&Ae.reportConsoleLog(r.level,[{message:r.message,stack:r.stack||"",source:window.location.href}],Date.now()).catch(()=>{})}},s=()=>{const r=Date.now();kn||r<Ot||(kn=Ae.initialize().then(a=>{if(!a){Ot=Date.now()+oi;return}Ot=0,i()}).catch(()=>{Ot=Date.now()+oi}).finally(()=>{kn=null}))};Ae.isInitialized()?o():(Xt.length>=Zv&&Xt.shift(),Xt.push({level:e,message:t,stack:n}),s())}function Bn(e){return e.map(t=>{if(t instanceof Error)return t.message;if(typeof t=="object")try{return JSON.stringify(t)}catch{return String(t)}return String(t)}).join(" ")}function za(e){for(const t of e)if(t instanceof Error&&t.stack)return t.stack;return""}function Jv(){if(Oa||!("serviceWorker"in navigator))return;Oa=!0;const e=()=>{if(Ae.isInitialized())Ae.subscribeToEvent("debug:statusChanged",t=>{const n=t,o=n.enabled??n.debugModeEnabled??!1;zn=o,Na(o)}),Ae.getDebugStatus().then(t=>{const n=t.enabled??t.debugModeEnabled??!1;zn=n,Na(n)});else{const t=Date.now();!kn&&t>=Ot&&(kn=Ae.initialize().then(n=>{if(!n){Ot=Date.now()+oi;return}for(Ot=0;Xt.length>0&&Ae.isInitialized();){const o=Xt.shift();o&&Ae.reportConsoleLog(o.level,[{message:o.message,stack:o.stack||"",source:window.location.href}],Date.now()).catch(()=>{})}}).catch(()=>{Ot=Date.now()+oi}).finally(()=>{kn=null})),setTimeout(e,500)}};e(),console.error=function(...t){Fn.error.apply(console,t),Gt("error",Bn(t),za(t))},console.warn=function(...t){Fn.warn.apply(console,t),Gt("warn",Bn(t),za(t))},console.log=function(...t){Fn.log.apply(console,t),zn&&Gt("log",Bn(t),"")},console.info=function(...t){Fn.info.apply(console,t),zn&&Gt("info",Bn(t),"")},console.debug=function(...t){Fn.debug.apply(console,t),zn&&Gt("debug",Bn(t),"")},window.addEventListener("error",t=>{var o;const n=`${t.message} at ${t.filename}:${t.lineno}:${t.colno}`;Es(n)||Gt("error",n,((o=t.error)==null?void 0:o.stack)||"")}),window.addEventListener("unhandledrejection",t=>{const n=t.reason,o=n instanceof Error?n.message:`Unhandled Promise: ${String(n)}`,i=n instanceof Error&&n.stack||"";Es(o)||Gt("error",o,i)})}const Qv=typeof window<"u"&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),eS=typeof window<"u"?new URLSearchParams(window.location.search).get("sw"):null,uu=eS==="0",du=typeof navigator<"u"&&"serviceWorker"in navigator,hu=du&&!uu;hu&&Jv();et.markLoadingStart();et.checkUrlSafeMode();Yg();const tS="1.0.2",nS=ff(),Fa="_lazy_chunk_retry",oS="_t";function iS(){if(typeof window>"u")return;const e=new URL(window.location.href);if(e.searchParams.has(Fa)){e.searchParams.delete(Fa),e.searchParams.delete(oS);try{window.history.replaceState(window.history.state,"",e.toString())}catch{}}}iS();function fu(e){return e==="jsdelivr"||e==="unpkg"||e==="local"}function sS(){return window.__OPENTU_BOOT__||null}function yn(e){var t,n;(n=(t=sS())==null?void 0:t.setProgress)==null||n.call(t,e==null?void 0:e.progress,e)}function rS(){const e=window.__OPENTU_CDN__||window.__AITU_CDN__;return!e||!fu(e.cdn)?null:{cdn:e.cdn,latency:Number.isFinite(e.latency)&&e.latency>=0?e.latency:0,timestamp:Number.isFinite(e.timestamp)&&e.timestamp>0?e.timestamp:Date.now()}}function Ba(e){const t=rS();if(!t)return;const n={type:"SW_CDN_SET_PREFERENCE",...t,version:tS},o=new Set,i=[navigator.serviceWorker.controller,e==null?void 0:e.active,e==null?void 0:e.waiting,e==null?void 0:e.installing];for(const s of i)s&&o.add(s);o.forEach(s=>{s.postMessage(n)})}function Ha(e){Ba(e);const t=window.__OPENTU_CDN_API__||window.__AITU_CDN_API__;t!=null&&t.selectBestCDN&&t.selectBestCDN().then(n=>{n&&fu(n.cdn)&&(window.__OPENTU_CDN__=n),Ba(e)}).catch(n=>{console.warn("[Main] Failed to sync CDN preference to Service Worker:",n)})}function aS(){navigator.serviceWorker.getRegistration().then(e=>e==null?void 0:e.unregister()).catch(e=>{console.warn("[Main] Disabled service worker cleanup failed:",e)})}function Ao(e,t={}){if(typeof window>"u")return;const{delay:n=0,timeout:o=2e3}=t,i=()=>{const r=window.requestIdleCallback;if(typeof r=="function"){r(e,{timeout:o});return}window.setTimeout(e,Math.min(o,500))},s=()=>{if(n>0){window.setTimeout(i,n);return}i()};window.requestAnimationFrame(()=>{window.requestAnimationFrame(s)})}yn({tip:"正在初始化启动服务...",source:"phase",progress:12});if(typeof window<"u"){ig();const e=()=>{if(window.posthog){pf(nS),og();return}setTimeout(e,300)};Ao(e,{delay:0,timeout:1e3}),Ao(()=>{Zc().catch(n=>{console.warn("[Main] Database cleanup failed:",n)}),lg.runMigration().then(()=>Promise.all([gf(),Ff.initializeAsync()])).catch(n=>{console.warn("[Main] Storage migration/init failed:",n)})},{delay:400,timeout:2500}),Ao(()=>{br.start(),br.logMemoryStatus()},{delay:5e3,timeout:2500});const t=()=>{window.posthog?Zf():setTimeout(t,500)};Ao(t,{delay:1500,timeout:3e3})}du&&uu&&aS();if(hu){const e=Qv;let t=null,n=!1,o=!1,i=null,s=null;const r=m=>{i!==m&&(i=m,window.dispatchEvent(new CustomEvent("sw-update-available",{detail:{version:m}})))},a=m=>{if(m.pendingVersion&&m.pendingVersion!==m.committedVersion&&(m.upgradeState==="ready"||m.upgradeState==="committing")){r(m.pendingVersion);return}m.pendingVersion||(i=null)},c=m=>{const w=m||t||(s==null?void 0:s.waiting)||navigator.serviceWorker.controller||(s==null?void 0:s.active)||null;w&&w.postMessage({type:"GET_VERSION_STATE"})},u=m=>{navigator.serviceWorker.controller||!(m!=null&&m.active)||m.active.postMessage({type:"CLAIM_CLIENTS"})},l=m=>{!n||o||(o=!0,setTimeout(()=>{co()},1e3))},h=async()=>{const m=[t,s==null?void 0:s.waiting];try{const w=await navigator.serviceWorker.getRegistration()||null;w&&(s=w,m.push(w.waiting))}catch(w){console.warn("[Main] Failed to get live service worker registration:",w)}try{const w=await navigator.serviceWorker.ready;m.push(w.waiting)}catch(w){console.warn("[Main] Failed to inspect ready service worker registration:",w)}for(const w of m)if(!(!w||w.state==="redundant")&&w!==navigator.serviceWorker.controller)return t=w,w;return null},f=window.__OPENTU_SW_REGISTRATION_PROMISE__||navigator.serviceWorker.register("./sw.js").catch(m=>(console.warn("[Main] Service worker registration failed:",m),null));window.__OPENTU_SW_REGISTRATION_PROMISE__=f,f.then(m=>{if(!m){yn({tip:"离线加速未启用,正在直接启动工作台...",source:"phase",progress:70});return}s=m,u(m),navigator.serviceWorker.ready.then(u).catch(w=>{console.warn("[Main] Service worker ready check failed:",w)}),yn({tip:"启动缓存服务已连接,正在准备资源清单...",source:"phase",progress:72}),Ha(m),e?(m.update().catch(w=>console.warn("Forced update check failed:",w)),m.waiting&&m.waiting.postMessage({type:"FORCE_UPGRADE"})):m.waiting&&navigator.serviceWorker.controller&&(t=m.waiting,c(m.waiting)),m.addEventListener("updatefound",()=>{const w=m.installing;w&&w.addEventListener("statechange",()=>{w.state==="installed"&&navigator.serviceWorker.controller&&(t=w,e?w.postMessage({type:"FORCE_UPGRADE"}):(c(w),setTimeout(()=>c(w),5e3)))})}),m.active&&!m.installing&&!m.waiting&&yn({tip:"启动缓存服务已就绪,正在恢复工作台状态...",source:"phase",progress:78}),c(),setInterval(()=>{m.update().catch(w=>{console.warn("Update check failed:",w)})},300*1e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&c()})}).catch(m=>{yn({tip:"离线加速未启用,正在直接启动工作台...",source:"phase",progress:70})});const g=()=>{if(!Ae.isInitialized()){setTimeout(g,500);return}Ae.setEventHandlers({onSWUpdated:m=>{c()},onSWNewVersionReady:m=>{r(m.version),c()},onSWActivated:m=>{if(n){l();return}t=null,c()}}),s!=null&&s.waiting&&navigator.serviceWorker.controller&&(t=s.waiting,c(s.waiting))};setTimeout(g,1e3);const y=async()=>{if(!Ae.isInitialized()){setTimeout(y,500);return}Ae.registerVideoThumbnailHandler(async(m,w)=>{try{const{generateVideoThumbnailFromBlob:S}=await re(async()=>{const{generateVideoThumbnailFromBlob:H}=await import("./ai-chat-BnWVpTEI.js").then(B=>B.sH);return{generateVideoThumbnailFromBlob:H}},__vite__mapDeps([0]),import.meta.url);let v=null;const C=await(await caches.open("drawnix-images")).match(m);if(C&&(v=await C.blob()),!v&&(m.startsWith("http://")||m.startsWith("https://")))try{const H=await fetch(m);H.ok&&(v=await H.blob())}catch{v=null}if(!v)return{error:"Video not found in cache or network"};const D=await S(v,w||400);return{thumbnailUrl:await new Promise((H,B)=>{const j=new FileReader;j.onloadend=()=>H(j.result),j.onerror=B,j.readAsDataURL(D)})}}catch(S){return{error:S instanceof Error?S.message:String(S)}}})};y(),navigator.serviceWorker.addEventListener("message",m=>{var w;((w=m.data)==null?void 0:w.type)==="SW_VERSION_STATE"&&a(m.data)}),navigator.serviceWorker.addEventListener("controllerchange",()=>{Ha(s),c(),l()}),window.addEventListener("user-confirmed-upgrade",()=>{(async()=>{const m=await h();if(!m){console.warn("[Main] No waiting service worker available for COMMIT_UPGRADE"),c(),s==null||s.update().catch(w=>{console.warn("[Main] Update check after missing waiting worker failed:",w)});return}n=!0,m.postMessage({type:"COMMIT_UPGRADE"})})()})}yn({tip:"正在挂载工作台界面...",source:"phase",progress:88});const cS=mo.createRoot(document.getElementById("root"));cS.render(d.jsx(p.StrictMode,{children:d.jsx(Zg,{children:d.jsx(sp,{})})}));const vS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{Dl as A,Xp as B,yS as D,Ml as F,an as I,kt as S,tm as W,og as a,ig as b,et as c,Kc as d,$f as e,Vf as f,Ye as g,pS as h,Zf as i,Pv as j,mS as k,gS as l,Yc as m,wS as n,Tv as o,zw as p,Fw as q,Zc as r,lg as s,nn as t,qf as u,Rl as v,Um as w,Vy as x,fS as y,vS as z};
|