import{React as ye,reactExports as i,jsxRuntimeExports as k,createRoot as Ze}from"./chunks/vendor-react.js";import{XProvider as et,localeValues as tt,XMarkdown as nt,Mermaid as rt}from"./chunks/spec-template-vendor.js";import{antdTheme as Pe,Modal as ot,ConfigProvider as at,Tabs as st,Anchor as ct}from"./chunks/vendor-antd.js";import{createGenieEditor as it}from"./chunks/vendor-genie.js";import{SimpleEditor as lt}from"./chunks/vendor-editor.js";import"./chunks/_commonjsHelpers.js";import"./chunks/vendor-common.js";import"./chunks/preload-helper.js";import"./chunks/_commonjs-dynamic-modules.js";const me="#008F5D",dt="#E08200",ut="#D92D20",pt="0 4px 14px rgba(0, 143, 93, 0.2)",ve="#FFFFFF",mt=t=>({algorithm:t?Pe.darkAlgorithm:Pe.defaultAlgorithm,token:{colorPrimary:me,colorInfo:me,colorSuccess:me,colorWarning:dt,colorError:ut,fontSize:14,borderRadius:10},components:{Menu:{itemSelectedColor:ve},Select:{optionSelectedColor:ve},Form:{labelFontSize:14},Button:{primaryShadow:pt,contentFontSizeSM:12}}}),ft=mt(!1);function q(t){try{return decodeURIComponent(t)}catch{return t}}function V(t){const e=String(t||"").trim();return e?e.toLowerCase().endsWith(".md")?e:`${e}.md`:""}function ht(t){if(!t)return"";try{return new URL(t,"http://localhost").pathname}catch{return""}}function yt(t){if(!t)return"";const e=Array.isArray(t.selectors)?t.selectors.map(r=>String(r||"").trim()).filter(Boolean):[];return e.length>0?e.join(" | "):Array.isArray(t.path)&&t.path.length>0?t.path.join(">"):""}function wt(t){const e=String(t.savedContent??""),r=String(t.currentContent??""),c=String(t.nextContent??"");return!t.userChanged&&e===r&&c!==r}function Le(t){const e={resourceKind:"unknown",entryType:"unknown",entryName:"",docType:"unknown",docPath:"",prototypePath:""},r=ht(t);if(!r)return e;try{const c=new URL(t||"","http://localhost");if(c.pathname==="/api/markdown-file"||c.pathname==="/markdown-file/spec.html"){const y=V(q(c.searchParams.get(c.pathname==="/api/markdown-file"?"path":"file")||""));return y?{resourceKind:"doc",entryType:"unknown",entryName:"",docType:"doc",docPath:y,prototypePath:""}:e}}catch{}if(r.startsWith("/api/docs/templates/")){const c=V(q(r.slice(20)));return c?{resourceKind:"template",entryType:"unknown",entryName:"",docType:"template",docPath:`src/resources/templates/${c}`,prototypePath:""}:e}if(r.startsWith("/api/docs/")){const c=V(q(r.slice(10)));return c?{resourceKind:"doc",entryType:"unknown",entryName:"",docType:"doc",docPath:`src/resources/${c}`,prototypePath:""}:e}if(r.startsWith("/docs/templates/")){const c=V(q(r.slice(16)));return c?{resourceKind:"template",entryType:"unknown",entryName:"",docType:"template",docPath:`src/resources/templates/${c}`,prototypePath:""}:e}if(r.startsWith("/docs/")){const c=V(q(r.slice(6)));return c?{resourceKind:"doc",entryType:"unknown",entryName:"",docType:"doc",docPath:`src/resources/${c}`,prototypePath:""}:e}return e}function gt(t){const{docLabel:e,docUrl:r,modifiedElements:c,promptTemplate:y}=t,h=Le(r),m=h.docPath||r||"(unknown)",f=h.docPath||"";if(y)try{return{prompt:y({meta:h,docLabel:e,docPath:m,modifiedElements:c}),targetPath:f,meta:h}}catch(d){console.warn("[quickEdit] Custom promptTemplate failed, falling back to default:",d)}const p=[];return p.push("请根据以下 Markdown 文档预览上的批注，完成对应文档更新。"),p.push(""),p.push(`文档名称: ${e||"文档"}`),p.push(`文档路径: ${m}`),h.prototypePath&&p.push(`对应原型入口: ${h.prototypePath}`),p.push(""),p.push("执行要求："),p.push(`1. 所有批注都要优先落到文档文件 ${m}。`),p.push("2. 仅修改这个 Markdown 文档本身，不要额外同步更新页面、组件、原型或其他文件。"),p.push("3. 输出修改文件清单、关键改动摘要，以及需要我验证的点。"),p.push(""),p.push("批注列表："),c.forEach((d,E)=>{p.push(`- 批注项 ${E+1}`),p.push(`  - 批注目标: ${d.label||"未命名元素"}`);const w=yt(d.locator);w&&p.push(`  - 预览定位: ${w}`),d.note&&p.push(`  - 批注说明: ${d.note}`),d.imageCount>0&&p.push(`  - 附带图片: ${d.imageCount} 张`),d.changeKinds.length>0&&p.push(`  - 涉及改动类型: ${d.changeKinds.join(", ")}`)}),{prompt:p.join(`
`),targetPath:f,meta:h}}const se="specEdit",kt="axhub-spec-draft:",Et=650;function bt(){var t;if(typeof window>"u")return"";try{return((t=new URL(window.location.href).searchParams.get("axhubDisplayName"))==null?void 0:t.trim())??""}catch{return""}}function St(t,e){const r=bt()||String(e||"").trim()||String(t.entryName||"").trim();return r?t.docType==="spec"||t.docType==="prd"?`${r} ${t.docType}`:r:""}function Re(){return typeof window>"u"?"http://localhost:32123/api":`${window.location.protocol}//${window.location.hostname}:32123/api`}function Me(t){const e=String(t||"").trim().replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+/g,"/");if(!e)return"/api/docs";if(e==="templates"||e.startsWith("templates/")){const r=e==="templates"?"":e.slice(10);return r?`/api/docs/templates/${encodeURIComponent(r)}`:"/api/docs/templates"}return`/api/docs/${encodeURIComponent(e)}`}function De(t){const e=String(t||"").trim();return e?e.toLowerCase().endsWith(".md")?e:`${e}.md`:""}function Tt(t){const e=String(t||""),r=e.indexOf("#"),c=r===-1?e:e.slice(0,r),y=r===-1?"":e.slice(r+1),h=c.indexOf("?");if(h===-1)return{cleanSrc:e,width:null};const m=c.slice(0,h),f=c.slice(h+1),p=new URLSearchParams(f),d=p.get("axw"),E=d?Number.parseInt(d,10):NaN,w=Number.isFinite(E)&&E>0?E:null;p.delete("axw");const P=p.toString(),b=P?`${m}?${P}`:m;return{cleanSrc:y?`${b}#${y}`:b,width:w}}function Ct(t,e){const r=String(t||"").trim();if(!r||/^(?:[a-z]+:)?\/\//i.test(r)||r.startsWith("data:")||r.startsWith("blob:")||r.startsWith("/")||r.startsWith("#")||typeof window>"u")return r;try{const m=new URL(e||"",window.location.origin);if(m.pathname==="/api/markdown-file"){const f=String(m.searchParams.get("path")||"").trim();if(f)return`/api/markdown-file-asset?path=${encodeURIComponent(f)}&asset=${encodeURIComponent(r)}`}}catch{}const h=(m=>{if(!m)return null;let f="";try{f=new URL(m,window.location.origin).pathname}catch{return null}const p=w=>{const P=decodeURIComponent(w).replace(/\.md$/i,""),b=P.lastIndexOf("/");return`/docs/${b>=0?P.slice(0,b+1):""}`};if(f.startsWith("/api/docs/"))return p(f.slice(10));if(f.startsWith("/docs/"))return p(f.slice(6));const d=f.match(/^\/(components|prototypes|themes)\/([^/]+)\/(spec|prd)\.md$/i);if(d)return`/${d[1]}/${d[2]}/`;const E=f.match(/^\/api\/git\/version-file\/[^/]+\/(components|prototypes|themes)\/([^/]+)\/(spec|prd)\.md$/i);return E?`/${E[1]}/${E[2]}/`:null})(e)||window.location.pathname;try{return new URL(r,new URL(h,window.location.origin)).toString()}catch{return r}}const xt=t=>{const{domNode:e,streamStatus:r,children:c,class:y,classname:h,src:m,style:f,documentUrl:p,...d}=t||{},E=typeof m=="string"?m:"",{cleanSrc:w,width:P}=Tt(E),b=Ct(w||E,p);return k.jsx("img",{...d,src:b,style:{...f||{},...P?{width:`${P}px`}:{},maxWidth:"100%",height:"auto"}})},Pt=`
  body {
    background: #f5f5f5;
  }
  .markdown-container {
    display: flex;
    gap: 40px;
    max-width: 1200px;
    margin: 0 auto;
    padding: 40px 24px;
    position: relative;
    align-items: flex-start;
  }
  .markdown-content {
    flex: 1;
    min-width: 0;
  }
  .markdown-content > div {
    background: #fff;
    padding: 24px;
    border-radius: 8px;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03), 0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px 0 rgba(0, 0, 0, 0.02);
  }
  .anchor-sidebar {
    width: 240px;
    flex-shrink: 0;
    position: sticky;
    top: 40px;
  }
  @media (max-width: 1200px) {
    .anchor-sidebar {
      display: none;
    }
  }
  .ant-anchor-link-title {
    font-size: 12px;
  }
  .markdown-tabs-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 24px 24px 0;
  }
  .markdown-tabs-container .ant-tabs-nav {
    margin-bottom: 0;
  }
  .spec-editor-shell {
    min-height: calc(100vh - 170px);
  }
  .spec-editor-shell .simple-editor-wrapper {
    width: 100%;
    min-height: calc(100vh - 230px);
    height: auto;
  }
  .spec-editor-shell .simple-editor-content {
    max-width: 100%;
    width: 100%;
    min-height: calc(100vh - 230px);
  }
  .spec-editor-shell .simple-editor-content .tiptap.ProseMirror.simple-editor {
    min-height: calc(100vh - 320px);
    padding: 1.5rem 1.5rem 22vh;
  }
  .spec-editor-shell .tiptap-toolbar {
    top: 0;
    bottom: auto !important;
    position: sticky;
    border-radius: 8px;
    z-index: 24;
    margin-bottom: 12px;
    width: 100%;
    max-width: 100%;
  }
  @media (max-width: 768px) {
    .spec-editor-shell .simple-editor-content .tiptap.ProseMirror.simple-editor {
      padding: 1rem 1rem 26vh;
    }
  }
`;function Be(t){return t.toLowerCase().replace(/[^\w\u4e00-\u9fa5]+/g,"-").replace(/^-+|-+$/g,"")}function vt(t){const e=[],r=t.split(`
`),c=[];for(const y of r){const h=y.match(/^(#{1,6})\s+(.+)$/);if(!h)continue;const m=h[1].length,f=h[2].trim(),d={id:Be(f),title:f,level:m};for(;c.length>0&&c[c.length-1].level>=m;)c.pop();if(c.length===0)e.push(d);else{const E=c[c.length-1];E.children||(E.children=[]),E.children.push(d)}c.push(d)}return e}function je(t){return t.map(e=>({key:e.id,href:`#${e.id}`,title:e.title,children:e.children?je(e.children):void 0}))}const Rt=t=>{var y;const{className:e,children:r}=t,c=((y=e==null?void 0:e.match(/language-(\w+)/))==null?void 0:y[1])||"";return typeof r!="string"?null:c==="mermaid"?k.jsx(rt,{children:r}):k.jsx("code",{className:e,children:r})},F=t=>r=>{const{children:c}=r,h=Be(typeof c=="string"?c:""),m=`h${t}`;return k.jsx(m,{id:h,children:c})};function we(t){let e=t.key||t.label||"default";if(t.url)try{e=new URL(t.url,window.location.origin).pathname||e}catch{e=t.url||e}return`${kt}${encodeURIComponent(e)}`}function Ie(t){if(typeof window>"u")return null;try{return window.localStorage.getItem(we(t))}catch{return null}}function Ne(t,e){if(!(typeof window>"u"))try{window.localStorage.setItem(we(t),e)}catch{}}function fe(t){if(!(typeof window>"u"))try{window.localStorage.removeItem(we(t))}catch{}}function $e(){if(typeof window>"u")return"none";try{const t=new URLSearchParams(window.location.search);if(t.get("editor")==="specComment")return"comment";const e=t.get(se)??t.get("edit");return e&&(e==="1"||e.toLowerCase()==="true")?"comment":"none"}catch{return"none"}}function Mt(t){if(!(typeof window>"u"))try{const e=new URL(window.location.href),r=e.searchParams.get(se);if(t){r!=="1"&&e.searchParams.set(se,"1"),window.history.replaceState(null,"",e.toString());return}r!==null&&(e.searchParams.delete(se),window.history.replaceState(null,"",e.toString()))}catch{}}function J(t){window.parent!==window&&window.parent.postMessage(t,"*")}function Ue(t){return t.reduce((e,r)=>(e[r.key]=r.content||"",e),{})}const Dt=ye.forwardRef(function({content:e,documentUrl:r,documents:c,onDocumentChange:y},h){var Ce;const m=i.useMemo(()=>c&&c.length>0?c:[{key:"default",label:"文档",content:e||"",url:r}],[e,r,c]),[f,p]=i.useState(m),[d,E]=i.useState(()=>Ue(m)),[w,P]=i.useState(((Ce=m[0])==null?void 0:Ce.key)||"default"),[b,v]=i.useState(()=>$e()),[X,ie]=i.useState(!1),[ge,We]=ot.useModal(),L=i.useRef(f),le=i.useRef(d),de=i.useRef(void 0),G=i.useRef(b),W=i.useRef(null),B=i.useRef(new Set),Q=i.useRef(null),R=i.useRef(null),ue=i.useRef(!1),Y=i.useRef(new Set),s=i.useMemo(()=>f.find(n=>n.key===w)||f[0],[f,w]),j=b!=="none",I=b==="edit",ke=b==="comment",T=i.useCallback(()=>{W.current!==null&&(window.clearTimeout(W.current),W.current=null)},[]),$=i.useCallback(n=>{n&&fe(n)},[]),M=i.useCallback(()=>{L.current.forEach(n=>fe(n))},[]),Ee=i.useCallback(()=>{if(T(),G.current!=="edit")return;const n=L.current,o=le.current;n.forEach(a=>{const l=o[a.key]||"",u=a.content||"";if(l===u){fe(a);return}Ne(a,u)})},[T]),be=i.useCallback(n=>{if(!n)return null;const o=Le(n.url),a=o.docPath;return{kind:"markdown-document",id:o.docPath||n.url||n.key,path:a||void 0,url:typeof window<"u"?window.location.href:n.url,meta:{resourceKind:o.resourceKind,entryType:o.entryType,entryName:o.entryName,docType:o.docType,targetPath:a,currentFilePath:o.docPath,docPath:o.docPath,prototypeFilePath:o.prototypePath,storageScope:o.docPath?`markdown-doc:${o.docPath}`:`markdown-doc:${n.key}`}}},[]),H=i.useCallback(n=>{var l;const o=!!((n==null?void 0:n.initialDarkMode)??ue.current);if(R.current&&ue.current===o)return R.current;(l=R.current)==null||l.destroy();const a=it({interactionProfile:"text-comment",ui:{toolbarMode:"host",initialDarkMode:o,skillInstallSource:".agents/skills/prototype-comments/SKILL.md"},host:{getResourceContext:()=>be(de.current)},genieBridge:{apiBaseUrl:Re(),integrationChannel:"make",targetClientId:"make",provider:"codex"},integrationWs:{enabled:!0,apiBaseUrl:Re(),channel:"make",clientId:`make-doc-${Math.random().toString(36).slice(2,10)}`,source:"make-doc"}});return R.current=a,ue.current=o,a},[be]),U=i.useCallback(()=>{var n;(n=R.current)==null||n.stop()},[]),Z=i.useCallback(()=>{if(!s)throw new Error("当前没有可用文档");const n=R.current;if(!n)throw new Error("批注编辑器尚未就绪");const o=n.getEditedSnapshot();if(!o.modifiedElements.length)throw new Error("当前没有可生成 Prompt 的批注");const{prompt:a,targetPath:l,meta:u}=gt({docLabel:s.label,docUrl:s.url,modifiedElements:o.modifiedElements.map(g=>({label:g.label,note:g.note,imageCount:g.imageCount,changeKinds:g.changeKinds.filter(A=>A==="text"||A==="style"||A==="class"),locator:g.locator}))});return{prompt:a,targetPath:l||u.docPath||"",context:{version:"1",systemContext:"",currentFile:{path:u.docPath||l||"",displayName:St(u,s.label)},selectedElements:[],extensions:{source:"spec-comment-editor",pageUrl:typeof window<"u"?window.location.href:"",docLabel:s.label,docUrl:s.url||"",resourceKind:u.resourceKind,docPath:u.docPath,prototypePath:u.prototypePath,entryType:u.entryType,entryName:u.entryName,docType:u.docType,updatedAt:new Date().toISOString()}}}},[s]);i.useEffect(()=>{p(m),E(Ue(m)),P(n=>{var o;return m.some(a=>a.key===n)?n:((o=m[0])==null?void 0:o.key)||"default"}),v($e()),ie(!1)},[m]),i.useEffect(()=>{L.current=f},[f]),i.useEffect(()=>{le.current=d},[d]),i.useEffect(()=>{G.current=b},[b]),i.useEffect(()=>{de.current=s,y==null||y(s||null)},[s,y]);const D=i.useMemo(()=>f.reduce((n,o)=>(n[o.key]=(d[o.key]||"")!==(o.content||""),n),{}),[f,d]),ee=i.useMemo(()=>Object.values(D).some(Boolean),[D]),te=i.useMemo(()=>Object.values(D).filter(Boolean).length,[D]),Qe=i.useCallback(n=>{const o=w;p(a=>{let l=!1;const u=a.map(g=>g.key!==o||wt({savedContent:le.current[g.key]||"",currentContent:g.content||"",nextContent:n,userChanged:Y.current.has(g.key)})?g:(l=!0,{...g,content:n}));return l?(L.current=u,u):a})},[w]),_=i.useCallback(()=>{w&&Y.current.add(w)},[w]),ze=i.useCallback(n=>{var a;const o=n.target;(a=o==null?void 0:o.closest)!=null&&a.call(o,".tiptap-toolbar")&&_()},[_]),qe=i.useCallback(async(n,o,a)=>{const l=de.current||s;if(!(l!=null&&l.url))throw new Error("缺少文档地址，无法上传图片");const u=l.url;return Y.current.add(l.key),new Promise((g,A)=>{const pe=new FormData;pe.append("file",n,n.name||"image"),pe.append("docUrl",u);const C=new XMLHttpRequest;let oe=!1,ae=null;const xe=()=>{a&&ae&&a.removeEventListener("abort",ae)},z=S=>{oe||(oe=!0,xe(),A(S))},Ge=S=>{oe||(oe=!0,xe(),g(S))},Ye=()=>{if(C.response&&typeof C.response=="object")return C.response;if(!C.responseText)return{};try{return JSON.parse(C.responseText)}catch{return{}}};if(ae=()=>{try{C.abort()}catch{z(new Error("Upload cancelled"))}},a){if(a.aborted){z(new Error("Upload cancelled"));return}a.addEventListener("abort",ae,{once:!0})}C.open("POST","/api/spec-doc/upload-image"),C.responseType="json",C.upload.onprogress=S=>{S.lengthComputable&&(o==null||o({progress:Math.round(S.loaded/S.total*100)}))},C.onerror=()=>{z(new Error("图片上传失败，请检查网络后重试"))},C.onabort=()=>{z(new Error("Upload cancelled"))},C.onload=()=>{const S=Ye();if(C.status>=200&&C.status<300&&(S!=null&&S.success)&&typeof(S==null?void 0:S.url)=="string"){o==null||o({progress:100}),Ge(S.url);return}z(new Error((S==null?void 0:S.error)||"图片上传失败"))},C.send(pe)})},[s]),K=i.useCallback(()=>{p(n=>{const o=n.map(a=>D[a.key]?{...a,content:d[a.key]||""}:a);return L.current=o,o})},[D,d]),N=i.useCallback((n,o)=>{J({type:"SPEC_EDIT_NOTICE",level:n,message:o})},[]),Se=i.useCallback((n,o)=>{let a="",l="";try{const u=new URL(n,window.location.origin);a=u.pathname,l=u.search}catch{a=n,l=""}if(a==="/api/markdown-file"||a.startsWith("/api/docs/"))return{url:`${a}${l}`,init:{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})}};if(a.startsWith("/docs/templates/")){const u=a.slice(16),g=decodeURIComponent(u);return{url:Me(`templates/${De(g)}`),init:{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})}}}if(a.startsWith("/docs/")){const u=a.slice(6),g=decodeURIComponent(u);return{url:Me(De(g)),init:{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})}}}return{url:"/api/spec-doc/save",init:{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({docUrl:n,content:o})}}},[]),O=i.useCallback(async n=>{if(!s)return N("warning","当前没有可保存的文档"),!1;if(!D[s.key])return T(),$(s),n!=null&&n.exitAfterSave?(M(),v("none")):n!=null&&n.suppressNoChangeNotice||N("info","当前文档没有需要保存的更改"),!0;if(!s.url)return N("error","缺少文档地址，无法保存"),!1;ie(!0);try{const{url:a,init:l}=Se(s.url,s.content||""),u=await fetch(a,l),g=await u.json().catch(()=>({}));if(!u.ok)throw new Error((g==null?void 0:g.error)||"保存失败");return E(A=>({...A,[s.key]:s.content||""})),T(),$(s),n!=null&&n.suppressSuccessNotice||N("success",`${s.label} 已保存`),n!=null&&n.exitAfterSave&&(M(),v("none")),!0}catch(a){return N("error",(a==null?void 0:a.message)||"保存失败"),!1}finally{ie(!1)}},[Se,M,$,T,s,D,N]),ne=i.useCallback(async(n,o)=>{const a=(o==null?void 0:o.saveBehavior)??"none";if(n==="comment"&&G.current==="edit")if(a==="save"){if(!await O({suppressNoChangeNotice:!0,suppressSuccessNotice:!0}))return!1}else a==="discard"&&(K(),T(),M());return v(n),!0},[M,T,K,O]);i.useEffect(()=>{I&&s&&Y.current.delete(s.key)},[s==null?void 0:s.key,I]);const re=i.useCallback(()=>{J({type:"SPEC_EDIT_STATUS",enabled:j,dirty:ee,saving:X,dirtyCount:te,activeDocKey:w,quickEditMode:b})},[w,te,ee,j,X,b]);i.useEffect(()=>{re()},[re]),i.useEffect(()=>{Mt(j)},[j]),i.useEffect(()=>{if(!ke||!s){U();return}const n=window.setTimeout(()=>{H().start()},0);return()=>{window.clearTimeout(n),U()}},[s,H,ke,U]),i.useEffect(()=>{const n=()=>{Ee(),U()};return window.addEventListener("beforeunload",n),()=>{window.removeEventListener("beforeunload",n)}},[Ee,U]),i.useEffect(()=>{if(!I||!s){T();return}const n=d[s.key]||"",o=s.content||"";if(n===o){T();const a=Ie(s);!!(a&&a!==o&&a!==n)||$(s);return}return T(),W.current=window.setTimeout(()=>{Ne(s,o),W.current=null},Et),()=>{T()}},[$,T,s,I,d]),i.useEffect(()=>{if(!I||!s){B.current.clear(),Q.current=null;return}if(B.current.has(s.key))return;B.current.add(s.key);const n=Ie(s);!n||n===s.content||n===(d[s.key]||"")||Q.current!==s.key&&(Q.current=s.key,ge.confirm({title:"检测到本地缓存",content:`检测到「${s.label}」存在本地未保存缓存，是否加载缓存版本？`,okText:"加载缓存",cancelText:"忽略",onOk:()=>{p(o=>{const a=o.map(l=>l.key===s.key?{...l,content:n}:l);return L.current=a,a}),N("info",`已加载 ${s.label} 的本地缓存版本`)},onCancel:()=>{$(s)},afterClose:()=>{Q.current===s.key&&(Q.current=null)}}))},[$,s,I,ge,N,d]),i.useEffect(()=>{J({type:"spec-doc-changed",activeDocKey:w})},[w]),i.useEffect(()=>{const n=o=>{const a=o.data;if(!(!a||typeof a.type!="string")){if(a.type==="SPEC_EDIT_ENABLE"){B.current.clear(),v("comment");return}if(a.type==="SPEC_EDIT_SET_MODE"){const l=a.mode==="edit"?"edit":"comment";ne(l,{saveBehavior:a.saveBehavior==="save"||a.saveBehavior==="discard"?a.saveBehavior:"none"});return}if(a.type==="SPEC_EDIT_SAVE"){O({exitAfterSave:!!a.exitAfterSave});return}if(a.type==="SPEC_EDIT_EXIT"){a.discardChanges&&K(),T(),M(),v("none");return}if(a.type==="SPEC_EDIT_STATUS_REQUEST"){re();return}if(a.type==="SPEC_EDIT_PROMPT_REQUEST"){const l=String(a.requestId||"").trim();if(!l)return;(async()=>{try{if(G.current!=="comment")throw new Error("请先切换到批注模式");const u=Z();J({type:"SPEC_EDIT_PROMPT_RESPONSE",requestId:l,success:!0,prompt:u.prompt,targetPath:u.targetPath,context:u.context})}catch(u){J({type:"SPEC_EDIT_PROMPT_RESPONSE",requestId:l,success:!1,error:(u==null?void 0:u.message)||"生成 Prompt 失败"})}})()}}};return window.addEventListener("message",n),()=>{window.removeEventListener("message",n)}},[Z,M,T,re,K,O,ne]),i.useImperativeHandle(h,()=>({enableQuickEdit(){B.current.clear(),v("comment")},disableQuickEdit(n){n!=null&&n.discardChanges&&K(),T(),M(),v("none")},enableDocumentEditor(n){B.current.clear(),v("comment"),H({initialDarkMode:n==null?void 0:n.initialDarkMode}).start()},disableDocumentEditor(){U()},getHostToolbarState(){var n,o;return((o=(n=R.current)==null?void 0:n.getHostToolbarState)==null?void 0:o.call(n))??null},subscribeHostToolbarState(n){return H().subscribeHostToolbarState(n)},runHostToolbarAction(n){return H().runHostToolbarAction(n)},async setQuickEditMode(n,o){return ne(n,o)},getQuickEditStatus(){return{enabled:j,dirty:ee,saving:X,dirtyCount:te,activeDocKey:w,quickEditMode:b}},handleCopyPrompt(){return Promise.resolve(Z())},saveCurrentDoc:O}),[w,Z,M,T,te,ee,H,j,X,b,K,O,ne,U]),i.useEffect(()=>()=>{var n;(n=R.current)==null||n.destroy(),R.current=null},[]);const{anchorItems:Te}=i.useMemo(()=>{const n=vt((s==null?void 0:s.content)||"");return{anchorItems:je(n)}},[s==null?void 0:s.content]),Ve=f.length>1,Je=()=>k.jsxs("div",{className:"markdown-container",children:[k.jsx("div",{className:"markdown-content",children:k.jsx("div",{children:k.jsx(nt,{className:"x-markdown-light",content:(s==null?void 0:s.content)||"",components:{code:Rt,img:n=>k.jsx(xt,{...n,documentUrl:s==null?void 0:s.url}),h1:F(1),h2:F(2),h3:F(3),h4:F(4),h5:F(5),h6:F(6)}})})}),Te.length>0&&k.jsxs("div",{className:"anchor-sidebar",children:[k.jsx("div",{style:{marginBottom:12,fontWeight:600,fontSize:16,paddingLeft:16,borderLeft:"2px solid transparent"},children:"目录"}),k.jsx(ct,{affix:!1,offsetTop:40,targetOffset:80,items:Te,onClick:(n,o)=>{n.preventDefault();const a=o.href.replace("#",""),l=document.getElementById(a);l&&l.scrollIntoView({behavior:"smooth",block:"start"})}})]})]}),Xe=()=>k.jsx("div",{className:"markdown-container spec-editor-shell",onBeforeInputCapture:_,onInputCapture:_,onKeyDownCapture:_,onPasteCapture:_,onDropCapture:_,onPointerDownCapture:ze,children:k.jsx("div",{className:"markdown-content",children:k.jsx("div",{children:k.jsx(lt,{content:(s==null?void 0:s.content)||"",contentType:"markdown",editable:I,showThemeToggle:!1,toolbarPreset:"full",imageUpload:qe,onMarkdownChange:Qe})})})});return k.jsx(at,{theme:ft,children:k.jsxs(et,{locale:tt,children:[We,k.jsx("style",{children:Pt}),Ve&&k.jsx("div",{className:"markdown-tabs-container",children:k.jsx(st,{activeKey:w,onChange:P,items:f.map(n=>({key:n.key,label:D[n.key]?`${n.label} *`:n.label}))})}),I?Xe():Je()]})})});let he=null,x=ye.createRef(),ce="";function It(t){ce=(t==null?void 0:t.url)||ce}function _e(t){var e;(e=x.current)==null||e.enableDocumentEditor(t)}function Ae(){var t;(t=x.current)==null||t.disableDocumentEditor()}function Nt(){var t;return((t=x.current)==null?void 0:t.getHostToolbarState())??null}function $t(t){var e;return((e=x.current)==null?void 0:e.subscribeHostToolbarState(t))??(()=>{})}function Ut(t){var e;return((e=x.current)==null?void 0:e.runHostToolbarAction(t))??Promise.resolve(!1)}function He(t){const e=document.getElementById("spec-root");if(!e){console.error("[Spec Template] 找不到 #spec-root 元素");return}he||(e.innerHTML="",he=Ze(e)),e.className="",x=ye.createRef(),he.render(k.jsx(Dt,{ref:x,...t,onDocumentChange:It}))}function Ke(t,e){try{ce=e||"",He({content:t,documentUrl:e}),console.log("[Spec Template] Markdown 已渲染")}catch(r){console.error("[Spec Template] 渲染失败:",r);const c=document.getElementById("spec-root");if(!c)return;c.innerHTML=`
      <div style="color: red; padding: 20px;">
        <h2>渲染失败</h2>
        <pre>${r}</pre>
      </div>
    `}}function Oe(t){var e;try{ce=((e=t[0])==null?void 0:e.url)||"",He({documents:t}),console.log("[Spec Template] 多文档 Markdown 已渲染")}catch(r){console.error("[Spec Template] 渲染失败:",r);const c=document.getElementById("spec-root");if(!c)return;c.innerHTML=`
      <div style="color: red; padding: 20px;">
        <h2>渲染失败</h2>
        <pre>${r}</pre>
      </div>
    `}}async function Fe(t){if((t.headers.get("content-type")||"").includes("application/json")){const r=await t.json().catch(()=>null);return typeof(r==null?void 0:r.content)=="string"?r.content:JSON.stringify(r,null,2)}return t.text()}async function _t(t){try{console.log("[Spec Template] 加载 Markdown:",t);const e=await fetch(t);if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);const r=await Fe(e);Ke(r,t)}catch(e){console.error("[Spec Template] 加载失败:",e);const r=document.getElementById("spec-root");r&&(r.innerHTML=`
        <div style="color: red; padding: 20px;">
          <h2>加载失败</h2>
          <p>无法加载 Markdown 文件: ${t}</p>
          <pre>${e}</pre>
        </div>
      `)}}async function At(t){try{console.log("[Spec Template] 加载多个 Markdown 文档:",t);const e=await Promise.all(t.map(async({key:r,label:c,url:y})=>{const h=await fetch(y);if(!h.ok)throw new Error(`HTTP ${h.status}: ${h.statusText} for ${y}`);const m=await Fe(h);return{key:r,label:c,content:m,url:y}}));Oe(e)}catch(e){console.error("[Spec Template] 加载失败:",e);const r=document.getElementById("spec-root");r&&(r.innerHTML=`
        <div style="color: red; padding: 20px;">
          <h2>加载失败</h2>
          <p>无法加载 Markdown 文件</p>
          <pre>${e}</pre>
        </div>
      `)}}typeof window<"u"&&(window.SpecTemplateBootstrap={renderMarkdown:Ke,renderMarkdownDocuments:Oe,loadMarkdownFromUrl:_t,loadMarkdownDocumentsFromUrls:At},window.SpecTemplateBootstrap.editors={enable(t,e){var r;(r=x.current)==null||r.enableQuickEdit(),e!=null&&e.toolbarMode&&_e({toolbarMode:e.toolbarMode})},disable(t){var e;(e=x.current)==null||e.disableQuickEdit(t),Ae()},setQuickEditMode(t,e){var r;return((r=x.current)==null?void 0:r.setQuickEditMode(t,e))??Promise.resolve(!1)},getStatus(){var t;return((t=x.current)==null?void 0:t.getQuickEditStatus())??{enabled:!1,dirty:!1,saving:!1,dirtyCount:0,activeDocKey:"",quickEditMode:"none"}},handleCopyPrompt(){var t;return((t=x.current)==null?void 0:t.handleCopyPrompt())??Promise.reject(new Error("Markdown viewer is not ready"))},save(t){var e;return((e=x.current)==null?void 0:e.saveCurrentDoc(t))??Promise.resolve(!1)},enableDocumentEditor:_e,disableDocumentEditor:Ae,getHostToolbarState:Nt,subscribeHostToolbarState:$t,runHostToolbarAction:Ut},console.log("[Spec Template Bootstrap] 已挂载到全局"));export{At as loadMarkdownDocumentsFromUrls,_t as loadMarkdownFromUrl,Ke as renderMarkdown,Oe as renderMarkdownDocuments};
