aitu-app 0.5.21 → 0.5.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +3 -3
  2. package/assets/{ChatMessagesArea-CAnmzKeA.js → ChatMessagesArea-DtzEt9y0.js} +3 -3
  3. package/assets/{Serializer-DPCLjt6U.js → Serializer-rTHzSF0Y.js} +1 -1
  4. package/assets/{ToolboxDrawer-D-ZDs49h.js → ToolboxDrawer-D0dL1xDI.js} +1 -1
  5. package/assets/{_baseUniq-CHS3E5If.js → _baseUniq-CJcN2wXt.js} +1 -1
  6. package/assets/{advancedFormat-Chr195ZY.js → advancedFormat-D3noAem-.js} +1 -1
  7. package/assets/{ai-analyze-D3V-tpIV.js → ai-analyze-DSNdzApa.js} +1 -1
  8. package/assets/{arc-lNLKXIKC.js → arc-DCMdqNJq.js} +1 -1
  9. package/assets/{architectureDiagram-VXUJARFQ-CCzBT9XK.js → architectureDiagram-VXUJARFQ-CNLyKX9W.js} +1 -1
  10. package/assets/{batch-image-generation-CgR-a8Ii.js → batch-image-generation-BEr8WnyA.js} +1 -1
  11. package/assets/{blockDiagram-38ab4fdb-CbcE_DRD.js → blockDiagram-38ab4fdb-BfuatLv6.js} +1 -1
  12. package/assets/{blockDiagram-VD42YOAC-CgcfCyW1.js → blockDiagram-VD42YOAC-Lc7hzFMW.js} +1 -1
  13. package/assets/{c4Diagram-3d4e48cf-DqzYo_xg.js → c4Diagram-3d4e48cf-CLYmRF8m.js} +1 -1
  14. package/assets/{c4Diagram-YG6GDRKO-BTZAWhX1.js → c4Diagram-YG6GDRKO-DFgYCXSR.js} +1 -1
  15. package/assets/channel-x6LKWmtX.js +1 -0
  16. package/assets/{chunk-4BX2VUAB-DH-I_3Sl.js → chunk-4BX2VUAB-ZP_vY4vZ.js} +1 -1
  17. package/assets/{chunk-55IACEB6-BJKBSn0v.js → chunk-55IACEB6-B5HoA7RC.js} +1 -1
  18. package/assets/{chunk-B4BG7PRW-BIhB4ChZ.js → chunk-B4BG7PRW-DYumBzJl.js} +1 -1
  19. package/assets/{chunk-DI55MBZ5-NlFLhYIc.js → chunk-DI55MBZ5-8cmxakR4.js} +1 -1
  20. package/assets/{chunk-FMBD7UC4-QVfOPBEJ.js → chunk-FMBD7UC4-CAoW1kf1.js} +1 -1
  21. package/assets/{chunk-QN33PNHL-C_DotWZ6.js → chunk-QN33PNHL-DT5Dd0sR.js} +1 -1
  22. package/assets/{chunk-QZHKN3VN-Ei6ogyMg.js → chunk-QZHKN3VN-CZH2zyPP.js} +1 -1
  23. package/assets/{chunk-TZMSLE5B-CKPTgIMs.js → chunk-TZMSLE5B-BX3lW2Ds.js} +1 -1
  24. package/assets/classDiagram-2ON5EDUG-xDDBDhvH.js +1 -0
  25. package/assets/{classDiagram-70f12bd4-DeAD0Lw4.js → classDiagram-70f12bd4-H_Ao4SWS.js} +1 -1
  26. package/assets/classDiagram-v2-WZHVMYZB-xDDBDhvH.js +1 -0
  27. package/assets/{classDiagram-v2-f2320105-DR43MMrr.js → classDiagram-v2-f2320105-wpOcN7Cp.js} +1 -1
  28. package/assets/clone-BliL8GTL.js +1 -0
  29. package/assets/{cose-bilkent-S5V4N54A-CE31mcuy.js → cose-bilkent-S5V4N54A-BpodmnGt.js} +1 -1
  30. package/assets/{createText-2e5e7dd3-DuyGuD-n.js → createText-2e5e7dd3-DevXK6aG.js} +1 -1
  31. package/assets/{cytoscape-cose-bilkent-DTqUuT3l.js → cytoscape-cose-bilkent-CfL2kyJn.js} +1 -1
  32. package/assets/{dagre-6UL2VRFP-CuJmVGl3.js → dagre-6UL2VRFP-DxcT4smm.js} +1 -1
  33. package/assets/{diagram-PSM6KHXK-D5Y5dlL9.js → diagram-PSM6KHXK-15LgvIqL.js} +1 -1
  34. package/assets/{diagram-QEK2KX5R-DOWAGxHq.js → diagram-QEK2KX5R-Cq44VPiw.js} +1 -1
  35. package/assets/{diagram-S2PKOQOG-ykMhl6fc.js → diagram-S2PKOQOG-DjR4N2-I.js} +1 -1
  36. package/assets/{edges-e0da2a9e-BpsZLv9t.js → edges-e0da2a9e-4-cJcCOg.js} +1 -1
  37. package/assets/{erDiagram-9861fffd-rZLPDBgy.js → erDiagram-9861fffd-CAhGmEfN.js} +1 -1
  38. package/assets/{erDiagram-Q2GNP2WA-zRo1erex.js → erDiagram-Q2GNP2WA-Bv6twqgU.js} +1 -1
  39. package/assets/{flowDb-956e92f1-f4MK2XS7.js → flowDb-956e92f1-7HzSxpZE.js} +1 -1
  40. package/assets/{flowDiagram-66a62f08-_6Eo5sZi.js → flowDiagram-66a62f08-Di0dNdDw.js} +1 -1
  41. package/assets/{flowDiagram-NV44I4VS-CFCClCRc.js → flowDiagram-NV44I4VS-jjJtsD7c.js} +1 -1
  42. package/assets/flowDiagram-v2-96b9c2cf-C7Z70T_R.js +1 -0
  43. package/assets/{flowchart-elk-definition-4a651766-t4QJuK_b.js → flowchart-elk-definition-4a651766-K2hM47DX.js} +1 -1
  44. package/assets/{ganttDiagram-JELNMOA3-DIX2ad-2.js → ganttDiagram-JELNMOA3-DcSqTXib.js} +1 -1
  45. package/assets/{ganttDiagram-c361ad54-dX5QjWrh.js → ganttDiagram-c361ad54-CH7Glt3P.js} +1 -1
  46. package/assets/{gitGraphDiagram-72cf32ee-BBZSqS6J.js → gitGraphDiagram-72cf32ee-BnEB0GU4.js} +1 -1
  47. package/assets/{gitGraphDiagram-NY62KEGX-C-FRyLSQ.js → gitGraphDiagram-NY62KEGX-O0TpP5xG.js} +1 -1
  48. package/assets/{graph-BpCqwwyJ.js → graph-BZ_Ixkdn.js} +1 -1
  49. package/assets/{graph-dwf5l9kJ.js → graph-DHfOf9vz.js} +1 -1
  50. package/assets/{grid-image-DRAUp_wj.js → grid-image-jIEBt3FV.js} +1 -1
  51. package/assets/{has-BBSmRLAB.js → has-C78hNt79.js} +1 -1
  52. package/assets/{hasIn-CGUnHN5L.js → hasIn-DNHU2Dgx.js} +1 -1
  53. package/assets/{index-3862675e-BmuXVGGA.js → index-3862675e-CQkaubhC.js} +1 -1
  54. package/assets/{index-DNIlXgAo.js → index-BNXtnhmh.js} +1 -1
  55. package/assets/{index-Ds1UcDjn.js → index-C6f1jS5T.js} +8 -8
  56. package/assets/{index-CISxTBJ3.js → index-CiiU0LMF.js} +1 -1
  57. package/assets/{index-DEjUAZUe.js → index-D1NStEds.js} +1 -1
  58. package/assets/{index-DvbaH1wH.js → index-DGb8pRqW.js} +1 -1
  59. package/assets/{index-DCs3C-gs.js → index-JhVJEcm-.js} +1 -1
  60. package/assets/{index-_FyCDKGq.js → index-QG8-KVAs.js} +4 -4
  61. package/assets/{index-eOV7y-oZ.js → index-sRDAAYLb.js} +1 -1
  62. package/assets/{infoDiagram-WHAUD3N6-Cw6LtQsv.js → infoDiagram-WHAUD3N6-CZKQnKde.js} +1 -1
  63. package/assets/{infoDiagram-f8f76790-suYKggbB.js → infoDiagram-f8f76790-Cq8UHTek.js} +1 -1
  64. package/assets/{inspiration-board-8CO8xK39.js → inspiration-board-CXBpTN2S.js} +1 -1
  65. package/assets/{isEmpty-BZ44SF3F.js → isEmpty-Bg6e-LN7.js} +1 -1
  66. package/assets/{journeyDiagram-49397b02-DLzRdow3.js → journeyDiagram-49397b02-u4P4ZPSo.js} +1 -1
  67. package/assets/{journeyDiagram-XKPGCS4Q-CcD6LNVi.js → journeyDiagram-XKPGCS4Q-DppWgwdD.js} +1 -1
  68. package/assets/{kanban-definition-3W4ZIXB7-DWA3YqY9.js → kanban-definition-3W4ZIXB7-Cu9Oq__U.js} +1 -1
  69. package/assets/{layout-D8KZ21ze.js → layout-Oya54E8b.js} +1 -1
  70. package/assets/{layout-jxFX0Ar3.js → layout-PukuJPWh.js} +1 -1
  71. package/assets/{line-B3fXWiyE.js → line-CCnY_Zjv.js} +1 -1
  72. package/assets/{linear-DsVcoO9v.js → linear-FgTbCOcj.js} +1 -1
  73. package/assets/{mermaid.core-ruaJ9d8x.js → mermaid.core-Bb0rcjVt.js} +4 -4
  74. package/assets/{min-B6fh4WRE.js → min-BYNXcs16.js} +1 -1
  75. package/assets/{mindmap-definition-VGOIOE7T-BzeNa7DW.js → mindmap-definition-VGOIOE7T-euTygwOP.js} +1 -1
  76. package/assets/{mindmap-definition-fc14e90a-C3sElkm0.js → mindmap-definition-fc14e90a-DMA7ROII.js} +1 -1
  77. package/assets/{photo-wall-splitter-C1GbxYBl.js → photo-wall-splitter-CAWxP47k.js} +1 -1
  78. package/assets/{pick-DUB8w7iE.js → pick-D_sga9lq.js} +1 -1
  79. package/assets/{pie-DAYMJpRO.js → pie-BWVaG8mI.js} +1 -1
  80. package/assets/{pieDiagram-8a3498a8-CZI3pF7g.js → pieDiagram-8a3498a8-JQ1MpLiZ.js} +1 -1
  81. package/assets/{pieDiagram-ADFJNKIX-BqonG77Q.js → pieDiagram-ADFJNKIX-BOGQkDt6.js} +1 -1
  82. package/assets/{quadrantDiagram-120e2f19-Q2bVMK-T.js → quadrantDiagram-120e2f19-kJzxW0Br.js} +1 -1
  83. package/assets/{quadrantDiagram-AYHSOK5B-yJZRIs-Q.js → quadrantDiagram-AYHSOK5B-UxkYiRF3.js} +1 -1
  84. package/assets/{requirementDiagram-UZGBJVZJ-3kaAkLjO.js → requirementDiagram-UZGBJVZJ-Bk95peTm.js} +1 -1
  85. package/assets/{requirementDiagram-deff3bca-DHOhXBYo.js → requirementDiagram-deff3bca-DwSHfS3q.js} +1 -1
  86. package/assets/{sankeyDiagram-04a897e0-3UqYNZg9.js → sankeyDiagram-04a897e0-Dee_8vG5.js} +1 -1
  87. package/assets/{sankeyDiagram-TZEHDZUN-Ce844Tbc.js → sankeyDiagram-TZEHDZUN-Dn-BrNQI.js} +1 -1
  88. package/assets/{sequenceDiagram-704730f1-CBXqjnXl.js → sequenceDiagram-704730f1-CK2_u2M2.js} +1 -1
  89. package/assets/{sequenceDiagram-WL72ISMW-DBN2cRGt.js → sequenceDiagram-WL72ISMW-PtdIXaXk.js} +1 -1
  90. package/assets/{settings-dialog-aU8BHcuS.js → settings-dialog-C4eZxway.js} +1 -1
  91. package/assets/{stateDiagram-587899a1-BGKPA37n.js → stateDiagram-587899a1-vSvTWjnf.js} +1 -1
  92. package/assets/{stateDiagram-FKZM4ZOC-Czg5Opf0.js → stateDiagram-FKZM4ZOC-DGbpdRXP.js} +1 -1
  93. package/assets/stateDiagram-v2-4FDKWEC3-C-2flGWR.js +1 -0
  94. package/assets/{stateDiagram-v2-d93cdb3a-DWU3UljE.js → stateDiagram-v2-d93cdb3a-BrPmXu5B.js} +1 -1
  95. package/assets/{styles-6aaf32cf-BVLDN8CD.js → styles-6aaf32cf-Cf3g-0g3.js} +1 -1
  96. package/assets/{styles-9a916d00-vSy8MhZp.js → styles-9a916d00--ZEFIk8R.js} +1 -1
  97. package/assets/{styles-c10674c1-dzTvI8BU.js → styles-c10674c1-DHwZqsJA.js} +1 -1
  98. package/assets/{svgDrawCommon-08f97a94-dptVwf62.js → svgDrawCommon-08f97a94-n9d3mPea.js} +1 -1
  99. package/assets/{timeline-definition-85554ec2-jKiT0ZaE.js → timeline-definition-85554ec2-H_sXtfLT.js} +1 -1
  100. package/assets/{timeline-definition-IT6M3QCI-B2NoE4jH.js → timeline-definition-IT6M3QCI-C-H3Ftyt.js} +1 -1
  101. package/assets/{treemap-KMMF4GRG-1nrNbz-r.js → treemap-KMMF4GRG-Cu1-wgRV.js} +1 -1
  102. package/assets/{ttd-dialog-WN-s4x87.js → ttd-dialog-TQYw_Nae.js} +5 -5
  103. package/assets/{union-B2D_ldts.js → union-DP4CDhaw.js} +1 -1
  104. package/assets/{upload-Crej215t.js → upload-DdSOuK5h.js} +1 -1
  105. package/assets/{video-recovery-service-Zb_336FQ.js → video-recovery-service-CZXUWRm1.js} +1 -1
  106. package/assets/{xychartDiagram-PRI3JC2R-UPkX0dfi.js → xychartDiagram-PRI3JC2R-CpjoxcIY.js} +1 -1
  107. package/assets/{xychartDiagram-e933f94c-BXYMaBZh.js → xychartDiagram-e933f94c-CTuQj9cZ.js} +1 -1
  108. package/assets/{zipObject-bwVIVuzi.js → zipObject-BF7eTaCR.js} +1 -1
  109. package/package.json +1 -1
  110. package/sw.js +7 -7
  111. package/version.json +2 -2
  112. package/assets/channel-Bew-Iahk.js +0 -1
  113. package/assets/classDiagram-2ON5EDUG-DIttp4Yk.js +0 -1
  114. package/assets/classDiagram-v2-WZHVMYZB-DIttp4Yk.js +0 -1
  115. package/assets/clone-Y0952eQY.js +0 -1
  116. package/assets/flowDiagram-v2-96b9c2cf-Dn2WmcvX.js +0 -1
  117. package/assets/stateDiagram-v2-4FDKWEC3-4Ev4KuVZ.js +0 -1
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-_FyCDKGq.js","./Serializer-DPCLjt6U.js","./isEmpty-BZ44SF3F.js","./index-DEjUAZUe.js","./index-CISxTBJ3.js","./index.dom-C3-224fz.js","./ChatMessagesArea-CAnmzKeA.js","./index-DI_5V2-m.js","./katex-Cu_Erd72.js","./ChatMessagesArea-Di0Z80Zh.css","./ttd-dialog-WN-s4x87.js","./index-DNIlXgAo.js","./pick-DUB8w7iE.js","./hasIn-CGUnHN5L.js","./index-C1XdOOAn.css","./ttd-dialog-DCapefb6.css","./settings-dialog-QUxXj54T.css","./settings-dialog-aU8BHcuS.js","./index-DvbaH1wH.js","./upload-Crej215t.js","./index-C4AKKbpQ.css","./ToolboxDrawer-D-ZDs49h.js","./has-BBSmRLAB.js","./ToolboxDrawer-fPqvDLQE.css","./index-DCs3C-gs.js","./index-Bs7-jmv6.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-QG8-KVAs.js","./Serializer-rTHzSF0Y.js","./isEmpty-Bg6e-LN7.js","./index-D1NStEds.js","./index-CiiU0LMF.js","./index.dom-C3-224fz.js","./ChatMessagesArea-DtzEt9y0.js","./index-DI_5V2-m.js","./katex-Cu_Erd72.js","./ChatMessagesArea-Di0Z80Zh.css","./ttd-dialog-TQYw_Nae.js","./index-BNXtnhmh.js","./pick-D_sga9lq.js","./hasIn-DNHU2Dgx.js","./index-C1XdOOAn.css","./ttd-dialog-DCapefb6.css","./settings-dialog-QUxXj54T.css","./settings-dialog-C4eZxway.js","./index-DGb8pRqW.js","./upload-DdSOuK5h.js","./index-C4AKKbpQ.css","./ToolboxDrawer-D0dL1xDI.js","./has-C78hNt79.js","./ToolboxDrawer-fPqvDLQE.css","./index-JhVJEcm-.js","./index-Bs7-jmv6.css"])))=>i.map(i=>d[i]);
2
2
  function IH(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in e)){const s=Object.getOwnPropertyDescriptor(r,i);s&&Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var vo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Io(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n_={exports:{}},r0={},r_={exports:{}},wn={};/**
3
3
  * @license React
4
4
  * react.production.min.js
@@ -1303,7 +1303,7 @@ Latex block: $e=mc^2$`}]},l={max_tokens:n.max_tokens||1024,model:i,temperature:n
1303
1303
  - 水平布局:同组内容(相同groupId)从左到右排列,表示并列关系
1304
1304
 
1305
1305
  不适用场景:
1306
- - 仅生成内容但不需要显示在画布上`,inputSchema:{type:"object",properties:{items:{type:"array",description:"要插入的内容列表",items:{type:"object",properties:{type:{type:"string",description:"内容类型:text(文本)、image(图片URL)、video(视频URL)、svg(SVG代码)",enum:["text","image","video","svg"]},content:{type:"string",description:"内容:文本内容或媒体URL"},label:{type:"string",description:"标签/描述(可选)"},groupId:{type:"string",description:"分组ID,相同groupId的内容会水平排列(可选)"}},required:["type","content"]}},verticalGap:{type:"number",description:"垂直间距(像素),默认50",default:50},horizontalGap:{type:"number",description:"水平间距(像素),默认20",default:20}},required:["items"]},execute:async e=>bee()};async function _7e(e,t,n,r){return bee()}const T7e=Object.freeze(Object.defineProperty({__proto__:null,canvasInsertionTool:Cee,quickInsert:_7e},Symbol.toStringTag,{value:"Module"}));let Eee=null;function F9(e){Eee=e}function a3(){return Eee}const p1=20,l3=50,k7e=100;function wC(e,t){if(t){const i=new RegExp(`\`\`\`(?:${t}|${t.charAt(0).toUpperCase()+t.slice(1)})\\s*([\\s\\S]*?)\`\`\``,"i"),s=e.match(i);if(s)return s[1].trim()}const n=/```(?:\w+)?\s*([\s\S]*?)```/,r=e.match(n);return r?r[1].trim():e.trim()}function P7e(e,t,n=p1){const r=e.x-n,i=e.x+e.width+n,s=e.y-n,o=e.y+e.height+n,a=t.x,l=t.x+t.width,c=t.y,u=t.y+t.height;return!(i<a||r>l||o<c||s>u)}function A7e(e){const t=[];if(!e.children||e.children.length===0)return t;for(const n of e.children)try{const r=Et(e,[n],!1);t.push({x:r.x,y:r.y,width:r.width,height:r.height})}catch(r){console.warn("[InsertUtils] Failed to get bounding box for element:",r)}return t}function See(e,t,n=p1){for(const r of t)if(P7e(e,r,n))return!0;return!1}function D7e(e,t,n,r=p1,i=l3){let s=[...e],o=0;for(;o<k7e;){const a={x:s[0],y:s[1],width:t.width,height:t.height};if(!See(a,n,r))return s;s=[s[0],s[1]+i],o++}return console.warn("[InsertUtils] Max iterations reached, returning current position:",s),s}function I7e(e,t){try{const n=Et(e,[t],!1);return{x:n.x,y:n.y,width:n.width,height:n.height}}catch(n){return console.warn("[InsertUtils] Failed to get actual bounding box:",n),null}}function O7e(e,t){const n=[];if(!e.children||e.children.length===0)return n;for(const r of e.children){const i=r;if(!t.has(i.id))try{const s=Et(e,[i],!1);n.push({x:s.x,y:s.y,width:s.width,height:s.height})}catch{}}return n}function M7e(e,t,n,r){try{const i=e.children.findIndex(a=>a.id===t.id);if(i<0)return console.warn("[InsertUtils] Element not found in board:",t.id),!1;const s=t.points;if(!s||s.length===0)return console.warn("[InsertUtils] Element has no points:",t.id),!1;const o=s.map(a=>[a[0]+n,a[1]+r]);return Ke.setNode(e,{points:o},[i]),!0}catch(i){return console.error("[InsertUtils] Failed to move element:",i),!1}}function R7e(e){const t=GX(e);if(t)return t;const n=A7e(e);if(n.length>0){let c=-1/0,u=0;for(const d of n){const f=d.y+d.height;f>c&&(c=f,u=d.x+d.width/2)}return[u,c+l3]}const r=Q.getBoardContainer(e).getBoundingClientRect(),i=[r.width/2,r.height/2],s=e.viewport.zoom,o=pu(e),a=o[0]+i[0]/s,l=o[1]+i[1]/s;return[a,l]}function B7e(e,t){let n=!1;for(const r of t){const i=e.children.find(u=>u.id===r);if(!i)continue;const s=I7e(e,i);if(!s)continue;const o=O7e(e,t);if(o.length===0||!See(s,o,p1))continue;const a=D7e([s.x,s.y],{width:s.width,height:s.height},o,p1,l3),l=a[0]-s.x,c=a[1]-s.y;(l!==0||c!==0)&&M7e(e,i,l,c)&&(n=!0)}return n}function _ee(e,t,n){if(!t||t.length===0)return{success:!1,error:"没有可插入的元素"};try{const r=new Set(e.children.map(o=>o.id)),i=n||R7e(e);e.insertFragment({elements:JSON.parse(JSON.stringify(t))},i,na.paste);const s=new Set;for(const o of e.children){const a=o;r.has(a.id)||s.add(a.id)}return s.size>0?requestAnimationFrame(()=>{const o=B7e(e,s);i&&So(e,i)}):i&&requestAnimationFrame(()=>{So(e,i)}),{success:!0,elementsCount:t.length}}catch(r){return console.error("[InsertUtils] Failed to insert elements:",r),{success:!1,error:r.message||"插入元素失败"}}}const Tee={loaded:!1,api:new Promise((e,t)=>{ln(()=>import("./index-_FyCDKGq.js").then(n=>n.O),__vite__mapDeps([0,1,2]),import.meta.url).then(n=>{Tee.loaded=!0,e(n)}).catch(t)})};function L7e(e){return wC(e,"mermaid")}function N7e(e){const t=e.trim().toLowerCase();return t.startsWith("flowchart")||t.startsWith("graph")?"flowchart":t.startsWith("sequencediagram")?"sequence":t.startsWith("classdiagram")?"classDiagram":t.startsWith("statediagram")?"stateDiagram":t.startsWith("erdiagram")?"erDiagram":t.startsWith("gantt")?"gantt":t.startsWith("pie")?"pie":t.startsWith("mindmap")?"mindmap":"unknown"}async function j7e(e){const t=a3();if(!t)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};const{mermaid:n}=e;if(!n||typeof n!="string"||n.trim()==="")return{success:!1,error:"缺少必填参数 mermaid,请提供有效的Mermaid markdown字符串",type:"error"};try{const r=L7e(n),i=N7e(r),s=await Tee.api;let o;try{o=await s.parseMermaidToDrawnix(r)}catch(c){console.warn("[MermaidTool] First parse attempt failed, retrying with quote replacement:",c.message),o=await s.parseMermaidToDrawnix(r.replace(/"/g,"'"))}const{elements:a}=o;if(!a||a.length===0)return{success:!1,error:"Mermaid代码解析成功,但未生成任何图表元素",type:"error"};const l=_ee(t,a);return l.success?{success:!0,data:{diagramType:i,elementsCount:l.elementsCount,mermaidCode:r.substring(0,200)+(r.length>200?"...":"")},type:"canvas"}:{success:!1,error:l.error||"插入图表失败",type:"error"}}catch(r){return console.error("[MermaidTool] Failed to process mermaid:",r),{success:!1,error:`Mermaid转换失败: ${r.message||"未知错误"}`,type:"error"}}}const F7e={name:"insert_mermaid",description:`将Mermaid图表插入到画布工具。将Mermaid markdown语法转换为可视化图表并插入到画布中。
1306
+ - 仅生成内容但不需要显示在画布上`,inputSchema:{type:"object",properties:{items:{type:"array",description:"要插入的内容列表",items:{type:"object",properties:{type:{type:"string",description:"内容类型:text(文本)、image(图片URL)、video(视频URL)、svg(SVG代码)",enum:["text","image","video","svg"]},content:{type:"string",description:"内容:文本内容或媒体URL"},label:{type:"string",description:"标签/描述(可选)"},groupId:{type:"string",description:"分组ID,相同groupId的内容会水平排列(可选)"}},required:["type","content"]}},verticalGap:{type:"number",description:"垂直间距(像素),默认50",default:50},horizontalGap:{type:"number",description:"水平间距(像素),默认20",default:20}},required:["items"]},execute:async e=>bee()};async function _7e(e,t,n,r){return bee()}const T7e=Object.freeze(Object.defineProperty({__proto__:null,canvasInsertionTool:Cee,quickInsert:_7e},Symbol.toStringTag,{value:"Module"}));let Eee=null;function F9(e){Eee=e}function a3(){return Eee}const p1=20,l3=50,k7e=100;function wC(e,t){if(t){const i=new RegExp(`\`\`\`(?:${t}|${t.charAt(0).toUpperCase()+t.slice(1)})\\s*([\\s\\S]*?)\`\`\``,"i"),s=e.match(i);if(s)return s[1].trim()}const n=/```(?:\w+)?\s*([\s\S]*?)```/,r=e.match(n);return r?r[1].trim():e.trim()}function P7e(e,t,n=p1){const r=e.x-n,i=e.x+e.width+n,s=e.y-n,o=e.y+e.height+n,a=t.x,l=t.x+t.width,c=t.y,u=t.y+t.height;return!(i<a||r>l||o<c||s>u)}function A7e(e){const t=[];if(!e.children||e.children.length===0)return t;for(const n of e.children)try{const r=Et(e,[n],!1);t.push({x:r.x,y:r.y,width:r.width,height:r.height})}catch(r){console.warn("[InsertUtils] Failed to get bounding box for element:",r)}return t}function See(e,t,n=p1){for(const r of t)if(P7e(e,r,n))return!0;return!1}function D7e(e,t,n,r=p1,i=l3){let s=[...e],o=0;for(;o<k7e;){const a={x:s[0],y:s[1],width:t.width,height:t.height};if(!See(a,n,r))return s;s=[s[0],s[1]+i],o++}return console.warn("[InsertUtils] Max iterations reached, returning current position:",s),s}function I7e(e,t){try{const n=Et(e,[t],!1);return{x:n.x,y:n.y,width:n.width,height:n.height}}catch(n){return console.warn("[InsertUtils] Failed to get actual bounding box:",n),null}}function O7e(e,t){const n=[];if(!e.children||e.children.length===0)return n;for(const r of e.children){const i=r;if(!t.has(i.id))try{const s=Et(e,[i],!1);n.push({x:s.x,y:s.y,width:s.width,height:s.height})}catch{}}return n}function M7e(e,t,n,r){try{const i=e.children.findIndex(a=>a.id===t.id);if(i<0)return console.warn("[InsertUtils] Element not found in board:",t.id),!1;const s=t.points;if(!s||s.length===0)return console.warn("[InsertUtils] Element has no points:",t.id),!1;const o=s.map(a=>[a[0]+n,a[1]+r]);return Ke.setNode(e,{points:o},[i]),!0}catch(i){return console.error("[InsertUtils] Failed to move element:",i),!1}}function R7e(e){const t=GX(e);if(t)return t;const n=A7e(e);if(n.length>0){let c=-1/0,u=0;for(const d of n){const f=d.y+d.height;f>c&&(c=f,u=d.x+d.width/2)}return[u,c+l3]}const r=Q.getBoardContainer(e).getBoundingClientRect(),i=[r.width/2,r.height/2],s=e.viewport.zoom,o=pu(e),a=o[0]+i[0]/s,l=o[1]+i[1]/s;return[a,l]}function B7e(e,t){let n=!1;for(const r of t){const i=e.children.find(u=>u.id===r);if(!i)continue;const s=I7e(e,i);if(!s)continue;const o=O7e(e,t);if(o.length===0||!See(s,o,p1))continue;const a=D7e([s.x,s.y],{width:s.width,height:s.height},o,p1,l3),l=a[0]-s.x,c=a[1]-s.y;(l!==0||c!==0)&&M7e(e,i,l,c)&&(n=!0)}return n}function _ee(e,t,n){if(!t||t.length===0)return{success:!1,error:"没有可插入的元素"};try{const r=new Set(e.children.map(o=>o.id)),i=n||R7e(e);e.insertFragment({elements:JSON.parse(JSON.stringify(t))},i,na.paste);const s=new Set;for(const o of e.children){const a=o;r.has(a.id)||s.add(a.id)}return s.size>0?requestAnimationFrame(()=>{const o=B7e(e,s);i&&So(e,i)}):i&&requestAnimationFrame(()=>{So(e,i)}),{success:!0,elementsCount:t.length}}catch(r){return console.error("[InsertUtils] Failed to insert elements:",r),{success:!1,error:r.message||"插入元素失败"}}}const Tee={loaded:!1,api:new Promise((e,t)=>{ln(()=>import("./index-QG8-KVAs.js").then(n=>n.O),__vite__mapDeps([0,1,2]),import.meta.url).then(n=>{Tee.loaded=!0,e(n)}).catch(t)})};function L7e(e){return wC(e,"mermaid")}function N7e(e){const t=e.trim().toLowerCase();return t.startsWith("flowchart")||t.startsWith("graph")?"flowchart":t.startsWith("sequencediagram")?"sequence":t.startsWith("classdiagram")?"classDiagram":t.startsWith("statediagram")?"stateDiagram":t.startsWith("erdiagram")?"erDiagram":t.startsWith("gantt")?"gantt":t.startsWith("pie")?"pie":t.startsWith("mindmap")?"mindmap":"unknown"}async function j7e(e){const t=a3();if(!t)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};const{mermaid:n}=e;if(!n||typeof n!="string"||n.trim()==="")return{success:!1,error:"缺少必填参数 mermaid,请提供有效的Mermaid markdown字符串",type:"error"};try{const r=L7e(n),i=N7e(r),s=await Tee.api;let o;try{o=await s.parseMermaidToDrawnix(r)}catch(c){console.warn("[MermaidTool] First parse attempt failed, retrying with quote replacement:",c.message),o=await s.parseMermaidToDrawnix(r.replace(/"/g,"'"))}const{elements:a}=o;if(!a||a.length===0)return{success:!1,error:"Mermaid代码解析成功,但未生成任何图表元素",type:"error"};const l=_ee(t,a);return l.success?{success:!0,data:{diagramType:i,elementsCount:l.elementsCount,mermaidCode:r.substring(0,200)+(r.length>200?"...":"")},type:"canvas"}:{success:!1,error:l.error||"插入图表失败",type:"error"}}catch(r){return console.error("[MermaidTool] Failed to process mermaid:",r),{success:!1,error:`Mermaid转换失败: ${r.message||"未知错误"}`,type:"error"}}}const F7e={name:"insert_mermaid",description:`将Mermaid图表插入到画布工具。将Mermaid markdown语法转换为可视化图表并插入到画布中。
1307
1307
 
1308
1308
  使用场景:
1309
1309
  - 用户需要在画布上创建流程图、时序图、类图等图表
@@ -1336,7 +1336,7 @@ sequenceDiagram
1336
1336
  AuthServer->>Client: 返回Access Token
1337
1337
  Client->>ResourceServer: 携带Token请求资源
1338
1338
  ResourceServer->>Client: 返回资源
1339
- \`\`\``,inputSchema:{type:"object",properties:{mermaid:{type:"string",description:"Mermaid markdown字符串,可以是纯Mermaid代码或包含```mermaid代码块的markdown"}},required:["mermaid"]},execute:async e=>j7e(e)},kee={loaded:!1,api:new Promise((e,t)=>{ln(()=>import("./index-DEjUAZUe.js"),__vite__mapDeps([3,4,5]),import.meta.url).then(n=>{kee.loaded=!0,e(n)}).catch(t)})};function $7e(e){const t=wC(e,"markdown");return t===e.trim(),t}async function z7e(e){const t=a3();if(!t)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};const{markdown:n}=e;if(!n||typeof n!="string"||n.trim()==="")return{success:!1,error:"缺少必填参数 markdown,请提供有效的 Markdown 思维导图定义",type:"error"};try{const r=$7e(n),i=await kee.api;let s;try{s=await i.parseMarkdownToDrawnix(r)}catch(l){console.warn("[MindmapTool] First parse attempt failed, retrying with quote replacement:",l.message),s=await i.parseMarkdownToDrawnix(r.replace(/"/g,"'"))}if(!s)return{success:!1,error:"Markdown 解析成功,但未生成思维导图元素",type:"error"};s.points=[[0,0]];const a=_ee(t,[s]);return a.success?{success:!0,data:{type:"mindmap",elementsCount:a.elementsCount,markdownPreview:r.substring(0,200)+(r.length>200?"...":"")},type:"canvas"}:{success:!1,error:a.error||"插入思维导图失败",type:"error"}}catch(r){return console.error("[MindmapTool] Failed to process markdown:",r),{success:!1,error:`思维导图转换失败: ${r.message||"未知错误"}`,type:"error"}}}const H7e={name:"insert_mindmap",description:`将 Markdown 思维导图插入到画布工具。将 Markdown 语法转换为可视化思维导图并插入到画布中。
1339
+ \`\`\``,inputSchema:{type:"object",properties:{mermaid:{type:"string",description:"Mermaid markdown字符串,可以是纯Mermaid代码或包含```mermaid代码块的markdown"}},required:["mermaid"]},execute:async e=>j7e(e)},kee={loaded:!1,api:new Promise((e,t)=>{ln(()=>import("./index-D1NStEds.js"),__vite__mapDeps([3,4,5]),import.meta.url).then(n=>{kee.loaded=!0,e(n)}).catch(t)})};function $7e(e){const t=wC(e,"markdown");return t===e.trim(),t}async function z7e(e){const t=a3();if(!t)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};const{markdown:n}=e;if(!n||typeof n!="string"||n.trim()==="")return{success:!1,error:"缺少必填参数 markdown,请提供有效的 Markdown 思维导图定义",type:"error"};try{const r=$7e(n),i=await kee.api;let s;try{s=await i.parseMarkdownToDrawnix(r)}catch(l){console.warn("[MindmapTool] First parse attempt failed, retrying with quote replacement:",l.message),s=await i.parseMarkdownToDrawnix(r.replace(/"/g,"'"))}if(!s)return{success:!1,error:"Markdown 解析成功,但未生成思维导图元素",type:"error"};s.points=[[0,0]];const a=_ee(t,[s]);return a.success?{success:!0,data:{type:"mindmap",elementsCount:a.elementsCount,markdownPreview:r.substring(0,200)+(r.length>200?"...":"")},type:"canvas"}:{success:!1,error:a.error||"插入思维导图失败",type:"error"}}catch(r){return console.error("[MindmapTool] Failed to process markdown:",r),{success:!1,error:`思维导图转换失败: ${r.message||"未知错误"}`,type:"error"}}}const H7e={name:"insert_mindmap",description:`将 Markdown 思维导图插入到画布工具。将 Markdown 语法转换为可视化思维导图并插入到画布中。
1340
1340
 
1341
1341
  使用场景:
1342
1342
  - 用户需要在画布上创建思维导图
@@ -1487,7 +1487,7 @@ ${V7e()}
1487
1487
  不适用场景:
1488
1488
  - 只想生成单张图片(使用 generate_image 工具)
1489
1489
  - 想要整齐的网格排列(使用 generate_grid_image 工具)
1490
- - 想要生成视频(使用 generate_video 工具)`,inputSchema:{type:"object",properties:{theme:{type:"string",description:'灵感图主题描述,如"可爱香蕉的各种形态"、"咖啡文化"、"城市街角"等'},imageCount:{type:"number",description:"图片数量,1-16 之间,默认 9",default:9},imageSize:{type:"string",description:"生成图片的尺寸比例(建议横向)",enum:["16x9","3x2","1x1"],default:"16x9"},imageQuality:{type:"string",description:"图片质量",enum:["1k","2k","4k"],default:"2k"},referenceImages:{type:"array",description:"参考图片 URL 列表,用于风格参考",items:{type:"string"}},model:{type:"string",description:"图片生成模型,不指定时使用用户设置的模型"}},required:["theme"]},supportedModes:["queue"],promptGuidance:{whenToUse:"当用户想要生成创意灵感图、灵感板、Mood Board 效果时使用。关键词:灵感图、灵感板、创意拼贴、艺术展示、Mood Board、Pinterest 风格。",parameterGuidance:{theme:"主题描述应该具体且有多样性潜力。好的主题:描述一类事物的多种变体、不同角度或不同场景。避免过于具体的单一描述。",imageCount:"1-16 张,会自动计算最优网格布局(如 9 张 = 3x3,12 张 = 3x4)。",imageSize:"建议使用 16x9 横向比例,生成更大尺寸的图片。"},bestPractices:['主题应强调多样性和变化,如"咖啡的各种形态"而非"一杯咖啡"','可以指定风格混搭,如"写实与插画混合"、"不同时代风格"',"描述具体的视觉元素,帮助 AI 生成更丰富的内容","生成的是紧凑网格图,拆分后每张子图都是高质量大图"],examples:[{input:"生成一个可爱香蕉的灵感图",args:{theme:"可爱香蕉的各种形态,包含卡通香蕉、写实香蕉、香蕉角色、香蕉图案等不同风格",imageCount:9},explanation:"生成 3x3 网格,拆分后 9 张等大图片以散落布局插入"},{input:"做个城市街角的 Mood Board",args:{theme:"城市街角,包含不同城市、不同时间、不同天气、不同风格的街角场景",imageCount:8,imageSize:"16x9"},explanation:"生成 2x4 网格,横向布局更适合展示街景"}],warnings:["生成的是紧凑网格生产图,拆分后以散落布局插入画布","实际图片数量取决于网格布局(如 7 张会调整为 2x4 = 8 张)","建议使用横向比例(16x9)以获得更大的子图尺寸"]},execute:async(e,t)=>Y7e(e,t||{})};function Aee(e,t,n,r=240){return e>=r&&t>=r&&n>=r}function c3(e,t=50){return e<t}function Dee(e,t){const{width:n,data:r}=e;let i=0;for(let s=0;s<n;s++){const o=(t*n+s)*4;Aee(r[o],r[o+1],r[o+2])&&i++}return i/n}function Q7e(e,t){const{width:n,data:r}=e;let i=0;for(let s=0;s<n;s++){const o=(t*n+s)*4;c3(r[o+3])&&i++}return i/n}function Iee(e,t){const{width:n,height:r,data:i}=e;let s=0;for(let o=0;o<r;o++){const a=(o*n+t)*4;Aee(i[a],i[a+1],i[a+2])&&s++}return s/r}function J7e(e,t){const{width:n,height:r,data:i}=e;let s=0;for(let o=0;o<r;o++){const a=(o*n+t)*4;c3(i[a+3])&&s++}return s/r}function eje(e,t,n=.9){return Dee(e,t)>=n}function tje(e,t,n=1){return Q7e(e,t)>=n}function nje(e,t,n=.9){return Iee(e,t)>=n}function rje(e,t,n=1){return J7e(e,t)>=n}function $9(e,t=10){if(e.length===0)return[];const n=[...e].sort((o,a)=>o-a),r=[];let i=n[0],s=n[0];for(let o=1;o<n.length;o++)n[o]-s<=t||(r.push(Math.floor((i+s)/2)),i=n[o]),s=n[o];return r.push(Math.floor((i+s)/2)),r}function ije(e,t){return[{rows:4,cols:4},{rows:4,cols:3},{rows:4,cols:2},{rows:2,cols:2},{rows:2,cols:3},{rows:2,cols:4},{rows:3,cols:2},{rows:3,cols:3},{rows:3,cols:4},{rows:5,cols:5}].map(s=>{const o=e/s.cols,a=t/s.rows,l=o/a,u=1/(1+Math.abs(l-1)*10);return{...s,score:u,cellAspectRatio:l}}).filter(s=>s.cellAspectRatio>=.8&&s.cellAspectRatio<=1.25)}function sje(e,t,n){const r=ije(t,n);if(r.length===0)return null;for(const i of r)if(oje(e,t,n,i.rows,i.cols))return{rows:i.rows,cols:i.cols};return null}function oje(e,t,n,r,i){const s=t/i,o=n/r,a=10,l=.7;for(let c=1;c<i;c++){const u=Math.round(c*s);let d=!1;for(let f=u-a;f<=u+a;f++){if(f<0||f>=t)continue;if(Iee(e,f)>=l){d=!0;break}}if(!d)return!1}for(let c=1;c<r;c++){const u=Math.round(c*o);let d=!1;for(let f=u-a;f<=u+a;f++){if(f<0||f>=n)continue;if(Dee(e,f)>=l){d=!0;break}}if(!d)return!1}return!0}function z9(e,t=3){if(e.length===0)return[];const n=[...e].sort((o,a)=>o-a),r=[];let i=n[0],s=n[0];for(let o=1;o<=n.length;o++)o<n.length&&n[o]-s<=1?s=n[o]:(s-i+1>=t&&r.push(Math.floor((i+s)/2)),o<n.length&&(i=n[o],s=n[o]));return r}function aje(e){const{data:t}=e;for(let n=3;n<t.length;n+=4)if(t[n]>50)return!1;return!0}function Oee(e){const{data:t}=e;let n=0;const r=t.length/4;for(let s=3;s<t.length;s+=40)c3(t[s])&&n++;const i=Math.floor(r/10);return n/i>.05}async function Mee(e,t){const n=await K1(e),{naturalWidth:r,naturalHeight:i}=n,s=document.createElement("canvas");s.width=r,s.height=i;const o=s.getContext("2d",{willReadFrequently:!0});if(!o)throw new Error("Failed to get canvas context");o.drawImage(n,0,0);const a=o.getImageData(0,0,r,i),l=t??Oee(a),c=[],u=Math.floor(i*.05);if(l)for(let b=u;b<i-u;b++)tje(a,b)&&c.push(b);else for(let b=u;b<i-u;b++)eje(a,b)&&c.push(b);const d=[],f=Math.floor(r*.05);if(l)for(let b=f;b<r-f;b++)rje(a,b)&&d.push(b);else for(let b=f;b<r-f;b++)nje(a,b)&&d.push(b);const h=z9(c,2),m=z9(d,2),g=$9(h,Math.floor(i*.02)),w=$9(m,Math.floor(r*.02)),C=sje(a,r,i);if(C){const b=r/C.cols,_=i/C.rows,T=[],S=[];for(let k=1;k<C.rows;k++)T.push(Math.round(k*_));for(let k=1;k<C.cols;k++)S.push(Math.round(k*b));return{detection:{rows:C.rows,cols:C.cols,rowLines:T,colLines:S},img:n,imageData:a,canvas:s,hasTransparency:l}}return{detection:{rows:g.length+1,cols:w.length+1,rowLines:g,colLines:w},img:n,imageData:a,canvas:s,hasTransparency:l}}async function Ree(e,t){const{detection:n}=await Mee(e,t);return n}async function lje(e){try{const{detectPhotoWallRegions:t}=await ln(async()=>{const{detectPhotoWallRegions:r}=await import("./photo-wall-splitter-C1GbxYBl.js");return{detectPhotoWallRegions:r}},[],import.meta.url);return(await t(e,{minRegionSize:3e3,minRegionRatio:.005})).count>=2}catch(t){return console.warn("[ImageSplitter] Failed to detect inspiration board format:",t),!1}}function cje(e,t,n){const{rowLines:r,colLines:i}=e;if(r.length===0||i.length===0)return!1;const s=n/(r.length+1);for(let a=0;a<r.length;a++){const l=s*(a+1);if(Math.abs(r[a]-l)>s*.15)return!1}const o=t/(i.length+1);for(let a=0;a<i.length;a++){const l=o*(a+1);if(Math.abs(i[a]-l)>o*.15)return!1}return!0}function uje(e,t,n,r=220,i=30){const o=e.getImageData(0,0,t,n).data,a=m=>{const g=o[m],w=o[m+1],C=o[m+2];return o[m+3]<=i?!0:g<r||w<r||C<r?!1:Math.max(g,w,C)-Math.min(g,w,C)<=40},l=m=>{for(let g=0;g<t;g++){const w=(m*t+g)*4;if(!a(w))return!1}return!0},c=m=>{for(let g=0;g<n;g++){const w=(g*t+m)*4;if(!a(w))return!1}return!0};let u=0;for(;u<n&&l(u);)u++;let d=n-1;for(;d>u&&l(d);)d--;let f=0;for(;f<t&&c(f);)f++;let h=t-1;for(;h>f&&c(h);)h--;return{top:u,right:h,bottom:d,left:f}}async function dje(e,t,n,r){const i=e.naturalWidth,s=e.naturalHeight,o=Math.floor(i/n),a=Math.floor(s/t),l=[];for(let c=0;c<t;c++)for(let u=0;u<n;u++){const d=c*n+u,f=u*o,h=c*a,m=document.createElement("canvas");m.width=o,m.height=a;const g=m.getContext("2d",{willReadFrequently:!0});if(!g)continue;g.drawImage(e,f,h,o,a,0,0,o,a);const w=uje(g,o,a),C=w.right-w.left+1,b=w.bottom-w.top+1;if(C<o||b<a){const _=document.createElement("canvas");_.width=C,_.height=b;const T=_.getContext("2d");if(!T)continue;T.drawImage(m,w.left,w.top,C,b,0,0,C,b),l.push({imageData:_.toDataURL("image/jpeg",.92),index:d,width:C,height:b,sourceX:f+w.left,sourceY:h+w.top,hasTransparency:r})}else l.push({imageData:m.toDataURL("image/jpeg",.92),index:d,width:o,height:a,sourceX:f,sourceY:h,hasTransparency:r})}return l}async function u3(e,t,n){const r=await K1(e),{naturalWidth:i,naturalHeight:s}=r;if(cje(t,i,s))return dje(r,t.rows,t.cols,n);const a=[0,...t.rowLines,s],l=[0,...t.colLines,i],c=[];let u=0;const d=document.createElement("canvas");d.width=i,d.height=s;const f=d.getContext("2d",{willReadFrequently:!0});if(!f)return c;f.drawImage(r,0,0);const h=f.getImageData(0,0,i,s),m=n??Oee(h);for(let g=0;g<a.length-1;g++)for(let w=0;w<l.length-1;w++){const C=l[w],b=l[w+1],_=a[g],T=a[g+1],S=m?0:8;let k=C+(w>0?S:0),D=_+(g>0?S:0),O=b-C-(w>0?S:0)-(w<l.length-2?S:0),I=T-_-(g>0?S:0)-(g<a.length-2?S:0);if(O<=0||I<=0)continue;const R=f.getImageData(k,D,O,I);if(m&&aje(R))continue;let F;m?F=hje(R,!0):F=MX(R,.5,.15);const M=k+F.left,$=D+F.top,A=F.right-F.left+1,z=F.bottom-F.top+1;if(A<=10||z<=10)continue;const G=document.createElement("canvas");G.width=A,G.height=z;const W=G.getContext("2d");if(!W)continue;W.drawImage(r,M,$,A,z,0,0,A,z);const K=m?"image/png":"image/jpeg",j=m?void 0:.92;c.push({imageData:G.toDataURL(K,j),index:u++,width:A,height:z,sourceX:M,sourceY:$,hasTransparency:m})}return c}function H9(e,t,n,r=235){return e>=r&&t>=r&&n>=r}function fje(e,t=.7,n=.15){const{width:r,height:i,data:s}=e,o=Math.floor(i*n),a=Math.floor(i*n),l=Math.floor(r*n),c=Math.floor(r*n),u=Math.min(r,i)*.15,d=C=>{let b=0;const _=Math.floor(u),T=r-Math.floor(u),S=T-_;if(S<=0)return!1;for(let k=_;k<T;k++){const D=(C*r+k)*4;H9(s[D],s[D+1],s[D+2])&&b++}return b/S>t},f=C=>{let b=0;const _=Math.floor(u),T=i-Math.floor(u),S=T-_;if(S<=0)return!1;for(let k=_;k<T;k++){const D=(k*r+C)*4;H9(s[D],s[D+1],s[D+2])&&b++}return b/S>t};let h=0;for(;h<o&&h<i-1&&d(h);)h++;let m=i-1;for(;i-1-m<a&&m>h&&d(m);)m--;let g=0;for(;g<l&&g<r-1&&f(g);)g++;let w=r-1;for(;r-1-w<c&&w>g&&f(w);)w--;return{top:h,right:w,bottom:m,left:g}}function hje(e,t=!0){const{width:n,height:r,data:i}=e,s=t?0:50,o=f=>{for(let h=0;h<n;h++){const m=(f*n+h)*4;if(i[m+3]>s)return!1}return!0},a=f=>{for(let h=0;h<r;h++){const m=(h*n+f)*4;if(i[m+3]>s)return!1}return!0};let l=0;for(;l<r&&o(l);)l++;let c=r-1;for(;c>l&&o(c);)c--;let u=0;for(;u<n&&a(u);)u++;let d=n-1;for(;d>u&&a(d);)d--;return{top:l,right:d,bottom:c,left:u}}async function BA(e){const t=await K1(e),n=t.naturalWidth,r=t.naturalHeight,i=document.createElement("canvas");i.width=n,i.height=r;const s=i.getContext("2d",{willReadFrequently:!0});if(!s)return{trimmedImageUrl:e,borderInfo:{original:{width:n,height:r},trimmed:{width:n,height:r},borders:{left:0,top:0,right:0,bottom:0},hasBorders:!1}};s.drawImage(t,0,0);const o=s.getImageData(0,0,n,r),a=fje(o,.8,.1),l=a.right-a.left+1,c=a.bottom-a.top+1,u=a.left,d=a.top,f=n-a.right-1,h=r-a.bottom-1,m=5;let g=0;if(u>m&&g++,d>m&&g++,f>m&&g++,h>m&&g++,!(g>=2))return{trimmedImageUrl:e,borderInfo:{original:{width:n,height:r},trimmed:{width:n,height:r},borders:{left:0,top:0,right:0,bottom:0},hasBorders:!1}};const C=document.createElement("canvas");C.width=l,C.height=c;const b=C.getContext("2d");return b?(b.drawImage(i,a.left,a.top,l,c,0,0,l,c),{trimmedImageUrl:C.toDataURL("image/jpeg",.95),borderInfo:{original:{width:n,height:r},trimmed:{width:l,height:c},borders:{left:u,top:d,right:f,bottom:h},hasBorders:!0}}):{trimmedImageUrl:e,borderInfo:{original:{width:n,height:r},trimmed:{width:n,height:r},borders:{left:0,top:0,right:0,bottom:0},hasBorders:!1}}}const hp=100;async function d3(e,t=0,n=2,r){if(t>=n)return[e];if(e.width<hp||e.height<hp)return[e];let i=e.imageData,s=e.width,o=e.height,a=!1;{const{trimmedImageUrl:f,borderInfo:h}=await BA(e.imageData);if(i=f,s=h.trimmed.width,o=h.trimmed.height,a=h.hasBorders,s<hp||o<hp)return a?[{...e,imageData:i,width:s,height:o}]:[e]}const l=await Ree(i,e.hasTransparency);if(l.rows<=1&&l.cols<=1)return a?[{...e,imageData:i,width:s,height:o}]:[e];const c=l.rows>1&&l.cols>1,u=await u3(i,l,e.hasTransparency);if(u.length<=1)return a?[{...e,imageData:i,width:s,height:o}]:[e];if(c)return u;const d=[];for(const f of u){if(f.width<hp||f.height<hp){d.push(f);continue}const h=await d3(f,t+1,n);d.push(...h)}return d}function pje(e){if(!e.children||e.children.length===0)return{x:100,y:100};try{let t=null,n=-1/0;for(const i of e.children)try{const s=Et(e,[i],!1),o=s.y+s.height;o>n&&(n=o,t=i)}catch{}if(!t)return{x:100,y:100};const r=Et(e,[t],!1);return{x:r.x,y:r.y+r.height+50}}catch{return{x:100,y:100}}}async function f3(e,t,n){const r=iZ("图片分割"),{sourceRect:i,startPoint:s,scrollToResult:o=!0}=n||{};try{let a=[],l=!1,c,u;const{trimmedImageUrl:d,borderInfo:f}=await BA(t);c=f.trimmed.width,u=f.trimmed.height;const{detection:h,hasTransparency:m}=await Mee(d);if(h.rows>1||h.cols>1){const S=await u3(d,h,m);if(l=h.rows>1&&h.cols>1,m)a=S;else if(l)a=S;else for(const O of S){if(a.length>=25)break;if(O.width<100||O.height<100){a.push(O);continue}const I=await d3(O,0,2),R=25-a.length;a.push(...I.slice(0,R))}}else if(await lje(d)){const{splitPhotoWall:k}=await ln(async()=>{const{splitPhotoWall:O}=await import("./photo-wall-splitter-C1GbxYBl.js");return{splitPhotoWall:O}},[],import.meta.url);a=(await k(d)).map((O,I)=>({imageData:O.imageData,index:I,width:O.width,height:O.height,sourceX:0,sourceY:0}))}if(a.length===0)return{success:!1,count:0,error:"未检测到可拆分的区域,请确保图片包含分割线或灵感图格式"};if(!l){const S=[];for(const k of a){const{trimmedImageUrl:D,borderInfo:O}=await BA(k.imageData);S.push({...k,imageData:D,width:O.trimmed.width,height:O.trimmed.height})}a=S}a=a.map((S,k)=>({...S,index:k}));let g=1;i&&(g=Math.min(i.width/c,i.height/u));let w,C;if(s)w=s[0],C=s[1];else if(i)w=i.x,C=i.y+i.height+20;else{const S=pje(e);w=S.x,C=S.y}let b,_;const{unifiedCacheService:T}=await ln(async()=>{const{unifiedCacheService:S}=await Promise.resolve().then(()=>Kb);return{unifiedCacheService:S}},void 0,import.meta.url);for(let S=0;S<a.length;S++){const k=a[S],D=k.sourceX*g,O=k.sourceY*g,I=w+D,R=C+O,F=k.width*g,M=k.height*g;b||(b=[I,R],_={width:F,height:M});const $=k.hasTransparency?"png":"jpg",z=`/__aitu_cache__/image/${`split-image-${Date.now()}-${S}`}.${$}`,W=await(await fetch(k.imageData)).blob();await T.cacheToCacheStorageOnly(z,W);const K={url:z,width:F,height:M};Yn.insertImage(e,K,[I,R])}if(o&&b&&_){const S=[b[0]+_.width/2,b[1]+_.height/2];requestAnimationFrame(()=>{So(e,S)})}return r(),{success:!0,count:a.length}}catch(a){return r(),{success:!1,count:0,error:a.message||"拆分图片失败"}}}const gje=Object.freeze(Object.defineProperty({__proto__:null,detectGridLines:Ree,recursiveSplitElement:d3,splitAndInsertImages:f3,splitImageByLines:u3},Symbol.toStringTag,{value:"Module"}));function mje(e){return!e||typeof e!="string"?!1:e.startsWith("http://")||e.startsWith("https://")||e.startsWith("data:image/")||e.startsWith("blob:")}async function vje(e,t){const{imageUrl:n}=e;return mje(n)?{success:!1,error:"画板未初始化",type:"error"}:{success:!1,error:"无效的图片 URL,支持 http/https/base64/blob 格式",type:"error"}}const yje={name:"split_image",description:`图片拆分工具。将一张包含多个元素的图片拆分成多个独立图片,并插入到画板中。
1490
+ - 想要生成视频(使用 generate_video 工具)`,inputSchema:{type:"object",properties:{theme:{type:"string",description:'灵感图主题描述,如"可爱香蕉的各种形态"、"咖啡文化"、"城市街角"等'},imageCount:{type:"number",description:"图片数量,1-16 之间,默认 9",default:9},imageSize:{type:"string",description:"生成图片的尺寸比例(建议横向)",enum:["16x9","3x2","1x1"],default:"16x9"},imageQuality:{type:"string",description:"图片质量",enum:["1k","2k","4k"],default:"2k"},referenceImages:{type:"array",description:"参考图片 URL 列表,用于风格参考",items:{type:"string"}},model:{type:"string",description:"图片生成模型,不指定时使用用户设置的模型"}},required:["theme"]},supportedModes:["queue"],promptGuidance:{whenToUse:"当用户想要生成创意灵感图、灵感板、Mood Board 效果时使用。关键词:灵感图、灵感板、创意拼贴、艺术展示、Mood Board、Pinterest 风格。",parameterGuidance:{theme:"主题描述应该具体且有多样性潜力。好的主题:描述一类事物的多种变体、不同角度或不同场景。避免过于具体的单一描述。",imageCount:"1-16 张,会自动计算最优网格布局(如 9 张 = 3x3,12 张 = 3x4)。",imageSize:"建议使用 16x9 横向比例,生成更大尺寸的图片。"},bestPractices:['主题应强调多样性和变化,如"咖啡的各种形态"而非"一杯咖啡"','可以指定风格混搭,如"写实与插画混合"、"不同时代风格"',"描述具体的视觉元素,帮助 AI 生成更丰富的内容","生成的是紧凑网格图,拆分后每张子图都是高质量大图"],examples:[{input:"生成一个可爱香蕉的灵感图",args:{theme:"可爱香蕉的各种形态,包含卡通香蕉、写实香蕉、香蕉角色、香蕉图案等不同风格",imageCount:9},explanation:"生成 3x3 网格,拆分后 9 张等大图片以散落布局插入"},{input:"做个城市街角的 Mood Board",args:{theme:"城市街角,包含不同城市、不同时间、不同天气、不同风格的街角场景",imageCount:8,imageSize:"16x9"},explanation:"生成 2x4 网格,横向布局更适合展示街景"}],warnings:["生成的是紧凑网格生产图,拆分后以散落布局插入画布","实际图片数量取决于网格布局(如 7 张会调整为 2x4 = 8 张)","建议使用横向比例(16x9)以获得更大的子图尺寸"]},execute:async(e,t)=>Y7e(e,t||{})};function Aee(e,t,n,r=240){return e>=r&&t>=r&&n>=r}function c3(e,t=50){return e<t}function Dee(e,t){const{width:n,data:r}=e;let i=0;for(let s=0;s<n;s++){const o=(t*n+s)*4;Aee(r[o],r[o+1],r[o+2])&&i++}return i/n}function Q7e(e,t){const{width:n,data:r}=e;let i=0;for(let s=0;s<n;s++){const o=(t*n+s)*4;c3(r[o+3])&&i++}return i/n}function Iee(e,t){const{width:n,height:r,data:i}=e;let s=0;for(let o=0;o<r;o++){const a=(o*n+t)*4;Aee(i[a],i[a+1],i[a+2])&&s++}return s/r}function J7e(e,t){const{width:n,height:r,data:i}=e;let s=0;for(let o=0;o<r;o++){const a=(o*n+t)*4;c3(i[a+3])&&s++}return s/r}function eje(e,t,n=.9){return Dee(e,t)>=n}function tje(e,t,n=1){return Q7e(e,t)>=n}function nje(e,t,n=.9){return Iee(e,t)>=n}function rje(e,t,n=1){return J7e(e,t)>=n}function $9(e,t=10){if(e.length===0)return[];const n=[...e].sort((o,a)=>o-a),r=[];let i=n[0],s=n[0];for(let o=1;o<n.length;o++)n[o]-s<=t||(r.push(Math.floor((i+s)/2)),i=n[o]),s=n[o];return r.push(Math.floor((i+s)/2)),r}function ije(e,t){return[{rows:4,cols:4},{rows:4,cols:3},{rows:4,cols:2},{rows:2,cols:2},{rows:2,cols:3},{rows:2,cols:4},{rows:3,cols:2},{rows:3,cols:3},{rows:3,cols:4},{rows:5,cols:5}].map(s=>{const o=e/s.cols,a=t/s.rows,l=o/a,u=1/(1+Math.abs(l-1)*10);return{...s,score:u,cellAspectRatio:l}}).filter(s=>s.cellAspectRatio>=.8&&s.cellAspectRatio<=1.25)}function sje(e,t,n){const r=ije(t,n);if(r.length===0)return null;for(const i of r)if(oje(e,t,n,i.rows,i.cols))return{rows:i.rows,cols:i.cols};return null}function oje(e,t,n,r,i){const s=t/i,o=n/r,a=10,l=.7;for(let c=1;c<i;c++){const u=Math.round(c*s);let d=!1;for(let f=u-a;f<=u+a;f++){if(f<0||f>=t)continue;if(Iee(e,f)>=l){d=!0;break}}if(!d)return!1}for(let c=1;c<r;c++){const u=Math.round(c*o);let d=!1;for(let f=u-a;f<=u+a;f++){if(f<0||f>=n)continue;if(Dee(e,f)>=l){d=!0;break}}if(!d)return!1}return!0}function z9(e,t=3){if(e.length===0)return[];const n=[...e].sort((o,a)=>o-a),r=[];let i=n[0],s=n[0];for(let o=1;o<=n.length;o++)o<n.length&&n[o]-s<=1?s=n[o]:(s-i+1>=t&&r.push(Math.floor((i+s)/2)),o<n.length&&(i=n[o],s=n[o]));return r}function aje(e){const{data:t}=e;for(let n=3;n<t.length;n+=4)if(t[n]>50)return!1;return!0}function Oee(e){const{data:t}=e;let n=0;const r=t.length/4;for(let s=3;s<t.length;s+=40)c3(t[s])&&n++;const i=Math.floor(r/10);return n/i>.05}async function Mee(e,t){const n=await K1(e),{naturalWidth:r,naturalHeight:i}=n,s=document.createElement("canvas");s.width=r,s.height=i;const o=s.getContext("2d",{willReadFrequently:!0});if(!o)throw new Error("Failed to get canvas context");o.drawImage(n,0,0);const a=o.getImageData(0,0,r,i),l=t??Oee(a),c=[],u=Math.floor(i*.05);if(l)for(let b=u;b<i-u;b++)tje(a,b)&&c.push(b);else for(let b=u;b<i-u;b++)eje(a,b)&&c.push(b);const d=[],f=Math.floor(r*.05);if(l)for(let b=f;b<r-f;b++)rje(a,b)&&d.push(b);else for(let b=f;b<r-f;b++)nje(a,b)&&d.push(b);const h=z9(c,2),m=z9(d,2),g=$9(h,Math.floor(i*.02)),w=$9(m,Math.floor(r*.02)),C=sje(a,r,i);if(C){const b=r/C.cols,_=i/C.rows,T=[],S=[];for(let k=1;k<C.rows;k++)T.push(Math.round(k*_));for(let k=1;k<C.cols;k++)S.push(Math.round(k*b));return{detection:{rows:C.rows,cols:C.cols,rowLines:T,colLines:S},img:n,imageData:a,canvas:s,hasTransparency:l}}return{detection:{rows:g.length+1,cols:w.length+1,rowLines:g,colLines:w},img:n,imageData:a,canvas:s,hasTransparency:l}}async function Ree(e,t){const{detection:n}=await Mee(e,t);return n}async function lje(e){try{const{detectPhotoWallRegions:t}=await ln(async()=>{const{detectPhotoWallRegions:r}=await import("./photo-wall-splitter-CAWxP47k.js");return{detectPhotoWallRegions:r}},[],import.meta.url);return(await t(e,{minRegionSize:3e3,minRegionRatio:.005})).count>=2}catch(t){return console.warn("[ImageSplitter] Failed to detect inspiration board format:",t),!1}}function cje(e,t,n){const{rowLines:r,colLines:i}=e;if(r.length===0||i.length===0)return!1;const s=n/(r.length+1);for(let a=0;a<r.length;a++){const l=s*(a+1);if(Math.abs(r[a]-l)>s*.15)return!1}const o=t/(i.length+1);for(let a=0;a<i.length;a++){const l=o*(a+1);if(Math.abs(i[a]-l)>o*.15)return!1}return!0}function uje(e,t,n,r=220,i=30){const o=e.getImageData(0,0,t,n).data,a=m=>{const g=o[m],w=o[m+1],C=o[m+2];return o[m+3]<=i?!0:g<r||w<r||C<r?!1:Math.max(g,w,C)-Math.min(g,w,C)<=40},l=m=>{for(let g=0;g<t;g++){const w=(m*t+g)*4;if(!a(w))return!1}return!0},c=m=>{for(let g=0;g<n;g++){const w=(g*t+m)*4;if(!a(w))return!1}return!0};let u=0;for(;u<n&&l(u);)u++;let d=n-1;for(;d>u&&l(d);)d--;let f=0;for(;f<t&&c(f);)f++;let h=t-1;for(;h>f&&c(h);)h--;return{top:u,right:h,bottom:d,left:f}}async function dje(e,t,n,r){const i=e.naturalWidth,s=e.naturalHeight,o=Math.floor(i/n),a=Math.floor(s/t),l=[];for(let c=0;c<t;c++)for(let u=0;u<n;u++){const d=c*n+u,f=u*o,h=c*a,m=document.createElement("canvas");m.width=o,m.height=a;const g=m.getContext("2d",{willReadFrequently:!0});if(!g)continue;g.drawImage(e,f,h,o,a,0,0,o,a);const w=uje(g,o,a),C=w.right-w.left+1,b=w.bottom-w.top+1;if(C<o||b<a){const _=document.createElement("canvas");_.width=C,_.height=b;const T=_.getContext("2d");if(!T)continue;T.drawImage(m,w.left,w.top,C,b,0,0,C,b),l.push({imageData:_.toDataURL("image/jpeg",.92),index:d,width:C,height:b,sourceX:f+w.left,sourceY:h+w.top,hasTransparency:r})}else l.push({imageData:m.toDataURL("image/jpeg",.92),index:d,width:o,height:a,sourceX:f,sourceY:h,hasTransparency:r})}return l}async function u3(e,t,n){const r=await K1(e),{naturalWidth:i,naturalHeight:s}=r;if(cje(t,i,s))return dje(r,t.rows,t.cols,n);const a=[0,...t.rowLines,s],l=[0,...t.colLines,i],c=[];let u=0;const d=document.createElement("canvas");d.width=i,d.height=s;const f=d.getContext("2d",{willReadFrequently:!0});if(!f)return c;f.drawImage(r,0,0);const h=f.getImageData(0,0,i,s),m=n??Oee(h);for(let g=0;g<a.length-1;g++)for(let w=0;w<l.length-1;w++){const C=l[w],b=l[w+1],_=a[g],T=a[g+1],S=m?0:8;let k=C+(w>0?S:0),D=_+(g>0?S:0),O=b-C-(w>0?S:0)-(w<l.length-2?S:0),I=T-_-(g>0?S:0)-(g<a.length-2?S:0);if(O<=0||I<=0)continue;const R=f.getImageData(k,D,O,I);if(m&&aje(R))continue;let F;m?F=hje(R,!0):F=MX(R,.5,.15);const M=k+F.left,$=D+F.top,A=F.right-F.left+1,z=F.bottom-F.top+1;if(A<=10||z<=10)continue;const G=document.createElement("canvas");G.width=A,G.height=z;const W=G.getContext("2d");if(!W)continue;W.drawImage(r,M,$,A,z,0,0,A,z);const K=m?"image/png":"image/jpeg",j=m?void 0:.92;c.push({imageData:G.toDataURL(K,j),index:u++,width:A,height:z,sourceX:M,sourceY:$,hasTransparency:m})}return c}function H9(e,t,n,r=235){return e>=r&&t>=r&&n>=r}function fje(e,t=.7,n=.15){const{width:r,height:i,data:s}=e,o=Math.floor(i*n),a=Math.floor(i*n),l=Math.floor(r*n),c=Math.floor(r*n),u=Math.min(r,i)*.15,d=C=>{let b=0;const _=Math.floor(u),T=r-Math.floor(u),S=T-_;if(S<=0)return!1;for(let k=_;k<T;k++){const D=(C*r+k)*4;H9(s[D],s[D+1],s[D+2])&&b++}return b/S>t},f=C=>{let b=0;const _=Math.floor(u),T=i-Math.floor(u),S=T-_;if(S<=0)return!1;for(let k=_;k<T;k++){const D=(k*r+C)*4;H9(s[D],s[D+1],s[D+2])&&b++}return b/S>t};let h=0;for(;h<o&&h<i-1&&d(h);)h++;let m=i-1;for(;i-1-m<a&&m>h&&d(m);)m--;let g=0;for(;g<l&&g<r-1&&f(g);)g++;let w=r-1;for(;r-1-w<c&&w>g&&f(w);)w--;return{top:h,right:w,bottom:m,left:g}}function hje(e,t=!0){const{width:n,height:r,data:i}=e,s=t?0:50,o=f=>{for(let h=0;h<n;h++){const m=(f*n+h)*4;if(i[m+3]>s)return!1}return!0},a=f=>{for(let h=0;h<r;h++){const m=(h*n+f)*4;if(i[m+3]>s)return!1}return!0};let l=0;for(;l<r&&o(l);)l++;let c=r-1;for(;c>l&&o(c);)c--;let u=0;for(;u<n&&a(u);)u++;let d=n-1;for(;d>u&&a(d);)d--;return{top:l,right:d,bottom:c,left:u}}async function BA(e){const t=await K1(e),n=t.naturalWidth,r=t.naturalHeight,i=document.createElement("canvas");i.width=n,i.height=r;const s=i.getContext("2d",{willReadFrequently:!0});if(!s)return{trimmedImageUrl:e,borderInfo:{original:{width:n,height:r},trimmed:{width:n,height:r},borders:{left:0,top:0,right:0,bottom:0},hasBorders:!1}};s.drawImage(t,0,0);const o=s.getImageData(0,0,n,r),a=fje(o,.8,.1),l=a.right-a.left+1,c=a.bottom-a.top+1,u=a.left,d=a.top,f=n-a.right-1,h=r-a.bottom-1,m=5;let g=0;if(u>m&&g++,d>m&&g++,f>m&&g++,h>m&&g++,!(g>=2))return{trimmedImageUrl:e,borderInfo:{original:{width:n,height:r},trimmed:{width:n,height:r},borders:{left:0,top:0,right:0,bottom:0},hasBorders:!1}};const C=document.createElement("canvas");C.width=l,C.height=c;const b=C.getContext("2d");return b?(b.drawImage(i,a.left,a.top,l,c,0,0,l,c),{trimmedImageUrl:C.toDataURL("image/jpeg",.95),borderInfo:{original:{width:n,height:r},trimmed:{width:l,height:c},borders:{left:u,top:d,right:f,bottom:h},hasBorders:!0}}):{trimmedImageUrl:e,borderInfo:{original:{width:n,height:r},trimmed:{width:n,height:r},borders:{left:0,top:0,right:0,bottom:0},hasBorders:!1}}}const hp=100;async function d3(e,t=0,n=2,r){if(t>=n)return[e];if(e.width<hp||e.height<hp)return[e];let i=e.imageData,s=e.width,o=e.height,a=!1;{const{trimmedImageUrl:f,borderInfo:h}=await BA(e.imageData);if(i=f,s=h.trimmed.width,o=h.trimmed.height,a=h.hasBorders,s<hp||o<hp)return a?[{...e,imageData:i,width:s,height:o}]:[e]}const l=await Ree(i,e.hasTransparency);if(l.rows<=1&&l.cols<=1)return a?[{...e,imageData:i,width:s,height:o}]:[e];const c=l.rows>1&&l.cols>1,u=await u3(i,l,e.hasTransparency);if(u.length<=1)return a?[{...e,imageData:i,width:s,height:o}]:[e];if(c)return u;const d=[];for(const f of u){if(f.width<hp||f.height<hp){d.push(f);continue}const h=await d3(f,t+1,n);d.push(...h)}return d}function pje(e){if(!e.children||e.children.length===0)return{x:100,y:100};try{let t=null,n=-1/0;for(const i of e.children)try{const s=Et(e,[i],!1),o=s.y+s.height;o>n&&(n=o,t=i)}catch{}if(!t)return{x:100,y:100};const r=Et(e,[t],!1);return{x:r.x,y:r.y+r.height+50}}catch{return{x:100,y:100}}}async function f3(e,t,n){const r=iZ("图片分割"),{sourceRect:i,startPoint:s,scrollToResult:o=!0}=n||{};try{let a=[],l=!1,c,u;const{trimmedImageUrl:d,borderInfo:f}=await BA(t);c=f.trimmed.width,u=f.trimmed.height;const{detection:h,hasTransparency:m}=await Mee(d);if(h.rows>1||h.cols>1){const S=await u3(d,h,m);if(l=h.rows>1&&h.cols>1,m)a=S;else if(l)a=S;else for(const O of S){if(a.length>=25)break;if(O.width<100||O.height<100){a.push(O);continue}const I=await d3(O,0,2),R=25-a.length;a.push(...I.slice(0,R))}}else if(await lje(d)){const{splitPhotoWall:k}=await ln(async()=>{const{splitPhotoWall:O}=await import("./photo-wall-splitter-CAWxP47k.js");return{splitPhotoWall:O}},[],import.meta.url);a=(await k(d)).map((O,I)=>({imageData:O.imageData,index:I,width:O.width,height:O.height,sourceX:0,sourceY:0}))}if(a.length===0)return{success:!1,count:0,error:"未检测到可拆分的区域,请确保图片包含分割线或灵感图格式"};if(!l){const S=[];for(const k of a){const{trimmedImageUrl:D,borderInfo:O}=await BA(k.imageData);S.push({...k,imageData:D,width:O.trimmed.width,height:O.trimmed.height})}a=S}a=a.map((S,k)=>({...S,index:k}));let g=1;i&&(g=Math.min(i.width/c,i.height/u));let w,C;if(s)w=s[0],C=s[1];else if(i)w=i.x,C=i.y+i.height+20;else{const S=pje(e);w=S.x,C=S.y}let b,_;const{unifiedCacheService:T}=await ln(async()=>{const{unifiedCacheService:S}=await Promise.resolve().then(()=>Kb);return{unifiedCacheService:S}},void 0,import.meta.url);for(let S=0;S<a.length;S++){const k=a[S],D=k.sourceX*g,O=k.sourceY*g,I=w+D,R=C+O,F=k.width*g,M=k.height*g;b||(b=[I,R],_={width:F,height:M});const $=k.hasTransparency?"png":"jpg",z=`/__aitu_cache__/image/${`split-image-${Date.now()}-${S}`}.${$}`,W=await(await fetch(k.imageData)).blob();await T.cacheToCacheStorageOnly(z,W);const K={url:z,width:F,height:M};Yn.insertImage(e,K,[I,R])}if(o&&b&&_){const S=[b[0]+_.width/2,b[1]+_.height/2];requestAnimationFrame(()=>{So(e,S)})}return r(),{success:!0,count:a.length}}catch(a){return r(),{success:!1,count:0,error:a.message||"拆分图片失败"}}}const gje=Object.freeze(Object.defineProperty({__proto__:null,detectGridLines:Ree,recursiveSplitElement:d3,splitAndInsertImages:f3,splitImageByLines:u3},Symbol.toStringTag,{value:"Module"}));function mje(e){return!e||typeof e!="string"?!1:e.startsWith("http://")||e.startsWith("https://")||e.startsWith("data:image/")||e.startsWith("blob:")}async function vje(e,t){const{imageUrl:n}=e;return mje(n)?{success:!1,error:"画板未初始化",type:"error"}:{success:!1,error:"无效的图片 URL,支持 http/https/base64/blob 格式",type:"error"}}const yje={name:"split_image",description:`图片拆分工具。将一张包含多个元素的图片拆分成多个独立图片,并插入到画板中。
1491
1491
 
1492
1492
  使用场景:
1493
1493
  - 用户有一张九宫格/拼贴图,想要拆分成独立图片
@@ -1999,7 +1999,7 @@ Style: Disney-style animation, vibrant colors, dreamy lighting.`,"a beautiful su
1999
1999
  `,ts.appendChild(e),document.body.appendChild(ts)}if(window.visualViewport){const e=window.visualViewport,t=e.scale,n=ts.querySelector(".viewport-scaling-message");if(n){const r=e.offsetLeft+e.width/2,i=e.offsetTop+e.height/2;if(n.style.left=`${r}px`,n.style.top=`${i}px`,t!==1){const s=1/t;n.style.transform=`translate(-50%, -50%) scale(${s})`}else n.style.transform="translate(-50%, -50%)"}}requestAnimationFrame(()=>{ts&&(ts.style.opacity="1")}),C0=setTimeout(()=>{ts&&(ts.style.opacity="0",setTimeout(()=>{ts&&ts.parentNode&&(ts.parentNode.removeChild(ts),ts=null)},150)),C0=null},1e3)};function ES(e,t={}){const{enablePositionTracking:n=!1,enableScaleCompensation:r=!0}=t,i=J.useCallback(()=>{const s=e.current;if(!s)return;const o=window.visualViewport,a=o.scale;if(a!==1&&Uze(),n){const l=o.offsetLeft,c=o.offsetTop;s.style.left=`${l}px`,s.style.top=`${c}px`,r&&a!==1?(s.style.transform=`scale(${1/a})`,s.style.transformOrigin="top left"):r&&(s.style.transform="",s.style.transformOrigin="")}else if(r&&a!==1){const l=1/a,c=o.offsetLeft/a,u=o.offsetTop/a;s.style.transform=`translate(${c}px, ${u}px) scale(${l})`,s.style.transformOrigin="top left"}else r&&(s.style.transform="",s.style.transformOrigin="")},[e,n,r]);return x.useEffect(()=>{if(window.visualViewport)return window.visualViewport.addEventListener("resize",i),window.visualViewport.addEventListener("scroll",i),i(),()=>{var s,o;(s=window.visualViewport)==null||s.removeEventListener("resize",i),(o=window.visualViewport)==null||o.removeEventListener("scroll",i)}},[i]),i}const Kze=460,qze=J.memo(({className:e,projectDrawerOpen:t=!1,onProjectDrawerToggle:n,toolboxDrawerOpen:r=!1,onToolboxDrawerToggle:i,taskPanelExpanded:s=!1,onTaskPanelToggle:o,onOpenBackupRestore:a})=>{const[l,c]=x.useState(!1),u=x.useRef(!1),d=x.useRef(null);ES(d,{enablePositionTracking:!0,enableScaleCompensation:!0});const f=x.useCallback(g=>{if(g[0]){const w=g[0].contentRect.height;c(w<Kze)}},[]);x.useEffect(()=>{const g=d.current;if(!g)return;const w=new ResizeObserver(f);return w.observe(g),()=>{w.disconnect()}},[f]);const h=x.useCallback(()=>{!s&&!u.current&&(u.current=!0),o==null||o()},[s,o]),m=x.useCallback(()=>{s&&(o==null||o())},[s,o]);return y.jsxs(y.Fragment,{children:[u.current&&y.jsx(Vze,{expanded:s,onClose:m}),y.jsxs(xr,{ref:d,className:Le("unified-toolbar",vi,{"unified-toolbar--icon-only":l},e),padding:1,children:[y.jsx("div",{className:"unified-toolbar__section unified-toolbar__section--fixed-top",children:y.jsx(U9e,{embedded:!0,iconMode:l,onOpenBackupRestore:a})}),y.jsx("div",{className:"unified-toolbar__scrollable",children:y.jsx("div",{className:"unified-toolbar__section",children:y.jsx(A$e,{embedded:!0,iconMode:l})})}),y.jsx("div",{className:"unified-toolbar__section unified-toolbar__section--fixed-bottom",children:y.jsx(B$e,{projectDrawerOpen:t,onProjectDrawerToggle:n||(()=>{}),toolboxDrawerOpen:r,onToolboxDrawerToggle:i,taskPanelExpanded:s,onTaskPanelToggle:h})})]})]})}),Xze=e=>n=>{const{globalKeyDown:r,keyDown:i}=n;return n.globalKeyDown=s=>{if(!(s.target instanceof HTMLInputElement||s.target instanceof HTMLTextAreaElement)&&(Q.getMovingPointInBoard(n)||Q.isMovingPointInBoard(n))&&!Q.hasBeenTextEditing(n)){if(yn.isHotkey(["mod+shift+e"],{byKey:!0})(s)){eb(n,!0),s.preventDefault();return}if(yn.isHotkey(["mod+s"],{byKey:!0})(s)){PX(n),s.preventDefault();return}if(yn.isHotkey(["mod+backspace"])(s)||yn.isHotkey(["mod+delete"])(s)){e({openCleanConfirm:!0}),s.preventDefault();return}if(yn.isHotkey(["mod+u"])(s)&&mS(n),!s.altKey&&!s.metaKey&&!s.ctrlKey){if(s.key==="h"&&($t.updatePointerType(n,fn.hand),e({pointer:fn.hand})),s.key==="v"&&($t.updatePointerType(n,fn.selection),e({pointer:fn.selection})),s.key==="m"&&(li(n,Ar.dnd),$t.updatePointerType(n,$a.mind),e({pointer:$a.mind})),s.key==="e"&&(li(n,Ar.drawing),$t.updatePointerType(n,Jr.eraser),e({pointer:Jr.eraser})),s.key==="p"&&(s.shiftKey?(li(n,Ar.drawing),$t.updatePointerType(n,Ul.pen),e({pointer:Ul.pen})):(li(n,Ar.drawing),$t.updatePointerType(n,Jr.feltTipPen),e({pointer:Jr.feltTipPen}))),s.key==="a"&&!yn.isHotkey(["mod+a"])(s)&&nt(n).length===0&&(li(n,Ar.drawing),$t.updatePointerType(n,Gn.straight),e({pointer:Gn.straight})),s.key==="r"||s.key==="o"||s.key==="t"){const a={r:yt.rectangle,o:yt.ellipse,t:yt.text};a[s.key]===yt.text?li(n,Ar.dnd):li(n,Ar.drawing),$t.updatePointerType(n,a[s.key]),e({pointer:a[s.key]})}s.preventDefault();return}}r(s)},n.keyDown=s=>{if(yn.isHotkey(["mod+z"],{byKey:!0})(s)){n.undo(),s.preventDefault();return}if(yn.isHotkey(["mod+shift+z"],{byKey:!0})(s)){n.redo(),s.preventDefault();return}i(s)},n},gl={...ci,double:"double"},Yze={strokeWidth:2,strokeColor:ei,strokeStyle:ci.solid,eraserWidth:20,pressureEnabled:!1},Sm=new WeakMap,va=e=>Sm.get(e)||{...Yze},Sz=(e,t)=>{const n=va(e);Sm.set(e,{...n,strokeWidth:t})},Zze=(e,t)=>{const n=va(e);Sm.set(e,{...n,strokeColor:t})},Qze=(e,t)=>{const n=va(e);Sm.set(e,{...n,strokeStyle:t})},Jze=(e,t)=>{const n=va(e);Sm.set(e,{...n,eraserWidth:t})},eHe=(e,t)=>{const n=va(e);Sm.set(e,{...n,pressureEnabled:t})};function D3(e,t){const n=Math.min(t/50,1),r=.2+n*.1,i=6-n*4,s=r+e*(i-r);return Math.max(.5,t*s)}function tHe(e,t,n,r,i){const s=document.createElementNS("http://www.w3.org/2000/svg","g");if(e.length<2){if(e.length===1){const u=document.createElementNS("http://www.w3.org/2000/svg","circle"),d=D3(t[0]??.5,n);u.setAttribute("cx",String(e[0][0])),u.setAttribute("cy",String(e[0][1])),u.setAttribute("r",String(d/2)),u.setAttribute("fill",r),s.appendChild(u)}return s}const o=Q5(e,1,3);if(i===gl.double){const u=n*.8,d=n*.4,[f,h]=rHe(o,t,d,u);if(f){const m=document.createElementNS("http://www.w3.org/2000/svg","path");m.setAttribute("d",f),m.setAttribute("fill",r),m.setAttribute("stroke","none"),s.appendChild(m)}if(h){const m=document.createElementNS("http://www.w3.org/2000/svg","path");m.setAttribute("d",h),m.setAttribute("fill",r),m.setAttribute("stroke","none"),s.appendChild(m)}return s}const a=nc(i,n),l=i!==ci.solid&&a?a.join(" "):"",c=iHe(o,t,n);if(c.length>0){const u=document.createElementNS("http://www.w3.org/2000/svg","path");u.setAttribute("d",c),u.setAttribute("fill",r),u.setAttribute("stroke","none"),l&&(u.setAttribute("fill","none"),u.setAttribute("stroke",r),u.setAttribute("stroke-width",String(n)),u.setAttribute("stroke-dasharray",l),u.setAttribute("stroke-linecap","round"),u.setAttribute("stroke-linejoin","round")),s.appendChild(u)}return s}function nHe(e,t,n){const r=document.createElementNS("http://www.w3.org/2000/svg","g");if(e.length<2){if(e.length===1){const h=t*.8,m=t*.4,g=document.createElementNS("http://www.w3.org/2000/svg","circle");g.setAttribute("cx",String(e[0][0])),g.setAttribute("cy",String(e[0][1]-h/2)),g.setAttribute("r",String(m/2)),g.setAttribute("fill",n),r.appendChild(g);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]+h/2)),w.setAttribute("r",String(m/2)),w.setAttribute("fill",n),r.appendChild(w)}return r}const i=Q5(e,1,3),s=t*.8,o=t*.4,a=[],l=[];for(let h=0;h<i.length;h++){let m,g;h===0?(m=i[1][0]-i[0][0],g=i[1][1]-i[0][1]):h===i.length-1?(m=i[h][0]-i[h-1][0],g=i[h][1]-i[h-1][1]):(m=i[h+1][0]-i[h-1][0],g=i[h+1][1]-i[h-1][1]);const w=Math.sqrt(m*m+g*g);if(w>0){const C=-g/w,b=m/w,_=s/2;a.push([i[h][0]+C*_,i[h][1]+b*_]),l.push([i[h][0]-C*_,i[h][1]-b*_])}else a.push(i[h]),l.push(i[h])}const c=document.createElementNS("http://www.w3.org/2000/svg","path");let u=`M ${a[0][0]} ${a[0][1]}`;for(let h=1;h<a.length;h++){const m=a[h-1],g=a[h],w=(m[0]+g[0])/2,C=(m[1]+g[1])/2;u+=` Q ${m[0]} ${m[1]} ${w} ${C}`}u+=` L ${a[a.length-1][0]} ${a[a.length-1][1]}`,c.setAttribute("d",u),c.setAttribute("fill","none"),c.setAttribute("stroke",n),c.setAttribute("stroke-width",String(o)),c.setAttribute("stroke-linecap","round"),c.setAttribute("stroke-linejoin","round"),r.appendChild(c);const d=document.createElementNS("http://www.w3.org/2000/svg","path");let f=`M ${l[0][0]} ${l[0][1]}`;for(let h=1;h<l.length;h++){const m=l[h-1],g=l[h],w=(m[0]+g[0])/2,C=(m[1]+g[1])/2;f+=` Q ${m[0]} ${m[1]} ${w} ${C}`}return f+=` L ${l[l.length-1][0]} ${l[l.length-1][1]}`,d.setAttribute("d",f),d.setAttribute("fill","none"),d.setAttribute("stroke",n),d.setAttribute("stroke-width",String(o)),d.setAttribute("stroke-linecap","round"),d.setAttribute("stroke-linejoin","round"),r.appendChild(d),r}function rHe(e,t,n,r){if(e.length<2)return["",""];const i=[],s=[];for(let l=0;l<e.length;l++){let c,u;l===0?(c=e[1][0]-e[0][0],u=e[1][1]-e[0][1]):l===e.length-1?(c=e[l][0]-e[l-1][0],u=e[l][1]-e[l-1][1]):(c=e[l+1][0]-e[l-1][0],u=e[l+1][1]-e[l-1][1]);const d=Math.sqrt(c*c+u*u);if(d>0){const f=-u/d,h=c/d,m=r/2;i.push([e[l][0]+f*m,e[l][1]+h*m]),s.push([e[l][0]-f*m,e[l][1]-h*m])}else i.push(e[l]),s.push(e[l])}const o=_z(i,t,n),a=_z(s,t,n);return[o,a]}function _z(e,t,n){if(e.length<2)return"";const r=[],i=[];for(let o=0;o<e.length;o++){const a=t[o]??.5,c=D3(a,n)/2;let u,d;o===0?(u=e[1][0]-e[0][0],d=e[1][1]-e[0][1]):o===e.length-1?(u=e[o][0]-e[o-1][0],d=e[o][1]-e[o-1][1]):(u=e[o+1][0]-e[o-1][0],d=e[o+1][1]-e[o-1][1]);const f=Math.sqrt(u*u+d*d);if(f>0){const h=-d/f,m=u/f;r.push([e[o][0]+h*c,e[o][1]+m*c]),i.push([e[o][0]-h*c,e[o][1]-m*c])}else r.push(e[o]),i.push(e[o])}let s=`M ${r[0][0]} ${r[0][1]}`;for(let o=1;o<r.length;o++){const a=r[o-1],l=r[o],c=(a[0]+l[0])/2,u=(a[1]+l[1])/2;s+=` Q ${a[0]} ${a[1]} ${c} ${u}`}s+=` L ${r[r.length-1][0]} ${r[r.length-1][1]}`,s+=` L ${i[i.length-1][0]} ${i[i.length-1][1]}`;for(let o=i.length-2;o>=0;o--){const a=i[o+1],l=i[o],c=(a[0]+l[0])/2,u=(a[1]+l[1])/2;s+=` Q ${a[0]} ${a[1]} ${c} ${u}`}return s+=` L ${i[0][0]} ${i[0][1]}`,s+=" Z",s}function iHe(e,t,n){if(e.length<2)return"";const r=[],i=[];for(let o=0;o<e.length;o++){const a=t[o]??.5,c=D3(a,n)/2;let u,d;o===0?(u=e[1][0]-e[0][0],d=e[1][1]-e[0][1]):o===e.length-1?(u=e[o][0]-e[o-1][0],d=e[o][1]-e[o-1][1]):(u=e[o+1][0]-e[o-1][0],d=e[o+1][1]-e[o-1][1]);const f=Math.sqrt(u*u+d*d);if(f>0){const h=-d/f,m=u/f;r.push([e[o][0]+h*c,e[o][1]+m*c]),i.push([e[o][0]-h*c,e[o][1]-m*c])}else r.push(e[o]),i.push(e[o])}let s=`M ${r[0][0]} ${r[0][1]}`;for(let o=1;o<r.length;o++){const a=r[o-1],l=r[o],c=(a[0]+l[0])/2,u=(a[1]+l[1])/2;s+=` Q ${a[0]} ${a[1]} ${c} ${u}`}s+=` L ${r[r.length-1][0]} ${r[r.length-1][1]}`,s+=` L ${i[i.length-1][0]} ${i[i.length-1][1]}`;for(let o=i.length-2;o>=0;o--){const a=i[o+1],l=i[o],c=(a[0]+l[0])/2,u=(a[1]+l[1])/2;s+=` Q ${a[0]} ${a[1]} ${c} ${u}`}return s+=` L ${i[0][0]} ${i[0][1]}`,s+=" Z",s}class one extends Qs{draw(t){const n=pn(t),r=Z5(this.board,t),i=HJ(this.board,t),s=fm(this.board,t),o=nc(s,n);if(t.pressures&&t.pressures.length>0)return tHe(t.points,t.pressures,n,r,s);if(s===gl.double)return nHe(t.points,n,r);const a={strokeWidth:n,stroke:r,fill:i,fillStyle:"solid",strokeLineDash:s!==ci.solid?o:void 0},l=Q.getRoughSVG(this.board).curve(Q5(t.points,1,3),a);return hn(l,"round"),l}canDraw(t){return!0}}class sHe extends Xa{constructor(){super()}initializeGenerator(){this.activeGenerator=Td(this.board,{getRectangle:t=>ly(t),getStrokeWidth:()=>Ir,getStrokeOpacity:()=>1,hasResizeHandle:()=>om(this.board,this.element)}),this.generator=new one(this.board)}initialize(){super.initialize(),this.initializeGenerator(),this.generator.processDrawing(this.element,this.getElementG())}onContextChanged(t,n){t.element!==n.element||t.hasThemeChanged?(this.generator.processDrawing(this.element,this.getElementG()),this.activeGenerator.processDrawing(this.element,Q.getActiveHost(this.board),{selected:this.selected})):(t.selected!==n.selected||t.selected)&&this.activeGenerator.processDrawing(this.element,Q.getActiveHost(this.board),{selected:this.selected})}destroy(){var t;super.destroy(),(t=this.activeGenerator)==null||t.destroy()}}class oHe{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 r=n.timestamp??Date.now();if(this.points.length===0){const l={point:t,timestamp:r,...n};return this.points.push(l),this.lastProcessedTime=r,t}if(r-this.lastProcessedTime<this.options.samplingRate&&r-this.lastProcessedTime<2)return null;const i={point:t,timestamp:r,...n};if(!this.checkDistance(t)&&this.points.length>1&&r-this.lastProcessedTime<32)return null;this.updatePoints(i);const o=this.calculateDynamicParameters(i),a=this.smooth(t,o);return this.lastProcessedTime=r,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,r=this.getDistance(n,t);let i=this.options.minDistance;if(this.movingAverageVelocity.length>0){const s=this.getAverageVelocity();i*=Math.max(.5,Math.min(1.5,s/200))}return r>=i}calculateDynamicParameters(t){const n=this.calculateVelocity(t);this.updateMovingAverage(n);const r=this.getAverageVelocity(),i={...this.options};if(t.pressure!==void 0){const o=Math.pow(t.pressure,1.2);i.smoothing*=1-o*i.pressureSensitivity*.8}const s=Math.min(r/i.velocityThreshold,1);if(i.velocityWeight=.2+s*.3,i.smoothing*=1+s*.2,t.tiltX!==void 0&&t.tiltY!==void 0){const o=Math.sqrt(t.tiltX**2+t.tiltY**2)/90;i.smoothing*=1+o*i.tiltSensitivity*.7}return i}smooth(t,n){if(this.points.length<2)return t;const r=this.calculateWeights(n),i=r.reduce((o,a)=>o+a,0);if(i===0)return t;const s=[0,0];for(let o=0;o<this.points.length;o++){const a=r[o]/i;s[0]+=this.points[o].point[0]*a,s[1]+=this.points[o].point[1]*a}return s}calculateWeights(t){const n=[],r=this.points.length-1;for(let i=0;i<this.points.length;i++){let s=Math.pow(t.smoothing,(r-i)*.8);if(i<r){const o=this.getPointVelocity(i);s*=1+o*t.velocityWeight*.8}if(i>0&&i<r){const o=this.getPointCurvature(i);s*=1+o*t.curvatureWeight*.7}n.push(s)}return n}getDistance(t,n){return Xt(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],r=this.getDistance(n.point,t.point),i=t.timestamp-n.timestamp;return i>0?r/i:0}updateMovingAverage(t){this.movingAverageVelocity.push(t),this.movingAverageVelocity.length>this.velocityWindowSize&&this.movingAverageVelocity.shift()}getAverageVelocity(){return this.movingAverageVelocity.length===0?0:this.movingAverageVelocity.reduce((t,n)=>t+n)/this.movingAverageVelocity.length}getPointVelocity(t){if(t>=this.points.length-1)return 0;const n=this.points[t],r=this.points[t+1],i=this.getDistance(n.point,r.point),s=r.timestamp-n.timestamp;return s>0?i/s:0}getPointCurvature(t){if(t<=0||t>=this.points.length-1)return 0;const n=this.points[t-1].point,r=this.points[t].point,i=this.points[t+1].point,s=this.getDistance(n,r),o=this.getDistance(r,i),a=this.getDistance(n,i),l=(s+o+a)/2;return 4*Math.sqrt(Math.max(0,l*(l-s)*(l-o)*(l-a)))/(s*o*a+1e-4)}}const aHe=e=>{const{pointerDown:t,pointerMove:n,pointerUp:r,globalPointerUp:i}=e;let s=!1,o=!1,a=[],l=[],c=null;const u=new one(e),d=new oHe({smoothing:.7,pressureSensitivity:.6});let f=null,h=null,m=null,g=0;const w=(_=!1)=>{if(!h||_){const T=va(e);h={strokeWidth:T.strokeWidth,strokeColor:T.strokeColor,strokeStyle:T.strokeStyle,pressureEnabled:T.pressureEnabled}}return h},C=(_,T)=>{if(!T)return 1;if(_.pointerType==="pen"&&_.pressure>0&&_.pressure!==.5)return _.pressure;const k=[_.x,_.y],D=performance.now();if(m&&g>0){const O=k[0]-m[0],I=k[1]-m[1],R=Math.sqrt(O*O+I*I),F=D-g;if(F>0){const M=R/F,$=.2,A=1,G=Math.min(M/1.5,1),W=A-G*(A-$);return m=k,g=D,W}}return m=k,g=D,.6},b=_=>{if(s){const T=Q.getPointer(e);o&&(a.push(a[0]),l.length>0&&l.push(l[0]));const S=w();f=h9(T,a,{...S,pressures:S.pressureEnabled?l:void 0})}f&&!_&&Ke.insertNode(e,f,[e.children.length]),u==null||u.destroy(),f=null,s=!1,a=[],l=[],m=null,g=0,h=null,d.reset()};return e.pointerDown=_=>{const T=Y5();if(Q.isInPointer(e,T)&&vh(e)){s=!0;const k=w(!0);c=[_.x,_.y];const D=d.process(c);if(D){const O=Vt(e,Kt(e,D[0],D[1]));a.push(O),l.push(C(_,k.pressureEnabled))}}t(_)},e.pointerMove=_=>{if(s){const T=[_.x,_.y];c&&Xt(c[0],c[1],T[0],T[1])<8?o=!0:o=!1;const S=d.process(T);if(S){u==null||u.destroy();const k=Vt(e,Kt(e,S[0],S[1]));a.push(k);const D=w();l.push(C(_,D.pressureEnabled));const O=Q.getPointer(e);f=h9(O,a,{...D,pressures:D.pressureEnabled?l:void 0}),u.processDrawing(f,Q.getElementTopHost(e))}return}n(_)},e.pointerUp=_=>{b(),r(_)},e.globalPointerUp=_=>{b(!0),i(_)},e},lHe=e=>{const t=e,{getDeletedFragment:n,buildFragment:r,insertFragment:i}=t;return t.getDeletedFragment=s=>{const o=g9(t);return o.length&&s.push(...o),n(s)},t.buildFragment=(s,o,a,l)=>{const c=g9(t);if(c.length){const u=iE(t,c,o?[o.x,o.y]:[0,0]);s=tm(s,{text:"",type:Ga.elements,elements:u})}return r(s,o,a,l)},t.insertFragment=(s,o,a)=>{var c;const l=(c=s==null?void 0:s.elements)==null?void 0:c.filter(u=>ir.isFreehand(u));l&&l.length>0&&sE(t,l,o),i(s,o,a)},t};let ib=!1;typeof window<"u"&&(window.addEventListener("keydown",e=>{e.key==="Shift"&&(ib=!0)}),window.addEventListener("keyup",e=>{e.key==="Shift"&&(ib=!1)}),window.addEventListener("blur",()=>{ib=!1}));function SS(){return ib}function _S(e,t,n,r,i=!1,s=20){let o=e.x,a=e.y,l=e.width,c=e.height;const u=e.width/e.height;switch(t){case"0":o=e.x+n,a=e.y+r,l=e.width-n,c=e.height-r;break;case"1":a=e.y+r,l=e.width+n,c=e.height-r;break;case"2":l=e.width+n,c=e.height+r;break;case"3":o=e.x+n,l=e.width-n,c=e.height+r;break;case"4":a=e.y+r,c=e.height-r;break;case"5":l=e.width+n;break;case"6":c=e.height+r;break;case"7":o=e.x+n,l=e.width-n;break}if(i){const d=["0","1","2","3"].includes(t),f=["5","7"].includes(t),h=["4","6"].includes(t);if(d){const m=Math.abs(l-e.width),g=Math.abs(c-e.height);if(m>g){const w=l/u;switch(w-e.height,t){case"0":case"1":a=e.y+e.height-w,c=w;break;case"2":case"3":c=w;break}}else{const w=c*u;switch(w-e.width,t){case"0":case"3":o=e.x+e.width-w,l=w;break;case"1":case"2":l=w;break}}}else if(f){const m=l/u,g=m-e.height;a=e.y-g/2,c=m}else if(h){const m=c*u,g=m-e.width;o=e.x-g/2,l=m}}if(l<s&&((t==="0"||t==="7"||t==="3")&&(o=e.x+e.width-s),l=s,i)){const d=s/u;(t==="0"||t==="4"||t==="1")&&(a=e.y+e.height-d),c=d}if(c<s&&((t==="0"||t==="4"||t==="1")&&(a=e.y+e.height-s),c=s,i)){const d=s*u;(t==="0"||t==="7"||t==="3")&&(o=e.x+e.width-d),l=d}return{x:o,y:a,width:l,height:c}}function cHe(e,t,n,r=0){const i=X.getCenterPoint(t),s=sm(t,Gi);if(r){const o=uHe(n,i,-r);let a=s.find(l=>X.isHit(X.getRectangleByPoints([o,o]),l.rectangle));return a&&(a.cursorClass=eE(a.cursorClass,r)),a}else return s.find(o=>X.isHit(X.getRectangleByPoints([n,n]),o.rectangle))}function uHe(e,t,n){const r=n*Math.PI/180,i=Math.cos(r),s=Math.sin(r),o=e[0]-t[0],a=e[1]-t[1];return[t[0]+o*i-a*s,t[1]+o*s+a*i]}function ane(e){const t=nt(e);return t.length===1&&ir.isFreehand(t[0])?t[0]:null}function dHe(e){return ane(e)!==null}function fHe(e,t){const n=ane(e);if(!n)return null;const r=ly(n),i=n.angle||0,s=cHe(e,r,t,i);return s?{element:n,rectangle:r,handle:s.handle,cursorClass:s.cursorClass}:null}function hHe(e,t,n){const r=n.width/t.width,i=n.height/t.height;return e.map(s=>{const o=s[0]-t.x,a=s[1]-t.y;return[n.x+o*r,n.y+a*i]})}function pHe(e,t,n){const{element:r,rectangle:i,handle:s}=t,{startPoint:o,endPoint:a}=n;if(!i)return;const l=a[0]-o[0],c=a[1]-o[1],u=_S(i,s,l,c,SS(),10),d=hHe(r.points,i,u),f=e.children.findIndex(h=>h.id===r.id);f>=0&&Ke.setNode(e,{points:d},[f])}const gHe=e=>qa(e,{key:"freehand",canResize:()=>dHe(e),hitTest:t=>fHe(e,t),onResize:(t,n)=>pHe(e,t,n)}),mHe=e=>{const{pointerDown:t,pointerMove:n,pointerUp:r,globalPointerUp:i}=e;let s=!1;const o=new Set,a=u=>{const d=Vt(e,Kt(e,u[0],u[1])),h=va(e).eraserWidth/2;e.children.filter(g=>ir.isFreehand(g)).forEach(g=>{!o.has(g.id)&&RBe(e,g,d,h)&&(_n.getElementG(g).style.opacity="0.2",o.add(g.id))})},l=()=>{if(o.size>0){const u=e.children.filter(d=>o.has(d.id));u.length>0&&mh.removeElements(e,u)}},c=()=>{s&&(l(),s=!1,o.clear())};return e.pointerDown=u=>{if(Q.isInPointer(e,[Jr.eraser])&&vh(e)){s=!0,o.clear();const f=[u.x,u.y];a(f);return}t(u)},e.pointerMove=u=>{if(s){ca(e,"with-freehand-erase",()=>{const d=[u.x,u.y];a(d)});return}n(u)},e.pointerUp=u=>{if(s){c();return}r(u)},e.globalPointerUp=u=>{if(s){c();return}i(u)},e},vHe=e=>{const{getRectangle:t,drawElement:n,isHit:r,isRectangleHit:i,getOneHitElement:s,isMovable:o,isAlign:a}=e;return e.drawElement=l=>ir.isFreehand(l.element)?sHe:n(l),e.getRectangle=l=>ir.isFreehand(l)?ly(l):t(l),e.isRectangleHit=(l,c)=>ir.isFreehand(l)?BBe(e,l,c):i(l,c),e.isHit=(l,c,u)=>ir.isFreehand(l)?OBe(e,l,c):r(l,c,u),e.getOneHitElement=l=>l.every(u=>ir.isFreehand(u))?gE(e,l):s(l),e.isMovable=l=>ir.isFreehand(l)?!0:o(l),e.isAlign=l=>ir.isFreehand(l)?!0:a(l),e.setPluginOptions(oE,{customGeometryTypes:[IX]}),gHe(mHe(lHe(aHe(e))))};class yHe extends Xa{constructor(){super()}initializeGenerator(){this.activeGenerator=Td(this.board,{getRectangle:t=>uy(t),getStrokeWidth:()=>Ir,getStrokeOpacity:()=>1,hasResizeHandle:()=>om(this.board,this.element)}),this.generator=new f$e(this.board)}initialize(){super.initialize(),this.initializeGenerator(),this.generator.processDrawing(this.element,this.getElementG()),this.selected&&this.activeGenerator.processDrawing(this.element,Q.getActiveHost(this.board),{selected:this.selected})}onContextChanged(t,n){t.element!==n.element||t.hasThemeChanged?(this.generator.processDrawing(this.element,this.getElementG()),this.activeGenerator.processDrawing(this.element,Q.getActiveHost(this.board),{selected:this.selected})):(t.selected!==n.selected||t.selected)&&this.activeGenerator.processDrawing(this.element,Q.getActiveHost(this.board),{selected:this.selected})}destroy(){var t;super.destroy(),(t=this.activeGenerator)==null||t.destroy()}}const wHe=e=>e,xHe=e=>{const t=e,{getDeletedFragment:n,buildFragment:r,insertFragment:i}=t;return t.getDeletedFragment=s=>{const o=f$(t);return o.length&&s.push(...o),n(s)},t.buildFragment=(s,o,a,l)=>{const c=f$(t);if(c.length){const u=iE(t,c,o?[o.x,o.y]:[0,0]);s=tm(s,{text:"",type:Ga.elements,elements:u})}return r(s,o,a,l)},t.insertFragment=(s,o,a)=>{var c;const l=(c=s==null?void 0:s.elements)==null?void 0:c.filter(u=>lr.isPenPath(u));l&&l.length>0&&sE(t,l,o),i(s,o,a)},t};function bHe(e,t,n,r=0){const i=X.getCenterPoint(t),s=sm(t,Gi);if(r){const o=CHe(n,i,-r);let a=s.find(l=>X.isHit(X.getRectangleByPoints([o,o]),l.rectangle));return a&&(a.cursorClass=eE(a.cursorClass,r)),a}else return s.find(o=>X.isHit(X.getRectangleByPoints([n,n]),o.rectangle))}function CHe(e,t,n){const r=n*Math.PI/180,i=Math.cos(r),s=Math.sin(r),o=e[0]-t[0],a=e[1]-t[1];return[t[0]+o*i-a*s,t[1]+o*s+a*i]}function lne(e){const t=nt(e);return t.length===1&&lr.isPenPath(t[0])?t[0]:null}function EHe(e){return lne(e)!==null}function SHe(e,t){const n=lne(e);if(!n)return null;const r=uy(n),i=n.angle||0,s=bHe(e,r,t,i);return s?{element:n,rectangle:r,handle:s.handle,cursorClass:s.cursorClass}:null}function _He(e,t,n){return e.map(r=>({...r,point:[r.point[0]*t,r.point[1]*n],handleIn:r.handleIn?[r.handleIn[0]*t,r.handleIn[1]*n]:void 0,handleOut:r.handleOut?[r.handleOut[0]*t,r.handleOut[1]*n]:void 0}))}function THe(e,t,n){const{element:r,rectangle:i,handle:s}=t,{startPoint:o,endPoint:a}=n;if(!i)return;const l=a[0]-o[0],c=a[1]-o[1],u=_S(i,s,l,c,SS(),10),d=u.width/i.width,f=u.height/i.height,h=_He(r.anchors,d,f),g=[[u.x,u.y],[u.x+u.width,u.y+u.height]],w=e.children.findIndex(C=>C.id===r.id);w>=0&&Ke.setNode(e,{points:g,anchors:h},[w])}const kHe=e=>qa(e,{key:"pen-path",canResize:()=>EHe(e),hitTest:t=>SHe(e,t),onResize:(t,n)=>THe(e,t,n)}),PHe=e=>{const{getRectangle:t,drawElement:n,isHit:r,isRectangleHit:i,getOneHitElement:s,isMovable:o,isAlign:a}=e;return e.drawElement=l=>lr.isPenPath(l.element)?yHe:n(l),e.getRectangle=l=>lr.isPenPath(l)?uy(l):t(l),e.isRectangleHit=(l,c)=>lr.isPenPath(l)?c$e(e,l,c):i(l,c),e.isHit=(l,c,u)=>lr.isPenPath(l)?l$e(e,l,c):r(l,c,u),e.getOneHitElement=l=>l.every(u=>lr.isPenPath(u))?gE(e,l):s(l),e.isMovable=l=>lr.isPenPath(l)?!0:o(l),e.isAlign=l=>lr.isPenPath(l)?!0:a(l),e.setPluginOptions(oE,{customGeometryTypes:[RO]}),kHe(xHe(wHe(w$e(e))))},cne=new WeakMap,Tz=e=>!!cne.get(e),une=(e,t)=>{cne.set(e,t)},AHe=e=>n=>{const{pointerDown:r}=n;return n.pointerDown=i=>{eP(i)&&!Tz(n)&&(une(n,!0),e({isPencilMode:!0})),!(Tz(n)&&!eP(i))&&r(i)},n},DHe=()=>{const e=Hr(),{appState:t,setAppState:n}=Mi();return y.jsx(y.Fragment,{children:t.isPencilMode&&y.jsx("div",{className:"pencil-mode-toolbar",children:y.jsx(jt,{type:"button",visible:!0,title:"X Pencil","aria-label":"Arrow",label:"Pencil X",onPointerDown:()=>{n({...t,isPencilMode:!1}),une(e,!1)}})})})},IHe="#f5f5f5";function kz(e,t){const n=Math.max(4,Math.min(256,t)),r=n+4,i=r/2,s=n/2,o=`<svg width="${r}" height="${r}" viewBox="0 0 ${r} ${r}" fill="none" xmlns="http://www.w3.org/2000/svg">
2000
2000
  <circle cx="${i}" cy="${i}" r="${s}" fill="${e}" stroke="#fff" stroke-width="1"/>
2001
2001
  <circle cx="${i}" cy="${i}" r="${s}" fill="none" stroke="#333" stroke-width="0.5" stroke-opacity="0.5"/>
2002
- </svg>`;return`url('data:image/svg+xml;base64,${btoa(o)}') ${i} ${i}, crosshair`}function dne(e){return Y5().includes(e)&&e!==Jr.eraser}function fne(e){return e===Jr.eraser}function xv(e,t){var o;const n=document.querySelector(".plait-board-container"),r=n==null?void 0:n.querySelector(".board-host-svg");if(!r)return;const i=va(e),s=((o=e.viewport)==null?void 0:o.zoom)||1;if(dne(t)){const a=i.strokeWidth*s,l=kz(i.strokeColor,a);r.style.cursor=l}else if(fne(t)){const a=i.eraserWidth*s,l=kz(IHe,a);r.style.cursor=l}else r.style.cursor=""}function OHe({board:e,pointer:t}){const n=x.useRef(1),r=x.useRef(null);return x.useEffect(()=>{var o;if(!e)return;xv(e,t),n.current=((o=e.viewport)==null?void 0:o.zoom)||1;let s=null;return(dne(t)||fne(t))&&(s=setInterval(()=>{var l;const a=((l=e.viewport)==null?void 0:l.zoom)||1;Math.abs(a-n.current)>.01&&(n.current=a,xv(e,t))},100)),()=>{s&&clearInterval(s),r.current&&cancelAnimationFrame(r.current);const a=document.querySelector(".plait-board-container"),l=a==null?void 0:a.querySelector(".board-host-svg");l&&(l.style.cursor="")}},[e,t]),{updateCursor:x.useCallback(()=>{e&&xv(e,t)},[e,t])}}function ZT(e,t){xv(e,t)}function MHe(e){xv(e,Jr.eraser)}const RHe=({color:e,size:t,zoom:n})=>{const r=t*n,i=Math.max(4,Math.min(256,r));return y.jsx("div",{className:"cursor-preview-dot",style:{width:i,height:i,backgroundColor:e}})},BHe=()=>{var z;const e=Hr(),{appState:t}=Mi(),{t:n}=jn(),r=x.useRef(null);ES(r,{enablePositionTracking:!0,enableScaleCompensation:!0});const i=va(e),[s,o]=x.useState(i.strokeWidth),[a,l]=x.useState(i.strokeColor),[c,u]=x.useState(i.strokeStyle),[d,f]=x.useState(i.pressureEnabled),[h,m]=x.useState(!1),[g,w]=x.useState(!1),[C,b]=x.useState(String(i.strokeWidth)),[_,T]=x.useState(!1),k=Y5().includes(t.pointer)&&t.pointer!==Jr.eraser;x.useEffect(()=>{const G=va(e);o(G.strokeWidth),l(G.strokeColor),u(G.strokeStyle),f(G.pressureEnabled),b(String(G.strokeWidth))},[e,t.pointer]);const D=x.useCallback(G=>{b(G.target.value)},[]),O=x.useCallback(()=>{const G=parseInt(C,10);!isNaN(G)&&G>=1&&G<=100?(o(G),Sz(e,G),ZT(e,t.pointer)):b(String(s))},[e,C,s,t.pointer]),I=x.useCallback(G=>{G.key==="Enter"?(O(),G.target.blur()):G.key==="Escape"&&(b(String(s)),G.target.blur())},[O,s]),R=x.useCallback(G=>{l(G),Zze(e,G),ZT(e,t.pointer)},[e,t.pointer]),F=x.useCallback(G=>{u(G),Qze(e,G)},[e]),M=x.useCallback(G=>{f(G),eHe(e,G)},[e]);if(!k)return null;const $=Q.getBoardContainer(e),A=((z=e.viewport)==null?void 0:z.zoom)??1;return y.jsxs("div",{className:"pencil-settings-toolbar",onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),children:[_&&y.jsx(RHe,{color:a||ei,size:s,zoom:A}),y.jsx(xr,{ref:r,padding:1,children:y.jsxs(Mr.Row,{gap:0,align:"center",children:[y.jsxs(ti,{sideOffset:12,open:h,onOpenChange:m,placement:"bottom",children:[y.jsx(ni,{asChild:!0,children:y.jsx(jt,{className:"pencil-color-button",type:"button",visible:!0,title:n("toolbar.strokeColor"),"aria-label":n("toolbar.strokeColor"),onPointerUp:()=>m(!h),children:y.jsx("div",{className:"pencil-color-preview",style:{backgroundColor:a||ei}})})}),y.jsx(ri,{container:$,children:y.jsx(xr,{padding:4,className:Le("stroke-setting"),children:y.jsx(th,{value:a,onChange:R})})})]}),y.jsxs("div",{className:"pencil-stroke-style-picker",children:[y.jsx(jt,{className:Le("pencil-stroke-style-button",{active:c===gl.solid}),type:"button",visible:!0,icon:vY,title:"实线","aria-label":"实线",onPointerUp:()=>F(gl.solid)}),y.jsx(jt,{className:Le("pencil-stroke-style-button",{active:c===gl.dashed}),type:"button",visible:!0,icon:yY,title:"虚线","aria-label":"虚线",onPointerUp:()=>F(gl.dashed)}),y.jsx(jt,{className:Le("pencil-stroke-style-button",{active:c===gl.dotted}),type:"button",visible:!0,icon:wY,title:"点线","aria-label":"点线",onPointerUp:()=>F(gl.dotted)}),y.jsx(jt,{className:Le("pencil-stroke-style-button",{active:c===gl.double}),type:"button",visible:!0,icon:N2e,title:"双层线","aria-label":"双层线",onPointerUp:()=>F(gl.double)})]}),y.jsxs(ti,{sideOffset:12,open:g,onOpenChange:w,placement:"bottom",children:[y.jsx(ni,{asChild:!0,children:y.jsx(jt,{className:"pencil-width-button",type:"button",visible:!0,title:n("toolbar.strokeWidth"),"aria-label":n("toolbar.strokeWidth"),onPointerUp:()=>w(!g),children:y.jsxs("svg",{className:"pencil-width-icon",viewBox:"0 0 24 24",children:[y.jsx("line",{x1:"4",y1:"8",x2:"20",y2:"8",strokeWidth:"1",stroke:"currentColor"}),y.jsx("line",{x1:"4",y1:"12",x2:"20",y2:"12",strokeWidth:"2",stroke:"currentColor"}),y.jsx("line",{x1:"4",y1:"16",x2:"20",y2:"16",strokeWidth:"3",stroke:"currentColor"})]})})}),y.jsx(ri,{container:$,children:y.jsx(xr,{padding:4,className:Le("stroke-width-picker"),children:y.jsxs(Mr.Row,{gap:3,align:"center",style:{padding:"4px 8px"},children:[y.jsxs("div",{className:"stroke-width-value",style:{minWidth:"40px",fontSize:"13px",fontWeight:500,color:"var(--color-on-surface)"},children:[s,"px"]}),y.jsx("div",{className:"stroke-width-slider-wrapper",style:{flex:1,minWidth:"160px"},children:y.jsx(aS,{value:s,min:1,max:100,step:1,onChange:G=>{const W=G;o(W),b(String(W)),Sz(e,W),ZT(e,t.pointer)},label:!1})})]})})})]}),y.jsxs("div",{className:"pencil-width-input-wrapper",children:[y.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:C,onChange:D,onBlur:O,onKeyDown:I,className:"pencil-width-input"}),y.jsx("span",{className:"pencil-width-input-unit",children:"px"})]}),y.jsx(Di,{content:"压力感应:支持压感笔;鼠标/触控板使用速度模拟(慢=粗,快=细)",theme:"light",children:y.jsx("div",{className:"pencil-pressure-switch",children:y.jsx(R8e,{size:"small",value:d,onChange:M})})})]})})]})},LHe=({color:e,size:t,zoom:n})=>{const r=t*n,i=Math.max(4,Math.min(256,r));return y.jsx("div",{className:"cursor-preview-dot",style:{width:i,height:i,backgroundColor:e}})},NHe=()=>y.jsxs("svg",{className:"size-picker-icon",viewBox:"0 0 24 24",children:[y.jsx("line",{x1:"4",y1:"8",x2:"20",y2:"8",strokeWidth:"1",stroke:"currentColor"}),y.jsx("line",{x1:"4",y1:"12",x2:"20",y2:"12",strokeWidth:"2",stroke:"currentColor"}),y.jsx("line",{x1:"4",y1:"16",x2:"20",y2:"16",strokeWidth:"3",stroke:"currentColor"})]}),jHe=({size:e,onSizeChange:t,presets:n,previewColor:r,title:i,container:s,icon:o})=>{const{t:a}=jn(),[l,c]=x.useState(!1),[u,d]=x.useState(String(e));J.useEffect(()=>{d(String(e))},[e]);const f=x.useCallback(g=>{d(g.target.value)},[]),h=x.useCallback(()=>{const g=parseInt(u,10);!isNaN(g)&&g>=1?t(g):d(String(e))},[u,e,t]),m=x.useCallback(g=>{g.key==="Enter"?(h(),g.target.blur()):g.key==="Escape"&&(d(String(e)),g.target.blur())},[h,e]);return y.jsxs(y.Fragment,{children:[y.jsxs(ti,{sideOffset:12,open:l,onOpenChange:c,placement:"bottom",children:[y.jsx(ni,{asChild:!0,children:y.jsx(jt,{className:"size-picker-button",type:"button",visible:!0,title:i,"aria-label":i,onPointerUp:()=>c(!l),children:o||y.jsx(NHe,{})})}),y.jsx(ri,{container:s,children:y.jsx(xr,{padding:4,className:Le("size-picker-popover"),children:y.jsxs(Mr.Row,{gap:3,align:"center",style:{padding:"4px 8px"},children:[y.jsxs("div",{className:"size-picker-value",style:{minWidth:"40px",fontSize:"13px",fontWeight:500,color:"var(--color-on-surface)"},children:[e,"px"]}),y.jsx("div",{className:"size-picker-slider-wrapper",style:{flex:1,minWidth:"160px"},children:y.jsx(aS,{value:e,min:1,max:Math.max(256,...n),step:1,onChange:g=>{const w=g;d(String(w)),t(w)},label:!1})})]})})})]}),y.jsxs("div",{className:"size-picker-input-wrapper",children:[y.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:u,onChange:f,onBlur:h,onKeyDown:m,className:"size-picker-input"}),y.jsx("span",{className:"size-picker-input-unit",children:"px"})]})]})},FHe=[16,32,48,64,96,128,192,256],$He="#f5f5f5",zHe=()=>{var h;const e=Hr(),{appState:t}=Mi(),{t:n}=jn(),r=x.useRef(null);ES(r,{enablePositionTracking:!0,enableScaleCompensation:!0});const i=va(e),[s,o]=x.useState(i.eraserWidth),[a,l]=x.useState(!1),c=t.pointer===Jr.eraser;x.useEffect(()=>{const m=va(e);o(m.eraserWidth)},[e,t.pointer]);const u=x.useCallback(m=>{o(m),Jze(e,m),MHe(e)},[e]);if(!c)return null;const d=Q.getBoardContainer(e),f=((h=e.viewport)==null?void 0:h.zoom)??1;return y.jsxs("div",{className:"pencil-settings-toolbar eraser-settings-toolbar",onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[a&&y.jsx(LHe,{color:$He,size:s,zoom:f}),y.jsx(xr,{ref:r,padding:1,children:y.jsx(Mr.Row,{gap:0,align:"center",children:y.jsx(jHe,{size:s,onSizeChange:u,presets:FHe,previewColor:"#999",title:n("toolbar.eraserSize"),container:d})})})]})},HHe=[{icon:z2e,type:"corner",titleKey:"toolbar.anchorCorner"},{icon:H2e,type:"smooth",titleKey:"toolbar.anchorSmooth"},{icon:W2e,type:"symmetric",titleKey:"toolbar.anchorSymmetric"}],WHe=()=>{const e=Hr(),{appState:t}=Mi(),{t:n}=jn(),r=x.useRef(null);ES(r,{enablePositionTracking:!0,enableScaleCompensation:!0});const i=w1(e),[s,o]=x.useState(i.defaultAnchorType),a=t.pointer===Ul.pen&&e.pointer===Ul.pen;x.useEffect(()=>{const c=w1(e);o(c.defaultAnchorType)},[e,t.pointer,e.pointer]);const l=x.useCallback(c=>{o(c),i$e(e,c)},[e]);return a?y.jsx("div",{className:"pen-settings-toolbar",children:y.jsx(xr,{ref:r,padding:1,children:y.jsx(Mr.Row,{gap:0,align:"center",children:y.jsx("div",{className:"pen-anchor-type-picker",children:HHe.map(c=>y.jsx(jt,{className:Le("pen-anchor-type-button",{active:s===c.type}),type:"button",visible:!0,icon:c.icon,title:n(c.titleKey),"aria-label":n(c.titleKey),onPointerUp:()=>l(c.type)},c.type))})})})}):null};function GHe({initialOpen:e=!1,open:t,onOpenChange:n}={}){const[r,i]=x.useState(e),[s,o]=x.useState(),[a,l]=x.useState(),c=t??r,u=n??i,d=Z1({open:c,onOpenChange:u}),f=d.context,h=eZ(f,{enabled:t==null}),m=tZ(f,{outsidePressEvent:"mousedown"}),g=rZ(f),w=nZ([h,m,g]);return x.useMemo(()=>({open:c,setOpen:u,...w,...d,labelId:s,descriptionId:a,setLabelId:o,setDescriptionId:l}),[c,u,w,d,s,a])}const hne=x.createContext(null),fy=()=>{const e=x.useContext(hne);if(e==null)throw new Error("Dialog components must be wrapped in <Dialog />");return e};function VHe({children:e,...t}){const n=GHe(t);return y.jsx(hne.Provider,{value:n,children:e})}x.forwardRef(function({children:t,asChild:n=!1,...r},i){const s=fy(),o=t.ref,a=KE([s.refs.setReference,i,o]);return n&&x.isValidElement(t)?x.cloneElement(t,s.getReferenceProps({ref:a,...r,...t.props,"data-state":s.open?"open":"closed"})):y.jsx("button",{ref:a,"data-state":s.open?"open":"closed",...s.getReferenceProps(r),children:t})});const UHe=x.forwardRef(function(t,n){const{context:r,...i}=fy(),s=KE([i.refs.setFloating,n]);return r.open?y.jsx(ZY,{root:t.container,children:y.jsx(tke,{className:"Dialog-overlay",lockScroll:!0,children:y.jsx(JY,{context:r,children:y.jsx("div",{ref:s,"aria-labelledby":i.labelId,"aria-describedby":i.descriptionId,...i.getFloatingProps(t),children:t.children})})})}):null});x.forwardRef(function({children:t,...n},r){const{setLabelId:i}=fy(),s=Y1();return x.useLayoutEffect(()=>(i(s),()=>i(void 0)),[s,i]),y.jsx("h2",{...n,ref:r,id:s,children:t})});x.forwardRef(function({children:t,...n},r){const{setDescriptionId:i}=fy(),s=Y1();return x.useLayoutEffect(()=>(i(s),()=>i(void 0)),[s,i]),y.jsx("p",{...n,ref:r,id:s,children:t})});x.forwardRef(function(t,n){const{setOpen:r}=fy();return y.jsx("button",{type:"button",...t,ref:n,"data-track":"dialog_click_close",onClick:()=>r(!1)})});const KHe=({container:e})=>{const{appState:t,setAppState:n}=Mi(),{t:r}=jn(),i=Hr();return y.jsx(VHe,{open:t.openCleanConfirm,onOpenChange:s=>{n({...t,openCleanConfirm:s})},children:y.jsxs(UHe,{className:"clean-confirm",container:e,children:[y.jsx("h2",{className:"clean-confirm__title",children:r("cleanConfirm.title")}),y.jsx("p",{className:"clean-confirm__description",children:r("cleanConfirm.description")}),y.jsxs("div",{className:"clean-confirm__actions",children:[y.jsx("button",{className:"clean-confirm__button clean-confirm__button--cancel",onClick:()=>{n({...t,openCleanConfirm:!1})},children:r("cleanConfirm.cancel")}),y.jsx("button",{className:"clean-confirm__button clean-confirm__button--ok",autoFocus:!0,onClick:()=>{i.deleteFragment(i.children),n({...t,openCleanConfirm:!1})},children:r("cleanConfirm.ok")})]})]})})},Pz=e=>{const{appState:t}=e;return t&&t.linkState&&t.linkState.isHovering},Az=e=>{const{appState:t}=e;return t&&t.linkState&&t.linkState.isEditing},qHe=e=>n=>{const{pointerMove:r}=n;let i=null,s=null;return n.pointerMove=o=>{(Q.isPointer(n,fn.selection)||Q.isPointer(n,fn.hand))&&!$l(n)&&!Lc(n)&&!Pz(n)&&!Az(n)&&ca(n,"with-text-link",()=>{const a=o.target.closest(".plait-board-link");if(a&&a!==i){const l=a.closest(".plait-text-container"),c=ut.toSlateNode(void 0,l),u=ut.toSlateNode(void 0,a);i=a,e({linkState:{targetDom:a,targetElement:u,editor:c,isEditing:!1,isHovering:!1,isHoveringOrigin:!0}}),clearTimeout(s)}else!a&&i&&(s=setTimeout(()=>{!Pz(n)&&!Az(n)&&e({linkState:null})},300),i=null)}),r(o)},n},XHe=()=>{var w,C,b,_;const[e,t]=x.useState(""),{appState:n,setAppState:r}=Mi(),i=Hr(),{refs:s,floatingStyles:o}=Z1({placement:"top",middleware:[VE(20),UE()]}),a=n.linkState,l=((w=n.linkState)==null?void 0:w.targetDom)||null,c=((C=n.linkState)==null?void 0:C.isEditing)||!1,u=((b=n.linkState)==null?void 0:b.isHoveringOrigin)||!1,d=((_=n.linkState)==null?void 0:_.isHovering)||!1,f=c||u||d,h=x.useRef(n.linkState);x.useEffect(()=>{h.current=n.linkState,n.linkState?t(n.linkState.targetElement.url):t("")},[n.linkState]),x.useEffect(()=>{if(l){const T=l.getBoundingClientRect();s.setPositionReference({getBoundingClientRect(){return{x:T.x,y:T.y,width:T.width,height:T.height,top:T.y,left:T.x,right:T.x+T.width,bottom:T.y+T.height}}})}},[i.viewport,l,s]);const m=x.useRef();m.current=T=>{if(s.floating.current&&!s.floating.current.contains(T.target)){if(h.current){const S=ad.getLinkElement(h.current.editor);S&&!S[0].url.trim()&&ad.unwrapLink(h.current.editor)}r({...n,linkState:null})}},x.useEffect(()=>{const T=S=>{var k;(k=m.current)==null||k.call(m,S)};return document.addEventListener("mousedown",T),()=>{document.removeEventListener("mousedown",T)}},[]);const g=()=>{if(!a)return;if(e!==a.targetElement.url){const S=a.editor,k=a.targetElement,D=ut.findPath(S,k);Je.setNodes(S,{url:e},{at:D})}const T=ad.getLinkElement(a.editor);T&&r({...n,linkState:{...n.linkState,targetElement:T[0],isEditing:!1,isHoveringOrigin:!0}})};return f&&y.jsx(xr,{ref:s.setFloating,style:o,padding:1,className:Le("link-popup"),onPointerEnter:()=>{!d&&n.linkState&&r({...n,linkState:{...n.linkState,isHovering:!0}})},onPointerLeave:()=>{!c&&n.linkState&&r({...n,linkState:{...n.linkState,isHovering:!1}})},children:y.jsx(Mr.Row,{gap:1,align:"center",children:c?y.jsxs(y.Fragment,{children:[y.jsx("input",{type:"text",value:e,onChange:T=>{t(T.target.value)},onKeyDown:T=>{T.key==="Enter"&&g()},className:"link-popup__input",autoFocus:!0}),y.jsx(jt,{type:"icon",visible:!0,icon:Xb,title:"Delete link","aria-label":"Delete link",onPointerDown:()=>{if(!a)return;const T=a.editor,S=a.targetElement,k=ut.findPath(T,S);Je.unwrapNodes(T,{at:k}),r({...n,linkState:null})}})]}):y.jsxs(y.Fragment,{children:[y.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"link-popup__link",children:e}),y.jsx(jt,{className:"link-popup__edit",type:"icon",visible:!0,icon:xm,title:"Edit link","aria-label":"Edit link",onPointerDown:({event:T})=>{T.preventDefault(),n.linkState&&r({...n,linkState:{...n.linkState,isEditing:!0}})}}),y.jsx(jt,{type:"icon",visible:!0,icon:Xb,title:"Delete link","aria-label":"Delete link",onPointerDown:()=>{if(!a)return;const T=a.editor,S=a.targetElement,k=ut.findPath(T,S);Je.unwrapNodes(T,{at:k}),r({...n,linkState:null})}})]})})})},W0={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 YHe(){return"0.5.21"}function Dz(e){return{...W0,...e,retryPolicy:{...W0.retryPolicy,...e.retryPolicy||{}},cacheConfig:{...W0.cacheConfig,...e.cacheConfig||{}},batchConfig:{...W0.batchConfig,...e.batchConfig||{}}}}class ZHe{isAvailable(){return qt.isAnalyticsEnabled()}async track(t){if(!this.isAvailable())throw new Error("PostHog SDK not loaded");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{qt.track(t.eventName,n)}catch(r){throw console.error("[Tracking] PostHog track failed:",r),r}}async trackBatch(t){const n=[];for(const r of t)try{await this.track(r),n.push({success:!0})}catch(i){n.push({success:!1,error:i})}return n}getSDKInfo(){return{available:this.isAvailable(),version:this.isAvailable()?"PostHog JS":void 0}}}const Iz=new ZHe;class QHe{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 Iz.trackBatch(t),r=n.filter(i=>!i.success);if(r.length>0){console.error(`Batch upload: ${r.length}/${t.length} events failed`);const i=t.filter((s,o)=>!n[o].success);this.requeueFailedEvents(i)}}catch(n){console.error("Batch upload failed:",n),this.requeueFailedEvents(t)}finally{this.uploading=!1}}async uploadImmediate(t){try{await Iz.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 JHe{constructor(t=500){this.debounceMap=new WeakMap,this.globalDebounceMap=new Map,this.globalDebounceTime=200,this.debounceTime=t}shouldTrack(t,n,r=!1){const i=Date.now(),s=this.globalDebounceMap.get(n);if(s&&i-s<this.globalDebounceTime)return r&&console.warn(`[Tracking] 🚫 Global debounce: ${n} (${i-s}ms ago)`),!1;const o=this.debounceMap.get(t);if(!o){const l=new Map;return l.set(n,i),this.debounceMap.set(t,l),this.globalDebounceMap.set(n,i),!0}const a=o.get(n);return!a||i-a>this.debounceTime?(o.set(n,i),this.globalDebounceMap.set(n,i),!0):(r&&console.warn(`[Tracking] 🚫 Element debounce: ${n} (${i-a}ms ago)`),!1)}clear(t){this.debounceMap.delete(t)}setDebounceTime(t){this.debounceTime=t}}const eWe=["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 tWe(e,t){if(!e.matches(eWe))return!1;for(const r of t)if(e.matches(r)||e.closest(r))return!1;return e.hasAttribute("data-track-ignore")?!1:(e.onclick!==null,!0)}function nWe(e,t="click"){var a;const n=`auto_${t}_`;if(e.id)return`${n}${e.id}`;const r=e.getAttribute("aria-label");if(r)return`${n}${Oz(r)}`;const i=(a=e.textContent)==null?void 0:a.trim();if(i&&i.length>0){const l=Oz(i.substring(0,20));return`${n}${l}`}const s=e.tagName.toLowerCase(),o=e.className?`.${e.className.split(" ")[0]}`:"";return`${n}${s}${o}`}function Oz(e){return e.toLowerCase().trim().replace(/\s+/g,"_").replace(/[^a-z0-9_-]/g,"").substring(0,50)}function rWe(e){if(e.id)return`#${e.id}`;const t=[];let n=e;for(;n&&n!==document.body;){let r=n.tagName.toLowerCase();if(n.className){const i=n.className.split(" ").filter(Boolean);i.length>0&&(r+=`.${i[0]}`)}t.unshift(r),n=n.parentElement}return t.join(" > ")}function QT(e){const t=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 pne(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function iWe(){if(typeof window>"u")return"server-side";const e="tracking_session_id";let t=sessionStorage.getItem(e);return t||(t=pne(),sessionStorage.setItem(e,t)),t}function sWe(){return typeof window>"u"?{width:0,height:0}:{width:window.innerWidth||0,height:window.innerHeight||0}}class oWe{constructor(t={}){this.state$=new PD({initialized:!1,config:W0,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=Dz(t),this.batchService=new QHe(this.config.batchConfig),this.debouncer=new JHe(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 r=n.closest("[data-track]");if(r){const i=r.getAttribute("data-track");if(i){if(this.isElementExcluded(r))return;this.trackClick(r,i);return}}if(this.config.autoTrack&&tWe(n,this.config.excludedSelectors)){if(this.isElementExcluded(n))return;const i=nWe(n,"click");this.trackClick(n,i)}},document.body.addEventListener("click",this.clickListener,!0))}setupMultiEventListeners(){if(typeof document>"u")return;document.querySelectorAll("[track-hover]").forEach(r=>{this.attachHoverListener(r)}),document.querySelectorAll("[track-focus]").forEach(r=>{this.attachFocusListener(r)})}attachHoverListener(t){const n=t.getAttribute("track-hover");if(!n||this.hasAttachedListener(t,"hover"))return;const r=()=>{if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents");return}const i=QT(t),s=this.createTrackEvent(n,i,"hover",t);this.track(s)};t.addEventListener("mouseenter",r),this.markListenerAttached(t,"hover")}attachFocusListener(t){const n=t.getAttribute("track-focus");if(!n||this.hasAttachedListener(t,"focus"))return;const r=()=>{if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents");return}const i=QT(t),s=this.createTrackEvent(n,i,"focus",t);this.track(s)};t.addEventListener("focus",r,!0),this.markListenerAttached(t,"focus")}hasAttachedListener(t,n){const r=this.attachedListeners.get(t);return r?r.has(n):!1}markListenerAttached(t,n){let r=this.attachedListeners.get(t);r||(r=new Set,this.attachedListeners.set(t,r)),r.add(n)}setupMutationObserver(){typeof window>"u"||typeof MutationObserver>"u"||(this.mutationObserver=new MutationObserver(t=>{t.forEach(n=>{n.addedNodes.forEach(r=>{if(r.nodeType===Node.ELEMENT_NODE){const i=r;i.hasAttribute("track-hover")&&this.attachHoverListener(i),i.hasAttribute("track-focus")&&this.attachFocusListener(i),i.querySelectorAll("[track-hover]").forEach(a=>this.attachHoverListener(a)),i.querySelectorAll("[track-focus]").forEach(a=>this.attachFocusListener(a))}})})}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}))}trackClick(t,n){if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents"),this.log("debug",`Event debounced: ${n}`);return}const r=QT(t),i=this.createTrackEvent(n,r,"click",t);this.track(i)}createTrackEvent(t,n,r,i){const s={timestamp:Date.now(),url:typeof window<"u"?window.location.href:"",version:YHe(),sessionId:iWe(),userAgent:typeof navigator<"u"?navigator.userAgent:void 0,viewport:sWe(),eventType:r},o={eventName:t,params:n||void 0,metadata:s,id:pne(),createdAt:Date.now()};return this.config.devMode&&this.log("debug",`Event created: ${t}`,{params:n,element:i?rWe(i):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=Dz({...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,r){this.config.logLevel!=="silent"&&(t==="error"||t==="debug"&&this.config.devMode)}}let Ac=null;function aWe(){Ac&&(Ac.destroy(),Ac=null)}function lWe(e,t){return Ac||(Ac=new oWe(t),typeof window<"u"&&setTimeout(()=>{Ac==null||Ac.initialize()},0),typeof module<"u"&&module.hot&&module.hot.dispose(()=>{aWe()})),e.trackingService=Ac,e}function cWe(e,t,n,r=0){const i=X.getCenterPoint(t),s=sm(t,Gi);if(r){const o=uWe(n,i,-r);let a=s.find(l=>X.isHit(X.getRectangleByPoints([o,o]),l.rectangle));return a&&(a.cursorClass=eE(a.cursorClass,r)),a}else return s.find(o=>X.isHit(X.getRectangleByPoints([n,n]),o.rectangle))}function uWe(e,t,n){const r=n*Math.PI/180,i=Math.cos(r),s=Math.sin(r),o=e[0]-t[0],a=e[1]-t[1];return[t[0]+o*i-a*s,t[1]+o*s+a*i]}function dWe(e){const t=nt(e);return t.length!==1?!1:js(t[0])}function fWe(e,t){const n=nt(e);if(n.length!==1||!js(n[0]))return null;const r=n[0],i=X.getRectangleByPoints(r.points),s=r.angle||0,o=cWe(e,i,t,s);return o?{element:r,rectangle:i,handle:o.handle,cursorClass:o.cursorClass}:null}function hWe(e,t,n){const{element:r,rectangle:i,handle:s}=t,{startPoint:o,endPoint:a}=n;if(!i){console.warn("startRectangle is undefined");return}const l=a[0]-o[0],c=a[1]-o[1],u=_S(i,s,l,c,SS(),100),d=[[u.x,u.y],[u.x+u.width,u.y+u.height]],f=e.children.findIndex(h=>h.id===r.id);f>=0&&Ke.setNode(e,{points:d},[f])}const pWe=e=>qa(e,{key:"tool-elements",canResize:()=>dWe(e),hitTest:t=>fWe(e,t),onResize:(t,n)=>hWe(e,t,n)});let EC=null;function gWe(e,t){return ir.isFreehand(t)?ly(t):lr.isPenPath(t)?uy(t):e.getRectangle(t)}function mWe(e,t){return sm(e,Gi).find(r=>X.isHit(X.getRectangleByPoints([t,t]),r.rectangle))}function I3(e){return e.some(t=>ir.isFreehand(t)||lr.isPenPath(t))}function gne(e){const t=nt(e);if(t.length<2||!I3(t))return null;try{const n=Et(e,t,!1);return{elements:t,rectangle:n}}catch{return null}}function vWe(e){return gne(e)!==null}function yWe(e,t){const n=gne(e);if(!n)return null;const r=mWe(n.rectangle,t);if(r){EC=new Map;for(const i of n.elements){const s=gWe(e,i);s&&EC.set(i.id,{element:JSON.parse(JSON.stringify(i)),rectangle:{...s}})}return{element:n.elements,rectangle:n.rectangle,handle:r.handle,cursorClass:r.cursorClass}}return null}function wWe(e,t,n,r,i,s){const o=s.width/i.width,a=s.height/i.height,l=r.x-i.x,c=r.y-i.y,u=s.x+l*o,d=s.y+c*a,f=n.points.map(m=>{const g=m[0]-r.x,w=m[1]-r.y,C=g*o,b=w*a;return[u+C,d+b]}),h=e.children.findIndex(m=>m.id===t);h>=0&&Ke.setNode(e,{points:f},[h])}function xWe(e,t,n,r,i,s){const o=s.width/i.width,a=s.height/i.height,l=r.x-i.x,c=r.y-i.y,u=s.x+l*o,d=s.y+c*a,f=n.anchors.map(b=>({...b,point:[b.point[0]*o,b.point[1]*a],handleIn:b.handleIn?[b.handleIn[0]*o,b.handleIn[1]*a]:void 0,handleOut:b.handleOut?[b.handleOut[0]*o,b.handleOut[1]*a]:void 0})),h=r.width*o,m=r.height*a,w=[[u,d],[u+h,d+m]],C=e.children.findIndex(b=>b.id===t);C>=0&&Ke.setNode(e,{points:w,anchors:f},[C])}function bWe(e,t,n,r,i,s){const o=s.width/i.width,a=s.height/i.height,l=r.x-i.x,c=r.y-i.y,u=s.x+l*o,d=s.y+c*a,f=r.width*o,h=r.height*a,m=[[u,d],[u+f,d+h]],g=e.children.findIndex(w=>w.id===t);g>=0&&(be.isDrawElement(n)&&be.isImage(n)?Ke.setNode(e,{points:m,width:f,height:h},[g]):Ke.setNode(e,{points:m},[g]))}function CWe(e,t,n){const{element:r,rectangle:i,handle:s}=t,{startPoint:o,endPoint:a}=n;if(!i||!Array.isArray(r)||!EC)return;const l=a[0]-o[0],c=a[1]-o[1],u=_S(i,s,l,c,SS());for(const d of r){const f=EC.get(d.id);if(!f)continue;const{element:h,rectangle:m}=f;ir.isFreehand(h)?wWe(e,d.id,h,m,i,u):lr.isPenPath(h)?xWe(e,d.id,h,m,i,u):bWe(e,d.id,h,m,i,u)}}function EWe(e){const t=nt(e);if(t.length<2||!I3(t))return null;try{const n=Jt(),r=Et(e,t,!1),i=Wi(e,r);return X.getCornerPoints(i).forEach(o=>{const a=gI(e,o);n.append(a)}),n}catch{return null}}const SWe=e=>{const{afterChange:t}=e;let n=null;return e.afterChange=()=>{t(),n&&(n.remove(),n=null);const r=nt(e);r.length>1&&I3(r)&&!ui(e)&&(n=EWe(e),n&&Q.getActiveHost(e).append(n))},qa(e,{key:"multi-resize",canResize:()=>vWe(e),hitTest:r=>yWe(e,r),onResize:(r,i)=>CWe(e,r,i)})};function _We(e){return e.some(n=>ir.isFreehand(n)||lr.isPenPath(n))}function TWe(e){const t=nt(e);if(t.length<2||!_We(t))return null;try{return Et(e,t,!1)}catch{return null}}const kWe=()=>{const e=Hr(),[t,n]=x.useState([]),[r,i]=x.useState(!1),[s,o]=x.useState(!1),a=x.useRef(!1),l=x.useCallback(()=>{const d=Fl(e)||$l(e)||ui(e);if(o(d),d)return;nt(e);const f=TWe(e);if(!f){i(!1);return}const m=[{x:f.x,y:f.y,cursor:"nwse-resize"},{x:f.x+f.width,y:f.y,cursor:"nesw-resize"},{x:f.x+f.width,y:f.y+f.height,cursor:"nwse-resize"},{x:f.x,y:f.y+f.height,cursor:"nesw-resize"}].map(g=>{const w=vf(e,[g.x,g.y]);return{x:w[0],y:w[1],cursor:g.cursor}});n(m),i(!0)},[e]);if(x.useEffect(()=>{a.current=s},[s]),x.useEffect(()=>{l();let d,f=JSON.stringify(e.viewport),h=JSON.stringify(e.selection),m=e.children.length;const g=()=>{const w=JSON.stringify(e.viewport),C=JSON.stringify(e.selection),b=e.children.length,_=Fl(e)||$l(e)||ui(e);(w!==f||C!==h||b!==m||_!==a.current)&&(f=w,h=C,m=b,l()),d=requestAnimationFrame(g)};return d=requestAnimationFrame(g),()=>{cancelAnimationFrame(d)}},[e,l]),!r||t.length===0||s)return null;const c=Gi,u=c/2;return y.jsx("div",{className:Le("multi-selection-handles",vi),children:t.map((d,f)=>y.jsx("div",{className:"multi-selection-handle",style:{left:d.x-u,top:d.y-u,width:c,height:c,cursor:d.cursor}},f))})},PWe=()=>null;class AWe{constructor(){this.initialized=!1,this.store=pi.createInstance({driver:pi.INDEXEDDB,name:FT.DATABASE_NAME,version:FT.DATABASE_VERSION,storeName:FT.TASKS_STORE_NAME,description:"Task queue persistent storage"})}async initialize(){if(!this.initialized)try{await this.store.ready(),this.initialized=!0}catch(t){throw console.error("[StorageService] Failed to initialize:",t),new Error("Storage initialization failed")}}async saveTask(t){try{await this.ensureInitialized(),await this.store.setItem(t.id,t)}catch(n){throw console.error("[StorageService] Failed to save task:",n),new Error("Failed to save task to storage")}}async saveTasks(t){try{await this.ensureInitialized(),await Promise.all(t.map(n=>this.saveTask(n)))}catch(n){throw console.error("[StorageService] Failed to save tasks:",n),new Error("Failed to save tasks to storage")}}async loadTask(t){try{return await this.ensureInitialized(),await this.store.getItem(t)}catch(n){return console.error(`[StorageService] Failed to load task ${t}:`,n),null}}async loadTasks(){try{await this.ensureInitialized();const t=[];return await this.store.iterate(n=>{n&&typeof n=="object"&&"id"in n&&t.push(n)}),await new Promise(n=>{typeof window<"u"&&"requestIdleCallback"in window?window.requestIdleCallback(()=>n(),{timeout:50}):setTimeout(n,0)}),t}catch(t){return console.error("[StorageService] Failed to load tasks:",t),[]}}async deleteTask(t){try{await this.ensureInitialized(),await this.store.removeItem(t)}catch(n){throw console.error(`[StorageService] Failed to delete task ${t}:`,n),new Error("Failed to delete task from storage")}}async getStorageSize(){try{await this.ensureInitialized();const t=await this.loadTasks(),n=JSON.stringify(t);return new Blob([n]).size}catch(t){return console.error("[StorageService] Failed to get storage size:",t),0}}async isStorageNearLimit(){return await this.getStorageSize()>=A9.WARNING_THRESHOLD}async pruneOldTasks(){try{await this.ensureInitialized();const t=await this.loadTasks();t.sort((i,s)=>s.createdAt-i.createdAt);const n=t.slice(A9.MAX_RETAINED_TASKS);await Promise.all(n.map(i=>this.deleteTask(i.id)));const r=t.length-n.length}catch(t){throw console.error("[StorageService] Failed to prune old tasks:",t),new Error("Failed to prune old tasks")}}async clearAll(){try{await this.ensureInitialized(),await this.store.clear()}catch(t){throw console.error("[StorageService] Failed to clear storage:",t),new Error("Failed to clear storage")}}async ensureInitialized(){this.initialized||await this.initialize()}}const Ku=new AWe;function DWe(e){const t=e.imageUrl.toLowerCase(),n=t.includes(".png")?"png":t.includes(".jpg")||t.includes(".jpeg")?"jpg":t.includes(".webp")?"webp":"png";return{id:e.id,type:Ft.IMAGE,status:ht.COMPLETED,params:{prompt:e.prompt,width:e.width,height:e.height},result:{url:e.imageUrl,format:n,size:0,width:e.width,height:e.height},createdAt:e.timestamp,updatedAt:e.timestamp,completedAt:e.timestamp}}function IWe(e){const t=e.previewUrl.toLowerCase(),n=t.includes(".mp4")?"mp4":t.includes(".webm")?"webm":t.includes(".mov")?"mov":"mp4";return{id:e.id,type:Ft.VIDEO,status:ht.COMPLETED,params:{prompt:e.prompt,width:e.width,height:e.height},result:{url:e.previewUrl,format:n,size:0,width:e.width,height:e.height,thumbnailUrl:e.imageUrl},createdAt:e.timestamp,updatedAt:e.timestamp,completedAt:e.timestamp}}async function OWe(){try{const e=localStorage.getItem(N9);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t)||t.length===0)return[];const n=t.map(DWe);return await Ku.saveTasks(n),localStorage.removeItem(N9),n}catch(e){return console.error("[HistoryMigration] Failed to migrate image history:",e),[]}}async function MWe(){try{const e=localStorage.getItem(j9);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t)||t.length===0)return[];const n=t.map(IWe);return await Ku.saveTasks(n),localStorage.removeItem(j9),n}catch(e){return console.error("[HistoryMigration] Failed to migrate video history:",e),[]}}async function RWe(){try{const e=await OWe(),t=await MWe();e.length+t.length>0}catch(e){console.error("[HistoryMigration] Migration failed:",e)}}let JT=!1;function ek(e=100){return new Promise(t=>{"requestIdleCallback"in window?window.requestIdleCallback(()=>t(),{timeout:e}):setTimeout(t,0)})}function BWe(){x.useEffect(()=>{let e=!0;const t=xu(),n=async()=>{if(!JT){JT=!0,await ek(50);try{if(await Ku.initialize(),await ek(50),await RWe(),t){const{swTaskQueueService:o}=await ln(async()=>{const{swTaskQueueService:l}=await Promise.resolve().then(()=>g3);return{swTaskQueueService:l}},void 0,import.meta.url);await o.initialize(),await ek(50);const a=await Ku.loadTasks();if(a.length>0){await o.restoreTasks(a);for(const l of a)await Ku.deleteTask(l.id)}await o.syncTasksFromSW();return}const s=await Ku.loadTasks();if(s.length>0&&e){bn.restoreTasks(s);const o=s.filter(u=>u.status==="processing");o.length>0&&o.forEach(u=>{if(!(u.type===Ft.VIDEO&&u.remoteId)){let d="任务被中断(页面刷新)",f="INTERRUPTED";u.type===Ft.VIDEO&&u.executionPhase===ah.SUBMITTING&&(d="任务在提交过程中被中断,可能已在后台执行",f="INTERRUPTED_DURING_SUBMISSION"),vr.updateTaskStatus(u.id,ht.FAILED,{startedAt:void 0,executionPhase:void 0,error:{code:f,message:d,details:{originalError:`Task interrupted by page refresh before completion (phase: ${u.executionPhase||"unknown"})`,timestamp:Date.now()}}})}});const a=s.filter(u=>u.type===Ft.VIDEO&&u.status==="failed"&&u.remoteId);if(a.length>0){const u=d=>{var C,b,_,T;const f=((C=d.error)==null?void 0:C.message)||"",h=((_=(b=d.error)==null?void 0:b.details)==null?void 0:_.originalError)||"",m=((T=d.error)==null?void 0:T.code)||"",g=`${f} ${h}`.toLowerCase();return g.includes("generation_failed")||g.includes("invalid_argument")||g.includes("prohibited")||g.includes("content policy")||g.includes("视频生成失败")||m.includes("generation_failed")||m.includes("INVALID")?!1:g.includes("failed to fetch")||g.includes("network")||g.includes("fetch")||g.includes("timeout")||g.includes("aborted")||g.includes("connection")||g.includes("status query failed")};a.forEach(d=>{u(d)&&(console.log(`[useTaskStorage] Recovering failed video task ${d.id} (network error, has remoteId: ${d.remoteId})`),vr.updateTaskStatus(d.id,ht.PROCESSING,{error:void 0,executionPhase:ah.POLLING}))})}const l=s.filter(u=>u.status==="pending"),c=o.filter(u=>u.type===Ft.VIDEO&&u.remoteId);if(l.length>0||c.length>0){const u=l.length+c.length}}}catch(s){JT=!1,console.error("[useTaskStorage] Failed to initialize storage:",s)}}},r=KSe(async s=>{try{await Ku.saveTask(s)}catch(o){console.error("[useTaskStorage] Failed to save task:",o)}},ENe.STORAGE_SYNC),i=bn.observeTaskUpdates().subscribe(s=>{e&&(s.type==="taskDeleted"?Ku.deleteTask(s.task.id).catch(o=>{console.error("[useTaskStorage] Failed to delete task from storage:",o)}):r(s.task))});return n(),()=>{e=!1,i.unsubscribe()}},[])}class LWe{constructor(){this.abortControllers=new Map}async generate(t,n,r){const i=new AbortController;this.abortControllers.set(t,i);const s=Date.now(),o=r===Ft.IMAGE?"image":"video";qt.trackModelCall({taskId:t,taskType:o,model:o==="image"?"gemini-image":"gemini-video",promptLength:n.prompt.length,hasUploadedImage:!!n.uploadedImage||!!n.uploadedImages,startTime:s});try{const a=vC[r.toUpperCase()],l=new Promise((f,h)=>{setTimeout(()=>{h(new Error("TIMEOUT"))},a)}),c=r===Ft.IMAGE?this.generateImage(n,i.signal):this.generateVideo(t,n,i.signal),u=await Promise.race([c,l]),d=Date.now()-s;return qt.trackModelSuccess({taskId:t,taskType:o,model:o==="image"?"gemini-image":"gemini-video",duration:d,resultSize:u.size}),u}catch(a){const l=Date.now()-s;throw console.error(`[GenerationAPI] Generation failed for task ${t}:`,a),a.message==="TIMEOUT"?(qt.trackModelFailure({taskId:t,taskType:o,model:o==="image"?"gemini-image":"gemini-video",duration:l,error:"TIMEOUT"}),new Error(`${r===Ft.IMAGE?"图片":"视频"}生成超时`)):a.name==="AbortError"?(qt.trackTaskCancellation({taskId:t,taskType:o,duration:l}),new Error("任务已取消")):(qt.trackModelFailure({taskId:t,taskType:o,model:o==="image"?"gemini-image":"gemini-video",duration:l,error:a.message||"UNKNOWN_ERROR"}),a)}finally{this.abortControllers.delete(t)}}convertAspectRatioToSize(t){return!t||t==="auto"?void 0:{"1:1":"1x1","2:3":"2x3","3:2":"3x2","3:4":"3x4","4:3":"4x3","4:5":"4x5","5:4":"5x4","9:16":"9x16","16:9":"16x9","21:9":"21x9"}[t]}async generateImage(t,n){try{let r=t.size;if(!r){const u=t.aspectRatio;r=this.convertAspectRatioToSize(u)}let i;if(t.uploadedImages){const u=t.uploadedImages,d=[];for(const f of u)if(f.type==="url"&&f.url){const h=await Mn.getImageForAI(f.url);d.push(h.value)}d.length>0&&(i=d)}const s=t.quality,o=await du.generateImage(t.prompt,{size:r,image:i&&i.length>0?i:void 0,response_format:"url",quality:s,model:t.model}),a=u=>{const d=`Generate an image: ${t.prompt}: `;if(u.startsWith(d))return u.substring(d.length);const f="Generate an image: ";if(u.startsWith(f)){const h=u.substring(f.length),m=h.indexOf(": ");if(m!==-1)return h.substring(m+2)}return u};if(o.data&&Array.isArray(o.data)&&o.data.length>0){const u=o.data[0];let d;if(u.url)d=u.url;else if(u.b64_json)d=`data:image/png;base64,${u.b64_json}`;else{const f=u.revised_prompt||"";if(f.includes("PROHIBITED_CONTENT")||f.includes("has been blocked")){const g=f.match(/your request has been blocked[^:]*:\s*([^.]+)/i);if(g)throw new Error(g[0]);const w=f.toLowerCase().lastIndexOf("blocked");if(w!==-1){const C=f.slice(w-20);throw new Error(C.trim())}}let h;u.revised_prompt?h=a(u.revised_prompt):h=JSON.stringify(u);const m=new Error(`API 未返回有效的图片数据: ${h}`);throw m.fullResponse=h,m}return{url:d,format:"png",size:0}}let l;o.revised_prompt?l=a(o.revised_prompt):l=JSON.stringify(o);const c=new Error(`API 未返回有效的图片数据: ${l}`);throw c.fullResponse=l,c}catch(r){console.error("[GenerationAPI] Image generation error:",r);const i=new Error(r.message||"图片生成失败");throw r.apiErrorBody&&(i.apiErrorBody=r.apiErrorBody),r.httpStatus&&(i.httpStatus=r.httpStatus),r.fullResponse&&(i.fullResponse=r.fullResponse),i}}async generateVideo(t,n,r){try{vr.updateTaskStatus(t,"processing",{executionPhase:ah.SUBMITTING});let i,s;if(n.uploadedImages&&n.uploadedImages.length>0)i=n.uploadedImages;else if(n.uploadedImage){const f=n.uploadedImage;f.type==="url"&&f.url&&(s=f.url)}const o=An.get(),a=n.model||o.videoModelName||"veo3";let l;n.seconds?l=n.seconds:n.duration?l=n.duration.toString():a.startsWith("sora")?l="10":l="8";let c;n.size?c=n.size:n.width&&n.height?c=`${n.width}x${n.height}`:c="1280x720";const u=await RA.generateVideoWithPolling({model:a,prompt:n.prompt,seconds:l,size:c,inputReferences:i,inputReference:s},{interval:5e3,onProgress:(f,h)=>{vr.updateTaskProgress(t,f)},onSubmitted:f=>{vr.updateTaskStatus(t,"processing",{remoteId:f,executionPhase:ah.POLLING})}}),d=u.video_url||u.url;if(!d)throw new Error("API 未返回有效的视频 URL");return{url:d,format:"mp4",size:0,duration:parseInt(u.seconds)||n.duration||8}}catch(i){console.error("[GenerationAPI] Video generation error:",i);const s=new Error(i.message||"视频生成失败");throw i.apiErrorBody&&(s.apiErrorBody=i.apiErrorBody),i.httpStatus&&(s.httpStatus=i.httpStatus),s}}async resumeVideoGeneration(t,n){const r=Date.now();qt.trackModelCall({taskId:t,taskType:"video",model:"gemini-video",promptLength:0,hasUploadedImage:!1,startTime:r});try{const i=vC.VIDEO,s=new Promise((u,d)=>{setTimeout(()=>{d(new Error("TIMEOUT"))},i)}),o=RA.resumePolling(n,{interval:5e3,onProgress:(u,d)=>{vr.updateTaskProgress(t,u)}}),a=await Promise.race([o,s]),l=Date.now()-r;qt.trackModelSuccess({taskId:t,taskType:"video",model:"gemini-video",duration:l,resultSize:0});const c=a.video_url||a.url;if(!c)throw new Error("API 未返回有效的视频 URL");return{url:c,format:"mp4",size:0,duration:parseInt(a.seconds)||8}}catch(i){const s=Date.now()-r;throw console.error(`[GenerationAPI] Resumed video generation failed for task ${t}:`,i),qt.trackModelFailure({taskId:t,taskType:"video",model:"gemini-video",duration:s,error:i.message||"UNKNOWN_ERROR"}),i}}cancelRequest(t){const n=this.abortControllers.get(t);n&&(n.abort(),this.abortControllers.delete(t))}hasActiveRequest(t){return this.abortControllers.has(t)}}const mx=new LWe,NWe=xu()?cy:vr;function jWe(e){var t;if(!e)return null;try{const n=JSON.parse(e);if((t=n.error)!=null&&t.message)return n.error.message;if(n.message)return n.message;if(n.error&&typeof n.error=="string")return n.error;if(n.detail)return n.detail;if(n.msg)return n.msg}catch{return e}return null}function tk(e){const t=(e==null?void 0:e.message)||String(e),n=(e==null?void 0:e.apiErrorBody)||"",r=e==null?void 0:e.httpStatus,i=jWe(n),s=`${t} ${n}`;return s.includes("insufficient_user_quota")||s.includes("预扣费额度失败")?"账户额度不足,请充值后重试":t.includes("PROHIBITED_CONTENT")||t.includes("has been blocked by Google Gemini")?t:t.includes("cannot")||t.includes("I cannot")||t.includes("I can't")?"AI 拒绝生成此内容":t.includes("unable to")||t.includes("not able to")?"AI 无法处理此请求":t.includes("signal")&&t.includes("timed out")?"请求超时,服务器响应过慢,正在自动重试":t.includes("TIMEOUT")||t.includes("超时")?"生成超时,请稍后重试":t.includes("network")||t.includes("Network")||t.includes("fetch")||t.includes("Failed to fetch")?"网络连接失败,请检查网络后重试":t.includes("rate limit")||t.includes("429")||r===429?"请求过于频繁,请稍后重试":t.includes("401")||r===401?"API 认证失败,请检查 API Key 配置":(t.includes("403")||r===403)&&!n.includes("quota")?"API 访问被拒绝,请检查配置":t.includes("500")||r===500?i?`AI 服务器内部错误: ${i}`:"AI 服务器内部错误,正在自动重试":t.includes("502")||r===502?i?`AI 服务暂时不可用: ${i}`:"AI 服务暂时不可用(502),正在自动重试":t.includes("503")||r===503?i?`AI 服务繁忙: ${i}`:"AI 服务繁忙(503),正在自动重试":t.includes("504")||r===504?i?`AI 服务响应超时: ${i}`:"AI 服务响应超时(504),正在自动重试":i||t}function FWe(){const e=x.useRef(new Set),t=x.useRef(null),n=xu();x.useEffect(()=>{let r=!0;if(n){const u=NWe.observeTaskUpdates().subscribe(async d=>{var f;if(r&&d.type==="taskUpdated"&&d.task.status===ht.COMPLETED){const h=d.task;if((f=h.result)!=null&&f.url)try{await Mn.registerImageMetadata(h.result.url,{taskId:h.id,model:h.params.model,prompt:h.params.prompt,params:h.params})}catch(m){console.error(`[TaskExecutor] Failed to register metadata for task ${h.id}:`,m)}if(h.type===Ft.CHARACTER&&h.result)try{await Rs.saveCharacter({id:h.remoteId||h.id,username:h.result.characterUsername||"",profilePictureUrl:h.result.characterProfileUrl||h.result.url,permalink:h.result.characterPermalink||"",sourceTaskId:h.params.sourceLocalTaskId||"",sourceVideoId:h.params.sourceVideoTaskId||"",sourcePrompt:h.params.prompt,characterTimestamps:h.params.characterTimestamps,status:"completed",createdAt:h.createdAt,completedAt:Date.now()})}catch(m){console.error(`[TaskExecutor] Failed to save character for task ${h.id}:`,m)}}});return()=>{r=!1,u.unsubscribe()}}const i=async u=>{const d=u.id,f=u.remoteId;if(!e.current.has(d)){e.current.add(d);try{const h=await mx.resumeVideoGeneration(d,f);if(!r)return;if(vr.updateTaskStatus(d,ht.COMPLETED,{result:h}),h.url)try{await Mn.registerImageMetadata(h.url,{taskId:u.id,model:u.params.model,prompt:u.params.prompt,params:u.params})}catch(m){console.error(`[TaskExecutor] Failed to register metadata for resumed task ${d}:`,m)}}catch(h){if(!r||(console.error(`[TaskExecutor] Resumed task ${d} failed:`,h),!vr.getTask(d)))return;const g=h.httpStatus?`HTTP_${h.httpStatus}`:h.name||"ERROR",w=tk(h),b={originalError:h.fullResponse||h.apiErrorBody||h.message||String(h),timestamp:Date.now()};vr.updateTaskStatus(d,ht.FAILED,{error:{code:g,message:w,details:b}})}finally{e.current.delete(d)}}},s=async u=>{const d=u.id;if(!e.current.has(d)){e.current.add(d);try{vr.updateTaskStatus(d,ht.PROCESSING);const{sourceVideoTaskId:f,characterTimestamps:h,model:m,prompt:g}=u.params;if(!f)throw new Error("缺少源视频任务ID");const w=await rb.createCharacterWithPolling({videoTaskId:f,characterTimestamps:h,localTaskId:u.params.sourceLocalTaskId,sourcePrompt:g,sourceModel:m},{onStatusChange:C=>{}});if(!r)return;await Rs.saveCharacter({id:w.characterId,username:w.username,profilePictureUrl:w.profile_picture_url,permalink:w.permalink,sourceTaskId:u.params.sourceLocalTaskId||"",sourceVideoId:f,sourcePrompt:g,characterTimestamps:h,status:"completed",createdAt:u.createdAt,completedAt:Date.now()}),vr.updateTaskStatus(d,ht.COMPLETED,{result:{url:w.profile_picture_url,format:"character",size:0,characterUsername:w.username,characterProfileUrl:w.profile_picture_url,characterPermalink:w.permalink},remoteId:w.characterId})}catch(f){if(!r||(console.error(`[TaskExecutor] Character task ${d} failed:`,f),!vr.getTask(d)))return;const m=f.httpStatus?`HTTP_${f.httpStatus}`:f.name||"ERROR",g=tk(f),C={originalError:f.fullResponse||f.apiErrorBody||f.message||String(f),timestamp:Date.now()};vr.updateTaskStatus(d,ht.FAILED,{error:{code:m,message:g,details:C}})}finally{e.current.delete(d)}}},o=async u=>{const d=u.id;if(u.type===Ft.CHARACTER)return s(u);if(u.type===Ft.VIDEO&&u.remoteId&&u.status===ht.PROCESSING)return i(u);if(!e.current.has(d)){e.current.add(d);try{vr.updateTaskStatus(d,ht.PROCESSING);const f=await mx.generate(d,u.params,u.type);if(!r)return;if(vr.updateTaskStatus(d,ht.COMPLETED,{result:f}),f.url)try{await Mn.registerImageMetadata(f.url,{taskId:u.id,model:u.params.model,prompt:u.params.prompt,params:u.params})}catch(h){console.error(`[TaskExecutor] Failed to register metadata for task ${d}:`,h)}}catch(f){if(!r||(console.error(`[TaskExecutor] Task ${d} failed:`,f),!vr.getTask(d)))return;const m=f.httpStatus?`HTTP_${f.httpStatus}`:f.name||"ERROR",g=tk(f),C={originalError:f.fullResponse||f.apiErrorBody||f.message||String(f),timestamp:Date.now()};vr.updateTaskStatus(d,ht.FAILED,{error:{code:m,message:g,details:C}})}finally{e.current.delete(d)}}},a=()=>{if(!r)return;const u=vr.getAllTasks();u.filter(h=>h.status===ht.PENDING).forEach(h=>{o(h)}),u.filter(h=>h.type===Ft.VIDEO&&h.status===ht.PROCESSING&&h.remoteId).forEach(h=>{o(h)})},l=()=>{if(!r)return;vr.getAllTasks().filter(f=>f.status===ht.PROCESSING).forEach(f=>{if(SNe(f)){console.warn(`[TaskExecutor] Task ${f.id} timed out`),mx.cancelRequest(f.id);const h={originalError:`Task ${f.id} timed out after processing`,timestamp:Date.now()};vr.updateTaskStatus(f.id,ht.FAILED,{error:{code:"TIMEOUT",message:"任务执行超时",details:h}})}})},c=vr.observeTaskUpdates().subscribe(u=>{if(r&&(u.type==="taskCreated"||u.type==="taskUpdated")){const d=u.task;(d.status===ht.PENDING||d.type===Ft.VIDEO&&d.status===ht.PROCESSING&&d.remoteId&&!e.current.has(d.id))&&o(d)}});return a(),t.current=setInterval(l,1e4),()=>{r=!1,c.unsubscribe(),t.current&&clearInterval(t.current),e.current.forEach(u=>{mx.cancelRequest(u)}),e.current.clear()}},[])}class $We{constructor(){this.postProcessingResults=new Map,this.batchTasks=new Map,this.taskToBatch=new Map,this.completionEvents$=new Ks,this.batchCompletionEvents$=new Ks,this.isProcessing$=new PD(!1)}registerTask(t,n){n&&(this.taskToBatch.set(t,n),this.batchTasks.has(n)||this.batchTasks.set(n,new Set),this.batchTasks.get(n).add(t)),this.postProcessingResults.set(t,{taskId:t,status:"pending",type:"direct_insert"})}startPostProcessing(t,n){const r={taskId:t,status:"processing",type:n};this.postProcessingResults.set(t,r),this.isProcessing$.next(!0),this.completionEvents$.next({taskId:t,batchId:this.taskToBatch.get(t),type:"postProcessingStarted",result:r,timestamp:Date.now()})}completePostProcessing(t,n,r){const i=this.postProcessingResults.get(t),s={taskId:t,status:"completed",type:(i==null?void 0:i.type)||"direct_insert",insertedCount:n,firstElementPosition:r,completedAt:Date.now()};this.postProcessingResults.set(t,s),this.completionEvents$.next({taskId:t,batchId:this.taskToBatch.get(t),type:"postProcessingCompleted",result:s,timestamp:Date.now()}),this.checkBatchCompletion(t),this.updateProcessingStatus()}failPostProcessing(t,n){const r=this.postProcessingResults.get(t),i={taskId:t,status:"failed",type:(r==null?void 0:r.type)||"direct_insert",error:n,completedAt:Date.now()};this.postProcessingResults.set(t,i),this.completionEvents$.next({taskId:t,batchId:this.taskToBatch.get(t),type:"postProcessingFailed",result:i,timestamp:Date.now()}),this.checkBatchCompletion(t),this.updateProcessingStatus()}checkBatchCompletion(t){var c;const n=this.taskToBatch.get(t);if(!n)return;const r=this.batchTasks.get(n);if(!r)return;const i=[];for(const u of r){const d=this.postProcessingResults.get(u);if(!d||d.status!=="completed"&&d.status!=="failed")return;i.push(d)}const s=i.every(u=>u.status==="completed"),o=i.reduce((u,d)=>u+(d.insertedCount||0),0),a=(c=i.find(u=>u.firstElementPosition))==null?void 0:c.firstElementPosition,l={batchId:n,results:i,allSuccess:s,totalInsertedCount:o,firstElementPosition:a,timestamp:Date.now()};this.batchCompletionEvents$.next(l)}updateProcessingStatus(){const t=Array.from(this.postProcessingResults.values()).some(n=>n.status==="processing");this.isProcessing$.next(t)}getPostProcessingStatus(t){return this.postProcessingResults.get(t)}isPostProcessingCompleted(t){const n=this.postProcessingResults.get(t);return(n==null?void 0:n.status)==="completed"||(n==null?void 0:n.status)==="failed"}observeCompletionEvents(){return this.completionEvents$.asObservable()}observeBatchCompletionEvents(){return this.batchCompletionEvents$.asObservable()}observeProcessingStatus(){return this.isProcessing$.asObservable()}clearTask(t){const n=this.taskToBatch.get(t);if(n){const r=this.batchTasks.get(n);r&&(r.delete(t),r.size===0&&this.batchTasks.delete(n)),this.taskToBatch.delete(t)}this.postProcessingResults.delete(t)}clear(){this.postProcessingResults.clear(),this.batchTasks.clear(),this.taskToBatch.clear(),this.isProcessing$.next(!1)}}const ps=new $We,mne=8,zWe="veo3.1";function HWe(e,t){return`你是一个专业的视频脚本编剧。用户会给你一个视频主题,你需要将其拆分为 ${e} 个连续的视频片段脚本。
2002
+ </svg>`;return`url('data:image/svg+xml;base64,${btoa(o)}') ${i} ${i}, crosshair`}function dne(e){return Y5().includes(e)&&e!==Jr.eraser}function fne(e){return e===Jr.eraser}function xv(e,t){var o;const n=document.querySelector(".plait-board-container"),r=n==null?void 0:n.querySelector(".board-host-svg");if(!r)return;const i=va(e),s=((o=e.viewport)==null?void 0:o.zoom)||1;if(dne(t)){const a=i.strokeWidth*s,l=kz(i.strokeColor,a);r.style.cursor=l}else if(fne(t)){const a=i.eraserWidth*s,l=kz(IHe,a);r.style.cursor=l}else r.style.cursor=""}function OHe({board:e,pointer:t}){const n=x.useRef(1),r=x.useRef(null);return x.useEffect(()=>{var o;if(!e)return;xv(e,t),n.current=((o=e.viewport)==null?void 0:o.zoom)||1;let s=null;return(dne(t)||fne(t))&&(s=setInterval(()=>{var l;const a=((l=e.viewport)==null?void 0:l.zoom)||1;Math.abs(a-n.current)>.01&&(n.current=a,xv(e,t))},100)),()=>{s&&clearInterval(s),r.current&&cancelAnimationFrame(r.current);const a=document.querySelector(".plait-board-container"),l=a==null?void 0:a.querySelector(".board-host-svg");l&&(l.style.cursor="")}},[e,t]),{updateCursor:x.useCallback(()=>{e&&xv(e,t)},[e,t])}}function ZT(e,t){xv(e,t)}function MHe(e){xv(e,Jr.eraser)}const RHe=({color:e,size:t,zoom:n})=>{const r=t*n,i=Math.max(4,Math.min(256,r));return y.jsx("div",{className:"cursor-preview-dot",style:{width:i,height:i,backgroundColor:e}})},BHe=()=>{var z;const e=Hr(),{appState:t}=Mi(),{t:n}=jn(),r=x.useRef(null);ES(r,{enablePositionTracking:!0,enableScaleCompensation:!0});const i=va(e),[s,o]=x.useState(i.strokeWidth),[a,l]=x.useState(i.strokeColor),[c,u]=x.useState(i.strokeStyle),[d,f]=x.useState(i.pressureEnabled),[h,m]=x.useState(!1),[g,w]=x.useState(!1),[C,b]=x.useState(String(i.strokeWidth)),[_,T]=x.useState(!1),k=Y5().includes(t.pointer)&&t.pointer!==Jr.eraser;x.useEffect(()=>{const G=va(e);o(G.strokeWidth),l(G.strokeColor),u(G.strokeStyle),f(G.pressureEnabled),b(String(G.strokeWidth))},[e,t.pointer]);const D=x.useCallback(G=>{b(G.target.value)},[]),O=x.useCallback(()=>{const G=parseInt(C,10);!isNaN(G)&&G>=1&&G<=100?(o(G),Sz(e,G),ZT(e,t.pointer)):b(String(s))},[e,C,s,t.pointer]),I=x.useCallback(G=>{G.key==="Enter"?(O(),G.target.blur()):G.key==="Escape"&&(b(String(s)),G.target.blur())},[O,s]),R=x.useCallback(G=>{l(G),Zze(e,G),ZT(e,t.pointer)},[e,t.pointer]),F=x.useCallback(G=>{u(G),Qze(e,G)},[e]),M=x.useCallback(G=>{f(G),eHe(e,G)},[e]);if(!k)return null;const $=Q.getBoardContainer(e),A=((z=e.viewport)==null?void 0:z.zoom)??1;return y.jsxs("div",{className:"pencil-settings-toolbar",onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),children:[_&&y.jsx(RHe,{color:a||ei,size:s,zoom:A}),y.jsx(xr,{ref:r,padding:1,children:y.jsxs(Mr.Row,{gap:0,align:"center",children:[y.jsxs(ti,{sideOffset:12,open:h,onOpenChange:m,placement:"bottom",children:[y.jsx(ni,{asChild:!0,children:y.jsx(jt,{className:"pencil-color-button",type:"button",visible:!0,title:n("toolbar.strokeColor"),"aria-label":n("toolbar.strokeColor"),onPointerUp:()=>m(!h),children:y.jsx("div",{className:"pencil-color-preview",style:{backgroundColor:a||ei}})})}),y.jsx(ri,{container:$,children:y.jsx(xr,{padding:4,className:Le("stroke-setting"),children:y.jsx(th,{value:a,onChange:R})})})]}),y.jsxs("div",{className:"pencil-stroke-style-picker",children:[y.jsx(jt,{className:Le("pencil-stroke-style-button",{active:c===gl.solid}),type:"button",visible:!0,icon:vY,title:"实线","aria-label":"实线",onPointerUp:()=>F(gl.solid)}),y.jsx(jt,{className:Le("pencil-stroke-style-button",{active:c===gl.dashed}),type:"button",visible:!0,icon:yY,title:"虚线","aria-label":"虚线",onPointerUp:()=>F(gl.dashed)}),y.jsx(jt,{className:Le("pencil-stroke-style-button",{active:c===gl.dotted}),type:"button",visible:!0,icon:wY,title:"点线","aria-label":"点线",onPointerUp:()=>F(gl.dotted)}),y.jsx(jt,{className:Le("pencil-stroke-style-button",{active:c===gl.double}),type:"button",visible:!0,icon:N2e,title:"双层线","aria-label":"双层线",onPointerUp:()=>F(gl.double)})]}),y.jsxs(ti,{sideOffset:12,open:g,onOpenChange:w,placement:"bottom",children:[y.jsx(ni,{asChild:!0,children:y.jsx(jt,{className:"pencil-width-button",type:"button",visible:!0,title:n("toolbar.strokeWidth"),"aria-label":n("toolbar.strokeWidth"),onPointerUp:()=>w(!g),children:y.jsxs("svg",{className:"pencil-width-icon",viewBox:"0 0 24 24",children:[y.jsx("line",{x1:"4",y1:"8",x2:"20",y2:"8",strokeWidth:"1",stroke:"currentColor"}),y.jsx("line",{x1:"4",y1:"12",x2:"20",y2:"12",strokeWidth:"2",stroke:"currentColor"}),y.jsx("line",{x1:"4",y1:"16",x2:"20",y2:"16",strokeWidth:"3",stroke:"currentColor"})]})})}),y.jsx(ri,{container:$,children:y.jsx(xr,{padding:4,className:Le("stroke-width-picker"),children:y.jsxs(Mr.Row,{gap:3,align:"center",style:{padding:"4px 8px"},children:[y.jsxs("div",{className:"stroke-width-value",style:{minWidth:"40px",fontSize:"13px",fontWeight:500,color:"var(--color-on-surface)"},children:[s,"px"]}),y.jsx("div",{className:"stroke-width-slider-wrapper",style:{flex:1,minWidth:"160px"},children:y.jsx(aS,{value:s,min:1,max:100,step:1,onChange:G=>{const W=G;o(W),b(String(W)),Sz(e,W),ZT(e,t.pointer)},label:!1})})]})})})]}),y.jsxs("div",{className:"pencil-width-input-wrapper",children:[y.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:C,onChange:D,onBlur:O,onKeyDown:I,className:"pencil-width-input"}),y.jsx("span",{className:"pencil-width-input-unit",children:"px"})]}),y.jsx(Di,{content:"压力感应:支持压感笔;鼠标/触控板使用速度模拟(慢=粗,快=细)",theme:"light",children:y.jsx("div",{className:"pencil-pressure-switch",children:y.jsx(R8e,{size:"small",value:d,onChange:M})})})]})})]})},LHe=({color:e,size:t,zoom:n})=>{const r=t*n,i=Math.max(4,Math.min(256,r));return y.jsx("div",{className:"cursor-preview-dot",style:{width:i,height:i,backgroundColor:e}})},NHe=()=>y.jsxs("svg",{className:"size-picker-icon",viewBox:"0 0 24 24",children:[y.jsx("line",{x1:"4",y1:"8",x2:"20",y2:"8",strokeWidth:"1",stroke:"currentColor"}),y.jsx("line",{x1:"4",y1:"12",x2:"20",y2:"12",strokeWidth:"2",stroke:"currentColor"}),y.jsx("line",{x1:"4",y1:"16",x2:"20",y2:"16",strokeWidth:"3",stroke:"currentColor"})]}),jHe=({size:e,onSizeChange:t,presets:n,previewColor:r,title:i,container:s,icon:o})=>{const{t:a}=jn(),[l,c]=x.useState(!1),[u,d]=x.useState(String(e));J.useEffect(()=>{d(String(e))},[e]);const f=x.useCallback(g=>{d(g.target.value)},[]),h=x.useCallback(()=>{const g=parseInt(u,10);!isNaN(g)&&g>=1?t(g):d(String(e))},[u,e,t]),m=x.useCallback(g=>{g.key==="Enter"?(h(),g.target.blur()):g.key==="Escape"&&(d(String(e)),g.target.blur())},[h,e]);return y.jsxs(y.Fragment,{children:[y.jsxs(ti,{sideOffset:12,open:l,onOpenChange:c,placement:"bottom",children:[y.jsx(ni,{asChild:!0,children:y.jsx(jt,{className:"size-picker-button",type:"button",visible:!0,title:i,"aria-label":i,onPointerUp:()=>c(!l),children:o||y.jsx(NHe,{})})}),y.jsx(ri,{container:s,children:y.jsx(xr,{padding:4,className:Le("size-picker-popover"),children:y.jsxs(Mr.Row,{gap:3,align:"center",style:{padding:"4px 8px"},children:[y.jsxs("div",{className:"size-picker-value",style:{minWidth:"40px",fontSize:"13px",fontWeight:500,color:"var(--color-on-surface)"},children:[e,"px"]}),y.jsx("div",{className:"size-picker-slider-wrapper",style:{flex:1,minWidth:"160px"},children:y.jsx(aS,{value:e,min:1,max:Math.max(256,...n),step:1,onChange:g=>{const w=g;d(String(w)),t(w)},label:!1})})]})})})]}),y.jsxs("div",{className:"size-picker-input-wrapper",children:[y.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",value:u,onChange:f,onBlur:h,onKeyDown:m,className:"size-picker-input"}),y.jsx("span",{className:"size-picker-input-unit",children:"px"})]})]})},FHe=[16,32,48,64,96,128,192,256],$He="#f5f5f5",zHe=()=>{var h;const e=Hr(),{appState:t}=Mi(),{t:n}=jn(),r=x.useRef(null);ES(r,{enablePositionTracking:!0,enableScaleCompensation:!0});const i=va(e),[s,o]=x.useState(i.eraserWidth),[a,l]=x.useState(!1),c=t.pointer===Jr.eraser;x.useEffect(()=>{const m=va(e);o(m.eraserWidth)},[e,t.pointer]);const u=x.useCallback(m=>{o(m),Jze(e,m),MHe(e)},[e]);if(!c)return null;const d=Q.getBoardContainer(e),f=((h=e.viewport)==null?void 0:h.zoom)??1;return y.jsxs("div",{className:"pencil-settings-toolbar eraser-settings-toolbar",onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[a&&y.jsx(LHe,{color:$He,size:s,zoom:f}),y.jsx(xr,{ref:r,padding:1,children:y.jsx(Mr.Row,{gap:0,align:"center",children:y.jsx(jHe,{size:s,onSizeChange:u,presets:FHe,previewColor:"#999",title:n("toolbar.eraserSize"),container:d})})})]})},HHe=[{icon:z2e,type:"corner",titleKey:"toolbar.anchorCorner"},{icon:H2e,type:"smooth",titleKey:"toolbar.anchorSmooth"},{icon:W2e,type:"symmetric",titleKey:"toolbar.anchorSymmetric"}],WHe=()=>{const e=Hr(),{appState:t}=Mi(),{t:n}=jn(),r=x.useRef(null);ES(r,{enablePositionTracking:!0,enableScaleCompensation:!0});const i=w1(e),[s,o]=x.useState(i.defaultAnchorType),a=t.pointer===Ul.pen&&e.pointer===Ul.pen;x.useEffect(()=>{const c=w1(e);o(c.defaultAnchorType)},[e,t.pointer,e.pointer]);const l=x.useCallback(c=>{o(c),i$e(e,c)},[e]);return a?y.jsx("div",{className:"pen-settings-toolbar",children:y.jsx(xr,{ref:r,padding:1,children:y.jsx(Mr.Row,{gap:0,align:"center",children:y.jsx("div",{className:"pen-anchor-type-picker",children:HHe.map(c=>y.jsx(jt,{className:Le("pen-anchor-type-button",{active:s===c.type}),type:"button",visible:!0,icon:c.icon,title:n(c.titleKey),"aria-label":n(c.titleKey),onPointerUp:()=>l(c.type)},c.type))})})})}):null};function GHe({initialOpen:e=!1,open:t,onOpenChange:n}={}){const[r,i]=x.useState(e),[s,o]=x.useState(),[a,l]=x.useState(),c=t??r,u=n??i,d=Z1({open:c,onOpenChange:u}),f=d.context,h=eZ(f,{enabled:t==null}),m=tZ(f,{outsidePressEvent:"mousedown"}),g=rZ(f),w=nZ([h,m,g]);return x.useMemo(()=>({open:c,setOpen:u,...w,...d,labelId:s,descriptionId:a,setLabelId:o,setDescriptionId:l}),[c,u,w,d,s,a])}const hne=x.createContext(null),fy=()=>{const e=x.useContext(hne);if(e==null)throw new Error("Dialog components must be wrapped in <Dialog />");return e};function VHe({children:e,...t}){const n=GHe(t);return y.jsx(hne.Provider,{value:n,children:e})}x.forwardRef(function({children:t,asChild:n=!1,...r},i){const s=fy(),o=t.ref,a=KE([s.refs.setReference,i,o]);return n&&x.isValidElement(t)?x.cloneElement(t,s.getReferenceProps({ref:a,...r,...t.props,"data-state":s.open?"open":"closed"})):y.jsx("button",{ref:a,"data-state":s.open?"open":"closed",...s.getReferenceProps(r),children:t})});const UHe=x.forwardRef(function(t,n){const{context:r,...i}=fy(),s=KE([i.refs.setFloating,n]);return r.open?y.jsx(ZY,{root:t.container,children:y.jsx(tke,{className:"Dialog-overlay",lockScroll:!0,children:y.jsx(JY,{context:r,children:y.jsx("div",{ref:s,"aria-labelledby":i.labelId,"aria-describedby":i.descriptionId,...i.getFloatingProps(t),children:t.children})})})}):null});x.forwardRef(function({children:t,...n},r){const{setLabelId:i}=fy(),s=Y1();return x.useLayoutEffect(()=>(i(s),()=>i(void 0)),[s,i]),y.jsx("h2",{...n,ref:r,id:s,children:t})});x.forwardRef(function({children:t,...n},r){const{setDescriptionId:i}=fy(),s=Y1();return x.useLayoutEffect(()=>(i(s),()=>i(void 0)),[s,i]),y.jsx("p",{...n,ref:r,id:s,children:t})});x.forwardRef(function(t,n){const{setOpen:r}=fy();return y.jsx("button",{type:"button",...t,ref:n,"data-track":"dialog_click_close",onClick:()=>r(!1)})});const KHe=({container:e})=>{const{appState:t,setAppState:n}=Mi(),{t:r}=jn(),i=Hr();return y.jsx(VHe,{open:t.openCleanConfirm,onOpenChange:s=>{n({...t,openCleanConfirm:s})},children:y.jsxs(UHe,{className:"clean-confirm",container:e,children:[y.jsx("h2",{className:"clean-confirm__title",children:r("cleanConfirm.title")}),y.jsx("p",{className:"clean-confirm__description",children:r("cleanConfirm.description")}),y.jsxs("div",{className:"clean-confirm__actions",children:[y.jsx("button",{className:"clean-confirm__button clean-confirm__button--cancel",onClick:()=>{n({...t,openCleanConfirm:!1})},children:r("cleanConfirm.cancel")}),y.jsx("button",{className:"clean-confirm__button clean-confirm__button--ok",autoFocus:!0,onClick:()=>{i.deleteFragment(i.children),n({...t,openCleanConfirm:!1})},children:r("cleanConfirm.ok")})]})]})})},Pz=e=>{const{appState:t}=e;return t&&t.linkState&&t.linkState.isHovering},Az=e=>{const{appState:t}=e;return t&&t.linkState&&t.linkState.isEditing},qHe=e=>n=>{const{pointerMove:r}=n;let i=null,s=null;return n.pointerMove=o=>{(Q.isPointer(n,fn.selection)||Q.isPointer(n,fn.hand))&&!$l(n)&&!Lc(n)&&!Pz(n)&&!Az(n)&&ca(n,"with-text-link",()=>{const a=o.target.closest(".plait-board-link");if(a&&a!==i){const l=a.closest(".plait-text-container"),c=ut.toSlateNode(void 0,l),u=ut.toSlateNode(void 0,a);i=a,e({linkState:{targetDom:a,targetElement:u,editor:c,isEditing:!1,isHovering:!1,isHoveringOrigin:!0}}),clearTimeout(s)}else!a&&i&&(s=setTimeout(()=>{!Pz(n)&&!Az(n)&&e({linkState:null})},300),i=null)}),r(o)},n},XHe=()=>{var w,C,b,_;const[e,t]=x.useState(""),{appState:n,setAppState:r}=Mi(),i=Hr(),{refs:s,floatingStyles:o}=Z1({placement:"top",middleware:[VE(20),UE()]}),a=n.linkState,l=((w=n.linkState)==null?void 0:w.targetDom)||null,c=((C=n.linkState)==null?void 0:C.isEditing)||!1,u=((b=n.linkState)==null?void 0:b.isHoveringOrigin)||!1,d=((_=n.linkState)==null?void 0:_.isHovering)||!1,f=c||u||d,h=x.useRef(n.linkState);x.useEffect(()=>{h.current=n.linkState,n.linkState?t(n.linkState.targetElement.url):t("")},[n.linkState]),x.useEffect(()=>{if(l){const T=l.getBoundingClientRect();s.setPositionReference({getBoundingClientRect(){return{x:T.x,y:T.y,width:T.width,height:T.height,top:T.y,left:T.x,right:T.x+T.width,bottom:T.y+T.height}}})}},[i.viewport,l,s]);const m=x.useRef();m.current=T=>{if(s.floating.current&&!s.floating.current.contains(T.target)){if(h.current){const S=ad.getLinkElement(h.current.editor);S&&!S[0].url.trim()&&ad.unwrapLink(h.current.editor)}r({...n,linkState:null})}},x.useEffect(()=>{const T=S=>{var k;(k=m.current)==null||k.call(m,S)};return document.addEventListener("mousedown",T),()=>{document.removeEventListener("mousedown",T)}},[]);const g=()=>{if(!a)return;if(e!==a.targetElement.url){const S=a.editor,k=a.targetElement,D=ut.findPath(S,k);Je.setNodes(S,{url:e},{at:D})}const T=ad.getLinkElement(a.editor);T&&r({...n,linkState:{...n.linkState,targetElement:T[0],isEditing:!1,isHoveringOrigin:!0}})};return f&&y.jsx(xr,{ref:s.setFloating,style:o,padding:1,className:Le("link-popup"),onPointerEnter:()=>{!d&&n.linkState&&r({...n,linkState:{...n.linkState,isHovering:!0}})},onPointerLeave:()=>{!c&&n.linkState&&r({...n,linkState:{...n.linkState,isHovering:!1}})},children:y.jsx(Mr.Row,{gap:1,align:"center",children:c?y.jsxs(y.Fragment,{children:[y.jsx("input",{type:"text",value:e,onChange:T=>{t(T.target.value)},onKeyDown:T=>{T.key==="Enter"&&g()},className:"link-popup__input",autoFocus:!0}),y.jsx(jt,{type:"icon",visible:!0,icon:Xb,title:"Delete link","aria-label":"Delete link",onPointerDown:()=>{if(!a)return;const T=a.editor,S=a.targetElement,k=ut.findPath(T,S);Je.unwrapNodes(T,{at:k}),r({...n,linkState:null})}})]}):y.jsxs(y.Fragment,{children:[y.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"link-popup__link",children:e}),y.jsx(jt,{className:"link-popup__edit",type:"icon",visible:!0,icon:xm,title:"Edit link","aria-label":"Edit link",onPointerDown:({event:T})=>{T.preventDefault(),n.linkState&&r({...n,linkState:{...n.linkState,isEditing:!0}})}}),y.jsx(jt,{type:"icon",visible:!0,icon:Xb,title:"Delete link","aria-label":"Delete link",onPointerDown:()=>{if(!a)return;const T=a.editor,S=a.targetElement,k=ut.findPath(T,S);Je.unwrapNodes(T,{at:k}),r({...n,linkState:null})}})]})})})},W0={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 YHe(){return"0.5.22"}function Dz(e){return{...W0,...e,retryPolicy:{...W0.retryPolicy,...e.retryPolicy||{}},cacheConfig:{...W0.cacheConfig,...e.cacheConfig||{}},batchConfig:{...W0.batchConfig,...e.batchConfig||{}}}}class ZHe{isAvailable(){return qt.isAnalyticsEnabled()}async track(t){if(!this.isAvailable())throw new Error("PostHog SDK not loaded");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{qt.track(t.eventName,n)}catch(r){throw console.error("[Tracking] PostHog track failed:",r),r}}async trackBatch(t){const n=[];for(const r of t)try{await this.track(r),n.push({success:!0})}catch(i){n.push({success:!1,error:i})}return n}getSDKInfo(){return{available:this.isAvailable(),version:this.isAvailable()?"PostHog JS":void 0}}}const Iz=new ZHe;class QHe{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 Iz.trackBatch(t),r=n.filter(i=>!i.success);if(r.length>0){console.error(`Batch upload: ${r.length}/${t.length} events failed`);const i=t.filter((s,o)=>!n[o].success);this.requeueFailedEvents(i)}}catch(n){console.error("Batch upload failed:",n),this.requeueFailedEvents(t)}finally{this.uploading=!1}}async uploadImmediate(t){try{await Iz.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 JHe{constructor(t=500){this.debounceMap=new WeakMap,this.globalDebounceMap=new Map,this.globalDebounceTime=200,this.debounceTime=t}shouldTrack(t,n,r=!1){const i=Date.now(),s=this.globalDebounceMap.get(n);if(s&&i-s<this.globalDebounceTime)return r&&console.warn(`[Tracking] 🚫 Global debounce: ${n} (${i-s}ms ago)`),!1;const o=this.debounceMap.get(t);if(!o){const l=new Map;return l.set(n,i),this.debounceMap.set(t,l),this.globalDebounceMap.set(n,i),!0}const a=o.get(n);return!a||i-a>this.debounceTime?(o.set(n,i),this.globalDebounceMap.set(n,i),!0):(r&&console.warn(`[Tracking] 🚫 Element debounce: ${n} (${i-a}ms ago)`),!1)}clear(t){this.debounceMap.delete(t)}setDebounceTime(t){this.debounceTime=t}}const eWe=["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 tWe(e,t){if(!e.matches(eWe))return!1;for(const r of t)if(e.matches(r)||e.closest(r))return!1;return e.hasAttribute("data-track-ignore")?!1:(e.onclick!==null,!0)}function nWe(e,t="click"){var a;const n=`auto_${t}_`;if(e.id)return`${n}${e.id}`;const r=e.getAttribute("aria-label");if(r)return`${n}${Oz(r)}`;const i=(a=e.textContent)==null?void 0:a.trim();if(i&&i.length>0){const l=Oz(i.substring(0,20));return`${n}${l}`}const s=e.tagName.toLowerCase(),o=e.className?`.${e.className.split(" ")[0]}`:"";return`${n}${s}${o}`}function Oz(e){return e.toLowerCase().trim().replace(/\s+/g,"_").replace(/[^a-z0-9_-]/g,"").substring(0,50)}function rWe(e){if(e.id)return`#${e.id}`;const t=[];let n=e;for(;n&&n!==document.body;){let r=n.tagName.toLowerCase();if(n.className){const i=n.className.split(" ").filter(Boolean);i.length>0&&(r+=`.${i[0]}`)}t.unshift(r),n=n.parentElement}return t.join(" > ")}function QT(e){const t=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 pne(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function iWe(){if(typeof window>"u")return"server-side";const e="tracking_session_id";let t=sessionStorage.getItem(e);return t||(t=pne(),sessionStorage.setItem(e,t)),t}function sWe(){return typeof window>"u"?{width:0,height:0}:{width:window.innerWidth||0,height:window.innerHeight||0}}class oWe{constructor(t={}){this.state$=new PD({initialized:!1,config:W0,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=Dz(t),this.batchService=new QHe(this.config.batchConfig),this.debouncer=new JHe(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 r=n.closest("[data-track]");if(r){const i=r.getAttribute("data-track");if(i){if(this.isElementExcluded(r))return;this.trackClick(r,i);return}}if(this.config.autoTrack&&tWe(n,this.config.excludedSelectors)){if(this.isElementExcluded(n))return;const i=nWe(n,"click");this.trackClick(n,i)}},document.body.addEventListener("click",this.clickListener,!0))}setupMultiEventListeners(){if(typeof document>"u")return;document.querySelectorAll("[track-hover]").forEach(r=>{this.attachHoverListener(r)}),document.querySelectorAll("[track-focus]").forEach(r=>{this.attachFocusListener(r)})}attachHoverListener(t){const n=t.getAttribute("track-hover");if(!n||this.hasAttachedListener(t,"hover"))return;const r=()=>{if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents");return}const i=QT(t),s=this.createTrackEvent(n,i,"hover",t);this.track(s)};t.addEventListener("mouseenter",r),this.markListenerAttached(t,"hover")}attachFocusListener(t){const n=t.getAttribute("track-focus");if(!n||this.hasAttachedListener(t,"focus"))return;const r=()=>{if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents");return}const i=QT(t),s=this.createTrackEvent(n,i,"focus",t);this.track(s)};t.addEventListener("focus",r,!0),this.markListenerAttached(t,"focus")}hasAttachedListener(t,n){const r=this.attachedListeners.get(t);return r?r.has(n):!1}markListenerAttached(t,n){let r=this.attachedListeners.get(t);r||(r=new Set,this.attachedListeners.set(t,r)),r.add(n)}setupMutationObserver(){typeof window>"u"||typeof MutationObserver>"u"||(this.mutationObserver=new MutationObserver(t=>{t.forEach(n=>{n.addedNodes.forEach(r=>{if(r.nodeType===Node.ELEMENT_NODE){const i=r;i.hasAttribute("track-hover")&&this.attachHoverListener(i),i.hasAttribute("track-focus")&&this.attachFocusListener(i),i.querySelectorAll("[track-hover]").forEach(a=>this.attachHoverListener(a)),i.querySelectorAll("[track-focus]").forEach(a=>this.attachFocusListener(a))}})})}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}))}trackClick(t,n){if(!this.debouncer.shouldTrack(t,n,this.config.devMode)){this.incrementStat("debouncedEvents"),this.log("debug",`Event debounced: ${n}`);return}const r=QT(t),i=this.createTrackEvent(n,r,"click",t);this.track(i)}createTrackEvent(t,n,r,i){const s={timestamp:Date.now(),url:typeof window<"u"?window.location.href:"",version:YHe(),sessionId:iWe(),userAgent:typeof navigator<"u"?navigator.userAgent:void 0,viewport:sWe(),eventType:r},o={eventName:t,params:n||void 0,metadata:s,id:pne(),createdAt:Date.now()};return this.config.devMode&&this.log("debug",`Event created: ${t}`,{params:n,element:i?rWe(i):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=Dz({...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,r){this.config.logLevel!=="silent"&&(t==="error"||t==="debug"&&this.config.devMode)}}let Ac=null;function aWe(){Ac&&(Ac.destroy(),Ac=null)}function lWe(e,t){return Ac||(Ac=new oWe(t),typeof window<"u"&&setTimeout(()=>{Ac==null||Ac.initialize()},0),typeof module<"u"&&module.hot&&module.hot.dispose(()=>{aWe()})),e.trackingService=Ac,e}function cWe(e,t,n,r=0){const i=X.getCenterPoint(t),s=sm(t,Gi);if(r){const o=uWe(n,i,-r);let a=s.find(l=>X.isHit(X.getRectangleByPoints([o,o]),l.rectangle));return a&&(a.cursorClass=eE(a.cursorClass,r)),a}else return s.find(o=>X.isHit(X.getRectangleByPoints([n,n]),o.rectangle))}function uWe(e,t,n){const r=n*Math.PI/180,i=Math.cos(r),s=Math.sin(r),o=e[0]-t[0],a=e[1]-t[1];return[t[0]+o*i-a*s,t[1]+o*s+a*i]}function dWe(e){const t=nt(e);return t.length!==1?!1:js(t[0])}function fWe(e,t){const n=nt(e);if(n.length!==1||!js(n[0]))return null;const r=n[0],i=X.getRectangleByPoints(r.points),s=r.angle||0,o=cWe(e,i,t,s);return o?{element:r,rectangle:i,handle:o.handle,cursorClass:o.cursorClass}:null}function hWe(e,t,n){const{element:r,rectangle:i,handle:s}=t,{startPoint:o,endPoint:a}=n;if(!i){console.warn("startRectangle is undefined");return}const l=a[0]-o[0],c=a[1]-o[1],u=_S(i,s,l,c,SS(),100),d=[[u.x,u.y],[u.x+u.width,u.y+u.height]],f=e.children.findIndex(h=>h.id===r.id);f>=0&&Ke.setNode(e,{points:d},[f])}const pWe=e=>qa(e,{key:"tool-elements",canResize:()=>dWe(e),hitTest:t=>fWe(e,t),onResize:(t,n)=>hWe(e,t,n)});let EC=null;function gWe(e,t){return ir.isFreehand(t)?ly(t):lr.isPenPath(t)?uy(t):e.getRectangle(t)}function mWe(e,t){return sm(e,Gi).find(r=>X.isHit(X.getRectangleByPoints([t,t]),r.rectangle))}function I3(e){return e.some(t=>ir.isFreehand(t)||lr.isPenPath(t))}function gne(e){const t=nt(e);if(t.length<2||!I3(t))return null;try{const n=Et(e,t,!1);return{elements:t,rectangle:n}}catch{return null}}function vWe(e){return gne(e)!==null}function yWe(e,t){const n=gne(e);if(!n)return null;const r=mWe(n.rectangle,t);if(r){EC=new Map;for(const i of n.elements){const s=gWe(e,i);s&&EC.set(i.id,{element:JSON.parse(JSON.stringify(i)),rectangle:{...s}})}return{element:n.elements,rectangle:n.rectangle,handle:r.handle,cursorClass:r.cursorClass}}return null}function wWe(e,t,n,r,i,s){const o=s.width/i.width,a=s.height/i.height,l=r.x-i.x,c=r.y-i.y,u=s.x+l*o,d=s.y+c*a,f=n.points.map(m=>{const g=m[0]-r.x,w=m[1]-r.y,C=g*o,b=w*a;return[u+C,d+b]}),h=e.children.findIndex(m=>m.id===t);h>=0&&Ke.setNode(e,{points:f},[h])}function xWe(e,t,n,r,i,s){const o=s.width/i.width,a=s.height/i.height,l=r.x-i.x,c=r.y-i.y,u=s.x+l*o,d=s.y+c*a,f=n.anchors.map(b=>({...b,point:[b.point[0]*o,b.point[1]*a],handleIn:b.handleIn?[b.handleIn[0]*o,b.handleIn[1]*a]:void 0,handleOut:b.handleOut?[b.handleOut[0]*o,b.handleOut[1]*a]:void 0})),h=r.width*o,m=r.height*a,w=[[u,d],[u+h,d+m]],C=e.children.findIndex(b=>b.id===t);C>=0&&Ke.setNode(e,{points:w,anchors:f},[C])}function bWe(e,t,n,r,i,s){const o=s.width/i.width,a=s.height/i.height,l=r.x-i.x,c=r.y-i.y,u=s.x+l*o,d=s.y+c*a,f=r.width*o,h=r.height*a,m=[[u,d],[u+f,d+h]],g=e.children.findIndex(w=>w.id===t);g>=0&&(be.isDrawElement(n)&&be.isImage(n)?Ke.setNode(e,{points:m,width:f,height:h},[g]):Ke.setNode(e,{points:m},[g]))}function CWe(e,t,n){const{element:r,rectangle:i,handle:s}=t,{startPoint:o,endPoint:a}=n;if(!i||!Array.isArray(r)||!EC)return;const l=a[0]-o[0],c=a[1]-o[1],u=_S(i,s,l,c,SS());for(const d of r){const f=EC.get(d.id);if(!f)continue;const{element:h,rectangle:m}=f;ir.isFreehand(h)?wWe(e,d.id,h,m,i,u):lr.isPenPath(h)?xWe(e,d.id,h,m,i,u):bWe(e,d.id,h,m,i,u)}}function EWe(e){const t=nt(e);if(t.length<2||!I3(t))return null;try{const n=Jt(),r=Et(e,t,!1),i=Wi(e,r);return X.getCornerPoints(i).forEach(o=>{const a=gI(e,o);n.append(a)}),n}catch{return null}}const SWe=e=>{const{afterChange:t}=e;let n=null;return e.afterChange=()=>{t(),n&&(n.remove(),n=null);const r=nt(e);r.length>1&&I3(r)&&!ui(e)&&(n=EWe(e),n&&Q.getActiveHost(e).append(n))},qa(e,{key:"multi-resize",canResize:()=>vWe(e),hitTest:r=>yWe(e,r),onResize:(r,i)=>CWe(e,r,i)})};function _We(e){return e.some(n=>ir.isFreehand(n)||lr.isPenPath(n))}function TWe(e){const t=nt(e);if(t.length<2||!_We(t))return null;try{return Et(e,t,!1)}catch{return null}}const kWe=()=>{const e=Hr(),[t,n]=x.useState([]),[r,i]=x.useState(!1),[s,o]=x.useState(!1),a=x.useRef(!1),l=x.useCallback(()=>{const d=Fl(e)||$l(e)||ui(e);if(o(d),d)return;nt(e);const f=TWe(e);if(!f){i(!1);return}const m=[{x:f.x,y:f.y,cursor:"nwse-resize"},{x:f.x+f.width,y:f.y,cursor:"nesw-resize"},{x:f.x+f.width,y:f.y+f.height,cursor:"nwse-resize"},{x:f.x,y:f.y+f.height,cursor:"nesw-resize"}].map(g=>{const w=vf(e,[g.x,g.y]);return{x:w[0],y:w[1],cursor:g.cursor}});n(m),i(!0)},[e]);if(x.useEffect(()=>{a.current=s},[s]),x.useEffect(()=>{l();let d,f=JSON.stringify(e.viewport),h=JSON.stringify(e.selection),m=e.children.length;const g=()=>{const w=JSON.stringify(e.viewport),C=JSON.stringify(e.selection),b=e.children.length,_=Fl(e)||$l(e)||ui(e);(w!==f||C!==h||b!==m||_!==a.current)&&(f=w,h=C,m=b,l()),d=requestAnimationFrame(g)};return d=requestAnimationFrame(g),()=>{cancelAnimationFrame(d)}},[e,l]),!r||t.length===0||s)return null;const c=Gi,u=c/2;return y.jsx("div",{className:Le("multi-selection-handles",vi),children:t.map((d,f)=>y.jsx("div",{className:"multi-selection-handle",style:{left:d.x-u,top:d.y-u,width:c,height:c,cursor:d.cursor}},f))})},PWe=()=>null;class AWe{constructor(){this.initialized=!1,this.store=pi.createInstance({driver:pi.INDEXEDDB,name:FT.DATABASE_NAME,version:FT.DATABASE_VERSION,storeName:FT.TASKS_STORE_NAME,description:"Task queue persistent storage"})}async initialize(){if(!this.initialized)try{await this.store.ready(),this.initialized=!0}catch(t){throw console.error("[StorageService] Failed to initialize:",t),new Error("Storage initialization failed")}}async saveTask(t){try{await this.ensureInitialized(),await this.store.setItem(t.id,t)}catch(n){throw console.error("[StorageService] Failed to save task:",n),new Error("Failed to save task to storage")}}async saveTasks(t){try{await this.ensureInitialized(),await Promise.all(t.map(n=>this.saveTask(n)))}catch(n){throw console.error("[StorageService] Failed to save tasks:",n),new Error("Failed to save tasks to storage")}}async loadTask(t){try{return await this.ensureInitialized(),await this.store.getItem(t)}catch(n){return console.error(`[StorageService] Failed to load task ${t}:`,n),null}}async loadTasks(){try{await this.ensureInitialized();const t=[];return await this.store.iterate(n=>{n&&typeof n=="object"&&"id"in n&&t.push(n)}),await new Promise(n=>{typeof window<"u"&&"requestIdleCallback"in window?window.requestIdleCallback(()=>n(),{timeout:50}):setTimeout(n,0)}),t}catch(t){return console.error("[StorageService] Failed to load tasks:",t),[]}}async deleteTask(t){try{await this.ensureInitialized(),await this.store.removeItem(t)}catch(n){throw console.error(`[StorageService] Failed to delete task ${t}:`,n),new Error("Failed to delete task from storage")}}async getStorageSize(){try{await this.ensureInitialized();const t=await this.loadTasks(),n=JSON.stringify(t);return new Blob([n]).size}catch(t){return console.error("[StorageService] Failed to get storage size:",t),0}}async isStorageNearLimit(){return await this.getStorageSize()>=A9.WARNING_THRESHOLD}async pruneOldTasks(){try{await this.ensureInitialized();const t=await this.loadTasks();t.sort((i,s)=>s.createdAt-i.createdAt);const n=t.slice(A9.MAX_RETAINED_TASKS);await Promise.all(n.map(i=>this.deleteTask(i.id)));const r=t.length-n.length}catch(t){throw console.error("[StorageService] Failed to prune old tasks:",t),new Error("Failed to prune old tasks")}}async clearAll(){try{await this.ensureInitialized(),await this.store.clear()}catch(t){throw console.error("[StorageService] Failed to clear storage:",t),new Error("Failed to clear storage")}}async ensureInitialized(){this.initialized||await this.initialize()}}const Ku=new AWe;function DWe(e){const t=e.imageUrl.toLowerCase(),n=t.includes(".png")?"png":t.includes(".jpg")||t.includes(".jpeg")?"jpg":t.includes(".webp")?"webp":"png";return{id:e.id,type:Ft.IMAGE,status:ht.COMPLETED,params:{prompt:e.prompt,width:e.width,height:e.height},result:{url:e.imageUrl,format:n,size:0,width:e.width,height:e.height},createdAt:e.timestamp,updatedAt:e.timestamp,completedAt:e.timestamp}}function IWe(e){const t=e.previewUrl.toLowerCase(),n=t.includes(".mp4")?"mp4":t.includes(".webm")?"webm":t.includes(".mov")?"mov":"mp4";return{id:e.id,type:Ft.VIDEO,status:ht.COMPLETED,params:{prompt:e.prompt,width:e.width,height:e.height},result:{url:e.previewUrl,format:n,size:0,width:e.width,height:e.height,thumbnailUrl:e.imageUrl},createdAt:e.timestamp,updatedAt:e.timestamp,completedAt:e.timestamp}}async function OWe(){try{const e=localStorage.getItem(N9);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t)||t.length===0)return[];const n=t.map(DWe);return await Ku.saveTasks(n),localStorage.removeItem(N9),n}catch(e){return console.error("[HistoryMigration] Failed to migrate image history:",e),[]}}async function MWe(){try{const e=localStorage.getItem(j9);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t)||t.length===0)return[];const n=t.map(IWe);return await Ku.saveTasks(n),localStorage.removeItem(j9),n}catch(e){return console.error("[HistoryMigration] Failed to migrate video history:",e),[]}}async function RWe(){try{const e=await OWe(),t=await MWe();e.length+t.length>0}catch(e){console.error("[HistoryMigration] Migration failed:",e)}}let JT=!1;function ek(e=100){return new Promise(t=>{"requestIdleCallback"in window?window.requestIdleCallback(()=>t(),{timeout:e}):setTimeout(t,0)})}function BWe(){x.useEffect(()=>{let e=!0;const t=xu(),n=async()=>{if(!JT){JT=!0,await ek(50);try{if(await Ku.initialize(),await ek(50),await RWe(),t){const{swTaskQueueService:o}=await ln(async()=>{const{swTaskQueueService:l}=await Promise.resolve().then(()=>g3);return{swTaskQueueService:l}},void 0,import.meta.url);await o.initialize(),await ek(50);const a=await Ku.loadTasks();if(a.length>0){await o.restoreTasks(a);for(const l of a)await Ku.deleteTask(l.id)}await o.syncTasksFromSW();return}const s=await Ku.loadTasks();if(s.length>0&&e){bn.restoreTasks(s);const o=s.filter(u=>u.status==="processing");o.length>0&&o.forEach(u=>{if(!(u.type===Ft.VIDEO&&u.remoteId)){let d="任务被中断(页面刷新)",f="INTERRUPTED";u.type===Ft.VIDEO&&u.executionPhase===ah.SUBMITTING&&(d="任务在提交过程中被中断,可能已在后台执行",f="INTERRUPTED_DURING_SUBMISSION"),vr.updateTaskStatus(u.id,ht.FAILED,{startedAt:void 0,executionPhase:void 0,error:{code:f,message:d,details:{originalError:`Task interrupted by page refresh before completion (phase: ${u.executionPhase||"unknown"})`,timestamp:Date.now()}}})}});const a=s.filter(u=>u.type===Ft.VIDEO&&u.status==="failed"&&u.remoteId);if(a.length>0){const u=d=>{var C,b,_,T;const f=((C=d.error)==null?void 0:C.message)||"",h=((_=(b=d.error)==null?void 0:b.details)==null?void 0:_.originalError)||"",m=((T=d.error)==null?void 0:T.code)||"",g=`${f} ${h}`.toLowerCase();return g.includes("generation_failed")||g.includes("invalid_argument")||g.includes("prohibited")||g.includes("content policy")||g.includes("视频生成失败")||m.includes("generation_failed")||m.includes("INVALID")?!1:g.includes("failed to fetch")||g.includes("network")||g.includes("fetch")||g.includes("timeout")||g.includes("aborted")||g.includes("connection")||g.includes("status query failed")};a.forEach(d=>{u(d)&&(console.log(`[useTaskStorage] Recovering failed video task ${d.id} (network error, has remoteId: ${d.remoteId})`),vr.updateTaskStatus(d.id,ht.PROCESSING,{error:void 0,executionPhase:ah.POLLING}))})}const l=s.filter(u=>u.status==="pending"),c=o.filter(u=>u.type===Ft.VIDEO&&u.remoteId);if(l.length>0||c.length>0){const u=l.length+c.length}}}catch(s){JT=!1,console.error("[useTaskStorage] Failed to initialize storage:",s)}}},r=KSe(async s=>{try{await Ku.saveTask(s)}catch(o){console.error("[useTaskStorage] Failed to save task:",o)}},ENe.STORAGE_SYNC),i=bn.observeTaskUpdates().subscribe(s=>{e&&(s.type==="taskDeleted"?Ku.deleteTask(s.task.id).catch(o=>{console.error("[useTaskStorage] Failed to delete task from storage:",o)}):r(s.task))});return n(),()=>{e=!1,i.unsubscribe()}},[])}class LWe{constructor(){this.abortControllers=new Map}async generate(t,n,r){const i=new AbortController;this.abortControllers.set(t,i);const s=Date.now(),o=r===Ft.IMAGE?"image":"video";qt.trackModelCall({taskId:t,taskType:o,model:o==="image"?"gemini-image":"gemini-video",promptLength:n.prompt.length,hasUploadedImage:!!n.uploadedImage||!!n.uploadedImages,startTime:s});try{const a=vC[r.toUpperCase()],l=new Promise((f,h)=>{setTimeout(()=>{h(new Error("TIMEOUT"))},a)}),c=r===Ft.IMAGE?this.generateImage(n,i.signal):this.generateVideo(t,n,i.signal),u=await Promise.race([c,l]),d=Date.now()-s;return qt.trackModelSuccess({taskId:t,taskType:o,model:o==="image"?"gemini-image":"gemini-video",duration:d,resultSize:u.size}),u}catch(a){const l=Date.now()-s;throw console.error(`[GenerationAPI] Generation failed for task ${t}:`,a),a.message==="TIMEOUT"?(qt.trackModelFailure({taskId:t,taskType:o,model:o==="image"?"gemini-image":"gemini-video",duration:l,error:"TIMEOUT"}),new Error(`${r===Ft.IMAGE?"图片":"视频"}生成超时`)):a.name==="AbortError"?(qt.trackTaskCancellation({taskId:t,taskType:o,duration:l}),new Error("任务已取消")):(qt.trackModelFailure({taskId:t,taskType:o,model:o==="image"?"gemini-image":"gemini-video",duration:l,error:a.message||"UNKNOWN_ERROR"}),a)}finally{this.abortControllers.delete(t)}}convertAspectRatioToSize(t){return!t||t==="auto"?void 0:{"1:1":"1x1","2:3":"2x3","3:2":"3x2","3:4":"3x4","4:3":"4x3","4:5":"4x5","5:4":"5x4","9:16":"9x16","16:9":"16x9","21:9":"21x9"}[t]}async generateImage(t,n){try{let r=t.size;if(!r){const u=t.aspectRatio;r=this.convertAspectRatioToSize(u)}let i;if(t.uploadedImages){const u=t.uploadedImages,d=[];for(const f of u)if(f.type==="url"&&f.url){const h=await Mn.getImageForAI(f.url);d.push(h.value)}d.length>0&&(i=d)}const s=t.quality,o=await du.generateImage(t.prompt,{size:r,image:i&&i.length>0?i:void 0,response_format:"url",quality:s,model:t.model}),a=u=>{const d=`Generate an image: ${t.prompt}: `;if(u.startsWith(d))return u.substring(d.length);const f="Generate an image: ";if(u.startsWith(f)){const h=u.substring(f.length),m=h.indexOf(": ");if(m!==-1)return h.substring(m+2)}return u};if(o.data&&Array.isArray(o.data)&&o.data.length>0){const u=o.data[0];let d;if(u.url)d=u.url;else if(u.b64_json)d=`data:image/png;base64,${u.b64_json}`;else{const f=u.revised_prompt||"";if(f.includes("PROHIBITED_CONTENT")||f.includes("has been blocked")){const g=f.match(/your request has been blocked[^:]*:\s*([^.]+)/i);if(g)throw new Error(g[0]);const w=f.toLowerCase().lastIndexOf("blocked");if(w!==-1){const C=f.slice(w-20);throw new Error(C.trim())}}let h;u.revised_prompt?h=a(u.revised_prompt):h=JSON.stringify(u);const m=new Error(`API 未返回有效的图片数据: ${h}`);throw m.fullResponse=h,m}return{url:d,format:"png",size:0}}let l;o.revised_prompt?l=a(o.revised_prompt):l=JSON.stringify(o);const c=new Error(`API 未返回有效的图片数据: ${l}`);throw c.fullResponse=l,c}catch(r){console.error("[GenerationAPI] Image generation error:",r);const i=new Error(r.message||"图片生成失败");throw r.apiErrorBody&&(i.apiErrorBody=r.apiErrorBody),r.httpStatus&&(i.httpStatus=r.httpStatus),r.fullResponse&&(i.fullResponse=r.fullResponse),i}}async generateVideo(t,n,r){try{vr.updateTaskStatus(t,"processing",{executionPhase:ah.SUBMITTING});let i,s;if(n.uploadedImages&&n.uploadedImages.length>0)i=n.uploadedImages;else if(n.uploadedImage){const f=n.uploadedImage;f.type==="url"&&f.url&&(s=f.url)}const o=An.get(),a=n.model||o.videoModelName||"veo3";let l;n.seconds?l=n.seconds:n.duration?l=n.duration.toString():a.startsWith("sora")?l="10":l="8";let c;n.size?c=n.size:n.width&&n.height?c=`${n.width}x${n.height}`:c="1280x720";const u=await RA.generateVideoWithPolling({model:a,prompt:n.prompt,seconds:l,size:c,inputReferences:i,inputReference:s},{interval:5e3,onProgress:(f,h)=>{vr.updateTaskProgress(t,f)},onSubmitted:f=>{vr.updateTaskStatus(t,"processing",{remoteId:f,executionPhase:ah.POLLING})}}),d=u.video_url||u.url;if(!d)throw new Error("API 未返回有效的视频 URL");return{url:d,format:"mp4",size:0,duration:parseInt(u.seconds)||n.duration||8}}catch(i){console.error("[GenerationAPI] Video generation error:",i);const s=new Error(i.message||"视频生成失败");throw i.apiErrorBody&&(s.apiErrorBody=i.apiErrorBody),i.httpStatus&&(s.httpStatus=i.httpStatus),s}}async resumeVideoGeneration(t,n){const r=Date.now();qt.trackModelCall({taskId:t,taskType:"video",model:"gemini-video",promptLength:0,hasUploadedImage:!1,startTime:r});try{const i=vC.VIDEO,s=new Promise((u,d)=>{setTimeout(()=>{d(new Error("TIMEOUT"))},i)}),o=RA.resumePolling(n,{interval:5e3,onProgress:(u,d)=>{vr.updateTaskProgress(t,u)}}),a=await Promise.race([o,s]),l=Date.now()-r;qt.trackModelSuccess({taskId:t,taskType:"video",model:"gemini-video",duration:l,resultSize:0});const c=a.video_url||a.url;if(!c)throw new Error("API 未返回有效的视频 URL");return{url:c,format:"mp4",size:0,duration:parseInt(a.seconds)||8}}catch(i){const s=Date.now()-r;throw console.error(`[GenerationAPI] Resumed video generation failed for task ${t}:`,i),qt.trackModelFailure({taskId:t,taskType:"video",model:"gemini-video",duration:s,error:i.message||"UNKNOWN_ERROR"}),i}}cancelRequest(t){const n=this.abortControllers.get(t);n&&(n.abort(),this.abortControllers.delete(t))}hasActiveRequest(t){return this.abortControllers.has(t)}}const mx=new LWe,NWe=xu()?cy:vr;function jWe(e){var t;if(!e)return null;try{const n=JSON.parse(e);if((t=n.error)!=null&&t.message)return n.error.message;if(n.message)return n.message;if(n.error&&typeof n.error=="string")return n.error;if(n.detail)return n.detail;if(n.msg)return n.msg}catch{return e}return null}function tk(e){const t=(e==null?void 0:e.message)||String(e),n=(e==null?void 0:e.apiErrorBody)||"",r=e==null?void 0:e.httpStatus,i=jWe(n),s=`${t} ${n}`;return s.includes("insufficient_user_quota")||s.includes("预扣费额度失败")?"账户额度不足,请充值后重试":t.includes("PROHIBITED_CONTENT")||t.includes("has been blocked by Google Gemini")?t:t.includes("cannot")||t.includes("I cannot")||t.includes("I can't")?"AI 拒绝生成此内容":t.includes("unable to")||t.includes("not able to")?"AI 无法处理此请求":t.includes("signal")&&t.includes("timed out")?"请求超时,服务器响应过慢,正在自动重试":t.includes("TIMEOUT")||t.includes("超时")?"生成超时,请稍后重试":t.includes("network")||t.includes("Network")||t.includes("fetch")||t.includes("Failed to fetch")?"网络连接失败,请检查网络后重试":t.includes("rate limit")||t.includes("429")||r===429?"请求过于频繁,请稍后重试":t.includes("401")||r===401?"API 认证失败,请检查 API Key 配置":(t.includes("403")||r===403)&&!n.includes("quota")?"API 访问被拒绝,请检查配置":t.includes("500")||r===500?i?`AI 服务器内部错误: ${i}`:"AI 服务器内部错误,正在自动重试":t.includes("502")||r===502?i?`AI 服务暂时不可用: ${i}`:"AI 服务暂时不可用(502),正在自动重试":t.includes("503")||r===503?i?`AI 服务繁忙: ${i}`:"AI 服务繁忙(503),正在自动重试":t.includes("504")||r===504?i?`AI 服务响应超时: ${i}`:"AI 服务响应超时(504),正在自动重试":i||t}function FWe(){const e=x.useRef(new Set),t=x.useRef(null),n=xu();x.useEffect(()=>{let r=!0;if(n){const u=NWe.observeTaskUpdates().subscribe(async d=>{var f;if(r&&d.type==="taskUpdated"&&d.task.status===ht.COMPLETED){const h=d.task;if((f=h.result)!=null&&f.url)try{await Mn.registerImageMetadata(h.result.url,{taskId:h.id,model:h.params.model,prompt:h.params.prompt,params:h.params})}catch(m){console.error(`[TaskExecutor] Failed to register metadata for task ${h.id}:`,m)}if(h.type===Ft.CHARACTER&&h.result)try{await Rs.saveCharacter({id:h.remoteId||h.id,username:h.result.characterUsername||"",profilePictureUrl:h.result.characterProfileUrl||h.result.url,permalink:h.result.characterPermalink||"",sourceTaskId:h.params.sourceLocalTaskId||"",sourceVideoId:h.params.sourceVideoTaskId||"",sourcePrompt:h.params.prompt,characterTimestamps:h.params.characterTimestamps,status:"completed",createdAt:h.createdAt,completedAt:Date.now()})}catch(m){console.error(`[TaskExecutor] Failed to save character for task ${h.id}:`,m)}}});return()=>{r=!1,u.unsubscribe()}}const i=async u=>{const d=u.id,f=u.remoteId;if(!e.current.has(d)){e.current.add(d);try{const h=await mx.resumeVideoGeneration(d,f);if(!r)return;if(vr.updateTaskStatus(d,ht.COMPLETED,{result:h}),h.url)try{await Mn.registerImageMetadata(h.url,{taskId:u.id,model:u.params.model,prompt:u.params.prompt,params:u.params})}catch(m){console.error(`[TaskExecutor] Failed to register metadata for resumed task ${d}:`,m)}}catch(h){if(!r||(console.error(`[TaskExecutor] Resumed task ${d} failed:`,h),!vr.getTask(d)))return;const g=h.httpStatus?`HTTP_${h.httpStatus}`:h.name||"ERROR",w=tk(h),b={originalError:h.fullResponse||h.apiErrorBody||h.message||String(h),timestamp:Date.now()};vr.updateTaskStatus(d,ht.FAILED,{error:{code:g,message:w,details:b}})}finally{e.current.delete(d)}}},s=async u=>{const d=u.id;if(!e.current.has(d)){e.current.add(d);try{vr.updateTaskStatus(d,ht.PROCESSING);const{sourceVideoTaskId:f,characterTimestamps:h,model:m,prompt:g}=u.params;if(!f)throw new Error("缺少源视频任务ID");const w=await rb.createCharacterWithPolling({videoTaskId:f,characterTimestamps:h,localTaskId:u.params.sourceLocalTaskId,sourcePrompt:g,sourceModel:m},{onStatusChange:C=>{}});if(!r)return;await Rs.saveCharacter({id:w.characterId,username:w.username,profilePictureUrl:w.profile_picture_url,permalink:w.permalink,sourceTaskId:u.params.sourceLocalTaskId||"",sourceVideoId:f,sourcePrompt:g,characterTimestamps:h,status:"completed",createdAt:u.createdAt,completedAt:Date.now()}),vr.updateTaskStatus(d,ht.COMPLETED,{result:{url:w.profile_picture_url,format:"character",size:0,characterUsername:w.username,characterProfileUrl:w.profile_picture_url,characterPermalink:w.permalink},remoteId:w.characterId})}catch(f){if(!r||(console.error(`[TaskExecutor] Character task ${d} failed:`,f),!vr.getTask(d)))return;const m=f.httpStatus?`HTTP_${f.httpStatus}`:f.name||"ERROR",g=tk(f),C={originalError:f.fullResponse||f.apiErrorBody||f.message||String(f),timestamp:Date.now()};vr.updateTaskStatus(d,ht.FAILED,{error:{code:m,message:g,details:C}})}finally{e.current.delete(d)}}},o=async u=>{const d=u.id;if(u.type===Ft.CHARACTER)return s(u);if(u.type===Ft.VIDEO&&u.remoteId&&u.status===ht.PROCESSING)return i(u);if(!e.current.has(d)){e.current.add(d);try{vr.updateTaskStatus(d,ht.PROCESSING);const f=await mx.generate(d,u.params,u.type);if(!r)return;if(vr.updateTaskStatus(d,ht.COMPLETED,{result:f}),f.url)try{await Mn.registerImageMetadata(f.url,{taskId:u.id,model:u.params.model,prompt:u.params.prompt,params:u.params})}catch(h){console.error(`[TaskExecutor] Failed to register metadata for task ${d}:`,h)}}catch(f){if(!r||(console.error(`[TaskExecutor] Task ${d} failed:`,f),!vr.getTask(d)))return;const m=f.httpStatus?`HTTP_${f.httpStatus}`:f.name||"ERROR",g=tk(f),C={originalError:f.fullResponse||f.apiErrorBody||f.message||String(f),timestamp:Date.now()};vr.updateTaskStatus(d,ht.FAILED,{error:{code:m,message:g,details:C}})}finally{e.current.delete(d)}}},a=()=>{if(!r)return;const u=vr.getAllTasks();u.filter(h=>h.status===ht.PENDING).forEach(h=>{o(h)}),u.filter(h=>h.type===Ft.VIDEO&&h.status===ht.PROCESSING&&h.remoteId).forEach(h=>{o(h)})},l=()=>{if(!r)return;vr.getAllTasks().filter(f=>f.status===ht.PROCESSING).forEach(f=>{if(SNe(f)){console.warn(`[TaskExecutor] Task ${f.id} timed out`),mx.cancelRequest(f.id);const h={originalError:`Task ${f.id} timed out after processing`,timestamp:Date.now()};vr.updateTaskStatus(f.id,ht.FAILED,{error:{code:"TIMEOUT",message:"任务执行超时",details:h}})}})},c=vr.observeTaskUpdates().subscribe(u=>{if(r&&(u.type==="taskCreated"||u.type==="taskUpdated")){const d=u.task;(d.status===ht.PENDING||d.type===Ft.VIDEO&&d.status===ht.PROCESSING&&d.remoteId&&!e.current.has(d.id))&&o(d)}});return a(),t.current=setInterval(l,1e4),()=>{r=!1,c.unsubscribe(),t.current&&clearInterval(t.current),e.current.forEach(u=>{mx.cancelRequest(u)}),e.current.clear()}},[])}class $We{constructor(){this.postProcessingResults=new Map,this.batchTasks=new Map,this.taskToBatch=new Map,this.completionEvents$=new Ks,this.batchCompletionEvents$=new Ks,this.isProcessing$=new PD(!1)}registerTask(t,n){n&&(this.taskToBatch.set(t,n),this.batchTasks.has(n)||this.batchTasks.set(n,new Set),this.batchTasks.get(n).add(t)),this.postProcessingResults.set(t,{taskId:t,status:"pending",type:"direct_insert"})}startPostProcessing(t,n){const r={taskId:t,status:"processing",type:n};this.postProcessingResults.set(t,r),this.isProcessing$.next(!0),this.completionEvents$.next({taskId:t,batchId:this.taskToBatch.get(t),type:"postProcessingStarted",result:r,timestamp:Date.now()})}completePostProcessing(t,n,r){const i=this.postProcessingResults.get(t),s={taskId:t,status:"completed",type:(i==null?void 0:i.type)||"direct_insert",insertedCount:n,firstElementPosition:r,completedAt:Date.now()};this.postProcessingResults.set(t,s),this.completionEvents$.next({taskId:t,batchId:this.taskToBatch.get(t),type:"postProcessingCompleted",result:s,timestamp:Date.now()}),this.checkBatchCompletion(t),this.updateProcessingStatus()}failPostProcessing(t,n){const r=this.postProcessingResults.get(t),i={taskId:t,status:"failed",type:(r==null?void 0:r.type)||"direct_insert",error:n,completedAt:Date.now()};this.postProcessingResults.set(t,i),this.completionEvents$.next({taskId:t,batchId:this.taskToBatch.get(t),type:"postProcessingFailed",result:i,timestamp:Date.now()}),this.checkBatchCompletion(t),this.updateProcessingStatus()}checkBatchCompletion(t){var c;const n=this.taskToBatch.get(t);if(!n)return;const r=this.batchTasks.get(n);if(!r)return;const i=[];for(const u of r){const d=this.postProcessingResults.get(u);if(!d||d.status!=="completed"&&d.status!=="failed")return;i.push(d)}const s=i.every(u=>u.status==="completed"),o=i.reduce((u,d)=>u+(d.insertedCount||0),0),a=(c=i.find(u=>u.firstElementPosition))==null?void 0:c.firstElementPosition,l={batchId:n,results:i,allSuccess:s,totalInsertedCount:o,firstElementPosition:a,timestamp:Date.now()};this.batchCompletionEvents$.next(l)}updateProcessingStatus(){const t=Array.from(this.postProcessingResults.values()).some(n=>n.status==="processing");this.isProcessing$.next(t)}getPostProcessingStatus(t){return this.postProcessingResults.get(t)}isPostProcessingCompleted(t){const n=this.postProcessingResults.get(t);return(n==null?void 0:n.status)==="completed"||(n==null?void 0:n.status)==="failed"}observeCompletionEvents(){return this.completionEvents$.asObservable()}observeBatchCompletionEvents(){return this.batchCompletionEvents$.asObservable()}observeProcessingStatus(){return this.isProcessing$.asObservable()}clearTask(t){const n=this.taskToBatch.get(t);if(n){const r=this.batchTasks.get(n);r&&(r.delete(t),r.size===0&&this.batchTasks.delete(n)),this.taskToBatch.delete(t)}this.postProcessingResults.delete(t)}clear(){this.postProcessingResults.clear(),this.batchTasks.clear(),this.taskToBatch.clear(),this.isProcessing$.next(!1)}}const ps=new $We,mne=8,zWe="veo3.1";function HWe(e,t){return`你是一个专业的视频脚本编剧。用户会给你一个视频主题,你需要将其拆分为 ${e} 个连续的视频片段脚本。
2003
2003
 
2004
2004
  要求:
2005
2005
  1. 每个片段时长约 ${t} 秒
@@ -2048,7 +2048,7 @@ Style: Disney-style animation, vibrant colors, dreamy lighting.`,"a beautiful su
2048
2048
  `),(T=t==null?void 0:t.onChunk)==null||T.call(t,`- 您可以在任务队列中查看实时进度
2049
2049
  `),{success:!0,data:{batchId:D,taskId:R.id,segmentCount:k.length,totalDuration:r,scripts:k},type:"video",taskId:R.id}}catch(S){return console.error("[LongVideo] Generation failed:",S),{success:!1,error:S.message||"长视频生成失败",type:"error"}}}const UWe=Object.freeze(Object.defineProperty({__proto__:null,createLongVideoSegmentTask:O3,createLongVideoTask:VWe},Symbol.toStringTag,{value:"Module"})),Si={DEFAULT_VERTICAL_GAP:50,DEFAULT_HORIZONTAL_GAP:20,TEXT_DEFAULT_WIDTH:300,TEXT_LINE_HEIGHT:24,MEDIA_DEFAULT_SIZE:400,MEDIA_MAX_SIZE:600};function Mz(e,t=400){if(!e)return{width:t,height:t};const n=e.match(/^(\d+)x(\d+)$/);if(!n)return{width:t,height:t};const r=parseInt(n[1],10),i=parseInt(n[2],10);if(r<=0||i<=0)return{width:t,height:t};const s=i/r,o=Math.round(t*s);return{width:t,height:o}}let M3=null;function Rz(e){M3=e}function hy(){return M3}function KWe(e){const t=e.appState,n=(t==null?void 0:t.lastSelectedElementIds)||[];if(n.length===0)return;const r=n.map(i=>e.children.find(s=>s.id===i)).filter(Boolean);if(r.length!==0)try{const i=Et(e,r,!1),s=i.x,o=i.y+i.height+Si.DEFAULT_VERTICAL_GAP;return[s,o]}catch(i){console.warn("[CanvasInsertion] Error calculating start point:",i);return}}function qWe(e){if(!e.children||e.children.length===0)return[100,100];let t=0,n=100;for(const r of e.children)try{const i=Et(e,[r],!1),s=i.y+i.height;s>t&&(t=s,n=i.x)}catch{}return[n,t+Si.DEFAULT_VERTICAL_GAP]}function vne(e){const t=e.split(`
2050
2050
  `),n=Math.max(...t.map(s=>s.length)),r=Math.min(n*8,Si.TEXT_DEFAULT_WIDTH),i=t.length*Si.TEXT_LINE_HEIGHT;return{width:r,height:i}}function XWe(e){const t=new Map;for(const i of e)if(i.groupId){const s=t.get(i.groupId)||[];s.push(i),t.set(i.groupId,s)}const n=[];let r=null;for(const i of e)if(i.groupId){if(r!==i.groupId){r=i.groupId;const s=t.get(i.groupId);s&&n.push(s)}}else n.push([i]),r=null;return n}async function Bz(e,t,n){return Yn.insertText(e,n,t),vne(t)}async function Lz(e,t,n,r){const i=r||{width:Si.MEDIA_DEFAULT_SIZE,height:Si.MEDIA_DEFAULT_SIZE};return await wm(e,t,n,!1,i,!0,!0),i}async function Nz(e,t,n,r){if(r)return await lh(e,t,n,!1,r,!0,!0),r;const i={width:Si.MEDIA_DEFAULT_SIZE,height:Math.round(Si.MEDIA_DEFAULT_SIZE*(9/16))};return await lh(e,t,n,!1,i,!0,!0),i}function YWe(e){return`data:image/svg+xml,${encodeURIComponent(e).replace(/'/g,"%27").replace(/"/g,"%22")}`}function ZWe(e){let t=e.trim();return t.includes("xmlns=")||(t=t.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),t}function QWe(e){const t=e.match(/viewBox=["']([^"']+)["']/i);if(t){const i=t[1].split(/\s+/).map(Number);if(i.length>=4&&i[2]&&i[3])return{width:i[2],height:i[3]}}const n=e.match(/width=["'](\d+)(?:px)?["']/i),r=e.match(/height=["'](\d+)(?:px)?["']/i);return n&&r?{width:parseInt(n[1]),height:parseInt(r[1])}:{width:400,height:400}}async function jz(e,t,n){const r=ZWe(t),i=QWe(r),s=Math.min(i.width,Si.MEDIA_DEFAULT_SIZE),o=i.height/i.width,a=s*o,c={url:YWe(r),width:s,height:a};return Yn.insertImage(e,c,n),{width:s,height:a}}async function R3(e){const t=M3;if(!t)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};const{items:n,verticalGap:r=Si.DEFAULT_VERTICAL_GAP,horizontalGap:i=Si.DEFAULT_HORIZONTAL_GAP}=e;if(!n||n.length===0)return{success:!1,error:"没有要插入的内容",type:"error"};try{let s=e.startPoint;s||(s=KWe(t)),s||(s=qWe(t));const o=XWe(n);let a=s[1];const l=s[0],c=[];for(const u of o)if(u.length===1){const d=u[0];let f={width:Si.MEDIA_DEFAULT_SIZE,height:225};d.type==="text"?f=vne(d.content):d.type==="image"?f=d.dimensions||{width:Si.MEDIA_DEFAULT_SIZE,height:Si.MEDIA_DEFAULT_SIZE}:d.type==="video"&&(f=d.dimensions||{width:Si.MEDIA_DEFAULT_SIZE,height:Math.round(Si.MEDIA_DEFAULT_SIZE*(9/16))});const h=[l,a];if(d.type==="text")await Bz(t,d.content,h),a+=f.height+r;else if(d.type==="image"){const m=await Lz(t,d.content,h,d.dimensions);a+=m.height+r}else if(d.type==="video"){const m=await Nz(t,d.content,h,d.dimensions);a+=m.height+r}else if(d.type==="svg"){const m=await jz(t,d.content,h);a+=m.height+r}c.push({type:d.type,point:h})}else{let d=l,f=0;for(const h of u){const m=[d,a];if(h.type==="text"){const g=await Bz(t,h.content,m);f=Math.max(f,g.height),d+=g.width+i}else if(h.type==="image"){const g=await Lz(t,h.content,m,h.dimensions);f=Math.max(f,g.height),d+=g.width+i}else if(h.type==="video"){const g=await Nz(t,h.content,m,h.dimensions);f=Math.max(f,g.height),d+=g.width+i}else if(h.type==="svg"){const g=await jz(t,h.content,m);f=Math.max(f,g.height),d+=g.width+i}c.push({type:h.type,point:m})}a+=f+r}if(c.length>0){const u=c[0],d=[u.point[0]+Si.MEDIA_DEFAULT_SIZE/2,u.point[1]+Si.MEDIA_DEFAULT_SIZE/2];requestAnimationFrame(()=>{So(t,d)})}return{success:!0,data:{insertedCount:c.length,items:c,firstElementPosition:c.length>0?c[0].point:void 0},type:"text"}}catch(s){return console.error("[CanvasInsertion] Failed to insert content:",s),{success:!1,error:`插入失败: ${s.message||"未知错误"}`,type:"error"}}}async function qA(e,t,n,r){return R3({items:[{type:e,content:t,dimensions:r}],startPoint:n})}async function yne(e,t,n){const r=`img-group-${Date.now()}`;return R3({items:e.map(i=>({type:"image",content:i,groupId:r,dimensions:n})),startPoint:t})}async function Fz(e,t,n){const r=[{type:"text",content:e,label:"Prompt"}];if(t.length===1)r.push({type:t[0].type,content:t[0].url,dimensions:t[0].dimensions});else{const i=`result-group-${Date.now()}`;t.forEach(s=>{r.push({type:s.type,content:s.url,groupId:i,dimensions:s.dimensions})})}return R3({items:r,startPoint:n})}function JWe(e){return!!(e.gridImageRows&&e.gridImageCols)}function eGe(e){return!!(e.isInspirationBoard&&e.inspirationBoardLayoutStyle==="inspiration-board")}function tGe(e=800){const t=hy();if(t)return bh(t)}async function nGe(e,t,n,r={}){const i=hy();if(!i)return{success:!1,count:0,error:"Board not available"};ps.registerTask(e,n.batchId),ps.startPostProcessing(e,"split_and_insert");try{const s=await f3(i,t,{scrollToResult:r.scrollToResult??!0}),o=r.insertionPoint||tGe();return s.success?(ps.completePostProcessing(e,s.count,o),{success:!0,count:s.count}):(console.warn(`[MediaResultHandler] Split failed: ${s.error}, falling back to direct insert`),(await yne([t],o)).success?(ps.completePostProcessing(e,1,o),{success:!0,count:1}):(ps.failPostProcessing(e,s.error||"Split and insert failed"),{success:!1,count:0,error:s.error}))}catch(s){const o=String(s);return console.error("[MediaResultHandler] Split and insert error:",s),ps.failPostProcessing(e,o),{success:!1,count:0,error:o}}}const rGe={enabled:!0,insertPrompt:!1,groupSimilarTasks:!0,groupTimeWindow:5e3},nk=new Set;function wne(e){var r;const t=hy();if(!t)return null;const n=$r.getAllWorkZones(t);for(const i of n)if((r=i.workflow.steps)==null?void 0:r.some(o=>{const a=o.result;return(a==null?void 0:a.taskId)===e}))return i;return null}function E0(e,t,n,r){var a;const i=hy();if(!i)return;const s=wne(e);if(!s)return;const o=(a=s.workflow.steps)==null?void 0:a.map(l=>{const c=l.result;if((c==null?void 0:c.taskId)===e){const u=typeof l.result=="object"&&l.result!==null?l.result:{};return{...l,status:t,result:n?{...u,url:n.url,success:t==="completed"}:l.result,error:r}}return l});o&&($r.updateWorkflow(i,s.id,{steps:o}),o.every(c=>c.status==="completed"||c.status==="failed"||c.status==="skipped")&&setTimeout(()=>{$r.removeWorkZone(i,s.id),window.dispatchEvent(new CustomEvent("ai-generation-complete",{detail:{type:"image",success:!0,workzoneId:s.id}}))},1500))}function iGe(e={}){const t={...rGe,...e},n=x.useRef(new Map),r=x.useRef(null);x.useEffect(()=>{if(!t.enabled)return;let i=!0;const s=async()=>{var C,b,_;const f=hy();if(!f||!i)return;const h=n.current;if(h.size===0)return;const m=new Map(h);h.clear();const g=(b=(C=Array.from(m.values())[0])==null?void 0:C[0])==null?void 0:b.task;let w;if(g){const T=wne(g.id);T!=null&&T.expectedInsertPosition&&(w=T.expectedInsertPosition)}w||(w=bh(f));for(const[T,S]of m){if(!i)break;for(const{task:k}of S){const D=k.params.batchId;ps.registerTask(k.id,D),ps.startPostProcessing(k.id,S.length===1?"direct_insert":"group_insert")}try{if(S.length===1){const{task:k}=S[0],D=(_=k.result)==null?void 0:_.url;if(!D){ps.failPostProcessing(k.id,"No result URL");continue}const O=k.type===Ft.VIDEO?"video":"image",I=Mz(k.params.size);if(t.insertPrompt){const R=await Fz(k.params.prompt,[{type:O,url:D,dimensions:I}],w)}else{const R=await qA(O,D,w,I)}ps.completePostProcessing(k.id,1,w)}else{const k=S.map(({task:R})=>{var F;return(F=R.result)==null?void 0:F.url}).filter(R=>!!R);if(k.length===0){for(const{task:R}of S)ps.failPostProcessing(R.id,"No result URL");continue}const D=S[0].task,O=D.type===Ft.VIDEO?"video":"image",I=Mz(D.params.size);if(t.insertPrompt)await Fz(D.params.prompt,k.map(R=>({type:O,url:R,dimensions:I})),w);else if(O==="image")await yne(k,w,I);else for(const R of k)await qA("video",R,w,I);for(const{task:R}of S)ps.completePostProcessing(R.id,1,w)}}catch(k){console.error(`[AutoInsert] Failed to insert for prompt ${T}:`,k);for(const{task:D}of S)ps.failPostProcessing(D.id,String(k))}}},o=()=>{r.current&&clearTimeout(r.current),r.current=setTimeout(()=>{s()},t.groupTimeWindow)},a=async f=>{var w;const h=(w=f.result)==null?void 0:w.url;if(!h){console.error("[AutoInsert] Split task has no result URL"),ps.failPostProcessing(f.id,"No result URL"),E0(f.id,"failed",void 0,"No result URL");return}const m=f.params,g=await nGe(f.id,h,m,{scrollToResult:!0});g.success?E0(f.id,"completed",{url:h}):E0(f.id,"failed",void 0,g.error||"拆分失败")},l=f=>{var C;if(!f.params.autoInsertToCanvas||nk.has(f.id))return;if(f.insertedToCanvas){nk.add(f.id);return}if(f.type!==Ft.IMAGE&&f.type!==Ft.VIDEO)return;if(!((C=f.result)!=null&&C.url)){console.warn(`[AutoInsert] Task ${f.id} completed but has no result URL`);return}nk.add(f.id),NA().markAsInserted(f.id);const m=f.params;if(eGe(m)){a(f);return}if(JWe(m)){a(f);return}E0(f.id,"completed",{url:f.result.url});const g=f.params.prompt||"unknown",w=n.current.get(g)||[];w.push({task:f,completedAt:Date.now()}),n.current.set(g,w),t.groupSimilarTasks?o():s()},c=f=>{var h;E0(f.id,"failed",void 0,((h=f.error)==null?void 0:h.message)||"任务执行失败")},d=NA().observeTaskUpdates().subscribe(f=>{i&&(f.type==="taskUpdated"?f.task.status===ht.COMPLETED?l(f.task):f.task.status===ht.FAILED&&c(f.task):f.type==="taskSynced"&&f.task.status===ht.COMPLETED&&l(f.task))});return()=>{i=!1,d.unsubscribe(),r.current&&clearTimeout(r.current)}},[t.enabled,t.insertPrompt,t.groupSimilarTasks,t.groupTimeWindow])}function sGe(){x.useEffect(()=>{const e=t=>{if(bn.getAllTasks().filter(i=>i.status===ht.PENDING||i.status===ht.PROCESSING).length>0)return t.preventDefault(),t.returnValue="",""};return window.onbeforeunload=e,()=>{window.onbeforeunload=null}},[])}const xne=J.memo(({session:e,isActive:t,onSelect:n,onDelete:r,onRename:i})=>{const[s,o]=x.useState(!1),[a,l]=x.useState(e.title),c=x.useRef(null),u=x.useCallback(()=>{s||n()},[n,s]),d=x.useCallback(b=>{b.stopPropagation(),r()},[r]),f=x.useCallback(b=>{b.stopPropagation(),l(e.title),o(!0)},[e.title]),h=x.useCallback(()=>{const b=a.trim();b&&b!==e.title&&i(b),o(!1)},[a,e.title,i]),m=x.useCallback(()=>{l(e.title),o(!1)},[e.title]),g=x.useCallback(b=>{b.key==="Enter"?(b.preventDefault(),h()):b.key==="Escape"&&(b.preventDefault(),m())},[h,m]),w=x.useCallback(b=>{l(b.target.value)},[]);x.useEffect(()=>{s&&c.current&&(c.current.focus(),c.current.select())},[s]);const C=x.useMemo(()=>{const b=new Date(e.updatedAt),_=new Date;return b.toDateString()===_.toDateString()?b.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"}):b.toLocaleDateString("zh-CN",{month:"short",day:"numeric"})},[e.updatedAt]);return y.jsxs("div",{className:`session-item ${t?"session-item--active":""} ${s?"session-item--editing":""}`,"data-track":"chat_click_session_select",onClick:u,role:"button",tabIndex:0,onKeyDown:b=>!s&&b.key==="Enter"&&u(),children:[y.jsxs("div",{className:"session-item__content",children:[s?y.jsx("input",{ref:c,className:"session-item__title-input",value:a,onChange:w,onKeyDown:g,onBlur:h,onClick:b=>b.stopPropagation(),maxLength:50}):y.jsx("div",{className:"session-item__title",children:e.title}),y.jsx("div",{className:"session-item__time",children:C})]}),!s&&y.jsxs("div",{className:"session-item__actions",children:[y.jsx("button",{className:"session-item__edit","data-track":"chat_click_session_edit",onClick:f,"aria-label":`编辑会话标题: ${e.title}`,children:y.jsx(P3,{size:14})}),y.jsx("button",{className:"session-item__delete","data-track":"chat_click_session_delete",onClick:d,"aria-label":`删除会话: ${e.title}`,children:y.jsx(Gg,{size:14})})]})]})});xne.displayName="SessionItem";const bne=J.memo(({sessions:e,activeSessionId:t,onSelectSession:n,onNewSession:r,onDeleteSession:i,onRenameSession:s})=>{const[o,a]=J.useState(null),l=x.useCallback(h=>{n(h)},[n]),c=x.useCallback(h=>{a(h)},[]),u=x.useCallback(()=>{o&&(i(o),a(null))},[o,i]),d=x.useCallback(()=>{a(null)},[]),f=x.useCallback((h,m)=>{s(h,m)},[s]);return y.jsxs("div",{className:"session-list",children:[y.jsxs("div",{className:"session-list__header",children:[y.jsx("span",{className:"session-list__title",children:"会话列表"}),y.jsxs("button",{className:"session-list__new-btn","data-track":"chat_click_session_new",onClick:r,"aria-label":"新建会话",children:[y.jsx(dy,{size:14}),y.jsx("span",{children:"新建"})]})]}),y.jsx("div",{className:"session-list__items",children:e.length===0?y.jsx("div",{className:"session-list__empty",children:"暂无会话"}):e.map(h=>y.jsx(xne,{session:h,isActive:h.id===t,onSelect:()=>l(h.id),onDelete:()=>c(h.id),onRename:m=>f(h.id,m)},h.id))}),y.jsx(Jo,{visible:o!==null,header:"删除会话",onConfirm:u,onCancel:d,onClose:d,confirmBtn:"删除",cancelBtn:"取消",children:"确定删除此会话吗?删除后无法恢复。"})]})});bne.displayName="SessionList";const Cne=J.memo(({isOpen:e,onClick:t,drawerWidth:n})=>{const r=e&&n?{right:n-18}:void 0;return y.jsx(Di,{content:e?"收起对话":"展开对话",theme:"light",children:y.jsx("button",{className:`chat-drawer-trigger ${e?"chat-drawer-trigger--active":""}`,"data-track":e?"chat_click_drawer_close":"chat_click_drawer_open",onClick:t,"aria-label":e?"收起对话":"展开对话","aria-expanded":e,style:r,children:y.jsx(xS,{size:16,className:"chat-drawer-trigger__icon"})})})});Cne.displayName="ChatDrawerTrigger";var $c=(e=>(e.OPENAI="OPENAI",e.ANTHROPIC="ANTHROPIC",e.DEEPSEEK="DEEPSEEK",e.GOOGLE="GOOGLE",e))($c||{});const $z={OPENAI:"OpenAI",ANTHROPIC:"Anthropic",DEEPSEEK:"DeepSeek",GOOGLE:"Google"},XA=[{id:"gpt-image-1.5",name:"GPT Image 1.5",description:"OpenAI 最新图片生成模型",provider:"OPENAI",badges:["NEW","Multimodal"],maxTokens:128e3,supportsVision:!0},{id:"gpt-4o-image",name:"GPT-4o Image",description:"OpenAI 多模态图片模型",provider:"OPENAI",badges:["Multimodal"],maxTokens:128e3,supportsVision:!0},{id:"gpt-5.2",name:"GPT-5.2",description:"最新旗舰模型",provider:"OPENAI",badges:["NEW"],maxTokens:128e3},{id:"gpt-5.2-all",name:"GPT-5.2 All",description:"全功能版本",provider:"OPENAI",badges:["NEW"],maxTokens:128e3},{id:"gpt-5.1",name:"GPT-5.1",description:"旗舰模型",provider:"OPENAI",maxTokens:128e3},{id:"gpt-5.1-thinking",name:"GPT-5.1 Thinking",description:"推理增强版本",provider:"OPENAI",maxTokens:128e3},{id:"gpt-5.1-all",name:"GPT-5.1 All",description:"全功能版本",provider:"OPENAI",maxTokens:128e3},{id:"gpt-5",name:"GPT-5",description:"通用模型",provider:"OPENAI",maxTokens:128e3},{id:"gpt-5-all",name:"GPT-5 All",description:"全功能版本",provider:"OPENAI",maxTokens:128e3},{id:"gemini-3-pro-image-preview-2k",name:"Gemini 3 Pro Image Preview 2K",description:"Google 图片生成模型 (2K分辨率)",provider:"GOOGLE",badges:["NEW","Multimodal"],maxTokens:2e6,supportsVision:!0},{id:"gemini-3-pro-image-preview",name:"Gemini 3 Pro Image Preview",description:"Google 图片生成模型",provider:"GOOGLE",badges:["NEW","Multimodal"],maxTokens:2e6,supportsVision:!0},{id:"gemini-3-pro-preview",name:"Gemini 3 Pro Preview",description:"Google 最新预览版",provider:"GOOGLE",badges:["NEW"],maxTokens:2e6},{id:"gemini-3-pro-preview-thinking",name:"Gemini 3 Pro Preview Thinking",description:"推理增强版本",provider:"GOOGLE",maxTokens:2e6},{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",description:"专业版模型",provider:"GOOGLE",maxTokens:2e6},{id:"gemini-2.5-pro-all",name:"Gemini 2.5 Pro All",description:"全功能版本",provider:"GOOGLE",maxTokens:2e6},{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",description:"快速模型",provider:"GOOGLE",maxTokens:1e6},{id:"deepseek-v3.2",name:"DeepSeek V3.2",description:"最新版本",provider:"DEEPSEEK",badges:["NEW"],maxTokens:64e3},{id:"deepseek-v3.2-thinking",name:"DeepSeek V3.2 Thinking",description:"推理增强版本",provider:"DEEPSEEK",maxTokens:64e3},{id:"deepseek-v3.1",name:"DeepSeek V3.1",description:"稳定版本",provider:"DEEPSEEK",maxTokens:64e3},{id:"deepseek-v3",name:"DeepSeek V3",description:"通用模型",provider:"DEEPSEEK",maxTokens:64e3},{id:"deepseek-r1",name:"DeepSeek R1",description:"推理模型",provider:"DEEPSEEK",maxTokens:64e3},{id:"claude-opus-4-5-20251101",name:"Claude Opus 4.5",description:"Anthropic 旗舰模型",provider:"ANTHROPIC",badges:["NEW"],maxTokens:2e5},{id:"claude-sonnet-4-5-20250929",name:"Claude Sonnet 4.5",description:"平衡模型",provider:"ANTHROPIC",maxTokens:2e5},{id:"claude-sonnet-4-5-20250929-thinking",name:"Claude Sonnet 4.5 Thinking",description:"推理增强版本",provider:"ANTHROPIC",maxTokens:2e5}],oGe="gpt-5.1";function aGe(e){return XA.find(t=>t.id===e)}const zz=({provider:e,className:t="w-5 h-5"})=>{switch(e){case $c.GOOGLE:return y.jsxs("svg",{viewBox:"0 0 24 24",className:t,xmlns:"http://www.w3.org/2000/svg",children:[y.jsx("circle",{cx:"12",cy:"12",r:"10",fill:"#4285F4"}),y.jsx("text",{x:"12",y:"16",fontSize:"14",fontWeight:"700",fill:"white",textAnchor:"middle",fontFamily:"Arial, sans-serif",children:"G"})]});case $c.DEEPSEEK:return y.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",className:t,xmlns:"http://www.w3.org/2000/svg",children:[y.jsx("circle",{cx:"12",cy:"12",r:"10",fill:"#6366f1"}),y.jsx("path",{d:"M8 12L12 8L16 12L12 16L8 12Z",fill:"white"})]});case $c.OPENAI:return y.jsxs("svg",{viewBox:"0 0 24 24",className:t,xmlns:"http://www.w3.org/2000/svg",children:[y.jsx("circle",{cx:"12",cy:"12",r:"10",fill:"#10a37f"}),y.jsx("circle",{cx:"12",cy:"12",r:"4",fill:"white"})]});case $c.ANTHROPIC:return y.jsxs("svg",{viewBox:"0 0 24 24",className:t,xmlns:"http://www.w3.org/2000/svg",children:[y.jsx("circle",{cx:"12",cy:"12",r:"10",fill:"#D97757"}),y.jsx("path",{d:"M9 12h6M12 9v6",stroke:"white",strokeWidth:"2",strokeLinecap:"round"})]});default:return null}},lGe={NEW:"badge-new",Fast:"badge-fast",Multimodal:"badge-multimodal",Reasoning:"badge-reasoning",Pro:"badge-pro",Economic:"badge-economic"},Ene=J.memo(({className:e,value:t,onChange:n})=>{const[r,i]=x.useState(oGe),s=t??r,[o,a]=x.useState(!1),[l,c]=x.useState(""),u=x.useRef(null),d=x.useRef(null);x.useEffect(()=>{if(!o)return;const C=_=>{const T=_.target;u.current&&!u.current.contains(T)&&d.current&&!d.current.contains(T)&&(a(!1),c(""))},b=setTimeout(()=>{document.addEventListener("mousedown",C)},100);return()=>{clearTimeout(b),document.removeEventListener("mousedown",C)}},[o]);const f=x.useCallback(C=>{t===void 0&&i(C),n==null||n(C),a(!1),c("")},[t,n]),h=x.useCallback(()=>{a(C=>!C),o&&c("")},[o]),m=x.useMemo(()=>{if(!l.trim())return XA;const C=l.toLowerCase();return XA.filter(b=>b.name.toLowerCase().includes(C)||b.description.toLowerCase().includes(C)||$z[b.provider].toLowerCase().includes(C))},[l]),g=x.useMemo(()=>{const C={[$c.OPENAI]:[],[$c.ANTHROPIC]:[],[$c.DEEPSEEK]:[],[$c.GOOGLE]:[]};return m.forEach(b=>{C[b.provider].push(b)}),Object.entries(C).filter(([b,_])=>_.length>0)},[m]),w=aGe(s);return y.jsxs("div",{className:`model-selector ${e||""}`,children:[y.jsxs("button",{ref:d,className:`model-selector__trigger ${o?"model-selector__trigger--active":""}`,"data-track":"chat_click_model_selector",onClick:h,"aria-label":"选择模型","aria-expanded":o,children:[w&&y.jsx(zz,{provider:w.provider,className:"model-selector__trigger-icon-provider"}),y.jsx("span",{className:"model-selector__trigger-text",children:(w==null?void 0:w.name)||"选择模型"}),y.jsx(k3,{size:16,className:`model-selector__trigger-icon ${o?"model-selector__trigger-icon--open":""}`})]}),o&&y.jsxs("div",{ref:u,className:"model-selector__dropdown",children:[y.jsx("div",{className:"model-selector__search",children:y.jsx(oy,{value:l,onChange:c,placeholder:"搜索模型...",prefixIcon:y.jsx(A3,{}),clearable:!0,autofocus:!0})}),y.jsx("div",{className:"model-selector__list",children:g.length===0?y.jsx("div",{className:"model-selector__empty",children:"未找到匹配的模型"}):g.map(([C,b])=>y.jsxs("div",{className:"model-selector__group",children:[y.jsx("div",{className:"model-selector__group-header",children:$z[C]}),b.map(_=>y.jsxs("button",{className:`model-selector__item ${_.id===s?"model-selector__item--active":""}`,"data-track":"chat_click_model_select",onClick:()=>f(_.id),children:[y.jsx(zz,{provider:_.provider,className:"model-selector__item-icon"}),y.jsxs("div",{className:"model-selector__item-content",children:[y.jsxs("div",{className:"model-selector__item-header",children:[y.jsx("span",{className:"model-selector__item-name",children:_.name}),_.badges&&_.badges.length>0&&y.jsx("div",{className:"model-selector__badges",children:_.badges.map(T=>y.jsx("span",{className:`model-selector__badge ${lGe[T]}`,children:T},T))})]}),y.jsx("div",{className:"model-selector__item-desc",children:_.description})]}),_.id===s&&y.jsx("svg",{className:"model-selector__check",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:y.jsx("path",{d:"M13.3334 4L6.00002 11.3333L2.66669 8",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]},_.id))]},C))})]})]})});Ene.displayName="ModelSelector";const cGe=[{value:1,label:"1 张"},{value:2,label:"2 张"},{value:3,label:"3 张"},{value:4,label:"4 张"},{value:5,label:"5 张"},{value:10,label:"10 张"},{value:20,label:"20 张"}];function uGe(e){const{mode:t,keyword:n,selectedImageModel:r,selectedVideoModel:i,selectedParams:s,selectedCount:o,prompts:a=[],pendingParam:l}=e;return x.useMemo(()=>{if(l&&l.options)return fGe(n,l);switch(t){case"model":return dGe(n,r,i);case"param":return hGe(n,r,i,s);case"count":return pGe(n,o);case"prompt":return mGe(n,a);case"cold-start":return gGe(a);default:return[]}},[t,n,r,i,s,o,a,l])}function dGe(e,t,n){const r=e.toLowerCase().trim();let i=INe.filter(s=>!(s.type==="image"&&t||s.type==="video"&&n));return r&&(i=i.filter(s=>s.id.toLowerCase().includes(r)||s.label.toLowerCase().includes(r)||s.shortLabel&&s.shortLabel.toLowerCase().includes(r))),i.map(s=>({id:s.id,type:"model",label:s.label,shortLabel:s.shortLabel,description:s.description,modelType:s.type,modelConfig:s}))}function fGe(e,t){if(!t.options)return[];const n=e.toLowerCase().trim();let r=t.options;return n&&(r=r.filter(i=>i.value.toLowerCase().includes(n)||i.label.toLowerCase().includes(n))),r.map(i=>({id:`${t.id}=${i.value}`,type:"param",label:i.label,shortLabel:i.value,description:`${t.label}=${i.label}`,paramConfig:t,value:i.value}))}function hGe(e,t,n,r=[]){const i=e.toLowerCase().trim(),s=t||n,o=s?bo(s):null,a=o==null?void 0:o.type;let l;s?l=i3(s):a?l=yC.filter(u=>u.modelType===a):l=yC;const c=r.map(u=>u.id.toLowerCase());return l=l.filter(u=>!c.includes(u.id.toLowerCase())),l=l.filter(u=>!u.options||u.options.length>1),i&&(l=l.filter(u=>u.id.toLowerCase().includes(i)||u.label.toLowerCase().includes(i)||u.shortLabel&&u.shortLabel.toLowerCase().includes(i))),l.map(u=>({id:u.id,type:"param",label:u.label,shortLabel:u.shortLabel,description:u.description,paramConfig:u}))}function pGe(e,t){const n=e.trim();if(t!==void 0)return[];let r=cGe;return n&&(r=r.filter(i=>i.label.includes(n)||i.value.toString()===n)),r.map(i=>({id:`count-${i.value}`,type:"count",label:i.label,shortLabel:`${i.value}`,value:i.value}))}function gGe(e){return e.map(t=>({id:t.id,type:"cold-start",label:t.content,shortLabel:t.content,description:t.scene||"",content:t.content,scene:t.scene,tips:t.tips}))}function mGe(e,t){const n=e.toLowerCase().trim();let r=t;return n&&(r=t.filter(i=>{const s=i.content.toLowerCase();return s===n?!1:s.includes(n)})),r.map(i=>({id:i.id,type:"prompt",label:i.content,shortLabel:i.content,description:i.source==="history"?"历史记录":"推荐提示词",source:i.source,content:i.content,scene:i.scene,tips:i.tips,timestamp:i.timestamp}))}function S0(e,t,n){if(n){const i=n.shortLabel||n.label;return t==="zh"?`选择 ${i}`:`Select ${i}`}return e&&{model:t==="zh"?"选择模型":"Select Model",param:t==="zh"?"选择参数":"Select Parameter",count:t==="zh"?"生成数量":"Select Count",prompt:t==="zh"?"提示词":"Prompts","cold-start":t==="zh"?"试试这些创意":"Try these ideas"}[e]||""}function Hz(e){switch(e){case"model":return y.jsx(XJ,{size:16});case"param":return y.jsx(uNe,{size:16});case"count":return y.jsx(iNe,{size:16});case"prompt":return y.jsx(Fg,{size:16});case"cold-start":return y.jsx(fNe,{size:16});default:return null}}function Wz(e){return e==="zh"?"↑↓选择 Tab确认":"↑↓ to select, Tab to confirm"}const Gz=({item:e,isHighlighted:t,onSelect:n,onMouseEnter:r})=>{const i=(e.type==="cold-start"||e.type==="prompt")&&(e.scene||e.tips);return y.jsx("div",{className:`smart-suggestion-panel__item smart-suggestion-panel__item--card ${t?"smart-suggestion-panel__item--highlighted":""}`,onClick:()=>n(e),onMouseEnter:r,children:y.jsxs("div",{className:"smart-suggestion-panel__item-content",children:[y.jsx("span",{className:"smart-suggestion-panel__item-text",children:e.shortLabel||e.label}),i&&y.jsxs("div",{className:"smart-suggestion-panel__item-meta",children:[e.scene&&y.jsx("span",{className:"smart-suggestion-panel__item-scene",children:e.scene}),e.tips&&y.jsx("span",{className:"smart-suggestion-panel__item-tips",children:e.tips})]})]})})},vGe=({visible:e,mode:t,filterKeyword:n,selectedImageModel:r,selectedVideoModel:i,selectedParams:s,selectedCount:o,prompts:a=[],selectionHistoryPrompts:l=[],onSelectModel:c,onSelectParam:u,onSelectCount:d,onSelectPrompt:f,onDeleteHistory:h,onClose:m,language:g="zh"})=>{var H,L,V,Y;const w=x.useRef(null),[C,b]=x.useState(0),[_,T]=x.useState(null),[S,k]=x.useState("");x.useEffect(()=>{(!e||t!=="param")&&(T(null),k(""))},[e,t]);const D=uGe({mode:t,keyword:_?S:n,selectedImageModel:r,selectedVideoModel:i,selectedParams:s,selectedCount:o,prompts:a,pendingParam:_||void 0});x.useEffect(()=>{if(t==="param"&&!_&&D.length===1){const q=D[0];q.type==="param"&&q.paramConfig.options&&q.paramConfig.options.length>0&&(T(q.paramConfig),k(""),b(0))}},[t,D,_]);const{historyPrompts:O,presetPrompts:I,coldStartSuggestions:R,coldStartHistoryPrompts:F,modelModeHistoryPrompts:M}=x.useMemo(()=>{if(t==="cold-start"){const re=D.filter(ee=>ee.type==="cold-start"),ae=new Set(a.filter(ee=>ee.source==="history").map(ee=>ee.id)),de=re.filter(ee=>ae.has(ee.id)),oe=re.filter(ee=>!ae.has(ee.id));return{historyPrompts:[],presetPrompts:[],coldStartSuggestions:oe,coldStartHistoryPrompts:de,modelModeHistoryPrompts:[]}}if(t==="model"){const re=l.filter(ae=>{const de=ae.content.trim();return!/^#[\w.-]+$/.test(de)}).map(ae=>({id:ae.id,type:"prompt",label:ae.content,shortLabel:ae.content,description:"",source:"history",content:ae.content,timestamp:ae.timestamp}));return{historyPrompts:[],presetPrompts:[],coldStartSuggestions:[],coldStartHistoryPrompts:[],modelModeHistoryPrompts:re}}if(t!=="prompt")return{historyPrompts:[],presetPrompts:[],coldStartSuggestions:[],coldStartHistoryPrompts:[],modelModeHistoryPrompts:[]};const q=D.filter(re=>re.type==="prompt"&&re.source==="history"),Z=D.filter(re=>re.type==="prompt"&&re.source==="preset");return{historyPrompts:q,presetPrompts:Z,coldStartSuggestions:[],coldStartHistoryPrompts:[],modelModeHistoryPrompts:[]}},[t,D,l,a]),$=x.useMemo(()=>t==="prompt"||t==="cold-start"?[]:D,[t,D]),A=x.useMemo(()=>t==="cold-start"?[...F,...R]:t==="prompt"?[...O,...I]:t==="model"?[...M,...$]:$,[t,O,I,$,R,F,M]);x.useEffect(()=>{b(0)},[A.length,t]);const z=x.useCallback(q=>{switch(q.type){case"model":c(q.id);break;case"param":q.value?(u(q.paramConfig.id,q.value),T(null),k("")):q.paramConfig.options&&q.paramConfig.options.length>0?(T(q.paramConfig),k(""),b(0)):u(q.paramConfig.id);break;case"count":d(q.value);break;case"prompt":f==null||f({id:q.id,content:q.content,source:q.source,timestamp:q.timestamp});break;case"cold-start":f==null||f({id:q.id,content:q.content,source:"preset"});break}},[c,u,d,f]);x.useEffect(()=>{if(!e)return;const q=Z=>{if(A.length===0){Z.key==="Escape"&&(Z.preventDefault(),Z.stopPropagation(),m());return}switch(Z.key){case"ArrowUp":Z.preventDefault(),Z.stopPropagation(),b(re=>re<=0?A.length-1:re-1);break;case"ArrowDown":Z.preventDefault(),Z.stopPropagation(),b(re=>re>=A.length-1?0:re+1);break;case"Tab":Z.preventDefault(),Z.stopPropagation(),A[C]&&z(A[C]);break;case"Escape":Z.preventDefault(),Z.stopPropagation(),m();break}};return document.addEventListener("keydown",q,!0),()=>document.removeEventListener("keydown",q,!0)},[e,A,C,z,m]),x.useEffect(()=>{var Z;if(!e||A.length===0)return;const q=(Z=w.current)==null?void 0:Z.querySelector(".smart-suggestion-panel__item--highlighted");q&&q.scrollIntoView({block:"nearest",behavior:"smooth"})},[C,e,A.length]);const G=x.useCallback((q,Z)=>{q.stopPropagation(),h==null||h(Z)},[h]),W=x.useCallback((q,Z)=>q==="history"?Z:O.length+Z,[O.length]);if(!e||!t)return null;if(t==="model"&&!!r&&!!i)return y.jsxs("div",{ref:w,className:"smart-suggestion-panel",role:"dialog","aria-label":g==="zh"?"模型已选择":"Models Selected",onMouseDown:q=>q.preventDefault(),children:[y.jsxs("div",{className:"smart-suggestion-panel__header",children:[y.jsx(XJ,{size:16}),y.jsx("span",{children:g==="zh"?"模型已选择":"Models Selected"})]}),y.jsxs("div",{className:"smart-suggestion-panel__complete-message",children:[y.jsxs("div",{className:"smart-suggestion-panel__selected-models",children:[y.jsxs("div",{className:"smart-suggestion-panel__selected-item",children:[y.jsx(sh,{size:14}),y.jsxs("span",{className:"smart-suggestion-panel__selected-label",children:[g==="zh"?"图片":"Image",":"]}),y.jsx("span",{className:"smart-suggestion-panel__selected-name",children:((H=bo(r))==null?void 0:H.shortLabel)||((L=bo(r))==null?void 0:L.label)||r}),y.jsx(rg,{size:14,className:"smart-suggestion-panel__selected-check"})]}),y.jsxs("div",{className:"smart-suggestion-panel__selected-item",children:[y.jsx(oh,{size:14}),y.jsxs("span",{className:"smart-suggestion-panel__selected-label",children:[g==="zh"?"视频":"Video",":"]}),y.jsx("span",{className:"smart-suggestion-panel__selected-name",children:((V=bo(i))==null?void 0:V.shortLabel)||((Y=bo(i))==null?void 0:Y.label)||i}),y.jsx(rg,{size:14,className:"smart-suggestion-panel__selected-check"})]})]}),y.jsx("p",{className:"smart-suggestion-panel__hint-text",children:g==="zh"?"已选择图片和视频模型,无需再指定其他模型":"Image and video models selected, no need to specify more"})]})]});if(A.length===0)return null;if(t==="cold-start"){const q=F.length>0;return y.jsx("div",{ref:w,className:"smart-suggestion-panel smart-suggestion-panel--cold-start",role:"listbox","aria-label":S0(t,g),onMouseDown:Z=>Z.preventDefault(),children:y.jsxs("div",{className:"smart-suggestion-panel__content",children:[q&&y.jsxs("div",{className:"smart-suggestion-panel__section",children:[y.jsxs("div",{className:"smart-suggestion-panel__section-header",children:[y.jsx(Jx,{size:14}),y.jsx("span",{children:g==="zh"?"历史记录":"History"})]}),y.jsx("div",{className:"smart-suggestion-panel__list",style:{maxHeight:"150px",overflowY:"auto"},children:F.map((Z,re)=>y.jsxs("div",{className:`smart-suggestion-panel__item smart-suggestion-panel__item--history ${re===C?"smart-suggestion-panel__item--highlighted":""}`,onClick:()=>z(Z),onMouseEnter:()=>b(re),title:Z.label,children:[y.jsx("span",{className:"smart-suggestion-panel__item-text",children:Z.shortLabel||Z.label}),h&&y.jsx("button",{className:"smart-suggestion-panel__item-delete",onClick:ae=>G(ae,Z.id),title:g==="zh"?"删除":"Delete",children:y.jsx(ig,{size:12})})]},Z.id))})]}),R.length>0&&y.jsxs("div",{className:"smart-suggestion-panel__section",children:[y.jsxs("div",{className:"smart-suggestion-panel__section-header",children:[Hz(t),y.jsx("span",{children:S0(t,g)}),y.jsx("span",{className:"smart-suggestion-panel__hint",children:Wz(g)})]}),y.jsx("div",{className:"smart-suggestion-panel__list smart-suggestion-panel__list--cold-start",children:R.map((Z,re)=>{const ae=F.length+re;return y.jsx(Gz,{item:Z,isHighlighted:ae===C,onSelect:z,onMouseEnter:()=>b(ae)},Z.id)})})]})]})})}if(t==="prompt")return y.jsx("div",{ref:w,className:"smart-suggestion-panel smart-suggestion-panel--prompt",role:"listbox","aria-label":S0(t,g),onMouseDown:q=>q.preventDefault(),children:y.jsxs("div",{className:"smart-suggestion-panel__content",children:[O.length>0&&y.jsxs("div",{className:"smart-suggestion-panel__section",children:[y.jsxs("div",{className:"smart-suggestion-panel__section-header",children:[y.jsx(Jx,{size:14}),y.jsx("span",{children:g==="zh"?"历史记录":"History"})]}),y.jsx("div",{className:"smart-suggestion-panel__list",style:{maxHeight:"150px",overflowY:"auto"},children:O.map((q,Z)=>y.jsxs("div",{className:`smart-suggestion-panel__item smart-suggestion-panel__item--history ${W("history",Z)===C?"smart-suggestion-panel__item--highlighted":""}`,onClick:()=>z(q),onMouseEnter:()=>b(W("history",Z)),title:q.label,children:[y.jsx("span",{className:"smart-suggestion-panel__item-text",children:q.shortLabel||q.label}),h&&y.jsx("button",{className:"smart-suggestion-panel__item-delete",onClick:re=>G(re,q.id),title:g==="zh"?"删除":"Delete",children:y.jsx(ig,{size:12})})]},q.id))})]}),I.length>0&&y.jsxs("div",{className:"smart-suggestion-panel__section",children:[y.jsxs("div",{className:"smart-suggestion-panel__section-header",children:[y.jsx(Fg,{size:14}),y.jsx("span",{children:g==="zh"?"推荐指令":"Suggestions"})]}),y.jsx("div",{className:"smart-suggestion-panel__list",children:I.map((q,Z)=>y.jsx(Gz,{item:q,isHighlighted:W("preset",Z)===C,onSelect:z,onMouseEnter:()=>b(W("preset",Z))},q.id))})]})]})});const j=M.length>0;return y.jsx("div",{ref:w,className:`smart-suggestion-panel smart-suggestion-panel--${t}${_?" smart-suggestion-panel--enum-values":""}${j?" smart-suggestion-panel--with-history":""}`,role:"listbox","aria-label":S0(t,g,_),onMouseDown:q=>q.preventDefault(),children:y.jsxs("div",{className:"smart-suggestion-panel__content",children:[j&&y.jsxs("div",{className:"smart-suggestion-panel__section",children:[y.jsxs("div",{className:"smart-suggestion-panel__section-header",children:[y.jsx(Jx,{size:14}),y.jsx("span",{children:g==="zh"?"历史记录":"History"})]}),y.jsx("div",{className:"smart-suggestion-panel__list",style:{maxHeight:"150px",overflowY:"auto"},children:M.map((q,Z)=>{const re=C===Z;return y.jsxs("div",{className:`smart-suggestion-panel__item smart-suggestion-panel__item--history ${re?"smart-suggestion-panel__item--highlighted":""}`,onClick:()=>z(q),onMouseEnter:()=>b(Z),title:q.label,children:[y.jsx("span",{className:"smart-suggestion-panel__item-text",children:q.shortLabel||q.label}),h&&y.jsx("button",{className:"smart-suggestion-panel__item-delete",onClick:ae=>G(ae,q.id),title:g==="zh"?"删除":"Delete",children:y.jsx(ig,{size:12})})]},q.id)})})]}),y.jsxs("div",{className:"smart-suggestion-panel__section",children:[y.jsxs("div",{className:"smart-suggestion-panel__section-header",children:[Hz(t),y.jsx("span",{children:S0(t,g,_)}),y.jsx("span",{className:"smart-suggestion-panel__hint",children:Wz(g)})]}),y.jsx("div",{className:"smart-suggestion-panel__list",children:$.map((q,Z)=>{const re=j?M.length+Z:Z,ae=C===re,de=`${q.type}-${q.id}-${Z}`;return y.jsxs("div",{className:`smart-suggestion-panel__item smart-suggestion-panel__item--${q.type} ${ae?"smart-suggestion-panel__item--highlighted":""}`,onClick:()=>z(q),onMouseEnter:()=>b(re),role:"option","aria-selected":ae,children:[y.jsxs("div",{className:"smart-suggestion-panel__item-content",children:[y.jsxs("div",{className:"smart-suggestion-panel__item-name",children:[q.type==="model"&&y.jsxs(y.Fragment,{children:[y.jsxs("span",{className:`smart-suggestion-panel__item-id smart-suggestion-panel__item-id--${q.modelType}`,children:["#",q.id]}),y.jsx("span",{className:"smart-suggestion-panel__item-label",children:q.shortLabel||q.label}),y.jsxs("span",{className:`smart-suggestion-panel__item-type smart-suggestion-panel__item-type--${q.modelType}`,children:[q.modelType==="image"?y.jsx(sh,{size:12}):y.jsx(oh,{size:12}),q.modelType==="image"?g==="zh"?"图片":"Image":g==="zh"?"视频":"Video"]})]}),q.type==="param"&&y.jsxs(y.Fragment,{children:[y.jsxs("span",{className:"smart-suggestion-panel__item-id smart-suggestion-panel__item-id--param",children:["-",q.value?`${q.paramConfig.id}:${q.value}`:q.id]}),y.jsx("span",{className:"smart-suggestion-panel__item-label",children:q.label})]}),q.type==="count"&&y.jsx(y.Fragment,{children:y.jsx("span",{className:"smart-suggestion-panel__item-label",children:q.label})})]}),q.description&&y.jsx("div",{className:"smart-suggestion-panel__item-desc",children:q.description})]}),q.type==="count"&&ae&&y.jsx(rg,{size:16,className:"smart-suggestion-panel__item-check"})]},de)})})]})]})})};function yGe(e,t=!1){return x.useMemo(()=>Sne(e,t),[e,t])}function Sne(e,t=!1){const n=[];let r="",i,s;const o=[];let a;const l=ONe(),c=NNe(),u=/(#[\w.-]+)|(-[\w]+(?:=[\w:x.]+)?)|(\+\d+)/g;let d,f=0;const h=[];for(;(d=u.exec(e))!==null;){const C=d[0],b=d.index,_=b+C.length;if(C.startsWith("#")){const T=C.substring(1),S=l.find(k=>k.toLowerCase()===T.toLowerCase());if(S){const k=r3(S);if(k==="image"&&!i){i=S;const D=bo(S);h.push({start:b,end:_,type:"image-model",id:S,displayName:`#${(D==null?void 0:D.shortLabel)||(D==null?void 0:D.label)||S}`})}else if(k==="video"&&!s){s=S;const D=bo(S);h.push({start:b,end:_,type:"video-model",id:S,displayName:`#${(D==null?void 0:D.shortLabel)||(D==null?void 0:D.label)||S}`})}}}else if(C.startsWith("-")){const T=C.substring(1),S=T.indexOf("="),k=S>0?T.substring(0,S):T,D=S>0?T.substring(S+1):void 0,O=c.some(R=>R.toLowerCase()===k.toLowerCase()),I=o.some(R=>R.id.toLowerCase()===k.toLowerCase());O&&!I&&D&&(o.push({id:k,value:D}),h.push({start:b,end:_,type:"param",id:k,value:D,displayName:`-${k}=${D}`}))}else if(C.startsWith("+")){const T=C.substring(1),S=parseInt(T,10);!isNaN(S)&&S>0&&S<=10&&!a&&(a=S,h.push({start:b,end:_,type:"count",id:"count",value:T,displayName:`+${S}`}))}}f=0,h.sort((C,b)=>C.start-b.start);for(const C of h){if(C.start>f){const _=e.substring(f,C.start);n.push({type:"text",content:_}),_.trim()&&(r+=_)}const b=e.substring(C.start,C.end);n.push({type:C.type,content:b,displayName:C.displayName,id:C.id,value:C.value}),f=C.end}if(f<e.length){const C=e.substring(f);n.push({type:"text",content:C}),C.trim()&&(r+=C)}r=r.trim();const{mode:m,keyword:g,triggerPosition:w}=wGe(e,h,l,c,i,s,o,a,t);return{mode:m,keyword:g,triggerPosition:w,selectedImageModel:i,selectedVideoModel:s,selectedParams:o,selectedCount:a,cleanText:r,segments:n.length>0?n:[{type:"text",content:e}]}}function wGe(e,t,n,r,i,s,o,a,l=!1){const c=e.lastIndexOf("#");if(c!==-1&&!t.some(h=>c>=h.start&&c<h.end)){const h=e.substring(c+1);if(h.indexOf(" ")===-1&&!(!!i&&!!s))return{mode:"model",keyword:h,triggerPosition:c}}const u=e.lastIndexOf("-");if(u!==-1&&!t.some(h=>u>=h.start&&u<h.end)){const h=e.substring(u+1);if(h.indexOf(" ")===-1)return h.indexOf("=")===-1?{mode:"param",keyword:h,triggerPosition:u}:{mode:"param",keyword:h,triggerPosition:u}}const d=e.lastIndexOf("+");if(d!==-1&&!t.some(h=>d>=h.start&&d<h.end)){const h=e.substring(d+1);if(h.indexOf(" ")===-1)return{mode:"count",keyword:h,triggerPosition:d}}return l?!!i||!!s?o&&o.length>0?a?{mode:"prompt",keyword:e,triggerPosition:void 0}:{mode:"count",keyword:"",triggerPosition:void 0}:{mode:"param",keyword:"",triggerPosition:void 0}:{mode:"model",keyword:"",triggerPosition:void 0}:{mode:null,keyword:"",triggerPosition:void 0}}function rk(e,t,n,r="#"){if(n!==void 0){const a=e.substring(0,n),l=e.substring(n+1),c=l.indexOf(" "),u=c===-1?"":l.substring(c);return`${a}${r}${t}${u||" "}`.trimEnd()+" "}const i=`${r}${t}`,s=xGe(e);let o="";return r==="#"?(o=i,s.models&&(o+=" "+s.models),s.params&&(o+=" "+s.params),s.count&&(o+=" "+s.count),s.prompt&&(o+=" "+s.prompt)):r==="-"?(s.models&&(o=s.models+" "),o+=i,s.params&&(o+=" "+s.params),s.count&&(o+=" "+s.count),s.prompt&&(o+=" "+s.prompt)):r==="+"&&(s.models&&(o=s.models+" "),s.params&&(o+=s.params+" "),o+=i,s.count&&(o+=" "+s.count),s.prompt&&(o+=" "+s.prompt)),o.trim()+" "}function xGe(e){const t=[],n=[];let r="";const i=[],s=e.split(/\s+/).filter(o=>o);for(const o of s)o.startsWith("#")?t.push(o):o.startsWith("-")&&o.includes("=")?n.push(o):o.startsWith("+")&&/^\+\d+$/.test(o)?r=o:(o.startsWith("-"),i.push(o));return{models:t.join(" "),params:n.join(" "),count:r,prompt:i.join(" ")}}const ik={model:"#",param:"-",count:"+"},_ne=({items:e,language:t="zh",enableHoverPreview:n=!0,className:r,onRemove:i,removableStartIndex:s=0})=>{const[o,a]=x.useState(null),l=x.useCallback((u,d)=>{if(!n)return;const f=d.currentTarget.getBoundingClientRect(),h=f.left+f.width/2,m=f.top-10;a({type:u.type,url:u.url,text:u.text,x:h,y:m})},[n]),c=x.useCallback(()=>{a(null)},[]);return e.length===0?null:y.jsxs(y.Fragment,{children:[n&&o&&wf.createPortal(y.jsxs("div",{className:`selected-content-preview__hover selected-content-preview__hover--${o.type}`,style:{left:`${o.x}px`,top:`${o.y}px`,transform:"translate(-50%, -100%)"},children:[(o.type==="image"||o.type==="graphics")&&o.url&&y.jsx("img",{src:o.url,alt:"Preview"}),o.type==="video"&&o.url&&y.jsx("div",{className:"selected-content-preview__hover-video",children:y.jsx("video",{src:o.url,controls:!0,autoPlay:!0,muted:!0,loop:!0,playsInline:!0})}),o.type==="text"&&o.text&&y.jsxs("div",{className:"selected-content-preview__hover-text",children:[y.jsxs("div",{className:"selected-content-preview__hover-text-header",children:[y.jsx(P9,{size:16}),y.jsx("span",{children:t==="zh"?"文字内容":"Text Content"})]}),y.jsx("div",{className:"selected-content-preview__hover-text-content",children:o.text})]})]}),document.body),y.jsx("div",{className:`selected-content-preview ${r||""}`,children:e.map((u,d)=>{const f=i&&d<s;return y.jsxs("div",{className:`selected-content-preview__item selected-content-preview__item--${u.type}`,onMouseEnter:h=>l(u,h),onMouseLeave:c,children:[u.type==="text"?y.jsxs("div",{className:"selected-content-preview__text",children:[y.jsx(P9,{size:14,className:"selected-content-preview__text-icon"}),y.jsx("span",{className:"selected-content-preview__text-content",children:u.text&&u.text.length>20?`${u.text.substring(0,20)}...`:u.text})]}):u.type==="video"?y.jsxs(y.Fragment,{children:[y.jsx("div",{className:"selected-content-preview__video-placeholder",children:y.jsx(oh,{size:20})}),y.jsx("div",{className:"selected-content-preview__video-overlay",children:y.jsx(nNe,{size:16,fill:"white"})})]}):y.jsx("img",{src:u.url,alt:u.name}),u.type==="graphics"&&y.jsx("span",{className:"selected-content-preview__label",children:t==="zh"?"图形":"Graphics"}),u.type==="video"&&y.jsx("span",{className:"selected-content-preview__label selected-content-preview__label--video",children:t==="zh"?"视频":"Video"}),f&&y.jsx("button",{className:"selected-content-preview__remove-btn",onClick:h=>{h.stopPropagation(),i(d)},onMouseDown:h=>h.preventDefault(),title:t==="zh"?"移除":"Remove",children:y.jsx(ig,{size:12})})]},`${u.type}-${d}`)})})]})};function G0(e){return e.tagName==="TEXTAREA"||e.tagName==="INPUT"}function bGe(e){const t=e.selectionStart||0,n=e.selectionEnd||0;return e.value.substring(t,n)}function Tne(e){const t=window.getSelection();if(!t||t.rangeCount===0)return"";const n=t.getRangeAt(0);return e.contains(n.commonAncestorContainer)?t.toString():""}function sk(e){return G0(e)?bGe(e):Tne(e)}function B3(e,t={}){const{enableCopy:n=!0,stopPropagation:r=!0}=t,i=x.useRef(null);return x.useEffect(()=>{const s=e.current;if(!s)return;const o=g=>!g||!(g instanceof HTMLElement)?!1:!!(["BUTTON","A","INPUT","SELECT","TEXTAREA","LABEL"].includes(g.tagName)||g.onclick||g.getAttribute("role")==="button"||g.closest('button, a, [role="button"], [onclick]')),a=()=>{const g=window.getSelection();return g!==null&&g.toString().length>0},l=g=>{r&&(o(g.target)||a()&&g.stopPropagation())},c=g=>{r&&(o(g.target)||g.stopPropagation())},u=g=>{const w=(g.ctrlKey||g.metaKey)&&g.key==="c",C=(g.ctrlKey||g.metaKey)&&g.key==="x";if(n&&(w||C)){const b=sk(s);b&&navigator.clipboard.writeText(b).then(()=>{}).catch(_=>{console.error("Failed to copy text:",_);try{document.execCommand("copy")}catch(T){console.error("execCommand copy also failed:",T)}}),r&&g.stopPropagation()}},d=g=>{if(n){const w=sk(s);w&&g.clipboardData&&(g.clipboardData.setData("text/plain",w),g.preventDefault())}r&&g.stopPropagation()},f=g=>{if(n){const w=sk(s);w&&g.clipboardData&&g.clipboardData.setData("text/plain",w)}r&&g.stopPropagation()},h=()=>{if(G0(s)){const g=s.selectionStart||0,w=s.selectionEnd||0;g!==w&&(i.current={text:s.value.substring(g,w),start:g,end:w})}else{const g=Tne(s);g&&(i.current={text:g})}},m=()=>{G0(s)||h()};return s.addEventListener("pointerdown",c),s.addEventListener("mousedown",c),s.addEventListener("pointerup",l),s.addEventListener("pointermove",l),s.addEventListener("mouseup",l),s.addEventListener("click",l),s.addEventListener("keydown",u),s.addEventListener("copy",d),s.addEventListener("cut",f),G0(s)?s.addEventListener("select",h):document.addEventListener("selectionchange",m),()=>{s.removeEventListener("pointerdown",c),s.removeEventListener("mousedown",c),s.removeEventListener("pointerup",l),s.removeEventListener("pointermove",l),s.removeEventListener("mouseup",l),s.removeEventListener("click",l),s.removeEventListener("keydown",u),s.removeEventListener("copy",d),s.removeEventListener("cut",f),G0(s)?s.removeEventListener("select",h):document.removeEventListener("selectionchange",m)}},[e,n,r]),{lastSelection:i.current}}function CGe(e){const{hasSelection:t=!1,passiveOnly:n=!1,inputRef:r,containerRef:i}=e,[s,o]=x.useState(""),[a,l]=x.useState(!1),c=yGe(s,t),{mode:u,triggerPosition:d}=c;B3(r,{enableCopy:!0,stopPropagation:!0}),x.useEffect(()=>{n?l(!!(u&&d!==void 0)):u&&u!=="prompt"?l(!0):t||l(!1)},[u,d,t,n]),x.useEffect(()=>{if(!i)return;const C=b=>{i.current&&!i.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[i]);const f=x.useCallback(C=>{var _;const b=rk(s,C,d,ik.model);o(b),(_=r.current)==null||_.focus()},[s,d,r]),h=x.useCallback((C,b)=>{var S;const _=b?`${C}=${b}`:C,T=rk(s,_,d,ik.param);o(T),(S=r.current)==null||S.focus()},[s,d,r]),m=x.useCallback(C=>{var _;const b=rk(s,String(C),d,ik.count);o(b),(_=r.current)==null||_.focus()},[s,d,r]),g=x.useCallback(C=>{var b;o(_=>_+C.content),(b=r.current)==null||b.focus(),l(!1)},[r]),w=x.useCallback(()=>{l(!1)},[]);return{input:s,setInput:o,showSuggestion:a,setShowSuggestion:l,parseResult:c,handleSelectModel:f,handleSelectParam:h,handleSelectCount:m,handleSelectPrompt:g,handleCloseSuggestion:w}}const kne=x.forwardRef(({selectedContent:e,onSend:t,disabled:n=!1,placeholder:r="输入消息..."},i)=>{const s=x.useRef(null),o=x.useRef(null),a=e.length>0,{addHistory:l}=pS(),{input:c,setInput:u,showSuggestion:d,parseResult:f,handleSelectModel:h,handleSelectParam:m,handleSelectCount:g,handleSelectPrompt:w,handleCloseSuggestion:C}=CGe({hasSelection:a,passiveOnly:!0,inputRef:s,containerRef:o}),{mode:b,keyword:_}=f;x.useImperativeHandle(i,()=>({setContent:I=>{var R;u(I),(R=s.current)==null||R.focus()},getContent:()=>c,focus:()=>{var I;return(I=s.current)==null?void 0:I.focus()}}),[c,u]);const T=x.useCallback(()=>{const I=c.trim();if(!I&&e.length===0)return;const R=[];I&&R.push({type:"text",text:I}),e.forEach((M,$)=>{M.type==="image"||M.type==="graphics"?R.push({type:"data-file",data:{filename:`${M.type}-${$+1}.png`,mediaType:"image/png",url:M.url||""}}):M.type==="video"&&R.push({type:"data-file",data:{filename:`video-${$+1}.mp4`,mediaType:"video/mp4",url:M.url||""}})});const F={id:`msg_${Date.now()}`,role:"user",parts:R};I&&l(I,a),t(F),u("")},[c,e,t,u,l,a]),S=x.useCallback(I=>{I.nativeEvent.isComposing||(I.key==="Enter"&&!I.shiftKey?(I.preventDefault(),T()):I.key==="Escape"&&C())},[T,C]);x.useEffect(()=>{s.current&&(s.current.style.height="auto",s.current.style.height=`${Math.min(s.current.scrollHeight,120)}px`)},[c]);const k=()=>e.length===0?null:y.jsx("div",{className:"enhanced-chat-input__selection",children:y.jsx(_ne,{items:e,language:"zh",enableHoverPreview:!0})}),D=()=>{const{segments:I}=f;return!I||!I.some(R=>R.type!=="text")?null:y.jsx("div",{className:"enhanced-chat-input__highlight-layer","aria-hidden":"true",children:I.map((R,F)=>{if(R.type==="text")return y.jsx("span",{className:"enhanced-chat-input__highlight-text",children:R.content},F);let M="";switch(R.type){case"image-model":M="enhanced-chat-input__highlight-tag--image";break;case"video-model":M="enhanced-chat-input__highlight-tag--video";break;case"param":M="enhanced-chat-input__highlight-tag--param";break;case"count":M="enhanced-chat-input__highlight-tag--count";break}return y.jsx("span",{className:`enhanced-chat-input__highlight-tag ${M}`,children:R.content},F)})})},O=(c.trim()||e.length>0)&&!n;return y.jsxs("div",{className:"enhanced-chat-input",ref:o,children:[k(),y.jsxs("div",{className:"enhanced-chat-input__form",children:[y.jsxs("div",{className:"enhanced-chat-input__input-wrapper",children:[D(),y.jsx("textarea",{ref:s,className:"enhanced-chat-input__textarea",value:c,onChange:I=>u(I.target.value),onKeyDown:S,placeholder:a?"描述你想要的效果... (可用 # 指定模型)":r,disabled:n,rows:4})]}),y.jsx("button",{className:`enhanced-chat-input__send ${O?"enhanced-chat-input__send--active":""}`,onClick:T,disabled:!O,"aria-label":"发送",children:y.jsx(Qte,{size:20})})]}),d&&b&&y.jsx(vGe,{visible:d,mode:b,filterKeyword:_,selectedImageModel:f.selectedImageModel,selectedVideoModel:f.selectedVideoModel,selectedParams:f.selectedParams,selectedCount:f.selectedCount,onSelectModel:h,onSelectParam:m,onSelectCount:g,onSelectPrompt:w,onClose:C})]})});kne.displayName="EnhancedChatInput";const bv={MAX_TITLE_LENGTH:30,DRAWER_MIN_WIDTH:320,DRAWER_MAX_WIDTH:500,DRAWER_DEFAULT_WIDTH_RATIO:.3},uh={DRAWER_STATE:"aitu:chat:drawer-state",ACTIVE_SESSION:"aitu:chat:active-session",DATABASE_NAME:"aitu-chat",SESSIONS_STORE:"sessions",MESSAGES_STORE:"messages"},_m=pi.createInstance({name:uh.DATABASE_NAME,storeName:uh.SESSIONS_STORE}),bd=pi.createInstance({name:uh.DATABASE_NAME,storeName:uh.MESSAGES_STORE});function Pne(){return crypto.randomUUID()}function EGe(e){const t=e.trim().replace(/\n/g," ");return t.length<=bv.MAX_TITLE_LENGTH?t:t.slice(0,bv.MAX_TITLE_LENGTH-3)+"..."}async function SGe(){const e=Date.now(),t={id:Pne(),title:"新对话",createdAt:e,updatedAt:e,messageCount:0};return await _m.setItem(t.id,t),t}async function TS(e){return _m.getItem(e)}async function _Ge(){const e=[];return await _m.iterate(t=>{e.push(t)}),await new Promise(t=>{typeof window<"u"&&"requestIdleCallback"in window?window.requestIdleCallback(()=>t(),{timeout:50}):setTimeout(t,0)}),e.sort((t,n)=>n.updatedAt-t.updatedAt)}async function L3(e,t){const n=await TS(e);if(n){const r={...n,...t,updatedAt:Date.now()};await _m.setItem(e,r)}}async function TGe(e){const t=await Ane(e);for(const n of t)await bd.removeItem(n.id);await _m.removeItem(e)}async function kGe(e){await bd.setItem(e.id,e);const t=await TS(e.sessionId);if(t){const n={messageCount:t.messageCount+1,updatedAt:Date.now()};await L3(e.sessionId,n)}}async function Ane(e){const t=[];return await bd.iterate(n=>{n.sessionId===e&&t.push(n)}),t.sort((n,r)=>n.timestamp-r.timestamp)}async function PGe(e,t){const n=await bd.getItem(e);if(n){const r={...n,...t};await bd.setItem(e,r)}}async function AGe(e){const t=await bd.getItem(e);if(t){await bd.removeItem(e);const n=await TS(t.sessionId);n&&await L3(t.sessionId,{messageCount:Math.max(0,n.messageCount-1)})}}const Vz={isOpen:!1,width:Math.min(bv.DRAWER_MAX_WIDTH,Math.max(bv.DRAWER_MIN_WIDTH,window.innerWidth*bv.DRAWER_DEFAULT_WIDTH_RATIO)),activeSessionId:null};function Dne(){try{const e=localStorage.getItem(uh.DRAWER_STATE);if(e)return{...Vz,...JSON.parse(e)}}catch(e){console.error("[ChatStorage] Failed to get drawer state:",e)}return Vz}function DGe(e){try{const n={...Dne(),...e};localStorage.setItem(uh.DRAWER_STATE,JSON.stringify(n))}catch(t){console.error("[ChatStorage] Failed to set drawer state:",t)}}async function IGe(){await _m.clear(),await bd.clear(),localStorage.removeItem(uh.DRAWER_STATE)}async function OGe(e){console.warn("[ChatStorage] pruneOldSessions is deprecated and disabled")}const Hn={createSession:SGe,getSession:TS,getAllSessions:_Ge,updateSession:L3,deleteSession:TGe,addMessage:kGe,getMessages:Ane,updateMessage:PGe,deleteMessage:AGe,getDrawerState:Dne,setDrawerState:DGe,clearAllData:IGe,pruneOldSessions:OGe,generateId:Pne,generateTitle:EGe};var go=(e=>(e.SENDING="sending",e.STREAMING="streaming",e.SUCCESS="success",e.FAILED="failed",e))(go||{}),ea=(e=>(e.USER="user",e.ASSISTANT="assistant",e))(ea||{});let wl=null,Mc=null;function kS(e){const t={};let n=1,r=1,i=1,s=e;return s=s.replace(/data:image\/[^;]+;base64,[A-Za-z0-9+/=]+/g,o=>{const a=`[图片${n}]`;return t[a]=o,n++,a}),s=s.replace(/data:video\/[^;]+;base64,[A-Za-z0-9+/=]+/g,o=>{const a=`[视频${r}]`;return t[a]=o,r++,a}),s=s.replace(/blob:[^\s"'<>]+/g,o=>{const a=`[媒体${i}]`;return t[a]=o,i++,a}),s=s.replace(/https?:\/\/[^\s"'<>]+\.(png|jpg|jpeg|gif|webp|svg|bmp)(\?[^\s"'<>]*)?/gi,o=>{const a=`[图片${n}]`;return t[a]=o,n++,a}),s=s.replace(/https?:\/\/[^\s"'<>]+\.(mp4|webm|mov|avi|mkv)(\?[^\s"'<>]*)?/gi,o=>{const a=`[视频${r}]`;return t[a]=o,r++,a}),{sanitized:s,urlMap:t}}function Ine(e,t){let n=e;for(const[r,i]of Object.entries(t))n=n.split(r).join(i);return n}function MGe(e){const t={};return{geminiMessages:e.filter(r=>r.status==="success"||r.status==="streaming").map(r=>{const{sanitized:i,urlMap:s}=kS(r.content);return Object.assign(t,s),{role:r.role===ea.USER?"user":"assistant",content:[{type:"text",text:i}]}}),urlMap:t}}function RGe(e){const t={};return{swMessages:e.filter(r=>r.status==="success"||r.status==="streaming").map(r=>{const{sanitized:i,urlMap:s}=kS(r.content);return Object.assign(t,s),{role:r.role===ea.USER?"user":"assistant",content:i}}),urlMap:t}}async function BGe(e){const t=[];for(const n of e)if(n.type.startsWith("image/")){const r=await LGe(n);t.push({type:"image",name:n.name,mimeType:n.type,data:r})}return t}function LGe(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const i=r.result,s=i.split(",")[1]||i;t(s)},r.onerror=n,r.readAsDataURL(e)})}async function NGe(e,t,n=[],r,i,s){if(xu()){if(!nr.isInitialized()){const o=An.get();if(o.apiKey&&o.baseUrl)try{const a=await nr.initialize({apiKey:o.apiKey,baseUrl:o.baseUrl,modelName:o.chatModel},{baseUrl:o.baseUrl})}catch(a){console.error("[ChatService] SW client initialization failed:",a)}}if(nr.isInitialized())return jGe(e,t,n,r,i,s)}return FGe(e,t,n,r,i,s)}async function jGe(e,t,n=[],r,i,s){Mc&&nr.stopChat(Mc);const o=`chat_${Date.now()}_${Math.random().toString(36).slice(2,9)}`;Mc=o;const a=Date.now().toString(),l=Date.now(),c=i||du.getConfig().modelName||"unknown";qt.trackModelCall({taskId:a,taskType:"chat",model:c,promptLength:t.length,hasUploadedImage:n.length>0,startTime:l});const{swMessages:u,urlMap:d}=RGe(e),{sanitized:f,urlMap:h}=kS(t),m={...d,...h},g=await BGe(n),w={messages:u,newContent:f,attachments:g,temporaryModel:i,systemPrompt:s};return new Promise((C,b)=>{let _="",T=!1;const S=()=>{Mc===o&&(Mc=null)};nr.startChat(o,w,{onChunk:(k,D)=>{if(T)return;const O=Ine(D,m);_=O,r({type:"content",content:O})},onDone:(k,D)=>{if(T)return;T=!0,S();const O=Date.now()-l;qt.trackModelSuccess({taskId:a,taskType:"chat",model:c,duration:O,resultSize:_.length}),r({type:"done"}),C(_)},onError:(k,D)=>{if(T)return;T=!0,S();const O=Date.now()-l;qt.trackModelFailure({taskId:a,taskType:"chat",model:c,duration:O,error:D}),r({type:"error",error:D}),b(new Error(D))}})})}async function FGe(e,t,n=[],r,i,s){wl&&wl.abort(),wl=new AbortController;const o=wl.signal,a=Date.now().toString(),l=Date.now(),c=i||du.getConfig().modelName||"unknown";try{qt.trackModelCall({taskId:a,taskType:"chat",model:c,promptLength:t.length,hasUploadedImage:n.length>0,startTime:l});const{geminiMessages:u,urlMap:d}=MGe(e),{sanitized:f,urlMap:h}=kS(t),m={...d,...h},g=[{type:"text",text:f}],w=[];s&&w.push({role:"system",content:[{type:"text",text:s}]}),w.push(...u,{role:"user",content:g});let C="";if(await du.sendChat(w,_=>{if(o.aborted)return;const T=Ine(_,m);C=T,r({type:"content",content:T})},o,i),o.aborted)throw new Error("Request cancelled");const b=Date.now()-l;return qt.trackModelSuccess({taskId:a,taskType:"chat",model:c,duration:b,resultSize:C.length}),r({type:"done"}),wl=null,C}catch(u){wl=null;const d=Date.now()-l;if(o.aborted||u.message==="Request cancelled"||u.name==="AbortError")throw qt.trackTaskCancellation({taskId:a,taskType:"chat",duration:d}),r({type:"done"}),new Error("Request cancelled");const f=u instanceof Error?u.message:"Unknown error occurred";throw qt.trackModelFailure({taskId:a,taskType:"chat",model:c,duration:d,error:f}),r({type:"error",error:f}),u}}function $Ge(){Mc&&(nr.stopChat(Mc),Mc=null),wl&&(wl.abort(),wl=null)}function zGe(){return wl!==null||Mc!==null}const Uz={sendChatMessage:NGe,stopGeneration:$Ge,isGenerating:zGe},YA="[[WORKFLOW_MESSAGE]]",HGe=["generate_image","generate_video","generate_grid_image","generate_photo_wall"];function WGe(e){var i;if(!HGe.includes(e.name))return e;const t={...e.arguments},n=t.model;let r=!1;if(!n)r=!0;else{const s=r3(n),o=e.name==="generate_video";(o&&s!=="video"||!o&&s!=="image")&&(r=!0)}if(r){const s=An.get(),o=e.name==="generate_video";let a;o?a=s.videoModelName||"veo3":a=s.imageModelName||((i=Xl[0])==null?void 0:i.id)||"gemini-2.5-flash-image-vip",t.model=a}return{...e,arguments:t}}function GGe(e){const t=[];e.aiAnalysis&&t.push(e.aiAnalysis);const n=e.steps.filter(o=>o.status==="completed"),r=e.steps.filter(o=>o.status==="failed");if(n.length>0||r.length>0){const o=[];n.length>0&&o.push(`成功执行 ${n.length} 个工具`),r.length>0&&o.push(`${r.length} 个工具执行失败`),o.length>0&&t.push(`[执行结果: ${o.join(",")}]`)}const i=e.steps.map(o=>{const a={};for(const[l,c]of Object.entries(o.args||{}))l!=="context"&&(typeof c=="string"&&c.length>200?a[l]=c.substring(0,200)+"...":a[l]=c);return{mcp:o.mcp,args:a}}),s={content:t.join(`
2051
- `)||`已完成任务: ${e.name}`,next:i};return JSON.stringify(s)}function VGe(e){const t=[{type:"text",text:e.content}];if(e.attachments&&e.attachments.length>0)for(const n of e.attachments)t.push({type:"data-file",data:{filename:n.name,mediaType:n.type,url:n.data}});return{id:e.id,role:e.role===ea.USER?"user":"assistant",parts:t}}function UGe(e,t){const r=e.parts.filter(o=>o.type==="text").map(o=>o.text).join(""),s=e.parts.filter(o=>o.type==="data-file").map((o,a)=>{const l=o.data;return{id:`${e.id}-att-${a}`,name:l.filename,type:l.mediaType,size:0,data:l.url,isBlob:!1}});return{id:e.id,sessionId:t,role:e.role==="user"?ea.USER:ea.ASSISTANT,content:r,timestamp:Date.now(),status:go.SUCCESS,attachments:s.length>0?s:void 0}}function KGe(e){return e.workflow&&e.content.startsWith(YA)?{...e,content:GGe(e.workflow)}:e}function Kz(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("")}p3();function qGe(e){const{sessionId:t,temporaryModel:n,onToolCalls:r,onWorkflowUpdate:i}=e,s=x.useRef(h3()),o=x.useRef(r);o.current=r;const a=x.useRef(i);a.current=i;const[l,c]=x.useState([]),[u,d]=x.useState("ready"),[f,h]=x.useState(!1),m=x.useRef(null),g=x.useRef([]),w=x.useRef(!1);x.useEffect(()=>{if(!t){c([]),g.current=[];return}(async()=>{h(!0);try{const D=await Hn.getMessages(t);g.current=D,c(D.map(VGe))}catch(D){console.error("[useChatHandler] Failed to load messages:",D),c([]),g.current=[]}finally{h(!1)}})()},[t]);const C=x.useCallback(async k=>{if(!t)return;if(w.current){console.warn("[useChatHandler] Message already being sent, ignoring duplicate call");return}w.current=!0,d("submitted");const D=UGe(k,t);await Hn.addMessage(D),c(A=>[...A,k]);const O=await Hn.getSession(t);await Hn.updateSession(t,{updatedAt:Date.now(),messageCount:((O==null?void 0:O.messageCount)||0)+1});const I=Hn.generateId();m.current=I;const R={id:I,role:"assistant",parts:[{type:"text",text:""}]};c(A=>[...A,R]),d("streaming");const F=g.current.map(KGe);F.push(D),g.current=[...g.current,D];const M=Kz(k);let $="";try{await Uz.sendChatMessage(F.slice(0,-1),M,[],A=>{if(A.type==="content"&&A.content)$+=A.content,c(z=>z.map(G=>G.id===I?{...G,parts:[{type:"text",text:$}]}:G));else if(A.type==="done"){const z=tee($),G=nee($)||$;if(z.length>0&&o.current){const K=z.map(L=>WGe(L)),j=async()=>{const L=[];for(const V of K)try{const Y=await h1.executeTool(V);L.push({toolCall:V,success:Y.success,data:Y.data,error:Y.error,taskId:Y.taskId})}catch(Y){L.push({toolCall:V,success:!1,error:Y.message||"工具执行失败"})}return L},H=`${YA}${I}`;c(L=>L.map(V=>V.id===I?{...V,parts:[{type:"text",text:H}]}:V)),o.current(K,I,j,G)}d("ready");const W={id:I,sessionId:t,role:ea.ASSISTANT,content:z.length>0?`${YA}${I}`:$,timestamp:Date.now(),status:z.length>0?go.STREAMING:go.SUCCESS};Hn.addMessage(W),g.current=[...g.current,W],Hn.updateSession(t,{updatedAt:Date.now(),messageCount:((O==null?void 0:O.messageCount)||0)+2}),m.current=null,w.current=!1}else if(A.type==="error"&&A.error){d("error");const z=`❌ 错误: ${A.error}`;c(W=>W.map(K=>K.id===I?{...K,parts:[{type:"text",text:z}]}:K));const G={id:I,sessionId:t,role:ea.ASSISTANT,content:z,timestamp:Date.now(),status:go.FAILED,error:A.error};Hn.addMessage(G),g.current=[...g.current,G],m.current=null,w.current=!1}},n,s.current)}catch(A){if(A.message!=="Request cancelled"){d("error"),console.error("[useChatHandler] Stream error:",A);const z=`❌ 错误: ${A.message||"未知错误"}`;if(c(G=>G.map(W=>W.id===I?{...W,parts:[{type:"text",text:z}]}:W)),t&&I){const G={id:I,sessionId:t,role:ea.ASSISTANT,content:z,timestamp:Date.now(),status:go.FAILED,error:A.message||"未知错误"};Hn.addMessage(G),g.current=[...g.current,G]}}m.current=null,w.current=!1}},[t]),b=x.useCallback(async()=>{if(Uz.stopGeneration(),d("ready"),m.current&&t){const k=l.find(D=>D.id===m.current);if(k){const D=Kz(k),O={id:k.id,sessionId:t,role:ea.ASSISTANT,content:D,timestamp:Date.now(),status:go.SUCCESS};await Hn.addMessage(O)}m.current=null}},[t,l]),_=x.useCallback(k=>{if(l.length<2)return;const D=[...l].reverse().findIndex(F=>F.role==="user");if(D===-1)return;const O=l.length-1-D,I=l[O],R=l.slice(0,O+1);c(R),C(I)},[l,C]),T=x.useCallback((k,D)=>{c(k),D&&(g.current=D)},[]),S=x.useCallback((k,D)=>{g.current=g.current.map(O=>O.id===k?{...O,workflow:D}:O)},[]);return{messages:l,status:u,sendMessage:C,stop:b,regenerate:_,setMessages:c,setMessagesWithRaw:T,updateRawMessageWorkflow:S,isLoading:f}}const One=x.createContext(null),XGe=typeof window<"u"?Math.max(375,window.innerWidth*.5):600,YGe=({children:e})=>{const t=x.useRef(null),n=x.useRef(null),[r,i]=x.useState([]),[s,o]=x.useState(!1),[a,l]=x.useState(XGe),c=x.useCallback(d=>{n.current=d},[]),u=x.useCallback(async(d,f)=>{n.current?await n.current(d,f):console.warn("[ChatDrawerContext] No retry handler registered")},[]);return y.jsx(One.Provider,{value:{chatDrawerRef:t,registerRetryHandler:c,executeRetry:u,selectedContent:r,setSelectedContent:i,isDrawerOpen:s,setIsDrawerOpen:o,drawerWidth:a,setDrawerWidth:l},children:e})};function N3(){const e=x.useContext(One);if(!e)throw new Error("useChatDrawer must be used within a ChatDrawerProvider");return e}function j3(){const{chatDrawerRef:e,registerRetryHandler:t,executeRetry:n,selectedContent:r,setSelectedContent:i,isDrawerOpen:s,setIsDrawerOpen:o,drawerWidth:a,setDrawerWidth:l}=N3();return{openChatDrawer:()=>{var c;(c=e.current)==null||c.open()},closeChatDrawer:()=>{var c;(c=e.current)==null||c.close()},toggleChatDrawer:()=>{var c;(c=e.current)==null||c.toggle()},sendMessageToChatDrawer:async c=>{var u;await((u=e.current)==null?void 0:u.sendMessage(c))},sendWorkflowMessage:async c=>{var u;await((u=e.current)==null?void 0:u.sendWorkflowMessage(c))},updateWorkflowMessage:c=>{var u;(u=e.current)==null||u.updateWorkflowMessage(c)},appendAgentLog:c=>{var u;(u=e.current)==null||u.appendAgentLog(c)},updateThinkingContent:c=>{var u;(u=e.current)==null||u.updateThinkingContent(c)},isChatDrawerOpen:()=>{var c;return((c=e.current)==null?void 0:c.isOpen())??!1},isDrawerOpen:s,setIsDrawerOpen:o,drawerWidth:a,setDrawerWidth:l,registerRetryHandler:t,retryWorkflowFromStep:async(c,u)=>{await n(c,u)},selectedContent:r,setSelectedContent:i}}const ZGe=J.lazy(()=>ln(()=>import("./ChatMessagesArea-CAnmzKeA.js").then(e=>e.C),__vite__mapDeps([6,7,5,8,4,9]),import.meta.url)),qz="[[WORKFLOW_MESSAGE]]";function QGe(e,t){switch(e){case"generate_image":return`生成图片: ${((t==null?void 0:t.prompt)||"").substring(0,30)}...`;case"generate_video":return`生成视频: ${((t==null?void 0:t.prompt)||"").substring(0,30)}...`;case"generate_grid_image":return`生成宫格图: ${((t==null?void 0:t.theme)||"").substring(0,30)}...`;case"canvas_insertion":return"插入到画布";case"generate_mermaid":return"生成流程图";case"generate_mindmap":return"生成思维导图";default:return`执行 ${e}`}}const Xz="chat-drawer-width",JGe=Math.max(375,window.innerWidth*.5),Yz=375,Mne=x.forwardRef(({defaultOpen:e=!1,onOpenChange:t},n)=>{const[r,i]=x.useState(()=>Hn.getDrawerState().isOpen??e),[s,o]=x.useState([]),[a,l]=x.useState(null),[c,u]=x.useState(!1),[d,f]=x.useState(()=>{const je=localStorage.getItem(Xz);if(je){const Me=parseInt(je,10);if(!isNaN(Me)&&Me>=Yz)return Math.min(Me,window.innerWidth-60)}return JGe}),[h,m]=x.useState(!1),g=x.useRef(null),[w,C]=x.useState(void 0),[b,_]=x.useState(new Map),T=x.useRef(null),[S,k]=x.useState(null),{executeRetry:D,selectedContent:O,setIsDrawerOpen:I,setDrawerWidth:R}=N3();x.useEffect(()=>{I(r)},[r,I]),x.useEffect(()=>{R(d)},[d,R]);const F=J.useRef(null),M=J.useRef(null),{appState:$,setAppState:A}=Mi();x.useEffect(()=>{if(!h)return;const je=_e=>{const We=window.innerWidth-_e.clientX,Se=Math.max(Yz,Math.min(We,window.innerWidth-60));f(Se)},Me=()=>{m(!1),localStorage.setItem(Xz,String(d))};return document.addEventListener("mousemove",je),document.addEventListener("mouseup",Me),document.body.style.userSelect="none",document.body.style.cursor="ew-resize",()=>{document.removeEventListener("mousemove",je),document.removeEventListener("mouseup",Me),document.body.style.userSelect="",document.body.style.cursor=""}},[h,d]),x.useEffect(()=>{const je=()=>{const Me=window.innerWidth-60;d>Me&&f(Me)};return window.addEventListener("resize",je),()=>window.removeEventListener("resize",je)},[d]);const z=x.useCallback(je=>{je.preventDefault(),m(!0)},[]),G=x.useCallback(async(je,Me,_e,We)=>{var Be;const pe={id:`workflow-${Date.now()}`,name:"AI 智能生成",generationType:(Be=je[0])!=null&&Be.name.includes("video")?"video":"image",prompt:We||"",aiAnalysis:We,count:je.length,steps:je.map((Pe,Qe)=>({id:`step-${Qe}`,mcp:Pe.name,status:"pending",description:QGe(Pe.name,Pe.arguments),args:Pe.arguments}))};_(Pe=>{const Qe=new Map(Pe);return Qe.set(Me,pe),Qe}),T.current=Me,Hn.updateMessage(Me,{workflow:pe});try{const Pe=await _e();qt.track("chat_tool_execution_complete",{success:!0,resultCount:Pe.length}),_(Qe=>{const wt=new Map(Qe),Ct=wt.get(Me);if(Ct){const $e={...Ct,steps:Ct.steps.map((Fe,rt)=>{const bt=Pe[rt];return{...Fe,status:bt!=null&&bt.success?"completed":"failed",error:bt==null?void 0:bt.error,result:bt==null?void 0:bt.data}})};wt.set(Me,$e),Hn.updateMessage(Me,{workflow:$e,status:go.SUCCESS})}return wt})}catch(Pe){console.error("[ChatDrawer] Tool execution failed:",Pe),_(Qe=>{const wt=new Map(Qe),Ct=wt.get(Me);if(Ct){const $e={...Ct,steps:Ct.steps.map(Fe=>({...Fe,status:"failed",error:Pe.message||"执行失败"}))};wt.set(Me,$e),Hn.updateMessage(Me,{workflow:$e,status:go.FAILED})}return wt})}},[]),W=qGe({sessionId:a,temporaryModel:w,onToolCalls:G}),K=x.useRef(W.sendMessage);K.current=W.sendMessage,x.useEffect(()=>{(async()=>{const Me=Hn.getDrawerState(),_e=await Hn.getAllSessions();o(_e);let We=null;if(Me.activeSessionId?(We=Me.activeSessionId,l(Me.activeSessionId)):_e.length>0&&(We=_e[0].id,l(_e[0].id)),We)try{const Se=await Hn.getMessages(We),pe=new Map;for(const Pe of Se)Pe.workflow&&pe.set(Pe.id,Pe.workflow);_(pe);const Be=Se.find(Pe=>Pe.workflow&&Pe.status===go.STREAMING);T.current=(Be==null?void 0:Be.id)||null}catch(Se){console.error("[ChatDrawer] Failed to load workflow messages:",Se)}})()},[]),x.useEffect(()=>{Hn.setDrawerState({isOpen:r,activeSessionId:a})},[r,a]),x.useEffect(()=>{if(a&&re.current){const je=re.current;re.current=null,setTimeout(()=>{K.current(je)},100)}},[a]),x.useEffect(()=>{if(!$.openSettings&&re.current){const je=An.get();if(je!=null&&je.apiKey){const Me=re.current;re.current=null,a?setTimeout(()=>{K.current(Me)},100):(async()=>{const _e=await Hn.createSession();o(We=>[_e,...We]),l(_e.id),re.current=Me})()}}},[$.openSettings,a]),x.useEffect(()=>{const je=Me=>{Me.key==="Escape"&&r&&(i(!1),t==null||t(!1))};return window.addEventListener("keydown",je),()=>window.removeEventListener("keydown",je)},[r,t]),x.useEffect(()=>{if(!c)return;const je=_e=>{const We=_e.target;We.closest(".t-dialog")===null&&F.current&&!F.current.contains(We)&&M.current&&!M.current.contains(We)&&u(!1)},Me=setTimeout(()=>{document.addEventListener("mousedown",je)},100);return()=>{clearTimeout(Me),document.removeEventListener("mousedown",je)}},[c]);const j=x.useCallback(()=>{i(je=>{const Me=!je;return t==null||t(Me),Me})},[t]),H=x.useCallback(()=>{i(!1),t==null||t(!1)},[t]),L=x.useCallback(async()=>{qt.track("chat_session_create");const je=await Hn.createSession();o(Me=>[je,...Me]),l(je.id),u(!1),_(new Map),T.current=null,C(void 0)},[]),V=x.useCallback(()=>{u(je=>!je)},[]),Y=x.useCallback(async je=>{qt.track("chat_session_select"),l(je),u(!1),C(void 0);try{const Me=await Hn.getMessages(je),_e=new Map;for(const Se of Me)Se.workflow&&_e.set(Se.id,Se.workflow);_(_e);const We=Me.find(Se=>Se.workflow&&Se.status===go.STREAMING);T.current=(We==null?void 0:We.id)||null}catch(Me){console.error("[ChatDrawer] Failed to load workflow messages:",Me),_(new Map),T.current=null}},[]),q=x.useCallback(async je=>{qt.track("chat_session_delete"),await Hn.deleteSession(je),o(Me=>{const _e=Me.filter(We=>We.id!==je);if(a===je){const We=_e[0]||null;l((We==null?void 0:We.id)||null)}return _e})},[a]),Z=x.useCallback(async(je,Me)=>{qt.track("chat_session_rename"),await Hn.updateSession(je,{title:Me}),o(_e=>_e.map(We=>We.id===je?{...We,title:Me}:We))},[]),re=J.useRef(null),ae=x.useCallback(async je=>{qt.track("chat_message_send",{hasImages:je.parts.some(_e=>_e.type==="image_url")});const Me=An.get();if(!(Me!=null&&Me.apiKey)){re.current=je,A({...$,openSettings:!0});return}if(re.current=null,!a){const _e=await Hn.createSession();o(We=>[_e,...We]),l(_e.id),re.current=je;return}await W.sendMessage(je)},[a,W,$,A]),de=x.useCallback(async je=>{var Rn;const{context:Me,workflow:_e,textModel:We,autoOpen:Se=!0}=je;Se&&(i(!0),t==null||t(!0)),We&&C(We);const pe=await Hn.createSession(),Be=[];Me.userInstruction&&Be.push(`
2051
+ `)||`已完成任务: ${e.name}`,next:i};return JSON.stringify(s)}function VGe(e){const t=[{type:"text",text:e.content}];if(e.attachments&&e.attachments.length>0)for(const n of e.attachments)t.push({type:"data-file",data:{filename:n.name,mediaType:n.type,url:n.data}});return{id:e.id,role:e.role===ea.USER?"user":"assistant",parts:t}}function UGe(e,t){const r=e.parts.filter(o=>o.type==="text").map(o=>o.text).join(""),s=e.parts.filter(o=>o.type==="data-file").map((o,a)=>{const l=o.data;return{id:`${e.id}-att-${a}`,name:l.filename,type:l.mediaType,size:0,data:l.url,isBlob:!1}});return{id:e.id,sessionId:t,role:e.role==="user"?ea.USER:ea.ASSISTANT,content:r,timestamp:Date.now(),status:go.SUCCESS,attachments:s.length>0?s:void 0}}function KGe(e){return e.workflow&&e.content.startsWith(YA)?{...e,content:GGe(e.workflow)}:e}function Kz(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("")}p3();function qGe(e){const{sessionId:t,temporaryModel:n,onToolCalls:r,onWorkflowUpdate:i}=e,s=x.useRef(h3()),o=x.useRef(r);o.current=r;const a=x.useRef(i);a.current=i;const[l,c]=x.useState([]),[u,d]=x.useState("ready"),[f,h]=x.useState(!1),m=x.useRef(null),g=x.useRef([]),w=x.useRef(!1);x.useEffect(()=>{if(!t){c([]),g.current=[];return}(async()=>{h(!0);try{const D=await Hn.getMessages(t);g.current=D,c(D.map(VGe))}catch(D){console.error("[useChatHandler] Failed to load messages:",D),c([]),g.current=[]}finally{h(!1)}})()},[t]);const C=x.useCallback(async k=>{if(!t)return;if(w.current){console.warn("[useChatHandler] Message already being sent, ignoring duplicate call");return}w.current=!0,d("submitted");const D=UGe(k,t);await Hn.addMessage(D),c(A=>[...A,k]);const O=await Hn.getSession(t);await Hn.updateSession(t,{updatedAt:Date.now(),messageCount:((O==null?void 0:O.messageCount)||0)+1});const I=Hn.generateId();m.current=I;const R={id:I,role:"assistant",parts:[{type:"text",text:""}]};c(A=>[...A,R]),d("streaming");const F=g.current.map(KGe);F.push(D),g.current=[...g.current,D];const M=Kz(k);let $="";try{await Uz.sendChatMessage(F.slice(0,-1),M,[],A=>{if(A.type==="content"&&A.content)$+=A.content,c(z=>z.map(G=>G.id===I?{...G,parts:[{type:"text",text:$}]}:G));else if(A.type==="done"){const z=tee($),G=nee($)||$;if(z.length>0&&o.current){const K=z.map(L=>WGe(L)),j=async()=>{const L=[];for(const V of K)try{const Y=await h1.executeTool(V);L.push({toolCall:V,success:Y.success,data:Y.data,error:Y.error,taskId:Y.taskId})}catch(Y){L.push({toolCall:V,success:!1,error:Y.message||"工具执行失败"})}return L},H=`${YA}${I}`;c(L=>L.map(V=>V.id===I?{...V,parts:[{type:"text",text:H}]}:V)),o.current(K,I,j,G)}d("ready");const W={id:I,sessionId:t,role:ea.ASSISTANT,content:z.length>0?`${YA}${I}`:$,timestamp:Date.now(),status:z.length>0?go.STREAMING:go.SUCCESS};Hn.addMessage(W),g.current=[...g.current,W],Hn.updateSession(t,{updatedAt:Date.now(),messageCount:((O==null?void 0:O.messageCount)||0)+2}),m.current=null,w.current=!1}else if(A.type==="error"&&A.error){d("error");const z=`❌ 错误: ${A.error}`;c(W=>W.map(K=>K.id===I?{...K,parts:[{type:"text",text:z}]}:K));const G={id:I,sessionId:t,role:ea.ASSISTANT,content:z,timestamp:Date.now(),status:go.FAILED,error:A.error};Hn.addMessage(G),g.current=[...g.current,G],m.current=null,w.current=!1}},n,s.current)}catch(A){if(A.message!=="Request cancelled"){d("error"),console.error("[useChatHandler] Stream error:",A);const z=`❌ 错误: ${A.message||"未知错误"}`;if(c(G=>G.map(W=>W.id===I?{...W,parts:[{type:"text",text:z}]}:W)),t&&I){const G={id:I,sessionId:t,role:ea.ASSISTANT,content:z,timestamp:Date.now(),status:go.FAILED,error:A.message||"未知错误"};Hn.addMessage(G),g.current=[...g.current,G]}}m.current=null,w.current=!1}},[t]),b=x.useCallback(async()=>{if(Uz.stopGeneration(),d("ready"),m.current&&t){const k=l.find(D=>D.id===m.current);if(k){const D=Kz(k),O={id:k.id,sessionId:t,role:ea.ASSISTANT,content:D,timestamp:Date.now(),status:go.SUCCESS};await Hn.addMessage(O)}m.current=null}},[t,l]),_=x.useCallback(k=>{if(l.length<2)return;const D=[...l].reverse().findIndex(F=>F.role==="user");if(D===-1)return;const O=l.length-1-D,I=l[O],R=l.slice(0,O+1);c(R),C(I)},[l,C]),T=x.useCallback((k,D)=>{c(k),D&&(g.current=D)},[]),S=x.useCallback((k,D)=>{g.current=g.current.map(O=>O.id===k?{...O,workflow:D}:O)},[]);return{messages:l,status:u,sendMessage:C,stop:b,regenerate:_,setMessages:c,setMessagesWithRaw:T,updateRawMessageWorkflow:S,isLoading:f}}const One=x.createContext(null),XGe=typeof window<"u"?Math.max(375,window.innerWidth*.5):600,YGe=({children:e})=>{const t=x.useRef(null),n=x.useRef(null),[r,i]=x.useState([]),[s,o]=x.useState(!1),[a,l]=x.useState(XGe),c=x.useCallback(d=>{n.current=d},[]),u=x.useCallback(async(d,f)=>{n.current?await n.current(d,f):console.warn("[ChatDrawerContext] No retry handler registered")},[]);return y.jsx(One.Provider,{value:{chatDrawerRef:t,registerRetryHandler:c,executeRetry:u,selectedContent:r,setSelectedContent:i,isDrawerOpen:s,setIsDrawerOpen:o,drawerWidth:a,setDrawerWidth:l},children:e})};function N3(){const e=x.useContext(One);if(!e)throw new Error("useChatDrawer must be used within a ChatDrawerProvider");return e}function j3(){const{chatDrawerRef:e,registerRetryHandler:t,executeRetry:n,selectedContent:r,setSelectedContent:i,isDrawerOpen:s,setIsDrawerOpen:o,drawerWidth:a,setDrawerWidth:l}=N3();return{openChatDrawer:()=>{var c;(c=e.current)==null||c.open()},closeChatDrawer:()=>{var c;(c=e.current)==null||c.close()},toggleChatDrawer:()=>{var c;(c=e.current)==null||c.toggle()},sendMessageToChatDrawer:async c=>{var u;await((u=e.current)==null?void 0:u.sendMessage(c))},sendWorkflowMessage:async c=>{var u;await((u=e.current)==null?void 0:u.sendWorkflowMessage(c))},updateWorkflowMessage:c=>{var u;(u=e.current)==null||u.updateWorkflowMessage(c)},appendAgentLog:c=>{var u;(u=e.current)==null||u.appendAgentLog(c)},updateThinkingContent:c=>{var u;(u=e.current)==null||u.updateThinkingContent(c)},isChatDrawerOpen:()=>{var c;return((c=e.current)==null?void 0:c.isOpen())??!1},isDrawerOpen:s,setIsDrawerOpen:o,drawerWidth:a,setDrawerWidth:l,registerRetryHandler:t,retryWorkflowFromStep:async(c,u)=>{await n(c,u)},selectedContent:r,setSelectedContent:i}}const ZGe=J.lazy(()=>ln(()=>import("./ChatMessagesArea-DtzEt9y0.js").then(e=>e.C),__vite__mapDeps([6,7,5,8,4,9]),import.meta.url)),qz="[[WORKFLOW_MESSAGE]]";function QGe(e,t){switch(e){case"generate_image":return`生成图片: ${((t==null?void 0:t.prompt)||"").substring(0,30)}...`;case"generate_video":return`生成视频: ${((t==null?void 0:t.prompt)||"").substring(0,30)}...`;case"generate_grid_image":return`生成宫格图: ${((t==null?void 0:t.theme)||"").substring(0,30)}...`;case"canvas_insertion":return"插入到画布";case"generate_mermaid":return"生成流程图";case"generate_mindmap":return"生成思维导图";default:return`执行 ${e}`}}const Xz="chat-drawer-width",JGe=Math.max(375,window.innerWidth*.5),Yz=375,Mne=x.forwardRef(({defaultOpen:e=!1,onOpenChange:t},n)=>{const[r,i]=x.useState(()=>Hn.getDrawerState().isOpen??e),[s,o]=x.useState([]),[a,l]=x.useState(null),[c,u]=x.useState(!1),[d,f]=x.useState(()=>{const je=localStorage.getItem(Xz);if(je){const Me=parseInt(je,10);if(!isNaN(Me)&&Me>=Yz)return Math.min(Me,window.innerWidth-60)}return JGe}),[h,m]=x.useState(!1),g=x.useRef(null),[w,C]=x.useState(void 0),[b,_]=x.useState(new Map),T=x.useRef(null),[S,k]=x.useState(null),{executeRetry:D,selectedContent:O,setIsDrawerOpen:I,setDrawerWidth:R}=N3();x.useEffect(()=>{I(r)},[r,I]),x.useEffect(()=>{R(d)},[d,R]);const F=J.useRef(null),M=J.useRef(null),{appState:$,setAppState:A}=Mi();x.useEffect(()=>{if(!h)return;const je=_e=>{const We=window.innerWidth-_e.clientX,Se=Math.max(Yz,Math.min(We,window.innerWidth-60));f(Se)},Me=()=>{m(!1),localStorage.setItem(Xz,String(d))};return document.addEventListener("mousemove",je),document.addEventListener("mouseup",Me),document.body.style.userSelect="none",document.body.style.cursor="ew-resize",()=>{document.removeEventListener("mousemove",je),document.removeEventListener("mouseup",Me),document.body.style.userSelect="",document.body.style.cursor=""}},[h,d]),x.useEffect(()=>{const je=()=>{const Me=window.innerWidth-60;d>Me&&f(Me)};return window.addEventListener("resize",je),()=>window.removeEventListener("resize",je)},[d]);const z=x.useCallback(je=>{je.preventDefault(),m(!0)},[]),G=x.useCallback(async(je,Me,_e,We)=>{var Be;const pe={id:`workflow-${Date.now()}`,name:"AI 智能生成",generationType:(Be=je[0])!=null&&Be.name.includes("video")?"video":"image",prompt:We||"",aiAnalysis:We,count:je.length,steps:je.map((Pe,Qe)=>({id:`step-${Qe}`,mcp:Pe.name,status:"pending",description:QGe(Pe.name,Pe.arguments),args:Pe.arguments}))};_(Pe=>{const Qe=new Map(Pe);return Qe.set(Me,pe),Qe}),T.current=Me,Hn.updateMessage(Me,{workflow:pe});try{const Pe=await _e();qt.track("chat_tool_execution_complete",{success:!0,resultCount:Pe.length}),_(Qe=>{const wt=new Map(Qe),Ct=wt.get(Me);if(Ct){const $e={...Ct,steps:Ct.steps.map((Fe,rt)=>{const bt=Pe[rt];return{...Fe,status:bt!=null&&bt.success?"completed":"failed",error:bt==null?void 0:bt.error,result:bt==null?void 0:bt.data}})};wt.set(Me,$e),Hn.updateMessage(Me,{workflow:$e,status:go.SUCCESS})}return wt})}catch(Pe){console.error("[ChatDrawer] Tool execution failed:",Pe),_(Qe=>{const wt=new Map(Qe),Ct=wt.get(Me);if(Ct){const $e={...Ct,steps:Ct.steps.map(Fe=>({...Fe,status:"failed",error:Pe.message||"执行失败"}))};wt.set(Me,$e),Hn.updateMessage(Me,{workflow:$e,status:go.FAILED})}return wt})}},[]),W=qGe({sessionId:a,temporaryModel:w,onToolCalls:G}),K=x.useRef(W.sendMessage);K.current=W.sendMessage,x.useEffect(()=>{(async()=>{const Me=Hn.getDrawerState(),_e=await Hn.getAllSessions();o(_e);let We=null;if(Me.activeSessionId?(We=Me.activeSessionId,l(Me.activeSessionId)):_e.length>0&&(We=_e[0].id,l(_e[0].id)),We)try{const Se=await Hn.getMessages(We),pe=new Map;for(const Pe of Se)Pe.workflow&&pe.set(Pe.id,Pe.workflow);_(pe);const Be=Se.find(Pe=>Pe.workflow&&Pe.status===go.STREAMING);T.current=(Be==null?void 0:Be.id)||null}catch(Se){console.error("[ChatDrawer] Failed to load workflow messages:",Se)}})()},[]),x.useEffect(()=>{Hn.setDrawerState({isOpen:r,activeSessionId:a})},[r,a]),x.useEffect(()=>{if(a&&re.current){const je=re.current;re.current=null,setTimeout(()=>{K.current(je)},100)}},[a]),x.useEffect(()=>{if(!$.openSettings&&re.current){const je=An.get();if(je!=null&&je.apiKey){const Me=re.current;re.current=null,a?setTimeout(()=>{K.current(Me)},100):(async()=>{const _e=await Hn.createSession();o(We=>[_e,...We]),l(_e.id),re.current=Me})()}}},[$.openSettings,a]),x.useEffect(()=>{const je=Me=>{Me.key==="Escape"&&r&&(i(!1),t==null||t(!1))};return window.addEventListener("keydown",je),()=>window.removeEventListener("keydown",je)},[r,t]),x.useEffect(()=>{if(!c)return;const je=_e=>{const We=_e.target;We.closest(".t-dialog")===null&&F.current&&!F.current.contains(We)&&M.current&&!M.current.contains(We)&&u(!1)},Me=setTimeout(()=>{document.addEventListener("mousedown",je)},100);return()=>{clearTimeout(Me),document.removeEventListener("mousedown",je)}},[c]);const j=x.useCallback(()=>{i(je=>{const Me=!je;return t==null||t(Me),Me})},[t]),H=x.useCallback(()=>{i(!1),t==null||t(!1)},[t]),L=x.useCallback(async()=>{qt.track("chat_session_create");const je=await Hn.createSession();o(Me=>[je,...Me]),l(je.id),u(!1),_(new Map),T.current=null,C(void 0)},[]),V=x.useCallback(()=>{u(je=>!je)},[]),Y=x.useCallback(async je=>{qt.track("chat_session_select"),l(je),u(!1),C(void 0);try{const Me=await Hn.getMessages(je),_e=new Map;for(const Se of Me)Se.workflow&&_e.set(Se.id,Se.workflow);_(_e);const We=Me.find(Se=>Se.workflow&&Se.status===go.STREAMING);T.current=(We==null?void 0:We.id)||null}catch(Me){console.error("[ChatDrawer] Failed to load workflow messages:",Me),_(new Map),T.current=null}},[]),q=x.useCallback(async je=>{qt.track("chat_session_delete"),await Hn.deleteSession(je),o(Me=>{const _e=Me.filter(We=>We.id!==je);if(a===je){const We=_e[0]||null;l((We==null?void 0:We.id)||null)}return _e})},[a]),Z=x.useCallback(async(je,Me)=>{qt.track("chat_session_rename"),await Hn.updateSession(je,{title:Me}),o(_e=>_e.map(We=>We.id===je?{...We,title:Me}:We))},[]),re=J.useRef(null),ae=x.useCallback(async je=>{qt.track("chat_message_send",{hasImages:je.parts.some(_e=>_e.type==="image_url")});const Me=An.get();if(!(Me!=null&&Me.apiKey)){re.current=je,A({...$,openSettings:!0});return}if(re.current=null,!a){const _e=await Hn.createSession();o(We=>[_e,...We]),l(_e.id),re.current=je;return}await W.sendMessage(je)},[a,W,$,A]),de=x.useCallback(async je=>{var Rn;const{context:Me,workflow:_e,textModel:We,autoOpen:Se=!0}=je;Se&&(i(!0),t==null||t(!0)),We&&C(We);const pe=await Hn.createSession(),Be=[];Me.userInstruction&&Be.push(`
2052
2052
  💬 用户指令:
2053
2053
  ${Me.userInstruction}`),Me.selection.texts.length===0&&!Me.userInstruction&&Me.finalPrompt&&Be.push(`
2054
2054
  提示词:
@@ -2056,9 +2056,9 @@ ${Me.finalPrompt}`);const Pe=Me.model.isExplicit?`模型: ${Me.model.id}`:`模
2056
2056
  📝 选中的文本:
2057
2057
  ${Me.selection.texts.join(`
2058
2058
  `)}`);const Qe=Be.join(`
2059
- `);let wt="新任务";if(Me.finalPrompt)wt=Me.finalPrompt;else if(Me.selection.texts.length>0)wt=Me.selection.texts[0];else if(Me.userInstruction){const sn=Me.userInstruction.indexOf(":"),Pn=Me.userInstruction.indexOf(":"),dr=sn>=0&&Pn>=0?Math.min(sn,Pn):Math.max(sn,Pn);dr>=0&&dr<Me.userInstruction.length-1?wt=Me.userInstruction.substring(dr+1).trim():wt=Me.userInstruction}else Me.model.id&&(wt=`模型: ${Me.model.id}`);const Ct=wt;await Hn.updateSession(pe.id,{title:Ct}),pe.title=Ct,o(sn=>[pe,...sn]),l(pe.id);const $e=Date.now(),Fe=`msg_${$e}_user`,rt=[{type:"text",text:Qe}],bt=[...Me.selection.images,...Me.selection.graphics];for(let sn=0;sn<bt.length;sn++)rt.push({type:"data-file",data:{filename:`image-${sn+1}.png`,mediaType:"image/png",url:bt[sn]}});for(let sn=0;sn<Me.selection.videos.length;sn++)rt.push({type:"data-file",data:{filename:`video-${sn+1}.mp4`,mediaType:"video/mp4",url:Me.selection.videos[sn]}});const on={id:Fe,role:"user",parts:rt},tt=`msg_${$e}_workflow`,Ut={id:tt,role:"assistant",parts:[{type:"text",text:`${qz}${tt}`}]};_(sn=>{const Pn=new Map(sn);return Pn.set(tt,_e),Pn}),T.current=tt;const kn={id:Fe,sessionId:pe.id,role:ea.USER,content:Qe,timestamp:Date.now(),status:go.SUCCESS,attachments:bt.length>0||Me.selection.videos.length>0?[...bt.map((sn,Pn)=>({id:`${Fe}-img-${Pn}`,name:`image-${Pn+1}.png`,type:"image/png",size:0,data:sn,isBlob:!1})),...Me.selection.videos.map((sn,Pn)=>({id:`${Fe}-vid-${Pn}`,name:`video-${Pn+1}.mp4`,type:"video/mp4",size:0,data:sn,isBlob:!1}))]:void 0};await Hn.addMessage(kn);const Cn={id:tt,sessionId:pe.id,role:ea.ASSISTANT,content:`${qz}${tt}`,timestamp:Date.now(),status:go.STREAMING,workflow:_e};await Hn.addMessage(Cn),(Rn=W.setMessagesWithRaw)==null||Rn.call(W,[on,Ut],[kn,Cn])},[W,t]),oe=x.useCallback(async je=>{var _e;let Me=T.current;if(!Me){for(const[We,Se]of b.entries())if(Se.id===je.id){Me=We,T.current=We;break}}Me&&(_(We=>{const Se=new Map(We);return Se.set(Me,je),Se}),Hn.updateMessage(Me,{workflow:je}),(_e=W.updateRawMessageWorkflow)==null||_e.call(W,Me,je))},[a,s,W,b]),ee=x.useCallback(je=>{const Me=T.current;Me&&_(_e=>{var pe;const We=new Map(_e),Se=We.get(Me);if(Se){const Be=Se.logs||[],Pe={...Se,logs:[...Be,je]};We.set(Me,Pe),Hn.updateMessage(Me,{workflow:Pe}),(pe=W.updateRawMessageWorkflow)==null||pe.call(W,Me,Pe)}return We})},[W]),ce=x.useRef(null),me=x.useCallback(je=>{const Me=T.current;Me&&_(_e=>{const We=new Map(_e),Se=We.get(Me);if(Se){const pe=Se.logs||[];let Be=-1;for(let Qe=pe.length-1;Qe>=0;Qe--)if(pe[Qe].type==="thinking"){Be=Qe;break}let Pe;if(Be>=0){const Qe=[...pe],wt=Qe[Be];Qe[Be]={...wt,content:wt.content+je},Pe={...Se,logs:Qe}}else Pe={...Se,logs:[...pe,{type:"thinking",timestamp:Date.now(),content:je}]};We.set(Me,Pe),ce.current&&clearTimeout(ce.current),ce.current=setTimeout(()=>{var Qe;Hn.updateMessage(Me,{workflow:Pe}),(Qe=W.updateRawMessageWorkflow)==null||Qe.call(W,Me,Pe)},500)}return We})},[W]),ve=x.useCallback(async(je,Me,_e)=>{if(!S){qt.track("chat_workflow_retry",{stepIndex:_e});try{k(je),T.current=je,await D(Me,_e)}finally{k(null)}}},[D,S]);x.useImperativeHandle(n,()=>({open:()=>{i(!0),t==null||t(!0)},close:()=>{i(!1),t==null||t(!1)},toggle:j,sendMessage:async je=>{i(!0),t==null||t(!0);const Me={id:`msg_${Date.now()}`,role:"user",parts:[{type:"text",text:je}]};await ae(Me)},sendWorkflowMessage:de,updateWorkflowMessage:oe,appendAgentLog:ee,updateThinkingContent:me,isOpen:()=>r,retryWorkflowFromStep:async(je,Me)=>{let _e=null;for(const[We,Se]of b.entries())if(Se.id===je.id){_e=We;break}_e?await ve(_e,je,Me):console.warn("[ChatDrawer] Could not find message ID for workflow retry",je.id)}}),[r,j,ae,de,oe,ee,me,t,b,ve]);const N=x.useMemo(()=>({...W,sendMessage:ae}),[W,ae]),he=s.find(je=>je.id===a),fe=(he==null?void 0:he.title)||"新对话",[ne,ie]=x.useState(!1),[ue,Te]=x.useState(""),De=x.useRef(null),ye=x.useCallback(()=>{Te(fe),ie(!0)},[fe]),Ne=x.useCallback(async()=>{const je=ue.trim();je&&je!==fe&&a&&await Z(a,je),ie(!1)},[ue,fe,a,Z]),Re=x.useCallback(()=>{Te(fe),ie(!1)},[fe]),He=x.useCallback(je=>{je.key==="Enter"?(je.preventDefault(),Ne()):je.key==="Escape"&&(je.preventDefault(),Re())},[Ne,Re]);x.useEffect(()=>{ne&&De.current&&(De.current.focus(),De.current.select())},[ne]);const et=x.useRef(null);B3(et,{enableCopy:!0,stopPropagation:!0});const[gt,Ye]=x.useState(!1);return x.useEffect(()=>{r&&Ye(!0)},[r]),y.jsxs(y.Fragment,{children:[y.jsx(Cne,{isOpen:r,onClick:j,drawerWidth:d}),y.jsxs("div",{className:`chat-drawer ${vi} ${r?"chat-drawer--open":""} ${h?"chat-drawer--dragging":""}`,style:{width:d},children:[y.jsx("div",{ref:g,className:"chat-drawer__resize-handle",onMouseDown:z}),y.jsxs("div",{ref:et,className:"chat-drawer__body",children:[y.jsxs("div",{className:"chat-drawer__header",children:[y.jsxs("div",{className:"chat-drawer__header-top",children:[ne?y.jsx("input",{ref:De,className:"chat-drawer__title-input",value:ue,onChange:je=>Te(je.target.value),onKeyDown:He,onBlur:Ne,maxLength:50}):y.jsx("h2",{className:"chat-drawer__title chat-drawer__title--editable",onClick:ye,title:"点击编辑标题",children:fe}),y.jsx(Di,{content:"关闭",theme:"light",children:y.jsx("button",{className:"chat-drawer__close-btn","data-track":"chat_click_drawer_close",onClick:H,"aria-label":"关闭对话",children:y.jsx(CS,{size:16})})})]}),y.jsxs("div",{className:"chat-drawer__header-bottom",children:[y.jsx(Ene,{value:w,onChange:C}),y.jsxs("div",{className:"chat-drawer__session-actions",children:[y.jsx(Di,{content:"会话列表",theme:"light",children:y.jsx("button",{ref:M,className:`chat-drawer__close-btn ${c?"chat-drawer__close-btn--active":""}`,"data-track":"chat_click_sessions_toggle",onClick:V,"aria-label":"会话列表",children:y.jsx(tne,{size:16})})}),y.jsx(Di,{content:"新对话",theme:"light",children:y.jsx("button",{className:"chat-drawer__close-btn","data-track":"chat_click_new_session",onClick:L,"aria-label":"新对话",children:y.jsx(dy,{size:16})})})]})]})]}),c&&y.jsx("div",{ref:F,children:y.jsx(bne,{sessions:s,activeSessionId:a,onSelectSession:Y,onNewSession:L,onDeleteSession:q,onRenameSession:Z})}),y.jsxs("div",{className:"chat-drawer__content",children:[gt&&y.jsx(x.Suspense,{fallback:y.jsx("div",{className:"chat-loading",children:y.jsx("div",{className:"chat-loading__spinner"})}),children:y.jsx(ZGe,{handler:N,workflowMessages:b,retryingWorkflowId:S,handleWorkflowRetry:ve})}),y.jsx(kne,{selectedContent:O,onSend:ae,placeholder:"输入消息... (可用 # 指定模型)"})]})]})]})]})});Mne.displayName="ChatDrawer";function Rne(){return`wf-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}function eVe(e,t=[]){const{generationType:n,modelId:r,isModelExplicit:i,prompt:s,userInstruction:o,rawInput:a,count:l,size:c,duration:u,selection:d}=e,f=[],h=Rne(),m=`wf_batch_${h}`;for(let g=0;g<l;g++){const w=`${h}-step-${g+1}`,C={mode:"queue",batchId:m,batchIndex:g+1,batchTotal:l,globalIndex:g+1};if(n==="image"){const b={prompt:s,model:r};c&&(b.size=c),t.length>0&&(b.referenceImages=t),f.push({id:w,mcp:"generate_image",args:b,options:C,description:l>1?`生成图片 (${g+1}/${l})`:"生成图片",status:"pending"})}else{const b={prompt:s,model:r,seconds:u||"5"};c&&(b.size=c),t.length>0&&(b.referenceImages=t),f.push({id:w,mcp:"generate_video",args:b,options:C,description:l>1?`生成视频 (${g+1}/${l})`:"生成视频",status:"pending"})}}return{id:h,name:n==="image"?"图片生成":"视频生成",description:`使用 ${r} 模型${l>1?`生成 ${l} 个`:"生成"}${n==="image"?"图片":"视频"}`,scenarioType:"direct_generation",generationType:n,steps:f,metadata:{prompt:s,userInstruction:o,rawInput:a,modelId:r,isModelExplicit:i,count:l,size:c,duration:u,referenceImages:t.length>0?t:void 0,selection:d},createdAt:Date.now()}}function tVe(e,t=[]){const{generationType:n,modelId:r,isModelExplicit:i,prompt:s,userInstruction:o,rawInput:a,count:l,size:c,duration:u,selection:d}=e,f=Rne(),h={userInstruction:o,rawInput:a,model:{id:r,type:n,isExplicit:i},params:{count:l,size:c,duration:u},selection:d,finalPrompt:s},m=[{id:`${f}-step-analyze`,mcp:"ai_analyze",args:{context:h,textModel:r},options:{mode:"async"},description:"AI 分析用户意图",status:"pending"}];return{id:f,name:"AI 智能生成",description:"AI 分析用户请求并执行相应操作",scenarioType:"agent_flow",generationType:n,steps:m,metadata:{prompt:s,userInstruction:o,rawInput:a,modelId:r,isModelExplicit:i,count:l,size:c,duration:u,referenceImages:t.length>0?t:void 0,selection:d},createdAt:Date.now()}}function Bne(e,t=[]){return e.scenario==="direct_generation"?eVe(e,t):tVe(e,t)}function nVe(e,t=0){try{const n=e3(e),r=n.match(/\{\s*"content"\s*:[\s\S]*?"next"\s*:[\s\S]*?\}/)||n.match(/\{[\s\S]*"content"[\s\S]*"next"[\s\S]*\}/);if(!r)return{content:"",steps:[]};const i=r[0],s=JSON.parse(i),o=typeof s.content=="string"?s.content:"";if(!Array.isArray(s.next)||s.next.length===0)return{content:o,steps:[]};const a=s.next.filter(l=>typeof l.mcp=="string"&&typeof l.args=="object").map((l,c)=>({id:`step-${t+c+1}`,mcp:l.mcp,args:l.args,description:rVe(l.mcp,l.args),status:"pending"}));return{content:o,steps:a}}catch{return{content:"",steps:[]}}}function rVe(e,t){var n,r;switch(e){case"generate_image":return`生成图片: ${((n=t.prompt)==null?void 0:n.substring(0,30))||""}...`;case"generate_video":return`生成视频: ${((r=t.prompt)==null?void 0:r.substring(0,30))||""}...`;case"ai_analyze":return"AI 分析用户意图";case"format_markdown":return"格式化输出";case"show_result":return"展示结果";default:return`执行 ${e}`}}function iVe(e,t,n,r,i,s){return{...e,steps:e.steps.map(o=>o.id===t?{...o,status:n,result:r,error:i,duration:s}:o)}}function sVe(e,t){const n=new Set(e.steps.map(i=>i.id)),r=t.filter(i=>!n.has(i.id));return r.length===0?e:{...e,steps:[...e.steps,...r]}}function vx(e){const t=e.steps.filter(o=>o.status==="completed").length,n=e.steps.filter(o=>o.status==="failed").length,r=e.steps.find(o=>o.status==="running"),i=e.steps.filter(o=>o.status==="pending").length;let s;return n>0?s="failed":r?s="running":i===0&&t>0?s="completed":s="pending",{status:s,completedSteps:t,totalSteps:e.steps.length,currentStep:r||e.steps.find(o=>o.status==="pending")}}const Zz={workflow:null,status:"idle",currentStep:null,completedSteps:0,totalSteps:0,error:null};function oVe(){const[e,t]=x.useState(Zz),n=x.useRef(null),r=x.useRef(!1),i=x.useCallback(f=>{n.current=f,r.current=!1;const h=vx(f);t({workflow:f,status:"running",currentStep:h.currentStep||null,completedSteps:h.completedSteps,totalSteps:h.totalSteps,error:null})},[]),s=x.useCallback(f=>{n.current=f,r.current=!1;const h=vx(f);let m="running";f.status==="completed"?m="completed":(f.status==="failed"||f.status==="cancelled")&&(m="failed"),t({workflow:f,status:m,currentStep:h.currentStep||null,completedSteps:h.completedSteps,totalSteps:h.totalSteps,error:f.error||null})},[]),o=x.useCallback((f,h,m,g,w)=>{if(r.current)return;const C=n.current;if(!C)return;const b=iVe(C,f,h,m,g,w);n.current=b,t(_=>{const T=vx(b);let S="running";return T.status==="completed"?S="completed":T.status==="failed"&&(S="failed"),{..._,workflow:b,status:S,currentStep:T.currentStep||null,completedSteps:T.completedSteps,totalSteps:T.totalSteps,error:g||_.error}})},[]),a=x.useCallback(f=>{if(r.current||f.length===0)return;const h=n.current;if(!h)return;const m=sVe(h,f);n.current=m,t(g=>{const w=vx(m);return{...g,workflow:m,currentStep:w.currentStep||g.currentStep,totalSteps:w.totalSteps}})},[]),l=x.useCallback(f=>{const h=n.current;if(!h||r.current)return{content:"",steps:[]};const m=h.steps.length,{content:g,steps:w}=nVe(f,m);return g&&!h.aiAnalysis&&(n.current={...h,aiAnalysis:g}),w.length>0&&a(w),{content:g,steps:w}},[a]),c=x.useCallback(()=>{n.current=null,r.current=!1,t(Zz)},[]),u=x.useCallback(()=>{r.current=!0,t(f=>({...f,status:"failed",error:"工作流已中止"}))},[]),d=x.useCallback(()=>n.current,[]);return{state:e,startWorkflow:i,restoreWorkflow:s,updateStep:o,addSteps:a,addStepsFromAIResponse:l,resetWorkflow:c,abortWorkflow:u,getWorkflow:d}}const Lne=x.createContext(null),aVe=({children:e})=>{const t=oVe(),n=x.useMemo(()=>({state:t.state,startWorkflow:t.startWorkflow,restoreWorkflow:t.restoreWorkflow,updateStep:t.updateStep,addSteps:t.addSteps,addStepsFromAIResponse:t.addStepsFromAIResponse,resetWorkflow:t.resetWorkflow,abortWorkflow:t.abortWorkflow,getWorkflow:t.getWorkflow}),[t.state,t.startWorkflow,t.restoreWorkflow,t.updateStep,t.addSteps,t.addStepsFromAIResponse,t.resetWorkflow,t.abortWorkflow,t.getWorkflow]);return y.jsx(Lne.Provider,{value:n,children:e})};function lVe(){const e=x.useContext(Lne);if(!e)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return e}function Nne(){const e=lVe();return{startWorkflow:e.startWorkflow,restoreWorkflow:e.restoreWorkflow,updateStep:e.updateStep,addSteps:e.addSteps,addStepsFromAIResponse:e.addStepsFromAIResponse,resetWorkflow:e.resetWorkflow,abortWorkflow:e.abortWorkflow,getWorkflow:e.getWorkflow}}const Ap={DEFAULT_BOARD_NAME:"未命名画板",DEFAULT_FOLDER_NAME:"新建文件夹",SIDEBAR_WIDTH:280,SIDEBAR_MIN_WIDTH:200,SIDEBAR_MAX_WIDTH:400},cVe="drawnix-images";function uVe(e){return typeof e=="string"&&e.startsWith("data:image/")&&e.includes(";base64,")}async function dVe(e){const t=e.match(/^data:(image\/[^;]+);base64,(.+)$/);if(!t)return e;const[,n,r]=t;try{const i=atob(r),s=new Uint8Array(i.length);for(let f=0;f<i.length;f++)s[f]=i.charCodeAt(f);const o=new Blob([s],{type:n}),a=`img-${Date.now()}-${Math.random().toString(36).substring(2,10)}`,l=n.split("/")[1]||"png",c=`/__aitu_cache__/image/${a}.${l}`,u=await caches.open(cVe),d=new Response(o,{status:200,headers:{"Content-Type":n,"Content-Length":o.size.toString(),"Cache-Control":"max-age=31536000"}});return await u.put(c,d),c}catch(i){return console.error("[Migration] Failed to cache Base64 image:",i),e}}async function ZA(e){let t=!1;for(const n of e){if(n.url&&uVe(n.url)){const r=Math.round(n.url.length/1024),i=await dVe(n.url);i!==n.url&&(n.url=i,t=!0,console.log(`[Migration] Element ${n.id}: Base64 (${r}KB) -> ${i}`))}n.children&&Array.isArray(n.children)&&await ZA(n.children)&&(t=!0)}return t}const ml={DATABASE_NAME:"aitu-workspace",MIN_DATABASE_VERSION:8,STORES:{FOLDERS:"folders",BOARDS:"boards",STATE:"state"}},Qz="workspace_state";function ok(e=50){return new Promise(t=>{typeof window<"u"&&"requestIdleCallback"in window?window.requestIdleCallback(()=>t(),{timeout:e}):setTimeout(t,0)})}async function fVe(e){return new Promise(t=>{if(typeof indexedDB>"u"){console.warn("[WorkspaceStorage] IndexedDB not available, using min version"),t(ml.MIN_DATABASE_VERSION);return}const n=indexedDB.open(e);n.onsuccess=()=>{const r=n.result,i=r.version;r.close();const s=Math.max(i,ml.MIN_DATABASE_VERSION);console.log(`[WorkspaceStorage] Detected DB version: ${i}, using: ${s}`),t(s)},n.onerror=r=>{console.error("[WorkspaceStorage] Error detecting DB version:",r),t(10)},n.onblocked=()=>{console.warn("[WorkspaceStorage] DB blocked, using safe version 10"),t(10)}})}class hVe{constructor(){this.foldersStore=null,this.boardsStore=null,this.stateStore=null,this.initialized=!1,this.initPromise=null}async createStores(){const t=await fVe(ml.DATABASE_NAME);this.foldersStore=pi.createInstance({driver:pi.INDEXEDDB,name:ml.DATABASE_NAME,version:t,storeName:ml.STORES.FOLDERS,description:"Workspace folders storage"}),this.boardsStore=pi.createInstance({driver:pi.INDEXEDDB,name:ml.DATABASE_NAME,version:t,storeName:ml.STORES.BOARDS,description:"Workspace boards storage"}),this.stateStore=pi.createInstance({driver:pi.INDEXEDDB,name:ml.DATABASE_NAME,version:t,storeName:ml.STORES.STATE,description:"Workspace state storage"})}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise}}async doInitialize(){try{await this.createStores(),await Promise.all([this.foldersStore.ready(),this.boardsStore.ready(),this.stateStore.ready()]),this.initialized=!0}catch(t){console.error("[WorkspaceStorage] Failed to initialize:",t);const n=String(t);if(n.includes("can't be downgraded")||n.includes("version")){console.warn("[WorkspaceStorage] Version conflict detected, attempting recovery...");try{await this.deleteDatabase(),await this.createStores(),await Promise.all([this.foldersStore.ready(),this.boardsStore.ready(),this.stateStore.ready()]),this.initialized=!0,console.log("[WorkspaceStorage] Recovery successful, database recreated");return}catch(r){console.error("[WorkspaceStorage] Recovery failed:",r)}}throw new Error("Workspace storage initialization failed")}}async deleteDatabase(){return new Promise((t,n)=>{if(typeof indexedDB>"u"){t();return}const r=indexedDB.deleteDatabase(ml.DATABASE_NAME);r.onsuccess=()=>{console.log("[WorkspaceStorage] Database deleted successfully"),t()},r.onerror=()=>{console.error("[WorkspaceStorage] Failed to delete database"),n(new Error("Failed to delete database"))},r.onblocked=()=>{console.warn("[WorkspaceStorage] Database deletion blocked"),setTimeout(t,1e3)}})}getFoldersStore(){if(!this.foldersStore)throw new Error("WorkspaceStorage not initialized");return this.foldersStore}getBoardsStore(){if(!this.boardsStore)throw new Error("WorkspaceStorage not initialized");return this.boardsStore}getStateStore(){if(!this.stateStore)throw new Error("WorkspaceStorage not initialized");return this.stateStore}async saveFolder(t){await this.ensureInitialized(),await this.getFoldersStore().setItem(t.id,t)}async loadFolder(t){return await this.ensureInitialized(),this.getFoldersStore().getItem(t)}async loadAllFolders(){await this.ensureInitialized();const t=[];return await this.getFoldersStore().iterate(n=>{n&&n.id&&t.push(n)}),await ok(),t.sort((n,r)=>n.order-r.order)}async deleteFolder(t){await this.ensureInitialized(),await this.getFoldersStore().removeItem(t)}async saveBoard(t){await this.ensureInitialized(),await this.getBoardsStore().setItem(t.id,t)}async loadBoard(t){await this.ensureInitialized();const n=await this.getBoardsStore().getItem(t);if(n&&n.elements){n.elements=cT(n.elements);try{await ZA(n.elements)&&(await this.saveBoard(n),console.log(`[Migration] Board ${t}: Base64 URLs migrated and saved`))}catch(r){console.error(`[Migration] Board ${t}: Failed to migrate`,r)}}return n}async loadAllBoards(){await this.ensureInitialized();const t=[];await this.getBoardsStore().iterate(n=>{n&&n.id&&(n.elements&&(n.elements=cT(n.elements)),t.push(n))}),await ok();for(const n of t)if(n.elements)try{await ZA(n.elements)&&(await this.saveBoard(n),console.log(`[Migration] Board ${n.id}: Base64 URLs migrated and saved`))}catch(r){console.error(`[Migration] Board ${n.id}: Failed to migrate`,r)}return t.sort((n,r)=>n.order-r.order)}async loadFolderBoards(t){await this.ensureInitialized();const n=[];return await this.getBoardsStore().iterate(r=>{r&&r.folderId===t&&(r.elements&&(r.elements=cT(r.elements)),n.push(r))}),await ok(),n.sort((r,i)=>r.order-i.order)}async deleteBoard(t){await this.ensureInitialized(),await this.getBoardsStore().removeItem(t)}async deleteFolderBoards(t){await this.ensureInitialized();const n=await this.loadFolderBoards(t);await Promise.all(n.map(r=>this.deleteBoard(r.id)))}async saveState(t){await this.ensureInitialized(),await this.getStateStore().setItem(Qz,t)}async loadState(){return await this.ensureInitialized(),await this.getStateStore().getItem(Qz)||{currentBoardId:null,expandedFolderIds:[],sidebarWidth:Ap.SIDEBAR_WIDTH,sidebarCollapsed:!1}}async getBoardCount(){return await this.ensureInitialized(),this.getBoardsStore().length()}async clearAll(){await this.ensureInitialized(),await Promise.all([this.getFoldersStore().clear(),this.getBoardsStore().clear(),this.getStateStore().clear()])}async ensureInitialized(){this.initialized||await this.initialize()}}const tr=new hVe;function Jz(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}class Yo{constructor(){this.folders=new Map,this.boards=new Map,this.events$=new Ks,this.initialized=!1,this.initializationPromise=null,this.state={currentBoardId:null,expandedFolderIds:[],sidebarWidth:Ap.SIDEBAR_WIDTH,sidebarCollapsed:!1}}static getInstance(){return Yo.instance||(Yo.instance=new Yo),Yo.instance}async initialize(){if(!this.initialized)return this.initializationPromise?this.initializationPromise:(this.initializationPromise=this.doInitialize(),this.initializationPromise)}async doInitialize(){try{await tr.initialize();const[t,n,r]=await Promise.all([tr.loadAllFolders(),tr.loadAllBoards(),tr.loadState()]);await new Promise(i=>{"requestIdleCallback"in window?window.requestIdleCallback(()=>i(),{timeout:50}):setTimeout(i,0)}),this.folders=new Map(t.map(i=>[i.id,i])),this.boards=new Map(n.map(i=>[i.id,i])),this.state=r,this.initialized=!0}catch(t){throw console.error("[WorkspaceService] Failed to initialize:",t),this.initializationPromise=null,t}}async waitForInitialization(){if(!this.initialized)return this.initializationPromise?this.initializationPromise:this.initialize()}async createFolder(t){await this.ensureInitialized();const n=this.getFolderChildren(t.parentId||null),r=n.length>0?Math.max(...n.map(s=>s.order))+1:0,i={id:Jz(),name:t.name||Ap.DEFAULT_FOLDER_NAME,parentId:t.parentId||null,order:r,isExpanded:!0,createdAt:Date.now(),updatedAt:Date.now()};return this.folders.set(i.id,i),await tr.saveFolder(i),this.emit("folderCreated",i),i}async renameFolder(t,n){const r=this.folders.get(t);if(!r)throw new Error(`Folder ${t} not found`);r.name=n,r.updatedAt=Date.now(),this.folders.set(t,r),await tr.saveFolder(r),this.emit("folderUpdated",r)}async deleteFolder(t){const n=this.folders.get(t);if(!n)throw new Error(`Folder ${t} not found`);const r=this.getFolderChildren(t);for(const s of r)await this.deleteFolder(s.id);const i=this.getBoardsInFolder(t);for(const s of i)s.folderId=null,await tr.saveBoard(s);this.folders.delete(t),await tr.deleteFolder(t),this.emit("folderDeleted",n)}async deleteFolderWithContents(t){const n=this.folders.get(t);if(!n)throw new Error(`Folder ${t} not found`);const r=this.getBoardsInFolder(t);for(const s of r)this.boards.delete(s.id),await tr.deleteBoard(s.id),this.emit("boardDeleted",s);const i=this.getFolderChildren(t);for(const s of i)await this.deleteFolderWithContents(s.id);this.folders.delete(t),await tr.deleteFolder(t),this.emit("folderDeleted",n)}toggleFolderExpanded(t){const n=this.folders.get(t);n&&(n.isExpanded=!n.isExpanded,this.folders.set(t,n),n.isExpanded?this.state.expandedFolderIds.includes(t)||this.state.expandedFolderIds.push(t):this.state.expandedFolderIds=this.state.expandedFolderIds.filter(r=>r!==t),this.saveState(),this.emit("treeChanged"))}async createBoard(t){await this.ensureInitialized();const n=Jz(),r=Date.now(),i=this.getBoardsInFolder(t.folderId||null),s=i.length>0?Math.max(...i.map(a=>a.order))+1:0,o={id:n,name:t.name||Ap.DEFAULT_BOARD_NAME,folderId:t.folderId||null,order:s,elements:t.elements||[],viewport:t.viewport,theme:t.theme,createdAt:r,updatedAt:r};return this.boards.set(n,o),await tr.saveBoard(o),this.emit("boardCreated",o),o}async renameBoard(t,n){const r=this.boards.get(t);if(!r)throw new Error(`Board ${t} not found`);r.name=n,r.updatedAt=Date.now(),this.boards.set(t,r),await tr.saveBoard(r),this.emit("boardUpdated",r)}async deleteBoard(t){const n=this.boards.get(t);if(!n)throw new Error(`Board ${t} not found`);this.state.currentBoardId===t&&(this.state.currentBoardId=null,this.saveState()),this.boards.delete(t),await tr.deleteBoard(t),this.emit("boardDeleted",n)}async moveBoard(t,n,r,i){const s=this.boards.get(t);if(!s)throw new Error(`Board ${t} not found`);s.folderId=n,s.updatedAt=Date.now();const o=this.getBoardsInFolder(n).filter(c=>c.id!==t);let l=[...this.getFolderChildren(n).map(c=>({id:c.id,type:"folder"})),...o.map(c=>({id:c.id,type:"board"}))].sort((c,u)=>{var h,m,g,w;const d=c.type==="board"?((h=this.boards.get(c.id))==null?void 0:h.order)??0:((m=this.folders.get(c.id))==null?void 0:m.order)??0,f=u.type==="board"?((g=this.boards.get(u.id))==null?void 0:g.order)??0:((w=this.folders.get(u.id))==null?void 0:w.order)??0;return d-f});if(r&&i){const c=l.findIndex(u=>u.id===r);if(c!==-1){const u=i==="before"?c:c+1;l.splice(u,0,{id:s.id,type:"board"})}else l.push({id:s.id,type:"board"})}else l.push({id:s.id,type:"board"});for(let c=0;c<l.length;c++){const u=l[c];if(u.type==="board"){const d=this.boards.get(u.id);d&&(d.order=c,this.boards.set(u.id,d),await tr.saveBoard(d))}else{const d=this.folders.get(u.id);d&&(d.order=c,this.folders.set(u.id,d),await tr.saveFolder(d))}}this.emit("boardUpdated",s),this.emit("treeChanged")}async moveFolder(t,n,r,i){const s=this.folders.get(t);if(!s)throw new Error(`Folder ${t} not found`);if(n){let c=this.folders.get(n);for(;c;){if(c.id===t)throw new Error("Cannot move folder into itself or its descendants");c=c.parentId?this.folders.get(c.parentId):void 0}}s.parentId=n,s.updatedAt=Date.now();const o=this.getFolderChildren(n).filter(c=>c.id!==t),a=this.getBoardsInFolder(n);let l=[...o.map(c=>({id:c.id,type:"folder"})),...a.map(c=>({id:c.id,type:"board"}))].sort((c,u)=>{var h,m,g,w;const d=c.type==="board"?((h=this.boards.get(c.id))==null?void 0:h.order)??0:((m=this.folders.get(c.id))==null?void 0:m.order)??0,f=u.type==="board"?((g=this.boards.get(u.id))==null?void 0:g.order)??0:((w=this.folders.get(u.id))==null?void 0:w.order)??0;return d-f});if(r&&i){const c=l.findIndex(u=>u.id===r);if(c!==-1){const u=i==="before"?c:c+1;l.splice(u,0,{id:s.id,type:"folder"})}else l.push({id:s.id,type:"folder"})}else l.push({id:s.id,type:"folder"});for(let c=0;c<l.length;c++){const u=l[c];if(u.type==="board"){const d=this.boards.get(u.id);d&&(d.order=c,this.boards.set(u.id,d),await tr.saveBoard(d))}else{const d=this.folders.get(u.id);d&&(d.order=c,this.folders.set(u.id,d),await tr.saveFolder(d))}}this.emit("folderUpdated",s),this.emit("treeChanged")}async reorderItems(t){const n=Date.now();for(const r of t)if(r.type==="board"){const i=this.boards.get(r.id);i&&(i.order=r.order,i.updatedAt=n,this.boards.set(r.id,i),await tr.saveBoard(i))}else{const i=this.folders.get(r.id);i&&(i.order=r.order,i.updatedAt=n,this.folders.set(r.id,i),await tr.saveFolder(i))}this.emit("treeChanged")}async copyBoard(t){const n=this.boards.get(t);if(!n)throw new Error(`Board ${t} not found`);let r=`${n.name} 副本`;const i=Array.from(this.boards.values()).filter(a=>a.folderId===n.folderId).map(a=>a.name);let s=1;for(;i.includes(r);)s++,r=`${n.name} 副本 ${s}`;return await this.createBoard({name:r,folderId:n.folderId,elements:JSON.parse(JSON.stringify(n.elements)),viewport:n.viewport?{...n.viewport}:void 0,theme:n.theme})}async deleteBoardsBatch(t){for(const n of t)await this.deleteBoard(n)}async moveBoardsBatch(t,n){for(const r of t)await this.moveBoard(r,n)}async switchBoard(t){await this.ensureInitialized();const n=this.boards.get(t);if(!n)throw new Error(`Board ${t} not found`);return this.state.currentBoardId&&this.state.currentBoardId,this.state.currentBoardId=t,this.saveState(),this.emit("boardSwitched",n),n}async saveBoard(t,n){const r=this.boards.get(t);if(!r)throw new Error(`Board ${t} not found`);r.elements=n.children,r.viewport=n.viewport,r.theme=n.theme,r.updatedAt=Date.now(),this.boards.set(t,r),await tr.saveBoard(r)}async saveCurrentBoard(t){const n=this.state.currentBoardId;if(!n){console.warn("[WorkspaceService] No current board to save");return}await this.saveBoard(n,t)}getFolder(t){return this.folders.get(t)}getBoard(t){return this.boards.get(t)}getCurrentBoard(){return this.state.currentBoardId&&this.boards.get(this.state.currentBoardId)||null}getState(){return{...this.state}}getFolderChildren(t){return Array.from(this.folders.values()).filter(n=>n.parentId===t).sort((n,r)=>n.order-r.order)}getBoardsInFolder(t){return Array.from(this.boards.values()).filter(n=>n.folderId===t).sort((n,r)=>n.order-r.order)}getTree(){const t=s=>{const o=this.getFolderChildren(s.id),a=this.getBoardsInFolder(s.id),l=[...o.map(t),...a.map(n)];return{type:"folder",data:s,children:l}},n=s=>({type:"board",data:s}),r=this.getFolderChildren(null),i=this.getBoardsInFolder(null);return[...r.map(t),...i.map(n)]}setSidebarWidth(t){this.state.sidebarWidth=Math.max(Ap.SIDEBAR_MIN_WIDTH,Math.min(Ap.SIDEBAR_MAX_WIDTH,t)),this.saveState()}setSidebarCollapsed(t){this.state.sidebarCollapsed=t,this.saveState()}async saveState(){await tr.saveState(this.state)}observeEvents(){return this.events$.asObservable()}emit(t,n){this.events$.next({type:t,payload:n,timestamp:Date.now()})}async ensureInitialized(){this.initialized||await this.initialize()}isInitialized(){return this.initialized}hasBoards(){return this.boards.size>0}async reload(){try{const[t,n,r]=await Promise.all([tr.loadAllFolders(),tr.loadAllBoards(),tr.loadState()]);this.folders=new Map(t.map(i=>[i.id,i])),this.boards=new Map(n.map(i=>[i.id,i])),this.state=r,this.emit("tree-changed")}catch(t){throw console.error("[WorkspaceService] Failed to reload:",t),t}}}const qn=Yo.getInstance();function pVe(){const[e,t]=x.useState(!0),[n,r]=x.useState(null),[i,s]=x.useState([]),[o,a]=x.useState(null),[l,c]=x.useState(qn.getState()),[u,d]=x.useState(0),f=x.useCallback(()=>{s(qn.getTree()),a(qn.getCurrentBoard()),c(qn.getState())},[]);x.useEffect(()=>{let G=!0;(async()=>{try{t(!0),await qn.initialize(),G&&(f(),r(null))}catch(j){G&&r(j instanceof Error?j.message:"Failed to initialize")}finally{G&&t(!1)}})();const K=qn.observeEvents().subscribe(()=>{G&&(f(),d(j=>j+1))});return()=>{G=!1,K.unsubscribe()}},[f]);const h=x.useMemo(()=>qn.hasBoards(),[u]),m=x.useCallback(async G=>{try{return r(null),await qn.createFolder(G)}catch(W){return r(W instanceof Error?W.message:"Failed to create folder"),null}},[]),g=x.useCallback(async(G,W)=>{try{return r(null),await qn.renameFolder(G,W),!0}catch(K){return r(K instanceof Error?K.message:"Failed to rename folder"),!1}},[]),w=x.useCallback(async G=>{try{return r(null),await qn.deleteFolder(G),!0}catch(W){return r(W instanceof Error?W.message:"Failed to delete folder"),!1}},[]),C=x.useCallback(async G=>{try{return r(null),await qn.deleteFolderWithContents(G),!0}catch(W){return r(W instanceof Error?W.message:"Failed to delete folder with contents"),!1}},[]),b=x.useCallback(async(G,W,K,j)=>{try{return r(null),await qn.moveFolder(G,W,K,j),!0}catch(H){return r(H instanceof Error?H.message:"Failed to move folder"),!1}},[]),_=x.useCallback(G=>{qn.toggleFolderExpanded(G)},[]),T=x.useCallback(async G=>{try{return r(null),await qn.createBoard(G)}catch(W){return r(W instanceof Error?W.message:"Failed to create board"),null}},[]),S=x.useCallback(async(G,W)=>{try{return r(null),await qn.renameBoard(G,W),!0}catch(K){return r(K instanceof Error?K.message:"Failed to rename board"),!1}},[]),k=x.useCallback(async G=>{try{return r(null),await qn.deleteBoard(G),!0}catch(W){return r(W instanceof Error?W.message:"Failed to delete board"),!1}},[]),D=x.useCallback(async(G,W,K,j)=>{try{return r(null),await qn.moveBoard(G,W,K,j),!0}catch(H){return r(H instanceof Error?H.message:"Failed to move board"),!1}},[]),O=x.useCallback(async G=>{try{return r(null),await qn.switchBoard(G)}catch(W){return r(W instanceof Error?W.message:"Failed to switch board"),null}},[]),I=x.useCallback(async G=>{const W=qn.getCurrentBoard();if(!W)return!1;try{return await qn.saveBoard(W.id,G),!0}catch(K){return console.error("[useWorkspace] Failed to save board:",K),!1}},[]),R=x.useCallback(async G=>{try{return r(null),await qn.copyBoard(G)}catch(W){return r(W instanceof Error?W.message:"Failed to copy board"),null}},[]),F=x.useCallback(async G=>{try{return r(null),await qn.deleteBoardsBatch(G),!0}catch(W){return r(W instanceof Error?W.message:"Failed to delete boards"),!1}},[]),M=x.useCallback(async(G,W)=>{try{return r(null),await qn.moveBoardsBatch(G,W),!0}catch(K){return r(K instanceof Error?K.message:"Failed to move boards"),!1}},[]),$=x.useCallback(async G=>{try{return r(null),await qn.reorderItems(G),!0}catch(W){return r(W instanceof Error?W.message:"Failed to reorder items"),!1}},[]),A=x.useCallback(G=>{qn.setSidebarWidth(G),c(qn.getState())},[]),z=x.useCallback(G=>{qn.setSidebarCollapsed(G),c(qn.getState())},[]);return{isLoading:e,error:n,tree:i,currentBoard:o,workspaceState:l,hasBoards:h,createFolder:m,renameFolder:g,deleteFolder:w,deleteFolderWithContents:C,moveFolder:b,toggleFolderExpanded:_,createBoard:T,renameBoard:S,deleteBoard:k,moveBoard:D,copyBoard:R,switchBoard:O,saveBoard:I,deleteBoardsBatch:F,moveBoardsBatch:M,reorderItems:$,setSidebarWidth:A,setSidebarCollapsed:z,refresh:f}}var zc=(e=>(e.AI_TOOLS="ai-tools",e.CONTENT_TOOLS="content-tools",e.UTILITIES="utilities",e.CUSTOM="custom",e))(zc||{});const jne=[{id:"banana-prompt",name:"香蕉提示词",description:"查看和复制优质 AI 提示词",icon:"🍌",category:zc.CONTENT_TOOLS,url:"https://www.aiwind.org",defaultWidth:800,defaultHeight:600,permissions:["allow-scripts","allow-same-origin","allow-popups","allow-forms","allow-top-navigation-by-user-activation"]},{id:"pose-library",name:"动作场景库",description:"专业人体姿态参考素材库,提供多角度动作姿势",icon:"🧘",category:zc.CONTENT_TOOLS,url:"https://www.posemaniacs.com/zh-Hans/poses",defaultWidth:900,defaultHeight:700,permissions:["allow-scripts","allow-same-origin","allow-popups","allow-forms","allow-top-navigation-by-user-activation"]},{id:"batch-image",name:"批量出图工具",description:"Excel式批量AI图片生成,支持批量编辑和快速生成",icon:"🎨",category:zc.AI_TOOLS,url:"/batch-image.html",defaultWidth:1200,defaultHeight:800,permissions:["allow-scripts","allow-same-origin","allow-forms","allow-modals"]}],qu={defaultWidth:600,defaultHeight:400},gqe={[zc.AI_TOOLS]:"AI 工具",[zc.CONTENT_TOOLS]:"内容工具",[zc.UTILITIES]:"实用工具",[zc.CUSTOM]:"自定义工具"},fs=class fs{constructor(){this.customTools=[],this.isInitialized=!1,this.initialize()}static getInstance(){return fs.instance||(fs.instance=new fs),fs.instance}getAvailableTools(){return[...jne,...this.customTools]}getToolById(t){return this.getAvailableTools().find(r=>r.id===t)||null}async initialize(){if(!this.isInitialized)try{const t=await pi.getItem(fs.STORAGE_KEY);t&&(this.isCompatibleVersion(t.version)?this.customTools=t.tools:(console.warn("[Toolbox] Incompatible version, resetting custom tools"),await this.resetCustomTools()))}catch(t){console.error("[Toolbox] Failed to load custom tools:",t)}finally{this.isInitialized=!0}}async saveCustomTools(){try{const t={version:fs.STORAGE_VERSION,tools:this.customTools,updatedAt:Date.now()};await pi.setItem(fs.STORAGE_KEY,t)}catch(t){throw console.error("[Toolbox] Failed to save custom tools:",t),t}}async addCustomTool(t){if(this.customTools.length>=fs.MAX_CUSTOM_TOOLS)throw new Error(`Maximum ${fs.MAX_CUSTOM_TOOLS} custom tools allowed`);if(this.validateToolDefinition(t),this.customTools.some(i=>i.id===t.id))throw new Error(`Tool with id "${t.id}" already exists`);const r={...t,id:t.id||`custom-${Date.now()}`,category:t.category||zc.CUSTOM,defaultWidth:t.defaultWidth||800,defaultHeight:t.defaultHeight||600,permissions:t.permissions||["allow-scripts","allow-same-origin","allow-popups","allow-forms","allow-top-navigation-by-user-activation"]};this.customTools.push(r),await this.saveCustomTools()}async removeCustomTool(t){const n=this.customTools.length;this.customTools=this.customTools.filter(i=>i.id!==t);const r=this.customTools.length<n;return r&&await this.saveCustomTools(),r}async updateCustomTool(t,n){const r=this.customTools.findIndex(s=>s.id===t);if(r===-1)return!1;const i={...this.customTools[r],...n,id:t};return this.validateToolDefinition(i),this.customTools[r]=i,await this.saveCustomTools(),!0}getToolsByCategory(){const t=this.getAvailableTools(),n={};return t.forEach(r=>{const i=r.category||"utilities";n[i]||(n[i]=[]),n[i].push(r)}),n}searchTools(t){if(!t.trim())return this.getAvailableTools();const n=t.toLowerCase().trim();return this.getAvailableTools().filter(r=>{var i;return r.name.toLowerCase().includes(n)||((i=r.description)==null?void 0:i.toLowerCase().includes(n))||r.id.toLowerCase().includes(n)})}getCustomTools(){return[...this.customTools]}async clearCustomTools(){this.customTools=[],await this.saveCustomTools()}validateToolDefinition(t){if(!t.name||!t.url)throw new Error("Tool name and URL are required");try{const n=new URL(t.url);if(!["https:","http:"].includes(n.protocol))throw new Error("Only HTTP/HTTPS URLs are allowed")}catch{throw new Error("Invalid URL format")}if(t.name.length>50)throw new Error("Tool name too long (max 50 characters)");if(t.description&&t.description.length>200)throw new Error("Tool description too long (max 200 characters)")}isCompatibleVersion(t){return t===fs.STORAGE_VERSION}async resetCustomTools(){this.customTools=[],await this.saveCustomTools()}};fs.STORAGE_KEY="aitu:custom-tools",fs.STORAGE_VERSION="1.0",fs.MAX_CUSTOM_TOOLS=50;let QA=fs;const yx=QA.getInstance();class gVe{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=yx.getToolById("banana-prompt");if(!n){console.error('❌ Tool "banana-prompt" not found');return}Pc.insertTool(t,n.id,n.url,[100,100],{width:n.defaultWidth||qu.defaultWidth,height:n.defaultHeight||qu.defaultHeight},{name:n.name,category:n.category,permissions:n.permissions})}insertXiaohongshuTool(){const t=this.getBoard();if(!t)return;const n=yx.getToolById("xiaohongshu-tool");if(!n){console.error('❌ Tool "xiaohongshu-tool" not found');return}Pc.insertTool(t,n.id,n.url,[300,300],{width:n.defaultWidth||qu.defaultWidth,height:n.defaultHeight||qu.defaultHeight},{name:n.name,category:n.category,permissions:n.permissions})}insertToolById(t,n=200,r=200){const i=this.getBoard();if(!i)return;const s=yx.getToolById(t);if(!s){console.error(`❌ Tool "${t}" not found`);return}Pc.insertTool(i,s.id,s.url,[n,r],{width:s.defaultWidth||qu.defaultWidth,height:s.defaultHeight||qu.defaultHeight},{name:s.name,category:s.category,permissions:s.permissions})}listAllTools(){yx.getAvailableTools().forEach((n,r)=>{})}getAllToolElements(){const t=this.getBoard();if(!t)return;Pc.getAllTools(t).forEach((r,i)=>{})}removeAllTools(){const t=this.getBoard();if(!t)return;Pc.getAllTools(t).forEach(r=>{Pc.removeTool(t,r.id)})}help(){}}const mVe=new gVe;typeof window<"u"&&(window.testToolbox=mVe);const vVe={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)"},yVe={autoHideDelay:3e3},wVe=({board:e,config:t,className:n,displayMode:r="auto",autoTriggerConfig:i})=>{const s=x.useRef(null),o=x.useRef(null);x.useRef(null);const a={...vVe,...t},l={...yVe,...i},[c,u]=x.useState(()=>({expanded:r==="always"?!0:a.defaultExpanded,dragging:!1,autoMode:r==="auto",manuallyExpanded:!1})),d=x.useRef({isDragging:!1,startPoint:null}),f=x.useRef(null),[h,m]=x.useState(null),g=x.useRef(null),[w,C]=x.useState(!1),b=120,_=x.useRef(0),T=x.useRef({zoom:e.viewport.zoom,offsetX:e.viewport.offsetX,offsetY:e.viewport.offsetY}),S=x.useRef(!1),k=x.useCallback(()=>{if(!e||!e.children)return[];const ve=[];return e.children.forEach(N=>{try{let he=null;N.points&&Array.isArray(N.points)?he=X.getRectangleByPoints(N.points):N.x!==void 0&&N.y!==void 0&&(he={x:N.x,y:N.y,width:N.width||100,height:N.height||100}),he&&he.width>0&&he.height>0&&ve.push({id:N.id,bounds:he,type:N.type})}catch(he){console.warn("Failed to get bounds for element:",N.id,he)}}),ve},[e]),D=x.useCallback(()=>{const N=Q.getBoardContainer(e).getBoundingClientRect(),he=e.viewport.zoom,fe=pu(e),ne=fe[0],ie=fe[1],ue=N.width/he,Te=N.height/he;return{x:ne,y:ie,width:ue,height:Te}},[e]),O=x.useRef(c.expanded);O.current=c.expanded;const I=x.useRef(null),R=x.useRef(1);x.useEffect(()=>{if(r==="always"){O.current||u(N=>({...N,expanded:!0}));return}if(r!=="auto")return;const ve=setInterval(()=>{const N=e.viewport,he=T.current,fe=Math.abs(N.zoom-he.zoom)>.001,ne=Math.abs(N.offsetX-he.offsetX)>.5||Math.abs(N.offsetY-he.offsetY)>.5;if(fe||ne){if(T.current={zoom:N.zoom,offsetX:N.offsetX,offsetY:N.offsetY},!S.current){S.current=!0;return}_.current=Date.now(),O.current||u(ue=>({...ue,expanded:!0,manuallyExpanded:!1}))}},100);return()=>{clearInterval(ve)}},[r,e]),x.useEffect(()=>{if(r!=="auto"||!c.expanded||c.manuallyExpanded||c.dragging)return;const ve=setTimeout(()=>{u(N=>!N.autoMode||N.manuallyExpanded||N.dragging?N:{...N,expanded:!1})},l.autoHideDelay);return()=>{clearTimeout(ve)}},[r,c.expanded,c.manuallyExpanded,c.dragging,l.autoHideDelay]);const F=x.useCallback((ve,N)=>{if(ve.length===0)return{x:N.x-200,y:N.y-200,width:N.width+400,height:N.height+400};let he=N.x,fe=N.y,ne=N.x+N.width,ie=N.y+N.height;ve.forEach(Te=>{const{x:De,y:ye,width:Ne,height:Re}=Te.bounds;he=Math.min(he,De),fe=Math.min(fe,ye),ne=Math.max(ne,De+Ne),ie=Math.max(ie,ye+Re)});const ue=100;return{x:he-ue,y:fe-ue,width:ne-he+ue*2,height:ie-fe+ue*2}},[]),M=x.useCallback(ve=>{const he=(a.width-20)/ve.width,fe=(a.height-20)/ve.height;return Math.min(he,fe)},[a.width,a.height]),$=x.useCallback((ve,N,he,fe)=>{const ie=(ve-he.x)*fe+10,ue=(N-he.y)*fe+10;return[ie,ue]},[]),A=x.useCallback((ve,N,he,fe)=>{const ie=(ve-10)/fe+he.x,ue=(N-10)/fe+he.y;return[ie,ue]},[]),z=x.useCallback((ve,N,he)=>{if(100*he<5)return;ve.strokeStyle="rgba(0, 0, 0, 0.05)",ve.lineWidth=.5;const ie=Math.floor(N.x/100)*100,ue=Math.floor(N.y/100)*100,Te=N.x+N.width,De=N.y+N.height;for(let ye=ie;ye<=Te;ye+=100){const[Ne]=$(ye,0,N,he);ve.beginPath(),ve.moveTo(Ne,0),ve.lineTo(Ne,a.height),ve.stroke()}for(let ye=ue;ye<=De;ye+=100){const[,Ne]=$(0,ye,N,he);ve.beginPath(),ve.moveTo(0,Ne),ve.lineTo(a.width,Ne),ve.stroke()}},[$,a.width,a.height]),G=x.useCallback(()=>{const ve=s.current;if(!ve)return;const N=ve.getContext("2d");if(!N)return;N.clearRect(0,0,a.width,a.height);const he=k(),fe=D();if(he.length===0&&!fe){N.fillStyle="#999",N.font="12px sans-serif",N.textAlign="center",N.textBaseline="middle",N.fillText("空画布",a.width/2,a.height/2);return}const ne=F(he,fe),ie=M(ne);I.current=ne,R.current=ie,z(N,ne,ie),N.fillStyle=a.elementColor,N.strokeStyle="rgba(0, 0, 0, 0.1)",N.lineWidth=.5,he.forEach(He=>{const{x:et,y:gt,width:Ye,height:je}=He.bounds,[Me,_e]=$(et,gt,ne,ie),We=Ye*ie,Se=je*ie;N.fillRect(Me,_e,We,Se),N.strokeRect(Me,_e,We,Se)});const[ue,Te]=$(fe.x,fe.y,ne,ie),De=fe.width*ie,ye=fe.height*ie;N.fillStyle=a.viewportColor,N.fillRect(ue,Te,De,ye),N.strokeStyle=a.viewportColor.replace("0.3","1"),N.lineWidth=2,N.strokeRect(ue,Te,De,ye);const Ne=8;N.fillStyle=a.viewportColor.replace("0.3","0.8"),N.fillRect(ue,Te,Ne,2),N.fillRect(ue,Te,2,Ne),N.fillRect(ue+De-Ne,Te,Ne,2),N.fillRect(ue+De-2,Te,2,Ne),N.fillRect(ue,Te+ye-2,Ne,2),N.fillRect(ue,Te+ye-Ne,2,Ne),N.fillRect(ue+De-Ne,Te+ye-2,Ne,2),N.fillRect(ue+De-2,Te+ye-Ne,2,Ne);const Re=g.current;if(Re){const He=Re.x-De/2,et=Re.y-ye/2;N.fillStyle="rgba(243, 156, 18, 0.15)",N.fillRect(He,et,De,ye),N.strokeStyle="rgba(243, 156, 18, 0.8)",N.lineWidth=2,N.strokeRect(He,et,De,ye)}},[e,a,k,D,F,M,$,z]),W=x.useCallback(ve=>{ve.preventDefault(),ve.stopPropagation();const N=s.current;if(!N||!I.current)return;const he=N.getBoundingClientRect(),fe=ve.clientX-he.left,ne=ve.clientY-he.top,[ie,ue]=A(fe,ne,I.current,R.current);d.current={isDragging:!0,startPoint:[fe,ne]},u(Te=>({...Te,dragging:!0})),K(ie,ue)},[A,e]),K=x.useCallback((ve,N)=>{const fe=Q.getBoardContainer(e).getBoundingClientRect(),ne=e.viewport.zoom,ie=ve-fe.width/(2*ne),ue=N-fe.height/(2*ne);$t.updateViewport(e,[ie,ue],ne),requestAnimationFrame(()=>G())},[e,G]),j=x.useCallback(ve=>{if(!d.current.isDragging||!I.current)return;ve.preventDefault(),ve.stopPropagation();const N=s.current;if(!N)return;const he=N.getBoundingClientRect(),fe=ve.clientX-he.left,ne=ve.clientY-he.top,[ie,ue]=A(fe,ne,I.current,R.current);K(ie,ue)},[A,K]),H=x.useCallback(()=>{d.current={isDragging:!1,startPoint:null},u(ve=>({...ve,dragging:!1}))},[]),L=x.useCallback((ve,N)=>{const he=f.current;if(!he||!I.current)return;const fe=he.getContext("2d");if(!fe)return;const[ne,ie]=A(ve,N,I.current,R.current),ue=D(),Te=ue.width,De=ue.height,ye=Te,Ne=De;fe.clearRect(0,0,b,b),fe.fillStyle="#fff",fe.fillRect(0,0,b,b);const Re=ne-ye/2,He=ie-Ne/2,et=b/ye,gt=b/Ne,Ye=Math.min(et,gt),je=(b-ye*Ye)/2,Me=(b-Ne*Ye)/2;k().forEach(We=>{const{bounds:Se}=We;if(Se.x+Se.width>=Re&&Se.x<=Re+ye&&Se.y+Se.height>=He&&Se.y<=He+Ne){const pe=(Se.x-Re)*Ye+je,Be=(Se.y-He)*Ye+Me,Pe=Se.width*Ye,Qe=Se.height*Ye;fe.fillStyle="rgba(0, 0, 0, 0.6)",fe.fillRect(pe,Be,Pe,Qe)}}),fe.strokeStyle="rgba(90, 79, 207, 0.6)",fe.lineWidth=1,fe.setLineDash([4,4]),fe.beginPath(),fe.moveTo(0,b/2),fe.lineTo(b,b/2),fe.stroke(),fe.beginPath(),fe.moveTo(b/2,0),fe.lineTo(b/2,b),fe.stroke(),fe.setLineDash([]),fe.strokeStyle="rgba(90, 79, 207, 0.3)",fe.lineWidth=2,fe.strokeRect(0,0,b,b)},[k,D,A]),V=x.useCallback(()=>{c.dragging||C(!0)},[c.dragging]),Y=x.useCallback(()=>{C(!1),m(null),g.current=null},[]),q=x.useCallback(ve=>{if(c.dragging){C(!1),g.current=null;return}const N=s.current;if(!N)return;const he=N.getBoundingClientRect(),fe=ve.clientX-he.left,ne=ve.clientY-he.top,ie={x:fe,y:ne};m(ie),g.current=ie,C(!0),L(fe,ne),G()},[c.dragging,L,G]),Z=x.useRef(!1),re=x.useCallback(ve=>{Z.current=!0;const N=s.current;if(!N)return;const he=ve.touches[0],fe=N.getBoundingClientRect(),ne=he.clientX-fe.left,ie=he.clientY-fe.top,ue={x:ne,y:ie};m(ue),g.current=ue,C(!0),L(ne,ie),G()},[L,G]),ae=x.useCallback(ve=>{const N=s.current;if(!N)return;const he=ve.touches[0],fe=N.getBoundingClientRect(),ne=he.clientX-fe.left,ie=he.clientY-fe.top,ue={x:ne,y:ie};m(ue),g.current=ue,C(!0),L(ne,ie),G()},[L,G]),de=x.useCallback(()=>{Z.current=!1,setTimeout(()=>{Z.current||(C(!1),m(null),g.current=null,G())},500)},[G]);x.useEffect(()=>{if(!c.expanded)return;G();const ve=setInterval(()=>{G()},100);return()=>{clearInterval(ve)}},[e,c.expanded,G]);const oe=x.useCallback(()=>{u(ve=>{const N=!ve.expanded;return{...ve,expanded:N,manuallyExpanded:N}})},[]),ee={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},ce=w&&(Z.current||!c.dragging),me=h?{position:"absolute",right:a.width+8,top:Math.max(0,Math.min(h.y-b/2,a.height-b)),width:b,height:b,opacity:ce?1:0,pointerEvents:"none",transition:"opacity 0.15s ease-out, top 0.1s ease-out"}:{display:"none"};return y.jsxs("div",{ref:o,className:`minimap ${c.expanded?"minimap--expanded":"minimap--collapsed"} ${r==="auto"?"minimap--auto":""} ${n||""}`,style:{...ee,zIndex:ma.MINIMAP},"data-track":"minimap_container",children:[c.expanded&&y.jsxs("div",{className:"minimap__content",children:[y.jsx("canvas",{ref:s,width:a.width,height:a.height,className:"minimap__canvas",onPointerDown:W,onPointerMove:j,onPointerUp:H,onPointerLeave:H,onMouseEnter:V,onMouseLeave:Y,onMouseMove:q,onTouchStart:re,onTouchMove:ae,onTouchEnd:de,style:{cursor:c.dragging?"grabbing":"pointer"}}),y.jsx("div",{className:"minimap__preview",style:me,children:y.jsx("canvas",{ref:f,width:b,height:b,className:"minimap__preview-canvas"})})]}),a.collapsible&&y.jsx("button",{className:`minimap__toggle ${c.expanded?"minimap__toggle--expanded":""}`,onClick:oe,title:c.expanded?"折叠小地图":"展开小地图","data-track":"minimap_click_toggle",children:y.jsx(bS,{})})]})},eH=10,xVe=3e3,bVe=({showMinimap:e=!0,container:t})=>{var O,I,R,F;const n=Hr(),{t:r}=jn(),{isDrawerOpen:i,drawerWidth:s}=j3(),[o,a]=x.useState(!1),[l,c]=x.useState(!0),[u,d]=x.useState(!1),f=x.useRef(null),h=x.useRef({zoom:((O=n==null?void 0:n.viewport)==null?void 0:O.zoom)||1,offsetX:((I=n==null?void 0:n.viewport)==null?void 0:I.offsetX)||0,offsetY:((R=n==null?void 0:n.viewport)==null?void 0:R.offsetY)||0}),m=x.useRef(!1),g=x.useRef(null),w=x.useMemo(()=>i?s+eH:eH,[i,s]),C=x.useCallback(()=>{$t.updateZoom(n,n.viewport.zoom-.1)},[n]),b=x.useCallback(()=>{$t.updateZoom(n,n.viewport.zoom+.1)},[n]),_=x.useCallback(()=>{$t.fitViewport(n),a(!1)},[n]),T=x.useCallback(()=>{$t.updateZoom(n,1),a(!1)},[n]),S=x.useCallback(()=>{c(M=>{const $=!M;return d($),$})},[]);x.useEffect(()=>{if(!l||!n)return;const M=Q.getBoardContainer(n);if(!M)return;const $=A=>{var G;const z=A.target;(G=f.current)!=null&&G.contains(z)||(c(!1),d(!1))};return M.addEventListener("mousedown",$),()=>{M.removeEventListener("mousedown",$)}},[l,n]),x.useEffect(()=>{if(!e||!n)return;const M=setInterval(()=>{const $=n.viewport,A=h.current,z=Math.abs($.zoom-A.zoom)>.001,G=Math.abs($.offsetX-A.offsetX)>.5||Math.abs($.offsetY-A.offsetY)>.5;if(z||G){if(h.current={zoom:$.zoom,offsetX:$.offsetX,offsetY:$.offsetY},!m.current){m.current=!0;return}l||(c(!0),d(!1)),g.current&&clearTimeout(g.current)}},100);return()=>{clearInterval(M)}},[e,n,l]),x.useEffect(()=>{if(!(!l||u))return g.current=setTimeout(()=>{c(!1)},xVe),()=>{g.current&&clearTimeout(g.current)}},[l,u]);const k=x.useCallback(()=>{a(M=>!M)},[]),D=Math.round((((F=n==null?void 0:n.viewport)==null?void 0:F.zoom)||1)*100);return y.jsxs("div",{className:"view-navigation",style:{right:w,zIndex:ma.VIEW_NAVIGATION},ref:f,children:[y.jsxs("div",{className:"view-navigation__zoom",children:[y.jsx("button",{className:"view-navigation__zoom-btn",onClick:C,title:r("zoom.out"),"aria-label":r("zoom.out"),"data-track":"view_nav_zoom_out",children:y.jsx(Kte,{})}),y.jsxs(ti,{sideOffset:8,open:o,onOpenChange:a,placement:"bottom",children:[y.jsx(ni,{asChild:!0,children:y.jsxs("button",{className:"view-navigation__zoom-percent",onClick:k,title:r("zoom.fit"),"aria-label":r("zoom.fit"),"data-track":"view_nav_zoom_menu",children:[D,"%"]})}),y.jsx(ri,{container:t,style:{zIndex:ma.POPOVER},children:y.jsxs("div",{className:"view-navigation-zoom-menu",children:[y.jsxs("button",{className:"zoom-menu-item",onClick:_,"data-track":"view_nav_zoom_fit",children:[y.jsx("span",{className:"zoom-menu-item__label",children:r("zoom.fit")}),y.jsx("span",{className:"zoom-menu-item__shortcut",children:"⌘⇧="})]}),y.jsxs("button",{className:"zoom-menu-item",onClick:T,"data-track":"view_nav_zoom_100",children:[y.jsx("span",{className:"zoom-menu-item__label",children:r("zoom.100")}),y.jsx("span",{className:"zoom-menu-item__shortcut",children:"⌘0"})]})]})})]}),y.jsx("button",{className:"view-navigation__zoom-btn",onClick:b,title:r("zoom.in"),"aria-label":r("zoom.in"),"data-track":"view_nav_zoom_in",children:y.jsx(dy,{})}),e&&y.jsx("button",{className:`view-navigation__minimap-toggle ${l?"view-navigation__minimap-toggle--expanded":""}`,onClick:S,title:l?"折叠小地图":"展开小地图","aria-label":l?"折叠小地图":"展开小地图","data-track":"view_nav_minimap_toggle",children:y.jsx(k3,{})})]}),e&&l&&y.jsx("div",{className:"view-navigation__minimap",children:y.jsx(wVe,{board:n,displayMode:"always",config:{width:180,height:120,position:"top-right",margin:0,collapsible:!1,defaultExpanded:!0}})})]})};function CVe(){return()=>{}}const EVe=({selectedModel:e,onSelect:t,language:n="zh"})=>{const[r,i]=x.useState(!1),s=x.useRef(null),o=x.useRef(null),a=bo(e),l=(a==null?void 0:a.shortCode)||"img";x.useEffect(()=>{if(!r)return;const d=f=>{s.current&&!s.current.contains(f.target)&&i(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[r]),x.useEffect(()=>{if(!r)return;const d=f=>{f.key==="Escape"&&i(!1)};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[r]);const c=x.useCallback(()=>{i(d=>!d)},[]),u=x.useCallback(d=>{t(d),i(!1)},[t]);return y.jsxs("div",{className:"model-dropdown",ref:s,children:[y.jsxs("button",{className:`model-dropdown__trigger ${r?"model-dropdown__trigger--open":""}`,onClick:c,type:"button","aria-haspopup":"listbox","aria-expanded":r,title:(a==null?void 0:a.shortLabel)||(a==null?void 0:a.label)||e,children:[y.jsx("span",{className:"model-dropdown__at",children:"@"}),y.jsx("span",{className:"model-dropdown__code",children:l})]}),r&&y.jsxs("div",{className:"model-dropdown__menu",ref:o,role:"listbox","aria-label":n==="zh"?"选择模型":"Select Model",children:[y.jsx("div",{className:"model-dropdown__header",children:n==="zh"?"选择图片模型":"Select Image Model"}),y.jsx("div",{className:"model-dropdown__list",children:Xl.map(d=>{const f=d.id===e;return y.jsxs("div",{className:`model-dropdown__item ${f?"model-dropdown__item--selected":""}`,onClick:()=>u(d.id),role:"option","aria-selected":f,children:[y.jsxs("div",{className:"model-dropdown__item-content",children:[y.jsxs("div",{className:"model-dropdown__item-name",children:[y.jsxs("span",{className:"model-dropdown__item-code",children:["@",d.shortCode]}),y.jsx("span",{className:"model-dropdown__item-label",children:d.shortLabel||d.label}),d.isVip&&y.jsx("span",{className:"model-dropdown__item-vip",children:"VIP"})]}),d.description&&y.jsx("div",{className:"model-dropdown__item-desc",children:d.description})]}),f&&y.jsx(rg,{size:16,className:"model-dropdown__item-check"})]},d.id)})})]})]})},SVe=({selectedSize:e,onSelect:t,modelId:n,language:r="zh"})=>{const[i,s]=x.useState(!1),o=x.useRef(null),a=x.useMemo(()=>jNe(n),[n]);x.useEffect(()=>{if(a.length===0)return;if(!a.some(f=>f.value===e)){const f=hee(n);t(f)}},[n,a,e,t]);const l=x.useMemo(()=>{const d=a.find(f=>f.value===e);return(d==null?void 0:d.label)||e},[a,e]);x.useEffect(()=>{if(!i)return;const d=f=>{o.current&&!o.current.contains(f.target)&&s(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[i]),x.useEffect(()=>{if(!i)return;const d=f=>{f.key==="Escape"&&s(!1)};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[i]);const c=x.useCallback(()=>{s(d=>!d)},[]),u=x.useCallback(d=>{t(d),s(!1)},[t]);return a.length===0?null:y.jsxs("div",{className:"size-dropdown",ref:o,children:[y.jsxs("button",{className:`size-dropdown__trigger ${i?"size-dropdown__trigger--open":""}`,onClick:c,type:"button","aria-haspopup":"listbox","aria-expanded":i,title:r==="zh"?"选择尺寸":"Select Size",children:[y.jsx("span",{className:"size-dropdown__label",children:l}),y.jsx(YJ,{size:14,className:"size-dropdown__icon"})]}),i&&y.jsxs("div",{className:"size-dropdown__menu",role:"listbox","aria-label":r==="zh"?"选择尺寸":"Select Size",children:[y.jsx("div",{className:"size-dropdown__header",children:r==="zh"?"选择尺寸":"Select Size"}),y.jsx("div",{className:"size-dropdown__list",children:a.map(d=>{const f=d.value===e;return y.jsxs("div",{className:`size-dropdown__item ${f?"size-dropdown__item--selected":""}`,onClick:()=>u(d.value),role:"option","aria-selected":f,children:[y.jsx("span",{className:"size-dropdown__item-label",children:d.label}),f&&y.jsx(rg,{size:14,className:"size-dropdown__item-check"})]},d.value)})})]})]})},_Ve=({content:e,pinned:t=!1,isPreset:n=!1,onClick:r,onTogglePin:i,onDelete:s,language:o="zh",disabled:a=!1})=>{const l=u=>{u.stopPropagation(),i==null||i()},c=u=>{u.stopPropagation(),s==null||s()};return y.jsxs("div",{className:`prompt-list-item ${t?"prompt-list-item--pinned":""} ${n?"prompt-list-item--preset":""} ${a?"prompt-list-item--disabled":""}`,onClick:a?void 0:r,title:e,children:[t&&y.jsx("div",{className:"prompt-list-item__pin-badge",children:y.jsx(k9,{size:10})}),n&&y.jsx("div",{className:"prompt-list-item__preset-badge",children:y.jsx(Fg,{size:10})}),y.jsx("span",{className:"prompt-list-item__text",children:e}),y.jsxs("div",{className:"prompt-list-item__actions",children:[i&&y.jsx("button",{type:"button",className:"prompt-list-item__action",onClick:l,title:t?o==="zh"?"取消置顶":"Unpin":o==="zh"?"置顶":"Pin",children:t?y.jsx(JLe,{size:14}):y.jsx(k9,{size:14})}),s&&y.jsx("button",{type:"button",className:"prompt-list-item__action prompt-list-item__action--delete",onClick:c,title:o==="zh"?"删除":"Delete",children:y.jsx(ig,{size:14})})]})]})},TVe=({title:e,items:t,onSelect:n,onTogglePin:r,onDelete:i,language:s="zh",disabled:o=!1,showCount:a=!0,className:l=""})=>y.jsxs("div",{className:`prompt-list-panel ${l}`,children:[y.jsxs("div",{className:"prompt-list-panel__header",children:[y.jsx("span",{className:"prompt-list-panel__title",children:e}),a&&y.jsx("span",{className:"prompt-list-panel__count",children:t.length})]}),y.jsx("div",{className:"prompt-list-panel__list",children:t.map(c=>y.jsx(_Ve,{content:c.content,pinned:c.pinned,isPreset:c.isPreset,onClick:()=>n==null?void 0:n(c.content),onTogglePin:r&&!c.isPreset?()=>r(c.id):void 0,onDelete:i&&!c.isPreset?()=>i(c.id):void 0,language:s,disabled:o},c.id))})]}),kVe=({onSelectPrompt:e,language:t})=>{const{history:n,removeHistory:r,togglePinHistory:i,refreshHistory:s}=pS({deduplicateWithPresets:!1}),[o,a]=x.useState(!1),l=x.useRef(null),c=x.useRef(null),u=x.useRef(null),d=x.useMemo(()=>(Jee[t]||[]).map((_,T)=>({id:`preset_${T}`,content:_.content,isPreset:!0})),[t]),f=x.useMemo(()=>{const b=n.map(S=>({id:S.id,content:S.content,pinned:S.pinned})),_=new Set(n.map(S=>S.content.trim().toLowerCase())),T=d.filter(S=>!_.has(S.content.trim().toLowerCase())).map(S=>({id:S.id,content:S.content,pinned:!1,isPreset:!0}));return[...b,...T]},[n,d]);x.useEffect(()=>()=>{c.current&&clearTimeout(c.current),u.current&&clearTimeout(u.current)},[]);const h=x.useCallback(()=>{u.current&&(clearTimeout(u.current),u.current=null),c.current=setTimeout(()=>{s(),a(!0)},150)},[s]),m=x.useCallback(()=>{c.current&&(clearTimeout(c.current),c.current=null),u.current=setTimeout(()=>{a(!1)},200)},[]),g=x.useCallback(b=>{e(b),a(!1)},[e]),w=x.useCallback(b=>{b.startsWith("preset_")||r(b)},[r]),C=x.useCallback(b=>{b.startsWith("preset_")||i(b)},[i]);return y.jsxs("div",{ref:l,className:"prompt-history-popover",onMouseEnter:h,onMouseLeave:m,children:[y.jsx("button",{className:"prompt-history-popover__trigger",title:t==="zh"?"提示词":"Prompts","data-track":"ai_input_click_history",children:y.jsx(OLe,{size:18})}),o&&y.jsx("div",{className:"prompt-history-popover__panel-wrapper",children:y.jsx(TVe,{title:t==="zh"?"提示词":"Prompts",items:f,onSelect:g,onTogglePin:C,onDelete:w,language:t,showCount:!0})})]})};let Dp=null;function tH(e){Dp=e}class Fne{async execute(t){const{operation:n,args:r}=t;switch(n){case"canvas_insert":return this.handleCanvasInsert(r);case"insert_mermaid":return this.handleMermaid(r);case"insert_mindmap":return this.handleMindmap(r);case"insert_svg":return this.handleSvg(r);case"generate_grid_image":return this.handleGridImage(r);case"generate_inspiration_board":return this.handleInspirationBoard(r);case"split_image":return this.handleSplitImage(r);case"generate_long_video":return this.handleLongVideo(r);case"ai_analyze":return this.handleAIAnalyze(r);case"generate_image":return this.handleGenerateImage(r);case"generate_video":return this.handleGenerateVideo(r);default:return{success:!1,error:`Unknown operation: ${n}`,type:"error"}}}findWorkZoneForMCP(t,n){var s;const r=$r.getAllWorkZones(t);if(r.length===0)return null;for(const o of r)if((s=o.workflow.steps)==null?void 0:s.some(l=>l.mcp===n))return o;return r.sort((o,a)=>(a.createdAt||0)-(o.createdAt||0))[0]||null}async handleCanvasInsert(t){const n=Dp;if(!n)return{success:!1,error:"画布未初始化",type:"error"};const{items:r,startPoint:i,verticalGap:s=50,horizontalGap:o=20}=t;if(!r||r.length===0)return{success:!1,error:"没有要插入的内容",type:"error"};try{let a=i||this.getInsertionPoint(n),l=0;for(const c of r){const{type:u,content:d}=c;switch(u){case"image":await wm(n,d,a,!1,{width:400,height:400},!1,!0),a=[a[0],a[1]+400+s],l++;break;case"video":await lh(n,d,a),a=[a[0],a[1]+300+s],l++;break;case"text":Yn.insertText(n,a,d),a=[a[0],a[1]+100+s],l++;break;case"svg":const h={url:this.svgToDataUrl(d),width:400,height:400};Yn.insertImage(n,h,a),a=[a[0],a[1]+400+s],l++;break}}return{success:!0,data:{insertedCount:l},type:"canvas"}}catch(a){return{success:!1,error:a.message||"插入失败",type:"error"}}}async handleMermaid(t){const n=Dp;if(!n)return{success:!1,error:"画布未初始化",type:"error"};const{mermaid:r}=t;if(!r)return{success:!1,error:"缺少 mermaid 参数",type:"error"};try{const{parseMermaidToDrawnix:i}=await ln(async()=>{const{parseMermaidToDrawnix:d}=await import("./index-_FyCDKGq.js").then(f=>f.O);return{parseMermaidToDrawnix:d}},__vite__mapDeps([0,1,2]),import.meta.url),s=this.extractCodeBlock(r,"mermaid");let o;try{o=await i(s)}catch{o=await i(s.replace(/"/g,"'"))}const{elements:a}=o;if(!a||a.length===0)return{success:!1,error:"Mermaid 解析未生成元素",type:"error"};const l=this.findWorkZoneForMCP(n,"insert_mermaid"),c=this.getViewportCenter(n),u=this.insertElementsToCanvasAtPoint(n,a,c);return u.success&&(requestAnimationFrame(()=>{this.centerInsertedElementsInViewport(n,a.length)}),l&&setTimeout(()=>{$r.removeWorkZone(n,l.id),window.dispatchEvent(new CustomEvent("ai-generation-complete",{detail:{type:"mermaid",success:!0}}))},100)),{success:u.success,data:{elementsCount:u.elementsCount},type:"canvas",error:u.error}}catch(i){return console.error("[SWCapabilities] Mermaid conversion failed:",i),{success:!1,error:`Mermaid 转换失败: ${i.message}`,type:"error"}}}async handleMindmap(t){const n=Dp;if(!n)return{success:!1,error:"画布未初始化",type:"error"};const{markdown:r}=t;if(!r)return{success:!1,error:"缺少 markdown 参数",type:"error"};try{const{parseMarkdownToDrawnix:i}=await ln(async()=>{const{parseMarkdownToDrawnix:u}=await import("./index-DEjUAZUe.js");return{parseMarkdownToDrawnix:u}},__vite__mapDeps([3,4,5]),import.meta.url),s=this.extractCodeBlock(r,"markdown");let o;try{o=await i(s)}catch{o=await i(s.replace(/"/g,"'"))}if(!o)return{success:!1,error:"Markdown 解析未生成元素",type:"error"};o.points=[[0,0]];const a=this.findWorkZoneForMCP(n,"insert_mindmap"),l=this.getViewportCenter(n),c=this.insertElementsToCanvasAtPoint(n,[o],l);return c.success&&(requestAnimationFrame(()=>{this.centerInsertedElementsInViewport(n,1)}),a&&setTimeout(()=>{$r.removeWorkZone(n,a.id),window.dispatchEvent(new CustomEvent("ai-generation-complete",{detail:{type:"mindmap",success:!0}}))},100)),{success:c.success,data:{type:"mindmap",elementsCount:c.elementsCount},type:"canvas",error:c.error}}catch(i){return console.error("[SWCapabilities] Mindmap conversion failed:",i),{success:!1,error:`思维导图转换失败: ${i.message}`,type:"error"}}}async handleSvg(t){const n=Dp;if(!n)return{success:!1,error:"画布未初始化",type:"error"};const{svg:r,width:i=400,startPoint:s}=t;if(!r)return{success:!1,error:"缺少 svg 参数",type:"error"};try{const o=this.extractSvgCode(r),a=this.normalizeSvg(o),l=this.parseSvgDimensions(a),c=Math.min(Math.max(i,100),800),u=l.height/l.width,d=c*u,f=this.svgToDataUrl(a);let h=s||this.getInsertionPoint(n);h=[h[0]-c/2,h[1]];const m={url:f,width:c,height:d};Yn.insertImage(n,m,h);const g=[h[0]+c/2,h[1]+d/2];return requestAnimationFrame(()=>{So(n,g)}),{success:!0,data:{width:c,height:d},type:"canvas"}}catch(o){return{success:!1,error:`SVG 插入失败: ${o.message}`,type:"error"}}}async handleGridImage(t){try{const{createGridImageTask:n}=await ln(async()=>{const{createGridImageTask:i}=await import("./grid-image-DRAUp_wj.js");return{createGridImageTask:i}},[],import.meta.url),r=await n(t);return{success:r.success,data:r.data,type:r.type,taskId:r.taskId,error:r.error}}catch(n){return{success:!1,error:`宫格图生成失败: ${n.message}`,type:"error"}}}async handleInspirationBoard(t){try{const{createInspirationBoardTask:n}=await ln(async()=>{const{createInspirationBoardTask:i}=await import("./inspiration-board-8CO8xK39.js");return{createInspirationBoardTask:i}},[],import.meta.url),r=await n(t);return{success:r.success,data:r.data,type:r.type,taskId:r.taskId,error:r.error}}catch(n){return{success:!1,error:`灵感图生成失败: ${n.message}`,type:"error"}}}async handleSplitImage(t){const n=Dp;if(!n)return{success:!1,error:"画布未初始化",type:"error"};const{imageUrl:r}=t;if(!r)return{success:!1,error:"缺少 imageUrl 参数",type:"error"};try{const{splitAndInsertImages:i}=await ln(async()=>{const{splitAndInsertImages:o}=await Promise.resolve().then(()=>gje);return{splitAndInsertImages:o}},void 0,import.meta.url),s=await i(n,r,{scrollToResult:!0});return{success:s.success,data:{count:s.count},type:"canvas",error:s.error}}catch(i){return{success:!1,error:`图片拆分失败: ${i.message}`,type:"error"}}}async handleLongVideo(t){try{const{createLongVideoTask:n}=await ln(async()=>{const{createLongVideoTask:i}=await Promise.resolve().then(()=>UWe);return{createLongVideoTask:i}},void 0,import.meta.url),r=await n(t);return{success:r.success,data:r.data,type:r.type,taskId:r.taskId,error:r.error}}catch(n){return{success:!1,error:`长视频生成失败: ${n.message}`,type:"error"}}}async handleAIAnalyze(t){var n;try{const{analyzeWithAI:r}=await ln(async()=>{const{analyzeWithAI:s}=await import("./ai-analyze-D3V-tpIV.js");return{analyzeWithAI:s}},[],import.meta.url),i=await r(t.context,{onChunk:s=>{},onAddSteps:s=>{}});return{success:i.success,data:{response:i.response},type:"text",addSteps:(n=i.generatedSteps)==null?void 0:n.map(s=>({id:s.id,mcp:s.mcp,args:s.args,description:s.description,status:s.status})),error:i.error}}catch(r){return{success:!1,error:`AI 分析失败: ${r.message}`,type:"error"}}}async handleGenerateImage(t){var n;try{const{createImageTask:r}=await ln(async()=>{const{createImageTask:s}=await Promise.resolve().then(()=>p7e);return{createImageTask:s}},void 0,import.meta.url),i=await r(t);return i.success?{success:!0,data:i.data,type:"image",taskId:i.taskId,taskIds:(n=i.data)==null?void 0:n.taskIds}:(console.error("[SWCapabilities] Image task creation failed:",i.error),{success:!1,error:i.error||"图片生成任务创建失败",type:"error"})}catch(r){return console.error("[SWCapabilities] Image generation error:",r),{success:!1,error:`图片生成失败: ${r.message}`,type:"error"}}}async handleGenerateVideo(t){var n;try{const{createVideoTask:r}=await ln(async()=>{const{createVideoTask:s}=await Promise.resolve().then(()=>b7e);return{createVideoTask:s}},void 0,import.meta.url),i=await r(t);return i.success?{success:!0,data:i.data,type:"video",taskId:i.taskId,taskIds:(n=i.data)==null?void 0:n.taskIds}:(console.error("[SWCapabilities] Video task creation failed:",i.error),{success:!1,error:i.error||"视频生成任务创建失败",type:"error"})}catch(r){return console.error("[SWCapabilities] Video generation error:",r),{success:!1,error:`视频生成失败: ${r.message}`,type:"error"}}}getInsertionPoint(t){const n=t.appState,r=(n==null?void 0:n.lastSelectedElementIds)||[];if(r.length>0){const i=r.map(s=>t.children.find(o=>o.id===s)).filter(Boolean);if(i.length>0)try{const s=Et(t,i,!1);return[s.x+s.width/2,s.y+s.height+50]}catch{}}if(t.children&&t.children.length>0){let i=0,s=100;for(const o of t.children)try{const a=Et(t,[o],!1),l=a.y+a.height;l>i&&(i=l,s=a.x+a.width/2)}catch{}return[s,i+50]}return[100,100]}insertElementsToCanvas(t,n){try{const r=this.getInsertionPoint(t);return t.insertFragment({elements:JSON.parse(JSON.stringify(n))},r,na.paste),requestAnimationFrame(()=>{So(t,r)}),{success:!0,elementsCount:n.length}}catch(r){return{success:!1,error:r.message}}}insertElementsToCanvasAtPoint(t,n,r){try{return t.insertFragment({elements:JSON.parse(JSON.stringify(n))},r,na.paste),requestAnimationFrame(()=>{So(t,r)}),{success:!0,elementsCount:n.length}}catch(i){return console.error("[SWCapabilities] insertElementsToCanvasAtPoint failed:",i),{success:!1,error:i.message}}}getViewportCenter(t){try{const r=Q.getBoardContainer(t).getBoundingClientRect(),i=t.viewport.zoom,s=pu(t);if(!s)return[0,0];const o=s[0]+r.width/(2*i),a=s[1]+r.height/(2*i);return[o,a]}catch(n){return console.warn("[SWCapabilities] Error getting viewport center:",n),[0,0]}}centerInsertedElementsInViewport(t,n){try{const i=t.children.slice(-n);if(i.length===0){console.warn("[SWCapabilities] No inserted elements found to center");return}const s=Et(t,i,!1),a=Q.getBoardContainer(t).getBoundingClientRect(),l=80,c=a.width-l*2,u=a.height-l*2,d=c/s.width,f=u/s.height;let h=Math.min(d,f);h=Math.min(Math.max(h,.2),1.5);const m=s.x+s.width/2,g=s.y+s.height/2,w=m-a.width/(2*h),C=g-a.height/(2*h);$t.updateViewport(t,[w,C],h)}catch(r){console.warn("[SWCapabilities] Error centering inserted elements:",r)}}extractCodeBlock(t,n){const r=new RegExp(`\`\`\`${n}\\s*\\n([\\s\\S]*?)\\n\\s*\`\`\``,"i"),i=t.match(r);if(i)return i[1].trim();const s=new RegExp(`\`\`\`${n}\\s*([\\s\\S]*?)\\s*\`\`\``,"i"),o=t.match(s);if(o)return o[1].trim();const a=new RegExp(`^${n}\\s*\\n`,"i");return a.test(t.trim())?t.trim().replace(a,"").trim():t.trim()}extractSvgCode(t){let n=this.extractCodeBlock(t,"svg");if(n===t&&(n=this.extractCodeBlock(t,"xml")),n===t&&!n.trim().startsWith("<svg")){const r=n.match(/<svg[\s\S]*?<\/svg>/i);r&&(n=r[0])}return n.trim()}normalizeSvg(t){let n=t.trim();return n.includes("xmlns=")||(n=n.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),n}parseSvgDimensions(t){const n=t.match(/viewBox=["']([^"']+)["']/i);if(n){const[,,s,o]=n[1].split(/\s+/).map(Number);if(s&&o)return{width:s,height:o}}const r=t.match(/width=["'](\d+)(?:px)?["']/i),i=t.match(/height=["'](\d+)(?:px)?["']/i);return r&&i?{width:parseInt(r[1]),height:parseInt(i[1])}:{width:400,height:400}}svgToDataUrl(t){return`data:image/svg+xml,${encodeURIComponent(t).replace(/'/g,"%27").replace(/"/g,"%22")}`}}const PVe=new Fne;async function AVe(e,t={}){const{timestamp:n="last",format:r="image/png",quality:i=.92,timeout:s=3e4}=t;return new Promise((o,a)=>{const l=document.createElement("video"),c=document.createElement("canvas"),u=c.getContext("2d");if(!u){a(new Error("Failed to get canvas context"));return}let d=null,f=!1;const h=()=>{d!==null&&(clearTimeout(d),d=null),l.removeEventListener("loadedmetadata",g),l.removeEventListener("seeked",w),l.removeEventListener("error",C),l.src="",l.load()},m=()=>{if(!f){f=!0;try{c.width=l.videoWidth,c.height=l.videoHeight,u.drawImage(l,0,0,c.width,c.height);const b=c.toDataURL(r,i);h(),o({dataUrl:b,timestamp:l.currentTime,width:l.videoWidth,height:l.videoHeight})}catch(b){h(),a(new Error(`Failed to extract frame: ${b}`))}}},g=()=>{const b=l.duration;let _;n==="last"?_=Math.max(0,b-.1):n==="first"?_=.1:_=Math.min(Math.max(0,n),b),l.currentTime=_},w=()=>{m()},C=()=>{var b;h(),a(new Error(`Failed to load video: ${((b=l.error)==null?void 0:b.message)||"Unknown error"}`))};d=window.setTimeout(()=>{f||(h(),a(new Error(`Video frame extraction timed out after ${s}ms`)))},s),l.addEventListener("loadedmetadata",g),l.addEventListener("seeked",w),l.addEventListener("error",C),l.crossOrigin="anonymous",l.muted=!0,l.playsInline=!0,l.preload="auto",l.src=e})}async function DVe(e){return AVe(e,{timestamp:"last"})}function IVe(e){var t;return!!((t=e.params)!=null&&t.longVideoMeta)}function OVe(e){var t;return((t=e.params)==null?void 0:t.longVideoMeta)||null}class Wp{constructor(){this.isInitialized=!1,this.batches=new Map,this.initTimestamp=0}static getInstance(){return Wp.instance||(Wp.instance=new Wp),Wp.instance}initialize(){this.isInitialized||(this.isInitialized=!0,this.initTimestamp=Date.now(),bn.observeTaskUpdates().subscribe(t=>{if(t.type==="taskUpdated"&&t.task.status===ht.COMPLETED&&t.task.type===Ft.VIDEO&&IVe(t.task)){if((t.task.completedAt||0)<this.initTimestamp)return;this.handleSegmentCompleted(t.task).catch(r=>{console.error("[LongVideoChain] Error handling completed segment:",r)})}}))}async handleSegmentCompleted(t){var c;const n=OVe(t);if(!n)return;const{segmentIndex:r,totalSegments:i,scripts:s,batchId:o}=n,a=(c=t.result)==null?void 0:c.url;let l=this.batches.get(o);if(l||(l={batchId:o,totalSegments:i,completedSegments:new Map,processedSegments:new Set,creatingNextFor:null,isMerging:!1,mergeCompleted:!1},this.batches.set(o,l)),!l.processedSegments.has(r)){if(l.processedSegments.add(r),a&&l.completedSegments.set(r,a),l.completedSegments.size===i){await this.mergeAndInsert(l);return}if(l.creatingNextFor!==r&&r<i){l.creatingNextFor=r;try{await this.createNextSegment(t,n,s,a)}finally{l.creatingNextFor=null}}}}async createNextSegment(t,n,r,i){const s=n.segmentIndex+1,o=r.find(c=>c.index===s);if(!o){console.error(`[LongVideoChain] Script not found for segment ${s}`);return}let a;if(i)try{a=(await DVe(i)).dataUrl}catch(c){console.error("[LongVideoChain] Failed to extract last frame:",c)}const l={...n,segmentIndex:s,needsLastFrame:s<n.totalSegments};O3(o,l,a)}async mergeAndInsert(t){if(!(t.isMerging||t.mergeCompleted)){t.isMerging=!0;try{const n=[];for(let s=1;s<=t.totalSegments;s++){const o=t.completedSegments.get(s);o&&n.push(o)}if(n.length===0){console.error("[LongVideoChain] No video URLs to merge");return}const i=await dte(n,(s,o,a)=>{const l=a||`${o} ${s.toFixed(1)}%`});await this.insertMergedVideo(i.url),t.mergeCompleted=!0,this.cleanupBatch(t.batchId)}catch(n){console.error("[LongVideoChain] Merge failed:",n),this.cleanupBatch(t.batchId)}finally{t.isMerging=!1}}}async insertMergedVideo(t){try{await qA("video",t)}catch(n){console.error("[LongVideoChain] Failed to insert video to canvas:",n)}}cleanupBatch(t){const n=this.batches.get(t);n&&(n.completedSegments.clear(),n.processedSegments.clear(),this.batches.delete(t))}getBatchStatus(t){const n=this.batches.get(t);return n?{completed:n.completedSegments.size,total:n.totalSegments,isMerging:n.isMerging,mergeCompleted:n.mergeCompleted}:null}}const MVe=Wp.getInstance();function RVe(){MVe.initialize()}function nH(){return`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}async function rH(e){return new Promise((t,n)=>{const r=new Image,i=e.startsWith("http")&&!e.startsWith(location.origin);r.crossOrigin="anonymous",r.onload=()=>t(r),r.onerror=()=>{n(i?new Error("无法加载外部图片,可能是跨域 (CORS) 限制。请先下载图片到本地后再操作。"):new Error("图片加载失败,请检查图片是否有效"))},r.src=e})}function BVe(e,t=.92){return e.toDataURL("image/jpeg",t)}class LVe{async split(t,n){const{rows:r,cols:i}=n;if(r<1||i<1)throw new Error("Grid rows and cols must be at least 1");const s=await rH(t),o=s.naturalWidth,a=s.naturalHeight,l=Math.floor(o/i),c=Math.floor(a/r),u=[];for(let d=0;d<r;d++)for(let f=0;f<i;f++){const h=d*i+f,m=f*l,g=d*c,w=document.createElement("canvas");w.width=l,w.height=c;const C=w.getContext("2d");if(!C)throw new Error("Failed to get canvas 2d context");C.drawImage(s,m,g,l,c,0,0,l,c);const b=BVe(w);u.push({id:nH(),imageData:b,originalIndex:h,width:l,height:c})}return u}async splitToBlob(t,n){const{rows:r,cols:i}=n;if(r<1||i<1)throw new Error("Grid rows and cols must be at least 1");const s=await rH(t),o=s.naturalWidth,a=s.naturalHeight,l=Math.floor(o/i),c=Math.floor(a/r),u=[];for(let d=0;d<r;d++)for(let f=0;f<i;f++){const h=d*i+f,m=f*l,g=d*c,w=document.createElement("canvas");w.width=l,w.height=c;const C=w.getContext("2d");if(!C)throw new Error("Failed to get canvas 2d context");C.drawImage(s,m,g,l,c,0,0,l,c);const b=await new Promise((T,S)=>{w.toBlob(k=>{k?T(k):S(new Error("Failed to create blob"))},"image/png",.92)}),_=URL.createObjectURL(b);u.push({id:nH(),imageData:_,originalIndex:h,width:l,height:c})}return u}revokeBlobUrls(t){for(const n of t)n.imageData.startsWith("blob:")&&URL.revokeObjectURL(n.imageData)}}const iH=new LVe;function Go(e,t){return Math.random()*(t-e)+e}function wx(e){const t=[...e];for(let n=t.length-1;n>0;n--){const r=Math.floor(Math.random()*(n+1));[t[n],t[r]]=[t[r],t[n]]}return t}class NVe{calculate(t,n,r,i){switch(n){case"scattered":return this.scatteredLayout(t,r,i);case"grid":return this.gridLayout(t,r);case"circular":return this.circularLayout(t,r,i);case"inspiration-board":return this.inspirationBoardLayout(t,r,i);default:return console.warn(`[LayoutEngine] Unknown layout style: ${n}, falling back to grid`),this.gridLayout(t,r)}}scatteredLayout(t,n,r){const{maxRotation:i=15,minScale:s=.85,maxScale:o=1.15,positionJitter:a=40}=r||{},{canvasWidth:l,canvasHeight:c,startX:u,startY:d,gap:f=20}=n,h=t.length,m=Math.ceil(Math.sqrt(h)),g=Math.ceil(h/m),w=Math.max(...t.map(O=>O.width)),C=Math.max(...t.map(O=>O.height)),b=l-f*2,_=c-f*2,T=b/m,S=_/g,k=Math.min((T-f)/w,(S-f)/C,1),D=wx(t.map((O,I)=>I));return t.map((O,I)=>{const R=Math.floor(I/m),F=I%m,M=u+f+F*T+T/2,$=d+f+R*S+S/2,A=Go(-a,a),z=Go(-a,a),G=Go(-i,i),W=Go(s,o),K=k*W,j=O.width*K,H=O.height*K;return{...O,x:M+A-j/2,y:$+z-H/2,rotation:G,scale:K,zIndex:D[I]}})}gridLayout(t,n){const{canvasWidth:r,canvasHeight:i,startX:s,startY:o,gap:a=20}=n,l=t.length,c=Math.ceil(Math.sqrt(l)),u=Math.ceil(l/c),d=Math.max(...t.map(b=>b.width)),f=Math.max(...t.map(b=>b.height)),h=r-a*(c+1),m=i-a*(u+1),g=h/c,w=m/u,C=Math.min(g/d,w/f,1);return t.map((b,_)=>{const T=Math.floor(_/c),S=_%c,k=b.width*C,D=b.height*C,O=s+a+S*(g+a),I=o+a+T*(w+a),R=O+(g-k)/2,F=I+(w-D)/2;return{...b,x:R,y:F,rotation:0,scale:C,zIndex:_}})}circularLayout(t,n,r){const{centerIndex:i=-1,radius:s,startAngle:o=-90}=r||{},{canvasWidth:a,canvasHeight:l,startX:c,startY:u}=n,d=c+a/2,f=u+l/2,h=i>=0&&i<t.length?t.filter((F,M)=>M!==i):t,m=i>=0&&i<t.length?t[i]:null,g=Math.max(...t.map(F=>F.width)),w=Math.max(...t.map(F=>F.height)),C=Math.max(g,w),b=h.length,_=C*.8,T=b*C*1.2,S=Math.max(_,T/(2*Math.PI)),k=s||Math.min(S,Math.min(a,l)/2-C/2),D=Math.min(a,l),O=Math.min(D*.25/C,1),I=[];if(m){const F=m.width*O*1.2,M=m.height*O*1.2;I.push({...m,x:d-F/2,y:f-M/2,rotation:0,scale:O*1.2,zIndex:b})}const R=360/b;return h.forEach((F,M)=>{const A=(o+M*R)*Math.PI/180,z=F.width*O,G=F.height*O,W=d+k*Math.cos(A)-z/2,K=f+k*Math.sin(A)-G/2;I.push({...F,x:W,y:K,rotation:0,scale:O,zIndex:M})}),I}inspirationBoardLayout(t,n,r){const{minWidthRatio:i=z0.minWidthRatio,maxWidthRatio:s=z0.maxWidthRatio,maxRotation:o=z0.maxRotation,gap:a=z0.gap}=r||{},{canvasWidth:l,canvasHeight:c,startX:u,startY:d}=n,f=t.length,h=this.assignSizeCategories(f),m=t.reduce((S,k)=>S+k.width,0)/f,g=t.reduce((S,k)=>S+k.height,0)/f,w=l||1200,C=c||600,b=Math.min(w*.25/m,C*.4/g,1),_=this.calculateInspirationBoardPositions(f,w,C,a),T=wx(t.map((S,k)=>k));return t.map((S,k)=>{const D=_[k],O=h[k];let I;switch(O){case"large":I=Go(1.2,s);break;case"medium":I=Go(.9,1.1);break;case"small":I=Go(i,.85);break;default:I=1}const R=b*I,F=Go(-o,o),M=Go(-20,20),$=Go(-15,15),A=S.width*R,z=S.height*R;return{...S,x:u+D.x+M-A/2,y:d+D.y+$-z/2,rotation:F,scale:R,zIndex:T[k]}})}assignSizeCategories(t){const n=[],r=Math.max(2,Math.floor(t*.25)),i=Math.max(2,Math.floor(t*.25)),s=t-r-i;for(let o=0;o<r;o++)n.push("large");for(let o=0;o<s;o++)n.push("medium");for(let o=0;o<i;o++)n.push("small");return wx(n)}calculateInspirationBoardPositions(t,n,r,i){const s=[],o=Math.ceil(t/4),a=Math.ceil(t/o),l=(n-i*2)/a,c=(r-i*2)/o;for(let u=0;u<t;u++){const d=Math.floor(u/a),f=u%a,h=i+f*l+l/2,m=i+d*c+c/2,g=Go(-l*.3,l*.3),w=Go(-c*.2,c*.2);s.push({x:h+g,y:m+w})}return wx(s)}calculateRequiredSize(t,n,r=.5){const i=t.length,s=Math.ceil(Math.sqrt(i)),o=Math.ceil(i/s),a=Math.max(...t.map(h=>h.width)),l=Math.max(...t.map(h=>h.height)),c=20,u=n==="scattered"?60:40,d=s*a*r+(s+1)*c+u*2,f=o*l*r+(o+1)*c+u*2;return{width:d,height:f}}}const sH=new NVe;class jVe{constructor(){this.board=null}setBoard(t){this.board=t}getBoard(){return this.board}async generate(t){const{theme:n,gridConfig:r=Oc.gridConfig,layoutStyle:i=Oc.layoutStyle,imageSize:s=Oc.imageSize,imageQuality:o=Oc.imageQuality}=t;try{const a=this.buildPrompt(n,r),l=await du.generateImage(a,{size:s,quality:o,response_format:"url"});if(!l.data||l.data.length===0)throw new Error("AI 生成图片失败:未返回图片数据");const c=l.data[0].url||l.data[0].b64_json;if(!c)throw new Error("AI 生成图片失败:未返回图片 URL");const u=await Mn.getImageForAI(c),d=u.type==="base64"?u.value:c,f=await iH.split(d,r),h=this.calculateLayoutParams(f),m=sH.calculate(f,i,h);return{success:!0,originalImageUrl:c,elements:m}}catch(a){return console.error("[GridImageService] Generation failed:",a),{success:!1,error:a.message||"宫格图生成失败"}}}async processExistingImage(t,n,r="scattered"){try{const i=await Mn.getImageForAI(t),s=i.type==="base64"?i.value:t,o=await iH.split(s,n),a=this.calculateLayoutParams(o),l=sH.calculate(o,r,a);return{success:!0,originalImageUrl:t,elements:l}}catch(i){return console.error("[GridImageService] Processing failed:",i),{success:!1,error:i.message||"宫格图处理失败"}}}async insertToBoard(t,n){if(!this.board)throw new Error("画板未初始化,请先调用 setBoard");let r=(n==null?void 0:n[0])??100,i=n==null?void 0:n[1];if(i===void 0){const o=bh(this.board);i=(o==null?void 0:o[1])??100,r=(o==null?void 0:o[0])??r}const s=[...t].sort((o,a)=>o.zIndex-a.zIndex);for(const o of s){const a=r+o.x,l=i+o.y,c={url:o.imageData,width:o.width*o.scale,height:o.height*o.scale};Yn.insertImage(this.board,c,[a,l])}}async generateAndInsert(t,n){const r=await this.generate(t);return r.success&&r.elements&&await this.insertToBoard(r.elements,n),r}buildPrompt(t,n){const r=Pee.zh;return r(t,n.rows,n.cols)}calculateLayoutParams(t){const n=t.reduce((h,m)=>h+m.width,0),r=t.reduce((h,m)=>h+m.height,0),i=t.length,s=Math.ceil(Math.sqrt(i)),o=Math.ceil(i/s),a=n/i,l=r/i,c=30,u=50,d=s*a+(s+1)*c+u*2,f=o*l+(o+1)*c+u*2;return{canvasWidth:d,canvasHeight:f,startX:0,startY:0,gap:c}}}const oH=new jVe;function FVe(){const e=An.get();return(e==null?void 0:e.imageModelName)||$g()}function $Ve(){const e=An.get();return(e==null?void 0:e.textModelName)||"deepseek-v3.2"}function zVe(e,t,n){if(t.length>0)return t.join(`
2059
+ `);let wt="新任务";if(Me.finalPrompt)wt=Me.finalPrompt;else if(Me.selection.texts.length>0)wt=Me.selection.texts[0];else if(Me.userInstruction){const sn=Me.userInstruction.indexOf(":"),Pn=Me.userInstruction.indexOf(":"),dr=sn>=0&&Pn>=0?Math.min(sn,Pn):Math.max(sn,Pn);dr>=0&&dr<Me.userInstruction.length-1?wt=Me.userInstruction.substring(dr+1).trim():wt=Me.userInstruction}else Me.model.id&&(wt=`模型: ${Me.model.id}`);const Ct=wt;await Hn.updateSession(pe.id,{title:Ct}),pe.title=Ct,o(sn=>[pe,...sn]),l(pe.id);const $e=Date.now(),Fe=`msg_${$e}_user`,rt=[{type:"text",text:Qe}],bt=[...Me.selection.images,...Me.selection.graphics];for(let sn=0;sn<bt.length;sn++)rt.push({type:"data-file",data:{filename:`image-${sn+1}.png`,mediaType:"image/png",url:bt[sn]}});for(let sn=0;sn<Me.selection.videos.length;sn++)rt.push({type:"data-file",data:{filename:`video-${sn+1}.mp4`,mediaType:"video/mp4",url:Me.selection.videos[sn]}});const on={id:Fe,role:"user",parts:rt},tt=`msg_${$e}_workflow`,Ut={id:tt,role:"assistant",parts:[{type:"text",text:`${qz}${tt}`}]};_(sn=>{const Pn=new Map(sn);return Pn.set(tt,_e),Pn}),T.current=tt;const kn={id:Fe,sessionId:pe.id,role:ea.USER,content:Qe,timestamp:Date.now(),status:go.SUCCESS,attachments:bt.length>0||Me.selection.videos.length>0?[...bt.map((sn,Pn)=>({id:`${Fe}-img-${Pn}`,name:`image-${Pn+1}.png`,type:"image/png",size:0,data:sn,isBlob:!1})),...Me.selection.videos.map((sn,Pn)=>({id:`${Fe}-vid-${Pn}`,name:`video-${Pn+1}.mp4`,type:"video/mp4",size:0,data:sn,isBlob:!1}))]:void 0};await Hn.addMessage(kn);const Cn={id:tt,sessionId:pe.id,role:ea.ASSISTANT,content:`${qz}${tt}`,timestamp:Date.now(),status:go.STREAMING,workflow:_e};await Hn.addMessage(Cn),(Rn=W.setMessagesWithRaw)==null||Rn.call(W,[on,Ut],[kn,Cn])},[W,t]),oe=x.useCallback(async je=>{var _e;let Me=T.current;if(!Me){for(const[We,Se]of b.entries())if(Se.id===je.id){Me=We,T.current=We;break}}Me&&(_(We=>{const Se=new Map(We);return Se.set(Me,je),Se}),Hn.updateMessage(Me,{workflow:je}),(_e=W.updateRawMessageWorkflow)==null||_e.call(W,Me,je))},[a,s,W,b]),ee=x.useCallback(je=>{const Me=T.current;Me&&_(_e=>{var pe;const We=new Map(_e),Se=We.get(Me);if(Se){const Be=Se.logs||[],Pe={...Se,logs:[...Be,je]};We.set(Me,Pe),Hn.updateMessage(Me,{workflow:Pe}),(pe=W.updateRawMessageWorkflow)==null||pe.call(W,Me,Pe)}return We})},[W]),ce=x.useRef(null),me=x.useCallback(je=>{const Me=T.current;Me&&_(_e=>{const We=new Map(_e),Se=We.get(Me);if(Se){const pe=Se.logs||[];let Be=-1;for(let Qe=pe.length-1;Qe>=0;Qe--)if(pe[Qe].type==="thinking"){Be=Qe;break}let Pe;if(Be>=0){const Qe=[...pe],wt=Qe[Be];Qe[Be]={...wt,content:wt.content+je},Pe={...Se,logs:Qe}}else Pe={...Se,logs:[...pe,{type:"thinking",timestamp:Date.now(),content:je}]};We.set(Me,Pe),ce.current&&clearTimeout(ce.current),ce.current=setTimeout(()=>{var Qe;Hn.updateMessage(Me,{workflow:Pe}),(Qe=W.updateRawMessageWorkflow)==null||Qe.call(W,Me,Pe)},500)}return We})},[W]),ve=x.useCallback(async(je,Me,_e)=>{if(!S){qt.track("chat_workflow_retry",{stepIndex:_e});try{k(je),T.current=je,await D(Me,_e)}finally{k(null)}}},[D,S]);x.useImperativeHandle(n,()=>({open:()=>{i(!0),t==null||t(!0)},close:()=>{i(!1),t==null||t(!1)},toggle:j,sendMessage:async je=>{i(!0),t==null||t(!0);const Me={id:`msg_${Date.now()}`,role:"user",parts:[{type:"text",text:je}]};await ae(Me)},sendWorkflowMessage:de,updateWorkflowMessage:oe,appendAgentLog:ee,updateThinkingContent:me,isOpen:()=>r,retryWorkflowFromStep:async(je,Me)=>{let _e=null;for(const[We,Se]of b.entries())if(Se.id===je.id){_e=We;break}_e?await ve(_e,je,Me):console.warn("[ChatDrawer] Could not find message ID for workflow retry",je.id)}}),[r,j,ae,de,oe,ee,me,t,b,ve]);const N=x.useMemo(()=>({...W,sendMessage:ae}),[W,ae]),he=s.find(je=>je.id===a),fe=(he==null?void 0:he.title)||"新对话",[ne,ie]=x.useState(!1),[ue,Te]=x.useState(""),De=x.useRef(null),ye=x.useCallback(()=>{Te(fe),ie(!0)},[fe]),Ne=x.useCallback(async()=>{const je=ue.trim();je&&je!==fe&&a&&await Z(a,je),ie(!1)},[ue,fe,a,Z]),Re=x.useCallback(()=>{Te(fe),ie(!1)},[fe]),He=x.useCallback(je=>{je.key==="Enter"?(je.preventDefault(),Ne()):je.key==="Escape"&&(je.preventDefault(),Re())},[Ne,Re]);x.useEffect(()=>{ne&&De.current&&(De.current.focus(),De.current.select())},[ne]);const et=x.useRef(null);B3(et,{enableCopy:!0,stopPropagation:!0});const[gt,Ye]=x.useState(!1);return x.useEffect(()=>{r&&Ye(!0)},[r]),y.jsxs(y.Fragment,{children:[y.jsx(Cne,{isOpen:r,onClick:j,drawerWidth:d}),y.jsxs("div",{className:`chat-drawer ${vi} ${r?"chat-drawer--open":""} ${h?"chat-drawer--dragging":""}`,style:{width:d},children:[y.jsx("div",{ref:g,className:"chat-drawer__resize-handle",onMouseDown:z}),y.jsxs("div",{ref:et,className:"chat-drawer__body",children:[y.jsxs("div",{className:"chat-drawer__header",children:[y.jsxs("div",{className:"chat-drawer__header-top",children:[ne?y.jsx("input",{ref:De,className:"chat-drawer__title-input",value:ue,onChange:je=>Te(je.target.value),onKeyDown:He,onBlur:Ne,maxLength:50}):y.jsx("h2",{className:"chat-drawer__title chat-drawer__title--editable",onClick:ye,title:"点击编辑标题",children:fe}),y.jsx(Di,{content:"关闭",theme:"light",children:y.jsx("button",{className:"chat-drawer__close-btn","data-track":"chat_click_drawer_close",onClick:H,"aria-label":"关闭对话",children:y.jsx(CS,{size:16})})})]}),y.jsxs("div",{className:"chat-drawer__header-bottom",children:[y.jsx(Ene,{value:w,onChange:C}),y.jsxs("div",{className:"chat-drawer__session-actions",children:[y.jsx(Di,{content:"会话列表",theme:"light",children:y.jsx("button",{ref:M,className:`chat-drawer__close-btn ${c?"chat-drawer__close-btn--active":""}`,"data-track":"chat_click_sessions_toggle",onClick:V,"aria-label":"会话列表",children:y.jsx(tne,{size:16})})}),y.jsx(Di,{content:"新对话",theme:"light",children:y.jsx("button",{className:"chat-drawer__close-btn","data-track":"chat_click_new_session",onClick:L,"aria-label":"新对话",children:y.jsx(dy,{size:16})})})]})]})]}),c&&y.jsx("div",{ref:F,children:y.jsx(bne,{sessions:s,activeSessionId:a,onSelectSession:Y,onNewSession:L,onDeleteSession:q,onRenameSession:Z})}),y.jsxs("div",{className:"chat-drawer__content",children:[gt&&y.jsx(x.Suspense,{fallback:y.jsx("div",{className:"chat-loading",children:y.jsx("div",{className:"chat-loading__spinner"})}),children:y.jsx(ZGe,{handler:N,workflowMessages:b,retryingWorkflowId:S,handleWorkflowRetry:ve})}),y.jsx(kne,{selectedContent:O,onSend:ae,placeholder:"输入消息... (可用 # 指定模型)"})]})]})]})]})});Mne.displayName="ChatDrawer";function Rne(){return`wf-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}function eVe(e,t=[]){const{generationType:n,modelId:r,isModelExplicit:i,prompt:s,userInstruction:o,rawInput:a,count:l,size:c,duration:u,selection:d}=e,f=[],h=Rne(),m=`wf_batch_${h}`;for(let g=0;g<l;g++){const w=`${h}-step-${g+1}`,C={mode:"queue",batchId:m,batchIndex:g+1,batchTotal:l,globalIndex:g+1};if(n==="image"){const b={prompt:s,model:r};c&&(b.size=c),t.length>0&&(b.referenceImages=t),f.push({id:w,mcp:"generate_image",args:b,options:C,description:l>1?`生成图片 (${g+1}/${l})`:"生成图片",status:"pending"})}else{const b={prompt:s,model:r,seconds:u||"5"};c&&(b.size=c),t.length>0&&(b.referenceImages=t),f.push({id:w,mcp:"generate_video",args:b,options:C,description:l>1?`生成视频 (${g+1}/${l})`:"生成视频",status:"pending"})}}return{id:h,name:n==="image"?"图片生成":"视频生成",description:`使用 ${r} 模型${l>1?`生成 ${l} 个`:"生成"}${n==="image"?"图片":"视频"}`,scenarioType:"direct_generation",generationType:n,steps:f,metadata:{prompt:s,userInstruction:o,rawInput:a,modelId:r,isModelExplicit:i,count:l,size:c,duration:u,referenceImages:t.length>0?t:void 0,selection:d},createdAt:Date.now()}}function tVe(e,t=[]){const{generationType:n,modelId:r,isModelExplicit:i,prompt:s,userInstruction:o,rawInput:a,count:l,size:c,duration:u,selection:d}=e,f=Rne(),h={userInstruction:o,rawInput:a,model:{id:r,type:n,isExplicit:i},params:{count:l,size:c,duration:u},selection:d,finalPrompt:s},m=[{id:`${f}-step-analyze`,mcp:"ai_analyze",args:{context:h,textModel:r},options:{mode:"async"},description:"AI 分析用户意图",status:"pending"}];return{id:f,name:"AI 智能生成",description:"AI 分析用户请求并执行相应操作",scenarioType:"agent_flow",generationType:n,steps:m,metadata:{prompt:s,userInstruction:o,rawInput:a,modelId:r,isModelExplicit:i,count:l,size:c,duration:u,referenceImages:t.length>0?t:void 0,selection:d},createdAt:Date.now()}}function Bne(e,t=[]){return e.scenario==="direct_generation"?eVe(e,t):tVe(e,t)}function nVe(e,t=0){try{const n=e3(e),r=n.match(/\{\s*"content"\s*:[\s\S]*?"next"\s*:[\s\S]*?\}/)||n.match(/\{[\s\S]*"content"[\s\S]*"next"[\s\S]*\}/);if(!r)return{content:"",steps:[]};const i=r[0],s=JSON.parse(i),o=typeof s.content=="string"?s.content:"";if(!Array.isArray(s.next)||s.next.length===0)return{content:o,steps:[]};const a=s.next.filter(l=>typeof l.mcp=="string"&&typeof l.args=="object").map((l,c)=>({id:`step-${t+c+1}`,mcp:l.mcp,args:l.args,description:rVe(l.mcp,l.args),status:"pending"}));return{content:o,steps:a}}catch{return{content:"",steps:[]}}}function rVe(e,t){var n,r;switch(e){case"generate_image":return`生成图片: ${((n=t.prompt)==null?void 0:n.substring(0,30))||""}...`;case"generate_video":return`生成视频: ${((r=t.prompt)==null?void 0:r.substring(0,30))||""}...`;case"ai_analyze":return"AI 分析用户意图";case"format_markdown":return"格式化输出";case"show_result":return"展示结果";default:return`执行 ${e}`}}function iVe(e,t,n,r,i,s){return{...e,steps:e.steps.map(o=>o.id===t?{...o,status:n,result:r,error:i,duration:s}:o)}}function sVe(e,t){const n=new Set(e.steps.map(i=>i.id)),r=t.filter(i=>!n.has(i.id));return r.length===0?e:{...e,steps:[...e.steps,...r]}}function vx(e){const t=e.steps.filter(o=>o.status==="completed").length,n=e.steps.filter(o=>o.status==="failed").length,r=e.steps.find(o=>o.status==="running"),i=e.steps.filter(o=>o.status==="pending").length;let s;return n>0?s="failed":r?s="running":i===0&&t>0?s="completed":s="pending",{status:s,completedSteps:t,totalSteps:e.steps.length,currentStep:r||e.steps.find(o=>o.status==="pending")}}const Zz={workflow:null,status:"idle",currentStep:null,completedSteps:0,totalSteps:0,error:null};function oVe(){const[e,t]=x.useState(Zz),n=x.useRef(null),r=x.useRef(!1),i=x.useCallback(f=>{n.current=f,r.current=!1;const h=vx(f);t({workflow:f,status:"running",currentStep:h.currentStep||null,completedSteps:h.completedSteps,totalSteps:h.totalSteps,error:null})},[]),s=x.useCallback(f=>{n.current=f,r.current=!1;const h=vx(f);let m="running";f.status==="completed"?m="completed":(f.status==="failed"||f.status==="cancelled")&&(m="failed"),t({workflow:f,status:m,currentStep:h.currentStep||null,completedSteps:h.completedSteps,totalSteps:h.totalSteps,error:f.error||null})},[]),o=x.useCallback((f,h,m,g,w)=>{if(r.current)return;const C=n.current;if(!C)return;const b=iVe(C,f,h,m,g,w);n.current=b,t(_=>{const T=vx(b);let S="running";return T.status==="completed"?S="completed":T.status==="failed"&&(S="failed"),{..._,workflow:b,status:S,currentStep:T.currentStep||null,completedSteps:T.completedSteps,totalSteps:T.totalSteps,error:g||_.error}})},[]),a=x.useCallback(f=>{if(r.current||f.length===0)return;const h=n.current;if(!h)return;const m=sVe(h,f);n.current=m,t(g=>{const w=vx(m);return{...g,workflow:m,currentStep:w.currentStep||g.currentStep,totalSteps:w.totalSteps}})},[]),l=x.useCallback(f=>{const h=n.current;if(!h||r.current)return{content:"",steps:[]};const m=h.steps.length,{content:g,steps:w}=nVe(f,m);return g&&!h.aiAnalysis&&(n.current={...h,aiAnalysis:g}),w.length>0&&a(w),{content:g,steps:w}},[a]),c=x.useCallback(()=>{n.current=null,r.current=!1,t(Zz)},[]),u=x.useCallback(()=>{r.current=!0,t(f=>({...f,status:"failed",error:"工作流已中止"}))},[]),d=x.useCallback(()=>n.current,[]);return{state:e,startWorkflow:i,restoreWorkflow:s,updateStep:o,addSteps:a,addStepsFromAIResponse:l,resetWorkflow:c,abortWorkflow:u,getWorkflow:d}}const Lne=x.createContext(null),aVe=({children:e})=>{const t=oVe(),n=x.useMemo(()=>({state:t.state,startWorkflow:t.startWorkflow,restoreWorkflow:t.restoreWorkflow,updateStep:t.updateStep,addSteps:t.addSteps,addStepsFromAIResponse:t.addStepsFromAIResponse,resetWorkflow:t.resetWorkflow,abortWorkflow:t.abortWorkflow,getWorkflow:t.getWorkflow}),[t.state,t.startWorkflow,t.restoreWorkflow,t.updateStep,t.addSteps,t.addStepsFromAIResponse,t.resetWorkflow,t.abortWorkflow,t.getWorkflow]);return y.jsx(Lne.Provider,{value:n,children:e})};function lVe(){const e=x.useContext(Lne);if(!e)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return e}function Nne(){const e=lVe();return{startWorkflow:e.startWorkflow,restoreWorkflow:e.restoreWorkflow,updateStep:e.updateStep,addSteps:e.addSteps,addStepsFromAIResponse:e.addStepsFromAIResponse,resetWorkflow:e.resetWorkflow,abortWorkflow:e.abortWorkflow,getWorkflow:e.getWorkflow}}const Ap={DEFAULT_BOARD_NAME:"未命名画板",DEFAULT_FOLDER_NAME:"新建文件夹",SIDEBAR_WIDTH:280,SIDEBAR_MIN_WIDTH:200,SIDEBAR_MAX_WIDTH:400},cVe="drawnix-images";function uVe(e){return typeof e=="string"&&e.startsWith("data:image/")&&e.includes(";base64,")}async function dVe(e){const t=e.match(/^data:(image\/[^;]+);base64,(.+)$/);if(!t)return e;const[,n,r]=t;try{const i=atob(r),s=new Uint8Array(i.length);for(let f=0;f<i.length;f++)s[f]=i.charCodeAt(f);const o=new Blob([s],{type:n}),a=`img-${Date.now()}-${Math.random().toString(36).substring(2,10)}`,l=n.split("/")[1]||"png",c=`/__aitu_cache__/image/${a}.${l}`,u=await caches.open(cVe),d=new Response(o,{status:200,headers:{"Content-Type":n,"Content-Length":o.size.toString(),"Cache-Control":"max-age=31536000"}});return await u.put(c,d),c}catch(i){return console.error("[Migration] Failed to cache Base64 image:",i),e}}async function ZA(e){let t=!1;for(const n of e){if(n.url&&uVe(n.url)){const r=Math.round(n.url.length/1024),i=await dVe(n.url);i!==n.url&&(n.url=i,t=!0,console.log(`[Migration] Element ${n.id}: Base64 (${r}KB) -> ${i}`))}n.children&&Array.isArray(n.children)&&await ZA(n.children)&&(t=!0)}return t}const ml={DATABASE_NAME:"aitu-workspace",MIN_DATABASE_VERSION:8,STORES:{FOLDERS:"folders",BOARDS:"boards",STATE:"state"}},Qz="workspace_state";function ok(e=50){return new Promise(t=>{typeof window<"u"&&"requestIdleCallback"in window?window.requestIdleCallback(()=>t(),{timeout:e}):setTimeout(t,0)})}async function fVe(e){return new Promise(t=>{if(typeof indexedDB>"u"){console.warn("[WorkspaceStorage] IndexedDB not available, using min version"),t(ml.MIN_DATABASE_VERSION);return}const n=indexedDB.open(e);n.onsuccess=()=>{const r=n.result,i=r.version;r.close();const s=Math.max(i,ml.MIN_DATABASE_VERSION);console.log(`[WorkspaceStorage] Detected DB version: ${i}, using: ${s}`),t(s)},n.onerror=r=>{console.error("[WorkspaceStorage] Error detecting DB version:",r),t(10)},n.onblocked=()=>{console.warn("[WorkspaceStorage] DB blocked, using safe version 10"),t(10)}})}class hVe{constructor(){this.foldersStore=null,this.boardsStore=null,this.stateStore=null,this.initialized=!1,this.initPromise=null}async createStores(){const t=await fVe(ml.DATABASE_NAME);this.foldersStore=pi.createInstance({driver:pi.INDEXEDDB,name:ml.DATABASE_NAME,version:t,storeName:ml.STORES.FOLDERS,description:"Workspace folders storage"}),this.boardsStore=pi.createInstance({driver:pi.INDEXEDDB,name:ml.DATABASE_NAME,version:t,storeName:ml.STORES.BOARDS,description:"Workspace boards storage"}),this.stateStore=pi.createInstance({driver:pi.INDEXEDDB,name:ml.DATABASE_NAME,version:t,storeName:ml.STORES.STATE,description:"Workspace state storage"})}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise}}async doInitialize(){try{await this.createStores(),await Promise.all([this.foldersStore.ready(),this.boardsStore.ready(),this.stateStore.ready()]),this.initialized=!0}catch(t){console.error("[WorkspaceStorage] Failed to initialize:",t);const n=String(t);if(n.includes("can't be downgraded")||n.includes("version")){console.warn("[WorkspaceStorage] Version conflict detected, attempting recovery...");try{await this.deleteDatabase(),await this.createStores(),await Promise.all([this.foldersStore.ready(),this.boardsStore.ready(),this.stateStore.ready()]),this.initialized=!0,console.log("[WorkspaceStorage] Recovery successful, database recreated");return}catch(r){console.error("[WorkspaceStorage] Recovery failed:",r)}}throw new Error("Workspace storage initialization failed")}}async deleteDatabase(){return new Promise((t,n)=>{if(typeof indexedDB>"u"){t();return}const r=indexedDB.deleteDatabase(ml.DATABASE_NAME);r.onsuccess=()=>{console.log("[WorkspaceStorage] Database deleted successfully"),t()},r.onerror=()=>{console.error("[WorkspaceStorage] Failed to delete database"),n(new Error("Failed to delete database"))},r.onblocked=()=>{console.warn("[WorkspaceStorage] Database deletion blocked"),setTimeout(t,1e3)}})}getFoldersStore(){if(!this.foldersStore)throw new Error("WorkspaceStorage not initialized");return this.foldersStore}getBoardsStore(){if(!this.boardsStore)throw new Error("WorkspaceStorage not initialized");return this.boardsStore}getStateStore(){if(!this.stateStore)throw new Error("WorkspaceStorage not initialized");return this.stateStore}async saveFolder(t){await this.ensureInitialized(),await this.getFoldersStore().setItem(t.id,t)}async loadFolder(t){return await this.ensureInitialized(),this.getFoldersStore().getItem(t)}async loadAllFolders(){await this.ensureInitialized();const t=[];return await this.getFoldersStore().iterate(n=>{n&&n.id&&t.push(n)}),await ok(),t.sort((n,r)=>n.order-r.order)}async deleteFolder(t){await this.ensureInitialized(),await this.getFoldersStore().removeItem(t)}async saveBoard(t){await this.ensureInitialized(),await this.getBoardsStore().setItem(t.id,t)}async loadBoard(t){await this.ensureInitialized();const n=await this.getBoardsStore().getItem(t);if(n&&n.elements){n.elements=cT(n.elements);try{await ZA(n.elements)&&(await this.saveBoard(n),console.log(`[Migration] Board ${t}: Base64 URLs migrated and saved`))}catch(r){console.error(`[Migration] Board ${t}: Failed to migrate`,r)}}return n}async loadAllBoards(){await this.ensureInitialized();const t=[];await this.getBoardsStore().iterate(n=>{n&&n.id&&(n.elements&&(n.elements=cT(n.elements)),t.push(n))}),await ok();for(const n of t)if(n.elements)try{await ZA(n.elements)&&(await this.saveBoard(n),console.log(`[Migration] Board ${n.id}: Base64 URLs migrated and saved`))}catch(r){console.error(`[Migration] Board ${n.id}: Failed to migrate`,r)}return t.sort((n,r)=>n.order-r.order)}async loadFolderBoards(t){await this.ensureInitialized();const n=[];return await this.getBoardsStore().iterate(r=>{r&&r.folderId===t&&(r.elements&&(r.elements=cT(r.elements)),n.push(r))}),await ok(),n.sort((r,i)=>r.order-i.order)}async deleteBoard(t){await this.ensureInitialized(),await this.getBoardsStore().removeItem(t)}async deleteFolderBoards(t){await this.ensureInitialized();const n=await this.loadFolderBoards(t);await Promise.all(n.map(r=>this.deleteBoard(r.id)))}async saveState(t){await this.ensureInitialized(),await this.getStateStore().setItem(Qz,t)}async loadState(){return await this.ensureInitialized(),await this.getStateStore().getItem(Qz)||{currentBoardId:null,expandedFolderIds:[],sidebarWidth:Ap.SIDEBAR_WIDTH,sidebarCollapsed:!1}}async getBoardCount(){return await this.ensureInitialized(),this.getBoardsStore().length()}async clearAll(){await this.ensureInitialized(),await Promise.all([this.getFoldersStore().clear(),this.getBoardsStore().clear(),this.getStateStore().clear()])}async ensureInitialized(){this.initialized||await this.initialize()}}const tr=new hVe;function Jz(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}class Yo{constructor(){this.folders=new Map,this.boards=new Map,this.events$=new Ks,this.initialized=!1,this.initializationPromise=null,this.state={currentBoardId:null,expandedFolderIds:[],sidebarWidth:Ap.SIDEBAR_WIDTH,sidebarCollapsed:!1}}static getInstance(){return Yo.instance||(Yo.instance=new Yo),Yo.instance}async initialize(){if(!this.initialized)return this.initializationPromise?this.initializationPromise:(this.initializationPromise=this.doInitialize(),this.initializationPromise)}async doInitialize(){try{await tr.initialize();const[t,n,r]=await Promise.all([tr.loadAllFolders(),tr.loadAllBoards(),tr.loadState()]);await new Promise(i=>{"requestIdleCallback"in window?window.requestIdleCallback(()=>i(),{timeout:50}):setTimeout(i,0)}),this.folders=new Map(t.map(i=>[i.id,i])),this.boards=new Map(n.map(i=>[i.id,i])),this.state=r,this.initialized=!0}catch(t){throw console.error("[WorkspaceService] Failed to initialize:",t),this.initializationPromise=null,t}}async waitForInitialization(){if(!this.initialized)return this.initializationPromise?this.initializationPromise:this.initialize()}async createFolder(t){await this.ensureInitialized();const n=this.getFolderChildren(t.parentId||null),r=n.length>0?Math.max(...n.map(s=>s.order))+1:0,i={id:Jz(),name:t.name||Ap.DEFAULT_FOLDER_NAME,parentId:t.parentId||null,order:r,isExpanded:!0,createdAt:Date.now(),updatedAt:Date.now()};return this.folders.set(i.id,i),await tr.saveFolder(i),this.emit("folderCreated",i),i}async renameFolder(t,n){const r=this.folders.get(t);if(!r)throw new Error(`Folder ${t} not found`);r.name=n,r.updatedAt=Date.now(),this.folders.set(t,r),await tr.saveFolder(r),this.emit("folderUpdated",r)}async deleteFolder(t){const n=this.folders.get(t);if(!n)throw new Error(`Folder ${t} not found`);const r=this.getFolderChildren(t);for(const s of r)await this.deleteFolder(s.id);const i=this.getBoardsInFolder(t);for(const s of i)s.folderId=null,await tr.saveBoard(s);this.folders.delete(t),await tr.deleteFolder(t),this.emit("folderDeleted",n)}async deleteFolderWithContents(t){const n=this.folders.get(t);if(!n)throw new Error(`Folder ${t} not found`);const r=this.getBoardsInFolder(t);for(const s of r)this.boards.delete(s.id),await tr.deleteBoard(s.id),this.emit("boardDeleted",s);const i=this.getFolderChildren(t);for(const s of i)await this.deleteFolderWithContents(s.id);this.folders.delete(t),await tr.deleteFolder(t),this.emit("folderDeleted",n)}toggleFolderExpanded(t){const n=this.folders.get(t);n&&(n.isExpanded=!n.isExpanded,this.folders.set(t,n),n.isExpanded?this.state.expandedFolderIds.includes(t)||this.state.expandedFolderIds.push(t):this.state.expandedFolderIds=this.state.expandedFolderIds.filter(r=>r!==t),this.saveState(),this.emit("treeChanged"))}async createBoard(t){await this.ensureInitialized();const n=Jz(),r=Date.now(),i=this.getBoardsInFolder(t.folderId||null),s=i.length>0?Math.max(...i.map(a=>a.order))+1:0,o={id:n,name:t.name||Ap.DEFAULT_BOARD_NAME,folderId:t.folderId||null,order:s,elements:t.elements||[],viewport:t.viewport,theme:t.theme,createdAt:r,updatedAt:r};return this.boards.set(n,o),await tr.saveBoard(o),this.emit("boardCreated",o),o}async renameBoard(t,n){const r=this.boards.get(t);if(!r)throw new Error(`Board ${t} not found`);r.name=n,r.updatedAt=Date.now(),this.boards.set(t,r),await tr.saveBoard(r),this.emit("boardUpdated",r)}async deleteBoard(t){const n=this.boards.get(t);if(!n)throw new Error(`Board ${t} not found`);this.state.currentBoardId===t&&(this.state.currentBoardId=null,this.saveState()),this.boards.delete(t),await tr.deleteBoard(t),this.emit("boardDeleted",n)}async moveBoard(t,n,r,i){const s=this.boards.get(t);if(!s)throw new Error(`Board ${t} not found`);s.folderId=n,s.updatedAt=Date.now();const o=this.getBoardsInFolder(n).filter(c=>c.id!==t);let l=[...this.getFolderChildren(n).map(c=>({id:c.id,type:"folder"})),...o.map(c=>({id:c.id,type:"board"}))].sort((c,u)=>{var h,m,g,w;const d=c.type==="board"?((h=this.boards.get(c.id))==null?void 0:h.order)??0:((m=this.folders.get(c.id))==null?void 0:m.order)??0,f=u.type==="board"?((g=this.boards.get(u.id))==null?void 0:g.order)??0:((w=this.folders.get(u.id))==null?void 0:w.order)??0;return d-f});if(r&&i){const c=l.findIndex(u=>u.id===r);if(c!==-1){const u=i==="before"?c:c+1;l.splice(u,0,{id:s.id,type:"board"})}else l.push({id:s.id,type:"board"})}else l.push({id:s.id,type:"board"});for(let c=0;c<l.length;c++){const u=l[c];if(u.type==="board"){const d=this.boards.get(u.id);d&&(d.order=c,this.boards.set(u.id,d),await tr.saveBoard(d))}else{const d=this.folders.get(u.id);d&&(d.order=c,this.folders.set(u.id,d),await tr.saveFolder(d))}}this.emit("boardUpdated",s),this.emit("treeChanged")}async moveFolder(t,n,r,i){const s=this.folders.get(t);if(!s)throw new Error(`Folder ${t} not found`);if(n){let c=this.folders.get(n);for(;c;){if(c.id===t)throw new Error("Cannot move folder into itself or its descendants");c=c.parentId?this.folders.get(c.parentId):void 0}}s.parentId=n,s.updatedAt=Date.now();const o=this.getFolderChildren(n).filter(c=>c.id!==t),a=this.getBoardsInFolder(n);let l=[...o.map(c=>({id:c.id,type:"folder"})),...a.map(c=>({id:c.id,type:"board"}))].sort((c,u)=>{var h,m,g,w;const d=c.type==="board"?((h=this.boards.get(c.id))==null?void 0:h.order)??0:((m=this.folders.get(c.id))==null?void 0:m.order)??0,f=u.type==="board"?((g=this.boards.get(u.id))==null?void 0:g.order)??0:((w=this.folders.get(u.id))==null?void 0:w.order)??0;return d-f});if(r&&i){const c=l.findIndex(u=>u.id===r);if(c!==-1){const u=i==="before"?c:c+1;l.splice(u,0,{id:s.id,type:"folder"})}else l.push({id:s.id,type:"folder"})}else l.push({id:s.id,type:"folder"});for(let c=0;c<l.length;c++){const u=l[c];if(u.type==="board"){const d=this.boards.get(u.id);d&&(d.order=c,this.boards.set(u.id,d),await tr.saveBoard(d))}else{const d=this.folders.get(u.id);d&&(d.order=c,this.folders.set(u.id,d),await tr.saveFolder(d))}}this.emit("folderUpdated",s),this.emit("treeChanged")}async reorderItems(t){const n=Date.now();for(const r of t)if(r.type==="board"){const i=this.boards.get(r.id);i&&(i.order=r.order,i.updatedAt=n,this.boards.set(r.id,i),await tr.saveBoard(i))}else{const i=this.folders.get(r.id);i&&(i.order=r.order,i.updatedAt=n,this.folders.set(r.id,i),await tr.saveFolder(i))}this.emit("treeChanged")}async copyBoard(t){const n=this.boards.get(t);if(!n)throw new Error(`Board ${t} not found`);let r=`${n.name} 副本`;const i=Array.from(this.boards.values()).filter(a=>a.folderId===n.folderId).map(a=>a.name);let s=1;for(;i.includes(r);)s++,r=`${n.name} 副本 ${s}`;return await this.createBoard({name:r,folderId:n.folderId,elements:JSON.parse(JSON.stringify(n.elements)),viewport:n.viewport?{...n.viewport}:void 0,theme:n.theme})}async deleteBoardsBatch(t){for(const n of t)await this.deleteBoard(n)}async moveBoardsBatch(t,n){for(const r of t)await this.moveBoard(r,n)}async switchBoard(t){await this.ensureInitialized();const n=this.boards.get(t);if(!n)throw new Error(`Board ${t} not found`);return this.state.currentBoardId&&this.state.currentBoardId,this.state.currentBoardId=t,this.saveState(),this.emit("boardSwitched",n),n}async saveBoard(t,n){const r=this.boards.get(t);if(!r)throw new Error(`Board ${t} not found`);r.elements=n.children,r.viewport=n.viewport,r.theme=n.theme,r.updatedAt=Date.now(),this.boards.set(t,r),await tr.saveBoard(r)}async saveCurrentBoard(t){const n=this.state.currentBoardId;if(!n){console.warn("[WorkspaceService] No current board to save");return}await this.saveBoard(n,t)}getFolder(t){return this.folders.get(t)}getBoard(t){return this.boards.get(t)}getCurrentBoard(){return this.state.currentBoardId&&this.boards.get(this.state.currentBoardId)||null}getState(){return{...this.state}}getFolderChildren(t){return Array.from(this.folders.values()).filter(n=>n.parentId===t).sort((n,r)=>n.order-r.order)}getBoardsInFolder(t){return Array.from(this.boards.values()).filter(n=>n.folderId===t).sort((n,r)=>n.order-r.order)}getTree(){const t=s=>{const o=this.getFolderChildren(s.id),a=this.getBoardsInFolder(s.id),l=[...o.map(t),...a.map(n)];return{type:"folder",data:s,children:l}},n=s=>({type:"board",data:s}),r=this.getFolderChildren(null),i=this.getBoardsInFolder(null);return[...r.map(t),...i.map(n)]}setSidebarWidth(t){this.state.sidebarWidth=Math.max(Ap.SIDEBAR_MIN_WIDTH,Math.min(Ap.SIDEBAR_MAX_WIDTH,t)),this.saveState()}setSidebarCollapsed(t){this.state.sidebarCollapsed=t,this.saveState()}async saveState(){await tr.saveState(this.state)}observeEvents(){return this.events$.asObservable()}emit(t,n){this.events$.next({type:t,payload:n,timestamp:Date.now()})}async ensureInitialized(){this.initialized||await this.initialize()}isInitialized(){return this.initialized}hasBoards(){return this.boards.size>0}async reload(){try{const[t,n,r]=await Promise.all([tr.loadAllFolders(),tr.loadAllBoards(),tr.loadState()]);this.folders=new Map(t.map(i=>[i.id,i])),this.boards=new Map(n.map(i=>[i.id,i])),this.state=r,this.emit("tree-changed")}catch(t){throw console.error("[WorkspaceService] Failed to reload:",t),t}}}const qn=Yo.getInstance();function pVe(){const[e,t]=x.useState(!0),[n,r]=x.useState(null),[i,s]=x.useState([]),[o,a]=x.useState(null),[l,c]=x.useState(qn.getState()),[u,d]=x.useState(0),f=x.useCallback(()=>{s(qn.getTree()),a(qn.getCurrentBoard()),c(qn.getState())},[]);x.useEffect(()=>{let G=!0;(async()=>{try{t(!0),await qn.initialize(),G&&(f(),r(null))}catch(j){G&&r(j instanceof Error?j.message:"Failed to initialize")}finally{G&&t(!1)}})();const K=qn.observeEvents().subscribe(()=>{G&&(f(),d(j=>j+1))});return()=>{G=!1,K.unsubscribe()}},[f]);const h=x.useMemo(()=>qn.hasBoards(),[u]),m=x.useCallback(async G=>{try{return r(null),await qn.createFolder(G)}catch(W){return r(W instanceof Error?W.message:"Failed to create folder"),null}},[]),g=x.useCallback(async(G,W)=>{try{return r(null),await qn.renameFolder(G,W),!0}catch(K){return r(K instanceof Error?K.message:"Failed to rename folder"),!1}},[]),w=x.useCallback(async G=>{try{return r(null),await qn.deleteFolder(G),!0}catch(W){return r(W instanceof Error?W.message:"Failed to delete folder"),!1}},[]),C=x.useCallback(async G=>{try{return r(null),await qn.deleteFolderWithContents(G),!0}catch(W){return r(W instanceof Error?W.message:"Failed to delete folder with contents"),!1}},[]),b=x.useCallback(async(G,W,K,j)=>{try{return r(null),await qn.moveFolder(G,W,K,j),!0}catch(H){return r(H instanceof Error?H.message:"Failed to move folder"),!1}},[]),_=x.useCallback(G=>{qn.toggleFolderExpanded(G)},[]),T=x.useCallback(async G=>{try{return r(null),await qn.createBoard(G)}catch(W){return r(W instanceof Error?W.message:"Failed to create board"),null}},[]),S=x.useCallback(async(G,W)=>{try{return r(null),await qn.renameBoard(G,W),!0}catch(K){return r(K instanceof Error?K.message:"Failed to rename board"),!1}},[]),k=x.useCallback(async G=>{try{return r(null),await qn.deleteBoard(G),!0}catch(W){return r(W instanceof Error?W.message:"Failed to delete board"),!1}},[]),D=x.useCallback(async(G,W,K,j)=>{try{return r(null),await qn.moveBoard(G,W,K,j),!0}catch(H){return r(H instanceof Error?H.message:"Failed to move board"),!1}},[]),O=x.useCallback(async G=>{try{return r(null),await qn.switchBoard(G)}catch(W){return r(W instanceof Error?W.message:"Failed to switch board"),null}},[]),I=x.useCallback(async G=>{const W=qn.getCurrentBoard();if(!W)return!1;try{return await qn.saveBoard(W.id,G),!0}catch(K){return console.error("[useWorkspace] Failed to save board:",K),!1}},[]),R=x.useCallback(async G=>{try{return r(null),await qn.copyBoard(G)}catch(W){return r(W instanceof Error?W.message:"Failed to copy board"),null}},[]),F=x.useCallback(async G=>{try{return r(null),await qn.deleteBoardsBatch(G),!0}catch(W){return r(W instanceof Error?W.message:"Failed to delete boards"),!1}},[]),M=x.useCallback(async(G,W)=>{try{return r(null),await qn.moveBoardsBatch(G,W),!0}catch(K){return r(K instanceof Error?K.message:"Failed to move boards"),!1}},[]),$=x.useCallback(async G=>{try{return r(null),await qn.reorderItems(G),!0}catch(W){return r(W instanceof Error?W.message:"Failed to reorder items"),!1}},[]),A=x.useCallback(G=>{qn.setSidebarWidth(G),c(qn.getState())},[]),z=x.useCallback(G=>{qn.setSidebarCollapsed(G),c(qn.getState())},[]);return{isLoading:e,error:n,tree:i,currentBoard:o,workspaceState:l,hasBoards:h,createFolder:m,renameFolder:g,deleteFolder:w,deleteFolderWithContents:C,moveFolder:b,toggleFolderExpanded:_,createBoard:T,renameBoard:S,deleteBoard:k,moveBoard:D,copyBoard:R,switchBoard:O,saveBoard:I,deleteBoardsBatch:F,moveBoardsBatch:M,reorderItems:$,setSidebarWidth:A,setSidebarCollapsed:z,refresh:f}}var zc=(e=>(e.AI_TOOLS="ai-tools",e.CONTENT_TOOLS="content-tools",e.UTILITIES="utilities",e.CUSTOM="custom",e))(zc||{});const jne=[{id:"banana-prompt",name:"香蕉提示词",description:"查看和复制优质 AI 提示词",icon:"🍌",category:zc.CONTENT_TOOLS,url:"https://www.aiwind.org",defaultWidth:800,defaultHeight:600,permissions:["allow-scripts","allow-same-origin","allow-popups","allow-forms","allow-top-navigation-by-user-activation"]},{id:"pose-library",name:"动作场景库",description:"专业人体姿态参考素材库,提供多角度动作姿势",icon:"🧘",category:zc.CONTENT_TOOLS,url:"https://www.posemaniacs.com/zh-Hans/poses",defaultWidth:900,defaultHeight:700,permissions:["allow-scripts","allow-same-origin","allow-popups","allow-forms","allow-top-navigation-by-user-activation"]},{id:"batch-image",name:"批量出图工具",description:"Excel式批量AI图片生成,支持批量编辑和快速生成",icon:"🎨",category:zc.AI_TOOLS,url:"/batch-image.html",defaultWidth:1200,defaultHeight:800,permissions:["allow-scripts","allow-same-origin","allow-forms","allow-modals"]}],qu={defaultWidth:600,defaultHeight:400},gqe={[zc.AI_TOOLS]:"AI 工具",[zc.CONTENT_TOOLS]:"内容工具",[zc.UTILITIES]:"实用工具",[zc.CUSTOM]:"自定义工具"},fs=class fs{constructor(){this.customTools=[],this.isInitialized=!1,this.initialize()}static getInstance(){return fs.instance||(fs.instance=new fs),fs.instance}getAvailableTools(){return[...jne,...this.customTools]}getToolById(t){return this.getAvailableTools().find(r=>r.id===t)||null}async initialize(){if(!this.isInitialized)try{const t=await pi.getItem(fs.STORAGE_KEY);t&&(this.isCompatibleVersion(t.version)?this.customTools=t.tools:(console.warn("[Toolbox] Incompatible version, resetting custom tools"),await this.resetCustomTools()))}catch(t){console.error("[Toolbox] Failed to load custom tools:",t)}finally{this.isInitialized=!0}}async saveCustomTools(){try{const t={version:fs.STORAGE_VERSION,tools:this.customTools,updatedAt:Date.now()};await pi.setItem(fs.STORAGE_KEY,t)}catch(t){throw console.error("[Toolbox] Failed to save custom tools:",t),t}}async addCustomTool(t){if(this.customTools.length>=fs.MAX_CUSTOM_TOOLS)throw new Error(`Maximum ${fs.MAX_CUSTOM_TOOLS} custom tools allowed`);if(this.validateToolDefinition(t),this.customTools.some(i=>i.id===t.id))throw new Error(`Tool with id "${t.id}" already exists`);const r={...t,id:t.id||`custom-${Date.now()}`,category:t.category||zc.CUSTOM,defaultWidth:t.defaultWidth||800,defaultHeight:t.defaultHeight||600,permissions:t.permissions||["allow-scripts","allow-same-origin","allow-popups","allow-forms","allow-top-navigation-by-user-activation"]};this.customTools.push(r),await this.saveCustomTools()}async removeCustomTool(t){const n=this.customTools.length;this.customTools=this.customTools.filter(i=>i.id!==t);const r=this.customTools.length<n;return r&&await this.saveCustomTools(),r}async updateCustomTool(t,n){const r=this.customTools.findIndex(s=>s.id===t);if(r===-1)return!1;const i={...this.customTools[r],...n,id:t};return this.validateToolDefinition(i),this.customTools[r]=i,await this.saveCustomTools(),!0}getToolsByCategory(){const t=this.getAvailableTools(),n={};return t.forEach(r=>{const i=r.category||"utilities";n[i]||(n[i]=[]),n[i].push(r)}),n}searchTools(t){if(!t.trim())return this.getAvailableTools();const n=t.toLowerCase().trim();return this.getAvailableTools().filter(r=>{var i;return r.name.toLowerCase().includes(n)||((i=r.description)==null?void 0:i.toLowerCase().includes(n))||r.id.toLowerCase().includes(n)})}getCustomTools(){return[...this.customTools]}async clearCustomTools(){this.customTools=[],await this.saveCustomTools()}validateToolDefinition(t){if(!t.name||!t.url)throw new Error("Tool name and URL are required");try{const n=new URL(t.url);if(!["https:","http:"].includes(n.protocol))throw new Error("Only HTTP/HTTPS URLs are allowed")}catch{throw new Error("Invalid URL format")}if(t.name.length>50)throw new Error("Tool name too long (max 50 characters)");if(t.description&&t.description.length>200)throw new Error("Tool description too long (max 200 characters)")}isCompatibleVersion(t){return t===fs.STORAGE_VERSION}async resetCustomTools(){this.customTools=[],await this.saveCustomTools()}};fs.STORAGE_KEY="aitu:custom-tools",fs.STORAGE_VERSION="1.0",fs.MAX_CUSTOM_TOOLS=50;let QA=fs;const yx=QA.getInstance();class gVe{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=yx.getToolById("banana-prompt");if(!n){console.error('❌ Tool "banana-prompt" not found');return}Pc.insertTool(t,n.id,n.url,[100,100],{width:n.defaultWidth||qu.defaultWidth,height:n.defaultHeight||qu.defaultHeight},{name:n.name,category:n.category,permissions:n.permissions})}insertXiaohongshuTool(){const t=this.getBoard();if(!t)return;const n=yx.getToolById("xiaohongshu-tool");if(!n){console.error('❌ Tool "xiaohongshu-tool" not found');return}Pc.insertTool(t,n.id,n.url,[300,300],{width:n.defaultWidth||qu.defaultWidth,height:n.defaultHeight||qu.defaultHeight},{name:n.name,category:n.category,permissions:n.permissions})}insertToolById(t,n=200,r=200){const i=this.getBoard();if(!i)return;const s=yx.getToolById(t);if(!s){console.error(`❌ Tool "${t}" not found`);return}Pc.insertTool(i,s.id,s.url,[n,r],{width:s.defaultWidth||qu.defaultWidth,height:s.defaultHeight||qu.defaultHeight},{name:s.name,category:s.category,permissions:s.permissions})}listAllTools(){yx.getAvailableTools().forEach((n,r)=>{})}getAllToolElements(){const t=this.getBoard();if(!t)return;Pc.getAllTools(t).forEach((r,i)=>{})}removeAllTools(){const t=this.getBoard();if(!t)return;Pc.getAllTools(t).forEach(r=>{Pc.removeTool(t,r.id)})}help(){}}const mVe=new gVe;typeof window<"u"&&(window.testToolbox=mVe);const vVe={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)"},yVe={autoHideDelay:3e3},wVe=({board:e,config:t,className:n,displayMode:r="auto",autoTriggerConfig:i})=>{const s=x.useRef(null),o=x.useRef(null);x.useRef(null);const a={...vVe,...t},l={...yVe,...i},[c,u]=x.useState(()=>({expanded:r==="always"?!0:a.defaultExpanded,dragging:!1,autoMode:r==="auto",manuallyExpanded:!1})),d=x.useRef({isDragging:!1,startPoint:null}),f=x.useRef(null),[h,m]=x.useState(null),g=x.useRef(null),[w,C]=x.useState(!1),b=120,_=x.useRef(0),T=x.useRef({zoom:e.viewport.zoom,offsetX:e.viewport.offsetX,offsetY:e.viewport.offsetY}),S=x.useRef(!1),k=x.useCallback(()=>{if(!e||!e.children)return[];const ve=[];return e.children.forEach(N=>{try{let he=null;N.points&&Array.isArray(N.points)?he=X.getRectangleByPoints(N.points):N.x!==void 0&&N.y!==void 0&&(he={x:N.x,y:N.y,width:N.width||100,height:N.height||100}),he&&he.width>0&&he.height>0&&ve.push({id:N.id,bounds:he,type:N.type})}catch(he){console.warn("Failed to get bounds for element:",N.id,he)}}),ve},[e]),D=x.useCallback(()=>{const N=Q.getBoardContainer(e).getBoundingClientRect(),he=e.viewport.zoom,fe=pu(e),ne=fe[0],ie=fe[1],ue=N.width/he,Te=N.height/he;return{x:ne,y:ie,width:ue,height:Te}},[e]),O=x.useRef(c.expanded);O.current=c.expanded;const I=x.useRef(null),R=x.useRef(1);x.useEffect(()=>{if(r==="always"){O.current||u(N=>({...N,expanded:!0}));return}if(r!=="auto")return;const ve=setInterval(()=>{const N=e.viewport,he=T.current,fe=Math.abs(N.zoom-he.zoom)>.001,ne=Math.abs(N.offsetX-he.offsetX)>.5||Math.abs(N.offsetY-he.offsetY)>.5;if(fe||ne){if(T.current={zoom:N.zoom,offsetX:N.offsetX,offsetY:N.offsetY},!S.current){S.current=!0;return}_.current=Date.now(),O.current||u(ue=>({...ue,expanded:!0,manuallyExpanded:!1}))}},100);return()=>{clearInterval(ve)}},[r,e]),x.useEffect(()=>{if(r!=="auto"||!c.expanded||c.manuallyExpanded||c.dragging)return;const ve=setTimeout(()=>{u(N=>!N.autoMode||N.manuallyExpanded||N.dragging?N:{...N,expanded:!1})},l.autoHideDelay);return()=>{clearTimeout(ve)}},[r,c.expanded,c.manuallyExpanded,c.dragging,l.autoHideDelay]);const F=x.useCallback((ve,N)=>{if(ve.length===0)return{x:N.x-200,y:N.y-200,width:N.width+400,height:N.height+400};let he=N.x,fe=N.y,ne=N.x+N.width,ie=N.y+N.height;ve.forEach(Te=>{const{x:De,y:ye,width:Ne,height:Re}=Te.bounds;he=Math.min(he,De),fe=Math.min(fe,ye),ne=Math.max(ne,De+Ne),ie=Math.max(ie,ye+Re)});const ue=100;return{x:he-ue,y:fe-ue,width:ne-he+ue*2,height:ie-fe+ue*2}},[]),M=x.useCallback(ve=>{const he=(a.width-20)/ve.width,fe=(a.height-20)/ve.height;return Math.min(he,fe)},[a.width,a.height]),$=x.useCallback((ve,N,he,fe)=>{const ie=(ve-he.x)*fe+10,ue=(N-he.y)*fe+10;return[ie,ue]},[]),A=x.useCallback((ve,N,he,fe)=>{const ie=(ve-10)/fe+he.x,ue=(N-10)/fe+he.y;return[ie,ue]},[]),z=x.useCallback((ve,N,he)=>{if(100*he<5)return;ve.strokeStyle="rgba(0, 0, 0, 0.05)",ve.lineWidth=.5;const ie=Math.floor(N.x/100)*100,ue=Math.floor(N.y/100)*100,Te=N.x+N.width,De=N.y+N.height;for(let ye=ie;ye<=Te;ye+=100){const[Ne]=$(ye,0,N,he);ve.beginPath(),ve.moveTo(Ne,0),ve.lineTo(Ne,a.height),ve.stroke()}for(let ye=ue;ye<=De;ye+=100){const[,Ne]=$(0,ye,N,he);ve.beginPath(),ve.moveTo(0,Ne),ve.lineTo(a.width,Ne),ve.stroke()}},[$,a.width,a.height]),G=x.useCallback(()=>{const ve=s.current;if(!ve)return;const N=ve.getContext("2d");if(!N)return;N.clearRect(0,0,a.width,a.height);const he=k(),fe=D();if(he.length===0&&!fe){N.fillStyle="#999",N.font="12px sans-serif",N.textAlign="center",N.textBaseline="middle",N.fillText("空画布",a.width/2,a.height/2);return}const ne=F(he,fe),ie=M(ne);I.current=ne,R.current=ie,z(N,ne,ie),N.fillStyle=a.elementColor,N.strokeStyle="rgba(0, 0, 0, 0.1)",N.lineWidth=.5,he.forEach(He=>{const{x:et,y:gt,width:Ye,height:je}=He.bounds,[Me,_e]=$(et,gt,ne,ie),We=Ye*ie,Se=je*ie;N.fillRect(Me,_e,We,Se),N.strokeRect(Me,_e,We,Se)});const[ue,Te]=$(fe.x,fe.y,ne,ie),De=fe.width*ie,ye=fe.height*ie;N.fillStyle=a.viewportColor,N.fillRect(ue,Te,De,ye),N.strokeStyle=a.viewportColor.replace("0.3","1"),N.lineWidth=2,N.strokeRect(ue,Te,De,ye);const Ne=8;N.fillStyle=a.viewportColor.replace("0.3","0.8"),N.fillRect(ue,Te,Ne,2),N.fillRect(ue,Te,2,Ne),N.fillRect(ue+De-Ne,Te,Ne,2),N.fillRect(ue+De-2,Te,2,Ne),N.fillRect(ue,Te+ye-2,Ne,2),N.fillRect(ue,Te+ye-Ne,2,Ne),N.fillRect(ue+De-Ne,Te+ye-2,Ne,2),N.fillRect(ue+De-2,Te+ye-Ne,2,Ne);const Re=g.current;if(Re){const He=Re.x-De/2,et=Re.y-ye/2;N.fillStyle="rgba(243, 156, 18, 0.15)",N.fillRect(He,et,De,ye),N.strokeStyle="rgba(243, 156, 18, 0.8)",N.lineWidth=2,N.strokeRect(He,et,De,ye)}},[e,a,k,D,F,M,$,z]),W=x.useCallback(ve=>{ve.preventDefault(),ve.stopPropagation();const N=s.current;if(!N||!I.current)return;const he=N.getBoundingClientRect(),fe=ve.clientX-he.left,ne=ve.clientY-he.top,[ie,ue]=A(fe,ne,I.current,R.current);d.current={isDragging:!0,startPoint:[fe,ne]},u(Te=>({...Te,dragging:!0})),K(ie,ue)},[A,e]),K=x.useCallback((ve,N)=>{const fe=Q.getBoardContainer(e).getBoundingClientRect(),ne=e.viewport.zoom,ie=ve-fe.width/(2*ne),ue=N-fe.height/(2*ne);$t.updateViewport(e,[ie,ue],ne),requestAnimationFrame(()=>G())},[e,G]),j=x.useCallback(ve=>{if(!d.current.isDragging||!I.current)return;ve.preventDefault(),ve.stopPropagation();const N=s.current;if(!N)return;const he=N.getBoundingClientRect(),fe=ve.clientX-he.left,ne=ve.clientY-he.top,[ie,ue]=A(fe,ne,I.current,R.current);K(ie,ue)},[A,K]),H=x.useCallback(()=>{d.current={isDragging:!1,startPoint:null},u(ve=>({...ve,dragging:!1}))},[]),L=x.useCallback((ve,N)=>{const he=f.current;if(!he||!I.current)return;const fe=he.getContext("2d");if(!fe)return;const[ne,ie]=A(ve,N,I.current,R.current),ue=D(),Te=ue.width,De=ue.height,ye=Te,Ne=De;fe.clearRect(0,0,b,b),fe.fillStyle="#fff",fe.fillRect(0,0,b,b);const Re=ne-ye/2,He=ie-Ne/2,et=b/ye,gt=b/Ne,Ye=Math.min(et,gt),je=(b-ye*Ye)/2,Me=(b-Ne*Ye)/2;k().forEach(We=>{const{bounds:Se}=We;if(Se.x+Se.width>=Re&&Se.x<=Re+ye&&Se.y+Se.height>=He&&Se.y<=He+Ne){const pe=(Se.x-Re)*Ye+je,Be=(Se.y-He)*Ye+Me,Pe=Se.width*Ye,Qe=Se.height*Ye;fe.fillStyle="rgba(0, 0, 0, 0.6)",fe.fillRect(pe,Be,Pe,Qe)}}),fe.strokeStyle="rgba(90, 79, 207, 0.6)",fe.lineWidth=1,fe.setLineDash([4,4]),fe.beginPath(),fe.moveTo(0,b/2),fe.lineTo(b,b/2),fe.stroke(),fe.beginPath(),fe.moveTo(b/2,0),fe.lineTo(b/2,b),fe.stroke(),fe.setLineDash([]),fe.strokeStyle="rgba(90, 79, 207, 0.3)",fe.lineWidth=2,fe.strokeRect(0,0,b,b)},[k,D,A]),V=x.useCallback(()=>{c.dragging||C(!0)},[c.dragging]),Y=x.useCallback(()=>{C(!1),m(null),g.current=null},[]),q=x.useCallback(ve=>{if(c.dragging){C(!1),g.current=null;return}const N=s.current;if(!N)return;const he=N.getBoundingClientRect(),fe=ve.clientX-he.left,ne=ve.clientY-he.top,ie={x:fe,y:ne};m(ie),g.current=ie,C(!0),L(fe,ne),G()},[c.dragging,L,G]),Z=x.useRef(!1),re=x.useCallback(ve=>{Z.current=!0;const N=s.current;if(!N)return;const he=ve.touches[0],fe=N.getBoundingClientRect(),ne=he.clientX-fe.left,ie=he.clientY-fe.top,ue={x:ne,y:ie};m(ue),g.current=ue,C(!0),L(ne,ie),G()},[L,G]),ae=x.useCallback(ve=>{const N=s.current;if(!N)return;const he=ve.touches[0],fe=N.getBoundingClientRect(),ne=he.clientX-fe.left,ie=he.clientY-fe.top,ue={x:ne,y:ie};m(ue),g.current=ue,C(!0),L(ne,ie),G()},[L,G]),de=x.useCallback(()=>{Z.current=!1,setTimeout(()=>{Z.current||(C(!1),m(null),g.current=null,G())},500)},[G]);x.useEffect(()=>{if(!c.expanded)return;G();const ve=setInterval(()=>{G()},100);return()=>{clearInterval(ve)}},[e,c.expanded,G]);const oe=x.useCallback(()=>{u(ve=>{const N=!ve.expanded;return{...ve,expanded:N,manuallyExpanded:N}})},[]),ee={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},ce=w&&(Z.current||!c.dragging),me=h?{position:"absolute",right:a.width+8,top:Math.max(0,Math.min(h.y-b/2,a.height-b)),width:b,height:b,opacity:ce?1:0,pointerEvents:"none",transition:"opacity 0.15s ease-out, top 0.1s ease-out"}:{display:"none"};return y.jsxs("div",{ref:o,className:`minimap ${c.expanded?"minimap--expanded":"minimap--collapsed"} ${r==="auto"?"minimap--auto":""} ${n||""}`,style:{...ee,zIndex:ma.MINIMAP},"data-track":"minimap_container",children:[c.expanded&&y.jsxs("div",{className:"minimap__content",children:[y.jsx("canvas",{ref:s,width:a.width,height:a.height,className:"minimap__canvas",onPointerDown:W,onPointerMove:j,onPointerUp:H,onPointerLeave:H,onMouseEnter:V,onMouseLeave:Y,onMouseMove:q,onTouchStart:re,onTouchMove:ae,onTouchEnd:de,style:{cursor:c.dragging?"grabbing":"pointer"}}),y.jsx("div",{className:"minimap__preview",style:me,children:y.jsx("canvas",{ref:f,width:b,height:b,className:"minimap__preview-canvas"})})]}),a.collapsible&&y.jsx("button",{className:`minimap__toggle ${c.expanded?"minimap__toggle--expanded":""}`,onClick:oe,title:c.expanded?"折叠小地图":"展开小地图","data-track":"minimap_click_toggle",children:y.jsx(bS,{})})]})},eH=10,xVe=3e3,bVe=({showMinimap:e=!0,container:t})=>{var O,I,R,F;const n=Hr(),{t:r}=jn(),{isDrawerOpen:i,drawerWidth:s}=j3(),[o,a]=x.useState(!1),[l,c]=x.useState(!0),[u,d]=x.useState(!1),f=x.useRef(null),h=x.useRef({zoom:((O=n==null?void 0:n.viewport)==null?void 0:O.zoom)||1,offsetX:((I=n==null?void 0:n.viewport)==null?void 0:I.offsetX)||0,offsetY:((R=n==null?void 0:n.viewport)==null?void 0:R.offsetY)||0}),m=x.useRef(!1),g=x.useRef(null),w=x.useMemo(()=>i?s+eH:eH,[i,s]),C=x.useCallback(()=>{$t.updateZoom(n,n.viewport.zoom-.1)},[n]),b=x.useCallback(()=>{$t.updateZoom(n,n.viewport.zoom+.1)},[n]),_=x.useCallback(()=>{$t.fitViewport(n),a(!1)},[n]),T=x.useCallback(()=>{$t.updateZoom(n,1),a(!1)},[n]),S=x.useCallback(()=>{c(M=>{const $=!M;return d($),$})},[]);x.useEffect(()=>{if(!l||!n)return;const M=Q.getBoardContainer(n);if(!M)return;const $=A=>{var G;const z=A.target;(G=f.current)!=null&&G.contains(z)||(c(!1),d(!1))};return M.addEventListener("mousedown",$),()=>{M.removeEventListener("mousedown",$)}},[l,n]),x.useEffect(()=>{if(!e||!n)return;const M=setInterval(()=>{const $=n.viewport,A=h.current,z=Math.abs($.zoom-A.zoom)>.001,G=Math.abs($.offsetX-A.offsetX)>.5||Math.abs($.offsetY-A.offsetY)>.5;if(z||G){if(h.current={zoom:$.zoom,offsetX:$.offsetX,offsetY:$.offsetY},!m.current){m.current=!0;return}l||(c(!0),d(!1)),g.current&&clearTimeout(g.current)}},100);return()=>{clearInterval(M)}},[e,n,l]),x.useEffect(()=>{if(!(!l||u))return g.current=setTimeout(()=>{c(!1)},xVe),()=>{g.current&&clearTimeout(g.current)}},[l,u]);const k=x.useCallback(()=>{a(M=>!M)},[]),D=Math.round((((F=n==null?void 0:n.viewport)==null?void 0:F.zoom)||1)*100);return y.jsxs("div",{className:"view-navigation",style:{right:w,zIndex:ma.VIEW_NAVIGATION},ref:f,children:[y.jsxs("div",{className:"view-navigation__zoom",children:[y.jsx("button",{className:"view-navigation__zoom-btn",onClick:C,title:r("zoom.out"),"aria-label":r("zoom.out"),"data-track":"view_nav_zoom_out",children:y.jsx(Kte,{})}),y.jsxs(ti,{sideOffset:8,open:o,onOpenChange:a,placement:"bottom",children:[y.jsx(ni,{asChild:!0,children:y.jsxs("button",{className:"view-navigation__zoom-percent",onClick:k,title:r("zoom.fit"),"aria-label":r("zoom.fit"),"data-track":"view_nav_zoom_menu",children:[D,"%"]})}),y.jsx(ri,{container:t,style:{zIndex:ma.POPOVER},children:y.jsxs("div",{className:"view-navigation-zoom-menu",children:[y.jsxs("button",{className:"zoom-menu-item",onClick:_,"data-track":"view_nav_zoom_fit",children:[y.jsx("span",{className:"zoom-menu-item__label",children:r("zoom.fit")}),y.jsx("span",{className:"zoom-menu-item__shortcut",children:"⌘⇧="})]}),y.jsxs("button",{className:"zoom-menu-item",onClick:T,"data-track":"view_nav_zoom_100",children:[y.jsx("span",{className:"zoom-menu-item__label",children:r("zoom.100")}),y.jsx("span",{className:"zoom-menu-item__shortcut",children:"⌘0"})]})]})})]}),y.jsx("button",{className:"view-navigation__zoom-btn",onClick:b,title:r("zoom.in"),"aria-label":r("zoom.in"),"data-track":"view_nav_zoom_in",children:y.jsx(dy,{})}),e&&y.jsx("button",{className:`view-navigation__minimap-toggle ${l?"view-navigation__minimap-toggle--expanded":""}`,onClick:S,title:l?"折叠小地图":"展开小地图","aria-label":l?"折叠小地图":"展开小地图","data-track":"view_nav_minimap_toggle",children:y.jsx(k3,{})})]}),e&&l&&y.jsx("div",{className:"view-navigation__minimap",children:y.jsx(wVe,{board:n,displayMode:"always",config:{width:180,height:120,position:"top-right",margin:0,collapsible:!1,defaultExpanded:!0}})})]})};function CVe(){return()=>{}}const EVe=({selectedModel:e,onSelect:t,language:n="zh"})=>{const[r,i]=x.useState(!1),s=x.useRef(null),o=x.useRef(null),a=bo(e),l=(a==null?void 0:a.shortCode)||"img";x.useEffect(()=>{if(!r)return;const d=f=>{s.current&&!s.current.contains(f.target)&&i(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[r]),x.useEffect(()=>{if(!r)return;const d=f=>{f.key==="Escape"&&i(!1)};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[r]);const c=x.useCallback(()=>{i(d=>!d)},[]),u=x.useCallback(d=>{t(d),i(!1)},[t]);return y.jsxs("div",{className:"model-dropdown",ref:s,children:[y.jsxs("button",{className:`model-dropdown__trigger ${r?"model-dropdown__trigger--open":""}`,onClick:c,type:"button","aria-haspopup":"listbox","aria-expanded":r,title:(a==null?void 0:a.shortLabel)||(a==null?void 0:a.label)||e,children:[y.jsx("span",{className:"model-dropdown__at",children:"@"}),y.jsx("span",{className:"model-dropdown__code",children:l})]}),r&&y.jsxs("div",{className:"model-dropdown__menu",ref:o,role:"listbox","aria-label":n==="zh"?"选择模型":"Select Model",children:[y.jsx("div",{className:"model-dropdown__header",children:n==="zh"?"选择图片模型":"Select Image Model"}),y.jsx("div",{className:"model-dropdown__list",children:Xl.map(d=>{const f=d.id===e;return y.jsxs("div",{className:`model-dropdown__item ${f?"model-dropdown__item--selected":""}`,onClick:()=>u(d.id),role:"option","aria-selected":f,children:[y.jsxs("div",{className:"model-dropdown__item-content",children:[y.jsxs("div",{className:"model-dropdown__item-name",children:[y.jsxs("span",{className:"model-dropdown__item-code",children:["@",d.shortCode]}),y.jsx("span",{className:"model-dropdown__item-label",children:d.shortLabel||d.label}),d.isVip&&y.jsx("span",{className:"model-dropdown__item-vip",children:"VIP"})]}),d.description&&y.jsx("div",{className:"model-dropdown__item-desc",children:d.description})]}),f&&y.jsx(rg,{size:16,className:"model-dropdown__item-check"})]},d.id)})})]})]})},SVe=({selectedSize:e,onSelect:t,modelId:n,language:r="zh"})=>{const[i,s]=x.useState(!1),o=x.useRef(null),a=x.useMemo(()=>jNe(n),[n]);x.useEffect(()=>{if(a.length===0)return;if(!a.some(f=>f.value===e)){const f=hee(n);t(f)}},[n,a,e,t]);const l=x.useMemo(()=>{const d=a.find(f=>f.value===e);return(d==null?void 0:d.label)||e},[a,e]);x.useEffect(()=>{if(!i)return;const d=f=>{o.current&&!o.current.contains(f.target)&&s(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[i]),x.useEffect(()=>{if(!i)return;const d=f=>{f.key==="Escape"&&s(!1)};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[i]);const c=x.useCallback(()=>{s(d=>!d)},[]),u=x.useCallback(d=>{t(d),s(!1)},[t]);return a.length===0?null:y.jsxs("div",{className:"size-dropdown",ref:o,children:[y.jsxs("button",{className:`size-dropdown__trigger ${i?"size-dropdown__trigger--open":""}`,onClick:c,type:"button","aria-haspopup":"listbox","aria-expanded":i,title:r==="zh"?"选择尺寸":"Select Size",children:[y.jsx("span",{className:"size-dropdown__label",children:l}),y.jsx(YJ,{size:14,className:"size-dropdown__icon"})]}),i&&y.jsxs("div",{className:"size-dropdown__menu",role:"listbox","aria-label":r==="zh"?"选择尺寸":"Select Size",children:[y.jsx("div",{className:"size-dropdown__header",children:r==="zh"?"选择尺寸":"Select Size"}),y.jsx("div",{className:"size-dropdown__list",children:a.map(d=>{const f=d.value===e;return y.jsxs("div",{className:`size-dropdown__item ${f?"size-dropdown__item--selected":""}`,onClick:()=>u(d.value),role:"option","aria-selected":f,children:[y.jsx("span",{className:"size-dropdown__item-label",children:d.label}),f&&y.jsx(rg,{size:14,className:"size-dropdown__item-check"})]},d.value)})})]})]})},_Ve=({content:e,pinned:t=!1,isPreset:n=!1,onClick:r,onTogglePin:i,onDelete:s,language:o="zh",disabled:a=!1})=>{const l=u=>{u.stopPropagation(),i==null||i()},c=u=>{u.stopPropagation(),s==null||s()};return y.jsxs("div",{className:`prompt-list-item ${t?"prompt-list-item--pinned":""} ${n?"prompt-list-item--preset":""} ${a?"prompt-list-item--disabled":""}`,onClick:a?void 0:r,title:e,children:[t&&y.jsx("div",{className:"prompt-list-item__pin-badge",children:y.jsx(k9,{size:10})}),n&&y.jsx("div",{className:"prompt-list-item__preset-badge",children:y.jsx(Fg,{size:10})}),y.jsx("span",{className:"prompt-list-item__text",children:e}),y.jsxs("div",{className:"prompt-list-item__actions",children:[i&&y.jsx("button",{type:"button",className:"prompt-list-item__action",onClick:l,title:t?o==="zh"?"取消置顶":"Unpin":o==="zh"?"置顶":"Pin",children:t?y.jsx(JLe,{size:14}):y.jsx(k9,{size:14})}),s&&y.jsx("button",{type:"button",className:"prompt-list-item__action prompt-list-item__action--delete",onClick:c,title:o==="zh"?"删除":"Delete",children:y.jsx(ig,{size:14})})]})]})},TVe=({title:e,items:t,onSelect:n,onTogglePin:r,onDelete:i,language:s="zh",disabled:o=!1,showCount:a=!0,className:l=""})=>y.jsxs("div",{className:`prompt-list-panel ${l}`,children:[y.jsxs("div",{className:"prompt-list-panel__header",children:[y.jsx("span",{className:"prompt-list-panel__title",children:e}),a&&y.jsx("span",{className:"prompt-list-panel__count",children:t.length})]}),y.jsx("div",{className:"prompt-list-panel__list",children:t.map(c=>y.jsx(_Ve,{content:c.content,pinned:c.pinned,isPreset:c.isPreset,onClick:()=>n==null?void 0:n(c.content),onTogglePin:r&&!c.isPreset?()=>r(c.id):void 0,onDelete:i&&!c.isPreset?()=>i(c.id):void 0,language:s,disabled:o},c.id))})]}),kVe=({onSelectPrompt:e,language:t})=>{const{history:n,removeHistory:r,togglePinHistory:i,refreshHistory:s}=pS({deduplicateWithPresets:!1}),[o,a]=x.useState(!1),l=x.useRef(null),c=x.useRef(null),u=x.useRef(null),d=x.useMemo(()=>(Jee[t]||[]).map((_,T)=>({id:`preset_${T}`,content:_.content,isPreset:!0})),[t]),f=x.useMemo(()=>{const b=n.map(S=>({id:S.id,content:S.content,pinned:S.pinned})),_=new Set(n.map(S=>S.content.trim().toLowerCase())),T=d.filter(S=>!_.has(S.content.trim().toLowerCase())).map(S=>({id:S.id,content:S.content,pinned:!1,isPreset:!0}));return[...b,...T]},[n,d]);x.useEffect(()=>()=>{c.current&&clearTimeout(c.current),u.current&&clearTimeout(u.current)},[]);const h=x.useCallback(()=>{u.current&&(clearTimeout(u.current),u.current=null),c.current=setTimeout(()=>{s(),a(!0)},150)},[s]),m=x.useCallback(()=>{c.current&&(clearTimeout(c.current),c.current=null),u.current=setTimeout(()=>{a(!1)},200)},[]),g=x.useCallback(b=>{e(b),a(!1)},[e]),w=x.useCallback(b=>{b.startsWith("preset_")||r(b)},[r]),C=x.useCallback(b=>{b.startsWith("preset_")||i(b)},[i]);return y.jsxs("div",{ref:l,className:"prompt-history-popover",onMouseEnter:h,onMouseLeave:m,children:[y.jsx("button",{className:"prompt-history-popover__trigger",title:t==="zh"?"提示词":"Prompts","data-track":"ai_input_click_history",children:y.jsx(OLe,{size:18})}),o&&y.jsx("div",{className:"prompt-history-popover__panel-wrapper",children:y.jsx(TVe,{title:t==="zh"?"提示词":"Prompts",items:f,onSelect:g,onTogglePin:C,onDelete:w,language:t,showCount:!0})})]})};let Dp=null;function tH(e){Dp=e}class Fne{async execute(t){const{operation:n,args:r}=t;switch(n){case"canvas_insert":return this.handleCanvasInsert(r);case"insert_mermaid":return this.handleMermaid(r);case"insert_mindmap":return this.handleMindmap(r);case"insert_svg":return this.handleSvg(r);case"generate_grid_image":return this.handleGridImage(r);case"generate_inspiration_board":return this.handleInspirationBoard(r);case"split_image":return this.handleSplitImage(r);case"generate_long_video":return this.handleLongVideo(r);case"ai_analyze":return this.handleAIAnalyze(r);case"generate_image":return this.handleGenerateImage(r);case"generate_video":return this.handleGenerateVideo(r);default:return{success:!1,error:`Unknown operation: ${n}`,type:"error"}}}findWorkZoneForMCP(t,n){var s;const r=$r.getAllWorkZones(t);if(r.length===0)return null;for(const o of r)if((s=o.workflow.steps)==null?void 0:s.some(l=>l.mcp===n))return o;return r.sort((o,a)=>(a.createdAt||0)-(o.createdAt||0))[0]||null}async handleCanvasInsert(t){const n=Dp;if(!n)return{success:!1,error:"画布未初始化",type:"error"};const{items:r,startPoint:i,verticalGap:s=50,horizontalGap:o=20}=t;if(!r||r.length===0)return{success:!1,error:"没有要插入的内容",type:"error"};try{let a=i||this.getInsertionPoint(n),l=0;for(const c of r){const{type:u,content:d}=c;switch(u){case"image":await wm(n,d,a,!1,{width:400,height:400},!1,!0),a=[a[0],a[1]+400+s],l++;break;case"video":await lh(n,d,a),a=[a[0],a[1]+300+s],l++;break;case"text":Yn.insertText(n,a,d),a=[a[0],a[1]+100+s],l++;break;case"svg":const h={url:this.svgToDataUrl(d),width:400,height:400};Yn.insertImage(n,h,a),a=[a[0],a[1]+400+s],l++;break}}return{success:!0,data:{insertedCount:l},type:"canvas"}}catch(a){return{success:!1,error:a.message||"插入失败",type:"error"}}}async handleMermaid(t){const n=Dp;if(!n)return{success:!1,error:"画布未初始化",type:"error"};const{mermaid:r}=t;if(!r)return{success:!1,error:"缺少 mermaid 参数",type:"error"};try{const{parseMermaidToDrawnix:i}=await ln(async()=>{const{parseMermaidToDrawnix:d}=await import("./index-QG8-KVAs.js").then(f=>f.O);return{parseMermaidToDrawnix:d}},__vite__mapDeps([0,1,2]),import.meta.url),s=this.extractCodeBlock(r,"mermaid");let o;try{o=await i(s)}catch{o=await i(s.replace(/"/g,"'"))}const{elements:a}=o;if(!a||a.length===0)return{success:!1,error:"Mermaid 解析未生成元素",type:"error"};const l=this.findWorkZoneForMCP(n,"insert_mermaid"),c=this.getViewportCenter(n),u=this.insertElementsToCanvasAtPoint(n,a,c);return u.success&&(requestAnimationFrame(()=>{this.centerInsertedElementsInViewport(n,a.length)}),l&&setTimeout(()=>{$r.removeWorkZone(n,l.id),window.dispatchEvent(new CustomEvent("ai-generation-complete",{detail:{type:"mermaid",success:!0}}))},100)),{success:u.success,data:{elementsCount:u.elementsCount},type:"canvas",error:u.error}}catch(i){return console.error("[SWCapabilities] Mermaid conversion failed:",i),{success:!1,error:`Mermaid 转换失败: ${i.message}`,type:"error"}}}async handleMindmap(t){const n=Dp;if(!n)return{success:!1,error:"画布未初始化",type:"error"};const{markdown:r}=t;if(!r)return{success:!1,error:"缺少 markdown 参数",type:"error"};try{const{parseMarkdownToDrawnix:i}=await ln(async()=>{const{parseMarkdownToDrawnix:u}=await import("./index-D1NStEds.js");return{parseMarkdownToDrawnix:u}},__vite__mapDeps([3,4,5]),import.meta.url),s=this.extractCodeBlock(r,"markdown");let o;try{o=await i(s)}catch{o=await i(s.replace(/"/g,"'"))}if(!o)return{success:!1,error:"Markdown 解析未生成元素",type:"error"};o.points=[[0,0]];const a=this.findWorkZoneForMCP(n,"insert_mindmap"),l=this.getViewportCenter(n),c=this.insertElementsToCanvasAtPoint(n,[o],l);return c.success&&(requestAnimationFrame(()=>{this.centerInsertedElementsInViewport(n,1)}),a&&setTimeout(()=>{$r.removeWorkZone(n,a.id),window.dispatchEvent(new CustomEvent("ai-generation-complete",{detail:{type:"mindmap",success:!0}}))},100)),{success:c.success,data:{type:"mindmap",elementsCount:c.elementsCount},type:"canvas",error:c.error}}catch(i){return console.error("[SWCapabilities] Mindmap conversion failed:",i),{success:!1,error:`思维导图转换失败: ${i.message}`,type:"error"}}}async handleSvg(t){const n=Dp;if(!n)return{success:!1,error:"画布未初始化",type:"error"};const{svg:r,width:i=400,startPoint:s}=t;if(!r)return{success:!1,error:"缺少 svg 参数",type:"error"};try{const o=this.extractSvgCode(r),a=this.normalizeSvg(o),l=this.parseSvgDimensions(a),c=Math.min(Math.max(i,100),800),u=l.height/l.width,d=c*u,f=this.svgToDataUrl(a);let h=s||this.getInsertionPoint(n);h=[h[0]-c/2,h[1]];const m={url:f,width:c,height:d};Yn.insertImage(n,m,h);const g=[h[0]+c/2,h[1]+d/2];return requestAnimationFrame(()=>{So(n,g)}),{success:!0,data:{width:c,height:d},type:"canvas"}}catch(o){return{success:!1,error:`SVG 插入失败: ${o.message}`,type:"error"}}}async handleGridImage(t){try{const{createGridImageTask:n}=await ln(async()=>{const{createGridImageTask:i}=await import("./grid-image-jIEBt3FV.js");return{createGridImageTask:i}},[],import.meta.url),r=await n(t);return{success:r.success,data:r.data,type:r.type,taskId:r.taskId,error:r.error}}catch(n){return{success:!1,error:`宫格图生成失败: ${n.message}`,type:"error"}}}async handleInspirationBoard(t){try{const{createInspirationBoardTask:n}=await ln(async()=>{const{createInspirationBoardTask:i}=await import("./inspiration-board-CXBpTN2S.js");return{createInspirationBoardTask:i}},[],import.meta.url),r=await n(t);return{success:r.success,data:r.data,type:r.type,taskId:r.taskId,error:r.error}}catch(n){return{success:!1,error:`灵感图生成失败: ${n.message}`,type:"error"}}}async handleSplitImage(t){const n=Dp;if(!n)return{success:!1,error:"画布未初始化",type:"error"};const{imageUrl:r}=t;if(!r)return{success:!1,error:"缺少 imageUrl 参数",type:"error"};try{const{splitAndInsertImages:i}=await ln(async()=>{const{splitAndInsertImages:o}=await Promise.resolve().then(()=>gje);return{splitAndInsertImages:o}},void 0,import.meta.url),s=await i(n,r,{scrollToResult:!0});return{success:s.success,data:{count:s.count},type:"canvas",error:s.error}}catch(i){return{success:!1,error:`图片拆分失败: ${i.message}`,type:"error"}}}async handleLongVideo(t){try{const{createLongVideoTask:n}=await ln(async()=>{const{createLongVideoTask:i}=await Promise.resolve().then(()=>UWe);return{createLongVideoTask:i}},void 0,import.meta.url),r=await n(t);return{success:r.success,data:r.data,type:r.type,taskId:r.taskId,error:r.error}}catch(n){return{success:!1,error:`长视频生成失败: ${n.message}`,type:"error"}}}async handleAIAnalyze(t){var n;try{const{analyzeWithAI:r}=await ln(async()=>{const{analyzeWithAI:s}=await import("./ai-analyze-DSNdzApa.js");return{analyzeWithAI:s}},[],import.meta.url),i=await r(t.context,{onChunk:s=>{},onAddSteps:s=>{}});return{success:i.success,data:{response:i.response},type:"text",addSteps:(n=i.generatedSteps)==null?void 0:n.map(s=>({id:s.id,mcp:s.mcp,args:s.args,description:s.description,status:s.status})),error:i.error}}catch(r){return{success:!1,error:`AI 分析失败: ${r.message}`,type:"error"}}}async handleGenerateImage(t){var n;try{const{createImageTask:r}=await ln(async()=>{const{createImageTask:s}=await Promise.resolve().then(()=>p7e);return{createImageTask:s}},void 0,import.meta.url),i=await r(t);return i.success?{success:!0,data:i.data,type:"image",taskId:i.taskId,taskIds:(n=i.data)==null?void 0:n.taskIds}:(console.error("[SWCapabilities] Image task creation failed:",i.error),{success:!1,error:i.error||"图片生成任务创建失败",type:"error"})}catch(r){return console.error("[SWCapabilities] Image generation error:",r),{success:!1,error:`图片生成失败: ${r.message}`,type:"error"}}}async handleGenerateVideo(t){var n;try{const{createVideoTask:r}=await ln(async()=>{const{createVideoTask:s}=await Promise.resolve().then(()=>b7e);return{createVideoTask:s}},void 0,import.meta.url),i=await r(t);return i.success?{success:!0,data:i.data,type:"video",taskId:i.taskId,taskIds:(n=i.data)==null?void 0:n.taskIds}:(console.error("[SWCapabilities] Video task creation failed:",i.error),{success:!1,error:i.error||"视频生成任务创建失败",type:"error"})}catch(r){return console.error("[SWCapabilities] Video generation error:",r),{success:!1,error:`视频生成失败: ${r.message}`,type:"error"}}}getInsertionPoint(t){const n=t.appState,r=(n==null?void 0:n.lastSelectedElementIds)||[];if(r.length>0){const i=r.map(s=>t.children.find(o=>o.id===s)).filter(Boolean);if(i.length>0)try{const s=Et(t,i,!1);return[s.x+s.width/2,s.y+s.height+50]}catch{}}if(t.children&&t.children.length>0){let i=0,s=100;for(const o of t.children)try{const a=Et(t,[o],!1),l=a.y+a.height;l>i&&(i=l,s=a.x+a.width/2)}catch{}return[s,i+50]}return[100,100]}insertElementsToCanvas(t,n){try{const r=this.getInsertionPoint(t);return t.insertFragment({elements:JSON.parse(JSON.stringify(n))},r,na.paste),requestAnimationFrame(()=>{So(t,r)}),{success:!0,elementsCount:n.length}}catch(r){return{success:!1,error:r.message}}}insertElementsToCanvasAtPoint(t,n,r){try{return t.insertFragment({elements:JSON.parse(JSON.stringify(n))},r,na.paste),requestAnimationFrame(()=>{So(t,r)}),{success:!0,elementsCount:n.length}}catch(i){return console.error("[SWCapabilities] insertElementsToCanvasAtPoint failed:",i),{success:!1,error:i.message}}}getViewportCenter(t){try{const r=Q.getBoardContainer(t).getBoundingClientRect(),i=t.viewport.zoom,s=pu(t);if(!s)return[0,0];const o=s[0]+r.width/(2*i),a=s[1]+r.height/(2*i);return[o,a]}catch(n){return console.warn("[SWCapabilities] Error getting viewport center:",n),[0,0]}}centerInsertedElementsInViewport(t,n){try{const i=t.children.slice(-n);if(i.length===0){console.warn("[SWCapabilities] No inserted elements found to center");return}const s=Et(t,i,!1),a=Q.getBoardContainer(t).getBoundingClientRect(),l=80,c=a.width-l*2,u=a.height-l*2,d=c/s.width,f=u/s.height;let h=Math.min(d,f);h=Math.min(Math.max(h,.2),1.5);const m=s.x+s.width/2,g=s.y+s.height/2,w=m-a.width/(2*h),C=g-a.height/(2*h);$t.updateViewport(t,[w,C],h)}catch(r){console.warn("[SWCapabilities] Error centering inserted elements:",r)}}extractCodeBlock(t,n){const r=new RegExp(`\`\`\`${n}\\s*\\n([\\s\\S]*?)\\n\\s*\`\`\``,"i"),i=t.match(r);if(i)return i[1].trim();const s=new RegExp(`\`\`\`${n}\\s*([\\s\\S]*?)\\s*\`\`\``,"i"),o=t.match(s);if(o)return o[1].trim();const a=new RegExp(`^${n}\\s*\\n`,"i");return a.test(t.trim())?t.trim().replace(a,"").trim():t.trim()}extractSvgCode(t){let n=this.extractCodeBlock(t,"svg");if(n===t&&(n=this.extractCodeBlock(t,"xml")),n===t&&!n.trim().startsWith("<svg")){const r=n.match(/<svg[\s\S]*?<\/svg>/i);r&&(n=r[0])}return n.trim()}normalizeSvg(t){let n=t.trim();return n.includes("xmlns=")||(n=n.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),n}parseSvgDimensions(t){const n=t.match(/viewBox=["']([^"']+)["']/i);if(n){const[,,s,o]=n[1].split(/\s+/).map(Number);if(s&&o)return{width:s,height:o}}const r=t.match(/width=["'](\d+)(?:px)?["']/i),i=t.match(/height=["'](\d+)(?:px)?["']/i);return r&&i?{width:parseInt(r[1]),height:parseInt(i[1])}:{width:400,height:400}}svgToDataUrl(t){return`data:image/svg+xml,${encodeURIComponent(t).replace(/'/g,"%27").replace(/"/g,"%22")}`}}const PVe=new Fne;async function AVe(e,t={}){const{timestamp:n="last",format:r="image/png",quality:i=.92,timeout:s=3e4}=t;return new Promise((o,a)=>{const l=document.createElement("video"),c=document.createElement("canvas"),u=c.getContext("2d");if(!u){a(new Error("Failed to get canvas context"));return}let d=null,f=!1;const h=()=>{d!==null&&(clearTimeout(d),d=null),l.removeEventListener("loadedmetadata",g),l.removeEventListener("seeked",w),l.removeEventListener("error",C),l.src="",l.load()},m=()=>{if(!f){f=!0;try{c.width=l.videoWidth,c.height=l.videoHeight,u.drawImage(l,0,0,c.width,c.height);const b=c.toDataURL(r,i);h(),o({dataUrl:b,timestamp:l.currentTime,width:l.videoWidth,height:l.videoHeight})}catch(b){h(),a(new Error(`Failed to extract frame: ${b}`))}}},g=()=>{const b=l.duration;let _;n==="last"?_=Math.max(0,b-.1):n==="first"?_=.1:_=Math.min(Math.max(0,n),b),l.currentTime=_},w=()=>{m()},C=()=>{var b;h(),a(new Error(`Failed to load video: ${((b=l.error)==null?void 0:b.message)||"Unknown error"}`))};d=window.setTimeout(()=>{f||(h(),a(new Error(`Video frame extraction timed out after ${s}ms`)))},s),l.addEventListener("loadedmetadata",g),l.addEventListener("seeked",w),l.addEventListener("error",C),l.crossOrigin="anonymous",l.muted=!0,l.playsInline=!0,l.preload="auto",l.src=e})}async function DVe(e){return AVe(e,{timestamp:"last"})}function IVe(e){var t;return!!((t=e.params)!=null&&t.longVideoMeta)}function OVe(e){var t;return((t=e.params)==null?void 0:t.longVideoMeta)||null}class Wp{constructor(){this.isInitialized=!1,this.batches=new Map,this.initTimestamp=0}static getInstance(){return Wp.instance||(Wp.instance=new Wp),Wp.instance}initialize(){this.isInitialized||(this.isInitialized=!0,this.initTimestamp=Date.now(),bn.observeTaskUpdates().subscribe(t=>{if(t.type==="taskUpdated"&&t.task.status===ht.COMPLETED&&t.task.type===Ft.VIDEO&&IVe(t.task)){if((t.task.completedAt||0)<this.initTimestamp)return;this.handleSegmentCompleted(t.task).catch(r=>{console.error("[LongVideoChain] Error handling completed segment:",r)})}}))}async handleSegmentCompleted(t){var c;const n=OVe(t);if(!n)return;const{segmentIndex:r,totalSegments:i,scripts:s,batchId:o}=n,a=(c=t.result)==null?void 0:c.url;let l=this.batches.get(o);if(l||(l={batchId:o,totalSegments:i,completedSegments:new Map,processedSegments:new Set,creatingNextFor:null,isMerging:!1,mergeCompleted:!1},this.batches.set(o,l)),!l.processedSegments.has(r)){if(l.processedSegments.add(r),a&&l.completedSegments.set(r,a),l.completedSegments.size===i){await this.mergeAndInsert(l);return}if(l.creatingNextFor!==r&&r<i){l.creatingNextFor=r;try{await this.createNextSegment(t,n,s,a)}finally{l.creatingNextFor=null}}}}async createNextSegment(t,n,r,i){const s=n.segmentIndex+1,o=r.find(c=>c.index===s);if(!o){console.error(`[LongVideoChain] Script not found for segment ${s}`);return}let a;if(i)try{a=(await DVe(i)).dataUrl}catch(c){console.error("[LongVideoChain] Failed to extract last frame:",c)}const l={...n,segmentIndex:s,needsLastFrame:s<n.totalSegments};O3(o,l,a)}async mergeAndInsert(t){if(!(t.isMerging||t.mergeCompleted)){t.isMerging=!0;try{const n=[];for(let s=1;s<=t.totalSegments;s++){const o=t.completedSegments.get(s);o&&n.push(o)}if(n.length===0){console.error("[LongVideoChain] No video URLs to merge");return}const i=await dte(n,(s,o,a)=>{const l=a||`${o} ${s.toFixed(1)}%`});await this.insertMergedVideo(i.url),t.mergeCompleted=!0,this.cleanupBatch(t.batchId)}catch(n){console.error("[LongVideoChain] Merge failed:",n),this.cleanupBatch(t.batchId)}finally{t.isMerging=!1}}}async insertMergedVideo(t){try{await qA("video",t)}catch(n){console.error("[LongVideoChain] Failed to insert video to canvas:",n)}}cleanupBatch(t){const n=this.batches.get(t);n&&(n.completedSegments.clear(),n.processedSegments.clear(),this.batches.delete(t))}getBatchStatus(t){const n=this.batches.get(t);return n?{completed:n.completedSegments.size,total:n.totalSegments,isMerging:n.isMerging,mergeCompleted:n.mergeCompleted}:null}}const MVe=Wp.getInstance();function RVe(){MVe.initialize()}function nH(){return`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}async function rH(e){return new Promise((t,n)=>{const r=new Image,i=e.startsWith("http")&&!e.startsWith(location.origin);r.crossOrigin="anonymous",r.onload=()=>t(r),r.onerror=()=>{n(i?new Error("无法加载外部图片,可能是跨域 (CORS) 限制。请先下载图片到本地后再操作。"):new Error("图片加载失败,请检查图片是否有效"))},r.src=e})}function BVe(e,t=.92){return e.toDataURL("image/jpeg",t)}class LVe{async split(t,n){const{rows:r,cols:i}=n;if(r<1||i<1)throw new Error("Grid rows and cols must be at least 1");const s=await rH(t),o=s.naturalWidth,a=s.naturalHeight,l=Math.floor(o/i),c=Math.floor(a/r),u=[];for(let d=0;d<r;d++)for(let f=0;f<i;f++){const h=d*i+f,m=f*l,g=d*c,w=document.createElement("canvas");w.width=l,w.height=c;const C=w.getContext("2d");if(!C)throw new Error("Failed to get canvas 2d context");C.drawImage(s,m,g,l,c,0,0,l,c);const b=BVe(w);u.push({id:nH(),imageData:b,originalIndex:h,width:l,height:c})}return u}async splitToBlob(t,n){const{rows:r,cols:i}=n;if(r<1||i<1)throw new Error("Grid rows and cols must be at least 1");const s=await rH(t),o=s.naturalWidth,a=s.naturalHeight,l=Math.floor(o/i),c=Math.floor(a/r),u=[];for(let d=0;d<r;d++)for(let f=0;f<i;f++){const h=d*i+f,m=f*l,g=d*c,w=document.createElement("canvas");w.width=l,w.height=c;const C=w.getContext("2d");if(!C)throw new Error("Failed to get canvas 2d context");C.drawImage(s,m,g,l,c,0,0,l,c);const b=await new Promise((T,S)=>{w.toBlob(k=>{k?T(k):S(new Error("Failed to create blob"))},"image/png",.92)}),_=URL.createObjectURL(b);u.push({id:nH(),imageData:_,originalIndex:h,width:l,height:c})}return u}revokeBlobUrls(t){for(const n of t)n.imageData.startsWith("blob:")&&URL.revokeObjectURL(n.imageData)}}const iH=new LVe;function Go(e,t){return Math.random()*(t-e)+e}function wx(e){const t=[...e];for(let n=t.length-1;n>0;n--){const r=Math.floor(Math.random()*(n+1));[t[n],t[r]]=[t[r],t[n]]}return t}class NVe{calculate(t,n,r,i){switch(n){case"scattered":return this.scatteredLayout(t,r,i);case"grid":return this.gridLayout(t,r);case"circular":return this.circularLayout(t,r,i);case"inspiration-board":return this.inspirationBoardLayout(t,r,i);default:return console.warn(`[LayoutEngine] Unknown layout style: ${n}, falling back to grid`),this.gridLayout(t,r)}}scatteredLayout(t,n,r){const{maxRotation:i=15,minScale:s=.85,maxScale:o=1.15,positionJitter:a=40}=r||{},{canvasWidth:l,canvasHeight:c,startX:u,startY:d,gap:f=20}=n,h=t.length,m=Math.ceil(Math.sqrt(h)),g=Math.ceil(h/m),w=Math.max(...t.map(O=>O.width)),C=Math.max(...t.map(O=>O.height)),b=l-f*2,_=c-f*2,T=b/m,S=_/g,k=Math.min((T-f)/w,(S-f)/C,1),D=wx(t.map((O,I)=>I));return t.map((O,I)=>{const R=Math.floor(I/m),F=I%m,M=u+f+F*T+T/2,$=d+f+R*S+S/2,A=Go(-a,a),z=Go(-a,a),G=Go(-i,i),W=Go(s,o),K=k*W,j=O.width*K,H=O.height*K;return{...O,x:M+A-j/2,y:$+z-H/2,rotation:G,scale:K,zIndex:D[I]}})}gridLayout(t,n){const{canvasWidth:r,canvasHeight:i,startX:s,startY:o,gap:a=20}=n,l=t.length,c=Math.ceil(Math.sqrt(l)),u=Math.ceil(l/c),d=Math.max(...t.map(b=>b.width)),f=Math.max(...t.map(b=>b.height)),h=r-a*(c+1),m=i-a*(u+1),g=h/c,w=m/u,C=Math.min(g/d,w/f,1);return t.map((b,_)=>{const T=Math.floor(_/c),S=_%c,k=b.width*C,D=b.height*C,O=s+a+S*(g+a),I=o+a+T*(w+a),R=O+(g-k)/2,F=I+(w-D)/2;return{...b,x:R,y:F,rotation:0,scale:C,zIndex:_}})}circularLayout(t,n,r){const{centerIndex:i=-1,radius:s,startAngle:o=-90}=r||{},{canvasWidth:a,canvasHeight:l,startX:c,startY:u}=n,d=c+a/2,f=u+l/2,h=i>=0&&i<t.length?t.filter((F,M)=>M!==i):t,m=i>=0&&i<t.length?t[i]:null,g=Math.max(...t.map(F=>F.width)),w=Math.max(...t.map(F=>F.height)),C=Math.max(g,w),b=h.length,_=C*.8,T=b*C*1.2,S=Math.max(_,T/(2*Math.PI)),k=s||Math.min(S,Math.min(a,l)/2-C/2),D=Math.min(a,l),O=Math.min(D*.25/C,1),I=[];if(m){const F=m.width*O*1.2,M=m.height*O*1.2;I.push({...m,x:d-F/2,y:f-M/2,rotation:0,scale:O*1.2,zIndex:b})}const R=360/b;return h.forEach((F,M)=>{const A=(o+M*R)*Math.PI/180,z=F.width*O,G=F.height*O,W=d+k*Math.cos(A)-z/2,K=f+k*Math.sin(A)-G/2;I.push({...F,x:W,y:K,rotation:0,scale:O,zIndex:M})}),I}inspirationBoardLayout(t,n,r){const{minWidthRatio:i=z0.minWidthRatio,maxWidthRatio:s=z0.maxWidthRatio,maxRotation:o=z0.maxRotation,gap:a=z0.gap}=r||{},{canvasWidth:l,canvasHeight:c,startX:u,startY:d}=n,f=t.length,h=this.assignSizeCategories(f),m=t.reduce((S,k)=>S+k.width,0)/f,g=t.reduce((S,k)=>S+k.height,0)/f,w=l||1200,C=c||600,b=Math.min(w*.25/m,C*.4/g,1),_=this.calculateInspirationBoardPositions(f,w,C,a),T=wx(t.map((S,k)=>k));return t.map((S,k)=>{const D=_[k],O=h[k];let I;switch(O){case"large":I=Go(1.2,s);break;case"medium":I=Go(.9,1.1);break;case"small":I=Go(i,.85);break;default:I=1}const R=b*I,F=Go(-o,o),M=Go(-20,20),$=Go(-15,15),A=S.width*R,z=S.height*R;return{...S,x:u+D.x+M-A/2,y:d+D.y+$-z/2,rotation:F,scale:R,zIndex:T[k]}})}assignSizeCategories(t){const n=[],r=Math.max(2,Math.floor(t*.25)),i=Math.max(2,Math.floor(t*.25)),s=t-r-i;for(let o=0;o<r;o++)n.push("large");for(let o=0;o<s;o++)n.push("medium");for(let o=0;o<i;o++)n.push("small");return wx(n)}calculateInspirationBoardPositions(t,n,r,i){const s=[],o=Math.ceil(t/4),a=Math.ceil(t/o),l=(n-i*2)/a,c=(r-i*2)/o;for(let u=0;u<t;u++){const d=Math.floor(u/a),f=u%a,h=i+f*l+l/2,m=i+d*c+c/2,g=Go(-l*.3,l*.3),w=Go(-c*.2,c*.2);s.push({x:h+g,y:m+w})}return wx(s)}calculateRequiredSize(t,n,r=.5){const i=t.length,s=Math.ceil(Math.sqrt(i)),o=Math.ceil(i/s),a=Math.max(...t.map(h=>h.width)),l=Math.max(...t.map(h=>h.height)),c=20,u=n==="scattered"?60:40,d=s*a*r+(s+1)*c+u*2,f=o*l*r+(o+1)*c+u*2;return{width:d,height:f}}}const sH=new NVe;class jVe{constructor(){this.board=null}setBoard(t){this.board=t}getBoard(){return this.board}async generate(t){const{theme:n,gridConfig:r=Oc.gridConfig,layoutStyle:i=Oc.layoutStyle,imageSize:s=Oc.imageSize,imageQuality:o=Oc.imageQuality}=t;try{const a=this.buildPrompt(n,r),l=await du.generateImage(a,{size:s,quality:o,response_format:"url"});if(!l.data||l.data.length===0)throw new Error("AI 生成图片失败:未返回图片数据");const c=l.data[0].url||l.data[0].b64_json;if(!c)throw new Error("AI 生成图片失败:未返回图片 URL");const u=await Mn.getImageForAI(c),d=u.type==="base64"?u.value:c,f=await iH.split(d,r),h=this.calculateLayoutParams(f),m=sH.calculate(f,i,h);return{success:!0,originalImageUrl:c,elements:m}}catch(a){return console.error("[GridImageService] Generation failed:",a),{success:!1,error:a.message||"宫格图生成失败"}}}async processExistingImage(t,n,r="scattered"){try{const i=await Mn.getImageForAI(t),s=i.type==="base64"?i.value:t,o=await iH.split(s,n),a=this.calculateLayoutParams(o),l=sH.calculate(o,r,a);return{success:!0,originalImageUrl:t,elements:l}}catch(i){return console.error("[GridImageService] Processing failed:",i),{success:!1,error:i.message||"宫格图处理失败"}}}async insertToBoard(t,n){if(!this.board)throw new Error("画板未初始化,请先调用 setBoard");let r=(n==null?void 0:n[0])??100,i=n==null?void 0:n[1];if(i===void 0){const o=bh(this.board);i=(o==null?void 0:o[1])??100,r=(o==null?void 0:o[0])??r}const s=[...t].sort((o,a)=>o.zIndex-a.zIndex);for(const o of s){const a=r+o.x,l=i+o.y,c={url:o.imageData,width:o.width*o.scale,height:o.height*o.scale};Yn.insertImage(this.board,c,[a,l])}}async generateAndInsert(t,n){const r=await this.generate(t);return r.success&&r.elements&&await this.insertToBoard(r.elements,n),r}buildPrompt(t,n){const r=Pee.zh;return r(t,n.rows,n.cols)}calculateLayoutParams(t){const n=t.reduce((h,m)=>h+m.width,0),r=t.reduce((h,m)=>h+m.height,0),i=t.length,s=Math.ceil(Math.sqrt(i)),o=Math.ceil(i/s),a=n/i,l=r/i,c=30,u=50,d=s*a+(s+1)*c+u*2,f=o*l+(o+1)*c+u*2;return{canvasWidth:d,canvasHeight:f,startX:0,startY:0,gap:c}}}const oH=new jVe;function FVe(){const e=An.get();return(e==null?void 0:e.imageModelName)||$g()}function $Ve(){const e=An.get();return(e==null?void 0:e.textModelName)||"deepseek-v3.2"}function zVe(e,t,n){if(t.length>0)return t.join(`
2060
2060
  `);if(e){if(n===1)return"请仔细分析这张图片的内容、风格、构图、色调和艺术特点,推测生成这张图片可能使用的原始提示词,然后基于你推测的提示词重新生成一张全新的、风格相似但内容不完全相同的图片。不要直接复制原图。";if(n>1)return"请分析这些图片的主题、风格和视觉元素,找出它们之间的共同点或关联性,然后创造性地将它们融合成一张全新的、和谐统一的图片。融合时请保持各图片的精华元素,确保最终作品在构图、色调和风格上协调一致。"}return""}function xx(e){return e.replace(":","x").toLowerCase()}function HVe(e,t,n){const r=t.texts.length>0||t.images.length>0||t.videos.length>0||t.graphics.length>0,i=t.texts,s=t.images.length+t.graphics.length,o=Sne(e),a=o.cleanText.trim().length>0,l=a?"agent_flow":"direct_generation";let c="image",u,d=!1;if(n!=null&&n.modelId){const C=bo(n.modelId);(C==null?void 0:C.type)==="video"?c="video":c="image",u=n.modelId,d=!0}else o.selectedVideoModel?(c="video",u=o.selectedVideoModel,d=!0):o.selectedImageModel?(c="image",u=o.selectedImageModel,d=!0):!r&&a?(c="text",u=$Ve()):u=FVe();let f=o.cleanText.trim();f||(f=zVe(r,i,s));const h=o.selectedCount||1;let m,g;if(n!=null&&n.size&&n.size!=="auto")m=xx(n.size);else if((n==null?void 0:n.size)!=="auto"){for(const C of o.selectedParams)if(C.id==="size"){m=xx(C.value);break}}for(const C of o.selectedParams)C.id==="duration"&&(g=C.value);if(!m&&(n==null?void 0:n.size)!=="auto"&&c!=="text"){const C=bo(u);if((C==null?void 0:C.type)==="image"&&C.imageDefaults)m="1x1";else if((C==null?void 0:C.type)==="video"&&C.videoDefaults)m=xx(C.videoDefaults.size),g||(g=C.videoDefaults.duration);else if(c==="image")m="1x1";else if(c==="video"){const b=O9(u);m=xx(b.size),g||(g=b.duration)}}!g&&c==="video"&&(g=O9(u).duration);const w=o.cleanText.trim();return{scenario:l,generationType:c,modelId:u,isModelExplicit:d,prompt:f,userInstruction:w,rawInput:e,count:h,size:m,duration:g,parseResult:o,hasExtraContent:a,selection:t}}var xl=(e=>(e.VIDEO="视频创作",e.IMAGE="图片生成",e.MINDMAP="思维导图",e.FLOWCHART="流程图",e.GRID="宫格图",e.SVG="SVG矢量图",e))(xl||{});const _0=3,aH=[{id:"grid-emoji",title:"智能拆分宫格图",description:"宫格图,风格统一",prompt:"生成16宫格猫咪表情包",category:xl.GRID,imageUrl:"https://tuziphoto.codernote.club/aitu/gonggetu.jpg",badgeColor:"badge--grid"},{id:"flowchart-process",title:"业务流程图",description:"使用 Mermaid 语法生成清晰的流程图",prompt:"绘制一个用户注册登录的流程图,包含邮箱验证、密码校验、短信验证码、登录成功/失败等节点",category:xl.FLOWCHART,imageUrl:"https://tuziphoto.codernote.club/aitu/liuchengtu.png",badgeColor:"badge--flowchart"},{id:"mindmap-project",title:"项目规划脑图",description:"快速生成结构化的思维导图,梳理项目计划",prompt:"创建一个关于「移动应用开发」的思维导图,包含需求分析、UI设计、前端开发、后端开发、测试上线等主要分支",category:xl.MINDMAP,imageUrl:"https://tuziphoto.codernote.club/aitu/siweidaotu.png",badgeColor:"badge--mindmap"}],WVe={[xl.VIDEO]:{bg:"#fce7f3",text:"#be185d"},[xl.IMAGE]:{bg:"#dbeafe",text:"#1d4ed8"},[xl.MINDMAP]:{bg:"#dcfce7",text:"#15803d"},[xl.FLOWCHART]:{bg:"#fef3c7",text:"#b45309"},[xl.GRID]:{bg:"#f3e8ff",text:"#7c3aed"},[xl.SVG]:{bg:"#e0e7ff",text:"#4338ca"}},GVe=({template:e,onClick:t})=>{const n=WVe[e.category],r=i=>{i.preventDefault()};return y.jsxs("div",{className:"inspiration-card",onMouseDown:r,onClick:t,"data-track":`inspiration_click_${e.id}`,children:[y.jsxs("div",{className:"inspiration-card__image-wrapper",children:[y.jsx("img",{src:e.imageUrl,alt:e.title,className:"inspiration-card__image",loading:"lazy"}),y.jsx("span",{className:"inspiration-card__badge",style:{backgroundColor:n.bg,color:n.text},children:e.category}),y.jsx("div",{className:"inspiration-card__hover-overlay",children:y.jsx("div",{className:"inspiration-card__arrow",children:y.jsx(zte,{size:16})})})]}),y.jsxs("div",{className:"inspiration-card__content",children:[y.jsx("h3",{className:"inspiration-card__title",children:e.title}),y.jsx("p",{className:"inspiration-card__description",children:e.description})]})]})},VVe=({isCanvasEmpty:e,onSelectPrompt:t,onOpenPromptTool:n,visible:r=!0,className:i=""})=>{const[s,o]=x.useState(0),a=Math.ceil(aH.length/_0),l=a>1,c=aH.slice(s*_0,(s+1)*_0),u=x.useCallback(h=>{h.preventDefault(),h.stopPropagation(),o(m=>(m-1+a)%a)},[a]),d=x.useCallback(h=>{h.preventDefault(),h.stopPropagation(),o(m=>(m+1)%a)},[a]),f=x.useCallback(h=>{t(h)},[t]);return!e||!r?null:y.jsxs("div",{className:`inspiration-board ${i}`,children:[y.jsxs("div",{className:"inspiration-board__header",children:[y.jsx("h3",{className:"inspiration-board__title",children:"灵感创意"}),n&&y.jsxs("button",{className:"inspiration-board__prompt-btn",onClick:n,onMouseDown:h=>h.preventDefault(),title:"提示词工具","data-track":"inspiration_click_prompt_tool",children:[y.jsx(Fg,{size:14}),y.jsx("span",{children:"提示词"})]}),l&&y.jsxs("div",{className:"inspiration-board__pagination",children:[y.jsxs("span",{className:"inspiration-board__page-indicator",children:[s+1," / ",a]}),y.jsxs("div",{className:"inspiration-board__nav-buttons",children:[y.jsx("button",{className:"inspiration-board__nav-btn",onMouseDown:h=>h.preventDefault(),onClick:u,"aria-label":"上一页","data-track":"inspiration_click_prev",children:y.jsx(xS,{size:16})}),y.jsx("button",{className:"inspiration-board__nav-btn",onMouseDown:h=>h.preventDefault(),onClick:d,"aria-label":"下一页","data-track":"inspiration_click_next",children:y.jsx(bS,{size:16})})]})]})]}),y.jsxs("div",{className:"inspiration-board__grid",children:[c.map(h=>y.jsx(GVe,{template:h,onClick:()=>f(h.prompt)},h.id)),c.length<_0&&Array.from({length:_0-c.length}).map((h,m)=>y.jsx("div",{className:"inspiration-card inspiration-card--placeholder"},`placeholder-${m}`))]})]})},UVe={defaultTimeout:3e4,debug:!1},vl=class vl{constructor(t={}){this.initialized=!1,this.messageSubject=new Ks,this.pendingRequests=new Map,this.messageHandlers=new Map,this.logIdCounter=0,this.storedGeminiConfig=null,this.storedVideoConfig=null,this.config={...UVe,...t},this.setupMessageListener(),this.setupControllerChangeListener()}static getInstance(t){return vl.instance||(vl.instance=new vl(t)),vl.instance}static resetInstance(){vl.instance&&(vl.instance.destroy(),vl.instance=null)}async initialize(t,n){if(this.initialized)return this.storedGeminiConfig=t,this.storedVideoConfig=n,!0;if(!this.isServiceWorkerSupported())return console.warn("[DuplexBridge] Service Worker not supported"),!1;if(this.storedGeminiConfig=t,this.storedVideoConfig=n,!(await navigator.serviceWorker.ready).active)return console.warn("[DuplexBridge] No active Service Worker"),!1;await this.sendMessage({type:"TASK_QUEUE_INIT",geminiConfig:t,videoConfig:n});try{const i=await this.waitForMessage("TASK_QUEUE_INITIALIZED",5e3);return this.initialized=(i==null?void 0:i.success)??!0,this.initialized&&await this.recoverWorkflows(),this.initialized}catch{return this.initialized=!0,!0}}async request(t,n,r={}){const i=this.generateRequestId(),s=r.timeout||this.config.defaultTimeout;return new Promise((o,a)=>{const l=setTimeout(()=>{this.pendingRequests.delete(i),a(new Error(`Request timeout: ${t}`))},s);this.pendingRequests.set(i,{requestId:i,messageType:t,resolve:o,reject:a,timeoutHandle:l,startTime:Date.now()}),this.sendMessage({type:t,requestId:i,...n}).catch(c=>{this.pendingRequests.delete(i),clearTimeout(l),a(c)})})}async sendMessage(t){if(!this.isServiceWorkerSupported())throw new Error("Service Worker not supported");const n=navigator.serviceWorker.controller;if(n)n.postMessage(t);else{const r=await navigator.serviceWorker.ready;if(!r.active)throw new Error("No active Service Worker");r.active.postMessage(t)}this.logMessage("send",t.type,t)}async waitForMessage(t,n){const r=this.messageSubject.pipe(Fi(i=>i.type===t),Cl(1));return od(n?r.pipe(Vp(n)):r)}onMessage(t){return t?this.messageSubject.pipe(Fi(n=>n.type===t)):this.messageSubject.asObservable()}registerHandler(t,n){this.messageHandlers.has(t)||this.messageHandlers.set(t,[]),this.messageHandlers.get(t).push(n)}unregisterHandler(t,n){const r=this.messageHandlers.get(t);if(r){const i=r.indexOf(n);i>=0&&r.splice(i,1)}}isInitialized(){return this.initialized}isServiceWorkerSupported(){return"serviceWorker"in navigator}isConnected(){return this.isServiceWorkerSupported()&&navigator.serviceWorker.controller!==null}enableDebug(t){this.config.debug=!0,t&&(this.config.debugLogger=t)}disableDebug(){this.config.debug=!1,this.config.debugLogger=void 0}getStoredConfig(){return{geminiConfig:this.storedGeminiConfig,videoConfig:this.storedVideoConfig}}destroy(){for(const[,t]of this.pendingRequests)clearTimeout(t.timeoutHandle),t.reject(new Error("Bridge destroyed"));this.pendingRequests.clear(),this.messageHandlers.clear(),this.messageSubject.complete(),this.initialized=!1}setupMessageListener(){this.isServiceWorkerSupported()&&navigator.serviceWorker.addEventListener("message",t=>{const n=t.data;if(!n||typeof n!="object"||!n.type)return;this.logMessage("receive",n.type,n),this.handleResponse(n),this.messageSubject.next(n);const r=this.messageHandlers.get(n.type);r&&r.forEach(i=>{try{i(n)}catch(s){console.error(`[DuplexBridge] Handler error for ${n.type}:`,s)}}),n.type==="SW_REQUEST_CONFIG"&&this.handleConfigRequest()})}setupControllerChangeListener(){this.isServiceWorkerSupported()&&navigator.serviceWorker.addEventListener("controllerchange",()=>{console.log("[DuplexBridge] Service Worker controller changed"),this.storedGeminiConfig&&this.storedVideoConfig&&(this.initialized=!1,this.initialize(this.storedGeminiConfig,this.storedVideoConfig))})}handleResponse(t){const n=t.requestId;if(!n)return;const r=this.pendingRequests.get(n);r&&(clearTimeout(r.timeoutHandle),this.pendingRequests.delete(n),t.error?r.reject(new Error(t.error)):r.resolve(t))}handleConfigRequest(){this.storedGeminiConfig&&this.storedVideoConfig&&this.sendMessage({type:"TASK_QUEUE_INIT",geminiConfig:this.storedGeminiConfig,videoConfig:this.storedVideoConfig}).catch(t=>{console.error("[DuplexBridge] Failed to resend config:",t)})}async recoverWorkflows(){try{this.sendMessage({type:"WORKFLOW_GET_ALL"})}catch(t){console.warn("[DuplexBridge] Failed to recover workflows:",t)}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}logMessage(t,n,r){if(!this.config.debug)return;const i={id:`bridge-${Date.now()}-${++this.logIdCounter}`,timestamp:Date.now(),direction:t,messageType:n,data:this.sanitizeData(r)};this.config.debugLogger?this.config.debugLogger(i):console.log(`[DuplexBridge] ${t==="send"?"→":"←"} ${n}`,r)}sanitizeData(t){if(!t)return t;try{const n=JSON.parse(JSON.stringify(t));return this.sanitizeObject(n),n}catch{return"[Non-serializable]"}}sanitizeObject(t){if(!t||typeof t!="object")return;const n=["apiKey","password","token","secret"];for(const r in t)n.some(i=>r.toLowerCase().includes(i))?t[r]="[REDACTED]":typeof t[r]=="object"&&this.sanitizeObject(t[r])}};vl.instance=null;let JA=vl;function KVe(e){return JA.getInstance(e)}const mf=class mf{constructor(){this.events$=new Ks,this.workflows=new Map,this.initialized=!1,this.subscriptions=[],this.bridge=KVe(),this.setupEventListeners()}static getInstance(){return mf.instance||(mf.instance=new mf),mf.instance}async initialize(){if(!this.initialized){if(!this.bridge.isInitialized()){console.warn("[WorkflowBridge] DuplexBridge not initialized");return}this.initialized=!0,await this.recoverWorkflows()}}async submit(t){if(!this.bridge.isConnected())throw new Error("Service Worker not connected");this.workflows.set(t.id,t),await this.bridge.sendMessage({type:"WORKFLOW_SUBMIT",workflow:t})}async cancel(t){await this.bridge.sendMessage({type:"WORKFLOW_CANCEL",workflowId:t})}async getWorkflowStatus(t){const n=this.workflows.get(t);this.bridge.sendMessage({type:"WORKFLOW_GET_STATUS",workflowId:t});try{const r=await this.bridge.waitForMessage("WORKFLOW_STATUS_RESPONSE",5e3);return r.workflow?(this.workflows.set(t,r.workflow),r.workflow):n||null}catch{return n||null}}async getAllWorkflows(){this.bridge.sendMessage({type:"WORKFLOW_GET_ALL"});try{const t=await this.bridge.waitForMessage("WORKFLOW_ALL_RESPONSE",5e3);if(t.workflows){for(const n of t.workflows)this.workflows.set(n.id,n);return t.workflows}return Array.from(this.workflows.values())}catch{return Array.from(this.workflows.values())}}getWorkflow(t){return this.workflows.get(t)}getCachedWorkflows(){return Array.from(this.workflows.values())}getRunningWorkflows(){return Array.from(this.workflows.values()).filter(t=>t.status==="running"||t.status==="pending")}get events(){return this.events$.asObservable()}subscribeToWorkflow(t,n){return this.events$.pipe(Fi(r=>r.workflowId===t)).subscribe(n)}async recoverWorkflows(){try{const t=await this.getAllWorkflows(),n=t.filter(r=>r.status==="running"||r.status==="pending");for(const r of n)this.events$.next({type:"recovered",workflowId:r.id,workflow:r});return t}catch(t){return console.warn("[WorkflowBridge] Failed to recover workflows:",t),[]}}destroy(){this.subscriptions.forEach(t=>t.unsubscribe()),this.subscriptions=[],this.events$.complete(),this.workflows.clear(),this.initialized=!1}cloneWorkflow(t){return JSON.parse(JSON.stringify(t))}getMutableWorkflow(t){const n=this.workflows.get(t);if(!n)return;const r=this.cloneWorkflow(n);return this.workflows.set(t,r),r}setupEventListeners(){const t=this.bridge.onMessage("WORKFLOW_STATUS").subscribe(l=>{const c=this.getMutableWorkflow(l.workflowId);c&&(c.status=l.status,c.updatedAt=l.updatedAt||Date.now()),this.events$.next({type:"status",workflowId:l.workflowId,status:l.status})});this.subscriptions.push(t);const n=this.bridge.onMessage("WORKFLOW_STEP_STATUS").subscribe(l=>{const c=this.getMutableWorkflow(l.workflowId);if(c){const u=c.steps.find(d=>d.id===l.stepId);u&&(u.status=l.status,u.result=l.result,u.error=l.error,u.duration=l.duration)}this.events$.next({type:"step",workflowId:l.workflowId,stepId:l.stepId,status:l.status,result:l.result,error:l.error,duration:l.duration})});this.subscriptions.push(n);const r=this.bridge.onMessage("WORKFLOW_COMPLETED").subscribe(l=>{l.workflow&&this.workflows.set(l.workflowId,this.cloneWorkflow(l.workflow)),this.events$.next({type:"completed",workflowId:l.workflowId,workflow:l.workflow})});this.subscriptions.push(r);const i=this.bridge.onMessage("WORKFLOW_FAILED").subscribe(l=>{const c=this.getMutableWorkflow(l.workflowId);c&&(c.status="failed",c.error=l.error),this.events$.next({type:"failed",workflowId:l.workflowId,error:l.error})});this.subscriptions.push(i);const s=this.bridge.onMessage("WORKFLOW_STEPS_ADDED").subscribe(l=>{const c=this.getMutableWorkflow(l.workflowId);if(c&&l.steps)for(const u of l.steps)c.steps.find(d=>d.id===u.id)||c.steps.push(u);this.events$.next({type:"steps_added",workflowId:l.workflowId,steps:l.steps})});this.subscriptions.push(s);const o=this.bridge.onMessage("WORKFLOW_RECOVERED").subscribe(l=>{l.workflow&&(this.workflows.set(l.workflowId,l.workflow),this.events$.next({type:"recovered",workflowId:l.workflowId,workflow:l.workflow}))});this.subscriptions.push(o);const a=this.bridge.onMessage("WORKFLOW_ALL_RESPONSE").subscribe(l=>{if(l.workflows)for(const c of l.workflows)this.workflows.set(c.id,c)});this.subscriptions.push(a)}};mf.instance=null;let eD=mf;function qVe(){return eD.getInstance()}const XVe=300*1e3;class YVe{constructor(){this.events$=new Ks,this.workflows=new Map,this.cleanupTimers=new Map,this.messageHandler=null,this.initialized=!1,this.workflowBridge=null,this.bridgeSubscription=null}init(){if(!this.initialized){if(!navigator.serviceWorker){console.warn("[WorkflowSubmissionService] Service Worker not supported");return}this.messageHandler=t=>{this.handleSWMessage(t.data)},navigator.serviceWorker.addEventListener("message",this.messageHandler),this.workflowBridge=qVe(),this.bridgeSubscription=this.workflowBridge.events.subscribe(t=>{this.handleBridgeEvent(t)}),this.initialized=!0}}destroy(){var t;this.messageHandler&&((t=navigator.serviceWorker)==null||t.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.bridgeSubscription&&(this.bridgeSubscription.unsubscribe(),this.bridgeSubscription=null),this.events$.complete(),this.initialized=!1}handleBridgeEvent(t){switch(t.type){case"recovered":t.workflow&&this.workflows.set(t.workflowId,t.workflow),this.events$.next({type:"recovered",workflowId:t.workflowId,workflow:t.workflow});break}}async recoverWorkflows(){if(!this.workflowBridge)return console.warn("[WorkflowSubmissionService] WorkflowBridge not initialized"),[];try{const t=await this.workflowBridge.recoverWorkflows();for(const n of t)this.workflows.set(n.id,n);return t}catch(t){return console.warn("[WorkflowSubmissionService] Failed to recover workflows:",t),[]}}getRunningWorkflows(){return Array.from(this.workflows.values()).filter(t=>t.status==="running"||t.status==="pending")}createWorkflow(t,n=[]){const r=`wf_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,i=Date.now(),s=t.generationType==="video"?"generate_video":"generate_image",o={prompt:t.prompt,model:t.modelId};t.size&&(o.size=t.size),t.count&&t.count>1&&(o.count=t.count),t.duration&&(o.seconds=t.duration),n.length>0&&(o.referenceImages=n);const a=[],l=t.count||1;for(let u=0;u<l;u++)a.push({id:`step_${u}_${Math.random().toString(36).substr(2,9)}`,mcp:s,args:{...o,count:1},description:t.generationType==="video"?`生成视频 ${u+1}/${l}`:`生成图片 ${u+1}/${l}`,status:"pending"});return{id:r,name:t.generationType==="video"?"视频生成":"图片生成",steps:a,status:"pending",createdAt:i,updatedAt:i,context:{userInput:t.userInstruction,model:t.modelId,params:{count:t.count,size:t.size,duration:t.duration},referenceImages:n}}}async submit(t){const n=await this.getServiceWorker();if(!n)throw new Error("Service Worker not available");this.workflows.set(t.id,t),n.postMessage({type:"WORKFLOW_SUBMIT",workflow:t})}async cancel(t){const n=await this.getServiceWorker();n&&n.postMessage({type:"WORKFLOW_CANCEL",workflowId:t})}getWorkflow(t){return this.workflows.get(t)}async queryWorkflowStatus(t){const n=await this.getServiceWorker();return n?new Promise(r=>{var s;const i=o=>{var a,l;((a=o.data)==null?void 0:a.type)==="WORKFLOW_STATUS_RESPONSE"&&o.data.workflowId===t&&((l=navigator.serviceWorker)==null||l.removeEventListener("message",i),o.data.workflow&&this.workflows.set(t,o.data.workflow),r(o.data.workflow||null))};(s=navigator.serviceWorker)==null||s.addEventListener("message",i),setTimeout(()=>{var o;(o=navigator.serviceWorker)==null||o.removeEventListener("message",i),r(this.workflows.get(t)||null)},5e3),n.postMessage({type:"WORKFLOW_GET_STATUS",workflowId:t})}):null}async queryAllWorkflows(){const t=await this.getServiceWorker();return t?new Promise(n=>{var i;const r=s=>{var o,a;if(((o=s.data)==null?void 0:o.type)==="WORKFLOW_ALL_RESPONSE"){(a=navigator.serviceWorker)==null||a.removeEventListener("message",r);for(const l of s.data.workflows)this.workflows.set(l.id,l);n(s.data.workflows)}};(i=navigator.serviceWorker)==null||i.addEventListener("message",r),setTimeout(()=>{var s;(s=navigator.serviceWorker)==null||s.removeEventListener("message",r),n(Array.from(this.workflows.values()))},5e3),t.postMessage({type:"WORKFLOW_GET_ALL"})}):Array.from(this.workflows.values())}get events(){return this.events$.asObservable()}subscribeToWorkflow(t,n){return this.events$.pipe(Fi(r=>r.type==="canvas_insert"?!1:r.workflowId===t)).subscribe(n)}subscribeToCanvasInserts(t){return this.events$.pipe(Fi(n=>n.type==="canvas_insert")).subscribe(t)}async respondToCanvasInsert(t,n,r){const i=await this.getServiceWorker();i&&i.postMessage({type:"CANVAS_OPERATION_RESPONSE",requestId:t,success:n,error:r})}subscribeToToolRequests(t){return this.events$.pipe(Fi(n=>n.type==="main_thread_tool_request")).subscribe(t)}subscribeToAllEvents(t){return this.events$.subscribe(t)}async respondToToolRequest(t,n,r,i,s){const o=await this.getServiceWorker();o&&o.postMessage({type:"MAIN_THREAD_TOOL_RESPONSE",requestId:t,success:n,result:r,error:i,addSteps:s})}handleSWMessage(t){if(!(!t||typeof t!="object"||!t.type))switch(t.type.startsWith("WORKFLOW_"),t.type){case"WORKFLOW_STATUS":this.handleWorkflowStatus(t);break;case"WORKFLOW_STEP_STATUS":this.handleStepStatus(t);break;case"WORKFLOW_COMPLETED":this.handleWorkflowCompleted(t);break;case"WORKFLOW_FAILED":this.handleWorkflowFailed(t);break;case"CANVAS_OPERATION_REQUEST":this.handleCanvasOperation(t);break;case"MAIN_THREAD_TOOL_REQUEST":this.handleMainThreadToolRequest(t);break;case"WORKFLOW_STEPS_ADDED":this.handleWorkflowStepsAdded(t);break;case"WORKFLOW_RECOVERED":this.handleWorkflowRecovered(t);break}}cloneWorkflow(t){return JSON.parse(JSON.stringify(t))}getMutableWorkflow(t){const n=this.workflows.get(t);if(!n)return;const r=this.cloneWorkflow(n);return this.workflows.set(t,r),r}handleWorkflowStatus(t){const n=this.getMutableWorkflow(t.workflowId);n&&(n.status=t.status,n.updatedAt=t.updatedAt||Date.now()),this.events$.next({type:"status",workflowId:t.workflowId,status:t.status})}handleStepStatus(t){const n=this.getMutableWorkflow(t.workflowId);if(n){const r=n.steps.find(i=>i.id===t.stepId);r&&(r.status=t.status,r.result=t.result,r.error=t.error,r.duration=t.duration)}this.events$.next({type:"step",workflowId:t.workflowId,stepId:t.stepId,status:t.status,result:t.result,error:t.error,duration:t.duration})}handleWorkflowCompleted(t){t.workflow&&this.workflows.set(t.workflowId,this.cloneWorkflow(t.workflow)),this.events$.next({type:"completed",workflowId:t.workflowId,workflow:t.workflow}),this.scheduleWorkflowCleanup(t.workflowId)}handleWorkflowFailed(t){console.error("[WorkflowSubmissionService] Workflow failed:",t.workflowId,"-",t.error);const n=this.getMutableWorkflow(t.workflowId);n&&(n.status="failed",n.error=t.error),t.error&&vee(t.error)&&yee({message:t.error,source:"workflow"}),this.events$.next({type:"failed",workflowId:t.workflowId,error:t.error}),this.scheduleWorkflowCleanup(t.workflowId)}handleCanvasOperation(t){this.events$.next({type:"canvas_insert",requestId:t.requestId,operation:t.operation,params:t.params})}handleMainThreadToolRequest(t){this.events$.next({type:"main_thread_tool_request",requestId:t.requestId,workflowId:t.workflowId,stepId:t.stepId,toolName:t.toolName,args:t.args})}handleWorkflowStepsAdded(t){const n=this.workflows.get(t.workflowId);if(n&&t.steps){for(const r of t.steps)n.steps.find(i=>i.id===r.id)||n.steps.push({id:r.id,mcp:r.mcp,args:r.args,description:r.description,status:r.status});this.events$.next({type:"steps_added",workflowId:t.workflowId,steps:t.steps})}}handleWorkflowRecovered(t){t.workflow&&(this.workflows.set(t.workflowId,t.workflow),this.events$.next({type:"recovered",workflowId:t.workflowId,workflow:t.workflow}))}async getServiceWorker(){return navigator.serviceWorker?(await navigator.serviceWorker.ready).active:null}scheduleWorkflowCleanup(t){const n=this.cleanupTimers.get(t);n&&clearTimeout(n);const r=setTimeout(()=>{this.workflows.delete(t),this.cleanupTimers.delete(t)},XVe);this.cleanupTimers.set(t,r)}}const hl=new YVe,lH=Object.freeze(Object.defineProperty({__proto__:null,workflowSubmissionService:hl},Symbol.toStringTag,{value:"Module"}));function vp(e,t,n,r){var s;const i=e.metadata||{};return{id:e.id,name:e.name,generationType:e.generationType,prompt:i.prompt||((s=t==null?void 0:t.aiContext)==null?void 0:s.finalPrompt)||"",aiAnalysis:e.aiAnalysis,count:i.count,steps:e.steps.map(o=>({id:o.id,description:o.description,status:o.status,mcp:o.mcp,args:o.args,result:o.result,error:o.error,duration:o.duration,options:o.options})),retryContext:t,postProcessingStatus:n,insertedCount:r}}function tD(){return!!(navigator.serviceWorker&&navigator.serviceWorker.controller)}function ZVe(e){return tD()}async function QVe(e,t){const{operation:n,params:r}=t;try{const{insertImageFromUrl:i}=await ln(async()=>{const{insertImageFromUrl:l}=await Promise.resolve().then(()=>g2e);return{insertImageFromUrl:l}},void 0,import.meta.url),{insertVideoFromUrl:s}=await ln(async()=>{const{insertVideoFromUrl:l}=await Promise.resolve().then(()=>S7e);return{insertVideoFromUrl:l}},void 0,import.meta.url),{getSmartInsertionPoint:o}=await ln(async()=>{const{getSmartInsertionPoint:l}=await Promise.resolve().then(()=>GSe);return{getSmartInsertionPoint:l}},void 0,import.meta.url),a=r.position?[r.position.x,r.position.y]:o(e)||[100,100];if(n==="canvas_insert"&&r.items)for(const l of r.items)l.type==="image"&&l.url?await i(e,l.url,a):l.type==="video"&&l.url&&await s(e,l.url,a);else n==="insert_image"&&r.url?await i(e,r.url,a):n==="insert_video"&&r.url&&await s(e,r.url,a)}catch(i){console.error("[useWorkflowSubmission] Failed to insert to canvas:",i)}}function JVe(e){const{boardRef:t,workZoneIdRef:n,useSWExecution:r=!0}=e,i=Nne(),s=j3(),o=x.useRef(s.sendWorkflowMessage),a=x.useRef(s.updateWorkflowMessage);x.useEffect(()=>{o.current=s.sendWorkflowMessage,a.current=s.updateWorkflowMessage},[s.sendWorkflowMessage,s.updateWorkflowMessage]);const l=x.useRef(null),c=x.useRef([]),u=x.useRef(!1),d=x.useRef(null),f=x.useCallback(async()=>{if(!u.current){u.current=!0;try{const S=await hl.recoverWorkflows()}catch(S){console.warn("[useWorkflowSubmission] Failed to recover workflows:",S)}}},[]),h=x.useCallback(S=>{var M,$,A,z,G,W,K,j,H;if(S.type!=="recovered"||!S.workflow)return;const k=S.workflow,D=t.current,O=n.current;if(k.status!=="running"&&k.status!=="pending")return;(M=i.restoreWorkflow)==null||M.call(i,k);const I={aiContext:{rawInput:(($=k.context)==null?void 0:$.userInput)||"",userInstruction:((A=k.context)==null?void 0:A.userInput)||"",model:{id:((z=k.context)==null?void 0:z.model)||"",type:k.generationType==="video"?"video":"image",isExplicit:!0},params:{count:(G=k.metadata)==null?void 0:G.count,size:(W=k.metadata)==null?void 0:W.size,duration:(K=k.metadata)==null?void 0:K.duration},selection:{texts:[],images:[],videos:[],graphics:[]},finalPrompt:((j=k.metadata)==null?void 0:j.prompt)||""},referenceImages:((H=k.context)==null?void 0:H.referenceImages)||[],textModel:An.get().textModelName},R=vp(k,I);a.current(R),O&&D&&$r.updateWorkflow(D,O,R);const F=hl.subscribeToWorkflow(k.id,L=>{var V;(V=d.current)==null||V.call(d,L,k,I)});c.current.push(F)},[i,t,n]);x.useEffect(()=>{hl.init();const S=hl.subscribeToCanvasInserts(async D=>{await hl.respondToCanvasInsert(D.requestId,!0)});c.current.push(S);const k=hl.subscribeToAllEvents(D=>{D.type==="recovered"&&h(D)});return c.current.push(k),f(),()=>{c.current.forEach(D=>D.unsubscribe()),c.current=[]}},[]);const m=x.useCallback((S,k,D)=>{const O=t.current,I=n.current;switch(S.type){case"step":{i.updateStep(S.stepId,S.status,S.result,S.error,S.duration);const R=i.getWorkflow();if(R){const F=vp(R,D);a.current(F),I&&O&&$r.updateWorkflow(O,I,F)}break}case"completed":{const R=i.getWorkflow();let F=!1;R&&R.steps.forEach($=>{if($.status==="running"||$.status==="pending"){const A=$.result;(A==null?void 0:A.taskId)?F=!0:i.updateStep($.id,"completed")}});const M=i.getWorkflow();if(M){const $=vp(M,D);a.current($),I&&O&&($r.updateWorkflow(O,I,$),F||setTimeout(()=>{$r.removeWorkZone(O,I)},1500))}break}case"failed":{console.error("[useWorkflowSubmission] ✗ Workflow failed:",S.error),i.abortWorkflow();const R=i.getWorkflow();if(R){const F=vp(R,D);a.current(F),I&&O&&$r.updateWorkflow(O,I,F)}break}case"steps_added":{const R=S;i.addSteps(R.steps.map(M=>({id:M.id,mcp:M.mcp,args:M.args,description:M.description,status:M.status})));const F=i.getWorkflow();if(F){const M=vp(F,D);a.current(M),I&&O&&$r.updateWorkflow(O,I,M)}break}case"canvas_insert":{O&&QVe(O,S);break}}},[i,t,n]);x.useEffect(()=>{d.current=m},[m]);const g=x.useCallback(async(S,k,D,O)=>{const{swTaskQueueService:I}=await ln(async()=>{const{swTaskQueueService:M}=await Promise.resolve().then(()=>g3);return{swTaskQueueService:M}},void 0,import.meta.url);await I.initialize();const R={id:S.id,name:S.name,steps:S.steps.map(M=>({id:M.id,mcp:M.mcp,args:M.args,description:M.description,status:M.status})),status:"pending",createdAt:S.createdAt,updatedAt:Date.now(),context:{userInput:k.userInstruction,model:k.modelId,params:{count:k.count,size:k.size,duration:k.duration},referenceImages:D}},F=hl.subscribeToWorkflow(R.id,M=>{m(M,S,O)});return c.current.push(F),console.log("[WorkflowSubmit] Submitting to SW:",{workflowId:R.id,stepsCount:R.steps.length,timestamp:new Date().toISOString()}),await hl.submit(R),console.log("[WorkflowSubmit] ✓ Submitted to SW:",R.id),R.id},[m]),w=x.useCallback(async(S,k,D,O)=>{console.log("[WorkflowSubmit] ▶ submitWorkflow called",{scenario:S.scenario,generationType:S.generationType,useSWExecution:r,swAvailable:tD(),existingWorkflowId:O==null?void 0:O.id,timestamp:new Date().toISOString()});const I=O||Bne(S,k);console.log("[WorkflowSubmit] Created/using workflow:",{workflowId:I.id,name:I.name,stepsCount:I.steps.length}),i.startWorkflow(I);const F=An.get().textModelName,M=D||{aiContext:{rawInput:S.rawInput||S.userInstruction,userInstruction:S.userInstruction,model:{id:S.modelId,type:S.generationType,isExplicit:S.isModelExplicit},params:{count:S.count,size:S.size,duration:S.duration},selection:S.selection||{texts:[],images:[],videos:[],graphics:[]},finalPrompt:S.prompt},referenceImages:k,textModel:F};l.current=M;const $=vp(I,M);return await o.current({context:M.aiContext,workflow:$,textModel:F,autoOpen:!1}),r&&ZVe()?(await g(I,S,k,M),{workflowId:I.id,usedSW:!0}):{workflowId:I.id,usedSW:!1}},[i,r,g]),C=x.useCallback(async S=>{await hl.cancel(S),i.abortWorkflow()},[i]),b=x.useCallback(async(S,k)=>{const D=S.retryContext;if(!D){console.error("[useWorkflowSubmission] No retry context available");return}const O={prompt:S.prompt,userInstruction:D.aiContext.userInstruction,rawInput:D.aiContext.rawInput,modelId:D.aiContext.model.id,isModelExplicit:D.aiContext.model.isExplicit,generationType:D.aiContext.model.type,count:S.count||1,size:D.aiContext.params.size,duration:D.aiContext.params.duration,scenario:"direct_generation",selection:D.aiContext.selection,parseResult:{},hasExtraContent:!1};await w(O,D.referenceImages||[],D)},[w]),_=x.useCallback(()=>tD(),[]),T=x.useCallback(()=>l.current,[]);return{submitWorkflow:w,cancelWorkflow:C,retryWorkflow:b,isSWAvailable:_,getRetryContext:T}}function co(e,t,n,r){var s;const i=e.metadata||{};return{id:e.id,name:e.name,generationType:e.generationType,prompt:i.prompt||((s=t==null?void 0:t.aiContext)==null?void 0:s.finalPrompt)||"",aiAnalysis:e.aiAnalysis,count:i.count,steps:e.steps.map(o=>({id:o.id,description:o.description,status:o.status,mcp:o.mcp,args:o.args,result:o.result,error:o.error,duration:o.duration,options:o.options})),retryContext:t,postProcessingStatus:n,insertedCount:r}}let cH=!1;cH||(p3(),RVe(),cH=!0);function eUe(e){if(!e)return!1;const t=e.toLowerCase();return t.includes("#video")?!0:[".mp4",".webm",".mov",".avi",".mkv",".m4v",".flv",".wmv"].some(r=>t.includes(r))}const $ne=J.memo(({language:e,onSelectionChange:t,externalBoardRef:n,onCanvasEmptyChange:r,isDataReady:i})=>{const s=Hr(),o=x.useRef(s);o.current=s,x.useEffect(()=>(Rz(s),F9(s),tH(s),oH.setBoard(s),n&&(n.current=s),()=>{Rz(null),F9(null),tH(null),oH.setBoard(null),n&&(n.current=null)}),[s,n]);const a=x.useRef(r);a.current=r,x.useEffect(()=>{if(!s||!a.current||!i)return;const u=setInterval(()=>{var f;const d=s.children||[];(f=a.current)==null||f.call(a,d.length===0)},500);return()=>{clearInterval(u)}},[s,i]);const l=x.useRef(t);return l.current=t,x.useEffect(()=>{const c=async()=>{var h,m;const d=o.current;if(!d)return;if(nt(d).length===0){l.current([]);return}try{const g=await WX(d),w=[];g.graphicsImage&&w.push({url:g.graphicsImage,name:e==="zh"?"图形元素":"Graphics",type:"graphics",width:(h=g.graphicsImageDimensions)==null?void 0:h.width,height:(m=g.graphicsImageDimensions)==null?void 0:m.height});for(const C of g.remainingImages){const b=C.url||"",_=eUe(b);w.push({url:b,name:C.name||(_?`video-${Date.now()}`:`image-${Date.now()}`),type:_?"video":"image",width:C.width,height:C.height})}g.remainingText&&g.remainingText.trim()&&w.push({type:"text",text:g.remainingText.trim(),name:e==="zh"?"文字内容":"Text Content"}),l.current(w)}catch(g){console.error("Failed to process selected content:",g),l.current([])}};c();const u=()=>{setTimeout(c,50)};return document.addEventListener("mouseup",u),()=>{document.removeEventListener("mouseup",u)}},[e]),null});$ne.displayName="SelectionWatcher";const zne=J.memo(({className:e,isDataReady:t})=>{const{language:n}=jn(),r=j3(),i=Nne(),{addHistory:s}=pS(),{addAsset:o}=m3(),a=x.useRef(r.sendWorkflowMessage);a.current=r.sendWorkflowMessage;const l=x.useRef(r.updateWorkflowMessage);l.current=r.updateWorkflowMessage;const c=x.useRef(r.appendAgentLog);c.current=r.appendAgentLog;const u=x.useRef(r.updateThinkingContent);u.current=r.updateThinkingContent;const d=x.useRef(r.setSelectedContent);d.current=r.setSelectedContent;const f=x.useRef(r.registerRetryHandler);f.current=r.registerRetryHandler;const h=x.useRef(null),m=x.useRef(null),[g,w]=x.useState(""),[C,b]=x.useState([]),[_,T]=x.useState([]),[S,k]=x.useState(!1),D=x.useRef(null),[O,I]=x.useState(!1),[R,F]=x.useState(null),[M,$]=x.useState($g),[A,z]=x.useState(()=>hee($g())),[G,W]=x.useState(!1),[K,j]=x.useState(""),[H,L]=x.useState(0),V=x.useRef(null),Y=x.useMemo(()=>[..._,...C],[_,C]);x.useEffect(()=>{if(!O)return;const _e=We=>{const Se=We.target;oe.current&&!oe.current.contains(Se)&&I(!1)};return document.addEventListener("mousedown",_e),()=>document.removeEventListener("mousedown",_e)},[O]),x.useEffect(()=>()=>{D.current&&clearTimeout(D.current)},[]),x.useEffect(()=>{const _e=We=>{D.current&&(clearTimeout(D.current),D.current=null),k(!1)};return window.addEventListener("ai-generation-complete",_e),()=>{window.removeEventListener("ai-generation-complete",_e)}},[]),x.useEffect(()=>{const _e=bn.observeTaskUpdates().subscribe(We=>{var Ct,$e;const Se=We.task,pe=i.getWorkflow();if(!pe)return;const Be=pe.steps.find(Fe=>{const rt=Fe.result;return(rt==null?void 0:rt.taskId)===Se.id});if(!Be)return;let Pe=Be.status,Qe=Be.result,wt=Be.error;switch(Se.status){case ht.PENDING:case ht.PROCESSING:Pe="running";break;case ht.COMPLETED:Pe="completed",Qe={...typeof Qe=="object"?Qe:{},taskId:Se.id,result:Se.result};break;case ht.FAILED:Pe="failed",wt=((Ct=Se.error)==null?void 0:Ct.message)||"任务执行失败";break;case ht.CANCELLED:Pe="skipped";break}if(Pe!==Be.status){if(i.updateStep(Be.id,Pe,Qe,wt),Pe==="failed"){const rt=($e=Be.options)==null?void 0:$e.batchId;rt&&pe.steps.forEach(bt=>{var on;bt.id!==Be.id&&((on=bt.options)==null?void 0:on.batchId)===rt&&bt.status==="running"&&i.updateStep(bt.id,"skipped",void 0,"前置任务失败")})}const Fe=i.getWorkflow();if(Fe){const rt=co(Fe,h.current||void 0);l.current(rt);const bt=m.current,on=re.current;bt&&on&&$r.updateWorkflow(on,bt,rt)}}});return()=>_e.unsubscribe()},[i]);const q=x.useRef(void 0),Z=x.useRef(void 0);x.useEffect(()=>{const _e=ps.observeCompletionEvents().subscribe(We=>{const Se=i.getWorkflow(),pe=Se==null?void 0:Se.steps.find(Qe=>{const wt=Qe.result;return(wt==null?void 0:wt.taskId)===We.taskId});let Be,Pe;switch(We.type){case"postProcessingStarted":Be="processing";break;case"postProcessingCompleted":Be="completed",Pe=We.result.insertedCount;break;case"postProcessingFailed":Be="failed";break}if(q.current=Be,Pe!==void 0&&(Z.current=(Z.current||0)+Pe),Se&&pe){const Qe=i.getWorkflow();if(Qe){const wt=co(Qe,h.current||void 0,Be,Z.current);l.current(wt);const Ct=m.current,$e=re.current;Ct&&$e&&$r.updateWorkflow($e,Ct,wt)}}if(We.type==="postProcessingCompleted"){const Qe=We.result.firstElementPosition;D.current&&(clearTimeout(D.current),D.current=null),k(!1),setTimeout(()=>{var $e;r.closeChatDrawer();const wt=m.current,Ct=re.current;if(wt&&Ct&&($r.removeWorkZone(Ct,wt),m.current=null),Qe&&Ct){const Fe=($e=Ct.host)==null?void 0:$e.getBoundingClientRect();if(Fe){const rt=Ct.viewport.zoom,bt=Qe[0]-Fe.width/(2*rt),on=Qe[1]-Fe.height/(2*rt);$t.updateViewport(Ct,[bt,on],rt)}}},500),q.current=void 0,Z.current=void 0}});return()=>_e.unsubscribe()},[i,r]);const re=x.useRef(null),{submitWorkflow:ae}=JVe({boardRef:re,workZoneIdRef:m,useSWExecution:!0}),de=x.useRef(null),oe=x.useRef(null),ee=x.useRef(null);B3(de,{enableCopy:!0,stopPropagation:!0});const ce=x.useCallback(_e=>{var We;w(_e),(We=de.current)==null||We.focus()},[]),me=x.useCallback(_e=>{var We;w(_e),(We=de.current)==null||We.focus()},[]),ve=x.useCallback(()=>{const _e=re.current;if(!_e){console.warn("[AIInputBar] Board not ready for prompt tool");return}const We=jne.find(Fe=>Fe.id==="banana-prompt");if(!We){console.warn("[AIInputBar] Banana prompt tool not found");return}const Se=Q.getBoardContainer(_e).getBoundingClientRect(),pe=[Se.width/2,Se.height/2],Be=_e.viewport.zoom,Pe=pu(_e),Qe=Pe[0]+pe[0]/Be,wt=Pe[1]+pe[1]/Be,Ct=We.defaultWidth||qu.defaultWidth,$e=We.defaultHeight||qu.defaultHeight;Pc.insertTool(_e,We.id,We.url,[Qe-Ct/2,wt-$e/2],{width:Ct,height:$e},{name:We.name,category:We.category,permissions:We.permissions})},[]),N=x.useCallback(()=>{var _e;(_e=ee.current)==null||_e.click()},[]),he=x.useCallback(_e=>new Promise((We,Se)=>{const pe=new FileReader;pe.onload=()=>{const Be=pe.result,Pe=new Image;Pe.onload=()=>{We({url:Be,width:Pe.naturalWidth,height:Pe.naturalHeight})},Pe.onerror=()=>{We({url:Be,width:0,height:0})},Pe.src=Be},pe.onerror=Se,pe.readAsDataURL(_e)}),[]),fe=x.useCallback(async _e=>{const We=_e.target.files;if(!We||We.length===0)return;const Se=[];for(let pe=0;pe<We.length;pe++){const Be=We[pe];if(Be.type.startsWith("image/")){o(Be,Kr.IMAGE,Ic.LOCAL,Be.name).catch(Pe=>{console.warn("[AIInputBar] Failed to add asset to library:",Pe)});try{const{url:Pe,width:Qe,height:wt}=await he(Be);Se.push({type:"image",url:Pe,name:Be.name||`上传图片 ${pe+1}`,width:Qe||void 0,height:wt||void 0})}catch(Pe){console.error("Failed to convert file to base64:",Pe)}}}Se.length>0&&T(pe=>[...pe,...Se]),_e.target.value=""},[he,o]),ne=x.useCallback(_e=>{b(_e)},[]),ie=x.useCallback(_e=>{_e<_.length&&T(We=>We.filter((Se,pe)=>pe!==_e))},[_.length]);x.useEffect(()=>{d.current(Y.map(_e=>({type:_e.type,url:_e.url,text:_e.text,name:_e.name})))},[Y]);const ue=x.useCallback(_e=>{qt.track("ai_input_change_model_dropdown",{model:_e}),$(_e)},[]),Te=x.useMemo(()=>{if(!K)return Xl;const _e=K.toLowerCase();return Xl.filter(We=>{var Se,pe;return((Se=We.shortCode)==null?void 0:Se.toLowerCase().includes(_e))||((pe=We.shortLabel)==null?void 0:pe.toLowerCase().includes(_e))||We.label.toLowerCase().includes(_e)})},[K]),De=x.useCallback((_e,We)=>{let Se=-1;for(let pe=We-1;pe>=0;pe--){const Be=_e[pe];if(Be===" "||Be===`
2061
2061
  `)break;if(Be==="@"){Se=pe;break}}if(Se>=0){const pe=_e.slice(Se+1,We);j(pe),W(!0),L(0)}else W(!1),j("")},[]),ye=x.useCallback(_e=>{const We=_e.target.value;w(We);const Se=_e.target.selectionStart||0;De(We,Se)},[De]),Ne=x.useCallback(_e=>{const We=de.current;if(!We)return;const Se=We.selectionStart||0,pe=g;let Be=-1;for(let Pe=Se-1;Pe>=0;Pe--){if(pe[Pe]==="@"){Be=Pe;break}if(pe[Pe]===" "||pe[Pe]===`
2062
2062
  `)break}if(Be>=0){const Pe=pe.slice(0,Be)+pe.slice(Se);w(Pe)}$(_e),W(!1),j(""),We.focus()},[g]),Re=x.useCallback(async()=>{var _e,We,Se,pe,Be,Pe,Qe;if(!(!g.trim()&&Y.length===0)&&!S){k(!0);try{const wt=Y.filter(Pt=>Pt.type==="image"&&Pt.url),Ct=Y.filter(Pt=>Pt.type==="graphics"&&Pt.url),$e=[...wt,...Ct].map(Pt=>{if(Pt.width&&Pt.height)return{width:Pt.width,height:Pt.height}}).filter(Pt=>Pt!==void 0),Fe={texts:Y.filter(Pt=>Pt.type==="text"&&Pt.text).map(Pt=>Pt.text),images:wt.map(Pt=>Pt.url),videos:Y.filter(Pt=>Pt.type==="video"&&Pt.url).map(Pt=>Pt.url),graphics:Ct.map(Pt=>Pt.url),imageDimensions:$e},rt=HVe(g,Fe,{modelId:M,size:A}),bt=[...Fe.images,...Fe.graphics],on=Bne(rt,bt),tt=re.current;if(tt){const Br=(_e=tt.host)==null?void 0:_e.getBoundingClientRect(),fr=((We=tt.viewport)==null?void 0:We.zoom)||1,Cr=((pe=(Se=tt.viewport)==null?void 0:Se.origination)==null?void 0:pe[0])||0,wi=((Pe=(Be=tt.viewport)==null?void 0:Be.origination)==null?void 0:Pe[1])||0,to=tt.children.filter(Ts=>Ts.type!=="workzone"),lc=Cr+((Br==null?void 0:Br.width)||0)/2/fr,Ja=wi+((Br==null?void 0:Br.height)||0)/2/fr;let _s=lc-200,Bo=Ja,Dn=_s,xa=Ja-240/2,Yi="viewport-center";if(to.length>0){const Ts=nt(tt);let ba=!1;if(Ts.length>0)try{const xi=Et(tt,Ts,!1),Yr=xi.y+xi.height;_s=xi.x,Bo=Yr+50,Dn=_s,xa=Bo,Yi="below-selected",ba=!0}catch(xi){console.warn("[AIInputBar] Failed to calculate position for selected elements:",xi)}if(!ba){let xi=null,Yr=-1/0;for(const Lo of to)try{const si=Et(tt,[Lo],!1),le=si.y+si.height;le>Yr&&(Yr=le,xi=Lo)}catch(si){console.warn("[AIInputBar] Failed to get rectangle for element:",si)}if(xi){const Lo=Et(tt,[xi],!1);_s=Lo.x,Bo=Lo.y+Lo.height+50,Dn=_s,xa=Bo,Yi="below-bottommost"}}}const cc=co(on),no=$r.insertWorkZone(tt,{workflow:cc,position:[Dn,xa],size:{width:360,height:240},expectedInsertPosition:[_s,Bo],zoom:fr});m.current=no.id,setTimeout(()=>{const Ts=Dn+180,ba=xa+240/2;So(tt,[Ts,ba],100)},100)}else console.warn("[AIInputBar] Board not available, skipping WorkZone creation");const Ut={rawInput:g,userInstruction:rt.userInstruction,model:{id:rt.modelId,type:rt.generationType,isExplicit:rt.isModelExplicit},params:{count:rt.count,size:rt.size,duration:rt.duration},selection:Fe,finalPrompt:rt.prompt},Cn=An.get().textModelName,Rn={aiContext:Ut,referenceImages:bt,textModel:Cn};h.current=Rn;try{const{usedSW:Pt}=await ae(rt,bt,Rn,on);if(Pt){if(g.trim()){const Gr=Y.length>0;s(g.trim(),Gr)}w(""),b([]),T([]),D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{k(!1),D.current=null},1e3);return}}catch(Pt){console.warn("[AIInputBar] SW execution failed, falling back to main thread:",Pt)}const sn=[],Pn=[],dr=(Pt,Gr)=>({onChunk:Zn=>{u.current(Zn)},onAddSteps:Zn=>{i.updateStep(Pt.id,"completed",{analysis:"completed"},void 0,Date.now()-Gr);const Br=Zn.map((Cr,wi)=>({...Cr,status:Cr.status==="completed"?"completed":"pending",options:{mode:"queue",batchId:`agent_${Date.now()}`,batchIndex:wi+1,batchTotal:Zn.length,globalIndex:wi+1}}));i.addSteps(Br),Pn.push(...Br),Zn.forEach(Cr=>{c.current({type:"tool_call",timestamp:Date.now(),toolName:Cr.mcp,args:Cr.args})});const fr=co(i.getWorkflow(),h.current||void 0);l.current(fr),m.current&&tt&&$r.updateWorkflow(tt,m.current,fr)},onUpdateStep:(Zn,Br,fr,Cr)=>{i.updateStep(Zn,Br,fr,Cr),c.current({type:"tool_result",timestamp:Date.now(),toolName:Zn,success:Br==="completed",data:fr,error:Cr});const wi=co(i.getWorkflow(),h.current||void 0);l.current(wi),m.current&&tt&&$r.updateWorkflow(tt,m.current,wi)}});let Ri=!1;const Bi=()=>{const Pt=co(i.getWorkflow(),h.current||void 0);l.current(Pt),m.current&&tt&&$r.updateWorkflow(tt,m.current,Pt)},Ss=async Pt=>{var Zn,Br;const Gr=Date.now();i.updateStep(Pt.id,"running"),Bi();try{const fr={...Pt.options,...dr(Pt,Gr)},Cr=await h1.executeTool({name:Pt.mcp,arguments:Pt.args},fr),wi=(Br=(Zn=i.getWorkflow())==null?void 0:Zn.steps.find(to=>to.id===Pt.id))==null?void 0:Br.status;if(Cr.success)Cr.taskId?(sn.push(Cr.taskId),i.updateStep(Pt.id,"running",{taskId:Cr.taskId})):wi==="running"&&i.updateStep(Pt.id,"completed",Cr.data,void 0,Date.now()-Gr);else return i.updateStep(Pt.id,"failed",void 0,Cr.error||"执行失败",Date.now()-Gr),!1;return!0}catch(fr){return i.updateStep(Pt.id,"failed",void 0,String(fr)),!1}finally{Bi()}};for(const Pt of on.steps){if(Ri){i.updateStep(Pt.id,"skipped"),Bi();continue}await Ss(Pt)||(Ri=!0)}if(!Ri&&Pn.length>0){const Pt=i.getWorkflow();for(const Gr of Pn){if(Ri){i.updateStep(Gr.id,"skipped"),Bi();continue}const Zn=(Qe=i.getWorkflow())==null?void 0:Qe.steps.find(fr=>fr.id===Gr.id);if(!Zn){console.warn(`[AIInputBar] Step ${Gr.id} not found in workflow!`);continue}if(Zn.status==="completed")continue;await Ss(Zn)||(Ri=!0)}}if(g.trim()){const Pt=Y.length>0;s(g.trim(),Pt)}const eo=i.getWorkflow(),Qa=eo==null?void 0:eo.steps.every(Pt=>Pt.status==="completed"||Pt.status==="failed"||Pt.status==="skipped"),ac=sn.length>0;if(Qa&&!ac){const Pt=m.current,Gr=re.current;Pt&&Gr&&setTimeout(()=>{$r.removeWorkZone(Gr,Pt),m.current=null},1500)}w(""),b([]),T([])}catch(wt){console.error("Failed to create generation task:",wt),i.abortWorkflow(),k(!1)}D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{k(!1),D.current=null},1e3)}},[g,Y,S,M,i,ae,s,A]),He=x.useCallback(async(_e,We)=>{var on;const Se=_e.retryContext;if(!Se){console.error("[AIInputBar] No retry context available for workflow");return}const pe={id:_e.id,name:_e.name,description:`重试: ${_e.name}`,scenarioType:_e.steps.some(tt=>tt.mcp==="ai_analyze")?"agent_flow":"direct_generation",generationType:_e.generationType,steps:_e.steps.map((tt,Ut)=>({id:tt.id,mcp:tt.mcp,args:tt.args,description:tt.description,status:Ut<We?tt.status:"pending",result:Ut<We?tt.result:void 0,error:Ut<We?tt.error:void 0,duration:Ut<We?tt.duration:void 0,options:tt.options})),metadata:{prompt:_e.prompt,userInstruction:Se.aiContext.userInstruction,rawInput:Se.aiContext.rawInput,modelId:Se.aiContext.model.id,isModelExplicit:Se.aiContext.model.isExplicit,count:_e.count,size:Se.aiContext.params.size,duration:Se.aiContext.params.duration,referenceImages:Se.referenceImages,selection:Se.aiContext.selection},createdAt:Date.now()};i.startWorkflow(pe),c.current({type:"retry",timestamp:Date.now(),reason:`从步骤 ${We+1} 开始重试`,attempt:1}),l.current(co(pe,Se));const Be=(tt,Ut)=>({onChunk:kn=>{u.current(kn)},onAddSteps:kn=>{i.updateStep(tt.id,"completed",{analysis:"completed"},void 0,Date.now()-Ut);const Cn=kn.map((Rn,sn)=>({...Rn,status:Rn.status==="completed"?"completed":"pending",options:{mode:"queue",batchId:`agent_${Date.now()}`,batchIndex:sn+1,batchTotal:kn.length,globalIndex:sn+1}}));i.addSteps(Cn),Pe.push(...Cn),kn.forEach(Rn=>{c.current({type:"tool_call",timestamp:Date.now(),toolName:Rn.mcp,args:Rn.args})}),l.current(co(i.getWorkflow(),Se))},onUpdateStep:(kn,Cn,Rn,sn)=>{i.updateStep(kn,Cn,Rn,sn),c.current({type:"tool_result",timestamp:Date.now(),toolName:kn,success:Cn==="completed",data:Rn,error:sn}),l.current(co(i.getWorkflow(),Se))}}),Pe=[];let Qe=!1;const wt=new Map;_e.steps.forEach(tt=>{var kn;const Ut=(kn=tt.result)==null?void 0:kn.taskId;Ut&&wt.set(tt.id,Ut)});const Ct=async tt=>{var kn,Cn;const Ut=Date.now();i.updateStep(tt.id,"running"),l.current(co(i.getWorkflow(),Se));try{const Rn=wt.get(tt.id),sn={...tt.options,...Be(tt,Ut),...Rn?{retryTaskId:Rn}:{}},Pn=await h1.executeTool({name:tt.mcp,arguments:tt.args},sn),dr=(Cn=(kn=i.getWorkflow())==null?void 0:kn.steps.find(Ri=>Ri.id===tt.id))==null?void 0:Cn.status;if(Pn.success)Pn.taskId?i.updateStep(tt.id,"running",{taskId:Pn.taskId}):dr==="running"&&i.updateStep(tt.id,"completed",Pn.data,void 0,Date.now()-Ut);else return i.updateStep(tt.id,"failed",void 0,Pn.error||"执行失败",Date.now()-Ut),!1;return!0}catch(Rn){return i.updateStep(tt.id,"failed",void 0,String(Rn)),!1}finally{l.current(co(i.getWorkflow(),Se))}},$e=pe.steps.slice(We);for(const tt of $e){if(Qe){i.updateStep(tt.id,"skipped"),l.current(co(i.getWorkflow(),Se));continue}await Ct(tt)||(Qe=!0)}if(!Qe&&Pe.length>0)for(const tt of Pe){if(Qe){i.updateStep(tt.id,"skipped"),l.current(co(i.getWorkflow(),Se));continue}const Ut=(on=i.getWorkflow())==null?void 0:on.steps.find(Cn=>Cn.id===tt.id);if(!Ut||Ut.status==="completed")continue;await Ct(Ut)||(Qe=!0)}const Fe=i.getWorkflow(),rt=Fe==null?void 0:Fe.steps.every(tt=>tt.status==="completed"||tt.status==="failed"||tt.status==="skipped"),bt=Fe==null?void 0:Fe.steps.some(tt=>{var Ut;return(Ut=tt.result)==null?void 0:Ut.taskId});if(rt&&!bt){const tt=m.current,Ut=re.current;tt&&Ut&&setTimeout(()=>{$r.removeWorkZone(Ut,tt),m.current=null},1500)}},[i]);x.useEffect(()=>{f.current(He)},[He]);const et=x.useCallback(_e=>{var We;if(!_e.nativeEvent.isComposing){if(G&&Te.length>0){if(_e.key==="ArrowDown"){_e.preventDefault(),L(Se=>Se<Te.length-1?Se+1:0);return}if(_e.key==="ArrowUp"){_e.preventDefault(),L(Se=>Se>0?Se-1:Te.length-1);return}if(_e.key==="Tab"||_e.key==="Enter"){_e.preventDefault();const Se=Te[H];Se&&(qt.track("ai_input_select_model_at_keyboard",{model:Se.id}),Ne(Se.id));return}if(_e.key==="Escape"){_e.preventDefault(),W(!1),j("");return}}if(!(_e.key==="Enter"&&(_e.shiftKey||_e.altKey))){if(_e.key==="Enter"){_e.preventDefault(),qt.track("ai_input_submit_keyboard"),Re();return}if(_e.key==="Escape"){I(!1),(We=de.current)==null||We.blur();return}}}},[Re,G,Te,H,Ne]),gt=x.useCallback(()=>{qt.track("ai_input_focus_textarea"),I(_e=>_e||!0)},[]),Ye=x.useCallback(()=>{qt.track("ai_input_blur_textarea"),I(_e=>_e&&!1)},[]),je=g.trim().length>0||Y.length>0,Me=R===!0;return y.jsxs("div",{ref:oe,className:Le("ai-input-bar",vi,e,{"ai-input-bar--with-inspiration":Me}),children:[y.jsx($ne,{language:n,onSelectionChange:ne,externalBoardRef:re,onCanvasEmptyChange:F,isDataReady:t}),y.jsx(VVe,{isCanvasEmpty:Me,onSelectPrompt:ce,onOpenPromptTool:ve}),y.jsxs("div",{className:Le("ai-input-bar__container",{"ai-input-bar__container--expanded":O||Y.length>0}),children:[y.jsxs("div",{className:"ai-input-bar__bottom-bar",children:[y.jsx("input",{ref:ee,type:"file",accept:"image/*",multiple:!0,onChange:fe,style:{display:"none"}}),y.jsx("button",{className:"ai-input-bar__upload-btn",onMouseDown:_e=>{_e.preventDefault(),_e.stopPropagation()},onClick:N,title:n==="zh"?"上传图片":"Upload images","data-track":"ai_input_click_upload",children:y.jsx(FLe,{size:18})}),y.jsx(EVe,{selectedModel:M,onSelect:ue,language:n}),y.jsx(SVe,{selectedSize:A,onSelect:z,modelId:M,language:n}),y.jsx("div",{className:"ai-input-bar__bottom-spacer"}),y.jsx("button",{className:`ai-input-bar__send-btn ${je?"active":""} ${S?"loading":""}`,onMouseDown:_e=>{_e.preventDefault(),_e.stopPropagation()},onClick:Re,disabled:!je||S,"data-track":"ai_input_click_send",children:y.jsx(lNe,{size:18})})]}),y.jsxs("div",{className:Le("ai-input-bar__input-area",{"ai-input-bar__input-area--expanded":O}),children:[Y.length>0&&y.jsx("div",{className:"ai-input-bar__content-preview",children:y.jsx(_ne,{items:Y,language:n,enableHoverPreview:!0,onRemove:ie,removableStartIndex:_.length})}),y.jsx(kVe,{onSelectPrompt:me,language:n}),y.jsxs("div",{className:"ai-input-bar__rich-input",children:[y.jsx("textarea",{ref:de,className:Le("ai-input-bar__input",{"ai-input-bar__input--focused":O}),value:g,onChange:ye,onKeyDown:et,onFocus:gt,onBlur:Ye,placeholder:n==="zh"?"描述你想要创建什么,输入 @ 选择模型":"Describe what you want to create, type @ to select model",rows:O?4:1,disabled:S}),G&&Te.length>0&&y.jsxs("div",{className:"ai-input-bar__at-suggestion",ref:V,role:"listbox","aria-label":n==="zh"?"选择模型":"Select Model",children:[y.jsx("div",{className:"ai-input-bar__at-suggestion-header",children:n==="zh"?"选择图片模型":"Select Image Model"}),y.jsx("div",{className:"ai-input-bar__at-suggestion-list",children:Te.map((_e,We)=>{const Se=We===H,pe=_e.id===M;return y.jsxs("div",{className:Le("ai-input-bar__at-suggestion-item",{"ai-input-bar__at-suggestion-item--highlighted":Se,"ai-input-bar__at-suggestion-item--selected":pe}),onClick:()=>Ne(_e.id),onMouseEnter:()=>L(We),role:"option","aria-selected":pe,children:[y.jsxs("div",{className:"ai-input-bar__at-suggestion-item-content",children:[y.jsxs("div",{className:"ai-input-bar__at-suggestion-item-name",children:[y.jsxs("span",{className:"ai-input-bar__at-suggestion-item-code",children:["@",_e.shortCode]}),y.jsx("span",{className:"ai-input-bar__at-suggestion-item-label",children:_e.shortLabel||_e.label}),_e.isVip&&y.jsx("span",{className:"ai-input-bar__at-suggestion-item-vip",children:"VIP"})]}),_e.description&&y.jsx("div",{className:"ai-input-bar__at-suggestion-item-desc",children:_e.description})]}),pe&&y.jsx(rg,{size:16,className:"ai-input-bar__at-suggestion-item-check"})]},_e.id)})})]})]})]})]})]})});zne.displayName="AIInputBar";const tUe=()=>{var o;const[e,t]=x.useState(null),[n,r]=x.useState(!1),{activeTasks:i}=wS();x.useEffect(()=>{const a=async l=>{var d;const c=l,u=(d=c.detail)==null?void 0:d.version;try{const f=await fetch(`/version.json?t=${Date.now()}`);if(f.ok){const h=await f.json();if(!u||h.version===u){t(h);return}}}catch(f){console.warn("Failed to fetch version.json:",f)}t(c.detail)};return window.addEventListener("sw-update-available",a),()=>{window.removeEventListener("sw-update-available",a)}},[]);const s=()=>{t(null),r(!1),window.dispatchEvent(new CustomEvent("user-confirmed-upgrade"))};return!e||i.length>0?null:y.jsxs(y.Fragment,{children:[y.jsx("div",{className:"version-update-prompt",children:y.jsxs("div",{className:"version-update-prompt__content",children:[y.jsxs("span",{className:"version-update-prompt__text",children:["新版本 v",e.version," 已就绪"]}),e.changelog&&e.changelog.length>0&&y.jsx(tn,{theme:"default",variant:"text",size:"small",onClick:()=>r(!0),children:"查看更新内容"}),y.jsx(tn,{theme:"primary",size:"small",onClick:s,icon:y.jsx(ch,{}),children:"立即更新"})]})}),y.jsx(Jo,{header:`新版本 v${e.version} 更新内容`,visible:n,onClose:()=>r(!1),width:600,footer:y.jsx(tn,{theme:"primary",onClick:s,children:"立即更新"}),children:y.jsx("div",{style:{maxHeight:"400px",overflowY:"auto",paddingRight:"8px"},children:y.jsx("ul",{style:{paddingLeft:"20px",margin:0},children:(o=e.changelog)==null?void 0:o.map((a,l)=>y.jsxs("li",{style:{marginBottom:"4px",lineHeight:"1.5"},children:[l+1,". ",a]},l))})})})]})},nUe=.75,rUe=.9,iUe=6e4;class sUe{constructor(){this.checkTimer=null,this.cleanupHandlers=[],this.lastCleanupTime=0,this.cleanupCooldown=6e4}getMemoryStats(){const t=performance;if(!t.memory)return null;const{usedJSHeapSize:n,totalJSHeapSize:r,jsHeapSizeLimit:i}=t.memory,s=n/i*100;return{usedJSHeapSize:n,totalJSHeapSize:r,jsHeapSizeLimit:i,usagePercent:s,isUnderPressure:s>nUe*100,formatted:{used:this.formatBytes(n),total:this.formatBytes(r),limit:this.formatBytes(i)}}}formatBytes(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/1024/1024).toFixed(1)} MB`:`${(t/1024/1024/1024).toFixed(2)} GB`}registerCleanupHandler(t){this.cleanupHandlers.push(t),this.cleanupHandlers.sort((n,r)=>n.priority-r.priority)}unregisterCleanupHandler(t){this.cleanupHandlers=this.cleanupHandlers.filter(n=>n.name!==t)}async triggerCleanup(t=!1){const n=Date.now();if(!t&&n-this.lastCleanupTime<this.cleanupCooldown){console.log("[MemoryMonitor] Cleanup skipped (cooldown)");return}console.log("[MemoryMonitor] Starting memory cleanup..."),this.lastCleanupTime=n;const r=this.getMemoryStats();for(const s of this.cleanupHandlers)try{console.log(`[MemoryMonitor] Running cleanup: ${s.name}`),await s.cleanup()}catch(o){console.error(`[MemoryMonitor] Cleanup failed: ${s.name}`,o)}typeof globalThis.gc=="function"&&globalThis.gc();const i=this.getMemoryStats();if(r&&i){const s=r.usedJSHeapSize-i.usedJSHeapSize;console.log(`[MemoryMonitor] Cleanup complete. Freed: ${this.formatBytes(s)}`)}}checkMemory(){const t=this.getMemoryStats();if(t){if(t.usagePercent>rUe*100){console.warn(`[MemoryMonitor] Critical memory pressure: ${t.usagePercent.toFixed(1)}%`),this.triggerCleanup(!0);return}t.isUnderPressure&&(console.warn(`[MemoryMonitor] Memory pressure: ${t.usagePercent.toFixed(1)}%`),this.triggerCleanup())}}start(){if(this.checkTimer)return;if(!this.getMemoryStats()){console.log("[MemoryMonitor] Memory API not available");return}console.log("[MemoryMonitor] Starting memory monitor"),this.checkTimer=setInterval(()=>this.checkMemory(),iUe),this.checkMemory()}stop(){this.checkTimer&&(clearInterval(this.checkTimer),this.checkTimer=null,console.log("[MemoryMonitor] Memory monitor stopped"))}logMemoryStatus(){const t=this.getMemoryStats();if(!t){console.log("[MemoryMonitor] Memory API not available");return}console.log("[MemoryMonitor] Memory Status:",{used:t.formatted.used,total:t.formatted.total,limit:t.formatted.limit,usage:`${t.usagePercent.toFixed(1)}%`,pressure:t.isUnderPressure?"YES":"NO"})}}const SC=new sUe;SC.registerCleanupHandler({name:"idle-gc-hint",priority:10,cleanup:async()=>new Promise(e=>{"requestIdleCallback"in window?window.requestIdleCallback(()=>{e()},{timeout:1e3}):setTimeout(e,0)})});const uH="drawnix_performance_panel_settings",dH={x:-1,y:-1},fH=60,oUe=80,aUe=({container:e,onCreateProject:t})=>{const{language:n}=jn(),[r,i]=x.useState(null),[s,o]=x.useState(()=>{try{const A=localStorage.getItem(uH);if(A){const z=JSON.parse(A);return{position:z.position||dH,pinned:z.pinned||!1}}}catch{}return{position:dH,pinned:!1}}),[a,l]=x.useState({dismissed:!1}),[c,u]=x.useState(!1),[d,f]=x.useState({x:0,y:0}),h=x.useRef(null),m=x.useRef(null),g=x.useCallback(A=>{o(z=>{const G={...z,...A};try{localStorage.setItem(uH,JSON.stringify(G))}catch{}return G})},[]),w=x.useCallback(()=>{const A=SC.getMemoryStats();i(A)},[]);x.useEffect(()=>(w(),m.current=setInterval(w,5e3),()=>{m.current&&clearInterval(m.current)}),[w]);const C=x.useMemo(()=>r?s.pinned?!0:a.dismissed?!1:r.usagePercent>=fH:!1,[r,s.pinned,a.dismissed]),b=x.useMemo(()=>r?r.usagePercent>=oUe?"critical":r.usagePercent>=fH?"warning":"normal":"normal",[r]),_=x.useMemo(()=>{const A={zIndex:ma.PERFORMANCE_PANEL};return s.position.x>=0&&s.position.y>=0&&(A.left=s.position.x,A.top=s.position.y,A.right="auto",A.bottom="auto"),A},[s.position]),T=x.useCallback(A=>{if(!h.current)return;A.preventDefault(),A.stopPropagation();const z=h.current.getBoundingClientRect();f({x:A.clientX-z.left,y:A.clientY-z.top}),u(!0),A.target.setPointerCapture(A.pointerId)},[]),S=x.useCallback(A=>{var j,H;if(!c)return;A.preventDefault();const z=A.clientX-d.x,G=A.clientY-d.y,W=window.innerWidth-(((j=h.current)==null?void 0:j.offsetWidth)||60),K=window.innerHeight-(((H=h.current)==null?void 0:H.offsetHeight)||200);g({position:{x:Math.max(0,Math.min(z,W)),y:Math.max(0,Math.min(G,K))}})},[c,d,g]),k=x.useCallback(A=>{c&&(u(!1),A.target.releasePointerCapture(A.pointerId))},[c]),D=x.useCallback(()=>{g({pinned:!s.pinned})},[s.pinned,g]),O=x.useCallback(()=>{l({dismissed:!0})},[]),I=x.useCallback(()=>{window.location.reload()},[]),[R,F]=x.useState(!1),M=x.useCallback(async()=>{if(!(R||!t)){F(!0);try{await t()}catch(A){console.error("[PerformancePanel] Failed to create project:",A)}finally{F(!1)}}},[R,t]);if(!C)return null;const $=y.jsxs("div",{className:"performance-panel__tooltip",children:[y.jsx("div",{className:"performance-panel__tooltip-title",children:n==="zh"?"内存使用情况":"Memory Usage"}),y.jsxs("div",{className:"performance-panel__tooltip-content",children:[y.jsxs("div",{children:[n==="zh"?"已使用":"Used",": ",r==null?void 0:r.formatted.used]}),y.jsxs("div",{children:[n==="zh"?"总计":"Total",": ",r==null?void 0:r.formatted.total]}),y.jsxs("div",{children:[n==="zh"?"限制":"Limit",": ",r==null?void 0:r.formatted.limit]})]}),y.jsx("div",{className:"performance-panel__tooltip-tip",children:n==="zh"?`➕ 新建项目可释放当前画布内存
2063
2063
  🔄 刷新页面完全释放内存`:`➕ New project frees current canvas memory
2064
- 🔄 Refresh page fully releases memory`})]});return y.jsxs("div",{ref:h,className:`performance-panel performance-panel--${b} ${c?"performance-panel--dragging":""}`,style:_,children:[y.jsx("div",{className:"performance-panel__drag-handle",onPointerDown:T,onPointerMove:S,onPointerUp:k,onPointerCancel:k,title:n==="zh"?"拖拽移动":"Drag to move",children:y.jsx(qte,{})}),y.jsx(Di,{content:$,placement:"left",theme:"light",children:y.jsxs("div",{className:"performance-panel__content",children:[y.jsx("div",{className:"performance-panel__icon",children:b==="critical"?"🔴":"🟠"}),y.jsxs("div",{className:"performance-panel__value",children:[r==null?void 0:r.usagePercent.toFixed(0),"%"]})]})}),y.jsx("div",{className:"performance-panel__divider"}),t&&y.jsx("button",{className:"performance-panel__btn",onClick:M,disabled:R,title:n==="zh"?"新建项目":"New project",children:y.jsx(dy,{})}),y.jsx(DJ,{content:n==="zh"?"刷新页面可释放内存":"Refresh to free memory",confirmBtn:n==="zh"?"刷新":"Refresh",cancelBtn:n==="zh"?"取消":"Cancel",onConfirm:I,placement:"left",theme:"default",children:y.jsx("button",{className:"performance-panel__btn",title:n==="zh"?"刷新页面":"Refresh page",children:y.jsx(ch,{})})}),y.jsx("div",{className:"performance-panel__divider"}),y.jsx("button",{className:`performance-panel__btn ${s.pinned?"performance-panel__btn--active":""}`,onClick:D,title:s.pinned?n==="zh"?"取消常驻":"Unpin":n==="zh"?"常驻":"Pin",children:s.pinned?y.jsx(Yte,{}):y.jsx(Zte,{})}),y.jsx("button",{className:"performance-panel__btn",onClick:O,title:n==="zh"?"关闭":"Close",children:y.jsx(CS,{})})]})},lUe=({position:e,visible:t,onClose:n})=>{const r=Hr(),{t:i}=jn(),s=y3(),o=Q.getBoardContainer(r),[a,l]=x.useState({freehand:!1,arrow:!1,shape:!1}),[c,u]=x.useState(!1),{refs:d,floatingStyles:f}=Z1({placement:"bottom",middleware:[VE(12),e5({padding:16}),UE({fallbackPlacements:["top","right","left"]})]});x.useEffect(()=>{if(e&&t){const[I,R]=e;d.setPositionReference({getBoundingClientRect(){return{width:1,height:1,x:I,y:R,top:R,left:I,right:I+1,bottom:R+1}}})}},[e,t,d]),x.useEffect(()=>{if(!t)return;const I=F=>{const M=F.target,$=M.closest(".quick-creation-toolbar"),A=M.closest(".quick-toolbar-popover")||M.closest("[data-radix-popper-content-wrapper]")||M.closest(".plait-popover")||M.closest(".shape-picker")||M.closest(".arrow-picker")||M.closest(".freehand-panel"),z=M.closest(".media-library-modal");!$&&!A&&!z&&n()},R=setTimeout(()=>{document.addEventListener("mousedown",I)},100);return()=>{clearTimeout(R),document.removeEventListener("mousedown",I)}},[t,n]);const h=()=>{l({freehand:!1,arrow:!1,shape:!1})},m=I=>{l({freehand:!1,arrow:!1,shape:!1,[I]:!0})},g=()=>{h(),fu(r),li(r,Ar.drawing),$t.updatePointerType(r,yt.text),s(yt.text),n()},w=()=>{h(),u(!0)},C=()=>{h(),mS(r),n()},b=async I=>{try{I.type===Kr.IMAGE?await wm(r,I.url):I.type===Kr.VIDEO&&await lh(r,I.url),xt.success(i("toolbar.assetInserted")||"素材已插入到画板"),u(!1),n()}catch(R){console.error("Failed to insert asset:",R),xt.error(i("toolbar.assetInsertFailed")||"插入素材失败")}},[_,T]=x.useState(Jr.feltTipPen),S=300,k=x.useRef(null),D=x.useCallback(()=>{k.current&&(clearTimeout(k.current),k.current=null)},[]);x.useEffect(()=>()=>{D()},[D]);const O=(I,R,F,M)=>y.jsxs(ti,{open:a[R],sideOffset:12,onOpenChange:$=>{$||h()},placement:"bottom",children:[y.jsx(ni,{asChild:!0,children:y.jsx("div",{onPointerEnter:()=>{D(),k.current=setTimeout(()=>{m(R)},S)},onPointerLeave:()=>{D()},children:y.jsx(jt,{type:"icon",visible:!0,selected:a[R],icon:I,title:"","aria-label":F,"data-track":`quick_toolbar_click_${R}`,onPointerDown:()=>{D(),m(R),fu(r),R==="freehand"&&(li(r,Ar.dnd),$t.updatePointerType(r,_),s(_))},onPointerUp:()=>{R==="freehand"&&li(r,Ar.drawing)}})})}),y.jsx(ri,{container:o,style:{zIndex:ma.POPOVER},className:"quick-toolbar-popover",children:M})]});return t?y.jsxs(y.Fragment,{children:[y.jsx(xr,{padding:1,className:`quick-creation-toolbar ${vi}`,ref:d.setFloating,style:f,children:y.jsxs(Mr.Row,{gap:1,children:[y.jsx(jt,{type:"icon",visible:!0,icon:WO,title:"","aria-label":i("toolbar.text"),"data-track":"quick_toolbar_click_text",onPointerUp:g}),y.jsx(jt,{type:"icon",visible:!0,icon:KO,title:"","aria-label":i("toolbar.image"),"data-track":"quick_toolbar_click_image",onPointerUp:C}),y.jsx(jt,{type:"icon",visible:!0,icon:qO,title:"","aria-label":i("toolbar.mediaLibrary"),"data-track":"quick_toolbar_click_media_library",onPointerUp:w}),O(xm,"freehand",i("toolbar.pen"),y.jsx(S3,{onPointerUp:I=>{h(),T(I),$t.updatePointerType(r,I),s(I),n()}})),O(GO,"arrow",i("toolbar.arrow"),y.jsx(T3,{onPointerUp:I=>{h(),$t.updatePointerType(r,I),s(I),n()}})),O(HO,"shape",i("toolbar.shape"),y.jsx(_3,{onPointerUp:I=>{h(),$t.updatePointerType(r,I),s(I),n()}}))]})}),y.jsx(dS,{isOpen:c,onClose:()=>{u(!1)},mode:ym.SELECT,onSelect:b,selectButtonText:i("toolbar.insert")||"插入"})]}):null},cUe=({children:e,onOpenMediaLibrary:t})=>{const[n,r]=x.useState(!1),i=x.useCallback(()=>{if(!n){r(!0);const s=I8e.confirm({header:"缓存空间已满",body:"图片缓存空间已满,无法继续缓存新图片。是否打开素材库清理缓存?",theme:"warning",confirmBtn:"打开素材库",cancelBtn:"稍后处理",onConfirm:()=>{r(!1),t==null||t(),s.hide()},onCancel:()=>{r(!1),s.hide()},onClose:()=>{r(!1)}})}},[n,t]);return wze(i),y.jsx(y.Fragment,{children:e})},_C={visible:!1,position:{x:0,y:0},sourceElement:null,currentShape:null,hitIndex:-1,hitPoint:null,mode:"hover",arrowLineElement:null,arrowLineEndPoint:null},Hne=new WeakMap,nD=new WeakMap;function TC(e){return Hne.get(e)||_C}function V0(e,t){Hne.set(e,t);const n=nD.get(e);n&&n(t)}function uUe(e,t){return nD.set(e,t),()=>{nD.delete(e)}}function F3(e){V0(e,_C)}const T0=100;function dUe(e,t,n,r,i){const s=cU(n),o=X.getRectangleByPoints(t.points),a=o.width,l=o.height,c=o.x+a/2,u=o.y+l/2,f=X.getEdgeCenterPoints(o)[n];let h,m;switch(s){case zt.right:h=c+a/2+T0+a/2,m=u;break;case zt.bottom:h=c,m=u+l/2+T0+l/2;break;case zt.left:h=c-a/2-T0-a/2,m=u;break;case zt.top:h=c,m=u-l/2-T0-l/2;break;default:h=c+a/2+T0+a/2,m=u}const g=[[h-a/2,m-l/2],[h+a/2,m+l/2]],w=gd(e,g,i);if(w.fill="#ffffff",be.isShapeElement(t)&&!be.isText(t)){const F=t;F.angle!==void 0&&(w.angle=F.angle),F.fill&&F.fill!=="none"&&(w.fill=F.fill),F.strokeColor!==void 0&&(w.strokeColor=F.strokeColor),F.strokeStyle!==void 0&&(w.strokeStyle=F.strokeStyle),F.strokeWidth!==void 0&&(w.strokeWidth=F.strokeWidth)}const C=ua(f,t)||f,b=be.isShapeElement(t)?Wl(e,C,t):void 0;let _;switch(s){case zt.right:_=3;break;case zt.bottom:_=0;break;case zt.left:_=1;break;case zt.top:_=2;break;default:_=3}const T=X.getRectangleByPoints(w.points),k=X.getEdgeCenterPoints(T)[_],D=ua(k,w)||k,O=Wl(e,D,w),I=WI(Gn.straight,[C,D],{marker:Ur.none,connection:b,boundId:t.id},{marker:Ur.arrow,connection:O,boundId:w.id},[],{});Ke.insertNode(e,I,[e.children.length]),da(e,w),F3(e);const R=w.id;setTimeout(()=>{const F=e.children.findIndex($=>$.id===R),M=F>=0?e.children[F]:null;M&&(aa(e),ya(e,M),$t.updatePointerType(e,fn.selection),Ke.setNode(e,{_forceRender:Date.now()},[F]),Ke.setNode(e,{_forceRender:void 0},[F]))},50)}function fUe(e,t,n,r){var m;let i=100,s=100;const o=t,a=(m=o.source)==null?void 0:m.boundId;if(a){const g=e.children.find(w=>w.id===a);if(g&&be.isShapeElement(g)){const w=X.getRectangleByPoints(g.points);i=w.width,s=w.height}}const l=[[n[0]-i/2,n[1]-s/2],[n[0]+i/2,n[1]+s/2]],c=gd(e,l,r);c.fill="#ffffff";const u=X.getRectangleByPoints(c.points),d=X.getEdgeCenterPoints(u),f=o.points||[];if(f.length>=2){const g=f[0],w=f[f.length-1],C=w[0]-g[0],b=w[1]-g[1];let _;Math.abs(C)>Math.abs(b)?_=C>0?3:1:_=b>0?0:2;const T=d[_],S=Wl(e,T,c),k=e.children.findIndex(D=>D.id===t.id);k!==-1&&Ke.setNode(e,{target:{marker:Ur.arrow,connection:S,boundId:c.id},points:[g,T]},[k])}da(e,c),F3(e);const h=c.id;setTimeout(()=>{const g=e.children.findIndex(C=>C.id===h),w=g>=0?e.children[g]:null;w&&(aa(e),ya(e,w),$t.updatePointerType(e,fn.selection),Ke.setNode(e,{_forceRender:Date.now()},[g]),Ke.setNode(e,{_forceRender:void 0},[g]))},50)}const hUe=e=>{const{pointerMove:t,pointerLeave:n,globalPointerUp:r}=e;let i=null,s=-1,o=e.children.length,a={x:0,y:0};return e.pointerMove=l=>{a={x:l.clientX,y:l.clientY},i&&(clearTimeout(i),i=null);const c=_g(e),u=c.length===1&&c[0],d=TC(e);if(!u||!be.isShapeElement(u)||be.isText(u)){d.visible&&d.mode==="hover"&&V0(e,{..._C}),s=-1,t(l);return}const f=hd(e,l.x,l.y),h=H1(e,u,!0),m=Hl(e,f,u,!0)||f,g=bE(m,h),w=h[g];if(w){if(g!==s||!d.visible){s=g;const C=l.clientX,b=l.clientY;i=setTimeout(()=>{const _=be.isImage(u)?yt.rectangle:u.shape||yt.rectangle;V0(e,{visible:!0,position:{x:C-140,y:b+20},sourceElement:u,currentShape:_,hitIndex:g,hitPoint:w,mode:"hover"})},50)}}else s=-1,d.visible&&d.mode==="hover"&&(i=setTimeout(()=>{const C=TC(e);C.visible&&C.mode==="hover"&&V0(e,{..._C})},300));t(l)},e.pointerLeave=l=>{i&&(clearTimeout(i),i=null),n(l)},e.globalPointerUp=l=>{var u;r(l);const c=e.children.length;if(c>o){const d=e.children[c-1];if(be.isArrowLine(d)){const f=d;if(!((u=f.target)==null?void 0:u.boundId)){const m=f.points||[];if(m.length>=2){const g=m[m.length-1];setTimeout(()=>{V0(e,{visible:!0,position:{x:a.x-140,y:a.y+20},sourceElement:null,currentShape:yt.rectangle,hitIndex:-1,hitPoint:null,mode:"arrowLine",arrowLineElement:d,arrowLineEndPoint:g})},50)}}}}o=e.children.length},e},pUe=[{icon:aY,title:"Rectangle",pointer:yt.rectangle},{icon:cY,title:"Ellipse",pointer:yt.ellipse},{icon:uY,title:"Triangle",pointer:yt.triangle},{icon:lY,title:"Terminal",pointer:Bt.terminal},{icon:dY,title:"Diamond",pointer:yt.diamond},{icon:fY,title:"Parallelogram",pointer:yt.parallelogram},{icon:hY,title:"RoundRectangle",pointer:yt.roundRectangle}],gUe=({visible:e,position:t,currentShape:n,onSelectShape:r,onClose:i,container:s})=>{const o=x.useRef(null);x.useEffect(()=>{if(!e)return;const f=g=>{o.current&&!o.current.contains(g.target)&&i()},h=g=>{g.key==="Escape"&&i()},m=setTimeout(()=>{document.addEventListener("mousedown",f),document.addEventListener("keydown",h)},50);return()=>{clearTimeout(m),document.removeEventListener("mousedown",f),document.removeEventListener("keydown",h)}},[e,i]);const a=x.useCallback(f=>{r(f)},[r]);if(!e)return null;const l={x:isNaN(t.x)?0:t.x,y:isNaN(t.y)?0:t.y},c=200,u=80;typeof window<"u"&&(l.x+c>window.innerWidth&&(l.x=window.innerWidth-c-10),l.y+u>window.innerHeight&&(l.y=t.y-u-20));const d=y.jsx("div",{ref:o,className:Le("auto-complete-shape-picker",vi),style:{left:l.x,top:l.y},children:y.jsx(xr,{padding:1,children:y.jsx(Mr.Col,{gap:1,children:y.jsx(Mr.Row,{gap:1,children:pUe.map((f,h)=>y.jsx(jt,{className:Le("shape-button",{"is-current":n===f.pointer}),type:"icon",size:"small",visible:!0,icon:f.icon,title:f.title,"aria-label":f.title,onPointerDown:({event:m})=>{m.stopPropagation(),a(f.pointer)}},h))})})})});return s?Mo.createPortal(d,s):d},mUe={visible:!1,position:{x:0,y:0},sourceElement:null,currentShape:null,hitIndex:-1,hitPoint:null,mode:"hover"};function vUe(e){const[t,n]=x.useState(mUe);x.useEffect(()=>{if(!e)return;n(TC(e));const s=uUe(e,o=>{n(o)});return()=>{s()}},[e]);const r=x.useCallback(s=>{if(!e)return;const o=TC(e);o.mode==="arrowLine"?o.arrowLineElement&&o.arrowLineEndPoint&&fUe(e,o.arrowLineElement,o.arrowLineEndPoint,s):o.sourceElement&&o.hitPoint&&o.hitIndex>=0&&dUe(e,o.sourceElement,o.hitIndex,o.hitPoint,s)},[e]),i=x.useCallback(()=>{e&&F3(e)},[e]);return{state:t,selectShape:r,closePicker:i}}const yUe="#ffffff",wUe=[yt.rectangle,yt.ellipse,yt.triangle,yt.diamond,yt.parallelogram,yt.roundRectangle];function hH(e){if(!be.isGeometry(e)||be.isText(e)||be.isImage(e))return!1;const t=e;return!(!t.shape||!wUe.includes(t.shape)||t.fill&&t.fill!=="none")}const xUe=e=>{const{afterChange:t}=e,n=new Set;return e.afterChange=()=>{t();const r=[];e.children.forEach((i,s)=>{hH(i)&&!n.has(i.id)&&(r.push({path:[s],element:i}),n.add(i.id))}),r.length>0&&setTimeout(()=>{r.forEach(({path:i})=>{const s=e.children[i[0]];s&&hH(s)&&Ke.setNode(e,{fill:yUe},i)})},0)},e},kC=new WeakMap;let ak=null,Sc=null;function Wne(e,t){try{const n=_n.getElementG(t);if(n)return n}catch{}if(t!=null&&t.id){const n=Q.getElementHost(e);if(n){const r=n.querySelector(`g[id="${t.id}"]`);if(r)return r}}return null}function Gne(e){return e.querySelector("path, rect, ellipse, polygon, circle")}function Vne(e){let t=e.querySelector("defs");return t||(t=RSe(),e.insertBefore(t,e.firstChild)),t}function bUe(e,t){const n=kC.get(t);if(n){const r=e.querySelector(`#${n}`);r&&r.remove()}}function PC(e,t,n){const r=Wne(e,t);if(!r)return;const i=Gne(r);if(!i)return;const s=r.closest("svg");if(!s)return;const o=Et(e,[t],!1),a=(o==null?void 0:o.width)||100,l=(o==null?void 0:o.height)||100,c=NX(n,t.id,a,l),u=Vne(s);if(c.defElement){const d=c.defElement.id,f=u.querySelector(`#${d}`);f?f.replaceWith(c.defElement):u.appendChild(c.defElement),i.setAttribute("fill",c.fillValue),kC.set(t,d);const h=kC.get(t);if(h&&h!==d){const m=u.querySelector(`#${h}`);m&&m.remove()}}else i.setAttribute("fill",c.fillValue),bUe(s,t)}function sb(e,t){return e.children.find(n=>n.id===t)||null}function Hc(e){const t=e.fillConfig;return t&&is(t)?t:e.fill&&is(e.fill)?e.fill:null}function Une(e,t){if(!e)return!1;if(e==="[object Object]")return!0;if(e.startsWith("url(#")){const n=e.match(/url\(#([^)]+)\)/);if(n){const r=n[1];if(!document.getElementById(r))return!0}return!1}if(t){const n=Hc(t);if(n&&(n.type==="gradient"||n.type==="image"))return!0}return!1}function CUe(e){if(!Sc)return;const t=new Set;e.forEach(n=>{if(n.type==="attributes"&&n.attributeName==="fill"){const r=n.target,i=r.getAttribute("fill"),s=r.closest("g[id]");if(s){const o=s.getAttribute("id");if(o){const a=sb(Sc,o),l=a?Hc(a):null;a&&l&&sa(Sc,a)&&Une(i,a)&&t.add(a)}}}n.type==="childList"&&n.addedNodes.forEach(r=>{if(r instanceof SVGGElement&&r.hasAttribute("id")){const i=r.getAttribute("id");if(i){const s=sb(Sc,i),o=s?Hc(s):null;s&&o&&sa(Sc,s)&&t.add(s)}}if(r instanceof Element){const i=r.closest("g[id]");if(i){const s=i.getAttribute("id");if(s){const o=sb(Sc,s),a=o?Hc(o):null;o&&a&&sa(Sc,o)&&t.add(o)}}}})}),t.size>0&&t.forEach(n=>{const r=Hc(n);r&&PC(Sc,n,r)})}function EUe(e){if(ak)return;const t=Q.getElementHost(e);t&&(Sc=e,ak=new MutationObserver(CUe),ak.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["fill"]}))}function SUe(e){const t=Q.getElementHost(e);if(!t)return;t.querySelectorAll("path[fill], rect[fill], ellipse[fill], polygon[fill], circle[fill]").forEach(r=>{const i=r.getAttribute("fill"),s=r.closest("g[id]");if(s){const o=s.getAttribute("id");if(o){const a=sb(e,o),l=a?Hc(a):null;a&&l&&sa(e,a)&&Une(i,a)&&PC(e,a,l)}}})}function rD(e,t=!1){e.children.forEach(n=>{const r=Hc(n);r&&sa(e,n)&&(t?PC(e,n,r):requestAnimationFrame(()=>{PC(e,n,r)}))}),t&&SUe(e)}let pH=!0;const gH=new WeakSet;function Kne(e){const t=Q.getElementHost(e);if(!t)return;const n=t.closest("svg")||t.querySelector("svg");n&&e.children.forEach(r=>{const i=Hc(r);if(i&&(i.type==="gradient"||i.type==="image")&&sa(e,r)){const s=Et(e,[r],!1),o=(s==null?void 0:s.width)||100,a=(s==null?void 0:s.height)||100,l=NX(i,r.id,o,a);if(l.defElement){const c=Vne(n);c.querySelector(`#${l.defElement.id}`)||(c.appendChild(l.defElement),kC.set(r,l.defElement.id))}}})}function _Ue(e){let t=0;return e.children.forEach(n=>{const r=Hc(n);if(r&&(r.type==="gradient"||r.type==="image")&&sa(e,n)){const i=Wne(e,n);(i?Gne(i):null)||t++}}),t}function TUe(e){if(gH.has(e))return;gH.add(e);const t=15,n=16;let r=0;const i=()=>{r++;try{if(!Q.getElementHost(e))return;if(Kne(e),rD(e,!0),_Ue(e)>0&&r<t){const a=Math.min(n*Math.pow(1.5,r),500);setTimeout(i,a)}}catch{}};requestAnimationFrame(()=>{i(),setTimeout(i,0)})}const kUe=e=>{const{afterChange:t}=e;return e.afterChange=()=>{t(),EUe(e),Kne(e),pH?(pH=!1,rD(e,!0),TUe(e)):rD(e,!0)},e},PUe=x.lazy(()=>ln(()=>import("./ttd-dialog-WN-s4x87.js"),__vite__mapDeps([10,11,12,13,14,15,16]),import.meta.url).then(e=>({default:e.TTDDialog}))),AUe=x.lazy(()=>ln(()=>import("./settings-dialog-aU8BHcuS.js"),__vite__mapDeps([17,11,12,13,14,16]),import.meta.url).then(e=>({default:e.SettingsDialog}))),DUe=x.lazy(()=>ln(()=>import("./index-DvbaH1wH.js"),__vite__mapDeps([18,19,20]),import.meta.url).then(e=>({default:e.ProjectDrawer}))),IUe=x.lazy(()=>ln(()=>import("./ToolboxDrawer-D-ZDs49h.js"),__vite__mapDeps([21,2,13,22,12,11,14,23]),import.meta.url).then(e=>({default:e.ToolboxDrawer}))),OUe=x.lazy(()=>ln(()=>Promise.resolve().then(()=>tre),void 0,import.meta.url).then(e=>({default:e.MediaLibraryModal}))),MUe=x.lazy(()=>ln(()=>import("./index-DCs3C-gs.js"),__vite__mapDeps([24,19,25]),import.meta.url).then(e=>({default:e.BackupRestoreDialog}))),RUe=({value:e,viewport:t,theme:n,onChange:r,onSelectionChange:i,onViewportChange:s,onThemeChange:o,onValueChange:a,afterInit:l,onBoardSwitch:c,isDataReady:u=!1})=>{const d={readonly:!1,hideScrollbar:!1,disabledScrollOnNonFocus:!1,themeColors:Vbe},[f,h]=x.useState(()=>{const ae=new MEe(window.navigator.userAgent);return{pointer:fn.hand,isMobile:ae.mobile()!==null,isPencilMode:!1,openDialogType:null,dialogInitialData:null,openCleanConfirm:!1,openSettings:!1}}),[m,g]=x.useState(null),[w,C]=x.useState(!1),[b,_]=x.useState(!1),[T,S]=x.useState(!1),[k,D]=x.useState(!1),[O,I]=x.useState(!1),R=x.useRef(null),F=x.useCallback(()=>{C(!1),_(!1),S(!1),D(!1)},[]),M=x.useCallback(()=>{C(ae=>(ae||F(),!ae))},[F]),$=x.useCallback(()=>{_(ae=>(ae||F(),!ae))},[F]),A=x.useCallback(()=>{S(ae=>(ae||F(),!ae))},[F]),z=x.useCallback(()=>{F(),D(!0)},[F]),G=x.useCallback(ae=>{h(ae)},[]),W=x.useCallback(ae=>{h(de=>({...de,...ae}))},[]);x.useEffect(()=>{m&&(m.appState=f,R.current=m)},[m,f]),x.useEffect(()=>CVe(),[]),x.useEffect(()=>{e&&e.length>0&&zp.preloadBoardFonts(e).then(()=>{}).catch(ae=>{console.warn("Failed to preload board fonts:",ae)})},[e]),x.useEffect(()=>{m&&ln(async()=>{const{initVideoRecoveryService:ae}=await import("./video-recovery-service-Zb_336FQ.js");return{initVideoRecoveryService:ae}},[],import.meta.url).then(({initVideoRecoveryService:ae})=>{ae(m)})},[m]),x.useEffect(()=>{const ae=de=>{const oe=de,{message:ee}=oe.detail;xt.error({content:"API Key 无效或已过期,请重新配置",duration:5e3}),console.error("[Drawnix] API auth error:",ee),h(ce=>({...ce,openSettings:!0}))};return window.addEventListener(OA,ae),()=>{window.removeEventListener(OA,ae)}},[]),x.useEffect(()=>{m&&e&&e.length>0&&(async()=>{const{WorkZoneTransforms:de}=await ln(async()=>{const{WorkZoneTransforms:ue}=await Promise.resolve().then(()=>o$);return{WorkZoneTransforms:ue}},void 0,import.meta.url),{shouldUseSWTaskQueue:oe}=await ln(async()=>{const{shouldUseSWTaskQueue:ue}=await Promise.resolve().then(()=>U9);return{shouldUseSWTaskQueue:ue}},void 0,import.meta.url),{TaskStatus:ee}=await ln(async()=>{const{TaskStatus:ue}=await Promise.resolve().then(()=>CNe);return{TaskStatus:ue}},void 0,import.meta.url);if(oe()){const{swTaskQueueService:ue}=await ln(async()=>{const{swTaskQueueService:Te}=await Promise.resolve().then(()=>g3);return{swTaskQueueService:Te}},void 0,import.meta.url);await ue.initialize(),await ue.syncTasksFromSW()}const{chatWorkflowClient:ce}=await ln(async()=>{const{chatWorkflowClient:ue}=await Promise.resolve().then(()=>Uje);return{chatWorkflowClient:ue}},void 0,import.meta.url),me=await ce.getAllActiveWorkflows(),ve=new Set(me.map(ue=>ue.id)),{workflowSubmissionService:N}=await ln(async()=>{const{workflowSubmissionService:ue}=await Promise.resolve().then(()=>lH);return{workflowSubmissionService:ue}},void 0,import.meta.url),he=await N.queryAllWorkflows(),fe=new Set(he.map(ue=>ue.id)),{taskQueueService:ne}=await ln(async()=>{const{taskQueueService:ue}=await Promise.resolve().then(()=>U9);return{taskQueueService:ue}},void 0,import.meta.url),ie=de.getAllWorkZones(m);for(const ue of ie){const Te=he.find(Ye=>Ye.id===ue.workflow.id),De=ue.workflow.steps.some(Ye=>Ye.status==="running"||Ye.status==="pending");let ye={...ue.workflow,steps:[...ue.workflow.steps]};if(Te&&(Te.steps.length!==ye.steps.length||Te.status!==ye.status)&&(de.updateWorkflow(m,ue.id,{steps:Te.steps,status:Te.status,error:Te.error}),ye={...ye,steps:Te.steps,status:Te.status}),!De&&!Te)continue;const Ne=ve.has(ye.id),Re=fe.has(ye.id),He=Ne||Re,et=ye.steps.map(Ye=>{var _e,We;if(Ye.status!=="running"&&Ye.status!=="pending")return Ye;const je=(_e=Ye.result)==null?void 0:_e.taskId;if(!je)return Ye.mcp==="ai_analyze"?He?Ye:{...Ye,status:"failed",error:"页面刷新导致中断,请删除后重新发起"}:Ye.status==="running"?{...Ye,status:"failed",error:"页面刷新导致中断,请删除后重新发起"}:Ye;const Me=ne.getTask(je);if(!Me)return{...Ye,status:"failed",error:"任务未找到,请重试"};switch(Me.status){case ee.COMPLETED:return{...Ye,status:"completed",result:{taskId:je,result:Me.result}};case ee.FAILED:return{...Ye,status:"failed",error:((We=Me.error)==null?void 0:We.message)||"任务执行失败"};case ee.CANCELLED:return{...Ye,status:"skipped"};case ee.PENDING:case ee.PROCESSING:return Ye;default:return Ye}});et.some((Ye,je)=>{var Me;return Ye.status!==((Me=ye.steps[je])==null?void 0:Me.status)})&&de.updateWorkflow(m,ue.id,{steps:et})}})().catch(de=>{console.error("[Drawnix] Failed to restore WorkZones:",de)})},[m]),x.useEffect(()=>{if(!m)return;let ae=null;return(async()=>{const oe=await ln(()=>Promise.resolve().then(()=>lH),void 0,import.meta.url),{WorkZoneTransforms:ee}=await ln(async()=>{const{WorkZoneTransforms:me}=await Promise.resolve().then(()=>o$);return{WorkZoneTransforms:me}},void 0,import.meta.url),{workflowSubmissionService:ce}=oe;ae=ce.subscribeToAllEvents(me=>{const ve=me,he=ee.getAllWorkZones(m).find(fe=>fe.workflow.id===ve.workflowId);if(he)switch(ve.type){case"step":{const fe=he.workflow.steps.map(ne=>ne.id===ve.stepId?{...ne,status:ve.status||ne.status,result:ve.result??ne.result,error:ve.error??ne.error,duration:ve.duration??ne.duration}:ne);ee.updateWorkflow(m,he.id,{steps:fe});break}case"steps_added":{const fe=(ve.steps||[]).map(ne=>({id:ne.id,mcp:ne.mcp,args:ne.args,description:ne.description,status:ne.status}));ee.updateWorkflow(m,he.id,{steps:[...he.workflow.steps,...fe]});break}case"completed":case"failed":{const fe=ve.type==="completed"?"completed":"failed",ne=he.workflow.steps.map(ie=>{if(ie.status==="running"||ie.status==="pending"){const ue=ie.result;return ue!=null&&ue.taskId?ie:{...ie,status:fe,error:ve.type==="failed"?ve.error:void 0}}return ie});ee.updateWorkflow(m,he.id,{steps:ne});break}case"recovered":{const fe=ve.workflow;fe&&ee.updateWorkflow(m,he.id,{steps:fe.steps,status:fe.status});break}}})})().catch(oe=>{console.error("[Drawnix] Failed to setup workflow sync:",oe)}),()=>{ae==null||ae.unsubscribe()}},[m]);const K=[_q,Tye,DEe,REe,E2e,Xze(W),vHe,PHe,SWe,AHe(W),qHe(W),l9e,b9e,pWe,g9e,ute,hUe,xUe,kUe,lWe],j=x.useRef(null);BWe(),FWe(),iGe({enabled:!0,insertPrompt:!1,groupSimilarTasks:!0}),sGe();const{saveBoard:H,createBoard:L,switchBoard:V}=pVe(),Y=x.useCallback(async()=>{if(r&&R.current){const ae={children:R.current.children||[],viewport:R.current.viewport,theme:R.current.theme};await H(ae)}},[r,H]),q=x.useCallback(async()=>{await Y();const ae=await L({name:"新画布"});ae&&(await V(ae.id),setTimeout(()=>{window.location.reload()},500))},[Y,L,V]),Z=x.useCallback(ae=>{const de=R.current;if(de&&ae){const ee=nt(de).map(ce=>ce.id).filter(Boolean);W({lastSelectedElementIds:ee})}i&&i(ae)},[i,W]),re=x.useMemo(()=>({appState:f,setAppState:G,board:m}),[f,G,m]);return y.jsx(oLe,{children:y.jsx(Dke,{children:y.jsx(qje,{children:y.jsx(V9e,{children:y.jsx(cUe,{onOpenMediaLibrary:z,children:y.jsx(YGe,{children:y.jsx(aVe,{children:y.jsxs(Wee.Provider,{value:re,children:[y.jsx(BUe,{value:e,viewport:t,theme:n,options:d,plugins:K,containerRef:j,appState:f,board:m,setBoard:g,projectDrawerOpen:w,toolboxDrawerOpen:b,taskPanelExpanded:T,mediaLibraryOpen:k,backupRestoreOpen:O,onChange:r,onSelectionChange:Z,onViewportChange:s,onThemeChange:o,onValueChange:a,afterInit:l,onBoardSwitch:c,handleProjectDrawerToggle:M,handleToolboxDrawerToggle:$,handleTaskPanelToggle:A,setProjectDrawerOpen:C,setToolboxDrawerOpen:_,setMediaLibraryOpen:D,setBackupRestoreOpen:I,handleBeforeSwitch:Y,isDataReady:u,onCreateProjectForMemory:q}),y.jsx(x.Suspense,{fallback:null,children:y.jsx(OUe,{isOpen:k,onClose:()=>D(!1)})})]})})})})})})})})},BUe=({value:e,viewport:t,theme:n,options:r,plugins:i,containerRef:s,appState:o,board:a,setBoard:l,projectDrawerOpen:c,toolboxDrawerOpen:u,taskPanelExpanded:d,backupRestoreOpen:f,onChange:h,onSelectionChange:m,onViewportChange:g,onThemeChange:w,onValueChange:C,afterInit:b,onBoardSwitch:_,handleProjectDrawerToggle:T,handleToolboxDrawerToggle:S,handleTaskPanelToggle:k,setProjectDrawerOpen:D,setToolboxDrawerOpen:O,setBackupRestoreOpen:I,handleBeforeSwitch:R,isDataReady:F,onCreateProjectForMemory:M})=>{const{chatDrawerRef:$}=N3();OHe({board:a,pointer:o.pointer});const[A,z]=x.useState(!1),[G,W]=x.useState(null),{state:K,selectShape:j,closePicker:H}=vUe(a);return x.useEffect(()=>{if(!a)return;const L=Y=>{const q=Y.target;if(!(q.closest(".board-host-svg")||q.closest(".plait-board-container")))return;const re=Vt(a,Kt(a,Y.clientX,Y.clientY));if(!Oo(a,re)){const de=[Y.clientX,Y.clientY];W(de),z(!0)}},V=s.current;return V&&V.addEventListener("dblclick",L),()=>{V&&V.removeEventListener("dblclick",L)}},[a,s]),y.jsx("div",{className:Le("drawnix",{"drawnix--mobile":o.isMobile}),ref:s,children:y.jsxs("div",{className:"drawnix__main",children:[y.jsxs(Gye,{value:e,viewport:t,theme:n,options:r,plugins:i,onChange:L=>{h&&h(L)},onSelectionChange:m,onViewportChange:g,onThemeChange:w,onValueChange:C,children:[y.jsx(Upe,{afterInit:L=>{l(L),L.children&&L.children.length>0&&zp.preloadBoardFonts(L.children).catch(V=>{console.warn("Failed to preload board fonts:",V)}),b&&b(L),L.afterChange&&L.afterChange()}}),y.jsx(kWe,{}),y.jsx(qze,{projectDrawerOpen:c,onProjectDrawerToggle:T,toolboxDrawerOpen:u,onToolboxDrawerToggle:S,taskPanelExpanded:d,onTaskPanelToggle:k,onOpenBackupRestore:()=>I(!0)}),y.jsx(D9e,{}),y.jsx(XHe,{}),y.jsx(DHe,{}),y.jsx(BHe,{}),y.jsx(WHe,{}),y.jsx(zHe,{}),o.openDialogType&&y.jsx(x.Suspense,{fallback:null,children:y.jsx(PUe,{container:s.current})}),y.jsx(KHe,{container:s.current}),o.openSettings&&y.jsx(x.Suspense,{fallback:null,children:y.jsx(AUe,{container:s.current})}),f&&y.jsx(x.Suspense,{fallback:null,children:y.jsx(MUe,{open:f,onOpenChange:I,container:s.current,onBeforeImport:async()=>{R&&await R()},onSwitchBoard:async(L,V)=>{const Y=await qn.switchBoard(L);Y&&_&&(V&&(Y.viewport=V),_(Y))}})}),y.jsx(lUe,{position:G,visible:A,onClose:()=>z(!1)}),y.jsx(gUe,{visible:K.visible,position:K.position,currentShape:K.currentShape||void 0,onSelectShape:j,onClose:H,container:s.current}),y.jsx(zne,{isDataReady:F}),y.jsx(tUe,{}),y.jsx(bVe,{})]}),y.jsx(PWe,{}),y.jsx(aUe,{container:s.current,onCreateProject:M}),y.jsx(Mne,{ref:$}),y.jsx(x.Suspense,{fallback:null,children:y.jsx(DUe,{isOpen:c,onOpenChange:D,onBeforeSwitch:R,onBoardSwitch:_})}),y.jsx(x.Suspense,{fallback:null,children:y.jsx(IUe,{isOpen:u,onOpenChange:O})})]})})},qne="main_board_content",Xne=pi.createInstance({name:"Drawnix",storeName:WNe,driver:[pi.INDEXEDDB,pi.LOCALSTORAGE]});async function Yne(){try{const e=await tr.loadState();return(e==null?void 0:e.migrationCompleted)===!0}catch(e){return console.error("[WorkspaceMigration] Failed to check migration status:",e),!1}}async function mH(){try{const e=await tr.loadState();e.migrationCompleted=!0,await tr.saveState(e)}catch(e){console.error("[WorkspaceMigration] Failed to mark migration completed:",e)}}async function LUe(){try{const e=await Xne.getItem(qne);if(e&&e.children&&e.children.length>0)return e;const t=localStorage.getItem(mee);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 NUe(){try{if(await Yne())return null;const t=await LUe();if(!t||!t.children||t.children.length===0)return await mH(),null;const n=Yo.getInstance();await n.initialize();const r=await n.createBoard({name:"迁移的画板",elements:t.children,viewport:t.viewport,theme:t.theme});return r?(await n.switchBoard(r.id),await mH(),await jUe(),r.id):(console.error("[WorkspaceMigration] Failed to create board"),null)}catch(e){return console.error("[WorkspaceMigration] Migration failed:",e),null}}async function jUe(){try{await Xne.removeItem(qne),localStorage.removeItem(mee)}catch(e){console.error("[WorkspaceMigration] Failed to clear legacy data:",e)}}function k0(e){if(!qt.isAnalyticsEnabled())return;const t=FUe(e.name,e.value),n={[`$web_vitals_${e.name}_value`]:e.value,[`$web_vitals_${e.name}_event`]:{id:e.id,delta:e.delta,rating:t,navigationType:e.navigationType},page_url:window.location.href,page_path:window.location.pathname,referrer:document.referrer,timestamp:Date.now()};qt.track("$web_vitals",n)}function FUe(e,t){const r={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 r?t<=r.good?"good":t<=r.poor?"needs-improvement":"poor":"needs-improvement"}async function $Ue(){try{const e=await ln(()=>import("./web-vitals-DcvjKPr-.js"),[],import.meta.url),{onCLS:t,onFCP:n,onLCP:r,onTTFB:i,onINP:s}=e;t(k0),n(k0),r(k0),i(k0),s(k0)}catch(e){console.error("[Web Vitals] Failed to initialize monitoring:",e)}}const b1="page_report";function zUe(){const e=window.innerWidth;return e<768?"mobile":e<1024?"tablet":"desktop"}function HUe(){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:zUe(),user_agent:navigator.userAgent,language:navigator.language,timestamp:Date.now()}}function WUe(){if(!window.performance)return null;const e={page_url:window.location.href,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,r)=>n+(r.transferSize||0),0)}return e}function bx(){if(!qt.isAnalyticsEnabled())return;const e=HUe();qt.track("page_view",{category:b1,...e})}function vH(){if(!qt.isAnalyticsEnabled())return;const e=WUe();if(!e){console.warn("[Page Report] Performance data not available");return}qt.track("page_performance",{category:b1,...e})}function GUe(){if(!qt.isAnalyticsEnabled())return;const e=Math.round(performance.now());qt.track("page_unload",{category:b1,page_url:window.location.href,page_path:window.location.pathname,time_on_page:e,timestamp:Date.now()})}function VUe(){try{bx(),document.readyState==="complete"?vH():window.addEventListener("load",()=>{setTimeout(()=>{vH()},0)}),window.addEventListener("beforeunload",()=>{GUe()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?qt.track("page_hidden",{category:b1,page_url:window.location.href,page_path:window.location.pathname,timestamp:Date.now()}):document.visibilityState==="visible"&&qt.track("page_visible",{category:b1,page_url:window.location.href,page_path:window.location.pathname,timestamp:Date.now()})}),window.addEventListener("popstate",()=>{setTimeout(()=>{bx()},100)});const e=history.pushState,t=history.replaceState;history.pushState=function(...n){e.apply(this,n),setTimeout(()=>{bx()},100)},history.replaceState=function(...n){t.apply(this,n),setTimeout(()=>{bx()},100)}}catch(e){console.error("[Page Report] Failed to initialize monitoring:",e)}}function UUe(){if(typeof window>"u")return()=>{};const e=r=>{r.touches.length>1&&(r.preventDefault(),r.stopPropagation())},t=r=>{r.preventDefault(),r.stopPropagation()},n=r=>{(r.ctrlKey||r.metaKey)&&r.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 iD=XE.DB_CLEANUP_DONE;function Zne(){let e=0;for(const t of oZ)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 Qne(){localStorage.getItem(iD)||(Zne(),localStorage.setItem(iD,Date.now().toString()))}function KUe(){localStorage.removeItem(iD)}typeof window<"u"&&(window.__dbCleanup={run:Qne,reset:KUe,cleanupLS:Zne,LS_KEYS_DEPRECATED:oZ});const $3=[{lsKey:Fr.PROMPT_HISTORY,idbKey:Fr.PROMPT_HISTORY,deleteAfterMigration:!0},{lsKey:Fr.VIDEO_PROMPT_HISTORY,idbKey:Fr.VIDEO_PROMPT_HISTORY,deleteAfterMigration:!0},{lsKey:Fr.PRESET_SETTINGS,idbKey:Fr.PRESET_SETTINGS,deleteAfterMigration:!0},{lsKey:Fr.BATCH_IMAGE_CACHE,idbKey:Fr.BATCH_IMAGE_CACHE,deleteAfterMigration:!0},{lsKey:Fr.RECENT_TEXT_COLORS,idbKey:Fr.RECENT_TEXT_COLORS,deleteAfterMigration:!0},{lsKey:Fr.CUSTOM_GRADIENTS,idbKey:Fr.CUSTOM_GRADIENTS,deleteAfterMigration:!0},{lsKey:Fr.CUSTOM_FONTS,idbKey:Fr.CUSTOM_FONTS,deleteAfterMigration:!0},{lsKey:Fr.TOOLBAR_CONFIG,idbKey:Fr.TOOLBAR_CONFIG,deleteAfterMigration:!0}];function z3(){try{return localStorage.getItem(XE.LS_TO_IDB_MIGRATION_DONE)!==null}catch{return!1}}function qUe(){try{localStorage.setItem(XE.LS_TO_IDB_MIGRATION_DONE,Date.now().toString())}catch(e){console.error("[StorageMigration] Failed to mark migration done:",e)}}function XUe(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 yH(e){try{localStorage.removeItem(e)}catch(t){console.warn(`[StorageMigration] Failed to delete ${e} from LocalStorage:`,t)}}async function YUe(e){const{lsKey:t,idbKey:n,deleteAfterMigration:r}=e;try{const i=XUe(t);return i===null?{key:t,success:!0}:await Or.get(n)!==null?(r&&yH(t),{key:t,success:!0}):(await Or.set(n,i),await Or.get(n)===null?{key:t,success:!1,error:"Verification failed: data not found after write"}:(r&&yH(t),{key:t,success:!0}))}catch(i){const s=i instanceof Error?i.message:String(i);return console.error(`[StorageMigration] Failed to migrate ${t}:`,i),{key:t,success:!1,error:s}}}async function Jne(){if(!Or.isAvailable())return console.warn("[StorageMigration] IndexedDB not available, skipping migration"),[];if(z3())return[];const e=[];for(const n of $3){const r=await YUe(n);e.push(r),r.success||console.warn(`[StorageMigration] Failed: ${r.key} - ${r.error}`)}return e.filter(n=>n.success).length,e.filter(n=>!n.success).length===0&&qUe(),e}function ere(){try{localStorage.removeItem(XE.LS_TO_IDB_MIGRATION_DONE)}catch(e){console.error("[StorageMigration] Failed to reset migration status:",e)}}const ZUe={isMigrationDone:z3,runMigration:Jne,resetMigration:ere,MIGRATION_CONFIGS:$3};typeof window<"u"&&(window.__storageMigration={run:Jne,reset:ere,isDone:z3,configs:$3});const QUe=500;let wH=!1;function JUe(){const[e,t]=x.useState(!0),[n,r]=x.useState(!1),[i,s]=x.useState({children:[]}),o=x.useRef(),a=x.useRef(null);x.useEffect(()=>{(async()=>{if(wH){const f=Yo.getInstance();await f.waitForInitialization();const h=f.getCurrentBoard();h&&s({children:h.elements||[],viewport:h.viewport,theme:h.theme}),t(!1);return}wH=!0;try{const f=Yo.getInstance();await f.initialize(),await Yne()||await NUe();let m=f.getCurrentBoard();if(!m&&!f.hasBoards()){const g=await f.createBoard({name:"我的画板1",elements:[]});g&&(m=await f.switchBoard(g.id))}if(m){const g=m.elements||[];s({children:g,viewport:m.viewport,theme:m.theme}),xH(g).then(w=>{w!==g&&s(C=>({...C,children:w}))}).catch(w=>{console.error("[App] Video URL recovery failed:",w)})}}catch(f){console.error("[App] Initialization failed:",f)}finally{r(!0),t(!1)}})()},[]);const l=x.useCallback(async d=>{const f=await xH(d.elements||[]);s({children:f,viewport:d.viewport,theme:d.theme})},[]),c=x.useCallback(d=>{s(d),o.current=d.viewport,Yo.getInstance().saveCurrentBoard(d).catch(h=>{console.error("[App] Failed to save board:",h)})},[]),u=x.useCallback(d=>{o.current=d,a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{const f=Yo.getInstance(),h=f.getCurrentBoard();h&&f.saveCurrentBoard({children:h.elements,viewport:d,theme:h.theme}).catch(m=>{console.error("[App] Failed to save viewport:",m)})},QUe)},[]);return x.useEffect(()=>{const d=()=>{a.current&&(clearTimeout(a.current),a.current=null);const m=o.current;if(m){const g=Yo.getInstance(),w=g.getCurrentBoard();w&&(w.viewport=m,g.saveCurrentBoard({children:w.elements,viewport:m,theme:w.theme}).catch(()=>{}))}},f=()=>{d()},h=()=>{document.visibilityState==="hidden"&&d()};return window.addEventListener("beforeunload",f),document.addEventListener("visibilitychange",h),()=>{window.removeEventListener("beforeunload",f),document.removeEventListener("visibilitychange",h),a.current&&clearTimeout(a.current)}},[]),e?y.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100vh"},children:"加载中..."}):y.jsx("div",{style:{height:"100vh"},children:y.jsx(RUe,{value:i.children,viewport:i.viewport,theme:i.theme,onChange:c,onViewportChange:u,onBoardSwitch:l,isDataReady:n,afterInit:d=>{window.__drawnix__web__console=f=>{eKe(d,f)}}})})}const eKe=(e,t)=>{const n=Q.getBoardContainer(e).closest(".drawnix");let r=n.querySelector(".drawnix-console");r||(r=document.createElement("div"),r.classList.add("drawnix-console"),n.append(r));const i=document.createElement("div");i.innerHTML=t,r.append(i)};async function xH(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 r=n.indexOf("#merged-video-");if(r!==-1){const i=n.substring(r+1),s=i.indexOf("#",1),a=`/__aitu_cache__/video/${s>0?i.substring(0,s):i}.mp4`;return{...t,url:a}}}return t})}const tKe=3e4,nKe=800,rKe=.6,iKe=3,H3="aitu_last_snapshot",sKe=50,bH=3e3,oKe=1e4,aKe=200,lKe=5e3,cKe=10,uKe=5e3,dKe=30,fKe=20,CH=20,hKe=100,pKe=30;let EH=null,SH=!1,_H=null,TH=null,lk=null,ck=0,kf=60,U0=!1,uk=!1;const Zc=[],Ff=[],bl=[];function gKe(e){const t=ss(),n=Date.now();return()=>{const r=ss();if(!t||!r)return;const i=(r.usedJSHeapSize-t.usedJSHeapSize)/(1024*1024),s=Date.now()-n;if(Math.abs(i)>=sKe){const o=i>=0?"+":"";console.warn(`[MemoryLog] ${e}: ${o}${i.toFixed(0)} MB (${s}ms)`)}}}function ss(){if(typeof performance<"u"&&"memory"in performance){const e=performance.memory;return{usedJSHeapSize:e.usedJSHeapSize,totalJSHeapSize:e.totalJSHeapSize,jsHeapSizeLimit:e.jsHeapSizeLimit}}}function Vg(){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 oa(e){var t;try{(t=navigator.serviceWorker)!=null&&t.controller&&navigator.serviceWorker.controller.postMessage({type:"CRASH_SNAPSHOT",snapshot:e})}catch(n){console.warn("[MemoryLog] Failed to send snapshot to SW:",n)}}function mKe(e){try{localStorage.setItem(H3,JSON.stringify(e))}catch{}}function vKe(){try{const e=localStorage.getItem(H3);if(e)return JSON.parse(e)}catch{}return null}function yKe(){try{localStorage.removeItem(H3)}catch{}}function wKe(){const e={id:`startup-${Date.now()}`,timestamp:Date.now(),type:"startup",userAgent:navigator.userAgent,url:location.href,memory:ss()};oa(e)}function xKe(){if(EH!==null)return;let e=0;EH=window.setInterval(()=>{const t=ss();if(!t)return;const n=t.usedJSHeapSize/(1024*1024),r=t.jsHeapSizeLimit/(1024*1024),i=n/r;if(n>nKe||i>rKe){e++;const a=e>=iKe?Vg():void 0,l={id:`periodic-${Date.now()}`,timestamp:Date.now(),type:"periodic",memory:t,pageStats:a,userAgent:navigator.userAgent,url:location.href};oa(l)}else e=0},tKe)}function bKe(){window.addEventListener("error",e=>{var n;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:ss(),userAgent:navigator.userAgent,url:location.href,customData:{recentActions:Zc.slice(-10),filename:e.filename,lineno:e.lineno,colno:e.colno}};oa(t),console.error("[MemoryLog] Uncaught error captured:",e.message)}),window.addEventListener("unhandledrejection",e=>{const t=e.reason,n={id:`rejection-${Date.now()}`,timestamp:Date.now(),type:"error",error:{message:(t==null?void 0:t.message)||String(t)||"Unhandled Promise rejection",stack:t==null?void 0:t.stack,type:"unhandledRejection"},memory:ss(),userAgent:navigator.userAgent,url:location.href,customData:{recentActions:Zc.slice(-10)}};oa(n),console.error("[MemoryLog] Unhandled rejection captured:",t)}),window.addEventListener("beforeunload",()=>{const e=ss();if(e){const t={id:`beforeunload-${Date.now()}`,timestamp:Date.now(),type:"beforeunload",memory:e,userAgent:navigator.userAgent,url:location.href};mKe(t),oa(t)}})}function CKe(){if(_H!==null)return;let e=Date.now();document.addEventListener("visibilitychange",()=>{document.hidden?uk=!0:(e=Date.now(),setTimeout(()=>{uk=!1},bH+100))}),_H=window.setInterval(()=>{var r;const t=Date.now(),n=t-e;if(n>oKe&&!uk&&!document.hidden){const i={id:`freeze-${Date.now()}`,timestamp:Date.now(),type:"freeze",memory:ss(),pageStats:Vg(),performance:{freezeDuration:n,lastHeartbeat:e,fps:kf},userAgent:navigator.userAgent,url:location.href,customData:{recentActions:Zc.slice(-10),recentErrors:Ff.slice(-5),recentNetworkErrors:bl.slice(-5)}};oa(i)}e=t,(r=navigator.serviceWorker)!=null&&r.controller&&navigator.serviceWorker.controller.postMessage({type:"HEARTBEAT",timestamp:t})},bH)}function EKe(){if(lk===null&&!(typeof PerformanceObserver>"u"))try{lk=new PerformanceObserver(e=>{for(const t of e.getEntries())if(t.duration>aKe){const r=t.attribution;let i;if(r&&r.length>0){const o=r[0];i={name:o.name,containerType:o.containerType,containerSrc:o.containerSrc,containerId:o.containerId,containerName:o.containerName}}const s={id:`longtask-${Date.now()}`,timestamp:Date.now(),type:"longtask",memory:ss(),performance:{longTaskDuration:t.duration,fps:kf},userAgent:navigator.userAgent,url:location.href,customData:{taskName:t.name,startTime:t.startTime,attribution:i,debugTip:"Use Chrome DevTools Performance panel to record and analyze the call stack"}};oa(s)}}),lk.observe({entryTypes:["longtask"]})}catch{}}function SKe(){if(TH!==null)return;let e=0;const t=()=>{if(e++,e>=pKe){const n=performance.now(),r=n-ck;r>0&&(kf=Math.round(e*1e3/r)),e=0,ck=n}requestAnimationFrame(t)};ck=performance.now(),requestAnimationFrame(t),TH=window.setInterval(()=>{if(kf<cKe&&kf>0){const n={id:`lowfps-${Date.now()}`,timestamp:Date.now(),type:"freeze",memory:ss(),performance:{fps:kf},userAgent:navigator.userAgent,url:location.href};oa(n)}},lKe)}function _Ke(){setTimeout(()=>{kH()},uKe),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&!U0&&setTimeout(kH,1e3)})}function kH(){if(U0)return;const e=document.getElementById("root"),t=e&&e.children.length>0,r=!!document.querySelector(".plait-board-container");if(document.body.children.length>1,e&&!t){U0=!0;const i={id:`whitescreen-${Date.now()}`,timestamp:Date.now(),type:"whitescreen",memory:ss(),pageStats:{domNodeCount:document.getElementsByTagName("*").length,canvasCount:0,imageCount:0,videoCount:0,iframeCount:0,plaitBoardExists:r},userAgent:navigator.userAgent,url:location.href,customData:{rootExists:!!e,rootChildCount:(e==null?void 0:e.children.length)||0,bodyChildCount:document.body.children.length,hasPlaitBoard:r}};oa(i),console.error("[MemoryLog] 白屏检测: React 未渲染内容")}t&&!r&&location.pathname==="/"&&setTimeout(()=>{if(!document.querySelector(".plait-board-container")&&!U0){U0=!0;const i={id:`whitescreen-noboard-${Date.now()}`,timestamp:Date.now(),type:"whitescreen",memory:ss(),pageStats:Vg(),userAgent:navigator.userAgent,url:location.href,customData:{reason:"画板未加载",rootChildCount:(e==null?void 0:e.children.length)||0}};oa(i),console.error("[MemoryLog] 白屏检测: 画板组件未加载")}},5e3)}function K0(e,t,n){Zc.push({time:Date.now(),action:e,target:t,detail:n}),Zc.length>dKe&&Zc.shift()}function TKe(){let e=0;document.addEventListener("click",t=>{const n=Date.now();if(n-e<hKe)return;e=n;const r=t.target;if(!r)return;const i=()=>{var a,l,c,u,d,f,h,m,g,w,C,b,_,T,S;let s="";const o=(l=(a=r.closest)==null?void 0:a.call(r,"[data-track]"))==null?void 0:l.getAttribute("data-track");if(o)s=o;else if(r.tagName==="BUTTON"||(c=r.closest)!=null&&c.call(r,"button")){const k=((u=r.closest)==null?void 0:u.call(r,"button"))||r,D=(d=k.textContent)==null?void 0:d.trim().slice(0,20),O=(g=(m=(h=(f=k.className)==null?void 0:f.split)==null?void 0:h.call(f," "))==null?void 0:m[0])==null?void 0:g.slice(0,20);s=`btn:${D||O||"unknown"}`}else if(r.tagName==="A")s=`link:${((w=r.pathname)==null?void 0:w.slice(0,30))||""}`;else if(r.tagName==="INPUT"||r.tagName==="TEXTAREA"){const k=r;s=`input:${k.name||k.type||((C=k.placeholder)==null?void 0:C.slice(0,15))||""}`}else if(r.id)s=`#${r.id}`;else{const k=(T=(_=(b=r.className)==null?void 0:b.split)==null?void 0:_.call(b," "))==null?void 0:T[0];s=k?`.${k.slice(0,20)}`:((S=r.tagName)==null?void 0:S.toLowerCase())||"unknown"}K0("click",s)};"requestIdleCallback"in window?window.requestIdleCallback(i,{timeout:100}):setTimeout(i,0)},{capture:!0,passive:!0}),document.addEventListener("keydown",t=>{if(t.ctrlKey||t.metaKey||t.altKey){const n=[];(t.ctrlKey||t.metaKey)&&n.push("Cmd"),t.altKey&&n.push("Alt"),t.shiftKey&&n.push("Shift"),n.push(t.key),K0("shortcut",n.join("+"))}},{capture:!0,passive:!0}),window.addEventListener("popstate",()=>{K0("navigate",location.pathname)}),window.addEventListener("hashchange",()=>{K0("navigate",location.hash)})}function kKe(){const e=window.fetch;window.fetch=async function(t,n){const r=Date.now();try{const i=await e.call(this,t,n);if(!i.ok){const s=typeof t=="string"?t:t.url,o=Date.now()-r;bl.push({time:Date.now(),url:s.slice(0,300),method:(n==null?void 0:n.method)||"GET",status:i.status,statusText:i.statusText,duration:o}),bl.length>CH&&bl.shift()}return i}catch(i){const s=typeof t=="string"?t:t.url,o=Date.now()-r;throw bl.push({time:Date.now(),url:s.slice(0,300),method:(n==null?void 0:n.method)||"GET",error:i.message,duration:o}),bl.length>CH&&bl.shift(),i}}}function PKe(){window.addEventListener("error",e=>{var n;const t=e.target;if(t&&t!==window&&t instanceof HTMLElement&&("src"in t||"href"in t)){const r=t.src||t.href,i=(n=t.tagName)==null?void 0:n.toLowerCase();K0("resource_error",i,r==null?void 0:r.slice(0,100))}},{capture:!0})}function AKe(){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 r=[...t];setTimeout(()=>{var o;let i="",s;for(let a=0;a<Math.min(r.length,5);a++){const l=r[a];if(typeof l=="string")i+=l+" ";else if(typeof l=="number"||typeof l=="boolean")i+=String(l)+" ";else if(l instanceof Error)i+=`Error: ${l.message} `,s=l.stack;else if(l&&typeof l=="object")try{const u=Object.keys(l).slice(0,5).map(d=>{const f=l[d];return`${d}:${typeof f=="string"?f.slice(0,20):typeof f}`}).join(",");i+=`{${u}} `}catch{i+=`[${((o=l.constructor)==null?void 0:o.name)||"Object"}] `}}Ff.push({time:Date.now(),message:i.trim().slice(0,500),stack:s}),Ff.length>fKe&&Ff.shift()},0)}}function DKe(){return{userActions:[...Zc],consoleErrors:[...Ff],networkErrors:[...bl],memory:ss(),pageStats:Vg(),fps:kf}}function IKe(){typeof window>"u"||(window.__memoryLog={getMemory:()=>{const e=ss();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:gKe,diagnose:()=>{const e=ss(),t=Vg();if(console.group("[MemoryLog] 内存诊断"),e){const n=e.usedJSHeapSize/1048576,r=e.jsHeapSizeLimit/(1024*1024),i=n/r*100;console.log(`内存: ${n.toFixed(0)} MB / ${r.toFixed(0)} MB (${i.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:ss(),pageStats:Vg(),userAgent:navigator.userAgent,url:location.href};oa(e)},getDiagnostics:DKe,getActions:()=>(console.table(Zc.map(e=>({time:new Date(e.time).toLocaleTimeString("zh-CN"),action:e.action,target:e.target,detail:e.detail}))),Zc),getNetworkErrors:()=>(console.table(bl.map(e=>({time:new Date(e.time).toLocaleTimeString("zh-CN"),url:e.url,status:e.status,error:e.error}))),bl),getConsoleErrors:()=>(console.table(Ff.map(e=>({time:new Date(e.time).toLocaleTimeString("zh-CN"),message:e.message.slice(0,100)}))),Ff)})}function OKe(){if(SH)return;SH=!0,wKe(),bKe(),xKe(),CKe(),EKe(),SKe(),_Ke(),TKe(),kKe(),PKe(),AKe(),IKe();const e=vKe();e&&(e.customData={...e.customData,recovered:!0,recoveredAt:Date.now()},oa(e),yKe())}const PH=window.addEventListener.bind(window),MKe=window.removeEventListener.bind(window);let W3=null;window.addEventListener=function(e,t,n){if(e==="unload"){console.warn("[Permissions Policy] Blocked unload event listener");return}return e==="beforeunload"&&(W3=t),PH.call(window,e,t,n)};window.removeEventListener=function(e,t,n){return e==="beforeunload"&&(W3=null),MKe.call(window,e,t,n)};window.__checkBeforeUnload=()=>!!W3;let AH=!1,Hu=!1;const Ec={error:console.error,warn:console.warn,info:console.info,log:console.log,debug:console.debug};function Jd(e,t,n){var r;(r=navigator.serviceWorker)!=null&&r.controller&&navigator.serviceWorker.controller.postMessage({type:"SW_CONSOLE_LOG_REPORT",logLevel:e,logMessage:t,logStack:n||"",logSource:window.location.href})}function P0(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 DH(e){for(const t of e)if(t instanceof Error&&t.stack)return t.stack;return""}function RKe(){AH||"serviceWorker"in navigator&&(AH=!0,navigator.serviceWorker.addEventListener("message",e=>{var t,n,r,i;if(((t=e.data)==null?void 0:t.type)==="SW_DEBUG_STATUS"){const s=Hu;Hu=((n=e.data.status)==null?void 0:n.debugModeEnabled)||!1,Hu&&!s&&Ec.log("[SW Console Capture] 调试模式已开启,开始捕获所有日志")}else((r=e.data)==null?void 0:r.type)==="SW_DEBUG_ENABLED"?(Hu=!0,Ec.log("[SW Console Capture] 调试模式已开启,开始捕获所有日志")):((i=e.data)==null?void 0:i.type)==="SW_DEBUG_DISABLED"&&(Hu=!1,Ec.log("[SW Console Capture] 调试模式已关闭,仅捕获 warn/error"))}),navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"SW_DEBUG_GET_STATUS"}),navigator.serviceWorker.addEventListener("controllerchange",()=>{navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"SW_DEBUG_GET_STATUS"})}),console.error=function(...e){Ec.error.apply(console,e),Jd("error",P0(e),DH(e))},console.warn=function(...e){Ec.warn.apply(console,e),Jd("warn",P0(e),DH(e))},console.log=function(...e){Ec.log.apply(console,e),Hu&&Jd("log",P0(e),"")},console.info=function(...e){Ec.info.apply(console,e),Hu&&Jd("info",P0(e),"")},console.debug=function(...e){Ec.debug.apply(console,e),Hu&&Jd("debug",P0(e),"")},window.addEventListener("error",e=>{var n;const t=`${e.message} at ${e.filename}:${e.lineno}:${e.colno}`;Jd("error",t,((n=e.error)==null?void 0:n.stack)||"")}),window.addEventListener("unhandledrejection",e=>{const t=e.reason,n=t instanceof Error?t.message:`Unhandled Promise: ${String(t)}`,r=t instanceof Error&&t.stack||"";Jd("error",n,r)}),Ec.log("[SW Console Capture] 已初始化"))}OKe();kce({dsn:"https://a18e755345995baaa0e1972c4cf24497@o4510700882296832.ingest.us.sentry.io/4510700883869696",sendDefaultPii:!0});typeof window<"u"&&(UUe(),Qne().catch(e=>{console.warn("[Main] Database cleanup failed:",e)}),ZUe.runMigration().then(()=>Promise.all([fS(),cf.initializeAsync()])).catch(e=>{console.warn("[Main] Storage migration/init failed:",e)}));if(typeof window<"u"){setTimeout(()=>{SC.start(),SC.logMemoryStatus()},5e3);const e=()=>{window.posthog?($Ue(),VUe()):setTimeout(e,500)};setTimeout(e,1e3)}if("serviceWorker"in navigator){const e=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1";let t=null,n=!1,r=null;window.addEventListener("load",()=>{navigator.serviceWorker.register("/sw.js").then(i=>{r=i,RKe(),e&&(i.update().catch(s=>console.warn("Forced update check failed:",s)),i.waiting&&i.waiting.postMessage({type:"SKIP_WAITING"})),i.addEventListener("updatefound",()=>{const s=i.installing;s&&s.addEventListener("statechange",()=>{s.state==="installed"&&navigator.serviceWorker.controller&&(t=s,e?s.postMessage({type:"SKIP_WAITING"}):window.dispatchEvent(new CustomEvent("sw-update-available",{detail:{version:"new"}})))})}),setInterval(()=>{i.update().catch(s=>{console.warn("Update check failed:",s)})},300*1e3)}).catch(i=>{})}),navigator.serviceWorker.addEventListener("message",i=>{if(i.data&&i.data.type==="SW_UPDATED"){if(!n)return;setTimeout(()=>{window.location.reload()},1e3)}else i.data&&i.data.type==="CACHE_CLEANUP_COMPLETE"||(i.data&&i.data.type==="SW_NEW_VERSION_READY"?window.dispatchEvent(new CustomEvent("sw-update-available",{detail:{version:i.data.version}})):i.data&&i.data.type==="SW_UPGRADING"||i.data&&i.data.type)}),navigator.serviceWorker.addEventListener("controllerchange",()=>{n&&setTimeout(()=>{window.location.reload()},1e3)}),window.addEventListener("user-confirmed-upgrade",()=>{if(n=!0,t){t.postMessage({type:"SKIP_WAITING"});return}if(r&&r.waiting){r.waiting.postMessage({type:"SKIP_WAITING"});return}caches.keys().then(i=>{const s=i.filter(o=>o.startsWith("drawnix-static-v"));return Promise.all(s.map(o=>caches.delete(o)))}).finally(()=>{window.location.href=window.location.href.split("?")[0]+"?_t="+Date.now()})})}const BKe=C1.createRoot(document.getElementById("root"));BKe.render(y.jsx(x.StrictMode,{children:y.jsx(JUe,{})}));const LKe=Object.freeze(Object.defineProperty({__proto__:null,SWCapabilitiesHandler:Fne,swCapabilitiesHandler:PVe},Symbol.toStringTag,{value:"Module"})),tre=Object.freeze(Object.defineProperty({__proto__:null,AssetItem:v3,MediaLibraryEmpty:zee,MediaLibraryGrid:Vee,MediaLibraryInspector:jA,MediaLibraryModal:dS,MediaLibrarySidebar:Kee,MediaLibraryStorageBar:Uee},Symbol.toStringTag,{value:"Module"}));export{ht as $,c1 as A,cv as B,Mi as C,jn as D,$g as E,IA as F,Oc as G,rqe as H,br as I,y as J,VHe as K,UHe as L,Di as M,eqe as N,nqe as O,wS as P,m3 as Q,Kr as R,Or as S,Ke as T,Fr as U,tqe as V,xt as W,Ic as X,iZ as Y,ln as Z,ur as _,WKe as a,oy as a$,Zee as a0,QNe as a1,I8e as a2,Jo as a3,dS as a4,ym as a5,sh as a6,GLe as a7,pFe as a8,qn as a9,vo as aA,td as aB,Io as aC,YE as aD,fZ as aE,er as aF,Ii as aG,cn as aH,Le as aI,Xe as aJ,_7 as aK,J as aL,y5 as aM,st as aN,MQ as aO,Es as aP,L5 as aQ,s3e as aR,r3e as aS,OQ as aT,kc as aU,Ap as aV,pVe as aW,Oze as aX,tn as aY,Th as aZ,Vte as a_,tr as aa,OO as ab,GEe as ac,pi as ad,iu as ae,cy as af,fS as ag,OFe as ah,x3 as ai,ite as aj,AFe as ak,f1 as al,G8e as am,uZ as an,APe as ao,rDe as ap,N5e as aq,tDe as ar,c5 as as,_Z as at,yZ as au,gZ as av,qi as aw,mZ as ax,sDe as ay,kZ as az,HKe as b,t5e as b$,A3 as b0,dy as b1,bS as b2,P3 as b3,Gg as b4,qte as b5,X as b6,ci as b7,Ur as b8,lhe as b9,Ro as bA,fl as bB,Og as bC,N5 as bD,I6e as bE,sr as bF,lu as bG,as as bH,Rd as bI,sy as bJ,YKe as bK,wRe as bL,ty as bM,Ui as bN,JKe as bO,Ol as bP,p5 as bQ,SAe as bR,SPe as bS,LIe as bT,NDe as bU,pA as bV,u5e as bW,aC as bX,o5e as bY,iDe as bZ,z5e as b_,tc as ba,hm as bb,xE as bc,yt as bd,lm as be,Bt as bf,WI as bg,Gn as bh,wg as bi,qc as bj,MI as bk,kt as bl,ct as bm,Eo as bn,Nn as bo,l5 as bp,X5e as bq,GN as br,IPe as bs,J1 as bt,Q1 as bu,M5e as bv,r5 as bw,s5 as bx,ey as by,U5e as bz,Ft as c,lh as c$,Q5e as c0,$3e as c1,A7 as c2,a3e as c3,S7 as c4,Kl as c5,cu as c6,j5 as c7,rS as c8,B3e as c9,So as cA,ine as cB,Lze as cC,gp as cD,ma as cE,TVe as cF,Mo as cG,FFe as cH,pqe as cI,$Ke as cJ,dqe as cK,fqe as cL,FKe as cM,NFe as cN,hqe as cO,lqe as cP,aqe as cQ,F0 as cR,R8e as cS,ZJ as cT,RLe as cU,ig as cV,Ize as cW,xS as cX,Rze as cY,Co as cZ,wm as c_,D6e as ca,Ml as cb,ZKe as cc,L3e as cd,jne as ce,gqe as cf,zc as cg,yx as ch,Q as ci,pu as cj,qu as ck,Pc as cl,jKe as cm,Kk as cn,RE as co,Gye as cp,_q as cq,DEe as cr,Tye as cs,E2e as ct,Vbe as cu,Upe as cv,XKe as cw,Hr as cx,GX as cy,na as cz,Xl as d,KX as d0,uS as d1,Xee as d2,rne as d3,uqe as d4,cqe as d5,ES as d6,oqe as d7,iqe as d8,sqe as d9,WX as da,WSe as db,IE as dc,OE as dd,vt as de,CS as df,Nie as dg,BTe as dh,VE as di,e5 as dj,UE as dk,UKe as dl,qKe as dm,KKe as dn,VKe as dp,_Te as dq,wf as dr,R6 as ds,NKe as dt,Av as du,QKe as dv,Pee as e,z0 as f,An as g,G7e as h,zKe as i,Fje as j,r3 as k,K1 as l,ZE as m,ws as n,o1 as o,o5 as p,sC as q,x as r,La as s,bn as t,Mn as u,i5 as v,vAe as w,CPe as x,xs as y,a5 as z};
2064
+ 🔄 Refresh page fully releases memory`})]});return y.jsxs("div",{ref:h,className:`performance-panel performance-panel--${b} ${c?"performance-panel--dragging":""}`,style:_,children:[y.jsx("div",{className:"performance-panel__drag-handle",onPointerDown:T,onPointerMove:S,onPointerUp:k,onPointerCancel:k,title:n==="zh"?"拖拽移动":"Drag to move",children:y.jsx(qte,{})}),y.jsx(Di,{content:$,placement:"left",theme:"light",children:y.jsxs("div",{className:"performance-panel__content",children:[y.jsx("div",{className:"performance-panel__icon",children:b==="critical"?"🔴":"🟠"}),y.jsxs("div",{className:"performance-panel__value",children:[r==null?void 0:r.usagePercent.toFixed(0),"%"]})]})}),y.jsx("div",{className:"performance-panel__divider"}),t&&y.jsx("button",{className:"performance-panel__btn",onClick:M,disabled:R,title:n==="zh"?"新建项目":"New project",children:y.jsx(dy,{})}),y.jsx(DJ,{content:n==="zh"?"刷新页面可释放内存":"Refresh to free memory",confirmBtn:n==="zh"?"刷新":"Refresh",cancelBtn:n==="zh"?"取消":"Cancel",onConfirm:I,placement:"left",theme:"default",children:y.jsx("button",{className:"performance-panel__btn",title:n==="zh"?"刷新页面":"Refresh page",children:y.jsx(ch,{})})}),y.jsx("div",{className:"performance-panel__divider"}),y.jsx("button",{className:`performance-panel__btn ${s.pinned?"performance-panel__btn--active":""}`,onClick:D,title:s.pinned?n==="zh"?"取消常驻":"Unpin":n==="zh"?"常驻":"Pin",children:s.pinned?y.jsx(Yte,{}):y.jsx(Zte,{})}),y.jsx("button",{className:"performance-panel__btn",onClick:O,title:n==="zh"?"关闭":"Close",children:y.jsx(CS,{})})]})},lUe=({position:e,visible:t,onClose:n})=>{const r=Hr(),{t:i}=jn(),s=y3(),o=Q.getBoardContainer(r),[a,l]=x.useState({freehand:!1,arrow:!1,shape:!1}),[c,u]=x.useState(!1),{refs:d,floatingStyles:f}=Z1({placement:"bottom",middleware:[VE(12),e5({padding:16}),UE({fallbackPlacements:["top","right","left"]})]});x.useEffect(()=>{if(e&&t){const[I,R]=e;d.setPositionReference({getBoundingClientRect(){return{width:1,height:1,x:I,y:R,top:R,left:I,right:I+1,bottom:R+1}}})}},[e,t,d]),x.useEffect(()=>{if(!t)return;const I=F=>{const M=F.target,$=M.closest(".quick-creation-toolbar"),A=M.closest(".quick-toolbar-popover")||M.closest("[data-radix-popper-content-wrapper]")||M.closest(".plait-popover")||M.closest(".shape-picker")||M.closest(".arrow-picker")||M.closest(".freehand-panel"),z=M.closest(".media-library-modal");!$&&!A&&!z&&n()},R=setTimeout(()=>{document.addEventListener("mousedown",I)},100);return()=>{clearTimeout(R),document.removeEventListener("mousedown",I)}},[t,n]);const h=()=>{l({freehand:!1,arrow:!1,shape:!1})},m=I=>{l({freehand:!1,arrow:!1,shape:!1,[I]:!0})},g=()=>{h(),fu(r),li(r,Ar.drawing),$t.updatePointerType(r,yt.text),s(yt.text),n()},w=()=>{h(),u(!0)},C=()=>{h(),mS(r),n()},b=async I=>{try{I.type===Kr.IMAGE?await wm(r,I.url):I.type===Kr.VIDEO&&await lh(r,I.url),xt.success(i("toolbar.assetInserted")||"素材已插入到画板"),u(!1),n()}catch(R){console.error("Failed to insert asset:",R),xt.error(i("toolbar.assetInsertFailed")||"插入素材失败")}},[_,T]=x.useState(Jr.feltTipPen),S=300,k=x.useRef(null),D=x.useCallback(()=>{k.current&&(clearTimeout(k.current),k.current=null)},[]);x.useEffect(()=>()=>{D()},[D]);const O=(I,R,F,M)=>y.jsxs(ti,{open:a[R],sideOffset:12,onOpenChange:$=>{$||h()},placement:"bottom",children:[y.jsx(ni,{asChild:!0,children:y.jsx("div",{onPointerEnter:()=>{D(),k.current=setTimeout(()=>{m(R)},S)},onPointerLeave:()=>{D()},children:y.jsx(jt,{type:"icon",visible:!0,selected:a[R],icon:I,title:"","aria-label":F,"data-track":`quick_toolbar_click_${R}`,onPointerDown:()=>{D(),m(R),fu(r),R==="freehand"&&(li(r,Ar.dnd),$t.updatePointerType(r,_),s(_))},onPointerUp:()=>{R==="freehand"&&li(r,Ar.drawing)}})})}),y.jsx(ri,{container:o,style:{zIndex:ma.POPOVER},className:"quick-toolbar-popover",children:M})]});return t?y.jsxs(y.Fragment,{children:[y.jsx(xr,{padding:1,className:`quick-creation-toolbar ${vi}`,ref:d.setFloating,style:f,children:y.jsxs(Mr.Row,{gap:1,children:[y.jsx(jt,{type:"icon",visible:!0,icon:WO,title:"","aria-label":i("toolbar.text"),"data-track":"quick_toolbar_click_text",onPointerUp:g}),y.jsx(jt,{type:"icon",visible:!0,icon:KO,title:"","aria-label":i("toolbar.image"),"data-track":"quick_toolbar_click_image",onPointerUp:C}),y.jsx(jt,{type:"icon",visible:!0,icon:qO,title:"","aria-label":i("toolbar.mediaLibrary"),"data-track":"quick_toolbar_click_media_library",onPointerUp:w}),O(xm,"freehand",i("toolbar.pen"),y.jsx(S3,{onPointerUp:I=>{h(),T(I),$t.updatePointerType(r,I),s(I),n()}})),O(GO,"arrow",i("toolbar.arrow"),y.jsx(T3,{onPointerUp:I=>{h(),$t.updatePointerType(r,I),s(I),n()}})),O(HO,"shape",i("toolbar.shape"),y.jsx(_3,{onPointerUp:I=>{h(),$t.updatePointerType(r,I),s(I),n()}}))]})}),y.jsx(dS,{isOpen:c,onClose:()=>{u(!1)},mode:ym.SELECT,onSelect:b,selectButtonText:i("toolbar.insert")||"插入"})]}):null},cUe=({children:e,onOpenMediaLibrary:t})=>{const[n,r]=x.useState(!1),i=x.useCallback(()=>{if(!n){r(!0);const s=I8e.confirm({header:"缓存空间已满",body:"图片缓存空间已满,无法继续缓存新图片。是否打开素材库清理缓存?",theme:"warning",confirmBtn:"打开素材库",cancelBtn:"稍后处理",onConfirm:()=>{r(!1),t==null||t(),s.hide()},onCancel:()=>{r(!1),s.hide()},onClose:()=>{r(!1)}})}},[n,t]);return wze(i),y.jsx(y.Fragment,{children:e})},_C={visible:!1,position:{x:0,y:0},sourceElement:null,currentShape:null,hitIndex:-1,hitPoint:null,mode:"hover",arrowLineElement:null,arrowLineEndPoint:null},Hne=new WeakMap,nD=new WeakMap;function TC(e){return Hne.get(e)||_C}function V0(e,t){Hne.set(e,t);const n=nD.get(e);n&&n(t)}function uUe(e,t){return nD.set(e,t),()=>{nD.delete(e)}}function F3(e){V0(e,_C)}const T0=100;function dUe(e,t,n,r,i){const s=cU(n),o=X.getRectangleByPoints(t.points),a=o.width,l=o.height,c=o.x+a/2,u=o.y+l/2,f=X.getEdgeCenterPoints(o)[n];let h,m;switch(s){case zt.right:h=c+a/2+T0+a/2,m=u;break;case zt.bottom:h=c,m=u+l/2+T0+l/2;break;case zt.left:h=c-a/2-T0-a/2,m=u;break;case zt.top:h=c,m=u-l/2-T0-l/2;break;default:h=c+a/2+T0+a/2,m=u}const g=[[h-a/2,m-l/2],[h+a/2,m+l/2]],w=gd(e,g,i);if(w.fill="#ffffff",be.isShapeElement(t)&&!be.isText(t)){const F=t;F.angle!==void 0&&(w.angle=F.angle),F.fill&&F.fill!=="none"&&(w.fill=F.fill),F.strokeColor!==void 0&&(w.strokeColor=F.strokeColor),F.strokeStyle!==void 0&&(w.strokeStyle=F.strokeStyle),F.strokeWidth!==void 0&&(w.strokeWidth=F.strokeWidth)}const C=ua(f,t)||f,b=be.isShapeElement(t)?Wl(e,C,t):void 0;let _;switch(s){case zt.right:_=3;break;case zt.bottom:_=0;break;case zt.left:_=1;break;case zt.top:_=2;break;default:_=3}const T=X.getRectangleByPoints(w.points),k=X.getEdgeCenterPoints(T)[_],D=ua(k,w)||k,O=Wl(e,D,w),I=WI(Gn.straight,[C,D],{marker:Ur.none,connection:b,boundId:t.id},{marker:Ur.arrow,connection:O,boundId:w.id},[],{});Ke.insertNode(e,I,[e.children.length]),da(e,w),F3(e);const R=w.id;setTimeout(()=>{const F=e.children.findIndex($=>$.id===R),M=F>=0?e.children[F]:null;M&&(aa(e),ya(e,M),$t.updatePointerType(e,fn.selection),Ke.setNode(e,{_forceRender:Date.now()},[F]),Ke.setNode(e,{_forceRender:void 0},[F]))},50)}function fUe(e,t,n,r){var m;let i=100,s=100;const o=t,a=(m=o.source)==null?void 0:m.boundId;if(a){const g=e.children.find(w=>w.id===a);if(g&&be.isShapeElement(g)){const w=X.getRectangleByPoints(g.points);i=w.width,s=w.height}}const l=[[n[0]-i/2,n[1]-s/2],[n[0]+i/2,n[1]+s/2]],c=gd(e,l,r);c.fill="#ffffff";const u=X.getRectangleByPoints(c.points),d=X.getEdgeCenterPoints(u),f=o.points||[];if(f.length>=2){const g=f[0],w=f[f.length-1],C=w[0]-g[0],b=w[1]-g[1];let _;Math.abs(C)>Math.abs(b)?_=C>0?3:1:_=b>0?0:2;const T=d[_],S=Wl(e,T,c),k=e.children.findIndex(D=>D.id===t.id);k!==-1&&Ke.setNode(e,{target:{marker:Ur.arrow,connection:S,boundId:c.id},points:[g,T]},[k])}da(e,c),F3(e);const h=c.id;setTimeout(()=>{const g=e.children.findIndex(C=>C.id===h),w=g>=0?e.children[g]:null;w&&(aa(e),ya(e,w),$t.updatePointerType(e,fn.selection),Ke.setNode(e,{_forceRender:Date.now()},[g]),Ke.setNode(e,{_forceRender:void 0},[g]))},50)}const hUe=e=>{const{pointerMove:t,pointerLeave:n,globalPointerUp:r}=e;let i=null,s=-1,o=e.children.length,a={x:0,y:0};return e.pointerMove=l=>{a={x:l.clientX,y:l.clientY},i&&(clearTimeout(i),i=null);const c=_g(e),u=c.length===1&&c[0],d=TC(e);if(!u||!be.isShapeElement(u)||be.isText(u)){d.visible&&d.mode==="hover"&&V0(e,{..._C}),s=-1,t(l);return}const f=hd(e,l.x,l.y),h=H1(e,u,!0),m=Hl(e,f,u,!0)||f,g=bE(m,h),w=h[g];if(w){if(g!==s||!d.visible){s=g;const C=l.clientX,b=l.clientY;i=setTimeout(()=>{const _=be.isImage(u)?yt.rectangle:u.shape||yt.rectangle;V0(e,{visible:!0,position:{x:C-140,y:b+20},sourceElement:u,currentShape:_,hitIndex:g,hitPoint:w,mode:"hover"})},50)}}else s=-1,d.visible&&d.mode==="hover"&&(i=setTimeout(()=>{const C=TC(e);C.visible&&C.mode==="hover"&&V0(e,{..._C})},300));t(l)},e.pointerLeave=l=>{i&&(clearTimeout(i),i=null),n(l)},e.globalPointerUp=l=>{var u;r(l);const c=e.children.length;if(c>o){const d=e.children[c-1];if(be.isArrowLine(d)){const f=d;if(!((u=f.target)==null?void 0:u.boundId)){const m=f.points||[];if(m.length>=2){const g=m[m.length-1];setTimeout(()=>{V0(e,{visible:!0,position:{x:a.x-140,y:a.y+20},sourceElement:null,currentShape:yt.rectangle,hitIndex:-1,hitPoint:null,mode:"arrowLine",arrowLineElement:d,arrowLineEndPoint:g})},50)}}}}o=e.children.length},e},pUe=[{icon:aY,title:"Rectangle",pointer:yt.rectangle},{icon:cY,title:"Ellipse",pointer:yt.ellipse},{icon:uY,title:"Triangle",pointer:yt.triangle},{icon:lY,title:"Terminal",pointer:Bt.terminal},{icon:dY,title:"Diamond",pointer:yt.diamond},{icon:fY,title:"Parallelogram",pointer:yt.parallelogram},{icon:hY,title:"RoundRectangle",pointer:yt.roundRectangle}],gUe=({visible:e,position:t,currentShape:n,onSelectShape:r,onClose:i,container:s})=>{const o=x.useRef(null);x.useEffect(()=>{if(!e)return;const f=g=>{o.current&&!o.current.contains(g.target)&&i()},h=g=>{g.key==="Escape"&&i()},m=setTimeout(()=>{document.addEventListener("mousedown",f),document.addEventListener("keydown",h)},50);return()=>{clearTimeout(m),document.removeEventListener("mousedown",f),document.removeEventListener("keydown",h)}},[e,i]);const a=x.useCallback(f=>{r(f)},[r]);if(!e)return null;const l={x:isNaN(t.x)?0:t.x,y:isNaN(t.y)?0:t.y},c=200,u=80;typeof window<"u"&&(l.x+c>window.innerWidth&&(l.x=window.innerWidth-c-10),l.y+u>window.innerHeight&&(l.y=t.y-u-20));const d=y.jsx("div",{ref:o,className:Le("auto-complete-shape-picker",vi),style:{left:l.x,top:l.y},children:y.jsx(xr,{padding:1,children:y.jsx(Mr.Col,{gap:1,children:y.jsx(Mr.Row,{gap:1,children:pUe.map((f,h)=>y.jsx(jt,{className:Le("shape-button",{"is-current":n===f.pointer}),type:"icon",size:"small",visible:!0,icon:f.icon,title:f.title,"aria-label":f.title,onPointerDown:({event:m})=>{m.stopPropagation(),a(f.pointer)}},h))})})})});return s?Mo.createPortal(d,s):d},mUe={visible:!1,position:{x:0,y:0},sourceElement:null,currentShape:null,hitIndex:-1,hitPoint:null,mode:"hover"};function vUe(e){const[t,n]=x.useState(mUe);x.useEffect(()=>{if(!e)return;n(TC(e));const s=uUe(e,o=>{n(o)});return()=>{s()}},[e]);const r=x.useCallback(s=>{if(!e)return;const o=TC(e);o.mode==="arrowLine"?o.arrowLineElement&&o.arrowLineEndPoint&&fUe(e,o.arrowLineElement,o.arrowLineEndPoint,s):o.sourceElement&&o.hitPoint&&o.hitIndex>=0&&dUe(e,o.sourceElement,o.hitIndex,o.hitPoint,s)},[e]),i=x.useCallback(()=>{e&&F3(e)},[e]);return{state:t,selectShape:r,closePicker:i}}const yUe="#ffffff",wUe=[yt.rectangle,yt.ellipse,yt.triangle,yt.diamond,yt.parallelogram,yt.roundRectangle];function hH(e){if(!be.isGeometry(e)||be.isText(e)||be.isImage(e))return!1;const t=e;return!(!t.shape||!wUe.includes(t.shape)||t.fill&&t.fill!=="none")}const xUe=e=>{const{afterChange:t}=e,n=new Set;return e.afterChange=()=>{t();const r=[];e.children.forEach((i,s)=>{hH(i)&&!n.has(i.id)&&(r.push({path:[s],element:i}),n.add(i.id))}),r.length>0&&setTimeout(()=>{r.forEach(({path:i})=>{const s=e.children[i[0]];s&&hH(s)&&Ke.setNode(e,{fill:yUe},i)})},0)},e},kC=new WeakMap;let ak=null,Sc=null;function Wne(e,t){try{const n=_n.getElementG(t);if(n)return n}catch{}if(t!=null&&t.id){const n=Q.getElementHost(e);if(n){const r=n.querySelector(`g[id="${t.id}"]`);if(r)return r}}return null}function Gne(e){return e.querySelector("path, rect, ellipse, polygon, circle")}function Vne(e){let t=e.querySelector("defs");return t||(t=RSe(),e.insertBefore(t,e.firstChild)),t}function bUe(e,t){const n=kC.get(t);if(n){const r=e.querySelector(`#${n}`);r&&r.remove()}}function PC(e,t,n){const r=Wne(e,t);if(!r)return;const i=Gne(r);if(!i)return;const s=r.closest("svg");if(!s)return;const o=Et(e,[t],!1),a=(o==null?void 0:o.width)||100,l=(o==null?void 0:o.height)||100,c=NX(n,t.id,a,l),u=Vne(s);if(c.defElement){const d=c.defElement.id,f=u.querySelector(`#${d}`);f?f.replaceWith(c.defElement):u.appendChild(c.defElement),i.setAttribute("fill",c.fillValue),kC.set(t,d);const h=kC.get(t);if(h&&h!==d){const m=u.querySelector(`#${h}`);m&&m.remove()}}else i.setAttribute("fill",c.fillValue),bUe(s,t)}function sb(e,t){return e.children.find(n=>n.id===t)||null}function Hc(e){const t=e.fillConfig;return t&&is(t)?t:e.fill&&is(e.fill)?e.fill:null}function Une(e,t){if(!e)return!1;if(e==="[object Object]")return!0;if(e.startsWith("url(#")){const n=e.match(/url\(#([^)]+)\)/);if(n){const r=n[1];if(!document.getElementById(r))return!0}return!1}if(t){const n=Hc(t);if(n&&(n.type==="gradient"||n.type==="image"))return!0}return!1}function CUe(e){if(!Sc)return;const t=new Set;e.forEach(n=>{if(n.type==="attributes"&&n.attributeName==="fill"){const r=n.target,i=r.getAttribute("fill"),s=r.closest("g[id]");if(s){const o=s.getAttribute("id");if(o){const a=sb(Sc,o),l=a?Hc(a):null;a&&l&&sa(Sc,a)&&Une(i,a)&&t.add(a)}}}n.type==="childList"&&n.addedNodes.forEach(r=>{if(r instanceof SVGGElement&&r.hasAttribute("id")){const i=r.getAttribute("id");if(i){const s=sb(Sc,i),o=s?Hc(s):null;s&&o&&sa(Sc,s)&&t.add(s)}}if(r instanceof Element){const i=r.closest("g[id]");if(i){const s=i.getAttribute("id");if(s){const o=sb(Sc,s),a=o?Hc(o):null;o&&a&&sa(Sc,o)&&t.add(o)}}}})}),t.size>0&&t.forEach(n=>{const r=Hc(n);r&&PC(Sc,n,r)})}function EUe(e){if(ak)return;const t=Q.getElementHost(e);t&&(Sc=e,ak=new MutationObserver(CUe),ak.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["fill"]}))}function SUe(e){const t=Q.getElementHost(e);if(!t)return;t.querySelectorAll("path[fill], rect[fill], ellipse[fill], polygon[fill], circle[fill]").forEach(r=>{const i=r.getAttribute("fill"),s=r.closest("g[id]");if(s){const o=s.getAttribute("id");if(o){const a=sb(e,o),l=a?Hc(a):null;a&&l&&sa(e,a)&&Une(i,a)&&PC(e,a,l)}}})}function rD(e,t=!1){e.children.forEach(n=>{const r=Hc(n);r&&sa(e,n)&&(t?PC(e,n,r):requestAnimationFrame(()=>{PC(e,n,r)}))}),t&&SUe(e)}let pH=!0;const gH=new WeakSet;function Kne(e){const t=Q.getElementHost(e);if(!t)return;const n=t.closest("svg")||t.querySelector("svg");n&&e.children.forEach(r=>{const i=Hc(r);if(i&&(i.type==="gradient"||i.type==="image")&&sa(e,r)){const s=Et(e,[r],!1),o=(s==null?void 0:s.width)||100,a=(s==null?void 0:s.height)||100,l=NX(i,r.id,o,a);if(l.defElement){const c=Vne(n);c.querySelector(`#${l.defElement.id}`)||(c.appendChild(l.defElement),kC.set(r,l.defElement.id))}}})}function _Ue(e){let t=0;return e.children.forEach(n=>{const r=Hc(n);if(r&&(r.type==="gradient"||r.type==="image")&&sa(e,n)){const i=Wne(e,n);(i?Gne(i):null)||t++}}),t}function TUe(e){if(gH.has(e))return;gH.add(e);const t=15,n=16;let r=0;const i=()=>{r++;try{if(!Q.getElementHost(e))return;if(Kne(e),rD(e,!0),_Ue(e)>0&&r<t){const a=Math.min(n*Math.pow(1.5,r),500);setTimeout(i,a)}}catch{}};requestAnimationFrame(()=>{i(),setTimeout(i,0)})}const kUe=e=>{const{afterChange:t}=e;return e.afterChange=()=>{t(),EUe(e),Kne(e),pH?(pH=!1,rD(e,!0),TUe(e)):rD(e,!0)},e},PUe=x.lazy(()=>ln(()=>import("./ttd-dialog-TQYw_Nae.js"),__vite__mapDeps([10,11,12,13,14,15,16]),import.meta.url).then(e=>({default:e.TTDDialog}))),AUe=x.lazy(()=>ln(()=>import("./settings-dialog-C4eZxway.js"),__vite__mapDeps([17,11,12,13,14,16]),import.meta.url).then(e=>({default:e.SettingsDialog}))),DUe=x.lazy(()=>ln(()=>import("./index-DGb8pRqW.js"),__vite__mapDeps([18,19,20]),import.meta.url).then(e=>({default:e.ProjectDrawer}))),IUe=x.lazy(()=>ln(()=>import("./ToolboxDrawer-D0dL1xDI.js"),__vite__mapDeps([21,2,13,22,12,11,14,23]),import.meta.url).then(e=>({default:e.ToolboxDrawer}))),OUe=x.lazy(()=>ln(()=>Promise.resolve().then(()=>tre),void 0,import.meta.url).then(e=>({default:e.MediaLibraryModal}))),MUe=x.lazy(()=>ln(()=>import("./index-JhVJEcm-.js"),__vite__mapDeps([24,19,25]),import.meta.url).then(e=>({default:e.BackupRestoreDialog}))),RUe=({value:e,viewport:t,theme:n,onChange:r,onSelectionChange:i,onViewportChange:s,onThemeChange:o,onValueChange:a,afterInit:l,onBoardSwitch:c,isDataReady:u=!1})=>{const d={readonly:!1,hideScrollbar:!1,disabledScrollOnNonFocus:!1,themeColors:Vbe},[f,h]=x.useState(()=>{const ae=new MEe(window.navigator.userAgent);return{pointer:fn.hand,isMobile:ae.mobile()!==null,isPencilMode:!1,openDialogType:null,dialogInitialData:null,openCleanConfirm:!1,openSettings:!1}}),[m,g]=x.useState(null),[w,C]=x.useState(!1),[b,_]=x.useState(!1),[T,S]=x.useState(!1),[k,D]=x.useState(!1),[O,I]=x.useState(!1),R=x.useRef(null),F=x.useCallback(()=>{C(!1),_(!1),S(!1),D(!1)},[]),M=x.useCallback(()=>{C(ae=>(ae||F(),!ae))},[F]),$=x.useCallback(()=>{_(ae=>(ae||F(),!ae))},[F]),A=x.useCallback(()=>{S(ae=>(ae||F(),!ae))},[F]),z=x.useCallback(()=>{F(),D(!0)},[F]),G=x.useCallback(ae=>{h(ae)},[]),W=x.useCallback(ae=>{h(de=>({...de,...ae}))},[]);x.useEffect(()=>{m&&(m.appState=f,R.current=m)},[m,f]),x.useEffect(()=>CVe(),[]),x.useEffect(()=>{e&&e.length>0&&zp.preloadBoardFonts(e).then(()=>{}).catch(ae=>{console.warn("Failed to preload board fonts:",ae)})},[e]),x.useEffect(()=>{m&&ln(async()=>{const{initVideoRecoveryService:ae}=await import("./video-recovery-service-CZXUWRm1.js");return{initVideoRecoveryService:ae}},[],import.meta.url).then(({initVideoRecoveryService:ae})=>{ae(m)})},[m]),x.useEffect(()=>{const ae=de=>{const oe=de,{message:ee}=oe.detail;xt.error({content:"API Key 无效或已过期,请重新配置",duration:5e3}),console.error("[Drawnix] API auth error:",ee),h(ce=>({...ce,openSettings:!0}))};return window.addEventListener(OA,ae),()=>{window.removeEventListener(OA,ae)}},[]),x.useEffect(()=>{m&&e&&e.length>0&&(async()=>{const{WorkZoneTransforms:de}=await ln(async()=>{const{WorkZoneTransforms:ue}=await Promise.resolve().then(()=>o$);return{WorkZoneTransforms:ue}},void 0,import.meta.url),{shouldUseSWTaskQueue:oe}=await ln(async()=>{const{shouldUseSWTaskQueue:ue}=await Promise.resolve().then(()=>U9);return{shouldUseSWTaskQueue:ue}},void 0,import.meta.url),{TaskStatus:ee}=await ln(async()=>{const{TaskStatus:ue}=await Promise.resolve().then(()=>CNe);return{TaskStatus:ue}},void 0,import.meta.url);if(oe()){const{swTaskQueueService:ue}=await ln(async()=>{const{swTaskQueueService:Te}=await Promise.resolve().then(()=>g3);return{swTaskQueueService:Te}},void 0,import.meta.url);await ue.initialize(),await ue.syncTasksFromSW()}const{chatWorkflowClient:ce}=await ln(async()=>{const{chatWorkflowClient:ue}=await Promise.resolve().then(()=>Uje);return{chatWorkflowClient:ue}},void 0,import.meta.url),me=await ce.getAllActiveWorkflows(),ve=new Set(me.map(ue=>ue.id)),{workflowSubmissionService:N}=await ln(async()=>{const{workflowSubmissionService:ue}=await Promise.resolve().then(()=>lH);return{workflowSubmissionService:ue}},void 0,import.meta.url),he=await N.queryAllWorkflows(),fe=new Set(he.map(ue=>ue.id)),{taskQueueService:ne}=await ln(async()=>{const{taskQueueService:ue}=await Promise.resolve().then(()=>U9);return{taskQueueService:ue}},void 0,import.meta.url),ie=de.getAllWorkZones(m);for(const ue of ie){const Te=he.find(Ye=>Ye.id===ue.workflow.id),De=ue.workflow.steps.some(Ye=>Ye.status==="running"||Ye.status==="pending");let ye={...ue.workflow,steps:[...ue.workflow.steps]};if(Te&&(Te.steps.length!==ye.steps.length||Te.status!==ye.status)&&(de.updateWorkflow(m,ue.id,{steps:Te.steps,status:Te.status,error:Te.error}),ye={...ye,steps:Te.steps,status:Te.status}),!De&&!Te)continue;const Ne=ve.has(ye.id),Re=fe.has(ye.id),He=Ne||Re,et=ye.steps.map(Ye=>{var _e,We;if(Ye.status!=="running"&&Ye.status!=="pending")return Ye;const je=(_e=Ye.result)==null?void 0:_e.taskId;if(!je)return Ye.mcp==="ai_analyze"?He?Ye:{...Ye,status:"failed",error:"页面刷新导致中断,请删除后重新发起"}:Ye.status==="running"?{...Ye,status:"failed",error:"页面刷新导致中断,请删除后重新发起"}:Ye;const Me=ne.getTask(je);if(!Me)return{...Ye,status:"failed",error:"任务未找到,请重试"};switch(Me.status){case ee.COMPLETED:return{...Ye,status:"completed",result:{taskId:je,result:Me.result}};case ee.FAILED:return{...Ye,status:"failed",error:((We=Me.error)==null?void 0:We.message)||"任务执行失败"};case ee.CANCELLED:return{...Ye,status:"skipped"};case ee.PENDING:case ee.PROCESSING:return Ye;default:return Ye}});et.some((Ye,je)=>{var Me;return Ye.status!==((Me=ye.steps[je])==null?void 0:Me.status)})&&de.updateWorkflow(m,ue.id,{steps:et})}})().catch(de=>{console.error("[Drawnix] Failed to restore WorkZones:",de)})},[m]),x.useEffect(()=>{if(!m)return;let ae=null;return(async()=>{const oe=await ln(()=>Promise.resolve().then(()=>lH),void 0,import.meta.url),{WorkZoneTransforms:ee}=await ln(async()=>{const{WorkZoneTransforms:me}=await Promise.resolve().then(()=>o$);return{WorkZoneTransforms:me}},void 0,import.meta.url),{workflowSubmissionService:ce}=oe;ae=ce.subscribeToAllEvents(me=>{const ve=me,he=ee.getAllWorkZones(m).find(fe=>fe.workflow.id===ve.workflowId);if(he)switch(ve.type){case"step":{const fe=he.workflow.steps.map(ne=>ne.id===ve.stepId?{...ne,status:ve.status||ne.status,result:ve.result??ne.result,error:ve.error??ne.error,duration:ve.duration??ne.duration}:ne);ee.updateWorkflow(m,he.id,{steps:fe});break}case"steps_added":{const fe=(ve.steps||[]).map(ne=>({id:ne.id,mcp:ne.mcp,args:ne.args,description:ne.description,status:ne.status}));ee.updateWorkflow(m,he.id,{steps:[...he.workflow.steps,...fe]});break}case"completed":case"failed":{const fe=ve.type==="completed"?"completed":"failed",ne=he.workflow.steps.map(ie=>{if(ie.status==="running"||ie.status==="pending"){const ue=ie.result;return ue!=null&&ue.taskId?ie:{...ie,status:fe,error:ve.type==="failed"?ve.error:void 0}}return ie});ee.updateWorkflow(m,he.id,{steps:ne});break}case"recovered":{const fe=ve.workflow;fe&&ee.updateWorkflow(m,he.id,{steps:fe.steps,status:fe.status});break}}})})().catch(oe=>{console.error("[Drawnix] Failed to setup workflow sync:",oe)}),()=>{ae==null||ae.unsubscribe()}},[m]);const K=[_q,Tye,DEe,REe,E2e,Xze(W),vHe,PHe,SWe,AHe(W),qHe(W),l9e,b9e,pWe,g9e,ute,hUe,xUe,kUe,lWe],j=x.useRef(null);BWe(),FWe(),iGe({enabled:!0,insertPrompt:!1,groupSimilarTasks:!0}),sGe();const{saveBoard:H,createBoard:L,switchBoard:V}=pVe(),Y=x.useCallback(async()=>{if(r&&R.current){const ae={children:R.current.children||[],viewport:R.current.viewport,theme:R.current.theme};await H(ae)}},[r,H]),q=x.useCallback(async()=>{await Y();const ae=await L({name:"新画布"});ae&&(await V(ae.id),setTimeout(()=>{window.location.reload()},500))},[Y,L,V]),Z=x.useCallback(ae=>{const de=R.current;if(de&&ae){const ee=nt(de).map(ce=>ce.id).filter(Boolean);W({lastSelectedElementIds:ee})}i&&i(ae)},[i,W]),re=x.useMemo(()=>({appState:f,setAppState:G,board:m}),[f,G,m]);return y.jsx(oLe,{children:y.jsx(Dke,{children:y.jsx(qje,{children:y.jsx(V9e,{children:y.jsx(cUe,{onOpenMediaLibrary:z,children:y.jsx(YGe,{children:y.jsx(aVe,{children:y.jsxs(Wee.Provider,{value:re,children:[y.jsx(BUe,{value:e,viewport:t,theme:n,options:d,plugins:K,containerRef:j,appState:f,board:m,setBoard:g,projectDrawerOpen:w,toolboxDrawerOpen:b,taskPanelExpanded:T,mediaLibraryOpen:k,backupRestoreOpen:O,onChange:r,onSelectionChange:Z,onViewportChange:s,onThemeChange:o,onValueChange:a,afterInit:l,onBoardSwitch:c,handleProjectDrawerToggle:M,handleToolboxDrawerToggle:$,handleTaskPanelToggle:A,setProjectDrawerOpen:C,setToolboxDrawerOpen:_,setMediaLibraryOpen:D,setBackupRestoreOpen:I,handleBeforeSwitch:Y,isDataReady:u,onCreateProjectForMemory:q}),y.jsx(x.Suspense,{fallback:null,children:y.jsx(OUe,{isOpen:k,onClose:()=>D(!1)})})]})})})})})})})})},BUe=({value:e,viewport:t,theme:n,options:r,plugins:i,containerRef:s,appState:o,board:a,setBoard:l,projectDrawerOpen:c,toolboxDrawerOpen:u,taskPanelExpanded:d,backupRestoreOpen:f,onChange:h,onSelectionChange:m,onViewportChange:g,onThemeChange:w,onValueChange:C,afterInit:b,onBoardSwitch:_,handleProjectDrawerToggle:T,handleToolboxDrawerToggle:S,handleTaskPanelToggle:k,setProjectDrawerOpen:D,setToolboxDrawerOpen:O,setBackupRestoreOpen:I,handleBeforeSwitch:R,isDataReady:F,onCreateProjectForMemory:M})=>{const{chatDrawerRef:$}=N3();OHe({board:a,pointer:o.pointer});const[A,z]=x.useState(!1),[G,W]=x.useState(null),{state:K,selectShape:j,closePicker:H}=vUe(a);return x.useEffect(()=>{if(!a)return;const L=Y=>{const q=Y.target;if(!(q.closest(".board-host-svg")||q.closest(".plait-board-container")))return;const re=Vt(a,Kt(a,Y.clientX,Y.clientY));if(!Oo(a,re)){const de=[Y.clientX,Y.clientY];W(de),z(!0)}},V=s.current;return V&&V.addEventListener("dblclick",L),()=>{V&&V.removeEventListener("dblclick",L)}},[a,s]),y.jsx("div",{className:Le("drawnix",{"drawnix--mobile":o.isMobile}),ref:s,children:y.jsxs("div",{className:"drawnix__main",children:[y.jsxs(Gye,{value:e,viewport:t,theme:n,options:r,plugins:i,onChange:L=>{h&&h(L)},onSelectionChange:m,onViewportChange:g,onThemeChange:w,onValueChange:C,children:[y.jsx(Upe,{afterInit:L=>{l(L),L.children&&L.children.length>0&&zp.preloadBoardFonts(L.children).catch(V=>{console.warn("Failed to preload board fonts:",V)}),b&&b(L),L.afterChange&&L.afterChange()}}),y.jsx(kWe,{}),y.jsx(qze,{projectDrawerOpen:c,onProjectDrawerToggle:T,toolboxDrawerOpen:u,onToolboxDrawerToggle:S,taskPanelExpanded:d,onTaskPanelToggle:k,onOpenBackupRestore:()=>I(!0)}),y.jsx(D9e,{}),y.jsx(XHe,{}),y.jsx(DHe,{}),y.jsx(BHe,{}),y.jsx(WHe,{}),y.jsx(zHe,{}),o.openDialogType&&y.jsx(x.Suspense,{fallback:null,children:y.jsx(PUe,{container:s.current})}),y.jsx(KHe,{container:s.current}),o.openSettings&&y.jsx(x.Suspense,{fallback:null,children:y.jsx(AUe,{container:s.current})}),f&&y.jsx(x.Suspense,{fallback:null,children:y.jsx(MUe,{open:f,onOpenChange:I,container:s.current,onBeforeImport:async()=>{R&&await R()},onSwitchBoard:async(L,V)=>{const Y=await qn.switchBoard(L);Y&&_&&(V&&(Y.viewport=V),_(Y))}})}),y.jsx(lUe,{position:G,visible:A,onClose:()=>z(!1)}),y.jsx(gUe,{visible:K.visible,position:K.position,currentShape:K.currentShape||void 0,onSelectShape:j,onClose:H,container:s.current}),y.jsx(zne,{isDataReady:F}),y.jsx(tUe,{}),y.jsx(bVe,{})]}),y.jsx(PWe,{}),y.jsx(aUe,{container:s.current,onCreateProject:M}),y.jsx(Mne,{ref:$}),y.jsx(x.Suspense,{fallback:null,children:y.jsx(DUe,{isOpen:c,onOpenChange:D,onBeforeSwitch:R,onBoardSwitch:_})}),y.jsx(x.Suspense,{fallback:null,children:y.jsx(IUe,{isOpen:u,onOpenChange:O})})]})})},qne="main_board_content",Xne=pi.createInstance({name:"Drawnix",storeName:WNe,driver:[pi.INDEXEDDB,pi.LOCALSTORAGE]});async function Yne(){try{const e=await tr.loadState();return(e==null?void 0:e.migrationCompleted)===!0}catch(e){return console.error("[WorkspaceMigration] Failed to check migration status:",e),!1}}async function mH(){try{const e=await tr.loadState();e.migrationCompleted=!0,await tr.saveState(e)}catch(e){console.error("[WorkspaceMigration] Failed to mark migration completed:",e)}}async function LUe(){try{const e=await Xne.getItem(qne);if(e&&e.children&&e.children.length>0)return e;const t=localStorage.getItem(mee);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 NUe(){try{if(await Yne())return null;const t=await LUe();if(!t||!t.children||t.children.length===0)return await mH(),null;const n=Yo.getInstance();await n.initialize();const r=await n.createBoard({name:"迁移的画板",elements:t.children,viewport:t.viewport,theme:t.theme});return r?(await n.switchBoard(r.id),await mH(),await jUe(),r.id):(console.error("[WorkspaceMigration] Failed to create board"),null)}catch(e){return console.error("[WorkspaceMigration] Migration failed:",e),null}}async function jUe(){try{await Xne.removeItem(qne),localStorage.removeItem(mee)}catch(e){console.error("[WorkspaceMigration] Failed to clear legacy data:",e)}}function k0(e){if(!qt.isAnalyticsEnabled())return;const t=FUe(e.name,e.value),n={[`$web_vitals_${e.name}_value`]:e.value,[`$web_vitals_${e.name}_event`]:{id:e.id,delta:e.delta,rating:t,navigationType:e.navigationType},page_url:window.location.href,page_path:window.location.pathname,referrer:document.referrer,timestamp:Date.now()};qt.track("$web_vitals",n)}function FUe(e,t){const r={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 r?t<=r.good?"good":t<=r.poor?"needs-improvement":"poor":"needs-improvement"}async function $Ue(){try{const e=await ln(()=>import("./web-vitals-DcvjKPr-.js"),[],import.meta.url),{onCLS:t,onFCP:n,onLCP:r,onTTFB:i,onINP:s}=e;t(k0),n(k0),r(k0),i(k0),s(k0)}catch(e){console.error("[Web Vitals] Failed to initialize monitoring:",e)}}const b1="page_report";function zUe(){const e=window.innerWidth;return e<768?"mobile":e<1024?"tablet":"desktop"}function HUe(){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:zUe(),user_agent:navigator.userAgent,language:navigator.language,timestamp:Date.now()}}function WUe(){if(!window.performance)return null;const e={page_url:window.location.href,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,r)=>n+(r.transferSize||0),0)}return e}function bx(){if(!qt.isAnalyticsEnabled())return;const e=HUe();qt.track("page_view",{category:b1,...e})}function vH(){if(!qt.isAnalyticsEnabled())return;const e=WUe();if(!e){console.warn("[Page Report] Performance data not available");return}qt.track("page_performance",{category:b1,...e})}function GUe(){if(!qt.isAnalyticsEnabled())return;const e=Math.round(performance.now());qt.track("page_unload",{category:b1,page_url:window.location.href,page_path:window.location.pathname,time_on_page:e,timestamp:Date.now()})}function VUe(){try{bx(),document.readyState==="complete"?vH():window.addEventListener("load",()=>{setTimeout(()=>{vH()},0)}),window.addEventListener("beforeunload",()=>{GUe()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?qt.track("page_hidden",{category:b1,page_url:window.location.href,page_path:window.location.pathname,timestamp:Date.now()}):document.visibilityState==="visible"&&qt.track("page_visible",{category:b1,page_url:window.location.href,page_path:window.location.pathname,timestamp:Date.now()})}),window.addEventListener("popstate",()=>{setTimeout(()=>{bx()},100)});const e=history.pushState,t=history.replaceState;history.pushState=function(...n){e.apply(this,n),setTimeout(()=>{bx()},100)},history.replaceState=function(...n){t.apply(this,n),setTimeout(()=>{bx()},100)}}catch(e){console.error("[Page Report] Failed to initialize monitoring:",e)}}function UUe(){if(typeof window>"u")return()=>{};const e=r=>{r.touches.length>1&&(r.preventDefault(),r.stopPropagation())},t=r=>{r.preventDefault(),r.stopPropagation()},n=r=>{(r.ctrlKey||r.metaKey)&&r.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 iD=XE.DB_CLEANUP_DONE;function Zne(){let e=0;for(const t of oZ)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 Qne(){localStorage.getItem(iD)||(Zne(),localStorage.setItem(iD,Date.now().toString()))}function KUe(){localStorage.removeItem(iD)}typeof window<"u"&&(window.__dbCleanup={run:Qne,reset:KUe,cleanupLS:Zne,LS_KEYS_DEPRECATED:oZ});const $3=[{lsKey:Fr.PROMPT_HISTORY,idbKey:Fr.PROMPT_HISTORY,deleteAfterMigration:!0},{lsKey:Fr.VIDEO_PROMPT_HISTORY,idbKey:Fr.VIDEO_PROMPT_HISTORY,deleteAfterMigration:!0},{lsKey:Fr.PRESET_SETTINGS,idbKey:Fr.PRESET_SETTINGS,deleteAfterMigration:!0},{lsKey:Fr.BATCH_IMAGE_CACHE,idbKey:Fr.BATCH_IMAGE_CACHE,deleteAfterMigration:!0},{lsKey:Fr.RECENT_TEXT_COLORS,idbKey:Fr.RECENT_TEXT_COLORS,deleteAfterMigration:!0},{lsKey:Fr.CUSTOM_GRADIENTS,idbKey:Fr.CUSTOM_GRADIENTS,deleteAfterMigration:!0},{lsKey:Fr.CUSTOM_FONTS,idbKey:Fr.CUSTOM_FONTS,deleteAfterMigration:!0},{lsKey:Fr.TOOLBAR_CONFIG,idbKey:Fr.TOOLBAR_CONFIG,deleteAfterMigration:!0}];function z3(){try{return localStorage.getItem(XE.LS_TO_IDB_MIGRATION_DONE)!==null}catch{return!1}}function qUe(){try{localStorage.setItem(XE.LS_TO_IDB_MIGRATION_DONE,Date.now().toString())}catch(e){console.error("[StorageMigration] Failed to mark migration done:",e)}}function XUe(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 yH(e){try{localStorage.removeItem(e)}catch(t){console.warn(`[StorageMigration] Failed to delete ${e} from LocalStorage:`,t)}}async function YUe(e){const{lsKey:t,idbKey:n,deleteAfterMigration:r}=e;try{const i=XUe(t);return i===null?{key:t,success:!0}:await Or.get(n)!==null?(r&&yH(t),{key:t,success:!0}):(await Or.set(n,i),await Or.get(n)===null?{key:t,success:!1,error:"Verification failed: data not found after write"}:(r&&yH(t),{key:t,success:!0}))}catch(i){const s=i instanceof Error?i.message:String(i);return console.error(`[StorageMigration] Failed to migrate ${t}:`,i),{key:t,success:!1,error:s}}}async function Jne(){if(!Or.isAvailable())return console.warn("[StorageMigration] IndexedDB not available, skipping migration"),[];if(z3())return[];const e=[];for(const n of $3){const r=await YUe(n);e.push(r),r.success||console.warn(`[StorageMigration] Failed: ${r.key} - ${r.error}`)}return e.filter(n=>n.success).length,e.filter(n=>!n.success).length===0&&qUe(),e}function ere(){try{localStorage.removeItem(XE.LS_TO_IDB_MIGRATION_DONE)}catch(e){console.error("[StorageMigration] Failed to reset migration status:",e)}}const ZUe={isMigrationDone:z3,runMigration:Jne,resetMigration:ere,MIGRATION_CONFIGS:$3};typeof window<"u"&&(window.__storageMigration={run:Jne,reset:ere,isDone:z3,configs:$3});const QUe=500;let wH=!1;function JUe(){const[e,t]=x.useState(!0),[n,r]=x.useState(!1),[i,s]=x.useState({children:[]}),o=x.useRef(),a=x.useRef(null);x.useEffect(()=>{(async()=>{if(wH){const f=Yo.getInstance();await f.waitForInitialization();const h=f.getCurrentBoard();h&&s({children:h.elements||[],viewport:h.viewport,theme:h.theme}),t(!1);return}wH=!0;try{const f=Yo.getInstance();await f.initialize(),await Yne()||await NUe();let m=f.getCurrentBoard();if(!m&&!f.hasBoards()){const g=await f.createBoard({name:"我的画板1",elements:[]});g&&(m=await f.switchBoard(g.id))}if(m){const g=m.elements||[];s({children:g,viewport:m.viewport,theme:m.theme}),xH(g).then(w=>{w!==g&&s(C=>({...C,children:w}))}).catch(w=>{console.error("[App] Video URL recovery failed:",w)})}}catch(f){console.error("[App] Initialization failed:",f)}finally{r(!0),t(!1)}})()},[]);const l=x.useCallback(async d=>{const f=await xH(d.elements||[]);s({children:f,viewport:d.viewport,theme:d.theme})},[]),c=x.useCallback(d=>{s(d),o.current=d.viewport,Yo.getInstance().saveCurrentBoard(d).catch(h=>{console.error("[App] Failed to save board:",h)})},[]),u=x.useCallback(d=>{o.current=d,a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{const f=Yo.getInstance(),h=f.getCurrentBoard();h&&f.saveCurrentBoard({children:h.elements,viewport:d,theme:h.theme}).catch(m=>{console.error("[App] Failed to save viewport:",m)})},QUe)},[]);return x.useEffect(()=>{const d=()=>{a.current&&(clearTimeout(a.current),a.current=null);const m=o.current;if(m){const g=Yo.getInstance(),w=g.getCurrentBoard();w&&(w.viewport=m,g.saveCurrentBoard({children:w.elements,viewport:m,theme:w.theme}).catch(()=>{}))}},f=()=>{d()},h=()=>{document.visibilityState==="hidden"&&d()};return window.addEventListener("beforeunload",f),document.addEventListener("visibilitychange",h),()=>{window.removeEventListener("beforeunload",f),document.removeEventListener("visibilitychange",h),a.current&&clearTimeout(a.current)}},[]),e?y.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100vh"},children:"加载中..."}):y.jsx("div",{style:{height:"100vh"},children:y.jsx(RUe,{value:i.children,viewport:i.viewport,theme:i.theme,onChange:c,onViewportChange:u,onBoardSwitch:l,isDataReady:n,afterInit:d=>{window.__drawnix__web__console=f=>{eKe(d,f)}}})})}const eKe=(e,t)=>{const n=Q.getBoardContainer(e).closest(".drawnix");let r=n.querySelector(".drawnix-console");r||(r=document.createElement("div"),r.classList.add("drawnix-console"),n.append(r));const i=document.createElement("div");i.innerHTML=t,r.append(i)};async function xH(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 r=n.indexOf("#merged-video-");if(r!==-1){const i=n.substring(r+1),s=i.indexOf("#",1),a=`/__aitu_cache__/video/${s>0?i.substring(0,s):i}.mp4`;return{...t,url:a}}}return t})}const tKe=3e4,nKe=800,rKe=.6,iKe=3,H3="aitu_last_snapshot",sKe=50,bH=3e3,oKe=1e4,aKe=200,lKe=5e3,cKe=10,uKe=5e3,dKe=30,fKe=20,CH=20,hKe=100,pKe=30;let EH=null,SH=!1,_H=null,TH=null,lk=null,ck=0,kf=60,U0=!1,uk=!1;const Zc=[],Ff=[],bl=[];function gKe(e){const t=ss(),n=Date.now();return()=>{const r=ss();if(!t||!r)return;const i=(r.usedJSHeapSize-t.usedJSHeapSize)/(1024*1024),s=Date.now()-n;if(Math.abs(i)>=sKe){const o=i>=0?"+":"";console.warn(`[MemoryLog] ${e}: ${o}${i.toFixed(0)} MB (${s}ms)`)}}}function ss(){if(typeof performance<"u"&&"memory"in performance){const e=performance.memory;return{usedJSHeapSize:e.usedJSHeapSize,totalJSHeapSize:e.totalJSHeapSize,jsHeapSizeLimit:e.jsHeapSizeLimit}}}function Vg(){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 oa(e){var t;try{(t=navigator.serviceWorker)!=null&&t.controller&&navigator.serviceWorker.controller.postMessage({type:"CRASH_SNAPSHOT",snapshot:e})}catch(n){console.warn("[MemoryLog] Failed to send snapshot to SW:",n)}}function mKe(e){try{localStorage.setItem(H3,JSON.stringify(e))}catch{}}function vKe(){try{const e=localStorage.getItem(H3);if(e)return JSON.parse(e)}catch{}return null}function yKe(){try{localStorage.removeItem(H3)}catch{}}function wKe(){const e={id:`startup-${Date.now()}`,timestamp:Date.now(),type:"startup",userAgent:navigator.userAgent,url:location.href,memory:ss()};oa(e)}function xKe(){if(EH!==null)return;let e=0;EH=window.setInterval(()=>{const t=ss();if(!t)return;const n=t.usedJSHeapSize/(1024*1024),r=t.jsHeapSizeLimit/(1024*1024),i=n/r;if(n>nKe||i>rKe){e++;const a=e>=iKe?Vg():void 0,l={id:`periodic-${Date.now()}`,timestamp:Date.now(),type:"periodic",memory:t,pageStats:a,userAgent:navigator.userAgent,url:location.href};oa(l)}else e=0},tKe)}function bKe(){window.addEventListener("error",e=>{var n;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:ss(),userAgent:navigator.userAgent,url:location.href,customData:{recentActions:Zc.slice(-10),filename:e.filename,lineno:e.lineno,colno:e.colno}};oa(t),console.error("[MemoryLog] Uncaught error captured:",e.message)}),window.addEventListener("unhandledrejection",e=>{const t=e.reason,n={id:`rejection-${Date.now()}`,timestamp:Date.now(),type:"error",error:{message:(t==null?void 0:t.message)||String(t)||"Unhandled Promise rejection",stack:t==null?void 0:t.stack,type:"unhandledRejection"},memory:ss(),userAgent:navigator.userAgent,url:location.href,customData:{recentActions:Zc.slice(-10)}};oa(n),console.error("[MemoryLog] Unhandled rejection captured:",t)}),window.addEventListener("beforeunload",()=>{const e=ss();if(e){const t={id:`beforeunload-${Date.now()}`,timestamp:Date.now(),type:"beforeunload",memory:e,userAgent:navigator.userAgent,url:location.href};mKe(t),oa(t)}})}function CKe(){if(_H!==null)return;let e=Date.now();document.addEventListener("visibilitychange",()=>{document.hidden?uk=!0:(e=Date.now(),setTimeout(()=>{uk=!1},bH+100))}),_H=window.setInterval(()=>{var r;const t=Date.now(),n=t-e;if(n>oKe&&!uk&&!document.hidden){const i={id:`freeze-${Date.now()}`,timestamp:Date.now(),type:"freeze",memory:ss(),pageStats:Vg(),performance:{freezeDuration:n,lastHeartbeat:e,fps:kf},userAgent:navigator.userAgent,url:location.href,customData:{recentActions:Zc.slice(-10),recentErrors:Ff.slice(-5),recentNetworkErrors:bl.slice(-5)}};oa(i)}e=t,(r=navigator.serviceWorker)!=null&&r.controller&&navigator.serviceWorker.controller.postMessage({type:"HEARTBEAT",timestamp:t})},bH)}function EKe(){if(lk===null&&!(typeof PerformanceObserver>"u"))try{lk=new PerformanceObserver(e=>{for(const t of e.getEntries())if(t.duration>aKe){const r=t.attribution;let i;if(r&&r.length>0){const o=r[0];i={name:o.name,containerType:o.containerType,containerSrc:o.containerSrc,containerId:o.containerId,containerName:o.containerName}}const s={id:`longtask-${Date.now()}`,timestamp:Date.now(),type:"longtask",memory:ss(),performance:{longTaskDuration:t.duration,fps:kf},userAgent:navigator.userAgent,url:location.href,customData:{taskName:t.name,startTime:t.startTime,attribution:i,debugTip:"Use Chrome DevTools Performance panel to record and analyze the call stack"}};oa(s)}}),lk.observe({entryTypes:["longtask"]})}catch{}}function SKe(){if(TH!==null)return;let e=0;const t=()=>{if(e++,e>=pKe){const n=performance.now(),r=n-ck;r>0&&(kf=Math.round(e*1e3/r)),e=0,ck=n}requestAnimationFrame(t)};ck=performance.now(),requestAnimationFrame(t),TH=window.setInterval(()=>{if(kf<cKe&&kf>0){const n={id:`lowfps-${Date.now()}`,timestamp:Date.now(),type:"freeze",memory:ss(),performance:{fps:kf},userAgent:navigator.userAgent,url:location.href};oa(n)}},lKe)}function _Ke(){setTimeout(()=>{kH()},uKe),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&!U0&&setTimeout(kH,1e3)})}function kH(){if(U0)return;const e=document.getElementById("root"),t=e&&e.children.length>0,r=!!document.querySelector(".plait-board-container");if(document.body.children.length>1,e&&!t){U0=!0;const i={id:`whitescreen-${Date.now()}`,timestamp:Date.now(),type:"whitescreen",memory:ss(),pageStats:{domNodeCount:document.getElementsByTagName("*").length,canvasCount:0,imageCount:0,videoCount:0,iframeCount:0,plaitBoardExists:r},userAgent:navigator.userAgent,url:location.href,customData:{rootExists:!!e,rootChildCount:(e==null?void 0:e.children.length)||0,bodyChildCount:document.body.children.length,hasPlaitBoard:r}};oa(i),console.error("[MemoryLog] 白屏检测: React 未渲染内容")}t&&!r&&location.pathname==="/"&&setTimeout(()=>{if(!document.querySelector(".plait-board-container")&&!U0){U0=!0;const i={id:`whitescreen-noboard-${Date.now()}`,timestamp:Date.now(),type:"whitescreen",memory:ss(),pageStats:Vg(),userAgent:navigator.userAgent,url:location.href,customData:{reason:"画板未加载",rootChildCount:(e==null?void 0:e.children.length)||0}};oa(i),console.error("[MemoryLog] 白屏检测: 画板组件未加载")}},5e3)}function K0(e,t,n){Zc.push({time:Date.now(),action:e,target:t,detail:n}),Zc.length>dKe&&Zc.shift()}function TKe(){let e=0;document.addEventListener("click",t=>{const n=Date.now();if(n-e<hKe)return;e=n;const r=t.target;if(!r)return;const i=()=>{var a,l,c,u,d,f,h,m,g,w,C,b,_,T,S;let s="";const o=(l=(a=r.closest)==null?void 0:a.call(r,"[data-track]"))==null?void 0:l.getAttribute("data-track");if(o)s=o;else if(r.tagName==="BUTTON"||(c=r.closest)!=null&&c.call(r,"button")){const k=((u=r.closest)==null?void 0:u.call(r,"button"))||r,D=(d=k.textContent)==null?void 0:d.trim().slice(0,20),O=(g=(m=(h=(f=k.className)==null?void 0:f.split)==null?void 0:h.call(f," "))==null?void 0:m[0])==null?void 0:g.slice(0,20);s=`btn:${D||O||"unknown"}`}else if(r.tagName==="A")s=`link:${((w=r.pathname)==null?void 0:w.slice(0,30))||""}`;else if(r.tagName==="INPUT"||r.tagName==="TEXTAREA"){const k=r;s=`input:${k.name||k.type||((C=k.placeholder)==null?void 0:C.slice(0,15))||""}`}else if(r.id)s=`#${r.id}`;else{const k=(T=(_=(b=r.className)==null?void 0:b.split)==null?void 0:_.call(b," "))==null?void 0:T[0];s=k?`.${k.slice(0,20)}`:((S=r.tagName)==null?void 0:S.toLowerCase())||"unknown"}K0("click",s)};"requestIdleCallback"in window?window.requestIdleCallback(i,{timeout:100}):setTimeout(i,0)},{capture:!0,passive:!0}),document.addEventListener("keydown",t=>{if(t.ctrlKey||t.metaKey||t.altKey){const n=[];(t.ctrlKey||t.metaKey)&&n.push("Cmd"),t.altKey&&n.push("Alt"),t.shiftKey&&n.push("Shift"),n.push(t.key),K0("shortcut",n.join("+"))}},{capture:!0,passive:!0}),window.addEventListener("popstate",()=>{K0("navigate",location.pathname)}),window.addEventListener("hashchange",()=>{K0("navigate",location.hash)})}function kKe(){const e=window.fetch;window.fetch=async function(t,n){const r=Date.now();try{const i=await e.call(this,t,n);if(!i.ok){const s=typeof t=="string"?t:t.url,o=Date.now()-r;bl.push({time:Date.now(),url:s.slice(0,300),method:(n==null?void 0:n.method)||"GET",status:i.status,statusText:i.statusText,duration:o}),bl.length>CH&&bl.shift()}return i}catch(i){const s=typeof t=="string"?t:t.url,o=Date.now()-r;throw bl.push({time:Date.now(),url:s.slice(0,300),method:(n==null?void 0:n.method)||"GET",error:i.message,duration:o}),bl.length>CH&&bl.shift(),i}}}function PKe(){window.addEventListener("error",e=>{var n;const t=e.target;if(t&&t!==window&&t instanceof HTMLElement&&("src"in t||"href"in t)){const r=t.src||t.href,i=(n=t.tagName)==null?void 0:n.toLowerCase();K0("resource_error",i,r==null?void 0:r.slice(0,100))}},{capture:!0})}function AKe(){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 r=[...t];setTimeout(()=>{var o;let i="",s;for(let a=0;a<Math.min(r.length,5);a++){const l=r[a];if(typeof l=="string")i+=l+" ";else if(typeof l=="number"||typeof l=="boolean")i+=String(l)+" ";else if(l instanceof Error)i+=`Error: ${l.message} `,s=l.stack;else if(l&&typeof l=="object")try{const u=Object.keys(l).slice(0,5).map(d=>{const f=l[d];return`${d}:${typeof f=="string"?f.slice(0,20):typeof f}`}).join(",");i+=`{${u}} `}catch{i+=`[${((o=l.constructor)==null?void 0:o.name)||"Object"}] `}}Ff.push({time:Date.now(),message:i.trim().slice(0,500),stack:s}),Ff.length>fKe&&Ff.shift()},0)}}function DKe(){return{userActions:[...Zc],consoleErrors:[...Ff],networkErrors:[...bl],memory:ss(),pageStats:Vg(),fps:kf}}function IKe(){typeof window>"u"||(window.__memoryLog={getMemory:()=>{const e=ss();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:gKe,diagnose:()=>{const e=ss(),t=Vg();if(console.group("[MemoryLog] 内存诊断"),e){const n=e.usedJSHeapSize/1048576,r=e.jsHeapSizeLimit/(1024*1024),i=n/r*100;console.log(`内存: ${n.toFixed(0)} MB / ${r.toFixed(0)} MB (${i.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:ss(),pageStats:Vg(),userAgent:navigator.userAgent,url:location.href};oa(e)},getDiagnostics:DKe,getActions:()=>(console.table(Zc.map(e=>({time:new Date(e.time).toLocaleTimeString("zh-CN"),action:e.action,target:e.target,detail:e.detail}))),Zc),getNetworkErrors:()=>(console.table(bl.map(e=>({time:new Date(e.time).toLocaleTimeString("zh-CN"),url:e.url,status:e.status,error:e.error}))),bl),getConsoleErrors:()=>(console.table(Ff.map(e=>({time:new Date(e.time).toLocaleTimeString("zh-CN"),message:e.message.slice(0,100)}))),Ff)})}function OKe(){if(SH)return;SH=!0,wKe(),bKe(),xKe(),CKe(),EKe(),SKe(),_Ke(),TKe(),kKe(),PKe(),AKe(),IKe();const e=vKe();e&&(e.customData={...e.customData,recovered:!0,recoveredAt:Date.now()},oa(e),yKe())}const PH=window.addEventListener.bind(window),MKe=window.removeEventListener.bind(window);let W3=null;window.addEventListener=function(e,t,n){if(e==="unload"){console.warn("[Permissions Policy] Blocked unload event listener");return}return e==="beforeunload"&&(W3=t),PH.call(window,e,t,n)};window.removeEventListener=function(e,t,n){return e==="beforeunload"&&(W3=null),MKe.call(window,e,t,n)};window.__checkBeforeUnload=()=>!!W3;let AH=!1,Hu=!1;const Ec={error:console.error,warn:console.warn,info:console.info,log:console.log,debug:console.debug};function Jd(e,t,n){var r;(r=navigator.serviceWorker)!=null&&r.controller&&navigator.serviceWorker.controller.postMessage({type:"SW_CONSOLE_LOG_REPORT",logLevel:e,logMessage:t,logStack:n||"",logSource:window.location.href})}function P0(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 DH(e){for(const t of e)if(t instanceof Error&&t.stack)return t.stack;return""}function RKe(){AH||"serviceWorker"in navigator&&(AH=!0,navigator.serviceWorker.addEventListener("message",e=>{var t,n,r,i;if(((t=e.data)==null?void 0:t.type)==="SW_DEBUG_STATUS"){const s=Hu;Hu=((n=e.data.status)==null?void 0:n.debugModeEnabled)||!1,Hu&&!s&&Ec.log("[SW Console Capture] 调试模式已开启,开始捕获所有日志")}else((r=e.data)==null?void 0:r.type)==="SW_DEBUG_ENABLED"?(Hu=!0,Ec.log("[SW Console Capture] 调试模式已开启,开始捕获所有日志")):((i=e.data)==null?void 0:i.type)==="SW_DEBUG_DISABLED"&&(Hu=!1,Ec.log("[SW Console Capture] 调试模式已关闭,仅捕获 warn/error"))}),navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"SW_DEBUG_GET_STATUS"}),navigator.serviceWorker.addEventListener("controllerchange",()=>{navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"SW_DEBUG_GET_STATUS"})}),console.error=function(...e){Ec.error.apply(console,e),Jd("error",P0(e),DH(e))},console.warn=function(...e){Ec.warn.apply(console,e),Jd("warn",P0(e),DH(e))},console.log=function(...e){Ec.log.apply(console,e),Hu&&Jd("log",P0(e),"")},console.info=function(...e){Ec.info.apply(console,e),Hu&&Jd("info",P0(e),"")},console.debug=function(...e){Ec.debug.apply(console,e),Hu&&Jd("debug",P0(e),"")},window.addEventListener("error",e=>{var n;const t=`${e.message} at ${e.filename}:${e.lineno}:${e.colno}`;Jd("error",t,((n=e.error)==null?void 0:n.stack)||"")}),window.addEventListener("unhandledrejection",e=>{const t=e.reason,n=t instanceof Error?t.message:`Unhandled Promise: ${String(t)}`,r=t instanceof Error&&t.stack||"";Jd("error",n,r)}),Ec.log("[SW Console Capture] 已初始化"))}OKe();kce({dsn:"https://a18e755345995baaa0e1972c4cf24497@o4510700882296832.ingest.us.sentry.io/4510700883869696",sendDefaultPii:!0});typeof window<"u"&&(UUe(),Qne().catch(e=>{console.warn("[Main] Database cleanup failed:",e)}),ZUe.runMigration().then(()=>Promise.all([fS(),cf.initializeAsync()])).catch(e=>{console.warn("[Main] Storage migration/init failed:",e)}));if(typeof window<"u"){setTimeout(()=>{SC.start(),SC.logMemoryStatus()},5e3);const e=()=>{window.posthog?($Ue(),VUe()):setTimeout(e,500)};setTimeout(e,1e3)}if("serviceWorker"in navigator){const e=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1";let t=null,n=!1,r=null;window.addEventListener("load",()=>{navigator.serviceWorker.register("/sw.js").then(i=>{r=i,RKe(),e&&(i.update().catch(s=>console.warn("Forced update check failed:",s)),i.waiting&&i.waiting.postMessage({type:"SKIP_WAITING"})),i.addEventListener("updatefound",()=>{const s=i.installing;s&&s.addEventListener("statechange",()=>{s.state==="installed"&&navigator.serviceWorker.controller&&(t=s,e?s.postMessage({type:"SKIP_WAITING"}):window.dispatchEvent(new CustomEvent("sw-update-available",{detail:{version:"new"}})))})}),setInterval(()=>{i.update().catch(s=>{console.warn("Update check failed:",s)})},300*1e3)}).catch(i=>{})}),navigator.serviceWorker.addEventListener("message",i=>{if(i.data&&i.data.type==="SW_UPDATED"){if(!n)return;setTimeout(()=>{window.location.reload()},1e3)}else i.data&&i.data.type==="CACHE_CLEANUP_COMPLETE"||(i.data&&i.data.type==="SW_NEW_VERSION_READY"?window.dispatchEvent(new CustomEvent("sw-update-available",{detail:{version:i.data.version}})):i.data&&i.data.type==="SW_UPGRADING"||i.data&&i.data.type)}),navigator.serviceWorker.addEventListener("controllerchange",()=>{n&&setTimeout(()=>{window.location.reload()},1e3)}),window.addEventListener("user-confirmed-upgrade",()=>{if(n=!0,t){t.postMessage({type:"SKIP_WAITING"});return}if(r&&r.waiting){r.waiting.postMessage({type:"SKIP_WAITING"});return}caches.keys().then(i=>{const s=i.filter(o=>o.startsWith("drawnix-static-v"));return Promise.all(s.map(o=>caches.delete(o)))}).finally(()=>{window.location.href=window.location.href.split("?")[0]+"?_t="+Date.now()})})}const BKe=C1.createRoot(document.getElementById("root"));BKe.render(y.jsx(x.StrictMode,{children:y.jsx(JUe,{})}));const LKe=Object.freeze(Object.defineProperty({__proto__:null,SWCapabilitiesHandler:Fne,swCapabilitiesHandler:PVe},Symbol.toStringTag,{value:"Module"})),tre=Object.freeze(Object.defineProperty({__proto__:null,AssetItem:v3,MediaLibraryEmpty:zee,MediaLibraryGrid:Vee,MediaLibraryInspector:jA,MediaLibraryModal:dS,MediaLibrarySidebar:Kee,MediaLibraryStorageBar:Uee},Symbol.toStringTag,{value:"Module"}));export{ht as $,c1 as A,cv as B,Mi as C,jn as D,$g as E,IA as F,Oc as G,rqe as H,br as I,y as J,VHe as K,UHe as L,Di as M,eqe as N,nqe as O,wS as P,m3 as Q,Kr as R,Or as S,Ke as T,Fr as U,tqe as V,xt as W,Ic as X,iZ as Y,ln as Z,ur as _,WKe as a,oy as a$,Zee as a0,QNe as a1,I8e as a2,Jo as a3,dS as a4,ym as a5,sh as a6,GLe as a7,pFe as a8,qn as a9,vo as aA,td as aB,Io as aC,YE as aD,fZ as aE,er as aF,Ii as aG,cn as aH,Le as aI,Xe as aJ,_7 as aK,J as aL,y5 as aM,st as aN,MQ as aO,Es as aP,L5 as aQ,s3e as aR,r3e as aS,OQ as aT,kc as aU,Ap as aV,pVe as aW,Oze as aX,tn as aY,Th as aZ,Vte as a_,tr as aa,OO as ab,GEe as ac,pi as ad,iu as ae,cy as af,fS as ag,OFe as ah,x3 as ai,ite as aj,AFe as ak,f1 as al,G8e as am,uZ as an,APe as ao,rDe as ap,N5e as aq,tDe as ar,c5 as as,_Z as at,yZ as au,gZ as av,qi as aw,mZ as ax,sDe as ay,kZ as az,HKe as b,t5e as b$,A3 as b0,dy as b1,bS as b2,P3 as b3,Gg as b4,qte as b5,X as b6,ci as b7,Ur as b8,lhe as b9,Ro as bA,fl as bB,Og as bC,N5 as bD,I6e as bE,sr as bF,lu as bG,as as bH,Rd as bI,sy as bJ,YKe as bK,wRe as bL,ty as bM,Ui as bN,JKe as bO,Ol as bP,p5 as bQ,SAe as bR,SPe as bS,LIe as bT,NDe as bU,pA as bV,u5e as bW,aC as bX,o5e as bY,iDe as bZ,z5e as b_,tc as ba,hm as bb,xE as bc,yt as bd,lm as be,Bt as bf,WI as bg,Gn as bh,wg as bi,qc as bj,MI as bk,kt as bl,ct as bm,Eo as bn,Nn as bo,l5 as bp,X5e as bq,GN as br,IPe as bs,J1 as bt,Q1 as bu,M5e as bv,r5 as bw,s5 as bx,ey as by,U5e as bz,Ft as c,lh as c$,Q5e as c0,$3e as c1,A7 as c2,a3e as c3,S7 as c4,Kl as c5,cu as c6,j5 as c7,rS as c8,B3e as c9,So as cA,ine as cB,Lze as cC,gp as cD,ma as cE,TVe as cF,Mo as cG,FFe as cH,pqe as cI,$Ke as cJ,dqe as cK,fqe as cL,FKe as cM,NFe as cN,hqe as cO,lqe as cP,aqe as cQ,F0 as cR,R8e as cS,ZJ as cT,RLe as cU,ig as cV,Ize as cW,xS as cX,Rze as cY,Co as cZ,wm as c_,D6e as ca,Ml as cb,ZKe as cc,L3e as cd,jne as ce,gqe as cf,zc as cg,yx as ch,Q as ci,pu as cj,qu as ck,Pc as cl,jKe as cm,Kk as cn,RE as co,Gye as cp,_q as cq,DEe as cr,Tye as cs,E2e as ct,Vbe as cu,Upe as cv,XKe as cw,Hr as cx,GX as cy,na as cz,Xl as d,KX as d0,uS as d1,Xee as d2,rne as d3,uqe as d4,cqe as d5,ES as d6,oqe as d7,iqe as d8,sqe as d9,WX as da,WSe as db,IE as dc,OE as dd,vt as de,CS as df,Nie as dg,BTe as dh,VE as di,e5 as dj,UE as dk,UKe as dl,qKe as dm,KKe as dn,VKe as dp,_Te as dq,wf as dr,R6 as ds,NKe as dt,Av as du,QKe as dv,Pee as e,z0 as f,An as g,G7e as h,zKe as i,Fje as j,r3 as k,K1 as l,ZE as m,ws as n,o1 as o,o5 as p,sC as q,x as r,La as s,bn as t,Mn as u,i5 as v,vAe as w,CPe as x,xs as y,a5 as z};