aitu-app 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/assets/{CanvasAudioPlayer-DgcRAPAw.js → CanvasAudioPlayer-HtUs8HDj.js} +1 -1
- package/assets/{ComicCreator-BycaWmuc.js → ComicCreator-DhxXCyJR.js} +2 -2
- package/assets/{DeferredAIInputBar-CwJirFC0.js → DeferredAIInputBar-B2R2-2RU.js} +2 -2
- package/assets/{DrawnixDeferredFeatures-iBvUtWse.js → DrawnixDeferredFeatures-DHTr0c-V.js} +1 -1
- package/assets/{KnowledgeBaseContent-BHBg5nrj.js → KnowledgeBaseContent-CAq5kXdt.js} +3 -3
- package/assets/{MVCreator-j2vSDPdb.js → MVCreator-B9uaRsGE.js} +1 -1
- package/assets/{ModelBenchmarkWorkbench-Dq5hRRXu.js → ModelBenchmarkWorkbench-CK33zizl.js} +1 -1
- package/assets/{MusicAnalyzer-BLhUXQSA.js → MusicAnalyzer-D2NTonEA.js} +1 -1
- package/assets/{PromptHistoryTool-DJngTSmU.js → PromptHistoryTool-q6vOxFr6.js} +1 -1
- package/assets/{ResizableDivider-AjiNRzA1.js → ResizableDivider-BvT-DCEo.js} +1 -1
- package/assets/{TaskQueuePanel-YDHmXxWX.js → TaskQueuePanel-PayswYlG.js} +1 -1
- package/assets/{VideoAnalyzer-Qb6tEi0u.js → VideoAnalyzer-DnowtohS.js} +1 -1
- package/assets/{VideoAnalyzer-BjWgocHv.js → VideoAnalyzer-DoaGlK92.js} +1 -1
- package/assets/{ai-chat-D2kHVW04.js → ai-chat-BnWVpTEI.js} +9 -9
- package/assets/{batch-image-generation-A6_tinN3.js → batch-image-generation-CkmX4dem.js} +1 -1
- package/assets/{bootstrap-Cz9TDvTq.js → bootstrap-CQRLkOtk.js} +6 -6
- package/assets/{clean-confirm-DD8itIZV.js → clean-confirm-CIViVQ8s.js} +1 -1
- package/assets/{diagram-engines-BjFHXhwN.js → diagram-engines-DpAsX7pc.js} +2 -2
- package/assets/{editor-engines-FCgCX6kJ.js → editor-engines-9_72Ghfn.js} +1 -1
- package/assets/{external-skill-service-DuwhmKoU.js → external-skill-service-BN8ZCtPn.js} +1 -1
- package/assets/{frame-size-matcher-D5rWn72p.js → frame-size-matcher-9rxQ-bAY.js} +1 -1
- package/assets/{index-DkwucWUB.js → index-291TeU7i.js} +1 -1
- package/assets/{index-CHHy4efO.js → index-BJ-vS89P.js} +1 -1
- package/assets/{index-D0v91lhB.js → index-BSZAS0wO.js} +1 -1
- package/assets/{index-BECWJUV2.js → index-C7DAD_xK.js} +1 -1
- package/assets/{index-7TrMzH1l.js → index-CIgiIDgZ.js} +1 -1
- package/assets/{index-CBf-BvIi.js → index-CpHWUe__.js} +1 -1
- package/assets/{index-DeHXjhMn.js → index-D1LQ9eQM.js} +1 -1
- package/assets/{index-DsGlObqC.js → index-DRGxmFyd.js} +1 -1
- package/assets/{index-DUugpXxH.js → index-DmtcRYr8.js} +1 -1
- package/assets/{index.es-Dgi90kXH.js → index.es-Ch45-H39.js} +1 -1
- package/assets/{jspdf.es.min-Bm9veIPK.js → jspdf.es.min-bNprb1JY.js} +2 -2
- package/assets/{link-popup-Dw0GTx0j.js → link-popup-B6ReK6iq.js} +1 -1
- package/assets/{markdown-to-drawnix-CDain2y9.js → markdown-to-drawnix-BqT-3zQO.js} +2 -2
- package/assets/{mermaid-to-drawnix-Ddpp0aQq.js → mermaid-to-drawnix-CSctnpU0.js} +2 -2
- package/assets/{model-benchmark-launcher-DLwj4o8h.js → model-benchmark-launcher-DNMp2MLQ.js} +1 -1
- package/assets/{photo-wall-splitter-D2Ji--gy.js → photo-wall-splitter-DhBTEpdG.js} +1 -1
- package/assets/{popup-toolbar-mBe3Bjaq.js → popup-toolbar-BChsudwW.js} +3 -3
- package/assets/{prompt-utils-CatisMlq.js → prompt-utils-BX0pRV-Z.js} +1 -1
- package/assets/{quick-creation-toolbar-jRI3BBKS.js → quick-creation-toolbar-3-AYFpEF.js} +1 -1
- package/assets/{settings-dialog-BOrvJdPV.js → settings-dialog-Ccemaout.js} +1 -1
- package/assets/{size-picker-Blua_9Dv.js → size-picker-DTrdjyLh.js} +1 -1
- package/assets/{skill-dsl-parser-1E3u-6mw.js → skill-dsl-parser-ZR--uu5h.js} +1 -1
- package/assets/{startup-app-BXcHjIQM.js → startup-app-CH3QzBb4.js} +1 -1
- package/assets/{task-sync-CPtlvCdr.js → task-sync-C5XXOQ5m.js} +1 -1
- package/assets/{tool-windows-CSaRGLIT.js → tool-windows-Bf_pMml-.js} +5 -5
- package/assets/{ttd-dialog-RLopc37W.js → ttd-dialog-CohjwODB.js} +2 -2
- package/assets/{ttd-dialog-submit-shortcut-C9_wsIZ5.js → ttd-dialog-submit-shortcut-BVB8O_wE.js} +1 -1
- package/assets/{useCharacters-BCCGOiPW.js → useCharacters-CFlPvydq.js} +1 -1
- package/assets/{useWorkflowSubmission-Bo-icE0J.js → useWorkflowSubmission-CKkOEcAT.js} +2 -2
- package/assets/{video-merge-webcodecs-BWAut6ma.js → video-merge-webcodecs-BInWo9HA.js} +1 -1
- package/assets/{video-recovery-service-L4OR1un7.js → video-recovery-service-DITdD0pC.js} +1 -1
- package/assets/{workflow-generation-utils-CUmdJnGW.js → workflow-generation-utils-e0nRpAgJ.js} +2 -2
- package/assets/{workflow-submission-service-kAjrrvI-.js → workflow-submission-service-BqiL_5Cj.js} +1 -1
- package/changelog.json +87 -6
- package/idle-prefetch-manifest.json +128 -276
- package/manifest.json +3 -3
- package/package.json +1 -1
- package/precache-manifest.json +6 -6
- package/sw.js +1 -1
- package/version.json +58 -3
- package/.DS_Store +0 -0
- package/user-manual/gifs//346/200/235/347/273/264/345/257/274/345/233/276/345/210/233/345/273/272/346/274/224/347/244/272.gif +0 -0
- package/user-manual/screenshots/ai-step-0.png +0 -0
- package/user-manual/screenshots/ai-step-1.png +0 -0
- package/user-manual/screenshots/ai-step-2.png +0 -0
- package/user-manual/screenshots/ai-step-3.png +0 -0
- package/user-manual/screenshots/app-menu.png +0 -0
- package/user-manual/screenshots/backup-restore.png +0 -0
- package/user-manual/screenshots/canvas-tools.png +0 -0
- package/user-manual/screenshots/debug-panel.png +0 -0
- package/user-manual/screenshots/drawing-step-0.png +0 -0
- package/user-manual/screenshots/drawing-step-1.png +0 -0
- package/user-manual/screenshots/drawing-step-2.png +0 -0
- package/user-manual/screenshots/edit-selected.png +0 -0
- package/user-manual/screenshots/element-selected.png +0 -0
- package/user-manual/screenshots/flowchart-step-1.png +0 -0
- package/user-manual/screenshots/flowchart-step-2.png +0 -0
- package/user-manual/screenshots/flowchart-step-3.png +0 -0
- package/user-manual/screenshots/image-preview-empty.png +0 -0
- package/user-manual/screenshots/insert-from-library.png +0 -0
- package/user-manual/screenshots/insert-tools.png +0 -0
- package/user-manual/screenshots/inspiration-step-1.png +0 -0
- package/user-manual/screenshots/inspiration-step-2.png +0 -0
- package/user-manual/screenshots/media-library.png +0 -0
- package/user-manual/screenshots/mindmap-step-1.png +0 -0
- package/user-manual/screenshots/mindmap-step-2.png +0 -0
- package/user-manual/screenshots/mindmap-toolbar-menu.png +0 -0
- package/user-manual/screenshots/project-drawer.png +0 -0
- package/user-manual/screenshots/settings-dialog.png +0 -0
- package/user-manual/screenshots/shape-step-1.png +0 -0
- package/user-manual/screenshots/shape-step-2.png +0 -0
- package/user-manual/screenshots/text-step-1.png +0 -0
- package/user-manual/screenshots/text-step-2.png +0 -0
- package/user-manual/screenshots/toolbox-drawer.png +0 -0
- package/user-manual/screenshots/toolbox-entry.png +0 -0
- package/user-manual/screenshots/video-entry.png +0 -0
- package/user-manual/screenshots/view-navigation.png +0 -0
- package/user-manual/screenshots/zoom-menu.png +0 -0
|
@@ -87,7 +87,7 @@ ${n.description}
|
|
|
87
87
|
${t||Nv}
|
|
88
88
|
${Jo(n)}`}function OL(e,t){return e?typeof e.autoRefreshSourceSignature=="string"?e.autoRefreshSourceSignature===t:e.autoRefreshSourceSignature===null?!1:e.sourceSignature===t:!1}function hye(e){const n=Rm(e.pricingUrl||"")||(e.baseUrl?cye(e.baseUrl):"");return n?{pricingUrl:n,pricingGroup:e.pricingGroup||Nv,cnyPerUsd:e.cnyPerUsd??(uye(e.baseUrl||"")?sye:1)}:null}function v2(e,t=0){return typeof e=="number"&&Number.isFinite(e)?e:t}function Zo(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function fm(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function zK(e){return fm(e.data)&&fm(e.data.group_info)&&Array.isArray(e.data.model_info)}function UK(e){const t=e;return Array.isArray(e.data)&&(!t.group_ratio||fm(t.group_ratio))&&(!t.usable_group||fm(t.usable_group))&&(!t.group_info||fm(t.group_info))&&(!t.group_model_pricing||fm(t.group_model_pricing))}function pye(e){return zK(e)||UK(e)}function mye(e,t,n){if(e.quota_type===1){const i=Jo(e.model_ratio*2*t),o=Jo(e.model_ratio*2*e.model_completion_ratio*t);return{inputCnyMtok:Jo(i*n),outputCnyMtok:Jo(o*n),flatCny:null,billingType:"token"}}const r=Jo(e.model_price*t);return{inputCnyMtok:null,outputCnyMtok:null,flatCny:Jo(r*n),billingType:e.quota_type===2?"per-second":"flat"}}function gye(e,t,n){var s;if(!e)return[];const r=[],i=/tier\(\s*["']([^"']+)["']\s*,\s*sec\s*\*\s*(-?\d+(?:\.\d+)?)\s*\)/g;let o;for(;(o=i.exec(e))!==null;){const a=(s=o[1])==null?void 0:s.trim(),l=Number(o[2]);!a||!Number.isFinite(l)||r.push({label:a,perSecondCny:Jo(l*t*n)})}return r}function yye(e,t,n,r){var c,u,d,f,p,y,v,w,C,x;if(e.billing_mode==="tiered_expr"){const E=gye(e.billing_expr,t,n);if(E.length>0)return{inputCnyMtok:null,outputCnyMtok:null,flatCny:null,billingType:"tiered",tieredCny:E}}const i=e.model_name,o=Zo((c=r==null?void 0:r.model_quota_type)==null?void 0:c[i])??Zo((u=r==null?void 0:r.quota_type)==null?void 0:u[i])??e.quota_type,s=Zo((d=r==null?void 0:r.model_ratio)==null?void 0:d[i])??v2(e.model_ratio),a=Zo((f=r==null?void 0:r.model_price)==null?void 0:f[i])??v2(e.model_price);if(o===2&&a>0){const E=Jo(a*t);return{inputCnyMtok:null,outputCnyMtok:null,flatCny:Jo(E*n),billingType:"per-second"}}if(s>0){const E=Zo((p=r==null?void 0:r.model_completion_ratio)==null?void 0:p[i])??v2(e.completion_ratio,1),_=Jo(s*2*t),I=Jo(s*2*E*t),D=Zo((y=r==null?void 0:r.model_cache_ratio)==null?void 0:y[i])??Zo(e.cache_ratio),P=Zo((v=r==null?void 0:r.model_create_cache_ratio)==null?void 0:v[i])??Zo(e.create_cache_ratio),k=Zo((w=r==null?void 0:r.model_image_ratio)==null?void 0:w[i])??Zo(e.image_ratio),R=Zo((C=r==null?void 0:r.model_audio_ratio)==null?void 0:C[i])??Zo(e.audio_ratio),T=Zo((x=r==null?void 0:r.model_audio_completion_ratio)==null?void 0:x[i])??Zo(e.audio_completion_ratio),M=F=>Jo(F*n);return{inputCnyMtok:M(_),outputCnyMtok:M(I),cacheReadCnyMtok:D!=null?M(_*D):null,cacheCreateCnyMtok:P!=null?M(_*P):null,imageInputCnyMtok:k!=null?M(_*k):null,audioInputCnyMtok:R!=null?M(_*R):null,audioOutputCnyMtok:R!=null&&T!=null?M(_*R*T):null,flatCny:null,billingType:"token"}}const l=Jo(a*t);return{inputCnyMtok:null,outputCnyMtok:null,flatCny:Jo(l*n),billingType:"flat"}}function vye(e){if(typeof e=="string"){const u=e.trim();return u?{path:u,method:"POST"}:null}if(!e||typeof e!="object")return null;const t=typeof e.path=="string"?e.path.trim():"",n=typeof e.method=="string"&&e.method.trim()?e.method.trim().toUpperCase():void 0,r=typeof e.docs=="string"?e.docs.trim():"",i=typeof e.label=="string"?e.label.trim():"",o=typeof e.description=="string"?e.description.trim():"",s=typeof e.scenario=="string"?e.scenario.trim():"",a=Array.isArray(e.highlights)?e.highlights.filter(u=>typeof u=="string"):void 0,l=Array.isArray(e.parameters)?e.parameters:void 0,c=e.request_template!==void 0?e.request_template:void 0;return!t&&!n&&!r&&!i&&!o&&!s&&!(a!=null&&a.length)&&!(l!=null&&l.length)&&c===void 0?null:{...t?{path:t}:{},...n?{method:n}:{},...r?{docs:r}:{},...i?{label:i}:{},...o?{description:o}:{},...s?{scenario:s}:{},...a!=null&&a.length?{highlights:a}:{},...l!=null&&l.length?{parameters:l}:{},...c!==void 0?{request_template:c}:{}}}function wye(e,t){const n=Array.isArray(e.supported_endpoint_types)?e.supported_endpoint_types.map(String):[],r=[e.endpoints,t].filter(Boolean);if(r.length===0)return null;const i={},o=n.length>0?n:Array.from(new Set(r.flatMap(s=>Object.keys(s))));for(const s of o)for(const a of r){const l=vye(a[s]);if(l){i[s]=l;break}}return Object.keys(i).length>0?i:null}function jO(e){return Array.from(new Set([...Object.keys(e.group_ratio||{}),...Object.keys(e.usable_group||{}),...Object.keys(e.group_info||{}),...Object.keys(e.group_model_pricing||{}),...e.data.flatMap(t=>HK(t)).filter(t=>t&&t!=="all")]))}function bye(e,t){var i,o;const n=(i=e.usable_group)==null?void 0:i[t];if(n)return n;const r=(o=e.group_info)==null?void 0:o[t];return typeof r=="string"?r:typeof r=="number"?t:(r==null?void 0:r.DisplayName)||(r==null?void 0:r.display_name)||(r==null?void 0:r.name)||t}function RL(e,t){var i,o;const n=(i=e.group_ratio)==null?void 0:i[t];if(typeof n=="number"&&Number.isFinite(n))return n;const r=(o=e.group_info)==null?void 0:o[t];return typeof r=="number"&&Number.isFinite(r)?r:r&&typeof r=="object"?v2(r.GroupRatio??r.group_ratio??r.ratio,1):1}function xye(e,t){const n=jO(e);return n.includes(t)?t:n[0]||t||Nv}function HK(e){return e.enable_groups||e.enable_group||[]}function Sye(e,t,n){const r=jO(e),i=HK(t),o=r.includes(n);return i.length===0||i.includes("all")?xye(e,n):o?i.includes(n)?n:null:r.find(s=>i.includes(s))||null}function WK(e){var t;if(e.billingType==="tiered"&&((t=e.tieredCny)!=null&&t.length))return e.tieredCny.map(n=>`${n.label} ¥${n.perSecondCny.toFixed(2)}/秒`);if(e.billingType==="per-second"&&e.flatCny!=null&&e.flatCny>0)return[`¥${e.flatCny.toFixed(2)}/秒`];if(e.billingType==="flat"&&e.flatCny!=null&&e.flatCny>0)return[`¥${e.flatCny.toFixed(2)}/次`];if(e.billingType==="token"&&e.inputCnyMtok!=null&&e.outputCnyMtok!=null&&(e.inputCnyMtok>0||e.outputCnyMtok>0)){const n=[`输入 ¥${e.inputCnyMtok.toFixed(2)}`,`补全 ¥${e.outputCnyMtok.toFixed(2)}`];return e.cacheReadCnyMtok!=null&&n.push(`缓存读取 ¥${e.cacheReadCnyMtok.toFixed(2)}`),e.cacheCreateCnyMtok!=null&&n.push(`缓存创建 ¥${e.cacheCreateCnyMtok.toFixed(2)}`),e.audioInputCnyMtok!=null&&n.push(`音频输入 ¥${e.audioInputCnyMtok.toFixed(2)}`),e.audioOutputCnyMtok!=null&&n.push(`音频补全 ¥${e.audioOutputCnyMtok.toFixed(2)}`),n}return[]}function VK(e){return e.billingType==="token"?" / 1M Tokens":""}function Cye(e){const t=WK(e);return t.length===0?"":`${t.join(" · ")}${VK(e)}`}function Eye(e){const t=WK(e);return t.length===0?"":`${t.slice(0,2).join(" · ")}${VK(e)}`}function _ye(e){return Cye(e)}class Iye{constructor(){this.cacheMap=new Map,this.listeners=new Set,this.sharedResponseCacheMap=new Map,this.inflightRequestMap=new Map,this.version=0;const t=AL.get();Array.isArray(t)&&t.forEach(n=>this.cacheMap.set(n.profileId,n))}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}notify(){this.version+=1,this.listeners.forEach(t=>t())}buildSharedCacheKey(t,n){return`${Rm(t)}
|
|
89
89
|
${n}`}buildSourceSignature(t,n,r){return fye(t,n,r)}isFresh(t,n,r=Date.now()){return typeof t=="number"&&r-t<n}pruneExpiredSharedResponses(t=Date.now()){this.sharedResponseCacheMap.forEach((n,r)=>{this.isFresh(n.fetchedAt,n.ttlMs,t)||this.sharedResponseCacheMap.delete(r)})}async fetchPricingResponse(t,n,r={}){const i=Rm(t),o=this.buildSharedCacheKey(i,n),s=ML(i),a=Date.now();if(this.pruneExpiredSharedResponses(a),!r.force){const u=this.sharedResponseCacheMap.get(o);if(u&&this.isFresh(u.fetchedAt,u.ttlMs,a))return u.response}const l=this.inflightRequestMap.get(o);if(l)return l;const c=(async()=>{const u={Accept:"application/json"};n&&(u.Authorization=`Bearer ${n}`);const d=await fetch(i,{headers:u});if(!d.ok)throw new Error(`Pricing API error: ${d.status}`);const f=await d.json();if(!pye(f))throw new Error("Invalid pricing API response");return this.sharedResponseCacheMap.set(o,{fetchedAt:Date.now(),ttlMs:s,response:f}),f})();this.inflightRequestMap.set(o,c);try{return await c}finally{this.inflightRequestMap.delete(o)}}buildTuziProviderCache(t,n,r,i,o,s){var p,y;const a=Object.entries(n.data.group_info).map(([v,w])=>({name:v,displayName:w.DisplayName||v,ratio:w.GroupRatio??1})),l=r||Nv,c=n.data.group_info[l],u=(c==null?void 0:c.GroupRatio)??1,d={},f={};for(const v of n.data.model_info){const w=(p=v.price_info)==null?void 0:p[l],C=w==null?void 0:w.default;if(!C)continue;const x=(y=Object.values(v.endpoints||{}).find(E=>E.docs))==null?void 0:y.docs;d[v.model_name]={...mye(C,u,i),description:v.description||void 0,docsUrl:x||void 0},v.endpoints&&Object.keys(v.endpoints).length>0&&(f[v.model_name]=v.endpoints)}return{profileId:t,fetchedAt:Date.now(),sourceSignature:o,autoRefreshSourceSignature:s,groups:a,prices:d,modelEndpoints:f}}buildNewApiProviderCache(t,n,r,i,o,s){var d,f;const a=jO(n).map(p=>({name:p,displayName:bye(n,p),ratio:RL(n,p)})),l=r||Nv,c={},u={};for(const p of n.data){if(!p.model_name)continue;const y=Sye(n,p,l);if(!y)continue;const v=RL(n,y),w=(d=n.group_model_pricing)==null?void 0:d[y],C=wye(p,n.supported_endpoint),x=C?(f=Object.values(C).find(E=>E.docs))==null?void 0:f.docs:void 0;c[p.model_name]={...yye(p,v,i,w),description:p.description||void 0,docsUrl:x||void 0},C&&(u[p.model_name]=C)}return{profileId:t,fetchedAt:Date.now(),sourceSignature:o,autoRefreshSourceSignature:s,groups:a,prices:c,modelEndpoints:u}}buildProviderCache(t,n,r,i,o,s){if(zK(n))return this.buildTuziProviderCache(t,n,r,i,o,s);if(UK(n))return this.buildNewApiProviderCache(t,n,r,i,o,s);throw new Error("Invalid pricing API response")}async fetchAndCache(t,n,r,i,o,s={}){const a=Rm(n),l=ML(a),c=this.buildSourceSignature(a,i,o),u=this.cacheMap.get(t);if(!s.force&&u&&u.sourceSignature===c&&this.isFresh(u.fetchedAt,l))return u;const d=await this.fetchPricingResponse(a,r,s),f=s.promoteToAutoRefresh||OL(u,c)?c:null,p=this.buildProviderCache(t,d,i,o,c,f);return this.cacheMap.set(t,p),this.persist(),this.notify(),p}getCache(t){return this.cacheMap.get(t)??null}getModelPrice(t,n){var r;return t?((r=this.cacheMap.get(t))==null?void 0:r.prices[n])??null:null}getModelEndpoints(t,n){var r,i;return t?((i=(r=this.cacheMap.get(t))==null?void 0:r.modelEndpoints)==null?void 0:i[n])??null:null}getGroups(t){var n;return((n=this.cacheMap.get(t))==null?void 0:n.groups)??[]}removeCache(t){this.cacheMap.delete(t)&&(this.persist(),this.notify())}getVersion(){return this.version}warmupProfiles(t){t.filter(n=>n.enabled!==!1).forEach(n=>{const r=hye(n);if(!r)return;const i=this.buildSourceSignature(r.pricingUrl,r.pricingGroup,r.cnyPerUsd),o=this.cacheMap.get(n.id);OL(o,i)&&this.fetchAndCache(n.id,r.pricingUrl,n.apiKey,r.pricingGroup,r.cnyPerUsd).catch(s=>{console.warn(`[ModelPricingService] Warmup failed for profile ${n.id}:`,s)})})}persist(){const t=Array.from(this.cacheMap.values());AL.update(t)}}const ru=new Iye;function Aye(e){const t=e.trim().toLowerCase();return t.includes("generativelanguage.googleapis.com")||t.includes("vertex.googleapis.com")?"gemini-compatible":t.includes("/openai")||t.endsWith("/v1")||t.includes("api.openai.com")||GK(t)?"openai-compatible":"custom"}function GK(e){const t=e.trim().toLowerCase();if(!t)return!1;try{const r=new URL(/^[a-z][a-z\d+\-.]*:\/\//i.test(t)?t:`https://${t}`).hostname.toLowerCase();return r==="tu-zi.com"||r.endsWith(".tu-zi.com")}catch{return!1}}function KK(e,t,n){return n==="bearer"||n==="header"||n==="query"||n==="custom"?n:"bearer"}function Pye(e){return{id:e.id,name:e.name,providerType:e.providerType,baseUrl:e.baseUrl,apiKey:e.apiKey,authType:KK(e.baseUrl,e.providerType,e.authType),imageApiCompatibility:e.imageApiCompatibility||tv,preferAsyncImageEndpoint:e.preferAsyncImageEndpoint??!1,extraHeaders:e.extraHeaders}}function kye(e){const t=e.toLowerCase();return t.includes("flux")?Be.FLUX:t.startsWith("mj")||t.includes("midjourney")?Be.MIDJOURNEY:t.includes("suno")||t.includes("chirp")?Be.SUNO:t.includes("kling")?Be.KLING:t.includes("happyhorse")?Be.HAPPYHORSE:t.includes("seedance")||t.includes("seedream")?Be.DOUBAO:t.includes("veo")?Be.VEO:t.includes("gemini")||t.includes("gemma")||t.includes("imagen")?Be.GEMINI:Be.OTHER}function Tye(e,t){return{id:e,label:e,shortLabel:e,type:t,vendor:kye(e)}}function Dye(e,t){const n=Cl(e);return n||Tye(e,t)}function qK(){var o,s;const e=ci.get(),t=Xs.get().find(a=>a.id===lr),n=((o=e.baseUrl)==null?void 0:o.trim())||nv,r=GK(n)?p2:tv,i=(t==null?void 0:t.providerType)==="openai-compatible"||(t==null?void 0:t.providerType)==="gemini-compatible"||(t==null?void 0:t.providerType)==="custom"?t.providerType:Aye(n);return{id:lr,name:MO,providerType:i,baseUrl:n,apiKey:((s=e.apiKey)==null?void 0:s.trim())||"",authType:KK(n,i,t==null?void 0:t.authType),imageApiCompatibility:(t==null?void 0:t.imageApiCompatibility)||r,preferAsyncImageEndpoint:(t==null?void 0:t.preferAsyncImageEndpoint)??!1}}function Mye(e){var r,i,o,s,a;const t=ci.get(),n=[{modelId:((r=t.textModelName)==null?void 0:r.trim())||((i=t.chatModel)==null?void 0:i.trim())||uh(),type:"text"},{modelId:((o=t.audioModelName)==null?void 0:o.trim())||Lh(),type:"audio"},{modelId:((s=t.imageModelName)==null?void 0:s.trim())||El(),type:"image"},{modelId:((a=t.videoModelName)==null?void 0:a.trim())||uu(),type:"video"}];return BK(e,n.map(l=>Dye(l.modelId,l.type)))}function Oye(e){const t=new Map;return e.forEach(n=>{const r=`${n.profileId}:${n.modelId}:${n.operation}`,i=t.get(r)||[];i.push(n),t.set(r,i)}),t}function YK(e={}){const t=Xs.get().filter(n=>n.enabled!==!1).filter(n=>n.id!==lr).map(n=>Pye(n));return e.includeLegacyProfile!==!1&&t.unshift(qK()),t}function Rye(e={}){const t=YK(e),n=new Map(t.map(s=>[s.id,s])),r=y2.get().flatMap(s=>{const a=n.get(s.profileId);if(!a)return[];const l=ru.getCache(s.profileId);return BK(a,s.discoveredModels,(l==null?void 0:l.modelEndpoints)??null)}),i=e.includeLegacyProfile===!1?[]:Mye(n.get(lr)||qK()),o=new Map;return[...r,...i,...e.manualBindings||[]].forEach(s=>{o.set(s.id,s)}),Array.from(o.values())}function Nye(e={}){return{getProviderProfile(t){return YK(e).find(n=>n.id===t)||null},getModelBindings(t,n){return Oye(Rye(e)).get(`${t.profileId}:${t.modelId}:${n}`)||[]}}}function jye(e,t={}){const n=Nye(t);return new IK(n).plan(e)}function _i(e,t,n={}){const r=so(e,t),i=qn(r.profileId,r.modelId);if(!i)return null;try{return jye({operation:e,modelRef:i,bindingId:n.bindingId,preferredRequestSchema:n.preferredRequestSchema},n)}catch{return null}}const Lye="llm-api-logs",Bye=4,zf="logs",NL=1e3,jL=128*1024,Nm=[],Fye=50;function $ye(){return new Promise((e,t)=>{const n=indexedDB.open(Lye,Bye);n.onerror=()=>t(n.error),n.onsuccess=()=>e(n.result),n.onupgradeneeded=r=>{const i=r.target.result,o=r.oldVersion;let s;if(!i.objectStoreNames.contains(zf))s=i.createObjectStore(zf,{keyPath:"id"}),s.createIndex("timestamp","timestamp",{unique:!1}),s.createIndex("taskType","taskType",{unique:!1}),s.createIndex("status","status",{unique:!1}),s.createIndex("taskId","taskId",{unique:!1});else{const a=r.target.transaction;a&&(s=a.objectStore(zf),o<4&&!s.indexNames.contains("taskId")&&s.createIndex("taskId","taskId",{unique:!1}))}}})}async function eE(e){try{const t=await $ye(),n=t.transaction(zf,"readwrite");n.objectStore(zf).put(e),await new Promise((i,o)=>{n.oncomplete=()=>i(),n.onerror=()=>o(n.error)});try{const o=t.transaction(zf,"readwrite").objectStore(zf),s=o.count();s.onsuccess=()=>{if(s.result>NL){const a=o.index("timestamp"),l=s.result-NL;let c=0;a.openCursor().onsuccess=u=>{const d=u.target.result;d&&c<l&&(d.delete(),c++,d.continue())}}}}catch{}}catch(t){console.warn("[LLMApiLogger:Fallback] Failed to save log:",t)}}function _a(e){const t=`llm-fallback-${Date.now()}-${Math.random().toString(36).substring(2,8)}`,n={id:t,timestamp:Date.now(),endpoint:e.endpoint,model:e.model,taskType:e.taskType,prompt:e.prompt?Vg(e.prompt,2e3):void 0,requestBody:e.requestBody?WG(e.requestBody):void 0,hasReferenceImages:e.hasReferenceImages,referenceImageCount:e.referenceImageCount,referenceImages:e.referenceImages,status:"pending",taskId:e.taskId,workflowId:e.workflowId};return Nm.unshift(n),Nm.length>Fye&&Nm.pop(),eE(n),t}function qs(e,t){const n=Nm.find(r=>r.id===e);n&&(n.status="success",n.httpStatus=t.httpStatus,n.duration=t.duration,n.resultType=t.resultType,n.resultCount=t.resultCount,n.resultUrl=t.resultUrl,n.resultText=t.resultText?Vg(t.resultText,1e3):void 0,n.responseBody=t.responseBody?BO(t.responseBody):void 0,n.remoteId=t.remoteId,eE(n))}function LO(e,t){const n=Nm.find(r=>r.id===e);n&&(t.remoteId&&(n.remoteId=t.remoteId),t.responseBody&&(n.responseBody=BO(t.responseBody)),t.httpStatus&&(n.httpStatus=t.httpStatus),eE(n))}function xo(e,t){const n=Nm.find(r=>r.id===e);n&&(n.status="error",n.httpStatus=t.httpStatus,n.duration=t.duration,n.errorMessage=Vg(t.errorMessage,500),n.responseBody=t.responseBody?BO(t.responseBody):void 0,eE(n))}function BO(e){return e.length<=jL?e:`${e.substring(0,jL)}
|
|
90
|
-
... [response truncated for log storage]`}const dh={modelName:"gemini-3-pro-image-preview-vip"},jv={modelName:"veo3"},zye=["seedream-4-0-250828","seedream-v4","doubao-seedream-4-5-251128","doubao-seedream-5-0-260128","gemini-3-pro-image-preview-async","gemini-3-pro-image-preview-2k-async","gemini-3-pro-image-preview-4k-async"];function Uye(e){if(!e)return!1;const t=e.toLowerCase();return zye.some(n=>t.includes(n.toLowerCase()))}function Hye(e){const t=String(e||"").trim();if(!t)return null;try{const n=new URL(t);return{origin:n.origin,host:n.host,protocol:n.protocol.replace(":","")}}catch{return null}}function Wye(e){return e<=0?"0":e<=50?"1-50":e<=200?"51-200":e<=500?"201-500":e<=1e3?"501-1000":e<=2e3?"1001-2000":"2000+"}function dP(e){const t=String(e||"").trim();return{has_prompt:t.length>0,prompt_length:t.length,prompt_length_bucket:Wye(t.length),prompt_line_count:t?t.split(/\r?\n/).length:0}}function Vye(e){const t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="0.0.0.0"||t.endsWith(".local")?"local":t.includes("preview")||t.includes("vercel")||t.includes("netlify")?"preview":t.includes("staging")||t.includes("test")||t.includes("dev")?"staging":"production"}function Gye(){return"1.0.
|
|
90
|
+
... [response truncated for log storage]`}const dh={modelName:"gemini-3-pro-image-preview-vip"},jv={modelName:"veo3"},zye=["seedream-4-0-250828","seedream-v4","doubao-seedream-4-5-251128","doubao-seedream-5-0-260128","gemini-3-pro-image-preview-async","gemini-3-pro-image-preview-2k-async","gemini-3-pro-image-preview-4k-async"];function Uye(e){if(!e)return!1;const t=e.toLowerCase();return zye.some(n=>t.includes(n.toLowerCase()))}function Hye(e){const t=String(e||"").trim();if(!t)return null;try{const n=new URL(t);return{origin:n.origin,host:n.host,protocol:n.protocol.replace(":","")}}catch{return null}}function Wye(e){return e<=0?"0":e<=50?"1-50":e<=200?"51-200":e<=500?"201-500":e<=1e3?"501-1000":e<=2e3?"1001-2000":"2000+"}function dP(e){const t=String(e||"").trim();return{has_prompt:t.length>0,prompt_length:t.length,prompt_length_bucket:Wye(t.length),prompt_line_count:t?t.split(/\r?\n/).length:0}}function Vye(e){const t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="0.0.0.0"||t.endsWith(".local")?"local":t.includes("preview")||t.includes("vercel")||t.includes("netlify")?"preview":t.includes("staging")||t.includes("test")||t.includes("dev")?"staging":"production"}function Gye(){return"1.0.2"}function XK(){const e=Gye();if(typeof window>"u")return{version:e,appVersion:e,app_version:e,deployment_env:"local",release_channel:"local",host:"",hostname:"",route_name:"/"};const{hostname:t,pathname:n}=window.location,r=Vye(t);return{version:e,appVersion:e,app_version:e,host:window.location.host||t,hostname:t,route_name:n||"/",deployment_env:r,release_channel:r}}function Kye(){return XK()}function kat(e){var t;if(!(typeof window>"u"||!((t=window.posthog)!=null&&t.register)))try{window.posthog.register({...XK(),...e||{}})}catch{}}function LL(e){return{$ai_model:e.model,$ai_latency:e.duration,$ai_is_error:e.status==="failed",task_id:e.taskId,task_type:e.taskType,status:e.status,model:e.model,duration_ms:e.duration,...e.error?{error:e.error}:{}}}class qye{track(t,n){if(typeof window>"u"||!window.posthog)return;const r=()=>{try{const i={...Kye(),...n||{}},o=Object.keys(i).length>0?Rv(i):void 0;window.posthog.capture(t,o)}catch{}};typeof globalThis.requestIdleCallback=="function"?globalThis.requestIdleCallback(r,{timeout:2e3}):setTimeout(r,0)}trackUIInteraction(t){const{metadata:n,...r}=t;this.track("ui_interaction",{category:"ui_interaction",...r,metadata:n||void 0,timestamp:Date.now()})}trackPPTAction(t){const{prompt:n,metadata:r,...i}=t;this.track("ppt_action",{category:"ppt",...i,...n!==void 0?dP(n):{},metadata:r||void 0,timestamp:Date.now()})}trackPromptAction(t){const{prompt:n,requirements:r,metadata:i,...o}=t,s=n!==void 0?dP(n):void 0,a=r!==void 0?dP(r):void 0;this.track("prompt_action",{category:"prompt",...o,...s||{},...a?{has_requirements:a.has_prompt,requirements_length:a.prompt_length,requirements_length_bucket:a.prompt_length_bucket,requirements_line_count:a.prompt_line_count}:{},metadata:i||void 0,timestamp:Date.now()})}isAnalyticsEnabled(){return typeof window<"u"&&!!window.posthog}trackAIGeneration(t,n){this.track(t,{category:"ai_generation",...n,timestamp:Date.now()})}trackModelCall(t){const n={image:"image_generation_start",video:"video_generation_start",audio:"audio_generation_start",chat:"chat_generation_start"};this.trackAIGeneration(n[t.taskType],t)}trackModelSuccess(t){const n={image:"image_generation_success",video:"video_generation_success",audio:"audio_generation_success",chat:"chat_generation_success"};this.trackAIGeneration(n[t.taskType],t),this.track("$ai_generation",LL({taskId:t.taskId,taskType:t.taskType,model:t.model,duration:t.duration,status:"success"}))}trackModelFailure(t){const n={image:"image_generation_failed",video:"video_generation_failed",audio:"audio_generation_failed",chat:"chat_generation_failed"};this.trackAIGeneration(n[t.taskType],t),this.track("$ai_generation",LL({taskId:t.taskId,taskType:t.taskType,model:t.model,duration:t.duration,status:"failed",error:t.error}))}trackTaskCancellation(t){this.trackAIGeneration("task_cancelled",t)}trackAPICallStart(t){this.track("api_call_start",{category:"system",...t,timestamp:Date.now()})}trackAPICallSuccess(t){this.track("api_call_success",{category:"system",...t,timestamp:Date.now()})}trackAPICallFailure(t){this.track("api_call_failed",{category:"system",...t,timestamp:Date.now()})}trackAPICallRetry(t){this.track("api_call_retry",{category:"system",...t,timestamp:Date.now()})}}const Kt=new qye,Yye=ss;function ZK(e){return e.protocol==="google.generateContent"}function tE(e){return e.provider||{profileId:"runtime",profileName:"Runtime",providerType:e.providerType||"custom",baseUrl:e.baseUrl,apiKey:e.apiKey,authType:e.authType||"bearer",extraHeaders:e.extraHeaders}}function Eo(e){var n,r,i,o,s;const t=Hye(((n=e.provider)==null?void 0:n.baseUrl)||e.baseUrl);return{providerType:((r=e.provider)==null?void 0:r.providerType)||e.providerType||"custom",profileId:(i=e.provider)==null?void 0:i.profileId,profileName:(o=e.provider)==null?void 0:o.profileName,providerOrigin:t==null?void 0:t.origin,providerHost:t==null?void 0:t.host,providerProtocol:t==null?void 0:t.protocol,baseUrlStrategy:(s=e.binding)==null?void 0:s.baseUrlStrategy}}function xd(e){e&&typeof e=="object"&&(e.__aituApiFailureTracked=!0)}function Lv(e){return!!(e&&typeof e=="object"&&e.__aituApiFailureTracked)}function Xye(e,t){const n=e==null?void 0:e.trim();return n?n.replace(/\{model(?:_name)?\}/g,t).replace(/^(\/v\d+(?:alpha|beta)?\/)([^/]+:(?:generateContent|streamGenerateContent))$/i,"$1models/$2"):`/v1/models/${t}:generateContent`}function Zye(e,t,n){var i;const r=Xye((i=e.binding)==null?void 0:i.submitPath,t);return!n||r.endsWith(":streamGenerateContent")?r:r.endsWith(":generateContent")?`${r.slice(0,-16)}:streamGenerateContent`:`/v1beta/models/${t}:streamGenerateContent`}function Jye(e,t){const n=new AbortController;let r=!1;const i=()=>{n.abort()};e!=null&&e.aborted?n.abort():e&&e.addEventListener("abort",i,{once:!0});const o=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,didTimeout:()=>r,cleanup:()=>{clearTimeout(o),e==null||e.removeEventListener("abort",i)}}}function Qye(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(String(r.result||"")),r.onerror=()=>n(new Error("图片读取失败")),r.readAsDataURL(e)})}function BL(e){const t=e.match(/^data:([^;]+);base64,(.+)$/);if(!t)throw new Error("Invalid data URL");return{mimeType:t[1]||"image/png",data:t[2]||""}}async function e0e(e){if(e.startsWith("data:")){const o=BL(e);return{mime_type:o.mimeType,data:o.data}}const t=await fetch(e);if(!t.ok)throw new Error(`Failed to load image input: ${t.status}`);const n=await t.blob(),r=await Qye(n),i=BL(r);return{mime_type:i.mimeType,data:i.data}}async function t0e(e){var r;const t=[],n=[];for(const i of e){const o=[];for(const s of i.content)s.type==="text"&&s.text?o.push({text:s.text}):s.type==="image_url"&&((r=s.image_url)!=null&&r.url)?o.push({inline_data:await e0e(s.image_url.url)}):s.type==="inline_data"&&s.data?o.push({inline_data:{mime_type:s.mimeType,data:s.data}}):s.type==="file_uri"&&s.fileUri&&o.push({fileData:{fileUri:s.fileUri}});if(i.role==="system"){o.forEach(s=>{typeof s.text=="string"&&s.text.trim()&&n.push(s.text)});continue}o.length!==0&&t.push({role:i.role==="assistant"?"model":"user",parts:o})}return{contents:t,systemInstruction:n.length>0?{parts:n.map(i=>({text:i}))}:void 0}}function n0e(e){if(typeof e.text=="string")return e.text;const t=e.inline_data||e.inlineData;if(t!=null&&t.data)return`data:${t.mime_type||t.mimeType||"image/png"};base64,${t.data}`;const n=e.file_data||e.fileData,r=(n==null?void 0:n.file_uri)||(n==null?void 0:n.fileUri);return typeof r=="string"?r:""}function JK(e){return(Array.isArray(e.candidates)?e.candidates:[]).flatMap(r=>{var i;return Array.isArray((i=r==null?void 0:r.content)==null?void 0:i.parts)?r.content.parts:[]}).map(r=>n0e(r||{})).filter(Boolean).join(`
|
|
91
91
|
`)}function r0e(e){return{choices:[{message:{role:"assistant",content:JK(e)}}]}}function Tat(e){return{data:(Array.isArray(e.candidates)?e.candidates:[]).flatMap(r=>{var o;return(Array.isArray((o=r==null?void 0:r.content)==null?void 0:o.parts)?r.content.parts:[]).map(s=>{const a=s.inline_data||s.inlineData;if(a!=null&&a.data)return{b64_json:a.data,mime_type:a.mime_type||a.mimeType||"video/mp4"};const l=s.file_data||s.fileData,c=(l==null?void 0:l.file_uri)||(l==null?void 0:l.fileUri);return typeof c=="string"?{url:c}:null}).filter(Boolean)}),raw:e}}async function i0e(e){var t,n;try{const r=await e.json();return((t=r==null?void 0:r.error)==null?void 0:t.message)||((n=r==null?void 0:r.error)==null?void 0:n.status)||(r==null?void 0:r.message)||e.statusText}catch{return await e.text().catch(()=>"")||e.statusText}}async function H1(e,t,n={stream:!1}){var d,f,p,y,v,w;const r=Date.now(),i=e.modelName||"gemini-2.0-flash",o=Zye(e,i,n.stream),s=await t0e(t),a={contents:s.contents};s.systemInstruction&&(a.systemInstruction=s.systemInstruction),n.generationConfig&&(a.generationConfig=n.generationConfig),Kt.trackAPICallStart({endpoint:o,model:i,messageCount:t.length,stream:n.stream,...Eo(e)});const l=tE(e),c=Math.max(e.timeout||0,Yye),u=Jye(n.signal,c);try{const C=await Wi.send(l,{path:o,baseUrlStrategy:(d=e.binding)==null?void 0:d.baseUrlStrategy,method:"POST",headers:{"Content-Type":"application/json"},query:n.stream?{alt:"sse"}:void 0,body:JSON.stringify(a),signal:u.signal});if(!C.ok){const P=Date.now()-r,k=await i0e(C);Kt.trackAPICallFailure({endpoint:o,model:i,duration:P,error:k,httpStatus:C.status,stream:n.stream,...Eo(e)});const R=new Error(`HTTP ${C.status}: ${k}`);throw R.httpStatus=C.status,xd(R),R}if(!n.stream){const P=await C.json(),k=r0e(P),R=Date.now()-r;return Kt.trackAPICallSuccess({endpoint:o,model:i,duration:R,responseLength:((y=(p=(f=k.choices[0])==null?void 0:f.message)==null?void 0:p.content)==null?void 0:y.length)||0,stream:!1,...Eo(e)}),k}const x=(v=C.body)==null?void 0:v.getReader();if(!x)throw new Error("无法获取响应流");const E=new TextDecoder;let _="",I="";try{for(;;){const{done:P,value:k}=await x.read();if(P)break;const R=E.decode(k,{stream:!0}),M=(I+R).split(`
|
|
92
92
|
`);I=M.pop()||"";for(const F of M){const V=F.trim();if(!V.startsWith("data: "))continue;const H=V.slice(6).trim();if(!(!H||H==="[DONE]"))try{const j=JSON.parse(H),z=JK(j);if(!z)continue;_+=z,(w=n.onChunk)==null||w.call(n,_)}catch{}}}}finally{x.releaseLock()}const D=Date.now()-r;return Kt.trackAPICallSuccess({endpoint:o,model:i,duration:D,responseLength:_.length,stream:!0,...Eo(e)}),{choices:[{message:{role:"assistant",content:_}}]}}catch(C){const x=Date.now()-r,E=u.didTimeout()&&C instanceof Error&&C.name==="AbortError"?new Error(`generateContent 请求超时(>${Math.floor(c/6e4)} 分钟)`):C,_=E instanceof Error?E.message:String(E);throw!Lv(C)&&!Lv(E)&&(Kt.trackAPICallFailure({endpoint:o,model:i,duration:x,error:_,stream:n.stream,...Eo(e)}),xd(E)),E}finally{u.cleanup()}}async function o0e(e,t){var a,l,c,u;if(ZK(e))return H1(e,t,{stream:!1});const n=Date.now(),r=e.modelName||"gemini-3-pro-image-preview-vip",i="/chat/completions";Kt.trackAPICallStart({endpoint:i,model:r,messageCount:t.length,stream:!1,...Eo(e)});const o={"Content-Type":"application/json"},s={model:r,messages:t,stream:!1};try{const d=await Wi.send(tE(e),{path:i,method:"POST",headers:o,body:JSON.stringify(s)});if(!d.ok){const y=Date.now()-n;let v="",w=d.statusText;try{const x=await d.json();x.error&&(w=x.error.message||x.error.code||d.statusText,v=JSON.stringify(x.error))}catch{try{v=await d.text()}catch{}}Kt.trackAPICallFailure({endpoint:i,model:r,duration:y,error:w,httpStatus:d.status,stream:!1,...Eo(e)});const C=new Error(`HTTP ${d.status}: ${w}`);throw C.apiErrorBody=v,C.httpStatus=d.status,xd(C),C}const f=await d.json(),p=Date.now()-n;return Kt.trackAPICallSuccess({endpoint:i,model:r,duration:p,responseLength:(u=(c=(l=(a=f.choices)==null?void 0:a[0])==null?void 0:l.message)==null?void 0:c.content)==null?void 0:u.length,stream:!1,...Eo(e)}),f}catch(d){const f=Date.now()-n,p=d instanceof Error?d.message:String(d);throw Lv(d)||(Kt.trackAPICallFailure({endpoint:i,model:r,duration:f,error:p,stream:!1,...Eo(e)}),xd(d)),d}}async function QK(e,t,n,r){return ZK(e)?H1(e,t,{stream:!0,onChunk:n,signal:r}):s0e(e,t,n,r)}async function s0e(e,t,n,r){var c,u,d,f;const i=Date.now(),o=e.modelName||"gemini-3-pro-image-preview-vip",s="/chat/completions";Kt.trackAPICallStart({endpoint:s,model:o,messageCount:t.length,stream:!0,...Eo(e)});const a={"Content-Type":"application/json"},l={model:o,messages:t,presence_penalty:0,temperature:.5,top_p:1,stream:!0};try{const p=await Wi.send(tE(e),{path:s,method:"POST",headers:a,body:JSON.stringify(l),signal:r});if(!p.ok){const D=Date.now()-i;let P="",k=p.statusText;try{const T=await p.json();T.error&&(k=T.error.message||T.error.code||p.statusText,P=JSON.stringify(T.error))}catch{try{P=await p.text()}catch{}}Kt.trackAPICallFailure({endpoint:s,model:o,duration:D,error:k,httpStatus:p.status,stream:!0,...Eo(e)});const R=new Error(`HTTP ${p.status}: ${k}`);throw R.apiErrorBody=P,R.httpStatus=p.status,xd(R),R}const y=(c=p.body)==null?void 0:c.getReader();if(!y)throw new Error("无法获取响应流");const v=new TextDecoder;let w="",C=!1,x="";try{for(;!C;){const{done:D,value:P}=await y.read();if(D){C=!0;continue}const k=v.decode(P,{stream:!0}),T=(x+k).split(`
|
|
93
93
|
`);x=T.pop()||"";for(const M of T){const F=M.trim();if(F.startsWith("data: ")){const V=F.slice(6).trim();if(V==="[DONE]")break;try{const j=(f=(d=(u=JSON.parse(V).choices)==null?void 0:u[0])==null?void 0:d.delta)==null?void 0:f.content;j&&(w+=j,n&&n(w))}catch{}}}}}finally{y.releaseLock()}const E=Date.now()-i,_=w.includes("正在生成")||w.includes("generating"),I=w.includes(";return _&&!I&&console.warn('[StreamAPI] Warning: Response contains "generating" text but no image URL - response may be incomplete'),Kt.trackAPICallSuccess({endpoint:s,model:o,duration:E,responseLength:w.length,stream:!0,...Eo(e)}),{choices:[{message:{role:"assistant",content:w}}]}}catch(p){const y=Date.now()-i,v=p instanceof Error?p.message:String(p);throw Lv(p)||(Kt.trackAPICallFailure({endpoint:s,model:o,duration:y,error:v,stream:!0,...Eo(e)}),xd(p)),p}}async function a0e(e,t,n={}){var c,u,d,f;const r=Date.now(),i=e.modelName||jv.modelName||"veo3",o="/chat/completions";Kt.trackAPICallStart({endpoint:o,model:i,messageCount:t.length+1,stream:!0,...Eo(e)});const s={"Content-Type":"application/json"},a={role:"user",content:[{type:"text",text:`You are Video Creator.
|
|
@@ -1729,7 +1729,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1729
1729
|
* tdesign v1.16.3
|
|
1730
1730
|
* (c) 2026 tdesign
|
|
1731
1731
|
* @license MIT
|
|
1732
|
-
*/var $6e=KR;let YP=null;function gD(){return YP||(YP=xn(()=>import("./index-DsGlObqC.js"),[],import.meta.url).then(e=>e.MessagePlugin)),YP}function z6e(e){return typeof e=="object"&&e!==null&&e.__aituLazyMessageInstance===!0}function U6e(e){return typeof e=="object"&&e!==null&&typeof e.then=="function"}function H6e(e){return typeof e=="object"&&e!==null&&typeof e.close=="function"}function _x(e,t){gD().then(n=>{const r=n[e];r(...t)}).catch(n=>{console.warn("[MessagePlugin] failed to load tdesign-react:",n)})}const tn={success(...e){_x("success",e)},error(...e){_x("error",e)},warning(...e){_x("warning",e)},info(...e){_x("info",e)},loading(...e){const t=gD().then(n=>{const r=n.loading;return r(...e)});return Object.assign(t,{__aituLazyMessageInstance:!0,instancePromise:t})},close(e){var t;if(z6e(e)){e.instancePromise.then(n=>{var r;(r=n==null?void 0:n.close)==null||r.call(n)}).catch(n=>{console.warn("[MessagePlugin] failed to close lazy message:",n)});return}if(H6e(e)){(t=e.close)==null||t.call(e);return}U6e(e)&&gD().then(n=>{n.close(e)}).catch(n=>{console.warn("[MessagePlugin] failed to load tdesign-react:",n)})}},kJ=({tabs:e,activeTab:t,onTabChange:n,middleTabs:r,activeMiddleTab:i,onMiddleTabChange:o,searchQuery:s,children:a,compact:l=!1,tabsFooter:c})=>{const u=!!(s!=null&&s.trim()),d=r&&r.length>0&&!u,f=b.useCallback(y=>{n(y)},[n]),p=b.useCallback(y=>{o==null||o(y)},[o]);return g.jsxs("div",{className:`vendor-tab-panel ${l?"vendor-tab-panel--compact":""} ${d?"vendor-tab-panel--three-col":""}`,children:[!u&&g.jsxs("div",{className:"vendor-tab-panel__tabs",children:[g.jsx("div",{className:"vendor-tab-panel__tabs-list",children:e.map(({id:y,label:v,count:w,icon:C})=>{const x=t===y;return g.jsxs("button",{className:`vendor-tab-panel__tab ${x?"vendor-tab-panel__tab--active":""}`,onClick:()=>f(y),type:"button",children:[C?g.jsx("span",{className:"vendor-tab-panel__tab-icon",children:C}):null,g.jsx("span",{className:"vendor-tab-panel__tab-label",children:v}),g.jsx("span",{className:"vendor-tab-panel__tab-count",children:w})]},y)})}),c?g.jsx("div",{className:"vendor-tab-panel__tabs-footer",children:c}):null]}),d&&g.jsx("div",{className:"vendor-tab-panel__middle-tabs",children:r.map(({id:y,label:v,count:w,icon:C})=>{const x=i===y;return g.jsxs("button",{className:`vendor-tab-panel__tab ${x?"vendor-tab-panel__tab--active":""}`,onClick:()=>p(y),type:"button",children:[C?g.jsx("span",{className:"vendor-tab-panel__tab-icon",children:C}):null,g.jsx("span",{className:"vendor-tab-panel__tab-label",children:v}),g.jsx("span",{className:"vendor-tab-panel__tab-count",children:w})]},y)})}),g.jsx("div",{className:"vendor-tab-panel__content",children:a})]})};var TJ=Symbol.for("immer-nothing"),cz=Symbol.for("immer-draftable"),sa=Symbol.for("immer-state");function ml(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Qv=Object.getPrototypeOf;function ou(e){return!!e&&!!e[sa]}function vh(e){var t;return e?DJ(e)||Array.isArray(e)||!!e[cz]||!!((t=e.constructor)!=null&&t[cz])||iw(e)||TE(e):!1}var W6e=Object.prototype.constructor.toString(),uz=new WeakMap;function DJ(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return!0;const n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;if(n===Object)return!0;if(typeof n!="function")return!1;let r=uz.get(n);return r===void 0&&(r=Function.toString.call(n),uz.set(n,r)),r===W6e}function NS(e,t,n=!0){kE(e)===0?(n?Reflect.ownKeys(e):Object.keys(e)).forEach(i=>{t(i,e[i],e)}):e.forEach((r,i)=>t(i,r,e))}function kE(e){const t=e[sa];return t?t.type_:Array.isArray(e)?1:iw(e)?2:TE(e)?3:0}function yD(e,t){return kE(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function MJ(e,t,n){const r=kE(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function V6e(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function iw(e){return e instanceof Map}function TE(e){return e instanceof Set}function _f(e){return e.copy_||e.base_}function vD(e,t){if(iw(e))return new Map(e);if(TE(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const n=DJ(e);if(t===!0||t==="class_only"&&!n){const r=Object.getOwnPropertyDescriptors(e);delete r[sa];let i=Reflect.ownKeys(r);for(let o=0;o<i.length;o++){const s=i[o],a=r[s];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[s]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[s]})}return Object.create(Qv(e),r)}else{const r=Qv(e);if(r!==null&&n)return{...e};const i=Object.create(r);return Object.assign(i,e)}}function qR(e,t=!1){return DE(e)||ou(e)||!vh(e)||(kE(e)>1&&Object.defineProperties(e,{set:Ix,add:Ix,clear:Ix,delete:Ix}),Object.freeze(e),t&&Object.values(e).forEach(n=>qR(n,!0))),e}function G6e(){ml(2)}var Ix={value:G6e};function DE(e){return e===null||typeof e!="object"?!0:Object.isFrozen(e)}var K6e={};function wh(e){const t=K6e[e];return t||ml(0,e),t}var e1;function OJ(){return e1}function q6e(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function dz(e,t){t&&(wh("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function wD(e){bD(e),e.drafts_.forEach(Y6e),e.drafts_=null}function bD(e){e===e1&&(e1=e.parent_)}function fz(e){return e1=q6e(e1,e)}function Y6e(e){const t=e[sa];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function hz(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[sa].modified_&&(wD(t),ml(4)),vh(e)&&(e=jS(t,e),t.parent_||LS(t,e)),t.patches_&&wh("Patches").generateReplacementPatches_(n[sa].base_,e,t.patches_,t.inversePatches_)):e=jS(t,n,[]),wD(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==TJ?e:void 0}function jS(e,t,n){if(DE(t))return t;const r=e.immer_.shouldUseStrictIteration(),i=t[sa];if(!i)return NS(t,(o,s)=>pz(e,i,t,o,s,n),r),t;if(i.scope_!==e)return t;if(!i.modified_)return LS(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;const o=i.copy_;let s=o,a=!1;i.type_===3&&(s=new Set(o),o.clear(),a=!0),NS(s,(l,c)=>pz(e,i,o,l,c,n,a),r),LS(e,o,!1),n&&e.patches_&&wh("Patches").generatePatches_(i,n,e.patches_,e.inversePatches_)}return i.copy_}function pz(e,t,n,r,i,o,s){if(i==null||typeof i!="object"&&!s)return;const a=DE(i);if(!(a&&!s)){if(ou(i)){const l=o&&t&&t.type_!==3&&!yD(t.assigned_,r)?o.concat(r):void 0,c=jS(e,i,l);if(MJ(n,r,c),ou(c))e.canAutoFreeze_=!1;else return}else s&&n.add(i);if(vh(i)&&!a){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||t&&t.base_&&t.base_[r]===i&&a)return;jS(e,i),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&(iw(n)?n.has(r):Object.prototype.propertyIsEnumerable.call(n,r))&&LS(e,i)}}}function LS(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&qR(t,n)}function X6e(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:OJ(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let i=r,o=YR;n&&(i=[r],o=t1);const{revoke:s,proxy:a}=Proxy.revocable(i,o);return r.draft_=a,r.revoke_=s,a}var YR={get(e,t){if(t===sa)return e;const n=_f(e);if(!yD(n,t))return Z6e(e,n,t);const r=n[t];return e.finalized_||!vh(r)?r:r===XP(e.base_,t)?(ZP(e),e.copy_[t]=SD(r,e)):r},has(e,t){return t in _f(e)},ownKeys(e){return Reflect.ownKeys(_f(e))},set(e,t,n){const r=RJ(_f(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const i=XP(_f(e),t),o=i==null?void 0:i[sa];if(o&&o.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(V6e(n,i)&&(n!==void 0||yD(e.base_,t)))return!0;ZP(e),xD(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return XP(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,ZP(e),xD(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=_f(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ml(11)},getPrototypeOf(e){return Qv(e.base_)},setPrototypeOf(){ml(12)}},t1={};NS(YR,(e,t)=>{t1[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});t1.deleteProperty=function(e,t){return t1.set.call(this,e,t,void 0)};t1.set=function(e,t,n){return YR.set.call(this,e[0],t,n,e[0])};function XP(e,t){const n=e[sa];return(n?_f(n):e)[t]}function Z6e(e,t,n){var i;const r=RJ(t,n);return r?"value"in r?r.value:(i=r.get)==null?void 0:i.call(e.draft_):void 0}function RJ(e,t){if(!(t in e))return;let n=Qv(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=Qv(n)}}function xD(e){e.modified_||(e.modified_=!0,e.parent_&&xD(e.parent_))}function ZP(e){e.copy_||(e.copy_=vD(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var J6e=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const o=n;n=t;const s=this;return function(l=o,...c){return s.produce(l,u=>n.call(this,u,...c))}}typeof n!="function"&&ml(6),r!==void 0&&typeof r!="function"&&ml(7);let i;if(vh(t)){const o=fz(this),s=SD(t,void 0);let a=!0;try{i=n(s),a=!1}finally{a?wD(o):bD(o)}return dz(o,r),hz(i,o)}else if(!t||typeof t!="object"){if(i=n(t),i===void 0&&(i=t),i===TJ&&(i=void 0),this.autoFreeze_&&qR(i,!0),r){const o=[],s=[];wh("Patches").generateReplacementPatches_(t,i,o,s),r(o,s)}return i}else ml(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,l=>t(l,...a));let r,i;return[this.produce(t,n,(s,a)=>{r=s,i=a}),r,i]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),typeof(e==null?void 0:e.useStrictIteration)=="boolean"&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){vh(e)||ml(8),ou(e)&&(e=Q6e(e));const t=fz(this),n=SD(e,void 0);return n[sa].isManual_=!0,bD(t),n}finishDraft(e,t){const n=e&&e[sa];(!n||!n.isManual_)&&ml(9);const{scope_:r}=n;return dz(r,t),hz(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const i=t[n];if(i.path.length===0&&i.op==="replace"){e=i.value;break}}n>-1&&(t=t.slice(n+1));const r=wh("Patches").applyPatches_;return ou(e)?r(e,t):this.produce(e,i=>r(i,t))}};function SD(e,t){const n=iw(e)?wh("MapSet").proxyMap_(e,t):TE(e)?wh("MapSet").proxySet_(e,t):X6e(e,t);return(t?t.scope_:OJ()).drafts_.push(n),n}function Q6e(e){return ou(e)||ml(10,e),NJ(e)}function NJ(e){if(!vh(e)||DE(e))return e;const t=e[sa];let n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=vD(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=vD(e,!0);return NS(n,(i,o)=>{MJ(n,i,NJ(o))},r),t&&(t.finalized_=!1),n}var n1=new J6e,eje=n1.produce,Ax=n1.createDraft.bind(n1),Px=n1.finishDraft.bind(n1),ol={},mz;function tje(){if(mz)return ol;mz=1,Object.defineProperty(ol,"__esModule",{value:!0});for(var e=typeof window<"u"&&/Mac|iPod|iPhone|iPad/.test(window.navigator.platform),t={alt:"altKey",control:"ctrlKey",meta:"metaKey",shift:"shiftKey"},n={add:"+",break:"pause",cmd:"meta",command:"meta",ctl:"control",ctrl:"control",del:"delete",down:"arrowdown",esc:"escape",ins:"insert",left:"arrowleft",mod:e?"meta":"control",opt:"alt",option:"alt",return:"enter",right:"arrowright",space:" ",spacebar:" ",up:"arrowup",win:"meta",windows:"meta"},r={backspace:8,tab:9,enter:13,shift:16,control:17,alt:18,pause:19,capslock:20,escape:27," ":32,pageup:33,pagedown:34,end:35,home:36,arrowleft:37,arrowup:38,arrowright:39,arrowdown:40,insert:45,delete:46,meta:91,numlock:144,scrolllock:145,";":186,"=":187,",":188,"-":189,".":190,"/":191,"`":192,"[":219,"\\":220,"]":221,"'":222},i=1;i<20;i++)r["f"+i]=111+i;function o(f,p,y){p&&!("byKey"in p)&&(y=p,p=null),Array.isArray(f)||(f=[f]);var v=f.map(function(x){return l(x,p)}),w=function(E){return v.some(function(_){return c(_,E)})},C=y==null?w:w(y);return C}function s(f,p){return o(f,p)}function a(f,p){return o(f,{byKey:!0},p)}function l(f,p){var y=p&&p.byKey,v={};f=f.replace("++","+add");var w=f.split("+"),C=w.length;for(var x in t)v[t[x]]=!1;var E=!0,_=!1,I=void 0;try{for(var D=w[Symbol.iterator](),P;!(E=(P=D.next()).done);E=!0){var k=P.value,R=k.endsWith("?")&&k.length>1;R&&(k=k.slice(0,-1));var T=d(k),M=t[T];if(k.length>1&&!M&&!n[k]&&!r[T])throw new TypeError('Unknown modifier: "'+k+'"');(C===1||!M)&&(y?v.key=T:v.which=u(k)),M&&(v[M]=R?null:!0)}}catch(F){_=!0,I=F}finally{try{!E&&D.return&&D.return()}finally{if(_)throw I}}return v}function c(f,p){for(var y in f){var v=f[y],w=void 0;if(v!=null&&(y==="key"&&p.key!=null?w=p.key.toLowerCase():y==="which"?w=v===91&&p.which===93?91:p.which:w=p[y],!(w==null&&v===!1)&&w!==v))return!1}return!0}function u(f){f=d(f);var p=r[f]||f.toUpperCase().charCodeAt(0);return p}function d(f){return f=f.toLowerCase(),f=n[f]||f,f}return ol.default=o,ol.isHotkey=o,ol.isCodeHotkey=s,ol.isKeyHotkey=a,ol.parseHotkey=l,ol.compareHotkey=c,ol.toKeyCode=u,ol.toKeyName=d,ol}var $r=tje(),Ia;(function(e){e.ew="ew-resize",e.ns="ns-resize",e.nesw="nesw-resize",e.nwse="nwse-resize"})(Ia||(Ia={}));var Um;(function(e){e.crosshair="crosshair"})(Um||(Um={}));const T2=[Ia.ns,Ia.nesw,Ia.ew,Ia.nwse],Vh="plait-board-attached",ti=1,BS=2,ny="selection-rectangle",jJ="selection-rectangle-bounding",nje=.1,LJ=.1,BJ=4,rje="plait-board-container",XR="active-with-moving",CD="rotate-handle",FJ="resize-handle",$J=20,ZR={MAIN:0,WHEEL:1},ME=3,JR=10,OE=5;function zJ(e){return!!e.beforeContextChange}function UJ(e){return!!e.onContextChanged}const ED=new WeakMap,D2=new WeakMap,rh=new WeakMap,gd=new WeakMap,HJ=new WeakMap,ym=new WeakMap,vm=new WeakMap,FS=new WeakMap,WJ=new WeakMap,VJ=new WeakMap,GJ=new WeakMap,KJ=new WeakMap,qJ=new WeakMap,YJ=new WeakMap,Yu=new WeakMap,QR=new WeakMap,XJ=new WeakMap,ZJ=new WeakMap,RE=new WeakMap,NE=new WeakMap,ow=new WeakMap,sw=new WeakMap,_D=new WeakMap,wm=new WeakMap;function _l(e){return e==null}const _g=(e,t)=>e+Math.floor(t*255).toString(16);function JJ(e){return e.button===2}function jE(e){const t=new Map;return e.forEach(n=>{t.has(n.id)||t.set(n.id,n)}),Array.from(t.values())}const QJ=(e,t,n=e.length-1)=>{n<0&&(n=e.length+n),n=Math.min(e.length-1,Math.max(n,0));let r=n+1;for(;--r>-1;)if(t(e[r],r,e))return r;return-1},eQ=(e,t,n=0)=>{n<0&&(n=e.length+n),n=Math.min(e.length,Math.max(n,0));let r=n-1;for(;++r<e.length;)if(t(e[r],r,e))return r;return-1},tQ=e=>{e.sort((t,n)=>t-n);for(let t=1;t<e.length;t++)if(e[t]!==e[t-1]+1)return!1;return!0},nQ={isViewport:e=>!_l(e.zoom)&&!_l(e.viewBackgroundColor)},pn={ancestors(e,t={}){const{reverse:n=!1}=t;let r=pn.levels(e,t);return n?r=r.slice(1):r=r.slice(0,-1),r},levels(e,t={}){const{reverse:n=!1}=t,r=[];for(let i=0;i<=e.length;i++)r.push(e.slice(0,i));return n&&r.reverse(),r},parent(e){if(e.length===0)throw new Error(`Cannot get the parent path of the root path [${e}].`);return e.slice(0,-1)},next(e){if(e.length===0)throw new Error(`Cannot get the next path of a root path [${e}], because it has no next index.`);const t=e[e.length-1];return e.slice(0,-1).concat(t+1)},hasPrevious(e){return e[e.length-1]>0},previous(e){if(e.length===0)throw new Error(`Cannot get the previous path of a root path [${e}], because it has no previous index.`);const t=e[e.length-1];if(t<=0)throw new Error(`Cannot get the previous path of a first child path [${e}] because it would result in a negative index.`);return e.slice(0,-1).concat(t-1)},isAncestor(e,t){return e.length<t.length&&pn.compare(e,t)===0},compare(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0},equals(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])},endsBefore(e,t){const n=e.length-1,r=e.slice(0,n),i=t.slice(0,n),o=e[n],s=t[n];return pn.equals(r,i)&&o<s},isSibling(e,t){if(e.length!==t.length)return!1;const n=e.slice(0,-1),r=t.slice(0,-1),i=e[e.length-1],o=t[t.length-1];return i!==o&&pn.equals(n,r)},transform(e,t){if(!e)return null;const n=[...e];if(e.length===0)return n;switch(t.type){case"insert_node":{const{path:r}=t;(pn.equals(r,n)||pn.endsBefore(r,n)||pn.isAncestor(r,n))&&(n[r.length-1]+=1);break}case"remove_node":{const{path:r}=t;if(pn.equals(r,n)||pn.isAncestor(r,n))return null;pn.endsBefore(r,n)&&(n[r.length-1]-=1);break}case"move_node":{const{path:r,newPath:i}=t;if(pn.equals(r,i))return n;if(pn.isAncestor(r,n)||pn.equals(r,n)){const o=i.slice();return pn.endsBefore(r,i)&&r.length<i.length&&(o[r.length-1]-=1),o.concat(n.slice(r.length))}else pn.isSibling(r,i)&&(pn.isAncestor(i,n)||pn.equals(i,n))?pn.endsBefore(r,n)?n[r.length-1]-=1:n[r.length-1]+=1:pn.endsBefore(i,n)||pn.equals(i,n)||pn.isAncestor(i,n)?(pn.endsBefore(r,n)&&(n[r.length-1]-=1),n[i.length-1]+=1):pn.endsBefore(r,n)&&(pn.equals(i,n)&&(n[i.length-1]+=1),n[r.length-1]-=1);break}}return n}},Vn={parent:(e,t)=>{const n=pn.parent(t);return Vn.get(e,n)},*parents(e,t,n={}){for(const r of pn.ancestors(t,n))yield Vn.get(e,r)},get(e,t){let n=e;for(let r=0;r<t.length;r++){const i=t[r];if(!n||!n.children||!n.children[i])throw new Error(`Cannot find a descendant at path [${t}]`);n=n.children[i]}return n},last(e,t){let n=Vn.get(e,t);for(;n&&n.children&&n.children.length>0;){const r=n.children.length-1;n=n.children[r]}return n},first(e,t){const n=t.slice();let r=Vn.get(e,n);if(!r.children||!e.isExpanded(r))return r;for(;r&&r.children&&r.children.length>0&&e.isExpanded(r)&&r.children.length!==0;)r=r.children[0],n.push(0);return r}},ije=(e,t,n,r,i)=>{var o,s;switch(i.type){case"insert_node":{const{path:a,node:l}=i,c=Vn.parent(e,a),u=a[a.length-1];if(!c.children||u>c.children.length)throw new Error(`Cannot apply an "insert_node" operation at path [${a}] because the destination is past the end of the node.`);c.children.splice(u,0,l);break}case"remove_node":{const{path:a}=i,l=Vn.parent(e,a),c=a[a.length-1];if(!l.children||c>l.children.length)throw new Error(`Cannot apply an "insert_node" operation at path [${a}] because the destination is past the end of the node.`);l.children.splice(c,1);break}case"move_node":{const{path:a,newPath:l}=i;if(pn.isAncestor(a,l))throw new Error(`Cannot move a path [${a}] to new path [${l}] because the destination is inside itself.`);const c=Vn.get(e,a),u=Vn.parent(e,a),d=a[a.length-1];(o=u.children)==null||o.splice(d,1);const f=pn.transform(a,i),p=Vn.get(e,pn.parent(f)),y=f[f.length-1];(s=p.children)==null||s.splice(y,0,c);break}case"set_node":{const{path:a,properties:l,newProperties:c}=i;if(a.length===0)throw new Error("Cannot set properties on the root node!");const u=Vn.get(e,a);for(const d in c){const f=c[d];f==null?delete u[d]:u[d]=f}for(const d in l)c.hasOwnProperty(d)||delete u[d];break}case"set_viewport":{const{newProperties:a}=i;if(a==null)n=a;else{if(n==null){if(!nQ.isViewport(a))throw new Error(`Cannot apply an incomplete "set_viewport" operation properties ${JSON.stringify(a)} when there is no current viewport.`);n={...a}}for(const l in a){const c=a[l];c==null?delete n[l]:n[l]=c}}break}case"set_selection":{const{newProperties:a}=i;a==null?t=a:t===null?t=i.newProperties:t=a;break}case"set_theme":{const{newProperties:a}=i;r=a;break}}return{selection:t,viewport:n,theme:r}},oje={transform(e,t){e.children=Ax(e.children);let n=e.viewport&&Ax(e.viewport),r=e.selection&&Ax(e.selection),i=e.theme&&Ax(e.theme);try{const o=ije(e,r,n,i,t);n=o.viewport,r=o.selection,i=o.theme}finally{e.children=Px(e.children),r?e.selection=ou(r)?Px(r):r:e.selection=null,e.viewport=ou(n)?Px(n):n,e.theme=ou(i)?Px(i):i}}},q={isHit:(e,t)=>q.isHitX(e,t)&&q.isHitY(e,t),isHitX:(e,t)=>{const n=e.x<t.x?e.x:t.x,r=e.x+e.width>t.x+t.width?e.x+e.width:t.x+t.width;return Math.floor(r-n-e.width-t.width)<=0},isHitY:(e,t)=>{const n=e.y<t.y?e.y:t.y,r=e.y+e.height>t.y+t.height?e.y+e.height:t.y+t.height;return Math.floor(r-n-e.height-t.height)<=0},getPoints(e){return[[e.x,e.y],[e.x+e.width,e.y+e.height]]},getRectangleByCenterPoint(e,t,n){return q.getRectangleByPoint([e[0]-t/2,e[1]-n/2],t,n)},getRectangleByPoint(e,t,n){return{x:e[0],y:e[1],width:t,height:n}},getRectangleByPoints(e){sje(e)&&(e=[e]);let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const s of e){const a=s.map(c=>c[0]),l=s.map(c=>c[1]);t=Math.min(t,...a),n=Math.min(n,...l),r=Math.max(r,...a),n=Math.min(n,...l),i=Math.max(i,...l)}return{x:t,y:n,width:r-t,height:i-n}},getCornerPointsByPoints(e){const t=e.map(a=>a[0]),n=e.map(a=>a[1]),r=Math.min(...t),i=Math.max(...t),o=Math.min(...n),s=Math.max(...n);return[[r,o],[i,o],[i,s],[r,s]]},getOutlineRectangle:(e,t)=>({x:e.x+t,y:e.y+t,width:e.width-t*2,height:e.height-t*2}),inflate:(e,t)=>{const n=t/2;return{x:e.x-n,y:e.y-n,width:e.width+n*2,height:e.height+n*2}},isEqual:(e,t)=>e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height,getCornerPoints:e=>[[e.x,e.y],[e.x+e.width,e.y],[e.x+e.width,e.y+e.height],[e.x,e.y+e.height]],getCenterPoint:e=>[e.x+e.width/2,e.y+e.height/2],getCenterPointByPoints:e=>q.getCenterPoint(q.getRectangleByPoints(e)),getEdgeCenterPoints:e=>[[e.x+e.width/2,e.y],[e.x+e.width,e.y+e.height/2],[e.x+e.width/2,e.y+e.height],[e.x,e.y+e.height/2]],getConnectionPoint:(e,t)=>[e.x+e.width*t[0],e.y+e.height*t[1]],expand(e,t,n=t,r=t,i=n){return{x:e.x-t,y:e.y-n,width:e.width+t+r,height:e.height+n+i}},getGapCenter(e,t,n){const r=n?"x":"y",i=n?"width":"height",s=[e[r],e[r]+e[i],t[r],t[r]+t[i]].sort((a,l)=>a-l);return(s[1]+s[2])/2},isPointInRectangle(e,t){const n=t[0],r=t[1];return n>e.x&&n<e.x+e.width&&r>e.y&&r<e.y+e.height},getBoundingRectangle(e){if(e.length===0)throw new Error("rectangles can not be empty array");let t=Number.MAX_VALUE,n=Number.MAX_VALUE,r=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return e.forEach(o=>{t=Math.min(t,o.x),n=Math.min(n,o.y),r=Math.max(r,o.x+o.width),i=Math.max(i,o.y+o.height)}),{x:t,y:n,width:r-t,height:i-n}}};function sje(e){return Array.isArray(e)&&e.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number")}function e3(e,t,n,r,i,o){const s=e-n,a=t-r,l=i-n,c=o-r,u=s*l+a*c,d=l*l+c*c;let f=-1;d!==0&&(f=u/d);let p,y;f<0?(p=n,y=r):f>1?(p=i,y=o):(p=n+f*l,y=r+f*c);const v=e-p,w=t-y;return Math.hypot(v,w)}function aw(e,t){const n=e[0],r=e[1],i=t[0][0],o=t[0][1],s=t[1][0],a=t[1][1],l=n-i,c=r-o,u=s-i,d=a-o,f=l*u+c*d,p=u*u+d*d;let y=-1;p!==0&&(y=f/p);let v,w;return y<0?(v=i,w=o):y>1?(v=s,w=a):(v=i+y*u,w=o+y*d),[v,w]}function t3(e,t){const n=t.length;let r=1/0;if(t.length===1)return kn(...t[0],...e);for(let i=0;i<n-1;i++){const o=t[i],s=t[i+1],a=e3(e[0],e[1],o[0],o[1],s[0],s[1]);a<r&&(r=a)}return r}function Dr(e,t,n=!0){const r=t.length;let i=1/0,o=e;for(let s=0;s<r;s++){const a=t[s];if(s===r-1&&!n)continue;const l=s===r-1?t[0]:t[s+1],c=e3(e[0],e[1],a[0],a[1],l[0],l[1]);c<i&&(i=c,o=aw(e,[a,l]))}return o}function LE(e,t){let n=1/0,r=e;for(const i of t){const o=aw(e,i),s=kn(e[0],e[1],o[0],o[1]);s<n&&(n=s,r=o)}return r}function ko(e,t,n,r){const i={x:t[0]-n,y:t[1]-r,height:r*2,width:n*2},o=Math.abs(e[0]-i.x-i.width/2),s=Math.abs(e[1]-i.y-i.height/2);let a=.707,l=.707;const c=Math.abs(i.width)/2,u=Math.abs(i.height)/2;[0,1,2,3].forEach(p=>{const y=c*a,v=u*l,w=(c*c-u*u)*a**3/c,C=(u*u-c*c)*l**3/u,x=y-w,E=v-C,_=o-w,I=s-C,D=Math.hypot(E,x),P=Math.hypot(I,_);a=Math.min(1,Math.max(0,(_*D/P+w)/c)),l=Math.min(1,Math.max(0,(I*D/P+C)/u));const k=Math.hypot(l,a);a/=k,l/=k});const d=e[0]>t[0]?1:-1,f=e[1]>t[1]?1:-1;return[t[0]+c*a*d,t[1]+u*l*f]}function bh(e,t,n,r,i){return[(e-n)*Math.cos(i)-(t-r)*Math.sin(i)+n,(e-n)*Math.sin(i)+(t-r)*Math.cos(i)+r]}function kn(e,t,n,r){const i=e-n,o=t-r;return Math.hypot(i,o)}function ry(e,t,n){var r=Math.max(n.x-e,0,e-(n.x+n.width)),i=Math.max(n.y-t,0,t-(n.y+n.height));return Math.sqrt(r*r+i*i)}const V0=(e,t,n,r)=>{if(on.isEquals(e,t)&&on.isEquals(n,r)&&!on.isEquals(e,n))return!1;const i=(d,f)=>d[0]*f[1]-d[1]*f[0],o=[t[0]-e[0],t[1]-e[1]],s=[n[0]-e[0],n[1]-e[1]],a=[r[0]-e[0],r[1]-e[1]],l=[e[0]-n[0],e[1]-n[1]],c=[t[0]-n[0],t[1]-n[1]],u=[r[0]-n[0],r[1]-n[1]];return i(o,s)*i(o,a)<=0&&i(u,l)*i(u,c)<=0},r1=(e,t)=>{if(e.length===1)return q.isPointInRectangle(t,e[0]);const n=q.getCornerPoints(t),r=e.length;for(let i=0;i<r;i++){const o=e[i],s=e[(i+1)%r];if(i===r-1&&on.isEquals(o,s))continue;if(rQ(o,s,t)||hc(o,n)||hc(s,n))return!0}return!1},rQ=(e,t,n)=>{const r=q.getCornerPoints(n);return V0(e,t,r[0],r[1])||V0(e,t,r[1],r[2])||V0(e,t,r[2],r[3])||V0(e,t,r[3],r[0])},hc=(e,t)=>{const n=e[0],r=e[1];let i=!1;for(var o=0,s=t.length-1;o<t.length;s=o++){let a=t[o][0],l=t[o][1],c=t[s][0],u=t[s][1];l>r!=u>r&&n<(c-a)*(r-l)/(u-l)+a&&(i=!i)}return i},pc=(e,t,n,r,i=0)=>{const o=Math.cos(i),s=Math.sin(i),a=(e[0]-t[0])*o+(e[1]-t[1])*s,l=(e[1]-t[1])*o-(e[0]-t[0])*s;return a*a/(n*n)+l*l/(r*r)<=1},BE=(e,t,n,r=0)=>{const{x:i,y:o,width:s,height:a}=t,l=e[0]>=i&&e[0]<=i+s&&e[1]>=o&&e[1]<=o+a,c=e[0]>=i&&e[0]<=i+n&&e[1]>=o&&e[1]<=o+n&&Math.hypot(e[0]-(i+n),e[1]-(o+n))>n,u=e[0]>=i&&e[0]<=i+n&&e[1]>=o+a&&e[1]<=o+a-n&&Math.hypot(e[0]-(i+n),e[1]-(o+a-n))>n,d=e[0]>=i+s-n&&e[0]<=i+s&&e[1]>=o&&e[1]<=o+n&&Math.hypot(e[0]-(i+s-n),e[1]-(o+n))>n,f=e[0]>=i+s-n&&e[0]<=i+s&&e[1]>=o+a-n&&e[1]<=o+a&&Math.hypot(e[0]-(i+s-n),e[1]-(o+a-n))>n;return l&&!(c||u||d||f)},iy=function(e){let n,r,i,o,s,a,l,c,u,d,f,p,y;var v,w,C,x,E,_;const I=[];I.push([Math.round(e[0][0]),Math.round(e[0][1])]);for(var D=e.length,P=0;P<D-1;P++)n=P==0?e[0]:e[P-1],r=e[P],i=e[P+1],o=P+2<D?e[P+2]:i,l=Math.sqrt(Math.pow(n[0]-r[0],2)+Math.pow(n[1]-r[1],2)),c=Math.sqrt(Math.pow(r[0]-i[0],2)+Math.pow(r[1]-i[1],2)),u=Math.sqrt(Math.pow(i[0]-o[0],2)+Math.pow(i[1]-o[1],2)),v=Math.pow(u,.5),C=Math.pow(u,2*.5),w=Math.pow(c,.5),x=Math.pow(c,2*.5),_=Math.pow(l,.5),E=Math.pow(l,2*.5),d=2*E+3*_*w+x,f=2*C+3*v*w+x,p=3*_*(_+w),p>0&&(p=1/p),y=3*v*(v+w),y>0&&(y=1/y),s=[(-x*n[0]+d*r[0]+E*i[0])*p,(-x*n[1]+d*r[1]+E*i[1])*p],a=[(C*r[0]+f*i[0]-x*o[0])*y,(C*r[1]+f*i[1]-x*o[1])*y],s[0]==0&&s[1]==0&&(s=r),a[0]==0&&a[1]==0&&(a=i),I.push(s,a,i);return I};function Ol(e,t,n,r){return Math.abs(t)===0?e>0?-1/0:1/0:-r*r*e/(n*n*t)}function Rl(e,t,n){if(n===1/0)return[0,-1];if(n===-1/0)return[0,1];let r=[1,-n];return t<0&&(r=[-r[0],-r[1]]),r}function FE(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}function $S(e,t,n=1e-6){return Math.abs(e-t)<=n}function ID(e,t,n,r,i,o,s=!0){if(i===0||o===0||e[0]===t[0]&&e[1]===t[1])return[];i=i<0?i:-i,o=o<0?o:-o,e[0]-=n,e[1]-=r,t[0]-=n,t[1]-=r;var a=(t[0]-e[0])*(t[0]-e[0])/i/i+(t[1]-e[1])*(t[1]-e[1])/o/o,l=2*e[0]*(t[0]-e[0])/i/i+2*e[1]*(t[1]-e[1])/o/o,c=e[0]*e[0]/i/i+e[1]*e[1]/o/o-1,u=[],d=l*l-4*a*c;return d===0?u.push(-l/2/a):d>0&&(u.push((-l+Math.sqrt(d))/2/a),u.push((-l-Math.sqrt(d))/2/a)),u.filter(f=>!s||f>=0&&f<=1).map(f=>[e[0]+(t[0]-e[0])*f+n,e[1]+(t[1]-e[1])*f+r])}function aje(e,t,n,r,i=.5){return[e+(n-e)*i,t+(r-t)*i]}function n3(e,t){const n=(t.endX-e[0])/2,r=(t.endY-e[1])/2,i=Math.cos(t.xAxisRotation),o=Math.sin(t.xAxisRotation),s=i*n+o*r,a=-o*n+i*r,l=Math.abs(t.rx),c=Math.abs(t.ry),u=s*s/(l*l)+a*a/(c*c),d=u>1?Math.sqrt(u):1,f=l*d,p=c*d,y=t.largeArcFlag===t.sweepFlag?-1:1,v=(f*f*p*p-f*f*a*a-p*p*s*s)/(f*f*a*a+p*p*s*s),w=y*Math.sqrt(Math.max(0,v)),C=w*(f*a/p),x=w*(-(p*s)/f),E=i*C-o*x+(e[0]+t.endX)/2,_=o*C+i*x+(e[1]+t.endY)/2;return{center:[E,_],rx:f,ry:p}}function lw(e,t,n){const{center:r,rx:i,ry:o}=n3(t,n),s=ko(e,r,i,o),a=Math.atan2(t[1]-r[1],t[0]-r[0]),l=Math.atan2(n.endY-r[1],n.endX-r[0]),c=Math.atan2(s[1]-r[1],s[0]-r[0]);if(lje(c,a,l,n.sweepFlag===1))return s;const d=kn(e[0],e[1],t[0],t[1]),f=kn(e[0],e[1],n.endX,n.endY);return d<f?t:[n.endX,n.endY]}function lje(e,t,n,r){const i=l=>(l%(2*Math.PI)+2*Math.PI)%(2*Math.PI),o=i(e),s=i(t),a=i(n);return r?s<=a?o>=s&&o<=a:o>=s||o<=a:s>=a?o<=s&&o>=a:o<=s||o>=a}function iQ(e,t,n){const i=ne.getBoardContainer(e).getBoundingClientRect();return ry(t,n,i)===0}function $E(e){const{hideScrollbar:t}=e.options;let n=0;if(!t){const r=ne.getViewportContainer(e);n=r.offsetWidth-r.clientWidth}return n}const Gh="http://www.w3.org/2000/svg";function Tn(){return document.createElementNS(Gh,"g")}function zE(){return document.createElementNS(Gh,"path")}function M2(e,t){const n=document.createElementNS(Gh,"rect");n.setAttribute("x",`${e.x}`),n.setAttribute("y",`${e.y}`),n.setAttribute("width",`${e.width}`),n.setAttribute("height",`${e.height}`);for(let r in t){const i=r;n.setAttribute(r,`${t[i]}`)}return n}const Un=(e,t)=>{e.setAttribute("stroke-linecap",t)},oQ=(e,t)=>{e.querySelectorAll("path").forEach(n=>{n.setAttribute("stroke-linecap",t)})};function sQ(){return document.createElementNS(Gh,"mask")}function aQ(e,t,n,r){var i=document.createElementNS(Gh,"text");return i.setAttribute("x",`${e}`),i.setAttribute("y",`${t}`),i.setAttribute("fill",n),i.textContent=r,i}const lQ=e=>cQ(e)&&e.nodeType===1,cQ=e=>e instanceof window.Node,cje=e=>!!(lQ(e)&&(e.tagName==="INPUT"||e.tagName==="TEXTAREA")),Il=e=>e.button===ZR.MAIN,uQ=e=>e.button===ZR.WHEEL;function UE(e,t,n,r){var i=document.createElementNS(Gh,"foreignObject");return i.setAttribute("x",`${e}`),i.setAttribute("y",`${t}`),i.setAttribute("width",`${FE(n,0)}`),i.setAttribute("height",`${r}`),i}function Hm(e,t,n,r,i){const o=e instanceof SVGForeignObjectElement?e:e.querySelector("foreignObject");o&&(o.setAttribute("width",`${FE(t,0)}`),o.setAttribute("height",`${n}`),o.setAttribute("x",`${r}`),o.setAttribute("y",`${i}`))}function dQ(e,t){const n=e instanceof SVGForeignObjectElement?e:e.querySelector("foreignObject");n&&n.setAttribute("width",`${FE(t,0)}`)}const fQ=typeof window<"u"&&/Mac|iPod|iPhone|iPad/.test(window.navigator.platform),uje=typeof navigator<"u"&&typeof window<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,zS=typeof navigator<"u"&&/Mac OS X/.test(navigator.userAgent),dje=typeof navigator<"u"&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent),fje=typeof navigator<"u"&&/Version\/[\d\.]+.*Safari/.test(navigator.userAgent),hje=typeof navigator<"u"&&/Chrome/i.test(navigator.userAgent),hQ=(e,t)=>e.type==="set_viewport"&&e.type===(t==null?void 0:t.type),pQ=(e,t)=>!(e.type==="set_selection"||e.type==="set_viewport"),mQ=e=>e.type!=="set_selection",Ca={isSaving(e){return R2.get(e)},isMerging(e){return Qi.get(e)},isSplittingOnce(e){return K0.get(e)},setSplittingOnce(e,t){K0.set(e,t)},withMerging(e,t){const n=Ca.isMerging(e);Qi.set(e,!0),t(),Qi.set(e,n)},withNewBatch(e,t){const n=Ca.isMerging(e);Qi.set(e,!0),K0.set(e,!0),t(),Qi.set(e,n),K0.delete(e)},withoutMerging(e,t){const n=Ca.isMerging(e);Qi.set(e,!1),t(),Qi.set(e,n)},withoutSaving(e,t){const n=Ca.isSaving(e);R2.set(e,!1),t(),R2.set(e,n)}},pje={bold:"mod+b",compose:["down","left","right","up","backspace","enter"],arrow:["down","left","right","up"],extendArrow:["shift+down","shift+left","shift+right","shift+up"],moveBackward:"left",moveForward:"right",moveUp:"up",moveDown:"down",moveWordBackward:"ctrl+left",moveWordForward:"ctrl+right",deleteBackward:"shift?+backspace",deleteForward:"shift?+delete",extendBackward:"shift+left",extendForward:"shift+right",extendUp:"shift+up",extendDown:"shift+down",italic:"mod+i",splitBlock:"shift?+enter",undo:"mod+z",shift:"shift"},mje={moveLineBackward:"opt+up",moveLineForward:"opt+down",moveWordBackward:"opt+left",moveWordForward:"opt+right",deleteBackward:["ctrl+backspace","ctrl+h"],deleteForward:["ctrl+delete","ctrl+d"],deleteLineBackward:"cmd+shift?+backspace",deleteLineForward:["cmd+shift?+delete","ctrl+k"],deleteWordBackward:"opt+shift?+backspace",deleteWordForward:"opt+shift?+delete",extendLineBackward:"opt+shift+up",extendLineForward:"opt+shift+down",redo:"cmd+shift+z",transposeCharacter:"ctrl+t"},gje={deleteWordBackward:"ctrl+shift?+backspace",deleteWordForward:"ctrl+shift?+delete",redo:["ctrl+y","ctrl+shift+z"]},Er=e=>{const t=pje[e],n=mje[e],r=gje[e],i=t&&$r.isKeyHotkey(t),o=n&&$r.isKeyHotkey(n),s=r&&$r.isKeyHotkey(r);return a=>!!(i&&i(a)||zS&&o&&o(a)||!zS&&s&&s(a))},wo={isBold:Er("bold"),isCompose:Er("compose"),isArrow:Er("arrow"),isMoveBackward:Er("moveBackward"),isMoveForward:Er("moveForward"),isMoveUp:Er("moveUp"),isMoveDown:Er("moveDown"),isDeleteBackward:Er("deleteBackward"),isDeleteForward:Er("deleteForward"),isDeleteLineBackward:Er("deleteLineBackward"),isDeleteLineForward:Er("deleteLineForward"),isDeleteWordBackward:Er("deleteWordBackward"),isDeleteWordForward:Er("deleteWordForward"),isExtendBackward:Er("extendBackward"),isExtendForward:Er("extendForward"),isExtendUp:Er("extendUp"),isExtendDown:Er("extendDown"),isExtendArrow:Er("extendArrow"),isExtendLineBackward:Er("extendLineBackward"),isExtendLineForward:Er("extendLineForward"),isItalic:Er("italic"),isMoveLineBackward:Er("moveLineBackward"),isMoveLineForward:Er("moveLineForward"),isMoveWordBackward:Er("moveWordBackward"),isMoveWordForward:Er("moveWordForward"),isRedo:Er("redo"),isSplitBlock:Er("splitBlock"),isTransposeCharacter:Er("transposeCharacter"),isUndo:Er("undo"),isShift:Er("shift")};function fr(e=5){const t="ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz",n=t.length;let r="";for(let i=0;i<e;i++)r+=t.charAt(Math.floor(Math.random()*n));return r}function co(e,t,n,r){if(e.children&&(!n||n(e))){let i=[...e.children];i=r?i.reverse():i,i.forEach(o=>{co(o,t,n)})}t(e)}const zd=e=>t=>!!(ne.isBoard(t)||e.isRecursion(t)),ns="#6698FF",HE="#6698FF25",xh={isCollapsed(e){return e.anchor[0]==e.focus[0]&&e.anchor[1]===e.focus[1]}},sr={isRootElement(e){const t=gd.get(e);return!!(t&&ne.isBoard(t))},getElementRef(e){return wm.get(e)},getElementG(e){const t=ym.get(e);if(!t)throw new Error(`can not resolve element g: ${JSON.stringify(e)}`);return t},hasMounted(e){return!!sr.getContainerG(e,{suppressThrow:!0})},getContainerG(e,t){const n=vm.get(e)||null;if(!n){if(t.suppressThrow)return null;throw new Error("can not resolve container g")}return n}},cw=(e,t,n=!0)=>[...t].sort((r,i)=>{const o=ne.findPath(e,r),s=ne.findPath(e,i);return n?o[0]-s[0]:s[0]-o[0]}),gQ=new Map,I0=e=>gQ.get(e)||[],A0=(e,t)=>{gQ.set(e,t)};class yQ{constructor(t){this.debugKey=t}isDebug(){return Wc(this.debugKey)}clear(){if(!this.isDebug())return;const t=I0(this.debugKey);A0(this.debugKey,[]),t.forEach(n=>n.remove())}drawPolygon(t,n,r){if(!Wc(this.debugKey))return;const i=ne.getRoughSVG(t).polygon(n,r||{stroke:"red"});i.classList.add(this.debugKey),ne.getElementTopHost(t).append(i);const o=I0(this.debugKey);return o.push(i),A0(this.debugKey,o),i}drawLine(t,n,r){if(!Wc(this.debugKey))return;const i=ne.getRoughSVG(t).linearPath(n,r||{stroke:"red"});i.classList.add(this.debugKey),ne.getElementTopHost(t).append(i);const o=I0(this.debugKey);return o.push(i),A0(this.debugKey,o),i}drawRectangle(t,n,r){if(!Wc(this.debugKey))return;let i;n instanceof Array?i=q.getRectangleByPoints(n):i=n;const o=ne.getRoughSVG(t).rectangle(i.x,i.y,i.width,i.height,r||{stroke:"red"});o.classList.add(this.debugKey),ne.getElementTopHost(t).append(o);const s=I0(this.debugKey);return s.push(o),A0(this.debugKey,s),o}drawCircles(t,n,r=0,i=!1,o){if(!Wc(this.debugKey))return;const s=[];return n.forEach((a,l)=>{const c=ne.getRoughSVG(t).circle(a[0],a[1],i?r*(l+1):r,Object.assign({},{stroke:"red",fill:"red",fillStyle:"solid"},o||{}));c.classList.add(this.debugKey),ne.getElementTopHost(t).append(c);const u=I0(this.debugKey);u.push(c),s.push(c),A0(this.debugKey,u)}),s}}const Kh=e=>new yQ(e),Wc=e=>localStorage.getItem(e||"debug:plait")==="true";var xl;(function(e){e.withSelection="withSelection",e.withHand="withHand"})(xl||(xl={}));const r3=(e,t,n=()=>!0)=>{const r=t||e.selection,i=[];if(!r)return[];if(xh.isCollapsed(r)){const s=i3(e,r.anchor,n);return s!=null&&s.length?s:[]}return co(e,s=>{if(!ne.isBoard(s)&&n(s)){let a=!1;try{a=e.isRectangleHit(s,r)}catch(l){Wc()&&console.error("isRectangleHit",l,"node",s)}a&&i.push(s)}},zd(e),!0),i},i3=(e,t,n=()=>!0,r=!0)=>{let i=[];return co(e,o=>{if(ne.isBoard(o)||!n(o)||!sr.hasMounted(o))return;let s=!1;try{s=e.isHit(o,t,r)}catch(a){Wc()&&console.error("isHit",a,"node",o)}if(s){i.push(o);return}},zd(e),!0),i},$a=(e,t,n=()=>!0,r=!0)=>{const i=i3(e,t,n,r);return e.getOneHitElement(i)},vQ=(e,t)=>{const n=Et(e),r=n.length>0&&Pn(e,n,!1);return r&&q.isPointInRectangle(r,t)?n:[]},yl=(e,t)=>{const n=cw(e,t);QR.set(e,n)},Et=e=>QR.get(e)||[],za=(e,t)=>{let n=[];Array.isArray(t)?n.push(...t):n.push(t);const r=Et(e);yl(e,[...r,...n])},uw=(e,t,n=!1)=>{const r=Et(e);if(r.includes(t)){const i=[];e.isRecursion(t)&&n?co(t,s=>{i.push(s)},s=>e.isRecursion(s)):i.push(t);const o=r.filter(s=>!i.includes(s));yl(e,o)}},wQ=(e,t,n)=>{const r=Et(e);r.splice(r.indexOf(t),1,n)},Nl=e=>{yl(e,[])},yd=(e,t)=>!!Et(e).find(r=>r===t),US=e=>{const t=e.getPluginOptions(xl.withSelection);e.setPluginOptions(xl.withSelection,{isDisabledSelection:!0}),setTimeout(()=>{e.setPluginOptions(xl.withSelection,{...t})},0)},bQ=(e,t)=>vQ(e,t).length>0,o3=(e,t)=>!!$a(e,t)||bQ(e,t);function qh(e,t,n,r,i,o,s=!1,a){let l=a||0;const c=[t+l,n],u=[r-l,n],d=[r,n+l],f=[r,i-l],p=[r-l,i],y=[t+l,i],v=[t,i-l],w=[t,n+l],C=e.path(`M${u[0]} ${u[1]} A ${l} ${l}, 0, 0, 1, ${d[0]} ${d[1]} L ${f[0]} ${f[1]} A ${l} ${l}, 0, 0, 1, ${p[0]} ${p[1]} L ${y[0]} ${y[1]} A ${l} ${l}, 0, 0, 1, ${v[0]} ${v[1]} L ${w[0]} ${w[1]} A ${l} ${l}, 0, 0, 1, ${c[0]} ${c[1]} Z`,o);return Un(C,"round"),C}const Ua=(e,t,n)=>{const i=ne.getRoughSVG(e).rectangle(t.x,t.y,t.width,t.height,n);return Un(i,"round"),i};function Yh(e,t,n=40){const r=Math.abs(e[0]-t[0]),i=Math.abs(e[1]-t[1]);let o=Math.hypot(r,i);const s=o/2,a=s/o*r,l=s/o*i,c=[t[0]>e[0]?t[0]-a:t[0]+a,t[1]>e[1]?t[1]-l:t[1]+l],u=bh(c[0],c[1],t[0],t[1],n*Math.PI/180);return{pointLeft:bh(c[0],c[1],t[0],t[1],-n*Math.PI/180),pointRight:u}}function Ud(e,t,n,r){return e.circle(t[0],t[1],n,r)}function G0(e,t,n,r){return e.linearPath([t,n],r)}function aa(e,t,n){const r=Tn(),i=zE();let o="";return e.forEach((s,a)=>{a===0?o+=`M ${s[0]} ${s[1]} `:o+=`L ${s[0]} ${s[1]} `}),n&&(o+="Z"),i.setAttribute("d",o),i.setAttribute("stroke",`${t==null?void 0:t.stroke}`),i.setAttribute("stroke-width",`${t==null?void 0:t.strokeWidth}`),i.setAttribute("fill",`${(t==null?void 0:t.fill)||"none"}`),t!=null&&t.strokeLineDash&&i.setAttribute("stroke-dasharray",`${t.strokeLineDash}`),r.appendChild(i),r}function xQ(e,t){const n=Tn(),r=zE();let i="";for(let o=0;o<e.length-3;o+=3)o===0?i+=`M ${e[0][0]} ${e[0][1]} `:i+=`C ${e[o+1][0]} ${e[o+1][1]}, ${e[o+2][0]} ${e[o+2][1]}, ${e[o+3][0]} ${e[o+3][1]}`;return r.setAttribute("d",i),r.setAttribute("stroke",`${t==null?void 0:t.stroke}`),r.setAttribute("stroke-width",`${t==null?void 0:t.strokeWidth}`),r.setAttribute("fill","none"),n.appendChild(r),n}function s3(e,t){const n={type:"set_viewport",properties:e.viewport,newProperties:t};e.apply(n)}const yje={setViewport:s3};function vje(e,t){const n={type:"set_theme",properties:e.theme,newProperties:t};e.apply(n)}function WE(e,t,n){n=n??e.viewport.zoom,s3(e,{...e.viewport,zoom:n,origination:t}),p3(e)}function wje(e,t,n){t=PQ(t);const i=ne.getBoardContainer(e).getBoundingClientRect(),o=ne.getBoardContainer(e).getBoundingClientRect();let s=[o.width/2,o.height/2];n&&ry(n[0],n[1],i)===0&&(s=[n[0]-i.x,n[1]-i.y]);const a=e.viewport.zoom,l=Xh(e),c=l[0]+s[0]/a,u=l[1]+s[1]/a,d=[c-s[0]/t,u-s[1]/t];WE(e,d,t)}function bje(e){let t=$E(e);const n=ne.getBoardContainer(e).getBoundingClientRect(),r=Pn(e,e.children,!0),i=e.viewport.zoom,o=16,s=n.width-2*o,a=n.height-2*o;let l=i;s<r.width||a<r.height?l=Math.min(s/r.width,a/r.height):l=1;const c=d3(e),u=[c[0]-n.width/2/l+t/2/i,c[1]-n.height/2/l+t/2/i];WE(e,u,l)}function xje(e,t){let n=$E(e);const r=ne.getBoardContainer(e),i=r.getBoundingClientRect();let o=0;t.maxWidth?o=t.maxWidth:o=i.width;const s=Pn(e,e.children,!0),a=o-2*t.autoFitPadding;let l=0;a<s.width?l=Math.min(a/s.width):l=1;let c=s.height*l+2*t.autoFitPadding;if(c>t.limitHeight){const p=r.closest(`.${t.containerClass}`);p.style.height=`${c}px`,TQ(e)}else c=t.limitHeight;const u=s.x+s.width/2,d=s.y+s.height/2,f=[u-o/2/l+n/2/l,d-c/2/l+n/2/l];WE(e,f,l)}function Sje(e,t){t=t??e.theme.themeColorMode,vje(e,{themeColorMode:t}),co(e,n=>{e.applyTheme(n)})}const Cje=(e,t)=>{e.pointer!==t&&(e.pointer=t)};function Eje(e,t){var r;if((r=Et(e))==null?void 0:r[0]){const i=ne.getBoardContainer(e).getBoundingClientRect(),o=$E(e),s=d3(e),a=t[0]-s[0],l=t[1]-s[1],c=e.viewport.zoom,u=[a-i.width/2/c+o/2/c,l-i.height/2/c+o/2/c];s3(e,{...e.viewport,origination:u}),p3(e)}}const $i={updatePointerType:Cje,updateViewport:WE,fitViewport:bje,updateZoom:wje,updateThemeColor:Sje,fitViewportWidth:xje,moveToCenter:Eje},VE=e=>ne.getHost(e).viewBox.baseVal;function An(e,t,n){const i=ne.getHost(e).getBoundingClientRect();return[t-i.x,n-i.y]}function _o(e,t){const n=[t.x,t.y],r=[t.x+t.width,t.y+t.height],i=Ig(e,n),o=Ig(e,r);return q.getRectangleByPoints([i,o])}function Ig(e,t){const n=CQ(e,a3(e,t));return Ed(e,n[0],n[1])}function Ed(e,t,n){const i=ne.getBoardContainer(e).getBoundingClientRect();return[t-i.x,n-i.y]}function SQ(e,t){const r=ne.getBoardContainer(e).getBoundingClientRect();return[r.x+t[0],r.y+t[1]]}function _n(e,t){const n=VE(e),{zoom:r}=e.viewport,i=t[0]/r+n.x,o=t[1]/r+n.y;return[i,o]}function CQ(e,t){const r=ne.getHost(e).getBoundingClientRect();return[t[0]+r.x,t[1]+r.y]}function a3(e,t){const{zoom:n}=e.viewport,r=VE(e),i=(t[0]-r.x)*n,o=(t[1]-r.y)*n;return[i,o]}const l3=.75,EQ=new WeakMap,_Q=new WeakMap;function IQ(e){const{hideScrollbar:t}=e.options,n=t?$J:0,r=ne.getBoardContainer(e).getBoundingClientRect();return{width:r.width+n,height:r.height+n}}function AQ(e,t){const n=Pn(e,e.children,!0);let r,i,o,s;return r=n.x,i=n.x+n.width,o=n.y,s=n.y+n.height,{left:r,right:i,top:o,bottom:s}}function PQ(e,t=LJ,n=BJ){return e<t?t:e>n?n:e}function c3(e,t){const n=ne.getBoardContainer(e).getBoundingClientRect(),r=AQ(e),i=n.width,o=n.height;let s=r.right-r.left,a=r.bottom-r.top;const l=i/2,c=o/2;if(s<l/t){const u=r.left+s/2;r.left=u-l/2/t,r.right=u+l/2/t,s=l/t}if(a<c/t){const u=r.top+a/2;r.top=u-c/2/t,r.bottom=u+c/2/t,a=c/t}return{elementHostBBox:r,containerWidth:i,containerHeight:o,width:s,height:a}}function HS(e,t,n,r,i,o,s=l3){const a=t*s/o,l=n*s/o;return[e.left-a,e.top-l,r+a*2,i+l*2]}function u3(e,t){const{elementHostBBox:n,containerWidth:r,containerHeight:i,width:o,height:s}=c3(e,t);return HS(n,r,i,o,s,t)}function d3(e){const t=Pn(e,e.children,!0);return[t.x+t.width/2,t.y+t.height/2]}function f3(e,t){const n=e.viewport.zoom,r=ne.getHost(e);r.style.display="block",r.style.width=`${t[2]*n}px`,r.style.height=`${t[3]*n}px`,t&&t[2]>0&&t[3]>0&&r.setAttribute("viewBox",t.join(" "))}function AD(e){const t=Xh(e);if(!t)return;const[n,r]=a3(e,t);h3(e,n,r)}function h3(e,t,n,r=!0){const i=ne.getViewportContainer(e),o=i.scrollLeft,s=i.scrollTop;if(!$S(i.scrollLeft,t,1)||!$S(i.scrollTop,n,1)){i.scrollLeft=t,i.scrollTop=n;const a=i.offsetWidth,l=i.offsetHeight;if(o===i.scrollLeft&&s===i.scrollTop)kQ(e,o,s);else{const c=t>0&&n>0&&t<i.scrollWidth-a&&n<i.scrollHeight-l;r&&c&&OQ(e,!0)}}}function kQ(e,t,n){const r=_n(e,[t,n]);on.isEquals(r,Xh(e))||($i.updateViewport(e,r),MQ(e,!0))}function TQ(e){const{width:t,height:n}=IQ(e),r=ne.getViewportContainer(e);r.style.width=`${t}px`,r.style.height=`${n}px`}function _je(e){const t=e.viewport.zoom,n=u3(e,t);f3(e,n)}function Ije(e){const t=e.viewport.zoom,{elementHostBBox:n,containerWidth:r,containerHeight:i,width:o,height:s}=c3(e,t),a=HS(n,r,i,o,s,t,.5),l=VE(e);if(a[0]<l.x||a[1]<l.y||a[0]+a[2]>l.x+l.width||a[1]+a[3]>l.y+l.height){const c=HS(n,r,i,o,s,t,l3);f3(e,c)}}function Aje(e){var t;if(!((t=e.viewport)!=null&&t.origination)){const n=e.viewport.zoom,r=ne.getBoardContainer(e).getBoundingClientRect(),i=u3(e,n),o=i[0]+i[2]/2,s=i[1]+i[3]/2,a=[o-r.width/2/n,s-r.height/2/n];DQ(e,a),AD(e);return}AD(e)}const DQ=(e,t)=>{RE.set(e,t)},p3=e=>{RE.delete(e)},Xh=e=>{const t=RE.get(e);return t||e.viewport.origination},Pje=e=>!!EQ.get(e),MQ=(e,t)=>{EQ.set(e,t)},kje=e=>!!_Q.get(e),OQ=(e,t)=>{_Q.set(e,t)};function Tje(e,t,n){const r={type:"insert_node",node:t,path:n};e.apply(r)}function Dje(e,t,n){const r={},i={},o=Vn.get(e,n);for(const a in t)o[a]!==t[a]&&(o.hasOwnProperty(a)&&(r[a]=o[a]),t[a]!=null&&(i[a]=t[a]));const s={type:"set_node",properties:r,newProperties:i,path:n};e.apply(s)}function RQ(e,t){const n=Vn.get(e,t),r={type:"remove_node",path:t,node:n};e.apply(r)}function Mje(e,t,n){const r={type:"move_node",path:t,newPath:n};e.apply(r)}const ih={insertNode:Tje,setNode:Dje,removeNode:RQ,moveNode:Mje},O2=new WeakMap,Oje=(e,t)=>NQ(e)[t]||null,NQ=e=>O2.get(e)||{},mc=(e,t,n)=>{const r=()=>{let o=requestAnimationFrame(()=>{const a=O2.get(e)||{};a[t]=null,O2.set(e,a),ne.isAlive(e)&&n()});const s=NQ(e);s[t]=o,O2.set(e,s)};let i=Oje(e,t);i!==null&&cancelAnimationFrame(i),r()},dw=(e,t)=>(cw(e,t),t.map(n=>e.children.map(r=>r.id).indexOf(n.id)).filter(n=>n>=0)),jQ=(e,t)=>{const n=dw(e,t);return n[n.length-1]},oy=(e,t)=>{t.map(n=>{const r=ne.findPath(e,n.element),i=e.pathRef(r);return()=>{i.current&&ih.moveNode(e,i.current,n.newPath),i.unref()}}).forEach(n=>{n()})},m3=new WeakMap,sy=e=>!!m3.get(e),Cc=(e,t)=>{m3.set(e,t)},LQ=e=>sw.get(e)||[],Ag=e=>(sw.get(e)||[]).length>0,BQ=e=>{sw.delete(e),Cc(e,!1)},PD=(e,t)=>{sw.set(e,t),Cc(e,!0)},kD="foreignObject[class^='foreign-object']";function gz(e){return e.nodeType===Node.ELEMENT_NODE}function Rje(e){return new Promise((t,n)=>{const r=new Image;r.crossOrigin="Anonymous",r.onload=()=>t(r),r.onerror=()=>n(new Error("Failed to load image")),r.src=e})}function Nje(e,t,n="transparent"){const r=document.createElement("canvas"),i=r.getContext("2d");return r.width=e,r.height=t,r.style.width=`${e}px`,r.style.height=`${t}px`,i.strokeStyle="#ffffff",i.fillStyle=n,i.fillRect(0,0,e,t),{canvas:r,ctx:i}}async function jje(e){const n=await(await fetch(e)).blob();return new Promise((r,i)=>{const o=new FileReader;o.onloadend=()=>r(o.result),o.onerror=i,o.readAsDataURL(n)})}function Lje(e,t){const n=t==null?void 0:t.style;if(!n)return;const r=window.getComputedStyle(e);r.cssText?(n.cssText=r.cssText,n.transformOrigin=r.transformOrigin):Array.from(r).forEach(i=>{let o=r.getPropertyValue(i);n.setProperty(i,o,r.getPropertyPriority(i))})}function Bje(e,t,n){if(n){const r=n+`, ${kD}`,i=Array.from(e.querySelectorAll(r)),o=Array.from(t.querySelectorAll(r));i.forEach((s,a)=>{const l=Array.from(s.querySelectorAll("*")).filter(gz),c=Array.from(o[a].querySelectorAll("*")).filter(gz);i.push(...l),o.push(...c)}),i.map((s,a)=>{Lje(s,o[a])})}}async function Fje(e,t){const n=Array.from(e.querySelectorAll(`${kD}`)),r=Array.from(t.querySelectorAll(`${kD}`));await Promise.all(n.map((i,o)=>new Promise(s=>{const l=r[o].querySelector("img"),c=l==null?void 0:l.getAttribute("src");if(!c)return s(!0);jje(c).then(u=>{l==null||l.setAttribute("src",u),s(!0)})})))}async function $je(e,t,n,r){const{width:i,height:o,x:s,y:a}=n,{padding:l=4,inlineStyleClassNames:c}=r,u=ne.getHost(e),d=t.map(v=>sr.getElementG(v)),f=u.cloneNode(),p=ne.getElementHost(e).cloneNode();f.style.width=`${i}px`,f.style.height=`${o}px`,f.style.backgroundColor="",f.setAttribute("width",`${i}`),f.setAttribute("height",`${o}`),f.setAttribute("viewBox",[s-l,a-l,i+2*l,o+2*l].join(","));const y=new Array(d.length);return await Promise.all(d.map(async(v,w)=>{const C=v.cloneNode(!0);Bje(v,C,c),await Fje(v,C),y[w]=C})),p.append(...y),f.appendChild(p),f}async function FQ(e,t){if(!e)return;const n=t.elements||Zh(e,{match:()=>!0,recursion:()=>!0,isReverse:!1}),r=Pn(e,n,!1),{ratio:i=2,fillStyle:o="transparent"}=t,{width:s,height:a}=r,l=s*i,c=a*i,u=await $je(e,n,r,t),{canvas:d,ctx:f}=Nje(l,c,o),p=new XMLSerializer().serializeToString(u),y=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(p)}`;try{const v=await Rje(y);return f.drawImage(v,0,0,l,c),d.toDataURL("image/png")}catch(v){console.error("Error converting SVG to image:",v);return}}var gc;(function(e){e.medias="medias",e.elements="elements"})(gc||(gc={}));var _d;(function(e){e.copy="copy",e.cut="cut",e.duplicate="duplicate",e.paste="paste"})(_d||(_d={}));const GE=(e,t)=>`<plait>${HQ(JSON.stringify({type:e,data:t}))}</plait>`,KE=e=>{var n;let t=(n=e==null?void 0:e.match(/<plait[^>]*>(.*)<\/plait>/))==null?void 0:n[1];if(t){t=WQ(t);try{const r=JSON.parse(t);if(r){if(r.type===gc.elements)return{elements:r.data};if(r.type===gc.medias)return{medias:r.data}}}catch(r){return console.error(r),null}}return null},TD=e=>{const t=document.implementation.createHTMLDocument("");return t.documentElement.innerHTML=e.trim(),t.body.textContent||t.body.innerText||""},g3=()=>"clipboard"in navigator&&"write"in navigator.clipboard,$Q=()=>"clipboard"in navigator&&"writeText"in navigator.clipboard,y3=()=>"clipboard"in navigator&&"read"in navigator.clipboard,zQ=(e,t,n)=>({type:e,elements:t,text:n}),UQ=(e,t)=>{const{type:n,elements:r,text:i}=e;return n===t.type?{type:n,elements:r.concat(t.elements),text:i+" "+t.text}:e},fw=(e,t)=>e?UQ(e,t):t,HQ=e=>e.replace(/</g,"<").replace(/>/g,">"),WQ=e=>e.replace(/</g,"<").replace(/>/g,">"),VQ=(e,t,n)=>{e==null||e.setData("text/html",GE(t,n))},GQ=(e,t)=>{e==null||e.setData("text/plain",t)},KQ=e=>{const t=e==null?void 0:e.getData("text/html");if(t){const n=KE(t);if(n)return n}return{}},qQ=e=>{if(!e)return{};const t=e==null?void 0:e.getData("text/plain");if(t){const n=KE(t);if(n)return n}return{text:t}},zje=async(e,t,n="")=>{let r=n;g3()&&await navigator.clipboard.write([new ClipboardItem({"text/html":new Blob([GE(e,t)],{type:"text/html"}),"text/plain":new Blob([r??JSON.stringify(t)],{type:"text/plain"})})])},Uje=async()=>{if(!y3())return{};const e=await navigator.clipboard.read();let t={};if(Array.isArray(e)&&e[0]instanceof ClipboardItem)for(const n of e){if(Hje(n)){const r=n.types.filter(a=>a.match(/^image\//)),o=(await Promise.all(r.map(a=>n.getType(a)))).filter(Boolean).map(a=>URL.createObjectURL(a));return{files:await Promise.all(o.map(async a=>{const l=await(await fetch(a)).blob();return new File([l],"plait-file",{type:l.type})}))}}if(n.types.includes("text/html")){const r=await yz(await n.getType("text/html")),i=KE(r);if(i)return i;r&&r.trim()&&(t={text:TD(r)})}if(n.types.includes("text/plain")){const r=await yz(await n.getType("text/plain"));t={text:TD(r)}}}return t},Hje=e=>e.types.find(t=>t.match(/^image\//)),yz=e=>new Promise((t,n)=>{const r=new FileReader;r.addEventListener("loadend",()=>{const i=r.result;t(i)}),r.addEventListener("error",()=>{n(r.error)}),r.readAsText(e)}),Wje=async e=>{let t={};return e?e.files.length?{files:Array.from(e.files)}:(t=KQ(e),Object.keys(t).length===0&&(t=qQ(e)),t):y3()?await Uje():t},YQ=async(e,t)=>{if(!t)return;const{type:n,elements:r,text:i}=t;if(g3())return await zje(n,r,i);if(e){VQ(e,n,r),GQ(e,i);return}if($Q())return await navigator.clipboard.writeText(GE(n,r))};function Go(e){return!!NE.get(e)}function XQ(e){ne.getBoardContainer(e).classList.add("selection-moving"),NE.set(e,!0),Cc(e,!0)}function ZQ(e){ne.getBoardContainer(e).classList.remove("selection-moving"),NE.delete(e),Cc(e,!1)}function DD(e){const t=fv(e);return e.pointer!==Ir.hand&&!t.isDisabledSelection&&!ne.isReadonly(e)}function MD(e){return!!e.operations.find(t=>j3.isSetSelectionOperation(t))}function JQ(e){const t=ow.get(e);if(t)return t.elements}function QQ(e){return ow.get(e)}function eee(e){ow.delete(e)}function tee(e){const t=Et(e),n=Pn(e,t,!1),r=_o(e,n);if(r.width>0&&r.height>0&&t.length>1){const i=Ua(e,q.inflate(r,ti),{stroke:ns,strokeWidth:ti,fillStyle:"solid"});i.classList.add(ny,jJ);const o=es(t);return o&&ta(i,q.getCenterPoint(r),o),i}return null}function nee(e,t,n){if(!e.selection)return;const r=Et(e);if(!xh.isCollapsed(e.selection)){let i=[...r];t.forEach(o=>{o.groupId?i.push(...YE(e,o)):i.push(o)}),yl(e,jE(i));return}if(xh.isCollapsed(e.selection)){const i=t[0],o=Su(e,i,!0);if(o.length>0){const s=ua(e,o[o.length-1],!0)||[],a=r.some(l=>s.map(c=>c.id).includes(l.id));n?ree(e,t,a,s):iee(e,t,a,o)}}}function ree(e,t,n,r){const i=Et(e);let o=[...i];const s=t[0];let a=[];if(!n)a=r;else{const l=i.some(u=>u.id===s.id),c=r.filter(u=>i.includes(u));l?a=c.filter(u=>u.id!==s.id):a.push(...c,...t)}r.forEach(l=>{o.includes(l)&&o.splice(o.indexOf(l),1)}),a.length&&o.push(...a),yl(e,jE(o))}function iee(e,t,n,r){let i=[...t];const o=v3(e,r);if(o.length>0)if(o.length>1)i=i1(e,o[o.length-2],!0);else{const s=e.getOneHitElement(t);s&&(i=[s])}else{const s=i1(e,r[r.length-1],!0);if(!n)i=s;else{const a=e.getOneHitElement(t);a&&(i=[a])}}yl(e,jE(i))}const fv=e=>e.getPluginOptions(xl.withSelection),WS=(e,t)=>{e.setPluginOptions(xl.withSelection,t)},ua=(e,t,n,r)=>{let i=[];const o=e.children.filter(s=>s.groupId===t.id);return n?o.forEach(s=>{rs.isGroup(s)?(r&&i.push(s),i.push(...ua(e,s,n,r))):i.push(s)}):i=r?o:o.filter(s=>!rs.isGroup(s)),i},i1=(e,t,n,r)=>{const i=ua(e,t,n,r),o=[];return i.forEach(s=>{co(s,a=>{o.push(a)},()=>!0)}),o},qE=(e,t,n)=>{const r=i1(e,t,n);return Pn(e,r,!1)},Su=(e,t,n,r)=>{const i=(r||e.children).find(o=>o.id===(t==null?void 0:t.groupId));if(!i)return[];{const o=[i],s=Su(e,i,n,r);return s.length&&o.push(...s),o}},VS=(e,t)=>{const n=Su(e,t,!0);return n.length?n[n.length-1]:null},YE=(e,t)=>{const n=VS(e,t);return n?i1(e,n,!0):[t]},GS=(e,t,n)=>{const r=n!=null&&n.length?n:Et(e);return rs.isGroup(t)?o1(e,t,n):r.map(i=>i.id).includes(t.id)},o1=(e,t,n)=>{const r=n!=null&&n.length?n:Et(e);return ua(e,t,!0).every(o=>r.map(s=>s.id).includes(o.id))},v3=(e,t,n)=>{const r=[];return t.forEach(i=>{GS(e,i,n)&&r.push(i)}),r},oee=(e,t,n)=>{const r=Cu(e,t,n),i=[];return r.forEach(o=>{i.push(o);const s=ua(e,o,!0,!0);i.push(...s.filter(a=>rs.isGroup(a)))}),i},w3=(e,t,n,r)=>{const i=Su(e,t,!0,r),o=v3(e,i,n);return o.length?o[o.length-1]:null},Cu=(e,t,n)=>{let r=[];return(t!=null&&t.length?t:Et(e)).forEach(o=>{if(o.groupId){const s=w3(e,o,t,n);s&&!r.includes(s)&&r.push(s)}}),r},XE=(e,t)=>{let n=[];return(t!=null&&t.length?t:Et(e)).filter(i=>!rs.isGroup(i)).forEach(i=>{i.groupId&&w3(e,i,t)||n.push(i)}),n},ZE=(e,t)=>XE(e,t).filter(r=>e.canAddToGroup(r)),see=(e,t)=>[...Cu(e,t),...XE(e,t)],aee=(e,t)=>{const n=Et(e).map(o=>o.id);let r=null;const i=Go(e);return t.forEach(o=>{const s=!n.includes(o.id)&&!i||i;if(o.groupId&&s){r||(r=Tn());const a=YE(e,o),l=Pn(e,a,!1),c=Ua(e,l,{stroke:ns,strokeWidth:ti,strokeLineDash:[5]}),u=es(a);u&&ta(c,q.getCenterPoint(l),u),r.append(c)}}),r},lee=e=>({id:fr(),type:"group"}),cee=e=>e.every(t=>!t.groupId),b3=e=>e.every(t=>t.groupId&&t.groupId===e[0].groupId),uee=(e,t)=>{const r=see(e,t).filter(i=>e.canAddToGroup(i));return r.length>1?cee(r)||b3(r):!1},dee=(e,t,n)=>{const r=Cu(e,t,n);return Et(e).length>0&&r.length>0},x3=(e,t)=>{const n=Su(e,t,!0);let r=null;if(n!=null&&n.length){for(let i=0;i<(n==null?void 0:n.length);i++)if(!o1(e,n[i])){r=n[i];break}}return r},fee=(e,t,n)=>{const r=[...t];cw(e,r),r.pop(),oy(e,r.map(i=>({element:i,newPath:n})))},hee=e=>{const t=e.getDeletedFragment([]);e.deleteFragment(t)},Vje=(e,t,n)=>{const r=Et(e),i=Pn(e,r,!1),o=e.buildFragment(null,i,t);o&&YQ(n,o)},S3=(e,t,n)=>{const r=t!=null&&t.length?t:Et(e),i=Pn(e,r,!1),o=e.buildFragment(null,i,_d.duplicate,r),s=o&&JSON.stringify(o),a=s&&JSON.parse(s);a&&e.insertFragment({...a,text:void 0},n||[i.x+i.width/2,i.y+i.height/2],_d.duplicate)},ac=2,Gje=24;function C3(e,t){return Zh(e,{match:r=>e.isAlign(r)&&!t.some(i=>i.id===r.id),recursion:()=>!0,isReverse:!1}).map(r=>{const i=e.getRectangle(r);return ly(i,r.angle||0)})}function pee(e,t){return t?[[e[0],e[1]-4],[e[0],e[1]+4]]:[[e[0]-4,e[1]],[e[0]+4,e[1]]]}function Wm(e,t,n){let r=ac;return e.forEach(i=>{const o=mee(t,i,n);Math.abs(o)<Math.abs(r)&&(r=o)}),r}const mee=(e,t,n)=>{const i=Id(t,n).map(a=>a-e),o=i.map(a=>Math.abs(a)),s=o.indexOf(Math.min(...o));return i[s]},Id=(e,t)=>{const n=t?"x":"y",r=t?"width":"height";return[e[n],e[n]+e[r]/2,e[n]+e[r]]};function If(e,t){let n=1/0,r=e[0];return e.forEach(i=>{const o=Math.sqrt(Math.pow(t.x-i.x,2)+Math.pow(t.y-i.y,2));o<n&&(n=o,r=i)}),r}const Af=(e,t,n)=>Id(t,n).includes(e);function E3(e,t,n,r=!0,i=!0,o=!1){let s=[];const a=Id(t,!0),l=Id(t,!1),c=[{axis:a[0],isHorizontal:!0,pointRectangles:[]},{axis:a[1],isHorizontal:!0,pointRectangles:[]},{axis:a[2],isHorizontal:!0,pointRectangles:[]},{axis:l[0],isHorizontal:!1,pointRectangles:[]},{axis:l[1],isHorizontal:!1,pointRectangles:[]},{axis:l[2],isHorizontal:!1,pointRectangles:[]}];for(let d=0;d<n.length;d++){const f=n[d];Af(c[0].axis,f,c[0].isHorizontal)&&c[0].pointRectangles.push(f),Af(c[1].axis,f,c[1].isHorizontal)&&c[1].pointRectangles.push(f),Af(c[2].axis,f,c[2].isHorizontal)&&c[2].pointRectangles.push(f),Af(c[3].axis,f,c[3].isHorizontal)&&c[3].pointRectangles.push(f),Af(c[4].axis,f,c[4].isHorizontal)&&c[4].pointRectangles.push(f),Af(c[5].axis,f,c[5].isHorizontal)&&c[5].pointRectangles.push(f)}const u=(d,f,p)=>{const y=q.inflate(q.getBoundingRectangle([t,f]),Gje);if(p){const v=[d,y.y],w=[d,y.y+y.height];s.push([v,w])}else{const v=[y.x,d],w=[y.x+y.width,d];s.push([v,w])}};if(r&&c[0].pointRectangles.length){const d=c[0].pointRectangles.length===1?c[0].pointRectangles[0]:If(c[0].pointRectangles,t);u(c[0].axis,d,c[0].isHorizontal)}if(r&&o&&c[1].pointRectangles.length){const d=c[1].pointRectangles.length===1?c[1].pointRectangles[0]:If(c[1].pointRectangles,t);u(c[1].axis,d,c[1].isHorizontal)}if(r&&c[2].pointRectangles.length){const d=c[2].pointRectangles.length===1?c[2].pointRectangles[0]:If(c[2].pointRectangles,t);u(c[2].axis,d,c[2].isHorizontal)}if(i&&c[3].pointRectangles.length){const d=c[3].pointRectangles.length===1?c[3].pointRectangles[0]:If(c[3].pointRectangles,t);u(c[3].axis,d,c[3].isHorizontal)}if(i&&o&&c[4].pointRectangles.length){const d=c[4].pointRectangles.length===1?c[4].pointRectangles[0]:If(c[4].pointRectangles,t);u(c[4].axis,d,c[4].isHorizontal)}if(i&&c[5].pointRectangles.length){const d=c[5].pointRectangles.length===1?c[5].pointRectangles[0]:If(c[5].pointRectangles,t);u(c[5].axis,d,c[5].isHorizontal)}return gee(e,s)}function gee(e,t){const n=Tn();return t.forEach(r=>{if(!r.length)return;const i=ne.getRoughSVG(e).line(r[0][0],r[0][1],r[1][0],r[1][1],{stroke:ns,strokeWidth:1,strokeLineDash:[4,4]});n.appendChild(i)}),n}function _3(e,t){const n=Tn();return t.forEach(r=>{if(!r.length)return;let i=r[0][1]===r[1][1];const o=ne.getRoughSVG(e).line(r[0][0],r[0][1],r[1][0],r[1][1],{stroke:ns,strokeWidth:1});n.appendChild(o),r.forEach(s=>{const a=pee(s,i),l=ne.getRoughSVG(e).line(a[0][0],a[0][1],a[1][0],a[1][1],{stroke:ns,strokeWidth:1});n.appendChild(l)})}),n}const I3=(e,t)=>{const n=dw(e,Et(e));let r=yee(e,n);t==="up"&&(r=r.reverse());let i=[];return r.forEach((o,s)=>{const a=o[0],l=o[o.length-1],c=t==="down"?a:l,u=Kje(e,c,t);u===-1||c===u||(t==="down"&&(o=o.reverse()),i.push(...o.map(d=>({element:e.children[d],newPath:[u]}))))}),i},A3=(e,t)=>{const n=dw(e,Et(e));let r=yee(e,n),i=[];return t==="down"&&(r=r.reverse()),r.forEach(o=>{const s=o[0],a=o[o.length-1],l=t==="down"?s:a,c=e.children[l],u=x3(e,c);let d=t==="down"?0:e.children.length-1;if(u){const f=cw(e,ua(e,u,!0,!0));d=t==="down"?e.children.indexOf(f[0]):e.children.indexOf(f[f.length-1])}t==="down"&&(o=o.reverse()),i.push(...o.map(f=>({element:e.children[f],newPath:[d]})))}),i},yee=(e,t)=>{let n=0;return t.reduce((r,i,o)=>{if(o>0){const s=e.children[i],a=e.children[t[o-1]],l=i-1===t[o-1]?!0:e.children.every((u,d)=>d>t[o-1]&&d<=i-1?rs.isGroup(u):!0);let c=!1;if(a!=null&&a.groupId||s!=null&&s.groupId&&(a==null?void 0:a.groupId)!==(s==null?void 0:s.groupId)){let u=!1,d=!1;if(a.groupId){const f=VS(e,a);u=!o1(e,f)}if(s.groupId){const f=VS(e,s);d=!o1(e,f)}c=u||d}(!l||c)&&(n=++n)}return(r[n]||(r[n]=[])).push(i),r},[])},Kje=(e,t,n)=>{if(t===0&&n==="down"||t===e.children.length-1&&n==="up")return-1;const r=d=>!(d.isDeleted||rs.isGroup(d)),i=n==="down"?QJ(e.children,d=>r(d),Math.max(0,t-1)):eQ(e.children,d=>r(d),t+1),o=e.children[i];if(!o)return-1;const s=[...e.children],a=s[t],l=x3(e,a),c=Su(e,o,!0)||[];if(l&&(a==null?void 0:a.groupId)!==(o==null?void 0:o.groupId)&&!c.find(d=>d.id===l.id))return-1;if(!o.groupId)return i;let u;if(l?u=c[c.indexOf(l)-1]:u=c[c.length-1],u){let d=ua(e,u,!0,!1);if(d.length)return d.sort((f,p)=>{const y=e.children.findIndex(w=>w.id===f.id),v=e.children.findIndex(w=>w.id===p.id);return y-v}),n==="down"?s.indexOf(d[0]):s.indexOf(d[d.length-1])}return i},P3=e=>vee(e)||wee(e),vee=e=>e.pointerType==="pen",wee=e=>e.pointerType==="touch",qje=(e,t)=>{const n=Cu(e,t),r=ZE(e),i=[...n,...r],o=lee();if(uee(e)){i.forEach(u=>{const d=ne.findPath(e,u);ih.setNode(e,{groupId:o.id},d)});const s=Et(e),a=jQ(e,s),l=dw(e,i);if(tQ(l)||fee(e,s,[a-1]),b3(i)){const u=r[0].groupId;ih.insertNode(e,{...o,groupId:u},[e.children.length])}else ih.insertNode(e,o,[e.children.length])}},Yje=(e,t)=>{const n=Cu(e,t);dee(e)&&(n.forEach(r=>{Zh(e,{match:o=>o.groupId===r.id,recursion:()=>!1}).forEach(o=>{const s=ne.findPath(e,o);ih.setNode(e,{groupId:r.groupId||void 0},s)})}),n.map(r=>{const i=ne.findPath(e,r),o=e.pathRef(i);return()=>{o.current&&ih.removeNode(e,o.current),o.unref()}}).forEach(r=>{r()}))},Xje={addGroup:qje,removeGroup:Yje};function bee(e,t){const n={type:"set_selection",properties:e.selection,newProperties:t};e.apply(n)}const Zje={setSelection:bee,addSelectionWithTemporaryElements:xee};function xee(e,t){const n=setTimeout(()=>{bee(e,{anchor:[0,0],focus:[0,0]})},0);let r=QQ(e);if(r){clearTimeout(r.timeoutId);const i=r.elements;r.elements.push(...t.filter(o=>!i.includes(o))),r.timeoutId=n}else ow.set(e,{timeoutId:n,elements:t})}const Jje=e=>{const t=A3(e,"up");oy(e,t)},Qje=e=>{const t=A3(e,"down");oy(e,t)},eLe=e=>{const t=I3(e,"up");oy(e,t)},tLe=e=>{const t=I3(e,"down");oy(e,t)},nLe={moveUp:eLe,moveDown:tLe,moveToTop:Jje,moveToBottom:Qje},rLe=(e,t)=>{t.map(n=>{const r=ne.findPath(e,n),i=e.pathRef(r);return()=>{i.current&&RQ(e,i.current),i.unref(),uw(e,n,!0)}}).forEach(n=>{n()})},ay={removeElements:rLe},Qe={...oje,...yje,...Zje,...ih,...Xje,...nLe},Di=(e,t,n)=>(n||(n=0),Array.isArray(e)&&typeof e[0]=="number"?bh(e[0],e[1],t[0],t[1],n):e.map(r=>bh(r[0],r[1],t[0],t[1],n||0))),es=e=>{var n;let t=((n=e[0])==null?void 0:n.angle)||0;return e.forEach(r=>{r.angle!==t&&!$S((r.angle||0)%(Math.PI/2)-t%(Math.PI/2),0)&&(t=0)}),t},See=e=>{if(!e.length)return!1;const t=e[0].angle;return t===void 0?!1:!e.some(n=>n.angle!==t)},Cee=(e,t)=>{let n=[];for(let a=0;a<e.length;a++){const l=e[a],c=Di(l,[0,0],-t);n.push(q.getRectangleByPoints(c))}const r=q.getBoundingRectangle(n),i=q.getCornerPoints(r),o=Di(i,[0,0],t),s=q.getCenterPoint(q.getRectangleByPoints(o));return q.getRectangleByPoints(Di(o,s,-t))},Eee=(e,t,n)=>{const r=q.getCenterPoint(e),[i]=Di([r],t,n),o=i[0]-r[0],s=i[1]-r[1];return{offsetX:o,offsetY:s}},KS=(e,t,n)=>{const{offsetX:r,offsetY:i}=Eee(q.getRectangleByPoints(e),t,n);return e.map(o=>[o[0]+r,o[1]+i])},Al=e=>k3(e.angle),k3=e=>e&&e!==0,Pl=(e,t)=>{if(Al(t)){let n=q.getRectangleByPoints(t.points);const r=q.getCenterPoint(n);return Di(e,r,t.angle)}else return null},_ee=(e,t)=>{if(k3(t)){let n=q.getRectangleByPoints(e);const r=q.getCenterPoint(n);return Di(e,r,t)}else return null},yc=(e,t,n,r=!1)=>{if(Al(n)){let i=q.getRectangleByPoints(n.points);const o=r?_o(e,i):i,s=q.getCenterPoint(o);return Di(t,s,n.angle?-n.angle:0)}else return null},ly=(e,t)=>{if(t){const n=q.getCornerPoints(e),r=q.getCenterPoint(e);return q.getRectangleByPoints(Di(n,r,t))}return e},Iee=e=>{const t=Math.abs(e)%Math.PI;return t>=1/4*Math.PI&&t<=3/4*Math.PI};function qS(e){return e/180*Math.PI}function Aee(e,t,n){const r=Pn(e,t,!1),i=q.getCenterPoint(r);t.forEach(o=>{const s=o.angle,a=KS(o.points,i,Pg(n)),l=ne.findPath(e,o);Qe.setNode(e,{points:a,angle:Pg((s||0)+n)},l)})}const Pg=e=>e<0?e+2*Math.PI:e>=2*Math.PI?e-2*Math.PI:e,Pee=(e,t,n)=>{const r=5*Math.PI/2+Math.atan2(e[1]-n[1],e[0]-n[0]),i=5*Math.PI/2+Math.atan2(t[1]-n[1],t[0]-n[0]);return Pg(i-r)},kee=e=>e==null?void 0:e.angle,ta=(e,t,n)=>{if(n===0){e.removeAttribute("transform");return}var r=t[0],i=t[1];let o=Math.cos(n),s=Math.sin(n),l="matrix("+[o,s,-s,o,r*(1-o)+i*s,i*(1-o)-r*s].join(",")+")";e.setAttribute("transform",`${l}`)};function Pn(e,t,n){const r=[],i=o=>{const s=e.getRectangle(o);if(s){const a=q.getCornerPoints(s),l=Pl(a,o)||a;r.push(l)}else console.error("can not get rectangle of element:",o)};if(t.forEach(o=>{n?co(o,s=>i(s),s=>e.isRecursion(s)):i(o)}),r.length>0)if(See(t)){const o=es(t);return Cee(r,o)}else{const o=r.reduce((s,a)=>s.concat(a),[]);return q.getRectangleByPoints(o)}else return{x:0,y:0,width:0,height:0}}function Zs(e,t,n){const r=!n&&hv(e).get(t);return r||(n||(n=Zh(e,{match:o=>!0,recursion:o=>!0})),n.find(o=>o.id===t))}function hv(e){const t=HJ.get(e);if(!t)throw new Error("can not resolve element map");return t}function Zh(e,t){let n=[];const r=t.isReverse??!0;return co(e,i=>{!ne.isBoard(i)&&t.match(i)&&n.push(i)},i=>ne.isBoard(i)?!0:zd(e)(i)&&t.recursion(i),r),n}var Rr;(function(e){e.default="default",e.colorful="colorful",e.soft="soft",e.retro="retro",e.dark="dark",e.starry="starry"})(Rr||(Rr={}));const uo="#333333",T3={mode:Rr.default,boardBackground:"#ffffff",textColor:uo},D3={mode:Rr.colorful,boardBackground:"#ffffff",textColor:uo},M3={mode:Rr.soft,boardBackground:"#f5f5f5",textColor:uo},O3={mode:Rr.retro,boardBackground:"#f9f8ed",textColor:uo},R3={mode:Rr.dark,boardBackground:"#141414",textColor:"#FFFFFF"},N3={mode:Rr.starry,boardBackground:"#0d2537",textColor:"#FFFFFF"},Tee=[T3,D3,M3,O3,R3,N3],ne={isBoard(e){const t=ED.get(e);if(t!==void 0)return t;const n=typeof e.onChange=="function"&&typeof e.apply=="function";return ED.set(e,n),n},isAlive(e){return!!YJ.get(e)},findPath(e,t){const n=[];let r=t;for(;;){const i=gd.get(r);if(i==null){if(ne.isBoard(r))return n;break}const o=rh.get(r);if(o==null)break;n.unshift(o),r=i}throw new Error(`Unable to find the path for Plait node: ${JSON.stringify(t)}`)},getHost(e){return KJ.get(e)},getElementLowerHost(e){var t;return(t=Yu.get(e))==null?void 0:t.lowerHost},getElementHost(e){var t;return(t=Yu.get(e))==null?void 0:t.host},getElementUpperHost(e){var t;return(t=Yu.get(e))==null?void 0:t.upperHost},getElementTopHost(e){var t;return(t=Yu.get(e))==null?void 0:t.topHost},getActiveHost(e){var t;return(t=Yu.get(e))==null?void 0:t.activeHost},getRoughSVG(e){return GJ.get(e)},getBoardContainer(e){var t;return(t=Yu.get(e))==null?void 0:t.container},getBoardContext(e){return qJ.get(e)},getRectangle(e){return Pn(e,e.children,!0)},getViewportContainer(e){var t;return(t=Yu.get(e))==null?void 0:t.viewportContainer},isFocus(e){return!!e.selection},isReadonly(e){return e.options.readonly},hasBeenTextEditing(e){return!!FS.get(e)},getPointer(e){return e.pointer},isPointer(e,t){return e.pointer===t},isInPointer(e,t){const n=e.pointer;return t.includes(n)},getMovingPointInBoard(e){return XJ.get(e)},isMovingPointInBoard(e){const t=ZJ.get(e),n=ne.getBoardContainer(e).getBoundingClientRect();return!!(t&&ry(t[0],t[1],n)===0)},getThemeColors(e){return e.options.themeColors||Tee}};var Ir;(function(e){e.hand="hand",e.selection="selection"})(Ir||(Ir={}));const Dee=e=>e.type==="set_viewport",Mee=e=>e.type==="set_selection",Oee=e=>e.type==="set_theme",Ree=e=>{switch(e.type){case"insert_node":return{...e,type:"remove_node"};case"remove_node":return{...e,type:"insert_node"};case"move_node":{const{newPath:t,path:n}=e;if(pn.equals(t,n))return e;const r=pn.transform(n,e),i=pn.transform(pn.next(n),e);return{...e,path:r,newPath:i}}case"set_node":{const{properties:t,newProperties:n}=e;return{...e,properties:n,newProperties:t}}case"set_selection":{const{properties:t,newProperties:n}=e;return t==null?{...e,properties:n,newProperties:null}:n==null?{...e,properties:null,newProperties:t}:{...e,properties:n,newProperties:t}}case"set_viewport":{const{properties:t,newProperties:n}=e;return t==null?{...e,properties:n,newProperties:n}:n==null?{...e,properties:t,newProperties:t}:{...e,properties:n,newProperties:t}}case"set_theme":{const{properties:t,newProperties:n}=e;return{...e,properties:n,newProperties:t}}}},j3={isSetViewportOperation:Dee,isSetSelectionOperation:Mee,isSetThemeOperation:Oee,inverse:Ree},on={isEquals(e,t){return e&&t&&e[0]===t[0]&&e[1]===t[1]},isHorizontal(e,t,n=0){return e&&t&&on.isOverHorizontal([e,t],n)},isOverHorizontal(e,t=0){return e.every(n=>Math.abs(n[1]-e[0][1])<=t)},isVertical(e,t,n=0){return e&&t&&on.isOverVertical([e,t],n)},isOverVertical(e,t=0){return e.every(n=>Math.abs(n[0]-e[0][0])<=t)},isAlign(e,t=0){return on.isOverHorizontal(e,t)||on.isOverVertical(e,t)},getOffsetX(e,t){return t[0]-e[0]},getOffsetY(e,t){return t[1]-e[1]}},R2=new WeakMap,Qi=new WeakMap,K0=new WeakMap;var In;(function(e){e.left="left",e.top="top",e.right="right",e.bottom="bottom"})(In||(In={}));const Nee=e=>e===In.left||e===In.right,rs={isGroup:e=>e.type==="group"};/**
|
|
1732
|
+
*/var $6e=KR;let YP=null;function gD(){return YP||(YP=xn(()=>import("./index-DRGxmFyd.js"),[],import.meta.url).then(e=>e.MessagePlugin)),YP}function z6e(e){return typeof e=="object"&&e!==null&&e.__aituLazyMessageInstance===!0}function U6e(e){return typeof e=="object"&&e!==null&&typeof e.then=="function"}function H6e(e){return typeof e=="object"&&e!==null&&typeof e.close=="function"}function _x(e,t){gD().then(n=>{const r=n[e];r(...t)}).catch(n=>{console.warn("[MessagePlugin] failed to load tdesign-react:",n)})}const tn={success(...e){_x("success",e)},error(...e){_x("error",e)},warning(...e){_x("warning",e)},info(...e){_x("info",e)},loading(...e){const t=gD().then(n=>{const r=n.loading;return r(...e)});return Object.assign(t,{__aituLazyMessageInstance:!0,instancePromise:t})},close(e){var t;if(z6e(e)){e.instancePromise.then(n=>{var r;(r=n==null?void 0:n.close)==null||r.call(n)}).catch(n=>{console.warn("[MessagePlugin] failed to close lazy message:",n)});return}if(H6e(e)){(t=e.close)==null||t.call(e);return}U6e(e)&&gD().then(n=>{n.close(e)}).catch(n=>{console.warn("[MessagePlugin] failed to load tdesign-react:",n)})}},kJ=({tabs:e,activeTab:t,onTabChange:n,middleTabs:r,activeMiddleTab:i,onMiddleTabChange:o,searchQuery:s,children:a,compact:l=!1,tabsFooter:c})=>{const u=!!(s!=null&&s.trim()),d=r&&r.length>0&&!u,f=b.useCallback(y=>{n(y)},[n]),p=b.useCallback(y=>{o==null||o(y)},[o]);return g.jsxs("div",{className:`vendor-tab-panel ${l?"vendor-tab-panel--compact":""} ${d?"vendor-tab-panel--three-col":""}`,children:[!u&&g.jsxs("div",{className:"vendor-tab-panel__tabs",children:[g.jsx("div",{className:"vendor-tab-panel__tabs-list",children:e.map(({id:y,label:v,count:w,icon:C})=>{const x=t===y;return g.jsxs("button",{className:`vendor-tab-panel__tab ${x?"vendor-tab-panel__tab--active":""}`,onClick:()=>f(y),type:"button",children:[C?g.jsx("span",{className:"vendor-tab-panel__tab-icon",children:C}):null,g.jsx("span",{className:"vendor-tab-panel__tab-label",children:v}),g.jsx("span",{className:"vendor-tab-panel__tab-count",children:w})]},y)})}),c?g.jsx("div",{className:"vendor-tab-panel__tabs-footer",children:c}):null]}),d&&g.jsx("div",{className:"vendor-tab-panel__middle-tabs",children:r.map(({id:y,label:v,count:w,icon:C})=>{const x=i===y;return g.jsxs("button",{className:`vendor-tab-panel__tab ${x?"vendor-tab-panel__tab--active":""}`,onClick:()=>p(y),type:"button",children:[C?g.jsx("span",{className:"vendor-tab-panel__tab-icon",children:C}):null,g.jsx("span",{className:"vendor-tab-panel__tab-label",children:v}),g.jsx("span",{className:"vendor-tab-panel__tab-count",children:w})]},y)})}),g.jsx("div",{className:"vendor-tab-panel__content",children:a})]})};var TJ=Symbol.for("immer-nothing"),cz=Symbol.for("immer-draftable"),sa=Symbol.for("immer-state");function ml(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Qv=Object.getPrototypeOf;function ou(e){return!!e&&!!e[sa]}function vh(e){var t;return e?DJ(e)||Array.isArray(e)||!!e[cz]||!!((t=e.constructor)!=null&&t[cz])||iw(e)||TE(e):!1}var W6e=Object.prototype.constructor.toString(),uz=new WeakMap;function DJ(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return!0;const n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;if(n===Object)return!0;if(typeof n!="function")return!1;let r=uz.get(n);return r===void 0&&(r=Function.toString.call(n),uz.set(n,r)),r===W6e}function NS(e,t,n=!0){kE(e)===0?(n?Reflect.ownKeys(e):Object.keys(e)).forEach(i=>{t(i,e[i],e)}):e.forEach((r,i)=>t(i,r,e))}function kE(e){const t=e[sa];return t?t.type_:Array.isArray(e)?1:iw(e)?2:TE(e)?3:0}function yD(e,t){return kE(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function MJ(e,t,n){const r=kE(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function V6e(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function iw(e){return e instanceof Map}function TE(e){return e instanceof Set}function _f(e){return e.copy_||e.base_}function vD(e,t){if(iw(e))return new Map(e);if(TE(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const n=DJ(e);if(t===!0||t==="class_only"&&!n){const r=Object.getOwnPropertyDescriptors(e);delete r[sa];let i=Reflect.ownKeys(r);for(let o=0;o<i.length;o++){const s=i[o],a=r[s];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[s]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[s]})}return Object.create(Qv(e),r)}else{const r=Qv(e);if(r!==null&&n)return{...e};const i=Object.create(r);return Object.assign(i,e)}}function qR(e,t=!1){return DE(e)||ou(e)||!vh(e)||(kE(e)>1&&Object.defineProperties(e,{set:Ix,add:Ix,clear:Ix,delete:Ix}),Object.freeze(e),t&&Object.values(e).forEach(n=>qR(n,!0))),e}function G6e(){ml(2)}var Ix={value:G6e};function DE(e){return e===null||typeof e!="object"?!0:Object.isFrozen(e)}var K6e={};function wh(e){const t=K6e[e];return t||ml(0,e),t}var e1;function OJ(){return e1}function q6e(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function dz(e,t){t&&(wh("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function wD(e){bD(e),e.drafts_.forEach(Y6e),e.drafts_=null}function bD(e){e===e1&&(e1=e.parent_)}function fz(e){return e1=q6e(e1,e)}function Y6e(e){const t=e[sa];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function hz(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[sa].modified_&&(wD(t),ml(4)),vh(e)&&(e=jS(t,e),t.parent_||LS(t,e)),t.patches_&&wh("Patches").generateReplacementPatches_(n[sa].base_,e,t.patches_,t.inversePatches_)):e=jS(t,n,[]),wD(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==TJ?e:void 0}function jS(e,t,n){if(DE(t))return t;const r=e.immer_.shouldUseStrictIteration(),i=t[sa];if(!i)return NS(t,(o,s)=>pz(e,i,t,o,s,n),r),t;if(i.scope_!==e)return t;if(!i.modified_)return LS(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;const o=i.copy_;let s=o,a=!1;i.type_===3&&(s=new Set(o),o.clear(),a=!0),NS(s,(l,c)=>pz(e,i,o,l,c,n,a),r),LS(e,o,!1),n&&e.patches_&&wh("Patches").generatePatches_(i,n,e.patches_,e.inversePatches_)}return i.copy_}function pz(e,t,n,r,i,o,s){if(i==null||typeof i!="object"&&!s)return;const a=DE(i);if(!(a&&!s)){if(ou(i)){const l=o&&t&&t.type_!==3&&!yD(t.assigned_,r)?o.concat(r):void 0,c=jS(e,i,l);if(MJ(n,r,c),ou(c))e.canAutoFreeze_=!1;else return}else s&&n.add(i);if(vh(i)&&!a){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||t&&t.base_&&t.base_[r]===i&&a)return;jS(e,i),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&(iw(n)?n.has(r):Object.prototype.propertyIsEnumerable.call(n,r))&&LS(e,i)}}}function LS(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&qR(t,n)}function X6e(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:OJ(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let i=r,o=YR;n&&(i=[r],o=t1);const{revoke:s,proxy:a}=Proxy.revocable(i,o);return r.draft_=a,r.revoke_=s,a}var YR={get(e,t){if(t===sa)return e;const n=_f(e);if(!yD(n,t))return Z6e(e,n,t);const r=n[t];return e.finalized_||!vh(r)?r:r===XP(e.base_,t)?(ZP(e),e.copy_[t]=SD(r,e)):r},has(e,t){return t in _f(e)},ownKeys(e){return Reflect.ownKeys(_f(e))},set(e,t,n){const r=RJ(_f(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const i=XP(_f(e),t),o=i==null?void 0:i[sa];if(o&&o.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(V6e(n,i)&&(n!==void 0||yD(e.base_,t)))return!0;ZP(e),xD(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return XP(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,ZP(e),xD(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=_f(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ml(11)},getPrototypeOf(e){return Qv(e.base_)},setPrototypeOf(){ml(12)}},t1={};NS(YR,(e,t)=>{t1[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});t1.deleteProperty=function(e,t){return t1.set.call(this,e,t,void 0)};t1.set=function(e,t,n){return YR.set.call(this,e[0],t,n,e[0])};function XP(e,t){const n=e[sa];return(n?_f(n):e)[t]}function Z6e(e,t,n){var i;const r=RJ(t,n);return r?"value"in r?r.value:(i=r.get)==null?void 0:i.call(e.draft_):void 0}function RJ(e,t){if(!(t in e))return;let n=Qv(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=Qv(n)}}function xD(e){e.modified_||(e.modified_=!0,e.parent_&&xD(e.parent_))}function ZP(e){e.copy_||(e.copy_=vD(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var J6e=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const o=n;n=t;const s=this;return function(l=o,...c){return s.produce(l,u=>n.call(this,u,...c))}}typeof n!="function"&&ml(6),r!==void 0&&typeof r!="function"&&ml(7);let i;if(vh(t)){const o=fz(this),s=SD(t,void 0);let a=!0;try{i=n(s),a=!1}finally{a?wD(o):bD(o)}return dz(o,r),hz(i,o)}else if(!t||typeof t!="object"){if(i=n(t),i===void 0&&(i=t),i===TJ&&(i=void 0),this.autoFreeze_&&qR(i,!0),r){const o=[],s=[];wh("Patches").generateReplacementPatches_(t,i,o,s),r(o,s)}return i}else ml(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...a)=>this.produceWithPatches(s,l=>t(l,...a));let r,i;return[this.produce(t,n,(s,a)=>{r=s,i=a}),r,i]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),typeof(e==null?void 0:e.useStrictIteration)=="boolean"&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){vh(e)||ml(8),ou(e)&&(e=Q6e(e));const t=fz(this),n=SD(e,void 0);return n[sa].isManual_=!0,bD(t),n}finishDraft(e,t){const n=e&&e[sa];(!n||!n.isManual_)&&ml(9);const{scope_:r}=n;return dz(r,t),hz(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const i=t[n];if(i.path.length===0&&i.op==="replace"){e=i.value;break}}n>-1&&(t=t.slice(n+1));const r=wh("Patches").applyPatches_;return ou(e)?r(e,t):this.produce(e,i=>r(i,t))}};function SD(e,t){const n=iw(e)?wh("MapSet").proxyMap_(e,t):TE(e)?wh("MapSet").proxySet_(e,t):X6e(e,t);return(t?t.scope_:OJ()).drafts_.push(n),n}function Q6e(e){return ou(e)||ml(10,e),NJ(e)}function NJ(e){if(!vh(e)||DE(e))return e;const t=e[sa];let n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=vD(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=vD(e,!0);return NS(n,(i,o)=>{MJ(n,i,NJ(o))},r),t&&(t.finalized_=!1),n}var n1=new J6e,eje=n1.produce,Ax=n1.createDraft.bind(n1),Px=n1.finishDraft.bind(n1),ol={},mz;function tje(){if(mz)return ol;mz=1,Object.defineProperty(ol,"__esModule",{value:!0});for(var e=typeof window<"u"&&/Mac|iPod|iPhone|iPad/.test(window.navigator.platform),t={alt:"altKey",control:"ctrlKey",meta:"metaKey",shift:"shiftKey"},n={add:"+",break:"pause",cmd:"meta",command:"meta",ctl:"control",ctrl:"control",del:"delete",down:"arrowdown",esc:"escape",ins:"insert",left:"arrowleft",mod:e?"meta":"control",opt:"alt",option:"alt",return:"enter",right:"arrowright",space:" ",spacebar:" ",up:"arrowup",win:"meta",windows:"meta"},r={backspace:8,tab:9,enter:13,shift:16,control:17,alt:18,pause:19,capslock:20,escape:27," ":32,pageup:33,pagedown:34,end:35,home:36,arrowleft:37,arrowup:38,arrowright:39,arrowdown:40,insert:45,delete:46,meta:91,numlock:144,scrolllock:145,";":186,"=":187,",":188,"-":189,".":190,"/":191,"`":192,"[":219,"\\":220,"]":221,"'":222},i=1;i<20;i++)r["f"+i]=111+i;function o(f,p,y){p&&!("byKey"in p)&&(y=p,p=null),Array.isArray(f)||(f=[f]);var v=f.map(function(x){return l(x,p)}),w=function(E){return v.some(function(_){return c(_,E)})},C=y==null?w:w(y);return C}function s(f,p){return o(f,p)}function a(f,p){return o(f,{byKey:!0},p)}function l(f,p){var y=p&&p.byKey,v={};f=f.replace("++","+add");var w=f.split("+"),C=w.length;for(var x in t)v[t[x]]=!1;var E=!0,_=!1,I=void 0;try{for(var D=w[Symbol.iterator](),P;!(E=(P=D.next()).done);E=!0){var k=P.value,R=k.endsWith("?")&&k.length>1;R&&(k=k.slice(0,-1));var T=d(k),M=t[T];if(k.length>1&&!M&&!n[k]&&!r[T])throw new TypeError('Unknown modifier: "'+k+'"');(C===1||!M)&&(y?v.key=T:v.which=u(k)),M&&(v[M]=R?null:!0)}}catch(F){_=!0,I=F}finally{try{!E&&D.return&&D.return()}finally{if(_)throw I}}return v}function c(f,p){for(var y in f){var v=f[y],w=void 0;if(v!=null&&(y==="key"&&p.key!=null?w=p.key.toLowerCase():y==="which"?w=v===91&&p.which===93?91:p.which:w=p[y],!(w==null&&v===!1)&&w!==v))return!1}return!0}function u(f){f=d(f);var p=r[f]||f.toUpperCase().charCodeAt(0);return p}function d(f){return f=f.toLowerCase(),f=n[f]||f,f}return ol.default=o,ol.isHotkey=o,ol.isCodeHotkey=s,ol.isKeyHotkey=a,ol.parseHotkey=l,ol.compareHotkey=c,ol.toKeyCode=u,ol.toKeyName=d,ol}var $r=tje(),Ia;(function(e){e.ew="ew-resize",e.ns="ns-resize",e.nesw="nesw-resize",e.nwse="nwse-resize"})(Ia||(Ia={}));var Um;(function(e){e.crosshair="crosshair"})(Um||(Um={}));const T2=[Ia.ns,Ia.nesw,Ia.ew,Ia.nwse],Vh="plait-board-attached",ti=1,BS=2,ny="selection-rectangle",jJ="selection-rectangle-bounding",nje=.1,LJ=.1,BJ=4,rje="plait-board-container",XR="active-with-moving",CD="rotate-handle",FJ="resize-handle",$J=20,ZR={MAIN:0,WHEEL:1},ME=3,JR=10,OE=5;function zJ(e){return!!e.beforeContextChange}function UJ(e){return!!e.onContextChanged}const ED=new WeakMap,D2=new WeakMap,rh=new WeakMap,gd=new WeakMap,HJ=new WeakMap,ym=new WeakMap,vm=new WeakMap,FS=new WeakMap,WJ=new WeakMap,VJ=new WeakMap,GJ=new WeakMap,KJ=new WeakMap,qJ=new WeakMap,YJ=new WeakMap,Yu=new WeakMap,QR=new WeakMap,XJ=new WeakMap,ZJ=new WeakMap,RE=new WeakMap,NE=new WeakMap,ow=new WeakMap,sw=new WeakMap,_D=new WeakMap,wm=new WeakMap;function _l(e){return e==null}const _g=(e,t)=>e+Math.floor(t*255).toString(16);function JJ(e){return e.button===2}function jE(e){const t=new Map;return e.forEach(n=>{t.has(n.id)||t.set(n.id,n)}),Array.from(t.values())}const QJ=(e,t,n=e.length-1)=>{n<0&&(n=e.length+n),n=Math.min(e.length-1,Math.max(n,0));let r=n+1;for(;--r>-1;)if(t(e[r],r,e))return r;return-1},eQ=(e,t,n=0)=>{n<0&&(n=e.length+n),n=Math.min(e.length,Math.max(n,0));let r=n-1;for(;++r<e.length;)if(t(e[r],r,e))return r;return-1},tQ=e=>{e.sort((t,n)=>t-n);for(let t=1;t<e.length;t++)if(e[t]!==e[t-1]+1)return!1;return!0},nQ={isViewport:e=>!_l(e.zoom)&&!_l(e.viewBackgroundColor)},pn={ancestors(e,t={}){const{reverse:n=!1}=t;let r=pn.levels(e,t);return n?r=r.slice(1):r=r.slice(0,-1),r},levels(e,t={}){const{reverse:n=!1}=t,r=[];for(let i=0;i<=e.length;i++)r.push(e.slice(0,i));return n&&r.reverse(),r},parent(e){if(e.length===0)throw new Error(`Cannot get the parent path of the root path [${e}].`);return e.slice(0,-1)},next(e){if(e.length===0)throw new Error(`Cannot get the next path of a root path [${e}], because it has no next index.`);const t=e[e.length-1];return e.slice(0,-1).concat(t+1)},hasPrevious(e){return e[e.length-1]>0},previous(e){if(e.length===0)throw new Error(`Cannot get the previous path of a root path [${e}], because it has no previous index.`);const t=e[e.length-1];if(t<=0)throw new Error(`Cannot get the previous path of a first child path [${e}] because it would result in a negative index.`);return e.slice(0,-1).concat(t-1)},isAncestor(e,t){return e.length<t.length&&pn.compare(e,t)===0},compare(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0},equals(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])},endsBefore(e,t){const n=e.length-1,r=e.slice(0,n),i=t.slice(0,n),o=e[n],s=t[n];return pn.equals(r,i)&&o<s},isSibling(e,t){if(e.length!==t.length)return!1;const n=e.slice(0,-1),r=t.slice(0,-1),i=e[e.length-1],o=t[t.length-1];return i!==o&&pn.equals(n,r)},transform(e,t){if(!e)return null;const n=[...e];if(e.length===0)return n;switch(t.type){case"insert_node":{const{path:r}=t;(pn.equals(r,n)||pn.endsBefore(r,n)||pn.isAncestor(r,n))&&(n[r.length-1]+=1);break}case"remove_node":{const{path:r}=t;if(pn.equals(r,n)||pn.isAncestor(r,n))return null;pn.endsBefore(r,n)&&(n[r.length-1]-=1);break}case"move_node":{const{path:r,newPath:i}=t;if(pn.equals(r,i))return n;if(pn.isAncestor(r,n)||pn.equals(r,n)){const o=i.slice();return pn.endsBefore(r,i)&&r.length<i.length&&(o[r.length-1]-=1),o.concat(n.slice(r.length))}else pn.isSibling(r,i)&&(pn.isAncestor(i,n)||pn.equals(i,n))?pn.endsBefore(r,n)?n[r.length-1]-=1:n[r.length-1]+=1:pn.endsBefore(i,n)||pn.equals(i,n)||pn.isAncestor(i,n)?(pn.endsBefore(r,n)&&(n[r.length-1]-=1),n[i.length-1]+=1):pn.endsBefore(r,n)&&(pn.equals(i,n)&&(n[i.length-1]+=1),n[r.length-1]-=1);break}}return n}},Vn={parent:(e,t)=>{const n=pn.parent(t);return Vn.get(e,n)},*parents(e,t,n={}){for(const r of pn.ancestors(t,n))yield Vn.get(e,r)},get(e,t){let n=e;for(let r=0;r<t.length;r++){const i=t[r];if(!n||!n.children||!n.children[i])throw new Error(`Cannot find a descendant at path [${t}]`);n=n.children[i]}return n},last(e,t){let n=Vn.get(e,t);for(;n&&n.children&&n.children.length>0;){const r=n.children.length-1;n=n.children[r]}return n},first(e,t){const n=t.slice();let r=Vn.get(e,n);if(!r.children||!e.isExpanded(r))return r;for(;r&&r.children&&r.children.length>0&&e.isExpanded(r)&&r.children.length!==0;)r=r.children[0],n.push(0);return r}},ije=(e,t,n,r,i)=>{var o,s;switch(i.type){case"insert_node":{const{path:a,node:l}=i,c=Vn.parent(e,a),u=a[a.length-1];if(!c.children||u>c.children.length)throw new Error(`Cannot apply an "insert_node" operation at path [${a}] because the destination is past the end of the node.`);c.children.splice(u,0,l);break}case"remove_node":{const{path:a}=i,l=Vn.parent(e,a),c=a[a.length-1];if(!l.children||c>l.children.length)throw new Error(`Cannot apply an "insert_node" operation at path [${a}] because the destination is past the end of the node.`);l.children.splice(c,1);break}case"move_node":{const{path:a,newPath:l}=i;if(pn.isAncestor(a,l))throw new Error(`Cannot move a path [${a}] to new path [${l}] because the destination is inside itself.`);const c=Vn.get(e,a),u=Vn.parent(e,a),d=a[a.length-1];(o=u.children)==null||o.splice(d,1);const f=pn.transform(a,i),p=Vn.get(e,pn.parent(f)),y=f[f.length-1];(s=p.children)==null||s.splice(y,0,c);break}case"set_node":{const{path:a,properties:l,newProperties:c}=i;if(a.length===0)throw new Error("Cannot set properties on the root node!");const u=Vn.get(e,a);for(const d in c){const f=c[d];f==null?delete u[d]:u[d]=f}for(const d in l)c.hasOwnProperty(d)||delete u[d];break}case"set_viewport":{const{newProperties:a}=i;if(a==null)n=a;else{if(n==null){if(!nQ.isViewport(a))throw new Error(`Cannot apply an incomplete "set_viewport" operation properties ${JSON.stringify(a)} when there is no current viewport.`);n={...a}}for(const l in a){const c=a[l];c==null?delete n[l]:n[l]=c}}break}case"set_selection":{const{newProperties:a}=i;a==null?t=a:t===null?t=i.newProperties:t=a;break}case"set_theme":{const{newProperties:a}=i;r=a;break}}return{selection:t,viewport:n,theme:r}},oje={transform(e,t){e.children=Ax(e.children);let n=e.viewport&&Ax(e.viewport),r=e.selection&&Ax(e.selection),i=e.theme&&Ax(e.theme);try{const o=ije(e,r,n,i,t);n=o.viewport,r=o.selection,i=o.theme}finally{e.children=Px(e.children),r?e.selection=ou(r)?Px(r):r:e.selection=null,e.viewport=ou(n)?Px(n):n,e.theme=ou(i)?Px(i):i}}},q={isHit:(e,t)=>q.isHitX(e,t)&&q.isHitY(e,t),isHitX:(e,t)=>{const n=e.x<t.x?e.x:t.x,r=e.x+e.width>t.x+t.width?e.x+e.width:t.x+t.width;return Math.floor(r-n-e.width-t.width)<=0},isHitY:(e,t)=>{const n=e.y<t.y?e.y:t.y,r=e.y+e.height>t.y+t.height?e.y+e.height:t.y+t.height;return Math.floor(r-n-e.height-t.height)<=0},getPoints(e){return[[e.x,e.y],[e.x+e.width,e.y+e.height]]},getRectangleByCenterPoint(e,t,n){return q.getRectangleByPoint([e[0]-t/2,e[1]-n/2],t,n)},getRectangleByPoint(e,t,n){return{x:e[0],y:e[1],width:t,height:n}},getRectangleByPoints(e){sje(e)&&(e=[e]);let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const s of e){const a=s.map(c=>c[0]),l=s.map(c=>c[1]);t=Math.min(t,...a),n=Math.min(n,...l),r=Math.max(r,...a),n=Math.min(n,...l),i=Math.max(i,...l)}return{x:t,y:n,width:r-t,height:i-n}},getCornerPointsByPoints(e){const t=e.map(a=>a[0]),n=e.map(a=>a[1]),r=Math.min(...t),i=Math.max(...t),o=Math.min(...n),s=Math.max(...n);return[[r,o],[i,o],[i,s],[r,s]]},getOutlineRectangle:(e,t)=>({x:e.x+t,y:e.y+t,width:e.width-t*2,height:e.height-t*2}),inflate:(e,t)=>{const n=t/2;return{x:e.x-n,y:e.y-n,width:e.width+n*2,height:e.height+n*2}},isEqual:(e,t)=>e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height,getCornerPoints:e=>[[e.x,e.y],[e.x+e.width,e.y],[e.x+e.width,e.y+e.height],[e.x,e.y+e.height]],getCenterPoint:e=>[e.x+e.width/2,e.y+e.height/2],getCenterPointByPoints:e=>q.getCenterPoint(q.getRectangleByPoints(e)),getEdgeCenterPoints:e=>[[e.x+e.width/2,e.y],[e.x+e.width,e.y+e.height/2],[e.x+e.width/2,e.y+e.height],[e.x,e.y+e.height/2]],getConnectionPoint:(e,t)=>[e.x+e.width*t[0],e.y+e.height*t[1]],expand(e,t,n=t,r=t,i=n){return{x:e.x-t,y:e.y-n,width:e.width+t+r,height:e.height+n+i}},getGapCenter(e,t,n){const r=n?"x":"y",i=n?"width":"height",s=[e[r],e[r]+e[i],t[r],t[r]+t[i]].sort((a,l)=>a-l);return(s[1]+s[2])/2},isPointInRectangle(e,t){const n=t[0],r=t[1];return n>e.x&&n<e.x+e.width&&r>e.y&&r<e.y+e.height},getBoundingRectangle(e){if(e.length===0)throw new Error("rectangles can not be empty array");let t=Number.MAX_VALUE,n=Number.MAX_VALUE,r=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return e.forEach(o=>{t=Math.min(t,o.x),n=Math.min(n,o.y),r=Math.max(r,o.x+o.width),i=Math.max(i,o.y+o.height)}),{x:t,y:n,width:r-t,height:i-n}}};function sje(e){return Array.isArray(e)&&e.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number")}function e3(e,t,n,r,i,o){const s=e-n,a=t-r,l=i-n,c=o-r,u=s*l+a*c,d=l*l+c*c;let f=-1;d!==0&&(f=u/d);let p,y;f<0?(p=n,y=r):f>1?(p=i,y=o):(p=n+f*l,y=r+f*c);const v=e-p,w=t-y;return Math.hypot(v,w)}function aw(e,t){const n=e[0],r=e[1],i=t[0][0],o=t[0][1],s=t[1][0],a=t[1][1],l=n-i,c=r-o,u=s-i,d=a-o,f=l*u+c*d,p=u*u+d*d;let y=-1;p!==0&&(y=f/p);let v,w;return y<0?(v=i,w=o):y>1?(v=s,w=a):(v=i+y*u,w=o+y*d),[v,w]}function t3(e,t){const n=t.length;let r=1/0;if(t.length===1)return kn(...t[0],...e);for(let i=0;i<n-1;i++){const o=t[i],s=t[i+1],a=e3(e[0],e[1],o[0],o[1],s[0],s[1]);a<r&&(r=a)}return r}function Dr(e,t,n=!0){const r=t.length;let i=1/0,o=e;for(let s=0;s<r;s++){const a=t[s];if(s===r-1&&!n)continue;const l=s===r-1?t[0]:t[s+1],c=e3(e[0],e[1],a[0],a[1],l[0],l[1]);c<i&&(i=c,o=aw(e,[a,l]))}return o}function LE(e,t){let n=1/0,r=e;for(const i of t){const o=aw(e,i),s=kn(e[0],e[1],o[0],o[1]);s<n&&(n=s,r=o)}return r}function ko(e,t,n,r){const i={x:t[0]-n,y:t[1]-r,height:r*2,width:n*2},o=Math.abs(e[0]-i.x-i.width/2),s=Math.abs(e[1]-i.y-i.height/2);let a=.707,l=.707;const c=Math.abs(i.width)/2,u=Math.abs(i.height)/2;[0,1,2,3].forEach(p=>{const y=c*a,v=u*l,w=(c*c-u*u)*a**3/c,C=(u*u-c*c)*l**3/u,x=y-w,E=v-C,_=o-w,I=s-C,D=Math.hypot(E,x),P=Math.hypot(I,_);a=Math.min(1,Math.max(0,(_*D/P+w)/c)),l=Math.min(1,Math.max(0,(I*D/P+C)/u));const k=Math.hypot(l,a);a/=k,l/=k});const d=e[0]>t[0]?1:-1,f=e[1]>t[1]?1:-1;return[t[0]+c*a*d,t[1]+u*l*f]}function bh(e,t,n,r,i){return[(e-n)*Math.cos(i)-(t-r)*Math.sin(i)+n,(e-n)*Math.sin(i)+(t-r)*Math.cos(i)+r]}function kn(e,t,n,r){const i=e-n,o=t-r;return Math.hypot(i,o)}function ry(e,t,n){var r=Math.max(n.x-e,0,e-(n.x+n.width)),i=Math.max(n.y-t,0,t-(n.y+n.height));return Math.sqrt(r*r+i*i)}const V0=(e,t,n,r)=>{if(on.isEquals(e,t)&&on.isEquals(n,r)&&!on.isEquals(e,n))return!1;const i=(d,f)=>d[0]*f[1]-d[1]*f[0],o=[t[0]-e[0],t[1]-e[1]],s=[n[0]-e[0],n[1]-e[1]],a=[r[0]-e[0],r[1]-e[1]],l=[e[0]-n[0],e[1]-n[1]],c=[t[0]-n[0],t[1]-n[1]],u=[r[0]-n[0],r[1]-n[1]];return i(o,s)*i(o,a)<=0&&i(u,l)*i(u,c)<=0},r1=(e,t)=>{if(e.length===1)return q.isPointInRectangle(t,e[0]);const n=q.getCornerPoints(t),r=e.length;for(let i=0;i<r;i++){const o=e[i],s=e[(i+1)%r];if(i===r-1&&on.isEquals(o,s))continue;if(rQ(o,s,t)||hc(o,n)||hc(s,n))return!0}return!1},rQ=(e,t,n)=>{const r=q.getCornerPoints(n);return V0(e,t,r[0],r[1])||V0(e,t,r[1],r[2])||V0(e,t,r[2],r[3])||V0(e,t,r[3],r[0])},hc=(e,t)=>{const n=e[0],r=e[1];let i=!1;for(var o=0,s=t.length-1;o<t.length;s=o++){let a=t[o][0],l=t[o][1],c=t[s][0],u=t[s][1];l>r!=u>r&&n<(c-a)*(r-l)/(u-l)+a&&(i=!i)}return i},pc=(e,t,n,r,i=0)=>{const o=Math.cos(i),s=Math.sin(i),a=(e[0]-t[0])*o+(e[1]-t[1])*s,l=(e[1]-t[1])*o-(e[0]-t[0])*s;return a*a/(n*n)+l*l/(r*r)<=1},BE=(e,t,n,r=0)=>{const{x:i,y:o,width:s,height:a}=t,l=e[0]>=i&&e[0]<=i+s&&e[1]>=o&&e[1]<=o+a,c=e[0]>=i&&e[0]<=i+n&&e[1]>=o&&e[1]<=o+n&&Math.hypot(e[0]-(i+n),e[1]-(o+n))>n,u=e[0]>=i&&e[0]<=i+n&&e[1]>=o+a&&e[1]<=o+a-n&&Math.hypot(e[0]-(i+n),e[1]-(o+a-n))>n,d=e[0]>=i+s-n&&e[0]<=i+s&&e[1]>=o&&e[1]<=o+n&&Math.hypot(e[0]-(i+s-n),e[1]-(o+n))>n,f=e[0]>=i+s-n&&e[0]<=i+s&&e[1]>=o+a-n&&e[1]<=o+a&&Math.hypot(e[0]-(i+s-n),e[1]-(o+a-n))>n;return l&&!(c||u||d||f)},iy=function(e){let n,r,i,o,s,a,l,c,u,d,f,p,y;var v,w,C,x,E,_;const I=[];I.push([Math.round(e[0][0]),Math.round(e[0][1])]);for(var D=e.length,P=0;P<D-1;P++)n=P==0?e[0]:e[P-1],r=e[P],i=e[P+1],o=P+2<D?e[P+2]:i,l=Math.sqrt(Math.pow(n[0]-r[0],2)+Math.pow(n[1]-r[1],2)),c=Math.sqrt(Math.pow(r[0]-i[0],2)+Math.pow(r[1]-i[1],2)),u=Math.sqrt(Math.pow(i[0]-o[0],2)+Math.pow(i[1]-o[1],2)),v=Math.pow(u,.5),C=Math.pow(u,2*.5),w=Math.pow(c,.5),x=Math.pow(c,2*.5),_=Math.pow(l,.5),E=Math.pow(l,2*.5),d=2*E+3*_*w+x,f=2*C+3*v*w+x,p=3*_*(_+w),p>0&&(p=1/p),y=3*v*(v+w),y>0&&(y=1/y),s=[(-x*n[0]+d*r[0]+E*i[0])*p,(-x*n[1]+d*r[1]+E*i[1])*p],a=[(C*r[0]+f*i[0]-x*o[0])*y,(C*r[1]+f*i[1]-x*o[1])*y],s[0]==0&&s[1]==0&&(s=r),a[0]==0&&a[1]==0&&(a=i),I.push(s,a,i);return I};function Ol(e,t,n,r){return Math.abs(t)===0?e>0?-1/0:1/0:-r*r*e/(n*n*t)}function Rl(e,t,n){if(n===1/0)return[0,-1];if(n===-1/0)return[0,1];let r=[1,-n];return t<0&&(r=[-r[0],-r[1]]),r}function FE(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}function $S(e,t,n=1e-6){return Math.abs(e-t)<=n}function ID(e,t,n,r,i,o,s=!0){if(i===0||o===0||e[0]===t[0]&&e[1]===t[1])return[];i=i<0?i:-i,o=o<0?o:-o,e[0]-=n,e[1]-=r,t[0]-=n,t[1]-=r;var a=(t[0]-e[0])*(t[0]-e[0])/i/i+(t[1]-e[1])*(t[1]-e[1])/o/o,l=2*e[0]*(t[0]-e[0])/i/i+2*e[1]*(t[1]-e[1])/o/o,c=e[0]*e[0]/i/i+e[1]*e[1]/o/o-1,u=[],d=l*l-4*a*c;return d===0?u.push(-l/2/a):d>0&&(u.push((-l+Math.sqrt(d))/2/a),u.push((-l-Math.sqrt(d))/2/a)),u.filter(f=>!s||f>=0&&f<=1).map(f=>[e[0]+(t[0]-e[0])*f+n,e[1]+(t[1]-e[1])*f+r])}function aje(e,t,n,r,i=.5){return[e+(n-e)*i,t+(r-t)*i]}function n3(e,t){const n=(t.endX-e[0])/2,r=(t.endY-e[1])/2,i=Math.cos(t.xAxisRotation),o=Math.sin(t.xAxisRotation),s=i*n+o*r,a=-o*n+i*r,l=Math.abs(t.rx),c=Math.abs(t.ry),u=s*s/(l*l)+a*a/(c*c),d=u>1?Math.sqrt(u):1,f=l*d,p=c*d,y=t.largeArcFlag===t.sweepFlag?-1:1,v=(f*f*p*p-f*f*a*a-p*p*s*s)/(f*f*a*a+p*p*s*s),w=y*Math.sqrt(Math.max(0,v)),C=w*(f*a/p),x=w*(-(p*s)/f),E=i*C-o*x+(e[0]+t.endX)/2,_=o*C+i*x+(e[1]+t.endY)/2;return{center:[E,_],rx:f,ry:p}}function lw(e,t,n){const{center:r,rx:i,ry:o}=n3(t,n),s=ko(e,r,i,o),a=Math.atan2(t[1]-r[1],t[0]-r[0]),l=Math.atan2(n.endY-r[1],n.endX-r[0]),c=Math.atan2(s[1]-r[1],s[0]-r[0]);if(lje(c,a,l,n.sweepFlag===1))return s;const d=kn(e[0],e[1],t[0],t[1]),f=kn(e[0],e[1],n.endX,n.endY);return d<f?t:[n.endX,n.endY]}function lje(e,t,n,r){const i=l=>(l%(2*Math.PI)+2*Math.PI)%(2*Math.PI),o=i(e),s=i(t),a=i(n);return r?s<=a?o>=s&&o<=a:o>=s||o<=a:s>=a?o<=s&&o>=a:o<=s||o>=a}function iQ(e,t,n){const i=ne.getBoardContainer(e).getBoundingClientRect();return ry(t,n,i)===0}function $E(e){const{hideScrollbar:t}=e.options;let n=0;if(!t){const r=ne.getViewportContainer(e);n=r.offsetWidth-r.clientWidth}return n}const Gh="http://www.w3.org/2000/svg";function Tn(){return document.createElementNS(Gh,"g")}function zE(){return document.createElementNS(Gh,"path")}function M2(e,t){const n=document.createElementNS(Gh,"rect");n.setAttribute("x",`${e.x}`),n.setAttribute("y",`${e.y}`),n.setAttribute("width",`${e.width}`),n.setAttribute("height",`${e.height}`);for(let r in t){const i=r;n.setAttribute(r,`${t[i]}`)}return n}const Un=(e,t)=>{e.setAttribute("stroke-linecap",t)},oQ=(e,t)=>{e.querySelectorAll("path").forEach(n=>{n.setAttribute("stroke-linecap",t)})};function sQ(){return document.createElementNS(Gh,"mask")}function aQ(e,t,n,r){var i=document.createElementNS(Gh,"text");return i.setAttribute("x",`${e}`),i.setAttribute("y",`${t}`),i.setAttribute("fill",n),i.textContent=r,i}const lQ=e=>cQ(e)&&e.nodeType===1,cQ=e=>e instanceof window.Node,cje=e=>!!(lQ(e)&&(e.tagName==="INPUT"||e.tagName==="TEXTAREA")),Il=e=>e.button===ZR.MAIN,uQ=e=>e.button===ZR.WHEEL;function UE(e,t,n,r){var i=document.createElementNS(Gh,"foreignObject");return i.setAttribute("x",`${e}`),i.setAttribute("y",`${t}`),i.setAttribute("width",`${FE(n,0)}`),i.setAttribute("height",`${r}`),i}function Hm(e,t,n,r,i){const o=e instanceof SVGForeignObjectElement?e:e.querySelector("foreignObject");o&&(o.setAttribute("width",`${FE(t,0)}`),o.setAttribute("height",`${n}`),o.setAttribute("x",`${r}`),o.setAttribute("y",`${i}`))}function dQ(e,t){const n=e instanceof SVGForeignObjectElement?e:e.querySelector("foreignObject");n&&n.setAttribute("width",`${FE(t,0)}`)}const fQ=typeof window<"u"&&/Mac|iPod|iPhone|iPad/.test(window.navigator.platform),uje=typeof navigator<"u"&&typeof window<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,zS=typeof navigator<"u"&&/Mac OS X/.test(navigator.userAgent),dje=typeof navigator<"u"&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent),fje=typeof navigator<"u"&&/Version\/[\d\.]+.*Safari/.test(navigator.userAgent),hje=typeof navigator<"u"&&/Chrome/i.test(navigator.userAgent),hQ=(e,t)=>e.type==="set_viewport"&&e.type===(t==null?void 0:t.type),pQ=(e,t)=>!(e.type==="set_selection"||e.type==="set_viewport"),mQ=e=>e.type!=="set_selection",Ca={isSaving(e){return R2.get(e)},isMerging(e){return Qi.get(e)},isSplittingOnce(e){return K0.get(e)},setSplittingOnce(e,t){K0.set(e,t)},withMerging(e,t){const n=Ca.isMerging(e);Qi.set(e,!0),t(),Qi.set(e,n)},withNewBatch(e,t){const n=Ca.isMerging(e);Qi.set(e,!0),K0.set(e,!0),t(),Qi.set(e,n),K0.delete(e)},withoutMerging(e,t){const n=Ca.isMerging(e);Qi.set(e,!1),t(),Qi.set(e,n)},withoutSaving(e,t){const n=Ca.isSaving(e);R2.set(e,!1),t(),R2.set(e,n)}},pje={bold:"mod+b",compose:["down","left","right","up","backspace","enter"],arrow:["down","left","right","up"],extendArrow:["shift+down","shift+left","shift+right","shift+up"],moveBackward:"left",moveForward:"right",moveUp:"up",moveDown:"down",moveWordBackward:"ctrl+left",moveWordForward:"ctrl+right",deleteBackward:"shift?+backspace",deleteForward:"shift?+delete",extendBackward:"shift+left",extendForward:"shift+right",extendUp:"shift+up",extendDown:"shift+down",italic:"mod+i",splitBlock:"shift?+enter",undo:"mod+z",shift:"shift"},mje={moveLineBackward:"opt+up",moveLineForward:"opt+down",moveWordBackward:"opt+left",moveWordForward:"opt+right",deleteBackward:["ctrl+backspace","ctrl+h"],deleteForward:["ctrl+delete","ctrl+d"],deleteLineBackward:"cmd+shift?+backspace",deleteLineForward:["cmd+shift?+delete","ctrl+k"],deleteWordBackward:"opt+shift?+backspace",deleteWordForward:"opt+shift?+delete",extendLineBackward:"opt+shift+up",extendLineForward:"opt+shift+down",redo:"cmd+shift+z",transposeCharacter:"ctrl+t"},gje={deleteWordBackward:"ctrl+shift?+backspace",deleteWordForward:"ctrl+shift?+delete",redo:["ctrl+y","ctrl+shift+z"]},Er=e=>{const t=pje[e],n=mje[e],r=gje[e],i=t&&$r.isKeyHotkey(t),o=n&&$r.isKeyHotkey(n),s=r&&$r.isKeyHotkey(r);return a=>!!(i&&i(a)||zS&&o&&o(a)||!zS&&s&&s(a))},wo={isBold:Er("bold"),isCompose:Er("compose"),isArrow:Er("arrow"),isMoveBackward:Er("moveBackward"),isMoveForward:Er("moveForward"),isMoveUp:Er("moveUp"),isMoveDown:Er("moveDown"),isDeleteBackward:Er("deleteBackward"),isDeleteForward:Er("deleteForward"),isDeleteLineBackward:Er("deleteLineBackward"),isDeleteLineForward:Er("deleteLineForward"),isDeleteWordBackward:Er("deleteWordBackward"),isDeleteWordForward:Er("deleteWordForward"),isExtendBackward:Er("extendBackward"),isExtendForward:Er("extendForward"),isExtendUp:Er("extendUp"),isExtendDown:Er("extendDown"),isExtendArrow:Er("extendArrow"),isExtendLineBackward:Er("extendLineBackward"),isExtendLineForward:Er("extendLineForward"),isItalic:Er("italic"),isMoveLineBackward:Er("moveLineBackward"),isMoveLineForward:Er("moveLineForward"),isMoveWordBackward:Er("moveWordBackward"),isMoveWordForward:Er("moveWordForward"),isRedo:Er("redo"),isSplitBlock:Er("splitBlock"),isTransposeCharacter:Er("transposeCharacter"),isUndo:Er("undo"),isShift:Er("shift")};function fr(e=5){const t="ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz",n=t.length;let r="";for(let i=0;i<e;i++)r+=t.charAt(Math.floor(Math.random()*n));return r}function co(e,t,n,r){if(e.children&&(!n||n(e))){let i=[...e.children];i=r?i.reverse():i,i.forEach(o=>{co(o,t,n)})}t(e)}const zd=e=>t=>!!(ne.isBoard(t)||e.isRecursion(t)),ns="#6698FF",HE="#6698FF25",xh={isCollapsed(e){return e.anchor[0]==e.focus[0]&&e.anchor[1]===e.focus[1]}},sr={isRootElement(e){const t=gd.get(e);return!!(t&&ne.isBoard(t))},getElementRef(e){return wm.get(e)},getElementG(e){const t=ym.get(e);if(!t)throw new Error(`can not resolve element g: ${JSON.stringify(e)}`);return t},hasMounted(e){return!!sr.getContainerG(e,{suppressThrow:!0})},getContainerG(e,t){const n=vm.get(e)||null;if(!n){if(t.suppressThrow)return null;throw new Error("can not resolve container g")}return n}},cw=(e,t,n=!0)=>[...t].sort((r,i)=>{const o=ne.findPath(e,r),s=ne.findPath(e,i);return n?o[0]-s[0]:s[0]-o[0]}),gQ=new Map,I0=e=>gQ.get(e)||[],A0=(e,t)=>{gQ.set(e,t)};class yQ{constructor(t){this.debugKey=t}isDebug(){return Wc(this.debugKey)}clear(){if(!this.isDebug())return;const t=I0(this.debugKey);A0(this.debugKey,[]),t.forEach(n=>n.remove())}drawPolygon(t,n,r){if(!Wc(this.debugKey))return;const i=ne.getRoughSVG(t).polygon(n,r||{stroke:"red"});i.classList.add(this.debugKey),ne.getElementTopHost(t).append(i);const o=I0(this.debugKey);return o.push(i),A0(this.debugKey,o),i}drawLine(t,n,r){if(!Wc(this.debugKey))return;const i=ne.getRoughSVG(t).linearPath(n,r||{stroke:"red"});i.classList.add(this.debugKey),ne.getElementTopHost(t).append(i);const o=I0(this.debugKey);return o.push(i),A0(this.debugKey,o),i}drawRectangle(t,n,r){if(!Wc(this.debugKey))return;let i;n instanceof Array?i=q.getRectangleByPoints(n):i=n;const o=ne.getRoughSVG(t).rectangle(i.x,i.y,i.width,i.height,r||{stroke:"red"});o.classList.add(this.debugKey),ne.getElementTopHost(t).append(o);const s=I0(this.debugKey);return s.push(o),A0(this.debugKey,s),o}drawCircles(t,n,r=0,i=!1,o){if(!Wc(this.debugKey))return;const s=[];return n.forEach((a,l)=>{const c=ne.getRoughSVG(t).circle(a[0],a[1],i?r*(l+1):r,Object.assign({},{stroke:"red",fill:"red",fillStyle:"solid"},o||{}));c.classList.add(this.debugKey),ne.getElementTopHost(t).append(c);const u=I0(this.debugKey);u.push(c),s.push(c),A0(this.debugKey,u)}),s}}const Kh=e=>new yQ(e),Wc=e=>localStorage.getItem(e||"debug:plait")==="true";var xl;(function(e){e.withSelection="withSelection",e.withHand="withHand"})(xl||(xl={}));const r3=(e,t,n=()=>!0)=>{const r=t||e.selection,i=[];if(!r)return[];if(xh.isCollapsed(r)){const s=i3(e,r.anchor,n);return s!=null&&s.length?s:[]}return co(e,s=>{if(!ne.isBoard(s)&&n(s)){let a=!1;try{a=e.isRectangleHit(s,r)}catch(l){Wc()&&console.error("isRectangleHit",l,"node",s)}a&&i.push(s)}},zd(e),!0),i},i3=(e,t,n=()=>!0,r=!0)=>{let i=[];return co(e,o=>{if(ne.isBoard(o)||!n(o)||!sr.hasMounted(o))return;let s=!1;try{s=e.isHit(o,t,r)}catch(a){Wc()&&console.error("isHit",a,"node",o)}if(s){i.push(o);return}},zd(e),!0),i},$a=(e,t,n=()=>!0,r=!0)=>{const i=i3(e,t,n,r);return e.getOneHitElement(i)},vQ=(e,t)=>{const n=Et(e),r=n.length>0&&Pn(e,n,!1);return r&&q.isPointInRectangle(r,t)?n:[]},yl=(e,t)=>{const n=cw(e,t);QR.set(e,n)},Et=e=>QR.get(e)||[],za=(e,t)=>{let n=[];Array.isArray(t)?n.push(...t):n.push(t);const r=Et(e);yl(e,[...r,...n])},uw=(e,t,n=!1)=>{const r=Et(e);if(r.includes(t)){const i=[];e.isRecursion(t)&&n?co(t,s=>{i.push(s)},s=>e.isRecursion(s)):i.push(t);const o=r.filter(s=>!i.includes(s));yl(e,o)}},wQ=(e,t,n)=>{const r=Et(e);r.splice(r.indexOf(t),1,n)},Nl=e=>{yl(e,[])},yd=(e,t)=>!!Et(e).find(r=>r===t),US=e=>{const t=e.getPluginOptions(xl.withSelection);e.setPluginOptions(xl.withSelection,{isDisabledSelection:!0}),setTimeout(()=>{e.setPluginOptions(xl.withSelection,{...t})},0)},bQ=(e,t)=>vQ(e,t).length>0,o3=(e,t)=>!!$a(e,t)||bQ(e,t);function qh(e,t,n,r,i,o,s=!1,a){let l=a||0;const c=[t+l,n],u=[r-l,n],d=[r,n+l],f=[r,i-l],p=[r-l,i],y=[t+l,i],v=[t,i-l],w=[t,n+l],C=e.path(`M${u[0]} ${u[1]} A ${l} ${l}, 0, 0, 1, ${d[0]} ${d[1]} L ${f[0]} ${f[1]} A ${l} ${l}, 0, 0, 1, ${p[0]} ${p[1]} L ${y[0]} ${y[1]} A ${l} ${l}, 0, 0, 1, ${v[0]} ${v[1]} L ${w[0]} ${w[1]} A ${l} ${l}, 0, 0, 1, ${c[0]} ${c[1]} Z`,o);return Un(C,"round"),C}const Ua=(e,t,n)=>{const i=ne.getRoughSVG(e).rectangle(t.x,t.y,t.width,t.height,n);return Un(i,"round"),i};function Yh(e,t,n=40){const r=Math.abs(e[0]-t[0]),i=Math.abs(e[1]-t[1]);let o=Math.hypot(r,i);const s=o/2,a=s/o*r,l=s/o*i,c=[t[0]>e[0]?t[0]-a:t[0]+a,t[1]>e[1]?t[1]-l:t[1]+l],u=bh(c[0],c[1],t[0],t[1],n*Math.PI/180);return{pointLeft:bh(c[0],c[1],t[0],t[1],-n*Math.PI/180),pointRight:u}}function Ud(e,t,n,r){return e.circle(t[0],t[1],n,r)}function G0(e,t,n,r){return e.linearPath([t,n],r)}function aa(e,t,n){const r=Tn(),i=zE();let o="";return e.forEach((s,a)=>{a===0?o+=`M ${s[0]} ${s[1]} `:o+=`L ${s[0]} ${s[1]} `}),n&&(o+="Z"),i.setAttribute("d",o),i.setAttribute("stroke",`${t==null?void 0:t.stroke}`),i.setAttribute("stroke-width",`${t==null?void 0:t.strokeWidth}`),i.setAttribute("fill",`${(t==null?void 0:t.fill)||"none"}`),t!=null&&t.strokeLineDash&&i.setAttribute("stroke-dasharray",`${t.strokeLineDash}`),r.appendChild(i),r}function xQ(e,t){const n=Tn(),r=zE();let i="";for(let o=0;o<e.length-3;o+=3)o===0?i+=`M ${e[0][0]} ${e[0][1]} `:i+=`C ${e[o+1][0]} ${e[o+1][1]}, ${e[o+2][0]} ${e[o+2][1]}, ${e[o+3][0]} ${e[o+3][1]}`;return r.setAttribute("d",i),r.setAttribute("stroke",`${t==null?void 0:t.stroke}`),r.setAttribute("stroke-width",`${t==null?void 0:t.strokeWidth}`),r.setAttribute("fill","none"),n.appendChild(r),n}function s3(e,t){const n={type:"set_viewport",properties:e.viewport,newProperties:t};e.apply(n)}const yje={setViewport:s3};function vje(e,t){const n={type:"set_theme",properties:e.theme,newProperties:t};e.apply(n)}function WE(e,t,n){n=n??e.viewport.zoom,s3(e,{...e.viewport,zoom:n,origination:t}),p3(e)}function wje(e,t,n){t=PQ(t);const i=ne.getBoardContainer(e).getBoundingClientRect(),o=ne.getBoardContainer(e).getBoundingClientRect();let s=[o.width/2,o.height/2];n&&ry(n[0],n[1],i)===0&&(s=[n[0]-i.x,n[1]-i.y]);const a=e.viewport.zoom,l=Xh(e),c=l[0]+s[0]/a,u=l[1]+s[1]/a,d=[c-s[0]/t,u-s[1]/t];WE(e,d,t)}function bje(e){let t=$E(e);const n=ne.getBoardContainer(e).getBoundingClientRect(),r=Pn(e,e.children,!0),i=e.viewport.zoom,o=16,s=n.width-2*o,a=n.height-2*o;let l=i;s<r.width||a<r.height?l=Math.min(s/r.width,a/r.height):l=1;const c=d3(e),u=[c[0]-n.width/2/l+t/2/i,c[1]-n.height/2/l+t/2/i];WE(e,u,l)}function xje(e,t){let n=$E(e);const r=ne.getBoardContainer(e),i=r.getBoundingClientRect();let o=0;t.maxWidth?o=t.maxWidth:o=i.width;const s=Pn(e,e.children,!0),a=o-2*t.autoFitPadding;let l=0;a<s.width?l=Math.min(a/s.width):l=1;let c=s.height*l+2*t.autoFitPadding;if(c>t.limitHeight){const p=r.closest(`.${t.containerClass}`);p.style.height=`${c}px`,TQ(e)}else c=t.limitHeight;const u=s.x+s.width/2,d=s.y+s.height/2,f=[u-o/2/l+n/2/l,d-c/2/l+n/2/l];WE(e,f,l)}function Sje(e,t){t=t??e.theme.themeColorMode,vje(e,{themeColorMode:t}),co(e,n=>{e.applyTheme(n)})}const Cje=(e,t)=>{e.pointer!==t&&(e.pointer=t)};function Eje(e,t){var r;if((r=Et(e))==null?void 0:r[0]){const i=ne.getBoardContainer(e).getBoundingClientRect(),o=$E(e),s=d3(e),a=t[0]-s[0],l=t[1]-s[1],c=e.viewport.zoom,u=[a-i.width/2/c+o/2/c,l-i.height/2/c+o/2/c];s3(e,{...e.viewport,origination:u}),p3(e)}}const $i={updatePointerType:Cje,updateViewport:WE,fitViewport:bje,updateZoom:wje,updateThemeColor:Sje,fitViewportWidth:xje,moveToCenter:Eje},VE=e=>ne.getHost(e).viewBox.baseVal;function An(e,t,n){const i=ne.getHost(e).getBoundingClientRect();return[t-i.x,n-i.y]}function _o(e,t){const n=[t.x,t.y],r=[t.x+t.width,t.y+t.height],i=Ig(e,n),o=Ig(e,r);return q.getRectangleByPoints([i,o])}function Ig(e,t){const n=CQ(e,a3(e,t));return Ed(e,n[0],n[1])}function Ed(e,t,n){const i=ne.getBoardContainer(e).getBoundingClientRect();return[t-i.x,n-i.y]}function SQ(e,t){const r=ne.getBoardContainer(e).getBoundingClientRect();return[r.x+t[0],r.y+t[1]]}function _n(e,t){const n=VE(e),{zoom:r}=e.viewport,i=t[0]/r+n.x,o=t[1]/r+n.y;return[i,o]}function CQ(e,t){const r=ne.getHost(e).getBoundingClientRect();return[t[0]+r.x,t[1]+r.y]}function a3(e,t){const{zoom:n}=e.viewport,r=VE(e),i=(t[0]-r.x)*n,o=(t[1]-r.y)*n;return[i,o]}const l3=.75,EQ=new WeakMap,_Q=new WeakMap;function IQ(e){const{hideScrollbar:t}=e.options,n=t?$J:0,r=ne.getBoardContainer(e).getBoundingClientRect();return{width:r.width+n,height:r.height+n}}function AQ(e,t){const n=Pn(e,e.children,!0);let r,i,o,s;return r=n.x,i=n.x+n.width,o=n.y,s=n.y+n.height,{left:r,right:i,top:o,bottom:s}}function PQ(e,t=LJ,n=BJ){return e<t?t:e>n?n:e}function c3(e,t){const n=ne.getBoardContainer(e).getBoundingClientRect(),r=AQ(e),i=n.width,o=n.height;let s=r.right-r.left,a=r.bottom-r.top;const l=i/2,c=o/2;if(s<l/t){const u=r.left+s/2;r.left=u-l/2/t,r.right=u+l/2/t,s=l/t}if(a<c/t){const u=r.top+a/2;r.top=u-c/2/t,r.bottom=u+c/2/t,a=c/t}return{elementHostBBox:r,containerWidth:i,containerHeight:o,width:s,height:a}}function HS(e,t,n,r,i,o,s=l3){const a=t*s/o,l=n*s/o;return[e.left-a,e.top-l,r+a*2,i+l*2]}function u3(e,t){const{elementHostBBox:n,containerWidth:r,containerHeight:i,width:o,height:s}=c3(e,t);return HS(n,r,i,o,s,t)}function d3(e){const t=Pn(e,e.children,!0);return[t.x+t.width/2,t.y+t.height/2]}function f3(e,t){const n=e.viewport.zoom,r=ne.getHost(e);r.style.display="block",r.style.width=`${t[2]*n}px`,r.style.height=`${t[3]*n}px`,t&&t[2]>0&&t[3]>0&&r.setAttribute("viewBox",t.join(" "))}function AD(e){const t=Xh(e);if(!t)return;const[n,r]=a3(e,t);h3(e,n,r)}function h3(e,t,n,r=!0){const i=ne.getViewportContainer(e),o=i.scrollLeft,s=i.scrollTop;if(!$S(i.scrollLeft,t,1)||!$S(i.scrollTop,n,1)){i.scrollLeft=t,i.scrollTop=n;const a=i.offsetWidth,l=i.offsetHeight;if(o===i.scrollLeft&&s===i.scrollTop)kQ(e,o,s);else{const c=t>0&&n>0&&t<i.scrollWidth-a&&n<i.scrollHeight-l;r&&c&&OQ(e,!0)}}}function kQ(e,t,n){const r=_n(e,[t,n]);on.isEquals(r,Xh(e))||($i.updateViewport(e,r),MQ(e,!0))}function TQ(e){const{width:t,height:n}=IQ(e),r=ne.getViewportContainer(e);r.style.width=`${t}px`,r.style.height=`${n}px`}function _je(e){const t=e.viewport.zoom,n=u3(e,t);f3(e,n)}function Ije(e){const t=e.viewport.zoom,{elementHostBBox:n,containerWidth:r,containerHeight:i,width:o,height:s}=c3(e,t),a=HS(n,r,i,o,s,t,.5),l=VE(e);if(a[0]<l.x||a[1]<l.y||a[0]+a[2]>l.x+l.width||a[1]+a[3]>l.y+l.height){const c=HS(n,r,i,o,s,t,l3);f3(e,c)}}function Aje(e){var t;if(!((t=e.viewport)!=null&&t.origination)){const n=e.viewport.zoom,r=ne.getBoardContainer(e).getBoundingClientRect(),i=u3(e,n),o=i[0]+i[2]/2,s=i[1]+i[3]/2,a=[o-r.width/2/n,s-r.height/2/n];DQ(e,a),AD(e);return}AD(e)}const DQ=(e,t)=>{RE.set(e,t)},p3=e=>{RE.delete(e)},Xh=e=>{const t=RE.get(e);return t||e.viewport.origination},Pje=e=>!!EQ.get(e),MQ=(e,t)=>{EQ.set(e,t)},kje=e=>!!_Q.get(e),OQ=(e,t)=>{_Q.set(e,t)};function Tje(e,t,n){const r={type:"insert_node",node:t,path:n};e.apply(r)}function Dje(e,t,n){const r={},i={},o=Vn.get(e,n);for(const a in t)o[a]!==t[a]&&(o.hasOwnProperty(a)&&(r[a]=o[a]),t[a]!=null&&(i[a]=t[a]));const s={type:"set_node",properties:r,newProperties:i,path:n};e.apply(s)}function RQ(e,t){const n=Vn.get(e,t),r={type:"remove_node",path:t,node:n};e.apply(r)}function Mje(e,t,n){const r={type:"move_node",path:t,newPath:n};e.apply(r)}const ih={insertNode:Tje,setNode:Dje,removeNode:RQ,moveNode:Mje},O2=new WeakMap,Oje=(e,t)=>NQ(e)[t]||null,NQ=e=>O2.get(e)||{},mc=(e,t,n)=>{const r=()=>{let o=requestAnimationFrame(()=>{const a=O2.get(e)||{};a[t]=null,O2.set(e,a),ne.isAlive(e)&&n()});const s=NQ(e);s[t]=o,O2.set(e,s)};let i=Oje(e,t);i!==null&&cancelAnimationFrame(i),r()},dw=(e,t)=>(cw(e,t),t.map(n=>e.children.map(r=>r.id).indexOf(n.id)).filter(n=>n>=0)),jQ=(e,t)=>{const n=dw(e,t);return n[n.length-1]},oy=(e,t)=>{t.map(n=>{const r=ne.findPath(e,n.element),i=e.pathRef(r);return()=>{i.current&&ih.moveNode(e,i.current,n.newPath),i.unref()}}).forEach(n=>{n()})},m3=new WeakMap,sy=e=>!!m3.get(e),Cc=(e,t)=>{m3.set(e,t)},LQ=e=>sw.get(e)||[],Ag=e=>(sw.get(e)||[]).length>0,BQ=e=>{sw.delete(e),Cc(e,!1)},PD=(e,t)=>{sw.set(e,t),Cc(e,!0)},kD="foreignObject[class^='foreign-object']";function gz(e){return e.nodeType===Node.ELEMENT_NODE}function Rje(e){return new Promise((t,n)=>{const r=new Image;r.crossOrigin="Anonymous",r.onload=()=>t(r),r.onerror=()=>n(new Error("Failed to load image")),r.src=e})}function Nje(e,t,n="transparent"){const r=document.createElement("canvas"),i=r.getContext("2d");return r.width=e,r.height=t,r.style.width=`${e}px`,r.style.height=`${t}px`,i.strokeStyle="#ffffff",i.fillStyle=n,i.fillRect(0,0,e,t),{canvas:r,ctx:i}}async function jje(e){const n=await(await fetch(e)).blob();return new Promise((r,i)=>{const o=new FileReader;o.onloadend=()=>r(o.result),o.onerror=i,o.readAsDataURL(n)})}function Lje(e,t){const n=t==null?void 0:t.style;if(!n)return;const r=window.getComputedStyle(e);r.cssText?(n.cssText=r.cssText,n.transformOrigin=r.transformOrigin):Array.from(r).forEach(i=>{let o=r.getPropertyValue(i);n.setProperty(i,o,r.getPropertyPriority(i))})}function Bje(e,t,n){if(n){const r=n+`, ${kD}`,i=Array.from(e.querySelectorAll(r)),o=Array.from(t.querySelectorAll(r));i.forEach((s,a)=>{const l=Array.from(s.querySelectorAll("*")).filter(gz),c=Array.from(o[a].querySelectorAll("*")).filter(gz);i.push(...l),o.push(...c)}),i.map((s,a)=>{Lje(s,o[a])})}}async function Fje(e,t){const n=Array.from(e.querySelectorAll(`${kD}`)),r=Array.from(t.querySelectorAll(`${kD}`));await Promise.all(n.map((i,o)=>new Promise(s=>{const l=r[o].querySelector("img"),c=l==null?void 0:l.getAttribute("src");if(!c)return s(!0);jje(c).then(u=>{l==null||l.setAttribute("src",u),s(!0)})})))}async function $je(e,t,n,r){const{width:i,height:o,x:s,y:a}=n,{padding:l=4,inlineStyleClassNames:c}=r,u=ne.getHost(e),d=t.map(v=>sr.getElementG(v)),f=u.cloneNode(),p=ne.getElementHost(e).cloneNode();f.style.width=`${i}px`,f.style.height=`${o}px`,f.style.backgroundColor="",f.setAttribute("width",`${i}`),f.setAttribute("height",`${o}`),f.setAttribute("viewBox",[s-l,a-l,i+2*l,o+2*l].join(","));const y=new Array(d.length);return await Promise.all(d.map(async(v,w)=>{const C=v.cloneNode(!0);Bje(v,C,c),await Fje(v,C),y[w]=C})),p.append(...y),f.appendChild(p),f}async function FQ(e,t){if(!e)return;const n=t.elements||Zh(e,{match:()=>!0,recursion:()=>!0,isReverse:!1}),r=Pn(e,n,!1),{ratio:i=2,fillStyle:o="transparent"}=t,{width:s,height:a}=r,l=s*i,c=a*i,u=await $je(e,n,r,t),{canvas:d,ctx:f}=Nje(l,c,o),p=new XMLSerializer().serializeToString(u),y=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(p)}`;try{const v=await Rje(y);return f.drawImage(v,0,0,l,c),d.toDataURL("image/png")}catch(v){console.error("Error converting SVG to image:",v);return}}var gc;(function(e){e.medias="medias",e.elements="elements"})(gc||(gc={}));var _d;(function(e){e.copy="copy",e.cut="cut",e.duplicate="duplicate",e.paste="paste"})(_d||(_d={}));const GE=(e,t)=>`<plait>${HQ(JSON.stringify({type:e,data:t}))}</plait>`,KE=e=>{var n;let t=(n=e==null?void 0:e.match(/<plait[^>]*>(.*)<\/plait>/))==null?void 0:n[1];if(t){t=WQ(t);try{const r=JSON.parse(t);if(r){if(r.type===gc.elements)return{elements:r.data};if(r.type===gc.medias)return{medias:r.data}}}catch(r){return console.error(r),null}}return null},TD=e=>{const t=document.implementation.createHTMLDocument("");return t.documentElement.innerHTML=e.trim(),t.body.textContent||t.body.innerText||""},g3=()=>"clipboard"in navigator&&"write"in navigator.clipboard,$Q=()=>"clipboard"in navigator&&"writeText"in navigator.clipboard,y3=()=>"clipboard"in navigator&&"read"in navigator.clipboard,zQ=(e,t,n)=>({type:e,elements:t,text:n}),UQ=(e,t)=>{const{type:n,elements:r,text:i}=e;return n===t.type?{type:n,elements:r.concat(t.elements),text:i+" "+t.text}:e},fw=(e,t)=>e?UQ(e,t):t,HQ=e=>e.replace(/</g,"<").replace(/>/g,">"),WQ=e=>e.replace(/</g,"<").replace(/>/g,">"),VQ=(e,t,n)=>{e==null||e.setData("text/html",GE(t,n))},GQ=(e,t)=>{e==null||e.setData("text/plain",t)},KQ=e=>{const t=e==null?void 0:e.getData("text/html");if(t){const n=KE(t);if(n)return n}return{}},qQ=e=>{if(!e)return{};const t=e==null?void 0:e.getData("text/plain");if(t){const n=KE(t);if(n)return n}return{text:t}},zje=async(e,t,n="")=>{let r=n;g3()&&await navigator.clipboard.write([new ClipboardItem({"text/html":new Blob([GE(e,t)],{type:"text/html"}),"text/plain":new Blob([r??JSON.stringify(t)],{type:"text/plain"})})])},Uje=async()=>{if(!y3())return{};const e=await navigator.clipboard.read();let t={};if(Array.isArray(e)&&e[0]instanceof ClipboardItem)for(const n of e){if(Hje(n)){const r=n.types.filter(a=>a.match(/^image\//)),o=(await Promise.all(r.map(a=>n.getType(a)))).filter(Boolean).map(a=>URL.createObjectURL(a));return{files:await Promise.all(o.map(async a=>{const l=await(await fetch(a)).blob();return new File([l],"plait-file",{type:l.type})}))}}if(n.types.includes("text/html")){const r=await yz(await n.getType("text/html")),i=KE(r);if(i)return i;r&&r.trim()&&(t={text:TD(r)})}if(n.types.includes("text/plain")){const r=await yz(await n.getType("text/plain"));t={text:TD(r)}}}return t},Hje=e=>e.types.find(t=>t.match(/^image\//)),yz=e=>new Promise((t,n)=>{const r=new FileReader;r.addEventListener("loadend",()=>{const i=r.result;t(i)}),r.addEventListener("error",()=>{n(r.error)}),r.readAsText(e)}),Wje=async e=>{let t={};return e?e.files.length?{files:Array.from(e.files)}:(t=KQ(e),Object.keys(t).length===0&&(t=qQ(e)),t):y3()?await Uje():t},YQ=async(e,t)=>{if(!t)return;const{type:n,elements:r,text:i}=t;if(g3())return await zje(n,r,i);if(e){VQ(e,n,r),GQ(e,i);return}if($Q())return await navigator.clipboard.writeText(GE(n,r))};function Go(e){return!!NE.get(e)}function XQ(e){ne.getBoardContainer(e).classList.add("selection-moving"),NE.set(e,!0),Cc(e,!0)}function ZQ(e){ne.getBoardContainer(e).classList.remove("selection-moving"),NE.delete(e),Cc(e,!1)}function DD(e){const t=fv(e);return e.pointer!==Ir.hand&&!t.isDisabledSelection&&!ne.isReadonly(e)}function MD(e){return!!e.operations.find(t=>j3.isSetSelectionOperation(t))}function JQ(e){const t=ow.get(e);if(t)return t.elements}function QQ(e){return ow.get(e)}function eee(e){ow.delete(e)}function tee(e){const t=Et(e),n=Pn(e,t,!1),r=_o(e,n);if(r.width>0&&r.height>0&&t.length>1){const i=Ua(e,q.inflate(r,ti),{stroke:ns,strokeWidth:ti,fillStyle:"solid"});i.classList.add(ny,jJ);const o=es(t);return o&&ta(i,q.getCenterPoint(r),o),i}return null}function nee(e,t,n){if(!e.selection)return;const r=Et(e);if(!xh.isCollapsed(e.selection)){let i=[...r];t.forEach(o=>{o.groupId?i.push(...YE(e,o)):i.push(o)}),yl(e,jE(i));return}if(xh.isCollapsed(e.selection)){const i=t[0],o=Su(e,i,!0);if(o.length>0){const s=ua(e,o[o.length-1],!0)||[],a=r.some(l=>s.map(c=>c.id).includes(l.id));n?ree(e,t,a,s):iee(e,t,a,o)}}}function ree(e,t,n,r){const i=Et(e);let o=[...i];const s=t[0];let a=[];if(!n)a=r;else{const l=i.some(u=>u.id===s.id),c=r.filter(u=>i.includes(u));l?a=c.filter(u=>u.id!==s.id):a.push(...c,...t)}r.forEach(l=>{o.includes(l)&&o.splice(o.indexOf(l),1)}),a.length&&o.push(...a),yl(e,jE(o))}function iee(e,t,n,r){let i=[...t];const o=v3(e,r);if(o.length>0)if(o.length>1)i=i1(e,o[o.length-2],!0);else{const s=e.getOneHitElement(t);s&&(i=[s])}else{const s=i1(e,r[r.length-1],!0);if(!n)i=s;else{const a=e.getOneHitElement(t);a&&(i=[a])}}yl(e,jE(i))}const fv=e=>e.getPluginOptions(xl.withSelection),WS=(e,t)=>{e.setPluginOptions(xl.withSelection,t)},ua=(e,t,n,r)=>{let i=[];const o=e.children.filter(s=>s.groupId===t.id);return n?o.forEach(s=>{rs.isGroup(s)?(r&&i.push(s),i.push(...ua(e,s,n,r))):i.push(s)}):i=r?o:o.filter(s=>!rs.isGroup(s)),i},i1=(e,t,n,r)=>{const i=ua(e,t,n,r),o=[];return i.forEach(s=>{co(s,a=>{o.push(a)},()=>!0)}),o},qE=(e,t,n)=>{const r=i1(e,t,n);return Pn(e,r,!1)},Su=(e,t,n,r)=>{const i=(r||e.children).find(o=>o.id===(t==null?void 0:t.groupId));if(!i)return[];{const o=[i],s=Su(e,i,n,r);return s.length&&o.push(...s),o}},VS=(e,t)=>{const n=Su(e,t,!0);return n.length?n[n.length-1]:null},YE=(e,t)=>{const n=VS(e,t);return n?i1(e,n,!0):[t]},GS=(e,t,n)=>{const r=n!=null&&n.length?n:Et(e);return rs.isGroup(t)?o1(e,t,n):r.map(i=>i.id).includes(t.id)},o1=(e,t,n)=>{const r=n!=null&&n.length?n:Et(e);return ua(e,t,!0).every(o=>r.map(s=>s.id).includes(o.id))},v3=(e,t,n)=>{const r=[];return t.forEach(i=>{GS(e,i,n)&&r.push(i)}),r},oee=(e,t,n)=>{const r=Cu(e,t,n),i=[];return r.forEach(o=>{i.push(o);const s=ua(e,o,!0,!0);i.push(...s.filter(a=>rs.isGroup(a)))}),i},w3=(e,t,n,r)=>{const i=Su(e,t,!0,r),o=v3(e,i,n);return o.length?o[o.length-1]:null},Cu=(e,t,n)=>{let r=[];return(t!=null&&t.length?t:Et(e)).forEach(o=>{if(o.groupId){const s=w3(e,o,t,n);s&&!r.includes(s)&&r.push(s)}}),r},XE=(e,t)=>{let n=[];return(t!=null&&t.length?t:Et(e)).filter(i=>!rs.isGroup(i)).forEach(i=>{i.groupId&&w3(e,i,t)||n.push(i)}),n},ZE=(e,t)=>XE(e,t).filter(r=>e.canAddToGroup(r)),see=(e,t)=>[...Cu(e,t),...XE(e,t)],aee=(e,t)=>{const n=Et(e).map(o=>o.id);let r=null;const i=Go(e);return t.forEach(o=>{const s=!n.includes(o.id)&&!i||i;if(o.groupId&&s){r||(r=Tn());const a=YE(e,o),l=Pn(e,a,!1),c=Ua(e,l,{stroke:ns,strokeWidth:ti,strokeLineDash:[5]}),u=es(a);u&&ta(c,q.getCenterPoint(l),u),r.append(c)}}),r},lee=e=>({id:fr(),type:"group"}),cee=e=>e.every(t=>!t.groupId),b3=e=>e.every(t=>t.groupId&&t.groupId===e[0].groupId),uee=(e,t)=>{const r=see(e,t).filter(i=>e.canAddToGroup(i));return r.length>1?cee(r)||b3(r):!1},dee=(e,t,n)=>{const r=Cu(e,t,n);return Et(e).length>0&&r.length>0},x3=(e,t)=>{const n=Su(e,t,!0);let r=null;if(n!=null&&n.length){for(let i=0;i<(n==null?void 0:n.length);i++)if(!o1(e,n[i])){r=n[i];break}}return r},fee=(e,t,n)=>{const r=[...t];cw(e,r),r.pop(),oy(e,r.map(i=>({element:i,newPath:n})))},hee=e=>{const t=e.getDeletedFragment([]);e.deleteFragment(t)},Vje=(e,t,n)=>{const r=Et(e),i=Pn(e,r,!1),o=e.buildFragment(null,i,t);o&&YQ(n,o)},S3=(e,t,n)=>{const r=t!=null&&t.length?t:Et(e),i=Pn(e,r,!1),o=e.buildFragment(null,i,_d.duplicate,r),s=o&&JSON.stringify(o),a=s&&JSON.parse(s);a&&e.insertFragment({...a,text:void 0},n||[i.x+i.width/2,i.y+i.height/2],_d.duplicate)},ac=2,Gje=24;function C3(e,t){return Zh(e,{match:r=>e.isAlign(r)&&!t.some(i=>i.id===r.id),recursion:()=>!0,isReverse:!1}).map(r=>{const i=e.getRectangle(r);return ly(i,r.angle||0)})}function pee(e,t){return t?[[e[0],e[1]-4],[e[0],e[1]+4]]:[[e[0]-4,e[1]],[e[0]+4,e[1]]]}function Wm(e,t,n){let r=ac;return e.forEach(i=>{const o=mee(t,i,n);Math.abs(o)<Math.abs(r)&&(r=o)}),r}const mee=(e,t,n)=>{const i=Id(t,n).map(a=>a-e),o=i.map(a=>Math.abs(a)),s=o.indexOf(Math.min(...o));return i[s]},Id=(e,t)=>{const n=t?"x":"y",r=t?"width":"height";return[e[n],e[n]+e[r]/2,e[n]+e[r]]};function If(e,t){let n=1/0,r=e[0];return e.forEach(i=>{const o=Math.sqrt(Math.pow(t.x-i.x,2)+Math.pow(t.y-i.y,2));o<n&&(n=o,r=i)}),r}const Af=(e,t,n)=>Id(t,n).includes(e);function E3(e,t,n,r=!0,i=!0,o=!1){let s=[];const a=Id(t,!0),l=Id(t,!1),c=[{axis:a[0],isHorizontal:!0,pointRectangles:[]},{axis:a[1],isHorizontal:!0,pointRectangles:[]},{axis:a[2],isHorizontal:!0,pointRectangles:[]},{axis:l[0],isHorizontal:!1,pointRectangles:[]},{axis:l[1],isHorizontal:!1,pointRectangles:[]},{axis:l[2],isHorizontal:!1,pointRectangles:[]}];for(let d=0;d<n.length;d++){const f=n[d];Af(c[0].axis,f,c[0].isHorizontal)&&c[0].pointRectangles.push(f),Af(c[1].axis,f,c[1].isHorizontal)&&c[1].pointRectangles.push(f),Af(c[2].axis,f,c[2].isHorizontal)&&c[2].pointRectangles.push(f),Af(c[3].axis,f,c[3].isHorizontal)&&c[3].pointRectangles.push(f),Af(c[4].axis,f,c[4].isHorizontal)&&c[4].pointRectangles.push(f),Af(c[5].axis,f,c[5].isHorizontal)&&c[5].pointRectangles.push(f)}const u=(d,f,p)=>{const y=q.inflate(q.getBoundingRectangle([t,f]),Gje);if(p){const v=[d,y.y],w=[d,y.y+y.height];s.push([v,w])}else{const v=[y.x,d],w=[y.x+y.width,d];s.push([v,w])}};if(r&&c[0].pointRectangles.length){const d=c[0].pointRectangles.length===1?c[0].pointRectangles[0]:If(c[0].pointRectangles,t);u(c[0].axis,d,c[0].isHorizontal)}if(r&&o&&c[1].pointRectangles.length){const d=c[1].pointRectangles.length===1?c[1].pointRectangles[0]:If(c[1].pointRectangles,t);u(c[1].axis,d,c[1].isHorizontal)}if(r&&c[2].pointRectangles.length){const d=c[2].pointRectangles.length===1?c[2].pointRectangles[0]:If(c[2].pointRectangles,t);u(c[2].axis,d,c[2].isHorizontal)}if(i&&c[3].pointRectangles.length){const d=c[3].pointRectangles.length===1?c[3].pointRectangles[0]:If(c[3].pointRectangles,t);u(c[3].axis,d,c[3].isHorizontal)}if(i&&o&&c[4].pointRectangles.length){const d=c[4].pointRectangles.length===1?c[4].pointRectangles[0]:If(c[4].pointRectangles,t);u(c[4].axis,d,c[4].isHorizontal)}if(i&&c[5].pointRectangles.length){const d=c[5].pointRectangles.length===1?c[5].pointRectangles[0]:If(c[5].pointRectangles,t);u(c[5].axis,d,c[5].isHorizontal)}return gee(e,s)}function gee(e,t){const n=Tn();return t.forEach(r=>{if(!r.length)return;const i=ne.getRoughSVG(e).line(r[0][0],r[0][1],r[1][0],r[1][1],{stroke:ns,strokeWidth:1,strokeLineDash:[4,4]});n.appendChild(i)}),n}function _3(e,t){const n=Tn();return t.forEach(r=>{if(!r.length)return;let i=r[0][1]===r[1][1];const o=ne.getRoughSVG(e).line(r[0][0],r[0][1],r[1][0],r[1][1],{stroke:ns,strokeWidth:1});n.appendChild(o),r.forEach(s=>{const a=pee(s,i),l=ne.getRoughSVG(e).line(a[0][0],a[0][1],a[1][0],a[1][1],{stroke:ns,strokeWidth:1});n.appendChild(l)})}),n}const I3=(e,t)=>{const n=dw(e,Et(e));let r=yee(e,n);t==="up"&&(r=r.reverse());let i=[];return r.forEach((o,s)=>{const a=o[0],l=o[o.length-1],c=t==="down"?a:l,u=Kje(e,c,t);u===-1||c===u||(t==="down"&&(o=o.reverse()),i.push(...o.map(d=>({element:e.children[d],newPath:[u]}))))}),i},A3=(e,t)=>{const n=dw(e,Et(e));let r=yee(e,n),i=[];return t==="down"&&(r=r.reverse()),r.forEach(o=>{const s=o[0],a=o[o.length-1],l=t==="down"?s:a,c=e.children[l],u=x3(e,c);let d=t==="down"?0:e.children.length-1;if(u){const f=cw(e,ua(e,u,!0,!0));d=t==="down"?e.children.indexOf(f[0]):e.children.indexOf(f[f.length-1])}t==="down"&&(o=o.reverse()),i.push(...o.map(f=>({element:e.children[f],newPath:[d]})))}),i},yee=(e,t)=>{let n=0;return t.reduce((r,i,o)=>{if(o>0){const s=e.children[i],a=e.children[t[o-1]],l=i-1===t[o-1]?!0:e.children.every((u,d)=>d>t[o-1]&&d<=i-1?rs.isGroup(u):!0);let c=!1;if(a!=null&&a.groupId||s!=null&&s.groupId&&(a==null?void 0:a.groupId)!==(s==null?void 0:s.groupId)){let u=!1,d=!1;if(a.groupId){const f=VS(e,a);u=!o1(e,f)}if(s.groupId){const f=VS(e,s);d=!o1(e,f)}c=u||d}(!l||c)&&(n=++n)}return(r[n]||(r[n]=[])).push(i),r},[])},Kje=(e,t,n)=>{if(t===0&&n==="down"||t===e.children.length-1&&n==="up")return-1;const r=d=>!(d.isDeleted||rs.isGroup(d)),i=n==="down"?QJ(e.children,d=>r(d),Math.max(0,t-1)):eQ(e.children,d=>r(d),t+1),o=e.children[i];if(!o)return-1;const s=[...e.children],a=s[t],l=x3(e,a),c=Su(e,o,!0)||[];if(l&&(a==null?void 0:a.groupId)!==(o==null?void 0:o.groupId)&&!c.find(d=>d.id===l.id))return-1;if(!o.groupId)return i;let u;if(l?u=c[c.indexOf(l)-1]:u=c[c.length-1],u){let d=ua(e,u,!0,!1);if(d.length)return d.sort((f,p)=>{const y=e.children.findIndex(w=>w.id===f.id),v=e.children.findIndex(w=>w.id===p.id);return y-v}),n==="down"?s.indexOf(d[0]):s.indexOf(d[d.length-1])}return i},P3=e=>vee(e)||wee(e),vee=e=>e.pointerType==="pen",wee=e=>e.pointerType==="touch",qje=(e,t)=>{const n=Cu(e,t),r=ZE(e),i=[...n,...r],o=lee();if(uee(e)){i.forEach(u=>{const d=ne.findPath(e,u);ih.setNode(e,{groupId:o.id},d)});const s=Et(e),a=jQ(e,s),l=dw(e,i);if(tQ(l)||fee(e,s,[a-1]),b3(i)){const u=r[0].groupId;ih.insertNode(e,{...o,groupId:u},[e.children.length])}else ih.insertNode(e,o,[e.children.length])}},Yje=(e,t)=>{const n=Cu(e,t);dee(e)&&(n.forEach(r=>{Zh(e,{match:o=>o.groupId===r.id,recursion:()=>!1}).forEach(o=>{const s=ne.findPath(e,o);ih.setNode(e,{groupId:r.groupId||void 0},s)})}),n.map(r=>{const i=ne.findPath(e,r),o=e.pathRef(i);return()=>{o.current&&ih.removeNode(e,o.current),o.unref()}}).forEach(r=>{r()}))},Xje={addGroup:qje,removeGroup:Yje};function bee(e,t){const n={type:"set_selection",properties:e.selection,newProperties:t};e.apply(n)}const Zje={setSelection:bee,addSelectionWithTemporaryElements:xee};function xee(e,t){const n=setTimeout(()=>{bee(e,{anchor:[0,0],focus:[0,0]})},0);let r=QQ(e);if(r){clearTimeout(r.timeoutId);const i=r.elements;r.elements.push(...t.filter(o=>!i.includes(o))),r.timeoutId=n}else ow.set(e,{timeoutId:n,elements:t})}const Jje=e=>{const t=A3(e,"up");oy(e,t)},Qje=e=>{const t=A3(e,"down");oy(e,t)},eLe=e=>{const t=I3(e,"up");oy(e,t)},tLe=e=>{const t=I3(e,"down");oy(e,t)},nLe={moveUp:eLe,moveDown:tLe,moveToTop:Jje,moveToBottom:Qje},rLe=(e,t)=>{t.map(n=>{const r=ne.findPath(e,n),i=e.pathRef(r);return()=>{i.current&&RQ(e,i.current),i.unref(),uw(e,n,!0)}}).forEach(n=>{n()})},ay={removeElements:rLe},Qe={...oje,...yje,...Zje,...ih,...Xje,...nLe},Di=(e,t,n)=>(n||(n=0),Array.isArray(e)&&typeof e[0]=="number"?bh(e[0],e[1],t[0],t[1],n):e.map(r=>bh(r[0],r[1],t[0],t[1],n||0))),es=e=>{var n;let t=((n=e[0])==null?void 0:n.angle)||0;return e.forEach(r=>{r.angle!==t&&!$S((r.angle||0)%(Math.PI/2)-t%(Math.PI/2),0)&&(t=0)}),t},See=e=>{if(!e.length)return!1;const t=e[0].angle;return t===void 0?!1:!e.some(n=>n.angle!==t)},Cee=(e,t)=>{let n=[];for(let a=0;a<e.length;a++){const l=e[a],c=Di(l,[0,0],-t);n.push(q.getRectangleByPoints(c))}const r=q.getBoundingRectangle(n),i=q.getCornerPoints(r),o=Di(i,[0,0],t),s=q.getCenterPoint(q.getRectangleByPoints(o));return q.getRectangleByPoints(Di(o,s,-t))},Eee=(e,t,n)=>{const r=q.getCenterPoint(e),[i]=Di([r],t,n),o=i[0]-r[0],s=i[1]-r[1];return{offsetX:o,offsetY:s}},KS=(e,t,n)=>{const{offsetX:r,offsetY:i}=Eee(q.getRectangleByPoints(e),t,n);return e.map(o=>[o[0]+r,o[1]+i])},Al=e=>k3(e.angle),k3=e=>e&&e!==0,Pl=(e,t)=>{if(Al(t)){let n=q.getRectangleByPoints(t.points);const r=q.getCenterPoint(n);return Di(e,r,t.angle)}else return null},_ee=(e,t)=>{if(k3(t)){let n=q.getRectangleByPoints(e);const r=q.getCenterPoint(n);return Di(e,r,t)}else return null},yc=(e,t,n,r=!1)=>{if(Al(n)){let i=q.getRectangleByPoints(n.points);const o=r?_o(e,i):i,s=q.getCenterPoint(o);return Di(t,s,n.angle?-n.angle:0)}else return null},ly=(e,t)=>{if(t){const n=q.getCornerPoints(e),r=q.getCenterPoint(e);return q.getRectangleByPoints(Di(n,r,t))}return e},Iee=e=>{const t=Math.abs(e)%Math.PI;return t>=1/4*Math.PI&&t<=3/4*Math.PI};function qS(e){return e/180*Math.PI}function Aee(e,t,n){const r=Pn(e,t,!1),i=q.getCenterPoint(r);t.forEach(o=>{const s=o.angle,a=KS(o.points,i,Pg(n)),l=ne.findPath(e,o);Qe.setNode(e,{points:a,angle:Pg((s||0)+n)},l)})}const Pg=e=>e<0?e+2*Math.PI:e>=2*Math.PI?e-2*Math.PI:e,Pee=(e,t,n)=>{const r=5*Math.PI/2+Math.atan2(e[1]-n[1],e[0]-n[0]),i=5*Math.PI/2+Math.atan2(t[1]-n[1],t[0]-n[0]);return Pg(i-r)},kee=e=>e==null?void 0:e.angle,ta=(e,t,n)=>{if(n===0){e.removeAttribute("transform");return}var r=t[0],i=t[1];let o=Math.cos(n),s=Math.sin(n),l="matrix("+[o,s,-s,o,r*(1-o)+i*s,i*(1-o)-r*s].join(",")+")";e.setAttribute("transform",`${l}`)};function Pn(e,t,n){const r=[],i=o=>{const s=e.getRectangle(o);if(s){const a=q.getCornerPoints(s),l=Pl(a,o)||a;r.push(l)}else console.error("can not get rectangle of element:",o)};if(t.forEach(o=>{n?co(o,s=>i(s),s=>e.isRecursion(s)):i(o)}),r.length>0)if(See(t)){const o=es(t);return Cee(r,o)}else{const o=r.reduce((s,a)=>s.concat(a),[]);return q.getRectangleByPoints(o)}else return{x:0,y:0,width:0,height:0}}function Zs(e,t,n){const r=!n&&hv(e).get(t);return r||(n||(n=Zh(e,{match:o=>!0,recursion:o=>!0})),n.find(o=>o.id===t))}function hv(e){const t=HJ.get(e);if(!t)throw new Error("can not resolve element map");return t}function Zh(e,t){let n=[];const r=t.isReverse??!0;return co(e,i=>{!ne.isBoard(i)&&t.match(i)&&n.push(i)},i=>ne.isBoard(i)?!0:zd(e)(i)&&t.recursion(i),r),n}var Rr;(function(e){e.default="default",e.colorful="colorful",e.soft="soft",e.retro="retro",e.dark="dark",e.starry="starry"})(Rr||(Rr={}));const uo="#333333",T3={mode:Rr.default,boardBackground:"#ffffff",textColor:uo},D3={mode:Rr.colorful,boardBackground:"#ffffff",textColor:uo},M3={mode:Rr.soft,boardBackground:"#f5f5f5",textColor:uo},O3={mode:Rr.retro,boardBackground:"#f9f8ed",textColor:uo},R3={mode:Rr.dark,boardBackground:"#141414",textColor:"#FFFFFF"},N3={mode:Rr.starry,boardBackground:"#0d2537",textColor:"#FFFFFF"},Tee=[T3,D3,M3,O3,R3,N3],ne={isBoard(e){const t=ED.get(e);if(t!==void 0)return t;const n=typeof e.onChange=="function"&&typeof e.apply=="function";return ED.set(e,n),n},isAlive(e){return!!YJ.get(e)},findPath(e,t){const n=[];let r=t;for(;;){const i=gd.get(r);if(i==null){if(ne.isBoard(r))return n;break}const o=rh.get(r);if(o==null)break;n.unshift(o),r=i}throw new Error(`Unable to find the path for Plait node: ${JSON.stringify(t)}`)},getHost(e){return KJ.get(e)},getElementLowerHost(e){var t;return(t=Yu.get(e))==null?void 0:t.lowerHost},getElementHost(e){var t;return(t=Yu.get(e))==null?void 0:t.host},getElementUpperHost(e){var t;return(t=Yu.get(e))==null?void 0:t.upperHost},getElementTopHost(e){var t;return(t=Yu.get(e))==null?void 0:t.topHost},getActiveHost(e){var t;return(t=Yu.get(e))==null?void 0:t.activeHost},getRoughSVG(e){return GJ.get(e)},getBoardContainer(e){var t;return(t=Yu.get(e))==null?void 0:t.container},getBoardContext(e){return qJ.get(e)},getRectangle(e){return Pn(e,e.children,!0)},getViewportContainer(e){var t;return(t=Yu.get(e))==null?void 0:t.viewportContainer},isFocus(e){return!!e.selection},isReadonly(e){return e.options.readonly},hasBeenTextEditing(e){return!!FS.get(e)},getPointer(e){return e.pointer},isPointer(e,t){return e.pointer===t},isInPointer(e,t){const n=e.pointer;return t.includes(n)},getMovingPointInBoard(e){return XJ.get(e)},isMovingPointInBoard(e){const t=ZJ.get(e),n=ne.getBoardContainer(e).getBoundingClientRect();return!!(t&&ry(t[0],t[1],n)===0)},getThemeColors(e){return e.options.themeColors||Tee}};var Ir;(function(e){e.hand="hand",e.selection="selection"})(Ir||(Ir={}));const Dee=e=>e.type==="set_viewport",Mee=e=>e.type==="set_selection",Oee=e=>e.type==="set_theme",Ree=e=>{switch(e.type){case"insert_node":return{...e,type:"remove_node"};case"remove_node":return{...e,type:"insert_node"};case"move_node":{const{newPath:t,path:n}=e;if(pn.equals(t,n))return e;const r=pn.transform(n,e),i=pn.transform(pn.next(n),e);return{...e,path:r,newPath:i}}case"set_node":{const{properties:t,newProperties:n}=e;return{...e,properties:n,newProperties:t}}case"set_selection":{const{properties:t,newProperties:n}=e;return t==null?{...e,properties:n,newProperties:null}:n==null?{...e,properties:null,newProperties:t}:{...e,properties:n,newProperties:t}}case"set_viewport":{const{properties:t,newProperties:n}=e;return t==null?{...e,properties:n,newProperties:n}:n==null?{...e,properties:t,newProperties:t}:{...e,properties:n,newProperties:t}}case"set_theme":{const{properties:t,newProperties:n}=e;return{...e,properties:n,newProperties:t}}}},j3={isSetViewportOperation:Dee,isSetSelectionOperation:Mee,isSetThemeOperation:Oee,inverse:Ree},on={isEquals(e,t){return e&&t&&e[0]===t[0]&&e[1]===t[1]},isHorizontal(e,t,n=0){return e&&t&&on.isOverHorizontal([e,t],n)},isOverHorizontal(e,t=0){return e.every(n=>Math.abs(n[1]-e[0][1])<=t)},isVertical(e,t,n=0){return e&&t&&on.isOverVertical([e,t],n)},isOverVertical(e,t=0){return e.every(n=>Math.abs(n[0]-e[0][0])<=t)},isAlign(e,t=0){return on.isOverHorizontal(e,t)||on.isOverVertical(e,t)},getOffsetX(e,t){return t[0]-e[0]},getOffsetY(e,t){return t[1]-e[1]}},R2=new WeakMap,Qi=new WeakMap,K0=new WeakMap;var In;(function(e){e.left="left",e.top="top",e.right="right",e.bottom="bottom"})(In||(In={}));const Nee=e=>e===In.left||e===In.right,rs={isGroup:e=>e.type==="group"};/**
|
|
1733
1733
|
* @license
|
|
1734
1734
|
* Copyright Google LLC All Rights Reserved.
|
|
1735
1735
|
*
|
|
@@ -2584,11 +2584,11 @@ ${P}`))}if(C&&p.length>0&&!Exe(E)){const P=await cY(p,x);E=dY(E,P)}let _=0,I="";
|
|
|
2584
2584
|
`,r.length>0&&(i+=`tags: [${r.map(a=>`"${a}"`).join(", ")}]
|
|
2585
2585
|
`),i+=`---
|
|
2586
2586
|
|
|
2587
|
-
`;const o=i+t.content;return{filename:`${t.title.replace(/[/\\?%*:|"<>]/g,"_")||"untitled"}.md`,content:o}}async function Net(e,t,n){let r=(n==null?void 0:n.replace(/\.md$/i,""))||"导入的笔记",i=e;const o=[],s=e.match(/^---\n([\s\S]*?)\n---\n*([\s\S]*)$/);if(s){const u=s[1];i=s[2];const d=u.match(/^title:\s*"?([^"\n]+)"?$/m);d&&(r=d[1].trim());const f=u.match(/^tags:\s*\[([^\]]*)\]$/m);if(f){const y=f[1].match(/"([^"]+)"/g);if(y)for(const v of y)o.push(v.replace(/"/g,""))}}const a=await my(t),l=a.filter(u=>u.title===r);if(l.length>0){for(const f of l){const p=await vc(f.id);if(p&&p.content===i)return null}let u=1,d=`${r} (${u})`;for(;a.some(f=>f.title===d);)u++,d=`${r} (${u})`;r=d}const c=await Wd(r,t,i);for(const u of o){const d=await bw(u);await gy(c.id,d.id)}return c}class jet{async getLocalData(){return await Oet()}merge(t,n){fe("Merging knowledge base data",{localDirs:t.directories.length,remoteDirs:n.directories.length,localNotes:t.notes.length,remoteNotes:n.notes.length});const r=new Map,i=new Map,o=new Map,s=f=>{if(r.has(f.id)){const p=r.get(f.id);f.updatedAt>p.updatedAt&&(r.set(f.id,f),p.name!==f.name&&i.set(f.name,f.id));return}if(i.has(f.name)){const p=i.get(f.name),y=r.get(p);o.set(f.id,p);let v={...y};f.updatedAt>y.updatedAt&&(v={...f,id:p}),(f.isDefault||y.isDefault)&&(v.isDefault=!0),r.set(p,v);return}r.set(f.id,f),i.set(f.name,f.id)};n.directories.forEach(s),t.directories.forEach(s);const a=new Map;n.tags.forEach(f=>a.set(f.id,f)),t.tags.forEach(f=>{a.get(f.id),a.set(f.id,f)});const l=new Map,c=f=>{let p=f.directoryId;o.has(p)&&(p=o.get(p));const y={...f,directoryId:p},v=l.get(y.id);(!v||y.updatedAt>v.updatedAt)&&l.set(y.id,y)};n.notes.forEach(c),t.notes.forEach(c);const u=new Map;n.noteTags.forEach(f=>u.set(f.id,f)),t.noteTags.forEach(f=>u.set(f.id,f));const d=new Map;return n.images&&n.images.forEach(f=>d.set(f.id,f)),t.images&&t.images.forEach(f=>{d.set(f.id,f)}),{version:2,exportedAt:Date.now(),directories:Array.from(r.values()),notes:Array.from(l.values()),tags:Array.from(a.values()),noteTags:Array.from(u.values()),images:Array.from(d.values())}}async apply(t){const{directoriesStore:n,notesStore:r,noteContentsStore:i,tagsStore:o,noteTagsStore:s,noteImagesStore:a}=yw();Tr("Applying knowledge base sync data",{dirs:t.directories.length,notes:t.notes.length});for(const l of t.directories)await n.setItem(l.id,l);for(const l of t.tags)await o.setItem(l.id,l);for(const l of t.notes){const{content:c,...u}=l;await r.setItem(l.id,u),c!==void 0&&await i.setItem(l.id,{id:l.id,noteId:l.id,content:c})}for(const l of t.noteTags)await s.setItem(l.id,l);if(t.images&&a)for(const l of t.images)await a.setItem(l.id,l)}}const Bf=new jet;function bV(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(36)}function Let(){let e=localStorage.getItem(bd);return e||(e=`${Date.now().toString(36)}-${Math.random().toString(36).substring(2,9)}`,localStorage.setItem(bd,e)),e}function Bet(){const e=navigator.userAgent;return/iPhone|iPad|iPod/.test(e)?"iOS Device":/Android/.test(e)?"Android Device":/Macintosh|Mac OS X/.test(e)?"Mac":/Windows/.test(e)?"Windows PC":/Linux/.test(e)?"Linux":navigator.platform||"Unknown"}class Fet{async collectSyncData(){const[t,n,r]=await Promise.all([Bn.loadAllFolders(),Bn.loadAllBoards(),Bn.loadState()]);await w_();const i=Lne(),o=n4(),s=r4(),l=(await Ks.getAllTasks()).filter(C=>C.status===un.COMPLETED&&(C.type===Qt.IMAGE||C.type===Qt.VIDEO)),c=await Bf.getLocalData(),u={},d=new Map;let f=0;for(const C of n){const x=JSON.stringify(C.elements);u[C.id]={name:C.name,updatedAt:C.updatedAt,checksum:bV(x)},d.set(C.id,C),f++,f%5===0&&await Wo()}const p={folders:t,boardMetadata:n.map(C=>this.extractBoardMetadata(C)),currentBoardId:(r==null?void 0:r.currentBoardId)||null,expandedFolders:(r==null?void 0:r.expandedFolderIds)||[]},y=Let(),v=Date.now();return{manifest:{version:net,appVersion:Ove.app,createdAt:v,updatedAt:v,deviceId:y,devices:{[y]:{name:Bet(),lastSyncTime:v}},boards:u},workspace:p,boards:d,prompts:{promptHistory:i,videoPromptHistory:o,imagePromptHistory:s},tasks:{completedTasks:l},knowledgeBase:c}}async collectSyncDataPaged(){const t=await this.collectSyncData(),{index:n,pages:r}=_le(t.tasks.completedTasks),o=(await Ile.getAllWorkflows()).filter(l=>l.status==="completed"||l.status==="failed"||l.status==="cancelled"),{index:s,pages:a}=Ple(o);return fe("DataSerializer: Collected paged sync data",{boards:t.boards.size,taskPages:r.length,taskItems:n.items.length,workflowPages:a.length,workflowItems:s.items.length,knowledgeBase:t.knowledgeBase?{notes:t.knowledgeBase.notes.length,directories:t.knowledgeBase.directories.length}:"NULL"}),{manifest:t.manifest,workspace:t.workspace,boards:t.boards,prompts:t.prompts,taskIndex:n,taskPages:r,workflowIndex:s,workflowPages:a,knowledgeBase:t.knowledgeBase}}extractBoardMetadata(t){return{id:t.id,name:t.name,folderId:t.folderId,order:t.order,viewport:t.viewport,theme:t.theme,createdAt:t.createdAt,updatedAt:t.updatedAt}}serializeToGistFiles(t){const n={};n[_t.MANIFEST]=JSON.stringify(t.manifest,null,2),n[_t.WORKSPACE]=JSON.stringify(t.workspace,null,2);for(const[r,i]of t.boards)n[_t.boardFile(r)]=JSON.stringify(i,null,2);return n[_t.PROMPTS]=JSON.stringify(t.prompts,null,2),t.knowledgeBase&&(n[_t.KNOWLEDGE_BASE]=JSON.stringify(t.knowledgeBase,null,2)),n}async serializeToGistFilesEncrypted(t,n,r){const i={},o=JSON.stringify(t.manifest);i[_t.MANIFEST]=await Nn.encrypt(o,n,r);const s=JSON.stringify(t.workspace);i[_t.WORKSPACE]=await Nn.encrypt(s,n,r);let a=0;for(const[c,u]of t.boards){const d=JSON.stringify(u);i[_t.boardFile(c)]=await Nn.encrypt(d,n,r),a++,a%3===0&&await Wo()}const l=JSON.stringify(t.prompts);if(i[_t.PROMPTS]=await Nn.encrypt(l,n,r),t.knowledgeBase){const c=JSON.stringify(t.knowledgeBase);i[_t.KNOWLEDGE_BASE]=await Nn.encrypt(c,n,r)}return i}async serializeToGistFilesPagedEncrypted(t,n,r){const i={},o=JSON.stringify(t.manifest);i[_t.MANIFEST]=await Nn.encrypt(o,n,r);const s=JSON.stringify(t.workspace);i[_t.WORKSPACE]=await Nn.encrypt(s,n,r);let a=0;for(const[p,y]of t.boards){const v=JSON.stringify(y);i[_t.boardFile(p)]=await Nn.encrypt(v,n,r),a++,a%3===0&&await Wo()}const l=JSON.stringify(t.prompts);if(i[_t.PROMPTS]=await Nn.encrypt(l,n,r),t.knowledgeBase){const p=JSON.stringify(t.knowledgeBase);i[_t.KNOWLEDGE_BASE]=await Nn.encrypt(p,n,r)}const c=JSON.stringify(t.taskIndex);i[li.TASK_INDEX]=await Nn.encrypt(c,n,r);let u=0;for(const p of t.taskPages){const y=JSON.stringify(p),v=li.taskPageFile(p.pageId);i[v]=await Nn.encrypt(y,n,r),u++,u%3===0&&await Wo()}const d=JSON.stringify(t.workflowIndex);i[li.WORKFLOW_INDEX]=await Nn.encrypt(d,n,r);let f=0;for(const p of t.workflowPages){const y=JSON.stringify(p),v=li.workflowPageFile(p.pageId);i[v]=await Nn.encrypt(y,n,r),f++,f%3===0&&await Wo()}return fe("DataSerializer: Serialized paged files",{totalFiles:Object.keys(i).length,taskPages:t.taskPages.length,workflowPages:t.workflowPages.length}),i}deserializeFromGistFiles(t){var r;const n={manifest:null,workspace:null,boards:new Map,prompts:null,tasks:null,knowledgeBase:null};if(t[_t.MANIFEST])try{n.manifest=JSON.parse(t[_t.MANIFEST])}catch(i){Pt("DataSerializer: Failed to parse manifest:",{error:String(i)})}if(t[_t.WORKSPACE])try{n.workspace=JSON.parse(t[_t.WORKSPACE])}catch(i){Pt("DataSerializer: Failed to parse workspace:",{error:String(i)})}for(const[i,o]of Object.entries(t))if(i.startsWith("board_")&&i.endsWith(".json"))try{const s=JSON.parse(o);fe(`DataSerializer: Parsed board ${i}:`,{id:s.id,name:s.name,elements:((r=s.elements)==null?void 0:r.length)||0,hasElements:!!s.elements,viewport:s.viewport}),n.boards.set(s.id,s)}catch(s){Pt(`DataSerializer: Failed to parse board ${i}:`,{error:String(s)})}if(t[_t.PROMPTS])try{n.prompts=JSON.parse(t[_t.PROMPTS])}catch(i){Pt("DataSerializer: Failed to parse prompts:",{error:String(i)})}if(t[_t.KNOWLEDGE_BASE])try{n.knowledgeBase=JSON.parse(t[_t.KNOWLEDGE_BASE])}catch(i){Pt("DataSerializer: Failed to parse knowledge base:",{error:String(i)})}return n}async deserializeFromGistFilesWithDecryption(t,n,r){var s,a,l,c,u,d,f,p,y,v,w,C,x,E,_,I,D,P,k,R,T;fe("DataSerializer: ========== deserializeFromGistFilesWithDecryption START =========="),fe("DataSerializer: Input files:",{fileCount:Object.keys(t).length,fileNames:Object.keys(t),fileSizes:Object.fromEntries(Object.entries(t).map(([M,F])=>[M,(F==null?void 0:F.length)||0]))}),fe("DataSerializer: gistId:",{id:(n==null?void 0:n.substring(0,8))+"..."}),fe("DataSerializer: customPassword:",{status:r?"***SET***":"NOT SET"});const i={manifest:null,workspace:null,boards:new Map,prompts:null,tasks:null,knowledgeBase:null};if(t[_t.MANIFEST]){fe("DataSerializer: Parsing manifest",{encrypted:cd(t[_t.MANIFEST])});try{const M=await Nn.decryptOrPassthrough(t[_t.MANIFEST],n,r);i.manifest=JSON.parse(M),fe("DataSerializer: Manifest parsed successfully:",{version:(s=i.manifest)==null?void 0:s.version,boardsCount:(a=i.manifest)!=null&&a.boards?Object.keys(i.manifest.boards).length:0,boardIds:(l=i.manifest)!=null&&l.boards?Object.keys(i.manifest.boards):[]})}catch(M){if(M instanceof Error&&M.name==="DecryptionError")throw M;Pt("DataSerializer: Failed to parse manifest:",{error:String(M)})}}else Pt("DataSerializer: Manifest file NOT FOUND in input files!");if(fe("DataSerializer: Deserializing with customPassword",{enabled:!!r}),t[_t.WORKSPACE]){fe("DataSerializer: Parsing workspace",{encrypted:cd(t[_t.WORKSPACE])});try{const M=await Nn.decryptOrPassthrough(t[_t.WORKSPACE],n,r);fe("DataSerializer: Workspace decrypted content length",{length:M.length}),i.workspace=JSON.parse(M),fe("DataSerializer: Workspace parsed successfully:",{currentBoardId:(c=i.workspace)==null?void 0:c.currentBoardId,folders:((d=(u=i.workspace)==null?void 0:u.folders)==null?void 0:d.length)||0,boardMetadata:((p=(f=i.workspace)==null?void 0:f.boardMetadata)==null?void 0:p.length)||0,boardMetadataIds:((v=(y=i.workspace)==null?void 0:y.boardMetadata)==null?void 0:v.map(F=>F.id))||[]})}catch(M){if(M instanceof Error&&M.name==="DecryptionError")throw M;Pt("DataSerializer: Failed to parse workspace:",{error:String(M)})}}else Pt("DataSerializer: Workspace file NOT FOUND in input files!");fe("DataSerializer: Parsing boards...");let o=0;for(const[M,F]of Object.entries(t))if(M.startsWith("board_")&&M.endsWith(".json")){o++,fe("DataSerializer: Processing board file",{filename:M,length:(F==null?void 0:F.length)||0});try{const V=await Nn.decryptOrPassthrough(F,n,r);fe("DataSerializer: Board decrypted",{filename:M,length:V.length});const H=JSON.parse(V);fe(`DataSerializer: Parsed board ${M}:`,{id:H.id,name:H.name,elements:((w=H.elements)==null?void 0:w.length)||0,hasElements:!!H.elements,viewport:H.viewport}),i.boards.set(H.id,H)}catch(V){if(V instanceof Error&&V.name==="DecryptionError")throw V;Pt(`DataSerializer: Failed to parse board ${M}:`,{error:String(V)})}}if(fe("DataSerializer: Board files found",{found:o,parsed:i.boards.size}),t[_t.PROMPTS]){fe("DataSerializer: Parsing prompts",{encrypted:cd(t[_t.PROMPTS])});try{const M=await Nn.decryptOrPassthrough(t[_t.PROMPTS],n,r);i.prompts=JSON.parse(M),fe("DataSerializer: Prompts parsed successfully:",{promptHistory:((x=(C=i.prompts)==null?void 0:C.promptHistory)==null?void 0:x.length)||0,videoPromptHistory:((_=(E=i.prompts)==null?void 0:E.videoPromptHistory)==null?void 0:_.length)||0,imagePromptHistory:((D=(I=i.prompts)==null?void 0:I.imagePromptHistory)==null?void 0:D.length)||0})}catch(M){if(M instanceof Error&&M.name==="DecryptionError")throw M;Pt("DataSerializer: Failed to parse prompts:",{error:String(M)})}}else Pt("DataSerializer: Prompts file NOT FOUND in input files!");if(t[_t.KNOWLEDGE_BASE]){fe("DataSerializer: Parsing knowledge base",{encrypted:cd(t[_t.KNOWLEDGE_BASE])});try{const M=await Nn.decryptOrPassthrough(t[_t.KNOWLEDGE_BASE],n,r);i.knowledgeBase=JSON.parse(M),fe("DataSerializer: Knowledge base parsed successfully:",{directories:((k=(P=i.knowledgeBase)==null?void 0:P.directories)==null?void 0:k.length)||0,notes:((T=(R=i.knowledgeBase)==null?void 0:R.notes)==null?void 0:T.length)||0})}catch(M){if(M instanceof Error&&M.name==="DecryptionError")throw M;Pt("DataSerializer: Failed to parse knowledge base:",{error:String(M)})}}return fe("DataSerializer: ========== deserializeFromGistFilesWithDecryption END =========="),fe("DataSerializer: Final result:",{hasManifest:!!i.manifest,hasWorkspace:!!i.workspace,boardsCount:i.boards.size,boardIds:Array.from(i.boards.keys()),hasPrompts:!!i.prompts,hasTasks:!!i.tasks}),i}async deserializeFromGistFilesPagedWithDecryption(t,n,r){var o,s,a,l,c,u,d,f;fe("DataSerializer: ========== deserializeFromGistFilesPagedWithDecryption START ==========");const i={manifest:null,workspace:null,boards:new Map,prompts:null,taskIndex:null,taskPages:new Map,workflowIndex:null,workflowPages:new Map,knowledgeBase:null};if(t[_t.MANIFEST])try{const p=await Nn.decryptOrPassthrough(t[_t.MANIFEST],n,r);i.manifest=JSON.parse(p)}catch(p){if(p instanceof Error&&p.name==="DecryptionError")throw p;Pt("DataSerializer: Failed to parse manifest:",{error:String(p)})}if(t[_t.WORKSPACE])try{const p=await Nn.decryptOrPassthrough(t[_t.WORKSPACE],n,r);i.workspace=JSON.parse(p)}catch(p){if(p instanceof Error&&p.name==="DecryptionError")throw p;Pt("DataSerializer: Failed to parse workspace:",{error:String(p)})}for(const[p,y]of Object.entries(t))if(p.startsWith("board_")&&p.endsWith(".json"))try{const v=await Nn.decryptOrPassthrough(y,n,r),w=JSON.parse(v);i.boards.set(w.id,w)}catch(v){if(v instanceof Error&&v.name==="DecryptionError")throw v;Pt(`DataSerializer: Failed to parse board ${p}:`,{error:String(v)})}if(t[_t.PROMPTS])try{const p=await Nn.decryptOrPassthrough(t[_t.PROMPTS],n,r);i.prompts=JSON.parse(p)}catch(p){if(p instanceof Error&&p.name==="DecryptionError")throw p;Pt("DataSerializer: Failed to parse prompts:",{error:String(p)})}if(t[li.TASK_INDEX])try{const p=await Nn.decryptOrPassthrough(t[li.TASK_INDEX],n,r);i.taskIndex=JSON.parse(p),fe("DataSerializer: Parsed task index:",{items:((s=(o=i.taskIndex)==null?void 0:o.items)==null?void 0:s.length)||0,pages:((l=(a=i.taskIndex)==null?void 0:a.pages)==null?void 0:l.length)||0})}catch(p){if(p instanceof Error&&p.name==="DecryptionError")throw p;Pt("DataSerializer: Failed to parse task index:",{error:String(p)})}for(const[p,y]of Object.entries(t))if(li.isTaskPageFile(p))try{const v=await Nn.decryptOrPassthrough(y,n,r),w=JSON.parse(v);i.taskPages.set(w.pageId,w)}catch(v){if(v instanceof Error&&v.name==="DecryptionError")throw v;Pt(`DataSerializer: Failed to parse task page ${p}:`,{error:String(v)})}if(t[li.WORKFLOW_INDEX])try{const p=await Nn.decryptOrPassthrough(t[li.WORKFLOW_INDEX],n,r);i.workflowIndex=JSON.parse(p),fe("DataSerializer: Parsed workflow index:",{items:((u=(c=i.workflowIndex)==null?void 0:c.items)==null?void 0:u.length)||0,pages:((f=(d=i.workflowIndex)==null?void 0:d.pages)==null?void 0:f.length)||0})}catch(p){if(p instanceof Error&&p.name==="DecryptionError")throw p;Pt("DataSerializer: Failed to parse workflow index:",{error:String(p)})}for(const[p,y]of Object.entries(t))if(li.isWorkflowPageFile(p))try{const v=await Nn.decryptOrPassthrough(y,n,r),w=JSON.parse(v);i.workflowPages.set(w.pageId,w)}catch(v){if(v instanceof Error&&v.name==="DecryptionError")throw v;Pt(`DataSerializer: Failed to parse workflow page ${p}:`,{error:String(v)})}if(t[_t.KNOWLEDGE_BASE])try{const p=await Nn.decryptOrPassthrough(t[_t.KNOWLEDGE_BASE],n,r);i.knowledgeBase=JSON.parse(p)}catch(p){if(p instanceof Error&&p.name==="DecryptionError")throw p;Pt("DataSerializer: Failed to parse knowledge base:",{error:String(p)})}return fe("DataSerializer: ========== deserializeFromGistFilesPagedWithDecryption END =========="),fe("DataSerializer: Paged result:",{hasManifest:!!i.manifest,hasWorkspace:!!i.workspace,boardsCount:i.boards.size,hasPrompts:!!i.prompts,hasTaskIndex:!!i.taskIndex,taskPagesCount:i.taskPages.size,hasWorkflowIndex:!!i.workflowIndex,workflowPagesCount:i.workflowPages.size,hasKnowledgeBase:!!i.knowledgeBase}),i}async applySyncData(t){var f,p,y,v,w,C,x,E,_,I,D,P,k,R,T,M,F,V,H;fe("DataSerializer: ========== applySyncData START =========="),fe("DataSerializer: applySyncData called with:",{hasWorkspace:!!t.workspace,workspace:t.workspace?{currentBoardId:t.workspace.currentBoardId,folders:((f=t.workspace.folders)==null?void 0:f.length)||0,boardMetadata:((p=t.workspace.boardMetadata)==null?void 0:p.length)||0,boardMetadataIds:((y=t.workspace.boardMetadata)==null?void 0:y.map(j=>j.id))||[]}:"NULL",boardsCount:t.boards.size,boardIds:Array.from(t.boards.keys()),hasPrompts:!!t.prompts,prompts:t.prompts?{promptHistory:((v=t.prompts.promptHistory)==null?void 0:v.length)||0,videoPromptHistory:((w=t.prompts.videoPromptHistory)==null?void 0:w.length)||0,imagePromptHistory:((C=t.prompts.imagePromptHistory)==null?void 0:C.length)||0}:"NULL",hasTasks:!!t.tasks,tasks:t.tasks?{completedTasks:((x=t.tasks.completedTasks)==null?void 0:x.length)||0}:"NULL",hasKnowledgeBase:!!t.knowledgeBase,deletedBoardIds:((E=t.deletedBoardIds)==null?void 0:E.length)||0,deletedPromptIds:((_=t.deletedPromptIds)==null?void 0:_.length)||0,deletedTaskIds:((I=t.deletedTaskIds)==null?void 0:I.length)||0});let n=0,r=0,i=0,o=0,s=0,a=0,l=0;if(t.workspace){fe("DataSerializer: Applying folders:",{count:t.workspace.folders.length});for(const j of t.workspace.folders)await Bn.saveFolder(j)}fe("DataSerializer: Applying boards...");for(const[j,z]of t.boards){fe(`DataSerializer: Saving board: ${j} - ${z.name}, elements: ${((D=z.elements)==null?void 0:D.length)||0}`,{folderId:z.folderId,viewport:z.viewport,createdAt:z.createdAt,updatedAt:z.updatedAt}),await Bn.saveBoard(z);const N=await Bn.loadBoard(j);fe(`DataSerializer: Verified saved board: ${j}`,{found:!!N,elements:((P=N==null?void 0:N.elements)==null?void 0:P.length)||0}),n++}if(fe("DataSerializer: Boards applied:",{count:n}),t.deletedBoardIds&&t.deletedBoardIds.length>0){fe("DataSerializer: Deleting boards:",{ids:t.deletedBoardIds});for(const j of t.deletedBoardIds)try{await Bn.deleteBoard(j),s++,fe(`DataSerializer: Deleted board: ${j}`)}catch(z){Pt(`DataSerializer: Failed to delete board ${j}:`,{error:String(z)})}fe("DataSerializer: Boards deleted:",{count:s})}if(n>0){fe("DataSerializer: ========== RELOAD WORKSPACE START =========="),fe("DataSerializer: Calling workspaceService.reload()..."),await AG(),fe("DataSerializer: workspaceService.reload() completed");const j=yhe();fe("DataSerializer: Workspace reloaded, boards in memory:",{count:j.length,ids:j.map(z=>z.id),names:j.map(z=>z.name)}),fe("DataSerializer: Verifying all saved boards in storage...");for(const z of t.boards.keys()){const N=await Bn.loadBoard(z);fe(`DataSerializer: VERIFY board ${z}:`,{foundInStorage:!!N,name:(N==null?void 0:N.name)||"N/A",elements:((k=N==null?void 0:N.elements)==null?void 0:k.length)||0})}if((R=t.workspace)!=null&&R.currentBoardId){fe("DataSerializer: Setting currentBoardId from remote:",{id:t.workspace.currentBoardId});const z=ghe();fe("DataSerializer: Current state before update:",{state:z}),await Bn.saveState({...z,currentBoardId:t.workspace.currentBoardId}),fe("DataSerializer: Saved workspace state with currentBoardId");const N=await Bn.loadState();fe("DataSerializer: VERIFY state after save:",{currentBoardId:N.currentBoardId,match:N.currentBoardId===t.workspace.currentBoardId})}fe("DataSerializer: ========== RELOAD WORKSPACE END ==========")}if(t.prompts&&(t.prompts.promptHistory&&t.prompts.promptHistory.length>0&&(r+=v$e(t.prompts.promptHistory)),t.prompts.videoPromptHistory&&t.prompts.videoPromptHistory.length>0&&(r+=_$e(t.prompts.videoPromptHistory)),t.prompts.imagePromptHistory&&t.prompts.imagePromptHistory.length>0&&(r+=k$e(t.prompts.imagePromptHistory))),fe("DataSerializer: Applying tasks...",{hasTasks:!!t.tasks,completedTasksCount:((M=(T=t.tasks)==null?void 0:T.completedTasks)==null?void 0:M.length)||0}),t.tasks&&t.tasks.completedTasks&&t.tasks.completedTasks.length>0){const j=await Ks.getAllTasks(),z=new Map(j.map(B=>[B.id,B]));fe("DataSerializer: Local tasks:",{count:j.length,ids:Array.from(z.keys()).slice(0,5)});const N=[];for(const B of t.tasks.completedTasks){const O=z.get(B.id);O?B.updatedAt&&O.updatedAt&&B.updatedAt>O.updatedAt&&N.push(B):N.push(B)}if(fe("DataSerializer: Tasks to restore after merge:",{count:N.length,ids:N.slice(0,5).map(B=>B.id)}),N.length>0){const B=N.map(O=>{var $;return($=O.result)!=null&&$.url&&Zf(O.result.url)?{...O,result:{...O.result,needsMediaDownload:!0}}:O});fe("DataSerializer: Calling restoreTasks with tasks",{count:B.length});try{Mi.restoreTasks(B),i=B.length,fe("DataSerializer: Tasks restored:",{count:i})}catch(O){Pt("DataSerializer: Failed to restore tasks (SW may not be ready):",{error:String(O)}),i=0}}}else fe("DataSerializer: No tasks to apply");if(t.knowledgeBase){fe("DataSerializer: Applying knowledge base...");try{await Bf.apply(t.knowledgeBase),o=(((F=t.knowledgeBase.notes)==null?void 0:F.length)||0)+(((V=t.knowledgeBase.directories)==null?void 0:V.length)||0),fe("DataSerializer: Knowledge base applied successfully")}catch(j){Pt("DataSerializer: Failed to apply knowledge base:",{error:String(j)})}}const c=((H=t.workspace)==null?void 0:H.currentBoardId)||null;fe("DataSerializer: ========== applySyncData END =========="),fe("DataSerializer: applySyncData completed:",{boardsApplied:n,promptsApplied:r,tasksApplied:i,knowledgeBaseApplied:o,boardsDeleted:s,promptsDeleted:a,tasksDeleted:l,remoteCurrentBoardId:c});const u=await Bn.loadState();fe("DataSerializer: Final workspace state in storage:",{currentBoardId:u.currentBoardId,expected:c,match:u.currentBoardId===c});const d=await Bn.loadAllBoards();return fe("DataSerializer: Final boards in storage:",{count:d.length,ids:d.map(j=>j.id),names:d.map(j=>j.name)}),{boardsApplied:n,promptsApplied:r,tasksApplied:i,knowledgeBaseApplied:o,boardsDeleted:s,promptsDeleted:a,tasksDeleted:l,remoteCurrentBoardId:c}}calculateBoardChecksum(t){const n=JSON.stringify(t.elements);return bV(n)}mergeBoardElements(t,n){const r=t.elements||[],i=n.elements||[],o=new Map,s=new Map;for(const y of r)y.id&&o.set(y.id,y);for(const y of i)y.id&&s.set(y.id,y);const a=[],l=[];let c=0,u=0,d=0;const f=new Set;for(const y of r){if(!y.id){a.push(y);continue}f.add(y.id);const v=s.get(y.id);if(!v)a.push(y),c++;else{const w=JSON.stringify(y),C=JSON.stringify(v);w===C?a.push(y):(a.push(y),l.push({elementId:y.id,localElement:y,remoteElement:v}),d++)}}for(const y of i)!y.id||f.has(y.id)||(a.push(y),u++);return{mergedBoard:{...t,elements:a,updatedAt:Math.max(t.updatedAt,n.updatedAt)},hasConflicts:l.length>0,conflictingElements:l,addedFromLocal:c,addedFromRemote:u,updated:d}}compareBoardChanges(t,n,r){const i=[],o=[],s=[],a=[],l=new Set(t.keys()),c=new Set(Object.keys(n.boards));for(const[u,d]of t){const f=n.boards[u],p=this.calculateBoardChecksum(d);f?f.deletedAt?a.push(u):p!==f.checksum&&(r?d.updatedAt>r&&f.updatedAt>r?s.push(u):d.updatedAt>r?i.push(u):o.push(u):!d.elements||d.elements.length===0?(fe(`Sync: Initial sync: Local board ${u} is empty, preferring remote version.`),o.push(u)):d.updatedAt>f.updatedAt?i.push(u):o.push(u)):i.push(u)}for(const u of c)l.has(u)||n.boards[u].deletedAt||o.push(u);return{toUpload:i,toDownload:o,conflicts:s,toDeleteLocally:a}}detectDeletions(t,n){const r=[],i=[],o=[];if(!n)return{deletedBoards:r,deletedPrompts:i,deletedTasks:o};for(const[s,a]of Object.entries(n.boards))a.deletedAt||t.boards.has(s)||r.push({id:s,name:a.name});return fe("DataSerializer: detectDeletions result:",{deletedBoards:r.length,deletedPrompts:i.length,deletedTasks:o.length}),{deletedBoards:r,deletedPrompts:i,deletedTasks:o}}markBoardsAsDeleted(t,n,r){const i=Date.now(),o={...t};for(const s of n)o.boards[s.id]?o.boards[s.id]={...o.boards[s.id],deletedAt:i,deletedBy:r}:o.boards[s.id]={name:s.name,updatedAt:i,checksum:"",deletedAt:i,deletedBy:r};return o.updatedAt=i,o}unmarkBoardAsDeleted(t,n){const r={...t};if(r.boards[n]){const{deletedAt:i,deletedBy:o,...s}=r.boards[n];r.boards[n]=s}return r.updatedAt=Date.now(),r}getDeletedBoards(t){const n=[];for(const[r,i]of Object.entries(t.boards))i.deletedAt&&i.deletedBy&&n.push({id:r,name:i.name,deletedAt:i.deletedAt,deletedBy:i.deletedBy});return n.sort((r,i)=>i.deletedAt-r.deletedAt),n}}const Or=new Fet;function Tle(e){return iI(e)}function Dle(e){return e.startsWith("http://")||e.startsWith("https://")}function Mle(e,t,n){return e?t==="local"?n==="image"?"current_board_local_image":"current_board_local_video":n==="image"?"current_board_url_image":"current_board_url_video":t==="local"?n==="image"?"other_local_image":"other_local_video":n==="image"?"other_url_image":"other_url_video"}const xV={current_board_local_image:1,current_board_local_video:2,current_board_url_image:3,current_board_url_video:4,other_local_image:5,other_local_video:6,other_url_image:7,other_url_video:8};function Yk(e){return[...e].sort((t,n)=>xV[t.priority]-xV[n.priority])}function SV(e,t){const n=[],r=e.id===t;if(!e.elements||e.elements.length===0)return n;for(const i of e.elements){const o=i.url;if(!o||typeof o!="string"||o.startsWith("blob:"))continue;const s=Pe.isDrawElement(i)&&Pe.isImage(i),a=xJe(i);if(!s&&!a)continue;const l=a?"video":"image";let c,u;if(Tle(o))c="local";else if(Dle(o))c="external",u=o;else continue;const d=Mle(r,c,l),f=n.findIndex(p=>p.url===o);f>=0?(n[f].boardIds.includes(e.id)||n[f].boardIds.push(e.id),r&&!n[f].isCurrentBoard&&(n[f].isCurrentBoard=!0,n[f].priority=d)):n.push({url:o,type:l,source:c,originalUrl:u,boardIds:[e.id],isCurrentBoard:r,priority:d})}return n}class $et{async collectCurrentBoardMedia(t){const n=await Bn.loadBoard(t);if(!n)return this.createEmptyResult();const r=SV(n,t);await this.enrichMediaMetadata(r);const i=Yk(r.filter(o=>o.isCurrentBoard));return{items:Yk(r),currentBoardItems:i,otherItems:[],stats:this.calculateStats(r)}}async collectAllBoardsMedia(t){const n=await Bn.loadAllBoards(),r=[];for(const a of n){const l=SV(a,t);for(const c of l){const u=r.findIndex(d=>d.url===c.url);if(u>=0){for(const d of c.boardIds)r[u].boardIds.includes(d)||r[u].boardIds.push(d);c.isCurrentBoard&&!r[u].isCurrentBoard&&(r[u].isCurrentBoard=!0,r[u].priority=c.priority)}else r.push(c)}}await this.enrichMediaMetadata(r);const i=Yk(r),o=i.filter(a=>a.isCurrentBoard),s=i.filter(a=>!a.isCurrentBoard);return{items:i,currentBoardItems:o,otherItems:s,stats:this.calculateStats(r)}}async collectAssetLibraryMedia(){await Vs.initialize();const t=await Vs.getAllAssets(),n=[];for(const r of t){const i=r.type==="IMAGE"?"image":"video";n.push({url:r.url,type:i,source:"local",boardIds:[],isCurrentBoard:!1,priority:i==="image"?"other_local_image":"other_local_video",mimeType:r.mimeType,size:r.size})}return n}async collectTaskQueueMedia(){var i,o;const t=await Ks.getAllTasks(),n=[],r=t.filter(s=>{var a;return s.status===un.COMPLETED&&(s.type===Qt.IMAGE||s.type===Qt.VIDEO)&&((a=s.result)==null?void 0:a.url)});for(const s of r){const a=s.result.url,l=s.type===Qt.VIDEO?"video":"image";n.some(c=>c.url===a)||n.push({url:a,type:l,source:"local",boardIds:[],isCurrentBoard:!1,priority:l==="image"?"other_local_image":"other_local_video",mimeType:(i=s.result)==null?void 0:i.format,size:(o=s.result)==null?void 0:o.size})}return n}async collectMediaByUrls(t){const n=[];for(const r of t){if(r.startsWith("blob:"))continue;const i=this.guessMediaType(r);let o,s;if(Tle(r))o="local";else if(Dle(r))o="external",s=r;else continue;n.push({url:r,type:i,source:o,originalUrl:s,boardIds:[],isCurrentBoard:!1,priority:Mle(!1,o,i)})}return await this.enrichMediaMetadata(n),n}async enrichMediaMetadata(t){var n;for(const r of t)if(!(r.mimeType&&r.size))try{const i=await yn.getCacheInfo(r.url);i.isCached&&(r.size=i.size,r.mimeType=(n=i.metadata)==null?void 0:n.mimeType)}catch(i){Pt(`MediaCollector] Failed to get metadata for ${r.url}:`,i)}}guessMediaType(t){const n=t.toLowerCase();return[".mp4",".mov",".avi",".mkv",".webm",".m4v",".flv",".wmv"].some(i=>n.includes(i))||n.includes("/video/")||n.includes("#video")?"video":"image"}calculateStats(t){return{total:t.length,currentBoard:t.filter(n=>n.isCurrentBoard).length,localImages:t.filter(n=>n.source==="local"&&n.type==="image").length,localVideos:t.filter(n=>n.source==="local"&&n.type==="video").length,urlImages:t.filter(n=>n.source==="external"&&n.type==="image").length,urlVideos:t.filter(n=>n.source==="external"&&n.type==="video").length}}createEmptyResult(){return{items:[],currentBoardItems:[],otherItems:[],stats:{total:0,currentBoard:0,localImages:0,localVideos:0,urlImages:0,urlVideos:0}}}}const CV=new $et;async function Ole(e){return(await xn(()=>Promise.resolve().then(()=>_O),void 0,import.meta.url)).blobToBase64(e)}function Rle(e,t){const n=atob(e),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return new Blob([r],{type:t})}function K2(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(1)} MB`}const EV="github_media_sync_status";function zet(){return localStorage.getItem(bd)||"unknown"}class Uet{constructor(){this.statusCache={},this.syncingUrls=new Set,this.syncCompletedListeners=new Set,this.loadStatusCache()}addSyncCompletedListener(t){this.syncCompletedListeners.add(t)}removeSyncCompletedListener(t){this.syncCompletedListeners.delete(t)}notifySyncCompleted(t){t.succeeded>0&&this.syncCompletedListeners.forEach(n=>{try{n(t)}catch(r){vn("Sync completed callback error",r instanceof Error?r:new Error(String(r)))}})}async loadStatusCache(){const t=await er.get(EV);t&&(this.statusCache=t)}async saveStatusCache(){await er.set(EV,this.statusCache)}getUrlSyncStatus(t){if(this.syncingUrls.has(t))return"syncing";const n=this.statusCache[t];return n?n.status:"not_synced"}async syncCurrentBoardMedia(t,n){const r=Date.now();fe("syncCurrentBoardMedia",{currentBoardId:t}),Tr("开始同步当前画板媒体",{boardId:t});try{const i=await CV.collectCurrentBoardMedia(t);if(fe("Collected media",i.stats),i.currentBoardItems.length===0)return Tr("当前画板无媒体需要同步"),this.createEmptyBatchResult(r);const o=await this.getRemoteSyncedUrls(),s=i.currentBoardItems.filter(l=>!o.has(l.url));if(fe("Items to sync",{toSync:s.length,total:i.currentBoardItems.length,alreadySynced:o.size}),Tr("媒体增量计算完成",{total:i.currentBoardItems.length,alreadySynced:o.size,toSync:s.length}),s.length===0)return this.createEmptyBatchResult(r);const a=await this.syncMediaItems(s,n);return Jr("媒体同步完成",{succeeded:a.succeeded,failed:a.failed,skipped:a.skipped,totalSize:a.totalSize,duration:a.duration}),a}catch(i){return vn("syncCurrentBoardMedia failed",i instanceof Error?i:new Error(String(i))),vn("媒体同步失败",i instanceof Error?i:new Error(String(i))),{succeeded:0,failed:0,skipped:0,results:[],totalSize:0,duration:Date.now()-r}}}async syncSelectedMedia(t,n){const r=Date.now();fe("syncSelectedMedia",{urlCount:t.length});try{const i=await CV.collectMediaByUrls(t);if(i.length===0)return this.createEmptyBatchResult(r);const o=await this.getRemoteSyncedUrls(),s=i.filter(a=>!o.has(a.url));return fe("Items to sync",{toSync:s.length,requested:i.length,alreadySynced:i.length-s.length}),s.length===0?{succeeded:0,failed:0,skipped:i.length,results:i.map(a=>({success:!0,url:a.url,error:"已同步"})),totalSize:0,duration:Date.now()-r}:await this.syncMediaItems(s,n)}catch(i){return vn("syncSelectedMedia failed",i instanceof Error?i:new Error(String(i))),{succeeded:0,failed:0,skipped:0,results:[],totalSize:0,duration:Date.now()-r}}}async getRemoteSyncedUrls(){try{if(!yt.hasGistId())return new Set;const{shardSyncService:t}=await xn(async()=>{const{shardSyncService:n}=await Promise.resolve().then(()=>Qtt);return{shardSyncService:n}},void 0,import.meta.url);return await t.getSyncedUrls()}catch(t){return Pt("Failed to get remote synced URLs",{error:String(t)}),new Set}}async syncMediaItems(t,n){var o,s;const r=Date.now();try{const{shardedMediaSyncAdapter:a}=await xn(async()=>{const{shardedMediaSyncAdapter:l}=await Promise.resolve().then(()=>Qle);return{shardedMediaSyncAdapter:l}},void 0,import.meta.url);if(await a.initialize(),a.isShardingEnabled()){fe("Using sharded media sync adapter");const l=await a.uploadMedia(t,n);return l.duration=Date.now()-r,fe("Sharded sync completed",{succeeded:l.succeeded,failed:l.failed,skipped:l.skipped,duration:l.duration}),this.notifySyncCompleted(l),l}}catch(a){Pt("Failed to use sharded adapter, falling back",{error:String(a)})}const i={succeeded:0,failed:0,skipped:0,results:[],totalSize:0,duration:0};for(let a=0;a<t.length;a++){const l=t[a];n==null||n(a+1,t.length,l.url,"uploading");const c=await this.syncSingleMediaItem(l);i.results.push(c),c.success?(i.succeeded++,i.totalSize+=c.size||0):(o=c.error)!=null&&o.includes("过大")||(s=c.error)!=null&&s.includes("CORS")?i.skipped++:i.failed++}return i.duration=Date.now()-r,fe("Legacy sync completed",{succeeded:i.succeeded,failed:i.failed,skipped:i.skipped,totalSize:K2(i.totalSize),duration:i.duration}),this.notifySyncCompleted(i),i}async syncSingleMediaItem(t){const{url:n,type:r,source:i,originalUrl:o,mimeType:s}=t;this.syncingUrls.add(n);try{let a=null;if(i==="local"?a=await yn.getCachedBlob(n):i==="external"&&(a=await yn.getCachedBlob(n)),!a||a.size===0)return{success:!1,url:n,error:"无法获取媒体文件"};if(a.size>eO)return{success:!1,url:n,error:`文件过大(${K2(a.size)}),最大支持 ${K2(eO)}`,size:a.size};const l=await Ole(a),c={url:n,type:r,source:i,mimeType:s||a.type,size:a.size,base64Data:l,syncedAt:Date.now(),syncedFromDevice:zet(),originalUrl:i==="external"?o:void 0},u=`media_${ng(n)}.json`,d=JSON.stringify(c,null,2);return await yt.updateGistFiles({[u]:d}),this.statusCache[n]={status:"synced",syncedAt:Date.now()},await this.saveStatusCache(),{success:!0,url:n,size:a.size}}catch(a){vn(`Failed to sync media: ${n}`,a instanceof Error?a:new Error(String(a)));const l=a instanceof Error?a.message:"同步失败";return this.statusCache[n]={status:"error",error:l},await this.saveStatusCache(),{success:!1,url:n,error:l}}finally{this.syncingUrls.delete(n)}}async fetchMediaFromUrl(t){try{const n=await fetch(t,{mode:"cors",credentials:"omit"});return n.ok?await n.blob():(Pt("Failed to fetch media",{status:n.status}),null)}catch(n){return vn("Fetch media failed",n instanceof Error?n:new Error(String(n))),null}}createEmptyBatchResult(t){return{succeeded:0,failed:0,skipped:0,results:[],totalSize:0,duration:Date.now()-t}}async downloadAndCacheMediaByUrl(t){try{const n=`media_${ng(t)}.json`,r=await yt.getGistFileContent(n);if(!r)return null;const i=JSON.parse(r),o=Rle(i.base64Data,i.mimeType);return!o||o.size===0?null:(await yn.cacheToCacheStorageOnly(t,o),fe("Downloaded and cached media",{url:t}),t)}catch(n){return vn(`Failed to download media: ${t}`,n instanceof Error?n:new Error(String(n))),null}}async downloadAllRemoteMedia(t){const n=Date.now(),r={succeeded:0,failed:0,skipped:0,results:[],totalSize:0,duration:0};try{const i=await this.getRemoteSyncedUrls(),o=Array.from(i);fe("Found remote media to download",{count:o.length});for(let s=0;s<o.length;s++){const a=o[s];if(t==null||t(s+1,o.length,a,"downloading"),(await yn.getCacheInfo(a)).isCached){r.skipped++,r.results.push({success:!0,url:a,error:"已缓存"});continue}await this.downloadAndCacheMediaByUrl(a)?(r.succeeded++,r.results.push({success:!0,url:a})):(r.failed++,r.results.push({success:!1,url:a,error:"下载失败"}))}}catch(i){vn("downloadAllRemoteMedia failed",i instanceof Error?i:new Error(String(i)))}return r.duration=Date.now()-n,r}async refreshSyncStatus(){try{const t=await this.getRemoteSyncedUrls();this.statusCache={};for(const n of t)this.statusCache[n]={status:"synced",syncedAt:Date.now()};await this.saveStatusCache()}catch(t){vn("Refresh failed",t instanceof Error?t:new Error(String(t)))}}async deleteSyncedMedia(t){try{const n=`media_${ng(t)}.json`;return await yt.deleteGistFiles([n]),delete this.statusCache[t],await this.saveStatusCache(),!0}catch(n){return vn("Delete failed",n instanceof Error?n:new Error(String(n))),!1}}}const qc=new Uet,tO=Object.freeze(Object.defineProperty({__proto__:null,mediaSyncService:qc},Symbol.toStringTag,{value:"Module"})),Xk="github_sync_password";function Nle(){return[navigator.userAgent,navigator.language,screen.width.toString(),screen.height.toString(),new Date().getTimezoneOffset().toString()].join("|")}function Het(e){const t=Nle();let n="";for(let r=0;r<e.length;r++){const i=e.charCodeAt(r)^t.charCodeAt(r%t.length);n+=String.fromCharCode(i)}return btoa(n)}function Wet(e){const t=Nle(),n=atob(e);let r="";for(let i=0;i<n.length;i++){const o=n.charCodeAt(i)^t.charCodeAt(i%t.length);r+=String.fromCharCode(o)}return r}class Vet{constructor(){this.cachedPassword=null,this.cacheLoaded=!1}async savePassword(t){if(!t){await er.remove(Xk),this.cachedPassword=null,this.cacheLoaded=!0;return}const n={encrypted:Het(t),storedAt:Date.now()};await er.set(Xk,n),this.cachedPassword=t,this.cacheLoaded=!0}async getPassword(){if(this.cacheLoaded)return this.cachedPassword;const t=await er.get(Xk);if(!t)return this.cachedPassword=null,this.cacheLoaded=!0,null;try{return this.cachedPassword=Wet(t.encrypted),this.cacheLoaded=!0,this.cachedPassword}catch{return this.cachedPassword=null,this.cacheLoaded=!0,null}}async hasPassword(){return!!await this.getPassword()}clearCache(){this.cachedPassword=null,this.cacheLoaded=!1}}const pi=new Vet,Zk="1.0";class Get{async getToolboxService(){const{toolboxService:t}=await xn(async()=>{const{toolboxService:n}=await import("./tool-windows-CSaRGLIT.js").then(r=>r.b2);return{toolboxService:n}},__vite__mapDeps([0]),import.meta.url);return t}async syncTools(t,n){fe("ToolSyncService: Starting tool sync");try{const r=await this.getToolboxService(),i=r.getCustomTools(),o=await r.getUpdatedAt(),s=await this.downloadRemoteTools(t,n);let a=0,l=0,c=0;if(!s)i.length>0?(await this.uploadTools(i,t,n),a=i.length,Tr("ToolSyncService: Uploaded local tools",{count:a})):fe("ToolSyncService: No tools to sync");else{const{toUpload:u,toDownload:d}=this.compareTools(i,s.tools,o,s.updatedAt);if(d.length>0){const f=await r.importTools(d);l=f.imported,c+=f.skipped,Tr("ToolSyncService: Downloaded remote tools",{imported:f.imported,skipped:f.skipped})}if(u.length>0||l>0){const f=r.getCustomTools();await this.uploadTools(f,t,n),a=u.length,Tr("ToolSyncService: Uploaded local tools",{count:a})}}return a>0||l>0?Jr("ToolSyncService: Tool sync completed",{uploaded:a,downloaded:l,skipped:c}):fe("ToolSyncService: Tool sync completed (no changes)"),{uploaded:a,downloaded:l,skipped:c}}catch(r){return Pt("ToolSyncService: Tool sync failed",{error:r instanceof Error?r.message:String(r)}),{uploaded:0,downloaded:0,skipped:0}}}compareTools(t,n,r,i){const o=new Set(t.map(c=>c.id)),s=new Set(n.map(c=>c.id)),a=t.filter(c=>!s.has(c.id)),l=n.filter(c=>!o.has(c.id));return fe("ToolSyncService: Compared tools",{localCount:t.length,remoteCount:n.length,toUpload:a.length,toDownload:l.length}),{toUpload:a,toDownload:l}}async downloadRemoteTools(t,n){try{const r=await yt.getGistFileContent(_t.CUSTOM_TOOLS);if(!r)return fe("ToolSyncService: No remote tools found"),null;const i=await Nn.decryptOrPassthrough(r,t,n),o=JSON.parse(i);return o.version!==Zk?(Pt("ToolSyncService: Incompatible remote version",{remote:o.version,local:Zk}),null):o}catch(r){return Pt("ToolSyncService: Failed to download remote tools",{error:r instanceof Error?r.message:String(r)}),null}}async uploadTools(t,n,r){const i={version:Zk,tools:t,updatedAt:Date.now()},o=JSON.stringify(i,null,2),s=await Nn.encrypt(o,n,r);await yt.updateGistFiles({[_t.CUSTOM_TOOLS]:s})}}const Ket=new Get,_V="github_sync_config",o2="github_sync_local_deletions_pending";class qet{constructor(){this.status="not_configured",this.statusListeners=new Set,this.syncInProgress=!1,this.autoSyncTimer=null,this.pendingChanges=!1,this.initialize()}async initialize(){if(ai.hasToken()){const n=await this.getConfig();n.gistId?(yt.setGistId(n.gistId),this.status="synced"):this.status="local_changes"}else this.status="not_configured"}async getConfig(){return await er.get(_V)||{...tet}}async saveConfig(t){const r={...await this.getConfig(),...t};await er.set(_V,r)}getSyncStatus(){return this.status}setStatus(t,n){this.status=t,this.notifyStatusListeners(t,n)}addStatusListener(t){this.statusListeners.add(t)}removeStatusListener(t){this.statusListeners.delete(t)}notifyStatusListeners(t,n){this.statusListeners.forEach(r=>{try{r(t,n)}catch(i){vn("状态监听器错误",i instanceof Error?i:new Error(String(i)))}})}performSafetyCheck(t){var u;const{localBoards:n,toDeleteLocally:r,currentBoardId:i,isFirstSync:o,remoteManifest:s}=t,a={passed:!0,warnings:[],skippedItems:[]};if(r.length===0)return a;if(fe("Safety check",{localBoardsCount:n.size,toDeleteCount:r.length,currentBoardId:i,isFirstSync:o,hasRemoteManifest:!!s}),!s||Object.keys(s.boards).length===0)return fe("Safety: Remote manifest empty or invalid, skipping all deletions"),a.skippedItems=r.map(d=>{var f;return{id:d,name:((f=n.get(d))==null?void 0:f.name)||d,reason:"new_device"}}),a;if(o&&r.length>0)return fe("Safety: First sync, skipping all deletions"),a.skippedItems=r.map(d=>{var f;return{id:d,name:((f=n.get(d))==null?void 0:f.name)||d,reason:"new_device"}}),a;i&&r.includes(i)&&(fe("Safety: Current board protected",{currentBoardId:i}),a.skippedItems.push({id:i,name:((u=n.get(i))==null?void 0:u.name)||i,reason:"current_board"}));const l=new Set(a.skippedItems.map(d=>d.id)),c=r.filter(d=>!l.has(d));if(c.length===n.size&&n.size>0)return fe("Safety: Blocked - would delete all local boards"),a.passed=!1,a.blockedReason="检测到异常操作:远程数据要求删除所有本地画板,已阻止执行。请检查远程数据是否正常。",a;if(c.length>1){const d=c.length/n.size;d>.5&&(fe("Safety: Bulk delete warning",{deleteRatio:d}),a.passed=!1,a.warnings.push({type:"bulk_delete",message:`即将删除 ${c.length}/${n.size} 个画板 (${Math.round(d*100)}%)`,affectedItems:c.map(f=>{var p;return{id:f,name:((p=n.get(f))==null?void 0:p.name)||f}})}))}return a}async sync(){var i,o,s,a,l,c,u,d,f,p,y,v,w;if(this.syncInProgress)return{success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],error:"同步正在进行中",duration:0};const t=Date.now();this.syncInProgress=!0,this.setStatus("syncing","正在同步...");const n=fhe();Tr("开始同步",{sessionId:n});const r={success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0};try{if(!await ai.getToken())throw new Error("未配置 GitHub Token");Tr("Token 验证通过"),fe("Collecting local data...");const x=await Or.collectSyncData();Tr("本地数据收集完成",{boards:x.boards.size,folders:x.workspace.folders.length}),fe("Local data collected",{boards:x.boards.size,folders:x.workspace.folders.length,currentBoardId:x.workspace.currentBoardId});const E=await this.getConfig();fe("Config",{gistId:E.gistId,lastSyncTime:E.lastSyncTime,enabled:E.enabled});let _=null,I={},D=!1;if(E.gistId){fe("Using existing gistId",{gistId:xa(E.gistId)}),yt.setGistId(E.gistId);try{const k=await yt.getGist();fe("Got gist",{files:Object.keys(k.files)});for(const T of Object.keys(k.files)){const M=await yt.getGistFileContent(T);M&&(I[T]=M)}fe("Loaded remote files",{count:Object.keys(I).length});const R=await pi.getPassword();if(I[_t.MANIFEST])try{const{cryptoService:T}=await xn(async()=>{const{cryptoService:F}=await Promise.resolve().then(()=>sl);return{cryptoService:F}},void 0,import.meta.url),M=await T.decryptOrPassthrough(I[_t.MANIFEST],E.gistId,R||void 0);_=JSON.parse(M)}catch(T){if(Pt("Failed to decrypt/parse manifest",{error:String(T)}),x.boards.size>0||x.prompts.promptHistory.length>0||x.tasks.completedTasks.length>0)Pt("Local has data, will overwrite remote"),D=!0;else throw vn("Local is empty, refusing to overwrite remote"),new Error("解密失败且本地无数据,拒绝覆盖远程数据以防止数据丢失")}fe("Remote manifest",{version:_==null?void 0:_.version,boards:_?Object.keys(_.boards).length:0,shouldOverwriteRemote:D})}catch(k){if(vn("Error fetching gist",k instanceof Error?k:new Error(String(k))),k instanceof cl&&k.statusCode===404)fe("Gist not found (404), will create new one"),E.gistId=null;else throw k}}if(D&&E.gistId){Tr("Decryption failed, overwriting remote with local data...");const k=await pi.getPassword(),R=await Or.serializeToGistFilesEncrypted(x,E.gistId,k||void 0);await yt.updateGistFiles(R);try{const T=await Kl.syncTasks(E.gistId,k||void 0);r.uploaded.tasks=T.uploaded}catch(T){Pt("Tasks paged sync failed during overwrite",{error:String(T)})}await this.saveConfig({lastSyncTime:Date.now()}),r.uploaded.boards=x.boards.size,r.uploaded.prompts=x.prompts.promptHistory.length+x.prompts.videoPromptHistory.length+x.prompts.imagePromptHistory.length,r.uploaded.knowledgeBase=(((i=x.knowledgeBase)==null?void 0:i.notes.length)||0)+(((o=x.knowledgeBase)==null?void 0:o.directories.length)||0),r.success=!0,Jr("Remote overwritten with local data")}else if(E.gistId){if(E.gistId)if(fe("Has gistId, comparing changes..."),_){fe("Has remoteManifest, comparing changes...");const k=Or.compareBoardChanges(x.boards,_,E.lastSyncTime);fe("Changes detected",{toUpload:k.toUpload,toDownload:k.toDownload,conflicts:k.conflicts,toDeleteLocally:k.toDeleteLocally}),Tr("变更检测完成",{toUpload:k.toUpload.length,toDownload:k.toDownload.length,conflicts:k.conflicts.length,toDeleteLocally:k.toDeleteLocally.length}),fe("Detecting local deletions...");const R=Or.detectDeletions(x,_);fe("Local deletions detected",{boards:R.deletedBoards.length,deletedBoardIds:R.deletedBoards.map(N=>N.id)});let T=[];if(k.toDeleteLocally.length>0){const N=await Bn.loadState(),B=this.performSafetyCheck({localBoards:x.boards,toDeleteLocally:k.toDeleteLocally,currentBoardId:N.currentBoardId||null,isFirstSync:!E.lastSyncTime,remoteManifest:_});if(fe("Safety check result",{passed:B.passed,warnings:B.warnings.length,skipped:B.skippedItems.length,blockedReason:B.blockedReason}),r.safetyWarnings=B.warnings,r.skippedItems=B.skippedItems,B.blockedReason)Pt("Safety: Blocked all deletions",{reason:B.blockedReason});else if(!B.passed&&B.warnings.length>0)Pt("Safety: Warnings present, skipping deletions pending user confirmation");else{const O=new Set(B.skippedItems.map($=>$.id));T=k.toDeleteLocally.filter($=>!O.has($))}}const M=await pi.getPassword();fe("Incremental sync",{hasCustomPassword:!!M});const F=await Or.deserializeFromGistFilesWithDecryption(I,E.gistId,M||void 0);fe("Remote data for merge",{boards:F.boards.size,workspaceFolders:((v=(y=F.workspace)==null?void 0:y.folders)==null?void 0:v.length)||0});const V=[];if(k.conflicts.length>0){Tr(`发现 ${k.conflicts.length} 个冲突画板,开始合并`);for(const N of k.conflicts){const B=x.boards.get(N),O=F.boards.get(N),$=_.boards[N];if(B&&O&&$){const U=Or.mergeBoardElements(B,O);V.push({boardId:N,board:U.mergedBoard}),Tr(`画板合并完成: ${B.name}`,{boardId:N,addedFromLocal:U.addedFromLocal,addedFromRemote:U.addedFromRemote,conflictingElements:U.conflictingElements.length,hasConflicts:U.hasConflicts}),U.hasConflicts&&(r.conflicts.push({type:"board",id:N,name:B.name,localUpdatedAt:B.updatedAt,remoteUpdatedAt:$.updatedAt,merged:!0,mergeInfo:{addedFromLocal:U.addedFromLocal,addedFromRemote:U.addedFromRemote,conflictingElements:U.conflictingElements.length}}),Pt(`画板存在元素冲突: ${B.name}`,{boardId:N,conflictingElements:U.conflictingElements.length})),fe("Merged board",{boardId:N,addedFromLocal:U.addedFromLocal,addedFromRemote:U.addedFromRemote,conflicts:U.conflictingElements.length})}}}if(k.toDownload.length>0){Tr(`下载 ${k.toDownload.length} 个远程画板`);const N=new Set(V.map($=>$.boardId)),B=new Map;for(const $ of k.toDownload)if(!N.has($)){const U=F.boards.get($);U?(B.set($,U),fe("Will download board",{boardId:$,name:U.name})):fe("Board not found in remote data",{boardId:$})}fe("Boards to download after filtering",{count:B.size});const O=await Or.applySyncData({workspace:F.workspace,boards:B,prompts:F.prompts,tasks:F.tasks,deletedBoardIds:T});fe("Applied remote data",O),Jr("远程数据下载完成",{boards:O.boardsApplied,prompts:O.promptsApplied,tasks:O.tasksApplied,deleted:O.boardsDeleted}),r.downloaded.boards=O.boardsApplied,r.downloaded.prompts=O.promptsApplied,r.downloaded.tasks=O.tasksApplied,r.remoteCurrentBoardId=O.remoteCurrentBoardId,O.boardsDeleted>0&&(r.deleted={boards:O.boardsDeleted,prompts:O.promptsDeleted,tasks:O.tasksDeleted,media:0})}else{if(fe("No boards to download"),T.length>0){const N=await Or.applySyncData({workspace:null,boards:new Map,prompts:null,tasks:null,deletedBoardIds:T});N.boardsDeleted>0&&(r.deleted={boards:N.boardsDeleted,prompts:N.promptsDeleted,tasks:N.tasksDeleted,media:0})}r.remoteCurrentBoardId=((w=F.workspace)==null?void 0:w.currentBoardId)||null,fe("Set remoteCurrentBoardId from workspace",{remoteCurrentBoardId:r.remoteCurrentBoardId})}if(V.length>0){for(const{boardId:N,board:B}of V)await Bn.saveBoard(B),x.boards.set(N,B);k.toUpload.push(...V.map(N=>N.boardId)),r.downloaded.boards+=V.length}let H=!1;if(x.knowledgeBase||F.knowledgeBase){fe("Processing Knowledge Base sync...");let N=x.knowledgeBase;if(x.knowledgeBase&&F.knowledgeBase){fe("Merging local and remote Knowledge Base"),N=Bf.merge(x.knowledgeBase,F.knowledgeBase);const B=JSON.stringify(x.knowledgeBase),O=JSON.stringify(N);B!==O&&(Tr("Knowledge Base merged, applying to local"),await Bf.apply(N),x.knowledgeBase=N,r.downloaded.knowledgeBase=Math.abs(N.notes.length+N.directories.length-(JSON.parse(B).notes.length+JSON.parse(B).directories.length)))}else F.knowledgeBase&&!x.knowledgeBase&&(Tr("Downloading Knowledge Base from remote"),await Bf.apply(F.knowledgeBase),x.knowledgeBase=F.knowledgeBase,N=F.knowledgeBase,r.downloaded.knowledgeBase=N.notes.length+N.directories.length);if(x.knowledgeBase){const B=JSON.stringify(x.knowledgeBase),O=F.knowledgeBase?JSON.stringify(F.knowledgeBase):"";B!==O&&(H=!0)}}const j=k.toUpload.length>0,z=R.deletedBoards.length>0;if(j||z||H){Tr("开始上传本地变更",{boardsToUpload:k.toUpload.length,deletedBoards:R.deletedBoards.length,kbNeedsUpload:H});const N={},B=new Set,{cryptoService:O}=await xn(async()=>{const{cryptoService:K}=await Promise.resolve().then(()=>sl);return{cryptoService:K}},void 0,import.meta.url);for(const K of k.toUpload){if(B.has(K))continue;B.add(K);const Z=x.boards.get(K);if(Z){const oe=JSON.stringify(Z);N[_t.boardFile(K)]=await O.encrypt(oe,E.gistId,M||void 0),x.manifest.boards[K]={name:Z.name,updatedAt:Z.updatedAt,checksum:Or.calculateBoardChecksum(Z)}}}if(z){fe("标记删除的画板为 tombstone",{boards:R.deletedBoards.map(Z=>Z.id)});const K=Or.markBoardsAsDeleted(x.manifest,R.deletedBoards,x.manifest.deviceId);x.manifest=K}x.manifest.updatedAt=Date.now();const $=JSON.stringify(x.manifest);N[_t.MANIFEST]=await O.encrypt($,E.gistId,M||void 0);const U=JSON.stringify(x.workspace);N[_t.WORKSPACE]=await O.encrypt(U,E.gistId,M||void 0);const Y=JSON.stringify(x.prompts);if(N[_t.PROMPTS]=await O.encrypt(Y,E.gistId,M||void 0),x.knowledgeBase){const K=JSON.stringify(x.knowledgeBase),Z=F.knowledgeBase?JSON.stringify(F.knowledgeBase):"";K!==Z&&(fe("Uploading Knowledge Base (changed)"),N[_t.KNOWLEDGE_BASE]=await O.encrypt(K,E.gistId,M||void 0),r.uploaded.knowledgeBase=x.knowledgeBase.notes.length+x.knowledgeBase.directories.length)}await yt.updateGistFiles(N),r.uploaded.boards=k.toUpload.length;try{const K=await Kl.syncTasks(E.gistId,M||void 0);r.uploaded.tasks=K.uploaded}catch(K){Pt("Tasks paged sync failed during incremental sync",{error:String(K)})}Jr("本地变更上传完成",{boards:k.toUpload.length,files:Object.keys(N).length}),z&&!r.deleted&&(r.deleted={boards:0,prompts:0,tasks:0,media:0}),z&&r.deleted&&(fe("Tombstone 上传完成",{count:R.deletedBoards.length}),Tr("删除标记上传完成",{count:R.deletedBoards.length}),await this.clearLocalDeletions(R.deletedBoards.map(K=>K.id)))}await this.saveConfig({lastSyncTime:Date.now()}),r.success=!0}else{Pt("No remote manifest found, will perform full upload");const{cryptoService:k}=await xn(async()=>{const{cryptoService:H}=await Promise.resolve().then(()=>sl);return{cryptoService:H}},void 0,import.meta.url),R={},T=await pi.getPassword();fe("Full upload",{hasCustomPassword:!!T});for(const[H,j]of x.boards){const z=JSON.stringify(j);R[_t.boardFile(H)]=await k.encrypt(z,E.gistId,T||void 0),x.manifest.boards[H]={name:j.name,updatedAt:j.updatedAt,checksum:Or.calculateBoardChecksum(j)}}x.manifest.updatedAt=Date.now();const M=JSON.stringify(x.manifest);R[_t.MANIFEST]=await k.encrypt(M,E.gistId,T||void 0);const F=JSON.stringify(x.workspace);R[_t.WORKSPACE]=await k.encrypt(F,E.gistId,T||void 0);const V=JSON.stringify(x.prompts);R[_t.PROMPTS]=await k.encrypt(V,E.gistId,T||void 0),await yt.updateGistFiles(R),r.uploaded.boards=x.boards.size;try{const H=await Kl.syncTasks(E.gistId,T||void 0);r.uploaded.tasks=H.uploaded}catch(H){Pt("Tasks paged sync failed during initial sync",{error:String(H)})}r.success=!0,await this.saveConfig({lastSyncTime:Date.now()})}}else{fe("No gistId in config, searching for existing sync gist...");const k=await yt.findSyncGist();if(k){fe("Found existing gist",{gistId:xa(k.id),files:Object.keys(k.files).length}),yt.setGistId(k.id);for(const T of Object.keys(k.files)){const M=await yt.getGistFileContent(T);M&&(I[T]=M,fe("Loaded file",{filename:T,length:M.length}))}const R=await pi.getPassword();fe("Custom password available",{hasPassword:!!R});try{fe("Deserializing remote data...");const T=await Or.deserializeFromGistFilesWithDecryption(I,k.id,R||void 0);fe("Remote data parsed",{boards:T.boards.size,folders:((a=(s=T.workspace)==null?void 0:s.folders)==null?void 0:a.length)||0,tasks:((c=(l=T.tasks)==null?void 0:l.completedTasks)==null?void 0:c.length)||0}),fe("Applying remote data to local...");const M=await Or.applySyncData({workspace:T.workspace,boards:T.boards,prompts:T.prompts,tasks:T.tasks});fe("Applied result",M),await this.saveConfig({gistId:k.id,lastSyncTime:Date.now(),enabled:!0}),r.downloaded.boards=M.boardsApplied,r.downloaded.prompts=M.promptsApplied,r.downloaded.tasks=M.tasksApplied,r.downloaded.knowledgeBase=M.knowledgeBaseApplied,r.remoteCurrentBoardId=M.remoteCurrentBoardId,r.success=!0}catch(T){Pt("Decryption failed for existing gist, overwriting with local data",{error:String(T)});const M=await Or.serializeToGistFilesEncrypted(x,k.id,R||void 0);await yt.updateGistFiles(M);try{const F=await Kl.syncTasks(k.id,R||void 0);r.uploaded.tasks=F.uploaded}catch(F){Pt("Tasks paged sync failed during overwrite",{error:String(F)})}await this.saveConfig({gistId:k.id,lastSyncTime:Date.now(),enabled:!0}),r.uploaded.boards=x.boards.size,r.uploaded.prompts=x.prompts.promptHistory.length+x.prompts.videoPromptHistory.length+x.prompts.imagePromptHistory.length,r.uploaded.knowledgeBase=(((u=x.knowledgeBase)==null?void 0:u.notes.length)||0)+(((d=x.knowledgeBase)==null?void 0:d.directories.length)||0),r.success=!0,Jr("Existing gist overwritten with local data")}}else{fe("No existing gist found, will create new one with encryption");const R=await yt.createSyncGist({"manifest.json":JSON.stringify({version:1,initializing:!0},null,2)}),T=R.id,M=await pi.getPassword();fe("Creating new gist",{hasCustomPassword:!!M});const F=await Or.serializeToGistFilesEncrypted(x,T,M||void 0);yt.setGistId(T),await yt.updateGistFiles(F);try{const H=await Kl.syncTasks(T,M||void 0);r.uploaded.tasks=H.uploaded}catch(H){Pt("Tasks paged sync failed during new gist creation",{error:String(H)})}const V=R;await this.saveConfig({gistId:V.id,lastSyncTime:Date.now(),enabled:!0}),r.uploaded.boards=x.boards.size,r.uploaded.prompts=x.prompts.promptHistory.length+x.prompts.videoPromptHistory.length+x.prompts.imagePromptHistory.length,r.uploaded.knowledgeBase=(((f=x.knowledgeBase)==null?void 0:f.notes.length)||0)+(((p=x.knowledgeBase)==null?void 0:p.directories.length)||0),r.success=!0}}this.setStatus("synced"),this.pendingChanges=!1,Jr("同步完成",{uploaded:r.uploaded,downloaded:r.downloaded,conflicts:r.conflicts.length});const P=x.workspace.currentBoardId;P&&r.uploaded.boards>0&&this.syncCurrentBoardMediaAsync(P),(r.downloaded.tasks>0||r.downloaded.boards>0)&&this.downloadSyncedMediaAsync()}catch(C){vn("同步失败",C instanceof Error?C:new Error(String(C))),r.error=C instanceof Error?C.message:"同步失败",this.setStatus("error",r.error),vn("同步失败",C instanceof Error?C:new Error(String(C)))}finally{this.syncInProgress=!1,r.duration=Date.now()-t,Tr("同步会话结束",{duration:r.duration,success:r.success}),hhe(),phe().catch(()=>{})}return r}async syncCurrentBoardMediaAsync(t){try{fe("Starting async current board media sync",{currentBoardId:t});const n=await qc.syncCurrentBoardMedia(t,(r,i,o,s)=>{fe("Media sync progress",{status:s,current:r,total:i,url:o})});Jr("Current board media sync completed",{succeeded:n.succeeded,failed:n.failed,skipped:n.skipped})}catch(n){vn("Current board media sync failed",n instanceof Error?n:new Error(String(n)))}}async uploadMergedTasksToRemote(t,n){try{fe("uploadMergedTasksToRemote: Starting with paged format...");const r=await Kl.syncTasks(t,n);Jr("uploadMergedTasksToRemote: Tasks synced",{uploaded:r.uploaded,downloaded:r.downloaded,skipped:r.skipped})}catch(r){vn("uploadMergedTasksToRemote: Failed to sync tasks",r instanceof Error?r:new Error(String(r)))}}async downloadSyncedMediaAsync(){try{fe("Starting async media download...");const t=await qc.downloadAllRemoteMedia((n,r,i,o)=>{fe("Downloading media",{current:n,total:r,url:i,status:o})});Jr("Media download completed",{succeeded:t.succeeded,failed:t.failed,skipped:t.skipped})}catch(t){vn("Media download failed",t instanceof Error?t:new Error(String(t)))}}async pushToRemote(){if(this.syncInProgress)return{success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],error:"同步正在进行中",duration:0};const t=Date.now();this.syncInProgress=!0,this.setStatus("syncing","正在上传本地数据...");const n={success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0};try{if(!await ai.getToken())throw new Error("未配置 GitHub Token");const i=await pi.getPassword();fe("pushToRemote: 收集本地数据");const o=await Or.collectSyncData(),s=await this.getConfig();if(s.gistId){fe("pushToRemote: 增量上传",{gistId:xa(s.gistId)}),yt.setGistId(s.gistId);const{cryptoService:c}=await xn(async()=>{const{cryptoService:w}=await Promise.resolve().then(()=>sl);return{cryptoService:w}},void 0,import.meta.url);let u=null;try{const w=await yt.getGistFileContent(_t.MANIFEST);if(w){const C=await c.decryptOrPassthrough(w,s.gistId,i||void 0);u=JSON.parse(C)}}catch{fe("pushToRemote: 无远程 manifest 或解密失败,将上传全部")}const d={};let f=0;if(u){let w=0;for(const[C,x]of o.boards){const E=Or.calculateBoardChecksum(x),_=u.boards[C];if(!_||_.checksum!==E){const I=JSON.stringify(x);d[_t.boardFile(C)]=await c.encrypt(I,s.gistId,i||void 0),f++,fe("pushToRemote: 画板需要上传 (checksum 变化)",{boardId:C})}w++,w%3===0&&await Wo()}for(const C of Object.keys(u.boards)){const x=u.boards[C];x.deletedAt||o.boards.has(C)||(o.manifest.boards[C]={...x,deletedAt:Date.now()},fe("pushToRemote: 画板软删除 (移入回收站)",{boardId:C}))}}else{let w=0;for(const[C,x]of o.boards){const E=JSON.stringify(x);d[_t.boardFile(C)]=await c.encrypt(E,s.gistId,i||void 0),f++,w++,w%3===0&&await Wo()}}const p=JSON.stringify(o.manifest);d[_t.MANIFEST]=await c.encrypt(p,s.gistId,i||void 0);const y=JSON.stringify(o.workspace);d[_t.WORKSPACE]=await c.encrypt(y,s.gistId,i||void 0);const v=JSON.stringify(o.prompts);if(d[_t.PROMPTS]=await c.encrypt(v,s.gistId,i||void 0),o.knowledgeBase){const w=JSON.stringify(o.knowledgeBase);d[_t.KNOWLEDGE_BASE]=await c.encrypt(w,s.gistId,i||void 0),n.uploaded.knowledgeBase=o.knowledgeBase.notes.length+o.knowledgeBase.directories.length}Object.keys(d).length>0&&(await yt.updateGistFiles(d),fe("pushToRemote: 增量上传完成",{boardsUploaded:f})),n.uploaded.boards=f;try{const w=await Kl.syncTasks(s.gistId,i||void 0);n.uploaded.tasks=w.uploaded}catch(w){Pt("pushToRemote: Tasks paged sync failed",{error:String(w)})}await this.saveConfig({lastSyncTime:Date.now()})}else{fe("pushToRemote: 创建新 Gist");const u=(await yt.createSyncGist({"manifest.json":JSON.stringify({version:1,initializing:!0},null,2)})).id;fe("pushToRemote: 创建空 Gist 完成",{gistId:xa(u)});const d=await Or.serializeToGistFilesEncrypted(o,u,i||void 0);yt.setGistId(u),await yt.updateGistFiles(d);try{const f=await Kl.syncTasks(u,i||void 0);n.uploaded.tasks=f.uploaded}catch(f){Pt("pushToRemote: Tasks paged sync failed during new gist creation",{error:String(f)})}await this.saveConfig({gistId:u,lastSyncTime:Date.now(),enabled:!0}),n.uploaded.boards=o.boards.size}n.uploaded.prompts=o.prompts.promptHistory.length+o.prompts.videoPromptHistory.length+o.prompts.imagePromptHistory.length,n.success=!0,Jr("pushToRemote: 上传成功",n.uploaded),this.setStatus("synced"),this.pendingChanges=!1;const a=await this.getLocalDeletionsPendingSync();a.size>0&&await this.clearLocalDeletions(Array.from(a.keys()));const l=o.workspace.currentBoardId;l&&this.syncCurrentBoardMediaAsync(l)}catch(r){vn("pushToRemote 失败",r instanceof Error?r:new Error(String(r))),n.error=r instanceof Error?r.message:"上传失败",this.setStatus("error",n.error)}finally{this.syncInProgress=!1,n.duration=Date.now()-t}return n}async pullFromRemote(){var r,i,o,s,a,l,c,u,d,f;if(Tr("pullFromRemote START"),this.syncInProgress)return fe("pullFromRemote: Sync already in progress, aborting"),{success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],error:"同步正在进行中",duration:0};const t=Date.now();this.syncInProgress=!0,this.setStatus("syncing","正在下载远程数据...");const n={success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0};try{if(!await ai.getToken())throw new Error("未配置 GitHub Token");const y=await pi.getPassword(),v=await this.getConfig();let w=v.gistId;if(!w){fe("pullFromRemote: No gistId, searching for sync gist...");const K=await yt.findSyncGist();if(K)w=K.id;else throw new Error("未找到可同步的 Gist,请先上传数据或在其他设备创建同步")}yt.setGistId(w);const{cryptoService:C}=await xn(async()=>{const{cryptoService:K}=await Promise.resolve().then(()=>sl);return{cryptoService:K}},void 0,import.meta.url);fe("pullFromRemote: 获取远程 manifest");const x=await yt.getGistFileContent(_t.MANIFEST);if(!x)throw new Error("远程数据为空");const E=await C.decryptOrPassthrough(x,w,y||void 0),_=JSON.parse(E);fe("pullFromRemote: 远程画板数量",{count:Object.keys(_.boards).length});const I=await Or.collectSyncData(),D=v.lastSyncTime;fe("pullFromRemote: lastSyncTime",{lastSyncTime:D});const P=await this.getLocalDeletionsPendingSync();fe("pullFromRemote: 待同步本地删除",{count:P.size,pending:P.size>0?Object.fromEntries(P):"none"});const k=[],R=[],T=[],M=[];for(const[K,Z]of Object.entries(_.boards)){if(Z.deletedAt){fe("pullFromRemote: 画板已远程删除,跳过",{boardId:K});continue}const oe=P.get(K);oe!==void 0&&(fe("pullFromRemote: 画板本地已删除,但远程为准将恢复",{boardId:K,localDeletedAt:oe,remoteUpdatedAt:Z.updatedAt}),await this.clearLocalDeletions([K]));const J=I.boards.get(K);if(!J)fe("pullFromRemote: 画板本地不存在,将下载",{boardId:K}),k.push(K);else{const ae=Or.calculateBoardChecksum(J);if(ae===Z.checksum)fe("pullFromRemote: checksum 匹配,跳过下载",{boardId:K,checksum:ae});else{const Q=J.updatedAt||0,se=Z.updatedAt||0;Q>se?(fe("pullFromRemote: 本地更新,跳过下载",{boardId:K,localUpdatedAt:new Date(Q).toISOString(),remoteUpdatedAt:new Date(se).toISOString()}),T.push({id:K,name:J.name||Z.name||K,localUpdatedAt:Q,remoteUpdatedAt:se})):(fe("pullFromRemote: checksum 不匹配,将下载远程版本",{boardId:K,localUpdatedAt:new Date(Q).toISOString(),remoteUpdatedAt:new Date(se).toISOString()}),k.push(K))}}}for(const K of I.boards.keys())_.boards[K]||R.push(K);fe("pullFromRemote: 同步计划",{toDownload:k.length,toDelete:R.length,skippedLocalDeletion:M.length,skippedLocalNewer:T.length}),T.length>0&&fe("pullFromRemote: 跳过的画板 (本地更新)",{boards:T.map(K=>K.id)});const F={};F[_t.MANIFEST]=x,fe("pullFromRemote: 下载 workspace 文件");const V=await yt.getGistFileContent(_t.WORKSPACE);V?(F[_t.WORKSPACE]=V,fe("pullFromRemote: workspace.json 已下载",{length:V.length})):Pt("pullFromRemote: workspace.json 未找到或为空"),fe("pullFromRemote: 下载 prompts 文件");const H=await yt.getGistFileContent(_t.PROMPTS);H?(F[_t.PROMPTS]=H,fe("pullFromRemote: prompts.json 已下载",{length:H.length})):Pt("pullFromRemote: prompts.json 未找到或为空"),fe("pullFromRemote: Downloading knowledge base file");const j=await yt.getGistFileContent(_t.KNOWLEDGE_BASE);j?(F[_t.KNOWLEDGE_BASE]=j,fe("pullFromRemote: knowledge-base.json downloaded",{length:j.length})):Pt("pullFromRemote: knowledge-base.json not found or empty"),fe("pullFromRemote: 下载画板文件",{count:k.length});for(const K of k){const Z=_t.boardFile(K);fe("pullFromRemote: 下载画板",{boardId:K});const oe=await yt.getGistFileContent(Z);oe?(F[Z]=oe,fe("pullFromRemote: 画板已下载",{boardId:K,length:oe.length})):Pt("pullFromRemote: 画板未找到或为空",{boardId:K})}fe("pullFromRemote: 文件下载摘要",{totalFiles:Object.keys(F).length,fileNames:Object.keys(F)}),fe("pullFromRemote: 开始反序列化");const z=await Or.deserializeFromGistFilesWithDecryption(F,w,y||void 0);fe("pullFromRemote: 反序列化完成",{workspace:z.workspace?{currentBoardId:z.workspace.currentBoardId,folders:((r=z.workspace.folders)==null?void 0:r.length)||0,boardMetadata:((i=z.workspace.boardMetadata)==null?void 0:i.length)||0}:null,boardsCount:z.boards.size,promptsCount:z.prompts?(((o=z.prompts.promptHistory)==null?void 0:o.length)||0)+(((s=z.prompts.videoPromptHistory)==null?void 0:s.length)||0)+(((a=z.prompts.imagePromptHistory)==null?void 0:a.length)||0):0,tasksCount:((c=(l=z.tasks)==null?void 0:l.completedTasks)==null?void 0:c.length)||0});const N=new Map(z.boards);for(const[K,Z]of I.boards)!k.includes(K)&&!R.includes(K)&&(N.has(K)||N.set(K,Z));const B=new Set(N.keys()),O=new Set(M);let $=z.workspace;$!=null&&$.boardMetadata&&($={...$,boardMetadata:$.boardMetadata.filter(K=>B.has(K.id)&&!O.has(K.id)),currentBoardId:$.currentBoardId&&B.has($.currentBoardId)&&!O.has($.currentBoardId)?$.currentBoardId:null}),fe("pullFromRemote: Workspace 已过滤",{appliedBoardIds:B.size,skippedBoardIds:O.size,currentBoardId:($==null?void 0:$.currentBoardId)||null}),fe("pullFromRemote: 开始应用同步数据",{boardsCount:N.size,boardIds:Array.from(N.keys()),workspace:$?{currentBoardId:$.currentBoardId,folders:((u=$.folders)==null?void 0:u.length)||0,boardMetadata:((d=$.boardMetadata)==null?void 0:d.length)||0}:null});const U=await Or.applySyncData({workspace:$,boards:N,prompts:z.prompts,tasks:z.tasks});if(fe("pullFromRemote: 应用同步数据完成",{boardsApplied:U.boardsApplied,promptsApplied:U.promptsApplied,tasksApplied:U.tasksApplied,remoteCurrentBoardId:U.remoteCurrentBoardId}),await this.saveConfig({gistId:w,lastSyncTime:Date.now(),enabled:!0}),n.downloaded.boards=k.length,n.downloaded.prompts=U.promptsApplied,n.downloaded.tasks=U.tasksApplied,n.remoteCurrentBoardId=U.remoteCurrentBoardId,z.knowledgeBase){fe("pullFromRemote: Applying knowledge base (merge)");let K=z.knowledgeBase;I.knowledgeBase&&(K=Bf.merge(I.knowledgeBase,z.knowledgeBase)),await Bf.apply(K),n.downloaded.knowledgeBase=K.notes.length+K.directories.length}n.success=!0,T.length>0&&(n.skippedItems=T.map(K=>({id:K.id,name:K.name,reason:"local_newer",localUpdatedAt:K.localUpdatedAt,remoteUpdatedAt:K.remoteUpdatedAt}))),Jr("pullFromRemote: 下载成功",{downloaded:n.downloaded,skippedItems:((f=n.skippedItems)==null?void 0:f.length)||0,remoteCurrentBoardId:n.remoteCurrentBoardId}),this.setStatus("synced"),this.pendingChanges=!1;const Y=[];for(const[K]of P)_.boards[K]?k.includes(K)&&Y.push(K):Y.push(K);Y.length>0&&(fe("pullFromRemote: 清理删除记录",{count:Y.length}),await this.clearLocalDeletions(Y)),await this.uploadMergedTasksToRemote(w,y||void 0),await this.initializeShardingSystem(w),this.downloadSyncedMediaAsync()}catch(p){vn("pullFromRemote 失败",p instanceof Error?p:new Error(String(p))),p instanceof Lf?(n.error=p.message,n.needsPassword=p.needsPassword):n.error=p instanceof Error?p.message:"下载失败",this.setStatus("error",n.error)}finally{this.syncInProgress=!1,n.duration=Date.now()-t}return n}markDirty(){fe("markDirty called",{status:this.status,syncInProgress:this.syncInProgress}),this.pendingChanges=!0,this.status==="synced"&&this.setStatus("local_changes"),this.scheduleAutoSync()}hasPendingChanges(){return this.pendingChanges}async getLocalDeletionsPendingSync(){const t=await er.get(o2);if(fe("getLocalDeletionsPendingSync: 从存储加载数据",{hasData:!!t}),!t)return new Map;if(Array.isArray(t)){fe("getLocalDeletionsPendingSync: 从旧格式迁移");const r=Date.now(),i=new Map;return t.forEach(o=>i.set(o,r)),await er.set(o2,Object.fromEntries(i)),i}const n=new Map(Object.entries(t));return fe("getLocalDeletionsPendingSync: 已加载删除记录",{count:n.size}),n}async recordLocalDeletion(t){const n=await this.getLocalDeletionsPendingSync(),r=Date.now();n.set(t,r),fe("recordLocalDeletion: 记录本地删除",{boardId:t,deletedAt:r}),await er.set(o2,Object.fromEntries(n))}async syncBoardDeletion(t){if(fe("syncBoardDeletion",{boardId:t}),!ai.hasToken())return fe("syncBoardDeletion: 无 Token,跳过"),{success:!1,error:"未配置 GitHub Token"};const n=await this.getConfig();if(!n.gistId)return fe("syncBoardDeletion: 无 GistId,跳过"),{success:!1,error:"未配置同步 Gist"};try{yt.setGistId(n.gistId);const r=await pi.getPassword(),{cryptoService:i}=await xn(async()=>{const{cryptoService:p}=await Promise.resolve().then(()=>sl);return{cryptoService:p}},void 0,import.meta.url),o=await yt.getGistFileContent(_t.MANIFEST);if(!o)return{success:!1,error:"远程 manifest 不存在"};const s=await i.decryptOrPassthrough(o,n.gistId,r||void 0),a=JSON.parse(s),l=a.boards[t];if(!l)return fe("syncBoardDeletion: 画板不在远程 manifest 中"),{success:!0};if(l.deletedAt)return fe("syncBoardDeletion: 画板已在远程删除"),{success:!0};const c=await ai.getUserInfo(),u=(c==null?void 0:c.login)||"unknown",d=Date.now();a.boards[t]={...l,deletedAt:d,deletedBy:u},a.updatedAt=d;const f=JSON.stringify(a);return await yt.updateGistFiles({[_t.MANIFEST]:await i.encrypt(f,n.gistId,r||void 0)}),fe("syncBoardDeletion: Manifest 已加密更新"),Jr("syncBoardDeletion: 画板已移入回收站",{boardId:t}),await this.clearLocalDeletions([t]),{success:!0}}catch(r){return vn("syncBoardDeletion 失败",r instanceof Error?r:new Error(String(r))),{success:!1,error:r instanceof Error?r.message:"同步删除失败"}}}async clearLocalDeletions(t){if(t.length===0)return;const n=await this.getLocalDeletionsPendingSync();t.forEach(r=>n.delete(r)),fe("clearLocalDeletions",{boardIds:t}),await er.set(o2,Object.fromEntries(n))}async scheduleAutoSync(){if(!ai.hasToken()){fe("scheduleAutoSync: No token, skipping");return}const t=await this.getConfig();if(fe("scheduleAutoSync config",{autoSync:t.autoSync,debounceMs:t.autoSyncDebounceMs}),!t.autoSync){fe("scheduleAutoSync: Auto sync disabled, skipping");return}this.autoSyncTimer&&(fe("scheduleAutoSync: Clearing previous timer"),clearTimeout(this.autoSyncTimer)),this.autoSyncTimer=setTimeout(async()=>{fe("Auto sync timer fired",{pendingChanges:this.pendingChanges,syncInProgress:this.syncInProgress}),this.pendingChanges&&!this.syncInProgress?(fe("Auto sync triggered after debounce, pushing local changes to remote..."),await this.pushToRemote()):fe("Auto sync skipped",{pendingChanges:this.pendingChanges,syncInProgress:this.syncInProgress})},t.autoSyncDebounceMs),fe("Auto sync scheduled",{debounceMs:t.autoSyncDebounceMs})}async detectLocalChanges(){const t=await this.getConfig(),n=await Or.collectSyncData();if(!t.gistId||!t.lastSyncTime)return{addedBoards:Array.from(n.boards.keys()),modifiedBoards:[],deletedBoards:[],promptsChanged:!0,tasksChanged:!0};try{const r=await pi.getPassword(),{cryptoService:i}=await xn(async()=>{const{cryptoService:c}=await Promise.resolve().then(()=>sl);return{cryptoService:c}},void 0,import.meta.url),o=await yt.getGistFileContent(_t.MANIFEST);if(!o)return{addedBoards:Array.from(n.boards.keys()),modifiedBoards:[],deletedBoards:[],promptsChanged:!0,tasksChanged:!0};const s=await i.decryptOrPassthrough(o,t.gistId,r||void 0),a=JSON.parse(s),l=Or.compareBoardChanges(n.boards,a,t.lastSyncTime);return{addedBoards:l.toUpload.filter(c=>!a.boards[c]),modifiedBoards:l.toUpload.filter(c=>a.boards[c]),deletedBoards:[],promptsChanged:!0,tasksChanged:!0}}catch(r){return vn("检测变更失败",r instanceof Error?r:new Error(String(r))),{addedBoards:[],modifiedBoards:[],deletedBoards:[],promptsChanged:!1,tasksChanged:!1}}}async resolveConflict(t,n){fe("解决冲突",{conflictId:t.id,resolution:n})}async getDeletedItems(){const t={boards:[],prompts:[],tasks:[]},n=await this.getConfig();if(!n.gistId)return t;try{yt.setGistId(n.gistId);const r=await pi.getPassword(),{cryptoService:i}=await xn(async()=>{const{cryptoService:l}=await Promise.resolve().then(()=>sl);return{cryptoService:l}},void 0,import.meta.url),o=await yt.getGistFileContent(_t.MANIFEST);if(!o)return t;const s=await i.decryptOrPassthrough(o,n.gistId,r||void 0),a=JSON.parse(s);return t.boards=Or.getDeletedBoards(a),a.deletedPrompts&&(t.prompts=a.deletedPrompts),a.deletedTasks&&(t.tasks=a.deletedTasks),fe("getDeletedItems",{boards:t.boards.length,prompts:t.prompts.length,tasks:t.tasks.length}),t}catch(r){return vn("获取已删除项目失败",r instanceof Error?r:new Error(String(r))),t}}async restoreItem(t,n){const r=await this.getConfig();if(!r.gistId)return{success:!1,error:"未配置同步"};try{yt.setGistId(r.gistId);const i=await pi.getPassword(),{cryptoService:o}=await xn(async()=>{const{cryptoService:c}=await Promise.resolve().then(()=>sl);return{cryptoService:c}},void 0,import.meta.url),s=await yt.getGistFileContent(_t.MANIFEST);if(!s)return{success:!1,error:"无法获取远程数据"};const a=await o.decryptOrPassthrough(s,r.gistId,i||void 0);let l=JSON.parse(a);if(t==="board"){const c=l.boards[n];if(!c||!c.deletedAt)return{success:!1,error:"画板不存在或未被删除"};const u=await yt.getGistFileContent(_t.boardFile(n));if(!u)return{success:!1,error:"画板数据不存在"};const d=await o.decryptOrPassthrough(u,r.gistId,i||void 0),f=JSON.parse(d);await Bn.saveBoard(f),l=Or.unmarkBoardAsDeleted(l,n);const p=JSON.stringify(l);return await yt.updateGistFiles({[_t.MANIFEST]:await o.encrypt(p,r.gistId,i||void 0)}),await AG(),Jr("恢复画板成功",{boardId:n}),{success:!0}}else{if(t==="prompt")return{success:!1,error:"提示词恢复功能暂未实现"};if(t==="task")return{success:!1,error:"任务恢复功能暂未实现"}}return{success:!1,error:"未知类型"}}catch(i){return vn("恢复项目失败",i instanceof Error?i:new Error(String(i))),{success:!1,error:i instanceof Error?i.message:"恢复失败"}}}async permanentlyDelete(t,n){const r=await this.getConfig();if(!r.gistId)return{success:!1,error:"未配置同步"};try{yt.setGistId(r.gistId);const i=await pi.getPassword(),{cryptoService:o}=await xn(async()=>{const{cryptoService:c}=await Promise.resolve().then(()=>sl);return{cryptoService:c}},void 0,import.meta.url),s=await yt.getGistFileContent(_t.MANIFEST);if(!s)return{success:!1,error:"无法获取远程数据"};const a=await o.decryptOrPassthrough(s,r.gistId,i||void 0);let l=JSON.parse(a);if(t==="board"){const c=l.boards[n];if(!c||!c.deletedAt)return{success:!1,error:"画板不存在或未被删除"};delete l.boards[n],l.updatedAt=Date.now();const u=JSON.stringify(l),d={[_t.MANIFEST]:await o.encrypt(u,r.gistId,i||void 0)};return await yt.deleteGistFiles([_t.boardFile(n)]),await yt.updateGistFiles(d),Jr("永久删除画板成功",{boardId:n}),{success:!0}}else{if(t==="prompt")return{success:!1,error:"提示词永久删除功能暂未实现"};if(t==="task")return{success:!1,error:"任务永久删除功能暂未实现"}}return{success:!1,error:"未知类型"}}catch(i){return vn("永久删除项目失败",i instanceof Error?i:new Error(String(i))),{success:!1,error:i instanceof Error?i.message:"删除失败"}}}async emptyRecycleBin(){var r,i;const t={success:!1,deletedBoards:0,deletedPrompts:0,deletedTasks:0},n=await this.getConfig();if(!n.gistId)return{...t,error:"未配置同步"};try{yt.setGistId(n.gistId);const o=await pi.getPassword(),{cryptoService:s}=await xn(async()=>{const{cryptoService:v}=await Promise.resolve().then(()=>sl);return{cryptoService:v}},void 0,import.meta.url),a=await yt.getGistFileContent(_t.MANIFEST);if(!a)return{...t,error:"无法获取远程数据"};const l=await s.decryptOrPassthrough(a,n.gistId,o||void 0);let c=JSON.parse(l);const u=[],d=[];for(const[v,w]of Object.entries(c.boards))w.deletedAt&&(u.push(_t.boardFile(v)),d.push(v));for(const v of d)delete c.boards[v];const f=((r=c.deletedPrompts)==null?void 0:r.length)||0,p=((i=c.deletedTasks)==null?void 0:i.length)||0;c.deletedPrompts=[],c.deletedTasks=[],c.updatedAt=Date.now(),u.length>0&&await yt.deleteGistFiles(u);const y=JSON.stringify(c);return await yt.updateGistFiles({[_t.MANIFEST]:await s.encrypt(y,n.gistId,o||void 0)}),t.success=!0,t.deletedBoards=d.length,t.deletedPrompts=f,t.deletedTasks=p,Jr("回收站已清空",t),t}catch(o){return vn("清空回收站失败",o instanceof Error?o:new Error(String(o))),{...t,error:o instanceof Error?o.message:"清空失败"}}}async reset(){await this.saveConfig({gistId:null,lastSyncTime:null,enabled:!1}),yt.setGistId(null),this.setStatus("not_configured")}async disconnect(){ai.clearToken(),await this.reset()}async getLastSyncTime(){return(await this.getConfig()).lastSyncTime}getGistUrl(){return yt.getGistWebUrl()}async listSyncGists(){const t=await yt.listSyncGists(),n=await this.getConfig();return t.map(r=>({id:r.id,description:r.description,createdAt:r.created_at,updatedAt:r.updated_at,filesCount:Object.keys(r.files).length,url:`https://gist.github.com/${r.id}`,isCurrent:r.id===n.gistId,isMaster:yt.isGistMaster(r)}))}async switchToGist(t){return await this.saveConfig({gistId:t,lastSyncTime:null,enabled:!0}),yt.setGistId(t),this.sync()}async deleteGist(t){(await this.getConfig()).gistId===t&&await this.reset(),await yt.deleteGist(t)}async createNewGist(){const t=Date.now(),n={success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0};try{this.setStatus("syncing","正在创建新的 Gist..."),await this.saveConfig({gistId:null,lastSyncTime:null,enabled:!0}),yt.setGistId(null);const r=await Or.collectSyncData();fe("创建新 Gist");const o=(await yt.createSyncGist({"manifest.json":JSON.stringify({version:1,initializing:!0},null,2)})).id;fe("空 Gist 已创建",{gistId:xa(o)});const s=await pi.getPassword();fe("使用自定义密码创建 Gist",{hasPassword:!!s});const a=await Or.serializeToGistFilesEncrypted(r,o,s||void 0);yt.setGistId(o),await yt.updateGistFiles(a);try{const c=await Kl.syncTasks(o,s||void 0);n.uploaded.tasks=c.uploaded}catch(c){Pt("创建新 Gist: Tasks paged sync failed",{error:String(c)})}await this.saveConfig({gistId:o,lastSyncTime:Date.now(),enabled:!0}),n.uploaded.boards=r.boards.size,n.uploaded.prompts=r.prompts.promptHistory.length+r.prompts.videoPromptHistory.length+r.prompts.imagePromptHistory.length,n.success=!0,this.setStatus("synced"),this.pendingChanges=!1,Jr("新 Gist 创建成功");const l=r.workspace.currentBoardId;l&&n.uploaded.boards>0&&this.syncCurrentBoardMediaAsync(l)}catch(r){vn("创建新 Gist 失败",r instanceof Error?r:new Error(String(r))),n.error=r instanceof Error?r.message:"创建失败",this.setStatus("error",n.error)}finally{n.duration=Date.now()-t}return n}async initializeShardingSystem(t){try{const{shardedMediaSyncAdapter:n}=await xn(async()=>{const{shardedMediaSyncAdapter:i}=await Promise.resolve().then(()=>Qle);return{shardedMediaSyncAdapter:i}},void 0,import.meta.url);if(n.isShardingEnabled()){fe("分片系统已启用");return}fe("初始化分片系统",{gistId:xa(t)});const r=await n.setupShardSystem(t);r.success?Jr("分片系统初始化成功"):Pt("分片系统初始化失败",{error:r.error})}catch(n){vn("分片系统初始化错误",n instanceof Error?n:new Error(String(n)))}}async syncPaged(){const t={success:!1,tasksUploaded:0,tasksDownloaded:0,workflowsUploaded:0,workflowsDownloaded:0,tasksSkipped:0,workflowsSkipped:0};try{const n=await this.getConfig();if(!n.gistId)return t.error="未配置 Gist ID",t;const r=await pi.getPassword();Tr("开始分页同步",{gistId:xa(n.gistId)});try{const i=await Kl.syncTasks(n.gistId,r||void 0);t.tasksUploaded=i.uploaded,t.tasksDownloaded=i.downloaded,t.tasksSkipped=i.skipped}catch(i){Pt("任务同步失败",{error:String(i)})}try{const i=await Eet.syncWorkflows(n.gistId,r||void 0);t.workflowsUploaded=i.uploaded,t.workflowsDownloaded=i.downloaded,t.workflowsSkipped=i.skipped}catch(i){Pt("工作流同步失败",{error:String(i)})}try{const i=await Ket.syncTools(n.gistId,r||void 0);fe("自定义工具同步结果",i)}catch(i){Pt("自定义工具同步失败",{error:String(i)})}t.success=!0,Jr("分页同步完成",{tasksUploaded:t.tasksUploaded,tasksDownloaded:t.tasksDownloaded,tasksSkipped:t.tasksSkipped,workflowsUploaded:t.workflowsUploaded,workflowsDownloaded:t.workflowsDownloaded,workflowsSkipped:t.workflowsSkipped})}catch(n){t.error=n instanceof Error?n.message:String(n),vn("分页同步失败",n instanceof Error?n:new Error(String(n)))}return t}async detectRemoteTaskFormat(){try{const t=await this.getConfig();return t.gistId?(yt.setGistId(t.gistId),(await yt.getGist()).files[li.TASK_INDEX]?"paged":"none"):"none"}catch(t){return Pt("检测远程格式失败",{error:t instanceof Error?t.message:String(t)}),"none"}}destroy(){this.autoSyncTimer&&(clearTimeout(this.autoSyncTimer),this.autoSyncTimer=null),this.statusListeners.clear()}}const Kn=new qet,IV=Object.freeze(Object.defineProperty({__proto__:null,syncEngine:Kn},Symbol.toStringTag,{value:"Module"}));function Gp(e,t,n){let r=n.initialDeps??[],i,o=!0;function s(){var a,l,c;let u;n.key&&((a=n.debug)!=null&&a.call(n))&&(u=Date.now());const d=e();if(!(d.length!==r.length||d.some((y,v)=>r[v]!==y)))return i;r=d;let p;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(p=Date.now()),i=t(...d),n.key&&((c=n.debug)!=null&&c.call(n))){const y=Math.round((Date.now()-u)*100)/100,v=Math.round((Date.now()-p)*100)/100,w=v/16,C=(x,E)=>{for(x=String(x);x.length<E;)x=" "+x;return x};console.info(`%c⏱ ${C(v,5)} /${C(y,5)} ms`,`
|
|
2587
|
+
`;const o=i+t.content;return{filename:`${t.title.replace(/[/\\?%*:|"<>]/g,"_")||"untitled"}.md`,content:o}}async function Net(e,t,n){let r=(n==null?void 0:n.replace(/\.md$/i,""))||"导入的笔记",i=e;const o=[],s=e.match(/^---\n([\s\S]*?)\n---\n*([\s\S]*)$/);if(s){const u=s[1];i=s[2];const d=u.match(/^title:\s*"?([^"\n]+)"?$/m);d&&(r=d[1].trim());const f=u.match(/^tags:\s*\[([^\]]*)\]$/m);if(f){const y=f[1].match(/"([^"]+)"/g);if(y)for(const v of y)o.push(v.replace(/"/g,""))}}const a=await my(t),l=a.filter(u=>u.title===r);if(l.length>0){for(const f of l){const p=await vc(f.id);if(p&&p.content===i)return null}let u=1,d=`${r} (${u})`;for(;a.some(f=>f.title===d);)u++,d=`${r} (${u})`;r=d}const c=await Wd(r,t,i);for(const u of o){const d=await bw(u);await gy(c.id,d.id)}return c}class jet{async getLocalData(){return await Oet()}merge(t,n){fe("Merging knowledge base data",{localDirs:t.directories.length,remoteDirs:n.directories.length,localNotes:t.notes.length,remoteNotes:n.notes.length});const r=new Map,i=new Map,o=new Map,s=f=>{if(r.has(f.id)){const p=r.get(f.id);f.updatedAt>p.updatedAt&&(r.set(f.id,f),p.name!==f.name&&i.set(f.name,f.id));return}if(i.has(f.name)){const p=i.get(f.name),y=r.get(p);o.set(f.id,p);let v={...y};f.updatedAt>y.updatedAt&&(v={...f,id:p}),(f.isDefault||y.isDefault)&&(v.isDefault=!0),r.set(p,v);return}r.set(f.id,f),i.set(f.name,f.id)};n.directories.forEach(s),t.directories.forEach(s);const a=new Map;n.tags.forEach(f=>a.set(f.id,f)),t.tags.forEach(f=>{a.get(f.id),a.set(f.id,f)});const l=new Map,c=f=>{let p=f.directoryId;o.has(p)&&(p=o.get(p));const y={...f,directoryId:p},v=l.get(y.id);(!v||y.updatedAt>v.updatedAt)&&l.set(y.id,y)};n.notes.forEach(c),t.notes.forEach(c);const u=new Map;n.noteTags.forEach(f=>u.set(f.id,f)),t.noteTags.forEach(f=>u.set(f.id,f));const d=new Map;return n.images&&n.images.forEach(f=>d.set(f.id,f)),t.images&&t.images.forEach(f=>{d.set(f.id,f)}),{version:2,exportedAt:Date.now(),directories:Array.from(r.values()),notes:Array.from(l.values()),tags:Array.from(a.values()),noteTags:Array.from(u.values()),images:Array.from(d.values())}}async apply(t){const{directoriesStore:n,notesStore:r,noteContentsStore:i,tagsStore:o,noteTagsStore:s,noteImagesStore:a}=yw();Tr("Applying knowledge base sync data",{dirs:t.directories.length,notes:t.notes.length});for(const l of t.directories)await n.setItem(l.id,l);for(const l of t.tags)await o.setItem(l.id,l);for(const l of t.notes){const{content:c,...u}=l;await r.setItem(l.id,u),c!==void 0&&await i.setItem(l.id,{id:l.id,noteId:l.id,content:c})}for(const l of t.noteTags)await s.setItem(l.id,l);if(t.images&&a)for(const l of t.images)await a.setItem(l.id,l)}}const Bf=new jet;function bV(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(36)}function Let(){let e=localStorage.getItem(bd);return e||(e=`${Date.now().toString(36)}-${Math.random().toString(36).substring(2,9)}`,localStorage.setItem(bd,e)),e}function Bet(){const e=navigator.userAgent;return/iPhone|iPad|iPod/.test(e)?"iOS Device":/Android/.test(e)?"Android Device":/Macintosh|Mac OS X/.test(e)?"Mac":/Windows/.test(e)?"Windows PC":/Linux/.test(e)?"Linux":navigator.platform||"Unknown"}class Fet{async collectSyncData(){const[t,n,r]=await Promise.all([Bn.loadAllFolders(),Bn.loadAllBoards(),Bn.loadState()]);await w_();const i=Lne(),o=n4(),s=r4(),l=(await Ks.getAllTasks()).filter(C=>C.status===un.COMPLETED&&(C.type===Qt.IMAGE||C.type===Qt.VIDEO)),c=await Bf.getLocalData(),u={},d=new Map;let f=0;for(const C of n){const x=JSON.stringify(C.elements);u[C.id]={name:C.name,updatedAt:C.updatedAt,checksum:bV(x)},d.set(C.id,C),f++,f%5===0&&await Wo()}const p={folders:t,boardMetadata:n.map(C=>this.extractBoardMetadata(C)),currentBoardId:(r==null?void 0:r.currentBoardId)||null,expandedFolders:(r==null?void 0:r.expandedFolderIds)||[]},y=Let(),v=Date.now();return{manifest:{version:net,appVersion:Ove.app,createdAt:v,updatedAt:v,deviceId:y,devices:{[y]:{name:Bet(),lastSyncTime:v}},boards:u},workspace:p,boards:d,prompts:{promptHistory:i,videoPromptHistory:o,imagePromptHistory:s},tasks:{completedTasks:l},knowledgeBase:c}}async collectSyncDataPaged(){const t=await this.collectSyncData(),{index:n,pages:r}=_le(t.tasks.completedTasks),o=(await Ile.getAllWorkflows()).filter(l=>l.status==="completed"||l.status==="failed"||l.status==="cancelled"),{index:s,pages:a}=Ple(o);return fe("DataSerializer: Collected paged sync data",{boards:t.boards.size,taskPages:r.length,taskItems:n.items.length,workflowPages:a.length,workflowItems:s.items.length,knowledgeBase:t.knowledgeBase?{notes:t.knowledgeBase.notes.length,directories:t.knowledgeBase.directories.length}:"NULL"}),{manifest:t.manifest,workspace:t.workspace,boards:t.boards,prompts:t.prompts,taskIndex:n,taskPages:r,workflowIndex:s,workflowPages:a,knowledgeBase:t.knowledgeBase}}extractBoardMetadata(t){return{id:t.id,name:t.name,folderId:t.folderId,order:t.order,viewport:t.viewport,theme:t.theme,createdAt:t.createdAt,updatedAt:t.updatedAt}}serializeToGistFiles(t){const n={};n[_t.MANIFEST]=JSON.stringify(t.manifest,null,2),n[_t.WORKSPACE]=JSON.stringify(t.workspace,null,2);for(const[r,i]of t.boards)n[_t.boardFile(r)]=JSON.stringify(i,null,2);return n[_t.PROMPTS]=JSON.stringify(t.prompts,null,2),t.knowledgeBase&&(n[_t.KNOWLEDGE_BASE]=JSON.stringify(t.knowledgeBase,null,2)),n}async serializeToGistFilesEncrypted(t,n,r){const i={},o=JSON.stringify(t.manifest);i[_t.MANIFEST]=await Nn.encrypt(o,n,r);const s=JSON.stringify(t.workspace);i[_t.WORKSPACE]=await Nn.encrypt(s,n,r);let a=0;for(const[c,u]of t.boards){const d=JSON.stringify(u);i[_t.boardFile(c)]=await Nn.encrypt(d,n,r),a++,a%3===0&&await Wo()}const l=JSON.stringify(t.prompts);if(i[_t.PROMPTS]=await Nn.encrypt(l,n,r),t.knowledgeBase){const c=JSON.stringify(t.knowledgeBase);i[_t.KNOWLEDGE_BASE]=await Nn.encrypt(c,n,r)}return i}async serializeToGistFilesPagedEncrypted(t,n,r){const i={},o=JSON.stringify(t.manifest);i[_t.MANIFEST]=await Nn.encrypt(o,n,r);const s=JSON.stringify(t.workspace);i[_t.WORKSPACE]=await Nn.encrypt(s,n,r);let a=0;for(const[p,y]of t.boards){const v=JSON.stringify(y);i[_t.boardFile(p)]=await Nn.encrypt(v,n,r),a++,a%3===0&&await Wo()}const l=JSON.stringify(t.prompts);if(i[_t.PROMPTS]=await Nn.encrypt(l,n,r),t.knowledgeBase){const p=JSON.stringify(t.knowledgeBase);i[_t.KNOWLEDGE_BASE]=await Nn.encrypt(p,n,r)}const c=JSON.stringify(t.taskIndex);i[li.TASK_INDEX]=await Nn.encrypt(c,n,r);let u=0;for(const p of t.taskPages){const y=JSON.stringify(p),v=li.taskPageFile(p.pageId);i[v]=await Nn.encrypt(y,n,r),u++,u%3===0&&await Wo()}const d=JSON.stringify(t.workflowIndex);i[li.WORKFLOW_INDEX]=await Nn.encrypt(d,n,r);let f=0;for(const p of t.workflowPages){const y=JSON.stringify(p),v=li.workflowPageFile(p.pageId);i[v]=await Nn.encrypt(y,n,r),f++,f%3===0&&await Wo()}return fe("DataSerializer: Serialized paged files",{totalFiles:Object.keys(i).length,taskPages:t.taskPages.length,workflowPages:t.workflowPages.length}),i}deserializeFromGistFiles(t){var r;const n={manifest:null,workspace:null,boards:new Map,prompts:null,tasks:null,knowledgeBase:null};if(t[_t.MANIFEST])try{n.manifest=JSON.parse(t[_t.MANIFEST])}catch(i){Pt("DataSerializer: Failed to parse manifest:",{error:String(i)})}if(t[_t.WORKSPACE])try{n.workspace=JSON.parse(t[_t.WORKSPACE])}catch(i){Pt("DataSerializer: Failed to parse workspace:",{error:String(i)})}for(const[i,o]of Object.entries(t))if(i.startsWith("board_")&&i.endsWith(".json"))try{const s=JSON.parse(o);fe(`DataSerializer: Parsed board ${i}:`,{id:s.id,name:s.name,elements:((r=s.elements)==null?void 0:r.length)||0,hasElements:!!s.elements,viewport:s.viewport}),n.boards.set(s.id,s)}catch(s){Pt(`DataSerializer: Failed to parse board ${i}:`,{error:String(s)})}if(t[_t.PROMPTS])try{n.prompts=JSON.parse(t[_t.PROMPTS])}catch(i){Pt("DataSerializer: Failed to parse prompts:",{error:String(i)})}if(t[_t.KNOWLEDGE_BASE])try{n.knowledgeBase=JSON.parse(t[_t.KNOWLEDGE_BASE])}catch(i){Pt("DataSerializer: Failed to parse knowledge base:",{error:String(i)})}return n}async deserializeFromGistFilesWithDecryption(t,n,r){var s,a,l,c,u,d,f,p,y,v,w,C,x,E,_,I,D,P,k,R,T;fe("DataSerializer: ========== deserializeFromGistFilesWithDecryption START =========="),fe("DataSerializer: Input files:",{fileCount:Object.keys(t).length,fileNames:Object.keys(t),fileSizes:Object.fromEntries(Object.entries(t).map(([M,F])=>[M,(F==null?void 0:F.length)||0]))}),fe("DataSerializer: gistId:",{id:(n==null?void 0:n.substring(0,8))+"..."}),fe("DataSerializer: customPassword:",{status:r?"***SET***":"NOT SET"});const i={manifest:null,workspace:null,boards:new Map,prompts:null,tasks:null,knowledgeBase:null};if(t[_t.MANIFEST]){fe("DataSerializer: Parsing manifest",{encrypted:cd(t[_t.MANIFEST])});try{const M=await Nn.decryptOrPassthrough(t[_t.MANIFEST],n,r);i.manifest=JSON.parse(M),fe("DataSerializer: Manifest parsed successfully:",{version:(s=i.manifest)==null?void 0:s.version,boardsCount:(a=i.manifest)!=null&&a.boards?Object.keys(i.manifest.boards).length:0,boardIds:(l=i.manifest)!=null&&l.boards?Object.keys(i.manifest.boards):[]})}catch(M){if(M instanceof Error&&M.name==="DecryptionError")throw M;Pt("DataSerializer: Failed to parse manifest:",{error:String(M)})}}else Pt("DataSerializer: Manifest file NOT FOUND in input files!");if(fe("DataSerializer: Deserializing with customPassword",{enabled:!!r}),t[_t.WORKSPACE]){fe("DataSerializer: Parsing workspace",{encrypted:cd(t[_t.WORKSPACE])});try{const M=await Nn.decryptOrPassthrough(t[_t.WORKSPACE],n,r);fe("DataSerializer: Workspace decrypted content length",{length:M.length}),i.workspace=JSON.parse(M),fe("DataSerializer: Workspace parsed successfully:",{currentBoardId:(c=i.workspace)==null?void 0:c.currentBoardId,folders:((d=(u=i.workspace)==null?void 0:u.folders)==null?void 0:d.length)||0,boardMetadata:((p=(f=i.workspace)==null?void 0:f.boardMetadata)==null?void 0:p.length)||0,boardMetadataIds:((v=(y=i.workspace)==null?void 0:y.boardMetadata)==null?void 0:v.map(F=>F.id))||[]})}catch(M){if(M instanceof Error&&M.name==="DecryptionError")throw M;Pt("DataSerializer: Failed to parse workspace:",{error:String(M)})}}else Pt("DataSerializer: Workspace file NOT FOUND in input files!");fe("DataSerializer: Parsing boards...");let o=0;for(const[M,F]of Object.entries(t))if(M.startsWith("board_")&&M.endsWith(".json")){o++,fe("DataSerializer: Processing board file",{filename:M,length:(F==null?void 0:F.length)||0});try{const V=await Nn.decryptOrPassthrough(F,n,r);fe("DataSerializer: Board decrypted",{filename:M,length:V.length});const H=JSON.parse(V);fe(`DataSerializer: Parsed board ${M}:`,{id:H.id,name:H.name,elements:((w=H.elements)==null?void 0:w.length)||0,hasElements:!!H.elements,viewport:H.viewport}),i.boards.set(H.id,H)}catch(V){if(V instanceof Error&&V.name==="DecryptionError")throw V;Pt(`DataSerializer: Failed to parse board ${M}:`,{error:String(V)})}}if(fe("DataSerializer: Board files found",{found:o,parsed:i.boards.size}),t[_t.PROMPTS]){fe("DataSerializer: Parsing prompts",{encrypted:cd(t[_t.PROMPTS])});try{const M=await Nn.decryptOrPassthrough(t[_t.PROMPTS],n,r);i.prompts=JSON.parse(M),fe("DataSerializer: Prompts parsed successfully:",{promptHistory:((x=(C=i.prompts)==null?void 0:C.promptHistory)==null?void 0:x.length)||0,videoPromptHistory:((_=(E=i.prompts)==null?void 0:E.videoPromptHistory)==null?void 0:_.length)||0,imagePromptHistory:((D=(I=i.prompts)==null?void 0:I.imagePromptHistory)==null?void 0:D.length)||0})}catch(M){if(M instanceof Error&&M.name==="DecryptionError")throw M;Pt("DataSerializer: Failed to parse prompts:",{error:String(M)})}}else Pt("DataSerializer: Prompts file NOT FOUND in input files!");if(t[_t.KNOWLEDGE_BASE]){fe("DataSerializer: Parsing knowledge base",{encrypted:cd(t[_t.KNOWLEDGE_BASE])});try{const M=await Nn.decryptOrPassthrough(t[_t.KNOWLEDGE_BASE],n,r);i.knowledgeBase=JSON.parse(M),fe("DataSerializer: Knowledge base parsed successfully:",{directories:((k=(P=i.knowledgeBase)==null?void 0:P.directories)==null?void 0:k.length)||0,notes:((T=(R=i.knowledgeBase)==null?void 0:R.notes)==null?void 0:T.length)||0})}catch(M){if(M instanceof Error&&M.name==="DecryptionError")throw M;Pt("DataSerializer: Failed to parse knowledge base:",{error:String(M)})}}return fe("DataSerializer: ========== deserializeFromGistFilesWithDecryption END =========="),fe("DataSerializer: Final result:",{hasManifest:!!i.manifest,hasWorkspace:!!i.workspace,boardsCount:i.boards.size,boardIds:Array.from(i.boards.keys()),hasPrompts:!!i.prompts,hasTasks:!!i.tasks}),i}async deserializeFromGistFilesPagedWithDecryption(t,n,r){var o,s,a,l,c,u,d,f;fe("DataSerializer: ========== deserializeFromGistFilesPagedWithDecryption START ==========");const i={manifest:null,workspace:null,boards:new Map,prompts:null,taskIndex:null,taskPages:new Map,workflowIndex:null,workflowPages:new Map,knowledgeBase:null};if(t[_t.MANIFEST])try{const p=await Nn.decryptOrPassthrough(t[_t.MANIFEST],n,r);i.manifest=JSON.parse(p)}catch(p){if(p instanceof Error&&p.name==="DecryptionError")throw p;Pt("DataSerializer: Failed to parse manifest:",{error:String(p)})}if(t[_t.WORKSPACE])try{const p=await Nn.decryptOrPassthrough(t[_t.WORKSPACE],n,r);i.workspace=JSON.parse(p)}catch(p){if(p instanceof Error&&p.name==="DecryptionError")throw p;Pt("DataSerializer: Failed to parse workspace:",{error:String(p)})}for(const[p,y]of Object.entries(t))if(p.startsWith("board_")&&p.endsWith(".json"))try{const v=await Nn.decryptOrPassthrough(y,n,r),w=JSON.parse(v);i.boards.set(w.id,w)}catch(v){if(v instanceof Error&&v.name==="DecryptionError")throw v;Pt(`DataSerializer: Failed to parse board ${p}:`,{error:String(v)})}if(t[_t.PROMPTS])try{const p=await Nn.decryptOrPassthrough(t[_t.PROMPTS],n,r);i.prompts=JSON.parse(p)}catch(p){if(p instanceof Error&&p.name==="DecryptionError")throw p;Pt("DataSerializer: Failed to parse prompts:",{error:String(p)})}if(t[li.TASK_INDEX])try{const p=await Nn.decryptOrPassthrough(t[li.TASK_INDEX],n,r);i.taskIndex=JSON.parse(p),fe("DataSerializer: Parsed task index:",{items:((s=(o=i.taskIndex)==null?void 0:o.items)==null?void 0:s.length)||0,pages:((l=(a=i.taskIndex)==null?void 0:a.pages)==null?void 0:l.length)||0})}catch(p){if(p instanceof Error&&p.name==="DecryptionError")throw p;Pt("DataSerializer: Failed to parse task index:",{error:String(p)})}for(const[p,y]of Object.entries(t))if(li.isTaskPageFile(p))try{const v=await Nn.decryptOrPassthrough(y,n,r),w=JSON.parse(v);i.taskPages.set(w.pageId,w)}catch(v){if(v instanceof Error&&v.name==="DecryptionError")throw v;Pt(`DataSerializer: Failed to parse task page ${p}:`,{error:String(v)})}if(t[li.WORKFLOW_INDEX])try{const p=await Nn.decryptOrPassthrough(t[li.WORKFLOW_INDEX],n,r);i.workflowIndex=JSON.parse(p),fe("DataSerializer: Parsed workflow index:",{items:((u=(c=i.workflowIndex)==null?void 0:c.items)==null?void 0:u.length)||0,pages:((f=(d=i.workflowIndex)==null?void 0:d.pages)==null?void 0:f.length)||0})}catch(p){if(p instanceof Error&&p.name==="DecryptionError")throw p;Pt("DataSerializer: Failed to parse workflow index:",{error:String(p)})}for(const[p,y]of Object.entries(t))if(li.isWorkflowPageFile(p))try{const v=await Nn.decryptOrPassthrough(y,n,r),w=JSON.parse(v);i.workflowPages.set(w.pageId,w)}catch(v){if(v instanceof Error&&v.name==="DecryptionError")throw v;Pt(`DataSerializer: Failed to parse workflow page ${p}:`,{error:String(v)})}if(t[_t.KNOWLEDGE_BASE])try{const p=await Nn.decryptOrPassthrough(t[_t.KNOWLEDGE_BASE],n,r);i.knowledgeBase=JSON.parse(p)}catch(p){if(p instanceof Error&&p.name==="DecryptionError")throw p;Pt("DataSerializer: Failed to parse knowledge base:",{error:String(p)})}return fe("DataSerializer: ========== deserializeFromGistFilesPagedWithDecryption END =========="),fe("DataSerializer: Paged result:",{hasManifest:!!i.manifest,hasWorkspace:!!i.workspace,boardsCount:i.boards.size,hasPrompts:!!i.prompts,hasTaskIndex:!!i.taskIndex,taskPagesCount:i.taskPages.size,hasWorkflowIndex:!!i.workflowIndex,workflowPagesCount:i.workflowPages.size,hasKnowledgeBase:!!i.knowledgeBase}),i}async applySyncData(t){var f,p,y,v,w,C,x,E,_,I,D,P,k,R,T,M,F,V,H;fe("DataSerializer: ========== applySyncData START =========="),fe("DataSerializer: applySyncData called with:",{hasWorkspace:!!t.workspace,workspace:t.workspace?{currentBoardId:t.workspace.currentBoardId,folders:((f=t.workspace.folders)==null?void 0:f.length)||0,boardMetadata:((p=t.workspace.boardMetadata)==null?void 0:p.length)||0,boardMetadataIds:((y=t.workspace.boardMetadata)==null?void 0:y.map(j=>j.id))||[]}:"NULL",boardsCount:t.boards.size,boardIds:Array.from(t.boards.keys()),hasPrompts:!!t.prompts,prompts:t.prompts?{promptHistory:((v=t.prompts.promptHistory)==null?void 0:v.length)||0,videoPromptHistory:((w=t.prompts.videoPromptHistory)==null?void 0:w.length)||0,imagePromptHistory:((C=t.prompts.imagePromptHistory)==null?void 0:C.length)||0}:"NULL",hasTasks:!!t.tasks,tasks:t.tasks?{completedTasks:((x=t.tasks.completedTasks)==null?void 0:x.length)||0}:"NULL",hasKnowledgeBase:!!t.knowledgeBase,deletedBoardIds:((E=t.deletedBoardIds)==null?void 0:E.length)||0,deletedPromptIds:((_=t.deletedPromptIds)==null?void 0:_.length)||0,deletedTaskIds:((I=t.deletedTaskIds)==null?void 0:I.length)||0});let n=0,r=0,i=0,o=0,s=0,a=0,l=0;if(t.workspace){fe("DataSerializer: Applying folders:",{count:t.workspace.folders.length});for(const j of t.workspace.folders)await Bn.saveFolder(j)}fe("DataSerializer: Applying boards...");for(const[j,z]of t.boards){fe(`DataSerializer: Saving board: ${j} - ${z.name}, elements: ${((D=z.elements)==null?void 0:D.length)||0}`,{folderId:z.folderId,viewport:z.viewport,createdAt:z.createdAt,updatedAt:z.updatedAt}),await Bn.saveBoard(z);const N=await Bn.loadBoard(j);fe(`DataSerializer: Verified saved board: ${j}`,{found:!!N,elements:((P=N==null?void 0:N.elements)==null?void 0:P.length)||0}),n++}if(fe("DataSerializer: Boards applied:",{count:n}),t.deletedBoardIds&&t.deletedBoardIds.length>0){fe("DataSerializer: Deleting boards:",{ids:t.deletedBoardIds});for(const j of t.deletedBoardIds)try{await Bn.deleteBoard(j),s++,fe(`DataSerializer: Deleted board: ${j}`)}catch(z){Pt(`DataSerializer: Failed to delete board ${j}:`,{error:String(z)})}fe("DataSerializer: Boards deleted:",{count:s})}if(n>0){fe("DataSerializer: ========== RELOAD WORKSPACE START =========="),fe("DataSerializer: Calling workspaceService.reload()..."),await AG(),fe("DataSerializer: workspaceService.reload() completed");const j=yhe();fe("DataSerializer: Workspace reloaded, boards in memory:",{count:j.length,ids:j.map(z=>z.id),names:j.map(z=>z.name)}),fe("DataSerializer: Verifying all saved boards in storage...");for(const z of t.boards.keys()){const N=await Bn.loadBoard(z);fe(`DataSerializer: VERIFY board ${z}:`,{foundInStorage:!!N,name:(N==null?void 0:N.name)||"N/A",elements:((k=N==null?void 0:N.elements)==null?void 0:k.length)||0})}if((R=t.workspace)!=null&&R.currentBoardId){fe("DataSerializer: Setting currentBoardId from remote:",{id:t.workspace.currentBoardId});const z=ghe();fe("DataSerializer: Current state before update:",{state:z}),await Bn.saveState({...z,currentBoardId:t.workspace.currentBoardId}),fe("DataSerializer: Saved workspace state with currentBoardId");const N=await Bn.loadState();fe("DataSerializer: VERIFY state after save:",{currentBoardId:N.currentBoardId,match:N.currentBoardId===t.workspace.currentBoardId})}fe("DataSerializer: ========== RELOAD WORKSPACE END ==========")}if(t.prompts&&(t.prompts.promptHistory&&t.prompts.promptHistory.length>0&&(r+=v$e(t.prompts.promptHistory)),t.prompts.videoPromptHistory&&t.prompts.videoPromptHistory.length>0&&(r+=_$e(t.prompts.videoPromptHistory)),t.prompts.imagePromptHistory&&t.prompts.imagePromptHistory.length>0&&(r+=k$e(t.prompts.imagePromptHistory))),fe("DataSerializer: Applying tasks...",{hasTasks:!!t.tasks,completedTasksCount:((M=(T=t.tasks)==null?void 0:T.completedTasks)==null?void 0:M.length)||0}),t.tasks&&t.tasks.completedTasks&&t.tasks.completedTasks.length>0){const j=await Ks.getAllTasks(),z=new Map(j.map(B=>[B.id,B]));fe("DataSerializer: Local tasks:",{count:j.length,ids:Array.from(z.keys()).slice(0,5)});const N=[];for(const B of t.tasks.completedTasks){const O=z.get(B.id);O?B.updatedAt&&O.updatedAt&&B.updatedAt>O.updatedAt&&N.push(B):N.push(B)}if(fe("DataSerializer: Tasks to restore after merge:",{count:N.length,ids:N.slice(0,5).map(B=>B.id)}),N.length>0){const B=N.map(O=>{var $;return($=O.result)!=null&&$.url&&Zf(O.result.url)?{...O,result:{...O.result,needsMediaDownload:!0}}:O});fe("DataSerializer: Calling restoreTasks with tasks",{count:B.length});try{Mi.restoreTasks(B),i=B.length,fe("DataSerializer: Tasks restored:",{count:i})}catch(O){Pt("DataSerializer: Failed to restore tasks (SW may not be ready):",{error:String(O)}),i=0}}}else fe("DataSerializer: No tasks to apply");if(t.knowledgeBase){fe("DataSerializer: Applying knowledge base...");try{await Bf.apply(t.knowledgeBase),o=(((F=t.knowledgeBase.notes)==null?void 0:F.length)||0)+(((V=t.knowledgeBase.directories)==null?void 0:V.length)||0),fe("DataSerializer: Knowledge base applied successfully")}catch(j){Pt("DataSerializer: Failed to apply knowledge base:",{error:String(j)})}}const c=((H=t.workspace)==null?void 0:H.currentBoardId)||null;fe("DataSerializer: ========== applySyncData END =========="),fe("DataSerializer: applySyncData completed:",{boardsApplied:n,promptsApplied:r,tasksApplied:i,knowledgeBaseApplied:o,boardsDeleted:s,promptsDeleted:a,tasksDeleted:l,remoteCurrentBoardId:c});const u=await Bn.loadState();fe("DataSerializer: Final workspace state in storage:",{currentBoardId:u.currentBoardId,expected:c,match:u.currentBoardId===c});const d=await Bn.loadAllBoards();return fe("DataSerializer: Final boards in storage:",{count:d.length,ids:d.map(j=>j.id),names:d.map(j=>j.name)}),{boardsApplied:n,promptsApplied:r,tasksApplied:i,knowledgeBaseApplied:o,boardsDeleted:s,promptsDeleted:a,tasksDeleted:l,remoteCurrentBoardId:c}}calculateBoardChecksum(t){const n=JSON.stringify(t.elements);return bV(n)}mergeBoardElements(t,n){const r=t.elements||[],i=n.elements||[],o=new Map,s=new Map;for(const y of r)y.id&&o.set(y.id,y);for(const y of i)y.id&&s.set(y.id,y);const a=[],l=[];let c=0,u=0,d=0;const f=new Set;for(const y of r){if(!y.id){a.push(y);continue}f.add(y.id);const v=s.get(y.id);if(!v)a.push(y),c++;else{const w=JSON.stringify(y),C=JSON.stringify(v);w===C?a.push(y):(a.push(y),l.push({elementId:y.id,localElement:y,remoteElement:v}),d++)}}for(const y of i)!y.id||f.has(y.id)||(a.push(y),u++);return{mergedBoard:{...t,elements:a,updatedAt:Math.max(t.updatedAt,n.updatedAt)},hasConflicts:l.length>0,conflictingElements:l,addedFromLocal:c,addedFromRemote:u,updated:d}}compareBoardChanges(t,n,r){const i=[],o=[],s=[],a=[],l=new Set(t.keys()),c=new Set(Object.keys(n.boards));for(const[u,d]of t){const f=n.boards[u],p=this.calculateBoardChecksum(d);f?f.deletedAt?a.push(u):p!==f.checksum&&(r?d.updatedAt>r&&f.updatedAt>r?s.push(u):d.updatedAt>r?i.push(u):o.push(u):!d.elements||d.elements.length===0?(fe(`Sync: Initial sync: Local board ${u} is empty, preferring remote version.`),o.push(u)):d.updatedAt>f.updatedAt?i.push(u):o.push(u)):i.push(u)}for(const u of c)l.has(u)||n.boards[u].deletedAt||o.push(u);return{toUpload:i,toDownload:o,conflicts:s,toDeleteLocally:a}}detectDeletions(t,n){const r=[],i=[],o=[];if(!n)return{deletedBoards:r,deletedPrompts:i,deletedTasks:o};for(const[s,a]of Object.entries(n.boards))a.deletedAt||t.boards.has(s)||r.push({id:s,name:a.name});return fe("DataSerializer: detectDeletions result:",{deletedBoards:r.length,deletedPrompts:i.length,deletedTasks:o.length}),{deletedBoards:r,deletedPrompts:i,deletedTasks:o}}markBoardsAsDeleted(t,n,r){const i=Date.now(),o={...t};for(const s of n)o.boards[s.id]?o.boards[s.id]={...o.boards[s.id],deletedAt:i,deletedBy:r}:o.boards[s.id]={name:s.name,updatedAt:i,checksum:"",deletedAt:i,deletedBy:r};return o.updatedAt=i,o}unmarkBoardAsDeleted(t,n){const r={...t};if(r.boards[n]){const{deletedAt:i,deletedBy:o,...s}=r.boards[n];r.boards[n]=s}return r.updatedAt=Date.now(),r}getDeletedBoards(t){const n=[];for(const[r,i]of Object.entries(t.boards))i.deletedAt&&i.deletedBy&&n.push({id:r,name:i.name,deletedAt:i.deletedAt,deletedBy:i.deletedBy});return n.sort((r,i)=>i.deletedAt-r.deletedAt),n}}const Or=new Fet;function Tle(e){return iI(e)}function Dle(e){return e.startsWith("http://")||e.startsWith("https://")}function Mle(e,t,n){return e?t==="local"?n==="image"?"current_board_local_image":"current_board_local_video":n==="image"?"current_board_url_image":"current_board_url_video":t==="local"?n==="image"?"other_local_image":"other_local_video":n==="image"?"other_url_image":"other_url_video"}const xV={current_board_local_image:1,current_board_local_video:2,current_board_url_image:3,current_board_url_video:4,other_local_image:5,other_local_video:6,other_url_image:7,other_url_video:8};function Yk(e){return[...e].sort((t,n)=>xV[t.priority]-xV[n.priority])}function SV(e,t){const n=[],r=e.id===t;if(!e.elements||e.elements.length===0)return n;for(const i of e.elements){const o=i.url;if(!o||typeof o!="string"||o.startsWith("blob:"))continue;const s=Pe.isDrawElement(i)&&Pe.isImage(i),a=xJe(i);if(!s&&!a)continue;const l=a?"video":"image";let c,u;if(Tle(o))c="local";else if(Dle(o))c="external",u=o;else continue;const d=Mle(r,c,l),f=n.findIndex(p=>p.url===o);f>=0?(n[f].boardIds.includes(e.id)||n[f].boardIds.push(e.id),r&&!n[f].isCurrentBoard&&(n[f].isCurrentBoard=!0,n[f].priority=d)):n.push({url:o,type:l,source:c,originalUrl:u,boardIds:[e.id],isCurrentBoard:r,priority:d})}return n}class $et{async collectCurrentBoardMedia(t){const n=await Bn.loadBoard(t);if(!n)return this.createEmptyResult();const r=SV(n,t);await this.enrichMediaMetadata(r);const i=Yk(r.filter(o=>o.isCurrentBoard));return{items:Yk(r),currentBoardItems:i,otherItems:[],stats:this.calculateStats(r)}}async collectAllBoardsMedia(t){const n=await Bn.loadAllBoards(),r=[];for(const a of n){const l=SV(a,t);for(const c of l){const u=r.findIndex(d=>d.url===c.url);if(u>=0){for(const d of c.boardIds)r[u].boardIds.includes(d)||r[u].boardIds.push(d);c.isCurrentBoard&&!r[u].isCurrentBoard&&(r[u].isCurrentBoard=!0,r[u].priority=c.priority)}else r.push(c)}}await this.enrichMediaMetadata(r);const i=Yk(r),o=i.filter(a=>a.isCurrentBoard),s=i.filter(a=>!a.isCurrentBoard);return{items:i,currentBoardItems:o,otherItems:s,stats:this.calculateStats(r)}}async collectAssetLibraryMedia(){await Vs.initialize();const t=await Vs.getAllAssets(),n=[];for(const r of t){const i=r.type==="IMAGE"?"image":"video";n.push({url:r.url,type:i,source:"local",boardIds:[],isCurrentBoard:!1,priority:i==="image"?"other_local_image":"other_local_video",mimeType:r.mimeType,size:r.size})}return n}async collectTaskQueueMedia(){var i,o;const t=await Ks.getAllTasks(),n=[],r=t.filter(s=>{var a;return s.status===un.COMPLETED&&(s.type===Qt.IMAGE||s.type===Qt.VIDEO)&&((a=s.result)==null?void 0:a.url)});for(const s of r){const a=s.result.url,l=s.type===Qt.VIDEO?"video":"image";n.some(c=>c.url===a)||n.push({url:a,type:l,source:"local",boardIds:[],isCurrentBoard:!1,priority:l==="image"?"other_local_image":"other_local_video",mimeType:(i=s.result)==null?void 0:i.format,size:(o=s.result)==null?void 0:o.size})}return n}async collectMediaByUrls(t){const n=[];for(const r of t){if(r.startsWith("blob:"))continue;const i=this.guessMediaType(r);let o,s;if(Tle(r))o="local";else if(Dle(r))o="external",s=r;else continue;n.push({url:r,type:i,source:o,originalUrl:s,boardIds:[],isCurrentBoard:!1,priority:Mle(!1,o,i)})}return await this.enrichMediaMetadata(n),n}async enrichMediaMetadata(t){var n;for(const r of t)if(!(r.mimeType&&r.size))try{const i=await yn.getCacheInfo(r.url);i.isCached&&(r.size=i.size,r.mimeType=(n=i.metadata)==null?void 0:n.mimeType)}catch(i){Pt(`MediaCollector] Failed to get metadata for ${r.url}:`,i)}}guessMediaType(t){const n=t.toLowerCase();return[".mp4",".mov",".avi",".mkv",".webm",".m4v",".flv",".wmv"].some(i=>n.includes(i))||n.includes("/video/")||n.includes("#video")?"video":"image"}calculateStats(t){return{total:t.length,currentBoard:t.filter(n=>n.isCurrentBoard).length,localImages:t.filter(n=>n.source==="local"&&n.type==="image").length,localVideos:t.filter(n=>n.source==="local"&&n.type==="video").length,urlImages:t.filter(n=>n.source==="external"&&n.type==="image").length,urlVideos:t.filter(n=>n.source==="external"&&n.type==="video").length}}createEmptyResult(){return{items:[],currentBoardItems:[],otherItems:[],stats:{total:0,currentBoard:0,localImages:0,localVideos:0,urlImages:0,urlVideos:0}}}}const CV=new $et;async function Ole(e){return(await xn(()=>Promise.resolve().then(()=>_O),void 0,import.meta.url)).blobToBase64(e)}function Rle(e,t){const n=atob(e),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return new Blob([r],{type:t})}function K2(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(1)} MB`}const EV="github_media_sync_status";function zet(){return localStorage.getItem(bd)||"unknown"}class Uet{constructor(){this.statusCache={},this.syncingUrls=new Set,this.syncCompletedListeners=new Set,this.loadStatusCache()}addSyncCompletedListener(t){this.syncCompletedListeners.add(t)}removeSyncCompletedListener(t){this.syncCompletedListeners.delete(t)}notifySyncCompleted(t){t.succeeded>0&&this.syncCompletedListeners.forEach(n=>{try{n(t)}catch(r){vn("Sync completed callback error",r instanceof Error?r:new Error(String(r)))}})}async loadStatusCache(){const t=await er.get(EV);t&&(this.statusCache=t)}async saveStatusCache(){await er.set(EV,this.statusCache)}getUrlSyncStatus(t){if(this.syncingUrls.has(t))return"syncing";const n=this.statusCache[t];return n?n.status:"not_synced"}async syncCurrentBoardMedia(t,n){const r=Date.now();fe("syncCurrentBoardMedia",{currentBoardId:t}),Tr("开始同步当前画板媒体",{boardId:t});try{const i=await CV.collectCurrentBoardMedia(t);if(fe("Collected media",i.stats),i.currentBoardItems.length===0)return Tr("当前画板无媒体需要同步"),this.createEmptyBatchResult(r);const o=await this.getRemoteSyncedUrls(),s=i.currentBoardItems.filter(l=>!o.has(l.url));if(fe("Items to sync",{toSync:s.length,total:i.currentBoardItems.length,alreadySynced:o.size}),Tr("媒体增量计算完成",{total:i.currentBoardItems.length,alreadySynced:o.size,toSync:s.length}),s.length===0)return this.createEmptyBatchResult(r);const a=await this.syncMediaItems(s,n);return Jr("媒体同步完成",{succeeded:a.succeeded,failed:a.failed,skipped:a.skipped,totalSize:a.totalSize,duration:a.duration}),a}catch(i){return vn("syncCurrentBoardMedia failed",i instanceof Error?i:new Error(String(i))),vn("媒体同步失败",i instanceof Error?i:new Error(String(i))),{succeeded:0,failed:0,skipped:0,results:[],totalSize:0,duration:Date.now()-r}}}async syncSelectedMedia(t,n){const r=Date.now();fe("syncSelectedMedia",{urlCount:t.length});try{const i=await CV.collectMediaByUrls(t);if(i.length===0)return this.createEmptyBatchResult(r);const o=await this.getRemoteSyncedUrls(),s=i.filter(a=>!o.has(a.url));return fe("Items to sync",{toSync:s.length,requested:i.length,alreadySynced:i.length-s.length}),s.length===0?{succeeded:0,failed:0,skipped:i.length,results:i.map(a=>({success:!0,url:a.url,error:"已同步"})),totalSize:0,duration:Date.now()-r}:await this.syncMediaItems(s,n)}catch(i){return vn("syncSelectedMedia failed",i instanceof Error?i:new Error(String(i))),{succeeded:0,failed:0,skipped:0,results:[],totalSize:0,duration:Date.now()-r}}}async getRemoteSyncedUrls(){try{if(!yt.hasGistId())return new Set;const{shardSyncService:t}=await xn(async()=>{const{shardSyncService:n}=await Promise.resolve().then(()=>Qtt);return{shardSyncService:n}},void 0,import.meta.url);return await t.getSyncedUrls()}catch(t){return Pt("Failed to get remote synced URLs",{error:String(t)}),new Set}}async syncMediaItems(t,n){var o,s;const r=Date.now();try{const{shardedMediaSyncAdapter:a}=await xn(async()=>{const{shardedMediaSyncAdapter:l}=await Promise.resolve().then(()=>Qle);return{shardedMediaSyncAdapter:l}},void 0,import.meta.url);if(await a.initialize(),a.isShardingEnabled()){fe("Using sharded media sync adapter");const l=await a.uploadMedia(t,n);return l.duration=Date.now()-r,fe("Sharded sync completed",{succeeded:l.succeeded,failed:l.failed,skipped:l.skipped,duration:l.duration}),this.notifySyncCompleted(l),l}}catch(a){Pt("Failed to use sharded adapter, falling back",{error:String(a)})}const i={succeeded:0,failed:0,skipped:0,results:[],totalSize:0,duration:0};for(let a=0;a<t.length;a++){const l=t[a];n==null||n(a+1,t.length,l.url,"uploading");const c=await this.syncSingleMediaItem(l);i.results.push(c),c.success?(i.succeeded++,i.totalSize+=c.size||0):(o=c.error)!=null&&o.includes("过大")||(s=c.error)!=null&&s.includes("CORS")?i.skipped++:i.failed++}return i.duration=Date.now()-r,fe("Legacy sync completed",{succeeded:i.succeeded,failed:i.failed,skipped:i.skipped,totalSize:K2(i.totalSize),duration:i.duration}),this.notifySyncCompleted(i),i}async syncSingleMediaItem(t){const{url:n,type:r,source:i,originalUrl:o,mimeType:s}=t;this.syncingUrls.add(n);try{let a=null;if(i==="local"?a=await yn.getCachedBlob(n):i==="external"&&(a=await yn.getCachedBlob(n)),!a||a.size===0)return{success:!1,url:n,error:"无法获取媒体文件"};if(a.size>eO)return{success:!1,url:n,error:`文件过大(${K2(a.size)}),最大支持 ${K2(eO)}`,size:a.size};const l=await Ole(a),c={url:n,type:r,source:i,mimeType:s||a.type,size:a.size,base64Data:l,syncedAt:Date.now(),syncedFromDevice:zet(),originalUrl:i==="external"?o:void 0},u=`media_${ng(n)}.json`,d=JSON.stringify(c,null,2);return await yt.updateGistFiles({[u]:d}),this.statusCache[n]={status:"synced",syncedAt:Date.now()},await this.saveStatusCache(),{success:!0,url:n,size:a.size}}catch(a){vn(`Failed to sync media: ${n}`,a instanceof Error?a:new Error(String(a)));const l=a instanceof Error?a.message:"同步失败";return this.statusCache[n]={status:"error",error:l},await this.saveStatusCache(),{success:!1,url:n,error:l}}finally{this.syncingUrls.delete(n)}}async fetchMediaFromUrl(t){try{const n=await fetch(t,{mode:"cors",credentials:"omit"});return n.ok?await n.blob():(Pt("Failed to fetch media",{status:n.status}),null)}catch(n){return vn("Fetch media failed",n instanceof Error?n:new Error(String(n))),null}}createEmptyBatchResult(t){return{succeeded:0,failed:0,skipped:0,results:[],totalSize:0,duration:Date.now()-t}}async downloadAndCacheMediaByUrl(t){try{const n=`media_${ng(t)}.json`,r=await yt.getGistFileContent(n);if(!r)return null;const i=JSON.parse(r),o=Rle(i.base64Data,i.mimeType);return!o||o.size===0?null:(await yn.cacheToCacheStorageOnly(t,o),fe("Downloaded and cached media",{url:t}),t)}catch(n){return vn(`Failed to download media: ${t}`,n instanceof Error?n:new Error(String(n))),null}}async downloadAllRemoteMedia(t){const n=Date.now(),r={succeeded:0,failed:0,skipped:0,results:[],totalSize:0,duration:0};try{const i=await this.getRemoteSyncedUrls(),o=Array.from(i);fe("Found remote media to download",{count:o.length});for(let s=0;s<o.length;s++){const a=o[s];if(t==null||t(s+1,o.length,a,"downloading"),(await yn.getCacheInfo(a)).isCached){r.skipped++,r.results.push({success:!0,url:a,error:"已缓存"});continue}await this.downloadAndCacheMediaByUrl(a)?(r.succeeded++,r.results.push({success:!0,url:a})):(r.failed++,r.results.push({success:!1,url:a,error:"下载失败"}))}}catch(i){vn("downloadAllRemoteMedia failed",i instanceof Error?i:new Error(String(i)))}return r.duration=Date.now()-n,r}async refreshSyncStatus(){try{const t=await this.getRemoteSyncedUrls();this.statusCache={};for(const n of t)this.statusCache[n]={status:"synced",syncedAt:Date.now()};await this.saveStatusCache()}catch(t){vn("Refresh failed",t instanceof Error?t:new Error(String(t)))}}async deleteSyncedMedia(t){try{const n=`media_${ng(t)}.json`;return await yt.deleteGistFiles([n]),delete this.statusCache[t],await this.saveStatusCache(),!0}catch(n){return vn("Delete failed",n instanceof Error?n:new Error(String(n))),!1}}}const qc=new Uet,tO=Object.freeze(Object.defineProperty({__proto__:null,mediaSyncService:qc},Symbol.toStringTag,{value:"Module"})),Xk="github_sync_password";function Nle(){return[navigator.userAgent,navigator.language,screen.width.toString(),screen.height.toString(),new Date().getTimezoneOffset().toString()].join("|")}function Het(e){const t=Nle();let n="";for(let r=0;r<e.length;r++){const i=e.charCodeAt(r)^t.charCodeAt(r%t.length);n+=String.fromCharCode(i)}return btoa(n)}function Wet(e){const t=Nle(),n=atob(e);let r="";for(let i=0;i<n.length;i++){const o=n.charCodeAt(i)^t.charCodeAt(i%t.length);r+=String.fromCharCode(o)}return r}class Vet{constructor(){this.cachedPassword=null,this.cacheLoaded=!1}async savePassword(t){if(!t){await er.remove(Xk),this.cachedPassword=null,this.cacheLoaded=!0;return}const n={encrypted:Het(t),storedAt:Date.now()};await er.set(Xk,n),this.cachedPassword=t,this.cacheLoaded=!0}async getPassword(){if(this.cacheLoaded)return this.cachedPassword;const t=await er.get(Xk);if(!t)return this.cachedPassword=null,this.cacheLoaded=!0,null;try{return this.cachedPassword=Wet(t.encrypted),this.cacheLoaded=!0,this.cachedPassword}catch{return this.cachedPassword=null,this.cacheLoaded=!0,null}}async hasPassword(){return!!await this.getPassword()}clearCache(){this.cachedPassword=null,this.cacheLoaded=!1}}const pi=new Vet,Zk="1.0";class Get{async getToolboxService(){const{toolboxService:t}=await xn(async()=>{const{toolboxService:n}=await import("./tool-windows-Bf_pMml-.js").then(r=>r.b2);return{toolboxService:n}},__vite__mapDeps([0]),import.meta.url);return t}async syncTools(t,n){fe("ToolSyncService: Starting tool sync");try{const r=await this.getToolboxService(),i=r.getCustomTools(),o=await r.getUpdatedAt(),s=await this.downloadRemoteTools(t,n);let a=0,l=0,c=0;if(!s)i.length>0?(await this.uploadTools(i,t,n),a=i.length,Tr("ToolSyncService: Uploaded local tools",{count:a})):fe("ToolSyncService: No tools to sync");else{const{toUpload:u,toDownload:d}=this.compareTools(i,s.tools,o,s.updatedAt);if(d.length>0){const f=await r.importTools(d);l=f.imported,c+=f.skipped,Tr("ToolSyncService: Downloaded remote tools",{imported:f.imported,skipped:f.skipped})}if(u.length>0||l>0){const f=r.getCustomTools();await this.uploadTools(f,t,n),a=u.length,Tr("ToolSyncService: Uploaded local tools",{count:a})}}return a>0||l>0?Jr("ToolSyncService: Tool sync completed",{uploaded:a,downloaded:l,skipped:c}):fe("ToolSyncService: Tool sync completed (no changes)"),{uploaded:a,downloaded:l,skipped:c}}catch(r){return Pt("ToolSyncService: Tool sync failed",{error:r instanceof Error?r.message:String(r)}),{uploaded:0,downloaded:0,skipped:0}}}compareTools(t,n,r,i){const o=new Set(t.map(c=>c.id)),s=new Set(n.map(c=>c.id)),a=t.filter(c=>!s.has(c.id)),l=n.filter(c=>!o.has(c.id));return fe("ToolSyncService: Compared tools",{localCount:t.length,remoteCount:n.length,toUpload:a.length,toDownload:l.length}),{toUpload:a,toDownload:l}}async downloadRemoteTools(t,n){try{const r=await yt.getGistFileContent(_t.CUSTOM_TOOLS);if(!r)return fe("ToolSyncService: No remote tools found"),null;const i=await Nn.decryptOrPassthrough(r,t,n),o=JSON.parse(i);return o.version!==Zk?(Pt("ToolSyncService: Incompatible remote version",{remote:o.version,local:Zk}),null):o}catch(r){return Pt("ToolSyncService: Failed to download remote tools",{error:r instanceof Error?r.message:String(r)}),null}}async uploadTools(t,n,r){const i={version:Zk,tools:t,updatedAt:Date.now()},o=JSON.stringify(i,null,2),s=await Nn.encrypt(o,n,r);await yt.updateGistFiles({[_t.CUSTOM_TOOLS]:s})}}const Ket=new Get,_V="github_sync_config",o2="github_sync_local_deletions_pending";class qet{constructor(){this.status="not_configured",this.statusListeners=new Set,this.syncInProgress=!1,this.autoSyncTimer=null,this.pendingChanges=!1,this.initialize()}async initialize(){if(ai.hasToken()){const n=await this.getConfig();n.gistId?(yt.setGistId(n.gistId),this.status="synced"):this.status="local_changes"}else this.status="not_configured"}async getConfig(){return await er.get(_V)||{...tet}}async saveConfig(t){const r={...await this.getConfig(),...t};await er.set(_V,r)}getSyncStatus(){return this.status}setStatus(t,n){this.status=t,this.notifyStatusListeners(t,n)}addStatusListener(t){this.statusListeners.add(t)}removeStatusListener(t){this.statusListeners.delete(t)}notifyStatusListeners(t,n){this.statusListeners.forEach(r=>{try{r(t,n)}catch(i){vn("状态监听器错误",i instanceof Error?i:new Error(String(i)))}})}performSafetyCheck(t){var u;const{localBoards:n,toDeleteLocally:r,currentBoardId:i,isFirstSync:o,remoteManifest:s}=t,a={passed:!0,warnings:[],skippedItems:[]};if(r.length===0)return a;if(fe("Safety check",{localBoardsCount:n.size,toDeleteCount:r.length,currentBoardId:i,isFirstSync:o,hasRemoteManifest:!!s}),!s||Object.keys(s.boards).length===0)return fe("Safety: Remote manifest empty or invalid, skipping all deletions"),a.skippedItems=r.map(d=>{var f;return{id:d,name:((f=n.get(d))==null?void 0:f.name)||d,reason:"new_device"}}),a;if(o&&r.length>0)return fe("Safety: First sync, skipping all deletions"),a.skippedItems=r.map(d=>{var f;return{id:d,name:((f=n.get(d))==null?void 0:f.name)||d,reason:"new_device"}}),a;i&&r.includes(i)&&(fe("Safety: Current board protected",{currentBoardId:i}),a.skippedItems.push({id:i,name:((u=n.get(i))==null?void 0:u.name)||i,reason:"current_board"}));const l=new Set(a.skippedItems.map(d=>d.id)),c=r.filter(d=>!l.has(d));if(c.length===n.size&&n.size>0)return fe("Safety: Blocked - would delete all local boards"),a.passed=!1,a.blockedReason="检测到异常操作:远程数据要求删除所有本地画板,已阻止执行。请检查远程数据是否正常。",a;if(c.length>1){const d=c.length/n.size;d>.5&&(fe("Safety: Bulk delete warning",{deleteRatio:d}),a.passed=!1,a.warnings.push({type:"bulk_delete",message:`即将删除 ${c.length}/${n.size} 个画板 (${Math.round(d*100)}%)`,affectedItems:c.map(f=>{var p;return{id:f,name:((p=n.get(f))==null?void 0:p.name)||f}})}))}return a}async sync(){var i,o,s,a,l,c,u,d,f,p,y,v,w;if(this.syncInProgress)return{success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],error:"同步正在进行中",duration:0};const t=Date.now();this.syncInProgress=!0,this.setStatus("syncing","正在同步...");const n=fhe();Tr("开始同步",{sessionId:n});const r={success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0};try{if(!await ai.getToken())throw new Error("未配置 GitHub Token");Tr("Token 验证通过"),fe("Collecting local data...");const x=await Or.collectSyncData();Tr("本地数据收集完成",{boards:x.boards.size,folders:x.workspace.folders.length}),fe("Local data collected",{boards:x.boards.size,folders:x.workspace.folders.length,currentBoardId:x.workspace.currentBoardId});const E=await this.getConfig();fe("Config",{gistId:E.gistId,lastSyncTime:E.lastSyncTime,enabled:E.enabled});let _=null,I={},D=!1;if(E.gistId){fe("Using existing gistId",{gistId:xa(E.gistId)}),yt.setGistId(E.gistId);try{const k=await yt.getGist();fe("Got gist",{files:Object.keys(k.files)});for(const T of Object.keys(k.files)){const M=await yt.getGistFileContent(T);M&&(I[T]=M)}fe("Loaded remote files",{count:Object.keys(I).length});const R=await pi.getPassword();if(I[_t.MANIFEST])try{const{cryptoService:T}=await xn(async()=>{const{cryptoService:F}=await Promise.resolve().then(()=>sl);return{cryptoService:F}},void 0,import.meta.url),M=await T.decryptOrPassthrough(I[_t.MANIFEST],E.gistId,R||void 0);_=JSON.parse(M)}catch(T){if(Pt("Failed to decrypt/parse manifest",{error:String(T)}),x.boards.size>0||x.prompts.promptHistory.length>0||x.tasks.completedTasks.length>0)Pt("Local has data, will overwrite remote"),D=!0;else throw vn("Local is empty, refusing to overwrite remote"),new Error("解密失败且本地无数据,拒绝覆盖远程数据以防止数据丢失")}fe("Remote manifest",{version:_==null?void 0:_.version,boards:_?Object.keys(_.boards).length:0,shouldOverwriteRemote:D})}catch(k){if(vn("Error fetching gist",k instanceof Error?k:new Error(String(k))),k instanceof cl&&k.statusCode===404)fe("Gist not found (404), will create new one"),E.gistId=null;else throw k}}if(D&&E.gistId){Tr("Decryption failed, overwriting remote with local data...");const k=await pi.getPassword(),R=await Or.serializeToGistFilesEncrypted(x,E.gistId,k||void 0);await yt.updateGistFiles(R);try{const T=await Kl.syncTasks(E.gistId,k||void 0);r.uploaded.tasks=T.uploaded}catch(T){Pt("Tasks paged sync failed during overwrite",{error:String(T)})}await this.saveConfig({lastSyncTime:Date.now()}),r.uploaded.boards=x.boards.size,r.uploaded.prompts=x.prompts.promptHistory.length+x.prompts.videoPromptHistory.length+x.prompts.imagePromptHistory.length,r.uploaded.knowledgeBase=(((i=x.knowledgeBase)==null?void 0:i.notes.length)||0)+(((o=x.knowledgeBase)==null?void 0:o.directories.length)||0),r.success=!0,Jr("Remote overwritten with local data")}else if(E.gistId){if(E.gistId)if(fe("Has gistId, comparing changes..."),_){fe("Has remoteManifest, comparing changes...");const k=Or.compareBoardChanges(x.boards,_,E.lastSyncTime);fe("Changes detected",{toUpload:k.toUpload,toDownload:k.toDownload,conflicts:k.conflicts,toDeleteLocally:k.toDeleteLocally}),Tr("变更检测完成",{toUpload:k.toUpload.length,toDownload:k.toDownload.length,conflicts:k.conflicts.length,toDeleteLocally:k.toDeleteLocally.length}),fe("Detecting local deletions...");const R=Or.detectDeletions(x,_);fe("Local deletions detected",{boards:R.deletedBoards.length,deletedBoardIds:R.deletedBoards.map(N=>N.id)});let T=[];if(k.toDeleteLocally.length>0){const N=await Bn.loadState(),B=this.performSafetyCheck({localBoards:x.boards,toDeleteLocally:k.toDeleteLocally,currentBoardId:N.currentBoardId||null,isFirstSync:!E.lastSyncTime,remoteManifest:_});if(fe("Safety check result",{passed:B.passed,warnings:B.warnings.length,skipped:B.skippedItems.length,blockedReason:B.blockedReason}),r.safetyWarnings=B.warnings,r.skippedItems=B.skippedItems,B.blockedReason)Pt("Safety: Blocked all deletions",{reason:B.blockedReason});else if(!B.passed&&B.warnings.length>0)Pt("Safety: Warnings present, skipping deletions pending user confirmation");else{const O=new Set(B.skippedItems.map($=>$.id));T=k.toDeleteLocally.filter($=>!O.has($))}}const M=await pi.getPassword();fe("Incremental sync",{hasCustomPassword:!!M});const F=await Or.deserializeFromGistFilesWithDecryption(I,E.gistId,M||void 0);fe("Remote data for merge",{boards:F.boards.size,workspaceFolders:((v=(y=F.workspace)==null?void 0:y.folders)==null?void 0:v.length)||0});const V=[];if(k.conflicts.length>0){Tr(`发现 ${k.conflicts.length} 个冲突画板,开始合并`);for(const N of k.conflicts){const B=x.boards.get(N),O=F.boards.get(N),$=_.boards[N];if(B&&O&&$){const U=Or.mergeBoardElements(B,O);V.push({boardId:N,board:U.mergedBoard}),Tr(`画板合并完成: ${B.name}`,{boardId:N,addedFromLocal:U.addedFromLocal,addedFromRemote:U.addedFromRemote,conflictingElements:U.conflictingElements.length,hasConflicts:U.hasConflicts}),U.hasConflicts&&(r.conflicts.push({type:"board",id:N,name:B.name,localUpdatedAt:B.updatedAt,remoteUpdatedAt:$.updatedAt,merged:!0,mergeInfo:{addedFromLocal:U.addedFromLocal,addedFromRemote:U.addedFromRemote,conflictingElements:U.conflictingElements.length}}),Pt(`画板存在元素冲突: ${B.name}`,{boardId:N,conflictingElements:U.conflictingElements.length})),fe("Merged board",{boardId:N,addedFromLocal:U.addedFromLocal,addedFromRemote:U.addedFromRemote,conflicts:U.conflictingElements.length})}}}if(k.toDownload.length>0){Tr(`下载 ${k.toDownload.length} 个远程画板`);const N=new Set(V.map($=>$.boardId)),B=new Map;for(const $ of k.toDownload)if(!N.has($)){const U=F.boards.get($);U?(B.set($,U),fe("Will download board",{boardId:$,name:U.name})):fe("Board not found in remote data",{boardId:$})}fe("Boards to download after filtering",{count:B.size});const O=await Or.applySyncData({workspace:F.workspace,boards:B,prompts:F.prompts,tasks:F.tasks,deletedBoardIds:T});fe("Applied remote data",O),Jr("远程数据下载完成",{boards:O.boardsApplied,prompts:O.promptsApplied,tasks:O.tasksApplied,deleted:O.boardsDeleted}),r.downloaded.boards=O.boardsApplied,r.downloaded.prompts=O.promptsApplied,r.downloaded.tasks=O.tasksApplied,r.remoteCurrentBoardId=O.remoteCurrentBoardId,O.boardsDeleted>0&&(r.deleted={boards:O.boardsDeleted,prompts:O.promptsDeleted,tasks:O.tasksDeleted,media:0})}else{if(fe("No boards to download"),T.length>0){const N=await Or.applySyncData({workspace:null,boards:new Map,prompts:null,tasks:null,deletedBoardIds:T});N.boardsDeleted>0&&(r.deleted={boards:N.boardsDeleted,prompts:N.promptsDeleted,tasks:N.tasksDeleted,media:0})}r.remoteCurrentBoardId=((w=F.workspace)==null?void 0:w.currentBoardId)||null,fe("Set remoteCurrentBoardId from workspace",{remoteCurrentBoardId:r.remoteCurrentBoardId})}if(V.length>0){for(const{boardId:N,board:B}of V)await Bn.saveBoard(B),x.boards.set(N,B);k.toUpload.push(...V.map(N=>N.boardId)),r.downloaded.boards+=V.length}let H=!1;if(x.knowledgeBase||F.knowledgeBase){fe("Processing Knowledge Base sync...");let N=x.knowledgeBase;if(x.knowledgeBase&&F.knowledgeBase){fe("Merging local and remote Knowledge Base"),N=Bf.merge(x.knowledgeBase,F.knowledgeBase);const B=JSON.stringify(x.knowledgeBase),O=JSON.stringify(N);B!==O&&(Tr("Knowledge Base merged, applying to local"),await Bf.apply(N),x.knowledgeBase=N,r.downloaded.knowledgeBase=Math.abs(N.notes.length+N.directories.length-(JSON.parse(B).notes.length+JSON.parse(B).directories.length)))}else F.knowledgeBase&&!x.knowledgeBase&&(Tr("Downloading Knowledge Base from remote"),await Bf.apply(F.knowledgeBase),x.knowledgeBase=F.knowledgeBase,N=F.knowledgeBase,r.downloaded.knowledgeBase=N.notes.length+N.directories.length);if(x.knowledgeBase){const B=JSON.stringify(x.knowledgeBase),O=F.knowledgeBase?JSON.stringify(F.knowledgeBase):"";B!==O&&(H=!0)}}const j=k.toUpload.length>0,z=R.deletedBoards.length>0;if(j||z||H){Tr("开始上传本地变更",{boardsToUpload:k.toUpload.length,deletedBoards:R.deletedBoards.length,kbNeedsUpload:H});const N={},B=new Set,{cryptoService:O}=await xn(async()=>{const{cryptoService:K}=await Promise.resolve().then(()=>sl);return{cryptoService:K}},void 0,import.meta.url);for(const K of k.toUpload){if(B.has(K))continue;B.add(K);const Z=x.boards.get(K);if(Z){const oe=JSON.stringify(Z);N[_t.boardFile(K)]=await O.encrypt(oe,E.gistId,M||void 0),x.manifest.boards[K]={name:Z.name,updatedAt:Z.updatedAt,checksum:Or.calculateBoardChecksum(Z)}}}if(z){fe("标记删除的画板为 tombstone",{boards:R.deletedBoards.map(Z=>Z.id)});const K=Or.markBoardsAsDeleted(x.manifest,R.deletedBoards,x.manifest.deviceId);x.manifest=K}x.manifest.updatedAt=Date.now();const $=JSON.stringify(x.manifest);N[_t.MANIFEST]=await O.encrypt($,E.gistId,M||void 0);const U=JSON.stringify(x.workspace);N[_t.WORKSPACE]=await O.encrypt(U,E.gistId,M||void 0);const Y=JSON.stringify(x.prompts);if(N[_t.PROMPTS]=await O.encrypt(Y,E.gistId,M||void 0),x.knowledgeBase){const K=JSON.stringify(x.knowledgeBase),Z=F.knowledgeBase?JSON.stringify(F.knowledgeBase):"";K!==Z&&(fe("Uploading Knowledge Base (changed)"),N[_t.KNOWLEDGE_BASE]=await O.encrypt(K,E.gistId,M||void 0),r.uploaded.knowledgeBase=x.knowledgeBase.notes.length+x.knowledgeBase.directories.length)}await yt.updateGistFiles(N),r.uploaded.boards=k.toUpload.length;try{const K=await Kl.syncTasks(E.gistId,M||void 0);r.uploaded.tasks=K.uploaded}catch(K){Pt("Tasks paged sync failed during incremental sync",{error:String(K)})}Jr("本地变更上传完成",{boards:k.toUpload.length,files:Object.keys(N).length}),z&&!r.deleted&&(r.deleted={boards:0,prompts:0,tasks:0,media:0}),z&&r.deleted&&(fe("Tombstone 上传完成",{count:R.deletedBoards.length}),Tr("删除标记上传完成",{count:R.deletedBoards.length}),await this.clearLocalDeletions(R.deletedBoards.map(K=>K.id)))}await this.saveConfig({lastSyncTime:Date.now()}),r.success=!0}else{Pt("No remote manifest found, will perform full upload");const{cryptoService:k}=await xn(async()=>{const{cryptoService:H}=await Promise.resolve().then(()=>sl);return{cryptoService:H}},void 0,import.meta.url),R={},T=await pi.getPassword();fe("Full upload",{hasCustomPassword:!!T});for(const[H,j]of x.boards){const z=JSON.stringify(j);R[_t.boardFile(H)]=await k.encrypt(z,E.gistId,T||void 0),x.manifest.boards[H]={name:j.name,updatedAt:j.updatedAt,checksum:Or.calculateBoardChecksum(j)}}x.manifest.updatedAt=Date.now();const M=JSON.stringify(x.manifest);R[_t.MANIFEST]=await k.encrypt(M,E.gistId,T||void 0);const F=JSON.stringify(x.workspace);R[_t.WORKSPACE]=await k.encrypt(F,E.gistId,T||void 0);const V=JSON.stringify(x.prompts);R[_t.PROMPTS]=await k.encrypt(V,E.gistId,T||void 0),await yt.updateGistFiles(R),r.uploaded.boards=x.boards.size;try{const H=await Kl.syncTasks(E.gistId,T||void 0);r.uploaded.tasks=H.uploaded}catch(H){Pt("Tasks paged sync failed during initial sync",{error:String(H)})}r.success=!0,await this.saveConfig({lastSyncTime:Date.now()})}}else{fe("No gistId in config, searching for existing sync gist...");const k=await yt.findSyncGist();if(k){fe("Found existing gist",{gistId:xa(k.id),files:Object.keys(k.files).length}),yt.setGistId(k.id);for(const T of Object.keys(k.files)){const M=await yt.getGistFileContent(T);M&&(I[T]=M,fe("Loaded file",{filename:T,length:M.length}))}const R=await pi.getPassword();fe("Custom password available",{hasPassword:!!R});try{fe("Deserializing remote data...");const T=await Or.deserializeFromGistFilesWithDecryption(I,k.id,R||void 0);fe("Remote data parsed",{boards:T.boards.size,folders:((a=(s=T.workspace)==null?void 0:s.folders)==null?void 0:a.length)||0,tasks:((c=(l=T.tasks)==null?void 0:l.completedTasks)==null?void 0:c.length)||0}),fe("Applying remote data to local...");const M=await Or.applySyncData({workspace:T.workspace,boards:T.boards,prompts:T.prompts,tasks:T.tasks});fe("Applied result",M),await this.saveConfig({gistId:k.id,lastSyncTime:Date.now(),enabled:!0}),r.downloaded.boards=M.boardsApplied,r.downloaded.prompts=M.promptsApplied,r.downloaded.tasks=M.tasksApplied,r.downloaded.knowledgeBase=M.knowledgeBaseApplied,r.remoteCurrentBoardId=M.remoteCurrentBoardId,r.success=!0}catch(T){Pt("Decryption failed for existing gist, overwriting with local data",{error:String(T)});const M=await Or.serializeToGistFilesEncrypted(x,k.id,R||void 0);await yt.updateGistFiles(M);try{const F=await Kl.syncTasks(k.id,R||void 0);r.uploaded.tasks=F.uploaded}catch(F){Pt("Tasks paged sync failed during overwrite",{error:String(F)})}await this.saveConfig({gistId:k.id,lastSyncTime:Date.now(),enabled:!0}),r.uploaded.boards=x.boards.size,r.uploaded.prompts=x.prompts.promptHistory.length+x.prompts.videoPromptHistory.length+x.prompts.imagePromptHistory.length,r.uploaded.knowledgeBase=(((u=x.knowledgeBase)==null?void 0:u.notes.length)||0)+(((d=x.knowledgeBase)==null?void 0:d.directories.length)||0),r.success=!0,Jr("Existing gist overwritten with local data")}}else{fe("No existing gist found, will create new one with encryption");const R=await yt.createSyncGist({"manifest.json":JSON.stringify({version:1,initializing:!0},null,2)}),T=R.id,M=await pi.getPassword();fe("Creating new gist",{hasCustomPassword:!!M});const F=await Or.serializeToGistFilesEncrypted(x,T,M||void 0);yt.setGistId(T),await yt.updateGistFiles(F);try{const H=await Kl.syncTasks(T,M||void 0);r.uploaded.tasks=H.uploaded}catch(H){Pt("Tasks paged sync failed during new gist creation",{error:String(H)})}const V=R;await this.saveConfig({gistId:V.id,lastSyncTime:Date.now(),enabled:!0}),r.uploaded.boards=x.boards.size,r.uploaded.prompts=x.prompts.promptHistory.length+x.prompts.videoPromptHistory.length+x.prompts.imagePromptHistory.length,r.uploaded.knowledgeBase=(((f=x.knowledgeBase)==null?void 0:f.notes.length)||0)+(((p=x.knowledgeBase)==null?void 0:p.directories.length)||0),r.success=!0}}this.setStatus("synced"),this.pendingChanges=!1,Jr("同步完成",{uploaded:r.uploaded,downloaded:r.downloaded,conflicts:r.conflicts.length});const P=x.workspace.currentBoardId;P&&r.uploaded.boards>0&&this.syncCurrentBoardMediaAsync(P),(r.downloaded.tasks>0||r.downloaded.boards>0)&&this.downloadSyncedMediaAsync()}catch(C){vn("同步失败",C instanceof Error?C:new Error(String(C))),r.error=C instanceof Error?C.message:"同步失败",this.setStatus("error",r.error),vn("同步失败",C instanceof Error?C:new Error(String(C)))}finally{this.syncInProgress=!1,r.duration=Date.now()-t,Tr("同步会话结束",{duration:r.duration,success:r.success}),hhe(),phe().catch(()=>{})}return r}async syncCurrentBoardMediaAsync(t){try{fe("Starting async current board media sync",{currentBoardId:t});const n=await qc.syncCurrentBoardMedia(t,(r,i,o,s)=>{fe("Media sync progress",{status:s,current:r,total:i,url:o})});Jr("Current board media sync completed",{succeeded:n.succeeded,failed:n.failed,skipped:n.skipped})}catch(n){vn("Current board media sync failed",n instanceof Error?n:new Error(String(n)))}}async uploadMergedTasksToRemote(t,n){try{fe("uploadMergedTasksToRemote: Starting with paged format...");const r=await Kl.syncTasks(t,n);Jr("uploadMergedTasksToRemote: Tasks synced",{uploaded:r.uploaded,downloaded:r.downloaded,skipped:r.skipped})}catch(r){vn("uploadMergedTasksToRemote: Failed to sync tasks",r instanceof Error?r:new Error(String(r)))}}async downloadSyncedMediaAsync(){try{fe("Starting async media download...");const t=await qc.downloadAllRemoteMedia((n,r,i,o)=>{fe("Downloading media",{current:n,total:r,url:i,status:o})});Jr("Media download completed",{succeeded:t.succeeded,failed:t.failed,skipped:t.skipped})}catch(t){vn("Media download failed",t instanceof Error?t:new Error(String(t)))}}async pushToRemote(){if(this.syncInProgress)return{success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],error:"同步正在进行中",duration:0};const t=Date.now();this.syncInProgress=!0,this.setStatus("syncing","正在上传本地数据...");const n={success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0};try{if(!await ai.getToken())throw new Error("未配置 GitHub Token");const i=await pi.getPassword();fe("pushToRemote: 收集本地数据");const o=await Or.collectSyncData(),s=await this.getConfig();if(s.gistId){fe("pushToRemote: 增量上传",{gistId:xa(s.gistId)}),yt.setGistId(s.gistId);const{cryptoService:c}=await xn(async()=>{const{cryptoService:w}=await Promise.resolve().then(()=>sl);return{cryptoService:w}},void 0,import.meta.url);let u=null;try{const w=await yt.getGistFileContent(_t.MANIFEST);if(w){const C=await c.decryptOrPassthrough(w,s.gistId,i||void 0);u=JSON.parse(C)}}catch{fe("pushToRemote: 无远程 manifest 或解密失败,将上传全部")}const d={};let f=0;if(u){let w=0;for(const[C,x]of o.boards){const E=Or.calculateBoardChecksum(x),_=u.boards[C];if(!_||_.checksum!==E){const I=JSON.stringify(x);d[_t.boardFile(C)]=await c.encrypt(I,s.gistId,i||void 0),f++,fe("pushToRemote: 画板需要上传 (checksum 变化)",{boardId:C})}w++,w%3===0&&await Wo()}for(const C of Object.keys(u.boards)){const x=u.boards[C];x.deletedAt||o.boards.has(C)||(o.manifest.boards[C]={...x,deletedAt:Date.now()},fe("pushToRemote: 画板软删除 (移入回收站)",{boardId:C}))}}else{let w=0;for(const[C,x]of o.boards){const E=JSON.stringify(x);d[_t.boardFile(C)]=await c.encrypt(E,s.gistId,i||void 0),f++,w++,w%3===0&&await Wo()}}const p=JSON.stringify(o.manifest);d[_t.MANIFEST]=await c.encrypt(p,s.gistId,i||void 0);const y=JSON.stringify(o.workspace);d[_t.WORKSPACE]=await c.encrypt(y,s.gistId,i||void 0);const v=JSON.stringify(o.prompts);if(d[_t.PROMPTS]=await c.encrypt(v,s.gistId,i||void 0),o.knowledgeBase){const w=JSON.stringify(o.knowledgeBase);d[_t.KNOWLEDGE_BASE]=await c.encrypt(w,s.gistId,i||void 0),n.uploaded.knowledgeBase=o.knowledgeBase.notes.length+o.knowledgeBase.directories.length}Object.keys(d).length>0&&(await yt.updateGistFiles(d),fe("pushToRemote: 增量上传完成",{boardsUploaded:f})),n.uploaded.boards=f;try{const w=await Kl.syncTasks(s.gistId,i||void 0);n.uploaded.tasks=w.uploaded}catch(w){Pt("pushToRemote: Tasks paged sync failed",{error:String(w)})}await this.saveConfig({lastSyncTime:Date.now()})}else{fe("pushToRemote: 创建新 Gist");const u=(await yt.createSyncGist({"manifest.json":JSON.stringify({version:1,initializing:!0},null,2)})).id;fe("pushToRemote: 创建空 Gist 完成",{gistId:xa(u)});const d=await Or.serializeToGistFilesEncrypted(o,u,i||void 0);yt.setGistId(u),await yt.updateGistFiles(d);try{const f=await Kl.syncTasks(u,i||void 0);n.uploaded.tasks=f.uploaded}catch(f){Pt("pushToRemote: Tasks paged sync failed during new gist creation",{error:String(f)})}await this.saveConfig({gistId:u,lastSyncTime:Date.now(),enabled:!0}),n.uploaded.boards=o.boards.size}n.uploaded.prompts=o.prompts.promptHistory.length+o.prompts.videoPromptHistory.length+o.prompts.imagePromptHistory.length,n.success=!0,Jr("pushToRemote: 上传成功",n.uploaded),this.setStatus("synced"),this.pendingChanges=!1;const a=await this.getLocalDeletionsPendingSync();a.size>0&&await this.clearLocalDeletions(Array.from(a.keys()));const l=o.workspace.currentBoardId;l&&this.syncCurrentBoardMediaAsync(l)}catch(r){vn("pushToRemote 失败",r instanceof Error?r:new Error(String(r))),n.error=r instanceof Error?r.message:"上传失败",this.setStatus("error",n.error)}finally{this.syncInProgress=!1,n.duration=Date.now()-t}return n}async pullFromRemote(){var r,i,o,s,a,l,c,u,d,f;if(Tr("pullFromRemote START"),this.syncInProgress)return fe("pullFromRemote: Sync already in progress, aborting"),{success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],error:"同步正在进行中",duration:0};const t=Date.now();this.syncInProgress=!0,this.setStatus("syncing","正在下载远程数据...");const n={success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0};try{if(!await ai.getToken())throw new Error("未配置 GitHub Token");const y=await pi.getPassword(),v=await this.getConfig();let w=v.gistId;if(!w){fe("pullFromRemote: No gistId, searching for sync gist...");const K=await yt.findSyncGist();if(K)w=K.id;else throw new Error("未找到可同步的 Gist,请先上传数据或在其他设备创建同步")}yt.setGistId(w);const{cryptoService:C}=await xn(async()=>{const{cryptoService:K}=await Promise.resolve().then(()=>sl);return{cryptoService:K}},void 0,import.meta.url);fe("pullFromRemote: 获取远程 manifest");const x=await yt.getGistFileContent(_t.MANIFEST);if(!x)throw new Error("远程数据为空");const E=await C.decryptOrPassthrough(x,w,y||void 0),_=JSON.parse(E);fe("pullFromRemote: 远程画板数量",{count:Object.keys(_.boards).length});const I=await Or.collectSyncData(),D=v.lastSyncTime;fe("pullFromRemote: lastSyncTime",{lastSyncTime:D});const P=await this.getLocalDeletionsPendingSync();fe("pullFromRemote: 待同步本地删除",{count:P.size,pending:P.size>0?Object.fromEntries(P):"none"});const k=[],R=[],T=[],M=[];for(const[K,Z]of Object.entries(_.boards)){if(Z.deletedAt){fe("pullFromRemote: 画板已远程删除,跳过",{boardId:K});continue}const oe=P.get(K);oe!==void 0&&(fe("pullFromRemote: 画板本地已删除,但远程为准将恢复",{boardId:K,localDeletedAt:oe,remoteUpdatedAt:Z.updatedAt}),await this.clearLocalDeletions([K]));const J=I.boards.get(K);if(!J)fe("pullFromRemote: 画板本地不存在,将下载",{boardId:K}),k.push(K);else{const ae=Or.calculateBoardChecksum(J);if(ae===Z.checksum)fe("pullFromRemote: checksum 匹配,跳过下载",{boardId:K,checksum:ae});else{const Q=J.updatedAt||0,se=Z.updatedAt||0;Q>se?(fe("pullFromRemote: 本地更新,跳过下载",{boardId:K,localUpdatedAt:new Date(Q).toISOString(),remoteUpdatedAt:new Date(se).toISOString()}),T.push({id:K,name:J.name||Z.name||K,localUpdatedAt:Q,remoteUpdatedAt:se})):(fe("pullFromRemote: checksum 不匹配,将下载远程版本",{boardId:K,localUpdatedAt:new Date(Q).toISOString(),remoteUpdatedAt:new Date(se).toISOString()}),k.push(K))}}}for(const K of I.boards.keys())_.boards[K]||R.push(K);fe("pullFromRemote: 同步计划",{toDownload:k.length,toDelete:R.length,skippedLocalDeletion:M.length,skippedLocalNewer:T.length}),T.length>0&&fe("pullFromRemote: 跳过的画板 (本地更新)",{boards:T.map(K=>K.id)});const F={};F[_t.MANIFEST]=x,fe("pullFromRemote: 下载 workspace 文件");const V=await yt.getGistFileContent(_t.WORKSPACE);V?(F[_t.WORKSPACE]=V,fe("pullFromRemote: workspace.json 已下载",{length:V.length})):Pt("pullFromRemote: workspace.json 未找到或为空"),fe("pullFromRemote: 下载 prompts 文件");const H=await yt.getGistFileContent(_t.PROMPTS);H?(F[_t.PROMPTS]=H,fe("pullFromRemote: prompts.json 已下载",{length:H.length})):Pt("pullFromRemote: prompts.json 未找到或为空"),fe("pullFromRemote: Downloading knowledge base file");const j=await yt.getGistFileContent(_t.KNOWLEDGE_BASE);j?(F[_t.KNOWLEDGE_BASE]=j,fe("pullFromRemote: knowledge-base.json downloaded",{length:j.length})):Pt("pullFromRemote: knowledge-base.json not found or empty"),fe("pullFromRemote: 下载画板文件",{count:k.length});for(const K of k){const Z=_t.boardFile(K);fe("pullFromRemote: 下载画板",{boardId:K});const oe=await yt.getGistFileContent(Z);oe?(F[Z]=oe,fe("pullFromRemote: 画板已下载",{boardId:K,length:oe.length})):Pt("pullFromRemote: 画板未找到或为空",{boardId:K})}fe("pullFromRemote: 文件下载摘要",{totalFiles:Object.keys(F).length,fileNames:Object.keys(F)}),fe("pullFromRemote: 开始反序列化");const z=await Or.deserializeFromGistFilesWithDecryption(F,w,y||void 0);fe("pullFromRemote: 反序列化完成",{workspace:z.workspace?{currentBoardId:z.workspace.currentBoardId,folders:((r=z.workspace.folders)==null?void 0:r.length)||0,boardMetadata:((i=z.workspace.boardMetadata)==null?void 0:i.length)||0}:null,boardsCount:z.boards.size,promptsCount:z.prompts?(((o=z.prompts.promptHistory)==null?void 0:o.length)||0)+(((s=z.prompts.videoPromptHistory)==null?void 0:s.length)||0)+(((a=z.prompts.imagePromptHistory)==null?void 0:a.length)||0):0,tasksCount:((c=(l=z.tasks)==null?void 0:l.completedTasks)==null?void 0:c.length)||0});const N=new Map(z.boards);for(const[K,Z]of I.boards)!k.includes(K)&&!R.includes(K)&&(N.has(K)||N.set(K,Z));const B=new Set(N.keys()),O=new Set(M);let $=z.workspace;$!=null&&$.boardMetadata&&($={...$,boardMetadata:$.boardMetadata.filter(K=>B.has(K.id)&&!O.has(K.id)),currentBoardId:$.currentBoardId&&B.has($.currentBoardId)&&!O.has($.currentBoardId)?$.currentBoardId:null}),fe("pullFromRemote: Workspace 已过滤",{appliedBoardIds:B.size,skippedBoardIds:O.size,currentBoardId:($==null?void 0:$.currentBoardId)||null}),fe("pullFromRemote: 开始应用同步数据",{boardsCount:N.size,boardIds:Array.from(N.keys()),workspace:$?{currentBoardId:$.currentBoardId,folders:((u=$.folders)==null?void 0:u.length)||0,boardMetadata:((d=$.boardMetadata)==null?void 0:d.length)||0}:null});const U=await Or.applySyncData({workspace:$,boards:N,prompts:z.prompts,tasks:z.tasks});if(fe("pullFromRemote: 应用同步数据完成",{boardsApplied:U.boardsApplied,promptsApplied:U.promptsApplied,tasksApplied:U.tasksApplied,remoteCurrentBoardId:U.remoteCurrentBoardId}),await this.saveConfig({gistId:w,lastSyncTime:Date.now(),enabled:!0}),n.downloaded.boards=k.length,n.downloaded.prompts=U.promptsApplied,n.downloaded.tasks=U.tasksApplied,n.remoteCurrentBoardId=U.remoteCurrentBoardId,z.knowledgeBase){fe("pullFromRemote: Applying knowledge base (merge)");let K=z.knowledgeBase;I.knowledgeBase&&(K=Bf.merge(I.knowledgeBase,z.knowledgeBase)),await Bf.apply(K),n.downloaded.knowledgeBase=K.notes.length+K.directories.length}n.success=!0,T.length>0&&(n.skippedItems=T.map(K=>({id:K.id,name:K.name,reason:"local_newer",localUpdatedAt:K.localUpdatedAt,remoteUpdatedAt:K.remoteUpdatedAt}))),Jr("pullFromRemote: 下载成功",{downloaded:n.downloaded,skippedItems:((f=n.skippedItems)==null?void 0:f.length)||0,remoteCurrentBoardId:n.remoteCurrentBoardId}),this.setStatus("synced"),this.pendingChanges=!1;const Y=[];for(const[K]of P)_.boards[K]?k.includes(K)&&Y.push(K):Y.push(K);Y.length>0&&(fe("pullFromRemote: 清理删除记录",{count:Y.length}),await this.clearLocalDeletions(Y)),await this.uploadMergedTasksToRemote(w,y||void 0),await this.initializeShardingSystem(w),this.downloadSyncedMediaAsync()}catch(p){vn("pullFromRemote 失败",p instanceof Error?p:new Error(String(p))),p instanceof Lf?(n.error=p.message,n.needsPassword=p.needsPassword):n.error=p instanceof Error?p.message:"下载失败",this.setStatus("error",n.error)}finally{this.syncInProgress=!1,n.duration=Date.now()-t}return n}markDirty(){fe("markDirty called",{status:this.status,syncInProgress:this.syncInProgress}),this.pendingChanges=!0,this.status==="synced"&&this.setStatus("local_changes"),this.scheduleAutoSync()}hasPendingChanges(){return this.pendingChanges}async getLocalDeletionsPendingSync(){const t=await er.get(o2);if(fe("getLocalDeletionsPendingSync: 从存储加载数据",{hasData:!!t}),!t)return new Map;if(Array.isArray(t)){fe("getLocalDeletionsPendingSync: 从旧格式迁移");const r=Date.now(),i=new Map;return t.forEach(o=>i.set(o,r)),await er.set(o2,Object.fromEntries(i)),i}const n=new Map(Object.entries(t));return fe("getLocalDeletionsPendingSync: 已加载删除记录",{count:n.size}),n}async recordLocalDeletion(t){const n=await this.getLocalDeletionsPendingSync(),r=Date.now();n.set(t,r),fe("recordLocalDeletion: 记录本地删除",{boardId:t,deletedAt:r}),await er.set(o2,Object.fromEntries(n))}async syncBoardDeletion(t){if(fe("syncBoardDeletion",{boardId:t}),!ai.hasToken())return fe("syncBoardDeletion: 无 Token,跳过"),{success:!1,error:"未配置 GitHub Token"};const n=await this.getConfig();if(!n.gistId)return fe("syncBoardDeletion: 无 GistId,跳过"),{success:!1,error:"未配置同步 Gist"};try{yt.setGistId(n.gistId);const r=await pi.getPassword(),{cryptoService:i}=await xn(async()=>{const{cryptoService:p}=await Promise.resolve().then(()=>sl);return{cryptoService:p}},void 0,import.meta.url),o=await yt.getGistFileContent(_t.MANIFEST);if(!o)return{success:!1,error:"远程 manifest 不存在"};const s=await i.decryptOrPassthrough(o,n.gistId,r||void 0),a=JSON.parse(s),l=a.boards[t];if(!l)return fe("syncBoardDeletion: 画板不在远程 manifest 中"),{success:!0};if(l.deletedAt)return fe("syncBoardDeletion: 画板已在远程删除"),{success:!0};const c=await ai.getUserInfo(),u=(c==null?void 0:c.login)||"unknown",d=Date.now();a.boards[t]={...l,deletedAt:d,deletedBy:u},a.updatedAt=d;const f=JSON.stringify(a);return await yt.updateGistFiles({[_t.MANIFEST]:await i.encrypt(f,n.gistId,r||void 0)}),fe("syncBoardDeletion: Manifest 已加密更新"),Jr("syncBoardDeletion: 画板已移入回收站",{boardId:t}),await this.clearLocalDeletions([t]),{success:!0}}catch(r){return vn("syncBoardDeletion 失败",r instanceof Error?r:new Error(String(r))),{success:!1,error:r instanceof Error?r.message:"同步删除失败"}}}async clearLocalDeletions(t){if(t.length===0)return;const n=await this.getLocalDeletionsPendingSync();t.forEach(r=>n.delete(r)),fe("clearLocalDeletions",{boardIds:t}),await er.set(o2,Object.fromEntries(n))}async scheduleAutoSync(){if(!ai.hasToken()){fe("scheduleAutoSync: No token, skipping");return}const t=await this.getConfig();if(fe("scheduleAutoSync config",{autoSync:t.autoSync,debounceMs:t.autoSyncDebounceMs}),!t.autoSync){fe("scheduleAutoSync: Auto sync disabled, skipping");return}this.autoSyncTimer&&(fe("scheduleAutoSync: Clearing previous timer"),clearTimeout(this.autoSyncTimer)),this.autoSyncTimer=setTimeout(async()=>{fe("Auto sync timer fired",{pendingChanges:this.pendingChanges,syncInProgress:this.syncInProgress}),this.pendingChanges&&!this.syncInProgress?(fe("Auto sync triggered after debounce, pushing local changes to remote..."),await this.pushToRemote()):fe("Auto sync skipped",{pendingChanges:this.pendingChanges,syncInProgress:this.syncInProgress})},t.autoSyncDebounceMs),fe("Auto sync scheduled",{debounceMs:t.autoSyncDebounceMs})}async detectLocalChanges(){const t=await this.getConfig(),n=await Or.collectSyncData();if(!t.gistId||!t.lastSyncTime)return{addedBoards:Array.from(n.boards.keys()),modifiedBoards:[],deletedBoards:[],promptsChanged:!0,tasksChanged:!0};try{const r=await pi.getPassword(),{cryptoService:i}=await xn(async()=>{const{cryptoService:c}=await Promise.resolve().then(()=>sl);return{cryptoService:c}},void 0,import.meta.url),o=await yt.getGistFileContent(_t.MANIFEST);if(!o)return{addedBoards:Array.from(n.boards.keys()),modifiedBoards:[],deletedBoards:[],promptsChanged:!0,tasksChanged:!0};const s=await i.decryptOrPassthrough(o,t.gistId,r||void 0),a=JSON.parse(s),l=Or.compareBoardChanges(n.boards,a,t.lastSyncTime);return{addedBoards:l.toUpload.filter(c=>!a.boards[c]),modifiedBoards:l.toUpload.filter(c=>a.boards[c]),deletedBoards:[],promptsChanged:!0,tasksChanged:!0}}catch(r){return vn("检测变更失败",r instanceof Error?r:new Error(String(r))),{addedBoards:[],modifiedBoards:[],deletedBoards:[],promptsChanged:!1,tasksChanged:!1}}}async resolveConflict(t,n){fe("解决冲突",{conflictId:t.id,resolution:n})}async getDeletedItems(){const t={boards:[],prompts:[],tasks:[]},n=await this.getConfig();if(!n.gistId)return t;try{yt.setGistId(n.gistId);const r=await pi.getPassword(),{cryptoService:i}=await xn(async()=>{const{cryptoService:l}=await Promise.resolve().then(()=>sl);return{cryptoService:l}},void 0,import.meta.url),o=await yt.getGistFileContent(_t.MANIFEST);if(!o)return t;const s=await i.decryptOrPassthrough(o,n.gistId,r||void 0),a=JSON.parse(s);return t.boards=Or.getDeletedBoards(a),a.deletedPrompts&&(t.prompts=a.deletedPrompts),a.deletedTasks&&(t.tasks=a.deletedTasks),fe("getDeletedItems",{boards:t.boards.length,prompts:t.prompts.length,tasks:t.tasks.length}),t}catch(r){return vn("获取已删除项目失败",r instanceof Error?r:new Error(String(r))),t}}async restoreItem(t,n){const r=await this.getConfig();if(!r.gistId)return{success:!1,error:"未配置同步"};try{yt.setGistId(r.gistId);const i=await pi.getPassword(),{cryptoService:o}=await xn(async()=>{const{cryptoService:c}=await Promise.resolve().then(()=>sl);return{cryptoService:c}},void 0,import.meta.url),s=await yt.getGistFileContent(_t.MANIFEST);if(!s)return{success:!1,error:"无法获取远程数据"};const a=await o.decryptOrPassthrough(s,r.gistId,i||void 0);let l=JSON.parse(a);if(t==="board"){const c=l.boards[n];if(!c||!c.deletedAt)return{success:!1,error:"画板不存在或未被删除"};const u=await yt.getGistFileContent(_t.boardFile(n));if(!u)return{success:!1,error:"画板数据不存在"};const d=await o.decryptOrPassthrough(u,r.gistId,i||void 0),f=JSON.parse(d);await Bn.saveBoard(f),l=Or.unmarkBoardAsDeleted(l,n);const p=JSON.stringify(l);return await yt.updateGistFiles({[_t.MANIFEST]:await o.encrypt(p,r.gistId,i||void 0)}),await AG(),Jr("恢复画板成功",{boardId:n}),{success:!0}}else{if(t==="prompt")return{success:!1,error:"提示词恢复功能暂未实现"};if(t==="task")return{success:!1,error:"任务恢复功能暂未实现"}}return{success:!1,error:"未知类型"}}catch(i){return vn("恢复项目失败",i instanceof Error?i:new Error(String(i))),{success:!1,error:i instanceof Error?i.message:"恢复失败"}}}async permanentlyDelete(t,n){const r=await this.getConfig();if(!r.gistId)return{success:!1,error:"未配置同步"};try{yt.setGistId(r.gistId);const i=await pi.getPassword(),{cryptoService:o}=await xn(async()=>{const{cryptoService:c}=await Promise.resolve().then(()=>sl);return{cryptoService:c}},void 0,import.meta.url),s=await yt.getGistFileContent(_t.MANIFEST);if(!s)return{success:!1,error:"无法获取远程数据"};const a=await o.decryptOrPassthrough(s,r.gistId,i||void 0);let l=JSON.parse(a);if(t==="board"){const c=l.boards[n];if(!c||!c.deletedAt)return{success:!1,error:"画板不存在或未被删除"};delete l.boards[n],l.updatedAt=Date.now();const u=JSON.stringify(l),d={[_t.MANIFEST]:await o.encrypt(u,r.gistId,i||void 0)};return await yt.deleteGistFiles([_t.boardFile(n)]),await yt.updateGistFiles(d),Jr("永久删除画板成功",{boardId:n}),{success:!0}}else{if(t==="prompt")return{success:!1,error:"提示词永久删除功能暂未实现"};if(t==="task")return{success:!1,error:"任务永久删除功能暂未实现"}}return{success:!1,error:"未知类型"}}catch(i){return vn("永久删除项目失败",i instanceof Error?i:new Error(String(i))),{success:!1,error:i instanceof Error?i.message:"删除失败"}}}async emptyRecycleBin(){var r,i;const t={success:!1,deletedBoards:0,deletedPrompts:0,deletedTasks:0},n=await this.getConfig();if(!n.gistId)return{...t,error:"未配置同步"};try{yt.setGistId(n.gistId);const o=await pi.getPassword(),{cryptoService:s}=await xn(async()=>{const{cryptoService:v}=await Promise.resolve().then(()=>sl);return{cryptoService:v}},void 0,import.meta.url),a=await yt.getGistFileContent(_t.MANIFEST);if(!a)return{...t,error:"无法获取远程数据"};const l=await s.decryptOrPassthrough(a,n.gistId,o||void 0);let c=JSON.parse(l);const u=[],d=[];for(const[v,w]of Object.entries(c.boards))w.deletedAt&&(u.push(_t.boardFile(v)),d.push(v));for(const v of d)delete c.boards[v];const f=((r=c.deletedPrompts)==null?void 0:r.length)||0,p=((i=c.deletedTasks)==null?void 0:i.length)||0;c.deletedPrompts=[],c.deletedTasks=[],c.updatedAt=Date.now(),u.length>0&&await yt.deleteGistFiles(u);const y=JSON.stringify(c);return await yt.updateGistFiles({[_t.MANIFEST]:await s.encrypt(y,n.gistId,o||void 0)}),t.success=!0,t.deletedBoards=d.length,t.deletedPrompts=f,t.deletedTasks=p,Jr("回收站已清空",t),t}catch(o){return vn("清空回收站失败",o instanceof Error?o:new Error(String(o))),{...t,error:o instanceof Error?o.message:"清空失败"}}}async reset(){await this.saveConfig({gistId:null,lastSyncTime:null,enabled:!1}),yt.setGistId(null),this.setStatus("not_configured")}async disconnect(){ai.clearToken(),await this.reset()}async getLastSyncTime(){return(await this.getConfig()).lastSyncTime}getGistUrl(){return yt.getGistWebUrl()}async listSyncGists(){const t=await yt.listSyncGists(),n=await this.getConfig();return t.map(r=>({id:r.id,description:r.description,createdAt:r.created_at,updatedAt:r.updated_at,filesCount:Object.keys(r.files).length,url:`https://gist.github.com/${r.id}`,isCurrent:r.id===n.gistId,isMaster:yt.isGistMaster(r)}))}async switchToGist(t){return await this.saveConfig({gistId:t,lastSyncTime:null,enabled:!0}),yt.setGistId(t),this.sync()}async deleteGist(t){(await this.getConfig()).gistId===t&&await this.reset(),await yt.deleteGist(t)}async createNewGist(){const t=Date.now(),n={success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0};try{this.setStatus("syncing","正在创建新的 Gist..."),await this.saveConfig({gistId:null,lastSyncTime:null,enabled:!0}),yt.setGistId(null);const r=await Or.collectSyncData();fe("创建新 Gist");const o=(await yt.createSyncGist({"manifest.json":JSON.stringify({version:1,initializing:!0},null,2)})).id;fe("空 Gist 已创建",{gistId:xa(o)});const s=await pi.getPassword();fe("使用自定义密码创建 Gist",{hasPassword:!!s});const a=await Or.serializeToGistFilesEncrypted(r,o,s||void 0);yt.setGistId(o),await yt.updateGistFiles(a);try{const c=await Kl.syncTasks(o,s||void 0);n.uploaded.tasks=c.uploaded}catch(c){Pt("创建新 Gist: Tasks paged sync failed",{error:String(c)})}await this.saveConfig({gistId:o,lastSyncTime:Date.now(),enabled:!0}),n.uploaded.boards=r.boards.size,n.uploaded.prompts=r.prompts.promptHistory.length+r.prompts.videoPromptHistory.length+r.prompts.imagePromptHistory.length,n.success=!0,this.setStatus("synced"),this.pendingChanges=!1,Jr("新 Gist 创建成功");const l=r.workspace.currentBoardId;l&&n.uploaded.boards>0&&this.syncCurrentBoardMediaAsync(l)}catch(r){vn("创建新 Gist 失败",r instanceof Error?r:new Error(String(r))),n.error=r instanceof Error?r.message:"创建失败",this.setStatus("error",n.error)}finally{n.duration=Date.now()-t}return n}async initializeShardingSystem(t){try{const{shardedMediaSyncAdapter:n}=await xn(async()=>{const{shardedMediaSyncAdapter:i}=await Promise.resolve().then(()=>Qle);return{shardedMediaSyncAdapter:i}},void 0,import.meta.url);if(n.isShardingEnabled()){fe("分片系统已启用");return}fe("初始化分片系统",{gistId:xa(t)});const r=await n.setupShardSystem(t);r.success?Jr("分片系统初始化成功"):Pt("分片系统初始化失败",{error:r.error})}catch(n){vn("分片系统初始化错误",n instanceof Error?n:new Error(String(n)))}}async syncPaged(){const t={success:!1,tasksUploaded:0,tasksDownloaded:0,workflowsUploaded:0,workflowsDownloaded:0,tasksSkipped:0,workflowsSkipped:0};try{const n=await this.getConfig();if(!n.gistId)return t.error="未配置 Gist ID",t;const r=await pi.getPassword();Tr("开始分页同步",{gistId:xa(n.gistId)});try{const i=await Kl.syncTasks(n.gistId,r||void 0);t.tasksUploaded=i.uploaded,t.tasksDownloaded=i.downloaded,t.tasksSkipped=i.skipped}catch(i){Pt("任务同步失败",{error:String(i)})}try{const i=await Eet.syncWorkflows(n.gistId,r||void 0);t.workflowsUploaded=i.uploaded,t.workflowsDownloaded=i.downloaded,t.workflowsSkipped=i.skipped}catch(i){Pt("工作流同步失败",{error:String(i)})}try{const i=await Ket.syncTools(n.gistId,r||void 0);fe("自定义工具同步结果",i)}catch(i){Pt("自定义工具同步失败",{error:String(i)})}t.success=!0,Jr("分页同步完成",{tasksUploaded:t.tasksUploaded,tasksDownloaded:t.tasksDownloaded,tasksSkipped:t.tasksSkipped,workflowsUploaded:t.workflowsUploaded,workflowsDownloaded:t.workflowsDownloaded,workflowsSkipped:t.workflowsSkipped})}catch(n){t.error=n instanceof Error?n.message:String(n),vn("分页同步失败",n instanceof Error?n:new Error(String(n)))}return t}async detectRemoteTaskFormat(){try{const t=await this.getConfig();return t.gistId?(yt.setGistId(t.gistId),(await yt.getGist()).files[li.TASK_INDEX]?"paged":"none"):"none"}catch(t){return Pt("检测远程格式失败",{error:t instanceof Error?t.message:String(t)}),"none"}}destroy(){this.autoSyncTimer&&(clearTimeout(this.autoSyncTimer),this.autoSyncTimer=null),this.statusListeners.clear()}}const Kn=new qet,IV=Object.freeze(Object.defineProperty({__proto__:null,syncEngine:Kn},Symbol.toStringTag,{value:"Module"}));function Gp(e,t,n){let r=n.initialDeps??[],i,o=!0;function s(){var a,l,c;let u;n.key&&((a=n.debug)!=null&&a.call(n))&&(u=Date.now());const d=e();if(!(d.length!==r.length||d.some((y,v)=>r[v]!==y)))return i;r=d;let p;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(p=Date.now()),i=t(...d),n.key&&((c=n.debug)!=null&&c.call(n))){const y=Math.round((Date.now()-u)*100)/100,v=Math.round((Date.now()-p)*100)/100,w=v/16,C=(x,E)=>{for(x=String(x);x.length<E;)x=" "+x;return x};console.info(`%c⏱ ${C(v,5)} /${C(y,5)} ms`,`
|
|
2588
2588
|
font-size: .6rem;
|
|
2589
2589
|
font-weight: bold;
|
|
2590
2590
|
color: hsl(${Math.max(0,Math.min(120-120*w,120))}deg 100% 31%);`,n==null?void 0:n.key)}return n!=null&&n.onChange&&!(o&&n.skipInitialOnChange)&&n.onChange(i),o=!1,i}return s.updateDeps=a=>{r=a},s}function AV(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const Yet=(e,t)=>Math.abs(e-t)<1.01,Xet=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},PV=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},Zet=e=>e,Jet=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),r=[];for(let i=t;i<=n;i++)r.push(i);return r},Qet=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=s=>{const{width:a,height:l}=s;t({width:Math.round(a),height:Math.round(l)})};if(i(PV(n)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(s=>{const a=()=>{const l=s[0];if(l!=null&&l.borderBoxSize){const c=l.borderBoxSize[0];if(c){i({width:c.inlineSize,height:c.blockSize});return}}i(PV(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},kV={passive:!0},TV=typeof window>"u"?!0:"onscrollend"in window,ett=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let i=0;const o=e.options.useScrollendEvent&&TV?()=>{}:Xet(r,()=>{t(i,!1)},e.options.isScrollingResetDelay),s=u=>()=>{const{horizontal:d,isRtl:f}=e.options;i=d?n.scrollLeft*(f&&-1||1):n.scrollTop,o(),t(i,u)},a=s(!0),l=s(!1);n.addEventListener("scroll",a,kV);const c=e.options.useScrollendEvent&&TV;return c&&n.addEventListener("scrollend",l,kV),()=>{n.removeEventListener("scroll",a),c&&n.removeEventListener("scrollend",l)}},ttt=(e,t,n)=>{if(t!=null&&t.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},ntt=(e,{adjustments:t=0,behavior:n},r)=>{var i,o;const s=e+t;(o=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||o.call(i,{[r.options.horizontal?"left":"top"]:s,behavior:n})};class rtt{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.currentScrollToIndex=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(o=>{const s=()=>{this._measureElement(o.target,o)};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(s):s()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var o;return(o=r())==null?void 0:o.observe(i,{box:"border-box"})},unobserve:i=>{var o;return(o=r())==null?void 0:o.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([r,i])=>{typeof i>"u"&&delete n[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Zet,rangeExtractor:Jet,onChange:()=>{},measureElement:ttt,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...n}},this.notify=n=>{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=Gp(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(i=>{this.observer.observe(i)}),this.unsubs.push(this.options.observeElementRect(this,i=>{this.scrollRect=i,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(i,o)=>{this.scrollAdjustments=0,this.scrollDirection=o?this.getScrollOffset()<i?"forward":"backward":null,this.scrollOffset=i,this.isScrolling=o,this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,r)=>{const i=new Map,o=new Map;for(let s=r-1;s>=0;s--){const a=n[s];if(i.has(a.lane))continue;const l=o.get(a.lane);if(l==null||a.end>l.end?o.set(a.lane,a):a.end<l.end&&i.set(a.lane,!0),i.size===this.options.lanes)break}return o.size===this.options.lanes?Array.from(o.values()).sort((s,a)=>s.end===a.end?s.index-a.index:s.end-a.end)[0]:void 0},this.getMeasurementOptions=Gp(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes],(n,r,i,o,s,a)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:i,getItemKey:o,enabled:s,lanes:a}),{key:!1}),this.getMeasurements=Gp(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:i,getItemKey:o,enabled:s,lanes:a},l)=>{if(!s)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const f of this.laneAssignments.keys())f>=n&&this.laneAssignments.delete(f);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(f=>{this.itemSizeCache.set(f.key,f.size)}));const c=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1);const u=this.measurementsCache.slice(0,c),d=new Array(a).fill(void 0);for(let f=0;f<c;f++){const p=u[f];p&&(d[p.lane]=f)}for(let f=c;f<n;f++){const p=o(f),y=this.laneAssignments.get(f);let v,w;if(y!==void 0&&this.options.lanes>1){v=y;const _=d[v],I=_!==void 0?u[_]:void 0;w=I?I.end+this.options.gap:r+i}else{const _=this.options.lanes===1?u[f-1]:this.getFurthestMeasurement(u,f);w=_?_.end+this.options.gap:r+i,v=_?_.lane:f%this.options.lanes,this.options.lanes>1&&this.laneAssignments.set(f,v)}const C=l.get(p),x=typeof C=="number"?C:this.options.estimateSize(f),E=w+x;u[f]={index:f,start:w,size:x,end:E,key:p,lane:v},d[v]=f}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Gp(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,o)=>this.range=n.length>0&&r>0?itt({measurements:n,outerSize:r,scrollOffset:i,lanes:o}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Gp(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,o,s)=>o===null||s===null?[]:n({startIndex:o,endIndex:s,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this._measureElement=(n,r)=>{const i=this.indexFromElement(n),o=this.measurementsCache[i];if(!o)return;const s=o.key,a=this.elementsCache.get(s);a!==n&&(a&&this.observer.unobserve(a),this.observer.observe(n),this.elementsCache.set(s,n)),n.isConnected&&this.resizeItem(i,this.options.measureElement(n,r,this))},this.resizeItem=(n,r)=>{const i=this.measurementsCache[n];if(!i)return;const o=this.itemSizeCache.get(i.key)??i.size,s=r-o;s!==0&&((this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(i,s,this):i.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=s,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(i.index),this.itemSizeCache=new Map(this.itemSizeCache.set(i.key,r)),this.notify(!1))},this.measureElement=n=>{if(!n){this.elementsCache.forEach((r,i)=>{r.isConnected||(this.observer.unobserve(r),this.elementsCache.delete(i))});return}this._measureElement(n,void 0)},this.getVirtualItems=Gp(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let o=0,s=n.length;o<s;o++){const a=n[o],l=r[a];i.push(l)}return i},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return AV(r[jle(0,r.length-1,i=>AV(r[i]).start,n)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),s=this.getScrollOffset();r==="auto"&&(r=n>=s+o?"end":"start"),r==="center"?n+=(i-o)/2:r==="end"&&(n-=o);const a=this.getMaxScrollOffset();return Math.max(Math.min(a,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.measurementsCache[n];if(!i)return;const o=this.getSize(),s=this.getScrollOffset();if(r==="auto")if(i.end>=s+o-this.options.scrollPaddingEnd)r="end";else if(i.start<=s+this.options.scrollPaddingStart)r="start";else return[s,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const a=r==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,r,i.size),r]},this.isDynamicMode=()=>this.elementsCache.size>0,this.scrollToOffset=(n,{align:r="start",behavior:i}={})=>{i==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getOffsetForAlignment(n,r),{adjustments:void 0,behavior:i})},this.scrollToIndex=(n,{align:r="auto",behavior:i}={})=>{i==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),n=Math.max(0,Math.min(n,this.options.count-1)),this.currentScrollToIndex=n;let o=0;const s=10,a=c=>{if(!this.targetWindow)return;const u=this.getOffsetForIndex(n,c);if(!u){console.warn("Failed to get offset for index:",n);return}const[d,f]=u;this._scrollToOffset(d,{adjustments:void 0,behavior:i}),this.targetWindow.requestAnimationFrame(()=>{const p=()=>{if(this.currentScrollToIndex!==n)return;const y=this.getScrollOffset(),v=this.getOffsetForIndex(n,f);if(!v){console.warn("Failed to get offset for index:",n);return}Yet(v[0],y)||l(f)};this.isDynamicMode()?this.targetWindow.requestAnimationFrame(p):p()})},l=c=>{this.targetWindow&&this.currentScrollToIndex===n&&(o++,o<s?this.targetWindow.requestAnimationFrame(()=>a(c)):console.warn(`Failed to scroll to index ${n} after ${s} attempts.`))};a(r)},this.scrollBy=(n,{behavior:r}={})=>{r==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getScrollOffset()+n,{adjustments:void 0,behavior:r})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1)i=((n=r[r.length-1])==null?void 0:n.end)??0;else{const o=Array(this.options.lanes).fill(null);let s=r.length-1;for(;s>=0&&o.some(a=>a===null);){const a=r[s];o[a.lane]===null&&(o[a.lane]=a.end),s--}i=Math.max(...o.filter(a=>a!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(t)}}const jle=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,o=n(i);if(o<r)e=i+1;else if(o>r)t=i-1;else return i}return e>0?e-1:0};function itt({measurements:e,outerSize:t,scrollOffset:n,lanes:r}){const i=e.length-1,o=l=>e[l].start;if(e.length<=r)return{startIndex:0,endIndex:i};let s=jle(0,i,o,n),a=s;if(r===1)for(;a<i&&e[a].end<n+t;)a++;else if(r>1){const l=Array(r).fill(0);for(;a<i&&l.some(u=>u<n+t);){const u=e[a];l[u.lane]=u.end,a++}const c=Array(r).fill(n+t);for(;s>=0&&c.some(u=>u>=n);){const u=e[s];c[u.lane]=u.start,s--}s=Math.max(0,s-s%r),a=Math.min(i,a+(r-1-a%r))}return{startIndex:s,endIndex:a}}const DV=typeof document<"u"?b.useLayoutEffect:b.useEffect;function ott({useFlushSync:e=!0,...t}){const n=b.useReducer(()=>({}),{})[1],r={...t,onChange:(o,s)=>{var a;e&&s?Ui.flushSync(n):n(),(a=t.onChange)==null||a.call(t,o,s)}},[i]=b.useState(()=>new rtt(r));return i.setOptions(r),DV(()=>i._didMount(),[]),DV(()=>i._willUpdate()),i}function stt(e){return ott({observeElementRect:Qet,observeElementOffset:ett,scrollToFn:ntt,...e})}const MV=b.memo(function({src:t,alt:n,placeholder:r,className:i="",style:o,objectFit:s="contain",rootMargin:a="200px",showLoading:l=!0,showError:c=!0,onLoad:u,onError:d,onClick:f}){const p=b.useRef(null),[y,v]=b.useState(!1),[w,C]=b.useState(!1),[x,E]=b.useState(!1),[_,I]=b.useState(!1);b.useEffect(()=>{E(!1),I(!1),C(!1)},[t]),b.useEffect(()=>{if(y)return;const P=p.current;if(!P)return;const k=new IntersectionObserver(R=>{R.forEach(T=>{T.isIntersecting&&(v(!0),k.disconnect())})},{rootMargin:a,threshold:0});return k.observe(P),()=>{k.disconnect()}},[y,a]),b.useEffect(()=>{y&&t&&!x&&!_&&C(!0)},[_,x,y,t]);const D=b.useCallback(()=>{I(!1),E(!1),C(!1),v(!1),requestAnimationFrame(()=>v(!0))},[]);return g.jsxs("div",{ref:p,className:`lazy-image ${i}`,style:o,onClick:f,children:[!x&&!_&&g.jsx("div",{className:"lazy-image__placeholder",children:r||(l&&w?g.jsx(ty,{size:"small"}):g.jsx("div",{className:"lazy-image__skeleton"}))}),_&&c&&g.jsxs("div",{className:"lazy-image__error",onClick:D,children:[g.jsx("span",{className:"lazy-image__error-icon",children:"⚠️"}),g.jsx("span",{className:"lazy-image__error-text",children:"加载失败"}),g.jsx("span",{className:"lazy-image__error-retry",children:"点击重试"})]}),y&&!_&&g.jsx(xs,{src:t,alt:n,className:"lazy-image__img",style:{objectFit:s},showSkeleton:!1,onLoad:()=>{C(!1),E(!0),u==null||u()},onLoadFailure:()=>{C(!1),I(!0),d==null||d()}})]})}),Ff=new Map,Lle=300*1e3,OV=500,ud=new Set;let rg=!1,Jk=null,Qk=null;function att(){return Jk||(Jk=caches.open("drawnix-images-thumb")),Jk}function ltt(){return Qk||(Qk=caches.open("drawnix-images")),Qk}function Ble(e,t){return`${e}|${t}`}function ctt(e,t){try{const n=new URL(e,window.location.origin);return n.searchParams.delete("thumbnail"),n.searchParams.set("_thumb",t),n.toString()}catch{const n=e.replace(/[?&]thumbnail=[^&]*/g,"").replace(/thumbnail=[^&]*&?/g,""),r=n.includes("?")?"&":"?";return`${n}${r}_thumb=${t}`}}function uI(e,t){return e.startsWith("data:")||e.startsWith("blob:")||t!=="video"&&(e.startsWith("http://")||e.startsWith("https://"))}function RV(e,t="small",n){const r=zn(e);if(uI(r,n))return r;try{const i=new URL(r,window.location.origin);return i.searchParams.set("thumbnail",t),i.toString()}catch{const i=r.includes("?")?"&":"?";return`${r}${i}thumbnail=${t}`}}async function Dv(){if(!(rg||ud.size===0)){rg=!0;try{const e=Date.now();if(Ff.size>OV)for(const[r,i]of Ff)(e-i>Lle||Ff.size>OV)&&Ff.delete(r);const n=Array.from(ud).slice(0,5);for(const r of n){ud.delete(r);const[i,o,s="small"]=r.split("|");try{await Fle(i,o,s),Ff.set(Ble(i,s),Date.now())}catch(a){console.warn("Failed to ensure thumbnail:",i,a)}}ud.size>0&&("requestIdleCallback"in window?window.requestIdleCallback(Dv):setTimeout(Dv,100))}finally{rg=!1}}}async function Fle(e,t,n){const r=zn(e);if(uI(r,t))return;const i=ctt(r,n);if(await(await att()).match(i))return;const a=await ltt();let l=await a.match(r);if(!l)try{const c=new URL(r,window.location.origin);(c.pathname.startsWith("/__aitu_cache__/")||c.pathname.startsWith("/asset-library/"))&&(l=await a.match(c.pathname))}catch{}if(l){const c=await l.blob();if(Hc.isInitialized()){const u=await c.arrayBuffer();await Hc.generateThumbnail(r,t,u,c.type,[n])}}}function utt(e,t,n,r=!1){const i=zn(e);if(uI(i,t))return;const o=Ble(i,n),s=Ff.get(o);if(s&&Date.now()-s<Lle)return;const a=`${i}|${t}|${n}`;if(!ud.has(a)){if(ud.add(a),r){(async()=>{if(!rg)try{rg=!0,ud.delete(a),await Fle(i,t,n),Ff.set(o,Date.now())}catch(l){console.warn("Failed to ensure thumbnail immediately:",i,l)}finally{rg=!1,ud.size>0&&setTimeout(Dv,0)}})();return}"requestIdleCallback"in window?window.requestIdleCallback(Dv,{timeout:2e3}):setTimeout(Dv,200)}}function $le(e,t,n="small"){const[r,i]=b.useState(e?RV(e,n,t):void 0);return b.useEffect(()=>{if(!e){i(void 0);return}const o=zn(e),s=RV(o,n,t);i(s),t&&!uI(e,t)&&utt(e,t,n,t==="video")},[e,t,n]),r}const NV=1,dtt=4,zle=600*1e3,Ule=600*1e3,LC=new Map,BC=new Map;function Hle(e){LC.forEach((t,n)=>{e-t>zle&&LC.delete(n)})}function ftt(e){const t=Date.now();Hle(t),LC.set(e,t)}function htt(e){const t=Date.now();Hle(t);const n=LC.get(e);return typeof n=="number"&&t-n<=zle}function Wle(e){BC.forEach((t,n)=>{e-t.resolvedAt>Ule&&BC.delete(n)})}function ptt(e,t){const n=Date.now();Wle(n),BC.set(e,{resolvedPoster:t,resolvedAt:n})}function jV(e){if(!e)return null;const t=Date.now();Wle(t);const n=BC.get(e);return n&&t-n.resolvedAt<=Ule?n.resolvedPoster:null}function mtt(e,t){if(t<=0||!e)return e;try{const n=new URL(e,window.location.origin);return n.searchParams.set("_poster_retry",String(t)),n.toString()}catch{const n=e.includes("?")?"&":"?";return`${e}${n}_poster_retry=${t}`}}function eT(e,t){return g.jsxs("div",{className:"video-poster-preview",children:[e,t&&g.jsx("div",{className:"video-poster-preview__play-overlay","aria-hidden":"true",children:g.jsx(lZ,{size:"32px"})})]})}const cN=({src:e,poster:t,alt:n="",className:r,thumbnailSize:i="small",imageLoading:o="lazy",activateVideoOnClick:s=!1,playOnActivate:a=!1,onClick:l,videoProps:c})=>{const u=b.useMemo(()=>typeof t=="string"&&t.trim()?t.trim():void 0,[t]),d=b.useMemo(()=>u?htt(u):!1,[u]),f=$le(e,"video",i),[p,y]=b.useState(d),v=p?f:u||f,w=!!(u&&!p),C=!!(v&&v===f&&v!==e),x=b.useRef(null),E=b.useRef(!1),_=b.useRef(null),[I,D]=b.useState(()=>jV(v)),[P,k]=b.useState(0),[R,T]=b.useState(!1),M=s;b.useEffect(()=>{y(d)},[d]),b.useEffect(()=>{D(jV(v)),k(0),T(!1),E.current=!1,_.current!==null&&(window.clearTimeout(_.current),_.current=null)},[e,v,s,f,u,i]),b.useEffect(()=>{if(R||I&&I===v)return;if(!v){M||T(!0);return}const j=w?v:mtt(v,P);let z=!1;const N=new Image,B=()=>{if(!C||P>=dtt){M||T(!0);return}_.current=window.setTimeout(()=>{k(O=>O+1)},180+P*220)};return N.onload=()=>{if(!z){if(w||N.naturalWidth>NV||N.naturalHeight>NV){ptt(v,v),D(v);return}B()}},N.onerror=()=>{if(!z){if(w&&u){ftt(u),y(!0),D(null),k(0);return}B()}},N.src=j,()=>{z=!0,N.onload=null,N.onerror=null,_.current!==null&&(window.clearTimeout(_.current),_.current=null)}},[e,v,P,w,C,R,u,I,M]),b.useEffect(()=>{var j;!R||!a||!E.current||(E.current=!1,(j=x.current)==null||j.play().catch(()=>{}))},[R,a]),b.useEffect(()=>()=>{const j=x.current;if(j)try{j.pause(),j.removeAttribute("src"),j.load()}catch{}},[]);const F=j=>{s&&(E.current=!0,T(!0)),l==null||l(j)},V=j=>{l==null||l(j)},H=s&&!R;return!R&&I?eT(g.jsx("img",{src:I,alt:n,className:`video-poster-preview__media${r?` ${r}`:""}`,loading:o,decoding:"async",draggable:!1,referrerPolicy:"no-referrer",onClick:F}),H):!R&&!I?eT(g.jsx("div",{className:`video-poster-preview__placeholder${r?` ${r}`:""}`,"aria-hidden":"true",onClick:s?()=>{E.current=!0,T(!0)}:void 0}),H):eT(g.jsx("video",{ref:x,src:e,poster:I||u,className:`video-poster-preview__media${r?` ${r}`:""}`,playsInline:!0,...c,onClick:V}),!1)},Vle=b.memo(({asset:e,viewMode:t,isSelected:n,onSelect:r,onDoubleClick:i,onPreview:o,onContextMenu:s,isInSelectionMode:a,isSynced:l,isFavorite:c,onToggleFavorite:u})=>{var V,H;const d=fle(e.id,e.url,e.size),f=t==="grid"?"large":"small",p=$le(e.url,e.type==="IMAGE"?"image":void 0,f),{isCached:y,cacheWarning:v}=OQe(e.type==="IMAGE"||e.type==="VIDEO"?e.url:void 0),w=(e.type==="IMAGE"||e.type==="VIDEO")&&!y?v||e.cacheWarning:void 0,C=w?`${w.message}${w.expiresHint?`
|
|
2591
|
-
${w.expiresHint}`:""}`:"",x=b.useCallback(j=>{r(e.id,j)},[e.id,r]),E=b.useCallback(()=>{o&&!a&&o(e)},[e,o,a]),_=b.useCallback(j=>{j.preventDefault(),j.stopPropagation(),r(e.id,j)},[e.id,r]),I=b.useCallback(()=>{},[]),D=b.useCallback(j=>{j.stopPropagation(),j.preventDefault(),i==null||i(e)},[e,i]),P=b.useCallback(j=>{s==null||s(e,j)},[e,s]),k=b.useCallback(j=>{j.stopPropagation(),j.preventDefault(),u==null||u(e,j)},[e,u]),R=["asset-item",`asset-item--${t}`,n?"asset-item--selected":"",a?"asset-item--selection-mode":""].filter(Boolean).join(" "),T=t==="list",M=t==="compact",F=e.category===_s.CHARACTER;return g.jsxs("div",{className:R,onClick:x,onDoubleClick:E,onContextMenu:P,role:"button",tabIndex:0,"data-track":`asset_item_click_${t}`,children:[T&&a&&g.jsx("div",{className:"asset-item__checkbox asset-item__checkbox--left",onClick:_,children:g.jsx(ZT,{checked:n,onChange:I,"data-track":"asset_item_checkbox"})}),g.jsxs("div",{className:"asset-item__thumbnail",children:[e.type==="AUDIO"?e.thumbnail?g.jsx(MV,{src:e.thumbnail,alt:e.name,className:"asset-item__image",rootMargin:"100px"}):g.jsx("div",{className:"asset-item__audio-preview",children:g.jsx(zv,{size:32})}):e.type==="IMAGE"?g.jsx(MV,{src:p||e.url,alt:e.name,className:"asset-item__image",rootMargin:"100px"}):g.jsx(cN,{src:e.url,className:"asset-item__video",alt:e.name,poster:e.thumbnail,thumbnailSize:f,videoProps:{muted:!0,preload:"metadata"}}),!T&&!M&&g.jsxs("div",{className:"asset-item__badges",children:[g.jsx("div",{className:"asset-item__type-badge",children:e.type==="AUDIO"?g.jsx(zv,{}):e.type==="IMAGE"?g.jsx(wS,{}):g.jsx(cg,{})}),e.source==="AI_GENERATED"&&g.jsx("div",{className:"asset-item__ai-badge",children:"AI"}),F&&g.jsx(cn,{content:((V=e.characterMeta)==null?void 0:V.name)||"主体",showArrow:!1,children:g.jsxs("div",{className:"asset-item__subject-badge",children:[g.jsx(NT,{size:10}),g.jsx("span",{children:"主体"})]})}),l&&g.jsx(cn,{content:"已同步到云端",showArrow:!1,children:g.jsx("div",{className:"asset-item__synced-badge",children:g.jsx(T8,{size:10})})}),w&&g.jsx(cn,{content:C,showArrow:!1,children:g.jsx("div",{className:"asset-item__cache-warning-badge",children:"需下载"})})]}),e.type==="AUDIO"&&!a&&g.jsx("button",{type:"button",className:`asset-item__favorite-btn ${c?"asset-item__favorite-btn--active":""}`,onClick:k,"aria-label":c?"取消收藏":"加入收藏",children:g.jsx(vS,{size:14,fill:c?"currentColor":"none"})}),!T&&a&&g.jsx("div",{className:"asset-item__checkbox asset-item__checkbox--overlay",onClick:_,children:g.jsx(ZT,{checked:n,onChange:I,"data-track":"asset_item_checkbox"})}),!T&&!a&&i&&g.jsx(cn,{content:"插入到画布",showArrow:!1,children:g.jsx("button",{type:"button",className:"asset-item__preview-btn",onClick:D,"aria-label":"插入到画布","data-track":"asset_item_insert",children:g.jsx(ic,{size:16})})}),!T&&!M&&g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"asset-item__overlay"}),g.jsx(cn,{content:e.name,showArrow:!1,children:g.jsx("div",{className:"asset-item__name-overlay",children:e.name})})]})]}),T&&g.jsxs("div",{className:"asset-item__info",children:[g.jsx(cn,{content:e.name,showArrow:!1,children:g.jsx("div",{className:"asset-item__name",children:e.name})}),g.jsxs("div",{className:"asset-item__meta",children:[g.jsxs("span",{className:"asset-item__type",children:[e.type==="IMAGE"?g.jsx(wS,{size:12}):g.jsx(cg,{size:12}),e.type==="IMAGE"?"图片":"视频"]}),d&&g.jsx("span",{className:"asset-item__size",children:DC(d)}),g.jsx("span",{className:"asset-item__date",children:Eae(e.createdAt)})]})]}),T&&e.type==="AUDIO"&&!a&&g.jsx("button",{type:"button",className:`asset-item__favorite-btn asset-item__favorite-btn--list ${c?"asset-item__favorite-btn--active":""}`,onClick:k,"aria-label":c?"取消收藏":"加入收藏",children:g.jsx(vS,{size:14,fill:c?"currentColor":"none"})}),T&&e.source==="AI_GENERATED"&&g.jsx("div",{className:"asset-item__ai-badge asset-item__ai-badge--list",children:"AI"}),T&&F&&g.jsx(cn,{content:((H=e.characterMeta)==null?void 0:H.name)||"主体",showArrow:!1,children:g.jsxs("div",{className:"asset-item__subject-badge asset-item__subject-badge--list",children:[g.jsx(NT,{size:12}),g.jsx("span",{children:"主体"})]})}),T&&l&&g.jsx(cn,{content:"已同步到云端",showArrow:!1,children:g.jsx("div",{className:"asset-item__synced-badge asset-item__synced-badge--list",children:g.jsx(T8,{size:12})})}),T&&w&&g.jsx(cn,{content:C,showArrow:!1,children:g.jsx("div",{className:"asset-item__cache-warning-badge asset-item__cache-warning-badge--list",children:"需下载"})}),T&&!a&&i&&g.jsx(cn,{content:"插入到画布",showArrow:!1,children:g.jsx("button",{type:"button",className:"asset-item__preview-btn",onClick:D,"aria-label":"插入到画布","data-track":"asset_item_insert",children:g.jsx(ic,{size:16})})})]})},(e,t)=>e.asset.id===t.asset.id&&e.asset.name===t.asset.name&&e.asset.cacheWarning===t.asset.cacheWarning&&e.viewMode===t.viewMode&&e.isSelected===t.isSelected&&e.isInSelectionMode===t.isInSelectionMode&&e.onDoubleClick===t.onDoubleClick&&e.isSynced===t.isSynced&&e.isFavorite===t.isFavorite);Vle.displayName="AssetItem";const gtt={grid:{maxItemSize:180,minItemSize:120,gap:16,padding:20},compact:{maxItemSize:80,minItemSize:60,gap:4,padding:12},list:{maxItemSize:76,minItemSize:76,gap:0,padding:16}};function ytt(e){return!!e.closest('button, input, textarea, select, option, label, video, audio, a, .t-checkbox, [data-marquee-ignore="true"]')}function vtt(e,t){return!(e.right<t.left||e.left>t.right||e.bottom<t.top||e.top>t.bottom)}function wtt({assets:e,viewMode:t,gridSize:n=180,selectedAssetId:r,isAssetSelected:i,isSelectionMode:o,marqueeEnabled:s=!1,onSelectAsset:a,onMarqueeSelect:l,onDoubleClick:c,onPreview:u,onContextMenu:d,isFavorite:f,onToggleFavorite:p,syncedUrls:y}){const v=b.useRef(null),w=b.useRef(null),C=b.useRef(!1),x=b.useMemo(()=>{const $=gtt[t];return t==="grid"||t==="compact"?{...$,maxItemSize:n,minItemSize:Math.min(n,$.minItemSize)}:$},[t,n]),[E,_]=b.useState(800),[I,D]=b.useState(null);b.useEffect(()=>{const $=v.current;if(!$)return;const U=()=>{_($.clientWidth)};U();const Y=new ResizeObserver(U);return Y.observe($),()=>{Y.disconnect()}},[]);const P=b.useMemo(()=>{if(t==="list")return{columns:1,itemSize:x.maxItemSize};const $=E-x.padding*2,U=Math.max(1,Math.floor(($+x.gap)/(x.maxItemSize+x.gap))),Y=Math.floor(($-x.gap*(U-1))/U);return{columns:U,itemSize:Y}},[t,E,x]),k=P.columns,R=b.useMemo(()=>t==="list"?{width:E-x.padding*2,height:P.itemSize}:{width:P.itemSize,height:P.itemSize},[t,E,x.padding,P.itemSize]),T=b.useMemo(()=>Math.ceil(e.length/k),[e.length,k]),M=b.useCallback(()=>R.height+x.gap,[R.height,x.gap]),F=stt({count:T,getScrollElement:()=>v.current,estimateSize:M,overscan:3});b.useEffect(()=>{F.measure()},[E,T,k,F]);const V=b.useCallback($=>{const U=$*k;return e.slice(U,U+k).map(K=>{const Z=y?y.has(K.url):!1;return g.jsx("div",{"data-asset-cell":"true","data-asset-id":K.id,style:{width:"100%",height:R.height},children:g.jsx(Vle,{asset:K,viewMode:t,isSelected:o?i(K):r===K.id,onSelect:a,onDoubleClick:c,onPreview:u,onContextMenu:d,isInSelectionMode:o,isSynced:Z,isFavorite:f==null?void 0:f(K.id),onToggleFavorite:p})},K.id)})},[e,k,t,r,i,o,a,c,u,d,f,p,R.height,y]),H=F.getVirtualItems(),j=b.useCallback(()=>{w.current=null,D(null),window.setTimeout(()=>{C.current=!1},0)},[]);b.useEffect(()=>{s||(w.current=null,D(null),C.current=!1)},[s]);const z=b.useCallback($=>{const U=w.current,Y=v.current;if(!U||!Y||!s||!l)return;const K=Y.getBoundingClientRect(),Z=Math.min(Math.max($.clientX,K.left),K.right),oe=Math.min(Math.max($.clientY,K.top),K.bottom),J=Z-U.startX,ae=oe-U.startY;if(!U.active&&Math.hypot(J,ae)<6)return;U.active||(U.active=!0,C.current=!0);const Q=Math.min(U.startX,Z)-K.left,se=Math.min(U.startY,oe)-K.top,ie=Math.abs(Z-U.startX),ce=Math.abs(oe-U.startY),ge={left:Q,top:se,width:ie,height:ce};D(ge);const Se=new DOMRect(K.left+ge.left,K.top+ge.top,ge.width,ge.height),Ae=Array.from(Y.querySelectorAll('[data-asset-cell="true"][data-asset-id]')).filter(Le=>vtt(Le.getBoundingClientRect(),Se)).map(Le=>Le.dataset.assetId).filter(Le=>!!Le);l(Ae)},[s,l]),N=b.useCallback(()=>{j(),document.removeEventListener("pointermove",z),document.removeEventListener("pointerup",N)},[z,j]),B=b.useCallback($=>{if(!s||!l||$.button!==0)return;const U=$.target;!(U instanceof HTMLElement)||ytt(U)||(w.current={startX:$.clientX,startY:$.clientY,active:!1},C.current=!1,document.addEventListener("pointermove",z),document.addEventListener("pointerup",N))},[z,N,s,l]),O=b.useCallback($=>{C.current&&($.preventDefault(),$.stopPropagation())},[]);return b.useEffect(()=>()=>{w.current=null,document.removeEventListener("pointermove",z),document.removeEventListener("pointerup",N)},[z,N]),g.jsxs("div",{ref:v,className:`virtual-asset-grid virtual-asset-grid--${t} ${I?"virtual-asset-grid--marquee-active":""}`,onPointerDownCapture:B,onClickCapture:O,style:{height:"100%",overflow:"auto",position:"relative"},children:[g.jsx("div",{style:{height:`${F.getTotalSize()}px`,width:"100%",position:"relative"},children:H.map($=>g.jsx("div",{className:`virtual-asset-grid__row virtual-asset-grid__row--${t}`,style:{position:"absolute",top:0,left:0,width:"100%",height:`${R.height}px`,transform:`translateY(${$.start}px)`,display:t==="list"?"block":"grid",gridTemplateColumns:t==="list"?"none":`repeat(${k}, 1fr)`,gap:`${x.gap}px`,padding:`0 ${x.padding}px`},children:V($.index)},$.key))}),I&&g.jsx("div",{className:"virtual-asset-grid__marquee",style:{left:I.left,top:I.top,width:I.width,height:I.height}})]})}function btt(){return g.jsxs("div",{className:"media-library-empty",children:[g.jsx("div",{className:"media-library-empty__icon-container",children:g.jsx(cI,{size:48,className:"media-library-empty__icon"})}),g.jsx("h3",{className:"media-library-empty__title",children:"暂无素材"}),g.jsx("p",{className:"media-library-empty__description",children:"开始使用AI生成图片或视频,或者上传本地文件"})]})}const xtt=[{mode:"grid",icon:g.jsx(bSe,{size:16}),label:"默认网格"},{mode:"compact",icon:g.jsx(cSe,{size:16}),label:"紧凑网格"},{mode:"list",icon:g.jsx(kSe,{size:16}),label:"列表视图"}],Gle=b.memo(({viewMode:e,onViewModeChange:t})=>{const n=b.useCallback(r=>{r!==e&&t(r)},[e,t]);return g.jsx("div",{className:"view-mode-toggle",children:xtt.map(({mode:r,icon:i,label:o})=>g.jsx(cn,{content:o,children:g.jsx("button",{className:`view-mode-toggle__btn ${e===r?"view-mode-toggle__btn--active":""}`,onClick:()=>n(r),"data-track":`view_mode_${r}`,"aria-label":o,children:i})},r))})});Gle.displayName="ViewModeToggle";const Stt=.1,Ctt=5,LV=e=>Math.max(Stt,Math.min(Ctt,e));function Ett(e){const{items:t,initialMode:n="single",initialIndex:r=0,maxCompareSlots:i=4,defaultCompareLayout:o="horizontal",visible:s,onModeChange:a}=e,l=b.useCallback(()=>{if(Array.isArray(r))return r.slice(0,i);const ie=typeof r=="number"?r:0,ce=(ie+1)%t.length;return t.length>1?[ie,ce]:[ie]},[r,i,t.length]),c=b.useCallback(()=>{const ie=l().length;return ie>=4?4:ie===3?3:2},[l]),[u,d]=b.useState(n),[f,p]=b.useState(typeof r=="number"?r:0),[y,v]=b.useState(l),[w,C]=b.useState(o),[x,E]=b.useState(!1),[_,I]=b.useState(1),[D,P]=b.useState({x:0,y:0}),[k,R]=b.useState(0),[T,M]=b.useState(c);b.useEffect(()=>{if(s){const ie=l();d(n),p(typeof r=="number"?r:0),v(ie),M(ie.length>=4?4:ie.length===3?3:2),I(1),P({x:0,y:0}),R(0)}},[s,n,r,l]);const F=b.useRef(t);b.useEffect(()=>{if(!s||t===F.current){F.current=t;return}const ie=F.current;F.current=t;const ce=ie[f];if(!(ce!=null&&ce.id))return;const ge=t.findIndex(Se=>Se.id===ce.id);ge!==-1&&ge!==f&&p(ge)},[s,t,f]);const V=b.useMemo(()=>({mode:u,currentIndex:f,compareIndices:y,compareLayout:w,syncMode:x,zoomLevel:_,panOffset:D,focusedSlot:k}),[u,f,y,w,x,_,D,k]),H=b.useCallback(ie=>{if(ie!==u){if(ie==="compare"){const ce=(f+1)%t.length;v(t.length>1?[f,ce]:[f])}else{const ce=y[k]??y[0]??0;p(ce)}d(ie),I(1),P({x:0,y:0}),a==null||a(ie)}},[u,f,t.length,y,k,a]),j=b.useCallback(ie=>{ie>=0&&ie<t.length&&(p(ie),I(1),P({x:0,y:0}))},[t.length]),z=b.useCallback(()=>{const ie=f>0?f-1:t.length-1;j(ie)},[f,t.length,j]),N=b.useCallback(()=>{const ie=f<t.length-1?f+1:0;j(ie)},[f,t.length,j]),B=b.useCallback((ie,ce)=>{v(ge=>{const Se=[...ge];return typeof ce=="number"&&ce<T?Se[ce]=ie:Se.length<T?Se.push(ie):Se[k]=ie,Se})},[T,k]),O=b.useCallback(ie=>{v(ce=>{if(ce.length<=2)return ce;const ge=[...ce];return ge.splice(ie,1),ge}),k>=ie&&k>0&&R(k-1)},[k]),$=b.useCallback((ie,ce)=>{v(ge=>{const Se=[...ge],Ae=Se[ie];return Se[ie]=Se[ce],Se[ce]=Ae,Se})},[]),U=b.useCallback(ie=>{C(ie)},[]),Y=b.useCallback(()=>{E(ie=>!ie)},[]),K=b.useCallback(ie=>{I(ce=>{const ge=ce+ie;return LV(ge)})},[]),Z=b.useCallback(ie=>{I(LV(ie))},[]),oe=b.useCallback(()=>{I(1),P({x:0,y:0})},[]),J=b.useCallback(ie=>{P(ie)},[]),ae=b.useCallback(ie=>{R(ie)},[]),Q=b.useCallback(ie=>{M(ie),v(ce=>{if(ce.length>ie)return ce.slice(0,ie);if(ce.length<ie&&t.length>ce.length){const ge=[...ce];let Se=(ce[ce.length-1]+1)%t.length;for(;ge.length<ie&&ge.length<t.length;)ge.includes(Se)||ge.push(Se),Se=(Se+1)%t.length;return ge}return ce})},[t.length]),se=b.useMemo(()=>({setMode:H,goTo:j,goToPrev:z,goToNext:N,addToCompare:B,removeFromCompare:O,swapSlots:$,setCompareLayout:U,toggleSyncMode:Y,zoom:K,setZoomLevel:Z,setPan:J,resetView:oe,setFocusedSlot:ae,setSlotCount:Q}),[H,j,z,N,B,O,$,U,Y,K,Z,J,oe,ae,Q]);return[V,se]}const Pm=400;function _tt(e){return e==="video"?{width:Pm,height:Math.round(Pm*(9/16))}:{width:Pm,height:Pm}}async function Itt(e,t,n,r,i){const o=i||_tt(t);return t==="video"?(await O1(e,n,r,!1,o,!0,!0),o):(await M1(e,n,r,!1,o,!0,!0),o)}async function Att(e,t,n,r){const i=QJe();if(!i)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};try{if(!n){const c=await F5(i,t,e,r);if(c)return{success:!0,data:{insertedCount:1,items:[{type:e,point:c.point,elementId:c.elementId,size:c.size}],firstElementId:c.elementId,firstElementPosition:c.point,firstElementSize:c.size},type:"text"}}const o=n||rp(i,{logPrefix:"MediaQuickInsert"})||K5(i,{emptyPoint:hr.DEFAULT_POINT})||hr.DEFAULT_POINT,s=i.children.length,a=await Itt(i,e,t,o,r),l=i.children[s];return requestAnimationFrame(()=>{Ba(i,[o[0]+Pm/2,o[1]+Pm/2])}),{success:!0,data:{insertedCount:1,items:[{type:e,point:o,elementId:l==null?void 0:l.id,size:a}],firstElementId:l==null?void 0:l.id,firstElementPosition:o,firstElementSize:a},type:"text"}}catch(o){return console.error("[MediaQuickInsert] Failed to insert media:",o),{success:!1,error:`插入失败: ${o.message||"未知错误"}`,type:"error"}}}const Pr=({content:e,children:t,placement:n="bottom",sideOffset:r=8,crossAxisOffset:i=0,contentClassName:o,closeDelay:s=100})=>g.jsx(sFe,{content:e,placement:n,sideOffset:r,crossAxisOffset:i,contentClassName:o||"viewer-popover",closeDelay:s,children:t}),s2={x:0,y:0},Ptt=.1,ktt=5,Q0=.001,BV=.25,Ttt=.0025,FV=.08,Dtt=1,Mtt=2,Ott=16,Rtt=800,Ntt=32,jtt=88,Ltt=140,Btt=e=>Math.max(Ptt,Math.min(ktt,e)),Ftt=e=>e.deltaMode===Dtt?e.deltaY*Ott:e.deltaMode===Mtt?e.deltaY*Rtt:e.deltaY,$tt=e=>Math.max(-FV,Math.min(FV,e)),ztt=(e,t)=>{if(e.offsetWidth>0&&e.offsetHeight>0)return{width:e.offsetWidth,height:e.offsetHeight};const n=e.getBoundingClientRect(),r=Math.max(Math.abs(t),Q0);return{width:n.width/r,height:n.height/r}},Kle="media-viewport-toolbar-state-single",Utt=()=>{try{const e=localStorage.getItem(Kle);if(e)return JSON.parse(e)}catch{}return{orientation:"horizontal",position:null}},Htt=e=>{try{localStorage.setItem(Kle,JSON.stringify(e))}catch{}},nO=b.forwardRef(({item:e,slotIndex:t,isFocused:n=!1,zoomLevel:r=1,panOffset:i,onClick:o,videoAutoPlay:s=!1,videoLoop:a=!0,onZoomChange:l,onPanChange:c,isCompareMode:u=!1,onInsertToCanvas:d,onDownload:f,onEdit:p,onVideoPlayStateChange:y,onVideoTimeUpdate:v,isSyncMode:w=!1},C)=>{var Fn;const x=b.useRef(null),E=b.useRef(null),_=b.useRef(null),[I,D]=b.useState(!1),[P,k]=b.useState(!0),[R,T]=b.useState(!1),[M,F]=b.useState({x:0,y:0}),[V,H]=b.useState(i??s2),[j,z]=b.useState(r),N=b.useRef(r),[B,O]=b.useState(0),[$,U]=b.useState(!1),[Y,K]=b.useState(!1),[Z,oe]=b.useState(!1),[J,ae]=b.useState(!1),[Q,se]=b.useState(!1),ie=b.useRef(null),ce=b.useRef(!1),ge=b.useRef(r),Se=b.useRef(i);b.useImperativeHandle(C,()=>({resetVideo:()=>{E.current&&(E.current.currentTime=0,E.current.play().catch(()=>{}))},playVideo:()=>{E.current&&E.current.play().catch(()=>{})},pauseVideo:()=>{E.current&&E.current.pause()},toggleVideoPlayback:()=>{if(E.current){if(E.current.paused||E.current.ended){E.current.play().catch(()=>{});return}E.current.pause()}},setVideoTime:We=>{E.current&&(E.current.currentTime=We)},getVideoTime:()=>{var We;return((We=E.current)==null?void 0:We.currentTime)??0},isVideo:()=>(e==null?void 0:e.type)==="video"}),[e]);const[Ae]=b.useState(()=>u?{orientation:"horizontal",position:null}:Utt()),[Le,it]=b.useState(Ae.orientation),[Te,Re]=b.useState(Ae.position),[ht,Ze]=b.useState(!1),Ge=b.useRef({x:0,y:0,posX:0,posY:0}),pt=(e==null?void 0:e.type)==="video",at=(e==null?void 0:e.type)==="audio",ct=((Fn=e==null?void 0:e.prompt)==null?void 0:Fn.trim())||"",nt=!!ct&&(Z||J)&&!Q,It=e?pt||at?e.url:zn(e.url):"",Lt=e!=null&&e.posterUrl?zn(e.posterUrl):"",dt=e?`${e.type}:${e.id||e.url}`:"empty",wt=!!(e!=null&&e.url&&!at&&!u&&!I),mt=b.useCallback(()=>{ie.current!==null&&(window.clearTimeout(ie.current),ie.current=null)},[]),Bt=b.useCallback(()=>{mt(),oe(!0)},[mt]),He=b.useCallback(()=>{oe(!1),mt(),ie.current=window.setTimeout(()=>{ae(!1),ie.current=null},120)},[mt]),we=b.useCallback(()=>{mt(),ae(!0)},[mt]),ue=b.useCallback(()=>{ae(!1)},[]);b.useLayoutEffect(()=>{D(!1),k(!(e!=null&&e.url)||at||u),T(!1);const We=Se.current??s2,rn=ge.current;H(We),N.current=rn,z(rn),O(0),U(!1),K(!1),ce.current=!1},[dt,e==null?void 0:e.url,at,u]),b.useEffect(()=>()=>{mt()},[mt]),b.useEffect(()=>{u||Htt({orientation:Le,position:Te})},[Le,Te,u]),b.useLayoutEffect(()=>{const We=i??s2;Se.current=i,H(rn=>rn.x===We.x&&rn.y===We.y?rn:We)},[i]),b.useLayoutEffect(()=>{ge.current=r,N.current=r,z(We=>We===r?We:r)},[r]);const _e=b.useCallback((We,rn="manual")=>{const Rn=Btt(We);rn==="manual"&&(ce.current=!0),!(Math.abs(N.current-Rn)<=Q0)&&(N.current=Rn,z(tr=>Math.abs(tr-Rn)<=Q0?tr:Rn),l==null||l(Rn))},[l]),xe=b.useCallback(We=>{const rn=Se.current??s2;Math.abs(rn.x-We.x)<=Q0&&Math.abs(rn.y-We.y)<=Q0||(Se.current=We,H(We),c==null||c(We))},[c]),Fe=b.useCallback(()=>{if(u||at||!x.current)return;if(ce.current){k(!0);return}const We=pt?E.current:_.current;if(!We||!x.current)return;const rn=x.current.getBoundingClientRect();if(rn.width<=0||rn.height<=0)return;const Rn=pt?We.videoWidth:We.naturalWidth,tr=pt?We.videoHeight:We.naturalHeight;if(Rn<=0||tr<=0)return;const dr=ztt(We,N.current);if(dr.width<=0||dr.height<=0)return;const Yn=pt?Ltt:jtt,pr=Math.max(rn.width-Ntt,0),gr=Math.max(rn.height-Yn,0);if(pr<=0||gr<=0)return;const Ar=Math.min(pr/dr.width,gr/dr.height);!Number.isFinite(Ar)||Ar<=0||(xe({x:0,y:-Yn/2}),_e(Ar,"auto"),k(!0))},[u,at,pt,xe,_e]);b.useLayoutEffect(()=>{if(!(e!=null&&e.url)||at||u)return;const We=pt?E.current:_.current;if(!We)return;if(pt){We.readyState>=1&&Fe();return}const rn=We;rn.complete&&rn.naturalWidth>0&&Fe()},[e,at,u,pt,Fe]),b.useEffect(()=>{if(!(e!=null&&e.url)||at||u||typeof ResizeObserver>"u"||!x.current)return;const We=new ResizeObserver(()=>{Fe()});return We.observe(x.current),()=>{We.disconnect()}},[e==null?void 0:e.url,at,u,Fe]);const lt=b.useCallback(We=>{We.button===0&&(We.preventDefault(),T(!0),F({x:We.clientX-V.x,y:We.clientY-V.y}))},[V]),Ht=b.useCallback(We=>{if(!R)return;ce.current=!0;const rn={x:We.clientX-M.x,y:We.clientY-M.y};Se.current=rn,H(rn),c==null||c(rn)},[R,M,c]),At=b.useCallback(()=>{T(!1)},[]),le=b.useCallback(We=>{We.preventDefault();const rn=Ftt(We);if(!Number.isFinite(rn)||rn===0)return;const Rn=$tt(-rn*Ttt);_e(N.current+Rn)},[_e]),me=b.useCallback(()=>{_e(N.current+BV)},[_e]),ke=b.useCallback(()=>{_e(N.current-BV)},[_e]),Oe=b.useCallback(()=>{O(We=>We-90)},[]),De=b.useCallback(()=>{O(We=>We+90)},[]),Ye=b.useCallback(()=>{U(We=>!We)},[]),Rt=b.useCallback(()=>{K(We=>!We)},[]),St=b.useCallback(async()=>{if(e)try{const We=e.type==="video"?"video":"image";if(e.type==="audio"){tn.warning("音频暂不支持直接插入到画布");return}const rn=await Att(We,It);rn.success?tn.success(e.type==="video"?"视频已插入到画布":"图片已插入到画布"):tn.error(rn.error||"插入失败")}catch(We){console.error("Failed to insert to canvas:",We),tn.error("插入失败")}},[e,It]),Ct=b.useCallback(()=>{it(We=>We==="horizontal"?"vertical":"horizontal")},[]),Dt=b.useCallback(We=>{We.preventDefault(),We.stopPropagation(),Ze(!0);const rn=Te||{x:0,y:0};Ge.current={x:We.clientX,y:We.clientY,posX:rn.x,posY:rn.y};const Rn=dr=>{const Yn=dr.clientX-Ge.current.x,pr=dr.clientY-Ge.current.y;Re({x:Ge.current.posX+Yn,y:Ge.current.posY+pr})},tr=()=>{Ze(!1),document.removeEventListener("mousemove",Rn),document.removeEventListener("mouseup",tr)};document.addEventListener("mousemove",Rn),document.addEventListener("mouseup",tr)},[Te]),Gt=b.useCallback(We=>{if(We.stopPropagation(),We.touches.length!==1)return;const rn=We.touches[0];Ze(!0);const Rn=Te||{x:0,y:0};Ge.current={x:rn.clientX,y:rn.clientY,posX:Rn.x,posY:Rn.y};const tr=Yn=>{if(Yn.touches.length!==1)return;Yn.preventDefault();const pr=Yn.touches[0],gr=pr.clientX-Ge.current.x,Ar=pr.clientY-Ge.current.y;Re({x:Ge.current.posX+gr,y:Ge.current.posY+Ar})},dr=()=>{Ze(!1),document.removeEventListener("touchmove",tr),document.removeEventListener("touchend",dr),document.removeEventListener("touchcancel",dr)};document.addEventListener("touchmove",tr,{passive:!1}),document.addEventListener("touchend",dr),document.addEventListener("touchcancel",dr)},[Te]),Ft=b.useCallback(()=>{Re(null)},[]);if(!e)return g.jsx("div",{className:`media-viewport media-viewport--empty ${n?"media-viewport--focused":""}`,onClick:o,children:g.jsx("div",{className:"media-viewport__placeholder",children:g.jsx("span",{children:"点击底部缩略图添加媒体"})})});const Ne=$?-j:j,gt=Y?-j:j,nn={transform:`translate(${V.x}px, ${V.y}px) scale(${Ne}, ${gt}) rotate(${B}deg)`},Zt=wt&&!P;return g.jsxs("div",{ref:x,className:`media-viewport ${n?"media-viewport--focused":""} ${at?"media-viewport--audio":""} ${pt?"media-viewport--video":""} ${u?"":"media-viewport--single"}`,onClick:o,onMouseDown:at?void 0:lt,onMouseMove:at?void 0:Ht,onMouseUp:at?void 0:At,onWheel:at?void 0:le,onMouseLeave:()=>{at||At(),oe(!1),ae(!1),se(!1),mt()},"data-slot":t,children:[g.jsx("div",{className:`media-viewport__content ${Zt?"media-viewport__content--auto-fitting":""}`,style:at?void 0:nn,children:pt?g.jsx("div",{className:"media-viewport__media-hitbox",onMouseEnter:Bt,onMouseLeave:He,children:g.jsx("video",{ref:E,src:It,autoPlay:s,loop:a,controls:!0,className:"media-viewport__video",referrerPolicy:"no-referrer",onClick:We=>We.stopPropagation(),onPlay:()=>{w&&y&&y(!0)},onPause:()=>{w&&y&&y(!1)},onSeeked:()=>{w&&v&&E.current&&v(E.current.currentTime)},onLoadedMetadata:Fe})}):at?g.jsx("div",{className:"media-viewport__audio-shell",onClick:We=>We.stopPropagation(),children:g.jsxs("div",{className:"media-viewport__audio-card",children:[g.jsx(wle,{src:Lt,alt:e.alt||e.title||"",imageClassName:"media-viewport__audio-poster",fallbackClassName:"media-viewport__audio-poster media-viewport__audio-poster--fallback",iconSize:56}),g.jsxs("div",{className:"media-viewport__audio-meta",children:[e.title&&g.jsx("div",{className:"media-viewport__audio-title",children:e.title}),typeof e.duration=="number"&&Number.isFinite(e.duration)&&e.duration>0&&g.jsxs("div",{className:"media-viewport__audio-duration",children:[Math.floor(e.duration/60),":",String(Math.round(e.duration%60)).padStart(2,"0")]})]}),g.jsx("audio",{src:It,controls:!0,preload:"metadata",className:"media-viewport__audio",referrerPolicy:"no-referrer"})]})}):I?g.jsx("div",{className:"media-viewport__media-hitbox",onMouseEnter:Bt,onMouseLeave:He,children:g.jsx("div",{className:"media-viewport__image-fallback",children:g.jsx("span",{children:"图片加载失败"})})}):g.jsx("div",{className:"media-viewport__media-hitbox",onMouseEnter:Bt,onMouseLeave:He,children:g.jsx(xs,{ref:_,src:It,alt:e.alt||e.title||"",className:"media-viewport__image",draggable:!1,showSkeleton:!1,eager:!0,onLoad:Fe,onError:()=>{D(!0),k(!0)}})})}),g.jsxs("div",{className:`media-viewport__toolbar media-viewport__toolbar--${Le} ${ht?"media-viewport__toolbar--dragging":""} ${u?"media-viewport__toolbar--compact":""}`,style:!u&&Te?{transform:`translate(calc(-50% + ${Te.x}px), ${Te.y}px)`}:void 0,onMouseEnter:()=>se(!0),onMouseLeave:()=>se(!1),onMouseDown:We=>We.stopPropagation(),onClick:We=>We.stopPropagation(),children:[!at&&g.jsxs(g.Fragment,{children:[!u&&g.jsxs(g.Fragment,{children:[g.jsx(Pr,{content:"拖拽移动工具栏,双击重置位置",placement:"top",contentClassName:"viewer-popover",children:g.jsx("div",{className:"media-viewport__toolbar-handle",onMouseDown:Dt,onTouchStart:Gt,onDoubleClick:We=>{We.stopPropagation(),Ft()},children:g.jsx(dSe,{size:14})})}),g.jsx(Pr,{content:Le==="horizontal"?"切换为垂直布局":"切换为水平布局",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button",className:"media-viewport__toolbar-orientation-btn",onClick:We=>{We.stopPropagation(),We.preventDefault(),Ct()},children:g.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:Le==="horizontal"?g.jsxs(g.Fragment,{children:[g.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),g.jsx("polyline",{points:"8 7 12 3 16 7"}),g.jsx("polyline",{points:"8 17 12 21 16 17"})]}):g.jsxs(g.Fragment,{children:[g.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),g.jsx("polyline",{points:"7 8 3 12 7 16"}),g.jsx("polyline",{points:"17 8 21 12 17 16"})]})})})}),g.jsx("div",{className:"media-viewport__toolbar-divider"})]}),g.jsxs("div",{className:"media-viewport__toolbar-group",children:[g.jsx(Pr,{content:"缩小",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button","aria-label":"缩小",onClick:We=>{We.stopPropagation(),We.preventDefault(),ke()},children:g.jsx(IY,{size:16})})}),g.jsxs("span",{className:"media-viewport__zoom-level",children:[Math.round(j*100),"%"]}),g.jsx(Pr,{content:"放大",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button","aria-label":"放大",onClick:We=>{We.stopPropagation(),We.preventDefault(),me()},children:g.jsx(_Y,{size:16})})})]}),g.jsx("div",{className:"media-viewport__toolbar-divider"}),g.jsxs("div",{className:"media-viewport__toolbar-group",children:[g.jsx(Pr,{content:"向左旋转 90°",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button","aria-label":"向左旋转 90°",onClick:We=>{We.stopPropagation(),We.preventDefault(),Oe()},children:g.jsx(Uv,{size:16})})}),g.jsx(Pr,{content:"向右旋转 90°",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button","aria-label":"向右旋转 90°",onClick:We=>{We.stopPropagation(),We.preventDefault(),De()},children:g.jsx(CY,{size:16})})})]}),g.jsx("div",{className:"media-viewport__toolbar-divider"}),g.jsxs("div",{className:"media-viewport__toolbar-group",children:[g.jsx(Pr,{content:"水平翻转",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button","aria-label":"水平翻转",className:$?"active":"",onClick:We=>{We.stopPropagation(),We.preventDefault(),Ye()},children:g.jsx(wY,{size:16})})}),g.jsx(Pr,{content:"垂直翻转",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button","aria-label":"垂直翻转",className:Y?"active":"",onClick:We=>{We.stopPropagation(),We.preventDefault(),Rt()},children:g.jsx(bY,{size:16})})})]})]}),!u&&!at&&g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"media-viewport__toolbar-divider"}),g.jsx(Pr,{content:"插入到画布",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button",onClick:We=>{We.stopPropagation(),We.preventDefault(),d?d():St()},children:g.jsx(ic,{size:16})})})]}),!u&&f&&g.jsxs(g.Fragment,{children:[at&&g.jsx("div",{className:"media-viewport__toolbar-divider"}),g.jsx(Pr,{content:"下载",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button",onClick:We=>{We.stopPropagation(),We.preventDefault(),f()},children:g.jsx($v,{size:16})})})]}),!u&&p&&(e==null?void 0:e.type)==="image"&&g.jsx(Pr,{content:"编辑图片",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button",onClick:We=>{We.stopPropagation(),We.preventDefault(),p()},children:g.jsx(oR,{size:16})})})]}),ct&&!at&&g.jsx(Pr,{content:ct,placement:"bottom",sideOffset:10,contentClassName:"viewer-popover viewer-popover--prompt",children:g.jsx("div",{className:`media-viewport__prompt ${nt?"media-viewport__prompt--visible":""} ${J?"media-viewport__prompt--expanded":""}`,onMouseEnter:we,onMouseLeave:ue,children:ct})})]})});nO.displayName="MediaViewport";const Wtt=({src:e,fallbackSrc:t,alt:n})=>{const[r,i]=b.useState(e),[o,s]=b.useState(!1);return b.useEffect(()=>{i(e),s(!1)},[e]),o?g.jsx("div",{className:"thumbnail-queue__image thumbnail-queue__image-fallback",children:g.jsx("span",{children:"加载失败"})}):g.jsx(xs,{src:r,alt:n,className:"thumbnail-queue__image",showSkeleton:!1,onError:()=>{if(t&&r!==t){i(t);return}s(!0)}})};function Vtt(e,t="small"){const n=zn(e);if(n.startsWith("http://")||n.startsWith("https://")||n.startsWith("blob:")||F1(n))return n;try{const r=new URL(n,window.location.origin);return r.searchParams.set("thumbnail",t),r.toString()}catch{const r=n.includes("?")?"&":"?";return`${n}${r}thumbnail=${t}`}}const Gtt=({items:e,mode:t,currentIndex:n,compareIndices:r,onThumbnailClick:i,onDragStart:o})=>{const s=b.useRef(null),[a,l]=b.useState(null);b.useEffect(()=>{if(t==="single"&&s.current){const y=s.current.querySelector(".thumbnail-queue__item--active");y&&y.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})}},[n,t]);const c=b.useCallback((y,v)=>{v.dataTransfer.setData("text/plain",String(y)),v.dataTransfer.effectAllowed="move",l(y),o==null||o(y)},[o]),u=b.useCallback(()=>{l(null)},[]),d=b.useCallback(y=>t==="single"?y===n:r.includes(y),[t,n,r]),f=b.useCallback(y=>{if(t!=="compare")return;const v=r.indexOf(y);return v>=0?v+1:void 0},[t,r]),p=b.useCallback((y,v)=>{const w=d(v),C=f(v),x=a===v,E=y.type==="video",_=y.type==="audio",I=zn(y.url),D=y.posterUrl?zn(y.posterUrl):"",P=Vtt(_&&D?D:I,"small");return g.jsxs("div",{className:`thumbnail-queue__item ${w?"thumbnail-queue__item--active":""} ${x?"thumbnail-queue__item--dragging":""}`,onClick:()=>i(v),draggable:t==="compare",onDragStart:k=>c(v,k),onDragEnd:u,role:"button",tabIndex:0,onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),i(v))},children:[g.jsx("div",{className:"thumbnail-queue__thumb",children:E?g.jsxs(g.Fragment,{children:[g.jsx(cN,{src:I,poster:D||void 0,className:"thumbnail-queue__video",alt:y.alt||y.title||"",thumbnailSize:"small",videoProps:{muted:!0,preload:"metadata"}}),g.jsx("div",{className:"thumbnail-queue__video-icon",children:g.jsx(SY,{size:16})})]}):_?g.jsxs(g.Fragment,{children:[g.jsx(wle,{src:D?P:void 0,fallbackSrc:D,alt:y.alt||y.title||"",imageClassName:"thumbnail-queue__image",fallbackClassName:"thumbnail-queue__image thumbnail-queue__audio-fallback",iconSize:18,loading:"lazy"}),g.jsx("div",{className:"thumbnail-queue__video-icon",children:g.jsx(iR,{size:16})})]}):g.jsx(Wtt,{src:P,alt:y.alt||y.title||"",fallbackSrc:I})}),w&&g.jsx("div",{className:"thumbnail-queue__check",children:C?g.jsx("span",{className:"thumbnail-queue__slot-number",children:C}):g.jsx(S2,{size:18})})]},y.id||`${y.url}-${v}`)},[d,f,a,t,i,c,u]);return e.length===0?null:g.jsx("div",{className:"thumbnail-queue",ref:s,children:g.jsx("div",{className:"thumbnail-queue__list",children:e.map((y,v)=>p(y,v))})})},Ktt=({mode:e,currentIndex:t,totalCount:n,slotCount:r,compareLayout:i,syncMode:o,onModeChange:s,onSlotCountChange:a,onLayoutChange:l,onSyncToggle:c,onResetView:u,onClose:d,onFullscreen:f,isImage:p=!1,showEditButton:y=!1,onBackToPreview:v,onResetEdit:w,onSaveEdit:C})=>{const x=b.useCallback(k=>{l(k),k==="grid"&&r<4&&a(4)},[l,a,r]),E=()=>g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"viewer-toolbar__indicator",children:[g.jsx("span",{className:"viewer-toolbar__current",children:t+1}),g.jsx("span",{className:"viewer-toolbar__separator",children:"/"}),g.jsx("span",{className:"viewer-toolbar__total",children:n})]}),n>1&&g.jsx(Pr,{content:"对比模式",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn",onClick:()=>s("compare"),"aria-label":"对比模式",children:g.jsx(D8,{size:18})})}),y&&p&&g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"viewer-toolbar__divider"}),g.jsx(Pr,{content:"编辑图片",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn",onClick:()=>s("edit"),"aria-label":"编辑图片",children:g.jsx(oR,{size:18})})})]})]}),_=()=>g.jsxs(g.Fragment,{children:[g.jsx(Pr,{content:"返回预览",placement:"bottom",contentClassName:"viewer-popover",children:g.jsxs("button",{className:"viewer-toolbar__btn",onClick:v,"aria-label":"返回预览",children:[g.jsx(x2,{size:18}),g.jsx("span",{className:"viewer-toolbar__btn-text",children:"返回"})]})}),g.jsx("div",{className:"viewer-toolbar__divider"}),g.jsx("div",{className:"viewer-toolbar__title",children:"编辑图片"})]}),I=()=>g.jsxs(g.Fragment,{children:[g.jsx(Pr,{content:"单图模式",placement:"bottom",contentClassName:"viewer-popover",children:g.jsxs("button",{className:"viewer-toolbar__btn",onClick:()=>s("single"),"aria-label":"单图模式",children:[g.jsx(x2,{size:18}),g.jsx("span",{className:"viewer-toolbar__btn-text",children:"单图"})]})}),g.jsx("div",{className:"viewer-toolbar__divider"}),g.jsxs("div",{className:"viewer-toolbar__group",children:[g.jsx("span",{className:"viewer-toolbar__label",children:"分屏"}),[2,3,4].map(k=>g.jsx(X.Fragment,{children:g.jsx(Pr,{content:`${k}分屏`,placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:`viewer-toolbar__btn viewer-toolbar__btn--small ${r===k?"viewer-toolbar__btn--active":""}`,onClick:()=>a(k),"aria-label":`${k}分屏`,children:k})})},k))]}),g.jsx("div",{className:"viewer-toolbar__divider"}),g.jsxs("div",{className:"viewer-toolbar__group",children:[g.jsx(Pr,{content:"水平布局",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:`viewer-toolbar__btn ${i==="horizontal"?"viewer-toolbar__btn--active":""}`,onClick:()=>x("horizontal"),"aria-label":"水平布局",children:g.jsx(D8,{size:18})})}),g.jsx(Pr,{content:"垂直布局",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:`viewer-toolbar__btn ${i==="vertical"?"viewer-toolbar__btn--active":""}`,onClick:()=>x("vertical"),"aria-label":"垂直布局",children:g.jsx(hCe,{size:18})})}),g.jsx(Pr,{content:"网格布局",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:`viewer-toolbar__btn ${i==="grid"?"viewer-toolbar__btn--active":""}`,onClick:()=>x("grid"),"aria-label":"网格布局",children:g.jsx(aSe,{size:18})})})]}),g.jsx("div",{className:"viewer-toolbar__divider"}),g.jsx(Pr,{content:o?"取消联动(快捷键 S)":"联动缩放/拖拽(快捷键 S)",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:`viewer-toolbar__btn ${o?"viewer-toolbar__btn--active":""}`,onClick:c,"aria-label":o?"取消联动":"联动缩放/拖拽",children:o?g.jsx(_Se,{size:18}):g.jsx(zCe,{size:18})})}),o&&g.jsx(Pr,{content:"重置视图",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn",onClick:u,children:g.jsx(Uv,{size:18})})})]}),D=()=>{switch(e){case"edit":return _();case"compare":return I();default:return E()}},P=()=>e==="edit"?g.jsxs(g.Fragment,{children:[g.jsx(Pr,{content:"重置",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn",onClick:w,children:g.jsx(Uv,{size:18})})}),g.jsx(Pr,{content:"保存",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn viewer-toolbar__btn--primary",onClick:C,"aria-label":"保存",children:g.jsx(Nd,{size:18})})}),g.jsx(Pr,{content:"关闭(Esc)",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn viewer-toolbar__btn--close",onClick:d,"aria-label":"关闭",children:g.jsx(md,{size:20})})})]}):g.jsxs(g.Fragment,{children:[f&&g.jsx(Pr,{content:"全屏",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn",onClick:f,children:g.jsx(xY,{size:18})})}),g.jsx(Pr,{content:"关闭(Esc)",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn viewer-toolbar__btn--close",onClick:d,"aria-label":"关闭",children:g.jsx(md,{size:20})})})]});return e==="edit"?g.jsxs("div",{className:"viewer-toolbar viewer-toolbar--edit-simplified",children:[g.jsx(Pr,{content:"返回预览",placement:"bottom",contentClassName:"viewer-popover",children:g.jsxs("button",{className:"viewer-toolbar__corner-btn viewer-toolbar__corner-btn--left",onClick:v,"aria-label":"返回预览",children:[g.jsx(x2,{size:20}),g.jsx("span",{children:"返回"})]})}),g.jsx(Pr,{content:"关闭(Esc)",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__corner-btn viewer-toolbar__corner-btn--right",onClick:d,"aria-label":"关闭",children:g.jsx(md,{size:20})})})]}):g.jsxs("div",{className:"viewer-toolbar",children:[g.jsx("div",{className:"viewer-toolbar__left",children:D()}),g.jsx("div",{className:"viewer-toolbar__right",children:P()})]})},Zu={brightness:100,contrast:100,saturate:100,blur:0,grayscale:0,sepia:0,hueRotate:0,invert:0},qle=[{label:"自由",value:null},{label:"1:1",value:1},{label:"4:3",value:4/3},{label:"3:4",value:3/4},{label:"16:9",value:16/9},{label:"9:16",value:9/16},{label:"3:2",value:3/2},{label:"2:3",value:2/3}],rO=[{label:"原图",type:"none",filter:"none"},{label:"黑白",type:"grayscale",filter:"grayscale(100%)"},{label:"怀旧",type:"sepia",filter:"sepia(80%)"},{label:"复古",type:"vintage",filter:"sepia(40%) contrast(110%) brightness(90%)"},{label:"冷色",type:"cold",filter:"saturate(80%) hue-rotate(180deg) brightness(105%)"},{label:"暖色",type:"warm",filter:"saturate(120%) sepia(20%) brightness(105%)"},{label:"高对比",type:"contrast",filter:"contrast(150%)"},{label:"高饱和",type:"saturate",filter:"saturate(180%)"},{label:"反转",type:"invert",filter:"invert(100%)"}],Yle=({aspectRatio:e,presets:t,onAspectRatioChange:n,rotation:r,flipH:i,flipV:o,onRotate:s,onFlipH:a,onFlipV:l,onConfirmCrop:c,hasCropArea:u=!1,onAutoTrimWhitespace:d,isDetectingWhitespace:f=!1})=>g.jsxs("div",{className:"crop-panel",children:[d&&g.jsxs("div",{className:"crop-panel__section",children:[g.jsx("div",{className:"crop-panel__section-title",children:"智能裁剪"}),g.jsxs("button",{type:"button",className:`crop-panel__auto-trim-btn ${f?"loading":""}`,onClick:d,disabled:f,children:[g.jsx(yCe,{size:16}),g.jsx("span",{children:f?"检测中...":"智能去白边"})]}),g.jsx("div",{className:"crop-panel__auto-trim-hint",children:"自动检测并移除图片周围的白色边框"})]}),g.jsxs("div",{className:"crop-panel__section",children:[g.jsx("div",{className:"crop-panel__section-title",children:"裁剪比例"}),g.jsx("div",{className:"crop-panel__ratio-grid",children:t.map(p=>g.jsx("button",{type:"button",className:`crop-panel__ratio-btn ${e===p.value?"active":""}`,onClick:()=>n(p.value),children:p.label},p.label))})]}),g.jsxs("div",{className:"crop-panel__section",children:[g.jsx("div",{className:"crop-panel__section-title",children:"旋转和翻转"}),g.jsxs("div",{className:"crop-panel__transform-row",children:[g.jsx(cn,{content:"向左旋转 90°",placement:"top",children:g.jsx("button",{type:"button",className:"crop-panel__transform-btn",onClick:()=>s(-90),children:g.jsx(Uv,{size:18})})}),g.jsx(cn,{content:"向右旋转 90°",placement:"top",children:g.jsx("button",{type:"button",className:"crop-panel__transform-btn",onClick:()=>s(90),children:g.jsx(CY,{size:18})})}),g.jsx(cn,{content:"水平翻转",placement:"top",children:g.jsx("button",{type:"button",className:`crop-panel__transform-btn ${i?"active":""}`,onClick:a,children:g.jsx(wY,{size:18})})}),g.jsx(cn,{content:"垂直翻转",placement:"top",children:g.jsx("button",{type:"button",className:`crop-panel__transform-btn ${o?"active":""}`,onClick:l,children:g.jsx(bY,{size:18})})})]}),r!==0&&g.jsxs("div",{className:"crop-panel__rotation-info",children:["当前旋转: ",r,"°"]})]}),c&&g.jsxs("div",{className:"crop-panel__section",children:[g.jsxs("button",{type:"button",className:`crop-panel__confirm-btn ${u?"":"disabled"}`,onClick:c,disabled:!u,children:[g.jsx(Nd,{size:16}),g.jsx("span",{children:"应用裁剪"})]}),g.jsx("div",{className:"crop-panel__confirm-hint",children:"按 Enter 键快速确认"})]}),g.jsxs("div",{className:"crop-panel__tips",children:[g.jsx("p",{children:"拖动裁剪框调整位置"}),g.jsx("p",{children:"拖动边角调整大小"})]})]}),Xle=({filterType:e,filterParams:t,presets:n,imageUrl:r,onPresetSelect:i,onParamChange:o})=>g.jsxs("div",{className:"filter-panel",children:[g.jsxs("div",{className:"filter-panel__section",children:[g.jsx("div",{className:"filter-panel__section-title",children:"滤镜预设"}),g.jsx("div",{className:"filter-panel__preset-grid",children:n.map(s=>g.jsxs("button",{type:"button",className:`filter-panel__preset-btn ${e===s.type?"active":""}`,onClick:()=>i(s.type),children:[g.jsx("div",{className:"filter-panel__preset-preview",style:{backgroundImage:`url(${r})`,filter:s.filter}}),g.jsx("span",{className:"filter-panel__preset-label",children:s.label})]},s.type))})]}),g.jsxs("div",{className:"filter-panel__section",children:[g.jsx("div",{className:"filter-panel__section-title",children:"参数调节"}),g.jsxs("div",{className:"filter-panel__sliders",children:[g.jsx(yf,{label:"亮度",value:t.brightness,min:0,max:200,defaultValue:100,onChange:s=>o("brightness",s)}),g.jsx(yf,{label:"对比度",value:t.contrast,min:0,max:200,defaultValue:100,onChange:s=>o("contrast",s)}),g.jsx(yf,{label:"饱和度",value:t.saturate,min:0,max:200,defaultValue:100,onChange:s=>o("saturate",s)}),g.jsx(yf,{label:"灰度",value:t.grayscale,min:0,max:100,defaultValue:0,onChange:s=>o("grayscale",s)}),g.jsx(yf,{label:"复古",value:t.sepia,min:0,max:100,defaultValue:0,onChange:s=>o("sepia",s)}),g.jsx(yf,{label:"色相",value:t.hueRotate,min:0,max:360,defaultValue:0,onChange:s=>o("hueRotate",s)}),g.jsx(yf,{label:"模糊",value:t.blur,min:0,max:10,defaultValue:0,step:.5,onChange:s=>o("blur",s)})]})]})]}),yf=({label:e,value:t,min:n,max:r,defaultValue:i,step:o=1,onChange:s})=>{const a=t===i;return g.jsxs("div",{className:"filter-slider",children:[g.jsxs("div",{className:"filter-slider__header",children:[g.jsx("span",{className:"filter-slider__label",children:e}),g.jsx("span",{className:`filter-slider__value ${a?"":"modified"}`,children:t})]}),g.jsx(b6e,{value:t,min:n,max:r,step:o,onChange:l=>s(l)})]})},zc=10010;function qtt(e,t={}){const{threshold:n=250,tolerance:r=.02,minContentSize:i=50}=t,o=e.naturalWidth,s=e.naturalHeight,a=document.createElement("canvas");a.width=o,a.height=s;const l=a.getContext("2d");if(!l)return null;l.drawImage(e,0,0);const u=l.getImageData(0,0,o,s).data,d=D=>{const P=u[D],k=u[D+1],R=u[D+2];return u[D+3]<10?!0:P>=n&&k>=n&&R>=n},f=D=>{let P=0;for(let k=0;k<o;k++){const R=(D*o+k)*4;d(R)&&P++}return P/o>=1-r},p=D=>{let P=0;for(let k=0;k<s;k++){const R=(k*o+D)*4;d(R)&&P++}return P/s>=1-r};let y=0;for(;y<s&&f(y);)y++;let v=s-1;for(;v>y&&f(v);)v--;let w=0;for(;w<o&&p(w);)w++;let C=o-1;for(;C>w&&p(C);)C--;const x=C-w+1,E=v-y+1,_=y>0||w>0||C<o-1||v<s-1,I=x>=i&&E>=i;return!_||!I?null:{x:w,y,width:x,height:E}}const dI=b.forwardRef(({imageUrl:e,showOverwrite:t=!1,onOverwrite:n,onInsert:r,onClose:i,onSave:o,className:s},a)=>{const[l,c]=b.useState("crop"),[u,d]=b.useState(null),[f,p]=b.useState(null),[y,v]=b.useState("none"),[w,C]=b.useState(Zu),[x,E]=b.useState(0),[_,I]=b.useState(!1),[D,P]=b.useState(!1),[k,R]=b.useState({width:0,height:0}),[T,M]=b.useState(1),[F,V]=b.useState(1),H=.1,j=5,z=.1,[N,B]=b.useState({x:0,y:0}),[O,$]=b.useState(!1),[U,Y]=b.useState({x:0,y:0}),[K,Z]=b.useState(!1),[oe,J]=b.useState(null),[ae,Q]=b.useState(!1),[se,ie]=b.useState(null),[ce,ge]=b.useState(!1),[Se,Ae]=b.useState([]),[Le,it]=b.useState(-1),Te=b.useRef(!1),Re=b.useRef(null),ht=b.useRef(null),Ze=b.useRef(null);b.useEffect(()=>{Ze.current!==null&&Ze.current!==e&&(d(null),ie(null),p(null),v("none"),C(Zu),E(0),I(!1),P(!1),V(1),M(1),R({width:0,height:0}),B({x:0,y:0}),c("crop"),Ae([{cropArea:null,confirmedCropArea:null,aspectRatio:null,filterType:"none",filterParams:Zu,rotation:0,flipH:!1,flipV:!1}]),it(0)),Ze.current=e},[e]),b.useEffect(()=>{if(!e)return;const Ne=new Image;return Ne.crossOrigin="anonymous",Ne.onload=()=>{Re.current=Ne,R({width:Ne.naturalWidth,height:Ne.naturalHeight})},Ne.onerror=()=>{tn.error("图片加载失败")},Ne.src=e,()=>{Re.current=null}},[e]),b.useEffect(()=>{e&&Se.length===0&&(Ae([{cropArea:null,confirmedCropArea:null,aspectRatio:null,filterType:"none",filterParams:Zu,rotation:0,flipH:!1,flipV:!1}]),it(0))},[e,Se.length]),b.useEffect(()=>{if(!ht.current||k.width===0)return;const Ne=()=>{const nn=ht.current;if(!nn)return;const Zt=nn.clientWidth-80,Fn=nn.clientHeight-80;if(Zt<=0||Fn<=0)return;const We=Zt/k.width,rn=Fn/k.height,Rn=Math.min(We,rn,1);Rn>0&&isFinite(Rn)&&M(Rn)};requestAnimationFrame(Ne);const gt=new ResizeObserver(Ne);return gt.observe(ht.current),()=>gt.disconnect()},[k]);const Ge=b.useRef(null);b.useEffect(()=>{if(!(Te.current||Se.length===0))return Ge.current&&clearTimeout(Ge.current),Ge.current=setTimeout(()=>{It()},300),()=>{Ge.current&&clearTimeout(Ge.current)}},[x,_,D,y,w,f,se]);const pt=b.useCallback(()=>{if(y!=="none"){const gt=rO.find(nn=>nn.type===y);if(gt)return gt.filter}const Ne=[];return w.brightness!==100&&Ne.push(`brightness(${w.brightness}%)`),w.contrast!==100&&Ne.push(`contrast(${w.contrast}%)`),w.saturate!==100&&Ne.push(`saturate(${w.saturate}%)`),w.blur>0&&Ne.push(`blur(${w.blur}px)`),w.grayscale>0&&Ne.push(`grayscale(${w.grayscale}%)`),w.sepia>0&&Ne.push(`sepia(${w.sepia}%)`),w.hueRotate!==0&&Ne.push(`hue-rotate(${w.hueRotate}deg)`),w.invert>0&&Ne.push(`invert(${w.invert}%)`),Ne.length>0?Ne.join(" "):"none"},[y,w]),at=b.useCallback(()=>{const Ne=[];return x!==0&&Ne.push(`rotate(${x}deg)`),_&&Ne.push("scaleX(-1)"),D&&Ne.push("scaleY(-1)"),Ne.length>0?Ne.join(" "):"none"},[x,_,D]),ct=b.useCallback(()=>({cropArea:u,confirmedCropArea:se,aspectRatio:f,filterType:y,filterParams:w,rotation:x,flipH:_,flipV:D}),[u,se,f,y,w,x,_,D]),nt=b.useCallback(Ne=>{Te.current=!0,d(Ne.cropArea),ie(Ne.confirmedCropArea),p(Ne.aspectRatio),v(Ne.filterType),C(Ne.filterParams),E(Ne.rotation),I(Ne.flipH),P(Ne.flipV),requestAnimationFrame(()=>{Te.current=!1})},[]),It=b.useCallback(()=>{if(Te.current)return;const Ne=ct();Ae(gt=>{const nn=gt.slice(0,Le+1);return nn.push(Ne),nn.length>50&&nn.shift(),nn}),it(gt=>Math.min(gt+1,49))},[ct,Le]),Lt=b.useCallback(()=>{if(Le<=0)return;const Ne=Le-1;it(Ne),nt(Se[Ne])},[Le,Se,nt]),dt=b.useCallback(()=>{if(Le>=Se.length-1)return;const Ne=Le+1;it(Ne),nt(Se[Ne])},[Le,Se,nt]),wt=Le>0,mt=Le<Se.length-1,Bt=b.useCallback(()=>se!==null||u!==null||x!==0||_||D||y!=="none"||Object.keys(w).some(Ne=>w[Ne]!==Zu[Ne]),[se,u,x,_,D,y,w]),He=b.useCallback(()=>{d(null),ie(null),p(null),v("none"),C(Zu),E(0),I(!1),P(!1),V(1),B({x:0,y:0}),Ae([]),it(-1)},[]),we=b.useCallback(async()=>{const Ne=Re.current;if(!Ne){tn.error("图片未加载");return}const gt=tn.loading("正在处理图片...",0);try{const nn=document.createElement("canvas"),Zt=nn.getContext("2d");if(!Zt)throw new Error("无法创建 Canvas 上下文");let Fn=Ne.naturalWidth,We=Ne.naturalHeight,rn=0,Rn=0,tr=Ne.naturalWidth,dr=Ne.naturalHeight;const Yn=se||u;Yn&&(rn=Yn.x,Rn=Yn.y,tr=Yn.width,dr=Yn.height,Fn=Yn.width,We=Yn.height);const pr=(x%360+360)%360;(pr===90||pr===270)&&([Fn,We]=[We,Fn]),nn.width=Fn,nn.height=We,Zt.save(),Zt.translate(Fn/2,We/2),x!==0&&Zt.rotate(x*Math.PI/180),_&&Zt.scale(-1,1),D&&Zt.scale(1,-1);let gr=tr,Ar=dr;(pr===90||pr===270)&&([gr,Ar]=[Ar,gr]);const Oi=pt();Oi!=="none"&&(Zt.filter=Oi),Zt.drawImage(Ne,rn,Rn,tr,dr,-gr/2,-Ar/2,gr,Ar),Zt.restore();const Ur=nn.toDataURL("image/png");if(tn.close(gt),o){o(Ur);return}J(Ur),Z(!0)}catch(nn){tn.close(gt),tn.error(nn instanceof Error?nn.message:"图片处理失败")}},[se,u,x,_,D,pt,o]),ue=b.useCallback(Ne=>{if(oe){switch(Ne){case"overwrite":n==null||n(oe);break;case"insert":r==null||r(oe);break;case"download":{const gt=document.createElement("a");gt.href=oe,gt.download=`edited-image-${Date.now()}.png`,gt.click(),tn.success("图片已下载");break}}Z(!1),J(null),i==null||i()}},[oe,n,r,i]),_e=b.useCallback(Ne=>{p(Ne),d(null),ie(null)},[]),xe=b.useCallback(Ne=>{v(Ne),Ne!=="none"&&C(Zu)},[]),Fe=b.useCallback((Ne,gt)=>{C(nn=>({...nn,[Ne]:gt})),v("none")},[]),lt=b.useCallback(Ne=>{E(gt=>gt+Ne)},[]),Ht=b.useCallback(()=>{I(Ne=>!Ne)},[]),At=b.useCallback(()=>{P(Ne=>!Ne)},[]),le=b.useCallback(()=>{!u||!Re.current||(ie({...u}),c("filter"))},[u]),me=b.useCallback(()=>{const Ne=Re.current;if(!Ne){tn.warning("图片未加载完成");return}ge(!0),requestAnimationFrame(()=>{try{const gt=qtt(Ne);gt?(p(null),d(gt),tn.success("已检测到白边,裁剪框已自动调整")):tn.info("未检测到明显的白边")}catch{tn.error("检测白边失败")}finally{ge(!1)}})},[]);b.useEffect(()=>{const Ne=gt=>{gt.target instanceof HTMLInputElement||gt.target instanceof HTMLTextAreaElement||(gt.key==="Enter"&&l==="crop"&&u&&(gt.preventDefault(),le()),(gt.ctrlKey||gt.metaKey)&>.key==="z"&&!gt.shiftKey&&(gt.preventDefault(),Lt()),(gt.ctrlKey||gt.metaKey)&&(gt.key==="y"||gt.key==="z"&>.shiftKey)&&(gt.preventDefault(),dt()))};return window.addEventListener("keydown",Ne),()=>window.removeEventListener("keydown",Ne)},[l,u,le,Lt,dt]);const ke=b.useCallback(()=>{V(Ne=>Math.min(Ne+z,j))},[]),Oe=b.useCallback(()=>{V(Ne=>Math.max(Ne-z,H))},[]),De=b.useCallback(()=>{V(1),B({x:0,y:0})},[]),Ye=b.useCallback(Ne=>{Ne.preventDefault();const gt=Math.abs(Ne.deltaY);let nn;gt>50?nn=Ne.deltaY>0?-.15:.15:nn=-Ne.deltaY*.008,V(Zt=>Math.max(H,Math.min(j,Zt+nn)))},[]);b.useEffect(()=>{const Ne=ht.current;if(Ne)return Ne.addEventListener("wheel",Ye,{passive:!1}),()=>Ne.removeEventListener("wheel",Ye)},[Ye]);const Rt=b.useCallback(Ne=>{Ne==="crop"&&se&&!u&&d({...se}),c(Ne)},[se,u]),St=b.useCallback(Ne=>{l!=="crop"&&($(!0),Y({x:Ne.clientX-N.x,y:Ne.clientY-N.y}))},[l,N]),Ct=b.useCallback(Ne=>{O&&B({x:Ne.clientX-U.x,y:Ne.clientY-U.y})},[O,U]),Dt=b.useCallback(()=>{$(!1)},[]);b.useEffect(()=>{if(!O)return;const Ne=nn=>{B({x:nn.clientX-U.x,y:nn.clientY-U.y})},gt=()=>{$(!1)};return document.addEventListener("mousemove",Ne),document.addEventListener("mouseup",gt),()=>{document.removeEventListener("mousemove",Ne),document.removeEventListener("mouseup",gt)}},[O,U]),b.useEffect(()=>{V(1),B({x:0,y:0})},[l]),b.useImperativeHandle(a,()=>({reset:He,save:we,hasChanges:Bt,getState:ct,setState:nt}));const Gt=pt(),Ft=at();return g.jsxs("div",{className:`image-editor-core ${s||""}`,children:[g.jsxs("div",{className:"image-editor-core__header",children:[g.jsx("div",{className:"image-editor-core__title",children:"编辑图片"}),g.jsxs("div",{className:"image-editor-core__actions",children:[g.jsx(cn,{content:"撤销 (Ctrl+Z)",theme:"light",placement:"bottom",zIndex:zc,children:g.jsx("button",{type:"button",className:`image-editor-core__btn ${wt?"":"disabled"}`,onClick:Lt,disabled:!wt,children:g.jsx(FCe,{size:18})})}),g.jsx(cn,{content:"重做 (Ctrl+Y)",theme:"light",placement:"bottom",zIndex:zc,children:g.jsx("button",{type:"button",className:`image-editor-core__btn ${mt?"":"disabled"}`,onClick:dt,disabled:!mt,children:g.jsx(iCe,{size:18})})}),g.jsx("div",{className:"image-editor-core__divider"}),g.jsx(cn,{content:"对比原图(按住查看)",theme:"light",placement:"bottom",zIndex:zc,children:g.jsx("button",{type:"button",className:`image-editor-core__btn ${ae?"active":""}`,onMouseDown:()=>Q(!0),onMouseUp:()=>Q(!1),onMouseLeave:()=>Q(!1),children:g.jsx(vY,{size:18})})}),g.jsx(cn,{content:"重置",theme:"light",placement:"bottom",zIndex:zc,children:g.jsx("button",{type:"button",className:"image-editor-core__btn",onClick:He,children:g.jsx(Uv,{size:18})})}),i&&g.jsx(cn,{content:"取消",theme:"light",placement:"bottom",zIndex:zc,children:g.jsx("button",{type:"button",className:"image-editor-core__btn",onClick:i,children:g.jsx(md,{size:18})})}),(o||n||r)&&g.jsx(cn,{content:"保存",theme:"light",placement:"bottom",zIndex:zc,children:g.jsx("button",{type:"button",className:"image-editor-core__btn image-editor-core__btn--primary",onClick:we,children:g.jsx(Nd,{size:18})})})]})]}),g.jsxs("div",{className:"image-editor-core__main",children:[g.jsxs("div",{className:"image-editor-core__sidebar",children:[g.jsxs("div",{className:"image-editor-core__mode-tabs",children:[g.jsxs("button",{type:"button",className:`image-editor-core__mode-tab ${l==="crop"?"active":""}`,onClick:()=>Rt("crop"),children:[g.jsx(j2e,{size:16}),g.jsx("span",{children:"裁剪"})]}),g.jsxs("button",{type:"button",className:`image-editor-core__mode-tab ${l==="filter"?"active":""}`,onClick:()=>Rt("filter"),children:[g.jsx(ACe,{size:16}),g.jsx("span",{children:"滤镜"})]})]}),g.jsx("div",{className:"image-editor-core__panel",children:l==="crop"?g.jsx(Yle,{aspectRatio:f,presets:qle,onAspectRatioChange:_e,rotation:x,flipH:_,flipV:D,onRotate:lt,onFlipH:Ht,onFlipV:At,onConfirmCrop:le,hasCropArea:!!u,onAutoTrimWhitespace:me,isDetectingWhitespace:ce}):g.jsx(Xle,{filterType:y,filterParams:w,presets:rO,imageUrl:e,onPresetSelect:xe,onParamChange:Fe})})]}),g.jsxs("div",{className:"image-editor-core__preview",ref:ht,onMouseDown:St,onMouseMove:Ct,onMouseUp:Dt,onMouseLeave:Dt,style:{cursor:O?"grabbing":"grab"},children:[g.jsx("div",{className:"image-editor-core__canvas-wrapper",style:{transform:`translate(${N.x}px, ${N.y}px)`},children:ae?se?(()=>{const Ne=se.y/k.height*100,gt=(k.width-se.x-se.width)/k.width*100,nn=(k.height-se.y-se.height)/k.height*100,Zt=se.x/k.width*100;return g.jsx("div",{className:"image-editor-core__filter-preview",style:{transform:`${Ft} scale(${T*F})`.trim(),clipPath:`inset(${Ne}% ${gt}% ${nn}% ${Zt}%)`},children:g.jsx("img",{src:e,alt:"Original",draggable:!1})})})():g.jsx("div",{className:"image-editor-core__filter-preview",style:{transform:`${Ft} scale(${T*F})`.trim()},children:g.jsx("img",{src:e,alt:"Original",draggable:!1})}):l==="crop"?g.jsx(Ytt,{imageUrl:e,imageSize:k,cropArea:u,aspectRatio:f,rotation:x,displayScale:T,flipH:_,flipV:D,zoom:F,filterCSS:Gt,onCropChange:d},e):se?(()=>{const Ne=se.y/k.height*100,gt=(k.width-se.x-se.width)/k.width*100,nn=(k.height-se.y-se.height)/k.height*100,Zt=se.x/k.width*100;return g.jsx("div",{className:"image-editor-core__filter-preview",style:{filter:Gt,transform:`${Ft} scale(${T*F})`.trim(),clipPath:`inset(${Ne}% ${gt}% ${nn}% ${Zt}%)`},children:g.jsx("img",{src:e,alt:"Preview",draggable:!1})})})():g.jsx("div",{className:"image-editor-core__filter-preview",style:{filter:Gt,transform:`${Ft} scale(${T*F})`.trim()},children:g.jsx("img",{src:e,alt:"Preview",draggable:!1})})}),g.jsxs("div",{className:"image-editor-core__zoom-controls",children:[g.jsx(cn,{content:"缩小",theme:"light",placement:"top",zIndex:zc,children:g.jsx("button",{type:"button",className:"image-editor-core__zoom-btn",onClick:Oe,disabled:F<=H,children:g.jsx(IY,{size:16})})}),g.jsxs("span",{className:"image-editor-core__zoom-value",children:[Math.round(F*100),"%"]}),g.jsx(cn,{content:"放大",theme:"light",placement:"top",zIndex:zc,children:g.jsx("button",{type:"button",className:"image-editor-core__zoom-btn",onClick:ke,disabled:F>=j,children:g.jsx(_Y,{size:16})})}),g.jsx(cn,{content:"重置视图",theme:"light",placement:"top",zIndex:zc,children:g.jsx("button",{type:"button",className:"image-editor-core__zoom-btn",onClick:De,children:g.jsx(xY,{size:16})})})]})]})]}),K&&oe&&g.jsxs("div",{className:"image-editor-core__save-dialog",children:[g.jsx("div",{className:"image-editor-core__save-dialog-backdrop",onClick:()=>Z(!1)}),g.jsxs("div",{className:"image-editor-core__save-dialog-content",children:[g.jsx("h3",{className:"image-editor-core__save-dialog-title",children:"保存图片"}),g.jsxs("div",{className:"image-editor-core__save-options",children:[t&&n&&g.jsxs("button",{type:"button",className:"image-editor-core__save-option",onClick:()=>ue("overwrite"),children:[g.jsx(cCe,{size:20}),g.jsxs("div",{className:"image-editor-core__save-option-content",children:[g.jsx("span",{className:"image-editor-core__save-option-label",children:"覆盖原图"}),g.jsx("span",{className:"image-editor-core__save-option-desc",children:"替换画布中的原图片"})]})]}),r&&g.jsxs("button",{type:"button",className:"image-editor-core__save-option",onClick:()=>ue("insert"),children:[g.jsx(gSe,{size:20}),g.jsxs("div",{className:"image-editor-core__save-option-content",children:[g.jsx("span",{className:"image-editor-core__save-option-label",children:"插入新图片"}),g.jsx("span",{className:"image-editor-core__save-option-desc",children:"在画布中插入编辑后的图片"})]})]}),g.jsxs("button",{type:"button",className:"image-editor-core__save-option",onClick:()=>ue("download"),children:[g.jsx($v,{size:20}),g.jsxs("div",{className:"image-editor-core__save-option-content",children:[g.jsx("span",{className:"image-editor-core__save-option-label",children:"下载到本地"}),g.jsx("span",{className:"image-editor-core__save-option-desc",children:"保存编辑后的图片到本地"})]})]})]}),g.jsx("button",{type:"button",className:"image-editor-core__save-cancel",onClick:()=>Z(!1),children:"取消"})]})]})]})});dI.displayName="ImageEditorCore";const Ytt=({imageUrl:e,imageSize:t,cropArea:n,aspectRatio:r,rotation:i,flipH:o,flipV:s,zoom:a,displayScale:l,filterCSS:c,onCropChange:u})=>{const d=b.useRef(null),[f,p]=b.useState(!1),[y,v]=b.useState(null),[w,C]=b.useState(null),[x,E]=b.useState({x:0,y:0}),[_,I]=b.useState(null);b.useEffect(()=>{if(!n&&t.width>0){let M;if(r)if(t.width/t.height>r){const V=t.height,H=V*r;M={x:(t.width-H)/2,y:0,width:H,height:V}}else{const V=t.width,H=V/r;M={x:0,y:(t.height-H)/2,width:V,height:H}}else M={x:0,y:0,width:t.width,height:t.height};u(M)}},[r,t,n,u]);const D=b.useCallback((M,F,V)=>{M.preventDefault(),M.stopPropagation(),p(!0),v(F),C(V||null),E({x:M.clientX,y:M.clientY}),I(n)},[n]);b.useEffect(()=>{if(!f||!_)return;const M=V=>{let H=(V.clientX-x.x)/(l*a),j=(V.clientY-x.y)/(l*a);const z=(i%360+360)%360;let N,B;switch(z){case 90:N=j,B=-H;break;case 180:N=-H,B=-j;break;case 270:N=-j,B=H;break;default:N=H,B=j}o&&(N=-N),s&&(B=-B);const O={..._};if(y==="move")O.x=Math.max(0,Math.min(_.x+N,t.width-_.width)),O.y=Math.max(0,Math.min(_.y+B,t.height-_.height));else if(y==="resize"&&w){switch(w){case"nw":O.x=Math.min(_.x+N,_.x+_.width-20),O.y=Math.min(_.y+B,_.y+_.height-20),O.width=Math.max(20,_.width-N),O.height=Math.max(20,_.height-B);break;case"ne":O.y=Math.min(_.y+B,_.y+_.height-20),O.width=Math.max(20,_.width+N),O.height=Math.max(20,_.height-B);break;case"sw":O.x=Math.min(_.x+N,_.x+_.width-20),O.width=Math.max(20,_.width-N),O.height=Math.max(20,_.height+B);break;case"se":O.width=Math.max(20,_.width+N),O.height=Math.max(20,_.height+B);break;case"n":O.y=Math.min(_.y+B,_.y+_.height-20),O.height=Math.max(20,_.height-B);break;case"s":O.height=Math.max(20,_.height+B);break;case"w":O.x=Math.min(_.x+N,_.x+_.width-20),O.width=Math.max(20,_.width-N);break;case"e":O.width=Math.max(20,_.width+N);break}if(r&&(["e","w","ne","nw","se","sw"].includes(w)?O.height=O.width/r:["n","s"].includes(w)&&(O.width=O.height*r)),O.x<0&&(O.width+=O.x,O.x=0),O.y<0&&(O.height+=O.y,O.y=0),O.width=Math.min(O.width,t.width-O.x),O.height=Math.min(O.height,t.height-O.y),O.width=Math.max(20,O.width),O.height=Math.max(20,O.height),r){const U=O.height*r,Y=O.width/r;O.width>U?O.width=U:O.height>Y&&(O.height=Y)}}u(O)},F=()=>{p(!1),v(null),C(null)};return document.addEventListener("mousemove",M),document.addEventListener("mouseup",F),()=>{document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",F)}},[f,y,w,x,_,l,a,i,o,s,t,r,u]);const P=t.width*l*a,k=t.height*l*a,R={transform:`rotate(${i}deg) ${o?"scaleX(-1)":""} ${s?"scaleY(-1)":""}`.trim()},T=M=>{const F={nw:"nw-resize",ne:"ne-resize",sw:"sw-resize",se:"se-resize",n:"n-resize",s:"s-resize",w:"w-resize",e:"e-resize"},V={nw:"ne",ne:"se",se:"sw",sw:"nw",n:"e",e:"s",s:"w",w:"n"};let H=M;const j=(i%360+360)%360,z=Math.round(j/90)%4;for(let N=0;N<z;N++)H=V[H]||H;return o&&(H.includes("w")?H=H.replace("w","e"):H.includes("e")&&(H=H.replace("e","w"))),s&&(H.includes("n")?H=H.replace("n","s"):H.includes("s")&&(H=H.replace("s","n"))),F[H]||"pointer"};return g.jsx("div",{ref:d,className:"crop-canvas",children:g.jsxs("div",{className:"crop-canvas__image-container",style:{width:P,height:k,...R},children:[g.jsx("img",{src:e,alt:"Crop",draggable:!1,style:{filter:c||"none"}}),n&&g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"crop-canvas__overlay"}),g.jsxs("div",{className:"crop-canvas__crop-area",style:{left:n.x*l*a,top:n.y*l*a,width:n.width*l*a,height:n.height*l*a},onMouseDown:M=>D(M,"move"),children:[g.jsx("div",{className:"crop-canvas__crop-image",style:{backgroundImage:`url(${e})`,backgroundPosition:`-${n.x*l*a}px -${n.y*l*a}px`,backgroundSize:`${P}px ${k}px`,filter:c||"none"}}),g.jsxs("div",{className:"crop-canvas__grid",children:[g.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--h1"}),g.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--h2"}),g.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--v1"}),g.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--v2"})]}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--nw",style:{cursor:T("nw")},onMouseDown:M=>D(M,"resize","nw")}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--ne",style:{cursor:T("ne")},onMouseDown:M=>D(M,"resize","ne")}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--sw",style:{cursor:T("sw")},onMouseDown:M=>D(M,"resize","sw")}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--se",style:{cursor:T("se")},onMouseDown:M=>D(M,"resize","se")}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--n",style:{cursor:T("n")},onMouseDown:M=>D(M,"resize","n")}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--s",style:{cursor:T("s")},onMouseDown:M=>D(M,"resize","s")}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--w",style:{cursor:T("w")},onMouseDown:M=>D(M,"resize","w")}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--e",style:{cursor:T("e")},onMouseDown:M=>D(M,"resize","e")})]})]})]})})},Zle=b.forwardRef(({imageUrl:e,showOverwrite:t=!1,onOverwrite:n,onInsert:r},i)=>g.jsx(dI,{ref:i,imageUrl:e,showOverwrite:t,onOverwrite:n,onInsert:r,className:"embedded-editor"}));Zle.displayName="ImageEditorContent";const Hg=({visible:e,items:t,initialMode:n="single",initialIndex:r=0,onClose:i,onModeChange:o,showThumbnails:s=!0,maxCompareSlots:a=4,defaultCompareLayout:l="horizontal",className:c="",showTitle:u=!0,videoAutoPlay:d=!1,videoLoop:f=!0,onInsertToCanvas:p,onEdit:y,useBuiltInEditor:v=!1,onEditOverwrite:w,onEditInsert:C,showEditOverwrite:x=!1})=>{const E=b.useRef(null),_=b.useRef(null),[I,D]=b.useState(2),[P,k]=b.useState(!1),[R,T]=b.useState(null),M=b.useRef(null),F=b.useRef(new Map),V=b.useRef([]),H=b.useRef(null),j=b.useRef(!1),[z,N]=Ett({items:t,initialMode:n,initialIndex:r,maxCompareSlots:a,defaultCompareLayout:l,visible:e,onModeChange:o}),{mode:B,currentIndex:O,compareIndices:$,compareLayout:U,syncMode:Y,zoomLevel:K,panOffset:Z,focusedSlot:oe}=z,J=b.useCallback(ue=>{M.current=ue,T(ue)},[]);b.useEffect(()=>{e||(F.current.clear(),J(null))},[e,J]);const ae=b.useCallback(()=>{if(t.length<=I)return;const _e=Math.max(...$)+1;if(_e>=t.length){const xe=[];for(let Fe=0;Fe<I&&Fe<t.length;Fe++)xe.push(Fe);xe.forEach((Fe,lt)=>N.addToCompare(Fe,lt))}else{const xe=[];for(let Fe=0;Fe<I;Fe++){const lt=(_e+Fe)%t.length;xe.push(lt)}xe.forEach((Fe,lt)=>N.addToCompare(Fe,lt))}},[t.length,I,$,N]),Q=b.useCallback(()=>{if(t.length<=I)return;const _e=Math.min(...$)-I;if(_e<0){const xe=Math.max(0,t.length-I),Fe=[];for(let lt=0;lt<I&&xe+lt<t.length;lt++)Fe.push(xe+lt);Fe.forEach((lt,Ht)=>N.addToCompare(lt,Ht))}else{const xe=[];for(let Fe=0;Fe<I;Fe++)xe.push(_e+Fe);xe.forEach((Fe,lt)=>N.addToCompare(Fe,lt))}},[t.length,I,$,N]),se=b.useCallback(ue=>{const _e=t[ue];if(!_e||_e.type!=="image")return!1;const xe=M.current;if(xe&&_.current){const Fe=_.current.getState();F.current.set(xe.url,Fe)}return N.goTo(ue),J(_e),setTimeout(()=>{const Fe=F.current.get(_e.url);Fe&&_.current&&_.current.setState(Fe)},50),!0},[t,N,J]),ie=b.useCallback(()=>{N.resetView(),V.current.forEach(ue=>{ue!=null&&ue.isVideo()&&ue.resetVideo()})},[N]);b.useEffect(()=>{if(!e)return;const ue=_e=>{const xe=_e.target instanceof HTMLElement?_e.target:null;if(xe instanceof HTMLInputElement||xe instanceof HTMLTextAreaElement||xe instanceof HTMLSelectElement||xe instanceof HTMLButtonElement||xe!=null&&xe.isContentEditable)return;const Fe=B==="single"?H.current:V.current[oe]||null;switch(_e.key){case"Escape":_e.preventDefault(),i();break;case"ArrowLeft":case"ArrowUp":if(_e.preventDefault(),B==="edit"){const lt=(O-1+t.length)%t.length;se(lt)}else B==="single"?N.goToPrev():Q();break;case"ArrowRight":case"ArrowDown":if(_e.preventDefault(),B==="edit"){const lt=(O+1)%t.length;se(lt)}else B==="single"?N.goToNext():ae();break;case"c":case"C":t.length>1&&(_e.preventDefault(),N.setMode(B==="single"?"compare":"single"));break;case"1":case"2":case"3":case"4":if(B==="compare"){const lt=parseInt(_e.key,10)-1;lt<I&&(_e.preventDefault(),N.setFocusedSlot(lt))}break;case"+":case"=":_e.preventDefault(),N.zoom(.25);break;case"-":case"_":_e.preventDefault(),N.zoom(-.25);break;case"0":_e.preventDefault(),B==="compare"?ie():N.resetView();break;case" ":case"Spacebar":Fe!=null&&Fe.isVideo()&&(_e.preventDefault(),Fe.toggleVideoPlayback());break;case"s":case"S":B==="compare"&&(_e.preventDefault(),N.toggleSyncMode());break}};return window.addEventListener("keydown",ue),()=>window.removeEventListener("keydown",ue)},[e,B,t.length,t,O,oe,N,i,I,ae,Q,se,ie]);const ce=b.useCallback(()=>{if(E.current)if(P){const ue=lEe();ue==null||ue.catch(()=>{})}else{const ue=aEe(E.current);ue==null||ue.catch(()=>{})}},[P]);b.useEffect(()=>{const ue=()=>{k(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",ue),()=>document.removeEventListener("fullscreenchange",ue)},[]);const ge=b.useCallback(ue=>{ue.target===ue.currentTarget&&i()},[i]),Se=b.useCallback(ue=>{B==="edit"?se(ue):B==="single"?N.goTo(ue):N.addToCompare(ue,oe)},[B,N,oe,se]),Ae=b.useCallback(ue=>{D(ue),N.setSlotCount(ue)},[N]),Le=b.useCallback((ue,_e)=>ue==="grid"?_e<=2?"layout-horizontal":"layout-grid":`layout-${ue}`,[]),it=b.useCallback(()=>{const ue=t[O];ue&&p&&p(ue)},[t,O,p]),Te=b.useCallback(async()=>{const ue=t[O];if(!ue)return;const _e=ue.type==="image"?zn(ue.url):ue.url;if(_e.startsWith("blob:")){const{unifiedCacheService:lt}=await xn(async()=>{const{unifiedCacheService:me}=await Promise.resolve().then(()=>du);return{unifiedCacheService:me}},void 0,import.meta.url),{downloadFromBlob:Ht}=await xn(async()=>{const{downloadFromBlob:me}=await Promise.resolve().then(()=>_O);return{downloadFromBlob:me}},void 0,import.meta.url),At=_e.indexOf("#"),le=At>0?_e.substring(At+1):null;if(le&&le.startsWith("merged-video-")){const me=await lt.getCachedBlob(le);if(me){const ke=me.type||"video/webm",Oe=ke.startsWith("video/mp4")?"mp4":ke.startsWith("video/webm")?"webm":"bin";Ht(me,`merged-video-${Date.now()}.${Oe}`);return}}try{const ke=await(await fetch(_e)).blob(),Oe=ke.type.startsWith("video/mp4")?"mp4":ke.type.startsWith("video/webm")?"webm":ke.type.startsWith("audio/mpeg")?"mp3":ke.type.startsWith("audio/wav")?"wav":ke.type.startsWith("audio/")?"m4a":ke.type.startsWith("image/")?"png":"bin";Ht(ke,`${ue.type}_${Date.now()}.${Oe}`)}catch(me){console.error("[UnifiedMediaViewer] Failed to fetch blob URL:",me)}return}const{smartDownload:xe,buildDownloadFilename:Fe}=await xn(async()=>{const{smartDownload:lt,buildDownloadFilename:Ht}=await Promise.resolve().then(()=>bnt);return{smartDownload:lt,buildDownloadFilename:Ht}},void 0,import.meta.url);await xe([{url:_e,type:ue.type,filename:ue.type==="audio"?Fe(ue.title,"audio","mp3"):void 0,audioMetadata:ue.type==="audio"?{title:ue.title,prompt:ue.prompt,tags:ue.tags,coverUrl:ue.posterUrl,artist:ue.artist,album:ue.album}:void 0}])},[t,O]),Re=b.useCallback(()=>{const ue=t[O];ue&&ue.type==="image"&&(v?(J(ue),N.setMode("edit")):y&&y(ue))},[t,O,y,v,N,J]),ht=b.useCallback(ue=>{if(ue==="edit"){const _e=t[O];_e&&_e.type==="image"&&J(_e)}N.setMode(ue)},[t,O,N,J]),Ze=b.useCallback(()=>{F.current.clear(),J(null),N.setMode("single")},[N,J]),Ge=b.useCallback(()=>{var ue;(ue=_.current)==null||ue.reset()},[]),pt=b.useCallback(()=>{var ue;(ue=_.current)==null||ue.save()},[]),at=b.useCallback(ue=>{const _e=M.current;w&&_e&&w(ue,_e),Ze()},[w,Ze]),ct=b.useCallback(ue=>{C&&C(ue),Ze()},[C,Ze]),nt=b.useCallback((ue,_e)=>{V.current[ue]=_e},[]),It=b.useCallback((ue,_e)=>{j.current||(j.current=!0,V.current.forEach((xe,Fe)=>{Fe!==ue&&(xe!=null&&xe.isVideo())&&(_e?xe.playVideo():xe.pauseVideo())}),setTimeout(()=>{j.current=!1},50))},[]),Lt=b.useCallback((ue,_e)=>{j.current||(j.current=!0,V.current.forEach((xe,Fe)=>{Fe!==ue&&(xe!=null&&xe.isVideo())&&xe.setVideoTime(_e)}),setTimeout(()=>{j.current=!1},50))},[]),dt=()=>{const ue=t[O]||null;return g.jsxs("div",{className:"unified-viewer__single",children:[t.length>1&&g.jsx("button",{className:"unified-viewer__nav unified-viewer__nav--prev",onClick:N.goToPrev,"aria-label":"上一个",children:g.jsx(x2,{size:32})}),g.jsx(nO,{ref:H,item:ue,zoomLevel:K,panOffset:Z,videoAutoPlay:d,videoLoop:f,onZoomChange:N.setZoomLevel,onPanChange:()=>{},onInsertToCanvas:p?it:void 0,onDownload:Te,onEdit:y?Re:void 0}),t.length>1&&g.jsx("button",{className:"unified-viewer__nav unified-viewer__nav--next",onClick:N.goToNext,"aria-label":"下一个",children:g.jsx(gY,{size:32})})]})},wt=()=>{const ue=Le(U,I);return g.jsx("div",{className:`unified-viewer__compare ${ue}`,children:Array.from({length:I}).map((_e,xe)=>{const Fe=$[xe],lt=typeof Fe=="number"?t[Fe]:null;return g.jsx(nO,{ref:Ht=>nt(xe,Ht),item:lt,slotIndex:xe,isFocused:oe===xe,zoomLevel:Y?K:void 0,panOffset:Y?Z:void 0,onClick:()=>N.setFocusedSlot(xe),onClose:I>2?()=>N.removeFromCompare(xe):void 0,videoAutoPlay:d,videoLoop:f,onZoomChange:Y?N.setZoomLevel:void 0,onPanChange:Y?N.setPan:void 0,isCompareMode:!0,isSyncMode:Y,onVideoPlayStateChange:Y?Ht=>It(xe,Ht):void 0,onVideoTimeUpdate:Y?Ht=>Lt(xe,Ht):void 0},xe)})})},mt=()=>{const ue=R||t[O];return!ue||ue.type!=="image"?null:g.jsx("div",{className:"unified-viewer__edit",children:g.jsx(Zle,{ref:_,imageUrl:ue.url,showOverwrite:x,onOverwrite:w?at:void 0,onInsert:C?ct:void 0})})},Bt=t[O]||null;if(!e||t.length===0)return null;const He=()=>{switch(B){case"edit":return mt();case"compare":return wt();default:return dt()}},we=g.jsx("div",{ref:E,className:`unified-viewer ${c} ${P?"unified-viewer--fullscreen":""} ${B==="edit"?"unified-viewer--edit-mode":""}`,onClick:ge,children:g.jsxs("div",{className:"unified-viewer__container",children:[g.jsx(Ktt,{mode:B,currentIndex:O,totalCount:t.length,slotCount:I,compareLayout:U,syncMode:Y,onModeChange:ht,onSlotCountChange:Ae,onLayoutChange:N.setCompareLayout,onSyncToggle:N.toggleSyncMode,onResetView:B==="compare"?ie:N.resetView,onClose:i,onFullscreen:ce,isImage:(Bt==null?void 0:Bt.type)==="image",showEditButton:v||!!y,onBackToPreview:Ze,onResetEdit:Ge,onSaveEdit:pt}),g.jsx("div",{className:"unified-viewer__content",children:He()}),s&&t.length>1&&g.jsx(Gtt,{items:t,mode:B==="edit"?"single":B,currentIndex:O,compareIndices:$,onThumbnailClick:Se})]})});return Ui.createPortal(we,document.body)},gpt=Object.freeze(Object.defineProperty({__proto__:null,UnifiedMediaViewer:Hg,default:Hg},Symbol.toStringTag,{value:"Module"})),Jle=({visible:e,imageUrl:t,onClose:n,onSave:r,onOverwrite:i,onInsert:o,showOverwrite:s=!1})=>{const a=b.useRef(null);if(b.useEffect(()=>{var c;e||(c=a.current)==null||c.reset()},[e]),!e)return null;const l=g.jsxs("div",{className:"image-editor",style:{zIndex:Eu.DIALOG_AI_IMAGE},"data-testid":"image-editor",children:[g.jsx("div",{className:"image-editor__backdrop",onClick:n}),g.jsx("div",{className:"image-editor__container",children:g.jsx(dI,{ref:a,imageUrl:t,showOverwrite:s,onOverwrite:i,onInsert:o,onClose:n,onSave:r})})]});return Ui.createPortal(l,document.body)},ypt=Object.freeze(Object.defineProperty({__proto__:null,ASPECT_RATIO_PRESETS:qle,CropPanel:Yle,DEFAULT_FILTER_PARAMS:Zu,FILTER_PRESETS:rO,FilterPanel:Xle,ImageEditor:Jle,ImageEditorCore:dI},Symbol.toStringTag,{value:"Module"})),Xtt=({className:e,selectedPlaylistId:t,allCount:n,allTracksCount:r,allTracksLabel:i="全部语音",tempTabs:o=[],playlists:s,playlistItems:a,onSelect:l,onCreate:c,onRename:u,onDelete:d,allLabel:f="全部音频",createLabel:p="新建播放列表"})=>{const{contextMenu:y,open:v,close:w}=H3(),C=b.useMemo(()=>typeof u=="function"||typeof d=="function",[d,u]),x=b.useMemo(()=>[{key:"create",label:"新建播放列表",icon:g.jsx(ic,{size:14}),onSelect:()=>c()},{key:"rename",label:"重命名",icon:g.jsx(oR,{size:14}),disabled:I=>I.isSystem||!u,onSelect:I=>u==null?void 0:u(I)},{key:"delete",label:"删除播放列表",icon:g.jsx(aR,{size:14}),danger:!0,disabled:I=>I.isSystem||!d,onSelect:I=>d==null?void 0:d(I)}],[c,d,u]),E=b.useMemo(()=>s.find(I=>I.id===ul)||null,[s]),_=b.useMemo(()=>s.filter(I=>I.id!==ul),[s]);return g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:Je("audio-playlist-tabs",e),children:[g.jsxs("button",{type:"button",className:Je("audio-playlist-tabs__chip",{"audio-playlist-tabs__chip--active":t===hl}),onClick:()=>l(hl),onContextMenu:C?I=>{I.preventDefault(),I.stopPropagation(),v(I,{id:hl,name:f,createdAt:0,updatedAt:0,isSystem:!0})}:void 0,children:[g.jsx(ov,{size:14}),g.jsx("span",{children:f}),g.jsx("span",{className:"audio-playlist-tabs__count",children:n})]}),typeof r=="number"?g.jsxs("button",{type:"button",className:Je("audio-playlist-tabs__chip",{"audio-playlist-tabs__chip--active":t===iV}),onClick:()=>l(iV),children:[g.jsx(yS,{size:14}),g.jsx("span",{children:i}),g.jsx("span",{className:"audio-playlist-tabs__count",children:r})]}):null,E?g.jsxs("button",{type:"button",className:Je("audio-playlist-tabs__chip",{"audio-playlist-tabs__chip--active":t===E.id}),onClick:()=>l(E.id),onContextMenu:C?I=>{I.preventDefault(),I.stopPropagation(),v(I,E)}:void 0,children:[g.jsx(vS,{size:14}),g.jsx("span",{children:E.name}),g.jsx("span",{className:"audio-playlist-tabs__count",children:(a[E.id]||[]).length})]}):null,o.map(I=>g.jsxs("button",{type:"button",className:Je("audio-playlist-tabs__chip",{"audio-playlist-tabs__chip--active":t===I.id}),onClick:()=>l(I.id),children:[I.type==="reading"?g.jsx(yS,{size:14}):g.jsx(ov,{size:14}),g.jsx("span",{children:I.label}),g.jsx("span",{className:"audio-playlist-tabs__count",children:I.count})]},I.id)),_.map(I=>{const D=(a[I.id]||[]).length,P=C;return g.jsxs("button",{type:"button",className:Je("audio-playlist-tabs__chip",{"audio-playlist-tabs__chip--active":t===I.id}),onClick:()=>l(I.id),onContextMenu:P?k=>{k.preventDefault(),k.stopPropagation(),v(k,I)}:void 0,children:[g.jsx(ov,{size:14}),g.jsx("span",{children:I.name}),g.jsx("span",{className:"audio-playlist-tabs__count",children:D})]},I.id)}),g.jsxs("button",{type:"button",className:"audio-playlist-tabs__create",onClick:c,children:[g.jsx(ic,{size:14}),g.jsx("span",{children:p})]})]}),g.jsx(W3,{state:y,items:x,onClose:w})]})},tT="github_sync_master_index",nT="github_sync_master_gist_id";class Ztt{constructor(){this.masterIndex=null,this.masterGistId=null,this.initialized=!1}async initialize(){this.initialized||(this.masterIndex=await er.get(tT),this.masterGistId=await er.get(nT),this.initialized=!0,fe("ShardRouter initialized",{hasMasterIndex:!!this.masterIndex,masterGistId:this.masterGistId?xa(this.masterGistId):null,shardCount:this.masterIndex?Object.keys(this.masterIndex.shards).length:0}))}getMasterIndex(){return this.masterIndex}getMasterGistId(){return this.masterGistId}async setMasterGistId(t){this.masterGistId=t,await er.set(nT,t)}isConfigured(){return!!this.masterIndex&&!!this.masterGistId}async loadMasterIndexFromRemote(){if(!this.masterGistId)return fe("No master gist ID configured"),null;try{const t=await yt.getGistFileContent(Is.MASTER_INDEX,this.masterGistId);if(!t)return fe("No master index found in remote"),null;const n=JSON.parse(t);return this.masterIndex=n,await this.saveMasterIndexLocally(),fe("Loaded master index from remote",{shards:Object.keys(n.shards).length,files:Object.keys(n.fileIndex).length}),n}catch(t){return vn("Failed to load master index",t instanceof Error?t:new Error(String(t))),null}}async saveMasterIndexLocally(){this.masterIndex&&await er.set(tT,this.masterIndex)}async saveMasterIndexToRemote(){if(!this.masterIndex||!this.masterGistId)throw new Error("Master index or gist ID not configured");QM(this.masterIndex),await yt.updateGistFiles({[Is.MASTER_INDEX]:JSON.stringify(this.masterIndex,null,2)},this.masterGistId),await this.saveMasterIndexLocally(),fe("Saved master index to remote")}async initializeMasterIndex(t){if(this.masterIndex)return this.masterIndex;if(this.masterIndex=XQe(t),!this.masterGistId)throw new Error("Master gist ID must be set before initializing index");return await this.saveMasterIndexLocally(),fe("Initialized new master index"),this.masterIndex}getShardForFile(t){if(!this.masterIndex)return null;const n=this.masterIndex.fileIndex[t];return n&&this.masterIndex.shards[n.shardId]||null}getFileIndexEntry(t){return this.masterIndex&&this.masterIndex.fileIndex[t]||null}isFileSynced(t){return this.getFileIndexEntry(t)!==null}findActiveShard(t){if(!this.masterIndex)return null;const n=Object.values(this.masterIndex.shards).filter(r=>r.status==="active").sort((r,i)=>i.fileCount-r.fileCount);for(const r of n)if(QQe(r,t))return r;return null}async createShard(t){if(!this.masterIndex||!this.masterGistId)throw new Error("Master index not initialized");const n=Object.keys(this.masterIndex.shards).length+1,r=t||eet(n);if(this.masterIndex.shards[r])throw new Error(`Shard alias "${r}" already exists`);const i=`${jC.SHARD} #${n} (${r})`,o=Sle(r,this.masterGistId),s=await pi.getPassword(),a=JSON.stringify(o,null,2),l=await Nn.encrypt(a,this.masterGistId,s||void 0),c=await yt.createSyncGist({[Is.SHARD_MANIFEST]:l});try{await yt.updateGistFiles({[Is.SHARD_MANIFEST]:l},c.id)}catch(d){Pt("Failed to update shard description",{error:String(d)})}const u=ZQe(c.id,r,n);return u.description=i,this.masterIndex.shards[r]=u,QM(this.masterIndex),fe("Created new shard",{alias:r,gistId:xa(c.id),order:n}),u}async allocateFile(t){if(!this.masterIndex)throw new Error("Master index not initialized");const n=this.findActiveShard(t);return n?{shard:n,isNewShard:!1}:{shard:await this.createShard(),isNewShard:!0}}async allocateFiles(t){if(!this.masterIndex)throw new Error("Master index not initialized");const n=new Map,r=[];let i=null,o=0,s=0;const a=Object.values(this.masterIndex.shards).filter(l=>l.status==="active").sort((l,c)=>c.fileCount-l.fileCount);a.length>0&&(i=a[0],o=i.fileCount,s=i.totalSize);for(const l of t){const c=this.masterIndex.fileIndex[l.url];if(c){const d=this.masterIndex.shards[c.shardId];if(d){n.set(l.url,d);continue}}if(!i||o>=bs.FILE_LIMIT||s+l.size>bs.SIZE_LIMIT){const d=await this.createShard();r.push(d),i=d,o=0,s=0}n.set(l.url,i),o++,s+=l.size}return fe("Batch allocation completed",{totalFiles:t.length,newShardsCreated:r.length}),{allocations:n,newShards:r}}registerFile(t,n,r,i,o){if(!this.masterIndex)throw new Error("Master index not initialized");const s={shardId:n,filename:r,size:i,type:o,syncedAt:Date.now()};this.masterIndex.fileIndex[t]=s;const a=this.masterIndex.shards[n];a&&(a.fileCount++,a.totalSize+=i,a.updatedAt=Date.now(),a.fileCount>=bs.FILE_LIMIT&&(a.status="full",fe("Shard is now full",{shardId:n})))}unregisterFile(t){if(!this.masterIndex)return null;const n=this.masterIndex.fileIndex[t];if(!n)return null;delete this.masterIndex.fileIndex[t];const r=this.masterIndex.shards[n.shardId];return r&&(r.fileCount=Math.max(0,r.fileCount-1),r.totalSize=Math.max(0,r.totalSize-n.size),r.updatedAt=Date.now(),r.status==="full"&&r.fileCount<bs.FILE_LIMIT&&(r.status="active",fe("Shard reactivated",{shardId:n.shardId}))),n}getShard(t){return this.masterIndex&&this.masterIndex.shards[t]||null}getAllShards(){return this.masterIndex?Object.values(this.masterIndex.shards):[]}async updateShardAlias(t,n){if(!this.masterIndex)throw new Error("Master index not initialized");const r=this.masterIndex.shards[t];if(!r)throw new Error(`Shard "${t}" not found`);if(t!==n&&this.masterIndex.shards[n])throw new Error(`Alias "${n}" already exists`);for(const i of Object.keys(this.masterIndex.fileIndex)){const o=this.masterIndex.fileIndex[i];o.shardId===t&&(o.shardId=n)}for(const i of this.masterIndex.tombstones)i.shardId===t&&(i.shardId=n);delete this.masterIndex.shards[t],r.alias=n,r.description=`${jC.SHARD} #${r.order} (${n})`,r.updatedAt=Date.now(),this.masterIndex.shards[n]=r,fe("Updated shard alias",{old:t,new:n})}archiveShard(t){if(!this.masterIndex)throw new Error("Master index not initialized");const n=this.masterIndex.shards[t];if(!n)throw new Error(`Shard "${t}" not found`);n.status="archived",n.updatedAt=Date.now(),fe("Archived shard",{shardId:t})}reactivateShard(t){if(!this.masterIndex)throw new Error("Master index not initialized");const n=this.masterIndex.shards[t];if(!n)throw new Error(`Shard "${t}" not found`);n.fileCount>=bs.FILE_LIMIT?n.status="full":n.status="active",n.updatedAt=Date.now(),fe("Reactivated shard",{shardId:t})}getStats(){if(!this.masterIndex)return{totalShards:0,activeShards:0,fullShards:0,archivedShards:0,totalFiles:0,totalSize:0};const t=Object.values(this.masterIndex.shards);return{totalShards:t.length,activeShards:t.filter(n=>n.status==="active").length,fullShards:t.filter(n=>n.status==="full").length,archivedShards:t.filter(n=>n.status==="archived").length,totalFiles:Object.keys(this.masterIndex.fileIndex).length,totalSize:t.reduce((n,r)=>n+r.totalSize,0)}}async clearLocalCache(){this.masterIndex=null,this.masterGistId=null,this.initialized=!1,await er.remove(tT),await er.remove(nT),fe("Cleared local cache")}destroy(){this.masterIndex=null,this.masterGistId=null,this.initialized=!1}}const vt=new Ztt;function rT(){return localStorage.getItem(bd)||"unknown"}class Jtt{constructor(){this.syncingUrls=new Set}async uploadMedia(t,n){const r=Date.now(),i={success:!0,uploaded:0,downloaded:0,deleted:0,skipped:0,details:[]};if(await vt.initialize(),!vt.isConfigured())return i.success=!1,i.error="分片系统未配置",i;const o=t.filter(f=>this.syncingUrls.has(f.url)?(i.skipped++,i.details.push({url:f.url,action:"skip",success:!0,error:"正在同步中"}),!1):vt.isFileSynced(f.url)?(i.skipped++,i.details.push({url:f.url,action:"skip",success:!0,error:"已同步"}),!1):!0);if(o.length===0)return i;const s=await this.getFileSizes(o),a=await vt.allocateFiles(s),l=this.groupByShards(o,a.allocations),c=Object.keys(l);for(let f=0;f<c.length;f+=bs.CONCURRENCY){const p=c.slice(f,f+bs.CONCURRENCY);await Promise.all(p.map(y=>this.uploadToShard(y,l[y],i,n)))}await vt.saveMasterIndexToRemote(),i.success=i.uploaded>0||i.skipped>0;const u=i.details.filter(f=>!f.success).length,d=Date.now()-r;return fe("Upload completed",{uploaded:i.uploaded,skipped:i.skipped,failed:u,duration:d}),Jr("分片上传完成",{uploaded:i.uploaded,skipped:i.skipped,failed:u,duration:d}),i}async getFileSizes(t){const n=[];for(const r of t){let i=r.size||0;if(!i){const o=await yn.getCachedBlob(r.url);i=(o==null?void 0:o.size)||0}n.push({url:r.url,size:i})}return n}groupByShards(t,n){const r={};for(const i of t){const o=n.get(i.url);o&&(r[o.alias]||(r[o.alias]=[]),r[o.alias].push(i))}return r}async uploadToShard(t,n,r,i){const o=vt.getShard(t);if(!o){for(const l of n)r.details.push({url:l.url,action:"upload",success:!1,error:`分片 ${t} 不存在`});return}const s={},a=[];for(const l of n){this.syncingUrls.add(l.url);try{const c=await this.prepareMediaForUpload(l);if(c.success&&c.content){const u=`media_${ng(l.url)}.json`;s[u]=c.content,a.push(l),vt.registerFile(l.url,t,u,c.size,l.type),r.details.push({url:l.url,action:"upload",success:!0,shardId:t}),r.uploaded++,i==null||i(r.uploaded+r.skipped,r.uploaded+r.skipped+n.length,l.url,"uploading")}else r.details.push({url:l.url,action:"upload",success:!1,error:c.error||"准备上传失败"})}catch(c){vn(`Failed to prepare: ${l.url}`,c instanceof Error?c:new Error(String(c))),r.details.push({url:l.url,action:"upload",success:!1,error:c instanceof Error?c.message:"上传失败"})}finally{this.syncingUrls.delete(l.url)}}if(Object.keys(s).length>0)try{const l=await this.getOrCreateShardManifest(o);for(const y of a){const v=`media_${ng(y.url)}.json`;l.files[v]={url:y.url,type:y.type,size:y.size||0,mimeType:y.mimeType||"",syncedAt:Date.now(),syncedFromDevice:rT()}}l.updatedAt=Date.now();const c=JSON.stringify(l,null,2),u=vt.getMasterGistId();if(u){const y=await pi.getPassword();s[Is.SHARD_MANIFEST]=await Nn.encrypt(c,u,y||void 0)}else s[Is.SHARD_MANIFEST]=c;const d=Object.values(s).reduce((y,v)=>y+v.length,0),f=Object.keys(s).length;fe("Uploading to shard",{shardId:t,fileCount:f,totalSizeMB:(d/1024/1024).toFixed(2)});const p=8*1024*1024;d>p?(fe("Total size exceeds limit, splitting into batches"),await this.uploadInBatches(s,o.gistId,p)):await yt.updateGistFiles(s,o.gistId),fe("Uploaded files to shard",{count:a.length,shardId:t})}catch(l){vn(`Failed to update shard: ${t}`,l instanceof Error?l:new Error(String(l)));for(const c of a)vt.unregisterFile(c.url);for(const c of a){const u=r.details.find(d=>d.url===c.url);u&&(u.success=!1,u.error="批量上传失败"),r.uploaded--}}}async uploadInBatches(t,n,r){const i=Object.entries(t);let o={},s=0,a=0;for(const[l,c]of i){const u=c.length;if(u>r){Object.keys(o).length>0&&(fe("Uploading batch",{batch:a+1,fileCount:Object.keys(o).length}),await yt.updateGistFiles(o,n),o={},s=0,a++),fe("Uploading large file",{filename:l,sizeMB:(u/1024/1024).toFixed(2)}),await yt.updateGistFiles({[l]:c},n),a++;continue}s+u>r&&Object.keys(o).length>0&&(fe(`ShardSyncService] Uploading batch ${a+1}: ${Object.keys(o).length} files`),await yt.updateGistFiles(o,n),o={},s=0,a++),o[l]=c,s+=u}Object.keys(o).length>0&&(fe("Uploading final batch",{batch:a+1,fileCount:Object.keys(o).length}),await yt.updateGistFiles(o,n))}async prepareMediaForUpload(t){const{url:n,type:r,source:i,originalUrl:o,mimeType:s}=t;let a=null;if(i==="local"?a=await yn.getCachedBlob(n):i==="external"&&(a=await yn.getCachedBlob(n)),!a||a.size===0)return{success:!1,size:0,error:"无法获取媒体文件"};if(a.size>eO)return{success:!1,size:a.size,error:`文件过大(${K2(a.size)})`};const l=await Ole(a),c={url:n,type:r,source:i,mimeType:s||a.type,size:a.size,base64Data:l,syncedAt:Date.now(),syncedFromDevice:rT(),originalUrl:i==="external"?o:void 0},u=vt.getMasterGistId();if(!u)return{success:!1,size:a.size,error:"未配置主 Gist ID"};const d=await pi.getPassword(),f=JSON.stringify(c,null,2);return{success:!0,content:await Nn.encrypt(f,u,d||void 0),size:a.size}}async getOrCreateShardManifest(t){try{const r=await yt.getGistFileContent(Is.SHARD_MANIFEST,t.gistId);if(r){const i=vt.getMasterGistId();if(i){const o=await pi.getPassword(),s=await Nn.decrypt(r,i,o||void 0);return JSON.parse(s)}return JSON.parse(r)}}catch(r){Pt("Failed to get shard manifest",{shard:t.alias,error:String(r)})}const n=vt.getMasterGistId();if(!n)throw new Error("Master gist ID not configured");return Sle(t.alias,n)}async downloadMedia(t,n){const r={success:!0,uploaded:0,downloaded:0,deleted:0,skipped:0,details:[]};await vt.initialize();for(let o=0;o<t.length;o++){const s=t[o];if(n==null||n(o+1,t.length,s,"downloading"),(await yn.getCacheInfo(s)).isCached){r.skipped++,r.details.push({url:s,action:"skip",success:!0,error:"已缓存"});continue}const l=vt.getFileIndexEntry(s);if(!l){r.details.push({url:s,action:"download",success:!1,error:"文件未同步"});continue}const c=vt.getShard(l.shardId);if(!c){r.details.push({url:s,action:"download",success:!1,error:`分片 ${l.shardId} 不存在`});continue}try{const u=await yt.getGistFileContent(l.filename,c.gistId);if(!u){r.details.push({url:s,action:"download",success:!1,error:"文件不存在"});continue}const d=vt.getMasterGistId();if(!d){r.details.push({url:s,action:"download",success:!1,error:"未配置主 Gist ID"});continue}const f=await pi.getPassword(),p=await Nn.decrypt(u,d,f||void 0),y=JSON.parse(p),v=Rle(y.base64Data,y.mimeType);if(!v||v.size===0){r.details.push({url:s,action:"download",success:!1,error:"文件数据无效"});continue}await yn.cacheToCacheStorageOnly(s,v),r.downloaded++,r.details.push({url:s,action:"download",success:!0,shardId:l.shardId}),fe("Downloaded and cached",{url:s})}catch(u){vn(`Failed to download: ${s}`,u instanceof Error?u:new Error(String(u))),r.details.push({url:s,action:"download",success:!1,error:u instanceof Error?u.message:"下载失败"})}}r.success=r.downloaded>0||r.skipped>0;const i=r.details.filter(o=>!o.success).length;return r.downloaded>0?Jr("分片下载完成",{downloaded:r.downloaded,skipped:r.skipped,failed:i}):i>0&&Pt("分片下载部分失败",{downloaded:r.downloaded,skipped:r.skipped,failed:i}),r}async softDeleteMedia(t){const n={success:!0,uploaded:0,downloaded:0,deleted:0,skipped:0,details:[]};await vt.initialize();const r=vt.getMasterIndex();if(!r)return n.success=!1,n.error="主索引未加载",n;const i=rT();for(const o of t){const s=vt.getFileIndexEntry(o);if(!s){n.skipped++,n.details.push({url:o,action:"skip",success:!0,error:"文件未同步"});continue}const a=JQe(o,s.shardId,s.filename,s.size,i);r.tombstones.push(a),vt.unregisterFile(o),n.deleted++,n.details.push({url:o,action:"delete",success:!0,shardId:s.shardId}),fe("Soft deleted",{url:o})}return n.deleted>0&&await vt.saveMasterIndexToRemote(),n}async restoreMedia(t){await vt.initialize();const n=vt.getMasterIndex();if(!n)return!1;const r=n.tombstones.findIndex(s=>s.url===t);if(r===-1)return Pt("No tombstone found",{url:t}),!1;const i=n.tombstones[r],o=vt.getShard(i.shardId);if(!o)return Pt("Shard not found for restore",{shardId:i.shardId}),!1;try{const s=await yt.getGistFileContent(i.filename,o.gistId);if(!s)return Pt("File not found in shard",{filename:i.filename}),!1;const a=vt.getMasterGistId();if(!a)return Pt("Master gist ID not configured"),!1;const l=await pi.getPassword(),c=await Nn.decrypt(s,a,l||void 0),u=JSON.parse(c);return vt.registerFile(t,i.shardId,i.filename,i.size,u.type),n.tombstones.splice(r,1),await vt.saveMasterIndexToRemote(),fe("Restored",{url:t}),!0}catch(s){return vn(`Failed to restore: ${t}`,s instanceof Error?s:new Error(String(s))),!1}}async cleanupExpiredTombstones(){await vt.initialize();const t=vt.getMasterIndex();if(!t)return 0;const n=t.tombstones.filter(yV);if(n.length===0)return 0;fe("Cleaning up expired tombstones",{count:n.length});const r={};for(const i of n)r[i.shardId]||(r[i.shardId]=[]),r[i.shardId].push(i.filename);for(const[i,o]of Object.entries(r)){const s=vt.getShard(i);if(s)try{await yt.deleteGistFiles(o,s.gistId),fe("Deleted files from shard",{count:o.length,shardId:i})}catch(a){vn(`Failed to delete files from shard: ${i}`,a instanceof Error?a:new Error(String(a)))}}return t.tombstones=t.tombstones.filter(i=>!yV(i)),await vt.saveMasterIndexToRemote(),n.length}async getSyncedUrls(){await vt.initialize();const t=vt.getMasterIndex();return t?new Set(Object.keys(t.fileIndex)):new Set}async getTombstones(){await vt.initialize();const t=vt.getMasterIndex();return t?[...t.tombstones]:[]}async isInTombstones(t){await vt.initialize();const n=vt.getMasterIndex();return n?n.tombstones.some(r=>r.url===t):!1}}const Qu=new Jtt,Qtt=Object.freeze(Object.defineProperty({__proto__:null,shardSyncService:Qu},Symbol.toStringTag,{value:"Module"}));class ent{async initialize(){await vt.initialize()}isConfigured(){return vt.isConfigured()}async listShards(){return await vt.initialize(),vt.getAllShards()}async getShardDetails(t){await vt.initialize();const n=vt.getShard(t);if(!n)return null;let r=null;try{const i=await yt.getGistFileContent(Is.SHARD_MANIFEST,n.gistId);i&&(r=JSON.parse(i))}catch(i){Pt(`ShardManager] Failed to get manifest for shard ${t}:`,i)}return{info:n,manifest:r,fileCount:n.fileCount,totalSize:n.totalSize}}async renameShardAlias(t,n){await vt.initialize();const r=vt.getShard(t);if(!r)throw new Error(`分片 "${t}" 不存在`);if(!this.isValidAlias(n))throw new Error("别名只能包含字母、数字、连字符和下划线");await vt.updateShardAlias(t,n),`${jC.SHARD}${r.order}${n}`;try{const i=await yt.getGistFileContent(Is.SHARD_MANIFEST,r.gistId);if(i){const o=JSON.parse(i);o.shardId=n,o.updatedAt=Date.now(),await yt.updateGistFiles({[Is.SHARD_MANIFEST]:JSON.stringify(o,null,2)},r.gistId)}}catch(i){Pt("ShardManager] Failed to update shard manifest:",i)}await vt.saveMasterIndexToRemote(),fe(`ShardManager] Renamed shard "${t}" to "${n}"`)}isValidAlias(t){return/^[a-zA-Z0-9_-]+$/.test(t)&&t.length>=1&&t.length<=50}async archiveShard(t){if(await vt.initialize(),!vt.getShard(t))throw new Error(`分片 "${t}" 不存在`);vt.archiveShard(t),await vt.saveMasterIndexToRemote(),fe(`ShardManager] Archived shard "${t}"`)}async reactivateShard(t){if(await vt.initialize(),!vt.getShard(t))throw new Error(`分片 "${t}" 不存在`);vt.reactivateShard(t),await vt.saveMasterIndexToRemote(),fe(`ShardManager] Reactivated shard "${t}"`)}async deleteShard(t,n=!1){await vt.initialize();const r=vt.getShard(t);if(!r)throw new Error(`分片 "${t}" 不存在`);if(r.fileCount>0&&!n)throw new Error(`分片 "${t}" 还有 ${r.fileCount} 个文件,请先清空或使用强制删除`);if(r.fileCount>0&&n){const o=vt.getMasterIndex();if(o){const s=Object.entries(o.fileIndex).filter(([a,l])=>l.shardId===t).map(([a])=>a);s.length>0&&await Qu.softDeleteMedia(s)}}try{await yt.deleteGist(r.gistId)}catch(o){vn(`ShardManager] Failed to delete Gist ${r.gistId}:`,o)}const i=vt.getMasterIndex();i&&(delete i.shards[t],QM(i),await vt.saveMasterIndexToRemote()),fe(`ShardManager] Deleted shard "${t}"`)}async getShardStats(){await vt.initialize();const t=vt.getAllShards(),n=vt.getStats();let r=0;for(const o of t){const s=o.fileCount/bs.FILE_LIMIT,a=o.totalSize/bs.SIZE_LIMIT;r+=Math.max(s,a)}const i=t.length>0?r/t.length:0;return{totalShards:n.totalShards,activeShards:n.activeShards,fullShards:n.fullShards,archivedShards:n.archivedShards,totalFiles:n.totalFiles,totalSize:n.totalSize,averageUsage:i,shardDetails:t}}async mergeShards(t,n){await vt.initialize();const r={success:!0,movedFiles:0,errors:[]},i=vt.getShard(n);if(!i)return r.success=!1,r.errors.push(`目标分片 "${n}" 不存在`),r;if(i.status==="archived")return r.success=!1,r.errors.push(`目标分片 "${n}" 已归档`),r;const o=vt.getMasterIndex();if(!o)return r.success=!1,r.errors.push("主索引未加载"),r;const s=[];for(const l of t){if(l===n)continue;if(!vt.getShard(l)){r.errors.push(`源分片 "${l}" 不存在`);continue}for(const[u,d]of Object.entries(o.fileIndex))d.shardId===l&&s.push({url:u,sourceShardId:l,filename:d.filename})}const a=s.length;if(i.fileCount+a>bs.FILE_LIMIT)return r.success=!1,r.errors.push(`目标分片空间不足,需要 ${a} 个位置,只有 ${bs.FILE_LIMIT-i.fileCount} 个`),r;for(const l of s)try{const c=vt.getShard(l.sourceShardId),u=await yt.getGistFileContent(l.filename,c.gistId);if(!u){r.errors.push(`无法读取文件 ${l.filename}`);continue}const d=JSON.parse(u);await yt.updateGistFiles({[l.filename]:u},i.gistId);const f=o.fileIndex[l.url];if(f){const p=vt.getShard(l.sourceShardId);p&&(p.fileCount--,p.totalSize-=f.size),f.shardId=n,i.fileCount++,i.totalSize+=f.size}await yt.deleteGistFiles([l.filename],c.gistId),r.movedFiles++}catch(c){vn(`ShardManager] Failed to move file ${l.url}:`,c),r.errors.push(`移动文件失败: ${l.url}`)}return await vt.saveMasterIndexToRemote(),r.success=r.movedFiles>0,fe(`ShardManager] Merged ${r.movedFiles} files to shard "${n}"`),r}async validateShards(){await vt.initialize();const t=[],n=vt.getAllShards(),r=vt.getMasterIndex();if(!r)return{valid:!1,issues:[{shardId:"",type:"missing_gist",details:"主索引未加载"}]};for(const i of n){try{await yt.getGist(i.gistId)}catch(o){if(o instanceof cl&&o.statusCode===404){t.push({shardId:i.alias,type:"missing_gist",details:`Gist ${xa(i.gistId)} 不存在`});continue}}try{const o=await yt.getGist(i.gistId),s=Object.keys(o.files).filter(l=>l.startsWith("media_")&&l.endsWith(".json")),a=Object.entries(r.fileIndex).filter(([l,c])=>c.shardId===i.alias).map(([l,c])=>c.filename);s.length!==a.length&&t.push({shardId:i.alias,type:"count_mismatch",details:`索引记录 ${a.length} 个文件,实际 ${s.length} 个`});for(const l of a)s.includes(l)||t.push({shardId:i.alias,type:"missing_file",details:`文件 ${l} 在索引中但不在 Gist 中`});for(const l of s)a.includes(l)||t.push({shardId:i.alias,type:"orphan_file",details:`文件 ${l} 在 Gist 中但不在索引中`})}catch(o){vn(`ShardManager] Failed to validate shard ${i.alias}:`,o)}}return{valid:t.length===0,issues:t}}async repairOrphanFiles(){await vt.initialize();const n=(await this.validateShards()).issues.filter(o=>o.type==="orphan_file");if(n.length===0)return 0;let r=0;if(!vt.getMasterIndex())return 0;for(const o of n){const s=vt.getShard(o.shardId);if(!s)continue;const a=o.details.match(/文件 (.+) 在 Gist 中/);if(!a)continue;const l=a[1];try{const c=await yt.getGistFileContent(l,s.gistId);if(!c)continue;const u=JSON.parse(c),d=u.url,f=u.type,p=u.size||0;if(!d)continue;vt.registerFile(d,o.shardId,l,p,f),r++,fe(`ShardManager] Repaired orphan file: ${l} -> ${d}`)}catch(c){vn(`ShardManager] Failed to repair orphan file ${l}:`,c)}}return r>0&&await vt.saveMasterIndexToRemote(),r}async clearLocalCache(){await vt.clearLocalCache(),fe("ShardManager] Cleared local cache")}destroy(){vt.destroy()}}const $V=new ent,iT="github_sync_shard_enabled",tnt="0.5.0";class nnt{constructor(){this.shardingEnabled=!1,this.initialized=!1}async initialize(){this.initialized||(this.shardingEnabled=await er.get(iT)??!1,this.shardingEnabled&&await vt.initialize(),this.initialized=!0,fe("ShardedMediaSyncAdapter] Initialized, sharding enabled:",this.shardingEnabled))}isShardingEnabled(){return this.shardingEnabled}async enableSharding(){this.shardingEnabled=!0,await er.set(iT,!0),await vt.initialize(),fe("ShardedMediaSyncAdapter] Sharding enabled")}async disableSharding(){this.shardingEnabled=!1,await er.set(iT,!1),fe("ShardedMediaSyncAdapter] Sharding disabled")}async setupShardSystem(t){try{fe("ShardedMediaSyncAdapter] Setting up shard system..."),await vt.setMasterGistId(t),await vt.initialize();let n=await vt.loadMasterIndexFromRemote();return n||(n=await vt.initializeMasterIndex(tnt),await yt.updateGistFiles({[Is.MASTER_INDEX]:JSON.stringify(n,null,2)},t),fe("ShardedMediaSyncAdapter] Created new master index")),await this.enableSharding(),{success:!0}}catch(n){return vn("ShardedMediaSyncAdapter] Setup failed:",n),{success:!1,error:n instanceof Error?n.message:"设置失败"}}}async uploadMedia(t,n){if(await this.initialize(),this.shardingEnabled&&vt.isConfigured()){const r=await Qu.uploadMedia(t,n);return this.convertToLegacyResult(r)}else return fe("ShardedMediaSyncAdapter] Sharding not enabled, use mediaSyncService instead"),this.createEmptyResult()}async downloadMedia(t,n){if(await this.initialize(),this.shardingEnabled&&vt.isConfigured()){const r=await Qu.downloadMedia(t,n);return this.convertToLegacyResult(r)}else return fe("ShardedMediaSyncAdapter] Sharding not enabled, use mediaSyncService instead"),this.createEmptyResult()}async getSyncedUrls(){return await this.initialize(),this.shardingEnabled&&vt.isConfigured()?await Qu.getSyncedUrls():new Set}async softDeleteMedia(t){return await this.initialize(),!this.shardingEnabled||!vt.isConfigured()?{success:!1,uploaded:0,downloaded:0,deleted:0,skipped:0,error:"分片系统未启用",details:[]}:await Qu.softDeleteMedia(t)}async restoreMedia(t){return await this.initialize(),!this.shardingEnabled||!vt.isConfigured()?!1:await Qu.restoreMedia(t)}async getShardStats(){if(await this.initialize(),!this.shardingEnabled||!vt.isConfigured())return{enabled:!1};const t=await $V.getShardStats();return{enabled:!0,stats:{totalShards:t.totalShards,activeShards:t.activeShards,fullShards:t.fullShards,totalFiles:t.totalFiles,totalSize:t.totalSize}}}async cleanupExpiredTombstones(){return await this.initialize(),!this.shardingEnabled||!vt.isConfigured()?0:await Qu.cleanupExpiredTombstones()}convertToLegacyResult(t){return{succeeded:t.uploaded+t.downloaded,failed:t.details.filter(n=>!n.success&&n.action!=="skip").length,skipped:t.skipped,results:t.details.map(n=>({success:n.success,url:n.url,error:n.error})),totalSize:0,duration:0}}createEmptyResult(){return{succeeded:0,failed:0,skipped:0,results:[],totalSize:0,duration:0}}destroy(){$V.destroy(),this.initialized=!1}}const rnt=new nnt,Qle=Object.freeze(Object.defineProperty({__proto__:null,shardedMediaSyncAdapter:rnt},Symbol.toStringTag,{value:"Module"})),ece=b.createContext(null),N0={success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0,error:"GitHub Sync context is unavailable"},int={isConnected:!1,isConfigured:!1,syncStatus:"not_configured",isSyncing:!1,lastSyncTime:null,userInfo:null,error:"GitHub Sync context is unavailable",setToken:async()=>!1,clearToken:()=>{},sync:async()=>N0,pullFromRemote:async()=>N0,pushToRemote:async()=>N0,gistUrl:null,listGists:async()=>[],switchGist:async()=>N0,deleteGist:async()=>{},createNewGist:async()=>N0,config:null,updateConfig:async()=>{}};async function a2(e){if(fe("handleBoardSwitchAfterSync START",{success:e.success,downloaded:e.downloaded,uploaded:e.uploaded,remoteCurrentBoardId:e.remoteCurrentBoardId}),!e.success){fe("handleBoardSwitchAfterSync END (not successful)");return}try{const n=gs.getState().currentBoardId,r=gs.getAllBoardMetadata();fe("Current workspace state",{currentBoardId:n,totalBoards:r.length});let i=e.remoteCurrentBoardId;if(fe("Initial targetBoardId",{targetBoardId:i}),i||(r.length>0?(i=r[0].id,fe("Using first board as target",{targetBoardId:i,name:r[0].name})):fe("No boards available")),fe("Final targetBoardId",{targetBoardId:i}),!i){fe("handleBoardSwitchAfterSync END (no target)");return}const o=r.some(a=>a.id===i);if(fe("Target board exists in metadata",{targetExists:o}),o||Pt("Target board not found in available boards",{targetBoardId:i,availableIds:r.map(a=>a.id)}),!n){fe("DECISION: No current board, switching to target",{targetBoardId:i}),await gs.switchBoard(i),fe("handleBoardSwitchAfterSync END (switched from null)");return}if(i===n){fe("DECISION: Target board is current board, reloading");try{await gs.reloadBoard(i),fe("Board data reloaded successfully")}catch(a){vn("Failed to reload board data",a instanceof Error?a:new Error(String(a)))}fe("handleBoardSwitchAfterSync END (same board, reloaded)");return}const s=await gs.isDefaultEmptyBoard(n);fe("isCurrentDefaultEmpty",{isCurrentDefaultEmpty:s}),s?(fe("DECISION: Current board is default empty, auto-switching",{targetBoardId:i}),await gs.switchBoard(i),await gs.deleteBoard(n),fe("handleBoardSwitchAfterSync END (replaced default)")):(fe("DECISION: Current board is not default empty, keeping current"),fe("handleBoardSwitchAfterSync END (keep current)"))}catch(t){vn("handleBoardSwitchAfterSync failed",t instanceof Error?t:new Error(String(t)))}}function vpt({children:e}){const[t,n]=b.useState(!1),[r,i]=b.useState(!1),[o,s]=b.useState("not_configured"),[a,l]=b.useState(!1),[c,u]=b.useState(null),[d,f]=b.useState(null),[p,y]=b.useState(null),[v,w]=b.useState(null),[C,x]=b.useState(null),E=b.useRef(!1);b.useEffect(()=>{if(E.current)return;E.current=!0,fe("GitHubSyncProvider initializing"),(async()=>{const U=ai.hasToken();if(i(U),U){const{isValid:Y,userInfo:K}=await ai.validateAndGetUserInfo();if(n(Y),Y){f(K);const Z=await Kn.getConfig();if(w(Z),u(Z.lastSyncTime),x(Kn.getGistUrl()),Z.gistId){const oe=()=>{"requestIdleCallback"in window?window.requestIdleCallback(async()=>{await J()},{timeout:3e3}):setTimeout(async()=>{await J()},1e3)},J=async()=>{try{qc.refreshSyncStatus().catch(()=>{}),Tr("Auto-syncing from remote on page load (deferred)");const ae=await Kn.pullFromRemote();if(ae.success){Jr("Auto-sync from remote successful",ae.downloaded);const Q=await Kn.getConfig();u(Q.lastSyncTime),await a2(ae)}else Pt("Auto-sync from remote failed",{error:ae.error})}catch(ae){vn("Auto-sync from remote error",ae instanceof Error?ae:new Error(String(ae)))}};oe()}}else y("Token 无效,请重新配置")}s(Kn.getSyncStatus())})();const z=(U,Y)=>{s(U),l(U==="syncing"),U==="error"&&Y?y(Y):U==="synced"&&y(null)};Kn.addStatusListener(z);const N=()=>{document.visibilityState==="hidden"&&ai.hasToken()&&Kn.hasPendingChanges()&&(fe("Page hidden, triggering sync"),Kn.sync().catch(()=>{}))},B=U=>{if(Kn.getSyncStatus()==="syncing")return U.preventDefault(),U.returnValue="同步正在进行中,确定要离开吗?",U.returnValue;ai.hasToken()&&Kn.hasPendingChanges()&&(fe("Page unloading, triggering sync"),Kn.sync().catch(()=>{}))};document.addEventListener("visibilitychange",N),window.addEventListener("beforeunload",B),fe("Setting up workspace event subscription");const $=gs.observeEvents().subscribe({next:U=>{var K;const Y=["boardCreated","boardUpdated","boardDeleted","folderCreated","folderUpdated","folderDeleted"];if(ai.hasToken()&&Y.includes(U.type)&&(fe("Workspace changed, marking dirty",{eventType:U.type}),Kn.markDirty(),U.type==="boardDeleted")){const Z=(K=U.payload)==null?void 0:K.id;Z&&typeof Z=="string"?(fe("Syncing board deletion to remote",{boardId:Z}),Kn.recordLocalDeletion(Z).then(()=>Kn.syncBoardDeletion(Z)).then(oe=>{oe.success?Jr("Board moved to remote recycle bin",{boardId:Z}):Pt("Failed to sync deletion to remote",{boardId:Z,error:oe.error})}).catch(oe=>{vn("Failed to sync board deletion",oe instanceof Error?oe:new Error(String(oe)),{boardId:Z})})):Pt("boardDeleted event has invalid payload",{payload:U.payload})}},error:U=>{vn("Workspace event subscription error",U instanceof Error?U:new Error(String(U)))},complete:()=>{fe("Workspace event subscription completed")}});return fe("Workspace event subscription established"),()=>{Kn.removeStatusListener(z),document.removeEventListener("visibilitychange",N),window.removeEventListener("beforeunload",B),$.unsubscribe()}},[]);const _=b.useCallback(async j=>{try{if(y(null),!ai.isValidTokenFormat(j))return y("Token 格式无效"),!1;const{isValid:z,userInfo:N}=await ai.validateAndGetUserInfo(j);if(!z)return y("Token 无效或已过期"),!1;if(await ai.saveToken(j),!await ai.hasGistScope())return y("Token 缺少 gist 权限,请重新创建"),ai.clearToken(),!1;f(N);try{Tr("Auto-connecting and syncing..."),await Kn.saveConfig({gistId:null});const O=await Kn.sync(),$=await Kn.getConfig();w($),u($.lastSyncTime),x(Kn.getGistUrl()),O.success?(Jr("Auto-connect sync successful",{downloaded:O.downloaded,gistId:$.gistId?xa($.gistId):null}),await a2(O)):Pt("Auto-connect sync failed",{error:O.error})}catch(O){vn("Failed to auto-connect gist",O instanceof Error?O:new Error(String(O)))}return i(!0),n(!0),!0}catch(z){const N=z instanceof Error?z.message:"设置 Token 失败";return y(N),!1}},[]),I=b.useCallback(()=>{ai.clearToken(),Kn.disconnect(),i(!1),n(!1),f(null),s("not_configured"),u(null),x(null),w(null),y(null)},[]),D=b.useCallback(async()=>{if(a)return{success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0};y(null);const j=await Kn.sync();if(j.success){const z=await Kn.getConfig();if(u(z.lastSyncTime),x(Kn.getGistUrl()),w(z),j.downloaded.boards>0){const N=gs.getState().currentBoardId;if(N)try{await gs.reloadBoard(N)}catch(B){Pt("Failed to reload current board",{error:String(B)})}}await a2(j)}else j.error&&j.error!=="同步正在进行中"&&y(j.error);return j},[a]),P=b.useCallback(async()=>{if(a)return{success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0};y(null);const j=await Kn.pullFromRemote();if(j.success){const z=await Kn.getConfig();u(z.lastSyncTime),x(Kn.getGistUrl()),w(z),await a2(j)}else j.error&&j.error!=="同步正在进行中"&&y(j.error);return j},[a]),k=b.useCallback(async()=>{if(a)return{success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0};y(null);const j=await Kn.pushToRemote();if(j.success){const z=await Kn.getConfig();u(z.lastSyncTime),x(Kn.getGistUrl()),w(z)}else j.error&&j.error!=="同步正在进行中"&&y(j.error);return j},[a]),R=b.useCallback(async j=>{await Kn.saveConfig(j);const z=await Kn.getConfig();w(z)},[]),T=b.useCallback(async()=>t?Kn.listSyncGists():[],[t]),M=b.useCallback(async j=>{y(null);const z=await Kn.switchToGist(j);if(z.success){const N=await Kn.getConfig();u(N.lastSyncTime),x(Kn.getGistUrl()),w(N)}else z.error&&z.error!=="同步正在进行中"&&y(z.error);return z},[]),F=b.useCallback(async j=>{await Kn.deleteGist(j);const z=await Kn.getConfig();z.gistId||(x(null),w(z),s("not_configured"))},[]),V=b.useCallback(async()=>{y(null);const j=await Kn.createNewGist();if(j.success){const z=await Kn.getConfig();u(z.lastSyncTime),x(Kn.getGistUrl()),w(z)}else j.error&&j.error!=="同步正在进行中"&&y(j.error);return j},[]),H={isConnected:t,isConfigured:r,syncStatus:o,isSyncing:a,lastSyncTime:c,userInfo:d,error:p,setToken:_,clearToken:I,sync:D,pullFromRemote:P,pushToRemote:k,gistUrl:C,listGists:T,switchGist:M,deleteGist:F,createNewGist:V,config:v,updateConfig:R};return g.jsx(ece.Provider,{value:H,children:e})}function ont(){return b.useContext(ece)??int}async function tce(){const e={id:CQe,name:"音乐播放器",description:"从素材库选择音频并后台播放,可与画布播放控件联动",icon:"🎵",category:"utilities",component:"music-player",defaultWidth:420,defaultHeight:640},{toolWindowService:t}=await xn(async()=>{const{toolWindowService:n}=await import("./tool-windows-CSaRGLIT.js").then(r=>r.b0);return{toolWindowService:n}},__vite__mapDeps([0]),import.meta.url);return t.openTool(e,{autoPin:!0}),!0}async function nce(e){var t,n,r,i,o,s;return await tce(),e.queue&&e.queue.length>0&&(e.queue.every(a=>Tv(a))?n2.setReadingQueue(e.queue,{queueId:(t=e.queueTab)==null?void 0:t.queueId,queueName:(n=e.queueTab)==null?void 0:n.queueName}):n2.setQueue(e.queue,{queueSource:e.playlist?"playlist":"canvas",playlistId:(r=e.playlist)==null?void 0:r.playlistId,playlistName:(i=e.playlist)==null?void 0:i.playlistName,queueId:(o=e.queueTab)==null?void 0:o.queueId,queueName:(s=e.queueTab)==null?void 0:s.queueName})),Tv(e.source)?n2.toggleReadingPlayback(e.source):await n2.togglePlayback(e.source),!0}const wpt=Object.freeze(Object.defineProperty({__proto__:null,openMusicPlayerTool:tce,openMusicPlayerToolAndPlay:nce},Symbol.toStringTag,{value:"Module"}));function fI(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}function rce(e){const t=new Uint8Array(2+e.length*2);t[0]=255,t[1]=254;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n),i=2+n*2;t[i]=r&255,t[i+1]=r>>8&255}return t}function Wg(...e){const t=e.reduce((i,o)=>i+o.length,0),n=new Uint8Array(t);let r=0;for(const i of e)n.set(i,r),r+=i.length;return n}function snt(e){return new Uint8Array([e>>21&127,e>>14&127,e>>7&127,e&127])}function ant(e){return(e[0]??0)<<21|(e[1]??0)<<14|(e[2]??0)<<7|(e[3]??0)}function uN(e){const t=new Uint8Array(10);t.set(fI(e.id.slice(0,4)),0);const n=e.data.length;return t[4]=n>>24&255,t[5]=n>>16&255,t[6]=n>>8&255,t[7]=n&255,Wg(t,e.data)}function j0(e,t){return t!=null&&t.trim()?uN({id:e,data:Wg(new Uint8Array([1]),rce(t.trim()))}):null}function lnt(e){return e!=null&&e.trim()?uN({id:"COMM",data:Wg(new Uint8Array([1]),fI("eng"),new Uint8Array([255,254,0,0]),rce(e.trim()))}):null}function cnt(e){if(e.length<10||e[0]!==73||e[1]!==68||e[2]!==51)return e;const t=ant(e.slice(6,10)),n=e[5]&16?10:0,r=10+t+n;return r>=e.length?e:e.slice(r)}async function unt(e){if(!e)return null;try{const t=await fetch(e,{referrerPolicy:"no-referrer"});if(!t.ok)return null;const n=await t.blob(),r=await n.arrayBuffer();return{bytes:new Uint8Array(r),mimeType:n.type||"image/jpeg"}}catch{return null}}async function dnt(e){const t=await unt(e);return t?uN({id:"APIC",data:Wg(new Uint8Array([0]),fI(t.mimeType),new Uint8Array([0,3,0]),t.bytes)}):null}function fnt(e,t){return e.type==="audio/mpeg"||e.type==="audio/mp3"||/\.mp3(?:$|[?#])/i.test(t)}async function ice(e,t,n){var p,y,v,w,C,x;if(!t||!fnt(e,n))return e;const r=(p=t.title)==null?void 0:p.trim(),i=(y=t.prompt)==null?void 0:y.trim(),o=(v=t.tags)==null?void 0:v.trim(),s=((w=t.artist)==null?void 0:w.trim())||"Aitu",a=((C=t.album)==null?void 0:C.trim())||"Aitu Generated",l=((x=t.year)==null?void 0:x.trim())||String(new Date().getFullYear()),c=(await Promise.all([Promise.resolve(j0("TIT2",r)),Promise.resolve(j0("TPE1",s)),Promise.resolve(j0("TALB",a)),Promise.resolve(j0("TCON",o)),Promise.resolve(j0("TYER",l)),Promise.resolve(lnt(i)),dnt(t.coverUrl)])).filter(E=>E!==null);if(c.length===0)return e;const u=cnt(new Uint8Array(await e.arrayBuffer())),d=Wg(...c),f=Wg(fI("ID3"),new Uint8Array([3,0,0]),snt(d.length));return new Blob([f,d,u],{type:e.type||"audio/mpeg"})}function dN(e={}){return{openedCount:0,downloadedCount:0,failedCount:0,...e}}function hnt(e){if(typeof window>"u"||typeof window.location>"u")return/^https?:\/\//i.test(e);try{return new URL(e,window.location.href).origin!==window.location.origin}catch{return!1}}function pnt(e){if(e instanceof TypeError)return!0;const t=e instanceof Error?e.message:String(e);return/Failed to fetch|Load failed|NetworkError/i.test(t)}function mnt(e,t){return hnt(e)&&pnt(t)}function gnt(e){return cK(e),dN({openedCount:1})}async function zV(e,t){try{return await t(),dN({downloadedCount:1})}catch(n){if(mnt(e,n))return gnt(e);throw n}}function fN(e,t,n,r){return`${MG(e||"")||t}${r||""}.${n}`}function ynt(e){return Math.min(100,Math.max(0,Math.round(e)))}function km(e,t){e===void 0||t===void 0||e(ynt(t))}function oce(e){return{title:e.title,prompt:e.prompt,tags:e.tags,coverUrl:e.coverUrl,artist:e.artist||"Aitu",album:e.album||"Aitu Generated"}}function sce(e){return e==="image"?"png":e==="video"?"mp4":"mp3"}function ace(e,t,n){if(e&&/^[a-z0-9]+$/i.test(e))return e.toLowerCase();const r=e?lo(e):"bin";if(r!=="bin")return r;const i=n?lo(n):"bin";return i!=="bin"?i:t}function vnt(e,t){const n=t.get(e)||0;if(t.set(e,n+1),n===0)return e;const r=e.lastIndexOf(".");return r<=0?`${e}_${n}`:`${e.slice(0,r)}_${n}${e.slice(r)}`}function hI(e){const t=e.type===ln.IMAGE?"image":e.type===ln.VIDEO?"video":"audio",n=ace(e.name,sce(t),e.url);return{url:e.url,type:t,filename:fN(e.name,t,n),audioMetadata:t==="audio"?oce({title:e.name,prompt:e.prompt,coverUrl:e.thumbnail,artist:e.modelName}):void 0}}function lce(e){return e.map(hI)}function wnt(e){var r,i,o,s;if(!((r=e.result)!=null&&r.url)&&!((o=(i=e.result)==null?void 0:i.urls)!=null&&o.length))return[];const t=e.type===Qt.IMAGE?"image":e.type===Qt.VIDEO?"video":"audio",n=(s=e.result.urls)!=null&&s.length?e.result.urls:[e.result.url];return n.map((a,l)=>{var f,p,y,v,w,C;const c=(p=(f=e.result)==null?void 0:f.clips)==null?void 0:p[l],u=(c==null?void 0:c.title)||((y=e.result)==null?void 0:y.title)||e.params.title||e.params.prompt,d=ace((v=e.result)==null?void 0:v.format,sce(t),a);return{url:a,type:t,filename:fN(u,t,d,n.length>1?`-${l+1}`:void 0),audioMetadata:e.type===Qt.AUDIO?oce({title:(c==null?void 0:c.title)||((w=e.result)==null?void 0:w.title)||e.params.title,prompt:e.params.prompt,tags:typeof e.params.tags=="string"?e.params.tags:void 0,coverUrl:(c==null?void 0:c.imageLargeUrl)||(c==null?void 0:c.imageUrl)||((C=e.result)==null?void 0:C.previewImageUrl),artist:e.params.model||e.params.mv}):void 0}})}async function cce(e,t,n){if(e.length===0)throw new Error("No files to download");const{default:r}=await xn(async()=>{const{default:d}=await import("./office-data-DMEex_0S.js").then(f=>f.j);return{default:d}},[],import.meta.url),i=new r,o=new Date().toISOString().slice(0,19).replace(/[T:]/g,"-"),s=t||`aitu_download_${o}.zip`,a=new Map;let l=0,c=0;if(km(n,0),await dK(e,async(d,f)=>{try{const p=d.type==="image"?zn(d.url):d.url,y=await fetch(p,{referrerPolicy:"no-referrer"});if(!y.ok){console.warn(`Failed to fetch ${p}: ${y.status}`);return}const v=await y.blob(),w=d.type==="audio"?await ice(v,d.audioMetadata,p):v,C=lo(p,w.type),x=d.type==="image"?"image":d.type==="video"?"video":"audio",E=vnt(d.filename||`${x}_${f+1}.${C}`,a);i.file(E,w),c+=1}catch(p){console.error("Failed to add file to zip:",p)}finally{l+=1,km(n,e.length>0?l/e.length*50:50)}},3),c===0)throw new Error("No files available to download");const u=await i.generateAsync({type:"blob"},d=>{km(n,50+d.percent/2)});return YC(u,s),km(n,100),dN({downloadedCount:c,failedCount:e.length-c})}async function FC(e,t,n){if(e.length===0)throw new Error("No files to download");if(e.length===1){const r=e[0],i=r.type==="image"?zn(r.url):r.url;if(r.type==="audio"){const l=await zV(i,async()=>{const c=await fetch(i,{referrerPolicy:"no-referrer"});if(!c.ok)throw new Error(`Failed to fetch ${i}: ${c.status}`);const u=await c.blob(),d=await ice(u,r.audioMetadata,i),f=lo(i,d.type)||"mp3",p=r.filename||`${r.type}_download.${f}`;YC(d,p)});return km(n,100),l}const o=lo(i)||(r.type==="image"?"png":r.type==="video"?"mp4":"mp3"),s=r.filename||`${r.type}_download.${o}`,a=await zV(i,async()=>uK(i,s));return km(n,100),a}else return cce(e,t,n)}const bnt=Object.freeze(Object.defineProperty({__proto__:null,buildAssetDownloadItem:hI,buildAssetDownloadItems:lce,buildDownloadFilename:fN,buildTaskDownloadItems:wnt,downloadAsZip:cce,smartDownload:FC},Symbol.toStringTag,{value:"Module"})),xnt=150,uce="media-library-view-mode",iO="media-library-grid-size";function UV(e,t="image/png"){const n=e.trim();if(!n||n.startsWith("data:")||n.startsWith("blob:")||n.startsWith("http://")||n.startsWith("https://")||n.startsWith("/")||n.startsWith("./")||n.startsWith("../"))return n||e;const r=n.replace(/\s+/g,"");return!/^[A-Za-z0-9+/=]+$/.test(r)||r.length<32?n:`data:${t};base64,${r}`}const HV=()=>{try{const e=localStorage.getItem(uce);if(e==="grid"||e==="compact"||e==="list")return e}catch{}return"grid"},Snt=()=>{try{const e=localStorage.getItem(iO);if(e){const t=parseInt(e,10);if(!isNaN(t)&&t>=80&&t<=300)return t}}catch{}return 180},Cnt=[{value:"ALL",label:"全部",icon:cI},{value:ln.IMAGE,label:"图片",icon:NC},{value:ln.VIDEO,label:"视频",icon:cg},{value:ln.AUDIO,label:"音频",icon:zv}],Ent=[{value:Lr.LOCAL,label:"本地",tooltip:"本地上传",icon:OT,countKey:"local"},{value:Lr.AI_GENERATED,label:"AI",tooltip:"AI生成",icon:Hv,countKey:"ai"}],_nt=[{value:_s.CHARACTER,label:"主体",tooltip:"主体素材",icon:VCe,countKey:"character"}],Int=[{id:"DATE",label:"时间",options:{asc:"DATE_ASC",desc:"DATE_DESC"},icons:{asc:h2e,desc:A2e},default:"DATE_DESC"},{id:"NAME",label:"名称",options:{asc:"NAME_ASC",desc:"NAME_DESC"},icons:{asc:r2e,desc:Qxe},default:"NAME_ASC"},{id:"SIZE",label:"大小",options:{asc:"SIZE_ASC",desc:"SIZE_DESC"},icons:{asc:o2e,desc:Zxe},default:"SIZE_DESC"}];function WV(){return{scope:null,selectedIds:new Set,deselectedIds:new Set}}function oT(e,t,n){var l;if(!t)return!1;const r=!t.activeType||e.type===t.activeType,i=!t.activeSource||e.source===t.activeSource,o=!t.activeCategory||(e.category||_s.GENERAL)===t.activeCategory,s=Cae(e,t.searchQuery);let a=!0;return t.playlistId&&(t.playlistId===hl?a=e.type===ln.AUDIO:a=((l=n.get(t.playlistId))==null?void 0:l.has(e.id))??!1),r&&i&&o&&s&&a}function Ant({selectedAssetId:e,onSelectAsset:t,onDoubleClick:n,onFileUpload:r,onUploadClick:i,storageStatus:o,onSelectionChange:s}){const{assets:a,filters:l,loading:c,setFilters:u,removeAssets:d,syncedUrls:f,loadSyncedUrls:p}=sN(),{playlists:y,favoriteAssetIds:v,playlistItems:w,createPlaylist:C,renamePlaylist:x,deletePlaylist:E,addAssetToPlaylist:_,removeAssetFromPlaylist:I,toggleFavorite:D,isFavorite:P,getPlaylistAssetIds:k}=SQe(),{board:R}=cy(),{isMobile:T}=ule(),[M,F]=b.useState(!1),[V,H]=b.useState(!1),[j,z]=b.useState(()=>WV()),[N,B]=b.useState(Snt),O=b.useRef(null),[$,U]=b.useState(!1),[Y,K]=b.useState([]),[Z,oe]=b.useState(0),J=b.useRef(null),[ae,Q]=b.useState(!1),[se,ie]=b.useState(""),[ce,ge]=b.useState(!1),[Se,Ae]=b.useState(0),{isConfigured:Le}=ont(),[it,Te]=b.useState(!1),[Re,ht]=b.useState(0),[Ze,Ge]=b.useState(null),{contextMenu:pt,open:at,close:ct}=H3(),[nt,It]=b.useState(null),[Lt,dt]=b.useState(""),{confirm:wt,confirmDialog:mt}=TQe();b.useEffect(()=>{Le&&p()},[Le,p]),b.useEffect(()=>{l.activeType&&l.activeType!==ln.AUDIO&&Ze&&Ge(null)},[l.activeType,Ze]),b.useEffect(()=>{Ze&&Ze!==hl&&!y.some(G=>G.id===Ze)&&Ge(null)},[y,Ze]),b.useEffect(()=>{if(!Le)return;let G=!0;const te=async()=>{G&&await p()};return xn(async()=>{const{mediaSyncService:re}=await Promise.resolve().then(()=>tO);return{mediaSyncService:re}},void 0,import.meta.url).then(({mediaSyncService:re})=>{re.addSyncCompletedListener(te)}),()=>{G=!1,xn(async()=>{const{mediaSyncService:re}=await Promise.resolve().then(()=>tO);return{mediaSyncService:re}},void 0,import.meta.url).then(({mediaSyncService:re})=>{re.removeSyncCompletedListener(te)})}},[Le,p]);const Bt=b.useMemo(()=>({all:a.length,image:a.filter(G=>G.type===ln.IMAGE).length,video:a.filter(G=>G.type===ln.VIDEO).length,audio:a.filter(G=>G.type===ln.AUDIO).length,character:a.filter(G=>G.category===_s.CHARACTER).length,local:a.filter(G=>G.source===Lr.LOCAL).length,ai:a.filter(G=>G.source===Lr.AI_GENERATED).length}),[a]),He=b.useMemo(()=>e&&a.find(G=>G.id===e)||null,[a,e]);b.useEffect(()=>{localStorage.setItem(iO,N.toString())},[N]);const[we,ue]=b.useState(HV),[_e,xe]=b.useState(HV),[Fe,lt]=b.useState(!1),[Ht,At]=b.useTransition(),le=b.useRef(null),me=b.useMemo(()=>{const G=KXe(a,l);if(!Ze)return G;const te=new Set(Ze===hl?a.filter(de=>de.type===ln.AUDIO).map(de=>de.id):k(Ze)),re=G.assets.filter(de=>te.has(de.id));return{assets:re,count:re.length,isEmpty:re.length===0}},[a,l,Ze,k]),ke=b.useMemo(()=>new Set(Ze&&Ze!==hl?k(Ze):[]),[k,Ze]),Oe=b.useMemo(()=>{const G=new Map;return Object.keys(w).forEach(te=>{const re=w[te]??[];G.set(te,new Set(re.map(de=>de.assetId).filter(de=>typeof de=="string"&&de.length>0)))}),G},[w]),De=b.useCallback(async G=>{await FC([hI(G)])},[]),Ye=b.useMemo(()=>[{key:"open-player",label:"在音乐播放器中打开",icon:g.jsx(zv,{size:14}),onSelect:async G=>{const te=me.assets.filter(de=>de.type===ln.AUDIO).map(de=>({elementId:`asset:${de.id}`,audioUrl:de.url,title:de.name,duration:de.duration,previewImageUrl:de.thumbnail,clipId:de.clipId,providerTaskId:de.providerTaskId})),re=Ze&&y.find(de=>de.id===Ze)||null;await nce({source:{elementId:`asset:${G.id}`,audioUrl:G.url,title:G.name,duration:G.duration,previewImageUrl:G.thumbnail,clipId:G.clipId,providerTaskId:G.providerTaskId},queue:te,playlist:re&&Ze!==hl?{playlistId:re.id,playlistName:re.name}:void 0})}},{key:"favorite",label:G=>v.has(G.id)?"取消收藏":"加入收藏",icon:g.jsx(vS,{size:14}),onSelect:G=>{G.type===ln.AUDIO&&D(G.id)}},{key:"playlist-actions",type:"submenu",label:"添加到播放列表",icon:g.jsx(ov,{size:14}),children:G=>y.map(te=>{const re=(w[te.id]||[]).some(de=>de.assetId===G.id);return{key:`playlist-${te.id}`,label:re?`已在 ${te.name}`:`添加到 ${te.name}`,icon:g.jsx(ov,{size:14}),disabled:re,onSelect:()=>{_(G.id,te.id)}}})},{key:"remove-current",label:"从当前播放列表移除",icon:g.jsx(O8,{size:14}),danger:!0,disabled:G=>!Ze||Ze===hl||!ke.has(G.id),onSelect:G=>{Ze&&Ze!==hl&&I(G.id,Ze)}},{key:"create-playlist",label:"新建播放列表并添加",icon:g.jsx(ic,{size:14}),onSelect:G=>{dt(""),It({mode:"create-and-add",targetAssetId:G.id}),ct()}}],[_,ct,ke,v,me.assets,y,w,I,Ze,D]),Rt=b.useCallback(G=>{if(G===we)return;le.current&&clearTimeout(le.current),xe(G);let te=N;G==="grid"?te=180:G==="compact"&&(te=80),B(te),localStorage.setItem(iO,te.toString()),lt(!0);try{localStorage.setItem(uce,G)}catch{}le.current=setTimeout(()=>{At(()=>{ue(G),setTimeout(()=>{lt(!1)},100)})},xnt)},[N,we]);b.useEffect(()=>()=>{le.current&&clearTimeout(le.current)},[]);const St=b.useCallback(()=>({activeType:l.activeType&&l.activeType!=="ALL"?l.activeType:void 0,activeSource:l.activeSource&&l.activeSource!=="ALL"?l.activeSource:void 0,activeCategory:l.activeCategory&&l.activeCategory!=="ALL"?l.activeCategory:void 0,searchQuery:l.searchQuery.trim().toLowerCase(),playlistId:Ze||null}),[l.activeCategory,l.activeSource,l.activeType,l.searchQuery,Ze]),Ct=b.useCallback(G=>j.selectedIds.has(G.id)?!0:oT(G,j.scope,Oe)&&!j.deselectedIds.has(G.id),[Oe,j]),Dt=b.useMemo(()=>me.assets.filter(Ct),[me.assets,Ct]),Gt=Dt.length;b.useEffect(()=>{s==null||s(Dt,V)},[Dt,V,s]);const Ft=b.useMemo(()=>me.assets.length===0?!1:Gt===me.assets.length,[me.assets.length,Gt]),Ne=b.useMemo(()=>me.assets.length===0?!1:Gt>0&&Gt<me.assets.length,[me.assets.length,Gt]),gt=b.useCallback(()=>{z(WV()),O.current=null},[]),nn=b.useCallback(G=>{z({scope:null,selectedIds:new Set(G),deselectedIds:new Set}),O.current=G.length>0?G[G.length-1]:null,G.length>0&&t(G[G.length-1])},[t]),Zt=b.useCallback(G=>{G.preventDefault(),G.stopPropagation(),F(!0)},[]),Fn=b.useCallback(G=>{G.preventDefault(),G.stopPropagation(),F(!1)},[]),We=b.useCallback(G=>{G.preventDefault(),G.stopPropagation(),F(!1);const te=G.dataTransfer.files;te&&te.length>0&&r&&r(te)},[r]),rn=b.useCallback(()=>{H(G=>!G),gt()},[gt]),Rn=b.useCallback(()=>{Ft?gt():z({scope:St(),selectedIds:new Set,deselectedIds:new Set})},[gt,St,Ft]),tr=b.useCallback((G,te)=>{const re=me.assets.find(de=>de.id===G);if(re){if(te!=null&&te.shiftKey&&O.current&&O.current!==G){const de=me.assets.findIndex(pe=>pe.id===O.current),ye=me.assets.findIndex(pe=>pe.id===G);if(de!==-1&&ye!==-1){const pe=Math.min(de,ye),Me=Math.max(de,ye),Ve=me.assets.slice(pe,Me+1);z(Xe=>{const tt=new Set(Xe.selectedIds),ft=new Set(Xe.deselectedIds);return Ve.forEach(qe=>{oT(qe,Xe.scope,Oe)?ft.delete(qe.id):tt.add(qe.id)}),{...Xe,selectedIds:tt,deselectedIds:ft}}),t(G);return}}z(de=>{const ye=new Set(de.selectedIds),pe=new Set(de.deselectedIds),Me=oT(re,de.scope,Oe);return ye.has(G)||Me&&!pe.has(G)?ye.has(G)?ye.delete(G):Me&&pe.add(G):Me?pe.delete(G):ye.add(G),{...de,selectedIds:ye,deselectedIds:pe}}),O.current=G,t(G)}},[me.assets,t,Oe]),dr=b.useCallback(G=>{nn(G)},[nn]),Yn=b.useCallback(async()=>{const G=Dt.map(te=>te.id);if(G.length!==0)try{if(R){const te=Dt.filter(de=>Av(de.url)),re=G.filter(de=>!te.some(ye=>ye.id===de));for(const de of te)nae(R,de.dedupeUrls||[de.url]);if(re.length>0){const de=Dt.flatMap(ye=>Av(ye.url)?[]:ye.dedupeAssetIds||[ye.id]);eae(R,de)}}await d(G),gt(),H(!1)}catch(te){console.error("[MediaLibraryGrid] Batch delete failed:",te)}},[R,gt,Dt,d]),pr=b.useMemo(()=>{if(!R||Dt.length===0)return{hasCacheAssets:!1,affectedCount:0};let G=0;const te=Dt.filter(re=>Av(re.url));for(const re of te)G+=tae(R,re.dedupeUrls||[re.url]);return{hasCacheAssets:te.length>0,affectedCount:G}},[R,Dt]),gr=b.useCallback(async()=>{if(Gt===0)return;await wt({title:"确认批量删除",confirmText:"删除",cancelText:"取消",danger:!0,children:g.jsxs(g.Fragment,{children:[g.jsxs("p",{children:["确定要删除选中的 ",Gt," 个素材吗?"]}),pr.hasCacheAssets&&pr.affectedCount>0?g.jsxs("p",{style:{marginTop:"8px",color:"var(--td-error-color)"},children:[g.jsx("span",{role:"img","aria-label":"注意",children:"⚠️"})," ","画布中有 ",g.jsx("strong",{children:pr.affectedCount})," ","个元素正在使用这些素材,删除后将被一并移除!"]}):null]})})&&await Yn()},[pr,wt,Gt,Yn]),Ar=b.useCallback(async G=>{await wt({title:"确认删除播放列表",description:`确定要删除播放列表「${G.name}」吗?删除后列表内关联关系将被移除,此操作不可撤销。`,confirmText:"删除",cancelText:"取消",danger:!0})&&await E(G.id)},[wt,E]),Oi=b.useCallback(async()=>{if(!(Dt.length===0||ce)){ge(!0),Ae(0);try{await FC(lce(Dt),`素材_${new Date().toISOString().slice(0,10)}.zip`,Ae)}catch(G){console.error("[MediaLibraryGrid] Download failed:",G)}finally{ge(!1),Ae(0)}}},[Dt,ce]),Ur=b.useCallback(async()=>{if(Dt.length===0||it)return;const G=[];if(Dt.filter(te=>te.source===Lr.AI_GENERATED).forEach(te=>{qc.getUrlSyncStatus(te.url)!=="synced"&&G.push(te.url)}),Dt.filter(te=>te.source===Lr.LOCAL&&te.url.startsWith("/__aitu_cache__/")).forEach(te=>{qc.getUrlSyncStatus(te.url)!=="synced"&&G.push(te.url)}),G.length!==0){Te(!0),ht(0);try{const te=await qc.syncSelectedMedia(G,(re,de,ye,pe)=>{ht(Math.round(re/de*100))});ht(100),te.succeeded>0&&await p()}catch(te){console.error("[MediaLibraryGrid] Batch sync failed:",te)}finally{Te(!1),ht(0)}}},[Dt,it,p]),ho=b.useMemo(()=>{const G=Dt.filter(re=>re.source!==Lr.AI_GENERATED?!1:qc.getUrlSyncStatus(re.url)!=="synced").length,te=Dt.filter(re=>re.source!==Lr.LOCAL||!re.url.startsWith("/__aitu_cache__/")?!1:qc.getUrlSyncStatus(re.url)!=="synced").length;return G+te},[Dt]),Xn=b.useCallback(async G=>{G.type===ln.AUDIO&&await D(G.id)},[D]),Sn=b.useCallback((G,te)=>{G.type===ln.AUDIO&&(te.preventDefault(),te.stopPropagation(),at(te,G))},[at]),Ai=b.useCallback(G=>{Ge(G),G&&u({activeType:ln.AUDIO})},[u]),Ri=b.useCallback((G,te)=>{dt(""),It({mode:G,targetAssetId:te}),ct()},[ct]),Ns=b.useCallback(G=>{dt(G.name),It({mode:"rename",playlistId:G.id})},[]),po=b.useCallback(async()=>{if(nt){if(nt.mode==="rename"&&nt.playlistId)await x(nt.playlistId,Lt);else{const G=await C(Lt);nt.mode==="create-and-add"&&nt.targetAssetId&&await _(nt.targetAssetId,G.id),Ai(G.id)}It(null),dt("")}},[nt,x,Lt,C,_,Ai]),Ln=b.useCallback(G=>G.map(te=>({id:te.id,url:te.type===ln.IMAGE?UV(te.url):te.url,type:te.type===ln.VIDEO?"video":te.type===ln.AUDIO?"audio":"image",title:te.name,alt:te.name,posterUrl:te.thumbnail,prompt:te.prompt,artist:te.modelName,album:te.type===ln.AUDIO?"Aitu Generated":void 0})),[]),sn=b.useCallback(G=>{const te=Ln(me.assets),re=me.assets.findIndex(de=>de.id===G.id);K(te),oe(re>=0?re:0),U(!0)},[me.assets,Ln]),hn=b.useCallback(()=>{U(!1)},[]),Dn=b.useCallback(async G=>{if(n){const te=me.assets.find(re=>re.id===G.id);if(te){n(te);return}}if(R)try{const te=me.assets.find(re=>re.id===G.id);G.type==="video"?await O1(R,G.url):G.type==="audio"?await Z5(R,G.url,{title:(te==null?void 0:te.name)||G.title,duration:te==null?void 0:te.duration,previewImageUrl:(te==null?void 0:te.thumbnail)||G.posterUrl,prompt:te==null?void 0:te.prompt,mv:te==null?void 0:te.modelName,clipId:te==null?void 0:te.clipId,providerTaskId:te==null?void 0:te.providerTaskId}):await M1(R,UV(G.url)),U(!1)}catch(te){console.error("Failed to insert media to canvas:",te)}},[me.assets,n,R]),nr=b.useCallback(G=>{G.type==="image"&&(ie(G.url),Q(!0),U(!1))},[]),Zn=b.useCallback(async G=>{if(R)try{const{unifiedCacheService:te}=await xn(async()=>{const{unifiedCacheService:Me}=await Promise.resolve().then(()=>du);return{unifiedCacheService:Me}},void 0,import.meta.url),re=`edited-image-${Date.now()}`,de=`/__aitu_cache__/image/${re}.png`,pe=await(await fetch(G)).blob();await te.cacheMediaFromBlob(de,pe,"image",{taskId:re}),await M1(R,de),Q(!1),ie("")}catch(te){console.error("Failed to insert edited image:",te)}},[R]);return b.useEffect(()=>{const G=te=>{var de;if(!((de=J.current)!=null&&de.contains(document.activeElement)))return;const re=te.target;if(!(re.tagName==="INPUT"||re.tagName==="TEXTAREA")&&!$&&(te.key===" "||te.key==="Enter")&&e){te.preventDefault();const ye=me.assets.find(pe=>pe.id===e);ye&&sn(ye)}};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[e,me.assets,sn,$]),c&&a.length===0?g.jsx("div",{className:"media-library-grid__loading",children:g.jsx(ty,{size:"large",text:"加载素材中..."})}):g.jsxs("div",{ref:J,className:`media-library-grid ${M?"media-library-grid--dragging":""}`,onDragOver:Zt,onDragLeave:Fn,onDrop:We,"data-testid":"media-library-grid",children:[g.jsxs("div",{className:"media-library-grid__header",children:[g.jsxs("div",{className:"media-library-grid__header-top",children:[g.jsx("div",{className:"media-library-grid__search",children:g.jsx(Cd,{value:l.searchQuery,onChange:G=>u({searchQuery:G}),placeholder:"搜索素材...",prefixIcon:g.jsx(sR,{size:16}),clearable:!0,"data-track":"grid_search_input"})}),g.jsxs("div",{className:"media-library-grid__header-right",children:[g.jsx(Gle,{viewMode:_e,onViewModeChange:Rt}),V?g.jsxs(g.Fragment,{children:[g.jsx(Ei,{variant:"base",theme:"danger",size:"small",icon:g.jsx(aR,{size:16}),disabled:Gt===0,onClick:()=>{gr()},"data-track":"grid_batch_delete",children:"删除"}),g.jsx(Ei,{variant:"outline",size:"small",icon:g.jsx(O8,{size:16}),onClick:rn,"data-track":"grid_cancel_selection",children:"取消"}),g.jsx(Ei,{variant:"outline",size:"small",icon:g.jsx($v,{size:16}),disabled:Gt===0||ce,loading:ce,onClick:Oi,"data-track":"grid_batch_download",children:"下载"}),Le&&g.jsx(cn,{content:"同步选中的素材到云端",placement:"bottom",children:g.jsx(Ei,{variant:"outline",size:"small",icon:g.jsx(k2e,{size:16}),disabled:ho===0||it,loading:it,onClick:Ur,"data-track":"grid_batch_sync",children:it?`${Re}%`:`同步 (${ho})`})})]}):g.jsxs(g.Fragment,{children:[g.jsx(Ei,{variant:"outline",size:"small",icon:g.jsx(TCe,{size:16}),onClick:rn,"data-track":"grid_toggle_selection_mode",children:"批量选择"}),g.jsx(Ei,{variant:"outline",size:"small",icon:g.jsx(NC,{size:16}),onClick:i,"data-track":"grid_upload_click",children:"上传"})]})]})]}),g.jsxs("div",{className:"media-library-grid__header-bottom",children:[V&&g.jsxs("div",{className:"media-library-grid__selection-info",onClick:Rn,role:"button",tabIndex:0,onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),Rn())},children:[g.jsx(ZT,{checked:Ft,indeterminate:Ne,"data-track":"grid_select_all"}),g.jsx("span",{className:"media-library-grid__selection-count",children:Gt})]}),g.jsx("div",{className:"media-library-grid__filter-island",children:g.jsxs("div",{className:"media-library-grid__filter-group",children:[g.jsx("div",{className:"media-library-grid__type-tabs",children:Cnt.map(G=>{const te=G.value==="ALL"?Bt.all:G.value===ln.IMAGE?Bt.image:G.value===ln.AUDIO?Bt.audio:Bt.video,re=G.icon,de=(l.activeType||"ALL")===G.value;return g.jsx(cn,{content:`${G.label} (${te})`,placement:"top",showArrow:!1,children:g.jsxs("button",{type:"button","aria-label":`${G.label}:${te}`,"aria-pressed":de,className:`media-library-grid__type-tab ${de?"media-library-grid__type-tab--active":""}`,onClick:()=>u({activeType:G.value==="ALL"?void 0:G.value}),children:[g.jsx(re,{size:14,strokeWidth:1.5,className:G.value==="ALL"?"icon-all":""}),g.jsx("span",{className:"media-library-grid__type-tab-label",children:G.label}),g.jsx("span",{className:"media-library-grid__type-tab-count",children:te})]})},G.value)})}),g.jsxs("div",{className:"media-library-grid__filter-tags",children:[g.jsx("span",{className:"media-library-grid__filter-tags-label",children:"标签"}),_nt.map(G=>{const te=Bt[G.countKey],re=G.icon,de=l.activeCategory===G.value;return g.jsx(cn,{content:`${G.tooltip} (${te})`,placement:"top",showArrow:!1,children:g.jsxs("button",{type:"button","aria-label":`${G.tooltip}:${te}`,"aria-pressed":de,className:`media-library-grid__filter-chip ${de?"media-library-grid__filter-chip--active":""}`,onClick:()=>u({activeCategory:de?void 0:G.value,...de?{}:{activeType:ln.IMAGE}}),children:[g.jsx(re,{size:13,strokeWidth:1.7}),g.jsx("span",{className:"media-library-grid__filter-chip-label",children:G.label}),g.jsx("span",{className:"media-library-grid__filter-chip-count",children:te})]})},G.value)}),g.jsx("span",{className:"media-library-grid__filter-tags-divider"}),Ent.map(G=>{const te=Bt[G.countKey],re=G.icon,de=l.activeSource===G.value;return g.jsx(cn,{content:`${G.tooltip} (${te})`,placement:"top",showArrow:!1,children:g.jsxs("button",{type:"button","aria-label":`${G.tooltip}:${te}`,"aria-pressed":de,className:`media-library-grid__filter-chip ${de?"media-library-grid__filter-chip--active":""}`,onClick:()=>u({activeSource:de?void 0:G.value}),children:[g.jsx(re,{size:13,strokeWidth:1.7}),g.jsx("span",{className:"media-library-grid__filter-chip-label",children:G.label}),g.jsx("span",{className:"media-library-grid__filter-chip-count",children:te})]})},G.value)})]})]})}),g.jsx("div",{className:"media-library-grid__header-spacer"}),g.jsx("div",{className:"media-library-grid__sort-options",children:Int.map(G=>{const te=l.sortBy||"DATE_DESC",re=te===G.options.asc,de=te===G.options.desc,ye=re||de,pe=re?G.icons.asc:G.icons.desc,Me=()=>{te===G.options.asc?u({sortBy:G.options.desc}):te===G.options.desc?te==="DATE_DESC"&&G.id==="DATE"?u({sortBy:"DATE_ASC"}):u({sortBy:"DATE_DESC"}):u({sortBy:G.options.asc})};return g.jsx(cn,{content:`${G.label}: ${re?"正序":de?"逆序":"默认"}`,placement:"top",showArrow:!1,children:g.jsx("div",{className:`media-library-grid__filter-option ${ye?"media-library-grid__filter-option--active":""}`,onClick:Me,children:g.jsx(pe,{size:14,strokeWidth:1.5})})},G.id)})})]}),(!l.activeType||l.activeType===ln.AUDIO)&&g.jsx(Xtt,{className:"media-library-grid__playlist-bar",selectedPlaylistId:Ze||hl,allCount:Bt.audio,playlists:y,playlistItems:w,onSelect:Ai,onCreate:()=>Ri("create"),onRename:Ns,onDelete:G=>void Ar(G)}),ce&&g.jsxs("div",{className:"media-library-grid__progress",children:[g.jsx("div",{className:"media-library-grid__progress-bar",children:g.jsx("div",{className:"media-library-grid__progress-fill",style:{width:`${Se}%`}})}),g.jsxs("span",{className:"media-library-grid__progress-text",children:[Se<50?"下载中":"压缩中"," ",Se,"%"]})]})]}),M&&g.jsx("div",{className:"media-library-grid__drop-overlay",children:g.jsxs("div",{className:"media-library-grid__drop-message",children:[g.jsx("div",{className:"media-library-grid__drop-message-icon",children:g.jsx(NC,{size:32})}),g.jsx("h3",{className:"media-library-grid__drop-message-title",children:"拖放文件到这里"}),g.jsx("p",{className:"media-library-grid__drop-message-description",children:"支持 JPG、PNG、MP4 格式"})]})}),me.isEmpty?g.jsx(btt,{}):g.jsxs(g.Fragment,{children:[g.jsx("div",{className:`media-library-grid__container ${Fe||Ht?"media-library-grid__container--transitioning":""}`,children:g.jsx(wtt,{assets:me.assets,viewMode:we,gridSize:N,selectedAssetId:e??void 0,isAssetSelected:Ct,isSelectionMode:V,marqueeEnabled:!T&&V,onSelectAsset:V?tr:t,onMarqueeSelect:dr,onDoubleClick:n,onPreview:sn,onContextMenu:Sn,isFavorite:P,onToggleFavorite:Xn,syncedUrls:f})}),T&&He&&!V&&g.jsxs("div",{className:"media-library-grid__mobile-inspector",children:[g.jsxs("div",{className:"media-library-grid__mobile-inspector-info",children:[g.jsxs("div",{className:"media-library-grid__mobile-inspector-type",children:[He.type===ln.IMAGE?g.jsx(wS,{size:14}):He.type===ln.AUDIO?g.jsx(zv,{size:14}):g.jsx(cg,{size:14}),g.jsx("span",{children:He.type===ln.IMAGE?"图片":He.type===ln.AUDIO?"音频":"视频"}),He.source===Lr.AI_GENERATED&&g.jsx("span",{className:"media-library-grid__mobile-inspector-ai",children:"AI"})]}),g.jsx(cn,{content:He.name,showArrow:!1,children:g.jsx("div",{className:"media-library-grid__mobile-inspector-name",children:He.name})})]}),g.jsxs("div",{className:"media-library-grid__mobile-inspector-actions",children:[g.jsx(cn,{content:"预览",children:g.jsx("button",{className:"media-library-grid__mobile-inspector-btn",onClick:()=>sn(He),"data-track":"mobile_preview",children:g.jsx(vY,{size:18})})}),n&&g.jsx(cn,{content:"插入画布",children:g.jsx("button",{className:"media-library-grid__mobile-inspector-btn media-library-grid__mobile-inspector-btn--primary",onClick:()=>n(He),"data-track":"mobile_insert",children:g.jsx(ic,{size:18})})}),g.jsx(cn,{content:"下载",children:g.jsx("button",{className:"media-library-grid__mobile-inspector-btn",onClick:()=>{De(He)},"data-track":"mobile_download",children:g.jsx($v,{size:18})})})]})]}),g.jsxs("div",{className:"media-library-grid__footer",children:[g.jsxs("div",{className:"media-library-grid__footer-left",children:[o?g.jsxs("div",{className:"media-library-grid__footer-storage",children:[g.jsx(OT,{size:14}),g.jsxs("span",{children:["已用 ",DC(o.quota.usage)]})]}):g.jsxs("div",{className:"media-library-grid__footer-storage",children:[g.jsx(OT,{size:14}),g.jsx("span",{children:"正在获取存储状态..."})]}),g.jsxs("span",{className:"media-library-grid__footer-count",children:["共 ",me.count," 个素材"]}),!V&&g.jsx("span",{className:"media-library-grid__footer-hint",children:"双击预览"})]}),g.jsx("div",{className:"media-library-grid__footer-right",children:we!=="list"&&g.jsxs("div",{className:"media-library-grid__zoom-control",children:[g.jsx(jSe,{size:14,onClick:()=>B(G=>Math.max(80,G-20))}),g.jsx("input",{type:"range",min:"80",max:"300",step:"10",value:N,onChange:G=>B(Number(G.target.value)),className:"media-library-grid__zoom-slider","data-track":"grid_zoom_slider"}),g.jsx(ic,{size:14,onClick:()=>B(G=>Math.min(300,G+20))})]})})]})]}),g.jsx(Hg,{visible:$,items:Y,initialIndex:Z,onClose:hn,showThumbnails:!0,onInsertToCanvas:R?Dn:void 0,onEdit:nr}),ae&&se&&g.jsx(Jle,{visible:ae,imageUrl:se,showOverwrite:!1,onClose:()=>{Q(!1),ie("")},onInsert:R?Zn:void 0}),g.jsx(W3,{state:pt,items:Ye,onClose:ct}),g.jsx(NR,{visible:!!nt,header:(nt==null?void 0:nt.mode)==="rename"?"重命名播放列表":"新建播放列表",onClose:()=>It(null),onConfirm:()=>void po(),confirmBtn:"确定",cancelBtn:"取消",children:g.jsx(Cd,{value:Lt,onChange:G=>dt(String(G)),placeholder:"请输入播放列表名称",autofocus:!0})}),mt]})}function Pnt(e,t="small"){const n=zn(e);if(n.startsWith("http://")||n.startsWith("https://")||n.startsWith("blob:")||F1(n))return n;try{const r=new URL(n,window.location.origin);return r.searchParams.set("thumbnail",t),r.toString()}catch{const r=n.includes("?")?"&":"?";return`${n}${r}thumbnail=${t}`}}function VV({asset:e,selectedAssets:t=[],isSelectionMode:n=!1,onRename:r,onDelete:i,onDownload:o,onMarkAsSubject:s,onSelect:a,onSelectMultiple:l,showSelectButton:c,selecting:u=!1,selectButtonText:d="使用"}){var Le,it;const[f,p]=b.useState(!1),[y,v]=b.useState(""),[w,C]=b.useState(!1),[x,E]=b.useState(!1),[_,I]=b.useState(""),[D,P]=b.useState(""),[k,R]=b.useState(!1),{board:T}=cy(),M=fle(e==null?void 0:e.id,e==null?void 0:e.url,e==null?void 0:e.size),F=t.length,V=t.filter(Te=>Te.type===ln.IMAGE).length,H=t.filter(Te=>Te.type===ln.VIDEO).length,j=t.filter(Te=>Te.type===ln.AUDIO).length,z=t.reduce((Te,Re)=>Te+(Re.size||0),0),{isCacheAsset:N,canvasElementCount:B}=b.useMemo(()=>{if(!e||!T)return{isCacheAsset:!1,canvasElementCount:0};const Te=Av(e.url),Re=Te?tae(T,e.dedupeUrls||[e.url]):0;return{isCacheAsset:Te,canvasElementCount:Re}},[e,T]),O=b.useMemo(()=>{if(e)return JSON.stringify({assetId:e.id,assetType:e.type,assetSource:e.source})},[e]),$=b.useCallback(()=>{e&&(v(e.name),p(!0))},[e]),U=b.useCallback(async()=>{if(!e){p(!1);return}const Te=y.trim();if(!Te||Te===e.name){p(!1),v("");return}try{await r(e.id,Te),p(!1)}catch{p(!1)}},[e,y,r]),Y=b.useCallback(Te=>{Te.key==="Escape"&&(p(!1),v(""))},[]),K=b.useCallback(()=>{C(!0)},[]),Z=b.useCallback(async()=>{if(e)try{await i(e.id),C(!1)}catch{}},[e,i]),oe=b.useCallback(()=>{e&&(o(e),tn.success("开始下载"))},[e,o]),J=b.useCallback(()=>{e&&a&&!u&&a(e)},[e,a,u]),ae=b.useCallback(async()=>{!l||t.length===0||u||await l(t)},[l,t,u]),Q=b.useCallback(async()=>{if(e!=null&&e.prompt)try{await aE(e.prompt),tn.success("提示词已复制")}catch{tn.error("复制失败")}},[e==null?void 0:e.prompt]),se=b.useCallback(()=>{var Te,Re;e&&(I(((Te=e.characterMeta)==null?void 0:Te.name)||""),P(((Re=e.characterMeta)==null?void 0:Re.prompt)||e.prompt||""),E(!0))},[e]),ie=b.useCallback(()=>{k||E(!1)},[k]),ce=b.useCallback(async()=>{if(!e||!s||k)return;const Te=_.trim(),Re=D.trim();if(!Te){tn.warning("请先给主体起一个名字");return}try{R(!0),await s(e,{name:Te,...Re&&{prompt:Re}}),E(!1)}catch(ht){console.error("[MediaLibraryInspector] Failed to mark subject:",ht),tn.error("设置主体失败")}finally{R(!1)}},[e,k,s,_,D]);if(n)return g.jsxs("div",{className:"media-library-inspector media-library-inspector--selection",children:[g.jsxs("div",{className:"media-library-inspector__selection-card",children:[g.jsx("div",{className:"media-library-inspector__selection-icon",children:g.jsx(S2,{size:22})}),g.jsxs("div",{className:"media-library-inspector__selection-copy",children:[g.jsx("span",{className:"media-library-inspector__selection-kicker",children:"批量选择"}),g.jsxs("h3",{className:"media-library-inspector__selection-title",children:["已选 ",F," 个素材"]}),g.jsx("p",{className:"media-library-inspector__selection-desc",children:"右侧操作会应用到当前筛选结果中已勾选的素材。"})]})]}),g.jsxs("div",{className:"media-library-inspector__selection-summary",children:[g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"图片"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:V})]}),g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"视频"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:H})]}),g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"音频"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:j})]}),g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"总大小"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:z>0?DC(z):"-"})]})]}),g.jsx("div",{className:"media-library-inspector__actions media-library-inspector__actions--batch",children:c&&l&&g.jsxs(Ei,{theme:"primary",block:!0,icon:g.jsx(S2,{size:16}),onClick:()=>{ae()},loading:u,disabled:u||F===0,"data-track":"inspector_batch_use_assets",className:"inspector-btn-select",children:[d,F>0?` (${F})`:""]})})]});if(!e)return g.jsx("div",{className:"media-library-inspector media-library-inspector--empty",children:g.jsx("p",{children:"选择素材查看详情"})});const ge=e.type==="IMAGE"?zn(e.url):e.url,Se=e.category===_s.CHARACTER,Ae=e.type===ln.IMAGE&&!!s;return g.jsxs("div",{className:"media-library-inspector",children:[g.jsx("div",{className:"media-library-inspector__preview",children:e.type==="AUDIO"?g.jsxs("div",{className:"media-library-inspector__audio-preview",children:[e.thumbnail&&g.jsx(xs,{src:e.thumbnail,alt:e.name,className:"media-library-inspector__audio-cover",showSkeleton:!1,eager:!0}),g.jsx("audio",{src:ge,controls:!0,className:"media-library-inspector__audio"})]}):e.type==="IMAGE"?g.jsx(xs,{src:Pnt(ge,"large"),alt:e.name,className:"media-library-inspector__image",fallback:g.jsx(xs,{src:ge,alt:e.name,className:"media-library-inspector__image",showSkeleton:!1,eager:!0}),showSkeleton:!1,eager:!0}):g.jsx(cN,{src:ge,alt:e.name,className:"media-library-inspector__video",poster:e.thumbnail,thumbnailSize:"large",activateVideoOnClick:!0,playOnActivate:!0,videoProps:{controls:!0,preload:"metadata"}})}),g.jsx("div",{className:"media-library-inspector__name-section",children:f?g.jsx("div",{className:"media-library-inspector__name-edit",children:g.jsx(Cd,{value:y,onChange:Te=>v(Te),autofocus:!0,onBlur:U,onEnter:U,onKeydown:Y,placeholder:"输入名称,按 Enter 或点击外部保存"})}):g.jsxs("div",{className:"media-library-inspector__name-display",children:[g.jsx(cn,{content:e.name,showArrow:!1,children:g.jsx("h3",{className:"media-library-inspector__name",children:e.name})}),g.jsx(Ei,{size:"small",variant:"text",icon:g.jsx(YSe,{size:14}),onClick:$,"data-track":"inspector_rename_start"})]})}),g.jsxs("div",{className:"media-library-inspector__metadata",children:[g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"类型"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:e.type==="IMAGE"?"图片":e.type==="AUDIO"?"音频":"视频"})]}),g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"来源"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:e.source==="AI_GENERATED"?"AI生成":"本地上传"})]}),Se&&g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"类别"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:"主体"})]}),((Le=e.characterMeta)==null?void 0:Le.name)&&g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"主体名"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:e.characterMeta.name})]})]}),g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"创建时间"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:Eae(e.createdAt)})]}),M&&g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"文件大小"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:DC(M)})]})]}),e.prompt&&g.jsxs("div",{className:"media-library-inspector__prompt-section",children:[g.jsxs("div",{className:"media-library-inspector__prompt-header",children:[g.jsx("span",{className:"media-library-inspector__prompt-label",children:"提示词"}),g.jsx(Ei,{size:"small",variant:"text",icon:g.jsx(yY,{size:12}),onClick:Q,"data-track":"inspector_copy_prompt",children:"复制"})]}),g.jsx("div",{className:"media-library-inspector__prompt-content",children:e.prompt})]}),((it=e.characterMeta)==null?void 0:it.prompt)&&e.characterMeta.prompt!==e.prompt&&g.jsxs("div",{className:"media-library-inspector__prompt-section media-library-inspector__prompt-section--compact",children:[g.jsx("div",{className:"media-library-inspector__prompt-header",children:g.jsx("span",{className:"media-library-inspector__prompt-label",children:"主体提示词"})}),g.jsx("div",{className:"media-library-inspector__prompt-content",children:e.characterMeta.prompt})]}),g.jsxs("div",{className:`media-library-inspector__actions ${c&&a&&Ae?"media-library-inspector__actions--with-select-subject":c&&a?"media-library-inspector__actions--with-select":Ae?"media-library-inspector__actions--with-subject":"media-library-inspector__actions--no-select"}`,children:[c&&a&&g.jsx(Ei,{theme:"primary",block:!0,icon:g.jsx(S2,{size:16}),onClick:J,loading:u,disabled:u,"data-track":"inspector_use_asset","data-track-params":O,className:"inspector-btn-select",children:d}),Ae&&g.jsx(Ei,{variant:"outline",block:!0,icon:g.jsx(NT,{size:16}),onClick:se,"data-track":"inspector_mark_subject","data-track-params":O,className:"inspector-btn-subject",children:Se?"编辑主体":"设为主体"}),g.jsx(Ei,{variant:"outline",block:!0,icon:g.jsx($v,{size:16}),onClick:oe,"data-track":"inspector_download","data-track-params":O,className:"inspector-btn-download",children:"下载"}),g.jsx(Ei,{theme:"danger",variant:"outline",block:!0,icon:g.jsx(aR,{size:16}),onClick:K,"data-track":"inspector_delete","data-track-params":O,className:"inspector-btn-delete",children:"删除"})]}),g.jsx(NR,{visible:x,header:Se?"编辑主体信息":"设为主体",onClose:ie,onConfirm:()=>void ce(),confirmBtn:k?"保存中...":"保存",cancelBtn:"取消",children:g.jsxs("div",{className:"media-library-inspector__subject-dialog",children:[g.jsxs("label",{className:"media-library-inspector__subject-label",children:["主体名",g.jsx(Cd,{value:_,onChange:Te=>I(String(Te)),placeholder:"例如:Lily / 银色耳机 / 红色跑车",autofocus:!0,disabled:k})]}),g.jsx("p",{className:"media-library-inspector__subject-hint",children:"主体名用于脚本复用,不会修改素材标题。"}),g.jsxs("label",{className:"media-library-inspector__subject-label",children:["主体提示词",g.jsx("textarea",{className:"media-library-inspector__subject-textarea",value:D,onChange:Te=>P(Te.target.value),placeholder:"可选;用于回填脚本中的主体提示词",rows:4,disabled:k})]})]})}),g.jsxs(aN,{open:w,title:"确认删除",confirmText:"删除",cancelText:"取消",danger:!0,onOpenChange:C,onConfirm:Z,children:[g.jsx("p",{children:"删除后无法恢复,确认删除该素材?"}),g.jsxs("p",{style:{marginTop:"8px",color:"var(--td-text-color-secondary)"},children:["素材名称: ",g.jsx("strong",{children:e.name})]}),N&&B>0&&g.jsxs("p",{style:{marginTop:"8px",color:"var(--td-error-color)"},children:["⚠️ 画布中有 ",g.jsx("strong",{children:B})," 个元素正在使用此素材,删除后这些元素也将被移除!"]})]})]})}const knt=Eu.DIALOG_AI_IMAGE;class Tm{constructor(){this.windows=new Map,this.counter=0}static getInstance(){return Tm.instance||(Tm.instance=new Tm),Tm.instance}register(t,n){const r=this.windows.get(t);r?(r.element=n,r.activationOrder=++this.counter):this.windows.set(t,{windowId:t,activationOrder:++this.counter,element:n}),this.applyAllZIndexes()}unregister(t){this.windows.delete(t)&&this.applyAllZIndexes()}bringToFront(t){const n=this.windows.get(t);n&&(this.isTopWindow(t)||(n.activationOrder=++this.counter,this.applyAllZIndexes()))}updateElement(t,n){const r=this.windows.get(t);r&&(r.element=n,this.applyZIndex(r,this.getPositionIndex(t)))}getTopWindowId(){let t=null,n=-1;return this.windows.forEach(r=>{r.activationOrder>n&&(n=r.activationOrder,t=r.windowId)}),t}isTopWindow(t){return this.getTopWindowId()===t}getPositionIndex(t){return this.getSortedEntries().findIndex(r=>r.windowId===t)}getSortedEntries(){return Array.from(this.windows.values()).sort((t,n)=>t.activationOrder-n.activationOrder)}applyAllZIndexes(){this.getSortedEntries().forEach((n,r)=>{this.applyZIndex(n,r)})}applyZIndex(t,n){!t.element||n<0||t.element.style.setProperty("--aitu-winbox-z-index",String(knt+n))}}const vf=Tm.getInstance();let Ws=null,l2=null;const Tnt=async()=>Ws||(typeof window<"u"&&window.WinBox?(Ws=window.WinBox,Ws):l2||(l2=(async()=>{try{if(await xn(()=>import("./winbox.bundle.min-CoRPjCs5.js"),[],import.meta.url),Ws=window.WinBox,Ws)return Ws;throw new Error("WinBox not found after import")}catch(e){return console.warn("Dynamic import failed, falling back to CDN:",e),new Promise((t,n)=>{const r=document.createElement("script");r.src="https://cdn.jsdelivr.net/npm/winbox@0.2.82/dist/winbox.bundle.min.js",r.async=!0,r.onload=()=>{Ws=window.WinBox,Ws?t(Ws):n(new Error("WinBox not found after CDN loading"))},r.onerror=n,document.head.appendChild(r)})}})(),l2)),dce=({visible:e,title:t,icon:n,onClose:r,children:i,width:o="80%",height:s="80%",minWidth:a=400,minHeight:l=300,x:c="center",y:u="center",maximizable:d=!0,minimizable:f=!0,resizable:p=!0,movable:y=!0,modal:v=!1,background:w="linear-gradient(135deg, #5A4FCF 0%, #7B68EE 50%, #E91E63 100%)",border:C=0,className:x,id:E,headerContent:_,container:I,onMaximize:D,onMinimize:P,onRestore:k,onFocus:R,onBlur:T,onMove:M,onResize:F,autoMaximize:V=!1,minVisiblePixels:H=50,onInsertToCanvas:j,keepAlive:z=!1,minimizeTargetSelector:N,onActivate:B})=>{var At;const O=b.useRef(E||`winbox-${Bh()}`),$=b.useRef(null),U=b.useRef(null),Y=b.useRef(r),K=b.useRef(B),Z=b.useRef(!0),oe=b.useRef(!1),J=b.useRef(null),ae=b.useRef([]);Y.current=r,K.current=B;const Q=b.useRef(null),se=b.useRef(!1),[ie,ce]=b.useState(null),[ge,Se]=b.useState(null),[Ae,Le]=b.useState(null),[it,Te]=b.useState(!1),[Re,ht]=b.useState(!!Ws),[Ze,Ge]=b.useState(null),pt=b.useRef(null),at=b.useRef(null),ct=b.useCallback(()=>{ae.current.forEach(le=>{window.clearTimeout(le)}),ae.current=[]},[]),nt=b.useCallback((le,me)=>{const ke=window.setTimeout(()=>{ae.current=ae.current.filter(Oe=>Oe!==ke),le()},me);return ae.current.push(ke),ke},[]),It=b.useCallback(()=>{Z.current&&(ce(null),Se(null),Le(null),Te(!1))},[]),Lt=b.useCallback((le,me=!0)=>{if(le){ct(),me&&(le.onclose=null);try{le.close(!0)}catch{}}},[ct]),dt=b.useCallback(()=>{const le=J.current;le&&(J.current=null,Lt(le))},[Lt]),wt=b.useCallback(le=>{if(le){ct(),J.current=le;try{le.hide()}catch{}nt(()=>{oe.current=!1,dt()},800)}},[ct,dt,nt]),mt=b.useCallback(le=>{Ge(le),pt.current=le,le===null&&at.current!==null&&$.current&&($.current.minwidth=at.current,at.current=null)},[]),Bt=b.useCallback(()=>{const le={left:!1,right:!1};if(typeof window>"u"||!window.WinBox)return le;const ke=window.WinBox.stack(),Oe=window.innerWidth;return ke.forEach(De=>{if(De===$.current)return;Math.abs(De.width-Oe/2)<20&&(De.x<20&&(le.left=!0),Math.abs(De.x+De.width-Oe)<20&&(le.right=!0))}),le},[]),He=b.useCallback(le=>{if(!le||!le.window)return;const me=window.innerWidth,ke=window.innerHeight;at.current!==null&&(le.minwidth=at.current,at.current=null),le.left=0,le.right=0,le.top=0,le.bottom=0;let Oe,De;typeof o=="string"&&o.endsWith("%")?Oe=Math.floor(me*parseInt(o)/100):Oe=typeof o=="number"?o:Math.floor(me*.8),typeof s=="string"&&s.endsWith("%")?De=Math.floor(ke*parseInt(s)/100):De=typeof s=="number"?s:Math.floor(ke*.8),Oe=Math.max(Oe,a),De=Math.max(De,l);const Ye=Math.floor((me-Oe)/2),Rt=Math.floor((ke-De)/2);le.resize(Oe,De).move(Ye,Rt),mt(null)},[o,s,a,l,mt]),we=b.useCallback((le,me,ke,Oe,De)=>{!le||!le.window||(le.left=0,le.right=0,le.top=0,le.bottom=0,me==="left"?(le.resize(ke,De).move(0,0),mt("left")):(le.resize(ke,De).move(Oe-ke,0),mt("right")))},[mt]),ue=b.useCallback(()=>{const le=$.current,me=pt.current;if(!le||!le.window)return;const ke=window.innerWidth,Oe=window.innerHeight,De=Bt(),Ye=Math.floor(ke/2),Rt=Ct=>{at.current===null&&(at.current=le.minwidth),le.minwidth=Math.min(200,Ye),le.max?(le.restore(),requestAnimationFrame(()=>{!le||!le.window||we(le,Ct,Ye,ke,Oe)})):we(le,Ct,Ye,ke,Oe)},St=()=>{le.max?(le.restore(),requestAnimationFrame(()=>{!le||!le.window||He(le)})):He(le)};if(me==="left"){St();return}if(me==="right"){De.left?St():Rt("left");return}De.right&&!De.left?Rt("left"):Rt("right")},[Bt,He,we]),_e=tQe(U,{enablePositionTracking:!1,enableScaleCompensation:!Ze&&!((At=$.current)!=null&&At.max)});b.useEffect(()=>{Re||Tnt().then(()=>ht(!0))},[Re]),b.useEffect(()=>(Z.current=!0,()=>{Z.current=!1}),[]);const xe=b.useRef(!1),Fe=b.useCallback(()=>{var le;return vf.unregister(O.current),(le=Y.current)==null||le.call(Y),!1},[]),lt=b.useCallback(()=>{var le;vf.bringToFront(O.current),(le=K.current)==null||le.call(K)},[]);b.useEffect(()=>{if(!(!Re||!Ws)){if(!e){if($.current)if(vf.unregister(O.current),ct(),z)try{$.current.hide()}catch{}else{const le=$.current;oe.current?wt(le):Lt(le),$.current=null,U.current=null,It()}return}if(e&&$.current){$.current.show(),$.current.focus(),vf.register(O.current,$.current.window);return}if(e&&!$.current){dt();const le=["winbox-react"];d||le.push("no-max"),f||le.push("no-min"),p||le.push("no-resize"),y||le.push("no-move"),le.push("no-full"),x&&le.push(x);const me=new Ws({id:E,title:t,width:o,height:s,minwidth:a,minheight:l,x:c,y:u,modal:v,background:w,border:C,overflow:!0,class:le,root:I||document.body,onclose:Fe,onmaximize:D,onminimize:function(){se.current=!0;const ke=Q.current,Oe=ke?{x:ke.x,y:ke.y}:{x:this.x||0,y:this.y||0},De=ke?{width:ke.width,height:ke.height}:{width:this.width||800,height:this.height||600},Ye=this.window;if(N&&Ye){const Rt=document.querySelector(N);if(Rt){Ye.style.transition="none",Ye.style.transform="",Ye.style.opacity="1",ke&&(Ye.style.left=`${ke.x}px`,Ye.style.top=`${ke.y}px`,Ye.style.width=`${ke.width}px`,Ye.style.height=`${ke.height}px`),Ye.offsetHeight;const St=Ye.getBoundingClientRect(),Ct=Rt.getBoundingClientRect(),Dt=Ct.left+Ct.width/2,Gt=Ct.top+Ct.height/2,Ft=St.left,Ne=St.top+St.height/2,gt=Dt-Ft,nn=Gt-Ne,Zt=Math.min(Ct.width/St.width,Ct.height/St.height,.06);Ye.style.transformOrigin="left center";const Fn=Ye.parentElement;Fn&&(Fn.style.perspective="1000px",Fn.style.perspectiveOrigin="left center"),Ye.offsetHeight;const We=400;return Ye.style.transition=`transform ${We}ms cubic-bezier(0.4, 0, 0.2, 1), opacity ${We}ms ease-out`,Ye.style.transform=`translate(${gt}px, ${nn}px) scale(${Zt}) rotateY(-30deg)`,Ye.style.opacity="0",nt(()=>{Ye.isConnected&&(Ye.style.transition="none",Ye.style.transform="",Ye.style.opacity="",Fn&&(Fn.style.perspective="",Fn.style.perspectiveOrigin=""),this.hide(),P==null||P(Oe,De))},We),!0}}return this.hide(),P==null||P(Oe,De),!0},onrestore:k,onfocus:function(){R==null||R(),lt()},onblur:T,onmove:function(ke,Oe){if(this.max||this.min||xe.current)return;const De=window.innerWidth,Ye=window.innerHeight,Rt=this.width;this.height;const St=H;if(pt.current){const Ne=pt.current==="left"?0:De-Rt;Math.abs(ke-Ne)>50&&mt(null)}let Ct=ke,Dt=Oe;ke<St-Rt&&(Ct=St-Rt),ke>De-St&&(Ct=De-St),Oe<0&&(Dt=0),Oe>Ye-St&&(Dt=Ye-St),(Ct!==ke||Dt!==Oe)&&(xe.current=!0,this.move(Ct,Dt),xe.current=!1);const Gt=Q.current,Ft=Gt&&Dt-Gt.y>200;!this.min&&!this.max&&!se.current&&!Ft&&(Q.current={x:Ct,y:Dt,width:this.width,height:this.height}),M==null||M(Ct,Dt)},onresize:function(ke,Oe){const De=Q.current,Ye=De&&(Oe<100||De.height-Oe>200);!this.min&&!this.max&&!se.current&&!Ye&&(Q.current={x:this.x,y:this.y,width:ke,height:Oe}),F==null||F(ke,Oe)}});if($.current=me,me.addControl({index:0,class:"wb-split",image:"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjxyZWN0IHg9IjMiIHk9IjMiIHdpZHRoPSIxOCIgaGVpZ2h0PSIxOCIgcng9IjIiIHJ5PSIyIj48L3JlY3Q+PGxpbmUgeDE9IjEyIiB5MT0iMyIgeDI9IjEyIiB5Mj0iMjEiPjwvbGluZT48L3N2Zz4=",click:ke=>{ke.preventDefault(),ke.stopPropagation(),ue()}}),j&&me.addControl({index:0,class:"wb-insert-canvas",image:"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjxyZWN0IHg9IjMiIHk9IjMiIHdpZHRoPSIxOCIgaGVpZ2h0PSIxOCIgcng9IjIiLz48cGF0aCBkPSJNMTIgOHY4Ii8+PHBhdGggZD0iTTggMTJoOCIvPjwvc3ZnPg==",click:ke=>{ke.preventDefault(),ke.stopPropagation();const Oe=me.window;if(Oe){const De=Oe.getBoundingClientRect(),Ye={x:De.left,y:De.top,width:De.width,height:De.height};j(Ye)}else{const De={x:me.x||0,y:me.y||0,width:me.width||800,height:me.height||600};j(De)}}}),me.window){U.current=me.window,vf.register(O.current,U.current),requestAnimationFrame(()=>{_e()});const ke=me.window.querySelector(".wb-body");if(ke&&Se(ke),n){const Oe=me.window.querySelector(".wb-drag"),De=me.window.querySelector(".wb-title");if(Oe&&De){const Ye=document.createElement("div");Ye.className="wb-icon-container",Oe.insertBefore(Ye,De),Le(Ye)}}}if(_&&me.window){const ke=me.window.querySelector(".wb-drag");if(ke){const Oe=document.createElement("div");Oe.className="wb-header-custom";const De=Ye=>{Ye.stopPropagation()};Oe.addEventListener("mousedown",De,!0),Oe.addEventListener("touchstart",De,!0),Oe.addEventListener("pointerdown",De,!0),ke.appendChild(Oe),ce(Oe)}}me&&!me.min&&!me.max&&(Q.current={x:me.x,y:me.y,width:me.width,height:me.height}),Te(!0),V&&nt(()=>{$.current&&$.current.maximize()},100)}}},[e,Re,V,z,ct,Lt,wt,dt,It,nt]),b.useEffect(()=>{const le=O.current;return()=>{if(vf.unregister(le),$.current){const me=$.current;oe.current?wt(me):Lt(me),$.current=null,U.current=null}J.current||ct()}},[ct,Lt,wt]),b.useEffect(()=>{$.current&&t&&$.current.setTitle(t)},[t]),b.useEffect(()=>{var le,me;if($.current&&n&&!Ae){const ke=$.current,Oe=(le=ke.window)==null?void 0:le.querySelector(".wb-drag"),De=(me=ke.window)==null?void 0:me.querySelector(".wb-title");if(Oe&&De&&!Oe.querySelector(".wb-icon-container")){const Rt=document.createElement("div");Rt.className="wb-icon-container",Oe.insertBefore(Rt,De),Le(Rt)}}},[n,Ae]),b.useEffect(()=>{if($.current){const le=Q.current;if(e){const me=$.current.min||$.current.hidden;$.current.min&&($.current.restore(),le&&($.current.move(le.x,le.y),$.current.resize(le.width,le.height)),se.current=!1),$.current.show(),$.current.focus(),vf.bringToFront(O.current),me&&N&&requestAnimationFrame(()=>{Ht()})}else $.current.hide()}},[e]);const Ht=b.useCallback(()=>{if(!N||!$.current)return;const le=$.current.window,me=document.querySelector(N);if(!le||!me)return;const ke=Q.current;if(!ke)return;const Oe=me.getBoundingClientRect(),De=Oe.left+Oe.width/2,Ye=Oe.top+Oe.height/2,Rt=ke.x,St=ke.y+ke.height/2,Ct=De-Rt,Dt=Ye-St,Gt=Math.min(Oe.width/ke.width,Oe.height/ke.height,.06),Ft=le.parentElement;Ft&&(Ft.style.perspective="1000px",Ft.style.perspectiveOrigin="left center"),le.style.transition="none",le.style.transformOrigin="left center",le.style.transform=`translate(${Ct}px, ${Dt}px) scale(${Gt}) rotateY(-30deg)`,le.style.opacity="0",le.offsetHeight;const Ne=350;le.style.transition=`transform ${Ne}ms cubic-bezier(0.2, 0, 0.4, 1), opacity ${Ne*.6}ms ease-out`,le.style.transform="",le.style.opacity="1",nt(()=>{le.isConnected&&(le.style.transition="none",le.style.transform="",le.style.transformOrigin="",Ft&&(Ft.style.perspective="",Ft.style.perspectiveOrigin=""))},Ne)},[N,nt]);return b.useEffect(()=>{const le=U.current;if(!le)return;const me=[".wb-drag",".wb-n",".wb-s",".wb-e",".wb-w",".wb-ne",".wb-nw",".wb-se",".wb-sw"].join(", "),ke=De=>{const Ye=De.target;Ye instanceof Element&&Ye.closest(me)&&(oe.current=!0)},Oe=()=>{!oe.current&&!J.current||(oe.current=!1,dt())};return le.addEventListener("mousedown",ke,!0),le.addEventListener("touchstart",ke,!0),window.addEventListener("mouseup",Oe,!0),window.addEventListener("touchend",Oe,!0),window.addEventListener("touchcancel",Oe,!0),window.addEventListener("blur",Oe),()=>{le.removeEventListener("mousedown",ke,!0),le.removeEventListener("touchstart",ke,!0),window.removeEventListener("mouseup",Oe,!0),window.removeEventListener("touchend",Oe,!0),window.removeEventListener("touchcancel",Oe,!0),window.removeEventListener("blur",Oe)}},[it,dt]),b.useEffect(()=>{$.current&&V&&$.current.maximize()},[V]),b.useEffect(()=>{const le=U.current;if(!le)return;const me=()=>{lt()},ke=()=>{lt()};return le.addEventListener("pointerdown",me,!0),le.addEventListener("focusin",ke,!0),()=>{le.removeEventListener("pointerdown",me,!0),le.removeEventListener("focusin",ke,!0)}},[it,lt]),b.useEffect(()=>{if(!$.current||!e||pt.current)return;const le=typeof o=="number"?o:$.current.width,me=typeof s=="number"?s:$.current.height;typeof le!="number"||typeof me!="number"||$.current.width===le&&$.current.height===me&&$.current.minwidth===a&&$.current.minheight===l||($.current.minwidth=a,$.current.minheight=l,$.current.resize(le,me))},[s,l,a,e,o]),g.jsxs(g.Fragment,{children:[it&&n&&Ae&&Ui.createPortal(g.jsx("span",{className:"wb-icon-content",children:n}),Ae),it&&ge&&Ui.createPortal(g.jsx("div",{className:"winbox-content-wrapper",children:i}),ge),it&&_&&ie&&Ui.createPortal(_,ie)]})};function Dnt(e){var r;const t=(r=e.split(".").pop())==null?void 0:r.toLowerCase();return t&&{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",mp4:"video/mp4",webm:"video/webm",ogg:"video/ogg"}[t]||null}function Mnt(e){return As.ALLOWED_IMAGE_TYPES.includes(e)||As.ALLOWED_VIDEO_TYPES.includes(e)}function q2(e){return e.split("/").pop()||e}function Ont(e){const t=q2(e);return t.startsWith(".")||t.startsWith("__MACOSX")||t==="Thumbs.db"||t===".DS_Store"}async function Rnt(e,t=100*1024*1024){const n={files:[],skippedCount:0,errors:[]};try{const{default:r}=await xn(async()=>{const{default:s}=await import("./office-data-DMEex_0S.js").then(a=>a.j);return{default:s}},[],import.meta.url),i=await r.loadAsync(e),o=Object.entries(i.files);for(const[s,a]of o){if(a.dir)continue;if(Ont(s)){n.skippedCount++;continue}const l=Dnt(s);if(!l||!Mnt(l)){n.skippedCount++;continue}try{const c=await a.async("arraybuffer");if(c.byteLength>t){n.errors.push(`文件 "${q2(s)}" 超过 100MB 限制,已跳过`),n.skippedCount++;continue}const u=new Blob([c],{type:l}),d=l.startsWith("image/");n.files.push({name:q2(s),blob:u,type:d?"image":"video",mimeType:l})}catch(c){const u=c instanceof Error?c.message:String(c);n.errors.push(`解压 "${q2(s)}" 失败: ${u}`),n.skippedCount++}}}catch(r){const i=r instanceof Error?r.message:String(r);n.errors.push(`读取 ZIP 文件失败: ${i}`)}return n}function Nnt(e){return As.ALLOWED_ZIP_TYPES.includes(e.type)||e.name.toLowerCase().endsWith(".zip")}function fce({isOpen:e,onClose:t,mode:n=V5.BROWSE,filterType:r,filterCategory:i,onSelect:o,onSelectMultiple:s,selectButtonText:a}){const{assets:l,loadAssets:c,addAsset:u,setFilters:d,selectedAssetId:f,setSelectedAssetId:p,storageStatus:y,checkStorageQuota:v,renameAsset:w,markAssetAsSubject:C,removeAsset:x}=sN(),{board:E}=cy(),[_,I]=b.useState(null),[D,P]=b.useState(!1),[k,R]=b.useState(!1),[T,M]=b.useState(!1),[F,V]=b.useState(!1),[H,j]=b.useState([]),z=b.useRef(null),N=b.useRef(!0),B=b.useRef(!1);b.useEffect(()=>(N.current=!0,()=>{N.current=!1}),[]),b.useEffect(()=>{e&&(c(),v())},[e,c,v]),b.useEffect(()=>{e&&(r||i)&&d({...r?{activeType:r}:{},activeCategory:i||void 0})},[e,r,i,d]),b.useEffect(()=>{e&&I(f)},[e,f]),b.useEffect(()=>{const ge=()=>{R(window.innerWidth<=768)};return ge(),window.addEventListener("resize",ge),()=>window.removeEventListener("resize",ge)},[]);const O=b.useCallback(ge=>{I(ge),p(ge)},[p]),$=b.useCallback(()=>{P(!1)},[]),U=b.useCallback(async ge=>{if(!(!o||B.current))try{B.current=!0,M(!0),await o(ge),t()}finally{B.current=!1,N.current&&M(!1)}},[t,o]),Y=b.useCallback(async ge=>{if(!(!o||B.current))try{B.current=!0,M(!0),await o(ge),t()}finally{B.current=!1,N.current&&M(!1)}},[t,o]),K=b.useCallback(async ge=>{if(!(!s||B.current)&&ge.length!==0)try{B.current=!0,M(!0),await s(ge),t()}finally{B.current=!1,N.current&&M(!1)}},[t,s]),Z=b.useCallback((ge,Se)=>{V(Se),j(ge)},[]),oe=b.useCallback(async ge=>{await FC([hI(ge)])},[]),J=b.useCallback(async ge=>{if(!ge||ge.length===0)return;const Se=[],Ae=[];for(let Te=0;Te<ge.length;Te++){const Re=ge[Te];Nnt(Re)?Se.push(Re):Ae.push(Re)}const Le=[];for(const Te of Ae){const Re=Te.type.startsWith("image/"),ht=Te.type.startsWith("video/"),Ze=Te.type.startsWith("audio/");if(!Re&&!ht&&!Ze){console.warn(`[MediaLibrary] Invalid file type: ${Te.type}`),tn.warning(`文件 "${Te.name}" 不是有效的图片、视频或音频格式`);continue}const Ge=100*1024*1024;if(Te.size>Ge){console.warn(`[MediaLibrary] File too large: ${Te.size} bytes`),tn.warning(`文件 "${Te.name}" 超过 100MB 限制`);continue}Le.push(Te)}let it=0;for(const Te of Se)try{tn.info(`正在解压 "${Te.name}"...`);const Re=await Rnt(Te);Re.errors.length>0&&Re.errors.forEach(ht=>tn.warning(ht));for(const ht of Re.files){const Ze=ht.type==="image"?ln.IMAGE:ln.VIDEO;await u(ht.blob,Ze,Lr.LOCAL,ht.name),it++}Re.skippedCount>0&&tn.info(`"${Te.name}" 中跳过了 ${Re.skippedCount} 个不支持的文件`)}catch(Re){console.error("[MediaLibrary] ZIP extraction error:",Re),tn.error(`解压 "${Te.name}" 失败`)}try{for(const Re of Le){const ht=Re.type.startsWith("image/"),Ze=Re.type.startsWith("audio/"),Ge=ht?ln.IMAGE:Ze?ln.AUDIO:ln.VIDEO;await u(Re,Ge,Lr.LOCAL)}const Te=Le.length+it;Te>0&&tn.success(`成功上传 ${Te} 个文件`),await c()}catch(Te){console.error("[MediaLibrary] File upload error:",Te)}},[u,c]),ae=b.useCallback(()=>{var ge;(ge=z.current)==null||ge.click()},[]),Q=b.useCallback(ge=>{const Se=ge.target.files;Se&&J(Se),ge.target.value=""},[J]),se=l.find(ge=>ge.id===_)||null,ie=n==="SELECT"&&!!o,ce=b.useCallback(async ge=>{const Se=l.find(Ae=>Ae.id===ge);E&&Se&&(Av(Se.url)?nae(E,Se.dedupeUrls||[Se.url]):eae(E,Se.dedupeAssetIds||[ge])),await x(ge)},[E,x,l]);return g.jsxs(g.Fragment,{children:[g.jsxs(dce,{visible:e,title:"素材库",onClose:t,width:"85%",height:"85%",minWidth:800,minHeight:500,x:"center",y:"center",maximizable:!0,minimizable:!1,resizable:!0,movable:!0,modal:!1,className:"winbox-media-library media-library-modal","data-testid":"media-library-modal",icon:g.jsx(cI,{size:18}),children:[g.jsx("input",{ref:z,type:"file",accept:"image/*,video/*,audio/*,.zip,application/zip,application/x-zip-compressed",multiple:!0,style:{display:"none"},onChange:Q}),g.jsxs("div",{className:"media-library-layout",children:[g.jsx("div",{className:"media-library-layout__main",children:g.jsx(Ant,{filterType:r,filterCategory:i,selectedAssetId:_,onSelectAsset:O,onDoubleClick:U,onFileUpload:J,onUploadClick:ae,storageStatus:y,onSelectionChange:Z})}),!k&&g.jsx("div",{className:"media-library-layout__inspector",children:g.jsx(VV,{asset:se,selectedAssets:H,isSelectionMode:F,onRename:w,onDelete:ce,onDownload:oe,onMarkAsSubject:C,onSelect:ie?Y:void 0,onSelectMultiple:ie&&s?K:void 0,showSelectButton:ie,selecting:T,selectButtonText:a})})]})]}),k&&g.jsx(F3e,{visible:D,onClose:$,header:"素材详情",placement:"bottom",size:"70vh",destroyOnClose:!0,className:"media-library-mobile-drawer",children:g.jsx(VV,{asset:se,selectedAssets:H,isSelectionMode:F,onRename:w,onDelete:ce,onDownload:oe,onMarkAsSubject:C,onSelect:ie?Y:void 0,onSelectMultiple:ie&&s?K:void 0,showSelectButton:ie,selecting:T,selectButtonText:a})})]})}const bpt=Object.freeze(Object.defineProperty({__proto__:null,MediaLibraryModal:fce},Symbol.toStringTag,{value:"Module"})),jnt={image:"prompt-list-item__tag--image",video:"prompt-list-item__tag--video",audio:"prompt-list-item__tag--audio",text:"prompt-list-item__tag--text",agent:"prompt-list-item__tag--agent","ppt-common":"prompt-list-item__tag--ppt-common","ppt-slide":"prompt-list-item__tag--ppt-slide"},Lnt=({content:e,title:t,sentPrompt:n,tags:r,resultPreview:i,pinned:o=!1,isPreset:s=!1,modelType:a,scene:l,previewExamples:c,onClick:u,onTogglePin:d,onDelete:f,onPreviewExample:p,language:y="zh",disabled:v=!1})=>{const w=z=>{z.stopPropagation(),d==null||d()},C=z=>{z.stopPropagation(),f==null||f()},x=(c==null?void 0:c.slice(0,3))??[],E=x.length>0,_=(t==null?void 0:t.trim())||e,I=(r||[]).filter(Boolean).slice(0,4),D=!!(n||i||I.length>0)&&!E,P=x.length===1,k=!!(p&&!v),R=z=>N=>{N.preventDefault(),N.stopPropagation(),k&&(p==null||p({content:e,previewExamples:x,initialIndex:z}))},T=z=>{z.preventDefault(),z.stopPropagation()},M=z=>N=>{N.key!=="Enter"&&N.key!==" "||(N.preventDefault(),N.stopPropagation(),k&&(p==null||p({content:e,previewExamples:x,initialIndex:z})))},F=g.jsxs("div",{className:`prompt-list-item ${o?"prompt-list-item--pinned":""} ${s?"prompt-list-item--preset":""} ${v?"prompt-list-item--disabled":""}`,onClick:v?void 0:u,children:[o&&g.jsx("div",{className:"prompt-list-item__pin-badge",children:g.jsx(M8,{size:10})}),s&&g.jsx("div",{className:"prompt-list-item__preset-badge",children:g.jsx(SSe,{size:10})}),l&&g.jsx("span",{className:`prompt-list-item__tag ${a&&jnt[a]||""}`,children:l}),g.jsx("span",{className:"prompt-list-item__text",children:_}),g.jsxs("div",{className:"prompt-list-item__actions",children:[d&&g.jsx(cn,{content:o?y==="zh"?"取消置顶":"Unpin":y==="zh"?"置顶":"Pin",children:g.jsx("button",{type:"button",className:"prompt-list-item__action",onClick:w,children:o?g.jsx(JSe,{size:14}):g.jsx(M8,{size:14})})}),f&&g.jsx(cn,{content:y==="zh"?"删除":"Delete",children:g.jsx("button",{type:"button",className:"prompt-list-item__action prompt-list-item__action--delete",onClick:C,children:g.jsx(md,{size:14})})})]})]}),V=E?g.jsxs("div",{className:"prompt-list-item__hover-card",children:[g.jsx("div",{className:"prompt-list-item__hover-text",children:e}),g.jsx("div",{className:`prompt-list-item__hover-gallery ${P?"prompt-list-item__hover-gallery--single":""}`,children:x.map((z,N)=>g.jsx("div",{className:`prompt-list-item__hover-thumb ${P?"prompt-list-item__hover-thumb--single":""}`,children:k?g.jsx("button",{type:"button",className:"prompt-list-item__hover-thumb-button","aria-label":`${y==="zh"?"预览示例图":"Preview example"} ${N+1}`,onMouseDown:R(N),onClick:T,onKeyDown:M(N),children:g.jsx(xs,{src:z.kind==="video"&&z.posterSrc||z.src,alt:z.alt,showSkeleton:!1})}):g.jsx(xs,{src:z.kind==="video"&&z.posterSrc||z.src,alt:z.alt,showSkeleton:!1})},`${z.src}-${z.alt}`))}),k&&g.jsx("div",{className:"prompt-list-item__hover-hint",children:y==="zh"?"点击预览":"Click to preview"})]}):null,H=i?g.jsxs("div",{className:"prompt-list-item__result-preview",children:[(i.kind==="image"||i.kind==="video")&&g.jsx("div",{className:"prompt-list-item__result-media",children:g.jsx(xs,{src:i.kind==="video"&&i.posterUrl||i.url,alt:i.title||_,showSkeleton:!1})}),i.kind==="audio"&&g.jsxs("div",{className:"prompt-list-item__result-audio",children:[i.coverUrl&&g.jsx(xs,{src:i.coverUrl,alt:i.title||_,showSkeleton:!1}),g.jsxs("div",{children:[g.jsx("div",{className:"prompt-list-item__result-title",children:i.title||"音频结果"}),i.text&&g.jsx("div",{className:"prompt-list-item__result-text",children:i.text})]})]}),(i.kind==="text"||i.kind==="error"||i.kind==="none")&&g.jsxs("div",{className:`prompt-list-item__result-text ${i.kind==="error"?"prompt-list-item__result-text--error":""}`,children:[i.kind==="text"&&i.title&&g.jsx("strong",{children:i.title}),i.text]})]}):null,j=D?g.jsxs("div",{className:"prompt-list-item__history-card",children:[g.jsx("div",{className:"prompt-list-item__history-title",children:_}),n&&g.jsxs("div",{className:"prompt-list-item__history-section",children:[g.jsx("div",{className:"prompt-list-item__history-label",children:"发送提示词"}),g.jsx("div",{className:"prompt-list-item__history-text",children:n})]}),I.length>0&&g.jsx("div",{className:"prompt-list-item__history-tags",children:I.map(z=>g.jsx("span",{children:z},z))}),H&&g.jsxs("div",{className:"prompt-list-item__history-section",children:[g.jsx("div",{className:"prompt-list-item__history-label",children:"结果预览"}),H]})]}):null;return V?g.jsx(cn,{content:V,placement:"right",delay:40,overlayClassName:"prompt-list-item__hover-card-popover",children:F}):j?g.jsx(cn,{content:j,placement:"right",delay:60,overlayClassName:"prompt-list-item__history-card-popover",children:F}):g.jsx(cn,{content:_===e?e:`${_}
|
|
2591
|
+
${w.expiresHint}`:""}`:"",x=b.useCallback(j=>{r(e.id,j)},[e.id,r]),E=b.useCallback(()=>{o&&!a&&o(e)},[e,o,a]),_=b.useCallback(j=>{j.preventDefault(),j.stopPropagation(),r(e.id,j)},[e.id,r]),I=b.useCallback(()=>{},[]),D=b.useCallback(j=>{j.stopPropagation(),j.preventDefault(),i==null||i(e)},[e,i]),P=b.useCallback(j=>{s==null||s(e,j)},[e,s]),k=b.useCallback(j=>{j.stopPropagation(),j.preventDefault(),u==null||u(e,j)},[e,u]),R=["asset-item",`asset-item--${t}`,n?"asset-item--selected":"",a?"asset-item--selection-mode":""].filter(Boolean).join(" "),T=t==="list",M=t==="compact",F=e.category===_s.CHARACTER;return g.jsxs("div",{className:R,onClick:x,onDoubleClick:E,onContextMenu:P,role:"button",tabIndex:0,"data-track":`asset_item_click_${t}`,children:[T&&a&&g.jsx("div",{className:"asset-item__checkbox asset-item__checkbox--left",onClick:_,children:g.jsx(ZT,{checked:n,onChange:I,"data-track":"asset_item_checkbox"})}),g.jsxs("div",{className:"asset-item__thumbnail",children:[e.type==="AUDIO"?e.thumbnail?g.jsx(MV,{src:e.thumbnail,alt:e.name,className:"asset-item__image",rootMargin:"100px"}):g.jsx("div",{className:"asset-item__audio-preview",children:g.jsx(zv,{size:32})}):e.type==="IMAGE"?g.jsx(MV,{src:p||e.url,alt:e.name,className:"asset-item__image",rootMargin:"100px"}):g.jsx(cN,{src:e.url,className:"asset-item__video",alt:e.name,poster:e.thumbnail,thumbnailSize:f,videoProps:{muted:!0,preload:"metadata"}}),!T&&!M&&g.jsxs("div",{className:"asset-item__badges",children:[g.jsx("div",{className:"asset-item__type-badge",children:e.type==="AUDIO"?g.jsx(zv,{}):e.type==="IMAGE"?g.jsx(wS,{}):g.jsx(cg,{})}),e.source==="AI_GENERATED"&&g.jsx("div",{className:"asset-item__ai-badge",children:"AI"}),F&&g.jsx(cn,{content:((V=e.characterMeta)==null?void 0:V.name)||"主体",showArrow:!1,children:g.jsxs("div",{className:"asset-item__subject-badge",children:[g.jsx(NT,{size:10}),g.jsx("span",{children:"主体"})]})}),l&&g.jsx(cn,{content:"已同步到云端",showArrow:!1,children:g.jsx("div",{className:"asset-item__synced-badge",children:g.jsx(T8,{size:10})})}),w&&g.jsx(cn,{content:C,showArrow:!1,children:g.jsx("div",{className:"asset-item__cache-warning-badge",children:"需下载"})})]}),e.type==="AUDIO"&&!a&&g.jsx("button",{type:"button",className:`asset-item__favorite-btn ${c?"asset-item__favorite-btn--active":""}`,onClick:k,"aria-label":c?"取消收藏":"加入收藏",children:g.jsx(vS,{size:14,fill:c?"currentColor":"none"})}),!T&&a&&g.jsx("div",{className:"asset-item__checkbox asset-item__checkbox--overlay",onClick:_,children:g.jsx(ZT,{checked:n,onChange:I,"data-track":"asset_item_checkbox"})}),!T&&!a&&i&&g.jsx(cn,{content:"插入到画布",showArrow:!1,children:g.jsx("button",{type:"button",className:"asset-item__preview-btn",onClick:D,"aria-label":"插入到画布","data-track":"asset_item_insert",children:g.jsx(ic,{size:16})})}),!T&&!M&&g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"asset-item__overlay"}),g.jsx(cn,{content:e.name,showArrow:!1,children:g.jsx("div",{className:"asset-item__name-overlay",children:e.name})})]})]}),T&&g.jsxs("div",{className:"asset-item__info",children:[g.jsx(cn,{content:e.name,showArrow:!1,children:g.jsx("div",{className:"asset-item__name",children:e.name})}),g.jsxs("div",{className:"asset-item__meta",children:[g.jsxs("span",{className:"asset-item__type",children:[e.type==="IMAGE"?g.jsx(wS,{size:12}):g.jsx(cg,{size:12}),e.type==="IMAGE"?"图片":"视频"]}),d&&g.jsx("span",{className:"asset-item__size",children:DC(d)}),g.jsx("span",{className:"asset-item__date",children:Eae(e.createdAt)})]})]}),T&&e.type==="AUDIO"&&!a&&g.jsx("button",{type:"button",className:`asset-item__favorite-btn asset-item__favorite-btn--list ${c?"asset-item__favorite-btn--active":""}`,onClick:k,"aria-label":c?"取消收藏":"加入收藏",children:g.jsx(vS,{size:14,fill:c?"currentColor":"none"})}),T&&e.source==="AI_GENERATED"&&g.jsx("div",{className:"asset-item__ai-badge asset-item__ai-badge--list",children:"AI"}),T&&F&&g.jsx(cn,{content:((H=e.characterMeta)==null?void 0:H.name)||"主体",showArrow:!1,children:g.jsxs("div",{className:"asset-item__subject-badge asset-item__subject-badge--list",children:[g.jsx(NT,{size:12}),g.jsx("span",{children:"主体"})]})}),T&&l&&g.jsx(cn,{content:"已同步到云端",showArrow:!1,children:g.jsx("div",{className:"asset-item__synced-badge asset-item__synced-badge--list",children:g.jsx(T8,{size:12})})}),T&&w&&g.jsx(cn,{content:C,showArrow:!1,children:g.jsx("div",{className:"asset-item__cache-warning-badge asset-item__cache-warning-badge--list",children:"需下载"})}),T&&!a&&i&&g.jsx(cn,{content:"插入到画布",showArrow:!1,children:g.jsx("button",{type:"button",className:"asset-item__preview-btn",onClick:D,"aria-label":"插入到画布","data-track":"asset_item_insert",children:g.jsx(ic,{size:16})})})]})},(e,t)=>e.asset.id===t.asset.id&&e.asset.name===t.asset.name&&e.asset.cacheWarning===t.asset.cacheWarning&&e.viewMode===t.viewMode&&e.isSelected===t.isSelected&&e.isInSelectionMode===t.isInSelectionMode&&e.onDoubleClick===t.onDoubleClick&&e.isSynced===t.isSynced&&e.isFavorite===t.isFavorite);Vle.displayName="AssetItem";const gtt={grid:{maxItemSize:180,minItemSize:120,gap:16,padding:20},compact:{maxItemSize:80,minItemSize:60,gap:4,padding:12},list:{maxItemSize:76,minItemSize:76,gap:0,padding:16}};function ytt(e){return!!e.closest('button, input, textarea, select, option, label, video, audio, a, .t-checkbox, [data-marquee-ignore="true"]')}function vtt(e,t){return!(e.right<t.left||e.left>t.right||e.bottom<t.top||e.top>t.bottom)}function wtt({assets:e,viewMode:t,gridSize:n=180,selectedAssetId:r,isAssetSelected:i,isSelectionMode:o,marqueeEnabled:s=!1,onSelectAsset:a,onMarqueeSelect:l,onDoubleClick:c,onPreview:u,onContextMenu:d,isFavorite:f,onToggleFavorite:p,syncedUrls:y}){const v=b.useRef(null),w=b.useRef(null),C=b.useRef(!1),x=b.useMemo(()=>{const $=gtt[t];return t==="grid"||t==="compact"?{...$,maxItemSize:n,minItemSize:Math.min(n,$.minItemSize)}:$},[t,n]),[E,_]=b.useState(800),[I,D]=b.useState(null);b.useEffect(()=>{const $=v.current;if(!$)return;const U=()=>{_($.clientWidth)};U();const Y=new ResizeObserver(U);return Y.observe($),()=>{Y.disconnect()}},[]);const P=b.useMemo(()=>{if(t==="list")return{columns:1,itemSize:x.maxItemSize};const $=E-x.padding*2,U=Math.max(1,Math.floor(($+x.gap)/(x.maxItemSize+x.gap))),Y=Math.floor(($-x.gap*(U-1))/U);return{columns:U,itemSize:Y}},[t,E,x]),k=P.columns,R=b.useMemo(()=>t==="list"?{width:E-x.padding*2,height:P.itemSize}:{width:P.itemSize,height:P.itemSize},[t,E,x.padding,P.itemSize]),T=b.useMemo(()=>Math.ceil(e.length/k),[e.length,k]),M=b.useCallback(()=>R.height+x.gap,[R.height,x.gap]),F=stt({count:T,getScrollElement:()=>v.current,estimateSize:M,overscan:3});b.useEffect(()=>{F.measure()},[E,T,k,F]);const V=b.useCallback($=>{const U=$*k;return e.slice(U,U+k).map(K=>{const Z=y?y.has(K.url):!1;return g.jsx("div",{"data-asset-cell":"true","data-asset-id":K.id,style:{width:"100%",height:R.height},children:g.jsx(Vle,{asset:K,viewMode:t,isSelected:o?i(K):r===K.id,onSelect:a,onDoubleClick:c,onPreview:u,onContextMenu:d,isInSelectionMode:o,isSynced:Z,isFavorite:f==null?void 0:f(K.id),onToggleFavorite:p})},K.id)})},[e,k,t,r,i,o,a,c,u,d,f,p,R.height,y]),H=F.getVirtualItems(),j=b.useCallback(()=>{w.current=null,D(null),window.setTimeout(()=>{C.current=!1},0)},[]);b.useEffect(()=>{s||(w.current=null,D(null),C.current=!1)},[s]);const z=b.useCallback($=>{const U=w.current,Y=v.current;if(!U||!Y||!s||!l)return;const K=Y.getBoundingClientRect(),Z=Math.min(Math.max($.clientX,K.left),K.right),oe=Math.min(Math.max($.clientY,K.top),K.bottom),J=Z-U.startX,ae=oe-U.startY;if(!U.active&&Math.hypot(J,ae)<6)return;U.active||(U.active=!0,C.current=!0);const Q=Math.min(U.startX,Z)-K.left,se=Math.min(U.startY,oe)-K.top,ie=Math.abs(Z-U.startX),ce=Math.abs(oe-U.startY),ge={left:Q,top:se,width:ie,height:ce};D(ge);const Se=new DOMRect(K.left+ge.left,K.top+ge.top,ge.width,ge.height),Ae=Array.from(Y.querySelectorAll('[data-asset-cell="true"][data-asset-id]')).filter(Le=>vtt(Le.getBoundingClientRect(),Se)).map(Le=>Le.dataset.assetId).filter(Le=>!!Le);l(Ae)},[s,l]),N=b.useCallback(()=>{j(),document.removeEventListener("pointermove",z),document.removeEventListener("pointerup",N)},[z,j]),B=b.useCallback($=>{if(!s||!l||$.button!==0)return;const U=$.target;!(U instanceof HTMLElement)||ytt(U)||(w.current={startX:$.clientX,startY:$.clientY,active:!1},C.current=!1,document.addEventListener("pointermove",z),document.addEventListener("pointerup",N))},[z,N,s,l]),O=b.useCallback($=>{C.current&&($.preventDefault(),$.stopPropagation())},[]);return b.useEffect(()=>()=>{w.current=null,document.removeEventListener("pointermove",z),document.removeEventListener("pointerup",N)},[z,N]),g.jsxs("div",{ref:v,className:`virtual-asset-grid virtual-asset-grid--${t} ${I?"virtual-asset-grid--marquee-active":""}`,onPointerDownCapture:B,onClickCapture:O,style:{height:"100%",overflow:"auto",position:"relative"},children:[g.jsx("div",{style:{height:`${F.getTotalSize()}px`,width:"100%",position:"relative"},children:H.map($=>g.jsx("div",{className:`virtual-asset-grid__row virtual-asset-grid__row--${t}`,style:{position:"absolute",top:0,left:0,width:"100%",height:`${R.height}px`,transform:`translateY(${$.start}px)`,display:t==="list"?"block":"grid",gridTemplateColumns:t==="list"?"none":`repeat(${k}, 1fr)`,gap:`${x.gap}px`,padding:`0 ${x.padding}px`},children:V($.index)},$.key))}),I&&g.jsx("div",{className:"virtual-asset-grid__marquee",style:{left:I.left,top:I.top,width:I.width,height:I.height}})]})}function btt(){return g.jsxs("div",{className:"media-library-empty",children:[g.jsx("div",{className:"media-library-empty__icon-container",children:g.jsx(cI,{size:48,className:"media-library-empty__icon"})}),g.jsx("h3",{className:"media-library-empty__title",children:"暂无素材"}),g.jsx("p",{className:"media-library-empty__description",children:"开始使用AI生成图片或视频,或者上传本地文件"})]})}const xtt=[{mode:"grid",icon:g.jsx(bSe,{size:16}),label:"默认网格"},{mode:"compact",icon:g.jsx(cSe,{size:16}),label:"紧凑网格"},{mode:"list",icon:g.jsx(kSe,{size:16}),label:"列表视图"}],Gle=b.memo(({viewMode:e,onViewModeChange:t})=>{const n=b.useCallback(r=>{r!==e&&t(r)},[e,t]);return g.jsx("div",{className:"view-mode-toggle",children:xtt.map(({mode:r,icon:i,label:o})=>g.jsx(cn,{content:o,children:g.jsx("button",{className:`view-mode-toggle__btn ${e===r?"view-mode-toggle__btn--active":""}`,onClick:()=>n(r),"data-track":`view_mode_${r}`,"aria-label":o,children:i})},r))})});Gle.displayName="ViewModeToggle";const Stt=.1,Ctt=5,LV=e=>Math.max(Stt,Math.min(Ctt,e));function Ett(e){const{items:t,initialMode:n="single",initialIndex:r=0,maxCompareSlots:i=4,defaultCompareLayout:o="horizontal",visible:s,onModeChange:a}=e,l=b.useCallback(()=>{if(Array.isArray(r))return r.slice(0,i);const ie=typeof r=="number"?r:0,ce=(ie+1)%t.length;return t.length>1?[ie,ce]:[ie]},[r,i,t.length]),c=b.useCallback(()=>{const ie=l().length;return ie>=4?4:ie===3?3:2},[l]),[u,d]=b.useState(n),[f,p]=b.useState(typeof r=="number"?r:0),[y,v]=b.useState(l),[w,C]=b.useState(o),[x,E]=b.useState(!1),[_,I]=b.useState(1),[D,P]=b.useState({x:0,y:0}),[k,R]=b.useState(0),[T,M]=b.useState(c);b.useEffect(()=>{if(s){const ie=l();d(n),p(typeof r=="number"?r:0),v(ie),M(ie.length>=4?4:ie.length===3?3:2),I(1),P({x:0,y:0}),R(0)}},[s,n,r,l]);const F=b.useRef(t);b.useEffect(()=>{if(!s||t===F.current){F.current=t;return}const ie=F.current;F.current=t;const ce=ie[f];if(!(ce!=null&&ce.id))return;const ge=t.findIndex(Se=>Se.id===ce.id);ge!==-1&&ge!==f&&p(ge)},[s,t,f]);const V=b.useMemo(()=>({mode:u,currentIndex:f,compareIndices:y,compareLayout:w,syncMode:x,zoomLevel:_,panOffset:D,focusedSlot:k}),[u,f,y,w,x,_,D,k]),H=b.useCallback(ie=>{if(ie!==u){if(ie==="compare"){const ce=(f+1)%t.length;v(t.length>1?[f,ce]:[f])}else{const ce=y[k]??y[0]??0;p(ce)}d(ie),I(1),P({x:0,y:0}),a==null||a(ie)}},[u,f,t.length,y,k,a]),j=b.useCallback(ie=>{ie>=0&&ie<t.length&&(p(ie),I(1),P({x:0,y:0}))},[t.length]),z=b.useCallback(()=>{const ie=f>0?f-1:t.length-1;j(ie)},[f,t.length,j]),N=b.useCallback(()=>{const ie=f<t.length-1?f+1:0;j(ie)},[f,t.length,j]),B=b.useCallback((ie,ce)=>{v(ge=>{const Se=[...ge];return typeof ce=="number"&&ce<T?Se[ce]=ie:Se.length<T?Se.push(ie):Se[k]=ie,Se})},[T,k]),O=b.useCallback(ie=>{v(ce=>{if(ce.length<=2)return ce;const ge=[...ce];return ge.splice(ie,1),ge}),k>=ie&&k>0&&R(k-1)},[k]),$=b.useCallback((ie,ce)=>{v(ge=>{const Se=[...ge],Ae=Se[ie];return Se[ie]=Se[ce],Se[ce]=Ae,Se})},[]),U=b.useCallback(ie=>{C(ie)},[]),Y=b.useCallback(()=>{E(ie=>!ie)},[]),K=b.useCallback(ie=>{I(ce=>{const ge=ce+ie;return LV(ge)})},[]),Z=b.useCallback(ie=>{I(LV(ie))},[]),oe=b.useCallback(()=>{I(1),P({x:0,y:0})},[]),J=b.useCallback(ie=>{P(ie)},[]),ae=b.useCallback(ie=>{R(ie)},[]),Q=b.useCallback(ie=>{M(ie),v(ce=>{if(ce.length>ie)return ce.slice(0,ie);if(ce.length<ie&&t.length>ce.length){const ge=[...ce];let Se=(ce[ce.length-1]+1)%t.length;for(;ge.length<ie&&ge.length<t.length;)ge.includes(Se)||ge.push(Se),Se=(Se+1)%t.length;return ge}return ce})},[t.length]),se=b.useMemo(()=>({setMode:H,goTo:j,goToPrev:z,goToNext:N,addToCompare:B,removeFromCompare:O,swapSlots:$,setCompareLayout:U,toggleSyncMode:Y,zoom:K,setZoomLevel:Z,setPan:J,resetView:oe,setFocusedSlot:ae,setSlotCount:Q}),[H,j,z,N,B,O,$,U,Y,K,Z,J,oe,ae,Q]);return[V,se]}const Pm=400;function _tt(e){return e==="video"?{width:Pm,height:Math.round(Pm*(9/16))}:{width:Pm,height:Pm}}async function Itt(e,t,n,r,i){const o=i||_tt(t);return t==="video"?(await O1(e,n,r,!1,o,!0,!0),o):(await M1(e,n,r,!1,o,!0,!0),o)}async function Att(e,t,n,r){const i=QJe();if(!i)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};try{if(!n){const c=await F5(i,t,e,r);if(c)return{success:!0,data:{insertedCount:1,items:[{type:e,point:c.point,elementId:c.elementId,size:c.size}],firstElementId:c.elementId,firstElementPosition:c.point,firstElementSize:c.size},type:"text"}}const o=n||rp(i,{logPrefix:"MediaQuickInsert"})||K5(i,{emptyPoint:hr.DEFAULT_POINT})||hr.DEFAULT_POINT,s=i.children.length,a=await Itt(i,e,t,o,r),l=i.children[s];return requestAnimationFrame(()=>{Ba(i,[o[0]+Pm/2,o[1]+Pm/2])}),{success:!0,data:{insertedCount:1,items:[{type:e,point:o,elementId:l==null?void 0:l.id,size:a}],firstElementId:l==null?void 0:l.id,firstElementPosition:o,firstElementSize:a},type:"text"}}catch(o){return console.error("[MediaQuickInsert] Failed to insert media:",o),{success:!1,error:`插入失败: ${o.message||"未知错误"}`,type:"error"}}}const Pr=({content:e,children:t,placement:n="bottom",sideOffset:r=8,crossAxisOffset:i=0,contentClassName:o,closeDelay:s=100})=>g.jsx(sFe,{content:e,placement:n,sideOffset:r,crossAxisOffset:i,contentClassName:o||"viewer-popover",closeDelay:s,children:t}),s2={x:0,y:0},Ptt=.1,ktt=5,Q0=.001,BV=.25,Ttt=.0025,FV=.08,Dtt=1,Mtt=2,Ott=16,Rtt=800,Ntt=32,jtt=88,Ltt=140,Btt=e=>Math.max(Ptt,Math.min(ktt,e)),Ftt=e=>e.deltaMode===Dtt?e.deltaY*Ott:e.deltaMode===Mtt?e.deltaY*Rtt:e.deltaY,$tt=e=>Math.max(-FV,Math.min(FV,e)),ztt=(e,t)=>{if(e.offsetWidth>0&&e.offsetHeight>0)return{width:e.offsetWidth,height:e.offsetHeight};const n=e.getBoundingClientRect(),r=Math.max(Math.abs(t),Q0);return{width:n.width/r,height:n.height/r}},Kle="media-viewport-toolbar-state-single",Utt=()=>{try{const e=localStorage.getItem(Kle);if(e)return JSON.parse(e)}catch{}return{orientation:"horizontal",position:null}},Htt=e=>{try{localStorage.setItem(Kle,JSON.stringify(e))}catch{}},nO=b.forwardRef(({item:e,slotIndex:t,isFocused:n=!1,zoomLevel:r=1,panOffset:i,onClick:o,videoAutoPlay:s=!1,videoLoop:a=!0,onZoomChange:l,onPanChange:c,isCompareMode:u=!1,onInsertToCanvas:d,onDownload:f,onEdit:p,onVideoPlayStateChange:y,onVideoTimeUpdate:v,isSyncMode:w=!1},C)=>{var Fn;const x=b.useRef(null),E=b.useRef(null),_=b.useRef(null),[I,D]=b.useState(!1),[P,k]=b.useState(!0),[R,T]=b.useState(!1),[M,F]=b.useState({x:0,y:0}),[V,H]=b.useState(i??s2),[j,z]=b.useState(r),N=b.useRef(r),[B,O]=b.useState(0),[$,U]=b.useState(!1),[Y,K]=b.useState(!1),[Z,oe]=b.useState(!1),[J,ae]=b.useState(!1),[Q,se]=b.useState(!1),ie=b.useRef(null),ce=b.useRef(!1),ge=b.useRef(r),Se=b.useRef(i);b.useImperativeHandle(C,()=>({resetVideo:()=>{E.current&&(E.current.currentTime=0,E.current.play().catch(()=>{}))},playVideo:()=>{E.current&&E.current.play().catch(()=>{})},pauseVideo:()=>{E.current&&E.current.pause()},toggleVideoPlayback:()=>{if(E.current){if(E.current.paused||E.current.ended){E.current.play().catch(()=>{});return}E.current.pause()}},setVideoTime:We=>{E.current&&(E.current.currentTime=We)},getVideoTime:()=>{var We;return((We=E.current)==null?void 0:We.currentTime)??0},isVideo:()=>(e==null?void 0:e.type)==="video"}),[e]);const[Ae]=b.useState(()=>u?{orientation:"horizontal",position:null}:Utt()),[Le,it]=b.useState(Ae.orientation),[Te,Re]=b.useState(Ae.position),[ht,Ze]=b.useState(!1),Ge=b.useRef({x:0,y:0,posX:0,posY:0}),pt=(e==null?void 0:e.type)==="video",at=(e==null?void 0:e.type)==="audio",ct=((Fn=e==null?void 0:e.prompt)==null?void 0:Fn.trim())||"",nt=!!ct&&(Z||J)&&!Q,It=e?pt||at?e.url:zn(e.url):"",Lt=e!=null&&e.posterUrl?zn(e.posterUrl):"",dt=e?`${e.type}:${e.id||e.url}`:"empty",wt=!!(e!=null&&e.url&&!at&&!u&&!I),mt=b.useCallback(()=>{ie.current!==null&&(window.clearTimeout(ie.current),ie.current=null)},[]),Bt=b.useCallback(()=>{mt(),oe(!0)},[mt]),He=b.useCallback(()=>{oe(!1),mt(),ie.current=window.setTimeout(()=>{ae(!1),ie.current=null},120)},[mt]),we=b.useCallback(()=>{mt(),ae(!0)},[mt]),ue=b.useCallback(()=>{ae(!1)},[]);b.useLayoutEffect(()=>{D(!1),k(!(e!=null&&e.url)||at||u),T(!1);const We=Se.current??s2,rn=ge.current;H(We),N.current=rn,z(rn),O(0),U(!1),K(!1),ce.current=!1},[dt,e==null?void 0:e.url,at,u]),b.useEffect(()=>()=>{mt()},[mt]),b.useEffect(()=>{u||Htt({orientation:Le,position:Te})},[Le,Te,u]),b.useLayoutEffect(()=>{const We=i??s2;Se.current=i,H(rn=>rn.x===We.x&&rn.y===We.y?rn:We)},[i]),b.useLayoutEffect(()=>{ge.current=r,N.current=r,z(We=>We===r?We:r)},[r]);const _e=b.useCallback((We,rn="manual")=>{const Rn=Btt(We);rn==="manual"&&(ce.current=!0),!(Math.abs(N.current-Rn)<=Q0)&&(N.current=Rn,z(tr=>Math.abs(tr-Rn)<=Q0?tr:Rn),l==null||l(Rn))},[l]),xe=b.useCallback(We=>{const rn=Se.current??s2;Math.abs(rn.x-We.x)<=Q0&&Math.abs(rn.y-We.y)<=Q0||(Se.current=We,H(We),c==null||c(We))},[c]),Fe=b.useCallback(()=>{if(u||at||!x.current)return;if(ce.current){k(!0);return}const We=pt?E.current:_.current;if(!We||!x.current)return;const rn=x.current.getBoundingClientRect();if(rn.width<=0||rn.height<=0)return;const Rn=pt?We.videoWidth:We.naturalWidth,tr=pt?We.videoHeight:We.naturalHeight;if(Rn<=0||tr<=0)return;const dr=ztt(We,N.current);if(dr.width<=0||dr.height<=0)return;const Yn=pt?Ltt:jtt,pr=Math.max(rn.width-Ntt,0),gr=Math.max(rn.height-Yn,0);if(pr<=0||gr<=0)return;const Ar=Math.min(pr/dr.width,gr/dr.height);!Number.isFinite(Ar)||Ar<=0||(xe({x:0,y:-Yn/2}),_e(Ar,"auto"),k(!0))},[u,at,pt,xe,_e]);b.useLayoutEffect(()=>{if(!(e!=null&&e.url)||at||u)return;const We=pt?E.current:_.current;if(!We)return;if(pt){We.readyState>=1&&Fe();return}const rn=We;rn.complete&&rn.naturalWidth>0&&Fe()},[e,at,u,pt,Fe]),b.useEffect(()=>{if(!(e!=null&&e.url)||at||u||typeof ResizeObserver>"u"||!x.current)return;const We=new ResizeObserver(()=>{Fe()});return We.observe(x.current),()=>{We.disconnect()}},[e==null?void 0:e.url,at,u,Fe]);const lt=b.useCallback(We=>{We.button===0&&(We.preventDefault(),T(!0),F({x:We.clientX-V.x,y:We.clientY-V.y}))},[V]),Ht=b.useCallback(We=>{if(!R)return;ce.current=!0;const rn={x:We.clientX-M.x,y:We.clientY-M.y};Se.current=rn,H(rn),c==null||c(rn)},[R,M,c]),At=b.useCallback(()=>{T(!1)},[]),le=b.useCallback(We=>{We.preventDefault();const rn=Ftt(We);if(!Number.isFinite(rn)||rn===0)return;const Rn=$tt(-rn*Ttt);_e(N.current+Rn)},[_e]),me=b.useCallback(()=>{_e(N.current+BV)},[_e]),ke=b.useCallback(()=>{_e(N.current-BV)},[_e]),Oe=b.useCallback(()=>{O(We=>We-90)},[]),De=b.useCallback(()=>{O(We=>We+90)},[]),Ye=b.useCallback(()=>{U(We=>!We)},[]),Rt=b.useCallback(()=>{K(We=>!We)},[]),St=b.useCallback(async()=>{if(e)try{const We=e.type==="video"?"video":"image";if(e.type==="audio"){tn.warning("音频暂不支持直接插入到画布");return}const rn=await Att(We,It);rn.success?tn.success(e.type==="video"?"视频已插入到画布":"图片已插入到画布"):tn.error(rn.error||"插入失败")}catch(We){console.error("Failed to insert to canvas:",We),tn.error("插入失败")}},[e,It]),Ct=b.useCallback(()=>{it(We=>We==="horizontal"?"vertical":"horizontal")},[]),Dt=b.useCallback(We=>{We.preventDefault(),We.stopPropagation(),Ze(!0);const rn=Te||{x:0,y:0};Ge.current={x:We.clientX,y:We.clientY,posX:rn.x,posY:rn.y};const Rn=dr=>{const Yn=dr.clientX-Ge.current.x,pr=dr.clientY-Ge.current.y;Re({x:Ge.current.posX+Yn,y:Ge.current.posY+pr})},tr=()=>{Ze(!1),document.removeEventListener("mousemove",Rn),document.removeEventListener("mouseup",tr)};document.addEventListener("mousemove",Rn),document.addEventListener("mouseup",tr)},[Te]),Gt=b.useCallback(We=>{if(We.stopPropagation(),We.touches.length!==1)return;const rn=We.touches[0];Ze(!0);const Rn=Te||{x:0,y:0};Ge.current={x:rn.clientX,y:rn.clientY,posX:Rn.x,posY:Rn.y};const tr=Yn=>{if(Yn.touches.length!==1)return;Yn.preventDefault();const pr=Yn.touches[0],gr=pr.clientX-Ge.current.x,Ar=pr.clientY-Ge.current.y;Re({x:Ge.current.posX+gr,y:Ge.current.posY+Ar})},dr=()=>{Ze(!1),document.removeEventListener("touchmove",tr),document.removeEventListener("touchend",dr),document.removeEventListener("touchcancel",dr)};document.addEventListener("touchmove",tr,{passive:!1}),document.addEventListener("touchend",dr),document.addEventListener("touchcancel",dr)},[Te]),Ft=b.useCallback(()=>{Re(null)},[]);if(!e)return g.jsx("div",{className:`media-viewport media-viewport--empty ${n?"media-viewport--focused":""}`,onClick:o,children:g.jsx("div",{className:"media-viewport__placeholder",children:g.jsx("span",{children:"点击底部缩略图添加媒体"})})});const Ne=$?-j:j,gt=Y?-j:j,nn={transform:`translate(${V.x}px, ${V.y}px) scale(${Ne}, ${gt}) rotate(${B}deg)`},Zt=wt&&!P;return g.jsxs("div",{ref:x,className:`media-viewport ${n?"media-viewport--focused":""} ${at?"media-viewport--audio":""} ${pt?"media-viewport--video":""} ${u?"":"media-viewport--single"}`,onClick:o,onMouseDown:at?void 0:lt,onMouseMove:at?void 0:Ht,onMouseUp:at?void 0:At,onWheel:at?void 0:le,onMouseLeave:()=>{at||At(),oe(!1),ae(!1),se(!1),mt()},"data-slot":t,children:[g.jsx("div",{className:`media-viewport__content ${Zt?"media-viewport__content--auto-fitting":""}`,style:at?void 0:nn,children:pt?g.jsx("div",{className:"media-viewport__media-hitbox",onMouseEnter:Bt,onMouseLeave:He,children:g.jsx("video",{ref:E,src:It,autoPlay:s,loop:a,controls:!0,className:"media-viewport__video",referrerPolicy:"no-referrer",onClick:We=>We.stopPropagation(),onPlay:()=>{w&&y&&y(!0)},onPause:()=>{w&&y&&y(!1)},onSeeked:()=>{w&&v&&E.current&&v(E.current.currentTime)},onLoadedMetadata:Fe})}):at?g.jsx("div",{className:"media-viewport__audio-shell",onClick:We=>We.stopPropagation(),children:g.jsxs("div",{className:"media-viewport__audio-card",children:[g.jsx(wle,{src:Lt,alt:e.alt||e.title||"",imageClassName:"media-viewport__audio-poster",fallbackClassName:"media-viewport__audio-poster media-viewport__audio-poster--fallback",iconSize:56}),g.jsxs("div",{className:"media-viewport__audio-meta",children:[e.title&&g.jsx("div",{className:"media-viewport__audio-title",children:e.title}),typeof e.duration=="number"&&Number.isFinite(e.duration)&&e.duration>0&&g.jsxs("div",{className:"media-viewport__audio-duration",children:[Math.floor(e.duration/60),":",String(Math.round(e.duration%60)).padStart(2,"0")]})]}),g.jsx("audio",{src:It,controls:!0,preload:"metadata",className:"media-viewport__audio",referrerPolicy:"no-referrer"})]})}):I?g.jsx("div",{className:"media-viewport__media-hitbox",onMouseEnter:Bt,onMouseLeave:He,children:g.jsx("div",{className:"media-viewport__image-fallback",children:g.jsx("span",{children:"图片加载失败"})})}):g.jsx("div",{className:"media-viewport__media-hitbox",onMouseEnter:Bt,onMouseLeave:He,children:g.jsx(xs,{ref:_,src:It,alt:e.alt||e.title||"",className:"media-viewport__image",draggable:!1,showSkeleton:!1,eager:!0,onLoad:Fe,onError:()=>{D(!0),k(!0)}})})}),g.jsxs("div",{className:`media-viewport__toolbar media-viewport__toolbar--${Le} ${ht?"media-viewport__toolbar--dragging":""} ${u?"media-viewport__toolbar--compact":""}`,style:!u&&Te?{transform:`translate(calc(-50% + ${Te.x}px), ${Te.y}px)`}:void 0,onMouseEnter:()=>se(!0),onMouseLeave:()=>se(!1),onMouseDown:We=>We.stopPropagation(),onClick:We=>We.stopPropagation(),children:[!at&&g.jsxs(g.Fragment,{children:[!u&&g.jsxs(g.Fragment,{children:[g.jsx(Pr,{content:"拖拽移动工具栏,双击重置位置",placement:"top",contentClassName:"viewer-popover",children:g.jsx("div",{className:"media-viewport__toolbar-handle",onMouseDown:Dt,onTouchStart:Gt,onDoubleClick:We=>{We.stopPropagation(),Ft()},children:g.jsx(dSe,{size:14})})}),g.jsx(Pr,{content:Le==="horizontal"?"切换为垂直布局":"切换为水平布局",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button",className:"media-viewport__toolbar-orientation-btn",onClick:We=>{We.stopPropagation(),We.preventDefault(),Ct()},children:g.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:Le==="horizontal"?g.jsxs(g.Fragment,{children:[g.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),g.jsx("polyline",{points:"8 7 12 3 16 7"}),g.jsx("polyline",{points:"8 17 12 21 16 17"})]}):g.jsxs(g.Fragment,{children:[g.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),g.jsx("polyline",{points:"7 8 3 12 7 16"}),g.jsx("polyline",{points:"17 8 21 12 17 16"})]})})})}),g.jsx("div",{className:"media-viewport__toolbar-divider"})]}),g.jsxs("div",{className:"media-viewport__toolbar-group",children:[g.jsx(Pr,{content:"缩小",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button","aria-label":"缩小",onClick:We=>{We.stopPropagation(),We.preventDefault(),ke()},children:g.jsx(IY,{size:16})})}),g.jsxs("span",{className:"media-viewport__zoom-level",children:[Math.round(j*100),"%"]}),g.jsx(Pr,{content:"放大",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button","aria-label":"放大",onClick:We=>{We.stopPropagation(),We.preventDefault(),me()},children:g.jsx(_Y,{size:16})})})]}),g.jsx("div",{className:"media-viewport__toolbar-divider"}),g.jsxs("div",{className:"media-viewport__toolbar-group",children:[g.jsx(Pr,{content:"向左旋转 90°",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button","aria-label":"向左旋转 90°",onClick:We=>{We.stopPropagation(),We.preventDefault(),Oe()},children:g.jsx(Uv,{size:16})})}),g.jsx(Pr,{content:"向右旋转 90°",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button","aria-label":"向右旋转 90°",onClick:We=>{We.stopPropagation(),We.preventDefault(),De()},children:g.jsx(CY,{size:16})})})]}),g.jsx("div",{className:"media-viewport__toolbar-divider"}),g.jsxs("div",{className:"media-viewport__toolbar-group",children:[g.jsx(Pr,{content:"水平翻转",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button","aria-label":"水平翻转",className:$?"active":"",onClick:We=>{We.stopPropagation(),We.preventDefault(),Ye()},children:g.jsx(wY,{size:16})})}),g.jsx(Pr,{content:"垂直翻转",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button","aria-label":"垂直翻转",className:Y?"active":"",onClick:We=>{We.stopPropagation(),We.preventDefault(),Rt()},children:g.jsx(bY,{size:16})})})]})]}),!u&&!at&&g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"media-viewport__toolbar-divider"}),g.jsx(Pr,{content:"插入到画布",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button",onClick:We=>{We.stopPropagation(),We.preventDefault(),d?d():St()},children:g.jsx(ic,{size:16})})})]}),!u&&f&&g.jsxs(g.Fragment,{children:[at&&g.jsx("div",{className:"media-viewport__toolbar-divider"}),g.jsx(Pr,{content:"下载",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button",onClick:We=>{We.stopPropagation(),We.preventDefault(),f()},children:g.jsx($v,{size:16})})})]}),!u&&p&&(e==null?void 0:e.type)==="image"&&g.jsx(Pr,{content:"编辑图片",placement:"top",contentClassName:"viewer-popover",children:g.jsx("button",{type:"button",onClick:We=>{We.stopPropagation(),We.preventDefault(),p()},children:g.jsx(oR,{size:16})})})]}),ct&&!at&&g.jsx(Pr,{content:ct,placement:"bottom",sideOffset:10,contentClassName:"viewer-popover viewer-popover--prompt",children:g.jsx("div",{className:`media-viewport__prompt ${nt?"media-viewport__prompt--visible":""} ${J?"media-viewport__prompt--expanded":""}`,onMouseEnter:we,onMouseLeave:ue,children:ct})})]})});nO.displayName="MediaViewport";const Wtt=({src:e,fallbackSrc:t,alt:n})=>{const[r,i]=b.useState(e),[o,s]=b.useState(!1);return b.useEffect(()=>{i(e),s(!1)},[e]),o?g.jsx("div",{className:"thumbnail-queue__image thumbnail-queue__image-fallback",children:g.jsx("span",{children:"加载失败"})}):g.jsx(xs,{src:r,alt:n,className:"thumbnail-queue__image",showSkeleton:!1,onError:()=>{if(t&&r!==t){i(t);return}s(!0)}})};function Vtt(e,t="small"){const n=zn(e);if(n.startsWith("http://")||n.startsWith("https://")||n.startsWith("blob:")||F1(n))return n;try{const r=new URL(n,window.location.origin);return r.searchParams.set("thumbnail",t),r.toString()}catch{const r=n.includes("?")?"&":"?";return`${n}${r}thumbnail=${t}`}}const Gtt=({items:e,mode:t,currentIndex:n,compareIndices:r,onThumbnailClick:i,onDragStart:o})=>{const s=b.useRef(null),[a,l]=b.useState(null);b.useEffect(()=>{if(t==="single"&&s.current){const y=s.current.querySelector(".thumbnail-queue__item--active");y&&y.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})}},[n,t]);const c=b.useCallback((y,v)=>{v.dataTransfer.setData("text/plain",String(y)),v.dataTransfer.effectAllowed="move",l(y),o==null||o(y)},[o]),u=b.useCallback(()=>{l(null)},[]),d=b.useCallback(y=>t==="single"?y===n:r.includes(y),[t,n,r]),f=b.useCallback(y=>{if(t!=="compare")return;const v=r.indexOf(y);return v>=0?v+1:void 0},[t,r]),p=b.useCallback((y,v)=>{const w=d(v),C=f(v),x=a===v,E=y.type==="video",_=y.type==="audio",I=zn(y.url),D=y.posterUrl?zn(y.posterUrl):"",P=Vtt(_&&D?D:I,"small");return g.jsxs("div",{className:`thumbnail-queue__item ${w?"thumbnail-queue__item--active":""} ${x?"thumbnail-queue__item--dragging":""}`,onClick:()=>i(v),draggable:t==="compare",onDragStart:k=>c(v,k),onDragEnd:u,role:"button",tabIndex:0,onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),i(v))},children:[g.jsx("div",{className:"thumbnail-queue__thumb",children:E?g.jsxs(g.Fragment,{children:[g.jsx(cN,{src:I,poster:D||void 0,className:"thumbnail-queue__video",alt:y.alt||y.title||"",thumbnailSize:"small",videoProps:{muted:!0,preload:"metadata"}}),g.jsx("div",{className:"thumbnail-queue__video-icon",children:g.jsx(SY,{size:16})})]}):_?g.jsxs(g.Fragment,{children:[g.jsx(wle,{src:D?P:void 0,fallbackSrc:D,alt:y.alt||y.title||"",imageClassName:"thumbnail-queue__image",fallbackClassName:"thumbnail-queue__image thumbnail-queue__audio-fallback",iconSize:18,loading:"lazy"}),g.jsx("div",{className:"thumbnail-queue__video-icon",children:g.jsx(iR,{size:16})})]}):g.jsx(Wtt,{src:P,alt:y.alt||y.title||"",fallbackSrc:I})}),w&&g.jsx("div",{className:"thumbnail-queue__check",children:C?g.jsx("span",{className:"thumbnail-queue__slot-number",children:C}):g.jsx(S2,{size:18})})]},y.id||`${y.url}-${v}`)},[d,f,a,t,i,c,u]);return e.length===0?null:g.jsx("div",{className:"thumbnail-queue",ref:s,children:g.jsx("div",{className:"thumbnail-queue__list",children:e.map((y,v)=>p(y,v))})})},Ktt=({mode:e,currentIndex:t,totalCount:n,slotCount:r,compareLayout:i,syncMode:o,onModeChange:s,onSlotCountChange:a,onLayoutChange:l,onSyncToggle:c,onResetView:u,onClose:d,onFullscreen:f,isImage:p=!1,showEditButton:y=!1,onBackToPreview:v,onResetEdit:w,onSaveEdit:C})=>{const x=b.useCallback(k=>{l(k),k==="grid"&&r<4&&a(4)},[l,a,r]),E=()=>g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"viewer-toolbar__indicator",children:[g.jsx("span",{className:"viewer-toolbar__current",children:t+1}),g.jsx("span",{className:"viewer-toolbar__separator",children:"/"}),g.jsx("span",{className:"viewer-toolbar__total",children:n})]}),n>1&&g.jsx(Pr,{content:"对比模式",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn",onClick:()=>s("compare"),"aria-label":"对比模式",children:g.jsx(D8,{size:18})})}),y&&p&&g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"viewer-toolbar__divider"}),g.jsx(Pr,{content:"编辑图片",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn",onClick:()=>s("edit"),"aria-label":"编辑图片",children:g.jsx(oR,{size:18})})})]})]}),_=()=>g.jsxs(g.Fragment,{children:[g.jsx(Pr,{content:"返回预览",placement:"bottom",contentClassName:"viewer-popover",children:g.jsxs("button",{className:"viewer-toolbar__btn",onClick:v,"aria-label":"返回预览",children:[g.jsx(x2,{size:18}),g.jsx("span",{className:"viewer-toolbar__btn-text",children:"返回"})]})}),g.jsx("div",{className:"viewer-toolbar__divider"}),g.jsx("div",{className:"viewer-toolbar__title",children:"编辑图片"})]}),I=()=>g.jsxs(g.Fragment,{children:[g.jsx(Pr,{content:"单图模式",placement:"bottom",contentClassName:"viewer-popover",children:g.jsxs("button",{className:"viewer-toolbar__btn",onClick:()=>s("single"),"aria-label":"单图模式",children:[g.jsx(x2,{size:18}),g.jsx("span",{className:"viewer-toolbar__btn-text",children:"单图"})]})}),g.jsx("div",{className:"viewer-toolbar__divider"}),g.jsxs("div",{className:"viewer-toolbar__group",children:[g.jsx("span",{className:"viewer-toolbar__label",children:"分屏"}),[2,3,4].map(k=>g.jsx(X.Fragment,{children:g.jsx(Pr,{content:`${k}分屏`,placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:`viewer-toolbar__btn viewer-toolbar__btn--small ${r===k?"viewer-toolbar__btn--active":""}`,onClick:()=>a(k),"aria-label":`${k}分屏`,children:k})})},k))]}),g.jsx("div",{className:"viewer-toolbar__divider"}),g.jsxs("div",{className:"viewer-toolbar__group",children:[g.jsx(Pr,{content:"水平布局",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:`viewer-toolbar__btn ${i==="horizontal"?"viewer-toolbar__btn--active":""}`,onClick:()=>x("horizontal"),"aria-label":"水平布局",children:g.jsx(D8,{size:18})})}),g.jsx(Pr,{content:"垂直布局",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:`viewer-toolbar__btn ${i==="vertical"?"viewer-toolbar__btn--active":""}`,onClick:()=>x("vertical"),"aria-label":"垂直布局",children:g.jsx(hCe,{size:18})})}),g.jsx(Pr,{content:"网格布局",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:`viewer-toolbar__btn ${i==="grid"?"viewer-toolbar__btn--active":""}`,onClick:()=>x("grid"),"aria-label":"网格布局",children:g.jsx(aSe,{size:18})})})]}),g.jsx("div",{className:"viewer-toolbar__divider"}),g.jsx(Pr,{content:o?"取消联动(快捷键 S)":"联动缩放/拖拽(快捷键 S)",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:`viewer-toolbar__btn ${o?"viewer-toolbar__btn--active":""}`,onClick:c,"aria-label":o?"取消联动":"联动缩放/拖拽",children:o?g.jsx(_Se,{size:18}):g.jsx(zCe,{size:18})})}),o&&g.jsx(Pr,{content:"重置视图",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn",onClick:u,children:g.jsx(Uv,{size:18})})})]}),D=()=>{switch(e){case"edit":return _();case"compare":return I();default:return E()}},P=()=>e==="edit"?g.jsxs(g.Fragment,{children:[g.jsx(Pr,{content:"重置",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn",onClick:w,children:g.jsx(Uv,{size:18})})}),g.jsx(Pr,{content:"保存",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn viewer-toolbar__btn--primary",onClick:C,"aria-label":"保存",children:g.jsx(Nd,{size:18})})}),g.jsx(Pr,{content:"关闭(Esc)",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn viewer-toolbar__btn--close",onClick:d,"aria-label":"关闭",children:g.jsx(md,{size:20})})})]}):g.jsxs(g.Fragment,{children:[f&&g.jsx(Pr,{content:"全屏",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn",onClick:f,children:g.jsx(xY,{size:18})})}),g.jsx(Pr,{content:"关闭(Esc)",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__btn viewer-toolbar__btn--close",onClick:d,"aria-label":"关闭",children:g.jsx(md,{size:20})})})]});return e==="edit"?g.jsxs("div",{className:"viewer-toolbar viewer-toolbar--edit-simplified",children:[g.jsx(Pr,{content:"返回预览",placement:"bottom",contentClassName:"viewer-popover",children:g.jsxs("button",{className:"viewer-toolbar__corner-btn viewer-toolbar__corner-btn--left",onClick:v,"aria-label":"返回预览",children:[g.jsx(x2,{size:20}),g.jsx("span",{children:"返回"})]})}),g.jsx(Pr,{content:"关闭(Esc)",placement:"bottom",contentClassName:"viewer-popover",children:g.jsx("button",{className:"viewer-toolbar__corner-btn viewer-toolbar__corner-btn--right",onClick:d,"aria-label":"关闭",children:g.jsx(md,{size:20})})})]}):g.jsxs("div",{className:"viewer-toolbar",children:[g.jsx("div",{className:"viewer-toolbar__left",children:D()}),g.jsx("div",{className:"viewer-toolbar__right",children:P()})]})},Zu={brightness:100,contrast:100,saturate:100,blur:0,grayscale:0,sepia:0,hueRotate:0,invert:0},qle=[{label:"自由",value:null},{label:"1:1",value:1},{label:"4:3",value:4/3},{label:"3:4",value:3/4},{label:"16:9",value:16/9},{label:"9:16",value:9/16},{label:"3:2",value:3/2},{label:"2:3",value:2/3}],rO=[{label:"原图",type:"none",filter:"none"},{label:"黑白",type:"grayscale",filter:"grayscale(100%)"},{label:"怀旧",type:"sepia",filter:"sepia(80%)"},{label:"复古",type:"vintage",filter:"sepia(40%) contrast(110%) brightness(90%)"},{label:"冷色",type:"cold",filter:"saturate(80%) hue-rotate(180deg) brightness(105%)"},{label:"暖色",type:"warm",filter:"saturate(120%) sepia(20%) brightness(105%)"},{label:"高对比",type:"contrast",filter:"contrast(150%)"},{label:"高饱和",type:"saturate",filter:"saturate(180%)"},{label:"反转",type:"invert",filter:"invert(100%)"}],Yle=({aspectRatio:e,presets:t,onAspectRatioChange:n,rotation:r,flipH:i,flipV:o,onRotate:s,onFlipH:a,onFlipV:l,onConfirmCrop:c,hasCropArea:u=!1,onAutoTrimWhitespace:d,isDetectingWhitespace:f=!1})=>g.jsxs("div",{className:"crop-panel",children:[d&&g.jsxs("div",{className:"crop-panel__section",children:[g.jsx("div",{className:"crop-panel__section-title",children:"智能裁剪"}),g.jsxs("button",{type:"button",className:`crop-panel__auto-trim-btn ${f?"loading":""}`,onClick:d,disabled:f,children:[g.jsx(yCe,{size:16}),g.jsx("span",{children:f?"检测中...":"智能去白边"})]}),g.jsx("div",{className:"crop-panel__auto-trim-hint",children:"自动检测并移除图片周围的白色边框"})]}),g.jsxs("div",{className:"crop-panel__section",children:[g.jsx("div",{className:"crop-panel__section-title",children:"裁剪比例"}),g.jsx("div",{className:"crop-panel__ratio-grid",children:t.map(p=>g.jsx("button",{type:"button",className:`crop-panel__ratio-btn ${e===p.value?"active":""}`,onClick:()=>n(p.value),children:p.label},p.label))})]}),g.jsxs("div",{className:"crop-panel__section",children:[g.jsx("div",{className:"crop-panel__section-title",children:"旋转和翻转"}),g.jsxs("div",{className:"crop-panel__transform-row",children:[g.jsx(cn,{content:"向左旋转 90°",placement:"top",children:g.jsx("button",{type:"button",className:"crop-panel__transform-btn",onClick:()=>s(-90),children:g.jsx(Uv,{size:18})})}),g.jsx(cn,{content:"向右旋转 90°",placement:"top",children:g.jsx("button",{type:"button",className:"crop-panel__transform-btn",onClick:()=>s(90),children:g.jsx(CY,{size:18})})}),g.jsx(cn,{content:"水平翻转",placement:"top",children:g.jsx("button",{type:"button",className:`crop-panel__transform-btn ${i?"active":""}`,onClick:a,children:g.jsx(wY,{size:18})})}),g.jsx(cn,{content:"垂直翻转",placement:"top",children:g.jsx("button",{type:"button",className:`crop-panel__transform-btn ${o?"active":""}`,onClick:l,children:g.jsx(bY,{size:18})})})]}),r!==0&&g.jsxs("div",{className:"crop-panel__rotation-info",children:["当前旋转: ",r,"°"]})]}),c&&g.jsxs("div",{className:"crop-panel__section",children:[g.jsxs("button",{type:"button",className:`crop-panel__confirm-btn ${u?"":"disabled"}`,onClick:c,disabled:!u,children:[g.jsx(Nd,{size:16}),g.jsx("span",{children:"应用裁剪"})]}),g.jsx("div",{className:"crop-panel__confirm-hint",children:"按 Enter 键快速确认"})]}),g.jsxs("div",{className:"crop-panel__tips",children:[g.jsx("p",{children:"拖动裁剪框调整位置"}),g.jsx("p",{children:"拖动边角调整大小"})]})]}),Xle=({filterType:e,filterParams:t,presets:n,imageUrl:r,onPresetSelect:i,onParamChange:o})=>g.jsxs("div",{className:"filter-panel",children:[g.jsxs("div",{className:"filter-panel__section",children:[g.jsx("div",{className:"filter-panel__section-title",children:"滤镜预设"}),g.jsx("div",{className:"filter-panel__preset-grid",children:n.map(s=>g.jsxs("button",{type:"button",className:`filter-panel__preset-btn ${e===s.type?"active":""}`,onClick:()=>i(s.type),children:[g.jsx("div",{className:"filter-panel__preset-preview",style:{backgroundImage:`url(${r})`,filter:s.filter}}),g.jsx("span",{className:"filter-panel__preset-label",children:s.label})]},s.type))})]}),g.jsxs("div",{className:"filter-panel__section",children:[g.jsx("div",{className:"filter-panel__section-title",children:"参数调节"}),g.jsxs("div",{className:"filter-panel__sliders",children:[g.jsx(yf,{label:"亮度",value:t.brightness,min:0,max:200,defaultValue:100,onChange:s=>o("brightness",s)}),g.jsx(yf,{label:"对比度",value:t.contrast,min:0,max:200,defaultValue:100,onChange:s=>o("contrast",s)}),g.jsx(yf,{label:"饱和度",value:t.saturate,min:0,max:200,defaultValue:100,onChange:s=>o("saturate",s)}),g.jsx(yf,{label:"灰度",value:t.grayscale,min:0,max:100,defaultValue:0,onChange:s=>o("grayscale",s)}),g.jsx(yf,{label:"复古",value:t.sepia,min:0,max:100,defaultValue:0,onChange:s=>o("sepia",s)}),g.jsx(yf,{label:"色相",value:t.hueRotate,min:0,max:360,defaultValue:0,onChange:s=>o("hueRotate",s)}),g.jsx(yf,{label:"模糊",value:t.blur,min:0,max:10,defaultValue:0,step:.5,onChange:s=>o("blur",s)})]})]})]}),yf=({label:e,value:t,min:n,max:r,defaultValue:i,step:o=1,onChange:s})=>{const a=t===i;return g.jsxs("div",{className:"filter-slider",children:[g.jsxs("div",{className:"filter-slider__header",children:[g.jsx("span",{className:"filter-slider__label",children:e}),g.jsx("span",{className:`filter-slider__value ${a?"":"modified"}`,children:t})]}),g.jsx(b6e,{value:t,min:n,max:r,step:o,onChange:l=>s(l)})]})},zc=10010;function qtt(e,t={}){const{threshold:n=250,tolerance:r=.02,minContentSize:i=50}=t,o=e.naturalWidth,s=e.naturalHeight,a=document.createElement("canvas");a.width=o,a.height=s;const l=a.getContext("2d");if(!l)return null;l.drawImage(e,0,0);const u=l.getImageData(0,0,o,s).data,d=D=>{const P=u[D],k=u[D+1],R=u[D+2];return u[D+3]<10?!0:P>=n&&k>=n&&R>=n},f=D=>{let P=0;for(let k=0;k<o;k++){const R=(D*o+k)*4;d(R)&&P++}return P/o>=1-r},p=D=>{let P=0;for(let k=0;k<s;k++){const R=(k*o+D)*4;d(R)&&P++}return P/s>=1-r};let y=0;for(;y<s&&f(y);)y++;let v=s-1;for(;v>y&&f(v);)v--;let w=0;for(;w<o&&p(w);)w++;let C=o-1;for(;C>w&&p(C);)C--;const x=C-w+1,E=v-y+1,_=y>0||w>0||C<o-1||v<s-1,I=x>=i&&E>=i;return!_||!I?null:{x:w,y,width:x,height:E}}const dI=b.forwardRef(({imageUrl:e,showOverwrite:t=!1,onOverwrite:n,onInsert:r,onClose:i,onSave:o,className:s},a)=>{const[l,c]=b.useState("crop"),[u,d]=b.useState(null),[f,p]=b.useState(null),[y,v]=b.useState("none"),[w,C]=b.useState(Zu),[x,E]=b.useState(0),[_,I]=b.useState(!1),[D,P]=b.useState(!1),[k,R]=b.useState({width:0,height:0}),[T,M]=b.useState(1),[F,V]=b.useState(1),H=.1,j=5,z=.1,[N,B]=b.useState({x:0,y:0}),[O,$]=b.useState(!1),[U,Y]=b.useState({x:0,y:0}),[K,Z]=b.useState(!1),[oe,J]=b.useState(null),[ae,Q]=b.useState(!1),[se,ie]=b.useState(null),[ce,ge]=b.useState(!1),[Se,Ae]=b.useState([]),[Le,it]=b.useState(-1),Te=b.useRef(!1),Re=b.useRef(null),ht=b.useRef(null),Ze=b.useRef(null);b.useEffect(()=>{Ze.current!==null&&Ze.current!==e&&(d(null),ie(null),p(null),v("none"),C(Zu),E(0),I(!1),P(!1),V(1),M(1),R({width:0,height:0}),B({x:0,y:0}),c("crop"),Ae([{cropArea:null,confirmedCropArea:null,aspectRatio:null,filterType:"none",filterParams:Zu,rotation:0,flipH:!1,flipV:!1}]),it(0)),Ze.current=e},[e]),b.useEffect(()=>{if(!e)return;const Ne=new Image;return Ne.crossOrigin="anonymous",Ne.onload=()=>{Re.current=Ne,R({width:Ne.naturalWidth,height:Ne.naturalHeight})},Ne.onerror=()=>{tn.error("图片加载失败")},Ne.src=e,()=>{Re.current=null}},[e]),b.useEffect(()=>{e&&Se.length===0&&(Ae([{cropArea:null,confirmedCropArea:null,aspectRatio:null,filterType:"none",filterParams:Zu,rotation:0,flipH:!1,flipV:!1}]),it(0))},[e,Se.length]),b.useEffect(()=>{if(!ht.current||k.width===0)return;const Ne=()=>{const nn=ht.current;if(!nn)return;const Zt=nn.clientWidth-80,Fn=nn.clientHeight-80;if(Zt<=0||Fn<=0)return;const We=Zt/k.width,rn=Fn/k.height,Rn=Math.min(We,rn,1);Rn>0&&isFinite(Rn)&&M(Rn)};requestAnimationFrame(Ne);const gt=new ResizeObserver(Ne);return gt.observe(ht.current),()=>gt.disconnect()},[k]);const Ge=b.useRef(null);b.useEffect(()=>{if(!(Te.current||Se.length===0))return Ge.current&&clearTimeout(Ge.current),Ge.current=setTimeout(()=>{It()},300),()=>{Ge.current&&clearTimeout(Ge.current)}},[x,_,D,y,w,f,se]);const pt=b.useCallback(()=>{if(y!=="none"){const gt=rO.find(nn=>nn.type===y);if(gt)return gt.filter}const Ne=[];return w.brightness!==100&&Ne.push(`brightness(${w.brightness}%)`),w.contrast!==100&&Ne.push(`contrast(${w.contrast}%)`),w.saturate!==100&&Ne.push(`saturate(${w.saturate}%)`),w.blur>0&&Ne.push(`blur(${w.blur}px)`),w.grayscale>0&&Ne.push(`grayscale(${w.grayscale}%)`),w.sepia>0&&Ne.push(`sepia(${w.sepia}%)`),w.hueRotate!==0&&Ne.push(`hue-rotate(${w.hueRotate}deg)`),w.invert>0&&Ne.push(`invert(${w.invert}%)`),Ne.length>0?Ne.join(" "):"none"},[y,w]),at=b.useCallback(()=>{const Ne=[];return x!==0&&Ne.push(`rotate(${x}deg)`),_&&Ne.push("scaleX(-1)"),D&&Ne.push("scaleY(-1)"),Ne.length>0?Ne.join(" "):"none"},[x,_,D]),ct=b.useCallback(()=>({cropArea:u,confirmedCropArea:se,aspectRatio:f,filterType:y,filterParams:w,rotation:x,flipH:_,flipV:D}),[u,se,f,y,w,x,_,D]),nt=b.useCallback(Ne=>{Te.current=!0,d(Ne.cropArea),ie(Ne.confirmedCropArea),p(Ne.aspectRatio),v(Ne.filterType),C(Ne.filterParams),E(Ne.rotation),I(Ne.flipH),P(Ne.flipV),requestAnimationFrame(()=>{Te.current=!1})},[]),It=b.useCallback(()=>{if(Te.current)return;const Ne=ct();Ae(gt=>{const nn=gt.slice(0,Le+1);return nn.push(Ne),nn.length>50&&nn.shift(),nn}),it(gt=>Math.min(gt+1,49))},[ct,Le]),Lt=b.useCallback(()=>{if(Le<=0)return;const Ne=Le-1;it(Ne),nt(Se[Ne])},[Le,Se,nt]),dt=b.useCallback(()=>{if(Le>=Se.length-1)return;const Ne=Le+1;it(Ne),nt(Se[Ne])},[Le,Se,nt]),wt=Le>0,mt=Le<Se.length-1,Bt=b.useCallback(()=>se!==null||u!==null||x!==0||_||D||y!=="none"||Object.keys(w).some(Ne=>w[Ne]!==Zu[Ne]),[se,u,x,_,D,y,w]),He=b.useCallback(()=>{d(null),ie(null),p(null),v("none"),C(Zu),E(0),I(!1),P(!1),V(1),B({x:0,y:0}),Ae([]),it(-1)},[]),we=b.useCallback(async()=>{const Ne=Re.current;if(!Ne){tn.error("图片未加载");return}const gt=tn.loading("正在处理图片...",0);try{const nn=document.createElement("canvas"),Zt=nn.getContext("2d");if(!Zt)throw new Error("无法创建 Canvas 上下文");let Fn=Ne.naturalWidth,We=Ne.naturalHeight,rn=0,Rn=0,tr=Ne.naturalWidth,dr=Ne.naturalHeight;const Yn=se||u;Yn&&(rn=Yn.x,Rn=Yn.y,tr=Yn.width,dr=Yn.height,Fn=Yn.width,We=Yn.height);const pr=(x%360+360)%360;(pr===90||pr===270)&&([Fn,We]=[We,Fn]),nn.width=Fn,nn.height=We,Zt.save(),Zt.translate(Fn/2,We/2),x!==0&&Zt.rotate(x*Math.PI/180),_&&Zt.scale(-1,1),D&&Zt.scale(1,-1);let gr=tr,Ar=dr;(pr===90||pr===270)&&([gr,Ar]=[Ar,gr]);const Oi=pt();Oi!=="none"&&(Zt.filter=Oi),Zt.drawImage(Ne,rn,Rn,tr,dr,-gr/2,-Ar/2,gr,Ar),Zt.restore();const Ur=nn.toDataURL("image/png");if(tn.close(gt),o){o(Ur);return}J(Ur),Z(!0)}catch(nn){tn.close(gt),tn.error(nn instanceof Error?nn.message:"图片处理失败")}},[se,u,x,_,D,pt,o]),ue=b.useCallback(Ne=>{if(oe){switch(Ne){case"overwrite":n==null||n(oe);break;case"insert":r==null||r(oe);break;case"download":{const gt=document.createElement("a");gt.href=oe,gt.download=`edited-image-${Date.now()}.png`,gt.click(),tn.success("图片已下载");break}}Z(!1),J(null),i==null||i()}},[oe,n,r,i]),_e=b.useCallback(Ne=>{p(Ne),d(null),ie(null)},[]),xe=b.useCallback(Ne=>{v(Ne),Ne!=="none"&&C(Zu)},[]),Fe=b.useCallback((Ne,gt)=>{C(nn=>({...nn,[Ne]:gt})),v("none")},[]),lt=b.useCallback(Ne=>{E(gt=>gt+Ne)},[]),Ht=b.useCallback(()=>{I(Ne=>!Ne)},[]),At=b.useCallback(()=>{P(Ne=>!Ne)},[]),le=b.useCallback(()=>{!u||!Re.current||(ie({...u}),c("filter"))},[u]),me=b.useCallback(()=>{const Ne=Re.current;if(!Ne){tn.warning("图片未加载完成");return}ge(!0),requestAnimationFrame(()=>{try{const gt=qtt(Ne);gt?(p(null),d(gt),tn.success("已检测到白边,裁剪框已自动调整")):tn.info("未检测到明显的白边")}catch{tn.error("检测白边失败")}finally{ge(!1)}})},[]);b.useEffect(()=>{const Ne=gt=>{gt.target instanceof HTMLInputElement||gt.target instanceof HTMLTextAreaElement||(gt.key==="Enter"&&l==="crop"&&u&&(gt.preventDefault(),le()),(gt.ctrlKey||gt.metaKey)&>.key==="z"&&!gt.shiftKey&&(gt.preventDefault(),Lt()),(gt.ctrlKey||gt.metaKey)&&(gt.key==="y"||gt.key==="z"&>.shiftKey)&&(gt.preventDefault(),dt()))};return window.addEventListener("keydown",Ne),()=>window.removeEventListener("keydown",Ne)},[l,u,le,Lt,dt]);const ke=b.useCallback(()=>{V(Ne=>Math.min(Ne+z,j))},[]),Oe=b.useCallback(()=>{V(Ne=>Math.max(Ne-z,H))},[]),De=b.useCallback(()=>{V(1),B({x:0,y:0})},[]),Ye=b.useCallback(Ne=>{Ne.preventDefault();const gt=Math.abs(Ne.deltaY);let nn;gt>50?nn=Ne.deltaY>0?-.15:.15:nn=-Ne.deltaY*.008,V(Zt=>Math.max(H,Math.min(j,Zt+nn)))},[]);b.useEffect(()=>{const Ne=ht.current;if(Ne)return Ne.addEventListener("wheel",Ye,{passive:!1}),()=>Ne.removeEventListener("wheel",Ye)},[Ye]);const Rt=b.useCallback(Ne=>{Ne==="crop"&&se&&!u&&d({...se}),c(Ne)},[se,u]),St=b.useCallback(Ne=>{l!=="crop"&&($(!0),Y({x:Ne.clientX-N.x,y:Ne.clientY-N.y}))},[l,N]),Ct=b.useCallback(Ne=>{O&&B({x:Ne.clientX-U.x,y:Ne.clientY-U.y})},[O,U]),Dt=b.useCallback(()=>{$(!1)},[]);b.useEffect(()=>{if(!O)return;const Ne=nn=>{B({x:nn.clientX-U.x,y:nn.clientY-U.y})},gt=()=>{$(!1)};return document.addEventListener("mousemove",Ne),document.addEventListener("mouseup",gt),()=>{document.removeEventListener("mousemove",Ne),document.removeEventListener("mouseup",gt)}},[O,U]),b.useEffect(()=>{V(1),B({x:0,y:0})},[l]),b.useImperativeHandle(a,()=>({reset:He,save:we,hasChanges:Bt,getState:ct,setState:nt}));const Gt=pt(),Ft=at();return g.jsxs("div",{className:`image-editor-core ${s||""}`,children:[g.jsxs("div",{className:"image-editor-core__header",children:[g.jsx("div",{className:"image-editor-core__title",children:"编辑图片"}),g.jsxs("div",{className:"image-editor-core__actions",children:[g.jsx(cn,{content:"撤销 (Ctrl+Z)",theme:"light",placement:"bottom",zIndex:zc,children:g.jsx("button",{type:"button",className:`image-editor-core__btn ${wt?"":"disabled"}`,onClick:Lt,disabled:!wt,children:g.jsx(FCe,{size:18})})}),g.jsx(cn,{content:"重做 (Ctrl+Y)",theme:"light",placement:"bottom",zIndex:zc,children:g.jsx("button",{type:"button",className:`image-editor-core__btn ${mt?"":"disabled"}`,onClick:dt,disabled:!mt,children:g.jsx(iCe,{size:18})})}),g.jsx("div",{className:"image-editor-core__divider"}),g.jsx(cn,{content:"对比原图(按住查看)",theme:"light",placement:"bottom",zIndex:zc,children:g.jsx("button",{type:"button",className:`image-editor-core__btn ${ae?"active":""}`,onMouseDown:()=>Q(!0),onMouseUp:()=>Q(!1),onMouseLeave:()=>Q(!1),children:g.jsx(vY,{size:18})})}),g.jsx(cn,{content:"重置",theme:"light",placement:"bottom",zIndex:zc,children:g.jsx("button",{type:"button",className:"image-editor-core__btn",onClick:He,children:g.jsx(Uv,{size:18})})}),i&&g.jsx(cn,{content:"取消",theme:"light",placement:"bottom",zIndex:zc,children:g.jsx("button",{type:"button",className:"image-editor-core__btn",onClick:i,children:g.jsx(md,{size:18})})}),(o||n||r)&&g.jsx(cn,{content:"保存",theme:"light",placement:"bottom",zIndex:zc,children:g.jsx("button",{type:"button",className:"image-editor-core__btn image-editor-core__btn--primary",onClick:we,children:g.jsx(Nd,{size:18})})})]})]}),g.jsxs("div",{className:"image-editor-core__main",children:[g.jsxs("div",{className:"image-editor-core__sidebar",children:[g.jsxs("div",{className:"image-editor-core__mode-tabs",children:[g.jsxs("button",{type:"button",className:`image-editor-core__mode-tab ${l==="crop"?"active":""}`,onClick:()=>Rt("crop"),children:[g.jsx(j2e,{size:16}),g.jsx("span",{children:"裁剪"})]}),g.jsxs("button",{type:"button",className:`image-editor-core__mode-tab ${l==="filter"?"active":""}`,onClick:()=>Rt("filter"),children:[g.jsx(ACe,{size:16}),g.jsx("span",{children:"滤镜"})]})]}),g.jsx("div",{className:"image-editor-core__panel",children:l==="crop"?g.jsx(Yle,{aspectRatio:f,presets:qle,onAspectRatioChange:_e,rotation:x,flipH:_,flipV:D,onRotate:lt,onFlipH:Ht,onFlipV:At,onConfirmCrop:le,hasCropArea:!!u,onAutoTrimWhitespace:me,isDetectingWhitespace:ce}):g.jsx(Xle,{filterType:y,filterParams:w,presets:rO,imageUrl:e,onPresetSelect:xe,onParamChange:Fe})})]}),g.jsxs("div",{className:"image-editor-core__preview",ref:ht,onMouseDown:St,onMouseMove:Ct,onMouseUp:Dt,onMouseLeave:Dt,style:{cursor:O?"grabbing":"grab"},children:[g.jsx("div",{className:"image-editor-core__canvas-wrapper",style:{transform:`translate(${N.x}px, ${N.y}px)`},children:ae?se?(()=>{const Ne=se.y/k.height*100,gt=(k.width-se.x-se.width)/k.width*100,nn=(k.height-se.y-se.height)/k.height*100,Zt=se.x/k.width*100;return g.jsx("div",{className:"image-editor-core__filter-preview",style:{transform:`${Ft} scale(${T*F})`.trim(),clipPath:`inset(${Ne}% ${gt}% ${nn}% ${Zt}%)`},children:g.jsx("img",{src:e,alt:"Original",draggable:!1})})})():g.jsx("div",{className:"image-editor-core__filter-preview",style:{transform:`${Ft} scale(${T*F})`.trim()},children:g.jsx("img",{src:e,alt:"Original",draggable:!1})}):l==="crop"?g.jsx(Ytt,{imageUrl:e,imageSize:k,cropArea:u,aspectRatio:f,rotation:x,displayScale:T,flipH:_,flipV:D,zoom:F,filterCSS:Gt,onCropChange:d},e):se?(()=>{const Ne=se.y/k.height*100,gt=(k.width-se.x-se.width)/k.width*100,nn=(k.height-se.y-se.height)/k.height*100,Zt=se.x/k.width*100;return g.jsx("div",{className:"image-editor-core__filter-preview",style:{filter:Gt,transform:`${Ft} scale(${T*F})`.trim(),clipPath:`inset(${Ne}% ${gt}% ${nn}% ${Zt}%)`},children:g.jsx("img",{src:e,alt:"Preview",draggable:!1})})})():g.jsx("div",{className:"image-editor-core__filter-preview",style:{filter:Gt,transform:`${Ft} scale(${T*F})`.trim()},children:g.jsx("img",{src:e,alt:"Preview",draggable:!1})})}),g.jsxs("div",{className:"image-editor-core__zoom-controls",children:[g.jsx(cn,{content:"缩小",theme:"light",placement:"top",zIndex:zc,children:g.jsx("button",{type:"button",className:"image-editor-core__zoom-btn",onClick:Oe,disabled:F<=H,children:g.jsx(IY,{size:16})})}),g.jsxs("span",{className:"image-editor-core__zoom-value",children:[Math.round(F*100),"%"]}),g.jsx(cn,{content:"放大",theme:"light",placement:"top",zIndex:zc,children:g.jsx("button",{type:"button",className:"image-editor-core__zoom-btn",onClick:ke,disabled:F>=j,children:g.jsx(_Y,{size:16})})}),g.jsx(cn,{content:"重置视图",theme:"light",placement:"top",zIndex:zc,children:g.jsx("button",{type:"button",className:"image-editor-core__zoom-btn",onClick:De,children:g.jsx(xY,{size:16})})})]})]})]}),K&&oe&&g.jsxs("div",{className:"image-editor-core__save-dialog",children:[g.jsx("div",{className:"image-editor-core__save-dialog-backdrop",onClick:()=>Z(!1)}),g.jsxs("div",{className:"image-editor-core__save-dialog-content",children:[g.jsx("h3",{className:"image-editor-core__save-dialog-title",children:"保存图片"}),g.jsxs("div",{className:"image-editor-core__save-options",children:[t&&n&&g.jsxs("button",{type:"button",className:"image-editor-core__save-option",onClick:()=>ue("overwrite"),children:[g.jsx(cCe,{size:20}),g.jsxs("div",{className:"image-editor-core__save-option-content",children:[g.jsx("span",{className:"image-editor-core__save-option-label",children:"覆盖原图"}),g.jsx("span",{className:"image-editor-core__save-option-desc",children:"替换画布中的原图片"})]})]}),r&&g.jsxs("button",{type:"button",className:"image-editor-core__save-option",onClick:()=>ue("insert"),children:[g.jsx(gSe,{size:20}),g.jsxs("div",{className:"image-editor-core__save-option-content",children:[g.jsx("span",{className:"image-editor-core__save-option-label",children:"插入新图片"}),g.jsx("span",{className:"image-editor-core__save-option-desc",children:"在画布中插入编辑后的图片"})]})]}),g.jsxs("button",{type:"button",className:"image-editor-core__save-option",onClick:()=>ue("download"),children:[g.jsx($v,{size:20}),g.jsxs("div",{className:"image-editor-core__save-option-content",children:[g.jsx("span",{className:"image-editor-core__save-option-label",children:"下载到本地"}),g.jsx("span",{className:"image-editor-core__save-option-desc",children:"保存编辑后的图片到本地"})]})]})]}),g.jsx("button",{type:"button",className:"image-editor-core__save-cancel",onClick:()=>Z(!1),children:"取消"})]})]})]})});dI.displayName="ImageEditorCore";const Ytt=({imageUrl:e,imageSize:t,cropArea:n,aspectRatio:r,rotation:i,flipH:o,flipV:s,zoom:a,displayScale:l,filterCSS:c,onCropChange:u})=>{const d=b.useRef(null),[f,p]=b.useState(!1),[y,v]=b.useState(null),[w,C]=b.useState(null),[x,E]=b.useState({x:0,y:0}),[_,I]=b.useState(null);b.useEffect(()=>{if(!n&&t.width>0){let M;if(r)if(t.width/t.height>r){const V=t.height,H=V*r;M={x:(t.width-H)/2,y:0,width:H,height:V}}else{const V=t.width,H=V/r;M={x:0,y:(t.height-H)/2,width:V,height:H}}else M={x:0,y:0,width:t.width,height:t.height};u(M)}},[r,t,n,u]);const D=b.useCallback((M,F,V)=>{M.preventDefault(),M.stopPropagation(),p(!0),v(F),C(V||null),E({x:M.clientX,y:M.clientY}),I(n)},[n]);b.useEffect(()=>{if(!f||!_)return;const M=V=>{let H=(V.clientX-x.x)/(l*a),j=(V.clientY-x.y)/(l*a);const z=(i%360+360)%360;let N,B;switch(z){case 90:N=j,B=-H;break;case 180:N=-H,B=-j;break;case 270:N=-j,B=H;break;default:N=H,B=j}o&&(N=-N),s&&(B=-B);const O={..._};if(y==="move")O.x=Math.max(0,Math.min(_.x+N,t.width-_.width)),O.y=Math.max(0,Math.min(_.y+B,t.height-_.height));else if(y==="resize"&&w){switch(w){case"nw":O.x=Math.min(_.x+N,_.x+_.width-20),O.y=Math.min(_.y+B,_.y+_.height-20),O.width=Math.max(20,_.width-N),O.height=Math.max(20,_.height-B);break;case"ne":O.y=Math.min(_.y+B,_.y+_.height-20),O.width=Math.max(20,_.width+N),O.height=Math.max(20,_.height-B);break;case"sw":O.x=Math.min(_.x+N,_.x+_.width-20),O.width=Math.max(20,_.width-N),O.height=Math.max(20,_.height+B);break;case"se":O.width=Math.max(20,_.width+N),O.height=Math.max(20,_.height+B);break;case"n":O.y=Math.min(_.y+B,_.y+_.height-20),O.height=Math.max(20,_.height-B);break;case"s":O.height=Math.max(20,_.height+B);break;case"w":O.x=Math.min(_.x+N,_.x+_.width-20),O.width=Math.max(20,_.width-N);break;case"e":O.width=Math.max(20,_.width+N);break}if(r&&(["e","w","ne","nw","se","sw"].includes(w)?O.height=O.width/r:["n","s"].includes(w)&&(O.width=O.height*r)),O.x<0&&(O.width+=O.x,O.x=0),O.y<0&&(O.height+=O.y,O.y=0),O.width=Math.min(O.width,t.width-O.x),O.height=Math.min(O.height,t.height-O.y),O.width=Math.max(20,O.width),O.height=Math.max(20,O.height),r){const U=O.height*r,Y=O.width/r;O.width>U?O.width=U:O.height>Y&&(O.height=Y)}}u(O)},F=()=>{p(!1),v(null),C(null)};return document.addEventListener("mousemove",M),document.addEventListener("mouseup",F),()=>{document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",F)}},[f,y,w,x,_,l,a,i,o,s,t,r,u]);const P=t.width*l*a,k=t.height*l*a,R={transform:`rotate(${i}deg) ${o?"scaleX(-1)":""} ${s?"scaleY(-1)":""}`.trim()},T=M=>{const F={nw:"nw-resize",ne:"ne-resize",sw:"sw-resize",se:"se-resize",n:"n-resize",s:"s-resize",w:"w-resize",e:"e-resize"},V={nw:"ne",ne:"se",se:"sw",sw:"nw",n:"e",e:"s",s:"w",w:"n"};let H=M;const j=(i%360+360)%360,z=Math.round(j/90)%4;for(let N=0;N<z;N++)H=V[H]||H;return o&&(H.includes("w")?H=H.replace("w","e"):H.includes("e")&&(H=H.replace("e","w"))),s&&(H.includes("n")?H=H.replace("n","s"):H.includes("s")&&(H=H.replace("s","n"))),F[H]||"pointer"};return g.jsx("div",{ref:d,className:"crop-canvas",children:g.jsxs("div",{className:"crop-canvas__image-container",style:{width:P,height:k,...R},children:[g.jsx("img",{src:e,alt:"Crop",draggable:!1,style:{filter:c||"none"}}),n&&g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"crop-canvas__overlay"}),g.jsxs("div",{className:"crop-canvas__crop-area",style:{left:n.x*l*a,top:n.y*l*a,width:n.width*l*a,height:n.height*l*a},onMouseDown:M=>D(M,"move"),children:[g.jsx("div",{className:"crop-canvas__crop-image",style:{backgroundImage:`url(${e})`,backgroundPosition:`-${n.x*l*a}px -${n.y*l*a}px`,backgroundSize:`${P}px ${k}px`,filter:c||"none"}}),g.jsxs("div",{className:"crop-canvas__grid",children:[g.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--h1"}),g.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--h2"}),g.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--v1"}),g.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--v2"})]}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--nw",style:{cursor:T("nw")},onMouseDown:M=>D(M,"resize","nw")}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--ne",style:{cursor:T("ne")},onMouseDown:M=>D(M,"resize","ne")}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--sw",style:{cursor:T("sw")},onMouseDown:M=>D(M,"resize","sw")}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--se",style:{cursor:T("se")},onMouseDown:M=>D(M,"resize","se")}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--n",style:{cursor:T("n")},onMouseDown:M=>D(M,"resize","n")}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--s",style:{cursor:T("s")},onMouseDown:M=>D(M,"resize","s")}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--w",style:{cursor:T("w")},onMouseDown:M=>D(M,"resize","w")}),g.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--e",style:{cursor:T("e")},onMouseDown:M=>D(M,"resize","e")})]})]})]})})},Zle=b.forwardRef(({imageUrl:e,showOverwrite:t=!1,onOverwrite:n,onInsert:r},i)=>g.jsx(dI,{ref:i,imageUrl:e,showOverwrite:t,onOverwrite:n,onInsert:r,className:"embedded-editor"}));Zle.displayName="ImageEditorContent";const Hg=({visible:e,items:t,initialMode:n="single",initialIndex:r=0,onClose:i,onModeChange:o,showThumbnails:s=!0,maxCompareSlots:a=4,defaultCompareLayout:l="horizontal",className:c="",showTitle:u=!0,videoAutoPlay:d=!1,videoLoop:f=!0,onInsertToCanvas:p,onEdit:y,useBuiltInEditor:v=!1,onEditOverwrite:w,onEditInsert:C,showEditOverwrite:x=!1})=>{const E=b.useRef(null),_=b.useRef(null),[I,D]=b.useState(2),[P,k]=b.useState(!1),[R,T]=b.useState(null),M=b.useRef(null),F=b.useRef(new Map),V=b.useRef([]),H=b.useRef(null),j=b.useRef(!1),[z,N]=Ett({items:t,initialMode:n,initialIndex:r,maxCompareSlots:a,defaultCompareLayout:l,visible:e,onModeChange:o}),{mode:B,currentIndex:O,compareIndices:$,compareLayout:U,syncMode:Y,zoomLevel:K,panOffset:Z,focusedSlot:oe}=z,J=b.useCallback(ue=>{M.current=ue,T(ue)},[]);b.useEffect(()=>{e||(F.current.clear(),J(null))},[e,J]);const ae=b.useCallback(()=>{if(t.length<=I)return;const _e=Math.max(...$)+1;if(_e>=t.length){const xe=[];for(let Fe=0;Fe<I&&Fe<t.length;Fe++)xe.push(Fe);xe.forEach((Fe,lt)=>N.addToCompare(Fe,lt))}else{const xe=[];for(let Fe=0;Fe<I;Fe++){const lt=(_e+Fe)%t.length;xe.push(lt)}xe.forEach((Fe,lt)=>N.addToCompare(Fe,lt))}},[t.length,I,$,N]),Q=b.useCallback(()=>{if(t.length<=I)return;const _e=Math.min(...$)-I;if(_e<0){const xe=Math.max(0,t.length-I),Fe=[];for(let lt=0;lt<I&&xe+lt<t.length;lt++)Fe.push(xe+lt);Fe.forEach((lt,Ht)=>N.addToCompare(lt,Ht))}else{const xe=[];for(let Fe=0;Fe<I;Fe++)xe.push(_e+Fe);xe.forEach((Fe,lt)=>N.addToCompare(Fe,lt))}},[t.length,I,$,N]),se=b.useCallback(ue=>{const _e=t[ue];if(!_e||_e.type!=="image")return!1;const xe=M.current;if(xe&&_.current){const Fe=_.current.getState();F.current.set(xe.url,Fe)}return N.goTo(ue),J(_e),setTimeout(()=>{const Fe=F.current.get(_e.url);Fe&&_.current&&_.current.setState(Fe)},50),!0},[t,N,J]),ie=b.useCallback(()=>{N.resetView(),V.current.forEach(ue=>{ue!=null&&ue.isVideo()&&ue.resetVideo()})},[N]);b.useEffect(()=>{if(!e)return;const ue=_e=>{const xe=_e.target instanceof HTMLElement?_e.target:null;if(xe instanceof HTMLInputElement||xe instanceof HTMLTextAreaElement||xe instanceof HTMLSelectElement||xe instanceof HTMLButtonElement||xe!=null&&xe.isContentEditable)return;const Fe=B==="single"?H.current:V.current[oe]||null;switch(_e.key){case"Escape":_e.preventDefault(),i();break;case"ArrowLeft":case"ArrowUp":if(_e.preventDefault(),B==="edit"){const lt=(O-1+t.length)%t.length;se(lt)}else B==="single"?N.goToPrev():Q();break;case"ArrowRight":case"ArrowDown":if(_e.preventDefault(),B==="edit"){const lt=(O+1)%t.length;se(lt)}else B==="single"?N.goToNext():ae();break;case"c":case"C":t.length>1&&(_e.preventDefault(),N.setMode(B==="single"?"compare":"single"));break;case"1":case"2":case"3":case"4":if(B==="compare"){const lt=parseInt(_e.key,10)-1;lt<I&&(_e.preventDefault(),N.setFocusedSlot(lt))}break;case"+":case"=":_e.preventDefault(),N.zoom(.25);break;case"-":case"_":_e.preventDefault(),N.zoom(-.25);break;case"0":_e.preventDefault(),B==="compare"?ie():N.resetView();break;case" ":case"Spacebar":Fe!=null&&Fe.isVideo()&&(_e.preventDefault(),Fe.toggleVideoPlayback());break;case"s":case"S":B==="compare"&&(_e.preventDefault(),N.toggleSyncMode());break}};return window.addEventListener("keydown",ue),()=>window.removeEventListener("keydown",ue)},[e,B,t.length,t,O,oe,N,i,I,ae,Q,se,ie]);const ce=b.useCallback(()=>{if(E.current)if(P){const ue=lEe();ue==null||ue.catch(()=>{})}else{const ue=aEe(E.current);ue==null||ue.catch(()=>{})}},[P]);b.useEffect(()=>{const ue=()=>{k(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",ue),()=>document.removeEventListener("fullscreenchange",ue)},[]);const ge=b.useCallback(ue=>{ue.target===ue.currentTarget&&i()},[i]),Se=b.useCallback(ue=>{B==="edit"?se(ue):B==="single"?N.goTo(ue):N.addToCompare(ue,oe)},[B,N,oe,se]),Ae=b.useCallback(ue=>{D(ue),N.setSlotCount(ue)},[N]),Le=b.useCallback((ue,_e)=>ue==="grid"?_e<=2?"layout-horizontal":"layout-grid":`layout-${ue}`,[]),it=b.useCallback(()=>{const ue=t[O];ue&&p&&p(ue)},[t,O,p]),Te=b.useCallback(async()=>{const ue=t[O];if(!ue)return;const _e=ue.type==="image"?zn(ue.url):ue.url;if(_e.startsWith("blob:")){const{unifiedCacheService:lt}=await xn(async()=>{const{unifiedCacheService:me}=await Promise.resolve().then(()=>du);return{unifiedCacheService:me}},void 0,import.meta.url),{downloadFromBlob:Ht}=await xn(async()=>{const{downloadFromBlob:me}=await Promise.resolve().then(()=>_O);return{downloadFromBlob:me}},void 0,import.meta.url),At=_e.indexOf("#"),le=At>0?_e.substring(At+1):null;if(le&&le.startsWith("merged-video-")){const me=await lt.getCachedBlob(le);if(me){const ke=me.type||"video/webm",Oe=ke.startsWith("video/mp4")?"mp4":ke.startsWith("video/webm")?"webm":"bin";Ht(me,`merged-video-${Date.now()}.${Oe}`);return}}try{const ke=await(await fetch(_e)).blob(),Oe=ke.type.startsWith("video/mp4")?"mp4":ke.type.startsWith("video/webm")?"webm":ke.type.startsWith("audio/mpeg")?"mp3":ke.type.startsWith("audio/wav")?"wav":ke.type.startsWith("audio/")?"m4a":ke.type.startsWith("image/")?"png":"bin";Ht(ke,`${ue.type}_${Date.now()}.${Oe}`)}catch(me){console.error("[UnifiedMediaViewer] Failed to fetch blob URL:",me)}return}const{smartDownload:xe,buildDownloadFilename:Fe}=await xn(async()=>{const{smartDownload:lt,buildDownloadFilename:Ht}=await Promise.resolve().then(()=>bnt);return{smartDownload:lt,buildDownloadFilename:Ht}},void 0,import.meta.url);await xe([{url:_e,type:ue.type,filename:ue.type==="audio"?Fe(ue.title,"audio","mp3"):void 0,audioMetadata:ue.type==="audio"?{title:ue.title,prompt:ue.prompt,tags:ue.tags,coverUrl:ue.posterUrl,artist:ue.artist,album:ue.album}:void 0}])},[t,O]),Re=b.useCallback(()=>{const ue=t[O];ue&&ue.type==="image"&&(v?(J(ue),N.setMode("edit")):y&&y(ue))},[t,O,y,v,N,J]),ht=b.useCallback(ue=>{if(ue==="edit"){const _e=t[O];_e&&_e.type==="image"&&J(_e)}N.setMode(ue)},[t,O,N,J]),Ze=b.useCallback(()=>{F.current.clear(),J(null),N.setMode("single")},[N,J]),Ge=b.useCallback(()=>{var ue;(ue=_.current)==null||ue.reset()},[]),pt=b.useCallback(()=>{var ue;(ue=_.current)==null||ue.save()},[]),at=b.useCallback(ue=>{const _e=M.current;w&&_e&&w(ue,_e),Ze()},[w,Ze]),ct=b.useCallback(ue=>{C&&C(ue),Ze()},[C,Ze]),nt=b.useCallback((ue,_e)=>{V.current[ue]=_e},[]),It=b.useCallback((ue,_e)=>{j.current||(j.current=!0,V.current.forEach((xe,Fe)=>{Fe!==ue&&(xe!=null&&xe.isVideo())&&(_e?xe.playVideo():xe.pauseVideo())}),setTimeout(()=>{j.current=!1},50))},[]),Lt=b.useCallback((ue,_e)=>{j.current||(j.current=!0,V.current.forEach((xe,Fe)=>{Fe!==ue&&(xe!=null&&xe.isVideo())&&xe.setVideoTime(_e)}),setTimeout(()=>{j.current=!1},50))},[]),dt=()=>{const ue=t[O]||null;return g.jsxs("div",{className:"unified-viewer__single",children:[t.length>1&&g.jsx("button",{className:"unified-viewer__nav unified-viewer__nav--prev",onClick:N.goToPrev,"aria-label":"上一个",children:g.jsx(x2,{size:32})}),g.jsx(nO,{ref:H,item:ue,zoomLevel:K,panOffset:Z,videoAutoPlay:d,videoLoop:f,onZoomChange:N.setZoomLevel,onPanChange:()=>{},onInsertToCanvas:p?it:void 0,onDownload:Te,onEdit:y?Re:void 0}),t.length>1&&g.jsx("button",{className:"unified-viewer__nav unified-viewer__nav--next",onClick:N.goToNext,"aria-label":"下一个",children:g.jsx(gY,{size:32})})]})},wt=()=>{const ue=Le(U,I);return g.jsx("div",{className:`unified-viewer__compare ${ue}`,children:Array.from({length:I}).map((_e,xe)=>{const Fe=$[xe],lt=typeof Fe=="number"?t[Fe]:null;return g.jsx(nO,{ref:Ht=>nt(xe,Ht),item:lt,slotIndex:xe,isFocused:oe===xe,zoomLevel:Y?K:void 0,panOffset:Y?Z:void 0,onClick:()=>N.setFocusedSlot(xe),onClose:I>2?()=>N.removeFromCompare(xe):void 0,videoAutoPlay:d,videoLoop:f,onZoomChange:Y?N.setZoomLevel:void 0,onPanChange:Y?N.setPan:void 0,isCompareMode:!0,isSyncMode:Y,onVideoPlayStateChange:Y?Ht=>It(xe,Ht):void 0,onVideoTimeUpdate:Y?Ht=>Lt(xe,Ht):void 0},xe)})})},mt=()=>{const ue=R||t[O];return!ue||ue.type!=="image"?null:g.jsx("div",{className:"unified-viewer__edit",children:g.jsx(Zle,{ref:_,imageUrl:ue.url,showOverwrite:x,onOverwrite:w?at:void 0,onInsert:C?ct:void 0})})},Bt=t[O]||null;if(!e||t.length===0)return null;const He=()=>{switch(B){case"edit":return mt();case"compare":return wt();default:return dt()}},we=g.jsx("div",{ref:E,className:`unified-viewer ${c} ${P?"unified-viewer--fullscreen":""} ${B==="edit"?"unified-viewer--edit-mode":""}`,onClick:ge,children:g.jsxs("div",{className:"unified-viewer__container",children:[g.jsx(Ktt,{mode:B,currentIndex:O,totalCount:t.length,slotCount:I,compareLayout:U,syncMode:Y,onModeChange:ht,onSlotCountChange:Ae,onLayoutChange:N.setCompareLayout,onSyncToggle:N.toggleSyncMode,onResetView:B==="compare"?ie:N.resetView,onClose:i,onFullscreen:ce,isImage:(Bt==null?void 0:Bt.type)==="image",showEditButton:v||!!y,onBackToPreview:Ze,onResetEdit:Ge,onSaveEdit:pt}),g.jsx("div",{className:"unified-viewer__content",children:He()}),s&&t.length>1&&g.jsx(Gtt,{items:t,mode:B==="edit"?"single":B,currentIndex:O,compareIndices:$,onThumbnailClick:Se})]})});return Ui.createPortal(we,document.body)},gpt=Object.freeze(Object.defineProperty({__proto__:null,UnifiedMediaViewer:Hg,default:Hg},Symbol.toStringTag,{value:"Module"})),Jle=({visible:e,imageUrl:t,onClose:n,onSave:r,onOverwrite:i,onInsert:o,showOverwrite:s=!1})=>{const a=b.useRef(null);if(b.useEffect(()=>{var c;e||(c=a.current)==null||c.reset()},[e]),!e)return null;const l=g.jsxs("div",{className:"image-editor",style:{zIndex:Eu.DIALOG_AI_IMAGE},"data-testid":"image-editor",children:[g.jsx("div",{className:"image-editor__backdrop",onClick:n}),g.jsx("div",{className:"image-editor__container",children:g.jsx(dI,{ref:a,imageUrl:t,showOverwrite:s,onOverwrite:i,onInsert:o,onClose:n,onSave:r})})]});return Ui.createPortal(l,document.body)},ypt=Object.freeze(Object.defineProperty({__proto__:null,ASPECT_RATIO_PRESETS:qle,CropPanel:Yle,DEFAULT_FILTER_PARAMS:Zu,FILTER_PRESETS:rO,FilterPanel:Xle,ImageEditor:Jle,ImageEditorCore:dI},Symbol.toStringTag,{value:"Module"})),Xtt=({className:e,selectedPlaylistId:t,allCount:n,allTracksCount:r,allTracksLabel:i="全部语音",tempTabs:o=[],playlists:s,playlistItems:a,onSelect:l,onCreate:c,onRename:u,onDelete:d,allLabel:f="全部音频",createLabel:p="新建播放列表"})=>{const{contextMenu:y,open:v,close:w}=H3(),C=b.useMemo(()=>typeof u=="function"||typeof d=="function",[d,u]),x=b.useMemo(()=>[{key:"create",label:"新建播放列表",icon:g.jsx(ic,{size:14}),onSelect:()=>c()},{key:"rename",label:"重命名",icon:g.jsx(oR,{size:14}),disabled:I=>I.isSystem||!u,onSelect:I=>u==null?void 0:u(I)},{key:"delete",label:"删除播放列表",icon:g.jsx(aR,{size:14}),danger:!0,disabled:I=>I.isSystem||!d,onSelect:I=>d==null?void 0:d(I)}],[c,d,u]),E=b.useMemo(()=>s.find(I=>I.id===ul)||null,[s]),_=b.useMemo(()=>s.filter(I=>I.id!==ul),[s]);return g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:Je("audio-playlist-tabs",e),children:[g.jsxs("button",{type:"button",className:Je("audio-playlist-tabs__chip",{"audio-playlist-tabs__chip--active":t===hl}),onClick:()=>l(hl),onContextMenu:C?I=>{I.preventDefault(),I.stopPropagation(),v(I,{id:hl,name:f,createdAt:0,updatedAt:0,isSystem:!0})}:void 0,children:[g.jsx(ov,{size:14}),g.jsx("span",{children:f}),g.jsx("span",{className:"audio-playlist-tabs__count",children:n})]}),typeof r=="number"?g.jsxs("button",{type:"button",className:Je("audio-playlist-tabs__chip",{"audio-playlist-tabs__chip--active":t===iV}),onClick:()=>l(iV),children:[g.jsx(yS,{size:14}),g.jsx("span",{children:i}),g.jsx("span",{className:"audio-playlist-tabs__count",children:r})]}):null,E?g.jsxs("button",{type:"button",className:Je("audio-playlist-tabs__chip",{"audio-playlist-tabs__chip--active":t===E.id}),onClick:()=>l(E.id),onContextMenu:C?I=>{I.preventDefault(),I.stopPropagation(),v(I,E)}:void 0,children:[g.jsx(vS,{size:14}),g.jsx("span",{children:E.name}),g.jsx("span",{className:"audio-playlist-tabs__count",children:(a[E.id]||[]).length})]}):null,o.map(I=>g.jsxs("button",{type:"button",className:Je("audio-playlist-tabs__chip",{"audio-playlist-tabs__chip--active":t===I.id}),onClick:()=>l(I.id),children:[I.type==="reading"?g.jsx(yS,{size:14}):g.jsx(ov,{size:14}),g.jsx("span",{children:I.label}),g.jsx("span",{className:"audio-playlist-tabs__count",children:I.count})]},I.id)),_.map(I=>{const D=(a[I.id]||[]).length,P=C;return g.jsxs("button",{type:"button",className:Je("audio-playlist-tabs__chip",{"audio-playlist-tabs__chip--active":t===I.id}),onClick:()=>l(I.id),onContextMenu:P?k=>{k.preventDefault(),k.stopPropagation(),v(k,I)}:void 0,children:[g.jsx(ov,{size:14}),g.jsx("span",{children:I.name}),g.jsx("span",{className:"audio-playlist-tabs__count",children:D})]},I.id)}),g.jsxs("button",{type:"button",className:"audio-playlist-tabs__create",onClick:c,children:[g.jsx(ic,{size:14}),g.jsx("span",{children:p})]})]}),g.jsx(W3,{state:y,items:x,onClose:w})]})},tT="github_sync_master_index",nT="github_sync_master_gist_id";class Ztt{constructor(){this.masterIndex=null,this.masterGistId=null,this.initialized=!1}async initialize(){this.initialized||(this.masterIndex=await er.get(tT),this.masterGistId=await er.get(nT),this.initialized=!0,fe("ShardRouter initialized",{hasMasterIndex:!!this.masterIndex,masterGistId:this.masterGistId?xa(this.masterGistId):null,shardCount:this.masterIndex?Object.keys(this.masterIndex.shards).length:0}))}getMasterIndex(){return this.masterIndex}getMasterGistId(){return this.masterGistId}async setMasterGistId(t){this.masterGistId=t,await er.set(nT,t)}isConfigured(){return!!this.masterIndex&&!!this.masterGistId}async loadMasterIndexFromRemote(){if(!this.masterGistId)return fe("No master gist ID configured"),null;try{const t=await yt.getGistFileContent(Is.MASTER_INDEX,this.masterGistId);if(!t)return fe("No master index found in remote"),null;const n=JSON.parse(t);return this.masterIndex=n,await this.saveMasterIndexLocally(),fe("Loaded master index from remote",{shards:Object.keys(n.shards).length,files:Object.keys(n.fileIndex).length}),n}catch(t){return vn("Failed to load master index",t instanceof Error?t:new Error(String(t))),null}}async saveMasterIndexLocally(){this.masterIndex&&await er.set(tT,this.masterIndex)}async saveMasterIndexToRemote(){if(!this.masterIndex||!this.masterGistId)throw new Error("Master index or gist ID not configured");QM(this.masterIndex),await yt.updateGistFiles({[Is.MASTER_INDEX]:JSON.stringify(this.masterIndex,null,2)},this.masterGistId),await this.saveMasterIndexLocally(),fe("Saved master index to remote")}async initializeMasterIndex(t){if(this.masterIndex)return this.masterIndex;if(this.masterIndex=XQe(t),!this.masterGistId)throw new Error("Master gist ID must be set before initializing index");return await this.saveMasterIndexLocally(),fe("Initialized new master index"),this.masterIndex}getShardForFile(t){if(!this.masterIndex)return null;const n=this.masterIndex.fileIndex[t];return n&&this.masterIndex.shards[n.shardId]||null}getFileIndexEntry(t){return this.masterIndex&&this.masterIndex.fileIndex[t]||null}isFileSynced(t){return this.getFileIndexEntry(t)!==null}findActiveShard(t){if(!this.masterIndex)return null;const n=Object.values(this.masterIndex.shards).filter(r=>r.status==="active").sort((r,i)=>i.fileCount-r.fileCount);for(const r of n)if(QQe(r,t))return r;return null}async createShard(t){if(!this.masterIndex||!this.masterGistId)throw new Error("Master index not initialized");const n=Object.keys(this.masterIndex.shards).length+1,r=t||eet(n);if(this.masterIndex.shards[r])throw new Error(`Shard alias "${r}" already exists`);const i=`${jC.SHARD} #${n} (${r})`,o=Sle(r,this.masterGistId),s=await pi.getPassword(),a=JSON.stringify(o,null,2),l=await Nn.encrypt(a,this.masterGistId,s||void 0),c=await yt.createSyncGist({[Is.SHARD_MANIFEST]:l});try{await yt.updateGistFiles({[Is.SHARD_MANIFEST]:l},c.id)}catch(d){Pt("Failed to update shard description",{error:String(d)})}const u=ZQe(c.id,r,n);return u.description=i,this.masterIndex.shards[r]=u,QM(this.masterIndex),fe("Created new shard",{alias:r,gistId:xa(c.id),order:n}),u}async allocateFile(t){if(!this.masterIndex)throw new Error("Master index not initialized");const n=this.findActiveShard(t);return n?{shard:n,isNewShard:!1}:{shard:await this.createShard(),isNewShard:!0}}async allocateFiles(t){if(!this.masterIndex)throw new Error("Master index not initialized");const n=new Map,r=[];let i=null,o=0,s=0;const a=Object.values(this.masterIndex.shards).filter(l=>l.status==="active").sort((l,c)=>c.fileCount-l.fileCount);a.length>0&&(i=a[0],o=i.fileCount,s=i.totalSize);for(const l of t){const c=this.masterIndex.fileIndex[l.url];if(c){const d=this.masterIndex.shards[c.shardId];if(d){n.set(l.url,d);continue}}if(!i||o>=bs.FILE_LIMIT||s+l.size>bs.SIZE_LIMIT){const d=await this.createShard();r.push(d),i=d,o=0,s=0}n.set(l.url,i),o++,s+=l.size}return fe("Batch allocation completed",{totalFiles:t.length,newShardsCreated:r.length}),{allocations:n,newShards:r}}registerFile(t,n,r,i,o){if(!this.masterIndex)throw new Error("Master index not initialized");const s={shardId:n,filename:r,size:i,type:o,syncedAt:Date.now()};this.masterIndex.fileIndex[t]=s;const a=this.masterIndex.shards[n];a&&(a.fileCount++,a.totalSize+=i,a.updatedAt=Date.now(),a.fileCount>=bs.FILE_LIMIT&&(a.status="full",fe("Shard is now full",{shardId:n})))}unregisterFile(t){if(!this.masterIndex)return null;const n=this.masterIndex.fileIndex[t];if(!n)return null;delete this.masterIndex.fileIndex[t];const r=this.masterIndex.shards[n.shardId];return r&&(r.fileCount=Math.max(0,r.fileCount-1),r.totalSize=Math.max(0,r.totalSize-n.size),r.updatedAt=Date.now(),r.status==="full"&&r.fileCount<bs.FILE_LIMIT&&(r.status="active",fe("Shard reactivated",{shardId:n.shardId}))),n}getShard(t){return this.masterIndex&&this.masterIndex.shards[t]||null}getAllShards(){return this.masterIndex?Object.values(this.masterIndex.shards):[]}async updateShardAlias(t,n){if(!this.masterIndex)throw new Error("Master index not initialized");const r=this.masterIndex.shards[t];if(!r)throw new Error(`Shard "${t}" not found`);if(t!==n&&this.masterIndex.shards[n])throw new Error(`Alias "${n}" already exists`);for(const i of Object.keys(this.masterIndex.fileIndex)){const o=this.masterIndex.fileIndex[i];o.shardId===t&&(o.shardId=n)}for(const i of this.masterIndex.tombstones)i.shardId===t&&(i.shardId=n);delete this.masterIndex.shards[t],r.alias=n,r.description=`${jC.SHARD} #${r.order} (${n})`,r.updatedAt=Date.now(),this.masterIndex.shards[n]=r,fe("Updated shard alias",{old:t,new:n})}archiveShard(t){if(!this.masterIndex)throw new Error("Master index not initialized");const n=this.masterIndex.shards[t];if(!n)throw new Error(`Shard "${t}" not found`);n.status="archived",n.updatedAt=Date.now(),fe("Archived shard",{shardId:t})}reactivateShard(t){if(!this.masterIndex)throw new Error("Master index not initialized");const n=this.masterIndex.shards[t];if(!n)throw new Error(`Shard "${t}" not found`);n.fileCount>=bs.FILE_LIMIT?n.status="full":n.status="active",n.updatedAt=Date.now(),fe("Reactivated shard",{shardId:t})}getStats(){if(!this.masterIndex)return{totalShards:0,activeShards:0,fullShards:0,archivedShards:0,totalFiles:0,totalSize:0};const t=Object.values(this.masterIndex.shards);return{totalShards:t.length,activeShards:t.filter(n=>n.status==="active").length,fullShards:t.filter(n=>n.status==="full").length,archivedShards:t.filter(n=>n.status==="archived").length,totalFiles:Object.keys(this.masterIndex.fileIndex).length,totalSize:t.reduce((n,r)=>n+r.totalSize,0)}}async clearLocalCache(){this.masterIndex=null,this.masterGistId=null,this.initialized=!1,await er.remove(tT),await er.remove(nT),fe("Cleared local cache")}destroy(){this.masterIndex=null,this.masterGistId=null,this.initialized=!1}}const vt=new Ztt;function rT(){return localStorage.getItem(bd)||"unknown"}class Jtt{constructor(){this.syncingUrls=new Set}async uploadMedia(t,n){const r=Date.now(),i={success:!0,uploaded:0,downloaded:0,deleted:0,skipped:0,details:[]};if(await vt.initialize(),!vt.isConfigured())return i.success=!1,i.error="分片系统未配置",i;const o=t.filter(f=>this.syncingUrls.has(f.url)?(i.skipped++,i.details.push({url:f.url,action:"skip",success:!0,error:"正在同步中"}),!1):vt.isFileSynced(f.url)?(i.skipped++,i.details.push({url:f.url,action:"skip",success:!0,error:"已同步"}),!1):!0);if(o.length===0)return i;const s=await this.getFileSizes(o),a=await vt.allocateFiles(s),l=this.groupByShards(o,a.allocations),c=Object.keys(l);for(let f=0;f<c.length;f+=bs.CONCURRENCY){const p=c.slice(f,f+bs.CONCURRENCY);await Promise.all(p.map(y=>this.uploadToShard(y,l[y],i,n)))}await vt.saveMasterIndexToRemote(),i.success=i.uploaded>0||i.skipped>0;const u=i.details.filter(f=>!f.success).length,d=Date.now()-r;return fe("Upload completed",{uploaded:i.uploaded,skipped:i.skipped,failed:u,duration:d}),Jr("分片上传完成",{uploaded:i.uploaded,skipped:i.skipped,failed:u,duration:d}),i}async getFileSizes(t){const n=[];for(const r of t){let i=r.size||0;if(!i){const o=await yn.getCachedBlob(r.url);i=(o==null?void 0:o.size)||0}n.push({url:r.url,size:i})}return n}groupByShards(t,n){const r={};for(const i of t){const o=n.get(i.url);o&&(r[o.alias]||(r[o.alias]=[]),r[o.alias].push(i))}return r}async uploadToShard(t,n,r,i){const o=vt.getShard(t);if(!o){for(const l of n)r.details.push({url:l.url,action:"upload",success:!1,error:`分片 ${t} 不存在`});return}const s={},a=[];for(const l of n){this.syncingUrls.add(l.url);try{const c=await this.prepareMediaForUpload(l);if(c.success&&c.content){const u=`media_${ng(l.url)}.json`;s[u]=c.content,a.push(l),vt.registerFile(l.url,t,u,c.size,l.type),r.details.push({url:l.url,action:"upload",success:!0,shardId:t}),r.uploaded++,i==null||i(r.uploaded+r.skipped,r.uploaded+r.skipped+n.length,l.url,"uploading")}else r.details.push({url:l.url,action:"upload",success:!1,error:c.error||"准备上传失败"})}catch(c){vn(`Failed to prepare: ${l.url}`,c instanceof Error?c:new Error(String(c))),r.details.push({url:l.url,action:"upload",success:!1,error:c instanceof Error?c.message:"上传失败"})}finally{this.syncingUrls.delete(l.url)}}if(Object.keys(s).length>0)try{const l=await this.getOrCreateShardManifest(o);for(const y of a){const v=`media_${ng(y.url)}.json`;l.files[v]={url:y.url,type:y.type,size:y.size||0,mimeType:y.mimeType||"",syncedAt:Date.now(),syncedFromDevice:rT()}}l.updatedAt=Date.now();const c=JSON.stringify(l,null,2),u=vt.getMasterGistId();if(u){const y=await pi.getPassword();s[Is.SHARD_MANIFEST]=await Nn.encrypt(c,u,y||void 0)}else s[Is.SHARD_MANIFEST]=c;const d=Object.values(s).reduce((y,v)=>y+v.length,0),f=Object.keys(s).length;fe("Uploading to shard",{shardId:t,fileCount:f,totalSizeMB:(d/1024/1024).toFixed(2)});const p=8*1024*1024;d>p?(fe("Total size exceeds limit, splitting into batches"),await this.uploadInBatches(s,o.gistId,p)):await yt.updateGistFiles(s,o.gistId),fe("Uploaded files to shard",{count:a.length,shardId:t})}catch(l){vn(`Failed to update shard: ${t}`,l instanceof Error?l:new Error(String(l)));for(const c of a)vt.unregisterFile(c.url);for(const c of a){const u=r.details.find(d=>d.url===c.url);u&&(u.success=!1,u.error="批量上传失败"),r.uploaded--}}}async uploadInBatches(t,n,r){const i=Object.entries(t);let o={},s=0,a=0;for(const[l,c]of i){const u=c.length;if(u>r){Object.keys(o).length>0&&(fe("Uploading batch",{batch:a+1,fileCount:Object.keys(o).length}),await yt.updateGistFiles(o,n),o={},s=0,a++),fe("Uploading large file",{filename:l,sizeMB:(u/1024/1024).toFixed(2)}),await yt.updateGistFiles({[l]:c},n),a++;continue}s+u>r&&Object.keys(o).length>0&&(fe(`ShardSyncService] Uploading batch ${a+1}: ${Object.keys(o).length} files`),await yt.updateGistFiles(o,n),o={},s=0,a++),o[l]=c,s+=u}Object.keys(o).length>0&&(fe("Uploading final batch",{batch:a+1,fileCount:Object.keys(o).length}),await yt.updateGistFiles(o,n))}async prepareMediaForUpload(t){const{url:n,type:r,source:i,originalUrl:o,mimeType:s}=t;let a=null;if(i==="local"?a=await yn.getCachedBlob(n):i==="external"&&(a=await yn.getCachedBlob(n)),!a||a.size===0)return{success:!1,size:0,error:"无法获取媒体文件"};if(a.size>eO)return{success:!1,size:a.size,error:`文件过大(${K2(a.size)})`};const l=await Ole(a),c={url:n,type:r,source:i,mimeType:s||a.type,size:a.size,base64Data:l,syncedAt:Date.now(),syncedFromDevice:rT(),originalUrl:i==="external"?o:void 0},u=vt.getMasterGistId();if(!u)return{success:!1,size:a.size,error:"未配置主 Gist ID"};const d=await pi.getPassword(),f=JSON.stringify(c,null,2);return{success:!0,content:await Nn.encrypt(f,u,d||void 0),size:a.size}}async getOrCreateShardManifest(t){try{const r=await yt.getGistFileContent(Is.SHARD_MANIFEST,t.gistId);if(r){const i=vt.getMasterGistId();if(i){const o=await pi.getPassword(),s=await Nn.decrypt(r,i,o||void 0);return JSON.parse(s)}return JSON.parse(r)}}catch(r){Pt("Failed to get shard manifest",{shard:t.alias,error:String(r)})}const n=vt.getMasterGistId();if(!n)throw new Error("Master gist ID not configured");return Sle(t.alias,n)}async downloadMedia(t,n){const r={success:!0,uploaded:0,downloaded:0,deleted:0,skipped:0,details:[]};await vt.initialize();for(let o=0;o<t.length;o++){const s=t[o];if(n==null||n(o+1,t.length,s,"downloading"),(await yn.getCacheInfo(s)).isCached){r.skipped++,r.details.push({url:s,action:"skip",success:!0,error:"已缓存"});continue}const l=vt.getFileIndexEntry(s);if(!l){r.details.push({url:s,action:"download",success:!1,error:"文件未同步"});continue}const c=vt.getShard(l.shardId);if(!c){r.details.push({url:s,action:"download",success:!1,error:`分片 ${l.shardId} 不存在`});continue}try{const u=await yt.getGistFileContent(l.filename,c.gistId);if(!u){r.details.push({url:s,action:"download",success:!1,error:"文件不存在"});continue}const d=vt.getMasterGistId();if(!d){r.details.push({url:s,action:"download",success:!1,error:"未配置主 Gist ID"});continue}const f=await pi.getPassword(),p=await Nn.decrypt(u,d,f||void 0),y=JSON.parse(p),v=Rle(y.base64Data,y.mimeType);if(!v||v.size===0){r.details.push({url:s,action:"download",success:!1,error:"文件数据无效"});continue}await yn.cacheToCacheStorageOnly(s,v),r.downloaded++,r.details.push({url:s,action:"download",success:!0,shardId:l.shardId}),fe("Downloaded and cached",{url:s})}catch(u){vn(`Failed to download: ${s}`,u instanceof Error?u:new Error(String(u))),r.details.push({url:s,action:"download",success:!1,error:u instanceof Error?u.message:"下载失败"})}}r.success=r.downloaded>0||r.skipped>0;const i=r.details.filter(o=>!o.success).length;return r.downloaded>0?Jr("分片下载完成",{downloaded:r.downloaded,skipped:r.skipped,failed:i}):i>0&&Pt("分片下载部分失败",{downloaded:r.downloaded,skipped:r.skipped,failed:i}),r}async softDeleteMedia(t){const n={success:!0,uploaded:0,downloaded:0,deleted:0,skipped:0,details:[]};await vt.initialize();const r=vt.getMasterIndex();if(!r)return n.success=!1,n.error="主索引未加载",n;const i=rT();for(const o of t){const s=vt.getFileIndexEntry(o);if(!s){n.skipped++,n.details.push({url:o,action:"skip",success:!0,error:"文件未同步"});continue}const a=JQe(o,s.shardId,s.filename,s.size,i);r.tombstones.push(a),vt.unregisterFile(o),n.deleted++,n.details.push({url:o,action:"delete",success:!0,shardId:s.shardId}),fe("Soft deleted",{url:o})}return n.deleted>0&&await vt.saveMasterIndexToRemote(),n}async restoreMedia(t){await vt.initialize();const n=vt.getMasterIndex();if(!n)return!1;const r=n.tombstones.findIndex(s=>s.url===t);if(r===-1)return Pt("No tombstone found",{url:t}),!1;const i=n.tombstones[r],o=vt.getShard(i.shardId);if(!o)return Pt("Shard not found for restore",{shardId:i.shardId}),!1;try{const s=await yt.getGistFileContent(i.filename,o.gistId);if(!s)return Pt("File not found in shard",{filename:i.filename}),!1;const a=vt.getMasterGistId();if(!a)return Pt("Master gist ID not configured"),!1;const l=await pi.getPassword(),c=await Nn.decrypt(s,a,l||void 0),u=JSON.parse(c);return vt.registerFile(t,i.shardId,i.filename,i.size,u.type),n.tombstones.splice(r,1),await vt.saveMasterIndexToRemote(),fe("Restored",{url:t}),!0}catch(s){return vn(`Failed to restore: ${t}`,s instanceof Error?s:new Error(String(s))),!1}}async cleanupExpiredTombstones(){await vt.initialize();const t=vt.getMasterIndex();if(!t)return 0;const n=t.tombstones.filter(yV);if(n.length===0)return 0;fe("Cleaning up expired tombstones",{count:n.length});const r={};for(const i of n)r[i.shardId]||(r[i.shardId]=[]),r[i.shardId].push(i.filename);for(const[i,o]of Object.entries(r)){const s=vt.getShard(i);if(s)try{await yt.deleteGistFiles(o,s.gistId),fe("Deleted files from shard",{count:o.length,shardId:i})}catch(a){vn(`Failed to delete files from shard: ${i}`,a instanceof Error?a:new Error(String(a)))}}return t.tombstones=t.tombstones.filter(i=>!yV(i)),await vt.saveMasterIndexToRemote(),n.length}async getSyncedUrls(){await vt.initialize();const t=vt.getMasterIndex();return t?new Set(Object.keys(t.fileIndex)):new Set}async getTombstones(){await vt.initialize();const t=vt.getMasterIndex();return t?[...t.tombstones]:[]}async isInTombstones(t){await vt.initialize();const n=vt.getMasterIndex();return n?n.tombstones.some(r=>r.url===t):!1}}const Qu=new Jtt,Qtt=Object.freeze(Object.defineProperty({__proto__:null,shardSyncService:Qu},Symbol.toStringTag,{value:"Module"}));class ent{async initialize(){await vt.initialize()}isConfigured(){return vt.isConfigured()}async listShards(){return await vt.initialize(),vt.getAllShards()}async getShardDetails(t){await vt.initialize();const n=vt.getShard(t);if(!n)return null;let r=null;try{const i=await yt.getGistFileContent(Is.SHARD_MANIFEST,n.gistId);i&&(r=JSON.parse(i))}catch(i){Pt(`ShardManager] Failed to get manifest for shard ${t}:`,i)}return{info:n,manifest:r,fileCount:n.fileCount,totalSize:n.totalSize}}async renameShardAlias(t,n){await vt.initialize();const r=vt.getShard(t);if(!r)throw new Error(`分片 "${t}" 不存在`);if(!this.isValidAlias(n))throw new Error("别名只能包含字母、数字、连字符和下划线");await vt.updateShardAlias(t,n),`${jC.SHARD}${r.order}${n}`;try{const i=await yt.getGistFileContent(Is.SHARD_MANIFEST,r.gistId);if(i){const o=JSON.parse(i);o.shardId=n,o.updatedAt=Date.now(),await yt.updateGistFiles({[Is.SHARD_MANIFEST]:JSON.stringify(o,null,2)},r.gistId)}}catch(i){Pt("ShardManager] Failed to update shard manifest:",i)}await vt.saveMasterIndexToRemote(),fe(`ShardManager] Renamed shard "${t}" to "${n}"`)}isValidAlias(t){return/^[a-zA-Z0-9_-]+$/.test(t)&&t.length>=1&&t.length<=50}async archiveShard(t){if(await vt.initialize(),!vt.getShard(t))throw new Error(`分片 "${t}" 不存在`);vt.archiveShard(t),await vt.saveMasterIndexToRemote(),fe(`ShardManager] Archived shard "${t}"`)}async reactivateShard(t){if(await vt.initialize(),!vt.getShard(t))throw new Error(`分片 "${t}" 不存在`);vt.reactivateShard(t),await vt.saveMasterIndexToRemote(),fe(`ShardManager] Reactivated shard "${t}"`)}async deleteShard(t,n=!1){await vt.initialize();const r=vt.getShard(t);if(!r)throw new Error(`分片 "${t}" 不存在`);if(r.fileCount>0&&!n)throw new Error(`分片 "${t}" 还有 ${r.fileCount} 个文件,请先清空或使用强制删除`);if(r.fileCount>0&&n){const o=vt.getMasterIndex();if(o){const s=Object.entries(o.fileIndex).filter(([a,l])=>l.shardId===t).map(([a])=>a);s.length>0&&await Qu.softDeleteMedia(s)}}try{await yt.deleteGist(r.gistId)}catch(o){vn(`ShardManager] Failed to delete Gist ${r.gistId}:`,o)}const i=vt.getMasterIndex();i&&(delete i.shards[t],QM(i),await vt.saveMasterIndexToRemote()),fe(`ShardManager] Deleted shard "${t}"`)}async getShardStats(){await vt.initialize();const t=vt.getAllShards(),n=vt.getStats();let r=0;for(const o of t){const s=o.fileCount/bs.FILE_LIMIT,a=o.totalSize/bs.SIZE_LIMIT;r+=Math.max(s,a)}const i=t.length>0?r/t.length:0;return{totalShards:n.totalShards,activeShards:n.activeShards,fullShards:n.fullShards,archivedShards:n.archivedShards,totalFiles:n.totalFiles,totalSize:n.totalSize,averageUsage:i,shardDetails:t}}async mergeShards(t,n){await vt.initialize();const r={success:!0,movedFiles:0,errors:[]},i=vt.getShard(n);if(!i)return r.success=!1,r.errors.push(`目标分片 "${n}" 不存在`),r;if(i.status==="archived")return r.success=!1,r.errors.push(`目标分片 "${n}" 已归档`),r;const o=vt.getMasterIndex();if(!o)return r.success=!1,r.errors.push("主索引未加载"),r;const s=[];for(const l of t){if(l===n)continue;if(!vt.getShard(l)){r.errors.push(`源分片 "${l}" 不存在`);continue}for(const[u,d]of Object.entries(o.fileIndex))d.shardId===l&&s.push({url:u,sourceShardId:l,filename:d.filename})}const a=s.length;if(i.fileCount+a>bs.FILE_LIMIT)return r.success=!1,r.errors.push(`目标分片空间不足,需要 ${a} 个位置,只有 ${bs.FILE_LIMIT-i.fileCount} 个`),r;for(const l of s)try{const c=vt.getShard(l.sourceShardId),u=await yt.getGistFileContent(l.filename,c.gistId);if(!u){r.errors.push(`无法读取文件 ${l.filename}`);continue}const d=JSON.parse(u);await yt.updateGistFiles({[l.filename]:u},i.gistId);const f=o.fileIndex[l.url];if(f){const p=vt.getShard(l.sourceShardId);p&&(p.fileCount--,p.totalSize-=f.size),f.shardId=n,i.fileCount++,i.totalSize+=f.size}await yt.deleteGistFiles([l.filename],c.gistId),r.movedFiles++}catch(c){vn(`ShardManager] Failed to move file ${l.url}:`,c),r.errors.push(`移动文件失败: ${l.url}`)}return await vt.saveMasterIndexToRemote(),r.success=r.movedFiles>0,fe(`ShardManager] Merged ${r.movedFiles} files to shard "${n}"`),r}async validateShards(){await vt.initialize();const t=[],n=vt.getAllShards(),r=vt.getMasterIndex();if(!r)return{valid:!1,issues:[{shardId:"",type:"missing_gist",details:"主索引未加载"}]};for(const i of n){try{await yt.getGist(i.gistId)}catch(o){if(o instanceof cl&&o.statusCode===404){t.push({shardId:i.alias,type:"missing_gist",details:`Gist ${xa(i.gistId)} 不存在`});continue}}try{const o=await yt.getGist(i.gistId),s=Object.keys(o.files).filter(l=>l.startsWith("media_")&&l.endsWith(".json")),a=Object.entries(r.fileIndex).filter(([l,c])=>c.shardId===i.alias).map(([l,c])=>c.filename);s.length!==a.length&&t.push({shardId:i.alias,type:"count_mismatch",details:`索引记录 ${a.length} 个文件,实际 ${s.length} 个`});for(const l of a)s.includes(l)||t.push({shardId:i.alias,type:"missing_file",details:`文件 ${l} 在索引中但不在 Gist 中`});for(const l of s)a.includes(l)||t.push({shardId:i.alias,type:"orphan_file",details:`文件 ${l} 在 Gist 中但不在索引中`})}catch(o){vn(`ShardManager] Failed to validate shard ${i.alias}:`,o)}}return{valid:t.length===0,issues:t}}async repairOrphanFiles(){await vt.initialize();const n=(await this.validateShards()).issues.filter(o=>o.type==="orphan_file");if(n.length===0)return 0;let r=0;if(!vt.getMasterIndex())return 0;for(const o of n){const s=vt.getShard(o.shardId);if(!s)continue;const a=o.details.match(/文件 (.+) 在 Gist 中/);if(!a)continue;const l=a[1];try{const c=await yt.getGistFileContent(l,s.gistId);if(!c)continue;const u=JSON.parse(c),d=u.url,f=u.type,p=u.size||0;if(!d)continue;vt.registerFile(d,o.shardId,l,p,f),r++,fe(`ShardManager] Repaired orphan file: ${l} -> ${d}`)}catch(c){vn(`ShardManager] Failed to repair orphan file ${l}:`,c)}}return r>0&&await vt.saveMasterIndexToRemote(),r}async clearLocalCache(){await vt.clearLocalCache(),fe("ShardManager] Cleared local cache")}destroy(){vt.destroy()}}const $V=new ent,iT="github_sync_shard_enabled",tnt="0.5.0";class nnt{constructor(){this.shardingEnabled=!1,this.initialized=!1}async initialize(){this.initialized||(this.shardingEnabled=await er.get(iT)??!1,this.shardingEnabled&&await vt.initialize(),this.initialized=!0,fe("ShardedMediaSyncAdapter] Initialized, sharding enabled:",this.shardingEnabled))}isShardingEnabled(){return this.shardingEnabled}async enableSharding(){this.shardingEnabled=!0,await er.set(iT,!0),await vt.initialize(),fe("ShardedMediaSyncAdapter] Sharding enabled")}async disableSharding(){this.shardingEnabled=!1,await er.set(iT,!1),fe("ShardedMediaSyncAdapter] Sharding disabled")}async setupShardSystem(t){try{fe("ShardedMediaSyncAdapter] Setting up shard system..."),await vt.setMasterGistId(t),await vt.initialize();let n=await vt.loadMasterIndexFromRemote();return n||(n=await vt.initializeMasterIndex(tnt),await yt.updateGistFiles({[Is.MASTER_INDEX]:JSON.stringify(n,null,2)},t),fe("ShardedMediaSyncAdapter] Created new master index")),await this.enableSharding(),{success:!0}}catch(n){return vn("ShardedMediaSyncAdapter] Setup failed:",n),{success:!1,error:n instanceof Error?n.message:"设置失败"}}}async uploadMedia(t,n){if(await this.initialize(),this.shardingEnabled&&vt.isConfigured()){const r=await Qu.uploadMedia(t,n);return this.convertToLegacyResult(r)}else return fe("ShardedMediaSyncAdapter] Sharding not enabled, use mediaSyncService instead"),this.createEmptyResult()}async downloadMedia(t,n){if(await this.initialize(),this.shardingEnabled&&vt.isConfigured()){const r=await Qu.downloadMedia(t,n);return this.convertToLegacyResult(r)}else return fe("ShardedMediaSyncAdapter] Sharding not enabled, use mediaSyncService instead"),this.createEmptyResult()}async getSyncedUrls(){return await this.initialize(),this.shardingEnabled&&vt.isConfigured()?await Qu.getSyncedUrls():new Set}async softDeleteMedia(t){return await this.initialize(),!this.shardingEnabled||!vt.isConfigured()?{success:!1,uploaded:0,downloaded:0,deleted:0,skipped:0,error:"分片系统未启用",details:[]}:await Qu.softDeleteMedia(t)}async restoreMedia(t){return await this.initialize(),!this.shardingEnabled||!vt.isConfigured()?!1:await Qu.restoreMedia(t)}async getShardStats(){if(await this.initialize(),!this.shardingEnabled||!vt.isConfigured())return{enabled:!1};const t=await $V.getShardStats();return{enabled:!0,stats:{totalShards:t.totalShards,activeShards:t.activeShards,fullShards:t.fullShards,totalFiles:t.totalFiles,totalSize:t.totalSize}}}async cleanupExpiredTombstones(){return await this.initialize(),!this.shardingEnabled||!vt.isConfigured()?0:await Qu.cleanupExpiredTombstones()}convertToLegacyResult(t){return{succeeded:t.uploaded+t.downloaded,failed:t.details.filter(n=>!n.success&&n.action!=="skip").length,skipped:t.skipped,results:t.details.map(n=>({success:n.success,url:n.url,error:n.error})),totalSize:0,duration:0}}createEmptyResult(){return{succeeded:0,failed:0,skipped:0,results:[],totalSize:0,duration:0}}destroy(){$V.destroy(),this.initialized=!1}}const rnt=new nnt,Qle=Object.freeze(Object.defineProperty({__proto__:null,shardedMediaSyncAdapter:rnt},Symbol.toStringTag,{value:"Module"})),ece=b.createContext(null),N0={success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0,error:"GitHub Sync context is unavailable"},int={isConnected:!1,isConfigured:!1,syncStatus:"not_configured",isSyncing:!1,lastSyncTime:null,userInfo:null,error:"GitHub Sync context is unavailable",setToken:async()=>!1,clearToken:()=>{},sync:async()=>N0,pullFromRemote:async()=>N0,pushToRemote:async()=>N0,gistUrl:null,listGists:async()=>[],switchGist:async()=>N0,deleteGist:async()=>{},createNewGist:async()=>N0,config:null,updateConfig:async()=>{}};async function a2(e){if(fe("handleBoardSwitchAfterSync START",{success:e.success,downloaded:e.downloaded,uploaded:e.uploaded,remoteCurrentBoardId:e.remoteCurrentBoardId}),!e.success){fe("handleBoardSwitchAfterSync END (not successful)");return}try{const n=gs.getState().currentBoardId,r=gs.getAllBoardMetadata();fe("Current workspace state",{currentBoardId:n,totalBoards:r.length});let i=e.remoteCurrentBoardId;if(fe("Initial targetBoardId",{targetBoardId:i}),i||(r.length>0?(i=r[0].id,fe("Using first board as target",{targetBoardId:i,name:r[0].name})):fe("No boards available")),fe("Final targetBoardId",{targetBoardId:i}),!i){fe("handleBoardSwitchAfterSync END (no target)");return}const o=r.some(a=>a.id===i);if(fe("Target board exists in metadata",{targetExists:o}),o||Pt("Target board not found in available boards",{targetBoardId:i,availableIds:r.map(a=>a.id)}),!n){fe("DECISION: No current board, switching to target",{targetBoardId:i}),await gs.switchBoard(i),fe("handleBoardSwitchAfterSync END (switched from null)");return}if(i===n){fe("DECISION: Target board is current board, reloading");try{await gs.reloadBoard(i),fe("Board data reloaded successfully")}catch(a){vn("Failed to reload board data",a instanceof Error?a:new Error(String(a)))}fe("handleBoardSwitchAfterSync END (same board, reloaded)");return}const s=await gs.isDefaultEmptyBoard(n);fe("isCurrentDefaultEmpty",{isCurrentDefaultEmpty:s}),s?(fe("DECISION: Current board is default empty, auto-switching",{targetBoardId:i}),await gs.switchBoard(i),await gs.deleteBoard(n),fe("handleBoardSwitchAfterSync END (replaced default)")):(fe("DECISION: Current board is not default empty, keeping current"),fe("handleBoardSwitchAfterSync END (keep current)"))}catch(t){vn("handleBoardSwitchAfterSync failed",t instanceof Error?t:new Error(String(t)))}}function vpt({children:e}){const[t,n]=b.useState(!1),[r,i]=b.useState(!1),[o,s]=b.useState("not_configured"),[a,l]=b.useState(!1),[c,u]=b.useState(null),[d,f]=b.useState(null),[p,y]=b.useState(null),[v,w]=b.useState(null),[C,x]=b.useState(null),E=b.useRef(!1);b.useEffect(()=>{if(E.current)return;E.current=!0,fe("GitHubSyncProvider initializing"),(async()=>{const U=ai.hasToken();if(i(U),U){const{isValid:Y,userInfo:K}=await ai.validateAndGetUserInfo();if(n(Y),Y){f(K);const Z=await Kn.getConfig();if(w(Z),u(Z.lastSyncTime),x(Kn.getGistUrl()),Z.gistId){const oe=()=>{"requestIdleCallback"in window?window.requestIdleCallback(async()=>{await J()},{timeout:3e3}):setTimeout(async()=>{await J()},1e3)},J=async()=>{try{qc.refreshSyncStatus().catch(()=>{}),Tr("Auto-syncing from remote on page load (deferred)");const ae=await Kn.pullFromRemote();if(ae.success){Jr("Auto-sync from remote successful",ae.downloaded);const Q=await Kn.getConfig();u(Q.lastSyncTime),await a2(ae)}else Pt("Auto-sync from remote failed",{error:ae.error})}catch(ae){vn("Auto-sync from remote error",ae instanceof Error?ae:new Error(String(ae)))}};oe()}}else y("Token 无效,请重新配置")}s(Kn.getSyncStatus())})();const z=(U,Y)=>{s(U),l(U==="syncing"),U==="error"&&Y?y(Y):U==="synced"&&y(null)};Kn.addStatusListener(z);const N=()=>{document.visibilityState==="hidden"&&ai.hasToken()&&Kn.hasPendingChanges()&&(fe("Page hidden, triggering sync"),Kn.sync().catch(()=>{}))},B=U=>{if(Kn.getSyncStatus()==="syncing")return U.preventDefault(),U.returnValue="同步正在进行中,确定要离开吗?",U.returnValue;ai.hasToken()&&Kn.hasPendingChanges()&&(fe("Page unloading, triggering sync"),Kn.sync().catch(()=>{}))};document.addEventListener("visibilitychange",N),window.addEventListener("beforeunload",B),fe("Setting up workspace event subscription");const $=gs.observeEvents().subscribe({next:U=>{var K;const Y=["boardCreated","boardUpdated","boardDeleted","folderCreated","folderUpdated","folderDeleted"];if(ai.hasToken()&&Y.includes(U.type)&&(fe("Workspace changed, marking dirty",{eventType:U.type}),Kn.markDirty(),U.type==="boardDeleted")){const Z=(K=U.payload)==null?void 0:K.id;Z&&typeof Z=="string"?(fe("Syncing board deletion to remote",{boardId:Z}),Kn.recordLocalDeletion(Z).then(()=>Kn.syncBoardDeletion(Z)).then(oe=>{oe.success?Jr("Board moved to remote recycle bin",{boardId:Z}):Pt("Failed to sync deletion to remote",{boardId:Z,error:oe.error})}).catch(oe=>{vn("Failed to sync board deletion",oe instanceof Error?oe:new Error(String(oe)),{boardId:Z})})):Pt("boardDeleted event has invalid payload",{payload:U.payload})}},error:U=>{vn("Workspace event subscription error",U instanceof Error?U:new Error(String(U)))},complete:()=>{fe("Workspace event subscription completed")}});return fe("Workspace event subscription established"),()=>{Kn.removeStatusListener(z),document.removeEventListener("visibilitychange",N),window.removeEventListener("beforeunload",B),$.unsubscribe()}},[]);const _=b.useCallback(async j=>{try{if(y(null),!ai.isValidTokenFormat(j))return y("Token 格式无效"),!1;const{isValid:z,userInfo:N}=await ai.validateAndGetUserInfo(j);if(!z)return y("Token 无效或已过期"),!1;if(await ai.saveToken(j),!await ai.hasGistScope())return y("Token 缺少 gist 权限,请重新创建"),ai.clearToken(),!1;f(N);try{Tr("Auto-connecting and syncing..."),await Kn.saveConfig({gistId:null});const O=await Kn.sync(),$=await Kn.getConfig();w($),u($.lastSyncTime),x(Kn.getGistUrl()),O.success?(Jr("Auto-connect sync successful",{downloaded:O.downloaded,gistId:$.gistId?xa($.gistId):null}),await a2(O)):Pt("Auto-connect sync failed",{error:O.error})}catch(O){vn("Failed to auto-connect gist",O instanceof Error?O:new Error(String(O)))}return i(!0),n(!0),!0}catch(z){const N=z instanceof Error?z.message:"设置 Token 失败";return y(N),!1}},[]),I=b.useCallback(()=>{ai.clearToken(),Kn.disconnect(),i(!1),n(!1),f(null),s("not_configured"),u(null),x(null),w(null),y(null)},[]),D=b.useCallback(async()=>{if(a)return{success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0};y(null);const j=await Kn.sync();if(j.success){const z=await Kn.getConfig();if(u(z.lastSyncTime),x(Kn.getGistUrl()),w(z),j.downloaded.boards>0){const N=gs.getState().currentBoardId;if(N)try{await gs.reloadBoard(N)}catch(B){Pt("Failed to reload current board",{error:String(B)})}}await a2(j)}else j.error&&j.error!=="同步正在进行中"&&y(j.error);return j},[a]),P=b.useCallback(async()=>{if(a)return{success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0};y(null);const j=await Kn.pullFromRemote();if(j.success){const z=await Kn.getConfig();u(z.lastSyncTime),x(Kn.getGistUrl()),w(z),await a2(j)}else j.error&&j.error!=="同步正在进行中"&&y(j.error);return j},[a]),k=b.useCallback(async()=>{if(a)return{success:!1,uploaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},downloaded:{boards:0,prompts:0,tasks:0,media:0,knowledgeBase:0},conflicts:[],duration:0};y(null);const j=await Kn.pushToRemote();if(j.success){const z=await Kn.getConfig();u(z.lastSyncTime),x(Kn.getGistUrl()),w(z)}else j.error&&j.error!=="同步正在进行中"&&y(j.error);return j},[a]),R=b.useCallback(async j=>{await Kn.saveConfig(j);const z=await Kn.getConfig();w(z)},[]),T=b.useCallback(async()=>t?Kn.listSyncGists():[],[t]),M=b.useCallback(async j=>{y(null);const z=await Kn.switchToGist(j);if(z.success){const N=await Kn.getConfig();u(N.lastSyncTime),x(Kn.getGistUrl()),w(N)}else z.error&&z.error!=="同步正在进行中"&&y(z.error);return z},[]),F=b.useCallback(async j=>{await Kn.deleteGist(j);const z=await Kn.getConfig();z.gistId||(x(null),w(z),s("not_configured"))},[]),V=b.useCallback(async()=>{y(null);const j=await Kn.createNewGist();if(j.success){const z=await Kn.getConfig();u(z.lastSyncTime),x(Kn.getGistUrl()),w(z)}else j.error&&j.error!=="同步正在进行中"&&y(j.error);return j},[]),H={isConnected:t,isConfigured:r,syncStatus:o,isSyncing:a,lastSyncTime:c,userInfo:d,error:p,setToken:_,clearToken:I,sync:D,pullFromRemote:P,pushToRemote:k,gistUrl:C,listGists:T,switchGist:M,deleteGist:F,createNewGist:V,config:v,updateConfig:R};return g.jsx(ece.Provider,{value:H,children:e})}function ont(){return b.useContext(ece)??int}async function tce(){const e={id:CQe,name:"音乐播放器",description:"从素材库选择音频并后台播放,可与画布播放控件联动",icon:"🎵",category:"utilities",component:"music-player",defaultWidth:420,defaultHeight:640},{toolWindowService:t}=await xn(async()=>{const{toolWindowService:n}=await import("./tool-windows-Bf_pMml-.js").then(r=>r.b0);return{toolWindowService:n}},__vite__mapDeps([0]),import.meta.url);return t.openTool(e,{autoPin:!0}),!0}async function nce(e){var t,n,r,i,o,s;return await tce(),e.queue&&e.queue.length>0&&(e.queue.every(a=>Tv(a))?n2.setReadingQueue(e.queue,{queueId:(t=e.queueTab)==null?void 0:t.queueId,queueName:(n=e.queueTab)==null?void 0:n.queueName}):n2.setQueue(e.queue,{queueSource:e.playlist?"playlist":"canvas",playlistId:(r=e.playlist)==null?void 0:r.playlistId,playlistName:(i=e.playlist)==null?void 0:i.playlistName,queueId:(o=e.queueTab)==null?void 0:o.queueId,queueName:(s=e.queueTab)==null?void 0:s.queueName})),Tv(e.source)?n2.toggleReadingPlayback(e.source):await n2.togglePlayback(e.source),!0}const wpt=Object.freeze(Object.defineProperty({__proto__:null,openMusicPlayerTool:tce,openMusicPlayerToolAndPlay:nce},Symbol.toStringTag,{value:"Module"}));function fI(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}function rce(e){const t=new Uint8Array(2+e.length*2);t[0]=255,t[1]=254;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n),i=2+n*2;t[i]=r&255,t[i+1]=r>>8&255}return t}function Wg(...e){const t=e.reduce((i,o)=>i+o.length,0),n=new Uint8Array(t);let r=0;for(const i of e)n.set(i,r),r+=i.length;return n}function snt(e){return new Uint8Array([e>>21&127,e>>14&127,e>>7&127,e&127])}function ant(e){return(e[0]??0)<<21|(e[1]??0)<<14|(e[2]??0)<<7|(e[3]??0)}function uN(e){const t=new Uint8Array(10);t.set(fI(e.id.slice(0,4)),0);const n=e.data.length;return t[4]=n>>24&255,t[5]=n>>16&255,t[6]=n>>8&255,t[7]=n&255,Wg(t,e.data)}function j0(e,t){return t!=null&&t.trim()?uN({id:e,data:Wg(new Uint8Array([1]),rce(t.trim()))}):null}function lnt(e){return e!=null&&e.trim()?uN({id:"COMM",data:Wg(new Uint8Array([1]),fI("eng"),new Uint8Array([255,254,0,0]),rce(e.trim()))}):null}function cnt(e){if(e.length<10||e[0]!==73||e[1]!==68||e[2]!==51)return e;const t=ant(e.slice(6,10)),n=e[5]&16?10:0,r=10+t+n;return r>=e.length?e:e.slice(r)}async function unt(e){if(!e)return null;try{const t=await fetch(e,{referrerPolicy:"no-referrer"});if(!t.ok)return null;const n=await t.blob(),r=await n.arrayBuffer();return{bytes:new Uint8Array(r),mimeType:n.type||"image/jpeg"}}catch{return null}}async function dnt(e){const t=await unt(e);return t?uN({id:"APIC",data:Wg(new Uint8Array([0]),fI(t.mimeType),new Uint8Array([0,3,0]),t.bytes)}):null}function fnt(e,t){return e.type==="audio/mpeg"||e.type==="audio/mp3"||/\.mp3(?:$|[?#])/i.test(t)}async function ice(e,t,n){var p,y,v,w,C,x;if(!t||!fnt(e,n))return e;const r=(p=t.title)==null?void 0:p.trim(),i=(y=t.prompt)==null?void 0:y.trim(),o=(v=t.tags)==null?void 0:v.trim(),s=((w=t.artist)==null?void 0:w.trim())||"Aitu",a=((C=t.album)==null?void 0:C.trim())||"Aitu Generated",l=((x=t.year)==null?void 0:x.trim())||String(new Date().getFullYear()),c=(await Promise.all([Promise.resolve(j0("TIT2",r)),Promise.resolve(j0("TPE1",s)),Promise.resolve(j0("TALB",a)),Promise.resolve(j0("TCON",o)),Promise.resolve(j0("TYER",l)),Promise.resolve(lnt(i)),dnt(t.coverUrl)])).filter(E=>E!==null);if(c.length===0)return e;const u=cnt(new Uint8Array(await e.arrayBuffer())),d=Wg(...c),f=Wg(fI("ID3"),new Uint8Array([3,0,0]),snt(d.length));return new Blob([f,d,u],{type:e.type||"audio/mpeg"})}function dN(e={}){return{openedCount:0,downloadedCount:0,failedCount:0,...e}}function hnt(e){if(typeof window>"u"||typeof window.location>"u")return/^https?:\/\//i.test(e);try{return new URL(e,window.location.href).origin!==window.location.origin}catch{return!1}}function pnt(e){if(e instanceof TypeError)return!0;const t=e instanceof Error?e.message:String(e);return/Failed to fetch|Load failed|NetworkError/i.test(t)}function mnt(e,t){return hnt(e)&&pnt(t)}function gnt(e){return cK(e),dN({openedCount:1})}async function zV(e,t){try{return await t(),dN({downloadedCount:1})}catch(n){if(mnt(e,n))return gnt(e);throw n}}function fN(e,t,n,r){return`${MG(e||"")||t}${r||""}.${n}`}function ynt(e){return Math.min(100,Math.max(0,Math.round(e)))}function km(e,t){e===void 0||t===void 0||e(ynt(t))}function oce(e){return{title:e.title,prompt:e.prompt,tags:e.tags,coverUrl:e.coverUrl,artist:e.artist||"Aitu",album:e.album||"Aitu Generated"}}function sce(e){return e==="image"?"png":e==="video"?"mp4":"mp3"}function ace(e,t,n){if(e&&/^[a-z0-9]+$/i.test(e))return e.toLowerCase();const r=e?lo(e):"bin";if(r!=="bin")return r;const i=n?lo(n):"bin";return i!=="bin"?i:t}function vnt(e,t){const n=t.get(e)||0;if(t.set(e,n+1),n===0)return e;const r=e.lastIndexOf(".");return r<=0?`${e}_${n}`:`${e.slice(0,r)}_${n}${e.slice(r)}`}function hI(e){const t=e.type===ln.IMAGE?"image":e.type===ln.VIDEO?"video":"audio",n=ace(e.name,sce(t),e.url);return{url:e.url,type:t,filename:fN(e.name,t,n),audioMetadata:t==="audio"?oce({title:e.name,prompt:e.prompt,coverUrl:e.thumbnail,artist:e.modelName}):void 0}}function lce(e){return e.map(hI)}function wnt(e){var r,i,o,s;if(!((r=e.result)!=null&&r.url)&&!((o=(i=e.result)==null?void 0:i.urls)!=null&&o.length))return[];const t=e.type===Qt.IMAGE?"image":e.type===Qt.VIDEO?"video":"audio",n=(s=e.result.urls)!=null&&s.length?e.result.urls:[e.result.url];return n.map((a,l)=>{var f,p,y,v,w,C;const c=(p=(f=e.result)==null?void 0:f.clips)==null?void 0:p[l],u=(c==null?void 0:c.title)||((y=e.result)==null?void 0:y.title)||e.params.title||e.params.prompt,d=ace((v=e.result)==null?void 0:v.format,sce(t),a);return{url:a,type:t,filename:fN(u,t,d,n.length>1?`-${l+1}`:void 0),audioMetadata:e.type===Qt.AUDIO?oce({title:(c==null?void 0:c.title)||((w=e.result)==null?void 0:w.title)||e.params.title,prompt:e.params.prompt,tags:typeof e.params.tags=="string"?e.params.tags:void 0,coverUrl:(c==null?void 0:c.imageLargeUrl)||(c==null?void 0:c.imageUrl)||((C=e.result)==null?void 0:C.previewImageUrl),artist:e.params.model||e.params.mv}):void 0}})}async function cce(e,t,n){if(e.length===0)throw new Error("No files to download");const{default:r}=await xn(async()=>{const{default:d}=await import("./office-data-DMEex_0S.js").then(f=>f.j);return{default:d}},[],import.meta.url),i=new r,o=new Date().toISOString().slice(0,19).replace(/[T:]/g,"-"),s=t||`aitu_download_${o}.zip`,a=new Map;let l=0,c=0;if(km(n,0),await dK(e,async(d,f)=>{try{const p=d.type==="image"?zn(d.url):d.url,y=await fetch(p,{referrerPolicy:"no-referrer"});if(!y.ok){console.warn(`Failed to fetch ${p}: ${y.status}`);return}const v=await y.blob(),w=d.type==="audio"?await ice(v,d.audioMetadata,p):v,C=lo(p,w.type),x=d.type==="image"?"image":d.type==="video"?"video":"audio",E=vnt(d.filename||`${x}_${f+1}.${C}`,a);i.file(E,w),c+=1}catch(p){console.error("Failed to add file to zip:",p)}finally{l+=1,km(n,e.length>0?l/e.length*50:50)}},3),c===0)throw new Error("No files available to download");const u=await i.generateAsync({type:"blob"},d=>{km(n,50+d.percent/2)});return YC(u,s),km(n,100),dN({downloadedCount:c,failedCount:e.length-c})}async function FC(e,t,n){if(e.length===0)throw new Error("No files to download");if(e.length===1){const r=e[0],i=r.type==="image"?zn(r.url):r.url;if(r.type==="audio"){const l=await zV(i,async()=>{const c=await fetch(i,{referrerPolicy:"no-referrer"});if(!c.ok)throw new Error(`Failed to fetch ${i}: ${c.status}`);const u=await c.blob(),d=await ice(u,r.audioMetadata,i),f=lo(i,d.type)||"mp3",p=r.filename||`${r.type}_download.${f}`;YC(d,p)});return km(n,100),l}const o=lo(i)||(r.type==="image"?"png":r.type==="video"?"mp4":"mp3"),s=r.filename||`${r.type}_download.${o}`,a=await zV(i,async()=>uK(i,s));return km(n,100),a}else return cce(e,t,n)}const bnt=Object.freeze(Object.defineProperty({__proto__:null,buildAssetDownloadItem:hI,buildAssetDownloadItems:lce,buildDownloadFilename:fN,buildTaskDownloadItems:wnt,downloadAsZip:cce,smartDownload:FC},Symbol.toStringTag,{value:"Module"})),xnt=150,uce="media-library-view-mode",iO="media-library-grid-size";function UV(e,t="image/png"){const n=e.trim();if(!n||n.startsWith("data:")||n.startsWith("blob:")||n.startsWith("http://")||n.startsWith("https://")||n.startsWith("/")||n.startsWith("./")||n.startsWith("../"))return n||e;const r=n.replace(/\s+/g,"");return!/^[A-Za-z0-9+/=]+$/.test(r)||r.length<32?n:`data:${t};base64,${r}`}const HV=()=>{try{const e=localStorage.getItem(uce);if(e==="grid"||e==="compact"||e==="list")return e}catch{}return"grid"},Snt=()=>{try{const e=localStorage.getItem(iO);if(e){const t=parseInt(e,10);if(!isNaN(t)&&t>=80&&t<=300)return t}}catch{}return 180},Cnt=[{value:"ALL",label:"全部",icon:cI},{value:ln.IMAGE,label:"图片",icon:NC},{value:ln.VIDEO,label:"视频",icon:cg},{value:ln.AUDIO,label:"音频",icon:zv}],Ent=[{value:Lr.LOCAL,label:"本地",tooltip:"本地上传",icon:OT,countKey:"local"},{value:Lr.AI_GENERATED,label:"AI",tooltip:"AI生成",icon:Hv,countKey:"ai"}],_nt=[{value:_s.CHARACTER,label:"主体",tooltip:"主体素材",icon:VCe,countKey:"character"}],Int=[{id:"DATE",label:"时间",options:{asc:"DATE_ASC",desc:"DATE_DESC"},icons:{asc:h2e,desc:A2e},default:"DATE_DESC"},{id:"NAME",label:"名称",options:{asc:"NAME_ASC",desc:"NAME_DESC"},icons:{asc:r2e,desc:Qxe},default:"NAME_ASC"},{id:"SIZE",label:"大小",options:{asc:"SIZE_ASC",desc:"SIZE_DESC"},icons:{asc:o2e,desc:Zxe},default:"SIZE_DESC"}];function WV(){return{scope:null,selectedIds:new Set,deselectedIds:new Set}}function oT(e,t,n){var l;if(!t)return!1;const r=!t.activeType||e.type===t.activeType,i=!t.activeSource||e.source===t.activeSource,o=!t.activeCategory||(e.category||_s.GENERAL)===t.activeCategory,s=Cae(e,t.searchQuery);let a=!0;return t.playlistId&&(t.playlistId===hl?a=e.type===ln.AUDIO:a=((l=n.get(t.playlistId))==null?void 0:l.has(e.id))??!1),r&&i&&o&&s&&a}function Ant({selectedAssetId:e,onSelectAsset:t,onDoubleClick:n,onFileUpload:r,onUploadClick:i,storageStatus:o,onSelectionChange:s}){const{assets:a,filters:l,loading:c,setFilters:u,removeAssets:d,syncedUrls:f,loadSyncedUrls:p}=sN(),{playlists:y,favoriteAssetIds:v,playlistItems:w,createPlaylist:C,renamePlaylist:x,deletePlaylist:E,addAssetToPlaylist:_,removeAssetFromPlaylist:I,toggleFavorite:D,isFavorite:P,getPlaylistAssetIds:k}=SQe(),{board:R}=cy(),{isMobile:T}=ule(),[M,F]=b.useState(!1),[V,H]=b.useState(!1),[j,z]=b.useState(()=>WV()),[N,B]=b.useState(Snt),O=b.useRef(null),[$,U]=b.useState(!1),[Y,K]=b.useState([]),[Z,oe]=b.useState(0),J=b.useRef(null),[ae,Q]=b.useState(!1),[se,ie]=b.useState(""),[ce,ge]=b.useState(!1),[Se,Ae]=b.useState(0),{isConfigured:Le}=ont(),[it,Te]=b.useState(!1),[Re,ht]=b.useState(0),[Ze,Ge]=b.useState(null),{contextMenu:pt,open:at,close:ct}=H3(),[nt,It]=b.useState(null),[Lt,dt]=b.useState(""),{confirm:wt,confirmDialog:mt}=TQe();b.useEffect(()=>{Le&&p()},[Le,p]),b.useEffect(()=>{l.activeType&&l.activeType!==ln.AUDIO&&Ze&&Ge(null)},[l.activeType,Ze]),b.useEffect(()=>{Ze&&Ze!==hl&&!y.some(G=>G.id===Ze)&&Ge(null)},[y,Ze]),b.useEffect(()=>{if(!Le)return;let G=!0;const te=async()=>{G&&await p()};return xn(async()=>{const{mediaSyncService:re}=await Promise.resolve().then(()=>tO);return{mediaSyncService:re}},void 0,import.meta.url).then(({mediaSyncService:re})=>{re.addSyncCompletedListener(te)}),()=>{G=!1,xn(async()=>{const{mediaSyncService:re}=await Promise.resolve().then(()=>tO);return{mediaSyncService:re}},void 0,import.meta.url).then(({mediaSyncService:re})=>{re.removeSyncCompletedListener(te)})}},[Le,p]);const Bt=b.useMemo(()=>({all:a.length,image:a.filter(G=>G.type===ln.IMAGE).length,video:a.filter(G=>G.type===ln.VIDEO).length,audio:a.filter(G=>G.type===ln.AUDIO).length,character:a.filter(G=>G.category===_s.CHARACTER).length,local:a.filter(G=>G.source===Lr.LOCAL).length,ai:a.filter(G=>G.source===Lr.AI_GENERATED).length}),[a]),He=b.useMemo(()=>e&&a.find(G=>G.id===e)||null,[a,e]);b.useEffect(()=>{localStorage.setItem(iO,N.toString())},[N]);const[we,ue]=b.useState(HV),[_e,xe]=b.useState(HV),[Fe,lt]=b.useState(!1),[Ht,At]=b.useTransition(),le=b.useRef(null),me=b.useMemo(()=>{const G=KXe(a,l);if(!Ze)return G;const te=new Set(Ze===hl?a.filter(de=>de.type===ln.AUDIO).map(de=>de.id):k(Ze)),re=G.assets.filter(de=>te.has(de.id));return{assets:re,count:re.length,isEmpty:re.length===0}},[a,l,Ze,k]),ke=b.useMemo(()=>new Set(Ze&&Ze!==hl?k(Ze):[]),[k,Ze]),Oe=b.useMemo(()=>{const G=new Map;return Object.keys(w).forEach(te=>{const re=w[te]??[];G.set(te,new Set(re.map(de=>de.assetId).filter(de=>typeof de=="string"&&de.length>0)))}),G},[w]),De=b.useCallback(async G=>{await FC([hI(G)])},[]),Ye=b.useMemo(()=>[{key:"open-player",label:"在音乐播放器中打开",icon:g.jsx(zv,{size:14}),onSelect:async G=>{const te=me.assets.filter(de=>de.type===ln.AUDIO).map(de=>({elementId:`asset:${de.id}`,audioUrl:de.url,title:de.name,duration:de.duration,previewImageUrl:de.thumbnail,clipId:de.clipId,providerTaskId:de.providerTaskId})),re=Ze&&y.find(de=>de.id===Ze)||null;await nce({source:{elementId:`asset:${G.id}`,audioUrl:G.url,title:G.name,duration:G.duration,previewImageUrl:G.thumbnail,clipId:G.clipId,providerTaskId:G.providerTaskId},queue:te,playlist:re&&Ze!==hl?{playlistId:re.id,playlistName:re.name}:void 0})}},{key:"favorite",label:G=>v.has(G.id)?"取消收藏":"加入收藏",icon:g.jsx(vS,{size:14}),onSelect:G=>{G.type===ln.AUDIO&&D(G.id)}},{key:"playlist-actions",type:"submenu",label:"添加到播放列表",icon:g.jsx(ov,{size:14}),children:G=>y.map(te=>{const re=(w[te.id]||[]).some(de=>de.assetId===G.id);return{key:`playlist-${te.id}`,label:re?`已在 ${te.name}`:`添加到 ${te.name}`,icon:g.jsx(ov,{size:14}),disabled:re,onSelect:()=>{_(G.id,te.id)}}})},{key:"remove-current",label:"从当前播放列表移除",icon:g.jsx(O8,{size:14}),danger:!0,disabled:G=>!Ze||Ze===hl||!ke.has(G.id),onSelect:G=>{Ze&&Ze!==hl&&I(G.id,Ze)}},{key:"create-playlist",label:"新建播放列表并添加",icon:g.jsx(ic,{size:14}),onSelect:G=>{dt(""),It({mode:"create-and-add",targetAssetId:G.id}),ct()}}],[_,ct,ke,v,me.assets,y,w,I,Ze,D]),Rt=b.useCallback(G=>{if(G===we)return;le.current&&clearTimeout(le.current),xe(G);let te=N;G==="grid"?te=180:G==="compact"&&(te=80),B(te),localStorage.setItem(iO,te.toString()),lt(!0);try{localStorage.setItem(uce,G)}catch{}le.current=setTimeout(()=>{At(()=>{ue(G),setTimeout(()=>{lt(!1)},100)})},xnt)},[N,we]);b.useEffect(()=>()=>{le.current&&clearTimeout(le.current)},[]);const St=b.useCallback(()=>({activeType:l.activeType&&l.activeType!=="ALL"?l.activeType:void 0,activeSource:l.activeSource&&l.activeSource!=="ALL"?l.activeSource:void 0,activeCategory:l.activeCategory&&l.activeCategory!=="ALL"?l.activeCategory:void 0,searchQuery:l.searchQuery.trim().toLowerCase(),playlistId:Ze||null}),[l.activeCategory,l.activeSource,l.activeType,l.searchQuery,Ze]),Ct=b.useCallback(G=>j.selectedIds.has(G.id)?!0:oT(G,j.scope,Oe)&&!j.deselectedIds.has(G.id),[Oe,j]),Dt=b.useMemo(()=>me.assets.filter(Ct),[me.assets,Ct]),Gt=Dt.length;b.useEffect(()=>{s==null||s(Dt,V)},[Dt,V,s]);const Ft=b.useMemo(()=>me.assets.length===0?!1:Gt===me.assets.length,[me.assets.length,Gt]),Ne=b.useMemo(()=>me.assets.length===0?!1:Gt>0&&Gt<me.assets.length,[me.assets.length,Gt]),gt=b.useCallback(()=>{z(WV()),O.current=null},[]),nn=b.useCallback(G=>{z({scope:null,selectedIds:new Set(G),deselectedIds:new Set}),O.current=G.length>0?G[G.length-1]:null,G.length>0&&t(G[G.length-1])},[t]),Zt=b.useCallback(G=>{G.preventDefault(),G.stopPropagation(),F(!0)},[]),Fn=b.useCallback(G=>{G.preventDefault(),G.stopPropagation(),F(!1)},[]),We=b.useCallback(G=>{G.preventDefault(),G.stopPropagation(),F(!1);const te=G.dataTransfer.files;te&&te.length>0&&r&&r(te)},[r]),rn=b.useCallback(()=>{H(G=>!G),gt()},[gt]),Rn=b.useCallback(()=>{Ft?gt():z({scope:St(),selectedIds:new Set,deselectedIds:new Set})},[gt,St,Ft]),tr=b.useCallback((G,te)=>{const re=me.assets.find(de=>de.id===G);if(re){if(te!=null&&te.shiftKey&&O.current&&O.current!==G){const de=me.assets.findIndex(pe=>pe.id===O.current),ye=me.assets.findIndex(pe=>pe.id===G);if(de!==-1&&ye!==-1){const pe=Math.min(de,ye),Me=Math.max(de,ye),Ve=me.assets.slice(pe,Me+1);z(Xe=>{const tt=new Set(Xe.selectedIds),ft=new Set(Xe.deselectedIds);return Ve.forEach(qe=>{oT(qe,Xe.scope,Oe)?ft.delete(qe.id):tt.add(qe.id)}),{...Xe,selectedIds:tt,deselectedIds:ft}}),t(G);return}}z(de=>{const ye=new Set(de.selectedIds),pe=new Set(de.deselectedIds),Me=oT(re,de.scope,Oe);return ye.has(G)||Me&&!pe.has(G)?ye.has(G)?ye.delete(G):Me&&pe.add(G):Me?pe.delete(G):ye.add(G),{...de,selectedIds:ye,deselectedIds:pe}}),O.current=G,t(G)}},[me.assets,t,Oe]),dr=b.useCallback(G=>{nn(G)},[nn]),Yn=b.useCallback(async()=>{const G=Dt.map(te=>te.id);if(G.length!==0)try{if(R){const te=Dt.filter(de=>Av(de.url)),re=G.filter(de=>!te.some(ye=>ye.id===de));for(const de of te)nae(R,de.dedupeUrls||[de.url]);if(re.length>0){const de=Dt.flatMap(ye=>Av(ye.url)?[]:ye.dedupeAssetIds||[ye.id]);eae(R,de)}}await d(G),gt(),H(!1)}catch(te){console.error("[MediaLibraryGrid] Batch delete failed:",te)}},[R,gt,Dt,d]),pr=b.useMemo(()=>{if(!R||Dt.length===0)return{hasCacheAssets:!1,affectedCount:0};let G=0;const te=Dt.filter(re=>Av(re.url));for(const re of te)G+=tae(R,re.dedupeUrls||[re.url]);return{hasCacheAssets:te.length>0,affectedCount:G}},[R,Dt]),gr=b.useCallback(async()=>{if(Gt===0)return;await wt({title:"确认批量删除",confirmText:"删除",cancelText:"取消",danger:!0,children:g.jsxs(g.Fragment,{children:[g.jsxs("p",{children:["确定要删除选中的 ",Gt," 个素材吗?"]}),pr.hasCacheAssets&&pr.affectedCount>0?g.jsxs("p",{style:{marginTop:"8px",color:"var(--td-error-color)"},children:[g.jsx("span",{role:"img","aria-label":"注意",children:"⚠️"})," ","画布中有 ",g.jsx("strong",{children:pr.affectedCount})," ","个元素正在使用这些素材,删除后将被一并移除!"]}):null]})})&&await Yn()},[pr,wt,Gt,Yn]),Ar=b.useCallback(async G=>{await wt({title:"确认删除播放列表",description:`确定要删除播放列表「${G.name}」吗?删除后列表内关联关系将被移除,此操作不可撤销。`,confirmText:"删除",cancelText:"取消",danger:!0})&&await E(G.id)},[wt,E]),Oi=b.useCallback(async()=>{if(!(Dt.length===0||ce)){ge(!0),Ae(0);try{await FC(lce(Dt),`素材_${new Date().toISOString().slice(0,10)}.zip`,Ae)}catch(G){console.error("[MediaLibraryGrid] Download failed:",G)}finally{ge(!1),Ae(0)}}},[Dt,ce]),Ur=b.useCallback(async()=>{if(Dt.length===0||it)return;const G=[];if(Dt.filter(te=>te.source===Lr.AI_GENERATED).forEach(te=>{qc.getUrlSyncStatus(te.url)!=="synced"&&G.push(te.url)}),Dt.filter(te=>te.source===Lr.LOCAL&&te.url.startsWith("/__aitu_cache__/")).forEach(te=>{qc.getUrlSyncStatus(te.url)!=="synced"&&G.push(te.url)}),G.length!==0){Te(!0),ht(0);try{const te=await qc.syncSelectedMedia(G,(re,de,ye,pe)=>{ht(Math.round(re/de*100))});ht(100),te.succeeded>0&&await p()}catch(te){console.error("[MediaLibraryGrid] Batch sync failed:",te)}finally{Te(!1),ht(0)}}},[Dt,it,p]),ho=b.useMemo(()=>{const G=Dt.filter(re=>re.source!==Lr.AI_GENERATED?!1:qc.getUrlSyncStatus(re.url)!=="synced").length,te=Dt.filter(re=>re.source!==Lr.LOCAL||!re.url.startsWith("/__aitu_cache__/")?!1:qc.getUrlSyncStatus(re.url)!=="synced").length;return G+te},[Dt]),Xn=b.useCallback(async G=>{G.type===ln.AUDIO&&await D(G.id)},[D]),Sn=b.useCallback((G,te)=>{G.type===ln.AUDIO&&(te.preventDefault(),te.stopPropagation(),at(te,G))},[at]),Ai=b.useCallback(G=>{Ge(G),G&&u({activeType:ln.AUDIO})},[u]),Ri=b.useCallback((G,te)=>{dt(""),It({mode:G,targetAssetId:te}),ct()},[ct]),Ns=b.useCallback(G=>{dt(G.name),It({mode:"rename",playlistId:G.id})},[]),po=b.useCallback(async()=>{if(nt){if(nt.mode==="rename"&&nt.playlistId)await x(nt.playlistId,Lt);else{const G=await C(Lt);nt.mode==="create-and-add"&&nt.targetAssetId&&await _(nt.targetAssetId,G.id),Ai(G.id)}It(null),dt("")}},[nt,x,Lt,C,_,Ai]),Ln=b.useCallback(G=>G.map(te=>({id:te.id,url:te.type===ln.IMAGE?UV(te.url):te.url,type:te.type===ln.VIDEO?"video":te.type===ln.AUDIO?"audio":"image",title:te.name,alt:te.name,posterUrl:te.thumbnail,prompt:te.prompt,artist:te.modelName,album:te.type===ln.AUDIO?"Aitu Generated":void 0})),[]),sn=b.useCallback(G=>{const te=Ln(me.assets),re=me.assets.findIndex(de=>de.id===G.id);K(te),oe(re>=0?re:0),U(!0)},[me.assets,Ln]),hn=b.useCallback(()=>{U(!1)},[]),Dn=b.useCallback(async G=>{if(n){const te=me.assets.find(re=>re.id===G.id);if(te){n(te);return}}if(R)try{const te=me.assets.find(re=>re.id===G.id);G.type==="video"?await O1(R,G.url):G.type==="audio"?await Z5(R,G.url,{title:(te==null?void 0:te.name)||G.title,duration:te==null?void 0:te.duration,previewImageUrl:(te==null?void 0:te.thumbnail)||G.posterUrl,prompt:te==null?void 0:te.prompt,mv:te==null?void 0:te.modelName,clipId:te==null?void 0:te.clipId,providerTaskId:te==null?void 0:te.providerTaskId}):await M1(R,UV(G.url)),U(!1)}catch(te){console.error("Failed to insert media to canvas:",te)}},[me.assets,n,R]),nr=b.useCallback(G=>{G.type==="image"&&(ie(G.url),Q(!0),U(!1))},[]),Zn=b.useCallback(async G=>{if(R)try{const{unifiedCacheService:te}=await xn(async()=>{const{unifiedCacheService:Me}=await Promise.resolve().then(()=>du);return{unifiedCacheService:Me}},void 0,import.meta.url),re=`edited-image-${Date.now()}`,de=`/__aitu_cache__/image/${re}.png`,pe=await(await fetch(G)).blob();await te.cacheMediaFromBlob(de,pe,"image",{taskId:re}),await M1(R,de),Q(!1),ie("")}catch(te){console.error("Failed to insert edited image:",te)}},[R]);return b.useEffect(()=>{const G=te=>{var de;if(!((de=J.current)!=null&&de.contains(document.activeElement)))return;const re=te.target;if(!(re.tagName==="INPUT"||re.tagName==="TEXTAREA")&&!$&&(te.key===" "||te.key==="Enter")&&e){te.preventDefault();const ye=me.assets.find(pe=>pe.id===e);ye&&sn(ye)}};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[e,me.assets,sn,$]),c&&a.length===0?g.jsx("div",{className:"media-library-grid__loading",children:g.jsx(ty,{size:"large",text:"加载素材中..."})}):g.jsxs("div",{ref:J,className:`media-library-grid ${M?"media-library-grid--dragging":""}`,onDragOver:Zt,onDragLeave:Fn,onDrop:We,"data-testid":"media-library-grid",children:[g.jsxs("div",{className:"media-library-grid__header",children:[g.jsxs("div",{className:"media-library-grid__header-top",children:[g.jsx("div",{className:"media-library-grid__search",children:g.jsx(Cd,{value:l.searchQuery,onChange:G=>u({searchQuery:G}),placeholder:"搜索素材...",prefixIcon:g.jsx(sR,{size:16}),clearable:!0,"data-track":"grid_search_input"})}),g.jsxs("div",{className:"media-library-grid__header-right",children:[g.jsx(Gle,{viewMode:_e,onViewModeChange:Rt}),V?g.jsxs(g.Fragment,{children:[g.jsx(Ei,{variant:"base",theme:"danger",size:"small",icon:g.jsx(aR,{size:16}),disabled:Gt===0,onClick:()=>{gr()},"data-track":"grid_batch_delete",children:"删除"}),g.jsx(Ei,{variant:"outline",size:"small",icon:g.jsx(O8,{size:16}),onClick:rn,"data-track":"grid_cancel_selection",children:"取消"}),g.jsx(Ei,{variant:"outline",size:"small",icon:g.jsx($v,{size:16}),disabled:Gt===0||ce,loading:ce,onClick:Oi,"data-track":"grid_batch_download",children:"下载"}),Le&&g.jsx(cn,{content:"同步选中的素材到云端",placement:"bottom",children:g.jsx(Ei,{variant:"outline",size:"small",icon:g.jsx(k2e,{size:16}),disabled:ho===0||it,loading:it,onClick:Ur,"data-track":"grid_batch_sync",children:it?`${Re}%`:`同步 (${ho})`})})]}):g.jsxs(g.Fragment,{children:[g.jsx(Ei,{variant:"outline",size:"small",icon:g.jsx(TCe,{size:16}),onClick:rn,"data-track":"grid_toggle_selection_mode",children:"批量选择"}),g.jsx(Ei,{variant:"outline",size:"small",icon:g.jsx(NC,{size:16}),onClick:i,"data-track":"grid_upload_click",children:"上传"})]})]})]}),g.jsxs("div",{className:"media-library-grid__header-bottom",children:[V&&g.jsxs("div",{className:"media-library-grid__selection-info",onClick:Rn,role:"button",tabIndex:0,onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),Rn())},children:[g.jsx(ZT,{checked:Ft,indeterminate:Ne,"data-track":"grid_select_all"}),g.jsx("span",{className:"media-library-grid__selection-count",children:Gt})]}),g.jsx("div",{className:"media-library-grid__filter-island",children:g.jsxs("div",{className:"media-library-grid__filter-group",children:[g.jsx("div",{className:"media-library-grid__type-tabs",children:Cnt.map(G=>{const te=G.value==="ALL"?Bt.all:G.value===ln.IMAGE?Bt.image:G.value===ln.AUDIO?Bt.audio:Bt.video,re=G.icon,de=(l.activeType||"ALL")===G.value;return g.jsx(cn,{content:`${G.label} (${te})`,placement:"top",showArrow:!1,children:g.jsxs("button",{type:"button","aria-label":`${G.label}:${te}`,"aria-pressed":de,className:`media-library-grid__type-tab ${de?"media-library-grid__type-tab--active":""}`,onClick:()=>u({activeType:G.value==="ALL"?void 0:G.value}),children:[g.jsx(re,{size:14,strokeWidth:1.5,className:G.value==="ALL"?"icon-all":""}),g.jsx("span",{className:"media-library-grid__type-tab-label",children:G.label}),g.jsx("span",{className:"media-library-grid__type-tab-count",children:te})]})},G.value)})}),g.jsxs("div",{className:"media-library-grid__filter-tags",children:[g.jsx("span",{className:"media-library-grid__filter-tags-label",children:"标签"}),_nt.map(G=>{const te=Bt[G.countKey],re=G.icon,de=l.activeCategory===G.value;return g.jsx(cn,{content:`${G.tooltip} (${te})`,placement:"top",showArrow:!1,children:g.jsxs("button",{type:"button","aria-label":`${G.tooltip}:${te}`,"aria-pressed":de,className:`media-library-grid__filter-chip ${de?"media-library-grid__filter-chip--active":""}`,onClick:()=>u({activeCategory:de?void 0:G.value,...de?{}:{activeType:ln.IMAGE}}),children:[g.jsx(re,{size:13,strokeWidth:1.7}),g.jsx("span",{className:"media-library-grid__filter-chip-label",children:G.label}),g.jsx("span",{className:"media-library-grid__filter-chip-count",children:te})]})},G.value)}),g.jsx("span",{className:"media-library-grid__filter-tags-divider"}),Ent.map(G=>{const te=Bt[G.countKey],re=G.icon,de=l.activeSource===G.value;return g.jsx(cn,{content:`${G.tooltip} (${te})`,placement:"top",showArrow:!1,children:g.jsxs("button",{type:"button","aria-label":`${G.tooltip}:${te}`,"aria-pressed":de,className:`media-library-grid__filter-chip ${de?"media-library-grid__filter-chip--active":""}`,onClick:()=>u({activeSource:de?void 0:G.value}),children:[g.jsx(re,{size:13,strokeWidth:1.7}),g.jsx("span",{className:"media-library-grid__filter-chip-label",children:G.label}),g.jsx("span",{className:"media-library-grid__filter-chip-count",children:te})]})},G.value)})]})]})}),g.jsx("div",{className:"media-library-grid__header-spacer"}),g.jsx("div",{className:"media-library-grid__sort-options",children:Int.map(G=>{const te=l.sortBy||"DATE_DESC",re=te===G.options.asc,de=te===G.options.desc,ye=re||de,pe=re?G.icons.asc:G.icons.desc,Me=()=>{te===G.options.asc?u({sortBy:G.options.desc}):te===G.options.desc?te==="DATE_DESC"&&G.id==="DATE"?u({sortBy:"DATE_ASC"}):u({sortBy:"DATE_DESC"}):u({sortBy:G.options.asc})};return g.jsx(cn,{content:`${G.label}: ${re?"正序":de?"逆序":"默认"}`,placement:"top",showArrow:!1,children:g.jsx("div",{className:`media-library-grid__filter-option ${ye?"media-library-grid__filter-option--active":""}`,onClick:Me,children:g.jsx(pe,{size:14,strokeWidth:1.5})})},G.id)})})]}),(!l.activeType||l.activeType===ln.AUDIO)&&g.jsx(Xtt,{className:"media-library-grid__playlist-bar",selectedPlaylistId:Ze||hl,allCount:Bt.audio,playlists:y,playlistItems:w,onSelect:Ai,onCreate:()=>Ri("create"),onRename:Ns,onDelete:G=>void Ar(G)}),ce&&g.jsxs("div",{className:"media-library-grid__progress",children:[g.jsx("div",{className:"media-library-grid__progress-bar",children:g.jsx("div",{className:"media-library-grid__progress-fill",style:{width:`${Se}%`}})}),g.jsxs("span",{className:"media-library-grid__progress-text",children:[Se<50?"下载中":"压缩中"," ",Se,"%"]})]})]}),M&&g.jsx("div",{className:"media-library-grid__drop-overlay",children:g.jsxs("div",{className:"media-library-grid__drop-message",children:[g.jsx("div",{className:"media-library-grid__drop-message-icon",children:g.jsx(NC,{size:32})}),g.jsx("h3",{className:"media-library-grid__drop-message-title",children:"拖放文件到这里"}),g.jsx("p",{className:"media-library-grid__drop-message-description",children:"支持 JPG、PNG、MP4 格式"})]})}),me.isEmpty?g.jsx(btt,{}):g.jsxs(g.Fragment,{children:[g.jsx("div",{className:`media-library-grid__container ${Fe||Ht?"media-library-grid__container--transitioning":""}`,children:g.jsx(wtt,{assets:me.assets,viewMode:we,gridSize:N,selectedAssetId:e??void 0,isAssetSelected:Ct,isSelectionMode:V,marqueeEnabled:!T&&V,onSelectAsset:V?tr:t,onMarqueeSelect:dr,onDoubleClick:n,onPreview:sn,onContextMenu:Sn,isFavorite:P,onToggleFavorite:Xn,syncedUrls:f})}),T&&He&&!V&&g.jsxs("div",{className:"media-library-grid__mobile-inspector",children:[g.jsxs("div",{className:"media-library-grid__mobile-inspector-info",children:[g.jsxs("div",{className:"media-library-grid__mobile-inspector-type",children:[He.type===ln.IMAGE?g.jsx(wS,{size:14}):He.type===ln.AUDIO?g.jsx(zv,{size:14}):g.jsx(cg,{size:14}),g.jsx("span",{children:He.type===ln.IMAGE?"图片":He.type===ln.AUDIO?"音频":"视频"}),He.source===Lr.AI_GENERATED&&g.jsx("span",{className:"media-library-grid__mobile-inspector-ai",children:"AI"})]}),g.jsx(cn,{content:He.name,showArrow:!1,children:g.jsx("div",{className:"media-library-grid__mobile-inspector-name",children:He.name})})]}),g.jsxs("div",{className:"media-library-grid__mobile-inspector-actions",children:[g.jsx(cn,{content:"预览",children:g.jsx("button",{className:"media-library-grid__mobile-inspector-btn",onClick:()=>sn(He),"data-track":"mobile_preview",children:g.jsx(vY,{size:18})})}),n&&g.jsx(cn,{content:"插入画布",children:g.jsx("button",{className:"media-library-grid__mobile-inspector-btn media-library-grid__mobile-inspector-btn--primary",onClick:()=>n(He),"data-track":"mobile_insert",children:g.jsx(ic,{size:18})})}),g.jsx(cn,{content:"下载",children:g.jsx("button",{className:"media-library-grid__mobile-inspector-btn",onClick:()=>{De(He)},"data-track":"mobile_download",children:g.jsx($v,{size:18})})})]})]}),g.jsxs("div",{className:"media-library-grid__footer",children:[g.jsxs("div",{className:"media-library-grid__footer-left",children:[o?g.jsxs("div",{className:"media-library-grid__footer-storage",children:[g.jsx(OT,{size:14}),g.jsxs("span",{children:["已用 ",DC(o.quota.usage)]})]}):g.jsxs("div",{className:"media-library-grid__footer-storage",children:[g.jsx(OT,{size:14}),g.jsx("span",{children:"正在获取存储状态..."})]}),g.jsxs("span",{className:"media-library-grid__footer-count",children:["共 ",me.count," 个素材"]}),!V&&g.jsx("span",{className:"media-library-grid__footer-hint",children:"双击预览"})]}),g.jsx("div",{className:"media-library-grid__footer-right",children:we!=="list"&&g.jsxs("div",{className:"media-library-grid__zoom-control",children:[g.jsx(jSe,{size:14,onClick:()=>B(G=>Math.max(80,G-20))}),g.jsx("input",{type:"range",min:"80",max:"300",step:"10",value:N,onChange:G=>B(Number(G.target.value)),className:"media-library-grid__zoom-slider","data-track":"grid_zoom_slider"}),g.jsx(ic,{size:14,onClick:()=>B(G=>Math.min(300,G+20))})]})})]})]}),g.jsx(Hg,{visible:$,items:Y,initialIndex:Z,onClose:hn,showThumbnails:!0,onInsertToCanvas:R?Dn:void 0,onEdit:nr}),ae&&se&&g.jsx(Jle,{visible:ae,imageUrl:se,showOverwrite:!1,onClose:()=>{Q(!1),ie("")},onInsert:R?Zn:void 0}),g.jsx(W3,{state:pt,items:Ye,onClose:ct}),g.jsx(NR,{visible:!!nt,header:(nt==null?void 0:nt.mode)==="rename"?"重命名播放列表":"新建播放列表",onClose:()=>It(null),onConfirm:()=>void po(),confirmBtn:"确定",cancelBtn:"取消",children:g.jsx(Cd,{value:Lt,onChange:G=>dt(String(G)),placeholder:"请输入播放列表名称",autofocus:!0})}),mt]})}function Pnt(e,t="small"){const n=zn(e);if(n.startsWith("http://")||n.startsWith("https://")||n.startsWith("blob:")||F1(n))return n;try{const r=new URL(n,window.location.origin);return r.searchParams.set("thumbnail",t),r.toString()}catch{const r=n.includes("?")?"&":"?";return`${n}${r}thumbnail=${t}`}}function VV({asset:e,selectedAssets:t=[],isSelectionMode:n=!1,onRename:r,onDelete:i,onDownload:o,onMarkAsSubject:s,onSelect:a,onSelectMultiple:l,showSelectButton:c,selecting:u=!1,selectButtonText:d="使用"}){var Le,it;const[f,p]=b.useState(!1),[y,v]=b.useState(""),[w,C]=b.useState(!1),[x,E]=b.useState(!1),[_,I]=b.useState(""),[D,P]=b.useState(""),[k,R]=b.useState(!1),{board:T}=cy(),M=fle(e==null?void 0:e.id,e==null?void 0:e.url,e==null?void 0:e.size),F=t.length,V=t.filter(Te=>Te.type===ln.IMAGE).length,H=t.filter(Te=>Te.type===ln.VIDEO).length,j=t.filter(Te=>Te.type===ln.AUDIO).length,z=t.reduce((Te,Re)=>Te+(Re.size||0),0),{isCacheAsset:N,canvasElementCount:B}=b.useMemo(()=>{if(!e||!T)return{isCacheAsset:!1,canvasElementCount:0};const Te=Av(e.url),Re=Te?tae(T,e.dedupeUrls||[e.url]):0;return{isCacheAsset:Te,canvasElementCount:Re}},[e,T]),O=b.useMemo(()=>{if(e)return JSON.stringify({assetId:e.id,assetType:e.type,assetSource:e.source})},[e]),$=b.useCallback(()=>{e&&(v(e.name),p(!0))},[e]),U=b.useCallback(async()=>{if(!e){p(!1);return}const Te=y.trim();if(!Te||Te===e.name){p(!1),v("");return}try{await r(e.id,Te),p(!1)}catch{p(!1)}},[e,y,r]),Y=b.useCallback(Te=>{Te.key==="Escape"&&(p(!1),v(""))},[]),K=b.useCallback(()=>{C(!0)},[]),Z=b.useCallback(async()=>{if(e)try{await i(e.id),C(!1)}catch{}},[e,i]),oe=b.useCallback(()=>{e&&(o(e),tn.success("开始下载"))},[e,o]),J=b.useCallback(()=>{e&&a&&!u&&a(e)},[e,a,u]),ae=b.useCallback(async()=>{!l||t.length===0||u||await l(t)},[l,t,u]),Q=b.useCallback(async()=>{if(e!=null&&e.prompt)try{await aE(e.prompt),tn.success("提示词已复制")}catch{tn.error("复制失败")}},[e==null?void 0:e.prompt]),se=b.useCallback(()=>{var Te,Re;e&&(I(((Te=e.characterMeta)==null?void 0:Te.name)||""),P(((Re=e.characterMeta)==null?void 0:Re.prompt)||e.prompt||""),E(!0))},[e]),ie=b.useCallback(()=>{k||E(!1)},[k]),ce=b.useCallback(async()=>{if(!e||!s||k)return;const Te=_.trim(),Re=D.trim();if(!Te){tn.warning("请先给主体起一个名字");return}try{R(!0),await s(e,{name:Te,...Re&&{prompt:Re}}),E(!1)}catch(ht){console.error("[MediaLibraryInspector] Failed to mark subject:",ht),tn.error("设置主体失败")}finally{R(!1)}},[e,k,s,_,D]);if(n)return g.jsxs("div",{className:"media-library-inspector media-library-inspector--selection",children:[g.jsxs("div",{className:"media-library-inspector__selection-card",children:[g.jsx("div",{className:"media-library-inspector__selection-icon",children:g.jsx(S2,{size:22})}),g.jsxs("div",{className:"media-library-inspector__selection-copy",children:[g.jsx("span",{className:"media-library-inspector__selection-kicker",children:"批量选择"}),g.jsxs("h3",{className:"media-library-inspector__selection-title",children:["已选 ",F," 个素材"]}),g.jsx("p",{className:"media-library-inspector__selection-desc",children:"右侧操作会应用到当前筛选结果中已勾选的素材。"})]})]}),g.jsxs("div",{className:"media-library-inspector__selection-summary",children:[g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"图片"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:V})]}),g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"视频"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:H})]}),g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"音频"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:j})]}),g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"总大小"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:z>0?DC(z):"-"})]})]}),g.jsx("div",{className:"media-library-inspector__actions media-library-inspector__actions--batch",children:c&&l&&g.jsxs(Ei,{theme:"primary",block:!0,icon:g.jsx(S2,{size:16}),onClick:()=>{ae()},loading:u,disabled:u||F===0,"data-track":"inspector_batch_use_assets",className:"inspector-btn-select",children:[d,F>0?` (${F})`:""]})})]});if(!e)return g.jsx("div",{className:"media-library-inspector media-library-inspector--empty",children:g.jsx("p",{children:"选择素材查看详情"})});const ge=e.type==="IMAGE"?zn(e.url):e.url,Se=e.category===_s.CHARACTER,Ae=e.type===ln.IMAGE&&!!s;return g.jsxs("div",{className:"media-library-inspector",children:[g.jsx("div",{className:"media-library-inspector__preview",children:e.type==="AUDIO"?g.jsxs("div",{className:"media-library-inspector__audio-preview",children:[e.thumbnail&&g.jsx(xs,{src:e.thumbnail,alt:e.name,className:"media-library-inspector__audio-cover",showSkeleton:!1,eager:!0}),g.jsx("audio",{src:ge,controls:!0,className:"media-library-inspector__audio"})]}):e.type==="IMAGE"?g.jsx(xs,{src:Pnt(ge,"large"),alt:e.name,className:"media-library-inspector__image",fallback:g.jsx(xs,{src:ge,alt:e.name,className:"media-library-inspector__image",showSkeleton:!1,eager:!0}),showSkeleton:!1,eager:!0}):g.jsx(cN,{src:ge,alt:e.name,className:"media-library-inspector__video",poster:e.thumbnail,thumbnailSize:"large",activateVideoOnClick:!0,playOnActivate:!0,videoProps:{controls:!0,preload:"metadata"}})}),g.jsx("div",{className:"media-library-inspector__name-section",children:f?g.jsx("div",{className:"media-library-inspector__name-edit",children:g.jsx(Cd,{value:y,onChange:Te=>v(Te),autofocus:!0,onBlur:U,onEnter:U,onKeydown:Y,placeholder:"输入名称,按 Enter 或点击外部保存"})}):g.jsxs("div",{className:"media-library-inspector__name-display",children:[g.jsx(cn,{content:e.name,showArrow:!1,children:g.jsx("h3",{className:"media-library-inspector__name",children:e.name})}),g.jsx(Ei,{size:"small",variant:"text",icon:g.jsx(YSe,{size:14}),onClick:$,"data-track":"inspector_rename_start"})]})}),g.jsxs("div",{className:"media-library-inspector__metadata",children:[g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"类型"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:e.type==="IMAGE"?"图片":e.type==="AUDIO"?"音频":"视频"})]}),g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"来源"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:e.source==="AI_GENERATED"?"AI生成":"本地上传"})]}),Se&&g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"类别"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:"主体"})]}),((Le=e.characterMeta)==null?void 0:Le.name)&&g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"主体名"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:e.characterMeta.name})]})]}),g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"创建时间"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:Eae(e.createdAt)})]}),M&&g.jsxs("div",{className:"media-library-inspector__meta-item",children:[g.jsx("span",{className:"media-library-inspector__meta-label",children:"文件大小"}),g.jsx("span",{className:"media-library-inspector__meta-value",children:DC(M)})]})]}),e.prompt&&g.jsxs("div",{className:"media-library-inspector__prompt-section",children:[g.jsxs("div",{className:"media-library-inspector__prompt-header",children:[g.jsx("span",{className:"media-library-inspector__prompt-label",children:"提示词"}),g.jsx(Ei,{size:"small",variant:"text",icon:g.jsx(yY,{size:12}),onClick:Q,"data-track":"inspector_copy_prompt",children:"复制"})]}),g.jsx("div",{className:"media-library-inspector__prompt-content",children:e.prompt})]}),((it=e.characterMeta)==null?void 0:it.prompt)&&e.characterMeta.prompt!==e.prompt&&g.jsxs("div",{className:"media-library-inspector__prompt-section media-library-inspector__prompt-section--compact",children:[g.jsx("div",{className:"media-library-inspector__prompt-header",children:g.jsx("span",{className:"media-library-inspector__prompt-label",children:"主体提示词"})}),g.jsx("div",{className:"media-library-inspector__prompt-content",children:e.characterMeta.prompt})]}),g.jsxs("div",{className:`media-library-inspector__actions ${c&&a&&Ae?"media-library-inspector__actions--with-select-subject":c&&a?"media-library-inspector__actions--with-select":Ae?"media-library-inspector__actions--with-subject":"media-library-inspector__actions--no-select"}`,children:[c&&a&&g.jsx(Ei,{theme:"primary",block:!0,icon:g.jsx(S2,{size:16}),onClick:J,loading:u,disabled:u,"data-track":"inspector_use_asset","data-track-params":O,className:"inspector-btn-select",children:d}),Ae&&g.jsx(Ei,{variant:"outline",block:!0,icon:g.jsx(NT,{size:16}),onClick:se,"data-track":"inspector_mark_subject","data-track-params":O,className:"inspector-btn-subject",children:Se?"编辑主体":"设为主体"}),g.jsx(Ei,{variant:"outline",block:!0,icon:g.jsx($v,{size:16}),onClick:oe,"data-track":"inspector_download","data-track-params":O,className:"inspector-btn-download",children:"下载"}),g.jsx(Ei,{theme:"danger",variant:"outline",block:!0,icon:g.jsx(aR,{size:16}),onClick:K,"data-track":"inspector_delete","data-track-params":O,className:"inspector-btn-delete",children:"删除"})]}),g.jsx(NR,{visible:x,header:Se?"编辑主体信息":"设为主体",onClose:ie,onConfirm:()=>void ce(),confirmBtn:k?"保存中...":"保存",cancelBtn:"取消",children:g.jsxs("div",{className:"media-library-inspector__subject-dialog",children:[g.jsxs("label",{className:"media-library-inspector__subject-label",children:["主体名",g.jsx(Cd,{value:_,onChange:Te=>I(String(Te)),placeholder:"例如:Lily / 银色耳机 / 红色跑车",autofocus:!0,disabled:k})]}),g.jsx("p",{className:"media-library-inspector__subject-hint",children:"主体名用于脚本复用,不会修改素材标题。"}),g.jsxs("label",{className:"media-library-inspector__subject-label",children:["主体提示词",g.jsx("textarea",{className:"media-library-inspector__subject-textarea",value:D,onChange:Te=>P(Te.target.value),placeholder:"可选;用于回填脚本中的主体提示词",rows:4,disabled:k})]})]})}),g.jsxs(aN,{open:w,title:"确认删除",confirmText:"删除",cancelText:"取消",danger:!0,onOpenChange:C,onConfirm:Z,children:[g.jsx("p",{children:"删除后无法恢复,确认删除该素材?"}),g.jsxs("p",{style:{marginTop:"8px",color:"var(--td-text-color-secondary)"},children:["素材名称: ",g.jsx("strong",{children:e.name})]}),N&&B>0&&g.jsxs("p",{style:{marginTop:"8px",color:"var(--td-error-color)"},children:["⚠️ 画布中有 ",g.jsx("strong",{children:B})," 个元素正在使用此素材,删除后这些元素也将被移除!"]})]})]})}const knt=Eu.DIALOG_AI_IMAGE;class Tm{constructor(){this.windows=new Map,this.counter=0}static getInstance(){return Tm.instance||(Tm.instance=new Tm),Tm.instance}register(t,n){const r=this.windows.get(t);r?(r.element=n,r.activationOrder=++this.counter):this.windows.set(t,{windowId:t,activationOrder:++this.counter,element:n}),this.applyAllZIndexes()}unregister(t){this.windows.delete(t)&&this.applyAllZIndexes()}bringToFront(t){const n=this.windows.get(t);n&&(this.isTopWindow(t)||(n.activationOrder=++this.counter,this.applyAllZIndexes()))}updateElement(t,n){const r=this.windows.get(t);r&&(r.element=n,this.applyZIndex(r,this.getPositionIndex(t)))}getTopWindowId(){let t=null,n=-1;return this.windows.forEach(r=>{r.activationOrder>n&&(n=r.activationOrder,t=r.windowId)}),t}isTopWindow(t){return this.getTopWindowId()===t}getPositionIndex(t){return this.getSortedEntries().findIndex(r=>r.windowId===t)}getSortedEntries(){return Array.from(this.windows.values()).sort((t,n)=>t.activationOrder-n.activationOrder)}applyAllZIndexes(){this.getSortedEntries().forEach((n,r)=>{this.applyZIndex(n,r)})}applyZIndex(t,n){!t.element||n<0||t.element.style.setProperty("--aitu-winbox-z-index",String(knt+n))}}const vf=Tm.getInstance();let Ws=null,l2=null;const Tnt=async()=>Ws||(typeof window<"u"&&window.WinBox?(Ws=window.WinBox,Ws):l2||(l2=(async()=>{try{if(await xn(()=>import("./winbox.bundle.min-CoRPjCs5.js"),[],import.meta.url),Ws=window.WinBox,Ws)return Ws;throw new Error("WinBox not found after import")}catch(e){return console.warn("Dynamic import failed, falling back to CDN:",e),new Promise((t,n)=>{const r=document.createElement("script");r.src="https://cdn.jsdelivr.net/npm/winbox@0.2.82/dist/winbox.bundle.min.js",r.async=!0,r.onload=()=>{Ws=window.WinBox,Ws?t(Ws):n(new Error("WinBox not found after CDN loading"))},r.onerror=n,document.head.appendChild(r)})}})(),l2)),dce=({visible:e,title:t,icon:n,onClose:r,children:i,width:o="80%",height:s="80%",minWidth:a=400,minHeight:l=300,x:c="center",y:u="center",maximizable:d=!0,minimizable:f=!0,resizable:p=!0,movable:y=!0,modal:v=!1,background:w="linear-gradient(135deg, #5A4FCF 0%, #7B68EE 50%, #E91E63 100%)",border:C=0,className:x,id:E,headerContent:_,container:I,onMaximize:D,onMinimize:P,onRestore:k,onFocus:R,onBlur:T,onMove:M,onResize:F,autoMaximize:V=!1,minVisiblePixels:H=50,onInsertToCanvas:j,keepAlive:z=!1,minimizeTargetSelector:N,onActivate:B})=>{var At;const O=b.useRef(E||`winbox-${Bh()}`),$=b.useRef(null),U=b.useRef(null),Y=b.useRef(r),K=b.useRef(B),Z=b.useRef(!0),oe=b.useRef(!1),J=b.useRef(null),ae=b.useRef([]);Y.current=r,K.current=B;const Q=b.useRef(null),se=b.useRef(!1),[ie,ce]=b.useState(null),[ge,Se]=b.useState(null),[Ae,Le]=b.useState(null),[it,Te]=b.useState(!1),[Re,ht]=b.useState(!!Ws),[Ze,Ge]=b.useState(null),pt=b.useRef(null),at=b.useRef(null),ct=b.useCallback(()=>{ae.current.forEach(le=>{window.clearTimeout(le)}),ae.current=[]},[]),nt=b.useCallback((le,me)=>{const ke=window.setTimeout(()=>{ae.current=ae.current.filter(Oe=>Oe!==ke),le()},me);return ae.current.push(ke),ke},[]),It=b.useCallback(()=>{Z.current&&(ce(null),Se(null),Le(null),Te(!1))},[]),Lt=b.useCallback((le,me=!0)=>{if(le){ct(),me&&(le.onclose=null);try{le.close(!0)}catch{}}},[ct]),dt=b.useCallback(()=>{const le=J.current;le&&(J.current=null,Lt(le))},[Lt]),wt=b.useCallback(le=>{if(le){ct(),J.current=le;try{le.hide()}catch{}nt(()=>{oe.current=!1,dt()},800)}},[ct,dt,nt]),mt=b.useCallback(le=>{Ge(le),pt.current=le,le===null&&at.current!==null&&$.current&&($.current.minwidth=at.current,at.current=null)},[]),Bt=b.useCallback(()=>{const le={left:!1,right:!1};if(typeof window>"u"||!window.WinBox)return le;const ke=window.WinBox.stack(),Oe=window.innerWidth;return ke.forEach(De=>{if(De===$.current)return;Math.abs(De.width-Oe/2)<20&&(De.x<20&&(le.left=!0),Math.abs(De.x+De.width-Oe)<20&&(le.right=!0))}),le},[]),He=b.useCallback(le=>{if(!le||!le.window)return;const me=window.innerWidth,ke=window.innerHeight;at.current!==null&&(le.minwidth=at.current,at.current=null),le.left=0,le.right=0,le.top=0,le.bottom=0;let Oe,De;typeof o=="string"&&o.endsWith("%")?Oe=Math.floor(me*parseInt(o)/100):Oe=typeof o=="number"?o:Math.floor(me*.8),typeof s=="string"&&s.endsWith("%")?De=Math.floor(ke*parseInt(s)/100):De=typeof s=="number"?s:Math.floor(ke*.8),Oe=Math.max(Oe,a),De=Math.max(De,l);const Ye=Math.floor((me-Oe)/2),Rt=Math.floor((ke-De)/2);le.resize(Oe,De).move(Ye,Rt),mt(null)},[o,s,a,l,mt]),we=b.useCallback((le,me,ke,Oe,De)=>{!le||!le.window||(le.left=0,le.right=0,le.top=0,le.bottom=0,me==="left"?(le.resize(ke,De).move(0,0),mt("left")):(le.resize(ke,De).move(Oe-ke,0),mt("right")))},[mt]),ue=b.useCallback(()=>{const le=$.current,me=pt.current;if(!le||!le.window)return;const ke=window.innerWidth,Oe=window.innerHeight,De=Bt(),Ye=Math.floor(ke/2),Rt=Ct=>{at.current===null&&(at.current=le.minwidth),le.minwidth=Math.min(200,Ye),le.max?(le.restore(),requestAnimationFrame(()=>{!le||!le.window||we(le,Ct,Ye,ke,Oe)})):we(le,Ct,Ye,ke,Oe)},St=()=>{le.max?(le.restore(),requestAnimationFrame(()=>{!le||!le.window||He(le)})):He(le)};if(me==="left"){St();return}if(me==="right"){De.left?St():Rt("left");return}De.right&&!De.left?Rt("left"):Rt("right")},[Bt,He,we]),_e=tQe(U,{enablePositionTracking:!1,enableScaleCompensation:!Ze&&!((At=$.current)!=null&&At.max)});b.useEffect(()=>{Re||Tnt().then(()=>ht(!0))},[Re]),b.useEffect(()=>(Z.current=!0,()=>{Z.current=!1}),[]);const xe=b.useRef(!1),Fe=b.useCallback(()=>{var le;return vf.unregister(O.current),(le=Y.current)==null||le.call(Y),!1},[]),lt=b.useCallback(()=>{var le;vf.bringToFront(O.current),(le=K.current)==null||le.call(K)},[]);b.useEffect(()=>{if(!(!Re||!Ws)){if(!e){if($.current)if(vf.unregister(O.current),ct(),z)try{$.current.hide()}catch{}else{const le=$.current;oe.current?wt(le):Lt(le),$.current=null,U.current=null,It()}return}if(e&&$.current){$.current.show(),$.current.focus(),vf.register(O.current,$.current.window);return}if(e&&!$.current){dt();const le=["winbox-react"];d||le.push("no-max"),f||le.push("no-min"),p||le.push("no-resize"),y||le.push("no-move"),le.push("no-full"),x&&le.push(x);const me=new Ws({id:E,title:t,width:o,height:s,minwidth:a,minheight:l,x:c,y:u,modal:v,background:w,border:C,overflow:!0,class:le,root:I||document.body,onclose:Fe,onmaximize:D,onminimize:function(){se.current=!0;const ke=Q.current,Oe=ke?{x:ke.x,y:ke.y}:{x:this.x||0,y:this.y||0},De=ke?{width:ke.width,height:ke.height}:{width:this.width||800,height:this.height||600},Ye=this.window;if(N&&Ye){const Rt=document.querySelector(N);if(Rt){Ye.style.transition="none",Ye.style.transform="",Ye.style.opacity="1",ke&&(Ye.style.left=`${ke.x}px`,Ye.style.top=`${ke.y}px`,Ye.style.width=`${ke.width}px`,Ye.style.height=`${ke.height}px`),Ye.offsetHeight;const St=Ye.getBoundingClientRect(),Ct=Rt.getBoundingClientRect(),Dt=Ct.left+Ct.width/2,Gt=Ct.top+Ct.height/2,Ft=St.left,Ne=St.top+St.height/2,gt=Dt-Ft,nn=Gt-Ne,Zt=Math.min(Ct.width/St.width,Ct.height/St.height,.06);Ye.style.transformOrigin="left center";const Fn=Ye.parentElement;Fn&&(Fn.style.perspective="1000px",Fn.style.perspectiveOrigin="left center"),Ye.offsetHeight;const We=400;return Ye.style.transition=`transform ${We}ms cubic-bezier(0.4, 0, 0.2, 1), opacity ${We}ms ease-out`,Ye.style.transform=`translate(${gt}px, ${nn}px) scale(${Zt}) rotateY(-30deg)`,Ye.style.opacity="0",nt(()=>{Ye.isConnected&&(Ye.style.transition="none",Ye.style.transform="",Ye.style.opacity="",Fn&&(Fn.style.perspective="",Fn.style.perspectiveOrigin=""),this.hide(),P==null||P(Oe,De))},We),!0}}return this.hide(),P==null||P(Oe,De),!0},onrestore:k,onfocus:function(){R==null||R(),lt()},onblur:T,onmove:function(ke,Oe){if(this.max||this.min||xe.current)return;const De=window.innerWidth,Ye=window.innerHeight,Rt=this.width;this.height;const St=H;if(pt.current){const Ne=pt.current==="left"?0:De-Rt;Math.abs(ke-Ne)>50&&mt(null)}let Ct=ke,Dt=Oe;ke<St-Rt&&(Ct=St-Rt),ke>De-St&&(Ct=De-St),Oe<0&&(Dt=0),Oe>Ye-St&&(Dt=Ye-St),(Ct!==ke||Dt!==Oe)&&(xe.current=!0,this.move(Ct,Dt),xe.current=!1);const Gt=Q.current,Ft=Gt&&Dt-Gt.y>200;!this.min&&!this.max&&!se.current&&!Ft&&(Q.current={x:Ct,y:Dt,width:this.width,height:this.height}),M==null||M(Ct,Dt)},onresize:function(ke,Oe){const De=Q.current,Ye=De&&(Oe<100||De.height-Oe>200);!this.min&&!this.max&&!se.current&&!Ye&&(Q.current={x:this.x,y:this.y,width:ke,height:Oe}),F==null||F(ke,Oe)}});if($.current=me,me.addControl({index:0,class:"wb-split",image:"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjxyZWN0IHg9IjMiIHk9IjMiIHdpZHRoPSIxOCIgaGVpZ2h0PSIxOCIgcng9IjIiIHJ5PSIyIj48L3JlY3Q+PGxpbmUgeDE9IjEyIiB5MT0iMyIgeDI9IjEyIiB5Mj0iMjEiPjwvbGluZT48L3N2Zz4=",click:ke=>{ke.preventDefault(),ke.stopPropagation(),ue()}}),j&&me.addControl({index:0,class:"wb-insert-canvas",image:"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjxyZWN0IHg9IjMiIHk9IjMiIHdpZHRoPSIxOCIgaGVpZ2h0PSIxOCIgcng9IjIiLz48cGF0aCBkPSJNMTIgOHY4Ii8+PHBhdGggZD0iTTggMTJoOCIvPjwvc3ZnPg==",click:ke=>{ke.preventDefault(),ke.stopPropagation();const Oe=me.window;if(Oe){const De=Oe.getBoundingClientRect(),Ye={x:De.left,y:De.top,width:De.width,height:De.height};j(Ye)}else{const De={x:me.x||0,y:me.y||0,width:me.width||800,height:me.height||600};j(De)}}}),me.window){U.current=me.window,vf.register(O.current,U.current),requestAnimationFrame(()=>{_e()});const ke=me.window.querySelector(".wb-body");if(ke&&Se(ke),n){const Oe=me.window.querySelector(".wb-drag"),De=me.window.querySelector(".wb-title");if(Oe&&De){const Ye=document.createElement("div");Ye.className="wb-icon-container",Oe.insertBefore(Ye,De),Le(Ye)}}}if(_&&me.window){const ke=me.window.querySelector(".wb-drag");if(ke){const Oe=document.createElement("div");Oe.className="wb-header-custom";const De=Ye=>{Ye.stopPropagation()};Oe.addEventListener("mousedown",De,!0),Oe.addEventListener("touchstart",De,!0),Oe.addEventListener("pointerdown",De,!0),ke.appendChild(Oe),ce(Oe)}}me&&!me.min&&!me.max&&(Q.current={x:me.x,y:me.y,width:me.width,height:me.height}),Te(!0),V&&nt(()=>{$.current&&$.current.maximize()},100)}}},[e,Re,V,z,ct,Lt,wt,dt,It,nt]),b.useEffect(()=>{const le=O.current;return()=>{if(vf.unregister(le),$.current){const me=$.current;oe.current?wt(me):Lt(me),$.current=null,U.current=null}J.current||ct()}},[ct,Lt,wt]),b.useEffect(()=>{$.current&&t&&$.current.setTitle(t)},[t]),b.useEffect(()=>{var le,me;if($.current&&n&&!Ae){const ke=$.current,Oe=(le=ke.window)==null?void 0:le.querySelector(".wb-drag"),De=(me=ke.window)==null?void 0:me.querySelector(".wb-title");if(Oe&&De&&!Oe.querySelector(".wb-icon-container")){const Rt=document.createElement("div");Rt.className="wb-icon-container",Oe.insertBefore(Rt,De),Le(Rt)}}},[n,Ae]),b.useEffect(()=>{if($.current){const le=Q.current;if(e){const me=$.current.min||$.current.hidden;$.current.min&&($.current.restore(),le&&($.current.move(le.x,le.y),$.current.resize(le.width,le.height)),se.current=!1),$.current.show(),$.current.focus(),vf.bringToFront(O.current),me&&N&&requestAnimationFrame(()=>{Ht()})}else $.current.hide()}},[e]);const Ht=b.useCallback(()=>{if(!N||!$.current)return;const le=$.current.window,me=document.querySelector(N);if(!le||!me)return;const ke=Q.current;if(!ke)return;const Oe=me.getBoundingClientRect(),De=Oe.left+Oe.width/2,Ye=Oe.top+Oe.height/2,Rt=ke.x,St=ke.y+ke.height/2,Ct=De-Rt,Dt=Ye-St,Gt=Math.min(Oe.width/ke.width,Oe.height/ke.height,.06),Ft=le.parentElement;Ft&&(Ft.style.perspective="1000px",Ft.style.perspectiveOrigin="left center"),le.style.transition="none",le.style.transformOrigin="left center",le.style.transform=`translate(${Ct}px, ${Dt}px) scale(${Gt}) rotateY(-30deg)`,le.style.opacity="0",le.offsetHeight;const Ne=350;le.style.transition=`transform ${Ne}ms cubic-bezier(0.2, 0, 0.4, 1), opacity ${Ne*.6}ms ease-out`,le.style.transform="",le.style.opacity="1",nt(()=>{le.isConnected&&(le.style.transition="none",le.style.transform="",le.style.transformOrigin="",Ft&&(Ft.style.perspective="",Ft.style.perspectiveOrigin=""))},Ne)},[N,nt]);return b.useEffect(()=>{const le=U.current;if(!le)return;const me=[".wb-drag",".wb-n",".wb-s",".wb-e",".wb-w",".wb-ne",".wb-nw",".wb-se",".wb-sw"].join(", "),ke=De=>{const Ye=De.target;Ye instanceof Element&&Ye.closest(me)&&(oe.current=!0)},Oe=()=>{!oe.current&&!J.current||(oe.current=!1,dt())};return le.addEventListener("mousedown",ke,!0),le.addEventListener("touchstart",ke,!0),window.addEventListener("mouseup",Oe,!0),window.addEventListener("touchend",Oe,!0),window.addEventListener("touchcancel",Oe,!0),window.addEventListener("blur",Oe),()=>{le.removeEventListener("mousedown",ke,!0),le.removeEventListener("touchstart",ke,!0),window.removeEventListener("mouseup",Oe,!0),window.removeEventListener("touchend",Oe,!0),window.removeEventListener("touchcancel",Oe,!0),window.removeEventListener("blur",Oe)}},[it,dt]),b.useEffect(()=>{$.current&&V&&$.current.maximize()},[V]),b.useEffect(()=>{const le=U.current;if(!le)return;const me=()=>{lt()},ke=()=>{lt()};return le.addEventListener("pointerdown",me,!0),le.addEventListener("focusin",ke,!0),()=>{le.removeEventListener("pointerdown",me,!0),le.removeEventListener("focusin",ke,!0)}},[it,lt]),b.useEffect(()=>{if(!$.current||!e||pt.current)return;const le=typeof o=="number"?o:$.current.width,me=typeof s=="number"?s:$.current.height;typeof le!="number"||typeof me!="number"||$.current.width===le&&$.current.height===me&&$.current.minwidth===a&&$.current.minheight===l||($.current.minwidth=a,$.current.minheight=l,$.current.resize(le,me))},[s,l,a,e,o]),g.jsxs(g.Fragment,{children:[it&&n&&Ae&&Ui.createPortal(g.jsx("span",{className:"wb-icon-content",children:n}),Ae),it&&ge&&Ui.createPortal(g.jsx("div",{className:"winbox-content-wrapper",children:i}),ge),it&&_&&ie&&Ui.createPortal(_,ie)]})};function Dnt(e){var r;const t=(r=e.split(".").pop())==null?void 0:r.toLowerCase();return t&&{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",mp4:"video/mp4",webm:"video/webm",ogg:"video/ogg"}[t]||null}function Mnt(e){return As.ALLOWED_IMAGE_TYPES.includes(e)||As.ALLOWED_VIDEO_TYPES.includes(e)}function q2(e){return e.split("/").pop()||e}function Ont(e){const t=q2(e);return t.startsWith(".")||t.startsWith("__MACOSX")||t==="Thumbs.db"||t===".DS_Store"}async function Rnt(e,t=100*1024*1024){const n={files:[],skippedCount:0,errors:[]};try{const{default:r}=await xn(async()=>{const{default:s}=await import("./office-data-DMEex_0S.js").then(a=>a.j);return{default:s}},[],import.meta.url),i=await r.loadAsync(e),o=Object.entries(i.files);for(const[s,a]of o){if(a.dir)continue;if(Ont(s)){n.skippedCount++;continue}const l=Dnt(s);if(!l||!Mnt(l)){n.skippedCount++;continue}try{const c=await a.async("arraybuffer");if(c.byteLength>t){n.errors.push(`文件 "${q2(s)}" 超过 100MB 限制,已跳过`),n.skippedCount++;continue}const u=new Blob([c],{type:l}),d=l.startsWith("image/");n.files.push({name:q2(s),blob:u,type:d?"image":"video",mimeType:l})}catch(c){const u=c instanceof Error?c.message:String(c);n.errors.push(`解压 "${q2(s)}" 失败: ${u}`),n.skippedCount++}}}catch(r){const i=r instanceof Error?r.message:String(r);n.errors.push(`读取 ZIP 文件失败: ${i}`)}return n}function Nnt(e){return As.ALLOWED_ZIP_TYPES.includes(e.type)||e.name.toLowerCase().endsWith(".zip")}function fce({isOpen:e,onClose:t,mode:n=V5.BROWSE,filterType:r,filterCategory:i,onSelect:o,onSelectMultiple:s,selectButtonText:a}){const{assets:l,loadAssets:c,addAsset:u,setFilters:d,selectedAssetId:f,setSelectedAssetId:p,storageStatus:y,checkStorageQuota:v,renameAsset:w,markAssetAsSubject:C,removeAsset:x}=sN(),{board:E}=cy(),[_,I]=b.useState(null),[D,P]=b.useState(!1),[k,R]=b.useState(!1),[T,M]=b.useState(!1),[F,V]=b.useState(!1),[H,j]=b.useState([]),z=b.useRef(null),N=b.useRef(!0),B=b.useRef(!1);b.useEffect(()=>(N.current=!0,()=>{N.current=!1}),[]),b.useEffect(()=>{e&&(c(),v())},[e,c,v]),b.useEffect(()=>{e&&(r||i)&&d({...r?{activeType:r}:{},activeCategory:i||void 0})},[e,r,i,d]),b.useEffect(()=>{e&&I(f)},[e,f]),b.useEffect(()=>{const ge=()=>{R(window.innerWidth<=768)};return ge(),window.addEventListener("resize",ge),()=>window.removeEventListener("resize",ge)},[]);const O=b.useCallback(ge=>{I(ge),p(ge)},[p]),$=b.useCallback(()=>{P(!1)},[]),U=b.useCallback(async ge=>{if(!(!o||B.current))try{B.current=!0,M(!0),await o(ge),t()}finally{B.current=!1,N.current&&M(!1)}},[t,o]),Y=b.useCallback(async ge=>{if(!(!o||B.current))try{B.current=!0,M(!0),await o(ge),t()}finally{B.current=!1,N.current&&M(!1)}},[t,o]),K=b.useCallback(async ge=>{if(!(!s||B.current)&&ge.length!==0)try{B.current=!0,M(!0),await s(ge),t()}finally{B.current=!1,N.current&&M(!1)}},[t,s]),Z=b.useCallback((ge,Se)=>{V(Se),j(ge)},[]),oe=b.useCallback(async ge=>{await FC([hI(ge)])},[]),J=b.useCallback(async ge=>{if(!ge||ge.length===0)return;const Se=[],Ae=[];for(let Te=0;Te<ge.length;Te++){const Re=ge[Te];Nnt(Re)?Se.push(Re):Ae.push(Re)}const Le=[];for(const Te of Ae){const Re=Te.type.startsWith("image/"),ht=Te.type.startsWith("video/"),Ze=Te.type.startsWith("audio/");if(!Re&&!ht&&!Ze){console.warn(`[MediaLibrary] Invalid file type: ${Te.type}`),tn.warning(`文件 "${Te.name}" 不是有效的图片、视频或音频格式`);continue}const Ge=100*1024*1024;if(Te.size>Ge){console.warn(`[MediaLibrary] File too large: ${Te.size} bytes`),tn.warning(`文件 "${Te.name}" 超过 100MB 限制`);continue}Le.push(Te)}let it=0;for(const Te of Se)try{tn.info(`正在解压 "${Te.name}"...`);const Re=await Rnt(Te);Re.errors.length>0&&Re.errors.forEach(ht=>tn.warning(ht));for(const ht of Re.files){const Ze=ht.type==="image"?ln.IMAGE:ln.VIDEO;await u(ht.blob,Ze,Lr.LOCAL,ht.name),it++}Re.skippedCount>0&&tn.info(`"${Te.name}" 中跳过了 ${Re.skippedCount} 个不支持的文件`)}catch(Re){console.error("[MediaLibrary] ZIP extraction error:",Re),tn.error(`解压 "${Te.name}" 失败`)}try{for(const Re of Le){const ht=Re.type.startsWith("image/"),Ze=Re.type.startsWith("audio/"),Ge=ht?ln.IMAGE:Ze?ln.AUDIO:ln.VIDEO;await u(Re,Ge,Lr.LOCAL)}const Te=Le.length+it;Te>0&&tn.success(`成功上传 ${Te} 个文件`),await c()}catch(Te){console.error("[MediaLibrary] File upload error:",Te)}},[u,c]),ae=b.useCallback(()=>{var ge;(ge=z.current)==null||ge.click()},[]),Q=b.useCallback(ge=>{const Se=ge.target.files;Se&&J(Se),ge.target.value=""},[J]),se=l.find(ge=>ge.id===_)||null,ie=n==="SELECT"&&!!o,ce=b.useCallback(async ge=>{const Se=l.find(Ae=>Ae.id===ge);E&&Se&&(Av(Se.url)?nae(E,Se.dedupeUrls||[Se.url]):eae(E,Se.dedupeAssetIds||[ge])),await x(ge)},[E,x,l]);return g.jsxs(g.Fragment,{children:[g.jsxs(dce,{visible:e,title:"素材库",onClose:t,width:"85%",height:"85%",minWidth:800,minHeight:500,x:"center",y:"center",maximizable:!0,minimizable:!1,resizable:!0,movable:!0,modal:!1,className:"winbox-media-library media-library-modal","data-testid":"media-library-modal",icon:g.jsx(cI,{size:18}),children:[g.jsx("input",{ref:z,type:"file",accept:"image/*,video/*,audio/*,.zip,application/zip,application/x-zip-compressed",multiple:!0,style:{display:"none"},onChange:Q}),g.jsxs("div",{className:"media-library-layout",children:[g.jsx("div",{className:"media-library-layout__main",children:g.jsx(Ant,{filterType:r,filterCategory:i,selectedAssetId:_,onSelectAsset:O,onDoubleClick:U,onFileUpload:J,onUploadClick:ae,storageStatus:y,onSelectionChange:Z})}),!k&&g.jsx("div",{className:"media-library-layout__inspector",children:g.jsx(VV,{asset:se,selectedAssets:H,isSelectionMode:F,onRename:w,onDelete:ce,onDownload:oe,onMarkAsSubject:C,onSelect:ie?Y:void 0,onSelectMultiple:ie&&s?K:void 0,showSelectButton:ie,selecting:T,selectButtonText:a})})]})]}),k&&g.jsx(F3e,{visible:D,onClose:$,header:"素材详情",placement:"bottom",size:"70vh",destroyOnClose:!0,className:"media-library-mobile-drawer",children:g.jsx(VV,{asset:se,selectedAssets:H,isSelectionMode:F,onRename:w,onDelete:ce,onDownload:oe,onMarkAsSubject:C,onSelect:ie?Y:void 0,onSelectMultiple:ie&&s?K:void 0,showSelectButton:ie,selecting:T,selectButtonText:a})})]})}const bpt=Object.freeze(Object.defineProperty({__proto__:null,MediaLibraryModal:fce},Symbol.toStringTag,{value:"Module"})),jnt={image:"prompt-list-item__tag--image",video:"prompt-list-item__tag--video",audio:"prompt-list-item__tag--audio",text:"prompt-list-item__tag--text",agent:"prompt-list-item__tag--agent","ppt-common":"prompt-list-item__tag--ppt-common","ppt-slide":"prompt-list-item__tag--ppt-slide"},Lnt=({content:e,title:t,sentPrompt:n,tags:r,resultPreview:i,pinned:o=!1,isPreset:s=!1,modelType:a,scene:l,previewExamples:c,onClick:u,onTogglePin:d,onDelete:f,onPreviewExample:p,language:y="zh",disabled:v=!1})=>{const w=z=>{z.stopPropagation(),d==null||d()},C=z=>{z.stopPropagation(),f==null||f()},x=(c==null?void 0:c.slice(0,3))??[],E=x.length>0,_=(t==null?void 0:t.trim())||e,I=(r||[]).filter(Boolean).slice(0,4),D=!!(n||i||I.length>0)&&!E,P=x.length===1,k=!!(p&&!v),R=z=>N=>{N.preventDefault(),N.stopPropagation(),k&&(p==null||p({content:e,previewExamples:x,initialIndex:z}))},T=z=>{z.preventDefault(),z.stopPropagation()},M=z=>N=>{N.key!=="Enter"&&N.key!==" "||(N.preventDefault(),N.stopPropagation(),k&&(p==null||p({content:e,previewExamples:x,initialIndex:z})))},F=g.jsxs("div",{className:`prompt-list-item ${o?"prompt-list-item--pinned":""} ${s?"prompt-list-item--preset":""} ${v?"prompt-list-item--disabled":""}`,onClick:v?void 0:u,children:[o&&g.jsx("div",{className:"prompt-list-item__pin-badge",children:g.jsx(M8,{size:10})}),s&&g.jsx("div",{className:"prompt-list-item__preset-badge",children:g.jsx(SSe,{size:10})}),l&&g.jsx("span",{className:`prompt-list-item__tag ${a&&jnt[a]||""}`,children:l}),g.jsx("span",{className:"prompt-list-item__text",children:_}),g.jsxs("div",{className:"prompt-list-item__actions",children:[d&&g.jsx(cn,{content:o?y==="zh"?"取消置顶":"Unpin":y==="zh"?"置顶":"Pin",children:g.jsx("button",{type:"button",className:"prompt-list-item__action",onClick:w,children:o?g.jsx(JSe,{size:14}):g.jsx(M8,{size:14})})}),f&&g.jsx(cn,{content:y==="zh"?"删除":"Delete",children:g.jsx("button",{type:"button",className:"prompt-list-item__action prompt-list-item__action--delete",onClick:C,children:g.jsx(md,{size:14})})})]})]}),V=E?g.jsxs("div",{className:"prompt-list-item__hover-card",children:[g.jsx("div",{className:"prompt-list-item__hover-text",children:e}),g.jsx("div",{className:`prompt-list-item__hover-gallery ${P?"prompt-list-item__hover-gallery--single":""}`,children:x.map((z,N)=>g.jsx("div",{className:`prompt-list-item__hover-thumb ${P?"prompt-list-item__hover-thumb--single":""}`,children:k?g.jsx("button",{type:"button",className:"prompt-list-item__hover-thumb-button","aria-label":`${y==="zh"?"预览示例图":"Preview example"} ${N+1}`,onMouseDown:R(N),onClick:T,onKeyDown:M(N),children:g.jsx(xs,{src:z.kind==="video"&&z.posterSrc||z.src,alt:z.alt,showSkeleton:!1})}):g.jsx(xs,{src:z.kind==="video"&&z.posterSrc||z.src,alt:z.alt,showSkeleton:!1})},`${z.src}-${z.alt}`))}),k&&g.jsx("div",{className:"prompt-list-item__hover-hint",children:y==="zh"?"点击预览":"Click to preview"})]}):null,H=i?g.jsxs("div",{className:"prompt-list-item__result-preview",children:[(i.kind==="image"||i.kind==="video")&&g.jsx("div",{className:"prompt-list-item__result-media",children:g.jsx(xs,{src:i.kind==="video"&&i.posterUrl||i.url,alt:i.title||_,showSkeleton:!1})}),i.kind==="audio"&&g.jsxs("div",{className:"prompt-list-item__result-audio",children:[i.coverUrl&&g.jsx(xs,{src:i.coverUrl,alt:i.title||_,showSkeleton:!1}),g.jsxs("div",{children:[g.jsx("div",{className:"prompt-list-item__result-title",children:i.title||"音频结果"}),i.text&&g.jsx("div",{className:"prompt-list-item__result-text",children:i.text})]})]}),(i.kind==="text"||i.kind==="error"||i.kind==="none")&&g.jsxs("div",{className:`prompt-list-item__result-text ${i.kind==="error"?"prompt-list-item__result-text--error":""}`,children:[i.kind==="text"&&i.title&&g.jsx("strong",{children:i.title}),i.text]})]}):null,j=D?g.jsxs("div",{className:"prompt-list-item__history-card",children:[g.jsx("div",{className:"prompt-list-item__history-title",children:_}),n&&g.jsxs("div",{className:"prompt-list-item__history-section",children:[g.jsx("div",{className:"prompt-list-item__history-label",children:"发送提示词"}),g.jsx("div",{className:"prompt-list-item__history-text",children:n})]}),I.length>0&&g.jsx("div",{className:"prompt-list-item__history-tags",children:I.map(z=>g.jsx("span",{children:z},z))}),H&&g.jsxs("div",{className:"prompt-list-item__history-section",children:[g.jsx("div",{className:"prompt-list-item__history-label",children:"结果预览"}),H]})]}):null;return V?g.jsx(cn,{content:V,placement:"right",delay:40,overlayClassName:"prompt-list-item__hover-card-popover",children:F}):j?g.jsx(cn,{content:j,placement:"right",delay:60,overlayClassName:"prompt-list-item__history-card-popover",children:F}):g.jsx(cn,{content:_===e?e:`${_}
|
|
2592
2592
|
|
|
2593
2593
|
${e}`,placement:"right-top",delay:80,overlayClassName:"prompt-list-item__text-tip-popover",overlayInnerClassName:"prompt-list-item__text-tip",children:F})};function hce(e=lr){const[t,n]=b.useState(()=>ld.getState(e));return b.useEffect(()=>(n(ld.getState(e)),ld.subscribe(()=>{n(ld.getState(e))})),[e]),t}function pce(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n].id!==t[n].id||e[n].selectionKey!==t[n].selectionKey)return!1;return!0}function Dm(e){const t=hce(),n=b.useRef([]);return b.useMemo(()=>{const r=$Je(e);return pce(n.current,r)?n.current:(n.current=r,r)},[e,t])}function xpt(e,t){const n=hce(e),r=b.useRef([]);return b.useMemo(()=>{const i=zJe(e,t);return pce(r.current,i)?r.current:(r.current=i,i)},[e,t,n])}const Bnt={zh:[`产品海报:一款透明玻璃质感的智能水杯放在浅灰色桌面,背景是干净的厨房晨光。
|
|
2594
2594
|
画面保留顶部留白用于标题,主体居中偏下,真实摄影风格,柔和阴影,细节清晰,1:1。`,`人物形象:年轻创作者坐在整洁书桌前使用平板绘图,窗边自然光,神情专注。
|
|
@@ -2616,7 +2616,7 @@ Macro photography, shallow depth of field, quiet healing mood, delicate motion,
|
|
|
2616
2616
|
`):""}function ort(e){return["你是一名专业的「{{scenarioName}}」提示词优化助手。","","请基于用户原始提示词和补充要求,输出一版可直接用于下游模型的最终提示词。","","场景优化方向:",e.focus,"","通用要求:","1. 保持原始意图,不要擅自改题、换主题或新增关键事实。","2. 优先满足补充要求;补充要求为空时,仅做必要润色、结构补全和可执行性增强。","3. 输出语言尽量跟随原始提示词;中英混合时保留原表达习惯。","4. 原始提示词已经完整时,做轻量优化,避免堆砌无关细节。","5. 当前模式为 {{mode}}。structured 模式下可以强化结构、字段和可复用性;polish 模式下保持自然文本。","6. 只输出最终优化后的提示词,不要解释、不要标题、不要 Markdown 代码块。","","可用变量:{{originalPrompt}}、{{requirements}}、{{language}}、{{mode}}、{{scenarioName}}。"].join(`
|
|
2617
2617
|
`)}function srt(e,t){return e.replace(/\{\{\s*(originalPrompt|requirements|language|mode|scenarioName)\s*\}\}/g,(n,r)=>t[r])}async function art(){const t=(await Ko()).find(n=>n.name===sT);if(t)return t.id;try{return(await py(sT)).id}catch{const r=(await Ko()).find(i=>i.name===sT);if(!r)throw new Error("提示词优化目录创建失败");return r.id}}async function wce(e){const t=await art(),n=nrt(e.id),r=ort(e),o=(await d_(n))[0];if(o){const s=await vc(o.id),a=(s==null?void 0:s.content)||"";return a.trim()?a:(await c_(o.id,{title:o.title||e.noteTitle,directoryId:o.directoryId||t,content:r,metadata:{...o.metadata,sourceUrl:n,domain:"提示词优化",tags:["提示词优化",e.type]}}),r)}return await Wd(e.noteTitle,t,r,{sourceUrl:n,domain:"提示词优化",tags:["提示词优化",e.type]}),r}async function Cpt(){for(const e of Object.values(yce))await wce(e)}async function lrt({scenarioId:e,originalPrompt:t,optimizationRequirements:n,language:r,type:i,mode:o}){const s=vce(e,i),a=o||s.defaultMode,l=t.trim(),c=(n==null?void 0:n.trim())||"",u=await wce(s),d=srt(u,{originalPrompt:l,requirements:c||"无",language:r,mode:a,scenarioName:s.name}),f=irt(s,a,r),p=r==="zh"?["","---","以下输入块由系统固定附加,请必须以此为准:","","【原始提示词】",l,"","【补充要求】",c||"无,做通顺、准确、可执行的轻量优化。",f,"","【输出要求】",f?"只输出符合视觉结构化 schema 的合法 JSON 对象,不要解释、不要标题、不要 Markdown 代码块。":"只输出最终优化后的提示词,不要解释、不要标题、不要 Markdown 代码块。"]:["","---","The following input block is appended by the system and must be treated as authoritative:","","[Original Prompt]",l,"","[Refinement Requirements]",c||"None. Apply light polishing for clarity and execution quality.",f,"","[Output Requirement]",f?"Output only a valid JSON object following the visual structured schema. No explanation, no title, no Markdown code block.":"Output only the final optimized prompt. No explanation, no title, no Markdown code block."];return`${d.trim()}
|
|
2618
2618
|
${p.join(`
|
|
2619
|
-
`)}`}const crt=e=>{const t=e.trim(),n=t.match(/^```[\w-]*\n?([\s\S]*?)\n?```$/);return n?n[1].trim():t},pN=30,urt=60;function zC(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(xr.PROMPT_OPTIMIZE_REQUIREMENTS_HISTORY),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(n=>n&&typeof n.id=="string"&&typeof n.content=="string"&&typeof n.timestamp=="number"&&n.content.trim().length>0).sort((n,r)=>r.timestamp-n.timestamp).slice(0,pN):[]}catch{return[]}}function drt(e){if(!(typeof window>"u"))try{window.localStorage.setItem(xr.PROMPT_OPTIMIZE_REQUIREMENTS_HISTORY,JSON.stringify(e.slice(0,pN)))}catch{}}function frt(e){const t=e.trim();if(!t)return zC();const n=[{id:`requirements-${Date.now()}`,content:t,timestamp:Date.now()},...zC().filter(r=>r.content!==t)].slice(0,pN);return drt(n),n}const hrt=e=>{const{open:t,onOpenChange:n,originalPrompt:r,language:i,type:o,onApply:s,historyType:a,allowStructuredMode:l=!1,defaultMode:c}=e,u=e.scenarioId,d=b.useId(),f=b.useId(),p=b.useId(),y=b.useId(),v=b.useMemo(()=>vce(u,o),[u,o]),w=o||v.type,C=a||v.historyType,x=c??v.defaultMode,[E,_]=b.useState(""),[I,D]=b.useState(r),[P,k]=b.useState(""),[R,T]=b.useState(x),[M,F]=b.useState(!1),[V,H]=b.useState(null),[j,z]=b.useState([]),N=b.useRef(null),B=b.useRef(!1),O=b.useRef(null),{isMobile:$,viewportWidth:U,viewportHeight:Y}=ule(),{history:K,addHistory:Z,refreshHistory:oe}=mce({deduplicateWithPresets:!1,modelTypeFilter:C}),J=Dm("text"),ae=b.useCallback(()=>{var At;const He=so("text"),we=qn(He.profileId,He.modelId),ue=He.modelId||((At=J[0])==null?void 0:At.id)||"",_e=we||(ue?qn(null,ue):null),xe=f7e(xr.PROMPT_OPTIMIZE_TEXT_MODEL,ue,_e),Fe=$C(J,xe.modelId,xe.modelRef)||KM("text",xe.modelId,xe.modelRef),lt=(Fe==null?void 0:Fe.id)||xe.modelId||ue,Ht=GV(Fe)||xe.modelRef||_e||(lt?qn(null,lt):null);return{modelId:lt,modelRef:Ht}},[J]),[Q,se]=b.useState(()=>ae().modelId),[ie,ce]=b.useState(()=>ae().modelRef),ge=b.useMemo(()=>{if($C(J,Q,ie)||!Q)return J;const we=KM("text",Q,ie);return we?[we,...J]:J},[Q,ie,J]),Se=b.useCallback(()=>{const He=ae();se(He.modelId),ce(He.modelRef)},[ae]),Ae=b.useCallback(()=>{var He;(He=N.current)==null||He.abort(),N.current=null,B.current=!1,F(!1),_(""),k(""),T(x),n(!1)},[x,n]),Le=b.useCallback(async()=>{var _e;const He=I.trim();if(!He){tn.warning(i==="zh"?"请先填写当前提示词":"Please enter the current prompt first");return}if(B.current||M)return;B.current=!0,Z(He,!1,C||w),E.trim()&&z(frt(E));const we=new AbortController,ue=Date.now();(_e=N.current)==null||_e.abort(),N.current=we,F(!0),Kt.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,status:"start",model:Q||void 0,prompt:He,requirements:E});try{const xe=crt((await tR.getFallbackExecutor().generateText({prompt:await lrt({scenarioId:u,originalPrompt:He,optimizationRequirements:E,language:i,type:w,mode:R}),model:Q||void 0,modelRef:ie},{signal:we.signal})).content);if(!xe)throw new Error("Empty optimized prompt");k(xe),Kt.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,status:"success",model:Q||void 0,prompt:He,requirements:E,durationMs:Date.now()-ue,metadata:{result_length_bucket:xe.length<=200?"1-200":xe.length<=500?"201-500":xe.length<=1e3?"501-1000":"1000+"}}),tn.success(i==="zh"?R==="structured"?"结构化提示词已生成,可继续优化或回填":"提示词优化完成,可继续优化或回填":R==="structured"?"Structured prompt generated. You can refine again or apply it.":"Prompt optimized. You can refine again or apply it."),_("")}catch(xe){if(we.signal.aborted){Kt.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,status:"cancelled",model:Q||void 0,prompt:He,requirements:E,durationMs:Date.now()-ue});return}console.error("[PromptOptimizeDialog] Failed to optimize prompt:",xe),Kt.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,status:"failed",model:Q||void 0,prompt:He,requirements:E,durationMs:Date.now()-ue,metadata:{error:xe instanceof Error?xe.name||"Error":typeof xe}}),tn.error(i==="zh"?R==="structured"?"结构化提示词生成失败,请稍后重试":"提示词优化失败,请稍后重试":R==="structured"?"Failed to generate structured prompt, please try again later":"Failed to optimize prompt, please try again later")}finally{N.current===we&&(N.current=null),B.current=!1,F(!1)}},[I,i,R,Q,ie,E,Z,C,w,M,u]),it=b.useCallback(()=>{const He=P.trim();He&&(Kt.trackPromptAction({action:"use_draft_as_current",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,prompt:He}),D(He),_(""))},[C,w,R,P]),Te=b.useCallback(()=>{const He=(P||I).trim();if(!He){tn.warning(i==="zh"?"没有可回填的提示词":"There is no prompt to apply");return}Kt.trackPromptAction({action:"apply",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,prompt:He}),s(He),Ae()},[I,C,w,Ae,i,R,s,P]);b.useEffect(()=>{t&&(Se(),D(r),k(""),_(""),z(zC()),H(null),T(x))},[x,t,r,Se]),b.useEffect(()=>()=>{var He;(He=N.current)==null||He.abort(),N.current=null,B.current=!1},[]),b.useEffect(()=>{if(!V)return;const He=we=>{var _e;const ue=we.target;ue instanceof Node&&((_e=O.current)!=null&&_e.contains(ue))||ue instanceof Element&&ue.closest(".prompt-optimize-dialog__history-btn")||H(null)};return document.addEventListener("mousedown",He,!0),()=>{document.removeEventListener("mousedown",He,!0)}},[V]);const Re=i==="zh"?R==="structured"?"例如:突出时间轴结构、把区域与数量拆开、保留标题与图例、输出 JSON 不要解释...":"例如:更电影感、补充镜头语言、减少冗余、强调主体与光线...":R==="structured"?"For example: emphasize timeline structure, split regions and counts, preserve titles and legends, output JSON only...":"For example: make it more cinematic, add camera language, reduce redundancy, emphasize subject and lighting...",ht=I.trim().length>0,Ze=(P.length>0?P:I).trim().length>0,Ge=P.length>0,pt=b.useMemo(()=>K.slice(0,urt).map(He=>({id:He.id,content:He.content,pinned:He.pinned,modelType:He.modelType})),[K]),at=b.useMemo(()=>j.map(He=>({id:He.id,content:He.content})),[j]),ct=b.useMemo(()=>`prompt-optimize-dialog-${d.replace(/[^a-zA-Z0-9_-]/g,"")}`,[d]),nt=i==="zh"?R==="structured"?"结构化提示词":"提示词优化":R==="structured"?"Structured Prompt":"Prompt Optimization",It=b.useMemo(()=>{const He=$?16:48,we=Math.max(280,U-He),ue=Math.max(320,Y-He),_e=Ge?1120:680,xe=Ge?760:680,Fe=Math.max(280,Math.min(_e,we)),lt=Math.max(320,Math.min(xe,ue));return{width:Fe,height:lt,minWidth:Math.min(Ge?640:320,Fe),minHeight:Math.min(420,lt)}},[Ge,$,Y,U]),Lt=b.useCallback(He=>{He==="current"?oe():z(zC()),Kt.trackPromptAction({action:"toggle_history",surface:"prompt_optimize_dialog",promptType:He==="current"?C||w:void 0,mode:R,metadata:{panel:He}}),H(we=>we===He?null:He)},[C,w,R,oe]),dt=b.useCallback(He=>{D(He.content),H(null)},[]),wt=b.useCallback(He=>{_(He.content),H(null)},[]),mt=b.useCallback(He=>{Kt.trackPromptAction({action:"mode_select",surface:"prompt_optimize_dialog",promptType:C||w,mode:He}),T(He)},[C,w]),Bt=(He,we,ue)=>V!==He?null:g.jsx("div",{ref:O,className:"prompt-optimize-dialog__history-panel",children:we.length>0?g.jsx(Ynt,{title:i==="zh"?"历史":"History",items:we,onSelect:ue,language:i,analyticsSurface:`prompt_optimize_${He}_history`,analyticsPromptType:He==="current"?C||w:void 0,showCount:!0}):g.jsx("div",{className:"prompt-optimize-dialog__history-empty",children:i==="zh"?"暂无历史":"No history yet"})});return t?g.jsx(dce,{id:ct,visible:t,title:nt,icon:g.jsx(Hv,{size:16}),onClose:Ae,width:It.width,height:It.height,minWidth:It.minWidth,minHeight:It.minHeight,x:"center",y:"center",maximizable:!$,minimizable:!1,resizable:!$,movable:!$,modal:!1,background:"#ffffff",className:`winbox-ai-generation winbox-prompt-optimize ${Ge?"winbox-prompt-optimize--split":""}`,children:g.jsxs("div",{className:`prompt-optimize-dialog ${Ge?"prompt-optimize-dialog--split":""}`,children:[g.jsxs("div",{className:`prompt-optimize-dialog__body ${Ge?"prompt-optimize-dialog__body--split":""}`,children:[g.jsxs("div",{className:"prompt-optimize-dialog__form-pane",children:[g.jsxs("div",{className:"prompt-optimize-dialog__section prompt-optimize-dialog__section--current",children:[g.jsxs("div",{className:"prompt-optimize-dialog__label-row",children:[g.jsx("label",{className:"prompt-optimize-dialog__label",htmlFor:f,children:i==="zh"?"当前提示词":"Current Prompt"}),g.jsx("button",{type:"button",className:"prompt-optimize-dialog__history-btn",onClick:()=>Lt("current"),"aria-label":i==="zh"?"当前提示词历史":"Current prompt history",children:g.jsx(RT,{size:16})}),Bt("current",pt,dt)]}),g.jsx("textarea",{id:f,className:"prompt-optimize-dialog__textarea prompt-optimize-dialog__textarea--current",value:I,onChange:He=>D(He.target.value),placeholder:i==="zh"?"输入或编辑要优化的提示词...":"Enter or edit the prompt to optimize...",rows:5,disabled:M})]}),g.jsxs("div",{className:"prompt-optimize-dialog__section prompt-optimize-dialog__section--requirements",children:[g.jsxs("div",{className:"prompt-optimize-dialog__label-row",children:[g.jsx("label",{className:"prompt-optimize-dialog__label",htmlFor:p,children:i==="zh"?"补充要求":"Additional Requirements"}),g.jsx("button",{type:"button",className:"prompt-optimize-dialog__history-btn",onClick:()=>Lt("requirements"),"aria-label":i==="zh"?"补充要求历史":"Additional requirements history",children:g.jsx(RT,{size:16})}),Bt("requirements",at,wt)]}),g.jsx("textarea",{id:p,className:"prompt-optimize-dialog__textarea",value:E,onChange:He=>_(He.target.value),placeholder:Re,rows:4,disabled:M})]})]}),Ge&&g.jsx("div",{className:"prompt-optimize-dialog__result-pane",children:g.jsxs("div",{className:"prompt-optimize-dialog__section prompt-optimize-dialog__section--result",children:[g.jsx("div",{className:"prompt-optimize-dialog__result-header",children:g.jsx("label",{className:"prompt-optimize-dialog__label",htmlFor:y,children:i==="zh"?"优化结果草稿":"Optimized Draft"})}),g.jsx("textarea",{id:y,className:"prompt-optimize-dialog__textarea prompt-optimize-dialog__textarea--draft",value:P,onChange:He=>k(He.target.value),rows:6,disabled:M})]})})]}),g.jsxs("div",{className:`prompt-optimize-dialog__footer ${Ge?"prompt-optimize-dialog__footer--split":""}`,children:[g.jsxs("div",{className:"prompt-optimize-dialog__footer-actions prompt-optimize-dialog__footer-actions--form",children:[g.jsxs("div",{className:"prompt-optimize-dialog__footer-controls",children:[l&&g.jsxs("div",{className:"prompt-optimize-dialog__mode-switch","aria-label":i==="zh"?"输出模式":"Output Mode",children:[g.jsxs("button",{type:"button",className:`prompt-optimize-dialog__mode-btn ${R==="polish"?"prompt-optimize-dialog__mode-btn--active":""}`,onClick:()=>mt("polish"),disabled:M,children:[g.jsx(Hv,{size:14}),g.jsx("span",{children:i==="zh"?"普通润色":"Polish"})]}),g.jsx("button",{type:"button",className:`prompt-optimize-dialog__mode-btn ${R==="structured"?"prompt-optimize-dialog__mode-btn--active":""}`,onClick:()=>mt("structured"),disabled:M,children:g.jsx("span",{children:i==="zh"?"结构化 JSON":"Structured JSON"})})]}),g.jsx("div",{className:"prompt-optimize-dialog__model",children:g.jsx(X3,{selectedModel:Q,selectedSelectionKey:hN(Q,ie),onSelect:(He,we)=>{const ue=we||null;Kt.trackPromptAction({action:"model_select",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,model:He}),se(He),ce(ue),yU(xr.PROMPT_OPTIMIZE_TEXT_MODEL,He,ue)},onSelectModel:He=>{const we=GV(He);Kt.trackPromptAction({action:"model_select",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,model:He.id}),se(He.id),ce(we),yU(xr.PROMPT_OPTIMIZE_TEXT_MODEL,He.id,we)},language:i,models:ge,placement:"up",header:i==="zh"?"选择文本模型 (↑↓ Tab)":"Select text model (↑↓ Tab)",disabled:M})})]}),g.jsxs("div",{className:"prompt-optimize-dialog__footer-buttons",children:[g.jsx("button",{type:"button",className:"prompt-optimize-dialog__footer-btn prompt-optimize-dialog__footer-btn--primary",onClick:()=>void Le(),disabled:M||!ht,children:i==="zh"?M?R==="structured"?"生成中...":"优化中...":R==="structured"?"生成结构化提示词":"开始优化":M?R==="structured"?"Generating...":"Optimizing...":R==="structured"?"Generate Structured Prompt":"Optimize"}),g.jsx("button",{type:"button",className:"prompt-optimize-dialog__footer-btn prompt-optimize-dialog__footer-btn--apply",onClick:Te,disabled:M||!Ze,children:i==="zh"?"回填":"Apply"})]})]}),Ge&&g.jsx("div",{className:"prompt-optimize-dialog__footer-actions prompt-optimize-dialog__footer-actions--result",children:g.jsx("button",{type:"button",className:"prompt-optimize-dialog__footer-btn prompt-optimize-dialog__footer-btn--secondary",onClick:it,disabled:M,children:i==="zh"?"用结果继续优化":"Use Draft to Refine"})})]})]})}):null},Ept=({disabled:e=!1,className:t,iconSize:n=16,tooltipPlacement:r="right",tooltipContent:i,language:o,onApply:s,onMouseDown:a,onOpenChange:l,...c})=>{const[u,d]=b.useState(!1),f=b.useCallback(v=>{d(v),l==null||l(v)},[l]),p=b.useCallback(v=>{s(v)},[s]),y=o==="zh"?"提示词优化":"Prompt optimization";return g.jsxs(g.Fragment,{children:[g.jsx(cn,{content:i??y,placement:r,disabled:e,children:g.jsx("button",{type:"button",className:t||"prompt-optimize-button",disabled:e,onMouseDown:a,onClick:()=>f(!0),"aria-label":y,children:g.jsx(Hv,{size:n})})}),g.jsx(hrt,{...c,language:o,open:u,onOpenChange:f,onApply:p})]})};function KV(e){return e.toLowerCase().replace(/\s+/g,"").trim()}function prt(e,t,n){const r=KV(n);if(!r)return e;const i=new Map(t.map(o=>[o.id,o.name]));return e.filter(o=>{var a,l,c,u;return KV([o.title,(a=o.metadata)==null?void 0:a.description,(l=o.metadata)==null?void 0:l.domain,(c=o.metadata)==null?void 0:c.sourceUrl,i.get(o.directoryId),...((u=o.metadata)==null?void 0:u.tags)||[]].filter(Boolean).join(" ")).includes(r)})}function mrt(e,t,n){return!t.includes(e)&&t.length>=n}function grt(e,t="zh"){const n=e.map(o=>o.title||"未命名笔记"),r=n.join("、"),i=e.length>0;return{triggerLabel:i?t==="zh"?`知识库上下文,已选 ${e.length} 篇笔记`:`Knowledge context, ${e.length} notes selected`:t==="zh"?"选择知识库笔记":"Select knowledge notes",selectedTitleText:r,hoverTitle:t==="zh"?"已选知识库笔记":"Selected notes",noteTitles:n,shouldShowChips:!1,canClear:i,clearLabel:t==="zh"?"清除":"Clear",clearAriaLabel:t==="zh"?"清除已选知识库笔记":"Clear selected knowledge notes",addNoteLabel:t==="zh"?"添加笔记":"Add note",addNoteAriaLabel:t==="zh"?"打开知识库新建笔记":"Open knowledge base to add note",badgeText:i?String(e.length):void 0}}function yrt(e){if(!e)return"";try{return new Date(e).toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})}catch{return""}}const _pt=({value:e,onChange:t,disabled:n=!1,label:r,language:i="zh",maxNotes:o=qte,className:s="",variant:a="default",placement:l="down"})=>{const[c,u]=b.useState(!1),[d,f]=b.useState(!1),[p,y]=b.useState([]),[v,w]=b.useState([]),[C,x]=b.useState(""),E=b.useRef(null),_=b.useRef(null),[I,D]=b.useState({}),P=b.useMemo(()=>_h(e,o),[o,e]),k=b.useMemo(()=>new Set(P.map(K=>K.noteId)),[P]),R=b.useMemo(()=>new Map(v.map(K=>[K.id,K.name])),[v]),T=b.useCallback(async()=>{f(!0);try{await vv.initialize();const[K,Z]=await Promise.all([vv.getAllNoteMetas(),vv.getAllDirectories()]);y([...K].sort((oe,J)=>J.updatedAt-oe.updatedAt)),w(Z)}finally{f(!1)}},[]);b.useEffect(()=>{c&&T()},[T,c]),b.useEffect(()=>{if(!c)return;const K=Z=>{var J,ae;const oe=Z.target;!((J=E.current)!=null&&J.contains(oe))&&!((ae=_.current)!=null&&ae.contains(oe))&&u(!1)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[c]),b.useEffect(()=>{if(!c||a!=="compact"||!E.current)return;const K=()=>{var ae;const Z=(ae=E.current)==null?void 0:ae.getBoundingClientRect();if(!Z)return;const oe=Math.min(360,Math.max(240,window.innerWidth-32)),J=Math.min(Math.max(16,Z.left),window.innerWidth-oe-16);D({position:"fixed",top:"auto",bottom:window.innerHeight-Z.top+8,left:J,width:oe,zIndex:Eu.DROPDOWN_PORTAL})};return K(),window.addEventListener("resize",K),window.addEventListener("scroll",K,!0),()=>{window.removeEventListener("resize",K),window.removeEventListener("scroll",K,!0)}},[c,a]);const M=b.useMemo(()=>prt(p,v,C),[v,p,C]),F=b.useCallback(K=>{const oe=k.has(K.id)?P.filter(J=>J.noteId!==K.id):[...P,OFe(K)];t(_h(oe,o))},[o,t,k,P]),V=b.useCallback(K=>{t(P.filter(Z=>Z.noteId!==K))},[t,P]),H=b.useCallback(K=>{K==null||K.stopPropagation(),t([])},[t]),j=b.useCallback(K=>{if(K==null||K.stopPropagation(),n||typeof window>"u")return;const Z={directoryName:"笔记",autoCreateNote:!0};window.__kbPendingNavigation=Z,window.dispatchEvent(new CustomEvent("kb:open",{detail:{}})),window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("kb:navigate",{detail:Z}))},300),u(!1)},[n]),z=r||(i==="zh"?"知识库上下文":"Knowledge Context"),N=i==="zh"?"搜索知识库笔记...":"Search notes...",B=i==="zh"?"暂无可选笔记":"No notes available",O=i==="zh"?"无匹配笔记":"No matching notes",$=a==="compact",U=grt(P,i),Y=c?g.jsxs("div",{ref:_,className:"knowledge-note-context-selector__dropdown",style:$?I:void 0,onMouseDown:K=>K.stopPropagation(),children:[g.jsxs("div",{className:"knowledge-note-context-selector__search",children:[g.jsx(sR,{size:14}),g.jsx("input",{value:C,onChange:K=>x(K.target.value),placeholder:N,autoFocus:!0})]}),g.jsx("div",{className:"knowledge-note-context-selector__list",children:d?g.jsx("div",{className:"knowledge-note-context-selector__empty",children:i==="zh"?"加载中...":"Loading..."}):M.length>0?M.map(K=>{const Z=k.has(K.id),oe=mrt(K.id,P.map(ae=>ae.noteId),o),J=R.get(K.directoryId);return g.jsxs("button",{type:"button",className:`knowledge-note-context-selector__item ${Z?"knowledge-note-context-selector__item--selected":""}`,onClick:()=>!oe&&F(K),disabled:oe,children:[g.jsxs("span",{className:"knowledge-note-context-selector__item-main",children:[g.jsx("span",{className:"knowledge-note-context-selector__item-title",children:K.title||"未命名笔记"}),g.jsx("span",{className:"knowledge-note-context-selector__item-meta",children:[J,yrt(K.updatedAt)].filter(Boolean).join(" · ")})]}),Z?g.jsx(Nd,{size:15}):null]},K.id)}):g.jsx("div",{className:"knowledge-note-context-selector__empty",children:p.length===0?B:O})}),g.jsxs("div",{className:"knowledge-note-context-selector__footer",children:[g.jsx("span",{className:"knowledge-note-context-selector__footer-text",children:i==="zh"?`最多选择 ${o} 篇,提交时按需读取正文`:`Up to ${o}; content is read on submit`}),g.jsxs("span",{className:"knowledge-note-context-selector__footer-actions",children:[g.jsxs("button",{type:"button",className:"knowledge-note-context-selector__footer-add",onClick:j,disabled:n,"aria-label":U.addNoteAriaLabel,children:[g.jsx(ic,{size:12}),U.addNoteLabel]}),U.canClear?g.jsx("button",{type:"button",className:"knowledge-note-context-selector__footer-clear",onClick:H,disabled:n,"aria-label":U.clearAriaLabel,children:U.clearLabel}):null]})]})]}):null;return g.jsxs("div",{className:Je("knowledge-note-context-selector",{"knowledge-note-context-selector--compact":$,"knowledge-note-context-selector--selected":P.length>0,"knowledge-note-context-selector--open":c,"knowledge-note-context-selector--placement-up":l==="up"},s),ref:E,children:[$?null:g.jsxs("div",{className:"knowledge-note-context-selector__header",children:[g.jsx("span",{className:"knowledge-note-context-selector__label",children:z}),P.length>0?g.jsx("button",{type:"button",className:"knowledge-note-context-selector__clear",onClick:H,disabled:n,children:i==="zh"?"清空":"Clear"}):null]}),g.jsxs("button",{type:"button",className:"knowledge-note-context-selector__trigger",onClick:()=>!n&&u(K=>!K),disabled:n,"aria-expanded":c,"aria-label":U.triggerLabel,title:$?U.selectedTitleText||U.triggerLabel:void 0,children:[g.jsx(yS,{size:$?18:15}),$?U.badgeText?g.jsx("span",{className:"knowledge-note-context-selector__badge",children:U.badgeText}):null:g.jsxs(g.Fragment,{children:[g.jsx("span",{children:P.length>0?i==="zh"?`已选 ${P.length} 篇笔记`:`${P.length} notes selected`:i==="zh"?"选择知识库笔记":"Select notes"}),g.jsx(lg,{size:15})]})]}),$&&P.length>0?g.jsxs("div",{className:"knowledge-note-context-selector__hover-summary","aria-label":i==="zh"?`已选知识库笔记:${U.selectedTitleText}`:`Selected knowledge notes: ${U.selectedTitleText}`,children:[g.jsx("div",{className:"knowledge-note-context-selector__hover-title",children:U.hoverTitle}),g.jsx("div",{className:"knowledge-note-context-selector__hover-list",children:P.map((K,Z)=>g.jsx("div",{className:"knowledge-note-context-selector__hover-item",children:U.noteTitles[Z]},K.noteId))})]}):null,!$&&P.length>0?g.jsx("div",{className:"knowledge-note-context-selector__chips",children:P.map(K=>g.jsxs("span",{className:"knowledge-note-context-selector__chip",children:[g.jsx("span",{children:K.title}),g.jsx("button",{type:"button",onClick:()=>V(K.noteId),disabled:n,"aria-label":i==="zh"?"移除笔记":"Remove note",children:g.jsx(md,{size:12})})]},K.noteId))}):null,$&&Y?Ui.createPortal(Y,document.body):Y]})},vrt=({visible:e,items:t,initialIndex:n=0,onClose:r,onIndexChange:i,showToolbar:o=!0,className:s="",showTitle:a=!0,videoAutoPlay:l=!0,videoLoop:c=!0})=>{const u=t.map((d,f)=>({id:`media-${f}`,url:d.url,type:d.type,title:d.title,alt:d.alt,posterUrl:d.posterUrl,duration:d.duration,prompt:d.prompt,tags:d.tags,artist:d.artist,album:d.album}));return g.jsx(Hg,{visible:e,items:u,initialMode:"single",initialIndex:n,onClose:r,showThumbnails:t.length>1,className:s,showTitle:a,videoAutoPlay:l,videoLoop:c})};function wrt(e){switch(e){case"strict":return{borderRatio:1,maxTrimRatio:.05};case"normal":return{borderRatio:.95,maxTrimRatio:.05};case"none":return null}}function Ipt(e,t=10){if(e.length===0)return[];const n=[...e].sort((s,a)=>s-a),r=[];let i=n[0],o=n[0];for(let s=1;s<n.length;s++)n[s]-o<=t||(r.push(Math.round((i+o)/2)),i=n[s]),o=n[s];return r.push(Math.round((i+o)/2)),r}function bce(e,t,n,r=240){return e>=r&&t>=r&&n>=r}function mN(e,t=50){return e<t}function xce(e,t){const{width:n,data:r}=e;let i=0;for(let o=0;o<n;o++){const s=(t*n+o)*4;bce(r[s],r[s+1],r[s+2])&&i++}return i/n}function brt(e,t){const{width:n,data:r}=e;let i=0;for(let o=0;o<n;o++){const s=(t*n+o)*4;mN(r[s+3])&&i++}return i/n}function Sce(e,t){const{width:n,height:r,data:i}=e;let o=0;for(let s=0;s<r;s++){const a=(s*n+t)*4;bce(i[a],i[a+1],i[a+2])&&o++}return o/r}function xrt(e,t){const{width:n,height:r,data:i}=e;let o=0;for(let s=0;s<r;s++){const a=(s*n+t)*4;mN(i[a+3])&&o++}return o/r}function Srt(e,t,n=.9){return xce(e,t)>=n}function Crt(e,t,n=1){return brt(e,t)>=n}function Ert(e,t,n=.9){return Sce(e,t)>=n}function _rt(e,t,n=1){return xrt(e,t)>=n}function qV(e,t=10){if(e.length===0)return[];const n=[...e].sort((s,a)=>s-a),r=[];let i=n[0],o=n[0];for(let s=1;s<n.length;s++)n[s]-o<=t||(r.push(Math.floor((i+o)/2)),i=n[s]),o=n[s];return r.push(Math.floor((i+o)/2)),r}function Irt(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(o=>{const s=e/o.cols,a=t/o.rows,l=s/a,u=1/(1+Math.abs(l-1)*10);return{...o,score:u,cellAspectRatio:l}}).filter(o=>o.cellAspectRatio>=.8&&o.cellAspectRatio<=1.25)}function Art(e,t,n){const r=Irt(t,n);if(r.length===0)return null;for(const i of r)if(Prt(e,t,n,i.rows,i.cols))return{rows:i.rows,cols:i.cols};return null}function Prt(e,t,n,r,i){const o=t/i,s=n/r,a=10,l=.7;for(let c=1;c<i;c++){const u=Math.round(c*o);let d=!1;for(let f=u-a;f<=u+a;f++){if(f<0||f>=t)continue;if(Sce(e,f)>=l){d=!0;break}}if(!d)return!1}for(let c=1;c<r;c++){const u=Math.round(c*s);let d=!1;for(let f=u-a;f<=u+a;f++){if(f<0||f>=n)continue;if(xce(e,f)>=l){d=!0;break}}if(!d)return!1}return!0}const krt=[{rows:2,cols:2,minMean:42,minStrongRatio:.46},{rows:2,cols:3,minMean:44,minStrongRatio:.48},{rows:3,cols:2,minMean:44,minStrongRatio:.48},{rows:2,cols:4,minMean:46,minStrongRatio:.5},{rows:4,cols:2,minMean:46,minStrongRatio:.5},{rows:3,cols:3,minMean:50,minStrongRatio:.52}];function Trt(e,t,n,r){const i=e/r,o=t/n,s=i/o;return s>=.72&&s<=1.4}function Cce(e,t,n){const r=e[t]-e[n],i=e[t+1]-e[n+1],o=e[t+2]-e[n+2];return Math.sqrt(r*r+i*i+o*o)}function Drt(e,t){const{width:n,height:r,data:i}=e;if(t<=0||t>=n)return{mean:0,strongRatio:0,edgeBalance:0};const o=Math.floor(r*.03),s=Math.ceil(r*.97),a=Math.max(1,Math.floor(r/900));let l=0,c=0,u=0,d=0,f=0;for(let p=o;p<s;p+=a){const y=(p*n+t-1)*4,v=(p*n+t)*4,w=Cce(i,y,v);l+=w,w>=42?(c++,f++,d=Math.max(d,f)):f=0,u++}return u>0?{mean:l/u,strongRatio:c/u,edgeBalance:d/u}:{mean:0,strongRatio:0,edgeBalance:0}}function Mrt(e,t){const{width:n,height:r,data:i}=e;if(t<=0||t>=r)return{mean:0,strongRatio:0,edgeBalance:0};const o=Math.floor(n*.03),s=Math.ceil(n*.97),a=Math.max(1,Math.floor(n/900));let l=0,c=0,u=0,d=0,f=0;for(let p=o;p<s;p+=a){const y=((t-1)*n+p)*4,v=(t*n+p)*4,w=Cce(i,y,v);l+=w,w>=42?(c++,f++,d=Math.max(d,f)):f=0,u++}return u>0?{mean:l/u,strongRatio:c/u,edgeBalance:d/u}:{mean:0,strongRatio:0,edgeBalance:0}}function YV(e,t){return e.edgeBalance>=.18&&e.mean>=((t==null?void 0:t.minMean)??42)&&e.strongRatio>=((t==null?void 0:t.minStrongRatio)??.46)}function Ort(e,t){const n=Math.max(4,Math.floor(e.width*.006));let r={mean:0,strongRatio:0,edgeBalance:0,position:t};for(let i=t-n;i<=t+n;i++){const o=Drt(e,i);o.mean*o.strongRatio>r.mean*r.strongRatio&&(r={...o,position:i})}return r}function Rrt(e,t){const n=Math.max(4,Math.floor(e.height*.006));let r={mean:0,strongRatio:0,edgeBalance:0,position:t};for(let i=t-n;i<=t+n;i++){const o=Mrt(e,i);o.mean*o.strongRatio>r.mean*r.strongRatio&&(r={...o,position:i})}return r}function Nrt(e,t,n){let r=null;for(const i of krt){if(!Trt(t,n,i.rows,i.cols))continue;const o=t/i.cols,s=n/i.rows,a=[],l=[],c=[];let u=!0;for(let f=1;f<i.cols;f++){const p=Ort(e,Math.round(f*o));if(!YV(p,i)){u=!1;break}a.push(p),l.push(p.position)}if(!u)continue;for(let f=1;f<i.rows;f++){const p=Rrt(e,Math.round(f*s));if(!YV(p,i)){u=!1;break}a.push(p),c.push(p.position)}if(!u||a.length===0)continue;const d=a.reduce((f,p)=>f+p.mean*p.strongRatio*p.edgeBalance,0)/a.length;(!r||d>(r.score??0))&&(r={...i,rowLines:c,colLines:l,score:d})}return r}function XV(e,t=3){if(e.length===0)return[];const n=[...e].sort((s,a)=>s-a),r=[];let i=n[0],o=n[0];for(let s=1;s<=n.length;s++)s<n.length&&n[s]-o<=1?o=n[s]:(o-i+1>=t&&r.push(Math.floor((i+o)/2)),s<n.length&&(i=n[s],o=n[s]));return r}function jrt(e){const{data:t}=e;for(let n=3;n<t.length;n+=4)if(t[n]>50)return!1;return!0}function Ece(e){const{data:t}=e;let n=0;const r=t.length/4;for(let o=3;o<t.length;o+=40)mN(t[o])&&n++;const i=Math.floor(r/10);return n/i>.05}async function _ce(e,t){const n=await jh(e),{naturalWidth:r,naturalHeight:i}=n,o=document.createElement("canvas");o.width=r,o.height=i;const s=o.getContext("2d",{willReadFrequently:!0});if(!s)throw new Error("Failed to get canvas context");s.drawImage(n,0,0);const a=s.getImageData(0,0,r,i),l=t??Ece(a),c=[],u=Math.floor(i*.05);if(l)for(let E=u;E<i-u;E++)Crt(a,E)&&c.push(E);else for(let E=u;E<i-u;E++)Srt(a,E)&&c.push(E);const d=[],f=Math.floor(r*.05);if(l)for(let E=f;E<r-f;E++)_rt(a,E)&&d.push(E);else for(let E=f;E<r-f;E++)Ert(a,E)&&d.push(E);const p=XV(c,2),y=XV(d,2),v=qV(p,Math.floor(i*.02)),w=qV(y,Math.floor(r*.02)),C=Art(a,r,i);if(C){const E=r/C.cols,_=i/C.rows,I=[],D=[];for(let P=1;P<C.rows;P++)I.push(Math.round(P*_));for(let P=1;P<C.cols;P++)D.push(Math.round(P*E));return{detection:{rows:C.rows,cols:C.cols,rowLines:I,colLines:D},img:n,imageData:a,canvas:o,hasTransparency:l}}const x=l?null:Nrt(a,r,i);return x?{detection:{rows:x.rows,cols:x.cols,rowLines:x.rowLines??[],colLines:x.colLines??[],useDetectedLines:!0},img:n,imageData:a,canvas:o,hasTransparency:l}:{detection:{rows:v.length+1,cols:w.length+1,rowLines:v,colLines:w},img:n,imageData:a,canvas:o,hasTransparency:l}}async function Ice(e,t){const{detection:n}=await _ce(e,t);return n}async function Lrt(e){try{const{detectPhotoWallRegions:t}=await xn(async()=>{const{detectPhotoWallRegions:r}=await import("./photo-wall-splitter-D2Ji--gy.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 Brt(e,t,n){const{rowLines:r,colLines:i}=e;if(e.useDetectedLines||r.length===0||i.length===0)return!1;const o=n/(r.length+1);for(let a=0;a<r.length;a++){const l=o*(a+1);if(Math.abs(r[a]-l)>o*.15)return!1}const s=t/(i.length+1);for(let a=0;a<i.length;a++){const l=s*(a+1);if(Math.abs(i[a]-l)>s*.15)return!1}return!0}async function Frt(e,t,n,r){const i=e.naturalWidth,o=e.naturalHeight,s=Math.floor(i/n),a=Math.floor(o/t),l=[];for(let c=0;c<t;c++)for(let u=0;u<n;u++){const d=c*n+u,f=u*s,p=c*a,y=document.createElement("canvas");y.width=s,y.height=a;const v=y.getContext("2d");v&&(v.drawImage(e,f,p,s,a,0,0,s,a),l.push({imageData:y.toDataURL("image/jpeg",.92),index:d,width:s,height:a,sourceX:f,sourceY:p,hasTransparency:r}))}return l}async function gN(e,t,n,r){const i=await jh(e),{naturalWidth:o,naturalHeight:s}=i;if(Brt(t,o,s))return Frt(i,t.rows,t.cols,n);const l=[0,...t.rowLines,s],c=[0,...t.colLines,o],u=[];let d=0;const f=document.createElement("canvas");f.width=o,f.height=s;const p=f.getContext("2d",{willReadFrequently:!0});if(!p)return u;p.drawImage(i,0,0);const y=p.getImageData(0,0,o,s),v=n??Ece(y),w=(r==null?void 0:r.trimMode)??"normal",C=wrt(w);for(let x=0;x<l.length-1;x++)for(let E=0;E<c.length-1;E++){const _=c[E],I=c[E+1],D=l[x],P=l[x+1],k=t.useDetectedLines||v||w==="strict"?0:2,R=_+(E>0?k:0),T=D+(x>0?k:0),M=I-_-(E>0?k:0)-(E<c.length-2?k:0),F=P-D-(x>0?k:0)-(x<l.length-2?k:0);if(M<=0||F<=0)continue;const V=p.getImageData(R,T,M,F);if(v&&jrt(V))continue;let H;v?H=zrt(V,!0):C?H=GC(V,C.borderRatio,C.maxTrimRatio):H={top:0,right:M-1,bottom:F-1,left:0};const j=R+H.left,z=T+H.top,N=H.right-H.left+1,B=H.bottom-H.top+1;if(N<=10||B<=10)continue;const O=document.createElement("canvas");O.width=N,O.height=B;const $=O.getContext("2d");if(!$)continue;$.drawImage(i,j,z,N,B,0,0,N,B);const U=v?"image/png":"image/jpeg",Y=v?void 0:.92;u.push({imageData:O.toDataURL(U,Y),index:d++,width:N,height:B,sourceX:j,sourceY:z,hasTransparency:v})}return u}function ZV(e,t,n,r=235){return e>=r&&t>=r&&n>=r}function $rt(e,t=.7,n=.15){const{width:r,height:i,data:o}=e,s=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 x=0;const E=Math.floor(u),_=r-Math.floor(u),I=_-E;if(I<=0)return!1;for(let D=E;D<_;D++){const P=(C*r+D)*4;ZV(o[P],o[P+1],o[P+2])&&x++}return x/I>t},f=C=>{let x=0;const E=Math.floor(u),_=i-Math.floor(u),I=_-E;if(I<=0)return!1;for(let D=E;D<_;D++){const P=(D*r+C)*4;ZV(o[P],o[P+1],o[P+2])&&x++}return x/I>t};let p=0;for(;p<s&&p<i-1&&d(p);)p++;let y=i-1;for(;i-1-y<a&&y>p&&d(y);)y--;let v=0;for(;v<l&&v<r-1&&f(v);)v++;let w=r-1;for(;r-1-w<c&&w>v&&f(w);)w--;return{top:p,right:w,bottom:y,left:v}}function zrt(e,t=!0){const{width:n,height:r,data:i}=e,o=t?0:50,s=f=>{for(let p=0;p<n;p++){const y=(f*n+p)*4;if(i[y+3]>o)return!1}return!0},a=f=>{for(let p=0;p<r;p++){const y=(p*n+f)*4;if(i[y+3]>o)return!1}return!0};let l=0;for(;l<r&&s(l);)l++;let c=r-1;for(;c>l&&s(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 Ace(e){const t=await jh(e),n=t.naturalWidth,r=t.naturalHeight,i=document.createElement("canvas");i.width=n,i.height=r;const o=i.getContext("2d",{willReadFrequently:!0});if(!o)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}};o.drawImage(t,0,0);const s=o.getImageData(0,0,n,r),a=$rt(s,.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,p=r-a.bottom-1,y=5;let v=0;if(u>y&&v++,d>y&&v++,f>y&&v++,p>y&&v++,!(v>=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 x=C.getContext("2d");return x?(x.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:p},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 Kp=100;async function yN(e,t=0,n=2,r){if(t>=n)return[e];if(e.width<Kp||e.height<Kp)return[e];const i=(r==null?void 0:r.skipTrim)??!1;let o=e.imageData,s=e.width,a=e.height,l=!1,c=0,u=0;if(!i){const{trimmedImageUrl:x,borderInfo:E}=await Ace(e.imageData);if(o=x,s=E.trimmed.width,a=E.trimmed.height,l=E.hasBorders,c=E.borders.left,u=E.borders.top,s<Kp||a<Kp)return l?[{...e,imageData:o,width:s,height:a,sourceX:e.sourceX+c,sourceY:e.sourceY+u}]:[e]}const d=await Ice(o,e.hasTransparency);if(d.rows<=1&&d.cols<=1)return l?[{...e,imageData:o,width:s,height:a,sourceX:e.sourceX+c,sourceY:e.sourceY+u}]:[e];const f=d.rows>1&&d.cols>1,p=await gN(o,d,e.hasTransparency,{trimMode:f?"strict":"normal"});if(p.length<=1)return l?[{...e,imageData:o,width:s,height:a}]:[e];const y=e.sourceX+c,v=e.sourceY+u,w=p.map(x=>({...x,sourceX:x.sourceX+y,sourceY:x.sourceY+v}));if(f)return w;const C=[];for(const x of w){if(x.width<Kp||x.height<Kp){C.push(x);continue}const E=await yN(x,t+1,n,r);C.push(...E)}return C}function Urt(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 o=Pn(e,[i],!1),s=o.y+o.height;s>n&&(n=s,t=i)}catch{}if(!t)return{x:100,y:100};const r=Pn(e,[t],!1);return{x:r.x,y:r.y+r.height+50}}catch{return{x:100,y:100}}}async function Pce(e,t,n){const r=nXe("图片分割"),{sourceRect:i,startPoint:o,scrollToResult:s=!0}=n||{};try{let a=[],l=!1;const{trimmedImageUrl:c,borderInfo:u}=await Ace(t),d=u.trimmed.width,f=u.trimmed.height,{detection:p,hasTransparency:y}=await _ce(c);if(p.rows>1||p.cols>1){l=p.rows>1&&p.cols>1;const P=await gN(c,p,y,{trimMode:l?"strict":"normal"});if(y)a=P;else if(l)a=P;else for(const T of P){if(a.length>=25)break;if(T.width<100||T.height<100){a.push(T);continue}const M=await yN(T,0,2,{skipTrim:!0}),F=25-a.length;a.push(...M.slice(0,F))}}else if(await Lrt(c)){const{splitPhotoWall:k}=await xn(async()=>{const{splitPhotoWall:T}=await import("./photo-wall-splitter-D2Ji--gy.js");return{splitPhotoWall:T}},[],import.meta.url);a=(await k(c)).map((T,M)=>({imageData:T.imageData,index:M,width:T.width,height:T.height,sourceX:T.sourceX??0,sourceY:T.sourceY??0}))}if(a.length===0)return{success:!1,count:0,error:"未检测到可拆分的区域,请确保图片包含分割线或灵感图格式"};a=a.map((P,k)=>({...P,index:k}));let v=1;i&&(v=Math.min(i.width/d,i.height/f));let w,C;if(o)w=o[0],C=o[1];else if(i)w=i.x,C=i.y+i.height+20;else{const P=Urt(e);w=P.x,C=P.y}const x=a.some(P=>P.sourceX>0||P.sourceY>0);if(x&&!i){let P=0,k=0;for(const M of a){const F=M.sourceX+M.width,V=M.sourceY+M.height;F>P&&(P=F),V>k&&(k=V)}P>0&&k>0&&(v=Math.min(800/P,600/k,1))}let E,_;const{unifiedCacheService:I}=await xn(async()=>{const{unifiedCacheService:P}=await Promise.resolve().then(()=>du);return{unifiedCacheService:P}},void 0,import.meta.url),D=[];if(!x&&a.length>1){const P=a.length,k=Math.ceil(Math.sqrt(P)),R=Math.ceil(P/k),T=a.reduce((N,B)=>N+B.width,0)/a.length,M=a.reduce((N,B)=>N+B.height,0)/a.length,V=Math.min(400/Math.max(T,M),1),H=T*V,j=M*V,z=20;for(let N=0;N<a.length;N++){const B=Math.floor(N/k),O=N%k,$=a[N],U=Math.min(H/$.width,j/$.height,1);D.push({x:w+O*(H+z),y:C+B*(j+z),width:$.width*U,height:$.height*U})}}for(let P=0;P<a.length;P++){const k=a[P];let R,T,M,F;if(x){const O=k.sourceX*v,$=k.sourceY*v;R=w+O,T=C+$,M=k.width*v,F=k.height*v}else if(D.length>0){const O=D[P];R=(O==null?void 0:O.x)??w,T=(O==null?void 0:O.y)??C,M=(O==null?void 0:O.width)??k.width*v,F=(O==null?void 0:O.height)??k.height*v}else R=w,T=C,M=k.width*v,F=k.height*v;E||(E=[R,T],_={width:M,height:F});const V=k.hasTransparency?"png":"jpg",j=`/__aitu_cache__/image/${`split-image-${Date.now()}-${P}`}.${V}`,N=await(await fetch(k.imageData)).blob();await I.cacheToCacheStorageOnly(j,N);const B={url:j,width:M,height:F};ii.insertImage(e,B,[R,T])}if(s&&E&&_){const P=[E[0]+_.width/2,E[1]+_.height/2];requestAnimationFrame(()=>{Ba(e,P)})}return r(),{success:!0,count:a.length}}catch(a){return r(),{success:!1,count:0,error:a.message||"拆分图片失败"}}}const Apt=Object.freeze(Object.defineProperty({__proto__:null,detectGridLines:Ice,recursiveSplitElement:yN,splitAndInsertImages:Pce,splitImageByLines:gN},Symbol.toStringTag,{value:"Module"})),Hrt={label:"自动",value:"auto",width:0,height:0,description:"由模型自动决定最佳比例"},Y2=[Hrt,{label:"1:1",value:"1:1",width:1,height:1,description:"正方形"},{label:"1:4",value:"1:4",width:1,height:4,description:"超长竖版"},{label:"4:1",value:"4:1",width:4,height:1,description:"超长横版"},{label:"1:8",value:"1:8",width:1,height:8,description:"极长竖版"},{label:"8:1",value:"8:1",width:8,height:1,description:"极长横版"},{label:"2:3",value:"2:3",width:2,height:3,description:"竖版标准"},{label:"3:2",value:"3:2",width:3,height:2,description:"横版标准"},{label:"3:4",value:"3:4",width:3,height:4,description:"竖版"},{label:"4:3",value:"4:3",width:4,height:3,description:"横版"},{label:"4:5",value:"4:5",width:4,height:5,description:"竖版社交"},{label:"5:4",value:"5:4",width:5,height:4,description:"横版"},{label:"9:16",value:"9:16",width:9,height:16,description:"竖屏全屏"},{label:"16:9",value:"16:9",width:16,height:9,description:"横屏全屏"},{label:"21:9",value:"21:9",width:21,height:9,description:"超宽屏"}],oO="auto";function Wrt(e){return!e||e==="auto"?void 0:{"1:1":"1x1","1:4":"1x4","4:1":"4x1","1:8":"1x8","8:1":"8x1","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"}[e]}function JV(e,t){if(!e.url)return null;if(!e.maskImage)return g.jsx("img",{src:e.url,alt:e.name});const n=e.width&&e.height&&e.width>0&&e.height>0?{"--mask-pair-aspect":String(e.width*2/e.height)}:void 0;return g.jsxs("div",{className:`${t}__media-pair`,style:n,children:[g.jsx("img",{src:e.url,alt:e.name}),g.jsx("div",{className:`${t}__mask-thumb`,children:g.jsx("img",{src:e.maskImage,alt:`${e.name} mask`})})]})}const QV=({items:e,language:t="zh",enableHoverPreview:n=!0,className:r,onRemove:i,removableStartIndex:o=0})=>{const[s,a]=b.useState(null),l=b.useCallback((u,d)=>{if(!n)return;const f=d.currentTarget.getBoundingClientRect(),p=f.left+f.width/2,y=f.top-10;a({type:u.type,url:u.url,maskImage:u.maskImage,width:u.width,height:u.height,text:u.text,x:p,y})},[n]),c=b.useCallback(()=>{a(null)},[]);return e.length===0?null:g.jsxs(g.Fragment,{children:[n&&s&&Wf.createPortal(g.jsxs("div",{className:`selected-content-preview__hover selected-content-preview__hover--${s.type}`,style:{left:`${s.x}px`,top:`${s.y}px`,transform:"translate(-50%, -100%)"},children:[(s.type==="image"||s.type==="graphics")&&s.url&&JV({url:s.url,maskImage:s.maskImage,width:s.width,height:s.height,name:"Preview"},"selected-content-preview"),s.type==="video"&&s.url&&g.jsx("div",{className:"selected-content-preview__hover-video",children:g.jsx("video",{src:s.url,controls:!0,autoPlay:!0,muted:!0,loop:!0,playsInline:!0})}),s.type==="text"&&s.text&&g.jsxs("div",{className:"selected-content-preview__hover-text",children:[g.jsxs("div",{className:"selected-content-preview__hover-text-header",children:[g.jsx(R8,{size:16}),g.jsx("span",{children:t==="zh"?"文字内容":"Text Content"})]}),g.jsx("div",{className:"selected-content-preview__hover-text-content",children:s.text})]})]}),document.body),g.jsx("div",{className:`selected-content-preview ${r||""}`,children:e.map((u,d)=>{const f=i&&d<o;return g.jsxs("div",{className:`selected-content-preview__item selected-content-preview__item--${u.type}`,onMouseEnter:p=>l(u,p),onMouseLeave:c,children:[u.type==="text"?g.jsxs("div",{className:"selected-content-preview__text",children:[g.jsx(R8,{size:14,className:"selected-content-preview__text-icon"}),g.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"?g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"selected-content-preview__video-placeholder",children:g.jsx(cg,{size:20})}),g.jsx("div",{className:"selected-content-preview__video-overlay",children:g.jsx(SY,{size:16,fill:"white"})})]}):JV(u,"selected-content-preview"),u.type==="image"&&u.maskImage&&g.jsx("span",{className:"selected-content-preview__label selected-content-preview__label--mask",children:"Mask"}),u.type==="graphics"&&g.jsx("span",{className:"selected-content-preview__label",children:t==="zh"?"图形":"Graphics"}),u.type==="video"&&g.jsx("span",{className:"selected-content-preview__label selected-content-preview__label--video",children:t==="zh"?"视频":"Video"}),f&&g.jsx(cn,{content:t==="zh"?"移除":"Remove",showArrow:!1,children:g.jsx("button",{className:"selected-content-preview__remove-btn",onClick:p=>{p.stopPropagation(),i(d)},onMouseDown:p=>p.preventDefault(),children:g.jsx(md,{size:12})})})]},`${u.type}-${d}`)})})]})};function ev(e){return e.tagName==="TEXTAREA"||e.tagName==="INPUT"}function Vrt(e){const t=e.selectionStart||0,n=e.selectionEnd||0;return e.value.substring(t,n)}function kce(e){const t=window.getSelection();if(!t||t.rangeCount===0)return"";const n=t.getRangeAt(0);return e.contains(n.commonAncestorContainer)?t.toString():""}function aT(e){return ev(e)?Vrt(e):kce(e)}function Grt(e,t={}){const{enableCopy:n=!0,stopPropagation:r=!0}=t,i=b.useRef(null);return b.useEffect(()=>{const o=e.current;if(!o)return;const s=v=>!v||!(v instanceof HTMLElement)?!1:!!(["BUTTON","A","INPUT","SELECT","TEXTAREA","LABEL"].includes(v.tagName)||v.onclick||v.getAttribute("role")==="button"||v.closest('button, a, [role="button"], [onclick]')),a=()=>{const v=window.getSelection();return v!==null&&v.toString().length>0},l=v=>{r&&(s(v.target)||a()&&v.stopPropagation())},c=v=>{r&&(s(v.target)||v.stopPropagation())},u=v=>{const w=(v.ctrlKey||v.metaKey)&&v.key==="c",C=(v.ctrlKey||v.metaKey)&&v.key==="x";if(n&&(w||C)){const x=aT(o);x&&aE(x).then(()=>{}).catch(E=>{console.error("Failed to copy text:",E)}),r&&v.stopPropagation()}},d=v=>{if(n){const w=aT(o);w&&v.clipboardData&&(v.clipboardData.setData("text/plain",w),v.preventDefault())}r&&v.stopPropagation()},f=v=>{if(n){const w=aT(o);w&&v.clipboardData&&v.clipboardData.setData("text/plain",w)}r&&v.stopPropagation()},p=()=>{if(ev(o)){const v=o.selectionStart||0,w=o.selectionEnd||0;v!==w&&(i.current={text:o.value.substring(v,w),start:v,end:w})}else{const v=kce(o);v&&(i.current={text:v})}},y=()=>{ev(o)||p()};return o.addEventListener("pointerdown",c),o.addEventListener("mousedown",c),o.addEventListener("pointerup",l),o.addEventListener("pointermove",l),o.addEventListener("mouseup",l),o.addEventListener("click",l),o.addEventListener("keydown",u),o.addEventListener("copy",d),o.addEventListener("cut",f),ev(o)?o.addEventListener("select",p):document.addEventListener("selectionchange",y),()=>{o.removeEventListener("pointerdown",c),o.removeEventListener("mousedown",c),o.removeEventListener("pointerup",l),o.removeEventListener("pointermove",l),o.removeEventListener("mouseup",l),o.removeEventListener("click",l),o.removeEventListener("keydown",u),o.removeEventListener("copy",d),o.removeEventListener("cut",f),ev(o)?o.removeEventListener("select",p):document.removeEventListener("selectionchange",y)}},[e,n,r]),{lastSelection:i.current}}function Krt(e,t,n){return e==="size"?n.split("(")[0].trim():e==="duration"?`${t}s`:e==="klingAction2"?t==="image2video"?"图生":"文生":e==="mode"?t:n}function eG(e){return e.valueType==="number"&&e.id.toLowerCase().includes("seed")}function qrt(e){const t=Number.isFinite(e.min)?e.min:0,n=Number.isFinite(e.max)?e.max:2147483647,r=Math.min(t,n),i=Math.max(t,n);if(e.integer!==!1)return String(Math.floor(Math.random()*(i-r+1))+r);const o=Number.isFinite(e.step)&&e.step?e.step:1,s=Math.floor((i-r)/o);return String(r+Math.floor(Math.random()*(s+1))*o)}const Yrt=({selectedParams:e,onParamChange:t,compatibleParams:n,modelId:r,language:i="zh",disabled:o=!1,isOpen:s,onOpenChange:a,excludeParamIds:l,placement:c="auto"})=>{const{value:u,setValue:d}=F3({controlledValue:s,defaultValue:!1,onChange:a}),[f,p]=b.useState(0),[y,v]=b.useState(0),w=b.useMemo(()=>{const P=n??Kg(r);return l&&l.length>0?P.filter(k=>!l.includes(k.id)):P},[n,r,l]);b.useEffect(()=>{var P;if(u&&w.length>0){p(0);const k=w[0],R=e[k.id],T=((P=k.options)==null?void 0:P.findIndex(M=>M.value===R))??0;v(T>=0?T:0)}},[u,w,e]);const C=b.useMemo(()=>{if(w.length===0)return i==="zh"?"参数":"Params";const P=[];return w.forEach(k=>{var T;const R=e[k.id];if(R)if(k.valueType==="enum"){const M=(T=k.options)==null?void 0:T.find(F=>F.value===R);M&&P.push(Krt(k.id,R,M.label))}else{const M=R.length>10?`${R.slice(0,10)}…`:R;P.push(`${k.shortLabel||k.label}:${M}`)}}),P.length===0?i==="zh"?"配置参数":"Settings":P.join(", ")},[w,e,i]),x=b.useCallback(P=>{P.preventDefault(),!o&&d(!u)},[o,u,d]),E=b.useCallback(P=>{var T,M;if(P==="Escape")return d(!1),!0;const k=w[f],R=((T=k==null?void 0:k.options)==null?void 0:T.length)??0;if(P==="ArrowDown")return p(F=>{var N;const V=F<w.length-1?F+1:0,H=w[V],j=e[H.id],z=((N=H.options)==null?void 0:N.findIndex(B=>B.value===j))??0;return v(z>=0?z:0),V}),!0;if(P==="ArrowUp")return p(F=>{var N;const V=F>0?F-1:w.length-1,H=w[V],j=e[H.id],z=((N=H.options)==null?void 0:N.findIndex(B=>B.value===j))??0;return v(z>=0?z:0),V}),!0;if(P==="ArrowRight")return v(F=>F<R-1?F+1:0),!0;if(P==="ArrowLeft")return v(F=>F>0?F-1:R-1),!0;if(P==="Enter"||P===" "||P==="Tab"){const F=(M=k==null?void 0:k.options)==null?void 0:M[y];return F&&t(k.id,F.value),!0}return!1},[w,f,y,e,t]),_=b.useCallback((P,k)=>{t(P,k)},[t]),I=b.useCallback((P,k)=>{t(P,k,{keepOpen:!0})},[t]),D=b.useCallback(P=>{t(P.id,qrt(P),{keepOpen:!0})},[t]);return w.length===0?null:g.jsx(h_,{isOpen:u,setIsOpen:d,disabled:o,openKeys:["Enter"," ","ArrowDown","ArrowUp"],onOpenKey:E,placement:c,minMenuHeight:240,maxMenuHeight:420,children:({containerRef:P,menuRef:k,menuStyle:R,handleTriggerKeyDown:T})=>g.jsxs("div",{className:"parameters-dropdown",ref:P,children:[g.jsx(cn,{content:`${C} (↑↓ Tab)`,showArrow:!1,children:g.jsxs("button",{className:`parameters-dropdown__trigger ${u?"parameters-dropdown__trigger--open":""}`,onMouseDown:x,onKeyDown:T,type:"button",disabled:o,children:[g.jsx("span",{className:"parameters-dropdown__label",children:C}),g.jsx(lg,{size:14,className:`parameters-dropdown__icon ${u?"parameters-dropdown__icon--open":""}`})]})}),u&&Ui.createPortal(g.jsxs("div",{ref:k,className:`parameters-dropdown__menu parameters-dropdown__menu--flat ${Vh}`,style:{...R,zIndex:Eu.DROPDOWN_PORTAL},onMouseDown:M=>M.stopPropagation(),onClick:M=>M.stopPropagation(),children:[g.jsxs("div",{className:"parameters-dropdown__header",children:[g.jsx(SCe,{size:14}),g.jsx("span",{children:i==="zh"?"设置生成参数 (↑↓←→ Tab)":"Parameters (↑↓←→ Tab)"})]}),g.jsx("div",{className:"parameters-dropdown__sections",children:w.map((M,F)=>{var j;const V=e[M.id],H=F===f;return g.jsxs("div",{className:`parameters-dropdown__section ${H?"parameters-dropdown__section--highlighted":""}`,children:[g.jsx("div",{className:"parameters-dropdown__section-title",children:M.label}),M.valueType==="enum"?g.jsx("div",{className:"parameters-dropdown__options",children:(j=M.options)==null?void 0:j.map((z,N)=>{const B=V===z.value,O=H&&N===y;return g.jsxs("button",{type:"button",className:`parameters-dropdown__option ${B?"parameters-dropdown__option--selected":""} ${O?"parameters-dropdown__option--highlighted":""}`,onClick:()=>_(M.id,z.value),onMouseEnter:()=>{p(F),v(N)},children:[g.jsx("span",{className:"parameters-dropdown__option-label",children:z.label.split("(")[0].trim()}),B&&g.jsx(Nd,{size:12,className:"parameters-dropdown__option-check"})]},z.value)})}):g.jsxs("div",{className:`parameters-dropdown__field ${eG(M)?"parameters-dropdown__field--with-action":""}`,children:[g.jsx("input",{type:M.valueType==="number"?"number":"text",className:"parameters-dropdown__field-input",value:V||"",placeholder:M.description||M.label,min:M.valueType==="number"?M.min:void 0,max:M.valueType==="number"?M.max:void 0,step:M.valueType==="number"?M.step:void 0,onChange:z=>I(M.id,z.target.value),onMouseDown:z=>z.stopPropagation(),onKeyDown:z=>z.stopPropagation()}),eG(M)&&g.jsx(cn,{content:i==="zh"?"随机生成种子":"Randomize seed",showArrow:!1,children:g.jsx("button",{type:"button",className:"parameters-dropdown__field-action",onClick:()=>D(M),onMouseDown:z=>z.stopPropagation(),children:g.jsx(B2e,{size:14})})})]})]},M.id)})})]}),document.body)]})})};function vN(){const e=ci.get();return(e==null?void 0:e.videoModelName)||uu()}function Xrt(){const e=new Set;return Object.values(fu).forEach(t=>{t.durationOptions.forEach(n=>e.add(n.value))}),Array.from(e).sort((t,n)=>parseInt(t)-parseInt(n))}function Zrt(){const e=new Set;return Object.values(fu).forEach(t=>{t.sizeOptions.forEach(n=>e.add(n.value))}),Array.from(e)}async function Jrt(e){const{prompt:t,model:n="veo3",modelRef:r,seconds:i="8",size:o="1280x720",referenceImages:s,params:a}=e,l=Ay(t);if(l)return l;try{const c=n,u=Sd("video",c,r||null);if(!u||u.kind!=="video")return{success:!1,error:`未找到可用的视频适配器: ${c}`,type:"error"};const d=i?Number(i):void 0,f=await u.generateVideo(Rd("video",r||c),{prompt:t,size:o,model:c,modelRef:r||null,duration:Number.isFinite(d)?d:void 0,referenceImages:s,params:a}),p=f.url;return p?{success:!0,data:{url:p,format:f.format||"mp4",prompt:t,model:n,seconds:i,size:o},type:"video"}:{success:!1,error:"API 未返回有效的视频 URL",type:"error"}}catch(c){return console.error("[VideoGenerationTool] Generation failed:",c),S5(c,"视频生成失败")}}function Qrt(e){const t=e.model||"veo3",n=fu[t]||fu.veo3,r=C5(e.referenceImages);return{taskType:Qt.VIDEO,resultType:"video",getDefaultModel:vN,logPrefix:"VideoGenerationTool",buildTaskPayload:()=>({prompt:e.prompt,size:e.size||"16x9",duration:parseInt(e.seconds||n.defaultDuration,10),model:t,modelRef:e.modelRef||null,uploadedImages:r&&r.length>0?r:void 0,referenceImages:e.referenceImages&&e.referenceImages.length>0?e.referenceImages:void 0,params:e.params,promptMeta:e.promptMeta,knowledgeContextRefs:e.knowledgeContextRefs}),buildResultData:()=>({size:e.size||"16x9",duration:parseInt(e.seconds||n.defaultDuration,10)})}}const wN={name:"generate_video",description:`生成视频工具。根据用户的文字描述生成视频。
|
|
2619
|
+
`)}`}const crt=e=>{const t=e.trim(),n=t.match(/^```[\w-]*\n?([\s\S]*?)\n?```$/);return n?n[1].trim():t},pN=30,urt=60;function zC(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(xr.PROMPT_OPTIMIZE_REQUIREMENTS_HISTORY),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(n=>n&&typeof n.id=="string"&&typeof n.content=="string"&&typeof n.timestamp=="number"&&n.content.trim().length>0).sort((n,r)=>r.timestamp-n.timestamp).slice(0,pN):[]}catch{return[]}}function drt(e){if(!(typeof window>"u"))try{window.localStorage.setItem(xr.PROMPT_OPTIMIZE_REQUIREMENTS_HISTORY,JSON.stringify(e.slice(0,pN)))}catch{}}function frt(e){const t=e.trim();if(!t)return zC();const n=[{id:`requirements-${Date.now()}`,content:t,timestamp:Date.now()},...zC().filter(r=>r.content!==t)].slice(0,pN);return drt(n),n}const hrt=e=>{const{open:t,onOpenChange:n,originalPrompt:r,language:i,type:o,onApply:s,historyType:a,allowStructuredMode:l=!1,defaultMode:c}=e,u=e.scenarioId,d=b.useId(),f=b.useId(),p=b.useId(),y=b.useId(),v=b.useMemo(()=>vce(u,o),[u,o]),w=o||v.type,C=a||v.historyType,x=c??v.defaultMode,[E,_]=b.useState(""),[I,D]=b.useState(r),[P,k]=b.useState(""),[R,T]=b.useState(x),[M,F]=b.useState(!1),[V,H]=b.useState(null),[j,z]=b.useState([]),N=b.useRef(null),B=b.useRef(!1),O=b.useRef(null),{isMobile:$,viewportWidth:U,viewportHeight:Y}=ule(),{history:K,addHistory:Z,refreshHistory:oe}=mce({deduplicateWithPresets:!1,modelTypeFilter:C}),J=Dm("text"),ae=b.useCallback(()=>{var At;const He=so("text"),we=qn(He.profileId,He.modelId),ue=He.modelId||((At=J[0])==null?void 0:At.id)||"",_e=we||(ue?qn(null,ue):null),xe=f7e(xr.PROMPT_OPTIMIZE_TEXT_MODEL,ue,_e),Fe=$C(J,xe.modelId,xe.modelRef)||KM("text",xe.modelId,xe.modelRef),lt=(Fe==null?void 0:Fe.id)||xe.modelId||ue,Ht=GV(Fe)||xe.modelRef||_e||(lt?qn(null,lt):null);return{modelId:lt,modelRef:Ht}},[J]),[Q,se]=b.useState(()=>ae().modelId),[ie,ce]=b.useState(()=>ae().modelRef),ge=b.useMemo(()=>{if($C(J,Q,ie)||!Q)return J;const we=KM("text",Q,ie);return we?[we,...J]:J},[Q,ie,J]),Se=b.useCallback(()=>{const He=ae();se(He.modelId),ce(He.modelRef)},[ae]),Ae=b.useCallback(()=>{var He;(He=N.current)==null||He.abort(),N.current=null,B.current=!1,F(!1),_(""),k(""),T(x),n(!1)},[x,n]),Le=b.useCallback(async()=>{var _e;const He=I.trim();if(!He){tn.warning(i==="zh"?"请先填写当前提示词":"Please enter the current prompt first");return}if(B.current||M)return;B.current=!0,Z(He,!1,C||w),E.trim()&&z(frt(E));const we=new AbortController,ue=Date.now();(_e=N.current)==null||_e.abort(),N.current=we,F(!0),Kt.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,status:"start",model:Q||void 0,prompt:He,requirements:E});try{const xe=crt((await tR.getFallbackExecutor().generateText({prompt:await lrt({scenarioId:u,originalPrompt:He,optimizationRequirements:E,language:i,type:w,mode:R}),model:Q||void 0,modelRef:ie},{signal:we.signal})).content);if(!xe)throw new Error("Empty optimized prompt");k(xe),Kt.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,status:"success",model:Q||void 0,prompt:He,requirements:E,durationMs:Date.now()-ue,metadata:{result_length_bucket:xe.length<=200?"1-200":xe.length<=500?"201-500":xe.length<=1e3?"501-1000":"1000+"}}),tn.success(i==="zh"?R==="structured"?"结构化提示词已生成,可继续优化或回填":"提示词优化完成,可继续优化或回填":R==="structured"?"Structured prompt generated. You can refine again or apply it.":"Prompt optimized. You can refine again or apply it."),_("")}catch(xe){if(we.signal.aborted){Kt.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,status:"cancelled",model:Q||void 0,prompt:He,requirements:E,durationMs:Date.now()-ue});return}console.error("[PromptOptimizeDialog] Failed to optimize prompt:",xe),Kt.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,status:"failed",model:Q||void 0,prompt:He,requirements:E,durationMs:Date.now()-ue,metadata:{error:xe instanceof Error?xe.name||"Error":typeof xe}}),tn.error(i==="zh"?R==="structured"?"结构化提示词生成失败,请稍后重试":"提示词优化失败,请稍后重试":R==="structured"?"Failed to generate structured prompt, please try again later":"Failed to optimize prompt, please try again later")}finally{N.current===we&&(N.current=null),B.current=!1,F(!1)}},[I,i,R,Q,ie,E,Z,C,w,M,u]),it=b.useCallback(()=>{const He=P.trim();He&&(Kt.trackPromptAction({action:"use_draft_as_current",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,prompt:He}),D(He),_(""))},[C,w,R,P]),Te=b.useCallback(()=>{const He=(P||I).trim();if(!He){tn.warning(i==="zh"?"没有可回填的提示词":"There is no prompt to apply");return}Kt.trackPromptAction({action:"apply",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,prompt:He}),s(He),Ae()},[I,C,w,Ae,i,R,s,P]);b.useEffect(()=>{t&&(Se(),D(r),k(""),_(""),z(zC()),H(null),T(x))},[x,t,r,Se]),b.useEffect(()=>()=>{var He;(He=N.current)==null||He.abort(),N.current=null,B.current=!1},[]),b.useEffect(()=>{if(!V)return;const He=we=>{var _e;const ue=we.target;ue instanceof Node&&((_e=O.current)!=null&&_e.contains(ue))||ue instanceof Element&&ue.closest(".prompt-optimize-dialog__history-btn")||H(null)};return document.addEventListener("mousedown",He,!0),()=>{document.removeEventListener("mousedown",He,!0)}},[V]);const Re=i==="zh"?R==="structured"?"例如:突出时间轴结构、把区域与数量拆开、保留标题与图例、输出 JSON 不要解释...":"例如:更电影感、补充镜头语言、减少冗余、强调主体与光线...":R==="structured"?"For example: emphasize timeline structure, split regions and counts, preserve titles and legends, output JSON only...":"For example: make it more cinematic, add camera language, reduce redundancy, emphasize subject and lighting...",ht=I.trim().length>0,Ze=(P.length>0?P:I).trim().length>0,Ge=P.length>0,pt=b.useMemo(()=>K.slice(0,urt).map(He=>({id:He.id,content:He.content,pinned:He.pinned,modelType:He.modelType})),[K]),at=b.useMemo(()=>j.map(He=>({id:He.id,content:He.content})),[j]),ct=b.useMemo(()=>`prompt-optimize-dialog-${d.replace(/[^a-zA-Z0-9_-]/g,"")}`,[d]),nt=i==="zh"?R==="structured"?"结构化提示词":"提示词优化":R==="structured"?"Structured Prompt":"Prompt Optimization",It=b.useMemo(()=>{const He=$?16:48,we=Math.max(280,U-He),ue=Math.max(320,Y-He),_e=Ge?1120:680,xe=Ge?760:680,Fe=Math.max(280,Math.min(_e,we)),lt=Math.max(320,Math.min(xe,ue));return{width:Fe,height:lt,minWidth:Math.min(Ge?640:320,Fe),minHeight:Math.min(420,lt)}},[Ge,$,Y,U]),Lt=b.useCallback(He=>{He==="current"?oe():z(zC()),Kt.trackPromptAction({action:"toggle_history",surface:"prompt_optimize_dialog",promptType:He==="current"?C||w:void 0,mode:R,metadata:{panel:He}}),H(we=>we===He?null:He)},[C,w,R,oe]),dt=b.useCallback(He=>{D(He.content),H(null)},[]),wt=b.useCallback(He=>{_(He.content),H(null)},[]),mt=b.useCallback(He=>{Kt.trackPromptAction({action:"mode_select",surface:"prompt_optimize_dialog",promptType:C||w,mode:He}),T(He)},[C,w]),Bt=(He,we,ue)=>V!==He?null:g.jsx("div",{ref:O,className:"prompt-optimize-dialog__history-panel",children:we.length>0?g.jsx(Ynt,{title:i==="zh"?"历史":"History",items:we,onSelect:ue,language:i,analyticsSurface:`prompt_optimize_${He}_history`,analyticsPromptType:He==="current"?C||w:void 0,showCount:!0}):g.jsx("div",{className:"prompt-optimize-dialog__history-empty",children:i==="zh"?"暂无历史":"No history yet"})});return t?g.jsx(dce,{id:ct,visible:t,title:nt,icon:g.jsx(Hv,{size:16}),onClose:Ae,width:It.width,height:It.height,minWidth:It.minWidth,minHeight:It.minHeight,x:"center",y:"center",maximizable:!$,minimizable:!1,resizable:!$,movable:!$,modal:!1,background:"#ffffff",className:`winbox-ai-generation winbox-prompt-optimize ${Ge?"winbox-prompt-optimize--split":""}`,children:g.jsxs("div",{className:`prompt-optimize-dialog ${Ge?"prompt-optimize-dialog--split":""}`,children:[g.jsxs("div",{className:`prompt-optimize-dialog__body ${Ge?"prompt-optimize-dialog__body--split":""}`,children:[g.jsxs("div",{className:"prompt-optimize-dialog__form-pane",children:[g.jsxs("div",{className:"prompt-optimize-dialog__section prompt-optimize-dialog__section--current",children:[g.jsxs("div",{className:"prompt-optimize-dialog__label-row",children:[g.jsx("label",{className:"prompt-optimize-dialog__label",htmlFor:f,children:i==="zh"?"当前提示词":"Current Prompt"}),g.jsx("button",{type:"button",className:"prompt-optimize-dialog__history-btn",onClick:()=>Lt("current"),"aria-label":i==="zh"?"当前提示词历史":"Current prompt history",children:g.jsx(RT,{size:16})}),Bt("current",pt,dt)]}),g.jsx("textarea",{id:f,className:"prompt-optimize-dialog__textarea prompt-optimize-dialog__textarea--current",value:I,onChange:He=>D(He.target.value),placeholder:i==="zh"?"输入或编辑要优化的提示词...":"Enter or edit the prompt to optimize...",rows:5,disabled:M})]}),g.jsxs("div",{className:"prompt-optimize-dialog__section prompt-optimize-dialog__section--requirements",children:[g.jsxs("div",{className:"prompt-optimize-dialog__label-row",children:[g.jsx("label",{className:"prompt-optimize-dialog__label",htmlFor:p,children:i==="zh"?"补充要求":"Additional Requirements"}),g.jsx("button",{type:"button",className:"prompt-optimize-dialog__history-btn",onClick:()=>Lt("requirements"),"aria-label":i==="zh"?"补充要求历史":"Additional requirements history",children:g.jsx(RT,{size:16})}),Bt("requirements",at,wt)]}),g.jsx("textarea",{id:p,className:"prompt-optimize-dialog__textarea",value:E,onChange:He=>_(He.target.value),placeholder:Re,rows:4,disabled:M})]})]}),Ge&&g.jsx("div",{className:"prompt-optimize-dialog__result-pane",children:g.jsxs("div",{className:"prompt-optimize-dialog__section prompt-optimize-dialog__section--result",children:[g.jsx("div",{className:"prompt-optimize-dialog__result-header",children:g.jsx("label",{className:"prompt-optimize-dialog__label",htmlFor:y,children:i==="zh"?"优化结果草稿":"Optimized Draft"})}),g.jsx("textarea",{id:y,className:"prompt-optimize-dialog__textarea prompt-optimize-dialog__textarea--draft",value:P,onChange:He=>k(He.target.value),rows:6,disabled:M})]})})]}),g.jsxs("div",{className:`prompt-optimize-dialog__footer ${Ge?"prompt-optimize-dialog__footer--split":""}`,children:[g.jsxs("div",{className:"prompt-optimize-dialog__footer-actions prompt-optimize-dialog__footer-actions--form",children:[g.jsxs("div",{className:"prompt-optimize-dialog__footer-controls",children:[l&&g.jsxs("div",{className:"prompt-optimize-dialog__mode-switch","aria-label":i==="zh"?"输出模式":"Output Mode",children:[g.jsxs("button",{type:"button",className:`prompt-optimize-dialog__mode-btn ${R==="polish"?"prompt-optimize-dialog__mode-btn--active":""}`,onClick:()=>mt("polish"),disabled:M,children:[g.jsx(Hv,{size:14}),g.jsx("span",{children:i==="zh"?"普通润色":"Polish"})]}),g.jsx("button",{type:"button",className:`prompt-optimize-dialog__mode-btn ${R==="structured"?"prompt-optimize-dialog__mode-btn--active":""}`,onClick:()=>mt("structured"),disabled:M,children:g.jsx("span",{children:i==="zh"?"结构化 JSON":"Structured JSON"})})]}),g.jsx("div",{className:"prompt-optimize-dialog__model",children:g.jsx(X3,{selectedModel:Q,selectedSelectionKey:hN(Q,ie),onSelect:(He,we)=>{const ue=we||null;Kt.trackPromptAction({action:"model_select",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,model:He}),se(He),ce(ue),yU(xr.PROMPT_OPTIMIZE_TEXT_MODEL,He,ue)},onSelectModel:He=>{const we=GV(He);Kt.trackPromptAction({action:"model_select",surface:"prompt_optimize_dialog",promptType:C||w,mode:R,model:He.id}),se(He.id),ce(we),yU(xr.PROMPT_OPTIMIZE_TEXT_MODEL,He.id,we)},language:i,models:ge,placement:"up",header:i==="zh"?"选择文本模型 (↑↓ Tab)":"Select text model (↑↓ Tab)",disabled:M})})]}),g.jsxs("div",{className:"prompt-optimize-dialog__footer-buttons",children:[g.jsx("button",{type:"button",className:"prompt-optimize-dialog__footer-btn prompt-optimize-dialog__footer-btn--primary",onClick:()=>void Le(),disabled:M||!ht,children:i==="zh"?M?R==="structured"?"生成中...":"优化中...":R==="structured"?"生成结构化提示词":"开始优化":M?R==="structured"?"Generating...":"Optimizing...":R==="structured"?"Generate Structured Prompt":"Optimize"}),g.jsx("button",{type:"button",className:"prompt-optimize-dialog__footer-btn prompt-optimize-dialog__footer-btn--apply",onClick:Te,disabled:M||!Ze,children:i==="zh"?"回填":"Apply"})]})]}),Ge&&g.jsx("div",{className:"prompt-optimize-dialog__footer-actions prompt-optimize-dialog__footer-actions--result",children:g.jsx("button",{type:"button",className:"prompt-optimize-dialog__footer-btn prompt-optimize-dialog__footer-btn--secondary",onClick:it,disabled:M,children:i==="zh"?"用结果继续优化":"Use Draft to Refine"})})]})]})}):null},Ept=({disabled:e=!1,className:t,iconSize:n=16,tooltipPlacement:r="right",tooltipContent:i,language:o,onApply:s,onMouseDown:a,onOpenChange:l,...c})=>{const[u,d]=b.useState(!1),f=b.useCallback(v=>{d(v),l==null||l(v)},[l]),p=b.useCallback(v=>{s(v)},[s]),y=o==="zh"?"提示词优化":"Prompt optimization";return g.jsxs(g.Fragment,{children:[g.jsx(cn,{content:i??y,placement:r,disabled:e,children:g.jsx("button",{type:"button",className:t||"prompt-optimize-button",disabled:e,onMouseDown:a,onClick:()=>f(!0),"aria-label":y,children:g.jsx(Hv,{size:n})})}),g.jsx(hrt,{...c,language:o,open:u,onOpenChange:f,onApply:p})]})};function KV(e){return e.toLowerCase().replace(/\s+/g,"").trim()}function prt(e,t,n){const r=KV(n);if(!r)return e;const i=new Map(t.map(o=>[o.id,o.name]));return e.filter(o=>{var a,l,c,u;return KV([o.title,(a=o.metadata)==null?void 0:a.description,(l=o.metadata)==null?void 0:l.domain,(c=o.metadata)==null?void 0:c.sourceUrl,i.get(o.directoryId),...((u=o.metadata)==null?void 0:u.tags)||[]].filter(Boolean).join(" ")).includes(r)})}function mrt(e,t,n){return!t.includes(e)&&t.length>=n}function grt(e,t="zh"){const n=e.map(o=>o.title||"未命名笔记"),r=n.join("、"),i=e.length>0;return{triggerLabel:i?t==="zh"?`知识库上下文,已选 ${e.length} 篇笔记`:`Knowledge context, ${e.length} notes selected`:t==="zh"?"选择知识库笔记":"Select knowledge notes",selectedTitleText:r,hoverTitle:t==="zh"?"已选知识库笔记":"Selected notes",noteTitles:n,shouldShowChips:!1,canClear:i,clearLabel:t==="zh"?"清除":"Clear",clearAriaLabel:t==="zh"?"清除已选知识库笔记":"Clear selected knowledge notes",addNoteLabel:t==="zh"?"添加笔记":"Add note",addNoteAriaLabel:t==="zh"?"打开知识库新建笔记":"Open knowledge base to add note",badgeText:i?String(e.length):void 0}}function yrt(e){if(!e)return"";try{return new Date(e).toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})}catch{return""}}const _pt=({value:e,onChange:t,disabled:n=!1,label:r,language:i="zh",maxNotes:o=qte,className:s="",variant:a="default",placement:l="down"})=>{const[c,u]=b.useState(!1),[d,f]=b.useState(!1),[p,y]=b.useState([]),[v,w]=b.useState([]),[C,x]=b.useState(""),E=b.useRef(null),_=b.useRef(null),[I,D]=b.useState({}),P=b.useMemo(()=>_h(e,o),[o,e]),k=b.useMemo(()=>new Set(P.map(K=>K.noteId)),[P]),R=b.useMemo(()=>new Map(v.map(K=>[K.id,K.name])),[v]),T=b.useCallback(async()=>{f(!0);try{await vv.initialize();const[K,Z]=await Promise.all([vv.getAllNoteMetas(),vv.getAllDirectories()]);y([...K].sort((oe,J)=>J.updatedAt-oe.updatedAt)),w(Z)}finally{f(!1)}},[]);b.useEffect(()=>{c&&T()},[T,c]),b.useEffect(()=>{if(!c)return;const K=Z=>{var J,ae;const oe=Z.target;!((J=E.current)!=null&&J.contains(oe))&&!((ae=_.current)!=null&&ae.contains(oe))&&u(!1)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[c]),b.useEffect(()=>{if(!c||a!=="compact"||!E.current)return;const K=()=>{var ae;const Z=(ae=E.current)==null?void 0:ae.getBoundingClientRect();if(!Z)return;const oe=Math.min(360,Math.max(240,window.innerWidth-32)),J=Math.min(Math.max(16,Z.left),window.innerWidth-oe-16);D({position:"fixed",top:"auto",bottom:window.innerHeight-Z.top+8,left:J,width:oe,zIndex:Eu.DROPDOWN_PORTAL})};return K(),window.addEventListener("resize",K),window.addEventListener("scroll",K,!0),()=>{window.removeEventListener("resize",K),window.removeEventListener("scroll",K,!0)}},[c,a]);const M=b.useMemo(()=>prt(p,v,C),[v,p,C]),F=b.useCallback(K=>{const oe=k.has(K.id)?P.filter(J=>J.noteId!==K.id):[...P,OFe(K)];t(_h(oe,o))},[o,t,k,P]),V=b.useCallback(K=>{t(P.filter(Z=>Z.noteId!==K))},[t,P]),H=b.useCallback(K=>{K==null||K.stopPropagation(),t([])},[t]),j=b.useCallback(K=>{if(K==null||K.stopPropagation(),n||typeof window>"u")return;const Z={directoryName:"笔记",autoCreateNote:!0};window.__kbPendingNavigation=Z,window.dispatchEvent(new CustomEvent("kb:open",{detail:{}})),window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("kb:navigate",{detail:Z}))},300),u(!1)},[n]),z=r||(i==="zh"?"知识库上下文":"Knowledge Context"),N=i==="zh"?"搜索知识库笔记...":"Search notes...",B=i==="zh"?"暂无可选笔记":"No notes available",O=i==="zh"?"无匹配笔记":"No matching notes",$=a==="compact",U=grt(P,i),Y=c?g.jsxs("div",{ref:_,className:"knowledge-note-context-selector__dropdown",style:$?I:void 0,onMouseDown:K=>K.stopPropagation(),children:[g.jsxs("div",{className:"knowledge-note-context-selector__search",children:[g.jsx(sR,{size:14}),g.jsx("input",{value:C,onChange:K=>x(K.target.value),placeholder:N,autoFocus:!0})]}),g.jsx("div",{className:"knowledge-note-context-selector__list",children:d?g.jsx("div",{className:"knowledge-note-context-selector__empty",children:i==="zh"?"加载中...":"Loading..."}):M.length>0?M.map(K=>{const Z=k.has(K.id),oe=mrt(K.id,P.map(ae=>ae.noteId),o),J=R.get(K.directoryId);return g.jsxs("button",{type:"button",className:`knowledge-note-context-selector__item ${Z?"knowledge-note-context-selector__item--selected":""}`,onClick:()=>!oe&&F(K),disabled:oe,children:[g.jsxs("span",{className:"knowledge-note-context-selector__item-main",children:[g.jsx("span",{className:"knowledge-note-context-selector__item-title",children:K.title||"未命名笔记"}),g.jsx("span",{className:"knowledge-note-context-selector__item-meta",children:[J,yrt(K.updatedAt)].filter(Boolean).join(" · ")})]}),Z?g.jsx(Nd,{size:15}):null]},K.id)}):g.jsx("div",{className:"knowledge-note-context-selector__empty",children:p.length===0?B:O})}),g.jsxs("div",{className:"knowledge-note-context-selector__footer",children:[g.jsx("span",{className:"knowledge-note-context-selector__footer-text",children:i==="zh"?`最多选择 ${o} 篇,提交时按需读取正文`:`Up to ${o}; content is read on submit`}),g.jsxs("span",{className:"knowledge-note-context-selector__footer-actions",children:[g.jsxs("button",{type:"button",className:"knowledge-note-context-selector__footer-add",onClick:j,disabled:n,"aria-label":U.addNoteAriaLabel,children:[g.jsx(ic,{size:12}),U.addNoteLabel]}),U.canClear?g.jsx("button",{type:"button",className:"knowledge-note-context-selector__footer-clear",onClick:H,disabled:n,"aria-label":U.clearAriaLabel,children:U.clearLabel}):null]})]})]}):null;return g.jsxs("div",{className:Je("knowledge-note-context-selector",{"knowledge-note-context-selector--compact":$,"knowledge-note-context-selector--selected":P.length>0,"knowledge-note-context-selector--open":c,"knowledge-note-context-selector--placement-up":l==="up"},s),ref:E,children:[$?null:g.jsxs("div",{className:"knowledge-note-context-selector__header",children:[g.jsx("span",{className:"knowledge-note-context-selector__label",children:z}),P.length>0?g.jsx("button",{type:"button",className:"knowledge-note-context-selector__clear",onClick:H,disabled:n,children:i==="zh"?"清空":"Clear"}):null]}),g.jsxs("button",{type:"button",className:"knowledge-note-context-selector__trigger",onClick:()=>!n&&u(K=>!K),disabled:n,"aria-expanded":c,"aria-label":U.triggerLabel,title:$?U.selectedTitleText||U.triggerLabel:void 0,children:[g.jsx(yS,{size:$?18:15}),$?U.badgeText?g.jsx("span",{className:"knowledge-note-context-selector__badge",children:U.badgeText}):null:g.jsxs(g.Fragment,{children:[g.jsx("span",{children:P.length>0?i==="zh"?`已选 ${P.length} 篇笔记`:`${P.length} notes selected`:i==="zh"?"选择知识库笔记":"Select notes"}),g.jsx(lg,{size:15})]})]}),$&&P.length>0?g.jsxs("div",{className:"knowledge-note-context-selector__hover-summary","aria-label":i==="zh"?`已选知识库笔记:${U.selectedTitleText}`:`Selected knowledge notes: ${U.selectedTitleText}`,children:[g.jsx("div",{className:"knowledge-note-context-selector__hover-title",children:U.hoverTitle}),g.jsx("div",{className:"knowledge-note-context-selector__hover-list",children:P.map((K,Z)=>g.jsx("div",{className:"knowledge-note-context-selector__hover-item",children:U.noteTitles[Z]},K.noteId))})]}):null,!$&&P.length>0?g.jsx("div",{className:"knowledge-note-context-selector__chips",children:P.map(K=>g.jsxs("span",{className:"knowledge-note-context-selector__chip",children:[g.jsx("span",{children:K.title}),g.jsx("button",{type:"button",onClick:()=>V(K.noteId),disabled:n,"aria-label":i==="zh"?"移除笔记":"Remove note",children:g.jsx(md,{size:12})})]},K.noteId))}):null,$&&Y?Ui.createPortal(Y,document.body):Y]})},vrt=({visible:e,items:t,initialIndex:n=0,onClose:r,onIndexChange:i,showToolbar:o=!0,className:s="",showTitle:a=!0,videoAutoPlay:l=!0,videoLoop:c=!0})=>{const u=t.map((d,f)=>({id:`media-${f}`,url:d.url,type:d.type,title:d.title,alt:d.alt,posterUrl:d.posterUrl,duration:d.duration,prompt:d.prompt,tags:d.tags,artist:d.artist,album:d.album}));return g.jsx(Hg,{visible:e,items:u,initialMode:"single",initialIndex:n,onClose:r,showThumbnails:t.length>1,className:s,showTitle:a,videoAutoPlay:l,videoLoop:c})};function wrt(e){switch(e){case"strict":return{borderRatio:1,maxTrimRatio:.05};case"normal":return{borderRatio:.95,maxTrimRatio:.05};case"none":return null}}function Ipt(e,t=10){if(e.length===0)return[];const n=[...e].sort((s,a)=>s-a),r=[];let i=n[0],o=n[0];for(let s=1;s<n.length;s++)n[s]-o<=t||(r.push(Math.round((i+o)/2)),i=n[s]),o=n[s];return r.push(Math.round((i+o)/2)),r}function bce(e,t,n,r=240){return e>=r&&t>=r&&n>=r}function mN(e,t=50){return e<t}function xce(e,t){const{width:n,data:r}=e;let i=0;for(let o=0;o<n;o++){const s=(t*n+o)*4;bce(r[s],r[s+1],r[s+2])&&i++}return i/n}function brt(e,t){const{width:n,data:r}=e;let i=0;for(let o=0;o<n;o++){const s=(t*n+o)*4;mN(r[s+3])&&i++}return i/n}function Sce(e,t){const{width:n,height:r,data:i}=e;let o=0;for(let s=0;s<r;s++){const a=(s*n+t)*4;bce(i[a],i[a+1],i[a+2])&&o++}return o/r}function xrt(e,t){const{width:n,height:r,data:i}=e;let o=0;for(let s=0;s<r;s++){const a=(s*n+t)*4;mN(i[a+3])&&o++}return o/r}function Srt(e,t,n=.9){return xce(e,t)>=n}function Crt(e,t,n=1){return brt(e,t)>=n}function Ert(e,t,n=.9){return Sce(e,t)>=n}function _rt(e,t,n=1){return xrt(e,t)>=n}function qV(e,t=10){if(e.length===0)return[];const n=[...e].sort((s,a)=>s-a),r=[];let i=n[0],o=n[0];for(let s=1;s<n.length;s++)n[s]-o<=t||(r.push(Math.floor((i+o)/2)),i=n[s]),o=n[s];return r.push(Math.floor((i+o)/2)),r}function Irt(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(o=>{const s=e/o.cols,a=t/o.rows,l=s/a,u=1/(1+Math.abs(l-1)*10);return{...o,score:u,cellAspectRatio:l}}).filter(o=>o.cellAspectRatio>=.8&&o.cellAspectRatio<=1.25)}function Art(e,t,n){const r=Irt(t,n);if(r.length===0)return null;for(const i of r)if(Prt(e,t,n,i.rows,i.cols))return{rows:i.rows,cols:i.cols};return null}function Prt(e,t,n,r,i){const o=t/i,s=n/r,a=10,l=.7;for(let c=1;c<i;c++){const u=Math.round(c*o);let d=!1;for(let f=u-a;f<=u+a;f++){if(f<0||f>=t)continue;if(Sce(e,f)>=l){d=!0;break}}if(!d)return!1}for(let c=1;c<r;c++){const u=Math.round(c*s);let d=!1;for(let f=u-a;f<=u+a;f++){if(f<0||f>=n)continue;if(xce(e,f)>=l){d=!0;break}}if(!d)return!1}return!0}const krt=[{rows:2,cols:2,minMean:42,minStrongRatio:.46},{rows:2,cols:3,minMean:44,minStrongRatio:.48},{rows:3,cols:2,minMean:44,minStrongRatio:.48},{rows:2,cols:4,minMean:46,minStrongRatio:.5},{rows:4,cols:2,minMean:46,minStrongRatio:.5},{rows:3,cols:3,minMean:50,minStrongRatio:.52}];function Trt(e,t,n,r){const i=e/r,o=t/n,s=i/o;return s>=.72&&s<=1.4}function Cce(e,t,n){const r=e[t]-e[n],i=e[t+1]-e[n+1],o=e[t+2]-e[n+2];return Math.sqrt(r*r+i*i+o*o)}function Drt(e,t){const{width:n,height:r,data:i}=e;if(t<=0||t>=n)return{mean:0,strongRatio:0,edgeBalance:0};const o=Math.floor(r*.03),s=Math.ceil(r*.97),a=Math.max(1,Math.floor(r/900));let l=0,c=0,u=0,d=0,f=0;for(let p=o;p<s;p+=a){const y=(p*n+t-1)*4,v=(p*n+t)*4,w=Cce(i,y,v);l+=w,w>=42?(c++,f++,d=Math.max(d,f)):f=0,u++}return u>0?{mean:l/u,strongRatio:c/u,edgeBalance:d/u}:{mean:0,strongRatio:0,edgeBalance:0}}function Mrt(e,t){const{width:n,height:r,data:i}=e;if(t<=0||t>=r)return{mean:0,strongRatio:0,edgeBalance:0};const o=Math.floor(n*.03),s=Math.ceil(n*.97),a=Math.max(1,Math.floor(n/900));let l=0,c=0,u=0,d=0,f=0;for(let p=o;p<s;p+=a){const y=((t-1)*n+p)*4,v=(t*n+p)*4,w=Cce(i,y,v);l+=w,w>=42?(c++,f++,d=Math.max(d,f)):f=0,u++}return u>0?{mean:l/u,strongRatio:c/u,edgeBalance:d/u}:{mean:0,strongRatio:0,edgeBalance:0}}function YV(e,t){return e.edgeBalance>=.18&&e.mean>=((t==null?void 0:t.minMean)??42)&&e.strongRatio>=((t==null?void 0:t.minStrongRatio)??.46)}function Ort(e,t){const n=Math.max(4,Math.floor(e.width*.006));let r={mean:0,strongRatio:0,edgeBalance:0,position:t};for(let i=t-n;i<=t+n;i++){const o=Drt(e,i);o.mean*o.strongRatio>r.mean*r.strongRatio&&(r={...o,position:i})}return r}function Rrt(e,t){const n=Math.max(4,Math.floor(e.height*.006));let r={mean:0,strongRatio:0,edgeBalance:0,position:t};for(let i=t-n;i<=t+n;i++){const o=Mrt(e,i);o.mean*o.strongRatio>r.mean*r.strongRatio&&(r={...o,position:i})}return r}function Nrt(e,t,n){let r=null;for(const i of krt){if(!Trt(t,n,i.rows,i.cols))continue;const o=t/i.cols,s=n/i.rows,a=[],l=[],c=[];let u=!0;for(let f=1;f<i.cols;f++){const p=Ort(e,Math.round(f*o));if(!YV(p,i)){u=!1;break}a.push(p),l.push(p.position)}if(!u)continue;for(let f=1;f<i.rows;f++){const p=Rrt(e,Math.round(f*s));if(!YV(p,i)){u=!1;break}a.push(p),c.push(p.position)}if(!u||a.length===0)continue;const d=a.reduce((f,p)=>f+p.mean*p.strongRatio*p.edgeBalance,0)/a.length;(!r||d>(r.score??0))&&(r={...i,rowLines:c,colLines:l,score:d})}return r}function XV(e,t=3){if(e.length===0)return[];const n=[...e].sort((s,a)=>s-a),r=[];let i=n[0],o=n[0];for(let s=1;s<=n.length;s++)s<n.length&&n[s]-o<=1?o=n[s]:(o-i+1>=t&&r.push(Math.floor((i+o)/2)),s<n.length&&(i=n[s],o=n[s]));return r}function jrt(e){const{data:t}=e;for(let n=3;n<t.length;n+=4)if(t[n]>50)return!1;return!0}function Ece(e){const{data:t}=e;let n=0;const r=t.length/4;for(let o=3;o<t.length;o+=40)mN(t[o])&&n++;const i=Math.floor(r/10);return n/i>.05}async function _ce(e,t){const n=await jh(e),{naturalWidth:r,naturalHeight:i}=n,o=document.createElement("canvas");o.width=r,o.height=i;const s=o.getContext("2d",{willReadFrequently:!0});if(!s)throw new Error("Failed to get canvas context");s.drawImage(n,0,0);const a=s.getImageData(0,0,r,i),l=t??Ece(a),c=[],u=Math.floor(i*.05);if(l)for(let E=u;E<i-u;E++)Crt(a,E)&&c.push(E);else for(let E=u;E<i-u;E++)Srt(a,E)&&c.push(E);const d=[],f=Math.floor(r*.05);if(l)for(let E=f;E<r-f;E++)_rt(a,E)&&d.push(E);else for(let E=f;E<r-f;E++)Ert(a,E)&&d.push(E);const p=XV(c,2),y=XV(d,2),v=qV(p,Math.floor(i*.02)),w=qV(y,Math.floor(r*.02)),C=Art(a,r,i);if(C){const E=r/C.cols,_=i/C.rows,I=[],D=[];for(let P=1;P<C.rows;P++)I.push(Math.round(P*_));for(let P=1;P<C.cols;P++)D.push(Math.round(P*E));return{detection:{rows:C.rows,cols:C.cols,rowLines:I,colLines:D},img:n,imageData:a,canvas:o,hasTransparency:l}}const x=l?null:Nrt(a,r,i);return x?{detection:{rows:x.rows,cols:x.cols,rowLines:x.rowLines??[],colLines:x.colLines??[],useDetectedLines:!0},img:n,imageData:a,canvas:o,hasTransparency:l}:{detection:{rows:v.length+1,cols:w.length+1,rowLines:v,colLines:w},img:n,imageData:a,canvas:o,hasTransparency:l}}async function Ice(e,t){const{detection:n}=await _ce(e,t);return n}async function Lrt(e){try{const{detectPhotoWallRegions:t}=await xn(async()=>{const{detectPhotoWallRegions:r}=await import("./photo-wall-splitter-DhBTEpdG.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 Brt(e,t,n){const{rowLines:r,colLines:i}=e;if(e.useDetectedLines||r.length===0||i.length===0)return!1;const o=n/(r.length+1);for(let a=0;a<r.length;a++){const l=o*(a+1);if(Math.abs(r[a]-l)>o*.15)return!1}const s=t/(i.length+1);for(let a=0;a<i.length;a++){const l=s*(a+1);if(Math.abs(i[a]-l)>s*.15)return!1}return!0}async function Frt(e,t,n,r){const i=e.naturalWidth,o=e.naturalHeight,s=Math.floor(i/n),a=Math.floor(o/t),l=[];for(let c=0;c<t;c++)for(let u=0;u<n;u++){const d=c*n+u,f=u*s,p=c*a,y=document.createElement("canvas");y.width=s,y.height=a;const v=y.getContext("2d");v&&(v.drawImage(e,f,p,s,a,0,0,s,a),l.push({imageData:y.toDataURL("image/jpeg",.92),index:d,width:s,height:a,sourceX:f,sourceY:p,hasTransparency:r}))}return l}async function gN(e,t,n,r){const i=await jh(e),{naturalWidth:o,naturalHeight:s}=i;if(Brt(t,o,s))return Frt(i,t.rows,t.cols,n);const l=[0,...t.rowLines,s],c=[0,...t.colLines,o],u=[];let d=0;const f=document.createElement("canvas");f.width=o,f.height=s;const p=f.getContext("2d",{willReadFrequently:!0});if(!p)return u;p.drawImage(i,0,0);const y=p.getImageData(0,0,o,s),v=n??Ece(y),w=(r==null?void 0:r.trimMode)??"normal",C=wrt(w);for(let x=0;x<l.length-1;x++)for(let E=0;E<c.length-1;E++){const _=c[E],I=c[E+1],D=l[x],P=l[x+1],k=t.useDetectedLines||v||w==="strict"?0:2,R=_+(E>0?k:0),T=D+(x>0?k:0),M=I-_-(E>0?k:0)-(E<c.length-2?k:0),F=P-D-(x>0?k:0)-(x<l.length-2?k:0);if(M<=0||F<=0)continue;const V=p.getImageData(R,T,M,F);if(v&&jrt(V))continue;let H;v?H=zrt(V,!0):C?H=GC(V,C.borderRatio,C.maxTrimRatio):H={top:0,right:M-1,bottom:F-1,left:0};const j=R+H.left,z=T+H.top,N=H.right-H.left+1,B=H.bottom-H.top+1;if(N<=10||B<=10)continue;const O=document.createElement("canvas");O.width=N,O.height=B;const $=O.getContext("2d");if(!$)continue;$.drawImage(i,j,z,N,B,0,0,N,B);const U=v?"image/png":"image/jpeg",Y=v?void 0:.92;u.push({imageData:O.toDataURL(U,Y),index:d++,width:N,height:B,sourceX:j,sourceY:z,hasTransparency:v})}return u}function ZV(e,t,n,r=235){return e>=r&&t>=r&&n>=r}function $rt(e,t=.7,n=.15){const{width:r,height:i,data:o}=e,s=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 x=0;const E=Math.floor(u),_=r-Math.floor(u),I=_-E;if(I<=0)return!1;for(let D=E;D<_;D++){const P=(C*r+D)*4;ZV(o[P],o[P+1],o[P+2])&&x++}return x/I>t},f=C=>{let x=0;const E=Math.floor(u),_=i-Math.floor(u),I=_-E;if(I<=0)return!1;for(let D=E;D<_;D++){const P=(D*r+C)*4;ZV(o[P],o[P+1],o[P+2])&&x++}return x/I>t};let p=0;for(;p<s&&p<i-1&&d(p);)p++;let y=i-1;for(;i-1-y<a&&y>p&&d(y);)y--;let v=0;for(;v<l&&v<r-1&&f(v);)v++;let w=r-1;for(;r-1-w<c&&w>v&&f(w);)w--;return{top:p,right:w,bottom:y,left:v}}function zrt(e,t=!0){const{width:n,height:r,data:i}=e,o=t?0:50,s=f=>{for(let p=0;p<n;p++){const y=(f*n+p)*4;if(i[y+3]>o)return!1}return!0},a=f=>{for(let p=0;p<r;p++){const y=(p*n+f)*4;if(i[y+3]>o)return!1}return!0};let l=0;for(;l<r&&s(l);)l++;let c=r-1;for(;c>l&&s(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 Ace(e){const t=await jh(e),n=t.naturalWidth,r=t.naturalHeight,i=document.createElement("canvas");i.width=n,i.height=r;const o=i.getContext("2d",{willReadFrequently:!0});if(!o)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}};o.drawImage(t,0,0);const s=o.getImageData(0,0,n,r),a=$rt(s,.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,p=r-a.bottom-1,y=5;let v=0;if(u>y&&v++,d>y&&v++,f>y&&v++,p>y&&v++,!(v>=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 x=C.getContext("2d");return x?(x.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:p},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 Kp=100;async function yN(e,t=0,n=2,r){if(t>=n)return[e];if(e.width<Kp||e.height<Kp)return[e];const i=(r==null?void 0:r.skipTrim)??!1;let o=e.imageData,s=e.width,a=e.height,l=!1,c=0,u=0;if(!i){const{trimmedImageUrl:x,borderInfo:E}=await Ace(e.imageData);if(o=x,s=E.trimmed.width,a=E.trimmed.height,l=E.hasBorders,c=E.borders.left,u=E.borders.top,s<Kp||a<Kp)return l?[{...e,imageData:o,width:s,height:a,sourceX:e.sourceX+c,sourceY:e.sourceY+u}]:[e]}const d=await Ice(o,e.hasTransparency);if(d.rows<=1&&d.cols<=1)return l?[{...e,imageData:o,width:s,height:a,sourceX:e.sourceX+c,sourceY:e.sourceY+u}]:[e];const f=d.rows>1&&d.cols>1,p=await gN(o,d,e.hasTransparency,{trimMode:f?"strict":"normal"});if(p.length<=1)return l?[{...e,imageData:o,width:s,height:a}]:[e];const y=e.sourceX+c,v=e.sourceY+u,w=p.map(x=>({...x,sourceX:x.sourceX+y,sourceY:x.sourceY+v}));if(f)return w;const C=[];for(const x of w){if(x.width<Kp||x.height<Kp){C.push(x);continue}const E=await yN(x,t+1,n,r);C.push(...E)}return C}function Urt(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 o=Pn(e,[i],!1),s=o.y+o.height;s>n&&(n=s,t=i)}catch{}if(!t)return{x:100,y:100};const r=Pn(e,[t],!1);return{x:r.x,y:r.y+r.height+50}}catch{return{x:100,y:100}}}async function Pce(e,t,n){const r=nXe("图片分割"),{sourceRect:i,startPoint:o,scrollToResult:s=!0}=n||{};try{let a=[],l=!1;const{trimmedImageUrl:c,borderInfo:u}=await Ace(t),d=u.trimmed.width,f=u.trimmed.height,{detection:p,hasTransparency:y}=await _ce(c);if(p.rows>1||p.cols>1){l=p.rows>1&&p.cols>1;const P=await gN(c,p,y,{trimMode:l?"strict":"normal"});if(y)a=P;else if(l)a=P;else for(const T of P){if(a.length>=25)break;if(T.width<100||T.height<100){a.push(T);continue}const M=await yN(T,0,2,{skipTrim:!0}),F=25-a.length;a.push(...M.slice(0,F))}}else if(await Lrt(c)){const{splitPhotoWall:k}=await xn(async()=>{const{splitPhotoWall:T}=await import("./photo-wall-splitter-DhBTEpdG.js");return{splitPhotoWall:T}},[],import.meta.url);a=(await k(c)).map((T,M)=>({imageData:T.imageData,index:M,width:T.width,height:T.height,sourceX:T.sourceX??0,sourceY:T.sourceY??0}))}if(a.length===0)return{success:!1,count:0,error:"未检测到可拆分的区域,请确保图片包含分割线或灵感图格式"};a=a.map((P,k)=>({...P,index:k}));let v=1;i&&(v=Math.min(i.width/d,i.height/f));let w,C;if(o)w=o[0],C=o[1];else if(i)w=i.x,C=i.y+i.height+20;else{const P=Urt(e);w=P.x,C=P.y}const x=a.some(P=>P.sourceX>0||P.sourceY>0);if(x&&!i){let P=0,k=0;for(const M of a){const F=M.sourceX+M.width,V=M.sourceY+M.height;F>P&&(P=F),V>k&&(k=V)}P>0&&k>0&&(v=Math.min(800/P,600/k,1))}let E,_;const{unifiedCacheService:I}=await xn(async()=>{const{unifiedCacheService:P}=await Promise.resolve().then(()=>du);return{unifiedCacheService:P}},void 0,import.meta.url),D=[];if(!x&&a.length>1){const P=a.length,k=Math.ceil(Math.sqrt(P)),R=Math.ceil(P/k),T=a.reduce((N,B)=>N+B.width,0)/a.length,M=a.reduce((N,B)=>N+B.height,0)/a.length,V=Math.min(400/Math.max(T,M),1),H=T*V,j=M*V,z=20;for(let N=0;N<a.length;N++){const B=Math.floor(N/k),O=N%k,$=a[N],U=Math.min(H/$.width,j/$.height,1);D.push({x:w+O*(H+z),y:C+B*(j+z),width:$.width*U,height:$.height*U})}}for(let P=0;P<a.length;P++){const k=a[P];let R,T,M,F;if(x){const O=k.sourceX*v,$=k.sourceY*v;R=w+O,T=C+$,M=k.width*v,F=k.height*v}else if(D.length>0){const O=D[P];R=(O==null?void 0:O.x)??w,T=(O==null?void 0:O.y)??C,M=(O==null?void 0:O.width)??k.width*v,F=(O==null?void 0:O.height)??k.height*v}else R=w,T=C,M=k.width*v,F=k.height*v;E||(E=[R,T],_={width:M,height:F});const V=k.hasTransparency?"png":"jpg",j=`/__aitu_cache__/image/${`split-image-${Date.now()}-${P}`}.${V}`,N=await(await fetch(k.imageData)).blob();await I.cacheToCacheStorageOnly(j,N);const B={url:j,width:M,height:F};ii.insertImage(e,B,[R,T])}if(s&&E&&_){const P=[E[0]+_.width/2,E[1]+_.height/2];requestAnimationFrame(()=>{Ba(e,P)})}return r(),{success:!0,count:a.length}}catch(a){return r(),{success:!1,count:0,error:a.message||"拆分图片失败"}}}const Apt=Object.freeze(Object.defineProperty({__proto__:null,detectGridLines:Ice,recursiveSplitElement:yN,splitAndInsertImages:Pce,splitImageByLines:gN},Symbol.toStringTag,{value:"Module"})),Hrt={label:"自动",value:"auto",width:0,height:0,description:"由模型自动决定最佳比例"},Y2=[Hrt,{label:"1:1",value:"1:1",width:1,height:1,description:"正方形"},{label:"1:4",value:"1:4",width:1,height:4,description:"超长竖版"},{label:"4:1",value:"4:1",width:4,height:1,description:"超长横版"},{label:"1:8",value:"1:8",width:1,height:8,description:"极长竖版"},{label:"8:1",value:"8:1",width:8,height:1,description:"极长横版"},{label:"2:3",value:"2:3",width:2,height:3,description:"竖版标准"},{label:"3:2",value:"3:2",width:3,height:2,description:"横版标准"},{label:"3:4",value:"3:4",width:3,height:4,description:"竖版"},{label:"4:3",value:"4:3",width:4,height:3,description:"横版"},{label:"4:5",value:"4:5",width:4,height:5,description:"竖版社交"},{label:"5:4",value:"5:4",width:5,height:4,description:"横版"},{label:"9:16",value:"9:16",width:9,height:16,description:"竖屏全屏"},{label:"16:9",value:"16:9",width:16,height:9,description:"横屏全屏"},{label:"21:9",value:"21:9",width:21,height:9,description:"超宽屏"}],oO="auto";function Wrt(e){return!e||e==="auto"?void 0:{"1:1":"1x1","1:4":"1x4","4:1":"4x1","1:8":"1x8","8:1":"8x1","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"}[e]}function JV(e,t){if(!e.url)return null;if(!e.maskImage)return g.jsx("img",{src:e.url,alt:e.name});const n=e.width&&e.height&&e.width>0&&e.height>0?{"--mask-pair-aspect":String(e.width*2/e.height)}:void 0;return g.jsxs("div",{className:`${t}__media-pair`,style:n,children:[g.jsx("img",{src:e.url,alt:e.name}),g.jsx("div",{className:`${t}__mask-thumb`,children:g.jsx("img",{src:e.maskImage,alt:`${e.name} mask`})})]})}const QV=({items:e,language:t="zh",enableHoverPreview:n=!0,className:r,onRemove:i,removableStartIndex:o=0})=>{const[s,a]=b.useState(null),l=b.useCallback((u,d)=>{if(!n)return;const f=d.currentTarget.getBoundingClientRect(),p=f.left+f.width/2,y=f.top-10;a({type:u.type,url:u.url,maskImage:u.maskImage,width:u.width,height:u.height,text:u.text,x:p,y})},[n]),c=b.useCallback(()=>{a(null)},[]);return e.length===0?null:g.jsxs(g.Fragment,{children:[n&&s&&Wf.createPortal(g.jsxs("div",{className:`selected-content-preview__hover selected-content-preview__hover--${s.type}`,style:{left:`${s.x}px`,top:`${s.y}px`,transform:"translate(-50%, -100%)"},children:[(s.type==="image"||s.type==="graphics")&&s.url&&JV({url:s.url,maskImage:s.maskImage,width:s.width,height:s.height,name:"Preview"},"selected-content-preview"),s.type==="video"&&s.url&&g.jsx("div",{className:"selected-content-preview__hover-video",children:g.jsx("video",{src:s.url,controls:!0,autoPlay:!0,muted:!0,loop:!0,playsInline:!0})}),s.type==="text"&&s.text&&g.jsxs("div",{className:"selected-content-preview__hover-text",children:[g.jsxs("div",{className:"selected-content-preview__hover-text-header",children:[g.jsx(R8,{size:16}),g.jsx("span",{children:t==="zh"?"文字内容":"Text Content"})]}),g.jsx("div",{className:"selected-content-preview__hover-text-content",children:s.text})]})]}),document.body),g.jsx("div",{className:`selected-content-preview ${r||""}`,children:e.map((u,d)=>{const f=i&&d<o;return g.jsxs("div",{className:`selected-content-preview__item selected-content-preview__item--${u.type}`,onMouseEnter:p=>l(u,p),onMouseLeave:c,children:[u.type==="text"?g.jsxs("div",{className:"selected-content-preview__text",children:[g.jsx(R8,{size:14,className:"selected-content-preview__text-icon"}),g.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"?g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"selected-content-preview__video-placeholder",children:g.jsx(cg,{size:20})}),g.jsx("div",{className:"selected-content-preview__video-overlay",children:g.jsx(SY,{size:16,fill:"white"})})]}):JV(u,"selected-content-preview"),u.type==="image"&&u.maskImage&&g.jsx("span",{className:"selected-content-preview__label selected-content-preview__label--mask",children:"Mask"}),u.type==="graphics"&&g.jsx("span",{className:"selected-content-preview__label",children:t==="zh"?"图形":"Graphics"}),u.type==="video"&&g.jsx("span",{className:"selected-content-preview__label selected-content-preview__label--video",children:t==="zh"?"视频":"Video"}),f&&g.jsx(cn,{content:t==="zh"?"移除":"Remove",showArrow:!1,children:g.jsx("button",{className:"selected-content-preview__remove-btn",onClick:p=>{p.stopPropagation(),i(d)},onMouseDown:p=>p.preventDefault(),children:g.jsx(md,{size:12})})})]},`${u.type}-${d}`)})})]})};function ev(e){return e.tagName==="TEXTAREA"||e.tagName==="INPUT"}function Vrt(e){const t=e.selectionStart||0,n=e.selectionEnd||0;return e.value.substring(t,n)}function kce(e){const t=window.getSelection();if(!t||t.rangeCount===0)return"";const n=t.getRangeAt(0);return e.contains(n.commonAncestorContainer)?t.toString():""}function aT(e){return ev(e)?Vrt(e):kce(e)}function Grt(e,t={}){const{enableCopy:n=!0,stopPropagation:r=!0}=t,i=b.useRef(null);return b.useEffect(()=>{const o=e.current;if(!o)return;const s=v=>!v||!(v instanceof HTMLElement)?!1:!!(["BUTTON","A","INPUT","SELECT","TEXTAREA","LABEL"].includes(v.tagName)||v.onclick||v.getAttribute("role")==="button"||v.closest('button, a, [role="button"], [onclick]')),a=()=>{const v=window.getSelection();return v!==null&&v.toString().length>0},l=v=>{r&&(s(v.target)||a()&&v.stopPropagation())},c=v=>{r&&(s(v.target)||v.stopPropagation())},u=v=>{const w=(v.ctrlKey||v.metaKey)&&v.key==="c",C=(v.ctrlKey||v.metaKey)&&v.key==="x";if(n&&(w||C)){const x=aT(o);x&&aE(x).then(()=>{}).catch(E=>{console.error("Failed to copy text:",E)}),r&&v.stopPropagation()}},d=v=>{if(n){const w=aT(o);w&&v.clipboardData&&(v.clipboardData.setData("text/plain",w),v.preventDefault())}r&&v.stopPropagation()},f=v=>{if(n){const w=aT(o);w&&v.clipboardData&&v.clipboardData.setData("text/plain",w)}r&&v.stopPropagation()},p=()=>{if(ev(o)){const v=o.selectionStart||0,w=o.selectionEnd||0;v!==w&&(i.current={text:o.value.substring(v,w),start:v,end:w})}else{const v=kce(o);v&&(i.current={text:v})}},y=()=>{ev(o)||p()};return o.addEventListener("pointerdown",c),o.addEventListener("mousedown",c),o.addEventListener("pointerup",l),o.addEventListener("pointermove",l),o.addEventListener("mouseup",l),o.addEventListener("click",l),o.addEventListener("keydown",u),o.addEventListener("copy",d),o.addEventListener("cut",f),ev(o)?o.addEventListener("select",p):document.addEventListener("selectionchange",y),()=>{o.removeEventListener("pointerdown",c),o.removeEventListener("mousedown",c),o.removeEventListener("pointerup",l),o.removeEventListener("pointermove",l),o.removeEventListener("mouseup",l),o.removeEventListener("click",l),o.removeEventListener("keydown",u),o.removeEventListener("copy",d),o.removeEventListener("cut",f),ev(o)?o.removeEventListener("select",p):document.removeEventListener("selectionchange",y)}},[e,n,r]),{lastSelection:i.current}}function Krt(e,t,n){return e==="size"?n.split("(")[0].trim():e==="duration"?`${t}s`:e==="klingAction2"?t==="image2video"?"图生":"文生":e==="mode"?t:n}function eG(e){return e.valueType==="number"&&e.id.toLowerCase().includes("seed")}function qrt(e){const t=Number.isFinite(e.min)?e.min:0,n=Number.isFinite(e.max)?e.max:2147483647,r=Math.min(t,n),i=Math.max(t,n);if(e.integer!==!1)return String(Math.floor(Math.random()*(i-r+1))+r);const o=Number.isFinite(e.step)&&e.step?e.step:1,s=Math.floor((i-r)/o);return String(r+Math.floor(Math.random()*(s+1))*o)}const Yrt=({selectedParams:e,onParamChange:t,compatibleParams:n,modelId:r,language:i="zh",disabled:o=!1,isOpen:s,onOpenChange:a,excludeParamIds:l,placement:c="auto"})=>{const{value:u,setValue:d}=F3({controlledValue:s,defaultValue:!1,onChange:a}),[f,p]=b.useState(0),[y,v]=b.useState(0),w=b.useMemo(()=>{const P=n??Kg(r);return l&&l.length>0?P.filter(k=>!l.includes(k.id)):P},[n,r,l]);b.useEffect(()=>{var P;if(u&&w.length>0){p(0);const k=w[0],R=e[k.id],T=((P=k.options)==null?void 0:P.findIndex(M=>M.value===R))??0;v(T>=0?T:0)}},[u,w,e]);const C=b.useMemo(()=>{if(w.length===0)return i==="zh"?"参数":"Params";const P=[];return w.forEach(k=>{var T;const R=e[k.id];if(R)if(k.valueType==="enum"){const M=(T=k.options)==null?void 0:T.find(F=>F.value===R);M&&P.push(Krt(k.id,R,M.label))}else{const M=R.length>10?`${R.slice(0,10)}…`:R;P.push(`${k.shortLabel||k.label}:${M}`)}}),P.length===0?i==="zh"?"配置参数":"Settings":P.join(", ")},[w,e,i]),x=b.useCallback(P=>{P.preventDefault(),!o&&d(!u)},[o,u,d]),E=b.useCallback(P=>{var T,M;if(P==="Escape")return d(!1),!0;const k=w[f],R=((T=k==null?void 0:k.options)==null?void 0:T.length)??0;if(P==="ArrowDown")return p(F=>{var N;const V=F<w.length-1?F+1:0,H=w[V],j=e[H.id],z=((N=H.options)==null?void 0:N.findIndex(B=>B.value===j))??0;return v(z>=0?z:0),V}),!0;if(P==="ArrowUp")return p(F=>{var N;const V=F>0?F-1:w.length-1,H=w[V],j=e[H.id],z=((N=H.options)==null?void 0:N.findIndex(B=>B.value===j))??0;return v(z>=0?z:0),V}),!0;if(P==="ArrowRight")return v(F=>F<R-1?F+1:0),!0;if(P==="ArrowLeft")return v(F=>F>0?F-1:R-1),!0;if(P==="Enter"||P===" "||P==="Tab"){const F=(M=k==null?void 0:k.options)==null?void 0:M[y];return F&&t(k.id,F.value),!0}return!1},[w,f,y,e,t]),_=b.useCallback((P,k)=>{t(P,k)},[t]),I=b.useCallback((P,k)=>{t(P,k,{keepOpen:!0})},[t]),D=b.useCallback(P=>{t(P.id,qrt(P),{keepOpen:!0})},[t]);return w.length===0?null:g.jsx(h_,{isOpen:u,setIsOpen:d,disabled:o,openKeys:["Enter"," ","ArrowDown","ArrowUp"],onOpenKey:E,placement:c,minMenuHeight:240,maxMenuHeight:420,children:({containerRef:P,menuRef:k,menuStyle:R,handleTriggerKeyDown:T})=>g.jsxs("div",{className:"parameters-dropdown",ref:P,children:[g.jsx(cn,{content:`${C} (↑↓ Tab)`,showArrow:!1,children:g.jsxs("button",{className:`parameters-dropdown__trigger ${u?"parameters-dropdown__trigger--open":""}`,onMouseDown:x,onKeyDown:T,type:"button",disabled:o,children:[g.jsx("span",{className:"parameters-dropdown__label",children:C}),g.jsx(lg,{size:14,className:`parameters-dropdown__icon ${u?"parameters-dropdown__icon--open":""}`})]})}),u&&Ui.createPortal(g.jsxs("div",{ref:k,className:`parameters-dropdown__menu parameters-dropdown__menu--flat ${Vh}`,style:{...R,zIndex:Eu.DROPDOWN_PORTAL},onMouseDown:M=>M.stopPropagation(),onClick:M=>M.stopPropagation(),children:[g.jsxs("div",{className:"parameters-dropdown__header",children:[g.jsx(SCe,{size:14}),g.jsx("span",{children:i==="zh"?"设置生成参数 (↑↓←→ Tab)":"Parameters (↑↓←→ Tab)"})]}),g.jsx("div",{className:"parameters-dropdown__sections",children:w.map((M,F)=>{var j;const V=e[M.id],H=F===f;return g.jsxs("div",{className:`parameters-dropdown__section ${H?"parameters-dropdown__section--highlighted":""}`,children:[g.jsx("div",{className:"parameters-dropdown__section-title",children:M.label}),M.valueType==="enum"?g.jsx("div",{className:"parameters-dropdown__options",children:(j=M.options)==null?void 0:j.map((z,N)=>{const B=V===z.value,O=H&&N===y;return g.jsxs("button",{type:"button",className:`parameters-dropdown__option ${B?"parameters-dropdown__option--selected":""} ${O?"parameters-dropdown__option--highlighted":""}`,onClick:()=>_(M.id,z.value),onMouseEnter:()=>{p(F),v(N)},children:[g.jsx("span",{className:"parameters-dropdown__option-label",children:z.label.split("(")[0].trim()}),B&&g.jsx(Nd,{size:12,className:"parameters-dropdown__option-check"})]},z.value)})}):g.jsxs("div",{className:`parameters-dropdown__field ${eG(M)?"parameters-dropdown__field--with-action":""}`,children:[g.jsx("input",{type:M.valueType==="number"?"number":"text",className:"parameters-dropdown__field-input",value:V||"",placeholder:M.description||M.label,min:M.valueType==="number"?M.min:void 0,max:M.valueType==="number"?M.max:void 0,step:M.valueType==="number"?M.step:void 0,onChange:z=>I(M.id,z.target.value),onMouseDown:z=>z.stopPropagation(),onKeyDown:z=>z.stopPropagation()}),eG(M)&&g.jsx(cn,{content:i==="zh"?"随机生成种子":"Randomize seed",showArrow:!1,children:g.jsx("button",{type:"button",className:"parameters-dropdown__field-action",onClick:()=>D(M),onMouseDown:z=>z.stopPropagation(),children:g.jsx(B2e,{size:14})})})]})]},M.id)})})]}),document.body)]})})};function vN(){const e=ci.get();return(e==null?void 0:e.videoModelName)||uu()}function Xrt(){const e=new Set;return Object.values(fu).forEach(t=>{t.durationOptions.forEach(n=>e.add(n.value))}),Array.from(e).sort((t,n)=>parseInt(t)-parseInt(n))}function Zrt(){const e=new Set;return Object.values(fu).forEach(t=>{t.sizeOptions.forEach(n=>e.add(n.value))}),Array.from(e)}async function Jrt(e){const{prompt:t,model:n="veo3",modelRef:r,seconds:i="8",size:o="1280x720",referenceImages:s,params:a}=e,l=Ay(t);if(l)return l;try{const c=n,u=Sd("video",c,r||null);if(!u||u.kind!=="video")return{success:!1,error:`未找到可用的视频适配器: ${c}`,type:"error"};const d=i?Number(i):void 0,f=await u.generateVideo(Rd("video",r||c),{prompt:t,size:o,model:c,modelRef:r||null,duration:Number.isFinite(d)?d:void 0,referenceImages:s,params:a}),p=f.url;return p?{success:!0,data:{url:p,format:f.format||"mp4",prompt:t,model:n,seconds:i,size:o},type:"video"}:{success:!1,error:"API 未返回有效的视频 URL",type:"error"}}catch(c){return console.error("[VideoGenerationTool] Generation failed:",c),S5(c,"视频生成失败")}}function Qrt(e){const t=e.model||"veo3",n=fu[t]||fu.veo3,r=C5(e.referenceImages);return{taskType:Qt.VIDEO,resultType:"video",getDefaultModel:vN,logPrefix:"VideoGenerationTool",buildTaskPayload:()=>({prompt:e.prompt,size:e.size||"16x9",duration:parseInt(e.seconds||n.defaultDuration,10),model:t,modelRef:e.modelRef||null,uploadedImages:r&&r.length>0?r:void 0,referenceImages:e.referenceImages&&e.referenceImages.length>0?e.referenceImages:void 0,params:e.params,promptMeta:e.promptMeta,knowledgeContextRefs:e.knowledgeContextRefs}),buildResultData:()=>({size:e.size||"16x9",duration:parseInt(e.seconds||n.defaultDuration,10)})}}const wN={name:"generate_video",description:`生成视频工具。根据用户的文字描述生成视频。
|
|
2620
2620
|
|
|
2621
2621
|
使用场景:
|
|
2622
2622
|
- 用户想要创建、生成视频
|
|
@@ -2649,7 +2649,7 @@ ${p.join(`
|
|
|
2649
2649
|
- 用户选择了文本内容作为生成素材
|
|
2650
2650
|
|
|
2651
2651
|
不适用场景:
|
|
2652
|
-
- 简单的直接生成(使用 generate_image 或 generate_video)`,inputSchema:{type:"object",properties:{context:{type:"object",description:"Agent 执行上下文,包含用户指令、选中内容等"},textModel:{type:"string",description:"使用的文本模型 ID"},messages:{type:"array",description:"预构建的消息数组,传入时直接使用,不再生成默认系统提示词(用于 Skill 角色扮演/精准工具注入)"},knowledgeContextRefs:{type:"array",description:"本次 Agent 分析使用的知识库笔记轻量引用"}},required:["context"]},supportedModes:["async"],execute:async(e,t)=>{const{context:n,textModel:r,messages:i,modelRef:o,knowledgeContextRefs:s}=e;if(!n)return{success:!1,error:"缺少必填参数 context",type:"error"};const a=Date.now(),l=[],c=_h(s||n.knowledgeContextRefs),u={...n,knowledgeContextRefs:c.length>0?c:void 0};try{const d=await KJe.execute(u,{model:r||u.model.id,modelRef:o||null,messages:i,onChunk:p=>{var y;(y=t==null?void 0:t.onChunk)==null||y.call(t,p)},onToolCall:p=>{var C;const y=ci.get(),v=lle(p.name,{...p.arguments},{defaultModels:u.defaultModels,defaultModelRefs:u.defaultModelRefs,contextModel:u.model,contextModelRef:o||null,fallbackModels:{image:y.imageModelName||El(),video:y.videoModelName||uu(),audio:y.audioModelName||Lh()}});c.length>0&&["generate_image","generate_video","generate_long_video","generate_audio","generate_text"].includes(p.name)&&!v.knowledgeContextRefs&&(v.knowledgeContextRefs=c);const w={id:`step-tool-${Date.now()}-${Math.random().toString(36).substring(2,6)}`,mcp:p.name,args:v,description:bit(p.name,v),status:"running"};l.push(w),(C=t==null?void 0:t.onAddSteps)==null||C.call(t,[w])},onToolResult:p=>{var y;if(l.length>0){const v=l[l.length-1];v.status=p.success?"completed":"failed",(y=t==null?void 0:t.onUpdateStep)==null||y.call(t,v.id,v.status,p.data,p.error)}}}),f=Date.now()-a;return d.success?{success:!0,type:"text",data:{response:d.response,generatedSteps:l,duration:f}}:{success:!1,error:d.error||"AI 分析失败",type:"error",data:{duration:f,generatedSteps:l}}}catch(d){return console.error("[AIAnalyzeTool] Analysis failed:",d),{success:!1,error:d.message||"AI 分析失败",type:"error",data:{duration:Date.now()-a,generatedSteps:l}}}}};function bit(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_audio":return`生成音频: ${((t==null?void 0:t.prompt)||"").substring(0,30)}...`;case"generate_ppt":return`生成PPT: ${((t==null?void 0:t.topic)||"").substring(0,30)}...`;case"generate_grid_image":return`生成宫格图: ${((t==null?void 0:t.theme)||"").substring(0,30)}...`;case"insert_svg":return"插入SVG矢量图";case"canvas_insertion":case"insert_to_canvas":return"插入到画布";default:return`执行 ${e}`}}let R1=null;function xit(e){R1=e}function Ww(){return R1}function Sit(){return R1!==null}function Cit(){if(!R1)throw new Error("画布未初始化,请先打开画布");return R1}const N1=20,pI=50,Eit=100;function j1(e,t){if(t){const i=new RegExp(`\`\`\`(?:${t}|${t.charAt(0).toUpperCase()+t.slice(1)})\\s*([\\s\\S]*?)\`\`\``,"i"),o=e.match(i);if(o)return o[1].trim()}const n=/```(?:\w+)?\s*([\s\S]*?)```/,r=e.match(n);return r?r[1].trim():e.trim()}function Rce(e){return q.getBoundingRectangle(e.filter(t=>!rs.isGroup(t)).map(t=>q.getRectangleByPoints(t.points)))}function Nce(e,t,n=N1){const r=e.x-n,i=e.x+e.width+n,o=e.y-n,s=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||s<c||o>u)}function xN(e){const t=[];if(!e.children||e.children.length===0)return t;for(const n of e.children)try{const r=Pn(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 SN(e,t,n=N1){for(const r of t)if(Nce(e,r,n))return!0;return!1}function CN(e,t,n,r=N1,i=pI){let o=[...e],s=0;for(;s<Eit;){const a={x:o[0],y:o[1],width:t.width,height:t.height};if(!SN(a,n,r))return o;o=[o[0],o[1]+i],s++}return console.warn("[InsertUtils] Max iterations reached, returning current position:",o),o}function _it(e,t){const n=Rce(t),r=n.width,i=n.height,o=xN(e);let s;const a=W5(e);if(a)s=[a[0]-r/2,a[1]];else if(o.length>0){let c=-1/0,u=0;for(const d of o){const f=d.y+d.height;f>c&&(c=f,u=d.x+d.width/2)}s=[u-r/2,c+pI]}else{const c=ne.getBoardContainer(e).getBoundingClientRect(),u=[c.width/2,c.height/2],d=e.viewport.zoom,f=Xh(e),p=f[0]+u[0]/d,y=f[1]+u[1]/d;s=[p-r/2,y-i/2]}return CN(s,{width:r,height:i},o)}function jce(e,t){try{const n=Pn(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 Lce(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 o=Pn(e,[i],!1);n.push({x:o.x,y:o.y,width:o.width,height:o.height})}catch{}}return n}function Bce(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 o=t.points;if(!o||o.length===0)return console.warn("[InsertUtils] Element has no points:",t.id),!1;const s=o.map(a=>[a[0]+n,a[1]+r]);return Qe.setNode(e,{points:s},[i]),!0}catch(i){return console.error("[InsertUtils] Failed to move element:",i),!1}}function Fce(e){const t=W5(e);if(t)return t;const n=xN(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+pI]}const r=ne.getBoardContainer(e).getBoundingClientRect(),i=[r.width/2,r.height/2],o=e.viewport.zoom,s=Xh(e),a=s[0]+i[0]/o,l=s[1]+i[1]/o;return[a,l]}function $ce(e,t){let n=!1;for(const r of t){const i=e.children.find(u=>u.id===r);if(!i)continue;const o=jce(e,i);if(!o)continue;const s=Lce(e,t);if(s.length===0||!SN(o,s,N1))continue;const a=CN([o.x,o.y],{width:o.width,height:o.height},s,N1,pI),l=a[0]-o.x,c=a[1]-o.y;(l!==0||c!==0)&&Bce(e,i,l,c)&&(n=!0)}return n}function EN(e,t,n){if(!t||t.length===0)return{success:!1,error:"没有可插入的元素"};try{const r=new Set(e.children.map(s=>s.id)),i=n||Fce(e);e.insertFragment({elements:JSON.parse(JSON.stringify(t))},i,_d.paste);const o=new Set;for(const s of e.children){const a=s;r.has(a.id)||o.add(a.id)}return o.size>0?requestAnimationFrame(()=>{const s=$ce(e,o);i&&Ba(e,i)}):i&&requestAnimationFrame(()=>{Ba(e,i)}),{success:!0,elementsCount:t.length}}catch(r){return console.error("[InsertUtils] Failed to insert elements:",r),{success:!1,error:r.message||"插入元素失败"}}}const Tpt=Object.freeze(Object.defineProperty({__proto__:null,adjustOverlappingElements:$ce,calculateElementsBoundingRect:Rce,createQueueTask:Bw,extractCodeBlock:j1,findNonOverlappingPosition:CN,getAllElementBoundingBoxes:xN,getBoard:Ww,getElementActualBoundingBox:jce,getInitialInsertionPoint:Fce,getInsertionPoint:_it,getOtherElementBoundingBoxes:Lce,hasOverlapWithAny:SN,insertElementsToCanvas:EN,isBoardAvailable:Sit,isOverlapping:Nce,moveElement:Bce,requireBoard:Cit,setBoard:xit,toUploadedImages:C5,validatePrompt:Ay,wrapApiError:S5},Symbol.toStringTag,{value:"Module"}));let c2=null;function Iit(){return c2||(c2=xn(()=>import("./index-
|
|
2652
|
+
- 简单的直接生成(使用 generate_image 或 generate_video)`,inputSchema:{type:"object",properties:{context:{type:"object",description:"Agent 执行上下文,包含用户指令、选中内容等"},textModel:{type:"string",description:"使用的文本模型 ID"},messages:{type:"array",description:"预构建的消息数组,传入时直接使用,不再生成默认系统提示词(用于 Skill 角色扮演/精准工具注入)"},knowledgeContextRefs:{type:"array",description:"本次 Agent 分析使用的知识库笔记轻量引用"}},required:["context"]},supportedModes:["async"],execute:async(e,t)=>{const{context:n,textModel:r,messages:i,modelRef:o,knowledgeContextRefs:s}=e;if(!n)return{success:!1,error:"缺少必填参数 context",type:"error"};const a=Date.now(),l=[],c=_h(s||n.knowledgeContextRefs),u={...n,knowledgeContextRefs:c.length>0?c:void 0};try{const d=await KJe.execute(u,{model:r||u.model.id,modelRef:o||null,messages:i,onChunk:p=>{var y;(y=t==null?void 0:t.onChunk)==null||y.call(t,p)},onToolCall:p=>{var C;const y=ci.get(),v=lle(p.name,{...p.arguments},{defaultModels:u.defaultModels,defaultModelRefs:u.defaultModelRefs,contextModel:u.model,contextModelRef:o||null,fallbackModels:{image:y.imageModelName||El(),video:y.videoModelName||uu(),audio:y.audioModelName||Lh()}});c.length>0&&["generate_image","generate_video","generate_long_video","generate_audio","generate_text"].includes(p.name)&&!v.knowledgeContextRefs&&(v.knowledgeContextRefs=c);const w={id:`step-tool-${Date.now()}-${Math.random().toString(36).substring(2,6)}`,mcp:p.name,args:v,description:bit(p.name,v),status:"running"};l.push(w),(C=t==null?void 0:t.onAddSteps)==null||C.call(t,[w])},onToolResult:p=>{var y;if(l.length>0){const v=l[l.length-1];v.status=p.success?"completed":"failed",(y=t==null?void 0:t.onUpdateStep)==null||y.call(t,v.id,v.status,p.data,p.error)}}}),f=Date.now()-a;return d.success?{success:!0,type:"text",data:{response:d.response,generatedSteps:l,duration:f}}:{success:!1,error:d.error||"AI 分析失败",type:"error",data:{duration:f,generatedSteps:l}}}catch(d){return console.error("[AIAnalyzeTool] Analysis failed:",d),{success:!1,error:d.message||"AI 分析失败",type:"error",data:{duration:Date.now()-a,generatedSteps:l}}}}};function bit(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_audio":return`生成音频: ${((t==null?void 0:t.prompt)||"").substring(0,30)}...`;case"generate_ppt":return`生成PPT: ${((t==null?void 0:t.topic)||"").substring(0,30)}...`;case"generate_grid_image":return`生成宫格图: ${((t==null?void 0:t.theme)||"").substring(0,30)}...`;case"insert_svg":return"插入SVG矢量图";case"canvas_insertion":case"insert_to_canvas":return"插入到画布";default:return`执行 ${e}`}}let R1=null;function xit(e){R1=e}function Ww(){return R1}function Sit(){return R1!==null}function Cit(){if(!R1)throw new Error("画布未初始化,请先打开画布");return R1}const N1=20,pI=50,Eit=100;function j1(e,t){if(t){const i=new RegExp(`\`\`\`(?:${t}|${t.charAt(0).toUpperCase()+t.slice(1)})\\s*([\\s\\S]*?)\`\`\``,"i"),o=e.match(i);if(o)return o[1].trim()}const n=/```(?:\w+)?\s*([\s\S]*?)```/,r=e.match(n);return r?r[1].trim():e.trim()}function Rce(e){return q.getBoundingRectangle(e.filter(t=>!rs.isGroup(t)).map(t=>q.getRectangleByPoints(t.points)))}function Nce(e,t,n=N1){const r=e.x-n,i=e.x+e.width+n,o=e.y-n,s=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||s<c||o>u)}function xN(e){const t=[];if(!e.children||e.children.length===0)return t;for(const n of e.children)try{const r=Pn(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 SN(e,t,n=N1){for(const r of t)if(Nce(e,r,n))return!0;return!1}function CN(e,t,n,r=N1,i=pI){let o=[...e],s=0;for(;s<Eit;){const a={x:o[0],y:o[1],width:t.width,height:t.height};if(!SN(a,n,r))return o;o=[o[0],o[1]+i],s++}return console.warn("[InsertUtils] Max iterations reached, returning current position:",o),o}function _it(e,t){const n=Rce(t),r=n.width,i=n.height,o=xN(e);let s;const a=W5(e);if(a)s=[a[0]-r/2,a[1]];else if(o.length>0){let c=-1/0,u=0;for(const d of o){const f=d.y+d.height;f>c&&(c=f,u=d.x+d.width/2)}s=[u-r/2,c+pI]}else{const c=ne.getBoardContainer(e).getBoundingClientRect(),u=[c.width/2,c.height/2],d=e.viewport.zoom,f=Xh(e),p=f[0]+u[0]/d,y=f[1]+u[1]/d;s=[p-r/2,y-i/2]}return CN(s,{width:r,height:i},o)}function jce(e,t){try{const n=Pn(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 Lce(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 o=Pn(e,[i],!1);n.push({x:o.x,y:o.y,width:o.width,height:o.height})}catch{}}return n}function Bce(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 o=t.points;if(!o||o.length===0)return console.warn("[InsertUtils] Element has no points:",t.id),!1;const s=o.map(a=>[a[0]+n,a[1]+r]);return Qe.setNode(e,{points:s},[i]),!0}catch(i){return console.error("[InsertUtils] Failed to move element:",i),!1}}function Fce(e){const t=W5(e);if(t)return t;const n=xN(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+pI]}const r=ne.getBoardContainer(e).getBoundingClientRect(),i=[r.width/2,r.height/2],o=e.viewport.zoom,s=Xh(e),a=s[0]+i[0]/o,l=s[1]+i[1]/o;return[a,l]}function $ce(e,t){let n=!1;for(const r of t){const i=e.children.find(u=>u.id===r);if(!i)continue;const o=jce(e,i);if(!o)continue;const s=Lce(e,t);if(s.length===0||!SN(o,s,N1))continue;const a=CN([o.x,o.y],{width:o.width,height:o.height},s,N1,pI),l=a[0]-o.x,c=a[1]-o.y;(l!==0||c!==0)&&Bce(e,i,l,c)&&(n=!0)}return n}function EN(e,t,n){if(!t||t.length===0)return{success:!1,error:"没有可插入的元素"};try{const r=new Set(e.children.map(s=>s.id)),i=n||Fce(e);e.insertFragment({elements:JSON.parse(JSON.stringify(t))},i,_d.paste);const o=new Set;for(const s of e.children){const a=s;r.has(a.id)||o.add(a.id)}return o.size>0?requestAnimationFrame(()=>{const s=$ce(e,o);i&&Ba(e,i)}):i&&requestAnimationFrame(()=>{Ba(e,i)}),{success:!0,elementsCount:t.length}}catch(r){return console.error("[InsertUtils] Failed to insert elements:",r),{success:!1,error:r.message||"插入元素失败"}}}const Tpt=Object.freeze(Object.defineProperty({__proto__:null,adjustOverlappingElements:$ce,calculateElementsBoundingRect:Rce,createQueueTask:Bw,extractCodeBlock:j1,findNonOverlappingPosition:CN,getAllElementBoundingBoxes:xN,getBoard:Ww,getElementActualBoundingBox:jce,getInitialInsertionPoint:Fce,getInsertionPoint:_it,getOtherElementBoundingBoxes:Lce,hasOverlapWithAny:SN,insertElementsToCanvas:EN,isBoardAvailable:Sit,isOverlapping:Nce,moveElement:Bce,requireBoard:Cit,setBoard:xit,toUploadedImages:C5,validatePrompt:Ay,wrapApiError:S5},Symbol.toStringTag,{value:"Module"}));let c2=null;function Iit(){return c2||(c2=xn(()=>import("./index-CpHWUe__.js"),[],import.meta.url).catch(e=>{throw c2=null,e})),c2}function Ait(e){return j1(e,"mermaid")}function Pit(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 kit(e){const t=Ww();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=Ait(n),i=Pit(r),o=await Iit();let s;try{s=await o.parseMermaidToDrawnix(r)}catch(c){console.warn("[MermaidTool] First parse attempt failed, retrying with quote replacement:",c.message),s=await o.parseMermaidToDrawnix(r.replace(/"/g,"'"))}const{elements:a}=s;if(!a||a.length===0)return{success:!1,error:"Mermaid代码解析成功,但未生成任何图表元素",type:"error"};const l=EN(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 Tit={name:"insert_mermaid",description:`将Mermaid图表插入到画布工具。将Mermaid markdown语法转换为可视化图表并插入到画布中。
|
|
2653
2653
|
|
|
2654
2654
|
使用场景:
|
|
2655
2655
|
- 用户需要在画布上创建流程图、时序图、类图等图表
|
|
@@ -2682,7 +2682,7 @@ sequenceDiagram
|
|
|
2682
2682
|
AuthServer->>Client: 返回Access Token
|
|
2683
2683
|
Client->>ResourceServer: 携带Token请求资源
|
|
2684
2684
|
ResourceServer->>Client: 返回资源
|
|
2685
|
-
\`\`\``,inputSchema:{type:"object",properties:{mermaid:{type:"string",description:"Mermaid markdown字符串,可以是纯Mermaid代码或包含```mermaid代码块的markdown"}},required:["mermaid"]},execute:async e=>kit(e)};let u2=null;function Dit(){return u2||(u2=xn(()=>import("./index-
|
|
2685
|
+
\`\`\``,inputSchema:{type:"object",properties:{mermaid:{type:"string",description:"Mermaid markdown字符串,可以是纯Mermaid代码或包含```mermaid代码块的markdown"}},required:["mermaid"]},execute:async e=>kit(e)};let u2=null;function Dit(){return u2||(u2=xn(()=>import("./index-BJ-vS89P.js"),__vite__mapDeps([1]),import.meta.url).catch(e=>{throw u2=null,e})),u2}function Mit(e){const t=j1(e,"markdown");return t===e.trim(),t}async function Oit(e){const t=Ww();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=Mit(n),i=await Dit();let o;try{o=await i.parseMarkdownToDrawnix(r)}catch(l){console.warn("[MindmapTool] First parse attempt failed, retrying with quote replacement:",l.message),o=await i.parseMarkdownToDrawnix(r.replace(/"/g,"'"))}if(!o)return{success:!1,error:"Markdown 解析成功,但未生成思维导图元素",type:"error"};o.points=[[0,0]];const a=EN(t,[o]);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 Rit={name:"insert_mindmap",description:`将 Markdown 思维导图插入到画布工具。将 Markdown 语法转换为可视化思维导图并插入到画布中。
|
|
2686
2686
|
|
|
2687
2687
|
使用场景:
|
|
2688
2688
|
- 用户需要在画布上创建思维导图
|
|
@@ -2960,7 +2960,7 @@ ${r}
|
|
|
2960
2960
|
使用场景:
|
|
2961
2961
|
- 需要了解知识库的目录结构
|
|
2962
2962
|
- 创建笔记前查看可用目录`,inputSchema:{type:"object",properties:{}},execute:async()=>{try{return{success:!0,type:"text",data:(await Ko()).map(t=>({id:t.id,name:t.name,isDefault:t.isDefault,createdAt:new Date(t.createdAt).toISOString()}))}}catch(e){return{success:!1,error:`获取目录失败: ${e.message}`,type:"error"}}}},Sot=[vot,wot,bot,xot];function Cot(e){const t=e.prompt||fY,n=e.videoAnalyzerAction||"analyze";if(n!=="prompt-generate"&&!e.videoData&&!e.youtubeUrl&&!e.videoCacheUrl)return{success:!1,error:"需要提供 videoData、videoCacheUrl 或 youtubeUrl",type:"error"};const r=Mi.createTask({prompt:e.taskLabel||"视频分析",model:e.model,modelRef:e.modelRef||null,mimeType:e.mimeType||"video/mp4",youtubeUrl:e.youtubeUrl,videoData:e.videoData,videoCacheUrl:e.videoCacheUrl,pdfCacheUrl:e.pdfCacheUrl,pdfMimeType:e.pdfMimeType,pdfName:e.pdfName,videoAnalyzerAction:n,videoAnalyzerPrompt:t,videoAnalyzerSource:e.videoAnalyzerSource,videoAnalyzerSourceLabel:e.videoAnalyzerSourceLabel,videoAnalyzerSourceSnapshot:e.videoAnalyzerSourceSnapshot,videoAnalyzerProductInfo:e.videoAnalyzerProductInfo,knowledgeContextRefs:e.knowledgeContextRefs,autoInsertToCanvas:!1},Qt.CHAT);return{success:!0,data:{taskId:r.id,prompt:e.taskLabel||"视频分析",model:e.model},type:"text",taskId:r.id,task:r}}const Eot={name:"video_analyze",description:"分析视频内容,返回结构化的镜头拆解、脚本提取、风格分析等数据",supportedModes:["async","queue"],inputSchema:{type:"object",properties:{videoData:{type:"string",description:"base64 编码的视频数据(不含 data: 前缀),≤20MB"},mimeType:{type:"string",description:"视频 MIME 类型,默认 video/mp4",default:"video/mp4"},youtubeUrl:{type:"string",description:"YouTube 视频 URL"},videoCacheUrl:{type:"string",description:"本地缓存的视频 URL(队列模式)"},pdfCacheUrl:{type:"string",description:"本地缓存的 PDF URL(提示词生成上下文)"},pdfMimeType:{type:"string",description:"PDF MIME 类型,默认 application/pdf"},pdfName:{type:"string",description:"PDF 文件名"},prompt:{type:"string",description:"自定义分析 prompt(可选,有内置默认值)"},videoAnalyzerAction:{type:"string",description:"视频工具动作:analyze 或 prompt-generate"},videoAnalyzerProductInfo:{type:"object",description:"提示词生成时的画面风格、视频模型、单段时长等表单参数"},model:{type:"string",description:"模型 ID,默认使用当前文本模型"}},required:[]},execute:async(e,t)=>(t==null?void 0:t.mode)==="queue"?Cot(e):hY(e)};function _ot(e){const t=e.prompt||Q3;if(!e.audioData&&!e.audioCacheUrl)return{success:!1,error:"需要提供 audioData 或 audioCacheUrl",type:"error"};const n=Mi.createTask({prompt:e.taskLabel||"音频分析",model:e.model,modelRef:e.modelRef||null,mimeType:e.mimeType||"audio/mpeg",audioData:e.audioData,audioCacheUrl:e.audioCacheUrl,musicAnalyzerAction:"analyze",musicAnalyzerPrompt:t,musicAnalyzerSource:e.musicAnalyzerSource,musicAnalyzerSourceLabel:e.musicAnalyzerSourceLabel,musicAnalyzerSourceSnapshot:e.musicAnalyzerSourceSnapshot,autoInsertToCanvas:!1},Qt.CHAT);return{success:!0,data:{taskId:n.id,prompt:e.taskLabel||"音频分析",model:e.model},type:"text",taskId:n.id,task:n}}const Iot={name:"audio_analyze",description:"分析音频内容,返回结构化的音乐风格、情绪、Suno 标签和歌词改写建议",supportedModes:["async","queue"],inputSchema:{type:"object",properties:{audioData:{type:"string",description:"base64 编码的音频数据(不含 data: 前缀)"},mimeType:{type:"string",description:"音频 MIME 类型,默认 audio/mpeg",default:"audio/mpeg"},audioCacheUrl:{type:"string",description:"本地缓存的音频 URL(队列模式)"},prompt:{type:"string",description:"自定义分析 prompt(可选,有内置默认值)"},model:{type:"string",description:"Gemini 多模态模型 ID,默认使用当前文本模型"}},required:[]},execute:async(e,t)=>(t==null?void 0:t.mode)==="queue"?_ot(e):vne(e)};let tG=!1;function Aot(){tG||(tG=!0,oN.registerAll([Z_,wN,iit,cit,tot,Oce,wit,Tit,Rit,Bit,zit,Wit,qit,_N,...Sot,Eot,Iot]))}const Pot=({variant:e="canvas",expanded:t=!1,longText:n=!1,disabled:r=!1,className:i,preview:o,textarea:s,leftTools:a,controls:l,sendButton:c})=>g.jsxs("div",{className:Je("ai-input-bar__container","ai-input-composer-shell",`ai-input-composer-shell--${e}`,{"ai-input-bar__container--expanded":t,"ai-input-composer-shell--expanded":t,"ai-input-composer-shell--disabled":r},i),"aria-disabled":r||void 0,"data-testid":`ai-input-composer-shell-${e}`,children:[g.jsxs("div",{className:"ai-input-bar__bottom-bar ai-input-composer-shell__bottom-bar",children:[a?g.jsx("div",{className:"ai-input-bar__bottom-start ai-input-composer-shell__bottom-start",children:a}):null,l?g.jsx("div",{className:"ai-input-bar__bottom-controls ai-input-composer-shell__bottom-controls",children:l}):null,c]}),g.jsxs("div",{className:Je("ai-input-bar__input-area","ai-input-composer-shell__input-area",{"ai-input-bar__input-area--expanded":t,"ai-input-bar__input-area--long-text":n,"ai-input-composer-shell__input-area--expanded":t,"ai-input-composer-shell__input-area--long-text":n}),children:[o?g.jsx("div",{className:"ai-input-bar__content-preview ai-input-composer-shell__preview",children:o}):null,g.jsx("div",{className:"ai-input-bar__prompt-row ai-input-composer-shell__prompt-row",children:s})]})]}),wf=[{value:"image",label:"图片",icon:g.jsx(wS,{size:14}),zh:"图片",en:"Image"},{value:"video",label:"视频",icon:g.jsx(cg,{size:14}),zh:"视频",en:"Video"},{value:"audio",label:"音频",icon:g.jsx(iR,{size:14}),zh:"音频",en:"Audio"},{value:"text",label:"文本",icon:g.jsx(q2e,{size:14}),zh:"文本",en:"Text"},{value:"agent",label:"Agent",icon:g.jsx(u2e,{size:14}),zh:"Agent",en:"Agent"}],kot=({value:e,onSelect:t,disabled:n=!1})=>{const[r,i]=b.useState(!1),{language:o}=nN(),[s,a]=b.useState(0),l=b.useRef(null);b.useEffect(()=>{if(r){const p=wf.findIndex(y=>y.value===e);a(p>=0?p:0)}},[r,e]),b.useEffect(()=>{if(r&&l.current){const p=l.current.children[s];p&&p.scrollIntoView({block:"nearest"})}},[s,r]);const c=b.useCallback(p=>{p.preventDefault(),!n&&i(y=>!y)},[n]),u=b.useCallback(p=>{t(p),i(!1)},[t]),d=b.useCallback(p=>p==="Escape"?(i(!1),!0):p==="ArrowDown"?(a(y=>y<wf.length-1?y+1:0),!0):p==="ArrowUp"?(a(y=>y>0?y-1:wf.length-1),!0):p==="Enter"||p===" "||p==="Tab"?(u(wf[s].value),!0):!1,[s,u]),f=wf.find(p=>p.value===e)||wf[0];return g.jsx(h_,{isOpen:r,setIsOpen:i,disabled:n,openKeys:["Enter"," ","ArrowDown","ArrowUp"],onOpenKey:d,children:({containerRef:p,menuRef:y,menuStyle:v,handleTriggerKeyDown:w})=>g.jsxs("div",{className:"generation-type-dropdown",ref:p,children:[g.jsx(cn,{content:`${o==="zh"?"生成类型":"Type"}: ${o==="zh"?f.zh:f.en} (↑↓ Tab)`,showArrow:!1,children:g.jsxs("button",{className:`generation-type-dropdown__trigger ${r?"generation-type-dropdown__trigger--open":""}`,onMouseDown:c,onKeyDown:w,disabled:n,type:"button",children:[g.jsx("span",{className:"generation-type-dropdown__icon-prefix",children:f.icon}),g.jsx("span",{className:"generation-type-dropdown__label",children:o==="zh"?f.zh:f.en}),g.jsx(lg,{size:14,className:`generation-type-dropdown__chevron ${r?"generation-type-dropdown__chevron--open":""}`})]})}),r&&Ui.createPortal(g.jsxs("div",{ref:y,className:`generation-type-dropdown__menu ${Vh}`,style:{...v,zIndex:Eu.DROPDOWN_PORTAL},onMouseDown:C=>C.stopPropagation(),onClick:C=>C.stopPropagation(),children:[g.jsxs("div",{className:"generation-type-dropdown__header",children:[g.jsx(Hv,{size:14}),g.jsx("span",{children:o==="zh"?"生成类型 (↑↓ Tab)":"Generation type (↑↓ Tab)"})]}),g.jsx("div",{ref:l,className:"generation-type-dropdown__list",children:wf.map((C,x)=>{const E=C.value===e,_=x===s;return g.jsxs("div",{className:`generation-type-dropdown__item ${E?"generation-type-dropdown__item--selected":""} ${_?"generation-type-dropdown__item--highlighted":""}`,onClick:()=>u(C.value),onMouseEnter:()=>a(x),children:[g.jsx("span",{className:"generation-type-dropdown__item-icon",children:C.icon}),g.jsx("span",{className:"generation-type-dropdown__item-label",children:o==="zh"?C.zh:C.en}),E&&g.jsx(Nd,{size:14,className:"generation-type-dropdown__item-check"})]},C.value)})})]}),document.body)]})})},B0=[1,2,3,4,5,10,20],Tot=({value:e,onSelect:t,disabled:n=!1,isOpen:r,onOpenChange:i})=>{const{value:o,setValue:s}=F3({controlledValue:r,defaultValue:!1,onChange:i}),{language:a}=nN(),[l,c]=b.useState(0),u=b.useRef(null);b.useEffect(()=>{if(o){const y=B0.indexOf(e);c(y>=0?y:0)}},[o,e]),b.useEffect(()=>{if(o&&u.current){const y=u.current.children[l];y&&y.scrollIntoView({block:"nearest"})}},[l,o]);const d=b.useCallback(y=>{y.preventDefault(),!n&&s(!o)},[n,o,s]),f=b.useCallback(y=>{t(y),s(!1)},[t]),p=b.useCallback(y=>y==="Escape"?(s(!1),!0):y==="ArrowDown"?(c(v=>v<B0.length-1?v+1:0),!0):y==="ArrowUp"?(c(v=>v>0?v-1:B0.length-1),!0):y==="Enter"||y===" "||y==="Tab"?(f(B0[l]),!0):!1,[l,f]);return g.jsx(h_,{isOpen:o,setIsOpen:s,disabled:n,openKeys:["Enter"," ","ArrowDown","ArrowUp"],onOpenKey:p,children:({containerRef:y,menuRef:v,menuStyle:w,handleTriggerKeyDown:C})=>g.jsxs("div",{className:"count-dropdown",ref:y,children:[g.jsx(cn,{content:`${a==="zh"?"生成数量":"Count"}: ${e} (↑↓ Tab)`,showArrow:!1,children:g.jsxs("button",{className:`count-dropdown__trigger ${o?"count-dropdown__trigger--open":""}`,onMouseDown:d,onKeyDown:C,disabled:n,type:"button",children:[g.jsxs("span",{className:"count-dropdown__label",children:[e,a==="zh"?"个":""]}),g.jsx(lg,{size:14,className:`count-dropdown__chevron ${o?"count-dropdown__chevron--open":""}`})]})}),o&&Ui.createPortal(g.jsxs("div",{ref:v,className:`count-dropdown__menu ${Vh}`,style:{...w,zIndex:Eu.DROPDOWN_PORTAL},onMouseDown:x=>x.stopPropagation(),onClick:x=>x.stopPropagation(),children:[g.jsx("div",{className:"count-dropdown__header",children:g.jsx("span",{children:a==="zh"?"生成数量 (↑↓ Tab)":"Count (↑↓ Tab)"})}),g.jsx("div",{ref:u,className:"count-dropdown__list",children:B0.map((x,E)=>{const _=x===e,I=E===l;return g.jsxs("div",{className:`count-dropdown__item ${_?"count-dropdown__item--selected":""} ${I?"count-dropdown__item--highlighted":""}`,onClick:()=>f(x),onMouseEnter:()=>c(E),children:[g.jsxs("span",{className:"count-dropdown__item-label",children:[x,a==="zh"?"个":x>1?" items":" item"]}),_&&g.jsx(Nd,{size:14,className:"count-dropdown__item-check"})]},x)})})]}),document.body)]})})};function X2(e){return typeof e=="object"&&e!==null}function dd(e){return typeof e=="string"&&e.length>0?e:void 0}function lO(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function mI(e){if(!X2(e))return;const t=dd(e.taskId);if(t)return t;const n=X2(e.data)?dd(e.data.taskId):void 0;if(n)return n;const r=X2(e.result)?dd(e.result.taskId):void 0;if(r)return r;const[i]=Array.isArray(e.taskIds)?e.taskIds:[];return dd(i)}function Dot(e){return dd(e.params.workflowId)}function Mot(e){return dd(e.params.batchId)}function Oot(e){return lO(e.params.batchIndex)}function Rot(e){var t,n;return dd((t=e.options)==null?void 0:t.batchId)||dd((n=e.args)==null?void 0:n.batchId)}function Not(e){var t,n;return lO((t=e.options)==null?void 0:t.batchIndex)??lO((n=e.args)==null?void 0:n.batchIndex)}function jot(e,t){switch(e.type){case Qt.IMAGE:return t.mcp==="generate_image"||t.mcp==="generate_grid_image"||t.mcp==="generate_inspiration_board";case Qt.VIDEO:return t.mcp==="generate_video"||t.mcp==="generate_long_video";case Qt.AUDIO:return t.mcp==="generate_audio";case Qt.CHAT:return t.mcp==="generate_text"||t.mcp==="ai_analyze";default:return!0}}function Lot(e,t){const n=Oot(e),r=Not(t);if(typeof n!="number"||typeof r!="number"||n!==r)return!1;const i=Mot(e),o=Rot(t);return!i||!o||i===o}function Bot(e,t){return e==null?void 0:e.steps.find(n=>mI(n.result)===t)}function Fot(e,t){const n=Bot(e,t.id);if(n)return n;if(!e||Dot(t)!==e.id)return;const r=e.steps.filter(s=>jot(t,s)),i=r.find(s=>Lot(t,s));if(i)return i;const o=r.filter(s=>!mI(s.result));if(o.length===1)return o[0];if(r.length===1)return r[0]}function f2(e,t){return X2(e)?mI(e)?{...e}:{...e,taskId:t}:{taskId:t}}const $ot=new Set([1,2,3,4,5,10,20]);function Wa(e){try{const t=localStorage.getItem(e);if(!t)return null;const n=JSON.parse(t);return n&&typeof n=="object"&&"value"in n?n.value:n}catch{return null}}function My(e,t){try{const n={value:t,updatedAt:Date.now()};localStorage.setItem(e,JSON.stringify(n))}catch{}}function Rs(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.entries(e).reduce((t,[n,r])=>(typeof r=="string"&&(t[n]=r),t),{})}function Ic(e,t){return typeof t=="string"&&t.trim()?t.trim():e}function nG(e){var t;return new Set(((t=e==null?void 0:e.options)==null?void 0:t.map(n=>n.value))||[])}function zot(e,t){const n=e.find(d=>d.id==="resolution"),r=e.find(d=>d.id==="quality"),i=nG(n),o=nG(r),s=i.has("1k")&&i.has("2k")&&i.has("4k"),a=o.has("auto")&&o.has("low")&&o.has("medium")&&o.has("high");if(!s||!a)return t;const l={...t},c=l.resolution,u=l.quality;return u&&i.has(u)&&!i.has(c)&&(l.resolution=u),u&&!o.has(u)&&delete l.quality,l}function IN(e,t,n){var l;const r=Kg(e),i=new Set([]),o=zot(r,Rs(t)),s={},a=r.find(c=>c.id==="size");if(a&&!e.startsWith("mj")&&!i.has("size")&&(n==null?void 0:n.keepDefaultSize)!==!1){const c=o.size,u=(l=a.options)==null?void 0:l.some(d=>d.value===c);s.size=u?c:EK(e)}return r.forEach(c=>{var f;if(i.has(c.id)||c.id==="size")return;const u=o[c.id];if((c.valueType==="enum"?(f=c.options)==null?void 0:f.some(p=>p.value===u):typeof u=="string"&&u!=="")&&u){s[c.id]=u;return}c.defaultValue&&(s[c.id]=c.defaultValue)}),Oq(e,s)}function Wce(e,t){return IN(e,t)}function Uot(e,t){var o,s;const n=Wa(xr.AI_INPUT_PREFERENCES)||{},r=Ic(e,t),i=(s=(o=n.scopedPreferences)==null?void 0:o.image)==null?void 0:s[r];return i?Rs(i):n.generationType==="image"&&n.selectedModel===e?Rs(n.selectedParams):null}function Hot(e,t,n){var l,c,u;const r=Wa(xr.AI_INPUT_PREFERENCES)||{},i=Ic(e,t),o=r.generationType==="image"&&r.selectedModel===e?Rs(r.selectedParams):{},s=Rs((c=(l=r.scopedPreferences)==null?void 0:l.image)==null?void 0:c[i]),a=IN(e,{...o,...s,...n});My(xr.AI_INPUT_PREFERENCES,{...r,scopedPreferences:{...r.scopedPreferences||{},image:{...((u=r.scopedPreferences)==null?void 0:u.image)||{},[i]:a}}})}function AN(e,t){const n=Rs(t);return pq(e,e,n).reduce((i,o)=>{var l;const s=n[o.id];return(o.valueType==="enum"?(l=o.options)==null?void 0:l.some(c=>c.value===s):typeof s=="string"&&s!=="")&&s?(i[o.id]=s,i):(o.defaultValue&&(i[o.id]=o.defaultValue),i)},{})}function Vce(e,t,n){return{...Rs(e),...typeof t=="string"&&t.trim()?{duration:t.trim()}:{},...typeof n=="string"&&n.trim()?{size:n.trim()}:{}}}function Gce(e,t){const n=lve(VO(e)),{duration:r,size:i,...o}=t;return{extraParams:o,duration:r||n.duration,size:i||n.size}}function Wot(e,t){var o,s;const n=Wa(xr.AI_INPUT_PREFERENCES)||{},r=Ic(e,t),i=(s=(o=n.scopedPreferences)==null?void 0:o.video)==null?void 0:s[r];return i?Rs(i):n.generationType==="video"&&n.selectedModel===e?Rs(n.selectedParams):null}function Vot(e,t,n){var l,c,u;const r=Wa(xr.AI_INPUT_PREFERENCES)||{},i=Ic(e,t),o=r.generationType==="video"&&r.selectedModel===e?Rs(r.selectedParams):{},s=Rs((c=(l=r.scopedPreferences)==null?void 0:l.video)==null?void 0:c[i]),a=AN(e,{...o,...s,...n});My(xr.AI_INPUT_PREFERENCES,{...r,scopedPreferences:{...r.scopedPreferences||{},video:{...((u=r.scopedPreferences)==null?void 0:u.video)||{},[i]:a}}})}function Got(e){return e==="video"?uu():e==="audio"?Lh():e==="text"||e==="agent"?tge:El()}function Kot(e){return e==="image"||e==="video"||e==="audio"||e==="text"||e==="agent"}function qot(e){const t=CK(e);if(t.length===0)return new Set(Y2.map(i=>i.value));const n=new Set,r=new Map(Y2.map(i=>[i.value.replace(":","x"),i.value]));return t.forEach(i=>{if(i.value==="auto"){n.add("auto");return}const o=r.get(i.value);o&&n.add(o)}),n.size>0?n:new Set(Y2.map(i=>i.value))}function Kce(e,t){if(typeof t!="string")return oO;const n=qot(e);return n.has(t)?t:n.has("auto")?"auto":oO}function Yot(e){if(typeof e!="string"||!e.trim())return;if(e==="auto")return oO;const t=e.trim().replace(/[xX]/g,":");return Y2.some(n=>n.value===t)?t:void 0}function Xot(e,t){const n=Kce(e,t),r=Wrt(n);if(r)return CK(e).some(i=>i.value===r)?r:void 0}function qce(e,t,n){const r=Rs(t);if(r.size)return r;const i=Xot(e,n);return i?{...r,size:i}:r}function Zot(){const e=Wa(xr.AI_INPUT_PREFERENCES)||{},t=e.generationType,r=e.modeVersion!==2&&t==="text"?"agent":Kot(t)?t:"image",i=Got(r),o=typeof e.selectedModel=="string"?e.selectedModel:"",s=o?Cl(o):null,a=s&&(s.type===r||(r==="text"||r==="agent")&&s.type==="text")?o:i,l=r==="agent"?{}:IN(a,e.selectedParams),c=r==="agent"||r==="text"?1:typeof e.selectedCount=="number"&&$ot.has(e.selectedCount)?e.selectedCount:1;return{generationType:r,selectedModel:a,selectedParams:l,selectedCount:c,selectedSkillId:typeof e.selectedSkillId=="string"&&e.selectedSkillId.trim()?e.selectedSkillId.trim():"auto"}}function Jot(e){const t=Wa(xr.AI_INPUT_PREFERENCES)||{};My(xr.AI_INPUT_PREFERENCES,{...t,...e,modeVersion:2,selectedParams:e.generationType==="agent"?{}:e.selectedParams,selectedCount:e.generationType==="agent"||e.generationType==="text"?1:e.selectedCount})}function Mpt(e){const t=Wa(xr.AI_IMAGE_TOOL_PREFERENCES)||{},n=Ic(e.currentModel,e.currentSelectionKey),r=Wce(e.currentModel,qce(e.currentModel,e.extraParams,e.aspectRatio));My(xr.AI_IMAGE_TOOL_PREFERENCES,{...t,...e,extraParams:r,scopedPreferences:{...t.scopedPreferences||{},[n]:{modelId:e.currentModel,selectionKey:e.currentSelectionKey||null,extraParams:r,aspectRatio:e.aspectRatio}}}),Hot(e.currentModel,e.currentSelectionKey,r)}function Opt(e){const t=Wa(xr.AI_VIDEO_TOOL_PREFERENCES)||{},n=Ic(e.currentModel,e.currentSelectionKey),r=AN(e.currentModel,Vce(e.extraParams,e.duration,e.size)),i=Gce(e.currentModel,r);My(xr.AI_VIDEO_TOOL_PREFERENCES,{...t,...e,...i,scopedPreferences:{...t.scopedPreferences||{},[n]:{modelId:e.currentModel,selectionKey:e.currentSelectionKey||null,...i}}}),Vot(e.currentModel,e.currentSelectionKey,r)}function rG(e,t,n,r){var a,l;const i=Wa(xr.AI_INPUT_PREFERENCES)||{},o=Ic(t,n),s=(l=(a=i.scopedPreferences)==null?void 0:a[e])==null?void 0:l[o];return Rs(s??r)}function Qot(e,t,n,r){var s;const i=Wa(xr.AI_INPUT_PREFERENCES)||{},o=Ic(t,r);My(xr.AI_INPUT_PREFERENCES,{...i,scopedPreferences:{...i.scopedPreferences||{},[e]:{...((s=i.scopedPreferences)==null?void 0:s[e])||{},[o]:Rs(n)}}})}function Rpt(e,t){var c;const n=Wa(xr.AI_IMAGE_TOOL_PREFERENCES)||{},r=Ic(e,t),i=(c=n.scopedPreferences)==null?void 0:c[r],o=Uot(e,t),s=(i==null?void 0:i.aspectRatio)??n.aspectRatio,a=qce(e,o??(i==null?void 0:i.extraParams)??n.extraParams,s),l=Wce(e,a);return{extraParams:l,aspectRatio:Kce(e,Yot(l.size)||s)}}function Npt(e,t){var l;const n=Wa(xr.AI_VIDEO_TOOL_PREFERENCES)||{},r=Ic(e,t),i=(l=n.scopedPreferences)==null?void 0:l[r],o=VO(e),s=Wot(o,t),a=AN(o,s??Vce((i==null?void 0:i.extraParams)??n.extraParams,(i==null?void 0:i.duration)??n.duration,(i==null?void 0:i.size)??n.size));return Gce(o,a)}const Yce=X.memo(({session:e,isActive:t,onSelect:n,onDelete:r,onRename:i})=>{const[o,s]=b.useState(!1),[a,l]=b.useState(e.title),c=b.useRef(null),u=b.useCallback(()=>{o||n()},[n,o]),d=b.useCallback(x=>{x.stopPropagation(),r()},[r]),f=b.useCallback(x=>{x.stopPropagation(),l(e.title),s(!0)},[e.title]),p=b.useCallback(()=>{const x=a.trim();x&&x!==e.title&&i(x),s(!1)},[a,e.title,i]),y=b.useCallback(()=>{l(e.title),s(!1)},[e.title]),v=b.useCallback(x=>{x.key==="Enter"?(x.preventDefault(),p()):x.key==="Escape"&&(x.preventDefault(),y())},[p,y]),w=b.useCallback(x=>{l(x.target.value)},[]);b.useEffect(()=>{o&&c.current&&(c.current.focus(),c.current.select())},[o]);const C=b.useMemo(()=>{const x=new Date(e.updatedAt),E=new Date;return x.toDateString()===E.toDateString()?x.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"}):x.toLocaleDateString("zh-CN",{month:"short",day:"numeric"})},[e.updatedAt]);return g.jsxs("div",{className:`session-item ${t?"session-item--active":""} ${o?"session-item--editing":""}`,"data-track":"chat_click_session_select",onClick:u,role:"button",tabIndex:0,onKeyDown:x=>!o&&x.key==="Enter"&&u(),children:[g.jsxs("div",{className:"session-item__content",children:[o?g.jsx("input",{ref:c,className:"session-item__title-input",value:a,onChange:w,onKeyDown:v,onBlur:p,onClick:x=>x.stopPropagation(),maxLength:50}):g.jsx("div",{className:"session-item__title",children:e.title}),g.jsx("div",{className:"session-item__time",children:C})]}),!o&&g.jsxs("div",{className:"session-item__actions",children:[g.jsx("button",{className:"session-item__edit","data-track":"chat_click_session_edit",onClick:f,"aria-label":`编辑会话标题: ${e.title}`,children:g.jsx(rZ,{size:14})}),g.jsx("button",{className:"session-item__delete","data-track":"chat_click_session_delete",onClick:d,"aria-label":`删除会话: ${e.title}`,children:g.jsx(nZ,{size:14})})]})]})});Yce.displayName="SessionItem";const Xce=X.memo(({sessions:e,activeSessionId:t,onSelectSession:n,onNewSession:r,onDeleteSession:i,onRenameSession:o})=>{const[s,a]=X.useState(null),l=b.useCallback(p=>{n(p)},[n]),c=b.useCallback(p=>{a(p)},[]),u=b.useCallback(()=>{s&&(i(s),a(null))},[s,i]),d=b.useCallback(()=>{a(null)},[]),f=b.useCallback((p,y)=>{o(p,y)},[o]);return g.jsxs("div",{className:"session-list",children:[g.jsxs("div",{className:"session-list__header",children:[g.jsx("span",{className:"session-list__title",children:"会话列表"}),g.jsxs("button",{className:"session-list__new-btn","data-track":"chat_click_session_new",onClick:r,"aria-label":"新建会话",children:[g.jsx(J1,{size:14}),g.jsx("span",{children:"新建"})]})]}),g.jsx("div",{className:"session-list__items",children:e.length===0?g.jsx("div",{className:"session-list__empty",children:"暂无会话"}):e.map(p=>g.jsx(Yce,{session:p,isActive:p.id===t,onSelect:()=>l(p.id),onDelete:()=>c(p.id),onRename:y=>f(p.id,y)},p.id))}),g.jsx(aN,{open:s!==null,title:"删除会话",description:"确定删除此会话吗?删除后无法恢复。",confirmText:"删除",cancelText:"取消",danger:!0,onOpenChange:p=>{p||d()},onConfirm:u})]})});Xce.displayName="SessionList";const Zce=X.memo(({isOpen:e,onClick:t,drawerWidth:n})=>{const r={right:e&&n?`calc(var(--aitu-toolbar-right-dock-width, 0px) + ${n-18}px)`:"var(--aitu-toolbar-right-dock-width, 0px)"};return g.jsx(cn,{content:e?"收起对话":"展开对话",children:g.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:g.jsx(PR,{size:16,className:"chat-drawer-trigger__icon"})})})});Zce.displayName="ChatDrawerTrigger";function UC(e){return e.sourceProfileName||AO[e.vendor]||e.id}const est=X.memo(({model:e})=>{const{summary:t,detail:n}=nne(e.sourceProfileId,e.id);return t?g.jsx(cn,{content:n,placement:"top",disabled:n===t,children:g.jsx("span",{className:"model-selector__item-price",children:t})}):null}),tst=X.memo(({model:e})=>{const t=rne(e.sourceProfileId,e.id);return t!=null&&t.description?g.jsx("div",{className:"model-selector__item-desc",children:t.description}):null});function nst(e,t){var o;const n=UC(e),r=(o=e.description)==null?void 0:o.trim(),i=(t==null?void 0:t.includeProvider)??!0;return r?!i||r.includes(n)?r:`${n} · ${r}`:i?n:""}function rst(e){return UC(e).trim().slice(0,1).toUpperCase()||"M"}const Jce=X.memo(({className:e,value:t,valueRef:n,onChange:r,variant:i="capsule"})=>{var z;const o=Dm("text"),s=((z=o[0])==null?void 0:z.id)||DO,[a,l]=b.useState(s),[c,u]=b.useState(()=>qn(null,s)),d=t??a,f=n===void 0?c:n,[p,y]=b.useState(!1),[v,w]=b.useState(""),[C,x]=b.useState(null),E=b.useRef(null),_=b.useRef(null);b.useEffect(()=>{!t&&s&&a!==s&&(l(s),u(qn(null,s)))},[s,a,t]),b.useEffect(()=>{if(!p)return;const N=O=>{const $=O.target;E.current&&!E.current.contains($)&&_.current&&!_.current.contains($)&&(y(!1),w(""))},B=setTimeout(()=>{document.addEventListener("mousedown",N)},100);return()=>{clearTimeout(B),document.removeEventListener("mousedown",N)}},[p]);const I=b.useMemo(()=>d?hN(d,f):null,[d,f]),D=b.useMemo(()=>{if($C(o,d,f)||!d)return o;const B=KM("text",d,f);return B?[B,...o]:o},[o,d,f]),P=b.useMemo(()=>$C(D,d,f)||D.find(N=>N.id===d),[D,d,f]),k=b.useCallback(N=>{const B=qn(N.sourceProfileId||null,N.id);t===void 0&&l(N.id),n===void 0&&u(B),r==null||r(N.id,B),y(!1),w("")},[t,n,r]),R=b.useCallback(()=>{const N=!p;y(N),N?x((P==null?void 0:P.vendor)||null):w("")},[P==null?void 0:P.vendor,p]),T=b.useMemo(()=>{const N=new Map,B=[];return D.forEach(O=>{N.has(O.vendor)||(B.push(O.vendor),N.set(O.vendor,0)),N.set(O.vendor,(N.get(O.vendor)??0)+1)}),B.map(O=>({id:O,label:AO[O],count:N.get(O)??0,icon:g.jsx(pv,{vendor:O,size:14})}))},[D]),M=b.useCallback(N=>{x(N)},[]),F=b.useMemo(()=>{const N=v.toLowerCase().trim();return N?D.filter(B=>{var $,U;const O=UC(B).toLowerCase();return B.id.toLowerCase().includes(N)||B.label.toLowerCase().includes(N)||(($=B.shortLabel)==null?void 0:$.toLowerCase().includes(N))||((U=B.description)==null?void 0:U.toLowerCase().includes(N))||O.includes(N)}):C?D.filter(B=>B.vendor===C):D},[v,C,D]),[V,H]=b.useState({top:0,left:0,width:0,bottom:0,placement:"bottom",maxHeight:480});b.useLayoutEffect(()=>{if(!p)return;const N=()=>{if(!_.current)return;const B=_.current.getBoundingClientRect(),O=window.innerHeight,$=O-B.bottom,U=B.top,Y=$<400&&U>$?"top":"bottom",K=Y==="top"?U-16:O-B.bottom-16;H({top:B.top,left:B.left,width:B.width,bottom:B.bottom,placement:Y,maxHeight:Math.min(Math.max(K,200),600)})};return N(),window.addEventListener("resize",N),window.addEventListener("scroll",N,!0),()=>{window.removeEventListener("resize",N),window.removeEventListener("scroll",N,!0)}},[p]);const j=()=>{if(!p)return null;const N=g.jsxs("div",{ref:E,className:"model-selector__dropdown",style:{position:"fixed",zIndex:Eu.DROPDOWN_PORTAL,left:V.left,top:V.placement==="bottom"?V.bottom+8:"auto",bottom:V.placement==="top"?window.innerHeight-V.top+8:"auto",minWidth:360,width:i==="form"?V.width:"auto",maxHeight:V.maxHeight,visibility:V.width===0?"hidden":"visible",transformOrigin:V.placement==="bottom"?"top left":"bottom left",display:"flex",flexDirection:"column"},onClick:B=>B.stopPropagation(),children:[g.jsx("div",{className:"model-selector__search",children:g.jsx(Cd,{value:v,onChange:w,placeholder:"搜索模型...",prefixIcon:g.jsx(uZ,{}),clearable:!0,autofocus:!0})}),g.jsx(kJ,{tabs:T,activeTab:C,onTabChange:M,searchQuery:v,compact:!0,children:g.jsx("div",{className:"model-selector__list",children:F.length===0?g.jsx("div",{className:"model-selector__empty",children:"未找到匹配的模型"}):F.map(B=>{const O=gce(B),$=O===I,U=!!v.trim(),Y=nst(B,{includeProvider:!U});return g.jsxs("button",{className:`model-selector__item ${$?"model-selector__item--active":""}`,"data-track":"chat_click_model_select",onClick:()=>k(B),children:[g.jsx("span",{className:"model-selector__item-icon model-selector__item-icon--text","aria-hidden":"true",children:rst(B)}),g.jsxs("div",{className:"model-selector__item-content",children:[g.jsxs("div",{className:"model-selector__item-header",children:[g.jsx("span",{className:"model-selector__item-name",children:B.shortLabel||B.label}),U?g.jsx("span",{className:"model-selector__item-provider",children:UC(B)}):null,g.jsx(yv,{modelId:B.id,profileId:B.sourceProfileId||null}),g.jsx(ene,{modelId:B.id}),g.jsx(est,{model:B})]}),Y?g.jsx("div",{className:"model-selector__item-desc",children:Y}):g.jsx(tst,{model:B})]}),$&&g.jsx("svg",{className:"model-selector__check",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:g.jsx("path",{d:"M13.3334 4L6.00002 11.3333L2.66669 8",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]},O)})})})]});return Ui.createPortal(N,document.body)};return g.jsxs("div",{className:`model-selector ${e||""} model-selector--variant-${i}`,children:[g.jsxs("button",{ref:_,className:`model-selector__trigger ${p?"model-selector__trigger--active":""}`,"data-track":"chat_click_model_selector",onClick:R,"aria-label":"选择模型","aria-expanded":p,children:[g.jsxs("div",{className:"model-selector__trigger-content",children:[g.jsx(yv,{modelId:(P==null?void 0:P.id)||d,profileId:(P==null?void 0:P.sourceProfileId)||null,className:"model-selector__trigger-health"}),g.jsx("span",{className:"model-selector__trigger-text",children:(P==null?void 0:P.shortLabel)||(P==null?void 0:P.label)||"选择模型"})]}),g.jsx(AR,{size:16,className:`model-selector__trigger-icon ${p?"model-selector__trigger-icon--open":""}`})]}),j()]})});Jce.displayName="ModelSelector";function Ju(e,t){return t!=null&&t.profileId?`${t.profileId}::${e}`:e}function Qce(e){return e.selectionKey||(e.sourceProfileId?`${e.sourceProfileId}::${e.id}`:e.id)}function iG(e){return e?qn(e.sourceProfileId||null,e.id):null}function qp(e,t,n){const r=Ju(t,n),i=(n==null?void 0:n.profileId)??null;return e.find(o=>Qce(o)===r)||(i===null?e.find(o=>o.id===t&&!o.sourceProfileId):void 0)||e.find(o=>o.id===t)}function ist(e,t){return e==="agent"&&t==="text"?"agent":t}function ost(e){return e==="video"?uu():e==="audio"?Lh():e==="text"||e==="agent"?uh():El()}function sst(e){return e==="video"?"video":e==="audio"?"audio":e==="text"||e==="agent"?"text":"image"}function ast(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(i=>e[i]===t[i])}function lst(){const e=Dm("image"),t=Dm("video"),n=Dm("audio"),r=Dm("text"),i=b.useMemo(()=>Zot(),[]),[o,s]=b.useState(i.generationType),[a,l]=b.useState(i.selectedModel),[c,u]=b.useState(null),[d,f]=b.useState(i.selectedParams),[p,y]=b.useState(i.selectedCount),v=b.useRef(d),w=b.useRef(`${o}:${Ju(a,c)}`);b.useEffect(()=>{v.current=d},[d]);const C=b.useMemo(()=>o==="video"?t:o==="audio"?n:o==="text"||o==="agent"?r:e,[n,o,e,r,t]),x=b.useCallback((k,R)=>{const T=so(sst(k)),M=qp(R,T.modelId,qn(T.profileId,T.modelId))||qp(R,T.modelId,null);if(M)return M;const F=ost(k);return qp(R,F,null)||Cl(F)||R[0]},[]);b.useEffect(()=>{const R=qp(C,a,c)||x(o,C);if(R){const T=Ju(a,c),M=Qce(R);T!==M&&(l(R.id),u(iG(R)))}(o==="agent"||o==="text"||o==="audio")&&y(1)},[C,o,x,a,c]);const E=b.useMemo(()=>{var T;if(o==="agent")return[];if(o==="video")return pq(a,c||a,d);const k=Kg(a);return o!=="audio"?k:(d.sunoAction||((T=k.find(M=>M.id==="sunoAction"))==null?void 0:T.defaultValue)||"music")==="lyrics"?k.filter(M=>M.id==="sunoAction"||M.id==="mv"||M.id==="title"||M.id==="tags"):k},[o,a,c,d]);b.useEffect(()=>{const k=o==="agent"?"agent":`${o}:${Ju(a,c)}`,R=o==="agent"?{}:w.current===k?v.current||{}:rG(o,a,Ju(a,c),v.current),T={},M=E.find(j=>j.id==="size"),F=R.size,V=!F||!(M!=null&&M.options)||M.options.some(j=>j.value===F);!a.startsWith("mj")&&M&&(T.size=F&&V?F:M.defaultValue||EK(a)),E.forEach(j=>{if(j.id==="size")return;const z=R[j.id],N=!z||j.valueType!=="enum"||!j.options||j.options.some(B=>B.value===z);z&&N?T[j.id]=z:j.defaultValue&&(T[j.id]=j.defaultValue)});const H=Oq(a,T);ast(v.current||{},H)||(f(H),v.current=H),w.current=k},[E,o,a,c]),b.useEffect(()=>{Jot({generationType:o,selectedModel:a,selectedParams:d,selectedCount:p,selectedSkillId:"auto"}),o!=="agent"&&Qot(o,a,d,Ju(a,c))},[o,p,a,c,d]);const _=b.useCallback(k=>{const R=ist(o,k.type),T=iG(k);s(R),l(k.id),u(T),f(R==="agent"?{}:rG(R,k.id,Ju(k.id,T)))},[o]),I=b.useCallback((k,R)=>{const T=qp(C,k,R||null)||qp(C,k,null)||Cl(k);T&&_(T)},[_,C]),D=b.useCallback(k=>{_(k)},[_]),P=b.useCallback((k,R)=>{f(T=>{const M={...T};return R===void 0||R===""?delete M[k]:M[k]=R,M})},[]);return{generationType:o,setGenerationType:s,selectedModel:a,selectedModelRef:c,selectedSelectionKey:Ju(a,c),selectedParams:d,compatibleParams:E,selectedCount:p,setSelectedCount:y,currentModels:C,handleModelSelect:I,handleModelConfigSelect:D,handleParamSelect:P}}function cst(e){return typeof e=="object"&&e!==null}function ed(e){return typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("/"))}function eue(e,t){return e.startsWith("data:video/")||/\.(mp4|webm|mov)(\?|#|$)/i.test(e)?"video":e.startsWith("data:audio/")||/\.(mp3|wav|ogg|m4a)(\?|#|$)/i.test(e)?"audio":t==="video"||t==="audio"?t:"image"}function Yp(e){return Array.isArray(e)?e.filter(ed):[]}function ust(e,t,n,r){const i=[...Yp(e.urls),...Yp(e.imageUrls),...Yp(e.videoUrls),...Yp(e.audioUrls)];ed(e.url)&&i.unshift(e.url),ed(e.imageUrl)&&i.unshift(e.imageUrl),ed(e.videoUrl)&&i.unshift(e.videoUrl),ed(e.audioUrl)&&i.unshift(e.audioUrl);const o=[...Yp(e.thumbnailUrls),...Yp(e.previewImageUrls)];ed(e.thumbnailUrl)&&o.unshift(e.thumbnailUrl),ed(e.previewImageUrl)&&o.unshift(e.previewImageUrl),i.forEach((s,a)=>{r.has(s)||(r.add(s),n.push({type:eue(s,t),url:s,thumbnailUrl:o[a]||o[0],title:typeof e.title=="string"?e.title:void 0}))})}function tue(e,t=e.steps){const n=[],r=new Set,i=(o,s=0)=>{if(!(s>4)){if(Array.isArray(o)){o.forEach(a=>i(a,s+1));return}if(!cst(o)){ed(o)&&!r.has(o)&&(r.add(o),n.push({type:eue(o,e.generationType),url:o}));return}ust(o,e.generationType,n,r),["data","result","response","output"].forEach(a=>{const l=o[a];Array.isArray(l)?l.forEach(c=>i(c,s+1)):i(l,s+1)})}};return t.forEach(o=>{o.status==="completed"&&i(o.result)}),n}function oG(e){const t=Array.from(e);for(let n=t.length-1;n>=0;n-=1){const r=t[n],i=tue(r).filter(o=>o.type==="image");if(i.length!==0)return i.map((o,s)=>({type:"image",url:o.url,name:o.title||`上一次生成结果 ${s+1}`}))}return[]}function Z2(e){const t=e.trim().toLowerCase();return t?/上面|前面|刚才|上一|之前|这些|那些|这张|这几张|那张|原图|参考|基于|沿用|继续|修改|改成|换成|替换|变成|保持|previous|above|these|those|same|reference|continue|edit|modify|change|replace|turn.*into/i.test(t):!1}const nue=b.forwardRef(({selectedContent:e,implicitReferenceContent:t=[],implicitReferenceLabel:n,implicitReferencePinned:r=!1,onClearImplicitReference:i,onImplicitReferenceConsumed:o,onSend:s,disabled:a=!1,placeholder:l="输入消息..."},c)=>{const u=b.useRef(null),d=b.useRef(null),f=b.useRef(null),[p,y]=b.useState(""),[v,w]=b.useState([]),[C,x]=b.useState(!1),E=b.useMemo(()=>[...v,...e],[e,v]),_=E.length>0,I=E.length>0,{addHistory:D}=mce(),{language:P}=nN(),{addAsset:k}=sN(),R=MQe(),T=lst(),M=b.useCallback(Q=>{Q.length!==0&&w(se=>[...se,...Q])},[]),F=b.useCallback(Q=>new Promise((se,ie)=>{const ce=new FileReader;ce.onload=()=>{const ge=ce.result,Se=new Image;Se.onload=()=>{se({url:ge,width:Se.naturalWidth,height:Se.naturalHeight})},Se.onerror=()=>se({url:ge,width:0,height:0}),Se.src=ge},ce.onerror=ie,ce.readAsDataURL(Q)}),[]),V=b.useCallback(async Q=>{const se=Array.from(Q);if(se.length===0)return;const ie=[];for(const[ce,ge]of se.entries()){if(!ge.type.startsWith("image/")){tn.error("请选择图片文件");continue}if(ge.size>25*1024*1024){tn.error("图片不能超过 25MB");continue}try{k(ge,ln.IMAGE,Lr.LOCAL,ge.name).catch(it=>{console.warn("[EnhancedChatInput] Failed to add asset to library:",it)});const{url:Se,width:Ae,height:Le}=await F(ge);ie.push({type:"image",url:Se,name:ge.name||`上传图片 ${ce+1}`,width:Ae||void 0,height:Le||void 0})}catch(Se){console.error("[EnhancedChatInput] Failed to import image:",Se),tn.error("图片读取失败")}}M(ie)},[k,M,F]),H=b.useCallback(async Q=>{const se=Q.target.files;!se||se.length===0||(await V(se),Q.target.value="")},[V]),j=b.useCallback(()=>{var Q;(Q=d.current)==null||Q.click()},[]),z=b.useCallback(Q=>{const se={type:"image",url:Q.url,name:Q.name||`素材-${Date.now()}`};M([se]),x(!1)},[M]),N=b.useCallback(async Q=>{if(Q.length!==0)try{const se=Q.map(ie=>({type:"image",url:ie.url,name:ie.name||`素材-${Date.now()}`}));M(se),x(!1)}catch(se){console.error("Failed to batch select assets from library:",se),x(!1)}},[M]),B=b.useCallback(Q=>{w(se=>se.filter((ie,ce)=>ce!==Q))},[]);b.useImperativeHandle(c,()=>({setContent:Q=>{var se;y(Q),(se=u.current)==null||se.focus()},getContent:()=>p,focus:()=>{var Q;return(Q=u.current)==null?void 0:Q.focus()}}),[p]);const O=b.useCallback(async Q=>{const se=E.length===0&&t.length>0&&T.generationType!=="agent"&&(r||Z2(Q)),ie=se?t:E;if(!await R.submitGenerationFromDrawer({prompt:Q,selectedContent:ie,generationType:T.generationType,selectedModel:T.selectedModel,selectedModelRef:T.selectedModelRef,selectedParams:T.selectedParams,selectedCount:T.selectedCount})){tn.error("生成入口未准备好,请稍后重试");return}y(""),w([]),se&&(o==null||o())},[R,T.generationType,T.selectedCount,T.selectedModel,T.selectedModelRef,T.selectedParams,E,t,r,o]),$=b.useCallback(()=>{const Q=p.trim();if(!Q&&E.length===0)return;if(T.generationType!=="agent"){O(Q).catch(ce=>{console.error("[EnhancedChatInput] generation submit failed:",ce),tn.error("生成提交失败")});return}const se=[];Q&&se.push({type:"text",text:Q}),E.forEach((ce,ge)=>{ce.type==="image"||ce.type==="graphics"?se.push({type:"data-file",data:{filename:`${ce.type}-${ge+1}.png`,mediaType:"image/png",url:ce.url||""}}):ce.type==="video"&&se.push({type:"data-file",data:{filename:`video-${ge+1}.mp4`,mediaType:"video/mp4",url:ce.url||""}})});const ie={id:`msg_${Date.now()}`,role:"user",parts:se};Q&&D(Q,I,"agent"),Promise.resolve(s(ie)).catch(ce=>{console.error("[EnhancedChatInput] send failed:",ce)}),y(""),w([]),E.length===0&&t.length>0&&(r||Z2(Q))&&(o==null||o())},[p,E,T.generationType,O,s,D,I,t,r,o]),U=b.useCallback(Q=>{Q.nativeEvent.isComposing||Q.key==="Enter"&&!Q.shiftKey&&(Q.preventDefault(),$())},[$]);b.useEffect(()=>{u.current&&(u.current.style.height="auto",u.current.style.height=`${Math.min(u.current.scrollHeight,120)}px`)},[p]);const Y=()=>E.length===0?null:g.jsx("div",{className:"enhanced-chat-input__selection",children:g.jsx(QV,{items:E,language:"zh",enableHoverPreview:!0,onRemove:B,removableStartIndex:v.length})}),K=()=>!_&&t.length>0&&(r||Z2(p))?g.jsxs("div",{className:"enhanced-chat-input__selection enhanced-chat-input__selection--implicit",children:[g.jsxs("div",{className:"enhanced-chat-input__implicit-reference-header",children:[g.jsx("span",{className:"enhanced-chat-input__implicit-reference-label",children:n||(P==="zh"?"输入修改描述后,将以上一次生成结果作为参考":"Using the previous generated results as references")}),i&&g.jsx("button",{type:"button",className:"enhanced-chat-input__implicit-reference-clear",onClick:i,"aria-label":P==="zh"?"取消回复":"Cancel reply",children:"×"})]}),g.jsx(QV,{items:t,language:"zh",enableHoverPreview:!0})]}):null,oe=(()=>{const Q=Y(),se=K();return!Q&&!se?null:g.jsxs(g.Fragment,{children:[Q,se]})})(),J=(p.trim()||E.length>0)&&!a,ae=T.generationType!=="agent";return g.jsxs("div",{className:"enhanced-chat-input",ref:f,children:[g.jsx("div",{className:"enhanced-chat-input__composer-scope ai-input-bar",children:g.jsx(Pot,{variant:"drawer",expanded:!!p.trim()||!!oe,disabled:a,preview:oe,textarea:g.jsx("textarea",{ref:u,className:"enhanced-chat-input__textarea",value:p,onChange:Q=>y(Q.target.value),onKeyDown:U,placeholder:I?"描述你想要的效果...":l,disabled:a,rows:4}),leftTools:g.jsxs(g.Fragment,{children:[g.jsx("input",{ref:d,type:"file",accept:"image/*",multiple:!0,onChange:H,style:{display:"none"}}),g.jsx(cn,{content:P==="zh"?"上传图片":"Upload images",placement:"top",children:g.jsx("button",{className:"ai-input-bar__upload-btn",onMouseDown:Q=>{Q.preventDefault(),Q.stopPropagation()},onClick:j,"aria-label":P==="zh"?"上传图片":"Upload images",type:"button",children:g.jsx(NC,{size:18})})}),g.jsx(cn,{content:P==="zh"?"从素材库选择":"Select from library",placement:"top",children:g.jsx("button",{className:"ai-input-bar__library-btn",onMouseDown:Q=>{Q.preventDefault(),Q.stopPropagation()},onClick:()=>x(!0),"aria-label":P==="zh"?"从素材库选择":"Select from library",type:"button",children:g.jsx(cI,{size:18})})})]}),controls:g.jsxs(g.Fragment,{children:[g.jsx(kot,{value:T.generationType,onSelect:T.setGenerationType,disabled:a}),g.jsx(X3,{selectedModel:T.selectedModel,selectedSelectionKey:T.selectedSelectionKey,onSelect:T.handleModelSelect,onSelectModel:T.handleModelConfigSelect,language:P,models:T.currentModels,placement:"up",header:P==="zh"?ae?"选择模型 (↑↓ Tab)":"选择文本模型 (↑↓ Tab)":ae?"Select model (↑↓ Tab)":"Select text model (↑↓ Tab)",disabled:a}),ae&&T.compatibleParams.length>0&&g.jsx(Yrt,{selectedParams:T.selectedParams,onParamChange:T.handleParamSelect,compatibleParams:T.compatibleParams,modelId:T.selectedModel,language:P,disabled:a,placement:"up"},T.selectedModel),ae&&T.generationType!=="text"&&T.generationType!=="audio"&&g.jsx(Tot,{value:T.selectedCount,onSelect:T.setSelectedCount,disabled:a})]}),sendButton:g.jsx("button",{className:`ai-input-bar__send-btn ${J?"active":""}`,onMouseDown:Q=>{Q.preventDefault(),Q.stopPropagation()},onClick:$,disabled:!J,"aria-label":"发送","data-testid":"drawer-ai-send-btn",children:g.jsx(bCe,{size:18})})})}),C&&g.jsx(fce,{isOpen:C,onClose:()=>x(!1),mode:V5.SELECT,filterType:ln.IMAGE,onSelect:z,onSelectMultiple:N,batchSelectButtonText:"批量插入对话框"})]})});nue.displayName="EnhancedChatInput";const Mv={MAX_TITLE_LENGTH:30,DRAWER_MIN_WIDTH:320,DRAWER_MAX_WIDTH:500,DRAWER_DEFAULT_WIDTH_RATIO:.3},Nh={DRAWER_STATE:"aitu:chat:drawer-state",ACTIVE_SESSION:"aitu:chat:active-session",DATABASE_NAME:"aitu-chat",SESSIONS_STORE:"sessions",MESSAGES_STORE:"messages"},Oy=So.createInstance({name:Nh.DATABASE_NAME,storeName:Nh.SESSIONS_STORE}),Dd=So.createInstance({name:Nh.DATABASE_NAME,storeName:Nh.MESSAGES_STORE});function rue(){return Bh()}function dst(e){const t=e.trim().replace(/\n/g," ");return t.length<=Mv.MAX_TITLE_LENGTH?t:t.slice(0,Mv.MAX_TITLE_LENGTH-3)+"..."}async function fst(){const e=Date.now(),t={id:rue(),title:"新对话",createdAt:e,updatedAt:e,messageCount:0};return await Oy.setItem(t.id,t),t}async function gI(e){return Oy.getItem(e)}async function hst(){const e=[];return await Oy.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 PN(e,t){const n=await gI(e);if(n){const r={...n,...t,updatedAt:Date.now()};await Oy.setItem(e,r)}}async function pst(e){const t=await iue(e);for(const n of t)await Dd.removeItem(n.id);await Oy.removeItem(e)}async function mst(e){await Dd.setItem(e.id,e);const t=await gI(e.sessionId);if(t){const n={messageCount:t.messageCount+1,updatedAt:Date.now()};await PN(e.sessionId,n)}}async function iue(e){const t=[];return await Dd.iterate(n=>{n.sessionId===e&&t.push(n)}),t.sort((n,r)=>n.timestamp-r.timestamp)}async function gst(e,t){const n=await Dd.getItem(e);if(n){const r={...n,...t};await Dd.setItem(e,r)}}async function yst(e){const t=await Dd.getItem(e);if(t){await Dd.removeItem(e);const n=await gI(t.sessionId);n&&await PN(t.sessionId,{messageCount:Math.max(0,n.messageCount-1)})}}const sG={isOpen:!1,width:Math.min(Mv.DRAWER_MAX_WIDTH,Math.max(Mv.DRAWER_MIN_WIDTH,window.innerWidth*Mv.DRAWER_DEFAULT_WIDTH_RATIO)),activeSessionId:null};function oue(){try{const e=localStorage.getItem(Nh.DRAWER_STATE);if(e)return{...sG,...JSON.parse(e)}}catch(e){console.error("[ChatStorage] Failed to get drawer state:",e)}return sG}function vst(e){try{const n={...oue(),...e};localStorage.setItem(Nh.DRAWER_STATE,JSON.stringify(n))}catch(t){console.error("[ChatStorage] Failed to set drawer state:",t)}}async function wst(){await Oy.clear(),await Dd.clear(),localStorage.removeItem(Nh.DRAWER_STATE)}const ar={createSession:fst,getSession:gI,getAllSessions:hst,updateSession:PN,deleteSession:pst,addMessage:mst,getMessages:iue,updateMessage:gst,deleteMessage:yst,getDrawerState:oue,setDrawerState:vst,clearAllData:wst,generateId:rue,generateTitle:dst};var Ho=(e=>(e.SENDING="sending",e.STREAMING="streaming",e.SUCCESS="success",e.FAILED="failed",e))(Ho||{}),Pa=(e=>(e.USER="user",e.ASSISTANT="assistant",e))(Pa||{});let Jl=null;function sue(e){const t={};let n=1,r=1,i=1,o=e;return o=o.replace(/data:image\/[^;]+;base64,[A-Za-z0-9+/=]+/g,s=>{const a=`[图片${n}]`;return t[a]=s,n++,a}),o=o.replace(/data:video\/[^;]+;base64,[A-Za-z0-9+/=]+/g,s=>{const a=`[视频${r}]`;return t[a]=s,r++,a}),o=o.replace(/blob:[^\s"'<>]+/g,s=>{const a=`[媒体${i}]`;return t[a]=s,i++,a}),o=o.replace(/https?:\/\/[^\s"'<>]+\.(png|jpg|jpeg|gif|webp|svg|bmp)(\?[^\s"'<>]*)?/gi,s=>{const a=`[图片${n}]`;return t[a]=s,n++,a}),o=o.replace(/https?:\/\/[^\s"'<>]+\.(mp4|webm|mov|avi|mkv)(\?[^\s"'<>]*)?/gi,s=>{const a=`[视频${r}]`;return t[a]=s,r++,a}),{sanitized:o,urlMap:t}}function bst(e,t){let n=e;for(const[r,i]of Object.entries(t))n=n.split(r).join(i);return n}async function xst(e,t={}){const n={};let r=t.maxImageCount??Number.POSITIVE_INFINITY;return{geminiMessages:await Promise.all(e.filter(o=>o.status==="success"||o.status==="streaming").map(async o=>{const{sanitized:s,urlMap:a}=sue(o.content);Object.assign(n,a);const l=[{type:"text",text:s}];if(t.includeImageAttachments&&o.role===Pa.USER&&o.attachments&&o.attachments.length>0&&r>0){const c=await Cxe(o.attachments,r);r-=c.length,l.push(...c)}return{role:o.role===Pa.USER?"user":"assistant",content:l}})),urlMap:n}}async function Sst(e,t,n=[],r,i,o){return Cst(e,t,n,r,i,o)}async function Cst(e,t,n=[],r,i,o){Jl&&Jl.abort(),Jl=new AbortController;const s=Jl.signal,a=Date.now().toString(),l=Date.now(),c=(typeof i=="string"?i:i==null?void 0:i.modelId)||fh.getConfig().modelName||"unknown";try{Kt.trackModelCall({taskId:a,taskType:"chat",model:c,promptLength:t.length,hasUploadedImage:n.length>0,startTime:l});const u=_i("text",i),d=RO(u==null?void 0:u.binding),f=NO(u==null?void 0:u.binding),p=xxe(n),y=Math.max(f-p,0),{geminiMessages:v,urlMap:w}=await xst(e,{includeImageAttachments:d,maxImageCount:y}),{sanitized:C,urlMap:x}=sue(t),E={...w,...x},_=uY(v),I=Math.max(f-_,0),D=[{type:"text",text:C}];if(d&&n.length>0&&I>0){const T=await Sxe(n,I);D.push(...T)}const P=[];o&&P.push({role:"system",content:[{type:"text",text:o}]}),P.push(...v,{role:"user",content:D});let k="";if(await fh.sendChat(P,T=>{if(s.aborted)return;const M=bst(T,E);k=M,r({type:"content",content:M})},s,i||void 0),s.aborted)throw new Error("Request cancelled");const R=Date.now()-l;return Kt.trackModelSuccess({taskId:a,taskType:"chat",model:c,duration:R,resultSize:k.length}),r({type:"done"}),Jl=null,k}catch(u){Jl=null;const d=Date.now()-l;if(s.aborted||u.message==="Request cancelled"||u.name==="AbortError")throw Kt.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 Kt.trackModelFailure({taskId:a,taskType:"chat",model:c,duration:d,error:f}),r({type:"error",error:f}),u}}function Est(){Jl&&(Jl.abort(),Jl=null)}function _st(){return Jl!==null}const aG={sendChatMessage:Sst,stopGeneration:Est,isGenerating:_st},cO="[[WORKFLOW_MESSAGE]]",Ist=["generate_image","generate_video","generate_long_video","generate_audio","generate_grid_image","generate_photo_wall","generate_inspiration_board","generate_ppt"];function Ast(e){if(!Ist.includes(e.name)||!ale(e.name))return e;const t=ci.get(),n=lle(e.name,{...e.arguments},{fallbackModels:{image:t.imageModelName||El(),video:t.videoModelName||uu(),audio:t.audioModelName||Lh()}});return{...e,arguments:n}}function Pst(e){const t=[];e.aiAnalysis&&t.push(e.aiAnalysis);const n=e.steps.filter(s=>s.status==="completed"),r=e.steps.filter(s=>s.status==="failed");if(n.length>0||r.length>0){const s=[];n.length>0&&s.push(`成功执行 ${n.length} 个工具`),r.length>0&&s.push(`${r.length} 个工具执行失败`),s.length>0&&t.push(`[执行结果: ${s.join(",")}]`)}const i=e.steps.map(s=>{const a={};for(const[l,c]of Object.entries(s.args||{}))l!=="context"&&(typeof c=="string"&&c.length>200?a[l]=c.substring(0,200)+"...":a[l]=c);return{mcp:s.mcp,args:a}}),o={content:t.join(`
|
|
2963
|
-
`)||`已完成任务: ${e.name}`,next:i};return JSON.stringify(o)}function kst(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===Pa.USER?"user":"assistant",parts:t}}function Tst(e,t){const r=e.parts.filter(s=>s.type==="text").map(s=>s.text).join(""),o=e.parts.filter(s=>s.type==="data-file").map((s,a)=>{const l=s.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"?Pa.USER:Pa.ASSISTANT,content:r,timestamp:Date.now(),status:Ho.SUCCESS,attachments:o.length>0?o:void 0}}function Dst(e){return e.workflow&&e.content.startsWith(cO)?{...e,content:Pst(e.workflow)}:e}function lG(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("")}Aot();function Mst(e){const{sessionId:t,temporaryModel:n,onToolCalls:r,onWorkflowUpdate:i}=e,o=b.useRef(sle()),s=b.useRef(r);s.current=r;const a=b.useRef(i);a.current=i;const l=b.useRef(n);l.current=n;const[c,u]=b.useState([]),[d,f]=b.useState("ready"),[p,y]=b.useState(!1),v=b.useRef(null),w=b.useRef([]),C=b.useRef(!1);b.useEffect(()=>{if(!t){u([]),w.current=[];return}(async()=>{y(!0);try{const R=await ar.getMessages(t);w.current=R,u(R.map(kst))}catch(R){console.error("[useChatHandler] Failed to load messages:",R),u([]),w.current=[]}finally{y(!1)}})()},[t]);const x=b.useCallback(async k=>{if(!t)return;if(C.current){console.warn("[useChatHandler] Message already being sent, ignoring duplicate call");return}C.current=!0,f("submitted");const R=Tst(k,t);await ar.addMessage(R),u(N=>[...N,k]);const T=await ar.getSession(t);await ar.updateSession(t,{updatedAt:Date.now(),messageCount:((T==null?void 0:T.messageCount)||0)+1});const M=ar.generateId();v.current=M;const F={id:M,role:"assistant",parts:[{type:"text",text:""}]};u(N=>[...N,F]),f("streaming");const V=w.current.map(Dst);V.push(R),w.current=[...w.current,R];const H=lG(k);let j="",z=!1;try{await aG.sendChatMessage(V.slice(0,-1),H,R.attachments||[],N=>{if(N.type==="content"&&N.content)j=N.content,u(B=>B.map(O=>O.id===M?{...O,parts:[{type:"text",text:j}]}:O));else if(N.type==="done"){const B=zO(j),O=UO(j)||j;if(B.length>0&&s.current){const U=B.map(Z=>Ast(Z)),Y=async()=>{const Z=[];for(const oe of U)try{const J=await oN.executeTool(oe);Z.push({toolCall:oe,success:J.success,data:J.data,error:J.error,taskId:J.taskId})}catch(J){Z.push({toolCall:oe,success:!1,error:J.message||"工具执行失败"})}return Z},K=`${cO}${M}`;u(Z=>Z.map(oe=>oe.id===M?{...oe,parts:[{type:"text",text:K}]}:oe)),s.current(U,M,Y,O)}f("ready");const $={id:M,sessionId:t,role:Pa.ASSISTANT,content:B.length>0?`${cO}${M}`:j,timestamp:Date.now(),status:B.length>0?Ho.STREAMING:Ho.SUCCESS};ar.addMessage($),w.current=[...w.current,$],ar.updateSession(t,{updatedAt:Date.now(),messageCount:((T==null?void 0:T.messageCount)||0)+2}),v.current=null,C.current=!1}else if(N.type==="error"&&N.error){z=!0,f("error");const B=`❌ 错误: ${N.error}`;u($=>$.map(U=>U.id===M?{...U,parts:[{type:"text",text:B}]}:U));const O={id:M,sessionId:t,role:Pa.ASSISTANT,content:B,timestamp:Date.now(),status:Ho.FAILED,error:N.error};ar.addMessage(O),w.current=[...w.current,O],v.current=null,C.current=!1}},l.current,o.current)}catch(N){if(N.message!=="Request cancelled"&&!z){f("error"),console.error("[useChatHandler] Stream error:",N);const B=`❌ 错误: ${N.message||"未知错误"}`;if(u(O=>O.map($=>$.id===M?{...$,parts:[{type:"text",text:B}]}:$)),t&&M){const O={id:M,sessionId:t,role:Pa.ASSISTANT,content:B,timestamp:Date.now(),status:Ho.FAILED,error:N.message||"未知错误"};ar.addMessage(O),w.current=[...w.current,O]}}v.current=null,C.current=!1}},[t]),E=b.useCallback(async()=>{if(aG.stopGeneration(),f("ready"),v.current&&t){const k=c.find(R=>R.id===v.current);if(k){const R=lG(k),T={id:k.id,sessionId:t,role:Pa.ASSISTANT,content:R,timestamp:Date.now(),status:Ho.SUCCESS};await ar.addMessage(T)}v.current=null}},[t,c]),_=b.useCallback(k=>{if(c.length<2)return;const R=[...c].reverse().findIndex(V=>V.role==="user");if(R===-1)return;const T=c.length-1-R,M=c[T],F=c.slice(0,T+1);u(F),x(M)},[c,x]),I=b.useCallback((k,R)=>{u(k),R&&(w.current=R)},[]),D=b.useCallback((k,R)=>{u(T=>[...T,...k]),R&&(w.current=[...w.current,...R])},[]),P=b.useCallback((k,R)=>{w.current=w.current.map(T=>T.id===k?{...T,workflow:R}:T)},[]);return{messages:c,status:d,sendMessage:x,stop:E,regenerate:_,setMessages:u,setMessagesWithRaw:I,appendMessagesWithRaw:D,updateRawMessageWorkflow:P,isLoading:p}}function Ost(e){return typeof e=="object"&&e!==null}function cG(e){if(e.error)return e.error.message||e.error.code||"任务执行失败"}function Rst(e,t){return{...Ost(e)?{...e}:{},taskId:t.id,result:t.result}}function Nst(e){const t=e.filter(o=>o.status==="failed").length,n=e.filter(o=>o.status==="running").length,r=e.filter(o=>o.status==="pending").length,i=e.filter(o=>o.status==="completed").length;return t>0?"failed":n>0?"running":r===0&&i>0?"completed":"pending"}function jst(e){return e.length>0&&e.every(t=>t.status==="completed")}function Lst(e,t){const n=Fot(e,t);if(!n)return null;const r=e.steps.map(l=>{if(l.id!==n.id)return l;switch(t.status){case un.PENDING:case un.PROCESSING:return l.status==="completed"?{...l,result:f2(l.result,t.id)}:{...l,status:"running",result:f2(l.result,t.id),error:void 0};case un.COMPLETED:return{...l,status:"completed",result:Rst(l.result,t),error:void 0};case un.FAILED:return{...l,status:"failed",result:f2(l.result,t.id),error:cG(t)};case un.CANCELLED:return{...l,status:"skipped",result:f2(l.result,t.id),error:cG(t)};default:return l}}),i=jst(r),o=Nst(r),s=e.generationType==="image"&&i,a=e.generationType==="image"&&t.status!==un.COMPLETED&&e.postProcessingStatus!=="completed";return{...e,status:o,steps:r,error:o==="failed"?e.error:void 0,postProcessingStatus:s?"completed":a?void 0:e.postProcessingStatus}}function Bst(e,t){return t&&e?{mode:"append",sessionId:e}:{mode:"create"}}const Fst=X.lazy(()=>xn(()=>Promise.resolve().then(()=>nat),void 0,import.meta.url)),uG="[[WORKFLOW_MESSAGE]]";function $st(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_audio":return`生成音频: ${((t==null?void 0:t.prompt)||"").substring(0,30)}...`;case"generate_text":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 dG="chat-drawer-width",zst=Math.max(375,window.innerWidth*.5),fG=375;function Ust(e){switch(e.status){case"completed":return Ho.SUCCESS;case"failed":case"cancelled":return Ho.FAILED;default:return Ho.STREAMING}}const aue=b.forwardRef(({defaultOpen:e=!1,onOpenChange:t},n)=>{const[r,i]=b.useState(()=>ar.getDrawerState().isOpen??e),[o,s]=b.useState([]),[a,l]=b.useState(null),[c,u]=b.useState(!1),[d,f]=b.useState(()=>{const le=localStorage.getItem(dG);if(le){const me=parseInt(le,10);if(!isNaN(me)&&me>=fG)return Math.min(me,window.innerWidth-60)}return zst}),[p,y]=b.useState(!1),v=b.useRef(null),[w,C]=b.useState(()=>so("text").modelId),[x,E]=b.useState(()=>{const le=so("text");return qn(le.profileId,le.modelId)}),[_,I]=b.useState(new Map),D=b.useRef(_),P=b.useRef(null),[k,R]=b.useState(null),[T,M]=b.useState(null),F=b.useCallback(()=>{const le=new Map;D.current=le,I(le),P.current=null,M(null)},[]),{executeRetry:V,selectedContent:H,setIsDrawerOpen:j,setDrawerWidth:z}=vle();b.useEffect(()=>{j(r)},[r,j]),b.useEffect(()=>{z(d)},[d,z]);const N=X.useRef(null),B=X.useRef(null),{appState:O,setAppState:$}=cy();b.useEffect(()=>{if(!p)return;const le=ke=>{const Oe=window.innerWidth-ke.clientX,De=Math.max(fG,Math.min(Oe,window.innerWidth-60));f(De)},me=()=>{y(!1),localStorage.setItem(dG,String(d))};return document.addEventListener("mousemove",le),document.addEventListener("mouseup",me),document.body.style.userSelect="none",document.body.style.cursor="ew-resize",()=>{document.removeEventListener("mousemove",le),document.removeEventListener("mouseup",me),document.body.style.userSelect="",document.body.style.cursor=""}},[p,d]),b.useEffect(()=>{const le=()=>{const me=window.innerWidth-60;d>me&&f(me)};return window.addEventListener("resize",le),()=>window.removeEventListener("resize",le)},[d]);const U=b.useCallback(le=>{le.preventDefault(),y(!0)},[]),Y=b.useCallback(async(le,me,ke,Oe)=>{var Rt,St;const Ye={id:`workflow-${Date.now()}`,name:"AI 智能生成",generationType:(Rt=le[0])!=null&&Rt.name.includes("video")?"video":(St=le[0])!=null&&St.name.includes("audio")?"audio":"image",prompt:Oe||"",aiAnalysis:Oe,count:le.length,steps:le.map((Ct,Dt)=>({id:`step-${Dt}`,mcp:Ct.name,status:"pending",description:$st(Ct.name,Ct.arguments),args:Ct.arguments}))};I(Ct=>{const Dt=new Map(Ct);return Dt.set(me,Ye),Dt}),P.current=me,ar.updateMessage(me,{workflow:Ye});try{const Ct=await ke();Kt.track("chat_tool_execution_complete",{success:!0,resultCount:Ct.length}),Kt.track("ai_modality_used",{modality:"agent",action:"tool_execution_completed",source:"chat_drawer",success:!0,toolCount:le.length,resultCount:Ct.length}),I(Dt=>{const Gt=new Map(Dt),Ft=Gt.get(me);if(Ft){const Ne={...Ft,steps:Ft.steps.map((gt,nn)=>{const Zt=Ct[nn];return{...gt,status:Zt!=null&&Zt.success?"completed":"failed",error:Zt==null?void 0:Zt.error,result:Zt==null?void 0:Zt.data}})};Gt.set(me,Ne),ar.updateMessage(me,{workflow:Ne,status:Ho.SUCCESS})}return Gt})}catch(Ct){console.error("[ChatDrawer] Tool execution failed:",Ct),I(Dt=>{const Gt=new Map(Dt),Ft=Gt.get(me);if(Ft){const Ne={...Ft,steps:Ft.steps.map(gt=>({...gt,status:"failed",error:Ct.message||"执行失败"}))};Gt.set(me,Ne),ar.updateMessage(me,{workflow:Ne,status:Ho.FAILED})}return Gt})}},[]),K=Mst({sessionId:a,temporaryModel:x||w,onToolCalls:Y});b.useEffect(()=>{D.current=_},[_]);const Z=b.useRef(K.sendMessage);Z.current=K.sendMessage,b.useEffect(()=>{(async()=>{const me=ar.getDrawerState(),ke=await ar.getAllSessions();s(ke);let Oe=null;if(me.activeSessionId?(Oe=me.activeSessionId,l(me.activeSessionId)):ke.length>0&&(Oe=ke[0].id,l(ke[0].id)),Oe)try{const De=await ar.getMessages(Oe),Ye=new Map;for(const St of De)St.workflow&&Ye.set(St.id,St.workflow);D.current=Ye,I(Ye);const Rt=De.find(St=>St.workflow&&St.status===Ho.STREAMING);P.current=(Rt==null?void 0:Rt.id)||null}catch(De){console.error("[ChatDrawer] Failed to load workflow messages:",De)}})()},[]),b.useEffect(()=>{ar.setDrawerState({isOpen:r,activeSessionId:a})},[r,a]),b.useEffect(()=>{if(a&&ge.current){const le=ge.current;ge.current=null,setTimeout(()=>{Z.current(le)},100)}},[a]),b.useEffect(()=>{if(!O.openSettings&&ge.current){const le=ci.get();if(le!=null&&le.apiKey){const me=ge.current;ge.current=null,a?setTimeout(()=>{Z.current(me)},100):(async()=>{const ke=await ar.createSession();s(Oe=>[ke,...Oe]),l(ke.id),ge.current=me})()}}},[O.openSettings,a]),b.useEffect(()=>{const le=me=>{me.key==="Escape"&&r&&(i(!1),t==null||t(!1))};return window.addEventListener("keydown",le),()=>window.removeEventListener("keydown",le)},[r,t]),b.useEffect(()=>{let le=null;return(async()=>{const{workflowSubmissionService:ke}=await xn(async()=>{const{workflowSubmissionService:Oe}=await import("./workflow-submission-service-kAjrrvI-.js").then(De=>De.a);return{workflowSubmissionService:Oe}},__vite__mapDeps([0]),import.meta.url);le=ke.subscribeToAllEvents(Oe=>{const De=Oe;I(Ye=>{let Rt=null;for(const[Gt,Ft]of Ye.entries())if(Ft.id===De.workflowId){Rt=Gt;break}if(!Rt)return Ye;const St=Ye.get(Rt);if(!St)return Ye;const Ct=new Map(Ye);let Dt;switch(De.type){case"step":{Dt={...St,steps:St.steps.map(Gt=>Gt.id===De.stepId?{...Gt,status:De.status||Gt.status,result:De.result??Gt.result,error:De.error??Gt.error}:Gt)};break}case"steps_added":{const Ft=(De.steps||[]).map(Ne=>({id:Ne.id,mcp:Ne.mcp,args:Ne.args,description:Ne.description,status:Ne.status}));Dt={...St,steps:[...St.steps,...Ft]};break}case"completed":case"failed":{const Gt=De.type==="completed"?"completed":"failed";Dt={...St,status:Gt,steps:St.steps.map(Ft=>{if(Ft.status==="running"||Ft.status==="pending"){const Ne=Ft.result;return Ne!=null&&Ne.taskId?Ft:{...Ft,status:Gt,error:De.type==="failed"?De.error:void 0}}return Ft})};break}default:return Ye}return Ct.set(Rt,Dt),ar.updateMessage(Rt,{workflow:Dt}),Ct})})})().catch(ke=>{console.error("[ChatDrawer] Failed to setup workflow sync:",ke)}),()=>{le==null||le.unsubscribe()}},[]),b.useEffect(()=>{if(!c)return;const le=ke=>{const Oe=ke.target;Oe.closest(".t-dialog")===null&&N.current&&!N.current.contains(Oe)&&B.current&&!B.current.contains(Oe)&&u(!1)},me=setTimeout(()=>{document.addEventListener("mousedown",le)},100);return()=>{clearTimeout(me),document.removeEventListener("mousedown",le)}},[c]);const oe=b.useCallback(()=>{i(le=>{const me=!le;return t==null||t(me),me})},[t]),J=b.useCallback(()=>{i(!1),t==null||t(!1)},[t]),ae=b.useCallback(async()=>{Kt.track("chat_session_create");const le=await ar.createSession();s(me=>[le,...me]),l(le.id),u(!1),F(),C(void 0)},[F]),Q=b.useCallback(()=>{u(le=>!le)},[]),se=b.useCallback(async le=>{Kt.track("chat_session_select"),l(le),u(!1),F(),C(void 0);try{const me=await ar.getMessages(le),ke=new Map;for(const De of me)De.workflow&&ke.set(De.id,De.workflow);D.current=ke,I(ke);const Oe=me.find(De=>De.workflow&&De.status===Ho.STREAMING);P.current=(Oe==null?void 0:Oe.id)||null}catch(me){console.error("[ChatDrawer] Failed to load workflow messages:",me),F()}},[F]),ie=b.useCallback(async le=>{Kt.track("chat_session_delete"),await ar.deleteSession(le),s(me=>{const ke=me.filter(Oe=>Oe.id!==le);if(a===le){const Oe=ke[0]||null;l((Oe==null?void 0:Oe.id)||null),F()}return ke})},[a,F]),ce=b.useCallback(async(le,me)=>{Kt.track("chat_session_rename"),await ar.updateSession(le,{title:me}),s(ke=>ke.map(Oe=>Oe.id===le?{...Oe,title:me}:Oe))},[]),ge=X.useRef(null),Se=b.useCallback(async le=>{try{Kt.track("chat_message_send",{hasImages:le.parts.some(ke=>ke.type==="image_url")}),Kt.track("ai_modality_used",{modality:"agent",action:"message_send",source:"chat_drawer",hasImages:le.parts.some(ke=>ke.type==="image_url"),partCount:le.parts.length,textLength:le.parts.filter(ke=>ke.type==="text").reduce((ke,Oe)=>ke+String(Oe.text||"").length,0)});const me=ci.get();if(!(me!=null&&me.apiKey)){ge.current=le,$({...O,openSettings:!0});return}if(ge.current=null,!a){const ke=await ar.createSession();s(Oe=>[ke,...Oe]),l(ke.id),ge.current=le;return}await K.sendMessage(le)}catch(me){console.error("[ChatDrawer] send message failed:",me),ge.current=le}},[a,K,O,$]),Ae=b.useCallback(async le=>{var Ur,ho;const{context:me,workflow:ke,textModel:Oe,autoOpen:De=!0,appendToCurrentSession:Ye}=le;De&&(i(!0),t==null||t(!0)),Oe&&C(Oe);const Rt=Bst(a,Ye),St=[];me.userInstruction&&St.push(me.userInstruction),me.selection.texts.length>0&&St.push(`
|
|
2963
|
+
`)||`已完成任务: ${e.name}`,next:i};return JSON.stringify(o)}function kst(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===Pa.USER?"user":"assistant",parts:t}}function Tst(e,t){const r=e.parts.filter(s=>s.type==="text").map(s=>s.text).join(""),o=e.parts.filter(s=>s.type==="data-file").map((s,a)=>{const l=s.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"?Pa.USER:Pa.ASSISTANT,content:r,timestamp:Date.now(),status:Ho.SUCCESS,attachments:o.length>0?o:void 0}}function Dst(e){return e.workflow&&e.content.startsWith(cO)?{...e,content:Pst(e.workflow)}:e}function lG(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("")}Aot();function Mst(e){const{sessionId:t,temporaryModel:n,onToolCalls:r,onWorkflowUpdate:i}=e,o=b.useRef(sle()),s=b.useRef(r);s.current=r;const a=b.useRef(i);a.current=i;const l=b.useRef(n);l.current=n;const[c,u]=b.useState([]),[d,f]=b.useState("ready"),[p,y]=b.useState(!1),v=b.useRef(null),w=b.useRef([]),C=b.useRef(!1);b.useEffect(()=>{if(!t){u([]),w.current=[];return}(async()=>{y(!0);try{const R=await ar.getMessages(t);w.current=R,u(R.map(kst))}catch(R){console.error("[useChatHandler] Failed to load messages:",R),u([]),w.current=[]}finally{y(!1)}})()},[t]);const x=b.useCallback(async k=>{if(!t)return;if(C.current){console.warn("[useChatHandler] Message already being sent, ignoring duplicate call");return}C.current=!0,f("submitted");const R=Tst(k,t);await ar.addMessage(R),u(N=>[...N,k]);const T=await ar.getSession(t);await ar.updateSession(t,{updatedAt:Date.now(),messageCount:((T==null?void 0:T.messageCount)||0)+1});const M=ar.generateId();v.current=M;const F={id:M,role:"assistant",parts:[{type:"text",text:""}]};u(N=>[...N,F]),f("streaming");const V=w.current.map(Dst);V.push(R),w.current=[...w.current,R];const H=lG(k);let j="",z=!1;try{await aG.sendChatMessage(V.slice(0,-1),H,R.attachments||[],N=>{if(N.type==="content"&&N.content)j=N.content,u(B=>B.map(O=>O.id===M?{...O,parts:[{type:"text",text:j}]}:O));else if(N.type==="done"){const B=zO(j),O=UO(j)||j;if(B.length>0&&s.current){const U=B.map(Z=>Ast(Z)),Y=async()=>{const Z=[];for(const oe of U)try{const J=await oN.executeTool(oe);Z.push({toolCall:oe,success:J.success,data:J.data,error:J.error,taskId:J.taskId})}catch(J){Z.push({toolCall:oe,success:!1,error:J.message||"工具执行失败"})}return Z},K=`${cO}${M}`;u(Z=>Z.map(oe=>oe.id===M?{...oe,parts:[{type:"text",text:K}]}:oe)),s.current(U,M,Y,O)}f("ready");const $={id:M,sessionId:t,role:Pa.ASSISTANT,content:B.length>0?`${cO}${M}`:j,timestamp:Date.now(),status:B.length>0?Ho.STREAMING:Ho.SUCCESS};ar.addMessage($),w.current=[...w.current,$],ar.updateSession(t,{updatedAt:Date.now(),messageCount:((T==null?void 0:T.messageCount)||0)+2}),v.current=null,C.current=!1}else if(N.type==="error"&&N.error){z=!0,f("error");const B=`❌ 错误: ${N.error}`;u($=>$.map(U=>U.id===M?{...U,parts:[{type:"text",text:B}]}:U));const O={id:M,sessionId:t,role:Pa.ASSISTANT,content:B,timestamp:Date.now(),status:Ho.FAILED,error:N.error};ar.addMessage(O),w.current=[...w.current,O],v.current=null,C.current=!1}},l.current,o.current)}catch(N){if(N.message!=="Request cancelled"&&!z){f("error"),console.error("[useChatHandler] Stream error:",N);const B=`❌ 错误: ${N.message||"未知错误"}`;if(u(O=>O.map($=>$.id===M?{...$,parts:[{type:"text",text:B}]}:$)),t&&M){const O={id:M,sessionId:t,role:Pa.ASSISTANT,content:B,timestamp:Date.now(),status:Ho.FAILED,error:N.message||"未知错误"};ar.addMessage(O),w.current=[...w.current,O]}}v.current=null,C.current=!1}},[t]),E=b.useCallback(async()=>{if(aG.stopGeneration(),f("ready"),v.current&&t){const k=c.find(R=>R.id===v.current);if(k){const R=lG(k),T={id:k.id,sessionId:t,role:Pa.ASSISTANT,content:R,timestamp:Date.now(),status:Ho.SUCCESS};await ar.addMessage(T)}v.current=null}},[t,c]),_=b.useCallback(k=>{if(c.length<2)return;const R=[...c].reverse().findIndex(V=>V.role==="user");if(R===-1)return;const T=c.length-1-R,M=c[T],F=c.slice(0,T+1);u(F),x(M)},[c,x]),I=b.useCallback((k,R)=>{u(k),R&&(w.current=R)},[]),D=b.useCallback((k,R)=>{u(T=>[...T,...k]),R&&(w.current=[...w.current,...R])},[]),P=b.useCallback((k,R)=>{w.current=w.current.map(T=>T.id===k?{...T,workflow:R}:T)},[]);return{messages:c,status:d,sendMessage:x,stop:E,regenerate:_,setMessages:u,setMessagesWithRaw:I,appendMessagesWithRaw:D,updateRawMessageWorkflow:P,isLoading:p}}function Ost(e){return typeof e=="object"&&e!==null}function cG(e){if(e.error)return e.error.message||e.error.code||"任务执行失败"}function Rst(e,t){return{...Ost(e)?{...e}:{},taskId:t.id,result:t.result}}function Nst(e){const t=e.filter(o=>o.status==="failed").length,n=e.filter(o=>o.status==="running").length,r=e.filter(o=>o.status==="pending").length,i=e.filter(o=>o.status==="completed").length;return t>0?"failed":n>0?"running":r===0&&i>0?"completed":"pending"}function jst(e){return e.length>0&&e.every(t=>t.status==="completed")}function Lst(e,t){const n=Fot(e,t);if(!n)return null;const r=e.steps.map(l=>{if(l.id!==n.id)return l;switch(t.status){case un.PENDING:case un.PROCESSING:return l.status==="completed"?{...l,result:f2(l.result,t.id)}:{...l,status:"running",result:f2(l.result,t.id),error:void 0};case un.COMPLETED:return{...l,status:"completed",result:Rst(l.result,t),error:void 0};case un.FAILED:return{...l,status:"failed",result:f2(l.result,t.id),error:cG(t)};case un.CANCELLED:return{...l,status:"skipped",result:f2(l.result,t.id),error:cG(t)};default:return l}}),i=jst(r),o=Nst(r),s=e.generationType==="image"&&i,a=e.generationType==="image"&&t.status!==un.COMPLETED&&e.postProcessingStatus!=="completed";return{...e,status:o,steps:r,error:o==="failed"?e.error:void 0,postProcessingStatus:s?"completed":a?void 0:e.postProcessingStatus}}function Bst(e,t){return t&&e?{mode:"append",sessionId:e}:{mode:"create"}}const Fst=X.lazy(()=>xn(()=>Promise.resolve().then(()=>nat),void 0,import.meta.url)),uG="[[WORKFLOW_MESSAGE]]";function $st(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_audio":return`生成音频: ${((t==null?void 0:t.prompt)||"").substring(0,30)}...`;case"generate_text":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 dG="chat-drawer-width",zst=Math.max(375,window.innerWidth*.5),fG=375;function Ust(e){switch(e.status){case"completed":return Ho.SUCCESS;case"failed":case"cancelled":return Ho.FAILED;default:return Ho.STREAMING}}const aue=b.forwardRef(({defaultOpen:e=!1,onOpenChange:t},n)=>{const[r,i]=b.useState(()=>ar.getDrawerState().isOpen??e),[o,s]=b.useState([]),[a,l]=b.useState(null),[c,u]=b.useState(!1),[d,f]=b.useState(()=>{const le=localStorage.getItem(dG);if(le){const me=parseInt(le,10);if(!isNaN(me)&&me>=fG)return Math.min(me,window.innerWidth-60)}return zst}),[p,y]=b.useState(!1),v=b.useRef(null),[w,C]=b.useState(()=>so("text").modelId),[x,E]=b.useState(()=>{const le=so("text");return qn(le.profileId,le.modelId)}),[_,I]=b.useState(new Map),D=b.useRef(_),P=b.useRef(null),[k,R]=b.useState(null),[T,M]=b.useState(null),F=b.useCallback(()=>{const le=new Map;D.current=le,I(le),P.current=null,M(null)},[]),{executeRetry:V,selectedContent:H,setIsDrawerOpen:j,setDrawerWidth:z}=vle();b.useEffect(()=>{j(r)},[r,j]),b.useEffect(()=>{z(d)},[d,z]);const N=X.useRef(null),B=X.useRef(null),{appState:O,setAppState:$}=cy();b.useEffect(()=>{if(!p)return;const le=ke=>{const Oe=window.innerWidth-ke.clientX,De=Math.max(fG,Math.min(Oe,window.innerWidth-60));f(De)},me=()=>{y(!1),localStorage.setItem(dG,String(d))};return document.addEventListener("mousemove",le),document.addEventListener("mouseup",me),document.body.style.userSelect="none",document.body.style.cursor="ew-resize",()=>{document.removeEventListener("mousemove",le),document.removeEventListener("mouseup",me),document.body.style.userSelect="",document.body.style.cursor=""}},[p,d]),b.useEffect(()=>{const le=()=>{const me=window.innerWidth-60;d>me&&f(me)};return window.addEventListener("resize",le),()=>window.removeEventListener("resize",le)},[d]);const U=b.useCallback(le=>{le.preventDefault(),y(!0)},[]),Y=b.useCallback(async(le,me,ke,Oe)=>{var Rt,St;const Ye={id:`workflow-${Date.now()}`,name:"AI 智能生成",generationType:(Rt=le[0])!=null&&Rt.name.includes("video")?"video":(St=le[0])!=null&&St.name.includes("audio")?"audio":"image",prompt:Oe||"",aiAnalysis:Oe,count:le.length,steps:le.map((Ct,Dt)=>({id:`step-${Dt}`,mcp:Ct.name,status:"pending",description:$st(Ct.name,Ct.arguments),args:Ct.arguments}))};I(Ct=>{const Dt=new Map(Ct);return Dt.set(me,Ye),Dt}),P.current=me,ar.updateMessage(me,{workflow:Ye});try{const Ct=await ke();Kt.track("chat_tool_execution_complete",{success:!0,resultCount:Ct.length}),Kt.track("ai_modality_used",{modality:"agent",action:"tool_execution_completed",source:"chat_drawer",success:!0,toolCount:le.length,resultCount:Ct.length}),I(Dt=>{const Gt=new Map(Dt),Ft=Gt.get(me);if(Ft){const Ne={...Ft,steps:Ft.steps.map((gt,nn)=>{const Zt=Ct[nn];return{...gt,status:Zt!=null&&Zt.success?"completed":"failed",error:Zt==null?void 0:Zt.error,result:Zt==null?void 0:Zt.data}})};Gt.set(me,Ne),ar.updateMessage(me,{workflow:Ne,status:Ho.SUCCESS})}return Gt})}catch(Ct){console.error("[ChatDrawer] Tool execution failed:",Ct),I(Dt=>{const Gt=new Map(Dt),Ft=Gt.get(me);if(Ft){const Ne={...Ft,steps:Ft.steps.map(gt=>({...gt,status:"failed",error:Ct.message||"执行失败"}))};Gt.set(me,Ne),ar.updateMessage(me,{workflow:Ne,status:Ho.FAILED})}return Gt})}},[]),K=Mst({sessionId:a,temporaryModel:x||w,onToolCalls:Y});b.useEffect(()=>{D.current=_},[_]);const Z=b.useRef(K.sendMessage);Z.current=K.sendMessage,b.useEffect(()=>{(async()=>{const me=ar.getDrawerState(),ke=await ar.getAllSessions();s(ke);let Oe=null;if(me.activeSessionId?(Oe=me.activeSessionId,l(me.activeSessionId)):ke.length>0&&(Oe=ke[0].id,l(ke[0].id)),Oe)try{const De=await ar.getMessages(Oe),Ye=new Map;for(const St of De)St.workflow&&Ye.set(St.id,St.workflow);D.current=Ye,I(Ye);const Rt=De.find(St=>St.workflow&&St.status===Ho.STREAMING);P.current=(Rt==null?void 0:Rt.id)||null}catch(De){console.error("[ChatDrawer] Failed to load workflow messages:",De)}})()},[]),b.useEffect(()=>{ar.setDrawerState({isOpen:r,activeSessionId:a})},[r,a]),b.useEffect(()=>{if(a&&ge.current){const le=ge.current;ge.current=null,setTimeout(()=>{Z.current(le)},100)}},[a]),b.useEffect(()=>{if(!O.openSettings&&ge.current){const le=ci.get();if(le!=null&&le.apiKey){const me=ge.current;ge.current=null,a?setTimeout(()=>{Z.current(me)},100):(async()=>{const ke=await ar.createSession();s(Oe=>[ke,...Oe]),l(ke.id),ge.current=me})()}}},[O.openSettings,a]),b.useEffect(()=>{const le=me=>{me.key==="Escape"&&r&&(i(!1),t==null||t(!1))};return window.addEventListener("keydown",le),()=>window.removeEventListener("keydown",le)},[r,t]),b.useEffect(()=>{let le=null;return(async()=>{const{workflowSubmissionService:ke}=await xn(async()=>{const{workflowSubmissionService:Oe}=await import("./workflow-submission-service-BqiL_5Cj.js").then(De=>De.a);return{workflowSubmissionService:Oe}},__vite__mapDeps([0]),import.meta.url);le=ke.subscribeToAllEvents(Oe=>{const De=Oe;I(Ye=>{let Rt=null;for(const[Gt,Ft]of Ye.entries())if(Ft.id===De.workflowId){Rt=Gt;break}if(!Rt)return Ye;const St=Ye.get(Rt);if(!St)return Ye;const Ct=new Map(Ye);let Dt;switch(De.type){case"step":{Dt={...St,steps:St.steps.map(Gt=>Gt.id===De.stepId?{...Gt,status:De.status||Gt.status,result:De.result??Gt.result,error:De.error??Gt.error}:Gt)};break}case"steps_added":{const Ft=(De.steps||[]).map(Ne=>({id:Ne.id,mcp:Ne.mcp,args:Ne.args,description:Ne.description,status:Ne.status}));Dt={...St,steps:[...St.steps,...Ft]};break}case"completed":case"failed":{const Gt=De.type==="completed"?"completed":"failed";Dt={...St,status:Gt,steps:St.steps.map(Ft=>{if(Ft.status==="running"||Ft.status==="pending"){const Ne=Ft.result;return Ne!=null&&Ne.taskId?Ft:{...Ft,status:Gt,error:De.type==="failed"?De.error:void 0}}return Ft})};break}default:return Ye}return Ct.set(Rt,Dt),ar.updateMessage(Rt,{workflow:Dt}),Ct})})})().catch(ke=>{console.error("[ChatDrawer] Failed to setup workflow sync:",ke)}),()=>{le==null||le.unsubscribe()}},[]),b.useEffect(()=>{if(!c)return;const le=ke=>{const Oe=ke.target;Oe.closest(".t-dialog")===null&&N.current&&!N.current.contains(Oe)&&B.current&&!B.current.contains(Oe)&&u(!1)},me=setTimeout(()=>{document.addEventListener("mousedown",le)},100);return()=>{clearTimeout(me),document.removeEventListener("mousedown",le)}},[c]);const oe=b.useCallback(()=>{i(le=>{const me=!le;return t==null||t(me),me})},[t]),J=b.useCallback(()=>{i(!1),t==null||t(!1)},[t]),ae=b.useCallback(async()=>{Kt.track("chat_session_create");const le=await ar.createSession();s(me=>[le,...me]),l(le.id),u(!1),F(),C(void 0)},[F]),Q=b.useCallback(()=>{u(le=>!le)},[]),se=b.useCallback(async le=>{Kt.track("chat_session_select"),l(le),u(!1),F(),C(void 0);try{const me=await ar.getMessages(le),ke=new Map;for(const De of me)De.workflow&&ke.set(De.id,De.workflow);D.current=ke,I(ke);const Oe=me.find(De=>De.workflow&&De.status===Ho.STREAMING);P.current=(Oe==null?void 0:Oe.id)||null}catch(me){console.error("[ChatDrawer] Failed to load workflow messages:",me),F()}},[F]),ie=b.useCallback(async le=>{Kt.track("chat_session_delete"),await ar.deleteSession(le),s(me=>{const ke=me.filter(Oe=>Oe.id!==le);if(a===le){const Oe=ke[0]||null;l((Oe==null?void 0:Oe.id)||null),F()}return ke})},[a,F]),ce=b.useCallback(async(le,me)=>{Kt.track("chat_session_rename"),await ar.updateSession(le,{title:me}),s(ke=>ke.map(Oe=>Oe.id===le?{...Oe,title:me}:Oe))},[]),ge=X.useRef(null),Se=b.useCallback(async le=>{try{Kt.track("chat_message_send",{hasImages:le.parts.some(ke=>ke.type==="image_url")}),Kt.track("ai_modality_used",{modality:"agent",action:"message_send",source:"chat_drawer",hasImages:le.parts.some(ke=>ke.type==="image_url"),partCount:le.parts.length,textLength:le.parts.filter(ke=>ke.type==="text").reduce((ke,Oe)=>ke+String(Oe.text||"").length,0)});const me=ci.get();if(!(me!=null&&me.apiKey)){ge.current=le,$({...O,openSettings:!0});return}if(ge.current=null,!a){const ke=await ar.createSession();s(Oe=>[ke,...Oe]),l(ke.id),ge.current=le;return}await K.sendMessage(le)}catch(me){console.error("[ChatDrawer] send message failed:",me),ge.current=le}},[a,K,O,$]),Ae=b.useCallback(async le=>{var Ur,ho;const{context:me,workflow:ke,textModel:Oe,autoOpen:De=!0,appendToCurrentSession:Ye}=le;De&&(i(!0),t==null||t(!0)),Oe&&C(Oe);const Rt=Bst(a,Ye),St=[];me.userInstruction&&St.push(me.userInstruction),me.selection.texts.length>0&&St.push(`
|
|
2964
2964
|
📝 选中的文本:
|
|
2965
2965
|
${me.selection.texts.join(`
|
|
2966
2966
|
`)}`),me.selection.texts.length===0&&!me.userInstruction&&me.finalPrompt&&St.push(`
|
|
@@ -2974,4 +2974,4 @@ ${Ct.join(" • ")}`);const Gt=St.join(`
|
|
|
2974
2974
|
---
|
|
2975
2975
|
`);v=k[0],k[1].split(" • ").forEach(T=>{const M=T.replace(/模型:\s*/,"").replace(/数量:\s*/,"").replace(/尺寸:\s*/,"").trim();if(M){let F=g.jsx(A2,{size:"12px"});T.includes("数量")&&(F=g.jsx(av,{size:"12px"})),T.includes("尺寸")&&(F=g.jsx(YT,{size:"12px"})),w.push({label:M,icon:F})}})}else{const k=v.split(`
|
|
2976
2976
|
`),R=[];for(const T of k){const M=T.trim();if(M.startsWith("模型:")||M.startsWith("数量:")||M.startsWith("提示词:")){const F=M.replace(/.*:\s*/,"").trim();let V=g.jsx(A2,{size:"12px"});M.includes("数量")&&(V=g.jsx(av,{size:"12px"})),w.push({label:F,icon:V})}else M.startsWith("📝 选中的文本:")?w.push({label:M.replace("📝 ","").trim(),icon:g.jsx(qT,{size:"12px"})}):M&&!M.startsWith("💬 用户指令:")&&R.push(T)}v=R.join(`
|
|
2977
|
-
`).trim()}if(!v&&w.length>0){const k=f.match(/💬 用户指令:\s*([\s\S]*?)(?=\n模型:|\n数量:|$)/);k&&k[1].trim()&&(v=k[1].trim())}return{text:v||f,meta:w,images:p}},[e.parts,e.aiContext]),a=b.useCallback(f=>{f.stopPropagation()},[]),l=b.useCallback(f=>{if((f.ctrlKey||f.metaKey)&&f.key==="c"){const y=window.getSelection(),v=y==null?void 0:y.toString();v&&(aE(v).catch(w=>{console.error("Failed to copy text:",w)}),f.stopPropagation())}},[]);b.useEffect(()=>{const f=r.current;if(f)return f.addEventListener("pointerdown",a),f.addEventListener("pointerup",a),f.addEventListener("mousedown",a),f.addEventListener("mouseup",a),f.addEventListener("click",a),f.addEventListener("keydown",l),()=>{f.removeEventListener("pointerdown",a),f.removeEventListener("pointerup",a),f.removeEventListener("mousedown",a),f.removeEventListener("mouseup",a),f.removeEventListener("click",a),f.removeEventListener("keydown",l)}},[a,l]);const c=s.length===0&&(!o||o.length===0),u=b.useMemo(()=>s.map((f,p)=>({id:`${e.id||"user"}-image-${p}`,url:f.url,type:"image",alt:f.filename})),[s,e.id]),d=b.useCallback((f,p)=>{p==null||p.stopPropagation(),n==null||n(u,f)},[n,u]);return g.jsx(g.Fragment,{children:g.jsxs("div",{className:`user-bubble chat-message chat-message--user ${c?"user-bubble--text-only":""} ${t}`,children:[g.jsx("div",{className:"chat-message-avatar",children:g.jsx("span",{children:"👤"})}),g.jsxs("div",{className:"user-bubble__content chat-message-content",children:[s.length>0&&g.jsx("div",{className:`user-bubble__images user-bubble__images--${Math.min(s.length,4)}`,children:s.map((f,p)=>g.jsx("div",{className:"user-bubble__image-wrapper",onClick:y=>d(p,y),children:g.jsx("img",{src:f.url,alt:f.filename,className:"user-bubble__image",loading:"lazy",draggable:!1})},p))}),i&&g.jsx("div",{ref:r,className:"user-bubble__text user-bubble__text--selectable",children:i}),o&&o.length>0&&g.jsx("div",{className:"user-bubble__meta-tags",children:o.map((f,p)=>g.jsxs("div",{className:"user-bubble__meta-tag",children:[g.jsx("span",{className:"user-bubble__meta-icon",children:f.icon}),g.jsx("span",{className:"user-bubble__meta-label",children:f.label})]},p))})]})]})})},hG="[[WORKFLOW_MESSAGE]]",pG=({handler:e,workflowMessages:t,retryingWorkflowId:n,handleWorkflowReply:r,handleWorkflowRetry:i,className:o="chat-section"})=>{const[s,a]=b.useState(!1),[l,c]=b.useState([]),[u,d]=b.useState(0),f=b.useCallback(x=>{const E=x.parts.find(_=>_.type==="text");if(E&&"text"in E){const _=E.text;if(_.startsWith(hG))return _.replace(hG,"")}return null},[]),p=b.useCallback(x=>x.parts.some(E=>E.type==="data-file"),[]),y=b.useCallback(x=>{let E=null,_=null;for(const I of x.parts)if(I.type==="text"){if(E===null){E=I.text;continue}_||(_=[E]),_.push(I.text)}return _?_.join(""):E??""},[]),v=b.useCallback((x,E)=>{x.length!==0&&(c(x),d(E),a(!0))},[]),w=e.status==="submitted"||e.status==="streaming",C=e.messages.length===0&&!w;return g.jsxs("div",{className:o,children:[g.jsx("div",{className:"chat-messages",children:g.jsxs("div",{className:"chat-messages-list",children:[e.messages.map((x,E)=>{const _=f(x);if(_){const P=t.get(_);if(P)return g.jsx(eat,{workflow:P,onRetry:k=>i(_,P,k),onReply:r?()=>r(_,P):void 0,isRetrying:n===_},x.id)}const I=x.parts.some(P=>P.type==="text"&&"text"in P&&typeof P.text=="string"&&P.text.startsWith("❌ 错误")),D=`chat-message chat-message--${x.role} ${I?"chat-message--error":""}`;return x.role==="user"&&p(x)?g.jsx(tat,{message:x,onPreviewImages:v},x.id):g.jsxs("div",{className:D,"data-message-id":x.id,"data-message-last":E===e.messages.length-1,children:[g.jsx("div",{className:"chat-message-avatar",children:g.jsx("span",{children:x.role==="user"?"👤":"🤖"})}),g.jsx("div",{className:"chat-message-content",children:g.jsx(tN,{markdown:y(x),className:"chat-markdown"})}),x.role==="assistant"&&!I&&g.jsx("div",{className:"chat-message-actions"})]},x.id)}),w&&g.jsxs("div",{className:"chat-loading",children:[g.jsx("div",{className:"chat-loading__spinner"}),g.jsx("span",{children:"思考中..."})]}),C&&g.jsxs("div",{className:"chat-empty",children:[g.jsx("h3",{children:"开始对话"}),g.jsx("p",{children:"输入消息与AI助手交流"})]})]})}),g.jsx(Hg,{visible:s,items:l,initialIndex:u,onClose:()=>a(!1),showThumbnails:l.length>1,videoAutoPlay:!0})]})},nat=Object.freeze(Object.defineProperty({__proto__:null,ChatMessagesArea:pG,default:pG},Symbol.toStringTag,{value:"Module"}));function rat(e){let t=e;return t=t.replace(/\[([^\]]*[:\,\=\(\)\|\/\\][^\]]*)\]/g,(n,r)=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?n:`["${r}"]`),t=t.replace(/\(([^\)]*[:\,\=\[\]\|\/\\][^\)]*)\)/g,(n,r)=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?n:`("${r}")`),t=t.replace(/\{([^\}]*[:\,\=\[\]\(\)\|\/\\][^\}]*)\}/g,(n,r)=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?n:`{"${r}"}`),t}const iat=({code:e,className:t=""})=>{const n=b.useRef(null),[r,i]=b.useState(null),[o,s]=b.useState(!0),[a,l]=b.useState(""),[c,u]=b.useState(!1),[d,f]=b.useState("");if(b.useEffect(()=>{let y=!1;return(async()=>{if(!(!n.current||!e))try{s(!0),i(null);const w=rat(e);l(w);const C=(await xn(async()=>{const{default:_}=await import("./diagram-engines-BjFHXhwN.js").then(I=>I.a);return{default:_}},[],import.meta.url)).default;C.initialize({startOnLoad:!1,theme:"default",securityLevel:"loose",fontFamily:"Inter, SF Pro Display, -apple-system, sans-serif"});const x=`mermaid-${Math.random().toString(36).substr(2,9)}`,{svg:E}=await C.render(x,w);!y&&n.current&&(n.current.innerHTML=E,f(E),s(!1))}catch(w){console.error("[MermaidRenderer] Failed to render:",w),y||(i(w.message||"Failed to render diagram"),s(!1))}})(),()=>{y=!0}},[e]),r){const y=a&&a!==e;return g.jsx("div",{className:`mermaid-renderer mermaid-renderer--error ${t}`,children:g.jsxs("div",{className:"mermaid-renderer__error",children:[g.jsx("strong",{children:"Mermaid渲染错误:"}),g.jsx("pre",{children:r}),g.jsxs("details",{children:[g.jsx("summary",{children:"查看原始代码"}),g.jsx("pre",{children:e})]}),y&&g.jsxs("details",{children:[g.jsx("summary",{children:"查看预处理后的代码(已自动添加引号)"}),g.jsx("pre",{children:a})]})]})})}const p=()=>{!o&&d&&u(!0)};return g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:`mermaid-renderer ${t}`,children:[o&&g.jsx("div",{className:"mermaid-renderer__loading",children:"渲染中..."}),g.jsx(cn,{content:"点击查看大图",showArrow:!1,children:g.jsx("div",{ref:n,className:"mermaid-renderer__container",style:{display:o?"none":"block"},onClick:p})}),!o&&d&&g.jsxs("div",{className:"mermaid-renderer__hint",children:[g.jsx(oZ,{size:16}),g.jsx("span",{children:"点击查看大图"})]})]}),g.jsx(NR,{visible:c,onClose:()=>u(!1),header:"Mermaid 图表",width:"90vw",className:"mermaid-preview-dialog",footer:null,closeBtn:g.jsx(Bd,{}),children:g.jsx("div",{className:"mermaid-preview-content",dangerouslySetInnerHTML:{__html:d}})})]})},oat=Object.freeze(Object.defineProperty({__proto__:null,MermaidRenderer:iat},Symbol.toStringTag,{value:"Module"}));export{Ie as $,PX as A,Cct as B,bct as C,xct as D,pct as E,gE as F,hct as G,VX as H,_Be as I,CBe as J,IBe as K,Qg as L,EBe as M,SBe as N,mct as O,b as P,Mi as Q,X as R,er as S,un as T,uy as U,xt as V,he as W,Qo as X,wn as Y,Ot as Z,kr as _,wE as a,iZe as a$,jt as a0,$r as a1,fn as a2,Wf as a3,Sm as a4,zo as a5,Kut as a6,bH as a7,g as a8,Hut as a9,BYe as aA,fr as aB,O0 as aC,Qt as aD,ci as aE,Lht as aF,El as aG,_Je as aH,CJe as aI,EJe as aJ,KJe as aK,lle as aL,Lh as aM,uu as aN,uh as aO,fu as aP,fh as aQ,rE as aR,hr as aS,F5 as aT,QJe as aU,G5 as aV,rp as aW,K5 as aX,J0 as aY,tZe as aZ,rZe as a_,Je as aa,cn as ab,Ghe as ac,Mve as ad,jat as ae,wq as af,Ove as ag,Lat as ah,Bat as ai,uXe as aj,Et as ak,mdt as al,FG as am,npe as an,tn as ao,bq as ap,uZe as aq,Dl as ar,uo as as,q as at,cdt as au,hc as av,FYe as aw,adt as ax,sdt as ay,LYe as az,zr as b,am as b$,Ba as b0,lI as b1,X5 as b2,Y5 as b3,Iae as b4,J5 as b5,Pae as b6,WM as b7,ii as b8,M1 as b9,RLe as bA,Ght as bB,Vht as bC,CQe as bD,Ilt as bE,clt as bF,vlt as bG,cht as bH,hlt as bI,lht as bJ,RT as bK,hht as bL,iR as bM,ufe as bN,Bh as bO,Kt as bP,qde as bQ,_u as bR,wy as bS,ti as bT,Ew as bU,RUe as bV,fw as bW,gc as bX,NUe as bY,hZe as bZ,B1 as b_,O1 as ba,Z5 as bb,Tae as bc,ne as bd,Il as be,Nl as bf,An as bg,_n as bh,Ig as bi,Qe as bj,ir as bk,$i as bl,Ks as bm,rS as bn,Qc as bo,Pn as bp,Pe as bq,hee as br,za as bs,sI as bt,Vhe as bu,RG as bv,NG as bw,Nht as bx,Hht as by,Wht as bz,o_e as c,Cd as c$,Ca as c0,xs as c1,mlt as c2,aR as c3,Uv as c4,aN as c5,xr as c6,gs as c7,So as c8,n2 as c9,ic as cA,g2 as cB,ble as cC,Yht as cD,Xht as cE,vv as cF,wle as cG,yS as cH,$lt as cI,SY as cJ,sN as cK,SQe as cL,iV as cM,hl as cN,ln as cO,Jht as cP,Fht as cQ,zht as cR,$ht as cS,Uht as cT,Tv as cU,Ylt as cV,Xlt as cW,Elt as cX,Zht as cY,Mlt as cZ,Xtt as c_,et as ca,R_ as cb,W4 as cc,sg as cd,qfe as ce,aGe as cf,Odt as cg,L_ as ch,sGe as ci,Mdt as cj,Dw as ck,qut as cl,nN as cm,Fct as cn,Ei as co,$Oe as cp,UOe as cq,Bd as cr,Nhe as cs,qM as ct,oV as cu,W3 as cv,vS as cw,eg as cx,ov as cy,O8 as cz,gct as d,_ft as d$,sR as d0,NR as d1,Qht as d2,qlt as d3,Wlt as d4,Vlt as d5,Plt as d6,T1 as d7,bat as d8,vT as d9,Gse as dA,hYe as dB,MLe as dC,ru as dD,tct as dE,VOe as dF,eZ as dG,Zlt as dH,qct as dI,cae as dJ,ydt as dK,bdt as dL,xdt as dM,wdt as dN,Ir as dO,Jm as dP,gUe as dQ,m1 as dR,aEe as dS,lEe as dT,Ui as dU,Eu as dV,Kdt as dW,Rft as dX,tft as dY,jft as dZ,Sqe as d_,cS as da,yL as db,Wrt as dc,yn as dd,QC as de,Sd as df,Kme as dg,Rd as dh,gS as di,r8 as dj,B1e as dk,Lq as dl,jq as dm,sxe as dn,axe as dp,xat as dq,wat as dr,ixe as ds,hm as dt,Pce as du,zw as dv,a$e as dw,j5 as dx,Nae as dy,Rae as dz,pg as e,Ynt as e$,Ift as e0,Aft as e1,Pft as e2,Bn as e3,Vs as e4,yo as e5,As as e6,zct as e7,J1 as e8,OM as e9,$w as eA,Nd as eB,Rqe as eC,J_ as eD,MM as eE,L5 as eF,R5 as eG,gYe as eH,V5 as eI,rZ as eJ,tOe as eK,av as eL,Hv as eM,nZ as eN,fYe as eO,OLe as eP,Dse as eQ,GKe as eR,vxe as eS,ss as eT,uZ as eU,Ult as eV,kSe as eW,lZ as eX,ty as eY,Xft as eZ,Qat as e_,_qe as ea,rs as eb,z5 as ec,pae as ed,U5 as ee,TXe as ef,Gn as eg,uae as eh,np as ei,Q_ as ej,aae as ek,cy as el,mce as em,Dm as en,so as eo,TQe as ep,H3 as eq,tI as er,kqe as es,qn as et,Bse as eu,Lse as ev,$C as ew,GV as ex,KM as ey,T5 as ez,yct as f,apt as f$,Gct as f0,ZT as f1,X3 as f2,hN as f3,JOe as f4,mft as f5,cI as f6,hrt as f7,_5 as f8,E5 as f9,fce as fA,Iet as fB,_et as fC,KC as fD,qC as fE,cr as fF,vo as fG,Uo as fH,z1 as fI,ai as fJ,pi as fK,nS as fL,yat as fM,opt as fN,Oet as fO,w_ as fP,Lne as fQ,n4 as fR,r4 as fS,spt as fT,lpt as fU,kle as fV,rpt as fW,ket as fX,tpt as fY,ipt as fZ,Pet as f_,I5 as fa,Fw as fb,$le as fc,sFe as fd,Nse as fe,sr as ff,JX as fg,QX as fh,TOe as fi,POe as fj,aOe as fk,SMe as fl,YT as fm,sRe as fn,XMe as fo,jOe as fp,kR as fq,cOe as fr,dOe as fs,ROe as ft,uht as fu,COe as fv,$ct as fw,Hct as fx,Xh as fy,vpt as fz,BIe as g,YJ as g$,Hn as g0,mpt as g1,f$e as g2,yw as g3,zve as g4,fpt as g5,ept as g6,npt as g7,dpt as g8,upt as g9,ule as gA,vf as gB,dce as gC,mat as gD,tS as gE,vhe as gF,Xct as gG,Hc as gH,spe as gI,Od as gJ,XJ as gK,ZJ as gL,cje as gM,Vje as gN,_d as gO,Wje as gP,VE as gQ,PQ as gR,TQ as gS,_je as gT,AD as gU,kje as gV,OQ as gW,kQ as gX,nje as gY,GJ as gZ,KJ as g_,cpt as ga,One as gb,_Qe as gc,IQe as gd,Uct as ge,IOe as gf,Kn as gg,AR as gh,qOe as gi,ont as gj,Rct as gk,xE as gl,VMe as gm,gOe as gn,Q1 as go,zMe as gp,HMe as gq,Wct as gr,_m as gs,On as gt,gi as gu,$qe as gv,Sae as gw,slt as gx,lg as gy,md as gz,$X as h,$at as h$,Yu as h0,fLe as h1,qJ as h2,HJ as h3,Aje as h4,VJ as h5,WJ as h6,rje as h7,fje as h8,hje as h9,iae as hA,oI as hB,TYe as hC,kYe as hD,mYe as hE,iYe as hF,VKe as hG,Mqe as hH,DYe as hI,rdt as hJ,idt as hK,bc as hL,Ha as hM,ms as hN,Go as hO,Tn as hP,UE as hQ,LUe as hR,Hm as hS,ta as hT,ndt as hU,Fat as hV,Vf as hW,sy as hX,$a as hY,SGe as hZ,zat as h_,dje as ha,aje as hb,kn as hc,LJ as hd,BJ as he,j3 as hf,Pje as hg,MQ as hh,Ije as hi,D2 as hj,kLe as hk,vLe as hl,gLe as hm,yLe as hn,TLe as ho,ALe as hp,mLe as hq,DLe as hr,PLe as hs,Gut as ht,Vut as hu,pLe as hv,jee as hw,c5 as hx,tdt as hy,edt as hz,hg as i,tQe as i$,Lr as i0,_Ze as i1,IZe as i2,Khe as i3,Dve as i4,rFe as i5,iFe as i6,oFe as i7,xft as i8,bft as i9,sft as iA,ift as iB,aft as iC,lft as iD,cft as iE,uft as iF,dft as iG,fft as iH,qft as iI,vft as iJ,wft as iK,Uft as iL,zft as iM,Gft as iN,gft as iO,NC as iP,Qdt as iQ,nft as iR,eft as iS,Ydt as iT,Oht as iU,qdt as iV,Kft as iW,Xdt as iX,Zdt as iY,Nct as iZ,Jdt as i_,yft as ia,Mft as ib,xJe as ic,Mht as id,oht as ie,dht as ig,Dht as ih,Wft as ii,fht as ij,Rr as ik,hft as il,Tft as im,Dft as io,pft as ip,Vh as iq,ldt as ir,uQ as is,mc as it,BG as iu,Lft as iv,Nft as iw,dn as ix,rft as iy,oft as iz,wct as j,Jut as j$,Ug as j0,Idt as j1,Cdt as j2,Mw as j3,Vd as j4,Rdt as j5,Un as j6,odt as j7,_w as j8,Adt as j9,F_ as jA,yc as jB,J4 as jC,Fg as jD,kh as jE,Fi as jF,wc as jG,jUe as jH,In as jI,Pl as jJ,gie as jK,om as jL,sm as jM,EZe as jN,Ua as jO,ny as jP,sH as jQ,Oae as jR,hdt as jS,fdt as jT,Hs as jU,l0e as jV,Kht as jW,_Ve as jX,Wut as jY,Zut as jZ,Rht as j_,Ddt as ja,Gd as jb,jZe as jc,OZe as jd,NZe as je,vdt as jf,ay as jg,kdt as jh,dXe as ji,Tdt as jj,Pdt as jk,Rie as jl,yre as jm,jYe as jn,vee as jo,Ag as jp,_o as jq,Zne as jr,a3 as js,Qs as jt,MQe as ju,Fse as jv,MOe as jw,qht as jx,b1 as jy,Ed as jz,Uh as k,jwe as k$,Vdt as k0,Wdt as k1,Xut as k2,vle as k3,CZe as k4,pYe as k5,Lae as k6,XK as k7,kat as k8,gdt as k9,fS as kA,JL as kB,e1e as kC,n1e as kD,r1e as kE,z0 as kF,YO as kG,Yve as kH,G1 as kI,Hat as kJ,Ip as kK,vl as kL,Vat as kM,Gat as kN,Kat as kO,JO as kP,$1e as kQ,z1e as kR,Zbe as kS,Jbe as kT,Qbe as kU,exe as kV,Awe as kW,Pwe as kX,swe as kY,awe as kZ,Nwe as k_,nXe as ka,jht as kb,bd as kc,whe as kd,bhe as ke,xhe as kf,She as kg,Che as kh,Ehe as ki,_he as kj,gat as kk,Pq as kl,Wat as km,dh as kn,jv as ko,zye as kp,Uye as kq,Cq as kr,Eq as ks,Uat as kt,_q as ku,Tat as kv,H1 as kw,o0e as kx,QK as ky,a0e as kz,Act as l,Sft as l$,Hwe as l0,Wwe as l1,Abe as l2,kbe as l3,rY as l4,Rbe as l5,Nbe as l6,Zwe as l7,Jwe as l8,obe as l9,cie as lA,Bhe as lB,_l as lC,Whe as lD,Lhe as lE,$he as lF,Fhe as lG,Kfe as lH,Yut as lI,lre as lJ,Ek as lK,Ao as lL,Tqe as lM,b6e as lN,Cft as lO,Eft as lP,Hhe as lQ,Uhe as lR,cat as lS,dat as lT,uat as lU,The as lV,sS as lW,wO as lX,wS as lY,Gfe as lZ,fat as l_,sbe as la,Bbe as lb,Fbe as lc,Ube as ld,Hbe as le,AK as lf,OO as lg,PK as lh,Bq as li,ca as lj,kge as lk,Wi as ll,Zb as lm,IK as ln,Pat as lo,rye as lp,BK as lq,FK as lr,RO as ls,NO as lt,YK as lu,Rye as lv,Nye as lw,jye as lx,_i as ly,Aw as lz,fR as m,aE as m$,sht as m0,aht as m1,sre as m2,Hft as m3,Bnt as m4,xHe as m5,SSe as m6,cg as m7,Dlt as m8,Qft as m9,TBe as mA,DBe as mB,MBe as mC,bYe as mD,yXe as mE,vXe as mF,CQ as mG,pdt as mH,kft as mI,nce as mJ,nct as mK,iht as mL,oR as mM,yY as mN,Zft as mO,Vft as mP,Klt as mQ,Yft as mR,Nlt as mS,fN as mT,FC as mU,rK as mV,Jft as mW,S3 as mX,Oft as mY,Hlt as mZ,hat as m_,eht as ma,tht as mb,nht as mc,rht as md,pht as me,mht as mf,ght as mg,yht as mh,vht as mi,wht as mj,bht as mk,xht as ml,Sht as mm,Cht as mn,Eht as mo,_ht as mp,Iht as mq,Aht as mr,Pht as ms,kht as mt,Tht as mu,PYe as mv,kXe as mw,olt as mx,Hdt as my,bte as mz,Dct as n,Mpt as n$,Sdt as n0,_dt as n1,llt as n2,Edt as n3,Bft as n4,Fft as n5,$ft as n6,ZXe as n7,Lp as n8,plt as n9,Jot as nA,Qot as nB,bge as nC,I$e as nD,S$e as nE,oN as nF,Pot as nG,xY as nH,Ept as nI,QV as nJ,kot as nK,Yrt as nL,Tot as nM,_pt as nN,uit as nO,hae as nP,zXe as nQ,Aot as nR,Bht as nS,xit as nT,Yct as nU,tpe as nV,iRe as nW,Hg as nX,wnt as nY,Rpt as nZ,oO as n_,ome as na,zn as nb,Cl as nc,Nat as nd,h_ as ne,rct as nf,zv as ng,ale as nh,vMe as ni,nlt as nj,PR as nk,Olt as nl,bCe as nm,mFe as nn,Zot as no,rG as np,Kg as nq,EK as nr,pq as ns,Fot as nt,f2 as nu,mI as nv,Bot as nw,Grt as nx,_h as ny,Oq as nz,_ct as o,aZ as o$,CK as o0,Y2 as o1,Wce as o2,VO as o3,Npt as o4,hq as o5,Rat as o6,Oat as o7,Opt as o8,xge as o9,m0 as oA,g0 as oB,ld as oC,y0 as oD,$l as oE,x2 as oF,gY as oG,nv as oH,xOe as oI,vY as oJ,klt as oK,ele as oL,Xb as oM,Hye as oN,sne as oO,XFe as oP,Qlt as oQ,Be as oR,rne as oS,nne as oT,_at as oU,Iat as oV,Blt as oW,Glt as oX,flt as oY,bn as oZ,Fa as o_,Aat as oa,$Xe as ob,E$e as oc,P$e as od,ddt as oe,Wnt as of,Vnt as og,udt as oh,Spt as oi,NLe as oj,XS as ok,ane as ol,JC as om,a8e as on,pv as oo,wlt as op,tut as oq,hye as or,tv as os,lr as ot,bf as ou,hce as ov,xpt as ow,Xs as ox,Mf as oy,p0 as oz,Ect as p,btt as p$,pOe as p0,TR as p1,Yr as p2,Ue as p3,az as p4,io as p5,be as p6,Oct as p7,SE as p8,jct as p9,Ile as pA,aat as pB,HJe as pC,VJe as pD,nq as pE,tq as pF,sle as pG,Gu as pH,lee as pI,_c as pJ,Ey as pK,B_ as pL,xy as pM,Og as pN,su as pO,_4 as pP,Wt as pQ,q_ as pR,Y_ as pS,Tt as pT,OT as pU,DC as pV,_lt as pW,VCe as pX,Ant as pY,Vle as pZ,VV as p_,Lct as pa,fct as pb,KMe as pc,vrt as pd,uRe as pe,lRe as pf,Vct as pg,oOe as ph,fRe as pi,PMe as pj,BOe as pk,Jle as pl,qc as pm,OQe as pn,BMe as po,cN as pp,OS as pq,Cat as pr,Sat as ps,stt as pt,bMe as pu,U1 as pv,Ime as pw,Ame as px,IO as py,tR as pz,Ict as q,ppt as q$,jh as q0,gme as q1,Ipt as q2,hme as q3,pme as q4,Hst as q5,Lpt as q6,rOe as q7,TMe as q8,eRe as q9,BZe as qA,Dae as qB,Mae as qC,Udt as qD,$ae as qE,hle as qF,gSe as qG,dlt as qH,Ret as qI,$dt as qJ,$v as qK,Flt as qL,H2e as qM,h2e as qN,HR as qO,Clt as qP,YSe as qQ,yot as qR,Alt as qS,u2e as qT,Rlt as qU,Jce as qV,alt as qW,ilt as qX,tlt as qY,Net as qZ,hpt as q_,gMe as qa,dZ as qb,W5 as qc,uje as qd,zS as qe,EFe as qf,eut as qg,Zct as qh,Jct as qi,WD as qj,YC as qk,nRe as ql,dk as qm,zlt as qn,JSe as qo,M8 as qp,ult as qq,blt as qr,Slt as qs,Tlt as qt,q2e as qu,$M as qv,WZe as qw,HZe as qx,zdt as qy,FZe as qz,Pct as r,MT as r$,xlt as r0,Jlt as r1,ect as r2,Llt as r3,jlt as r4,Cpt as r5,Tg as r6,Sut as r7,Cut as r8,Eut as r9,oct as rA,sct as rB,ict as rC,xU as rD,Put as rE,cut as rF,$ut as rG,Fut as rH,p7e as rI,SU as rJ,y7e as rK,uut as rL,iut as rM,lut as rN,dut as rO,m7e as rP,Xat as rQ,w7e as rR,fut as rS,S7e as rT,Yat as rU,yut as rV,vut as rW,hut as rX,f7e as rY,yU as rZ,GO as r_,_ut as ra,Iut as rb,uf as rc,Mut as rd,Out as re,Aut as rf,Tut as rg,Lut as rh,e4 as ri,Ene as rj,Q3 as rk,M7e as rl,jut as rm,Nut as rn,Rut as ro,kut as rp,vit as rq,I7e as rr,But as rs,L7e as rt,zut as ru,xut as rv,sut as rw,out as rx,aut as ry,Dut as rz,ui as s,Apt as s$,mut as s0,Eot as s1,IP as s2,dct as s3,nut as s4,Jat as s5,mne as s6,but as s7,gut as s8,wut as s9,dP as sA,ylt as sB,glt as sC,EY as sD,Bct as sE,pat as sF,vat as sG,_O as sH,Eat as sI,Dat as sJ,du as sK,qat as sL,Kct as sM,Qct as sN,Uut as sO,KKe as sP,Qut as sQ,Ndt as sR,jdt as sS,Ldt as sT,Bdt as sU,Fdt as sV,Gdt as sW,gpt as sX,ypt as sY,wpt as sZ,bpt as s_,E7e as sa,Zat as sb,pY as sc,Mat as sd,uct as se,_s as sf,rut as sg,cct as sh,lct as si,act as sj,sQe as sk,put as sl,Sw as sm,dne as sn,une as so,fne as sp,J3 as sq,hne as sr,q1 as ss,h7e as st,pne as su,x0e as sv,$O as sw,rlt as sx,elt as sy,Jnt as sz,vct as t,Ppt as t0,kpt as t1,Tpt as t2,Dpt as t3,jpt as t4,Tct as u,Sct as v,kct as w,oDe as x,ATe as y,Mct as z};
|
|
2977
|
+
`).trim()}if(!v&&w.length>0){const k=f.match(/💬 用户指令:\s*([\s\S]*?)(?=\n模型:|\n数量:|$)/);k&&k[1].trim()&&(v=k[1].trim())}return{text:v||f,meta:w,images:p}},[e.parts,e.aiContext]),a=b.useCallback(f=>{f.stopPropagation()},[]),l=b.useCallback(f=>{if((f.ctrlKey||f.metaKey)&&f.key==="c"){const y=window.getSelection(),v=y==null?void 0:y.toString();v&&(aE(v).catch(w=>{console.error("Failed to copy text:",w)}),f.stopPropagation())}},[]);b.useEffect(()=>{const f=r.current;if(f)return f.addEventListener("pointerdown",a),f.addEventListener("pointerup",a),f.addEventListener("mousedown",a),f.addEventListener("mouseup",a),f.addEventListener("click",a),f.addEventListener("keydown",l),()=>{f.removeEventListener("pointerdown",a),f.removeEventListener("pointerup",a),f.removeEventListener("mousedown",a),f.removeEventListener("mouseup",a),f.removeEventListener("click",a),f.removeEventListener("keydown",l)}},[a,l]);const c=s.length===0&&(!o||o.length===0),u=b.useMemo(()=>s.map((f,p)=>({id:`${e.id||"user"}-image-${p}`,url:f.url,type:"image",alt:f.filename})),[s,e.id]),d=b.useCallback((f,p)=>{p==null||p.stopPropagation(),n==null||n(u,f)},[n,u]);return g.jsx(g.Fragment,{children:g.jsxs("div",{className:`user-bubble chat-message chat-message--user ${c?"user-bubble--text-only":""} ${t}`,children:[g.jsx("div",{className:"chat-message-avatar",children:g.jsx("span",{children:"👤"})}),g.jsxs("div",{className:"user-bubble__content chat-message-content",children:[s.length>0&&g.jsx("div",{className:`user-bubble__images user-bubble__images--${Math.min(s.length,4)}`,children:s.map((f,p)=>g.jsx("div",{className:"user-bubble__image-wrapper",onClick:y=>d(p,y),children:g.jsx("img",{src:f.url,alt:f.filename,className:"user-bubble__image",loading:"lazy",draggable:!1})},p))}),i&&g.jsx("div",{ref:r,className:"user-bubble__text user-bubble__text--selectable",children:i}),o&&o.length>0&&g.jsx("div",{className:"user-bubble__meta-tags",children:o.map((f,p)=>g.jsxs("div",{className:"user-bubble__meta-tag",children:[g.jsx("span",{className:"user-bubble__meta-icon",children:f.icon}),g.jsx("span",{className:"user-bubble__meta-label",children:f.label})]},p))})]})]})})},hG="[[WORKFLOW_MESSAGE]]",pG=({handler:e,workflowMessages:t,retryingWorkflowId:n,handleWorkflowReply:r,handleWorkflowRetry:i,className:o="chat-section"})=>{const[s,a]=b.useState(!1),[l,c]=b.useState([]),[u,d]=b.useState(0),f=b.useCallback(x=>{const E=x.parts.find(_=>_.type==="text");if(E&&"text"in E){const _=E.text;if(_.startsWith(hG))return _.replace(hG,"")}return null},[]),p=b.useCallback(x=>x.parts.some(E=>E.type==="data-file"),[]),y=b.useCallback(x=>{let E=null,_=null;for(const I of x.parts)if(I.type==="text"){if(E===null){E=I.text;continue}_||(_=[E]),_.push(I.text)}return _?_.join(""):E??""},[]),v=b.useCallback((x,E)=>{x.length!==0&&(c(x),d(E),a(!0))},[]),w=e.status==="submitted"||e.status==="streaming",C=e.messages.length===0&&!w;return g.jsxs("div",{className:o,children:[g.jsx("div",{className:"chat-messages",children:g.jsxs("div",{className:"chat-messages-list",children:[e.messages.map((x,E)=>{const _=f(x);if(_){const P=t.get(_);if(P)return g.jsx(eat,{workflow:P,onRetry:k=>i(_,P,k),onReply:r?()=>r(_,P):void 0,isRetrying:n===_},x.id)}const I=x.parts.some(P=>P.type==="text"&&"text"in P&&typeof P.text=="string"&&P.text.startsWith("❌ 错误")),D=`chat-message chat-message--${x.role} ${I?"chat-message--error":""}`;return x.role==="user"&&p(x)?g.jsx(tat,{message:x,onPreviewImages:v},x.id):g.jsxs("div",{className:D,"data-message-id":x.id,"data-message-last":E===e.messages.length-1,children:[g.jsx("div",{className:"chat-message-avatar",children:g.jsx("span",{children:x.role==="user"?"👤":"🤖"})}),g.jsx("div",{className:"chat-message-content",children:g.jsx(tN,{markdown:y(x),className:"chat-markdown"})}),x.role==="assistant"&&!I&&g.jsx("div",{className:"chat-message-actions"})]},x.id)}),w&&g.jsxs("div",{className:"chat-loading",children:[g.jsx("div",{className:"chat-loading__spinner"}),g.jsx("span",{children:"思考中..."})]}),C&&g.jsxs("div",{className:"chat-empty",children:[g.jsx("h3",{children:"开始对话"}),g.jsx("p",{children:"输入消息与AI助手交流"})]})]})}),g.jsx(Hg,{visible:s,items:l,initialIndex:u,onClose:()=>a(!1),showThumbnails:l.length>1,videoAutoPlay:!0})]})},nat=Object.freeze(Object.defineProperty({__proto__:null,ChatMessagesArea:pG,default:pG},Symbol.toStringTag,{value:"Module"}));function rat(e){let t=e;return t=t.replace(/\[([^\]]*[:\,\=\(\)\|\/\\][^\]]*)\]/g,(n,r)=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?n:`["${r}"]`),t=t.replace(/\(([^\)]*[:\,\=\[\]\|\/\\][^\)]*)\)/g,(n,r)=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?n:`("${r}")`),t=t.replace(/\{([^\}]*[:\,\=\[\]\(\)\|\/\\][^\}]*)\}/g,(n,r)=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?n:`{"${r}"}`),t}const iat=({code:e,className:t=""})=>{const n=b.useRef(null),[r,i]=b.useState(null),[o,s]=b.useState(!0),[a,l]=b.useState(""),[c,u]=b.useState(!1),[d,f]=b.useState("");if(b.useEffect(()=>{let y=!1;return(async()=>{if(!(!n.current||!e))try{s(!0),i(null);const w=rat(e);l(w);const C=(await xn(async()=>{const{default:_}=await import("./diagram-engines-DpAsX7pc.js").then(I=>I.a);return{default:_}},[],import.meta.url)).default;C.initialize({startOnLoad:!1,theme:"default",securityLevel:"loose",fontFamily:"Inter, SF Pro Display, -apple-system, sans-serif"});const x=`mermaid-${Math.random().toString(36).substr(2,9)}`,{svg:E}=await C.render(x,w);!y&&n.current&&(n.current.innerHTML=E,f(E),s(!1))}catch(w){console.error("[MermaidRenderer] Failed to render:",w),y||(i(w.message||"Failed to render diagram"),s(!1))}})(),()=>{y=!0}},[e]),r){const y=a&&a!==e;return g.jsx("div",{className:`mermaid-renderer mermaid-renderer--error ${t}`,children:g.jsxs("div",{className:"mermaid-renderer__error",children:[g.jsx("strong",{children:"Mermaid渲染错误:"}),g.jsx("pre",{children:r}),g.jsxs("details",{children:[g.jsx("summary",{children:"查看原始代码"}),g.jsx("pre",{children:e})]}),y&&g.jsxs("details",{children:[g.jsx("summary",{children:"查看预处理后的代码(已自动添加引号)"}),g.jsx("pre",{children:a})]})]})})}const p=()=>{!o&&d&&u(!0)};return g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:`mermaid-renderer ${t}`,children:[o&&g.jsx("div",{className:"mermaid-renderer__loading",children:"渲染中..."}),g.jsx(cn,{content:"点击查看大图",showArrow:!1,children:g.jsx("div",{ref:n,className:"mermaid-renderer__container",style:{display:o?"none":"block"},onClick:p})}),!o&&d&&g.jsxs("div",{className:"mermaid-renderer__hint",children:[g.jsx(oZ,{size:16}),g.jsx("span",{children:"点击查看大图"})]})]}),g.jsx(NR,{visible:c,onClose:()=>u(!1),header:"Mermaid 图表",width:"90vw",className:"mermaid-preview-dialog",footer:null,closeBtn:g.jsx(Bd,{}),children:g.jsx("div",{className:"mermaid-preview-content",dangerouslySetInnerHTML:{__html:d}})})]})},oat=Object.freeze(Object.defineProperty({__proto__:null,MermaidRenderer:iat},Symbol.toStringTag,{value:"Module"}));export{Ie as $,PX as A,Cct as B,bct as C,xct as D,pct as E,gE as F,hct as G,VX as H,_Be as I,CBe as J,IBe as K,Qg as L,EBe as M,SBe as N,mct as O,b as P,Mi as Q,X as R,er as S,un as T,uy as U,xt as V,he as W,Qo as X,wn as Y,Ot as Z,kr as _,wE as a,iZe as a$,jt as a0,$r as a1,fn as a2,Wf as a3,Sm as a4,zo as a5,Kut as a6,bH as a7,g as a8,Hut as a9,BYe as aA,fr as aB,O0 as aC,Qt as aD,ci as aE,Lht as aF,El as aG,_Je as aH,CJe as aI,EJe as aJ,KJe as aK,lle as aL,Lh as aM,uu as aN,uh as aO,fu as aP,fh as aQ,rE as aR,hr as aS,F5 as aT,QJe as aU,G5 as aV,rp as aW,K5 as aX,J0 as aY,tZe as aZ,rZe as a_,Je as aa,cn as ab,Ghe as ac,Mve as ad,jat as ae,wq as af,Ove as ag,Lat as ah,Bat as ai,uXe as aj,Et as ak,mdt as al,FG as am,npe as an,tn as ao,bq as ap,uZe as aq,Dl as ar,uo as as,q as at,cdt as au,hc as av,FYe as aw,adt as ax,sdt as ay,LYe as az,zr as b,am as b$,Ba as b0,lI as b1,X5 as b2,Y5 as b3,Iae as b4,J5 as b5,Pae as b6,WM as b7,ii as b8,M1 as b9,RLe as bA,Ght as bB,Vht as bC,CQe as bD,Ilt as bE,clt as bF,vlt as bG,cht as bH,hlt as bI,lht as bJ,RT as bK,hht as bL,iR as bM,ufe as bN,Bh as bO,Kt as bP,qde as bQ,_u as bR,wy as bS,ti as bT,Ew as bU,RUe as bV,fw as bW,gc as bX,NUe as bY,hZe as bZ,B1 as b_,O1 as ba,Z5 as bb,Tae as bc,ne as bd,Il as be,Nl as bf,An as bg,_n as bh,Ig as bi,Qe as bj,ir as bk,$i as bl,Ks as bm,rS as bn,Qc as bo,Pn as bp,Pe as bq,hee as br,za as bs,sI as bt,Vhe as bu,RG as bv,NG as bw,Nht as bx,Hht as by,Wht as bz,o_e as c,Cd as c$,Ca as c0,xs as c1,mlt as c2,aR as c3,Uv as c4,aN as c5,xr as c6,gs as c7,So as c8,n2 as c9,ic as cA,g2 as cB,ble as cC,Yht as cD,Xht as cE,vv as cF,wle as cG,yS as cH,$lt as cI,SY as cJ,sN as cK,SQe as cL,iV as cM,hl as cN,ln as cO,Jht as cP,Fht as cQ,zht as cR,$ht as cS,Uht as cT,Tv as cU,Ylt as cV,Xlt as cW,Elt as cX,Zht as cY,Mlt as cZ,Xtt as c_,et as ca,R_ as cb,W4 as cc,sg as cd,qfe as ce,aGe as cf,Odt as cg,L_ as ch,sGe as ci,Mdt as cj,Dw as ck,qut as cl,nN as cm,Fct as cn,Ei as co,$Oe as cp,UOe as cq,Bd as cr,Nhe as cs,qM as ct,oV as cu,W3 as cv,vS as cw,eg as cx,ov as cy,O8 as cz,gct as d,_ft as d$,sR as d0,NR as d1,Qht as d2,qlt as d3,Wlt as d4,Vlt as d5,Plt as d6,T1 as d7,bat as d8,vT as d9,Gse as dA,hYe as dB,MLe as dC,ru as dD,tct as dE,VOe as dF,eZ as dG,Zlt as dH,qct as dI,cae as dJ,ydt as dK,bdt as dL,xdt as dM,wdt as dN,Ir as dO,Jm as dP,gUe as dQ,m1 as dR,aEe as dS,lEe as dT,Ui as dU,Eu as dV,Kdt as dW,Rft as dX,tft as dY,jft as dZ,Sqe as d_,cS as da,yL as db,Wrt as dc,yn as dd,QC as de,Sd as df,Kme as dg,Rd as dh,gS as di,r8 as dj,B1e as dk,Lq as dl,jq as dm,sxe as dn,axe as dp,xat as dq,wat as dr,ixe as ds,hm as dt,Pce as du,zw as dv,a$e as dw,j5 as dx,Nae as dy,Rae as dz,pg as e,Ynt as e$,Ift as e0,Aft as e1,Pft as e2,Bn as e3,Vs as e4,yo as e5,As as e6,zct as e7,J1 as e8,OM as e9,$w as eA,Nd as eB,Rqe as eC,J_ as eD,MM as eE,L5 as eF,R5 as eG,gYe as eH,V5 as eI,rZ as eJ,tOe as eK,av as eL,Hv as eM,nZ as eN,fYe as eO,OLe as eP,Dse as eQ,GKe as eR,vxe as eS,ss as eT,uZ as eU,Ult as eV,kSe as eW,lZ as eX,ty as eY,Xft as eZ,Qat as e_,_qe as ea,rs as eb,z5 as ec,pae as ed,U5 as ee,TXe as ef,Gn as eg,uae as eh,np as ei,Q_ as ej,aae as ek,cy as el,mce as em,Dm as en,so as eo,TQe as ep,H3 as eq,tI as er,kqe as es,qn as et,Bse as eu,Lse as ev,$C as ew,GV as ex,KM as ey,T5 as ez,yct as f,apt as f$,Gct as f0,ZT as f1,X3 as f2,hN as f3,JOe as f4,mft as f5,cI as f6,hrt as f7,_5 as f8,E5 as f9,fce as fA,Iet as fB,_et as fC,KC as fD,qC as fE,cr as fF,vo as fG,Uo as fH,z1 as fI,ai as fJ,pi as fK,nS as fL,yat as fM,opt as fN,Oet as fO,w_ as fP,Lne as fQ,n4 as fR,r4 as fS,spt as fT,lpt as fU,kle as fV,rpt as fW,ket as fX,tpt as fY,ipt as fZ,Pet as f_,I5 as fa,Fw as fb,$le as fc,sFe as fd,Nse as fe,sr as ff,JX as fg,QX as fh,TOe as fi,POe as fj,aOe as fk,SMe as fl,YT as fm,sRe as fn,XMe as fo,jOe as fp,kR as fq,cOe as fr,dOe as fs,ROe as ft,uht as fu,COe as fv,$ct as fw,Hct as fx,Xh as fy,vpt as fz,BIe as g,YJ as g$,Hn as g0,mpt as g1,f$e as g2,yw as g3,zve as g4,fpt as g5,ept as g6,npt as g7,dpt as g8,upt as g9,ule as gA,vf as gB,dce as gC,mat as gD,tS as gE,vhe as gF,Xct as gG,Hc as gH,spe as gI,Od as gJ,XJ as gK,ZJ as gL,cje as gM,Vje as gN,_d as gO,Wje as gP,VE as gQ,PQ as gR,TQ as gS,_je as gT,AD as gU,kje as gV,OQ as gW,kQ as gX,nje as gY,GJ as gZ,KJ as g_,cpt as ga,One as gb,_Qe as gc,IQe as gd,Uct as ge,IOe as gf,Kn as gg,AR as gh,qOe as gi,ont as gj,Rct as gk,xE as gl,VMe as gm,gOe as gn,Q1 as go,zMe as gp,HMe as gq,Wct as gr,_m as gs,On as gt,gi as gu,$qe as gv,Sae as gw,slt as gx,lg as gy,md as gz,$X as h,$at as h$,Yu as h0,fLe as h1,qJ as h2,HJ as h3,Aje as h4,VJ as h5,WJ as h6,rje as h7,fje as h8,hje as h9,iae as hA,oI as hB,TYe as hC,kYe as hD,mYe as hE,iYe as hF,VKe as hG,Mqe as hH,DYe as hI,rdt as hJ,idt as hK,bc as hL,Ha as hM,ms as hN,Go as hO,Tn as hP,UE as hQ,LUe as hR,Hm as hS,ta as hT,ndt as hU,Fat as hV,Vf as hW,sy as hX,$a as hY,SGe as hZ,zat as h_,dje as ha,aje as hb,kn as hc,LJ as hd,BJ as he,j3 as hf,Pje as hg,MQ as hh,Ije as hi,D2 as hj,kLe as hk,vLe as hl,gLe as hm,yLe as hn,TLe as ho,ALe as hp,mLe as hq,DLe as hr,PLe as hs,Gut as ht,Vut as hu,pLe as hv,jee as hw,c5 as hx,tdt as hy,edt as hz,hg as i,tQe as i$,Lr as i0,_Ze as i1,IZe as i2,Khe as i3,Dve as i4,rFe as i5,iFe as i6,oFe as i7,xft as i8,bft as i9,sft as iA,ift as iB,aft as iC,lft as iD,cft as iE,uft as iF,dft as iG,fft as iH,qft as iI,vft as iJ,wft as iK,Uft as iL,zft as iM,Gft as iN,gft as iO,NC as iP,Qdt as iQ,nft as iR,eft as iS,Ydt as iT,Oht as iU,qdt as iV,Kft as iW,Xdt as iX,Zdt as iY,Nct as iZ,Jdt as i_,yft as ia,Mft as ib,xJe as ic,Mht as id,oht as ie,dht as ig,Dht as ih,Wft as ii,fht as ij,Rr as ik,hft as il,Tft as im,Dft as io,pft as ip,Vh as iq,ldt as ir,uQ as is,mc as it,BG as iu,Lft as iv,Nft as iw,dn as ix,rft as iy,oft as iz,wct as j,Jut as j$,Ug as j0,Idt as j1,Cdt as j2,Mw as j3,Vd as j4,Rdt as j5,Un as j6,odt as j7,_w as j8,Adt as j9,F_ as jA,yc as jB,J4 as jC,Fg as jD,kh as jE,Fi as jF,wc as jG,jUe as jH,In as jI,Pl as jJ,gie as jK,om as jL,sm as jM,EZe as jN,Ua as jO,ny as jP,sH as jQ,Oae as jR,hdt as jS,fdt as jT,Hs as jU,l0e as jV,Kht as jW,_Ve as jX,Wut as jY,Zut as jZ,Rht as j_,Ddt as ja,Gd as jb,jZe as jc,OZe as jd,NZe as je,vdt as jf,ay as jg,kdt as jh,dXe as ji,Tdt as jj,Pdt as jk,Rie as jl,yre as jm,jYe as jn,vee as jo,Ag as jp,_o as jq,Zne as jr,a3 as js,Qs as jt,MQe as ju,Fse as jv,MOe as jw,qht as jx,b1 as jy,Ed as jz,Uh as k,jwe as k$,Vdt as k0,Wdt as k1,Xut as k2,vle as k3,CZe as k4,pYe as k5,Lae as k6,XK as k7,kat as k8,gdt as k9,fS as kA,JL as kB,e1e as kC,n1e as kD,r1e as kE,z0 as kF,YO as kG,Yve as kH,G1 as kI,Hat as kJ,Ip as kK,vl as kL,Vat as kM,Gat as kN,Kat as kO,JO as kP,$1e as kQ,z1e as kR,Zbe as kS,Jbe as kT,Qbe as kU,exe as kV,Awe as kW,Pwe as kX,swe as kY,awe as kZ,Nwe as k_,nXe as ka,jht as kb,bd as kc,whe as kd,bhe as ke,xhe as kf,She as kg,Che as kh,Ehe as ki,_he as kj,gat as kk,Pq as kl,Wat as km,dh as kn,jv as ko,zye as kp,Uye as kq,Cq as kr,Eq as ks,Uat as kt,_q as ku,Tat as kv,H1 as kw,o0e as kx,QK as ky,a0e as kz,Act as l,Sft as l$,Hwe as l0,Wwe as l1,Abe as l2,kbe as l3,rY as l4,Rbe as l5,Nbe as l6,Zwe as l7,Jwe as l8,obe as l9,cie as lA,Bhe as lB,_l as lC,Whe as lD,Lhe as lE,$he as lF,Fhe as lG,Kfe as lH,Yut as lI,lre as lJ,Ek as lK,Ao as lL,Tqe as lM,b6e as lN,Cft as lO,Eft as lP,Hhe as lQ,Uhe as lR,cat as lS,dat as lT,uat as lU,The as lV,sS as lW,wO as lX,wS as lY,Gfe as lZ,fat as l_,sbe as la,Bbe as lb,Fbe as lc,Ube as ld,Hbe as le,AK as lf,OO as lg,PK as lh,Bq as li,ca as lj,kge as lk,Wi as ll,Zb as lm,IK as ln,Pat as lo,rye as lp,BK as lq,FK as lr,RO as ls,NO as lt,YK as lu,Rye as lv,Nye as lw,jye as lx,_i as ly,Aw as lz,fR as m,aE as m$,sht as m0,aht as m1,sre as m2,Hft as m3,Bnt as m4,xHe as m5,SSe as m6,cg as m7,Dlt as m8,Qft as m9,TBe as mA,DBe as mB,MBe as mC,bYe as mD,yXe as mE,vXe as mF,CQ as mG,pdt as mH,kft as mI,nce as mJ,nct as mK,iht as mL,oR as mM,yY as mN,Zft as mO,Vft as mP,Klt as mQ,Yft as mR,Nlt as mS,fN as mT,FC as mU,rK as mV,Jft as mW,S3 as mX,Oft as mY,Hlt as mZ,hat as m_,eht as ma,tht as mb,nht as mc,rht as md,pht as me,mht as mf,ght as mg,yht as mh,vht as mi,wht as mj,bht as mk,xht as ml,Sht as mm,Cht as mn,Eht as mo,_ht as mp,Iht as mq,Aht as mr,Pht as ms,kht as mt,Tht as mu,PYe as mv,kXe as mw,olt as mx,Hdt as my,bte as mz,Dct as n,Mpt as n$,Sdt as n0,_dt as n1,llt as n2,Edt as n3,Bft as n4,Fft as n5,$ft as n6,ZXe as n7,Lp as n8,plt as n9,Jot as nA,Qot as nB,bge as nC,I$e as nD,S$e as nE,oN as nF,Pot as nG,xY as nH,Ept as nI,QV as nJ,kot as nK,Yrt as nL,Tot as nM,_pt as nN,uit as nO,hae as nP,zXe as nQ,Aot as nR,Bht as nS,xit as nT,Yct as nU,tpe as nV,iRe as nW,Hg as nX,wnt as nY,Rpt as nZ,oO as n_,ome as na,zn as nb,Cl as nc,Nat as nd,h_ as ne,rct as nf,zv as ng,ale as nh,vMe as ni,nlt as nj,PR as nk,Olt as nl,bCe as nm,mFe as nn,Zot as no,rG as np,Kg as nq,EK as nr,pq as ns,Fot as nt,f2 as nu,mI as nv,Bot as nw,Grt as nx,_h as ny,Oq as nz,_ct as o,aZ as o$,CK as o0,Y2 as o1,Wce as o2,VO as o3,Npt as o4,hq as o5,Rat as o6,Oat as o7,Opt as o8,xge as o9,m0 as oA,g0 as oB,ld as oC,y0 as oD,$l as oE,x2 as oF,gY as oG,nv as oH,xOe as oI,vY as oJ,klt as oK,ele as oL,Xb as oM,Hye as oN,sne as oO,XFe as oP,Qlt as oQ,Be as oR,rne as oS,nne as oT,_at as oU,Iat as oV,Blt as oW,Glt as oX,flt as oY,bn as oZ,Fa as o_,Aat as oa,$Xe as ob,E$e as oc,P$e as od,ddt as oe,Wnt as of,Vnt as og,udt as oh,Spt as oi,NLe as oj,XS as ok,ane as ol,JC as om,a8e as on,pv as oo,wlt as op,tut as oq,hye as or,tv as os,lr as ot,bf as ou,hce as ov,xpt as ow,Xs as ox,Mf as oy,p0 as oz,Ect as p,btt as p$,pOe as p0,TR as p1,Yr as p2,Ue as p3,az as p4,io as p5,be as p6,Oct as p7,SE as p8,jct as p9,Ile as pA,aat as pB,HJe as pC,VJe as pD,nq as pE,tq as pF,sle as pG,Gu as pH,lee as pI,_c as pJ,Ey as pK,B_ as pL,xy as pM,Og as pN,su as pO,_4 as pP,Wt as pQ,q_ as pR,Y_ as pS,Tt as pT,OT as pU,DC as pV,_lt as pW,VCe as pX,Ant as pY,Vle as pZ,VV as p_,Lct as pa,fct as pb,KMe as pc,vrt as pd,uRe as pe,lRe as pf,Vct as pg,oOe as ph,fRe as pi,PMe as pj,BOe as pk,Jle as pl,qc as pm,OQe as pn,BMe as po,cN as pp,OS as pq,Cat as pr,Sat as ps,stt as pt,bMe as pu,U1 as pv,Ime as pw,Ame as px,IO as py,tR as pz,Ict as q,ppt as q$,jh as q0,gme as q1,Ipt as q2,hme as q3,pme as q4,Hst as q5,Lpt as q6,rOe as q7,TMe as q8,eRe as q9,BZe as qA,Dae as qB,Mae as qC,Udt as qD,$ae as qE,hle as qF,gSe as qG,dlt as qH,Ret as qI,$dt as qJ,$v as qK,Flt as qL,H2e as qM,h2e as qN,HR as qO,Clt as qP,YSe as qQ,yot as qR,Alt as qS,u2e as qT,Rlt as qU,Jce as qV,alt as qW,ilt as qX,tlt as qY,Net as qZ,hpt as q_,gMe as qa,dZ as qb,W5 as qc,uje as qd,zS as qe,EFe as qf,eut as qg,Zct as qh,Jct as qi,WD as qj,YC as qk,nRe as ql,dk as qm,zlt as qn,JSe as qo,M8 as qp,ult as qq,blt as qr,Slt as qs,Tlt as qt,q2e as qu,$M as qv,WZe as qw,HZe as qx,zdt as qy,FZe as qz,Pct as r,MT as r$,xlt as r0,Jlt as r1,ect as r2,Llt as r3,jlt as r4,Cpt as r5,Tg as r6,Sut as r7,Cut as r8,Eut as r9,oct as rA,sct as rB,ict as rC,xU as rD,Put as rE,cut as rF,$ut as rG,Fut as rH,p7e as rI,SU as rJ,y7e as rK,uut as rL,iut as rM,lut as rN,dut as rO,m7e as rP,Xat as rQ,w7e as rR,fut as rS,S7e as rT,Yat as rU,yut as rV,vut as rW,hut as rX,f7e as rY,yU as rZ,GO as r_,_ut as ra,Iut as rb,uf as rc,Mut as rd,Out as re,Aut as rf,Tut as rg,Lut as rh,e4 as ri,Ene as rj,Q3 as rk,M7e as rl,jut as rm,Nut as rn,Rut as ro,kut as rp,vit as rq,I7e as rr,But as rs,L7e as rt,zut as ru,xut as rv,sut as rw,out as rx,aut as ry,Dut as rz,ui as s,Apt as s$,mut as s0,Eot as s1,IP as s2,dct as s3,nut as s4,Jat as s5,mne as s6,but as s7,gut as s8,wut as s9,dP as sA,ylt as sB,glt as sC,EY as sD,Bct as sE,pat as sF,vat as sG,_O as sH,Eat as sI,Dat as sJ,du as sK,qat as sL,Kct as sM,Qct as sN,Uut as sO,KKe as sP,Qut as sQ,Ndt as sR,jdt as sS,Ldt as sT,Bdt as sU,Fdt as sV,Gdt as sW,gpt as sX,ypt as sY,wpt as sZ,bpt as s_,E7e as sa,Zat as sb,pY as sc,Mat as sd,uct as se,_s as sf,rut as sg,cct as sh,lct as si,act as sj,sQe as sk,put as sl,Sw as sm,dne as sn,une as so,fne as sp,J3 as sq,hne as sr,q1 as ss,h7e as st,pne as su,x0e as sv,$O as sw,rlt as sx,elt as sy,Jnt as sz,vct as t,Ppt as t0,kpt as t1,Tpt as t2,Dpt as t3,jpt as t4,Tct as u,Sct as v,kct as w,oDe as x,ATe as y,Mct as z};
|