aitu-app 0.6.63 → 0.6.64
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-Du5kXrAd.js → CanvasAudioPlayer-B2W5__ni.js} +1 -1
- package/assets/{ChatDrawer-CqZHx7x_.js → ChatDrawer-M1q92KNU.js} +2 -2
- package/assets/{ChatMessagesArea-AG3RXe34.js → ChatMessagesArea-D9LNDmbK.js} +2 -2
- package/assets/{DeferredAIInputBar-CNAPl6C2.js → DeferredAIInputBar-CKhI8Jhd.js} +2 -2
- package/assets/{DrawnixDeferredFeatures-BrhbEEBa.js → DrawnixDeferredFeatures-DxyxvT2y.js} +1 -1
- package/assets/{KnowledgeBaseContent-3hE8vBra.js → KnowledgeBaseContent-C_JxGQXg.js} +3 -3
- package/assets/{MVCreator-2NIxaaSL.js → MVCreator-DOt6pxq2.js} +1 -1
- package/assets/{ModelBenchmarkWorkbench-CacNyFbi.js → ModelBenchmarkWorkbench-3j77ocpe.js} +1 -1
- package/assets/{ModelDropdown-3MjTl1AO.js → ModelDropdown-CHYgRb1r.js} +1 -1
- package/assets/{MusicAnalyzer-Mmu92A4Y.js → MusicAnalyzer-BTXks5oV.js} +1 -1
- package/assets/{MusicAnalyzer-Drf2j8jn.js → MusicAnalyzer-Dr-DPePj.js} +1 -1
- package/assets/{ResizableDivider-B_67th7H.js → ResizableDivider-P1jpoJ3i.js} +1 -1
- package/assets/{TaskQueuePanel-VfjKIooN.js → TaskQueuePanel-D6NtMAbm.js} +1 -1
- package/assets/{VideoAnalyzer-DNWjNcIx.js → VideoAnalyzer-BHZMqLIa.js} +1 -1
- package/assets/{ai-generation-preferences-service-Ch1XhjkZ.js → ai-generation-preferences-service-CabuQA69.js} +1 -1
- package/assets/{arc-DE4qRd9D.js → arc-BajUk0_Z.js} +1 -1
- package/assets/{arc-DJ5Mb9x1.js → arc-Z9PGo_2L.js} +1 -1
- package/assets/{batch-image-generation-Bk8HSFol.js → batch-image-generation-RKz5tz-Y.js} +1 -1
- package/assets/{blockDiagram-38ab4fdb-B62iB8ti.js → blockDiagram-38ab4fdb-BsEJDcLK.js} +1 -1
- package/assets/{blockDiagram-38ab4fdb-D2MnfN1Q.js → blockDiagram-38ab4fdb-Cfmk3_6A.js} +1 -1
- package/assets/{c4Diagram-3d4e48cf-CgUaipiZ.js → c4Diagram-3d4e48cf-D2OyfHpd.js} +1 -1
- package/assets/{c4Diagram-3d4e48cf-DHV35ltP.js → c4Diagram-3d4e48cf-K-ewbsK1.js} +1 -1
- package/assets/{canvas-insertion-ZEZkcXvB.js → canvas-insertion-CYbFgP4L.js} +1 -1
- package/assets/channel-6DAc0JPc.js +1 -0
- package/assets/channel-WrMsNCbC.js +1 -0
- package/assets/{classDiagram-70f12bd4-C6X-VZXt.js → classDiagram-70f12bd4-BGEF352u.js} +1 -1
- package/assets/{classDiagram-70f12bd4-OH5sF1K-.js → classDiagram-70f12bd4-Gn3MZjEL.js} +1 -1
- package/assets/{classDiagram-v2-f2320105-otk4V9KH.js → classDiagram-v2-f2320105-C_aAfIgL.js} +1 -1
- package/assets/{classDiagram-v2-f2320105-D1I5s2af.js → classDiagram-v2-f2320105-DYPMFlcT.js} +1 -1
- package/assets/{clipper-BWlMmsTH.js → clipper-ByL4oIbZ.js} +1 -1
- package/assets/clone-keJVIubx.js +1 -0
- package/assets/{createText-2e5e7dd3-DuiUpOXV.js → createText-2e5e7dd3-C0UgSBh5.js} +1 -1
- package/assets/{createText-2e5e7dd3-D78Dn_q8.js → createText-2e5e7dd3-CoA6JNKB.js} +1 -1
- package/assets/{edges-e0da2a9e-Br3GgeJK.js → edges-e0da2a9e-DmyL0L_b.js} +1 -1
- package/assets/{edges-e0da2a9e-Dio4S9-4.js → edges-e0da2a9e-qdTreft0.js} +1 -1
- package/assets/{erDiagram-9861fffd-BYkBBs0M.js → erDiagram-9861fffd-Bjyf78Da.js} +1 -1
- package/assets/{erDiagram-9861fffd-DuZccGHy.js → erDiagram-9861fffd-DYWtVkXG.js} +1 -1
- package/assets/{flowDb-956e92f1-BvHxN76x.js → flowDb-956e92f1-Clfuqh48.js} +1 -1
- package/assets/{flowDb-956e92f1-D6cTY_st.js → flowDb-956e92f1-vnfymslR.js} +1 -1
- package/assets/{flowDiagram-66a62f08-Bh5LanWu.js → flowDiagram-66a62f08-54OX2XOH.js} +1 -1
- package/assets/{flowDiagram-66a62f08-rCNbZEwY.js → flowDiagram-66a62f08-lS8fOa4T.js} +1 -1
- package/assets/flowDiagram-v2-96b9c2cf-Bw7qAcFu.js +1 -0
- package/assets/flowDiagram-v2-96b9c2cf-DGyrUMgR.js +1 -0
- package/assets/{flowchart-elk-definition-4a651766-llVLlxyE.js → flowchart-elk-definition-4a651766-CXdElD40.js} +1 -1
- package/assets/{flowchart-elk-definition-4a651766-CIShIr5E.js → flowchart-elk-definition-4a651766-D4UghemK.js} +1 -1
- package/assets/{ganttDiagram-c361ad54-j2pPvoOi.js → ganttDiagram-c361ad54-Bl7rQCLW.js} +1 -1
- package/assets/{ganttDiagram-c361ad54-CUtUP4cJ.js → ganttDiagram-c361ad54-CwAjbWcn.js} +1 -1
- package/assets/{gitGraphDiagram-72cf32ee-hQmVrZTT.js → gitGraphDiagram-72cf32ee-B-ykaDuR.js} +1 -1
- package/assets/{gitGraphDiagram-72cf32ee-BijhDF7a.js → gitGraphDiagram-72cf32ee-ChvlaDvG.js} +1 -1
- package/assets/{graph-CVdXivUk.js → graph-Bq1HvHkL.js} +1 -1
- package/assets/{graph-iERr38Mn.js → graph-DM094zt_.js} +1 -1
- package/assets/{index-3862675e-BCU8UapW.js → index-3862675e-CA0xjB9W.js} +1 -1
- package/assets/{index-3862675e-BdD6mhWW.js → index-3862675e-DGrSmeWu.js} +1 -1
- package/assets/{index-CxqCKbLy.js → index-AFp_qpAI.js} +1 -1
- package/assets/{index-q02ppfIX.js → index-B4dceFKj.js} +1 -1
- package/assets/{index-BmNN2uGW.js → index-B67KSDhv.js} +1 -1
- package/assets/{index-ByxyNkwM.js → index-BC221_MJ.js} +1 -1
- package/assets/{index-nPSeKWRU.js → index-BGFWA6Zt.js} +1 -1
- package/assets/{index-DCjrDHEd.js → index-BH3jS3gm.js} +1 -1
- package/assets/{index-B-bas2QJ.js → index-BKTLxghO.js} +1 -1
- package/assets/{index-CW9BeyEu.js → index-Bks4xBST.js} +1 -1
- package/assets/{index-CvlBHvN3.js → index-BmEFRKV7.js} +1 -1
- package/assets/{index-DuFyvKRm.js → index-C3h-b0UN.js} +1 -1
- package/assets/{index-CmOEsqBQ.js → index-C5Onm0uO.js} +1 -1
- package/assets/{index-DYtXgeSz.js → index-CGelrSXy.js} +1 -1
- package/assets/{index-vw8fjMik.js → index-CKBsqCzR.js} +1 -1
- package/assets/{index-DjGrNkrV.js → index-CKjzms_e.js} +1 -1
- package/assets/{index-CxUWaNUo.js → index-CMLI8gQy.js} +1 -1
- package/assets/{index-CkjuY786.js → index-CVEllvWf.js} +1 -1
- package/assets/{index-BUZUbTWS.js → index-CW_ala_3.js} +1 -1
- package/assets/{index-BxdH1-er.js → index-Ci5Z3DWY.js} +1 -1
- package/assets/{index-BeRhCeQu.js → index-CtNjfEqK.js} +1 -1
- package/assets/{index-BakDREx4.js → index-CvbEsbIE.js} +1 -1
- package/assets/{index-BnaNWg7x.js → index-DM-iV9Y8.js} +2 -2
- package/assets/{index-DMfHKITi.js → index-DTqVJVfv.js} +1 -1
- package/assets/{index-BdSFouqR.js → index-DZtf3zC8.js} +1 -1
- package/assets/{index-ByECpktB.js → index-D_LadtY8.js} +1 -1
- package/assets/{index-UeGDfQIX.js → index-DiSWR48t.js} +1 -1
- package/assets/{index-D0O0qYML.js → index-DsFroXrj.js} +1 -1
- package/assets/{index-BN7eABQE.js → index-DxqCsnoj.js} +1 -1
- package/assets/{index-B_eFETCZ.js → index-Jvh12pKI.js} +1 -1
- package/assets/{index-CMQMxwMb.js → index-gHdnUGOu.js} +3 -3
- package/assets/{index-CE0NChcB.js → index-kKjFXTNL.js} +1 -1
- package/assets/{index-D4R9cQ86.js → index-v1v0x1ci.js} +3 -3
- package/assets/{infoDiagram-f8f76790-Cmv7jbWa.js → infoDiagram-f8f76790-C-wYgjah.js} +1 -1
- package/assets/{infoDiagram-f8f76790-D0DSz5Ue.js → infoDiagram-f8f76790-Cu-3eq4R.js} +1 -1
- package/assets/{journeyDiagram-49397b02-D6HU8bXU.js → journeyDiagram-49397b02-BG8aYQK6.js} +1 -1
- package/assets/{journeyDiagram-49397b02-Db00D03K.js → journeyDiagram-49397b02-DXPaY9vn.js} +1 -1
- package/assets/{layout-CPj4wl_r.js → layout-DvIBYRXu.js} +1 -1
- package/assets/{layout-DGJFFi9s.js → layout-SoDWNnQD.js} +1 -1
- package/assets/{line-D_WC7vRh.js → line-Bxc-zIvZ.js} +1 -1
- package/assets/{line-CpXi5g86.js → line-CFFXuH78.js} +1 -1
- package/assets/{linear-n85WiAhX.js → linear-BF0xIQKP.js} +1 -1
- package/assets/{linear-UpmxQM2f.js → linear-DQ3XkjOP.js} +1 -1
- package/assets/{main-DX4kRYQX.js → main-8GBlYJSO.js} +8 -8
- package/assets/{mermaid.core-N7WwfYcf.js → mermaid.core-BGyfnsLl.js} +3 -3
- package/assets/{mindmap-definition-fc14e90a-C8U6pdZ2.js → mindmap-definition-fc14e90a-CrYWIUXi.js} +1 -1
- package/assets/{mindmap-definition-fc14e90a-D2hbUBx2.js → mindmap-definition-fc14e90a-DOkI3ebm.js} +1 -1
- package/assets/{model-benchmark-launcher-BrOG9Vlm.js → model-benchmark-launcher-DtJmU6Wc.js} +1 -1
- package/assets/{model-benchmark-service-DDklUBjC.js → model-benchmark-service-B0QCqInK.js} +1 -1
- package/assets/{model-selection-BaH65gMK.js → model-selection-CbzU26xQ.js} +1 -1
- package/assets/{photo-wall-splitter-QuaIbsZ1.js → photo-wall-splitter-BPzdMtA1.js} +1 -1
- package/assets/{pieDiagram-8a3498a8-BPHw5PxR.js → pieDiagram-8a3498a8-ChLZxjKv.js} +1 -1
- package/assets/{pieDiagram-8a3498a8-DKV5uwrs.js → pieDiagram-8a3498a8-DAWd9-jL.js} +1 -1
- package/assets/{quadrantDiagram-120e2f19-pe-wI-U4.js → quadrantDiagram-120e2f19-CBBovNE2.js} +1 -1
- package/assets/{quadrantDiagram-120e2f19-DQdaeBYM.js → quadrantDiagram-120e2f19-DSvfgE7I.js} +1 -1
- package/assets/{requirementDiagram-deff3bca-DYepoptc.js → requirementDiagram-deff3bca-De51fyhT.js} +1 -1
- package/assets/{requirementDiagram-deff3bca-QX4OaNTO.js → requirementDiagram-deff3bca-ke6SiEw1.js} +1 -1
- package/assets/{sankeyDiagram-04a897e0-DJkKTFXr.js → sankeyDiagram-04a897e0-BxiqkhtK.js} +1 -1
- package/assets/{sankeyDiagram-04a897e0-1bYf2R8i.js → sankeyDiagram-04a897e0-Clr8_HiZ.js} +1 -1
- package/assets/{sequenceDiagram-704730f1-B52OA1Y3.js → sequenceDiagram-704730f1-Bc8zPHLG.js} +1 -1
- package/assets/{sequenceDiagram-704730f1-B4QsYTCd.js → sequenceDiagram-704730f1-BfBUJmAu.js} +1 -1
- package/assets/{settings-dialog-Bueh6yYA.js → settings-dialog-C9BMj8Zj.js} +1 -1
- package/assets/{skill-dsl-parser-CPpdtdC1.js → skill-dsl-parser-BxkJ9Ixc.js} +1 -1
- package/assets/{stateDiagram-587899a1-D221rMST.js → stateDiagram-587899a1-DAil8S_m.js} +1 -1
- package/assets/{stateDiagram-587899a1-X7bhoHKe.js → stateDiagram-587899a1-Vop8VRn5.js} +1 -1
- package/assets/{stateDiagram-v2-d93cdb3a-D9VdRPIN.js → stateDiagram-v2-d93cdb3a-8b1lkei5.js} +1 -1
- package/assets/{stateDiagram-v2-d93cdb3a-CGMASaM9.js → stateDiagram-v2-d93cdb3a-BHm8pPuv.js} +1 -1
- package/assets/{styles-6aaf32cf-D_xcN1dm.js → styles-6aaf32cf-BlD8JxQr.js} +1 -1
- package/assets/{styles-6aaf32cf-DHTzglnJ.js → styles-6aaf32cf-C4CEUYqK.js} +1 -1
- package/assets/{styles-9a916d00-w5Yn3LRO.js → styles-9a916d00-C6tkW5rH.js} +1 -1
- package/assets/{styles-9a916d00-BVoYXPeR.js → styles-9a916d00-Oss0YMv5.js} +1 -1
- package/assets/{styles-c10674c1-xX_gtHzZ.js → styles-c10674c1-D4YQTLGD.js} +1 -1
- package/assets/{styles-c10674c1-C3cgfc7I.js → styles-c10674c1-D6N_fge5.js} +1 -1
- package/assets/{svgDrawCommon-08f97a94-DFof-iml.js → svgDrawCommon-08f97a94-BOSx1sQS.js} +1 -1
- package/assets/{svgDrawCommon-08f97a94-DxU2UGYh.js → svgDrawCommon-08f97a94-RZvmFGZL.js} +1 -1
- package/assets/{timeline-definition-85554ec2-CzV_JohE.js → timeline-definition-85554ec2-BL5y0l6c.js} +1 -1
- package/assets/{timeline-definition-85554ec2-FPml3o0r.js → timeline-definition-85554ec2-BY6Jx-ZP.js} +1 -1
- package/assets/{tool-windows-hjm6YiPY.js → tool-windows-C4D0lII2.js} +137 -137
- package/assets/{ttd-dialog-CqISZ7cy.js → ttd-dialog-qD0QkDID.js} +4 -4
- package/assets/{use-runtime-models-C0uyCfar.js → use-runtime-models-BLwgp0M1.js} +1 -1
- package/assets/{useCharacters-BGdX9007.js → useCharacters-945b6dqW.js} +1 -1
- package/assets/{useWorkflowSubmission-BmFQdWt3.js → useWorkflowSubmission-Z0u0KCNN.js} +2 -2
- package/assets/{video-analyze-DszumYAr.js → video-analyze-Co9na7Gr.js} +1 -1
- package/assets/{video-generation-DEL-kJgF.js → video-generation-x2UMMPYg.js} +1 -1
- package/assets/{video-recovery-service-C9y_bfU1.js → video-recovery-service-BsV5nlEP.js} +1 -1
- package/assets/{workflow-generation-utils-Da12qXTb.js → workflow-generation-utils-CZULSJWQ.js} +2 -2
- package/assets/{workflow-submission-service-BuFuRV_m.js → workflow-submission-service-C-eCWm_8.js} +1 -1
- package/assets/{xychartDiagram-e933f94c-C41tCiSk.js → xychartDiagram-e933f94c-CNjZprqQ.js} +1 -1
- package/assets/{xychartDiagram-e933f94c-HanO46iU.js → xychartDiagram-e933f94c-DjIBec-i.js} +1 -1
- package/changelog.json +16 -0
- package/idle-prefetch-manifest.json +6 -6
- package/manifest.json +3 -3
- package/package.json +1 -1
- package/precache-manifest.json +304 -304
- package/sw.js +5 -5
- package/version.json +7 -3
- package/assets/channel-B5QZCgOy.js +0 -1
- package/assets/channel-CU3dhzIS.js +0 -1
- package/assets/clone-BAOxFbud.js +0 -1
- package/assets/flowDiagram-v2-96b9c2cf-BEdEe3Ip.js +0 -1
- package/assets/flowDiagram-v2-96b9c2cf-CVItVSoD.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./tool-windows-Cos6lOhr.css","./MediaLibrarySidebar-CNCXXhfY.css","./useCharacters-BJLEgDAP.css","./character-Bo9jcTNu.css","./use-runtime-models-BgWWl4Ng.css","./index-I7GscWS1.css","./ModelDropdown-CQTTHEI7.css","./ai-generation-preferences-service-CeFIqZqn.css","./prompt-optimize-dialog-DLdL2_a1.css","./DeferredAIInputBar-BmPgFhXr.css","./ChatDrawer-0jNvKIoI.css","./DrawnixDeferredFeatures-BBiW9_Pn.css","./ResizableDivider-ClzYJk-6.css","./ttd-dialog-BlUvpMr5.css","./settings-dialog-CdRrvvi_.css","./CanvasAudioPlayer-mm7y75Ol.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as f,B as eu,P as z,a as g0,h as m0,s as tu,W as pa,t as Gt,b as zt,g as S0,d as Ka,i as vf,c as qs,u as no,e as b0,f as y0,k as w0,l as fe,Z as T0,m as nu,n as iu,I as su,o as ru,p as v0,q as ou,K as au,v as x0,w as Ya,x as qa,y as l,z as q,H as E0,A as _0,C as C0,D as P0,E as ko,T as lu,R as vn,F as cu,G as Ao,J as io,M as k0,L as A0,N as Bi,O as M0,Q as I0,S as xf,U as He,V as Qi,X as uu,Y as D0,$ as N0,a0 as R0,a1 as j0,a2 as L0,a3 as O0,a4 as B0,a5 as H0,a6 as F0,a7 as G0,a8 as z0,a9 as V0,aa as U0,ab as W0,ac as $0,ad as X0,ae as ga,af as wr,ag as K0,ah as Y0,ai as ge,aj as q0,ak as Z0,al as oe,am as Q0,an as du,ao as hu,ap as J0,aq as fu,ar as eS,as as Nn,at as bi,au as tS,av as nS,aw as Gl,ax as iS,ay as sS,az as Ef,aA as Zs,aB as Qs,aC as Za,aD as tn,aE as rS,aF as oS,aG as aS,aH as Mo,aI as Gn,aJ as zn,aK as Vn,aL as cn,aM as _f,aN as os,aO as zl,aP as ue,aQ as Vl,aR as gs,aS as ms,aT as Mt,aU as lS,aV as _i,aW as Cf,aX as Pf,aY as Qn,aZ as _t,a_ as It,a$ as xe,b0 as Ji,b1 as Rn,b2 as at,b3 as lt,b4 as ne,b5 as ct,b6 as Ci,b7 as Dt,b8 as Ee,b9 as Pn,ba as Io,bb as Jn,bc as kf,bd as Af,be as Mf,bf as cS,bg as uS,bh as If,bi as Df,bj as Gr,bk as Do,bl as pu,bm as No,bn as xn,bo as At,_ as Ne,bp as Nf,bq as dS,br as hS,bs as fS,bt as Ro,bu as jo,bv as Rf,bw as Ul,bx as ni,by as jf,bz as Js,bA as pS,bB as gS,bC as Je,bD as Lo,bE as Ft,bF as mS,bG as SS,bH as bS,bI as Ti,bJ as V,bK as Xe,bL as Ut,bM as yS,bN as es,bO as wS,bP as Hi,bQ as TS,bR as vS,bS as Wl,bT as gu,bU as xS,bV as Ct,bW as ES,bX as _S,bY as CS,bZ as PS,b_ as kS,b$ as AS,c0 as MS,c1 as IS,c2 as on,c3 as DS,c4 as NS,c5 as RS,c6 as jS,c7 as LS,c8 as OS,c9 as BS,ca as ts,cb as HS,cc as FS,cd as GS,ce as zS,cf as Tn,cg as VS,ch as US,ci as WS,cj as $S,ck as XS,cl as KS,cm as YS,cn as mu,co as Su,cp as Tr,cq as qS,cr as ZS,cs as vr,ct as Lf,cu as QS,cv as JS,cw as eb,cx as tb,cy as nb,cz as $l,cA as Xl,cB as Of,cC as Kl,cD as wn,cE as Yl,cF as Kn,cG as bu,cH as xr,cI as Os,cJ as er,cK as ib,cL as sb,cM as yu,cN as rb,cO as ob,cP as ab,cQ as lb,cR as cb,cS as ub,cT as wu,cU as Bf,cV as db,cW as Tu,cX as ln,cY as Oo,cZ as Bo,c_ as hb,c$ as fb,d0 as pb,d1 as gb,d2 as mb,d3 as Sb,d4 as bb,d5 as yb,d6 as wb,d7 as ii,d8 as Pi,d9 as Tb,da as vu,db as Qa,dc as Hf,dd as Ff,de as vb,df as xb,dg as Eb,dh as _b,di as so,dj as ql,dk as Gf,dl as Cb,dm as Pb,dn as zf,dp as kb,dq as Vf,dr as Ab,ds as Ho,dt as Uf,du as Mb,dv as Ib,dw as Zl,dx as Db,dy as Nb,dz as Wf,dA as zr,dB as Rb,dC as jb,dD as Lb,dE as Ob,dF as Bb,dG as Hb,dH as Fb,dI as Gb,dJ as pi,dK as $f,dL as Fo,dM as Jt,dN as Xf,dO as Kf,dP as zb,dQ as Yf,dR as Ql,dS as qf,dT as Zf,dU as Vb,dV as Ub,dW as Wb,dX as $b,dY as Xb,dZ as Ja,d_ as Kb,d$ as Yb,e0 as Jl,e1 as Bn,e2 as tt,e3 as ot,e4 as Ss,e5 as qb,e6 as Zb,e7 as Qb,e8 as Qf,e9 as ht,ea as Et,eb as Pe,ec,ed as Jf,ee as ep,ef as tp,eg as np,eh as ip,ei as sp,ej as rp,ek as En,el as Jb,em as ey,en as ty,eo as vt,ep as tr,eq as ki,er as ny,es as tc,et as Go,eu as op,ev as nc,ew as ap,ex as lp,ey as cp,ez as up,eA as ic,eB as sc,eC as rc,eD as ro,eE as dp,eF as hp,eG as fp,eH as iy,eI as pp,eJ as sy,eK as ry,eL as oy,eM as ay,eN as ly,eO as cy,eP as uy,eQ as zo,eR as xu,eS as dy,eT as hy,eU as fy,eV as gp,eW as yn,eX as oc,eY as py,eZ as Bt,e_ as ac,e$ as mp,f0 as Sp,f1 as bp,f2 as Vo,f3 as lc,f4 as cc,f5 as el,f6 as si,f7 as Eu,f8 as yp,f9 as wp,fa as Tp,fb as vp,fc as Di,fd as bs,fe as Ni,ff as Uo,fg as pr,fh as ci,fi as _u,fj as tl,fk as gy,fl as my,fm as xp,fn as Sy,fo as by,fp as yy,fq as Ep,fr as _p,fs as wy,ft as Wo,fu as Cu,fv as Ty,fw as vy,fx as Pu,fy as ku,fz as xy,fA as Ey,fB as _y,fC as Cy,fD as Au,fE as Py,fF as oo,fG as Cp,fH as Pp,fI as ky,fJ as Ay,fK as My,fL as Iy,fM as Dy,fN as Ny,fO as Ry,fP as jy,fQ as ma,fR as Yt,fS as Ly,fT as Oy,fU as By,fV as Er,fW as Fi,fX as Gi,fY as Hy,fZ as Fy,f_ as Gy,f$ as zy,g0 as kp,g1 as Vy,g2 as Uy,g3 as Wy,g4 as $y,g5 as Xy,g6 as uc,g7 as nr,g8 as ir,g9 as Ap,ga as Ky,gb as ft,gc as ao,gd as Mp,ge as Ip,gf as Dp,gg as Yy,gh as qy,gi as Mu,gj as Zy,gk as vi,gl as Qy,gm as Jy,gn as ew,go as tw,gp as nw,gq as iw,gr as sw,gs as rw,gt as ow,gu as aw,gv as lw,gw as cw,gx as uw,gy as dw,gz as hw,gA as fw,gB as pw,gC as gw,gD as mw,gE as Sw,gF as Iu,gG as Sa,gH as ba,gI as bw,gJ as Np,gK as yw,gL as nl,gM as bn,gN as Rp,gO as jp,gP as $o,gQ as St,gR as jn,gS as ww,gT as Tw,gU as zi,gV as vw,gW as xw,gX as Du,gY as Ew}from"./tool-windows-
|
|
2
|
+
import{r as f,B as eu,P as z,a as g0,h as m0,s as tu,W as pa,t as Gt,b as zt,g as S0,d as Ka,i as vf,c as qs,u as no,e as b0,f as y0,k as w0,l as fe,Z as T0,m as nu,n as iu,I as su,o as ru,p as v0,q as ou,K as au,v as x0,w as Ya,x as qa,y as l,z as q,H as E0,A as _0,C as C0,D as P0,E as ko,T as lu,R as vn,F as cu,G as Ao,J as io,M as k0,L as A0,N as Bi,O as M0,Q as I0,S as xf,U as He,V as Qi,X as uu,Y as D0,$ as N0,a0 as R0,a1 as j0,a2 as L0,a3 as O0,a4 as B0,a5 as H0,a6 as F0,a7 as G0,a8 as z0,a9 as V0,aa as U0,ab as W0,ac as $0,ad as X0,ae as ga,af as wr,ag as K0,ah as Y0,ai as ge,aj as q0,ak as Z0,al as oe,am as Q0,an as du,ao as hu,ap as J0,aq as fu,ar as eS,as as Nn,at as bi,au as tS,av as nS,aw as Gl,ax as iS,ay as sS,az as Ef,aA as Zs,aB as Qs,aC as Za,aD as tn,aE as rS,aF as oS,aG as aS,aH as Mo,aI as Gn,aJ as zn,aK as Vn,aL as cn,aM as _f,aN as os,aO as zl,aP as ue,aQ as Vl,aR as gs,aS as ms,aT as Mt,aU as lS,aV as _i,aW as Cf,aX as Pf,aY as Qn,aZ as _t,a_ as It,a$ as xe,b0 as Ji,b1 as Rn,b2 as at,b3 as lt,b4 as ne,b5 as ct,b6 as Ci,b7 as Dt,b8 as Ee,b9 as Pn,ba as Io,bb as Jn,bc as kf,bd as Af,be as Mf,bf as cS,bg as uS,bh as If,bi as Df,bj as Gr,bk as Do,bl as pu,bm as No,bn as xn,bo as At,_ as Ne,bp as Nf,bq as dS,br as hS,bs as fS,bt as Ro,bu as jo,bv as Rf,bw as Ul,bx as ni,by as jf,bz as Js,bA as pS,bB as gS,bC as Je,bD as Lo,bE as Ft,bF as mS,bG as SS,bH as bS,bI as Ti,bJ as V,bK as Xe,bL as Ut,bM as yS,bN as es,bO as wS,bP as Hi,bQ as TS,bR as vS,bS as Wl,bT as gu,bU as xS,bV as Ct,bW as ES,bX as _S,bY as CS,bZ as PS,b_ as kS,b$ as AS,c0 as MS,c1 as IS,c2 as on,c3 as DS,c4 as NS,c5 as RS,c6 as jS,c7 as LS,c8 as OS,c9 as BS,ca as ts,cb as HS,cc as FS,cd as GS,ce as zS,cf as Tn,cg as VS,ch as US,ci as WS,cj as $S,ck as XS,cl as KS,cm as YS,cn as mu,co as Su,cp as Tr,cq as qS,cr as ZS,cs as vr,ct as Lf,cu as QS,cv as JS,cw as eb,cx as tb,cy as nb,cz as $l,cA as Xl,cB as Of,cC as Kl,cD as wn,cE as Yl,cF as Kn,cG as bu,cH as xr,cI as Os,cJ as er,cK as ib,cL as sb,cM as yu,cN as rb,cO as ob,cP as ab,cQ as lb,cR as cb,cS as ub,cT as wu,cU as Bf,cV as db,cW as Tu,cX as ln,cY as Oo,cZ as Bo,c_ as hb,c$ as fb,d0 as pb,d1 as gb,d2 as mb,d3 as Sb,d4 as bb,d5 as yb,d6 as wb,d7 as ii,d8 as Pi,d9 as Tb,da as vu,db as Qa,dc as Hf,dd as Ff,de as vb,df as xb,dg as Eb,dh as _b,di as so,dj as ql,dk as Gf,dl as Cb,dm as Pb,dn as zf,dp as kb,dq as Vf,dr as Ab,ds as Ho,dt as Uf,du as Mb,dv as Ib,dw as Zl,dx as Db,dy as Nb,dz as Wf,dA as zr,dB as Rb,dC as jb,dD as Lb,dE as Ob,dF as Bb,dG as Hb,dH as Fb,dI as Gb,dJ as pi,dK as $f,dL as Fo,dM as Jt,dN as Xf,dO as Kf,dP as zb,dQ as Yf,dR as Ql,dS as qf,dT as Zf,dU as Vb,dV as Ub,dW as Wb,dX as $b,dY as Xb,dZ as Ja,d_ as Kb,d$ as Yb,e0 as Jl,e1 as Bn,e2 as tt,e3 as ot,e4 as Ss,e5 as qb,e6 as Zb,e7 as Qb,e8 as Qf,e9 as ht,ea as Et,eb as Pe,ec,ed as Jf,ee as ep,ef as tp,eg as np,eh as ip,ei as sp,ej as rp,ek as En,el as Jb,em as ey,en as ty,eo as vt,ep as tr,eq as ki,er as ny,es as tc,et as Go,eu as op,ev as nc,ew as ap,ex as lp,ey as cp,ez as up,eA as ic,eB as sc,eC as rc,eD as ro,eE as dp,eF as hp,eG as fp,eH as iy,eI as pp,eJ as sy,eK as ry,eL as oy,eM as ay,eN as ly,eO as cy,eP as uy,eQ as zo,eR as xu,eS as dy,eT as hy,eU as fy,eV as gp,eW as yn,eX as oc,eY as py,eZ as Bt,e_ as ac,e$ as mp,f0 as Sp,f1 as bp,f2 as Vo,f3 as lc,f4 as cc,f5 as el,f6 as si,f7 as Eu,f8 as yp,f9 as wp,fa as Tp,fb as vp,fc as Di,fd as bs,fe as Ni,ff as Uo,fg as pr,fh as ci,fi as _u,fj as tl,fk as gy,fl as my,fm as xp,fn as Sy,fo as by,fp as yy,fq as Ep,fr as _p,fs as wy,ft as Wo,fu as Cu,fv as Ty,fw as vy,fx as Pu,fy as ku,fz as xy,fA as Ey,fB as _y,fC as Cy,fD as Au,fE as Py,fF as oo,fG as Cp,fH as Pp,fI as ky,fJ as Ay,fK as My,fL as Iy,fM as Dy,fN as Ny,fO as Ry,fP as jy,fQ as ma,fR as Yt,fS as Ly,fT as Oy,fU as By,fV as Er,fW as Fi,fX as Gi,fY as Hy,fZ as Fy,f_ as Gy,f$ as zy,g0 as kp,g1 as Vy,g2 as Uy,g3 as Wy,g4 as $y,g5 as Xy,g6 as uc,g7 as nr,g8 as ir,g9 as Ap,ga as Ky,gb as ft,gc as ao,gd as Mp,ge as Ip,gf as Dp,gg as Yy,gh as qy,gi as Mu,gj as Zy,gk as vi,gl as Qy,gm as Jy,gn as ew,go as tw,gp as nw,gq as iw,gr as sw,gs as rw,gt as ow,gu as aw,gv as lw,gw as cw,gx as uw,gy as dw,gz as hw,gA as fw,gB as pw,gC as gw,gD as mw,gE as Sw,gF as Iu,gG as Sa,gH as ba,gI as bw,gJ as Np,gK as yw,gL as nl,gM as bn,gN as Rp,gO as jp,gP as $o,gQ as St,gR as jn,gS as ww,gT as Tw,gU as zi,gV as vw,gW as xw,gX as Du,gY as Ew}from"./tool-windows-C4D0lII2.js";const _e=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,Ke=globalThis,xi="10.33.0";function Xo(){return Ko(Ke),Ke}function Ko(e){const t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||xi,t[xi]=t[xi]||{}}function ys(e,t,n=Ke){const i=n.__SENTRY__=n.__SENTRY__||{},s=i[xi]=i[xi]||{};return s[e]||(s[e]=t())}const _w=["debug","info","warn","error","log","assert","trace"],Cw="Sentry Logger ",lo={};function ws(e){if(!("console"in Ke))return e();const t=Ke.console,n={},i=Object.keys(lo);i.forEach(s=>{const r=lo[s];n[s]=t[s],t[s]=r});try{return e()}finally{i.forEach(s=>{t[s]=n[s]})}}function Pw(){hc().enabled=!0}function kw(){hc().enabled=!1}function Lp(){return hc().enabled}function Aw(...e){dc("log",...e)}function Mw(...e){dc("warn",...e)}function Iw(...e){dc("error",...e)}function dc(e,...t){_e&&Lp()&&ws(()=>{Ke.console[e](`${Cw}[${e}]:`,...t)})}function hc(){return _e?ys("loggerSettings",()=>({enabled:!1})):{enabled:!1}}const ye={enable:Pw,disable:kw,isEnabled:Lp,log:Aw,warn:Mw,error:Iw},Op=50,Ai="?",Nu=/\(error: (.*)\)/,Ru=/captureMessage|captureException/;function Bp(...e){const t=e.sort((n,i)=>n[0]-i[0]).map(n=>n[1]);return(n,i=0,s=0)=>{const r=[],o=n.split(`
|
|
3
3
|
`);for(let a=i;a<o.length;a++){let c=o[a];c.length>1024&&(c=c.slice(0,1024));const u=Nu.test(c)?c.replace(Nu,"$1"):c;if(!u.match(/\S*Error: /)){for(const d of t){const h=d(u);if(h){r.push(h);break}}if(r.length>=Op+s)break}}return Nw(r.slice(s))}}function Dw(e){return Array.isArray(e)?Bp(...e):e}function Nw(e){if(!e.length)return[];const t=Array.from(e);return/sentryWrapped/.test(_r(t).function||"")&&t.pop(),t.reverse(),Ru.test(_r(t).function||"")&&(t.pop(),Ru.test(_r(t).function||"")&&t.pop()),t.slice(0,Op).map(n=>({...n,filename:n.filename||_r(t).filename,function:n.function||Ai}))}function _r(e){return e[e.length-1]||{}}const ya="<anonymous>";function ri(e){try{return!e||typeof e!="function"?ya:e.name||ya}catch{return ya}}function ju(e){const t=e.exception;if(t){const n=[];try{return t.values.forEach(i=>{i.stacktrace.frames&&n.push(...i.stacktrace.frames)}),n}catch{return}}}function Hp(e){return"__v_isVNode"in e&&e.__v_isVNode?"[VueVNode]":"[VueViewModel]"}const Vr={},Lu={};function Ri(e,t){Vr[e]=Vr[e]||[],Vr[e].push(t)}function ji(e,t){if(!Lu[e]){Lu[e]=!0;try{t()}catch(n){_e&&ye.error(`Error while instrumenting ${e}`,n)}}}function mn(e,t){const n=e&&Vr[e];if(n)for(const i of n)try{i(t)}catch(s){_e&&ye.error(`Error while triggering instrumentation handler.
|
|
4
4
|
Type: ${e}
|
|
5
5
|
Name: ${ri(i)}
|
|
@@ -24,7 +24,7 @@ Url: ${uo(e)}`),!0}return!1}function u1(e,t){return t!=null&&t.length?pg(e).some
|
|
|
24
24
|
*/function c_(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Fd(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,Bg(i.key),i)}}function u_(e,t,n){return t&&Fd(e.prototype,t),n&&Fd(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function d_(e,t,n){return(t=Bg(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Gd(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,i)}return n}function Mc(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Gd(Object(n),!0).forEach(function(i){d_(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Gd(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}function h_(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var i=n.call(e,t);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}function Bg(e){var t=h_(e,"string");return typeof t=="symbol"?t:t+""}function xl(e){"@babel/helpers - typeof";return xl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},xl(e)}var zd={backdrop:!0,button:!0,navbar:!0,title:!0,toolbar:!0,className:"",container:"body",filter:null,fullscreen:!0,inheritedAttributes:["crossOrigin","decoding","isMap","loading","referrerPolicy","sizes","srcset","useMap"],initialCoverage:.9,initialViewIndex:0,inline:!1,interval:5e3,keyboard:!0,focus:!0,loading:!0,loop:!0,minWidth:200,minHeight:100,movable:!0,rotatable:!0,scalable:!0,zoomable:!0,zoomOnTouch:!0,zoomOnWheel:!0,slideOnTouch:!0,toggleOnDblclick:!0,tooltip:!0,transition:!0,zIndex:2015,zIndexInline:0,zoomRatio:.1,minZoomRatio:.01,maxZoomRatio:100,url:"src",ready:null,show:null,shown:null,hide:null,hidden:null,view:null,viewed:null,move:null,moved:null,rotate:null,rotated:null,scale:null,scaled:null,zoom:null,zoomed:null,play:null,stop:null},f_='<div class="viewer-container" tabindex="-1" touch-action="none"><div class="viewer-canvas"></div><div class="viewer-footer"><div class="viewer-title"></div><div class="viewer-toolbar"></div><div class="viewer-navbar"><ul class="viewer-list" role="navigation"></ul></div></div><div class="viewer-tooltip" role="alert" aria-hidden="true"></div><div class="viewer-button" data-viewer-action="mix" role="button"></div><div class="viewer-player"></div></div>',sa=typeof window<"u"&&typeof window.document<"u",Fn=sa?window:{},ns=sa&&Fn.document.documentElement?"ontouchstart"in Fn.document.documentElement:!1,Ic=sa?"PointerEvent"in Fn:!1,Ce="viewer",qr="move",Hg="switch",Hs="zoom",Ir="".concat(Ce,"-active"),p_="".concat(Ce,"-close"),Zr="".concat(Ce,"-fade"),El="".concat(Ce,"-fixed"),g_="".concat(Ce,"-fullscreen"),Vd="".concat(Ce,"-fullscreen-exit"),Si="".concat(Ce,"-hide"),m_="".concat(Ce,"-hide-md-down"),S_="".concat(Ce,"-hide-sm-down"),b_="".concat(Ce,"-hide-xs-down"),rn="".concat(Ce,"-in"),Ws="".concat(Ce,"-invisible"),is="".concat(Ce,"-loading"),y_="".concat(Ce,"-move"),Ud="".concat(Ce,"-open"),Ui="".concat(Ce,"-show"),yt="".concat(Ce,"-transition"),ds="click",_l="dblclick",Wd="dragstart",$d="focusin",Xd="keydown",an="load",Ei="error",w_=ns?"touchend touchcancel":"mouseup",T_=ns?"touchmove":"mousemove",v_=ns?"touchstart":"mousedown",Kd=Ic?"pointerdown":v_,Yd=Ic?"pointermove":T_,qd=Ic?"pointerup pointercancel":w_,Zd="resize",hn="transitionend",Qd="wheel",Jd="ready",eh="show",th="shown",nh="hide",ih="hidden",sh="view",ar="viewed",rh="move",oh="moved",ah="rotate",lh="rotated",ch="scale",uh="scaled",dh="zoom",hh="zoomed",fh="play",ph="stop",mo="".concat(Ce,"Action"),Dc=/\s\s*/,Dr=["zoom-in","zoom-out","one-to-one","reset","prev","play","next","rotate-left","rotate-right","flip-horizontal","flip-vertical"];function lr(e){return typeof e=="string"}var x_=Number.isNaN||Fn.isNaN;function mt(e){return typeof e=="number"&&!x_(e)}function Xi(e){return typeof e>"u"}function hs(e){return xl(e)==="object"&&e!==null}var E_=Object.prototype.hasOwnProperty;function Ki(e){if(!hs(e))return!1;try{var t=e.constructor,n=t.prototype;return t&&n&&E_.call(n,"isPrototypeOf")}catch{return!1}}function Ze(e){return typeof e=="function"}function nt(e,t){if(e&&Ze(t))if(Array.isArray(e)||mt(e.length)){var n=e.length,i;for(i=0;i<n&&t.call(e,e[i],i,e)!==!1;i+=1);}else hs(e)&&Object.keys(e).forEach(function(s){t.call(e,e[s],s,e)});return e}var Qt=Object.assign||function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];return hs(t)&&i.length>0&&i.forEach(function(r){hs(r)&&Object.keys(r).forEach(function(o){t[o]=r[o]})}),t},__=/^(?:width|height|left|top|marginLeft|marginTop)$/;function gn(e,t){var n=e.style;nt(t,function(i,s){__.test(s)&&mt(i)&&(i+="px"),n[s]=i})}function C_(e){return lr(e)?e.replace(/&(?!amp;|quot;|#39;|lt;|gt;)/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">"):e}function $i(e,t){return!e||!t?!1:e.classList?e.classList.contains(t):e.className.indexOf(t)>-1}function we(e,t){if(!(!e||!t)){if(mt(e.length)){nt(e,function(i){we(i,t)});return}if(e.classList){e.classList.add(t);return}var n=e.className.trim();n?n.indexOf(t)<0&&(e.className="".concat(n," ").concat(t)):e.className=t}}function We(e,t){if(!(!e||!t)){if(mt(e.length)){nt(e,function(n){We(n,t)});return}if(e.classList){e.classList.remove(t);return}e.className.indexOf(t)>=0&&(e.className=e.className.replace(t,""))}}function cr(e,t,n){if(t){if(mt(e.length)){nt(e,function(i){cr(i,t,n)});return}n?we(e,t):We(e,t)}}var P_=/([a-z\d])([A-Z])/g;function Nc(e){return e.replace(P_,"$1-$2").toLowerCase()}function Yi(e,t){return hs(e[t])?e[t]:e.dataset?e.dataset[t]:e.getAttribute("data-".concat(Nc(t)))}function Cl(e,t,n){hs(n)?e[t]=n:e.dataset?e.dataset[t]=n:e.setAttribute("data-".concat(Nc(t)),n)}var Fg=(function(){var e=!1;if(sa){var t=!1,n=function(){},i=Object.defineProperty({},"once",{get:function(){return e=!0,t},set:function(r){t=r}});Fn.addEventListener("test",n,i),Fn.removeEventListener("test",n,i)}return e})();function Qe(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},s=n;t.trim().split(Dc).forEach(function(r){if(!Fg){var o=e.listeners;o&&o[r]&&o[r][n]&&(s=o[r][n],delete o[r][n],Object.keys(o[r]).length===0&&delete o[r],Object.keys(o).length===0&&delete e.listeners)}e.removeEventListener(r,s,i)})}function ve(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},s=n;t.trim().split(Dc).forEach(function(r){if(i.once&&!Fg){var o=e.listeners,a=o===void 0?{}:o;s=function(){delete a[r][n],e.removeEventListener(r,s,i);for(var u=arguments.length,d=new Array(u),h=0;h<u;h++)d[h]=arguments[h];n.apply(e,d)},a[r]||(a[r]={}),a[r][n]&&e.removeEventListener(r,a[r][n],i),a[r][n]=s,e.listeners=a}e.addEventListener(r,s,i)})}function Tt(e,t,n,i){var s;return Ze(Event)&&Ze(CustomEvent)?s=new CustomEvent(t,Mc({bubbles:!0,cancelable:!0,detail:n},i)):(s=document.createEvent("CustomEvent"),s.initCustomEvent(t,!0,!0,n)),e.dispatchEvent(s)}function k_(e){var t=e.getBoundingClientRect();return{left:t.left+(window.pageXOffset-document.documentElement.clientLeft),top:t.top+(window.pageYOffset-document.documentElement.clientTop)}}function Qr(e){var t=e.rotate,n=e.scaleX,i=e.scaleY,s=e.translateX,r=e.translateY,o=[];mt(s)&&s!==0&&o.push("translateX(".concat(s,"px)")),mt(r)&&r!==0&&o.push("translateY(".concat(r,"px)")),mt(t)&&t!==0&&o.push("rotate(".concat(t,"deg)")),mt(n)&&n!==1&&o.push("scaleX(".concat(n,")")),mt(i)&&i!==1&&o.push("scaleY(".concat(i,")"));var a=o.length?o.join(" "):"none";return{WebkitTransform:a,msTransform:a,transform:a}}function A_(e){return lr(e)?decodeURIComponent(e.replace(/^.*\//,"").replace(/[?&#].*$/,"")):""}var Ma=Fn.navigator&&/Version\/\d+(\.\d+)+?\s+Safari/i.test(Fn.navigator.userAgent);function Gg(e,t,n){var i=document.createElement("img");if(e.naturalWidth&&!Ma)return n(e.naturalWidth,e.naturalHeight),i;var s=document.body||document.documentElement;return i.onload=function(){n(i.width,i.height),Ma||s.removeChild(i)},nt(t.inheritedAttributes,function(r){var o=e.getAttribute(r);o!==null&&i.setAttribute(r,o)}),i.src=e.src,Ma||(i.style.cssText="left:0;max-height:none!important;max-width:none!important;min-height:0!important;min-width:0!important;opacity:0;position:absolute;top:0;z-index:-1;",s.appendChild(i)),i}function Nr(e){switch(e){case 2:return b_;case 3:return S_;case 4:return m_;default:return""}}function M_(e){var t=Mc({},e),n=[];return nt(e,function(i,s){delete t[s],nt(t,function(r){var o=Math.abs(i.startX-r.startX),a=Math.abs(i.startY-r.startY),c=Math.abs(i.endX-r.endX),u=Math.abs(i.endY-r.endY),d=Math.sqrt(o*o+a*a),h=Math.sqrt(c*c+u*u),p=(h-d)/d;n.push(p)})}),n.sort(function(i,s){return Math.abs(i)<Math.abs(s)}),n[0]}function Rr(e,t){var n=e.pageX,i=e.pageY,s={endX:n,endY:i};return t?s:Mc({timeStamp:Date.now(),startX:n,startY:i},s)}function I_(e){var t=0,n=0,i=0;return nt(e,function(s){var r=s.startX,o=s.startY;t+=r,n+=o,i+=1}),t/=i,n/=i,{pageX:t,pageY:n}}var D_={render:function(){this.initContainer(),this.initViewer(),this.initList(),this.renderViewer()},initBody:function(){var t=this.element.ownerDocument,n=t.body||t.documentElement;this.body=n,this.scrollbarWidth=window.innerWidth-t.documentElement.clientWidth,this.initialBodyPaddingRight=n.style.paddingRight,this.initialBodyComputedPaddingRight=window.getComputedStyle(n).paddingRight},initContainer:function(){this.containerData={width:window.innerWidth,height:window.innerHeight}},initViewer:function(){var t=this.options,n=this.parent,i;t.inline&&(i={width:Math.max(n.offsetWidth,t.minWidth),height:Math.max(n.offsetHeight,t.minHeight)},this.parentData=i),(this.fulled||!i)&&(i=this.containerData),this.viewerData=Qt({},i)},renderViewer:function(){this.options.inline&&!this.fulled&&gn(this.viewer,this.viewerData)},initList:function(){var t=this,n=this.element,i=this.options,s=this.list,r=[];s.innerHTML="",nt(this.images,function(o,a){var c=o.src,u=o.alt||A_(c),d=t.getImageURL(o);if(c||d){var h=document.createElement("li"),p=document.createElement("img");nt(i.inheritedAttributes,function(g){var m=o.getAttribute(g);m!==null&&p.setAttribute(g,m)}),i.navbar&&(p.src=c||d),p.alt=u,p.setAttribute("data-original-url",d||c),h.setAttribute("data-index",a),h.setAttribute("data-viewer-action","view"),h.setAttribute("role","button"),i.keyboard&&h.setAttribute("tabindex",0),h.appendChild(p),s.appendChild(h),r.push(h)}}),this.items=r,nt(r,function(o){var a=o.firstElementChild,c,u;Cl(a,"filled",!0),i.loading&&we(o,is),ve(a,an,c=function(h){Qe(a,Ei,u),i.loading&&We(o,is),t.loadImage(h)},{once:!0}),ve(a,Ei,u=function(){Qe(a,an,c),i.loading&&We(o,is)},{once:!0})}),i.transition&&ve(n,ar,function(){we(s,yt)},{once:!0})},renderList:function(){var t=this.index,n=this.items[t];if(n){var i=n.nextElementSibling,s=parseInt(window.getComputedStyle(i||n).marginLeft,10),r=n.offsetWidth,o=r+s;gn(this.list,Qt({width:o*this.length-s},Qr({translateX:(this.viewerData.width-r)/2-o*t})))}},resetList:function(){var t=this.list;t.innerHTML="",We(t,yt),gn(t,Qr({translateX:0}))},initImage:function(t){var n=this,i=this.options,s=this.image,r=this.viewerData,o=this.footer.offsetHeight,a=r.width,c=Math.max(r.height-o,o),u=this.imageData||{},d;this.imageInitializing={abort:function(){d.onload=null}},d=Gg(s,i,function(h,p){var g=h/p,m=Math.max(0,Math.min(1,i.initialCoverage)),b=a,S=c;n.imageInitializing=!1,c*g>a?S=a/g:b=c*g,m=mt(m)?m:.9,b=Math.min(b*m,h),S=Math.min(S*m,p);var w=(a-b)/2,y=(c-S)/2,T={left:w,top:y,x:w,y,width:b,height:S,oldRatio:1,ratio:b/h,aspectRatio:g,naturalWidth:h,naturalHeight:p},C=Qt({},T);i.rotatable&&(T.rotate=u.rotate||0,C.rotate=0),i.scalable&&(T.scaleX=u.scaleX||1,T.scaleY=u.scaleY||1,C.scaleX=1,C.scaleY=1),n.imageData=T,n.initialImageData=C,t&&t()})},renderImage:function(t){var n=this,i=this.image,s=this.imageData;if(gn(i,Qt({width:s.width,height:s.height,marginLeft:s.x,marginTop:s.y},Qr(s))),t)if((this.viewing||this.moving||this.rotating||this.scaling||this.zooming)&&this.options.transition&&$i(i,yt)){var r=function(){n.imageRendering=!1,t()};this.imageRendering={abort:function(){Qe(i,hn,r)}},ve(i,hn,r,{once:!0})}else t()},resetImage:function(){var t=this.image;t&&(this.viewing&&this.viewing.abort(),t.parentNode.removeChild(t),this.image=null,this.title.innerHTML="")}},N_={bind:function(){var t=this.options,n=this.viewer,i=this.canvas,s=this.element.ownerDocument;ve(n,ds,this.onClick=this.click.bind(this)),ve(n,Wd,this.onDragStart=this.dragstart.bind(this)),ve(i,Kd,this.onPointerDown=this.pointerdown.bind(this)),ve(s,Yd,this.onPointerMove=this.pointermove.bind(this)),ve(s,qd,this.onPointerUp=this.pointerup.bind(this)),ve(s,Xd,this.onKeyDown=this.keydown.bind(this)),ve(window,Zd,this.onResize=this.resize.bind(this)),t.zoomable&&t.zoomOnWheel&&ve(n,Qd,this.onWheel=this.wheel.bind(this),{passive:!1,capture:!0}),t.toggleOnDblclick&&ve(i,_l,this.onDblclick=this.dblclick.bind(this))},unbind:function(){var t=this.options,n=this.viewer,i=this.canvas,s=this.element.ownerDocument;Qe(n,ds,this.onClick),Qe(n,Wd,this.onDragStart),Qe(i,Kd,this.onPointerDown),Qe(s,Yd,this.onPointerMove),Qe(s,qd,this.onPointerUp),Qe(s,Xd,this.onKeyDown),Qe(window,Zd,this.onResize),t.zoomable&&t.zoomOnWheel&&Qe(n,Qd,this.onWheel,{passive:!1,capture:!0}),t.toggleOnDblclick&&Qe(i,_l,this.onDblclick)}},R_={click:function(t){var n=this.options,i=this.imageData,s=t.target,r=Yi(s,mo);switch(!r&&s.localName==="img"&&s.parentElement.localName==="li"&&(s=s.parentElement,r=Yi(s,mo)),ns&&t.isTrusted&&s===this.canvas&&clearTimeout(this.clickCanvasTimeout),r){case"mix":this.played?this.stop():n.inline?this.fulled?this.exit():this.full():this.hide();break;case"hide":this.pointerMoved||this.hide();break;case"view":this.view(Yi(s,"index"));break;case"zoom-in":this.zoom(.1,!0);break;case"zoom-out":this.zoom(-.1,!0);break;case"one-to-one":this.toggle();break;case"reset":this.reset();break;case"prev":this.prev(n.loop);break;case"play":this.play(n.fullscreen);break;case"next":this.next(n.loop);break;case"rotate-left":this.rotate(-90);break;case"rotate-right":this.rotate(90);break;case"flip-horizontal":this.scaleX(-i.scaleX||-1);break;case"flip-vertical":this.scaleY(-i.scaleY||-1);break;default:this.played&&this.stop()}},dblclick:function(t){t.preventDefault(),this.viewed&&t.target===this.image&&(ns&&t.isTrusted&&clearTimeout(this.doubleClickImageTimeout),this.toggle(t.isTrusted?t:t.detail&&t.detail.originalEvent))},load:function(){var t=this;this.timeout&&(clearTimeout(this.timeout),this.timeout=!1);var n=this.element,i=this.options,s=this.image,r=this.index,o=this.viewerData;We(s,Ws),i.loading&&We(this.canvas,is),s.style.cssText="height:0;"+"margin-left:".concat(o.width/2,"px;")+"margin-top:".concat(o.height/2,"px;")+"max-width:none!important;position:relative;width:0;",this.initImage(function(){cr(s,y_,i.movable),cr(s,yt,i.transition),t.renderImage(function(){t.viewed=!0,t.viewing=!1,Ze(i.viewed)&&ve(n,ar,i.viewed,{once:!0}),Tt(n,ar,{originalImage:t.images[r],index:r,image:s},{cancelable:!1})})})},loadImage:function(t){var n=t.target,i=n.parentNode,s=i.offsetWidth||30,r=i.offsetHeight||50,o=!!Yi(n,"filled");Gg(n,this.options,function(a,c){var u=a/c,d=s,h=r;r*u>s?o?d=r*u:h=s/u:o?h=s/u:d=r*u,gn(n,Qt({width:d,height:h},Qr({translateX:(s-d)/2,translateY:(r-h)/2})))})},keydown:function(t){var n=this.options;if(n.keyboard){var i=t.keyCode||t.which||t.charCode;switch(i){case 13:this.viewer.contains(t.target)&&this.click(t);break}if(this.fulled)switch(i){case 27:this.played?this.stop():n.inline?this.fulled&&this.exit():this.hide();break;case 32:this.played&&this.stop();break;case 37:this.played&&this.playing?this.playing.prev():this.prev(n.loop);break;case 38:t.preventDefault(),this.zoom(n.zoomRatio,!0);break;case 39:this.played&&this.playing?this.playing.next():this.next(n.loop);break;case 40:t.preventDefault(),this.zoom(-n.zoomRatio,!0);break;case 48:case 49:t.ctrlKey&&(t.preventDefault(),this.toggle());break}}},dragstart:function(t){t.target.localName==="img"&&t.preventDefault()},pointerdown:function(t){var n=this.options,i=this.pointers,s=t.buttons,r=t.button;if(this.pointerMoved=!1,!(!this.viewed||this.showing||this.viewing||this.hiding||(t.type==="mousedown"||t.type==="pointerdown"&&t.pointerType==="mouse")&&(mt(s)&&s!==1||mt(r)&&r!==0||t.ctrlKey))){t.preventDefault(),t.changedTouches?nt(t.changedTouches,function(a){i[a.identifier]=Rr(a)}):i[t.pointerId||0]=Rr(t);var o=n.movable?qr:!1;n.zoomOnTouch&&n.zoomable&&Object.keys(i).length>1?o=Hs:n.slideOnTouch&&(t.pointerType==="touch"||t.type==="touchstart")&&this.isSwitchable()&&(o=Hg),n.transition&&(o===qr||o===Hs)&&We(this.image,yt),this.action=o}},pointermove:function(t){var n=this.pointers,i=this.action;!this.viewed||!i||(t.preventDefault(),t.changedTouches?nt(t.changedTouches,function(s){Qt(n[s.identifier]||{},Rr(s,!0))}):Qt(n[t.pointerId||0]||{},Rr(t,!0)),this.change(t))},pointerup:function(t){var n=this,i=this.options,s=this.action,r=this.pointers,o;t.changedTouches?nt(t.changedTouches,function(a){o=r[a.identifier],delete r[a.identifier]}):(o=r[t.pointerId||0],delete r[t.pointerId||0]),s&&(t.preventDefault(),i.transition&&(s===qr||s===Hs)&&we(this.image,yt),this.action=!1,ns&&s!==Hs&&o&&Date.now()-o.timeStamp<500&&(clearTimeout(this.clickCanvasTimeout),clearTimeout(this.doubleClickImageTimeout),i.toggleOnDblclick&&this.viewed&&t.target===this.image?this.imageClicked?(this.imageClicked=!1,this.doubleClickImageTimeout=setTimeout(function(){Tt(n.image,_l,{originalEvent:t})},50)):(this.imageClicked=!0,this.doubleClickImageTimeout=setTimeout(function(){n.imageClicked=!1},500)):(this.imageClicked=!1,i.backdrop&&i.backdrop!=="static"&&t.target===this.canvas&&(this.clickCanvasTimeout=setTimeout(function(){Tt(n.canvas,ds,{originalEvent:t})},50)))))},resize:function(){var t=this;if(!(!this.isShown||this.hiding)&&(this.fulled&&(this.close(),this.initBody(),this.open()),this.initContainer(),this.initViewer(),this.renderViewer(),this.renderList(),this.viewed&&this.initImage(function(){t.renderImage()}),this.played)){if(this.options.fullscreen&&this.fulled&&!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)){this.stop();return}nt(this.player.getElementsByTagName("img"),function(n){ve(n,an,t.loadImage.bind(t),{once:!0}),Tt(n,an)})}},wheel:function(t){var n=this;if(this.viewed&&(t.preventDefault(),!this.wheeling)){this.wheeling=!0,setTimeout(function(){n.wheeling=!1},50);var i=Number(this.options.zoomRatio)||.1,s=1;t.deltaY?s=t.deltaY>0?1:-1:t.wheelDelta?s=-t.wheelDelta/120:t.detail&&(s=t.detail>0?1:-1),this.zoom(-s*i,!0,null,t)}}},j_={show:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,n=this.element,i=this.options;if(i.inline||this.showing||this.isShown||this.showing)return this;if(!this.ready)return this.build(),this.ready&&this.show(t),this;if(Ze(i.show)&&ve(n,eh,i.show,{once:!0}),Tt(n,eh)===!1||!this.ready)return this;this.hiding&&this.transitioning.abort(),this.showing=!0,this.open();var s=this.viewer;if(We(s,Si),s.setAttribute("role","dialog"),s.setAttribute("aria-labelledby",this.title.id),s.setAttribute("aria-modal",!0),s.removeAttribute("aria-hidden"),i.transition&&!t){var r=this.shown.bind(this);this.transitioning={abort:function(){Qe(s,hn,r),We(s,rn)}},we(s,yt),s.initialOffsetWidth=s.offsetWidth,ve(s,hn,r,{once:!0}),we(s,rn)}else we(s,rn),this.shown();return this},hide:function(){var t=this,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,i=this.element,s=this.options;if(s.inline||this.hiding||!(this.isShown||this.showing))return this;if(Ze(s.hide)&&ve(i,nh,s.hide,{once:!0}),Tt(i,nh)===!1)return this;this.showing&&this.transitioning.abort(),this.hiding=!0,this.played?this.stop():this.viewing&&this.viewing.abort();var r=this.viewer,o=this.image,a=function(){We(r,rn),t.hidden()};if(s.transition&&!n){var c=function(h){h&&h.target===r&&(Qe(r,hn,c),t.hidden())},u=function(){$i(r,yt)?(ve(r,hn,c),We(r,rn)):a()};this.transitioning={abort:function(){t.viewed&&$i(o,yt)?Qe(o,hn,u):$i(r,yt)&&Qe(r,hn,c)}},this.viewed&&$i(o,yt)?(ve(o,hn,u,{once:!0}),this.zoomTo(0,!1,null,null,!0)):u()}else a();return this},view:function(){var t=this,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.initialViewIndex;if(n=Number(n)||0,this.hiding||this.played||n<0||n>=this.length||this.viewed&&n===this.index)return this;if(!this.isShown)return this.index=n,this.show();this.viewing&&this.viewing.abort();var i=this.element,s=this.options,r=this.title,o=this.canvas,a=this.items[n],c=a.querySelector("img"),u=Yi(c,"originalUrl"),d=c.getAttribute("alt"),h=document.createElement("img");if(nt(s.inheritedAttributes,function(S){var w=c.getAttribute(S);w!==null&&h.setAttribute(S,w)}),h.src=u,h.alt=d,Ze(s.view)&&ve(i,sh,s.view,{once:!0}),Tt(i,sh,{originalImage:this.images[n],index:n,image:h})===!1||!this.isShown||this.hiding||this.played)return this;var p=this.items[this.index];p&&(We(p,Ir),p.removeAttribute("aria-selected")),we(a,Ir),a.setAttribute("aria-selected",!0),s.focus&&a.focus(),this.image=h,this.viewed=!1,this.index=n,this.imageData={},we(h,Ws),s.loading&&we(o,is),o.innerHTML="",o.appendChild(h),this.renderList(),r.innerHTML="";var g=function(){var w=t.imageData,y=Array.isArray(s.title)?s.title[1]:s.title;r.innerHTML=C_(Ze(y)?y.call(t,h,w):"".concat(d," (").concat(w.naturalWidth," × ").concat(w.naturalHeight,")"))},m,b;return ve(i,ar,g,{once:!0}),this.viewing={abort:function(){Qe(i,ar,g),h.complete?t.imageRendering?t.imageRendering.abort():t.imageInitializing&&t.imageInitializing.abort():(h.src="",Qe(h,an,m),t.timeout&&clearTimeout(t.timeout))}},h.complete?this.load():(ve(h,an,m=function(){Qe(h,Ei,b),t.load()},{once:!0}),ve(h,Ei,b=function(){Qe(h,an,m),t.timeout&&(clearTimeout(t.timeout),t.timeout=!1),We(h,Ws),s.loading&&We(t.canvas,is)},{once:!0}),this.timeout&&clearTimeout(this.timeout),this.timeout=setTimeout(function(){We(h,Ws),t.timeout=!1},1e3)),this},prev:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,n=this.index-1;return n<0&&(n=t?this.length-1:0),this.view(n),this},next:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,n=this.length-1,i=this.index+1;return i>n&&(i=t?0:n),this.view(i),this},move:function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:t,i=this.imageData;return this.moveTo(Xi(t)?t:i.x+Number(t),Xi(n)?n:i.y+Number(n)),this},moveTo:function(t){var n=this,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:t,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,r=this.element,o=this.options,a=this.imageData;if(t=Number(t),i=Number(i),this.viewed&&!this.played&&o.movable){var c=a.x,u=a.y,d=!1;if(mt(t)?d=!0:t=c,mt(i)?d=!0:i=u,d){if(Ze(o.move)&&ve(r,rh,o.move,{once:!0}),Tt(r,rh,{x:t,y:i,oldX:c,oldY:u,originalEvent:s})===!1)return this;a.x=t,a.y=i,a.left=t,a.top=i,this.moving=!0,this.renderImage(function(){n.moving=!1,Ze(o.moved)&&ve(r,oh,o.moved,{once:!0}),Tt(r,oh,{x:t,y:i,oldX:c,oldY:u,originalEvent:s},{cancelable:!1})})}}return this},rotate:function(t){return this.rotateTo((this.imageData.rotate||0)+Number(t)),this},rotateTo:function(t){var n=this,i=this.element,s=this.options,r=this.imageData;if(t=Number(t),mt(t)&&this.viewed&&!this.played&&s.rotatable){var o=r.rotate;if(Ze(s.rotate)&&ve(i,ah,s.rotate,{once:!0}),Tt(i,ah,{degree:t,oldDegree:o})===!1)return this;r.rotate=t,this.rotating=!0,this.renderImage(function(){n.rotating=!1,Ze(s.rotated)&&ve(i,lh,s.rotated,{once:!0}),Tt(i,lh,{degree:t,oldDegree:o},{cancelable:!1})})}return this},scaleX:function(t){return this.scale(t,this.imageData.scaleY),this},scaleY:function(t){return this.scale(this.imageData.scaleX,t),this},scale:function(t){var n=this,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:t,s=this.element,r=this.options,o=this.imageData;if(t=Number(t),i=Number(i),this.viewed&&!this.played&&r.scalable){var a=o.scaleX,c=o.scaleY,u=!1;if(mt(t)?u=!0:t=a,mt(i)?u=!0:i=c,u){if(Ze(r.scale)&&ve(s,ch,r.scale,{once:!0}),Tt(s,ch,{scaleX:t,scaleY:i,oldScaleX:a,oldScaleY:c})===!1)return this;o.scaleX=t,o.scaleY=i,this.scaling=!0,this.renderImage(function(){n.scaling=!1,Ze(r.scaled)&&ve(s,uh,r.scaled,{once:!0}),Tt(s,uh,{scaleX:t,scaleY:i,oldScaleX:a,oldScaleY:c},{cancelable:!1})})}}return this},zoom:function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null,r=this.imageData;return t=Number(t),t<0?t=1/(1-t):t=1+t,this.zoomTo(r.width*t/r.naturalWidth,n,i,s),this},zoomTo:function(t){var n=this,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,a=this.element,c=this.options,u=this.pointers,d=this.imageData,h=d.x,p=d.y,g=d.width,m=d.height,b=d.naturalWidth,S=d.naturalHeight;if(t=Math.max(0,t),mt(t)&&this.viewed&&!this.played&&(o||c.zoomable)){if(!o){var w=Math.max(.01,c.minZoomRatio),y=Math.min(100,c.maxZoomRatio);t=Math.min(Math.max(t,w),y)}if(r)switch(r.type){case"wheel":c.zoomRatio>=.055&&t>.95&&t<1.05&&(t=1);break;case"pointermove":case"touchmove":case"mousemove":t>.99&&t<1.01&&(t=1);break}var T=b*t,C=S*t,E=T-g,v=C-m,x=d.ratio;if(Ze(c.zoom)&&ve(a,dh,c.zoom,{once:!0}),Tt(a,dh,{ratio:t,oldRatio:x,originalEvent:r})===!1)return this;if(this.zooming=!0,r){var O=k_(this.viewer),B=u&&Object.keys(u).length>0?I_(u):{pageX:r.pageX,pageY:r.pageY};d.x-=E*((B.pageX-O.left-h)/g),d.y-=v*((B.pageY-O.top-p)/m)}else Ki(s)&&mt(s.x)&&mt(s.y)?(d.x-=E*((s.x-h)/g),d.y-=v*((s.y-p)/m)):(d.x-=E/2,d.y-=v/2);d.left=d.x,d.top=d.y,d.width=T,d.height=C,d.oldRatio=x,d.ratio=t,this.renderImage(function(){n.zooming=!1,Ze(c.zoomed)&&ve(a,hh,c.zoomed,{once:!0}),Tt(a,hh,{ratio:t,oldRatio:x,originalEvent:r},{cancelable:!1})}),i&&this.tooltip()}return this},play:function(){var t=this,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!this.isShown||this.played)return this;var i=this.element,s=this.options;if(Ze(s.play)&&ve(i,fh,s.play,{once:!0}),Tt(i,fh)===!1)return this;var r=this.player,o=this.loadImage.bind(this),a=[],c=0,u=0;if(this.played=!0,this.onLoadWhenPlay=o,n&&this.requestFullscreen(n),we(r,Ui),nt(this.items,function(p,g){var m=p.querySelector("img"),b=document.createElement("img");b.src=Yi(m,"originalUrl"),b.alt=m.getAttribute("alt"),b.referrerPolicy=m.referrerPolicy,c+=1,we(b,Zr),cr(b,yt,s.transition),$i(p,Ir)&&(we(b,rn),u=g),a.push(b),ve(b,an,o,{once:!0}),r.appendChild(b)}),mt(s.interval)&&s.interval>0){var d=function(){clearTimeout(t.playing.timeout),We(a[u],rn),u-=1,u=u>=0?u:c-1,we(a[u],rn),t.playing.timeout=setTimeout(d,s.interval)},h=function(){clearTimeout(t.playing.timeout),We(a[u],rn),u+=1,u=u<c?u:0,we(a[u],rn),t.playing.timeout=setTimeout(h,s.interval)};c>1&&(this.playing={prev:d,next:h,timeout:setTimeout(h,s.interval)})}return this},stop:function(){var t=this;if(!this.played)return this;var n=this.element,i=this.options;if(Ze(i.stop)&&ve(n,ph,i.stop,{once:!0}),Tt(n,ph)===!1)return this;var s=this.player;return clearTimeout(this.playing.timeout),this.playing=!1,this.played=!1,nt(s.getElementsByTagName("img"),function(r){Qe(r,an,t.onLoadWhenPlay)}),We(s,Ui),s.innerHTML="",this.exitFullscreen(),this},full:function(){var t=this,n=this.options,i=this.viewer,s=this.image,r=this.list;return!this.isShown||this.played||this.fulled||!n.inline?this:(this.fulled=!0,this.open(),we(this.button,Vd),n.transition&&(We(r,yt),this.viewed&&We(s,yt)),we(i,El),i.setAttribute("role","dialog"),i.setAttribute("aria-labelledby",this.title.id),i.setAttribute("aria-modal",!0),i.removeAttribute("style"),gn(i,{zIndex:n.zIndex}),n.focus&&this.enforceFocus(),this.initContainer(),this.viewerData=Qt({},this.containerData),this.renderList(),this.viewed&&this.initImage(function(){t.renderImage(function(){n.transition&&setTimeout(function(){we(s,yt),we(r,yt)},0)})}),this)},exit:function(){var t=this,n=this.options,i=this.viewer,s=this.image,r=this.list;return!this.isShown||this.played||!this.fulled||!n.inline?this:(this.fulled=!1,this.close(),We(this.button,Vd),n.transition&&(We(r,yt),this.viewed&&We(s,yt)),n.focus&&this.clearEnforceFocus(),i.removeAttribute("role"),i.removeAttribute("aria-labelledby"),i.removeAttribute("aria-modal"),We(i,El),gn(i,{zIndex:n.zIndexInline}),this.viewerData=Qt({},this.parentData),this.renderViewer(),this.renderList(),this.viewed&&this.initImage(function(){t.renderImage(function(){n.transition&&setTimeout(function(){we(s,yt),we(r,yt)},0)})}),this)},tooltip:function(){var t=this,n=this.options,i=this.tooltipBox,s=this.imageData;return!this.viewed||this.played||!n.tooltip?this:(i.textContent="".concat(Math.round(s.ratio*100),"%"),this.tooltipping?clearTimeout(this.tooltipping):n.transition?(this.fading&&Tt(i,hn),we(i,Ui),we(i,Zr),we(i,yt),i.removeAttribute("aria-hidden"),i.initialOffsetWidth=i.offsetWidth,we(i,rn)):(we(i,Ui),i.removeAttribute("aria-hidden")),this.tooltipping=setTimeout(function(){n.transition?(ve(i,hn,function(){We(i,Ui),We(i,Zr),We(i,yt),i.setAttribute("aria-hidden",!0),t.fading=!1},{once:!0}),We(i,rn),t.fading=!0):(We(i,Ui),i.setAttribute("aria-hidden",!0)),t.tooltipping=!1},1e3),this)},toggle:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null;return this.imageData.ratio===1?this.zoomTo(this.imageData.oldRatio,!0,null,t):this.zoomTo(1,!0,null,t),this},reset:function(){return this.viewed&&!this.played&&(this.imageData=Qt({},this.initialImageData),this.renderImage()),this},update:function(){var t=this,n=this.element,i=this.options,s=this.isImg;if(s&&!n.parentNode)return this.destroy();var r=[];if(nt(s?[n]:n.querySelectorAll("img"),function(u){Ze(i.filter)?i.filter.call(t,u)&&r.push(u):t.getImageURL(u)&&r.push(u)}),!r.length)return this;if(this.images=r,this.length=r.length,this.ready){var o=[];if(nt(this.items,function(u,d){var h=u.querySelector("img"),p=r[d];p&&h?(p.src!==h.src||p.alt!==h.alt)&&o.push(d):o.push(d)}),gn(this.list,{width:"auto"}),this.initList(),this.isShown)if(this.length){if(this.viewed){var a=o.indexOf(this.index);if(a>=0)this.viewed=!1,this.view(Math.max(Math.min(this.index-a,this.length-1),0));else{var c=this.items[this.index];we(c,Ir),c.setAttribute("aria-selected",!0)}}}else this.image=null,this.viewed=!1,this.index=0,this.imageData={},this.canvas.innerHTML="",this.title.innerHTML=""}else this.build();return this},destroy:function(){var t=this.element,n=this.options;return t[Ce]?(this.destroyed=!0,this.ready?(this.played&&this.stop(),n.inline?(this.fulled&&this.exit(),this.unbind()):this.isShown?(this.viewing&&(this.imageRendering?this.imageRendering.abort():this.imageInitializing&&this.imageInitializing.abort()),this.hiding&&this.transitioning.abort(),this.hidden()):this.showing&&(this.transitioning.abort(),this.hidden()),this.ready=!1,this.viewer.parentNode.removeChild(this.viewer)):n.inline&&(this.delaying?this.delaying.abort():this.initializing&&this.initializing.abort()),n.inline||Qe(t,ds,this.onStart),t[Ce]=void 0,this):this}},L_={getImageURL:function(t){var n=this.options.url;return lr(n)?n=t.getAttribute(n):Ze(n)?n=n.call(this,t):n="",n},enforceFocus:function(){var t=this;this.clearEnforceFocus(),ve(document,$d,this.onFocusin=function(n){var i=t.viewer,s=n.target;if(!(s===document||s===i||i.contains(s))){for(;s;){if(s.getAttribute("tabindex")!==null||s.getAttribute("aria-modal")==="true")return;s=s.parentElement}i.focus()}})},clearEnforceFocus:function(){this.onFocusin&&(Qe(document,$d,this.onFocusin),this.onFocusin=null)},open:function(){var t=this.body;we(t,Ud),this.scrollbarWidth>0&&(t.style.paddingRight="".concat(this.scrollbarWidth+(parseFloat(this.initialBodyComputedPaddingRight)||0),"px"))},close:function(){var t=this.body;We(t,Ud),this.scrollbarWidth>0&&(t.style.paddingRight=this.initialBodyPaddingRight)},shown:function(){var t=this.element,n=this.options,i=this.viewer;this.fulled=!0,this.isShown=!0,this.render(),this.bind(),this.showing=!1,n.focus&&(i.focus(),this.enforceFocus()),Ze(n.shown)&&ve(t,th,n.shown,{once:!0}),Tt(t,th)!==!1&&this.ready&&this.isShown&&!this.hiding&&this.view(this.index)},hidden:function(){var t=this.element,n=this.options,i=this.viewer;n.fucus&&this.clearEnforceFocus(),this.close(),this.unbind(),we(i,Si),i.removeAttribute("role"),i.removeAttribute("aria-labelledby"),i.removeAttribute("aria-modal"),i.setAttribute("aria-hidden",!0),this.resetList(),this.resetImage(),this.fulled=!1,this.viewed=!1,this.isShown=!1,this.hiding=!1,this.destroyed||(Ze(n.hidden)&&ve(t,ih,n.hidden,{once:!0}),Tt(t,ih,null,{cancelable:!1}))},requestFullscreen:function(t){var n=this.element.ownerDocument;if(this.fulled&&!(n.fullscreenElement||n.webkitFullscreenElement||n.mozFullScreenElement||n.msFullscreenElement)){var i=n.documentElement;i.requestFullscreen?Ki(t)?i.requestFullscreen(t):i.requestFullscreen():i.webkitRequestFullscreen?i.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT):i.mozRequestFullScreen?i.mozRequestFullScreen():i.msRequestFullscreen&&i.msRequestFullscreen()}},exitFullscreen:function(){var t=this.element.ownerDocument;this.fulled&&(t.fullscreenElement||t.webkitFullscreenElement||t.mozFullScreenElement||t.msFullscreenElement)&&(t.exitFullscreen?t.exitFullscreen():t.webkitExitFullscreen?t.webkitExitFullscreen():t.mozCancelFullScreen?t.mozCancelFullScreen():t.msExitFullscreen&&t.msExitFullscreen())},change:function(t){var n=this.options,i=this.pointers,s=i[Object.keys(i)[0]];if(s){var r=s.endX-s.startX,o=s.endY-s.startY;switch(this.action){case qr:(r!==0||o!==0)&&(this.pointerMoved=!0,this.move(r,o,t));break;case Hs:this.zoom(M_(i),!1,null,t);break;case Hg:{this.action="switched";var a=Math.abs(r);a>1&&a>Math.abs(o)&&(this.pointers={},r>1?this.prev(n.loop):r<-1&&this.next(n.loop));break}}nt(i,function(c){c.startX=c.endX,c.startY=c.endY})}},isSwitchable:function(){var t=this.imageData,n=this.viewerData;return this.length>1&&t.x>=0&&t.y>=0&&t.width<=n.width&&t.height<=n.height}},O_=Fn.Viewer,B_=(function(e){return function(){return e+=1,e}})(-1),zg=(function(){function e(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(c_(this,e),!t||t.nodeType!==1)throw new Error("The first argument is required and must be an element.");this.element=t,this.options=Qt({},zd,Ki(n)&&n),this.action=!1,this.fading=!1,this.fulled=!1,this.hiding=!1,this.imageClicked=!1,this.imageData={},this.index=this.options.initialViewIndex,this.isImg=!1,this.isShown=!1,this.length=0,this.moving=!1,this.played=!1,this.playing=!1,this.pointers={},this.ready=!1,this.rotating=!1,this.scaling=!1,this.showing=!1,this.timeout=!1,this.tooltipping=!1,this.viewed=!1,this.viewing=!1,this.wheeling=!1,this.zooming=!1,this.pointerMoved=!1,this.id=B_(),this.init()}return u_(e,[{key:"init",value:function(){var n=this,i=this.element,s=this.options;if(!i[Ce]){i[Ce]=this,s.focus&&!s.keyboard&&(s.focus=!1);var r=i.localName==="img",o=[];if(nt(r?[i]:i.querySelectorAll("img"),function(u){Ze(s.filter)?s.filter.call(n,u)&&o.push(u):n.getImageURL(u)&&o.push(u)}),this.isImg=r,this.length=o.length,this.images=o,this.initBody(),Xi(document.createElement(Ce).style.transition)&&(s.transition=!1),s.inline){var a=0,c=function(){if(a+=1,a===n.length){var d;n.initializing=!1,n.delaying={abort:function(){clearTimeout(d)}},d=setTimeout(function(){n.delaying=!1,n.build()},0)}};this.initializing={abort:function(){nt(o,function(d){d.complete||(Qe(d,an,c),Qe(d,Ei,c))})}},nt(o,function(u){if(u.complete)c();else{var d,h;ve(u,an,d=function(){Qe(u,Ei,h),c()},{once:!0}),ve(u,Ei,h=function(){Qe(u,an,d),c()},{once:!0})}})}else ve(i,ds,this.onStart=function(u){var d=u.target;d.localName==="img"&&(!Ze(s.filter)||s.filter.call(n,d))&&n.view(n.images.indexOf(d))})}}},{key:"build",value:function(){if(!this.ready){var n=this.element,i=this.options,s=n.parentNode,r=document.createElement("div");r.innerHTML=f_;var o=r.querySelector(".".concat(Ce,"-container")),a=o.querySelector(".".concat(Ce,"-title")),c=o.querySelector(".".concat(Ce,"-toolbar")),u=o.querySelector(".".concat(Ce,"-navbar")),d=o.querySelector(".".concat(Ce,"-button")),h=o.querySelector(".".concat(Ce,"-canvas"));if(this.parent=s,this.viewer=o,this.title=a,this.toolbar=c,this.navbar=u,this.button=d,this.canvas=h,this.footer=o.querySelector(".".concat(Ce,"-footer")),this.tooltipBox=o.querySelector(".".concat(Ce,"-tooltip")),this.player=o.querySelector(".".concat(Ce,"-player")),this.list=o.querySelector(".".concat(Ce,"-list")),o.id="".concat(Ce).concat(this.id),a.id="".concat(Ce,"Title").concat(this.id),we(a,i.title?Nr(Array.isArray(i.title)?i.title[0]:i.title):Si),we(u,i.navbar?Nr(i.navbar):Si),cr(d,Si,!i.button),i.keyboard&&d.setAttribute("tabindex",0),i.backdrop&&(we(o,"".concat(Ce,"-backdrop")),!i.inline&&i.backdrop!=="static"&&Cl(h,mo,"hide")),lr(i.className)&&i.className&&i.className.split(Dc).forEach(function(T){we(o,T)}),i.toolbar){var p=document.createElement("ul"),g=Ki(i.toolbar),m=Dr.slice(0,3),b=Dr.slice(7,9),S=Dr.slice(9);g||we(c,Nr(i.toolbar)),nt(g?i.toolbar:Dr,function(T,C){var E=g&&Ki(T),v=g?Nc(C):T,x=E&&!Xi(T.show)?T.show:T;if(!(!x||!i.zoomable&&m.indexOf(v)!==-1||!i.rotatable&&b.indexOf(v)!==-1||!i.scalable&&S.indexOf(v)!==-1)){var O=E&&!Xi(T.size)?T.size:T,B=E&&!Xi(T.click)?T.click:T,X=document.createElement("li");i.keyboard&&X.setAttribute("tabindex",0),X.setAttribute("role","button"),we(X,"".concat(Ce,"-").concat(v)),Ze(B)||Cl(X,mo,v),mt(x)&&we(X,Nr(x)),["small","large"].indexOf(O)!==-1?we(X,"".concat(Ce,"-").concat(O)):v==="play"&&we(X,"".concat(Ce,"-large")),Ze(B)&&ve(X,ds,B),p.appendChild(X)}}),c.appendChild(p)}else we(c,Si);if(!i.rotatable){var w=c.querySelectorAll('li[class*="rotate"]');we(w,Ws),nt(w,function(T){c.appendChild(T)})}if(i.inline)we(d,g_),gn(o,{zIndex:i.zIndexInline}),window.getComputedStyle(s).position==="static"&&gn(s,{position:"relative"}),s.insertBefore(o,n.nextSibling);else{we(d,p_),we(o,El),we(o,Zr),we(o,Si),gn(o,{zIndex:i.zIndex});var y=i.container;lr(y)&&(y=n.ownerDocument.querySelector(y)),y||(y=this.body),y.appendChild(o)}if(i.inline&&(this.render(),this.bind(),this.isShown=!0),this.ready=!0,Ze(i.ready)&&ve(n,Jd,i.ready,{once:!0}),Tt(n,Jd)===!1){this.ready=!1;return}this.ready&&i.inline&&this.view(this.index)}}}],[{key:"noConflict",value:function(){return window.Viewer=O_,e}},{key:"setDefaults",value:function(n){Qt(zd,Ki(n)&&n)}}])})();Qt(zg.prototype,D_,N_,R_,j_,L_);const H_=()=>window.innerWidth<=768||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);class F_{constructor(t={}){this.viewer=null,this.container=null,this.options={zoomStep:t.zoomStep||.2,minZoom:t.minZoom||.1,maxZoom:t.maxZoom||5,enableKeyboard:t.enableKeyboard!==!1}}open(t,n=""){this.close(),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=H_(),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};this.viewer=new zg(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()}close(){this.viewer&&this.viewer.hide()}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()}}function G_(e){const t=e.getData("text/uri-list");if(t){const s=t.split(`
|
|
25
25
|
`).filter(r=>r&&!r.startsWith("#"));if(s.length>0&&gh(s[0]))return s[0].trim()}const n=e.getData("text/plain");if(n&&gh(n.trim()))return n.trim();const i=e.getData("text/html");if(i){const s=i.match(/<img[^>]+src=["']([^"']+)["']/i);if(s&&s[1])return s[1]}return null}function gh(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(s=>n.includes(s))?!0:[/\.(jpg|jpeg|png|gif|webp|svg|bmp)(\?|$)/i,/\/image\//i,/\/images\//i,/\/img\//i,/\/photo\//i,/data:image\//i,/blob:/i].some(s=>s.test(e))}const z_=e=>{const t=e,{insertFragment:n,drop:i,pointerUp:s}=t,r=new F_({zoomStep:.3,minZoom:.1,maxZoom:5,enableKeyboard:!0});return t.insertFragment=(o,a,c)=>{var u;if((u=o==null?void 0:o.files)!=null&&u.length&&du(o.files[0].type)){const d=o.files[0];hu(e,d,a,!1);return}n(o,a,c)},t.drop=o=>{var a,c;if((c=(a=o.dataTransfer)==null?void 0:a.files)!=null&&c.length){const u=o.dataTransfer.files[0];if(du(u.type)){const d=Gt(e,zt(e,o.x,o.y));return hu(e,u,d,!0),!0}if(J0(u.type)){const d=Gt(e,zt(e,o.x,o.y));return(async()=>{try{const h=u.name.replace(/\.[^.]+$/,"");await fu.initialize();const p=await fu.addAsset({type:Nn.AUDIO,source:eS.LOCAL,name:u.name,blob:u,mimeType:u.type});await bi.updateCachedMedia(p.url,{metadata:{name:h}});const[g,m]=await Promise.all([tS(u),nS(u)]);let b;if(m){const S=`/__aitu_cache__/image/${p.id}-cover.png`;await bi.cacheMediaFromBlob(S,m,"image",{taskId:`${p.id}-cover`,name:`${h}-cover`}),b=S}await Gl(e,p.url,{title:h,duration:g,previewImageUrl:b},d,!0)}catch(h){console.error("[withImagePlugin] Failed to insert audio from drop:",h)}})(),!0}}if(o.dataTransfer){const u=G_(o.dataTransfer);if(u){const d=Gt(e,zt(e,o.x,o.y));return iS(e,u,d).catch(h=>{console.error("[withImagePlugin] Failed to insert image from URL:",h)}),!0}}return i(o)},t.pointerUp=o=>{const a=sS(e);if(a&&!Ef(e)&&!Zs(e)&&!Qs(e)){const c=Gt(e,zt(e,o.x,o.y)),u=Za(e,c);u&&tn.isMindElement(e,u)&&tn.hasImage(u)&&rS(e,u,c)&&a===u&&r.open(u.data.image.url)}s(o)},t},Ps={MAX_CHARS_PER_LINE:50};function V_(e){const t=e.split(`
|
|
26
26
|
`),n=[];for(const i of t)if(i.length<=Ps.MAX_CHARS_PER_LINE)n.push(i);else{let s=i;for(;s.length>0;){let r=Ps.MAX_CHARS_PER_LINE;if(s.length>Ps.MAX_CHARS_PER_LINE){const o=s.lastIndexOf(" ",Ps.MAX_CHARS_PER_LINE);o>Ps.MAX_CHARS_PER_LINE*.7&&(r=o)}n.push(s.substring(0,r).trim()),s=s.substring(r).trim()}}return n.join(`
|
|
27
|
-
`)}function U_(e){var i,s;if(!e)return!1;const t=!!e.text||!!((i=e.data)!=null&&i.text),n=!!e.elements||!!((s=e.data)!=null&&s.elements);return t&&!n}function W_(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 i=t.getData("text/plain");if(i)return i}return null}const $_=e=>{const{insertFragment:t}=e;return e.insertFragment=(n,i,s)=>{if(U_(n)){const r=W_(n);if(r&&r.trim()){const o=r.trim(),a=oS(o);if(a&&a.length>0){const u=Math.round(window.innerWidth*.5);aS(e,a,i,u);return}const c=V_(o);Mo.insertText(e,i,c);return}}t(n,i,s)},e},X_=e=>{const t=e;return t.renderImage=(n,i)=>{const s=ko.createRoot(n);s.render(l.jsx(Hd,{...i}));let r={...i};return{destroy:()=>{setTimeout(()=>{s.unmount()},0)},update:a=>{r={...r,...a},s.render(l.jsx(Hd,{...r}))}}},$_(z_(t))},K_=f.forwardRef(({children:e,gap:t,align:n,justifyContent:i,className:s,style:r},o)=>l.jsx("div",{className:q("stack stack_horizontal",s),style:{"--gap":t,alignItems:n,justifyContent:i,...r},ref:o,children:e})),Y_=f.forwardRef(({children:e,gap:t,align:n,justifyContent:i,className:s,style:r},o)=>l.jsx("div",{className:q("stack stack_vertical",s),style:{"--gap":t,justifyItems:n,justifyContent:i,...r},ref:o,children:e})),pt={Row:K_,Col:Y_},qe=Gn.forwardRef(({children:e,padding:t,className:n,style:i,...s},r)=>l.jsx("div",{className:q("island",n),style:{"--padding":t,...i},ref:r,...s,children:e})),Vg=e=>e?typeof e=="string"?e:Rn(e)&&e.type==="solid"&&e.solid?e.solid.color:null:null,q_=(e,t)=>{zn.setFillColor(e,null,{getMemorizeKey:Vn,callback:(n,i)=>{if(!cn(e,n))return;const s=n.fill,r=Vg(s)||_f(e,n);if(!lS(r))return;const o=_i(r),a=gs(t)?o:ms(o,t);ue.setNode(e,{fill:a},i)}})},Z_=(e,t)=>{zn.setFillColor(e,null,{getMemorizeKey:Vn,callback:(n,i)=>{if(!cn(e,n))return;const s=n.fill,r=Vg(s)||_f(e,n),o=typeof r=="string"?os(r):void 0;zl(t)?ue.setNode(e,{fill:"none"},i):Vl(o)||gs(o)?ue.setNode(e,{fill:t},i):ue.setNode(e,{fill:ms(t,o)},i)}})},Q_=(e,t)=>{zn.setStrokeColor(e,null,{getMemorizeKey:Vn,callback:(n,i)=>{const s=Pf(e,n),r=_i(s),o=gs(t)?r:ms(r,t);ue.setNode(e,{strokeColor:o},i)}})},J_=(e,t)=>{zn.setStrokeColor(e,null,{getMemorizeKey:Vn,callback:(n,i)=>{const s=Pf(e,n),r=os(s);zl(t)?ue.setNode(e,{strokeColor:"none"},i):Vl(r)||gs(r)?ue.setNode(e,{strokeColor:t},i):ue.setNode(e,{strokeColor:ms(t,r)},i)}})},eC=(e,t)=>{zn.setStrokeStyle(e,t,{getMemorizeKey:Vn,callback:(n,i)=>{ue.setNode(e,{strokeStyle:t},i)}})},mh=(e,t)=>{zn.setStrokeWidth(e,t,{getMemorizeKey:Vn,callback:(n,i)=>{ue.setNode(e,{strokeWidth:t},i)}})},tC=(e,t,n)=>{const i=os(t);zl(n)?Qn.setTextColor(e,null):Vl(i)||gs(i)?Qn.setTextColor(e,n):Qn.setTextColor(e,ms(n,i))},nC=(e,t,n)=>{const i=_i(t),s=gs(n)?i:ms(i,n);Qn.setTextColor(e,s)},Ug=(e,t)=>{try{Qn.setFontSize(e,t,16)}catch{const i=_t(e);i&&i.length>0&&i.forEach(s=>{try{s.addMark("font-size",t)}catch(r){console.error("Failed to set font size mark:",r)}})}},iC=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),xe.addMark(i,"font-family",t)}catch(s){console.error("Failed to set font family:",s)}})},Ia=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),t?xe.addMark(i,"text-shadow",t):xe.removeMark(i,"text-shadow")}catch(s){console.error("Failed to set text shadow:",s)}})},Sh=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),t?xe.addMark(i,"text-gradient",t):xe.removeMark(i,"text-gradient")}catch(s){console.error("Failed to set text gradient:",s)}})},Wg=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),xe.addMark(i,"font-weight",String(t))}catch(s){console.error("Failed to set font weight:",s)}})},sC=(e,t)=>{try{let n;t==="left"?n=Ji.left:t==="center"?n=Ji.center:n=Ji.right,Qn.setTextAlign(e,n)}catch(n){console.error("Failed to set text align:",n)}},rC=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),xe.addMark(i,"line-height",String(t))}catch(s){console.error("Failed to set line height:",s)}})},oC=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i);const s=typeof t=="number"?`${t}px`:t;xe.addMark(i,"letter-spacing",s)}catch(s){console.error("Failed to set letter spacing:",s)}})},aC=e=>{const t=_t(e);t&&t.length>0&&t.forEach(n=>{try{It(n);const i=xe.marks(n);(i?!!i.bold:!1)?xe.removeMark(n,"bold"):xe.addMark(n,"bold",!0)}catch(i){console.error("Failed to toggle bold:",i)}})},lC=e=>{const t=_t(e);t&&t.length>0&&t.forEach(n=>{try{It(n);const i=xe.marks(n);(i?!!i.italic:!1)?xe.removeMark(n,"italic"):xe.addMark(n,"italic",!0)}catch(i){console.error("Failed to toggle italic:",i)}})},cC=e=>{const t=_t(e);t&&t.length>0&&t.forEach(n=>{try{It(n);const i=xe.marks(n);(i?!!i.underlined:!1)?xe.removeMark(n,"underlined"):xe.addMark(n,"underlined",!0)}catch(i){console.error("Failed to toggle underline:",i)}})},uC=e=>{const t=_t(e);t&&t.length>0&&t.forEach(n=>{try{It(n);const i=xe.marks(n);(i?!!i.strikethrough:!1)?xe.removeMark(n,"strikethrough"):xe.addMark(n,"strikethrough",!0)}catch(i){console.error("Failed to toggle strikethrough:",i)}})},dC=e=>{const t=_t(e);t&&t.length>0&&t.forEach(n=>{try{It(n);const i=xe.marks(n);(i?!!i.superscript:!1)?xe.removeMark(n,"superscript"):(xe.removeMark(n,"subscript"),xe.addMark(n,"superscript",!0))}catch(i){console.error("Failed to toggle superscript:",i)}})},hC=e=>{const t=_t(e);t&&t.length>0&&t.forEach(n=>{try{It(n);const i=xe.marks(n);(i?!!i.subscript:!1)?xe.removeMark(n,"subscript"):(xe.removeMark(n,"superscript"),xe.addMark(n,"subscript",!0))}catch(i){console.error("Failed to toggle subscript:",i)}})},fC=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),t?xe.addMark(i,"background-color",t):xe.removeMark(i,"background-color")}catch(s){console.error("Failed to set background color:",s)}})},pC=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),t&&t!=="none"?xe.addMark(i,"text-transform",t):xe.removeMark(i,"text-transform")}catch(s){console.error("Failed to set text transform:",s)}})},gC=(e,t,n)=>{const i=_t(e);i&&i.length>0&&i.forEach(s=>{try{It(s),t&&t>0?(xe.addMark(s,"text-stroke",t),n&&xe.addMark(s,"text-stroke-color",n)):(xe.removeMark(s,"text-stroke"),xe.removeMark(s,"text-stroke-color"))}catch(r){console.error("Failed to set text stroke:",r)}})},mC=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),t?xe.addMark(i,"text-decoration-style",t):xe.removeMark(i,"text-decoration-style")}catch(s){console.error("Failed to set text decoration style:",s)}})},SC=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),t?xe.addMark(i,"text-decoration-color",t):xe.removeMark(i,"text-decoration-color")}catch(s){console.error("Failed to set text decoration color:",s)}})},bC=e=>{const t=_t(e);if(t&&t.length>0){const n=t[0];try{return It(n),xe.marks(n)||{}}catch(i){return console.error("Failed to get text marks:",i),{}}}return{}},yC=e=>{const t=_t(e);if(t&&t.length>0){const n=t[0];try{const{selection:i}=n;if(i){const s=Array.from(xe.nodes(n,{at:i,match:r=>{const o=r.type==="paragraph",a="align"in r;return xe.isBlock(n,r)&&(o||a)}}));if(s.length>0){const[r]=s[0],o=r.align;if(o===Ji.right||o==="right")return"right";if(o===Ji.center||o==="center")return"center";if(o===Ji.left||o==="left")return"left"}}}catch(i){console.error("Failed to get text align:",i)}}return"left"},wC=(e,t)=>{zn.setFillColor(e,null,{getMemorizeKey:Vn,callback:(n,i)=>{if(!cn(e,n))return;const s=Cf(t),r={type:"gradient",gradient:t,fallbackColor:s};ue.setNode(e,{fill:s,fillConfig:r},i)}})},bh=(e,t)=>{zn.setFillColor(e,null,{getMemorizeKey:Vn,callback:(n,i)=>{if(!cn(e,n))return;const s="#FFFFFF",r={type:"image",image:t,fallbackColor:s};ue.setNode(e,{fill:s,fillConfig:r},i)}})},TC=(e,t)=>{zn.setFillColor(e,null,{getMemorizeKey:Vn,callback:(n,i)=>{if(!cn(e,n))return;const s=n.fillConfig,r=n.fill;if((s==null?void 0:s.type)!==t)switch(t){case"solid":{let o="#FFFFFF";typeof r=="string"&&r!=="none"?o=r:s!=null&&s.solid&&(o=s.solid.color),ue.setNode(e,{fill:o,fillConfig:void 0},i);break}case"gradient":{const o={type:"linear",angle:90,stops:[{offset:0,color:"#FFFFFF"},{offset:1,color:"#000000"}]},a=(s==null?void 0:s.gradient)||o,c=Cf(a),u={type:"gradient",gradient:a,fallbackColor:c};ue.setNode(e,{fill:c,fillConfig:u},i);break}case"image":{const o={imageUrl:"",mode:"stretch",scale:1,offsetX:0,offsetY:0,rotation:0},a="#FFFFFF",c={type:"image",image:(s==null?void 0:s.image)||o,fallbackColor:a};ue.setNode(e,{fill:a,fillConfig:c},i);break}default:return}}})},vC=(e,t)=>{const n=He(e);for(const i of n)if(Mt(i)){const s=e.children.findIndex(r=>r.id===i.id);s!==-1&&ue.setNode(e,{fillColor:t},[s])}},xC=({board:e,currentColor:t,fontColorIcon:n,title:i})=>{const[s,r]=f.useState(!1),o=z.getBoardContainer(e),a=f.useCallback(u=>{tC(e,t||u,u)},[e,t]),c=f.useCallback(u=>{t&&nC(e,t,u)},[e,t]);return l.jsxs(at,{sideOffset:12,open:s,onOpenChange:u=>{r(u)},placement:"top",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:q("property-button"),selected:s,visible:!0,icon:n,type:"button",tooltip:i,"aria-label":i,onPointerUp:()=>{r(!s)}})}),l.jsx(ct,{container:o,children:l.jsx(qe,{padding:4,className:q(`${Dt}`),children:l.jsx(Ci,{value:t,onChange:a,onOpacityChange:c})})})]})},Pl=[{key:"title",labelZh:"标题",labelEn:"Title",previewSize:26,...Pn.title},{key:"subtitle",labelZh:"副标题",labelEn:"Subtitle",previewSize:22,...Pn.subtitle},{key:"h1",labelZh:"标题 1",labelEn:"Heading 1",previewSize:20,...Pn.h1,divider:!0},{key:"h2",labelZh:"标题 2",labelEn:"Heading 2",previewSize:18,...Pn.h2},{key:"h3",labelZh:"标题 3",labelEn:"Heading 3",previewSize:16,...Pn.h3},{key:"h4",labelZh:"标题 4",labelEn:"Heading 4",previewSize:15,...Pn.h4},{key:"body",labelZh:"正文",labelEn:"Body",previewSize:14,...Pn.body,divider:!0},{key:"caption",labelZh:"注释",labelEn:"Caption",previewSize:13,...Pn.caption},{key:"footnote",labelZh:"脚注",labelEn:"Footnote",previewSize:12,...Pn.footnote}],EC=e=>{if(!e)return null;const t=parseInt(e,10);if(isNaN(t))return null;for(const n of Pl)if(n.fontSize===t)return n.key;return null},_C=({board:e,currentFontSize:t,title:n})=>{const[i,s]=f.useState(!1),{language:r}=Ee(),o=z.getBoardContainer(e),a=EC(t),c=f.useCallback(d=>{Ug(e,String(d.fontSize)),Wg(e,d.fontWeight),Qn.setTextColor(e,d.color),s(!1)},[e]),u=(()=>{if(a){const d=Pl.find(h=>h.key===a);if(d)return r==="zh"?d.labelZh:d.labelEn}return t||"16"})();return l.jsxs(at,{sideOffset:12,open:i,onOpenChange:s,placement:"bottom",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:q("property-button"),selected:i,visible:!0,type:"button",tooltip:n,"aria-label":n,onPointerUp:()=>s(!i),children:l.jsx("div",{style:{fontSize:"12px",fontWeight:"bold",minWidth:"20px"},children:u})})}),l.jsx(ct,{container:o,children:l.jsx(qe,{padding:4,className:q(`${Dt}`),children:l.jsxs(pt.Col,{gap:0,style:{minWidth:"200px"},children:[l.jsx("div",{style:{fontSize:"12px",color:"#666",marginBottom:"2px",padding:"4px 10px 0"},children:r==="zh"?"字体样式":"Font Style"}),l.jsx("div",{style:{maxHeight:"320px",overflowY:"auto"},children:Pl.map(d=>{const h=a===d.key;return l.jsxs(Gn.Fragment,{children:[d.divider&&l.jsx("div",{style:{height:"1px",backgroundColor:"#e8e8e8",margin:"4px 10px"}}),l.jsxs("div",{onClick:()=>c(d),style:{padding:"6px 10px",cursor:"pointer",backgroundColor:h?"#f0f7ff":"transparent",borderLeft:h?"3px solid #0052d9":"3px solid transparent",borderRadius:"2px",transition:"background-color 0.15s",display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:"8px"},onMouseEnter:p=>{h||(p.currentTarget.style.backgroundColor="#f5f5f5")},onMouseLeave:p=>{h||(p.currentTarget.style.backgroundColor="transparent")},children:[l.jsx("span",{style:{fontSize:`${d.previewSize}px`,fontWeight:d.fontWeight,color:d.color,lineHeight:1.4},children:r==="zh"?d.labelZh:d.labelEn}),l.jsxs("span",{style:{fontSize:"11px",color:"#bbb",flexShrink:0},children:[d.fontSize,"px"]})]})]},d.key)})})]})})})]})},CC=({board:e,currentColor:t,title:n,hasStrokeStyle:i,hasStrokeWidth:s,currentStrokeWidth:r,children:o})=>{const[a,c]=f.useState(!1),[u,d]=f.useState(String(r||2)),h=t&&_i(t),p=t?os(t):100,g=z.getBoardContainer(e);Gn.useEffect(()=>{d(String(r||2))},[r]);const m=If(p)?cS:Df(h)?uS:void 0,b=m?l.jsx(m,{}):void 0,S=x=>{eC(e,x)},w=f.useCallback(x=>{J_(e,x)},[e]),y=f.useCallback(x=>{Q_(e,x)},[e]),T=f.useCallback(x=>{mh(e,x),d(String(x))},[e]),C=f.useCallback(x=>{d(x.target.value)},[]),E=f.useCallback(()=>{const x=parseInt(u,10);!isNaN(x)&&x>=1&&x<=100?mh(e,x):d(String(r||2))},[e,u,r]),v=f.useCallback(x=>{x.key==="Enter"?(E(),x.target.blur()):x.key==="Escape"&&(d(String(r||2)),x.target.blur())},[E,r]);return l.jsxs(at,{sideOffset:12,crossAxisOffset:40,open:a,onOpenChange:x=>{c(x)},placement:"left",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:q("property-button"),visible:!0,icon:b,type:"button",tooltip:n,"aria-label":n,onPointerUp:()=>{c(!a)},children:!b&&o})}),l.jsx(ct,{container:g,children:l.jsx(qe,{padding:4,className:q(`${Dt}`,"stroke-setting",{"has-stroke-style":i}),children:l.jsxs(pt.Col,{children:[s&&l.jsx("div",{className:"stroke-width-section",style:{marginBottom:"8px"},children:l.jsxs(pt.Row,{gap:2,align:"center",children:[l.jsx("span",{style:{fontSize:"12px",color:"var(--color-on-surface)",whiteSpace:"nowrap"},children:"线宽:"}),l.jsx("div",{style:{flex:1,minWidth:"100px"},children:l.jsx(Io,{value:r||2,min:1,max:100,step:1,onChange:x=>T(x),label:!1})}),l.jsxs("div",{className:"stroke-width-input-wrapper",children:[l.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:u,onChange:C,onBlur:E,onKeyDown:v,className:"stroke-width-input"}),l.jsx("span",{className:"stroke-width-input-unit",children:"px"})]})]})}),i&&l.jsxs("div",{className:"stroke-style-section",children:[l.jsx("span",{className:"stroke-style-label",children:"样式:"}),l.jsxs(pt.Row,{className:q("stroke-style-picker"),children:[l.jsx(ne,{visible:!0,icon:l.jsx(kf,{}),type:"button",tooltip:"实线","aria-label":"实线",onPointerUp:()=>S(Jn.solid)}),l.jsx(ne,{visible:!0,icon:l.jsx(Af,{}),type:"button",tooltip:"虚线","aria-label":"虚线",onPointerUp:()=>S(Jn.dashed)}),l.jsx(ne,{visible:!0,icon:l.jsx(Mf,{}),type:"button",tooltip:"点线","aria-label":"点线",onPointerUp:()=>S(Jn.dotted)})]})]}),l.jsx(Ci,{value:t,onChange:w,onOpacityChange:y})]})})})]})},PC="drawnix-color-history",yh=24,wh=12,Th=Gr.createInstance({name:"drawnix",storeName:PC});let Me=null;function kl(e){const t=e.stops.map(n=>`${n.color}@${n.offset}`).join("|");return e.type==="linear"?`linear-${e.angle}-${t}`:`radial-${e.centerX}-${e.centerY}-${t}`}function kC(e,t){return kl(e)===kl(t)}class AC{constructor(){this.initialized=!1}async initialize(){if(!this.initialized)try{Me=await Th.getItem("history")||{colors:[],gradients:[]},this.initialized=!0}catch(t){console.error("[ColorHistoryService] Failed to initialize:",t),Me={colors:[],gradients:[]},this.initialized=!0}}async saveData(){if(Me)try{await Th.setItem("history",Me)}catch(t){console.error("[ColorHistoryService] Failed to save data:",t)}}async addColor(t){if(await this.initialize(),!Me)return;const n=t.toUpperCase(),i=Me.colors.findIndex(s=>s.color.toUpperCase()===n);if(i>=0){Me.colors[i].lastUsedAt=Date.now(),Me.colors[i].useCount+=1;const[s]=Me.colors.splice(i,1);Me.colors.unshift(s)}else Me.colors.unshift({color:n,lastUsedAt:Date.now(),useCount:1}),Me.colors.length>yh&&(Me.colors=Me.colors.slice(0,yh));await this.saveData()}async addGradient(t){if(await this.initialize(),!Me)return;const n=kl(t),i=Me.gradients.findIndex(s=>kC(s.config,t));if(i>=0){Me.gradients[i].lastUsedAt=Date.now(),Me.gradients[i].useCount+=1;const[s]=Me.gradients.splice(i,1);Me.gradients.unshift(s)}else Me.gradients.unshift({id:n,config:{...t},lastUsedAt:Date.now(),useCount:1}),Me.gradients.length>wh&&(Me.gradients=Me.gradients.slice(0,wh));await this.saveData()}async getColors(){return await this.initialize(),(Me==null?void 0:Me.colors)||[]}async getGradients(){return await this.initialize(),(Me==null?void 0:Me.gradients)||[]}async removeColor(t){if(await this.initialize(),!Me)return;const n=t.toUpperCase();Me.colors=Me.colors.filter(i=>i.color.toUpperCase()!==n),await this.saveData()}async removeGradient(t){await this.initialize(),Me&&(Me.gradients=Me.gradients.filter(n=>n.id!==t),await this.saveData())}async clearAll(){Me={colors:[],gradients:[]},await this.saveData()}resetCache(){Me=null,this.initialized=!1}}const Sn=new AC;function MC(){const[e,t]=f.useState([]),[n,i]=f.useState([]),[s,r]=f.useState(!0),o=f.useCallback(async()=>{try{const[h,p]=await Promise.all([Sn.getColors(),Sn.getGradients()]);t(h),i(p)}catch(h){console.error("[useColorHistory] Failed to load data:",h)}finally{r(!1)}},[]);f.useEffect(()=>{o()},[o]);const a=f.useCallback(async h=>{await Sn.addColor(h);const p=await Sn.getColors();t(p)},[]),c=f.useCallback(async h=>{await Sn.addGradient(h);const p=await Sn.getGradients();i(p)},[]),u=f.useCallback(async h=>{await Sn.removeColor(h);const p=await Sn.getColors();t(p)},[]),d=f.useCallback(async h=>{await Sn.removeGradient(h);const p=await Sn.getGradients();i(p)},[]);return{colors:e,gradients:n,isLoading:s,addColor:a,addGradient:c,removeColor:u,removeGradient:d,refresh:o}}function yi(e){const t=e.stops.map(n=>`${n.color} ${Math.round(n.offset*100)}%`).join(", ");if(e.type==="linear")return`linear-gradient(${e.angle}deg, ${t})`;{const n=Math.round(e.centerX*100),i=Math.round(e.centerY*100);return`radial-gradient(circle at ${n}% ${i}%, ${t})`}}function IC(e){const t=e.match(/linear-gradient\((\d+)deg,\s*(.+)\)/);if(t){const i=parseInt(t[1],10),s=t[2],r=vh(s);return{type:"linear",angle:i,stops:r.length>=2?r:[{color:"#FF6B6B",offset:0},{color:"#4ECDC4",offset:1}]}}const n=e.match(/radial-gradient\(circle(?:\s+at\s+(\d+)%\s+(\d+)%)?,\s*(.+)\)/);if(n){const i=n[1]?parseInt(n[1],10)/100:.5,s=n[2]?parseInt(n[2],10)/100:.5,r=n[3],o=vh(r);return{type:"radial",centerX:i,centerY:s,stops:o.length>=2?o:[{color:"#FF6B6B",offset:0},{color:"#4ECDC4",offset:1}]}}return Do}function vh(e){const t=[],n=/(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\))\s+(\d+)%/g;let i;for(;(i=n.exec(e))!==null;)t.push({color:i[1],offset:parseInt(i[2],10)/100});return t}const xh=[{key:"left",labelZh:"左",labelEn:"Left",x:0,y:.5},{key:"center",labelZh:"中心",labelEn:"Center",x:.5,y:.5},{key:"top-left",labelZh:"左上",labelEn:"Top left",x:0,y:0},{key:"top",labelZh:"上",labelEn:"Top",x:.5,y:0},{key:"right",labelZh:"右",labelEn:"Right",x:1,y:.5},{key:"bottom",labelZh:"下",labelEn:"Bottom",x:.5,y:1}],$g=({value:e,onChange:t,showPresets:n=!0,showHistory:i=!0,presetCategories:s,customPresets:r,compact:o=!1,inline:a=!1,onSavePreset:c,onDeletePreset:u})=>{const{language:d}=Ee(),{addGradient:h}=MC(),[p,g]=f.useState(e||Do),[m,b]=f.useState(0),[S,w]=f.useState(null),[y,T]=f.useState(!1),C=f.useRef(null);f.useEffect(()=>{e&&g(e)},[e]);const E=f.useCallback(K=>{g(K),t==null||t(K),h(K)},[t,h]),v=f.useCallback(K=>{E(K.config)},[E]),x=f.useCallback(K=>{const ae={...p,...K};E(ae)},[p,E]),O=f.useCallback(K=>{if(p.type!==K)if(K==="linear"){const ae={type:"linear",angle:90,stops:p.stops};E(ae)}else{const ae={type:"radial",centerX:.5,centerY:.5,stops:p.stops};E(ae)}},[p,E]),B=f.useCallback((K,ae)=>{const le=[...p.stops];le[K]={...le[K],...ae},le.sort((Te,ze)=>Te.offset-ze.offset);const me=le.findIndex(Te=>Te.color===(ae.color??p.stops[K].color));me!==-1&&me!==m&&b(me),x({stops:le})},[p.stops,m,x]),X=f.useCallback(()=>{if(p.stops.length>=8)return;const K=.5,le=[...p.stops,{color:"#888888",offset:K}].sort((me,Te)=>me.offset-Te.offset);x({stops:le}),b(le.findIndex(me=>me.offset===K))},[p.stops,x]),j=f.useCallback(K=>{if(p.stops.length<=2)return;const ae=p.stops.filter((le,me)=>me!==K);x({stops:ae}),b(Math.min(m,ae.length-1))},[p.stops,m,x]),L=f.useCallback((K,ae)=>{if(!C.current)return;const le=C.current.getBoundingClientRect(),Te=Math.max(0,Math.min(K.clientX-le.left,le.width))/le.width;B(ae,{offset:Te})},[B]),D=f.useCallback((K,ae)=>{K.preventDefault(),K.stopPropagation(),b(ae);const le=K.clientX,me=K.clientY;let Te=!1;const ze=3,Y=$e=>{const it=Math.abs($e.clientX-le),Ye=Math.abs($e.clientY-me);(it>ze||Ye>ze)&&(Te=!0,T(!0),L($e,ae))},Ie=()=>{document.removeEventListener("mousemove",Y),document.removeEventListener("mouseup",Ie),Te||w(ae),setTimeout(()=>{T(!1)},0)};document.addEventListener("mousemove",Y),document.addEventListener("mouseup",Ie)},[L]),k=f.useCallback(K=>{if(y||p.stops.length>=8||K.target!==C.current||!C.current)return;const le=C.current.getBoundingClientRect(),me=K.clientX-le.left,Te=Math.max(0,Math.min(me/le.width,1)),ze=[...p.stops].sort((Ye,P)=>Ye.offset-P.offset);let Y=ze[0];for(let Ye=0;Ye<ze.length-1;Ye++)if(ze[Ye].offset<=Te&&ze[Ye+1].offset>=Te){Y=ze[Ye];break}const Ie=Y.color,$e=[...p.stops,{color:Ie,offset:Te}].sort((Ye,P)=>Ye.offset-P.offset);x({stops:$e});const it=$e.findIndex(Ye=>Ye.offset===Te);b(it)},[y,p.stops,x]);f.useMemo(()=>yi(p),[p]),f.useMemo(()=>{const K=[{key:"basic",label:d==="zh"?"基础":"Basic"},{key:"colorful",label:d==="zh"?"多彩":"Colorful"},{key:"sunset",label:d==="zh"?"日落":"Sunset"},{key:"nature",label:d==="zh"?"自然":"Nature"},{key:"metal",label:d==="zh"?"金属":"Metal"}];return s?K.filter(ae=>s.includes(ae.key)):K},[d,s]);const N=f.useMemo(()=>r?r.length>0&&typeof r[0]=="string"?r.map((K,ae)=>({id:`custom-${ae}`,name:`Custom ${ae+1}`,nameZh:`自定义 ${ae+1}`,category:"custom",config:IC(K),css:K})):r:pu,[r]),M=f.useCallback(()=>{var le;if(p.type!=="radial")return null;const{centerX:K,centerY:ae}=p;return(le=xh.find(me=>Math.abs(me.x-K)<.01&&Math.abs(me.y-ae)<.01))==null?void 0:le.key},[p]),Z=f.useMemo(()=>r&&r.length>0&&typeof r[0]=="string",[r]),he=f.useMemo(()=>yi(p),[p]),R=f.useCallback(K=>he===K,[he]),W=()=>{const K=pu.slice(0,10),ae=Z?N:[];return l.jsxs("div",{className:"ge-quick-presets",children:[l.jsx("div",{className:"ge-quick-presets-header",children:l.jsx("span",{className:"ge-quick-presets-title",children:d==="zh"?"预设":"Presets"})}),l.jsxs("div",{className:"ge-quick-presets-grid",children:[ae.map((le,me)=>{const Te=le.css||yi(le.config);return l.jsxs("button",{className:q("ge-quick-preset-item ge-quick-preset-item--custom",{"ge-quick-preset-item--selected":R(Te)}),onClick:()=>v(le),title:d==="zh"?le.nameZh:le.name,children:[l.jsx("div",{className:"ge-quick-preset-preview",style:{background:Te}}),u&&l.jsx("button",{className:"ge-quick-preset-delete",onClick:ze=>{ze.stopPropagation(),u(me)},children:"×"})]},le.id)}),K.map(le=>{const me=yi(le.config);return l.jsx("button",{className:q("ge-quick-preset-item",{"ge-quick-preset-item--selected":R(me)}),onClick:()=>v(le),title:d==="zh"?le.nameZh:le.name,children:l.jsx("div",{className:"ge-quick-preset-preview",style:{background:me}})},le.id)})]})]})},ce=()=>l.jsxs("div",{className:q("ge-custom-editor",{"ge-custom-editor--inline":a}),children:[l.jsx("div",{className:"ge-type-section",children:l.jsxs("div",{className:"ge-type-buttons",children:[l.jsx("button",{className:q("ge-type-btn",{active:p.type==="linear"}),onClick:()=>O("linear"),children:d==="zh"?"线性":"Linear"}),l.jsx("button",{className:q("ge-type-btn",{active:p.type==="radial"}),onClick:()=>O("radial"),children:d==="zh"?"径向":"Radial"})]})}),l.jsxs("div",{className:"ge-color-section",children:[l.jsxs("div",{className:"ge-section-header",children:[l.jsx("span",{className:"ge-section-title",children:d==="zh"?"颜色":"Colors"}),l.jsxs("div",{className:"ge-stop-actions",children:[l.jsx("button",{className:"ge-action-btn",onClick:X,disabled:p.stops.length>=8,title:d==="zh"?"添加色标":"Add stop",children:"+"}),l.jsx("button",{className:"ge-action-btn",onClick:()=>j(m),disabled:p.stops.length<=2,title:d==="zh"?"删除色标":"Remove stop",children:"−"})]})]}),l.jsx("div",{className:"ge-gradient-bar-wrapper",children:l.jsx("div",{ref:C,className:"ge-gradient-bar",style:{background:`linear-gradient(90deg, ${p.stops.map(K=>`${K.color} ${Math.round(K.offset*100)}%`).join(", ")})`},onClick:k,children:p.stops.map((K,ae)=>l.jsxs(at,{open:S===ae,onOpenChange:le=>w(le?ae:null),children:[l.jsx(lt,{asChild:!0,children:l.jsx("button",{className:q("ge-stop-handle",{selected:m===ae}),style:{left:`${K.offset*100}%`,backgroundColor:K.color},onMouseDown:le=>{D(le,ae)}})}),l.jsx(ct,{children:l.jsx(qe,{padding:4,className:"ge-color-picker-popover "+Dt,children:l.jsx(Ci,{value:K.color,onChange:le=>B(ae,{color:le}),showAlpha:!1,showEyeDropper:!0,showPresets:!0,showRecentColors:!0,showHexInput:!0})})})]},ae))})})]}),p.type==="radial"&&l.jsxs("div",{className:"ge-origin-section",children:[l.jsx("span",{className:"ge-section-title",children:d==="zh"?"原点":"Origin"}),l.jsx("div",{className:"ge-origin-buttons",children:xh.map(K=>l.jsx("button",{className:q("ge-origin-btn",{active:M()===K.key}),onClick:()=>x({centerX:K.x,centerY:K.y}),children:d==="zh"?K.labelZh:K.labelEn},K.key))})]}),p.type==="linear"&&l.jsxs("div",{className:"ge-angle-section",children:[l.jsxs("div",{className:"ge-section-header",children:[l.jsx("span",{className:"ge-section-title",children:d==="zh"?"角度":"Angle"}),l.jsxs("span",{className:"ge-angle-value",children:[p.angle,"°"]})]}),l.jsx("input",{type:"range",min:0,max:360,value:p.angle,onChange:K=>x({angle:Number(K.target.value)}),className:"ge-angle-slider"})]}),c&&l.jsx("div",{className:"ge-save-section",children:l.jsx("button",{className:"ge-save-btn",onClick:c,children:d==="zh"?"保存":"Save"})}),W()]});return o||a?l.jsx("div",{className:q("gradient-editor",{"gradient-editor--compact":o,"gradient-editor--inline":a}),children:ce()}):l.jsx("div",{className:"gradient-editor",children:ce()})},Da=At.CUSTOM_GRADIENTS,DC=({value:e,onChange:t,inline:n=!1})=>{const{language:i}=Ee(),{confirm:s,confirmDialog:r}=No(),[o,a]=f.useState([]),[c,u]=f.useState(e||Do);f.useEffect(()=>{let g=!0;return xn.get(Da).then(m=>{g&&m&&a(m)}).catch(m=>{console.warn("Failed to load gradient data:",m)}),()=>{g=!1}},[]),f.useEffect(()=>{e&&u(e)},[e]);const d=f.useCallback(g=>{u(g),t==null||t(g)},[t]),h=f.useCallback(()=>{const g=yi(c),b=[{id:`custom-${Date.now()}`,css:g},...o].slice(0,8);a(b),xn.set(Da,b).catch(S=>{console.warn("Failed to save custom gradients:",S)})},[c,o]),p=f.useCallback(async g=>{const m=o[g];if(!m||!await s({title:i==="zh"?"确认删除渐变预设":"Delete Gradient Preset",description:i==="zh"?"确定要删除这个自定义渐变预设吗?":"Are you sure you want to delete this custom gradient preset?",confirmText:i==="zh"?"删除":"Delete",cancelText:i==="zh"?"取消":"Cancel",danger:!0}))return;const S=o.filter(w=>w.id!==m.id);a(S),xn.set(Da,S).catch(w=>{console.warn("Failed to save custom gradients:",w)})},[s,o,i]);return l.jsxs(l.Fragment,{children:[l.jsx($g,{value:c,onChange:d,showPresets:!0,showHistory:!0,inline:n,customPresets:o.map(g=>g.css),onSavePreset:h,onDeletePreset:p}),r]})},NC=f.lazy(()=>Ne(()=>import("./tool-windows-hjm6YiPY.js").then(e=>e.p0),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.MediaLibraryModal}))),RC=[{value:"stretch",labelZh:"拉伸",labelEn:"Stretch",icon:"⬌"},{value:"tile",labelZh:"平铺",labelEn:"Tile",icon:"⊞"},{value:"fit",labelZh:"适应",labelEn:"Fit",icon:"⊡"}],jC=({value:e,onChange:t,onOpenMediaLibrary:n,externalMediaLibraryControl:i=!1})=>{const{language:s}=Ee(),[r,o]=f.useState(e||Nf),[a,c]=f.useState(!1),[u,d]=f.useState(!1),h=f.useRef(null);f.useEffect(()=>{e&&o(e)},[e]);const p=f.useCallback(E=>{const v={...r,...E};o(v),t==null||t(v)},[r,t]),g=f.useMemo(()=>dS(E=>{t==null||t(E)},300),[t]),m=f.useCallback(E=>{const v={...r,...E};o(v),g(v)},[r,g]),b=f.useCallback((E,v,x,O,B=1)=>{const X=parseFloat(v);if(isNaN(X))return;const j=Math.max(x,Math.min(O,X)),L=B===1?j:j/B;p({[E]:L})},[p]),S=f.useCallback(E=>{p({imageUrl:E.url}),c(!1)},[p]),w=f.useCallback(async E=>{var B;const v=(B=E.target.files)==null?void 0:B[0];if(!v)return;if(!v.type.startsWith("image/")){oe.warning(s==="zh"?"请选择图片文件":"Please select an image file");return}if(v.size>25*1024*1024){oe.warning(s==="zh"?"图片大小不能超过 25MB":"Image size cannot exceed 25MB");return}let x=v;if(v.size>10*1024*1024){const X=hS(v.size/1048576),j=oe.loading({content:s==="zh"?`正在压缩图片 (${(v.size/1024/1024).toFixed(1)}MB)...`:`Compressing image (${(v.size/1024/1024).toFixed(1)}MB)...`,duration:0,placement:"top"});try{x=await fS(v,X.targetSizeMB),oe.close(j),oe.success({content:s==="zh"?`压缩完成: ${(v.size/1024/1024).toFixed(1)}MB → ${(x.size/1024/1024).toFixed(1)}MB`:`Compressed: ${(v.size/1024/1024).toFixed(1)}MB → ${(x.size/1024/1024).toFixed(1)}MB`,duration:2})}catch(L){oe.close(j),console.error("[ImageFillPanel] Compression failed:",L),oe.warning(s==="zh"?"图片压缩失败":"Image compression failed");return}}const O=new FileReader;O.onload=X=>{var L;const j=(L=X.target)==null?void 0:L.result;p({imageUrl:j})},O.readAsDataURL(x),E.target.value=""},[s,p]),y=f.useCallback(()=>{var E;(E=h.current)==null||E.click()},[]),T=f.useCallback(()=>{i&&n?n():c(!0)},[i,n]),C=()=>r.imageUrl?l.jsxs("div",{className:"ifp-image-preview",children:[l.jsx("img",{src:r.imageUrl,alt:"Fill preview"}),l.jsx("button",{className:"ifp-image-remove",onClick:()=>p({imageUrl:""}),title:s==="zh"?"移除图片":"Remove image",children:"×"})]}):l.jsxs("div",{className:"ifp-image-placeholder",children:[l.jsx(jf,{size:32,className:"ifp-placeholder-icon"}),l.jsx("span",{className:"ifp-placeholder-text",children:s==="zh"?"选择图片":"Select Image"})]});return l.jsxs("div",{className:"image-fill-panel",children:[l.jsx("input",{ref:h,type:"file",accept:"image/*",style:{display:"none"},onChange:w}),l.jsxs("div",{className:"ifp-image-section",children:[l.jsx("div",{className:"ifp-image-container",onClick:()=>!r.imageUrl&&T(),children:C()}),l.jsxs("div",{className:"ifp-image-actions",children:[l.jsxs("button",{className:"ifp-action-btn ifp-action-btn--primary",onClick:T,children:[l.jsx(Ro,{size:14}),l.jsx("span",{children:s==="zh"?"素材库":"Library"})]}),l.jsxs("button",{className:"ifp-action-btn",onClick:y,children:[l.jsx(jo,{size:14}),l.jsx("span",{children:s==="zh"?"上传":"Upload"})]})]})]}),r.imageUrl&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"ifp-control-section",children:[l.jsx("div",{className:"ifp-section-title",children:s==="zh"?"平铺模式":"Fill Mode"}),l.jsx("div",{className:"ifp-mode-buttons",children:RC.map(E=>l.jsxs("button",{className:q("ifp-mode-btn",{active:r.mode===E.value}),onClick:()=>p({mode:E.value}),title:s==="zh"?E.labelZh:E.labelEn,children:[l.jsx("span",{className:"ifp-mode-icon",children:E.icon}),l.jsx("span",{className:"ifp-mode-label",children:s==="zh"?E.labelZh:E.labelEn})]},E.value))})]}),l.jsxs("div",{className:"ifp-advanced-section",children:[l.jsxs("button",{className:"ifp-advanced-toggle",onClick:()=>d(!u),children:[l.jsx("span",{children:s==="zh"?"高级设置":"Advanced"}),u?l.jsx(Rf,{size:14}):l.jsx(Ul,{size:14})]}),u&&l.jsxs("div",{className:"ifp-advanced-content",children:[l.jsxs("div",{className:"ifp-control-row",children:[l.jsx("label",{className:"ifp-control-label",children:s==="zh"?"缩放":"Scale"}),l.jsxs("div",{className:"ifp-control-input",children:[l.jsx("input",{type:"range",min:50,max:200,value:(r.scale??1)*100,onChange:E=>m({scale:Number(E.target.value)/100}),className:"ifp-slider"}),l.jsxs("div",{className:"ifp-control-value-wrapper",children:[l.jsx("input",{type:"number",className:"ifp-control-value-input",value:Math.round((r.scale??1)*100),min:50,max:200,onChange:E=>b("scale",E.target.value,50,200,100)}),l.jsx("span",{className:"ifp-control-unit",children:"%"})]})]})]}),l.jsxs("div",{className:"ifp-control-row",children:[l.jsx("label",{className:"ifp-control-label",children:s==="zh"?"X 偏移":"Offset X"}),l.jsxs("div",{className:"ifp-control-input",children:[l.jsx("input",{type:"range",min:-100,max:100,value:(r.offsetX??0)*100,onChange:E=>m({offsetX:Number(E.target.value)/100}),className:"ifp-slider"}),l.jsxs("div",{className:"ifp-control-value-wrapper",children:[l.jsx("input",{type:"number",className:"ifp-control-value-input",value:Math.round((r.offsetX??0)*100),min:-100,max:100,onChange:E=>b("offsetX",E.target.value,-100,100,100)}),l.jsx("span",{className:"ifp-control-unit",children:"%"})]})]})]}),l.jsxs("div",{className:"ifp-control-row",children:[l.jsx("label",{className:"ifp-control-label",children:s==="zh"?"Y 偏移":"Offset Y"}),l.jsxs("div",{className:"ifp-control-input",children:[l.jsx("input",{type:"range",min:-100,max:100,value:(r.offsetY??0)*100,onChange:E=>m({offsetY:Number(E.target.value)/100}),className:"ifp-slider"}),l.jsxs("div",{className:"ifp-control-value-wrapper",children:[l.jsx("input",{type:"number",className:"ifp-control-value-input",value:Math.round((r.offsetY??0)*100),min:-100,max:100,onChange:E=>b("offsetY",E.target.value,-100,100,100)}),l.jsx("span",{className:"ifp-control-unit",children:"%"})]})]})]}),l.jsxs("div",{className:"ifp-control-row",children:[l.jsx("label",{className:"ifp-control-label",children:s==="zh"?"旋转":"Rotation"}),l.jsxs("div",{className:"ifp-control-input",children:[l.jsx("input",{type:"range",min:0,max:360,value:r.rotation??0,onChange:E=>m({rotation:Number(E.target.value)}),className:"ifp-slider"}),l.jsxs("div",{className:"ifp-control-value-wrapper",children:[l.jsx("input",{type:"number",className:"ifp-control-value-input",value:r.rotation??0,min:0,max:360,onChange:E=>b("rotation",E.target.value,0,360,1)}),l.jsx("span",{className:"ifp-control-unit",children:"°"})]})]})]}),l.jsx("button",{className:"ifp-reset-btn",onClick:()=>p({scale:1,offsetX:0,offsetY:0,rotation:0}),children:s==="zh"?"重置":"Reset"})]})]})]}),!i&&a&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(NC,{isOpen:a,onClose:()=>c(!1),mode:ni.SELECT,filterType:Nn.IMAGE,onSelect:S,selectButtonText:s==="zh"?"使用此图片":"Use this image"})})]})},LC=[{value:"solid",labelZh:"纯色",labelEn:"Solid"},{value:"gradient",labelZh:"渐变",labelEn:"Gradient"},{value:"image",labelZh:"图片",labelEn:"Image"}],OC=({value:e,onSolidChange:t,onOpacityChange:n,onGradientChange:i,onImageChange:s,onFillTypeChange:r,showClose:o=!1,onClose:a,onOpenMediaLibrary:c})=>{const{language:u}=Ee(),d=f.useMemo(()=>e?Js(e)?pS(e):Rn(e)?e:{type:"solid",solid:{color:"#FFFFFF"}}:{type:"solid",solid:{color:"#FFFFFF"}},[e]),[h,p]=f.useState(d.type);f.useEffect(()=>{p(d.type)},[d.type]);const[g,m]=f.useState(d.gradient||Do),[b,S]=f.useState(d.image||Nf);f.useEffect(()=>{d.gradient&&m(d.gradient)},[d.gradient]),f.useEffect(()=>{d.image&&S(d.image)},[d.image]);const w=f.useCallback(v=>{p(v)},[]),y=f.useCallback(v=>{r==null||r("solid"),t==null||t(v)},[t,r]),T=f.useCallback(v=>{m(v),r==null||r("gradient"),i==null||i(v)},[i,r]),C=f.useCallback(v=>{S(v),r==null||r("image"),s==null||s(v)},[s,r]),E=f.useMemo(()=>Js(e)?e:Rn(e)&&e.solid?e.solid.color:"#FFFFFF",[e]);return l.jsxs("div",{className:"fill-panel",children:[l.jsxs("div",{className:"fill-panel__header",children:[l.jsx("span",{className:"fill-panel__title",children:u==="zh"?"填充":"Fill"}),o&&l.jsx("button",{className:"fill-panel__close",onClick:a,children:"×"})]}),l.jsx("div",{className:"fill-panel__tabs",children:LC.map(v=>l.jsx("button",{className:q("fill-panel__tab",{active:h===v.value}),onClick:()=>w(v.value),children:u==="zh"?v.labelZh:v.labelEn},v.value))}),l.jsxs("div",{className:"fill-panel__content",children:[h==="solid"&&l.jsx("div",{className:"fill-panel__solid",children:l.jsx(Ci,{value:E,onChange:y,onOpacityChange:n})}),h==="gradient"&&l.jsx(DC,{value:g,onChange:T}),h==="image"&&l.jsx(jC,{value:b,onChange:C,onOpenMediaLibrary:c,externalMediaLibraryControl:!!c})]})]})},BC=f.lazy(()=>Ne(()=>import("./index-vw8fjMik.js"),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.MediaLibraryModal}))),HC=({board:e,currentColor:t,title:n,children:i})=>{const{language:s}=Ee(),[r,o]=f.useState(!1),[a,c]=f.useState(!1),{hexColor:u,opacity:d}=f.useMemo(()=>{var C;if(!t)return{hexColor:void 0,opacity:100};if(Js(t)){const E=_i(t),v=os(t);return{hexColor:E,opacity:v}}if(Rn(t))switch(t.type){case"solid":if(t.solid){const E=_i(t.solid.color),v=os(t.solid.color);return{hexColor:E,opacity:v}}break;case"gradient":if((C=t.gradient)!=null&&C.stops[0])return{hexColor:t.gradient.stops[0].color,opacity:100};break;case"image":return{hexColor:"#888888",opacity:100}}return{hexColor:void 0,opacity:100}},[t]),h=!u||If(d)?l.jsx(gS,{}):void 0,p=f.useCallback(C=>{Z_(e,C),vC(e,C)},[e]),g=f.useCallback(C=>{q_(e,C)},[e]),m=f.useCallback(C=>{wC(e,C)},[e]),b=f.useCallback(C=>{bh(e,C)},[e]),S=f.useCallback(C=>{TC(e,C)},[e]),w=f.useCallback(()=>{o(!1)},[]),y=f.useCallback(()=>{c(!0)},[]),T=f.useCallback(C=>{bh(e,{imageUrl:C.url,mode:"stretch",scale:1,offsetX:0,offsetY:0,rotation:0}),c(!1)},[e]);return l.jsxs(at,{sideOffset:12,crossAxisOffset:40,open:r,onOpenChange:C=>{!C&&a||o(C)},placement:"left",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:q("property-button"),visible:!0,icon:h,type:"button",tooltip:n,"aria-label":n,onPointerUp:()=>{o(!r)},children:!h&&i})}),l.jsx(ct,{children:l.jsx(qe,{padding:0,className:q(`${Dt}`,"fill-setting"),children:l.jsx(OC,{value:t,onSolidChange:p,onOpacityChange:g,onGradientChange:m,onImageChange:b,onFillTypeChange:S,showClose:!0,onClose:w,onOpenMediaLibrary:y})})}),a&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(BC,{isOpen:a,onClose:()=>c(!1),mode:ni.SELECT,filterType:Nn.IMAGE,onSelect:T,selectButtonText:s==="zh"?"使用此图片":"Use this image"})})]})},FC=({board:e,currentRadius:t,title:n,selectionRect:i})=>{const[s,r]=f.useState(!1),[o,a]=f.useState({top:0,left:0}),[c,u]=f.useState(""),d=f.useRef(null),h=f.useRef(null),p=z.getBoardContainer(e),{t:g}=Ee(),m=n||g("toolbar.cornerRadius")||"圆角",b=t??0;f.useEffect(()=>{u(String(b))},[b]),f.useEffect(()=>{if(s&&d.current){const v=d.current.getBoundingClientRect(),x=220,O=8;let B=v.left+v.width/2-x/2,X=v.bottom+O;const j=window.innerWidth,L=window.innerHeight;B+x>j-16&&(B=j-x-16),B<16&&(B=16),X+40>L-16&&(X=v.top-40-O),a({left:B,top:X})}},[s]),f.useEffect(()=>{if(!s)return;const v=O=>{const B=O.target;h.current&&h.current.contains(B)||d.current&&d.current.contains(B)||B.closest(".popup-toolbar")!==null||r(!1)},x=setTimeout(()=>{document.addEventListener("mousedown",v)},100);return()=>{clearTimeout(x),document.removeEventListener("mousedown",v)}},[s]);const S=f.useCallback(v=>{const x=Math.max(0,Math.min(100,v));He(e).filter(B=>Je.isPenPath(B)).forEach(B=>{const X=e.children.findIndex(j=>j.id===B.id);X>=0&&ue.setNode(e,{cornerRadius:x},[X])})},[e]),w=f.useCallback(v=>{u(String(v)),S(v)},[S]),y=f.useCallback(v=>{u(v.target.value)},[]),T=f.useCallback(()=>{const v=parseInt(c,10);if(isNaN(v))u(String(b));else{const x=Math.max(0,Math.min(100,v));u(String(x)),S(x)}},[c,b,S]),C=f.useCallback(v=>{v.key==="Enter"&&v.target.blur()},[]),E=f.useCallback(()=>{r(!s)},[s]);return l.jsxs(l.Fragment,{children:[l.jsx(ne,{ref:d,className:q("property-button","corner-radius-button",{"is-active":s}),visible:!0,type:"button",tooltip:m,"aria-label":m,onPointerUp:E,children:l.jsx("svg",{viewBox:"0 0 24 24",width:"18",height:"18",children:l.jsx("path",{d:"M4 4 L4 14 Q4 20 10 20 L20 20",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),s&&p&&Lo.createPortal(l.jsx("div",{ref:h,className:q(Dt,"corner-radius-panel"),style:{position:"fixed",top:o.top,left:o.left,zIndex:5e3},onPointerDown:v=>v.stopPropagation(),onMouseDown:v=>v.stopPropagation(),children:l.jsx(qe,{padding:2,className:"corner-radius-setting-compact",children:l.jsxs("div",{className:"corner-radius-row",children:[l.jsx("span",{className:"corner-radius-label",children:m}),l.jsx("div",{className:"corner-radius-slider",children:l.jsx(Io,{value:b,min:0,max:100,step:1,onChange:v=>w(v),label:!1})}),l.jsx("input",{type:"text",className:"corner-radius-input",value:c,onChange:y,onBlur:T,onKeyDown:C}),l.jsx("span",{className:"corner-radius-unit",children:"%"})]})})}),p)]})},GC=(e,t)=>{try{return Ft(e,[t],!1)}catch{return null}},Eh=(e,t,n,i,s,r)=>{const o=e.children.findIndex(m=>m.id===t.id);if(o<0)return;const a=GC(e,t);if(!a)return;const c=(a.x-n.x)/n.width,u=(a.y-n.y)/n.height,d=i.x+c*i.width,h=i.y+u*i.height,p=a.width*s,g=a.height*r;if(Ti(t)){const m=[[d,h],[d+p,h+g]];ue.setNode(e,{points:m},[o])}else if(V.isDrawElement(t)){const m=[[d,h],[d+p,h+g]];ue.setNode(e,{points:m},[o])}else if(tn.isMindElement(e,t)){const m=[[d,h],[d+p,h+g]];ue.setNode(e,{points:m},[o])}else if(Xe.isFreehand(t)){const b=t.points.map(S=>{const w=(S[0]-n.x)/n.width,y=(S[1]-n.y)/n.height;return[i.x+w*i.width,i.y+y*i.height]});ue.setNode(e,{points:b},[o])}else if(Je.isPenPath(t)){const b=t.anchors.map(w=>{const y=[w.point[0]*s,w.point[1]*r],T=w.handleIn?[w.handleIn[0]*s,w.handleIn[1]*r]:void 0,C=w.handleOut?[w.handleOut[0]*s,w.handleOut[1]*r]:void 0;return{...w,point:y,handleIn:T,handleOut:C}}),S=[d,h];ue.setNode(e,{points:[S,S],anchors:b},[o])}},zC=({board:e})=>{const{language:t}=Ee(),n=t==="zh",i=He(e),[s,r]=f.useState(!0),[o,a]=f.useState(""),[c,u]=f.useState(""),[d,h]=f.useState(1),[p,g]=f.useState(!1),m=f.useRef(null),b=z.getBoardContainer(e),S=i.length>0?Ft(e,i,!1):null;f.useEffect(()=>{S&&(m.current?(a(Math.round(m.current.width).toString()),u(Math.round(m.current.height).toString()),m.current=null):(a(Math.round(S.width).toString()),u(Math.round(S.height).toString())),h(S.width/S.height))},[S==null?void 0:S.width,S==null?void 0:S.height]);const w=f.useCallback(v=>{const x=v.target.value;if(a(x),s&&S){const O=parseFloat(x);if(!isNaN(O)&&O>0){const B=Math.round(O/d);u(B.toString())}}},[s,d,S]),y=f.useCallback(v=>{const x=v.target.value;if(u(x),s&&S){const O=parseFloat(x);if(!isNaN(O)&&O>0){const B=Math.round(O*d);a(B.toString())}}},[s,d,S]),T=f.useCallback(()=>{if(!S||i.length===0)return;const v=parseFloat(o),x=parseFloat(c);if(isNaN(v)||isNaN(x)||v<=0||x<=0){a(Math.round(S.width).toString()),u(Math.round(S.height).toString());return}if(Math.abs(v-S.width)<.5&&Math.abs(x-S.height)<.5)return;m.current={width:v,height:x};const O=v/S.width,B=x/S.height,X={x:S.x,y:S.y,width:v,height:x};i.forEach(j=>{Eh(e,j,S,X,O,B)})},[e,i,S,o,c]),C=f.useCallback(v=>{if(!S||i.length===0)return;const x=v.width,O=v.height;a(x.toString()),u(O.toString()),m.current={width:x,height:O};const B=x/S.width,X=O/S.height,j={x:S.x,y:S.y,width:x,height:O};i.forEach(L=>{Eh(e,L,S,j,B,X)}),h(x/O),g(!1)},[e,i,S]),E=f.useCallback(v=>{v.key==="Enter"?(T(),v.target.blur()):v.key==="Escape"&&(S&&(a(Math.round(S.width).toString()),u(Math.round(S.height).toString())),v.target.blur())},[T,S]);return S?l.jsxs("div",{className:"size-input-container",children:[l.jsxs("div",{className:"size-input-group",children:[l.jsx("span",{className:"size-input-label",children:"W"}),l.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"size-input",value:o,onChange:w,onBlur:T,onKeyDown:E})]}),l.jsx("button",{className:`size-lock-button ${s?"locked":""}`,onClick:()=>r(!s),title:s?"解锁比例":"锁定比例",children:s?l.jsx(mS,{}):l.jsx(SS,{})}),l.jsxs("div",{className:"size-input-group",children:[l.jsx("span",{className:"size-input-label",children:"H"}),l.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"size-input",value:c,onChange:y,onBlur:T,onKeyDown:E})]}),l.jsxs(at,{open:p,onOpenChange:g,placement:"bottom-end",sideOffset:8,children:[l.jsx(lt,{asChild:!0,children:l.jsx("button",{className:`size-preset-button ${p?"active":""}`,title:n?"常用尺寸":"Preset Sizes",onClick:()=>g(!p),children:l.jsx(Ul,{size:12})})}),l.jsx(ct,{container:b,children:l.jsx("div",{className:"size-preset-panel",children:bS.map(v=>l.jsxs("div",{className:"size-preset-category",children:[l.jsx("div",{className:"size-preset-category-label",children:n?v.category:v.categoryEn}),v.items.map(x=>l.jsxs("button",{className:"size-preset-item",onClick:()=>C(x),children:[l.jsx("span",{className:"size-preset-item-label",children:n?x.label:x.labelEn}),l.jsxs("span",{className:"size-preset-item-size",children:[x.width," x ",x.height]})]},`${x.width}x${x.height}-${x.label}`))]},v.category))})})]})]}):null},VC=({board:e,title:t})=>{const{appState:n,setAppState:i}=Ut();return l.jsx(ne,{className:q("property-button"),visible:!0,icon:l.jsx(wS,{}),type:"button",tooltip:t,"aria-label":t,onPointerUp:()=>{const s=He(e)[0],r=yS(s);es.getLinkElement(r)||es.wrapLink(r,"链接",""),setTimeout(()=>{const c=es.getLinkElement(r)[0],u=vn.toDOMNode(r,c);i({...n,linkState:{editor:r,targetDom:u,targetElement:c,isEditing:!0,isHovering:!1,isHoveringOrigin:!1}})},0)}})},Xg={zh:[`一张写实的半身人像,一位身穿水蓝色连身裙的年轻韩国亚洲女人走进旅馆大厅,女人脸上带着温暖的微笑,左手拿着白色棒球帽,右手拉着黄色行李箱。
|
|
27
|
+
`)}function U_(e){var i,s;if(!e)return!1;const t=!!e.text||!!((i=e.data)!=null&&i.text),n=!!e.elements||!!((s=e.data)!=null&&s.elements);return t&&!n}function W_(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 i=t.getData("text/plain");if(i)return i}return null}const $_=e=>{const{insertFragment:t}=e;return e.insertFragment=(n,i,s)=>{if(U_(n)){const r=W_(n);if(r&&r.trim()){const o=r.trim(),a=oS(o);if(a&&a.length>0){const u=Math.round(window.innerWidth*.5);aS(e,a,i,u);return}const c=V_(o);Mo.insertText(e,i,c);return}}t(n,i,s)},e},X_=e=>{const t=e;return t.renderImage=(n,i)=>{const s=ko.createRoot(n);s.render(l.jsx(Hd,{...i}));let r={...i};return{destroy:()=>{setTimeout(()=>{s.unmount()},0)},update:a=>{r={...r,...a},s.render(l.jsx(Hd,{...r}))}}},$_(z_(t))},K_=f.forwardRef(({children:e,gap:t,align:n,justifyContent:i,className:s,style:r},o)=>l.jsx("div",{className:q("stack stack_horizontal",s),style:{"--gap":t,alignItems:n,justifyContent:i,...r},ref:o,children:e})),Y_=f.forwardRef(({children:e,gap:t,align:n,justifyContent:i,className:s,style:r},o)=>l.jsx("div",{className:q("stack stack_vertical",s),style:{"--gap":t,justifyItems:n,justifyContent:i,...r},ref:o,children:e})),pt={Row:K_,Col:Y_},qe=Gn.forwardRef(({children:e,padding:t,className:n,style:i,...s},r)=>l.jsx("div",{className:q("island",n),style:{"--padding":t,...i},ref:r,...s,children:e})),Vg=e=>e?typeof e=="string"?e:Rn(e)&&e.type==="solid"&&e.solid?e.solid.color:null:null,q_=(e,t)=>{zn.setFillColor(e,null,{getMemorizeKey:Vn,callback:(n,i)=>{if(!cn(e,n))return;const s=n.fill,r=Vg(s)||_f(e,n);if(!lS(r))return;const o=_i(r),a=gs(t)?o:ms(o,t);ue.setNode(e,{fill:a},i)}})},Z_=(e,t)=>{zn.setFillColor(e,null,{getMemorizeKey:Vn,callback:(n,i)=>{if(!cn(e,n))return;const s=n.fill,r=Vg(s)||_f(e,n),o=typeof r=="string"?os(r):void 0;zl(t)?ue.setNode(e,{fill:"none"},i):Vl(o)||gs(o)?ue.setNode(e,{fill:t},i):ue.setNode(e,{fill:ms(t,o)},i)}})},Q_=(e,t)=>{zn.setStrokeColor(e,null,{getMemorizeKey:Vn,callback:(n,i)=>{const s=Pf(e,n),r=_i(s),o=gs(t)?r:ms(r,t);ue.setNode(e,{strokeColor:o},i)}})},J_=(e,t)=>{zn.setStrokeColor(e,null,{getMemorizeKey:Vn,callback:(n,i)=>{const s=Pf(e,n),r=os(s);zl(t)?ue.setNode(e,{strokeColor:"none"},i):Vl(r)||gs(r)?ue.setNode(e,{strokeColor:t},i):ue.setNode(e,{strokeColor:ms(t,r)},i)}})},eC=(e,t)=>{zn.setStrokeStyle(e,t,{getMemorizeKey:Vn,callback:(n,i)=>{ue.setNode(e,{strokeStyle:t},i)}})},mh=(e,t)=>{zn.setStrokeWidth(e,t,{getMemorizeKey:Vn,callback:(n,i)=>{ue.setNode(e,{strokeWidth:t},i)}})},tC=(e,t,n)=>{const i=os(t);zl(n)?Qn.setTextColor(e,null):Vl(i)||gs(i)?Qn.setTextColor(e,n):Qn.setTextColor(e,ms(n,i))},nC=(e,t,n)=>{const i=_i(t),s=gs(n)?i:ms(i,n);Qn.setTextColor(e,s)},Ug=(e,t)=>{try{Qn.setFontSize(e,t,16)}catch{const i=_t(e);i&&i.length>0&&i.forEach(s=>{try{s.addMark("font-size",t)}catch(r){console.error("Failed to set font size mark:",r)}})}},iC=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),xe.addMark(i,"font-family",t)}catch(s){console.error("Failed to set font family:",s)}})},Ia=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),t?xe.addMark(i,"text-shadow",t):xe.removeMark(i,"text-shadow")}catch(s){console.error("Failed to set text shadow:",s)}})},Sh=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),t?xe.addMark(i,"text-gradient",t):xe.removeMark(i,"text-gradient")}catch(s){console.error("Failed to set text gradient:",s)}})},Wg=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),xe.addMark(i,"font-weight",String(t))}catch(s){console.error("Failed to set font weight:",s)}})},sC=(e,t)=>{try{let n;t==="left"?n=Ji.left:t==="center"?n=Ji.center:n=Ji.right,Qn.setTextAlign(e,n)}catch(n){console.error("Failed to set text align:",n)}},rC=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),xe.addMark(i,"line-height",String(t))}catch(s){console.error("Failed to set line height:",s)}})},oC=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i);const s=typeof t=="number"?`${t}px`:t;xe.addMark(i,"letter-spacing",s)}catch(s){console.error("Failed to set letter spacing:",s)}})},aC=e=>{const t=_t(e);t&&t.length>0&&t.forEach(n=>{try{It(n);const i=xe.marks(n);(i?!!i.bold:!1)?xe.removeMark(n,"bold"):xe.addMark(n,"bold",!0)}catch(i){console.error("Failed to toggle bold:",i)}})},lC=e=>{const t=_t(e);t&&t.length>0&&t.forEach(n=>{try{It(n);const i=xe.marks(n);(i?!!i.italic:!1)?xe.removeMark(n,"italic"):xe.addMark(n,"italic",!0)}catch(i){console.error("Failed to toggle italic:",i)}})},cC=e=>{const t=_t(e);t&&t.length>0&&t.forEach(n=>{try{It(n);const i=xe.marks(n);(i?!!i.underlined:!1)?xe.removeMark(n,"underlined"):xe.addMark(n,"underlined",!0)}catch(i){console.error("Failed to toggle underline:",i)}})},uC=e=>{const t=_t(e);t&&t.length>0&&t.forEach(n=>{try{It(n);const i=xe.marks(n);(i?!!i.strikethrough:!1)?xe.removeMark(n,"strikethrough"):xe.addMark(n,"strikethrough",!0)}catch(i){console.error("Failed to toggle strikethrough:",i)}})},dC=e=>{const t=_t(e);t&&t.length>0&&t.forEach(n=>{try{It(n);const i=xe.marks(n);(i?!!i.superscript:!1)?xe.removeMark(n,"superscript"):(xe.removeMark(n,"subscript"),xe.addMark(n,"superscript",!0))}catch(i){console.error("Failed to toggle superscript:",i)}})},hC=e=>{const t=_t(e);t&&t.length>0&&t.forEach(n=>{try{It(n);const i=xe.marks(n);(i?!!i.subscript:!1)?xe.removeMark(n,"subscript"):(xe.removeMark(n,"superscript"),xe.addMark(n,"subscript",!0))}catch(i){console.error("Failed to toggle subscript:",i)}})},fC=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),t?xe.addMark(i,"background-color",t):xe.removeMark(i,"background-color")}catch(s){console.error("Failed to set background color:",s)}})},pC=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),t&&t!=="none"?xe.addMark(i,"text-transform",t):xe.removeMark(i,"text-transform")}catch(s){console.error("Failed to set text transform:",s)}})},gC=(e,t,n)=>{const i=_t(e);i&&i.length>0&&i.forEach(s=>{try{It(s),t&&t>0?(xe.addMark(s,"text-stroke",t),n&&xe.addMark(s,"text-stroke-color",n)):(xe.removeMark(s,"text-stroke"),xe.removeMark(s,"text-stroke-color"))}catch(r){console.error("Failed to set text stroke:",r)}})},mC=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),t?xe.addMark(i,"text-decoration-style",t):xe.removeMark(i,"text-decoration-style")}catch(s){console.error("Failed to set text decoration style:",s)}})},SC=(e,t)=>{const n=_t(e);n&&n.length>0&&n.forEach(i=>{try{It(i),t?xe.addMark(i,"text-decoration-color",t):xe.removeMark(i,"text-decoration-color")}catch(s){console.error("Failed to set text decoration color:",s)}})},bC=e=>{const t=_t(e);if(t&&t.length>0){const n=t[0];try{return It(n),xe.marks(n)||{}}catch(i){return console.error("Failed to get text marks:",i),{}}}return{}},yC=e=>{const t=_t(e);if(t&&t.length>0){const n=t[0];try{const{selection:i}=n;if(i){const s=Array.from(xe.nodes(n,{at:i,match:r=>{const o=r.type==="paragraph",a="align"in r;return xe.isBlock(n,r)&&(o||a)}}));if(s.length>0){const[r]=s[0],o=r.align;if(o===Ji.right||o==="right")return"right";if(o===Ji.center||o==="center")return"center";if(o===Ji.left||o==="left")return"left"}}}catch(i){console.error("Failed to get text align:",i)}}return"left"},wC=(e,t)=>{zn.setFillColor(e,null,{getMemorizeKey:Vn,callback:(n,i)=>{if(!cn(e,n))return;const s=Cf(t),r={type:"gradient",gradient:t,fallbackColor:s};ue.setNode(e,{fill:s,fillConfig:r},i)}})},bh=(e,t)=>{zn.setFillColor(e,null,{getMemorizeKey:Vn,callback:(n,i)=>{if(!cn(e,n))return;const s="#FFFFFF",r={type:"image",image:t,fallbackColor:s};ue.setNode(e,{fill:s,fillConfig:r},i)}})},TC=(e,t)=>{zn.setFillColor(e,null,{getMemorizeKey:Vn,callback:(n,i)=>{if(!cn(e,n))return;const s=n.fillConfig,r=n.fill;if((s==null?void 0:s.type)!==t)switch(t){case"solid":{let o="#FFFFFF";typeof r=="string"&&r!=="none"?o=r:s!=null&&s.solid&&(o=s.solid.color),ue.setNode(e,{fill:o,fillConfig:void 0},i);break}case"gradient":{const o={type:"linear",angle:90,stops:[{offset:0,color:"#FFFFFF"},{offset:1,color:"#000000"}]},a=(s==null?void 0:s.gradient)||o,c=Cf(a),u={type:"gradient",gradient:a,fallbackColor:c};ue.setNode(e,{fill:c,fillConfig:u},i);break}case"image":{const o={imageUrl:"",mode:"stretch",scale:1,offsetX:0,offsetY:0,rotation:0},a="#FFFFFF",c={type:"image",image:(s==null?void 0:s.image)||o,fallbackColor:a};ue.setNode(e,{fill:a,fillConfig:c},i);break}default:return}}})},vC=(e,t)=>{const n=He(e);for(const i of n)if(Mt(i)){const s=e.children.findIndex(r=>r.id===i.id);s!==-1&&ue.setNode(e,{fillColor:t},[s])}},xC=({board:e,currentColor:t,fontColorIcon:n,title:i})=>{const[s,r]=f.useState(!1),o=z.getBoardContainer(e),a=f.useCallback(u=>{tC(e,t||u,u)},[e,t]),c=f.useCallback(u=>{t&&nC(e,t,u)},[e,t]);return l.jsxs(at,{sideOffset:12,open:s,onOpenChange:u=>{r(u)},placement:"top",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:q("property-button"),selected:s,visible:!0,icon:n,type:"button",tooltip:i,"aria-label":i,onPointerUp:()=>{r(!s)}})}),l.jsx(ct,{container:o,children:l.jsx(qe,{padding:4,className:q(`${Dt}`),children:l.jsx(Ci,{value:t,onChange:a,onOpacityChange:c})})})]})},Pl=[{key:"title",labelZh:"标题",labelEn:"Title",previewSize:26,...Pn.title},{key:"subtitle",labelZh:"副标题",labelEn:"Subtitle",previewSize:22,...Pn.subtitle},{key:"h1",labelZh:"标题 1",labelEn:"Heading 1",previewSize:20,...Pn.h1,divider:!0},{key:"h2",labelZh:"标题 2",labelEn:"Heading 2",previewSize:18,...Pn.h2},{key:"h3",labelZh:"标题 3",labelEn:"Heading 3",previewSize:16,...Pn.h3},{key:"h4",labelZh:"标题 4",labelEn:"Heading 4",previewSize:15,...Pn.h4},{key:"body",labelZh:"正文",labelEn:"Body",previewSize:14,...Pn.body,divider:!0},{key:"caption",labelZh:"注释",labelEn:"Caption",previewSize:13,...Pn.caption},{key:"footnote",labelZh:"脚注",labelEn:"Footnote",previewSize:12,...Pn.footnote}],EC=e=>{if(!e)return null;const t=parseInt(e,10);if(isNaN(t))return null;for(const n of Pl)if(n.fontSize===t)return n.key;return null},_C=({board:e,currentFontSize:t,title:n})=>{const[i,s]=f.useState(!1),{language:r}=Ee(),o=z.getBoardContainer(e),a=EC(t),c=f.useCallback(d=>{Ug(e,String(d.fontSize)),Wg(e,d.fontWeight),Qn.setTextColor(e,d.color),s(!1)},[e]),u=(()=>{if(a){const d=Pl.find(h=>h.key===a);if(d)return r==="zh"?d.labelZh:d.labelEn}return t||"16"})();return l.jsxs(at,{sideOffset:12,open:i,onOpenChange:s,placement:"bottom",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:q("property-button"),selected:i,visible:!0,type:"button",tooltip:n,"aria-label":n,onPointerUp:()=>s(!i),children:l.jsx("div",{style:{fontSize:"12px",fontWeight:"bold",minWidth:"20px"},children:u})})}),l.jsx(ct,{container:o,children:l.jsx(qe,{padding:4,className:q(`${Dt}`),children:l.jsxs(pt.Col,{gap:0,style:{minWidth:"200px"},children:[l.jsx("div",{style:{fontSize:"12px",color:"#666",marginBottom:"2px",padding:"4px 10px 0"},children:r==="zh"?"字体样式":"Font Style"}),l.jsx("div",{style:{maxHeight:"320px",overflowY:"auto"},children:Pl.map(d=>{const h=a===d.key;return l.jsxs(Gn.Fragment,{children:[d.divider&&l.jsx("div",{style:{height:"1px",backgroundColor:"#e8e8e8",margin:"4px 10px"}}),l.jsxs("div",{onClick:()=>c(d),style:{padding:"6px 10px",cursor:"pointer",backgroundColor:h?"#f0f7ff":"transparent",borderLeft:h?"3px solid #0052d9":"3px solid transparent",borderRadius:"2px",transition:"background-color 0.15s",display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:"8px"},onMouseEnter:p=>{h||(p.currentTarget.style.backgroundColor="#f5f5f5")},onMouseLeave:p=>{h||(p.currentTarget.style.backgroundColor="transparent")},children:[l.jsx("span",{style:{fontSize:`${d.previewSize}px`,fontWeight:d.fontWeight,color:d.color,lineHeight:1.4},children:r==="zh"?d.labelZh:d.labelEn}),l.jsxs("span",{style:{fontSize:"11px",color:"#bbb",flexShrink:0},children:[d.fontSize,"px"]})]})]},d.key)})})]})})})]})},CC=({board:e,currentColor:t,title:n,hasStrokeStyle:i,hasStrokeWidth:s,currentStrokeWidth:r,children:o})=>{const[a,c]=f.useState(!1),[u,d]=f.useState(String(r||2)),h=t&&_i(t),p=t?os(t):100,g=z.getBoardContainer(e);Gn.useEffect(()=>{d(String(r||2))},[r]);const m=If(p)?cS:Df(h)?uS:void 0,b=m?l.jsx(m,{}):void 0,S=x=>{eC(e,x)},w=f.useCallback(x=>{J_(e,x)},[e]),y=f.useCallback(x=>{Q_(e,x)},[e]),T=f.useCallback(x=>{mh(e,x),d(String(x))},[e]),C=f.useCallback(x=>{d(x.target.value)},[]),E=f.useCallback(()=>{const x=parseInt(u,10);!isNaN(x)&&x>=1&&x<=100?mh(e,x):d(String(r||2))},[e,u,r]),v=f.useCallback(x=>{x.key==="Enter"?(E(),x.target.blur()):x.key==="Escape"&&(d(String(r||2)),x.target.blur())},[E,r]);return l.jsxs(at,{sideOffset:12,crossAxisOffset:40,open:a,onOpenChange:x=>{c(x)},placement:"left",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:q("property-button"),visible:!0,icon:b,type:"button",tooltip:n,"aria-label":n,onPointerUp:()=>{c(!a)},children:!b&&o})}),l.jsx(ct,{container:g,children:l.jsx(qe,{padding:4,className:q(`${Dt}`,"stroke-setting",{"has-stroke-style":i}),children:l.jsxs(pt.Col,{children:[s&&l.jsx("div",{className:"stroke-width-section",style:{marginBottom:"8px"},children:l.jsxs(pt.Row,{gap:2,align:"center",children:[l.jsx("span",{style:{fontSize:"12px",color:"var(--color-on-surface)",whiteSpace:"nowrap"},children:"线宽:"}),l.jsx("div",{style:{flex:1,minWidth:"100px"},children:l.jsx(Io,{value:r||2,min:1,max:100,step:1,onChange:x=>T(x),label:!1})}),l.jsxs("div",{className:"stroke-width-input-wrapper",children:[l.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:u,onChange:C,onBlur:E,onKeyDown:v,className:"stroke-width-input"}),l.jsx("span",{className:"stroke-width-input-unit",children:"px"})]})]})}),i&&l.jsxs("div",{className:"stroke-style-section",children:[l.jsx("span",{className:"stroke-style-label",children:"样式:"}),l.jsxs(pt.Row,{className:q("stroke-style-picker"),children:[l.jsx(ne,{visible:!0,icon:l.jsx(kf,{}),type:"button",tooltip:"实线","aria-label":"实线",onPointerUp:()=>S(Jn.solid)}),l.jsx(ne,{visible:!0,icon:l.jsx(Af,{}),type:"button",tooltip:"虚线","aria-label":"虚线",onPointerUp:()=>S(Jn.dashed)}),l.jsx(ne,{visible:!0,icon:l.jsx(Mf,{}),type:"button",tooltip:"点线","aria-label":"点线",onPointerUp:()=>S(Jn.dotted)})]})]}),l.jsx(Ci,{value:t,onChange:w,onOpacityChange:y})]})})})]})},PC="drawnix-color-history",yh=24,wh=12,Th=Gr.createInstance({name:"drawnix",storeName:PC});let Me=null;function kl(e){const t=e.stops.map(n=>`${n.color}@${n.offset}`).join("|");return e.type==="linear"?`linear-${e.angle}-${t}`:`radial-${e.centerX}-${e.centerY}-${t}`}function kC(e,t){return kl(e)===kl(t)}class AC{constructor(){this.initialized=!1}async initialize(){if(!this.initialized)try{Me=await Th.getItem("history")||{colors:[],gradients:[]},this.initialized=!0}catch(t){console.error("[ColorHistoryService] Failed to initialize:",t),Me={colors:[],gradients:[]},this.initialized=!0}}async saveData(){if(Me)try{await Th.setItem("history",Me)}catch(t){console.error("[ColorHistoryService] Failed to save data:",t)}}async addColor(t){if(await this.initialize(),!Me)return;const n=t.toUpperCase(),i=Me.colors.findIndex(s=>s.color.toUpperCase()===n);if(i>=0){Me.colors[i].lastUsedAt=Date.now(),Me.colors[i].useCount+=1;const[s]=Me.colors.splice(i,1);Me.colors.unshift(s)}else Me.colors.unshift({color:n,lastUsedAt:Date.now(),useCount:1}),Me.colors.length>yh&&(Me.colors=Me.colors.slice(0,yh));await this.saveData()}async addGradient(t){if(await this.initialize(),!Me)return;const n=kl(t),i=Me.gradients.findIndex(s=>kC(s.config,t));if(i>=0){Me.gradients[i].lastUsedAt=Date.now(),Me.gradients[i].useCount+=1;const[s]=Me.gradients.splice(i,1);Me.gradients.unshift(s)}else Me.gradients.unshift({id:n,config:{...t},lastUsedAt:Date.now(),useCount:1}),Me.gradients.length>wh&&(Me.gradients=Me.gradients.slice(0,wh));await this.saveData()}async getColors(){return await this.initialize(),(Me==null?void 0:Me.colors)||[]}async getGradients(){return await this.initialize(),(Me==null?void 0:Me.gradients)||[]}async removeColor(t){if(await this.initialize(),!Me)return;const n=t.toUpperCase();Me.colors=Me.colors.filter(i=>i.color.toUpperCase()!==n),await this.saveData()}async removeGradient(t){await this.initialize(),Me&&(Me.gradients=Me.gradients.filter(n=>n.id!==t),await this.saveData())}async clearAll(){Me={colors:[],gradients:[]},await this.saveData()}resetCache(){Me=null,this.initialized=!1}}const Sn=new AC;function MC(){const[e,t]=f.useState([]),[n,i]=f.useState([]),[s,r]=f.useState(!0),o=f.useCallback(async()=>{try{const[h,p]=await Promise.all([Sn.getColors(),Sn.getGradients()]);t(h),i(p)}catch(h){console.error("[useColorHistory] Failed to load data:",h)}finally{r(!1)}},[]);f.useEffect(()=>{o()},[o]);const a=f.useCallback(async h=>{await Sn.addColor(h);const p=await Sn.getColors();t(p)},[]),c=f.useCallback(async h=>{await Sn.addGradient(h);const p=await Sn.getGradients();i(p)},[]),u=f.useCallback(async h=>{await Sn.removeColor(h);const p=await Sn.getColors();t(p)},[]),d=f.useCallback(async h=>{await Sn.removeGradient(h);const p=await Sn.getGradients();i(p)},[]);return{colors:e,gradients:n,isLoading:s,addColor:a,addGradient:c,removeColor:u,removeGradient:d,refresh:o}}function yi(e){const t=e.stops.map(n=>`${n.color} ${Math.round(n.offset*100)}%`).join(", ");if(e.type==="linear")return`linear-gradient(${e.angle}deg, ${t})`;{const n=Math.round(e.centerX*100),i=Math.round(e.centerY*100);return`radial-gradient(circle at ${n}% ${i}%, ${t})`}}function IC(e){const t=e.match(/linear-gradient\((\d+)deg,\s*(.+)\)/);if(t){const i=parseInt(t[1],10),s=t[2],r=vh(s);return{type:"linear",angle:i,stops:r.length>=2?r:[{color:"#FF6B6B",offset:0},{color:"#4ECDC4",offset:1}]}}const n=e.match(/radial-gradient\(circle(?:\s+at\s+(\d+)%\s+(\d+)%)?,\s*(.+)\)/);if(n){const i=n[1]?parseInt(n[1],10)/100:.5,s=n[2]?parseInt(n[2],10)/100:.5,r=n[3],o=vh(r);return{type:"radial",centerX:i,centerY:s,stops:o.length>=2?o:[{color:"#FF6B6B",offset:0},{color:"#4ECDC4",offset:1}]}}return Do}function vh(e){const t=[],n=/(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\))\s+(\d+)%/g;let i;for(;(i=n.exec(e))!==null;)t.push({color:i[1],offset:parseInt(i[2],10)/100});return t}const xh=[{key:"left",labelZh:"左",labelEn:"Left",x:0,y:.5},{key:"center",labelZh:"中心",labelEn:"Center",x:.5,y:.5},{key:"top-left",labelZh:"左上",labelEn:"Top left",x:0,y:0},{key:"top",labelZh:"上",labelEn:"Top",x:.5,y:0},{key:"right",labelZh:"右",labelEn:"Right",x:1,y:.5},{key:"bottom",labelZh:"下",labelEn:"Bottom",x:.5,y:1}],$g=({value:e,onChange:t,showPresets:n=!0,showHistory:i=!0,presetCategories:s,customPresets:r,compact:o=!1,inline:a=!1,onSavePreset:c,onDeletePreset:u})=>{const{language:d}=Ee(),{addGradient:h}=MC(),[p,g]=f.useState(e||Do),[m,b]=f.useState(0),[S,w]=f.useState(null),[y,T]=f.useState(!1),C=f.useRef(null);f.useEffect(()=>{e&&g(e)},[e]);const E=f.useCallback(K=>{g(K),t==null||t(K),h(K)},[t,h]),v=f.useCallback(K=>{E(K.config)},[E]),x=f.useCallback(K=>{const ae={...p,...K};E(ae)},[p,E]),O=f.useCallback(K=>{if(p.type!==K)if(K==="linear"){const ae={type:"linear",angle:90,stops:p.stops};E(ae)}else{const ae={type:"radial",centerX:.5,centerY:.5,stops:p.stops};E(ae)}},[p,E]),B=f.useCallback((K,ae)=>{const le=[...p.stops];le[K]={...le[K],...ae},le.sort((Te,ze)=>Te.offset-ze.offset);const me=le.findIndex(Te=>Te.color===(ae.color??p.stops[K].color));me!==-1&&me!==m&&b(me),x({stops:le})},[p.stops,m,x]),X=f.useCallback(()=>{if(p.stops.length>=8)return;const K=.5,le=[...p.stops,{color:"#888888",offset:K}].sort((me,Te)=>me.offset-Te.offset);x({stops:le}),b(le.findIndex(me=>me.offset===K))},[p.stops,x]),j=f.useCallback(K=>{if(p.stops.length<=2)return;const ae=p.stops.filter((le,me)=>me!==K);x({stops:ae}),b(Math.min(m,ae.length-1))},[p.stops,m,x]),L=f.useCallback((K,ae)=>{if(!C.current)return;const le=C.current.getBoundingClientRect(),Te=Math.max(0,Math.min(K.clientX-le.left,le.width))/le.width;B(ae,{offset:Te})},[B]),D=f.useCallback((K,ae)=>{K.preventDefault(),K.stopPropagation(),b(ae);const le=K.clientX,me=K.clientY;let Te=!1;const ze=3,Y=$e=>{const it=Math.abs($e.clientX-le),Ye=Math.abs($e.clientY-me);(it>ze||Ye>ze)&&(Te=!0,T(!0),L($e,ae))},Ie=()=>{document.removeEventListener("mousemove",Y),document.removeEventListener("mouseup",Ie),Te||w(ae),setTimeout(()=>{T(!1)},0)};document.addEventListener("mousemove",Y),document.addEventListener("mouseup",Ie)},[L]),k=f.useCallback(K=>{if(y||p.stops.length>=8||K.target!==C.current||!C.current)return;const le=C.current.getBoundingClientRect(),me=K.clientX-le.left,Te=Math.max(0,Math.min(me/le.width,1)),ze=[...p.stops].sort((Ye,P)=>Ye.offset-P.offset);let Y=ze[0];for(let Ye=0;Ye<ze.length-1;Ye++)if(ze[Ye].offset<=Te&&ze[Ye+1].offset>=Te){Y=ze[Ye];break}const Ie=Y.color,$e=[...p.stops,{color:Ie,offset:Te}].sort((Ye,P)=>Ye.offset-P.offset);x({stops:$e});const it=$e.findIndex(Ye=>Ye.offset===Te);b(it)},[y,p.stops,x]);f.useMemo(()=>yi(p),[p]),f.useMemo(()=>{const K=[{key:"basic",label:d==="zh"?"基础":"Basic"},{key:"colorful",label:d==="zh"?"多彩":"Colorful"},{key:"sunset",label:d==="zh"?"日落":"Sunset"},{key:"nature",label:d==="zh"?"自然":"Nature"},{key:"metal",label:d==="zh"?"金属":"Metal"}];return s?K.filter(ae=>s.includes(ae.key)):K},[d,s]);const N=f.useMemo(()=>r?r.length>0&&typeof r[0]=="string"?r.map((K,ae)=>({id:`custom-${ae}`,name:`Custom ${ae+1}`,nameZh:`自定义 ${ae+1}`,category:"custom",config:IC(K),css:K})):r:pu,[r]),M=f.useCallback(()=>{var le;if(p.type!=="radial")return null;const{centerX:K,centerY:ae}=p;return(le=xh.find(me=>Math.abs(me.x-K)<.01&&Math.abs(me.y-ae)<.01))==null?void 0:le.key},[p]),Z=f.useMemo(()=>r&&r.length>0&&typeof r[0]=="string",[r]),he=f.useMemo(()=>yi(p),[p]),R=f.useCallback(K=>he===K,[he]),W=()=>{const K=pu.slice(0,10),ae=Z?N:[];return l.jsxs("div",{className:"ge-quick-presets",children:[l.jsx("div",{className:"ge-quick-presets-header",children:l.jsx("span",{className:"ge-quick-presets-title",children:d==="zh"?"预设":"Presets"})}),l.jsxs("div",{className:"ge-quick-presets-grid",children:[ae.map((le,me)=>{const Te=le.css||yi(le.config);return l.jsxs("button",{className:q("ge-quick-preset-item ge-quick-preset-item--custom",{"ge-quick-preset-item--selected":R(Te)}),onClick:()=>v(le),title:d==="zh"?le.nameZh:le.name,children:[l.jsx("div",{className:"ge-quick-preset-preview",style:{background:Te}}),u&&l.jsx("button",{className:"ge-quick-preset-delete",onClick:ze=>{ze.stopPropagation(),u(me)},children:"×"})]},le.id)}),K.map(le=>{const me=yi(le.config);return l.jsx("button",{className:q("ge-quick-preset-item",{"ge-quick-preset-item--selected":R(me)}),onClick:()=>v(le),title:d==="zh"?le.nameZh:le.name,children:l.jsx("div",{className:"ge-quick-preset-preview",style:{background:me}})},le.id)})]})]})},ce=()=>l.jsxs("div",{className:q("ge-custom-editor",{"ge-custom-editor--inline":a}),children:[l.jsx("div",{className:"ge-type-section",children:l.jsxs("div",{className:"ge-type-buttons",children:[l.jsx("button",{className:q("ge-type-btn",{active:p.type==="linear"}),onClick:()=>O("linear"),children:d==="zh"?"线性":"Linear"}),l.jsx("button",{className:q("ge-type-btn",{active:p.type==="radial"}),onClick:()=>O("radial"),children:d==="zh"?"径向":"Radial"})]})}),l.jsxs("div",{className:"ge-color-section",children:[l.jsxs("div",{className:"ge-section-header",children:[l.jsx("span",{className:"ge-section-title",children:d==="zh"?"颜色":"Colors"}),l.jsxs("div",{className:"ge-stop-actions",children:[l.jsx("button",{className:"ge-action-btn",onClick:X,disabled:p.stops.length>=8,title:d==="zh"?"添加色标":"Add stop",children:"+"}),l.jsx("button",{className:"ge-action-btn",onClick:()=>j(m),disabled:p.stops.length<=2,title:d==="zh"?"删除色标":"Remove stop",children:"−"})]})]}),l.jsx("div",{className:"ge-gradient-bar-wrapper",children:l.jsx("div",{ref:C,className:"ge-gradient-bar",style:{background:`linear-gradient(90deg, ${p.stops.map(K=>`${K.color} ${Math.round(K.offset*100)}%`).join(", ")})`},onClick:k,children:p.stops.map((K,ae)=>l.jsxs(at,{open:S===ae,onOpenChange:le=>w(le?ae:null),children:[l.jsx(lt,{asChild:!0,children:l.jsx("button",{className:q("ge-stop-handle",{selected:m===ae}),style:{left:`${K.offset*100}%`,backgroundColor:K.color},onMouseDown:le=>{D(le,ae)}})}),l.jsx(ct,{children:l.jsx(qe,{padding:4,className:"ge-color-picker-popover "+Dt,children:l.jsx(Ci,{value:K.color,onChange:le=>B(ae,{color:le}),showAlpha:!1,showEyeDropper:!0,showPresets:!0,showRecentColors:!0,showHexInput:!0})})})]},ae))})})]}),p.type==="radial"&&l.jsxs("div",{className:"ge-origin-section",children:[l.jsx("span",{className:"ge-section-title",children:d==="zh"?"原点":"Origin"}),l.jsx("div",{className:"ge-origin-buttons",children:xh.map(K=>l.jsx("button",{className:q("ge-origin-btn",{active:M()===K.key}),onClick:()=>x({centerX:K.x,centerY:K.y}),children:d==="zh"?K.labelZh:K.labelEn},K.key))})]}),p.type==="linear"&&l.jsxs("div",{className:"ge-angle-section",children:[l.jsxs("div",{className:"ge-section-header",children:[l.jsx("span",{className:"ge-section-title",children:d==="zh"?"角度":"Angle"}),l.jsxs("span",{className:"ge-angle-value",children:[p.angle,"°"]})]}),l.jsx("input",{type:"range",min:0,max:360,value:p.angle,onChange:K=>x({angle:Number(K.target.value)}),className:"ge-angle-slider"})]}),c&&l.jsx("div",{className:"ge-save-section",children:l.jsx("button",{className:"ge-save-btn",onClick:c,children:d==="zh"?"保存":"Save"})}),W()]});return o||a?l.jsx("div",{className:q("gradient-editor",{"gradient-editor--compact":o,"gradient-editor--inline":a}),children:ce()}):l.jsx("div",{className:"gradient-editor",children:ce()})},Da=At.CUSTOM_GRADIENTS,DC=({value:e,onChange:t,inline:n=!1})=>{const{language:i}=Ee(),{confirm:s,confirmDialog:r}=No(),[o,a]=f.useState([]),[c,u]=f.useState(e||Do);f.useEffect(()=>{let g=!0;return xn.get(Da).then(m=>{g&&m&&a(m)}).catch(m=>{console.warn("Failed to load gradient data:",m)}),()=>{g=!1}},[]),f.useEffect(()=>{e&&u(e)},[e]);const d=f.useCallback(g=>{u(g),t==null||t(g)},[t]),h=f.useCallback(()=>{const g=yi(c),b=[{id:`custom-${Date.now()}`,css:g},...o].slice(0,8);a(b),xn.set(Da,b).catch(S=>{console.warn("Failed to save custom gradients:",S)})},[c,o]),p=f.useCallback(async g=>{const m=o[g];if(!m||!await s({title:i==="zh"?"确认删除渐变预设":"Delete Gradient Preset",description:i==="zh"?"确定要删除这个自定义渐变预设吗?":"Are you sure you want to delete this custom gradient preset?",confirmText:i==="zh"?"删除":"Delete",cancelText:i==="zh"?"取消":"Cancel",danger:!0}))return;const S=o.filter(w=>w.id!==m.id);a(S),xn.set(Da,S).catch(w=>{console.warn("Failed to save custom gradients:",w)})},[s,o,i]);return l.jsxs(l.Fragment,{children:[l.jsx($g,{value:c,onChange:d,showPresets:!0,showHistory:!0,inline:n,customPresets:o.map(g=>g.css),onSavePreset:h,onDeletePreset:p}),r]})},NC=f.lazy(()=>Ne(()=>import("./tool-windows-C4D0lII2.js").then(e=>e.p0),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.MediaLibraryModal}))),RC=[{value:"stretch",labelZh:"拉伸",labelEn:"Stretch",icon:"⬌"},{value:"tile",labelZh:"平铺",labelEn:"Tile",icon:"⊞"},{value:"fit",labelZh:"适应",labelEn:"Fit",icon:"⊡"}],jC=({value:e,onChange:t,onOpenMediaLibrary:n,externalMediaLibraryControl:i=!1})=>{const{language:s}=Ee(),[r,o]=f.useState(e||Nf),[a,c]=f.useState(!1),[u,d]=f.useState(!1),h=f.useRef(null);f.useEffect(()=>{e&&o(e)},[e]);const p=f.useCallback(E=>{const v={...r,...E};o(v),t==null||t(v)},[r,t]),g=f.useMemo(()=>dS(E=>{t==null||t(E)},300),[t]),m=f.useCallback(E=>{const v={...r,...E};o(v),g(v)},[r,g]),b=f.useCallback((E,v,x,O,B=1)=>{const X=parseFloat(v);if(isNaN(X))return;const j=Math.max(x,Math.min(O,X)),L=B===1?j:j/B;p({[E]:L})},[p]),S=f.useCallback(E=>{p({imageUrl:E.url}),c(!1)},[p]),w=f.useCallback(async E=>{var B;const v=(B=E.target.files)==null?void 0:B[0];if(!v)return;if(!v.type.startsWith("image/")){oe.warning(s==="zh"?"请选择图片文件":"Please select an image file");return}if(v.size>25*1024*1024){oe.warning(s==="zh"?"图片大小不能超过 25MB":"Image size cannot exceed 25MB");return}let x=v;if(v.size>10*1024*1024){const X=hS(v.size/1048576),j=oe.loading({content:s==="zh"?`正在压缩图片 (${(v.size/1024/1024).toFixed(1)}MB)...`:`Compressing image (${(v.size/1024/1024).toFixed(1)}MB)...`,duration:0,placement:"top"});try{x=await fS(v,X.targetSizeMB),oe.close(j),oe.success({content:s==="zh"?`压缩完成: ${(v.size/1024/1024).toFixed(1)}MB → ${(x.size/1024/1024).toFixed(1)}MB`:`Compressed: ${(v.size/1024/1024).toFixed(1)}MB → ${(x.size/1024/1024).toFixed(1)}MB`,duration:2})}catch(L){oe.close(j),console.error("[ImageFillPanel] Compression failed:",L),oe.warning(s==="zh"?"图片压缩失败":"Image compression failed");return}}const O=new FileReader;O.onload=X=>{var L;const j=(L=X.target)==null?void 0:L.result;p({imageUrl:j})},O.readAsDataURL(x),E.target.value=""},[s,p]),y=f.useCallback(()=>{var E;(E=h.current)==null||E.click()},[]),T=f.useCallback(()=>{i&&n?n():c(!0)},[i,n]),C=()=>r.imageUrl?l.jsxs("div",{className:"ifp-image-preview",children:[l.jsx("img",{src:r.imageUrl,alt:"Fill preview"}),l.jsx("button",{className:"ifp-image-remove",onClick:()=>p({imageUrl:""}),title:s==="zh"?"移除图片":"Remove image",children:"×"})]}):l.jsxs("div",{className:"ifp-image-placeholder",children:[l.jsx(jf,{size:32,className:"ifp-placeholder-icon"}),l.jsx("span",{className:"ifp-placeholder-text",children:s==="zh"?"选择图片":"Select Image"})]});return l.jsxs("div",{className:"image-fill-panel",children:[l.jsx("input",{ref:h,type:"file",accept:"image/*",style:{display:"none"},onChange:w}),l.jsxs("div",{className:"ifp-image-section",children:[l.jsx("div",{className:"ifp-image-container",onClick:()=>!r.imageUrl&&T(),children:C()}),l.jsxs("div",{className:"ifp-image-actions",children:[l.jsxs("button",{className:"ifp-action-btn ifp-action-btn--primary",onClick:T,children:[l.jsx(Ro,{size:14}),l.jsx("span",{children:s==="zh"?"素材库":"Library"})]}),l.jsxs("button",{className:"ifp-action-btn",onClick:y,children:[l.jsx(jo,{size:14}),l.jsx("span",{children:s==="zh"?"上传":"Upload"})]})]})]}),r.imageUrl&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"ifp-control-section",children:[l.jsx("div",{className:"ifp-section-title",children:s==="zh"?"平铺模式":"Fill Mode"}),l.jsx("div",{className:"ifp-mode-buttons",children:RC.map(E=>l.jsxs("button",{className:q("ifp-mode-btn",{active:r.mode===E.value}),onClick:()=>p({mode:E.value}),title:s==="zh"?E.labelZh:E.labelEn,children:[l.jsx("span",{className:"ifp-mode-icon",children:E.icon}),l.jsx("span",{className:"ifp-mode-label",children:s==="zh"?E.labelZh:E.labelEn})]},E.value))})]}),l.jsxs("div",{className:"ifp-advanced-section",children:[l.jsxs("button",{className:"ifp-advanced-toggle",onClick:()=>d(!u),children:[l.jsx("span",{children:s==="zh"?"高级设置":"Advanced"}),u?l.jsx(Rf,{size:14}):l.jsx(Ul,{size:14})]}),u&&l.jsxs("div",{className:"ifp-advanced-content",children:[l.jsxs("div",{className:"ifp-control-row",children:[l.jsx("label",{className:"ifp-control-label",children:s==="zh"?"缩放":"Scale"}),l.jsxs("div",{className:"ifp-control-input",children:[l.jsx("input",{type:"range",min:50,max:200,value:(r.scale??1)*100,onChange:E=>m({scale:Number(E.target.value)/100}),className:"ifp-slider"}),l.jsxs("div",{className:"ifp-control-value-wrapper",children:[l.jsx("input",{type:"number",className:"ifp-control-value-input",value:Math.round((r.scale??1)*100),min:50,max:200,onChange:E=>b("scale",E.target.value,50,200,100)}),l.jsx("span",{className:"ifp-control-unit",children:"%"})]})]})]}),l.jsxs("div",{className:"ifp-control-row",children:[l.jsx("label",{className:"ifp-control-label",children:s==="zh"?"X 偏移":"Offset X"}),l.jsxs("div",{className:"ifp-control-input",children:[l.jsx("input",{type:"range",min:-100,max:100,value:(r.offsetX??0)*100,onChange:E=>m({offsetX:Number(E.target.value)/100}),className:"ifp-slider"}),l.jsxs("div",{className:"ifp-control-value-wrapper",children:[l.jsx("input",{type:"number",className:"ifp-control-value-input",value:Math.round((r.offsetX??0)*100),min:-100,max:100,onChange:E=>b("offsetX",E.target.value,-100,100,100)}),l.jsx("span",{className:"ifp-control-unit",children:"%"})]})]})]}),l.jsxs("div",{className:"ifp-control-row",children:[l.jsx("label",{className:"ifp-control-label",children:s==="zh"?"Y 偏移":"Offset Y"}),l.jsxs("div",{className:"ifp-control-input",children:[l.jsx("input",{type:"range",min:-100,max:100,value:(r.offsetY??0)*100,onChange:E=>m({offsetY:Number(E.target.value)/100}),className:"ifp-slider"}),l.jsxs("div",{className:"ifp-control-value-wrapper",children:[l.jsx("input",{type:"number",className:"ifp-control-value-input",value:Math.round((r.offsetY??0)*100),min:-100,max:100,onChange:E=>b("offsetY",E.target.value,-100,100,100)}),l.jsx("span",{className:"ifp-control-unit",children:"%"})]})]})]}),l.jsxs("div",{className:"ifp-control-row",children:[l.jsx("label",{className:"ifp-control-label",children:s==="zh"?"旋转":"Rotation"}),l.jsxs("div",{className:"ifp-control-input",children:[l.jsx("input",{type:"range",min:0,max:360,value:r.rotation??0,onChange:E=>m({rotation:Number(E.target.value)}),className:"ifp-slider"}),l.jsxs("div",{className:"ifp-control-value-wrapper",children:[l.jsx("input",{type:"number",className:"ifp-control-value-input",value:r.rotation??0,min:0,max:360,onChange:E=>b("rotation",E.target.value,0,360,1)}),l.jsx("span",{className:"ifp-control-unit",children:"°"})]})]})]}),l.jsx("button",{className:"ifp-reset-btn",onClick:()=>p({scale:1,offsetX:0,offsetY:0,rotation:0}),children:s==="zh"?"重置":"Reset"})]})]})]}),!i&&a&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(NC,{isOpen:a,onClose:()=>c(!1),mode:ni.SELECT,filterType:Nn.IMAGE,onSelect:S,selectButtonText:s==="zh"?"使用此图片":"Use this image"})})]})},LC=[{value:"solid",labelZh:"纯色",labelEn:"Solid"},{value:"gradient",labelZh:"渐变",labelEn:"Gradient"},{value:"image",labelZh:"图片",labelEn:"Image"}],OC=({value:e,onSolidChange:t,onOpacityChange:n,onGradientChange:i,onImageChange:s,onFillTypeChange:r,showClose:o=!1,onClose:a,onOpenMediaLibrary:c})=>{const{language:u}=Ee(),d=f.useMemo(()=>e?Js(e)?pS(e):Rn(e)?e:{type:"solid",solid:{color:"#FFFFFF"}}:{type:"solid",solid:{color:"#FFFFFF"}},[e]),[h,p]=f.useState(d.type);f.useEffect(()=>{p(d.type)},[d.type]);const[g,m]=f.useState(d.gradient||Do),[b,S]=f.useState(d.image||Nf);f.useEffect(()=>{d.gradient&&m(d.gradient)},[d.gradient]),f.useEffect(()=>{d.image&&S(d.image)},[d.image]);const w=f.useCallback(v=>{p(v)},[]),y=f.useCallback(v=>{r==null||r("solid"),t==null||t(v)},[t,r]),T=f.useCallback(v=>{m(v),r==null||r("gradient"),i==null||i(v)},[i,r]),C=f.useCallback(v=>{S(v),r==null||r("image"),s==null||s(v)},[s,r]),E=f.useMemo(()=>Js(e)?e:Rn(e)&&e.solid?e.solid.color:"#FFFFFF",[e]);return l.jsxs("div",{className:"fill-panel",children:[l.jsxs("div",{className:"fill-panel__header",children:[l.jsx("span",{className:"fill-panel__title",children:u==="zh"?"填充":"Fill"}),o&&l.jsx("button",{className:"fill-panel__close",onClick:a,children:"×"})]}),l.jsx("div",{className:"fill-panel__tabs",children:LC.map(v=>l.jsx("button",{className:q("fill-panel__tab",{active:h===v.value}),onClick:()=>w(v.value),children:u==="zh"?v.labelZh:v.labelEn},v.value))}),l.jsxs("div",{className:"fill-panel__content",children:[h==="solid"&&l.jsx("div",{className:"fill-panel__solid",children:l.jsx(Ci,{value:E,onChange:y,onOpacityChange:n})}),h==="gradient"&&l.jsx(DC,{value:g,onChange:T}),h==="image"&&l.jsx(jC,{value:b,onChange:C,onOpenMediaLibrary:c,externalMediaLibraryControl:!!c})]})]})},BC=f.lazy(()=>Ne(()=>import("./index-CKBsqCzR.js"),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.MediaLibraryModal}))),HC=({board:e,currentColor:t,title:n,children:i})=>{const{language:s}=Ee(),[r,o]=f.useState(!1),[a,c]=f.useState(!1),{hexColor:u,opacity:d}=f.useMemo(()=>{var C;if(!t)return{hexColor:void 0,opacity:100};if(Js(t)){const E=_i(t),v=os(t);return{hexColor:E,opacity:v}}if(Rn(t))switch(t.type){case"solid":if(t.solid){const E=_i(t.solid.color),v=os(t.solid.color);return{hexColor:E,opacity:v}}break;case"gradient":if((C=t.gradient)!=null&&C.stops[0])return{hexColor:t.gradient.stops[0].color,opacity:100};break;case"image":return{hexColor:"#888888",opacity:100}}return{hexColor:void 0,opacity:100}},[t]),h=!u||If(d)?l.jsx(gS,{}):void 0,p=f.useCallback(C=>{Z_(e,C),vC(e,C)},[e]),g=f.useCallback(C=>{q_(e,C)},[e]),m=f.useCallback(C=>{wC(e,C)},[e]),b=f.useCallback(C=>{bh(e,C)},[e]),S=f.useCallback(C=>{TC(e,C)},[e]),w=f.useCallback(()=>{o(!1)},[]),y=f.useCallback(()=>{c(!0)},[]),T=f.useCallback(C=>{bh(e,{imageUrl:C.url,mode:"stretch",scale:1,offsetX:0,offsetY:0,rotation:0}),c(!1)},[e]);return l.jsxs(at,{sideOffset:12,crossAxisOffset:40,open:r,onOpenChange:C=>{!C&&a||o(C)},placement:"left",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:q("property-button"),visible:!0,icon:h,type:"button",tooltip:n,"aria-label":n,onPointerUp:()=>{o(!r)},children:!h&&i})}),l.jsx(ct,{children:l.jsx(qe,{padding:0,className:q(`${Dt}`,"fill-setting"),children:l.jsx(OC,{value:t,onSolidChange:p,onOpacityChange:g,onGradientChange:m,onImageChange:b,onFillTypeChange:S,showClose:!0,onClose:w,onOpenMediaLibrary:y})})}),a&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(BC,{isOpen:a,onClose:()=>c(!1),mode:ni.SELECT,filterType:Nn.IMAGE,onSelect:T,selectButtonText:s==="zh"?"使用此图片":"Use this image"})})]})},FC=({board:e,currentRadius:t,title:n,selectionRect:i})=>{const[s,r]=f.useState(!1),[o,a]=f.useState({top:0,left:0}),[c,u]=f.useState(""),d=f.useRef(null),h=f.useRef(null),p=z.getBoardContainer(e),{t:g}=Ee(),m=n||g("toolbar.cornerRadius")||"圆角",b=t??0;f.useEffect(()=>{u(String(b))},[b]),f.useEffect(()=>{if(s&&d.current){const v=d.current.getBoundingClientRect(),x=220,O=8;let B=v.left+v.width/2-x/2,X=v.bottom+O;const j=window.innerWidth,L=window.innerHeight;B+x>j-16&&(B=j-x-16),B<16&&(B=16),X+40>L-16&&(X=v.top-40-O),a({left:B,top:X})}},[s]),f.useEffect(()=>{if(!s)return;const v=O=>{const B=O.target;h.current&&h.current.contains(B)||d.current&&d.current.contains(B)||B.closest(".popup-toolbar")!==null||r(!1)},x=setTimeout(()=>{document.addEventListener("mousedown",v)},100);return()=>{clearTimeout(x),document.removeEventListener("mousedown",v)}},[s]);const S=f.useCallback(v=>{const x=Math.max(0,Math.min(100,v));He(e).filter(B=>Je.isPenPath(B)).forEach(B=>{const X=e.children.findIndex(j=>j.id===B.id);X>=0&&ue.setNode(e,{cornerRadius:x},[X])})},[e]),w=f.useCallback(v=>{u(String(v)),S(v)},[S]),y=f.useCallback(v=>{u(v.target.value)},[]),T=f.useCallback(()=>{const v=parseInt(c,10);if(isNaN(v))u(String(b));else{const x=Math.max(0,Math.min(100,v));u(String(x)),S(x)}},[c,b,S]),C=f.useCallback(v=>{v.key==="Enter"&&v.target.blur()},[]),E=f.useCallback(()=>{r(!s)},[s]);return l.jsxs(l.Fragment,{children:[l.jsx(ne,{ref:d,className:q("property-button","corner-radius-button",{"is-active":s}),visible:!0,type:"button",tooltip:m,"aria-label":m,onPointerUp:E,children:l.jsx("svg",{viewBox:"0 0 24 24",width:"18",height:"18",children:l.jsx("path",{d:"M4 4 L4 14 Q4 20 10 20 L20 20",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),s&&p&&Lo.createPortal(l.jsx("div",{ref:h,className:q(Dt,"corner-radius-panel"),style:{position:"fixed",top:o.top,left:o.left,zIndex:5e3},onPointerDown:v=>v.stopPropagation(),onMouseDown:v=>v.stopPropagation(),children:l.jsx(qe,{padding:2,className:"corner-radius-setting-compact",children:l.jsxs("div",{className:"corner-radius-row",children:[l.jsx("span",{className:"corner-radius-label",children:m}),l.jsx("div",{className:"corner-radius-slider",children:l.jsx(Io,{value:b,min:0,max:100,step:1,onChange:v=>w(v),label:!1})}),l.jsx("input",{type:"text",className:"corner-radius-input",value:c,onChange:y,onBlur:T,onKeyDown:C}),l.jsx("span",{className:"corner-radius-unit",children:"%"})]})})}),p)]})},GC=(e,t)=>{try{return Ft(e,[t],!1)}catch{return null}},Eh=(e,t,n,i,s,r)=>{const o=e.children.findIndex(m=>m.id===t.id);if(o<0)return;const a=GC(e,t);if(!a)return;const c=(a.x-n.x)/n.width,u=(a.y-n.y)/n.height,d=i.x+c*i.width,h=i.y+u*i.height,p=a.width*s,g=a.height*r;if(Ti(t)){const m=[[d,h],[d+p,h+g]];ue.setNode(e,{points:m},[o])}else if(V.isDrawElement(t)){const m=[[d,h],[d+p,h+g]];ue.setNode(e,{points:m},[o])}else if(tn.isMindElement(e,t)){const m=[[d,h],[d+p,h+g]];ue.setNode(e,{points:m},[o])}else if(Xe.isFreehand(t)){const b=t.points.map(S=>{const w=(S[0]-n.x)/n.width,y=(S[1]-n.y)/n.height;return[i.x+w*i.width,i.y+y*i.height]});ue.setNode(e,{points:b},[o])}else if(Je.isPenPath(t)){const b=t.anchors.map(w=>{const y=[w.point[0]*s,w.point[1]*r],T=w.handleIn?[w.handleIn[0]*s,w.handleIn[1]*r]:void 0,C=w.handleOut?[w.handleOut[0]*s,w.handleOut[1]*r]:void 0;return{...w,point:y,handleIn:T,handleOut:C}}),S=[d,h];ue.setNode(e,{points:[S,S],anchors:b},[o])}},zC=({board:e})=>{const{language:t}=Ee(),n=t==="zh",i=He(e),[s,r]=f.useState(!0),[o,a]=f.useState(""),[c,u]=f.useState(""),[d,h]=f.useState(1),[p,g]=f.useState(!1),m=f.useRef(null),b=z.getBoardContainer(e),S=i.length>0?Ft(e,i,!1):null;f.useEffect(()=>{S&&(m.current?(a(Math.round(m.current.width).toString()),u(Math.round(m.current.height).toString()),m.current=null):(a(Math.round(S.width).toString()),u(Math.round(S.height).toString())),h(S.width/S.height))},[S==null?void 0:S.width,S==null?void 0:S.height]);const w=f.useCallback(v=>{const x=v.target.value;if(a(x),s&&S){const O=parseFloat(x);if(!isNaN(O)&&O>0){const B=Math.round(O/d);u(B.toString())}}},[s,d,S]),y=f.useCallback(v=>{const x=v.target.value;if(u(x),s&&S){const O=parseFloat(x);if(!isNaN(O)&&O>0){const B=Math.round(O*d);a(B.toString())}}},[s,d,S]),T=f.useCallback(()=>{if(!S||i.length===0)return;const v=parseFloat(o),x=parseFloat(c);if(isNaN(v)||isNaN(x)||v<=0||x<=0){a(Math.round(S.width).toString()),u(Math.round(S.height).toString());return}if(Math.abs(v-S.width)<.5&&Math.abs(x-S.height)<.5)return;m.current={width:v,height:x};const O=v/S.width,B=x/S.height,X={x:S.x,y:S.y,width:v,height:x};i.forEach(j=>{Eh(e,j,S,X,O,B)})},[e,i,S,o,c]),C=f.useCallback(v=>{if(!S||i.length===0)return;const x=v.width,O=v.height;a(x.toString()),u(O.toString()),m.current={width:x,height:O};const B=x/S.width,X=O/S.height,j={x:S.x,y:S.y,width:x,height:O};i.forEach(L=>{Eh(e,L,S,j,B,X)}),h(x/O),g(!1)},[e,i,S]),E=f.useCallback(v=>{v.key==="Enter"?(T(),v.target.blur()):v.key==="Escape"&&(S&&(a(Math.round(S.width).toString()),u(Math.round(S.height).toString())),v.target.blur())},[T,S]);return S?l.jsxs("div",{className:"size-input-container",children:[l.jsxs("div",{className:"size-input-group",children:[l.jsx("span",{className:"size-input-label",children:"W"}),l.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"size-input",value:o,onChange:w,onBlur:T,onKeyDown:E})]}),l.jsx("button",{className:`size-lock-button ${s?"locked":""}`,onClick:()=>r(!s),title:s?"解锁比例":"锁定比例",children:s?l.jsx(mS,{}):l.jsx(SS,{})}),l.jsxs("div",{className:"size-input-group",children:[l.jsx("span",{className:"size-input-label",children:"H"}),l.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"size-input",value:c,onChange:y,onBlur:T,onKeyDown:E})]}),l.jsxs(at,{open:p,onOpenChange:g,placement:"bottom-end",sideOffset:8,children:[l.jsx(lt,{asChild:!0,children:l.jsx("button",{className:`size-preset-button ${p?"active":""}`,title:n?"常用尺寸":"Preset Sizes",onClick:()=>g(!p),children:l.jsx(Ul,{size:12})})}),l.jsx(ct,{container:b,children:l.jsx("div",{className:"size-preset-panel",children:bS.map(v=>l.jsxs("div",{className:"size-preset-category",children:[l.jsx("div",{className:"size-preset-category-label",children:n?v.category:v.categoryEn}),v.items.map(x=>l.jsxs("button",{className:"size-preset-item",onClick:()=>C(x),children:[l.jsx("span",{className:"size-preset-item-label",children:n?x.label:x.labelEn}),l.jsxs("span",{className:"size-preset-item-size",children:[x.width," x ",x.height]})]},`${x.width}x${x.height}-${x.label}`))]},v.category))})})]})]}):null},VC=({board:e,title:t})=>{const{appState:n,setAppState:i}=Ut();return l.jsx(ne,{className:q("property-button"),visible:!0,icon:l.jsx(wS,{}),type:"button",tooltip:t,"aria-label":t,onPointerUp:()=>{const s=He(e)[0],r=yS(s);es.getLinkElement(r)||es.wrapLink(r,"链接",""),setTimeout(()=>{const c=es.getLinkElement(r)[0],u=vn.toDOMNode(r,c);i({...n,linkState:{editor:r,targetDom:u,targetElement:c,isEditing:!0,isHovering:!1,isHoveringOrigin:!1}})},0)}})},Xg={zh:[`一张写实的半身人像,一位身穿水蓝色连身裙的年轻韩国亚洲女人走进旅馆大厅,女人脸上带着温暖的微笑,左手拿着白色棒球帽,右手拉着黄色行李箱。
|
|
28
28
|
场景在济州岛度假感的旅馆大厅里,柔和的光线从窗外洒入室内柔和的打在女人的身上,凸显了女人的脸部表情。
|
|
29
29
|
使用 50mm 人像镜头拍摄,女人在画面中央,背景呈现柔和的模糊(散景)。
|
|
30
30
|
氛围是日系杂志的色调并充满放松度假感。直式人像构图,比例1:1。`,"一只可爱的小猫坐在窗台上,阳光透过窗户洒在它的毛发上","美丽的山水风景,青山绿水,云雾缭绕","现代简约风格的室内设计,明亮宽敞","夜晚的城市天际线,霓虹灯闪烁","春天的樱花盛开,粉色花瓣飘落","科幻风格的太空站,星空背景","温馨的咖啡厅,暖色调灯光","抽象艺术风格,色彩丰富的几何图形"],en:[`young Korean woman in a light blue dress holding a white baseball cap and pulling a yellow suitcase, photography,
|
|
@@ -39,10 +39,10 @@ Action: The princesses smile at each other, then begin singing in harmony, then
|
|
|
39
39
|
Audio: Soft orchestral music with uplifting strings and choir, ambient sounds of rustling leaves and distant birds, dialogue: "Together, we believe tomorrow will be brighter."
|
|
40
40
|
Style: Disney-style animation, vibrant colors, dreamy lighting.`,"a beautiful sunrise scene where the sun slowly rises from behind mountains with clouds gently floating","a forest scene with leaves gently swaying in the breeze and dappled sunlight","a seaside scene with waves gently lapping the shore and seagulls circling overhead","a garden scene with flowers swaying in the breeze and butterflies dancing","a post-rain scene with water drops slowly dripping from leaves and a rainbow appearing in the sky","a winter scene with snowflakes gently falling","a starry night scene with twinkling stars and clouds slowly drifting across the moon","a stream scene with clear water flowing gently between stones and fish swimming by"]},WC={zh:[{content:"灵感图:咖啡文化,16图",scene:"灵感图",tips:"调用1次文本模型 + 1次生图模型,一张图排布n张子图(最多16张)",modelType:"agent"},{content:"宫格图:可爱猫咪表情包,16宫格",scene:"宫格图",tips:"调用1次文本模型 + 1次生图模型,一张图排布n张正方形子图(最多16张)",modelType:"agent"},{content:"创作一个视频:樱花树下的少女,微风吹过,花瓣飘落",scene:"视频创作",tips:"调用1次文本模型 + 1次生视频模型",modelType:"video"},{content:"画一个AI工作流的流程图",scene:"mermaid图",tips:"调用1次文本模型,支持流程图、泳道图、",modelType:"agent"},{content:"大模型发展趋势的思维导图",scene:"知识梳理",tips:"调用1次文本模型",modelType:"agent"},{content:"矢量图:一个简约风格的火箭作为公司logo",scene:"SVG矢量图",tips:"调用1次文本模型生成SVG图标,可无损缩放",modelType:"agent"},{content:"生成一份关于人工智能发展的PPT",scene:"PPT演示",tips:"调用1次文本模型生成大纲 + 自动布局为多页PPT幻灯片",modelType:"agent"}],en:[{content:"inspiration board: Coffee culture mood board, beans, latte art, cafe scenes",scene:"Inspiration board",tips:"1 text model + 1 image model",modelType:"agent"},{content:"grid image: Cute cat emoji pack, 4x4 scattered layout",scene:"Grid image",tips:"1 text model + 1 image model",modelType:"agent"},{content:"a video: A girl under cherry blossom tree, petals falling in the breeze",scene:"Video creation",tips:"1 text model + 1 video model",modelType:"video"},{content:"Draw a flowchart of AI workflow",scene:"Tech docs",tips:"1 text model",modelType:"agent"},{content:"Draw a mind map of LLM development trends",scene:"Knowledge organization",tips:"1 text model",modelType:"agent"},{content:"SVG: A minimalist rocket icon",scene:"SVG vector",tips:"1 text model to generate SVG code, scalable and lossless",modelType:"agent"},{content:"Generate a PPT about artificial intelligence development",scene:"PPT slides",tips:"1 text model for outline + auto layout into multi-page PPT slides",modelType:"agent"}]},dN=e=>Xg[e],hN=e=>UC[e];function $C(e={}){const{language:t="zh",deduplicateWithPresets:n=!0,customPresetContents:i}=e,[s,r]=f.useState([]),o=f.useMemo(()=>{if(!n)return new Set;if(i&&i.length>0)return new Set(i.map(m=>m.trim().toLowerCase()));const g=WC[t]||[];return new Set(g.map(m=>m.content.trim().toLowerCase()))},[t,n,i]),a=f.useMemo(()=>!n||o.size===0?s:s.filter(g=>!o.has(g.content.trim().toLowerCase())),[s,o,n]),c=f.useCallback(()=>{const g=Hi.getHistory();r(g)},[]);f.useEffect(()=>{let g=!0;return(async()=>{await Hi.waitForInit(),g&&c()})(),()=>{g=!1}},[c]);const u=f.useCallback((g,m,b)=>{Hi.addHistory(g,m,b),c()},[c]),d=f.useCallback(g=>{Hi.removeHistory(g),c()},[c]),h=f.useCallback(()=>{Hi.clearHistory(),c()},[c]),p=f.useCallback(g=>{Hi.togglePin(g),c()},[c]);return{history:a,addHistory:u,removeHistory:d,clearHistory:h,refreshHistory:c,togglePinHistory:p}}const ks=8,XC=60,KC=600,_h=24,YC='16px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';let Na=null,jr=null;function qC(){if(Na||(Na=document.createElement("canvas"),jr=Na.getContext("2d")),!jr)throw new Error("Failed to get canvas context");return jr.font=YC,jr}function Ra(e){return qC().measureText(e).width}function ZC(e){const t=e.split(`
|
|
41
41
|
`);let n=0;for(const a of t){const c=Ra(a);n=Math.max(n,c)}const i=Math.min(KC-ks*2,Math.max(XC-ks*2,n)),s=i+ks*2;let r=0;for(const a of t){if(a.length===0){r+=1;continue}if(Ra(a)<=i)r+=1;else{let u=0,d=1;for(const h of a){const p=Ra(h);u+p>i?(d++,u=p):u+=p}r+=d}}const o=Math.max(_h+ks*2,r*_h+ks*2);return{width:s,height:o}}function QC(e){switch(e){case"ai-input":return l.jsx(CS,{size:12});case"image":return l.jsx(jf,{size:12});case"video":return l.jsx(_S,{size:12});default:return null}}function JC(e,t){return{"ai-input":{zh:"AI输入",en:"AI Input"},image:{zh:"图片",en:"Image"},video:{zh:"视频",en:"Video"},preset:{zh:"预设",en:"Preset"}}[e][t]}const eP=({board:e,language:t,title:n})=>{const[i,s]=f.useState(!1),[r,o]=f.useState(0),{history:a,addHistory:c,removeHistory:u}=$C({deduplicateWithPresets:!1}),{confirm:d,confirmDialog:h}=No({container:e?z.getBoardContainer(e):null}),p=f.useRef(null),[g,m]=f.useState([]),[b,S]=f.useState([]);f.useEffect(()=>{i&&(m(TS()),S(vS()))},[i]);const w=f.useMemo(()=>{const x=Xg[t].map((N,M)=>({id:`preset_${M}`,content:N,source:"preset"})),O=a.map(N=>({id:N.id,content:N.content,source:"ai-input",timestamp:N.timestamp})),B=g.map(N=>({id:N.id,content:N.content,source:"image",timestamp:N.timestamp})),X=b.map(N=>({id:N.id,content:N.content,source:"video",timestamp:N.timestamp})),j=[...O,...B,...X];j.sort((N,M)=>(M.timestamp||0)-(N.timestamp||0));const L=new Set,D=[];for(const N of j){const M=N.content.trim();L.has(M)||(L.add(M),D.push(N))}const k=x.filter(N=>!L.has(N.content.trim()));return[...D,...k]},[t,a,g,b]),{historyPrompts:y,presetPrompts:T}=f.useMemo(()=>{const x=w.filter(B=>B.source!=="preset"),O=w.filter(B=>B.source==="preset");return{historyPrompts:x,presetPrompts:O}},[w]),C=f.useCallback((x,O)=>x==="history"?O:y.length+O,[y.length]);f.useEffect(()=>{i&&o(0)},[i]);const E=f.useCallback(x=>{c(x.content),s(!1);const O=He(e);if(O.length===0)return;const B=L=>({type:"paragraph",children:[{text:L}]}),{width:X,height:j}=ZC(x.content);for(const L of O){const D=e.children.findIndex(N=>N.id===L.id);if(D<0)continue;const k={};if(tn.isMindElement(e,L)){const N=[B(x.content)];ue.setNode(e,{data:N},[D]);continue}if(V.isText&&V.isText(L)){if(k.text=B(x.content),"points"in L&&Array.isArray(L.points)&&L.points.length>=2){const N=L.points,[M]=N,Z=[M,[M[0]+X,M[1]+j]];k.points=Z}ue.setNode(e,k,[D]);continue}if(V.isDrawElement(L)&&Wl([L])){if("text"in L&&L.text){if(k.text=B(x.content),"points"in L&&Array.isArray(L.points)&&L.points.length>=2){const N=L.points,[M]=N,Z=[M,[M[0]+X,M[1]+j]];k.points=Z}ue.setNode(e,k,[D]);continue}if("data"in L&&Array.isArray(L.data)){if(k.data=[B(x.content)],"points"in L&&Array.isArray(L.points)&&L.points.length>=2){const N=L.points,[M]=N,Z=[M,[M[0]+X,M[1]+j]];k.points=Z}ue.setNode(e,k,[D]);continue}}if("text"in L&&L.text){if(k.text=B(x.content),"points"in L&&Array.isArray(L.points)&&L.points.length>=2){const N=L.points,[M]=N,Z=[M,[M[0]+X,M[1]+j]];k.points=Z}ue.setNode(e,k,[D]);continue}"textContent"in L&&ue.setNode(e,{textContent:x.content},[D])}},[e,c]),v=f.useCallback(async(x,O)=>{x.stopPropagation(),await d({title:t==="zh"?"确认删除提示词":"Delete Prompt",description:t==="zh"?"确定要删除这条历史提示词吗?此操作不可撤销。":"Are you sure you want to delete this prompt history item? This action cannot be undone.",confirmText:t==="zh"?"删除":"Delete",cancelText:t==="zh"?"取消":"Cancel",danger:!0})&&u(O)},[d,t,u]);return f.useEffect(()=>{if(!i)return;const x=O=>{if(w.length===0){O.key==="Escape"&&(O.preventDefault(),s(!1));return}switch(O.key){case"ArrowUp":O.preventDefault(),o(B=>B<=0?w.length-1:B-1);break;case"ArrowDown":O.preventDefault(),o(B=>B>=w.length-1?0:B+1);break;case"Enter":O.preventDefault(),w[r]&&E(w[r]);break;case"Escape":O.preventDefault(),s(!1);break}};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[i,w,r,E]),f.useEffect(()=>{var O;if(!i||w.length===0)return;const x=(O=p.current)==null?void 0:O.querySelector(".popup-prompt-panel__item--highlighted");x&&x.scrollIntoView({block:"nearest",behavior:"smooth"})},[r,i,w.length]),l.jsxs(at,{open:i,onOpenChange:s,placement:"top",sideOffset:8,children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:"prompt-button",type:"icon",icon:l.jsx(gu,{size:16}),visible:!0,tooltip:n||(t==="zh"?"提示词":"Prompts"),"aria-label":n||(t==="zh"?"提示词":"Prompts"),onPointerUp:()=>s(!i)})}),l.jsx(ct,{className:`popup-prompt-panel ${Dt}`,onMouseDown:x=>x.preventDefault(),children:l.jsxs("div",{ref:p,className:"popup-prompt-panel__content",children:[y.length>0&&l.jsxs("div",{className:"popup-prompt-panel__section",children:[l.jsxs("div",{className:"popup-prompt-panel__section-header",children:[l.jsx(xS,{size:14}),l.jsx("span",{children:t==="zh"?"历史记录":"History"})]}),l.jsx("div",{className:"popup-prompt-panel__list",children:y.map((x,O)=>l.jsxs("div",{className:`popup-prompt-panel__item popup-prompt-panel__item--history ${C("history",O)===r?"popup-prompt-panel__item--highlighted":""}`,onClick:()=>E(x),onMouseEnter:()=>o(C("history",O)),children:[l.jsxs("div",{className:"popup-prompt-panel__item-content",children:[l.jsx("span",{className:"popup-prompt-panel__item-text",children:x.content}),l.jsxs("span",{className:`popup-prompt-panel__item-source popup-prompt-panel__item-source--${x.source}`,children:[QC(x.source),l.jsx("span",{children:JC(x.source,t)})]})]}),x.source==="ai-input"&&l.jsx(Ct,{content:t==="zh"?"删除":"Delete",showArrow:!1,children:l.jsx("button",{className:"popup-prompt-panel__item-delete",onClick:B=>v(B,x.id),children:l.jsx(ES,{size:12})})})]},x.id))})]}),T.length>0&&l.jsxs("div",{className:"popup-prompt-panel__section",children:[l.jsxs("div",{className:"popup-prompt-panel__section-header",children:[l.jsx(gu,{size:14}),l.jsx("span",{children:t==="zh"?"推荐提示词":"Suggestions"})]}),l.jsx("div",{className:"popup-prompt-panel__list",children:T.map((x,O)=>l.jsx("div",{className:`popup-prompt-panel__item ${C("preset",O)===r?"popup-prompt-panel__item--highlighted":""}`,onClick:()=>E(x),onMouseEnter:()=>o(C("preset",O)),children:l.jsx("span",{className:"popup-prompt-panel__item-text",children:x.content})},x.id))})]})]})}),h]})},As={bringToFront(e){const t=He(e);if(t.length===0)return;const n=e.children.length-1,i=t.map(s=>({element:s,index:e.children.findIndex(r=>r.id===s.id)})).sort((s,r)=>r.index-s.index);for(const{element:s,index:r}of i)r>=0&&r<n&&ue.moveNode(e,[r],[n])},bringForward(e){const t=He(e);if(t.length===0)return;const n=e.children.length-1,i=t.map(s=>({element:s,index:e.children.findIndex(r=>r.id===s.id)})).sort((s,r)=>r.index-s.index);for(const{element:s,index:r}of i)r>=0&&r<n&&ue.moveNode(e,[r],[r+2])},sendBackward(e){const t=He(e);if(t.length===0)return;const n=t.map(i=>({element:i,index:e.children.findIndex(s=>s.id===i.id)})).sort((i,s)=>i.index-s.index);for(const{element:i,index:s}of n)s>0&&ue.moveNode(e,[s],[s-1])},sendToBack(e){const t=He(e);if(t.length===0)return;const n=t.map(i=>({element:i,index:e.children.findIndex(s=>s.id===i.id)})).sort((i,s)=>i.index-s.index);for(const{element:i,index:s}of n)s>0&&ue.moveNode(e,[s],[0])},getLayerInfo(e,t){const n=e.children.findIndex(s=>s.id===t);if(n<0)return null;const i=e.children.length;return{index:n,total:i,canMoveUp:n<i-1,canMoveDown:n>0}}},tP=({board:e,title:t})=>{const{language:n}=Ee(),[i,s]=f.useState(!1),[r,o]=f.useState(0),a=z.getBoardContainer(e),c=f.useMemo(()=>{const b=He(e);if(b.length===0)return null;const S=b[0];return As.getLayerInfo(e,S.id)},[e,r]),u=f.useCallback(()=>{As.bringToFront(e),o(b=>b+1)},[e]),d=f.useCallback(()=>{As.bringForward(e),o(b=>b+1)},[e]),h=f.useCallback(()=>{As.sendBackward(e),o(b=>b+1)},[e]),p=f.useCallback(()=>{As.sendToBack(e),o(b=>b+1)},[e]),g=(c==null?void 0:c.canMoveUp)??!1,m=(c==null?void 0:c.canMoveDown)??!1;return l.jsxs(at,{sideOffset:12,crossAxisOffset:-100,open:i,onOpenChange:s,placement:"top-start",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:q("property-button","layer-control-button"),selected:i,visible:!0,icon:l.jsx(PS,{}),type:"button",tooltip:t,"aria-label":t,onPointerUp:()=>s(!i)})}),l.jsx(ct,{container:a,children:l.jsx(qe,{padding:1,className:q(Dt,"layer-control-panel"),children:l.jsxs("div",{className:"layer-actions",children:[l.jsx(Ct,{content:n==="zh"?"置顶":"Bring to Front",showArrow:!1,children:l.jsxs("button",{className:q("layer-action-btn",{disabled:!g}),onClick:u,disabled:!g,children:[l.jsx(kS,{}),l.jsx("span",{children:n==="zh"?"置顶":"Front"})]})}),l.jsx(Ct,{content:n==="zh"?"上移一层":"Bring Forward",showArrow:!1,children:l.jsxs("button",{className:q("layer-action-btn",{disabled:!g}),onClick:d,disabled:!g,children:[l.jsx(AS,{}),l.jsx("span",{children:n==="zh"?"上移":"Forward"})]})}),l.jsx(Ct,{content:n==="zh"?"下移一层":"Send Backward",showArrow:!1,children:l.jsxs("button",{className:q("layer-action-btn",{disabled:!m}),onClick:h,disabled:!m,children:[l.jsx(MS,{}),l.jsx("span",{children:n==="zh"?"下移":"Backward"})]})}),l.jsx(Ct,{content:n==="zh"?"置底":"Send to Back",showArrow:!1,children:l.jsxs("button",{className:q("layer-action-btn",{disabled:!m}),onClick:p,disabled:!m,children:[l.jsx(IS,{}),l.jsx("span",{children:n==="zh"?"置底":"Back"})]})}),c&&l.jsxs("span",{className:"layer-info",children:[c.index+1,"/",c.total]})]})})})]})},nP=({board:e,title:t})=>{const{language:n}=Ee(),[i,s]=f.useState(!1),r=z.getBoardContainer(e),o=f.useCallback(()=>{on.alignLeft(e)},[e]),a=f.useCallback(()=>{on.alignCenter(e)},[e]),c=f.useCallback(()=>{on.alignRight(e)},[e]),u=f.useCallback(()=>{on.alignTop(e)},[e]),d=f.useCallback(()=>{on.alignMiddle(e)},[e]),h=f.useCallback(()=>{on.alignBottom(e)},[e]),p=[{key:"left",icon:l.jsx(NS,{size:16}),label:n==="zh"?"左对齐":"Align Left",shortcut:"⌥ A",handler:o},{key:"center",icon:l.jsx(RS,{size:16}),label:n==="zh"?"水平居中":"Align Center",shortcut:"⌥ H",handler:a},{key:"right",icon:l.jsx(jS,{size:16}),label:n==="zh"?"右对齐":"Align Right",shortcut:"⌥ D",handler:c},{key:"top",icon:l.jsx(LS,{size:16}),label:n==="zh"?"顶部对齐":"Align Top",shortcut:"⌥ W",handler:u},{key:"middle",icon:l.jsx(OS,{size:16}),label:n==="zh"?"垂直居中":"Align Middle",shortcut:"⌥ V",handler:d},{key:"bottom",icon:l.jsx(BS,{size:16}),label:n==="zh"?"底部对齐":"Align Bottom",shortcut:"⌥ S",handler:h}];return l.jsxs(at,{sideOffset:12,crossAxisOffset:-100,open:i,onOpenChange:s,placement:"top-start",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:q("property-button","alignment-button"),selected:i,visible:!0,icon:l.jsx(DS,{size:16}),type:"button",tooltip:t,"aria-label":t,onPointerUp:()=>s(!i)})}),l.jsx(ct,{container:r,children:l.jsx(qe,{padding:1,className:q(Dt,"alignment-panel"),children:l.jsx("div",{className:"alignment-actions",children:p.map(g=>l.jsx(Ct,{content:g.label,showArrow:!1,children:l.jsxs("button",{className:"alignment-action-btn",onClick:g.handler,children:[g.icon,l.jsx("span",{className:"alignment-label",children:g.label}),l.jsx("span",{className:"alignment-shortcut",children:g.shortcut})]})},g.key))})})})]})},iP=({board:e,title:t})=>{const{language:n}=Ee(),[i,s]=f.useState(!1),r=z.getBoardContainer(e),o=f.useCallback(()=>{ts.distributeHorizontal(e)},[e]),a=f.useCallback(()=>{ts.distributeVertical(e)},[e]),c=f.useCallback(()=>{ts.autoArrange(e)},[e]),u=[{key:"horizontal",icon:l.jsx(FS,{size:16}),label:n==="zh"?"水平间距":"Horizontal Spacing",shortcut:"⇧ H",handler:o},{key:"vertical",icon:l.jsx(GS,{size:16}),label:n==="zh"?"垂直间距":"Vertical Spacing",shortcut:"⇧ V",handler:a},{key:"auto",icon:l.jsx(zS,{size:16}),label:n==="zh"?"自动排列":"Auto Arrange",shortcut:"⇧ A",handler:c}];return l.jsxs(at,{sideOffset:12,crossAxisOffset:-100,open:i,onOpenChange:s,placement:"top-start",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:q("property-button","distribute-button"),selected:i,visible:!0,icon:l.jsx(HS,{size:16}),type:"button",tooltip:t,"aria-label":t,onPointerUp:()=>s(!i)})}),l.jsx(ct,{container:r,children:l.jsx(qe,{padding:1,className:q(Dt,"distribute-panel"),children:l.jsx("div",{className:"distribute-actions",children:u.map(d=>l.jsx(Ct,{content:d.label,showArrow:!1,children:l.jsxs("button",{className:"distribute-action-btn",onClick:d.handler,children:[d.icon,l.jsx("span",{className:"distribute-label",children:d.label}),l.jsx("span",{className:"distribute-shortcut",children:d.shortcut})]})},d.key))})})})]})},sP=({board:e,title:t})=>{const{language:n}=Ee(),[i,s]=f.useState(!1),r=z.getBoardContainer(e),o=f.useCallback(()=>{Tn.union(e,n),s(!1)},[e,n]),a=f.useCallback(()=>{Tn.subtract(e,n)},[e,n]),c=f.useCallback(()=>{Tn.intersect(e,n)},[e,n]),u=f.useCallback(()=>{Tn.exclude(e,n)},[e,n]),d=f.useCallback(()=>{Tn.flatten(e,n)},[e,n]),h=[{key:"union",icon:l.jsx(US,{size:16}),label:n==="zh"?"合并":"Union",shortcut:"⌥⇧U",handler:o},{key:"subtract",icon:l.jsx(WS,{size:16}),label:n==="zh"?"减去":"Subtract",shortcut:"⌥⇧S",handler:a},{key:"intersect",icon:l.jsx($S,{size:16}),label:n==="zh"?"相交":"Intersect",shortcut:"⌥⇧I",handler:c},{key:"exclude",icon:l.jsx(XS,{size:16}),label:n==="zh"?"排除":"Exclude",shortcut:"⌥⇧E",handler:u},{key:"flatten",icon:l.jsx(KS,{size:16}),label:n==="zh"?"扁平化":"Flatten",shortcut:"⇧⌥F",handler:d}];return l.jsxs(at,{sideOffset:12,crossAxisOffset:-100,open:i,onOpenChange:s,placement:"top-start",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:q("property-button","boolean-button"),selected:i,visible:!0,icon:l.jsx(VS,{size:16}),type:"button",tooltip:t,"aria-label":t,onPointerUp:()=>s(!i)})}),l.jsx(ct,{container:r,children:l.jsx(qe,{padding:1,className:q(Dt,"boolean-panel"),children:l.jsx("div",{className:"boolean-actions",children:h.map(p=>l.jsx(Ct,{content:p.label,showArrow:!1,children:l.jsxs("button",{className:"boolean-action-btn",onClick:p.handler,children:[p.icon,l.jsx("span",{className:"boolean-label",children:p.label}),l.jsx("span",{className:"boolean-shortcut",children:p.shortcut})]})},p.key))})})})]})};function rP(e){return e.sort((t,n)=>t.position-n.position).map(t=>`${t.color} ${t.position}%`).join(", ")}function oP(e){const t=rP(e.stops);return e.type==="linear"?`linear-gradient(${e.angle}deg, ${t})`:`radial-gradient(circle, ${t})`}function ja(e){return e.enabled?`${e.offsetX}px ${e.offsetY}px ${e.blur}px ${e.color}`:""}const La=At.CUSTOM_GRADIENTS,aP=({board:e,isOpen:t,onClose:n,currentFontSize:i,currentFontFamily:s,currentColor:r,toolbarRect:o,selectionRect:a})=>{var Qc,Jc;const{t:c,language:u}=Ee(),{confirm:d,confirmDialog:h}=No({container:z.getBoardContainer(e)}),p=f.useRef(null),[g,m]=f.useState({top:0,left:0}),[b,S]=f.useState(i||"16"),[w,y]=f.useState(!1),[T,C]=f.useState(s||"PingFang SC"),[E,v]=f.useState(new Set),[x,O]=f.useState(400),[B,X]=f.useState("left"),[j,L]=f.useState(1.5),[D,k]=f.useState(0),[N,M]=f.useState(!1),[Z,he]=f.useState(!1),[R,W]=f.useState(!1),[ce,K]=f.useState(!1),[ae,le]=f.useState(!1),[me,Te]=f.useState(!1),[ze,Y]=f.useState(null),[Ie,$e]=f.useState(null),[it,Ye]=f.useState(0),[P,A]=f.useState("#000000"),[$,Q]=f.useState(null),[I,H]=f.useState(null),[F,U]=f.useState(!1),[te,ee]=f.useState(null),[G,J]=f.useState({color:"rgba(0, 0, 0, 0.5)",offsetX:2,offsetY:2,blur:4}),[se,Re]=f.useState(!1),[ut,Oe]=f.useState(null),[ie,De]=f.useState({type:"linear",angle:135,stops:[{color:"#FF6B6B",offset:0},{color:"#4ECDC4",offset:1}]}),[Le,ke]=f.useState([]),[Fe,Nt]=f.useState(r||"#000000"),[Pt,Rt]=f.useState(!1);f.useEffect(()=>{let _=!0;return xn.get(La).then(de=>{_&&de&&ke(de)}).catch(de=>{console.warn("Failed to load gradient data:",de)}),()=>{_=!1}},[]),f.useEffect(()=>{if(t){const _=bC(e);if(_["text-gradient"]){Re(!0);const Ae=YS.find(et=>oP(et.config)===_["text-gradient"]);Oe(Ae?Ae.id:null)}else Re(!1),Oe(null);if(_["text-shadow"]){U(!0);const Ae=_["text-shadow"];let et=null;for(const[sn,Wn]of Object.entries(mu.textShadow))if(ja(Wn)===Ae){et=sn;break}ee(et||null)}else U(!1),ee(null);if(_["font-family"]&&C(_["font-family"]),_["font-weight"]&&O(Number(_["font-weight"])),_["line-height"]&&L(Number(_["line-height"])),_["letter-spacing"]){const Ae=String(_["letter-spacing"]).replace("px","");k(Number(Ae))}const de=yC(e);X(de),M(!!_.bold),he(!!_.italic),W(!!_.underlined),K(!!_.strikethrough),le(!!_.superscript),Te(!!_.subscript),Y(_["background-color"]||null),$e(_["text-transform"]||null),Ye(_["text-stroke"]||0),A(_["text-stroke-color"]||"#000000"),Q(_["text-decoration-style"]||null),H(_["text-decoration-color"]||null)}},[t,e]),f.useEffect(()=>{if(t&&!w){const _=setTimeout(()=>{Su.forEach(de=>{Tr.isFontLoaded(de.family)||Tr.loadGoogleFont(de.family).catch(Ae=>{console.warn(`Failed to preload font ${de.family}:`,Ae)})})},500);return()=>clearTimeout(_)}},[t,w]),f.useEffect(()=>{if(t&&o&&a){let et=a.right+12,sn=o.top+o.height+8;const Wn=window.innerWidth,fa=window.innerHeight;et+320>Wn-16&&(et=a.left-320-12,et<16&&(et=Wn-320-16)),sn+520>fa-16&&(sn=Math.max(16,fa-520-16)),m({left:Math.max(16,et),top:Math.max(16,sn)})}},[t,o,a]);const jt=f.useCallback(_=>{const de=parseInt(_,10);!isNaN(de)&&de>=8&&de<=100&&(S(_),Ug(e,_))},[e]),nn=f.useCallback(async _=>{if(C(_.family),y(!1),_.source==="google"&&!Tr.isFontLoaded(_.family)){v(de=>new Set(de).add(_.family));try{await Tr.loadGoogleFont(_.family)}catch(de){console.error("Failed to load Google font:",de)}finally{v(de=>{const Ae=new Set(de);return Ae.delete(_.family),Ae})}}iC(e,_.family)},[e]);f.useEffect(()=>{r&&Nt(r)},[r]);const di=f.useCallback(_=>{Nt(_),Qn.setTextColor(e,_)},[e]),Un=f.useCallback((_,de)=>{ee(_),U(!0),J({color:de.color,offsetX:de.offsetX,offsetY:de.offsetY,blur:de.blur});const Ae=ja(de);Ia(e,Ae)},[e]),Se=f.useCallback((_,de)=>{const Ae={...G,[_]:de};J(Ae),ee(null);const et=`${Ae.offsetX}px ${Ae.offsetY}px ${Ae.blur}px ${Ae.color}`;Ia(e,et)},[e,G]),Ve=f.useCallback(_=>{De(_),Oe(null);const de=yi(_);Sh(e,de)},[e]),be=f.useCallback(()=>{const _=yi(ie),Ae=[{id:`custom-${Date.now()}`,css:_},...Le].slice(0,8);ke(Ae),xn.set(La,Ae).catch(et=>{console.warn("Failed to save custom gradients:",et)})},[ie,Le]),je=f.useCallback(async _=>{if(!await d({title:u==="zh"?"确认删除渐变预设":"Delete Gradient Preset",description:u==="zh"?"确定要删除这个自定义渐变预设吗?":"Are you sure you want to delete this custom gradient preset?",confirmText:u==="zh"?"删除":"Delete",cancelText:u==="zh"?"取消":"Cancel",danger:!0}))return;const Ae=Le.filter(et=>et.id!==_);ke(Ae),xn.set(La,Ae).catch(et=>{console.warn("Failed to save custom gradients:",et)})},[d,Le,u]),st=f.useCallback(()=>{const _=!F;U(_),_||(Ia(e,null),ee(null))},[e,F]),Ue=f.useCallback(()=>{const _=!se;Re(_),_||(Sh(e,null),Oe(null))},[e,se]),Ge=f.useCallback(_=>{O(_),Wg(e,_)},[e]),rt=f.useCallback(_=>{X(_),sC(e,_)},[e]),gt=f.useCallback(_=>{L(_),rC(e,_)},[e]),kt=f.useCallback(_=>{k(_),oC(e,_)},[e]),Lt=f.useCallback(()=>{M(!N),aC(e)},[e,N]),dt=f.useCallback(()=>{he(!Z),lC(e)},[e,Z]),dn=f.useCallback(()=>{W(!R),cC(e)},[e,R]),aa=f.useCallback(()=>{K(!ce),uC(e)},[e,ce]),la=f.useCallback(()=>{const _=!ae;le(_),_&&Te(!1),dC(e)},[e,ae]),ca=f.useCallback(()=>{const _=!me;Te(_),_&&le(!1),hC(e)},[e,me]),re=f.useCallback(_=>{Y(_),fC(e,_)},[e]),xs=f.useCallback(_=>{const de=_===Ie?null:_;$e(de),pC(e,de)},[e,Ie]),Oi=f.useCallback((_,de)=>{Ye(_),de&&A(de),gC(e,_>0?_:null,de||P)},[e,P]),d0=f.useCallback(_=>{Q(_),mC(e,_)},[e]),qc=f.useCallback(_=>{H(_),SC(e,_)},[e]);f.useEffect(()=>{if(!t)return;const _=Ae=>{const et=Ae.target;p.current&&p.current.contains(et)||et.closest(".popup-toolbar")!==null||n()},de=setTimeout(()=>{document.addEventListener("mousedown",_)},100);return()=>{clearTimeout(de),document.removeEventListener("mousedown",_)}},[t,n]);const h0=f.useCallback(_=>{_.target===_.currentTarget&&n()},[n]),[ua,da]=f.useState(!1),Zc=[{value:100,label:"Thin",labelZh:"极细"},{value:200,label:"Extra Light",labelZh:"特细"},{value:300,label:"Light",labelZh:"细体"},{value:400,label:"Regular",labelZh:"常规"},{value:500,label:"Medium",labelZh:"中等"},{value:600,label:"Semi Bold",labelZh:"半粗"},{value:700,label:"Bold",labelZh:"粗体"},{value:800,label:"Extra Bold",labelZh:"特粗"},{value:900,label:"Black",labelZh:"黑体"}],f0=f.useCallback(_=>{const de=Zc.find(Ae=>Ae.value===_);return de?u==="zh"?de.labelZh:de.label:String(_)},[u]),ha=[...qS,...Su],p0=f.useCallback(_=>{const de=ha.find(Ae=>Ae.family===_);return(de==null?void 0:de.displayName)||_},[ha]);return t?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"text-property-panel-overlay",onClick:h0,onPointerDown:_=>_.stopPropagation(),onMouseDown:_=>_.stopPropagation()}),l.jsxs("div",{ref:p,className:q("text-property-panel",{"is-open":t}),style:{top:g.top,left:g.left},onPointerDown:_=>_.stopPropagation(),onMouseDown:_=>_.stopPropagation(),onClick:_=>_.stopPropagation(),onPointerUp:_=>_.stopPropagation(),children:[l.jsxs("div",{className:"text-property-panel__header",children:[l.jsx("span",{className:"text-property-panel__header-title",children:c("propertyPanel.title")}),l.jsx("button",{className:"text-property-panel__header-close",onClick:n,children:l.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:l.jsx("path",{d:"M1 1L13 13M1 13L13 1",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]}),l.jsxs("div",{className:"text-property-panel__content",children:[l.jsx("div",{className:"text-property-panel__section",children:l.jsxs("div",{className:"text-property-panel__section-content",children:[l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"字号":"Size"}),l.jsxs("div",{className:"inline-control__slider-group",children:[l.jsx("input",{type:"range",className:"inline-control__slider",value:b,min:8,max:100,step:1,onChange:_=>{S(_.target.value),jt(_.target.value)}}),l.jsx("span",{className:"inline-control__value",children:b})]})]}),l.jsxs("div",{className:"inline-control inline-control--dropdown",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"字体":"Font"}),l.jsxs("div",{className:"custom-dropdown",children:[l.jsxs("div",{className:q("custom-dropdown__trigger",{"is-expanded":w}),onClick:()=>{y(!w),da(!1)},children:[l.jsx("span",{className:"custom-dropdown__value",style:{fontFamily:`'${T}', sans-serif`},children:p0(T)}),l.jsx("svg",{className:"custom-dropdown__arrow",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:l.jsx("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),l.jsx("div",{className:q("custom-dropdown__menu custom-dropdown__menu--font",{"is-open":w}),children:ha.map(_=>l.jsxs("div",{className:q("custom-dropdown__item custom-dropdown__item--font",{"is-active":T===_.family}),onClick:()=>{nn(_),y(!1)},children:[l.jsx("span",{className:"custom-dropdown__item-label",children:_.displayName}),l.jsx("span",{className:"custom-dropdown__item-preview",style:{fontFamily:`'${_.family}', sans-serif`},children:_.previewText})]},_.family))})]})]}),l.jsxs("div",{className:"inline-control inline-control--dropdown",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"字重":"Weight"}),l.jsxs("div",{className:"custom-dropdown",children:[l.jsxs("div",{className:q("custom-dropdown__trigger",{"is-expanded":ua}),onClick:()=>{da(!ua),y(!1)},children:[l.jsx("span",{className:"custom-dropdown__value",style:{fontWeight:x},children:f0(x)}),l.jsx("svg",{className:"custom-dropdown__arrow",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:l.jsx("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),l.jsx("div",{className:q("custom-dropdown__menu",{"is-open":ua}),children:Zc.map(_=>l.jsx("div",{className:q("custom-dropdown__item",{"is-active":x===_.value}),onClick:()=>{Ge(_.value),da(!1)},children:l.jsx("span",{className:"custom-dropdown__item-label",style:{fontWeight:_.value},children:u==="zh"?_.labelZh:_.label})},_.value))})]})]}),l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"对齐":"Align"}),l.jsxs("div",{className:"align-buttons align-buttons--compact",children:[l.jsx("button",{className:q("align-buttons__btn",{"is-active":B==="left"}),onClick:()=>rt("left"),title:u==="zh"?"左对齐":"Align Left",children:l.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:l.jsx("path",{d:"M2 3h12v2H2V3zm0 4h8v2H2V7zm0 4h12v2H2v-2z"})})}),l.jsx("button",{className:q("align-buttons__btn",{"is-active":B==="center"}),onClick:()=>rt("center"),title:u==="zh"?"居中对齐":"Align Center",children:l.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:l.jsx("path",{d:"M2 3h12v2H2V3zm2 4h8v2H4V7zm-2 4h12v2H2v-2z"})})}),l.jsx("button",{className:q("align-buttons__btn",{"is-active":B==="right"}),onClick:()=>rt("right"),title:u==="zh"?"右对齐":"Align Right",children:l.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:l.jsx("path",{d:"M2 3h12v2H2V3zm4 4h8v2H6V7zm-4 4h12v2H2v-2z"})})})]})]}),l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"样式":"Style"}),l.jsxs("div",{className:"style-buttons",children:[l.jsx("button",{className:q("style-buttons__btn",{"is-active":N}),onClick:Lt,title:u==="zh"?"加粗":"Bold",children:l.jsx("span",{className:"style-buttons__icon style-buttons__icon--bold",children:"B"})}),l.jsx("button",{className:q("style-buttons__btn",{"is-active":Z}),onClick:dt,title:u==="zh"?"斜体":"Italic",children:l.jsx("span",{className:"style-buttons__icon style-buttons__icon--italic",children:"I"})}),l.jsx("button",{className:q("style-buttons__btn",{"is-active":R}),onClick:dn,title:u==="zh"?"下划线":"Underline",children:l.jsx("span",{className:"style-buttons__icon style-buttons__icon--underline",children:"U"})}),l.jsx("button",{className:q("style-buttons__btn",{"is-active":ce}),onClick:aa,title:u==="zh"?"删除线":"Strikethrough",children:l.jsx("span",{className:"style-buttons__icon style-buttons__icon--strikethrough",children:"S"})}),l.jsx("button",{className:q("style-buttons__btn",{"is-active":ae}),onClick:la,title:u==="zh"?"上标":"Superscript",children:l.jsxs("span",{className:"style-buttons__icon style-buttons__icon--superscript",children:["X",l.jsx("sup",{children:"2"})]})}),l.jsx("button",{className:q("style-buttons__btn",{"is-active":me}),onClick:ca,title:u==="zh"?"下标":"Subscript",children:l.jsxs("span",{className:"style-buttons__icon style-buttons__icon--subscript",children:["X",l.jsx("sub",{children:"2"})]})})]})]}),l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"大小写":"Case"}),l.jsxs("div",{className:"case-buttons",children:[l.jsx("button",{className:q("case-buttons__btn",{"is-active":Ie==="uppercase"}),onClick:()=>xs("uppercase"),title:u==="zh"?"全大写":"Uppercase",children:"AA"}),l.jsx("button",{className:q("case-buttons__btn",{"is-active":Ie==="lowercase"}),onClick:()=>xs("lowercase"),title:u==="zh"?"全小写":"Lowercase",children:"aa"}),l.jsx("button",{className:q("case-buttons__btn",{"is-active":Ie==="capitalize"}),onClick:()=>xs("capitalize"),title:u==="zh"?"首字母大写":"Capitalize",children:"Aa"})]})]}),l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"行高":"Line"}),l.jsxs("div",{className:"inline-control__slider-group",children:[l.jsx("input",{type:"range",className:"inline-control__slider",value:j,min:.8,max:3,step:.1,onChange:_=>gt(Number(_.target.value))}),l.jsx("span",{className:"inline-control__value",children:j.toFixed(1)})]})]}),l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"字距":"Spacing"}),l.jsxs("div",{className:"inline-control__slider-group",children:[l.jsx("input",{type:"range",className:"inline-control__slider",value:D,min:-2,max:10,step:.5,onChange:_=>kt(Number(_.target.value))}),l.jsxs("span",{className:"inline-control__value",children:[D,"px"]})]})]})]})}),l.jsxs("div",{className:"text-property-panel__section",children:[l.jsx("div",{className:"text-property-panel__section-title",children:c("propertyPanel.textColor")}),l.jsx("div",{className:"text-property-panel__section-content text-color-picker",children:l.jsx(Ci,{value:Fe,onChange:di,showAlpha:!0,showEyeDropper:!0,showPresets:!0,showRecentColors:!0,showHexInput:!0})})]}),l.jsx("div",{className:"text-property-panel__section",children:l.jsxs("div",{className:"text-property-panel__section-content",children:[l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"高亮":"Highlight"}),l.jsxs("div",{className:"highlight-colors",children:[l.jsx("button",{className:q("highlight-colors__btn highlight-colors__btn--none",{"is-active":!ze}),onClick:()=>re(null),title:u==="zh"?"无":"None",children:l.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",children:l.jsx("line",{x1:"2",y1:"2",x2:"14",y2:"14",stroke:"currentColor",strokeWidth:"2"})})}),["#FFEB3B","#4CAF50","#2196F3","#E91E63","#FF9800","#9C27B0"].map(_=>l.jsx("button",{className:q("highlight-colors__btn",{"is-active":ze===_}),style:{backgroundColor:_},onClick:()=>re(_),title:_},_))]})]}),l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"描边":"Stroke"}),l.jsxs("div",{className:"inline-control__slider-group",children:[l.jsx("input",{type:"range",className:"inline-control__slider",value:it,min:0,max:3,step:.5,onChange:_=>Oi(Number(_.target.value))}),l.jsxs("span",{className:"inline-control__value",children:[it,"px"]}),it>0&&l.jsx("input",{type:"color",className:"inline-control__color-input",value:P,onChange:_=>Oi(it,_.target.value)})]})]}),(R||ce)&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"线型":"Line Style"}),l.jsx("div",{className:"decoration-style-buttons",children:["solid","double","dotted","dashed","wavy"].map(_=>l.jsx("button",{className:q("decoration-style-buttons__btn",{"is-active":$===_}),onClick:()=>d0($===_?null:_),title:_,children:l.jsx("span",{className:`decoration-preview decoration-preview--${_}`,children:"Ab"})},_))})]}),l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"线色":"Line Color"}),l.jsxs("div",{className:"highlight-colors",children:[l.jsx("button",{className:q("highlight-colors__btn highlight-colors__btn--none",{"is-active":!I}),onClick:()=>qc(null),title:u==="zh"?"默认":"Default",children:l.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",children:l.jsx("line",{x1:"2",y1:"2",x2:"14",y2:"14",stroke:"currentColor",strokeWidth:"2"})})}),["#E91E63","#FF5722","#4CAF50","#2196F3","#9C27B0","#000000"].map(_=>l.jsx("button",{className:q("highlight-colors__btn",{"is-active":I===_}),style:{backgroundColor:_},onClick:()=>qc(_),title:_},_))]})]})]})]})}),l.jsx("div",{className:"text-property-panel__section",children:l.jsxs("div",{className:"text-property-panel__section-content",children:[l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"阴影":"Shadow"}),l.jsx("div",{className:q("toggle-switch__control toggle-switch__control--inline",{"is-active":F}),onClick:st})]}),F&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"effect-presets",children:Object.entries(mu.textShadow).map(([_,de])=>l.jsx("div",{className:q("effect-presets__item",{"is-active":te===_}),onClick:()=>Un(_,de),title:_,children:l.jsx("span",{style:{textShadow:ja(de)},children:"Aa"})},_))}),l.jsxs("div",{className:"effect-config",children:[l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"颜色":"Color"}),l.jsxs("div",{className:"inline-control__color-group",children:[l.jsxs(at,{open:Pt,onOpenChange:Rt,placement:"bottom",sideOffset:8,children:[l.jsx(lt,{asChild:!0,children:l.jsx("button",{className:"inline-control__color-trigger",style:{backgroundColor:G.color.startsWith("rgba")?`#${((Qc=G.color.match(/\d+/g))==null?void 0:Qc.slice(0,3).map(_=>parseInt(_).toString(16).padStart(2,"0")).join(""))||"000000"}`:G.color},onClick:()=>Rt(!Pt)})}),l.jsx(ct,{children:l.jsx(qe,{padding:4,className:"color-picker-popover",children:l.jsx(Ci,{value:G.color.startsWith("rgba")?`#${((Jc=G.color.match(/\d+/g))==null?void 0:Jc.slice(0,3).map(_=>parseInt(_).toString(16).padStart(2,"0")).join(""))||"000000"}`:G.color,onChange:_=>{const de=parseInt(_.slice(1,3),16),Ae=parseInt(_.slice(3,5),16),et=parseInt(_.slice(5,7),16),sn=G.color.match(/[\d.]+\)$/),Wn=sn?parseFloat(sn[0]):.5;Se("color",`rgba(${de}, ${Ae}, ${et}, ${Wn})`)},showAlpha:!1,showEyeDropper:!0,showPresets:!0,showRecentColors:!0,showHexInput:!0})})})]}),l.jsx("input",{type:"range",className:"inline-control__slider inline-control__slider--short",value:(()=>{const _=G.color.match(/[\d.]+\)$/);return _?parseFloat(_[0])*100:50})(),min:0,max:100,step:5,title:u==="zh"?"透明度":"Opacity",onChange:_=>{const de=Number(_.target.value)/100,Ae=G.color.match(/\d+/g);if(Ae&&Ae.length>=3){const[et,sn,Wn]=Ae.slice(0,3);Se("color",`rgba(${et}, ${sn}, ${Wn}, ${de})`)}}}),l.jsxs("span",{className:"inline-control__value inline-control__value--narrow",children:[(()=>{const _=G.color.match(/[\d.]+\)$/);return _?Math.round(parseFloat(_[0])*100):50})(),"%"]})]})]}),l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"X偏移":"X"}),l.jsxs("div",{className:"inline-control__slider-group",children:[l.jsx("input",{type:"range",className:"inline-control__slider",value:G.offsetX,min:-20,max:20,step:1,onChange:_=>Se("offsetX",Number(_.target.value))}),l.jsxs("span",{className:"inline-control__value",children:[G.offsetX,"px"]})]})]}),l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"Y偏移":"Y"}),l.jsxs("div",{className:"inline-control__slider-group",children:[l.jsx("input",{type:"range",className:"inline-control__slider",value:G.offsetY,min:-20,max:20,step:1,onChange:_=>Se("offsetY",Number(_.target.value))}),l.jsxs("span",{className:"inline-control__value",children:[G.offsetY,"px"]})]})]}),l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"模糊":"Blur"}),l.jsxs("div",{className:"inline-control__slider-group",children:[l.jsx("input",{type:"range",className:"inline-control__slider",value:G.blur,min:0,max:30,step:1,onChange:_=>Se("blur",Number(_.target.value))}),l.jsxs("span",{className:"inline-control__value",children:[G.blur,"px"]})]})]})]})]})]})}),l.jsx("div",{className:"text-property-panel__section",children:l.jsxs("div",{className:"text-property-panel__section-content",children:[l.jsxs("div",{className:"inline-control",children:[l.jsx("label",{className:"inline-control__label",children:u==="zh"?"渐变":"Gradient"}),l.jsx("div",{className:q("toggle-switch__control toggle-switch__control--inline",{"is-active":se}),onClick:Ue})]}),se&&l.jsx("div",{className:"gradient-editor-wrapper",children:l.jsx($g,{value:ie,onChange:Ve,showPresets:!0,showHistory:!1,inline:!0,customPresets:Le.map(_=>_.css),onSavePreset:be,onDeletePreset:_=>{const de=Le[_];de&&je(de.id)}})})]})})]})]}),h]}):null};let li={x:0,y:0},fs=new Set,So=!1;const Kg=e=>{li={x:e.clientX,y:e.clientY},fs.forEach(t=>t(li))},Yg=e=>{li={x:e.clientX,y:e.clientY},fs.forEach(t=>t(li))},qg=e=>{li={x:e.clientX,y:e.clientY},fs.forEach(t=>t(li))},lP=()=>{So||(document.addEventListener("mousemove",Kg,!0),document.addEventListener("mousedown",Yg,!0),document.addEventListener("mouseup",qg,!0),So=!0)},cP=()=>{So&&fs.size===0&&(document.removeEventListener("mousemove",Kg,!0),document.removeEventListener("mousedown",Yg,!0),document.removeEventListener("mouseup",qg,!0),So=!1)},uP=()=>{const[e,t]=f.useState(()=>li),n=f.useRef();return f.useEffect(()=>(n.current=i=>{t(i)},fs.add(n.current),lP(),t(li),()=>{n.current&&fs.delete(n.current),cP()}),[]),e},dP=({visible:e,videoUrl:t,onClose:n,onConfirm:i})=>{const{language:s}=Ee(),r=f.useRef(null),o=f.useRef(null),a=f.useRef(null),[c,u]=f.useState(!0),[d,h]=f.useState(0),[p,g]=f.useState(0),[m,b]=f.useState(""),[S,w]=f.useState(!1),[y,T]=f.useState(!1);f.useEffect(()=>(e&&t&&(u(!0),b(""),w(!1),T(!1)),()=>{a.current!==null&&window.clearTimeout(a.current)}),[e,t]);const C=()=>{const k=r.current;k&&(h(k.duration),w(!0))},E=f.useCallback((k,N=!1)=>{const M=r.current;if(!M)return;a.current!==null&&(window.clearTimeout(a.current),a.current=null);const Z=()=>{if(M.readyState<2){console.warn("Video not ready for seeking, readyState:",M.readyState);const he=()=>{M.currentTime=k,M.removeEventListener("canplay",he)};M.addEventListener("canplay",he);return}M.currentTime=k};N?Z():a.current=window.setTimeout(Z,150)},[]);f.useEffect(()=>{const k=r.current;if(S&&k&&d>0){const N=Math.max(0,d-.1);g(N),E(N,!0)}},[S,d,E]);const v=f.useCallback(()=>{const k=r.current,N=o.current;if(!k||!N)return;const M=N.getContext("2d");if(M)try{N.width=k.videoWidth,N.height=k.videoHeight,M.drawImage(k,0,0,N.width,N.height);const Z=N.toDataURL("image/png");b(Z)}catch(Z){console.warn("Failed to generate frame image (likely due to CORS):",Z);try{M.fillStyle="#000",M.fillRect(0,0,N.width,N.height),M.fillStyle="#fff",M.font="16px Arial",M.textAlign="center",M.fillText("视频帧预览不可用",N.width/2,N.height/2);const he=N.toDataURL("image/png");b(he)}catch(he){console.error("Failed to create placeholder image:",he),b("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==")}}},[]),x=f.useCallback(()=>{y||(v(),u(!1))},[y,v]),O=()=>{T(!0)},B=k=>{if(r.current&&d>0&&S){const M=k/100*d;g(M),E(M,!1)}},X=()=>{T(!1),u(!0),r.current&&S&&E(p,!0)},j=k=>{if(!r.current||d===0||!S)return;const M=parseFloat(k.target.value);if(isNaN(M))return;const Z=Math.max(0,Math.min(d,M));g(Z),E(Z,!0),u(!0)},L=()=>{m&&(i(m,p),n())},D=k=>{const N=Math.floor(k/60),M=(k%60).toFixed(1);return`${N}:${M.padStart(4,"0")}`};return l.jsx(ZS,{visible:e,onClose:n,header:s==="zh"?"选择视频帧":"Select Video Frame",width:600,destroyOnClose:!0,footer:!1,children:l.jsxs("div",{className:"video-frame-selector",children:[l.jsx("video",{ref:r,src:t,style:{display:"none"},muted:!0,playsInline:!0,preload:"auto",crossOrigin:"anonymous",onLoadedMetadata:C,onSeeked:x}),l.jsx("canvas",{ref:o,style:{display:"none"}}),l.jsx("div",{className:"frame-preview",children:c?l.jsxs("div",{className:"loading-placeholder",children:[l.jsx("div",{className:"loading-spinner"}),l.jsx("div",{className:"loading-text",children:s==="zh"?"加载视频中...":"Loading video..."})]}):l.jsx("div",{className:"frame-image-container",children:l.jsx("img",{src:m,alt:"Video frame",className:"frame-image"})})}),l.jsxs("div",{className:"time-controls",children:[l.jsxs("div",{className:"time-display",children:[l.jsx("span",{className:"current-time",children:D(p)}),l.jsx("span",{className:"separator",children:"/"}),l.jsx("span",{className:"total-time",children:D(d)})]}),l.jsx("div",{className:"progress-container",children:l.jsx("input",{type:"range",min:0,max:100,value:d>0?p/d*100:0,onChange:k=>B(Number(k.target.value)),onMouseDown:O,onMouseUp:X,onTouchStart:O,onTouchEnd:X,className:"progress-slider",disabled:c&&!y})}),l.jsxs("div",{className:"time-input-container",children:[l.jsx("label",{className:"time-input-label",children:s==="zh"?"精确时间 (秒):":"Precise time (seconds):"}),l.jsx("input",{type:"number",min:0,max:d,step:.1,value:p.toFixed(1),onChange:j,className:"time-input",disabled:c})]})]}),l.jsxs("div",{className:"actions",children:[l.jsx("button",{className:"action-button secondary",onClick:n,children:s==="zh"?"取消":"Cancel"}),l.jsx("button",{className:"action-button primary",onClick:L,disabled:c||!m,children:s==="zh"?"确认插入":"Confirm Insert"})]})]})})},hP=async(e,t,n,i)=>{if(!e||!t)throw new Error("Board and video element are required");try{const s=Ft(e,[t],!1),r=[s.x,s.y+s.height+20],o=new Image,a=await new Promise(u=>{o.onload=()=>{u({width:o.naturalWidth,height:o.naturalHeight})},o.onerror=()=>{u({width:s.width,height:s.height})},o.src=n}),c={url:n,width:a.width,height:a.height,isVideoFrame:!0,videoTimestamp:i,sourceVideoId:t.id||"unknown"};Mo.insertImage(e,c,r)}catch(s){throw console.error("Failed to insert video frame:",s),new Error(`Video frame insertion failed: ${s instanceof Error?s.message:"Unknown error"}`)}};function fP(){if(typeof VideoDecoder>"u"||typeof VideoEncoder>"u")throw new Error(`当前浏览器不支持 WebCodecs API。
|
|
42
|
-
请使用 Chrome 94+ 或 Edge 94+ 浏览器。`)}function pP(){const e=[{mimeType:"video/mp4;codecs=avc1",extension:"mp4"},{mimeType:"video/webm;codecs=vp9",extension:"webm"},{mimeType:"video/webm;codecs=vp8",extension:"webm"}];for(const t of e)if(MediaRecorder.isTypeSupported(t.mimeType))return t;return console.warn("[WebCodecs] No preferred format supported, using default"),{mimeType:"video/webm",extension:"webm"}}async function gP(e,t,n){const i=document.createElement("canvas"),s=i.getContext("2d",{willReadFrequently:!1});if(!s)throw new Error("无法创建 Canvas 2D 上下文");const r=document.createElement("video");r.crossOrigin="anonymous",r.src=e[0],await new Promise((y,T)=>{r.onloadedmetadata=()=>y(),r.onerror=()=>T(new Error("无法加载第一个视频"))}),i.width=r.videoWidth,i.height=r.videoHeight;const o=pP(),a=new AudioContext,c=a.createMediaStreamDestination(),u=i.captureStream(30),d=new MediaStream([...u.getVideoTracks(),...c.stream.getAudioTracks()]),h=new MediaRecorder(d,{mimeType:o.mimeType,videoBitsPerSecond:8e6,audioBitsPerSecond:128e3}),p=[];h.ondataavailable=y=>{y.data.size>0&&p.push(y.data)},h.start(),t==null||t(0,"encoding","开始录制视频...");const g=(n==null?void 0:n.transitions)||[],m=(n==null?void 0:n.transitionDuration)??.5;for(let y=0;y<e.length;y++){t==null||t(y/e.length*100,"encoding",`正在处理视频 ${y+1}/${e.length}...`);const T=document.createElement("video");T.crossOrigin="anonymous",T.src=e[y],T.volume=1,await new Promise((x,O)=>{T.onloadedmetadata=()=>x(),T.onerror=()=>O(new Error(`无法加载视频 ${y+1}`))});let C=null;try{C=a.createMediaElementSource(T),C.connect(c)}catch(x){console.warn(`[WebCodecs] Failed to connect audio from video ${y+1}:`,x)}const E=y<g.length?g[y]:"cut",v=E==="dissolve"||E==="fade_to_black";await new Promise(x=>{T.play().catch(B=>{console.warn(`[WebCodecs] Failed to play video ${y+1}:`,B)});const O=()=>{if(T.ended){x();return}let B=1;if(v&&T.duration>0){const X=T.duration-T.currentTime;X<m&&(B=Math.max(0,X/m))}E==="fade_to_black"&&B<1&&(s.fillStyle="#000",s.fillRect(0,0,i.width,i.height)),s.globalAlpha=B,s.drawImage(T,0,0,i.width,i.height),s.globalAlpha=1,requestAnimationFrame(O)};T.onended=()=>x(),O()}),C&&C.disconnect(),T.pause(),T.src="",T.load()}t==null||t(100,"finalizing","正在生成最终视频..."),await new Promise(y=>{h.onstop=()=>y(),h.stop()}),await a.close();const b=o.mimeType.split(";")[0],S=new Blob(p,{type:b}),w=e.length*8;try{const{unifiedCacheService:y}=await Ne(async()=>{const{unifiedCacheService:v}=await import("./tool-windows-
|
|
42
|
+
请使用 Chrome 94+ 或 Edge 94+ 浏览器。`)}function pP(){const e=[{mimeType:"video/mp4;codecs=avc1",extension:"mp4"},{mimeType:"video/webm;codecs=vp9",extension:"webm"},{mimeType:"video/webm;codecs=vp8",extension:"webm"}];for(const t of e)if(MediaRecorder.isTypeSupported(t.mimeType))return t;return console.warn("[WebCodecs] No preferred format supported, using default"),{mimeType:"video/webm",extension:"webm"}}async function gP(e,t,n){const i=document.createElement("canvas"),s=i.getContext("2d",{willReadFrequently:!1});if(!s)throw new Error("无法创建 Canvas 2D 上下文");const r=document.createElement("video");r.crossOrigin="anonymous",r.src=e[0],await new Promise((y,T)=>{r.onloadedmetadata=()=>y(),r.onerror=()=>T(new Error("无法加载第一个视频"))}),i.width=r.videoWidth,i.height=r.videoHeight;const o=pP(),a=new AudioContext,c=a.createMediaStreamDestination(),u=i.captureStream(30),d=new MediaStream([...u.getVideoTracks(),...c.stream.getAudioTracks()]),h=new MediaRecorder(d,{mimeType:o.mimeType,videoBitsPerSecond:8e6,audioBitsPerSecond:128e3}),p=[];h.ondataavailable=y=>{y.data.size>0&&p.push(y.data)},h.start(),t==null||t(0,"encoding","开始录制视频...");const g=(n==null?void 0:n.transitions)||[],m=(n==null?void 0:n.transitionDuration)??.5;for(let y=0;y<e.length;y++){t==null||t(y/e.length*100,"encoding",`正在处理视频 ${y+1}/${e.length}...`);const T=document.createElement("video");T.crossOrigin="anonymous",T.src=e[y],T.volume=1,await new Promise((x,O)=>{T.onloadedmetadata=()=>x(),T.onerror=()=>O(new Error(`无法加载视频 ${y+1}`))});let C=null;try{C=a.createMediaElementSource(T),C.connect(c)}catch(x){console.warn(`[WebCodecs] Failed to connect audio from video ${y+1}:`,x)}const E=y<g.length?g[y]:"cut",v=E==="dissolve"||E==="fade_to_black";await new Promise(x=>{T.play().catch(B=>{console.warn(`[WebCodecs] Failed to play video ${y+1}:`,B)});const O=()=>{if(T.ended){x();return}let B=1;if(v&&T.duration>0){const X=T.duration-T.currentTime;X<m&&(B=Math.max(0,X/m))}E==="fade_to_black"&&B<1&&(s.fillStyle="#000",s.fillRect(0,0,i.width,i.height)),s.globalAlpha=B,s.drawImage(T,0,0,i.width,i.height),s.globalAlpha=1,requestAnimationFrame(O)};T.onended=()=>x(),O()}),C&&C.disconnect(),T.pause(),T.src="",T.load()}t==null||t(100,"finalizing","正在生成最终视频..."),await new Promise(y=>{h.onstop=()=>y(),h.stop()}),await a.close();const b=o.mimeType.split(";")[0],S=new Blob(p,{type:b}),w=e.length*8;try{const{unifiedCacheService:y}=await Ne(async()=>{const{unifiedCacheService:v}=await import("./tool-windows-C4D0lII2.js").then(x=>x.oG);return{unifiedCacheService:v}},__vite__mapDeps([0]),import.meta.url),T=`merged-video-${Date.now()}`,C=`/__aitu_cache__/video/${T}.mp4`,E=C;return await y.cacheMediaFromBlob(E,S,"video",{taskId:T}),{blob:S,url:C,duration:w,taskId:T}}catch(y){console.warn("[WebCodecs] Failed to cache video, using blob URL:",y);const T=URL.createObjectURL(S);return{blob:S,url:T,duration:w}}}class qi{constructor(){fP()}static getInstance(){return qi.instance||(qi.instance=new qi),qi.instance}async mergeVideos(t,n,i){if(t.length===0)throw new Error("没有视频可合并");if(t.length===1){n==null||n(0,"downloading","下载视频...");const r=await(await fetch(t[0])).blob();return{blob:r,url:URL.createObjectURL(r),duration:0}}try{n==null||n(0,"downloading",`下载 ${t.length} 个视频...`);const s=[];for(let r=0;r<t.length;r++){n==null||n(r/t.length*100,"downloading",`下载视频 ${r+1}/${t.length}...`);const a=await(await fetch(t[r])).blob();s.push(a)}return await gP(t,n,i)}catch(s){throw console.error("[WebCodecs] Merge failed:",s),new Error(`视频合并失败: ${s instanceof Error?s.message:String(s)}`)}}static isSupported(){return typeof VideoDecoder<"u"&&typeof VideoEncoder<"u"}}const mP=qi.getInstance();async function SP(e,t,n){return mP.mergeVideos(e,t,n)}const Ch="笔记",bP="新笔记",yP=24;function wP(e){var t;return((t=e.title)==null?void 0:t.trim())||bP}function TP(e){return(e.body||"").trim()}async function vP(){const{knowledgeBaseService:e}=await Ne(async()=>{const{knowledgeBaseService:s}=await import("./tool-windows-C4D0lII2.js").then(r=>r.o$);return{knowledgeBaseService:s}},__vite__mapDeps([0]),import.meta.url);await e.initialize();const n=(await e.getAllDirectories()).find(s=>s.name===Ch);if(n)return{knowledgeBaseService:e,directory:n};const i=await e.createDirectory(Ch);return{knowledgeBaseService:e,directory:i}}function xP(e,t,n){const i=e.children.findIndex(s=>s.id===t);i<0||ue.setNode(e,{noteId:n},[i])}function EP(e){var n,i;if(Mt(e)){const s=(n=e.title)!=null&&n.trim()?`# ${e.title.trim()}`:"",r=((i=e.body)==null?void 0:i.trim())||"";return[s,r].filter(Boolean).join(`
|
|
43
43
|
|
|
44
44
|
`).trim()}const t=[];if("data"in e&&Array.isArray(e.data)){for(const s of e.data)if(vr.isNode(s)){const r=vr.string(s).trim();r&&t.push(r)}}if("text"in e){if(typeof e.text=="string"){const s=e.text.trim();s&&t.push(s)}else if(e.text&&typeof e.text=="object"&&vr.isNode(e.text)){const s=vr.string(e.text).trim();s&&t.push(s)}}if("textContent"in e&&typeof e.textContent=="string"){const s=e.textContent.trim();s&&t.push(s)}return t.join(`
|
|
45
|
-
`).trim()}function _P(e){return V.isDrawElement(e)&&V.isText(e)}function CP(e,t){return[...t].sort((n,i)=>{const s=Ft(e,[n],!1),r=Ft(e,[i],!1);return Math.abs(s.x-r.x)<=yP&&Math.abs(s.y-r.y)>.5?s.y-r.y:s.x-r.x})}async function Zg(e,t,n="zh"){if(!t)return null;if(t.noteId)return t.noteId;try{const{knowledgeBaseService:i,directory:s}=await vP(),r=await i.createNote(wP(t),s.id),o=TP(t);return o&&await i.updateNote(r.id,{content:o}),xP(e,t.id,r.id),r.id}catch(i){return console.error("Failed to create note for card:",i),oe.error(n==="zh"?"保存到知识库失败":"Failed to save to knowledge base"),null}}async function PP(e,t){const n=[...new Set(e.filter(Boolean))];if(n.length===0)return;const{knowledgeBaseService:i}=await Ne(async()=>{const{knowledgeBaseService:r}=await import("./tool-windows-
|
|
45
|
+
`).trim()}function _P(e){return V.isDrawElement(e)&&V.isText(e)}function CP(e,t){return[...t].sort((n,i)=>{const s=Ft(e,[n],!1),r=Ft(e,[i],!1);return Math.abs(s.x-r.x)<=yP&&Math.abs(s.y-r.y)>.5?s.y-r.y:s.x-r.x})}async function Zg(e,t,n="zh"){if(!t)return null;if(t.noteId)return t.noteId;try{const{knowledgeBaseService:i,directory:s}=await vP(),r=await i.createNote(wP(t),s.id),o=TP(t);return o&&await i.updateNote(r.id,{content:o}),xP(e,t.id,r.id),r.id}catch(i){return console.error("Failed to create note for card:",i),oe.error(n==="zh"?"保存到知识库失败":"Failed to save to knowledge base"),null}}async function PP(e,t){const n=[...new Set(e.filter(Boolean))];if(n.length===0)return;const{knowledgeBaseService:i}=await Ne(async()=>{const{knowledgeBaseService:r}=await import("./tool-windows-C4D0lII2.js").then(o=>o.o$);return{knowledgeBaseService:r}},__vite__mapDeps([0]),import.meta.url);await i.initialize();const s=n[0];await i.updateNote(s,{content:t});for(const r of n.slice(1))await i.deleteNote(r);return s}const Qg=async(e,t,n="zh")=>{if(t){if(t.noteId){window.dispatchEvent(new CustomEvent("kb:open",{detail:{noteId:t.noteId}}));return}try{const i=await Zg(e,t,n);if(!i)return;window.dispatchEvent(new CustomEvent("kb:open",{detail:{noteId:i}}))}catch(i){console.error("Failed to create note for card:",i),oe.error(n==="zh"?"无法打开知识库笔记":"Failed to open knowledge base note")}}};function Ph(e){return eb(e).replace(/\u00a0/g," ").replace(/[ \t]+\n/g,`
|
|
46
46
|
`).replace(/\n{3,}/g,`
|
|
47
47
|
|
|
48
48
|
`).trim()}function Yn(e){if(!e)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(i=>Yn(i)).filter(Boolean).join(`
|
|
@@ -53,17 +53,17 @@ Style: Disney-style animation, vibrant colors, dreamy lighting.`,"a beautiful su
|
|
|
53
53
|
|
|
54
54
|
`));return{text:s,source:s?"element":null,title:(i==null?void 0:i.title)||(t.length===1?"画布朗读":`已选 ${t.length} 个元素`),sourceId:t.length===1?`${t[0].type}:${t[0].id}`:`selection:${t.map(r=>r.id).sort().join("|")}`,origin:i?{kind:"card",id:i.id}:void 0}}function Jg(e){return!e.text||!e.sourceId?null:Lf({elementId:e.sourceId,title:e.title,content:e.text,origin:e.origin||{kind:"card",id:e.sourceId}})}function IP(e,t){const n=Jg(t);if(!n)return[];if(!e.children||!t.origin||t.origin.kind!=="card")return[n];const i=QS(e,e.children.filter(Mt));return i.length<=1?[n]:i.map(s=>{var r;return s.id===((r=t.origin)==null?void 0:r.id)?n:Lf({elementId:`card:${s.id}`,title:s.title||"卡片朗读",content:[s.title,s.body].filter(Boolean).join(`
|
|
55
55
|
|
|
56
|
-
`),origin:{kind:"card",id:s.id}})}).filter(s=>!!s)}const DP=f.lazy(()=>Ne(()=>import("./tool-windows-
|
|
56
|
+
`),origin:{kind:"card",id:s.id}})}).filter(s=>!!s)}const DP=f.lazy(()=>Ne(()=>import("./tool-windows-C4D0lII2.js").then(e=>e.o_),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.ImageEditor}))),NP=f.lazy(()=>Ne(()=>import("./tool-windows-C4D0lII2.js").then(e=>e.p1),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.FrameSlideshow}))),RP=()=>{var it,Ye,P,A,$,Q;const e=bt(),n=He(e).filter(I=>!tb(I)),{openDialog:i}=Ut(),{language:s,t:r}=Ee(),[o,a]=f.useState(!1),c=f.useRef(o),[u,d]=f.useState(!1),[h,p]=f.useState(null),[g,m]=f.useState(!1),[b,S]=f.useState(""),[w,y]=f.useState(null),[T,C]=f.useState(!1),E=f.useRef(!1),[v,x]=f.useState(!1),[O,B]=f.useState(),[X,j]=f.useState({text:"",title:"",source:null}),[L,D]=f.useState(),[k,N]=f.useState(),M=f.useRef(null);uP();const Z=nb(),he=Z.mediaType==="reading"?Z.activeReadingSourceId:void 0,R=!!X.sourceId&&!!he&&he.startsWith(X.sourceId),W=f.useMemo(()=>n.map(I=>I.id).sort().join("|"),[n]),ce=R?Z.playing?s==="zh"?"暂停朗读":"Pause reading":s==="zh"?"继续朗读":"Resume reading":s==="zh"?"语音朗读":"Read aloud";f.useEffect(()=>{if(n.length===0||o){j(H=>H.text||H.source?{text:"",title:"",source:null}:H);return}const I=()=>{const H=MP(e,n);j(F=>F.text===H.text&&F.source===H.source&&F.title===H.title&&F.sourceId===H.sourceId?F:H)};return I(),document.addEventListener("selectionchange",I),()=>{document.removeEventListener("selectionchange",I)}},[e,W,o]);const K=n.length>0&&!Zs(e),{viewport:ae,selection:le,children:me}=e,{refs:Te,floatingStyles:ze}=$l({placement:"top",middleware:[Xl(12),Of({padding:16}),Kl({fallbackPlacements:["bottom","right","left"]})]});let Y={fill:"red"};if(K&&!o){const I=n.some(re=>OP(e,re))&&!z.hasBeenTextEditing(e),H=n.some(re=>HP(e,re)),F=n.length>0&&n.every(re=>V.isDrawElement(re)&&V.isText(re)),U=n.some(re=>sm(e,re))&&!z.hasBeenTextEditing(e),te=n.some(re=>BP(e,re))&&!z.hasBeenTextEditing(e),ee=n.some(re=>wn(re)),G=n.some(re=>Yl(re)),J=n.some(re=>Mt(re)),se=n.length>1&&n.every(re=>Mt(re)||_P(re)),Re=n.length>0&&!ee&&!G&&!J&&n.some(re=>V.isDrawElement(re)&&V.isImage(re))&&!z.hasBeenTextEditing(e),ut=n.length===1&&wn(n[0])&&!z.hasBeenTextEditing(e),Oe=!ee&&!G&&!J&&!z.hasBeenTextEditing(e),ie=n[0],De=V.isDrawElement(ie)&&V.isImage(ie)&&((it=ie.url)==null?void 0:it.startsWith("data:image/svg+xml")),Le=n.length===1&&!ee&&!G&&V.isDrawElement(n[0])&&V.isImage(n[0])&&!De&&!z.hasBeenTextEditing(e),ke=Le,Fe=Le,Nt=n.length>0&&!G&&n.some(re=>V.isDrawElement(re)&&V.isImage(re)||wn(re)||Kn(re))&&!z.hasBeenTextEditing(e),Pt=n.length>1&&!se&&!ee&&!G&&n.every(re=>V.isDrawElement(re)&&V.isImage(re)||V.isDrawElement(re)&&Wl([re])||V.isDrawElement(re)&&V.isShapeElement(re)&&!V.isImage(re)||V.isDrawElement(re)&&V.isArrowLine(re)||V.isDrawElement(re)&&V.isVectorLine(re)||V.isDrawElement(re)&&V.isTable(re)||Xe.isFreehand(re)||Je.isPenPath(re)||tn.isMindElement(e,re))&&!z.hasBeenTextEditing(e),jt=n.filter(re=>wn(re)).length>1&&!z.hasBeenTextEditing(e),nn=n.filter(re=>Je.isPenPath(re)),di=nn.length>0&&!z.hasBeenTextEditing(e);let Un;if(nn.length>0){const re=nn[0].cornerRadius??0;Un=nn.every(Oi=>(Oi.cornerRadius??0)===re)?re:void 0}const Se=n.filter(re=>Xe.isFreehand(re)),Ve=(nn.length>0||Se.length>0)&&!z.hasBeenTextEditing(e);let be;const je=[...nn.map(re=>re.strokeWidth??2),...Se.map(re=>re.strokeWidth??2)];if(je.length>0){const re=je[0];be=je.every(Oi=>Oi===re)?re:void 0}const st=n.length>0&&!G&&!z.hasBeenTextEditing(e),Ue=n.length>0&&n.every(re=>tn.isMindElement(e,re)),Ge=n.length>1&&!Ue&&!z.hasBeenTextEditing(e),rt=n.length>1&&!Ue&&!z.hasBeenTextEditing(e),gt=n.length>1&&!z.hasBeenTextEditing(e)&&n.every(re=>FP(e,re)),kt=n.length>0&&!z.hasBeenTextEditing(e)&&!!bu(e,n),Lt=n.length===1&&Mt(n[0])&&!!n[0].noteId&&!z.hasBeenTextEditing(e),dt=n.length===1&&Mt(n[0])&&!n[0].noteId&&!z.hasBeenTextEditing(e),dn=se&&!z.hasBeenTextEditing(e),aa=n.length===1&&Ti(n[0])&&!z.hasBeenTextEditing(e),la=n.length===1&&Kn(n[0])&&!z.hasBeenTextEditing(e),ca=typeof window<"u"&&"speechSynthesis"in window&&!z.hasBeenTextEditing(e)&&X.text.length>0;Y={...jP(e),hasFill:I,hasFontColor:H,hasFontSize:H,hasStroke:U,hasStrokeStyle:te,hasStrokeWidth:Ve,strokeWidth:be,hasText:H,isTextOnly:F,hasAIImage:Oe,hasAIVideo:Re,hasVideoFrame:ut,hasSplitImage:ke,hasImageEdit:Fe,hasDownloadable:Nt,hasMergeable:Pt,hasVideoMergeable:jt,hasCornerRadius:di,cornerRadius:Un,hasSizeInput:st,hasAlignment:Ge,hasDistribute:rt,hasBoolean:gt,hasMindmapToPPT:kt,hasCardEdit:Lt,hasCardSave:dt,hasContentMerge:dn,hasFramePlay:aa,hasAudioPlayer:la,hasTextToSpeech:ca}}const Ie=async(I,H)=>{if(!I)return;const F=I.title?`# ${I.title}
|
|
57
57
|
|
|
58
58
|
`:"",U=I.body||"",te=`${F}${U}`.trim();try{console.info("[CardCopy] Copy text from card",{source:H,id:I.id}),await kb(te),oe.success(s==="zh"?"已复制到剪贴板":"Copied to clipboard",2e3)}catch{oe.error(s==="zh"?"复制失败":"Copy failed",2e3)}},$e=async()=>{const I=CP(e,n);if(I.length<2)return;const H=I[0],F=I.map((te,ee)=>ee===0&&Mt(H)&&Mt(te)?(te.body||"").trim():EP(te)).filter(Boolean).join(`
|
|
59
59
|
|
|
60
|
-
`).trim();if(!F){oe.warning(s==="zh"?"没有可合并的内容":"No content to merge");return}const U=I.flatMap(te=>Mt(te)&&te.noteId?[te.noteId]:[]);try{const te=await PP(U,F),ee=I.slice(1).map(J=>e.children.findIndex(se=>se.id===J.id)).filter(J=>J>=0).sort((J,se)=>se-J);for(const J of ee)ue.removeNode(e,[J]);let G;if(Mt(H)){const J=e.children.findIndex(Re=>Re.id===H.id);if(J<0)throw new Error(s==="zh"?"合并目标不存在":"Merge target missing");const se={body:F};te&&(se.noteId=te),ue.setNode(e,se,[J]),G=e.children[J]}else{const J=Ft(e,[H],!1),se=e.children.findIndex(ie=>ie.id===H.id);if(se<0)throw new Error(s==="zh"?"合并目标不存在":"Merge target missing");const Re=Math.max(J.width,320),ut=Math.max(J.height,180),Oe={type:"card",id:`card-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,9)}`,body:F,fillColor:"#FA8C16",points:[[J.x,J.y],[J.x+Re,J.y+ut]],children:[],...te?{noteId:te}:{}};ue.insertNode(e,Oe,[se]),ue.removeNode(e,[se+1]),G=e.children[se]}ii(e),G&&Pi(e,G),oe.success(s==="zh"?`已合并 ${I.length} 个元素`:`Merged ${I.length} elements`)}catch(te){console.error("[PopupToolbar] Failed to merge content:",te),oe.error((te==null?void 0:te.message)||(s==="zh"?"合并内容失败":"Failed to merge content"))}};return f.useEffect(()=>{if(K){const I=n.length>0;if(!o&&I){let H,F;const U=He(e),te=Ft(e,U,!1),[ee,G]=ge.getPoints(te),J=xr(e,Os(e,ee)),se=xr(e,Os(e,G));H=J[0]+(se[0]-J[0])/2,F=J[1],Te.setPositionReference({getBoundingClientRect(){return{width:1,height:1,x:H,y:F,top:F,left:H,right:H+1,bottom:F+1}}})}}},[ae,le,me,o]),f.useEffect(()=>{if(K&&!o&&M.current){const I=M.current.getBoundingClientRect();D({top:I.top,left:I.left,width:I.width,height:I.height});const H=He(e);if(H.length>0){const F=Ft(e,H,!1),[U,te]=ge.getPoints(F),ee=xr(e,Os(e,U)),G=xr(e,Os(e,te));N({top:ee[1],left:ee[0],right:G[0],bottom:G[1],width:G[0]-ee[0],height:G[1]-ee[1]})}}},[K,o,ze,e]),f.useEffect(()=>{E.current=T},[T]),f.useEffect(()=>{if(n.length===0&&!o){const I=setTimeout(()=>{C(!1)},50);return()=>clearTimeout(I)}},[n.length,o]),f.useEffect(()=>{c.current=o},[o]),f.useEffect(()=>{const{pointerUp:I,pointerMove:H}=e;return e.pointerMove=F=>{(er(e)||Qs(e))&&!c.current&&a(!0),H(F)},e.pointerUp=F=>{c.current&&(er(e)||Qs(e))&&a(!1),I(F)},()=>{e.pointerUp=I,e.pointerMove=H}},[e]),l.jsxs(l.Fragment,{children:[K&&!o&&l.jsx(qe,{padding:1,className:q("popup-toolbar",Dt),ref:I=>{Te.setFloating(I),M.current=I},style:ze,"data-testid":"popup-toolbar",children:l.jsxs(pt.Row,{gap:1,children:[Y.hasFill&&l.jsx(HC,{board:e,currentColor:Y.fill,title:r("toolbar.fillColor"),children:l.jsx("label",{className:q("fill-label","color-label",{"color-white":Y.fill&&Js(Y.fill)&&Df(_i(Y.fill)),"color-mixed":Y.fill===void 0,"color-gradient":Y.fill&&Rn(Y.fill)&&Y.fill.type==="gradient","color-image":Y.fill&&Rn(Y.fill)&&Y.fill.type==="image"}),style:Y.fill===void 0?void 0:{background:Js(Y.fill)?Y.fill:Rn(Y.fill)?Y.fill.type==="gradient"&&Y.fill.gradient?ib(Y.fill.gradient):Y.fill.type==="solid"&&Y.fill.solid?Y.fill.solid.color:Y.fill.type==="image"&&((Ye=Y.fill.image)!=null&&Ye.imageUrl)?`url(${Y.fill.image.imageUrl}) center/cover no-repeat`:void 0:void 0}})},3),Y.hasStroke&&l.jsx(CC,{board:e,currentColor:Y.strokeColor,title:r("toolbar.stroke"),hasStrokeStyle:Y.hasStrokeStyle||!1,hasStrokeWidth:Y.hasStrokeWidth||!1,currentStrokeWidth:Y.strokeWidth,children:l.jsx("label",{className:q("stroke-label","color-label",{"color-mixed":Y.strokeColor===void 0}),style:{borderColor:Y.strokeColor}})},2),Y.hasFontColor&&l.jsx(xC,{board:e,currentColor:(P=Y.marks)==null?void 0:P.color,title:r("toolbar.fontColor"),fontColorIcon:l.jsx(sb,{currentColor:(A=Y.marks)==null?void 0:A.color})},0),Y.hasFontSize&&l.jsx(_C,{board:e,currentFontSize:Y.fontSize,title:r("toolbar.fontSize")},1),Y.hasCornerRadius&&l.jsx(FC,{board:e,currentRadius:Y.cornerRadius,title:r("toolbar.cornerRadius"),selectionRect:k},"corner-radius"),Y.hasText&&l.jsx(VC,{board:e,title:"Link"},4),Y.isTextOnly&&l.jsx(eP,{board:e,language:s,title:s==="zh"?"提示词":"Prompts"},"prompt"),Y.hasTextToSpeech&&l.jsx(ne,{className:"text-to-speech",type:"icon",icon:R&&Z.playing?l.jsx(ab,{size:15}):l.jsx(lb,{size:15}),visible:!0,selected:R&&Z.playing,title:ce,"aria-label":ce,"data-track":"toolbar_click_text_to_speech",onPointerUp:()=>{if(!X.text)return;const I=Jg(X);if(!I)return;const H=IP(e,X);if(R){Z.playing?Z.pausePlayback():Z.resumePlayback();return}yu({source:I,queue:H.length>0?H:[I],queueTab:{queueId:ob,queueName:rb}})}},"text-to-speech"),Y.hasText&&l.jsx(ne,{className:"property-settings",type:"icon",icon:l.jsx(cb,{}),visible:!0,selected:T,title:r("propertyPanel.title"),"aria-label":r("propertyPanel.title"),"data-track":"toolbar_click_property_settings",onPointerUp:()=>{C(!T)}},"property-settings"),Y.hasAlignment&&l.jsx(nP,{board:e,title:r("toolbar.alignment")},"alignment"),Y.hasDistribute&&l.jsx(iP,{board:e,title:r("toolbar.distribute")},"distribute"),Y.hasBoolean&&l.jsx(sP,{board:e,title:r("toolbar.boolean")},"boolean"),Y.hasMindmapToPPT&&l.jsx(ne,{className:"mindmap-to-ppt",type:"icon",icon:l.jsx(ub,{size:15}),visible:!0,title:s==="zh"?"转换为PPT":"Convert to PPT","aria-label":s==="zh"?"转换为PPT":"Convert to PPT","data-track":"toolbar_click_mindmap_to_ppt",onPointerUp:async()=>{const I=bu(e,n);if(!I)return;const H=oe.loading(s==="zh"?"正在转换为PPT...":"Converting to PPT...",0);try{const{generatePPTFromMindmap:F}=await Ne(async()=>{const{generatePPTFromMindmap:te}=await import("./tool-windows-hjm6YiPY.js").then(ee=>ee.oI);return{generatePPTFromMindmap:te}},__vite__mapDeps([0]),import.meta.url),U=await F(e,I);oe.close(H),U.success?oe.success(s==="zh"?`已生成 ${U.pageCount} 页PPT`:`Generated ${U.pageCount} PPT slides`):oe.error(U.error||(s==="zh"?"转换失败":"Conversion failed"))}catch(F){oe.close(H),oe.error(F.message||(s==="zh"?"转换失败":"Conversion failed"))}}},"mindmap-to-ppt"),Y.hasCardEdit&&l.jsx(ne,{className:"card-edit",type:"icon",icon:l.jsx(wu,{size:15}),visible:!0,title:s==="zh"?"在知识库中编辑":"Edit in Knowledge Base","aria-label":s==="zh"?"在知识库中编辑":"Edit in Knowledge Base","data-track":"toolbar_click_card_edit",onPointerUp:async()=>{const I=n[0];I&&await Qg(e,I,s)}},"card-edit"),Y.hasCardSave&&l.jsx(ne,{className:"card-save",type:"icon",icon:l.jsx(Bf,{size:15}),visible:!0,title:s==="zh"?"保存到知识库":"Save to Knowledge Base","aria-label":s==="zh"?"保存到知识库":"Save to Knowledge Base","data-track":"toolbar_click_card_save",onPointerUp:async()=>{const I=n[0];if(!I)return;await Zg(e,I,s)&&oe.success(s==="zh"?"已保存到知识库":"Saved to knowledge base")}},"card-save"),(Y.hasCardEdit||Y.hasCardSave)&&l.jsx(ne,{className:"card-copy",type:"icon",icon:l.jsx(db,{size:15}),visible:!0,title:s==="zh"?"复制文本内容":"Copy text content","aria-label":s==="zh"?"复制文本内容":"Copy text content","data-track":"toolbar_click_card_copy",onPointerDown:({event:I})=>{I.stopPropagation()},onPointerUp:async()=>{await Ie(n[0],"card-copy")}},"card-copy"),Y.hasContentMerge&&l.jsx(ne,{className:"content-merge",type:"icon",icon:l.jsx(Tu,{}),visible:!0,title:s==="zh"?"合并内容":"Merge Content","aria-label":s==="zh"?"合并内容":"Merge Content","data-track":"toolbar_click_content_merge",onPointerUp:()=>{$e()}},"content-merge"),Y.hasAIImage&&l.jsx(ne,{className:"ai-image",type:"icon",icon:l.jsx(Oo,{}),visible:!0,title:s==="zh"?"AI图片生成":"AI Image Generation","aria-label":s==="zh"?"AI图片生成":"AI Image Generation","data-track":"toolbar_click_ai_image",onPointerUp:()=>{i(ln.aiImageGeneration)}},5),Y.hasAIVideo&&l.jsx(ne,{className:"ai-video",type:"icon",icon:l.jsx(Bo,{}),visible:!0,title:s==="zh"?"AI视频生成":"AI Video Generation","aria-label":s==="zh"?"AI视频生成":"AI Video Generation","data-track":"toolbar_click_ai_video",onPointerUp:()=>{i(ln.aiVideoGeneration)}},6),Y.hasVideoFrame&&l.jsx(ne,{className:"video-frame",type:"icon",icon:l.jsx(hb,{}),visible:!0,title:s==="zh"?"视频帧选择":"Video Frame Selection","aria-label":s==="zh"?"视频帧选择":"Video Frame Selection","data-track":"toolbar_click_video_frame",onPointerUp:()=>{const I=n.find(H=>wn(H));I&&(p(I),d(!0))}},7),Y.hasSplitImage&&l.jsx(ne,{className:"split-image",type:"icon",icon:l.jsx(pb,{}),visible:!0,title:s==="zh"?"智能拆图":"Smart Split","aria-label":s==="zh"?"智能拆图":"Smart Split","data-track":"toolbar_click_split_image",onPointerUp:async()=>{const I=n[0];if(V.isImage(I)&&I.url){const H=oe.loading(s==="zh"?"正在分析图片...":"Analyzing image...",0);try{const F=Ft(e,[I],!1),U=await fb(e,I.url,{sourceRect:{x:F.x,y:F.y,width:F.width,height:F.height},scrollToResult:!0});oe.close(H),U.success?oe.success(s==="zh"?`成功拆分为 ${U.count} 张图片`:`Split into ${U.count} images`):oe.warning(U.error||(s==="zh"?"拆图失败":"Split failed"))}catch(F){oe.close(H),oe.error(F.message||(s==="zh"?"拆图失败":"Split failed"))}}}},"split-image"),Y.hasImageEdit&&l.jsx(ne,{className:"image-edit",type:"icon",icon:l.jsx(wu,{size:15}),visible:!0,title:s==="zh"?"编辑图片":"Edit Image","aria-label":s==="zh"?"编辑图片":"Edit Image","data-track":"toolbar_click_image_edit",onPointerUp:()=>{const I=n[0];V.isImage(I)&&I.url&&(S(I.url),y(I),m(!0))}},"image-edit"),Y.hasDownloadable&&l.jsx(ne,{className:"download",type:"icon",icon:l.jsx(Sb,{}),visible:!0,title:s==="zh"?"下载":"Download","aria-label":s==="zh"?"下载":"Download","data-track":"toolbar_click_download",onPointerUp:async()=>{const I=[];for(const U of n)V.isDrawElement(U)&&V.isImage(U)&&U.url?I.push({url:U.url,type:"image"}):wn(U)&&U.url?I.push({url:U.url,type:"video"}):Kn(U)&&U.audioUrl&&I.push({url:U.audioUrl,type:"audio",filename:gb(U.title,"audio","mp3"),audioMetadata:{title:U.title,prompt:U.prompt,tags:U.tags,coverUrl:U.previewImageUrl,artist:U.modelVersion||"Aitu",album:"Aitu Generated"}});if(I.length===0){oe.warning(s==="zh"?"没有可下载的内容":"No downloadable content");return}const H=I.length>1?s==="zh"?"正在打包下载...":"Packaging download...":s==="zh"?"正在下载...":"Downloading...",F=oe.loading(H,0);try{const{unifiedCacheService:U}=await Ne(async()=>{const{unifiedCacheService:J}=await import("./tool-windows-hjm6YiPY.js").then(se=>se.oG);return{unifiedCacheService:J}},__vite__mapDeps([0]),import.meta.url),{downloadFromBlob:te}=await Ne(async()=>{const{downloadFromBlob:J}=await import("./tool-windows-hjm6YiPY.js").then(se=>se.oF);return{downloadFromBlob:J}},__vite__mapDeps([0]),import.meta.url),ee=[];for(const J of I)if(J.url.startsWith("blob:")){const se=J.url.indexOf("#"),Re=se>0?J.url.substring(se+1):null;if(Re&&Re.startsWith("merged-video-")){const ut=await U.getCachedBlob(Re);if(ut){const Oe=ut.type||"video/webm",ie=Oe.startsWith("video/mp4")?"mp4":Oe.startsWith("video/webm")?"webm":"bin",De=`merged-video-${Date.now()}.${ie}`;te(ut,De);continue}else console.warn("[Download] Cache not found for taskId:",Re)}try{const Oe=await(await fetch(J.url)).blob(),ie=Oe.type.startsWith("video/mp4")?"mp4":Oe.type.startsWith("video/webm")?"webm":Oe.type.startsWith("image/")?"png":"bin",De=`${J.type}_${Date.now()}.${ie}`;te(Oe,De)}catch(ut){throw console.error("[Download] Failed to fetch blob URL:",ut),new Error(`Failed to download ${J.type}: Blob URL inaccessible`)}}else ee.push(J);let G;ee.length>0&&(G=await mb(ee)),oe.close(F),G!=null&&G.openedCount&&G.downloadedCount===0?oe.success(s==="zh"?G.openedCount>1?`已打开 ${G.openedCount} 个链接,请在新标签页下载`:"资源不支持直接下载,已打开链接":G.openedCount>1?`Opened ${G.openedCount} links for download`:"Opened link for download"):oe.success(I.length>1?s==="zh"?`已下载 ${I.length} 个文件`:`Downloaded ${I.length} files`:s==="zh"?"下载成功":"Download complete")}catch(U){oe.close(F),oe.error(U.message||(s==="zh"?"下载失败":"Download failed"))}}},"download"),Y.hasMergeable&&l.jsx(ne,{className:"merge",type:"icon",icon:l.jsx(Tu,{}),visible:!0,title:s==="zh"?"合并为图片":"Merge to Image","aria-label":s==="zh"?"合并为图片":"Merge to Image","data-track":"toolbar_click_merge",onPointerUp:async()=>{const I=bb("图片合并"),H=oe.loading(s==="zh"?"正在合并...":"Merging...",0);try{const F=n.filter(st=>{const Ue=st.url||st.imageUrl;if(!Ue||Ue.startsWith("/")||Ue.startsWith("data:")||Ue.startsWith("blob:"))return!1;try{return new URL(Ue).origin!==location.origin}catch{return!1}});if(F.length>0){const st=F.map(async rt=>{const gt=rt.url||rt.imageUrl;try{const kt=new AbortController,Lt=setTimeout(()=>kt.abort(),3e3),dt=await fetch(gt,{method:"HEAD",mode:"cors",signal:kt.signal});return clearTimeout(Lt),dt.ok}catch{return!1}});if((await Promise.all(st)).some(rt=>!rt)){oe.close(H),oe.warning(s==="zh"?"部分外部图片无法访问,请先下载到本地后再合并":"Some external images are inaccessible. Please download them locally first."),I();return}}const U=Ft(e,n,!1),te=[...n].sort((st,Ue)=>{const Ge=e.children.findIndex(gt=>gt.id===st.id),rt=e.children.findIndex(gt=>gt.id===Ue.id);return Ge-rt}),ee=await yb(e,{elements:te,fillStyle:"transparent",inlineStyleClassNames:".extend,.emojis,.text",ratio:2});if(!ee)throw new Error(s==="zh"?"合并失败:无法生成图片":"Merge failed: Unable to generate image");const G=new Image;await new Promise((st,Ue)=>{G.onload=()=>st(),G.onerror=()=>Ue(new Error("Failed to load merged image")),G.src=ee});const J=document.createElement("canvas");J.width=G.width,J.height=G.height;const se=J.getContext("2d");if(!se)throw new Error("Failed to get canvas context");se.drawImage(G,0,0);const Re=wb(J),{canvas:ut,left:Oe,top:ie,trimmedWidth:De,trimmedHeight:Le}=Re,ke=await new Promise((st,Ue)=>{ut.toBlob(Ge=>{Ge?st(Ge):Ue(new Error("Failed to convert canvas to blob"))},"image/png")}),{unifiedCacheService:Fe}=await Ne(async()=>{const{unifiedCacheService:st}=await import("./tool-windows-hjm6YiPY.js").then(Ue=>Ue.oG);return{unifiedCacheService:st}},__vite__mapDeps([0]),import.meta.url),Nt=`merged-image-${Date.now()}`,Pt=`/__aitu_cache__/image/${Nt}.png`,Rt=Pt;await Fe.cacheMediaFromBlob(Rt,ke,"image",{taskId:Nt});const jt=2,nn=U.x+Oe/jt,di=U.y+ie/jt,Un=De/jt,Se=Le/jt;Ka(e);const Ve=e.children.length,be={url:Pt,width:Un,height:Se};Mo.insertImage(e,be,[nn,di]);const je=e.children[Ve];je&&(ii(e),Pi(e,je)),oe.close(H),I(),oe.success(s==="zh"?`已将 ${n.length} 个元素合并为图片`:`Merged ${n.length} elements into image`)}catch(F){oe.close(H),I(),oe.error(F.message||(s==="zh"?"合并失败":"Merge failed"))}}},"merge"),Y.hasVideoMergeable&&l.jsx(ne,{className:"video-merge",type:"icon",icon:l.jsx(Tb,{}),visible:!0,title:s==="zh"?"合成视频":"Merge Videos","aria-label":s==="zh"?"合成视频":"Merge Videos","data-track":"toolbar_click_video_merge",onPointerUp:async()=>{const I=[];for(const F of n)wn(F)&&F.url&&I.push(F.url);if(I.length<2){oe.warning(s==="zh"?"请选择至少2个视频":"Please select at least 2 videos");return}const H=oe.loading(s==="zh"?"正在合成视频...":"Merging videos...",0);try{const F=await SP(I,(U,te)=>{const ee={downloading:s==="zh"?"下载视频...":"Downloading videos...",decoding:s==="zh"?"解码视频...":"Decoding videos...",encoding:s==="zh"?"编码视频...":"Encoding videos...",finalizing:s==="zh"?"生成文件中...":"Finalizing..."}});oe.close(H);try{const{quickInsert:U}=await Ne(async()=>{const{quickInsert:te}=await import("./canvas-insertion-ZEZkcXvB.js");return{quickInsert:te}},__vite__mapDeps([0]),import.meta.url);await U("video",F.url),oe.success(s==="zh"?`已合成并插入 ${I.length} 个视频`:`Merged and inserted ${I.length} videos`)}catch(U){console.error("[VideoMerge] Failed to insert video:",U);const te=F.blob.type||"video/webm",ee=te.startsWith("video/mp4")?"mp4":"webm",G=new Blob([F.blob],{type:te}),J=URL.createObjectURL(G),se=document.createElement("a");se.href=J,se.download=`merged-video-${Date.now()}.${ee}`,document.body.appendChild(se),se.click(),document.body.removeChild(se),setTimeout(()=>URL.revokeObjectURL(J),1e3),oe.warning(s==="zh"?`视频已合成,但插入失败,已自动下载 (${ee.toUpperCase()})`:`Video merged but failed to insert, downloaded as ${ee.toUpperCase()}`)}}catch(F){oe.close(H),oe.error(F.message||(s==="zh"?"视频合成失败":"Video merge failed"))}}},"video-merge"),l.jsx(tP,{board:e,title:r("textEffect.layer")},"layer-control"),Y.hasSizeInput&&l.jsx(zC,{board:e},"size-input"),Y.hasFramePlay&&l.jsx(ne,{className:"frame-play",type:"icon",icon:l.jsx(vu,{size:15}),visible:!0,title:s==="zh"?"播放幻灯片":"Play Slideshow","aria-label":s==="zh"?"播放幻灯片":"Play Slideshow","data-track":"toolbar_click_frame_play",onPointerUp:()=>{const I=n.find(H=>Ti(H));I&&(B(I.id),x(!0))}},"frame-play"),Y.hasAudioPlayer&&l.jsx(ne,{className:"audio-player-play",type:"icon",icon:l.jsx(vu,{size:15}),visible:!0,title:s==="zh"?"在音乐播放器中播放":"Play in Music Player","aria-label":s==="zh"?"在音乐播放器中播放":"Play in Music Player","data-track":"toolbar_click_audio_player_play",onPointerUp:()=>{const I=n.find(H=>Kn(H));!I||!Kn(I)||yu({source:{elementId:I.id,audioUrl:I.audioUrl,title:I.title,duration:I.duration,previewImageUrl:I.previewImageUrl,providerTaskId:I.providerTaskId,clipId:I.clipId,clipIds:I.clipIds},queue:Qa(e.children),queueTab:{queueId:Ff,queueName:Hf}})}},"audio-player-play"),l.jsx(ne,{className:"duplicate",type:"icon",icon:l.jsx(_b,{}),visible:!0,title:r("general.duplicate"),"aria-label":r("general.duplicate"),"data-track":"toolbar_click_duplicate",onPointerUp:()=>{if(n.length===1&&Ti(n[0])){const H=vb(e,n[0],s);H&&xb(e,H)}else Eb(e)}},8),l.jsx(ne,{className:"trash",type:"icon",icon:l.jsx(so,{}),visible:!0,title:r("general.delete"),"aria-label":r("general.delete"),"data-track":"toolbar_click_delete",onPointerUp:()=>{Ka(e)}},9)]})}),u&&h&&l.jsx(dP,{visible:u,videoUrl:h.url||"",onClose:()=>{d(!1),p(null)},onConfirm:async(I,H)=>{try{h&&await hP(e,h,I,H)}catch(F){console.error("Failed to insert video frame:",F)}}}),g&&b&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(DP,{visible:g,imageUrl:b,showOverwrite:!!w,onClose:()=>{m(!1),S(""),y(null)},onOverwrite:async I=>{if(w)try{const{unifiedCacheService:H}=await Ne(async()=>{const{unifiedCacheService:se}=await import("./tool-windows-hjm6YiPY.js").then(Re=>Re.oG);return{unifiedCacheService:se}},__vite__mapDeps([0]),import.meta.url),F=`edited-image-${Date.now()}`,U=`/__aitu_cache__/image/${F}.png`,ee=await(await fetch(I)).blob();await H.cacheMediaFromBlob(U,ee,"image",{taskId:F});const G=new Image;await new Promise((se,Re)=>{G.onload=()=>se(),G.onerror=()=>Re(new Error("Failed to load edited image")),G.src=I});const J=e.children.findIndex(se=>se.id===w.id);if(J>=0){const se=e.children[J],{newPoints:Re}=await Gf({url:se.url,width:se.width,height:se.height,points:se.points||[[0,0],[0,0]]},G.naturalWidth,G.naturalHeight);ue.setNode(e,{url:U,width:G.naturalWidth,height:G.naturalHeight,points:Re},[J])}}catch(H){console.error("Failed to update image:",H),oe.error(s==="zh"?"更新失败":"Update failed")}},onInsert:async I=>{try{const{unifiedCacheService:H}=await Ne(async()=>{const{unifiedCacheService:ie}=await import("./tool-windows-hjm6YiPY.js").then(De=>De.oG);return{unifiedCacheService:ie}},__vite__mapDeps([0]),import.meta.url),F=`edited-image-${Date.now()}`,U=`/__aitu_cache__/image/${F}.png`,ee=await(await fetch(I)).blob();await H.cacheMediaFromBlob(U,ee,"image",{taskId:F});const G=new Image;await new Promise((ie,De)=>{G.onload=()=>ie(),G.onerror=()=>De(new Error("Failed to load edited image")),G.src=I});const J=Ao(e),se=w?w.points[1][0]-w.points[0][0]+20:0,Re=w?w.points[0][0]:J?J[0]+100:100,ut=w?w.points[0][1]:J?J[1]+100:100,Oe=[Re+se,ut];await ql(e,U,Oe,!1,{width:G.naturalWidth,height:G.naturalHeight},!1,!0)}catch(H){console.error("Failed to insert image:",H),oe.error(s==="zh"?"插入失败":"Insert failed")}}})}),Y.hasText&&l.jsx(aP,{board:e,isOpen:T,onClose:()=>C(!1),currentFontSize:Y.fontSize,currentFontFamily:($=Y.marks)==null?void 0:$["font-family"],currentColor:(Q=Y.marks)==null?void 0:Q.color,toolbarRect:L,selectionRect:k}),v&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(NP,{visible:v,board:e,onClose:()=>{x(!1),B(void 0)},initialFrameId:O})})]})},em=(e,t)=>{const n=Vf(t);return{fill:Ho(t),strokeColor:Ab(e,t),fontSize:n["font-size"],marks:n}},tm=(e,t)=>{const n=Vf(t);return{fill:Ho(t),strokeColor:Mb(e,t),fontSize:n["font-size"],marks:n}},jP=e=>{const t=He(e);if(t.length===0)return{fill:void 0,strokeColor:void 0};if(t.length===1){const n=t[0];return Mt(n)?{fill:n.fillColor,strokeColor:void 0}:tn.isMindElement(e,n)?em(e,n):Xe.isFreehand(n)?nm(e,n):Je.isPenPath(n)?im(e,n):tm(e,n)}return LP(e,t)},LP=(e,t)=>{const n=t.map(a=>Mt(a)?{fill:a.fillColor,strokeColor:void 0}:tn.isMindElement(e,a)?em(e,a):Xe.isFreehand(a)?nm(e,a):Je.isPenPath(a)?im(e,a):V.isDrawElement(a)?tm(e,a):{fill:void 0,strokeColor:void 0}),i=n.map(a=>a.fill),s=n.map(a=>a.strokeColor),r=i.every(a=>a===i[0]),o=s.every(a=>a===s[0]);return{fill:r?i[0]:void 0,strokeColor:o?s[0]:void 0}},nm=(e,t)=>({fill:Ho(t),strokeColor:Uf(e,t)}),im=(e,t)=>({fill:Ho(t),strokeColor:t.strokeColor,cornerRadius:t.cornerRadius}),OP=(e,t)=>Mt(t)||tn.isMindElement(e,t)||Cb(e,t)?!0:Xe.isFreehand(t)?Pb(t.points):Je.isPenPath(t)?t.closed:V.isDrawElement(t)?V.isShapeElement(t)&&!V.isImage(t)&&!V.isText(t)&&zf(t):!1,sm=(e,t)=>tn.isMindElement(e,t)||Xe.isFreehand(t)||Je.isPenPath(t)?!0:V.isDrawElement(t)?V.isShapeElement(t)&&!V.isImage(t)&&!V.isText(t)||V.isArrowLine(t)||V.isVectorLine(t)||V.isTable(t):!1,BP=(e,t)=>sm(e,t),HP=(e,t)=>tn.isMindElement(e,t)?!0:V.isDrawElement(t)?Wl([t]):!1,FP=(e,t)=>{if(Je.isPenPath(t))return t.closed;if(Xe.isFreehand(t)){const n=t.points;if(!n||n.length<3)return!1;const i=n[0],s=n[n.length-1];return Math.hypot(s[0]-i[0],s[1]-i[1])<=10}return V.isDrawElement(t)?V.isImage(t)||V.isText(t)||V.isArrowLine(t)||V.isVectorLine(t)?!1:V.isShapeElement(t)&&zf(t):(tn.isMindElement(e,t),!1)},ra=Gn.createContext({}),kh=(e="",t=!1)=>`menu-item menu-item-base ${e} ${t?"menu-item--active":""}`.trim(),GP=(e,t)=>{const n=f.useContext(ra);return Ib(e,i=>{var r;const s=new CustomEvent(Zl.MENU_ITEM_SELECT,{bubbles:!0,cancelable:!0});t==null||t(s),s.defaultPrevented||(r=n.onSelect)==null||r.call(n,s)})},zP=({icon:e,shortcut:t,children:n})=>l.jsxs(l.Fragment,{children:[e&&l.jsx("div",{className:"menu-item__icon",children:e}),l.jsx("div",{className:"menu-item__text",children:n}),t&&l.jsx("div",{className:"menu-item__shortcut",children:t})]}),Be=({icon:e,onSelect:t,children:n,shortcut:i,className:s,selected:r,submenu:o,...a})=>{const[c,u]=f.useState(!1),d=f.useRef(),h=GP(a.onClick,t),p=l.jsx(zP,{icon:e,shortcut:i,children:n}),g=()=>{d.current&&window.clearTimeout(d.current),u(!0)},m=()=>{d.current=window.setTimeout(()=>{u(!1)},100)};return o?l.jsxs(at,{open:c,onOpenChange:u,placement:"right-start",children:[l.jsx(lt,{asChild:!0,children:l.jsx("button",{...a,type:"button",className:kh(s,r||c),title:a.title??a["aria-label"],onClick:h,onMouseEnter:g,onMouseLeave:m,role:"menuitem","aria-haspopup":"true","aria-expanded":c,children:p})}),l.jsx(ct,{onMouseEnter:g,onMouseLeave:m,children:o})]}):l.jsx("button",{...a,onClick:h,type:"button",className:kh(s,r),title:a.title??a["aria-label"],role:"menuitem",children:p})};Be.displayName="MenuItem";const rm=({children:e})=>l.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});rm.displayName="MenuItemBadge";Be.Badge=rm;const _n=({children:e,className:t="",onSelect:n,style:i,onClose:s})=>{const r=q(`menu ${t}`).trim(),o=f.useRef(null),a=f.useCallback(()=>o.current?Array.from(o.current.querySelectorAll("button.menu-item:not([disabled])")):[],[]),c=f.useCallback(u=>{var p,g,m,b;const d=a();if(d.length===0)return;const h=d.findIndex(S=>S===document.activeElement);switch(u.key){case"ArrowDown":{u.preventDefault();const S=h<d.length-1?h+1:0;(p=d[S])==null||p.focus();break}case"ArrowUp":{u.preventDefault();const S=h>0?h-1:d.length-1;(g=d[S])==null||g.focus();break}case"Home":{u.preventDefault(),(m=d[0])==null||m.focus();break}case"End":{u.preventDefault(),(b=d[d.length-1])==null||b.focus();break}case"Escape":{u.preventDefault(),s==null||s();break}case"Enter":case" ":{h>=0&&d[h]&&(u.preventDefault(),d[h].click());break}}},[a,s]);return f.useEffect(()=>{const u=a();u.length>0&&requestAnimationFrame(()=>{var d;(d=u[0])==null||d.focus()})},[a]),l.jsx(ra.Provider,{value:{onSelect:n},children:l.jsx("div",{className:r,style:i,"data-testid":"menu",onKeyDown:c,ref:o,role:"menu",children:l.jsx(qe,{className:"menu-container",padding:2,children:e})})})};_n.displayName="Menu";const om=()=>{const e=bt(),{t}=Ee();return l.jsx(Be,{"data-testid":"save-button","data-track":"toolbar_click_menu_save",onSelect:()=>{Wf(e)},icon:l.jsx(Bf,{}),"aria-label":t("menu.saveFile"),shortcut:"Cmd+S",children:t("menu.saveFile")})};om.displayName="SaveToFile";const am=()=>{const e=bt(),t=Og(),{t:n}=Ee(),i=(s,r,o)=>{e.children=s,e.viewport=r||{zoom:1},e.theme={themeColorMode:pi.default},t.update(e.children,{board:e,parent:e,parentG:z.getElementHost(e)}),fe.fitViewport(e)};return l.jsx(Be,{"data-testid":"open-button","data-track":"toolbar_click_menu_open",onSelect:()=>{Nb(e).then(s=>{s&&i(s.elements,s.viewport)})},icon:l.jsx(Db,{}),"aria-label":n("menu.open"),children:n("menu.open")})};am.displayName="OpenFile";const lm=()=>{const e=bt(),t=f.useContext(ra),{t:n}=Ee();return l.jsx(Be,{icon:l.jsx(Rb,{}),"data-testid":"image-export-button","data-track":"toolbar_click_menu_export",onSelect:()=>{zr(e,!0)},submenu:l.jsxs(_n,{onSelect:()=>{var s;const i=new CustomEvent(Zl.MENU_ITEM_SELECT,{bubbles:!0,cancelable:!0});(s=t.onSelect)==null||s.call(t,i)},children:[l.jsx(Be,{"data-track":"toolbar_click_menu_export_png",onSelect:()=>{zr(e,!0)},"aria-label":n("menu.exportImage.png"),children:n("menu.exportImage.png")}),l.jsx(Be,{"data-track":"toolbar_click_menu_export_jpg",onSelect:()=>{zr(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")})};lm.displayName="SaveAsImage";const cm=()=>{const{appState:e,setAppState:t}=Ut(),{t:n}=Ee();return l.jsx(Be,{icon:l.jsx(so,{}),"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")})};cm.displayName="CleanBoard";const um=({onOpenBackupRestore:e})=>{const{t}=Ee();return l.jsx(Be,{icon:l.jsx(Lb,{}),"data-track":"toolbar_click_menu_backup",onSelect:e,"aria-label":t("menu.backupRestore"),children:t("menu.backupRestore")})};um.displayName="BackupRestore";const dm=({onOpenCloudSync:e})=>{const{t}=Ee();return l.jsx(Be,{icon:l.jsx(Bb,{}),"data-track":"toolbar_click_menu_cloud_sync",onSelect:e,"aria-label":t("menu.cloudSync"),children:t("menu.cloudSync")})};dm.displayName="CloudSync";const hm=()=>{const{t:e}=Ee();return l.jsx(Be,{icon:l.jsx(Ob,{}),"data-track":"toolbar_click_menu_debug",onSelect:()=>{window.location.href="./sw-debug.html"},"aria-label":e("menu.debugPanel"),children:e("menu.debugPanel")})};hm.displayName="DebugPanel";const fm=()=>{const{appState:e,setAppState:t}=Ut(),{t:n}=Ee();return l.jsx(Be,{icon:l.jsx(Hb,{}),"data-track":"toolbar_click_menu_settings",onSelect:()=>{t({...e,openSettings:!0})},"aria-label":n("menu.settings"),children:n("menu.settings")})};fm.displayName="Settings";const pm=()=>{const{appState:e,setAppState:t}=Ut(),{t:n}=Ee();return l.jsx(Be,{icon:l.jsx(Fb,{}),"data-track":"toolbar_click_menu_commands",onSelect:()=>{t({...e,openCommandPalette:!0})},shortcut:"Cmd+K","aria-label":n("menu.commandPalette"),children:n("menu.commandPalette")})};pm.displayName="QuickCommands";const gm=()=>{const{t:e}=Ee();return l.jsx(Be,{icon:l.jsx(Gb,{}),"data-track":"toolbar_click_menu_manual",onSelect:()=>{window.open("./user-manual/index.html","_blank")},"aria-label":e("menu.userManual"),children:e("menu.userManual")})};gm.displayName="UserManual";const mm=()=>{var n;const{t:e}=Ee(),t=((n=document.querySelector('meta[name="app-version"]'))==null?void 0:n.getAttribute("content"))||"0.0.0";return l.jsx(Be,{"data-track":"toolbar_click_menu_version",onSelect:()=>{},"aria-label":e("menu.version"),children:l.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%"},children:[l.jsxs("span",{style:{color:"#666"},children:[e("menu.version"),":",t]}),l.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[l.jsx("span",{style:{color:"#1890ff",cursor:"pointer"},"data-track":"toolbar_click_menu_changelog",onClick:i=>{i.stopPropagation(),window.open("./versions.html","_blank")},children:e("menu.changelog")}),l.jsx("span",{style:{color:"#1890ff",cursor:"pointer"},"data-track":"toolbar_click_menu_more_versions",onClick:i=>{i.stopPropagation(),window.open("https://release.opentu.ai/","_blank")},children:e("menu.more")})]})]})})};mm.displayName="VersionInfo";async function VP(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 Sm=()=>{const e=bt(),{t}=Ee(),[n,i]=f.useState(!1),s=f.useCallback(async()=>{if(n)return;i(!0);const r=oe.loading(t("menu.cleanInvalidLinks.scanning"),0);try{const o=[];for(let u=0;u<e.children.length;u++){const d=e.children[u],h=d.url;if(!h||typeof h!="string")continue;const p=V.isDrawElement(d)&&V.isImage(d),g=wn(d);(p||g)&&o.push({element:d,index:u,url:h})}const a=[];if(await Promise.all(o.map(async({element:u,index:d,url:h})=>{await VP(h)||a.push({element:u,index:d})})),r.then(u=>{var d;return(d=u==null?void 0:u.close)==null?void 0:d.call(u)}),a.length===0){oe.success(t("menu.cleanInvalidLinks.noInvalid")),i(!1);return}a.sort((u,d)=>d.index-u.index);for(const{index:u}of a)ue.removeNode(e,[u]);const c=t("menu.cleanInvalidLinks.success").replace("{count}",String(a.length));oe.success(c)}catch(o){r.then(a=>{var c;return(c=a==null?void 0:a.close)==null?void 0:c.call(a)}),oe.error(t("menu.cleanInvalidLinks.error")),console.error("[CleanInvalidLinks] Error:",o)}finally{i(!1)}},[e,t,n]);return l.jsx(Be,{icon:l.jsx(jb,{}),"data-track":"toolbar_click_menu_clean_invalid_links",onSelect:s,"aria-label":t("menu.cleanInvalidLinks"),disabled:n,children:t("menu.cleanInvalidLinks")})};Sm.displayName="CleanInvalidLinks";const bm=()=>{const{language:e,setLanguage:t,t:n}=Ee(),i=f.useContext(ra);return l.jsx(Be,{icon:l.jsx($f,{}),"data-testid":"language-switcher-button",onSelect:()=>{},submenu:l.jsxs(_n,{onSelect:()=>{var r;const s=new CustomEvent(Zl.MENU_ITEM_SELECT,{bubbles:!0,cancelable:!0});(r=i.onSelect)==null||r.call(i,s)},children:[l.jsx(Be,{onSelect:()=>{t("zh")},"aria-label":n("language.chinese"),selected:e==="zh",children:n("language.chinese")}),l.jsx(Be,{onSelect:()=>{t("en")},"aria-label":n("language.english"),selected:e==="en",children:n("language.english")})]}),"aria-label":n("language.switcher"),children:n("language.switcher")})};bm.displayName="LanguageSwitcherMenu";const ur=()=>l.jsx("div",{style:{height:"1px",backgroundColor:"var(--color-gray-10)",margin:".5rem 0"}});ur.displayName="MenuSeparator";const Al=({children:e,buttonId:t,isVisible:n,visibleIndex:i=-1,disabled:s=!1})=>{const{t:r}=Ee(),{hideButton:o,showButton:a,resetToDefault:c,visibleButtons:u,reorderButton:d}=Fo(),[h,p]=f.useState(!1),[g,m]=f.useState({x:0,y:0}),b=f.useRef(null),S=f.useRef(null);f.useEffect(()=>{const j=S.current;if(!j)return;const L=D=>{D.button===2&&D.stopPropagation()};return j.addEventListener("pointerdown",L,!0),()=>{j.removeEventListener("pointerdown",L,!0)}},[]);const w=f.useCallback(j=>{s||(j.preventDefault(),j.stopPropagation(),m({x:j.clientX,y:j.clientY}),p(!0))},[s]),y=f.useCallback(()=>{p(!1)},[]),T=f.useCallback(()=>{n?o(t):a(t),y()},[n,t,o,a,y]),C=f.useCallback(()=>{i>0&&d(i,i-1,!0),y()},[i,d,y]),E=f.useCallback(()=>{i>=0&&i<u.length-1&&d(i,i+1,!0),y()},[i,u.length,d,y]),v=f.useCallback(()=>{i>0&&d(i,0,!0),y()},[i,d,y]),x=f.useCallback(()=>{i>=0&&i<u.length-1&&d(i,u.length-1,!0),y()},[i,u.length,d,y]),O=f.useCallback(()=>{c(),y()},[c,y]);f.useEffect(()=>{if(!h)return;const j=D=>{b.current&&!b.current.contains(D.target)&&y()},L=D=>{D.key==="Escape"&&y()};return document.addEventListener("mousedown",j),document.addEventListener("keydown",L),()=>{document.removeEventListener("mousedown",j),document.removeEventListener("keydown",L)}},[h,y]),f.useEffect(()=>{if(!h||!b.current)return;const L=b.current.getBoundingClientRect(),D=window.innerWidth,k=window.innerHeight;let N=g.x,M=g.y;g.x+L.width>D&&(N=D-L.width-8),g.y+L.height>k&&(M=k-L.height-8),(N!==g.x||M!==g.y)&&m({x:N,y:M})},[h,g]);const B=n&&i>0,X=n&&i>=0&&i<u.length-1;return l.jsxs(l.Fragment,{children:[l.jsx("div",{ref:S,onContextMenu:w,children:e}),h&&Lo.createPortal(l.jsx("div",{ref:b,className:"toolbar-context-menu",style:{position:"fixed",left:g.x,top:g.y,zIndex:Jt.DROPDOWN_PORTAL},children:l.jsxs(_n,{children:[n&&l.jsxs(l.Fragment,{children:[l.jsx(Be,{onSelect:C,disabled:!B,children:r("toolbar.moveUp")}),l.jsx(Be,{onSelect:E,disabled:!X,children:r("toolbar.moveDown")}),l.jsx(Be,{onSelect:v,disabled:!B,children:r("toolbar.moveToTop")}),l.jsx(Be,{onSelect:x,disabled:!X,children:r("toolbar.moveToBottom")}),l.jsx(ur,{})]}),l.jsx(Be,{onSelect:T,children:r(n?"toolbar.rightClickToHide":"toolbar.doubleClickToShow")}),l.jsx(ur,{}),l.jsx(Be,{onSelect:O,children:r("toolbar.resetToDefault")})]})}),document.body)]})},UP=({embedded:e=!1,iconMode:t=!1,onOpenBackupRestore:n,onOpenCloudSync:i})=>{const s=bt(),{t:r}=Ee(),{isButtonVisible:o,visibleButtons:a}=Fo(),c=z.getBoardContainer(s),[u,d]=f.useState(!1),h=s.history.undos.length<=0,p=s.history.redos.length<=0,g=o("undo"),m=o("redo"),b=a.findIndex(y=>y.id==="undo"),S=a.findIndex(y=>y.id==="redo"),w=l.jsxs(pt.Row,{gap:1,children:[l.jsxs(at,{sideOffset:12,open:u,onOpenChange:y=>{d(y)},placement:e?"right-start":"bottom-start",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{type:"icon",visible:!0,selected:u,icon:l.jsx($f,{}),tooltip:u?void 0:r("general.menu"),tooltipPlacement:e?"right":"bottom","aria-label":r("general.menu"),"data-track":"toolbar_click_menu",onPointerDown:()=>{d(!u)}})}),l.jsx(ct,{container:c,style:{zIndex:Jt.POPOVER_APP},children:l.jsxs(_n,{onSelect:()=>{d(!1)},onClose:()=>{d(!1)},children:[l.jsx(am,{}),l.jsx(om,{}),l.jsx(lm,{}),l.jsx(cm,{}),l.jsx(Sm,{}),l.jsx(ur,{}),l.jsx(bm,{}),l.jsx(um,{onOpenBackupRestore:()=>{d(!1),n==null||n()}}),l.jsx(hm,{}),l.jsx(dm,{onOpenCloudSync:()=>{d(!1),i==null||i()}}),l.jsx(fm,{}),l.jsx(ur,{}),l.jsx(pm,{}),l.jsx(gm,{}),l.jsx(mm,{})]})})]},0),g&&l.jsx(Al,{buttonId:"undo",isVisible:!0,visibleIndex:b,children:l.jsx(ne,{type:"icon",icon:l.jsx(Xf,{}),visible:!0,tooltip:r("general.undo"),tooltipPlacement:e?"right":"bottom","aria-label":r("general.undo"),"data-track":"toolbar_click_undo",onPointerUp:()=>{s.undo()},disabled:h},1)}),m&&l.jsx(Al,{buttonId:"redo",isVisible:!0,visibleIndex:S,children:l.jsx(ne,{type:"icon",icon:l.jsx(Kf,{}),visible:!0,tooltip:r("general.redo"),tooltipPlacement:e?"right":"bottom","aria-label":r("general.redo"),"data-track":"toolbar_click_redo",onPointerUp:()=>{s.redo()},disabled:p},2)})]});return e?l.jsxs("div",{className:q("app-toolbar",{"app-toolbar--embedded":e,"app-toolbar--icon-only":t}),children:[w,l.jsx(ne,{type:"icon",icon:l.jsx(zb,{}),visible:!0,tooltip:r("menu.github"),tooltipPlacement:"right","aria-label":r("menu.github"),"data-track":"toolbar_click_github",onPointerUp:()=>{window.open("https://github.com/ljquan/aitu","_blank")}})]}):l.jsx(qe,{padding:1,className:q("app-toolbar",Dt,{"app-toolbar--embedded":e,"app-toolbar--icon-only":t}),children:w})};function WP(e,t){return!e||e===Jn.solid?null:e===Jn.dashed?`${t*3},${t*2}`:e===Jn.dotted?`${t},${t*2}`:null}function hi(e){return e!==void 0&&!isNaN(e[0])&&!isNaN(e[1])&&isFinite(e[0])&&isFinite(e[1])}class $P extends Yf{constructor(t){super(t)}canDraw(t){return t.anchors&&t.anchors.length>0}draw(t){const n=Ql();n.classList.add("pen-path");const i=qf(t),s=t.cornerRadius||0,r=Zf(i,t.closed,s),o=t.strokeWidth||2,a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("d",r),a.setAttribute("fill",Vb(t.fill)),a.setAttribute("stroke",t.strokeColor||"#000000"),a.setAttribute("stroke-width",String(o)),a.setAttribute("stroke-linecap","round"),a.setAttribute("stroke-linejoin","round");const c=WP(t.strokeStyle,o);return c&&a.setAttribute("stroke-dasharray",c),n.appendChild(a),n}}function XP(e,t){const n=e.point,i=Wb;if(e.type==="corner"){const s=document.createElementNS("http://www.w3.org/2000/svg","rect");return s.setAttribute("x",String(n[0]-i/2)),s.setAttribute("y",String(n[1]-i/2)),s.setAttribute("width",String(i)),s.setAttribute("height",String(i)),s.setAttribute("fill",t?"#1890ff":"#ffffff"),s.setAttribute("stroke","#1890ff"),s.setAttribute("stroke-width","1.5"),s.classList.add("pen-anchor"),s}else{const s=document.createElementNS("http://www.w3.org/2000/svg","circle");return s.setAttribute("cx",String(n[0])),s.setAttribute("cy",String(n[1])),s.setAttribute("r",String(i/2)),s.setAttribute("fill",t?"#1890ff":"#ffffff"),s.setAttribute("stroke","#1890ff"),s.setAttribute("stroke-width","1.5"),s.classList.add("pen-anchor"),s}}function Ah(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(Ub/2)),t.setAttribute("fill","#ffffff"),t.setAttribute("stroke","#1890ff"),t.setAttribute("stroke-width","1"),t.classList.add("pen-handle"),t}function Mh(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 KP(e,t,n){const i="#ff4d4f";if(n.vertical&&n.verticalRefPoint){const r=n.verticalRefPoint,o=document.createElementNS("http://www.w3.org/2000/svg","line");o.setAttribute("x1",String(t[0])),o.setAttribute("y1",String(Math.min(t[1],r[1])-50)),o.setAttribute("x2",String(t[0])),o.setAttribute("y2",String(Math.max(t[1],r[1])+50)),o.setAttribute("stroke",i),o.setAttribute("stroke-width",String(1)),o.setAttribute("stroke-dasharray","4,4"),o.classList.add("pen-alignment-guide"),e.appendChild(o);const a=document.createElementNS("http://www.w3.org/2000/svg","circle");a.setAttribute("cx",String(r[0])),a.setAttribute("cy",String(r[1])),a.setAttribute("r","3"),a.setAttribute("fill",i),a.setAttribute("opacity","0.6"),a.classList.add("pen-alignment-marker"),e.appendChild(a)}if(n.horizontal&&n.horizontalRefPoint){const r=n.horizontalRefPoint,o=document.createElementNS("http://www.w3.org/2000/svg","line");if(o.setAttribute("x1",String(Math.min(t[0],r[0])-50)),o.setAttribute("y1",String(t[1])),o.setAttribute("x2",String(Math.max(t[0],r[0])+50)),o.setAttribute("y2",String(t[1])),o.setAttribute("stroke",i),o.setAttribute("stroke-width",String(1)),o.setAttribute("stroke-dasharray","4,4"),o.classList.add("pen-alignment-guide"),e.appendChild(o),!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(r[0])),a.setAttribute("cy",String(r[1])),a.setAttribute("r","3"),a.setAttribute("fill",i),a.setAttribute("opacity","0.6"),a.classList.add("pen-alignment-marker"),e.appendChild(a)}}}function YP(e,t,n="#1890ff",i=2,s){const r=Ql();if(r.classList.add("pen-preview"),e.length===0)return r;if(t&&hi(t)&&s&&(s.horizontal||s.vertical)&&KP(r,t,s),e.length>0){const o=Zf(e,!1),a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("d",o),a.setAttribute("fill","none"),a.setAttribute("stroke",n),a.setAttribute("stroke-width",String(i)),a.setAttribute("stroke-linecap","round"),a.setAttribute("stroke-linejoin","round"),r.appendChild(a)}if(t&&hi(t)&&e.length>0){const o=e[e.length-1];if(hi(o.point)){const a=document.createElementNS("http://www.w3.org/2000/svg","line"),c=o.handleOut&&hi(o.handleOut)?o.handleOut:o.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"),r.appendChild(a)}}for(let o=0;o<e.length;o++){const a=e[o];if(!hi(a.point))continue;if(a.handleIn&&hi(a.handleIn)){const u=Mh(a.point,a.handleIn);r.appendChild(u);const d=Ah(a.handleIn);r.appendChild(d)}if(a.handleOut&&hi(a.handleOut)){const u=Mh(a.point,a.handleOut);r.appendChild(u);const d=Ah(a.handleOut);r.appendChild(d)}const c=XP(a,o===e.length-1);r.appendChild(c)}return r}const qP=3,ZP=3,Ih=8,Ml=new WeakMap;function qn(e){let t=Ml.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}},Ml.set(e,t)),t}function Dh(e,t,n=!1){const i={horizontal:!1,vertical:!1,horizontalRefPoint:null,verticalRefPoint:null,referencePoint:null},s=[...e],r=n&&t.length>1?t.slice(0,-1):t;if(r.length===0)return{snappedPoint:e,alignment:i};let o=Ih,a=null,c=null,u=Ih,d=null,h=null;for(const p of r){const g=Math.abs(e[0]-p.point[0]),m=Math.abs(e[1]-p.point[1]);g<o&&(o=g,a=p.point[0],c=p.point),m<u&&(u=m,d=p.point[1],h=p.point)}return a!==null&&(s[0]=a,i.vertical=!0,i.verticalRefPoint=c),d!==null&&(s[1]=d,i.horizontal=!0,i.horizontalRefPoint=h),i.referencePoint=i.verticalRefPoint||i.horizontalRefPoint,{snappedPoint:s,alignment:i}}function ss(e){const t=qn(e);t.previewG&&t.previewG.remove(),ym(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 ym(e){z.getElementHost(e).querySelectorAll(".pen-preview").forEach(i=>i.remove())}function Ms(e){const t=qn(e),n=z.getElementHost(e);t.previewG&&t.previewG.remove(),t.previewG=YP(t.anchors,t.currentPoint,"#1890ff",2,t.alignment),n.appendChild(t.previewG)}function bo(e,t=!1){const n=qn(e),i=[...n.anchors];if(n.previewG&&(n.previewG.remove(),n.previewG=null),ym(e),i.length>=2){const s=$b(e,i,t);n.isCreating=!1,n.anchors=[],n.isDraggingHandle=!1,n.dragStartPoint=null,n.currentPoint=null,ue.insertNode(e,s,[e.children.length]),t?(ii(e),Pi(e,s)):ii(e)}else ss(e)}function Fs(e){return z.getPointer(e)===Bn.pen}function QP(e){const t=qn(e);t.isCreating&&(Fs(e)||(t.anchors.length>=2?bo(e,!1):ss(e)))}const JP=e=>{const{pointerDown:t,pointerMove:n,pointerUp:i,globalPointerUp:s,keyDown:r,globalKeyDown:o}=e,a=u=>u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLElement&&u.isContentEditable,c=u=>{if(u.defaultPrevented||!Fs(e)||a(u.target))return!1;const d=qn(e);return d.isCreating?u.key==="Enter"?(bo(e,!1),u.preventDefault(),!0):u.key==="Escape"?(ss(e),u.preventDefault(),!0):tt.isHotkey(["mod+z"],{byKey:!0})(u)||u.key==="Backspace"||u.key==="Delete"?(d.anchors.length>0&&(d.anchors.pop(),Ms(e)),d.anchors.length===0&&ss(e),u.preventDefault(),!0):!1:!1};return e.pointerDown=u=>{if(QP(e),!Fs(e)){t(u);return}const d=qn(e);let h=Gt(e,zt(e,u.x,u.y));if(d.isCreating&&d.anchors.length>=ZP){const b={anchors:d.anchors};if(Xb(b,h)){bo(e,!0);return}}if(d.anchors.length>0){const{snappedPoint:b}=Dh(h,d.anchors,!1);h=b}d.isCreating=!0,d.isDraggingHandle=!0,d.dragStartPoint=h;const g=Ja(e).defaultAnchorType,m={point:h,type:g};d.anchors.push(m),d.alignment={horizontal:!1,vertical:!1,horizontalRefPoint:null,verticalRefPoint:null,referencePoint:null},Ms(e)},e.pointerMove=u=>{if(!Fs(e)){n(u);return}const d=qn(e);let h=Gt(e,zt(e,u.x,u.y));const p=d.isDraggingHandle,{snappedPoint:g,alignment:m}=Dh(h,d.anchors,p);if(d.currentPoint=g,d.alignment=m,d.isDraggingHandle&&d.dragStartPoint&&d.anchors.length>0&&Kb(d.dragStartPoint,h)>qP){const S=d.anchors.length-1,w=d.anchors[S];if(w.type!=="corner"){if(w.type==="smooth"||w.type==="symmetric"){const y=Yb(w.point,h);d.anchors[S]={...w,handleIn:y.handleIn,handleOut:y.handleOut}}}}d.isCreating&&Jl(e,"pen-preview",()=>{Ms(e)}),n(u)},e.pointerUp=u=>{if(!Fs(e)){i(u);return}const d=qn(e);d.isDraggingHandle=!1,d.dragStartPoint=null,Ms(e),i(u)},e.globalPointerUp=u=>{s(u)},e.globalKeyDown=u=>{c(u)||o(u)},e.keyDown=u=>{c(u)||r(u)},e};function Cn(e){const t=Ml.get(e);t!=null&&t.isCreating&&(t.anchors.length>=2?bo(e,!1):ss(e))}const Rc=[{icon:l.jsx(Ss,{}),pointer:ot.feltTipPen,titleKey:"toolbar.pen"},{icon:l.jsx(qb,{}),pointer:Bn.pen,titleKey:"toolbar.vectorPen"},{icon:l.jsx(Zb,{}),pointer:ot.eraser,titleKey:"toolbar.eraser"},{icon:l.jsx(Qb,{}),pointer:ot.laserPointer,titleKey:"toolbar.laserPointer"}],ek=Qf(Rc,5),jc=({onPointerUp:e})=>{const{t}=Ee(),n=bt();return l.jsx(qe,{padding:1,children:l.jsx(pt.Row,{gap:1,align:"center",children:l.jsx(pt.Row,{gap:1,children:ek.map((i,s)=>i.map((r,o)=>l.jsx(ne,{className:q({fillable:!1}),selected:n.pointer===r.pointer,type:"icon",size:"small",visible:!0,icon:r.icon,tooltip:t(r.titleKey),"aria-label":t(r.titleKey),onPointerDown:()=>{r.pointer!==Bn.pen&&Cn(n),ht(n,Et.dnd),fe.updatePointerType(n,r.pointer)},onPointerUp:()=>{ht(n,Et.drawing),e(r.pointer)}},`${s}-${o}`)))})})})},tk=[{icon:l.jsx(Jf,{}),title:"Rectangle — R",pointer:Pe.rectangle},{icon:l.jsx(ep,{}),title:"Ellipse — O",pointer:Pe.ellipse},{icon:l.jsx(tp,{}),title:"Triangle",pointer:Pe.triangle},{icon:l.jsx(np,{}),title:"Terminal",pointer:ec.terminal},{icon:l.jsx(ip,{}),title:"Diamond",pointer:Pe.diamond},{icon:l.jsx(sp,{}),title:"Parallelogram",pointer:Pe.parallelogram},{icon:l.jsx(rp,{}),title:"RoundRectangle",pointer:Pe.roundRectangle}],nk=Qf(tk,5),Lc=({onPointerUp:e})=>{const t=bt();return l.jsx(qe,{padding:1,children:l.jsx(pt.Col,{gap:1,children:nk.map((n,i)=>l.jsx(pt.Row,{gap:1,children:n.map((s,r)=>l.jsx(ne,{className:q({fillable:!1}),type:"icon",size:"small",visible:!0,icon:s.icon,tooltip:s.title,"aria-label":s.title,onPointerDown:()=>{Cn(t),ht(t,Et.dnd),fe.updatePointerType(t,s.pointer)},onPointerUp:()=>{ht(t,Et.drawing),e(s.pointer)}},r))},i))})})},ik=[{icon:l.jsx(Jb,{}),title:"Straight Arrow Line",pointer:En.straight},{icon:l.jsx(ey,{}),title:"Elbow Arrow Line",pointer:En.elbow},{icon:l.jsx(ty,{}),title:"Curve Arrow Line",pointer:En.curve}],Oc=({onPointerUp:e})=>{const t=bt();return l.jsx(qe,{padding:1,children:l.jsx(pt.Row,{gap:1,children:ik.map((n,i)=>l.jsx(ne,{className:q({fillable:!1}),type:"icon",size:"small",visible:!0,icon:n.icon,tooltip:n.title,"aria-label":n.title,onPointerDown:()=>{Cn(t),ht(t,Et.drawing),fe.updatePointerType(t,n.pointer)},onPointerUp:()=>{e(n.pointer)}},i))})})},wm=[{value:pi.default,labelKey:"theme.default"},{value:pi.colorful,labelKey:"theme.colorful"},{value:pi.soft,labelKey:"theme.soft"},{value:pi.retro,labelKey:"theme.retro"},{value:pi.dark,labelKey:"theme.dark"},{value:pi.starry,labelKey:"theme.starry"}],Tm=l.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:l.jsx("polyline",{points:"20 6 9 17 4 12"})}),Jr=e=>e===vt.hand||e===vt.selection||e===tr,vm=l.jsx("span",{style:{width:"1rem",display:"inline-block"}}),Nh={hand:{icon:l.jsx(fp,{}),titleKey:"toolbar.hand",pointer:vt.hand},selection:{icon:l.jsx(hp,{}),titleKey:"toolbar.selection",pointer:vt.selection},lasso:{icon:l.jsx(dp,{}),titleKey:"toolbar.lasso",pointer:tr},mind:{icon:l.jsx(ro,{}),titleKey:"toolbar.mind",pointer:ki.mind},text:{icon:l.jsx(rc,{}),titleKey:"toolbar.text",pointer:Pe.text},freehand:{icon:l.jsx(Ss,{}),titleKey:"toolbar.pen",pointer:ot.feltTipPen,hasPopup:!0,popupKey:"freehand"},arrow:{icon:l.jsx(sc,{}),titleKey:"toolbar.arrow",pointer:En.straight,hasPopup:!0,popupKey:"arrow"},shape:{icon:l.jsx(ic,{}),titleKey:"toolbar.shape",pointer:Pe.rectangle,hasPopup:!0,popupKey:"shape"},image:{icon:l.jsx(jo,{size:24}),titleKey:"toolbar.image"},"media-library":{icon:l.jsx(Ro,{size:24}),titleKey:"toolbar.mediaLibrary"},"ai-image":{icon:l.jsx(Oo,{}),titleKey:"toolbar.aiImage"},"ai-video":{icon:l.jsx(Bo,{}),titleKey:"toolbar.aiVideo"},theme:{icon:l.jsx(up,{}),titleKey:"toolbar.theme",hasPopup:!0,popupKey:"theme"},"mermaid-to-drawnix":{icon:l.jsx(cp,{}),titleKey:"extraTools.mermaidToDrawnix"},"markdown-to-drawnix":{icon:l.jsx(lp,{}),titleKey:"extraTools.markdownToDrawnix"},undo:{icon:l.jsx(Xf,{}),titleKey:"general.undo"},redo:{icon:l.jsx(Kf,{}),titleKey:"general.redo"}},sk=({embedded:e=!1})=>{const{t}=Ee(),n=bt(),i=z.getBoardContainer(n),{hiddenButtons:s,showButton:r}=Fo(),[o,a]=f.useState(!1),[c,u]=f.useState(!1),d=f.useRef(null),h=f.useRef(null),p=f.useCallback(()=>{d.current&&(clearTimeout(d.current),d.current=null),h.current&&(clearTimeout(h.current),h.current=null)},[]),g=f.useCallback(()=>"ontouchstart"in window||navigator.maxTouchPoints>0,[]),m=f.useCallback(()=>{g()||(p(),u(!0),d.current=setTimeout(()=>{a(!0)},200))},[p,g]),b=f.useCallback(()=>{g()||(d.current&&(clearTimeout(d.current),d.current=null),h.current=setTimeout(()=>{u(!1),a(!1)},150))},[g]),S=f.useCallback(()=>{g()&&(a(T=>!T),u(!1))},[g]),w=f.useCallback(()=>{p(),u(!0)},[p]),y=f.useCallback(()=>{h.current=setTimeout(()=>{u(!1),a(!1)},150)},[]);return l.jsxs(at,{open:o,onOpenChange:T=>{!T&&(g()||!c)&&a(!1)},placement:e?"right-start":"bottom",sideOffset:12,children:[l.jsx(lt,{asChild:!0,children:l.jsx("div",{onMouseEnter:m,onMouseLeave:b,onClick:S,children:l.jsx(ne,{type:"icon",icon:l.jsx(ny,{}),tooltip:o?void 0:t("toolbar.more"),tooltipPlacement:e?"right":"bottom","aria-label":t("toolbar.more"),selected:o,visible:!0,"data-testid":"toolbar-more","data-track":"toolbar_click_more"})})}),l.jsx(ct,{container:i,style:{zIndex:Jt.POPOVER},onMouseEnter:w,onMouseLeave:y,children:l.jsx(rk,{hiddenButtons:s,showButton:r})})]})},rk=({hiddenButtons:e,showButton:t})=>{const{t:n}=Ee(),i=bt(),s=z.getBoardContainer(i),{openDialog:r}=Ut(),o=tc(),[a,c]=f.useState(null),[u,d]=f.useState(null),h=f.useRef({}),[p,g]=f.useState(null),m=f.useRef(null),[b,S]=f.useState(ot.feltTipPen),w=f.useCallback(()=>{c(null),d(null),Object.values(h.current).forEach(R=>{R&&clearTimeout(R)})},[]),y=f.useCallback(R=>{if(Object.values(h.current).forEach(W=>{W&&clearTimeout(W)}),u===R){d(null);return}a===R&&!u?c(null):(d(null),c(R))},[a,u]),T=f.useCallback(R=>{a&&!u||(h.current[R]&&clearTimeout(h.current[R]),Object.entries(h.current).forEach(([W,ce])=>{W!==R&&ce&&(clearTimeout(ce),h.current[W]=null)}),u&&u!==R?(c(R),d(R)):a||(h.current[R]=setTimeout(()=>{c(R),d(R)},300)))},[u,a]),C=f.useCallback(R=>{h.current[R]&&(clearTimeout(h.current[R]),h.current[R]=null),u===R&&(h.current[R]=setTimeout(()=>{c(null),d(null)},400))},[u]),E=f.useCallback(R=>{h.current[R]&&(clearTimeout(h.current[R]),h.current[R]=null)},[]),v=f.useCallback(R=>{u===R&&(c(null),d(null))},[u]),x=f.useCallback(R=>{Cn(i),R===Pe.text?ht(i,null):ht(i,Et.dnd),fe.updatePointerType(i,R),o(R)},[i,o]),O=f.useCallback(R=>{R!==Pe.text&&ht(i,Et.drawing)},[i]),B=f.useCallback(R=>{const W=Nh[R];if(W){if(W.hasPopup&&W.popupKey){y(W.popupKey);return}switch(w(),Cn(i),W.pointer&&(Jr(W.pointer)?(fe.updatePointerType(i,W.pointer),o(W.pointer)):(x(W.pointer),O(W.pointer))),R){case"image":Go(i);break;case"ai-image":r(ln.aiImageGeneration);break;case"ai-video":r(ln.aiVideoGeneration);break;case"mermaid-to-drawnix":r(ln.mermaidToDrawnix);break;case"markdown-to-drawnix":r(ln.markdownToDrawnix);break;case"undo":i.undo();break;case"redo":i.redo();break}}},[i,r,x,O,w,o,y]),X=f.useCallback((R,W)=>{R.preventDefault(),R.stopPropagation(),g({buttonId:W,x:R.clientX,y:R.clientY})},[]),j=f.useCallback(()=>{g(null)},[]),L=f.useCallback(()=>{p&&(t(p.buttonId),j())},[p,t,j]);Gn.useEffect(()=>{if(!p)return;const R=ce=>{m.current&&!m.current.contains(ce.target)&&j()},W=ce=>{ce.key==="Escape"&&j()};return document.addEventListener("mousedown",R),document.addEventListener("keydown",W),()=>{document.removeEventListener("mousedown",R),document.removeEventListener("keydown",W)}},[p,j]);const D=f.useCallback(R=>{switch(R){case"freehand":return l.jsx(jc,{onPointerUp:W=>{w(),o(W),S(W)}});case"shape":return l.jsx(Lc,{onPointerUp:W=>{w(),o(W)}});case"arrow":return l.jsx(Oc,{onPointerUp:W=>{w(),o(W)}});case"theme":return l.jsx(_n,{children:wm.map(W=>{const ce=i.theme.themeColorMode===W.value;return l.jsx(Be,{icon:ce?Tm:vm,"data-track":`toolbar_click_theme_${W.value}`,onSelect:()=>{fe.updateThemeColor(i,W.value),w()},"aria-label":n(W.labelKey),selected:ce,children:n(W.labelKey)},W.value)})});default:return null}},[i,w,o,n]),k=f.useMemo(()=>{const R=Rc.find(W=>W.pointer===b);return(R==null?void 0:R.icon)||l.jsx(Ss,{})},[b]),[N,M]=f.useState(!1),Z=f.useCallback(()=>{var R;return l.jsx("div",{className:"more-tools-panel__zoom-row",onContextMenu:W=>X(W,"zoom"),children:l.jsxs(pt.Row,{gap:1,children:[l.jsx(ne,{type:"button",icon:l.jsx(op,{}),visible:!0,tooltip:n("zoom.out"),tooltipPlacement:"top","aria-label":n("zoom.out"),"data-track":"toolbar_click_zoom_out",onPointerUp:()=>{fe.updateZoom(i,i.viewport.zoom-.1)},className:"zoom-out-button"}),l.jsxs(at,{sideOffset:12,open:N,onOpenChange:W=>{M(W)},placement:"right-start",children:[l.jsx(Ct,{content:n("zoom.fit"),showArrow:!1,children:l.jsx(lt,{asChild:!0,children:l.jsxs("div",{"aria-label":n("zoom.fit"),"data-track":"toolbar_click_zoom_menu",className:`zoom-menu-trigger ${N?"active":""}`,onPointerUp:()=>{M(!N)},children:[Number(((((R=i==null?void 0:i.viewport)==null?void 0:R.zoom)||1)*100).toFixed(0)),"%"]})})}),l.jsx(ct,{container:s,style:{zIndex:Jt.POPOVER+1},children:l.jsxs(_n,{onSelect:()=>{M(!1)},children:[l.jsx(Be,{"data-track":"toolbar_click_zoom_fit",onSelect:()=>{fe.fitViewport(i)},"aria-label":n("zoom.fit"),shortcut:"Cmd+Shift+=",children:n("zoom.fit")}),l.jsx(Be,{"data-track":"toolbar_click_zoom_fit_frame",onSelect:()=>{nc(i)},"aria-label":n("zoom.fitFrame"),children:n("zoom.fitFrame")}),l.jsx(Be,{"data-track":"toolbar_click_zoom_100",onSelect:()=>{fe.updateZoom(i,1)},"aria-label":n("zoom.100"),shortcut:"Cmd+0",children:n("zoom.100")})]})})]}),l.jsx(ne,{type:"button",icon:l.jsx(ap,{}),visible:!0,tooltip:n("zoom.in"),tooltipPlacement:"top","aria-label":n("zoom.in"),"data-track":"toolbar_click_zoom_in",onPointerUp:()=>{fe.updateZoom(i,i.viewport.zoom+.1)},className:"zoom-in-button"})]})},"zoom")},[i,s,X,n,N]),he=f.useCallback(R=>{var Te,ze,Y,Ie;if(R==="zoom")return Z();const W=Nh[R];if(!W)return null;const ce=n(W.titleKey),K=R==="freehand"?k:W.icon,ae=R==="undo"&&(((ze=(Te=i.history)==null?void 0:Te.undos)==null?void 0:ze.length)??0)<=0,le=R==="redo"&&(((Ie=(Y=i.history)==null?void 0:Y.redos)==null?void 0:Ie.length)??0)<=0,me=ae||le;if(W.hasPopup&&W.popupKey){const $e=W.popupKey;return l.jsx("div",{className:"more-tools-panel__item",onContextMenu:it=>X(it,R),children:l.jsxs(at,{open:a===$e,sideOffset:2,onOpenChange:it=>{it||w()},placement:"right-start",children:[l.jsx(lt,{asChild:!0,children:l.jsx("div",{onMouseEnter:()=>T($e),onMouseLeave:()=>C($e),children:l.jsx(ne,{type:"icon",icon:K,tooltip:ce,tooltipPlacement:"left","aria-label":ce,visible:!0,selected:a===$e,"data-track":`toolbar_click_${R}`,onPointerUp:()=>B(R)})})}),l.jsx(ct,{container:s,style:{zIndex:Jt.POPOVER+1},onMouseEnter:()=>E($e),onMouseLeave:()=>v($e),children:D($e)})]})},R)}return l.jsx("div",{className:"more-tools-panel__item",onContextMenu:$e=>X($e,R),children:l.jsx(ne,{type:"icon",icon:K,tooltip:ce,tooltipPlacement:"right","aria-label":ce,visible:!0,selected:!1,disabled:me,"data-track":`toolbar_click_${R}`,onPointerUp:()=>B(R)})},R)},[n,i,s,a,k,B,X,T,C,E,v,D,w,Z]);return e.length===0?l.jsxs("div",{className:"more-tools-panel",children:[l.jsx("div",{className:"more-tools-panel__header",children:l.jsx("span",{className:"more-tools-panel__title",children:n("toolbar.moreTools")})}),l.jsx("div",{className:"more-tools-panel__empty",children:l.jsx("span",{className:"more-tools-panel__empty-text",children:n("toolbar.allToolsVisible")})})]}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"more-tools-panel",children:[l.jsx("div",{className:"more-tools-panel__header",children:l.jsx("span",{className:"more-tools-panel__title",children:n("toolbar.moreTools")})}),l.jsx("div",{className:"more-tools-panel__content",children:e.map(R=>he(R.id))}),l.jsx("div",{className:"more-tools-panel__footer",children:l.jsx("span",{className:"more-tools-panel__hint",children:n("toolbar.rightClickToAdd")})})]}),p&&Lo.createPortal(l.jsx("div",{ref:m,className:"toolbar-context-menu",style:{position:"fixed",left:p.x,top:p.y,zIndex:Jt.DROPDOWN_PORTAL},children:l.jsx(_n,{children:l.jsx(Be,{onSelect:L,children:n("toolbar.addToToolbar")})})}),document.body)]})},ok=f.lazy(()=>Ne(()=>import("./tool-windows-hjm6YiPY.js").then(e=>e.p0),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.MediaLibraryModal}))),ak=f.lazy(()=>Ne(()=>import("./tool-windows-hjm6YiPY.js").then(e=>e.p2),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.MinimizedToolsBar})));var xm=(e=>(e.shape="shape",e.arrow="arrow",e.freehand="freehand",e.theme="theme",e))(xm||{});const Rh=[{icon:l.jsx(fp,{}),pointer:vt.hand,titleKey:"toolbar.hand",visibilityKey:"hand"},{icon:l.jsx(hp,{}),pointer:vt.selection,titleKey:"toolbar.selection",visibilityKey:"selection"},{icon:l.jsx(dp,{}),pointer:tr,titleKey:"toolbar.lasso",visibilityKey:"lasso"},{icon:l.jsx(ro,{}),pointer:ki.mind,titleKey:"toolbar.mind",visibilityKey:"mind"},{icon:l.jsx(rc,{}),pointer:Pe.text,titleKey:"toolbar.text",visibilityKey:"text"},{icon:l.jsx(jo,{size:24}),titleKey:"toolbar.image",key:"image",visibilityKey:"image"},{icon:l.jsx(Ro,{size:24}),titleKey:"toolbar.mediaLibrary",key:"media-library",visibilityKey:"media-library"},{icon:l.jsx(Oo,{}),titleKey:"toolbar.aiImage",key:"ai-image",visibilityKey:"ai-image"},{icon:l.jsx(Bo,{}),titleKey:"toolbar.aiVideo",key:"ai-video",visibilityKey:"ai-video"},{icon:l.jsx(ro,{}),pointer:ki.mind,titleKey:"toolbar.mind",visibilityKey:"mind"},{icon:l.jsx(Ss,{}),pointer:ot.feltTipPen,titleKey:"toolbar.pen",key:"freehand",visibilityKey:"freehand"},{icon:l.jsx(sc,{}),titleKey:"toolbar.arrow",key:"arrow",pointer:En.straight,visibilityKey:"arrow"},{icon:l.jsx(ic,{}),titleKey:"toolbar.shape",key:"shape",pointer:Pe.rectangle,visibilityKey:"shape"},{icon:l.jsx(up,{}),titleKey:"toolbar.theme",key:"theme",visibilityKey:"theme"},{icon:l.jsx(cp,{}),titleKey:"extraTools.mermaidToDrawnix",key:"mermaid-to-drawnix",visibilityKey:"mermaid-to-drawnix"},{icon:l.jsx(lp,{}),titleKey:"extraTools.markdownToDrawnix",key:"markdown-to-drawnix",visibilityKey:"markdown-to-drawnix"}],lk=e=>Object.keys(En).includes(e.pointer),ck=e=>Object.keys(Pe).includes(e.pointer)||Object.keys(ec).includes(e.pointer),uk=({embedded:e=!1,iconMode:t=!1,onOpenMediaLibrary:n,minimizedToolsBarEnabled:i=!1,onEnableToolWindows:s})=>{const r=bt(),{appState:o,openDialog:a}=Ut(),{t:c}=Ee(),u=tc(),d=z.getBoardContainer(r),{visibleButtons:h,loading:p,reorderButton:g}=Fo(),{getDragProps:m}=iy({items:h,getId:P=>P.id,onReorder:(P,A)=>{g(P,A,!0)},enabled:e}),[b,S]=f.useState({freehand:!1,arrow:!1,shape:!1,theme:!1}),[w,y]=f.useState(null),T=f.useRef({freehand:null,arrow:null,shape:null,theme:null}),[C,E]=f.useState(Rh.find(P=>P.key==="freehand")),[v,x]=f.useState(!1),O=f.useCallback(async P=>{try{P.type===Nn.IMAGE?await ql(r,P.url):P.type===Nn.VIDEO?await pp(r,P.url):P.type===Nn.AUDIO&&await Gl(r,P.url,{title:P.name,duration:P.duration,previewImageUrl:P.thumbnail,prompt:P.prompt,mv:P.modelName,clipId:P.clipId,providerTaskId:P.providerTaskId}),oe.success("素材已插入到画板")}catch(A){console.error("Failed to insert asset:",A),oe.error("插入素材失败")}},[r]),B=f.useCallback(()=>{if(n){n({mode:ni.SELECT,onSelect:O,selectButtonText:"插入"});return}x(!0)},[O,n]),X=f.useCallback(()=>{x(!1)},[]),j=()=>{S({freehand:!1,arrow:!1,shape:!1,theme:!1}),y(null),Object.values(T.current).forEach(P=>{P&&clearTimeout(P)})},L=P=>{y(null),Object.values(T.current).forEach(A=>{A&&clearTimeout(A)}),S({freehand:!1,arrow:!1,shape:!1,theme:!1,[P]:!0})},D=P=>{T.current[P]&&clearTimeout(T.current[P]),Object.entries(T.current).forEach(([A,$])=>{A!==P&&$&&(clearTimeout($),T.current[A]=null)}),w&&w!==P?(S(A=>({...A,[w]:!1,[P]:!0})),y(P)):b[P]||(T.current[P]=setTimeout(()=>{S(A=>({...A,[P]:!0})),y(P)},300))},k=P=>{T.current[P]&&(clearTimeout(T.current[P]),T.current[P]=null),w===P&&(T.current[P]=setTimeout(()=>{S(A=>({...A,[P]:!1})),y(null)},200))},N=P=>{T.current[P]&&(clearTimeout(T.current[P]),T.current[P]=null)},M=P=>{w===P&&(S(A=>({...A,[P]:!1})),y(null))},Z=P=>{Cn(r),P===Pe.text?(ht(r,null),fe.updatePointerType(r,P),u(P)):(ht(r,Et.dnd),fe.updatePointerType(r,P),u(P))},he=P=>{P!==Pe.text&&ht(r,Et.drawing)},R=()=>Object.values(b).some(P=>P),W=P=>z.isPointer(r,P.pointer)&&!R(),ce=P=>z.isInPointer(P,[ot.feltTipPen,ot.eraser,ot.laserPointer,Bn.pen]),K=P=>{j(),Cn(r),P.pointer&&!Jr(P.pointer)?he(P.pointer):P.pointer&&Jr(P.pointer)&&(fe.updatePointerType(r,P.pointer),u(P.pointer)),P.key==="image"?Go(r):P.key==="media-library"?B():P.key==="ai-image"?a(ln.aiImageGeneration):P.key==="ai-video"?a(ln.aiVideoGeneration):P.key==="mermaid-to-drawnix"?a(ln.mermaidToDrawnix):P.key==="markdown-to-drawnix"&&a(ln.markdownToDrawnix)},ae=(P,A,$)=>{const Q=()=>{switch($){case"freehand":return l.jsx(jc,{onPointerUp:U=>{j(),u(U),E(Rc.find(te=>te.pointer===U))}});case"shape":return l.jsx(Lc,{onPointerUp:U=>{j(),u(U)}});case"arrow":return l.jsx(Oc,{onPointerUp:U=>{j(),u(U)}});case"theme":return l.jsx(_n,{children:wm.map(U=>{const te=r.theme.themeColorMode===U.value;return l.jsx(Be,{icon:te?Tm:vm,"data-track":`toolbar_click_theme_${U.value}`,onSelect:()=>{fe.updateThemeColor(r,U.value),j()},"aria-label":c(U.labelKey),selected:te,children:c(U.labelKey)},U.value)})})}},I=()=>{const U=b[$],te=Object.entries(b).some(([ee,G])=>ee!==$&&G);switch($){case"freehand":return U||ce(r)&&!te;case"shape":return U||ck(r)&&!z.isPointer(r,Pe.text);case"arrow":return U||lk(r);default:return U}},H=$==="freehand"?C.icon:P.icon,F=$==="freehand"?C.titleKey?c(C.titleKey):"Freehand":P.titleKey?c(P.titleKey):"";return l.jsxs(at,{open:b[$],sideOffset:12,onOpenChange:U=>{U||j()},placement:e?"right-start":"bottom",children:[l.jsx(lt,{asChild:!0,children:l.jsx("div",{onMouseEnter:()=>D($),onMouseLeave:()=>k($),children:l.jsx(ne,{type:"icon",visible:!0,selected:I(),icon:H,tooltip:F,"aria-label":F,"data-track":`toolbar_click_${$}`,onPointerDown:()=>{L($),$==="freehand"&&C.pointer&&Z(C.pointer)},onPointerUp:()=>{$==="freehand"&&he()}})})}),l.jsx(ct,{container:d,style:{zIndex:Jt.POPOVER},onMouseEnter:()=>N($),onMouseLeave:()=>M($),children:Q()})]},A)},le=(P,A)=>l.jsx(ne,{type:"radio",icon:P.icon,checked:W(P),tooltip:P.titleKey?c(P.titleKey):"",tooltipPlacement:e?"right":"bottom","aria-label":P.titleKey?c(P.titleKey):"","data-track":`toolbar_click_${P.pointer||P.key}`,onPointerDown:()=>{P.pointer&&!Jr(P.pointer)&&Z(P.pointer)},onPointerUp:()=>{K(P)}},A),me=f.useMemo(()=>{const P=new Map;return Rh.forEach(A=>{A.visibilityKey&&P.set(A.visibilityKey,A)}),P},[]),[Te,ze]=f.useState(!1),Y=f.useCallback(P=>{var $;const A=e?pt.Col:pt.Row;return l.jsx("div",{className:q("creation-toolbar__zoom-inline",{"creation-toolbar__zoom-inline--vertical":e}),children:l.jsxs(A,{gap:0,children:[l.jsx(ne,{type:"button",icon:l.jsx(op,{}),visible:!0,tooltip:c("zoom.out"),tooltipPlacement:e?"right":"bottom","aria-label":c("zoom.out"),"data-track":"toolbar_click_zoom_out",onPointerUp:()=>{fe.updateZoom(r,r.viewport.zoom-.1)},className:"zoom-out-button"}),l.jsxs(at,{sideOffset:12,open:Te,onOpenChange:Q=>{ze(Q)},placement:e?"right-start":"bottom",children:[l.jsx(Ct,{content:c("zoom.fit"),showArrow:!1,children:l.jsx(lt,{asChild:!0,children:l.jsxs("div",{"aria-label":c("zoom.fit"),"data-track":"toolbar_click_zoom_menu",className:q("zoom-menu-trigger",{active:Te}),onPointerUp:()=>{ze(!Te)},children:[Number((((($=r==null?void 0:r.viewport)==null?void 0:$.zoom)||1)*100).toFixed(0)),"%"]})})}),l.jsx(ct,{container:d,style:{zIndex:Jt.POPOVER},children:l.jsxs(_n,{onSelect:()=>{ze(!1)},children:[l.jsx(Be,{"data-track":"toolbar_click_zoom_fit",onSelect:()=>{fe.fitViewport(r)},"aria-label":c("zoom.fit"),shortcut:"Cmd+Shift+=",children:c("zoom.fit")}),l.jsx(Be,{"data-track":"toolbar_click_zoom_fit_frame",onSelect:()=>{nc(r)},"aria-label":c("zoom.fitFrame"),children:c("zoom.fitFrame")}),l.jsx(Be,{"data-track":"toolbar_click_zoom_100",onSelect:()=>{fe.updateZoom(r,1)},"aria-label":c("zoom.100"),shortcut:"Cmd+0",children:c("zoom.100")})]})})]}),l.jsx(ne,{type:"button",icon:l.jsx(ap,{}),visible:!0,tooltip:c("zoom.in"),tooltipPlacement:e?"right":"bottom","aria-label":c("zoom.in"),"data-track":"toolbar_click_zoom_in",onPointerUp:()=>{fe.updateZoom(r,r.viewport.zoom+.1)},className:"zoom-in-button"})]})},`zoom-${P}`)},[r,d,e,c,Te]),Ie=f.useCallback((P,A)=>{if(P==="zoom")return Y(A);const $=me.get(P);return!$||o.isMobile&&$.pointer===vt.hand?null:$.key&&Object.values(xm).includes($.key)?ae($,A,$.key):le($,A)},[me,o.isMobile,ae,le,Y]),$e=f.useCallback((P,A,$=!0,Q=-1)=>{const I=Ie(P,A);if(!I)return null;const H=m(P,A);return l.jsx(Al,{buttonId:P,isVisible:$,visibleIndex:Q,children:l.jsx("div",{className:q("toolbar-button-wrapper",{"toolbar-button-wrapper--dragging":H["data-dragging"],"toolbar-button-wrapper--drag-over":H["data-drag-over"],"toolbar-button-wrapper--drag-before":H["data-drag-position"]==="before","toolbar-button-wrapper--drag-after":H["data-drag-position"]==="after"}),"data-button-id":P,...H,children:I})},`ctx-${P}-${A}`)},[Ie,m]),it=l.jsxs(pt.Row,{gap:1,children:[!p&&h.map((P,A)=>e?$e(P.id,A,!0,A):Ie(P.id,A)),l.jsx(sk,{embedded:e}),e&&i&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(ak,{ensureToolWindowsEnabled:s})})]}),Ye=v?l.jsx(f.Suspense,{fallback:null,children:l.jsx(ok,{isOpen:v,onClose:X,mode:ni.SELECT,onSelect:O,selectButtonText:"插入"})}):null;return e?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:q("draw-toolbar",{"draw-toolbar--embedded":e,"draw-toolbar--icon-only":t}),children:it}),Ye]}):l.jsxs(l.Fragment,{children:[l.jsx(qe,{padding:1,className:q("draw-toolbar",Dt,{"draw-toolbar--embedded":e,"draw-toolbar--icon-only":t}),children:it}),Ye]})},jh="https://tuziai.oss-cn-shenzhen.aliyuncs.com/aitu/AiTu.png",dk="https://tuziai.oss-cn-shenzhen.aliyuncs.com/linkme.png",hk=()=>{const e=bt(),t=z.getBoardContainer(e),[n,i]=f.useState(!1);return f.useEffect(()=>{const s=new Image;s.src=jh;const r=new Image;r.src=dk},[]),l.jsxs(at,{placement:"right-end",sideOffset:12,open:n,onOpenChange:i,children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{type:"icon",icon:l.jsx(sy,{}),"aria-label":"用户反馈群",title:"用户反馈群",tooltipPlacement:"right",selected:n,visible:!0,"data-track":"toolbar_click_feedback",onPointerDown:s=>{s.event.stopPropagation()},onClick:()=>i(!n)})}),l.jsx(ct,{container:t,style:{zIndex:Jt.POPOVER_FEEDBACK},children:l.jsx("div",{className:"feedback-qrcode-content",children:l.jsx("div",{className:"feedback-qrcode-grid",children:l.jsxs("div",{className:"feedback-qrcode-item",children:[l.jsx("img",{src:jh,alt:"用户反馈群二维码",className:"feedback-qrcode-image"}),l.jsx("div",{className:"feedback-qrcode-text",children:"用户反馈群"})]})})})})]})},fk=({projectDrawerOpen:e,onProjectDrawerToggle:t,toolboxDrawerOpen:n=!1,onToolboxDrawerToggle:i,taskPanelExpanded:s,onTaskPanelToggle:r})=>{const{activeTasks:o,completedTasks:a,failedTasks:c}=ry(),d=o.length+a.length+c.length>0?`任务队列 (生成中: ${o.length}, 已完成: ${a.length}, 失败: ${c.length})`:"任务队列 (暂无任务)";return l.jsxs("div",{className:"bottom-actions-section",children:[l.jsx(hk,{}),l.jsx(ne,{type:"icon",icon:l.jsx(oy,{}),"aria-label":e?"关闭项目":"打开项目",tooltip:e?"关闭项目":"打开项目",tooltipPlacement:"right",selected:e,visible:!0,"data-track":"toolbar_click_project_drawer","data-testid":"toolbar-project",onPointerDown:h=>{h.event.stopPropagation()},onClick:t}),i&&l.jsx(ne,{type:"icon",icon:l.jsx(ay,{}),"aria-label":n?"关闭工具箱":"打开工具箱",tooltip:n?"关闭工具箱":"打开工具箱",tooltipPlacement:"right",selected:n,visible:!0,"data-track":"toolbar_click_toolbox","data-testid":"toolbar-toolbox",onPointerDown:h=>{h.event.stopPropagation()},onClick:i}),l.jsxs("div",{className:"bottom-actions-section__task-wrapper",children:[l.jsx(ly,{count:o.length>0?o.length:0,showZero:!1,offset:[6,-6],children:l.jsx(ne,{type:"icon",icon:l.jsx(cy,{}),"aria-label":"任务队列",tooltip:d,tooltipPlacement:"right",selected:s,visible:!0,"data-track":"toolbar_click_tasks","data-testid":"toolbar-tasks",onPointerDown:h=>{h.event.stopPropagation()},onClick:r})}),o.length>0&&l.jsx("div",{className:"bottom-actions-section__status bottom-actions-section__status--active"}),c.length>0&&o.length===0&&l.jsx("div",{className:"bottom-actions-section__status bottom-actions-section__status--failed"})]})]})},pk=f.lazy(()=>Ne(()=>import("./TaskQueuePanel-VfjKIooN.js"),__vite__mapDeps([0,2,3]),import.meta.url).then(e=>({default:e.TaskQueuePanel}))),gk=460,mk=["ai-image","ai-video"],Sk=Gn.memo(({className:e,projectDrawerOpen:t=!1,onProjectDrawerToggle:n,toolboxDrawerOpen:i=!1,onToolboxDrawerToggle:s,taskPanelExpanded:r=!1,onTaskPanelToggle:o,onOpenBackupRestore:a,onOpenCloudSync:c,onOpenMediaLibrary:u,deferredFeaturesEnabled:d=!1,minimizedToolsBarEnabled:h=!1,onEnableToolWindows:p})=>{const[g,m]=f.useState(!1),[b,S]=f.useState(!0),w=f.useRef(!1),y=f.useRef(null),T=f.useRef(null),C=f.useRef(!1),{isMobile:E,isTablet:v}=uy(),x=E||v;zo(y,{enablePositionTracking:!0,enableScaleCompensation:!0});const O=f.useCallback(N=>{if(N[0]){const M=N[0].contentRect.height;m(M<gk)}},[]);f.useEffect(()=>{const N=y.current;if(!N)return;const M=new ResizeObserver(O);return M.observe(N),()=>{M.disconnect()}},[O]),f.useEffect(()=>{if(C.current)return;const N=T.current;if(!N)return;const M=()=>{C.current=!0;let he=null;for(const K of mk){const ae=N.querySelector(`[data-button-id="${K}"]`);if(ae){he=ae;break}}if(!he)return;const R=N.getBoundingClientRect(),W=he.getBoundingClientRect();if(!(W.bottom<=R.bottom&&W.top>=R.top)&&R.height>0){const K=W.top-R.top;N.scrollTop+=K}},Z=setTimeout(()=>{requestAnimationFrame(M)},100);return()=>{clearTimeout(Z)}},[]);const B=f.useCallback(()=>{!r&&!w.current&&(w.current=!0),o==null||o()},[r,o]),X=f.useCallback(()=>{r&&(o==null||o())},[r,o]),j=f.useCallback(()=>{S(N=>!N)},[]),{openDialog:L}=Ut(),D=f.useCallback(()=>{L(ln.aiImageGeneration)},[L]),k=f.useCallback(()=>{L(ln.aiVideoGeneration)},[L]);return l.jsxs(l.Fragment,{children:[w.current&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(pk,{expanded:r,onClose:X})}),l.jsxs(qe,{ref:y,className:q("unified-toolbar",Dt,{"unified-toolbar--icon-only":g||x,"unified-toolbar--mobile-collapsed":x&&b},e),padding:0,"data-testid":"unified-toolbar",children:[x&&b&&l.jsxs("div",{className:"unified-toolbar__collapsed-shortcuts",children:[l.jsx("button",{className:"unified-toolbar__collapsed-btn unified-toolbar__collapsed-btn--toggle",onClick:j,"aria-label":"展开工具栏",children:l.jsx(Rf,{size:18})}),l.jsx("button",{className:"unified-toolbar__collapsed-btn",onClick:D,"aria-label":"AI 图片生成",children:l.jsx(Oo,{})}),l.jsx("button",{className:"unified-toolbar__collapsed-btn",onClick:k,"aria-label":"AI 视频生成",children:l.jsx(Bo,{})})]}),x&&!b&&l.jsx("button",{className:"unified-toolbar__mobile-toggle unified-toolbar__mobile-toggle--expanded",onClick:j,"aria-label":"收起工具栏",children:l.jsx(Ul,{size:18})}),l.jsx("div",{className:"unified-toolbar__section unified-toolbar__section--fixed-top",children:l.jsx(UP,{embedded:!0,iconMode:g||x,onOpenBackupRestore:a,onOpenCloudSync:c})}),l.jsx("div",{ref:T,className:"unified-toolbar__scrollable",children:l.jsx("div",{className:"unified-toolbar__section",children:l.jsx(uk,{embedded:!0,iconMode:g||x,onOpenMediaLibrary:u,deferredFeaturesEnabled:d,minimizedToolsBarEnabled:h,onEnableToolWindows:p})})}),l.jsx("div",{className:"unified-toolbar__section unified-toolbar__section--fixed-bottom",children:l.jsx(fk,{projectDrawerOpen:t,onProjectDrawerToggle:n||(()=>{}),toolboxDrawerOpen:i,onToolboxDrawerToggle:s,taskPanelExpanded:r,onTaskPanelToggle:B})})]})]})}),bk=e=>n=>{const{globalKeyDown:i,keyDown:s}=n;return n.globalKeyDown=r=>{const o=r.target instanceof HTMLInputElement||r.target instanceof HTMLTextAreaElement||r.target instanceof HTMLElement&&r.target.isContentEditable;if(!o){if(tt.isHotkey(["mod+k"])(r)){e({openCommandPalette:!0}),r.preventDefault();return}if(tt.isHotkey(["mod+f"])(r)){e({openCanvasSearch:!0}),r.preventDefault();return}}if(!o&&(z.getMovingPointInBoard(n)||z.isMovingPointInBoard(n))&&!z.hasBeenTextEditing(n)){if(tt.isHotkey(["mod+shift+e"],{byKey:!0})(r)){zr(n,!0),r.preventDefault();return}if(tt.isHotkey(["mod+s"],{byKey:!0})(r)){Wf(n),r.preventDefault();return}if(tt.isHotkey(["mod+backspace"])(r)||tt.isHotkey(["mod+delete"])(r)){e({openCleanConfirm:!0}),r.preventDefault();return}if(tt.isHotkey(["mod+u"])(r)&&Go(n),He(n).length>1){if(tt.isHotkey(["alt+a"])(r)){on.alignLeft(n),r.preventDefault();return}if(tt.isHotkey(["alt+h"])(r)){on.alignCenter(n),r.preventDefault();return}if(tt.isHotkey(["alt+d"])(r)){on.alignRight(n),r.preventDefault();return}if(tt.isHotkey(["alt+w"])(r)){on.alignTop(n),r.preventDefault();return}if(tt.isHotkey(["alt+v"])(r)){on.alignMiddle(n),r.preventDefault();return}if(tt.isHotkey(["alt+s"])(r)){on.alignBottom(n),r.preventDefault();return}if(tt.isHotkey(["shift+h"])(r)){ts.distributeHorizontal(n),r.preventDefault();return}if(tt.isHotkey(["shift+v"])(r)){ts.distributeVertical(n),r.preventDefault();return}if(tt.isHotkey(["shift+a"])(r)){ts.autoArrange(n),r.preventDefault();return}if(tt.isHotkey(["alt+shift+u"])(r)){Tn.union(n,"zh"),r.preventDefault();return}if(tt.isHotkey(["alt+shift+s"])(r)){Tn.subtract(n,"zh"),r.preventDefault();return}if(tt.isHotkey(["alt+shift+i"])(r)){Tn.intersect(n,"zh"),r.preventDefault();return}if(tt.isHotkey(["alt+shift+e"])(r)){Tn.exclude(n,"zh"),r.preventDefault();return}if(tt.isHotkey(["alt+shift+f"])(r)){Tn.flatten(n,"zh"),r.preventDefault();return}}if(!r.altKey&&!r.metaKey&&!r.ctrlKey&&tt.isHotkey(["shift+p"],{byKey:!0})(r)){ht(n,Et.drawing),fe.updatePointerType(n,Bn.pen),e({pointer:Bn.pen}),r.preventDefault();return}if(!r.altKey&&!r.metaKey&&!r.ctrlKey&&!r.shiftKey){if(r.key==="l"){ht(n,Et.drawing),fe.updatePointerType(n,ot.laserPointer),e({pointer:ot.laserPointer}),r.preventDefault();return}if(r.key==="Escape"&&z.isPointer(n,ot.laserPointer)){fe.updatePointerType(n,vt.selection),e({pointer:vt.selection}),r.preventDefault();return}if(r.key==="h"&&(fe.updatePointerType(n,vt.hand),e({pointer:vt.hand})),r.key==="v"&&(fe.updatePointerType(n,vt.selection),e({pointer:vt.selection})),r.key==="q"&&(fe.updatePointerType(n,tr),e({pointer:tr})),r.key==="m"&&(ht(n,Et.dnd),fe.updatePointerType(n,ki.mind),e({pointer:ki.mind})),r.key==="e"&&(ht(n,Et.drawing),fe.updatePointerType(n,ot.eraser),e({pointer:ot.eraser})),r.key==="p"&&(ht(n,Et.drawing),fe.updatePointerType(n,ot.feltTipPen),e({pointer:ot.feltTipPen})),r.key==="a"&&!tt.isHotkey(["mod+a"])(r)&&He(n).length===0&&(ht(n,Et.drawing),fe.updatePointerType(n,En.straight),e({pointer:En.straight})),r.key==="f"&&(ht(n,Et.drawing),fe.updatePointerType(n,xu),e({pointer:xu})),r.key==="r"||r.key==="o"||r.key==="t"){const c={r:Pe.rectangle,o:Pe.ellipse,t:Pe.text};c[r.key]===Pe.text?ht(n,null):ht(n,Et.drawing),fe.updatePointerType(n,c[r.key]),e({pointer:c[r.key]})}r.preventDefault();return}}i(r)},n.keyDown=r=>{if(tt.isHotkey(["mod+z"],{byKey:!0})(r)){n.undo(),r.preventDefault();return}if(tt.isHotkey(["mod+shift+z"],{byKey:!0})(r)){n.redo(),r.preventDefault();return}s(r)},n};function Bc(e){return e===Bt.square?"square":"round"}function Hc(e,t){const n=Math.min(t/50,1),i=.2+n*.1,s=6-n*4,r=i+e*(s-i);return Math.max(.5,t*r)}function yk(e,t,n,i,s,r){const o=document.createElementNS("http://www.w3.org/2000/svg","g"),a=Bc(r);if(e.length<2){if(e.length===1){const p=Hc(t[0]??.5,n);if(r===Bt.square){const g=document.createElementNS("http://www.w3.org/2000/svg","rect");g.setAttribute("x",String(e[0][0]-p/2)),g.setAttribute("y",String(e[0][1]-p/2)),g.setAttribute("width",String(p)),g.setAttribute("height",String(p)),g.setAttribute("fill",i),o.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(p/2)),g.setAttribute("fill",i),o.appendChild(g)}}return o}const c=oc(e,1,3);if(s===yn.double){const p=n*.8,g=n*.4,[m,b]=Tk(c,t,g,p);if(m){const S=document.createElementNS("http://www.w3.org/2000/svg","path");S.setAttribute("d",m),S.setAttribute("fill",i),S.setAttribute("stroke","none"),o.appendChild(S)}if(b){const S=document.createElementNS("http://www.w3.org/2000/svg","path");S.setAttribute("d",b),S.setAttribute("fill",i),S.setAttribute("stroke","none"),o.appendChild(S)}return o}const u=gp(s,n),d=s!==Jn.solid&&u?u.join(" "):"",h=vk(c,t,n);if(h.length>0){const p=document.createElementNS("http://www.w3.org/2000/svg","path");p.setAttribute("d",h),p.setAttribute("fill",i),p.setAttribute("stroke","none"),d&&(p.setAttribute("fill","none"),p.setAttribute("stroke",i),p.setAttribute("stroke-width",String(n)),p.setAttribute("stroke-dasharray",d),p.setAttribute("stroke-linecap",a),p.setAttribute("stroke-linejoin",a==="square"?"miter":"round")),o.appendChild(p)}return o}function wk(e,t,n,i){const s=document.createElementNS("http://www.w3.org/2000/svg","g"),r=Bc(i);if(e.length<2){if(e.length===1){const b=t*.8,S=t*.4;if(i===Bt.square){const w=document.createElementNS("http://www.w3.org/2000/svg","rect");w.setAttribute("x",String(e[0][0]-S/2)),w.setAttribute("y",String(e[0][1]-b/2-S/2)),w.setAttribute("width",String(S)),w.setAttribute("height",String(S)),w.setAttribute("fill",n),s.appendChild(w);const y=document.createElementNS("http://www.w3.org/2000/svg","rect");y.setAttribute("x",String(e[0][0]-S/2)),y.setAttribute("y",String(e[0][1]+b/2-S/2)),y.setAttribute("width",String(S)),y.setAttribute("height",String(S)),y.setAttribute("fill",n),s.appendChild(y)}else{const w=document.createElementNS("http://www.w3.org/2000/svg","circle");w.setAttribute("cx",String(e[0][0])),w.setAttribute("cy",String(e[0][1]-b/2)),w.setAttribute("r",String(S/2)),w.setAttribute("fill",n),s.appendChild(w);const y=document.createElementNS("http://www.w3.org/2000/svg","circle");y.setAttribute("cx",String(e[0][0])),y.setAttribute("cy",String(e[0][1]+b/2)),y.setAttribute("r",String(S/2)),y.setAttribute("fill",n),s.appendChild(y)}}return s}const o=oc(e,1,3),a=t*.8,c=t*.4,u=[],d=[];for(let b=0;b<o.length;b++){let S,w;b===0?(S=o[1][0]-o[0][0],w=o[1][1]-o[0][1]):b===o.length-1?(S=o[b][0]-o[b-1][0],w=o[b][1]-o[b-1][1]):(S=o[b+1][0]-o[b-1][0],w=o[b+1][1]-o[b-1][1]);const y=Math.sqrt(S*S+w*w);if(y>0){const T=-w/y,C=S/y,E=a/2;u.push([o[b][0]+T*E,o[b][1]+C*E]),d.push([o[b][0]-T*E,o[b][1]-C*E])}else u.push(o[b]),d.push(o[b])}const h=document.createElementNS("http://www.w3.org/2000/svg","path");let p=`M ${u[0][0]} ${u[0][1]}`;for(let b=1;b<u.length;b++){const S=u[b-1],w=u[b],y=(S[0]+w[0])/2,T=(S[1]+w[1])/2;p+=` Q ${S[0]} ${S[1]} ${y} ${T}`}p+=` L ${u[u.length-1][0]} ${u[u.length-1][1]}`,h.setAttribute("d",p),h.setAttribute("fill","none"),h.setAttribute("stroke",n),h.setAttribute("stroke-width",String(c)),h.setAttribute("stroke-linecap",r),h.setAttribute("stroke-linejoin",r==="square"?"miter":"round"),s.appendChild(h);const g=document.createElementNS("http://www.w3.org/2000/svg","path");let m=`M ${d[0][0]} ${d[0][1]}`;for(let b=1;b<d.length;b++){const S=d[b-1],w=d[b],y=(S[0]+w[0])/2,T=(S[1]+w[1])/2;m+=` Q ${S[0]} ${S[1]} ${y} ${T}`}return m+=` L ${d[d.length-1][0]} ${d[d.length-1][1]}`,g.setAttribute("d",m),g.setAttribute("fill","none"),g.setAttribute("stroke",n),g.setAttribute("stroke-width",String(c)),g.setAttribute("stroke-linecap",r),g.setAttribute("stroke-linejoin",r==="square"?"miter":"round"),s.appendChild(g),s}function Tk(e,t,n,i){if(e.length<2)return["",""];const s=[],r=[];for(let c=0;c<e.length;c++){let u,d;c===0?(u=e[1][0]-e[0][0],d=e[1][1]-e[0][1]):c===e.length-1?(u=e[c][0]-e[c-1][0],d=e[c][1]-e[c-1][1]):(u=e[c+1][0]-e[c-1][0],d=e[c+1][1]-e[c-1][1]);const h=Math.sqrt(u*u+d*d);if(h>0){const p=-d/h,g=u/h,m=i/2;s.push([e[c][0]+p*m,e[c][1]+g*m]),r.push([e[c][0]-p*m,e[c][1]-g*m])}else s.push(e[c]),r.push(e[c])}const o=Lh(s,t,n),a=Lh(r,t,n);return[o,a]}function Lh(e,t,n){if(e.length<2)return"";const i=[],s=[];for(let o=0;o<e.length;o++){const a=t[o]??.5,u=Hc(a,n)/2;let d,h;o===0?(d=e[1][0]-e[0][0],h=e[1][1]-e[0][1]):o===e.length-1?(d=e[o][0]-e[o-1][0],h=e[o][1]-e[o-1][1]):(d=e[o+1][0]-e[o-1][0],h=e[o+1][1]-e[o-1][1]);const p=Math.sqrt(d*d+h*h);if(p>0){const g=-h/p,m=d/p;i.push([e[o][0]+g*u,e[o][1]+m*u]),s.push([e[o][0]-g*u,e[o][1]-m*u])}else i.push(e[o]),s.push(e[o])}let r=`M ${i[0][0]} ${i[0][1]}`;for(let o=1;o<i.length;o++){const a=i[o-1],c=i[o],u=(a[0]+c[0])/2,d=(a[1]+c[1])/2;r+=` Q ${a[0]} ${a[1]} ${u} ${d}`}r+=` L ${i[i.length-1][0]} ${i[i.length-1][1]}`,r+=` L ${s[s.length-1][0]} ${s[s.length-1][1]}`;for(let o=s.length-2;o>=0;o--){const a=s[o+1],c=s[o],u=(a[0]+c[0])/2,d=(a[1]+c[1])/2;r+=` Q ${a[0]} ${a[1]} ${u} ${d}`}return r+=` L ${s[0][0]} ${s[0][1]}`,r+=" Z",r}function vk(e,t,n){if(e.length<2)return"";const i=[],s=[];for(let o=0;o<e.length;o++){const a=t[o]??.5,u=Hc(a,n)/2;let d,h;o===0?(d=e[1][0]-e[0][0],h=e[1][1]-e[0][1]):o===e.length-1?(d=e[o][0]-e[o-1][0],h=e[o][1]-e[o-1][1]):(d=e[o+1][0]-e[o-1][0],h=e[o+1][1]-e[o-1][1]);const p=Math.sqrt(d*d+h*h);if(p>0){const g=-h/p,m=d/p;i.push([e[o][0]+g*u,e[o][1]+m*u]),s.push([e[o][0]-g*u,e[o][1]-m*u])}else i.push(e[o]),s.push(e[o])}let r=`M ${i[0][0]} ${i[0][1]}`;for(let o=1;o<i.length;o++){const a=i[o-1],c=i[o],u=(a[0]+c[0])/2,d=(a[1]+c[1])/2;r+=` Q ${a[0]} ${a[1]} ${u} ${d}`}r+=` L ${i[i.length-1][0]} ${i[i.length-1][1]}`,r+=` L ${s[s.length-1][0]} ${s[s.length-1][1]}`;for(let o=s.length-2;o>=0;o--){const a=s[o+1],c=s[o],u=(a[0]+c[0])/2,d=(a[1]+c[1])/2;r+=` Q ${a[0]} ${a[1]} ${u} ${d}`}return r+=` L ${s[0][0]} ${s[0][1]}`,r+=" Z",r}class Fc extends Yf{draw(t){const n=dy(t),i=Uf(this.board,t),s=hy(this.board,t),r=fy(this.board,t),o=gp(r,n),a=t.brushShape,c=Bc(a);if(t.pressures&&t.pressures.length>0)return yk(t.points,t.pressures,n,i,r,a);if(r===yn.double)return wk(t.points,n,i,a);const u={strokeWidth:n,stroke:i,fill:s,fillStyle:"solid",strokeLineDash:r!==Jn.solid?o:void 0},d=z.getRoughSVG(this.board).curve(oc(t.points,1,3),u);return py(d,c),d}canDraw(t){return!0}}class xk extends ac{constructor(){super()}initializeGenerator(){this.activeGenerator=mp(this.board,{getRectangle:t=>Vo(t),getStrokeWidth:()=>Sp,getStrokeOpacity:()=>1,hasResizeHandle:()=>bp(this.board,this.element)}),this.generator=new Fc(this.board)}initialize(){super.initialize(),this.initializeGenerator(),this.generator.processDrawing(this.element,this.getElementG())}onContextChanged(t,n){const i=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,z.getActiveHost(this.board),{selected:this.selected})):i&&t.selected?this.activeGenerator.processDrawing(this.element,z.getActiveHost(this.board),{selected:this.selected}):(t.selected!==n.selected||t.selected)&&this.activeGenerator.processDrawing(this.element,z.getActiveHost(this.board),{selected:this.selected})}destroy(){var t;super.destroy(),(t=this.activeGenerator)==null||t.destroy()}}class Em{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 i=n.timestamp??Date.now();if(this.points.length===0){const c={point:t,timestamp:i,...n};return this.points.push(c),this.lastProcessedTime=i,t}if(i-this.lastProcessedTime<this.options.samplingRate&&i-this.lastProcessedTime<2)return null;const s={point:t,timestamp:i,...n};if(!this.checkDistance(t)&&this.points.length>1&&i-this.lastProcessedTime<32)return null;this.updatePoints(s);const o=this.calculateDynamicParameters(s),a=this.smooth(t,o);return this.lastProcessedTime=i,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,i=this.getDistance(n,t);let s=this.options.minDistance;if(this.movingAverageVelocity.length>0){const r=this.getAverageVelocity();s*=Math.max(.5,Math.min(1.5,r/200))}return i>=s}calculateDynamicParameters(t){const n=this.calculateVelocity(t);this.updateMovingAverage(n);const i=this.getAverageVelocity(),s={...this.options};if(t.pressure!==void 0){const o=Math.pow(t.pressure,1.2);s.smoothing*=1-o*s.pressureSensitivity*.8}const r=Math.min(i/s.velocityThreshold,1);if(s.velocityWeight=.2+r*.3,s.smoothing*=1+r*.2,t.tiltX!==void 0&&t.tiltY!==void 0){const o=Math.sqrt(t.tiltX**2+t.tiltY**2)/90;s.smoothing*=1+o*s.tiltSensitivity*.7}return s}smooth(t,n){if(this.points.length<2)return t;const i=this.calculateWeights(n),s=i.reduce((o,a)=>o+a,0);if(s===0)return t;const r=[0,0];for(let o=0;o<this.points.length;o++){const a=i[o]/s;r[0]+=this.points[o].point[0]*a,r[1]+=this.points[o].point[1]*a}return r}calculateWeights(t){const n=[],i=this.points.length-1;for(let s=0;s<this.points.length;s++){let r=Math.pow(t.smoothing,(i-s)*.8);if(s<i){const o=this.getPointVelocity(s);r*=1+o*t.velocityWeight*.8}if(s>0&&s<i){const o=this.getPointCurvature(s);r*=1+o*t.curvatureWeight*.7}n.push(r)}return n}getDistance(t,n){return io(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],i=this.getDistance(n.point,t.point),s=t.timestamp-n.timestamp;return s>0?i/s: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],i=this.points[t+1],s=this.getDistance(n.point,i.point),r=i.timestamp-n.timestamp;return r>0?s/r:0}getPointCurvature(t){if(t<=0||t>=this.points.length-1)return 0;const n=this.points[t-1].point,i=this.points[t].point,s=this.points[t+1].point,r=this.getDistance(n,i),o=this.getDistance(i,s),a=this.getDistance(n,s),c=(r+o+a)/2;return 4*Math.sqrt(Math.max(0,c*(c-r)*(c-o)*(c-a)))/(r*o*a+1e-4)}}const Ek=e=>{const{pointerDown:t,pointerMove:n,pointerUp:i,globalPointerUp:s}=e;let r=!1,o=!1,a=[],c=[],u=null;const d=new Fc(e),h=new Em({smoothing:.7,pressureSensitivity:.6});let p=null,g=null,m=null,b=0;const S=(T=!1)=>{if(!g||T){const C=si(e);g={strokeWidth:C.strokeWidth,strokeColor:C.strokeColor,strokeStyle:C.strokeStyle,pencilShape:C.pencilShape,pressureEnabled:C.pressureEnabled}}return g},w=(T,C)=>{if(!C)return 1;if(T.pointerType==="pen"&&T.pressure>0&&T.pressure!==.5)return T.pressure;const v=[T.x,T.y],x=performance.now();if(m&&b>0){const O=v[0]-m[0],B=v[1]-m[1],X=Math.sqrt(O*O+B*B),j=x-b;if(j>0){const L=X/j,D=.2,k=1,M=Math.min(L/1.5,1),Z=k-M*(k-D);return m=v,b=x,Z}}return m=v,b=x,.6},y=T=>{if(r){const C=z.getPointer(e);o&&(a.push(a[0]),c.length>0&&c.push(c[0]));const E=S();p=el(C,a,{strokeWidth:E.strokeWidth,strokeColor:E.strokeColor,strokeStyle:E.strokeStyle,brushShape:E.pencilShape,pressures:E.pressureEnabled?c:void 0})}p&&!T&&ue.insertNode(e,p,[e.children.length]),d==null||d.destroy(),p=null,r=!1,a=[],c=[],m=null,b=0,g=null,h.reset()};return e.pointerDown=T=>{const C=lc();if(z.isInPointer(e,C)&&cc(e)){r=!0;const v=S(!0);u=[T.x,T.y];const x=h.process(u);if(x){const O=Gt(e,zt(e,x[0],x[1]));a.push(O),c.push(w(T,v.pressureEnabled))}}t(T)},e.pointerMove=T=>{if(r){const C=[T.x,T.y];u&&io(u[0],u[1],C[0],C[1])<8?o=!0:o=!1;const E=h.process(C);if(E){d==null||d.destroy();const v=Gt(e,zt(e,E[0],E[1]));a.push(v);const x=S();c.push(w(T,x.pressureEnabled));const O=z.getPointer(e);p=el(O,a,{strokeWidth:x.strokeWidth,strokeColor:x.strokeColor,strokeStyle:x.strokeStyle,brushShape:x.pencilShape,pressures:x.pressureEnabled?c:void 0}),d.processDrawing(p,z.getElementTopHost(e))}return}n(T)},e.pointerUp=T=>{y(),i(T)},e.globalPointerUp=T=>{y(!0),s(T)},e},_k=e=>{const t=e,{getDeletedFragment:n,buildFragment:i,insertFragment:s}=t;return t.getDeletedFragment=r=>{const o=Eu(t);return o.length&&r.push(...o),n(r)},t.buildFragment=(r,o,a,c)=>{const u=Eu(t);if(u.length){const d=yp(t,u,o?[o.x,o.y]:[0,0]);r=wp(r,{text:"",type:Tp.elements,elements:d})}return i(r,o,a,c)},t.insertFragment=(r,o,a)=>{var u;const c=(u=r==null?void 0:r.elements)==null?void 0:u.filter(d=>Xe.isFreehand(d));c&&c.length>0&&vp(t,c,o),s(r,o,a)},t};function Ck(e,t,n,i=0){const s=ge.getCenterPoint(t),r=Ni(t,ci);if(i){const o=Pk(n,s,-i);let a=r.find(c=>ge.isHit(ge.getRectangleByPoints([o,o]),c.rectangle));return a&&(a.cursorClass=Uo(a.cursorClass,i)),a}else return r.find(o=>ge.isHit(ge.getRectangleByPoints([n,n]),o.rectangle))}function Pk(e,t,n){const i=n*Math.PI/180,s=Math.cos(i),r=Math.sin(i),o=e[0]-t[0],a=e[1]-t[1];return[t[0]+o*s-a*r,t[1]+o*r+a*s]}function _m(e){const t=He(e);return t.length===1&&Xe.isFreehand(t[0])?t[0]:null}function kk(e){return _m(e)!==null}function Ak(e,t){const n=_m(e);if(!n)return null;const i=Vo(n),s=n.angle||0,r=Ck(e,i,t,s);return r?{element:n,rectangle:i,handle:r.handle,cursorClass:r.cursorClass}:null}function Mk(e,t,n){const i=n.width/t.width,s=n.height/t.height;return e.map(r=>{const o=r[0]-t.x,a=r[1]-t.y;return[n.x+o*i,n.y+a*s]})}function Ik(e,t,n){const{element:i,rectangle:s,handle:r}=t,{startPoint:o,endPoint:a}=n;if(!s)return;const c=a[0]-o[0],u=a[1]-o[1],d=bs(s,r,c,u,pr(),10),h=Mk(i.points,s,d),p=e.children.findIndex(g=>g.id===i.id);p>=0&&ue.setNode(e,{points:h},[p])}const Dk=e=>Di(e,{key:"freehand",canResize:()=>kk(e),hitTest:(t=>Ak(e,t)),onResize:(t,n)=>Ik(e,t,n)});function Nk(e){return e.type==="video"}const dr=1e3;async function Gc(){const e=await Ne(()=>import("./clipper-BWlMmsTH.js").then(t=>t.c),__vite__mapDeps([0]),import.meta.url);return e.default||e}function hr(e){return e.map(t=>({X:Math.round(t[0]*dr),Y:Math.round(t[1]*dr)}))}function Cm(e){return e.map(t=>[t.X/dr,t.Y/dr])}async function Rk(e,t,n=_u.circle){if(e.length<2)return[];const i=await Gc(),s=hr(e),r=new i.ClipperOffset;n===_u.square?r.AddPath(s,i.JoinType.jtMiter,i.EndType.etOpenSquare):r.AddPath(s,i.JoinType.jtRound,i.EndType.etOpenRound);const o=[];return r.Execute(o,t/2*dr),o.length===0?[]:Cm(o[0])}function zc(e){const t=e.points;if(!t||t.length<3)return!1;const n=t[0],i=t[t.length-1];return Math.hypot(i[0]-n[0],i[1]-n[1])<=10}function jk(e,t=20){if(Je.isPenPath(e)){if(!e.closed)return null;const n=qf(e);return gy(n,!0,t)}if(Xe.isFreehand(e)){const n=e.points;return!n||n.length<3||!zc(e)?null:n}return V.isDrawElement(e)&&V.isShapeElement(e)?V.isImage(e)||V.isText(e)?null:Lk(e,t):null}function Lk(e,t=20){const n=e.points;if(!n||n.length<2)return[];const[i,s]=n,r=Math.min(i[0],s[0]),o=Math.min(i[1],s[1]),a=Math.abs(s[0]-i[0]),c=Math.abs(s[1]-i[1]),u=e.shape;if(u==="ellipse"||u==="circle"){const d=r+a/2,h=o+c/2,p=a/2,g=c/2,m=[],b=Math.PI*(3*(p+g)-Math.sqrt((3*p+g)*(p+3*g))),S=Math.max(180,Math.ceil(b/2));for(let w=0;w<S;w++){const y=2*Math.PI*w/S;m.push([d+p*Math.cos(y),h+g*Math.sin(y)])}return m}return[[r,o],[r+a,o],[r+a,o+c],[r,o+c]]}function Ok(e,t,n,i){if(e.length<3)throw new Error("Polygon must have at least 3 points");let s=1/0,r=1/0,o=-1/0,a=-1/0;for(const h of e)s=Math.min(s,h[0]),r=Math.min(r,h[1]),o=Math.max(o,h[0]),a=Math.max(a,h[1]);const c=[s,r],u=e.map(h=>({point:[h[0]-c[0],h[1]-c[1]],type:"corner"}));return{id:my(),type:xp,shape:Bn.pen,points:[c,[o,a]],anchors:u,closed:!0,strokeColor:t,fill:n,strokeWidth:i}}function Bk(e){let t="#333333",n="#FFFFFF",i=2;return Je.isPenPath(e)?(t=e.strokeColor||t,n=e.fill||n,i=e.strokeWidth||i):Xe.isFreehand(e)?(t=e.strokeColor||t,i=e.strokeWidth||i):V.isDrawElement(e)&&(t=e.strokeColor||t,n=e.fill||n,i=e.strokeWidth||i),{strokeColor:t,fill:n,strokeWidth:i}}async function Hk(e,t){const n=await Gc(),i=new n.Clipper,s=[];return i.AddPath(hr(e),n.PolyType.ptSubject,!0),i.AddPath(hr(t),n.PolyType.ptClip,!0),i.Execute(n.ClipType.ctIntersection,s,n.PolyFillType.pftNonZero,n.PolyFillType.pftNonZero),s.length>0}async function Fk(e,t,n){const i=jk(t);if(!i||i.length<3||!await Hk(i,n))return null;const r=await Gc(),o=new r.Clipper,a=[];if(o.AddPath(hr(i),r.PolyType.ptSubject,!0),o.AddPath(hr(n),r.PolyType.ptClip,!0),!o.Execute(r.ClipType.ctDifference,a,r.PolyFillType.pftNonZero,r.PolyFillType.pftNonZero))return null;const{strokeColor:u,fill:d,strokeWidth:h}=Bk(t),p=[];for(const y of a)if(y.length>=3){let T=0;for(let C=0;C<y.length;C++){const E=(C+1)%y.length;T+=y[C].X*y[E].Y,T-=y[E].X*y[C].Y}T=T/2,p.push({path:y,signedArea:T,absArea:Math.abs(T)})}if(p.length===0)return[];const g=[...p].sort((y,T)=>T.absArea-y.absArea),m=g[0],b=g.slice(1);let S;b.length>0?S=Gk(m.path,b.map(y=>y.path)):S=m.path;const w=Cm(S);try{return[Ok(w,u,d,h)]}catch{return[]}}function Gk(e,t){let n=[...e];for(const i of t){let s=1/0,r=0,o=0;for(let c=0;c<n.length;c++)for(let u=0;u<i.length;u++){const d=n[c].X-i[u].X,h=n[c].Y-i[u].Y,p=d*d+h*h;p<s&&(s=p,r=c,o=u)}const a=[];for(let c=0;c<=r;c++)a.push(n[c]);for(let c=0;c<i.length;c++){const u=(o+c)%i.length;a.push(i[u])}a.push(i[o]);for(let c=r;c<n.length;c++)a.push(n[c]);n=a}return n}function Pm(e){if(Xe.isFreehand(e)){const s=e.points;if(!s||s.length<2)return null;const r=ge.getRectangleByPoints(s),o=e.strokeWidth??2,a=o/2;return{x:r.x-a,y:r.y-a,width:r.width+o,height:r.height+o}}if(Je.isPenPath(e)){const s=e.points;if(!s||s.length<2)return null;const[r,o]=s;return{x:Math.min(r[0],o[0]),y:Math.min(r[1],o[1]),width:Math.abs(o[0]-r[0]),height:Math.abs(o[1]-r[1])}}const t=e.points;if(!t||t.length<2)return null;const[n,i]=t;return{x:Math.min(n[0],i[0]),y:Math.min(n[1],i[1]),width:Math.abs(i[0]-n[0]),height:Math.abs(i[1]-n[1])}}function zk(e,t,n){if(t.length<2)return[];let i=1/0,s=1/0,r=-1/0,o=-1/0;for(const c of t)i=Math.min(i,c[0]-n),s=Math.min(s,c[1]-n),r=Math.max(r,c[0]+n),o=Math.max(o,c[1]+n);const a=[];for(const c of e.children){if(!Vk(c))continue;const u=Pm(c);if(!u)continue;const{x:d,y:h,width:p,height:g}=u;d+p>=i&&d<=r&&h+g>=s&&h<=o&&a.push(c)}return a}function Vk(e){return Je.isPenPath(e)?e.closed:Xe.isFreehand(e)?zc(e):V.isDrawElement(e)?V.isImage(e)||V.isText(e)||V.isArrowLine(e)||V.isVectorLine(e)?!1:V.isShapeElement(e):!1}function Uk(e){if(Je.isPenPath(e))return e.closed?null:"openPath";if(Xe.isFreehand(e))return zc(e)?null:"openPath";if(V.isDrawElement(e)){if(V.isImage(e))return"image";if(V.isText(e))return"text";if(V.isArrowLine(e))return"arrowLine";if(V.isVectorLine(e))return"vectorLine";if(V.isShapeElement(e))return null}return"unsupported"}function Wk(e,t,n){if(t.length<2)return[];let i=1/0,s=1/0,r=-1/0,o=-1/0;for(const c of t)i=Math.min(i,c[0]-n),s=Math.min(s,c[1]-n),r=Math.max(r,c[0]+n),o=Math.max(o,c[1]+n);const a=[];for(const c of e.children){const u=Pm(c);if(!u)continue;const{x:d,y:h,width:p,height:g}=u;d+p>=i&&d<=r&&h+g>=s&&h<=o&&Uk(c)&&a.push(c)}return a}async function $k(e,t,n,i,s){if(s.length===0)return;const r=await Rk(t,n,i);if(r.length<3)return;const o=[],a=[];for(const c of s){const u=await Fk(e,c,r);u!==null&&(o.push(c),a.push(...u))}o.length>0&&tl.removeElements(e,o);for(const c of a)ue.insertNode(e,c,[e.children.length])}const Xk=e=>{const{pointerDown:t,pointerMove:n,pointerUp:i,globalPointerUp:s}=e;let r=!1;const o=new Set;let a=[];const c=h=>{const p=Gt(e,zt(e,h[0],h[1])),m=si(e).eraserWidth/2;e.children.filter(S=>Xe.isFreehand(S)).forEach(S=>{!o.has(S.id)&&Sy(e,S,p,m)&&(Qi.getElementG(S).style.opacity="0.2",o.add(S.id))})},u=()=>{if(o.size>0){const h=e.children.filter(p=>o.has(p.id));h.length>0&&tl.removeElements(e,h)}},d=async()=>{if(r){if(u(),a.length>=2){const h=si(e),p=zk(e,a,h.eraserWidth).filter(m=>!Xe.isFreehand(m));if(p.length>0)try{await $k(e,a,h.eraserWidth,h.eraserShape,p)}catch(m){console.error("Precise erase error:",m)}const g=Wk(e,a,h.eraserWidth).filter(m=>!Xe.isFreehand(m)&&!Ti(m)&&!Nk(m)&&!(V.isDrawElement(m)&&V.isImage(m)));g.length>0&&tl.removeElements(e,g)}r=!1,o.clear(),a=[]}};return e.pointerDown=h=>{if(z.isInPointer(e,[ot.eraser])&&cc(e)){r=!0,o.clear(),a=[];const g=[h.x,h.y],m=Gt(e,zt(e,g[0],g[1]));a.push(m),c(g);return}t(h)},e.pointerMove=h=>{if(r){Jl(e,"with-freehand-erase",()=>{const p=[h.x,h.y],g=Gt(e,zt(e,p[0],p[1]));a.push(g),c(p)});return}n(h)},e.pointerUp=h=>{if(r){d();return}i(h)},e.globalPointerUp=h=>{if(r){d();return}s(h)},e},Kk="#e91e63",Yk=3,Oh=2e3,qk=e=>{const{pointerDown:t,pointerMove:n,pointerUp:i,globalPointerUp:s}=e;let r=!1,o=[];const a=new Fc(e),c=new Em({smoothing:.7,pressureSensitivity:0});let u=null;const d=[],h=()=>z.isPointer(e,ot.laserPointer),p=()=>{if(!r)return;r=!1;const m=a.g;m?(a.g=void 0,g(m)):a.destroy(),u=null,o=[],c.reset()},g=m=>{m.style.transition=`opacity ${Oh}ms ease-out`,m.style.opacity="1",m.getBoundingClientRect(),m.style.opacity="0";const b=window.setTimeout(()=>{m.remove();const S=d.findIndex(w=>w.g===m);S>=0&&d.splice(S,1)},Oh);d.push({g:m,timer:b})};return e.pointerDown=m=>{if(h()&&cc(e)){r=!0;const b=[m.x,m.y],S=c.process(b);if(S){const w=Gt(e,zt(e,S[0],S[1]));o.push(w)}return}t(m)},e.pointerMove=m=>{if(r){const b=[m.x,m.y],S=c.process(b);if(S){a.destroy();const w=Gt(e,zt(e,S[0],S[1]));o.push(w),u=el(ot.laserPointer,o,{strokeWidth:Yk,strokeColor:Kk}),a.processDrawing(u,z.getElementTopHost(e))}return}n(m)},e.pointerUp=m=>{r&&p(),i(m)},e.globalPointerUp=m=>{r&&p(),s(m)},e},Zk=e=>{const{getRectangle:t,drawElement:n,isHit:i,isRectangleHit:s,getOneHitElement:r,isMovable:o,isAlign:a}=e;return e.drawElement=c=>Xe.isFreehand(c.element)?xk:n(c),e.getRectangle=c=>Xe.isFreehand(c)?Vo(c):t(c),e.isRectangleHit=(c,u)=>Xe.isFreehand(c)?by(e,c,u):s(c,u),e.isHit=(c,u,d)=>Xe.isFreehand(c)?yy(e,c,u):i(c,u,d),e.getOneHitElement=c=>c.every(d=>Xe.isFreehand(d))?Ep(e,c):r(c),e.isMovable=c=>Xe.isFreehand(c)?!0:o(c),e.isAlign=c=>Xe.isFreehand(c)?!0:a(c),e.setPluginOptions(_p,{customGeometryTypes:[wy]}),qk(Dk(Xk(_k(Ek(e)))))};class Qk extends ac{constructor(){super()}initializeGenerator(){this.activeGenerator=mp(this.board,{getRectangle:t=>Wo(t),getStrokeWidth:()=>Sp,getStrokeOpacity:()=>1,hasResizeHandle:()=>bp(this.board,this.element)}),this.generator=new $P(this.board)}initialize(){super.initialize(),this.initializeGenerator(),this.generator.processDrawing(this.element,this.getElementG()),this.selected&&this.activeGenerator.processDrawing(this.element,z.getActiveHost(this.board),{selected:this.selected})}onContextChanged(t,n){const i=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,z.getActiveHost(this.board),{selected:this.selected})):i&&t.selected?this.activeGenerator.processDrawing(this.element,z.getActiveHost(this.board),{selected:this.selected}):(t.selected!==n.selected||t.selected)&&this.activeGenerator.processDrawing(this.element,z.getActiveHost(this.board),{selected:this.selected})}destroy(){var t;super.destroy(),(t=this.activeGenerator)==null||t.destroy()}}const Jk=e=>e,eA=e=>{const t=e,{getDeletedFragment:n,buildFragment:i,insertFragment:s}=t;return t.getDeletedFragment=r=>{const o=Cu(t);return o.length&&r.push(...o),n(r)},t.buildFragment=(r,o,a,c)=>{const u=Cu(t);if(u.length){const d=yp(t,u,o?[o.x,o.y]:[0,0]);r=wp(r,{text:"",type:Tp.elements,elements:d})}return i(r,o,a,c)},t.insertFragment=(r,o,a)=>{var u;const c=(u=r==null?void 0:r.elements)==null?void 0:u.filter(d=>Je.isPenPath(d));c&&c.length>0&&vp(t,c,o),s(r,o,a)},t};function tA(e,t,n,i=0){const s=ge.getCenterPoint(t),r=Ni(t,ci);if(i){const o=nA(n,s,-i);let a=r.find(c=>ge.isHit(ge.getRectangleByPoints([o,o]),c.rectangle));return a&&(a.cursorClass=Uo(a.cursorClass,i)),a}else return r.find(o=>ge.isHit(ge.getRectangleByPoints([n,n]),o.rectangle))}function nA(e,t,n){const i=n*Math.PI/180,s=Math.cos(i),r=Math.sin(i),o=e[0]-t[0],a=e[1]-t[1];return[t[0]+o*s-a*r,t[1]+o*r+a*s]}function km(e){const t=He(e);return t.length===1&&Je.isPenPath(t[0])?t[0]:null}function iA(e){return km(e)!==null}function sA(e,t){const n=km(e);if(!n)return null;const i=Wo(n),s=n.angle||0,r=tA(e,i,t,s);return r?{element:n,rectangle:i,handle:r.handle,cursorClass:r.cursorClass}:null}function rA(e,t,n){return e.map(i=>({...i,point:[i.point[0]*t,i.point[1]*n],handleIn:i.handleIn?[i.handleIn[0]*t,i.handleIn[1]*n]:void 0,handleOut:i.handleOut?[i.handleOut[0]*t,i.handleOut[1]*n]:void 0}))}function oA(e,t,n){const{element:i,rectangle:s,handle:r}=t,{startPoint:o,endPoint:a}=n;if(!s)return;const c=a[0]-o[0],u=a[1]-o[1],d=bs(s,r,c,u,pr(),10),h=d.width/s.width,p=d.height/s.height,g=rA(i.anchors,h,p),b=[[d.x,d.y],[d.x+d.width,d.y+d.height]],S=e.children.findIndex(w=>w.id===i.id);S>=0&&ue.setNode(e,{points:b,anchors:g},[S])}const aA=e=>Di(e,{key:"pen-path",canResize:()=>iA(e),hitTest:(t=>sA(e,t)),onResize:(t,n)=>oA(e,t,n)}),lA=e=>{const{getRectangle:t,drawElement:n,isHit:i,isRectangleHit:s,getOneHitElement:r,isMovable:o,isAlign:a}=e;return e.drawElement=c=>Je.isPenPath(c.element)?Qk:n(c),e.getRectangle=c=>Je.isPenPath(c)?Wo(c):t(c),e.isRectangleHit=(c,u)=>Je.isPenPath(c)?Ty(e,c,u):s(c,u),e.isHit=(c,u,d)=>Je.isPenPath(c)?vy(e,c,u):i(c,u,d),e.getOneHitElement=c=>c.every(d=>Je.isPenPath(d))?Ep(e,c):r(c),e.isMovable=c=>Je.isPenPath(c)?!0:o(c),e.isAlign=c=>Je.isPenPath(c)?!0:a(c),e.setPluginOptions(_p,{customGeometryTypes:[xp]}),aA(eA(Jk(JP(e))))},Am=new WeakMap,Bh=e=>!!Am.get(e),Mm=(e,t)=>{Am.set(e,t)},cA=e=>n=>{const{pointerDown:i}=n;return n.pointerDown=s=>{Pu(s)&&!Bh(n)&&(Mm(n,!0),e({isPencilMode:!0})),!(Bh(n)&&!Pu(s))&&i(s)},n},uA=()=>{const e=bt(),{appState:t,setAppState:n}=Ut();return l.jsx(l.Fragment,{children:t.isPencilMode&&l.jsx("div",{className:"pencil-mode-toolbar",children:l.jsx(ne,{type:"button",visible:!0,tooltip:"X Pencil","aria-label":"Arrow",label:"Pencil X",onPointerDown:()=>{n({...t,isPencilMode:!1}),Mm(e,!1)}})})})},dA="#f5f5f5";function hA(e,t){const n=Math.max(4,Math.min(256,t)),i=n+4,s=i/2,r=n/2,o=`<svg width="${i}" height="${i}" viewBox="0 0 ${i} ${i}" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
60
|
+
`).trim();if(!F){oe.warning(s==="zh"?"没有可合并的内容":"No content to merge");return}const U=I.flatMap(te=>Mt(te)&&te.noteId?[te.noteId]:[]);try{const te=await PP(U,F),ee=I.slice(1).map(J=>e.children.findIndex(se=>se.id===J.id)).filter(J=>J>=0).sort((J,se)=>se-J);for(const J of ee)ue.removeNode(e,[J]);let G;if(Mt(H)){const J=e.children.findIndex(Re=>Re.id===H.id);if(J<0)throw new Error(s==="zh"?"合并目标不存在":"Merge target missing");const se={body:F};te&&(se.noteId=te),ue.setNode(e,se,[J]),G=e.children[J]}else{const J=Ft(e,[H],!1),se=e.children.findIndex(ie=>ie.id===H.id);if(se<0)throw new Error(s==="zh"?"合并目标不存在":"Merge target missing");const Re=Math.max(J.width,320),ut=Math.max(J.height,180),Oe={type:"card",id:`card-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,9)}`,body:F,fillColor:"#FA8C16",points:[[J.x,J.y],[J.x+Re,J.y+ut]],children:[],...te?{noteId:te}:{}};ue.insertNode(e,Oe,[se]),ue.removeNode(e,[se+1]),G=e.children[se]}ii(e),G&&Pi(e,G),oe.success(s==="zh"?`已合并 ${I.length} 个元素`:`Merged ${I.length} elements`)}catch(te){console.error("[PopupToolbar] Failed to merge content:",te),oe.error((te==null?void 0:te.message)||(s==="zh"?"合并内容失败":"Failed to merge content"))}};return f.useEffect(()=>{if(K){const I=n.length>0;if(!o&&I){let H,F;const U=He(e),te=Ft(e,U,!1),[ee,G]=ge.getPoints(te),J=xr(e,Os(e,ee)),se=xr(e,Os(e,G));H=J[0]+(se[0]-J[0])/2,F=J[1],Te.setPositionReference({getBoundingClientRect(){return{width:1,height:1,x:H,y:F,top:F,left:H,right:H+1,bottom:F+1}}})}}},[ae,le,me,o]),f.useEffect(()=>{if(K&&!o&&M.current){const I=M.current.getBoundingClientRect();D({top:I.top,left:I.left,width:I.width,height:I.height});const H=He(e);if(H.length>0){const F=Ft(e,H,!1),[U,te]=ge.getPoints(F),ee=xr(e,Os(e,U)),G=xr(e,Os(e,te));N({top:ee[1],left:ee[0],right:G[0],bottom:G[1],width:G[0]-ee[0],height:G[1]-ee[1]})}}},[K,o,ze,e]),f.useEffect(()=>{E.current=T},[T]),f.useEffect(()=>{if(n.length===0&&!o){const I=setTimeout(()=>{C(!1)},50);return()=>clearTimeout(I)}},[n.length,o]),f.useEffect(()=>{c.current=o},[o]),f.useEffect(()=>{const{pointerUp:I,pointerMove:H}=e;return e.pointerMove=F=>{(er(e)||Qs(e))&&!c.current&&a(!0),H(F)},e.pointerUp=F=>{c.current&&(er(e)||Qs(e))&&a(!1),I(F)},()=>{e.pointerUp=I,e.pointerMove=H}},[e]),l.jsxs(l.Fragment,{children:[K&&!o&&l.jsx(qe,{padding:1,className:q("popup-toolbar",Dt),ref:I=>{Te.setFloating(I),M.current=I},style:ze,"data-testid":"popup-toolbar",children:l.jsxs(pt.Row,{gap:1,children:[Y.hasFill&&l.jsx(HC,{board:e,currentColor:Y.fill,title:r("toolbar.fillColor"),children:l.jsx("label",{className:q("fill-label","color-label",{"color-white":Y.fill&&Js(Y.fill)&&Df(_i(Y.fill)),"color-mixed":Y.fill===void 0,"color-gradient":Y.fill&&Rn(Y.fill)&&Y.fill.type==="gradient","color-image":Y.fill&&Rn(Y.fill)&&Y.fill.type==="image"}),style:Y.fill===void 0?void 0:{background:Js(Y.fill)?Y.fill:Rn(Y.fill)?Y.fill.type==="gradient"&&Y.fill.gradient?ib(Y.fill.gradient):Y.fill.type==="solid"&&Y.fill.solid?Y.fill.solid.color:Y.fill.type==="image"&&((Ye=Y.fill.image)!=null&&Ye.imageUrl)?`url(${Y.fill.image.imageUrl}) center/cover no-repeat`:void 0:void 0}})},3),Y.hasStroke&&l.jsx(CC,{board:e,currentColor:Y.strokeColor,title:r("toolbar.stroke"),hasStrokeStyle:Y.hasStrokeStyle||!1,hasStrokeWidth:Y.hasStrokeWidth||!1,currentStrokeWidth:Y.strokeWidth,children:l.jsx("label",{className:q("stroke-label","color-label",{"color-mixed":Y.strokeColor===void 0}),style:{borderColor:Y.strokeColor}})},2),Y.hasFontColor&&l.jsx(xC,{board:e,currentColor:(P=Y.marks)==null?void 0:P.color,title:r("toolbar.fontColor"),fontColorIcon:l.jsx(sb,{currentColor:(A=Y.marks)==null?void 0:A.color})},0),Y.hasFontSize&&l.jsx(_C,{board:e,currentFontSize:Y.fontSize,title:r("toolbar.fontSize")},1),Y.hasCornerRadius&&l.jsx(FC,{board:e,currentRadius:Y.cornerRadius,title:r("toolbar.cornerRadius"),selectionRect:k},"corner-radius"),Y.hasText&&l.jsx(VC,{board:e,title:"Link"},4),Y.isTextOnly&&l.jsx(eP,{board:e,language:s,title:s==="zh"?"提示词":"Prompts"},"prompt"),Y.hasTextToSpeech&&l.jsx(ne,{className:"text-to-speech",type:"icon",icon:R&&Z.playing?l.jsx(ab,{size:15}):l.jsx(lb,{size:15}),visible:!0,selected:R&&Z.playing,title:ce,"aria-label":ce,"data-track":"toolbar_click_text_to_speech",onPointerUp:()=>{if(!X.text)return;const I=Jg(X);if(!I)return;const H=IP(e,X);if(R){Z.playing?Z.pausePlayback():Z.resumePlayback();return}yu({source:I,queue:H.length>0?H:[I],queueTab:{queueId:ob,queueName:rb}})}},"text-to-speech"),Y.hasText&&l.jsx(ne,{className:"property-settings",type:"icon",icon:l.jsx(cb,{}),visible:!0,selected:T,title:r("propertyPanel.title"),"aria-label":r("propertyPanel.title"),"data-track":"toolbar_click_property_settings",onPointerUp:()=>{C(!T)}},"property-settings"),Y.hasAlignment&&l.jsx(nP,{board:e,title:r("toolbar.alignment")},"alignment"),Y.hasDistribute&&l.jsx(iP,{board:e,title:r("toolbar.distribute")},"distribute"),Y.hasBoolean&&l.jsx(sP,{board:e,title:r("toolbar.boolean")},"boolean"),Y.hasMindmapToPPT&&l.jsx(ne,{className:"mindmap-to-ppt",type:"icon",icon:l.jsx(ub,{size:15}),visible:!0,title:s==="zh"?"转换为PPT":"Convert to PPT","aria-label":s==="zh"?"转换为PPT":"Convert to PPT","data-track":"toolbar_click_mindmap_to_ppt",onPointerUp:async()=>{const I=bu(e,n);if(!I)return;const H=oe.loading(s==="zh"?"正在转换为PPT...":"Converting to PPT...",0);try{const{generatePPTFromMindmap:F}=await Ne(async()=>{const{generatePPTFromMindmap:te}=await import("./tool-windows-C4D0lII2.js").then(ee=>ee.oI);return{generatePPTFromMindmap:te}},__vite__mapDeps([0]),import.meta.url),U=await F(e,I);oe.close(H),U.success?oe.success(s==="zh"?`已生成 ${U.pageCount} 页PPT`:`Generated ${U.pageCount} PPT slides`):oe.error(U.error||(s==="zh"?"转换失败":"Conversion failed"))}catch(F){oe.close(H),oe.error(F.message||(s==="zh"?"转换失败":"Conversion failed"))}}},"mindmap-to-ppt"),Y.hasCardEdit&&l.jsx(ne,{className:"card-edit",type:"icon",icon:l.jsx(wu,{size:15}),visible:!0,title:s==="zh"?"在知识库中编辑":"Edit in Knowledge Base","aria-label":s==="zh"?"在知识库中编辑":"Edit in Knowledge Base","data-track":"toolbar_click_card_edit",onPointerUp:async()=>{const I=n[0];I&&await Qg(e,I,s)}},"card-edit"),Y.hasCardSave&&l.jsx(ne,{className:"card-save",type:"icon",icon:l.jsx(Bf,{size:15}),visible:!0,title:s==="zh"?"保存到知识库":"Save to Knowledge Base","aria-label":s==="zh"?"保存到知识库":"Save to Knowledge Base","data-track":"toolbar_click_card_save",onPointerUp:async()=>{const I=n[0];if(!I)return;await Zg(e,I,s)&&oe.success(s==="zh"?"已保存到知识库":"Saved to knowledge base")}},"card-save"),(Y.hasCardEdit||Y.hasCardSave)&&l.jsx(ne,{className:"card-copy",type:"icon",icon:l.jsx(db,{size:15}),visible:!0,title:s==="zh"?"复制文本内容":"Copy text content","aria-label":s==="zh"?"复制文本内容":"Copy text content","data-track":"toolbar_click_card_copy",onPointerDown:({event:I})=>{I.stopPropagation()},onPointerUp:async()=>{await Ie(n[0],"card-copy")}},"card-copy"),Y.hasContentMerge&&l.jsx(ne,{className:"content-merge",type:"icon",icon:l.jsx(Tu,{}),visible:!0,title:s==="zh"?"合并内容":"Merge Content","aria-label":s==="zh"?"合并内容":"Merge Content","data-track":"toolbar_click_content_merge",onPointerUp:()=>{$e()}},"content-merge"),Y.hasAIImage&&l.jsx(ne,{className:"ai-image",type:"icon",icon:l.jsx(Oo,{}),visible:!0,title:s==="zh"?"AI图片生成":"AI Image Generation","aria-label":s==="zh"?"AI图片生成":"AI Image Generation","data-track":"toolbar_click_ai_image",onPointerUp:()=>{i(ln.aiImageGeneration)}},5),Y.hasAIVideo&&l.jsx(ne,{className:"ai-video",type:"icon",icon:l.jsx(Bo,{}),visible:!0,title:s==="zh"?"AI视频生成":"AI Video Generation","aria-label":s==="zh"?"AI视频生成":"AI Video Generation","data-track":"toolbar_click_ai_video",onPointerUp:()=>{i(ln.aiVideoGeneration)}},6),Y.hasVideoFrame&&l.jsx(ne,{className:"video-frame",type:"icon",icon:l.jsx(hb,{}),visible:!0,title:s==="zh"?"视频帧选择":"Video Frame Selection","aria-label":s==="zh"?"视频帧选择":"Video Frame Selection","data-track":"toolbar_click_video_frame",onPointerUp:()=>{const I=n.find(H=>wn(H));I&&(p(I),d(!0))}},7),Y.hasSplitImage&&l.jsx(ne,{className:"split-image",type:"icon",icon:l.jsx(pb,{}),visible:!0,title:s==="zh"?"智能拆图":"Smart Split","aria-label":s==="zh"?"智能拆图":"Smart Split","data-track":"toolbar_click_split_image",onPointerUp:async()=>{const I=n[0];if(V.isImage(I)&&I.url){const H=oe.loading(s==="zh"?"正在分析图片...":"Analyzing image...",0);try{const F=Ft(e,[I],!1),U=await fb(e,I.url,{sourceRect:{x:F.x,y:F.y,width:F.width,height:F.height},scrollToResult:!0});oe.close(H),U.success?oe.success(s==="zh"?`成功拆分为 ${U.count} 张图片`:`Split into ${U.count} images`):oe.warning(U.error||(s==="zh"?"拆图失败":"Split failed"))}catch(F){oe.close(H),oe.error(F.message||(s==="zh"?"拆图失败":"Split failed"))}}}},"split-image"),Y.hasImageEdit&&l.jsx(ne,{className:"image-edit",type:"icon",icon:l.jsx(wu,{size:15}),visible:!0,title:s==="zh"?"编辑图片":"Edit Image","aria-label":s==="zh"?"编辑图片":"Edit Image","data-track":"toolbar_click_image_edit",onPointerUp:()=>{const I=n[0];V.isImage(I)&&I.url&&(S(I.url),y(I),m(!0))}},"image-edit"),Y.hasDownloadable&&l.jsx(ne,{className:"download",type:"icon",icon:l.jsx(Sb,{}),visible:!0,title:s==="zh"?"下载":"Download","aria-label":s==="zh"?"下载":"Download","data-track":"toolbar_click_download",onPointerUp:async()=>{const I=[];for(const U of n)V.isDrawElement(U)&&V.isImage(U)&&U.url?I.push({url:U.url,type:"image"}):wn(U)&&U.url?I.push({url:U.url,type:"video"}):Kn(U)&&U.audioUrl&&I.push({url:U.audioUrl,type:"audio",filename:gb(U.title,"audio","mp3"),audioMetadata:{title:U.title,prompt:U.prompt,tags:U.tags,coverUrl:U.previewImageUrl,artist:U.modelVersion||"Aitu",album:"Aitu Generated"}});if(I.length===0){oe.warning(s==="zh"?"没有可下载的内容":"No downloadable content");return}const H=I.length>1?s==="zh"?"正在打包下载...":"Packaging download...":s==="zh"?"正在下载...":"Downloading...",F=oe.loading(H,0);try{const{unifiedCacheService:U}=await Ne(async()=>{const{unifiedCacheService:J}=await import("./tool-windows-C4D0lII2.js").then(se=>se.oG);return{unifiedCacheService:J}},__vite__mapDeps([0]),import.meta.url),{downloadFromBlob:te}=await Ne(async()=>{const{downloadFromBlob:J}=await import("./tool-windows-C4D0lII2.js").then(se=>se.oF);return{downloadFromBlob:J}},__vite__mapDeps([0]),import.meta.url),ee=[];for(const J of I)if(J.url.startsWith("blob:")){const se=J.url.indexOf("#"),Re=se>0?J.url.substring(se+1):null;if(Re&&Re.startsWith("merged-video-")){const ut=await U.getCachedBlob(Re);if(ut){const Oe=ut.type||"video/webm",ie=Oe.startsWith("video/mp4")?"mp4":Oe.startsWith("video/webm")?"webm":"bin",De=`merged-video-${Date.now()}.${ie}`;te(ut,De);continue}else console.warn("[Download] Cache not found for taskId:",Re)}try{const Oe=await(await fetch(J.url)).blob(),ie=Oe.type.startsWith("video/mp4")?"mp4":Oe.type.startsWith("video/webm")?"webm":Oe.type.startsWith("image/")?"png":"bin",De=`${J.type}_${Date.now()}.${ie}`;te(Oe,De)}catch(ut){throw console.error("[Download] Failed to fetch blob URL:",ut),new Error(`Failed to download ${J.type}: Blob URL inaccessible`)}}else ee.push(J);let G;ee.length>0&&(G=await mb(ee)),oe.close(F),G!=null&&G.openedCount&&G.downloadedCount===0?oe.success(s==="zh"?G.openedCount>1?`已打开 ${G.openedCount} 个链接,请在新标签页下载`:"资源不支持直接下载,已打开链接":G.openedCount>1?`Opened ${G.openedCount} links for download`:"Opened link for download"):oe.success(I.length>1?s==="zh"?`已下载 ${I.length} 个文件`:`Downloaded ${I.length} files`:s==="zh"?"下载成功":"Download complete")}catch(U){oe.close(F),oe.error(U.message||(s==="zh"?"下载失败":"Download failed"))}}},"download"),Y.hasMergeable&&l.jsx(ne,{className:"merge",type:"icon",icon:l.jsx(Tu,{}),visible:!0,title:s==="zh"?"合并为图片":"Merge to Image","aria-label":s==="zh"?"合并为图片":"Merge to Image","data-track":"toolbar_click_merge",onPointerUp:async()=>{const I=bb("图片合并"),H=oe.loading(s==="zh"?"正在合并...":"Merging...",0);try{const F=n.filter(st=>{const Ue=st.url||st.imageUrl;if(!Ue||Ue.startsWith("/")||Ue.startsWith("data:")||Ue.startsWith("blob:"))return!1;try{return new URL(Ue).origin!==location.origin}catch{return!1}});if(F.length>0){const st=F.map(async rt=>{const gt=rt.url||rt.imageUrl;try{const kt=new AbortController,Lt=setTimeout(()=>kt.abort(),3e3),dt=await fetch(gt,{method:"HEAD",mode:"cors",signal:kt.signal});return clearTimeout(Lt),dt.ok}catch{return!1}});if((await Promise.all(st)).some(rt=>!rt)){oe.close(H),oe.warning(s==="zh"?"部分外部图片无法访问,请先下载到本地后再合并":"Some external images are inaccessible. Please download them locally first."),I();return}}const U=Ft(e,n,!1),te=[...n].sort((st,Ue)=>{const Ge=e.children.findIndex(gt=>gt.id===st.id),rt=e.children.findIndex(gt=>gt.id===Ue.id);return Ge-rt}),ee=await yb(e,{elements:te,fillStyle:"transparent",inlineStyleClassNames:".extend,.emojis,.text",ratio:2});if(!ee)throw new Error(s==="zh"?"合并失败:无法生成图片":"Merge failed: Unable to generate image");const G=new Image;await new Promise((st,Ue)=>{G.onload=()=>st(),G.onerror=()=>Ue(new Error("Failed to load merged image")),G.src=ee});const J=document.createElement("canvas");J.width=G.width,J.height=G.height;const se=J.getContext("2d");if(!se)throw new Error("Failed to get canvas context");se.drawImage(G,0,0);const Re=wb(J),{canvas:ut,left:Oe,top:ie,trimmedWidth:De,trimmedHeight:Le}=Re,ke=await new Promise((st,Ue)=>{ut.toBlob(Ge=>{Ge?st(Ge):Ue(new Error("Failed to convert canvas to blob"))},"image/png")}),{unifiedCacheService:Fe}=await Ne(async()=>{const{unifiedCacheService:st}=await import("./tool-windows-C4D0lII2.js").then(Ue=>Ue.oG);return{unifiedCacheService:st}},__vite__mapDeps([0]),import.meta.url),Nt=`merged-image-${Date.now()}`,Pt=`/__aitu_cache__/image/${Nt}.png`,Rt=Pt;await Fe.cacheMediaFromBlob(Rt,ke,"image",{taskId:Nt});const jt=2,nn=U.x+Oe/jt,di=U.y+ie/jt,Un=De/jt,Se=Le/jt;Ka(e);const Ve=e.children.length,be={url:Pt,width:Un,height:Se};Mo.insertImage(e,be,[nn,di]);const je=e.children[Ve];je&&(ii(e),Pi(e,je)),oe.close(H),I(),oe.success(s==="zh"?`已将 ${n.length} 个元素合并为图片`:`Merged ${n.length} elements into image`)}catch(F){oe.close(H),I(),oe.error(F.message||(s==="zh"?"合并失败":"Merge failed"))}}},"merge"),Y.hasVideoMergeable&&l.jsx(ne,{className:"video-merge",type:"icon",icon:l.jsx(Tb,{}),visible:!0,title:s==="zh"?"合成视频":"Merge Videos","aria-label":s==="zh"?"合成视频":"Merge Videos","data-track":"toolbar_click_video_merge",onPointerUp:async()=>{const I=[];for(const F of n)wn(F)&&F.url&&I.push(F.url);if(I.length<2){oe.warning(s==="zh"?"请选择至少2个视频":"Please select at least 2 videos");return}const H=oe.loading(s==="zh"?"正在合成视频...":"Merging videos...",0);try{const F=await SP(I,(U,te)=>{const ee={downloading:s==="zh"?"下载视频...":"Downloading videos...",decoding:s==="zh"?"解码视频...":"Decoding videos...",encoding:s==="zh"?"编码视频...":"Encoding videos...",finalizing:s==="zh"?"生成文件中...":"Finalizing..."}});oe.close(H);try{const{quickInsert:U}=await Ne(async()=>{const{quickInsert:te}=await import("./canvas-insertion-CYbFgP4L.js");return{quickInsert:te}},__vite__mapDeps([0]),import.meta.url);await U("video",F.url),oe.success(s==="zh"?`已合成并插入 ${I.length} 个视频`:`Merged and inserted ${I.length} videos`)}catch(U){console.error("[VideoMerge] Failed to insert video:",U);const te=F.blob.type||"video/webm",ee=te.startsWith("video/mp4")?"mp4":"webm",G=new Blob([F.blob],{type:te}),J=URL.createObjectURL(G),se=document.createElement("a");se.href=J,se.download=`merged-video-${Date.now()}.${ee}`,document.body.appendChild(se),se.click(),document.body.removeChild(se),setTimeout(()=>URL.revokeObjectURL(J),1e3),oe.warning(s==="zh"?`视频已合成,但插入失败,已自动下载 (${ee.toUpperCase()})`:`Video merged but failed to insert, downloaded as ${ee.toUpperCase()}`)}}catch(F){oe.close(H),oe.error(F.message||(s==="zh"?"视频合成失败":"Video merge failed"))}}},"video-merge"),l.jsx(tP,{board:e,title:r("textEffect.layer")},"layer-control"),Y.hasSizeInput&&l.jsx(zC,{board:e},"size-input"),Y.hasFramePlay&&l.jsx(ne,{className:"frame-play",type:"icon",icon:l.jsx(vu,{size:15}),visible:!0,title:s==="zh"?"播放幻灯片":"Play Slideshow","aria-label":s==="zh"?"播放幻灯片":"Play Slideshow","data-track":"toolbar_click_frame_play",onPointerUp:()=>{const I=n.find(H=>Ti(H));I&&(B(I.id),x(!0))}},"frame-play"),Y.hasAudioPlayer&&l.jsx(ne,{className:"audio-player-play",type:"icon",icon:l.jsx(vu,{size:15}),visible:!0,title:s==="zh"?"在音乐播放器中播放":"Play in Music Player","aria-label":s==="zh"?"在音乐播放器中播放":"Play in Music Player","data-track":"toolbar_click_audio_player_play",onPointerUp:()=>{const I=n.find(H=>Kn(H));!I||!Kn(I)||yu({source:{elementId:I.id,audioUrl:I.audioUrl,title:I.title,duration:I.duration,previewImageUrl:I.previewImageUrl,providerTaskId:I.providerTaskId,clipId:I.clipId,clipIds:I.clipIds},queue:Qa(e.children),queueTab:{queueId:Ff,queueName:Hf}})}},"audio-player-play"),l.jsx(ne,{className:"duplicate",type:"icon",icon:l.jsx(_b,{}),visible:!0,title:r("general.duplicate"),"aria-label":r("general.duplicate"),"data-track":"toolbar_click_duplicate",onPointerUp:()=>{if(n.length===1&&Ti(n[0])){const H=vb(e,n[0],s);H&&xb(e,H)}else Eb(e)}},8),l.jsx(ne,{className:"trash",type:"icon",icon:l.jsx(so,{}),visible:!0,title:r("general.delete"),"aria-label":r("general.delete"),"data-track":"toolbar_click_delete",onPointerUp:()=>{Ka(e)}},9)]})}),u&&h&&l.jsx(dP,{visible:u,videoUrl:h.url||"",onClose:()=>{d(!1),p(null)},onConfirm:async(I,H)=>{try{h&&await hP(e,h,I,H)}catch(F){console.error("Failed to insert video frame:",F)}}}),g&&b&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(DP,{visible:g,imageUrl:b,showOverwrite:!!w,onClose:()=>{m(!1),S(""),y(null)},onOverwrite:async I=>{if(w)try{const{unifiedCacheService:H}=await Ne(async()=>{const{unifiedCacheService:se}=await import("./tool-windows-C4D0lII2.js").then(Re=>Re.oG);return{unifiedCacheService:se}},__vite__mapDeps([0]),import.meta.url),F=`edited-image-${Date.now()}`,U=`/__aitu_cache__/image/${F}.png`,ee=await(await fetch(I)).blob();await H.cacheMediaFromBlob(U,ee,"image",{taskId:F});const G=new Image;await new Promise((se,Re)=>{G.onload=()=>se(),G.onerror=()=>Re(new Error("Failed to load edited image")),G.src=I});const J=e.children.findIndex(se=>se.id===w.id);if(J>=0){const se=e.children[J],{newPoints:Re}=await Gf({url:se.url,width:se.width,height:se.height,points:se.points||[[0,0],[0,0]]},G.naturalWidth,G.naturalHeight);ue.setNode(e,{url:U,width:G.naturalWidth,height:G.naturalHeight,points:Re},[J])}}catch(H){console.error("Failed to update image:",H),oe.error(s==="zh"?"更新失败":"Update failed")}},onInsert:async I=>{try{const{unifiedCacheService:H}=await Ne(async()=>{const{unifiedCacheService:ie}=await import("./tool-windows-C4D0lII2.js").then(De=>De.oG);return{unifiedCacheService:ie}},__vite__mapDeps([0]),import.meta.url),F=`edited-image-${Date.now()}`,U=`/__aitu_cache__/image/${F}.png`,ee=await(await fetch(I)).blob();await H.cacheMediaFromBlob(U,ee,"image",{taskId:F});const G=new Image;await new Promise((ie,De)=>{G.onload=()=>ie(),G.onerror=()=>De(new Error("Failed to load edited image")),G.src=I});const J=Ao(e),se=w?w.points[1][0]-w.points[0][0]+20:0,Re=w?w.points[0][0]:J?J[0]+100:100,ut=w?w.points[0][1]:J?J[1]+100:100,Oe=[Re+se,ut];await ql(e,U,Oe,!1,{width:G.naturalWidth,height:G.naturalHeight},!1,!0)}catch(H){console.error("Failed to insert image:",H),oe.error(s==="zh"?"插入失败":"Insert failed")}}})}),Y.hasText&&l.jsx(aP,{board:e,isOpen:T,onClose:()=>C(!1),currentFontSize:Y.fontSize,currentFontFamily:($=Y.marks)==null?void 0:$["font-family"],currentColor:(Q=Y.marks)==null?void 0:Q.color,toolbarRect:L,selectionRect:k}),v&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(NP,{visible:v,board:e,onClose:()=>{x(!1),B(void 0)},initialFrameId:O})})]})},em=(e,t)=>{const n=Vf(t);return{fill:Ho(t),strokeColor:Ab(e,t),fontSize:n["font-size"],marks:n}},tm=(e,t)=>{const n=Vf(t);return{fill:Ho(t),strokeColor:Mb(e,t),fontSize:n["font-size"],marks:n}},jP=e=>{const t=He(e);if(t.length===0)return{fill:void 0,strokeColor:void 0};if(t.length===1){const n=t[0];return Mt(n)?{fill:n.fillColor,strokeColor:void 0}:tn.isMindElement(e,n)?em(e,n):Xe.isFreehand(n)?nm(e,n):Je.isPenPath(n)?im(e,n):tm(e,n)}return LP(e,t)},LP=(e,t)=>{const n=t.map(a=>Mt(a)?{fill:a.fillColor,strokeColor:void 0}:tn.isMindElement(e,a)?em(e,a):Xe.isFreehand(a)?nm(e,a):Je.isPenPath(a)?im(e,a):V.isDrawElement(a)?tm(e,a):{fill:void 0,strokeColor:void 0}),i=n.map(a=>a.fill),s=n.map(a=>a.strokeColor),r=i.every(a=>a===i[0]),o=s.every(a=>a===s[0]);return{fill:r?i[0]:void 0,strokeColor:o?s[0]:void 0}},nm=(e,t)=>({fill:Ho(t),strokeColor:Uf(e,t)}),im=(e,t)=>({fill:Ho(t),strokeColor:t.strokeColor,cornerRadius:t.cornerRadius}),OP=(e,t)=>Mt(t)||tn.isMindElement(e,t)||Cb(e,t)?!0:Xe.isFreehand(t)?Pb(t.points):Je.isPenPath(t)?t.closed:V.isDrawElement(t)?V.isShapeElement(t)&&!V.isImage(t)&&!V.isText(t)&&zf(t):!1,sm=(e,t)=>tn.isMindElement(e,t)||Xe.isFreehand(t)||Je.isPenPath(t)?!0:V.isDrawElement(t)?V.isShapeElement(t)&&!V.isImage(t)&&!V.isText(t)||V.isArrowLine(t)||V.isVectorLine(t)||V.isTable(t):!1,BP=(e,t)=>sm(e,t),HP=(e,t)=>tn.isMindElement(e,t)?!0:V.isDrawElement(t)?Wl([t]):!1,FP=(e,t)=>{if(Je.isPenPath(t))return t.closed;if(Xe.isFreehand(t)){const n=t.points;if(!n||n.length<3)return!1;const i=n[0],s=n[n.length-1];return Math.hypot(s[0]-i[0],s[1]-i[1])<=10}return V.isDrawElement(t)?V.isImage(t)||V.isText(t)||V.isArrowLine(t)||V.isVectorLine(t)?!1:V.isShapeElement(t)&&zf(t):(tn.isMindElement(e,t),!1)},ra=Gn.createContext({}),kh=(e="",t=!1)=>`menu-item menu-item-base ${e} ${t?"menu-item--active":""}`.trim(),GP=(e,t)=>{const n=f.useContext(ra);return Ib(e,i=>{var r;const s=new CustomEvent(Zl.MENU_ITEM_SELECT,{bubbles:!0,cancelable:!0});t==null||t(s),s.defaultPrevented||(r=n.onSelect)==null||r.call(n,s)})},zP=({icon:e,shortcut:t,children:n})=>l.jsxs(l.Fragment,{children:[e&&l.jsx("div",{className:"menu-item__icon",children:e}),l.jsx("div",{className:"menu-item__text",children:n}),t&&l.jsx("div",{className:"menu-item__shortcut",children:t})]}),Be=({icon:e,onSelect:t,children:n,shortcut:i,className:s,selected:r,submenu:o,...a})=>{const[c,u]=f.useState(!1),d=f.useRef(),h=GP(a.onClick,t),p=l.jsx(zP,{icon:e,shortcut:i,children:n}),g=()=>{d.current&&window.clearTimeout(d.current),u(!0)},m=()=>{d.current=window.setTimeout(()=>{u(!1)},100)};return o?l.jsxs(at,{open:c,onOpenChange:u,placement:"right-start",children:[l.jsx(lt,{asChild:!0,children:l.jsx("button",{...a,type:"button",className:kh(s,r||c),title:a.title??a["aria-label"],onClick:h,onMouseEnter:g,onMouseLeave:m,role:"menuitem","aria-haspopup":"true","aria-expanded":c,children:p})}),l.jsx(ct,{onMouseEnter:g,onMouseLeave:m,children:o})]}):l.jsx("button",{...a,onClick:h,type:"button",className:kh(s,r),title:a.title??a["aria-label"],role:"menuitem",children:p})};Be.displayName="MenuItem";const rm=({children:e})=>l.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});rm.displayName="MenuItemBadge";Be.Badge=rm;const _n=({children:e,className:t="",onSelect:n,style:i,onClose:s})=>{const r=q(`menu ${t}`).trim(),o=f.useRef(null),a=f.useCallback(()=>o.current?Array.from(o.current.querySelectorAll("button.menu-item:not([disabled])")):[],[]),c=f.useCallback(u=>{var p,g,m,b;const d=a();if(d.length===0)return;const h=d.findIndex(S=>S===document.activeElement);switch(u.key){case"ArrowDown":{u.preventDefault();const S=h<d.length-1?h+1:0;(p=d[S])==null||p.focus();break}case"ArrowUp":{u.preventDefault();const S=h>0?h-1:d.length-1;(g=d[S])==null||g.focus();break}case"Home":{u.preventDefault(),(m=d[0])==null||m.focus();break}case"End":{u.preventDefault(),(b=d[d.length-1])==null||b.focus();break}case"Escape":{u.preventDefault(),s==null||s();break}case"Enter":case" ":{h>=0&&d[h]&&(u.preventDefault(),d[h].click());break}}},[a,s]);return f.useEffect(()=>{const u=a();u.length>0&&requestAnimationFrame(()=>{var d;(d=u[0])==null||d.focus()})},[a]),l.jsx(ra.Provider,{value:{onSelect:n},children:l.jsx("div",{className:r,style:i,"data-testid":"menu",onKeyDown:c,ref:o,role:"menu",children:l.jsx(qe,{className:"menu-container",padding:2,children:e})})})};_n.displayName="Menu";const om=()=>{const e=bt(),{t}=Ee();return l.jsx(Be,{"data-testid":"save-button","data-track":"toolbar_click_menu_save",onSelect:()=>{Wf(e)},icon:l.jsx(Bf,{}),"aria-label":t("menu.saveFile"),shortcut:"Cmd+S",children:t("menu.saveFile")})};om.displayName="SaveToFile";const am=()=>{const e=bt(),t=Og(),{t:n}=Ee(),i=(s,r,o)=>{e.children=s,e.viewport=r||{zoom:1},e.theme={themeColorMode:pi.default},t.update(e.children,{board:e,parent:e,parentG:z.getElementHost(e)}),fe.fitViewport(e)};return l.jsx(Be,{"data-testid":"open-button","data-track":"toolbar_click_menu_open",onSelect:()=>{Nb(e).then(s=>{s&&i(s.elements,s.viewport)})},icon:l.jsx(Db,{}),"aria-label":n("menu.open"),children:n("menu.open")})};am.displayName="OpenFile";const lm=()=>{const e=bt(),t=f.useContext(ra),{t:n}=Ee();return l.jsx(Be,{icon:l.jsx(Rb,{}),"data-testid":"image-export-button","data-track":"toolbar_click_menu_export",onSelect:()=>{zr(e,!0)},submenu:l.jsxs(_n,{onSelect:()=>{var s;const i=new CustomEvent(Zl.MENU_ITEM_SELECT,{bubbles:!0,cancelable:!0});(s=t.onSelect)==null||s.call(t,i)},children:[l.jsx(Be,{"data-track":"toolbar_click_menu_export_png",onSelect:()=>{zr(e,!0)},"aria-label":n("menu.exportImage.png"),children:n("menu.exportImage.png")}),l.jsx(Be,{"data-track":"toolbar_click_menu_export_jpg",onSelect:()=>{zr(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")})};lm.displayName="SaveAsImage";const cm=()=>{const{appState:e,setAppState:t}=Ut(),{t:n}=Ee();return l.jsx(Be,{icon:l.jsx(so,{}),"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")})};cm.displayName="CleanBoard";const um=({onOpenBackupRestore:e})=>{const{t}=Ee();return l.jsx(Be,{icon:l.jsx(Lb,{}),"data-track":"toolbar_click_menu_backup",onSelect:e,"aria-label":t("menu.backupRestore"),children:t("menu.backupRestore")})};um.displayName="BackupRestore";const dm=({onOpenCloudSync:e})=>{const{t}=Ee();return l.jsx(Be,{icon:l.jsx(Bb,{}),"data-track":"toolbar_click_menu_cloud_sync",onSelect:e,"aria-label":t("menu.cloudSync"),children:t("menu.cloudSync")})};dm.displayName="CloudSync";const hm=()=>{const{t:e}=Ee();return l.jsx(Be,{icon:l.jsx(Ob,{}),"data-track":"toolbar_click_menu_debug",onSelect:()=>{window.location.href="./sw-debug.html"},"aria-label":e("menu.debugPanel"),children:e("menu.debugPanel")})};hm.displayName="DebugPanel";const fm=()=>{const{appState:e,setAppState:t}=Ut(),{t:n}=Ee();return l.jsx(Be,{icon:l.jsx(Hb,{}),"data-track":"toolbar_click_menu_settings",onSelect:()=>{t({...e,openSettings:!0})},"aria-label":n("menu.settings"),children:n("menu.settings")})};fm.displayName="Settings";const pm=()=>{const{appState:e,setAppState:t}=Ut(),{t:n}=Ee();return l.jsx(Be,{icon:l.jsx(Fb,{}),"data-track":"toolbar_click_menu_commands",onSelect:()=>{t({...e,openCommandPalette:!0})},shortcut:"Cmd+K","aria-label":n("menu.commandPalette"),children:n("menu.commandPalette")})};pm.displayName="QuickCommands";const gm=()=>{const{t:e}=Ee();return l.jsx(Be,{icon:l.jsx(Gb,{}),"data-track":"toolbar_click_menu_manual",onSelect:()=>{window.open("./user-manual/index.html","_blank")},"aria-label":e("menu.userManual"),children:e("menu.userManual")})};gm.displayName="UserManual";const mm=()=>{var n;const{t:e}=Ee(),t=((n=document.querySelector('meta[name="app-version"]'))==null?void 0:n.getAttribute("content"))||"0.0.0";return l.jsx(Be,{"data-track":"toolbar_click_menu_version",onSelect:()=>{},"aria-label":e("menu.version"),children:l.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%"},children:[l.jsxs("span",{style:{color:"#666"},children:[e("menu.version"),":",t]}),l.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[l.jsx("span",{style:{color:"#1890ff",cursor:"pointer"},"data-track":"toolbar_click_menu_changelog",onClick:i=>{i.stopPropagation(),window.open("./versions.html","_blank")},children:e("menu.changelog")}),l.jsx("span",{style:{color:"#1890ff",cursor:"pointer"},"data-track":"toolbar_click_menu_more_versions",onClick:i=>{i.stopPropagation(),window.open("https://release.opentu.ai/","_blank")},children:e("menu.more")})]})]})})};mm.displayName="VersionInfo";async function VP(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 Sm=()=>{const e=bt(),{t}=Ee(),[n,i]=f.useState(!1),s=f.useCallback(async()=>{if(n)return;i(!0);const r=oe.loading(t("menu.cleanInvalidLinks.scanning"),0);try{const o=[];for(let u=0;u<e.children.length;u++){const d=e.children[u],h=d.url;if(!h||typeof h!="string")continue;const p=V.isDrawElement(d)&&V.isImage(d),g=wn(d);(p||g)&&o.push({element:d,index:u,url:h})}const a=[];if(await Promise.all(o.map(async({element:u,index:d,url:h})=>{await VP(h)||a.push({element:u,index:d})})),r.then(u=>{var d;return(d=u==null?void 0:u.close)==null?void 0:d.call(u)}),a.length===0){oe.success(t("menu.cleanInvalidLinks.noInvalid")),i(!1);return}a.sort((u,d)=>d.index-u.index);for(const{index:u}of a)ue.removeNode(e,[u]);const c=t("menu.cleanInvalidLinks.success").replace("{count}",String(a.length));oe.success(c)}catch(o){r.then(a=>{var c;return(c=a==null?void 0:a.close)==null?void 0:c.call(a)}),oe.error(t("menu.cleanInvalidLinks.error")),console.error("[CleanInvalidLinks] Error:",o)}finally{i(!1)}},[e,t,n]);return l.jsx(Be,{icon:l.jsx(jb,{}),"data-track":"toolbar_click_menu_clean_invalid_links",onSelect:s,"aria-label":t("menu.cleanInvalidLinks"),disabled:n,children:t("menu.cleanInvalidLinks")})};Sm.displayName="CleanInvalidLinks";const bm=()=>{const{language:e,setLanguage:t,t:n}=Ee(),i=f.useContext(ra);return l.jsx(Be,{icon:l.jsx($f,{}),"data-testid":"language-switcher-button",onSelect:()=>{},submenu:l.jsxs(_n,{onSelect:()=>{var r;const s=new CustomEvent(Zl.MENU_ITEM_SELECT,{bubbles:!0,cancelable:!0});(r=i.onSelect)==null||r.call(i,s)},children:[l.jsx(Be,{onSelect:()=>{t("zh")},"aria-label":n("language.chinese"),selected:e==="zh",children:n("language.chinese")}),l.jsx(Be,{onSelect:()=>{t("en")},"aria-label":n("language.english"),selected:e==="en",children:n("language.english")})]}),"aria-label":n("language.switcher"),children:n("language.switcher")})};bm.displayName="LanguageSwitcherMenu";const ur=()=>l.jsx("div",{style:{height:"1px",backgroundColor:"var(--color-gray-10)",margin:".5rem 0"}});ur.displayName="MenuSeparator";const Al=({children:e,buttonId:t,isVisible:n,visibleIndex:i=-1,disabled:s=!1})=>{const{t:r}=Ee(),{hideButton:o,showButton:a,resetToDefault:c,visibleButtons:u,reorderButton:d}=Fo(),[h,p]=f.useState(!1),[g,m]=f.useState({x:0,y:0}),b=f.useRef(null),S=f.useRef(null);f.useEffect(()=>{const j=S.current;if(!j)return;const L=D=>{D.button===2&&D.stopPropagation()};return j.addEventListener("pointerdown",L,!0),()=>{j.removeEventListener("pointerdown",L,!0)}},[]);const w=f.useCallback(j=>{s||(j.preventDefault(),j.stopPropagation(),m({x:j.clientX,y:j.clientY}),p(!0))},[s]),y=f.useCallback(()=>{p(!1)},[]),T=f.useCallback(()=>{n?o(t):a(t),y()},[n,t,o,a,y]),C=f.useCallback(()=>{i>0&&d(i,i-1,!0),y()},[i,d,y]),E=f.useCallback(()=>{i>=0&&i<u.length-1&&d(i,i+1,!0),y()},[i,u.length,d,y]),v=f.useCallback(()=>{i>0&&d(i,0,!0),y()},[i,d,y]),x=f.useCallback(()=>{i>=0&&i<u.length-1&&d(i,u.length-1,!0),y()},[i,u.length,d,y]),O=f.useCallback(()=>{c(),y()},[c,y]);f.useEffect(()=>{if(!h)return;const j=D=>{b.current&&!b.current.contains(D.target)&&y()},L=D=>{D.key==="Escape"&&y()};return document.addEventListener("mousedown",j),document.addEventListener("keydown",L),()=>{document.removeEventListener("mousedown",j),document.removeEventListener("keydown",L)}},[h,y]),f.useEffect(()=>{if(!h||!b.current)return;const L=b.current.getBoundingClientRect(),D=window.innerWidth,k=window.innerHeight;let N=g.x,M=g.y;g.x+L.width>D&&(N=D-L.width-8),g.y+L.height>k&&(M=k-L.height-8),(N!==g.x||M!==g.y)&&m({x:N,y:M})},[h,g]);const B=n&&i>0,X=n&&i>=0&&i<u.length-1;return l.jsxs(l.Fragment,{children:[l.jsx("div",{ref:S,onContextMenu:w,children:e}),h&&Lo.createPortal(l.jsx("div",{ref:b,className:"toolbar-context-menu",style:{position:"fixed",left:g.x,top:g.y,zIndex:Jt.DROPDOWN_PORTAL},children:l.jsxs(_n,{children:[n&&l.jsxs(l.Fragment,{children:[l.jsx(Be,{onSelect:C,disabled:!B,children:r("toolbar.moveUp")}),l.jsx(Be,{onSelect:E,disabled:!X,children:r("toolbar.moveDown")}),l.jsx(Be,{onSelect:v,disabled:!B,children:r("toolbar.moveToTop")}),l.jsx(Be,{onSelect:x,disabled:!X,children:r("toolbar.moveToBottom")}),l.jsx(ur,{})]}),l.jsx(Be,{onSelect:T,children:r(n?"toolbar.rightClickToHide":"toolbar.doubleClickToShow")}),l.jsx(ur,{}),l.jsx(Be,{onSelect:O,children:r("toolbar.resetToDefault")})]})}),document.body)]})},UP=({embedded:e=!1,iconMode:t=!1,onOpenBackupRestore:n,onOpenCloudSync:i})=>{const s=bt(),{t:r}=Ee(),{isButtonVisible:o,visibleButtons:a}=Fo(),c=z.getBoardContainer(s),[u,d]=f.useState(!1),h=s.history.undos.length<=0,p=s.history.redos.length<=0,g=o("undo"),m=o("redo"),b=a.findIndex(y=>y.id==="undo"),S=a.findIndex(y=>y.id==="redo"),w=l.jsxs(pt.Row,{gap:1,children:[l.jsxs(at,{sideOffset:12,open:u,onOpenChange:y=>{d(y)},placement:e?"right-start":"bottom-start",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{type:"icon",visible:!0,selected:u,icon:l.jsx($f,{}),tooltip:u?void 0:r("general.menu"),tooltipPlacement:e?"right":"bottom","aria-label":r("general.menu"),"data-track":"toolbar_click_menu",onPointerDown:()=>{d(!u)}})}),l.jsx(ct,{container:c,style:{zIndex:Jt.POPOVER_APP},children:l.jsxs(_n,{onSelect:()=>{d(!1)},onClose:()=>{d(!1)},children:[l.jsx(am,{}),l.jsx(om,{}),l.jsx(lm,{}),l.jsx(cm,{}),l.jsx(Sm,{}),l.jsx(ur,{}),l.jsx(bm,{}),l.jsx(um,{onOpenBackupRestore:()=>{d(!1),n==null||n()}}),l.jsx(hm,{}),l.jsx(dm,{onOpenCloudSync:()=>{d(!1),i==null||i()}}),l.jsx(fm,{}),l.jsx(ur,{}),l.jsx(pm,{}),l.jsx(gm,{}),l.jsx(mm,{})]})})]},0),g&&l.jsx(Al,{buttonId:"undo",isVisible:!0,visibleIndex:b,children:l.jsx(ne,{type:"icon",icon:l.jsx(Xf,{}),visible:!0,tooltip:r("general.undo"),tooltipPlacement:e?"right":"bottom","aria-label":r("general.undo"),"data-track":"toolbar_click_undo",onPointerUp:()=>{s.undo()},disabled:h},1)}),m&&l.jsx(Al,{buttonId:"redo",isVisible:!0,visibleIndex:S,children:l.jsx(ne,{type:"icon",icon:l.jsx(Kf,{}),visible:!0,tooltip:r("general.redo"),tooltipPlacement:e?"right":"bottom","aria-label":r("general.redo"),"data-track":"toolbar_click_redo",onPointerUp:()=>{s.redo()},disabled:p},2)})]});return e?l.jsxs("div",{className:q("app-toolbar",{"app-toolbar--embedded":e,"app-toolbar--icon-only":t}),children:[w,l.jsx(ne,{type:"icon",icon:l.jsx(zb,{}),visible:!0,tooltip:r("menu.github"),tooltipPlacement:"right","aria-label":r("menu.github"),"data-track":"toolbar_click_github",onPointerUp:()=>{window.open("https://github.com/ljquan/aitu","_blank")}})]}):l.jsx(qe,{padding:1,className:q("app-toolbar",Dt,{"app-toolbar--embedded":e,"app-toolbar--icon-only":t}),children:w})};function WP(e,t){return!e||e===Jn.solid?null:e===Jn.dashed?`${t*3},${t*2}`:e===Jn.dotted?`${t},${t*2}`:null}function hi(e){return e!==void 0&&!isNaN(e[0])&&!isNaN(e[1])&&isFinite(e[0])&&isFinite(e[1])}class $P extends Yf{constructor(t){super(t)}canDraw(t){return t.anchors&&t.anchors.length>0}draw(t){const n=Ql();n.classList.add("pen-path");const i=qf(t),s=t.cornerRadius||0,r=Zf(i,t.closed,s),o=t.strokeWidth||2,a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("d",r),a.setAttribute("fill",Vb(t.fill)),a.setAttribute("stroke",t.strokeColor||"#000000"),a.setAttribute("stroke-width",String(o)),a.setAttribute("stroke-linecap","round"),a.setAttribute("stroke-linejoin","round");const c=WP(t.strokeStyle,o);return c&&a.setAttribute("stroke-dasharray",c),n.appendChild(a),n}}function XP(e,t){const n=e.point,i=Wb;if(e.type==="corner"){const s=document.createElementNS("http://www.w3.org/2000/svg","rect");return s.setAttribute("x",String(n[0]-i/2)),s.setAttribute("y",String(n[1]-i/2)),s.setAttribute("width",String(i)),s.setAttribute("height",String(i)),s.setAttribute("fill",t?"#1890ff":"#ffffff"),s.setAttribute("stroke","#1890ff"),s.setAttribute("stroke-width","1.5"),s.classList.add("pen-anchor"),s}else{const s=document.createElementNS("http://www.w3.org/2000/svg","circle");return s.setAttribute("cx",String(n[0])),s.setAttribute("cy",String(n[1])),s.setAttribute("r",String(i/2)),s.setAttribute("fill",t?"#1890ff":"#ffffff"),s.setAttribute("stroke","#1890ff"),s.setAttribute("stroke-width","1.5"),s.classList.add("pen-anchor"),s}}function Ah(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(Ub/2)),t.setAttribute("fill","#ffffff"),t.setAttribute("stroke","#1890ff"),t.setAttribute("stroke-width","1"),t.classList.add("pen-handle"),t}function Mh(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 KP(e,t,n){const i="#ff4d4f";if(n.vertical&&n.verticalRefPoint){const r=n.verticalRefPoint,o=document.createElementNS("http://www.w3.org/2000/svg","line");o.setAttribute("x1",String(t[0])),o.setAttribute("y1",String(Math.min(t[1],r[1])-50)),o.setAttribute("x2",String(t[0])),o.setAttribute("y2",String(Math.max(t[1],r[1])+50)),o.setAttribute("stroke",i),o.setAttribute("stroke-width",String(1)),o.setAttribute("stroke-dasharray","4,4"),o.classList.add("pen-alignment-guide"),e.appendChild(o);const a=document.createElementNS("http://www.w3.org/2000/svg","circle");a.setAttribute("cx",String(r[0])),a.setAttribute("cy",String(r[1])),a.setAttribute("r","3"),a.setAttribute("fill",i),a.setAttribute("opacity","0.6"),a.classList.add("pen-alignment-marker"),e.appendChild(a)}if(n.horizontal&&n.horizontalRefPoint){const r=n.horizontalRefPoint,o=document.createElementNS("http://www.w3.org/2000/svg","line");if(o.setAttribute("x1",String(Math.min(t[0],r[0])-50)),o.setAttribute("y1",String(t[1])),o.setAttribute("x2",String(Math.max(t[0],r[0])+50)),o.setAttribute("y2",String(t[1])),o.setAttribute("stroke",i),o.setAttribute("stroke-width",String(1)),o.setAttribute("stroke-dasharray","4,4"),o.classList.add("pen-alignment-guide"),e.appendChild(o),!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(r[0])),a.setAttribute("cy",String(r[1])),a.setAttribute("r","3"),a.setAttribute("fill",i),a.setAttribute("opacity","0.6"),a.classList.add("pen-alignment-marker"),e.appendChild(a)}}}function YP(e,t,n="#1890ff",i=2,s){const r=Ql();if(r.classList.add("pen-preview"),e.length===0)return r;if(t&&hi(t)&&s&&(s.horizontal||s.vertical)&&KP(r,t,s),e.length>0){const o=Zf(e,!1),a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("d",o),a.setAttribute("fill","none"),a.setAttribute("stroke",n),a.setAttribute("stroke-width",String(i)),a.setAttribute("stroke-linecap","round"),a.setAttribute("stroke-linejoin","round"),r.appendChild(a)}if(t&&hi(t)&&e.length>0){const o=e[e.length-1];if(hi(o.point)){const a=document.createElementNS("http://www.w3.org/2000/svg","line"),c=o.handleOut&&hi(o.handleOut)?o.handleOut:o.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"),r.appendChild(a)}}for(let o=0;o<e.length;o++){const a=e[o];if(!hi(a.point))continue;if(a.handleIn&&hi(a.handleIn)){const u=Mh(a.point,a.handleIn);r.appendChild(u);const d=Ah(a.handleIn);r.appendChild(d)}if(a.handleOut&&hi(a.handleOut)){const u=Mh(a.point,a.handleOut);r.appendChild(u);const d=Ah(a.handleOut);r.appendChild(d)}const c=XP(a,o===e.length-1);r.appendChild(c)}return r}const qP=3,ZP=3,Ih=8,Ml=new WeakMap;function qn(e){let t=Ml.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}},Ml.set(e,t)),t}function Dh(e,t,n=!1){const i={horizontal:!1,vertical:!1,horizontalRefPoint:null,verticalRefPoint:null,referencePoint:null},s=[...e],r=n&&t.length>1?t.slice(0,-1):t;if(r.length===0)return{snappedPoint:e,alignment:i};let o=Ih,a=null,c=null,u=Ih,d=null,h=null;for(const p of r){const g=Math.abs(e[0]-p.point[0]),m=Math.abs(e[1]-p.point[1]);g<o&&(o=g,a=p.point[0],c=p.point),m<u&&(u=m,d=p.point[1],h=p.point)}return a!==null&&(s[0]=a,i.vertical=!0,i.verticalRefPoint=c),d!==null&&(s[1]=d,i.horizontal=!0,i.horizontalRefPoint=h),i.referencePoint=i.verticalRefPoint||i.horizontalRefPoint,{snappedPoint:s,alignment:i}}function ss(e){const t=qn(e);t.previewG&&t.previewG.remove(),ym(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 ym(e){z.getElementHost(e).querySelectorAll(".pen-preview").forEach(i=>i.remove())}function Ms(e){const t=qn(e),n=z.getElementHost(e);t.previewG&&t.previewG.remove(),t.previewG=YP(t.anchors,t.currentPoint,"#1890ff",2,t.alignment),n.appendChild(t.previewG)}function bo(e,t=!1){const n=qn(e),i=[...n.anchors];if(n.previewG&&(n.previewG.remove(),n.previewG=null),ym(e),i.length>=2){const s=$b(e,i,t);n.isCreating=!1,n.anchors=[],n.isDraggingHandle=!1,n.dragStartPoint=null,n.currentPoint=null,ue.insertNode(e,s,[e.children.length]),t?(ii(e),Pi(e,s)):ii(e)}else ss(e)}function Fs(e){return z.getPointer(e)===Bn.pen}function QP(e){const t=qn(e);t.isCreating&&(Fs(e)||(t.anchors.length>=2?bo(e,!1):ss(e)))}const JP=e=>{const{pointerDown:t,pointerMove:n,pointerUp:i,globalPointerUp:s,keyDown:r,globalKeyDown:o}=e,a=u=>u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLElement&&u.isContentEditable,c=u=>{if(u.defaultPrevented||!Fs(e)||a(u.target))return!1;const d=qn(e);return d.isCreating?u.key==="Enter"?(bo(e,!1),u.preventDefault(),!0):u.key==="Escape"?(ss(e),u.preventDefault(),!0):tt.isHotkey(["mod+z"],{byKey:!0})(u)||u.key==="Backspace"||u.key==="Delete"?(d.anchors.length>0&&(d.anchors.pop(),Ms(e)),d.anchors.length===0&&ss(e),u.preventDefault(),!0):!1:!1};return e.pointerDown=u=>{if(QP(e),!Fs(e)){t(u);return}const d=qn(e);let h=Gt(e,zt(e,u.x,u.y));if(d.isCreating&&d.anchors.length>=ZP){const b={anchors:d.anchors};if(Xb(b,h)){bo(e,!0);return}}if(d.anchors.length>0){const{snappedPoint:b}=Dh(h,d.anchors,!1);h=b}d.isCreating=!0,d.isDraggingHandle=!0,d.dragStartPoint=h;const g=Ja(e).defaultAnchorType,m={point:h,type:g};d.anchors.push(m),d.alignment={horizontal:!1,vertical:!1,horizontalRefPoint:null,verticalRefPoint:null,referencePoint:null},Ms(e)},e.pointerMove=u=>{if(!Fs(e)){n(u);return}const d=qn(e);let h=Gt(e,zt(e,u.x,u.y));const p=d.isDraggingHandle,{snappedPoint:g,alignment:m}=Dh(h,d.anchors,p);if(d.currentPoint=g,d.alignment=m,d.isDraggingHandle&&d.dragStartPoint&&d.anchors.length>0&&Kb(d.dragStartPoint,h)>qP){const S=d.anchors.length-1,w=d.anchors[S];if(w.type!=="corner"){if(w.type==="smooth"||w.type==="symmetric"){const y=Yb(w.point,h);d.anchors[S]={...w,handleIn:y.handleIn,handleOut:y.handleOut}}}}d.isCreating&&Jl(e,"pen-preview",()=>{Ms(e)}),n(u)},e.pointerUp=u=>{if(!Fs(e)){i(u);return}const d=qn(e);d.isDraggingHandle=!1,d.dragStartPoint=null,Ms(e),i(u)},e.globalPointerUp=u=>{s(u)},e.globalKeyDown=u=>{c(u)||o(u)},e.keyDown=u=>{c(u)||r(u)},e};function Cn(e){const t=Ml.get(e);t!=null&&t.isCreating&&(t.anchors.length>=2?bo(e,!1):ss(e))}const Rc=[{icon:l.jsx(Ss,{}),pointer:ot.feltTipPen,titleKey:"toolbar.pen"},{icon:l.jsx(qb,{}),pointer:Bn.pen,titleKey:"toolbar.vectorPen"},{icon:l.jsx(Zb,{}),pointer:ot.eraser,titleKey:"toolbar.eraser"},{icon:l.jsx(Qb,{}),pointer:ot.laserPointer,titleKey:"toolbar.laserPointer"}],ek=Qf(Rc,5),jc=({onPointerUp:e})=>{const{t}=Ee(),n=bt();return l.jsx(qe,{padding:1,children:l.jsx(pt.Row,{gap:1,align:"center",children:l.jsx(pt.Row,{gap:1,children:ek.map((i,s)=>i.map((r,o)=>l.jsx(ne,{className:q({fillable:!1}),selected:n.pointer===r.pointer,type:"icon",size:"small",visible:!0,icon:r.icon,tooltip:t(r.titleKey),"aria-label":t(r.titleKey),onPointerDown:()=>{r.pointer!==Bn.pen&&Cn(n),ht(n,Et.dnd),fe.updatePointerType(n,r.pointer)},onPointerUp:()=>{ht(n,Et.drawing),e(r.pointer)}},`${s}-${o}`)))})})})},tk=[{icon:l.jsx(Jf,{}),title:"Rectangle — R",pointer:Pe.rectangle},{icon:l.jsx(ep,{}),title:"Ellipse — O",pointer:Pe.ellipse},{icon:l.jsx(tp,{}),title:"Triangle",pointer:Pe.triangle},{icon:l.jsx(np,{}),title:"Terminal",pointer:ec.terminal},{icon:l.jsx(ip,{}),title:"Diamond",pointer:Pe.diamond},{icon:l.jsx(sp,{}),title:"Parallelogram",pointer:Pe.parallelogram},{icon:l.jsx(rp,{}),title:"RoundRectangle",pointer:Pe.roundRectangle}],nk=Qf(tk,5),Lc=({onPointerUp:e})=>{const t=bt();return l.jsx(qe,{padding:1,children:l.jsx(pt.Col,{gap:1,children:nk.map((n,i)=>l.jsx(pt.Row,{gap:1,children:n.map((s,r)=>l.jsx(ne,{className:q({fillable:!1}),type:"icon",size:"small",visible:!0,icon:s.icon,tooltip:s.title,"aria-label":s.title,onPointerDown:()=>{Cn(t),ht(t,Et.dnd),fe.updatePointerType(t,s.pointer)},onPointerUp:()=>{ht(t,Et.drawing),e(s.pointer)}},r))},i))})})},ik=[{icon:l.jsx(Jb,{}),title:"Straight Arrow Line",pointer:En.straight},{icon:l.jsx(ey,{}),title:"Elbow Arrow Line",pointer:En.elbow},{icon:l.jsx(ty,{}),title:"Curve Arrow Line",pointer:En.curve}],Oc=({onPointerUp:e})=>{const t=bt();return l.jsx(qe,{padding:1,children:l.jsx(pt.Row,{gap:1,children:ik.map((n,i)=>l.jsx(ne,{className:q({fillable:!1}),type:"icon",size:"small",visible:!0,icon:n.icon,tooltip:n.title,"aria-label":n.title,onPointerDown:()=>{Cn(t),ht(t,Et.drawing),fe.updatePointerType(t,n.pointer)},onPointerUp:()=>{e(n.pointer)}},i))})})},wm=[{value:pi.default,labelKey:"theme.default"},{value:pi.colorful,labelKey:"theme.colorful"},{value:pi.soft,labelKey:"theme.soft"},{value:pi.retro,labelKey:"theme.retro"},{value:pi.dark,labelKey:"theme.dark"},{value:pi.starry,labelKey:"theme.starry"}],Tm=l.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:l.jsx("polyline",{points:"20 6 9 17 4 12"})}),Jr=e=>e===vt.hand||e===vt.selection||e===tr,vm=l.jsx("span",{style:{width:"1rem",display:"inline-block"}}),Nh={hand:{icon:l.jsx(fp,{}),titleKey:"toolbar.hand",pointer:vt.hand},selection:{icon:l.jsx(hp,{}),titleKey:"toolbar.selection",pointer:vt.selection},lasso:{icon:l.jsx(dp,{}),titleKey:"toolbar.lasso",pointer:tr},mind:{icon:l.jsx(ro,{}),titleKey:"toolbar.mind",pointer:ki.mind},text:{icon:l.jsx(rc,{}),titleKey:"toolbar.text",pointer:Pe.text},freehand:{icon:l.jsx(Ss,{}),titleKey:"toolbar.pen",pointer:ot.feltTipPen,hasPopup:!0,popupKey:"freehand"},arrow:{icon:l.jsx(sc,{}),titleKey:"toolbar.arrow",pointer:En.straight,hasPopup:!0,popupKey:"arrow"},shape:{icon:l.jsx(ic,{}),titleKey:"toolbar.shape",pointer:Pe.rectangle,hasPopup:!0,popupKey:"shape"},image:{icon:l.jsx(jo,{size:24}),titleKey:"toolbar.image"},"media-library":{icon:l.jsx(Ro,{size:24}),titleKey:"toolbar.mediaLibrary"},"ai-image":{icon:l.jsx(Oo,{}),titleKey:"toolbar.aiImage"},"ai-video":{icon:l.jsx(Bo,{}),titleKey:"toolbar.aiVideo"},theme:{icon:l.jsx(up,{}),titleKey:"toolbar.theme",hasPopup:!0,popupKey:"theme"},"mermaid-to-drawnix":{icon:l.jsx(cp,{}),titleKey:"extraTools.mermaidToDrawnix"},"markdown-to-drawnix":{icon:l.jsx(lp,{}),titleKey:"extraTools.markdownToDrawnix"},undo:{icon:l.jsx(Xf,{}),titleKey:"general.undo"},redo:{icon:l.jsx(Kf,{}),titleKey:"general.redo"}},sk=({embedded:e=!1})=>{const{t}=Ee(),n=bt(),i=z.getBoardContainer(n),{hiddenButtons:s,showButton:r}=Fo(),[o,a]=f.useState(!1),[c,u]=f.useState(!1),d=f.useRef(null),h=f.useRef(null),p=f.useCallback(()=>{d.current&&(clearTimeout(d.current),d.current=null),h.current&&(clearTimeout(h.current),h.current=null)},[]),g=f.useCallback(()=>"ontouchstart"in window||navigator.maxTouchPoints>0,[]),m=f.useCallback(()=>{g()||(p(),u(!0),d.current=setTimeout(()=>{a(!0)},200))},[p,g]),b=f.useCallback(()=>{g()||(d.current&&(clearTimeout(d.current),d.current=null),h.current=setTimeout(()=>{u(!1),a(!1)},150))},[g]),S=f.useCallback(()=>{g()&&(a(T=>!T),u(!1))},[g]),w=f.useCallback(()=>{p(),u(!0)},[p]),y=f.useCallback(()=>{h.current=setTimeout(()=>{u(!1),a(!1)},150)},[]);return l.jsxs(at,{open:o,onOpenChange:T=>{!T&&(g()||!c)&&a(!1)},placement:e?"right-start":"bottom",sideOffset:12,children:[l.jsx(lt,{asChild:!0,children:l.jsx("div",{onMouseEnter:m,onMouseLeave:b,onClick:S,children:l.jsx(ne,{type:"icon",icon:l.jsx(ny,{}),tooltip:o?void 0:t("toolbar.more"),tooltipPlacement:e?"right":"bottom","aria-label":t("toolbar.more"),selected:o,visible:!0,"data-testid":"toolbar-more","data-track":"toolbar_click_more"})})}),l.jsx(ct,{container:i,style:{zIndex:Jt.POPOVER},onMouseEnter:w,onMouseLeave:y,children:l.jsx(rk,{hiddenButtons:s,showButton:r})})]})},rk=({hiddenButtons:e,showButton:t})=>{const{t:n}=Ee(),i=bt(),s=z.getBoardContainer(i),{openDialog:r}=Ut(),o=tc(),[a,c]=f.useState(null),[u,d]=f.useState(null),h=f.useRef({}),[p,g]=f.useState(null),m=f.useRef(null),[b,S]=f.useState(ot.feltTipPen),w=f.useCallback(()=>{c(null),d(null),Object.values(h.current).forEach(R=>{R&&clearTimeout(R)})},[]),y=f.useCallback(R=>{if(Object.values(h.current).forEach(W=>{W&&clearTimeout(W)}),u===R){d(null);return}a===R&&!u?c(null):(d(null),c(R))},[a,u]),T=f.useCallback(R=>{a&&!u||(h.current[R]&&clearTimeout(h.current[R]),Object.entries(h.current).forEach(([W,ce])=>{W!==R&&ce&&(clearTimeout(ce),h.current[W]=null)}),u&&u!==R?(c(R),d(R)):a||(h.current[R]=setTimeout(()=>{c(R),d(R)},300)))},[u,a]),C=f.useCallback(R=>{h.current[R]&&(clearTimeout(h.current[R]),h.current[R]=null),u===R&&(h.current[R]=setTimeout(()=>{c(null),d(null)},400))},[u]),E=f.useCallback(R=>{h.current[R]&&(clearTimeout(h.current[R]),h.current[R]=null)},[]),v=f.useCallback(R=>{u===R&&(c(null),d(null))},[u]),x=f.useCallback(R=>{Cn(i),R===Pe.text?ht(i,null):ht(i,Et.dnd),fe.updatePointerType(i,R),o(R)},[i,o]),O=f.useCallback(R=>{R!==Pe.text&&ht(i,Et.drawing)},[i]),B=f.useCallback(R=>{const W=Nh[R];if(W){if(W.hasPopup&&W.popupKey){y(W.popupKey);return}switch(w(),Cn(i),W.pointer&&(Jr(W.pointer)?(fe.updatePointerType(i,W.pointer),o(W.pointer)):(x(W.pointer),O(W.pointer))),R){case"image":Go(i);break;case"ai-image":r(ln.aiImageGeneration);break;case"ai-video":r(ln.aiVideoGeneration);break;case"mermaid-to-drawnix":r(ln.mermaidToDrawnix);break;case"markdown-to-drawnix":r(ln.markdownToDrawnix);break;case"undo":i.undo();break;case"redo":i.redo();break}}},[i,r,x,O,w,o,y]),X=f.useCallback((R,W)=>{R.preventDefault(),R.stopPropagation(),g({buttonId:W,x:R.clientX,y:R.clientY})},[]),j=f.useCallback(()=>{g(null)},[]),L=f.useCallback(()=>{p&&(t(p.buttonId),j())},[p,t,j]);Gn.useEffect(()=>{if(!p)return;const R=ce=>{m.current&&!m.current.contains(ce.target)&&j()},W=ce=>{ce.key==="Escape"&&j()};return document.addEventListener("mousedown",R),document.addEventListener("keydown",W),()=>{document.removeEventListener("mousedown",R),document.removeEventListener("keydown",W)}},[p,j]);const D=f.useCallback(R=>{switch(R){case"freehand":return l.jsx(jc,{onPointerUp:W=>{w(),o(W),S(W)}});case"shape":return l.jsx(Lc,{onPointerUp:W=>{w(),o(W)}});case"arrow":return l.jsx(Oc,{onPointerUp:W=>{w(),o(W)}});case"theme":return l.jsx(_n,{children:wm.map(W=>{const ce=i.theme.themeColorMode===W.value;return l.jsx(Be,{icon:ce?Tm:vm,"data-track":`toolbar_click_theme_${W.value}`,onSelect:()=>{fe.updateThemeColor(i,W.value),w()},"aria-label":n(W.labelKey),selected:ce,children:n(W.labelKey)},W.value)})});default:return null}},[i,w,o,n]),k=f.useMemo(()=>{const R=Rc.find(W=>W.pointer===b);return(R==null?void 0:R.icon)||l.jsx(Ss,{})},[b]),[N,M]=f.useState(!1),Z=f.useCallback(()=>{var R;return l.jsx("div",{className:"more-tools-panel__zoom-row",onContextMenu:W=>X(W,"zoom"),children:l.jsxs(pt.Row,{gap:1,children:[l.jsx(ne,{type:"button",icon:l.jsx(op,{}),visible:!0,tooltip:n("zoom.out"),tooltipPlacement:"top","aria-label":n("zoom.out"),"data-track":"toolbar_click_zoom_out",onPointerUp:()=>{fe.updateZoom(i,i.viewport.zoom-.1)},className:"zoom-out-button"}),l.jsxs(at,{sideOffset:12,open:N,onOpenChange:W=>{M(W)},placement:"right-start",children:[l.jsx(Ct,{content:n("zoom.fit"),showArrow:!1,children:l.jsx(lt,{asChild:!0,children:l.jsxs("div",{"aria-label":n("zoom.fit"),"data-track":"toolbar_click_zoom_menu",className:`zoom-menu-trigger ${N?"active":""}`,onPointerUp:()=>{M(!N)},children:[Number(((((R=i==null?void 0:i.viewport)==null?void 0:R.zoom)||1)*100).toFixed(0)),"%"]})})}),l.jsx(ct,{container:s,style:{zIndex:Jt.POPOVER+1},children:l.jsxs(_n,{onSelect:()=>{M(!1)},children:[l.jsx(Be,{"data-track":"toolbar_click_zoom_fit",onSelect:()=>{fe.fitViewport(i)},"aria-label":n("zoom.fit"),shortcut:"Cmd+Shift+=",children:n("zoom.fit")}),l.jsx(Be,{"data-track":"toolbar_click_zoom_fit_frame",onSelect:()=>{nc(i)},"aria-label":n("zoom.fitFrame"),children:n("zoom.fitFrame")}),l.jsx(Be,{"data-track":"toolbar_click_zoom_100",onSelect:()=>{fe.updateZoom(i,1)},"aria-label":n("zoom.100"),shortcut:"Cmd+0",children:n("zoom.100")})]})})]}),l.jsx(ne,{type:"button",icon:l.jsx(ap,{}),visible:!0,tooltip:n("zoom.in"),tooltipPlacement:"top","aria-label":n("zoom.in"),"data-track":"toolbar_click_zoom_in",onPointerUp:()=>{fe.updateZoom(i,i.viewport.zoom+.1)},className:"zoom-in-button"})]})},"zoom")},[i,s,X,n,N]),he=f.useCallback(R=>{var Te,ze,Y,Ie;if(R==="zoom")return Z();const W=Nh[R];if(!W)return null;const ce=n(W.titleKey),K=R==="freehand"?k:W.icon,ae=R==="undo"&&(((ze=(Te=i.history)==null?void 0:Te.undos)==null?void 0:ze.length)??0)<=0,le=R==="redo"&&(((Ie=(Y=i.history)==null?void 0:Y.redos)==null?void 0:Ie.length)??0)<=0,me=ae||le;if(W.hasPopup&&W.popupKey){const $e=W.popupKey;return l.jsx("div",{className:"more-tools-panel__item",onContextMenu:it=>X(it,R),children:l.jsxs(at,{open:a===$e,sideOffset:2,onOpenChange:it=>{it||w()},placement:"right-start",children:[l.jsx(lt,{asChild:!0,children:l.jsx("div",{onMouseEnter:()=>T($e),onMouseLeave:()=>C($e),children:l.jsx(ne,{type:"icon",icon:K,tooltip:ce,tooltipPlacement:"left","aria-label":ce,visible:!0,selected:a===$e,"data-track":`toolbar_click_${R}`,onPointerUp:()=>B(R)})})}),l.jsx(ct,{container:s,style:{zIndex:Jt.POPOVER+1},onMouseEnter:()=>E($e),onMouseLeave:()=>v($e),children:D($e)})]})},R)}return l.jsx("div",{className:"more-tools-panel__item",onContextMenu:$e=>X($e,R),children:l.jsx(ne,{type:"icon",icon:K,tooltip:ce,tooltipPlacement:"right","aria-label":ce,visible:!0,selected:!1,disabled:me,"data-track":`toolbar_click_${R}`,onPointerUp:()=>B(R)})},R)},[n,i,s,a,k,B,X,T,C,E,v,D,w,Z]);return e.length===0?l.jsxs("div",{className:"more-tools-panel",children:[l.jsx("div",{className:"more-tools-panel__header",children:l.jsx("span",{className:"more-tools-panel__title",children:n("toolbar.moreTools")})}),l.jsx("div",{className:"more-tools-panel__empty",children:l.jsx("span",{className:"more-tools-panel__empty-text",children:n("toolbar.allToolsVisible")})})]}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"more-tools-panel",children:[l.jsx("div",{className:"more-tools-panel__header",children:l.jsx("span",{className:"more-tools-panel__title",children:n("toolbar.moreTools")})}),l.jsx("div",{className:"more-tools-panel__content",children:e.map(R=>he(R.id))}),l.jsx("div",{className:"more-tools-panel__footer",children:l.jsx("span",{className:"more-tools-panel__hint",children:n("toolbar.rightClickToAdd")})})]}),p&&Lo.createPortal(l.jsx("div",{ref:m,className:"toolbar-context-menu",style:{position:"fixed",left:p.x,top:p.y,zIndex:Jt.DROPDOWN_PORTAL},children:l.jsx(_n,{children:l.jsx(Be,{onSelect:L,children:n("toolbar.addToToolbar")})})}),document.body)]})},ok=f.lazy(()=>Ne(()=>import("./tool-windows-C4D0lII2.js").then(e=>e.p0),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.MediaLibraryModal}))),ak=f.lazy(()=>Ne(()=>import("./tool-windows-C4D0lII2.js").then(e=>e.p2),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.MinimizedToolsBar})));var xm=(e=>(e.shape="shape",e.arrow="arrow",e.freehand="freehand",e.theme="theme",e))(xm||{});const Rh=[{icon:l.jsx(fp,{}),pointer:vt.hand,titleKey:"toolbar.hand",visibilityKey:"hand"},{icon:l.jsx(hp,{}),pointer:vt.selection,titleKey:"toolbar.selection",visibilityKey:"selection"},{icon:l.jsx(dp,{}),pointer:tr,titleKey:"toolbar.lasso",visibilityKey:"lasso"},{icon:l.jsx(ro,{}),pointer:ki.mind,titleKey:"toolbar.mind",visibilityKey:"mind"},{icon:l.jsx(rc,{}),pointer:Pe.text,titleKey:"toolbar.text",visibilityKey:"text"},{icon:l.jsx(jo,{size:24}),titleKey:"toolbar.image",key:"image",visibilityKey:"image"},{icon:l.jsx(Ro,{size:24}),titleKey:"toolbar.mediaLibrary",key:"media-library",visibilityKey:"media-library"},{icon:l.jsx(Oo,{}),titleKey:"toolbar.aiImage",key:"ai-image",visibilityKey:"ai-image"},{icon:l.jsx(Bo,{}),titleKey:"toolbar.aiVideo",key:"ai-video",visibilityKey:"ai-video"},{icon:l.jsx(ro,{}),pointer:ki.mind,titleKey:"toolbar.mind",visibilityKey:"mind"},{icon:l.jsx(Ss,{}),pointer:ot.feltTipPen,titleKey:"toolbar.pen",key:"freehand",visibilityKey:"freehand"},{icon:l.jsx(sc,{}),titleKey:"toolbar.arrow",key:"arrow",pointer:En.straight,visibilityKey:"arrow"},{icon:l.jsx(ic,{}),titleKey:"toolbar.shape",key:"shape",pointer:Pe.rectangle,visibilityKey:"shape"},{icon:l.jsx(up,{}),titleKey:"toolbar.theme",key:"theme",visibilityKey:"theme"},{icon:l.jsx(cp,{}),titleKey:"extraTools.mermaidToDrawnix",key:"mermaid-to-drawnix",visibilityKey:"mermaid-to-drawnix"},{icon:l.jsx(lp,{}),titleKey:"extraTools.markdownToDrawnix",key:"markdown-to-drawnix",visibilityKey:"markdown-to-drawnix"}],lk=e=>Object.keys(En).includes(e.pointer),ck=e=>Object.keys(Pe).includes(e.pointer)||Object.keys(ec).includes(e.pointer),uk=({embedded:e=!1,iconMode:t=!1,onOpenMediaLibrary:n,minimizedToolsBarEnabled:i=!1,onEnableToolWindows:s})=>{const r=bt(),{appState:o,openDialog:a}=Ut(),{t:c}=Ee(),u=tc(),d=z.getBoardContainer(r),{visibleButtons:h,loading:p,reorderButton:g}=Fo(),{getDragProps:m}=iy({items:h,getId:P=>P.id,onReorder:(P,A)=>{g(P,A,!0)},enabled:e}),[b,S]=f.useState({freehand:!1,arrow:!1,shape:!1,theme:!1}),[w,y]=f.useState(null),T=f.useRef({freehand:null,arrow:null,shape:null,theme:null}),[C,E]=f.useState(Rh.find(P=>P.key==="freehand")),[v,x]=f.useState(!1),O=f.useCallback(async P=>{try{P.type===Nn.IMAGE?await ql(r,P.url):P.type===Nn.VIDEO?await pp(r,P.url):P.type===Nn.AUDIO&&await Gl(r,P.url,{title:P.name,duration:P.duration,previewImageUrl:P.thumbnail,prompt:P.prompt,mv:P.modelName,clipId:P.clipId,providerTaskId:P.providerTaskId}),oe.success("素材已插入到画板")}catch(A){console.error("Failed to insert asset:",A),oe.error("插入素材失败")}},[r]),B=f.useCallback(()=>{if(n){n({mode:ni.SELECT,onSelect:O,selectButtonText:"插入"});return}x(!0)},[O,n]),X=f.useCallback(()=>{x(!1)},[]),j=()=>{S({freehand:!1,arrow:!1,shape:!1,theme:!1}),y(null),Object.values(T.current).forEach(P=>{P&&clearTimeout(P)})},L=P=>{y(null),Object.values(T.current).forEach(A=>{A&&clearTimeout(A)}),S({freehand:!1,arrow:!1,shape:!1,theme:!1,[P]:!0})},D=P=>{T.current[P]&&clearTimeout(T.current[P]),Object.entries(T.current).forEach(([A,$])=>{A!==P&&$&&(clearTimeout($),T.current[A]=null)}),w&&w!==P?(S(A=>({...A,[w]:!1,[P]:!0})),y(P)):b[P]||(T.current[P]=setTimeout(()=>{S(A=>({...A,[P]:!0})),y(P)},300))},k=P=>{T.current[P]&&(clearTimeout(T.current[P]),T.current[P]=null),w===P&&(T.current[P]=setTimeout(()=>{S(A=>({...A,[P]:!1})),y(null)},200))},N=P=>{T.current[P]&&(clearTimeout(T.current[P]),T.current[P]=null)},M=P=>{w===P&&(S(A=>({...A,[P]:!1})),y(null))},Z=P=>{Cn(r),P===Pe.text?(ht(r,null),fe.updatePointerType(r,P),u(P)):(ht(r,Et.dnd),fe.updatePointerType(r,P),u(P))},he=P=>{P!==Pe.text&&ht(r,Et.drawing)},R=()=>Object.values(b).some(P=>P),W=P=>z.isPointer(r,P.pointer)&&!R(),ce=P=>z.isInPointer(P,[ot.feltTipPen,ot.eraser,ot.laserPointer,Bn.pen]),K=P=>{j(),Cn(r),P.pointer&&!Jr(P.pointer)?he(P.pointer):P.pointer&&Jr(P.pointer)&&(fe.updatePointerType(r,P.pointer),u(P.pointer)),P.key==="image"?Go(r):P.key==="media-library"?B():P.key==="ai-image"?a(ln.aiImageGeneration):P.key==="ai-video"?a(ln.aiVideoGeneration):P.key==="mermaid-to-drawnix"?a(ln.mermaidToDrawnix):P.key==="markdown-to-drawnix"&&a(ln.markdownToDrawnix)},ae=(P,A,$)=>{const Q=()=>{switch($){case"freehand":return l.jsx(jc,{onPointerUp:U=>{j(),u(U),E(Rc.find(te=>te.pointer===U))}});case"shape":return l.jsx(Lc,{onPointerUp:U=>{j(),u(U)}});case"arrow":return l.jsx(Oc,{onPointerUp:U=>{j(),u(U)}});case"theme":return l.jsx(_n,{children:wm.map(U=>{const te=r.theme.themeColorMode===U.value;return l.jsx(Be,{icon:te?Tm:vm,"data-track":`toolbar_click_theme_${U.value}`,onSelect:()=>{fe.updateThemeColor(r,U.value),j()},"aria-label":c(U.labelKey),selected:te,children:c(U.labelKey)},U.value)})})}},I=()=>{const U=b[$],te=Object.entries(b).some(([ee,G])=>ee!==$&&G);switch($){case"freehand":return U||ce(r)&&!te;case"shape":return U||ck(r)&&!z.isPointer(r,Pe.text);case"arrow":return U||lk(r);default:return U}},H=$==="freehand"?C.icon:P.icon,F=$==="freehand"?C.titleKey?c(C.titleKey):"Freehand":P.titleKey?c(P.titleKey):"";return l.jsxs(at,{open:b[$],sideOffset:12,onOpenChange:U=>{U||j()},placement:e?"right-start":"bottom",children:[l.jsx(lt,{asChild:!0,children:l.jsx("div",{onMouseEnter:()=>D($),onMouseLeave:()=>k($),children:l.jsx(ne,{type:"icon",visible:!0,selected:I(),icon:H,tooltip:F,"aria-label":F,"data-track":`toolbar_click_${$}`,onPointerDown:()=>{L($),$==="freehand"&&C.pointer&&Z(C.pointer)},onPointerUp:()=>{$==="freehand"&&he()}})})}),l.jsx(ct,{container:d,style:{zIndex:Jt.POPOVER},onMouseEnter:()=>N($),onMouseLeave:()=>M($),children:Q()})]},A)},le=(P,A)=>l.jsx(ne,{type:"radio",icon:P.icon,checked:W(P),tooltip:P.titleKey?c(P.titleKey):"",tooltipPlacement:e?"right":"bottom","aria-label":P.titleKey?c(P.titleKey):"","data-track":`toolbar_click_${P.pointer||P.key}`,onPointerDown:()=>{P.pointer&&!Jr(P.pointer)&&Z(P.pointer)},onPointerUp:()=>{K(P)}},A),me=f.useMemo(()=>{const P=new Map;return Rh.forEach(A=>{A.visibilityKey&&P.set(A.visibilityKey,A)}),P},[]),[Te,ze]=f.useState(!1),Y=f.useCallback(P=>{var $;const A=e?pt.Col:pt.Row;return l.jsx("div",{className:q("creation-toolbar__zoom-inline",{"creation-toolbar__zoom-inline--vertical":e}),children:l.jsxs(A,{gap:0,children:[l.jsx(ne,{type:"button",icon:l.jsx(op,{}),visible:!0,tooltip:c("zoom.out"),tooltipPlacement:e?"right":"bottom","aria-label":c("zoom.out"),"data-track":"toolbar_click_zoom_out",onPointerUp:()=>{fe.updateZoom(r,r.viewport.zoom-.1)},className:"zoom-out-button"}),l.jsxs(at,{sideOffset:12,open:Te,onOpenChange:Q=>{ze(Q)},placement:e?"right-start":"bottom",children:[l.jsx(Ct,{content:c("zoom.fit"),showArrow:!1,children:l.jsx(lt,{asChild:!0,children:l.jsxs("div",{"aria-label":c("zoom.fit"),"data-track":"toolbar_click_zoom_menu",className:q("zoom-menu-trigger",{active:Te}),onPointerUp:()=>{ze(!Te)},children:[Number((((($=r==null?void 0:r.viewport)==null?void 0:$.zoom)||1)*100).toFixed(0)),"%"]})})}),l.jsx(ct,{container:d,style:{zIndex:Jt.POPOVER},children:l.jsxs(_n,{onSelect:()=>{ze(!1)},children:[l.jsx(Be,{"data-track":"toolbar_click_zoom_fit",onSelect:()=>{fe.fitViewport(r)},"aria-label":c("zoom.fit"),shortcut:"Cmd+Shift+=",children:c("zoom.fit")}),l.jsx(Be,{"data-track":"toolbar_click_zoom_fit_frame",onSelect:()=>{nc(r)},"aria-label":c("zoom.fitFrame"),children:c("zoom.fitFrame")}),l.jsx(Be,{"data-track":"toolbar_click_zoom_100",onSelect:()=>{fe.updateZoom(r,1)},"aria-label":c("zoom.100"),shortcut:"Cmd+0",children:c("zoom.100")})]})})]}),l.jsx(ne,{type:"button",icon:l.jsx(ap,{}),visible:!0,tooltip:c("zoom.in"),tooltipPlacement:e?"right":"bottom","aria-label":c("zoom.in"),"data-track":"toolbar_click_zoom_in",onPointerUp:()=>{fe.updateZoom(r,r.viewport.zoom+.1)},className:"zoom-in-button"})]})},`zoom-${P}`)},[r,d,e,c,Te]),Ie=f.useCallback((P,A)=>{if(P==="zoom")return Y(A);const $=me.get(P);return!$||o.isMobile&&$.pointer===vt.hand?null:$.key&&Object.values(xm).includes($.key)?ae($,A,$.key):le($,A)},[me,o.isMobile,ae,le,Y]),$e=f.useCallback((P,A,$=!0,Q=-1)=>{const I=Ie(P,A);if(!I)return null;const H=m(P,A);return l.jsx(Al,{buttonId:P,isVisible:$,visibleIndex:Q,children:l.jsx("div",{className:q("toolbar-button-wrapper",{"toolbar-button-wrapper--dragging":H["data-dragging"],"toolbar-button-wrapper--drag-over":H["data-drag-over"],"toolbar-button-wrapper--drag-before":H["data-drag-position"]==="before","toolbar-button-wrapper--drag-after":H["data-drag-position"]==="after"}),"data-button-id":P,...H,children:I})},`ctx-${P}-${A}`)},[Ie,m]),it=l.jsxs(pt.Row,{gap:1,children:[!p&&h.map((P,A)=>e?$e(P.id,A,!0,A):Ie(P.id,A)),l.jsx(sk,{embedded:e}),e&&i&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(ak,{ensureToolWindowsEnabled:s})})]}),Ye=v?l.jsx(f.Suspense,{fallback:null,children:l.jsx(ok,{isOpen:v,onClose:X,mode:ni.SELECT,onSelect:O,selectButtonText:"插入"})}):null;return e?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:q("draw-toolbar",{"draw-toolbar--embedded":e,"draw-toolbar--icon-only":t}),children:it}),Ye]}):l.jsxs(l.Fragment,{children:[l.jsx(qe,{padding:1,className:q("draw-toolbar",Dt,{"draw-toolbar--embedded":e,"draw-toolbar--icon-only":t}),children:it}),Ye]})},jh="https://tuziai.oss-cn-shenzhen.aliyuncs.com/aitu/AiTu.png",dk="https://tuziai.oss-cn-shenzhen.aliyuncs.com/linkme.png",hk=()=>{const e=bt(),t=z.getBoardContainer(e),[n,i]=f.useState(!1);return f.useEffect(()=>{const s=new Image;s.src=jh;const r=new Image;r.src=dk},[]),l.jsxs(at,{placement:"right-end",sideOffset:12,open:n,onOpenChange:i,children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{type:"icon",icon:l.jsx(sy,{}),"aria-label":"用户反馈群",title:"用户反馈群",tooltipPlacement:"right",selected:n,visible:!0,"data-track":"toolbar_click_feedback",onPointerDown:s=>{s.event.stopPropagation()},onClick:()=>i(!n)})}),l.jsx(ct,{container:t,style:{zIndex:Jt.POPOVER_FEEDBACK},children:l.jsx("div",{className:"feedback-qrcode-content",children:l.jsx("div",{className:"feedback-qrcode-grid",children:l.jsxs("div",{className:"feedback-qrcode-item",children:[l.jsx("img",{src:jh,alt:"用户反馈群二维码",className:"feedback-qrcode-image"}),l.jsx("div",{className:"feedback-qrcode-text",children:"用户反馈群"})]})})})})]})},fk=({projectDrawerOpen:e,onProjectDrawerToggle:t,toolboxDrawerOpen:n=!1,onToolboxDrawerToggle:i,taskPanelExpanded:s,onTaskPanelToggle:r})=>{const{activeTasks:o,completedTasks:a,failedTasks:c}=ry(),d=o.length+a.length+c.length>0?`任务队列 (生成中: ${o.length}, 已完成: ${a.length}, 失败: ${c.length})`:"任务队列 (暂无任务)";return l.jsxs("div",{className:"bottom-actions-section",children:[l.jsx(hk,{}),l.jsx(ne,{type:"icon",icon:l.jsx(oy,{}),"aria-label":e?"关闭项目":"打开项目",tooltip:e?"关闭项目":"打开项目",tooltipPlacement:"right",selected:e,visible:!0,"data-track":"toolbar_click_project_drawer","data-testid":"toolbar-project",onPointerDown:h=>{h.event.stopPropagation()},onClick:t}),i&&l.jsx(ne,{type:"icon",icon:l.jsx(ay,{}),"aria-label":n?"关闭工具箱":"打开工具箱",tooltip:n?"关闭工具箱":"打开工具箱",tooltipPlacement:"right",selected:n,visible:!0,"data-track":"toolbar_click_toolbox","data-testid":"toolbar-toolbox",onPointerDown:h=>{h.event.stopPropagation()},onClick:i}),l.jsxs("div",{className:"bottom-actions-section__task-wrapper",children:[l.jsx(ly,{count:o.length>0?o.length:0,showZero:!1,offset:[6,-6],children:l.jsx(ne,{type:"icon",icon:l.jsx(cy,{}),"aria-label":"任务队列",tooltip:d,tooltipPlacement:"right",selected:s,visible:!0,"data-track":"toolbar_click_tasks","data-testid":"toolbar-tasks",onPointerDown:h=>{h.event.stopPropagation()},onClick:r})}),o.length>0&&l.jsx("div",{className:"bottom-actions-section__status bottom-actions-section__status--active"}),c.length>0&&o.length===0&&l.jsx("div",{className:"bottom-actions-section__status bottom-actions-section__status--failed"})]})]})},pk=f.lazy(()=>Ne(()=>import("./TaskQueuePanel-D6NtMAbm.js"),__vite__mapDeps([0,2,3]),import.meta.url).then(e=>({default:e.TaskQueuePanel}))),gk=460,mk=["ai-image","ai-video"],Sk=Gn.memo(({className:e,projectDrawerOpen:t=!1,onProjectDrawerToggle:n,toolboxDrawerOpen:i=!1,onToolboxDrawerToggle:s,taskPanelExpanded:r=!1,onTaskPanelToggle:o,onOpenBackupRestore:a,onOpenCloudSync:c,onOpenMediaLibrary:u,deferredFeaturesEnabled:d=!1,minimizedToolsBarEnabled:h=!1,onEnableToolWindows:p})=>{const[g,m]=f.useState(!1),[b,S]=f.useState(!0),w=f.useRef(!1),y=f.useRef(null),T=f.useRef(null),C=f.useRef(!1),{isMobile:E,isTablet:v}=uy(),x=E||v;zo(y,{enablePositionTracking:!0,enableScaleCompensation:!0});const O=f.useCallback(N=>{if(N[0]){const M=N[0].contentRect.height;m(M<gk)}},[]);f.useEffect(()=>{const N=y.current;if(!N)return;const M=new ResizeObserver(O);return M.observe(N),()=>{M.disconnect()}},[O]),f.useEffect(()=>{if(C.current)return;const N=T.current;if(!N)return;const M=()=>{C.current=!0;let he=null;for(const K of mk){const ae=N.querySelector(`[data-button-id="${K}"]`);if(ae){he=ae;break}}if(!he)return;const R=N.getBoundingClientRect(),W=he.getBoundingClientRect();if(!(W.bottom<=R.bottom&&W.top>=R.top)&&R.height>0){const K=W.top-R.top;N.scrollTop+=K}},Z=setTimeout(()=>{requestAnimationFrame(M)},100);return()=>{clearTimeout(Z)}},[]);const B=f.useCallback(()=>{!r&&!w.current&&(w.current=!0),o==null||o()},[r,o]),X=f.useCallback(()=>{r&&(o==null||o())},[r,o]),j=f.useCallback(()=>{S(N=>!N)},[]),{openDialog:L}=Ut(),D=f.useCallback(()=>{L(ln.aiImageGeneration)},[L]),k=f.useCallback(()=>{L(ln.aiVideoGeneration)},[L]);return l.jsxs(l.Fragment,{children:[w.current&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(pk,{expanded:r,onClose:X})}),l.jsxs(qe,{ref:y,className:q("unified-toolbar",Dt,{"unified-toolbar--icon-only":g||x,"unified-toolbar--mobile-collapsed":x&&b},e),padding:0,"data-testid":"unified-toolbar",children:[x&&b&&l.jsxs("div",{className:"unified-toolbar__collapsed-shortcuts",children:[l.jsx("button",{className:"unified-toolbar__collapsed-btn unified-toolbar__collapsed-btn--toggle",onClick:j,"aria-label":"展开工具栏",children:l.jsx(Rf,{size:18})}),l.jsx("button",{className:"unified-toolbar__collapsed-btn",onClick:D,"aria-label":"AI 图片生成",children:l.jsx(Oo,{})}),l.jsx("button",{className:"unified-toolbar__collapsed-btn",onClick:k,"aria-label":"AI 视频生成",children:l.jsx(Bo,{})})]}),x&&!b&&l.jsx("button",{className:"unified-toolbar__mobile-toggle unified-toolbar__mobile-toggle--expanded",onClick:j,"aria-label":"收起工具栏",children:l.jsx(Ul,{size:18})}),l.jsx("div",{className:"unified-toolbar__section unified-toolbar__section--fixed-top",children:l.jsx(UP,{embedded:!0,iconMode:g||x,onOpenBackupRestore:a,onOpenCloudSync:c})}),l.jsx("div",{ref:T,className:"unified-toolbar__scrollable",children:l.jsx("div",{className:"unified-toolbar__section",children:l.jsx(uk,{embedded:!0,iconMode:g||x,onOpenMediaLibrary:u,deferredFeaturesEnabled:d,minimizedToolsBarEnabled:h,onEnableToolWindows:p})})}),l.jsx("div",{className:"unified-toolbar__section unified-toolbar__section--fixed-bottom",children:l.jsx(fk,{projectDrawerOpen:t,onProjectDrawerToggle:n||(()=>{}),toolboxDrawerOpen:i,onToolboxDrawerToggle:s,taskPanelExpanded:r,onTaskPanelToggle:B})})]})]})}),bk=e=>n=>{const{globalKeyDown:i,keyDown:s}=n;return n.globalKeyDown=r=>{const o=r.target instanceof HTMLInputElement||r.target instanceof HTMLTextAreaElement||r.target instanceof HTMLElement&&r.target.isContentEditable;if(!o){if(tt.isHotkey(["mod+k"])(r)){e({openCommandPalette:!0}),r.preventDefault();return}if(tt.isHotkey(["mod+f"])(r)){e({openCanvasSearch:!0}),r.preventDefault();return}}if(!o&&(z.getMovingPointInBoard(n)||z.isMovingPointInBoard(n))&&!z.hasBeenTextEditing(n)){if(tt.isHotkey(["mod+shift+e"],{byKey:!0})(r)){zr(n,!0),r.preventDefault();return}if(tt.isHotkey(["mod+s"],{byKey:!0})(r)){Wf(n),r.preventDefault();return}if(tt.isHotkey(["mod+backspace"])(r)||tt.isHotkey(["mod+delete"])(r)){e({openCleanConfirm:!0}),r.preventDefault();return}if(tt.isHotkey(["mod+u"])(r)&&Go(n),He(n).length>1){if(tt.isHotkey(["alt+a"])(r)){on.alignLeft(n),r.preventDefault();return}if(tt.isHotkey(["alt+h"])(r)){on.alignCenter(n),r.preventDefault();return}if(tt.isHotkey(["alt+d"])(r)){on.alignRight(n),r.preventDefault();return}if(tt.isHotkey(["alt+w"])(r)){on.alignTop(n),r.preventDefault();return}if(tt.isHotkey(["alt+v"])(r)){on.alignMiddle(n),r.preventDefault();return}if(tt.isHotkey(["alt+s"])(r)){on.alignBottom(n),r.preventDefault();return}if(tt.isHotkey(["shift+h"])(r)){ts.distributeHorizontal(n),r.preventDefault();return}if(tt.isHotkey(["shift+v"])(r)){ts.distributeVertical(n),r.preventDefault();return}if(tt.isHotkey(["shift+a"])(r)){ts.autoArrange(n),r.preventDefault();return}if(tt.isHotkey(["alt+shift+u"])(r)){Tn.union(n,"zh"),r.preventDefault();return}if(tt.isHotkey(["alt+shift+s"])(r)){Tn.subtract(n,"zh"),r.preventDefault();return}if(tt.isHotkey(["alt+shift+i"])(r)){Tn.intersect(n,"zh"),r.preventDefault();return}if(tt.isHotkey(["alt+shift+e"])(r)){Tn.exclude(n,"zh"),r.preventDefault();return}if(tt.isHotkey(["alt+shift+f"])(r)){Tn.flatten(n,"zh"),r.preventDefault();return}}if(!r.altKey&&!r.metaKey&&!r.ctrlKey&&tt.isHotkey(["shift+p"],{byKey:!0})(r)){ht(n,Et.drawing),fe.updatePointerType(n,Bn.pen),e({pointer:Bn.pen}),r.preventDefault();return}if(!r.altKey&&!r.metaKey&&!r.ctrlKey&&!r.shiftKey){if(r.key==="l"){ht(n,Et.drawing),fe.updatePointerType(n,ot.laserPointer),e({pointer:ot.laserPointer}),r.preventDefault();return}if(r.key==="Escape"&&z.isPointer(n,ot.laserPointer)){fe.updatePointerType(n,vt.selection),e({pointer:vt.selection}),r.preventDefault();return}if(r.key==="h"&&(fe.updatePointerType(n,vt.hand),e({pointer:vt.hand})),r.key==="v"&&(fe.updatePointerType(n,vt.selection),e({pointer:vt.selection})),r.key==="q"&&(fe.updatePointerType(n,tr),e({pointer:tr})),r.key==="m"&&(ht(n,Et.dnd),fe.updatePointerType(n,ki.mind),e({pointer:ki.mind})),r.key==="e"&&(ht(n,Et.drawing),fe.updatePointerType(n,ot.eraser),e({pointer:ot.eraser})),r.key==="p"&&(ht(n,Et.drawing),fe.updatePointerType(n,ot.feltTipPen),e({pointer:ot.feltTipPen})),r.key==="a"&&!tt.isHotkey(["mod+a"])(r)&&He(n).length===0&&(ht(n,Et.drawing),fe.updatePointerType(n,En.straight),e({pointer:En.straight})),r.key==="f"&&(ht(n,Et.drawing),fe.updatePointerType(n,xu),e({pointer:xu})),r.key==="r"||r.key==="o"||r.key==="t"){const c={r:Pe.rectangle,o:Pe.ellipse,t:Pe.text};c[r.key]===Pe.text?ht(n,null):ht(n,Et.drawing),fe.updatePointerType(n,c[r.key]),e({pointer:c[r.key]})}r.preventDefault();return}}i(r)},n.keyDown=r=>{if(tt.isHotkey(["mod+z"],{byKey:!0})(r)){n.undo(),r.preventDefault();return}if(tt.isHotkey(["mod+shift+z"],{byKey:!0})(r)){n.redo(),r.preventDefault();return}s(r)},n};function Bc(e){return e===Bt.square?"square":"round"}function Hc(e,t){const n=Math.min(t/50,1),i=.2+n*.1,s=6-n*4,r=i+e*(s-i);return Math.max(.5,t*r)}function yk(e,t,n,i,s,r){const o=document.createElementNS("http://www.w3.org/2000/svg","g"),a=Bc(r);if(e.length<2){if(e.length===1){const p=Hc(t[0]??.5,n);if(r===Bt.square){const g=document.createElementNS("http://www.w3.org/2000/svg","rect");g.setAttribute("x",String(e[0][0]-p/2)),g.setAttribute("y",String(e[0][1]-p/2)),g.setAttribute("width",String(p)),g.setAttribute("height",String(p)),g.setAttribute("fill",i),o.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(p/2)),g.setAttribute("fill",i),o.appendChild(g)}}return o}const c=oc(e,1,3);if(s===yn.double){const p=n*.8,g=n*.4,[m,b]=Tk(c,t,g,p);if(m){const S=document.createElementNS("http://www.w3.org/2000/svg","path");S.setAttribute("d",m),S.setAttribute("fill",i),S.setAttribute("stroke","none"),o.appendChild(S)}if(b){const S=document.createElementNS("http://www.w3.org/2000/svg","path");S.setAttribute("d",b),S.setAttribute("fill",i),S.setAttribute("stroke","none"),o.appendChild(S)}return o}const u=gp(s,n),d=s!==Jn.solid&&u?u.join(" "):"",h=vk(c,t,n);if(h.length>0){const p=document.createElementNS("http://www.w3.org/2000/svg","path");p.setAttribute("d",h),p.setAttribute("fill",i),p.setAttribute("stroke","none"),d&&(p.setAttribute("fill","none"),p.setAttribute("stroke",i),p.setAttribute("stroke-width",String(n)),p.setAttribute("stroke-dasharray",d),p.setAttribute("stroke-linecap",a),p.setAttribute("stroke-linejoin",a==="square"?"miter":"round")),o.appendChild(p)}return o}function wk(e,t,n,i){const s=document.createElementNS("http://www.w3.org/2000/svg","g"),r=Bc(i);if(e.length<2){if(e.length===1){const b=t*.8,S=t*.4;if(i===Bt.square){const w=document.createElementNS("http://www.w3.org/2000/svg","rect");w.setAttribute("x",String(e[0][0]-S/2)),w.setAttribute("y",String(e[0][1]-b/2-S/2)),w.setAttribute("width",String(S)),w.setAttribute("height",String(S)),w.setAttribute("fill",n),s.appendChild(w);const y=document.createElementNS("http://www.w3.org/2000/svg","rect");y.setAttribute("x",String(e[0][0]-S/2)),y.setAttribute("y",String(e[0][1]+b/2-S/2)),y.setAttribute("width",String(S)),y.setAttribute("height",String(S)),y.setAttribute("fill",n),s.appendChild(y)}else{const w=document.createElementNS("http://www.w3.org/2000/svg","circle");w.setAttribute("cx",String(e[0][0])),w.setAttribute("cy",String(e[0][1]-b/2)),w.setAttribute("r",String(S/2)),w.setAttribute("fill",n),s.appendChild(w);const y=document.createElementNS("http://www.w3.org/2000/svg","circle");y.setAttribute("cx",String(e[0][0])),y.setAttribute("cy",String(e[0][1]+b/2)),y.setAttribute("r",String(S/2)),y.setAttribute("fill",n),s.appendChild(y)}}return s}const o=oc(e,1,3),a=t*.8,c=t*.4,u=[],d=[];for(let b=0;b<o.length;b++){let S,w;b===0?(S=o[1][0]-o[0][0],w=o[1][1]-o[0][1]):b===o.length-1?(S=o[b][0]-o[b-1][0],w=o[b][1]-o[b-1][1]):(S=o[b+1][0]-o[b-1][0],w=o[b+1][1]-o[b-1][1]);const y=Math.sqrt(S*S+w*w);if(y>0){const T=-w/y,C=S/y,E=a/2;u.push([o[b][0]+T*E,o[b][1]+C*E]),d.push([o[b][0]-T*E,o[b][1]-C*E])}else u.push(o[b]),d.push(o[b])}const h=document.createElementNS("http://www.w3.org/2000/svg","path");let p=`M ${u[0][0]} ${u[0][1]}`;for(let b=1;b<u.length;b++){const S=u[b-1],w=u[b],y=(S[0]+w[0])/2,T=(S[1]+w[1])/2;p+=` Q ${S[0]} ${S[1]} ${y} ${T}`}p+=` L ${u[u.length-1][0]} ${u[u.length-1][1]}`,h.setAttribute("d",p),h.setAttribute("fill","none"),h.setAttribute("stroke",n),h.setAttribute("stroke-width",String(c)),h.setAttribute("stroke-linecap",r),h.setAttribute("stroke-linejoin",r==="square"?"miter":"round"),s.appendChild(h);const g=document.createElementNS("http://www.w3.org/2000/svg","path");let m=`M ${d[0][0]} ${d[0][1]}`;for(let b=1;b<d.length;b++){const S=d[b-1],w=d[b],y=(S[0]+w[0])/2,T=(S[1]+w[1])/2;m+=` Q ${S[0]} ${S[1]} ${y} ${T}`}return m+=` L ${d[d.length-1][0]} ${d[d.length-1][1]}`,g.setAttribute("d",m),g.setAttribute("fill","none"),g.setAttribute("stroke",n),g.setAttribute("stroke-width",String(c)),g.setAttribute("stroke-linecap",r),g.setAttribute("stroke-linejoin",r==="square"?"miter":"round"),s.appendChild(g),s}function Tk(e,t,n,i){if(e.length<2)return["",""];const s=[],r=[];for(let c=0;c<e.length;c++){let u,d;c===0?(u=e[1][0]-e[0][0],d=e[1][1]-e[0][1]):c===e.length-1?(u=e[c][0]-e[c-1][0],d=e[c][1]-e[c-1][1]):(u=e[c+1][0]-e[c-1][0],d=e[c+1][1]-e[c-1][1]);const h=Math.sqrt(u*u+d*d);if(h>0){const p=-d/h,g=u/h,m=i/2;s.push([e[c][0]+p*m,e[c][1]+g*m]),r.push([e[c][0]-p*m,e[c][1]-g*m])}else s.push(e[c]),r.push(e[c])}const o=Lh(s,t,n),a=Lh(r,t,n);return[o,a]}function Lh(e,t,n){if(e.length<2)return"";const i=[],s=[];for(let o=0;o<e.length;o++){const a=t[o]??.5,u=Hc(a,n)/2;let d,h;o===0?(d=e[1][0]-e[0][0],h=e[1][1]-e[0][1]):o===e.length-1?(d=e[o][0]-e[o-1][0],h=e[o][1]-e[o-1][1]):(d=e[o+1][0]-e[o-1][0],h=e[o+1][1]-e[o-1][1]);const p=Math.sqrt(d*d+h*h);if(p>0){const g=-h/p,m=d/p;i.push([e[o][0]+g*u,e[o][1]+m*u]),s.push([e[o][0]-g*u,e[o][1]-m*u])}else i.push(e[o]),s.push(e[o])}let r=`M ${i[0][0]} ${i[0][1]}`;for(let o=1;o<i.length;o++){const a=i[o-1],c=i[o],u=(a[0]+c[0])/2,d=(a[1]+c[1])/2;r+=` Q ${a[0]} ${a[1]} ${u} ${d}`}r+=` L ${i[i.length-1][0]} ${i[i.length-1][1]}`,r+=` L ${s[s.length-1][0]} ${s[s.length-1][1]}`;for(let o=s.length-2;o>=0;o--){const a=s[o+1],c=s[o],u=(a[0]+c[0])/2,d=(a[1]+c[1])/2;r+=` Q ${a[0]} ${a[1]} ${u} ${d}`}return r+=` L ${s[0][0]} ${s[0][1]}`,r+=" Z",r}function vk(e,t,n){if(e.length<2)return"";const i=[],s=[];for(let o=0;o<e.length;o++){const a=t[o]??.5,u=Hc(a,n)/2;let d,h;o===0?(d=e[1][0]-e[0][0],h=e[1][1]-e[0][1]):o===e.length-1?(d=e[o][0]-e[o-1][0],h=e[o][1]-e[o-1][1]):(d=e[o+1][0]-e[o-1][0],h=e[o+1][1]-e[o-1][1]);const p=Math.sqrt(d*d+h*h);if(p>0){const g=-h/p,m=d/p;i.push([e[o][0]+g*u,e[o][1]+m*u]),s.push([e[o][0]-g*u,e[o][1]-m*u])}else i.push(e[o]),s.push(e[o])}let r=`M ${i[0][0]} ${i[0][1]}`;for(let o=1;o<i.length;o++){const a=i[o-1],c=i[o],u=(a[0]+c[0])/2,d=(a[1]+c[1])/2;r+=` Q ${a[0]} ${a[1]} ${u} ${d}`}r+=` L ${i[i.length-1][0]} ${i[i.length-1][1]}`,r+=` L ${s[s.length-1][0]} ${s[s.length-1][1]}`;for(let o=s.length-2;o>=0;o--){const a=s[o+1],c=s[o],u=(a[0]+c[0])/2,d=(a[1]+c[1])/2;r+=` Q ${a[0]} ${a[1]} ${u} ${d}`}return r+=` L ${s[0][0]} ${s[0][1]}`,r+=" Z",r}class Fc extends Yf{draw(t){const n=dy(t),i=Uf(this.board,t),s=hy(this.board,t),r=fy(this.board,t),o=gp(r,n),a=t.brushShape,c=Bc(a);if(t.pressures&&t.pressures.length>0)return yk(t.points,t.pressures,n,i,r,a);if(r===yn.double)return wk(t.points,n,i,a);const u={strokeWidth:n,stroke:i,fill:s,fillStyle:"solid",strokeLineDash:r!==Jn.solid?o:void 0},d=z.getRoughSVG(this.board).curve(oc(t.points,1,3),u);return py(d,c),d}canDraw(t){return!0}}class xk extends ac{constructor(){super()}initializeGenerator(){this.activeGenerator=mp(this.board,{getRectangle:t=>Vo(t),getStrokeWidth:()=>Sp,getStrokeOpacity:()=>1,hasResizeHandle:()=>bp(this.board,this.element)}),this.generator=new Fc(this.board)}initialize(){super.initialize(),this.initializeGenerator(),this.generator.processDrawing(this.element,this.getElementG())}onContextChanged(t,n){const i=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,z.getActiveHost(this.board),{selected:this.selected})):i&&t.selected?this.activeGenerator.processDrawing(this.element,z.getActiveHost(this.board),{selected:this.selected}):(t.selected!==n.selected||t.selected)&&this.activeGenerator.processDrawing(this.element,z.getActiveHost(this.board),{selected:this.selected})}destroy(){var t;super.destroy(),(t=this.activeGenerator)==null||t.destroy()}}class Em{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 i=n.timestamp??Date.now();if(this.points.length===0){const c={point:t,timestamp:i,...n};return this.points.push(c),this.lastProcessedTime=i,t}if(i-this.lastProcessedTime<this.options.samplingRate&&i-this.lastProcessedTime<2)return null;const s={point:t,timestamp:i,...n};if(!this.checkDistance(t)&&this.points.length>1&&i-this.lastProcessedTime<32)return null;this.updatePoints(s);const o=this.calculateDynamicParameters(s),a=this.smooth(t,o);return this.lastProcessedTime=i,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,i=this.getDistance(n,t);let s=this.options.minDistance;if(this.movingAverageVelocity.length>0){const r=this.getAverageVelocity();s*=Math.max(.5,Math.min(1.5,r/200))}return i>=s}calculateDynamicParameters(t){const n=this.calculateVelocity(t);this.updateMovingAverage(n);const i=this.getAverageVelocity(),s={...this.options};if(t.pressure!==void 0){const o=Math.pow(t.pressure,1.2);s.smoothing*=1-o*s.pressureSensitivity*.8}const r=Math.min(i/s.velocityThreshold,1);if(s.velocityWeight=.2+r*.3,s.smoothing*=1+r*.2,t.tiltX!==void 0&&t.tiltY!==void 0){const o=Math.sqrt(t.tiltX**2+t.tiltY**2)/90;s.smoothing*=1+o*s.tiltSensitivity*.7}return s}smooth(t,n){if(this.points.length<2)return t;const i=this.calculateWeights(n),s=i.reduce((o,a)=>o+a,0);if(s===0)return t;const r=[0,0];for(let o=0;o<this.points.length;o++){const a=i[o]/s;r[0]+=this.points[o].point[0]*a,r[1]+=this.points[o].point[1]*a}return r}calculateWeights(t){const n=[],i=this.points.length-1;for(let s=0;s<this.points.length;s++){let r=Math.pow(t.smoothing,(i-s)*.8);if(s<i){const o=this.getPointVelocity(s);r*=1+o*t.velocityWeight*.8}if(s>0&&s<i){const o=this.getPointCurvature(s);r*=1+o*t.curvatureWeight*.7}n.push(r)}return n}getDistance(t,n){return io(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],i=this.getDistance(n.point,t.point),s=t.timestamp-n.timestamp;return s>0?i/s: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],i=this.points[t+1],s=this.getDistance(n.point,i.point),r=i.timestamp-n.timestamp;return r>0?s/r:0}getPointCurvature(t){if(t<=0||t>=this.points.length-1)return 0;const n=this.points[t-1].point,i=this.points[t].point,s=this.points[t+1].point,r=this.getDistance(n,i),o=this.getDistance(i,s),a=this.getDistance(n,s),c=(r+o+a)/2;return 4*Math.sqrt(Math.max(0,c*(c-r)*(c-o)*(c-a)))/(r*o*a+1e-4)}}const Ek=e=>{const{pointerDown:t,pointerMove:n,pointerUp:i,globalPointerUp:s}=e;let r=!1,o=!1,a=[],c=[],u=null;const d=new Fc(e),h=new Em({smoothing:.7,pressureSensitivity:.6});let p=null,g=null,m=null,b=0;const S=(T=!1)=>{if(!g||T){const C=si(e);g={strokeWidth:C.strokeWidth,strokeColor:C.strokeColor,strokeStyle:C.strokeStyle,pencilShape:C.pencilShape,pressureEnabled:C.pressureEnabled}}return g},w=(T,C)=>{if(!C)return 1;if(T.pointerType==="pen"&&T.pressure>0&&T.pressure!==.5)return T.pressure;const v=[T.x,T.y],x=performance.now();if(m&&b>0){const O=v[0]-m[0],B=v[1]-m[1],X=Math.sqrt(O*O+B*B),j=x-b;if(j>0){const L=X/j,D=.2,k=1,M=Math.min(L/1.5,1),Z=k-M*(k-D);return m=v,b=x,Z}}return m=v,b=x,.6},y=T=>{if(r){const C=z.getPointer(e);o&&(a.push(a[0]),c.length>0&&c.push(c[0]));const E=S();p=el(C,a,{strokeWidth:E.strokeWidth,strokeColor:E.strokeColor,strokeStyle:E.strokeStyle,brushShape:E.pencilShape,pressures:E.pressureEnabled?c:void 0})}p&&!T&&ue.insertNode(e,p,[e.children.length]),d==null||d.destroy(),p=null,r=!1,a=[],c=[],m=null,b=0,g=null,h.reset()};return e.pointerDown=T=>{const C=lc();if(z.isInPointer(e,C)&&cc(e)){r=!0;const v=S(!0);u=[T.x,T.y];const x=h.process(u);if(x){const O=Gt(e,zt(e,x[0],x[1]));a.push(O),c.push(w(T,v.pressureEnabled))}}t(T)},e.pointerMove=T=>{if(r){const C=[T.x,T.y];u&&io(u[0],u[1],C[0],C[1])<8?o=!0:o=!1;const E=h.process(C);if(E){d==null||d.destroy();const v=Gt(e,zt(e,E[0],E[1]));a.push(v);const x=S();c.push(w(T,x.pressureEnabled));const O=z.getPointer(e);p=el(O,a,{strokeWidth:x.strokeWidth,strokeColor:x.strokeColor,strokeStyle:x.strokeStyle,brushShape:x.pencilShape,pressures:x.pressureEnabled?c:void 0}),d.processDrawing(p,z.getElementTopHost(e))}return}n(T)},e.pointerUp=T=>{y(),i(T)},e.globalPointerUp=T=>{y(!0),s(T)},e},_k=e=>{const t=e,{getDeletedFragment:n,buildFragment:i,insertFragment:s}=t;return t.getDeletedFragment=r=>{const o=Eu(t);return o.length&&r.push(...o),n(r)},t.buildFragment=(r,o,a,c)=>{const u=Eu(t);if(u.length){const d=yp(t,u,o?[o.x,o.y]:[0,0]);r=wp(r,{text:"",type:Tp.elements,elements:d})}return i(r,o,a,c)},t.insertFragment=(r,o,a)=>{var u;const c=(u=r==null?void 0:r.elements)==null?void 0:u.filter(d=>Xe.isFreehand(d));c&&c.length>0&&vp(t,c,o),s(r,o,a)},t};function Ck(e,t,n,i=0){const s=ge.getCenterPoint(t),r=Ni(t,ci);if(i){const o=Pk(n,s,-i);let a=r.find(c=>ge.isHit(ge.getRectangleByPoints([o,o]),c.rectangle));return a&&(a.cursorClass=Uo(a.cursorClass,i)),a}else return r.find(o=>ge.isHit(ge.getRectangleByPoints([n,n]),o.rectangle))}function Pk(e,t,n){const i=n*Math.PI/180,s=Math.cos(i),r=Math.sin(i),o=e[0]-t[0],a=e[1]-t[1];return[t[0]+o*s-a*r,t[1]+o*r+a*s]}function _m(e){const t=He(e);return t.length===1&&Xe.isFreehand(t[0])?t[0]:null}function kk(e){return _m(e)!==null}function Ak(e,t){const n=_m(e);if(!n)return null;const i=Vo(n),s=n.angle||0,r=Ck(e,i,t,s);return r?{element:n,rectangle:i,handle:r.handle,cursorClass:r.cursorClass}:null}function Mk(e,t,n){const i=n.width/t.width,s=n.height/t.height;return e.map(r=>{const o=r[0]-t.x,a=r[1]-t.y;return[n.x+o*i,n.y+a*s]})}function Ik(e,t,n){const{element:i,rectangle:s,handle:r}=t,{startPoint:o,endPoint:a}=n;if(!s)return;const c=a[0]-o[0],u=a[1]-o[1],d=bs(s,r,c,u,pr(),10),h=Mk(i.points,s,d),p=e.children.findIndex(g=>g.id===i.id);p>=0&&ue.setNode(e,{points:h},[p])}const Dk=e=>Di(e,{key:"freehand",canResize:()=>kk(e),hitTest:(t=>Ak(e,t)),onResize:(t,n)=>Ik(e,t,n)});function Nk(e){return e.type==="video"}const dr=1e3;async function Gc(){const e=await Ne(()=>import("./clipper-ByL4oIbZ.js").then(t=>t.c),__vite__mapDeps([0]),import.meta.url);return e.default||e}function hr(e){return e.map(t=>({X:Math.round(t[0]*dr),Y:Math.round(t[1]*dr)}))}function Cm(e){return e.map(t=>[t.X/dr,t.Y/dr])}async function Rk(e,t,n=_u.circle){if(e.length<2)return[];const i=await Gc(),s=hr(e),r=new i.ClipperOffset;n===_u.square?r.AddPath(s,i.JoinType.jtMiter,i.EndType.etOpenSquare):r.AddPath(s,i.JoinType.jtRound,i.EndType.etOpenRound);const o=[];return r.Execute(o,t/2*dr),o.length===0?[]:Cm(o[0])}function zc(e){const t=e.points;if(!t||t.length<3)return!1;const n=t[0],i=t[t.length-1];return Math.hypot(i[0]-n[0],i[1]-n[1])<=10}function jk(e,t=20){if(Je.isPenPath(e)){if(!e.closed)return null;const n=qf(e);return gy(n,!0,t)}if(Xe.isFreehand(e)){const n=e.points;return!n||n.length<3||!zc(e)?null:n}return V.isDrawElement(e)&&V.isShapeElement(e)?V.isImage(e)||V.isText(e)?null:Lk(e,t):null}function Lk(e,t=20){const n=e.points;if(!n||n.length<2)return[];const[i,s]=n,r=Math.min(i[0],s[0]),o=Math.min(i[1],s[1]),a=Math.abs(s[0]-i[0]),c=Math.abs(s[1]-i[1]),u=e.shape;if(u==="ellipse"||u==="circle"){const d=r+a/2,h=o+c/2,p=a/2,g=c/2,m=[],b=Math.PI*(3*(p+g)-Math.sqrt((3*p+g)*(p+3*g))),S=Math.max(180,Math.ceil(b/2));for(let w=0;w<S;w++){const y=2*Math.PI*w/S;m.push([d+p*Math.cos(y),h+g*Math.sin(y)])}return m}return[[r,o],[r+a,o],[r+a,o+c],[r,o+c]]}function Ok(e,t,n,i){if(e.length<3)throw new Error("Polygon must have at least 3 points");let s=1/0,r=1/0,o=-1/0,a=-1/0;for(const h of e)s=Math.min(s,h[0]),r=Math.min(r,h[1]),o=Math.max(o,h[0]),a=Math.max(a,h[1]);const c=[s,r],u=e.map(h=>({point:[h[0]-c[0],h[1]-c[1]],type:"corner"}));return{id:my(),type:xp,shape:Bn.pen,points:[c,[o,a]],anchors:u,closed:!0,strokeColor:t,fill:n,strokeWidth:i}}function Bk(e){let t="#333333",n="#FFFFFF",i=2;return Je.isPenPath(e)?(t=e.strokeColor||t,n=e.fill||n,i=e.strokeWidth||i):Xe.isFreehand(e)?(t=e.strokeColor||t,i=e.strokeWidth||i):V.isDrawElement(e)&&(t=e.strokeColor||t,n=e.fill||n,i=e.strokeWidth||i),{strokeColor:t,fill:n,strokeWidth:i}}async function Hk(e,t){const n=await Gc(),i=new n.Clipper,s=[];return i.AddPath(hr(e),n.PolyType.ptSubject,!0),i.AddPath(hr(t),n.PolyType.ptClip,!0),i.Execute(n.ClipType.ctIntersection,s,n.PolyFillType.pftNonZero,n.PolyFillType.pftNonZero),s.length>0}async function Fk(e,t,n){const i=jk(t);if(!i||i.length<3||!await Hk(i,n))return null;const r=await Gc(),o=new r.Clipper,a=[];if(o.AddPath(hr(i),r.PolyType.ptSubject,!0),o.AddPath(hr(n),r.PolyType.ptClip,!0),!o.Execute(r.ClipType.ctDifference,a,r.PolyFillType.pftNonZero,r.PolyFillType.pftNonZero))return null;const{strokeColor:u,fill:d,strokeWidth:h}=Bk(t),p=[];for(const y of a)if(y.length>=3){let T=0;for(let C=0;C<y.length;C++){const E=(C+1)%y.length;T+=y[C].X*y[E].Y,T-=y[E].X*y[C].Y}T=T/2,p.push({path:y,signedArea:T,absArea:Math.abs(T)})}if(p.length===0)return[];const g=[...p].sort((y,T)=>T.absArea-y.absArea),m=g[0],b=g.slice(1);let S;b.length>0?S=Gk(m.path,b.map(y=>y.path)):S=m.path;const w=Cm(S);try{return[Ok(w,u,d,h)]}catch{return[]}}function Gk(e,t){let n=[...e];for(const i of t){let s=1/0,r=0,o=0;for(let c=0;c<n.length;c++)for(let u=0;u<i.length;u++){const d=n[c].X-i[u].X,h=n[c].Y-i[u].Y,p=d*d+h*h;p<s&&(s=p,r=c,o=u)}const a=[];for(let c=0;c<=r;c++)a.push(n[c]);for(let c=0;c<i.length;c++){const u=(o+c)%i.length;a.push(i[u])}a.push(i[o]);for(let c=r;c<n.length;c++)a.push(n[c]);n=a}return n}function Pm(e){if(Xe.isFreehand(e)){const s=e.points;if(!s||s.length<2)return null;const r=ge.getRectangleByPoints(s),o=e.strokeWidth??2,a=o/2;return{x:r.x-a,y:r.y-a,width:r.width+o,height:r.height+o}}if(Je.isPenPath(e)){const s=e.points;if(!s||s.length<2)return null;const[r,o]=s;return{x:Math.min(r[0],o[0]),y:Math.min(r[1],o[1]),width:Math.abs(o[0]-r[0]),height:Math.abs(o[1]-r[1])}}const t=e.points;if(!t||t.length<2)return null;const[n,i]=t;return{x:Math.min(n[0],i[0]),y:Math.min(n[1],i[1]),width:Math.abs(i[0]-n[0]),height:Math.abs(i[1]-n[1])}}function zk(e,t,n){if(t.length<2)return[];let i=1/0,s=1/0,r=-1/0,o=-1/0;for(const c of t)i=Math.min(i,c[0]-n),s=Math.min(s,c[1]-n),r=Math.max(r,c[0]+n),o=Math.max(o,c[1]+n);const a=[];for(const c of e.children){if(!Vk(c))continue;const u=Pm(c);if(!u)continue;const{x:d,y:h,width:p,height:g}=u;d+p>=i&&d<=r&&h+g>=s&&h<=o&&a.push(c)}return a}function Vk(e){return Je.isPenPath(e)?e.closed:Xe.isFreehand(e)?zc(e):V.isDrawElement(e)?V.isImage(e)||V.isText(e)||V.isArrowLine(e)||V.isVectorLine(e)?!1:V.isShapeElement(e):!1}function Uk(e){if(Je.isPenPath(e))return e.closed?null:"openPath";if(Xe.isFreehand(e))return zc(e)?null:"openPath";if(V.isDrawElement(e)){if(V.isImage(e))return"image";if(V.isText(e))return"text";if(V.isArrowLine(e))return"arrowLine";if(V.isVectorLine(e))return"vectorLine";if(V.isShapeElement(e))return null}return"unsupported"}function Wk(e,t,n){if(t.length<2)return[];let i=1/0,s=1/0,r=-1/0,o=-1/0;for(const c of t)i=Math.min(i,c[0]-n),s=Math.min(s,c[1]-n),r=Math.max(r,c[0]+n),o=Math.max(o,c[1]+n);const a=[];for(const c of e.children){const u=Pm(c);if(!u)continue;const{x:d,y:h,width:p,height:g}=u;d+p>=i&&d<=r&&h+g>=s&&h<=o&&Uk(c)&&a.push(c)}return a}async function $k(e,t,n,i,s){if(s.length===0)return;const r=await Rk(t,n,i);if(r.length<3)return;const o=[],a=[];for(const c of s){const u=await Fk(e,c,r);u!==null&&(o.push(c),a.push(...u))}o.length>0&&tl.removeElements(e,o);for(const c of a)ue.insertNode(e,c,[e.children.length])}const Xk=e=>{const{pointerDown:t,pointerMove:n,pointerUp:i,globalPointerUp:s}=e;let r=!1;const o=new Set;let a=[];const c=h=>{const p=Gt(e,zt(e,h[0],h[1])),m=si(e).eraserWidth/2;e.children.filter(S=>Xe.isFreehand(S)).forEach(S=>{!o.has(S.id)&&Sy(e,S,p,m)&&(Qi.getElementG(S).style.opacity="0.2",o.add(S.id))})},u=()=>{if(o.size>0){const h=e.children.filter(p=>o.has(p.id));h.length>0&&tl.removeElements(e,h)}},d=async()=>{if(r){if(u(),a.length>=2){const h=si(e),p=zk(e,a,h.eraserWidth).filter(m=>!Xe.isFreehand(m));if(p.length>0)try{await $k(e,a,h.eraserWidth,h.eraserShape,p)}catch(m){console.error("Precise erase error:",m)}const g=Wk(e,a,h.eraserWidth).filter(m=>!Xe.isFreehand(m)&&!Ti(m)&&!Nk(m)&&!(V.isDrawElement(m)&&V.isImage(m)));g.length>0&&tl.removeElements(e,g)}r=!1,o.clear(),a=[]}};return e.pointerDown=h=>{if(z.isInPointer(e,[ot.eraser])&&cc(e)){r=!0,o.clear(),a=[];const g=[h.x,h.y],m=Gt(e,zt(e,g[0],g[1]));a.push(m),c(g);return}t(h)},e.pointerMove=h=>{if(r){Jl(e,"with-freehand-erase",()=>{const p=[h.x,h.y],g=Gt(e,zt(e,p[0],p[1]));a.push(g),c(p)});return}n(h)},e.pointerUp=h=>{if(r){d();return}i(h)},e.globalPointerUp=h=>{if(r){d();return}s(h)},e},Kk="#e91e63",Yk=3,Oh=2e3,qk=e=>{const{pointerDown:t,pointerMove:n,pointerUp:i,globalPointerUp:s}=e;let r=!1,o=[];const a=new Fc(e),c=new Em({smoothing:.7,pressureSensitivity:0});let u=null;const d=[],h=()=>z.isPointer(e,ot.laserPointer),p=()=>{if(!r)return;r=!1;const m=a.g;m?(a.g=void 0,g(m)):a.destroy(),u=null,o=[],c.reset()},g=m=>{m.style.transition=`opacity ${Oh}ms ease-out`,m.style.opacity="1",m.getBoundingClientRect(),m.style.opacity="0";const b=window.setTimeout(()=>{m.remove();const S=d.findIndex(w=>w.g===m);S>=0&&d.splice(S,1)},Oh);d.push({g:m,timer:b})};return e.pointerDown=m=>{if(h()&&cc(e)){r=!0;const b=[m.x,m.y],S=c.process(b);if(S){const w=Gt(e,zt(e,S[0],S[1]));o.push(w)}return}t(m)},e.pointerMove=m=>{if(r){const b=[m.x,m.y],S=c.process(b);if(S){a.destroy();const w=Gt(e,zt(e,S[0],S[1]));o.push(w),u=el(ot.laserPointer,o,{strokeWidth:Yk,strokeColor:Kk}),a.processDrawing(u,z.getElementTopHost(e))}return}n(m)},e.pointerUp=m=>{r&&p(),i(m)},e.globalPointerUp=m=>{r&&p(),s(m)},e},Zk=e=>{const{getRectangle:t,drawElement:n,isHit:i,isRectangleHit:s,getOneHitElement:r,isMovable:o,isAlign:a}=e;return e.drawElement=c=>Xe.isFreehand(c.element)?xk:n(c),e.getRectangle=c=>Xe.isFreehand(c)?Vo(c):t(c),e.isRectangleHit=(c,u)=>Xe.isFreehand(c)?by(e,c,u):s(c,u),e.isHit=(c,u,d)=>Xe.isFreehand(c)?yy(e,c,u):i(c,u,d),e.getOneHitElement=c=>c.every(d=>Xe.isFreehand(d))?Ep(e,c):r(c),e.isMovable=c=>Xe.isFreehand(c)?!0:o(c),e.isAlign=c=>Xe.isFreehand(c)?!0:a(c),e.setPluginOptions(_p,{customGeometryTypes:[wy]}),qk(Dk(Xk(_k(Ek(e)))))};class Qk extends ac{constructor(){super()}initializeGenerator(){this.activeGenerator=mp(this.board,{getRectangle:t=>Wo(t),getStrokeWidth:()=>Sp,getStrokeOpacity:()=>1,hasResizeHandle:()=>bp(this.board,this.element)}),this.generator=new $P(this.board)}initialize(){super.initialize(),this.initializeGenerator(),this.generator.processDrawing(this.element,this.getElementG()),this.selected&&this.activeGenerator.processDrawing(this.element,z.getActiveHost(this.board),{selected:this.selected})}onContextChanged(t,n){const i=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,z.getActiveHost(this.board),{selected:this.selected})):i&&t.selected?this.activeGenerator.processDrawing(this.element,z.getActiveHost(this.board),{selected:this.selected}):(t.selected!==n.selected||t.selected)&&this.activeGenerator.processDrawing(this.element,z.getActiveHost(this.board),{selected:this.selected})}destroy(){var t;super.destroy(),(t=this.activeGenerator)==null||t.destroy()}}const Jk=e=>e,eA=e=>{const t=e,{getDeletedFragment:n,buildFragment:i,insertFragment:s}=t;return t.getDeletedFragment=r=>{const o=Cu(t);return o.length&&r.push(...o),n(r)},t.buildFragment=(r,o,a,c)=>{const u=Cu(t);if(u.length){const d=yp(t,u,o?[o.x,o.y]:[0,0]);r=wp(r,{text:"",type:Tp.elements,elements:d})}return i(r,o,a,c)},t.insertFragment=(r,o,a)=>{var u;const c=(u=r==null?void 0:r.elements)==null?void 0:u.filter(d=>Je.isPenPath(d));c&&c.length>0&&vp(t,c,o),s(r,o,a)},t};function tA(e,t,n,i=0){const s=ge.getCenterPoint(t),r=Ni(t,ci);if(i){const o=nA(n,s,-i);let a=r.find(c=>ge.isHit(ge.getRectangleByPoints([o,o]),c.rectangle));return a&&(a.cursorClass=Uo(a.cursorClass,i)),a}else return r.find(o=>ge.isHit(ge.getRectangleByPoints([n,n]),o.rectangle))}function nA(e,t,n){const i=n*Math.PI/180,s=Math.cos(i),r=Math.sin(i),o=e[0]-t[0],a=e[1]-t[1];return[t[0]+o*s-a*r,t[1]+o*r+a*s]}function km(e){const t=He(e);return t.length===1&&Je.isPenPath(t[0])?t[0]:null}function iA(e){return km(e)!==null}function sA(e,t){const n=km(e);if(!n)return null;const i=Wo(n),s=n.angle||0,r=tA(e,i,t,s);return r?{element:n,rectangle:i,handle:r.handle,cursorClass:r.cursorClass}:null}function rA(e,t,n){return e.map(i=>({...i,point:[i.point[0]*t,i.point[1]*n],handleIn:i.handleIn?[i.handleIn[0]*t,i.handleIn[1]*n]:void 0,handleOut:i.handleOut?[i.handleOut[0]*t,i.handleOut[1]*n]:void 0}))}function oA(e,t,n){const{element:i,rectangle:s,handle:r}=t,{startPoint:o,endPoint:a}=n;if(!s)return;const c=a[0]-o[0],u=a[1]-o[1],d=bs(s,r,c,u,pr(),10),h=d.width/s.width,p=d.height/s.height,g=rA(i.anchors,h,p),b=[[d.x,d.y],[d.x+d.width,d.y+d.height]],S=e.children.findIndex(w=>w.id===i.id);S>=0&&ue.setNode(e,{points:b,anchors:g},[S])}const aA=e=>Di(e,{key:"pen-path",canResize:()=>iA(e),hitTest:(t=>sA(e,t)),onResize:(t,n)=>oA(e,t,n)}),lA=e=>{const{getRectangle:t,drawElement:n,isHit:i,isRectangleHit:s,getOneHitElement:r,isMovable:o,isAlign:a}=e;return e.drawElement=c=>Je.isPenPath(c.element)?Qk:n(c),e.getRectangle=c=>Je.isPenPath(c)?Wo(c):t(c),e.isRectangleHit=(c,u)=>Je.isPenPath(c)?Ty(e,c,u):s(c,u),e.isHit=(c,u,d)=>Je.isPenPath(c)?vy(e,c,u):i(c,u,d),e.getOneHitElement=c=>c.every(d=>Je.isPenPath(d))?Ep(e,c):r(c),e.isMovable=c=>Je.isPenPath(c)?!0:o(c),e.isAlign=c=>Je.isPenPath(c)?!0:a(c),e.setPluginOptions(_p,{customGeometryTypes:[xp]}),aA(eA(Jk(JP(e))))},Am=new WeakMap,Bh=e=>!!Am.get(e),Mm=(e,t)=>{Am.set(e,t)},cA=e=>n=>{const{pointerDown:i}=n;return n.pointerDown=s=>{Pu(s)&&!Bh(n)&&(Mm(n,!0),e({isPencilMode:!0})),!(Bh(n)&&!Pu(s))&&i(s)},n},uA=()=>{const e=bt(),{appState:t,setAppState:n}=Ut();return l.jsx(l.Fragment,{children:t.isPencilMode&&l.jsx("div",{className:"pencil-mode-toolbar",children:l.jsx(ne,{type:"button",visible:!0,tooltip:"X Pencil","aria-label":"Arrow",label:"Pencil X",onPointerDown:()=>{n({...t,isPencilMode:!1}),Mm(e,!1)}})})})},dA="#f5f5f5";function hA(e,t){const n=Math.max(4,Math.min(256,t)),i=n+4,s=i/2,r=n/2,o=`<svg width="${i}" height="${i}" viewBox="0 0 ${i} ${i}" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
61
61
|
<circle cx="${s}" cy="${s}" r="${r}" fill="${e}" stroke="#fff" stroke-width="1"/>
|
|
62
62
|
<circle cx="${s}" cy="${s}" r="${r}" fill="none" stroke="#333" stroke-width="0.5" stroke-opacity="0.5"/>
|
|
63
63
|
</svg>`;return`url('data:image/svg+xml;base64,${btoa(o)}') ${s} ${s}, crosshair`}function fA(e,t){const n=Math.max(4,Math.min(256,t)),i=n+4,s=i/2,r=n/2,o=`<svg width="${i}" height="${i}" viewBox="0 0 ${i} ${i}" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
64
64
|
<rect x="${s-r}" y="${s-r}" width="${n}" height="${n}" fill="${e}" stroke="#fff" stroke-width="1"/>
|
|
65
65
|
<rect x="${s-r}" y="${s-r}" width="${n}" height="${n}" fill="none" stroke="#333" stroke-width="0.5" stroke-opacity="0.5"/>
|
|
66
|
-
</svg>`;return`url('data:image/svg+xml;base64,${btoa(o)}') ${s} ${s}, crosshair`}function Hh(e,t,n=Bt.circle){return n===Bt.square?fA(e,t):hA(e,t)}function Im(e){return lc().includes(e)&&e!==ot.eraser}function Dm(e){return e===ot.eraser}function $s(e,t){var o;const n=document.querySelector(".plait-board-container"),i=n==null?void 0:n.querySelector(".board-host-svg");if(!i)return;const s=si(e),r=((o=e.viewport)==null?void 0:o.zoom)||1;if(Im(t)){const a=s.strokeWidth*r,c=Hh(s.strokeColor,a,s.pencilShape);i.style.cursor=c}else if(Dm(t)){const a=s.eraserWidth*r,c=Hh(dA,a,s.eraserShape);i.style.cursor=c}else t===Pe.text?i.style.cursor="crosshair":i.style.cursor=""}function pA({board:e,pointer:t}){const n=f.useRef(1),i=f.useRef(null);return f.useEffect(()=>{var o;if(!e)return;$s(e,t),n.current=((o=e.viewport)==null?void 0:o.zoom)||1;let r=null;return(Im(t)||Dm(t))&&(r=setInterval(()=>{var c;const a=((c=e.viewport)==null?void 0:c.zoom)||1;Math.abs(a-n.current)>.01&&(n.current=a,$s(e,t))},100)),()=>{r&&clearInterval(r),i.current&&cancelAnimationFrame(i.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:f.useCallback(()=>{e&&$s(e,t)},[e,t])}}function Lr(e,t){$s(e,t)}function Fh(e){$s(e,ot.eraser)}const gA=({color:e,size:t,zoom:n,shape:i=Bt.circle})=>{const s=t*n,r=Math.max(4,Math.min(256,s)),o=i===Bt.circle?"50%":"0";return l.jsx("div",{className:"cursor-preview-dot",style:{width:r,height:r,backgroundColor:e,borderRadius:o}})},mA=()=>{var he;const e=bt(),{appState:t}=Ut(),{t:n}=Ee(),i=f.useRef(null);zo(i,{enablePositionTracking:!0,enableScaleCompensation:!0});const s=si(e),[r,o]=f.useState(s.strokeWidth),[a,c]=f.useState(s.strokeColor),[u,d]=f.useState(s.strokeStyle),[h,p]=f.useState(s.pencilShape),[g,m]=f.useState(s.pressureEnabled),[b,S]=f.useState(!1),[w,y]=f.useState(!1),[T,C]=f.useState(String(s.strokeWidth)),[E,v]=f.useState(!1),O=lc().includes(t.pointer)&&t.pointer!==ot.eraser;f.useEffect(()=>{const R=si(e);o(R.strokeWidth),c(R.strokeColor),d(R.strokeStyle),p(R.pencilShape),m(R.pressureEnabled),C(String(R.strokeWidth))},[e,t.pointer]);const B=f.useCallback(R=>{C(R.target.value)},[]),X=f.useCallback(()=>{const R=parseInt(T,10);!isNaN(R)&&R>=1&&R<=100?(o(R),ku(e,R),Lr(e,t.pointer)):C(String(r))},[e,T,r,t.pointer]),j=f.useCallback(R=>{R.key==="Enter"?(X(),R.target.blur()):R.key==="Escape"&&(C(String(r)),R.target.blur())},[X,r]),L=f.useCallback(R=>{c(R),xy(e,R),Lr(e,t.pointer)},[e,t.pointer]),D=f.useCallback(R=>{d(R),Ey(e,R)},[e]),k=f.useCallback(R=>{p(R),_y(e,R),Lr(e,t.pointer)},[e,t.pointer]),N=f.useCallback(R=>{m(R),Cy(e,R)},[e]);if(!O)return null;const M=z.getBoardContainer(e),Z=((he=e.viewport)==null?void 0:he.zoom)??1;return l.jsxs("div",{className:"pencil-settings-toolbar",onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),children:[E&&l.jsx(gA,{color:a||Au,size:r,zoom:Z,shape:h}),l.jsx(qe,{ref:i,padding:1,children:l.jsxs(pt.Row,{gap:0,align:"center",children:[l.jsxs(at,{sideOffset:12,open:b,onOpenChange:S,placement:"bottom",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:"pencil-color-button",type:"button",visible:!0,tooltip:n("toolbar.strokeColor"),"aria-label":n("toolbar.strokeColor"),onPointerUp:()=>S(!b),children:l.jsx("div",{className:"pencil-color-preview",style:{backgroundColor:a||Au}})})}),l.jsx(ct,{container:M,children:l.jsx(qe,{padding:4,className:q("stroke-setting"),children:l.jsx(Ci,{value:a,onChange:L})})})]}),l.jsxs("div",{className:"pencil-stroke-style-picker",children:[l.jsx(ne,{className:q("pencil-stroke-style-button",{active:u===yn.solid}),type:"button",visible:!0,icon:l.jsx(kf,{}),tooltip:"实线","aria-label":"实线",onPointerUp:()=>D(yn.solid)}),l.jsx(ne,{className:q("pencil-stroke-style-button",{active:u===yn.dashed}),type:"button",visible:!0,icon:l.jsx(Af,{}),tooltip:"虚线","aria-label":"虚线",onPointerUp:()=>D(yn.dashed)}),l.jsx(ne,{className:q("pencil-stroke-style-button",{active:u===yn.dotted}),type:"button",visible:!0,icon:l.jsx(Mf,{}),tooltip:"点线","aria-label":"点线",onPointerUp:()=>D(yn.dotted)}),l.jsx(ne,{className:q("pencil-stroke-style-button",{active:u===yn.double}),type:"button",visible:!0,icon:l.jsx(Py,{}),tooltip:"双层线","aria-label":"双层线",onPointerUp:()=>D(yn.double)})]}),l.jsxs("div",{className:"pencil-shape-picker",children:[l.jsx(Ct,{content:n("toolbar.pencilShape.circle"),children:l.jsx(oo,{variant:"text",size:"small",className:`pencil-shape-button ${h===Bt.circle?"active":""}`,onClick:()=>k(Bt.circle),children:l.jsx(Cp,{size:16})})}),l.jsx(Ct,{content:n("toolbar.pencilShape.square"),children:l.jsx(oo,{variant:"text",size:"small",className:`pencil-shape-button ${h===Bt.square?"active":""}`,onClick:()=>k(Bt.square),children:l.jsx(Pp,{size:16})})})]}),l.jsxs(at,{sideOffset:12,open:w,onOpenChange:y,placement:"bottom",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:"pencil-width-button",type:"button",visible:!0,tooltip:n("toolbar.strokeWidth"),"aria-label":n("toolbar.strokeWidth"),onPointerUp:()=>y(!w),children:l.jsxs("svg",{className:"pencil-width-icon",viewBox:"0 0 24 24",children:[l.jsx("line",{x1:"4",y1:"8",x2:"20",y2:"8",strokeWidth:"1",stroke:"currentColor"}),l.jsx("line",{x1:"4",y1:"12",x2:"20",y2:"12",strokeWidth:"2",stroke:"currentColor"}),l.jsx("line",{x1:"4",y1:"16",x2:"20",y2:"16",strokeWidth:"3",stroke:"currentColor"})]})})}),l.jsx(ct,{container:M,children:l.jsx(qe,{padding:4,className:q("stroke-width-picker"),children:l.jsxs(pt.Row,{gap:3,align:"center",style:{padding:"4px 8px"},children:[l.jsxs("div",{className:"stroke-width-value",style:{minWidth:"40px",fontSize:"13px",fontWeight:500,color:"var(--color-on-surface)"},children:[r,"px"]}),l.jsx("div",{className:"stroke-width-slider-wrapper",style:{flex:1,minWidth:"160px"},children:l.jsx(Io,{value:r,min:1,max:100,step:1,onChange:R=>{const W=R;o(W),C(String(W)),ku(e,W),Lr(e,t.pointer)},label:!1})})]})})})]}),l.jsxs("div",{className:"pencil-width-input-wrapper",children:[l.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:T,onChange:B,onBlur:X,onKeyDown:j,className:"pencil-width-input"}),l.jsx("span",{className:"pencil-width-input-unit",children:"px"})]}),l.jsx(Ct,{content:"压力感应:支持压感笔;鼠标/触控板使用速度模拟(慢=粗,快=细)",children:l.jsx("div",{className:"pencil-pressure-switch",children:l.jsx(ky,{size:"small",value:g,onChange:N})})})]})})]})},SA=({color:e,size:t,zoom:n,shape:i=Bt.circle})=>{const s=t*n,r=Math.max(4,Math.min(256,s)),o=i===Bt.circle?"50%":"0";return l.jsx("div",{className:"cursor-preview-dot",style:{width:r,height:r,backgroundColor:e,borderRadius:o}})},bA=()=>l.jsxs("svg",{className:"size-picker-icon",viewBox:"0 0 24 24",children:[l.jsx("line",{x1:"4",y1:"8",x2:"20",y2:"8",strokeWidth:"1",stroke:"currentColor"}),l.jsx("line",{x1:"4",y1:"12",x2:"20",y2:"12",strokeWidth:"2",stroke:"currentColor"}),l.jsx("line",{x1:"4",y1:"16",x2:"20",y2:"16",strokeWidth:"3",stroke:"currentColor"})]}),yA=({size:e,onSizeChange:t,presets:n,previewColor:i,title:s,container:r,icon:o})=>{const{t:a}=Ee(),[c,u]=f.useState(!1),[d,h]=f.useState(String(e));Gn.useEffect(()=>{h(String(e))},[e]);const p=f.useCallback(b=>{h(b.target.value)},[]),g=f.useCallback(()=>{const b=parseInt(d,10);!isNaN(b)&&b>=1?t(b):h(String(e))},[d,e,t]),m=f.useCallback(b=>{b.key==="Enter"?(g(),b.target.blur()):b.key==="Escape"&&(h(String(e)),b.target.blur())},[g,e]);return l.jsxs(l.Fragment,{children:[l.jsxs(at,{sideOffset:12,open:c,onOpenChange:u,placement:"bottom",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:"size-picker-button",type:"button",visible:!0,tooltip:s,"aria-label":s,onPointerUp:()=>u(!c),children:o||l.jsx(bA,{})})}),l.jsx(ct,{container:r,children:l.jsx(qe,{padding:4,className:q("size-picker-popover"),children:l.jsxs(pt.Row,{gap:3,align:"center",style:{padding:"4px 8px"},children:[l.jsxs("div",{className:"size-picker-value",style:{minWidth:"40px",fontSize:"13px",fontWeight:500,color:"var(--color-on-surface)"},children:[e,"px"]}),l.jsx("div",{className:"size-picker-slider-wrapper",style:{flex:1,minWidth:"160px"},children:l.jsx(Io,{value:e,min:1,max:Math.max(256,...n),step:1,onChange:b=>{const S=b;h(String(S)),t(S)},label:!1})})]})})})]}),l.jsxs("div",{className:"size-picker-input-wrapper",children:[l.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:d,onChange:p,onBlur:g,onKeyDown:m,className:"size-picker-input"}),l.jsx("span",{className:"size-picker-input-unit",children:"px"})]})]})},wA=[16,32,48,64,96,128,192,256],TA="#f5f5f5",vA=()=>{var S;const e=bt(),{appState:t}=Ut(),{t:n}=Ee(),i=f.useRef(null);zo(i,{enablePositionTracking:!0,enableScaleCompensation:!0});const s=si(e),[r,o]=f.useState(s.eraserWidth),[a,c]=f.useState(s.eraserShape),[u,d]=f.useState(!1),h=t.pointer===ot.eraser;f.useEffect(()=>{const w=si(e);o(w.eraserWidth),c(w.eraserShape)},[e,t.pointer]);const p=f.useCallback(w=>{o(w),Ay(e,w),Fh(e)},[e]),g=f.useCallback(w=>{c(w),My(e,w),Fh(e)},[e]);if(!h)return null;const m=z.getBoardContainer(e),b=((S=e.viewport)==null?void 0:S.zoom)??1;return l.jsxs("div",{className:"pencil-settings-toolbar eraser-settings-toolbar",onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:[u&&l.jsx(SA,{color:TA,size:r,zoom:b,shape:a}),l.jsx(qe,{ref:i,padding:1,children:l.jsxs(pt.Row,{gap:1,align:"center",children:[l.jsx(yA,{size:r,onSizeChange:p,presets:wA,previewColor:"#999",title:n("toolbar.eraserSize"),container:m}),l.jsx("div",{className:"toolbar-divider"}),l.jsxs("div",{className:"eraser-shape-picker",children:[l.jsx(Ct,{content:n("toolbar.eraserShape.circle"),children:l.jsx(oo,{variant:"text",size:"small",className:`eraser-shape-button ${a===Bt.circle?"active":""}`,onClick:()=>g(Bt.circle),children:l.jsx(Cp,{size:16})})}),l.jsx(Ct,{content:n("toolbar.eraserShape.square"),children:l.jsx(oo,{variant:"text",size:"small",className:`eraser-shape-button ${a===Bt.square?"active":""}`,onClick:()=>g(Bt.square),children:l.jsx(Pp,{size:16})})})]})]})})]})},xA=[{icon:l.jsx(Dy,{}),type:"corner",titleKey:"toolbar.anchorCorner"},{icon:l.jsx(Ny,{}),type:"smooth",titleKey:"toolbar.anchorSmooth"},{icon:l.jsx(Ry,{}),type:"symmetric",titleKey:"toolbar.anchorSymmetric"}],EA=()=>{const e=bt(),{appState:t}=Ut(),{t:n}=Ee(),i=f.useRef(null);zo(i,{enablePositionTracking:!0,enableScaleCompensation:!0});const s=Ja(e),[r,o]=f.useState(s.defaultAnchorType),a=t.pointer===Bn.pen&&e.pointer===Bn.pen;f.useEffect(()=>{const u=Ja(e);o(u.defaultAnchorType)},[e,t.pointer,e.pointer]);const c=f.useCallback(u=>{o(u),Iy(e,u)},[e]);return a?l.jsx("div",{className:"pen-settings-toolbar",children:l.jsx(qe,{ref:i,padding:1,children:l.jsx(pt.Row,{gap:0,align:"center",children:l.jsx("div",{className:"pen-anchor-type-picker",children:xA.map(u=>l.jsx(ne,{className:q("pen-anchor-type-button",{active:r===u.type}),type:"button",visible:!0,icon:u.icon,tooltip:n(u.titleKey),"aria-label":n(u.titleKey),onPointerUp:()=>c(u.type)},u.type))})})})}):null},_A=({container:e})=>{const{appState:t,setAppState:n}=Ut(),{t:i}=Ee(),s=bt();return l.jsx(jy,{open:t.openCleanConfirm,container:e,title:i("cleanConfirm.title"),description:i("cleanConfirm.description"),confirmText:i("cleanConfirm.ok"),cancelText:i("cleanConfirm.cancel"),danger:!0,onOpenChange:r=>{n({...t,openCleanConfirm:r})},onConfirm:()=>{s.deleteFragment(s.children)}})},Gh=e=>{const{appState:t}=e;return t&&t.linkState&&t.linkState.isHovering},zh=e=>{const{appState:t}=e;return t&&t.linkState&&t.linkState.isEditing},CA=e=>n=>{const{pointerMove:i}=n;let s=null,r=null;return n.pointerMove=o=>{(z.isPointer(n,vt.selection)||z.isPointer(n,vt.hand))&&!er(n)&&!Ef(n)&&!Gh(n)&&!zh(n)&&Jl(n,"with-text-link",()=>{const a=o.target.closest(".plait-board-link");if(a&&a!==s){const c=a.closest(".plait-text-container"),u=vn.toSlateNode(void 0,c),d=vn.toSlateNode(void 0,a);s=a,e({linkState:{targetDom:a,targetElement:d,editor:u,isEditing:!1,isHovering:!1,isHoveringOrigin:!0}}),clearTimeout(r)}else!a&&s&&(r=setTimeout(()=>{!Gh(n)&&!zh(n)&&e({linkState:null})},300),s=null)}),i(o)},n},PA=()=>{var S,w,y,T;const[e,t]=f.useState(""),{appState:n,setAppState:i}=Ut(),s=bt(),{refs:r,floatingStyles:o}=$l({placement:"top",middleware:[Xl(20),Kl()]}),a=n.linkState,c=((S=n.linkState)==null?void 0:S.targetDom)||null,u=((w=n.linkState)==null?void 0:w.isEditing)||!1,d=((y=n.linkState)==null?void 0:y.isHoveringOrigin)||!1,h=((T=n.linkState)==null?void 0:T.isHovering)||!1,p=u||d||h,g=f.useRef(n.linkState);f.useEffect(()=>{g.current=n.linkState,n.linkState?t(n.linkState.targetElement.url):t("")},[n.linkState]),f.useEffect(()=>{if(c){const C=c.getBoundingClientRect();r.setPositionReference({getBoundingClientRect(){return{x:C.x,y:C.y,width:C.width,height:C.height,top:C.y,left:C.x,right:C.x+C.width,bottom:C.y+C.height}}})}},[s.viewport,c,r]);const m=f.useRef();m.current=C=>{if(r.floating.current&&!r.floating.current.contains(C.target)){if(g.current){const E=es.getLinkElement(g.current.editor);E&&!E[0].url.trim()&&es.unwrapLink(g.current.editor)}i({...n,linkState:null})}},f.useEffect(()=>{const C=E=>{var v;(v=m.current)==null||v.call(m,E)};return document.addEventListener("mousedown",C),()=>{document.removeEventListener("mousedown",C)}},[]);const b=()=>{if(!a)return;if(e!==a.targetElement.url){const E=a.editor,v=a.targetElement,x=vn.findPath(E,v);ma.setNodes(E,{url:e},{at:x})}const C=es.getLinkElement(a.editor);C&&i({...n,linkState:{...n.linkState,targetElement:C[0],isEditing:!1,isHoveringOrigin:!0}})};return p&&l.jsx(qe,{ref:r.setFloating,style:o,padding:1,className:q("link-popup"),onPointerEnter:()=>{!h&&n.linkState&&i({...n,linkState:{...n.linkState,isHovering:!0}})},onPointerLeave:()=>{!u&&n.linkState&&i({...n,linkState:{...n.linkState,isHovering:!1}})},children:l.jsx(pt.Row,{gap:1,align:"center",children:u?l.jsxs(l.Fragment,{children:[l.jsx("input",{type:"text",value:e,onChange:C=>{t(C.target.value)},onKeyDown:C=>{C.key==="Enter"&&b()},className:"link-popup__input",autoFocus:!0}),l.jsx(ne,{type:"icon",visible:!0,icon:l.jsx(so,{}),tooltip:"Delete link","aria-label":"Delete link",onPointerDown:()=>{if(!a)return;const C=a.editor,E=a.targetElement,v=vn.findPath(C,E);ma.unwrapNodes(C,{at:v}),i({...n,linkState:null})}})]}):l.jsxs(l.Fragment,{children:[l.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"link-popup__link",children:e}),l.jsx(ne,{className:"link-popup__edit",type:"icon",visible:!0,icon:l.jsx(Ss,{}),tooltip:"Edit link","aria-label":"Edit link",onPointerDown:({event:C})=>{C.preventDefault(),n.linkState&&i({...n,linkState:{...n.linkState,isEditing:!0}})}}),l.jsx(ne,{type:"icon",visible:!0,icon:l.jsx(so,{}),tooltip:"Delete link","aria-label":"Delete link",onPointerDown:()=>{if(!a)return;const C=a.editor,E=a.targetElement,v=vn.findPath(C,E);ma.unwrapNodes(C,{at:v}),i({...n,linkState:null})}})]})})})},Gs={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 kA(){return"0.6.63"}function Vh(e){return{...Gs,...e,retryPolicy:{...Gs.retryPolicy,...e.retryPolicy||{}},cacheConfig:{...Gs.cacheConfig,...e.cacheConfig||{}},batchConfig:{...Gs.batchConfig,...e.batchConfig||{}}}}class AA{isAvailable(){return Yt.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{Yt.track(t.eventName,n)}catch(i){throw console.error("[Tracking] PostHog track failed:",i),i}}async trackBatch(t){const n=[];for(const i of t)try{await this.track(i),n.push({success:!0})}catch(s){n.push({success:!1,error:s})}return n}getSDKInfo(){return{available:this.isAvailable(),version:this.isAvailable()?"PostHog JS":void 0}}}const Uh=new AA;class MA{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 Uh.trackBatch(t),i=n.filter(s=>!s.success);if(i.length>0){console.error(`Batch upload: ${i.length}/${t.length} events failed`);const s=t.filter((r,o)=>!n[o].success);this.requeueFailedEvents(s)}}catch(n){console.error("Batch upload failed:",n),this.requeueFailedEvents(t)}finally{this.uploading=!1}}async uploadImmediate(t){try{await Uh.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 IA{constructor(t=500){this.debounceMap=new WeakMap,this.globalDebounceMap=new Map,this.globalDebounceTime=200,this.debounceTime=t}shouldTrack(t,n,i=!1){const s=Date.now(),r=this.globalDebounceMap.get(n);if(r&&s-r<this.globalDebounceTime)return i&&console.warn(`[Tracking] 🚫 Global debounce: ${n} (${s-r}ms ago)`),!1;const o=this.debounceMap.get(t);if(!o){const c=new Map;return c.set(n,s),this.debounceMap.set(t,c),this.globalDebounceMap.set(n,s),!0}const a=o.get(n);return!a||s-a>this.debounceTime?(o.set(n,s),this.globalDebounceMap.set(n,s),!0):(i&&console.warn(`[Tracking] 🚫 Element debounce: ${n} (${s-a}ms ago)`),!1)}clear(t){this.debounceMap.delete(t)}setDebounceTime(t){this.debounceTime=t}}const DA=["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 NA(e,t){if(!e.matches(DA))return!1;for(const i of t)if(e.matches(i)||e.closest(i))return!1;return e.hasAttribute("data-track-ignore")?!1:(e.onclick!==null,!0)}function RA(e,t="click"){var a;const n=`auto_${t}_`;if(e.id)return`${n}${e.id}`;const i=e.getAttribute("aria-label");if(i)return`${n}${Wh(i)}`;const s=(a=e.textContent)==null?void 0:a.trim();if(s&&s.length>0){const c=Wh(s.substring(0,20));return`${n}${c}`}const r=e.tagName.toLowerCase(),o=e.className?`.${e.className.split(" ")[0]}`:"";return`${n}${r}${o}`}function Wh(e){return e.toLowerCase().trim().replace(/\s+/g,"_").replace(/[^a-z0-9_-]/g,"").substring(0,50)}function jA(e){if(e.id)return`#${e.id}`;const t=[];let n=e;for(;n&&n!==document.body;){let i=n.tagName.toLowerCase();if(n.className){const s=n.className.split(" ").filter(Boolean);s.length>0&&(i+=`.${s[0]}`)}t.unshift(i),n=n.parentElement}return t.join(" > ")}function Oa(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 Nm(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function LA(){if(typeof window>"u")return"server-side";const e="tracking_session_id";let t=sessionStorage.getItem(e);return t||(t=Nm(),sessionStorage.setItem(e,t)),t}function OA(){return typeof window>"u"?{width:0,height:0}:{width:window.innerWidth||0,height:window.innerHeight||0}}class BA{constructor(t={}){this.state$=new Ly({initialized:!1,config:Gs,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=Vh(t),this.batchService=new MA(this.config.batchConfig),this.debouncer=new IA(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 i=n.closest("[data-track]");if(i){const s=i.getAttribute("data-track");if(s){if(this.isElementExcluded(i))return;this.trackClick(i,s);return}}if(this.config.autoTrack&&NA(n,this.config.excludedSelectors)){if(this.isElementExcluded(n))return;const s=RA(n,"click");this.trackClick(n,s)}},document.body.addEventListener("click",this.clickListener,!0))}setupMultiEventListeners(){if(typeof document>"u")return;document.querySelectorAll("[track-hover]").forEach(i=>{this.attachHoverListener(i)}),document.querySelectorAll("[track-focus]").forEach(i=>{this.attachFocusListener(i)})}attachHoverListener(t){const n=t.getAttribute("track-hover");if(!n||this.hasAttachedListener(t,"hover"))return;const i=()=>{if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents");return}const s=Oa(t),r=this.createTrackEvent(n,s,"hover",t);this.track(r)};t.addEventListener("mouseenter",i),this.markListenerAttached(t,"hover")}attachFocusListener(t){const n=t.getAttribute("track-focus");if(!n||this.hasAttachedListener(t,"focus"))return;const i=()=>{if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents");return}const s=Oa(t),r=this.createTrackEvent(n,s,"focus",t);this.track(r)};t.addEventListener("focus",i,!0),this.markListenerAttached(t,"focus")}hasAttachedListener(t,n){const i=this.attachedListeners.get(t);return i?i.has(n):!1}markListenerAttached(t,n){let i=this.attachedListeners.get(t);i||(i=new Set,this.attachedListeners.set(t,i)),i.add(n)}setupMutationObserver(){typeof window>"u"||typeof MutationObserver>"u"||(this.mutationObserver=new MutationObserver(t=>{t.forEach(n=>{n.addedNodes.forEach(i=>{if(i.nodeType===Node.ELEMENT_NODE){const s=i;s.hasAttribute("track-hover")&&this.attachHoverListener(s),s.hasAttribute("track-focus")&&this.attachFocusListener(s),s.querySelectorAll("[track-hover]").forEach(a=>this.attachHoverListener(a)),s.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 i=Oa(t),s=this.createTrackEvent(n,i,"click",t);this.track(s)}createTrackEvent(t,n,i,s){const r={timestamp:Date.now(),url:typeof window<"u"?window.location.href:"",version:kA(),sessionId:LA(),userAgent:typeof navigator<"u"?navigator.userAgent:void 0,viewport:OA(),eventType:i},o={eventName:t,params:n||void 0,metadata:r,id:Nm(),createdAt:Date.now()};return this.config.devMode&&this.log("debug",`Event created: ${t}`,{params:n,element:s?jA(s):void 0}),o}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=Vh({...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,i){this.config.logLevel!=="silent"&&(t==="error"||t==="debug"&&this.config.devMode)}}let In=null;function HA(){In&&(In.destroy(),In=null)}function FA(e,t){return In||(In=new BA(t),typeof window<"u"&&setTimeout(()=>{In==null||In.initialize()},0),typeof module<"u"&&module.hot&&module.hot.dispose(()=>{HA()})),e.trackingService=In,e}class GA extends ac{initialize(){super.initialize()}}const zA=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.`),GA}},e};function VA(e,t,n,i=0){const s=ge.getCenterPoint(t),r=Ni(t,ci);if(i){const o=UA(n,s,-i);let a=r.find(c=>ge.isHit(ge.getRectangleByPoints([o,o]),c.rectangle));return a&&(a.cursorClass=Uo(a.cursorClass,i)),a}else return r.find(o=>ge.isHit(ge.getRectangleByPoints([n,n]),o.rectangle))}function UA(e,t,n){const i=n*Math.PI/180,s=Math.cos(i),r=Math.sin(i),o=e[0]-t[0],a=e[1]-t[1];return[t[0]+o*s-a*r,t[1]+o*r+a*s]}function WA(e){const t=He(e);return t.length!==1?!1:Yl(t[0])}function $A(e,t){const n=He(e);if(n.length!==1||!Yl(n[0]))return null;const i=n[0],s=ge.getRectangleByPoints(i.points),r=i.angle||0,o=VA(e,s,t,r);return o?{element:i,rectangle:s,handle:o.handle,cursorClass:o.cursorClass}:null}function XA(e,t,n){const{element:i,rectangle:s,handle:r}=t,{startPoint:o,endPoint:a}=n;if(!s){console.warn("startRectangle is undefined");return}const c=a[0]-o[0],u=a[1]-o[1],d=bs(s,r,c,u,pr(),100),h=[[d.x,d.y],[d.x+d.width,d.y+d.height]],p=e.children.findIndex(g=>g.id===i.id);p>=0&&ue.setNode(e,{points:h},[p])}const KA=e=>Di(e,{key:"tool-elements",canResize:()=>WA(e),hitTest:(t=>$A(e,t)),onResize:(t,n)=>XA(e,t,n)});let yo=null;function YA(e,t){return Xe.isFreehand(t)?Vo(t):Je.isPenPath(t)?Wo(t):e.getRectangle(t)}function qA(e,t){return Ni(e,ci).find(i=>ge.isHit(ge.getRectangleByPoints([t,t]),i.rectangle))}function Vc(e){return e.some(t=>Xe.isFreehand(t)||Je.isPenPath(t)||V.isText(t))}function ZA(e){return e.some(t=>V.isText(t))}function Rm(e){const t=He(e);if(t.length<2||!Vc(t))return null;try{const n=Ft(e,t,!1);return{elements:t,rectangle:n}}catch{return null}}function QA(e){return Rm(e)!==null}function JA(e,t){const n=Rm(e);if(!n)return null;const i=qA(n.rectangle,t);if(i){yo=new Map;for(const s of n.elements){const r=YA(e,s);r&&yo.set(s.id,{element:JSON.parse(JSON.stringify(s)),rectangle:{...r}})}return{element:n.elements,rectangle:n.rectangle,handle:i.handle,cursorClass:i.cursorClass}}return null}function eM(e,t,n,i,s,r){const o=r.width/s.width,a=r.height/s.height,c=i.x-s.x,u=i.y-s.y,d=r.x+c*o,h=r.y+u*a,p=n.points.map(m=>{const b=m[0]-i.x,S=m[1]-i.y,w=b*o,y=S*a;return[d+w,h+y]}),g=e.children.findIndex(m=>m.id===t);g>=0&&ue.setNode(e,{points:p},[g])}function tM(e,t,n,i,s,r){const o=r.width/s.width,a=r.height/s.height,c=i.x-s.x,u=i.y-s.y,d=r.x+c*o,h=r.y+u*a,p=n.anchors.map(y=>({...y,point:[y.point[0]*o,y.point[1]*a],handleIn:y.handleIn?[y.handleIn[0]*o,y.handleIn[1]*a]:void 0,handleOut:y.handleOut?[y.handleOut[0]*o,y.handleOut[1]*a]:void 0})),g=i.width*o,m=i.height*a,S=[[d,h],[d+g,h+m]],w=e.children.findIndex(y=>y.id===t);w>=0&&ue.setNode(e,{points:S,anchors:p},[w])}const jm=14;function Lm(e,t){const n={...e};if("text"in e&&typeof e.text=="string"){const i=e["font-size"]?parseFloat(e["font-size"]):jm,s=Math.max(1,Math.round(i*t*10)/10);n["font-size"]=`${s}`}return Array.isArray(e.children)&&(n.children=e.children.map(i=>Lm(i,t))),n}function nM(e,t,n,i,s,r){const o=r.width/s.width,a=r.height/s.height,c=i.x-s.x,u=i.y-s.y,d=r.x+c*o,h=r.y+u*a,p=i.width*o,g=i.height*a,m=[[d,h],[d+p,h+g]],b=e.children.findIndex(S=>S.id===t);if(b>=0)if(V.isDrawElement(n)&&V.isImage(n))ue.setNode(e,{points:m,width:p,height:g},[b]);else if(V.isText(n)){const S=n,w=Lm(S.text,o),y=S.textHeight||jm*1.4;ue.setNode(e,{points:m,text:w,textHeight:y*o,autoSize:!1},[b])}else ue.setNode(e,{points:m},[b])}function iM(e,t,n){const{element:i,rectangle:s,handle:r}=t,{startPoint:o,endPoint:a}=n;if(!s||!Array.isArray(i)||!yo)return;const c=a[0]-o[0],u=a[1]-o[1],d=pr()||ZA(i),h=bs(s,r,c,u,d);for(const p of i){const g=yo.get(p.id);if(!g)continue;const{element:m,rectangle:b}=g;Xe.isFreehand(m)?eM(e,p.id,m,b,s,h):Je.isPenPath(m)?tM(e,p.id,m,b,s,h):nM(e,p.id,m,b,s,h)}}function sM(e){const t=He(e);if(t.length<2||!Vc(t))return null;try{const n=Ql(),i=Ft(e,t,!1),s=Oy(e,i);return ge.getCornerPoints(s).forEach(o=>{const a=By(e,o);n.append(a)}),n}catch{return null}}const rM=e=>{const{afterChange:t}=e;let n=null;return e.afterChange=()=>{t(),n&&(n.remove(),n=null);const i=He(e);i.length>1&&Vc(i)&&!Zs(e)&&(n=sM(e),n&&z.getActiveHost(e).append(n))},Di(e,{key:"multi-resize",canResize:()=>QA(e),hitTest:(i=>JA(e,i)),onResize:(i,s)=>iM(e,i,s)})},Om=14;let eo=null,Il=null;function oM(e,t){return Ni(e,ci).find(i=>ge.isHit(ge.getRectangleByPoints([t,t]),i.rectangle))}function Bm(e,t){const n={...e};if("text"in e&&typeof e.text=="string"){const i=e["font-size"]?parseFloat(e["font-size"]):Om,s=Math.max(1,Math.round(i*t*10)/10);n["font-size"]=`${s}`}return Array.isArray(e.children)&&(n.children=e.children.map(i=>Bm(i,t))),n}function aM(e){const t=He(e);return t.length!==1?!1:V.isText(t[0])}function lM(e,t){const n=He(e);if(n.length!==1||!V.isText(n[0]))return null;const i=n[0],s=ge.getRectangleByPoints(i.points),r=oM(s,t);return r?(eo=JSON.parse(JSON.stringify(i)),Il={...s},{element:i,rectangle:s,handle:r.handle,cursorClass:r.cursorClass}):null}function cM(e,t,n){const{element:i,rectangle:s,handle:r}=t,{startPoint:o,endPoint:a}=n;if(!s||!eo||!Il)return;const c=a[0]-o[0],u=a[1]-o[1],d=bs(s,r,c,u,!0,20),h=d.width/Il.width;if(h<=0)return;const p=Bm(eo.text,h),m=(eo.textHeight||Om*1.4)*h,b=[[d.x,d.y],[d.x+d.width,d.y+d.height]],S=e.children.findIndex(w=>w.id===i.id);S>=0&&ue.setNode(e,{points:b,text:p,textHeight:m,autoSize:!1},[S])}const uM=e=>Di(e,{key:"text-resize",canResize:()=>aM(e),hitTest:t=>lM(e,t),onResize:(t,n)=>cM(e,t,n)});function dM(e){return e.some(n=>Xe.isFreehand(n)||Je.isPenPath(n))}function hM(e){const t=He(e);if(t.length<2||!dM(t))return null;try{return Ft(e,t,!1)}catch{return null}}const fM=()=>{const e=bt(),[t,n]=f.useState([]),[i,s]=f.useState(!1),[r,o]=f.useState(!1),a=f.useRef(!1),c=f.useCallback(()=>{const h=Qs(e)||er(e)||Zs(e);if(o(h),h)return;He(e);const p=hM(e);if(!p){s(!1);return}const m=[{x:p.x,y:p.y,cursor:"nwse-resize"},{x:p.x+p.width,y:p.y,cursor:"nesw-resize"},{x:p.x+p.width,y:p.y+p.height,cursor:"nwse-resize"},{x:p.x,y:p.y+p.height,cursor:"nesw-resize"}].map(b=>{const S=Os(e,[b.x,b.y]);return{x:S[0],y:S[1],cursor:b.cursor}});n(m),s(!0)},[e]);if(f.useEffect(()=>{a.current=r},[r]),f.useEffect(()=>{c();let h,p=JSON.stringify(e.viewport),g=JSON.stringify(e.selection),m=e.children.length;const b=()=>{const S=JSON.stringify(e.viewport),w=JSON.stringify(e.selection),y=e.children.length,T=Qs(e)||er(e)||Zs(e);(S!==p||w!==g||y!==m||T!==a.current)&&(p=S,g=w,m=y,c()),h=requestAnimationFrame(b)};return h=requestAnimationFrame(b),()=>{cancelAnimationFrame(h)}},[e,c]),!i||t.length===0||r)return null;const u=ci,d=u/2;return l.jsx("div",{className:q("multi-selection-handles",Dt),children:t.map((h,p)=>l.jsx("div",{className:"multi-selection-handle",style:{left:h.x-d,top:h.y-d,width:u,height:u,cursor:h.cursor}},p))})},Hm=f.createContext(null),pM=typeof window<"u"?Math.max(375,window.innerWidth*.5):600,gM=({children:e})=>{const t=f.useRef(null),n=f.useRef(null),[i,s]=f.useState([]),[r,o]=f.useState(!1),[a,c]=f.useState(pM),u=f.useCallback(h=>{n.current=h},[]),d=f.useCallback(async(h,p)=>{n.current?await n.current(h,p):console.warn("[ChatDrawerContext] No retry handler registered")},[]);return l.jsx(Hm.Provider,{value:{chatDrawerRef:t,registerRetryHandler:u,executeRetry:d,selectedContent:i,setSelectedContent:s,isDrawerOpen:r,setIsDrawerOpen:o,drawerWidth:a,setDrawerWidth:c},children:e})};function Fm(){const e=f.useContext(Hm);if(!e)throw new Error("useChatDrawer must be used within a ChatDrawerProvider");return e}function mM(){const{chatDrawerRef:e,registerRetryHandler:t,executeRetry:n,selectedContent:i,setSelectedContent:s,isDrawerOpen:r,setIsDrawerOpen:o,drawerWidth:a,setDrawerWidth:c}=Fm();return{openChatDrawer:()=>{var u;(u=e.current)==null||u.open()},closeChatDrawer:()=>{var u;(u=e.current)==null||u.close()},toggleChatDrawer:()=>{var u;(u=e.current)==null||u.toggle()},sendMessageToChatDrawer:async u=>{var d;await((d=e.current)==null?void 0:d.sendMessage(u))},sendWorkflowMessage:async u=>{var d;await((d=e.current)==null?void 0:d.sendWorkflowMessage(u))},updateWorkflowMessage:u=>{var d;(d=e.current)==null||d.updateWorkflowMessage(u)},appendAgentLog:u=>{var d;(d=e.current)==null||d.appendAgentLog(u)},updateThinkingContent:u=>{var d;(d=e.current)==null||d.updateThinkingContent(u)},isChatDrawerOpen:()=>{var u;return((u=e.current)==null?void 0:u.isOpen())??!1},isDrawerOpen:r,setIsDrawerOpen:o,drawerWidth:a,setDrawerWidth:c,registerRetryHandler:t,retryWorkflowFromStep:async(u,d)=>{await n(u,d)},selectedContent:i,setSelectedContent:s}}class SM{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=Er.getToolById("banana-prompt");if(!n){console.error('❌ Tool "banana-prompt" not found');return}Fi.insertTool(t,n.id,n.url,[100,100],{width:n.defaultWidth||Gi.defaultWidth,height:n.defaultHeight||Gi.defaultHeight},{name:n.name,category:n.category,permissions:n.permissions})}insertXiaohongshuTool(){const t=this.getBoard();if(!t)return;const n=Er.getToolById("xiaohongshu-tool");if(!n){console.error('❌ Tool "xiaohongshu-tool" not found');return}Fi.insertTool(t,n.id,n.url,[300,300],{width:n.defaultWidth||Gi.defaultWidth,height:n.defaultHeight||Gi.defaultHeight},{name:n.name,category:n.category,permissions:n.permissions})}insertToolById(t,n=200,i=200){const s=this.getBoard();if(!s)return;const r=Er.getToolById(t);if(!r){console.error(`❌ Tool "${t}" not found`);return}Fi.insertTool(s,r.id,r.url,[n,i],{width:r.defaultWidth||Gi.defaultWidth,height:r.defaultHeight||Gi.defaultHeight},{name:r.name,category:r.category,permissions:r.permissions})}listAllTools(){Er.getAvailableTools().forEach((n,i)=>{})}getAllToolElements(){const t=this.getBoard();if(!t)return;Fi.getAllTools(t).forEach((i,s)=>{})}removeAllTools(){const t=this.getBoard();if(!t)return;Fi.getAllTools(t).forEach(i=>{Fi.removeTool(t,i.id)})}help(){}}const bM=new SM;typeof window<"u"&&(window.testToolbox=bM);const yM={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)"},wM={autoHideDelay:3e3},TM=({board:e,config:t,className:n,displayMode:i="auto",autoTriggerConfig:s})=>{const r=f.useRef(null),o=f.useRef(null);f.useRef(null);const a={...yM,...t},c={...wM,...s},[u,d]=f.useState(()=>({expanded:i==="always"?!0:a.defaultExpanded,dragging:!1,autoMode:i==="auto",manuallyExpanded:!1})),h=f.useRef({isDragging:!1,startPoint:null}),p=f.useRef(null),[g,m]=f.useState(null),b=f.useRef(null),[S,w]=f.useState(!1),y=120,T=f.useRef(0),C=f.useRef({zoom:e.viewport.zoom,offsetX:e.viewport.offsetX,offsetY:e.viewport.offsetY}),E=f.useRef(!1),v=f.useCallback(()=>{if(!e||!e.children)return[];const P=[];return e.children.forEach(A=>{try{let $=null;A.points&&Array.isArray(A.points)?$=ge.getRectangleByPoints(A.points):A.x!==void 0&&A.y!==void 0&&($={x:A.x,y:A.y,width:A.width||100,height:A.height||100}),$&&$.width>0&&$.height>0&&P.push({id:A.id,bounds:$,type:A.type})}catch($){console.warn("Failed to get bounds for element:",A.id,$)}}),P},[e]),x=f.useCallback(()=>{const A=z.getBoardContainer(e).getBoundingClientRect(),$=e.viewport.zoom,Q=Ao(e),I=Q[0],H=Q[1],F=A.width/$,U=A.height/$;return{x:I,y:H,width:F,height:U}},[e]),O=f.useRef(u.expanded);O.current=u.expanded;const B=f.useRef(null),X=f.useRef(1);f.useEffect(()=>{if(i==="always"){O.current||d(A=>({...A,expanded:!0}));return}if(i!=="auto")return;const P=setInterval(()=>{const A=e.viewport,$=C.current,Q=Math.abs(A.zoom-$.zoom)>.001,I=Math.abs(A.offsetX-$.offsetX)>.5||Math.abs(A.offsetY-$.offsetY)>.5;if(Q||I){if(C.current={zoom:A.zoom,offsetX:A.offsetX,offsetY:A.offsetY},!E.current){E.current=!0;return}T.current=Date.now(),O.current||d(F=>({...F,expanded:!0,manuallyExpanded:!1}))}},100);return()=>{clearInterval(P)}},[i,e]),f.useEffect(()=>{if(i!=="auto"||!u.expanded||u.manuallyExpanded||u.dragging)return;const P=setTimeout(()=>{d(A=>!A.autoMode||A.manuallyExpanded||A.dragging?A:{...A,expanded:!1})},c.autoHideDelay);return()=>{clearTimeout(P)}},[i,u.expanded,u.manuallyExpanded,u.dragging,c.autoHideDelay]);const j=f.useCallback((P,A)=>{if(P.length===0)return{x:A.x-200,y:A.y-200,width:A.width+400,height:A.height+400};let $=A.x,Q=A.y,I=A.x+A.width,H=A.y+A.height;P.forEach(U=>{const{x:te,y:ee,width:G,height:J}=U.bounds;$=Math.min($,te),Q=Math.min(Q,ee),I=Math.max(I,te+G),H=Math.max(H,ee+J)});const F=100;return{x:$-F,y:Q-F,width:I-$+F*2,height:H-Q+F*2}},[]),L=f.useCallback(P=>{const $=(a.width-20)/P.width,Q=(a.height-20)/P.height;return Math.min($,Q)},[a.width,a.height]),D=f.useCallback((P,A,$,Q)=>{const H=(P-$.x)*Q+10,F=(A-$.y)*Q+10;return[H,F]},[]),k=f.useCallback((P,A,$,Q)=>{const H=(P-10)/Q+$.x,F=(A-10)/Q+$.y;return[H,F]},[]),N=f.useCallback((P,A,$)=>{if(100*$<5)return;P.strokeStyle="rgba(0, 0, 0, 0.05)",P.lineWidth=.5;const H=Math.floor(A.x/100)*100,F=Math.floor(A.y/100)*100,U=A.x+A.width,te=A.y+A.height;for(let ee=H;ee<=U;ee+=100){const[G]=D(ee,0,A,$);P.beginPath(),P.moveTo(G,0),P.lineTo(G,a.height),P.stroke()}for(let ee=F;ee<=te;ee+=100){const[,G]=D(0,ee,A,$);P.beginPath(),P.moveTo(0,G),P.lineTo(a.width,G),P.stroke()}},[D,a.width,a.height]),M=f.useCallback(()=>{const P=r.current;if(!P)return;const A=P.getContext("2d");if(!A)return;A.clearRect(0,0,a.width,a.height);const $=v(),Q=x();if($.length===0&&!Q){A.fillStyle="#999",A.font="12px sans-serif",A.textAlign="center",A.textBaseline="middle",A.fillText("空画布",a.width/2,a.height/2);return}const I=j($,Q),H=L(I);B.current=I,X.current=H,N(A,I,H),A.fillStyle=a.elementColor,A.strokeStyle="rgba(0, 0, 0, 0.1)",A.lineWidth=.5,$.forEach(se=>{const{x:Re,y:ut,width:Oe,height:ie}=se.bounds,[De,Le]=D(Re,ut,I,H),ke=Oe*H,Fe=ie*H;A.fillRect(De,Le,ke,Fe),A.strokeRect(De,Le,ke,Fe)});const[F,U]=D(Q.x,Q.y,I,H),te=Q.width*H,ee=Q.height*H;A.fillStyle=a.viewportColor,A.fillRect(F,U,te,ee),A.strokeStyle=a.viewportColor.replace("0.3","1"),A.lineWidth=2,A.strokeRect(F,U,te,ee);const G=8;A.fillStyle=a.viewportColor.replace("0.3","0.8"),A.fillRect(F,U,G,2),A.fillRect(F,U,2,G),A.fillRect(F+te-G,U,G,2),A.fillRect(F+te-2,U,2,G),A.fillRect(F,U+ee-2,G,2),A.fillRect(F,U+ee-G,2,G),A.fillRect(F+te-G,U+ee-2,G,2),A.fillRect(F+te-2,U+ee-G,2,G);const J=b.current;if(J){const se=J.x-te/2,Re=J.y-ee/2;A.fillStyle="rgba(243, 156, 18, 0.15)",A.fillRect(se,Re,te,ee),A.strokeStyle="rgba(243, 156, 18, 0.8)",A.lineWidth=2,A.strokeRect(se,Re,te,ee)}},[e,a,v,x,j,L,D,N]),Z=f.useCallback(P=>{P.preventDefault(),P.stopPropagation();const A=r.current;if(!A||!B.current)return;const $=A.getBoundingClientRect(),Q=P.clientX-$.left,I=P.clientY-$.top;Yt.track("minimap_navigate",{action:"click",displayMode:i});const[H,F]=k(Q,I,B.current,X.current);h.current={isDragging:!0,startPoint:[Q,I]},d(U=>({...U,dragging:!0})),he(H,F)},[k,e]),he=f.useCallback((P,A)=>{const Q=z.getBoardContainer(e).getBoundingClientRect(),I=e.viewport.zoom,H=P-Q.width/(2*I),F=A-Q.height/(2*I);fe.updateViewport(e,[H,F],I),requestAnimationFrame(()=>M())},[e,M]),R=f.useCallback(P=>{if(!h.current.isDragging||!B.current)return;P.preventDefault(),P.stopPropagation();const A=r.current;if(!A)return;const $=A.getBoundingClientRect(),Q=P.clientX-$.left,I=P.clientY-$.top,[H,F]=k(Q,I,B.current,X.current);he(H,F)},[k,he]),W=f.useCallback(()=>{h.current.isDragging&&Yt.track("minimap_navigate",{action:"drag",displayMode:i}),h.current={isDragging:!1,startPoint:null},d(P=>({...P,dragging:!1}))},[i]),ce=f.useCallback((P,A)=>{const $=p.current;if(!$||!B.current)return;const Q=$.getContext("2d");if(!Q)return;const[I,H]=k(P,A,B.current,X.current),F=x(),U=F.width,te=F.height,ee=U,G=te;Q.clearRect(0,0,y,y),Q.fillStyle="#fff",Q.fillRect(0,0,y,y);const J=I-ee/2,se=H-G/2,Re=y/ee,ut=y/G,Oe=Math.min(Re,ut),ie=(y-ee*Oe)/2,De=(y-G*Oe)/2;v().forEach(ke=>{const{bounds:Fe}=ke;if(Fe.x+Fe.width>=J&&Fe.x<=J+ee&&Fe.y+Fe.height>=se&&Fe.y<=se+G){const Nt=(Fe.x-J)*Oe+ie,Pt=(Fe.y-se)*Oe+De,Rt=Fe.width*Oe,jt=Fe.height*Oe;Q.fillStyle="rgba(0, 0, 0, 0.6)",Q.fillRect(Nt,Pt,Rt,jt)}}),Q.strokeStyle="rgba(90, 79, 207, 0.6)",Q.lineWidth=1,Q.setLineDash([4,4]),Q.beginPath(),Q.moveTo(0,y/2),Q.lineTo(y,y/2),Q.stroke(),Q.beginPath(),Q.moveTo(y/2,0),Q.lineTo(y/2,y),Q.stroke(),Q.setLineDash([]),Q.strokeStyle="rgba(90, 79, 207, 0.3)",Q.lineWidth=2,Q.strokeRect(0,0,y,y)},[v,x,k]),K=f.useCallback(()=>{u.dragging||w(!0)},[u.dragging]),ae=f.useCallback(()=>{w(!1),m(null),b.current=null},[]),le=f.useCallback(P=>{if(u.dragging){w(!1),b.current=null;return}const A=r.current;if(!A)return;const $=A.getBoundingClientRect(),Q=P.clientX-$.left,I=P.clientY-$.top,H={x:Q,y:I};m(H),b.current=H,w(!0),ce(Q,I),M()},[u.dragging,ce,M]),me=f.useRef(!1),Te=f.useCallback(P=>{me.current=!0;const A=r.current;if(!A)return;const $=P.touches[0],Q=A.getBoundingClientRect(),I=$.clientX-Q.left,H=$.clientY-Q.top,F={x:I,y:H};m(F),b.current=F,w(!0),ce(I,H),M()},[ce,M]),ze=f.useCallback(P=>{const A=r.current;if(!A)return;const $=P.touches[0],Q=A.getBoundingClientRect(),I=$.clientX-Q.left,H=$.clientY-Q.top,F={x:I,y:H};m(F),b.current=F,w(!0),ce(I,H),M()},[ce,M]),Y=f.useCallback(()=>{me.current=!1,setTimeout(()=>{me.current||(w(!1),m(null),b.current=null,M())},500)},[M]);f.useEffect(()=>{if(!u.expanded)return;M();const P=setInterval(()=>{M()},100);return()=>{clearInterval(P)}},[e,u.expanded,M]);const Ie=f.useCallback(()=>{d(P=>{const A=!P.expanded;return{...P,expanded:A,manuallyExpanded:A}})},[]),$e={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},it=S&&(me.current||!u.dragging),Ye=g?{position:"absolute",right:a.width+8,top:Math.max(0,Math.min(g.y-y/2,a.height-y)),width:y,height:y,opacity:it?1:0,pointerEvents:"none",transition:"opacity 0.15s ease-out, top 0.1s ease-out"}:{display:"none"};return l.jsxs("div",{ref:o,className:`minimap ${u.expanded?"minimap--expanded":"minimap--collapsed"} ${i==="auto"?"minimap--auto":""} ${n||""}`,style:{...$e,zIndex:Jt.MINIMAP},"data-track":"minimap_container",children:[u.expanded&&l.jsxs("div",{className:"minimap__content",children:[l.jsx("canvas",{ref:r,width:a.width,height:a.height,className:"minimap__canvas",onPointerDown:Z,onPointerMove:R,onPointerUp:W,onPointerLeave:W,onMouseEnter:K,onMouseLeave:ae,onMouseMove:le,onTouchStart:Te,onTouchMove:ze,onTouchEnd:Y,style:{cursor:u.dragging?"grabbing":"pointer"}}),l.jsx("div",{className:"minimap__preview",style:Ye,children:l.jsx("canvas",{ref:p,width:y,height:y,className:"minimap__preview-canvas"})})]}),a.collapsible&&l.jsx("button",{className:`minimap__toggle ${u.expanded?"minimap__toggle--expanded":""}`,onClick:Ie,title:u.expanded?"折叠小地图":"展开小地图","data-track":"minimap_click_toggle",children:l.jsx(Hy,{})})]})},$h=10,vM=3e3,xM=({showMinimap:e=!0,container:t})=>{var B,X,j,L;const n=bt(),{t:i}=Ee(),{isDrawerOpen:s,drawerWidth:r}=mM(),[o,a]=f.useState(!1),[c,u]=f.useState(!0),[d,h]=f.useState(!1),p=f.useRef(null),g=f.useRef({zoom:((B=n==null?void 0:n.viewport)==null?void 0:B.zoom)||1,offsetX:((X=n==null?void 0:n.viewport)==null?void 0:X.offsetX)||0,offsetY:((j=n==null?void 0:n.viewport)==null?void 0:j.offsetY)||0}),m=f.useRef(!1),b=f.useRef(null),S=f.useMemo(()=>s?r+$h:$h,[s,r]),w=f.useCallback(()=>{fe.updateZoom(n,n.viewport.zoom-.1)},[n]),y=f.useCallback(()=>{fe.updateZoom(n,n.viewport.zoom+.1)},[n]),T=f.useCallback(()=>{fe.fitViewport(n),a(!1)},[n]),C=f.useCallback(()=>{fe.updateZoom(n,1),a(!1)},[n]),E=f.useCallback(()=>{nc(n),a(!1)},[n]),v=f.useCallback(()=>{u(D=>{const k=!D;return h(k),k})},[]);f.useEffect(()=>{if(!c||!n)return;const D=z.getBoardContainer(n);if(!D)return;const k=N=>{var Z;const M=N.target;(Z=p.current)!=null&&Z.contains(M)||(u(!1),h(!1))};return D.addEventListener("mousedown",k),()=>{D.removeEventListener("mousedown",k)}},[c,n]),f.useEffect(()=>{if(!e||!n)return;const D=setInterval(()=>{const k=n.viewport,N=g.current,M=Math.abs(k.zoom-N.zoom)>.001,Z=Math.abs(k.offsetX-N.offsetX)>.5||Math.abs(k.offsetY-N.offsetY)>.5;if(M||Z){if(g.current={zoom:k.zoom,offsetX:k.offsetX,offsetY:k.offsetY},!m.current){m.current=!0;return}c||(u(!0),h(!1)),b.current&&clearTimeout(b.current)}},100);return()=>{clearInterval(D)}},[e,n,c]),f.useEffect(()=>{if(!(!c||d))return b.current=setTimeout(()=>{u(!1)},vM),()=>{b.current&&clearTimeout(b.current)}},[c,d]);const x=f.useCallback(()=>{a(D=>!D)},[]),O=Math.round((((L=n==null?void 0:n.viewport)==null?void 0:L.zoom)||1)*100);return l.jsxs("div",{className:"view-navigation",style:{right:S,zIndex:Jt.VIEW_NAVIGATION},ref:p,"data-testid":"view-navigation",children:[l.jsxs("div",{className:"view-navigation__zoom",children:[l.jsx(Ct,{content:i("zoom.out"),showArrow:!1,children:l.jsx("button",{className:"view-navigation__zoom-btn",onClick:w,"aria-label":i("zoom.out"),"data-track":"view_nav_zoom_out","data-testid":"zoom-out",children:l.jsx(Fy,{})})}),l.jsxs(at,{sideOffset:8,open:o,onOpenChange:a,placement:"bottom",children:[l.jsx(Ct,{content:i("zoom.fit"),showArrow:!1,children:l.jsx(lt,{asChild:!0,children:l.jsxs("button",{className:"view-navigation__zoom-percent",onClick:x,"aria-label":i("zoom.fit"),"data-track":"view_nav_zoom_menu","data-testid":"zoom-display",children:[O,"%"]})})}),l.jsx(ct,{container:t,style:{zIndex:Jt.POPOVER},children:l.jsxs("div",{className:"view-navigation-zoom-menu",children:[l.jsxs("button",{className:"zoom-menu-item",onClick:T,"data-track":"view_nav_zoom_fit",children:[l.jsx("span",{className:"zoom-menu-item__label",children:i("zoom.fit")}),l.jsx("span",{className:"zoom-menu-item__shortcut",children:"⌘⇧="})]}),l.jsx("button",{className:"zoom-menu-item",onClick:E,"data-track":"view_nav_zoom_fit_frame",children:l.jsx("span",{className:"zoom-menu-item__label",children:i("zoom.fitFrame")})}),l.jsxs("button",{className:"zoom-menu-item",onClick:C,"data-track":"view_nav_zoom_100",children:[l.jsx("span",{className:"zoom-menu-item__label",children:i("zoom.100")}),l.jsx("span",{className:"zoom-menu-item__shortcut",children:"⌘0"})]})]})})]}),l.jsx(Ct,{content:i("zoom.in"),showArrow:!1,children:l.jsx("button",{className:"view-navigation__zoom-btn",onClick:y,"aria-label":i("zoom.in"),"data-track":"view_nav_zoom_in","data-testid":"zoom-in",children:l.jsx(Gy,{})})}),e&&l.jsx(Ct,{content:c?"折叠小地图":"展开小地图",showArrow:!1,children:l.jsx("button",{className:`view-navigation__minimap-toggle ${c?"view-navigation__minimap-toggle--expanded":""}`,onClick:v,"aria-label":c?"折叠小地图":"展开小地图","data-track":"view_nav_minimap_toggle",children:l.jsx(zy,{})})})]}),e&&c&&l.jsx("div",{className:"view-navigation__minimap",children:l.jsx(TM,{board:n,displayMode:"always",config:{width:180,height:120,position:"top-right",margin:0,collapsible:!1,defaultExpanded:!0}})})]})},EM=f.lazy(()=>Ne(()=>import("./tool-windows-hjm6YiPY.js").then(e=>e.p0),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.MediaLibraryModal}))),_M=({position:e,visible:t,onClose:n,onOpenMediaLibrary:i})=>{const s=bt(),{t:r}=Ee(),o=tc(),a=z.getBoardContainer(s),[c,u]=f.useState({freehand:!1,arrow:!1,shape:!1}),[d,h]=f.useState(!1),{refs:p,floatingStyles:g}=$l({placement:"bottom",middleware:[Xl(12),Of({padding:16}),Kl({fallbackPlacements:["top","right","left"]})]});f.useEffect(()=>{if(e&&t){const[j,L]=e;p.setPositionReference({getBoundingClientRect(){return{width:1,height:1,x:j,y:L,top:L,left:j,right:j+1,bottom:L+1}}})}},[e,t,p]),f.useEffect(()=>{if(!t)return;const j=D=>{const k=D.target,N=k.closest(".quick-creation-toolbar"),M=k.closest(".quick-toolbar-popover")||k.closest("[data-radix-popper-content-wrapper]")||k.closest(".plait-popover")||k.closest(".shape-picker")||k.closest(".arrow-picker")||k.closest(".freehand-panel"),Z=k.closest(".media-library-modal");!N&&!M&&!Z&&n()},L=setTimeout(()=>{document.addEventListener("mousedown",j)},100);return()=>{clearTimeout(L),document.removeEventListener("mousedown",j)}},[t,n]);const m=()=>{u({freehand:!1,arrow:!1,shape:!1})},b=j=>{u({freehand:!1,arrow:!1,shape:!1,[j]:!0})},S=()=>{m(),Cn(s),ht(s,null),fe.updatePointerType(s,Pe.text),o(Pe.text),n()},w=()=>{m(),Cn(s),ht(s,Et.dnd),fe.updatePointerType(s,ki.mind),o(ki.mind),n()},y=()=>{m(),Go(s),n()},T=async j=>{try{j.type===Nn.IMAGE?await ql(s,j.url):j.type===Nn.VIDEO?await pp(s,j.url):j.type===Nn.AUDIO&&await Gl(s,j.url,{title:j.name,duration:j.duration,previewImageUrl:j.thumbnail,prompt:j.prompt,mv:j.modelName,clipId:j.clipId,providerTaskId:j.providerTaskId}),oe.success(r("toolbar.assetInserted")||"素材已插入到画板"),h(!1),n()}catch(L){console.error("Failed to insert asset:",L),oe.error(r("toolbar.assetInsertFailed")||"插入素材失败")}},C=()=>{if(m(),i){i({mode:ni.SELECT,onSelect:T,selectButtonText:r("toolbar.insert")||"插入"}),n();return}h(!0)},[E,v]=f.useState(ot.feltTipPen),x=300,O=f.useRef(null),B=f.useCallback(()=>{O.current&&(clearTimeout(O.current),O.current=null)},[]);f.useEffect(()=>()=>{B()},[B]);const X=(j,L,D,k)=>l.jsxs(at,{open:c[L],sideOffset:12,onOpenChange:N=>{N||m()},placement:"bottom",children:[l.jsx(lt,{asChild:!0,children:l.jsx("div",{onPointerEnter:()=>{B(),O.current=setTimeout(()=>{b(L)},x)},onPointerLeave:()=>{B()},children:l.jsx(ne,{type:"icon",visible:!0,selected:c[L],icon:j,"aria-label":D,"data-track":`quick_toolbar_click_${L}`,onPointerDown:()=>{B(),b(L),Cn(s),L==="freehand"&&(ht(s,Et.dnd),fe.updatePointerType(s,E),o(E))},onPointerUp:()=>{L==="freehand"&&ht(s,Et.drawing)}})})}),l.jsx(ct,{container:a,style:{zIndex:Jt.POPOVER},className:"quick-toolbar-popover",children:k})]});return t?l.jsxs(l.Fragment,{children:[l.jsx(qe,{padding:1,className:`quick-creation-toolbar ${Dt}`,ref:p.setFloating,style:g,children:l.jsxs(pt.Row,{gap:1,children:[l.jsx(ne,{type:"icon",visible:!0,icon:l.jsx(rc,{}),"aria-label":r("toolbar.text"),"data-track":"quick_toolbar_click_text",onPointerUp:S}),l.jsx(ne,{type:"icon",visible:!0,icon:l.jsx(jo,{size:24}),"aria-label":r("toolbar.image"),"data-track":"quick_toolbar_click_image",onPointerUp:y}),l.jsx(ne,{type:"icon",visible:!0,icon:l.jsx(Ro,{}),"aria-label":r("toolbar.mediaLibrary"),"data-track":"quick_toolbar_click_media_library",onPointerUp:C}),X(l.jsx(Ss,{}),"freehand",r("toolbar.pen"),l.jsx(jc,{onPointerUp:j=>{m(),v(j),fe.updatePointerType(s,j),o(j),n()}})),X(l.jsx(sc,{}),"arrow",r("toolbar.arrow"),l.jsx(Oc,{onPointerUp:j=>{m(),fe.updatePointerType(s,j),o(j),n()}})),X(l.jsx(ic,{}),"shape",r("toolbar.shape"),l.jsx(Lc,{onPointerUp:j=>{m(),fe.updatePointerType(s,j),o(j),n()}})),l.jsx(ne,{type:"icon",visible:!0,icon:l.jsx(ro,{}),"aria-label":r("toolbar.mind"),"data-track":"quick_toolbar_click_mind",onPointerUp:w})]})}),d&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(EM,{isOpen:d,onClose:()=>{h(!1)},mode:ni.SELECT,onSelect:T,selectButtonText:r("toolbar.insert")||"插入"})})]}):null};function fN(e){const[t,n]=f.useState({isCached:!1}),[i,s]=f.useState(!1),r=f.useCallback(async()=>{if(!e){n({isCached:!1});return}try{const c=await bi.getCacheInfo(e);n(c)}catch(c){console.error("[useUnifiedCache] Failed to load cache info:",c),n({isCached:!1})}},[e]);f.useEffect(()=>{r()},[r]),f.useEffect(()=>bi.subscribe(()=>{r()}),[r]);const o=f.useCallback(async c=>{if(!e)return!1;s(!0);try{const u=await bi.cacheImage(e,c);return u&&await r(),u}catch(u){return console.error("[useUnifiedCache] Failed to cache image:",u),!1}finally{s(!1)}},[e,r]),a=f.useCallback(async()=>{if(!e)return!1;s(!0);try{return await bi.deleteCache(e),await r(),!0}catch(c){return console.error("[useUnifiedCache] Failed to delete cache:",c),!1}finally{s(!1)}},[e,r]);return{cacheInfo:t,isLoading:i,isCached:t.isCached,cacheAge:t.age,cacheImage:o,deleteCache:a,reload:r}}function CM(e){const[t,n]=f.useState(!1);f.useEffect(()=>{const s=()=>{n(!0),e==null||e()};return bi.onQuotaExceeded(s)},[e]);const i=f.useCallback(()=>{n(!1)},[]);return{isQuotaExceeded:t,resetQuotaFlag:i}}const PM=({children:e,onOpenMediaLibrary:t})=>{const[n,i]=f.useState(!1),{confirm:s,confirmDialog:r}=No(),o=f.useCallback(()=>{n||(i(!0),s({title:"缓存空间已满",description:"图片缓存空间已满,无法继续缓存新图片。是否打开素材库清理缓存?",confirmText:"打开素材库",cancelText:"稍后处理",confirmTheme:"warning"}).then(a=>{i(!1),a&&(t==null||t())}))},[s,n,t]);return CM(o),l.jsxs(l.Fragment,{children:[e,r]})},wo={visible:!1,position:{x:0,y:0},sourceElement:null,currentShape:null,hitIndex:-1,hitPoint:null,mode:"hover",arrowLineElement:null,arrowLineEndPoint:null},Gm=new WeakMap,Dl=new WeakMap;function To(e){return Gm.get(e)||wo}function zs(e,t){Gm.set(e,t);const n=Dl.get(e);n&&n(t)}function kM(e,t){return Dl.set(e,t),()=>{Dl.delete(e)}}function Uc(e){zs(e,wo)}const Is=100;function AM(e,t,n,i,s){const r=Ky(n),o=ge.getRectangleByPoints(t.points),a=o.width,c=o.height,u=o.x+a/2,d=o.y+c/2,p=ge.getEdgeCenterPoints(o)[n];let g,m;switch(r){case ft.right:g=u+a/2+Is+a/2,m=d;break;case ft.bottom:g=u,m=d+c/2+Is+c/2;break;case ft.left:g=u-a/2-Is-a/2,m=d;break;case ft.top:g=u,m=d-c/2-Is-c/2;break;default:g=u+a/2+Is+a/2,m=d}const b=[[g-a/2,m-c/2],[g+a/2,m+c/2]],S=uc(e,b,s);if(S.fill="#ffffff",V.isShapeElement(t)&&!V.isText(t)){const j=t;j.angle!==void 0&&(S.angle=j.angle),j.fill&&j.fill!=="none"&&(S.fill=j.fill),j.strokeColor!==void 0&&(S.strokeColor=j.strokeColor),j.strokeStyle!==void 0&&(S.strokeStyle=j.strokeStyle),j.strokeWidth!==void 0&&(S.strokeWidth=j.strokeWidth)}const w=ao(p,t)||p,y=V.isShapeElement(t)?nr(e,w,t):void 0;let T;switch(r){case ft.right:T=3;break;case ft.bottom:T=0;break;case ft.left:T=1;break;case ft.top:T=2;break;default:T=3}const C=ge.getRectangleByPoints(S.points),v=ge.getEdgeCenterPoints(C)[T],x=ao(v,S)||v,O=nr(e,x,S),B=Mp(En.straight,[w,x],{marker:ir.none,connection:y,boundId:t.id},{marker:ir.arrow,connection:O,boundId:S.id},[],{});ue.insertNode(e,B,[e.children.length]),Ap(e,S),Uc(e);const X=S.id;setTimeout(()=>{const j=e.children.findIndex(D=>D.id===X),L=j>=0?e.children[j]:null;L&&(ii(e),Pi(e,L),fe.updatePointerType(e,vt.selection),ue.setNode(e,{_forceRender:Date.now()},[j]),ue.setNode(e,{_forceRender:void 0},[j]))},50)}function MM(e,t,n,i){var m;let s=100,r=100;const o=t,a=(m=o.source)==null?void 0:m.boundId;if(a){const b=e.children.find(S=>S.id===a);if(b&&V.isShapeElement(b)){const S=ge.getRectangleByPoints(b.points);s=S.width,r=S.height}}const c=[[n[0]-s/2,n[1]-r/2],[n[0]+s/2,n[1]+r/2]],u=uc(e,c,i);u.fill="#ffffff";const d=ge.getRectangleByPoints(u.points),h=ge.getEdgeCenterPoints(d),p=o.points||[];if(p.length>=2){const b=p[0],S=p[p.length-1],w=S[0]-b[0],y=S[1]-b[1];let T;Math.abs(w)>Math.abs(y)?T=w>0?3:1:T=y>0?0:2;const C=h[T],E=nr(e,C,u),v=e.children.findIndex(x=>x.id===t.id);v!==-1&&ue.setNode(e,{target:{marker:ir.arrow,connection:E,boundId:u.id},points:[b,C]},[v])}Ap(e,u),Uc(e);const g=u.id;setTimeout(()=>{const b=e.children.findIndex(w=>w.id===g),S=b>=0?e.children[b]:null;S&&(ii(e),Pi(e,S),fe.updatePointerType(e,vt.selection),ue.setNode(e,{_forceRender:Date.now()},[b]),ue.setNode(e,{_forceRender:void 0},[b]))},50)}const IM=e=>{const{pointerMove:t,pointerLeave:n,globalPointerUp:i}=e;let s=null,r=-1,o=e.children.length,a={x:0,y:0};return e.pointerMove=c=>{var C;a={x:c.clientX,y:c.clientY},s&&(clearTimeout(s),s=null);const u=kp(e),d=u.length===1&&u[0],h=To(e);if(!d||!V.isShapeElement(d)||V.isText(d)){if(h.visible&&h.mode==="hover"&&zs(e,{...wo}),r=-1,d&&V.isShapeElement(d)&&!Qi.getElementRef(d))return;t(c);return}if(!Qi.getElementRef(d)){r=-1;return}const g=Vy(e,c.x,c.y),m=Uy(e,d,!0),b=Wy(e,g,d,!0)||g,S=$y(b,m),w=m[S];if(w){if(S!==r||!h.visible){r=S;const E=c.clientX,v=c.clientY;s=setTimeout(()=>{const x=V.isImage(d)?Pe.rectangle:d.shape||Pe.rectangle;zs(e,{visible:!0,position:{x:E-140,y:v+20},sourceElement:d,currentShape:x,hitIndex:S,hitPoint:w,mode:"hover"})},50)}}else r=-1,h.visible&&h.mode==="hover"&&(s=setTimeout(()=>{const E=To(e);E.visible&&E.mode==="hover"&&zs(e,{...wo})},300));const y=Qi.getElementRef(d);(C=y==null?void 0:y.getGenerator)!=null&&C.call(y,Xy.key)&&t(c)},e.pointerLeave=c=>{s&&(clearTimeout(s),s=null),n(c)},e.globalPointerUp=c=>{var d;i(c);const u=e.children.length;if(u>o){const h=e.children[u-1];if(V.isArrowLine(h)){const p=h;if(!((d=p.target)==null?void 0:d.boundId)){const m=p.points||[];if(m.length>=2){const b=m[m.length-1];setTimeout(()=>{zs(e,{visible:!0,position:{x:a.x-140,y:a.y+20},sourceElement:null,currentShape:Pe.rectangle,hitIndex:-1,hitPoint:null,mode:"arrowLine",arrowLineElement:h,arrowLineEndPoint:b})},50)}}}}o=e.children.length},e},Ds=100;function DM(e){switch(e){case"ArrowRight":return ft.right;case"ArrowDown":return ft.bottom;case"ArrowLeft":return ft.left;case"ArrowUp":return ft.top;default:return null}}function NM(e){switch(e){case ft.top:return 0;case ft.right:return 1;case ft.bottom:return 2;case ft.left:return 3;default:return 1}}function RM(e){return(e+2)%4}function jM(e,t,n,i,s,r){const o={x:t-i/2,y:n-s/2,width:i,height:s};for(const a of e.children)if(a.id!==r&&V.isDrawElement(a)&&!V.isArrowLine(a))try{const c=ge.getRectangleByPoints(a.points);if(o.x<c.x+c.width&&o.x+o.width>c.x&&o.y<c.y+c.height&&o.y+o.height>c.y)return!0}catch{}return!1}function LM(e,t,n){const i=ge.getRectangleByPoints(t.points),s=i.width,r=i.height,o=i.x+s/2,a=i.y+r/2;let c,u;switch(n){case ft.right:c=o+s/2+Ds+s/2,u=a;break;case ft.bottom:c=o,u=a+r/2+Ds+r/2;break;case ft.left:c=o-s/2-Ds-s/2,u=a;break;case ft.top:c=o,u=a-r/2-Ds-r/2;break;default:c=o+s/2+Ds+s/2,u=a}let d=0;const h=n===ft.right||n===ft.left?r+20:s+20;for(;jM(e,c,u,s,r,t.id)&&(d+=h,n===ft.right||n===ft.left?u=a+d:c=o+d,!(d>1e3)););const p=[[c-s/2,u-r/2],[c+s/2,u+r/2]],m=t.shape||"rectangle",b=uc(e,p,m);if(b.fill="#ffffff",V.isShapeElement(t)&&!V.isText(t)){const D=t;D.fill&&D.fill!=="none"&&(b.fill=D.fill),D.strokeColor!==void 0&&(b.strokeColor=D.strokeColor),D.strokeWidth!==void 0&&(b.strokeWidth=D.strokeWidth)}const S=NM(n),w=RM(S),T=ge.getEdgeCenterPoints(i)[S],C=ao(T,t)||T,E=V.isShapeElement(t)?nr(e,C,t):void 0,v=ge.getRectangleByPoints(b.points),O=ge.getEdgeCenterPoints(v)[w],B=ao(O,b)||O,X=nr(e,B,b),j=Mp(En.elbow,[C,B],{marker:ir.none,connection:E,boundId:t.id},{marker:ir.arrow,connection:X,boundId:b.id},[],{});ue.insertNode(e,j,[e.children.length]),ue.insertNode(e,b,[e.children.length]);const L=b.id;setTimeout(()=>{const D=e.children.find(k=>k.id===L);D&&(ii(e),Pi(e,D),fe.updatePointerType(e,vt.selection),Ip(e,[c,u]))},50)}function OM(e,t){var s,r,o,a;const n=[],i=[];for(const c of e.children){if(!V.isArrowLine(c))continue;const u=c;if(((s=u.source)==null?void 0:s.boundId)===t.id&&((r=u.target)!=null&&r.boundId)){const d=e.children.find(h=>h.id===u.target.boundId);d&&i.push(d)}if(((o=u.target)==null?void 0:o.boundId)===t.id&&((a=u.source)!=null&&a.boundId)){const d=e.children.find(h=>h.id===u.source.boundId);d&&n.push(d)}}return{incoming:n,outgoing:i}}function BM(e,t,n){const{incoming:i,outgoing:s}=OM(e,t),r=n?[...s,...i]:[...i,...s];if(r.length===0)return!1;const o=r[0];ii(e),Pi(e,o);try{const a=Ft(e,[o],!1),c=a.x+a.width/2,u=a.y+a.height/2;Ip(e,[c,u])}catch{}return!0}const HM=e=>{const{keyDown:t}=e;return e.keyDown=n=>{if(!n.altKey&&!n.metaKey&&!n.ctrlKey){if(!n.shiftKey){const i=DM(n.key);if(i!==null){const s=kp(e);if(s.length===1){const r=s[0];if(V.isShapeElement(r)&&!V.isText(r)&&!V.isImage(r)){LM(e,r,i),n.preventDefault();return}}}}if(n.key==="Tab"){const i=He(e);if(i.length===1){const s=i[0];if(V.isDrawElement(s)&&V.isShapeElement(s)&&BM(e,s,!n.shiftKey)){n.preventDefault();return}}}}t(n)},e},FM=240,GM=new Set(["5","7"]);function zM(e,t,n){const i=n*Math.PI/180,s=Math.cos(i),r=Math.sin(i),o=e[0]-t[0],a=e[1]-t[1];return[t[0]+o*s-a*r,t[1]+o*r+a*s]}function VM(e,t,n=0){const i=ge.getCenterPoint(e),r=Ni(e,ci).filter(o=>GM.has(String(o.handle)));if(n){const o=zM(t,i,-n),a=r.find(c=>ge.isHit(ge.getRectangleByPoints([o,o]),c.rectangle));return a&&(a.cursorClass=Uo(a.cursorClass,n)),a}return r.find(o=>ge.isHit(ge.getRectangleByPoints([t,t]),o.rectangle))}function UM(e){const t=He(e);return t.length===1&&Kn(t[0])}function WM(e,t){const n=He(e);if(n.length!==1||!Kn(n[0]))return null;const i=n[0],s=ge.getRectangleByPoints(i.points),r=VM(s,t,0);return r?{element:i,rectangle:s,handle:r.handle,cursorClass:r.cursorClass}:null}function $M(e,t,n,i){const s=e.width/e.height,r=t==="7",o=r?-n:n,a=Math.max(FM,e.width+o),c=a/s,u=(e.height-c)/2;return{x:r?e.x+(e.width-a):e.x,y:e.y+u,width:a,height:c}}function XM(e,t,n){const{element:i,rectangle:s,handle:r}=t,{startPoint:o,endPoint:a}=n;if(!s)return;const c=a[0]-o[0];a[1]-o[1];const u=$M(s,r,c),d=[[u.x,u.y],[u.x+u.width,u.y+u.height]],h=e.children.findIndex(p=>p.id===i.id);h>=0&&ue.setNode(e,{points:d},[h])}const KM=e=>Di(e,{key:"audio-nodes",canResize:()=>UM(e),hitTest:(t=>WM(e,t)),onResize:(t,n)=>XM(e,t,n)}),YM=[{icon:l.jsx(Jf,{}),title:"Rectangle",pointer:Pe.rectangle},{icon:l.jsx(ep,{}),title:"Ellipse",pointer:Pe.ellipse},{icon:l.jsx(tp,{}),title:"Triangle",pointer:Pe.triangle},{icon:l.jsx(np,{}),title:"Terminal",pointer:ec.terminal},{icon:l.jsx(ip,{}),title:"Diamond",pointer:Pe.diamond},{icon:l.jsx(sp,{}),title:"Parallelogram",pointer:Pe.parallelogram},{icon:l.jsx(rp,{}),title:"RoundRectangle",pointer:Pe.roundRectangle}],qM=({visible:e,position:t,currentShape:n,onSelectShape:i,onClose:s,container:r})=>{const o=f.useRef(null);f.useEffect(()=>{if(!e)return;const p=b=>{o.current&&!o.current.contains(b.target)&&s()},g=b=>{b.key==="Escape"&&s()},m=setTimeout(()=>{document.addEventListener("mousedown",p),document.addEventListener("keydown",g)},50);return()=>{clearTimeout(m),document.removeEventListener("mousedown",p),document.removeEventListener("keydown",g)}},[e,s]);const a=f.useCallback(p=>{i(p)},[i]);if(!e)return null;const c={x:isNaN(t.x)?0:t.x,y:isNaN(t.y)?0:t.y},u=200,d=80;typeof window<"u"&&(c.x+u>window.innerWidth&&(c.x=window.innerWidth-u-10),c.y+d>window.innerHeight&&(c.y=t.y-d-20));const h=l.jsx("div",{ref:o,className:q("auto-complete-shape-picker",Dt),style:{left:c.x,top:c.y},children:l.jsx(qe,{padding:1,children:l.jsx(pt.Col,{gap:1,children:l.jsx(pt.Row,{gap:1,children:YM.map((p,g)=>l.jsx(ne,{className:q("shape-button",{"is-current":n===p.pointer}),type:"icon",size:"small",visible:!0,icon:p.icon,tooltip:p.title,"aria-label":p.title,onPointerDown:({event:m})=>{m.stopPropagation(),a(p.pointer)}},g))})})})});return r?Lo.createPortal(h,r):h},ZM={visible:!1,position:{x:0,y:0},sourceElement:null,currentShape:null,hitIndex:-1,hitPoint:null,mode:"hover"};function QM(e){const[t,n]=f.useState(ZM);f.useEffect(()=>{if(!e)return;n(To(e));const r=kM(e,o=>{n(o)});return()=>{r()}},[e]);const i=f.useCallback(r=>{if(!e)return;const o=To(e);o.mode==="arrowLine"?o.arrowLineElement&&o.arrowLineEndPoint&&MM(e,o.arrowLineElement,o.arrowLineEndPoint,r):o.sourceElement&&o.hitPoint&&o.hitIndex>=0&&AM(e,o.sourceElement,o.hitIndex,o.hitPoint,r)},[e]),s=f.useCallback(()=>{e&&Uc(e)},[e]);return{state:t,selectShape:i,closePicker:s}}const JM="#ffffff",eI=[Pe.rectangle,Pe.ellipse,Pe.triangle,Pe.diamond,Pe.parallelogram,Pe.roundRectangle];function Xh(e){if(!V.isGeometry(e)||V.isText(e)||V.isImage(e))return!1;const t=e;return!(!t.shape||!eI.includes(t.shape)||t.fill&&t.fill!=="none")}const tI=e=>{const{afterChange:t}=e,n=new Set;return e.afterChange=()=>{t();const i=[];e.children.forEach((s,r)=>{Xh(s)&&!n.has(s.id)&&(i.push({path:[r],element:s}),n.add(s.id))}),i.length>0&&setTimeout(()=>{i.forEach(({path:s})=>{const r=e.children[s[0]];r&&Xh(r)&&ue.setNode(e,{fill:JM},s)})},0)},e},vo=new WeakMap;let Ba=null,An=null;function zm(e,t){try{const n=Qi.getElementG(t);if(n)return n}catch{}if(t!=null&&t.id){const n=z.getElementHost(e);if(n){const i=n.querySelector(`g[id="${t.id}"]`);if(i)return i}}return null}function Vm(e){return e.querySelector("path, rect, ellipse, polygon, circle")}function Um(e){let t=e.querySelector("defs");return t||(t=Yy(),e.insertBefore(t,e.firstChild)),t}function nI(e,t){const n=vo.get(t);if(n){const i=e.querySelector(`#${n}`);i&&i.remove()}}function xo(e,t,n){const i=zm(e,t);if(!i)return;const s=Vm(i);if(!s)return;const r=i.closest("svg");if(!r)return;const o=Ft(e,[t],!1),a=(o==null?void 0:o.width)||100,c=(o==null?void 0:o.height)||100,u=Dp(n,t.id,a,c),d=Um(r);if(u.defElement){const h=u.defElement.id,p=d.querySelector(`#${h}`);p?p.replaceWith(u.defElement):d.appendChild(u.defElement),s.setAttribute("fill",u.fillValue),vo.set(t,h);const g=vo.get(t);if(g&&g!==h){const m=d.querySelector(`#${g}`);m&&m.remove()}}else s.setAttribute("fill",u.fillValue),nI(r,t)}function to(e,t){return e.children.find(n=>n.id===t)||null}function Dn(e){const t=e.fillConfig;return t&&Rn(t)?t:e.fill&&Rn(e.fill)?e.fill:null}function Wm(e,t){if(!e)return!1;if(e==="[object Object]")return!0;if(e.startsWith("url(#")){const n=e.match(/url\(#([^)]+)\)/);if(n){const i=n[1];if(!document.getElementById(i))return!0}return!1}if(t){const n=Dn(t);if(n&&(n.type==="gradient"||n.type==="image"))return!0}return!1}function iI(e){if(!An)return;const t=new Set;e.forEach(n=>{if(n.type==="attributes"&&n.attributeName==="fill"){const i=n.target,s=i.getAttribute("fill"),r=i.closest("g[id]");if(r){const o=r.getAttribute("id");if(o){const a=to(An,o),c=a?Dn(a):null;a&&c&&cn(An,a)&&Wm(s,a)&&t.add(a)}}}n.type==="childList"&&n.addedNodes.forEach(i=>{if(i instanceof SVGGElement&&i.hasAttribute("id")){const s=i.getAttribute("id");if(s){const r=to(An,s),o=r?Dn(r):null;r&&o&&cn(An,r)&&t.add(r)}}if(i instanceof Element){const s=i.closest("g[id]");if(s){const r=s.getAttribute("id");if(r){const o=to(An,r),a=o?Dn(o):null;o&&a&&cn(An,o)&&t.add(o)}}}})}),t.size>0&&t.forEach(n=>{const i=Dn(n);i&&xo(An,n,i)})}function sI(e){if(Ba)return;const t=z.getElementHost(e);t&&(An=e,Ba=new MutationObserver(iI),Ba.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["fill"]}))}function rI(e){const t=z.getElementHost(e);if(!t)return;t.querySelectorAll("path[fill], rect[fill], ellipse[fill], polygon[fill], circle[fill]").forEach(i=>{const s=i.getAttribute("fill"),r=i.closest("g[id]");if(r){const o=r.getAttribute("id");if(o){const a=to(e,o),c=a?Dn(a):null;a&&c&&cn(e,a)&&Wm(s,a)&&xo(e,a,c)}}})}function Nl(e,t=!1){e.children.forEach(n=>{const i=Dn(n);i&&cn(e,n)&&(t?xo(e,n,i):requestAnimationFrame(()=>{xo(e,n,i)}))}),t&&rI(e)}let Kh=!0;const Yh=new WeakSet;function $m(e){const t=z.getElementHost(e);if(!t)return;const n=t.closest("svg")||t.querySelector("svg");n&&e.children.forEach(i=>{const s=Dn(i);if(s&&(s.type==="gradient"||s.type==="image")&&cn(e,i)){const r=Ft(e,[i],!1),o=(r==null?void 0:r.width)||100,a=(r==null?void 0:r.height)||100,c=Dp(s,i.id,o,a);if(c.defElement){const u=Um(n);u.querySelector(`#${c.defElement.id}`)||(u.appendChild(c.defElement),vo.set(i,c.defElement.id))}}})}function oI(e){let t=0;return e.children.forEach(n=>{const i=Dn(n);if(i&&(i.type==="gradient"||i.type==="image")&&cn(e,n)){const s=zm(e,n);(s?Vm(s):null)||t++}}),t}function aI(e){if(Yh.has(e))return;Yh.add(e);const t=15,n=16;let i=0;const s=()=>{i++;try{if(!z.getElementHost(e))return;if($m(e),Nl(e,!0),oI(e)>0&&i<t){const a=Math.min(n*Math.pow(1.5,i),500);setTimeout(s,a)}}catch{}};requestAnimationFrame(()=>{s(),setTimeout(s,0)})}const lI=e=>{const{afterChange:t}=e;return e.afterChange=()=>{t(),sI(e),$m(e),Kh?(Kh=!1,Nl(e,!0),aI(e)):Nl(e,!0)},e};function cI(e,t){return Ni(e,ci).find(i=>ge.isHit(ge.getRectangleByPoints([t,t]),i.rectangle))}function uI(e){const t=He(e);return t.length!==1?!1:Ti(t[0])}function dI(e,t){const n=He(e);if(n.length!==1||!Ti(n[0]))return null;const i=n[0],s=ge.getRectangleByPoints(i.points),r=cI(s,t);return r?{element:i,rectangle:s,handle:r.handle,cursorClass:r.cursorClass}:null}function hI(e,t,n){const{element:i,rectangle:s,handle:r}=t;if(!s)return;const{startPoint:o,endPoint:a}=n,c=a[0]-o[0],u=a[1]-o[1],d=bs(s,r,c,u,pr(),60),h=[[d.x,d.y],[d.x+d.width,d.y+d.height]],p=e.children.findIndex(g=>g.id===i.id);p>=0&&ue.setNode(e,{points:h},[p])}function fI(e,t){const{element:n}=t,i=e.children.find(s=>s.id===n.id);i&&qy.updateFrameMembers(e,i)}const pI=e=>Di(e,{key:"frame-elements",canResize:()=>uI(e),hitTest:t=>dI(e,t),onResize:(t,n)=>hI(e,t,n),afterResize:t=>fI(e,t)});function Ha(e){return!!e.locked}const gI=e=>{const{isHit:t,isRectangleHit:n,isMovable:i}=e;return e.isHit=(s,r,o)=>Ha(s)?!1:t(s,r,o),e.isRectangleHit=(s,r)=>Ha(s)?!1:n(s,r),e.isMovable=s=>Ha(s)?!1:i(s),e},Rl="aitu-tab-sync-version",mI=500,jl=`tab-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;function Xm({onSyncNeeded:e,enabled:t=!0,currentBoardId:n}){const i=f.useRef(-1),s=f.useRef();f.useEffect(()=>{if(!t)return;const r=localStorage.getItem(Rl);if(r)try{const o=JSON.parse(r);i.current=o.version}catch{i.current=parseInt(r,10)||Date.now()}else i.current=Date.now()},[t]),f.useEffect(()=>{if(!t)return;const r=()=>{const a=localStorage.getItem(Rl);if(a)try{const c=JSON.parse(a);if(c.version>i.current&&c.tabId!==jl){const u=n&&c.boardId&&c.boardId===n;i.current=c.version,u&&e()}else c.version>i.current&&c.tabId===jl&&(i.current=c.version)}catch{const c=parseInt(a,10);c>i.current&&(i.current=c)}};s.current=setInterval(()=>{document.hidden||r()},mI);const o=()=>{document.hidden||r()};return document.addEventListener("visibilitychange",o),()=>{s.current&&clearInterval(s.current),document.removeEventListener("visibilitychange",o)}},[t,e,n])}function Km(e){try{const n={version:Date.now(),tabId:jl,boardId:e};localStorage.setItem(Rl,JSON.stringify(n))}catch{}}const pN=Object.freeze(Object.defineProperty({__proto__:null,markTabSyncVersion:Km,useTabSync:Xm},Symbol.toStringTag,{value:"Module"})),Fa=new Set;function SI(){const e=typeof navigator<"u"?navigator.connection:void 0;return e?e.saveData?!1:e.effectiveType!=="slow-2g"&&e.effectiveType!=="2g":!0}function bI(e){if(typeof window>"u"||!("serviceWorker"in navigator)||e.length===0||!SI())return;const t=e.filter(r=>Fa.has(r)?!1:(Fa.add(r),!0));if(t.length===0)return;const n={type:"SW_PREFETCH_GROUPS",groups:t},i=()=>{const r=navigator.serviceWorker.controller;if(r){r.postMessage(n);return}navigator.serviceWorker.ready.then(o=>{var a;(a=o.active)==null||a.postMessage(n)}).catch(()=>{t.forEach(o=>Fa.delete(o))})},s=window.requestIdleCallback;typeof s=="function"?s(()=>i(),{timeout:1500}):window.setTimeout(i,400)}const yI=f.lazy(()=>Ne(()=>import("./DeferredAIInputBar-CNAPl6C2.js"),__vite__mapDeps([0,4,5,6,7,8,9]),import.meta.url).then(e=>({default:e.DeferredAIInputBar}))),wI=f.lazy(()=>Ne(()=>import("./index-BakDREx4.js"),__vite__mapDeps([0,4,5,10]),import.meta.url).then(e=>({default:e.ChatDrawer}))),Xn=["tool-runtime"],Or=["tool-drawers"],Ga=["tool-dialogs"],qh=["tool-runtime","tool-drawers","tool-dialogs"],TI=f.lazy(()=>Ne(()=>import("./DrawnixDeferredFeatures-BrhbEEBa.js"),__vite__mapDeps([0,11]),import.meta.url).then(e=>({default:e.DrawnixDeferredFeatures}))),vI=f.lazy(()=>Ne(()=>import("./tool-windows-hjm6YiPY.js").then(e=>e.p3),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.DrawnixDeferredRuntime}))),xI=f.lazy(()=>Ne(()=>import("./ttd-dialog-CqISZ7cy.js"),__vite__mapDeps([0,4,6,7,8,2,3,12,13]),import.meta.url).then(e=>({default:e.TTDDialog}))),EI=f.lazy(()=>Ne(()=>import("./settings-dialog-Bueh6yYA.js"),__vite__mapDeps([0,4,6,14]),import.meta.url).then(e=>({default:e.SettingsDialog}))),_I=f.lazy(()=>Ne(()=>import("./tool-windows-hjm6YiPY.js").then(e=>e.oZ),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.UnifiedMediaViewer}))),CI=f.lazy(()=>Ne(()=>import("./CanvasAudioPlayer-Du5kXrAd.js"),__vite__mapDeps([0,15]),import.meta.url).then(e=>({default:e.CanvasAudioPlayer}))),PI=[],kI=({value:e,viewport:t,theme:n,onChange:i,onSelectionChange:s,onViewportChange:r,onThemeChange:o,onValueChange:a,afterInit:c,onBoardSwitch:u,onTabSyncNeeded:d,isDataReady:h=!1,currentBoardId:p})=>{const g={readonly:!1,hideScrollbar:!1,disabledScrollOnNonFocus:!1,themeColors:Sw},[m,b]=f.useState(()=>{const ie=new r_(window.navigator.userAgent);return{pointer:vt.hand,isMobile:ie.mobile()!==null,isPencilMode:!1,openDialogTypes:new Set,dialogInitialData:null,dialogInitialDataByType:{},openCleanConfirm:!1,openSettings:!1}}),[S,w]=f.useState(null),[y,T]=f.useState(!1),[C,E]=f.useState(!1),[v,x]=f.useState(!1),[O,B]=f.useState(!1),[X,j]=f.useState({mode:ni.BROWSE}),[L,D]=f.useState(!1),[k,N]=f.useState(!1),[M,Z]=f.useState(!1),[he,R]=f.useState(!1),[W,ce]=f.useState(!1),[K,ae]=f.useState(!1),[le,me]=f.useState(!1),Te=f.useRef(null),ze=f.useCallback(()=>{T(!1),E(!1),x(!1),B(!1)},[]),Y=f.useCallback((ie=PI)=>{bI(ie),Z(!0)},[]),Ie=f.useCallback((ie=qh)=>{Y(ie),me(!0),ae(!0)},[Y]),$e=f.useCallback(()=>{Ie([...Xn,...Or]),Promise.all([Ne(()=>import("./tool-windows-hjm6YiPY.js").then(ie=>ie.oP),__vite__mapDeps([0]),import.meta.url),Ne(()=>import("./tool-windows-hjm6YiPY.js").then(ie=>ie.oO),__vite__mapDeps([0]),import.meta.url)]).then(([{toolWindowService:ie},{BUILT_IN_TOOLS:De}])=>{const Le=De.find(Fe=>Fe.id==="knowledge-base");if(!Le)return;const ke=ie.getToolState(Le.id);ke&&ke.status==="open"?ie.closeTool(Le.id):ie.openTool(Le)})},[Ie]);f.useEffect(()=>{const ie=De=>{const{noteId:Le}=De.detail;Ie([...Xn,...Or]),Promise.all([Ne(()=>import("./tool-windows-hjm6YiPY.js").then(ke=>ke.oP),__vite__mapDeps([0]),import.meta.url),Ne(()=>import("./tool-windows-hjm6YiPY.js").then(ke=>ke.oO),__vite__mapDeps([0]),import.meta.url)]).then(([{toolWindowService:ke},{BUILT_IN_TOOLS:Fe}])=>{const Nt=Fe.find(Rt=>Rt.id==="knowledge-base");if(!Nt)return;const Pt=ke.isToolOpen(Nt.id);ke.openTool(Nt,{componentProps:Le?{initialNoteId:Le}:{}}),Pt&&Le&&window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("kb:open-note",{detail:{noteId:Le}}))},50)})};return window.addEventListener("kb:open",ie),()=>window.removeEventListener("kb:open",ie)},[Ie]);const it=f.useCallback(()=>{if(Ie([...Xn,...Or]),y){T(!1);return}E(!1),x(!1),B(!1),T(!0)},[Ie,y]),Ye=f.useCallback(()=>{if(Ie([...Xn,...Or]),C){E(!1);return}T(!1),x(!1),B(!1),E(!0)},[Ie,C]),P=f.useCallback(()=>{if(Y(Xn),v){x(!1);return}T(!1),E(!1),B(!1),x(!0)},[Y,v]),A=f.useCallback(ie=>{Ie([...Xn,...Ga]),ze(),j({mode:ni.BROWSE,...ie}),B(!0)},[ze,Ie]),$=f.useCallback(()=>{Y([...Xn,...Ga]),D(!0)},[Y]),Q=f.useCallback(()=>{Y([...Xn,...Ga]),N(!0)},[Y]),I=f.useCallback(ie=>{b(ie)},[]),H=f.useCallback(ie=>{b(De=>({...De,...ie}))},[]);f.useEffect(()=>{S&&(S.appState=m,S.__setAppState=I,Te.current=S)},[S,m,I]),f.useEffect(()=>{if(new URLSearchParams(window.location.search).has("tool")){Ie(qh);return}},[Ie]),f.useEffect(()=>{if(typeof window>"u"||!("serviceWorker"in navigator))return;let ie=!1;const De=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1",Le=Pt=>{var Rt,jt;((Rt=Pt.data)==null?void 0:Rt.type)==="SW_IDLE_PREFETCH_STATUS"&&(jt=Pt.data.completedGroups)!=null&&jt.includes("tool-drawers")&&(ie=!0,me(!0))};navigator.serviceWorker.addEventListener("message",Le);const ke={type:"SW_IDLE_PREFETCH_STATUS_GET"},Fe=navigator.serviceWorker.controller;Fe?Fe.postMessage(ke):navigator.serviceWorker.ready.then(Pt=>{var Rt;(Rt=Pt.active)==null||Rt.postMessage(ke)}).catch(()=>{});const Nt=window.setTimeout(()=>{ie||le||(De?console.info("[Drawnix] SW idle prefetch status unresolved in dev, enabling minimized tools bar fallback"):console.warn("[Drawnix] SW idle prefetch status unresolved, enabling minimized tools bar fallback"),me(!0))},2200);return()=>{window.clearTimeout(Nt),navigator.serviceWorker.removeEventListener("message",Le)}},[le]),f.useEffect(()=>{const ie=window.requestIdleCallback;let De;const Le=window.setTimeout(()=>{const ke=()=>{R(!0),ce(!0)};if(typeof ie=="function"){De=ie(ke,{timeout:2500});return}ke()},5e3);return()=>{var ke;window.clearTimeout(Le),typeof De=="number"&&((ke=window.cancelIdleCallback)==null||ke.call(window,De))}},[]),f.useEffect(()=>{const ie=De=>{const Le=De,{message:ke}=Le.detail;oe.error({content:"API Key 无效或已过期,请重新配置",duration:5e3}),console.error("[Drawnix] API auth error:",ke),b(Fe=>({...Fe,openSettings:!0}))};return window.addEventListener(Mu,ie),()=>{window.removeEventListener(Mu,ie)}},[]);const F=[sw,rw,ow,o_,X_,bk(H),Zk,lA,uM,rM,cA(H),CA(H),aw,lw,KA,cw,uw,dw,IM,HM,hw,pI,fw,pw,gw,KM,tI,lI,mw,gI,FA,zA],U=f.useRef(null),{saveBoard:te,createBoard:ee,switchBoard:G}=Zy(),J=f.useCallback(async()=>{if(i&&Te.current){const ie={children:Te.current.children||[],viewport:Te.current.viewport,theme:Te.current.theme};await te(ie)}},[i,te]),se=f.useCallback(async()=>{await J();const ie=await ee({name:"新画布"});ie&&(await G(ie.id),setTimeout(()=>{vi()},500))},[J,ee,G]),Re=f.useCallback(ie=>{const De=Te.current;if(De&&ie){const ke=He(De).map(Fe=>Fe.id).filter(Boolean);H({lastSelectedElementIds:ke})}s&&s(ie)},[s,H]),ut=f.useMemo(()=>({appState:m,setAppState:I,board:S}),[m,I,S]),Oe=he||W||K||m.openCommandPalette||m.openCanvasSearch||y||C||O||L||k;return l.jsx(Qy,{children:l.jsx(Jy,{children:l.jsx(ew,{children:l.jsx(tw,{children:l.jsx(nw,{children:l.jsx(PM,{onOpenMediaLibrary:A,children:l.jsx(gM,{children:l.jsx(iw.Provider,{value:ut,children:l.jsx(AI,{value:e,viewport:t,theme:n,options:g,plugins:F,containerRef:U,appState:m,board:S,setBoard:w,projectDrawerOpen:y,toolboxDrawerOpen:C,taskPanelExpanded:v,mediaLibraryOpen:O,mediaLibraryConfig:X,backupRestoreOpen:L,onChange:i,onSelectionChange:Re,onViewportChange:r,onThemeChange:o,onValueChange:a,afterInit:c,onBoardSwitch:u,onTabSyncNeeded:d,handleProjectDrawerToggle:it,handleToolboxDrawerToggle:Ye,handleKnowledgeBaseToggle:$e,handleTaskPanelToggle:P,handleOpenMediaLibrary:A,handleOpenBackupRestore:$,handleOpenCloudSync:Q,setProjectDrawerOpen:T,setToolboxDrawerOpen:E,setMediaLibraryOpen:B,setBackupRestoreOpen:D,cloudSyncOpen:k,setCloudSyncOpen:N,handleBeforeSwitch:J,isDataReady:h,onCreateProjectForMemory:se,currentBoardId:p,deferredRuntimeEnabled:M,shouldRenderDeferredFeatures:Oe,versionUpdateEnabled:he,performancePanelEnabled:W,toolWindowManagerEnabled:K,minimizedToolsBarEnabled:le,enableToolWindows:Ie})})})})})})})})})},AI=({value:e,viewport:t,theme:n,options:i,plugins:s,containerRef:r,appState:o,board:a,setBoard:c,projectDrawerOpen:u,toolboxDrawerOpen:d,taskPanelExpanded:h,mediaLibraryOpen:p,mediaLibraryConfig:g,backupRestoreOpen:m,deferredRuntimeEnabled:b,shouldRenderDeferredFeatures:S,versionUpdateEnabled:w,performancePanelEnabled:y,toolWindowManagerEnabled:T,minimizedToolsBarEnabled:C,enableToolWindows:E,cloudSyncOpen:v,onChange:x,onSelectionChange:O,onViewportChange:B,onThemeChange:X,onValueChange:j,afterInit:L,onBoardSwitch:D,onTabSyncNeeded:k,handleProjectDrawerToggle:N,handleToolboxDrawerToggle:M,handleKnowledgeBaseToggle:Z,handleTaskPanelToggle:he,handleOpenMediaLibrary:R,handleOpenBackupRestore:W,handleOpenCloudSync:ce,setProjectDrawerOpen:K,setToolboxDrawerOpen:ae,setMediaLibraryOpen:le,setBackupRestoreOpen:me,setCloudSyncOpen:Te,handleBeforeSwitch:ze,isDataReady:Y,onCreateProjectForMemory:Ie,currentBoardId:$e})=>{const{setAppState:it}=Ut(),{chatDrawerRef:Ye}=Fm(),{language:P}=Ee(),A=Iu(Se=>Se.error),$=Iu(Se=>Se.playing||!!Se.activeAudioUrl||!!Se.activeReadingSourceId),Q=f.useRef(void 0),[I,H]=f.useState($);pA({board:a,pointer:o.pointer}),Xm({onSyncNeeded:f.useCallback(()=>{k?k():vi()},[k]),enabled:!0,currentBoardId:$e});const[F,U]=f.useState(!1),[te,ee]=f.useState(null),[G,J]=f.useState(null),se=f.useRef(null),[Re,ut]=f.useState(!1),[Oe,ie]=f.useState([]),[De,Le]=f.useState(0);f.useEffect(()=>{if(!A){Q.current=void 0;return}A!==Q.current&&(Q.current=A,oe.error(A))},[A]),f.useEffect(()=>{$&&H(!0)},[$]),f.useEffect(()=>{Sa.setCanvasQueue(Qa(e))},[e]),f.useEffect(()=>()=>{Sa.stopAndClear()},[]);const ke=f.useCallback(()=>{if(!a||!a.children)return{items:[],elementIds:[]};const Se=[],Ve=[];for(const be of a.children){const je=be.url;if(!je||typeof je!="string"||ba(be))continue;const st=V.isDrawElement(be)&&V.isImage(be),Ue=wn(be);(st||Ue)&&(Se.push({id:be.id,url:je,type:Ue?"video":"image",title:be.name||void 0}),Ve.push(be.id))}return{items:Se,elementIds:Ve}},[a]),Fe=f.useCallback(Se=>{const{items:Ve,elementIds:be}=ke();if(Ve.length===0)return;const je=be.indexOf(Se);je!==-1&&(ie(Ve),Le(je),ut(!0))},[ke]),Nt=f.useCallback(()=>{ut(!1)},[]),Pt=f.useCallback(async(Se,Ve)=>{const be=Ve.id;if(!(!be||!a))try{const{unifiedCacheService:je}=await Ne(async()=>{const{unifiedCacheService:dt}=await import("./tool-windows-hjm6YiPY.js").then(dn=>dn.oG);return{unifiedCacheService:dt}},__vite__mapDeps([0]),import.meta.url),{Transforms:st}=await Ne(async()=>{const{Transforms:dt}=await import("./tool-windows-hjm6YiPY.js").then(dn=>dn.oE);return{Transforms:dt}},__vite__mapDeps([0]),import.meta.url),Ue=`edited-image-${Date.now()}`,Ge=`/__aitu_cache__/image/${Ue}.png`,gt=await(await fetch(Se)).blob();await je.cacheMediaFromBlob(Ge,gt,"image",{taskId:Ue});const kt=new Image;await new Promise((dt,dn)=>{kt.onload=()=>dt(),kt.onerror=()=>dn(new Error("Failed to load edited image")),kt.src=Se});const Lt=a.children.findIndex(dt=>dt.id===be);if(Lt>=0){const dt=a.children[Lt],{newPoints:dn}=await Gf({url:dt.url,width:dt.width,height:dt.height,points:dt.points||[[0,0],[0,0]]},kt.naturalWidth,kt.naturalHeight);st.setNode(a,{url:Ge,width:kt.naturalWidth,height:kt.naturalHeight,points:dn},[Lt])}}catch(je){console.error("Failed to update image:",je),oe.error("更新失败")}},[a]),Rt=f.useCallback(async Se=>{if(a)try{const{unifiedCacheService:Ve}=await Ne(async()=>{const{unifiedCacheService:Lt}=await import("./tool-windows-hjm6YiPY.js").then(dt=>dt.oG);return{unifiedCacheService:Lt}},__vite__mapDeps([0]),import.meta.url),{insertImageFromUrl:be}=await Ne(async()=>{const{insertImageFromUrl:Lt}=await import("./tool-windows-hjm6YiPY.js").then(dt=>dt.oK);return{insertImageFromUrl:Lt}},__vite__mapDeps([0]),import.meta.url),je=`edited-image-${Date.now()}`,st=`/__aitu_cache__/image/${je}.png`,Ge=await(await fetch(Se)).blob();await Ve.cacheMediaFromBlob(st,Ge,"image",{taskId:je});const rt=new Image;await new Promise((Lt,dt)=>{rt.onload=()=>Lt(),rt.onerror=()=>dt(new Error("Failed to load edited image")),rt.src=Se});const gt=Ao(a),kt=[((gt==null?void 0:gt[0])??0)+100,((gt==null?void 0:gt[1])??0)+100];await be(a,st,kt,!1,{width:rt.naturalWidth,height:rt.naturalHeight},!1,!0)}catch(Ve){console.error("Failed to insert image:",Ve),oe.error("插入失败")}},[a]),{state:jt,selectShape:nn,closePicker:di}=QM(a);f.useEffect(()=>{G&&se.current&&se.current.focus()},[G]);const Un=f.useCallback(()=>{if(!a||!G||!se.current){J(null);return}const Se=se.current.innerText||"";Se.trim()&&(Mo.insertText(a,G.worldPoint,Se),requestAnimationFrame(()=>{const Ve=a.children[a.children.length-1];if(V.isText(Ve)){const be=Ve;if(!isFinite(be.textHeight)){const je=ge.getRectangleByPoints(be.points);ue.setNode(a,{textHeight:je.height},[a.children.length-1])}}})),J(null),fe.updatePointerType(a,vt.selection),it(Ve=>({...Ve,pointer:vt.selection}))},[a,G,it]);return f.useEffect(()=>{if(!a)return;const Se=be=>{const je=be.target;if(!(je.closest(".board-host-svg")||je.closest(".plait-board-container")))return;const Ue=Gt(a,zt(a,be.clientX,be.clientY)),Ge=Za(a,Ue);if(Ge&&Mt(Ge)){Qg(a,Ge,P),be.preventDefault(),be.stopPropagation();return}if(Ge){if(ba(Ge)){be.preventDefault(),be.stopPropagation();return}const gt=Ge.url;if(gt&&typeof gt=="string"){const kt=V.isDrawElement(Ge)&&V.isImage(Ge),Lt=wn(Ge);if(kt||Lt){Fe(Ge.id),be.preventDefault(),be.stopPropagation();return}}}const rt=je.closest(".plait-tool-container")||je.closest(".plait-workzone-container")||je.closest("foreignObject");if(!Ge&&!rt){const gt=[be.clientX,be.clientY];ee(gt),U(!0)}},Ve=r.current;return Ve&&Ve.addEventListener("dblclick",Se),()=>{Ve&&Ve.removeEventListener("dblclick",Se)}},[a,r,Fe,P]),f.useEffect(()=>{if(!a)return;const Se=be=>{const je=be.target;if(!(je.closest(".board-host-svg")||je.closest(".plait-board-container")))return;const Ue=Gt(a,zt(a,be.clientX,be.clientY)),Ge=Za(a,Ue);if(Ge&&ba(Ge)&&!Kn(Ge)){H(!0);const rt=bw(Ge);if(rt){be.preventDefault(),be.stopPropagation(),Sa.togglePlaybackInQueue(rt,Qa(a.children),{queueSource:"canvas",queueId:Ff,queueName:Hf}).catch(()=>{});return}}if(z.isPointer(a,Pe.text)&&!(je.closest(".plait-tool-container")||je.closest(".plait-workzone-container")||je.closest("foreignObject"))&&!Ge){J({screenX:be.clientX,screenY:be.clientY,worldPoint:Ue,zoom:a.viewport.zoom}),be.preventDefault(),be.stopPropagation();return}u&&K(!1),d&&ae(!1)},Ve=r.current;return Ve&&Ve.addEventListener("click",Se),()=>{Ve&&Ve.removeEventListener("click",Se)}},[a,r,u,d,K,ae]),l.jsx("div",{className:q("drawnix",{"drawnix--mobile":o.isMobile}),ref:r,children:l.jsxs("div",{className:"drawnix__main",children:[l.jsxs(e_,{value:e,viewport:t,theme:n,options:i,plugins:s,onChange:Se=>{x&&x(Se)},onSelectionChange:O,onViewportChange:B,onThemeChange:X,onValueChange:j,children:[l.jsx(qE,{afterInit:Se=>{c(Se),window.__drawnixBoard=Se,L&&L(Se),Se.afterChange&&Se.afterChange()}}),l.jsx(fM,{}),l.jsx(Sk,{projectDrawerOpen:u,onProjectDrawerToggle:N,toolboxDrawerOpen:d,onToolboxDrawerToggle:M,taskPanelExpanded:h,onTaskPanelToggle:he,onOpenBackupRestore:W,onOpenCloudSync:ce,onKnowledgeBaseToggle:Z,onOpenMediaLibrary:R,deferredFeaturesEnabled:T,minimizedToolsBarEnabled:C,onEnableToolWindows:E}),I&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(CI,{})}),l.jsx(RP,{}),l.jsx(PA,{}),l.jsx(uA,{}),l.jsx(mA,{}),l.jsx(EA,{}),l.jsx(vA,{}),o.openDialogTypes.size>0&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(xI,{container:r.current})}),o.openSettings&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(EI,{container:r.current})}),l.jsx(_A,{container:r.current}),l.jsx(f.Suspense,{fallback:null,children:l.jsx(yI,{isDataReady:Y,activationKey:0})}),l.jsx(_M,{position:te,visible:F,onClose:()=>U(!1),onOpenMediaLibrary:R}),G&&l.jsx("div",{ref:se,contentEditable:!0,suppressContentEditableWarning:!0,style:{position:"fixed",left:G.screenX,top:G.screenY-14*G.zoom/2,minWidth:"2px",minHeight:"1.5em",outline:"none",border:"none",background:"transparent",fontSize:`${14*G.zoom}px`,lineHeight:"1.5",color:"#333",caretColor:"#333",zIndex:1e4,whiteSpace:"pre-wrap",fontFamily:"inherit"},onBlur:Un,onKeyDown:Se=>{Se.key==="Escape"&&J(null),Se.stopPropagation()}}),Re&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(_I,{visible:Re,items:Oe,initialIndex:De,onClose:Nt,showThumbnails:!0,useBuiltInEditor:!0,showEditOverwrite:!0,onEditOverwrite:Pt,onEditInsert:Rt})}),l.jsx(qM,{visible:jt.visible,position:jt.position,currentShape:jt.currentShape||void 0,onSelectShape:nn,onClose:di,container:r.current}),l.jsx(xM,{})]}),l.jsx(f.Suspense,{fallback:null,children:l.jsx(wI,{ref:Ye})}),b&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(vI,{board:a,value:e})}),S&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(TI,{board:a,value:e,containerRef:r,versionUpdateEnabled:w,performancePanelEnabled:y,toolWindowManagerEnabled:T,projectDrawerOpen:u,toolboxDrawerOpen:d,mediaLibraryOpen:p,mediaLibraryConfig:g,backupRestoreOpen:m,cloudSyncOpen:v,onBoardSwitch:D,setProjectDrawerOpen:K,setToolboxDrawerOpen:ae,setMediaLibraryOpen:le,setBackupRestoreOpen:me,setCloudSyncOpen:Te,handleBeforeSwitch:ze,onCreateProjectForMemory:Ie})})]})})},MI="Opentu",II="Opentu - AI应用平台";function Eo(e){e&&e.trim()?document.title=`${MI} - ${e.trim()}`:document.title=II}function DI(e){if(!e){Eo();return}const t=Np.getBoard(e);Eo(t==null?void 0:t.name)}function NI(e,t){return f.useEffect(()=>{DI(e)},[e,t]),f.useEffect(()=>{const i=Np.observeEvents().subscribe(s=>{if(s.type==="boardUpdated"){const r=s.payload;r&&r.id===e&&Eo(r.name)}});return()=>{i.unsubscribe()}},[e]),{updateTitle:f.useCallback(i=>{Eo(i)},[])}}const Ym="main_board_content",qm=Gr.createInstance({name:"Drawnix",storeName:yw,driver:[Gr.INDEXEDDB,Gr.LOCALSTORAGE]});async function Zm(){try{const e=await nl.loadState();return(e==null?void 0:e.migrationCompleted)===!0}catch(e){return console.error("[WorkspaceMigration] Failed to check migration status:",e),!1}}async function Zh(){try{const e=await nl.loadState();e.migrationCompleted=!0,await nl.saveState(e)}catch(e){console.error("[WorkspaceMigration] Failed to mark migration completed:",e)}}async function RI(){try{const e=await qm.getItem(Ym);if(e&&e.children&&e.children.length>0)return e;const t=localStorage.getItem(Rp);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 jI(){try{if(await Zm())return null;const t=await RI();if(!t||!t.children||t.children.length===0)return await Zh(),null;const n=bn.getInstance();await n.initialize();const i=await n.createBoard({name:"迁移的画板",elements:t.children,viewport:t.viewport,theme:t.theme});return i?(await n.switchBoard(i.id),await Zh(),await LI(),i.id):(console.error("[WorkspaceMigration] Failed to create board"),null)}catch(e){return console.error("[WorkspaceMigration] Migration failed:",e),null}}async function LI(){try{await qm.removeItem(Ym),localStorage.removeItem(Rp)}catch(e){console.error("[WorkspaceMigration] Failed to clear legacy data:",e)}}function Ns(e){if(!Yt.isAnalyticsEnabled())return;const t=OI(e.name,e.value),n=document.referrer,i={[`$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(()=>{Yt.track("$web_vitals",i)},0)}function OI(e,t){const i={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 i?t<=i.good?"good":t<=i.poor?"needs-improvement":"poor":"needs-improvement"}async function BI(){try{const e=await Ne(()=>import("./web-vitals-DcvjKPr-.js"),[],import.meta.url),{onCLS:t,onFCP:n,onLCP:i,onTTFB:s,onINP:r}=e;t(Ns),n(Ns),i(Ns),s(Ns),r(Ns)}catch(e){console.error("[Web Vitals] Failed to initialize monitoring:",e)}}const fr="page_report",HI="app_page_view";let Qh=!1,Jh="";function FI(){const e=window.innerWidth;return e<768?"mobile":e<1024?"tablet":"desktop"}const ef=200;function GI(){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:FI(),user_agent:e.length>ef?e.slice(0,ef):e,language:navigator.language,timestamp:Date.now()}}function zI(){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,i)=>n+(i.transferSize||0),0)}return e}function za(){if(!Yt.isAnalyticsEnabled())return;const e=GI();e.page_url!==Jh&&(Jh=e.page_url,Yt.track(HI,{category:fr,...e}))}function tf(){if(!Yt.isAnalyticsEnabled())return;const e=zI();if(!e){console.warn("[Page Report] Performance data not available");return}Yt.track("page_performance",{category:fr,...e})}function VI(){if(!Yt.isAnalyticsEnabled())return;const e=Math.round(performance.now());Yt.track("page_unload",{category:fr,page_url:window.location.href,page_path:window.location.pathname,time_on_page:e,timestamp:Date.now()})}function UI(){try{if(Qh)return;Qh=!0,za(),document.readyState==="complete"?tf():window.addEventListener("load",()=>{setTimeout(()=>{tf()},0)}),window.addEventListener("beforeunload",()=>{VI()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?Yt.track("page_hidden",{category:fr,page_url:window.location.href,page_path:window.location.pathname,timestamp:Date.now()}):document.visibilityState==="visible"&&Yt.track("page_visible",{category:fr,page_url:window.location.href,page_path:window.location.pathname,timestamp:Date.now()})}),window.addEventListener("popstate",()=>{setTimeout(()=>{za()},100)});const e=history.pushState;history.pushState=function(...t){e.apply(this,t),setTimeout(()=>{za()},100)}}catch(e){console.error("[Page Report] Failed to initialize monitoring:",e)}}function nf(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",".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 i of n)if(t.matches(i)||t.closest(i))return!0;if(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth){const i=window.getComputedStyle(t);if(i.overflowY==="auto"||i.overflowY==="scroll"||i.overflowX==="auto"||i.overflowX==="scroll")return!0}return!1}function sf(e){if(!e||!(e instanceof Element))return!1;const t=e,n=[".plait-board-container",".plait-board","[plait-board]","svg.rough-svg"];for(const i of n)if(t.matches(i)||t.closest(i))return!0;return!1}function WI(){if(typeof window>"u")return()=>{};const e=i=>{if(i.touches.length>1){const s=i.target;if(nf(s))return;sf(s)&&(i.preventDefault(),i.stopPropagation())}},t=i=>{const s=i.target;nf(s)||sf(s)&&(i.preventDefault(),i.stopPropagation())},n=i=>{(i.ctrlKey||i.metaKey)&&i.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 Ll=$o.DB_CLEANUP_DONE;function Qm(){let e=0;for(const t of jp)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 Jm(){localStorage.getItem(Ll)||(Qm(),localStorage.setItem(Ll,Date.now().toString()))}function $I(){localStorage.removeItem(Ll)}typeof window<"u"&&(window.__dbCleanup={run:Jm,reset:$I,cleanupLS:Qm,LS_KEYS_DEPRECATED:jp});const Wc=[{lsKey:At.PROMPT_HISTORY,idbKey:At.PROMPT_HISTORY,deleteAfterMigration:!0},{lsKey:At.VIDEO_PROMPT_HISTORY,idbKey:At.VIDEO_PROMPT_HISTORY,deleteAfterMigration:!0},{lsKey:At.PRESET_SETTINGS,idbKey:At.PRESET_SETTINGS,deleteAfterMigration:!0},{lsKey:At.BATCH_IMAGE_CACHE,idbKey:At.BATCH_IMAGE_CACHE,deleteAfterMigration:!0},{lsKey:At.RECENT_TEXT_COLORS,idbKey:At.RECENT_TEXT_COLORS,deleteAfterMigration:!0},{lsKey:At.CUSTOM_GRADIENTS,idbKey:At.CUSTOM_GRADIENTS,deleteAfterMigration:!0},{lsKey:At.CUSTOM_FONTS,idbKey:At.CUSTOM_FONTS,deleteAfterMigration:!0},{lsKey:At.TOOLBAR_CONFIG,idbKey:At.TOOLBAR_CONFIG,deleteAfterMigration:!0}];function $c(){try{return localStorage.getItem($o.LS_TO_IDB_MIGRATION_DONE)!==null}catch{return!1}}function XI(){try{localStorage.setItem($o.LS_TO_IDB_MIGRATION_DONE,Date.now().toString())}catch(e){console.error("[StorageMigration] Failed to mark migration done:",e)}}function KI(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 rf(e){try{localStorage.removeItem(e)}catch(t){console.warn(`[StorageMigration] Failed to delete ${e} from LocalStorage:`,t)}}async function YI(e){const{lsKey:t,idbKey:n,deleteAfterMigration:i}=e;try{const s=KI(t);return s===null?{key:t,success:!0}:await xn.get(n)!==null?(i&&rf(t),{key:t,success:!0}):(await xn.set(n,s),await xn.get(n)===null?{key:t,success:!1,error:"Verification failed: data not found after write"}:(i&&rf(t),{key:t,success:!0}))}catch(s){const r=s instanceof Error?s.message:String(s);return console.error(`[StorageMigration] Failed to migrate ${t}:`,s),{key:t,success:!1,error:r}}}async function e0(){if(!xn.isAvailable())return console.warn("[StorageMigration] IndexedDB not available, skipping migration"),[];if($c())return[];const e=[];for(const n of Wc){const i=await YI(n);e.push(i),i.success||console.warn(`[StorageMigration] Failed: ${i.key} - ${i.error}`)}return e.filter(n=>n.success).length,e.filter(n=>!n.success).length===0&&XI(),e}function t0(){try{localStorage.removeItem($o.LS_TO_IDB_MIGRATION_DONE)}catch(e){console.error("[StorageMigration] Failed to reset migration status:",e)}}const qI={isMigrationDone:$c,runMigration:e0,resetMigration:t0,MIGRATION_CONFIGS:Wc};typeof window<"u"&&(window.__storageMigration={run:e0,reset:t0,isDone:$c,configs:Wc});const Xt={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 ZI{constructor(){this.state={crashDetected:!1,crashCount:0,isSafeMode:!1,crashHistory:[]}}markLoadingStart(){try{localStorage.getItem(Xt.LOADING_STATE)==="loading"&&(this.state.crashDetected=!0,this.incrementCrashCount(),this.recordCrash()),localStorage.setItem(Xt.LOADING_STATE,"loading"),this.state.isSafeMode=localStorage.getItem(Xt.SAFE_MODE)==="true",this.loadCrashHistory()}catch(t){console.warn("[CrashRecovery] Failed to mark loading start:",t)}}markLoadingComplete(){try{localStorage.setItem(Xt.LOADING_STATE,"complete"),localStorage.setItem(Xt.LAST_SUCCESS_LOAD,Date.now().toString()),this.state.isSafeMode||(localStorage.setItem(Xt.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(Xt.CRASH_COUNT)||"0",10);this.state.crashCount=t+1,localStorage.setItem(Xt.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(Xt.CRASH_HISTORY);t&&(this.state.crashHistory=JSON.parse(t))}catch{this.state.crashHistory=[]}}saveCrashHistory(){try{localStorage.setItem(Xt.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(Xt.SAFE_MODE,"true"),this.state.isSafeMode=!0}catch{}}disableSafeMode(){try{localStorage.removeItem(Xt.SAFE_MODE),this.state.isSafeMode=!1,localStorage.setItem(Xt.CRASH_COUNT,"0"),this.state.crashCount=0}catch{}}clearCrashState(){try{localStorage.setItem(Xt.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=i=>i<1024*1024?`${(i/1024).toFixed(1)} KB`:i<1024*1024*1024?`${(i/1024/1024).toFixed(1)} MB`:`${(i/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 Kt=new ZI,QI=3e4,JI=800,eD=.6,tD=3,Xc="aitu_last_snapshot",nD=50,Xs=[],iD=20,sD=2e3;let Ks=null;const of=3e3,rD=1e4,oD=200,aD=5e3,lD=10,cD=5e3,uD=30,dD=20,af=20,hD=100,fD=30,pD=240;let lf=null,cf=!1,uf=null,df=null,Va=null,Ua=0,wi=60,Vs=!1,Wa=!1;const ei=[],ti=[],fn=[];function gD(e){const t=Ht(),n=Date.now();return()=>{const i=Ht();if(!t||!i)return;const s=(i.usedJSHeapSize-t.usedJSHeapSize)/(1024*1024),r=Date.now()-n;if(Math.abs(s)>=nD){const o=s>=0?"+":"";console.warn(`[MemoryLog] ${e}: ${o}${s.toFixed(0)} MB (${r}ms)`)}}}function pn(e){if(e)return e.slice(0,pD)}function mD(){return"0.6.63"}function SD(){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:pn(e.scriptURL),state:e.state}:null,readyState:document.readyState,visibilityState:document.visibilityState}}function bD(){const e=Array.from(document.scripts).map(i=>pn(jn(i.src))).filter(Boolean).slice(-8),t=Array.from(document.querySelectorAll('link[rel="stylesheet"]')).map(i=>pn(jn(i.href))).filter(Boolean).slice(-8),n=Array.from(document.querySelectorAll('link[rel="modulepreload"]')).map(i=>pn(jn(i.href))).filter(Boolean).slice(-8);return{scripts:e,stylesheets:t,modulePreloads:n}}function n0(e){if(!(e instanceof HTMLElement))return;const t=e;return{tagName:e.tagName.toLowerCase(),id:pn(e.id||void 0),className:typeof e.className=="string"?pn(e.className):void 0,src:pn(t.currentSrc||t.src?jn(t.currentSrc||t.src||""):void 0),href:pn(t.href?jn(t.href):void 0),rel:pn(t.rel),crossOrigin:pn(t.crossOrigin||void 0)}}function Ol(e){return{appVersion:mD(),recentActions:ei.slice(-10),recentErrors:ti.slice(-5),recentNetworkErrors:fn.slice(-5),serviceWorker:SD(),loadedResources:bD(),...e}}function Ht(){if(typeof performance<"u"&&"memory"in performance){const e=performance.memory;return{usedJSHeapSize:e.usedJSHeapSize,totalJSHeapSize:e.totalJSHeapSize,jsHeapSizeLimit:e.jsHeapSizeLimit}}}function ps(){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 i0(){if(!St.isInitialized()||Xs.length===0)return;const e=Xs.splice(0,Xs.length);for(const t of e)St.reportCrashSnapshot(t).catch(()=>{});Ks&&(clearInterval(Ks),Ks=null)}function yD(){Ks||(Ks=setInterval(()=>{St.isInitialized()&&i0()},sD))}function en(e){try{St.isInitialized()?(i0(),St.reportCrashSnapshot(e).catch(()=>{})):Xs.length<iD&&(Xs.push(e),yD())}catch(t){console.warn("[MemoryLog] Failed to send snapshot to SW:",t)}}function wD(e){try{localStorage.setItem(Xc,JSON.stringify(e))}catch{}}function TD(){try{const e=localStorage.getItem(Xc);if(e)return JSON.parse(e)}catch{}return null}function vD(){try{localStorage.removeItem(Xc)}catch{}}function xD(){const e={id:`startup-${Date.now()}`,timestamp:Date.now(),type:"startup",userAgent:navigator.userAgent,url:location.href,memory:Ht()};en(e)}function ED(){if(lf!==null)return;let e=0;lf=window.setInterval(()=>{const t=Ht();if(!t)return;const n=t.usedJSHeapSize/(1024*1024),i=t.jsHeapSizeLimit/(1024*1024),s=n/i;if(n>JI||s>eD){e++;const a=e>=tD?ps():void 0,c={id:`periodic-${Date.now()}`,timestamp:Date.now(),type:"periodic",memory:t,pageStats:a,userAgent:navigator.userAgent,url:location.href};en(c)}else e=0},QI)}function _D(){window.addEventListener("error",e=>{var n;if(e.error instanceof DOMException&&(e.error.name==="AbortError"||e.error.name==="NotAllowedError"))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:Ht(),userAgent:navigator.userAgent,url:location.href,customData:Ol({filename:e.filename,lineno:e.lineno,colno:e.colno,eventTarget:n0(e.target)})};en(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)||"",i=(t==null?void 0:t.stack)||"";if(t instanceof DOMException&&(t.name==="AbortError"||t.name==="NotAllowedError"||t.name==="DataError"&&n.includes("No key or key range specified"))||n.includes("posthog.com")||n.includes("sentry.io")||i.includes("posthog")||i.includes("sentry"))return;const s={id:`rejection-${Date.now()}`,timestamp:Date.now(),type:"error",error:{message:n||"Unhandled Promise rejection",stack:i,type:"unhandledRejection"},memory:Ht(),userAgent:navigator.userAgent,url:location.href,customData:Ol()};en(s),console.error("[MemoryLog] Unhandled rejection captured:",t)}),window.addEventListener("beforeunload",()=>{const e=Ht();if(e){const t={id:`beforeunload-${Date.now()}`,timestamp:Date.now(),type:"beforeunload",memory:e,userAgent:navigator.userAgent,url:location.href};wD(t),en(t)}})}function CD(){if(uf!==null)return;let e=Date.now();document.addEventListener("visibilitychange",()=>{document.hidden?Wa=!0:(e=Date.now(),setTimeout(()=>{Wa=!1},of+100))}),uf=window.setInterval(()=>{const t=Date.now(),n=t-e;if(n>rD&&!Wa&&!document.hidden){const i={id:`freeze-${Date.now()}`,timestamp:Date.now(),type:"freeze",memory:Ht(),pageStats:ps(),performance:{freezeDuration:n,lastHeartbeat:e,fps:wi},userAgent:navigator.userAgent,url:location.href,customData:{recentActions:ei.slice(-10),recentErrors:ti.slice(-5),recentNetworkErrors:fn.slice(-5)}};en(i)}e=t,St.isInitialized()&&St.sendHeartbeat(t).catch(()=>{})},of)}function PD(){if(Va===null&&!(typeof PerformanceObserver>"u"))try{Va=new PerformanceObserver(e=>{for(const t of e.getEntries())if(t.duration>oD){const i=t.attribution;let s;if(i&&i.length>0){const o=i[0];s={name:o.name,containerType:o.containerType,containerSrc:o.containerSrc,containerId:o.containerId,containerName:o.containerName}}const r={id:`longtask-${Date.now()}`,timestamp:Date.now(),type:"longtask",memory:Ht(),performance:{longTaskDuration:t.duration,fps:wi},userAgent:navigator.userAgent,url:location.href,customData:{taskName:t.name,startTime:t.startTime,attribution:s,debugTip:"Use Chrome DevTools Performance panel to record and analyze the call stack"}};en(r)}}),Va.observe({entryTypes:["longtask"]})}catch{}}function kD(){if(df!==null)return;let e=0;const t=()=>{if(e++,e>=fD){const n=performance.now(),i=n-Ua;i>0&&(wi=Math.round(e*1e3/i)),e=0,Ua=n}requestAnimationFrame(t)};Ua=performance.now(),requestAnimationFrame(t),df=window.setInterval(()=>{if(wi<lD&&wi>0){const n={id:`lowfps-${Date.now()}`,timestamp:Date.now(),type:"freeze",memory:Ht(),performance:{fps:wi},userAgent:navigator.userAgent,url:location.href};en(n)}},aD)}function AD(){setTimeout(()=>{hf()},cD),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&!Vs&&setTimeout(hf,1e3)})}function hf(){if(Vs)return;const e=document.getElementById("root"),t=e&&e.children.length>0,i=!!document.querySelector(".plait-board-container");if(document.body.children.length>1,e&&!t){Vs=!0;const s={id:`whitescreen-${Date.now()}`,timestamp:Date.now(),type:"whitescreen",memory:Ht(),pageStats:{domNodeCount:document.getElementsByTagName("*").length,canvasCount:0,imageCount:0,videoCount:0,iframeCount:0,plaitBoardExists:i},userAgent:navigator.userAgent,url:location.href,customData:{rootExists:!!e,rootChildCount:(e==null?void 0:e.children.length)||0,bodyChildCount:document.body.children.length,hasPlaitBoard:i}};en(s),console.error("[MemoryLog] 白屏检测: React 未渲染内容")}t&&!i&&location.pathname==="/"&&setTimeout(()=>{if(!document.querySelector(".plait-board-container")&&!Vs){Vs=!0;const s={id:`whitescreen-noboard-${Date.now()}`,timestamp:Date.now(),type:"whitescreen",memory:Ht(),pageStats:ps(),userAgent:navigator.userAgent,url:location.href,customData:{reason:"画板未加载",rootChildCount:(e==null?void 0:e.children.length)||0}};en(s),console.error("[MemoryLog] 白屏检测: 画板组件未加载")}},5e3)}function Us(e,t,n){ei.push({time:Date.now(),action:e,target:t,detail:n}),ei.length>uD&&ei.shift()}function MD(){let e=0;document.addEventListener("click",t=>{const n=Date.now();if(n-e<hD)return;e=n;const i=t.target;if(!i)return;const s=()=>{var a,c,u,d,h,p,g,m,b,S,w,y,T,C,E;let r="";const o=(c=(a=i.closest)==null?void 0:a.call(i,"[data-track]"))==null?void 0:c.getAttribute("data-track");if(o)r=o;else if(i.tagName==="BUTTON"||(u=i.closest)!=null&&u.call(i,"button")){const v=((d=i.closest)==null?void 0:d.call(i,"button"))||i,x=(h=v.textContent)==null?void 0:h.trim().slice(0,20),O=(b=(m=(g=(p=v.className)==null?void 0:p.split)==null?void 0:g.call(p," "))==null?void 0:m[0])==null?void 0:b.slice(0,20);r=`btn:${x||O||"unknown"}`}else if(i.tagName==="A")r=`link:${((S=i.pathname)==null?void 0:S.slice(0,30))||""}`;else if(i.tagName==="INPUT"||i.tagName==="TEXTAREA"){const v=i;r=`input:${v.name||v.type||((w=v.placeholder)==null?void 0:w.slice(0,15))||""}`}else if(i.id)r=`#${i.id}`;else{const v=(C=(T=(y=i.className)==null?void 0:y.split)==null?void 0:T.call(y," "))==null?void 0:C[0];r=v?`.${v.slice(0,20)}`:((E=i.tagName)==null?void 0:E.toLowerCase())||"unknown"}Us("click",r)};"requestIdleCallback"in window?window.requestIdleCallback(s,{timeout:100}):setTimeout(s,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),Us("shortcut",n.join("+"))}},{capture:!0,passive:!0}),window.addEventListener("popstate",()=>{Us("navigate",location.pathname)}),window.addEventListener("hashchange",()=>{Us("navigate",location.hash)})}function ID(){const e=window.fetch;window.fetch=async function(t,n){const i=Date.now();try{const s=await e.call(this,t,n);if(!s.ok){const r=typeof t=="string"?t:t.url,o=Date.now()-i,a=jn(r).slice(0,300);fn.push({time:Date.now(),url:a,method:(n==null?void 0:n.method)||"GET",status:s.status,statusText:s.statusText,duration:o}),fn.length>af&&fn.shift()}return s}catch(s){const r=typeof t=="string"?t:t.url,o=Date.now()-i,a=jn(r).slice(0,300);throw fn.push({time:Date.now(),url:a,method:(n==null?void 0:n.method)||"GET",error:s.message,duration:o}),fn.length>af&&fn.shift(),s}}}function DD(){window.addEventListener("error",e=>{var n;const t=e.target;if(t&&t!==window&&t instanceof HTMLElement&&("src"in t||"href"in t)){const i=t.src||t.href,s=(n=t.tagName)==null?void 0:n.toLowerCase();Us("resource_error",s,i==null?void 0:i.slice(0,100));const r={id:`resource-error-${Date.now()}`,timestamp:Date.now(),type:"error",error:{message:`Resource load failed: ${s||"unknown"}`,type:"resourceError"},memory:Ht(),userAgent:navigator.userAgent,url:location.href,customData:Ol({resourceUrl:pn(i?jn(i):void 0),eventTarget:n0(t)})};en(r)}},{capture:!0})}function ND(){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 i=[...t];setTimeout(()=>{var o;let s="",r;for(let a=0;a<Math.min(i.length,5);a++){const c=i[a];if(typeof c=="string")s+=c+" ";else if(typeof c=="number"||typeof c=="boolean")s+=String(c)+" ";else if(c instanceof Error)s+=`Error: ${c.message} `,r=c.stack;else if(c&&typeof c=="object")try{const d=Object.keys(c).slice(0,5).map(h=>{const p=c[h];return`${h}:${typeof p=="string"?p.slice(0,20):typeof p}`}).join(",");s+=`{${d}} `}catch{s+=`[${((o=c.constructor)==null?void 0:o.name)||"Object"}] `}}ti.push({time:Date.now(),message:s.trim().slice(0,500),stack:r}),ti.length>dD&&ti.shift()},0)}}function s0(){return{userActions:[...ei],consoleErrors:[...ti],networkErrors:[...fn],memory:Ht(),pageStats:ps(),fps:wi}}function RD(){typeof window>"u"||(window.__memoryLog={getMemory:()=>{const e=Ht();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:gD,diagnose:()=>{const e=Ht(),t=ps();if(console.group("[MemoryLog] 内存诊断"),e){const n=e.usedJSHeapSize/1048576,i=e.jsHeapSizeLimit/(1024*1024),s=n/i*100;console.log(`内存: ${n.toFixed(0)} MB / ${i.toFixed(0)} MB (${s.toFixed(1)}%)`)}return console.log(`页面: DOM ${t.domNodeCount} | Canvas ${t.canvasCount} | Img ${t.imageCount} | Video ${t.videoCount}`),t.plaitElementCount!==void 0&&console.log(`Plait 元素: ${t.plaitElementCount}`),t.imageCount>50&&console.warn("图片较多,考虑懒加载"),t.domNodeCount>5e3&&console.warn("DOM 节点较多"),console.groupEnd(),{memory:e,pageStats:t}},snapshot:()=>{const e={id:`manual-${Date.now()}`,timestamp:Date.now(),type:"periodic",memory:Ht(),pageStats:ps(),userAgent:navigator.userAgent,url:location.href};en(e)},getDiagnostics:s0,getActions:()=>(console.table(ei.map(e=>({time:new Date(e.time).toLocaleTimeString("zh-CN"),action:e.action,target:e.target,detail:e.detail}))),ei),getNetworkErrors:()=>(console.table(fn.map(e=>({time:new Date(e.time).toLocaleTimeString("zh-CN"),url:e.url,status:e.status,error:e.error}))),fn),getConsoleErrors:()=>(console.table(ti.map(e=>({time:new Date(e.time).toLocaleTimeString("zh-CN"),message:e.message.slice(0,100)}))),ti)})}function jD(){if(cf)return;cf=!0,xD(),_D(),ED(),CD(),PD(),kD(),AD(),MD(),ID(),DD(),ND(),RD();const e=TD();e&&(e.customData={...e.customData,recovered:!0,recoveredAt:Date.now()},en(e),vD())}function Bl(e,t){try{const n=LD(e,t),i=JSON.stringify(n,null,2),s=new Blob([i],{type:"application/json"}),r=URL.createObjectURL(s),o=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),a=document.createElement("a");a.href=r,a.download=`opentu-error-log-${o}.json`,a.style.display="none",document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(r)},100)}catch(n){console.error("[ErrorLogExporter] Failed to export:",n)}}function LD(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:Kt.getState(),diagnostics:s0(),unifiedLogs:ww.getMemoryLogs()};return e&&(n.currentError={message:e.message,stack:e.stack,componentStack:(t==null?void 0:t.componentStack)??void 0}),n}const OD="aitu:lazy-chunk-retry",BD="_lazy_chunk_retry",HD="_t",FD=[/Failed to fetch dynamically imported module/i,/Importing a module script failed/i,/Loading chunk [\w-]+ failed/i,/ChunkLoadError/i];function GD(){var e;return typeof document>"u"?"unknown":((e=document.querySelector('meta[name="app-version"]'))==null?void 0:e.getAttribute("content"))||"unknown"}function r0(e){if(e instanceof Error){const t=[e.name,e.message,e.stack];return e.cause&&t.push(String(e.cause)),t.filter(Boolean).join(`
|
|
66
|
+
</svg>`;return`url('data:image/svg+xml;base64,${btoa(o)}') ${s} ${s}, crosshair`}function Hh(e,t,n=Bt.circle){return n===Bt.square?fA(e,t):hA(e,t)}function Im(e){return lc().includes(e)&&e!==ot.eraser}function Dm(e){return e===ot.eraser}function $s(e,t){var o;const n=document.querySelector(".plait-board-container"),i=n==null?void 0:n.querySelector(".board-host-svg");if(!i)return;const s=si(e),r=((o=e.viewport)==null?void 0:o.zoom)||1;if(Im(t)){const a=s.strokeWidth*r,c=Hh(s.strokeColor,a,s.pencilShape);i.style.cursor=c}else if(Dm(t)){const a=s.eraserWidth*r,c=Hh(dA,a,s.eraserShape);i.style.cursor=c}else t===Pe.text?i.style.cursor="crosshair":i.style.cursor=""}function pA({board:e,pointer:t}){const n=f.useRef(1),i=f.useRef(null);return f.useEffect(()=>{var o;if(!e)return;$s(e,t),n.current=((o=e.viewport)==null?void 0:o.zoom)||1;let r=null;return(Im(t)||Dm(t))&&(r=setInterval(()=>{var c;const a=((c=e.viewport)==null?void 0:c.zoom)||1;Math.abs(a-n.current)>.01&&(n.current=a,$s(e,t))},100)),()=>{r&&clearInterval(r),i.current&&cancelAnimationFrame(i.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:f.useCallback(()=>{e&&$s(e,t)},[e,t])}}function Lr(e,t){$s(e,t)}function Fh(e){$s(e,ot.eraser)}const gA=({color:e,size:t,zoom:n,shape:i=Bt.circle})=>{const s=t*n,r=Math.max(4,Math.min(256,s)),o=i===Bt.circle?"50%":"0";return l.jsx("div",{className:"cursor-preview-dot",style:{width:r,height:r,backgroundColor:e,borderRadius:o}})},mA=()=>{var he;const e=bt(),{appState:t}=Ut(),{t:n}=Ee(),i=f.useRef(null);zo(i,{enablePositionTracking:!0,enableScaleCompensation:!0});const s=si(e),[r,o]=f.useState(s.strokeWidth),[a,c]=f.useState(s.strokeColor),[u,d]=f.useState(s.strokeStyle),[h,p]=f.useState(s.pencilShape),[g,m]=f.useState(s.pressureEnabled),[b,S]=f.useState(!1),[w,y]=f.useState(!1),[T,C]=f.useState(String(s.strokeWidth)),[E,v]=f.useState(!1),O=lc().includes(t.pointer)&&t.pointer!==ot.eraser;f.useEffect(()=>{const R=si(e);o(R.strokeWidth),c(R.strokeColor),d(R.strokeStyle),p(R.pencilShape),m(R.pressureEnabled),C(String(R.strokeWidth))},[e,t.pointer]);const B=f.useCallback(R=>{C(R.target.value)},[]),X=f.useCallback(()=>{const R=parseInt(T,10);!isNaN(R)&&R>=1&&R<=100?(o(R),ku(e,R),Lr(e,t.pointer)):C(String(r))},[e,T,r,t.pointer]),j=f.useCallback(R=>{R.key==="Enter"?(X(),R.target.blur()):R.key==="Escape"&&(C(String(r)),R.target.blur())},[X,r]),L=f.useCallback(R=>{c(R),xy(e,R),Lr(e,t.pointer)},[e,t.pointer]),D=f.useCallback(R=>{d(R),Ey(e,R)},[e]),k=f.useCallback(R=>{p(R),_y(e,R),Lr(e,t.pointer)},[e,t.pointer]),N=f.useCallback(R=>{m(R),Cy(e,R)},[e]);if(!O)return null;const M=z.getBoardContainer(e),Z=((he=e.viewport)==null?void 0:he.zoom)??1;return l.jsxs("div",{className:"pencil-settings-toolbar",onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),children:[E&&l.jsx(gA,{color:a||Au,size:r,zoom:Z,shape:h}),l.jsx(qe,{ref:i,padding:1,children:l.jsxs(pt.Row,{gap:0,align:"center",children:[l.jsxs(at,{sideOffset:12,open:b,onOpenChange:S,placement:"bottom",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:"pencil-color-button",type:"button",visible:!0,tooltip:n("toolbar.strokeColor"),"aria-label":n("toolbar.strokeColor"),onPointerUp:()=>S(!b),children:l.jsx("div",{className:"pencil-color-preview",style:{backgroundColor:a||Au}})})}),l.jsx(ct,{container:M,children:l.jsx(qe,{padding:4,className:q("stroke-setting"),children:l.jsx(Ci,{value:a,onChange:L})})})]}),l.jsxs("div",{className:"pencil-stroke-style-picker",children:[l.jsx(ne,{className:q("pencil-stroke-style-button",{active:u===yn.solid}),type:"button",visible:!0,icon:l.jsx(kf,{}),tooltip:"实线","aria-label":"实线",onPointerUp:()=>D(yn.solid)}),l.jsx(ne,{className:q("pencil-stroke-style-button",{active:u===yn.dashed}),type:"button",visible:!0,icon:l.jsx(Af,{}),tooltip:"虚线","aria-label":"虚线",onPointerUp:()=>D(yn.dashed)}),l.jsx(ne,{className:q("pencil-stroke-style-button",{active:u===yn.dotted}),type:"button",visible:!0,icon:l.jsx(Mf,{}),tooltip:"点线","aria-label":"点线",onPointerUp:()=>D(yn.dotted)}),l.jsx(ne,{className:q("pencil-stroke-style-button",{active:u===yn.double}),type:"button",visible:!0,icon:l.jsx(Py,{}),tooltip:"双层线","aria-label":"双层线",onPointerUp:()=>D(yn.double)})]}),l.jsxs("div",{className:"pencil-shape-picker",children:[l.jsx(Ct,{content:n("toolbar.pencilShape.circle"),children:l.jsx(oo,{variant:"text",size:"small",className:`pencil-shape-button ${h===Bt.circle?"active":""}`,onClick:()=>k(Bt.circle),children:l.jsx(Cp,{size:16})})}),l.jsx(Ct,{content:n("toolbar.pencilShape.square"),children:l.jsx(oo,{variant:"text",size:"small",className:`pencil-shape-button ${h===Bt.square?"active":""}`,onClick:()=>k(Bt.square),children:l.jsx(Pp,{size:16})})})]}),l.jsxs(at,{sideOffset:12,open:w,onOpenChange:y,placement:"bottom",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:"pencil-width-button",type:"button",visible:!0,tooltip:n("toolbar.strokeWidth"),"aria-label":n("toolbar.strokeWidth"),onPointerUp:()=>y(!w),children:l.jsxs("svg",{className:"pencil-width-icon",viewBox:"0 0 24 24",children:[l.jsx("line",{x1:"4",y1:"8",x2:"20",y2:"8",strokeWidth:"1",stroke:"currentColor"}),l.jsx("line",{x1:"4",y1:"12",x2:"20",y2:"12",strokeWidth:"2",stroke:"currentColor"}),l.jsx("line",{x1:"4",y1:"16",x2:"20",y2:"16",strokeWidth:"3",stroke:"currentColor"})]})})}),l.jsx(ct,{container:M,children:l.jsx(qe,{padding:4,className:q("stroke-width-picker"),children:l.jsxs(pt.Row,{gap:3,align:"center",style:{padding:"4px 8px"},children:[l.jsxs("div",{className:"stroke-width-value",style:{minWidth:"40px",fontSize:"13px",fontWeight:500,color:"var(--color-on-surface)"},children:[r,"px"]}),l.jsx("div",{className:"stroke-width-slider-wrapper",style:{flex:1,minWidth:"160px"},children:l.jsx(Io,{value:r,min:1,max:100,step:1,onChange:R=>{const W=R;o(W),C(String(W)),ku(e,W),Lr(e,t.pointer)},label:!1})})]})})})]}),l.jsxs("div",{className:"pencil-width-input-wrapper",children:[l.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:T,onChange:B,onBlur:X,onKeyDown:j,className:"pencil-width-input"}),l.jsx("span",{className:"pencil-width-input-unit",children:"px"})]}),l.jsx(Ct,{content:"压力感应:支持压感笔;鼠标/触控板使用速度模拟(慢=粗,快=细)",children:l.jsx("div",{className:"pencil-pressure-switch",children:l.jsx(ky,{size:"small",value:g,onChange:N})})})]})})]})},SA=({color:e,size:t,zoom:n,shape:i=Bt.circle})=>{const s=t*n,r=Math.max(4,Math.min(256,s)),o=i===Bt.circle?"50%":"0";return l.jsx("div",{className:"cursor-preview-dot",style:{width:r,height:r,backgroundColor:e,borderRadius:o}})},bA=()=>l.jsxs("svg",{className:"size-picker-icon",viewBox:"0 0 24 24",children:[l.jsx("line",{x1:"4",y1:"8",x2:"20",y2:"8",strokeWidth:"1",stroke:"currentColor"}),l.jsx("line",{x1:"4",y1:"12",x2:"20",y2:"12",strokeWidth:"2",stroke:"currentColor"}),l.jsx("line",{x1:"4",y1:"16",x2:"20",y2:"16",strokeWidth:"3",stroke:"currentColor"})]}),yA=({size:e,onSizeChange:t,presets:n,previewColor:i,title:s,container:r,icon:o})=>{const{t:a}=Ee(),[c,u]=f.useState(!1),[d,h]=f.useState(String(e));Gn.useEffect(()=>{h(String(e))},[e]);const p=f.useCallback(b=>{h(b.target.value)},[]),g=f.useCallback(()=>{const b=parseInt(d,10);!isNaN(b)&&b>=1?t(b):h(String(e))},[d,e,t]),m=f.useCallback(b=>{b.key==="Enter"?(g(),b.target.blur()):b.key==="Escape"&&(h(String(e)),b.target.blur())},[g,e]);return l.jsxs(l.Fragment,{children:[l.jsxs(at,{sideOffset:12,open:c,onOpenChange:u,placement:"bottom",children:[l.jsx(lt,{asChild:!0,children:l.jsx(ne,{className:"size-picker-button",type:"button",visible:!0,tooltip:s,"aria-label":s,onPointerUp:()=>u(!c),children:o||l.jsx(bA,{})})}),l.jsx(ct,{container:r,children:l.jsx(qe,{padding:4,className:q("size-picker-popover"),children:l.jsxs(pt.Row,{gap:3,align:"center",style:{padding:"4px 8px"},children:[l.jsxs("div",{className:"size-picker-value",style:{minWidth:"40px",fontSize:"13px",fontWeight:500,color:"var(--color-on-surface)"},children:[e,"px"]}),l.jsx("div",{className:"size-picker-slider-wrapper",style:{flex:1,minWidth:"160px"},children:l.jsx(Io,{value:e,min:1,max:Math.max(256,...n),step:1,onChange:b=>{const S=b;h(String(S)),t(S)},label:!1})})]})})})]}),l.jsxs("div",{className:"size-picker-input-wrapper",children:[l.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:d,onChange:p,onBlur:g,onKeyDown:m,className:"size-picker-input"}),l.jsx("span",{className:"size-picker-input-unit",children:"px"})]})]})},wA=[16,32,48,64,96,128,192,256],TA="#f5f5f5",vA=()=>{var S;const e=bt(),{appState:t}=Ut(),{t:n}=Ee(),i=f.useRef(null);zo(i,{enablePositionTracking:!0,enableScaleCompensation:!0});const s=si(e),[r,o]=f.useState(s.eraserWidth),[a,c]=f.useState(s.eraserShape),[u,d]=f.useState(!1),h=t.pointer===ot.eraser;f.useEffect(()=>{const w=si(e);o(w.eraserWidth),c(w.eraserShape)},[e,t.pointer]);const p=f.useCallback(w=>{o(w),Ay(e,w),Fh(e)},[e]),g=f.useCallback(w=>{c(w),My(e,w),Fh(e)},[e]);if(!h)return null;const m=z.getBoardContainer(e),b=((S=e.viewport)==null?void 0:S.zoom)??1;return l.jsxs("div",{className:"pencil-settings-toolbar eraser-settings-toolbar",onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:[u&&l.jsx(SA,{color:TA,size:r,zoom:b,shape:a}),l.jsx(qe,{ref:i,padding:1,children:l.jsxs(pt.Row,{gap:1,align:"center",children:[l.jsx(yA,{size:r,onSizeChange:p,presets:wA,previewColor:"#999",title:n("toolbar.eraserSize"),container:m}),l.jsx("div",{className:"toolbar-divider"}),l.jsxs("div",{className:"eraser-shape-picker",children:[l.jsx(Ct,{content:n("toolbar.eraserShape.circle"),children:l.jsx(oo,{variant:"text",size:"small",className:`eraser-shape-button ${a===Bt.circle?"active":""}`,onClick:()=>g(Bt.circle),children:l.jsx(Cp,{size:16})})}),l.jsx(Ct,{content:n("toolbar.eraserShape.square"),children:l.jsx(oo,{variant:"text",size:"small",className:`eraser-shape-button ${a===Bt.square?"active":""}`,onClick:()=>g(Bt.square),children:l.jsx(Pp,{size:16})})})]})]})})]})},xA=[{icon:l.jsx(Dy,{}),type:"corner",titleKey:"toolbar.anchorCorner"},{icon:l.jsx(Ny,{}),type:"smooth",titleKey:"toolbar.anchorSmooth"},{icon:l.jsx(Ry,{}),type:"symmetric",titleKey:"toolbar.anchorSymmetric"}],EA=()=>{const e=bt(),{appState:t}=Ut(),{t:n}=Ee(),i=f.useRef(null);zo(i,{enablePositionTracking:!0,enableScaleCompensation:!0});const s=Ja(e),[r,o]=f.useState(s.defaultAnchorType),a=t.pointer===Bn.pen&&e.pointer===Bn.pen;f.useEffect(()=>{const u=Ja(e);o(u.defaultAnchorType)},[e,t.pointer,e.pointer]);const c=f.useCallback(u=>{o(u),Iy(e,u)},[e]);return a?l.jsx("div",{className:"pen-settings-toolbar",children:l.jsx(qe,{ref:i,padding:1,children:l.jsx(pt.Row,{gap:0,align:"center",children:l.jsx("div",{className:"pen-anchor-type-picker",children:xA.map(u=>l.jsx(ne,{className:q("pen-anchor-type-button",{active:r===u.type}),type:"button",visible:!0,icon:u.icon,tooltip:n(u.titleKey),"aria-label":n(u.titleKey),onPointerUp:()=>c(u.type)},u.type))})})})}):null},_A=({container:e})=>{const{appState:t,setAppState:n}=Ut(),{t:i}=Ee(),s=bt();return l.jsx(jy,{open:t.openCleanConfirm,container:e,title:i("cleanConfirm.title"),description:i("cleanConfirm.description"),confirmText:i("cleanConfirm.ok"),cancelText:i("cleanConfirm.cancel"),danger:!0,onOpenChange:r=>{n({...t,openCleanConfirm:r})},onConfirm:()=>{s.deleteFragment(s.children)}})},Gh=e=>{const{appState:t}=e;return t&&t.linkState&&t.linkState.isHovering},zh=e=>{const{appState:t}=e;return t&&t.linkState&&t.linkState.isEditing},CA=e=>n=>{const{pointerMove:i}=n;let s=null,r=null;return n.pointerMove=o=>{(z.isPointer(n,vt.selection)||z.isPointer(n,vt.hand))&&!er(n)&&!Ef(n)&&!Gh(n)&&!zh(n)&&Jl(n,"with-text-link",()=>{const a=o.target.closest(".plait-board-link");if(a&&a!==s){const c=a.closest(".plait-text-container"),u=vn.toSlateNode(void 0,c),d=vn.toSlateNode(void 0,a);s=a,e({linkState:{targetDom:a,targetElement:d,editor:u,isEditing:!1,isHovering:!1,isHoveringOrigin:!0}}),clearTimeout(r)}else!a&&s&&(r=setTimeout(()=>{!Gh(n)&&!zh(n)&&e({linkState:null})},300),s=null)}),i(o)},n},PA=()=>{var S,w,y,T;const[e,t]=f.useState(""),{appState:n,setAppState:i}=Ut(),s=bt(),{refs:r,floatingStyles:o}=$l({placement:"top",middleware:[Xl(20),Kl()]}),a=n.linkState,c=((S=n.linkState)==null?void 0:S.targetDom)||null,u=((w=n.linkState)==null?void 0:w.isEditing)||!1,d=((y=n.linkState)==null?void 0:y.isHoveringOrigin)||!1,h=((T=n.linkState)==null?void 0:T.isHovering)||!1,p=u||d||h,g=f.useRef(n.linkState);f.useEffect(()=>{g.current=n.linkState,n.linkState?t(n.linkState.targetElement.url):t("")},[n.linkState]),f.useEffect(()=>{if(c){const C=c.getBoundingClientRect();r.setPositionReference({getBoundingClientRect(){return{x:C.x,y:C.y,width:C.width,height:C.height,top:C.y,left:C.x,right:C.x+C.width,bottom:C.y+C.height}}})}},[s.viewport,c,r]);const m=f.useRef();m.current=C=>{if(r.floating.current&&!r.floating.current.contains(C.target)){if(g.current){const E=es.getLinkElement(g.current.editor);E&&!E[0].url.trim()&&es.unwrapLink(g.current.editor)}i({...n,linkState:null})}},f.useEffect(()=>{const C=E=>{var v;(v=m.current)==null||v.call(m,E)};return document.addEventListener("mousedown",C),()=>{document.removeEventListener("mousedown",C)}},[]);const b=()=>{if(!a)return;if(e!==a.targetElement.url){const E=a.editor,v=a.targetElement,x=vn.findPath(E,v);ma.setNodes(E,{url:e},{at:x})}const C=es.getLinkElement(a.editor);C&&i({...n,linkState:{...n.linkState,targetElement:C[0],isEditing:!1,isHoveringOrigin:!0}})};return p&&l.jsx(qe,{ref:r.setFloating,style:o,padding:1,className:q("link-popup"),onPointerEnter:()=>{!h&&n.linkState&&i({...n,linkState:{...n.linkState,isHovering:!0}})},onPointerLeave:()=>{!u&&n.linkState&&i({...n,linkState:{...n.linkState,isHovering:!1}})},children:l.jsx(pt.Row,{gap:1,align:"center",children:u?l.jsxs(l.Fragment,{children:[l.jsx("input",{type:"text",value:e,onChange:C=>{t(C.target.value)},onKeyDown:C=>{C.key==="Enter"&&b()},className:"link-popup__input",autoFocus:!0}),l.jsx(ne,{type:"icon",visible:!0,icon:l.jsx(so,{}),tooltip:"Delete link","aria-label":"Delete link",onPointerDown:()=>{if(!a)return;const C=a.editor,E=a.targetElement,v=vn.findPath(C,E);ma.unwrapNodes(C,{at:v}),i({...n,linkState:null})}})]}):l.jsxs(l.Fragment,{children:[l.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"link-popup__link",children:e}),l.jsx(ne,{className:"link-popup__edit",type:"icon",visible:!0,icon:l.jsx(Ss,{}),tooltip:"Edit link","aria-label":"Edit link",onPointerDown:({event:C})=>{C.preventDefault(),n.linkState&&i({...n,linkState:{...n.linkState,isEditing:!0}})}}),l.jsx(ne,{type:"icon",visible:!0,icon:l.jsx(so,{}),tooltip:"Delete link","aria-label":"Delete link",onPointerDown:()=>{if(!a)return;const C=a.editor,E=a.targetElement,v=vn.findPath(C,E);ma.unwrapNodes(C,{at:v}),i({...n,linkState:null})}})]})})})},Gs={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 kA(){return"0.6.64"}function Vh(e){return{...Gs,...e,retryPolicy:{...Gs.retryPolicy,...e.retryPolicy||{}},cacheConfig:{...Gs.cacheConfig,...e.cacheConfig||{}},batchConfig:{...Gs.batchConfig,...e.batchConfig||{}}}}class AA{isAvailable(){return Yt.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{Yt.track(t.eventName,n)}catch(i){throw console.error("[Tracking] PostHog track failed:",i),i}}async trackBatch(t){const n=[];for(const i of t)try{await this.track(i),n.push({success:!0})}catch(s){n.push({success:!1,error:s})}return n}getSDKInfo(){return{available:this.isAvailable(),version:this.isAvailable()?"PostHog JS":void 0}}}const Uh=new AA;class MA{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 Uh.trackBatch(t),i=n.filter(s=>!s.success);if(i.length>0){console.error(`Batch upload: ${i.length}/${t.length} events failed`);const s=t.filter((r,o)=>!n[o].success);this.requeueFailedEvents(s)}}catch(n){console.error("Batch upload failed:",n),this.requeueFailedEvents(t)}finally{this.uploading=!1}}async uploadImmediate(t){try{await Uh.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 IA{constructor(t=500){this.debounceMap=new WeakMap,this.globalDebounceMap=new Map,this.globalDebounceTime=200,this.debounceTime=t}shouldTrack(t,n,i=!1){const s=Date.now(),r=this.globalDebounceMap.get(n);if(r&&s-r<this.globalDebounceTime)return i&&console.warn(`[Tracking] 🚫 Global debounce: ${n} (${s-r}ms ago)`),!1;const o=this.debounceMap.get(t);if(!o){const c=new Map;return c.set(n,s),this.debounceMap.set(t,c),this.globalDebounceMap.set(n,s),!0}const a=o.get(n);return!a||s-a>this.debounceTime?(o.set(n,s),this.globalDebounceMap.set(n,s),!0):(i&&console.warn(`[Tracking] 🚫 Element debounce: ${n} (${s-a}ms ago)`),!1)}clear(t){this.debounceMap.delete(t)}setDebounceTime(t){this.debounceTime=t}}const DA=["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 NA(e,t){if(!e.matches(DA))return!1;for(const i of t)if(e.matches(i)||e.closest(i))return!1;return e.hasAttribute("data-track-ignore")?!1:(e.onclick!==null,!0)}function RA(e,t="click"){var a;const n=`auto_${t}_`;if(e.id)return`${n}${e.id}`;const i=e.getAttribute("aria-label");if(i)return`${n}${Wh(i)}`;const s=(a=e.textContent)==null?void 0:a.trim();if(s&&s.length>0){const c=Wh(s.substring(0,20));return`${n}${c}`}const r=e.tagName.toLowerCase(),o=e.className?`.${e.className.split(" ")[0]}`:"";return`${n}${r}${o}`}function Wh(e){return e.toLowerCase().trim().replace(/\s+/g,"_").replace(/[^a-z0-9_-]/g,"").substring(0,50)}function jA(e){if(e.id)return`#${e.id}`;const t=[];let n=e;for(;n&&n!==document.body;){let i=n.tagName.toLowerCase();if(n.className){const s=n.className.split(" ").filter(Boolean);s.length>0&&(i+=`.${s[0]}`)}t.unshift(i),n=n.parentElement}return t.join(" > ")}function Oa(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 Nm(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function LA(){if(typeof window>"u")return"server-side";const e="tracking_session_id";let t=sessionStorage.getItem(e);return t||(t=Nm(),sessionStorage.setItem(e,t)),t}function OA(){return typeof window>"u"?{width:0,height:0}:{width:window.innerWidth||0,height:window.innerHeight||0}}class BA{constructor(t={}){this.state$=new Ly({initialized:!1,config:Gs,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=Vh(t),this.batchService=new MA(this.config.batchConfig),this.debouncer=new IA(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 i=n.closest("[data-track]");if(i){const s=i.getAttribute("data-track");if(s){if(this.isElementExcluded(i))return;this.trackClick(i,s);return}}if(this.config.autoTrack&&NA(n,this.config.excludedSelectors)){if(this.isElementExcluded(n))return;const s=RA(n,"click");this.trackClick(n,s)}},document.body.addEventListener("click",this.clickListener,!0))}setupMultiEventListeners(){if(typeof document>"u")return;document.querySelectorAll("[track-hover]").forEach(i=>{this.attachHoverListener(i)}),document.querySelectorAll("[track-focus]").forEach(i=>{this.attachFocusListener(i)})}attachHoverListener(t){const n=t.getAttribute("track-hover");if(!n||this.hasAttachedListener(t,"hover"))return;const i=()=>{if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents");return}const s=Oa(t),r=this.createTrackEvent(n,s,"hover",t);this.track(r)};t.addEventListener("mouseenter",i),this.markListenerAttached(t,"hover")}attachFocusListener(t){const n=t.getAttribute("track-focus");if(!n||this.hasAttachedListener(t,"focus"))return;const i=()=>{if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents");return}const s=Oa(t),r=this.createTrackEvent(n,s,"focus",t);this.track(r)};t.addEventListener("focus",i,!0),this.markListenerAttached(t,"focus")}hasAttachedListener(t,n){const i=this.attachedListeners.get(t);return i?i.has(n):!1}markListenerAttached(t,n){let i=this.attachedListeners.get(t);i||(i=new Set,this.attachedListeners.set(t,i)),i.add(n)}setupMutationObserver(){typeof window>"u"||typeof MutationObserver>"u"||(this.mutationObserver=new MutationObserver(t=>{t.forEach(n=>{n.addedNodes.forEach(i=>{if(i.nodeType===Node.ELEMENT_NODE){const s=i;s.hasAttribute("track-hover")&&this.attachHoverListener(s),s.hasAttribute("track-focus")&&this.attachFocusListener(s),s.querySelectorAll("[track-hover]").forEach(a=>this.attachHoverListener(a)),s.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 i=Oa(t),s=this.createTrackEvent(n,i,"click",t);this.track(s)}createTrackEvent(t,n,i,s){const r={timestamp:Date.now(),url:typeof window<"u"?window.location.href:"",version:kA(),sessionId:LA(),userAgent:typeof navigator<"u"?navigator.userAgent:void 0,viewport:OA(),eventType:i},o={eventName:t,params:n||void 0,metadata:r,id:Nm(),createdAt:Date.now()};return this.config.devMode&&this.log("debug",`Event created: ${t}`,{params:n,element:s?jA(s):void 0}),o}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=Vh({...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,i){this.config.logLevel!=="silent"&&(t==="error"||t==="debug"&&this.config.devMode)}}let In=null;function HA(){In&&(In.destroy(),In=null)}function FA(e,t){return In||(In=new BA(t),typeof window<"u"&&setTimeout(()=>{In==null||In.initialize()},0),typeof module<"u"&&module.hot&&module.hot.dispose(()=>{HA()})),e.trackingService=In,e}class GA extends ac{initialize(){super.initialize()}}const zA=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.`),GA}},e};function VA(e,t,n,i=0){const s=ge.getCenterPoint(t),r=Ni(t,ci);if(i){const o=UA(n,s,-i);let a=r.find(c=>ge.isHit(ge.getRectangleByPoints([o,o]),c.rectangle));return a&&(a.cursorClass=Uo(a.cursorClass,i)),a}else return r.find(o=>ge.isHit(ge.getRectangleByPoints([n,n]),o.rectangle))}function UA(e,t,n){const i=n*Math.PI/180,s=Math.cos(i),r=Math.sin(i),o=e[0]-t[0],a=e[1]-t[1];return[t[0]+o*s-a*r,t[1]+o*r+a*s]}function WA(e){const t=He(e);return t.length!==1?!1:Yl(t[0])}function $A(e,t){const n=He(e);if(n.length!==1||!Yl(n[0]))return null;const i=n[0],s=ge.getRectangleByPoints(i.points),r=i.angle||0,o=VA(e,s,t,r);return o?{element:i,rectangle:s,handle:o.handle,cursorClass:o.cursorClass}:null}function XA(e,t,n){const{element:i,rectangle:s,handle:r}=t,{startPoint:o,endPoint:a}=n;if(!s){console.warn("startRectangle is undefined");return}const c=a[0]-o[0],u=a[1]-o[1],d=bs(s,r,c,u,pr(),100),h=[[d.x,d.y],[d.x+d.width,d.y+d.height]],p=e.children.findIndex(g=>g.id===i.id);p>=0&&ue.setNode(e,{points:h},[p])}const KA=e=>Di(e,{key:"tool-elements",canResize:()=>WA(e),hitTest:(t=>$A(e,t)),onResize:(t,n)=>XA(e,t,n)});let yo=null;function YA(e,t){return Xe.isFreehand(t)?Vo(t):Je.isPenPath(t)?Wo(t):e.getRectangle(t)}function qA(e,t){return Ni(e,ci).find(i=>ge.isHit(ge.getRectangleByPoints([t,t]),i.rectangle))}function Vc(e){return e.some(t=>Xe.isFreehand(t)||Je.isPenPath(t)||V.isText(t))}function ZA(e){return e.some(t=>V.isText(t))}function Rm(e){const t=He(e);if(t.length<2||!Vc(t))return null;try{const n=Ft(e,t,!1);return{elements:t,rectangle:n}}catch{return null}}function QA(e){return Rm(e)!==null}function JA(e,t){const n=Rm(e);if(!n)return null;const i=qA(n.rectangle,t);if(i){yo=new Map;for(const s of n.elements){const r=YA(e,s);r&&yo.set(s.id,{element:JSON.parse(JSON.stringify(s)),rectangle:{...r}})}return{element:n.elements,rectangle:n.rectangle,handle:i.handle,cursorClass:i.cursorClass}}return null}function eM(e,t,n,i,s,r){const o=r.width/s.width,a=r.height/s.height,c=i.x-s.x,u=i.y-s.y,d=r.x+c*o,h=r.y+u*a,p=n.points.map(m=>{const b=m[0]-i.x,S=m[1]-i.y,w=b*o,y=S*a;return[d+w,h+y]}),g=e.children.findIndex(m=>m.id===t);g>=0&&ue.setNode(e,{points:p},[g])}function tM(e,t,n,i,s,r){const o=r.width/s.width,a=r.height/s.height,c=i.x-s.x,u=i.y-s.y,d=r.x+c*o,h=r.y+u*a,p=n.anchors.map(y=>({...y,point:[y.point[0]*o,y.point[1]*a],handleIn:y.handleIn?[y.handleIn[0]*o,y.handleIn[1]*a]:void 0,handleOut:y.handleOut?[y.handleOut[0]*o,y.handleOut[1]*a]:void 0})),g=i.width*o,m=i.height*a,S=[[d,h],[d+g,h+m]],w=e.children.findIndex(y=>y.id===t);w>=0&&ue.setNode(e,{points:S,anchors:p},[w])}const jm=14;function Lm(e,t){const n={...e};if("text"in e&&typeof e.text=="string"){const i=e["font-size"]?parseFloat(e["font-size"]):jm,s=Math.max(1,Math.round(i*t*10)/10);n["font-size"]=`${s}`}return Array.isArray(e.children)&&(n.children=e.children.map(i=>Lm(i,t))),n}function nM(e,t,n,i,s,r){const o=r.width/s.width,a=r.height/s.height,c=i.x-s.x,u=i.y-s.y,d=r.x+c*o,h=r.y+u*a,p=i.width*o,g=i.height*a,m=[[d,h],[d+p,h+g]],b=e.children.findIndex(S=>S.id===t);if(b>=0)if(V.isDrawElement(n)&&V.isImage(n))ue.setNode(e,{points:m,width:p,height:g},[b]);else if(V.isText(n)){const S=n,w=Lm(S.text,o),y=S.textHeight||jm*1.4;ue.setNode(e,{points:m,text:w,textHeight:y*o,autoSize:!1},[b])}else ue.setNode(e,{points:m},[b])}function iM(e,t,n){const{element:i,rectangle:s,handle:r}=t,{startPoint:o,endPoint:a}=n;if(!s||!Array.isArray(i)||!yo)return;const c=a[0]-o[0],u=a[1]-o[1],d=pr()||ZA(i),h=bs(s,r,c,u,d);for(const p of i){const g=yo.get(p.id);if(!g)continue;const{element:m,rectangle:b}=g;Xe.isFreehand(m)?eM(e,p.id,m,b,s,h):Je.isPenPath(m)?tM(e,p.id,m,b,s,h):nM(e,p.id,m,b,s,h)}}function sM(e){const t=He(e);if(t.length<2||!Vc(t))return null;try{const n=Ql(),i=Ft(e,t,!1),s=Oy(e,i);return ge.getCornerPoints(s).forEach(o=>{const a=By(e,o);n.append(a)}),n}catch{return null}}const rM=e=>{const{afterChange:t}=e;let n=null;return e.afterChange=()=>{t(),n&&(n.remove(),n=null);const i=He(e);i.length>1&&Vc(i)&&!Zs(e)&&(n=sM(e),n&&z.getActiveHost(e).append(n))},Di(e,{key:"multi-resize",canResize:()=>QA(e),hitTest:(i=>JA(e,i)),onResize:(i,s)=>iM(e,i,s)})},Om=14;let eo=null,Il=null;function oM(e,t){return Ni(e,ci).find(i=>ge.isHit(ge.getRectangleByPoints([t,t]),i.rectangle))}function Bm(e,t){const n={...e};if("text"in e&&typeof e.text=="string"){const i=e["font-size"]?parseFloat(e["font-size"]):Om,s=Math.max(1,Math.round(i*t*10)/10);n["font-size"]=`${s}`}return Array.isArray(e.children)&&(n.children=e.children.map(i=>Bm(i,t))),n}function aM(e){const t=He(e);return t.length!==1?!1:V.isText(t[0])}function lM(e,t){const n=He(e);if(n.length!==1||!V.isText(n[0]))return null;const i=n[0],s=ge.getRectangleByPoints(i.points),r=oM(s,t);return r?(eo=JSON.parse(JSON.stringify(i)),Il={...s},{element:i,rectangle:s,handle:r.handle,cursorClass:r.cursorClass}):null}function cM(e,t,n){const{element:i,rectangle:s,handle:r}=t,{startPoint:o,endPoint:a}=n;if(!s||!eo||!Il)return;const c=a[0]-o[0],u=a[1]-o[1],d=bs(s,r,c,u,!0,20),h=d.width/Il.width;if(h<=0)return;const p=Bm(eo.text,h),m=(eo.textHeight||Om*1.4)*h,b=[[d.x,d.y],[d.x+d.width,d.y+d.height]],S=e.children.findIndex(w=>w.id===i.id);S>=0&&ue.setNode(e,{points:b,text:p,textHeight:m,autoSize:!1},[S])}const uM=e=>Di(e,{key:"text-resize",canResize:()=>aM(e),hitTest:t=>lM(e,t),onResize:(t,n)=>cM(e,t,n)});function dM(e){return e.some(n=>Xe.isFreehand(n)||Je.isPenPath(n))}function hM(e){const t=He(e);if(t.length<2||!dM(t))return null;try{return Ft(e,t,!1)}catch{return null}}const fM=()=>{const e=bt(),[t,n]=f.useState([]),[i,s]=f.useState(!1),[r,o]=f.useState(!1),a=f.useRef(!1),c=f.useCallback(()=>{const h=Qs(e)||er(e)||Zs(e);if(o(h),h)return;He(e);const p=hM(e);if(!p){s(!1);return}const m=[{x:p.x,y:p.y,cursor:"nwse-resize"},{x:p.x+p.width,y:p.y,cursor:"nesw-resize"},{x:p.x+p.width,y:p.y+p.height,cursor:"nwse-resize"},{x:p.x,y:p.y+p.height,cursor:"nesw-resize"}].map(b=>{const S=Os(e,[b.x,b.y]);return{x:S[0],y:S[1],cursor:b.cursor}});n(m),s(!0)},[e]);if(f.useEffect(()=>{a.current=r},[r]),f.useEffect(()=>{c();let h,p=JSON.stringify(e.viewport),g=JSON.stringify(e.selection),m=e.children.length;const b=()=>{const S=JSON.stringify(e.viewport),w=JSON.stringify(e.selection),y=e.children.length,T=Qs(e)||er(e)||Zs(e);(S!==p||w!==g||y!==m||T!==a.current)&&(p=S,g=w,m=y,c()),h=requestAnimationFrame(b)};return h=requestAnimationFrame(b),()=>{cancelAnimationFrame(h)}},[e,c]),!i||t.length===0||r)return null;const u=ci,d=u/2;return l.jsx("div",{className:q("multi-selection-handles",Dt),children:t.map((h,p)=>l.jsx("div",{className:"multi-selection-handle",style:{left:h.x-d,top:h.y-d,width:u,height:u,cursor:h.cursor}},p))})},Hm=f.createContext(null),pM=typeof window<"u"?Math.max(375,window.innerWidth*.5):600,gM=({children:e})=>{const t=f.useRef(null),n=f.useRef(null),[i,s]=f.useState([]),[r,o]=f.useState(!1),[a,c]=f.useState(pM),u=f.useCallback(h=>{n.current=h},[]),d=f.useCallback(async(h,p)=>{n.current?await n.current(h,p):console.warn("[ChatDrawerContext] No retry handler registered")},[]);return l.jsx(Hm.Provider,{value:{chatDrawerRef:t,registerRetryHandler:u,executeRetry:d,selectedContent:i,setSelectedContent:s,isDrawerOpen:r,setIsDrawerOpen:o,drawerWidth:a,setDrawerWidth:c},children:e})};function Fm(){const e=f.useContext(Hm);if(!e)throw new Error("useChatDrawer must be used within a ChatDrawerProvider");return e}function mM(){const{chatDrawerRef:e,registerRetryHandler:t,executeRetry:n,selectedContent:i,setSelectedContent:s,isDrawerOpen:r,setIsDrawerOpen:o,drawerWidth:a,setDrawerWidth:c}=Fm();return{openChatDrawer:()=>{var u;(u=e.current)==null||u.open()},closeChatDrawer:()=>{var u;(u=e.current)==null||u.close()},toggleChatDrawer:()=>{var u;(u=e.current)==null||u.toggle()},sendMessageToChatDrawer:async u=>{var d;await((d=e.current)==null?void 0:d.sendMessage(u))},sendWorkflowMessage:async u=>{var d;await((d=e.current)==null?void 0:d.sendWorkflowMessage(u))},updateWorkflowMessage:u=>{var d;(d=e.current)==null||d.updateWorkflowMessage(u)},appendAgentLog:u=>{var d;(d=e.current)==null||d.appendAgentLog(u)},updateThinkingContent:u=>{var d;(d=e.current)==null||d.updateThinkingContent(u)},isChatDrawerOpen:()=>{var u;return((u=e.current)==null?void 0:u.isOpen())??!1},isDrawerOpen:r,setIsDrawerOpen:o,drawerWidth:a,setDrawerWidth:c,registerRetryHandler:t,retryWorkflowFromStep:async(u,d)=>{await n(u,d)},selectedContent:i,setSelectedContent:s}}class SM{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=Er.getToolById("banana-prompt");if(!n){console.error('❌ Tool "banana-prompt" not found');return}Fi.insertTool(t,n.id,n.url,[100,100],{width:n.defaultWidth||Gi.defaultWidth,height:n.defaultHeight||Gi.defaultHeight},{name:n.name,category:n.category,permissions:n.permissions})}insertXiaohongshuTool(){const t=this.getBoard();if(!t)return;const n=Er.getToolById("xiaohongshu-tool");if(!n){console.error('❌ Tool "xiaohongshu-tool" not found');return}Fi.insertTool(t,n.id,n.url,[300,300],{width:n.defaultWidth||Gi.defaultWidth,height:n.defaultHeight||Gi.defaultHeight},{name:n.name,category:n.category,permissions:n.permissions})}insertToolById(t,n=200,i=200){const s=this.getBoard();if(!s)return;const r=Er.getToolById(t);if(!r){console.error(`❌ Tool "${t}" not found`);return}Fi.insertTool(s,r.id,r.url,[n,i],{width:r.defaultWidth||Gi.defaultWidth,height:r.defaultHeight||Gi.defaultHeight},{name:r.name,category:r.category,permissions:r.permissions})}listAllTools(){Er.getAvailableTools().forEach((n,i)=>{})}getAllToolElements(){const t=this.getBoard();if(!t)return;Fi.getAllTools(t).forEach((i,s)=>{})}removeAllTools(){const t=this.getBoard();if(!t)return;Fi.getAllTools(t).forEach(i=>{Fi.removeTool(t,i.id)})}help(){}}const bM=new SM;typeof window<"u"&&(window.testToolbox=bM);const yM={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)"},wM={autoHideDelay:3e3},TM=({board:e,config:t,className:n,displayMode:i="auto",autoTriggerConfig:s})=>{const r=f.useRef(null),o=f.useRef(null);f.useRef(null);const a={...yM,...t},c={...wM,...s},[u,d]=f.useState(()=>({expanded:i==="always"?!0:a.defaultExpanded,dragging:!1,autoMode:i==="auto",manuallyExpanded:!1})),h=f.useRef({isDragging:!1,startPoint:null}),p=f.useRef(null),[g,m]=f.useState(null),b=f.useRef(null),[S,w]=f.useState(!1),y=120,T=f.useRef(0),C=f.useRef({zoom:e.viewport.zoom,offsetX:e.viewport.offsetX,offsetY:e.viewport.offsetY}),E=f.useRef(!1),v=f.useCallback(()=>{if(!e||!e.children)return[];const P=[];return e.children.forEach(A=>{try{let $=null;A.points&&Array.isArray(A.points)?$=ge.getRectangleByPoints(A.points):A.x!==void 0&&A.y!==void 0&&($={x:A.x,y:A.y,width:A.width||100,height:A.height||100}),$&&$.width>0&&$.height>0&&P.push({id:A.id,bounds:$,type:A.type})}catch($){console.warn("Failed to get bounds for element:",A.id,$)}}),P},[e]),x=f.useCallback(()=>{const A=z.getBoardContainer(e).getBoundingClientRect(),$=e.viewport.zoom,Q=Ao(e),I=Q[0],H=Q[1],F=A.width/$,U=A.height/$;return{x:I,y:H,width:F,height:U}},[e]),O=f.useRef(u.expanded);O.current=u.expanded;const B=f.useRef(null),X=f.useRef(1);f.useEffect(()=>{if(i==="always"){O.current||d(A=>({...A,expanded:!0}));return}if(i!=="auto")return;const P=setInterval(()=>{const A=e.viewport,$=C.current,Q=Math.abs(A.zoom-$.zoom)>.001,I=Math.abs(A.offsetX-$.offsetX)>.5||Math.abs(A.offsetY-$.offsetY)>.5;if(Q||I){if(C.current={zoom:A.zoom,offsetX:A.offsetX,offsetY:A.offsetY},!E.current){E.current=!0;return}T.current=Date.now(),O.current||d(F=>({...F,expanded:!0,manuallyExpanded:!1}))}},100);return()=>{clearInterval(P)}},[i,e]),f.useEffect(()=>{if(i!=="auto"||!u.expanded||u.manuallyExpanded||u.dragging)return;const P=setTimeout(()=>{d(A=>!A.autoMode||A.manuallyExpanded||A.dragging?A:{...A,expanded:!1})},c.autoHideDelay);return()=>{clearTimeout(P)}},[i,u.expanded,u.manuallyExpanded,u.dragging,c.autoHideDelay]);const j=f.useCallback((P,A)=>{if(P.length===0)return{x:A.x-200,y:A.y-200,width:A.width+400,height:A.height+400};let $=A.x,Q=A.y,I=A.x+A.width,H=A.y+A.height;P.forEach(U=>{const{x:te,y:ee,width:G,height:J}=U.bounds;$=Math.min($,te),Q=Math.min(Q,ee),I=Math.max(I,te+G),H=Math.max(H,ee+J)});const F=100;return{x:$-F,y:Q-F,width:I-$+F*2,height:H-Q+F*2}},[]),L=f.useCallback(P=>{const $=(a.width-20)/P.width,Q=(a.height-20)/P.height;return Math.min($,Q)},[a.width,a.height]),D=f.useCallback((P,A,$,Q)=>{const H=(P-$.x)*Q+10,F=(A-$.y)*Q+10;return[H,F]},[]),k=f.useCallback((P,A,$,Q)=>{const H=(P-10)/Q+$.x,F=(A-10)/Q+$.y;return[H,F]},[]),N=f.useCallback((P,A,$)=>{if(100*$<5)return;P.strokeStyle="rgba(0, 0, 0, 0.05)",P.lineWidth=.5;const H=Math.floor(A.x/100)*100,F=Math.floor(A.y/100)*100,U=A.x+A.width,te=A.y+A.height;for(let ee=H;ee<=U;ee+=100){const[G]=D(ee,0,A,$);P.beginPath(),P.moveTo(G,0),P.lineTo(G,a.height),P.stroke()}for(let ee=F;ee<=te;ee+=100){const[,G]=D(0,ee,A,$);P.beginPath(),P.moveTo(0,G),P.lineTo(a.width,G),P.stroke()}},[D,a.width,a.height]),M=f.useCallback(()=>{const P=r.current;if(!P)return;const A=P.getContext("2d");if(!A)return;A.clearRect(0,0,a.width,a.height);const $=v(),Q=x();if($.length===0&&!Q){A.fillStyle="#999",A.font="12px sans-serif",A.textAlign="center",A.textBaseline="middle",A.fillText("空画布",a.width/2,a.height/2);return}const I=j($,Q),H=L(I);B.current=I,X.current=H,N(A,I,H),A.fillStyle=a.elementColor,A.strokeStyle="rgba(0, 0, 0, 0.1)",A.lineWidth=.5,$.forEach(se=>{const{x:Re,y:ut,width:Oe,height:ie}=se.bounds,[De,Le]=D(Re,ut,I,H),ke=Oe*H,Fe=ie*H;A.fillRect(De,Le,ke,Fe),A.strokeRect(De,Le,ke,Fe)});const[F,U]=D(Q.x,Q.y,I,H),te=Q.width*H,ee=Q.height*H;A.fillStyle=a.viewportColor,A.fillRect(F,U,te,ee),A.strokeStyle=a.viewportColor.replace("0.3","1"),A.lineWidth=2,A.strokeRect(F,U,te,ee);const G=8;A.fillStyle=a.viewportColor.replace("0.3","0.8"),A.fillRect(F,U,G,2),A.fillRect(F,U,2,G),A.fillRect(F+te-G,U,G,2),A.fillRect(F+te-2,U,2,G),A.fillRect(F,U+ee-2,G,2),A.fillRect(F,U+ee-G,2,G),A.fillRect(F+te-G,U+ee-2,G,2),A.fillRect(F+te-2,U+ee-G,2,G);const J=b.current;if(J){const se=J.x-te/2,Re=J.y-ee/2;A.fillStyle="rgba(243, 156, 18, 0.15)",A.fillRect(se,Re,te,ee),A.strokeStyle="rgba(243, 156, 18, 0.8)",A.lineWidth=2,A.strokeRect(se,Re,te,ee)}},[e,a,v,x,j,L,D,N]),Z=f.useCallback(P=>{P.preventDefault(),P.stopPropagation();const A=r.current;if(!A||!B.current)return;const $=A.getBoundingClientRect(),Q=P.clientX-$.left,I=P.clientY-$.top;Yt.track("minimap_navigate",{action:"click",displayMode:i});const[H,F]=k(Q,I,B.current,X.current);h.current={isDragging:!0,startPoint:[Q,I]},d(U=>({...U,dragging:!0})),he(H,F)},[k,e]),he=f.useCallback((P,A)=>{const Q=z.getBoardContainer(e).getBoundingClientRect(),I=e.viewport.zoom,H=P-Q.width/(2*I),F=A-Q.height/(2*I);fe.updateViewport(e,[H,F],I),requestAnimationFrame(()=>M())},[e,M]),R=f.useCallback(P=>{if(!h.current.isDragging||!B.current)return;P.preventDefault(),P.stopPropagation();const A=r.current;if(!A)return;const $=A.getBoundingClientRect(),Q=P.clientX-$.left,I=P.clientY-$.top,[H,F]=k(Q,I,B.current,X.current);he(H,F)},[k,he]),W=f.useCallback(()=>{h.current.isDragging&&Yt.track("minimap_navigate",{action:"drag",displayMode:i}),h.current={isDragging:!1,startPoint:null},d(P=>({...P,dragging:!1}))},[i]),ce=f.useCallback((P,A)=>{const $=p.current;if(!$||!B.current)return;const Q=$.getContext("2d");if(!Q)return;const[I,H]=k(P,A,B.current,X.current),F=x(),U=F.width,te=F.height,ee=U,G=te;Q.clearRect(0,0,y,y),Q.fillStyle="#fff",Q.fillRect(0,0,y,y);const J=I-ee/2,se=H-G/2,Re=y/ee,ut=y/G,Oe=Math.min(Re,ut),ie=(y-ee*Oe)/2,De=(y-G*Oe)/2;v().forEach(ke=>{const{bounds:Fe}=ke;if(Fe.x+Fe.width>=J&&Fe.x<=J+ee&&Fe.y+Fe.height>=se&&Fe.y<=se+G){const Nt=(Fe.x-J)*Oe+ie,Pt=(Fe.y-se)*Oe+De,Rt=Fe.width*Oe,jt=Fe.height*Oe;Q.fillStyle="rgba(0, 0, 0, 0.6)",Q.fillRect(Nt,Pt,Rt,jt)}}),Q.strokeStyle="rgba(90, 79, 207, 0.6)",Q.lineWidth=1,Q.setLineDash([4,4]),Q.beginPath(),Q.moveTo(0,y/2),Q.lineTo(y,y/2),Q.stroke(),Q.beginPath(),Q.moveTo(y/2,0),Q.lineTo(y/2,y),Q.stroke(),Q.setLineDash([]),Q.strokeStyle="rgba(90, 79, 207, 0.3)",Q.lineWidth=2,Q.strokeRect(0,0,y,y)},[v,x,k]),K=f.useCallback(()=>{u.dragging||w(!0)},[u.dragging]),ae=f.useCallback(()=>{w(!1),m(null),b.current=null},[]),le=f.useCallback(P=>{if(u.dragging){w(!1),b.current=null;return}const A=r.current;if(!A)return;const $=A.getBoundingClientRect(),Q=P.clientX-$.left,I=P.clientY-$.top,H={x:Q,y:I};m(H),b.current=H,w(!0),ce(Q,I),M()},[u.dragging,ce,M]),me=f.useRef(!1),Te=f.useCallback(P=>{me.current=!0;const A=r.current;if(!A)return;const $=P.touches[0],Q=A.getBoundingClientRect(),I=$.clientX-Q.left,H=$.clientY-Q.top,F={x:I,y:H};m(F),b.current=F,w(!0),ce(I,H),M()},[ce,M]),ze=f.useCallback(P=>{const A=r.current;if(!A)return;const $=P.touches[0],Q=A.getBoundingClientRect(),I=$.clientX-Q.left,H=$.clientY-Q.top,F={x:I,y:H};m(F),b.current=F,w(!0),ce(I,H),M()},[ce,M]),Y=f.useCallback(()=>{me.current=!1,setTimeout(()=>{me.current||(w(!1),m(null),b.current=null,M())},500)},[M]);f.useEffect(()=>{if(!u.expanded)return;M();const P=setInterval(()=>{M()},100);return()=>{clearInterval(P)}},[e,u.expanded,M]);const Ie=f.useCallback(()=>{d(P=>{const A=!P.expanded;return{...P,expanded:A,manuallyExpanded:A}})},[]),$e={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},it=S&&(me.current||!u.dragging),Ye=g?{position:"absolute",right:a.width+8,top:Math.max(0,Math.min(g.y-y/2,a.height-y)),width:y,height:y,opacity:it?1:0,pointerEvents:"none",transition:"opacity 0.15s ease-out, top 0.1s ease-out"}:{display:"none"};return l.jsxs("div",{ref:o,className:`minimap ${u.expanded?"minimap--expanded":"minimap--collapsed"} ${i==="auto"?"minimap--auto":""} ${n||""}`,style:{...$e,zIndex:Jt.MINIMAP},"data-track":"minimap_container",children:[u.expanded&&l.jsxs("div",{className:"minimap__content",children:[l.jsx("canvas",{ref:r,width:a.width,height:a.height,className:"minimap__canvas",onPointerDown:Z,onPointerMove:R,onPointerUp:W,onPointerLeave:W,onMouseEnter:K,onMouseLeave:ae,onMouseMove:le,onTouchStart:Te,onTouchMove:ze,onTouchEnd:Y,style:{cursor:u.dragging?"grabbing":"pointer"}}),l.jsx("div",{className:"minimap__preview",style:Ye,children:l.jsx("canvas",{ref:p,width:y,height:y,className:"minimap__preview-canvas"})})]}),a.collapsible&&l.jsx("button",{className:`minimap__toggle ${u.expanded?"minimap__toggle--expanded":""}`,onClick:Ie,title:u.expanded?"折叠小地图":"展开小地图","data-track":"minimap_click_toggle",children:l.jsx(Hy,{})})]})},$h=10,vM=3e3,xM=({showMinimap:e=!0,container:t})=>{var B,X,j,L;const n=bt(),{t:i}=Ee(),{isDrawerOpen:s,drawerWidth:r}=mM(),[o,a]=f.useState(!1),[c,u]=f.useState(!0),[d,h]=f.useState(!1),p=f.useRef(null),g=f.useRef({zoom:((B=n==null?void 0:n.viewport)==null?void 0:B.zoom)||1,offsetX:((X=n==null?void 0:n.viewport)==null?void 0:X.offsetX)||0,offsetY:((j=n==null?void 0:n.viewport)==null?void 0:j.offsetY)||0}),m=f.useRef(!1),b=f.useRef(null),S=f.useMemo(()=>s?r+$h:$h,[s,r]),w=f.useCallback(()=>{fe.updateZoom(n,n.viewport.zoom-.1)},[n]),y=f.useCallback(()=>{fe.updateZoom(n,n.viewport.zoom+.1)},[n]),T=f.useCallback(()=>{fe.fitViewport(n),a(!1)},[n]),C=f.useCallback(()=>{fe.updateZoom(n,1),a(!1)},[n]),E=f.useCallback(()=>{nc(n),a(!1)},[n]),v=f.useCallback(()=>{u(D=>{const k=!D;return h(k),k})},[]);f.useEffect(()=>{if(!c||!n)return;const D=z.getBoardContainer(n);if(!D)return;const k=N=>{var Z;const M=N.target;(Z=p.current)!=null&&Z.contains(M)||(u(!1),h(!1))};return D.addEventListener("mousedown",k),()=>{D.removeEventListener("mousedown",k)}},[c,n]),f.useEffect(()=>{if(!e||!n)return;const D=setInterval(()=>{const k=n.viewport,N=g.current,M=Math.abs(k.zoom-N.zoom)>.001,Z=Math.abs(k.offsetX-N.offsetX)>.5||Math.abs(k.offsetY-N.offsetY)>.5;if(M||Z){if(g.current={zoom:k.zoom,offsetX:k.offsetX,offsetY:k.offsetY},!m.current){m.current=!0;return}c||(u(!0),h(!1)),b.current&&clearTimeout(b.current)}},100);return()=>{clearInterval(D)}},[e,n,c]),f.useEffect(()=>{if(!(!c||d))return b.current=setTimeout(()=>{u(!1)},vM),()=>{b.current&&clearTimeout(b.current)}},[c,d]);const x=f.useCallback(()=>{a(D=>!D)},[]),O=Math.round((((L=n==null?void 0:n.viewport)==null?void 0:L.zoom)||1)*100);return l.jsxs("div",{className:"view-navigation",style:{right:S,zIndex:Jt.VIEW_NAVIGATION},ref:p,"data-testid":"view-navigation",children:[l.jsxs("div",{className:"view-navigation__zoom",children:[l.jsx(Ct,{content:i("zoom.out"),showArrow:!1,children:l.jsx("button",{className:"view-navigation__zoom-btn",onClick:w,"aria-label":i("zoom.out"),"data-track":"view_nav_zoom_out","data-testid":"zoom-out",children:l.jsx(Fy,{})})}),l.jsxs(at,{sideOffset:8,open:o,onOpenChange:a,placement:"bottom",children:[l.jsx(Ct,{content:i("zoom.fit"),showArrow:!1,children:l.jsx(lt,{asChild:!0,children:l.jsxs("button",{className:"view-navigation__zoom-percent",onClick:x,"aria-label":i("zoom.fit"),"data-track":"view_nav_zoom_menu","data-testid":"zoom-display",children:[O,"%"]})})}),l.jsx(ct,{container:t,style:{zIndex:Jt.POPOVER},children:l.jsxs("div",{className:"view-navigation-zoom-menu",children:[l.jsxs("button",{className:"zoom-menu-item",onClick:T,"data-track":"view_nav_zoom_fit",children:[l.jsx("span",{className:"zoom-menu-item__label",children:i("zoom.fit")}),l.jsx("span",{className:"zoom-menu-item__shortcut",children:"⌘⇧="})]}),l.jsx("button",{className:"zoom-menu-item",onClick:E,"data-track":"view_nav_zoom_fit_frame",children:l.jsx("span",{className:"zoom-menu-item__label",children:i("zoom.fitFrame")})}),l.jsxs("button",{className:"zoom-menu-item",onClick:C,"data-track":"view_nav_zoom_100",children:[l.jsx("span",{className:"zoom-menu-item__label",children:i("zoom.100")}),l.jsx("span",{className:"zoom-menu-item__shortcut",children:"⌘0"})]})]})})]}),l.jsx(Ct,{content:i("zoom.in"),showArrow:!1,children:l.jsx("button",{className:"view-navigation__zoom-btn",onClick:y,"aria-label":i("zoom.in"),"data-track":"view_nav_zoom_in","data-testid":"zoom-in",children:l.jsx(Gy,{})})}),e&&l.jsx(Ct,{content:c?"折叠小地图":"展开小地图",showArrow:!1,children:l.jsx("button",{className:`view-navigation__minimap-toggle ${c?"view-navigation__minimap-toggle--expanded":""}`,onClick:v,"aria-label":c?"折叠小地图":"展开小地图","data-track":"view_nav_minimap_toggle",children:l.jsx(zy,{})})})]}),e&&c&&l.jsx("div",{className:"view-navigation__minimap",children:l.jsx(TM,{board:n,displayMode:"always",config:{width:180,height:120,position:"top-right",margin:0,collapsible:!1,defaultExpanded:!0}})})]})},EM=f.lazy(()=>Ne(()=>import("./tool-windows-C4D0lII2.js").then(e=>e.p0),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.MediaLibraryModal}))),_M=({position:e,visible:t,onClose:n,onOpenMediaLibrary:i})=>{const s=bt(),{t:r}=Ee(),o=tc(),a=z.getBoardContainer(s),[c,u]=f.useState({freehand:!1,arrow:!1,shape:!1}),[d,h]=f.useState(!1),{refs:p,floatingStyles:g}=$l({placement:"bottom",middleware:[Xl(12),Of({padding:16}),Kl({fallbackPlacements:["top","right","left"]})]});f.useEffect(()=>{if(e&&t){const[j,L]=e;p.setPositionReference({getBoundingClientRect(){return{width:1,height:1,x:j,y:L,top:L,left:j,right:j+1,bottom:L+1}}})}},[e,t,p]),f.useEffect(()=>{if(!t)return;const j=D=>{const k=D.target,N=k.closest(".quick-creation-toolbar"),M=k.closest(".quick-toolbar-popover")||k.closest("[data-radix-popper-content-wrapper]")||k.closest(".plait-popover")||k.closest(".shape-picker")||k.closest(".arrow-picker")||k.closest(".freehand-panel"),Z=k.closest(".media-library-modal");!N&&!M&&!Z&&n()},L=setTimeout(()=>{document.addEventListener("mousedown",j)},100);return()=>{clearTimeout(L),document.removeEventListener("mousedown",j)}},[t,n]);const m=()=>{u({freehand:!1,arrow:!1,shape:!1})},b=j=>{u({freehand:!1,arrow:!1,shape:!1,[j]:!0})},S=()=>{m(),Cn(s),ht(s,null),fe.updatePointerType(s,Pe.text),o(Pe.text),n()},w=()=>{m(),Cn(s),ht(s,Et.dnd),fe.updatePointerType(s,ki.mind),o(ki.mind),n()},y=()=>{m(),Go(s),n()},T=async j=>{try{j.type===Nn.IMAGE?await ql(s,j.url):j.type===Nn.VIDEO?await pp(s,j.url):j.type===Nn.AUDIO&&await Gl(s,j.url,{title:j.name,duration:j.duration,previewImageUrl:j.thumbnail,prompt:j.prompt,mv:j.modelName,clipId:j.clipId,providerTaskId:j.providerTaskId}),oe.success(r("toolbar.assetInserted")||"素材已插入到画板"),h(!1),n()}catch(L){console.error("Failed to insert asset:",L),oe.error(r("toolbar.assetInsertFailed")||"插入素材失败")}},C=()=>{if(m(),i){i({mode:ni.SELECT,onSelect:T,selectButtonText:r("toolbar.insert")||"插入"}),n();return}h(!0)},[E,v]=f.useState(ot.feltTipPen),x=300,O=f.useRef(null),B=f.useCallback(()=>{O.current&&(clearTimeout(O.current),O.current=null)},[]);f.useEffect(()=>()=>{B()},[B]);const X=(j,L,D,k)=>l.jsxs(at,{open:c[L],sideOffset:12,onOpenChange:N=>{N||m()},placement:"bottom",children:[l.jsx(lt,{asChild:!0,children:l.jsx("div",{onPointerEnter:()=>{B(),O.current=setTimeout(()=>{b(L)},x)},onPointerLeave:()=>{B()},children:l.jsx(ne,{type:"icon",visible:!0,selected:c[L],icon:j,"aria-label":D,"data-track":`quick_toolbar_click_${L}`,onPointerDown:()=>{B(),b(L),Cn(s),L==="freehand"&&(ht(s,Et.dnd),fe.updatePointerType(s,E),o(E))},onPointerUp:()=>{L==="freehand"&&ht(s,Et.drawing)}})})}),l.jsx(ct,{container:a,style:{zIndex:Jt.POPOVER},className:"quick-toolbar-popover",children:k})]});return t?l.jsxs(l.Fragment,{children:[l.jsx(qe,{padding:1,className:`quick-creation-toolbar ${Dt}`,ref:p.setFloating,style:g,children:l.jsxs(pt.Row,{gap:1,children:[l.jsx(ne,{type:"icon",visible:!0,icon:l.jsx(rc,{}),"aria-label":r("toolbar.text"),"data-track":"quick_toolbar_click_text",onPointerUp:S}),l.jsx(ne,{type:"icon",visible:!0,icon:l.jsx(jo,{size:24}),"aria-label":r("toolbar.image"),"data-track":"quick_toolbar_click_image",onPointerUp:y}),l.jsx(ne,{type:"icon",visible:!0,icon:l.jsx(Ro,{}),"aria-label":r("toolbar.mediaLibrary"),"data-track":"quick_toolbar_click_media_library",onPointerUp:C}),X(l.jsx(Ss,{}),"freehand",r("toolbar.pen"),l.jsx(jc,{onPointerUp:j=>{m(),v(j),fe.updatePointerType(s,j),o(j),n()}})),X(l.jsx(sc,{}),"arrow",r("toolbar.arrow"),l.jsx(Oc,{onPointerUp:j=>{m(),fe.updatePointerType(s,j),o(j),n()}})),X(l.jsx(ic,{}),"shape",r("toolbar.shape"),l.jsx(Lc,{onPointerUp:j=>{m(),fe.updatePointerType(s,j),o(j),n()}})),l.jsx(ne,{type:"icon",visible:!0,icon:l.jsx(ro,{}),"aria-label":r("toolbar.mind"),"data-track":"quick_toolbar_click_mind",onPointerUp:w})]})}),d&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(EM,{isOpen:d,onClose:()=>{h(!1)},mode:ni.SELECT,onSelect:T,selectButtonText:r("toolbar.insert")||"插入"})})]}):null};function fN(e){const[t,n]=f.useState({isCached:!1}),[i,s]=f.useState(!1),r=f.useCallback(async()=>{if(!e){n({isCached:!1});return}try{const c=await bi.getCacheInfo(e);n(c)}catch(c){console.error("[useUnifiedCache] Failed to load cache info:",c),n({isCached:!1})}},[e]);f.useEffect(()=>{r()},[r]),f.useEffect(()=>bi.subscribe(()=>{r()}),[r]);const o=f.useCallback(async c=>{if(!e)return!1;s(!0);try{const u=await bi.cacheImage(e,c);return u&&await r(),u}catch(u){return console.error("[useUnifiedCache] Failed to cache image:",u),!1}finally{s(!1)}},[e,r]),a=f.useCallback(async()=>{if(!e)return!1;s(!0);try{return await bi.deleteCache(e),await r(),!0}catch(c){return console.error("[useUnifiedCache] Failed to delete cache:",c),!1}finally{s(!1)}},[e,r]);return{cacheInfo:t,isLoading:i,isCached:t.isCached,cacheAge:t.age,cacheImage:o,deleteCache:a,reload:r}}function CM(e){const[t,n]=f.useState(!1);f.useEffect(()=>{const s=()=>{n(!0),e==null||e()};return bi.onQuotaExceeded(s)},[e]);const i=f.useCallback(()=>{n(!1)},[]);return{isQuotaExceeded:t,resetQuotaFlag:i}}const PM=({children:e,onOpenMediaLibrary:t})=>{const[n,i]=f.useState(!1),{confirm:s,confirmDialog:r}=No(),o=f.useCallback(()=>{n||(i(!0),s({title:"缓存空间已满",description:"图片缓存空间已满,无法继续缓存新图片。是否打开素材库清理缓存?",confirmText:"打开素材库",cancelText:"稍后处理",confirmTheme:"warning"}).then(a=>{i(!1),a&&(t==null||t())}))},[s,n,t]);return CM(o),l.jsxs(l.Fragment,{children:[e,r]})},wo={visible:!1,position:{x:0,y:0},sourceElement:null,currentShape:null,hitIndex:-1,hitPoint:null,mode:"hover",arrowLineElement:null,arrowLineEndPoint:null},Gm=new WeakMap,Dl=new WeakMap;function To(e){return Gm.get(e)||wo}function zs(e,t){Gm.set(e,t);const n=Dl.get(e);n&&n(t)}function kM(e,t){return Dl.set(e,t),()=>{Dl.delete(e)}}function Uc(e){zs(e,wo)}const Is=100;function AM(e,t,n,i,s){const r=Ky(n),o=ge.getRectangleByPoints(t.points),a=o.width,c=o.height,u=o.x+a/2,d=o.y+c/2,p=ge.getEdgeCenterPoints(o)[n];let g,m;switch(r){case ft.right:g=u+a/2+Is+a/2,m=d;break;case ft.bottom:g=u,m=d+c/2+Is+c/2;break;case ft.left:g=u-a/2-Is-a/2,m=d;break;case ft.top:g=u,m=d-c/2-Is-c/2;break;default:g=u+a/2+Is+a/2,m=d}const b=[[g-a/2,m-c/2],[g+a/2,m+c/2]],S=uc(e,b,s);if(S.fill="#ffffff",V.isShapeElement(t)&&!V.isText(t)){const j=t;j.angle!==void 0&&(S.angle=j.angle),j.fill&&j.fill!=="none"&&(S.fill=j.fill),j.strokeColor!==void 0&&(S.strokeColor=j.strokeColor),j.strokeStyle!==void 0&&(S.strokeStyle=j.strokeStyle),j.strokeWidth!==void 0&&(S.strokeWidth=j.strokeWidth)}const w=ao(p,t)||p,y=V.isShapeElement(t)?nr(e,w,t):void 0;let T;switch(r){case ft.right:T=3;break;case ft.bottom:T=0;break;case ft.left:T=1;break;case ft.top:T=2;break;default:T=3}const C=ge.getRectangleByPoints(S.points),v=ge.getEdgeCenterPoints(C)[T],x=ao(v,S)||v,O=nr(e,x,S),B=Mp(En.straight,[w,x],{marker:ir.none,connection:y,boundId:t.id},{marker:ir.arrow,connection:O,boundId:S.id},[],{});ue.insertNode(e,B,[e.children.length]),Ap(e,S),Uc(e);const X=S.id;setTimeout(()=>{const j=e.children.findIndex(D=>D.id===X),L=j>=0?e.children[j]:null;L&&(ii(e),Pi(e,L),fe.updatePointerType(e,vt.selection),ue.setNode(e,{_forceRender:Date.now()},[j]),ue.setNode(e,{_forceRender:void 0},[j]))},50)}function MM(e,t,n,i){var m;let s=100,r=100;const o=t,a=(m=o.source)==null?void 0:m.boundId;if(a){const b=e.children.find(S=>S.id===a);if(b&&V.isShapeElement(b)){const S=ge.getRectangleByPoints(b.points);s=S.width,r=S.height}}const c=[[n[0]-s/2,n[1]-r/2],[n[0]+s/2,n[1]+r/2]],u=uc(e,c,i);u.fill="#ffffff";const d=ge.getRectangleByPoints(u.points),h=ge.getEdgeCenterPoints(d),p=o.points||[];if(p.length>=2){const b=p[0],S=p[p.length-1],w=S[0]-b[0],y=S[1]-b[1];let T;Math.abs(w)>Math.abs(y)?T=w>0?3:1:T=y>0?0:2;const C=h[T],E=nr(e,C,u),v=e.children.findIndex(x=>x.id===t.id);v!==-1&&ue.setNode(e,{target:{marker:ir.arrow,connection:E,boundId:u.id},points:[b,C]},[v])}Ap(e,u),Uc(e);const g=u.id;setTimeout(()=>{const b=e.children.findIndex(w=>w.id===g),S=b>=0?e.children[b]:null;S&&(ii(e),Pi(e,S),fe.updatePointerType(e,vt.selection),ue.setNode(e,{_forceRender:Date.now()},[b]),ue.setNode(e,{_forceRender:void 0},[b]))},50)}const IM=e=>{const{pointerMove:t,pointerLeave:n,globalPointerUp:i}=e;let s=null,r=-1,o=e.children.length,a={x:0,y:0};return e.pointerMove=c=>{var C;a={x:c.clientX,y:c.clientY},s&&(clearTimeout(s),s=null);const u=kp(e),d=u.length===1&&u[0],h=To(e);if(!d||!V.isShapeElement(d)||V.isText(d)){if(h.visible&&h.mode==="hover"&&zs(e,{...wo}),r=-1,d&&V.isShapeElement(d)&&!Qi.getElementRef(d))return;t(c);return}if(!Qi.getElementRef(d)){r=-1;return}const g=Vy(e,c.x,c.y),m=Uy(e,d,!0),b=Wy(e,g,d,!0)||g,S=$y(b,m),w=m[S];if(w){if(S!==r||!h.visible){r=S;const E=c.clientX,v=c.clientY;s=setTimeout(()=>{const x=V.isImage(d)?Pe.rectangle:d.shape||Pe.rectangle;zs(e,{visible:!0,position:{x:E-140,y:v+20},sourceElement:d,currentShape:x,hitIndex:S,hitPoint:w,mode:"hover"})},50)}}else r=-1,h.visible&&h.mode==="hover"&&(s=setTimeout(()=>{const E=To(e);E.visible&&E.mode==="hover"&&zs(e,{...wo})},300));const y=Qi.getElementRef(d);(C=y==null?void 0:y.getGenerator)!=null&&C.call(y,Xy.key)&&t(c)},e.pointerLeave=c=>{s&&(clearTimeout(s),s=null),n(c)},e.globalPointerUp=c=>{var d;i(c);const u=e.children.length;if(u>o){const h=e.children[u-1];if(V.isArrowLine(h)){const p=h;if(!((d=p.target)==null?void 0:d.boundId)){const m=p.points||[];if(m.length>=2){const b=m[m.length-1];setTimeout(()=>{zs(e,{visible:!0,position:{x:a.x-140,y:a.y+20},sourceElement:null,currentShape:Pe.rectangle,hitIndex:-1,hitPoint:null,mode:"arrowLine",arrowLineElement:h,arrowLineEndPoint:b})},50)}}}}o=e.children.length},e},Ds=100;function DM(e){switch(e){case"ArrowRight":return ft.right;case"ArrowDown":return ft.bottom;case"ArrowLeft":return ft.left;case"ArrowUp":return ft.top;default:return null}}function NM(e){switch(e){case ft.top:return 0;case ft.right:return 1;case ft.bottom:return 2;case ft.left:return 3;default:return 1}}function RM(e){return(e+2)%4}function jM(e,t,n,i,s,r){const o={x:t-i/2,y:n-s/2,width:i,height:s};for(const a of e.children)if(a.id!==r&&V.isDrawElement(a)&&!V.isArrowLine(a))try{const c=ge.getRectangleByPoints(a.points);if(o.x<c.x+c.width&&o.x+o.width>c.x&&o.y<c.y+c.height&&o.y+o.height>c.y)return!0}catch{}return!1}function LM(e,t,n){const i=ge.getRectangleByPoints(t.points),s=i.width,r=i.height,o=i.x+s/2,a=i.y+r/2;let c,u;switch(n){case ft.right:c=o+s/2+Ds+s/2,u=a;break;case ft.bottom:c=o,u=a+r/2+Ds+r/2;break;case ft.left:c=o-s/2-Ds-s/2,u=a;break;case ft.top:c=o,u=a-r/2-Ds-r/2;break;default:c=o+s/2+Ds+s/2,u=a}let d=0;const h=n===ft.right||n===ft.left?r+20:s+20;for(;jM(e,c,u,s,r,t.id)&&(d+=h,n===ft.right||n===ft.left?u=a+d:c=o+d,!(d>1e3)););const p=[[c-s/2,u-r/2],[c+s/2,u+r/2]],m=t.shape||"rectangle",b=uc(e,p,m);if(b.fill="#ffffff",V.isShapeElement(t)&&!V.isText(t)){const D=t;D.fill&&D.fill!=="none"&&(b.fill=D.fill),D.strokeColor!==void 0&&(b.strokeColor=D.strokeColor),D.strokeWidth!==void 0&&(b.strokeWidth=D.strokeWidth)}const S=NM(n),w=RM(S),T=ge.getEdgeCenterPoints(i)[S],C=ao(T,t)||T,E=V.isShapeElement(t)?nr(e,C,t):void 0,v=ge.getRectangleByPoints(b.points),O=ge.getEdgeCenterPoints(v)[w],B=ao(O,b)||O,X=nr(e,B,b),j=Mp(En.elbow,[C,B],{marker:ir.none,connection:E,boundId:t.id},{marker:ir.arrow,connection:X,boundId:b.id},[],{});ue.insertNode(e,j,[e.children.length]),ue.insertNode(e,b,[e.children.length]);const L=b.id;setTimeout(()=>{const D=e.children.find(k=>k.id===L);D&&(ii(e),Pi(e,D),fe.updatePointerType(e,vt.selection),Ip(e,[c,u]))},50)}function OM(e,t){var s,r,o,a;const n=[],i=[];for(const c of e.children){if(!V.isArrowLine(c))continue;const u=c;if(((s=u.source)==null?void 0:s.boundId)===t.id&&((r=u.target)!=null&&r.boundId)){const d=e.children.find(h=>h.id===u.target.boundId);d&&i.push(d)}if(((o=u.target)==null?void 0:o.boundId)===t.id&&((a=u.source)!=null&&a.boundId)){const d=e.children.find(h=>h.id===u.source.boundId);d&&n.push(d)}}return{incoming:n,outgoing:i}}function BM(e,t,n){const{incoming:i,outgoing:s}=OM(e,t),r=n?[...s,...i]:[...i,...s];if(r.length===0)return!1;const o=r[0];ii(e),Pi(e,o);try{const a=Ft(e,[o],!1),c=a.x+a.width/2,u=a.y+a.height/2;Ip(e,[c,u])}catch{}return!0}const HM=e=>{const{keyDown:t}=e;return e.keyDown=n=>{if(!n.altKey&&!n.metaKey&&!n.ctrlKey){if(!n.shiftKey){const i=DM(n.key);if(i!==null){const s=kp(e);if(s.length===1){const r=s[0];if(V.isShapeElement(r)&&!V.isText(r)&&!V.isImage(r)){LM(e,r,i),n.preventDefault();return}}}}if(n.key==="Tab"){const i=He(e);if(i.length===1){const s=i[0];if(V.isDrawElement(s)&&V.isShapeElement(s)&&BM(e,s,!n.shiftKey)){n.preventDefault();return}}}}t(n)},e},FM=240,GM=new Set(["5","7"]);function zM(e,t,n){const i=n*Math.PI/180,s=Math.cos(i),r=Math.sin(i),o=e[0]-t[0],a=e[1]-t[1];return[t[0]+o*s-a*r,t[1]+o*r+a*s]}function VM(e,t,n=0){const i=ge.getCenterPoint(e),r=Ni(e,ci).filter(o=>GM.has(String(o.handle)));if(n){const o=zM(t,i,-n),a=r.find(c=>ge.isHit(ge.getRectangleByPoints([o,o]),c.rectangle));return a&&(a.cursorClass=Uo(a.cursorClass,n)),a}return r.find(o=>ge.isHit(ge.getRectangleByPoints([t,t]),o.rectangle))}function UM(e){const t=He(e);return t.length===1&&Kn(t[0])}function WM(e,t){const n=He(e);if(n.length!==1||!Kn(n[0]))return null;const i=n[0],s=ge.getRectangleByPoints(i.points),r=VM(s,t,0);return r?{element:i,rectangle:s,handle:r.handle,cursorClass:r.cursorClass}:null}function $M(e,t,n,i){const s=e.width/e.height,r=t==="7",o=r?-n:n,a=Math.max(FM,e.width+o),c=a/s,u=(e.height-c)/2;return{x:r?e.x+(e.width-a):e.x,y:e.y+u,width:a,height:c}}function XM(e,t,n){const{element:i,rectangle:s,handle:r}=t,{startPoint:o,endPoint:a}=n;if(!s)return;const c=a[0]-o[0];a[1]-o[1];const u=$M(s,r,c),d=[[u.x,u.y],[u.x+u.width,u.y+u.height]],h=e.children.findIndex(p=>p.id===i.id);h>=0&&ue.setNode(e,{points:d},[h])}const KM=e=>Di(e,{key:"audio-nodes",canResize:()=>UM(e),hitTest:(t=>WM(e,t)),onResize:(t,n)=>XM(e,t,n)}),YM=[{icon:l.jsx(Jf,{}),title:"Rectangle",pointer:Pe.rectangle},{icon:l.jsx(ep,{}),title:"Ellipse",pointer:Pe.ellipse},{icon:l.jsx(tp,{}),title:"Triangle",pointer:Pe.triangle},{icon:l.jsx(np,{}),title:"Terminal",pointer:ec.terminal},{icon:l.jsx(ip,{}),title:"Diamond",pointer:Pe.diamond},{icon:l.jsx(sp,{}),title:"Parallelogram",pointer:Pe.parallelogram},{icon:l.jsx(rp,{}),title:"RoundRectangle",pointer:Pe.roundRectangle}],qM=({visible:e,position:t,currentShape:n,onSelectShape:i,onClose:s,container:r})=>{const o=f.useRef(null);f.useEffect(()=>{if(!e)return;const p=b=>{o.current&&!o.current.contains(b.target)&&s()},g=b=>{b.key==="Escape"&&s()},m=setTimeout(()=>{document.addEventListener("mousedown",p),document.addEventListener("keydown",g)},50);return()=>{clearTimeout(m),document.removeEventListener("mousedown",p),document.removeEventListener("keydown",g)}},[e,s]);const a=f.useCallback(p=>{i(p)},[i]);if(!e)return null;const c={x:isNaN(t.x)?0:t.x,y:isNaN(t.y)?0:t.y},u=200,d=80;typeof window<"u"&&(c.x+u>window.innerWidth&&(c.x=window.innerWidth-u-10),c.y+d>window.innerHeight&&(c.y=t.y-d-20));const h=l.jsx("div",{ref:o,className:q("auto-complete-shape-picker",Dt),style:{left:c.x,top:c.y},children:l.jsx(qe,{padding:1,children:l.jsx(pt.Col,{gap:1,children:l.jsx(pt.Row,{gap:1,children:YM.map((p,g)=>l.jsx(ne,{className:q("shape-button",{"is-current":n===p.pointer}),type:"icon",size:"small",visible:!0,icon:p.icon,tooltip:p.title,"aria-label":p.title,onPointerDown:({event:m})=>{m.stopPropagation(),a(p.pointer)}},g))})})})});return r?Lo.createPortal(h,r):h},ZM={visible:!1,position:{x:0,y:0},sourceElement:null,currentShape:null,hitIndex:-1,hitPoint:null,mode:"hover"};function QM(e){const[t,n]=f.useState(ZM);f.useEffect(()=>{if(!e)return;n(To(e));const r=kM(e,o=>{n(o)});return()=>{r()}},[e]);const i=f.useCallback(r=>{if(!e)return;const o=To(e);o.mode==="arrowLine"?o.arrowLineElement&&o.arrowLineEndPoint&&MM(e,o.arrowLineElement,o.arrowLineEndPoint,r):o.sourceElement&&o.hitPoint&&o.hitIndex>=0&&AM(e,o.sourceElement,o.hitIndex,o.hitPoint,r)},[e]),s=f.useCallback(()=>{e&&Uc(e)},[e]);return{state:t,selectShape:i,closePicker:s}}const JM="#ffffff",eI=[Pe.rectangle,Pe.ellipse,Pe.triangle,Pe.diamond,Pe.parallelogram,Pe.roundRectangle];function Xh(e){if(!V.isGeometry(e)||V.isText(e)||V.isImage(e))return!1;const t=e;return!(!t.shape||!eI.includes(t.shape)||t.fill&&t.fill!=="none")}const tI=e=>{const{afterChange:t}=e,n=new Set;return e.afterChange=()=>{t();const i=[];e.children.forEach((s,r)=>{Xh(s)&&!n.has(s.id)&&(i.push({path:[r],element:s}),n.add(s.id))}),i.length>0&&setTimeout(()=>{i.forEach(({path:s})=>{const r=e.children[s[0]];r&&Xh(r)&&ue.setNode(e,{fill:JM},s)})},0)},e},vo=new WeakMap;let Ba=null,An=null;function zm(e,t){try{const n=Qi.getElementG(t);if(n)return n}catch{}if(t!=null&&t.id){const n=z.getElementHost(e);if(n){const i=n.querySelector(`g[id="${t.id}"]`);if(i)return i}}return null}function Vm(e){return e.querySelector("path, rect, ellipse, polygon, circle")}function Um(e){let t=e.querySelector("defs");return t||(t=Yy(),e.insertBefore(t,e.firstChild)),t}function nI(e,t){const n=vo.get(t);if(n){const i=e.querySelector(`#${n}`);i&&i.remove()}}function xo(e,t,n){const i=zm(e,t);if(!i)return;const s=Vm(i);if(!s)return;const r=i.closest("svg");if(!r)return;const o=Ft(e,[t],!1),a=(o==null?void 0:o.width)||100,c=(o==null?void 0:o.height)||100,u=Dp(n,t.id,a,c),d=Um(r);if(u.defElement){const h=u.defElement.id,p=d.querySelector(`#${h}`);p?p.replaceWith(u.defElement):d.appendChild(u.defElement),s.setAttribute("fill",u.fillValue),vo.set(t,h);const g=vo.get(t);if(g&&g!==h){const m=d.querySelector(`#${g}`);m&&m.remove()}}else s.setAttribute("fill",u.fillValue),nI(r,t)}function to(e,t){return e.children.find(n=>n.id===t)||null}function Dn(e){const t=e.fillConfig;return t&&Rn(t)?t:e.fill&&Rn(e.fill)?e.fill:null}function Wm(e,t){if(!e)return!1;if(e==="[object Object]")return!0;if(e.startsWith("url(#")){const n=e.match(/url\(#([^)]+)\)/);if(n){const i=n[1];if(!document.getElementById(i))return!0}return!1}if(t){const n=Dn(t);if(n&&(n.type==="gradient"||n.type==="image"))return!0}return!1}function iI(e){if(!An)return;const t=new Set;e.forEach(n=>{if(n.type==="attributes"&&n.attributeName==="fill"){const i=n.target,s=i.getAttribute("fill"),r=i.closest("g[id]");if(r){const o=r.getAttribute("id");if(o){const a=to(An,o),c=a?Dn(a):null;a&&c&&cn(An,a)&&Wm(s,a)&&t.add(a)}}}n.type==="childList"&&n.addedNodes.forEach(i=>{if(i instanceof SVGGElement&&i.hasAttribute("id")){const s=i.getAttribute("id");if(s){const r=to(An,s),o=r?Dn(r):null;r&&o&&cn(An,r)&&t.add(r)}}if(i instanceof Element){const s=i.closest("g[id]");if(s){const r=s.getAttribute("id");if(r){const o=to(An,r),a=o?Dn(o):null;o&&a&&cn(An,o)&&t.add(o)}}}})}),t.size>0&&t.forEach(n=>{const i=Dn(n);i&&xo(An,n,i)})}function sI(e){if(Ba)return;const t=z.getElementHost(e);t&&(An=e,Ba=new MutationObserver(iI),Ba.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["fill"]}))}function rI(e){const t=z.getElementHost(e);if(!t)return;t.querySelectorAll("path[fill], rect[fill], ellipse[fill], polygon[fill], circle[fill]").forEach(i=>{const s=i.getAttribute("fill"),r=i.closest("g[id]");if(r){const o=r.getAttribute("id");if(o){const a=to(e,o),c=a?Dn(a):null;a&&c&&cn(e,a)&&Wm(s,a)&&xo(e,a,c)}}})}function Nl(e,t=!1){e.children.forEach(n=>{const i=Dn(n);i&&cn(e,n)&&(t?xo(e,n,i):requestAnimationFrame(()=>{xo(e,n,i)}))}),t&&rI(e)}let Kh=!0;const Yh=new WeakSet;function $m(e){const t=z.getElementHost(e);if(!t)return;const n=t.closest("svg")||t.querySelector("svg");n&&e.children.forEach(i=>{const s=Dn(i);if(s&&(s.type==="gradient"||s.type==="image")&&cn(e,i)){const r=Ft(e,[i],!1),o=(r==null?void 0:r.width)||100,a=(r==null?void 0:r.height)||100,c=Dp(s,i.id,o,a);if(c.defElement){const u=Um(n);u.querySelector(`#${c.defElement.id}`)||(u.appendChild(c.defElement),vo.set(i,c.defElement.id))}}})}function oI(e){let t=0;return e.children.forEach(n=>{const i=Dn(n);if(i&&(i.type==="gradient"||i.type==="image")&&cn(e,n)){const s=zm(e,n);(s?Vm(s):null)||t++}}),t}function aI(e){if(Yh.has(e))return;Yh.add(e);const t=15,n=16;let i=0;const s=()=>{i++;try{if(!z.getElementHost(e))return;if($m(e),Nl(e,!0),oI(e)>0&&i<t){const a=Math.min(n*Math.pow(1.5,i),500);setTimeout(s,a)}}catch{}};requestAnimationFrame(()=>{s(),setTimeout(s,0)})}const lI=e=>{const{afterChange:t}=e;return e.afterChange=()=>{t(),sI(e),$m(e),Kh?(Kh=!1,Nl(e,!0),aI(e)):Nl(e,!0)},e};function cI(e,t){return Ni(e,ci).find(i=>ge.isHit(ge.getRectangleByPoints([t,t]),i.rectangle))}function uI(e){const t=He(e);return t.length!==1?!1:Ti(t[0])}function dI(e,t){const n=He(e);if(n.length!==1||!Ti(n[0]))return null;const i=n[0],s=ge.getRectangleByPoints(i.points),r=cI(s,t);return r?{element:i,rectangle:s,handle:r.handle,cursorClass:r.cursorClass}:null}function hI(e,t,n){const{element:i,rectangle:s,handle:r}=t;if(!s)return;const{startPoint:o,endPoint:a}=n,c=a[0]-o[0],u=a[1]-o[1],d=bs(s,r,c,u,pr(),60),h=[[d.x,d.y],[d.x+d.width,d.y+d.height]],p=e.children.findIndex(g=>g.id===i.id);p>=0&&ue.setNode(e,{points:h},[p])}function fI(e,t){const{element:n}=t,i=e.children.find(s=>s.id===n.id);i&&qy.updateFrameMembers(e,i)}const pI=e=>Di(e,{key:"frame-elements",canResize:()=>uI(e),hitTest:t=>dI(e,t),onResize:(t,n)=>hI(e,t,n),afterResize:t=>fI(e,t)});function Ha(e){return!!e.locked}const gI=e=>{const{isHit:t,isRectangleHit:n,isMovable:i}=e;return e.isHit=(s,r,o)=>Ha(s)?!1:t(s,r,o),e.isRectangleHit=(s,r)=>Ha(s)?!1:n(s,r),e.isMovable=s=>Ha(s)?!1:i(s),e},Rl="aitu-tab-sync-version",mI=500,jl=`tab-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;function Xm({onSyncNeeded:e,enabled:t=!0,currentBoardId:n}){const i=f.useRef(-1),s=f.useRef();f.useEffect(()=>{if(!t)return;const r=localStorage.getItem(Rl);if(r)try{const o=JSON.parse(r);i.current=o.version}catch{i.current=parseInt(r,10)||Date.now()}else i.current=Date.now()},[t]),f.useEffect(()=>{if(!t)return;const r=()=>{const a=localStorage.getItem(Rl);if(a)try{const c=JSON.parse(a);if(c.version>i.current&&c.tabId!==jl){const u=n&&c.boardId&&c.boardId===n;i.current=c.version,u&&e()}else c.version>i.current&&c.tabId===jl&&(i.current=c.version)}catch{const c=parseInt(a,10);c>i.current&&(i.current=c)}};s.current=setInterval(()=>{document.hidden||r()},mI);const o=()=>{document.hidden||r()};return document.addEventListener("visibilitychange",o),()=>{s.current&&clearInterval(s.current),document.removeEventListener("visibilitychange",o)}},[t,e,n])}function Km(e){try{const n={version:Date.now(),tabId:jl,boardId:e};localStorage.setItem(Rl,JSON.stringify(n))}catch{}}const pN=Object.freeze(Object.defineProperty({__proto__:null,markTabSyncVersion:Km,useTabSync:Xm},Symbol.toStringTag,{value:"Module"})),Fa=new Set;function SI(){const e=typeof navigator<"u"?navigator.connection:void 0;return e?e.saveData?!1:e.effectiveType!=="slow-2g"&&e.effectiveType!=="2g":!0}function bI(e){if(typeof window>"u"||!("serviceWorker"in navigator)||e.length===0||!SI())return;const t=e.filter(r=>Fa.has(r)?!1:(Fa.add(r),!0));if(t.length===0)return;const n={type:"SW_PREFETCH_GROUPS",groups:t},i=()=>{const r=navigator.serviceWorker.controller;if(r){r.postMessage(n);return}navigator.serviceWorker.ready.then(o=>{var a;(a=o.active)==null||a.postMessage(n)}).catch(()=>{t.forEach(o=>Fa.delete(o))})},s=window.requestIdleCallback;typeof s=="function"?s(()=>i(),{timeout:1500}):window.setTimeout(i,400)}const yI=f.lazy(()=>Ne(()=>import("./DeferredAIInputBar-CKhI8Jhd.js"),__vite__mapDeps([0,4,5,6,7,8,9]),import.meta.url).then(e=>({default:e.DeferredAIInputBar}))),wI=f.lazy(()=>Ne(()=>import("./index-CvbEsbIE.js"),__vite__mapDeps([0,4,5,10]),import.meta.url).then(e=>({default:e.ChatDrawer}))),Xn=["tool-runtime"],Or=["tool-drawers"],Ga=["tool-dialogs"],qh=["tool-runtime","tool-drawers","tool-dialogs"],TI=f.lazy(()=>Ne(()=>import("./DrawnixDeferredFeatures-DxyxvT2y.js"),__vite__mapDeps([0,11]),import.meta.url).then(e=>({default:e.DrawnixDeferredFeatures}))),vI=f.lazy(()=>Ne(()=>import("./tool-windows-C4D0lII2.js").then(e=>e.p3),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.DrawnixDeferredRuntime}))),xI=f.lazy(()=>Ne(()=>import("./ttd-dialog-qD0QkDID.js"),__vite__mapDeps([0,4,6,7,8,2,3,12,13]),import.meta.url).then(e=>({default:e.TTDDialog}))),EI=f.lazy(()=>Ne(()=>import("./settings-dialog-C9BMj8Zj.js"),__vite__mapDeps([0,4,6,14]),import.meta.url).then(e=>({default:e.SettingsDialog}))),_I=f.lazy(()=>Ne(()=>import("./tool-windows-C4D0lII2.js").then(e=>e.oZ),__vite__mapDeps([0]),import.meta.url).then(e=>({default:e.UnifiedMediaViewer}))),CI=f.lazy(()=>Ne(()=>import("./CanvasAudioPlayer-B2W5__ni.js"),__vite__mapDeps([0,15]),import.meta.url).then(e=>({default:e.CanvasAudioPlayer}))),PI=[],kI=({value:e,viewport:t,theme:n,onChange:i,onSelectionChange:s,onViewportChange:r,onThemeChange:o,onValueChange:a,afterInit:c,onBoardSwitch:u,onTabSyncNeeded:d,isDataReady:h=!1,currentBoardId:p})=>{const g={readonly:!1,hideScrollbar:!1,disabledScrollOnNonFocus:!1,themeColors:Sw},[m,b]=f.useState(()=>{const ie=new r_(window.navigator.userAgent);return{pointer:vt.hand,isMobile:ie.mobile()!==null,isPencilMode:!1,openDialogTypes:new Set,dialogInitialData:null,dialogInitialDataByType:{},openCleanConfirm:!1,openSettings:!1}}),[S,w]=f.useState(null),[y,T]=f.useState(!1),[C,E]=f.useState(!1),[v,x]=f.useState(!1),[O,B]=f.useState(!1),[X,j]=f.useState({mode:ni.BROWSE}),[L,D]=f.useState(!1),[k,N]=f.useState(!1),[M,Z]=f.useState(!1),[he,R]=f.useState(!1),[W,ce]=f.useState(!1),[K,ae]=f.useState(!1),[le,me]=f.useState(!1),Te=f.useRef(null),ze=f.useCallback(()=>{T(!1),E(!1),x(!1),B(!1)},[]),Y=f.useCallback((ie=PI)=>{bI(ie),Z(!0)},[]),Ie=f.useCallback((ie=qh)=>{Y(ie),me(!0),ae(!0)},[Y]),$e=f.useCallback(()=>{Ie([...Xn,...Or]),Promise.all([Ne(()=>import("./tool-windows-C4D0lII2.js").then(ie=>ie.oP),__vite__mapDeps([0]),import.meta.url),Ne(()=>import("./tool-windows-C4D0lII2.js").then(ie=>ie.oO),__vite__mapDeps([0]),import.meta.url)]).then(([{toolWindowService:ie},{BUILT_IN_TOOLS:De}])=>{const Le=De.find(Fe=>Fe.id==="knowledge-base");if(!Le)return;const ke=ie.getToolState(Le.id);ke&&ke.status==="open"?ie.closeTool(Le.id):ie.openTool(Le)})},[Ie]);f.useEffect(()=>{const ie=De=>{const{noteId:Le}=De.detail;Ie([...Xn,...Or]),Promise.all([Ne(()=>import("./tool-windows-C4D0lII2.js").then(ke=>ke.oP),__vite__mapDeps([0]),import.meta.url),Ne(()=>import("./tool-windows-C4D0lII2.js").then(ke=>ke.oO),__vite__mapDeps([0]),import.meta.url)]).then(([{toolWindowService:ke},{BUILT_IN_TOOLS:Fe}])=>{const Nt=Fe.find(Rt=>Rt.id==="knowledge-base");if(!Nt)return;const Pt=ke.isToolOpen(Nt.id);ke.openTool(Nt,{componentProps:Le?{initialNoteId:Le}:{}}),Pt&&Le&&window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("kb:open-note",{detail:{noteId:Le}}))},50)})};return window.addEventListener("kb:open",ie),()=>window.removeEventListener("kb:open",ie)},[Ie]);const it=f.useCallback(()=>{if(Ie([...Xn,...Or]),y){T(!1);return}E(!1),x(!1),B(!1),T(!0)},[Ie,y]),Ye=f.useCallback(()=>{if(Ie([...Xn,...Or]),C){E(!1);return}T(!1),x(!1),B(!1),E(!0)},[Ie,C]),P=f.useCallback(()=>{if(Y(Xn),v){x(!1);return}T(!1),E(!1),B(!1),x(!0)},[Y,v]),A=f.useCallback(ie=>{Ie([...Xn,...Ga]),ze(),j({mode:ni.BROWSE,...ie}),B(!0)},[ze,Ie]),$=f.useCallback(()=>{Y([...Xn,...Ga]),D(!0)},[Y]),Q=f.useCallback(()=>{Y([...Xn,...Ga]),N(!0)},[Y]),I=f.useCallback(ie=>{b(ie)},[]),H=f.useCallback(ie=>{b(De=>({...De,...ie}))},[]);f.useEffect(()=>{S&&(S.appState=m,S.__setAppState=I,Te.current=S)},[S,m,I]),f.useEffect(()=>{if(new URLSearchParams(window.location.search).has("tool")){Ie(qh);return}},[Ie]),f.useEffect(()=>{if(typeof window>"u"||!("serviceWorker"in navigator))return;let ie=!1;const De=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1",Le=Pt=>{var Rt,jt;((Rt=Pt.data)==null?void 0:Rt.type)==="SW_IDLE_PREFETCH_STATUS"&&(jt=Pt.data.completedGroups)!=null&&jt.includes("tool-drawers")&&(ie=!0,me(!0))};navigator.serviceWorker.addEventListener("message",Le);const ke={type:"SW_IDLE_PREFETCH_STATUS_GET"},Fe=navigator.serviceWorker.controller;Fe?Fe.postMessage(ke):navigator.serviceWorker.ready.then(Pt=>{var Rt;(Rt=Pt.active)==null||Rt.postMessage(ke)}).catch(()=>{});const Nt=window.setTimeout(()=>{ie||le||(De?console.info("[Drawnix] SW idle prefetch status unresolved in dev, enabling minimized tools bar fallback"):console.warn("[Drawnix] SW idle prefetch status unresolved, enabling minimized tools bar fallback"),me(!0))},2200);return()=>{window.clearTimeout(Nt),navigator.serviceWorker.removeEventListener("message",Le)}},[le]),f.useEffect(()=>{const ie=window.requestIdleCallback;let De;const Le=window.setTimeout(()=>{const ke=()=>{R(!0),ce(!0)};if(typeof ie=="function"){De=ie(ke,{timeout:2500});return}ke()},5e3);return()=>{var ke;window.clearTimeout(Le),typeof De=="number"&&((ke=window.cancelIdleCallback)==null||ke.call(window,De))}},[]),f.useEffect(()=>{const ie=De=>{const Le=De,{message:ke}=Le.detail;oe.error({content:"API Key 无效或已过期,请重新配置",duration:5e3}),console.error("[Drawnix] API auth error:",ke),b(Fe=>({...Fe,openSettings:!0}))};return window.addEventListener(Mu,ie),()=>{window.removeEventListener(Mu,ie)}},[]);const F=[sw,rw,ow,o_,X_,bk(H),Zk,lA,uM,rM,cA(H),CA(H),aw,lw,KA,cw,uw,dw,IM,HM,hw,pI,fw,pw,gw,KM,tI,lI,mw,gI,FA,zA],U=f.useRef(null),{saveBoard:te,createBoard:ee,switchBoard:G}=Zy(),J=f.useCallback(async()=>{if(i&&Te.current){const ie={children:Te.current.children||[],viewport:Te.current.viewport,theme:Te.current.theme};await te(ie)}},[i,te]),se=f.useCallback(async()=>{await J();const ie=await ee({name:"新画布"});ie&&(await G(ie.id),setTimeout(()=>{vi()},500))},[J,ee,G]),Re=f.useCallback(ie=>{const De=Te.current;if(De&&ie){const ke=He(De).map(Fe=>Fe.id).filter(Boolean);H({lastSelectedElementIds:ke})}s&&s(ie)},[s,H]),ut=f.useMemo(()=>({appState:m,setAppState:I,board:S}),[m,I,S]),Oe=he||W||K||m.openCommandPalette||m.openCanvasSearch||y||C||O||L||k;return l.jsx(Qy,{children:l.jsx(Jy,{children:l.jsx(ew,{children:l.jsx(tw,{children:l.jsx(nw,{children:l.jsx(PM,{onOpenMediaLibrary:A,children:l.jsx(gM,{children:l.jsx(iw.Provider,{value:ut,children:l.jsx(AI,{value:e,viewport:t,theme:n,options:g,plugins:F,containerRef:U,appState:m,board:S,setBoard:w,projectDrawerOpen:y,toolboxDrawerOpen:C,taskPanelExpanded:v,mediaLibraryOpen:O,mediaLibraryConfig:X,backupRestoreOpen:L,onChange:i,onSelectionChange:Re,onViewportChange:r,onThemeChange:o,onValueChange:a,afterInit:c,onBoardSwitch:u,onTabSyncNeeded:d,handleProjectDrawerToggle:it,handleToolboxDrawerToggle:Ye,handleKnowledgeBaseToggle:$e,handleTaskPanelToggle:P,handleOpenMediaLibrary:A,handleOpenBackupRestore:$,handleOpenCloudSync:Q,setProjectDrawerOpen:T,setToolboxDrawerOpen:E,setMediaLibraryOpen:B,setBackupRestoreOpen:D,cloudSyncOpen:k,setCloudSyncOpen:N,handleBeforeSwitch:J,isDataReady:h,onCreateProjectForMemory:se,currentBoardId:p,deferredRuntimeEnabled:M,shouldRenderDeferredFeatures:Oe,versionUpdateEnabled:he,performancePanelEnabled:W,toolWindowManagerEnabled:K,minimizedToolsBarEnabled:le,enableToolWindows:Ie})})})})})})})})})},AI=({value:e,viewport:t,theme:n,options:i,plugins:s,containerRef:r,appState:o,board:a,setBoard:c,projectDrawerOpen:u,toolboxDrawerOpen:d,taskPanelExpanded:h,mediaLibraryOpen:p,mediaLibraryConfig:g,backupRestoreOpen:m,deferredRuntimeEnabled:b,shouldRenderDeferredFeatures:S,versionUpdateEnabled:w,performancePanelEnabled:y,toolWindowManagerEnabled:T,minimizedToolsBarEnabled:C,enableToolWindows:E,cloudSyncOpen:v,onChange:x,onSelectionChange:O,onViewportChange:B,onThemeChange:X,onValueChange:j,afterInit:L,onBoardSwitch:D,onTabSyncNeeded:k,handleProjectDrawerToggle:N,handleToolboxDrawerToggle:M,handleKnowledgeBaseToggle:Z,handleTaskPanelToggle:he,handleOpenMediaLibrary:R,handleOpenBackupRestore:W,handleOpenCloudSync:ce,setProjectDrawerOpen:K,setToolboxDrawerOpen:ae,setMediaLibraryOpen:le,setBackupRestoreOpen:me,setCloudSyncOpen:Te,handleBeforeSwitch:ze,isDataReady:Y,onCreateProjectForMemory:Ie,currentBoardId:$e})=>{const{setAppState:it}=Ut(),{chatDrawerRef:Ye}=Fm(),{language:P}=Ee(),A=Iu(Se=>Se.error),$=Iu(Se=>Se.playing||!!Se.activeAudioUrl||!!Se.activeReadingSourceId),Q=f.useRef(void 0),[I,H]=f.useState($);pA({board:a,pointer:o.pointer}),Xm({onSyncNeeded:f.useCallback(()=>{k?k():vi()},[k]),enabled:!0,currentBoardId:$e});const[F,U]=f.useState(!1),[te,ee]=f.useState(null),[G,J]=f.useState(null),se=f.useRef(null),[Re,ut]=f.useState(!1),[Oe,ie]=f.useState([]),[De,Le]=f.useState(0);f.useEffect(()=>{if(!A){Q.current=void 0;return}A!==Q.current&&(Q.current=A,oe.error(A))},[A]),f.useEffect(()=>{$&&H(!0)},[$]),f.useEffect(()=>{Sa.setCanvasQueue(Qa(e))},[e]),f.useEffect(()=>()=>{Sa.stopAndClear()},[]);const ke=f.useCallback(()=>{if(!a||!a.children)return{items:[],elementIds:[]};const Se=[],Ve=[];for(const be of a.children){const je=be.url;if(!je||typeof je!="string"||ba(be))continue;const st=V.isDrawElement(be)&&V.isImage(be),Ue=wn(be);(st||Ue)&&(Se.push({id:be.id,url:je,type:Ue?"video":"image",title:be.name||void 0}),Ve.push(be.id))}return{items:Se,elementIds:Ve}},[a]),Fe=f.useCallback(Se=>{const{items:Ve,elementIds:be}=ke();if(Ve.length===0)return;const je=be.indexOf(Se);je!==-1&&(ie(Ve),Le(je),ut(!0))},[ke]),Nt=f.useCallback(()=>{ut(!1)},[]),Pt=f.useCallback(async(Se,Ve)=>{const be=Ve.id;if(!(!be||!a))try{const{unifiedCacheService:je}=await Ne(async()=>{const{unifiedCacheService:dt}=await import("./tool-windows-C4D0lII2.js").then(dn=>dn.oG);return{unifiedCacheService:dt}},__vite__mapDeps([0]),import.meta.url),{Transforms:st}=await Ne(async()=>{const{Transforms:dt}=await import("./tool-windows-C4D0lII2.js").then(dn=>dn.oE);return{Transforms:dt}},__vite__mapDeps([0]),import.meta.url),Ue=`edited-image-${Date.now()}`,Ge=`/__aitu_cache__/image/${Ue}.png`,gt=await(await fetch(Se)).blob();await je.cacheMediaFromBlob(Ge,gt,"image",{taskId:Ue});const kt=new Image;await new Promise((dt,dn)=>{kt.onload=()=>dt(),kt.onerror=()=>dn(new Error("Failed to load edited image")),kt.src=Se});const Lt=a.children.findIndex(dt=>dt.id===be);if(Lt>=0){const dt=a.children[Lt],{newPoints:dn}=await Gf({url:dt.url,width:dt.width,height:dt.height,points:dt.points||[[0,0],[0,0]]},kt.naturalWidth,kt.naturalHeight);st.setNode(a,{url:Ge,width:kt.naturalWidth,height:kt.naturalHeight,points:dn},[Lt])}}catch(je){console.error("Failed to update image:",je),oe.error("更新失败")}},[a]),Rt=f.useCallback(async Se=>{if(a)try{const{unifiedCacheService:Ve}=await Ne(async()=>{const{unifiedCacheService:Lt}=await import("./tool-windows-C4D0lII2.js").then(dt=>dt.oG);return{unifiedCacheService:Lt}},__vite__mapDeps([0]),import.meta.url),{insertImageFromUrl:be}=await Ne(async()=>{const{insertImageFromUrl:Lt}=await import("./tool-windows-C4D0lII2.js").then(dt=>dt.oK);return{insertImageFromUrl:Lt}},__vite__mapDeps([0]),import.meta.url),je=`edited-image-${Date.now()}`,st=`/__aitu_cache__/image/${je}.png`,Ge=await(await fetch(Se)).blob();await Ve.cacheMediaFromBlob(st,Ge,"image",{taskId:je});const rt=new Image;await new Promise((Lt,dt)=>{rt.onload=()=>Lt(),rt.onerror=()=>dt(new Error("Failed to load edited image")),rt.src=Se});const gt=Ao(a),kt=[((gt==null?void 0:gt[0])??0)+100,((gt==null?void 0:gt[1])??0)+100];await be(a,st,kt,!1,{width:rt.naturalWidth,height:rt.naturalHeight},!1,!0)}catch(Ve){console.error("Failed to insert image:",Ve),oe.error("插入失败")}},[a]),{state:jt,selectShape:nn,closePicker:di}=QM(a);f.useEffect(()=>{G&&se.current&&se.current.focus()},[G]);const Un=f.useCallback(()=>{if(!a||!G||!se.current){J(null);return}const Se=se.current.innerText||"";Se.trim()&&(Mo.insertText(a,G.worldPoint,Se),requestAnimationFrame(()=>{const Ve=a.children[a.children.length-1];if(V.isText(Ve)){const be=Ve;if(!isFinite(be.textHeight)){const je=ge.getRectangleByPoints(be.points);ue.setNode(a,{textHeight:je.height},[a.children.length-1])}}})),J(null),fe.updatePointerType(a,vt.selection),it(Ve=>({...Ve,pointer:vt.selection}))},[a,G,it]);return f.useEffect(()=>{if(!a)return;const Se=be=>{const je=be.target;if(!(je.closest(".board-host-svg")||je.closest(".plait-board-container")))return;const Ue=Gt(a,zt(a,be.clientX,be.clientY)),Ge=Za(a,Ue);if(Ge&&Mt(Ge)){Qg(a,Ge,P),be.preventDefault(),be.stopPropagation();return}if(Ge){if(ba(Ge)){be.preventDefault(),be.stopPropagation();return}const gt=Ge.url;if(gt&&typeof gt=="string"){const kt=V.isDrawElement(Ge)&&V.isImage(Ge),Lt=wn(Ge);if(kt||Lt){Fe(Ge.id),be.preventDefault(),be.stopPropagation();return}}}const rt=je.closest(".plait-tool-container")||je.closest(".plait-workzone-container")||je.closest("foreignObject");if(!Ge&&!rt){const gt=[be.clientX,be.clientY];ee(gt),U(!0)}},Ve=r.current;return Ve&&Ve.addEventListener("dblclick",Se),()=>{Ve&&Ve.removeEventListener("dblclick",Se)}},[a,r,Fe,P]),f.useEffect(()=>{if(!a)return;const Se=be=>{const je=be.target;if(!(je.closest(".board-host-svg")||je.closest(".plait-board-container")))return;const Ue=Gt(a,zt(a,be.clientX,be.clientY)),Ge=Za(a,Ue);if(Ge&&ba(Ge)&&!Kn(Ge)){H(!0);const rt=bw(Ge);if(rt){be.preventDefault(),be.stopPropagation(),Sa.togglePlaybackInQueue(rt,Qa(a.children),{queueSource:"canvas",queueId:Ff,queueName:Hf}).catch(()=>{});return}}if(z.isPointer(a,Pe.text)&&!(je.closest(".plait-tool-container")||je.closest(".plait-workzone-container")||je.closest("foreignObject"))&&!Ge){J({screenX:be.clientX,screenY:be.clientY,worldPoint:Ue,zoom:a.viewport.zoom}),be.preventDefault(),be.stopPropagation();return}u&&K(!1),d&&ae(!1)},Ve=r.current;return Ve&&Ve.addEventListener("click",Se),()=>{Ve&&Ve.removeEventListener("click",Se)}},[a,r,u,d,K,ae]),l.jsx("div",{className:q("drawnix",{"drawnix--mobile":o.isMobile}),ref:r,children:l.jsxs("div",{className:"drawnix__main",children:[l.jsxs(e_,{value:e,viewport:t,theme:n,options:i,plugins:s,onChange:Se=>{x&&x(Se)},onSelectionChange:O,onViewportChange:B,onThemeChange:X,onValueChange:j,children:[l.jsx(qE,{afterInit:Se=>{c(Se),window.__drawnixBoard=Se,L&&L(Se),Se.afterChange&&Se.afterChange()}}),l.jsx(fM,{}),l.jsx(Sk,{projectDrawerOpen:u,onProjectDrawerToggle:N,toolboxDrawerOpen:d,onToolboxDrawerToggle:M,taskPanelExpanded:h,onTaskPanelToggle:he,onOpenBackupRestore:W,onOpenCloudSync:ce,onKnowledgeBaseToggle:Z,onOpenMediaLibrary:R,deferredFeaturesEnabled:T,minimizedToolsBarEnabled:C,onEnableToolWindows:E}),I&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(CI,{})}),l.jsx(RP,{}),l.jsx(PA,{}),l.jsx(uA,{}),l.jsx(mA,{}),l.jsx(EA,{}),l.jsx(vA,{}),o.openDialogTypes.size>0&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(xI,{container:r.current})}),o.openSettings&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(EI,{container:r.current})}),l.jsx(_A,{container:r.current}),l.jsx(f.Suspense,{fallback:null,children:l.jsx(yI,{isDataReady:Y,activationKey:0})}),l.jsx(_M,{position:te,visible:F,onClose:()=>U(!1),onOpenMediaLibrary:R}),G&&l.jsx("div",{ref:se,contentEditable:!0,suppressContentEditableWarning:!0,style:{position:"fixed",left:G.screenX,top:G.screenY-14*G.zoom/2,minWidth:"2px",minHeight:"1.5em",outline:"none",border:"none",background:"transparent",fontSize:`${14*G.zoom}px`,lineHeight:"1.5",color:"#333",caretColor:"#333",zIndex:1e4,whiteSpace:"pre-wrap",fontFamily:"inherit"},onBlur:Un,onKeyDown:Se=>{Se.key==="Escape"&&J(null),Se.stopPropagation()}}),Re&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(_I,{visible:Re,items:Oe,initialIndex:De,onClose:Nt,showThumbnails:!0,useBuiltInEditor:!0,showEditOverwrite:!0,onEditOverwrite:Pt,onEditInsert:Rt})}),l.jsx(qM,{visible:jt.visible,position:jt.position,currentShape:jt.currentShape||void 0,onSelectShape:nn,onClose:di,container:r.current}),l.jsx(xM,{})]}),l.jsx(f.Suspense,{fallback:null,children:l.jsx(wI,{ref:Ye})}),b&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(vI,{board:a,value:e})}),S&&l.jsx(f.Suspense,{fallback:null,children:l.jsx(TI,{board:a,value:e,containerRef:r,versionUpdateEnabled:w,performancePanelEnabled:y,toolWindowManagerEnabled:T,projectDrawerOpen:u,toolboxDrawerOpen:d,mediaLibraryOpen:p,mediaLibraryConfig:g,backupRestoreOpen:m,cloudSyncOpen:v,onBoardSwitch:D,setProjectDrawerOpen:K,setToolboxDrawerOpen:ae,setMediaLibraryOpen:le,setBackupRestoreOpen:me,setCloudSyncOpen:Te,handleBeforeSwitch:ze,onCreateProjectForMemory:Ie})})]})})},MI="Opentu",II="Opentu - AI应用平台";function Eo(e){e&&e.trim()?document.title=`${MI} - ${e.trim()}`:document.title=II}function DI(e){if(!e){Eo();return}const t=Np.getBoard(e);Eo(t==null?void 0:t.name)}function NI(e,t){return f.useEffect(()=>{DI(e)},[e,t]),f.useEffect(()=>{const i=Np.observeEvents().subscribe(s=>{if(s.type==="boardUpdated"){const r=s.payload;r&&r.id===e&&Eo(r.name)}});return()=>{i.unsubscribe()}},[e]),{updateTitle:f.useCallback(i=>{Eo(i)},[])}}const Ym="main_board_content",qm=Gr.createInstance({name:"Drawnix",storeName:yw,driver:[Gr.INDEXEDDB,Gr.LOCALSTORAGE]});async function Zm(){try{const e=await nl.loadState();return(e==null?void 0:e.migrationCompleted)===!0}catch(e){return console.error("[WorkspaceMigration] Failed to check migration status:",e),!1}}async function Zh(){try{const e=await nl.loadState();e.migrationCompleted=!0,await nl.saveState(e)}catch(e){console.error("[WorkspaceMigration] Failed to mark migration completed:",e)}}async function RI(){try{const e=await qm.getItem(Ym);if(e&&e.children&&e.children.length>0)return e;const t=localStorage.getItem(Rp);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 jI(){try{if(await Zm())return null;const t=await RI();if(!t||!t.children||t.children.length===0)return await Zh(),null;const n=bn.getInstance();await n.initialize();const i=await n.createBoard({name:"迁移的画板",elements:t.children,viewport:t.viewport,theme:t.theme});return i?(await n.switchBoard(i.id),await Zh(),await LI(),i.id):(console.error("[WorkspaceMigration] Failed to create board"),null)}catch(e){return console.error("[WorkspaceMigration] Migration failed:",e),null}}async function LI(){try{await qm.removeItem(Ym),localStorage.removeItem(Rp)}catch(e){console.error("[WorkspaceMigration] Failed to clear legacy data:",e)}}function Ns(e){if(!Yt.isAnalyticsEnabled())return;const t=OI(e.name,e.value),n=document.referrer,i={[`$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(()=>{Yt.track("$web_vitals",i)},0)}function OI(e,t){const i={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 i?t<=i.good?"good":t<=i.poor?"needs-improvement":"poor":"needs-improvement"}async function BI(){try{const e=await Ne(()=>import("./web-vitals-DcvjKPr-.js"),[],import.meta.url),{onCLS:t,onFCP:n,onLCP:i,onTTFB:s,onINP:r}=e;t(Ns),n(Ns),i(Ns),s(Ns),r(Ns)}catch(e){console.error("[Web Vitals] Failed to initialize monitoring:",e)}}const fr="page_report",HI="app_page_view";let Qh=!1,Jh="";function FI(){const e=window.innerWidth;return e<768?"mobile":e<1024?"tablet":"desktop"}const ef=200;function GI(){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:FI(),user_agent:e.length>ef?e.slice(0,ef):e,language:navigator.language,timestamp:Date.now()}}function zI(){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,i)=>n+(i.transferSize||0),0)}return e}function za(){if(!Yt.isAnalyticsEnabled())return;const e=GI();e.page_url!==Jh&&(Jh=e.page_url,Yt.track(HI,{category:fr,...e}))}function tf(){if(!Yt.isAnalyticsEnabled())return;const e=zI();if(!e){console.warn("[Page Report] Performance data not available");return}Yt.track("page_performance",{category:fr,...e})}function VI(){if(!Yt.isAnalyticsEnabled())return;const e=Math.round(performance.now());Yt.track("page_unload",{category:fr,page_url:window.location.href,page_path:window.location.pathname,time_on_page:e,timestamp:Date.now()})}function UI(){try{if(Qh)return;Qh=!0,za(),document.readyState==="complete"?tf():window.addEventListener("load",()=>{setTimeout(()=>{tf()},0)}),window.addEventListener("beforeunload",()=>{VI()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?Yt.track("page_hidden",{category:fr,page_url:window.location.href,page_path:window.location.pathname,timestamp:Date.now()}):document.visibilityState==="visible"&&Yt.track("page_visible",{category:fr,page_url:window.location.href,page_path:window.location.pathname,timestamp:Date.now()})}),window.addEventListener("popstate",()=>{setTimeout(()=>{za()},100)});const e=history.pushState;history.pushState=function(...t){e.apply(this,t),setTimeout(()=>{za()},100)}}catch(e){console.error("[Page Report] Failed to initialize monitoring:",e)}}function nf(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",".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 i of n)if(t.matches(i)||t.closest(i))return!0;if(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth){const i=window.getComputedStyle(t);if(i.overflowY==="auto"||i.overflowY==="scroll"||i.overflowX==="auto"||i.overflowX==="scroll")return!0}return!1}function sf(e){if(!e||!(e instanceof Element))return!1;const t=e,n=[".plait-board-container",".plait-board","[plait-board]","svg.rough-svg"];for(const i of n)if(t.matches(i)||t.closest(i))return!0;return!1}function WI(){if(typeof window>"u")return()=>{};const e=i=>{if(i.touches.length>1){const s=i.target;if(nf(s))return;sf(s)&&(i.preventDefault(),i.stopPropagation())}},t=i=>{const s=i.target;nf(s)||sf(s)&&(i.preventDefault(),i.stopPropagation())},n=i=>{(i.ctrlKey||i.metaKey)&&i.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 Ll=$o.DB_CLEANUP_DONE;function Qm(){let e=0;for(const t of jp)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 Jm(){localStorage.getItem(Ll)||(Qm(),localStorage.setItem(Ll,Date.now().toString()))}function $I(){localStorage.removeItem(Ll)}typeof window<"u"&&(window.__dbCleanup={run:Jm,reset:$I,cleanupLS:Qm,LS_KEYS_DEPRECATED:jp});const Wc=[{lsKey:At.PROMPT_HISTORY,idbKey:At.PROMPT_HISTORY,deleteAfterMigration:!0},{lsKey:At.VIDEO_PROMPT_HISTORY,idbKey:At.VIDEO_PROMPT_HISTORY,deleteAfterMigration:!0},{lsKey:At.PRESET_SETTINGS,idbKey:At.PRESET_SETTINGS,deleteAfterMigration:!0},{lsKey:At.BATCH_IMAGE_CACHE,idbKey:At.BATCH_IMAGE_CACHE,deleteAfterMigration:!0},{lsKey:At.RECENT_TEXT_COLORS,idbKey:At.RECENT_TEXT_COLORS,deleteAfterMigration:!0},{lsKey:At.CUSTOM_GRADIENTS,idbKey:At.CUSTOM_GRADIENTS,deleteAfterMigration:!0},{lsKey:At.CUSTOM_FONTS,idbKey:At.CUSTOM_FONTS,deleteAfterMigration:!0},{lsKey:At.TOOLBAR_CONFIG,idbKey:At.TOOLBAR_CONFIG,deleteAfterMigration:!0}];function $c(){try{return localStorage.getItem($o.LS_TO_IDB_MIGRATION_DONE)!==null}catch{return!1}}function XI(){try{localStorage.setItem($o.LS_TO_IDB_MIGRATION_DONE,Date.now().toString())}catch(e){console.error("[StorageMigration] Failed to mark migration done:",e)}}function KI(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 rf(e){try{localStorage.removeItem(e)}catch(t){console.warn(`[StorageMigration] Failed to delete ${e} from LocalStorage:`,t)}}async function YI(e){const{lsKey:t,idbKey:n,deleteAfterMigration:i}=e;try{const s=KI(t);return s===null?{key:t,success:!0}:await xn.get(n)!==null?(i&&rf(t),{key:t,success:!0}):(await xn.set(n,s),await xn.get(n)===null?{key:t,success:!1,error:"Verification failed: data not found after write"}:(i&&rf(t),{key:t,success:!0}))}catch(s){const r=s instanceof Error?s.message:String(s);return console.error(`[StorageMigration] Failed to migrate ${t}:`,s),{key:t,success:!1,error:r}}}async function e0(){if(!xn.isAvailable())return console.warn("[StorageMigration] IndexedDB not available, skipping migration"),[];if($c())return[];const e=[];for(const n of Wc){const i=await YI(n);e.push(i),i.success||console.warn(`[StorageMigration] Failed: ${i.key} - ${i.error}`)}return e.filter(n=>n.success).length,e.filter(n=>!n.success).length===0&&XI(),e}function t0(){try{localStorage.removeItem($o.LS_TO_IDB_MIGRATION_DONE)}catch(e){console.error("[StorageMigration] Failed to reset migration status:",e)}}const qI={isMigrationDone:$c,runMigration:e0,resetMigration:t0,MIGRATION_CONFIGS:Wc};typeof window<"u"&&(window.__storageMigration={run:e0,reset:t0,isDone:$c,configs:Wc});const Xt={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 ZI{constructor(){this.state={crashDetected:!1,crashCount:0,isSafeMode:!1,crashHistory:[]}}markLoadingStart(){try{localStorage.getItem(Xt.LOADING_STATE)==="loading"&&(this.state.crashDetected=!0,this.incrementCrashCount(),this.recordCrash()),localStorage.setItem(Xt.LOADING_STATE,"loading"),this.state.isSafeMode=localStorage.getItem(Xt.SAFE_MODE)==="true",this.loadCrashHistory()}catch(t){console.warn("[CrashRecovery] Failed to mark loading start:",t)}}markLoadingComplete(){try{localStorage.setItem(Xt.LOADING_STATE,"complete"),localStorage.setItem(Xt.LAST_SUCCESS_LOAD,Date.now().toString()),this.state.isSafeMode||(localStorage.setItem(Xt.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(Xt.CRASH_COUNT)||"0",10);this.state.crashCount=t+1,localStorage.setItem(Xt.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(Xt.CRASH_HISTORY);t&&(this.state.crashHistory=JSON.parse(t))}catch{this.state.crashHistory=[]}}saveCrashHistory(){try{localStorage.setItem(Xt.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(Xt.SAFE_MODE,"true"),this.state.isSafeMode=!0}catch{}}disableSafeMode(){try{localStorage.removeItem(Xt.SAFE_MODE),this.state.isSafeMode=!1,localStorage.setItem(Xt.CRASH_COUNT,"0"),this.state.crashCount=0}catch{}}clearCrashState(){try{localStorage.setItem(Xt.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=i=>i<1024*1024?`${(i/1024).toFixed(1)} KB`:i<1024*1024*1024?`${(i/1024/1024).toFixed(1)} MB`:`${(i/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 Kt=new ZI,QI=3e4,JI=800,eD=.6,tD=3,Xc="aitu_last_snapshot",nD=50,Xs=[],iD=20,sD=2e3;let Ks=null;const of=3e3,rD=1e4,oD=200,aD=5e3,lD=10,cD=5e3,uD=30,dD=20,af=20,hD=100,fD=30,pD=240;let lf=null,cf=!1,uf=null,df=null,Va=null,Ua=0,wi=60,Vs=!1,Wa=!1;const ei=[],ti=[],fn=[];function gD(e){const t=Ht(),n=Date.now();return()=>{const i=Ht();if(!t||!i)return;const s=(i.usedJSHeapSize-t.usedJSHeapSize)/(1024*1024),r=Date.now()-n;if(Math.abs(s)>=nD){const o=s>=0?"+":"";console.warn(`[MemoryLog] ${e}: ${o}${s.toFixed(0)} MB (${r}ms)`)}}}function pn(e){if(e)return e.slice(0,pD)}function mD(){return"0.6.64"}function SD(){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:pn(e.scriptURL),state:e.state}:null,readyState:document.readyState,visibilityState:document.visibilityState}}function bD(){const e=Array.from(document.scripts).map(i=>pn(jn(i.src))).filter(Boolean).slice(-8),t=Array.from(document.querySelectorAll('link[rel="stylesheet"]')).map(i=>pn(jn(i.href))).filter(Boolean).slice(-8),n=Array.from(document.querySelectorAll('link[rel="modulepreload"]')).map(i=>pn(jn(i.href))).filter(Boolean).slice(-8);return{scripts:e,stylesheets:t,modulePreloads:n}}function n0(e){if(!(e instanceof HTMLElement))return;const t=e;return{tagName:e.tagName.toLowerCase(),id:pn(e.id||void 0),className:typeof e.className=="string"?pn(e.className):void 0,src:pn(t.currentSrc||t.src?jn(t.currentSrc||t.src||""):void 0),href:pn(t.href?jn(t.href):void 0),rel:pn(t.rel),crossOrigin:pn(t.crossOrigin||void 0)}}function Ol(e){return{appVersion:mD(),recentActions:ei.slice(-10),recentErrors:ti.slice(-5),recentNetworkErrors:fn.slice(-5),serviceWorker:SD(),loadedResources:bD(),...e}}function Ht(){if(typeof performance<"u"&&"memory"in performance){const e=performance.memory;return{usedJSHeapSize:e.usedJSHeapSize,totalJSHeapSize:e.totalJSHeapSize,jsHeapSizeLimit:e.jsHeapSizeLimit}}}function ps(){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 i0(){if(!St.isInitialized()||Xs.length===0)return;const e=Xs.splice(0,Xs.length);for(const t of e)St.reportCrashSnapshot(t).catch(()=>{});Ks&&(clearInterval(Ks),Ks=null)}function yD(){Ks||(Ks=setInterval(()=>{St.isInitialized()&&i0()},sD))}function en(e){try{St.isInitialized()?(i0(),St.reportCrashSnapshot(e).catch(()=>{})):Xs.length<iD&&(Xs.push(e),yD())}catch(t){console.warn("[MemoryLog] Failed to send snapshot to SW:",t)}}function wD(e){try{localStorage.setItem(Xc,JSON.stringify(e))}catch{}}function TD(){try{const e=localStorage.getItem(Xc);if(e)return JSON.parse(e)}catch{}return null}function vD(){try{localStorage.removeItem(Xc)}catch{}}function xD(){const e={id:`startup-${Date.now()}`,timestamp:Date.now(),type:"startup",userAgent:navigator.userAgent,url:location.href,memory:Ht()};en(e)}function ED(){if(lf!==null)return;let e=0;lf=window.setInterval(()=>{const t=Ht();if(!t)return;const n=t.usedJSHeapSize/(1024*1024),i=t.jsHeapSizeLimit/(1024*1024),s=n/i;if(n>JI||s>eD){e++;const a=e>=tD?ps():void 0,c={id:`periodic-${Date.now()}`,timestamp:Date.now(),type:"periodic",memory:t,pageStats:a,userAgent:navigator.userAgent,url:location.href};en(c)}else e=0},QI)}function _D(){window.addEventListener("error",e=>{var n;if(e.error instanceof DOMException&&(e.error.name==="AbortError"||e.error.name==="NotAllowedError"))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:Ht(),userAgent:navigator.userAgent,url:location.href,customData:Ol({filename:e.filename,lineno:e.lineno,colno:e.colno,eventTarget:n0(e.target)})};en(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)||"",i=(t==null?void 0:t.stack)||"";if(t instanceof DOMException&&(t.name==="AbortError"||t.name==="NotAllowedError"||t.name==="DataError"&&n.includes("No key or key range specified"))||n.includes("posthog.com")||n.includes("sentry.io")||i.includes("posthog")||i.includes("sentry"))return;const s={id:`rejection-${Date.now()}`,timestamp:Date.now(),type:"error",error:{message:n||"Unhandled Promise rejection",stack:i,type:"unhandledRejection"},memory:Ht(),userAgent:navigator.userAgent,url:location.href,customData:Ol()};en(s),console.error("[MemoryLog] Unhandled rejection captured:",t)}),window.addEventListener("beforeunload",()=>{const e=Ht();if(e){const t={id:`beforeunload-${Date.now()}`,timestamp:Date.now(),type:"beforeunload",memory:e,userAgent:navigator.userAgent,url:location.href};wD(t),en(t)}})}function CD(){if(uf!==null)return;let e=Date.now();document.addEventListener("visibilitychange",()=>{document.hidden?Wa=!0:(e=Date.now(),setTimeout(()=>{Wa=!1},of+100))}),uf=window.setInterval(()=>{const t=Date.now(),n=t-e;if(n>rD&&!Wa&&!document.hidden){const i={id:`freeze-${Date.now()}`,timestamp:Date.now(),type:"freeze",memory:Ht(),pageStats:ps(),performance:{freezeDuration:n,lastHeartbeat:e,fps:wi},userAgent:navigator.userAgent,url:location.href,customData:{recentActions:ei.slice(-10),recentErrors:ti.slice(-5),recentNetworkErrors:fn.slice(-5)}};en(i)}e=t,St.isInitialized()&&St.sendHeartbeat(t).catch(()=>{})},of)}function PD(){if(Va===null&&!(typeof PerformanceObserver>"u"))try{Va=new PerformanceObserver(e=>{for(const t of e.getEntries())if(t.duration>oD){const i=t.attribution;let s;if(i&&i.length>0){const o=i[0];s={name:o.name,containerType:o.containerType,containerSrc:o.containerSrc,containerId:o.containerId,containerName:o.containerName}}const r={id:`longtask-${Date.now()}`,timestamp:Date.now(),type:"longtask",memory:Ht(),performance:{longTaskDuration:t.duration,fps:wi},userAgent:navigator.userAgent,url:location.href,customData:{taskName:t.name,startTime:t.startTime,attribution:s,debugTip:"Use Chrome DevTools Performance panel to record and analyze the call stack"}};en(r)}}),Va.observe({entryTypes:["longtask"]})}catch{}}function kD(){if(df!==null)return;let e=0;const t=()=>{if(e++,e>=fD){const n=performance.now(),i=n-Ua;i>0&&(wi=Math.round(e*1e3/i)),e=0,Ua=n}requestAnimationFrame(t)};Ua=performance.now(),requestAnimationFrame(t),df=window.setInterval(()=>{if(wi<lD&&wi>0){const n={id:`lowfps-${Date.now()}`,timestamp:Date.now(),type:"freeze",memory:Ht(),performance:{fps:wi},userAgent:navigator.userAgent,url:location.href};en(n)}},aD)}function AD(){setTimeout(()=>{hf()},cD),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&!Vs&&setTimeout(hf,1e3)})}function hf(){if(Vs)return;const e=document.getElementById("root"),t=e&&e.children.length>0,i=!!document.querySelector(".plait-board-container");if(document.body.children.length>1,e&&!t){Vs=!0;const s={id:`whitescreen-${Date.now()}`,timestamp:Date.now(),type:"whitescreen",memory:Ht(),pageStats:{domNodeCount:document.getElementsByTagName("*").length,canvasCount:0,imageCount:0,videoCount:0,iframeCount:0,plaitBoardExists:i},userAgent:navigator.userAgent,url:location.href,customData:{rootExists:!!e,rootChildCount:(e==null?void 0:e.children.length)||0,bodyChildCount:document.body.children.length,hasPlaitBoard:i}};en(s),console.error("[MemoryLog] 白屏检测: React 未渲染内容")}t&&!i&&location.pathname==="/"&&setTimeout(()=>{if(!document.querySelector(".plait-board-container")&&!Vs){Vs=!0;const s={id:`whitescreen-noboard-${Date.now()}`,timestamp:Date.now(),type:"whitescreen",memory:Ht(),pageStats:ps(),userAgent:navigator.userAgent,url:location.href,customData:{reason:"画板未加载",rootChildCount:(e==null?void 0:e.children.length)||0}};en(s),console.error("[MemoryLog] 白屏检测: 画板组件未加载")}},5e3)}function Us(e,t,n){ei.push({time:Date.now(),action:e,target:t,detail:n}),ei.length>uD&&ei.shift()}function MD(){let e=0;document.addEventListener("click",t=>{const n=Date.now();if(n-e<hD)return;e=n;const i=t.target;if(!i)return;const s=()=>{var a,c,u,d,h,p,g,m,b,S,w,y,T,C,E;let r="";const o=(c=(a=i.closest)==null?void 0:a.call(i,"[data-track]"))==null?void 0:c.getAttribute("data-track");if(o)r=o;else if(i.tagName==="BUTTON"||(u=i.closest)!=null&&u.call(i,"button")){const v=((d=i.closest)==null?void 0:d.call(i,"button"))||i,x=(h=v.textContent)==null?void 0:h.trim().slice(0,20),O=(b=(m=(g=(p=v.className)==null?void 0:p.split)==null?void 0:g.call(p," "))==null?void 0:m[0])==null?void 0:b.slice(0,20);r=`btn:${x||O||"unknown"}`}else if(i.tagName==="A")r=`link:${((S=i.pathname)==null?void 0:S.slice(0,30))||""}`;else if(i.tagName==="INPUT"||i.tagName==="TEXTAREA"){const v=i;r=`input:${v.name||v.type||((w=v.placeholder)==null?void 0:w.slice(0,15))||""}`}else if(i.id)r=`#${i.id}`;else{const v=(C=(T=(y=i.className)==null?void 0:y.split)==null?void 0:T.call(y," "))==null?void 0:C[0];r=v?`.${v.slice(0,20)}`:((E=i.tagName)==null?void 0:E.toLowerCase())||"unknown"}Us("click",r)};"requestIdleCallback"in window?window.requestIdleCallback(s,{timeout:100}):setTimeout(s,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),Us("shortcut",n.join("+"))}},{capture:!0,passive:!0}),window.addEventListener("popstate",()=>{Us("navigate",location.pathname)}),window.addEventListener("hashchange",()=>{Us("navigate",location.hash)})}function ID(){const e=window.fetch;window.fetch=async function(t,n){const i=Date.now();try{const s=await e.call(this,t,n);if(!s.ok){const r=typeof t=="string"?t:t.url,o=Date.now()-i,a=jn(r).slice(0,300);fn.push({time:Date.now(),url:a,method:(n==null?void 0:n.method)||"GET",status:s.status,statusText:s.statusText,duration:o}),fn.length>af&&fn.shift()}return s}catch(s){const r=typeof t=="string"?t:t.url,o=Date.now()-i,a=jn(r).slice(0,300);throw fn.push({time:Date.now(),url:a,method:(n==null?void 0:n.method)||"GET",error:s.message,duration:o}),fn.length>af&&fn.shift(),s}}}function DD(){window.addEventListener("error",e=>{var n;const t=e.target;if(t&&t!==window&&t instanceof HTMLElement&&("src"in t||"href"in t)){const i=t.src||t.href,s=(n=t.tagName)==null?void 0:n.toLowerCase();Us("resource_error",s,i==null?void 0:i.slice(0,100));const r={id:`resource-error-${Date.now()}`,timestamp:Date.now(),type:"error",error:{message:`Resource load failed: ${s||"unknown"}`,type:"resourceError"},memory:Ht(),userAgent:navigator.userAgent,url:location.href,customData:Ol({resourceUrl:pn(i?jn(i):void 0),eventTarget:n0(t)})};en(r)}},{capture:!0})}function ND(){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 i=[...t];setTimeout(()=>{var o;let s="",r;for(let a=0;a<Math.min(i.length,5);a++){const c=i[a];if(typeof c=="string")s+=c+" ";else if(typeof c=="number"||typeof c=="boolean")s+=String(c)+" ";else if(c instanceof Error)s+=`Error: ${c.message} `,r=c.stack;else if(c&&typeof c=="object")try{const d=Object.keys(c).slice(0,5).map(h=>{const p=c[h];return`${h}:${typeof p=="string"?p.slice(0,20):typeof p}`}).join(",");s+=`{${d}} `}catch{s+=`[${((o=c.constructor)==null?void 0:o.name)||"Object"}] `}}ti.push({time:Date.now(),message:s.trim().slice(0,500),stack:r}),ti.length>dD&&ti.shift()},0)}}function s0(){return{userActions:[...ei],consoleErrors:[...ti],networkErrors:[...fn],memory:Ht(),pageStats:ps(),fps:wi}}function RD(){typeof window>"u"||(window.__memoryLog={getMemory:()=>{const e=Ht();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:gD,diagnose:()=>{const e=Ht(),t=ps();if(console.group("[MemoryLog] 内存诊断"),e){const n=e.usedJSHeapSize/1048576,i=e.jsHeapSizeLimit/(1024*1024),s=n/i*100;console.log(`内存: ${n.toFixed(0)} MB / ${i.toFixed(0)} MB (${s.toFixed(1)}%)`)}return console.log(`页面: DOM ${t.domNodeCount} | Canvas ${t.canvasCount} | Img ${t.imageCount} | Video ${t.videoCount}`),t.plaitElementCount!==void 0&&console.log(`Plait 元素: ${t.plaitElementCount}`),t.imageCount>50&&console.warn("图片较多,考虑懒加载"),t.domNodeCount>5e3&&console.warn("DOM 节点较多"),console.groupEnd(),{memory:e,pageStats:t}},snapshot:()=>{const e={id:`manual-${Date.now()}`,timestamp:Date.now(),type:"periodic",memory:Ht(),pageStats:ps(),userAgent:navigator.userAgent,url:location.href};en(e)},getDiagnostics:s0,getActions:()=>(console.table(ei.map(e=>({time:new Date(e.time).toLocaleTimeString("zh-CN"),action:e.action,target:e.target,detail:e.detail}))),ei),getNetworkErrors:()=>(console.table(fn.map(e=>({time:new Date(e.time).toLocaleTimeString("zh-CN"),url:e.url,status:e.status,error:e.error}))),fn),getConsoleErrors:()=>(console.table(ti.map(e=>({time:new Date(e.time).toLocaleTimeString("zh-CN"),message:e.message.slice(0,100)}))),ti)})}function jD(){if(cf)return;cf=!0,xD(),_D(),ED(),CD(),PD(),kD(),AD(),MD(),ID(),DD(),ND(),RD();const e=TD();e&&(e.customData={...e.customData,recovered:!0,recoveredAt:Date.now()},en(e),vD())}function Bl(e,t){try{const n=LD(e,t),i=JSON.stringify(n,null,2),s=new Blob([i],{type:"application/json"}),r=URL.createObjectURL(s),o=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),a=document.createElement("a");a.href=r,a.download=`opentu-error-log-${o}.json`,a.style.display="none",document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(r)},100)}catch(n){console.error("[ErrorLogExporter] Failed to export:",n)}}function LD(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:Kt.getState(),diagnostics:s0(),unifiedLogs:ww.getMemoryLogs()};return e&&(n.currentError={message:e.message,stack:e.stack,componentStack:(t==null?void 0:t.componentStack)??void 0}),n}const OD="aitu:lazy-chunk-retry",BD="_lazy_chunk_retry",HD="_t",FD=[/Failed to fetch dynamically imported module/i,/Importing a module script failed/i,/Loading chunk [\w-]+ failed/i,/ChunkLoadError/i];function GD(){var e;return typeof document>"u"?"unknown":((e=document.querySelector('meta[name="app-version"]'))==null?void 0:e.getAttribute("content"))||"unknown"}function r0(e){if(e instanceof Error){const t=[e.name,e.message,e.stack];return e.cause&&t.push(String(e.cause)),t.filter(Boolean).join(`
|
|
67
67
|
`)}return String(e??"")}function zD(e){const t=e.match(/https?:\/\/[^\s)'"]+\.js(?:\?[^\s)'"]*)?/i);if(!t)return"unknown-module";try{return new URL(t[0]).pathname}catch{return t[0]}}function VD(e){const t=r0(e);return FD.some(n=>n.test(t))}function UD(e){if(typeof window>"u"||typeof sessionStorage>"u"||!VD(e))return!1;const t=r0(e),n=`${OD}:${GD()}:${zD(t)}`;try{if(sessionStorage.getItem(n)==="1")return!1;sessionStorage.setItem(n,"1")}catch{return!1}const i=new URL(window.location.href);return i.searchParams.set(BD,"1"),i.searchParams.set(HD,String(Date.now())),console.warn("[ErrorBoundary] Detected stale lazy chunk. Reloading once to recover.",e),window.setTimeout(()=>{window.location.replace(i.toString())},0),!0}class WD extends f.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 i=UD(t);this.setState({errorInfo:n,recoveringFromChunkError:i}),!i&&console.error("[ErrorBoundary] React render error:",t,n)}render(){var t,n,i,s,r,o;return this.state.hasError?this.state.recoveringFromChunkError?l.jsx(Co,{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:((i=this.state.errorInfo)==null?void 0:i.componentStack)??void 0,onExportLog:()=>Bl(this.state.error,this.state.errorInfo),onSafeModeReload:Hl,onGoToDebug:_o}):l.jsx(Co,{variant:"error",errorMessage:((s=this.state.error)==null?void 0:s.message)||"未知错误",errorStack:(r=this.state.error)==null?void 0:r.stack,componentStack:((o=this.state.errorInfo)==null?void 0:o.componentStack)??void 0,onExportLog:()=>Bl(this.state.error,this.state.errorInfo),onSafeModeReload:Hl,onGoToDebug:_o}):this.props.children}}function Hl(){try{localStorage.setItem("aitu_safe_mode","true")}catch{}window.location.reload()}function _o(){const e="/sw-debug.html";window.location.href=e}const $D={crash:{iconBg:"#FFF3E0",iconStroke:"#F57C00",iconPath:l.jsxs(l.Fragment,{children:[l.jsx("circle",{cx:"12",cy:"12",r:"10"}),l.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),l.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),defaultTitle:"检测到页面异常退出",defaultDesc:""},error:{iconBg:"#FFEBEE",iconStroke:"#E53935",iconPath:l.jsxs(l.Fragment,{children:[l.jsx("circle",{cx:"12",cy:"12",r:"10"}),l.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),l.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}),defaultTitle:"应用渲染出错",defaultDesc:"页面遇到了意外错误,可能是画布数据异常或浏览器内存不足。"}},Co=e=>{const{variant:t,crashCount:n,memoryInfo:i,onIgnore:s,title:r,description:o,errorMessage:a,errorStack:c,componentStack:u,onExportLog:d,onSafeModeReload:h,onGoToDebug:p}=e,[g,m]=Gn.useState(!1),b=$D[t],S=r||b.defaultTitle,w=o||b.defaultDesc;return l.jsx("div",{style:wt.overlay,children:l.jsxs("div",{style:wt.card,children:[l.jsx("div",{style:{...wt.iconWrap,backgroundColor:b.iconBg},children:l.jsx("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:b.iconStroke,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:b.iconPath})}),l.jsx("h2",{style:wt.title,children:S}),t==="crash"&&n!=null&&l.jsxs("p",{style:wt.desc,children:["页面已连续 ",n," 次未能正常加载,可能是因为:",l.jsx("br",{}),"• 画布元素过多导致内存不足",l.jsx("br",{}),"• 浏览器内存限制",l.jsx("br",{}),l.jsx("br",{}),"建议使用「安全模式」创建空白画布,稍后可从侧边栏切换到其他画布。"]}),t==="error"&&w&&l.jsx("p",{style:wt.desc,children:w}),i&&l.jsx(XD,{info:i}),t==="error"&&a&&l.jsxs("div",{style:wt.errorBox,children:[l.jsx("div",{style:wt.errorMsg,children:a}),(c||u)&&l.jsx("button",{onClick:()=>m(y=>!y),style:wt.detailToggle,children:g?"收起详情":"展开详情"}),g&&l.jsxs("pre",{style:wt.errorDetail,children:[c,u&&`
|
|
68
68
|
|
|
69
|
-
Component Stack:${u}`]})]}),l.jsxs("div",{style:wt.btnRow,children:[t==="crash"&&s&&l.jsx(Br,{label:"继续加载",onClick:s,bg:"#f5f5f5",bgHover:"#e8e8e8",color:"#666"}),t==="error"&&d&&l.jsx(Br,{label:"导出错误日志",onClick:d,bg:"#f5f5f5",bgHover:"#e8e8e8",color:"#333"}),l.jsx(Br,{label:"安全模式",onClick:h,bg:"#F39C12",bgHover:"#E67E22",color:"#fff"})]}),l.jsx("div",{style:wt.divider}),l.jsx("div",{style:wt.helpSection,children:l.jsxs("div",{style:wt.helpRow,children:[l.jsx("img",{src:"https://nav.ourzhishi.top/api/dynamic-image/qr-code",alt:"企业微信二维码",style:wt.qrcode,referrerPolicy:"no-referrer"}),l.jsxs("div",{style:wt.helpText,children:[l.jsx("p",{style:wt.helpTitle,children:"需要帮助?"}),l.jsx("p",{style:wt.helpDesc,children:"扫码联系客服,或前往调试页面导出完整日志与备份数据"}),l.jsx(Br,{label:"打开调试页面",onClick:p,bg:"#f0eefa",bgHover:"#e2ddf7",color:"#5A4FCF",small:!0})]})]})})]})})},XD=({info:e})=>{const t=e.percent>75?"#E53935":e.percent>50?"#FB8C00":"#43A047";return l.jsxs("div",{style:wt.memoryBox,children:[l.jsx("div",{style:{fontSize:12,color:"#888",marginBottom:8},children:"当前内存使用情况"}),l.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[l.jsxs("span",{style:{fontSize:14,color:"#333"},children:[e.used," / ",e.limit]}),l.jsxs("span",{style:{fontSize:14,fontWeight:500,color:t},children:[e.percent.toFixed(0),"%"]})]}),l.jsx("div",{style:{height:4,backgroundColor:"#e0e0e0",borderRadius:2,marginTop:8,overflow:"hidden"},children:l.jsx("div",{style:{height:"100%",width:`${Math.min(e.percent,100)}%`,backgroundColor:t,transition:"width 0.3s ease"}})})]})},Br=({label:e,onClick:t,bg:n,bgHover:i,color:s,small:r})=>{const[o,a]=Gn.useState(!1),c=r?{...wt.btnSmall,backgroundColor:o?i:n,color:s}:{...wt.btn,backgroundColor:o?i:n,color:s};return l.jsx("button",{onClick:t,onMouseOver:()=>a(!0),onMouseOut:()=>a(!1),style:c,children:e})},wt={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}},KD=500,Fl="board",Kc="aitu_board_close_snapshot_v1";let $a=!1;function YD(){if(!(typeof window>"u"))return window.__OPENTU_BOOT__}function ff(){return new URLSearchParams(window.location.search).get(Fl)}function pf(e,t=!1){const n=new URL(window.location.href);e?n.searchParams.set(Fl,e):n.searchParams.delete(Fl),t?window.history.replaceState({boardId:e},"",n.toString()):window.history.pushState({boardId:e},"",n.toString())}function qD(e){try{localStorage.setItem(Kc,JSON.stringify(e))}catch(t){console.warn("[App] Failed to save board close snapshot:",t)}}function o0(){try{const e=localStorage.getItem(Kc);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 Hr(e){try{const t=o0();if(!t)return;(!e||t.boardId===e)&&localStorage.removeItem(Kc)}catch(t){console.warn("[App] Failed to clear board close snapshot:",t)}}function ZD(){const[e,t]=f.useState(!0),[n,i]=f.useState(!1),s=f.useRef(!1),[r,o]=f.useState(!1),[a,c]=f.useState(null),[u,d]=f.useState({children:[]}),[h,p]=f.useState(null),g=f.useRef(null),m=f.useRef(),b=f.useRef(null),S=f.useRef(null),w=f.useRef(!1),y=f.useRef(null),T=f.useRef(!1),C=f.useRef(!1),E=f.useRef(!1);NI(h),f.useEffect(()=>{g.current=h},[h]);const v=f.useCallback((D,k,N=Date.now())=>{m.current=k.viewport,b.current={boardId:D,children:k.children,viewport:k.viewport,theme:k.theme,updatedAt:N}},[]),x=f.useCallback(D=>{const k=b.current,N=g.current;if(!k||!N||k.boardId!==N||!E.current)return;qD({...k,updatedAt:Date.now()}),bn.getInstance().saveCurrentBoard({children:k.children,viewport:k.viewport,theme:k.theme}).catch(Z=>{console.warn(`[App] Failed to flush board on ${D}:`,Z)})},[]);f.useEffect(()=>{const D=YD();D&&(r||a||!e)&&D.markReady()},[a,e,r]),f.useEffect(()=>{(async()=>{if(Kt.shouldShowSafeModePrompt()&&!Kt.isSafeMode()){o(!0),t(!1);return}if($a){const k=bn.getInstance();t(!1),await k.waitForInitialization();const N=k.getState().currentBoardId;if(N&&k.getBoardMetadata(N)){const M=await k.switchBoard(N),Z={children:M.elements||[],viewport:M.viewport,theme:M.theme};v(M.id,Z,M.updatedAt),E.current=!1,d(Z)}t(!1),Kt.markLoadingComplete();return}$a=!0;try{const k=bn.getInstance();if(t(!1),await k.initialize(),await Zm()||await jI(),Kt.isSafeMode()){console.log("[App] Safe mode: looking for existing safe mode board");const ce=k.getAllBoards().find(le=>le.name.startsWith("安全模式")&&(!le.elements||le.elements.length===0));if(ce)console.log("[App] Safe mode: reusing existing board:",ce.name),await k.switchBoard(ce.id),p(ce.id);else{console.log("[App] Safe mode: creating new blank board");const le=new Date().toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).replace(/\//g,"-"),me=await k.createBoard({name:`安全模式 ${le}`,elements:[]});me&&(await k.switchBoard(me.id),p(me.id))}const K={children:[]},ae=(ce==null?void 0:ce.id)||g.current||"safe-mode";v(ae,K,Date.now()),d(K),s.current=!0,i(!0),t(!1),Kt.markLoadingComplete(),Kt.disableSafeMode(),setTimeout(()=>{oe.warning({content:"当前处于安全模式,已创建空白画布。可从侧边栏切换到其他画布。",duration:8e3,closeBtn:!0})},500);return}let M=null;const Z=ff(),he=k.getState().currentBoardId;let R=null;if(Z&&k.getBoardMetadata(Z)?R=Z:he&&k.getBoardMetadata(he)&&(R=he),R)M=await k.switchBoard(R);else if(k.hasBoards()){const W=k.getTree(),ce=a0(W);ce&&(M=await k.switchBoard(ce.id))}else{const W=await k.createBoard({name:"我的画板1",elements:[]});W&&(M=await k.switchBoard(W.id))}if(M&&(pf(M.id,!0),p(M.id),k.persistCurrentBoardId(M.id),E.current=!1),M){const W=o0();let ce={children:M.elements||[],viewport:M.viewport,theme:M.theme};if(W&&W.boardId===M.id&&W.updatedAt>M.updatedAt){ce={children:W.children,viewport:W.viewport,theme:W.theme},M={...M,...ce,updatedAt:W.updatedAt};const K=M.id;k.saveBoard(K,ce).then(()=>{E.current=!1,Hr(K)}).catch(ae=>{console.warn("[App] Failed to rehydrate board from close snapshot:",ae)}),oe.warning({content:"检测到上次关闭前的未落盘画布,已自动恢复",duration:5e3,closeBtn:!0})}else W&&W.boardId&&!k.getBoardMetadata(W.boardId)&&Hr(W.boardId);v(M.id,ce,M.updatedAt),E.current=!1,d(ce),Xa(ce.children).then(K=>{if(K!==ce.children){const ae={...ce,children:K};v(M.id,ae,Date.now()),d(ae)}}).catch(K=>{console.error("[App] Video URL recovery failed:",K)})}}catch(k){console.error("[App] Initialization failed:",k),c(k instanceof Error?k:new Error(String(k)))}finally{s.current=!0,i(!0),t(!1),Kt.markLoadingComplete()}})()},[v]);const O=f.useCallback(async(D,k=!1)=>{try{k||(pf(D.id),bn.getInstance().persistCurrentBoardId(D.id)),p(D.id),C.current=!1,E.current=!1;const M={children:await Xa(D.elements||[]),viewport:D.viewport,theme:D.theme};v(D.id,M,D.updatedAt),d(M),setTimeout(()=>{y.current&&(qs(y.current),xf(y.current),no(y.current))},0)}catch(N){console.error("[App] Board switch failed:",N),oe.error({content:`切换画板失败: ${N instanceof Error?N.message:"未知错误"}`,duration:5e3,closeBtn:!0})}},[v]);f.useEffect(()=>{const D=async()=>{if(!w.current){w.current=!0;try{const k=ff();if(k&&k!==h){const N=bn.getInstance(),M=await N.switchBoard(k);M&&(await O(M,!0),N.persistCurrentBoardId(M.id))}}catch(k){console.error("[App] Failed to handle browser navigation:",k)}finally{w.current=!1}}};return window.addEventListener("popstate",D),()=>{window.removeEventListener("popstate",D)}},[h,O]);const B=f.useCallback(async()=>{T.current=!0;try{const D=bn.getInstance();let k=D.getCurrentBoard();if(!k){const M=D.getState().currentBoardId;if(!M){console.warn("[App] handleTabSyncNeeded: no current board ID");return}if(!D.getBoardMetadata(M)){console.warn("[App] handleTabSyncNeeded: board not found",M);return}try{k=await D.switchBoard(M)}catch(Z){console.error("[App] handleTabSyncNeeded: failed to load board",Z);return}}const N=await D.reloadBoard(k.id);if(N){const Z={children:await Xa(N.elements||[]),viewport:N.viewport,theme:N.theme};v(N.id,Z,N.updatedAt),E.current=!1,d(Z)}}catch(D){console.error("[App] Failed to sync board data:",D),vi()}finally{setTimeout(()=>{T.current=!1},100)}},[v]),X=f.useCallback(D=>{if(d(D),m.current=D.viewport,!s.current||T.current)return;C.current=!0,E.current=!0;const k=bn.getInstance(),N=k.getCurrentBoard();if(!N){console.warn("[App] handleBoardChange: board not fully loaded, skipping save");return}v(N.id,D),k.saveCurrentBoard(D).then(()=>{E.current=!1,Hr(N.id),Km(N.id)}).catch(M=>{console.error("[App] Failed to save board:",M)})},[v]),j=f.useCallback(D=>{m.current=D;const k=b.current;k&&(b.current={...k,viewport:D,updatedAt:Date.now()}),!T.current&&(E.current=!0,S.current&&clearTimeout(S.current),S.current=setTimeout(()=>{if(T.current)return;const N=bn.getInstance(),M=N.getCurrentBoard();M&&N.saveCurrentBoard({children:M.elements,viewport:D,theme:M.theme}).then(()=>{E.current=!1,Hr(M.id)}).catch(Z=>{console.error("[App] Failed to save viewport:",Z)})},KD))},[v]);f.useEffect(()=>{const D=Z=>{if(S.current&&(clearTimeout(S.current),S.current=null),T.current)return;const R=bn.getInstance().getCurrentBoard(),W=b.current,ce=m.current,K=g.current;R&&K&&(!W||W.boardId!==K)&&v(R.id,{children:R.elements,viewport:ce??R.viewport,theme:R.theme},Date.now()),!(Z==="visibilitychange"&&!C.current)&&x(Z)},k=()=>{D("beforeunload")},N=()=>{document.visibilityState==="hidden"&&D("visibilitychange")},M=()=>{D("pagehide")};return window.addEventListener("beforeunload",k),window.addEventListener("pagehide",M),document.addEventListener("visibilitychange",N),()=>{window.removeEventListener("beforeunload",k),window.removeEventListener("pagehide",M),document.removeEventListener("visibilitychange",N),S.current&&clearTimeout(S.current)}},[x,v]);const L=f.useCallback(D=>{o(!1),D?Kt.enableSafeMode():Kt.clearCrashState(),t(!0),$a=!1,setTimeout(()=>{vi()},100)},[]);return r?l.jsx(Co,{variant:"crash",crashCount:Kt.getCrashCount(),memoryInfo:Kt.getMemoryInfo(),onIgnore:()=>L(!1),onSafeModeReload:()=>L(!0),onGoToDebug:_o}):a?l.jsx(Co,{variant:"error",title:"应用初始化失败",description:"无法加载画板数据,可能是存储损坏或浏览器限制。",errorMessage:a.message,errorStack:a.stack,onExportLog:()=>Bl(a),onSafeModeReload:Hl,onGoToDebug:_o}):e?l.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100vh"},children:"加载中..."}):l.jsx("div",{style:{height:"100vh"},children:l.jsx(kI,{value:u.children,viewport:u.viewport,theme:u.theme,onChange:X,onViewportChange:j,onBoardSwitch:O,onTabSyncNeeded:B,isDataReady:n,currentBoardId:h,afterInit:D=>{y.current=D,window.__drawnix__web__console=k=>{QD(D,k)}}})})}const QD=(e,t)=>{const n=z.getBoardContainer(e).closest(".drawnix");let i=n.querySelector(".drawnix-console");i||(i=document.createElement("div"),i.classList.add("drawnix-console"),n.append(i));const s=document.createElement("div");s.innerHTML=t,i.append(s)};async function Xa(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 i=n.indexOf("#merged-video-");if(i!==-1){const s=n.substring(i+1),r=s.indexOf("#",1),a=`/__aitu_cache__/video/${r>0?s.substring(0,r):s}.mp4`;return{...t,url:a}}}return t})}function a0(e){for(const t of e){if(t.type==="board")return t.data;if(t.type==="folder"&&t.children){const n=a0(t.children);if(n)return n}}return null}const gf=window.addEventListener.bind(window),JD=window.removeEventListener.bind(window);let Yc=null;window.addEventListener=function(e,t,n){if(e==="unload"){console.warn("[Permissions Policy] Blocked unload event listener");return}return e==="beforeunload"&&(Yc=t),gf.call(window,e,t,n)};window.removeEventListener=function(e,t,n){return e==="beforeunload"&&(Yc=null),JD.call(window,e,t,n)};window.__checkBeforeUnload=()=>!!Yc;let mf=!1;const l0="sw-debug-enabled";function eN(){try{return sessionStorage.getItem(l0)==="true"}catch{return!1}}function Sf(e){try{sessionStorage.setItem(l0,e===!0?"true":"false")}catch{}}let Rs=eN();const Ys=[];let rs=null,Zn=0;const Po=15e3,js={error:console.error,warn:console.warn,info:console.info,log:console.log,debug:console.debug};function fi(e,t,n){if(t.includes("[SW]")||t.includes("[SWTaskQueue]")||t.includes("[SWChannelManager]")||t.includes("Invalid message structure")||t.includes("posthog.com")||t.includes("sentry.io")||n&&(n.includes("posthog")||n.includes("sentry")))return;const i=()=>{St.isInitialized()&&St.reportConsoleLog(e,[{message:t,stack:n||"",source:window.location.href}],Date.now()).catch(()=>{})},s=()=>{for(;Ys.length>0&&St.isInitialized();){const o=Ys.shift();St.reportConsoleLog(o.level,[{message:o.message,stack:o.stack||"",source:window.location.href}],Date.now()).catch(()=>{})}},r=()=>{const o=Date.now();rs||o<Zn||(rs=St.initialize().then(a=>{if(!a){Zn=Date.now()+Po;return}Zn=0,s()}).catch(()=>{Zn=Date.now()+Po}).finally(()=>{rs=null}))};St.isInitialized()?i():(Ys.push({level:e,message:t,stack:n}),r())}function Ls(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 bf(e){for(const t of e)if(t instanceof Error&&t.stack)return t.stack;return""}function tN(){if(mf||!("serviceWorker"in navigator))return;mf=!0;const e=()=>{if(St.isInitialized())St.subscribeToEvent("debug:statusChanged",t=>{const n=t,i=n.enabled??n.debugModeEnabled??!1;Rs=i,Sf(i)}),St.getDebugStatus().then(t=>{const n=t.enabled??t.debugModeEnabled??!1;Rs=n,Sf(n)});else{const t=Date.now();!rs&&t>=Zn&&(rs=St.initialize().then(n=>{if(!n){Zn=Date.now()+Po;return}for(Zn=0;Ys.length>0&&St.isInitialized();){const i=Ys.shift();St.reportConsoleLog(i.level,[{message:i.message,stack:i.stack||"",source:window.location.href}],Date.now()).catch(()=>{})}}).catch(()=>{Zn=Date.now()+Po}).finally(()=>{rs=null})),setTimeout(e,500)}};e(),console.error=function(...t){js.error.apply(console,t),fi("error",Ls(t),bf(t))},console.warn=function(...t){js.warn.apply(console,t),fi("warn",Ls(t),bf(t))},console.log=function(...t){js.log.apply(console,t),Rs&&fi("log",Ls(t),"")},console.info=function(...t){js.info.apply(console,t),Rs&&fi("info",Ls(t),"")},console.debug=function(...t){js.debug.apply(console,t),Rs&&fi("debug",Ls(t),"")},window.addEventListener("error",t=>{var i;const n=`${t.message} at ${t.filename}:${t.lineno}:${t.colno}`;fi("error",n,((i=t.error)==null?void 0:i.stack)||"")}),window.addEventListener("unhandledrejection",t=>{const n=t.reason,i=n instanceof Error?n.message:`Unhandled Promise: ${String(n)}`,s=n instanceof Error&&n.stack||"";fi("error",i,s)})}"serviceWorker"in navigator&&tN();Kt.markLoadingStart();Kt.checkUrlSafeMode();jD();const nN=typeof window<"u"&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),iN=typeof window<"u"&&new URLSearchParams(window.location.search).get("report")==="1",sN=iN||!nN&&!0,c0="0.6.63",oa=Tw(),yf="_lazy_chunk_retry",rN="_t";function oN(){if(typeof window>"u")return;const e=new URL(window.location.href);if(e.searchParams.has(yf)){e.searchParams.delete(yf),e.searchParams.delete(rN);try{window.history.replaceState(window.history.state,"",e.toString())}catch{}}}oN();function u0(e){return e==="jsdelivr"||e==="unpkg"||e==="local"}function aN(){return window.__OPENTU_BOOT__||null}function Zi(e){var t,n;(n=(t=aN())==null?void 0:t.setProgress)==null||n.call(t,e==null?void 0:e.progress,e)}function lN(){const e=window.__OPENTU_CDN__||window.__AITU_CDN__;return!e||!u0(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 wf(e){const t=lN();if(!t)return;const n={type:"SW_CDN_SET_PREFERENCE",...t,version:c0},i=new Set,s=[navigator.serviceWorker.controller,e==null?void 0:e.active,e==null?void 0:e.waiting,e==null?void 0:e.installing];for(const r of s)r&&i.add(r);i.forEach(r=>{r.postMessage(n)})}function Tf(e){wf(e);const t=window.__OPENTU_CDN_API__||window.__AITU_CDN_API__;t!=null&&t.selectBestCDN&&t.selectBestCDN().then(n=>{n&&u0(n.cdn)&&(window.__OPENTU_CDN__=n),wf(e)}).catch(n=>{console.warn("[Main] Failed to sync CDN preference to Service Worker:",n)})}function Fr(e,t={}){if(typeof window>"u")return;const{delay:n=0,timeout:i=2e3}=t,s=()=>{const o=window.requestIdleCallback;if(typeof o=="function"){o(e,{timeout:i});return}window.setTimeout(e,Math.min(i,500))},r=()=>{if(n>0){window.setTimeout(s,n);return}s()};window.requestAnimationFrame(()=>{window.requestAnimationFrame(r)})}uE({dsn:"https://a18e755345995baaa0e1972c4cf24497@o4510700882296832.ingest.us.sentry.io/4510700883869696",enabled:sN,sendDefaultPii:!1,tracesSampleRate:.1,beforeSend(e){return e.extra&&(e.extra=zi(e.extra)),e.contexts&&(e.contexts=zi(e.contexts)),e.breadcrumbs&&(e.breadcrumbs=e.breadcrumbs.map(t=>({...t,data:t.data?zi(t.data):void 0,message:t.message?String(zi(t.message)):void 0}))),e.request&&(e.request.headers&&(e.request.headers=zi(e.request.headers)),e.request.data&&(e.request.data=zi(e.request.data)),e.request.url&&(e.request.url=jn(e.request.url))),e}});ta("app_version",c0);ta("deployment_env",oa.deployment_env);ta("release_channel",oa.release_channel);ta("host",oa.host||"unknown");Zi({tip:"正在初始化启动服务...",source:"phase",progress:12});if(typeof window<"u"){WI();const e=()=>{if(window.posthog){Ew(oa),UI();return}setTimeout(e,300)};Fr(e,{delay:0,timeout:1e3}),Fr(()=>{Jm().catch(n=>{console.warn("[Main] Database cleanup failed:",n)}),qI.runMigration().then(()=>Promise.all([vw(),xw.initializeAsync()])).catch(n=>{console.warn("[Main] Storage migration/init failed:",n)})},{delay:400,timeout:2500}),Fr(()=>{Du.start(),Du.logMemoryStatus()},{delay:5e3,timeout:2500});const t=()=>{window.posthog?BI():setTimeout(t,500)};Fr(t,{delay:1500,timeout:3e3})}if("serviceWorker"in navigator){const e=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1";let t=null,n=!1,i=null,s=null;const r=h=>{i!==h&&(i=h,window.dispatchEvent(new CustomEvent("sw-update-available",{detail:{version:h}})))},o=h=>{if(h.pendingVersion&&h.pendingVersion!==h.committedVersion&&(h.upgradeState==="ready"||h.upgradeState==="committing")){r(h.pendingVersion);return}h.pendingVersion||(i=null)},a=h=>{const p=h||t||(s==null?void 0:s.waiting)||navigator.serviceWorker.controller||(s==null?void 0:s.active)||null;p&&p.postMessage({type:"GET_VERSION_STATE"})},c=window.__OPENTU_SW_REGISTRATION_PROMISE__||navigator.serviceWorker.register("/sw.js").catch(h=>(console.warn("[Main] Service worker registration failed:",h),null));window.__OPENTU_SW_REGISTRATION_PROMISE__=c,c.then(h=>{if(!h){Zi({tip:"离线加速未启用,正在直接启动工作台...",source:"phase",progress:70});return}s=h,Zi({tip:"启动缓存服务已连接,正在准备资源清单...",source:"phase",progress:72}),Tf(h),e?(h.update().catch(p=>console.warn("Forced update check failed:",p)),h.waiting&&h.waiting.postMessage({type:"FORCE_UPGRADE"})):h.waiting&&navigator.serviceWorker.controller&&(t=h.waiting,a(h.waiting)),h.addEventListener("updatefound",()=>{const p=h.installing;p&&p.addEventListener("statechange",()=>{p.state==="installed"&&navigator.serviceWorker.controller&&(t=p,e?p.postMessage({type:"FORCE_UPGRADE"}):(a(p),setTimeout(()=>a(p),5e3)))})}),h.active&&!h.installing&&!h.waiting&&Zi({tip:"启动缓存服务已就绪,正在恢复工作台状态...",source:"phase",progress:78}),a(),setInterval(()=>{h.update().catch(p=>{console.warn("Update check failed:",p)})},300*1e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&a()})}).catch(h=>{Zi({tip:"离线加速未启用,正在直接启动工作台...",source:"phase",progress:70})});const u=()=>{if(!St.isInitialized()){setTimeout(u,500);return}St.setEventHandlers({onSWUpdated:h=>{n&&setTimeout(()=>{vi()},1e3)},onSWNewVersionReady:h=>{r(h.version),a()},onSWActivated:h=>{n||(t=null,a())}}),s!=null&&s.waiting&&navigator.serviceWorker.controller&&(t=s.waiting,a(s.waiting))};setTimeout(u,1e3);const d=async()=>{if(!St.isInitialized()){setTimeout(d,500);return}St.registerVideoThumbnailHandler(async(h,p)=>{try{const{generateVideoThumbnailFromBlob:g}=await Ne(async()=>{const{generateVideoThumbnailFromBlob:T}=await import("./tool-windows-hjm6YiPY.js").then(C=>C.oF);return{generateVideoThumbnailFromBlob:T}},__vite__mapDeps([0]),import.meta.url);let m=null;const S=await(await caches.open("drawnix-images")).match(h);if(S&&(m=await S.blob()),!m&&(h.startsWith("http://")||h.startsWith("https://")))try{const T=await fetch(h);T.ok&&(m=await T.blob())}catch{m=null}if(!m)return{error:"Video not found in cache or network"};const w=await g(m,p||400);return{thumbnailUrl:await new Promise((T,C)=>{const E=new FileReader;E.onloadend=()=>T(E.result),E.onerror=C,E.readAsDataURL(w)})}}catch(g){return{error:g instanceof Error?g.message:String(g)}}})};d(),navigator.serviceWorker.addEventListener("message",h=>{var p;((p=h.data)==null?void 0:p.type)==="SW_VERSION_STATE"&&o(h.data)}),navigator.serviceWorker.addEventListener("controllerchange",()=>{Tf(s),a(),n&&setTimeout(()=>{vi()},1e3)}),window.addEventListener("user-confirmed-upgrade",()=>{if(n=!0,t){t.postMessage({type:"COMMIT_UPGRADE"});return}if(s&&s.waiting){s.waiting.postMessage({type:"COMMIT_UPGRADE"});return}if(navigator.serviceWorker.controller){navigator.serviceWorker.controller.postMessage({type:"COMMIT_UPGRADE"});return}vi()})}Zi({tip:"正在挂载工作台界面...",source:"phase",progress:88});const cN=ko.createRoot(document.getElementById("root"));cN.render(l.jsx(f.StrictMode,{children:l.jsx(WD,{children:l.jsx(ZD,{})})}));const gN=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{WC as A,qE as B,e_ as W,mM as a,bt as b,hN as c,fN as d,Fm as e,pN as f,dN as g,gN as h,Nk as i,SP as m,$C as u,X_ as w};
|
|
69
|
+
Component Stack:${u}`]})]}),l.jsxs("div",{style:wt.btnRow,children:[t==="crash"&&s&&l.jsx(Br,{label:"继续加载",onClick:s,bg:"#f5f5f5",bgHover:"#e8e8e8",color:"#666"}),t==="error"&&d&&l.jsx(Br,{label:"导出错误日志",onClick:d,bg:"#f5f5f5",bgHover:"#e8e8e8",color:"#333"}),l.jsx(Br,{label:"安全模式",onClick:h,bg:"#F39C12",bgHover:"#E67E22",color:"#fff"})]}),l.jsx("div",{style:wt.divider}),l.jsx("div",{style:wt.helpSection,children:l.jsxs("div",{style:wt.helpRow,children:[l.jsx("img",{src:"https://nav.ourzhishi.top/api/dynamic-image/qr-code",alt:"企业微信二维码",style:wt.qrcode,referrerPolicy:"no-referrer"}),l.jsxs("div",{style:wt.helpText,children:[l.jsx("p",{style:wt.helpTitle,children:"需要帮助?"}),l.jsx("p",{style:wt.helpDesc,children:"扫码联系客服,或前往调试页面导出完整日志与备份数据"}),l.jsx(Br,{label:"打开调试页面",onClick:p,bg:"#f0eefa",bgHover:"#e2ddf7",color:"#5A4FCF",small:!0})]})]})})]})})},XD=({info:e})=>{const t=e.percent>75?"#E53935":e.percent>50?"#FB8C00":"#43A047";return l.jsxs("div",{style:wt.memoryBox,children:[l.jsx("div",{style:{fontSize:12,color:"#888",marginBottom:8},children:"当前内存使用情况"}),l.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[l.jsxs("span",{style:{fontSize:14,color:"#333"},children:[e.used," / ",e.limit]}),l.jsxs("span",{style:{fontSize:14,fontWeight:500,color:t},children:[e.percent.toFixed(0),"%"]})]}),l.jsx("div",{style:{height:4,backgroundColor:"#e0e0e0",borderRadius:2,marginTop:8,overflow:"hidden"},children:l.jsx("div",{style:{height:"100%",width:`${Math.min(e.percent,100)}%`,backgroundColor:t,transition:"width 0.3s ease"}})})]})},Br=({label:e,onClick:t,bg:n,bgHover:i,color:s,small:r})=>{const[o,a]=Gn.useState(!1),c=r?{...wt.btnSmall,backgroundColor:o?i:n,color:s}:{...wt.btn,backgroundColor:o?i:n,color:s};return l.jsx("button",{onClick:t,onMouseOver:()=>a(!0),onMouseOut:()=>a(!1),style:c,children:e})},wt={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}},KD=500,Fl="board",Kc="aitu_board_close_snapshot_v1";let $a=!1;function YD(){if(!(typeof window>"u"))return window.__OPENTU_BOOT__}function ff(){return new URLSearchParams(window.location.search).get(Fl)}function pf(e,t=!1){const n=new URL(window.location.href);e?n.searchParams.set(Fl,e):n.searchParams.delete(Fl),t?window.history.replaceState({boardId:e},"",n.toString()):window.history.pushState({boardId:e},"",n.toString())}function qD(e){try{localStorage.setItem(Kc,JSON.stringify(e))}catch(t){console.warn("[App] Failed to save board close snapshot:",t)}}function o0(){try{const e=localStorage.getItem(Kc);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 Hr(e){try{const t=o0();if(!t)return;(!e||t.boardId===e)&&localStorage.removeItem(Kc)}catch(t){console.warn("[App] Failed to clear board close snapshot:",t)}}function ZD(){const[e,t]=f.useState(!0),[n,i]=f.useState(!1),s=f.useRef(!1),[r,o]=f.useState(!1),[a,c]=f.useState(null),[u,d]=f.useState({children:[]}),[h,p]=f.useState(null),g=f.useRef(null),m=f.useRef(),b=f.useRef(null),S=f.useRef(null),w=f.useRef(!1),y=f.useRef(null),T=f.useRef(!1),C=f.useRef(!1),E=f.useRef(!1);NI(h),f.useEffect(()=>{g.current=h},[h]);const v=f.useCallback((D,k,N=Date.now())=>{m.current=k.viewport,b.current={boardId:D,children:k.children,viewport:k.viewport,theme:k.theme,updatedAt:N}},[]),x=f.useCallback(D=>{const k=b.current,N=g.current;if(!k||!N||k.boardId!==N||!E.current)return;qD({...k,updatedAt:Date.now()}),bn.getInstance().saveCurrentBoard({children:k.children,viewport:k.viewport,theme:k.theme}).catch(Z=>{console.warn(`[App] Failed to flush board on ${D}:`,Z)})},[]);f.useEffect(()=>{const D=YD();D&&(r||a||!e)&&D.markReady()},[a,e,r]),f.useEffect(()=>{(async()=>{if(Kt.shouldShowSafeModePrompt()&&!Kt.isSafeMode()){o(!0),t(!1);return}if($a){const k=bn.getInstance();t(!1),await k.waitForInitialization();const N=k.getState().currentBoardId;if(N&&k.getBoardMetadata(N)){const M=await k.switchBoard(N),Z={children:M.elements||[],viewport:M.viewport,theme:M.theme};v(M.id,Z,M.updatedAt),E.current=!1,d(Z)}t(!1),Kt.markLoadingComplete();return}$a=!0;try{const k=bn.getInstance();if(t(!1),await k.initialize(),await Zm()||await jI(),Kt.isSafeMode()){console.log("[App] Safe mode: looking for existing safe mode board");const ce=k.getAllBoards().find(le=>le.name.startsWith("安全模式")&&(!le.elements||le.elements.length===0));if(ce)console.log("[App] Safe mode: reusing existing board:",ce.name),await k.switchBoard(ce.id),p(ce.id);else{console.log("[App] Safe mode: creating new blank board");const le=new Date().toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).replace(/\//g,"-"),me=await k.createBoard({name:`安全模式 ${le}`,elements:[]});me&&(await k.switchBoard(me.id),p(me.id))}const K={children:[]},ae=(ce==null?void 0:ce.id)||g.current||"safe-mode";v(ae,K,Date.now()),d(K),s.current=!0,i(!0),t(!1),Kt.markLoadingComplete(),Kt.disableSafeMode(),setTimeout(()=>{oe.warning({content:"当前处于安全模式,已创建空白画布。可从侧边栏切换到其他画布。",duration:8e3,closeBtn:!0})},500);return}let M=null;const Z=ff(),he=k.getState().currentBoardId;let R=null;if(Z&&k.getBoardMetadata(Z)?R=Z:he&&k.getBoardMetadata(he)&&(R=he),R)M=await k.switchBoard(R);else if(k.hasBoards()){const W=k.getTree(),ce=a0(W);ce&&(M=await k.switchBoard(ce.id))}else{const W=await k.createBoard({name:"我的画板1",elements:[]});W&&(M=await k.switchBoard(W.id))}if(M&&(pf(M.id,!0),p(M.id),k.persistCurrentBoardId(M.id),E.current=!1),M){const W=o0();let ce={children:M.elements||[],viewport:M.viewport,theme:M.theme};if(W&&W.boardId===M.id&&W.updatedAt>M.updatedAt){ce={children:W.children,viewport:W.viewport,theme:W.theme},M={...M,...ce,updatedAt:W.updatedAt};const K=M.id;k.saveBoard(K,ce).then(()=>{E.current=!1,Hr(K)}).catch(ae=>{console.warn("[App] Failed to rehydrate board from close snapshot:",ae)}),oe.warning({content:"检测到上次关闭前的未落盘画布,已自动恢复",duration:5e3,closeBtn:!0})}else W&&W.boardId&&!k.getBoardMetadata(W.boardId)&&Hr(W.boardId);v(M.id,ce,M.updatedAt),E.current=!1,d(ce),Xa(ce.children).then(K=>{if(K!==ce.children){const ae={...ce,children:K};v(M.id,ae,Date.now()),d(ae)}}).catch(K=>{console.error("[App] Video URL recovery failed:",K)})}}catch(k){console.error("[App] Initialization failed:",k),c(k instanceof Error?k:new Error(String(k)))}finally{s.current=!0,i(!0),t(!1),Kt.markLoadingComplete()}})()},[v]);const O=f.useCallback(async(D,k=!1)=>{try{k||(pf(D.id),bn.getInstance().persistCurrentBoardId(D.id)),p(D.id),C.current=!1,E.current=!1;const M={children:await Xa(D.elements||[]),viewport:D.viewport,theme:D.theme};v(D.id,M,D.updatedAt),d(M),setTimeout(()=>{y.current&&(qs(y.current),xf(y.current),no(y.current))},0)}catch(N){console.error("[App] Board switch failed:",N),oe.error({content:`切换画板失败: ${N instanceof Error?N.message:"未知错误"}`,duration:5e3,closeBtn:!0})}},[v]);f.useEffect(()=>{const D=async()=>{if(!w.current){w.current=!0;try{const k=ff();if(k&&k!==h){const N=bn.getInstance(),M=await N.switchBoard(k);M&&(await O(M,!0),N.persistCurrentBoardId(M.id))}}catch(k){console.error("[App] Failed to handle browser navigation:",k)}finally{w.current=!1}}};return window.addEventListener("popstate",D),()=>{window.removeEventListener("popstate",D)}},[h,O]);const B=f.useCallback(async()=>{T.current=!0;try{const D=bn.getInstance();let k=D.getCurrentBoard();if(!k){const M=D.getState().currentBoardId;if(!M){console.warn("[App] handleTabSyncNeeded: no current board ID");return}if(!D.getBoardMetadata(M)){console.warn("[App] handleTabSyncNeeded: board not found",M);return}try{k=await D.switchBoard(M)}catch(Z){console.error("[App] handleTabSyncNeeded: failed to load board",Z);return}}const N=await D.reloadBoard(k.id);if(N){const Z={children:await Xa(N.elements||[]),viewport:N.viewport,theme:N.theme};v(N.id,Z,N.updatedAt),E.current=!1,d(Z)}}catch(D){console.error("[App] Failed to sync board data:",D),vi()}finally{setTimeout(()=>{T.current=!1},100)}},[v]),X=f.useCallback(D=>{if(d(D),m.current=D.viewport,!s.current||T.current)return;C.current=!0,E.current=!0;const k=bn.getInstance(),N=k.getCurrentBoard();if(!N){console.warn("[App] handleBoardChange: board not fully loaded, skipping save");return}v(N.id,D),k.saveCurrentBoard(D).then(()=>{E.current=!1,Hr(N.id),Km(N.id)}).catch(M=>{console.error("[App] Failed to save board:",M)})},[v]),j=f.useCallback(D=>{m.current=D;const k=b.current;k&&(b.current={...k,viewport:D,updatedAt:Date.now()}),!T.current&&(E.current=!0,S.current&&clearTimeout(S.current),S.current=setTimeout(()=>{if(T.current)return;const N=bn.getInstance(),M=N.getCurrentBoard();M&&N.saveCurrentBoard({children:M.elements,viewport:D,theme:M.theme}).then(()=>{E.current=!1,Hr(M.id)}).catch(Z=>{console.error("[App] Failed to save viewport:",Z)})},KD))},[v]);f.useEffect(()=>{const D=Z=>{if(S.current&&(clearTimeout(S.current),S.current=null),T.current)return;const R=bn.getInstance().getCurrentBoard(),W=b.current,ce=m.current,K=g.current;R&&K&&(!W||W.boardId!==K)&&v(R.id,{children:R.elements,viewport:ce??R.viewport,theme:R.theme},Date.now()),!(Z==="visibilitychange"&&!C.current)&&x(Z)},k=()=>{D("beforeunload")},N=()=>{document.visibilityState==="hidden"&&D("visibilitychange")},M=()=>{D("pagehide")};return window.addEventListener("beforeunload",k),window.addEventListener("pagehide",M),document.addEventListener("visibilitychange",N),()=>{window.removeEventListener("beforeunload",k),window.removeEventListener("pagehide",M),document.removeEventListener("visibilitychange",N),S.current&&clearTimeout(S.current)}},[x,v]);const L=f.useCallback(D=>{o(!1),D?Kt.enableSafeMode():Kt.clearCrashState(),t(!0),$a=!1,setTimeout(()=>{vi()},100)},[]);return r?l.jsx(Co,{variant:"crash",crashCount:Kt.getCrashCount(),memoryInfo:Kt.getMemoryInfo(),onIgnore:()=>L(!1),onSafeModeReload:()=>L(!0),onGoToDebug:_o}):a?l.jsx(Co,{variant:"error",title:"应用初始化失败",description:"无法加载画板数据,可能是存储损坏或浏览器限制。",errorMessage:a.message,errorStack:a.stack,onExportLog:()=>Bl(a),onSafeModeReload:Hl,onGoToDebug:_o}):e?l.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100vh"},children:"加载中..."}):l.jsx("div",{style:{height:"100vh"},children:l.jsx(kI,{value:u.children,viewport:u.viewport,theme:u.theme,onChange:X,onViewportChange:j,onBoardSwitch:O,onTabSyncNeeded:B,isDataReady:n,currentBoardId:h,afterInit:D=>{y.current=D,window.__drawnix__web__console=k=>{QD(D,k)}}})})}const QD=(e,t)=>{const n=z.getBoardContainer(e).closest(".drawnix");let i=n.querySelector(".drawnix-console");i||(i=document.createElement("div"),i.classList.add("drawnix-console"),n.append(i));const s=document.createElement("div");s.innerHTML=t,i.append(s)};async function Xa(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 i=n.indexOf("#merged-video-");if(i!==-1){const s=n.substring(i+1),r=s.indexOf("#",1),a=`/__aitu_cache__/video/${r>0?s.substring(0,r):s}.mp4`;return{...t,url:a}}}return t})}function a0(e){for(const t of e){if(t.type==="board")return t.data;if(t.type==="folder"&&t.children){const n=a0(t.children);if(n)return n}}return null}const gf=window.addEventListener.bind(window),JD=window.removeEventListener.bind(window);let Yc=null;window.addEventListener=function(e,t,n){if(e==="unload"){console.warn("[Permissions Policy] Blocked unload event listener");return}return e==="beforeunload"&&(Yc=t),gf.call(window,e,t,n)};window.removeEventListener=function(e,t,n){return e==="beforeunload"&&(Yc=null),JD.call(window,e,t,n)};window.__checkBeforeUnload=()=>!!Yc;let mf=!1;const l0="sw-debug-enabled";function eN(){try{return sessionStorage.getItem(l0)==="true"}catch{return!1}}function Sf(e){try{sessionStorage.setItem(l0,e===!0?"true":"false")}catch{}}let Rs=eN();const Ys=[];let rs=null,Zn=0;const Po=15e3,js={error:console.error,warn:console.warn,info:console.info,log:console.log,debug:console.debug};function fi(e,t,n){if(t.includes("[SW]")||t.includes("[SWTaskQueue]")||t.includes("[SWChannelManager]")||t.includes("Invalid message structure")||t.includes("posthog.com")||t.includes("sentry.io")||n&&(n.includes("posthog")||n.includes("sentry")))return;const i=()=>{St.isInitialized()&&St.reportConsoleLog(e,[{message:t,stack:n||"",source:window.location.href}],Date.now()).catch(()=>{})},s=()=>{for(;Ys.length>0&&St.isInitialized();){const o=Ys.shift();St.reportConsoleLog(o.level,[{message:o.message,stack:o.stack||"",source:window.location.href}],Date.now()).catch(()=>{})}},r=()=>{const o=Date.now();rs||o<Zn||(rs=St.initialize().then(a=>{if(!a){Zn=Date.now()+Po;return}Zn=0,s()}).catch(()=>{Zn=Date.now()+Po}).finally(()=>{rs=null}))};St.isInitialized()?i():(Ys.push({level:e,message:t,stack:n}),r())}function Ls(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 bf(e){for(const t of e)if(t instanceof Error&&t.stack)return t.stack;return""}function tN(){if(mf||!("serviceWorker"in navigator))return;mf=!0;const e=()=>{if(St.isInitialized())St.subscribeToEvent("debug:statusChanged",t=>{const n=t,i=n.enabled??n.debugModeEnabled??!1;Rs=i,Sf(i)}),St.getDebugStatus().then(t=>{const n=t.enabled??t.debugModeEnabled??!1;Rs=n,Sf(n)});else{const t=Date.now();!rs&&t>=Zn&&(rs=St.initialize().then(n=>{if(!n){Zn=Date.now()+Po;return}for(Zn=0;Ys.length>0&&St.isInitialized();){const i=Ys.shift();St.reportConsoleLog(i.level,[{message:i.message,stack:i.stack||"",source:window.location.href}],Date.now()).catch(()=>{})}}).catch(()=>{Zn=Date.now()+Po}).finally(()=>{rs=null})),setTimeout(e,500)}};e(),console.error=function(...t){js.error.apply(console,t),fi("error",Ls(t),bf(t))},console.warn=function(...t){js.warn.apply(console,t),fi("warn",Ls(t),bf(t))},console.log=function(...t){js.log.apply(console,t),Rs&&fi("log",Ls(t),"")},console.info=function(...t){js.info.apply(console,t),Rs&&fi("info",Ls(t),"")},console.debug=function(...t){js.debug.apply(console,t),Rs&&fi("debug",Ls(t),"")},window.addEventListener("error",t=>{var i;const n=`${t.message} at ${t.filename}:${t.lineno}:${t.colno}`;fi("error",n,((i=t.error)==null?void 0:i.stack)||"")}),window.addEventListener("unhandledrejection",t=>{const n=t.reason,i=n instanceof Error?n.message:`Unhandled Promise: ${String(n)}`,s=n instanceof Error&&n.stack||"";fi("error",i,s)})}"serviceWorker"in navigator&&tN();Kt.markLoadingStart();Kt.checkUrlSafeMode();jD();const nN=typeof window<"u"&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),iN=typeof window<"u"&&new URLSearchParams(window.location.search).get("report")==="1",sN=iN||!nN&&!0,c0="0.6.64",oa=Tw(),yf="_lazy_chunk_retry",rN="_t";function oN(){if(typeof window>"u")return;const e=new URL(window.location.href);if(e.searchParams.has(yf)){e.searchParams.delete(yf),e.searchParams.delete(rN);try{window.history.replaceState(window.history.state,"",e.toString())}catch{}}}oN();function u0(e){return e==="jsdelivr"||e==="unpkg"||e==="local"}function aN(){return window.__OPENTU_BOOT__||null}function Zi(e){var t,n;(n=(t=aN())==null?void 0:t.setProgress)==null||n.call(t,e==null?void 0:e.progress,e)}function lN(){const e=window.__OPENTU_CDN__||window.__AITU_CDN__;return!e||!u0(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 wf(e){const t=lN();if(!t)return;const n={type:"SW_CDN_SET_PREFERENCE",...t,version:c0},i=new Set,s=[navigator.serviceWorker.controller,e==null?void 0:e.active,e==null?void 0:e.waiting,e==null?void 0:e.installing];for(const r of s)r&&i.add(r);i.forEach(r=>{r.postMessage(n)})}function Tf(e){wf(e);const t=window.__OPENTU_CDN_API__||window.__AITU_CDN_API__;t!=null&&t.selectBestCDN&&t.selectBestCDN().then(n=>{n&&u0(n.cdn)&&(window.__OPENTU_CDN__=n),wf(e)}).catch(n=>{console.warn("[Main] Failed to sync CDN preference to Service Worker:",n)})}function Fr(e,t={}){if(typeof window>"u")return;const{delay:n=0,timeout:i=2e3}=t,s=()=>{const o=window.requestIdleCallback;if(typeof o=="function"){o(e,{timeout:i});return}window.setTimeout(e,Math.min(i,500))},r=()=>{if(n>0){window.setTimeout(s,n);return}s()};window.requestAnimationFrame(()=>{window.requestAnimationFrame(r)})}uE({dsn:"https://a18e755345995baaa0e1972c4cf24497@o4510700882296832.ingest.us.sentry.io/4510700883869696",enabled:sN,sendDefaultPii:!1,tracesSampleRate:.1,beforeSend(e){return e.extra&&(e.extra=zi(e.extra)),e.contexts&&(e.contexts=zi(e.contexts)),e.breadcrumbs&&(e.breadcrumbs=e.breadcrumbs.map(t=>({...t,data:t.data?zi(t.data):void 0,message:t.message?String(zi(t.message)):void 0}))),e.request&&(e.request.headers&&(e.request.headers=zi(e.request.headers)),e.request.data&&(e.request.data=zi(e.request.data)),e.request.url&&(e.request.url=jn(e.request.url))),e}});ta("app_version",c0);ta("deployment_env",oa.deployment_env);ta("release_channel",oa.release_channel);ta("host",oa.host||"unknown");Zi({tip:"正在初始化启动服务...",source:"phase",progress:12});if(typeof window<"u"){WI();const e=()=>{if(window.posthog){Ew(oa),UI();return}setTimeout(e,300)};Fr(e,{delay:0,timeout:1e3}),Fr(()=>{Jm().catch(n=>{console.warn("[Main] Database cleanup failed:",n)}),qI.runMigration().then(()=>Promise.all([vw(),xw.initializeAsync()])).catch(n=>{console.warn("[Main] Storage migration/init failed:",n)})},{delay:400,timeout:2500}),Fr(()=>{Du.start(),Du.logMemoryStatus()},{delay:5e3,timeout:2500});const t=()=>{window.posthog?BI():setTimeout(t,500)};Fr(t,{delay:1500,timeout:3e3})}if("serviceWorker"in navigator){const e=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1";let t=null,n=!1,i=null,s=null;const r=h=>{i!==h&&(i=h,window.dispatchEvent(new CustomEvent("sw-update-available",{detail:{version:h}})))},o=h=>{if(h.pendingVersion&&h.pendingVersion!==h.committedVersion&&(h.upgradeState==="ready"||h.upgradeState==="committing")){r(h.pendingVersion);return}h.pendingVersion||(i=null)},a=h=>{const p=h||t||(s==null?void 0:s.waiting)||navigator.serviceWorker.controller||(s==null?void 0:s.active)||null;p&&p.postMessage({type:"GET_VERSION_STATE"})},c=window.__OPENTU_SW_REGISTRATION_PROMISE__||navigator.serviceWorker.register("/sw.js").catch(h=>(console.warn("[Main] Service worker registration failed:",h),null));window.__OPENTU_SW_REGISTRATION_PROMISE__=c,c.then(h=>{if(!h){Zi({tip:"离线加速未启用,正在直接启动工作台...",source:"phase",progress:70});return}s=h,Zi({tip:"启动缓存服务已连接,正在准备资源清单...",source:"phase",progress:72}),Tf(h),e?(h.update().catch(p=>console.warn("Forced update check failed:",p)),h.waiting&&h.waiting.postMessage({type:"FORCE_UPGRADE"})):h.waiting&&navigator.serviceWorker.controller&&(t=h.waiting,a(h.waiting)),h.addEventListener("updatefound",()=>{const p=h.installing;p&&p.addEventListener("statechange",()=>{p.state==="installed"&&navigator.serviceWorker.controller&&(t=p,e?p.postMessage({type:"FORCE_UPGRADE"}):(a(p),setTimeout(()=>a(p),5e3)))})}),h.active&&!h.installing&&!h.waiting&&Zi({tip:"启动缓存服务已就绪,正在恢复工作台状态...",source:"phase",progress:78}),a(),setInterval(()=>{h.update().catch(p=>{console.warn("Update check failed:",p)})},300*1e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&a()})}).catch(h=>{Zi({tip:"离线加速未启用,正在直接启动工作台...",source:"phase",progress:70})});const u=()=>{if(!St.isInitialized()){setTimeout(u,500);return}St.setEventHandlers({onSWUpdated:h=>{n&&setTimeout(()=>{vi()},1e3)},onSWNewVersionReady:h=>{r(h.version),a()},onSWActivated:h=>{n||(t=null,a())}}),s!=null&&s.waiting&&navigator.serviceWorker.controller&&(t=s.waiting,a(s.waiting))};setTimeout(u,1e3);const d=async()=>{if(!St.isInitialized()){setTimeout(d,500);return}St.registerVideoThumbnailHandler(async(h,p)=>{try{const{generateVideoThumbnailFromBlob:g}=await Ne(async()=>{const{generateVideoThumbnailFromBlob:T}=await import("./tool-windows-C4D0lII2.js").then(C=>C.oF);return{generateVideoThumbnailFromBlob:T}},__vite__mapDeps([0]),import.meta.url);let m=null;const S=await(await caches.open("drawnix-images")).match(h);if(S&&(m=await S.blob()),!m&&(h.startsWith("http://")||h.startsWith("https://")))try{const T=await fetch(h);T.ok&&(m=await T.blob())}catch{m=null}if(!m)return{error:"Video not found in cache or network"};const w=await g(m,p||400);return{thumbnailUrl:await new Promise((T,C)=>{const E=new FileReader;E.onloadend=()=>T(E.result),E.onerror=C,E.readAsDataURL(w)})}}catch(g){return{error:g instanceof Error?g.message:String(g)}}})};d(),navigator.serviceWorker.addEventListener("message",h=>{var p;((p=h.data)==null?void 0:p.type)==="SW_VERSION_STATE"&&o(h.data)}),navigator.serviceWorker.addEventListener("controllerchange",()=>{Tf(s),a(),n&&setTimeout(()=>{vi()},1e3)}),window.addEventListener("user-confirmed-upgrade",()=>{if(n=!0,t){t.postMessage({type:"COMMIT_UPGRADE"});return}if(s&&s.waiting){s.waiting.postMessage({type:"COMMIT_UPGRADE"});return}if(navigator.serviceWorker.controller){navigator.serviceWorker.controller.postMessage({type:"COMMIT_UPGRADE"});return}vi()})}Zi({tip:"正在挂载工作台界面...",source:"phase",progress:88});const cN=ko.createRoot(document.getElementById("root"));cN.render(l.jsx(f.StrictMode,{children:l.jsx(WD,{children:l.jsx(ZD,{})})}));const gN=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{WC as A,qE as B,e_ as W,mM as a,bt as b,hN as c,fN as d,Fm as e,pN as f,dN as g,gN as h,Nk as i,SP as m,$C as u,X_ as w};
|