@whispering233/ai-editor-server 0.0.67 → 0.0.68
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.
|
@@ -490,7 +490,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let o="<p>An error
|
|
|
490
490
|
`){e.lineFenceLen>=3&&(e.inFenced?e.lineFenceChar===e.fenceChar&&e.lineFenceLen>=e.fenceLen&&e.lineTailBlank&&(e.inFenced=!1,e.fenceChar="",e.fenceLen=0):(e.inFenced=!0,e.fenceChar=e.lineFenceChar,e.fenceLen=e.lineFenceLen)),e.lineIndent=0,e.lineFenceChar="",e.lineFenceLen=0,e.lineFenceRunEnded=!1,e.lineTailBlank=!0;return}e.lineFenceRunEnded?e.lineTailBlank=e.lineTailBlank&&/\s/.test(t):e.lineFenceLen===0&&t===" "&&e.lineIndent<3?e.lineIndent+=1:e.lineFenceLen===0&&(t==="`"||t==="~")?(e.lineFenceChar=t,e.lineFenceLen=1):e.lineFenceLen>0&&t===e.lineFenceChar?e.lineFenceLen+=1:(e.lineFenceRunEnded=!0,e.lineTailBlank=e.lineTailBlank&&/\s/.test(t))},Bze=e=>e.inFenced||e.lineFenceLen>=3,gre=/^(\*{1,3}|_{1,3})/,Hze=/^`+/,Fze=/^([-+*]\s{0,3})([\s\S]*)$/,Vze=/\s+$/,EV=e=>{const t=e.match(gre)?.[0]??"",n=e.slice(t.length),r=n.replace(Vze,"");if(r)return`${t}${r}${t}${n.slice(r.length)}`},Uze=(e,t)=>{switch(e){case Ir.Emphasis:return EV(t);case Ir.InlineCode:{const n=t.match(Hze)?.[0]??"";return t.length>n.length?`${t}${n}`:void 0}case Ir.Link:{const n=t.indexOf("]");return(n===-1?t.slice(1):t.slice(1,n))||void 0}case Ir.List:{const n=t.match(Fze);if(!n)return;const[,r,o]=n;if(!o)return;const s=gre.test(o)?EV(o):o;return s?`${r}${s}`:void 0}default:return}},Wze=e=>{let t="";for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);r>=55296&&r<=56319?n+1<e.length&&e.charCodeAt(n+1)>=56320&&e.charCodeAt(n+1)<=57343&&(t+=e[n]+e[n+1],n++):(r<56320||r>57343)&&(t+=e[n])}return t},qze=e=>{try{return encodeURIComponent(e)}catch(t){return t instanceof URIError?encodeURIComponent(Wze(e)):""}},Gze={output:"",sections:null},Kze=e=>typeof e=="object"&&typeof e.minSectionChars=="number"?e.minSectionChars:Mze,Xze=e=>typeof e=="object"?e.keepSectionsOnEnd!==!1:!0,Yze={},Zze=(e,t)=>{const{streaming:n,components:r=Yze}=t||{},{hasNextChunk:o=!1,incompleteMarkdownComponentMap:s,incompleteMarkdown:i="placeholder",incremental:a}=dre(n)||{},l=Kze(a),c=Xze(a),u=!!a,p=d.useRef(MS()),h=Object.keys(r).join("\0"),b=d.useMemo(()=>h?h.split("\0"):[],[h]),y=d.useCallback(C=>{const{token:E,pending:w}=C;if(E===Ir.Text||E===Ir.Image&&w==="!")return;if(E===Ir.Table&&C.table.newlines>1)return w;const $=s||{};if(i==="complete"&&!$[E])return Uze(E,w);const N=$[E]||`incomplete-${E}`,M=qze(w);return r?.[N]?`<${N} data-raw="${M}" />`:void 0},[s,i,r]),x=d.useCallback(C=>{if(!C)return p.current=MS(),"";const E=p.current.completeMarkdown+p.current.pending;C.startsWith(E)||(p.current=MS());const w=p.current,$=C.slice(w.processedLength);let N=w.processedLength;w.processedLength+=$.length;for(const k of $){if(w.pending+=k,zze(w.fence,k),hre(w.table,k),u&&k===`
|
|
491
491
|
`&&Lze(w,C,N,b,l),N+=k.length,Bze(w.fence)){YA(w);continue}if(w.token===Ir.Text)for(const R of OM)R.recognize(w);else if(OM.find(O=>O.tokenType===w.token)?.recognize(w),w.token===Ir.Text)for(const O of OM)O.recognize(w);w.token===Ir.Text&&YA(w)}const M=y(w);return w.completeMarkdown+(M||"")},[y,u,b,l]),S=typeof e=="string";return d.useEffect(()=>{S||console.error(`X-Markdown: input must be string, not ${typeof e}.`)},[e,S]),d.useMemo(()=>{if(!S)return Gze;if(!o){const w=p.current;return u&&c&&w.processedLength>0&&e.startsWith(w.completeMarkdown+w.pending)?(x(e),{output:e,sections:wV(w,e,e.length)}):(p.current=MS(),{output:e,sections:null})}const C=x(e),E=p.current;return{output:C,sections:u?wV(E,C,E.completeMarkdown.length):null}},[e,S,o,u,c,x])},Qze=24,Jze=3e3,eBe=["。","!","?",".","!","?",`
|
|
492
492
|
`],tBe=120,_M=140,$V=80,TV=260,NV=.28,RS=(e,t,n)=>e<t?t:e>n?n:e,bre=(e,t)=>{const n=e.charCodeAt(t);return n>=55296&&n<=56319},ZA=(e,t)=>t>0&&t<e.length&&bre(e,t-1)?t+1:t,kV=8205,nBe=e=>e===65038||e===65039,rBe=e=>e>=127995&&e<=127999,oBe=e=>e>=768&&e<=879||e>=6832&&e<=6911||e>=8400&&e<=8447,jM=e=>e>=127462&&e<=127487,sBe=e=>e>=917536&&e<=917631,iBe=8419,aBe=(e,t)=>{const n=e.codePointAt(t);return[n,t+(n>65535?2:1)]},MV=(e,t)=>{const n=t>=2&&bre(e,t-2)?t-2:t-1;return[e.codePointAt(n),n]},lBe=(e,t)=>{let n=ZA(e,t),r=0;for(let o=n;o>0;){const[s,i]=MV(e,o);if(!jM(s))break;r+=1,o=i}for(;;){if(n>=e.length)return e.length;const[o]=MV(e,n),[s,i]=aBe(e,n);if(s===kV||o===kV||nBe(s)||rBe(s)||oBe(s)||s===iBe||sBe(s)){n=i;continue}if(jM(s)&&jM(o)&&r%2===1){n=i,r+=1;continue}return n}};let PM;const cBe=()=>{if(PM===void 0){const e=typeof Intl<"u"?Intl.Segmenter:void 0;PM=typeof e=="function"?new e(void 0,{granularity:"grapheme"}):null}return PM},RV=32,IV=(e,t)=>{if(t<=0||t>=e.length)return t;const n=cBe();if(!n)return lBe(e,t);const r=Math.max(0,ZA(e,t-RV)),o=Math.min(e.length,ZA(e,t+RV));for(const{index:s,segment:i}of n.segment(e.slice(r,o))){const a=r+s,l=a+i.length;if(a>=t)return a;if(l>=t)return l}return o},IS=()=>({scanned:0,boundaries:[],inFence:!1,fenceChar:"",fenceLen:0,atLineStart:!0,lineFenceChar:"",lineFenceLen:0,inInlineCode:!1}),AV=(e,t,n)=>{for(let r=e.scanned;r<t.length;r++){const o=t[r];if(o===`
|
|
493
|
-
`){e.lineFenceLen>=3&&(e.inFence?e.lineFenceChar===e.fenceChar&&e.lineFenceLen>=e.fenceLen&&(e.inFence=!1):(e.inFence=!0,e.fenceChar=e.lineFenceChar,e.fenceLen=e.lineFenceLen)),e.lineFenceChar="",e.lineFenceLen=0,e.atLineStart=!0,e.inInlineCode=!1,e.boundaries.push(r+1);continue}if(e.atLineStart){if((o==="`"||o==="~")&&(e.lineFenceLen===0||e.lineFenceChar===o)){e.lineFenceChar=o,e.lineFenceLen+=1;continue}e.atLineStart=!1,e.lineFenceChar==="`"&&e.lineFenceLen<3&&(e.inInlineCode=e.lineFenceLen%2===1)}if(!e.inFence){if(o==="`"){e.inInlineCode=!e.inInlineCode;continue}!e.inInlineCode&&n.has(o)&&e.boundaries.push(r+1)}}e.scanned=t.length},DM=(e,t)=>{let n=0,r=e.length-1,o=0;for(;n<=r;){const s=n+r>>1;e[s]<=t?(o=e[s],n=s+1):r=s-1}return o},uBe=e=>{const t=typeof e=="object"?e:{};return{unit:t.unit??"char",delimiters:t.delimiters??eBe,minCps:t.minCps??Qze,maxCps:t.maxCps??Jze,pauseMs:t.pauseMs??0,maxSentenceChars:t.maxSentenceChars??tBe}},dBe=()=>typeof window<"u"&&typeof window.requestAnimationFrame=="function",fBe=(e,t,n)=>{const r=!!t&&n&&dBe(),{unit:o,delimiters:s,minCps:i,maxCps:a,pauseMs:l,maxSentenceChars:c}=uBe(t),u=d.useMemo(()=>new Set(s),[s]),[p,h]=d.useState(e.length),b=d.useRef(p),y=d.useRef(e),x=d.useRef(r),S=d.useRef(e.length),C=d.useRef(null),E=d.useRef(_M),w=d.useRef(null),$=d.useRef(null),N=d.useRef(0),M=d.useRef(IS()),k=d.useRef(r);y.current=e,x.current=r;const R=d.useCallback(()=>{w.current!=null&&(window.cancelAnimationFrame(w.current),w.current=null),$.current=null},[]),A=d.useCallback(z=>{z!==b.current&&(b.current=z,h(z))},[]),O=d.useCallback(z=>{w.current=null;const I=y.current,P=I.length;if(!x.current||b.current>=P){R();return}const D=$.current??z,U=Math.max(8,z-D);if($.current=z,z>=N.current){const V=P-S.current,W=RS(E.current,$V,TV),q=RS(V/W*1e3,i,a);S.current=Math.min(P,S.current+q*U/1e3);let B;if(o==="sentence"){AV(M.current,I,u);const{boundaries:F}=M.current,G=b.current,J=Math.floor(S.current),te=DM(F,J);J>=P?B=P:te>G?B=te:J-DM(F,G)>c?B=Math.min(P,IV(I,Math.max(G+1,J))):B=G}else if(B=Math.max(b.current+1,Math.floor(S.current)),B=Math.min(P,IV(I,B)),l>0&&B>b.current){AV(M.current,I,u);const F=DM(M.current.boundaries,B);F>b.current&&(B=F,S.current=F,N.current=z+l)}A(B)}b.current<y.current.length?w.current=window.requestAnimationFrame(O):R()},[A,u,a,c,i,l,R,o]),j=d.useCallback(()=>{w.current!=null||!x.current||b.current>=y.current.length||($.current=null,w.current=window.requestAnimationFrame(O))},[O]),L=d.useRef(e);return d.useEffect(()=>{const z=L.current;if(L.current=e,!r){R(),k.current=!1;return}if(!k.current){k.current=!0,M.current=IS(),S.current=e.length,A(e.length),C.current=null,E.current=_M;return}if(!e.startsWith(z.slice(0,b.current))){R(),M.current=IS(),S.current=e.length,A(e.length),C.current=null,E.current=_M;return}if(e.startsWith(z)||(M.current=IS(),S.current=Math.min(S.current,e.length)),e.length>z.length){const I=performance.now(),P=C.current;if(P!=null){const D=RS(I-P,30,500);E.current=RS((1-NV)*E.current+NV*D,$V,TV)}C.current=I}j()},[e,r,A,j,R]),d.useEffect(()=>R,[R]),d.useMemo(()=>r?p>=e.length?e:e.slice(0,p):e,[r,e,p])},mBe=X.memo(({content:e,parser:t,renderer:n,injectTail:r})=>{const o=d.useMemo(()=>t.parse(e,{injectTail:r}),[e,t,r]),s=d.useMemo(()=>n.render(o),[o,n]);return X.createElement(X.Fragment,null,s)}),OV="▋",pBe=e=>e?typeof e=="boolean"?OV:e.content||OV:null,t$=X.memo(e=>{const{streaming:t,config:n,components:r,componentsProps:o,paragraphTag:s,content:i,children:a,rootClassName:l,className:c,style:u,openLinksInNewTab:p,dompurifyConfig:h,protectCustomTagNewlines:b,disableCustomTagBlockMarkdown:y,escapeRawHtml:x,debug:S,disableDefaultStyles:C}=e,E=dre(t),w=d.useMemo(()=>pBe(E?.tail),[E?.tail]),$=typeof E?.tail=="object"?E.tail.component:void 0,N=!!E?.hasNextChunk&&w,M=d.useMemo(()=>{if(C===!0)return"x-md-disable-all";if(Array.isArray(C))return C.map(W=>`x-md-disable-${W}`)},[C]),k=ie("x-markdown",M,l,c),R=fBe(i||a||"",E?.typewriter,!!E?.hasNextChunk),{output:A,sections:O}=Zze(R,{streaming:E,components:r}),j=d.useMemo(()=>{if(!N)return r;const W=$?X.createElement($,{content:w}):X.createElement("span",{className:"xmd-tail"},w);return{...r,"xmd-tail":()=>W}},[N,r,$,w]),L=d.useMemo(()=>new KLe({markedConfig:n,paragraphTag:s,openLinksInNewTab:p,components:j,protectCustomTagNewlines:b,disableCustomTagBlockMarkdown:y,escapeRawHtml:x}),[n,s,p,j,b,y,x]),z=E?.enableAnimation,I=E?.animationConfig,P=d.useMemo(()=>new aP({components:j,componentsProps:o,dompurifyConfig:h,streaming:{enableAnimation:z,animationConfig:I}}),[j,o,h,z,I]),D=d.useMemo(()=>!A||O?"":L.parse(A,{injectTail:!!N}),[A,O,L,N]),U=d.useMemo(()=>D?P.render(D):null,[D,P]);if(!A)return null;const V=O?O.map((W,q)=>X.createElement(mBe,{key:q,content:W,parser:L,renderer:P,injectTail:!!N&&q===O.length-1})):null;return X.createElement(X.Fragment,null,X.createElement("div",{className:k,style:u},V??U),S?X.createElement(xze,null):null)}),hBe={get_entity:{lead:"查询实体",fields:{id:{label:"实体",id:!0},type:{label:"类型"}}},search_entities:{lead:"搜索实体",fields:{type:{label:"类型"},query:{label:"关键词"}}},query_relationships:{lead:"查询关系",fields:{source_id:{label:"源",id:!0},target_id:{label:"目标",id:!0},relation_type:{label:"关系类型"},depth:{label:"深度"}}},get_outline:{lead:"读取大纲",fields:{}},get_outline_path:{lead:"读取节点路径",fields:{node_id:{label:"节点",id:!0}}},get_chapter_text:{lead:"读取章正文",fields:{},render:bBe},compute_state:{lead:"计算状态",fields:{target_id:{label:"目标",id:!0},at_node_id:{label:"锚定节点",id:!0}}},get_delta_history:{lead:"查询变更历史",fields:{target_id:{label:"目标",id:!0}}},get_entity_summary:{lead:"读取实体统计",fields:{type:{label:"类型"}}},search_references:{lead:"搜索参考资料",fields:{query:{label:"关键词"},type:{label:"分类"},tags:{label:"标签"}}},analyze_consistency:{lead:"一致性分析",fields:{entity_id:{label:"实体",id:!0}}},detect_conflicts:{lead:"跨实体矛盾检测",fields:{}},trace_plot_paths:{lead:"剧情路径推演",fields:{from_node_id:{label:"起点",id:!0},to_node_id:{label:"终点",id:!0}}},find_orphan_elements:{lead:"孤立元素诊断",fields:{}},suggest_connections:{lead:"关系发现",fields:{entity_id:{label:"实体",id:!0}}},analyze_hook_health:{lead:"伏笔健康分析",fields:{}},trace_hook_lifecycle:{lead:"伏笔生命周期追踪",fields:{hook_id:{label:"伏笔",id:!0}}},suggest_hook_payoff:{lead:"伏笔回收建议",fields:{hook_id:{label:"伏笔",id:!0}}},find_hook_opportunities:{lead:"伏笔埋设机会",fields:{outline_node_id:{label:"节点",id:!0}}},detect_hook_conflicts:{lead:"伏笔矛盾检测",fields:{}},propose_create_entity:{lead:"新建实体",fields:{name:{label:"名称"},type:{label:"类型"},data:{label:"字段"}}},propose_update_entity:{lead:"更新实体",fields:{entity_id:{label:"实体",id:!0},patches:{label:"变更字段"}}},propose_delete_entity:{lead:"删除实体",fields:{entity_id:{label:"实体",id:!0}}},propose_add_relation:{lead:"新增关系",fields:{source:{label:"源",id:!0},target:{label:"目标",id:!0},type:{label:"关系类型"}}},propose_remove_relation:{lead:"移除关系",fields:{}},propose_add_delta:{lead:"追加变更",fields:{target:{label:"目标",id:!0},changes:{label:"变更条数"}}},propose_outline_node:{lead:"新建大纲节点",fields:{title:{label:"标题"},type:{label:"层级"},parent_id:{label:"上级",id:!0}}},propose_move_node:{lead:"移动大纲节点",fields:{node_id:{label:"节点",id:!0},parent_id:{label:"上级",id:!0},order:{label:"位置"}}},propose_delete_node:{lead:"删除大纲节点",fields:{node_id:{label:"节点",id:!0}}},propose_update_outline_node:{lead:"更新大纲节点",fields:{node_id:{label:"节点",id:!0},patches:{label:"变更字段"}}},propose_create_hook:{lead:"新建伏笔",fields:{name:{label:"名称"},plant_at_node_id:{label:"埋设节点",id:!0}}},propose_update_hook:{lead:"更新伏笔",fields:{hook_id:{label:"伏笔",id:!0},patches:{label:"变更字段"}}},propose_advance_hook:{lead:"推进伏笔",fields:{hook_id:{label:"伏笔",id:!0},node_id:{label:"节点",id:!0}}},propose_resolve_hook:{lead:"回收伏笔",fields:{hook_id:{label:"伏笔",id:!0},node_id:{label:"节点",id:!0}}},propose_abandon_hook:{lead:"废弃伏笔",fields:{hook_id:{label:"伏笔",id:!0}}},propose_reorder_timepoints:{lead:"重排时间点",fields:{}},propose_create_reference:{lead:"新建参考资料",fields:{name:{label:"标题"},type:{label:"分类"}}}};function yre(e){return typeof e=="string"?e:Array.isArray(e)?e.length>0&&typeof e[0]=="object"&&e[0]!==null?`${e.length} 项`:e.map(t=>String(t)).join("、"):typeof e=="object"&&e!==null?Object.keys(e).join("、"):String(e)}function gBe(e,t,n){if(t==null)return null;if(e.id===!0){if(typeof t!="string")return null;const o=n?.[t];return o==null?null:`${e.label}「${o.name}」`}const r=yre(t);return r===""?null:`${e.label}:${r}`}function bBe(e,t){const n=e.node_id,r=typeof n=="string"?t?.[n]:void 0,o=r==null?"读取章正文":`读取章正文:章「${r.name}」`,s=typeof e.offset=="number"&&e.offset>0?e.offset:null,i=typeof e.max_chars=="number"?e.max_chars:null,a=s!==null?`从第 ${s} 字起${i===null?"":`,读 ${i} 字`}`:i===null?null:`前 ${i} 字`;return[a===null?o:`${o}(${a})`]}function xre(e,t,n){const r=hBe[e];if(r===void 0)return null;if(typeof t!="object"||t===null)return[r.lead];if(r.render!==void 0)return r.render(t,n);const o=[];for(const[a,l]of Object.entries(t)){const c=r.fields[a];if(c===void 0)continue;const u=gBe(c,l,n);u!==null&&o.push({isId:c.id===!0,text:u})}if(o.length===0)return[r.lead];const s=o.find(a=>a.isId)??o[0],i=o.filter(a=>a!==s);return[`${r.lead}:${s.text}`,...i.map(a=>a.text)]}function vre(e){if(typeof e!="object"||e===null)return[];const t=[];for(const n of Object.values(e))if(typeof n=="string")t.push(n);else if(Array.isArray(n))for(const r of n)typeof r=="string"&&t.push(r);return t}function Sre(e,t,n){if(t==null)return null;if(typeof t=="string")return[t];if(typeof t!="object")return null;const r=t,o=[];if(typeof r.summary=="string"&&r.summary!==""&&o.push(r.summary),Array.isArray(r.changes)){for(const s of r.changes)if(typeof s=="string")o.push(s);else if(typeof s=="object"&&s!==null){const i=s,a=typeof i.id=="string"?n?.[i.id]:void 0,l=typeof i.name=="string"&&i.name!==""?i.name:a?.name;o.push(l===void 0?"调整位置":`「${l}」→ 位置 ${String(i.order??"")}`)}}if(typeof r.args=="object"&&r.args!==null){const s=xre(e,r.args,n);s!==null&&o.push(...s)}for(const[s,i]of Object.entries(r))s==="summary"||s==="changes"||s==="args"||s==="type"||i!=null&&o.push(`${s}:${yre(i)}`);return o.length>0?o:null}const yBe=70,xBe=90,vBe=["cost","speed","cache","total"];function _V(e){return Number.isInteger(e)?`${e}`:e.toFixed(1)}function Cre(e){if(e<1e3)return`${Math.round(e)}`;const t=Math.round(e/100)/10;return t<1e3?`${_V(t)}k`:`${_V(Math.round(e/1e5)/10)}M`}function SBe(e){const t=e>=1?2:e>=.01?3:4;return`$${e.toFixed(t)}`}function CBe(e){return`${e<10?e.toFixed(1):Math.round(e)} tok/s`}function wBe(e){return e>=xBe?"colorError":e>=yBe?"colorWarning":"colorPrimary"}function EBe(e){if(e===null)return null;const t=Cre(e.contextWindow);if(e.percent===null||e.tokens===null)return{percent:null,text:`? · ${t}`};const n=Math.min(100,Math.max(0,Math.round(e.percent)));return{percent:n,text:`${n}% · ${t}`}}function $Be(e){return e.cacheHitRate===void 0?null:`缓存 ${Math.round(e.cacheHitRate*100)}%`}function TBe(e,t){const{usage:n,speed:r}=t;switch(e){case"cost":return n!==null&&n.cost>0?SBe(n.cost):null;case"speed":return r===null?null:CBe(r.tps);case"cache":return n===null?null:$Be(n);case"total":return n!==null&&n.total>0?`累计 ${Cre(n.total)}`:null}}function NBe(e){return e.tokens===null?`上下文占用:未知(窗口 ${e.contextWindow} tokens)`:`上下文占用:${e.tokens} / ${e.contextWindow} tokens`}function kBe(e){const{contextUsage:t,usage:n,speed:r}=e,o=[];if(t!==null&&o.push(NBe(t)),n!==null&&(o.push(`输入 ${n.input} · 输出 ${n.output} · 缓存读 ${n.cacheRead} · 缓存写 ${n.cacheWrite} · 合计 ${n.total}`),n.cacheHitRate!==void 0&&o.push(`缓存命中率:${Math.round(n.cacheHitRate*100)}%(分母 = 输入 + 缓存读 + 缓存写)`),n.cost>0&&o.push(`成本:$${n.cost.toFixed(4)}${n.subscription?"(订阅 · 估算)":""}`)),r!==null){const s=`${r.outputTokens} tokens / ${(r.ms/1e3).toFixed(1)}s`;o.push(`速度:${r.tps.toFixed(1)} tok/s(样本 ${s})`)}return o}function MBe(e){const t=EBe(e.contextUsage),n=vBe.map(r=>({key:r,text:TBe(r,e)})).filter(r=>r.text!==null);return t===null&&n.length===0?null:{context:t,segments:n,title:kBe(e).join(`
|
|
493
|
+
`){e.lineFenceLen>=3&&(e.inFence?e.lineFenceChar===e.fenceChar&&e.lineFenceLen>=e.fenceLen&&(e.inFence=!1):(e.inFence=!0,e.fenceChar=e.lineFenceChar,e.fenceLen=e.lineFenceLen)),e.lineFenceChar="",e.lineFenceLen=0,e.atLineStart=!0,e.inInlineCode=!1,e.boundaries.push(r+1);continue}if(e.atLineStart){if((o==="`"||o==="~")&&(e.lineFenceLen===0||e.lineFenceChar===o)){e.lineFenceChar=o,e.lineFenceLen+=1;continue}e.atLineStart=!1,e.lineFenceChar==="`"&&e.lineFenceLen<3&&(e.inInlineCode=e.lineFenceLen%2===1)}if(!e.inFence){if(o==="`"){e.inInlineCode=!e.inInlineCode;continue}!e.inInlineCode&&n.has(o)&&e.boundaries.push(r+1)}}e.scanned=t.length},DM=(e,t)=>{let n=0,r=e.length-1,o=0;for(;n<=r;){const s=n+r>>1;e[s]<=t?(o=e[s],n=s+1):r=s-1}return o},uBe=e=>{const t=typeof e=="object"?e:{};return{unit:t.unit??"char",delimiters:t.delimiters??eBe,minCps:t.minCps??Qze,maxCps:t.maxCps??Jze,pauseMs:t.pauseMs??0,maxSentenceChars:t.maxSentenceChars??tBe}},dBe=()=>typeof window<"u"&&typeof window.requestAnimationFrame=="function",fBe=(e,t,n)=>{const r=!!t&&n&&dBe(),{unit:o,delimiters:s,minCps:i,maxCps:a,pauseMs:l,maxSentenceChars:c}=uBe(t),u=d.useMemo(()=>new Set(s),[s]),[p,h]=d.useState(e.length),b=d.useRef(p),y=d.useRef(e),x=d.useRef(r),S=d.useRef(e.length),C=d.useRef(null),E=d.useRef(_M),w=d.useRef(null),$=d.useRef(null),N=d.useRef(0),M=d.useRef(IS()),k=d.useRef(r);y.current=e,x.current=r;const R=d.useCallback(()=>{w.current!=null&&(window.cancelAnimationFrame(w.current),w.current=null),$.current=null},[]),A=d.useCallback(z=>{z!==b.current&&(b.current=z,h(z))},[]),O=d.useCallback(z=>{w.current=null;const I=y.current,P=I.length;if(!x.current||b.current>=P){R();return}const D=$.current??z,U=Math.max(8,z-D);if($.current=z,z>=N.current){const V=P-S.current,W=RS(E.current,$V,TV),q=RS(V/W*1e3,i,a);S.current=Math.min(P,S.current+q*U/1e3);let B;if(o==="sentence"){AV(M.current,I,u);const{boundaries:F}=M.current,G=b.current,J=Math.floor(S.current),te=DM(F,J);J>=P?B=P:te>G?B=te:J-DM(F,G)>c?B=Math.min(P,IV(I,Math.max(G+1,J))):B=G}else if(B=Math.max(b.current+1,Math.floor(S.current)),B=Math.min(P,IV(I,B)),l>0&&B>b.current){AV(M.current,I,u);const F=DM(M.current.boundaries,B);F>b.current&&(B=F,S.current=F,N.current=z+l)}A(B)}b.current<y.current.length?w.current=window.requestAnimationFrame(O):R()},[A,u,a,c,i,l,R,o]),j=d.useCallback(()=>{w.current!=null||!x.current||b.current>=y.current.length||($.current=null,w.current=window.requestAnimationFrame(O))},[O]),L=d.useRef(e);return d.useEffect(()=>{const z=L.current;if(L.current=e,!r){R(),k.current=!1;return}if(!k.current){k.current=!0,M.current=IS(),S.current=e.length,A(e.length),C.current=null,E.current=_M;return}if(!e.startsWith(z.slice(0,b.current))){R(),M.current=IS(),S.current=e.length,A(e.length),C.current=null,E.current=_M;return}if(e.startsWith(z)||(M.current=IS(),S.current=Math.min(S.current,e.length)),e.length>z.length){const I=performance.now(),P=C.current;if(P!=null){const D=RS(I-P,30,500);E.current=RS((1-NV)*E.current+NV*D,$V,TV)}C.current=I}j()},[e,r,A,j,R]),d.useEffect(()=>R,[R]),d.useMemo(()=>r?p>=e.length?e:e.slice(0,p):e,[r,e,p])},mBe=X.memo(({content:e,parser:t,renderer:n,injectTail:r})=>{const o=d.useMemo(()=>t.parse(e,{injectTail:r}),[e,t,r]),s=d.useMemo(()=>n.render(o),[o,n]);return X.createElement(X.Fragment,null,s)}),OV="▋",pBe=e=>e?typeof e=="boolean"?OV:e.content||OV:null,t$=X.memo(e=>{const{streaming:t,config:n,components:r,componentsProps:o,paragraphTag:s,content:i,children:a,rootClassName:l,className:c,style:u,openLinksInNewTab:p,dompurifyConfig:h,protectCustomTagNewlines:b,disableCustomTagBlockMarkdown:y,escapeRawHtml:x,debug:S,disableDefaultStyles:C}=e,E=dre(t),w=d.useMemo(()=>pBe(E?.tail),[E?.tail]),$=typeof E?.tail=="object"?E.tail.component:void 0,N=!!E?.hasNextChunk&&w,M=d.useMemo(()=>{if(C===!0)return"x-md-disable-all";if(Array.isArray(C))return C.map(W=>`x-md-disable-${W}`)},[C]),k=ie("x-markdown",M,l,c),R=fBe(i||a||"",E?.typewriter,!!E?.hasNextChunk),{output:A,sections:O}=Zze(R,{streaming:E,components:r}),j=d.useMemo(()=>{if(!N)return r;const W=$?X.createElement($,{content:w}):X.createElement("span",{className:"xmd-tail"},w);return{...r,"xmd-tail":()=>W}},[N,r,$,w]),L=d.useMemo(()=>new KLe({markedConfig:n,paragraphTag:s,openLinksInNewTab:p,components:j,protectCustomTagNewlines:b,disableCustomTagBlockMarkdown:y,escapeRawHtml:x}),[n,s,p,j,b,y,x]),z=E?.enableAnimation,I=E?.animationConfig,P=d.useMemo(()=>new aP({components:j,componentsProps:o,dompurifyConfig:h,streaming:{enableAnimation:z,animationConfig:I}}),[j,o,h,z,I]),D=d.useMemo(()=>!A||O?"":L.parse(A,{injectTail:!!N}),[A,O,L,N]),U=d.useMemo(()=>D?P.render(D):null,[D,P]);if(!A)return null;const V=O?O.map((W,q)=>X.createElement(mBe,{key:q,content:W,parser:L,renderer:P,injectTail:!!N&&q===O.length-1})):null;return X.createElement(X.Fragment,null,X.createElement("div",{className:k,style:u},V??U),S?X.createElement(xze,null):null)}),hBe={get_entity:{lead:"查询实体",fields:{id:{label:"实体",id:!0},type:{label:"类型"}}},search_entities:{lead:"搜索实体",fields:{type:{label:"类型"},query:{label:"关键词"}}},query_relationships:{lead:"查询关系",fields:{source_id:{label:"源",id:!0},target_id:{label:"目标",id:!0},relation_type:{label:"关系类型"},depth:{label:"深度"}}},get_outline:{lead:"读取大纲",fields:{}},get_outline_path:{lead:"读取节点路径",fields:{node_id:{label:"节点",id:!0}}},search_outline:{lead:"检索大纲",fields:{query:{label:"关键词"},status:{label:"状态"},tags:{label:"标签"},volume_id:{label:"卷",id:!0}}},get_chapter_text:{lead:"读取章正文",fields:{},render:bBe},search_manuscript:{lead:"搜索正文",fields:{query:{label:"关键词"}}},compute_state:{lead:"计算状态",fields:{target_id:{label:"目标",id:!0},at_node_id:{label:"锚定节点",id:!0}}},get_delta_history:{lead:"查询变更历史",fields:{target_id:{label:"目标",id:!0}}},get_entity_summary:{lead:"读取实体统计",fields:{type:{label:"类型"}}},search_references:{lead:"搜索参考资料",fields:{query:{label:"关键词"},type:{label:"分类"},tags:{label:"标签"}}},analyze_consistency:{lead:"一致性分析",fields:{entity_id:{label:"实体",id:!0}}},detect_conflicts:{lead:"跨实体矛盾检测",fields:{}},trace_plot_paths:{lead:"剧情路径推演",fields:{from_node_id:{label:"起点",id:!0},to_node_id:{label:"终点",id:!0}}},find_orphan_elements:{lead:"孤立元素诊断",fields:{}},suggest_connections:{lead:"关系发现",fields:{entity_id:{label:"实体",id:!0}}},analyze_hook_health:{lead:"伏笔健康分析",fields:{}},trace_hook_lifecycle:{lead:"伏笔生命周期追踪",fields:{hook_id:{label:"伏笔",id:!0}}},suggest_hook_payoff:{lead:"伏笔回收建议",fields:{hook_id:{label:"伏笔",id:!0}}},find_hook_opportunities:{lead:"伏笔埋设机会",fields:{outline_node_id:{label:"节点",id:!0}}},detect_hook_conflicts:{lead:"伏笔矛盾检测",fields:{}},propose_create_entity:{lead:"新建实体",fields:{name:{label:"名称"},type:{label:"类型"},data:{label:"字段"}}},propose_update_entity:{lead:"更新实体",fields:{entity_id:{label:"实体",id:!0},patches:{label:"变更字段"}}},propose_delete_entity:{lead:"删除实体",fields:{entity_id:{label:"实体",id:!0}}},propose_add_relation:{lead:"新增关系",fields:{source:{label:"源",id:!0},target:{label:"目标",id:!0},type:{label:"关系类型"}}},propose_remove_relation:{lead:"移除关系",fields:{}},propose_add_delta:{lead:"追加变更",fields:{target:{label:"目标",id:!0},changes:{label:"变更条数"}}},propose_outline_node:{lead:"新建大纲节点",fields:{title:{label:"标题"},type:{label:"层级"},parent_id:{label:"上级",id:!0}}},propose_move_node:{lead:"移动大纲节点",fields:{node_id:{label:"节点",id:!0},parent_id:{label:"上级",id:!0},order:{label:"位置"}}},propose_delete_node:{lead:"删除大纲节点",fields:{node_id:{label:"节点",id:!0}}},propose_update_outline_node:{lead:"更新大纲节点",fields:{node_id:{label:"节点",id:!0},patches:{label:"变更字段"}}},propose_create_hook:{lead:"新建伏笔",fields:{name:{label:"名称"},plant_at_node_id:{label:"埋设节点",id:!0}}},propose_update_hook:{lead:"更新伏笔",fields:{hook_id:{label:"伏笔",id:!0},patches:{label:"变更字段"}}},propose_advance_hook:{lead:"推进伏笔",fields:{hook_id:{label:"伏笔",id:!0},node_id:{label:"节点",id:!0}}},propose_resolve_hook:{lead:"回收伏笔",fields:{hook_id:{label:"伏笔",id:!0},node_id:{label:"节点",id:!0}}},propose_abandon_hook:{lead:"废弃伏笔",fields:{hook_id:{label:"伏笔",id:!0}}},propose_reorder_timepoints:{lead:"重排时间点",fields:{}},propose_create_reference:{lead:"新建参考资料",fields:{name:{label:"标题"},type:{label:"分类"}}}};function yre(e){return typeof e=="string"?e:Array.isArray(e)?e.length>0&&typeof e[0]=="object"&&e[0]!==null?`${e.length} 项`:e.map(t=>String(t)).join("、"):typeof e=="object"&&e!==null?Object.keys(e).join("、"):String(e)}function gBe(e,t,n){if(t==null)return null;if(e.id===!0){if(typeof t!="string")return null;const o=n?.[t];return o==null?null:`${e.label}「${o.name}」`}const r=yre(t);return r===""?null:`${e.label}:${r}`}function bBe(e,t){const n=e.node_id,r=typeof n=="string"?t?.[n]:void 0,o=r==null?"读取章正文":`读取章正文:章「${r.name}」`,s=typeof e.offset=="number"&&e.offset>0?e.offset:null,i=typeof e.max_chars=="number"?e.max_chars:null,a=s!==null?`从第 ${s} 字起${i===null?"":`,读 ${i} 字`}`:i===null?null:`前 ${i} 字`;return[a===null?o:`${o}(${a})`]}function xre(e,t,n){const r=hBe[e];if(r===void 0)return null;if(typeof t!="object"||t===null)return[r.lead];if(r.render!==void 0)return r.render(t,n);const o=[];for(const[a,l]of Object.entries(t)){const c=r.fields[a];if(c===void 0)continue;const u=gBe(c,l,n);u!==null&&o.push({isId:c.id===!0,text:u})}if(o.length===0)return[r.lead];const s=o.find(a=>a.isId)??o[0],i=o.filter(a=>a!==s);return[`${r.lead}:${s.text}`,...i.map(a=>a.text)]}function vre(e){if(typeof e!="object"||e===null)return[];const t=[];for(const n of Object.values(e))if(typeof n=="string")t.push(n);else if(Array.isArray(n))for(const r of n)typeof r=="string"&&t.push(r);return t}function Sre(e,t,n){if(t==null)return null;if(typeof t=="string")return[t];if(typeof t!="object")return null;const r=t,o=[];if(typeof r.summary=="string"&&r.summary!==""&&o.push(r.summary),Array.isArray(r.changes)){for(const s of r.changes)if(typeof s=="string")o.push(s);else if(typeof s=="object"&&s!==null){const i=s,a=typeof i.id=="string"?n?.[i.id]:void 0,l=typeof i.name=="string"&&i.name!==""?i.name:a?.name;o.push(l===void 0?"调整位置":`「${l}」→ 位置 ${String(i.order??"")}`)}}if(typeof r.args=="object"&&r.args!==null){const s=xre(e,r.args,n);s!==null&&o.push(...s)}for(const[s,i]of Object.entries(r))s==="summary"||s==="changes"||s==="args"||s==="type"||i!=null&&o.push(`${s}:${yre(i)}`);return o.length>0?o:null}const yBe=70,xBe=90,vBe=["cost","speed","cache","total"];function _V(e){return Number.isInteger(e)?`${e}`:e.toFixed(1)}function Cre(e){if(e<1e3)return`${Math.round(e)}`;const t=Math.round(e/100)/10;return t<1e3?`${_V(t)}k`:`${_V(Math.round(e/1e5)/10)}M`}function SBe(e){const t=e>=1?2:e>=.01?3:4;return`$${e.toFixed(t)}`}function CBe(e){return`${e<10?e.toFixed(1):Math.round(e)} tok/s`}function wBe(e){return e>=xBe?"colorError":e>=yBe?"colorWarning":"colorPrimary"}function EBe(e){if(e===null)return null;const t=Cre(e.contextWindow);if(e.percent===null||e.tokens===null)return{percent:null,text:`? · ${t}`};const n=Math.min(100,Math.max(0,Math.round(e.percent)));return{percent:n,text:`${n}% · ${t}`}}function $Be(e){return e.cacheHitRate===void 0?null:`缓存 ${Math.round(e.cacheHitRate*100)}%`}function TBe(e,t){const{usage:n,speed:r}=t;switch(e){case"cost":return n!==null&&n.cost>0?SBe(n.cost):null;case"speed":return r===null?null:CBe(r.tps);case"cache":return n===null?null:$Be(n);case"total":return n!==null&&n.total>0?`累计 ${Cre(n.total)}`:null}}function NBe(e){return e.tokens===null?`上下文占用:未知(窗口 ${e.contextWindow} tokens)`:`上下文占用:${e.tokens} / ${e.contextWindow} tokens`}function kBe(e){const{contextUsage:t,usage:n,speed:r}=e,o=[];if(t!==null&&o.push(NBe(t)),n!==null&&(o.push(`输入 ${n.input} · 输出 ${n.output} · 缓存读 ${n.cacheRead} · 缓存写 ${n.cacheWrite} · 合计 ${n.total}`),n.cacheHitRate!==void 0&&o.push(`缓存命中率:${Math.round(n.cacheHitRate*100)}%(分母 = 输入 + 缓存读 + 缓存写)`),n.cost>0&&o.push(`成本:$${n.cost.toFixed(4)}${n.subscription?"(订阅 · 估算)":""}`)),r!==null){const s=`${r.outputTokens} tokens / ${(r.ms/1e3).toFixed(1)}s`;o.push(`速度:${r.tps.toFixed(1)} tok/s(样本 ${s})`)}return o}function MBe(e){const t=EBe(e.contextUsage),n=vBe.map(r=>({key:r,text:TBe(r,e)})).filter(r=>r.text!==null);return t===null&&n.length===0?null:{context:t,segments:n,title:kBe(e).join(`
|
|
494
494
|
`)}}const RBe={total:"@max-[420px]:hidden",cache:"@max-[340px]:hidden"};function IBe({view:e}){const{token:t}=$m.useToken();return m.jsxs("div",{title:e.title,className:"@container mt-1 flex items-center gap-x-3 overflow-hidden text-xs text-muted-foreground whitespace-nowrap tabular-nums",children:[e.context!==null&&m.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[e.context.percent!==null&&m.jsx("span",{className:"block h-0.5 w-16 overflow-hidden rounded-full bg-accent",children:m.jsx("span",{className:"block h-full rounded-full",style:{width:`${e.context.percent}%`,background:t[wBe(e.context.percent)]}})}),m.jsx("span",{children:e.context.text})]}),e.segments.map(n=>m.jsx("span",{className:RBe[n.key],children:n.text},n.key))]})}function ABe(){const e=Kt(o=>o.contextUsage),t=Kt(o=>o.usage),n=Kt(o=>o.speed),r=MBe({contextUsage:e,usage:t,speed:n});return r===null?null:m.jsx(IBe,{view:r})}function ny(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}function wre(e){if(typeof e!="string")return null;let t;try{t=new URL(e)}catch{return null}return t.protocol!=="http:"&&t.protocol!=="https:"?null:{url:e,host:t.hostname.replace(/^www\./,"")}}function OBe(e){return String(e).replace(/\B(?=(\d{3})+$)/g,",")}function _Be(e){return e!==void 0&&/^\d{4}-\d{2}-\d{2}/.test(e)?e.slice(0,10):null}function jBe(e){if(typeof e!="object"||e===null)return null;const t=e,n=wre(t.url);if(n===null)return null;const r=_Be(ny(t.date));return{url:n.url,title:ny(t.title)??n.host,summary:ny(t.summary)??ny(t.content),meta:r===null?n.host:`${n.host} · ${r}`}}function PBe(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.content!="string")return null;const n=wre(t.url);return n===null?null:{url:n.url,title:`已读取:${ny(t.title)??n.host}`,meta:`${n.host} · ${OBe(t.content.length)} 字`}}function DBe(e,t){if(typeof t!="string")return null;let n;try{n=JSON.parse(t)}catch{return null}if(e==="web_search"){if(!Array.isArray(n))return null;const r=n.map(jBe).filter(o=>o!==null);return r.length>0?r:null}if(e==="fetch_content"){const r=PBe(n);return r===null?null:[r]}return null}function LBe({cards:e}){return m.jsx("div",{className:"space-y-1",children:e.map((t,n)=>m.jsxs("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-md border px-2 py-1.5 text-xs text-muted-foreground transition-colors hover:bg-accent",children:[m.jsx("span",{className:"line-clamp-2 text-foreground",children:t.title}),t.summary===void 0?null:m.jsx("span",{className:"mt-1 line-clamp-1",children:t.summary}),m.jsx("span",{className:"mt-1 block",children:t.meta})]},`${t.url}-${n}`))})}const Ds="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",wr="animate-pulse rounded bg-muted",n$=d.createContext(null);function bo({open:e,onOpenChange:t,children:n}){const r=d.useMemo(()=>({open:e,close:()=>t(!1)}),[e,t]);return d.useEffect(()=>{if(!e)return;const o=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=o}},[e]),m.jsx(n$.Provider,{value:r,children:n})}function Ere({children:e,...t}){const n=d.useContext(n$);return m.jsx("button",{type:"button","data-slot":"dialog-close",onClick:()=>n?.close(),...t,children:e})}function zBe({className:e,...t}){const n=d.useContext(n$);return n&&!n.open?null:m.jsx("div",{"data-slot":"dialog-overlay","aria-hidden":!0,onClick:()=>n?.close(),className:et("fixed inset-0 z-50 bg-black/10 backdrop-blur-[2px]",e),...t})}function yo({className:e,children:t,showCloseButton:n=!0,...r}){const o=d.useContext(n$);return d.useEffect(()=>{const s=i=>{i.key==="Escape"&&o?.close()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[o]),o===null||!o.open?null:Co.createPortal(m.jsxs("div",{role:"dialog","aria-modal":"true","data-slot":"dialog-root",children:[m.jsx(zBe,{}),m.jsxs("div",{"data-slot":"dialog-content",className:et("fixed top-1/2 left-1/2 z-50 grid max-h-[calc(100vh-4rem)] w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 overflow-y-auto rounded-lg bg-popover p-4 text-sm text-popover-foreground shadow-lg ring-1 ring-foreground/10",e),...r,children:[t,n&&m.jsx(Ere,{className:"absolute top-2 right-2 rounded-md p-1 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"关闭",children:m.jsx(Es,{className:"text-base"})})]})]}),document.body)}function lo({className:e,...t}){return m.jsx("div",{"data-slot":"dialog-header",className:et("flex flex-col gap-1.5 pr-6",e),...t})}function xo({className:e,showCloseButton:t=!1,children:n,...r}){return m.jsxs("div",{"data-slot":"dialog-footer",className:et("-mx-4 mt-2 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",e),...r,children:[n,t&&m.jsx(Ere,{className:"rounded-md border border-border px-3 py-1.5 text-sm hover:bg-muted",children:"关闭"})]})}function co({className:e,...t}){return m.jsx("h2",{"data-slot":"dialog-title",className:et("text-base leading-snug font-medium",e),...t})}function hu({className:e,...t}){return m.jsx("p",{"data-slot":"dialog-description",className:et("text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",e),...t})}const tc={volume:"卷",chapter:"章",scene:"场"},jV={volume:"chapter",chapter:"scene",scene:null};function Mi({title:e,description:t,confirmLabel:n,danger:r=!1,onConfirm:o,onClose:s}){const[i,a]=d.useState(null),[l,c]=d.useState(!1);async function u(){c(!0),a(null);try{await o(),s()}catch(p){a(p instanceof Ze?p.message:"操作失败,请稍后重试")}finally{c(!1)}}return m.jsx(bo,{open:!0,onOpenChange:p=>!p&&s(),children:m.jsxs(yo,{className:"sm:max-w-md",children:[m.jsx(lo,{children:m.jsx(co,{children:e})}),m.jsx("p",{className:"text-sm text-muted-foreground",children:t}),i&&m.jsx("p",{className:"mt-2 text-sm text-destructive",children:i}),m.jsxs(xo,{children:[m.jsx(de,{onClick:s,disabled:l,children:"取消"}),m.jsx(de,{type:"primary",danger:r,onClick:()=>{u()},disabled:l,children:n})]})]})})}const $re={propose_create_entity:"新建实体",propose_update_entity:"更新实体",propose_delete_entity:"删除实体",propose_add_relation:"新增关系",propose_remove_relation:"移除关系",propose_add_delta:"追加变更",propose_outline_node:"新建大纲节点",propose_move_node:"移动大纲节点",propose_delete_node:"删除大纲节点",propose_update_outline_node:"更新大纲节点",propose_create_hook:"新建伏笔",propose_update_hook:"更新伏笔",propose_advance_hook:"推进伏笔",propose_resolve_hook:"回收伏笔",propose_abandon_hook:"废弃伏笔",propose_reorder_timepoints:"重排时间轴时间点",propose_create_reference:"新建参考资料"},BBe={character:"角色",setting:"设定",location:"地点",hook:"伏笔",event:"事件",timepoint:"时间点",reference:"参考资料"};function HBe(e,t,n){if(e.focus_deduction===!0)return n===void 0?"推演节点":`推演节点 · ${n} 个`;const r=e.focus_entity_id??e.focus_node_id??"",o=e.focus_entity_type?BBe[e.focus_entity_type]??e.focus_entity_type:e.focus_node_id?"大纲节点":"",s=t===void 0?"":t??r;return o&&s?`${o} ${s}`:o||s||"当前内容"}const Tre=e=>{if(typeof e!="object"||e===null)return{};const t=e;if(t.function!==void 0||typeof t.name=="string"){const n=t.function===void 0?t.arguments:t.function.arguments;let r=n;if(typeof n=="string")try{r=JSON.parse(n)}catch{}const o=t.function===void 0?t.name:t.function.name;return{id:t.id,tool:o,name:o,args:r}}return t},FBe=["off","minimal","low","medium","high","xhigh","max"];function VBe(){const[e,t]=d.useState(null),[n,r]=R0e();d.useEffect(()=>{let c=!1;return UY().then(u=>{c||t(u)}).catch(()=>{}),()=>{c=!0}},[]);const o=e?.providers.find(c=>c.id===e.provider)??null,s=o?.models.find(c=>c.id===e?.model)??null,i=e!==null&&(o===null||!o.authConfigured);function a(c){const u=c.indexOf("::");if(u<=0)return;const p=c.slice(0,u),h=c.slice(u+2);t(b=>b&&{...b,provider:p,model:h}),cw({provider:p,model:h}).catch(()=>{})}function l(c){t(u=>u&&{...u,thinkingLevel:c}),cw({thinking_level:c}).catch(()=>{})}return e===null?null:m.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[m.jsx(xn,{size:"small",className:"min-w-0 max-w-48",popupMatchSelectWidth:!1,value:`${e.provider}::${e.model}`,onChange:c=>a(c),title:i?"当前 provider 未配置 API key:请切换到其他 provider 或在设置页配置":"选择模型(按 provider 分组;未配置凭证的组禁用)","aria-label":"选择模型",options:e.providers.filter(c=>c.authConfigured||c.id===e.provider).map(c=>{const u=!c.authConfigured&&c.id!==e.provider;return{label:`${c.displayName}${c.authConfigured?"":"(未配置)"}`,options:c.models.map(p=>({value:`${c.id}::${p.id}`,label:p.displayName??p.id,disabled:u}))}})}),m.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[m.jsx(xn,{size:"small",className:"w-max shrink-0",popupMatchSelectWidth:!1,value:e.thinkingLevel,disabled:i||!s?.reasoning,onChange:c=>l(c),title:"Thinking level","aria-label":"思考强度",options:FBe.map(c=>({value:c,label:c}))}),m.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-xs text-muted-foreground",title:"回合正常结束后自动确认全部提案(含删除类),不再逐条审阅",children:[m.jsx(L2,{size:"small",checked:n,onChange:r,"aria-label":"自动确认提案"}),"自动确认"]})]})]})}function QA(e){const t=e.name?.trim()??"";return t!==""?t:e.lastMessage||"(空会话)"}function UBe(e){return e===null||e.length===0?[{key:"__empty__",label:"暂无历史会话",disabled:!0}]:e.map(t=>({key:t.id,label:m.jsxs("span",{className:"flex min-w-0 flex-col",children:[m.jsx("span",{className:"truncate text-sm",children:QA(t)}),m.jsxs("span",{className:"truncate text-xs text-muted-foreground",children:[t.messageCount," 条 · ",Jc(t.updatedAt)]})]})}))}const PV="delete-session";function WBe(e,t){return n=>({items:[{key:PV,label:"删除会话",danger:!0,disabled:e}],onClick:({key:r,domEvent:o})=>{o.stopPropagation(),r===PV&&t(n.key)}})}function qBe({disabled:e,onClose:t,reserveShellToggle:n=!1}){const r=Kt(C=>C.sessions),o=Kt(C=>C.currentSessionId),s=Kt(C=>C.setCurrentSession),i=Kt(C=>C.newSession),a=Kt(C=>C.deleteSession),l=Kt(C=>C.streaming),c=r?.find(C=>C.id===o)??null,u=c?QA(c):"新会话",[p,h]=d.useState(!1),[b,y]=d.useState(null),x=d.useMemo(()=>UBe(r),[r]),S=d.useMemo(()=>WBe(l,C=>{const E=r?.find(w=>w.id===C)??null;E!==null&&y(E)}),[l,r]);return m.jsxs("div",{className:et("flex h-12 shrink-0 items-center gap-1 border-b border-border pl-2.5",n?"pr-12":"pr-2.5"),children:[m.jsx(Bw,{className:"shrink-0 text-muted-foreground"}),m.jsx(Vg,{disabled:e,trigger:["click"],open:p,onOpenChange:C=>{h(C)},popupRender:()=>m.jsx(Yte,{items:x,activeKey:o??void 0,onActiveChange:C=>{s(C),h(!1)},menu:S,classNames:{root:"rounded-lg bg-popover shadow-md ring-1 ring-foreground/10"},styles:{root:{width:320,maxHeight:320},item:{height:"auto",minHeight:40,paddingBlock:6}}}),children:m.jsxs(de,{size:"small",disabled:e,className:"max-w-44 min-w-0",children:[m.jsx("span",{className:"truncate text-sm font-medium",title:u,children:u}),m.jsx(Wx,{className:"shrink-0 text-xs"})]})}),m.jsx(de,{color:"default",variant:"text",size:"small",className:"shrink-0",disabled:e,onClick:i,"aria-label":"新会话",title:"新会话",icon:m.jsx(ca,{})}),t&&m.jsx(de,{color:"default",variant:"text",size:"small",className:"ml-auto shrink-0",onClick:t,"aria-label":"关闭聊天面板",icon:m.jsx(Es,{})}),b!==null&&m.jsx(Mi,{title:"删除会话",description:`将删除会话「${QA(b)}」及其 ${b.messageCount} 条消息,删除后无法恢复。`,confirmLabel:"确认删除",danger:!0,onConfirm:()=>a(b.id),onClose:()=>y(null)})]})}function GBe(){const e=Kt(r=>r.disconnected),t=Kt(r=>r.setDisconnected),n=Kt(r=>r.resendLast);return e?m.jsx(Za,{banner:!0,type:"warning",showIcon:!0,message:"上次会话已取消",action:m.jsx(de,{size:"small",onClick:n,children:"重新发送"}),closable:!0,onClose:()=>t(!1)}):null}function KBe(){const e=Kt(n=>n.streamError),t=Kt(n=>n.setStreamError);return e?m.jsx(Za,{banner:!0,type:"error",showIcon:!0,message:e,closable:!0,onClose:()=>t(null)}):null}function XBe(e){return e==="error"?"error":e==="ok"?void 0:"loading"}function YBe({toolName:e,args:t}){const[n,r]=d.useState(null),[o,s]=d.useState(!1);d.useEffect(()=>{const a=vre(t);if(a.length===0){r({});return}let l=!1;return N_(a).then(c=>{l||r(c.names)}).catch(()=>{l||s(!0)}),()=>{l=!0}},[t]);const i=d.useMemo(()=>n===null?null:xre(e,t,n),[e,t,n]);return m.jsx("div",{className:"max-h-40 overflow-auto text-xs whitespace-pre-wrap text-muted-foreground",children:o||i===null?m.jsx("pre",{children:typeof t=="string"?t:JSON.stringify(t??{},null,2)}):m.jsx("ul",{className:"space-y-0.5",children:i.map(a=>m.jsx("li",{children:a},a))})})}function ZBe({calls:e,toolResults:t,liveTools:n,openKeys:r,onToggle:o}){return e.map((s,i)=>{const a=Tre(s),l=a.id??`hist-${i}`,c=n?.get(l),u=l?t.get(l):void 0,p=c?.result??u?.content,h=c?.status??(u?.isError===!0?"error":u?"ok":void 0),b=r.has(l),y=a.tool??a.name??"工具",x=DBe(y,p);return{key:l,status:XBe(h),title:m.jsxs("button",{type:"button","aria-expanded":b,onClick:()=>o(l),className:"flex w-full min-w-0 items-center gap-1.5 text-left text-xs text-muted-foreground",children:[m.jsx(O_e,{className:"shrink-0"}),m.jsxs("span",{className:"min-w-0 flex-1 truncate",style:{fontWeight:400},children:["调用了 ",y]}),m.jsx(Ps,{className:"shrink-0 text-xs",rotate:b?90:0})]}),content:b?m.jsx(YBe,{toolName:y,args:a.args}):void 0,footer:x===null?void 0:m.jsx(LBe,{cards:x})}})}function DV({text:e,length:t,live:n=!1,deferred:r=!1,onRequestFull:o}){const[s,i]=d.useState(n),[a,l]=d.useState(null),[c,u]=d.useState(!1),[p,h]=d.useState(!1);d.useEffect(()=>{i(n)},[n]);const b=t>0?t:e.length,y=a??e,x=()=>{const S=!s;i(S),!(!S||!r||a!==null||o===void 0)&&(u(!0),h(!1),o().then(C=>l(C)).catch(()=>h(!0)).finally(()=>u(!1)))};return m.jsxs("div",{className:"text-xs",children:[m.jsxs("button",{type:"button",onClick:x,"aria-expanded":s,className:"flex w-full items-center gap-1 text-left text-muted-foreground",children:[s?m.jsx(Wx,{className:"shrink-0 text-xs"}):m.jsx(Ps,{className:"shrink-0 text-xs"}),m.jsxs("span",{className:"min-w-0 truncate",children:["思考过程 · ",b," 字"]})]}),s&&m.jsx("div",{className:"mt-1 max-h-48 overflow-auto border-l-2 border-input bg-muted px-2 py-1.5 text-xs whitespace-pre-wrap text-foreground/80",children:c?"思维链加载中…":p?"思维链加载失败":y})]})}function QBe({call:e,expanded:t,onToggle:n}){const r=$re[e.tool]??e.tool,o=d.useMemo(()=>Sre(e.tool,{args:e.args},null),[e.tool,e.args]),s=d.useMemo(()=>o===null?null:o.length===1&&!o[0].includes(":")?[]:o[0]===r?o.slice(1):o,[o,r]),i=s!==null&&s.length>0?s[0]:null,a=typeof e.args=="string"?e.args:JSON.stringify(e.args??{},null,2);return m.jsxs("div",{className:"py-1",children:[m.jsxs("div",{role:"button",tabIndex:0,"aria-expanded":t,onClick:n,onKeyDown:l=>{l.target===l.currentTarget&&(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),n())},className:"flex cursor-pointer items-center gap-1.5 rounded px-1 py-1 hover:bg-primary/10",children:[m.jsx(Ps,{className:et("shrink-0 text-xs text-muted-foreground transition-transform",t&&"rotate-90")}),m.jsx("span",{className:"shrink-0 text-xs font-medium text-foreground",children:r}),m.jsx("span",{className:"min-w-0 flex-1 truncate text-xs text-muted-foreground",children:i??"(无摘要)"})]}),t&&m.jsx("div",{className:"mt-1 space-y-1 pl-5",children:s!==null&&s.length>0?m.jsx("ul",{className:"max-h-32 space-y-0.5 overflow-auto text-xs whitespace-pre-wrap text-muted-foreground",children:s.map(l=>m.jsx("li",{children:l},l))}):m.jsx("pre",{className:"max-h-32 overflow-auto text-xs whitespace-pre-wrap text-muted-foreground",children:a})})]})}function JBe({calls:e}){const[t,n]=d.useState(()=>new Set);if(e.length===0)return null;const r=`历史提案 · ${e.length} 条(只读)`,o=s=>{n(i=>{const a=new Set(i);return a.has(s)?a.delete(s):a.add(s),a})};return m.jsxs("div",{className:"rounded-lg border border-primary/25 bg-primary/5 p-2",children:[m.jsxs("div",{className:"flex items-center gap-1.5",children:[m.jsx(H2,{className:"shrink-0 text-primary"}),m.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-foreground",children:r})]}),m.jsx("div",{className:"mt-1 divide-y divide-border/70",children:e.map((s,i)=>{const a=s.id??`hist-proposal-${i}`;return m.jsx(QBe,{call:s,expanded:t.has(a),onToggle:()=>o(a)},a)})})]})}function e7e(e,t){return e.map(Tre).filter(n=>typeof n.tool=="string"&&Ege.includes(n.tool)).filter(n=>n.id===void 0||t?.has(n.id)!==!0).map(n=>({id:n.id,tool:n.tool,args:n.args}))}const t7e={hasNextChunk:!0,incompleteMarkdown:"complete"},n7e={hasNextChunk:!1,incompleteMarkdown:"complete"};function r7e({message:e,toolResults:t,liveTools:n,liveProposalToolCallIds:r,streaming:o=!1}){const{token:s}=$m.useToken(),[i,a]=d.useState(()=>new Set),l=y=>a(x=>{const S=new Set(x);return S.has(y)?S.delete(y):S.add(y),S});if(e.role==="user")return m.jsx("div",{className:"flex justify-end",children:m.jsx(mu,{placement:"end",content:e.content??"",styles:{content:{background:s.colorFillTertiary,color:s.colorText},root:{maxWidth:"85%"}}})});if(e.role==="tool")return null;const c=Array.isArray(e.toolCalls)?e.toolCalls:[],u=e7e(c,r),p=e.content??"",h=e.thinkingText,b=e.thinking??[];return m.jsxs("div",{className:"space-y-1.5",children:[h!==void 0&&h!==""?m.jsx(DV,{text:h,length:h.length,live:e.thinkingStreaming===!0}):b.map(y=>m.jsx(DV,{text:y.preview,length:y.length,deferred:y.deferred,onRequestFull:()=>Gbe(e.sessionId,e.id,y.blockIndex).then(x=>x.thinking)},`thinking-${y.blockIndex}`)),c.length>0&&m.jsx(tre,{items:ZBe({calls:c,toolResults:t,liveTools:n,openKeys:i,onToggle:l})}),p.trim()!==""?m.jsx(mu,{content:m.jsx(t$,{streaming:o?t7e:n7e,children:p})}):null,u.length>0&&m.jsx(JBe,{calls:u})]})}function o7e(e){switch(e){case"pending":return"待处理";case"confirmed":return"✓ 已确认";case"rejected":return"已拒绝";case"stale":return"⚠ 已失效";default:return null}}function s7e({proposal:e,expanded:t,onToggle:n}){const r=Kt(S=>S.confirmProposal),o=Kt(S=>S.rejectProposal),s=Kt(S=>S.proposalBatchRunning),i=$re[e.type]??e.type,a=e.status!=="pending"||e.processing===!0||s,[l,c]=d.useState(null),[u,p]=d.useState(!1);d.useEffect(()=>{const S=e.preview;if(typeof S!="object"||S===null)return;const C=S,E=[];if(typeof C.args=="object"&&C.args!==null&&E.push(...vre(C.args)),Array.isArray(C.changes))for(const $ of C.changes)typeof $=="object"&&$!==null&&typeof $.id=="string"&&E.push($.id);if(E.length===0)return;let w=!1;return c(null),p(!1),N_(E).then($=>{w||c($.names)}).catch(()=>{w||p(!0)}),()=>{w=!0}},[e.preview]);const h=d.useMemo(()=>Sre(e.type,e.preview,l),[e.type,e.preview,l]),b=e.preview!==void 0&&(u||h===null&&typeof e.preview!="string"),y=h!==null&&h.length>0?h[0]:null,x=o7e(e.status);return m.jsxs("div",{className:"py-1",children:[m.jsxs("div",{role:"button",tabIndex:0,"aria-expanded":t,onClick:n,onKeyDown:S=>{S.target===S.currentTarget&&(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),n())},className:"flex cursor-pointer flex-wrap items-center gap-x-1.5 gap-y-1 rounded px-1 py-1 hover:bg-primary/10",children:[m.jsx(Ps,{className:et("shrink-0 text-xs text-muted-foreground transition-transform",t&&"rotate-90")}),m.jsx("span",{className:"shrink-0 text-xs font-medium text-foreground",children:i}),m.jsx("span",{className:"min-w-0 flex-1 truncate text-xs text-muted-foreground",children:y??"(无预览)"}),x!==null&&m.jsx("span",{className:et("shrink-0 text-xs",e.status==="confirmed"&&"text-primary",e.status==="stale"&&"text-destructive",(e.status==="pending"||e.status==="rejected")&&"text-muted-foreground"),title:e.status==="stale"?"数据已变化,此提案已失效":void 0,children:x}),m.jsxs("span",{className:"ml-auto flex shrink-0 gap-1",children:[m.jsx(de,{size:"small",type:"primary",disabled:a,onClick:S=>{S.stopPropagation(),r(e.proposalId)},children:"确认"}),m.jsx(de,{size:"small",disabled:a,onClick:S=>{S.stopPropagation(),o(e.proposalId)},children:"拒绝"})]})]}),t&&m.jsxs("div",{className:"mt-1 space-y-1 pl-5",children:[h!==null&&m.jsx("ul",{className:"max-h-32 space-y-0.5 overflow-auto text-xs whitespace-pre-wrap text-muted-foreground",children:h.map(S=>m.jsx("li",{children:S},S))}),b&&m.jsx("pre",{className:"max-h-32 overflow-auto text-xs whitespace-pre-wrap text-muted-foreground",children:typeof e.preview=="string"?e.preview:JSON.stringify(e.preview,null,2)}),e.status==="stale"&&m.jsx("p",{className:"text-xs text-destructive",children:"数据已变化,此提案已失效"})]})]})}function i7e({proposals:e}){const t=Kt(u=>u.confirmAllProposals),n=Kt(u=>u.rejectAllProposals),r=Kt(u=>u.proposalBatchRunning),[o,s]=d.useState(()=>new Set),i=e.filter(EC).length,a=`本轮提案 · ${e.length} 条(${i} 待处理)`,l=i===0||r,c=u=>{s(p=>{const h=new Set(p);return h.has(u)?h.delete(u):h.add(u),h})};return e.length===0?null:m.jsxs("div",{className:"rounded-lg border border-primary/25 bg-primary/5 p-2",children:[m.jsxs("div",{className:"flex flex-wrap items-center gap-x-1.5 gap-y-1",children:[m.jsx(H2,{className:"shrink-0 text-primary"}),m.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-foreground",children:a}),m.jsxs("span",{className:"ml-auto flex shrink-0 gap-1",children:[m.jsx(de,{size:"small",type:"primary",disabled:l,loading:r,onClick:()=>{t()},children:"全部确认"}),m.jsx(de,{size:"small",disabled:l,onClick:()=>{n()},children:"全部拒绝"})]})]}),m.jsx("div",{className:"mt-1 divide-y divide-border/70",children:e.map(u=>m.jsx(s7e,{proposal:u,expanded:o.has(u.proposalId),onToggle:()=>c(u.proposalId)},u.proposalId))})]})}function a7e(){const e=Kt(l=>l.focusContext),t=Kt(l=>l.clearFocusContext),n=lt(l=>l.outline),r=lt(l=>l.config),[o,s]=d.useState(void 0),i=d.useMemo(()=>n===null||r===null?void 0:C_(n,r.deductionNodes).length,[n,r]),a=e?.focus_entity_id??e?.focus_node_id??null;return d.useEffect(()=>{if(s(void 0),a===null)return;let l=!1;return N_([a]).then(c=>{l||s(c.names[a]?.name??null)}).catch(()=>{l||s(null)}),()=>{l=!0}},[a]),e?m.jsx("div",{className:"flex shrink-0 items-center gap-1.5 border-t border-border bg-muted px-3 py-1.5",children:m.jsxs(Td,{icon:m.jsx(H2,{}),closable:!0,onClose:l=>{l.preventDefault(),t()},style:{marginInlineEnd:0},children:["正在讨论:",HBe(e,o,i)]})}):null}function l7e(){return m.jsxs(m.Fragment,{children:[m.jsx(a7e,{}),m.jsx(c7e,{})]})}function c7e(){const[e,t]=d.useState(""),n=Kt(i=>i.streaming),r=Kt(i=>i.sendMessage),o=Kt(i=>i.focusInputSeq),s=d.useRef(null);return d.useEffect(()=>{o>0&&s.current?.inputElement?.focus()},[o]),m.jsxs("div",{className:"shrink-0 border-t border-border px-3 py-3",children:[m.jsx(iP,{ref:s,value:e,onChange:i=>t(i),onSubmit:i=>{const a=i.trim();a===""||n||(r(a),t(""))},placeholder:n?"AI 思考中…":"输入消息…",loading:n}),m.jsx(VBe,{}),m.jsx(ABe,{})]})}const u7e=32;function d7e(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=u7e}function f7e({disabled:e}){const t=Kt(C=>C.messages),n=Kt(C=>C.messagesLoading),r=Kt(C=>C.streaming),o=Kt(C=>C.statusNote),s=Kt(C=>C.streamTools),i=Kt(C=>C.proposals),a=d.useRef(null),l=d.useRef(!0),c=d.useRef(r),u=d.useRef(n),p=d.useMemo(()=>{const C=new Map;for(const E of t)E.role==="tool"&&E.toolCallId&&C.set(E.toolCallId,E);return C},[t]),h=d.useMemo(()=>new Map(s.map(C=>[C.id,C])),[s]),b=d.useMemo(()=>{const C=new Set;for(const E of i)E.toolCallId!==void 0&&C.add(E.toolCallId);return C},[i]);d.useEffect(()=>{(r&&!c.current||n&&!u.current)&&(l.current=!0),c.current=r,u.current=n},[r,n]);const y=t.length;d.useEffect(()=>{const C=a.current;C&&l.current&&(C.scrollTop=C.scrollHeight)},[y,t,n,s.length,i.length,o]);const x=r&&t.length>0&&t[t.length-1].role==="assistant"&&(t[t.length-1].content??"").trim()==="";if(e)return m.jsxs("div",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-2 p-4",children:[m.jsx(Bw,{className:"text-2xl text-muted-foreground/70"}),m.jsx("p",{className:"text-sm text-muted-foreground/70",children:"打开项目后可用"})]});if(n)return m.jsx("div",{className:"flex min-h-0 flex-1 flex-col gap-3 p-4",children:[0,1].map(C=>m.jsx("div",{className:et(wr,"rounded-lg bg-muted/60"),style:{height:40,width:C%2?"70%":"90%"}},C))});const S=t.length===0&&s.length===0&&i.length===0;return m.jsx("div",{ref:a,onScroll:C=>{l.current=d7e(C.currentTarget)},className:"min-h-0 flex-1 overflow-y-auto px-3 py-3",children:S?m.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-1.5 p-4 text-center",children:[m.jsx(Bw,{className:"text-2xl text-muted-foreground/70"}),m.jsx("p",{className:"text-sm text-muted-foreground",children:"试试问:这个设定有没有漏洞?"}),m.jsx("p",{className:"text-sm text-muted-foreground",children:"第 4 章剧情往哪走合理?"})]}):m.jsxs("div",{className:"flex flex-col gap-3",children:[t.map(C=>m.jsx(r7e,{message:C,streaming:r&&C.id===t[t.length-1]?.id,toolResults:p,liveTools:C.id===t[t.length-1]?.id?h:void 0,liveProposalToolCallIds:b},C.id)),x&&m.jsx(mu,{loading:!0,content:""}),o!==null&&r&&m.jsx("p",{className:"text-xs text-muted-foreground",children:o}),i.length>0&&m.jsx(i7e,{proposals:i})]})})}function LV({onClose:e,reserveShellToggle:t=!1}){const r=!lt(o=>o.config);return m.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[m.jsx(qBe,{disabled:r,onClose:e,reserveShellToggle:t}),!r&&m.jsxs(m.Fragment,{children:[m.jsx(GBe,{}),m.jsx(KBe,{})]}),m.jsx(f7e,{disabled:r}),!r&&m.jsx(l7e,{})]})}function m7e({open:e,onClose:t,width:n,reserveShellToggle:r=!1}){return Ig("(min-width: 1024px)")?m.jsx("aside",{className:"flex min-w-0 flex-[4_1_40%] flex-col border-l border-border bg-background",style:n!==void 0?{flex:`0 1 ${n}px`,minWidth:jy}:void 0,children:m.jsx(LV,{reserveShellToggle:r})}):e?m.jsxs("div",{className:"fixed inset-0 z-50",children:[m.jsx("div",{className:"absolute inset-0 animate-in bg-foreground/40 fade-in",onClick:t}),m.jsx("div",{className:"absolute inset-y-0 right-0 w-[85vw] max-w-md animate-in border-l border-border bg-background shadow-xl duration-300 slide-in-from-right",children:m.jsx(LV,{onClose:t})})]}):null}const LM=GY/1e3;function p7e(e,t){return e!==null&&e.id!==t}function h7e(){const e=$e(n=>n.confirmState),t=$e(n=>n.resolveConfirm);return e===null?null:m.jsx(Mi,{title:e.title,description:e.description??"",confirmLabel:"确认",danger:e.danger,onConfirm:async()=>t(!0),onClose:()=>t(!1)})}function g7e(){const e=$e(s=>s.toast),t=$e(s=>s.error),n=$e(s=>s.clearError),{message:r}=uj.useApp(),o=d.useRef(null);return d.useEffect(()=>{!e||!p7e(e,o.current)||(o.current=e.id,e.kind==="error"?r.error(e.text,LM):e.kind==="info"?r.info(e.text,LM):r.success(e.text,LM))},[e,r]),m.jsxs(m.Fragment,{children:[m.jsx(h7e,{}),t&&m.jsxs("div",{role:"alert",className:"fixed top-4 left-1/2 z-50 flex w-[min(92vw,32rem)] -translate-x-1/2 items-center gap-2 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive shadow-lg",children:[m.jsx(Dg,{className:"shrink-0 text-base"}),m.jsx("p",{className:"min-w-0 flex-1",children:t.message}),m.jsx(de,{color:"default",variant:"text",size:"small","aria-label":"关闭错误提示",onClick:n,icon:m.jsx(Es,{className:"text-base"})})]})]})}function zV({title:e,lines:t}){return m.jsxs("div",{className:"rounded-lg border border-border p-3",children:[m.jsx("p",{className:"mb-2 text-sm font-medium",children:e}),m.jsx("dl",{className:"flex flex-col gap-1 text-xs",children:t.map(n=>m.jsxs("div",{className:"flex gap-2",children:[m.jsx("dt",{className:"w-10 shrink-0 text-muted-foreground",children:n.label}),m.jsx("dd",{className:"min-w-0 flex-1 break-all",children:n.value})]},n.label))})]})}function b7e(){const e=_n(b=>b.conflictOpen),t=_n(b=>b.status),n=_n(b=>b.localLatest),r=_n(b=>b.localLatestUnavailable),o=_n(b=>b.pullConflictKeepCloud),s=_n(b=>b.busy),i=_n(b=>b.lastError),a=_n(b=>b.closeConflict),l=_n(b=>b.push),c=lt(b=>b.config?.kind),u=Rx(c);if(!e)return null;const p=t?.remote?.backups[0]??null,h=u==="novel";return m.jsx(bo,{open:!0,onOpenChange:b=>!b&&s===null&&a(),children:m.jsxs(yo,{className:"sm:max-w-lg",children:[m.jsx(lo,{children:m.jsx(co,{children:"两边都有改动"})}),m.jsx("p",{className:"text-sm text-muted-foreground",children:"云端和本机各自都有新备份——选一边作为当前内容,另一边不会丢:两边都会各留一份备份 (保留云端 = 本机当前状态先自动快照;用本机覆盖 = 云端那份先下载存进本机备份)。"}),m.jsxs("div",{className:"mt-1 grid grid-cols-2 gap-3",children:[m.jsx(zV,{title:"云端那份",lines:p===null?[{label:"状态",value:"(无法读取云端列表)"}]:[{label:"时间",value:Da(p.createdAt)},{label:"类型",value:zd[p.kind]},...p.name!==void 0?[{label:"标签",value:p.name}]:[],{label:"设备",value:p.device},...h&&p.stats!==void 0?[{label:"统计",value:uw(p.stats)}]:[],{label:"大小",value:du(p.size)}]}),m.jsx(zV,{title:"本机最新份",lines:n===null?[{label:"状态",value:"(本机还没有备份)"}]:[{label:"时间",value:Da(n.createdAt)},{label:"类型",value:zd[n.kind]},...n.name!==void 0?[{label:"标签",value:n.name}]:[],{label:"设备",value:n.device},...h&&n.stats!==void 0?[{label:"统计",value:uw(n.stats)}]:[],{label:"大小",value:du(n.size)}]})]}),i!==null&&m.jsx("p",{className:"mt-1 text-xs text-destructive",children:i}),r&&m.jsx("p",{className:"mt-1 text-xs text-destructive",children:"本机备份列表读取失败——无法确认本机有没有可用备份,先刷新设置页面板再裁决。"}),n===null&&!r&&m.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"本机还没有备份,先在设置页「立即备份」生成一份,才能用本机覆盖云端。"}),m.jsxs(xo,{children:[m.jsx(de,{disabled:s!==null||p===null,loading:s==="pull",onClick:()=>{o()},children:"保留云端(拉取覆盖本机)"}),m.jsx(de,{disabled:s!==null||n===null||r,loading:s==="push",onClick:()=>{l({force:!0})},children:"用本机覆盖云端"})]})]})})}function y7e(){const e=_n(a=>a.pullTarget),t=_n(a=>a.busy),n=_n(a=>a.closePullConfirm),r=_n(a=>a.pull),o=lt(a=>a.config?.kind),s=Rx(o);if(e===null)return null;const i=a2(e,s);return m.jsx(Mi,{title:"从云端拉取",description:`${Da(e.createdAt)} · ${zd[e.kind]}${e.name!==void 0?` · ${e.name}`:""} · ${i} · ${du(e.size)}。本机当前状态将先自动快照到本地备份(可回退);正文/参考资料/项目规则会随覆盖被云端那份替换(包内没有规则时本机规则会被清除);本机对话历史不受影响——会话不进云端。`,confirmLabel:"拉取",danger:!0,onConfirm:()=>r(e),onClose:()=>{t===null&&n()}})}function x7e(){const e=_n(u=>u.staleDialogOpen),t=_n(u=>u.localLatest),n=_n(u=>u.localLatestUnavailable),r=_n(u=>u.busy),o=_n(u=>u.lastError),s=_n(u=>u.closeStaleDialog),i=_n(u=>u.pushAfterFreshBackup),a=_n(u=>u.push);if(!e)return null;const l=t,c=l===null?"本机还没有任何备份":`${Da(l.createdAt)} · ${zd[l.kind]}${l.name!==void 0?` · ${l.name}`:""}`;return m.jsx(bo,{open:!0,onOpenChange:u=>!u&&r===null&&s(),children:m.jsxs(yo,{className:"sm:max-w-md",children:[m.jsx(lo,{children:m.jsx(co,{children:"有改动还没进备份"})}),m.jsxs("p",{className:"text-sm text-muted-foreground",children:["最新一份本地备份是「",c,"」,比本机最新改动要早——现在同步的话,云端只能拿到这份旧内容。 云端不会自动替你生成备份(备份始终归本机):"]}),m.jsxs("ul",{className:"flex flex-col gap-1 text-xs text-muted-foreground",children:[m.jsx("li",{children:"· 立即手动备份并推送:先生成一份包含当前改动的备份,再推上去(推荐,换机器时内容完整)。"}),m.jsx("li",{children:"· 上传旧备份:只把上面那份旧包推上去(云端内容会落后于本机)。"})]}),o!==null&&m.jsx("p",{className:"text-xs text-destructive",children:o}),t===null&&!n&&m.jsx("p",{className:"text-xs text-muted-foreground",children:"本机还没有备份,「上传旧备份」不可用——用左边那条先生成一份。"}),n&&m.jsx("p",{className:"text-xs text-destructive",children:"本机备份列表读取失败,无法确认有没有可上传的旧备份。"}),m.jsxs(xo,{children:[m.jsx(de,{disabled:r!==null||t===null||n,loading:r==="push",onClick:()=>{a()},children:"上传旧备份"}),m.jsx(de,{disabled:r!==null,onClick:()=>{i()},children:"立即手动备份并推送"})]})]})})}function v7e({chatOpen:e,onToggleChat:t,isDesktop:n,sidebarCollapsed:r,chatCollapsed:o}){const s=$e(i=>i.notifyDataChanged);return m.jsxs("div",{className:et("flex h-12 shrink-0 items-center gap-3 border-b border-border",n&&r?"pl-12":"pl-4",n&&o?"pr-12":"pr-4"),children:[m.jsx(de,{color:"default",variant:"text",size:"small",className:"ml-auto shrink-0",onClick:s,icon:m.jsx(Cte,{className:"text-base"}),"aria-label":"刷新数据",title:"刷新数据"}),!n&&m.jsx(de,{color:"default",variant:e?"filled":"text",size:"small",onClick:t,icon:m.jsx(Bw,{className:"text-base"}),"aria-label":e?"关闭聊天面板":"打开聊天面板"})]})}const BV=["一","二","三","四","五","六","日"],S7e=365,C7e=53,w7e=[1,200,500,1e3],Nre=[0,1,2,3,4],lP=[{key:"7",label:"近7天",days:7},{key:"15",label:"近15天",days:15},{key:"30",label:"近30天",days:30},{key:"month",label:"按月",days:null}],E7e=12;function HV(e){return String(e).padStart(2,"0")}function fg(e,t,n){return`${e}-${HV(t+1)}-${HV(n)}`}function ru(e){const[t,n,r]=e.split("-").map(Number);return{year:t,monthIndex:n-1,day:r}}function Qw(e,t){const{year:n,monthIndex:r,day:o}=ru(e),s=new Date(n,r,o+t);return fg(s.getFullYear(),s.getMonth(),s.getDate())}function kre(e,t,n){const r=new Date(e,t+n,1);return{year:r.getFullYear(),monthIndex:r.getMonth()}}function cP(e,t){return new Date(e,t+1,0).getDate()}function Mre(e){const{year:t,monthIndex:n,day:r}=ru(e);return(new Date(t,n,r).getDay()+6)%7}function $7e(e,t){const n=Array.from({length:Mre(fg(e,t,1))},()=>null);for(let o=1;o<=cP(e,t);o+=1)n.push(fg(e,t,o));for(;n.length%7!==0;)n.push(null);const r=[];for(let o=0;o<n.length;o+=7)r.push(n.slice(o,o+7));return r}function Rre(e,t){return`${e}年${t+1}月`}function Ire(e){const{monthIndex:t,day:n}=ru(e);return`${t+1}月${n}日`}function T7e(e,t){return Array.from({length:t},(n,r)=>Qw(e,r-t+1))}function N7e(e,t){const{year:n,monthIndex:r}=ru(e);return Array.from({length:t},(o,s)=>kre(n,r,s-t+1))}function Are(e){return new Map(e.map(t=>[t.date,t.chars]))}function uP(e,t,n){let r=0,o=0;for(let s=1;s<=cP(t,n);s+=1){const i=e.get(fg(t,n,s))??0;i>0&&(r+=i,o+=1)}return{chars:r,activeDays:o}}function k7e(e,t,n){const r=Are(e);if(n==="month")return N7e(t,E7e).map(({year:s,monthIndex:i})=>({key:fg(s,i,1),label:`${i+1}月`,title:Rre(s,i),chars:uP(r,s,i).chars}));const o=lP.find(s=>s.key===n)?.days??0;return T7e(t,o).map(s=>({key:s,label:String(ru(s).day),title:Ire(s),chars:r.get(s)??0}))}function M7e(e){if(e.length===0)return{total:0,average:0,max:0};const t=e.reduce((n,r)=>n+r,0);return{total:t,average:Math.round(t/e.length),max:Math.max(...e)}}function R7e(e){if(e<=0)return 0;let t=0;for(const n of w7e)e>=n&&(t+=1);return Nre[t]??0}function I7e(e){return{from:Qw(e,-364),to:e}}function A7e(e){const{from:t}=I7e(e),n=Qw(t,-Mre(t));return Array.from({length:C7e},(r,o)=>Array.from({length:7},(s,i)=>{const a=Qw(n,o*7+i);return a<t||a>e?null:a}))}function xi(e){return String(e).replace(/\B(?=(\d{3})+(?!\d))/g,",")}const O7e=1e4,_7e=5e3;function j7e(e,t,n){const r=e.lastEditAt===null?null:n-e.lastEditAt,o=r!==null&&r>=0&&r<=O7e?e.typingMs+r:e.typingMs;return{chars:e.chars+Math.max(0,t),typingMs:o,lastEditAt:n}}function FV(e){const t=Math.max(0,Math.floor(e/1e3)),n=r=>String(r).padStart(2,"0");return`${n(Math.floor(t/3600))}:${n(Math.floor(t%3600/60))}:${n(t%60)}`}function P7e(e,t){return t<_7e?"—":xi(Math.round(e/(t/36e5)))}const VV={chars:0,typingMs:0,lastEditAt:null,visible:!1,dismissed:!1,hasAutoOpened:!1},nd=Ix((e,t)=>({...VV,projectId:null,syncProject:n=>{t().projectId!==n&&e({...VV,projectId:n})},recordDelta:(n,r,o)=>{const s=t(),i=s.projectId===n,a=j7e(i?{chars:s.chars,typingMs:s.typingMs,lastEditAt:s.lastEditAt}:{chars:0,typingMs:0,lastEditAt:null},r,o),l=r>0&&!(i&&s.dismissed)&&!(i&&s.hasAutoOpened);e({projectId:n,...a,visible:l||(i?s.visible:!1),dismissed:i?s.dismissed:!1,hasAutoOpened:i&&s.hasAutoOpened||r>0})},open:()=>e({visible:!0}),dismiss:()=>e({visible:!1,dismissed:!0})})),Ore="ai-editor:stats-panel",UV=240,dd=8,JA=16,ex=64;function D7e(e){if(e===null)return null;try{const t=JSON.parse(e);if(typeof t!="object"||t===null)return null;const{left:n,top:r}=t;return typeof n!="number"||typeof r!="number"||!Number.isFinite(n)||!Number.isFinite(r)||n<0||r<0?null:{left:n,top:r}}catch{return null}}function eO(e,t,n){const r=Math.max(dd,t.width-n.width-dd),o=Math.max(dd,t.height-n.height-ex);return{left:Math.min(Math.max(e.left,dd),r),top:Math.min(Math.max(e.top,dd),o)}}function WV(e,t){return eO({left:e.width-t.width-JA,top:e.height-t.height-ex},e,t)}function L7e(e,t,n){return e===null?WV(t,n):e.left>=dd&&e.top>=dd&&e.left<=t.width-n.width-dd&&e.top<=t.height-n.height-ex?e:WV(t,n)}function z7e(){try{return D7e(globalThis.localStorage?.getItem(Ore)??null)}catch{return null}}function B7e(e){try{globalThis.localStorage?.setItem(Ore,JSON.stringify(e))}catch{}}function AS({label:e,value:t}){return m.jsxs("div",{children:[m.jsx("div",{className:"text-xs text-muted-foreground",children:e}),m.jsx("div",{className:"text-xl tabular-nums",children:t})]})}function H7e({focusMode:e}){const t=lt(R=>R.config),n=t?.id??null,r=nd(R=>R.syncProject),o=nd(R=>R.chars),s=nd(R=>R.typingMs),i=nd(R=>R.lastEditAt),a=nd(R=>R.visible),l=nd(R=>R.open),c=nd(R=>R.dismiss),[u,p]=d.useState(()=>Date.now()),[h,b]=d.useState(null),[y,x]=d.useState(!1),S=d.useRef(null),C=d.useRef(null),E=d.useRef({x:0,y:0});d.useLayoutEffect(()=>{r(n)},[n,r]),d.useEffect(()=>{if(!a||e)return;p(Date.now());const R=setInterval(()=>p(Date.now()),1e3);return()=>clearInterval(R)},[a,e]),d.useLayoutEffect(()=>{if(!a)return;const R=S.current,A=C.current;if(R===null||A===null)return;const O=()=>{const L=R.getBoundingClientRect(),z={width:A.offsetWidth,height:A.offsetHeight};b(I=>eO(I??L7e(z7e(),L,z),L,z))};if(O(),typeof ResizeObserver>"u")return;const j=new ResizeObserver(()=>O());return j.observe(R),()=>j.disconnect()},[a,e]),d.useEffect(()=>{if(y)return document.body.classList.add("select-none"),()=>document.body.classList.remove("select-none")},[y]);function w(R,A){const O=S.current,j=C.current;if(O===null||j===null)return null;const L=O.getBoundingClientRect();return eO({left:R-L.left-E.current.x,top:A-L.top-E.current.y},L,{width:j.offsetWidth,height:j.offsetHeight})}function $(R){const A=C.current;if(A===null)return;const O=A.getBoundingClientRect();E.current={x:R.clientX-O.left,y:R.clientY-O.top},R.currentTarget.setPointerCapture(R.pointerId),x(!0)}function N(R){if(!y)return;const A=w(R.clientX,R.clientY);A!==null&&b(A)}function M(R){if(!y)return;x(!1),R.currentTarget.hasPointerCapture(R.pointerId)&&R.currentTarget.releasePointerCapture(R.pointerId);const A=w(R.clientX,R.clientY);A!==null&&(b(A),B7e(A))}if(t===null||t.kind==="practice"||e)return null;const k=i===null?0:u-i;return m.jsxs("div",{ref:S,className:"pointer-events-none absolute inset-0 z-20",children:[!a&&m.jsx(Jd,{icon:m.jsx(jte,{className:"text-base"}),"aria-label":"码字统计",tooltip:{title:"码字统计",placement:"left"},onClick:l,className:"pointer-events-auto",style:{position:"absolute",insetInlineEnd:JA,bottom:ex,zIndex:20}}),a&&m.jsxs("div",{ref:C,role:"region","aria-label":"码字统计",onPointerDown:$,onPointerMove:N,onPointerUp:M,onPointerCancel:M,className:et("pointer-events-auto absolute touch-none rounded-lg bg-popover p-3 shadow-md ring-1 ring-foreground/10",y?"cursor-grabbing":"cursor-grab"),style:h===null?{width:UV,insetInlineEnd:JA,bottom:ex}:{width:UV,left:h.left,top:h.top},children:[m.jsxs("div",{className:"flex items-start justify-between gap-2",children:[m.jsxs("div",{className:"min-w-0",children:[m.jsx(Ar.Title,{level:5,children:"码字统计 · 本次"}),m.jsx("div",{className:"text-xs text-muted-foreground",children:"拖动面板移动"})]}),m.jsx(de,{size:"small",color:"default",variant:"text",icon:m.jsx(Es,{}),"aria-label":"关闭码字统计",className:"shrink-0",onPointerDown:R=>R.stopPropagation(),onClick:c})]}),m.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-3",children:[m.jsx(AS,{label:"本次码字",value:xi(o)}),m.jsx(AS,{label:"码字速率(字/时)",value:P7e(o,s)}),m.jsx(AS,{label:"码字时间",value:FV(s)}),m.jsx(AS,{label:"空闲时间",value:FV(k)})]})]})]})}function F7e({route:e,chatOpen:t,onToggleChat:n,onOpenChat:r,isDesktop:o,sidebarCollapsed:s,chatCollapsed:i,focusMode:a=!1,children:l}){const c=lt(S=>S.loadConfig),u=lt(S=>S.config),p=$e(S=>S.currentFocus),h=Kt(S=>S.setFocusContext),b=Kt(S=>S.requestFocusInput),y=$e(S=>S.clearCurrentFocus),x=$e(S=>S.setFocusMode);return d.useEffect(()=>{c()},[c]),d.useLayoutEffect(()=>{y(),x(!1)},[e.path,y,x]),m.jsxs("main",{className:"relative flex min-w-0 flex-[5_1_50%] flex-col",style:o?{flex:"1 1 0%",minWidth:b0e}:void 0,children:[!a&&m.jsx(v7e,{chatOpen:t,onToggleChat:n,isDesktop:o,sidebarCollapsed:s,chatCollapsed:i}),m.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-6",children:l}),m.jsx(H7e,{focusMode:a}),!a&&m.jsx(Jd,{icon:m.jsx(Dte,{className:"text-xl"}),type:"primary","aria-label":"问 AI",tooltip:{title:u?p?.focus_deduction===!0?"带着推演节点去问 AI":p?"带着当前页面上下文去问 AI":"去问 AI":"打开项目后可用",placement:"left"},onClick:()=>{if(!u){$e.getState().showToast("打开项目后可用","info");return}h(p),b();const S=r();!p&&!S&&$e.getState().showToast("未选中具体条目,可直接在右栏提问","info")},style:{position:"absolute",insetInlineEnd:16,bottom:16,zIndex:30}})]})}function V7e({side:e,className:t}){return m.jsxs("svg",{width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",className:et("shrink-0",t),children:[m.jsx("rect",{x:3,y:4,width:18,height:16,rx:2.5}),m.jsx("path",{d:e==="left"?"M9 4 V20":"M15 4 V20"})]})}function kl({side:e,collapsed:t,label:n,onToggle:r}){const o=`${t?"展开":"收起"}${n}`;return m.jsx(de,{color:"default",variant:"text",size:"small",onClick:r,icon:m.jsx(V7e,{side:e}),"aria-label":o,title:o,"aria-expanded":!t})}function U7e({sidebarCollapsed:e,chatCollapsed:t,onToggleSidebar:n,onToggleChat:r}){return m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"absolute left-4 top-3",children:m.jsx(kl,{side:"left",collapsed:e,label:"左栏",onToggle:n})}),m.jsx("div",{className:"absolute right-4 top-3",children:m.jsx(kl,{side:"right",collapsed:t,label:"右栏",onToggle:r})})]})}function W7e({className:e}){return m.jsx("svg",{width:16,height:16,viewBox:"0 0 64 64","aria-hidden":"true",focusable:"false",className:et("shrink-0",e),children:m.jsxs("g",{fill:"none",stroke:"currentColor",strokeLinecap:"round",children:[m.jsx("path",{d:"M12 10 V54",strokeWidth:7}),m.jsx("path",{d:"M26 18 H55",strokeWidth:6}),m.jsx("path",{d:"M26 32 H44",strokeWidth:6}),m.jsx("path",{d:"M26 46 H35",strokeWidth:6})]})})}const q7e={key:"/trash",icon:m.jsx(ss,{}),label:"回收站"},G7e={novel:{brandLabel:"书架",items:[{key:"/writing",icon:m.jsx(cc,{}),label:"写作"},{key:"/outline",icon:m.jsx(hAe,{}),label:"大纲"},{key:"/canvas",icon:m.jsx(tOe,{}),label:"大纲画布"},{key:"/characters",icon:m.jsx(N_e,{}),label:"人物"},{key:"/setting",icon:m.jsx(E_e,{}),label:"设定"},{key:"/locations",icon:m.jsx(oOe,{}),label:"地点"},{key:"/hooks",icon:m.jsx(r_e,{}),label:"伏笔"},{key:"/timeline",icon:m.jsx(hOe,{}),label:"时间轴"},{key:"/relations",icon:m.jsx(y_e,{}),label:"关联"},{key:"/references",icon:m.jsx(IH,{}),label:"参考资料"},{key:"/stats",icon:m.jsx(jte,{}),label:"码字统计"}],trash:!0,projectOverview:!0},practice:{brandLabel:"文风练习",items:[{key:"/author",icon:m.jsx(H_e,{}),label:"作家介绍"},{key:"/works",icon:m.jsx(IH,{}),label:"作品介绍"},{key:"/style",icon:m.jsx(H2,{}),label:"作家风格说明"},{key:"/practice",icon:m.jsx(EOe,{}),label:"文风练习"},{key:"/free",icon:m.jsx(cc,{}),label:"自由练习"}],trash:!1,projectOverview:!1}},qV="ai-editor:theme";function K7e(){const[e,t]=d.useState("light");d.useEffect(()=>{const o=localStorage.getItem(qV)==="dark"?"dark":"light";t(o),document.documentElement.classList.toggle("dark",o==="dark")},[]);function n(){const r=e==="dark"?"light":"dark";localStorage.setItem(qV,r),document.documentElement.classList.toggle("dark",r==="dark"),t(r)}return{theme:e,toggleTheme:n}}function X7e(e){const t=e.segments[0];return t===void 0||t==="overview"?null:t==="timepoints"?"/timeline":`/${t}`}function Y7e({width:e,reserveShellToggle:t=!1}){const{theme:n,toggleTheme:r}=K7e(),o=lt($=>$.config),s=lt($=>$.loadError),i=$e($=>$.showToast),a=yY(),[l,c]=d.useState(!1),u=_n($=>$.status),p=_n($=>$.busy),h=_n($=>$.syncNow),b=P0e(u);async function y(){if(!(o===null||l)){c(!0);try{await i2(),i("已备份")}catch($){i($ instanceof Ze&&$.code!==yn?$.message:"无法连接服务,备份失败","error")}finally{c(!1)}}}const x=s==="NO_PROJECT_OPEN",S=X7e(a),C=a.segments[0]==="overview",E=G7e[Rx(o?.kind)],w=E.items.map($=>({...$,disabled:x}));return m.jsxs("aside",{className:"flex min-w-0 flex-col border-r border-border bg-background",style:e!==void 0?{flex:`0 1 ${e}px`,minWidth:_y}:{flex:"1 1 10%"},children:[m.jsx("div",{className:et("flex h-12 shrink-0 items-center gap-1 border-b border-border pr-2",t?"pl-12":"pl-2"),children:m.jsxs("a",{href:"#/",title:"回到书架主页",className:"flex min-w-0 flex-1 items-center gap-1.5 rounded-md px-2 py-1.5",children:[m.jsx(W7e,{}),m.jsx("span",{className:"whitespace-nowrap text-base italic",children:E.brandLabel})]})}),m.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-2 py-2",children:[E.projectOverview&&m.jsx(de,{color:"default",variant:C?"filled":"text",block:!0,className:"mb-1",icon:m.jsx(HI,{}),disabled:x,title:x?"先在书架打开一本书":`打开《${o?.name??""}》概览`,onClick:()=>en("/overview"),children:m.jsx("span",{className:"min-w-0 flex-1 truncate text-left text-sm",children:o?.name??"概览"})}),m.jsx(Qd,{mode:"inline",selectedKeys:S!==null?[S]:[],items:[...w,...E.trash?[{type:"divider",key:"divider"},{...q7e,disabled:x}]:[]],onClick:({key:$})=>en($)})]}),m.jsxs("div",{className:"flex shrink-0 flex-col gap-1 border-t border-border px-2 py-2",children:[m.jsx(de,{color:"default",variant:"text",block:!0,icon:m.jsx(F2,{}),disabled:o===null,loading:l,onClick:()=>{y()},children:m.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:"立即备份"})}),m.jsxs(de,{color:"default",variant:"text",block:!0,icon:m.jsx(YAe,{}),disabled:o===null,loading:p!==null,onClick:()=>{h()},title:"同步云端(推送 / 拉取)",children:[m.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:"同步云端"}),b!==null&&m.jsx(Cj,{dot:!0,color:b==="error"?"var(--ant-color-error)":"var(--ant-color-warning)",className:"shrink-0"})]}),m.jsx(de,{color:"default",variant:"text",block:!0,icon:m.jsx(h_e,{}),onClick:()=>en("/preferences"),children:m.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:"设置"})}),m.jsx(de,{color:"default",variant:"text",block:!0,icon:n==="dark"?m.jsx(S_e,{}):m.jsx(KOe,{}),onClick:r,"aria-label":"切换主题",children:m.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:n==="dark"?"浅色模式":"深色模式"})})]})]})}function tx({label:e,active:t,onStart:n,onMove:r,onEnd:o}){return m.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":e,title:e,onPointerDown:s=>{s.preventDefault(),s.currentTarget.setPointerCapture(s.pointerId),n(s.clientX)},onPointerMove:s=>r(s.clientX),onPointerUp:o,onPointerCancel:o,className:et("group relative z-10 h-full w-1.5 shrink-0 cursor-col-resize touch-none bg-transparent transition-colors hover:bg-border",t&&"bg-border"),children:m.jsx(Ete,{className:"absolute inset-y-0 left-1/2 text-base -translate-x-1/2 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"})})}function Z7e({route:e,children:t}){const[n,r]=d.useState(!1),{layout:o,isDesktop:s,dragSide:i,toggleCollapse:a,startResize:l,moveResize:c,endResize:u}=S0e(),p=i!==null,h=$e(S=>S.focusMode);q0e(),d.useEffect(()=>{const S=l2();if(S)return S.onFlushRequest(()=>Lye(tZ()))},[]),d.useEffect(()=>{if(!s||h)return;function S(C){const E=Hye({key:C.key,ctrlKey:C.ctrlKey,metaKey:C.metaKey,altKey:C.altKey,shiftKey:C.shiftKey,target:C.target instanceof Element?C.target:null});E===null||C.repeat||(C.preventDefault(),a(E))}return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[s,h,a]);const b=lt(S=>S.config?.id??null),y=_n(S=>S.refresh),x=_n(S=>S.clearStatus);return d.useEffect(()=>{if(b===null){x();return}y()},[b,y,x]),m.jsxs("div",{className:et("relative flex h-screen overflow-hidden",p&&"select-none"),children:[!h&&m.jsx(m.Fragment,{children:(!s||!o.collapsedSidebar)&&m.jsxs(m.Fragment,{children:[m.jsx(Y7e,{width:s?o.sidebarWidth:void 0,reserveShellToggle:s}),s&&m.jsx(tx,{label:"调整左栏宽度",active:i==="sidebar",onStart:S=>l("sidebar",S),onMove:S=>c("sidebar",S),onEnd:u})]})}),m.jsx(F7e,{isDesktop:s,route:e,focusMode:h,chatOpen:n,sidebarCollapsed:o.collapsedSidebar,chatCollapsed:o.collapsedChat,onToggleChat:()=>r(S=>!S),onOpenChat:()=>s?o.collapsedChat?(a("chat"),!0):!1:n?!1:(r(!0),!0),children:t}),!h&&m.jsxs(m.Fragment,{children:[s&&!o.collapsedChat&&m.jsx(tx,{label:"调整右栏宽度",active:i==="chat",onStart:S=>l("chat",S),onMove:S=>c("chat",S),onEnd:u}),(!s||!o.collapsedChat)&&m.jsx(m7e,{open:n,onClose:()=>r(!1),width:s?o.chatWidth:void 0,reserveShellToggle:s})]}),!h&&s&&m.jsx(U7e,{sidebarCollapsed:o.collapsedSidebar,chatCollapsed:o.collapsedChat,onToggleSidebar:()=>a("sidebar"),onToggleChat:()=>a("chat")}),m.jsx(y7e,{}),m.jsx(b7e,{}),m.jsx(x7e,{}),m.jsx(g7e,{})]})}var $0={},T0={},GV;function Q7e(){if(GV)return T0;GV=1,Object.defineProperty(T0,"__esModule",{value:!0}),T0.default=void 0;const e={items_per_page:"条/页",jump_to:"跳至",jump_to_confirm:"确定",page:"页",prev_page:"上一页",next_page:"下一页",prev_5:"向前 5 页",next_5:"向后 5 页",prev_3:"向前 3 页",next_3:"向后 3 页",page_size:"页码"};return T0.default=e,T0}var N0={},k0={},M0={},KV;function J7e(){if(KV)return M0;KV=1,Object.defineProperty(M0,"__esModule",{value:!0}),M0.default=void 0;var e=Ite();const t={...e.commonLocale,locale:"zh_CN",today:"今天",now:"此刻",backToToday:"返回今天",ok:"确定",timeSelect:"选择时间",dateSelect:"选择日期",weekSelect:"选择周",clear:"清除",week:"周",month:"月",year:"年",previousMonth:"上个月",nextMonth:"下个月",monthSelect:"选择月份",yearSelect:"选择年份",decadeSelect:"选择年代",previousYear:"上一年",nextYear:"下一年",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世纪",nextCentury:"下一世纪",yearFormat:"YYYY年",cellDateFormat:"D",monthBeforeYear:!1};return M0.default=t,M0}var R0={},XV;function _re(){if(XV)return R0;XV=1,Object.defineProperty(R0,"__esModule",{value:!0}),R0.default=void 0;const e={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return R0.default=e,R0}var YV;function jre(){if(YV)return k0;YV=1;var e=pa().default;Object.defineProperty(k0,"__esModule",{value:!0}),k0.default=void 0;var t=e(J7e()),n=e(_re());const r={lang:{placeholder:"请选择日期",yearPlaceholder:"请选择年份",quarterPlaceholder:"请选择季度",monthPlaceholder:"请选择月份",weekPlaceholder:"请选择周",rangePlaceholder:["开始日期","结束日期"],rangeYearPlaceholder:["开始年份","结束年份"],rangeMonthPlaceholder:["开始月份","结束月份"],rangeQuarterPlaceholder:["开始季度","结束季度"],rangeWeekPlaceholder:["开始周","结束周"],...t.default},timePickerLocale:{...n.default}};return r.lang.ok="确定",k0.default=r,k0}var ZV;function e9e(){if(ZV)return N0;ZV=1;var e=pa().default;Object.defineProperty(N0,"__esModule",{value:!0}),N0.default=void 0;var t=e(jre());return N0.default=t.default,N0}var QV;function t9e(){if(QV)return $0;QV=1;var e=pa().default;Object.defineProperty($0,"__esModule",{value:!0}),$0.default=void 0;var t=e(Q7e()),n=e(e9e()),r=e(jre()),o=e(_re());const s="${label}不是一个有效的${type}",i={locale:"zh-cn",Pagination:t.default,DatePicker:r.default,TimePicker:o.default,Calendar:n.default,global:{placeholder:"请选择",close:"关闭",sortable:"可排序",show:"显示",hide:"隐藏"},Table:{filterTitle:"筛选",filterConfirm:"确定",filterReset:"重置",filterEmptyText:"无筛选项",filterCheckAll:"全选",filterSearchPlaceholder:"在筛选项中搜索",emptyText:"暂无数据",selectAll:"全选当页",selectInvert:"反选当页",selectNone:"清空所有",selectionAll:"全选所有",sortTitle:"排序",expand:"展开行",collapse:"关闭行",triggerDesc:"点击降序",triggerAsc:"点击升序",cancelSort:"取消排序"},Modal:{okText:"确定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"结束导览"},Popconfirm:{cancelText:"取消",okText:"确定"},Transfer:{titles:["",""],searchPlaceholder:"请输入搜索内容",itemUnit:"项",itemsUnit:"项",remove:"删除",selectCurrent:"全选当页",removeCurrent:"删除当页",selectAll:"全选所有",deselectAll:"取消全选",removeAll:"删除全部",selectInvert:"反选当页"},Upload:{uploading:"文件上传中",removeFile:"删除文件",uploadError:"上传错误",previewFile:"预览文件",downloadFile:"下载文件"},Empty:{description:"暂无数据"},Icon:{icon:"图标"},Text:{edit:"编辑",copy:"复制",copied:"复制成功",expand:"展开",collapse:"收起"},Carousel:{prevSlide:"上一张幻灯片",nextSlide:"下一张幻灯片"},Form:{optional:"(可选)",defaultValidateMessages:{default:"字段验证错误${label}",required:"请输入${label}",enum:"${label}必须是其中一个[${enum}]",whitespace:"${label}不能为空字符",date:{format:"${label}日期格式无效",parse:"${label}不能转换为日期",invalid:"${label}是一个无效日期"},types:{string:s,method:s,array:s,object:s,number:s,date:s,boolean:s,integer:s,float:s,regexp:s,email:s,url:s,hex:s},string:{len:"${label}须为${len}个字符",min:"${label}最少${min}个字符",max:"${label}最多${max}个字符",range:"${label}须在${min}-${max}字符之间"},number:{len:"${label}必须等于${len}",min:"${label}最小值为${min}",max:"${label}最大值为${max}",range:"${label}须在${min}-${max}之间"},array:{len:"须为${len}个${label}",min:"最少${min}个${label}",max:"最多${max}个${label}",range:"${label}数量须在${min}-${max}之间"},pattern:{mismatch:"${label}与模式不匹配${pattern}"}}},QRCode:{expired:"二维码过期",refresh:"点击刷新",scanned:"已扫描"},ColorPicker:{presetEmpty:"暂无",transparent:"无色",singleColor:"单色",gradientColor:"渐变色"}};return $0.default=i,$0}var zM,JV;function n9e(){return JV||(JV=1,zM=t9e()),zM}var r9e=n9e();const o9e=Ri(r9e);function Pre(){const[e,t]=d.useState(()=>typeof document>"u"?"light":document.documentElement.classList.contains("dark")?"dark":"light");return d.useEffect(()=>{const n=new MutationObserver(()=>{t(document.documentElement.classList.contains("dark")?"dark":"light")});return n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),()=>n.disconnect()},[]),e}const Dre={controlOutlineWidth:0},s9e="ai-editor-theme",eU="#37352f",tU="rgba(255,255,255,0.81)",Lre={...Dre,colorPrimary:eU,colorInfo:eU,colorText:"#37352f",colorTextSecondary:"#5d5b54",colorTextTertiary:"#787671",colorTextQuaternary:"#a4a097",colorBgLayout:"#f6f5f4",colorBgContainer:"#ffffff",colorBgElevated:"#ffffff",colorBorder:"#c8c4be",colorBorderSecondary:"#e5e3df",colorSplit:"#ede9e4",colorFillTertiary:"#f0eeec",colorLink:"#0075de",colorSuccess:"#1aae39",colorWarning:"#dd5b00",colorError:"#e03131"},zre={...Dre,colorPrimary:tU,colorInfo:tU,colorText:"rgba(255,255,255,0.81)",colorTextSecondary:"rgba(255,255,255,0.65)",colorTextTertiary:"rgba(255,255,255,0.51)",colorTextQuaternary:"rgba(255,255,255,0.34)",colorBgLayout:"#191919",colorBgContainer:"#202020",colorBgElevated:"#252525",colorBorder:"#4a4a4a",colorBorderSecondary:"#2f2f2f",colorSplit:"#373737",colorFillTertiary:"rgba(255,255,255,0.055)",colorLink:"#529cca",colorSuccess:"#1aae39",colorWarning:"#dd5b00",colorError:"#e03131"},Bre={Button:{primaryShadow:"none",defaultShadow:"none",dangerShadow:"none"},Card:{bodyPadding:16},Input:{activeShadow:"none"},Typography:{titleMarginBottom:0}},Hre={itemBorderRadius:6,itemHeight:32,itemMarginInline:4,itemBg:"transparent",activeBarBorderWidth:0},Fre={cellPaddingBlock:8},nU={autoComplete:"off"},i9e={horizontalMargin:"0",itemColor:Lre.colorTextSecondary},a9e={horizontalMargin:"0",itemColor:zre.colorTextSecondary},l9e={controlItemBgActive:"#f0eeec",controlItemBgActiveHover:"#f0eeec"},c9e={controlItemBgActive:"#373737",controlItemBgActiveHover:"#373737"},u9e={colorInfoBg:"#f0eeec",colorInfoBorder:"#e5e3df"},d9e={...Lre,...l9e,...u9e},f9e={...zre,...c9e},m9e={...Bre,Menu:Hre,Table:{...Fre,headerBg:"#ffffff",borderColor:"#e5e3df"},Tag:{defaultBg:"#f0eeec"},Tabs:i9e},p9e="#373737",h9e={...Bre,Menu:Hre,Table:{...Fre,headerBg:"#202020",borderColor:"#2f2f2f"},Tag:{defaultBg:p9e},Tabs:a9e};function g9e({children:e}){const n=Pre()==="dark";return m.jsx(gc,{locale:o9e,input:nU,textArea:nU,theme:{cssVar:{key:s9e},algorithm:n?$m.darkAlgorithm:$m.defaultAlgorithm,token:n?f9e:d9e,components:n?h9e:m9e},children:m.jsx(uj,{component:!1,children:e})})}class b9e extends d.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("[ErrorBoundary] 渲染异常:",t,n.componentStack)}render(){const{error:t}=this.state;return t===null?this.props.children:m.jsx("div",{className:"flex h-full min-h-64 flex-col items-center justify-center gap-3 p-8",children:m.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-lg border border-destructive/30 bg-destructive/10 px-8 py-6 text-center",children:[m.jsx(Dg,{className:"text-2xl text-destructive"}),m.jsx("p",{className:"text-base font-medium text-foreground",children:"界面出现异常"}),m.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"数据不会丢失,请重新加载页面继续写作。"}),m.jsx("p",{className:"max-w-md font-mono text-xs break-all text-destructive/80",children:t.message||String(t)}),m.jsxs("div",{className:"mt-2 flex gap-2",children:[m.jsxs(de,{type:"primary",onClick:()=>window.location.reload(),children:[m.jsx(zte,{className:"text-base"}),"重新加载"]}),m.jsx(de,{onClick:()=>{window.location.hash="#/",window.location.reload()},children:"回到首页"})]})]})})}}function tr({title:e,action:t,className:n,children:r}){return m.jsxs(jj,{className:n,children:[e!==void 0&&m.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[m.jsx(Ar.Title,{level:5,children:e}),t]}),r]})}function I0(e){switch(e){case"INVALID_PROJECT_PATH":return"路径无效:请使用绝对路径,且目标目录须已含 project.json(不是项目目录)";case"PROJECT_ALREADY_EXISTS":return"该目录已是项目,请直接打开(书架列表或「打开其他路径」)";case"PROJECT_VERSION_NEWER":return"该项目由更高版本的 ai-editor 创建,请升级程序后再打开(避免降级导致数据丢失)";case"NO_PROJECT_OPEN":return"";case"CLIENT_NETWORK_ERROR":return"无法连接服务,请确认 ai-editor 服务已启动";default:return"操作失败,请稍后重试"}}function y9e(e,t){switch(e){case"PROJECT_ALREADY_EXISTS":return"同名书籍已存在,请换一个书名";case"SCHEMA_VERSION_MISMATCH":return t;case"VALIDATION_ERROR":return t;case"NO_PROJECT_OPEN":return"";case"CLIENT_NETWORK_ERROR":return"无法连接服务,请确认 ai-editor 服务已启动";default:return"导入失败,请稍后重试"}}function x9e(e,t){return e==="CLIENT_NETWORK_ERROR"?"无法连接服务,请确认 ai-editor 服务已启动":t}function v9e(e,t){switch(e){case"INVALID_PROJECT_PATH":return"该书已不在书架目录里(可能已被删除或被移动),请刷新书架";case"CLIENT_NETWORK_ERROR":return"无法连接服务,请确认 ai-editor 服务已启动";case"CLOUD_CONFLICT":case"CLOUD_BACKUP_TOO_LARGE":case"CLOUD_AUTH_FAILED":case"CLOUD_UNREACHABLE":case"CLOUD_QUOTA_EXCEEDED":return`${t===""?"删除前的云端推送未成功":t}——本机未删除任何东西`;default:return t===""?"删除失败,请稍后重试":t}}const rU=!1,S9e=["本地目录连同 .backups/ 里的全部备份一并删除,不可恢复","已启用云备份时,会先把当前状态推送到云端(云端不会停在旧状态)"];function C9e(e){return e===null?{confirmLabel:"删除",force:!1,note:null}:{confirmLabel:"仍要删除",force:!0,note:"仍要删除:最新改动不会上传云端(云端那份保持原样)"}}function w9e(e,t){const n=[`已删除《${t}》`];return e.pushed!==void 0&&n.push(`(删前已推送一份 ${e.pushed.fileName} 到云端)`),e.remoteDeleted===!0&&n.push("(云端备份也已删除)"),e.remoteError!==void 0?{text:`${n.join("")}——云端备份未能删除(${e.remoteError.message}),可到云盘网页手动清理`,kind:"error"}:{text:n.join(""),kind:"success"}}function E9e({book:e,onDeleted:t,onOpenChange:n}){const[r,o]=d.useState(rU),[s,i]=d.useState(!1),[a,l]=d.useState(null),c=C9e(a);function u(){l(null),o(rU)}function p(){s||(u(),n(!1))}async function h(b){if(!(e===null||s)){i(!0),l(null);try{const y=await jbe({path:e.path,force:b,delete_remote:r}),x=w9e(y,e.name);$e.getState().showToast(x.text,x.kind),u(),n(!1),t(e)}catch(y){l(v9e(y instanceof Ze?y.code:null,y instanceof Ze?y.message:""))}finally{i(!1)}}}return m.jsx(bo,{open:e!==null,onOpenChange:b=>{b||p()},children:m.jsxs(yo,{className:"sm:max-w-md",children:[m.jsxs(lo,{children:[m.jsxs(co,{children:["删除《",e?.name,"》"]}),m.jsx(hu,{children:"删除不可恢复。这次删除会做三件事:"})]}),m.jsx("ul",{className:"list-disc space-y-1 pl-5 text-sm text-muted-foreground",children:S9e.map(b=>m.jsx("li",{children:b},b))}),m.jsx(lg,{checked:r,onChange:b=>o(b.target.checked),disabled:s,children:"同时删除云端备份"}),a!==null&&m.jsx("p",{className:"text-sm text-destructive",children:a}),c.note!==null&&m.jsx("p",{className:"text-sm text-destructive",children:c.note}),m.jsxs(xo,{children:[m.jsx(de,{onClick:p,disabled:s,children:"取消"}),m.jsx(de,{type:"primary",danger:!0,loading:s,onClick:()=>{h(c.force)},children:c.confirmLabel})]})]})})}const $9e={sm:"py-10",md:"py-12",lg:"py-14"};function Hn({children:e,icon:t,action:n,padding:r="md",className:o}){return m.jsxs("div",{className:et("rounded-lg border border-dashed border-border px-6 text-center",$9e[r],o),children:[t,m.jsx(ud,{image:!1,classNames:{image:"hidden"},description:e}),n&&m.jsx("div",{className:"mt-4",children:n})]})}const BM=["sky","sage","yellow"];function T9e(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t>>>0}const N9e={sky:"bg-tag-sky",sage:"bg-tag-sage",yellow:"bg-tag-yellow"};function k9e(e){const t=e.trim();return t===""?BM[0]:BM[T9e(t)%BM.length]}function dP(e){return N9e[k9e(e)]}const Vre="inline-flex items-center rounded-sm px-1 py-0.5 text-xs whitespace-nowrap";function fP({children:e,label:t,className:n,title:r}){const o=t??(typeof e=="string"?e:"");return m.jsx("span",{title:r,className:et(Vre,"text-foreground",dP(o),n),children:e})}const M9e={default:"border-type-badge-border",soft:"border-type-badge-border-soft"};function qr({children:e,className:t,title:n,tone:r="default"}){return m.jsx("span",{title:n,className:et(Vre,"border bg-accent text-foreground",M9e[r],t),children:e})}function R9e(e){return e.localExists?"already-local":e.backups.length===0?"no-backup":"importable"}const I9e={"already-local":"本机已有","no-backup":"无备份"};function A9e(e){return e.name??e.dirName}function O9e(e){const t=e.backups[0];return t===void 0?null:`${Da(t.createdAt)} · ${e.backups.length} 份 · ${du(t.size)}`}function oU(e,t){switch(e){case"CLOUD_NOT_CONFIGURED":return"还没有配置云端账号——去「设置 → 备份 → 云端备份」填好地址与账号再回来";case"PROJECT_ALREADY_EXISTS":return"本机已有这本书,打开后同步即可";case"CLIENT_NETWORK_ERROR":return"无法连接服务,请确认 ai-editor 服务已启动";default:return t!==""?t:"从云端恢复失败,请稍后重试"}}function _9e({books:e,loadError:t,loadNotConfigured:n,importError:r,importingDir:o,onImport:s,onRetry:i,onOpenCloudSettings:a,onClose:l}){return m.jsxs(m.Fragment,{children:[m.jsxs(lo,{children:[m.jsx(co,{children:"从云端恢复"}),m.jsx(hu,{children:"云端存着这些书的备份——导入会为本机建一本新书(沿用原项目 id,之后可继续同步),不会自动打开"})]}),t!==null?m.jsxs("div",{className:"flex flex-col gap-2",children:[m.jsx("p",{className:"text-sm break-all text-destructive",children:t}),m.jsxs("div",{className:"flex gap-2",children:[m.jsx(de,{size:"small",onClick:i,children:"重试"}),n&&m.jsx(de,{size:"small",onClick:a,children:"去设置页"})]})]}):e===null?m.jsx("p",{className:"text-sm text-muted-foreground",children:"正在读取云端备份…"}):e.length===0?m.jsx(Hn,{padding:"sm",children:"云端还没有可恢复的备份"}):m.jsx("ul",{className:"max-h-80 divide-y divide-border overflow-y-auto rounded-lg border border-border",children:e.map(c=>{const u=R9e(c),p=O9e(c);return m.jsxs("li",{className:"flex items-center gap-3 px-3 py-2 transition-colors hover:bg-muted",children:[m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsx("p",{className:"truncate text-sm text-foreground",children:A9e(c)}),p!==null&&m.jsx("p",{className:"truncate text-xs text-muted-foreground",children:p})]}),u==="importable"?m.jsx(de,{size:"small",className:"shrink-0",loading:o===c.dirName,disabled:o!==null,onClick:()=>s(c),children:"导入"}):m.jsx(qr,{className:"shrink-0",children:I9e[u]})]},c.dirName)})}),r!==null&&m.jsx("p",{className:"text-sm break-all text-destructive",children:r}),m.jsx(xo,{children:m.jsx(de,{onClick:l,disabled:o!==null,children:"关闭"})})]})}function j9e({open:e,onOpenChange:t,onImported:n}){const[r,o]=d.useState(null),[s,i]=d.useState(null),[a,l]=d.useState(!1),[c,u]=d.useState(null),[p,h]=d.useState(null),b=d.useRef(0);async function y(){const C=++b.current;o(null),i(null),l(!1),u(null),h(null);try{const E=await Jbe();if(C!==b.current)return;o(E.books)}catch(E){if(C!==b.current)return;const w=E instanceof Ze?E.code:null;l(w==="CLOUD_NOT_CONFIGURED"),i(oU(w,E instanceof Ze?E.message:""))}}d.useEffect(()=>{e&&y()},[e]);async function x(C){if(c===null){u(C.dirName),h(null);try{const E=await e0e({dirName:C.dirName});b.current+=1,t(!1),$e.getState().showToast(`已从云端恢复《${E.name}》`,"success"),n()}catch(E){h(oU(E instanceof Ze?E.code:null,E instanceof Ze?E.message:""))}finally{u(null)}}}function S(){_n.getState().requestCloudPane(),en("/preferences")}return m.jsx(bo,{open:e,onOpenChange:C=>{!C&&c!==null||t(C)},children:m.jsx(yo,{className:"sm:max-w-lg",children:m.jsx(_9e,{books:r,loadError:s,loadNotConfigured:a,importError:p,importingDir:c,onImport:C=>{x(C)},onRetry:()=>{y()},onOpenCloudSettings:S,onClose:()=>t(!1)})})})}const sU="project",P9e=[{kind:"project",label:"项目压缩文件",caption:e=>`${e}.zip · 三文件 + 项目规则(若有)· 可再导入(无损)`},{kind:"novel",label:"小说文档",caption:e=>`${e}-小说文档.zip · 卷/章 markdown 目录树 · 有损`},{kind:"txt",label:"纯文本",caption:e=>`${e}.txt · 整本单文件 · UTF-8 · 有损`}],D9e="网文排版(段首缩进、段间不空行;文件名加 -网文)";function L9e(e){return P9e.filter(t=>e==="novel"||t.kind==="project")}function z9e(e,t){return e==="novel"?`已导出《${t}》小说文档`:e==="txt"?`已导出《${t}》纯文本`:`已导出《${t}》备份`}function B9e({name:e,workspaceKind:t,kind:n,onKindChange:r,webnovel:o,onWebnovelChange:s,exporting:i,onExport:a,onCancel:l}){return m.jsxs(m.Fragment,{children:[m.jsx(lo,{children:m.jsxs(co,{children:["导出《",e,"》"]})}),m.jsx(Xy.Group,{value:n,onChange:c=>r(c.target.value),disabled:i,"aria-label":"导出类型",children:L9e(t).map(c=>m.jsxs("div",{className:"flex flex-col gap-0.5 py-1",children:[m.jsx(Xy,{value:c.kind,children:c.label}),m.jsx("span",{className:"pl-6 text-xs text-muted-foreground",children:c.caption(e)})]},c.kind))}),n==="txt"&&m.jsx(lg,{checked:o,onChange:c=>s(c.target.checked),disabled:i,children:D9e}),m.jsxs(xo,{children:[m.jsx(de,{onClick:l,disabled:i,children:"取消"}),m.jsx(de,{type:"primary",loading:i,disabled:i,onClick:a,children:"导出"})]})]})}function H9e({open:e,name:t,workspaceKind:n,exporting:r,onExport:o,onOpenChange:s}){const[i,a]=d.useState(sU),[l,c]=d.useState(!1);d.useEffect(()=>{e&&(a(sU),c(!1))},[e]);function u(){r||s(!1)}return m.jsx(bo,{open:e,onOpenChange:p=>{p||u()},children:m.jsx(yo,{className:"sm:max-w-md",children:m.jsx(B9e,{name:t,workspaceKind:n,kind:i,onKindChange:a,webnovel:l,onWebnovelChange:c,exporting:r,onExport:()=>o(i,i==="txt"&&l?"webnovel":"preserve"),onCancel:u})})})}function Ure({children:e,className:t,onClick:n,title:r}){return m.jsx(Ar.Title,{level:4,className:t,onClick:n,title:r,children:e})}function mP({className:e}){return m.jsx("div",{className:et("h-px w-full shrink-0 bg-border",e)})}function Ho({title:e,titleNode:t,leading:n,action:r,description:o,controls:s,divider:i=!0,truncateTitle:a,className:l}){return m.jsxs("header",{className:et("mb-4 flex shrink-0 flex-col",l),children:[m.jsxs("div",{className:et("flex items-center gap-3",n!==void 0&&"flex-wrap"),children:[n!==void 0&&m.jsx("div",{className:"flex shrink-0 items-center",children:n}),t??m.jsx(Ure,{className:et("min-w-0",a&&"truncate"),children:e}),r!==void 0&&m.jsx("div",{className:et("ml-auto flex items-center gap-2",n!==void 0?"min-w-0 flex-wrap justify-end":"shrink-0"),children:r})]}),o!==void 0&&m.jsx("div",{className:"mt-1",children:o}),s!==void 0&&m.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:s}),i&&m.jsx("div",{className:"mt-3",children:m.jsx(mP,{})})]})}function HM(e){const t=e.trim();return t===""?"请输入书名":/[\\/]|^\.+$|[\u0000-\u001f]/.test(t)?"书名不能包含 /、\\ 或为 . / ..":null}function FM(e,t){return t!==null&&e.id===t.id}const Wre={character:"characters",setting:"setting",location:"locations"},F9e={character:"characters",setting:"setting",location:"locations",hook:"hooks",event:"timeline",timepoint:"timepoints",reference:"references"};function qre(e){return`/${Wre[e]}`}function Nd(e,t){return`/${F9e[e]}/${t}`}function tO(e){return e==="character"||e==="setting"||e==="location"?`/${Wre[e]}`:e==="hook"?"/hooks":"/timeline"}function Hs(e){const t=$e(r=>r.dataVersion),n=d.useRef(t);d.useEffect(()=>{t!==n.current&&(n.current=t,e())},[t])}const iU={character:"人物",setting:"设定",location:"地点",hook:"伏笔",event:"事件",timepoint:"时间点",reference:"参考资料"},aU=["character","setting","location","hook"];function V9e(e){const t={volumes:0,chapters:0,scenes:0,updatedAt:null},n=r=>{for(const o of r)o.type==="volume"?t.volumes+=1:o.type==="chapter"?t.chapters+=1:t.scenes+=1,(t.updatedAt===null||o.updatedAt>t.updatedAt)&&(t.updatedAt=o.updatedAt),o.type!=="scene"&&o.children&&n(o.children)};return n(e),t}function A0(e){return e instanceof Ze?e.code:null}function VM({mode:e}){const t=lt(Ie=>Ie.config),n=lt(Ie=>Ie.configLoading),r=lt(Ie=>Ie.outline),o=lt(Ie=>Ie.outlineLoading),s=lt(Ie=>Ie.loadOutline),i=lt(Ie=>Ie.bookshelf),a=lt(Ie=>Ie.bookshelfLoading),l=lt(Ie=>Ie.bookshelfError),c=lt(Ie=>Ie.loadBookshelf),u=lt(Ie=>Ie.openProjectAt),p=lt(Ie=>Ie.createProjectAt),h=Kt(Ie=>Ie.sessions),b=Kt(Ie=>Ie.sessionsLoading),y=Kt(Ie=>Ie.sessionsError),x=Kt(Ie=>Ie.loadSessions),S=Kt(Ie=>Ie.setCurrentSession),C=Kt(Ie=>Ie.currentSessionId),E=$e(Ie=>Ie.setFocusOutlineNode),[w,$]=d.useState(""),[N,M]=d.useState(null),[k,R]=d.useState(null),[A,O]=d.useState(!1),[j,L]=d.useState(null),[z,I]=d.useState(!1),[P,D]=d.useState(""),U=l2(),[V,W]=d.useState(null),[q,B]=d.useState(!1),[F,G]=d.useState(!1),[J,te]=d.useState(!1),[ne,K]=d.useState(null),[ee,re]=d.useState(""),[ae,ue]=d.useState(null),[Y,oe]=d.useState(!1),[Z,se]=d.useState(!1),[ce,me]=d.useState(""),[ye,Ce]=d.useState(!1),[be,ke]=d.useState(!1),[we,Ue]=d.useState(null),[De,We]=d.useState(!1),[rt,ze]=d.useState(""),[Ae,Le]=d.useState(null),[Te,Se]=d.useState(!1),_e=d.useRef(null),[dt,ve]=d.useState(null),[Ge,Qe]=d.useState(!1),[ge,Ee]=d.useState(null),[Re,mt]=d.useState(0),[gt,wt]=d.useState(!1),Tt=t===null&&!n,Pt=r?V9e(r.children):null,Wt=t?.currentPosition!=null?u0e(r,t.currentPosition)??t.currentPosition:null;d.useEffect(()=>{e==="home"&&!a&&i===null&&l===null&&c()},[e,a,i,l,c]),d.useEffect(()=>{if(e!=="home"||t?.kind!=="practice"){L(null);return}let Ie=!1;return WY().then(bt=>{Ie||L(bt.samples.length)}).catch(()=>{Ie||L(null)}),()=>{Ie=!0}},[e,t?.id,t?.kind]),d.useEffect(()=>{e==="overview"&&wt(!1)},[e,t?.id]),Hs(()=>{e==="overview"&&(mt(Ie=>Ie+1),s(),x())}),d.useEffect(()=>{R(null)},[t?.id]),d.useEffect(()=>{e!=="overview"||t===null||r===null&&!o&&!gt&&(wt(!0),s())},[e,t,r,o,gt,s]),d.useEffect(()=>{if(e!=="overview"||t===null)return;let Ie=!1;return ve(null),Qe(!0),Ee(null),Promise.allSettled(aU.map(async bt=>({type:bt,total:(await zo(bt,{limit:1})).total}))).then(bt=>{if(Ie)return;const Nt={};let ft=!1;for(const Me of bt)Me.status==="fulfilled"?Nt[Me.value.type]=Me.value.total:ft=!0;ve(Nt),Ee(ft?"要素统计加载失败":null),Qe(!1)}),()=>{Ie=!0}},[e,t,Re]),d.useEffect(()=>{e!=="overview"||t===null||h===null&&!b&&y===null&&x()},[e,t,h,b,y,x]);async function sn(Ie){Ie.preventDefault();const bt=w.trim(),Nt=HM(bt);if(Nt!==null){M(Nt);return}if(!i){M("书架未加载,请稍后重试");return}B(!0),M(null);try{await p(nB(i.rootPath,"novel",bt),{name:bt,language:"zh",kind:"novel"}),await c(),$(""),O(!1),$e.getState().showToast(`已创建并打开《${bt}》`),en(Bf.novel)}catch(ft){M(I0(A0(ft)))}finally{B(!1)}}async function tt(Ie){if(i===null||q)return;const bt=nB(i.rootPath,"practice",Ie.name);B(!0),R(null);try{await p(bt,{name:Ie.name,language:"zh",kind:"practice",author_id:Ie.id}),await c(),$e.getState().showToast(`已开始《${Ie.name}》文风练习`),en(Bf.practice)}catch(Nt){if((Nt instanceof Ze?Nt.code:null)==="PROJECT_ALREADY_EXISTS"){await He(bt,"practice");return}R(I0(A0(Nt)))}finally{B(!1)}}function it(){O(Ie=>!Ie),$(""),M(null)}async function qe(Ie){if(Ie.preventDefault(),!P.trim()){W("请输入项目目录路径(绝对路径)");return}B(!0),W(null);try{await u(P.trim()),en("/overview")}catch(bt){W(I0(A0(bt)))}finally{B(!1)}}async function He(Ie,bt){R(null);try{await u(Ie),en(Bf[bt])}catch(Nt){R(I0(A0(Nt)))}}async function ot(){if(U===null||q)return;W(null);const Ie=await U.pickDirectory();if(Ie!==null){D(Ie),B(!0);try{await u(Ie),en("/overview")}catch(bt){W(I0(A0(bt)))}finally{B(!1)}}}async function pe(Ie,bt,Nt){if(!be){ke(!0);try{const{blob:ft,filename:Me}=bt==="novel"?await zbe():bt==="txt"?await Bbe(Nt):await Lbe(),ut=URL.createObjectURL(ft),Ye=document.createElement("a");Ye.href=ut,Ye.download=Me,document.body.appendChild(Ye),Ye.click(),Ye.remove(),setTimeout(()=>URL.revokeObjectURL(ut),0),$e.getState().showToast(z9e(bt,Ie)),Ce(!1)}catch(ft){$e.getState().showToast(x9e(ft instanceof Ze?ft.code:null,ft instanceof Ze?ft.message:"导出失败,请重试"),"error")}finally{ke(!1)}}}function Oe(Ie){const bt=Ie.trim(),Nt=ft=>i?.books.some(Me=>Me.name===ft)??!1;if(Z){if(bt===`${ce} (2)`||bt===ce&&Nt(bt))return;if(Nt(bt)){me(bt),re(`${bt} (2)`);return}se(!1),me("");return}bt!==""&&Nt(bt)&&(me(bt),se(!0),re(`${bt} (2)`))}function Be(Ie){const bt=Ie.target.value;re(bt),Oe(bt)}function Xe(Ie){const bt=Ie.target.files?.[0]??null;K(bt),ue(null)}async function Et(Ie,bt){const Nt=Ie.trim();if(!ne){ue("请选择备份文件");return}if(Nt!==""){const ft=HM(Nt);if(ft!==null){ue(ft);return}}oe(!0),ue(null);try{const ft=await Hbe(ne,Nt);$e.getState().showToast(ft.mode==="restored"?`已恢复备份《${ft.name}》`:`已导入为新书《${ft.name}》`),await c(),Dt()}catch(ft){const Me=y9e(ft instanceof Ze?ft.code:null,ft instanceof Ze?ft.message:"导入失败,请重试");ue(Me),Me!==""&&$e.getState().showToast(Me,"error")}finally{oe(!1)}}function Dt(){G(!1),ue(null),K(null),re(""),se(!1),me("")}function _t(){We(!1),ze(""),Le(null)}async function yt(){if(!De||Te)return;const Ie=rt.trim();if(Ie===lt.getState().config?.name){_t();return}const bt=HM(Ie);if(bt!==null){Le(bt);return}Se(!0),Le(null);try{await Ube(Ie),$e.getState().showToast(`已重命名为《${Ie}》`),await Promise.all([c(),lt.getState().loadConfig()]),_t()}catch(Nt){(Nt instanceof Ze?Nt.code:null)==="PROJECT_ALREADY_EXISTS"?Le("书架已有同名书籍,请换一个名字"):Nt instanceof Ze&&Nt.code!==yn?Le(Nt.message):Le("无法连接服务,请确认 ai-editor 服务已启动")}finally{Se(!1)}}async function un(Ie){if(await c(),!(t===null||Ie.id!==t.id)){_n.getState().clearStatus();try{await lt.getState().closeProject()}catch{}en("/")}}function vn(){ze(t?.name??""),Le(null),We(!0),window.setTimeout(()=>_e.current?.focus(),0)}function Zn(){t?.currentPosition!=null&&E(t.currentPosition)}if(n)return m.jsx("section",{children:m.jsx("p",{className:"mt-4 text-sm text-muted-foreground",children:"加载中…"})});if(e==="home"){let Ie=function(Ye){return m.jsxs("form",{onSubmit:ht=>{sn(ht)},className:Ye,children:[m.jsxs("div",{className:"flex gap-2",children:[m.jsx(kt,{value:w,onChange:ht=>$(ht.target.value),placeholder:"书名",maxLength:60,disabled:q}),m.jsx(de,{type:"primary",htmlType:"submit",disabled:q||i===null,children:"新建"})]}),N&&m.jsx("p",{className:"text-left text-sm text-destructive",children:N})]})};const bt=i===null&&a,Nt=l!==null,ft=obe(i?.books??null),Me=sbe(i?.books??null),ut=i?.books.find(Ye=>FM(Ye,t))??null;return m.jsxs("section",{className:"mx-auto w-full max-w-2xl px-4",children:[m.jsx(Ho,{className:"mt-8",title:"书架",description:m.jsx("p",{className:"text-sm text-muted-foreground",children:t!==null?`当前打开《${t.name}》,切换工作区或继续创作`:"选择一本小说或练习区打开,或新建一个"}),action:m.jsxs(m.Fragment,{children:[m.jsxs(de,{className:"shrink-0",onClick:()=>G(!0),children:[m.jsx(L_e,{className:"text-sm"}),"导入备份"]}),m.jsx(de,{className:"shrink-0",onClick:()=>te(!0),children:"从云端恢复…"})]})}),l!==null&&m.jsxs("div",{className:"mt-4 rounded-md border border-border bg-card p-3",children:[m.jsx("p",{className:"text-sm text-muted-foreground",children:l===yn?"无法连接服务,请确认 ai-editor 服务已启动后重试。":"书架加载失败,请重试。"}),m.jsx(de,{className:"mt-2",onClick:()=>{c()},children:"重试"})]}),t!==null&&m.jsxs("div",{className:"mt-4 rounded-lg border border-primary/30 bg-primary/5 px-4 py-3",children:[m.jsxs("div",{className:"flex items-center gap-3",children:[m.jsx(HI,{className:"shrink-0 text-xl text-primary"}),De?m.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:m.jsx(kt,{ref:_e,value:rt,onChange:Ye=>ze(Ye.target.value),onKeyDown:Ye=>{Ye.key==="Enter"?(Ye.preventDefault(),yt()):Ye.key==="Escape"&&_t()},onBlur:()=>{yt()},maxLength:60,disabled:Te,"aria-label":"重命名书名"})}):m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsx("p",{className:"truncate text-sm font-medium text-foreground",children:t.name}),m.jsx("p",{className:"text-xs text-muted-foreground",children:"已打开"})]}),!De&&m.jsxs(m.Fragment,{children:[m.jsxs(de,{size:"small",className:"shrink-0",onClick:()=>Ce(!0),children:[m.jsx(JIe,{className:"text-sm"}),"导出"]}),m.jsxs(de,{size:"small",className:"shrink-0",onClick:vn,children:[m.jsx(cc,{className:"text-sm"}),"重命名"]}),ut!==null&&m.jsxs(de,{size:"small",className:"shrink-0",onClick:()=>Ue(ut),children:[m.jsx(ss,{className:"text-sm"}),"删除"]}),m.jsx(de,{type:"primary",size:"small",className:"shrink-0",onClick:()=>en(Bf[t.kind]),children:"继续创作"})]})]}),De&&Ae&&m.jsx("p",{className:"mt-1 text-sm text-destructive",children:Ae})]}),k!==null&&m.jsx("p",{className:"mt-3 text-sm text-destructive",children:k}),m.jsxs("section",{className:"mt-6",children:[m.jsx(Ar.Title,{level:5,children:Uz.novel}),m.jsxs("div",{className:"mt-3 rounded-lg border border-dashed border-border bg-card px-6 py-6",children:[bt?m.jsxs("div",{className:"py-2",children:[m.jsx("div",{className:et(wr,"mx-auto h-6 w-2/3")}),m.jsx("div",{className:et(wr,"mx-auto mt-2 h-4 w-1/2")}),m.jsxs("div",{className:"mt-5 space-y-2",children:[m.jsx("div",{className:et(wr,"h-10 rounded-lg")}),m.jsx("div",{className:et(wr,"h-10 rounded-lg")})]})]}):ft.novel.length>0?m.jsxs(m.Fragment,{children:[m.jsx("ul",{className:"divide-y divide-border overflow-hidden rounded-lg border border-border",children:ft.novel.map(Ye=>{const ht=FM(Ye,t);return m.jsx("li",{children:m.jsxs("div",{className:et("flex w-full items-center gap-1 px-3 py-2.5 transition-colors hover:bg-muted",ht&&"bg-primary/10 ring-1 ring-primary/30 ring-inset"),children:[m.jsxs("button",{type:"button",title:ht?`继续创作《${Ye.name}》`:`打开《${Ye.name}》`,onClick:()=>{ht?en(Bf[Ye.kind]):He(Ye.path,Ye.kind)},className:"flex min-w-0 flex-1 items-center gap-3 text-left",children:[m.jsx(HI,{className:"shrink-0 text-base text-muted-foreground/60"}),m.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-foreground",children:Ye.name}),ht&&m.jsx("span",{className:"shrink-0 rounded border border-border px-1.5 py-0.5 text-xs text-muted-foreground",children:"已打开"}),m.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:Jc(Ye.updatedAt)})]}),m.jsx(de,{color:"danger",variant:"text",size:"small",className:"shrink-0",title:"删除书籍","aria-label":"删除书籍",icon:m.jsx(ss,{}),onClick:()=>Ue(Ye)})]})},Ye.path)})}),m.jsxs("div",{className:"mt-4 border-t border-border pt-3",children:[m.jsx("div",{className:"flex items-center gap-2",children:m.jsx("button",{type:"button",className:"rounded-md border border-border px-2.5 py-1 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:()=>it(),children:A?"收起":"新建一本…"})}),A&&Ie("mt-2 flex flex-col gap-2 text-left")]})]}):Nt?m.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"书架加载失败,重试后可查看书籍或新建"}):m.jsxs(m.Fragment,{children:[m.jsx("p",{className:"text-base font-semibold text-foreground",children:"还没有书,先创建一本"}),m.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"每本书一个独立目录(books/书名/),写作数据互不干扰"}),Ie("mx-auto mt-5 flex max-w-xs flex-col gap-2"),m.jsx("p",{className:"mt-2 text-center text-xs text-muted-foreground",children:"创建于 创作根/books/书名/ 目录"})]}),m.jsxs("div",{className:"mt-4 border-t border-border pt-3",children:[m.jsx("button",{type:"button",className:"rounded-md border border-border px-2.5 py-1 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:()=>I(Ye=>!Ye),children:z?"收起":"打开其他路径…"}),z&&m.jsxs("form",{onSubmit:qe,className:"mt-2 flex flex-col gap-2 text-left",children:[m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("div",{className:"flex-1",children:m.jsx(kt,{value:P,onChange:Ye=>D(Ye.target.value),placeholder:"/absolute/path/to/project(须含 project.json)",disabled:q})}),U!==null&&m.jsx(de,{disabled:q,onClick:()=>{ot()},children:"浏览…"})]}),m.jsx("div",{children:m.jsx(de,{htmlType:"submit",disabled:q,children:"打开"})}),V&&m.jsx("p",{className:"text-sm text-destructive",children:V})]})]})]})]}),m.jsxs("section",{className:"mt-6",children:[m.jsx(Ar.Title,{level:5,children:Uz.practice}),bt?m.jsxs("div",{className:"mt-3 space-y-2",children:[m.jsx("div",{className:et(wr,"h-16 rounded-lg")}),m.jsx("div",{className:et(wr,"h-16 rounded-lg")})]}):Nt?m.jsx("p",{className:"mt-3 text-sm text-muted-foreground",children:"加载失败,重试后可查看练习区"}):m.jsx("ul",{className:"mt-3 divide-y divide-border overflow-hidden rounded-lg border border-border",children:Me.map(Ye=>{const ht=Ye.workspace!==null&&FM(Ye.workspace,t);return m.jsx("li",{children:m.jsxs("button",{type:"button",disabled:q||i===null,title:Ye.workspace===null?`开始《${Ye.author.name}》文风练习`:`打开《${Ye.author.name}》文风练习`,onClick:()=>{Ye.workspace===null?tt(Ye.author):ht?en(Bf.practice):He(Ye.workspace.path,Ye.workspace.kind)},className:et("flex w-full flex-col gap-1 px-3 py-2.5 text-left transition-colors hover:bg-muted",ht&&"bg-primary/10 ring-1 ring-primary/30 ring-inset"),children:[m.jsxs("span",{className:"flex items-center gap-3",children:[m.jsx("span",{className:"min-w-0 flex-1 truncate text-base font-semibold text-foreground",children:Ye.author.name}),ht&&m.jsx("span",{className:"shrink-0 rounded border border-border px-1.5 py-0.5 text-xs text-muted-foreground",children:"已打开"})]}),m.jsx("span",{className:"w-full truncate text-xs text-muted-foreground",children:Ye.author.intro}),m.jsx("span",{className:"text-xs text-muted-foreground",children:ibe(Ye,ht?j:null)})]})},Ye.author.id)})})]}),m.jsx(bo,{open:F,onOpenChange:Ye=>Ye?G(!0):Dt(),children:m.jsxs(yo,{className:"sm:max-w-sm",children:[m.jsxs(lo,{children:[m.jsx(co,{children:"导入书籍"}),m.jsx(hu,{children:"从备份 zip 导入;与书架已有书 id 匹配时覆盖恢复,否则导入为新书(同名可重命名或保持原样并存)"})]}),m.jsxs("form",{id:"import-book-form",onSubmit:Ye=>{Ye.preventDefault(),Et(ee)},className:"flex flex-col gap-3",children:[m.jsx("input",{type:"file",accept:".zip,application/zip",onChange:Xe,disabled:Y,"aria-label":"选择备份文件",className:"block w-full cursor-pointer rounded-md border border-border bg-card px-3 py-1.5 text-sm text-foreground file:mr-2 file:cursor-pointer file:rounded file:border-0 file:bg-muted file:px-2 file:py-1 file:text-xs file:text-muted-foreground disabled:opacity-50"}),m.jsx(kt,{value:ee,onChange:Be,placeholder:"书名(留空 = 使用备份里的书名)",maxLength:60,disabled:Y}),Z&&m.jsxs("p",{className:"text-sm text-primary",children:["书架已有同名书籍《",ce,"》——可重命名导入,或保持原样(服务端自动去重)"]}),ae&&m.jsx("p",{className:"text-sm text-destructive",children:ae})]}),m.jsxs(xo,{children:[m.jsx(de,{onClick:Dt,disabled:Y,children:"取消"}),Z?m.jsxs(m.Fragment,{children:[m.jsx(de,{onClick:()=>{Et(ce)},disabled:Y||ne===null,children:Y?"导入中…":"保持原样导入"}),m.jsx(de,{type:"primary",onClick:()=>{Et(ee)},disabled:Y||ne===null,children:Y?"导入中…":"重命名导入"})]}):m.jsx(de,{type:"primary",htmlType:"submit",form:"import-book-form",disabled:Y||ne===null,children:Y?"导入中…":"导入"})]})]})}),m.jsx(H9e,{open:ye,name:t?.name??"",workspaceKind:t?.kind??"novel",exporting:be,onExport:(Ye,ht)=>{pe(t?.name??"",Ye,ht)},onOpenChange:Ce}),m.jsx(E9e,{book:we,onOpenChange:Ye=>{Ye||Ue(null)},onDeleted:Ye=>{un(Ye)}}),m.jsx(j9e,{open:J,onOpenChange:te,onImported:()=>{c()}})]})}return Tt?m.jsx("section",{className:"mx-auto w-full max-w-xl px-4",children:m.jsxs(Hn,{padding:"sm",className:"mt-16",action:m.jsx(de,{href:"#/",size:"small",children:"回到书架"}),children:[m.jsx("span",{className:"block text-base font-semibold text-foreground",children:"还没有打开的书"}),m.jsx("span",{className:"mt-1 block",children:"先到书架选择或创建一本"})]})}):m.jsxs("section",{children:[m.jsx(Ho,{title:"项目概览"}),m.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[m.jsx(tr,{title:"项目信息",children:m.jsxs("dl",{className:"mt-3 space-y-2 text-sm",children:[m.jsxs("div",{className:"flex items-baseline gap-2",children:[m.jsx("dt",{className:"w-16 shrink-0 text-muted-foreground",children:"名称"}),m.jsx("dd",{className:"min-w-0 truncate font-medium text-foreground",children:t?.name})]}),m.jsxs("div",{className:"flex items-baseline gap-2",children:[m.jsx("dt",{className:"w-16 shrink-0 text-muted-foreground",children:"语言"}),m.jsx("dd",{className:"text-foreground",children:t?.language==="zh"?"中文":"English"})]}),m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("dt",{className:"w-16 shrink-0 text-muted-foreground",children:"阅读进度"}),m.jsx("dd",{className:"min-w-0 flex-1 truncate",children:t?.currentPosition!=null?m.jsx("a",{href:"#/outline",onClick:Zn,className:"text-primary hover:underline",children:Wt??t.currentPosition}):m.jsx("span",{className:"text-muted-foreground",children:"未设置"})}),m.jsx(de,{href:"#/outline",onClick:Zn,size:"small",children:"去大纲"})]})]})}),m.jsx(tr,{title:"创作要素",children:Ge&&dt===null?m.jsx("div",{className:"mt-3 grid grid-cols-2 gap-2",children:[0,1,2,3].map(Ie=>m.jsx("div",{className:et(wr,"h-20 rounded-lg")},Ie))}):m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"mt-3 grid grid-cols-2 gap-2",children:aU.map(Ie=>m.jsxs("a",{href:`#${tO(Ie)}`,className:"group rounded-lg border border-border bg-background p-3 transition-colors hover:border-primary/40 hover:bg-muted",title:`查看${iU[Ie]}列表`,children:[m.jsx("p",{className:"text-xl font-semibold text-foreground",children:dt?.[Ie]??"–"}),m.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground transition-colors group-hover:text-foreground",children:iU[Ie]})]},Ie))}),ge!==null&&m.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-destructive",children:[ge,m.jsx(de,{size:"small",onClick:()=>mt(Ie=>Ie+1),children:"重试"})]})]})}),m.jsx(tr,{title:"大纲概览",className:"lg:col-span-2",children:r===null&&(o||!gt)?m.jsxs("div",{className:"mt-3 space-y-2",children:[m.jsx("div",{className:et(wr,"h-5 w-2/5")}),m.jsx("div",{className:et(wr,"h-4 w-1/3")})]}):r===null?m.jsxs("div",{className:"mt-3 flex items-center gap-2 text-sm text-muted-foreground",children:["大纲加载失败",m.jsx(de,{size:"small",onClick:()=>wt(!1),children:"重试"})]}):m.jsxs(m.Fragment,{children:[m.jsxs("p",{className:"mt-3 text-sm text-foreground",children:["卷 ",Pt?.volumes??0," · 章 ",Pt?.chapters??0," · 场景"," ",Pt?.scenes??0]}),m.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["最近更新:"," ",Pt?.updatedAt?Jc(Pt.updatedAt):"—"]}),r.children.length===0&&m.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[m.jsx("p",{className:"text-xs text-muted-foreground",children:"大纲还是空的"}),m.jsx(de,{size:"small",onClick:()=>S(null),children:"和 AI 聊聊设定"})]}),m.jsx("div",{className:"mt-3",children:m.jsx(de,{href:"#/outline",onClick:Zn,size:"small",children:"去大纲编辑"})})]})}),m.jsx(tr,{title:"最近会话",className:"lg:col-span-2",children:h===null?y!==null?m.jsxs("div",{className:"mt-3 flex items-center gap-2 text-sm text-muted-foreground",children:["会话加载失败",m.jsx(de,{size:"small",onClick:()=>{x()},children:"重试"})]}):m.jsx("div",{className:"mt-3 space-y-2",children:[0,1,2].map(Ie=>m.jsx("div",{className:et(wr,"h-8 rounded-md")},Ie))}):h.length===0?m.jsxs("div",{className:"mt-3",children:[m.jsx("p",{className:"text-sm text-muted-foreground",children:"还没有会话,和 AI 聊聊设定吧"}),m.jsx(de,{className:"mt-3",onClick:()=>S(null),children:"开始新对话"})]}):m.jsxs(m.Fragment,{children:[m.jsx("ul",{className:"mt-3 divide-y divide-border rounded-lg border border-border",children:h.slice(0,5).map(Ie=>m.jsx("li",{children:m.jsxs("button",{type:"button",title:Ie.lastMessage||"空会话",onClick:()=>S(Ie.id),className:et("flex w-full items-center gap-3 px-3 py-2 text-left transition-colors hover:bg-muted",C===Ie.id&&"bg-primary/10 ring-1 ring-primary/30 ring-inset"),children:[m.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-foreground",children:Ie.lastMessage||"(空会话)"}),m.jsxs("span",{className:"shrink-0 text-xs text-muted-foreground",children:[Ie.messageCount," 条消息"]}),m.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:Jc(Ie.updatedAt)})]})},Ie.id))}),m.jsx("div",{className:"mt-3",children:m.jsx(de,{onClick:()=>S(null),children:"开始新对话"})})]})})]})]})}function VC({value:e,onChange:t,onKeyDown:n,onBlur:r,placeholder:o}){return m.jsx(kt,{size:"small",className:"min-w-0 flex-1",autoComplete:"off",autoFocus:!0,value:e,onChange:s=>t(s.target.value),onKeyDown:n,onBlur:r,maxLength:200,placeholder:o})}const U9e={plants:"埋设",advances:"推进",resolves:"回收"},W9e={plants:e_e,advances:fOe,resolves:jg};function Gre({mark:e}){const t=W9e[e.relationType],n=`${U9e[e.relationType]}伏笔:${e.hookName}`;return m.jsx("a",{href:`#${Nd("hook",e.hookId)}`,draggable:!1,className:"shrink-0 rounded px-0.5 text-muted-foreground hover:text-primary hover:underline",title:`${n}(点击查看)`,"aria-label":n,children:m.jsx(t,{className:"text-xs"})})}function uc({position:e}){return m.jsxs("div",{"aria-hidden":"true",className:et("pointer-events-none absolute inset-x-0 z-10 flex items-center",e==="top"?"-top-[3px]":"-bottom-[3px]"),children:[m.jsx("span",{className:"size-2 shrink-0 rounded-full bg-primary"}),m.jsx("span",{className:"h-[3px] flex-1 rounded-full bg-primary"}),m.jsx("span",{className:"size-2 shrink-0 rounded-full bg-primary"})]})}function wi({title:e,leading:t,actions:n,meta:r,className:o,insetClassName:s="px-3"}){return m.jsxs("header",{className:et("mb-4 flex shrink-0 flex-col",o),children:[m.jsxs("div",{className:et("flex flex-col",s),children:[m.jsxs("div",{className:"flex h-10 min-w-0 items-center gap-2",children:[t!==void 0&&m.jsx("span",{className:"flex shrink-0 items-center",children:t}),m.jsx("span",{className:"min-w-0 flex-1 truncate text-base font-semibold",children:e}),n!==void 0&&m.jsx("span",{className:"flex shrink-0 items-center gap-1",children:n})]}),m.jsx("div",{className:"flex h-6 min-w-0 items-center gap-2",children:r})]}),m.jsx(mP,{})]})}const Kre="ai-editor:outline-rail",q9e="max(320px, calc(100% / 3))",nO=280,Xre=600;function UM(){return{width:null,collapsed:!1,detailCollapsed:!1}}function G9e(e){if(!e)return UM();let t;try{t=JSON.parse(e)}catch{return UM()}if(typeof t!="object"||t===null||Array.isArray(t))return UM();const n=t,r=n.width;return{width:typeof r=="number"&&Number.isFinite(r)?$l(r,nO,Xre):null,collapsed:n.collapsed===!0,detailCollapsed:n.detailCollapsed===!0}}function K9e(){if(typeof window>"u")return null;try{return window.localStorage.getItem(Kre)}catch{return null}}function WM(e){try{window.localStorage.setItem(Kre,JSON.stringify(e))}catch{}}function X9e(e){const[t,n]=d.useState(()=>G9e(K9e())),[r,o]=d.useState(!1),s=d.useRef(null),i=d.useRef(null);d.useEffect(()=>{!e&&i.current!==null&&(i.current=null,o(!1))},[e]);function a(b){return $l(b.startWidth+(b.lastX-b.startX),nO,Xre)}function l(b){const y=s.current?.getBoundingClientRect().width??nO;i.current={startX:b,startWidth:y,lastX:b},o(!0)}function c(b){const y=i.current;if(!y)return;y.lastX=b;const x=a(y);n(S=>({...S,width:x}))}function u(){const b=i.current;if(!b)return;const y=a(b);i.current=null,o(!1),n(x=>{const S={...x,width:y};return WM(S),S})}function p(){n(b=>{const y={...b,collapsed:!b.collapsed};return WM(y),y})}function h(){n(b=>{const y={...b,detailCollapsed:!b.detailCollapsed};return WM(y),y})}return{layout:t,resizing:r,railRef:s,startResize:l,moveResize:c,endResize:u,toggleCollapse:p,toggleDetail:h}}const Ki="root",Y9e={id:Ki,label:"(根)",depth:0};function Z9e(e,t){if(t==="volume")return[Y9e];const n=[],r=(o,s)=>{for(const i of o)t==="chapter"&&i.type==="volume"?n.push({id:i.id,label:i.title,depth:s}):t==="scene"&&i.type==="chapter"&&n.push({id:i.id,label:i.title,depth:s}),i.children&&r(i.children,s+1)};return r(e,1),n}function vi(e,t){for(const n of e){if(n.id===t)return n;if(n.type!=="scene"&&n.children){const r=vi(n.children,t);if(r)return r}}return null}function nx(e,t,n=[]){for(const r of e){const o=[...n,r.id];if(r.id===t)return o;if(r.type!=="scene"&&r.children){const s=nx(r.children,t,o);if(s)return s}}return null}function r$(e,t=0,n=[]){for(const r of e)n.push({id:r.id,label:r.title,depth:t}),r.type!=="scene"&&r.children&&r$(r.children,t+1,n);return n}function Q9e(e,t,n){const r=vi(e,t);if(!r)return!1;const o=s=>s.id===n?!0:s.type!=="scene"&&s.children?s.children.some(i=>o(i)):!1;return o(r)}function J9e(e,t,n){const r=nx(e,n);return r!==null&&r.includes(t)}function Jw(e,t,n){return t===e.id||Q9e(n,e.id,t)?!1:Z9e(n,e.type).some(r=>r.id===t)}function pP(e,t){const n=t.trim();return n!==""&&n!==e.trim()}function hP(e,t){return t.trim()!==(e??"").trim()}function eHe(e){return e==="OUTLINE_NODE_NOT_FOUND"?"abandon":"restore"}function Yre(e,t){if(t===Ki)return e;const n=r=>{for(const o of r){if(o.id===t)return o.children??[];if(o.children){const s=n(o.children);if(s)return s}}return null};return n(e)}function lU(e,t,n){const r=n===void 0?e:e.filter(s=>s.id!==n);if(t.kind==="end")return r.length;const o=r.findIndex(s=>s.id===t.nodeId);return o===-1?r.length:t.kind==="before"?o:o+1}function cU(e,t){return e===null||t===null?e===t:e.kind==="root-end"||t.kind==="root-end"?e.kind===t.kind:e.kind===t.kind&&e.nodeId===t.nodeId}function Zre(e,t){const n=(r,o)=>{for(const s of r){if(s.id===t)return o;if(s.children){const i=n(s.children,s.id);if(i!==null)return i}}return null};return n(e,Ki)}function tHe(e,t){const n=Zre(e,t);if(n===null)return null;const o=(Yre(e,n)??[]).findIndex(s=>s.id===t);return o===-1?null:{parentId:n,index:o}}function uU(e,t,n,r){const o=vi(e,t);if(o===null)return null;const s=Zre(e,n);if(s!==null&&Jw(o,s,e))return{parentId:s,insert:{kind:r,nodeId:n},target:{kind:r,nodeId:n}};const i=vi(e,n);return i!==null&&Jw(o,i.id,e)?{parentId:i.id,insert:{kind:"end"},target:{kind:"inside",nodeId:i.id}}:null}function dU(e,t,n,r){const o=tHe(e,t);return o===null||o.parentId!==n?!1:r===o.index}function kd(e){const t=[],n=(r,o)=>{for(const s of r)s.deleted!==!0&&(s.type==="chapter"&&t.push({id:s.id,label:s.title,depth:o}),s.type!=="scene"&&s.children&&n(s.children,o+1))};return n(e?.children??[],0),t}function Qre(e,t){return kd(e).some(n=>n.id===t)}function o$(e){const{volumes:t,chapters:n}=jY(e),r=new Map;for(const s of t)r.set(s.volumeId,s.volumeLabel);const o=[];for(const s of n){const i=vi(e?.children??[],s.chapterId);i===null||i.type!=="chapter"||(r.set(i.id,s.chapterLabel),o.push({chapter:i,volumeId:s.volumeId===""?Ki:s.volumeId,volumeLabel:s.volumeLabel,chapterLabel:s.chapterLabel}))}return{labels:r,chapterRows:o}}const OS=20,nHe={character:{key1:"role",label1:"角色",key2:"personality",label2:"性格",key3:"ability_panel",label3:"能力"},setting:{key1:"tags",label1:"标签",key3:"description",label3:"描述"},location:{key1:"type",label1:"类型"},hook:{key1:"status",label1:"状态",key2:"payoff_timing",label2:"回收时机"},event:{key1:"description",label1:"描述"},timepoint:{key1:"",label1:""}},s$={planted:"已埋设",progressing:"推进中",resolved:"已回收",abandoned:"已弃用"},gP={immediate:"立即",near_term:"近期",mid_arc:"中段",slow_burn:"慢热",endgame:"终局"};function _S(e,t,n){if(n==null||n==="")return"—";if(e==="hook"&&t==="status")return s$[String(n)]??String(n);if(e==="hook"&&t==="payoff_timing")return gP[String(n)]??String(n);if(t==="tags"&&Array.isArray(n)){const r=n.filter(o=>typeof o=="string"&&o!=="");return r.length>0?r.join("、"):"—"}return String(n)}const fU={character:{key:"role",label:"角色定位",input:"text"},setting:{key:"tags",label:"标签",input:"tags"},location:{key:"type",label:"地点类型",input:"text"},hook:{key:"status",label:"状态",input:"select",options:["planted","progressing","resolved","abandoned"]},event:{key:"description",label:"描述",input:"text"},timepoint:{key:"",label:"",input:"text"}};function i$(e){switch(e){case"character":return[{key:"role",label:"角色定位",control:"text"},{key:"priority",label:"优先级",control:"select",options:[...Cge],optionsLabels:wge},{key:"description",label:"描述",control:"textarea"},{key:"alias",label:"假名",control:"text"},{key:"gender",label:"性别",control:"text"},{key:"age",label:"年龄",control:"number"},{key:"race",label:"种族",control:"text"},{key:"personality",label:"性格",control:"tags"},{key:"motivation",label:"动机",control:"textarea"}];case"setting":return[{key:"description",label:"描述",control:"textarea"},{key:"tags",label:"标签",control:"tags"},{key:"rules",label:"规则",control:"tags"}];case"location":return[{key:"type",label:"地点类型",control:"text"},{key:"parent_id",label:"上级地点",control:"text"},{key:"description",label:"描述",control:"textarea"}];case"hook":return[{key:"status",label:"状态",control:"select",options:["planted","progressing","resolved","abandoned"],optionsLabels:s$},{key:"category",label:"类别",control:"text"},{key:"expected_payoff",label:"预期回收",control:"textarea"},{key:"payoff_timing",label:"回收时机",control:"select",options:["immediate","near_term","mid_arc","slow_burn","endgame"],optionsLabels:gP},{key:"half_life",label:"半衰期(章数)",control:"number"},{key:"is_core",label:"主线伏笔",control:"toggle"},{key:"notes",label:"备注",control:"textarea"},{key:"expected_resolve_node_id",label:"预计回收节点",control:"outline-node"}];case"event":return[{key:"description",label:"描述",control:"textarea"},{key:"tags",label:"标签",control:"tags"}];case"timepoint":return[]}return[]}function Xs(e){return xm[e]?.label??e}function qM(e,t){const n=e.filter(s=>s.relationType==="belongs_to"&&s.sourceType==="setting"&&s.targetType==="setting"),r=[];let o=null;for(const s of n){const i={relationId:s.id,parentId:s.targetId,parentName:s.targetName,childId:s.sourceId,childName:s.sourceName};s.sourceId===t?o===null&&(o=i):s.targetId===t&&r.push(i)}return{parent:o,children:r}}function mg(e,t){const n={};for(const r of new Set([...Object.keys(e),...Object.keys(t)])){const o=t[r];if(o===void 0)continue;const s=mU(e[r]),i=mU(o);JSON.stringify(s)!==JSON.stringify(i)&&(n[r]=o)}return Object.keys(n).length>0?n:null}function mU(e){return e==null||e===""||Array.isArray(e)&&e.length===0?null:e}const rHe=x_;function oHe(e,t){return t.type==="outline_node"&&t.nodeType===void 0&&rHe.includes(e)}function Jre(e,t,n){return Object.hasOwn(xm,e)&&xm[e].group==="mount"?!1:t===null?!0:oHe(e,t)?!1:n===void 0||Vge(e,t,n)}function sHe(e,t){return lu.filter(n=>Jre(n,e,t))}function pU(e){return e.type==="*"?"任意端点":e.type!=="outline_node"?xY[e.type]:e.nodeType===void 0?"大纲节点":Rge[e.nodeType]??"大纲节点"}function eoe(e,t,n){return Jre(e,t,n)?null:`「${Xs(e)}」不能用于 ${pU(t)} → ${pU(n)}`}function iHe(e,t,n){return Wge(e)??eoe(e,t,n)}function toe(e){const t=new Map;for(const n of e)lu.includes(n.relationType)||t.set(n.relationType,(t.get(n.relationType)??0)+1);return[...t].map(([n,r])=>({type:n,count:r})).sort((n,r)=>n.count!==r.count?r.count-n.count:n.type<r.type?-1:n.type>r.type?1:0)}function aHe(e,t){return[...e.map(n=>({value:n,label:Xs(n)})),...t.map(n=>({value:n.type,label:`${n.type} · ${n.count}`}))]}function hU(e,t){return[...e.map(n=>({value:Xs(n),label:Xs(n)})),...t.map(n=>({value:n.type,label:`${n.type} · ${n.count}`}))]}function gU(e){const t=e.trim();return lu.includes(t)?t:lu.find(r=>Xs(r)===t)??t}const jS={character:"人物",setting:"设定",location:"地点",hook:"伏笔",event:"事件",timepoint:"时间点",reference:"参考资料"};function lHe(e,t){return String(t?.label??"").toLowerCase().includes(e.toLowerCase())}function Mm({source:e,lockTargetType:t,relationTypes:n,onCreated:r,onClose:o}){const s=lt(B=>B.outline),[i,a]=d.useState([]),[l,c]=d.useState("character"),[u,p]=d.useState(null),[h,b]=d.useState(""),[y,x]=d.useState(t??"character"),[S,C]=d.useState(null),[E,w]=d.useState(""),$=e===null?{type:l}:e.type==="outline_node"?{type:"outline_node",nodeType:e.nodeType}:{type:e.type},N=y==="outline_node"&&E!==""?vi(s?.children??[],E):null,M=N?{type:"outline_node",nodeType:N.type}:{type:y},k=n??sHe($,M),[R,A]=d.useState(()=>hU(k,[])[0]?.value??""),O=`${$.type}:${$.nodeType??""}→${M.type}:${M.nodeType??""}`;d.useEffect(()=>{I(null),A(B=>B!==""&&eoe(gU(B),$,M)!==null?"":B)},[O]);const[j,L]=d.useState(null),[z,I]=d.useState(null),[P,D]=d.useState(!1);d.useEffect(()=>{let B=!1;return cu({depth:1}).then(F=>{B||a(toe(F.relations))}).catch(()=>{B||a([])}),()=>{B=!0}},[]),d.useEffect(()=>{e||(b(""),p(null),zo(l,{limit:100}).then(B=>p(B.items)).catch(()=>p([])))},[e,l]),d.useEffect(()=>{if(w(""),y==="outline_node"){C(null);return}C(null),zo(y,{limit:100}).then(B=>C(B.items)).catch(()=>C([]))},[y]);const U=r$(s?.children??[]),V=hU(k,i),W=gU(R);async function q(B){if(B.preventDefault(),!e&&!h){I("请选择源实体");return}if(!E){I("请选择关联对象");return}const F=iHe(W,$,M);if(F!==null){I(F);return}D(!0),I(null);try{const G={source_type:e?e.type:l,source_id:e?e.id:h,target_type:y,target_id:E,relation_type:W};await uu(G),$e.getState().showToast("已建立关系"),await r(),o()}catch(G){G instanceof Ze&&G.code==="RELATION_EXISTS"?I("这条关系已经存在"):I(G instanceof Ze?G.message:"创建失败,请重试")}finally{D(!1)}}return m.jsx(bo,{open:!0,onOpenChange:B=>!B&&o(),children:m.jsxs(yo,{className:"sm:max-w-2xl",children:[m.jsx(lo,{children:m.jsx(co,{children:"新增关联"})}),m.jsxs("form",{id:"create-relation-form",onSubmit:q,className:"flex flex-col gap-3",children:[m.jsxs("div",{className:"grid grid-cols-1 items-start gap-3 sm:grid-cols-[1fr_auto_1fr]",children:[m.jsxs("div",{className:"flex flex-col gap-2",children:[m.jsx("p",{className:"text-sm font-medium text-foreground",children:"源实体"}),e?m.jsxs("div",{title:e.name,className:"min-w-0 truncate rounded-md border border-border bg-muted/40 px-3 py-1.5 text-sm text-foreground",children:[e.type==="outline_node"?"本节点":"本实体",":",e.name]}):m.jsxs(m.Fragment,{children:[m.jsx(xn,{className:"w-full",value:l,onChange:B=>c(B),options:Mx.map(B=>({value:B,label:jS[B]}))}),m.jsx(xn,{className:"w-full",value:h,onChange:B=>b(B),options:[{value:"",label:`选择${jS[l]}…`},...(u??[]).map(B=>({value:B.id,label:B.name}))]})]})]}),m.jsxs("div",{className:"flex flex-col gap-2 sm:w-44",children:[m.jsx("p",{className:"text-sm font-medium text-foreground",children:"关系类型"}),m.jsx(bj,{className:"w-full","aria-label":"关系类型",value:R,searchValue:j??void 0,onSearch:B=>L(B),onOpenChange:B=>{if(B){L("");return}A(F=>{const G=j;return G!==null&&G.trim()!==""?G:F}),L(null)},onChange:B=>{A(B??""),L(null)},options:V,filterOption:lHe,notFoundContent:`将新建『${j??R}』`,popupMatchSelectWidth:!1}),m.jsx("span",{"aria-hidden":"true",className:"mt-auto pb-1 text-center text-xl leading-none text-muted-foreground select-none",children:"→"})]}),m.jsxs("div",{className:"flex flex-col gap-2",children:[m.jsx("p",{className:"text-sm font-medium text-foreground",children:"目标实体"}),t===void 0?m.jsx(xn,{className:"w-full",value:y,onChange:B=>x(B),options:[{value:"character",label:"人物"},{value:"setting",label:"设定"},{value:"location",label:"地点"},{value:"hook",label:"伏笔"},{value:"outline_node",label:"大纲节点"}]}):m.jsx("div",{className:"min-w-0 truncate rounded-md border border-border bg-muted/40 px-3 py-1.5 text-sm text-foreground",children:jS[t]}),y==="outline_node"?m.jsx(xn,{className:"w-full",value:E,onChange:B=>w(B),options:[{value:"",label:"选择大纲节点…"},...U.map(B=>({value:B.id,label:`${" ".repeat(B.depth)}${B.label}`}))]}):m.jsx(xn,{className:"w-full",value:E,onChange:B=>w(B),options:[{value:"",label:`选择${jS[y]}…`},...(S??[]).map(B=>({value:B.id,label:B.name}))]})]})]}),z&&m.jsx("p",{className:"text-sm text-destructive",children:z})]}),m.jsxs(xo,{children:[m.jsx(de,{onClick:o,disabled:P,children:"取消"}),m.jsx(de,{type:"primary",htmlType:"submit",form:"create-relation-form",disabled:P,children:"建立"})]})]})})}const cHe=40,uHe=500;function noe(e){return{label:typeof e?.label=="string"?e.label:"",description:typeof e?.description=="string"?e.description:""}}function roe(e,t){return{...e,label:t.label.trim(),description:t.description.trim()}}const bU="flex flex-col gap-1",yU="text-sm font-medium text-foreground";function ooe({value:e,onChange:t}){return m.jsxs("div",{className:"flex flex-col gap-3",children:[m.jsxs("div",{className:bU,children:[m.jsx("p",{className:yU,children:"短标签"}),m.jsx(kt,{"aria-label":"短标签",value:e.label,maxLength:cHe,showCount:!0,placeholder:"画布连线上显示,可留空",onChange:n=>t({...e,label:n.target.value})})]}),m.jsxs("div",{className:bU,children:[m.jsx("p",{className:yU,children:"说明"}),m.jsx(kt.TextArea,{"aria-label":"说明",rows:4,value:e.description,maxLength:uHe,showCount:!0,placeholder:"这段关系的来龙去脉,可留空",onChange:n=>t({...e,description:n.target.value})})]})]})}function xU(e,t){const n=t==="source"?e.sourceName:e.targetName,r=t==="source"?e.sourceId:e.targetId;return n??r}function dHe({relation:e,onSaved:t,onClose:n}){const[r,o]=d.useState(()=>noe(e.metadata)),[s,i]=d.useState(!1),[a,l]=d.useState(null);async function c(u){u.preventDefault(),i(!0),l(null);try{await BY(e.id,roe(e.metadata,r)),$e.getState().showToast("已保存关系说明"),t(),n()}catch(p){l(p instanceof Ze?p.message:"保存失败,请重试")}finally{i(!1)}}return m.jsx(bo,{open:!0,onOpenChange:u=>!u&&n(),children:m.jsxs(yo,{className:"sm:max-w-lg",children:[m.jsxs(lo,{children:[m.jsx(co,{children:"编辑关系说明"}),m.jsxs(hu,{children:[xU(e,"source")," ",Xs(e.relationType)," →"," ",xU(e,"target")]})]}),m.jsxs("form",{id:"edit-relation-meta-form",onSubmit:c,className:"flex flex-col gap-3",children:[m.jsx(ooe,{value:r,onChange:o}),a!==null&&m.jsx("p",{className:"text-xs text-destructive",children:a}),m.jsxs(xo,{children:[m.jsx(de,{onClick:n,disabled:s,children:"取消"}),m.jsx(de,{type:"primary",htmlType:"submit",loading:s,children:"保存"})]})]})]})})}const soe={...xY,outline_node:"大纲节点"},vU=Object.entries(soe).map(([e,t])=>({value:e,label:t})),SU={sourceType:"",targetType:"",relationType:"",nameQuery:""};function fHe(e,t){const n=t.nameQuery.trim().toLowerCase();return e.filter(r=>{if(t.sourceType!==""&&r.sourceType!==t.sourceType||t.targetType!==""&&r.targetType!==t.targetType||t.relationType!==""&&r.relationType!==t.relationType)return!1;if(n){const o=(r.sourceName??r.sourceId).toLowerCase(),s=(r.targetName??r.targetId).toLowerCase();if(!o.includes(n)&&!s.includes(n))return!1}return!0})}function CU({type:e}){return m.jsx(qr,{className:"shrink-0",children:soe[e]??e})}function GM({type:e,id:t,name:n}){const r=n??t;if(!(Mx.includes(e)||e==="outline_node"))return m.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[m.jsx(CU,{type:e}),m.jsx("span",{className:"min-w-0 truncate text-muted-foreground",title:r,children:r})]});const s=e==="outline_node"?`/outline/${t}`:Nd(e,t);return m.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[m.jsx(CU,{type:e}),m.jsx("button",{type:"button",onClick:()=>en(s),title:`打开《${r}》`,className:"min-w-0 truncate font-medium text-foreground underline-offset-2 hover:text-primary hover:underline",children:r})]})}function ch(e,t){const n=t==="source"?e.sourceName:e.targetName,r=t==="source"?e.sourceId:e.targetId;return n??r}function ioe({reloadKey:e,onOpenCreate:t,scope:n}){const[r,o]=d.useState(null),[s,i]=d.useState(!1),[a,l]=d.useState(null),[c,u]=d.useState(0),[p,h]=d.useState(SU),[b,y]=d.useState(null),[x,S]=d.useState(null);d.useEffect(()=>{let $=!1;i(!0),l(null);const N=n!==void 0?{source_type:n.type,source_id:n.id,depth:1}:{depth:1};return cu(N).then(M=>{$||o(M.relations)}).catch(M=>{$||(o(null),l(M instanceof Ze?M.code:yn))}).finally(()=>{$||i(!1)}),()=>{$=!0}},[e,c,n?.type,n?.id]);async function C(){if(b)try{await am(b.id),$e.getState().showToast("已删除关系"),y(null),u($=>$+1)}catch($){throw $}}const E=r===null?[]:fHe(r,p),w=aHe(lu,r===null?[]:toe(r));return m.jsxs("div",{children:[n===void 0&&m.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[m.jsx("div",{className:"w-48",children:m.jsx(kt,{prefix:m.jsx(Zd,{}),allowClear:!0,value:p.nameQuery,onChange:$=>h(N=>({...N,nameQuery:$.target.value})),placeholder:"搜索源/目标名称…"})}),m.jsx(xn,{size:"medium",value:p.sourceType===""?void 0:p.sourceType,onChange:$=>h(N=>({...N,sourceType:$===void 0?"":String($)})),"aria-label":"源端点类型过滤",prefix:m.jsx("span",{className:"text-xs text-muted-foreground",children:"源"}),placeholder:"全部类型",allowClear:!0,style:{minWidth:140},options:vU}),m.jsx(xn,{size:"medium",value:p.targetType===""?void 0:p.targetType,onChange:$=>h(N=>({...N,targetType:$===void 0?"":String($)})),"aria-label":"目标端点类型过滤",prefix:m.jsx("span",{className:"text-xs text-muted-foreground",children:"目标"}),placeholder:"全部类型",allowClear:!0,style:{minWidth:140},options:vU}),m.jsx(xn,{size:"medium",value:p.relationType===""?void 0:p.relationType,onChange:$=>h(N=>({...N,relationType:$===void 0?"":String($)})),"aria-label":"关系类型过滤",placeholder:"全部关系类型",allowClear:!0,style:{minWidth:140},options:w}),m.jsx(de,{type:"primary",className:"ml-auto",onClick:t,children:"+ 建立关联"})]}),n===void 0&&m.jsx(mP,{className:"mb-4"}),a!==null&&m.jsx(Za,{className:"mb-3",type:"error",showIcon:!0,message:a===yn?"无法连接服务,请确认 ai-editor 服务已启动。":"关系加载失败,请重试。",action:m.jsx(de,{size:"small",onClick:()=>u($=>$+1),children:"重试"})}),s&&r===null&&a===null&&m.jsx("div",{className:"rounded-md border border-border p-3",children:m.jsx(Mo,{active:!0,title:!1,paragraph:{rows:5}})}),!s&&r!==null&&r.length===0&&m.jsx(Hn,{padding:"sm",action:m.jsx(de,{type:"primary",onClick:t,children:"+ 建立关联"}),children:"还没有关联,建立一条"}),!s&&r!==null&&r.length>0&&E.length===0&&m.jsx(Hn,{padding:"sm",action:m.jsx(de,{onClick:()=>h(SU),children:"清空过滤"}),children:"没有匹配的关联"}),!s&&r!==null&&E.length>0&&m.jsxs("div",{className:"overflow-hidden rounded-md border border-border",children:[n===void 0&&m.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground",children:[m.jsx("span",{className:"w-1/4 shrink-0",children:"源"}),m.jsx("span",{className:"w-1/4 shrink-0",children:"关系"}),m.jsx("span",{className:"flex-1",children:"目标"}),m.jsx("span",{className:"w-14 shrink-0"})]}),m.jsx("ul",{className:"divide-y divide-border",children:E.map($=>m.jsxs("li",{className:"flex items-center gap-2 px-3 py-2 text-sm",children:[n!==void 0?m.jsxs(m.Fragment,{children:[m.jsxs(qr,{className:"shrink-0 truncate",children:[Xs($.relationType)," →"]}),m.jsx("span",{className:"min-w-0 flex-1",children:m.jsx(GM,{type:$.targetType,id:$.targetId,name:$.targetName})})]}):m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"w-1/4 min-w-0 shrink-0",children:m.jsx(GM,{type:$.sourceType,id:$.sourceId,name:$.sourceName})}),m.jsx("div",{className:"w-1/4 min-w-0 shrink-0",children:m.jsxs(qr,{className:"max-w-full truncate",children:[Xs($.relationType)," →"]})}),m.jsx("span",{className:"min-w-0 flex-1",children:m.jsx(GM,{type:$.targetType,id:$.targetId,name:$.targetName})})]}),m.jsx(de,{color:"default",variant:"text",size:"small","aria-label":`编辑关系说明(${ch($,"source")} → ${ch($,"target")})`,title:"编辑说明",icon:m.jsx(cc,{}),onClick:()=>S($)}),m.jsx(de,{color:"danger",variant:"text",size:"small","aria-label":`删除关系(${ch($,"source")} → ${ch($,"target")})`,title:"删除(物理删,可重新建立)",icon:m.jsx(ss,{}),onClick:()=>y($)})]},$.id))})]}),x&&m.jsx(dHe,{relation:x,onSaved:()=>u($=>$+1),onClose:()=>S(null)}),b&&m.jsx(Mi,{title:"删除关系",description:`删除关系「${ch(b,"source")} ${Xs(b.relationType)} ${ch(b,"target")}」?物理删除不可恢复,可重新建立。`,confirmLabel:"删除",danger:!0,onConfirm:C,onClose:()=>y(null)})]})}const mHe={set:"设为",update:"更新",add:"追加",remove:"移除"},pHe={character:"人物",setting:"设定",location:"地点",hook:"伏笔",outline_node:"大纲节点"};function bP(e){return pHe[e]??e}function Oa(e){return e==null?"空":typeof e=="object"?JSON.stringify(e):String(e)}function hHe(e){switch(e.op){case"set":return`${e.field} = ${Oa(e.to)}`;case"update":return`${e.field} ${Oa(e.from)} → ${Oa(e.to)}`;case"add":return`${e.field} +${Oa(e.value??e.to)}`;case"remove":return`${e.field} -${Oa(e.value??e.to)}`}}function gHe(e,t){const n=[];for(const r of new Set([...Object.keys(e),...Object.keys(t)])){const o=e[r]??null,s=t[r]??null;JSON.stringify(o)!==JSON.stringify(s)&&n.push({field:r,from:e[r],to:t[r]})}return n}function aoe({changes:e,skipped:t}){const n=t?new Set(t):null;return m.jsx("div",{className:"flex flex-wrap items-center gap-1",children:e.map((r,o)=>{const s=n?.has(o)??!1;return m.jsxs("span",{title:s?"该变更未应用(数据与变更记录不一致,见冲突标注)":void 0,className:et("inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-xs",s?"text-destructive":"text-muted-foreground"),children:[m.jsx("span",{className:et("shrink-0 font-medium",s?"text-destructive":"text-foreground/70"),children:mHe[r.op]}),hHe(r)]},o)})})}function bHe({nodeId:e,reloadKey:t}){const[n,r]=d.useState(null),[o,s]=d.useState(!1),[i,a]=d.useState(null),[l,c]=d.useState(0);return d.useEffect(()=>{let u=!1;return s(!0),a(null),Rbe(e).then(p=>{u||r([...p.deltas].sort((h,b)=>h.order-b.order))}).catch(p=>{u||a(p instanceof Ze?p.code:yn)}).finally(()=>{u||s(!1)}),()=>{u=!0}},[e,l,t]),m.jsxs("div",{children:[o&&n===null&&i===null&&m.jsxs("div",{className:"space-y-2 py-1",children:[m.jsx("div",{className:et(wr,"h-4 w-2/3")}),m.jsx("div",{className:et(wr,"h-4 w-1/2")})]}),i!==null&&m.jsxs("div",{className:"flex items-center gap-2 text-xs text-destructive",children:[m.jsx("span",{children:i==="OUTLINE_NODE_NOT_FOUND"?"节点不存在(可能已被删除),变更记录不可用":i===yn?"无法连接服务,请确认 ai-editor 服务已启动":"变更记录加载失败"}),i!=="OUTLINE_NODE_NOT_FOUND"&&m.jsx(de,{size:"small",onClick:()=>c(u=>u+1),children:"重试"})]}),!o&&i===null&&n!==null&&n.length===0&&m.jsx("p",{className:"py-1 text-xs text-muted-foreground",children:"该节点没有变更记录"}),!o&&i===null&&n!==null&&n.length>0&&m.jsx("ul",{className:"divide-y divide-border/70",children:n.map(u=>m.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[m.jsxs("div",{className:"flex items-baseline gap-2",children:[m.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-foreground",title:u.description,children:u.description}),m.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:na(u.createdAt)})]}),m.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[m.jsxs("span",{className:"shrink-0 rounded bg-muted px-1.5 py-0.5 text-xs text-muted-foreground",children:[bP(u.targetType),"《",u.targetName??u.targetId,"》"]}),m.jsx(aoe,{changes:u.changes})]})]},u.id))})]})}const yHe=Mx.filter(e=>e!=="event"&&e!=="timepoint"&&e!=="reference").map(e=>({value:e,label:bP(e)})),xHe={character:["role","description","alias","gender","age","race","personality","motivation","ability_panel","custom_fields"],setting:["description","tags","rules","custom_fields"],location:["type","parent_id","description","custom_fields"],hook:["status","category","expected_payoff","payoff_timing","half_life","is_core","notes","expected_resolve_node_id"]},vHe={character:PS("character"),setting:PS("setting"),location:PS("location"),hook:PS("hook")};function PS(e){return Object.fromEntries(i$(e).map(t=>[t.key,t.label]))}const SHe={character:["personality"],setting:["tags","rules"]},CHe={character:["age"],hook:["half_life"]};function wU(e,t){return(Age[e]??[]).includes(t)}function rO(e,t){return(SHe[e]??[]).includes(t)}function wHe(e,t){return(CHe[e]??[]).includes(t)}const EHe=["custom_fields","ability_panel"];function $He(e,t){const n=xHe[e]??[],r=CY[e]??[],o=n.filter(i=>!EHe.includes(i)&&!r.includes(i)).map(i=>({key:i,label:vHe[e]?.[i]??i,array:rO(e,i)}));if(e!=="character"||t===void 0)return o;const s=NY(t).map(i=>({key:TY(i),label:i.path,array:!1,numeric:typeof i.value=="number",panelLeaf:!0}));return[...o,...s]}function EU(e,t,n){return e==="character"&&t.startsWith("ability_panel.")?NY(n?.ability_panel).find(o=>TY(o)===t)?.value:n?.[t]}function loe(e){if(e!==void 0){if(e===null)return null;if(typeof e=="string"||typeof e=="number")return e}}function $U(e){return e.setOnly===!0?{options:["set"],default:"set"}:e.array?{options:["add","remove"],default:"add"}:loe(e.currentValue)!==void 0?{options:["update","set"],default:"update"}:{options:["set"],default:"set"}}function THe(e){const t=e.rawValue.trim();if(t==="")return{error:"请填写值"};const n=Number(t),r=e.panelLeaf?kY(t)??t:e.numeric&&!Number.isNaN(n)?n:t;switch(e.op){case"add":return{change:{field:e.field,op:"add",value:r}};case"remove":return{change:{field:e.field,op:"remove",value:r}};case"set":return{change:{field:e.field,op:"set",to:r}};case"update":{const o=loe(e.currentValue);return o===void 0?{error:"无法确定旧值(当前数据无此字段或类型不可表达),请改用「设为」"}:{change:{field:e.field,op:"update",from:o,to:r}}}}}const NHe={set:"设为",update:"更新",add:"追加",remove:"移除"};function kHe({nodeId:e,onCreated:t,onClose:n}){const[r,o]=d.useState(""),[s,i]=d.useState(""),[a,l]=d.useState(""),[c,u]=d.useState("add"),[p,h]=d.useState(""),[b,y]=d.useState(""),[x,S]=d.useState(!1),[C,E]=d.useState(null),[w,$]=d.useState(null),[N,M]=d.useState(null),[k,R]=d.useState(0),[A,O]=d.useState(null),[j,L]=d.useState(null);d.useEffect(()=>{if(i(""),O(null),L(null),r===""){$(null),M(null);return}let F=!1;return $(null),M(null),zo(r).then(G=>{F||$(G.items)}).catch(G=>{F||($(null),M(G instanceof Ze?G.code:yn))}),()=>{F=!0}},[r,k]),d.useEffect(()=>{if(r===""||s==="")return;let F=!1;return O(null),L(null),ja(r,s).then(G=>{F||O(G.data)}).catch(G=>{F||(O(null),L(G instanceof Ze?G.code:yn))}),()=>{F=!0}},[r,s]),d.useEffect(()=>{l(""),h(""),E(null)},[r,s]);const z=$He(r,A?.ability_panel),I=z.find(F=>F.key===a),P=EU(r,a,A),D=I?.numeric??wHe(r,a),U=wU(r,a),V=$U({array:rO(r,a),currentValue:P,setOnly:U});function W(F){l(F),u($U({array:rO(r,F),currentValue:EU(r,F,A),setOnly:wU(r,F)}).default)}async function q(){if(x)return;if(r===""||s===""){E("请选择变更目标");return}if(a===""){E("请选择变更字段");return}const F=b.trim();if(F===""){E("请填写描述(本节点触发了什么变化)");return}const G=THe({field:a,op:c,rawValue:p,numeric:D,currentValue:P,panelLeaf:I?.panelLeaf===!0});if("error"in G){E(G.error);return}S(!0),E(null);try{await $_({node_id:e,target_type:r,target_id:s,changes:[G.change],description:F}),$e.getState().showToast("已记录变更"),t()}catch(J){if(J instanceof Ze&&J.code==="OUTLINE_NODE_NOT_FOUND"){$e.getState().showToast("节点不存在(可能已被删除),无法记录变更","error"),n();return}E(J instanceof Ze?J.message:"提交失败,请重试")}finally{S(!1)}}const B=r;return m.jsxs("div",{className:"mb-3 space-y-3 rounded-md border border-border bg-muted/40 p-3",children:[m.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[m.jsxs("div",{children:[m.jsx("p",{className:"mb-1 text-xs font-medium text-foreground",children:"目标类型"}),m.jsx(xn,{className:"w-full",value:r,onChange:F=>o(F),"aria-label":"目标类型",options:[{value:"",label:"请选择目标类型"},...yHe.map(F=>({value:F.value,label:F.label}))]})]}),m.jsxs("div",{children:[m.jsx("p",{className:"mb-1 text-xs font-medium text-foreground",children:"目标"}),r===""?m.jsx("p",{className:"py-1 text-xs text-muted-foreground",children:"请先选择目标类型"}):N!==null?m.jsxs("div",{className:"flex items-center gap-2 text-xs text-destructive",children:[m.jsx("span",{children:N===yn?"无法连接服务,请确认 ai-editor 服务已启动":"实体列表加载失败"}),m.jsx(de,{size:"small",onClick:()=>R(F=>F+1),children:"重试"})]}):w===null?m.jsx("p",{className:"py-1 text-xs text-muted-foreground",children:"加载中…"}):w.length===0?m.jsxs("p",{className:"py-1 text-xs text-muted-foreground",children:["暂无",TU(B)]}):m.jsx(xn,{className:"w-full",value:s,onChange:F=>i(F),"aria-label":"目标实体",options:[{value:"",label:`请选择${TU(B)}`},...w.map(F=>({value:F.id,label:F.name}))]})]})]}),m.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr_auto_1fr]",children:[m.jsxs("div",{children:[m.jsx("p",{className:"mb-1 text-xs font-medium text-foreground",children:"字段"}),m.jsx(xn,{className:"w-full",value:a,onChange:F=>W(F),"aria-label":"变更字段",options:[{value:"",label:"请选择字段"},...z.map(F=>({value:F.key,label:F.label}))]})]}),m.jsxs("div",{children:[m.jsx("p",{className:"mb-1 text-xs font-medium text-foreground",children:"操作"}),m.jsx("span",{className:"block",title:U?"该字段为事实字段(写路径同步当前值),只能「设为」":void 0,children:m.jsx(xn,{className:"w-full min-w-20",value:c,onChange:F=>u(F),"aria-label":"操作",options:V.options.map(F=>({value:F,label:NHe[F]}))})})]}),m.jsxs("div",{children:[m.jsx("p",{className:"mb-1 text-xs font-medium text-foreground",children:c==="set"||c==="update"?"新值":c==="add"?"追加值":"移除值"}),m.jsx(kt,{autoComplete:"off",value:p,onChange:F=>h(F.target.value),placeholder:c==="remove"?"按值匹配删除":""})]})]}),c==="update"&&m.jsx("p",{className:"text-xs text-muted-foreground",children:j!==null?m.jsxs(m.Fragment,{children:["目标数据获取失败,无法自动取旧值(",j==="ENTITY_NOT_FOUND"?"目标已不存在":"请稍后重试",")——可将操作改为「设为」"]}):m.jsxs(m.Fragment,{children:["旧值:",Oa(P),"(自动取自目标当前数据,无需手填)"]})}),m.jsxs("div",{children:[m.jsx("p",{className:"mb-1 text-xs font-medium text-foreground",children:"描述"}),m.jsx(kt.TextArea,{className:"resize-none",value:b,onChange:F=>y(F.target.value),rows:2,maxLength:500,placeholder:"本节点触发了什么变化,如:张三获得断剑认可"})]}),C!==null&&m.jsx("p",{className:"text-sm text-destructive",children:C}),m.jsxs("div",{className:"flex items-center justify-end gap-2",children:[m.jsx(de,{onClick:n,disabled:x,children:"取消"}),m.jsx(de,{type:"primary",onClick:()=>{q()},disabled:x,children:x?"提交中…":"创建变更"})]})]})}function TU(e){return bP(e)}function MHe(e,t){return t<0||t>=e.length?null:t<e.length-1?{append:!1,focusIndex:t+1}:e[t].trim()!==""?{append:!0,focusIndex:e.length}:null}function RHe(e,t,n){if(t===n)return[...e];if(t<0||t>=e.length||n<0||n>=e.length)return[...e];const r=[...e],[o]=r.splice(t,1);return r.splice(n,0,o),r}function eE({id:e,options:t}){return t.length===0?null:m.jsx("datalist",{id:e,children:t.map(n=>m.jsx("option",{value:n},n))})}function KM(e){const t=new Set,n=[];for(const r of e)typeof r=="string"&&r!==""&&!t.has(r)&&(t.add(r),n.push(r));return n}const NU="entity-tags-suggestions";function yP({values:e,onChange:t,placeholder:n,suggestions:r,quickTags:o}){const s=d.useRef([]),[i,a]=d.useState(null),[l,c]=d.useState(null);return m.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.map((u,p)=>m.jsxs("div",{className:et("flex items-center gap-1.5 rounded-md px-0.5 py-0.5 transition-colors",i===p&&"opacity-40",l===p&&i!==null&&i!==p&&"bg-muted/60 ring-1 ring-ring"),onDragOver:h=>{i!==null&&(h.preventDefault(),h.dataTransfer.dropEffect="move",l!==p&&c(p))},onDrop:h=>{i!==null&&(h.preventDefault(),i!==p&&t(RHe(e,i,p)),a(null),c(null))},children:[m.jsx("span",{className:"flex shrink-0 cursor-grab active:cursor-grabbing",children:m.jsx(de,{color:"default",variant:"text",size:"small",draggable:!0,title:"拖拽排序","aria-label":"拖拽排序",onDragStart:h=>{a(p),h.dataTransfer.effectAllowed="move",h.dataTransfer.setData("text/plain",String(p))},onDragEnd:()=>{a(null),c(null)},icon:m.jsx(Ete,{className:"text-base"})})}),m.jsx(kt,{value:u,onChange:h=>{const b=[...e];b[p]=h.target.value,t(b)},ref:h=>{s.current[p]=h},onKeyDown:h=>{if(h.key!=="Enter")return;h.preventDefault();const b=MHe(e,p);b&&(b.append&&t([...e,""]),requestAnimationFrame(()=>s.current[b.focusIndex]?.focus()))},placeholder:n,list:r&&r.length>0?NU:void 0,className:"flex-1"}),m.jsx(de,{onClick:()=>t(e.filter((h,b)=>b!==p)),children:"删除"})]},p)),m.jsx(de,{className:"self-start",onClick:()=>t([...e,""]),children:"+ 添加"}),o&&o.length>0&&m.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[m.jsx("span",{className:"text-xs text-muted-foreground",children:"已有标签:"}),o.filter(u=>!e.includes(u)).map(u=>m.jsx("button",{type:"button",onClick:()=>t([...e,u]),className:"rounded-md border border-border px-1.5 py-0.5 text-xs text-foreground hover:bg-muted hover:text-foreground",children:u},u))]}),r&&r.length>0&&m.jsx(eE,{id:NU,options:r})]})}const IHe=2;function xP(e){if(typeof e!="object"||e===null)return[];const t=e.tags;return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n!==""):[]}function coe(e){const t=e.slice(0,IHe);return{visible:t,overflow:e.length-t.length}}const AHe={inner:"内心冲突",personal:"人际冲突",extra_personal:"社会冲突"};function OHe(e){switch(e){case"scene":return[{key:"goal",label:"场景目标",control:"textarea",maxLength:1e3},{key:"conflict_levels",label:"冲突层次",control:"checkbox-group",options:SY,optionsLabels:AHe},{key:"value_from",label:"开场价值",control:"text",maxLength:200},{key:"value_to",label:"收场价值",control:"text",maxLength:200}];case"chapter":return[{key:"status",label:"状态",control:"select",options:v_,optionsLabels:S_,defaultValue:"draft"},{key:"tags",label:"剧情线标签",control:"tags"},{key:"function",label:"叙事功能",control:"select",options:$ge,optionsLabels:Tge},{key:"tension",label:"张力度",control:"select",options:Nge,optionsLabels:kge},{key:"reversal",label:"章末反转",control:"textarea",maxLength:1e3},{key:"climax_scene",label:"章高潮场景",control:"scene-select"}];case"volume":return[{key:"climax_scene",label:"幕高潮场景",control:"scene-select"},{key:"inciting_scene",label:"激励事件",control:"scene-select"}]}}function _He(e){const t=new Map,n=r=>{for(const o of r){if(o.type==="chapter"||o.type==="scene")for(const s of xP(o.data))t.set(s,(t.get(s)??0)+1);o.type!=="scene"&&o.children&&n(o.children)}};return n(e),[...t].map(([r,o])=>({value:r,count:o})).sort((r,o)=>o.count-r.count||r.value.localeCompare(o.value,"zh"))}function jHe(e,t){return SY.includes(t)?e.includes(t)?e.filter(n=>n!==t):[...e,t]:e}function PHe(e){const t=[],n=(r,o)=>{for(const s of r)s.type==="scene"?t.push({id:s.id,label:s.title,depth:o}):s.children&&n(s.children,o+1)};return n(e,0),t}function uoe(e,t={}){let n=e;if(Array.isArray(e.tags)){const r=e.tags.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o!=="");n={...n,tags:r}}if(typeof n.result_summary=="string"){const{result_summary:r,...o}=n,s=r.trim(),i=DHe(t.result_summary)!=="";n=s!==""?{...o,result_summary:s}:i?{...o,result_summary:""}:o}return n}function DHe(e){return typeof e=="string"?e.trim():""}function doe(e,t){const n=uoe(t,e);return{normalizedData:n,dataPatch:mg(e,n)}}function LHe(e){return typeof e=="string"&&e!==""?e:""}const vP=1500;function foe({delayMs:e,save:t}){let n=null,r=null;const o=()=>{n!==null&&(clearTimeout(n),n=null)};function s(){if(o(),r===null)return Promise.resolve();const i=r;return r=null,t(i)}return{schedule(i){r=i,o(),n=setTimeout(()=>{s()},e)},flush:s,reset(){o(),r=null}}}function zHe(e,t){const n=o$(e).chapterRows,r=n.findIndex(o=>o.chapter.id===t);return r===-1?{prev:null,next:null}:{prev:n[r-1]??null,next:n[r+1]??null}}function tv(e){if(!Number.isFinite(e)||e<=0)return null;const t=Math.floor(e);return t<1e3?`${t} 字`:`${(t/1e3).toFixed(1).replace(/\.0$/,"")} 千字`}function SP(e){const t=String(e.getHours()).padStart(2,"0"),n=String(e.getMinutes()).padStart(2,"0");return`${t}:${n}`}const BHe=".ant-popover, .ant-dropdown, [role='dialog'], .bn-ak-popover, .bn-ak-menu";function HHe(){for(const e of document.querySelectorAll(BHe))if(e.checkVisibility())return!0;return!1}function FHe(e){return e==="DOCUMENT_STALE"?"conflict":e==="OUTLINE_NODE_NOT_FOUND"?"missing":"retry"}function VHe(e){return e==="chapter"}async function moe(e){try{return await lt.getState().updateConfig({current_position:e}),$e.getState().showToast("已设为阅读进度"),!0}catch{return $e.getState().showToast("设置失败:该节点可能已删除,无法设为阅读进度","error"),!1}}function poe(e){return e==="chapter"}function UHe(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e,t]}function hoe(e,t){return UHe(e.map(n=>n.nodeId),t)}function goe(e){return e?"移出推演节点":"标记为推演节点"}function boe(e,t){const n=`${e.label}(第${e.chapterNumber}章)`;return t>1?`${n} · 第 ${e.index} / 共 ${t} 个推演节点`:n}async function WHe(){try{return await lt.getState().updateConfig({deduction_nodes:[]}),$e.getState().showToast("已清除全部推演节点标记"),!0}catch{return $e.getState().showToast("清除失败,请重试","error"),!1}}async function yoe(e){const t=lt.getState().config?.deductionNodes??[];try{return await lt.getState().updateConfig({deduction_nodes:e}),$e.getState().showToast(e.length<t.length?"已移出推演节点":"已标记为推演节点"),!0}catch{return $e.getState().showToast("标记失败:该节点可能已删除或不可见,无法标记为推演节点","error"),!1}}function kU(e,t,n,r){const o=e.data??{},s=uoe(o),{normalizedData:i}=doe(s,r);return pP(e.title,t)||hP(e.summary,n)||mg(s,qHe(s,i))!==null}function qHe(e,t){return e.status!==void 0||t.status!=="draft"?t:{...t,status:void 0}}function GHe({node:e,nodeId:t,onReload:n,leading:r,headerActions:o,onDirtyChange:s,onNavigate:i}){const a=lt(oe=>oe.outline),l=lt(oe=>oe.config),[c,u]=d.useState(e.title),[p,h]=d.useState(e.summary??""),[b,y]=d.useState(()=>JSON.parse(JSON.stringify(e.data??{}))),[x,S]=d.useState(e),[C,E]=d.useState(!1),[w,$]=d.useState(null),[N,M]=d.useState(!1),[k,R]=d.useState(!1),[A,O]=d.useState(!1),[j,L]=d.useState(0),[z,I]=d.useState(!1),[P,D]=d.useState(0);Hs(()=>{L(oe=>oe+1),D(oe=>oe+1)});const U=OHe(e.type),V=PHe(a?.children??[]),W=d.useMemo(()=>_He(a?.children??[]).map(oe=>oe.value),[a]),q=l?.currentPosition===t,B=VHe(e.type),F=d.useMemo(()=>C_(a,l?.deductionNodes??[]),[a,l?.deductionNodes]),G=F.find(oe=>oe.nodeId===t),J=$e(oe=>oe.setCurrentFocus),te=F.length>0;d.useEffect(()=>{J(te?{focus_deduction:!0}:null)},[te,J]);const ne=poe(e.type),K=tv(e.type==="chapter"?e.metadata?.textLength??0:0);d.useEffect(()=>{if(e.id!==x.id){u(e.title),h(e.summary??""),y(JSON.parse(JSON.stringify(e.data??{}))),S(e);return}kU(x,c,p,b)||(u(e.title),h(e.summary??""),y(JSON.parse(JSON.stringify(e.data??{}))),S(e))},[e]);const ee=kU(x,c,p,b);d.useEffect(()=>{s?.(ee)},[ee,s]),d.useEffect(()=>()=>{s?.(!1)},[s]);async function re(){if(C)return;const oe=c.trim();if(oe==="")return $("标题不能为空"),!1;const Z={};pP(x.title,c)&&(Z.title=oe),hP(x.summary,p)&&(Z.summary=p.trim());const{normalizedData:se,dataPatch:ce}=doe(x.data??{},b);if(ce!==null&&(Z.data=ce),Object.keys(Z).length===0){u(e.title),h(e.summary??""),y(JSON.parse(JSON.stringify(e.data??{}))),S(e),$e.getState().showToast("没有变更");return}E(!0),$(null);try{await LY(e.id,Z),u(oe),h(p.trim()),y(se),S({...e,title:oe,summary:p.trim(),data:se}),$e.getState().showToast("已保存"),await n()}catch(me){return me instanceof Ze&&me.code==="OUTLINE_NODE_NOT_FOUND"?(await n(),!1):($(me instanceof Ze?me.message:"保存失败,请重试"),!1)}finally{E(!1)}}function ae(oe,Z){y(se=>({...se,[oe]:Z}))}async function ue(){if(!(N||q||!B)){M(!0);try{await moe(e.id)}finally{M(!1)}}}async function Y(){if(!(k||!ne)){R(!0);try{await yoe(hoe(F,e.id))}finally{R(!1)}}}return ni(()=>re()),m.jsxs("section",{className:"flex min-h-0 flex-1 flex-col",children:[m.jsx(wi,{title:e.title,leading:r,className:"-mx-6",insetClassName:"px-6",actions:m.jsxs(m.Fragment,{children:[e.type==="chapter"&&m.jsx(de,{color:"default",variant:"text",size:"small",href:`#/writing/${e.id}`,onClick:i&&(oe=>{oe.metaKey||oe.ctrlKey||oe.shiftKey||oe.altKey||oe.button!==0||(oe.preventDefault(),i(`/writing/${e.id}`))}),icon:m.jsx(cc,{}),title:"写正文","aria-label":"写正文"}),m.jsx(de,{color:"default",variant:"text",size:"small",disabled:q||N||!B,icon:m.jsx(II,{}),"aria-label":q?"阅读进度":"设为阅读进度",title:B?q?"当前节点已是阅读进度位置":"标记为阅读进度位置(顶栏展示 + 定位跳转基准)":"仅章节点可设为阅读进度(卷/场景不可标记)",onClick:()=>{ue()}}),ne&&m.jsx(de,{color:"default",variant:"text",size:"small",disabled:k,icon:m.jsx(VI,{}),"aria-label":goe(G!==void 0),title:G!==void 0?"从推演节点集合中移出(剧情推演不再以本章为边界)":"标记为推演节点(剧情推演以本章为边界)",onClick:()=>{Y()}}),m.jsx(de,{type:"primary",size:"small",icon:m.jsx(F2,{}),loading:C,title:"保存","aria-label":"保存",onClick:()=>{re()}}),o]}),meta:m.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-hidden text-xs text-muted-foreground",children:[m.jsx(qr,{className:"shrink-0",tone:e.type==="volume"?"default":"soft",children:tc[e.type]}),m.jsxs("span",{className:"shrink-0",title:na(e.updatedAt),children:["更新于 ",f3(e.updatedAt)]}),K!==null&&m.jsx("span",{className:"shrink-0 tabular-nums",children:K}),G!==void 0&&m.jsx(qr,{className:"shrink-0",title:boe(G,F.length),children:G.label}),q&&m.jsx(qr,{className:"shrink-0",children:"阅读进度"})]})}),m.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto",children:m.jsxs("div",{className:"flex flex-col gap-4",children:[m.jsxs("div",{className:"flex min-w-0 flex-col gap-4",children:[m.jsx(tr,{title:"基础信息",children:m.jsxs("div",{className:"flex flex-col gap-3",children:[m.jsxs("div",{children:[m.jsx("p",{className:"mb-1 text-sm font-medium text-foreground",children:"标题"}),m.jsx(kt,{value:c,onChange:oe=>u(oe.target.value),maxLength:200,placeholder:`${tc[e.type]}标题`})]}),m.jsxs("div",{children:[m.jsx("p",{className:"mb-1 text-sm font-medium text-foreground",children:"摘要"}),m.jsx(kt.TextArea,{value:p,onChange:oe=>h(oe.target.value),maxLength:200,rows:3,placeholder:"一句话概括本节点内容(可选)"})]}),e.type==="chapter"&&m.jsxs("div",{children:[m.jsx("p",{className:"mb-1 text-sm font-medium text-foreground",children:"实际摘要"}),m.jsx(kt.TextArea,{value:typeof b.result_summary=="string"?b.result_summary:"",onChange:oe=>ae("result_summary",oe.target.value),maxLength:Mge,rows:3,placeholder:"写完后本章实际发生了什么(可选)"})]})]})}),m.jsxs(tr,{title:`结构化信息(${tc[e.type]})`,children:[m.jsx("div",{className:"flex flex-col gap-3",children:U.map(oe=>m.jsxs("div",{children:[m.jsx("p",{className:"mb-1 text-sm font-medium text-foreground",children:oe.label}),m.jsx(KHe,{field:oe,value:b[oe.key],sceneOptions:V,tagPool:W,onChange:Z=>ae(oe.key,Z)})]},oe.key))}),w&&m.jsx("p",{className:"mt-3 text-sm text-destructive",children:w})]}),e.type==="chapter"&&m.jsxs(tr,{title:"变更记录",action:m.jsx(de,{size:"small",onClick:()=>I(oe=>!oe),children:z?"收起":"+ 新建变更"}),children:[z&&m.jsx(kHe,{nodeId:t,onCreated:()=>{I(!1),D(oe=>oe+1)},onClose:()=>I(!1)}),m.jsx(bHe,{nodeId:t,reloadKey:P})]}),m.jsx(tr,{title:"伏笔标记",className:"border-dashed",children:m.jsx("p",{className:"text-sm text-muted-foreground",children:"伏笔标记将在伏笔面板(S9)落地"})})]}),m.jsx("div",{className:"flex min-w-0 flex-col gap-4",children:m.jsxs(tr,{title:"相关实体",children:[m.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[m.jsx("p",{className:"text-xs text-muted-foreground",children:"本节点作为源的关系(1 跳)"}),m.jsx(de,{onClick:()=>O(!0),children:"+ 新增关联"})]}),m.jsx(ioe,{scope:{type:"outline_node",id:t},reloadKey:j,onOpenCreate:()=>O(!0)})]})})]})}),A&&m.jsx(Mm,{source:{type:"outline_node",id:e.id,name:e.title,nodeType:e.type},onCreated:()=>L(oe=>oe+1),onClose:()=>O(!1)})]})}function KHe({field:e,value:t,sceneOptions:n,tagPool:r,onChange:o}){switch(e.control){case"select":{const s=typeof t=="string"&&t!==""?t:e.defaultValue??"";return m.jsx(xn,{className:"w-full",value:s,onChange:i=>o(i),options:(e.options??[]).map(i=>({value:i,label:e.optionsLabels?.[i]??i}))})}case"tags":return m.jsx(yP,{values:Array.isArray(t)?t:[],onChange:o,placeholder:"标签(回车添加,如:复仇线)",suggestions:r,quickTags:r});case"textarea":return m.jsx(kt.TextArea,{value:typeof t=="string"?t:"",onChange:s=>o(s.target.value),maxLength:e.maxLength,rows:3});case"checkbox-group":{const s=Array.isArray(t)?t:[];return m.jsx("div",{className:"flex flex-wrap gap-x-4 gap-y-1.5",children:(e.options??[]).map(i=>m.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-sm text-foreground",children:[m.jsx("input",{type:"checkbox",checked:s.includes(i),onChange:()=>o(jHe(s,i)),className:"size-4 accent-primary"}),e.optionsLabels?.[i]??i]},i))})}case"scene-select":{const s=LHe(t),i=s!==""&&!n.some(a=>a.id===s);return m.jsx(xn,{value:s,onChange:a=>o(a),options:[{value:"",label:"(未设置)"},...i?[{value:s,label:`${s}(已删除)`}]:[],...n.map(a=>({value:a.id,label:`${" ".repeat(a.depth)}${a.label}`}))]})}default:return m.jsx(kt,{value:typeof t=="string"?t:"",onChange:s=>o(s.target.value),maxLength:e.maxLength})}}const a$=d.createContext(null);function XHe({children:e}){const[t,n]=d.useState({open:!1,x:0,y:0}),r=d.useCallback((i,a)=>n({open:!0,x:i,y:a}),[]),o=d.useCallback(()=>n(i=>i.open?{...i,open:!1}:i),[]),s=d.useMemo(()=>({state:t,openAt:r,close:o}),[t,r,o]);return d.useEffect(()=>{if(!t.open)return;const i=c=>{c.key==="Escape"&&o()},a=c=>{const u=c.target;u&&u.closest("[data-slot=context-menu-content]")||o()},l=()=>o();return window.addEventListener("keydown",i),window.addEventListener("pointerdown",a,!0),window.addEventListener("scroll",l,!0),window.addEventListener("resize",l),()=>{window.removeEventListener("keydown",i),window.removeEventListener("pointerdown",a,!0),window.removeEventListener("scroll",l,!0),window.removeEventListener("resize",l)}},[t.open,o]),m.jsx(a$.Provider,{value:s,children:e})}function YHe({render:e,children:t}){const n=d.useContext(a$);if(!n)return e;const r=e,o={...r.props,onContextMenu:i=>{i.preventDefault(),n.openAt(i.clientX,i.clientY)}},s=r.props.children;return d.createElement(r.type,o,t===void 0?s:t)}function ZHe({children:e}){return m.jsx(m.Fragment,{children:e})}function QHe({className:e,children:t,...n}){const r=d.useContext(a$);if(!r||!r.state.open)return null;const o=typeof window<"u"?window.innerWidth-192:0,s=typeof window<"u"?window.innerHeight-128:0,i=Math.max(0,Math.min(r.state.x,o)),a=Math.max(0,Math.min(r.state.y,s));return Co.createPortal(m.jsx("div",{"data-slot":"context-menu-content",role:"menu",className:et("fixed z-50 w-auto min-w-40 rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10",e),style:{left:i,top:a},...n,children:t}),document.body)}function JHe({...e}){return m.jsx("div",{"data-slot":"context-menu-group",...e})}function eFe({className:e,inset:t,...n}){return m.jsx("div",{"data-slot":"context-menu-label",className:et("px-1.5 py-1 text-xs font-medium text-muted-foreground",t&&"pl-7",e),...n})}function tE({className:e,inset:t,variant:n="default",onClick:r,...o}){const s=d.useContext(a$);return m.jsx("button",{type:"button",role:"menuitem","data-slot":"context-menu-item",className:et("flex w-full cursor-pointer items-center gap-1.5 rounded-md px-1.5 py-1 text-left text-sm outline-none select-none hover:bg-accent hover:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",t&&"pl-7",n==="destructive"&&"text-destructive hover:bg-destructive/10 hover:text-destructive",e),onClick:i=>{s?.close(),r?.(i)},...o})}function MU({className:e,...t}){return m.jsx("div",{"data-slot":"context-menu-separator",className:et("-mx-1 my-1 h-px bg-border",e),...t})}function ep({focus:e,source:t,onCreated:n,extraItems:r,trigger:o,children:s}){const i=Kt(p=>p.setFocusContext),a=Kt(p=>p.requestFocusInput),[l,c]=d.useState(!1);function u(){i(e),a()}return m.jsxs(XHe,{children:[m.jsx(YHe,{render:o,children:s}),m.jsx(ZHe,{children:m.jsxs(QHe,{className:"w-44",children:[m.jsx(JHe,{children:m.jsx(eFe,{className:"max-w-40 truncate",children:t.name})}),m.jsx(MU,{}),m.jsxs(tE,{onClick:u,children:[m.jsx(Dte,{className:"text-sm"}),"注入会话上下文"]}),m.jsxs(tE,{onClick:()=>c(!0),children:[m.jsx(Lte,{className:"text-sm"}),"建立关联"]}),r!==void 0&&m.jsxs(m.Fragment,{children:[m.jsx(MU,{}),r]})]})}),l&&m.jsx(Mm,{source:t,onCreated:()=>n?.(),onClose:()=>c(!1)})]})}const CP=x_,RU=x_;function IU(e){const t=RU.indexOf(e);return t===-1?RU.length:t}function xoe(e){const t=new Map;for(const n of e){if(!CP.includes(n.relationType)||n.sourceType!=="outline_node"||n.targetType!=="hook")continue;const r={relationType:n.relationType,hookId:n.targetId,hookName:n.targetName??n.targetId},o=t.get(n.sourceId);o===void 0?t.set(n.sourceId,[r]):o.push(r)}for(const n of t.values())n.sort((r,o)=>IU(r.relationType)-IU(o.relationType)||(r.hookName<o.hookName?-1:r.hookName>o.hookName?1:0)||(r.hookId<o.hookId?-1:r.hookId>o.hookId?1:0));return t}function l$(e){const t=document.querySelector(e);return t?(t.scrollIntoView({block:"center"}),t.focus({preventScroll:!0}),!0):!1}function tFe(e,t){let n=!1,r=!1,o=!1,s=!1,i=!1;function a(){i||n||(n=!0,r=!1,e.pushSentinel())}function l(){n&&(n=!1,e.onSentinel()&&(r=!0,e.back()))}return{setDirty(c){if(!c){l();return}a()},handlePopState(){if(!i){if(r){r=!1;return}if(o){s=!0;return}n&&(n=!1,o=!0,t().then(c=>{if(o=!1,i)return;const u=s;if(s=!1,!c){a();return}u||(r=!0,e.back())}))}},reset(){l(),i=!0}}}const nFe={backGuard:!0};function voe(e,t){const n=d.useRef(t);n.current=t;const r=d.useRef(null);d.useEffect(()=>{const o=tFe({pushSentinel:()=>window.history.pushState(nFe,"",window.location.href),onSentinel:()=>window.history.state?.backGuard===!0,back:()=>window.history.back()},()=>n.current());return r.current=o,window.addEventListener("popstate",o.handlePopState),()=>{window.removeEventListener("popstate",o.handlePopState),o.reset(),r.current=null}},[]),d.useEffect(()=>{r.current?.setDirty(e)},[e])}function wP({withMetadata:e}){const t=lt(l=>l.outline),n=lt(l=>l.outlineLoading),r=lt(l=>l.outlineWithMetadata),o=lt(l=>l.loadOutline),[s,i]=d.useState(!1),a=d.useCallback(()=>o({withMetadata:e}),[o,e]);return d.useEffect(()=>{if(!n){if(t===null){if(s)return;i(!0),a();return}r||a()}},[t,n,r,s,a,e]),{reload:a,retry:()=>i(!1)}}function DS(e){return e instanceof Ze?e.code:null}function uh(e){switch(e){case"OUTLINE_NODE_NOT_FOUND":return"节点不存在(可能已被彻底删除),大纲已刷新";case"CLIENT_NETWORK_ERROR":return"无法连接服务,请确认 ai-editor 服务已启动";default:return"操作失败,请稍后重试"}}function AU({value:e,onChange:t,onKeyDown:n,onCancel:r,className:o}){return m.jsxs("div",{className:et("flex items-center gap-2 rounded-md px-2 py-1",o),children:[m.jsx("span",{className:"-ml-2 w-6 shrink-0"}),m.jsx(qr,{className:"min-w-14 shrink-0 justify-center",children:tc.volume}),m.jsx(VC,{value:e,onChange:t,onKeyDown:n,onBlur:r,placeholder:"新卷标题,Enter 创建"})]})}function OU({nodeId:e}){const t=lt(I=>I.outline),n=lt(I=>I.outlineError),r=lt(I=>I.config),o=lt(I=>I.configLoading),{reload:s,retry:i}=wP({withMetadata:!0});Hs(()=>{s()});const[a,l]=d.useState(!1),c=Ig("(min-width: 1024px)"),{layout:u,resizing:p,railRef:h,startResize:b,moveResize:y,endResize:x,toggleCollapse:S,toggleDetail:C}=X9e(c),E=c&&u.collapsed,w=c&&!E&&u.detailCollapsed,$=$e(I=>I.focusOutlineNodeId);d.useEffect(()=>{$===null||t===null||!E||nx(t.children,$)!==null&&S()},[$,t,E,S]);const N=r===null&&!o;d.useEffect(()=>l(!1),[e]);async function M(){return a?$e.getState().confirm({title:"放弃未保存的修改?",description:"当前节点的修改尚未保存,切换后将丢失"}):!0}voe(a,M);function k(){if(u.detailCollapsed){C();return}M().then(I=>{I&&C()})}const R=t!==null&&e!==void 0?vi(t.children,e):null,A=c?m.jsx(kl,{side:"left",collapsed:E,label:"大纲树",onToggle:S}):void 0,O=c?m.jsx(kl,{side:"right",collapsed:u.detailCollapsed,label:"右侧详情",onToggle:k}):void 0,j=m.jsx("div",{className:"space-y-2 rounded-md border border-border p-3",children:Array.from({length:5},(I,P)=>m.jsx("div",{className:et(wr,"h-5"),style:{width:`${92-P*12}%`}},P))});let L;N?L=m.jsxs("section",{className:"flex min-h-0 flex-1 flex-col",children:[m.jsx(wi,{title:"详情",leading:E?A:void 0,actions:E?void 0:O,className:"-mx-6",insetClassName:"px-6"}),m.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto",children:m.jsx(Hn,{padding:"sm",action:m.jsx("a",{href:"#/",className:"text-sm text-muted-foreground underline hover:text-foreground",children:"回到首页打开或创建书籍"}),children:"未打开项目,无法查看大纲详情"})})]}):t===null?L=m.jsxs("section",{className:"flex min-h-0 flex-1 flex-col",children:[m.jsx(wi,{title:"详情",leading:E?A:void 0,actions:E?void 0:O,className:"-mx-6",insetClassName:"px-6"}),m.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto",children:n===null?j:m.jsxs("div",{className:et(Ds,"flex shrink-0 items-center gap-3"),children:[m.jsx("span",{className:"min-w-0 flex-1",children:"大纲加载失败,详情暂不可用"}),m.jsx(de,{size:"small",onClick:i,children:"重试"})]})})]}):e===void 0?L=m.jsxs("section",{className:"flex min-h-0 flex-1 flex-col",children:[m.jsx(wi,{title:"详情",leading:E?A:void 0,actions:E?void 0:O,className:"-mx-6",insetClassName:"px-6"}),m.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto",children:t.children.length===0?m.jsx(Hn,{padding:"sm",children:"还没有大纲,先在左侧新建第一卷"}):m.jsx("p",{className:"text-sm text-muted-foreground",children:E?"从页头左侧展开大纲树,选择卷、章或场查看详情":"从左侧选择一个卷、章或场查看详情"})})]}):R===null?L=m.jsxs("section",{className:"flex min-h-0 flex-1 flex-col",children:[m.jsx(wi,{title:"详情",leading:E?A:void 0,actions:E?void 0:O,className:"-mx-6",insetClassName:"px-6"}),m.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto",children:m.jsx(Hn,{padding:"sm",action:m.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[m.jsx("a",{href:"#/trash",className:"whitespace-nowrap rounded-md border border-border px-4 py-1.5 text-sm text-muted-foreground hover:bg-muted",children:"去回收站"}),m.jsx(de,{href:"#/outline",className:"whitespace-nowrap",children:"返回大纲"})]}),children:"该节点不存在或已被删除"})})]}):L=m.jsx(GHe,{node:R,nodeId:e,onReload:s,leading:E?A:void 0,headerActions:E?void 0:O,onDirtyChange:l,onNavigate:async I=>{await M()&&en(I)}},e);const z=!E&&(c||e===void 0);return m.jsxs("section",{className:et("-m-6 flex h-[calc(100%+3rem)] min-h-0 overflow-hidden",p&&"select-none"),children:[z&&m.jsx(rFe,{railRef:h,nodeId:e,reload:s,retry:i,confirmDiscard:M,width:c&&!w?u.width??q9e:void 0,leading:w?void 0:A,className:c&&!w?void 0:"w-full border-r-0",detailCollapsed:c?u.detailCollapsed:void 0,onToggleDetail:w?k:void 0}),c&&!E&&!w&&m.jsx(tx,{label:"调整大纲树宽度",active:p,onStart:b,onMove:y,onEnd:x}),!w&&(c||e!==void 0)&&m.jsxs("div",{className:et("flex min-h-0 min-w-0 flex-1 flex-col p-6",c&&"pt-0"),children:[!c&&e!==void 0&&m.jsxs("a",{href:"#/outline",onClick:I=>{I.preventDefault(),M().then(P=>{P&&en("/outline")})},className:"flex h-8 shrink-0 items-center gap-2 text-sm text-muted-foreground transition-colors hover:text-foreground",children:[m.jsx(Yx,{className:"text-xs"}),"大纲树"]}),L]})]})}function rFe({railRef:e,nodeId:t,reload:n,retry:r,confirmDiscard:o,width:s,className:i,leading:a,detailCollapsed:l,onToggleDetail:c}){const u=lt(ge=>ge.outline),p=lt(ge=>ge.outlineLoading),h=lt(ge=>ge.config),b=lt(ge=>ge.configLoading),y=d.useRef(t);y.current=t;const x=$e(ge=>ge.focusOutlineNodeId),S=$e(ge=>ge.clearFocusOutlineNode),C=$e(ge=>ge.setCurrentFocus),[E,w]=d.useState(null),[$,N]=d.useState(new Set),[M,k]=d.useState(!1),[R,A]=d.useState(null),[O,j]=d.useState(null),[L,z]=d.useState(""),[I,P]=d.useState(null),[D,U]=d.useState(""),[V,W]=d.useState(null),[q,B]=d.useState(null),[F,G]=d.useState(null),J=h===null&&!b,te=d.useMemo(()=>o$(u).labels,[u]),ne=d.useMemo(()=>{const ge=C_(u,h?.deductionNodes??[]);return{marks:ge,byNode:new Map(ge.map(Ee=>[Ee.nodeId,Ee]))}},[u,h?.deductionNodes]),K=ne.marks.length>0;d.useEffect(()=>{C(K?{focus_deduction:!0}:null)},[K,C]),d.useEffect(()=>{if(u===null){G(null);return}let ge=!1;return Promise.all(CP.map(Ee=>cu({source_type:"outline_node",relation_type:Ee,depth:1}).then(Re=>Re.relations).catch(()=>[]))).then(Ee=>{ge||G(xoe(Ee.flat()))}),()=>{ge=!0}},[u]),d.useEffect(()=>{if(R===null)return;const ge=setTimeout(()=>A(null),3e3);return()=>clearTimeout(ge)},[R]),d.useEffect(()=>{if(x===null||u===null)return;const ge=x,Ee=nx(u.children,ge);if(Ee===null){S();return}N(mt=>{if(Ee.every(wt=>!mt.has(wt)))return mt;const gt=new Set(mt);for(const wt of Ee)gt.delete(wt);return gt});const Re=setTimeout(()=>{window.location.replace(`#/outline/${ge}`),A(ge),S()},0);return()=>clearTimeout(Re)},[x,u,S]),d.useEffect(()=>{if(R===null)return;const ge=R,Ee=setTimeout(()=>l$(`[data-node-id="${ge}"]`),0);return()=>clearTimeout(Ee)},[R]),d.useEffect(()=>{if(t===void 0||u===null)return;const ge=nx(u.children,t);if(ge===null)return;const Ee=ge.slice(0,-1);N(mt=>{const gt=new Set(mt);let wt=!1;for(const Tt of Ee)gt.delete(Tt)&&(wt=!0);return wt?gt:mt});const Re=setTimeout(()=>{document.querySelector(`[data-node-id="${t}"]`)?.scrollIntoView({block:"nearest"})},0);return()=>clearTimeout(Re)},[t,u]);async function ee(ge,Ee){ge&&ae(ge),await n(),Ee&&A(Ee)}function re(ge){N(Ee=>{const Re=new Set(Ee);return Re.has(ge)?Re.delete(ge):Re.add(ge),Re})}function ae(ge){N(Ee=>{if(!Ee.has(ge))return Ee;const Re=new Set(Ee);return Re.delete(ge),Re})}function ue(ge,Ee=[]){for(const Re of ge)Re.type!=="scene"&&Re.children&&Re.children.length>0&&(Ee.push(Re.id),ue(Re.children,Ee));return Ee}function Y(ge,Ee){me(),j({nodeId:ge.id,field:Ee}),z(Ee==="title"?ge.title:ge.summary??"")}function oe(){j(null),z("")}async function Z(ge,Ee){if(!O||O.nodeId!==ge.id||O.field!==Ee||M)return;const Re=L;if(!(Ee==="title"?pP(ge.title,Re):hP(ge.summary,Re))){oe();return}k(!0);try{await LY(ge.id,Ee==="title"?{title:Re.trim()}:{summary:Re.trim()}),oe(),$e.getState().showToast("已保存"),await ee()}catch(gt){const wt=DS(gt);return eHe(wt)==="abandon"?(oe(),w(uh(wt)),await ee(),!1):(w(uh(wt)),!1)}finally{k(!1)}}ni(()=>{if(O===null)return;const ge=vi(u?.children??[],O.nodeId);if(ge)return Z(ge,O.field)},O!==null);function se(ge,Ee){return Re=>{Re.key==="Enter"?(Re.preventDefault(),Z(ge,Ee)):Re.key==="Escape"&&oe()}}function ce(ge,Ee){oe(),P({parentId:ge,type:Ee}),U(""),ge!==Ki&&ae(ge)}function me(){P(null),U("")}async function ye(){if(!I)return;const ge=D.trim(),{parentId:Ee,type:Re}=I;if(!ge){me();return}const mt={creatingAt:I,value:D};if(!await o()){P(mt.creatingAt),U(mt.value);return}me();try{const gt=await ybe({type:Re,title:ge,parent_id:Ee});$e.getState().showToast(`已创建${tc[Re]}《${ge}》`),await ee(Ee,gt.id),en(`/outline/${gt.id}`)}catch(gt){w(uh(DS(gt)))}}function Ce(ge){ge.key==="Enter"?(ge.preventDefault(),ye()):ge.key==="Escape"&&me()}async function be(ge,Ee){if(ge.target.closest("button, input, a")){ge.stopPropagation();return}ge.stopPropagation(),V===null&&t!==Ee.id&&await o()&&(oe(),me(),en(`/outline/${Ee.id}`))}function ke(ge,Ee){if(ge.key!=="Enter"||ge.target!==ge.currentTarget)return;const Re=jV[Ee.type];Re!==null&&(O!==null||I!==null||V!==null||M||t===Ee.id&&(ge.preventDefault(),ce(Ee.id,Re)))}function we(ge,Ee){ge.dataTransfer.setData("text/plain",Ee.id),ge.dataTransfer.effectAllowed="move",W(Ee.id),B(null)}function Ue(){W(null),B(null)}function De(ge){const Ee=ge.currentTarget.getBoundingClientRect();return ge.clientY<Ee.top+Ee.height/2?"before":"after"}function We(ge,Ee){ge.stopPropagation();const Re=u?.children??[],mt=V?vi(Re,V):null;if(!mt)return;const gt=uU(Re,mt.id,Ee,De(ge));gt!==null&&(ge.preventDefault(),ge.dataTransfer.dropEffect="move",B(wt=>cU(wt,gt.target)?wt:gt.target))}function rt(ge,Ee){ge.currentTarget.contains(ge.relatedTarget)||B(Re=>Re!==null&&Re.kind!=="root-end"&&Re.nodeId===Ee?null:Re)}async function ze(ge,Ee){if(ge.stopPropagation(),ge.preventDefault(),!V)return;const Re=u?.children??[],mt=vi(Re,V);if(!mt)return;const gt=uU(Re,mt.id,Ee,De(ge));if(gt===null)return;if(gt.insert.kind!=="end"&>.insert.nodeId===mt.id){W(null),B(null);return}const wt=Yre(Re,gt.parentId)??[],Tt=lU(wt,gt.insert,mt.id);if(dU(Re,mt.id,gt.parentId,Tt)){W(null),B(null);return}k(!0);try{await Kz(mt.id,{parent_id:gt.parentId,order:Tt}),$e.getState().showToast(`已移动《${mt.title}》`),await ee(gt.parentId)}catch(Pt){w(uh(DS(Pt)))}finally{k(!1),W(null),B(null)}}function Ae(ge){const Ee=V?vi(u?.children??[],V):null;!Ee||!Jw(Ee,Ki,u?.children??[])||(ge.preventDefault(),ge.dataTransfer.dropEffect="move",B(Re=>cU(Re,{kind:"root-end"})?Re:{kind:"root-end"}))}function Le(ge){ge.currentTarget.contains(ge.relatedTarget)||B(Ee=>Ee?.kind==="root-end"?null:Ee)}async function Te(ge){if(ge.preventDefault(),!V)return;const Ee=vi(u?.children??[],V);if(!Ee||!Jw(Ee,Ki,u?.children??[]))return;const Re=lU(u?.children??[],{kind:"end"},Ee.id);if(dU(u?.children??[],Ee.id,Ki,Re)){W(null),B(null);return}k(!0);try{await Kz(Ee.id,{parent_id:Ki,order:Re}),$e.getState().showToast(`已移动《${Ee.title}》`),await ee()}catch(mt){w(uh(DS(mt)))}finally{k(!1),W(null),B(null)}}async function Se(ge){h?.currentPosition!==ge.id&&await moe(ge.id)}async function _e(ge){await yoe(hoe(ne.marks,ge.id))}async function dt(ge){const Ee=u?.children??[];try{const Re=await xbe(ge.id),{children:mt,relations:gt,deltas:wt}=Re.cascaded,Tt=[];mt>0&&Tt.push(`${mt} 个子节点`),gt>0&&Tt.push(`${gt} 条关联`),wt>0&&Tt.push(`${wt} 条变化记录`),$e.getState().showToast(`已移入回收站${Tt.length>0?`(含 ${Tt.join("、")})`:""}`),await ee();const Pt=y.current;Pt!==void 0&&J9e(Ee,ge.id,Pt)&&window.location.replace("#/outline")}catch(Re){if(Re instanceof Ze&&Re.code==="OUTLINE_NODE_NOT_FOUND"){w(uh("OUTLINE_NODE_NOT_FOUND")),await ee();return}$e.getState().showToast(Re instanceof Ze?Re.message:"删除失败,请重试","error")}}function ve(){return I?.parentId!==Ki?null:m.jsx(AU,{className:"mb-1",value:D,onChange:U,onKeyDown:Ce,onCancel:me})}function Ge(ge,Ee){return ge.map(Re=>{const mt=Re.type!=="scene"&&(Re.children?.length??0)>0,gt=$.has(Re.id),wt=h?.currentPosition===Re.id,Tt=O?.nodeId===Re.id&&O.field==="title",Pt=O?.nodeId===Re.id&&O.field==="summary",Wt=q?.kind==="before"&&q.nodeId===Re.id,sn=q?.kind==="after"&&q.nodeId===Re.id,tt=q?.kind==="inside"&&q.nodeId===Re.id,it=V===Re.id,qe=I?.parentId===Re.id,He=Re.id===R,ot=t===Re.id,pe=te.get(Re.id),Oe=ne.byNode.get(Re.id),Be=Re.type==="chapter"?xP(Re.data):[],Xe=coe(Be),Et=jV[Re.type],Dt={"data-node-id":Re.id,draggable:!Tt&&!Pt&&!it&&!M,tabIndex:-1,onDragStart:yt=>we(yt,Re),onDragEnd:Ue,onDragOver:yt=>We(yt,Re.id),onDragLeave:yt=>rt(yt,Re.id),onDrop:yt=>{ze(yt,Re.id)},"aria-current":ot?"page":void 0,onClick:yt=>{be(yt,Re)},onKeyDown:yt=>ke(yt,Re),className:et("relative cursor-grab rounded-md px-2 py-1 transition-colors hover:bg-muted/60 active:cursor-grabbing",He&&"bg-primary/10 ring-1 ring-primary/30 ring-inset",it&&"opacity-50",ot&&"bg-accent",tt&&"bg-primary/10 ring-1 ring-primary/30 ring-inset"),style:{paddingLeft:Ee*20+8},title:"拖动到目标行即可移动(上半=插前、下半=插后;目标行可承载时整行=落为子级)"},_t=m.jsxs(m.Fragment,{children:[m.jsxs("div",{className:"flex items-center gap-2",children:[mt?m.jsx(de,{color:"default",variant:"text",size:"small",className:"-ml-2",onClick:yt=>{yt.stopPropagation(),re(Re.id)},"aria-label":gt?"展开":"折叠",icon:m.jsx(Ps,{className:et("text-sm transition-transform",!gt&&"rotate-90")})}):m.jsx("span",{className:"-ml-2 w-6 shrink-0"}),m.jsx(qr,{tone:Re.type==="volume"?"default":"soft",className:et("shrink-0 justify-center tabular-nums",pe!==void 0?"min-w-14":"w-7"),children:pe??tc[Re.type]}),Tt?m.jsx(VC,{value:L,onChange:z,onKeyDown:se(Re,"title"),onBlur:()=>{Z(Re,"title")},placeholder:"标题"}):m.jsx("span",{className:et("min-w-0 cursor-text truncate text-sm hover:underline","text-foreground"),title:"点击编辑标题",onClick:yt=>{yt.stopPropagation(),Y(Re,"title")},children:Re.title}),F!==null&&(F.get(Re.id)?.length??0)>0&&m.jsx("span",{className:"flex shrink-0 items-center gap-0.5",children:(F.get(Re.id)??[]).map(yt=>m.jsx(Gre,{mark:yt},`${yt.relationType}-${yt.hookId}`))}),m.jsxs("span",{className:"ml-auto flex shrink-0 items-center gap-1",children:[Oe!==void 0&&m.jsx(qr,{className:"shrink-0",title:boe(Oe,ne.marks.length),children:m.jsx(VI,{"aria-label":Oe.label})}),wt&&m.jsx(qr,{className:"shrink-0",title:"阅读进度",children:m.jsx(II,{"aria-label":"阅读进度"})}),Et!==null&&m.jsx(de,{color:"default",variant:"text",size:"small",title:`新建${tc[Et]}`,"aria-label":`在《${Re.title}》下新建${tc[Et]}`,onClick:yt=>{yt.stopPropagation(),ce(Re.id,Et)},icon:m.jsx(ca,{className:"text-sm"})}),m.jsx(de,{color:"default",variant:"text",size:"small",title:"移入回收站","aria-label":"移入回收站",onClick:yt=>{yt.stopPropagation(),dt(Re)},icon:m.jsx(ss,{className:"text-sm"})})]})]}),Pt||Re.summary?m.jsxs("div",{className:"mt-0.5 flex items-center gap-2",children:[m.jsx("span",{className:"-ml-2 w-6 shrink-0"}),m.jsx("span",{className:et("shrink-0",pe!==void 0?"min-w-14":"w-7")}),Pt?m.jsx(VC,{value:L,onChange:z,onKeyDown:se(Re,"summary"),onBlur:()=>{Z(Re,"summary")},placeholder:"摘要"}):m.jsx("span",{className:"min-w-0 cursor-text truncate text-xs text-muted-foreground hover:underline",title:"点击编辑摘要",onClick:yt=>{yt.stopPropagation(),Y(Re,"summary")},children:Re.summary})]}):null,Be.length>0&&m.jsxs("div",{className:"mt-0.5 flex min-w-0 items-center gap-2",children:[m.jsx("span",{className:"-ml-2 w-6 shrink-0"}),m.jsx("span",{className:et("shrink-0",pe!==void 0?"min-w-14":"w-7")}),m.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[Xe.visible.map(yt=>m.jsxs("span",{title:yt,className:et("min-w-0 truncate rounded-sm px-1 text-xs text-foreground",dP(yt)),children:["#",yt]},yt)),Xe.overflow>0&&m.jsxs("span",{className:"shrink-0 text-xs text-muted-foreground",title:Be.map(yt=>`#${yt}`).join(" "),children:["+",Xe.overflow]})]})]}),Wt&&m.jsx(uc,{position:"top"}),sn&&m.jsx(uc,{position:"bottom"})]});return m.jsxs("div",{children:[Tt||Pt?m.jsx("div",{...Dt,children:_t}):m.jsx(ep,{focus:{focus_node_id:Re.id},source:{type:"outline_node",id:Re.id,name:Re.title,nodeType:Re.type},onCreated:()=>$e.getState().notifyDataChanged(),extraItems:poe(Re.type)?m.jsxs(m.Fragment,{children:[m.jsxs(tE,{onClick:()=>{_e(Re)},children:[m.jsx(VI,{className:"text-sm"}),goe(Oe!==void 0)]}),m.jsxs(tE,{disabled:wt,onClick:()=>{Se(Re)},children:[m.jsx(II,{className:"text-sm"}),"设为阅读进度"]})]}):void 0,trigger:m.jsx("div",{...Dt}),children:_t}),mt&&!gt&&m.jsx("div",{children:Ge(Re.children??[],Ee+1)}),qe&&m.jsxs("div",{className:"flex items-center gap-2 rounded-md px-2 py-1",style:{paddingLeft:(Ee+1)*20+8},children:[m.jsx("span",{className:"-ml-2 w-6 shrink-0"}),m.jsx(qr,{tone:I.type==="volume"?"default":"soft",className:et("h-5 shrink-0 justify-center",I.type==="scene"?"w-7":"min-w-14"),children:tc[I.type]}),m.jsx(VC,{value:D,onChange:U,onKeyDown:Ce,onBlur:me,placeholder:`新${tc[I.type]}标题,Enter 创建`})]})]},Re.id)})}function Qe(){u&&($.size>0?N(new Set):N(new Set(ue(u.children))))}return m.jsxs("aside",{ref:e,"aria-label":"大纲树",style:s===void 0?void 0:{width:s},className:et("flex min-h-0 shrink-0 flex-col border-r border-border",i),children:[m.jsx(wi,{title:"大纲",leading:a,className:"mb-0",insetClassName:a!==void 0||c!==void 0?"px-6":void 0,actions:m.jsxs(m.Fragment,{children:[ne.marks.length>0&&m.jsx(de,{color:"default",variant:"text",size:"small",title:"清除推演标记","aria-label":"清除推演标记",onClick:()=>{WHe()},icon:m.jsx(Pte,{className:"text-sm"})}),m.jsx(de,{color:"default",variant:"text",size:"small",title:$.size>0?"全部展开":"全部折叠","aria-label":$.size>0?"全部展开":"全部折叠",disabled:!u||u.children.length===0,onClick:Qe,icon:$.size>0?m.jsx(Tte,{className:"text-sm"}):m.jsx($te,{className:"text-sm"})}),m.jsx(de,{color:"default",variant:"text",size:"small",title:"新建卷","aria-label":"新建卷",disabled:J||u===null,onClick:()=>ce(Ki,"volume"),icon:m.jsx(ca,{className:"text-sm"})}),c!==void 0&&m.jsx(kl,{side:"right",collapsed:l??!1,label:"右侧详情",onToggle:c})]})}),m.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-2",onClick:ge=>{ge.target.closest("button, input, a")||V===null&&t!==void 0&&o().then(Ee=>{Ee&&en("/outline")})},children:[E&&m.jsx("div",{className:et(Ds,"mb-2"),children:E}),J?m.jsx(Hn,{padding:"sm",action:m.jsx("a",{href:"#/",className:"text-sm text-muted-foreground underline hover:text-foreground",children:"回到首页打开或创建书籍"}),children:"未打开项目,无法编辑大纲"}):p&&u===null?m.jsx("div",{className:"space-y-2 rounded-md border border-border p-3",children:Array.from({length:6},(ge,Ee)=>m.jsx("div",{className:et(wr,"h-5"),style:{width:`${92-Ee%3*24}%`,marginLeft:Ee%3*20}},Ee))}):u===null?m.jsxs("div",{className:"rounded-md border border-border p-4 text-sm text-muted-foreground",children:["大纲加载失败",m.jsx(de,{className:"ml-3",onClick:r,children:"重试"})]}):u.children.length===0?I?.parentId===Ki?m.jsx(Hn,{action:m.jsx("div",{className:"mx-auto max-w-sm",children:m.jsx(AU,{value:D,onChange:U,onKeyDown:Ce,onCancel:me})}),children:"输入第一卷标题,Enter 创建"}):m.jsxs(Hn,{action:m.jsx(de,{type:"primary",onClick:()=>ce(Ki,"volume"),children:"新建第一卷"}),children:["大纲还是空的,先建第一卷",m.jsx("span",{className:"mt-1 block text-xs text-muted-foreground/70",children:"大纲是三层结构:卷 → 章 → 场景"})]}):m.jsxs("div",{className:et(q?.kind==="root-end"&&"ring-1 ring-primary/30 ring-inset"),onDragOver:Ae,onDragLeave:Le,onDrop:ge=>{Te(ge)},children:[ve(),Ge(u.children,0)]})]})]})}function Vo(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=Vo(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}const Ml={error001:(e="react")=>`Seems like you have not used ${e==="svelte"?"SvelteFlowProvider":"ReactFlowProvider"} as an ancestor. Help: https://${e}flow.dev/error#001`,error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:r}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs.",error016:e=>`Edge with id "${e}" does not exist, it may have been removed. This can happen when an edge is deleted before the "onEdgeClick" handler is called.`},rx=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Soe=["Enter"," ","Escape"],Coe={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};var pg;(function(e){e.Strict="strict",e.Loose="loose"})(pg||(pg={}));var fm;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(fm||(fm={}));var ox;(function(e){e.Partial="partial",e.Full="full"})(ox||(ox={}));const woe={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var fd;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(fd||(fd={}));var sx;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(sx||(sx={}));var tn;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(tn||(tn={}));const _U={[tn.Left]:tn.Right,[tn.Right]:tn.Left,[tn.Top]:tn.Bottom,[tn.Bottom]:tn.Top},Eoe=e=>!!e&&typeof e=="object"&&"id"in e&&"source"in e&&"target"in e,oFe=e=>!!e&&typeof e=="object"&&"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),EP=e=>!!e&&typeof e=="object"&&"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),nv=(e,t=[0,0])=>{const{width:n,height:r}=Dl(e),o=e.origin??t,s=n*o[0],i=r*o[1];return{x:e.position.x-s,y:e.position.y-i}},sFe=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};let n=!1;const r=e.reduce((o,s)=>{const i=typeof s=="string";let a=!t.nodeLookup&&!i?s:void 0;return t.nodeLookup&&(a=i?t.nodeLookup.get(s):EP(s)?s:t.nodeLookup.get(s.id)),a?(n=!0,c$(o,nE(a,t.nodeOrigin))):o},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return n?u$(r):{x:0,y:0,width:0,height:0}},rv=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(o=>{(t.filter===void 0||t.filter(o))&&(n=c$(n,nE(o)),r=!0)}),r?u$(n):{x:0,y:0,width:0,height:0}},$P=(e,t,[n,r,o]=[0,0,1],s=!1,i=!1)=>{const a=(t.x-n)/o,l=(t.y-r)/o,c=t.width/o,u=t.height/o,p=[];for(const h of e.values()){const{measured:b,selectable:y=!0,hidden:x=!1}=h;if(i&&!y||x)continue;const S=b.width??h.width??h.initialWidth??0,C=b.height??h.height??h.initialHeight??0,{x:E,y:w}=h.internals.positionAbsolute,$=koe(a,l,c,u,E,w,S,C),N=S*C,M=s&&$>0;(!h.internals.handleBounds||M||$>=N||h.dragging)&&p.push(h)}return p},iFe=(e,t)=>{const n=new Set;return e.forEach(r=>{n.add(r.id)}),t.filter(r=>n.has(r.source)||n.has(r.target))};function aFe(e,t){const n=new Map,r=t?.nodes?new Set(t.nodes.map(o=>o.id)):null;return e.forEach(o=>{let s;if(t?.includeHiddenNodes){const{width:i,height:a}=Dl(o);s=i>0&&a>0}else s=!!(o.measured.width&&o.measured.height&&!o.hidden);s&&(!r||r.has(o.id))&&n.set(o.id,o)}),n}async function lFe({nodes:e,width:t,height:n,panZoom:r,minZoom:o,maxZoom:s},i){if(e.size===0)return!0;const a=aFe(e,i),l=rv(a),c=NP(l,t,n,i?.minZoom??o,i?.maxZoom??s,i?.padding??.1);return await r.setViewport(c,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),!0}function $oe({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:o,onError:s}){const i=n.get(e),a=i.parentId?n.get(i.parentId):void 0,{x:l,y:c}=a?a.internals.positionAbsolute:{x:0,y:0},u=i.origin??r;let p=i.extent||o;if(i.extent==="parent"&&!i.expandParent)if(!a)s?.("005",Ml.error005());else{const{width:b,height:y}=Dl(a);b&&y&&(p=[[l,c],[l+b,c+y]])}else a&&Im(i.extent)&&(p=[[i.extent[0][0]+l,i.extent[0][1]+c],[i.extent[1][0]+l,i.extent[1][1]+c]]);const h=Im(p)?Rm(t,p,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&s?.("015",Ml.error015()),{position:{x:h.x-l+(i.measured.width??0)*u[0],y:h.y-c+(i.measured.height??0)*u[1]},positionAbsolute:h}}async function cFe({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:o}){const s=new Set(e.map(h=>h.id)),i=[];for(const h of n){if(h.deletable===!1)continue;const b=s.has(h.id),y=!b&&h.parentId&&i.find(x=>x.id===h.parentId);(b||y)&&i.push(h)}const a=new Set(t.map(h=>h.id)),l=r.filter(h=>h.deletable!==!1),u=iFe(i,l);for(const h of l)a.has(h.id)&&!u.find(y=>y.id===h.id)&&u.push(h);if(!o)return{edges:u,nodes:i};const p=await o({nodes:i,edges:u});return typeof p=="boolean"?p?{edges:u,nodes:i}:{edges:[],nodes:[]}:p}const hg=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Rm=(e={x:0,y:0},t,n)=>({x:hg(e.x,t[0][0],t[1][0]-(n?.width??0)),y:hg(e.y,t[0][1],t[1][1]-(n?.height??0))});function Toe(e,t,n){const{width:r,height:o}=Dl(n),{x:s,y:i}=n.internals.positionAbsolute;return Rm(e,[[s,i],[s+r,i+o]],t)}const jU=(e,t,n)=>e<t?hg(Math.abs(e-t),1,t)/t:e>n?-hg(Math.abs(e-n),1,t)/t:0,TP=(e,t,n=15,r=40)=>{const o=jU(e.x,r,t.width-r)*n,s=jU(e.y,r,t.height-r)*n;return[o,s]},c$=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),oO=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),u$=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),ix=(e,t=[0,0])=>{const{x:n,y:r}=EP(e)?e.internals.positionAbsolute:nv(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},nE=(e,t=[0,0])=>{const{x:n,y:r}=EP(e)?e.internals.positionAbsolute:nv(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},Noe=(e,t)=>u$(c$(oO(e),oO(t))),koe=(e,t,n,r,o,s,i,a)=>{const l=Math.max(0,Math.min(e+n,o+i)-Math.max(e,o)),c=Math.max(0,Math.min(t+r,s+a)-Math.max(t,s));return Math.ceil(l*c)},rE=(e,t)=>koe(e.x,e.y,e.width,e.height,t.x,t.y,t.width,t.height),PU=e=>pl(e.width)&&pl(e.height)&&pl(e.x)&&pl(e.y),pl=e=>!isNaN(e)&&isFinite(e),Moe=(e,t)=>(n,r)=>{},ov=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),sv=({x:e,y:t},[n,r,o],s=!1,i=[1,1])=>{const a={x:(e-n)/o,y:(t-r)/o};return s?ov(a,i):a},gg=({x:e,y:t},[n,r,o])=>({x:e*o+n,y:t*o+r});function dh(e,t){if(typeof e=="number")return Math.floor((t-t/(1+e))*.5);if(typeof e=="string"&&e.endsWith("px")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(n)}if(typeof e=="string"&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function uFe(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=dh(e,n),o=dh(e,t);return{top:r,right:o,bottom:r,left:o,x:o*2,y:r*2}}if(typeof e=="object"){const r=dh(e.top??e.y??0,n),o=dh(e.bottom??e.y??0,n),s=dh(e.left??e.x??0,t),i=dh(e.right??e.x??0,t);return{top:r,right:i,bottom:o,left:s,x:s+i,y:r+o}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function dFe(e,t,n,r,o,s){const{x:i,y:a}=gg(e,[t,n,r]),{x:l,y:c}=gg({x:e.x+e.width,y:e.y+e.height},[t,n,r]),u=o-l,p=s-c;return{left:Math.floor(i),top:Math.floor(a),right:Math.floor(u),bottom:Math.floor(p)}}const NP=(e,t,n,r,o,s)=>{const i=uFe(s,t,n),a=(t-i.x)/e.width,l=(n-i.y)/e.height,c=Math.min(a,l),u=hg(c,r,o),p=e.x+e.width/2,h=e.y+e.height/2,b=t/2-p*u,y=n/2-h*u,x=dFe(e,b,y,u,t,n),S={left:Math.min(x.left-i.left,0),top:Math.min(x.top-i.top,0),right:Math.min(x.right-i.right,0),bottom:Math.min(x.bottom-i.bottom,0)};return{x:b-S.left+S.right,y:y-S.top+S.bottom,zoom:u}},ax=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function Im(e){return e!=null&&e!=="parent"}function Dl(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function Roe(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function Ioe(e,t={width:0,height:0},n,r,o){const s={...e},i=r.get(n);if(i){const a=i.origin||o;s.x+=i.internals.positionAbsolute.x-(t.width??0)*a[0],s.y+=i.internals.positionAbsolute.y-(t.height??0)*a[1]}return s}function DU(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function fFe(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}function mFe(e){return{...Coe,...e||{}}}function Aoe(e){return e===null?null:e?"valid":"invalid"}function Cy(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:o}){const{x:s,y:i}=hl(e),a=sv({x:s-(o?.left??0),y:i-(o?.top??0)},r),{x:l,y:c}=n?ov(a,t):a;return{xSnapped:l,ySnapped:c,...a}}const kP=e=>({width:e.offsetWidth,height:e.offsetHeight}),Ooe=e=>e?.getRootNode?.()||window?.document,pFe=["INPUT","SELECT","TEXTAREA"];function _oe(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:pFe.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const joe=e=>"clientX"in e,hl=(e,t)=>{const n=joe(e),r=n?e.clientX:e.touches?.[0].clientX,o=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:o-(t?.top??0)}},LU=(e,t,n,r,o)=>{const s=t.querySelectorAll(`.${e}`);return!s||!s.length?null:Array.from(s).map(i=>{const a=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:o,position:i.getAttribute("data-handlepos"),x:(a.left-n.left)/r,y:(a.top-n.top)/r,...kP(i)}})};function Poe({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:o,sourceControlY:s,targetControlX:i,targetControlY:a}){const l=e*.125+o*.375+i*.375+n*.125,c=t*.125+s*.375+a*.375+r*.125,u=Math.abs(l-e),p=Math.abs(c-t);return[l,c,u,p]}function LS(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function zU({pos:e,x1:t,y1:n,x2:r,y2:o,c:s}){switch(e){case tn.Left:return[t-LS(t-r,s),n];case tn.Right:return[t+LS(r-t,s),n];case tn.Top:return[t,n-LS(n-o,s)];case tn.Bottom:return[t,n+LS(o-n,s)]}}function Doe({sourceX:e,sourceY:t,sourcePosition:n=tn.Bottom,targetX:r,targetY:o,targetPosition:s=tn.Top,curvature:i=.25}){const[a,l]=zU({pos:n,x1:e,y1:t,x2:r,y2:o,c:i}),[c,u]=zU({pos:s,x1:r,y1:o,x2:e,y2:t,c:i}),[p,h,b,y]=Poe({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:a,sourceControlY:l,targetControlX:c,targetControlY:u});return[`M${e},${t} C${a},${l} ${c},${u} ${r},${o}`,p,h,b,y]}function Loe({sourceX:e,sourceY:t,targetX:n,targetY:r}){const o=Math.abs(n-e)/2,s=n<e?n+o:n-o,i=Math.abs(r-t)/2,a=r<t?r+i:r-i;return[s,a,o,i]}function hFe({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:o=!1,zIndexMode:s="basic"}){if(s==="manual")return r;const i=o&&n?r+1e3:r,a=Math.max(e.parentId||o&&e.selected?e.internals.z:0,t.parentId||o&&t.selected?t.internals.z:0);return i+a}function gFe({sourceNode:e,targetNode:t,width:n,height:r,transform:o}){const s=c$(nE(e),nE(t));s.x===s.x2&&(s.x2+=1),s.y===s.y2&&(s.y2+=1);const i={x:-o[0]/o[2],y:-o[1]/o[2],width:n/o[2],height:r/o[2]};return rE(i,u$(s))>0}const bFe=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,yFe=(e,t)=>t.some(n=>n.source===e.source&&n.target===e.target&&(n.sourceHandle===e.sourceHandle||!n.sourceHandle&&!e.sourceHandle)&&(n.targetHandle===e.targetHandle||!n.targetHandle&&!e.targetHandle)),xFe=(e,t,n={})=>{if(!e.source||!e.target)return n.onError?.("006",Ml.error006()),t;const r=n.getEdgeId||bFe;let o;return Eoe(e)?o={...e}:o={...e,id:r(e)},yFe(o,t)?t:(o.sourceHandle===null&&delete o.sourceHandle,o.targetHandle===null&&delete o.targetHandle,t.concat(o))};function zoe({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[o,s,i,a]=Loe({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,o,s,i,a]}const BU={[tn.Left]:{x:-1,y:0},[tn.Right]:{x:1,y:0},[tn.Top]:{x:0,y:-1},[tn.Bottom]:{x:0,y:1}},vFe=({source:e,sourcePosition:t=tn.Bottom,target:n})=>t===tn.Left||t===tn.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},HU=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2)),SFe=(e,t,n)=>e.x===t.x&&t.x===n.x&&(t.y-e.y)*(n.y-t.y)>=0||e.y===t.y&&t.y===n.y&&(t.x-e.x)*(n.x-t.x)>=0;function CFe({source:e,sourcePosition:t=tn.Bottom,target:n,targetPosition:r=tn.Top,center:o,offset:s,stepPosition:i}){const a=BU[t],l=BU[r],c={x:e.x+a.x*s,y:e.y+a.y*s},u={x:n.x+l.x*s,y:n.y+l.y*s},p=vFe({source:c,sourcePosition:t,target:u}),h=p.x!==0?"x":"y",b=p[h];let y=[],x,S;const C={x:0,y:0},E={x:0,y:0},[,,w,$]=Loe({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(a[h]*l[h]===-1){h==="x"?(x=o.x??c.x+(u.x-c.x)*i,S=o.y??(c.y+u.y)/2):(x=o.x??(c.x+u.x)/2,S=o.y??c.y+(u.y-c.y)*i);const R=[{x,y:c.y},{x,y:u.y}],A=[{x:c.x,y:S},{x:u.x,y:S}];a[h]===b?y=h==="x"?R:A:y=h==="x"?A:R}else{const R=[{x:c.x,y:u.y}],A=[{x:u.x,y:c.y}];if(h==="x"?y=a.x===b?A:R:y=a.y===b?R:A,t===r){const I=Math.abs(e[h]-n[h]);if(I<=s){const P=Math.min(s-1,s-I);a[h]===b?C[h]=(c[h]>e[h]?-1:1)*P:E[h]=(u[h]>n[h]?-1:1)*P}}if(t!==r){const I=h==="x"?"y":"x",P=a[h]===l[I],D=c[I]>u[I],U=c[I]<u[I];(a[h]===1&&(!P&&D||P&&U)||a[h]!==1&&(!P&&U||P&&D))&&(y=h==="x"?R:A)}const O={x:c.x+C.x,y:c.y+C.y},j={x:u.x+E.x,y:u.y+E.y},L=Math.max(Math.abs(O.x-y[0].x),Math.abs(j.x-y[0].x)),z=Math.max(Math.abs(O.y-y[0].y),Math.abs(j.y-y[0].y));L>=z?(x=(O.x+j.x)/2,S=y[0].y):(x=y[0].x,S=(O.y+j.y)/2)}const N={x:c.x+C.x,y:c.y+C.y},M={x:u.x+E.x,y:u.y+E.y},k=[];for(const R of[e,N,...y,M,n]){const[A,O]=k.slice(-2);O&&SFe(A,O,R)&&k.pop(),k.push(R)}return[k,x,S,w,$]}function wFe(e,t,n,r){const o=Math.min(HU(e,t)/2,HU(t,n)/2,r),{x:s,y:i}=t;if(e.x===s&&s===n.x||e.y===i&&i===n.y)return`L${s} ${i}`;if(e.y===i){const c=e.x<n.x?-1:1,u=e.y<n.y?1:-1;return`L ${s+o*c},${i}Q ${s},${i} ${s},${i+o*u}`}const a=e.x<n.x?1:-1,l=e.y<n.y?-1:1;return`L ${s},${i+o*l}Q ${s},${i} ${s+o*a},${i}`}function sO({sourceX:e,sourceY:t,sourcePosition:n=tn.Bottom,targetX:r,targetY:o,targetPosition:s=tn.Top,borderRadius:i=5,centerX:a,centerY:l,offset:c=20,stepPosition:u=.5}){const[p,h,b,y,x]=CFe({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:o},targetPosition:s,center:{x:a,y:l},offset:c,stepPosition:u});let S=`M${p[0].x} ${p[0].y}`;for(let C=1;C<p.length-1;C++)S+=wFe(p[C-1],p[C],p[C+1],i);return S+=`L${p[p.length-1].x} ${p[p.length-1].y}`,[S,h,b,y,x]}function FU(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function EFe(e){const{sourceNode:t,targetNode:n}=e;if(!FU(t)||!FU(n))return null;const r=t.internals.handleBounds||VU(t.handles),o=n.internals.handleBounds||VU(n.handles),s=UU(r?.source??[],e.sourceHandle),i=UU(e.connectionMode===pg.Strict?o?.target??[]:(o?.target??[]).concat(o?.source??[]),e.targetHandle);if(!s||!i)return e.onError?.("008",Ml.error008(s?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const a=s?.position||tn.Bottom,l=i?.position||tn.Top,c=Am(t,s,a),u=Am(n,i,l);return{sourceX:c.x,sourceY:c.y,targetX:u.x,targetY:u.y,sourcePosition:a,targetPosition:l}}function VU(e){if(!e)return null;const t=[],n=[];for(const r of e)r.width=r.width??1,r.height=r.height??1,r.type==="source"?t.push(r):r.type==="target"&&n.push(r);return{source:t,target:n}}function Am(e,t,n=tn.Left,r=!1){const o=(t?.x??0)+e.internals.positionAbsolute.x,s=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:a}=t??Dl(e);if(r)return{x:o+i/2,y:s+a/2};switch(t?.position??n){case tn.Top:return{x:o+i/2,y:s};case tn.Right:return{x:o+i,y:s+a/2};case tn.Bottom:return{x:o+i/2,y:s+a};case tn.Left:return{x:o,y:s+a/2}}}function UU(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function iO(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function $Fe(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:o}){const s=new Set;return e.reduce((i,a)=>([a.markerStart||r,a.markerEnd||o].forEach(l=>{if(l&&typeof l=="object"){const c=iO(l,t);s.has(c)||(i.push({id:c,color:l.color||n,...l}),s.add(c))}}),i),[]).sort((i,a)=>i.id.localeCompare(a.id))}const Boe=1e3,TFe=10,MP={nodeOrigin:[0,0],nodeExtent:rx,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},NFe={...MP,checkEquality:!0};function RP(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function kFe(e,t,n){const r=RP(MP,n);for(const o of e.values())if(o.parentId)AP(o,e,t,r);else{const s=nv(o,r.nodeOrigin),i=Im(o.extent)?o.extent:r.nodeExtent,a=Rm(s,i,Dl(o));o.internals.positionAbsolute=a}}function MFe(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const o of e.handles){const s={id:o.id,width:o.width??1,height:o.height??1,nodeId:e.id,x:o.x,y:o.y,position:o.position,type:o.type};o.type==="source"?n.push(s):o.type==="target"&&r.push(s)}return{source:n,target:r}}function IP(e){return e==="manual"}function aO(e,t,n,r={}){const o=RP(NFe,r),s={i:0},i=new Map(t),a=o?.elevateNodesOnSelect&&!IP(o.zIndexMode)?Boe:0;let l=e.length>0,c=!1;t.clear(),n.clear();for(const u of e){let p=i.get(u.id);if(o.checkEquality&&u===p?.internals.userNode)t.set(u.id,p);else{const h=nv(u,o.nodeOrigin),b=Im(u.extent)?u.extent:o.nodeExtent,y=Rm(h,b,Dl(u));p={...o.defaults,...u,measured:{width:u.measured?.width,height:u.measured?.height},internals:{positionAbsolute:y,handleBounds:MFe(u,p),z:Hoe(u,a,o.zIndexMode),userNode:u}},t.set(u.id,p)}(p.measured===void 0||p.measured.width===void 0||p.measured.height===void 0)&&!p.hidden&&(l=!1),u.parentId&&AP(p,t,n,r,s),c||=u.selected??!1}return{nodesInitialized:l,hasSelectedNodes:c}}function RFe(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function AP(e,t,n,r,o){const{elevateNodesOnSelect:s,nodeOrigin:i,nodeExtent:a,zIndexMode:l}=RP(MP,r),c=e.parentId,u=t.get(c);if(!u){console.warn(`Parent node ${c} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}RFe(e,n),o&&!u.parentId&&u.internals.rootParentIndex===void 0&&l==="auto"&&(u.internals.rootParentIndex=++o.i,u.internals.z=u.internals.z+o.i*TFe),o&&u.internals.rootParentIndex!==void 0&&(o.i=u.internals.rootParentIndex);const p=s&&!IP(l)?Boe:0,{x:h,y:b,z:y}=IFe(e,u,i,a,p,l),{positionAbsolute:x}=e.internals,S=h!==x.x||b!==x.y;(S||y!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:S?{x:h,y:b}:x,z:y}})}function Hoe(e,t,n){const r=pl(e.zIndex)?e.zIndex:0;return IP(n)?r:r+(e.selected?t:0)}function IFe(e,t,n,r,o,s){const{x:i,y:a}=t.internals.positionAbsolute,l=Dl(e),c=nv(e,n),u=Im(e.extent)?Rm(c,e.extent,l):c;let p=Rm({x:i+u.x,y:a+u.y},r,l);e.extent==="parent"&&(p=Toe(p,l,t));const h=Hoe(e,o,s),b=t.internals.z??0;return{x:p.x,y:p.y,z:b>=h?b+1:h}}function OP(e,t,n,r=[0,0]){const o=[],s=new Map;for(const i of e){const a=t.get(i.parentId);if(!a)continue;const l=s.get(i.parentId)?.expandedRect??ix(a),c=Noe(l,i.rect);s.set(i.parentId,{expandedRect:c,parent:a})}return s.size>0&&s.forEach(({expandedRect:i,parent:a},l)=>{const c=a.internals.positionAbsolute,u=Dl(a),p=a.origin??r,h=i.x<c.x?Math.round(Math.abs(c.x-i.x)):0,b=i.y<c.y?Math.round(Math.abs(c.y-i.y)):0,y=Math.max(u.width,Math.round(i.width)),x=Math.max(u.height,Math.round(i.height)),S=(y-u.width)*p[0],C=(x-u.height)*p[1];(h>0||b>0||S||C)&&(o.push({id:l,type:"position",position:{x:a.position.x-h+S,y:a.position.y-b+C}}),n.get(l)?.forEach(E=>{e.some(w=>w.id===E.id)||o.push({id:E.id,type:"position",position:{x:E.position.x+h,y:E.position.y+b}})})),(u.width<i.width||u.height<i.height||h||b)&&o.push({id:l,type:"dimensions",setAttributes:!0,dimensions:{width:y+(h?p[0]*h-S:0),height:x+(b?p[1]*b-C:0)}})}),o}function AFe(e,t,n,r,o,s,i){const a=r?.querySelector(".xyflow__viewport");let l=!1;if(!a)return{changes:[],updatedInternals:l};const c=[],u=window.getComputedStyle(a),{m22:p}=new window.DOMMatrixReadOnly(u.transform),h=[];for(const b of e.values()){const y=t.get(b.id);if(!y)continue;if(y.hidden){t.set(y.id,{...y,internals:{...y.internals,handleBounds:void 0}}),l=!0;continue}const x=kP(b.nodeElement),S=y.measured.width!==x.width||y.measured.height!==x.height;if(!!(x.width&&x.height&&(S||!y.internals.handleBounds||b.force))){const E=b.nodeElement.getBoundingClientRect(),w=Im(y.extent)?y.extent:s;let{positionAbsolute:$}=y.internals;if(y.parentId&&y.extent==="parent"){const M=t.get(y.parentId);M&&($=Toe($,x,M))}else w&&($=Rm($,w,x));const N={...y,measured:x,internals:{...y.internals,positionAbsolute:$,handleBounds:{source:LU("source",b.nodeElement,E,p,y.id),target:LU("target",b.nodeElement,E,p,y.id)}}};t.set(y.id,N),y.parentId&&AP(N,t,n,{nodeOrigin:o,zIndexMode:i}),l=!0,S&&(c.push({id:y.id,type:"dimensions",dimensions:x}),y.expandParent&&y.parentId&&h.push({id:y.id,parentId:y.parentId,rect:ix(N,o)}))}}if(h.length>0){const b=OP(h,t,n,o);c.push(...b)}return{changes:c,updatedInternals:l}}async function OFe({delta:e,panZoom:t,transform:n,translateExtent:r,width:o,height:s}){if(!t||!e.x&&!e.y)return!1;const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[o,s]],r);return!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2])}function WU(e,t,n,r,o,s){let i=o;const a=r.get(i)||new Map;r.set(i,a.set(n,t)),i=`${o}-${e}`;const l=r.get(i)||new Map;if(r.set(i,l.set(n,t)),s){i=`${o}-${e}-${s}`;const c=r.get(i)||new Map;r.set(i,c.set(n,t))}}function Foe(e,t,n){e.clear(),t.clear();for(const r of n){const{source:o,target:s,sourceHandle:i=null,targetHandle:a=null}=r,l={edgeId:r.id,source:o,target:s,sourceHandle:i,targetHandle:a},c=`${o}-${i}--${s}-${a}`,u=`${s}-${a}--${o}-${i}`;WU("source",l,u,e,o,i),WU("target",l,c,e,s,a),t.set(r.id,r)}}function Voe(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:Voe(n,t):!1}function qU(e,t,n){let r=e;do{if(r?.matches?.(t))return!0;if(r===n)return!1;r=r?.parentElement}while(r);return!1}function _Fe(e,t,n,r,o){const s=new Map;for(const[i,a]of e)if((o?a.id===r:a.selected||a.id===r)&&(o||!a.parentId||!Voe(a,e))&&(a.draggable||t&&typeof a.draggable>"u")){const c=e.get(i);c&&s.set(i,{id:i,position:c.position||{x:0,y:0},distance:{x:n.x-c.internals.positionAbsolute.x,y:n.y-c.internals.positionAbsolute.y},extent:c.extent,parentId:c.parentId,origin:c.origin,expandParent:c.expandParent,internals:{positionAbsolute:c.internals.positionAbsolute||{x:0,y:0}},measured:{width:c.measured.width??0,height:c.measured.height??0}})}return s}function XM({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const o=[];for(const[i,a]of t){const l=n.get(i)?.internals.userNode;l&&o.push({...l,position:a.position,dragging:r})}if(!e)return[o[0],o];const s=n.get(e)?.internals.userNode;return[s?{...s,position:t.get(e)?.position||s.position,dragging:r}:o[0],o]}function jFe({dragItems:e,snapGrid:t,x:n,y:r}){const o=e.values().next().value;if(!o)return null;const s={x:n-o.distance.x,y:r-o.distance.y},i=ov(s,t);return{x:i.x-s.x,y:i.y-s.y}}function PFe({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:o}){let s={x:null,y:null},i=0,a=new Map,l=!1,c={x:0,y:0},u=null,p=!1,h=null,b=!1,y=!1,x=null;function S({noDragClassName:E,handleSelector:w,domNode:$,isSelectable:N,nodeId:M,nodeClickDistance:k=0}){h=Ji($);function R({x:L,y:z}){const{nodeLookup:I,nodeExtent:P,snapGrid:D,snapToGrid:U,nodeOrigin:V,onNodeDrag:W,onSelectionDrag:q,onError:B,updateNodePositions:F}=t();s={x:L,y:z};let G=!1;const J=a.size>1,te=J&&P?oO(rv(a)):null,ne=J&&U?jFe({dragItems:a,snapGrid:D,x:L,y:z}):null;for(const[K,ee]of a){if(!I.has(K))continue;let re={x:L-ee.distance.x,y:z-ee.distance.y};U&&(re=ne?{x:Math.round(re.x+ne.x),y:Math.round(re.y+ne.y)}:ov(re,D));let ae=null;if(J&&P&&!ee.extent&&te){const{positionAbsolute:oe}=ee.internals,Z=oe.x-te.x+P[0][0],se=oe.x+ee.measured.width-te.x2+P[1][0],ce=oe.y-te.y+P[0][1],me=oe.y+ee.measured.height-te.y2+P[1][1];ae=[[Z,ce],[se,me]]}const{position:ue,positionAbsolute:Y}=$oe({nodeId:K,nextPosition:re,nodeLookup:I,nodeExtent:ae||P,nodeOrigin:V,onError:B});G=G||ee.position.x!==ue.x||ee.position.y!==ue.y,ee.position=ue,ee.internals.positionAbsolute=Y}if(y=y||G,!!G&&(F(a,!0),x&&(r||W||!M&&q))){const[K,ee]=XM({nodeId:M,dragItems:a,nodeLookup:I});r?.(x,a,K,ee),W?.(x,K,ee),M||q?.(x,ee)}}async function A(){if(!u)return;const{transform:L,panBy:z,autoPanSpeed:I,autoPanOnNodeDrag:P}=t();if(!P){l=!1,cancelAnimationFrame(i);return}const[D,U]=TP(c,u,I);(D!==0||U!==0)&&(s.x=(s.x??0)-D/L[2],s.y=(s.y??0)-U/L[2],await z({x:D,y:U})&&R(s)),i=requestAnimationFrame(A)}function O(L){const{nodeLookup:z,multiSelectionActive:I,nodesDraggable:P,transform:D,snapGrid:U,snapToGrid:V,selectNodesOnDrag:W,onNodeDragStart:q,onSelectionDragStart:B,unselectNodesAndEdges:F}=t();p=!0;const G=!!M&&!I&&!z.get(M)?.selected;(!W||!N)&&!I&&M&&(z.get(M)?.selected||F()),N&&W&&M&&e?.(M);const J=Cy(L.sourceEvent,{transform:D,snapGrid:U,snapToGrid:V,containerBounds:u});if(s=J,a=_Fe(z,P,J,M,G),a.size>0&&(n||q||!M&&B)){const[te,ne]=XM({nodeId:M,dragItems:a,nodeLookup:z});n?.(L.sourceEvent,a,te,ne),q?.(L.sourceEvent,te,ne),M||B?.(L.sourceEvent,ne)}}const j=hne().clickDistance(k).on("start",L=>{const{domNode:z,nodeDragThreshold:I,transform:P,snapGrid:D,snapToGrid:U}=t();u=z?.getBoundingClientRect()||null,b=!1,y=!1,x=L.sourceEvent,I===0&&O(L),s=Cy(L.sourceEvent,{transform:P,snapGrid:D,snapToGrid:U,containerBounds:u}),c=hl(L.sourceEvent,u)}).on("drag",L=>{const{autoPanOnNodeDrag:z,transform:I,snapGrid:P,snapToGrid:D,nodeDragThreshold:U,nodeLookup:V}=t(),W=Cy(L.sourceEvent,{transform:I,snapGrid:P,snapToGrid:D,containerBounds:u});if(x=L.sourceEvent,(L.sourceEvent.type==="touchmove"&&L.sourceEvent.touches.length>1||M&&!V.has(M))&&(b=!0),!b){if(!l&&z&&p&&(l=!0,A()),!p){const q=hl(L.sourceEvent,u),B=q.x-c.x,F=q.y-c.y;Math.sqrt(B*B+F*F)>U&&O(L)}(s.x!==W.xSnapped||s.y!==W.ySnapped)&&a&&p&&(c=hl(L.sourceEvent,u),R(W))}}).on("end",L=>{if(!p||b){b&&a.size>0&&t().updateNodePositions(a,!1);return}if(l=!1,p=!1,cancelAnimationFrame(i),a.size>0){const{nodeLookup:z,updateNodePositions:I,onNodeDragStop:P,onSelectionDragStop:D}=t();if(y&&(I(a,!1),y=!1),o||P||!M&&D){const[U,V]=XM({nodeId:M,dragItems:a,nodeLookup:z,dragging:!1});o?.(L.sourceEvent,a,U,V),P?.(L.sourceEvent,U,V),M||D?.(L.sourceEvent,V)}}}).filter(L=>{const z=L.target;return!L.button&&(!E||!qU(z,`.${E}`,$))&&(!w||qU(z,w,$))});h.call(j)}function C(){h?.on(".drag",null)}return{update:S,destroy:C}}function DFe(e,t,n){const r=[],o={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const s of t.values())rE(o,ix(s))>0&&r.push(s);return r}const LFe=250;function zFe(e,t,n,r){let o=[],s=1/0;const i=DFe(e,n,t+LFe);for(const a of i){const l=[...a.internals.handleBounds?.source??[],...a.internals.handleBounds?.target??[]];for(const c of l){if(r.nodeId===c.nodeId&&r.type===c.type&&r.id===c.id)continue;const{x:u,y:p}=Am(a,c,c.position,!0),h=Math.sqrt(Math.pow(u-e.x,2)+Math.pow(p-e.y,2));h>t||(h<s?(o=[{...c,x:u,y:p}],s=h):h===s&&o.push({...c,x:u,y:p}))}}if(!o.length)return null;if(o.length>1){const a=r.type==="source"?"target":"source";return o.find(l=>l.type===a)??o[0]}return o[0]}function Uoe(e,t,n,r,o,s=!1){const i=r.get(e);if(!i)return null;const a=o==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],l=(n?a?.find(c=>c.id===n):a?.[0])??null;return l&&s?{...l,...Am(i,l,l.position,!0)}:l}function Woe(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function BFe(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const qoe=()=>!0;function HFe(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:o,edgeUpdaterType:s,isTarget:i,domNode:a,nodeLookup:l,lib:c,autoPanOnConnect:u,flowId:p,panBy:h,cancelConnection:b,onConnectStart:y,onConnect:x,onConnectEnd:S,isValidConnection:C=qoe,onReconnectEnd:E,updateConnection:w,getTransform:$,getFromHandle:N,autoPanSpeed:M,dragThreshold:k=1,handleDomNode:R}){const A=Ooe(e.target);let O=0,j;const{x:L,y:z}=hl(e),I=Woe(s,R),P=a?.getBoundingClientRect();let D=!1;if(!P||!I)return;const U=Uoe(o,I,r,l,t);if(!U)return;let V=hl(e,P),W=!1,q=null,B=!1,F=null;function G(){if(!u||!P)return;const[ue,Y]=TP(V,P,M);h({x:ue,y:Y}),O=requestAnimationFrame(G)}const J={...U,nodeId:o,type:I,position:U.position},te=l.get(o);let K={inProgress:!0,isValid:null,from:Am(te,J,tn.Left,!0),fromHandle:J,fromPosition:J.position,fromNode:te,to:V,toHandle:null,toPosition:_U[J.position],toNode:null,pointer:V};function ee(){D=!0,w(K),y?.(e,{nodeId:o,handleId:r,handleType:I})}k===0&&ee();function re(ue){if(!D){const{x:me,y:ye}=hl(ue),Ce=me-L,be=ye-z;if(!(Ce*Ce+be*be>k*k))return;ee()}if(!N()||!J){ae(ue);return}const Y=$();V=hl(ue,P),j=zFe(sv(V,Y,!1,[1,1]),n,l,J),W||(G(),W=!0);const oe=Goe(ue,{handle:j,connectionMode:t,fromNodeId:o,fromHandleId:r,fromType:i?"target":"source",isValidConnection:C,doc:A,lib:c,flowId:p,nodeLookup:l});F=oe.handleDomNode,q=oe.connection,B=BFe(!!j,oe.isValid);const Z=l.get(o),se=Z?Am(Z,J,tn.Left,!0):K.from,ce={...K,from:se,isValid:B,to:oe.toHandle&&B?gg({x:oe.toHandle.x,y:oe.toHandle.y},Y):V,toHandle:oe.toHandle,toPosition:B&&oe.toHandle?oe.toHandle.position:_U[J.position],toNode:oe.toHandle?l.get(oe.toHandle.nodeId):null,pointer:V};w(ce),K=ce}function ae(ue){if(!("touches"in ue&&ue.touches.length>0)){if(D){(j||F)&&q&&B&&x?.(q);const{inProgress:Y,...oe}=K,Z={...oe,toPosition:K.toHandle?K.toPosition:null};S?.(ue,Z),s&&E?.(ue,Z)}b(),cancelAnimationFrame(O),W=!1,B=!1,q=null,F=null,A.removeEventListener("mousemove",re),A.removeEventListener("mouseup",ae),A.removeEventListener("touchmove",re),A.removeEventListener("touchend",ae)}}A.addEventListener("mousemove",re),A.addEventListener("mouseup",ae),A.addEventListener("touchmove",re),A.addEventListener("touchend",ae)}function Goe(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:o,fromType:s,doc:i,lib:a,flowId:l,isValidConnection:c=qoe,nodeLookup:u}){const p=s==="target",h=t?i.querySelector(`.${a}-flow__handle[data-id="${l}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:b,y}=hl(e),x=i.elementFromPoint(b,y),S=x?.classList.contains(`${a}-flow__handle`)?x:h,C={handleDomNode:S,isValid:!1,connection:null,toHandle:null};if(S){const E=Woe(void 0,S),w=S.getAttribute("data-nodeid"),$=S.getAttribute("data-handleid"),N=S.classList.contains("connectable"),M=S.classList.contains("connectableend");if(!w||!E)return C;const k={source:p?w:r,sourceHandle:p?$:o,target:p?r:w,targetHandle:p?o:$};C.connection=k;const A=N&&M&&(n===pg.Strict?p&&E==="source"||!p&&E==="target":w!==r||$!==o);C.isValid=A&&c(k),C.toHandle=Uoe(w,E,$,u,n,!0)}return C}const lO={onPointerDown:HFe,isValid:Goe};function FFe({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const o=Ji(e);function s({translateExtent:a,width:l,height:c,zoomStep:u=1,pannable:p=!0,zoomable:h=!0,inversePan:b=!1}){const y=w=>{if(w.sourceEvent.type!=="wheel"||!t)return;const $=n(),N=w.sourceEvent.ctrlKey&&ax()?10:1,M=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*u,k=$[2]*Math.pow(2,M*N);t.scaleTo(k)};let x=[0,0];const S=w=>{(w.sourceEvent.type==="mousedown"||w.sourceEvent.type==="touchstart")&&(x=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY])},C=w=>{const $=n();if(w.sourceEvent.type!=="mousemove"&&w.sourceEvent.type!=="touchmove"||!t)return;const N=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY],M=[N[0]-x[0],N[1]-x[1]];x=N;const k=r()*Math.max($[2],Math.log($[2]))*(b?-1:1),R={x:$[0]-M[0]*k,y:$[1]-M[1]*k},A=[[0,0],[l,c]];t.setViewportConstrained({x:R.x,y:R.y,zoom:$[2]},A,a)},E=Rne().on("start",S).on("zoom",p?C:null).on("zoom.wheel",h?y:null);o.call(E,{})}function i(){o.on("zoom",null)}return{update:s,destroy:i,pointer:al}}const d$=e=>({x:e.x,y:e.y,zoom:e.k}),YM=({x:e,y:t,zoom:n})=>X2.translate(e,t).scale(n),id=(e,t)=>e.target.closest(`.${t}`),Koe=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),VFe=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,ZM=(e,t=0,n=VFe,r=()=>{})=>{const o=typeof t=="number"&&t>0;return o||r(),o?e.transition().duration(t).ease(n).on("end",r):e},Xoe=e=>{const t=e.ctrlKey&&ax()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function UFe({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:o,panOnScrollSpeed:s,zoomOnPinch:i,onPanZoomStart:a,onPanZoom:l,onPanZoomEnd:c}){return u=>{if(id(u,t))return u.ctrlKey&&u.preventDefault(),!1;u.preventDefault(),u.stopImmediatePropagation();const p=n.property("__zoom").k||1;if(u.ctrlKey&&i){const S=al(u),C=Xoe(u),E=p*Math.pow(2,C);r.scaleTo(n,E,S,u);return}const h=u.deltaMode===1?20:1;let b=o===fm.Vertical?0:u.deltaX*h,y=o===fm.Horizontal?0:u.deltaY*h;!ax()&&u.shiftKey&&o!==fm.Vertical&&(b=u.deltaY*h,y=0),r.translateBy(n,-(b/p)*s,-(y/p)*s,{internal:!0});const x=d$(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?l?.(u,x):(e.isPanScrolling=!0,a?.(u,x)),e.panScrollTimeout=setTimeout(()=>{c?.(u,x),e.isPanScrolling=!1},150)}}function WFe({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,o){const s=r.type==="wheel",i=!t&&s&&!r.ctrlKey,a=id(r,e);if(r.ctrlKey&&s&&a&&r.preventDefault(),i||a)return null;r.preventDefault(),n.call(this,r,o)}}function qFe({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const o=d$(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=o,r.sourceEvent?.type==="mousedown"&&t(!0),n&&n?.(r.sourceEvent,o)}}function GFe({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:o}){return s=>{e.usedRightMouseButton=!!(n&&Koe(t,e.mouseButton??0)),s.sourceEvent?.sync||r([s.transform.x,s.transform.y,s.transform.k]),o&&!s.sourceEvent?.internal&&o?.(s.sourceEvent,d$(s.transform))}}function KFe({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:o,onPaneContextMenu:s}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,s&&Koe(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&s(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),o)){const a=d$(i.transform);e.prevViewport=a,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{o?.(i.sourceEvent,a)},n?150:0)}}}function XFe({panActivationKeyPressed:e,zoomActivationKeyPressed:t,zoomOnScroll:n,zoomOnPinch:r,panOnDrag:o,panOnScroll:s,zoomOnDoubleClick:i,userSelectionActive:a,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:p}){return h=>{const b=t||n,y=r&&h.ctrlKey,x=h.type==="wheel";if(h.button===1&&h.type==="mousedown"&&(id(h,`${u}-flow__node`)||id(h,`${u}-flow__edge`)||id(h,`${u}-flow__selection`)||id(h,`${u}-flow__nodesselection`)))return!0;if(!o&&!b&&!s&&!i&&!r||a||p&&!x||id(h,l)&&x||id(h,c)&&(!x||s&&x&&!t)||!r&&h.ctrlKey&&x)return!1;if(!r&&h.type==="touchstart"&&h.touches?.length>1)return h.preventDefault(),!1;if(!b&&!s&&!y&&x||!o&&(h.type==="mousedown"||h.type==="touchstart")||Array.isArray(o)&&!o.includes(h.button)&&h.type==="mousedown")return!1;const S=Array.isArray(o)&&o.includes(h.button)||!h.button||h.button<=1;return(!h.ctrlKey||x||e)&&S}}function YFe({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:o,onPanZoom:s,onPanZoomStart:i,onPanZoomEnd:a,onDraggingChange:l}){const c={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},u=e.getBoundingClientRect();let p=[[0,0],[u.width,u.height]];const h=typeof ResizeObserver<"u"?new ResizeObserver(z=>{const I=z[0];I?.contentRect&&(p=[[0,0],[I.contentRect.width,I.contentRect.height]])}):null;h?.observe(e);const b=Rne().extent(()=>p).scaleExtent([t,n]).translateExtent(r),y=Ji(e).call(b);$({x:o.x,y:o.y,zoom:hg(o.zoom,t,n)},[[0,0],[u.width,u.height]],r);const x=y.on("wheel.zoom"),S=y.on("dblclick.zoom");b.wheelDelta(Xoe);async function C(z,I){return y?new Promise(P=>{b?.interpolate(I?.interpolate==="linear"?vy:zC).transform(ZM(y,I?.duration,I?.ease,()=>P(!0)),z)}):!1}function E({noWheelClassName:z,noPanClassName:I,onPaneContextMenu:P,userSelectionActive:D,panOnScroll:U,panOnDrag:V,panOnScrollMode:W,panOnScrollSpeed:q,preventScrolling:B,zoomOnPinch:F,zoomOnScroll:G,zoomOnDoubleClick:J,panActivationKeyPressed:te=!1,zoomActivationKeyPressed:ne,lib:K,onTransformChange:ee,connectionInProgress:re,paneClickDistance:ae,selectionOnDrag:ue}){D&&!c.isZoomingOrPanning&&b.on("zoom",null);const Y=U&&!ne&&!D;b.clickDistance(ue?1/0:!pl(ae)||ae<0?0:ae);const oe=Y?UFe({zoomPanValues:c,noWheelClassName:z,d3Selection:y,d3Zoom:b,panOnScrollMode:W,panOnScrollSpeed:q,zoomOnPinch:F,onPanZoomStart:i,onPanZoom:s,onPanZoomEnd:a}):WFe({noWheelClassName:z,preventScrolling:B,d3ZoomHandler:x});y.on("wheel.zoom",oe,{passive:!1});const Z=qFe({zoomPanValues:c,onDraggingChange:l,onPanZoomStart:i});b.on("start",Z);const se=GFe({zoomPanValues:c,panOnDrag:V,onPaneContextMenu:!!P,onPanZoom:s,onTransformChange:ee});b.on("zoom",se);const ce=KFe({zoomPanValues:c,panOnDrag:V,panOnScroll:U,onPaneContextMenu:P,onPanZoomEnd:a,onDraggingChange:l});b.on("end",ce);const me=XFe({panActivationKeyPressed:te,zoomActivationKeyPressed:ne,panOnDrag:V,zoomOnScroll:G,panOnScroll:U,zoomOnDoubleClick:J,zoomOnPinch:F,userSelectionActive:D,noPanClassName:I,noWheelClassName:z,lib:K,connectionInProgress:re});b.filter(me),J?y.on("dblclick.zoom",S):y.on("dblclick.zoom",null)}function w(){b.on("zoom",null),h?.disconnect()}async function $(z,I,P){const D=YM(z),U=b?.constrain()(D,I,P);return U&&await C(U),U}async function N(z,I){const P=YM(z);return await C(P,I),P}function M(z){if(y){const I=YM(z),P=y.property("__zoom");(P.k!==z.zoom||P.x!==z.x||P.y!==z.y)&&b?.transform(y,I,null,{sync:!0})}}function k(){const z=y?Mne(y.node()):{x:0,y:0,k:1};return{x:z.x,y:z.y,zoom:z.k}}async function R(z,I){return y?new Promise(P=>{b?.interpolate(I?.interpolate==="linear"?vy:zC).scaleTo(ZM(y,I?.duration,I?.ease,()=>P(!0)),z)}):!1}async function A(z,I){return y?new Promise(P=>{b?.interpolate(I?.interpolate==="linear"?vy:zC).scaleBy(ZM(y,I?.duration,I?.ease,()=>P(!0)),z)}):!1}function O(z){b?.scaleExtent(z)}function j(z){b?.translateExtent(z)}function L(z){const I=!pl(z)||z<0?0:z;b?.clickDistance(I)}return{update:E,destroy:w,setViewport:N,setViewportConstrained:$,getViewport:k,scaleTo:R,scaleBy:A,setScaleExtent:O,setTranslateExtent:j,syncViewport:M,setClickDistance:L}}var bg;(function(e){e.Line="line",e.Handle="handle"})(bg||(bg={}));function ZFe({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:o,affectsY:s}){const i=e-t,a=n-r,l=[i>0?1:i<0?-1:0,a>0?1:a<0?-1:0];return i&&o&&(l[0]=l[0]*-1),a&&s&&(l[1]=l[1]*-1),l}function GU(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),o=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:o}}function Yu(e,t){return Math.max(0,t-e)}function Zu(e,t){return Math.max(0,e-t)}function zS(e,t,n){return Math.max(0,t-e,e-n)}function KU(e,t){return e?!t:t}function QFe(e,t,n,r,o,s,i,a){let{affectsX:l,affectsY:c}=t;const{isHorizontal:u,isVertical:p}=t,h=u&&p,{xSnapped:b,ySnapped:y}=n,{minWidth:x,maxWidth:S,minHeight:C,maxHeight:E}=r,{x:w,y:$,width:N,height:M,aspectRatio:k}=e;let R=Math.floor(u?b-e.pointerX:0),A=Math.floor(p?y-e.pointerY:0);const O=N+(l?-R:R),j=M+(c?-A:A),L=-s[0]*N,z=-s[1]*M;let I=zS(O,x,S),P=zS(j,C,E);if(i){let V=0,W=0;l&&R<0?V=Yu(w+R+L,i[0][0]):!l&&R>0&&(V=Zu(w+O+L,i[1][0])),c&&A<0?W=Yu($+A+z,i[0][1]):!c&&A>0&&(W=Zu($+j+z,i[1][1])),I=Math.max(I,V),P=Math.max(P,W)}if(a){let V=0,W=0;l&&R>0?V=Zu(w+R,a[0][0]):!l&&R<0&&(V=Yu(w+O,a[1][0])),c&&A>0?W=Zu($+A,a[0][1]):!c&&A<0&&(W=Yu($+j,a[1][1])),I=Math.max(I,V),P=Math.max(P,W)}if(o){if(u){const V=zS(O/k,C,E)*k;if(I=Math.max(I,V),i){let W=0;!l&&!c||l&&!c&&h?W=Zu($+z+O/k,i[1][1])*k:W=Yu($+z+(l?R:-R)/k,i[0][1])*k,I=Math.max(I,W)}if(a){let W=0;!l&&!c||l&&!c&&h?W=Yu($+O/k,a[1][1])*k:W=Zu($+(l?R:-R)/k,a[0][1])*k,I=Math.max(I,W)}}if(p){const V=zS(j*k,x,S)/k;if(P=Math.max(P,V),i){let W=0;!l&&!c||c&&!l&&h?W=Zu(w+j*k+L,i[1][0])/k:W=Yu(w+(c?A:-A)*k+L,i[0][0])/k,P=Math.max(P,W)}if(a){let W=0;!l&&!c||c&&!l&&h?W=Yu(w+j*k,a[1][0])/k:W=Zu(w+(c?A:-A)*k,a[0][0])/k,P=Math.max(P,W)}}}A=A+(A<0?P:-P),R=R+(R<0?I:-I),o&&(h?O>j*k?A=(KU(l,c)?-R:R)/k:R=(KU(l,c)?-A:A)*k:u?(A=R/k,c=l):(R=A*k,l=c));const D=l?w+R:w,U=c?$+A:$;return{width:N+(l?-R:R),height:M+(c?-A:A),x:s[0]*R*(l?-1:1)+D,y:s[1]*A*(c?-1:1)+U}}const Yoe={width:0,height:0,x:0,y:0},JFe={...Yoe,pointerX:0,pointerY:0,aspectRatio:1};function eVe(e,t,n){const r=t.position.x+e.position.x,o=t.position.y+e.position.y,s=e.measured.width??0,i=e.measured.height??0,a=n[0]*s,l=n[1]*i;return[[r-a,o-l],[r+s-a,o+i-l]]}function tVe({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:o}){const s=Ji(e);let i={controlDirection:GU("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function a({controlPosition:c,boundaries:u,keepAspectRatio:p,resizeDirection:h,onResizeStart:b,onResize:y,onResizeEnd:x,shouldResize:S}){let C={...Yoe},E={...JFe};i={boundaries:u,resizeDirection:h,keepAspectRatio:p,controlDirection:GU(c)};let w,$=null,N=[],M,k,R;const A=hne().on("start",O=>{const{nodeLookup:j,transform:L,snapGrid:z,snapToGrid:I,nodeOrigin:P,paneDomNode:D}=n();if(w=j.get(t),!w)return;$=D?.getBoundingClientRect()??null;const{xSnapped:U,ySnapped:V}=Cy(O.sourceEvent,{transform:L,snapGrid:z,snapToGrid:I,containerBounds:$});C={width:w.measured.width??0,height:w.measured.height??0,x:w.position.x??0,y:w.position.y??0},E={...C,pointerX:U,pointerY:V,aspectRatio:C.width/C.height},M=void 0,k=Im(w.extent)?w.extent:void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(M=j.get(w.parentId)),M&&w.extent==="parent"&&(k=[[0,0],[M.measured.width,M.measured.height]]),N=[],R=void 0;for(const[W,q]of j)if(q.parentId===t&&(N.push({id:W,position:{...q.position},extent:q.extent}),q.extent==="parent"||q.expandParent)){const B=eVe(q,w,q.origin??P);R?R=[[Math.min(B[0][0],R[0][0]),Math.min(B[0][1],R[0][1])],[Math.max(B[1][0],R[1][0]),Math.max(B[1][1],R[1][1])]]:R=B}b?.(O,{...C})}).on("drag",O=>{const{transform:j,snapGrid:L,snapToGrid:z,nodeOrigin:I}=n(),P=Cy(O.sourceEvent,{transform:j,snapGrid:L,snapToGrid:z,containerBounds:$}),D=[];if(!w)return;const{x:U,y:V,width:W,height:q}=C,B={},F=w.origin??I,{width:G,height:J,x:te,y:ne}=QFe(E,i.controlDirection,P,i.boundaries,i.keepAspectRatio,F,k,R),K=G!==W,ee=J!==q,re=te!==U&&K,ae=ne!==V&ⅇif(!re&&!ae&&!K&&!ee)return;const ue={prevValues:{...C},startX:E.x,startY:E.y,childNodes:N.map(se=>({...se,position:{...se.position}}))};if((re||ae||F[0]===1||F[1]===1)&&(B.x=re?te:C.x,B.y=ae?ne:C.y,C.x=B.x,C.y=B.y,N.length>0)){const se=te-U,ce=ne-V;for(const me of N)me.position={x:me.position.x-se+F[0]*(G-W),y:me.position.y-ce+F[1]*(J-q)},D.push(me)}if((K||ee)&&(B.width=K&&(!i.resizeDirection||i.resizeDirection==="horizontal")?G:C.width,B.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?J:C.height,C.width=B.width,C.height=B.height),M&&w.expandParent){const se=F[0]*(B.width??0);B.x&&B.x<se&&(C.x=se,E.x=E.x-(B.x-se));const ce=F[1]*(B.height??0);B.y&&B.y<ce&&(C.y=ce,E.y=E.y-(B.y-ce))}const Y=ZFe({width:C.width,prevWidth:W,height:C.height,prevHeight:q,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),oe={...C,direction:Y};if(S?.(O,oe)===!1){C=ue.prevValues,E.x=ue.startX,E.y=ue.startY,N.forEach((se,ce)=>{se.position=ue.childNodes[ce].position});return}y?.(O,oe),r(B,D)}).on("end",O=>{x?.(O,{...C}),o?.({...C})});s.call(A)}function l(){s.on(".drag",null)}return{update:a,destroy:l}}var QM={exports:{}},JM={},eR={exports:{}},tR={};var XU;function nVe(){if(XU)return tR;XU=1;var e=pc();function t(p,h){return p===h&&(p!==0||1/p===1/h)||p!==p&&h!==h}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,s=e.useLayoutEffect,i=e.useDebugValue;function a(p,h){var b=h(),y=r({inst:{value:b,getSnapshot:h}}),x=y[0].inst,S=y[1];return s(function(){x.value=b,x.getSnapshot=h,l(x)&&S({inst:x})},[p,b,h]),o(function(){return l(x)&&S({inst:x}),p(function(){l(x)&&S({inst:x})})},[p]),i(b),b}function l(p){var h=p.getSnapshot;p=p.value;try{var b=h();return!n(p,b)}catch{return!0}}function c(p,h){return h()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?c:a;return tR.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:u,tR}var YU;function Zoe(){return YU||(YU=1,eR.exports=nVe()),eR.exports}var ZU;function rVe(){if(ZU)return JM;ZU=1;var e=pc(),t=Zoe();function n(c,u){return c===u&&(c!==0||1/c===1/u)||c!==c&&u!==u}var r=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,s=e.useRef,i=e.useEffect,a=e.useMemo,l=e.useDebugValue;return JM.useSyncExternalStoreWithSelector=function(c,u,p,h,b){var y=s(null);if(y.current===null){var x={hasValue:!1,value:null};y.current=x}else x=y.current;y=a(function(){function C(M){if(!E){if(E=!0,w=M,M=h(M),b!==void 0&&x.hasValue){var k=x.value;if(b(k,M))return $=k}return $=M}if(k=$,r(w,M))return k;var R=h(M);return b!==void 0&&b(k,R)?(w=M,k):(w=M,$=R)}var E=!1,w,$,N=p===void 0?null:p;return[function(){return C(u())},N===null?void 0:function(){return C(N())}]},[u,p,h,b]);var S=o(c,y[0],y[1]);return i(function(){x.hasValue=!0,x.value=S},[S]),l(S),S},JM}var QU;function oVe(){return QU||(QU=1,QM.exports=rVe()),QM.exports}var _P=oVe();const sVe=Ri(_P),iVe={},JU=e=>{let t;const n=new Set,r=(u,p)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const b=t;t=p??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(y=>y(t,b))}},o=()=>t,l={setState:r,getState:o,getInitialState:()=>c,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(iVe?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},c=t=e(r,o,l);return l},aVe=e=>e?JU(e):JU,{useDebugValue:lVe}=X,{useSyncExternalStoreWithSelector:cVe}=sVe,uVe=e=>e;function Qoe(e,t=uVe,n){const r=cVe(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return lVe(r),r}const eW=(e,t)=>{const n=aVe(e),r=(o,s=t)=>Qoe(n,o,s);return Object.assign(r,n),r},dVe=(e,t)=>e?eW(e,t):eW;function uo(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}const f$=d.createContext(null),fVe=f$.Provider,Joe=Ml.error001("react");function Jn(e,t){const n=d.useContext(f$);if(n===null)throw new Error(Joe);return Qoe(n,e,t)}function Gr(){const e=d.useContext(f$);if(e===null)throw new Error(Joe);return d.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const tW={display:"none"},mVe={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},ese="react-flow__node-desc",tse="react-flow__edge-desc",pVe="react-flow__aria-live",hVe=e=>e.ariaLiveMessage,gVe=e=>e.ariaLabelConfig;function bVe({rfId:e}){const t=Jn(hVe);return m.jsx("div",{id:`${pVe}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:mVe,children:t})}function yVe({rfId:e,disableKeyboardA11y:t}){const n=Jn(gVe);return m.jsxs(m.Fragment,{children:[m.jsx("div",{id:`${ese}-${e}`,style:tW,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),m.jsx("div",{id:`${tse}-${e}`,style:tW,children:n["edge.a11yDescription.default"]}),!t&&m.jsx(bVe,{rfId:e})]})}const iv=d.forwardRef(({position:e="top-left",children:t,className:n,style:r,...o},s)=>{const i=`${e}`.split("-");return m.jsx("div",{className:Vo(["react-flow__panel",n,...i]),style:r,ref:s,...o,children:t})});iv.displayName="Panel";const nW="https://reactflow.dev?utm_source=attribution";function xVe({proOptions:e,position:t="bottom-right"}){return d.useEffect(()=>{},[]),e?.hideAttribution?null:m.jsx(iv,{position:t,className:"react-flow__attribution","data-message":`Please only hide this attribution when you are subscribed to React Flow Pro: ${nW}`,children:m.jsx("a",{href:nW,target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const vVe=e=>{const t=[],n=[];for(const[,r]of e.nodeLookup)r.selected&&t.push(r.internals.userNode);for(const[,r]of e.edgeLookup)r.selected&&n.push(r);return{selectedNodes:t,selectedEdges:n}},BS=e=>e.id;function SVe(e,t){return uo(e.selectedNodes.map(BS),t.selectedNodes.map(BS))&&uo(e.selectedEdges.map(BS),t.selectedEdges.map(BS))}function CVe({onSelectionChange:e}){const t=Gr(),{selectedNodes:n,selectedEdges:r}=Jn(vVe,SVe);return d.useEffect(()=>{const o={nodes:n,edges:r};e?.(o),t.getState().onSelectionChangeHandlers.forEach(s=>s(o))},[n,r,e]),null}const wVe=e=>!!e.onSelectionChangeHandlers;function EVe({onSelectionChange:e}){const t=Jn(wVe);return e||t?m.jsx(CVe,{onSelectionChange:e}):null}const nse=[0,0],$Ve={x:0,y:0,zoom:1},TVe=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","autoPanOnNodeFocus","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","connectionDragThreshold","onBeforeDelete","debug","autoPanSpeed","ariaLabelConfig","zIndexMode"],rW=[...TVe,"rfId"],NVe=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),oW={translateExtent:rx,nodeOrigin:nse,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function kVe(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:o,setTranslateExtent:s,setNodeExtent:i,reset:a,setDefaultNodesAndEdges:l}=Jn(NVe,uo),c=Gr();d.useEffect(()=>(l(e.defaultNodes,e.defaultEdges),()=>{u.current=oW,a()}),[]);const u=d.useRef(oW);return d.useEffect(()=>{for(const p of rW){const h=e[p],b=u.current[p];h!==b&&(typeof e[p]>"u"||(p==="nodes"?t(h):p==="edges"?n(h):p==="minZoom"?r(h):p==="maxZoom"?o(h):p==="translateExtent"?s(h):p==="nodeExtent"?i(h):p==="ariaLabelConfig"?c.setState({ariaLabelConfig:mFe(h)}):p==="fitView"?c.setState({fitViewQueued:h}):p==="fitViewOptions"?c.setState({fitViewOptions:h}):c.setState({[p]:h})))}u.current=e},rW.map(p=>e[p])),null}function sW(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function MVe(e){const[t,n]=d.useState(e==="system"?null:e);return d.useEffect(()=>{if(e!=="system"){n(e);return}const r=sW(),o=()=>n(r?.matches?"dark":"light");return o(),r?.addEventListener("change",o),()=>{r?.removeEventListener("change",o)}},[e]),t!==null?t:sW()?.matches?"dark":"light"}const iW=typeof document<"u"?document:null;function lx(e=null,t={target:iW,actInsideInputWithModifier:!0}){const[n,r]=d.useState(!1),o=d.useRef(!1),s=d.useRef(new Set([])),[i,a]=d.useMemo(()=>{if(e!==null){const c=(Array.isArray(e)?e:[e]).filter(p=>typeof p=="string").map(p=>p.replace(/\+/g,`
|
|
495
495
|
`).replace(`
|
|
496
496
|
|
package/client-dist/index.html
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
// localStorage 不可用(隐私模式等)时静默跳过,默认浅色
|
|
15
15
|
}
|
|
16
16
|
</script>
|
|
17
|
-
<script type="module" crossorigin src="/assets/index-
|
|
17
|
+
<script type="module" crossorigin src="/assets/index-CGTD_qnU.js"></script>
|
|
18
18
|
<link rel="stylesheet" crossorigin href="/assets/index-Ct99SGum.css">
|
|
19
19
|
</head>
|
|
20
20
|
<body>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@whispering233/ai-editor-server",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.68",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Hono API 服务端(单进程:API + SPA 静态托管)",
|
|
6
6
|
"type": "module",
|
|
@@ -34,10 +34,10 @@
|
|
|
34
34
|
"@earendil-works/pi-ai": "1.4.0",
|
|
35
35
|
"@earendil-works/pi-coding-agent": "1.4.0",
|
|
36
36
|
"@hono/node-server": "^2.0.12",
|
|
37
|
-
"@whispering233/ai-editor-agent": "0.0.
|
|
38
|
-
"@whispering233/ai-editor-db": "0.0.
|
|
39
|
-
"@whispering233/ai-editor-shared": "0.0.
|
|
40
|
-
"@whispering233/ai-editor-tools": "0.0.
|
|
37
|
+
"@whispering233/ai-editor-agent": "0.0.68",
|
|
38
|
+
"@whispering233/ai-editor-db": "0.0.68",
|
|
39
|
+
"@whispering233/ai-editor-shared": "0.0.68",
|
|
40
|
+
"@whispering233/ai-editor-tools": "0.0.68",
|
|
41
41
|
"fflate": "^0.8.3",
|
|
42
42
|
"hono": "^4.7.0",
|
|
43
43
|
"undici": "8.5.0",
|