@miadi/stateloom-web 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/server/.next/BUILD_ID +1 -1
- package/server/.next/build-manifest.json +2 -2
- package/server/.next/server/app/_global-error.html +2 -2
- package/server/.next/server/app/_global-error.rsc +1 -1
- package/server/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/server/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/server/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/server/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/server/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/server/.next/server/app/_not-found.html +1 -1
- package/server/.next/server/app/_not-found.rsc +1 -1
- package/server/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/server/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/server/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
- package/server/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/server/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/server/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/server/.next/server/app/index.html +1 -1
- package/server/.next/server/app/index.rsc +2 -2
- package/server/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
- package/server/.next/server/app/index.segments/_full.segment.rsc +2 -2
- package/server/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/server/.next/server/app/index.segments/_index.segment.rsc +1 -1
- package/server/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/server/.next/server/app/page_client-reference-manifest.js +1 -1
- package/server/.next/server/chunks/ssr/[root-of-the-server]__edbb995c._.js +3 -3
- package/server/.next/server/pages/404.html +1 -1
- package/server/.next/server/pages/500.html +2 -2
- package/server/.next/static/chunks/{f03f883bab5194ab.js → ec729c54327cc597.js} +3 -3
- package/server/package-lock.json +2 -2
- package/server/package.json +1 -1
- package/server/src/components/stage/CompanionLayer.tsx +10 -1
- package/server/stateloom-web.json +2 -2
- /package/server/.next/static/{HNER2j3kS6-hB98CL_HRG → pbn7-8jVWdRn8FLy4fHnU}/_buildManifest.js +0 -0
- /package/server/.next/static/{HNER2j3kS6-hB98CL_HRG → pbn7-8jVWdRn8FLy4fHnU}/_clientMiddlewareManifest.json +0 -0
- /package/server/.next/static/{HNER2j3kS6-hB98CL_HRG → pbn7-8jVWdRn8FLy4fHnU}/_ssgManifest.js +0 -0
|
@@ -8,10 +8,10 @@ ${b.error}`)}}catch(a){m(`# RISE rispec generation failed
|
|
|
8
8
|
${a}`)}l(!0)},W=async()=>{let a=f();try{let b=await fetch("/api/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({definition:a,language:T})});if(b.ok){let a=await b.json();m(a.code)}else{let c=await b.json().catch(()=>({error:"Unknown error"}));m(`// Code generation failed: ${c.error}
|
|
9
9
|
// Showing definition JSON as fallback:
|
|
10
10
|
${a}`)}}catch{m(`// Backend unavailable — showing definition JSON
|
|
11
|
-
${a}`)}l(!0)};return(0,h.jsxs)("div",{className:"flex flex-col gap-1.5 px-2 py-1.5 bg-gray-900 border-b border-gray-800 md:flex-row md:flex-wrap md:items-center md:px-3",children:[(0,h.jsxs)("div",{className:"toolbar-ident",children:[(0,h.jsx)("input",{ref:A,type:"file",accept:".json,.smdf.json",onChange:a=>{let b=a.target.files?.[0];if(!b)return;let c=new FileReader;c.onload=a=>{e(a.target?.result,b.name)},c.readAsText(b),a.target.value=""},className:"hidden"}),(0,h.jsxs)("span",{className:"text-xs text-gray-400 mr-1 truncate max-w-[50vw] md:max-w-none",children:[b??"untitled.smdf.json",d&&(0,h.jsx)("span",{className:"text-yellow-500 ml-0.5",children:"●"})]}),(0,h.jsx)(d5,{}),"synced"===u&&(0,h.jsx)("span",{className:"text-[10px] text-emerald-500",title:"In sync with disk",children:"⌁ synced"}),"remote-changed"===u&&(0,h.jsx)("span",{className:"text-[10px] text-amber-400",title:v??"",children:"↻ remote changed"}),"error"===u&&(0,h.jsx)("span",{className:"text-[10px] text-red-400",title:v??"",children:"⚠ disk error"}),"idle"===u&&(0,h.jsx)("span",{className:"text-[10px] text-gray-600",title:v??"No file bound",children:"○ no disk"}),(0,h.jsx)(d6,{}),(0,h.jsx)("div",{className:"flex-1"})]}),(0,h.jsxs)("div",{className:"toolbar-strip",children:[(0,h.jsx)("button",{onClick:q,disabled:0===s.length,className:"toolbar-btn disabled:opacity-30",title:"Undo (Ctrl+Z)",children:"↩"}),(0,h.jsx)("button",{onClick:r,disabled:0===t.length,className:"toolbar-btn disabled:opacity-30",title:"Redo (Ctrl+Y)",children:"↪"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:p,className:"toolbar-btn",title:"Arrange states into layers (auto-layout)",children:"⤢ Arrange"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:()=>o("select"===n?"transition":"select"),className:`toolbar-btn ${"transition"===n?"!bg-amber-700 !text-white":""}`,title:"transition"===n?"Exit draw mode (Esc)":"Draw transition mode",children:"transition"===n?"✏️ Drawing":"↗ Draw"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:()=>A.current?.click(),className:"toolbar-btn",title:"Open local .smdf.json (browser)",children:"📂"}),(0,h.jsx)("button",{onClick:P,disabled:F,className:"toolbar-btn disabled:opacity-40",title:"Save to disk (STATELOOM_PROJECT_FILE)",children:"💾 Disk"}),(0,h.jsx)("button",{onClick:R,className:"toolbar-btn",title:"Reload from disk",children:"🔄"}),(0,h.jsx)("button",{onClick:()=>{let a=new Blob([f()],{type:"application/json"}),c=URL.createObjectURL(a),d=document.createElement("a");d.href=c,d.download=b??"statemachine.smdf.json",d.click(),URL.revokeObjectURL(c)},className:"toolbar-btn",title:"Download as file",children:"📥"}),(0,h.jsx)("select",{value:H,onChange:a=>{I(a.target.value),O(null),M(null)},className:"bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 px-1 py-0.5",title:"Export format",children:dS.map(a=>(0,h.jsx)("option",{value:a,children:dT[a]},a))}),(0,h.jsx)("button",{onClick:Q,disabled:J,className:`toolbar-btn disabled:opacity-40 ${L?"!text-red-400":""}`,title:L??`Export the board as ${dT[H]}`,children:J?"…":"🖼 Export"}),N&&!L&&(0,h.jsxs)("span",{className:"text-[10px] text-emerald-500 truncate max-w-[40vw] md:max-w-[16rem]",title:N,children:["⤓ ",N]}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),B?(0,h.jsxs)("div",{className:"flex items-center gap-1",children:[(0,h.jsx)("input",{autoFocus:!0,className:"bg-gray-800 border border-gray-700 rounded px-2 py-0.5 text-xs text-gray-200 w-32 md:w-24",placeholder:"State name...",value:D,onChange:a=>E(a.target.value),onKeyDown:a=>{"Enter"===a.key&&S(),"Escape"===a.key&&C(!1)}}),(0,h.jsx)("button",{onClick:S,className:"toolbar-btn-sm",children:"✓"}),(0,h.jsx)("button",{onClick:()=>C(!1),className:"toolbar-btn-sm",children:"✕"})]}):(0,h.jsx)("button",{onClick:()=>C(!0),className:"toolbar-btn",children:"+State"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:()=>j(),className:"toolbar-btn",children:"✓ Validate"}),(0,h.jsxs)("select",{value:T,onChange:a=>U(a.target.value),className:"bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 px-1 py-0.5",children:[(0,h.jsx)("option",{value:"python",children:"Python"}),(0,h.jsx)("option",{value:"typescript",children:"TypeScript"})]}),(0,h.jsx)("button",{onClick:W,className:"toolbar-btn",children:"⚡ Generate"}),(0,h.jsx)("button",{onClick:V,className:"toolbar-btn",title:"Generate RISE rispec markdown",children:"📜 RISE"}),(0,h.jsxs)("button",{onClick:()=>l(!k),className:`toolbar-btn ${k?"text-blue-400":""}`,children:["</>"," Code"]})]})]})}function d8(){let a=dM(a=>a.generatedCode),b=dM(a=>a.showCodePreview),c=dM(a=>a.setShowCodePreview);return b?(0,h.jsx)("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/60 p-2 md:p-0",children:(0,h.jsxs)("div",{className:"bg-gray-900 border border-gray-700 rounded-lg shadow-xl w-full max-h-[85dvh] md:w-[80%] md:max-w-3xl md:max-h-[80dvh] flex flex-col",children:[(0,h.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-800",children:[(0,h.jsx)("h3",{className:"text-sm font-semibold text-gray-300",children:"Generated Definition (JSON)"}),(0,h.jsx)("button",{onClick:()=>c(!1),className:"text-gray-500 hover:text-gray-300 text-lg min-h-11 min-w-11 md:min-h-0 md:min-w-0","aria-label":"Close preview",children:"✕"})]}),(0,h.jsx)("pre",{className:"flex-1 overflow-auto overscroll-contain p-4 text-[11px] leading-relaxed text-green-400 font-mono md:text-sm",children:a??"No code generated yet"}),(0,h.jsx)("div",{className:"flex justify-end px-4 py-2 border-t border-gray-800",children:(0,h.jsx)("button",{onClick:()=>{a&&navigator.clipboard.writeText(a)},className:"text-xs bg-gray-700 hover:bg-gray-600 text-gray-300 px-4 py-3 rounded md:px-3 md:py-1",children:"Copy to Clipboard"})})]})}):null}function d9(){let a=dM(a=>a.applyRemote),b=dM(a=>a.setRemoteStatus),c=dM(a=>a.setRemoteMtime),d=(0,d4.useRequestedDoc)();return(0,i.useEffect)(()=>{let e=!1,f=(0,d4.docQuery)(d);async function g(){try{let a=await fetch(`/api/file${f}`,{cache:"no-store"});if(!a.ok)return null;return await a.json()}catch{return null}}(async()=>{let c=await g();e||(c?.path&&dM.getState().setDocPath(c.path),c?.exists&&c.content?a(c.content,c.mtime,c.path.split("/").pop()):b("idle",c?`No file at ${c.path}`:null))})();let h=new EventSource(`/api/watch${f}`);return h.addEventListener("hello",a=>{try{let b=JSON.parse(a.data);"number"==typeof b?.mtime&&c(b.mtime)}catch{}}),h.addEventListener("change",async d=>{let e=0;try{e=JSON.parse(d.data)?.mtime??0}catch{}if(e<=(dM.getState().remoteMtime??0))return;let f=await g();f?.exists&&f.content&&(dM.getState().dirty?(b("remote-changed",`Disk changed at ${new Date(f.mtime).toLocaleTimeString()} — local has unsaved edits`),c(f.mtime)):a(f.content,f.mtime,f.path.split("/").pop()))}),h.addEventListener("error",()=>{b("error","Watch stream disconnected")}),()=>{e=!0,h.close()}},[a,b,c,d]),null}function ea({url:a}){let b=(0,d4.useRequestedDoc)();return(0,i.useEffect)(()=>{if(!a)return;let c=!1,d=null,e=null,f=null,g=null;return(async()=>{let h="";try{let a=await fetch(`/api/file${(0,d4.docQuery)(b)}`,{cache:"no-store"});a.ok&&(h=(await a.json())?.path??"")}catch{}c||(h&&dM.getState().setDocPath(h),(d=dy({url:a,role:"web",docId:h,name:"web-designer",onFull:a=>{dM.getState().applyRemote(JSON.stringify({stateMachine:a.def}),a.mtime??Date.now(),h&&h.split("/").pop()||void 0),g=a.def},onPatch:a=>{dM.getState().applyRemoteOps(a.ops,a.mtime??Date.now(),a.seq),g=dM.getState().definition},onPresence:a=>{dM.getState().setPresence(a)}})).connect(),e=dM.subscribe((a,b)=>{a.definition===b.definition||a._applyingRemote||(f&&clearTimeout(f),f=setTimeout(()=>{var a,b;let c,e;if(!d||"connected"!==d.getSnapshot().status)return;let f=dM.getState().definition;if(null===g){d.emitFull(f),g=f;return}let h=(a=g,b=f,c=a??{settings:{namespace:"",asynchronous:!1},events:[],state:{name:b.state.name,states:[]}},function(a,b,c){let d={},e=!1,f=new Set([...Object.keys(a.settings),...Object.keys(b.settings)]),g=a.settings,h=b.settings;for(let a of f)q(g[a],h[a])||void 0===h[a]||(d[a]=h[a],e=!0);void 0!==a.settings.notes&&void 0===b.settings.notes&&(d.notes="",e=!0),e&&c.push({op:"settings.update",patch:d})}(c,b,e=[]),function(a,b,c){let d=a.events,e=b.events,f=Math.min(d.length,e.length);for(let a=0;a<f;a++)!function(a,b,c,d){let e={},f=!1;for(let a of["name","file","feeder","description","timers"])q(b[a],c[a])||void 0===c[a]||(e[a]=c[a],f=!0);f&&d.push({op:"eventSource.update",index:a,patch:e});let g=b.events??[],h=c.events??[],i=new Set(h.map(a=>a.id));for(let a of g)i.has(a.id)||d.push({op:"event.remove",id:a.id});let j=g.filter(a=>i.has(a.id)),k=0;for(;k<h.length;){let b=h[k];k<j.length&&j[k].id===b.id?(function(a,b,c){let d={},e=!1;for(let c of["name","description","preAction","postAction"])q(a[c],b[c])||void 0===b[c]||(d[c]=b[c],e=!0);e&&c.push({op:"event.update",id:b.id,patch:d})}(j[k],b,d),function(a,b,c,d){let e=Math.min(b.length,c.length);for(let f=0;f<e;f++)if(!q(b[f],c[f])){let e={};b[f].name!==c[f].name&&(e.name=c[f].name),b[f].type!==c[f].type&&(e.type=c[f].type),d.push({op:"parameter.update",eventId:a,index:f,patch:e})}for(let b=e;b<c.length;b++)d.push({op:"parameter.add",eventId:a,parameter:c[b],index:b});for(let e=b.length-1;e>=c.length;e--)d.push({op:"parameter.remove",eventId:a,index:e})}(b.id,j[k].parameters??[],b.parameters??[],d)):(d.push({op:"event.add",sourceIndex:a,event:b,index:k}),j.splice(k,0,b)),k++}}(a,d[a],e[a],c);for(let a=d.length;a<e.length;a++)c.push({op:"eventSource.add",source:e[a]});for(let a=d.length-1;a>=e.length;a--)c.push({op:"eventSource.remove",index:a})}(c,b,e),function(a,b,c){let d=o(a.state),e=o(b.state),f=new Map(d.map(a=>[a.name,a])),g=new Map(e.map(a=>[a.name,a])),h=p(a.state),i=p(b.state),j=[];for(let a of e){if(f.has(a.name))continue;let b=i.get(a.name)??null,{states:d,transitions:e,...g}=a;c.push({op:"state.add",parent:b,state:{...g}}),e&&e.length>0&&j.push({state:a.name,transitions:e})}for(let a of e){if(!f.has(a.name))continue;let b=h.get(a.name)??null,d=i.get(a.name)??null;b!==d&&null!==d&&c.push({op:"state.nest",child:a.name,newParent:d})}for(let a of e){let b=f.get(a.name);if(!b)continue;let d={},e=!1;q(b.kind,a.kind)||void 0===a.kind||(d.kind=a.kind,e=!0),q(b.description,a.description)||void 0===a.description||(d.description=a.description,e=!0),q(b.notes,a.notes)||(d.notes=a.notes??"",e=!0),q(b.prompt,a.prompt)||(d.prompt=a.prompt??"",e=!0),e&&c.push({op:"state.update",name:a.name,patch:d}),r(a.name,"onEntry",b.onEntry?.actions??[],a.onEntry?.actions??[],c),r(a.name,"onExit",b.onExit?.actions??[],a.onExit?.actions??[],c)}for(let a of j)a.transitions.forEach((b,d)=>{c.push({op:"transition.add",state:a.state,transition:b,index:d})});for(let a of e){let b=f.get(a.name);b&&function(a,b,c,d){let e=Math.min(b.length,c.length);for(let f=0;f<e;f++){if(q(b[f],c[f]))continue;let e={};for(let a of["event","nextState","condition","description","actions"])q(b[f][a],c[f][a])||void 0===c[f][a]||(e[a]=c[f][a]);Object.keys(e).length>0&&d.push({op:"transition.update",state:a,index:f,patch:e})}for(let b=e;b<c.length;b++)d.push({op:"transition.add",state:a,transition:c[b],index:b});for(let e=b.length-1;e>=c.length;e--)d.push({op:"transition.remove",state:a,index:e})}(a.name,b.transitions??[],a.transitions??[],c)}for(let a=d.length-1;a>=0;a--){let b=d[a];if(g.has(b.name))continue;let e=b.transitions??[];for(let a=e.length-1;a>=0;a--)c.push({op:"transition.remove",state:b.name,index:a});c.push({op:"state.remove",name:b.name})}}(c,b,e),e);0!==h.length&&(d.emitPatch(h),g=f)},60))}))})(),()=>{c=!0,f&&clearTimeout(f),e&&e(),d&&d.disconnect()}},[a,b]),null}function eb(){let a=process.env.NEXT_PUBLIC_STATELOOM_BRIDGE_URL??process.env.NEXT_PUBLIC_SMCRAFT_BRIDGE_URL;return"string"==typeof a&&a.length>0?a:void 0}let ec=null;function ed(){return ec||(ec=(async()=>{let a=eb()??null;try{let b=await fetch("/api/config",{cache:"no-store"});if(b.ok){let c=await b.json();return{bridgeUrl:c.bridgeUrl||a,projectFile:c.projectFile??null,stage:c.stage??null,companion:!0===c.companion,companionEpisode:c.companionEpisode??null}}}catch{}return{bridgeUrl:a,projectFile:null,stage:null,companion:!1,companionEpisode:null}})())}function ee(){let a=eb(),[b,c]=(0,i.useState)(a);return((0,i.useEffect)(()=>{let a=!0;return ed().then(b=>{a&&b.bridgeUrl&&c(b.bridgeUrl)}),()=>{a=!1}},[]),"string"==typeof b&&b.length>0)?(0,h.jsx)(ea,{url:b}):(0,h.jsx)(d9,{})}function ef(a){return Number.isFinite(a)?Math.min(1.75,Math.max(.75,a)):1}function eg(a){"u">typeof document&&(document.documentElement.style.fontSize=`${16*ef(a)}px`)}let eh=1,ei=!1,ej=new Set;function ek(){return ei||(ei=!0,eh=1),eh}function el(){return 1}function em(a){return ej.add(a),()=>{ej.delete(a)}}function en(a,b){let c=ef(a);if(eg(c),b,ei=!0,c!==eh)for(let a of(eh=c,ej))a()}function eo(a,b){return Math.max(1,Math.hypot(b.clientX-a.clientX,b.clientY-a.clientY))}function ep(a,b){for(let c=0;c<a.length;c++)if(a[c].identifier===b)return a[c];return null}function eq(){let a=(0,i.useSyncExternalStore)(em,ek,el),b=(0,i.useRef)(null),c=(0,i.useRef)(null),d=(0,i.useRef)(null);(0,i.useEffect)(()=>{eg(a)},[a]);let e=(0,i.useCallback)(a=>{c.current=a,null===d.current&&(d.current=requestAnimationFrame(()=>{d.current=null,null!==c.current&&en(c.current,!1)}))},[]),f=(0,i.useCallback)(()=>{c.current=null,en(1,!0)},[]);return((0,i.useEffect)(()=>{let a=()=>{let a=b.current;if(b.current=null,!a?.engaged)return;null!==d.current&&(cancelAnimationFrame(d.current),d.current=null);let e=c.current??ek();c.current=null,en(ef(e),!0)},f=c=>{if(2!==c.touches.length){b.current&&a();return}let[d,e]=[c.touches[0],c.touches[1]];dP(d.target)||dP(e.target)||(b.current={a:d.identifier,b:e.identifier,startScale:ek(),startDist:eo(d,e),engaged:!1})},g=a=>{let c=b.current;if(!c)return;let d=ep(a.touches,c.a),f=ep(a.touches,c.b);if(!d||!f)return;a.preventDefault();let g=eo(d,f);if(!c.engaged){if(12>Math.abs(g-c.startDist))return;c.engaged=!0,c.startDist=g;return}e(ef(c.startScale*(g/c.startDist)))},h=c=>{let d=b.current;d&&(ep(c.touches,d.a)&&ep(c.touches,d.b)||a())};return document.addEventListener("touchstart",f,{passive:!0,capture:!0}),document.addEventListener("touchmove",g,{passive:!1,capture:!0}),document.addEventListener("touchend",h,{passive:!0,capture:!0}),document.addEventListener("touchcancel",h,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",f,{capture:!0}),document.removeEventListener("touchmove",g,{capture:!0}),document.removeEventListener("touchend",h,{capture:!0}),document.removeEventListener("touchcancel",h,{capture:!0}),null!==d.current&&cancelAnimationFrame(d.current)}},[e]),1===a)?null:(0,h.jsxs)("div",{className:"ui-scale-pill",role:"status","aria-live":"polite",children:[(0,h.jsxs)("span",{children:["UI ",Math.round(100*a),"%"]}),(0,h.jsx)("button",{type:"button",onClick:f,"aria-label":"Reset interface size to 100 percent",children:"Reset"})]})}var er=i;class es extends er.Component{state={error:null};static getDerivedStateFromError(a){return{error:a}}componentDidCatch(a,b){console.error(`[stateloom] the ${this.props.what} could not be drawn:`,a,b.componentStack)}componentDidUpdate(a){this.state.error&&a.resetKey!==this.props.resetKey&&this.setState({error:null})}render(){let{error:a}=this.state;return a?(0,h.jsx)("div",{role:"alert",className:"flex h-full w-full items-center justify-center p-6 text-center text-sm text-amber-300",children:(0,h.jsxs)("p",{className:"max-w-md",children:["This ",this.props.what," cannot be drawn: ",a.message,". The file on disk is unchanged — correct it in the panel, in the file, or with the agent that wrote it."]})}):this.props.children}}function et({size:a=16}){return(0,h.jsxs)("svg",{width:a,height:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,h.jsx)("path",{d:"M12 4.5 21 19.5H3Z"}),(0,h.jsx)("path",{d:"M12 10v4.5"}),(0,h.jsx)("path",{d:"M12 17.3v.01"})]})}function eu({locked:a,size:b=16}){return(0,h.jsxs)("svg",{width:b,height:b,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,h.jsx)("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),(0,h.jsx)("path",{d:a?"M8 11V8a4 4 0 0 1 8 0v3":"M8 11V8a4 4 0 0 1 7.5-1.9"})]})}function ev(a){let{onClose:b,restVh:c,tallVh:d}=a,[e,f]=(0,i.useState)(!1),[g,h]=(0,i.useState)(null),j=(0,i.useRef)(null),k=()=>{f(!1),b()},l=a=>{let b=j.current;if(!b||b.id!==a.pointerId)return;j.current=null;let c=a.clientY-b.y;if(h(null),6>Math.abs(c))return f(a=>!a);if(c<=-50)return f(!0);if(c>=80){if(e&&c<260)return f(!1);k()}},m=e?d:c,n=null!==g;return{zoneProps:{onPointerDown:a=>{a.target.closest("button")||(j.current={y:a.clientY,id:a.pointerId},a.currentTarget.setPointerCapture(a.pointerId),h(0))},onPointerMove:a=>{let b=j.current;b&&b.id===a.pointerId&&h(a.clientY-b.y)},onPointerUp:l,onPointerCancel:l,style:{touchAction:"none",cursor:"grab"}},sheetStyle:{"--sheet-h":n&&g<0?`min(calc(${m}dvh + ${-g}px), ${d}dvh)`:`${m}dvh`,...n?{transition:"none"}:{},...n&&g>0?{transform:`translateY(${g}px)`}:{}},close:k}}let ew="stateloom:focus-request",ex="stateloom:system-changed",ey="stateloom:strip-note";function ez(a){let[b,c]=(0,i.useState)(null);return(0,i.useEffect)(()=>{let a=()=>c(null);a();let b=["popstate",d4.DOC_CHANGE_EVENT,"stateloom:focus",ew];for(let c of b)window.addEventListener(c,a);return()=>{for(let c of b)window.removeEventListener(c,a)}},[a]),b}function eA(a){let b=new URL(window.location.href),c=b.searchParams.get("doc")!==a.doc;b.searchParams.set("doc",a.doc);let d=void 0===a.system?b.searchParams.get("system"):a.system;d?b.searchParams.set("system",d):b.searchParams.delete("system"),a.focus?b.searchParams.set("focus",a.focus):b.searchParams.delete("focus"),c?window.history.pushState({},"",b):window.history.replaceState(window.history.state,"",b),c&&window.dispatchEvent(new Event(d4.DOC_CHANGE_EVENT)),window.dispatchEvent(new Event(ew))}function eB(a){}function eC(){let[a,b]=(0,i.useState)({focus:null,nonce:0});return(0,i.useEffect)(()=>{let a=()=>b(a=>({focus:null,nonce:a.nonce+1}));a();let c=["popstate",d4.DOC_CHANGE_EVENT,ew];for(let b of c)window.addEventListener(b,a);return()=>{for(let b of c)window.removeEventListener(b,a)}},[]),a}let eD="/api/companion/",eE="stateloom.companion.autoplay",eF=/^\d{4}-\d{2}-\d{2}-episode-\d+-[a-z0-9-]+$/,eG=a=>{let b=new Date(a);return Number.isNaN(b.getTime())?"":b.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})},eH=a=>"starting"===a||"recording"===a||"sending"===a,eI={state:"idle",seconds:0,held:0,message:"",error:!1,stored:null},eJ={episode:null,items:[],presence:null,waiting:null,error:null};function eK({stage:a,defaultEpisode:b}){let[c,d]=(0,i.useState)(!1),[e,f]=(0,i.useState)(()=>"0"!==function(a){try{return window.localStorage.getItem(a)}catch{return null}}(eE)),[g,j]=(0,i.useState)(()=>{var a;let c,d=null;return(d&&eF.test(d)?d:null)??(a=(0,d4.requestedDoc)(),(c=a?.match(/(?:^|\/)(\d{4}-\d{2}-\d{2}-episode-\d+-[a-z0-9-]+)\/diagrams\/[^/]+$/))?c[1]:null)??b}),[k,l]=(0,i.useState)([]),[m,n]=(0,i.useState)(eI),[o,p]=(0,i.useState)(eJ),[q,r]=(0,i.useState)(null),[s,t]=(0,i.useState)([]),[u,v]=(0,i.useState)(null),[w,x]=(0,i.useState)(null),[y,z]=(0,i.useState)(()=>Date.now()),A=(0,i.useRef)(a),B=(0,i.useRef)(g),C=(0,i.useRef)(e);(0,i.useEffect)(()=>{A.current=a,B.current=g,C.current=e});let D=(0,i.useRef)(eI),E=(0,i.useRef)(null),F=(0,i.useRef)([]),G=(0,i.useRef)(!1),H=(0,i.useRef)([]),I=(0,i.useRef)(null),J=(0,i.useRef)(null),K=(0,i.useMemo)(()=>dz({recordings:!0,speech:!1}),[]),L=a=>{E.current=a,r(a)},M=(0,i.useRef)(async()=>{}),N=(0,i.useCallback)(async(a,b=0)=>{L(a.id),t(b=>b.filter(b=>b!==a.id)),a.steps?.length&&window.matchMedia("(max-width: 767px)").matches&&d(!1);let c=F.current.length;v(c?`${c} more of Mia's replies wait after this one.`:null);let e=await A.current.present(function(a,b,c="Mia"){let d=new Date(a.at),e=Number.isNaN(d.getTime())?`${c}'s reply`:`Reply at ${d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`,f=!a.unvoiced,g=(a,c)=>(function(a,b){if(!b)return;if(/^https?:\/\//.test(b))return b;let c=b.replace(/^\/?api\//,"");return`${a.endsWith("/")?a:`${a}/`}${c}`})(b,a||(f?c:null));return{settings:{namespace:"companion",name:e,author:c},steps:a.steps?.length?a.steps.map(({audio:b,...c},d)=>{let e=g(b,`api/replies/${a.id}/steps/${d}/audio`);return{...c,...e?{audio:e}:{}}}):[{say:a.text,...g(a.audio,`api/replies/${a.id}/audio`)?{audio:g(a.audio,`api/replies/${a.id}/audio`)}:{}}]}}(a,eD,"Mia"),{voice:K,origin:"Mia",from:b});if(E.current!==a.id||(L(null),G.current))return;if(!e){F.current=[];return}let f=F.current.shift();f&&!eH(D.current.state)?M.current(f):f&&F.current.unshift(f)},[K]);(0,i.useEffect)(()=>{M.current=N},[N]);let O=(0,i.useCallback)(a=>{let b=a.id;if(!C.current)return void t(a=>a.includes(b)?a:[...a,b]);if(eH(D.current.state)||E.current){t(a=>a.includes(b)?a:[...a,b]),F.current.some(a=>a.id===b)||F.current.push(a),v(eH(D.current.state)?`Mia replied at ${eG(a.at)}. Her voice waits until you have sent your take.`:`Mia replied again at ${eG(a.at)}. It plays when this one ends.`);return}M.current(a)},[]);(0,i.useEffect)(()=>{let a=function(a){let b=a.base.endsWith("/")?a.base:`${a.base}/`,c=a.fetch??((...a)=>fetch(...a)),d=a.everyMs??1e4,e=a.waitEveryMs??4e3,f=a.waitForMs??9e5,g={episode:null,items:[],presence:null,waiting:null,error:null},h=new Set,i=!1,j=null,k=null,l="",m=0,n=b=>{g={...g,...b},a.onChange?.(g)};async function o(){let d=g.episode;if(!d)return;let e=m;try{let j=await c(`${b}thread?episode=${encodeURIComponent(d)}`,{cache:"no-store"}),o=await j.json();if(e!==m)return;if(!o.success)return n({error:o.error??`HTTP ${j.status}`});let p=o.items??[],q=p.map(a=>"reply"===a.kind?`${a.id}:${+!!a.audio}:${a.feedback??""}`:`${a.take}:${a.text.length}`).join(",")+`|${o.presence?.state}`,r=p.filter(a=>"reply"===a.kind&&!h.has(a.id));for(let a of r)h.add(a.id);if((q!==l||g.error)&&(l=q,n({items:p,presence:o.presence??null,error:null})),i)for(let b of r)a.onReply?.(b);i=!0;let s=g.waiting;s&&(p.some(a=>"reply"===a.kind&&a.take===s.take)||Date.now()-s.since>f)&&(k&&clearInterval(k),k=null,n({waiting:null}))}catch(a){e===m&&n({error:a instanceof Error?a.message:String(a)})}}let p=()=>{"visible"===document.visibilityState&&o()};return"u">typeof document&&document.addEventListener("visibilitychange",p),{getSnapshot:()=>g,setEpisode(a){a!==g.episode&&(m+=1,h.clear(),i=!1,l="",k&&clearInterval(k),k=null,n({episode:a,items:[],presence:null,waiting:null,error:null}),a?(j&&clearInterval(j),j=setInterval(()=>{("u"<typeof document||"visible"===document.visibilityState)&&o()},d),o()):j&&(clearInterval(j),j=null))},refresh:o,waitFor(a){n({waiting:{take:a,since:Date.now()}}),k&&clearInterval(k),k=setInterval(()=>void o(),e),o()},async feedback(a,d){await c(`${b}replies/${a}/feedback`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({value:d})}),l="",await o()},destroy(){for(let a of(m+=1,[j,k]))a&&clearInterval(a);j=k=null,"u">typeof document&&document.removeEventListener("visibilitychange",p)}}}({base:eD,onChange:p,onReply:O}),b=function(a){let b=a.base.endsWith("/")?a.base:`${a.base}/`,c=a.fetch??((...a)=>fetch(...a)),d=a.partEveryMs??1e4,e=a.beatEveryMs??15e3,f=a.getUserMedia??(a=>navigator.mediaDevices.getUserMedia(a)),g=a.createRecorder??(a=>{let b,c,d,e,f,g,h,i;return c=(b=new(window.AudioContext??window.webkitAudioContext)).createMediaStreamSource(a),d=b.createScriptProcessor(4096,1,1),e=[],f=[],g=!1,h=null,i={mimeType:"audio/wav",ondataavailable:null,onstop:null,onerror:null,start(a=1e3){d.onaudioprocess=a=>{let b=a.inputBuffer.getChannelData(0),c=new Int16Array(b.length);for(let a=0;a<b.length;a++)c[a]=Math.max(-32768,Math.min(32767,Math.round(32767*b[a])));e.push(c),f.push(c)},c.connect(d),d.connect(b.destination),h=setInterval(()=>{if(!f.length)return;let a=g?[]:[dA(0x7fffffff,b.sampleRate)];g=!0,a.push(...f.map(a=>a.buffer)),f=[],i.ondataavailable?.({data:new Blob(a,{type:"audio/wav"})})},a)},stop(){h&&clearInterval(h),h=null;try{c.disconnect(),d.disconnect()}catch{}b.close().catch(()=>{}),i.whole=new Blob([dA(e.reduce((a,b)=>a+b.byteLength,0),b.sampleRate),...e.map(a=>a.buffer)],{type:"audio/wav"}),i.onstop?.()}}}),h={state:"idle",seconds:0,held:0,message:"",error:!1,stored:null,...!a.createRecorder?{unavailable:"this browser cannot record audio"}:{}},i=b=>{h={...h,...b},a.onChange?.(h)},j=null,k=null,l=[],m="",n="",o=null,p=0,q=null,r=null,s=null,t=null,u=!1,v=()=>p?Math.floor((Date.now()-p)/1e3):0,w=()=>(k?.mimeType||"audio/mp4").split(";")[0]||"audio/mp4",x=(a="")=>`episode=${encodeURIComponent(n)}${m?`&rec=${m}`:""}${o?`&context=${encodeURIComponent(o)}`:""}${a}`;function y(a){n&&c(`${b}recorder`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({episode:n,recording:a})}).catch(()=>{})}function z(a,d={}){m&&c(`${b}takes/diagnostic`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({rec:m,episode:n,kind:a,at:new Date().toISOString(),mime:k?.mimeType??null,visibility:"u">typeof document?document.visibilityState:"",agent:"u">typeof navigator?navigator.userAgent:"",source:"stateloom-canvas",...d}),keepalive:!0}).catch(()=>{})}function A(){for(let a of[r,s,t])a&&clearInterval(a);r=s=t=null}function B(){try{j?.getTracks().forEach(a=>a.stop())}catch{}j=null}async function C(){if(!m||u||!l.length)return;let a=new Blob(l,{type:w()});if(a.size<=h.held)return;u=!0;let d=m;try{let e=await c(`${b}takes/part?${x(`&offset=${h.held}`)}`,{method:"POST",headers:{"content-type":w()},body:a.slice(h.held)}),f=await e.json();d===m&&"number"==typeof f.bytes&&i({held:f.bytes})}catch{}finally{u=!1}}async function D(){let b;if("idle"!==h.state&&"retry"!==h.state)return;if(h.unavailable)return i({message:`Cannot record: ${h.unavailable}.`,error:!0});if(!(n=a.episode()??""))return i({message:"Choose the episode this take belongs to.",error:!0});let c=a.context?.()??null;o=c?JSON.stringify(c).slice(0,4e3):null,q=null,i({state:"starting",message:"",error:!1,held:0,seconds:0}),y(!0);try{b=await f({audio:!0})}catch(a){return y(!1),i({state:"idle",message:`Microphone refused: ${a instanceof Error?a.message:String(a)}`,error:!0})}if("starting"!==h.state)return void b.getTracks().forEach(a=>a.stop());j=b,l=[],m=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;try{k=g(b)}catch(a){return B(),y(!1),i({state:"idle",message:`This browser refused to record: ${a instanceof Error?a.message:String(a)}`,error:!0})}k.ondataavailable=a=>{a.data&&a.data.size&&l.push(a.data)},k.onerror=a=>{let b=v(),c=new Blob(l,{type:w()});if(z("recorder-error",{name:a?.error?.name??"",message:a?.error?.message??"",seconds:b,bytes:c.size,held:h.held}),A(),B(),y(!1),c.size)q=c,i({state:"retry",message:`The recorder stopped with an error after ${Math.floor(b/60)}:${String(b%60).padStart(2,"0")}. What it captured is kept: Send again.${h.held?` ${dB(h.held)} of it is already stored.`:""}`,error:!0});else i({state:"idle",message:"The recorder stopped before it captured anything. Nothing was sent.",error:!0})},k.start(1e3),p=Date.now(),r=setInterval(()=>void C(),d),s=setInterval(()=>y(!0),e),t=setInterval(()=>i({seconds:v()}),500),i({state:"recording",seconds:0,message:""})}async function E(d){i({state:"sending",message:`Sending ${dB(d.size)}, then transcribing and storing…`,error:!1});try{let e=await c(`${b}takes?${x()}`,{method:"POST",headers:{"content-type":(d.type||"audio/mp4").split(";")[0]},body:d}),f=await e.json();if(!f.success||!f.take)throw Error(f.error||`HTTP ${e.status}`);q=null,m="";let g=f.presence??{state:f.listening?"listening":"away"},h=f.transcriptError?` Transcription failed, so no session wakes yet: ${f.transcriptError}`:({listening:" The session listening there will hear it.",answering:" Mia is answering an earlier take; she hears this one next.",answered:" The session hears it as soon as it listens again."})[g.state]??" No session is listening yet; the take waits, and her reply comes here when one answers.";i({state:"idle",seconds:0,held:0,message:`Take ${f.take} is in the episode.${h}`,error:!!f.transcriptError,stored:{take:f.take,english:f.english??"",transcriptError:f.transcriptError,presence:g}}),f.transcriptError||a.onStored?.(f.take)}catch(a){q=d,z("send-failed",{message:a instanceof Error?a.message:String(a),bytes:d.size,held:h.held}),i({state:"retry",message:`Not stored: ${a instanceof Error?a.message:String(a)}. Your recording is kept — Send again.${h.held?` ${dB(h.held)} of it is already stored, and becomes a take by itself if you leave.`:""}`,error:!0})}}async function F(){if("recording"!==h.state)return;let a=v();A(),y(!1),i({state:"sending",seconds:a});let b=await new Promise(a=>{let b=!1,c=()=>{b||(b=!0,a(k?.whole??new Blob(l,{type:w()})))},d=setTimeout(c,3e3);if(!k)return c();k.onstop=()=>{clearTimeout(d),c()};try{k.stop()}catch{clearTimeout(d),c()}});if(B(),!b.size)return z("empty-at-stop",{seconds:a,held:h.held}),i({state:"idle",message:h.held?`The recorder handed back nothing at Stop, but ${dB(h.held)} is stored; it becomes a take within a few minutes.`:"Nothing was recorded. Try again.",error:!0});await E(b)}async function G(){"retry"===h.state&&q&&await E(q)}return{getSnapshot:()=>h,press:async()=>"recording"===h.state?F():"retry"===h.state&&q?G():D(),start:D,stop:F,resend:G,destroy(){A(),("recording"===h.state||"starting"===h.state)&&y(!1);try{k?.stop()}catch{}B()}}}({base:eD,episode:()=>B.current,context:()=>{let a=A.current.shown,b=a?{...a.title||a.step.title?{title:[a.title,a.step.title].filter(Boolean).join(" · ")}:{},say:a.step.say.slice(0,400),...null!==a.index&&null!==a.count?{index:a.index,count:a.count}:{},...a.origin?{by:a.origin}:{}}:null;return function(a,b={}){if(!a?.doc)return null;let c={stage:a.stage,doc:a.doc,kind:a.kind,system:a.system,focus:a.focus??void 0,visible:a.visible,tour:a.tour,who:a.who,at:new Date().toISOString(),...b};for(let a of Object.keys(c))(void 0===c[a]||null===c[a])&&delete c[a];return c}(A.current.lastReport(),{...H.current.length?{marks:H.current}:{},...a?.step.spotlight?.length?{spotlight:a.step.spotlight}:{},...b?{step:b}:{}})},onChange:a=>{let b=D.current.state;if(D.current=a,n(a),!eH(b)||eH(a.state)||(G.current=!1,!C.current||E.current))return;let c=F.current.shift();c?M.current(c):v(null)},onStored:b=>a.waitFor(b)});return J.current=a,I.current=b,D.current=b.getSnapshot(),n(b.getSnapshot()),()=>{b.destroy(),a.destroy(),J.current=null,I.current=null}},[O]),(0,i.useEffect)(()=>{J.current?.setEpisode(g)},[g]),(0,i.useEffect)(()=>{let a=!0;return fetch(`${eD}health`,{cache:"no-store"}).then(a=>a.json()).then(b=>{if(a){if(!b.success)return x(`The companion does not answer: ${b.error??"no reason given"}.`);x(null),b.defaultEpisode&&j(a=>a??b.defaultEpisode??null)}}).catch(b=>a&&x(`The companion does not answer: ${b instanceof Error?b.message:String(b)}.`)),()=>{a=!1}},[]),(0,i.useEffect)(()=>{if(!c||k.length)return;let a=!0;return fetch(`${eD}episodes`,{cache:"no-store"}).then(a=>a.json()).then(b=>{a&&b.success&&b.episodes&&l(b.episodes)}).catch(()=>{}),()=>{a=!1}},[c,k.length]);let P=(0,i.useRef)(null),Q=(0,i.useCallback)(async(a=!1)=>{let b=A.current.lastReport()?.doc??null;if(a||b!==P.current){if(P.current=b,!b){H.current=[];return}try{var c,d;let a=await fetch(`/api/marks?doc=${encodeURIComponent(b)}`,{cache:"no-store"}),e=await a.json();H.current=(c=function(a,b=""){let c=a&&"object"==typeof a?a:{},d=Array.isArray(c.marks)?c.marks.map(bn).filter(a=>null!==a):[];return{doc:bk(c.doc)||b,marks:d}}(e,b).marks,d="agent",c.filter(a=>"open"===a.status&&a.author.role!==d||"answered"===a.status&&a.author.role===d)).map(a=>a.id)}catch{H.current=[]}}},[]);(0,i.useEffect)(()=>{Q(!0);let a=A.current.onMarks(()=>void Q(!0)),b=setInterval(()=>void Q(),3e3);return()=>{a(),clearInterval(b)}},[Q]),(0,i.useEffect)(()=>{if(!o.waiting)return;let a=setInterval(()=>z(Date.now()),1e3);return()=>clearInterval(a)},[o.waiting]);let R=(0,i.useCallback)(()=>{let a=I.current;a&&(!eH(D.current.state)&&"retry"!==D.current.state&&E.current&&(G.current=!0,A.current.stop()),a.press())},[]),S=(0,i.useCallback)((a,b)=>{let c=J.current?.getSnapshot().items.find(b=>"reply"===b.kind&&b.id===a);if(c){if(eH(D.current.state))return void v(`Send your take first. Then press ▶ to hear Mia.`);F.current=[],G.current=!1,M.current(c,b)}},[]),T=(0,i.useCallback)(()=>{F.current=[],G.current=!1,A.current.stop()},[]),U=o.waiting?{take:o.waiting.take,seconds:Math.max(0,Math.floor((y-o.waiting.since)/1e3))}:null;return(0,h.jsx)("div",{className:"stage-talk-host",children:(0,h.jsx)(ci,{open:c,onOpenChange:a=>{d(a),a&&Q(!0)},who:"Mia",episode:g,episodes:k,onEpisode:a=>{eF.test(a)&&a!==g&&(F.current=[],t([]),v(null),j(a))},presence:o.presence,recorder:m,onRecord:R,items:o.items,unheard:s,playing:q,playingStep:q&&a.shown?.origin==="Mia"?a.shown.index:null,onPlay:S,onStop:T,onFeedback:(a,b)=>{J.current?.feedback(a,b).catch(a=>x(`Your thumb was not kept: ${a instanceof Error?a.message:String(a)}.`))},autoplay:e,onAutoplay:a=>{f(a);try{window.localStorage.setItem(eE,a?"1":"0")}catch{}a||(F.current=[])},waiting:U,notice:u,error:w??o.error})})}let eL=(0,i.createContext)(null);function eM(){return(0,i.useContext)(eL)}function eN(a,b){try{window.localStorage.setItem(a,b)}catch{}}function eO({children:a}){var b;let c,d,e,f,g,j,k,l,[m,n]=(0,i.useState)({bridgeUrl:null,stage:bf,companion:!1,companionEpisode:null});(0,i.useEffect)(()=>{let a=!0;return ed().then(b=>{if(!a)return;let c=null,d=bh(c)?c:bh(b.stage)?b.stage:bf;n({bridgeUrl:b.bridgeUrl,stage:d,companion:b.companion,companionEpisode:b.companionEpisode})}),()=>{a=!1}},[]);let[o,p]=(0,i.useState)(()=>!1),[q,r]=(0,i.useState)(()=>""),s=(0,i.useMemo)(()=>o?dz():null,[o]),t=(0,i.useMemo)(()=>null,[]),[u,v]=(0,i.useState)(null),w=(0,i.useRef)(new Set),x=(0,i.useCallback)(a=>{var b;if(!a)return void v(null);let{step:c}=a,d=(0,d4.requestedDoc)();if(a.caught,c.doc&&c.doc!==d)eA({doc:c.doc,system:c.system??void 0,focus:c.focus??null});else if(c.focus)if(c.system&&null!==c.system&&d)eA({doc:d,system:c.system,focus:c.focus});else{let a;b=c.focus,(a=new URL(window.location.href)).searchParams.set("focus",b),window.history.replaceState(window.history.state,"",a),window.dispatchEvent(new Event(ew))}v({doc:c.doc,focus:c.focus,spotlight:c.spotlight,region:c.region,nonce:a.nonce})},[]),y=(b={url:m.bridgeUrl??"",stage:m.stage,name:"web-stage",voice:s,enabled:!!m.bridgeUrl,onShow:x,onMarks:a=>{for(let b of[...w.current])b(a)}},(c=(0,i.useRef)({onShow:b.onShow,onMarks:b.onMarks})).current={onShow:b.onShow,onMarks:b.onMarks},d=(0,i.useRef)(null),e=`${b.url}\u0000${b.stage??""}\u0000${b.token??""}`,f=(0,i.useRef)(e),(null===d.current||f.current!==e)&&(f.current=e,d.current=function(a){let b,c=bh(a.stage)?a.stage:bf,d=a.setTimer??((a,b)=>setTimeout(a,b)),e=a.clearTimer??(a=>clearTimeout(a)),f=a.gapMs??900,g=a.client??dw({url:a.url,role:a.role??"web",docId:`stage:${c}`,name:a.name??"web-stage",token:a.token,autoResync:!1}),h=a.voice??null,i=a=>a&&void 0!==b?b:h,j=null,k=null,l=a=>{let b=k;k=null,b?.(a)},m=null,n=null,o=[],p=[],q=0,r=!1,s=!1,t=0,u=null,v=0,w=!1,x=!1,y=!1,z=!1,A=!1,B={status:g.status,stage:c,shown:m,tour:n,index:q,playing:r,speaking:s,ownVoice:!1},C=new Set;function D(){for(let a of(B={status:g.status,stage:c,shown:m,tour:n,index:q,playing:r,speaking:s,ownVoice:!!n&&void 0!==b},[...C]))a()}function E(){v+=1,u&&e(u),u=null,s&&j?.cancel(),s=!1,j=null}function F(a,b,c=b){E();let e=++v,g=()=>{e!==v||(s&&(s=!1,D()),b&&r&&(u=d(()=>{u=null,e===v&&r&&L()},h?f:0)))},h=i(c);if(h)s=!0,j=h,D(),h.speak(a).then(g,g);else{let c;b&&(u=d(()=>{u=null,g()},"number"==typeof(c=a.holdMs)&&Number.isFinite(c)&&a.holdMs>=0?a.holdMs:Math.min(2e4,Math.max(2500,1200+400*`${a.title??""} ${a.say??""}`.trim().split(/\s+/).filter(Boolean).length))))}}function G(b,c){t+=1,E(),m=b?{...b,nonce:t,...A?{caught:!0}:{}}:null,D(),a.onShow?.(m);let d=!!m&&null!==m.index;m&&(i(d)||c)&&F(m.step,c,d)}function H(a){if(!n)return null;let b=n.def.steps[a];if(!b)return null;let c=b.doc??o[a],d=b.system??p[a];return{step:{...b,...c?{doc:c}:{},...d?{system:d}:{}},index:a,count:n.def.steps.length,title:n.def.settings?.name,origin:n.origin,tourPath:n.path}}function I(a,c,d){var e;let f,g;l(!1),b=d;let h=Array.isArray(a.tour?.steps)?a.tour.steps:[];e=(n={def:{...a.tour,steps:h},path:a.path,origin:a.origin}).def,g=void 0,o=e.steps.map(a=>g=a.doc??g),p=h.map(a=>f=a.system??f),q=Math.min(Math.max(0,a.from??0),Math.max(0,h.length-1)),w=!1,r=c&&h.length>0,G(H(q),r)}function J(a){r=!1,G({step:a.step,index:null,count:null,title:a.title,origin:a.origin,tourPath:a.tour},!1)}function K(a){if(!n)return;let b=n.def.steps.length-1;b<0||(w=!1,G(H(q=Math.min(Math.max(0,Math.floor(a)),b)),r))}function L(){if(n){if(q>=n.def.steps.length-1){let a=r;w=r||w,r=!1,E(),D(),a&&l(!0);return}K(q+1)}}function M(){n&&q>0&&K(q-1)}function N(){n&&n.def.steps.length&&(r=!0,w&&(w=!1,q=0),m?.index!==q||m.caught?G(H(q),!0):(D(),F(m.step,!0)))}function O(){r=!1,E(),D()}function P(){l(!1),b=void 0,w=!1,n=null,o=[],p=[],q=0,r=!1,G(null,!1)}function Q(){z||(z=!0,g.joinStage(c).then(({state:a})=>{z=!1,y=!0,m||n||function(a){A=!0;try{a.tour&&I(a.tour,!1),a.step&&J(a.step)}finally{A=!1}}(a),D()}).catch(()=>{z=!1,D()}))}return g.on("stage-step",a=>{a?.stage===c&&a.step&&J(a)}),g.on("stage-load",a=>{a?.stage===c&&a.tour&&I(a,!1!==a.autoplay)}),g.on("stage-control",a=>{a?.stage===c&&function(a){switch(a.action){case"play":return N();case"pause":return O();case"next":return L();case"prev":return M();case"goto":return K(a.index??0);case"stop":return P()}}(a)}),g.on("marks",b=>a.onMarks?.(b)),g.on("status",a=>{"disconnected"===a||"error"===a?y=!1:"connected"===a&&x&&!y&&Q(),D()}),{getSnapshot:()=>B,subscribe:a=>(C.add(a),()=>{C.delete(a)}),connect(){x=!0,Q()},disconnect(){x=!1,E(),g.leaveStage(c),g.disconnect()},play:N,pause:O,next:L,prev:M,goto:K,stop:P,dismiss:function(){if(m){if(null===m.index&&n)return void G(H(q),!1);null===m.index?G(null,!1):P()}},setVoice(a){void 0===b&&E(),h=a,D()},present:(a,b={})=>Array.isArray(a?.steps)&&a.steps.length?new Promise(d=>{I({stage:c,tour:a,from:b.from??0,autoplay:!1!==b.autoplay,origin:b.origin??"page"},!1!==b.autoplay,b.voice),k=d}):Promise.resolve(!1),sendContext(a){g.emitContext({...a,stage:c,...n?{tour:{path:n.path,title:n.def.settings?.name,index:q,count:n.def.steps.length,playing:r}}:{}})},sendMarks(a){g.emitMarks({...a,stage:c}).catch(()=>{})}}}({...b,voice:b.voice??null,onShow:a=>c.current.onShow?.(a),onMarks:a=>c.current.onMarks?.(a)})),g=d.current,j=(0,i.useSyncExternalStore)(g.subscribe,g.getSnapshot,g.getSnapshot),k=!1!==b.enabled&&!!b.url,(0,i.useEffect)(()=>{if(k)return g.connect(),()=>g.disconnect()},[g,k]),l=b.voice??null,(0,i.useEffect)(()=>{g.setVoice(l)},[g,l]),{...j,play:g.play,pause:g.pause,next:g.next,prev:g.prev,goto:g.goto,stop:g.stop,dismiss:g.dismiss,sendContext:g.sendContext,sendMarks:g.sendMarks,present:g.present}),z=(0,i.useRef)(null),A=(0,i.useRef)(null),B=y.sendContext,C=(0,i.useCallback)(a=>{z.current={...a,stage:m.stage,who:q||void 0,at:new Date().toISOString()},A.current&&clearTimeout(A.current),A.current=setTimeout(()=>B({...a,who:q||void 0}),400)},[m.stage,q,B]);(0,i.useEffect)(()=>()=>{A.current&&clearTimeout(A.current)},[]),(0,i.useEffect)(()=>{z.current&&B({...z.current,who:q||void 0})},[y.index,y.playing,y.tour,B,q]);let[D,E]=(0,i.useState)(0),F=!!y.shown;(0,i.useEffect)(()=>{let a=document.documentElement,b=F?document.querySelector(".stage-caption-host .slc-stage-caption"):null;if(!b||"u"<typeof ResizeObserver)return void a.style.removeProperty("--stage-caption-h");let c=()=>a.style.setProperty("--stage-caption-h",`${Math.ceil(b.getBoundingClientRect().height)+12}px`),d=new ResizeObserver(c);return d.observe(b),c(),()=>{d.disconnect(),a.style.removeProperty("--stage-caption-h")}},[F]);let G=(0,i.useMemo)(()=>({stage:m.stage,connected:"connected"===y.status,lit:u,author:q,setAuthor:a=>{r(a),eN("stateloom.author",a)},listener:t,answerNonce:D,report:C,lastReport:()=>z.current,sendMarks:y.sendMarks,onMarks:a=>(w.current.add(a),()=>{w.current.delete(a)}),shown:y.shown,present:y.present,pause:y.pause,stop:y.stop}),[m.stage,y.status,y.shown,y.sendMarks,y.present,y.pause,y.stop,u,q,t,D,C]);return(0,h.jsxs)(eL.Provider,{value:G,children:[a,y.shown&&(0,h.jsx)("div",{className:"stage-caption-host",children:(0,h.jsx)(b6,{shown:y.shown,playing:y.playing,speaking:y.speaking,voice:y.ownVoice?void 0:o,onToggleVoice:()=>{let a=!o;p(a),eN("stateloom.stage.voice",a?"1":"0")},onPlay:y.play,onPause:y.pause,onNext:y.next,onPrev:y.prev,onGoto:y.goto,onClose:y.dismiss,onAnswer:()=>E(a=>a+1)})}),m.companion&&(0,h.jsx)(eK,{stage:G,defaultEpisode:m.companionEpisode})]})}let eP="flex h-9 min-w-9 items-center justify-center gap-1 rounded-lg border border-gray-700 bg-gray-900/90 px-2 text-sm text-gray-200 shadow-lg backdrop-blur hover:bg-gray-800";async function eQ(a,b){let c=await fetch(`/api/marks?doc=${encodeURIComponent(a)}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(b)}),d=await c.json().catch(()=>({}));if(!c.ok)throw Error(d?.error??`the marks could not be written (${c.status})`);return d}function eR({docPath:a,kind:b,viewport:c,setViewport:d,boxes:e,boardRef:f,focus:g=null,level:j,onReveal:k}){let l=eM(),[m,n]=(0,i.useState)([]),[o,p]=(0,i.useState)(!1),[q,r]=(0,i.useState)(null),[s,t]=(0,i.useState)(null),[u,v]=(0,i.useState)(!1),[w,x]=(0,i.useState)(!1),[y,z]=(0,i.useState)(null),[A,B]=(0,i.useState)(!1),C=(0,i.useCallback)(()=>{a&&fetch(`/api/marks?doc=${encodeURIComponent(a)}`,{cache:"no-store"}).then(a=>a.ok?a.json():null).then(a=>a&&Array.isArray(a.marks)&&n(a.marks)).catch(()=>{})},[a]);(0,i.useEffect)(()=>(n([]),t(null),r(null),C(),window.addEventListener("focus",C),()=>window.removeEventListener("focus",C)),[C]),(0,i.useEffect)(()=>l?.onMarks(b=>{a&&b.docId===a&&Array.isArray(b.marks)&&n(b.marks)}),[l,a]);let D=async b=>{if(!a)return!1;x(!0),z(null);try{let c=await eQ(a,b);return n(c.marks),l?.sendMarks({docId:a,marks:c.marks,change:c.change}),!0}catch(a){return z(a instanceof Error?a.message:String(a)),!1}finally{x(!1)}},E=l?.lit??null,F=E&&(!E.doc||E.doc===a)?E:null,G=F?.spotlight,H=F?.region??null,I=(0,i.useRef)(-1),J=(0,i.useRef)(-1),K=(0,i.useRef)(null),L=(0,i.useMemo)(()=>G?.length?br(e,G):[],[e,G]);(0,i.useEffect)(()=>{if(!F||I.current===F.nonce)return;let a=[...L,...H?[H]:[]];if(!a.length){G?.length&&J.current!==F.nonce&&(J.current=F.nonce,k?.(G));return}I.current=F.nonce;let b=()=>{let b=f.current?.getBoundingClientRect();if(!b?.width)return;let c=document.querySelector(".stage-caption-host .slc-stage-caption")?.getBoundingClientRect(),e=c&&c.top<b.bottom?Math.max(0,b.bottom-c.top+8):0,g=Math.max(.4*b.height,b.height-e);d(S(a,b.width,g,{padding:48,maxScale:1}))};b(),K.current&&clearTimeout(K.current),K.current=setTimeout(b,520)},[F,L,H,G,f,d,k]),(0,i.useEffect)(()=>()=>{K.current&&clearTimeout(K.current)},[]);let M=(0,i.useRef)(l?.answerNonce??0);(0,i.useEffect)(()=>{if(!l||l.answerNonce===M.current)return;M.current=l.answerNonce;let a=G?.length?[...G]:F?.focus?[F.focus]:g?[g]:[];v(!1),t(null),r({elements:a,region:H??void 0,listen:!!l.listener})},[l,G,F,g,H]);let N=l?.report;if((0,i.useEffect)(()=>{if(!N||!a)return;let d=f.current?.getBoundingClientRect(),e=O(c,{x:0,y:0}),h=d?O(c,{x:d.width,y:d.height}):e;N({doc:a,kind:b,system:void 0,focus:g,...d?.width?{visible:{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(h.x-e.x),height:Math.round(h.y-e.y)}}:{}})},[N,a,b,g,c,f]),!a)return null;let P=m.filter(a=>"open"===a.status&&"person"===a.author.role).length,Q=m.filter(a=>"open"===a.status&&"agent"===a.author.role).length,R=m.find(a=>a.id===s)??null;return(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(bT,{viewport:c,boxes:e,spotlight:G,region:H,marks:m,selectedMark:s,onSelectMark:a=>{r(null),v(!1),t(b=>b===a?null:a)},marking:o,onDraft:a=>{p(!1),t(null),v(!1),r(a)},draft:q}),(0,h.jsxs)("div",{className:"stage-board-controls",children:[(0,h.jsxs)("button",{type:"button",className:`${eP} ${o?"!border-amber-400 !text-amber-300":""}`,"aria-pressed":o,onClick:()=>{r(null),p(a=>!a)},title:o?"Marking: tap an element, or drag around several. Tap ✎ again to stop.":"Mark something for the agent — tap an element or drag around several",children:[(0,h.jsx)(b5,{}),o&&(0,h.jsx)("span",{className:"text-xs",children:"marking"})]}),(0,h.jsxs)("button",{type:"button",className:eP,"aria-expanded":u,onClick:()=>{r(null),t(null),v(a=>!a)},title:"Marks on this drawing",children:[(0,h.jsx)(bY,{}),P+Q>0&&(0,h.jsx)("span",{className:"text-xs text-amber-300",children:P+Q})]})]}),o&&!q&&(0,h.jsx)("div",{className:"stage-board-hint",role:"status",children:"Tap an element, or drag around several, to say something about it."}),(q||R||u)&&(0,h.jsx)("div",{className:"stage-board-card",children:q?(0,h.jsx)(ca,{elements:q.elements,region:q.region,author:l?.author??"",onAuthorChange:l?.setAuthor,listener:l?.listener,listenAtOnce:!!q.listen,busy:w,error:y,onCancel:()=>{r(null),z(null)},onSubmit:async({text:a,kind:b,author:c})=>{await D({action:"add",mark:{text:a,kind:b,elements:q.elements,region:q.region,level:j,author:{name:c||"someone"}}})&&r(null)}},`${q.elements.join(",")}|${q.region?JSON.stringify(q.region):""}`):R?(0,h.jsx)(cb,{mark:R,number:m.indexOf(R)+1,listener:l?.listener,busy:w,error:y,onClose:()=>t(null),onReply:a=>void D({action:"reply",id:R.id,text:a,author:{name:l?.author||"someone"}}),onResolve:()=>void D({action:"resolve",id:R.id}),onReopen:()=>void D({action:"reopen",id:R.id}),onRemove:async()=>{await D({action:"remove",id:R.id})&&t(null)}}):(0,h.jsx)(cc,{marks:m,selected:s,onSelect:a=>{v(!1),t(a)},onCopy:()=>{var b,c;let d,e;if(!a)return;let f=(b=l?.lastReport()??null,d=(c=[{doc:a,marks:m.filter(a=>"resolved"!==a.status)}]).reduce((a,b)=>a+b.marks.length,0),e=function(a){if(!a||!a.doc)return"No canvas has said what it is showing.";let b=[`${a.who?`${a.who} is`:"The canvas is"} on ${bs(a.doc)}${a.kind?` (${a.kind})`:""}`];a.system&&b.push(`as a member of ${bs(a.system)}`),a.focus&&b.push(`with ${a.focus} in hand`);let c=b.join(", ")+".";return a.tour&&(c+=` Tour ${a.tour.title?`'${a.tour.title}' `:""}at step ${a.tour.index+1} of ${a.tour.count}, ${a.tour.playing?"playing":"paused"}.`),a.at&&(c+=` (reported ${a.at})`),c}(b),d?`${e}
|
|
11
|
+
${a}`)}l(!0)};return(0,h.jsxs)("div",{className:"flex flex-col gap-1.5 px-2 py-1.5 bg-gray-900 border-b border-gray-800 md:flex-row md:flex-wrap md:items-center md:px-3",children:[(0,h.jsxs)("div",{className:"toolbar-ident",children:[(0,h.jsx)("input",{ref:A,type:"file",accept:".json,.smdf.json",onChange:a=>{let b=a.target.files?.[0];if(!b)return;let c=new FileReader;c.onload=a=>{e(a.target?.result,b.name)},c.readAsText(b),a.target.value=""},className:"hidden"}),(0,h.jsxs)("span",{className:"text-xs text-gray-400 mr-1 truncate max-w-[50vw] md:max-w-none",children:[b??"untitled.smdf.json",d&&(0,h.jsx)("span",{className:"text-yellow-500 ml-0.5",children:"●"})]}),(0,h.jsx)(d5,{}),"synced"===u&&(0,h.jsx)("span",{className:"text-[10px] text-emerald-500",title:"In sync with disk",children:"⌁ synced"}),"remote-changed"===u&&(0,h.jsx)("span",{className:"text-[10px] text-amber-400",title:v??"",children:"↻ remote changed"}),"error"===u&&(0,h.jsx)("span",{className:"text-[10px] text-red-400",title:v??"",children:"⚠ disk error"}),"idle"===u&&(0,h.jsx)("span",{className:"text-[10px] text-gray-600",title:v??"No file bound",children:"○ no disk"}),(0,h.jsx)(d6,{}),(0,h.jsx)("div",{className:"flex-1"})]}),(0,h.jsxs)("div",{className:"toolbar-strip",children:[(0,h.jsx)("button",{onClick:q,disabled:0===s.length,className:"toolbar-btn disabled:opacity-30",title:"Undo (Ctrl+Z)",children:"↩"}),(0,h.jsx)("button",{onClick:r,disabled:0===t.length,className:"toolbar-btn disabled:opacity-30",title:"Redo (Ctrl+Y)",children:"↪"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:p,className:"toolbar-btn",title:"Arrange states into layers (auto-layout)",children:"⤢ Arrange"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:()=>o("select"===n?"transition":"select"),className:`toolbar-btn ${"transition"===n?"!bg-amber-700 !text-white":""}`,title:"transition"===n?"Exit draw mode (Esc)":"Draw transition mode",children:"transition"===n?"✏️ Drawing":"↗ Draw"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:()=>A.current?.click(),className:"toolbar-btn",title:"Open local .smdf.json (browser)",children:"📂"}),(0,h.jsx)("button",{onClick:P,disabled:F,className:"toolbar-btn disabled:opacity-40",title:"Save to disk (STATELOOM_PROJECT_FILE)",children:"💾 Disk"}),(0,h.jsx)("button",{onClick:R,className:"toolbar-btn",title:"Reload from disk",children:"🔄"}),(0,h.jsx)("button",{onClick:()=>{let a=new Blob([f()],{type:"application/json"}),c=URL.createObjectURL(a),d=document.createElement("a");d.href=c,d.download=b??"statemachine.smdf.json",d.click(),URL.revokeObjectURL(c)},className:"toolbar-btn",title:"Download as file",children:"📥"}),(0,h.jsx)("select",{value:H,onChange:a=>{I(a.target.value),O(null),M(null)},className:"bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 px-1 py-0.5",title:"Export format",children:dS.map(a=>(0,h.jsx)("option",{value:a,children:dT[a]},a))}),(0,h.jsx)("button",{onClick:Q,disabled:J,className:`toolbar-btn disabled:opacity-40 ${L?"!text-red-400":""}`,title:L??`Export the board as ${dT[H]}`,children:J?"…":"🖼 Export"}),N&&!L&&(0,h.jsxs)("span",{className:"text-[10px] text-emerald-500 truncate max-w-[40vw] md:max-w-[16rem]",title:N,children:["⤓ ",N]}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),B?(0,h.jsxs)("div",{className:"flex items-center gap-1",children:[(0,h.jsx)("input",{autoFocus:!0,className:"bg-gray-800 border border-gray-700 rounded px-2 py-0.5 text-xs text-gray-200 w-32 md:w-24",placeholder:"State name...",value:D,onChange:a=>E(a.target.value),onKeyDown:a=>{"Enter"===a.key&&S(),"Escape"===a.key&&C(!1)}}),(0,h.jsx)("button",{onClick:S,className:"toolbar-btn-sm",children:"✓"}),(0,h.jsx)("button",{onClick:()=>C(!1),className:"toolbar-btn-sm",children:"✕"})]}):(0,h.jsx)("button",{onClick:()=>C(!0),className:"toolbar-btn",children:"+State"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:()=>j(),className:"toolbar-btn",children:"✓ Validate"}),(0,h.jsxs)("select",{value:T,onChange:a=>U(a.target.value),className:"bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 px-1 py-0.5",children:[(0,h.jsx)("option",{value:"python",children:"Python"}),(0,h.jsx)("option",{value:"typescript",children:"TypeScript"})]}),(0,h.jsx)("button",{onClick:W,className:"toolbar-btn",children:"⚡ Generate"}),(0,h.jsx)("button",{onClick:V,className:"toolbar-btn",title:"Generate RISE rispec markdown",children:"📜 RISE"}),(0,h.jsxs)("button",{onClick:()=>l(!k),className:`toolbar-btn ${k?"text-blue-400":""}`,children:["</>"," Code"]})]})]})}function d8(){let a=dM(a=>a.generatedCode),b=dM(a=>a.showCodePreview),c=dM(a=>a.setShowCodePreview);return b?(0,h.jsx)("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/60 p-2 md:p-0",children:(0,h.jsxs)("div",{className:"bg-gray-900 border border-gray-700 rounded-lg shadow-xl w-full max-h-[85dvh] md:w-[80%] md:max-w-3xl md:max-h-[80dvh] flex flex-col",children:[(0,h.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-800",children:[(0,h.jsx)("h3",{className:"text-sm font-semibold text-gray-300",children:"Generated Definition (JSON)"}),(0,h.jsx)("button",{onClick:()=>c(!1),className:"text-gray-500 hover:text-gray-300 text-lg min-h-11 min-w-11 md:min-h-0 md:min-w-0","aria-label":"Close preview",children:"✕"})]}),(0,h.jsx)("pre",{className:"flex-1 overflow-auto overscroll-contain p-4 text-[11px] leading-relaxed text-green-400 font-mono md:text-sm",children:a??"No code generated yet"}),(0,h.jsx)("div",{className:"flex justify-end px-4 py-2 border-t border-gray-800",children:(0,h.jsx)("button",{onClick:()=>{a&&navigator.clipboard.writeText(a)},className:"text-xs bg-gray-700 hover:bg-gray-600 text-gray-300 px-4 py-3 rounded md:px-3 md:py-1",children:"Copy to Clipboard"})})]})}):null}function d9(){let a=dM(a=>a.applyRemote),b=dM(a=>a.setRemoteStatus),c=dM(a=>a.setRemoteMtime),d=(0,d4.useRequestedDoc)();return(0,i.useEffect)(()=>{let e=!1,f=(0,d4.docQuery)(d);async function g(){try{let a=await fetch(`/api/file${f}`,{cache:"no-store"});if(!a.ok)return null;return await a.json()}catch{return null}}(async()=>{let c=await g();e||(c?.path&&dM.getState().setDocPath(c.path),c?.exists&&c.content?a(c.content,c.mtime,c.path.split("/").pop()):b("idle",c?`No file at ${c.path}`:null))})();let h=new EventSource(`/api/watch${f}`);return h.addEventListener("hello",a=>{try{let b=JSON.parse(a.data);"number"==typeof b?.mtime&&c(b.mtime)}catch{}}),h.addEventListener("change",async d=>{let e=0;try{e=JSON.parse(d.data)?.mtime??0}catch{}if(e<=(dM.getState().remoteMtime??0))return;let f=await g();f?.exists&&f.content&&(dM.getState().dirty?(b("remote-changed",`Disk changed at ${new Date(f.mtime).toLocaleTimeString()} — local has unsaved edits`),c(f.mtime)):a(f.content,f.mtime,f.path.split("/").pop()))}),h.addEventListener("error",()=>{b("error","Watch stream disconnected")}),()=>{e=!0,h.close()}},[a,b,c,d]),null}function ea({url:a}){let b=(0,d4.useRequestedDoc)();return(0,i.useEffect)(()=>{if(!a)return;let c=!1,d=null,e=null,f=null,g=null;return(async()=>{let h="";try{let a=await fetch(`/api/file${(0,d4.docQuery)(b)}`,{cache:"no-store"});a.ok&&(h=(await a.json())?.path??"")}catch{}c||(h&&dM.getState().setDocPath(h),(d=dy({url:a,role:"web",docId:h,name:"web-designer",onFull:a=>{dM.getState().applyRemote(JSON.stringify({stateMachine:a.def}),a.mtime??Date.now(),h&&h.split("/").pop()||void 0),g=a.def},onPatch:a=>{dM.getState().applyRemoteOps(a.ops,a.mtime??Date.now(),a.seq),g=dM.getState().definition},onPresence:a=>{dM.getState().setPresence(a)}})).connect(),e=dM.subscribe((a,b)=>{a.definition===b.definition||a._applyingRemote||(f&&clearTimeout(f),f=setTimeout(()=>{var a,b;let c,e;if(!d||"connected"!==d.getSnapshot().status)return;let f=dM.getState().definition;if(null===g){d.emitFull(f),g=f;return}let h=(a=g,b=f,c=a??{settings:{namespace:"",asynchronous:!1},events:[],state:{name:b.state.name,states:[]}},function(a,b,c){let d={},e=!1,f=new Set([...Object.keys(a.settings),...Object.keys(b.settings)]),g=a.settings,h=b.settings;for(let a of f)q(g[a],h[a])||void 0===h[a]||(d[a]=h[a],e=!0);void 0!==a.settings.notes&&void 0===b.settings.notes&&(d.notes="",e=!0),e&&c.push({op:"settings.update",patch:d})}(c,b,e=[]),function(a,b,c){let d=a.events,e=b.events,f=Math.min(d.length,e.length);for(let a=0;a<f;a++)!function(a,b,c,d){let e={},f=!1;for(let a of["name","file","feeder","description","timers"])q(b[a],c[a])||void 0===c[a]||(e[a]=c[a],f=!0);f&&d.push({op:"eventSource.update",index:a,patch:e});let g=b.events??[],h=c.events??[],i=new Set(h.map(a=>a.id));for(let a of g)i.has(a.id)||d.push({op:"event.remove",id:a.id});let j=g.filter(a=>i.has(a.id)),k=0;for(;k<h.length;){let b=h[k];k<j.length&&j[k].id===b.id?(function(a,b,c){let d={},e=!1;for(let c of["name","description","preAction","postAction"])q(a[c],b[c])||void 0===b[c]||(d[c]=b[c],e=!0);e&&c.push({op:"event.update",id:b.id,patch:d})}(j[k],b,d),function(a,b,c,d){let e=Math.min(b.length,c.length);for(let f=0;f<e;f++)if(!q(b[f],c[f])){let e={};b[f].name!==c[f].name&&(e.name=c[f].name),b[f].type!==c[f].type&&(e.type=c[f].type),d.push({op:"parameter.update",eventId:a,index:f,patch:e})}for(let b=e;b<c.length;b++)d.push({op:"parameter.add",eventId:a,parameter:c[b],index:b});for(let e=b.length-1;e>=c.length;e--)d.push({op:"parameter.remove",eventId:a,index:e})}(b.id,j[k].parameters??[],b.parameters??[],d)):(d.push({op:"event.add",sourceIndex:a,event:b,index:k}),j.splice(k,0,b)),k++}}(a,d[a],e[a],c);for(let a=d.length;a<e.length;a++)c.push({op:"eventSource.add",source:e[a]});for(let a=d.length-1;a>=e.length;a--)c.push({op:"eventSource.remove",index:a})}(c,b,e),function(a,b,c){let d=o(a.state),e=o(b.state),f=new Map(d.map(a=>[a.name,a])),g=new Map(e.map(a=>[a.name,a])),h=p(a.state),i=p(b.state),j=[];for(let a of e){if(f.has(a.name))continue;let b=i.get(a.name)??null,{states:d,transitions:e,...g}=a;c.push({op:"state.add",parent:b,state:{...g}}),e&&e.length>0&&j.push({state:a.name,transitions:e})}for(let a of e){if(!f.has(a.name))continue;let b=h.get(a.name)??null,d=i.get(a.name)??null;b!==d&&null!==d&&c.push({op:"state.nest",child:a.name,newParent:d})}for(let a of e){let b=f.get(a.name);if(!b)continue;let d={},e=!1;q(b.kind,a.kind)||void 0===a.kind||(d.kind=a.kind,e=!0),q(b.description,a.description)||void 0===a.description||(d.description=a.description,e=!0),q(b.notes,a.notes)||(d.notes=a.notes??"",e=!0),q(b.prompt,a.prompt)||(d.prompt=a.prompt??"",e=!0),e&&c.push({op:"state.update",name:a.name,patch:d}),r(a.name,"onEntry",b.onEntry?.actions??[],a.onEntry?.actions??[],c),r(a.name,"onExit",b.onExit?.actions??[],a.onExit?.actions??[],c)}for(let a of j)a.transitions.forEach((b,d)=>{c.push({op:"transition.add",state:a.state,transition:b,index:d})});for(let a of e){let b=f.get(a.name);b&&function(a,b,c,d){let e=Math.min(b.length,c.length);for(let f=0;f<e;f++){if(q(b[f],c[f]))continue;let e={};for(let a of["event","nextState","condition","description","actions"])q(b[f][a],c[f][a])||void 0===c[f][a]||(e[a]=c[f][a]);Object.keys(e).length>0&&d.push({op:"transition.update",state:a,index:f,patch:e})}for(let b=e;b<c.length;b++)d.push({op:"transition.add",state:a,transition:c[b],index:b});for(let e=b.length-1;e>=c.length;e--)d.push({op:"transition.remove",state:a,index:e})}(a.name,b.transitions??[],a.transitions??[],c)}for(let a=d.length-1;a>=0;a--){let b=d[a];if(g.has(b.name))continue;let e=b.transitions??[];for(let a=e.length-1;a>=0;a--)c.push({op:"transition.remove",state:b.name,index:a});c.push({op:"state.remove",name:b.name})}}(c,b,e),e);0!==h.length&&(d.emitPatch(h),g=f)},60))}))})(),()=>{c=!0,f&&clearTimeout(f),e&&e(),d&&d.disconnect()}},[a,b]),null}function eb(){let a=process.env.NEXT_PUBLIC_STATELOOM_BRIDGE_URL??process.env.NEXT_PUBLIC_SMCRAFT_BRIDGE_URL;return"string"==typeof a&&a.length>0?a:void 0}let ec=null;function ed(){return ec||(ec=(async()=>{let a=eb()??null;try{let b=await fetch("/api/config",{cache:"no-store"});if(b.ok){let c=await b.json();return{bridgeUrl:c.bridgeUrl||a,projectFile:c.projectFile??null,stage:c.stage??null,companion:!0===c.companion,companionEpisode:c.companionEpisode??null}}}catch{}return{bridgeUrl:a,projectFile:null,stage:null,companion:!1,companionEpisode:null}})())}function ee(){let a=eb(),[b,c]=(0,i.useState)(a);return((0,i.useEffect)(()=>{let a=!0;return ed().then(b=>{a&&b.bridgeUrl&&c(b.bridgeUrl)}),()=>{a=!1}},[]),"string"==typeof b&&b.length>0)?(0,h.jsx)(ea,{url:b}):(0,h.jsx)(d9,{})}function ef(a){return Number.isFinite(a)?Math.min(1.75,Math.max(.75,a)):1}function eg(a){"u">typeof document&&(document.documentElement.style.fontSize=`${16*ef(a)}px`)}let eh=1,ei=!1,ej=new Set;function ek(){return ei||(ei=!0,eh=1),eh}function el(){return 1}function em(a){return ej.add(a),()=>{ej.delete(a)}}function en(a,b){let c=ef(a);if(eg(c),b,ei=!0,c!==eh)for(let a of(eh=c,ej))a()}function eo(a,b){return Math.max(1,Math.hypot(b.clientX-a.clientX,b.clientY-a.clientY))}function ep(a,b){for(let c=0;c<a.length;c++)if(a[c].identifier===b)return a[c];return null}function eq(){let a=(0,i.useSyncExternalStore)(em,ek,el),b=(0,i.useRef)(null),c=(0,i.useRef)(null),d=(0,i.useRef)(null);(0,i.useEffect)(()=>{eg(a)},[a]);let e=(0,i.useCallback)(a=>{c.current=a,null===d.current&&(d.current=requestAnimationFrame(()=>{d.current=null,null!==c.current&&en(c.current,!1)}))},[]),f=(0,i.useCallback)(()=>{c.current=null,en(1,!0)},[]);return((0,i.useEffect)(()=>{let a=()=>{let a=b.current;if(b.current=null,!a?.engaged)return;null!==d.current&&(cancelAnimationFrame(d.current),d.current=null);let e=c.current??ek();c.current=null,en(ef(e),!0)},f=c=>{if(2!==c.touches.length){b.current&&a();return}let[d,e]=[c.touches[0],c.touches[1]];dP(d.target)||dP(e.target)||(b.current={a:d.identifier,b:e.identifier,startScale:ek(),startDist:eo(d,e),engaged:!1})},g=a=>{let c=b.current;if(!c)return;let d=ep(a.touches,c.a),f=ep(a.touches,c.b);if(!d||!f)return;a.preventDefault();let g=eo(d,f);if(!c.engaged){if(12>Math.abs(g-c.startDist))return;c.engaged=!0,c.startDist=g;return}e(ef(c.startScale*(g/c.startDist)))},h=c=>{let d=b.current;d&&(ep(c.touches,d.a)&&ep(c.touches,d.b)||a())};return document.addEventListener("touchstart",f,{passive:!0,capture:!0}),document.addEventListener("touchmove",g,{passive:!1,capture:!0}),document.addEventListener("touchend",h,{passive:!0,capture:!0}),document.addEventListener("touchcancel",h,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",f,{capture:!0}),document.removeEventListener("touchmove",g,{capture:!0}),document.removeEventListener("touchend",h,{capture:!0}),document.removeEventListener("touchcancel",h,{capture:!0}),null!==d.current&&cancelAnimationFrame(d.current)}},[e]),1===a)?null:(0,h.jsxs)("div",{className:"ui-scale-pill",role:"status","aria-live":"polite",children:[(0,h.jsxs)("span",{children:["UI ",Math.round(100*a),"%"]}),(0,h.jsx)("button",{type:"button",onClick:f,"aria-label":"Reset interface size to 100 percent",children:"Reset"})]})}var er=i;class es extends er.Component{state={error:null};static getDerivedStateFromError(a){return{error:a}}componentDidCatch(a,b){console.error(`[stateloom] the ${this.props.what} could not be drawn:`,a,b.componentStack)}componentDidUpdate(a){this.state.error&&a.resetKey!==this.props.resetKey&&this.setState({error:null})}render(){let{error:a}=this.state;return a?(0,h.jsx)("div",{role:"alert",className:"flex h-full w-full items-center justify-center p-6 text-center text-sm text-amber-300",children:(0,h.jsxs)("p",{className:"max-w-md",children:["This ",this.props.what," cannot be drawn: ",a.message,". The file on disk is unchanged — correct it in the panel, in the file, or with the agent that wrote it."]})}):this.props.children}}function et({size:a=16}){return(0,h.jsxs)("svg",{width:a,height:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,h.jsx)("path",{d:"M12 4.5 21 19.5H3Z"}),(0,h.jsx)("path",{d:"M12 10v4.5"}),(0,h.jsx)("path",{d:"M12 17.3v.01"})]})}function eu({locked:a,size:b=16}){return(0,h.jsxs)("svg",{width:b,height:b,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,h.jsx)("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),(0,h.jsx)("path",{d:a?"M8 11V8a4 4 0 0 1 8 0v3":"M8 11V8a4 4 0 0 1 7.5-1.9"})]})}function ev(a){let{onClose:b,restVh:c,tallVh:d}=a,[e,f]=(0,i.useState)(!1),[g,h]=(0,i.useState)(null),j=(0,i.useRef)(null),k=()=>{f(!1),b()},l=a=>{let b=j.current;if(!b||b.id!==a.pointerId)return;j.current=null;let c=a.clientY-b.y;if(h(null),6>Math.abs(c))return f(a=>!a);if(c<=-50)return f(!0);if(c>=80){if(e&&c<260)return f(!1);k()}},m=e?d:c,n=null!==g;return{zoneProps:{onPointerDown:a=>{a.target.closest("button")||(j.current={y:a.clientY,id:a.pointerId},a.currentTarget.setPointerCapture(a.pointerId),h(0))},onPointerMove:a=>{let b=j.current;b&&b.id===a.pointerId&&h(a.clientY-b.y)},onPointerUp:l,onPointerCancel:l,style:{touchAction:"none",cursor:"grab"}},sheetStyle:{"--sheet-h":n&&g<0?`min(calc(${m}dvh + ${-g}px), ${d}dvh)`:`${m}dvh`,...n?{transition:"none"}:{},...n&&g>0?{transform:`translateY(${g}px)`}:{}},close:k}}let ew="stateloom:focus-request",ex="stateloom:system-changed",ey="stateloom:strip-note";function ez(a){let[b,c]=(0,i.useState)(null);return(0,i.useEffect)(()=>{let a=()=>c(null);a();let b=["popstate",d4.DOC_CHANGE_EVENT,"stateloom:focus",ew];for(let c of b)window.addEventListener(c,a);return()=>{for(let c of b)window.removeEventListener(c,a)}},[a]),b}function eA(a){let b=new URL(window.location.href),c=b.searchParams.get("doc")!==a.doc;b.searchParams.set("doc",a.doc);let d=void 0===a.system?b.searchParams.get("system"):a.system;d?b.searchParams.set("system",d):b.searchParams.delete("system"),a.focus?b.searchParams.set("focus",a.focus):b.searchParams.delete("focus"),c?window.history.pushState({},"",b):window.history.replaceState(window.history.state,"",b),c&&window.dispatchEvent(new Event(d4.DOC_CHANGE_EVENT)),window.dispatchEvent(new Event(ew))}function eB(a){}function eC(){let[a,b]=(0,i.useState)({focus:null,nonce:0});return(0,i.useEffect)(()=>{let a=()=>b(a=>({focus:null,nonce:a.nonce+1}));a();let c=["popstate",d4.DOC_CHANGE_EVENT,ew];for(let b of c)window.addEventListener(b,a);return()=>{for(let b of c)window.removeEventListener(b,a)}},[]),a}let eD="/api/companion/",eE="stateloom.companion.autoplay",eF="stateloom.companion.episode",eG=/^\d{4}-\d{2}-\d{2}-episode-\d+-[a-z0-9-]+$/;function eH(a){try{return window.localStorage.getItem(a)}catch{return null}}function eI(a,b){try{window.localStorage.setItem(a,b)}catch{}}let eJ=a=>{let b=new Date(a);return Number.isNaN(b.getTime())?"":b.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})},eK=a=>"starting"===a||"recording"===a||"sending"===a,eL={state:"idle",seconds:0,held:0,message:"",error:!1,stored:null},eM={episode:null,items:[],presence:null,waiting:null,error:null};function eN({stage:a,defaultEpisode:b}){let[c,d]=(0,i.useState)(!1),[e,f]=(0,i.useState)(()=>"0"!==eH(eE)),[g,j]=(0,i.useState)(()=>{var a;let c,d=null,e=eH(eF);return(d&&eG.test(d)?d:null)??(a=(0,d4.requestedDoc)(),(c=a?.match(/(?:^|\/)(\d{4}-\d{2}-\d{2}-episode-\d+-[a-z0-9-]+)\/diagrams\/[^/]+$/))?c[1]:null)??(e&&eG.test(e)?e:null)??b}),[k,l]=(0,i.useState)([]),[m,n]=(0,i.useState)(eL),[o,p]=(0,i.useState)(eM),[q,r]=(0,i.useState)(null),[s,t]=(0,i.useState)([]),[u,v]=(0,i.useState)(null),[w,x]=(0,i.useState)(null),[y,z]=(0,i.useState)(()=>Date.now()),A=(0,i.useRef)(a),B=(0,i.useRef)(g),C=(0,i.useRef)(e);(0,i.useEffect)(()=>{A.current=a,B.current=g,C.current=e});let D=(0,i.useRef)(eL),E=(0,i.useRef)(null),F=(0,i.useRef)([]),G=(0,i.useRef)(!1),H=(0,i.useRef)([]),I=(0,i.useRef)(null),J=(0,i.useRef)(null),K=(0,i.useMemo)(()=>dz({recordings:!0,speech:!1}),[]),L=a=>{E.current=a,r(a)},M=(0,i.useRef)(async()=>{}),N=(0,i.useCallback)(async(a,b=0)=>{L(a.id),t(b=>b.filter(b=>b!==a.id)),a.steps?.length&&window.matchMedia("(max-width: 767px)").matches&&d(!1);let c=F.current.length;v(c?`${c} more of Mia's replies wait after this one.`:null);let e=await A.current.present(function(a,b,c="Mia"){let d=new Date(a.at),e=Number.isNaN(d.getTime())?`${c}'s reply`:`Reply at ${d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`,f=!a.unvoiced,g=(a,c)=>(function(a,b){if(!b)return;if(/^https?:\/\//.test(b))return b;let c=b.replace(/^\/?api\//,"");return`${a.endsWith("/")?a:`${a}/`}${c}`})(b,a||(f?c:null));return{settings:{namespace:"companion",name:e,author:c},steps:a.steps?.length?a.steps.map(({audio:b,...c},d)=>{let e=g(b,`api/replies/${a.id}/steps/${d}/audio`);return{...c,...e?{audio:e}:{}}}):[{say:a.text,...g(a.audio,`api/replies/${a.id}/audio`)?{audio:g(a.audio,`api/replies/${a.id}/audio`)}:{}}]}}(a,eD,"Mia"),{voice:K,origin:"Mia",from:b});if(E.current!==a.id||(L(null),G.current))return;if(!e){F.current=[];return}let f=F.current.shift();f&&!eK(D.current.state)?M.current(f):f&&F.current.unshift(f)},[K]);(0,i.useEffect)(()=>{M.current=N},[N]);let O=(0,i.useCallback)(a=>{let b=a.id;if(!C.current)return void t(a=>a.includes(b)?a:[...a,b]);if(eK(D.current.state)||E.current){t(a=>a.includes(b)?a:[...a,b]),F.current.some(a=>a.id===b)||F.current.push(a),v(eK(D.current.state)?`Mia replied at ${eJ(a.at)}. Her voice waits until you have sent your take.`:`Mia replied again at ${eJ(a.at)}. It plays when this one ends.`);return}M.current(a)},[]);(0,i.useEffect)(()=>{let a=function(a){let b=a.base.endsWith("/")?a.base:`${a.base}/`,c=a.fetch??((...a)=>fetch(...a)),d=a.everyMs??1e4,e=a.waitEveryMs??4e3,f=a.waitForMs??9e5,g={episode:null,items:[],presence:null,waiting:null,error:null},h=new Set,i=!1,j=null,k=null,l="",m=0,n=b=>{g={...g,...b},a.onChange?.(g)};async function o(){let d=g.episode;if(!d)return;let e=m;try{let j=await c(`${b}thread?episode=${encodeURIComponent(d)}`,{cache:"no-store"}),o=await j.json();if(e!==m)return;if(!o.success)return n({error:o.error??`HTTP ${j.status}`});let p=o.items??[],q=p.map(a=>"reply"===a.kind?`${a.id}:${+!!a.audio}:${a.feedback??""}`:`${a.take}:${a.text.length}`).join(",")+`|${o.presence?.state}`,r=p.filter(a=>"reply"===a.kind&&!h.has(a.id));for(let a of r)h.add(a.id);if((q!==l||g.error)&&(l=q,n({items:p,presence:o.presence??null,error:null})),i)for(let b of r)a.onReply?.(b);i=!0;let s=g.waiting;s&&(p.some(a=>"reply"===a.kind&&a.take===s.take)||Date.now()-s.since>f)&&(k&&clearInterval(k),k=null,n({waiting:null}))}catch(a){e===m&&n({error:a instanceof Error?a.message:String(a)})}}let p=()=>{"visible"===document.visibilityState&&o()};return"u">typeof document&&document.addEventListener("visibilitychange",p),{getSnapshot:()=>g,setEpisode(a){a!==g.episode&&(m+=1,h.clear(),i=!1,l="",k&&clearInterval(k),k=null,n({episode:a,items:[],presence:null,waiting:null,error:null}),a?(j&&clearInterval(j),j=setInterval(()=>{("u"<typeof document||"visible"===document.visibilityState)&&o()},d),o()):j&&(clearInterval(j),j=null))},refresh:o,waitFor(a){n({waiting:{take:a,since:Date.now()}}),k&&clearInterval(k),k=setInterval(()=>void o(),e),o()},async feedback(a,d){await c(`${b}replies/${a}/feedback`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({value:d})}),l="",await o()},destroy(){for(let a of(m+=1,[j,k]))a&&clearInterval(a);j=k=null,"u">typeof document&&document.removeEventListener("visibilitychange",p)}}}({base:eD,onChange:p,onReply:O}),b=function(a){let b=a.base.endsWith("/")?a.base:`${a.base}/`,c=a.fetch??((...a)=>fetch(...a)),d=a.partEveryMs??1e4,e=a.beatEveryMs??15e3,f=a.getUserMedia??(a=>navigator.mediaDevices.getUserMedia(a)),g=a.createRecorder??(a=>{let b,c,d,e,f,g,h,i;return c=(b=new(window.AudioContext??window.webkitAudioContext)).createMediaStreamSource(a),d=b.createScriptProcessor(4096,1,1),e=[],f=[],g=!1,h=null,i={mimeType:"audio/wav",ondataavailable:null,onstop:null,onerror:null,start(a=1e3){d.onaudioprocess=a=>{let b=a.inputBuffer.getChannelData(0),c=new Int16Array(b.length);for(let a=0;a<b.length;a++)c[a]=Math.max(-32768,Math.min(32767,Math.round(32767*b[a])));e.push(c),f.push(c)},c.connect(d),d.connect(b.destination),h=setInterval(()=>{if(!f.length)return;let a=g?[]:[dA(0x7fffffff,b.sampleRate)];g=!0,a.push(...f.map(a=>a.buffer)),f=[],i.ondataavailable?.({data:new Blob(a,{type:"audio/wav"})})},a)},stop(){h&&clearInterval(h),h=null;try{c.disconnect(),d.disconnect()}catch{}b.close().catch(()=>{}),i.whole=new Blob([dA(e.reduce((a,b)=>a+b.byteLength,0),b.sampleRate),...e.map(a=>a.buffer)],{type:"audio/wav"}),i.onstop?.()}}}),h={state:"idle",seconds:0,held:0,message:"",error:!1,stored:null,...!a.createRecorder?{unavailable:"this browser cannot record audio"}:{}},i=b=>{h={...h,...b},a.onChange?.(h)},j=null,k=null,l=[],m="",n="",o=null,p=0,q=null,r=null,s=null,t=null,u=!1,v=()=>p?Math.floor((Date.now()-p)/1e3):0,w=()=>(k?.mimeType||"audio/mp4").split(";")[0]||"audio/mp4",x=(a="")=>`episode=${encodeURIComponent(n)}${m?`&rec=${m}`:""}${o?`&context=${encodeURIComponent(o)}`:""}${a}`;function y(a){n&&c(`${b}recorder`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({episode:n,recording:a})}).catch(()=>{})}function z(a,d={}){m&&c(`${b}takes/diagnostic`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({rec:m,episode:n,kind:a,at:new Date().toISOString(),mime:k?.mimeType??null,visibility:"u">typeof document?document.visibilityState:"",agent:"u">typeof navigator?navigator.userAgent:"",source:"stateloom-canvas",...d}),keepalive:!0}).catch(()=>{})}function A(){for(let a of[r,s,t])a&&clearInterval(a);r=s=t=null}function B(){try{j?.getTracks().forEach(a=>a.stop())}catch{}j=null}async function C(){if(!m||u||!l.length)return;let a=new Blob(l,{type:w()});if(a.size<=h.held)return;u=!0;let d=m;try{let e=await c(`${b}takes/part?${x(`&offset=${h.held}`)}`,{method:"POST",headers:{"content-type":w()},body:a.slice(h.held)}),f=await e.json();d===m&&"number"==typeof f.bytes&&i({held:f.bytes})}catch{}finally{u=!1}}async function D(){let b;if("idle"!==h.state&&"retry"!==h.state)return;if(h.unavailable)return i({message:`Cannot record: ${h.unavailable}.`,error:!0});if(!(n=a.episode()??""))return i({message:"Choose the episode this take belongs to.",error:!0});let c=a.context?.()??null;o=c?JSON.stringify(c).slice(0,4e3):null,q=null,i({state:"starting",message:"",error:!1,held:0,seconds:0}),y(!0);try{b=await f({audio:!0})}catch(a){return y(!1),i({state:"idle",message:`Microphone refused: ${a instanceof Error?a.message:String(a)}`,error:!0})}if("starting"!==h.state)return void b.getTracks().forEach(a=>a.stop());j=b,l=[],m=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;try{k=g(b)}catch(a){return B(),y(!1),i({state:"idle",message:`This browser refused to record: ${a instanceof Error?a.message:String(a)}`,error:!0})}k.ondataavailable=a=>{a.data&&a.data.size&&l.push(a.data)},k.onerror=a=>{let b=v(),c=new Blob(l,{type:w()});if(z("recorder-error",{name:a?.error?.name??"",message:a?.error?.message??"",seconds:b,bytes:c.size,held:h.held}),A(),B(),y(!1),c.size)q=c,i({state:"retry",message:`The recorder stopped with an error after ${Math.floor(b/60)}:${String(b%60).padStart(2,"0")}. What it captured is kept: Send again.${h.held?` ${dB(h.held)} of it is already stored.`:""}`,error:!0});else i({state:"idle",message:"The recorder stopped before it captured anything. Nothing was sent.",error:!0})},k.start(1e3),p=Date.now(),r=setInterval(()=>void C(),d),s=setInterval(()=>y(!0),e),t=setInterval(()=>i({seconds:v()}),500),i({state:"recording",seconds:0,message:""})}async function E(d){i({state:"sending",message:`Sending ${dB(d.size)}, then transcribing and storing…`,error:!1});try{let e=await c(`${b}takes?${x()}`,{method:"POST",headers:{"content-type":(d.type||"audio/mp4").split(";")[0]},body:d}),f=await e.json();if(!f.success||!f.take)throw Error(f.error||`HTTP ${e.status}`);q=null,m="";let g=f.presence??{state:f.listening?"listening":"away"},h=f.transcriptError?` Transcription failed, so no session wakes yet: ${f.transcriptError}`:({listening:" The session listening there will hear it.",answering:" Mia is answering an earlier take; she hears this one next.",answered:" The session hears it as soon as it listens again."})[g.state]??" No session is listening yet; the take waits, and her reply comes here when one answers.";i({state:"idle",seconds:0,held:0,message:`Take ${f.take} is in the episode.${h}`,error:!!f.transcriptError,stored:{take:f.take,english:f.english??"",transcriptError:f.transcriptError,presence:g}}),f.transcriptError||a.onStored?.(f.take)}catch(a){q=d,z("send-failed",{message:a instanceof Error?a.message:String(a),bytes:d.size,held:h.held}),i({state:"retry",message:`Not stored: ${a instanceof Error?a.message:String(a)}. Your recording is kept — Send again.${h.held?` ${dB(h.held)} of it is already stored, and becomes a take by itself if you leave.`:""}`,error:!0})}}async function F(){if("recording"!==h.state)return;let a=v();A(),y(!1),i({state:"sending",seconds:a});let b=await new Promise(a=>{let b=!1,c=()=>{b||(b=!0,a(k?.whole??new Blob(l,{type:w()})))},d=setTimeout(c,3e3);if(!k)return c();k.onstop=()=>{clearTimeout(d),c()};try{k.stop()}catch{clearTimeout(d),c()}});if(B(),!b.size)return z("empty-at-stop",{seconds:a,held:h.held}),i({state:"idle",message:h.held?`The recorder handed back nothing at Stop, but ${dB(h.held)} is stored; it becomes a take within a few minutes.`:"Nothing was recorded. Try again.",error:!0});await E(b)}async function G(){"retry"===h.state&&q&&await E(q)}return{getSnapshot:()=>h,press:async()=>"recording"===h.state?F():"retry"===h.state&&q?G():D(),start:D,stop:F,resend:G,destroy(){A(),("recording"===h.state||"starting"===h.state)&&y(!1);try{k?.stop()}catch{}B()}}}({base:eD,episode:()=>B.current,context:()=>{let a=A.current.shown,b=a?{...a.title||a.step.title?{title:[a.title,a.step.title].filter(Boolean).join(" · ")}:{},say:a.step.say.slice(0,400),...null!==a.index&&null!==a.count?{index:a.index,count:a.count}:{},...a.origin?{by:a.origin}:{}}:null;return function(a,b={}){if(!a?.doc)return null;let c={stage:a.stage,doc:a.doc,kind:a.kind,system:a.system,focus:a.focus??void 0,visible:a.visible,tour:a.tour,who:a.who,at:new Date().toISOString(),...b};for(let a of Object.keys(c))(void 0===c[a]||null===c[a])&&delete c[a];return c}(A.current.lastReport(),{...H.current.length?{marks:H.current}:{},...a?.step.spotlight?.length?{spotlight:a.step.spotlight}:{},...b?{step:b}:{}})},onChange:a=>{let b=D.current.state;if(D.current=a,n(a),!eK(b)||eK(a.state)||(G.current=!1,!C.current||E.current))return;let c=F.current.shift();c?M.current(c):v(null)},onStored:b=>a.waitFor(b)});return J.current=a,I.current=b,D.current=b.getSnapshot(),n(b.getSnapshot()),()=>{b.destroy(),a.destroy(),J.current=null,I.current=null}},[O]),(0,i.useEffect)(()=>{J.current?.setEpisode(g)},[g]),(0,i.useEffect)(()=>{let a=!0;return fetch(`${eD}health`,{cache:"no-store"}).then(a=>a.json()).then(b=>{if(a){if(!b.success)return x(`The companion does not answer: ${b.error??"no reason given"}.`);x(null),b.defaultEpisode&&j(a=>a??b.defaultEpisode??null)}}).catch(b=>a&&x(`The companion does not answer: ${b instanceof Error?b.message:String(b)}.`)),()=>{a=!1}},[]),(0,i.useEffect)(()=>{if(!c||k.length)return;let a=!0;return fetch(`${eD}episodes`,{cache:"no-store"}).then(a=>a.json()).then(b=>{a&&b.success&&b.episodes&&l(b.episodes)}).catch(()=>{}),()=>{a=!1}},[c,k.length]);let P=(0,i.useRef)(null),Q=(0,i.useCallback)(async(a=!1)=>{let b=A.current.lastReport()?.doc??null;if(a||b!==P.current){if(P.current=b,!b){H.current=[];return}try{var c,d;let a=await fetch(`/api/marks?doc=${encodeURIComponent(b)}`,{cache:"no-store"}),e=await a.json();H.current=(c=function(a,b=""){let c=a&&"object"==typeof a?a:{},d=Array.isArray(c.marks)?c.marks.map(bn).filter(a=>null!==a):[];return{doc:bk(c.doc)||b,marks:d}}(e,b).marks,d="agent",c.filter(a=>"open"===a.status&&a.author.role!==d||"answered"===a.status&&a.author.role===d)).map(a=>a.id)}catch{H.current=[]}}},[]);(0,i.useEffect)(()=>{Q(!0);let a=A.current.onMarks(()=>void Q(!0)),b=setInterval(()=>void Q(),3e3);return()=>{a(),clearInterval(b)}},[Q]),(0,i.useEffect)(()=>{if(!o.waiting)return;let a=setInterval(()=>z(Date.now()),1e3);return()=>clearInterval(a)},[o.waiting]);let R=(0,i.useCallback)(()=>{let a=I.current;a&&(!eK(D.current.state)&&"retry"!==D.current.state&&E.current&&(G.current=!0,A.current.stop()),a.press())},[]),S=(0,i.useCallback)((a,b)=>{let c=J.current?.getSnapshot().items.find(b=>"reply"===b.kind&&b.id===a);if(c){if(eK(D.current.state))return void v(`Send your take first. Then press ▶ to hear Mia.`);F.current=[],G.current=!1,M.current(c,b)}},[]),T=(0,i.useCallback)(()=>{F.current=[],G.current=!1,A.current.stop()},[]),U=o.waiting?{take:o.waiting.take,seconds:Math.max(0,Math.floor((y-o.waiting.since)/1e3))}:null;return(0,h.jsx)("div",{className:"stage-talk-host",children:(0,h.jsx)(ci,{open:c,onOpenChange:a=>{d(a),a&&Q(!0)},who:"Mia",episode:g,episodes:k,onEpisode:a=>{eG.test(a)&&a!==g&&(F.current=[],t([]),v(null),j(a),eI(eF,a))},presence:o.presence,recorder:m,onRecord:R,items:o.items,unheard:s,playing:q,playingStep:q&&a.shown?.origin==="Mia"?a.shown.index:null,onPlay:S,onStop:T,onFeedback:(a,b)=>{J.current?.feedback(a,b).catch(a=>x(`Your thumb was not kept: ${a instanceof Error?a.message:String(a)}.`))},autoplay:e,onAutoplay:a=>{f(a),eI(eE,a?"1":"0"),a||(F.current=[])},waiting:U,notice:u,error:w??o.error})})}let eO=(0,i.createContext)(null);function eP(){return(0,i.useContext)(eO)}function eQ(a,b){try{window.localStorage.setItem(a,b)}catch{}}function eR({children:a}){var b;let c,d,e,f,g,j,k,l,[m,n]=(0,i.useState)({bridgeUrl:null,stage:bf,companion:!1,companionEpisode:null});(0,i.useEffect)(()=>{let a=!0;return ed().then(b=>{if(!a)return;let c=null,d=bh(c)?c:bh(b.stage)?b.stage:bf;n({bridgeUrl:b.bridgeUrl,stage:d,companion:b.companion,companionEpisode:b.companionEpisode})}),()=>{a=!1}},[]);let[o,p]=(0,i.useState)(()=>!1),[q,r]=(0,i.useState)(()=>""),s=(0,i.useMemo)(()=>o?dz():null,[o]),t=(0,i.useMemo)(()=>null,[]),[u,v]=(0,i.useState)(null),w=(0,i.useRef)(new Set),x=(0,i.useCallback)(a=>{var b;if(!a)return void v(null);let{step:c}=a,d=(0,d4.requestedDoc)();if(a.caught,c.doc&&c.doc!==d)eA({doc:c.doc,system:c.system??void 0,focus:c.focus??null});else if(c.focus)if(c.system&&null!==c.system&&d)eA({doc:d,system:c.system,focus:c.focus});else{let a;b=c.focus,(a=new URL(window.location.href)).searchParams.set("focus",b),window.history.replaceState(window.history.state,"",a),window.dispatchEvent(new Event(ew))}v({doc:c.doc,focus:c.focus,spotlight:c.spotlight,region:c.region,nonce:a.nonce})},[]),y=(b={url:m.bridgeUrl??"",stage:m.stage,name:"web-stage",voice:s,enabled:!!m.bridgeUrl,onShow:x,onMarks:a=>{for(let b of[...w.current])b(a)}},(c=(0,i.useRef)({onShow:b.onShow,onMarks:b.onMarks})).current={onShow:b.onShow,onMarks:b.onMarks},d=(0,i.useRef)(null),e=`${b.url}\u0000${b.stage??""}\u0000${b.token??""}`,f=(0,i.useRef)(e),(null===d.current||f.current!==e)&&(f.current=e,d.current=function(a){let b,c=bh(a.stage)?a.stage:bf,d=a.setTimer??((a,b)=>setTimeout(a,b)),e=a.clearTimer??(a=>clearTimeout(a)),f=a.gapMs??900,g=a.client??dw({url:a.url,role:a.role??"web",docId:`stage:${c}`,name:a.name??"web-stage",token:a.token,autoResync:!1}),h=a.voice??null,i=a=>a&&void 0!==b?b:h,j=null,k=null,l=a=>{let b=k;k=null,b?.(a)},m=null,n=null,o=[],p=[],q=0,r=!1,s=!1,t=0,u=null,v=0,w=!1,x=!1,y=!1,z=!1,A=!1,B={status:g.status,stage:c,shown:m,tour:n,index:q,playing:r,speaking:s,ownVoice:!1},C=new Set;function D(){for(let a of(B={status:g.status,stage:c,shown:m,tour:n,index:q,playing:r,speaking:s,ownVoice:!!n&&void 0!==b},[...C]))a()}function E(){v+=1,u&&e(u),u=null,s&&j?.cancel(),s=!1,j=null}function F(a,b,c=b){E();let e=++v,g=()=>{e!==v||(s&&(s=!1,D()),b&&r&&(u=d(()=>{u=null,e===v&&r&&L()},h?f:0)))},h=i(c);if(h)s=!0,j=h,D(),h.speak(a).then(g,g);else{let c;b&&(u=d(()=>{u=null,g()},"number"==typeof(c=a.holdMs)&&Number.isFinite(c)&&a.holdMs>=0?a.holdMs:Math.min(2e4,Math.max(2500,1200+400*`${a.title??""} ${a.say??""}`.trim().split(/\s+/).filter(Boolean).length))))}}function G(b,c){t+=1,E(),m=b?{...b,nonce:t,...A?{caught:!0}:{}}:null,D(),a.onShow?.(m);let d=!!m&&null!==m.index;m&&(i(d)||c)&&F(m.step,c,d)}function H(a){if(!n)return null;let b=n.def.steps[a];if(!b)return null;let c=b.doc??o[a],d=b.system??p[a];return{step:{...b,...c?{doc:c}:{},...d?{system:d}:{}},index:a,count:n.def.steps.length,title:n.def.settings?.name,origin:n.origin,tourPath:n.path}}function I(a,c,d){var e;let f,g;l(!1),b=d;let h=Array.isArray(a.tour?.steps)?a.tour.steps:[];e=(n={def:{...a.tour,steps:h},path:a.path,origin:a.origin}).def,g=void 0,o=e.steps.map(a=>g=a.doc??g),p=h.map(a=>f=a.system??f),q=Math.min(Math.max(0,a.from??0),Math.max(0,h.length-1)),w=!1,r=c&&h.length>0,G(H(q),r)}function J(a){r=!1,G({step:a.step,index:null,count:null,title:a.title,origin:a.origin,tourPath:a.tour},!1)}function K(a){if(!n)return;let b=n.def.steps.length-1;b<0||(w=!1,G(H(q=Math.min(Math.max(0,Math.floor(a)),b)),r))}function L(){if(n){if(q>=n.def.steps.length-1){let a=r;w=r||w,r=!1,E(),D(),a&&l(!0);return}K(q+1)}}function M(){n&&q>0&&K(q-1)}function N(){n&&n.def.steps.length&&(r=!0,w&&(w=!1,q=0),m?.index!==q||m.caught?G(H(q),!0):(D(),F(m.step,!0)))}function O(){r=!1,E(),D()}function P(){l(!1),b=void 0,w=!1,n=null,o=[],p=[],q=0,r=!1,G(null,!1)}function Q(){z||(z=!0,g.joinStage(c).then(({state:a})=>{z=!1,y=!0,m||n||function(a){A=!0;try{a.tour&&I(a.tour,!1),a.step&&J(a.step)}finally{A=!1}}(a),D()}).catch(()=>{z=!1,D()}))}return g.on("stage-step",a=>{a?.stage===c&&a.step&&J(a)}),g.on("stage-load",a=>{a?.stage===c&&a.tour&&I(a,!1!==a.autoplay)}),g.on("stage-control",a=>{a?.stage===c&&function(a){switch(a.action){case"play":return N();case"pause":return O();case"next":return L();case"prev":return M();case"goto":return K(a.index??0);case"stop":return P()}}(a)}),g.on("marks",b=>a.onMarks?.(b)),g.on("status",a=>{"disconnected"===a||"error"===a?y=!1:"connected"===a&&x&&!y&&Q(),D()}),{getSnapshot:()=>B,subscribe:a=>(C.add(a),()=>{C.delete(a)}),connect(){x=!0,Q()},disconnect(){x=!1,E(),g.leaveStage(c),g.disconnect()},play:N,pause:O,next:L,prev:M,goto:K,stop:P,dismiss:function(){if(m){if(null===m.index&&n)return void G(H(q),!1);null===m.index?G(null,!1):P()}},setVoice(a){void 0===b&&E(),h=a,D()},present:(a,b={})=>Array.isArray(a?.steps)&&a.steps.length?new Promise(d=>{I({stage:c,tour:a,from:b.from??0,autoplay:!1!==b.autoplay,origin:b.origin??"page"},!1!==b.autoplay,b.voice),k=d}):Promise.resolve(!1),sendContext(a){g.emitContext({...a,stage:c,...n?{tour:{path:n.path,title:n.def.settings?.name,index:q,count:n.def.steps.length,playing:r}}:{}})},sendMarks(a){g.emitMarks({...a,stage:c}).catch(()=>{})}}}({...b,voice:b.voice??null,onShow:a=>c.current.onShow?.(a),onMarks:a=>c.current.onMarks?.(a)})),g=d.current,j=(0,i.useSyncExternalStore)(g.subscribe,g.getSnapshot,g.getSnapshot),k=!1!==b.enabled&&!!b.url,(0,i.useEffect)(()=>{if(k)return g.connect(),()=>g.disconnect()},[g,k]),l=b.voice??null,(0,i.useEffect)(()=>{g.setVoice(l)},[g,l]),{...j,play:g.play,pause:g.pause,next:g.next,prev:g.prev,goto:g.goto,stop:g.stop,dismiss:g.dismiss,sendContext:g.sendContext,sendMarks:g.sendMarks,present:g.present}),z=(0,i.useRef)(null),A=(0,i.useRef)(null),B=y.sendContext,C=(0,i.useCallback)(a=>{z.current={...a,stage:m.stage,who:q||void 0,at:new Date().toISOString()},A.current&&clearTimeout(A.current),A.current=setTimeout(()=>B({...a,who:q||void 0}),400)},[m.stage,q,B]);(0,i.useEffect)(()=>()=>{A.current&&clearTimeout(A.current)},[]),(0,i.useEffect)(()=>{z.current&&B({...z.current,who:q||void 0})},[y.index,y.playing,y.tour,B,q]);let[D,E]=(0,i.useState)(0),F=!!y.shown;(0,i.useEffect)(()=>{let a=document.documentElement,b=F?document.querySelector(".stage-caption-host .slc-stage-caption"):null;if(!b||"u"<typeof ResizeObserver)return void a.style.removeProperty("--stage-caption-h");let c=()=>a.style.setProperty("--stage-caption-h",`${Math.ceil(b.getBoundingClientRect().height)+12}px`),d=new ResizeObserver(c);return d.observe(b),c(),()=>{d.disconnect(),a.style.removeProperty("--stage-caption-h")}},[F]);let G=(0,i.useMemo)(()=>({stage:m.stage,connected:"connected"===y.status,lit:u,author:q,setAuthor:a=>{r(a),eQ("stateloom.author",a)},listener:t,answerNonce:D,report:C,lastReport:()=>z.current,sendMarks:y.sendMarks,onMarks:a=>(w.current.add(a),()=>{w.current.delete(a)}),shown:y.shown,present:y.present,pause:y.pause,stop:y.stop}),[m.stage,y.status,y.shown,y.sendMarks,y.present,y.pause,y.stop,u,q,t,D,C]);return(0,h.jsxs)(eO.Provider,{value:G,children:[a,y.shown&&(0,h.jsx)("div",{className:"stage-caption-host",children:(0,h.jsx)(b6,{shown:y.shown,playing:y.playing,speaking:y.speaking,voice:y.ownVoice?void 0:o,onToggleVoice:()=>{let a=!o;p(a),eQ("stateloom.stage.voice",a?"1":"0")},onPlay:y.play,onPause:y.pause,onNext:y.next,onPrev:y.prev,onGoto:y.goto,onClose:y.dismiss,onAnswer:()=>E(a=>a+1)})}),m.companion&&(0,h.jsx)(eN,{stage:G,defaultEpisode:m.companionEpisode})]})}let eS="flex h-9 min-w-9 items-center justify-center gap-1 rounded-lg border border-gray-700 bg-gray-900/90 px-2 text-sm text-gray-200 shadow-lg backdrop-blur hover:bg-gray-800";async function eT(a,b){let c=await fetch(`/api/marks?doc=${encodeURIComponent(a)}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(b)}),d=await c.json().catch(()=>({}));if(!c.ok)throw Error(d?.error??`the marks could not be written (${c.status})`);return d}function eU({docPath:a,kind:b,viewport:c,setViewport:d,boxes:e,boardRef:f,focus:g=null,level:j,onReveal:k}){let l=eP(),[m,n]=(0,i.useState)([]),[o,p]=(0,i.useState)(!1),[q,r]=(0,i.useState)(null),[s,t]=(0,i.useState)(null),[u,v]=(0,i.useState)(!1),[w,x]=(0,i.useState)(!1),[y,z]=(0,i.useState)(null),[A,B]=(0,i.useState)(!1),C=(0,i.useCallback)(()=>{a&&fetch(`/api/marks?doc=${encodeURIComponent(a)}`,{cache:"no-store"}).then(a=>a.ok?a.json():null).then(a=>a&&Array.isArray(a.marks)&&n(a.marks)).catch(()=>{})},[a]);(0,i.useEffect)(()=>(n([]),t(null),r(null),C(),window.addEventListener("focus",C),()=>window.removeEventListener("focus",C)),[C]),(0,i.useEffect)(()=>l?.onMarks(b=>{a&&b.docId===a&&Array.isArray(b.marks)&&n(b.marks)}),[l,a]);let D=async b=>{if(!a)return!1;x(!0),z(null);try{let c=await eT(a,b);return n(c.marks),l?.sendMarks({docId:a,marks:c.marks,change:c.change}),!0}catch(a){return z(a instanceof Error?a.message:String(a)),!1}finally{x(!1)}},E=l?.lit??null,F=E&&(!E.doc||E.doc===a)?E:null,G=F?.spotlight,H=F?.region??null,I=(0,i.useRef)(-1),J=(0,i.useRef)(-1),K=(0,i.useRef)(null),L=(0,i.useMemo)(()=>G?.length?br(e,G):[],[e,G]);(0,i.useEffect)(()=>{if(!F||I.current===F.nonce)return;let a=[...L,...H?[H]:[]];if(!a.length){G?.length&&J.current!==F.nonce&&(J.current=F.nonce,k?.(G));return}I.current=F.nonce;let b=()=>{let b=f.current?.getBoundingClientRect();if(!b?.width)return;let c=document.querySelector(".stage-caption-host .slc-stage-caption")?.getBoundingClientRect(),e=c&&c.top<b.bottom?Math.max(0,b.bottom-c.top+8):0,g=Math.max(.4*b.height,b.height-e);d(S(a,b.width,g,{padding:48,maxScale:1}))};b(),K.current&&clearTimeout(K.current),K.current=setTimeout(b,520)},[F,L,H,G,f,d,k]),(0,i.useEffect)(()=>()=>{K.current&&clearTimeout(K.current)},[]);let M=(0,i.useRef)(l?.answerNonce??0);(0,i.useEffect)(()=>{if(!l||l.answerNonce===M.current)return;M.current=l.answerNonce;let a=G?.length?[...G]:F?.focus?[F.focus]:g?[g]:[];v(!1),t(null),r({elements:a,region:H??void 0,listen:!!l.listener})},[l,G,F,g,H]);let N=l?.report;if((0,i.useEffect)(()=>{if(!N||!a)return;let d=f.current?.getBoundingClientRect(),e=O(c,{x:0,y:0}),h=d?O(c,{x:d.width,y:d.height}):e;N({doc:a,kind:b,system:void 0,focus:g,...d?.width?{visible:{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(h.x-e.x),height:Math.round(h.y-e.y)}}:{}})},[N,a,b,g,c,f]),!a)return null;let P=m.filter(a=>"open"===a.status&&"person"===a.author.role).length,Q=m.filter(a=>"open"===a.status&&"agent"===a.author.role).length,R=m.find(a=>a.id===s)??null;return(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(bT,{viewport:c,boxes:e,spotlight:G,region:H,marks:m,selectedMark:s,onSelectMark:a=>{r(null),v(!1),t(b=>b===a?null:a)},marking:o,onDraft:a=>{p(!1),t(null),v(!1),r(a)},draft:q}),(0,h.jsxs)("div",{className:"stage-board-controls",children:[(0,h.jsxs)("button",{type:"button",className:`${eS} ${o?"!border-amber-400 !text-amber-300":""}`,"aria-pressed":o,onClick:()=>{r(null),p(a=>!a)},title:o?"Marking: tap an element, or drag around several. Tap ✎ again to stop.":"Mark something for the agent — tap an element or drag around several",children:[(0,h.jsx)(b5,{}),o&&(0,h.jsx)("span",{className:"text-xs",children:"marking"})]}),(0,h.jsxs)("button",{type:"button",className:eS,"aria-expanded":u,onClick:()=>{r(null),t(null),v(a=>!a)},title:"Marks on this drawing",children:[(0,h.jsx)(bY,{}),P+Q>0&&(0,h.jsx)("span",{className:"text-xs text-amber-300",children:P+Q})]})]}),o&&!q&&(0,h.jsx)("div",{className:"stage-board-hint",role:"status",children:"Tap an element, or drag around several, to say something about it."}),(q||R||u)&&(0,h.jsx)("div",{className:"stage-board-card",children:q?(0,h.jsx)(ca,{elements:q.elements,region:q.region,author:l?.author??"",onAuthorChange:l?.setAuthor,listener:l?.listener,listenAtOnce:!!q.listen,busy:w,error:y,onCancel:()=>{r(null),z(null)},onSubmit:async({text:a,kind:b,author:c})=>{await D({action:"add",mark:{text:a,kind:b,elements:q.elements,region:q.region,level:j,author:{name:c||"someone"}}})&&r(null)}},`${q.elements.join(",")}|${q.region?JSON.stringify(q.region):""}`):R?(0,h.jsx)(cb,{mark:R,number:m.indexOf(R)+1,listener:l?.listener,busy:w,error:y,onClose:()=>t(null),onReply:a=>void D({action:"reply",id:R.id,text:a,author:{name:l?.author||"someone"}}),onResolve:()=>void D({action:"resolve",id:R.id}),onReopen:()=>void D({action:"reopen",id:R.id}),onRemove:async()=>{await D({action:"remove",id:R.id})&&t(null)}}):(0,h.jsx)(cc,{marks:m,selected:s,onSelect:a=>{v(!1),t(a)},onCopy:()=>{var b,c;let d,e;if(!a)return;let f=(b=l?.lastReport()??null,d=(c=[{doc:a,marks:m.filter(a=>"resolved"!==a.status)}]).reduce((a,b)=>a+b.marks.length,0),e=function(a){if(!a||!a.doc)return"No canvas has said what it is showing.";let b=[`${a.who?`${a.who} is`:"The canvas is"} on ${bs(a.doc)}${a.kind?` (${a.kind})`:""}`];a.system&&b.push(`as a member of ${bs(a.system)}`),a.focus&&b.push(`with ${a.focus} in hand`);let c=b.join(", ")+".";return a.tour&&(c+=` Tour ${a.tour.title?`'${a.tour.title}' `:""}at step ${a.tour.index+1} of ${a.tour.count}, ${a.tour.playing?"playing":"paused"}.`),a.at&&(c+=` (reported ${a.at})`),c}(b),d?`${e}
|
|
12
12
|
${d} mark(s):
|
|
13
13
|
${function(a,b={}){let c=[],d=b.start??1;for(let{doc:b,marks:e}of a)for(let a of e){for(let e of(c.push(`${d}. [${a.status} \xb7 ${a.kind}] ${a.author.name}${"agent"===a.author.role?" (agent)":""} on ${bo(a)} (${bs(b)}) — ${a.id}`),c.push(` "${bt(a.text)}"`),a.replies??[]))c.push(` ↳ ${e.author.name}${"agent"===e.author.role?" (agent)":""}: "${bt(e.text)}"`);d++}return c.join("\n")}(c)}`:`${e}
|
|
14
|
-
No marks.`);navigator.clipboard?.writeText(f).then(()=>{B(!0),setTimeout(()=>B(!1),2e3)})},copied:A,onClose:()=>v(!1)})})]})}function eS({docPath:a,onReveal:b}){let c=eM(),d=c?.lit??null,e=(0,i.useRef)(-1);return(0,i.useEffect)(()=>{!d||e.current===d.nonce||d.doc&&d.doc!==a||(d.spotlight?.length||d.region)&&(e.current=d.nonce,b())},[d,a,b]),null}function eT(a,b,c){try{return a()}catch(d){let a=d instanceof Error?d.message:String(d);return console.warn("[stateloom] skipped on a malformed document:",a),c?.(a),b}}let eU=(a,b)=>"chen"===b?`stateloom:erd-layout:chen:${a}`:`stateloom:erd-layout:${a}`,eV="stateloom:erd-notation",eW="stateloom:erd-lock";function eX(a,b){try{return JSON.parse(localStorage.getItem(eU(a,b))??"{}")}catch{return{}}}async function eY(a){let b=a.slice(0,a.lastIndexOf("/")),c=((await (await fetch("/api/docs",{cache:"no-store"})).json()).docs??[]).map(a=>a.path).filter(a=>a.endsWith(".smdf.json")&&a.slice(0,a.lastIndexOf("/"))===b),d=[];for(let a of c)try{let b=await (await fetch(`/api/file${(0,d4.docQuery)(a)}`,{cache:"no-store"})).json(),c=JSON.parse(b.content??"null"),e=aq(c?.stateMachine??c?.StateMachine??c);e?.state&&d.push({path:a,def:e})}catch{}return d}let eZ="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",e$="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",e_="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function e0(){let a=(0,d4.useRequestedDoc)(),[b,c]=(0,i.useState)(""),[d,e]=(0,i.useState)(null),[f,g]=(0,i.useState)({}),[j,k]=(0,i.useState)("crowsfoot"),[l,m]=(0,i.useState)(!1),[n,o]=(0,i.useState)({...M}),[p,q]=(0,i.useState)(0),[r,s]=(0,i.useState)(null),[t,u]=(0,i.useState)({text:"loading…",tone:"ok"}),v=(0,i.useCallback)((a,b="ok")=>u({text:a,tone:b}),[]),[w,x]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=setTimeout(()=>x(!0),4e3);return()=>{clearTimeout(a),x(!1)}},[t]);let[y,z]=(0,i.useState)("entities"),[A,B]=(0,i.useState)(!1),[C,D]=(0,i.useState)(!1),[E,F]=(0,i.useState)(!1),G=(0,i.useRef)(null),H=ev({onClose:()=>B(!1),restVh:62,tallVh:92}),[I,J]=(0,i.useState)(0),[K,L]=(0,i.useState)(null),N=(0,i.useRef)(null);(0,i.useEffect)(()=>{let b=!1,d=null;return(async()=>{let f=await (await fetch(`/api/file${(0,d4.docQuery)(a)}`,{cache:"no-store"})).json();if(b)return;if(f.error)return v(f.error,"warn");let h=f.path??"",i=null;try{let a=f.content?aq(JSON.parse(f.content)):null;X(a)&&(i={...a,relationships:a.relationships??[]})}catch{}if(f.exists&&!i)return v(`${h} is not a readable ERD definition`,"warn");let j=(h.split("/").pop()??"Untitled").replace(/\.erdf\.json$/i,""),l=function(){try{return"chen"===localStorage.getItem(eV)?"chen":"crowsfoot"}catch{return"crowsfoot"}}();c(h),e(i??{settings:{namespace:"Default",name:j},entities:[],relationships:[]}),k(l),m(function(){try{let a=localStorage.getItem(eW);if(null!==a)return"1"===a;return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}()),g(eX(h,l)),s(null),L(null),q(a=>a+1),v(f.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:n}=await ed();!b&&n&&(N.current=d=dy({url:n,role:"web",docId:h,name:"web-designer",onFull:a=>{let b=a.def;X(b)&&(e({...b,relationships:b.relationships??[]}),v("updated live"))},onPatch:()=>{},onPresence:a=>J(a.length)}),d.connect())})().catch(a=>!b&&v(String(a),"warn")),()=>{b=!0,N.current=null,d?.disconnect()}},[a,v]);let O=(0,i.useMemo)(()=>{if(!d)return{};let a=eT(()=>(function(a,b={}){let c=b.notation??"crowsfoot",d=b.hSpacing??70,e=b.vSpacing??("chen"===c?130:90),f="chen"===c?aj:as,g=[],h=new Set;for(let b of a.entities??[])!b?.name||h.has(b.name)||(h.add(b.name),g.push(b));let i=new Map,j=(a,b,c=new Set)=>a===b||!c.has(a)&&(c.add(a),(i.get(a)??[]).some(a=>j(a,b,c)));for(let b of a.relationships??[]){if(!b||!h.has(b.from)||!h.has(b.to)||b.from===b.to)continue;let[a,c]="N:1"===b.cardinality?[b.to,b.from]:[b.from,b.to];if((i.get(a)??[]).includes(c)||j(c,a))continue;let d=i.get(a);d?d.push(c):i.set(a,[c])}let k=new Map,l=(a,b)=>{if(!((k.get(a)??-1)>=b))for(let c of(k.set(a,b),i.get(a)??[]))l(c,b+1)},m=new Set([...i.values()].flat());for(let a of g)m.has(a.name)||l(a.name,0);for(let a of g)k.has(a.name)||l(a.name,0);for(let a of[...g].sort((a,b)=>k.get(b.name)-k.get(a.name))){let b=i.get(a.name)??[];b.length&&k.set(a.name,Math.min(...b.map(a=>k.get(a)))-1)}let n=[],o=new Map,p=(a,b)=>((n[b]??=[]).push(a),o.set(a.id,a),a);for(let a of g)p({id:a.name,entity:a.name,...f(a),upper:[],lower:[],x:0},k.get(a.name)??0);let q=0;for(let[a,b]of i)for(let c of b){let b=a;for(let d=k.get(a)+1;d<k.get(c);d++){let a=p({id:`\u0000lane${q++}`,width:28,height:0,upper:[],lower:[],x:0},d);o.get(b).lower.push(a.id),a.upper.push(b),b=a.id}o.get(b).lower.push(c),o.get(c).upper.push(b)}for(let a=n.length-1;a>=0;a--)n[a]?.length||n.splice(a,1);let r=(a,b)=>a.length?a.reduce((a,c)=>a+b(o.get(c)),0)/a.length:null,s=(a,b)=>{let c=new Map;for(let a of n)a.forEach((a,b)=>c.set(a.id,b));let d=new Map(a.map((a,d)=>[a.id,r(a[b],a=>c.get(a.id))??d]));a.sort((a,b)=>d.get(a.id)-d.get(b.id))};for(let a=0;a<2;a++){for(let a=1;a<n.length;a++)s(n[a],"upper");for(let a=n.length-2;a>=0;a--)s(n[a],"lower")}let t=a=>a.x+a.width/2,u=(a,b)=>{let c=0;for(let e of a){let a=r(e[b],t);e.x=Math.max(c,null===a?c:a-e.width/2),c=e.x+e.width+d}};for(let a of n)u(a,"upper");for(let a=n.length-2;a>=0;a--)u(n[a],"lower");let v=Math.min(0,...[...o.values()].map(a=>a.x)),w={},x=40;for(let a of n){for(let b of a)b.entity&&(w[b.entity]={x:Math.round(b.x-v)+40,y:x,width:b.width,height:b.height});x+=Math.max(0,...a.map(a=>a.height))+e}return w})(d,{notation:j}),{});for(let[b,c]of Object.entries(f))a[b]&&(a[b]={...a[b],...c});return a},[d,f,j]),P=(0,i.useMemo)(()=>{if(!d)return[];let a="";return eT(()=>Y(d),null,b=>a=b)??[{ruleId:"E000",message:`The document could not be checked (${a}): a field is not the shape Spec 80 gives it`}]},[d]),R=(0,i.useMemo)(()=>P.map(a=>(a.element??"").split(/[.[]/)[0]).filter(Boolean),[P]),T=(0,i.useCallback)(async a=>{let c;if(d&&b){try{c=a(d)}catch(a){return v(a instanceof Error?a.message:String(a),"warn")}e(c),L(null);try{let a=await fetch(`/api/file${(0,d4.docQuery)(b)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(c,null,2)+"\n"})});if(!a.ok)throw Error((await a.json())?.error??`HTTP ${a.status}`);N.current?.emitFull(c),v("saved")}catch(a){v(`not saved: ${a instanceof Error?a.message:String(a)}`,"warn")}}},[d,b,v]),U=(0,i.useCallback)((a,c)=>{g(d=>{let e={...d,[a]:{x:Math.round(c.x),y:Math.round(c.y)}};try{localStorage.setItem(eU(b,j),JSON.stringify(e))}catch{}return e})},[b,j]),Z=()=>{g({});try{localStorage.removeItem(eU(b,j))}catch{}q(a=>a+1)},af=async()=>{if(!d)return;v("checking links…");let a=await eY(b);if(0===a.length)return L("none"),z("issues"),B(!0),v("no .smdf.json beside this document to check against","warn");let c=a.flatMap(a=>$(a.def,d).map(b=>({...b,message:`${a.def.settings?.name??a.path}: ${b.message}`})));c.push(..._(d,a.map(a=>a.def.settings?.name??""))),L(c),z("issues"),B(!0),F(!1),v(`checked ${a.length} machine(s): ${c.length} problem(s)`,c.length?"warn":"ok")},ag=async a=>{let c=(await eY(b)).find(b=>b.def.settings?.name===a);c?(0,d4.navigateToDoc)(c.path):v(`no .smdf.json beside this document defines '${a}'`,"warn")},ah=()=>{let a=G.current?.getBoundingClientRect();return{width:a?.width??0,height:a?.height??0}},ai=a=>{let{width:b,height:c}=ah();o(d=>Q(d,a,{x:b/2,y:c/2}))},al=a=>{let b=O[a],{width:c,height:d}=ah();b&&c&&(o(S([b],c,d,{padding:28,maxScale:1.25})),s(a),H.close())},ap=eC(),ar=ez("focus"),at=(0,i.useMemo)(()=>d?eT(()=>(function(a,b,c={}){let d=!1!==c.rows,e=[];for(let c of a?.entities??[]){let a=c?.name?b[c.name]:void 0;a&&(e.push({focus:`entity:${c.name}`,box:a}),(c.attributes??[]).filter(a=>a?.name).forEach((b,f)=>{e.push({focus:`attribute:${c.name}.${b.name}`,box:d?{x:a.x,y:a.y+30+20*f,width:a.width,height:20}:a})}))}return e})(d,O,{rows:"chen"!==j}),[]):[],[d,O,j]),au=(0,i.useRef)(-1);(0,i.useEffect)(()=>{if(!d||au.current===ap.nonce)return;au.current=ap.nonce;let a=ap.focus?a8(ap.focus):null,b=a?.kind==="entity"?a.name:a?.kind==="attribute"?a.name.split(".")[0]:null;b&&O[b]&&al(b)},[d,ap,O]),(0,i.useEffect)(()=>{r&&1&&eB(`entity:${r}`)},[r]);let av=d?.entities.find(a=>a.name===r)??null,aw=b.split("/").pop()||"…",ax=Array.isArray(K)?K:[],ay=P.length+ax.length,az=[{id:"entities",label:"Entities",icon:"▭"},{id:"relations",label:"Relations",icon:"⟷"},{id:"notes",label:"Notes",icon:"✎",badge:void 0},{id:"issues",label:"Issues",icon:(0,h.jsx)(et,{}),badge:ay||void 0}],aA=a=>y===a?"":"hidden md:block",aB=()=>{d&&navigator.clipboard?.writeText(function(a){let b=["erDiagram"],c=" ",d=new Set;for(let e of a.relationships??[]){if(!e?.from||!e?.to)continue;let a=ak[e.cardinality]??ak["1:N"];b.push(`${c}${am(e.from)} ${a} ${am(e.to)} : ${ao(e.label??"")}`),d.add(e.from),d.add(e.to)}let e=new Set;for(let f of a.entities??[]){if(!f?.name||e.has(f.name))continue;e.add(f.name);let a=(f.attributes??[]).filter(a=>a?.name);if(0===a.length){d.has(f.name)||b.push(`${c}${am(f.name)}`);continue}for(let d of(b.push(`${c}${am(f.name)} {`),a))b.push(`${c}${c}${function(a){let b=[];"pk"===a.key&&b.push("PK"),"uk"===a.key&&b.push("UK"),a.references&&b.push("FK");let c=[],d=V(a);d.length&&c.push(`stateOf ${d.join(", ")}`),a.description&&c.push(a.description);let e=[an(a.type??"","unknown"),an(a.name,"unnamed")];return b.length&&e.push(b.join(", ")),c.length&&e.push(ao(c.join(" — "))),e.join(" ")}(d)}`);b.push(`${c}}`)}return b.join("\n")}(d)).then(()=>v("mermaid copied"))};return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&D(!1),children:[(0,h.jsxs)("header",{className:"relative z-40 flex items-center gap-2 border-b border-gray-800 bg-gray-900 px-2 py-1.5 text-xs md:px-3 md:py-2",children:[(0,h.jsx)("span",{className:"font-semibold text-blue-300",children:"ERD"}),(0,h.jsx)(d5,{}),(0,h.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:b,children:[d?.settings.name??aw,(0,h.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",aw]})]}),(0,h.jsx)("span",{className:"inline-flex shrink-0 overflow-hidden rounded border border-gray-700",role:"group","aria-label":"Notation",children:[["crowsfoot","▤","Crow's foot — attributes listed inside the entity box"],["chen","◇","Chen — attributes as ovals, relationships as diamonds"]].map(([a,c,d])=>(0,h.jsx)("button",{title:d,"aria-label":d,"aria-pressed":j===a,onClick:()=>(a=>{if(a!==j){try{localStorage.setItem(eV,a)}catch{}k(a),g(eX(b,a)),q(a=>a+1)}})(a),className:`px-2.5 py-1.5 text-sm leading-none md:px-2 md:py-1 ${j===a?"bg-blue-900/60 text-blue-200":"bg-gray-800 text-gray-400 hover:bg-gray-700"}`,children:c},a))}),(0,h.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,h.jsx)("button",{className:e$,onClick:Z,title:"Forget the dragged positions and lay the board out again",children:"⤢ Arrange"}),(0,h.jsx)("button",{className:e$,onClick:af,title:"Check the state machines beside this document against it",children:"Check links"}),(0,h.jsx)("button",{className:e$,onClick:aB,children:"Copy mermaid"}),(0,h.jsx)("button",{className:e$,onClick:()=>F(a=>!a),"aria-pressed":!E,title:E?"Show the panel":"Hide the panel — the board takes the full width",children:E?"⟨ Panel":"Panel ⟩"})]}),(0,h.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,h.jsx)("button",{className:"rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-sm leading-none text-gray-200","aria-label":"More actions","aria-expanded":C,onClick:a=>{a.stopPropagation(),D(a=>!a)},children:"⋯"}),C&&(0,h.jsx)("div",{className:"absolute right-0 top-full z-50 mt-1 w-56 overflow-hidden rounded-lg border border-gray-700 bg-gray-900 py-1 shadow-xl",children:[["⤢ Arrange the board",Z],["Check links to the machines",af],["Copy as mermaid",aB]].map(([a,b])=>(0,h.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{D(!1),b()},children:a},a))})]})]}),(0,h.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,h.jsxs)("div",{ref:G,className:"relative min-w-0 flex-1 overflow-hidden",children:[d&&(0,h.jsx)(es,{what:"diagram",resetKey:d,children:(0,h.jsx)(bL,{definition:d,notation:j,positions:O,viewport:n,onViewportChange:o,selection:r,readOnly:l,errorElements:R,fitKey:p,onSelect:s,onClearSelection:()=>s(null),onEntityMove:U,onOpenMachine:ag,emptyHint:"No entities yet — add one in the panel, or let an agent call add_entity."})}),d&&(0,h.jsx)(eR,{docPath:b||null,kind:"erd",viewport:n,setViewport:o,boxes:at,boardRef:G,focus:ar}),(0,h.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 flex max-w-[75%] items-center gap-1.5 rounded bg-gray-950/70 px-1.5 py-0.5 text-[11px] ${"warn"===t.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,h.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===t.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,h.jsxs)("span",{className:`truncate transition-opacity duration-500 ${w&&"ok"===t.tone?"opacity-0":"opacity-100"}`,children:[t.text,I>1?` \xb7 ${I} in the room`:""]})]}),(0,h.jsxs)("div",{className:"absolute bottom-3 right-3 flex flex-col overflow-hidden rounded-lg border border-gray-700 bg-gray-900/90 shadow-lg backdrop-blur",children:[(0,h.jsx)("button",{title:l?"Shapes are locked: dragging moves the view. Tap to unlock.":"Lock the shapes in place, so dragging only moves the view","aria-label":"Lock shapes in place","aria-pressed":l,onClick:()=>{let a=!l;m(a);try{localStorage.setItem(eW,a?"1":"0")}catch{}v(a?"shapes locked — a drag anywhere moves the view":"shapes unlocked — drag one to move it")},className:`flex h-10 w-10 items-center justify-center border-b border-gray-800 hover:bg-gray-800 md:h-8 md:w-8 ${l?"bg-blue-950/60 text-blue-300":"text-gray-400"}`,children:(0,h.jsx)(eu,{locked:l})}),[["+","Zoom in",()=>ai(1.25)],["−","Zoom out",()=>ai(.8)],["⛶","Fit the whole diagram",()=>q(a=>a+1)]].map(([a,b,c])=>(0,h.jsx)("button",{title:b,"aria-label":b,onClick:c,className:"h-10 w-10 border-b border-gray-800 text-base leading-none text-gray-200 last:border-b-0 hover:bg-gray-800 md:h-8 md:w-8 md:text-sm",children:a},b))]}),av&&!A&&(0,h.jsxs)("button",{className:"absolute bottom-3 left-1/2 max-w-[60%] -translate-x-1/2 truncate rounded-full border border-blue-500/60 bg-gray-900/95 px-4 py-2 text-sm text-blue-200 shadow-lg md:hidden",onClick:()=>{z("entities"),B(!0)},children:["✎ ",av.name]})]}),A&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:H.close,"aria-hidden":"true"}),d&&(0,h.jsxs)("aside",{style:H.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 flex h-[var(--sheet-h)] flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${A?"translate-y-0":"pointer-events-none translate-y-full"} md:pointer-events-auto md:static md:z-auto md:h-auto md:w-80 md:translate-y-0 md:rounded-none md:border-l md:border-t-0 md:shadow-none md:transition-none ${E?"md:hidden":""}`,children:[(0,h.jsxs)("div",{className:"md:hidden",...H.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:az.find(a=>a.id===y)?.label}),(0,h.jsx)("button",{onClick:H.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,h.jsxs)("section",{className:aA("entities"),children:[(0,h.jsx)("div",{className:e_,style:{marginTop:0},children:"Entities"}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:d.entities.map(a=>(0,h.jsx)("button",{className:`${e$} ${r===a.name?"border-blue-500 text-blue-300":""}`,onClick:()=>s(a.name),children:a.name},a.name))}),(0,h.jsx)(e2,{fields:[{name:"name",placeholder:"new entity"}],submit:"+ Entity",onSubmit:a=>{T(b=>ad(b,{name:a.name.trim()})),s(a.name.trim())}}),av&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:`${e_} flex items-center justify-between gap-2`,children:[(0,h.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:av.name}),(0,h.jsx)("button",{className:`${e$} normal-case tracking-normal`,onClick:()=>al(av.name),title:"Bring this entity to the middle of the board at a readable size",children:"◎ Show on board"})]}),(0,h.jsxs)("label",{className:"mb-1 flex items-center gap-2 text-[11px] text-gray-400",title:"Exists only through another entity (an order line, without its order). Chen draws it as a double rectangle.",children:[(0,h.jsx)("input",{type:"checkbox",checked:!!av.weak,onChange:a=>T(b=>ae(b,av.name,{weak:a.target.checked}))}),"weak entity"]}),(av.attributes??[]).map(a=>(0,h.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 font-mono text-[11px]",children:[(0,h.jsxs)("span",{className:a.stateOf?"text-blue-300":"text-gray-300",children:[a.name," : ",a.type,(0,h.jsxs)("span",{className:"text-gray-500",children:[a.key?` ${a.key.toUpperCase()}`:"",a.references?` → ${a.references}`:"",a.stateOf?` ◉ ${[a.stateOf].flat().join(", ")}`:""]})]}),(0,h.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":`Remove ${a.name}`,onClick:()=>T(b=>(function(a,b,c){let d=aa(a),e=ab(d,b),f=e.attributes?.length??0;if(e.attributes=(e.attributes??[]).filter(a=>a.name!==c),e.attributes.length===f)throw Error(`Attribute '${b}.${c}' not found.`);return d})(b,av.name,a.name)),children:"✕"})]},a.name)),(0,h.jsx)(e2,{fields:[{name:"name",placeholder:"attribute"},{name:"type",placeholder:"type",initial:"string"},{name:"key",options:["","pk","uk"]},{name:"references",placeholder:"references Entity.attr"},{name:"stateOf",placeholder:"stateOf Machine"}],submit:"+ Attribute",onSubmit:a=>T(b=>(function(a,b,c){if(!c.name?.trim())throw Error("An attribute needs a name.");let d=aa(a),e=ab(d,b);if(e.attributes??=[],e.attributes.some(a=>a.name===c.name))throw Error(`Attribute '${b}.${c.name}' already exists.`);return e.attributes.push(ac({...c})),d})(b,av.name,{name:a.name.trim(),type:a.type.trim()||"string",key:"pk"===a.key||"uk"===a.key?a.key:void 0,references:a.references.trim()||void 0,stateOf:a.stateOf.trim()||void 0}))}),(0,h.jsxs)("button",{className:`${e$} mt-2 text-red-300`,onClick:()=>{T(a=>{var b;let c;return b=av.name,ab(c=aa(a),b),c.entities=c.entities.filter(a=>a.name!==b),c.relationships=c.relationships.filter(a=>a.from!==b&&a.to!==b),c}),s(null)},children:["🗑 Delete ",av.name]})]})]}),(0,h.jsxs)("section",{className:aA("relations"),children:[(0,h.jsx)("div",{className:`${e_} max-md:mt-0`,children:"Relationships"}),0===d.relationships.length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),d.relationships.map((a,b)=>(0,h.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 text-[11px] text-gray-300",children:[(0,h.jsxs)("span",{children:[a.from," ",(0,h.jsx)("span",{className:"text-gray-500",children:a.cardinality})," ",a.to,a.label?(0,h.jsxs)("span",{className:"text-gray-500",children:[" : ",a.label]}):null]}),(0,h.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":"Remove relationship",onClick:()=>T(b=>(function(a,b,c,d){let e=aa(a),f=e.relationships.length;if(e.relationships=e.relationships.filter(a=>a.from!==b||a.to!==c||void 0!==d&&a.label!==d),e.relationships.length===f)throw Error(`No relationship from '${b}' to '${c}'${void 0===d?"":` labelled '${d}'`}.`);return e})(b,a.from,a.to,a.label)),children:"✕"})]},b)),d.entities.length>0&&(0,h.jsx)(e2,{fields:[{name:"from",options:d.entities.map(a=>a.name)},{name:"cardinality",options:[...W],initial:"1:N"},{name:"to",options:d.entities.map(a=>a.name)},{name:"label",placeholder:"label (a verb)"}],submit:"+ Relationship",onSubmit:a=>T(b=>(function(a,b){let c=aa(a);if(ab(c,b.from),ab(c,b.to),!W.includes(b.cardinality))throw Error(`Cardinality '${b.cardinality}' is not one of ${W.join(", ")}.`);return c.relationships.push(ac({...b})),c})(b,{from:a.from,to:a.to,cardinality:a.cardinality,label:a.label.trim()||void 0}))})]}),(0,h.jsxs)("section",{className:aA("notes"),children:[(0,h.jsx)("div",{className:`${e_} max-md:mt-0`,children:"Notes"}),(0,h.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the document, for whoever opens it next — you, or an agent (it reads them with get_notes)."}),(0,h.jsx)(e1,{label:"On this diagram",value:d.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:a=>T(b=>(function(a,b){let c=aa(a);for(let a of["description","notes"]){let d=b[a];void 0!==d&&(d.trim()?c.settings[a]=d:delete c.settings[a])}return c})(b,{notes:a}))},"diagram"),av?(0,h.jsx)(e1,{label:`On ${av.name}`,value:av.notes??"",placeholder:`A question or a decision about ${av.name}…`,onSave:a=>T(b=>ae(b,av.name,{notes:a}))},`entity:${av.name}`):(0,h.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Select an entity to leave a note on it."}),d.entities.some(a=>a.notes?.trim())&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:e_,children:"Entities with notes"}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:d.entities.filter(a=>a.notes?.trim()).map(a=>(0,h.jsx)("button",{className:`${e$} ${r===a.name?"border-blue-500 text-blue-300":""}`,onClick:()=>s(a.name),children:a.name},a.name))})]})]}),(0,h.jsxs)("section",{className:aA("issues"),children:[(0,h.jsx)("div",{className:`${e_} max-md:mt-0 ${0===ay&&!K?"md:hidden":""}`,children:"Issues"}),P.map((a,b)=>(0,h.jsxs)("div",{className:"py-0.5 text-[11px] text-red-300",children:["[",a.ruleId,"] ",a.message]},`p${b}`)),ax.map((a,b)=>(0,h.jsxs)("div",{className:"py-0.5 text-[11px] text-amber-300",children:["[",a.ruleId,"] ",a.message]},`l${b}`)),"none"===K&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-amber-300",children:"No state machine (.smdf.json) sits beside this document, so there was nothing to check it against."}),0===ay&&"none"!==K&&(0,h.jsx)("div",{className:`py-0.5 text-[11px] ${K?"text-green-400":"text-gray-600 md:hidden"}`,children:K?"Every name the machines use resolves.":"The document is valid. “Check links” (⋯) holds the state machines beside it against it."})]})]})]})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:az.map(a=>{let b=A&&y===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(A&&y===b?H.close():B(!0),z(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1/2 top-1 min-w-[16px] translate-x-5 rounded-full border border-red-900/80 bg-red-950/80 px-1 text-[10px] leading-4 text-red-200",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})})]})}function e1({label:a,value:b,placeholder:c,onSave:d}){let[e,f]=(0,i.useState)(b),[g,j]=(0,i.useState)(b),[k,l]=(0,i.useState)(!1);b!==g&&(j(b),k||f(b));let m=(0,i.useRef)(null),n=a=>{m.current&&clearTimeout(m.current),m.current=null,a!==b&&d(a)};return(0,h.jsxs)("label",{className:"mt-2 block",children:[(0,h.jsx)("span",{className:"text-[11px] text-gray-500",children:a}),(0,h.jsx)("textarea",{className:`${eZ} h-24 resize-y leading-snug`,placeholder:c,value:e,onChange:a=>{let b=a.target.value;f(b),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>n(b),900)},onFocus:()=>l(!0),onBlur:()=>{l(!1),n(e)}})]})}function e2({fields:a,submit:b,onSubmit:c}){let d=()=>Object.fromEntries(a.map(a=>[a.name,a.initial??a.options?.[0]??""])),[e,f]=(0,i.useState)(d),g=a[0];return(0,h.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:b=>{b.preventDefault();let h={...d(),...e};h[g.name]?.trim()&&(c(h),f(b=>Object.fromEntries(a.map(a=>[a.name,a.options?b[a.name]??"":a.initial??""]))))},children:[a.map(a=>a.options?(0,h.jsx)("select",{className:eZ,"aria-label":a.name,value:e[a.name]??"",onChange:b=>f(c=>({...c,[a.name]:b.target.value})),children:a.options.map(b=>(0,h.jsx)("option",{value:b,children:b||`(${a.name})`},b))},a.name):(0,h.jsx)("input",{className:eZ,"aria-label":a.name,placeholder:a.placeholder,value:e[a.name]??"",onChange:b=>f(c=>({...c,[a.name]:b.target.value}))},a.name)),(0,h.jsx)("button",{type:"submit",className:`${e$} ${1===a.length?"":"col-span-2"}`,children:b})]})}let e3="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",e4="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",e5="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function e6({id:a,fields:b,submit:c,onSubmit:d,reset:e=!1,required:f}){let g=()=>Object.fromEntries(b.map(a=>[a.name,a.initial??(!a.checkbox&&(a.options?a.options[0]??"":""))])),[j,k]=(0,i.useState)(g),l=(a,b)=>k(c=>({...c,[a]:b}));return(0,h.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:a=>{a.preventDefault();let c={...g(),...j};!(f??[]).some(a=>!String(c[a]??"").trim())&&(d(c),e&&k(a=>Object.fromEntries(b.map(b=>[b.name,b.options||b.checkbox?a[b.name]??"":b.initial??""]))))},children:[b.map(b=>{let c=b.label??b.name;if(b.checkbox)return(0,h.jsxs)("label",{className:"flex items-center gap-2 text-[11px] text-gray-400",children:[(0,h.jsx)("input",{type:"checkbox",checked:!!j[b.name],onChange:a=>l(b.name,a.target.checked)}),c]},b.name);if(b.options)return(0,h.jsx)("select",{className:`${e3} ${b.wide?"col-span-2":""}`,"aria-label":c,title:c,value:String(j[b.name]??""),onChange:a=>l(b.name,a.target.value),children:b.options.map(a=>(0,h.jsx)("option",{value:a,children:a||`(${c})`},a))},b.name);let d=b.suggest?.length?`${a}-${b.name}`:void 0;return(0,h.jsxs)("span",{className:b.wide?"col-span-2":"",children:[(0,h.jsx)("input",{className:e3,"aria-label":c,title:c,placeholder:b.placeholder??c,list:d,value:String(j[b.name]??""),onChange:a=>l(b.name,a.target.value)}),d&&(0,h.jsx)("datalist",{id:d,children:b.suggest.map(a=>(0,h.jsx)("option",{value:a},a))})]},b.name)}),(0,h.jsx)("button",{type:"submit",className:`${e4} col-span-2`,children:c})]})}function e7({kind:a,size:b=16}){return(0,h.jsxs)("svg",{width:b,height:b,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"shrink-0",children:["erd"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("rect",{x:"4",y:"4.5",width:"16",height:"15",rx:"1.5"}),(0,h.jsx)("path",{d:"M4 9h16M8 13h8M8 16.5h6"})]}),"machine"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("rect",{x:"2.5",y:"4",width:"8",height:"6",rx:"2.5"}),(0,h.jsx)("rect",{x:"13.5",y:"14",width:"8",height:"6",rx:"2.5"}),(0,h.jsx)("path",{d:"M6.5 10v4.5a2.5 2.5 0 0 0 2.5 2.5h4.5"}),(0,h.jsx)("path",{d:"M11.5 15l2 2-2 2"})]}),"sequence"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("path",{d:"M6 4v16M18 4v16",strokeDasharray:"2 2.2"}),(0,h.jsx)("path",{d:"M6 9h11M15 7l2 2-2 2"}),(0,h.jsx)("path",{d:"M18 15H7M9 13l-2 2 2 2"})]}),"system"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("rect",{x:"3",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,h.jsx)("rect",{x:"14",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,h.jsx)("rect",{x:"8.5",y:"14.5",width:"7",height:"6",rx:"1.5"}),(0,h.jsx)("path",{d:"M10 6.5h4M7 9.5l3 5M17 9.5l-3 5"})]}),"link"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("path",{d:"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1.2 1.2"}),(0,h.jsx)("path",{d:"M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1.2-1.2"})]}),"actor"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("circle",{cx:"12",cy:"7.5",r:"3.5"}),(0,h.jsx)("path",{d:"M5 20a7 7 0 0 1 14 0"})]})]})}let e8=["text-sky-300","text-emerald-300","text-amber-300","text-rose-300","text-violet-300","text-cyan-300","text-lime-300","text-orange-300"],e9=a=>`seq-read-${a.kind}-${a.id}`;function fa({definition:a,selection:b,issues:c,onSelect:d,onShowInDiagram:e}){let f=new Map(a.participants.map((a,b)=>[a.name,e8[b%e8.length]])),g=az(a),i=g.filter(a=>null===a.fragment),j=(a.fragments??[]).map((a,b)=>({f:a,fi:b,rows:g.filter(a=>a.fragment===b)})),k=(a,c)=>b?.kind===a&&b.id===c,l=a=>(0,h.jsx)("span",{className:`font-semibold ${f.get(a)??"text-gray-300"}`,children:a||"?"}),m=(a,b)=>{let f={kind:"message",id:a},g=c.get(`message:${a}`)??[],i=g.some(a=>"error"===a.severity)?"error":g.length?"warning":null,j=k("message",a);return(0,h.jsx)("li",{id:e9(f),className:"scroll-mt-16 scroll-mb-24",children:(0,h.jsxs)("div",{role:"button",tabIndex:0,"aria-pressed":j,onClick:()=>d(f),onKeyDown:a=>("Enter"===a.key||" "===a.key)&&(a.preventDefault(),d(f)),className:`flex gap-3 rounded-lg border-l-2 px-3 py-2.5 ${j?"bg-blue-950/60 ring-1 ring-blue-500/60":"hover:bg-gray-900"} ${"error"===i?"border-red-500":"warning"===i?"border-amber-400":"border-transparent"}`,children:[(0,h.jsx)("span",{className:"mt-0.5 flex h-6 min-w-6 shrink-0 items-center justify-center rounded-full border border-gray-700 bg-gray-900 px-1 font-mono text-[11px] text-gray-300",children:a}),(0,h.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,h.jsxs)("div",{className:"text-[13px] leading-5 text-gray-400",children:[l(b.from),b.from===b.to?(0,h.jsx)("span",{children:" to itself"}):(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("span",{className:"px-1.5 text-gray-500",children:b.reply?"⇠":"→"}),l(b.to)]}),b.reply&&(0,h.jsx)("span",{className:"ml-2 text-[11px] text-gray-500",children:"reply"}),b.optional&&(0,h.jsx)("span",{className:"ml-2 rounded border border-gray-700 px-1 text-[11px] text-gray-400",children:"optional"})]}),(0,h.jsx)("div",{className:`mt-0.5 break-words text-[15px] leading-6 ${b.reply?"text-gray-300":"text-gray-100"}`,children:b.label||(0,h.jsx)("span",{className:"text-gray-500",children:"no label"})}),(b.event||b.state||b.carries)&&(0,h.jsxs)("div",{className:"mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] leading-5",children:[b.event&&(0,h.jsx)("span",{className:"rounded border border-blue-500/50 bg-blue-950/50 px-1.5 font-mono text-blue-200",children:b.event}),b.event&&b.machine&&(0,h.jsxs)("span",{className:"text-gray-400",children:["on ",b.machine]}),b.state&&(0,h.jsxs)("span",{className:"text-emerald-300",children:["→ ",b.state]}),b.carries&&(0,h.jsxs)("span",{className:"text-gray-400",children:["carries ",b.carries]})]}),g.map((a,b)=>(0,h.jsx)("p",{className:`mt-1.5 text-[12px] leading-5 ${"error"===a.severity?"text-red-300":"text-amber-300"}`,children:a.text},b)),j&&(0,h.jsx)("button",{className:"mt-2 rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-[12px] text-gray-200",onClick:a=>{a.stopPropagation(),e(f)},children:"Show in the diagram"})]})]})},a)};return(0,h.jsx)("div",{className:"h-full overflow-y-auto overscroll-contain",children:(0,h.jsxs)("div",{className:"mx-auto max-w-2xl px-4 pb-28 pt-10",children:[a.participants.length>0&&(0,h.jsx)("ul",{className:"mb-4 flex flex-wrap gap-2","aria-label":"Participants",children:a.participants.map(a=>{let b={kind:"participant",id:a.name},e=a.actor?"actor":a.object?"object":a.service?"service":"",f=c.get(`participant:${a.name}`)??[];return(0,h.jsx)("li",{id:e9(b),children:(0,h.jsxs)("button",{onClick:()=>d(b),"aria-pressed":k("participant",a.name),title:f.map(a=>a.text).join("\n")||void 0,className:`rounded-full border px-3 py-1 text-[13px] ${k("participant",a.name)?"border-blue-500 bg-blue-950/60":"border-gray-700 bg-gray-900"} ${f.length?"ring-1 ring-amber-400/70":""}`,children:[l(a.name),e&&(0,h.jsx)("span",{className:"ml-1.5 text-[11px] text-gray-400",children:e})]})},a.name)})}),0===g.length&&(0,h.jsx)("p",{className:"text-sm text-gray-400",children:"No messages yet — add them in the panel, or let an agent write the scenario."}),(0,h.jsx)("ol",{className:"flex flex-col gap-1",children:i.map(({ref:a,message:b})=>m(a,b))}),j.map(({f:a,fi:b,rows:c})=>(0,h.jsxs)("section",{className:"mt-5 rounded-xl border border-indigo-500/50 bg-indigo-950/20 p-1.5",children:[(0,h.jsxs)("header",{className:"px-3 pb-1.5 pt-2",children:[(0,h.jsxs)("div",{className:"text-[12px] text-indigo-200",children:[(0,h.jsx)("span",{className:"font-semibold uppercase tracking-wide",children:a.kind}),(0,h.jsxs)("span",{className:"text-indigo-300",children:[" · after ",a.after]})]}),(0,h.jsx)("div",{className:"mt-0.5 break-words text-[14px] leading-5 text-gray-100",children:a.label})]}),0===c.length?(0,h.jsx)("p",{className:"px-3 pb-2 text-[12px] text-gray-400",children:"No messages in this fragment."}):(0,h.jsx)("ol",{className:"flex flex-col gap-1",children:c.map(({ref:a,message:b})=>m(a,b))})]},b))]})})}async function fb(a){try{let b=await fetch(`/api/file${(0,d4.docQuery)(a)}`,{cache:"no-store"}),c=await b.json();if(!b.ok||c.error)return{path:a??"",content:null,exists:!1,error:c.error??`HTTP ${b.status}`};return{path:c.path??a??"",content:c.content??null,exists:!!c.exists,mtime:c.mtime}}catch(b){return{path:a??"",content:null,exists:!1,error:b instanceof Error?b.message:String(b)}}}class fc extends Error{constructor(a){super(`${a.split("/").pop()} changed on disk since it was read`)}}async function fd(a,b,c){let d=await fetch(`/api/file${(0,d4.docQuery)(a)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(b,null,2)+"\n",...void 0!==c?{mtime:c}:{}})}),e=await d.json().catch(()=>({}));if(409===d.status)throw new fc(a);if(!d.ok)throw Error(e?.error??`HTTP ${d.status}`);return e?.mtime}async function fe(a){let b=await fb(a),c={path:b.path||a,def:null,members:[],absOf:{},wrapped:{},mtimes:{}};if(b.error)return{...c,error:b.error};if(!b.exists||!b.content)return{...c,error:`${a} does not exist`};let d=null;try{let a=aq(JSON.parse(b.content));aR(a)&&(d=a)}catch{}if(!d)return{...c,error:`${b.path} is not a readable system definition`};let e={},f={},g={[b.path]:b.mtime??0},h=await Promise.all((d.members??[]).filter(a=>a?.path).map(async a=>{let c=aV(b.path,a.path);e[a.path]=c;let d=aS(a.path),h=await fb(c);if(h.error)return{path:a.path,kind:d,def:null,error:h.error};if(!h.exists||!h.content)return{path:a.path,kind:d,def:null,error:"the file does not exist"};g[a.path]=h.mtime??0;try{let b=JSON.parse(h.content);if("machine"===d&&b&&(b.stateMachine||b.StateMachine))return f[a.path]=!0,{path:a.path,kind:d,def:aq(b.stateMachine??b.StateMachine)};return{path:a.path,kind:d,def:aq(b)}}catch(b){return{path:a.path,kind:d,def:null,error:`not JSON: ${b instanceof Error?b.message:String(b)}`}}}));return{path:b.path,def:d,members:h,absOf:e,wrapped:f,mtimes:g}}function ff(){window.dispatchEvent(new Event(ex))}function fg(a){let[b,c]=(0,i.useState)(null),[d,e]=(0,i.useState)(0),f=(0,i.useCallback)(()=>e(a=>a+1),[]);return(0,i.useEffect)(()=>(window.addEventListener(ex,f),()=>window.removeEventListener(ex,f)),[f]),(0,i.useEffect)(()=>{if(!a)return;let b=!0;return fe(a).then(d=>b&&c({for:a,system:d})),()=>{b=!1}},[a,d]),{system:a&&b?.for===a?b.system:null,reload:f}}function fh(a,b){if(!a||!b)return null;for(let[c,d]of Object.entries(a.absOf))if(d===b)return c;return null}async function fi(a,b,c,d){let{bridgeUrl:e}=await ed();if(!e)return;let f=dw({url:e,role:"web",docId:a,name:"web-reconcile",autoResync:!1});try{let a=await Promise.race([f.join(),new Promise((a,b)=>setTimeout(()=>b(Error("join timeout")),3e3))]),e=a.snapshot?.def,g=a=>(function(a){let b=JSON.stringify(a),c=0x811c9dc5;for(let a=0;a<b.length;a++)c^=b.charCodeAt(a),c=Math.imul(c,0x1000193);return(c>>>0).toString(16).padStart(8,"0")})(a);if(e&&g(e)===g(b))return;await new Promise(a=>{let h=f.on("ack",()=>{h(),a()});d&&e&&g(e)===g(d.from)?f.emitPatch(d.ops,c):f.emitFull(b,c),setTimeout(a,800)})}catch{}finally{f.disconnect()}}async function fj(a,b){let c=[],d=[],e=[],f=async(a,b)=>{try{await b(),c.push(a)}catch(b){b instanceof fc?e.push(a):d.push(`${a}: ${b instanceof Error?b.message:String(b)}`)}};for(let c of b.machines){let b=a.absOf[c.member];b&&c.ops.length&&await f(c.member,async()=>{let d=a.wrapped[c.member]?{stateMachine:c.def}:c.def,e=await fd(b,d,a.mtimes[c.member]),f=a.members.find(a=>a.path===c.member)?.def;await fi(b,c.def,e,{from:f,ops:c.ops})})}for(let c of b.erds){let b=a.absOf[c.member];b&&await f(c.member,async()=>{let d=await fd(b,c.def,a.mtimes[c.member]);await fi(b,c.def,d)})}return b.system&&await f(a.path.split("/").pop()??a.path,async()=>{let c=await fd(a.path,b.system.def,a.mtimes[a.path]);await fi(a.path,b.system.def,c)}),ff(),{written:c,failed:d,conflicts:e}}async function fk(a){let b={result:null,written:[],failed:[],conflicts:[]};for(let c=0;c<2;c+=1){let d=await fe(a);if(!d.def)return{...b,failed:[d.error??"the system could not be read"],retried:c>0};let e=bd(d.def,d.members);if(!e.count)return{...b,result:e,conflicts:c?b.conflicts:[],retried:c>0};let f=await fj(d,e);if(b={result:e,written:[...b.written,...f.written],failed:f.failed,conflicts:f.conflicts},!f.conflicts.length)return{...b,retried:c>0}}return{...b,retried:!0}}let fl="stateloom.sequence.view",fm=["","actor","service","object"],fn=a=>"string"==typeof a?a.trim():"",fo=a=>fn(a).split(",").map(a=>a.trim()).filter(Boolean);function fp(a){return{from:fn(a.from),to:fn(a.to),label:fn(a.label),event:fn(a.event),machine:fn(a.machine),carries:fn(a.carries),state:fn(a.state),description:fn(a.description),optional:!!a.optional||void 0,reply:!!a.reply||void 0}}function fq(){let a,b,c,d=(0,d4.useRequestedDoc)(),e=ez("system"),{system:f}=fg(e),g=eC(),[j,k]=(0,i.useState)(""),[l,m]=(0,i.useState)(null),[n,o]=(0,i.useState)({...M}),[p,q]=(0,i.useState)(void 0),[r,s]=(0,i.useState)(null),[t,u]=(0,i.useState)({text:"loading…",tone:"ok"}),v=(0,i.useCallback)((a,b="ok")=>u({text:a,tone:b}),[]),[w,x]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=setTimeout(()=>x(!0),4e3);return()=>{clearTimeout(a),x(!1)}},[t]);let[y,z]=(0,i.useState)("messages"),[A,B]=(0,i.useState)(!1),[C,D]=(0,i.useState)(!1),[E,F]=(0,i.useState)(!1),[G,H]=(0,i.useState)("diagram"),I=(0,i.useRef)("diagram");(0,i.useEffect)(()=>{let a=null;try{a=window.localStorage.getItem(fl)}catch{}let b="list"===a||"diagram"===a?a:window.matchMedia("(max-width: 767px)").matches?"list":"diagram";I.current=b,H(b)},[]);let J=(0,i.useCallback)(a=>{I.current=a,H(a);try{window.localStorage.setItem(fl,a)}catch{}},[]),K=(0,i.useRef)(null),L=ev({onClose:()=>B(!1),restVh:62,tallVh:92}),[O,P]=(0,i.useState)(0),R=(0,i.useRef)(null),T=(0,i.useRef)(!0),U=(0,i.useRef)(-1);(0,i.useEffect)(()=>{let a=!1,b=null;return(async()=>{let c=await (await fetch(`/api/file${(0,d4.docQuery)(d)}`,{cache:"no-store"})).json();if(a)return;if(c.error)return v(c.error,"warn");let e=c.path??"",f=null;try{let a=c.content?aq(JSON.parse(c.content)):null;av(a)&&(f=a)}catch{}if(c.exists&&!f)return v(`${e} is not a readable sequence definition`,"warn");let g=(e.split("/").pop()??"Untitled").replace(/\.sqdf\.json$/i,"");k(e),m(f??aw("Default",g)),v(c.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:h}=await ed();!a&&h&&(R.current=b=dy({url:h,role:"web",docId:e,name:"web-designer",onFull:a=>{let b=a.def;av(b)&&(m(b),v("updated live"))},onPatch:()=>{},onPresence:a=>P(a.length)}),b.connect())})().catch(b=>!a&&v(String(b),"warn")),()=>{a=!0,R.current=null,b?.disconnect()}},[d,v]);let V=(0,i.useMemo)(()=>l?bR(l):null,[l]),W=(0,i.useMemo)(()=>V?aL(V):null,[V]),X=(0,i.useMemo)(()=>V&&W?eT(()=>(function(a,b){let c=[];for(let a of b.participants)c.push({focus:`participant:${a.name}`,box:{x:a.left,y:a.top,width:a.width,height:Math.max(a.height,b.lifelineBottom-a.top)}});let d=new Map(az(a).map(a=>[a.ref,a.message]));for(let a of b.rows){let b=a.self?a.fromX:Math.min(a.fromX,a.toX),e=a.self?220:Math.max(40,Math.abs(a.toX-a.fromX)),f={x:b-10,y:a.y-24,width:e+20,height:40};c.push({focus:`message:${a.ref}`,box:f});let g=d.get(a.ref)?.event;g&&c.push({focus:`event:${g}`,box:f})}return c})(V,W),[]):[],[V,W]),Y=ez("focus"),Z=(0,i.useMemo)(()=>{if(!l)return[];let a="";return eT(()=>aA(l),null,b=>a=b)??[{ruleId:"S000",message:`The document could not be checked (${a}): a field is not the shape Spec 81 gives it`}]},[l]),$=fh(f,j),_=(0,i.useMemo)(()=>f?.def&&$&&l?eT(()=>a6(f.def,f.members.map(a=>a.path===$?{...a,def:l,error:void 0}:a)),null):null,[f,$,l]),aa=(0,i.useMemo)(()=>(_?.issues??[]).filter(a=>a.member===$&&!/^S0/.test(a.ruleId)),[_,$]),ab=_?.replays.find(a=>a.member===$)?.report??null,ac=(0,i.useMemo)(()=>(function(a){let b={events:new Set,states:new Set,machines:new Set,objects:new Set,entities:new Set,actors:new Set};if(!a)return{events:[],states:[],machines:[],objects:[],entities:[],actors:[]};let{machines:c,erds:d}=a5(a.members);for(let{def:a}of(c.forEach(({def:a},c)=>{for(let d of(b.machines.add(a_(a,c)),a.events??[]))for(let a of[...d?.events??[],...d?.timers??[]])a?.id&&b.events.add(a.id);for(let c of a.settings?.objects??[])c?.instance&&b.objects.add(c.instance);let d=a=>{a&&(b.states.add(a.name),(a.states??[]).forEach(d),(a.parallel?.states??[]).forEach(d))};d(a.state)}),d))for(let c of a.entities??[])c?.name&&b.entities.add(c.name);for(let c of a.def?.actors??[])c?.name&&b.actors.add(c.name);let e=a=>[...a].sort((a,b)=>a.localeCompare(b));return{events:e(b.events),states:e(b.states),machines:e(b.machines),objects:e(b.objects),entities:e(b.entities),actors:e(b.actors)}})(f),[f]),ad=(0,i.useMemo)(()=>{let a=a=>a?/^(message|participant):/.test(a)?a:V?.participants.some(b=>b.name===a)?`participant:${a}`:"":"";return[...Z.map(b=>a(b.element)),...aa.filter(a=>"error"===a.severity).map(b=>a(b.element))].filter(Boolean)},[Z,aa,V]),ae=(0,i.useMemo)(()=>aa.filter(a=>"warning"===a.severity).map(a=>a.element??""),[aa]),af=(0,i.useMemo)(()=>{let a=new Map,b=(b,c)=>{let d=b?/^(message|participant):/.test(b)?b:V?.participants.some(a=>a.name===b)?`participant:${b}`:"":"";d&&a.set(d,[...a.get(d)??[],c])};return Z.forEach(a=>b(a.element,{severity:"error",text:a.message})),aa.forEach(a=>b(a.element,{severity:"error"===a.severity?"error":"warning",text:a.message})),a},[Z,aa,V]),ag=()=>{let a=K.current?.getBoundingClientRect();return{width:a?.width??0,height:a?.height??0}},ah=(0,i.useCallback)(a=>{let b=K.current?.getBoundingClientRect();if(!b?.width)return;let c=N(Math.max(S([a],b.width,b.height,{padding:24,maxScale:1.1}).scale,.7));o({scale:c,x:b.width/2-(a.x+a.width/2)*c,y:b.height/2-(a.y+a.height/2)*c})},[]),ai=(0,i.useCallback)(a=>{if(W)if("message"===a.kind){let b=W.rows.find(b=>b.ref===a.id);if(!b)return;let c=b.self?b.fromX:Math.min(b.fromX,b.toX),d=b.self?220:Math.abs(b.toX-b.fromX);ah({x:c-10,y:b.y-24,width:d+20,height:40})}else{let b=W.participants.find(b=>b.name===a.id);b&&ah({x:b.left-20,y:b.top,width:b.width+40,height:Math.min(260,W.height-b.top)})}},[W,ah]),aj=(0,i.useCallback)(a=>{if("diagram"===I.current)return ai(a);requestAnimationFrame(()=>document.getElementById(e9(a))?.scrollIntoView({block:"center",behavior:"smooth"}))},[ai]),ak=(0,i.useCallback)(a=>{s(a),a&&eB(`${a.kind}:${a.id}`)},[]);(0,i.useEffect)(()=>{if(!l||!W||U.current===g.nonce)return;U.current=g.nonce;let a=g.focus?a8(g.focus):null;if(!a)return;let b=null;if("message"===a.kind&&ay(V??l,a.name)&&(b={kind:"message",id:a.name}),"participant"===a.kind&&(V??l).participants.some(b=>b.name===a.name)&&(b={kind:"participant",id:a.name}),!b)return v(`${g.focus} is not in this sequence`,"warn");T.current=!1,s(b),aj(b)},[l,V,W,g,aj,v]),(0,i.useEffect)(()=>{if(!W||!T.current||"diagram"!==G)return;let{width:a,height:b}=ag();a&&(T.current=!1,Math.min((a-32)/W.width,(b-32)/W.height)>=.5||0===W.participants.length?q(a=>(a??0)+1):o({x:8,y:8,scale:.6}))},[W,G]);let al=(0,i.useCallback)(async a=>{let b;if(l&&j){try{b=a(l)}catch(a){return v(a instanceof Error?a.message:String(a),"warn")}m(b);try{let a=await fetch(`/api/file${(0,d4.docQuery)(j)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(b,null,2)+"\n"})});if(!a.ok)throw Error((await a.json())?.error??`HTTP ${a.status}`);R.current?.emitFull(b),v("saved")}catch(a){return v(`not saved: ${a instanceof Error?a.message:String(a)}`,"warn")}if(f?.def&&$){if("auto"===aO(f.def)){let{result:a,failed:b,conflicts:d}=await fk(f.path);if(a&&a.count>0){var c;return void(c=b.length?`auto: not written — ${b[0]}`:d.length?`auto: ${d.join(", ")} kept changing on disk; not written — save again`:be(a,"auto"),window.dispatchEvent(new CustomEvent(ey,{detail:{text:c,origin:void 0}})))}}ff()}}},[l,j,v,f,$]),am=a=>{let{width:b,height:c}=ag();o(d=>Q(d,a,{x:b/2,y:c/2}))},an=()=>{let a,b,c,d,e,f,g,h,i;l&&navigator.clipboard?.writeText((a=["sequenceDiagram"],b=new Map,(l.participants??[]).forEach((c,d)=>{let e=`p${d+1}`;b.set(c.name,e),a.push(` ${c.actor?"actor":"participant"} ${e} as ${aM(c.name)}`)}),c=a=>b.get(a)??aM(a).replace(/\W+/g,"_"),d=(a,b,d)=>{let e=a.reply?"-->>":"->>",f=[`${b} ${aM(a.label??"")}`,a.event?aM(a.event):""].filter(Boolean).join(" · "),g=`${d}${c(a.from)}${e}${c(a.to)}: ${f}`;return a.optional?[`${d}opt optional`,` ${g}`,`${d}end`]:[g]},e=l.messages??[],f=l.fragments??[],g=a=>f.filter(b=>b?.after===a),h=(b,c)=>(b.messages??[]).forEach((e,g)=>a.push(...d(e,`f${f.indexOf(b)+1}.${g+1}`,c+" "))),(i=(b,c,f)=>{for(let j=b;j<=e.length;j++){let b=j===f?[]:g(j);for(let d of b.filter(a=>"alt"!==a.kind))a.push(`${c}${d.kind} ${aM(d.label??"")}`),h(d,c),a.push(`${c}end`);let k=b.filter(a=>"alt"===a.kind);if(k.length){k.forEach((b,d)=>{a.push(`${c}${0===d?"alt":"else"} ${aM(b.label??"")}`),h(b,c)}),j<e.length&&(a.push(`${c}else as written`),i(j,c+" ",j)),a.push(`${c}end`);return}j<e.length&&a.push(...d(e[j],String(j+1),c))}})(0," ",null),a.join("\n")+"\n")).then(()=>v("mermaid copied"))},ao=a=>{let b=a?a8(a):null;if(!b||"message"!==b.kind&&"participant"!==b.kind)return;let c={kind:b.kind,id:b.name};ak(c),aj(c),L.close()},ap=V??aw("",""),ar=az(ap),as=l&&r?.kind==="message"?ay(ap,r.id):null,at=l&&r?.kind==="participant"?ap.participants.find(a=>a.name===r.id)??null:null,ax=ap.participants.map(a=>a.name),aK=j.split("/").pop()||"…",aN=Z.length+aa.filter(a=>"error"===a.severity).length,aP=aa.filter(a=>"warning"===a.severity).length,aQ=[{id:"participants",label:"Participants",icon:(0,h.jsx)(e7,{kind:"actor"})},{id:"messages",label:"Messages",icon:(0,h.jsx)(e7,{kind:"sequence"})},{id:"notes",label:"Notes",icon:"✎"},{id:"issues",label:"Issues",icon:(0,h.jsx)(et,{}),badge:aN+aP||void 0}],aR=a=>[{name:"from",label:"from",options:ax,initial:a?.from??ax[0]??""},{name:"to",label:"to",options:ax,initial:a?.to??ax[1]??ax[0]??""},{name:"label",label:"label",placeholder:"what is said or done",initial:a?.label??"",wide:!0},{name:"event",label:"event it fires",suggest:ac.events,initial:a?.event??""},{name:"state",label:"state after",suggest:ac.states,initial:a?.state??""},{name:"carries",label:"entity it carries",suggest:ac.entities,initial:a?.carries??""},{name:"machine",label:"machine",suggest:ac.machines,initial:a?.machine??""},{name:"optional",label:"optional",checkbox:!0,initial:!!a?.optional},{name:"reply",label:"reply (dashed)",checkbox:!0,initial:!!a?.reply}],aS=a=>a.actor?"actor":a.object?"object":a.service?"service":"",aT=["main: at the end",...as&&null===as.fragment?[`main: after ${as.index+1}`]:[],...(l?.fragments??[]).map((a,b)=>`fragment ${b+1}: ${a.kind} \xb7 ${a.label}`)];return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&D(!1),children:[(0,h.jsxs)("header",{className:"relative z-40 flex items-center gap-2 border-b border-gray-800 bg-gray-900 px-2 py-1.5 text-xs md:px-3 md:py-2",children:[(0,h.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,h.jsx)(e7,{kind:"sequence",size:14}),"SEQ"]}),(0,h.jsx)(d5,{}),(0,h.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:j,children:[l?.settings.name??aK,(0,h.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",aK]})]}),(0,h.jsx)("div",{className:"flex shrink-0 overflow-hidden rounded border border-gray-700 text-[12px] leading-none",role:"group","aria-label":"View",children:[["list","List","Read the messages in order, one under the other"],["diagram","Diagram","The lifelines and arrows"]].map(([a,b,c])=>(0,h.jsx)("button",{title:c,"aria-pressed":G===a,onClick:()=>{G!==a&&(r&&(T.current=!1),J(a),r&&requestAnimationFrame(()=>aj(r)))},className:`px-2.5 py-1.5 ${G===a?"bg-gray-700 text-gray-100":"bg-gray-800 text-gray-400 hover:text-gray-200"}`,children:b},a))}),(0,h.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,h.jsx)("button",{className:e4,onClick:an,children:"Copy mermaid"}),(0,h.jsx)("button",{className:e4,onClick:()=>F(a=>!a),"aria-pressed":!E,title:E?"Show the panel":"Hide the panel — the board takes the full width",children:E?"⟨ Panel":"Panel ⟩"})]}),(0,h.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,h.jsx)("button",{className:"rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-sm leading-none text-gray-200","aria-label":"More actions","aria-expanded":C,onClick:a=>{a.stopPropagation(),D(a=>!a)},children:"⋯"}),C&&(0,h.jsx)("div",{className:"absolute right-0 top-full z-50 mt-1 w-56 overflow-hidden rounded-lg border border-gray-700 bg-gray-900 py-1 shadow-xl",children:(0,h.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{D(!1),an()},children:"Copy as mermaid"})})]})]}),(0,h.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,h.jsxs)("div",{ref:K,className:"relative min-w-0 flex-1 overflow-hidden",children:[l&&W&&"list"===G&&V&&(0,h.jsx)(es,{what:"sequence",resetKey:l,children:(0,h.jsx)(fa,{definition:V,selection:r,issues:af,onSelect:a=>ak(a),onShowInDiagram:a=>{T.current=!1,J("diagram"),requestAnimationFrame(()=>ai(a))}})}),l&&W&&"diagram"===G&&(0,h.jsx)(es,{what:"sequence",resetKey:l,children:(0,h.jsx)(bS,{definition:V,layout:W,viewport:n,onViewportChange:o,selection:r,errorElements:ad,warningElements:ae,fitKey:p,onSelect:(a,b)=>ak({kind:a,id:b}),onClearSelection:()=>s(null),emptyHint:"No participants yet — add them in the panel, or let an agent write the scenario."})}),l&&W&&"diagram"===G&&(0,h.jsx)(eR,{docPath:j||null,kind:"sequence",viewport:n,setViewport:o,boxes:X,boardRef:K,focus:Y}),l&&W&&"list"===G&&(0,h.jsx)(eS,{docPath:j,onReveal:()=>J("diagram")}),(0,h.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 max-w-[75%] items-center gap-1.5 rounded bg-gray-950/70 px-1.5 py-0.5 text-[11px] ${"warn"===t.tone?"text-amber-300":"text-gray-500"} ${"list"===G&&w&&"ok"===t.tone?"hidden":"flex"}`,role:"status",children:[(0,h.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===t.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,h.jsxs)("span",{className:`truncate transition-opacity duration-500 ${w&&"ok"===t.tone?"opacity-0":"opacity-100"}`,children:[t.text,O>1?` \xb7 ${O} in the room`:""]})]}),(0,h.jsx)("div",{className:`absolute bottom-3 right-3 flex-col overflow-hidden rounded-lg border border-gray-700 bg-gray-900/90 shadow-lg backdrop-blur ${"diagram"===G?"flex":"hidden"}`,children:[["+","Zoom in",()=>am(1.25)],["−","Zoom out",()=>am(.8)],["⛶","Fit the whole diagram",()=>q(a=>(a??0)+1)]].map(([a,b,c])=>(0,h.jsx)("button",{title:b,"aria-label":b,onClick:c,className:"h-10 w-10 border-b border-gray-800 text-base leading-none text-gray-200 last:border-b-0 hover:bg-gray-800 md:h-8 md:w-8 md:text-sm",children:a},b))}),r&&!A&&(0,h.jsxs)("button",{className:"absolute bottom-3 left-1/2 max-w-[60%] -translate-x-1/2 truncate rounded-full border border-blue-500/60 bg-gray-900/95 px-4 py-2 text-sm text-blue-200 shadow-lg md:hidden",onClick:()=>{z("message"===r.kind?"messages":"participants"),B(!0)},children:["Edit ","message"===r.kind?`${r.id}. ${as?.message.label??""}`:r.id]})]}),A&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:L.close,"aria-hidden":"true"}),l&&(0,h.jsxs)("aside",{style:L.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 flex h-[var(--sheet-h)] flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${A?"translate-y-0":"pointer-events-none translate-y-full"} md:pointer-events-auto md:static md:z-auto md:h-auto md:w-80 md:translate-y-0 md:rounded-none md:border-l md:border-t-0 md:shadow-none md:transition-none ${E?"md:hidden":""}`,children:[(0,h.jsxs)("div",{className:"md:hidden",...L.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:aQ.find(a=>a.id===y)?.label}),(0,h.jsx)("button",{onClick:L.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:aQ.map(a=>(0,h.jsxs)("button",{onClick:()=>z(a.id),className:`relative flex-1 px-1 py-2 text-center text-xs transition-colors ${y===a.id?"border-b-2 border-blue-400 bg-gray-800/50 text-blue-400":"text-gray-500 hover:text-gray-300"}`,children:[a.label,void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1 top-1 min-w-[14px] rounded-full bg-red-900 px-1 text-[9px] text-red-100",children:a.badge})]},a.id))}),(0,h.jsx)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:(0,h.jsxs)(es,{what:"panel",resetKey:l,children:[(0,h.jsxs)("section",{className:"participants"===y?"":"hidden",children:[(0,h.jsx)("div",{className:e5,style:{marginTop:0},children:"Participants"}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:ap.participants.map(a=>(0,h.jsxs)("button",{className:`${e4} ${r?.kind==="participant"&&r.id===a.name?"border-blue-500 text-blue-300":""}`,onClick:()=>{ak({kind:"participant",id:a.name}),aj({kind:"participant",id:a.name})},title:aS(a)||"participant",children:[a.name,aS(a)&&(0,h.jsxs)("span",{className:"text-gray-500",children:[" · ",aS(a)]})]},a.name))}),(0,h.jsx)(e6,{id:"add-participant",reset:!0,required:["name"],fields:[{name:"name",placeholder:"new participant"},{name:"kind",options:fm,label:"kind"},{name:"value",placeholder:"actor / service / object",suggest:[...ac.actors,...ac.objects]},{name:"holds",placeholder:"holds: Entity, Entity",suggest:ac.entities}],submit:"+ Participant",onSubmit:a=>{let b=fn(a.name),c=fn(a.kind);al(d=>(function(a,b,c){if(!b.name?.trim())throw Error("A participant needs a name.");let d=aB(a);if(d.participants.some(a=>a.name===b.name))throw Error(`Participant '${b.name}' already exists.`);let e=d.participants.length;return d.participants.splice(e,0,aC({...b})),d})(d,{name:b,...c?{[c]:fn(a.value)||b}:{},holds:fo(a.holds)})),ak({kind:"participant",id:b})}}),at&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:`${e5} flex items-center justify-between gap-2`,children:[(0,h.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:at.name}),(0,h.jsx)("button",{className:`${e4} normal-case tracking-normal`,onClick:()=>aj({kind:"participant",id:at.name}),children:"◎ Show on board"})]}),(a=ap.participants.findIndex(a=>a.name===at.name),b=ap.participants.length-1,c=a=>al(b=>{var c;let d,e;return c=at.name,e=aD(d=aB(b),c),d.participants.splice(d.participants.indexOf(e),1),d.participants.splice(Math.max(0,Math.min(a,d.participants.length)),0,e),d}),(0,h.jsxs)("div",{className:"mb-1 flex items-center gap-1 text-[11px] text-gray-400",children:[(0,h.jsx)("button",{className:`${e4} disabled:opacity-40`,disabled:a<=0,onClick:()=>c(a-1),"aria-label":"Move one column left",children:"← Left"}),(0,h.jsxs)("span",{className:"flex-1 text-center",children:["column ",a+1," of ",b+1]}),(0,h.jsx)("button",{className:`${e4} disabled:opacity-40`,disabled:a>=b,onClick:()=>c(a+1),"aria-label":"Move one column right",children:"Right →"})]})),(0,h.jsx)(e6,{id:"rename-participant",required:["to"],fields:[{name:"to",label:"new name",initial:at.name}],submit:"Rename (every message follows)",onSubmit:a=>{let b=fn(a.to);b!==at.name&&(al(a=>(function(a,b,c){if(!c?.trim())throw Error("A participant needs a name.");let d=aB(a),e=aD(d,b);if(c===b)return d;if(d.participants.some(a=>a.name===c))throw Error(`Participant '${c}' already exists.`);e.name=c;let f=a=>{a.from===b&&(a.from=c),a.to===b&&(a.to=c)};for(let a of(d.messages.forEach(f),d.fragments??[]))a.messages.forEach(f);return d})(a,at.name,b)),ak({kind:"participant",id:b}))}},`rename:${at.name}`),(0,h.jsx)(e6,{id:"edit-participant",fields:[{name:"kind",options:fm,label:"kind",initial:aS(at)},{name:"value",placeholder:"actor / service / object",suggest:[...ac.actors,...ac.objects],initial:at.actor??at.object??at.service??""},{name:"holds",placeholder:"holds: Entity, Entity",suggest:ac.entities,initial:(at.holds??[]).join(", "),wide:!0},{name:"description",placeholder:"description",initial:at.description??"",wide:!0}],submit:"Save participant",onSubmit:a=>al(b=>{let c,d;return aG(b,at.name,{...(c=fn(a.kind),d=fn(a.value)||at.name,{actor:"actor"===c?d:"",service:"service"===c?d:"",object:"object"===c?d:""}),holds:fo(a.holds),description:fn(a.description)})})},`p:${JSON.stringify(at)}`),(0,h.jsxs)("button",{className:`${e4} mt-2 text-red-300`,onClick:()=>{al(a=>{var b;let c,d;return b=at.name,aD(c=aB(a),b),c.participants=c.participants.filter(a=>a.name!==b),d=a=>a.from!==b&&a.to!==b,c.messages=c.messages.filter(d),c.fragments&&(c.fragments=c.fragments.map(b=>{let c;return{...b,after:Math.max(0,b.after-(c=b.after,a.messages.slice(0,c).filter(a=>!d(a)).length)),messages:b.messages.filter(d)}}).filter(a=>a.messages.length>0),c.fragments.length||delete c.fragments),c}),s(null),eB(null)},title:"Also removes every message it sends or receives",children:["Delete ",at.name," and its messages"]})]})]}),(0,h.jsxs)("section",{className:"messages"===y?"":"hidden",children:[(0,h.jsx)("div",{className:e5,style:{marginTop:0},children:"Messages"}),0===ar.length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),(0,h.jsx)("div",{className:"flex flex-col",children:ar.map(({ref:a,message:b,fragment:c},d)=>{let e=null!==c&&(0===d||ar[d-1].fragment!==c),f=null!==c?ap.fragments?.[c]:void 0,g=r?.kind==="message"&&r.id===a;return(0,h.jsxs)("div",{children:[e&&f&&(0,h.jsxs)("div",{className:"mt-2 border-t border-gray-800 pt-1 text-[11px] text-indigo-300",children:[(0,h.jsx)("span",{className:"font-semibold",children:f.kind})," · after ",f.after," · ",f.label]}),(0,h.jsxs)("button",{className:`block w-full truncate rounded px-1 py-0.5 text-left text-[11px] ${g?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,onClick:()=>{ak({kind:"message",id:a}),aj({kind:"message",id:a})},title:`${b.from} → ${b.to}: ${b.label}`,children:[(0,h.jsxs)("span",{className:"text-gray-500",children:[a,"."]})," ",b.from," → ",b.to,": ",b.label,b.event?(0,h.jsxs)("span",{className:"text-blue-300",children:[" [",b.event,"]"]}):null,b.state?(0,h.jsxs)("span",{className:"text-emerald-400",children:[" → ",b.state]}):null,b.optional?(0,h.jsx)("span",{className:"text-gray-500",children:" opt"}):null]})]},a)})}),as&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:`${e5} flex items-center justify-between gap-2`,children:[(0,h.jsxs)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:["Message ",r.id]}),(0,h.jsxs)("span",{className:"flex gap-1 normal-case tracking-normal",children:[null===as.fragment&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("button",{className:e4,"aria-label":"Move up",title:"Move up",disabled:0===as.index,onClick:()=>{al(a=>aJ(a,as.index,as.index-1)),ak({kind:"message",id:String(as.index)})},children:"↑"}),(0,h.jsx)("button",{className:e4,"aria-label":"Move down",title:"Move down",disabled:as.index>=ap.messages.length-1,onClick:()=>{al(a=>aJ(a,as.index,as.index+1)),ak({kind:"message",id:String(as.index+2)})},children:"↓"})]}),(0,h.jsx)("button",{className:e4,onClick:()=>aj(r),children:"◎ Show"})]})]}),(0,h.jsx)(e6,{id:"edit-message",required:["label"],fields:[...aR(as.message),{name:"description",placeholder:"description",initial:as.message.description??"",wide:!0}],submit:"Save message",onSubmit:a=>al(b=>aI(b,as.index,fp(a),as.fragment))},`m:${r.id}:${JSON.stringify(as.message)}`),(0,h.jsxs)("button",{className:`${e4} mt-2 text-red-300`,onClick:()=>{al(a=>(function(a,b,c=null){let d=aB(a);if(null!==c){let a=aF(d,c);if(!a.messages[b])throw Error(`Message ${b+1} not found in fragment ${c+1}.`);return a.messages.splice(b,1),d}if(!d.messages[b])throw Error(`Message ${b+1} not found. The sequence has ${d.messages.length}.`);if(d.messages.splice(b,1),d.fragments)for(let a of d.fragments)a.after>b&&(a.after-=1);return d})(a,as.index,as.fragment)),s(null),eB(null)},children:["Delete message ",r.id]})]}),(0,h.jsx)("div",{className:e5,children:"Add a message"}),(0,h.jsx)(e6,{id:"add-message",reset:!0,required:["label"],fields:[{name:"where",options:aT,label:"where",wide:!0},...aR()],submit:"+ Message",onSubmit:a=>{let b=fn(a.where),c=fp(a),d=/^fragment (\d+):/.exec(b),e=/^main: after (\d+)$/.exec(b);d?al(a=>{var b;let e,f,g;return b=Number(d[1])-1,f=aF(e=aB(a),b),aE(e,c),g=f.messages.length,f.messages.splice(g,0,aC({...c})),e}):e?al(a=>aH(a,c,Number(e[1]))):al(a=>aH(a,c))}},`add:${aT.join("|")}:${ax.join("|")}`),(0,h.jsx)("div",{className:e5,children:"Fragments"}),0===(ap.fragments??[]).length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None."}),(ap.fragments??[]).map((a,b)=>(0,h.jsxs)("div",{className:"mb-2 rounded border border-gray-800 p-1.5",children:[(0,h.jsxs)("div",{className:"flex items-center justify-between text-[11px] text-indigo-300",children:[(0,h.jsxs)("span",{children:[b+1,". ",(0,h.jsx)("span",{className:"font-semibold",children:a.kind})," · after ",a.after," · ",a.messages.length," message(s)"]}),(0,h.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":`Remove fragment ${b+1}`,onClick:()=>al(a=>{let c;return aF(c=aB(a),b),c.fragments.splice(b,1),c.fragments.length||delete c.fragments,c}),children:"✕"})]}),(0,h.jsx)(e6,{id:`edit-fragment-${b}`,fields:[{name:"kind",options:au,initial:a.kind},{name:"after",placeholder:"after message",initial:String(a.after)},{name:"label",placeholder:"the condition, in words",initial:a.label,wide:!0}],submit:"Save fragment",onSubmit:a=>al(c=>(function(a,b,c){let d=aB(a),e=aF(d,b);if(void 0!==c.kind&&!au.includes(c.kind))throw Error(`A fragment is one of ${au.join(", ")}; got '${c.kind}'.`);if(void 0!==c.after&&(!Number.isInteger(c.after)||c.after<0||c.after>d.messages.length))throw Error(`A fragment branches after a main message, 0 to ${d.messages.length}; got ${c.after}.`);return d.fragments[b]={...aC({...e,...c,messages:void 0}),messages:e.messages??[]},d})(c,b,{kind:fn(a.kind),after:Number(fn(a.after)),label:fn(a.label)}))})]},`${b}:${JSON.stringify({...a,messages:void 0})}`)),(0,h.jsx)(e6,{id:"add-fragment",reset:!0,required:["label"],fields:[{name:"kind",options:au},{name:"after",placeholder:"after message",initial:String(as&&null===as.fragment?as.index+1:ap.messages.length)},{name:"label",placeholder:"the condition, in words",wide:!0},{name:"from",options:ax,label:"first message from"},{name:"to",options:ax,label:"to",initial:ax[1]??ax[0]??""},{name:"first",placeholder:"first message label (optional)",wide:!0}],submit:"+ Fragment",onSubmit:a=>al(b=>(function(a,b){if(!au.includes(b.kind))throw Error(`A fragment is one of ${au.join(", ")}; got '${b.kind}'.`);if(!b.label?.trim())throw Error("A fragment needs a label: the condition in words.");let c=aB(a);if(!Number.isInteger(b.after)||b.after<0||b.after>c.messages.length)throw Error(`A fragment branches after a main message, 0 to ${c.messages.length}; got ${b.after}.`);for(let a of b.messages??[])aE(c,a);return(c.fragments??=[]).push({...aC({...b,messages:void 0}),messages:(b.messages??[]).map(a=>aC({...a}))}),c})(b,{kind:fn(a.kind),after:Number(fn(a.after)),label:fn(a.label),messages:fn(a.first)?[{from:fn(a.from),to:fn(a.to),label:fn(a.first)}]:[]}))},`add-fragment:${ap.messages.length}:${as?.index??""}`)]}),(0,h.jsxs)("section",{className:"notes"===y?"":"hidden",children:[(0,h.jsx)("div",{className:e5,style:{marginTop:0},children:"Notes"}),(0,h.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the document, for whoever opens it next — you, or an agent."}),(0,h.jsx)(e1,{label:"On this sequence",value:l.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:a=>al(b=>{var c;let d;return c={notes:a},(d=aB(b)).settings=aC({...d.settings,...c}),d})},"sequence"),at&&(0,h.jsx)(e1,{label:`On ${at.name}`,value:at.notes??"",placeholder:`A question or a decision about ${at.name}…`,onSave:a=>al(b=>aG(b,at.name,{notes:a}))},`participant:${at.name}`),as&&(0,h.jsx)(e1,{label:`On message ${r.id}`,value:as.message.notes??"",placeholder:"A question or a decision about this message…",onSave:a=>al(b=>aI(b,as.index,{notes:a},as.fragment))},`message:${r.id}`),!r&&(0,h.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Select a participant or a message to leave a note on it."}),[...ap.participants.filter(a=>a.notes?.trim()),...ar.filter(a=>a.message.notes?.trim())].length>0&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:e5,children:"With notes"}),(0,h.jsxs)("div",{className:"flex flex-wrap gap-1",children:[ap.participants.filter(a=>a.notes?.trim()).map(a=>(0,h.jsx)("button",{className:e4,onClick:()=>ao(`participant:${a.name}`),children:a.name},`p${a.name}`)),ar.filter(a=>a.message.notes?.trim()).map(a=>(0,h.jsxs)("button",{className:e4,onClick:()=>ao(`message:${a.ref}`),children:["message ",a.ref]},`m${a.ref}`))]})]})]}),(0,h.jsxs)("section",{className:"issues"===y?"":"hidden",children:[(0,h.jsx)("div",{className:e5,style:{marginTop:0},children:"Issues"}),Z.map((a,b)=>(0,h.jsxs)("button",{className:"block w-full py-0.5 text-left text-[11px] text-red-300",onClick:()=>ao(a.element),children:["[",a.ruleId,"] ",a.message]},`p${b}`)),aa.map((a,b)=>(0,h.jsxs)("button",{className:`block w-full py-0.5 text-left text-[11px] ${"error"===a.severity?"text-red-300":"text-amber-300"}`,onClick:()=>ao(a.element),children:["[",a.ruleId,"] ",a.message]},`s${b}`)),0===Z.length&&0===aa.length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-green-400",children:_?"Valid, and every name it uses resolves in the system.":"The document is valid."}),!e&&(0,h.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Open this sequence from its system to check it against the machines and the data."}),e&&!$&&f&&(0,h.jsx)("p",{className:"mt-2 text-[11px] text-amber-300",children:"This document is not a member of the open system."}),ab&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:e5,children:["Replay against ",ab.machines.join(", ")||"no machine"]}),ab.paths.map(a=>(0,h.jsxs)("div",{className:"mb-2",children:[(0,h.jsxs)("div",{className:`text-[11px] font-semibold ${a.accepted?"text-green-400":"text-amber-300"}`,children:[a.name," — ",a.accepted?"accepted":"stops"]}),a.steps.filter(a=>"data"!==a.result).map(b=>(0,h.jsxs)("button",{className:`block w-full truncate py-0.5 pl-2 text-left font-mono text-[10.5px] ${"moved"===b.result||"stayed"===b.result?"text-gray-400":"text-amber-300"}`,title:b.note??b.result,onClick:()=>ao(`message:${b.ref}`),children:[b.ref,". ",b.event??""," ",b.from.join("|")||"·"," → ",b.to.join("|")||"·"," ",b.result]},`${a.name}:${b.ref}`))]},a.name))]})]})]})})]})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:aQ.map(a=>{let b=A&&y===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(A&&y===b?L.close():B(!0),z(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1/2 top-1 min-w-[16px] translate-x-5 rounded-full border border-red-900/80 bg-red-950/80 px-1 text-[10px] leading-4 text-red-200",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})})]})}function fr(a,b){let c=a?.members.find(a=>a.path===b)?.def;return c?.settings?.name||(b.split("/").pop()??b).replace(/\.(smdf|erdf|sqdf|sysdf)\.json$|\.json$/i,"")}let fs=(a,b)=>a?.members.find(a=>a.path===b)?.kind??"machine";function ft(a){return"message"===a.kind?`message ${a.name}`:`${a.kind} ${a.name}`}function fu({systemPath:a}){let b=ez("doc"),c=ez("focus"),{system:d}=fg(a),[e,f]=(0,i.useState)(!1),[g,j]=(0,i.useState)(null),k=(0,i.useRef)(d);(0,i.useEffect)(()=>{k.current=d},[d]);let l=(0,i.useMemo)(()=>d?eT(()=>a9(d.members),[]):[],[d]),m=fh(d,b),n=!!d&&(b===d.path||b===a),o=m&&c?function(a,b,c){let d=a8(c);if(!d)return[];let e=a=>a.member===b&&a.kind===d.kind&&a.name===d.name,f=[];for(let b of a)e(b.from)?f.push({other:b.to,text:b.text,rule:b.rule}):e(b.to)&&f.push({other:b.from,text:b.back,rule:b.rule});return f}(l,m,c):[],p=function(a,b){if(!b)return[];let c=new Map;for(let d of a)for(let a of[d.from,d.to]){if(a.member!==b)continue;let d=a7(a);c.set(d,(c.get(d)??0)+1)}return[...c.entries()].sort((a,b)=>a[0].localeCompare(b[0]))}(l,m);(0,i.useEffect)(()=>{let a=a=>{let b=a.detail;b?.text&&j({...b,at:Date.now()})};return window.addEventListener(ey,a),()=>window.removeEventListener(ey,a)},[]),(0,i.useEffect)(()=>{if(!g)return;let a=setTimeout(()=>j(null),9e3);return()=>clearTimeout(a)},[g]);let q=d?.path;(0,i.useEffect)(()=>{if(!q)return;let b=!0,c=null,d=null;return(async()=>{let{bridgeUrl:e}=await ed();if(b&&e){var g;let b,h,i,l;(c=dw({url:e,role:"web",docId:q,name:"web-system-strip"})).on("view",b=>{let c=k.current;if(!c)return;let d=b.member?void 0!==c.absOf[b.member]?b.member:Object.keys(c.absOf).find(a=>c.absOf[a]===b.member):void 0;if(b.member&&!d)return void j({text:`ignored a view of ${b.member.split("/").pop()}: it is not a member of this system`,origin:b.origin,at:Date.now()});eA({doc:d?c.absOf[d]:q,system:a,focus:b.focus??null}),f(!1);let e=[d?fr(c,d):"the system map",b.focus].filter(Boolean).join(" · ");j({text:b.note?b.note:`showing ${e}`,origin:b.origin,at:Date.now()})}),c.on("full",()=>ff()),g=c,b=!1,h=!1,i=()=>{g.join().then(()=>{b=!0}).catch(()=>{})},l=g.on("status",a=>{"connected"!==a?h=b:h&&(h=!1,i())}),i(),d=()=>{l()}}})(),()=>{b=!1,d?.(),c?.disconnect()}},[q,a]);let r=b=>{f(!1),d&&eA({doc:b.member?d.absOf[b.member]??aV(d.path,b.member):d.path,system:a,focus:b.focus??null})},s=d?.def?.members?.filter(a=>a?.path).map(a=>a.path)??[],t=d?.def?.settings?.name??(a.split("/").pop()??"system").replace(/\.sysdf\.json$/i,""),u=o.length;return(0,h.jsxs)("div",{className:"system-strip relative z-50 border-b border-gray-800 bg-gray-950 text-xs text-gray-300",children:[(0,h.jsxs)("div",{className:"flex h-[var(--strip-h)] items-center gap-1 px-1.5 md:px-2",children:[(0,h.jsxs)("button",{onClick:()=>r({}),className:`flex min-w-0 max-w-[30%] shrink-0 items-center gap-1 rounded px-1.5 py-1 md:max-w-[16rem] ${n?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,title:`${a} — the system map`,children:[(0,h.jsx)(e7,{kind:"system",size:15}),(0,h.jsx)("span",{className:"truncate font-semibold",children:t})]}),(0,h.jsx)("span",{className:"h-4 w-px shrink-0 bg-gray-800"}),(0,h.jsxs)("nav",{className:"flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto [scrollbar-width:none]","aria-label":"Members",children:[s.map(a=>{let b=a===m,c=d?.members.find(b=>b.path===a)?.error;return(0,h.jsxs)("button",{onClick:()=>r({member:a}),"aria-current":b?"page":void 0,title:`${fr(d,a)} — ${a}${c?` (cannot be read: ${c})`:""}`,className:`flex shrink-0 items-center gap-1 rounded px-1.5 py-1 ${b?"bg-blue-950/60 text-blue-200":c?"text-red-400 hover:bg-gray-800":"text-gray-400 hover:bg-gray-800 hover:text-gray-200"}`,children:[(0,h.jsx)(e7,{kind:fs(d,a),size:15}),(0,h.jsx)("span",{className:`max-w-[7.5rem] truncate md:max-w-[11rem] ${b?"":"hidden md:inline"}`,children:fr(d,a)})]},a)}),!d&&(0,h.jsx)("span",{className:"px-1 text-gray-600",children:"loading…"}),d?.error&&(0,h.jsx)("span",{className:"truncate px-1 text-amber-300",children:d.error})]}),(0,h.jsxs)("button",{onClick:()=>f(a=>!a),disabled:!m,"aria-expanded":e,title:m?c?`What ${c} links to in the other drawings`:"Elements of this drawing that link to the others":"Open a member to follow its links",className:`flex shrink-0 items-center gap-1 rounded px-1.5 py-1 disabled:opacity-40 ${e?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,children:[(0,h.jsx)(e7,{kind:"link",size:15}),(0,h.jsx)("span",{className:"hidden sm:inline",children:"Links"}),u>0&&(0,h.jsx)("span",{className:"rounded-full border border-gray-700 px-1 text-[10px] leading-4 text-gray-300",children:u})]})]}),g&&!e&&(0,h.jsx)("div",{className:"pointer-events-none absolute inset-x-0 top-full flex justify-center px-2 pt-1",role:"status",children:(0,h.jsxs)("span",{className:"max-w-full truncate rounded border border-gray-700 bg-gray-900/95 px-2 py-0.5 text-[11px] text-gray-300 shadow",children:[g.origin?(0,h.jsxs)("span",{className:"text-blue-300",children:[g.origin,": "]}):null,g.text]})}),e&&m&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:"fixed inset-0 z-40",onClick:()=>f(!1),"aria-hidden":"true"}),(0,h.jsxs)("div",{className:"absolute right-1 top-full z-50 mt-1 max-h-[60vh] w-[min(24rem,calc(100vw-0.5rem))] overflow-y-auto rounded-lg border border-gray-700 bg-gray-900 p-2 shadow-xl",children:[c&&a8(c)?(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:"mb-1 flex items-center justify-between gap-2 text-[11px] text-gray-500",children:[(0,h.jsxs)("span",{className:"truncate",children:[(0,h.jsx)("span",{className:"text-gray-200",children:ft(a8(c))})," in ",fr(d,m)]}),(0,h.jsx)("button",{className:"shrink-0 text-gray-500 hover:text-gray-200",onClick:()=>eA({doc:b,focus:null}),children:"clear"})]}),0===o.length&&(0,h.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"Nothing in the other drawings names it."}),o.map((a,b)=>(0,h.jsxs)("button",{onClick:()=>r({member:a.other.member,focus:a7(a.other)}),className:"flex w-full items-start gap-2 rounded px-1.5 py-1.5 text-left hover:bg-gray-800",children:[(0,h.jsx)("span",{className:"mt-0.5 text-gray-400",children:(0,h.jsx)(e7,{kind:fs(d,a.other.member),size:14})}),(0,h.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,h.jsx)("span",{className:"block text-[12px] text-gray-200",children:a.text}),(0,h.jsxs)("span",{className:"block truncate text-[10.5px] text-gray-500",children:[ft(a.other)," · ",fr(d,a.other.member)," · ",a.rule]})]})]},b))]}):null,(!c||!a8(c))&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["Elements of ",fr(d,m)," that the other drawings name — pick one to follow it."]}),0===p.length&&(0,h.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"None."}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:p.map(([a,c])=>(0,h.jsxs)("button",{onClick:()=>{f(!0),eA({doc:b,focus:a})},className:"rounded border border-gray-700 bg-gray-800 px-1.5 py-0.5 text-[11px] text-gray-200 hover:bg-gray-700",children:[a," ",(0,h.jsx)("span",{className:"text-gray-500",children:c})]},a))})]})]})]})]})}let fv={erd:"ERD",machine:"STATE MACHINE",sequence:"SEQUENCE",system:"SYSTEM"};function fw(a,b,c=!1){if(!b)return"";if("erd"===a)return`${b.entities?.length??0} entities \xb7 ${b.relationships?.length??0} relationships`;if("sequence"===a){let a=b.fragments?.length??0;return`${b.participants?.length??0} participants \xb7 ${b.messages?.length??0} messages${a&&!c?` \xb7 ${a} fragment${a>1?"s":""}`:""}`}let d=0,e=a=>{a&&(d+=1,(a.states??[]).forEach(e),(a.parallel?.states??[]).forEach(e))};(b.state?.states??[]).forEach(e),(b.state?.parallel?.states??[]).forEach(e);let f=(b.events??[]).reduce((a,b)=>a+(b?.events?.length??0)+(b?.timers?.length??0),0);return`${d} states \xb7 ${f} events`}let fx=(a,b)=>a<b?`${a}\u0000${b}`:`${b}\u0000${a}`;function fy(a){let b="message"===a.from.kind?`message ${a.from.name}`:`${a.from.kind} ${a.from.name}`;return`${b} ${a.text}`}function fz(){let a=(0,d4.useRequestedDoc)(),[b,c]=(0,i.useState)(a);(0,i.useEffect)(()=>{let b=!0;if(a)c(a);else fb(null).then(a=>b&&c(a.path||null));return()=>{b=!1}},[a]);let{system:d,reload:e}=fg(b),[f,g]=(0,i.useState)("members"),[j,k]=(0,i.useState)(!1),[l,m]=(0,i.useState)(!1),[n,o]=(0,i.useState)(!1),[p,q]=(0,i.useState)(null),[r,s]=(0,i.useState)({text:"loading…",tone:"ok"}),t=(0,i.useCallback)((a,b="ok")=>s({text:a,tone:b}),[]),[u,v]=(0,i.useState)(!1),w=ev({onClose:()=>k(!1),restVh:62,tallVh:92}),x=(0,i.useRef)(null),[y,z]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=x.current;if(!a)return;let b=()=>{let b=a.getBoundingClientRect();b.width&&z(b.height>1.1*b.width)};b();let c=new ResizeObserver(b);return c.observe(a),()=>c.disconnect()},[]);let A=(0,i.useRef)(!1);(0,i.useEffect)(()=>{d&&(d.error?t(d.error,"warn"):A.current||t(`${d.members.length} member${1===d.members.length?"":"s"} loaded`),A.current=!0)},[d,t]);let[B,C]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=setTimeout(()=>C(!0),4e3);return()=>{clearTimeout(a),C(!1)}},[r]);let D=(0,i.useMemo)(()=>d?.def?eT(()=>a6(d.def,d.members),null):null,[d]),E=(0,i.useMemo)(()=>d?eT(()=>a9(d.members),[]):[],[d]),F=(0,i.useMemo)(()=>d?.def?eT(()=>bd(d.def,d.members),null):null,[d]),G=aO(d?.def),H=(0,i.useMemo)(()=>{let a=new Map;for(let b of E){if(b.from.member===b.to.member)continue;let c=fx(b.from.member,b.to.member),d=a.get(c)??{a:c.split("\0")[0],b:c.split("\0")[1],links:[]};d.links.push(b),a.set(c,d)}return a},[E]),I=(D?.issues??[]).filter(a=>"error"===a.severity),J=(D?.issues??[]).filter(a=>"warning"===a.severity),K=(b,c)=>{d&&eA({doc:d.absOf[b]??b,system:a??d.path,focus:c??null})},L=async(a,b)=>{if(d)try{await fd(d.path,a,d.mtimes[d.path]),t(b),ff()}catch(a){a instanceof fc?(t("the system changed on disk — reloaded; make the change again","warn"),ff()):t(`not saved: ${a instanceof Error?a.message:String(a)}`,"warn")}},M=async()=>{if(!d||!F||!F.count)return;v(!0);let{result:a,written:b,failed:c,conflicts:e}=await fk(d.path);v(!1),c.length?t(`not all written: ${c.join("; ")}`,"warn"):e.length?t(`${e.join(", ")} kept changing on disk — not written; apply again`,"warn"):a?.count?t(`${be(a,"propose").replace(/ proposed/," applied")} — ${b.length} file(s) written`):t("nothing to apply: the drawings on disk already agree")},N=y?420:760,O=y?640:520,P=d?.def?.members?.filter(a=>a?.path).map(a=>a.path)??[],Q=d?.def?.actors??[],R=64*!!Q.length,S=(0,i.useMemo)(()=>{let a=P.length,b=N/2,c=(O-R)/2+6,d=Math.max(0,N/2-98-16),e=Math.max(0,(O-R)/2-46-18),f=new Map;return P.forEach((g,h)=>{if(1===a)return f.set(g,{x:b,y:c});if(y){let b=O-R-46-16;return f.set(g,{x:h%2?.67*N:.33*N,y:62+(b-62)*h/(a-1)})}if(2===a)return f.set(g,y?{x:b,y:h?c+e:c-e}:{x:h?b+d:b-d,y:c});let i=-Math.PI/2+2*h*Math.PI/a;f.set(g,{x:b+d*Math.cos(i),y:c+e*Math.sin(i)})}),f},[P.join("|"),N,O,196,R,y]),T=(0,i.useMemo)(()=>{let a=new Map;for(let{member:b,def:c}of a5(d?.members??[]).sequences)for(let d of c.participants??[]){if(!d?.actor)continue;let c=a.get(d.actor)??[];c.includes(b)||c.push(b),a.set(d.actor,c)}return a},[d]),U=d?.def,V=(d?.path??b??"").split("/").pop()||"…",W=[{id:"members",label:"Members",icon:(0,h.jsx)(e7,{kind:"system"})},{id:"checks",label:"Checks",icon:(0,h.jsx)(et,{}),badge:I.length+J.length||void 0},{id:"notes",label:"Notes",icon:"✎"}],X=p?H.get(p):void 0,Y=(0,i.useMemo)(()=>{let a=[];for(let b of["error","warning"]){let c=new Map;for(let a of D?.issues??[])a.severity===b&&c.set(a.ruleId,[...c.get(a.ruleId)??[],a]);for(let[d,e]of[...c.entries()].sort((a,b)=>a[0].localeCompare(b[0])))a.push({key:`${b}:${d}`,ruleId:d,severity:b,issues:e})}return a},[D]);return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>l&&m(!1),children:[(0,h.jsxs)("header",{className:"relative z-40 flex items-center gap-2 border-b border-gray-800 bg-gray-900 px-2 py-1.5 text-xs md:px-3 md:py-2",children:[(0,h.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,h.jsx)(e7,{kind:"system",size:14}),"SYS"]}),(0,h.jsx)(d5,{}),(0,h.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:d?.path,children:[U?.settings?.name??V,(0,h.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",V]})]}),(0,h.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,h.jsx)("button",{className:e4,onClick:e,title:"Read the system and every member again",children:"Re-check"}),(0,h.jsx)("button",{className:e4,onClick:()=>o(a=>!a),"aria-pressed":!n,children:n?"⟨ Panel":"Panel ⟩"})]}),(0,h.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,h.jsx)("button",{className:"rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-sm leading-none text-gray-200","aria-label":"More actions","aria-expanded":l,onClick:a=>{a.stopPropagation(),m(a=>!a)},children:"⋯"}),l&&(0,h.jsx)("div",{className:"absolute right-0 top-full z-50 mt-1 w-56 overflow-hidden rounded-lg border border-gray-700 bg-gray-900 py-1 shadow-xl",children:(0,h.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{m(!1),e()},children:"Re-check the system"})})]})]}),(0,h.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,h.jsxs)("div",{ref:x,className:"relative min-w-0 flex-1 overflow-hidden bg-[#030712]",children:[d&&U&&(0,h.jsx)(es,{what:"system map",resetKey:d,children:(0,h.jsxs)("svg",{className:"h-full w-full",viewBox:`0 0 ${N} ${O}`,preserveAspectRatio:"xMidYMid meet",role:"img","aria-label":`System map of ${U.settings?.name}`,children:[[...H.entries()].map(([a,b])=>{let c=S.get(b.a),d=S.get(b.b);if(!c||!d)return null;let e=(c.x+d.x)/2,f=(c.y+d.y)/2,i=`${b.links.length} link${1===b.links.length?"":"s"}`,j=6.4*i.length+16,l=p===a;return(0,h.jsxs)("g",{className:"cursor-pointer",onClick:()=>{q(l?null:a),g("members"),k(!0)},children:[(0,h.jsx)("line",{x1:c.x,y1:c.y,x2:d.x,y2:d.y,stroke:"transparent",strokeWidth:18}),(0,h.jsx)("line",{x1:c.x,y1:c.y,x2:d.x,y2:d.y,stroke:l?"#3b82f6":"#475569",strokeWidth:l?2.5:1.6}),(0,h.jsx)("rect",{x:e-j/2,y:f-11,width:j,height:22,rx:11,fill:"#0f172a",stroke:l?"#3b82f6":"#334155"}),(0,h.jsx)("text",{x:e,y:f+4,textAnchor:"middle",fontSize:11.5,fill:l?"#93c5fd":"#cbd5e1",children:i})]},a)}),Q.map((a,b)=>{let c=(b+1)*N/(Q.length+1),d=O-30;return(0,h.jsxs)("g",{children:[(T.get(a.name)??[]).map(a=>{let b=S.get(a);return b?(0,h.jsx)("line",{x1:c,y1:d-14,x2:b.x,y2:b.y+46,stroke:"#334155",strokeDasharray:"3 4"},a):null}),(0,h.jsx)("title",{children:[`${a.kind}`,a.description??"",a.wheelNode??""].filter(Boolean).join(" — ")}),(0,h.jsx)("rect",{x:c-62,y:d-14,width:124,height:28,rx:14,fill:"#0c1020",stroke:"#6366f1"}),(0,h.jsx)("g",{transform:`translate(${c-54} ${d-8})`,color:"#a5b4fc",children:(0,h.jsx)(e7,{kind:"actor",size:16})}),(0,h.jsx)("text",{x:c-34,y:d-1,fontSize:11.5,fontWeight:600,fill:"#e2e8f0",children:a.name.length>12?`${a.name.slice(0,11)}…`:a.name}),(0,h.jsx)("text",{x:c-34,y:d+9,fontSize:8.5,fill:"#94a3b8",children:a.kind})]},a.name)}),P.map(a=>{let b=S.get(a),c=d.members.find(b=>b.path===a);if(!b||!c)return null;let e=c.kind,f=(D?.issues??[]).filter(b=>b.member===a),g=f.filter(a=>"error"===a.severity).length,i=f.filter(a=>"warning"===a.severity).length,j=b.x-98,k=b.y-46,l=fr(d,a),m=X&&(X.a===a||X.b===a);return(0,h.jsxs)("g",{className:"cursor-pointer",onClick:()=>K(a),children:[(0,h.jsx)("title",{children:`${a}${c.error?` — cannot be read: ${c.error}`:""}
|
|
15
|
-
Tap to open it inside the system.`}),(0,h.jsx)("rect",{x:j,y:k,width:196,height:92,rx:10,fill:"#0f172a",stroke:c.error?"#ef4444":m?"#3b82f6":g?"#b91c1c":"#475569",strokeWidth:m?2.2:1.5,strokeDasharray:c.error?"5 4":void 0}),(0,h.jsx)("g",{transform:`translate(${j+10} ${k+9})`,color:"#93c5fd",children:(0,h.jsx)(e7,{kind:e,size:16})}),(0,h.jsx)("text",{x:j+32,y:k+21,fontSize:9,fontWeight:700,letterSpacing:"0.06em",fill:"#64748b",children:fv[e]}),(0,h.jsx)("text",{x:j+10,y:k+43,fontSize:14,fontWeight:600,fill:"#e2e8f0",children:l.length>22?`${l.slice(0,21)}…`:l}),(0,h.jsx)("text",{x:j+10,y:k+60,fontSize:10.5,fill:"#94a3b8",children:c.error?"cannot be read":fw(e,c.def,!0)}),(0,h.jsx)("text",{x:j+10,y:k+79,fontSize:10.5,fill:g?"#fca5a5":i?"#fcd34d":"#4ade80",children:c.error?c.error.length>30?`${c.error.slice(0,29)}…`:c.error:g||i?[g?`${g} error${g>1?"s":""}`:"",i?`${i} warning${i>1?"s":""}`:""].filter(Boolean).join(" · "):"checks pass"}),(0,h.jsx)("text",{x:j+196-10,y:k+79,fontSize:10.5,textAnchor:"end",fill:"#64748b",children:"open ›"})]},a)})]})}),d&&!U&&(0,h.jsx)("div",{className:"absolute inset-0 flex items-center justify-center p-6 text-center text-sm text-amber-300",children:d.error}),(0,h.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 flex max-w-[75%] items-center gap-1.5 rounded bg-gray-950/70 px-1.5 py-0.5 text-[11px] ${"warn"===r.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,h.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===r.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,h.jsx)("span",{className:`truncate transition-opacity duration-500 ${B&&"ok"===r.tone?"opacity-0":"opacity-100"}`,children:r.text})]})]}),j&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:w.close,"aria-hidden":"true"}),d&&U&&(0,h.jsxs)("aside",{style:w.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 flex h-[var(--sheet-h)] flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${j?"translate-y-0":"pointer-events-none translate-y-full"} md:pointer-events-auto md:static md:z-auto md:h-auto md:w-96 md:translate-y-0 md:rounded-none md:border-l md:border-t-0 md:shadow-none md:transition-none ${n?"md:hidden":""}`,children:[(0,h.jsxs)("div",{className:"md:hidden",...w.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:W.find(a=>a.id===f)?.label}),(0,h.jsx)("button",{onClick:w.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:W.map(a=>(0,h.jsxs)("button",{onClick:()=>g(a.id),className:`relative flex-1 px-1 py-2 text-center text-xs transition-colors ${f===a.id?"border-b-2 border-blue-400 bg-gray-800/50 text-blue-400":"text-gray-500 hover:text-gray-300"}`,children:[a.label,void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1 top-1 min-w-[14px] rounded-full bg-red-900 px-1 text-[9px] text-red-100",children:a.badge})]},a.id))}),(0,h.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,h.jsxs)("section",{className:"members"===f?"":"hidden",children:[(0,h.jsx)("div",{className:e5,style:{marginTop:0},children:"Members"}),P.map(a=>{let b=d.members.find(b=>b.path===a),c=U.members.find(b=>b.path===a)?.notes;return(0,h.jsxs)("div",{className:"mb-1 rounded border border-gray-800",children:[(0,h.jsxs)("button",{onClick:()=>K(a),className:"flex w-full items-start gap-2 p-2 text-left hover:bg-gray-800",children:[(0,h.jsx)("span",{className:"mt-0.5 text-blue-300",children:(0,h.jsx)(e7,{kind:b?.kind??"machine"})}),(0,h.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,h.jsx)("span",{className:"block truncate text-[12px] font-semibold text-gray-200",children:fr(d,a)}),(0,h.jsx)("span",{className:"block truncate text-[10.5px] text-gray-500",children:a}),(0,h.jsx)("span",{className:`block text-[11px] ${b?.error?"text-red-300":"text-gray-400"}`,children:b?.error?`cannot be read: ${b.error}`:fw(b?.kind??"machine",b?.def)})]}),(0,h.jsx)("span",{className:"shrink-0 text-[11px] text-gray-500",children:"open ›"})]}),(0,h.jsx)("div",{className:"px-2 pb-2 [&_label]:mt-0",children:(0,h.jsx)(e1,{label:"Note on this member, in the system",value:c??"",placeholder:`Why ${fr(d,a)} is part of this system, what is open…`,onSave:b=>void L(function(a,b,c){let d=aX(a),e=d.members.findIndex(a=>a.path===b);if(e<0)throw Error(`'${b}' is not a member. Members: ${a.members.map(a=>a.path).join(", ")||"none"}.`);return d.members[e]=aY({...d.members[e],...c}),d}(U,a,{notes:b}),"saved")},`member:${a}`)})]},a)}),(0,h.jsx)("div",{className:e5,children:"Links between members"}),0===H.size&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"No name crosses between the members yet."}),[...H.entries()].map(([a,b])=>(0,h.jsxs)("div",{className:"mb-1",children:[(0,h.jsxs)("button",{className:`flex w-full items-center justify-between rounded px-1.5 py-1 text-left text-[11px] ${p===a?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,onClick:()=>q(p===a?null:a),children:[(0,h.jsxs)("span",{className:"truncate",children:[fr(d,b.a)," ↔ ",fr(d,b.b)]}),(0,h.jsx)("span",{className:"shrink-0 text-gray-500",children:b.links.length})]}),p===a&&(0,h.jsx)("div",{className:"ml-2 border-l border-gray-800 pl-2",children:b.links.map((a,b)=>(0,h.jsxs)("button",{className:"block w-full truncate py-0.5 text-left text-[11px] text-gray-400 hover:text-gray-200",title:`${fy(a)} — ${a.rule}`,onClick:()=>{let b;return K((b=a.from).member,a7(b))},children:[(0,h.jsx)("span",{className:"text-gray-600",children:a.rule})," ",fy(a)]},b))})]},a)),Q.length>0&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:e5,children:"Actors"}),Q.map(a=>(0,h.jsxs)("div",{className:"py-0.5 text-[11px] text-gray-300",children:[a.name," ",(0,h.jsxs)("span",{className:"text-gray-500",children:["· ",a.kind]}),a.description?(0,h.jsxs)("span",{className:"text-gray-500",children:[" — ",a.description]}):null]},a.name))]})]}),(0,h.jsxs)("section",{className:"checks"===f?"":"hidden",children:[(0,h.jsx)("div",{className:e5,style:{marginTop:0},children:"Checks"}),(0,h.jsxs)("div",{className:`text-[11px] ${I.length?"text-red-300":J.length?"text-amber-300":"text-green-400"}`,children:[I.length," error",1===I.length?"":"s"," · ",J.length," warning",1===J.length?"":"s"]}),Y.map(a=>(0,h.jsxs)("div",{className:"mt-2",children:[(0,h.jsxs)("div",{className:`text-[11px] font-semibold ${"error"===a.severity?"text-red-300":"text-amber-300"}`,children:[a.ruleId," · ",a.issues.length," ",a.severity,1===a.issues.length?"":"s"]}),a.issues.map((a,b)=>(0,h.jsxs)("button",{className:"block w-full py-0.5 pl-2 text-left text-[11px] text-gray-300 hover:text-white",onClick:()=>{a.member&&K(a.member,a.element&&/^[a-z]+:/.test(a.element)?a.element:null)},title:a.member?`Open ${a.member}${a.element?` at ${a.element}`:""}`:void 0,children:[a.message,a.member&&(0,h.jsxs)("span",{className:"text-gray-500",children:[" — ",fr(d,a.member)]})]},b))]},a.key)),(0,h.jsx)("div",{className:e5,children:"Reconcile"}),(0,h.jsxs)("p",{className:"mb-1 text-[11px] text-gray-500",children:["What the scenarios imply for the machines and the data. ",(0,h.jsx)("b",{className:"text-gray-400",children:"propose"})," lists it here to apply by hand; ",(0,h.jsx)("b",{className:"text-gray-400",children:"auto"})," writes it each time a scenario is saved."]}),(0,h.jsx)("span",{className:"inline-flex overflow-hidden rounded border border-gray-700",role:"group","aria-label":"Reconcile mode",children:aN.map(a=>(0,h.jsx)("button",{"aria-pressed":G===a,onClick:()=>{d?.def&&a!==G&&L(function(a,b){if(!aN.includes(b))throw Error(`The reconcile mode is ${aN.join(" or ")}; got '${b}'.`);return aZ(a,{reconcile:b})}(d.def,a),`reconcile mode: ${a}`)},className:`px-3 py-1 text-xs ${G===a?"bg-blue-900/60 text-blue-200":"bg-gray-800 text-gray-400 hover:bg-gray-700"}`,children:a},a))}),(0,h.jsx)("div",{className:"mt-2 text-[11px] font-semibold text-gray-400",children:"Scenario changes"}),F&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:"text-[11px] text-gray-500",children:be(F,"propose")}),F.machines.map(a=>(0,h.jsxs)("div",{className:"mt-1",children:[(0,h.jsxs)("div",{className:"text-[11px] text-gray-300",children:[a.machine," ",(0,h.jsxs)("span",{className:"text-gray-500",children:["· ",a.member]})]}),a.reasons.map((a,b)=>(0,h.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",a]},b))]},a.member)),F.erds.map(a=>(0,h.jsxs)("div",{className:"mt-1",children:[(0,h.jsxs)("div",{className:"text-[11px] text-gray-300",children:[a.def.settings?.name??a.member," ",(0,h.jsxs)("span",{className:"text-gray-500",children:["· ",a.member]})]}),a.reasons.map((a,b)=>(0,h.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",a]},b))]},a.member)),F.system&&(0,h.jsxs)("div",{className:"mt-1",children:[(0,h.jsx)("div",{className:"text-[11px] text-gray-300",children:"the system"}),F.system.reasons.map((a,b)=>(0,h.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",a]},b))]}),F.unresolved.map((a,b)=>(0,h.jsxs)("div",{className:"mt-1 text-[11px] text-amber-300",children:["left open: ",a]},b)),(0,h.jsx)("button",{className:`${e4} mt-2 disabled:opacity-40`,disabled:!F.count||u,onClick:M,children:u?"Applying…":`Apply${F.count?` ${F.count} change${1===F.count?"":"s"}`:""}`})]}),(D?.replays??[]).map(({member:a,report:b})=>(0,h.jsxs)("div",{children:[(0,h.jsxs)("div",{className:e5,children:["Replay · ",fr(d,a)]}),(0,h.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["against ",b.machines.join(", ")||"no machine"]}),b.paths.map(b=>(0,h.jsxs)("div",{className:"mb-2",children:[(0,h.jsxs)("div",{className:`text-[11px] font-semibold ${b.accepted?"text-green-400":"text-amber-300"}`,children:[b.name," — ",b.accepted?"accepted":"stops"]}),b.steps.filter(a=>"data"!==a.result).map(c=>(0,h.jsxs)("button",{className:`block w-full truncate py-0.5 pl-2 text-left font-mono text-[10.5px] ${"moved"===c.result||"stayed"===c.result?"text-gray-400":"text-amber-300"}`,title:c.note??c.result,onClick:()=>K(a,`message:${c.ref}`),children:[c.ref,". ",c.event??""," ",c.from.join("|")||"·"," → ",c.to.join("|")||"·"," ",c.result]},`${b.name}:${c.ref}`))]},b.name))]},a))]}),(0,h.jsxs)("section",{className:"notes"===f?"":"hidden",children:[(0,h.jsx)("div",{className:e5,style:{marginTop:0},children:"Notes"}),(0,h.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the system file, for whoever opens it next."}),(0,h.jsx)(e1,{label:"On this system",value:U.settings?.notes??"",placeholder:"What the system is for, what is still open…",onSave:a=>void L(aZ(U,{notes:a}),"saved")},"system"),U.settings?.description&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:e5,children:"Description"}),(0,h.jsx)("p",{className:"text-[11px] text-gray-400",children:U.settings.description})]})]})]})]})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:W.map(a=>{let b=j&&f===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(j&&f===b?w.close():k(!0),g(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1/2 top-1 min-w-[16px] translate-x-5 rounded-full border border-red-900/80 bg-red-950/80 px-1 text-[10px] leading-4 text-red-200",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})})]})}function fA(){let a=dM(a=>a.definition),b=dM(a=>a.layout.positions),c=dM(a=>a.navigationPath),d=dM(a=>a.viewport),e=dM(a=>a.setViewport),f=dM(a=>a.docPath),g=ez("focus"),j=(0,i.useMemo)(()=>({get current(){return document.getElementById("machine-board")}}),[]),k=c.slice(1),l=(0,i.useMemo)(()=>a?.state?function(a,b){let c=[];for(let d of a){let a=d?.name?b[d.name]:void 0;a&&c.push({focus:`state:${d.name}`,box:a})}for(let d of a){let e=d?.name?b[d.name]:void 0;if(e)for(let f of d.transitions??[]){if(!f?.event)continue;let d=f.nextState?b[f.nextState]:void 0;c.push({focus:`event:${f.event}`,box:d&&a.some(a=>a.name===f.nextState)?bp([e,d]):e})}}return c}(bw(a.state,k),b):[],[a,b,c]);return(0,h.jsx)(eR,{docPath:f,kind:"machine",viewport:d,setViewport:e,boxes:l,boardRef:j,focus:g,level:c[c.length-1],onReveal:a=>{let b=a.map(a8).find(a=>a?.kind==="state");if(!b)return;let c=new URL(window.location.href);c.searchParams.set("focus",`state:${b.name}`),window.history.replaceState(window.history.state,"",c),window.dispatchEvent(new Event(ew))}})}let fB=a=>a.parallel?a.parallel.states:a.states??[];function fC(a,b){if(!a)return null;if(a.name===b)return[a.name];for(let c of fB(a)){let d=fC(c,b);if(d)return[a.name,...d]}return null}function fD(){let a=(0,d4.useRequestedDoc)(),b=ez("system"),[c,d]=(0,i.useState)(null);(0,i.useEffect)(()=>{let a=!0;return ed().then(b=>{a&&d(b.projectFile?aS(b.projectFile):"machine")}),()=>{a=!1}},[]);let e=a?aS(a):c;if(null===e)return(0,h.jsx)("div",{className:"app-shell bg-gray-950"});let f=a??"default",g="erd"===e?(0,h.jsx)(e0,{},f):"sequence"===e?(0,h.jsx)(fq,{},f):"system"===e?(0,h.jsx)(fz,{},f):(0,h.jsx)(fE,{}),j=(0,h.jsx)(es,{what:"document",resetKey:a,children:g});return b&&aQ(b)?(0,h.jsx)(eO,{children:(0,h.jsxs)("div",{className:"system-frame",children:[(0,h.jsx)(fu,{systemPath:b}),j]})}):(0,h.jsx)(eO,{children:j})}function fE(){let a,b;a=eC(),b=(0,i.useRef)(null),(0,i.useEffect)(()=>{let c=()=>{let a=b.current;if(!a)return;let c=dM.getState(),d=null;if(d&&c.docPath!==d||a.docAt!==c.docPath&&c.definition===a.defAt)return;b.current=null;let e=a8(a.focus);if(!e)return;let f=null,g=null;if("state"===e.kind)(f=fC(c.definition.state,e.name))&&(g={kind:"state",id:e.name});else if("event"===e.kind){let a=function a(b,c){if(!b)return null;let d=(b.transitions??[]).findIndex(a=>a?.event===c);if(d>=0)return{state:b.name,index:d};for(let d of fB(b)){let b=a(d,c);if(b)return b}return null}(c.definition.state,e.name);a&&(f=fC(c.definition.state,a.state),g={kind:"transition",id:`${a.state}:${a.index}`})}if(!f||!g)return;let h=f.length>1?f.slice(0,-1):f;dM.setState({navigationPath:h,currentParent:h[h.length-1]}),c.select(g.kind,g.id);let i=()=>{let a=dM.getState().layout.positions[f[f.length-1]],b=document.getElementById(dQ)?.getBoundingClientRect();if(!a||!b?.width)return;let c=S([a],b.width,b.height,{padding:60,maxScale:1});dM.getState().setViewport(c)};requestAnimationFrame(i),setTimeout(i,450)};if(a.nonce>0){let d=dM.getState();b.current=a.focus?{focus:a.focus,docAt:d.docPath,defAt:d.definition}:null,c()}return dM.subscribe(c)},[a]),(0,i.useEffect)(()=>dM.subscribe((a,b)=>{if(a.selection===b.selection||!a.selection.id)return;let{kind:c,id:d}=a.selection;if("state"===c)eB(`state:${d}`);else if("event"===c)eB(`event:${d}`);else if("transition"===c){let b=function(a,b){let c=b.lastIndexOf(":"),d=fC(a.state,b.slice(0,c));if(!d)return null;let e=a.state;for(let a of d.slice(1))e=fB(e).find(b=>b.name===a);return e?.transitions?.[Number(b.slice(c+1))]?.event??null}(a.definition,d);b&&eB(`event:${b}`)}}),[]);let[c,d]=(0,i.useState)("properties"),[e,f]=(0,i.useState)(!1),g=ev({onClose:()=>f(!1),restVh:70,tallVh:92}),j=dM(a=>a.errors),k=dM(a=>a.contextMenu),l=dM(a=>a.hideContextMenu),m=dM(a=>a.addState),n=dM(a=>a.removeState),o=dM(a=>a.setDrawMode),p=dM(a=>a.setDrawSource),q=[{id:"properties",label:"Properties",icon:"🎛"},{id:"events",label:"Events",icon:"⚡"},{id:"settings",label:"Settings",icon:"⚙"},{id:"validation",label:"Errors",icon:(0,h.jsx)(et,{}),badge:j.length||void 0}],r=q.find(a=>a.id===c)?.label??"";return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden",onClick:()=>k.visible&&l(),children:[(0,h.jsx)(ee,{}),(0,h.jsx)(eq,{}),(0,h.jsx)(d7,{}),(0,h.jsxs)("div",{className:"flex flex-1 min-h-0 overflow-hidden relative",children:[(0,h.jsxs)("div",{className:"relative flex-1 overflow-hidden",id:"machine-board",children:[(0,h.jsx)(es,{what:"state machine",children:(0,h.jsx)(dZ,{})}),(0,h.jsx)(fA,{})]}),e&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:g.close,"aria-hidden":"true"}),(0,h.jsxs)("aside",{style:g.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 h-[var(--sheet-h)] flex flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${e?"translate-y-0":"translate-y-full pointer-events-none"} md:static md:z-auto md:h-auto md:w-80 md:translate-y-0 md:pointer-events-auto md:rounded-none md:border-t-0 md:border-l md:shadow-none md:transition-none`,children:[(0,h.jsxs)("div",{className:"md:hidden",...g.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pt-2 pb-1",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:r}),(0,h.jsx)("button",{onClick:g.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:q.map(a=>(0,h.jsxs)("button",{onClick:()=>d(a.id),className:`flex-1 text-xs py-2 px-1 text-center transition-colors relative ${c===a.id?"text-blue-400 border-b-2 border-blue-400 bg-gray-800/50":"text-gray-500 hover:text-gray-300"}`,children:[a.label,void 0!==a.badge&&a.badge>0&&(0,h.jsx)("span",{className:"absolute top-1 right-1 bg-red-600 text-white text-[9px] rounded-full px-1 min-w-[14px]",children:a.badge})]},a.id))}),(0,h.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain",children:["properties"===c&&(0,h.jsx)(d_,{}),"events"===c&&(0,h.jsx)(d1,{}),"settings"===c&&(0,h.jsx)(d2,{}),"validation"===c&&(0,h.jsx)(d3,{})]})]}),(0,h.jsx)(d8,{})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:q.map(a=>{let b=e&&c===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(e&&c===b?g.close():f(!0),d(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&a.badge>0&&(0,h.jsx)("span",{className:"absolute top-1 right-1/2 translate-x-4 rounded-full bg-red-600 px-1 text-[10px] leading-4 text-white min-w-[16px]",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})}),k.visible&&(0,h.jsx)("div",{className:"fixed z-50 bg-gray-900 border border-gray-700 rounded-lg shadow-xl py-1 min-w-[180px] md:min-w-[140px]",style:{left:k.x,top:k.y,maxWidth:"calc(100vw - 1rem)",maxHeight:"calc(100dvh - 1rem)",overflowY:"auto",transform:"translate(0, 0)"},onClick:a=>a.stopPropagation(),children:k.target?.kind==="state"?(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("button",{className:"block w-full text-left text-sm text-gray-300 hover:bg-gray-800 px-4 py-3 md:text-xs md:px-3 md:py-1.5",onClick:()=>{o("transition"),p(k.target.id),l()},children:"↗ Draw transition from here"}),(0,h.jsx)("button",{className:"block w-full text-left text-sm text-red-400 hover:bg-gray-800 px-4 py-3 md:text-xs md:px-3 md:py-1.5",onClick:()=>{k.target?.id&&n(k.target.id),l()},children:"🗑 Delete state"})]}):(0,h.jsx)(h.Fragment,{children:(0,h.jsx)("button",{className:"block w-full text-left text-sm text-gray-300 hover:bg-gray-800 px-4 py-3 md:text-xs md:px-3 md:py-1.5",onClick:()=>{let a=prompt("State name:");a&&m(null,{name:a,kind:"normal"}),l()},children:"+ Add state here"})})})]})}a.s(["default",()=>fD],95421)}];
|
|
14
|
+
No marks.`);navigator.clipboard?.writeText(f).then(()=>{B(!0),setTimeout(()=>B(!1),2e3)})},copied:A,onClose:()=>v(!1)})})]})}function eV({docPath:a,onReveal:b}){let c=eP(),d=c?.lit??null,e=(0,i.useRef)(-1);return(0,i.useEffect)(()=>{!d||e.current===d.nonce||d.doc&&d.doc!==a||(d.spotlight?.length||d.region)&&(e.current=d.nonce,b())},[d,a,b]),null}function eW(a,b,c){try{return a()}catch(d){let a=d instanceof Error?d.message:String(d);return console.warn("[stateloom] skipped on a malformed document:",a),c?.(a),b}}let eX=(a,b)=>"chen"===b?`stateloom:erd-layout:chen:${a}`:`stateloom:erd-layout:${a}`,eY="stateloom:erd-notation",eZ="stateloom:erd-lock";function e$(a,b){try{return JSON.parse(localStorage.getItem(eX(a,b))??"{}")}catch{return{}}}async function e_(a){let b=a.slice(0,a.lastIndexOf("/")),c=((await (await fetch("/api/docs",{cache:"no-store"})).json()).docs??[]).map(a=>a.path).filter(a=>a.endsWith(".smdf.json")&&a.slice(0,a.lastIndexOf("/"))===b),d=[];for(let a of c)try{let b=await (await fetch(`/api/file${(0,d4.docQuery)(a)}`,{cache:"no-store"})).json(),c=JSON.parse(b.content??"null"),e=aq(c?.stateMachine??c?.StateMachine??c);e?.state&&d.push({path:a,def:e})}catch{}return d}let e0="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",e1="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",e2="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function e3(){let a=(0,d4.useRequestedDoc)(),[b,c]=(0,i.useState)(""),[d,e]=(0,i.useState)(null),[f,g]=(0,i.useState)({}),[j,k]=(0,i.useState)("crowsfoot"),[l,m]=(0,i.useState)(!1),[n,o]=(0,i.useState)({...M}),[p,q]=(0,i.useState)(0),[r,s]=(0,i.useState)(null),[t,u]=(0,i.useState)({text:"loading…",tone:"ok"}),v=(0,i.useCallback)((a,b="ok")=>u({text:a,tone:b}),[]),[w,x]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=setTimeout(()=>x(!0),4e3);return()=>{clearTimeout(a),x(!1)}},[t]);let[y,z]=(0,i.useState)("entities"),[A,B]=(0,i.useState)(!1),[C,D]=(0,i.useState)(!1),[E,F]=(0,i.useState)(!1),G=(0,i.useRef)(null),H=ev({onClose:()=>B(!1),restVh:62,tallVh:92}),[I,J]=(0,i.useState)(0),[K,L]=(0,i.useState)(null),N=(0,i.useRef)(null);(0,i.useEffect)(()=>{let b=!1,d=null;return(async()=>{let f=await (await fetch(`/api/file${(0,d4.docQuery)(a)}`,{cache:"no-store"})).json();if(b)return;if(f.error)return v(f.error,"warn");let h=f.path??"",i=null;try{let a=f.content?aq(JSON.parse(f.content)):null;X(a)&&(i={...a,relationships:a.relationships??[]})}catch{}if(f.exists&&!i)return v(`${h} is not a readable ERD definition`,"warn");let j=(h.split("/").pop()??"Untitled").replace(/\.erdf\.json$/i,""),l=function(){try{return"chen"===localStorage.getItem(eY)?"chen":"crowsfoot"}catch{return"crowsfoot"}}();c(h),e(i??{settings:{namespace:"Default",name:j},entities:[],relationships:[]}),k(l),m(function(){try{let a=localStorage.getItem(eZ);if(null!==a)return"1"===a;return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}()),g(e$(h,l)),s(null),L(null),q(a=>a+1),v(f.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:n}=await ed();!b&&n&&(N.current=d=dy({url:n,role:"web",docId:h,name:"web-designer",onFull:a=>{let b=a.def;X(b)&&(e({...b,relationships:b.relationships??[]}),v("updated live"))},onPatch:()=>{},onPresence:a=>J(a.length)}),d.connect())})().catch(a=>!b&&v(String(a),"warn")),()=>{b=!0,N.current=null,d?.disconnect()}},[a,v]);let O=(0,i.useMemo)(()=>{if(!d)return{};let a=eW(()=>(function(a,b={}){let c=b.notation??"crowsfoot",d=b.hSpacing??70,e=b.vSpacing??("chen"===c?130:90),f="chen"===c?aj:as,g=[],h=new Set;for(let b of a.entities??[])!b?.name||h.has(b.name)||(h.add(b.name),g.push(b));let i=new Map,j=(a,b,c=new Set)=>a===b||!c.has(a)&&(c.add(a),(i.get(a)??[]).some(a=>j(a,b,c)));for(let b of a.relationships??[]){if(!b||!h.has(b.from)||!h.has(b.to)||b.from===b.to)continue;let[a,c]="N:1"===b.cardinality?[b.to,b.from]:[b.from,b.to];if((i.get(a)??[]).includes(c)||j(c,a))continue;let d=i.get(a);d?d.push(c):i.set(a,[c])}let k=new Map,l=(a,b)=>{if(!((k.get(a)??-1)>=b))for(let c of(k.set(a,b),i.get(a)??[]))l(c,b+1)},m=new Set([...i.values()].flat());for(let a of g)m.has(a.name)||l(a.name,0);for(let a of g)k.has(a.name)||l(a.name,0);for(let a of[...g].sort((a,b)=>k.get(b.name)-k.get(a.name))){let b=i.get(a.name)??[];b.length&&k.set(a.name,Math.min(...b.map(a=>k.get(a)))-1)}let n=[],o=new Map,p=(a,b)=>((n[b]??=[]).push(a),o.set(a.id,a),a);for(let a of g)p({id:a.name,entity:a.name,...f(a),upper:[],lower:[],x:0},k.get(a.name)??0);let q=0;for(let[a,b]of i)for(let c of b){let b=a;for(let d=k.get(a)+1;d<k.get(c);d++){let a=p({id:`\u0000lane${q++}`,width:28,height:0,upper:[],lower:[],x:0},d);o.get(b).lower.push(a.id),a.upper.push(b),b=a.id}o.get(b).lower.push(c),o.get(c).upper.push(b)}for(let a=n.length-1;a>=0;a--)n[a]?.length||n.splice(a,1);let r=(a,b)=>a.length?a.reduce((a,c)=>a+b(o.get(c)),0)/a.length:null,s=(a,b)=>{let c=new Map;for(let a of n)a.forEach((a,b)=>c.set(a.id,b));let d=new Map(a.map((a,d)=>[a.id,r(a[b],a=>c.get(a.id))??d]));a.sort((a,b)=>d.get(a.id)-d.get(b.id))};for(let a=0;a<2;a++){for(let a=1;a<n.length;a++)s(n[a],"upper");for(let a=n.length-2;a>=0;a--)s(n[a],"lower")}let t=a=>a.x+a.width/2,u=(a,b)=>{let c=0;for(let e of a){let a=r(e[b],t);e.x=Math.max(c,null===a?c:a-e.width/2),c=e.x+e.width+d}};for(let a of n)u(a,"upper");for(let a=n.length-2;a>=0;a--)u(n[a],"lower");let v=Math.min(0,...[...o.values()].map(a=>a.x)),w={},x=40;for(let a of n){for(let b of a)b.entity&&(w[b.entity]={x:Math.round(b.x-v)+40,y:x,width:b.width,height:b.height});x+=Math.max(0,...a.map(a=>a.height))+e}return w})(d,{notation:j}),{});for(let[b,c]of Object.entries(f))a[b]&&(a[b]={...a[b],...c});return a},[d,f,j]),P=(0,i.useMemo)(()=>{if(!d)return[];let a="";return eW(()=>Y(d),null,b=>a=b)??[{ruleId:"E000",message:`The document could not be checked (${a}): a field is not the shape Spec 80 gives it`}]},[d]),R=(0,i.useMemo)(()=>P.map(a=>(a.element??"").split(/[.[]/)[0]).filter(Boolean),[P]),T=(0,i.useCallback)(async a=>{let c;if(d&&b){try{c=a(d)}catch(a){return v(a instanceof Error?a.message:String(a),"warn")}e(c),L(null);try{let a=await fetch(`/api/file${(0,d4.docQuery)(b)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(c,null,2)+"\n"})});if(!a.ok)throw Error((await a.json())?.error??`HTTP ${a.status}`);N.current?.emitFull(c),v("saved")}catch(a){v(`not saved: ${a instanceof Error?a.message:String(a)}`,"warn")}}},[d,b,v]),U=(0,i.useCallback)((a,c)=>{g(d=>{let e={...d,[a]:{x:Math.round(c.x),y:Math.round(c.y)}};try{localStorage.setItem(eX(b,j),JSON.stringify(e))}catch{}return e})},[b,j]),Z=()=>{g({});try{localStorage.removeItem(eX(b,j))}catch{}q(a=>a+1)},af=async()=>{if(!d)return;v("checking links…");let a=await e_(b);if(0===a.length)return L("none"),z("issues"),B(!0),v("no .smdf.json beside this document to check against","warn");let c=a.flatMap(a=>$(a.def,d).map(b=>({...b,message:`${a.def.settings?.name??a.path}: ${b.message}`})));c.push(..._(d,a.map(a=>a.def.settings?.name??""))),L(c),z("issues"),B(!0),F(!1),v(`checked ${a.length} machine(s): ${c.length} problem(s)`,c.length?"warn":"ok")},ag=async a=>{let c=(await e_(b)).find(b=>b.def.settings?.name===a);c?(0,d4.navigateToDoc)(c.path):v(`no .smdf.json beside this document defines '${a}'`,"warn")},ah=()=>{let a=G.current?.getBoundingClientRect();return{width:a?.width??0,height:a?.height??0}},ai=a=>{let{width:b,height:c}=ah();o(d=>Q(d,a,{x:b/2,y:c/2}))},al=a=>{let b=O[a],{width:c,height:d}=ah();b&&c&&(o(S([b],c,d,{padding:28,maxScale:1.25})),s(a),H.close())},ap=eC(),ar=ez("focus"),at=(0,i.useMemo)(()=>d?eW(()=>(function(a,b,c={}){let d=!1!==c.rows,e=[];for(let c of a?.entities??[]){let a=c?.name?b[c.name]:void 0;a&&(e.push({focus:`entity:${c.name}`,box:a}),(c.attributes??[]).filter(a=>a?.name).forEach((b,f)=>{e.push({focus:`attribute:${c.name}.${b.name}`,box:d?{x:a.x,y:a.y+30+20*f,width:a.width,height:20}:a})}))}return e})(d,O,{rows:"chen"!==j}),[]):[],[d,O,j]),au=(0,i.useRef)(-1);(0,i.useEffect)(()=>{if(!d||au.current===ap.nonce)return;au.current=ap.nonce;let a=ap.focus?a8(ap.focus):null,b=a?.kind==="entity"?a.name:a?.kind==="attribute"?a.name.split(".")[0]:null;b&&O[b]&&al(b)},[d,ap,O]),(0,i.useEffect)(()=>{r&&1&&eB(`entity:${r}`)},[r]);let av=d?.entities.find(a=>a.name===r)??null,aw=b.split("/").pop()||"…",ax=Array.isArray(K)?K:[],ay=P.length+ax.length,az=[{id:"entities",label:"Entities",icon:"▭"},{id:"relations",label:"Relations",icon:"⟷"},{id:"notes",label:"Notes",icon:"✎",badge:void 0},{id:"issues",label:"Issues",icon:(0,h.jsx)(et,{}),badge:ay||void 0}],aA=a=>y===a?"":"hidden md:block",aB=()=>{d&&navigator.clipboard?.writeText(function(a){let b=["erDiagram"],c=" ",d=new Set;for(let e of a.relationships??[]){if(!e?.from||!e?.to)continue;let a=ak[e.cardinality]??ak["1:N"];b.push(`${c}${am(e.from)} ${a} ${am(e.to)} : ${ao(e.label??"")}`),d.add(e.from),d.add(e.to)}let e=new Set;for(let f of a.entities??[]){if(!f?.name||e.has(f.name))continue;e.add(f.name);let a=(f.attributes??[]).filter(a=>a?.name);if(0===a.length){d.has(f.name)||b.push(`${c}${am(f.name)}`);continue}for(let d of(b.push(`${c}${am(f.name)} {`),a))b.push(`${c}${c}${function(a){let b=[];"pk"===a.key&&b.push("PK"),"uk"===a.key&&b.push("UK"),a.references&&b.push("FK");let c=[],d=V(a);d.length&&c.push(`stateOf ${d.join(", ")}`),a.description&&c.push(a.description);let e=[an(a.type??"","unknown"),an(a.name,"unnamed")];return b.length&&e.push(b.join(", ")),c.length&&e.push(ao(c.join(" — "))),e.join(" ")}(d)}`);b.push(`${c}}`)}return b.join("\n")}(d)).then(()=>v("mermaid copied"))};return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&D(!1),children:[(0,h.jsxs)("header",{className:"relative z-40 flex items-center gap-2 border-b border-gray-800 bg-gray-900 px-2 py-1.5 text-xs md:px-3 md:py-2",children:[(0,h.jsx)("span",{className:"font-semibold text-blue-300",children:"ERD"}),(0,h.jsx)(d5,{}),(0,h.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:b,children:[d?.settings.name??aw,(0,h.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",aw]})]}),(0,h.jsx)("span",{className:"inline-flex shrink-0 overflow-hidden rounded border border-gray-700",role:"group","aria-label":"Notation",children:[["crowsfoot","▤","Crow's foot — attributes listed inside the entity box"],["chen","◇","Chen — attributes as ovals, relationships as diamonds"]].map(([a,c,d])=>(0,h.jsx)("button",{title:d,"aria-label":d,"aria-pressed":j===a,onClick:()=>(a=>{if(a!==j){try{localStorage.setItem(eY,a)}catch{}k(a),g(e$(b,a)),q(a=>a+1)}})(a),className:`px-2.5 py-1.5 text-sm leading-none md:px-2 md:py-1 ${j===a?"bg-blue-900/60 text-blue-200":"bg-gray-800 text-gray-400 hover:bg-gray-700"}`,children:c},a))}),(0,h.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,h.jsx)("button",{className:e1,onClick:Z,title:"Forget the dragged positions and lay the board out again",children:"⤢ Arrange"}),(0,h.jsx)("button",{className:e1,onClick:af,title:"Check the state machines beside this document against it",children:"Check links"}),(0,h.jsx)("button",{className:e1,onClick:aB,children:"Copy mermaid"}),(0,h.jsx)("button",{className:e1,onClick:()=>F(a=>!a),"aria-pressed":!E,title:E?"Show the panel":"Hide the panel — the board takes the full width",children:E?"⟨ Panel":"Panel ⟩"})]}),(0,h.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,h.jsx)("button",{className:"rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-sm leading-none text-gray-200","aria-label":"More actions","aria-expanded":C,onClick:a=>{a.stopPropagation(),D(a=>!a)},children:"⋯"}),C&&(0,h.jsx)("div",{className:"absolute right-0 top-full z-50 mt-1 w-56 overflow-hidden rounded-lg border border-gray-700 bg-gray-900 py-1 shadow-xl",children:[["⤢ Arrange the board",Z],["Check links to the machines",af],["Copy as mermaid",aB]].map(([a,b])=>(0,h.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{D(!1),b()},children:a},a))})]})]}),(0,h.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,h.jsxs)("div",{ref:G,className:"relative min-w-0 flex-1 overflow-hidden",children:[d&&(0,h.jsx)(es,{what:"diagram",resetKey:d,children:(0,h.jsx)(bL,{definition:d,notation:j,positions:O,viewport:n,onViewportChange:o,selection:r,readOnly:l,errorElements:R,fitKey:p,onSelect:s,onClearSelection:()=>s(null),onEntityMove:U,onOpenMachine:ag,emptyHint:"No entities yet — add one in the panel, or let an agent call add_entity."})}),d&&(0,h.jsx)(eU,{docPath:b||null,kind:"erd",viewport:n,setViewport:o,boxes:at,boardRef:G,focus:ar}),(0,h.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 flex max-w-[75%] items-center gap-1.5 rounded bg-gray-950/70 px-1.5 py-0.5 text-[11px] ${"warn"===t.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,h.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===t.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,h.jsxs)("span",{className:`truncate transition-opacity duration-500 ${w&&"ok"===t.tone?"opacity-0":"opacity-100"}`,children:[t.text,I>1?` \xb7 ${I} in the room`:""]})]}),(0,h.jsxs)("div",{className:"absolute bottom-3 right-3 flex flex-col overflow-hidden rounded-lg border border-gray-700 bg-gray-900/90 shadow-lg backdrop-blur",children:[(0,h.jsx)("button",{title:l?"Shapes are locked: dragging moves the view. Tap to unlock.":"Lock the shapes in place, so dragging only moves the view","aria-label":"Lock shapes in place","aria-pressed":l,onClick:()=>{let a=!l;m(a);try{localStorage.setItem(eZ,a?"1":"0")}catch{}v(a?"shapes locked — a drag anywhere moves the view":"shapes unlocked — drag one to move it")},className:`flex h-10 w-10 items-center justify-center border-b border-gray-800 hover:bg-gray-800 md:h-8 md:w-8 ${l?"bg-blue-950/60 text-blue-300":"text-gray-400"}`,children:(0,h.jsx)(eu,{locked:l})}),[["+","Zoom in",()=>ai(1.25)],["−","Zoom out",()=>ai(.8)],["⛶","Fit the whole diagram",()=>q(a=>a+1)]].map(([a,b,c])=>(0,h.jsx)("button",{title:b,"aria-label":b,onClick:c,className:"h-10 w-10 border-b border-gray-800 text-base leading-none text-gray-200 last:border-b-0 hover:bg-gray-800 md:h-8 md:w-8 md:text-sm",children:a},b))]}),av&&!A&&(0,h.jsxs)("button",{className:"absolute bottom-3 left-1/2 max-w-[60%] -translate-x-1/2 truncate rounded-full border border-blue-500/60 bg-gray-900/95 px-4 py-2 text-sm text-blue-200 shadow-lg md:hidden",onClick:()=>{z("entities"),B(!0)},children:["✎ ",av.name]})]}),A&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:H.close,"aria-hidden":"true"}),d&&(0,h.jsxs)("aside",{style:H.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 flex h-[var(--sheet-h)] flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${A?"translate-y-0":"pointer-events-none translate-y-full"} md:pointer-events-auto md:static md:z-auto md:h-auto md:w-80 md:translate-y-0 md:rounded-none md:border-l md:border-t-0 md:shadow-none md:transition-none ${E?"md:hidden":""}`,children:[(0,h.jsxs)("div",{className:"md:hidden",...H.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:az.find(a=>a.id===y)?.label}),(0,h.jsx)("button",{onClick:H.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,h.jsxs)("section",{className:aA("entities"),children:[(0,h.jsx)("div",{className:e2,style:{marginTop:0},children:"Entities"}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:d.entities.map(a=>(0,h.jsx)("button",{className:`${e1} ${r===a.name?"border-blue-500 text-blue-300":""}`,onClick:()=>s(a.name),children:a.name},a.name))}),(0,h.jsx)(e5,{fields:[{name:"name",placeholder:"new entity"}],submit:"+ Entity",onSubmit:a=>{T(b=>ad(b,{name:a.name.trim()})),s(a.name.trim())}}),av&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:`${e2} flex items-center justify-between gap-2`,children:[(0,h.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:av.name}),(0,h.jsx)("button",{className:`${e1} normal-case tracking-normal`,onClick:()=>al(av.name),title:"Bring this entity to the middle of the board at a readable size",children:"◎ Show on board"})]}),(0,h.jsxs)("label",{className:"mb-1 flex items-center gap-2 text-[11px] text-gray-400",title:"Exists only through another entity (an order line, without its order). Chen draws it as a double rectangle.",children:[(0,h.jsx)("input",{type:"checkbox",checked:!!av.weak,onChange:a=>T(b=>ae(b,av.name,{weak:a.target.checked}))}),"weak entity"]}),(av.attributes??[]).map(a=>(0,h.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 font-mono text-[11px]",children:[(0,h.jsxs)("span",{className:a.stateOf?"text-blue-300":"text-gray-300",children:[a.name," : ",a.type,(0,h.jsxs)("span",{className:"text-gray-500",children:[a.key?` ${a.key.toUpperCase()}`:"",a.references?` → ${a.references}`:"",a.stateOf?` ◉ ${[a.stateOf].flat().join(", ")}`:""]})]}),(0,h.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":`Remove ${a.name}`,onClick:()=>T(b=>(function(a,b,c){let d=aa(a),e=ab(d,b),f=e.attributes?.length??0;if(e.attributes=(e.attributes??[]).filter(a=>a.name!==c),e.attributes.length===f)throw Error(`Attribute '${b}.${c}' not found.`);return d})(b,av.name,a.name)),children:"✕"})]},a.name)),(0,h.jsx)(e5,{fields:[{name:"name",placeholder:"attribute"},{name:"type",placeholder:"type",initial:"string"},{name:"key",options:["","pk","uk"]},{name:"references",placeholder:"references Entity.attr"},{name:"stateOf",placeholder:"stateOf Machine"}],submit:"+ Attribute",onSubmit:a=>T(b=>(function(a,b,c){if(!c.name?.trim())throw Error("An attribute needs a name.");let d=aa(a),e=ab(d,b);if(e.attributes??=[],e.attributes.some(a=>a.name===c.name))throw Error(`Attribute '${b}.${c.name}' already exists.`);return e.attributes.push(ac({...c})),d})(b,av.name,{name:a.name.trim(),type:a.type.trim()||"string",key:"pk"===a.key||"uk"===a.key?a.key:void 0,references:a.references.trim()||void 0,stateOf:a.stateOf.trim()||void 0}))}),(0,h.jsxs)("button",{className:`${e1} mt-2 text-red-300`,onClick:()=>{T(a=>{var b;let c;return b=av.name,ab(c=aa(a),b),c.entities=c.entities.filter(a=>a.name!==b),c.relationships=c.relationships.filter(a=>a.from!==b&&a.to!==b),c}),s(null)},children:["🗑 Delete ",av.name]})]})]}),(0,h.jsxs)("section",{className:aA("relations"),children:[(0,h.jsx)("div",{className:`${e2} max-md:mt-0`,children:"Relationships"}),0===d.relationships.length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),d.relationships.map((a,b)=>(0,h.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 text-[11px] text-gray-300",children:[(0,h.jsxs)("span",{children:[a.from," ",(0,h.jsx)("span",{className:"text-gray-500",children:a.cardinality})," ",a.to,a.label?(0,h.jsxs)("span",{className:"text-gray-500",children:[" : ",a.label]}):null]}),(0,h.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":"Remove relationship",onClick:()=>T(b=>(function(a,b,c,d){let e=aa(a),f=e.relationships.length;if(e.relationships=e.relationships.filter(a=>a.from!==b||a.to!==c||void 0!==d&&a.label!==d),e.relationships.length===f)throw Error(`No relationship from '${b}' to '${c}'${void 0===d?"":` labelled '${d}'`}.`);return e})(b,a.from,a.to,a.label)),children:"✕"})]},b)),d.entities.length>0&&(0,h.jsx)(e5,{fields:[{name:"from",options:d.entities.map(a=>a.name)},{name:"cardinality",options:[...W],initial:"1:N"},{name:"to",options:d.entities.map(a=>a.name)},{name:"label",placeholder:"label (a verb)"}],submit:"+ Relationship",onSubmit:a=>T(b=>(function(a,b){let c=aa(a);if(ab(c,b.from),ab(c,b.to),!W.includes(b.cardinality))throw Error(`Cardinality '${b.cardinality}' is not one of ${W.join(", ")}.`);return c.relationships.push(ac({...b})),c})(b,{from:a.from,to:a.to,cardinality:a.cardinality,label:a.label.trim()||void 0}))})]}),(0,h.jsxs)("section",{className:aA("notes"),children:[(0,h.jsx)("div",{className:`${e2} max-md:mt-0`,children:"Notes"}),(0,h.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the document, for whoever opens it next — you, or an agent (it reads them with get_notes)."}),(0,h.jsx)(e4,{label:"On this diagram",value:d.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:a=>T(b=>(function(a,b){let c=aa(a);for(let a of["description","notes"]){let d=b[a];void 0!==d&&(d.trim()?c.settings[a]=d:delete c.settings[a])}return c})(b,{notes:a}))},"diagram"),av?(0,h.jsx)(e4,{label:`On ${av.name}`,value:av.notes??"",placeholder:`A question or a decision about ${av.name}…`,onSave:a=>T(b=>ae(b,av.name,{notes:a}))},`entity:${av.name}`):(0,h.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Select an entity to leave a note on it."}),d.entities.some(a=>a.notes?.trim())&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:e2,children:"Entities with notes"}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:d.entities.filter(a=>a.notes?.trim()).map(a=>(0,h.jsx)("button",{className:`${e1} ${r===a.name?"border-blue-500 text-blue-300":""}`,onClick:()=>s(a.name),children:a.name},a.name))})]})]}),(0,h.jsxs)("section",{className:aA("issues"),children:[(0,h.jsx)("div",{className:`${e2} max-md:mt-0 ${0===ay&&!K?"md:hidden":""}`,children:"Issues"}),P.map((a,b)=>(0,h.jsxs)("div",{className:"py-0.5 text-[11px] text-red-300",children:["[",a.ruleId,"] ",a.message]},`p${b}`)),ax.map((a,b)=>(0,h.jsxs)("div",{className:"py-0.5 text-[11px] text-amber-300",children:["[",a.ruleId,"] ",a.message]},`l${b}`)),"none"===K&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-amber-300",children:"No state machine (.smdf.json) sits beside this document, so there was nothing to check it against."}),0===ay&&"none"!==K&&(0,h.jsx)("div",{className:`py-0.5 text-[11px] ${K?"text-green-400":"text-gray-600 md:hidden"}`,children:K?"Every name the machines use resolves.":"The document is valid. “Check links” (⋯) holds the state machines beside it against it."})]})]})]})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:az.map(a=>{let b=A&&y===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(A&&y===b?H.close():B(!0),z(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1/2 top-1 min-w-[16px] translate-x-5 rounded-full border border-red-900/80 bg-red-950/80 px-1 text-[10px] leading-4 text-red-200",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})})]})}function e4({label:a,value:b,placeholder:c,onSave:d}){let[e,f]=(0,i.useState)(b),[g,j]=(0,i.useState)(b),[k,l]=(0,i.useState)(!1);b!==g&&(j(b),k||f(b));let m=(0,i.useRef)(null),n=a=>{m.current&&clearTimeout(m.current),m.current=null,a!==b&&d(a)};return(0,h.jsxs)("label",{className:"mt-2 block",children:[(0,h.jsx)("span",{className:"text-[11px] text-gray-500",children:a}),(0,h.jsx)("textarea",{className:`${e0} h-24 resize-y leading-snug`,placeholder:c,value:e,onChange:a=>{let b=a.target.value;f(b),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>n(b),900)},onFocus:()=>l(!0),onBlur:()=>{l(!1),n(e)}})]})}function e5({fields:a,submit:b,onSubmit:c}){let d=()=>Object.fromEntries(a.map(a=>[a.name,a.initial??a.options?.[0]??""])),[e,f]=(0,i.useState)(d),g=a[0];return(0,h.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:b=>{b.preventDefault();let h={...d(),...e};h[g.name]?.trim()&&(c(h),f(b=>Object.fromEntries(a.map(a=>[a.name,a.options?b[a.name]??"":a.initial??""]))))},children:[a.map(a=>a.options?(0,h.jsx)("select",{className:e0,"aria-label":a.name,value:e[a.name]??"",onChange:b=>f(c=>({...c,[a.name]:b.target.value})),children:a.options.map(b=>(0,h.jsx)("option",{value:b,children:b||`(${a.name})`},b))},a.name):(0,h.jsx)("input",{className:e0,"aria-label":a.name,placeholder:a.placeholder,value:e[a.name]??"",onChange:b=>f(c=>({...c,[a.name]:b.target.value}))},a.name)),(0,h.jsx)("button",{type:"submit",className:`${e1} ${1===a.length?"":"col-span-2"}`,children:b})]})}let e6="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",e7="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",e8="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function e9({id:a,fields:b,submit:c,onSubmit:d,reset:e=!1,required:f}){let g=()=>Object.fromEntries(b.map(a=>[a.name,a.initial??(!a.checkbox&&(a.options?a.options[0]??"":""))])),[j,k]=(0,i.useState)(g),l=(a,b)=>k(c=>({...c,[a]:b}));return(0,h.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:a=>{a.preventDefault();let c={...g(),...j};!(f??[]).some(a=>!String(c[a]??"").trim())&&(d(c),e&&k(a=>Object.fromEntries(b.map(b=>[b.name,b.options||b.checkbox?a[b.name]??"":b.initial??""]))))},children:[b.map(b=>{let c=b.label??b.name;if(b.checkbox)return(0,h.jsxs)("label",{className:"flex items-center gap-2 text-[11px] text-gray-400",children:[(0,h.jsx)("input",{type:"checkbox",checked:!!j[b.name],onChange:a=>l(b.name,a.target.checked)}),c]},b.name);if(b.options)return(0,h.jsx)("select",{className:`${e6} ${b.wide?"col-span-2":""}`,"aria-label":c,title:c,value:String(j[b.name]??""),onChange:a=>l(b.name,a.target.value),children:b.options.map(a=>(0,h.jsx)("option",{value:a,children:a||`(${c})`},a))},b.name);let d=b.suggest?.length?`${a}-${b.name}`:void 0;return(0,h.jsxs)("span",{className:b.wide?"col-span-2":"",children:[(0,h.jsx)("input",{className:e6,"aria-label":c,title:c,placeholder:b.placeholder??c,list:d,value:String(j[b.name]??""),onChange:a=>l(b.name,a.target.value)}),d&&(0,h.jsx)("datalist",{id:d,children:b.suggest.map(a=>(0,h.jsx)("option",{value:a},a))})]},b.name)}),(0,h.jsx)("button",{type:"submit",className:`${e7} col-span-2`,children:c})]})}function fa({kind:a,size:b=16}){return(0,h.jsxs)("svg",{width:b,height:b,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"shrink-0",children:["erd"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("rect",{x:"4",y:"4.5",width:"16",height:"15",rx:"1.5"}),(0,h.jsx)("path",{d:"M4 9h16M8 13h8M8 16.5h6"})]}),"machine"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("rect",{x:"2.5",y:"4",width:"8",height:"6",rx:"2.5"}),(0,h.jsx)("rect",{x:"13.5",y:"14",width:"8",height:"6",rx:"2.5"}),(0,h.jsx)("path",{d:"M6.5 10v4.5a2.5 2.5 0 0 0 2.5 2.5h4.5"}),(0,h.jsx)("path",{d:"M11.5 15l2 2-2 2"})]}),"sequence"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("path",{d:"M6 4v16M18 4v16",strokeDasharray:"2 2.2"}),(0,h.jsx)("path",{d:"M6 9h11M15 7l2 2-2 2"}),(0,h.jsx)("path",{d:"M18 15H7M9 13l-2 2 2 2"})]}),"system"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("rect",{x:"3",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,h.jsx)("rect",{x:"14",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,h.jsx)("rect",{x:"8.5",y:"14.5",width:"7",height:"6",rx:"1.5"}),(0,h.jsx)("path",{d:"M10 6.5h4M7 9.5l3 5M17 9.5l-3 5"})]}),"link"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("path",{d:"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1.2 1.2"}),(0,h.jsx)("path",{d:"M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1.2-1.2"})]}),"actor"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("circle",{cx:"12",cy:"7.5",r:"3.5"}),(0,h.jsx)("path",{d:"M5 20a7 7 0 0 1 14 0"})]})]})}let fb=["text-sky-300","text-emerald-300","text-amber-300","text-rose-300","text-violet-300","text-cyan-300","text-lime-300","text-orange-300"],fc=a=>`seq-read-${a.kind}-${a.id}`;function fd({definition:a,selection:b,issues:c,onSelect:d,onShowInDiagram:e}){let f=new Map(a.participants.map((a,b)=>[a.name,fb[b%fb.length]])),g=az(a),i=g.filter(a=>null===a.fragment),j=(a.fragments??[]).map((a,b)=>({f:a,fi:b,rows:g.filter(a=>a.fragment===b)})),k=(a,c)=>b?.kind===a&&b.id===c,l=a=>(0,h.jsx)("span",{className:`font-semibold ${f.get(a)??"text-gray-300"}`,children:a||"?"}),m=(a,b)=>{let f={kind:"message",id:a},g=c.get(`message:${a}`)??[],i=g.some(a=>"error"===a.severity)?"error":g.length?"warning":null,j=k("message",a);return(0,h.jsx)("li",{id:fc(f),className:"scroll-mt-16 scroll-mb-24",children:(0,h.jsxs)("div",{role:"button",tabIndex:0,"aria-pressed":j,onClick:()=>d(f),onKeyDown:a=>("Enter"===a.key||" "===a.key)&&(a.preventDefault(),d(f)),className:`flex gap-3 rounded-lg border-l-2 px-3 py-2.5 ${j?"bg-blue-950/60 ring-1 ring-blue-500/60":"hover:bg-gray-900"} ${"error"===i?"border-red-500":"warning"===i?"border-amber-400":"border-transparent"}`,children:[(0,h.jsx)("span",{className:"mt-0.5 flex h-6 min-w-6 shrink-0 items-center justify-center rounded-full border border-gray-700 bg-gray-900 px-1 font-mono text-[11px] text-gray-300",children:a}),(0,h.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,h.jsxs)("div",{className:"text-[13px] leading-5 text-gray-400",children:[l(b.from),b.from===b.to?(0,h.jsx)("span",{children:" to itself"}):(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("span",{className:"px-1.5 text-gray-500",children:b.reply?"⇠":"→"}),l(b.to)]}),b.reply&&(0,h.jsx)("span",{className:"ml-2 text-[11px] text-gray-500",children:"reply"}),b.optional&&(0,h.jsx)("span",{className:"ml-2 rounded border border-gray-700 px-1 text-[11px] text-gray-400",children:"optional"})]}),(0,h.jsx)("div",{className:`mt-0.5 break-words text-[15px] leading-6 ${b.reply?"text-gray-300":"text-gray-100"}`,children:b.label||(0,h.jsx)("span",{className:"text-gray-500",children:"no label"})}),(b.event||b.state||b.carries)&&(0,h.jsxs)("div",{className:"mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] leading-5",children:[b.event&&(0,h.jsx)("span",{className:"rounded border border-blue-500/50 bg-blue-950/50 px-1.5 font-mono text-blue-200",children:b.event}),b.event&&b.machine&&(0,h.jsxs)("span",{className:"text-gray-400",children:["on ",b.machine]}),b.state&&(0,h.jsxs)("span",{className:"text-emerald-300",children:["→ ",b.state]}),b.carries&&(0,h.jsxs)("span",{className:"text-gray-400",children:["carries ",b.carries]})]}),g.map((a,b)=>(0,h.jsx)("p",{className:`mt-1.5 text-[12px] leading-5 ${"error"===a.severity?"text-red-300":"text-amber-300"}`,children:a.text},b)),j&&(0,h.jsx)("button",{className:"mt-2 rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-[12px] text-gray-200",onClick:a=>{a.stopPropagation(),e(f)},children:"Show in the diagram"})]})]})},a)};return(0,h.jsx)("div",{className:"h-full overflow-y-auto overscroll-contain",children:(0,h.jsxs)("div",{className:"mx-auto max-w-2xl px-4 pb-28 pt-10",children:[a.participants.length>0&&(0,h.jsx)("ul",{className:"mb-4 flex flex-wrap gap-2","aria-label":"Participants",children:a.participants.map(a=>{let b={kind:"participant",id:a.name},e=a.actor?"actor":a.object?"object":a.service?"service":"",f=c.get(`participant:${a.name}`)??[];return(0,h.jsx)("li",{id:fc(b),children:(0,h.jsxs)("button",{onClick:()=>d(b),"aria-pressed":k("participant",a.name),title:f.map(a=>a.text).join("\n")||void 0,className:`rounded-full border px-3 py-1 text-[13px] ${k("participant",a.name)?"border-blue-500 bg-blue-950/60":"border-gray-700 bg-gray-900"} ${f.length?"ring-1 ring-amber-400/70":""}`,children:[l(a.name),e&&(0,h.jsx)("span",{className:"ml-1.5 text-[11px] text-gray-400",children:e})]})},a.name)})}),0===g.length&&(0,h.jsx)("p",{className:"text-sm text-gray-400",children:"No messages yet — add them in the panel, or let an agent write the scenario."}),(0,h.jsx)("ol",{className:"flex flex-col gap-1",children:i.map(({ref:a,message:b})=>m(a,b))}),j.map(({f:a,fi:b,rows:c})=>(0,h.jsxs)("section",{className:"mt-5 rounded-xl border border-indigo-500/50 bg-indigo-950/20 p-1.5",children:[(0,h.jsxs)("header",{className:"px-3 pb-1.5 pt-2",children:[(0,h.jsxs)("div",{className:"text-[12px] text-indigo-200",children:[(0,h.jsx)("span",{className:"font-semibold uppercase tracking-wide",children:a.kind}),(0,h.jsxs)("span",{className:"text-indigo-300",children:[" · after ",a.after]})]}),(0,h.jsx)("div",{className:"mt-0.5 break-words text-[14px] leading-5 text-gray-100",children:a.label})]}),0===c.length?(0,h.jsx)("p",{className:"px-3 pb-2 text-[12px] text-gray-400",children:"No messages in this fragment."}):(0,h.jsx)("ol",{className:"flex flex-col gap-1",children:c.map(({ref:a,message:b})=>m(a,b))})]},b))]})})}async function fe(a){try{let b=await fetch(`/api/file${(0,d4.docQuery)(a)}`,{cache:"no-store"}),c=await b.json();if(!b.ok||c.error)return{path:a??"",content:null,exists:!1,error:c.error??`HTTP ${b.status}`};return{path:c.path??a??"",content:c.content??null,exists:!!c.exists,mtime:c.mtime}}catch(b){return{path:a??"",content:null,exists:!1,error:b instanceof Error?b.message:String(b)}}}class ff extends Error{constructor(a){super(`${a.split("/").pop()} changed on disk since it was read`)}}async function fg(a,b,c){let d=await fetch(`/api/file${(0,d4.docQuery)(a)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(b,null,2)+"\n",...void 0!==c?{mtime:c}:{}})}),e=await d.json().catch(()=>({}));if(409===d.status)throw new ff(a);if(!d.ok)throw Error(e?.error??`HTTP ${d.status}`);return e?.mtime}async function fh(a){let b=await fe(a),c={path:b.path||a,def:null,members:[],absOf:{},wrapped:{},mtimes:{}};if(b.error)return{...c,error:b.error};if(!b.exists||!b.content)return{...c,error:`${a} does not exist`};let d=null;try{let a=aq(JSON.parse(b.content));aR(a)&&(d=a)}catch{}if(!d)return{...c,error:`${b.path} is not a readable system definition`};let e={},f={},g={[b.path]:b.mtime??0},h=await Promise.all((d.members??[]).filter(a=>a?.path).map(async a=>{let c=aV(b.path,a.path);e[a.path]=c;let d=aS(a.path),h=await fe(c);if(h.error)return{path:a.path,kind:d,def:null,error:h.error};if(!h.exists||!h.content)return{path:a.path,kind:d,def:null,error:"the file does not exist"};g[a.path]=h.mtime??0;try{let b=JSON.parse(h.content);if("machine"===d&&b&&(b.stateMachine||b.StateMachine))return f[a.path]=!0,{path:a.path,kind:d,def:aq(b.stateMachine??b.StateMachine)};return{path:a.path,kind:d,def:aq(b)}}catch(b){return{path:a.path,kind:d,def:null,error:`not JSON: ${b instanceof Error?b.message:String(b)}`}}}));return{path:b.path,def:d,members:h,absOf:e,wrapped:f,mtimes:g}}function fi(){window.dispatchEvent(new Event(ex))}function fj(a){let[b,c]=(0,i.useState)(null),[d,e]=(0,i.useState)(0),f=(0,i.useCallback)(()=>e(a=>a+1),[]);return(0,i.useEffect)(()=>(window.addEventListener(ex,f),()=>window.removeEventListener(ex,f)),[f]),(0,i.useEffect)(()=>{if(!a)return;let b=!0;return fh(a).then(d=>b&&c({for:a,system:d})),()=>{b=!1}},[a,d]),{system:a&&b?.for===a?b.system:null,reload:f}}function fk(a,b){if(!a||!b)return null;for(let[c,d]of Object.entries(a.absOf))if(d===b)return c;return null}async function fl(a,b,c,d){let{bridgeUrl:e}=await ed();if(!e)return;let f=dw({url:e,role:"web",docId:a,name:"web-reconcile",autoResync:!1});try{let a=await Promise.race([f.join(),new Promise((a,b)=>setTimeout(()=>b(Error("join timeout")),3e3))]),e=a.snapshot?.def,g=a=>(function(a){let b=JSON.stringify(a),c=0x811c9dc5;for(let a=0;a<b.length;a++)c^=b.charCodeAt(a),c=Math.imul(c,0x1000193);return(c>>>0).toString(16).padStart(8,"0")})(a);if(e&&g(e)===g(b))return;await new Promise(a=>{let h=f.on("ack",()=>{h(),a()});d&&e&&g(e)===g(d.from)?f.emitPatch(d.ops,c):f.emitFull(b,c),setTimeout(a,800)})}catch{}finally{f.disconnect()}}async function fm(a,b){let c=[],d=[],e=[],f=async(a,b)=>{try{await b(),c.push(a)}catch(b){b instanceof ff?e.push(a):d.push(`${a}: ${b instanceof Error?b.message:String(b)}`)}};for(let c of b.machines){let b=a.absOf[c.member];b&&c.ops.length&&await f(c.member,async()=>{let d=a.wrapped[c.member]?{stateMachine:c.def}:c.def,e=await fg(b,d,a.mtimes[c.member]),f=a.members.find(a=>a.path===c.member)?.def;await fl(b,c.def,e,{from:f,ops:c.ops})})}for(let c of b.erds){let b=a.absOf[c.member];b&&await f(c.member,async()=>{let d=await fg(b,c.def,a.mtimes[c.member]);await fl(b,c.def,d)})}return b.system&&await f(a.path.split("/").pop()??a.path,async()=>{let c=await fg(a.path,b.system.def,a.mtimes[a.path]);await fl(a.path,b.system.def,c)}),fi(),{written:c,failed:d,conflicts:e}}async function fn(a){let b={result:null,written:[],failed:[],conflicts:[]};for(let c=0;c<2;c+=1){let d=await fh(a);if(!d.def)return{...b,failed:[d.error??"the system could not be read"],retried:c>0};let e=bd(d.def,d.members);if(!e.count)return{...b,result:e,conflicts:c?b.conflicts:[],retried:c>0};let f=await fm(d,e);if(b={result:e,written:[...b.written,...f.written],failed:f.failed,conflicts:f.conflicts},!f.conflicts.length)return{...b,retried:c>0}}return{...b,retried:!0}}let fo="stateloom.sequence.view",fp=["","actor","service","object"],fq=a=>"string"==typeof a?a.trim():"",fr=a=>fq(a).split(",").map(a=>a.trim()).filter(Boolean);function fs(a){return{from:fq(a.from),to:fq(a.to),label:fq(a.label),event:fq(a.event),machine:fq(a.machine),carries:fq(a.carries),state:fq(a.state),description:fq(a.description),optional:!!a.optional||void 0,reply:!!a.reply||void 0}}function ft(){let a,b,c,d=(0,d4.useRequestedDoc)(),e=ez("system"),{system:f}=fj(e),g=eC(),[j,k]=(0,i.useState)(""),[l,m]=(0,i.useState)(null),[n,o]=(0,i.useState)({...M}),[p,q]=(0,i.useState)(void 0),[r,s]=(0,i.useState)(null),[t,u]=(0,i.useState)({text:"loading…",tone:"ok"}),v=(0,i.useCallback)((a,b="ok")=>u({text:a,tone:b}),[]),[w,x]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=setTimeout(()=>x(!0),4e3);return()=>{clearTimeout(a),x(!1)}},[t]);let[y,z]=(0,i.useState)("messages"),[A,B]=(0,i.useState)(!1),[C,D]=(0,i.useState)(!1),[E,F]=(0,i.useState)(!1),[G,H]=(0,i.useState)("diagram"),I=(0,i.useRef)("diagram");(0,i.useEffect)(()=>{let a=null;try{a=window.localStorage.getItem(fo)}catch{}let b="list"===a||"diagram"===a?a:window.matchMedia("(max-width: 767px)").matches?"list":"diagram";I.current=b,H(b)},[]);let J=(0,i.useCallback)(a=>{I.current=a,H(a);try{window.localStorage.setItem(fo,a)}catch{}},[]),K=(0,i.useRef)(null),L=ev({onClose:()=>B(!1),restVh:62,tallVh:92}),[O,P]=(0,i.useState)(0),R=(0,i.useRef)(null),T=(0,i.useRef)(!0),U=(0,i.useRef)(-1);(0,i.useEffect)(()=>{let a=!1,b=null;return(async()=>{let c=await (await fetch(`/api/file${(0,d4.docQuery)(d)}`,{cache:"no-store"})).json();if(a)return;if(c.error)return v(c.error,"warn");let e=c.path??"",f=null;try{let a=c.content?aq(JSON.parse(c.content)):null;av(a)&&(f=a)}catch{}if(c.exists&&!f)return v(`${e} is not a readable sequence definition`,"warn");let g=(e.split("/").pop()??"Untitled").replace(/\.sqdf\.json$/i,"");k(e),m(f??aw("Default",g)),v(c.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:h}=await ed();!a&&h&&(R.current=b=dy({url:h,role:"web",docId:e,name:"web-designer",onFull:a=>{let b=a.def;av(b)&&(m(b),v("updated live"))},onPatch:()=>{},onPresence:a=>P(a.length)}),b.connect())})().catch(b=>!a&&v(String(b),"warn")),()=>{a=!0,R.current=null,b?.disconnect()}},[d,v]);let V=(0,i.useMemo)(()=>l?bR(l):null,[l]),W=(0,i.useMemo)(()=>V?aL(V):null,[V]),X=(0,i.useMemo)(()=>V&&W?eW(()=>(function(a,b){let c=[];for(let a of b.participants)c.push({focus:`participant:${a.name}`,box:{x:a.left,y:a.top,width:a.width,height:Math.max(a.height,b.lifelineBottom-a.top)}});let d=new Map(az(a).map(a=>[a.ref,a.message]));for(let a of b.rows){let b=a.self?a.fromX:Math.min(a.fromX,a.toX),e=a.self?220:Math.max(40,Math.abs(a.toX-a.fromX)),f={x:b-10,y:a.y-24,width:e+20,height:40};c.push({focus:`message:${a.ref}`,box:f});let g=d.get(a.ref)?.event;g&&c.push({focus:`event:${g}`,box:f})}return c})(V,W),[]):[],[V,W]),Y=ez("focus"),Z=(0,i.useMemo)(()=>{if(!l)return[];let a="";return eW(()=>aA(l),null,b=>a=b)??[{ruleId:"S000",message:`The document could not be checked (${a}): a field is not the shape Spec 81 gives it`}]},[l]),$=fk(f,j),_=(0,i.useMemo)(()=>f?.def&&$&&l?eW(()=>a6(f.def,f.members.map(a=>a.path===$?{...a,def:l,error:void 0}:a)),null):null,[f,$,l]),aa=(0,i.useMemo)(()=>(_?.issues??[]).filter(a=>a.member===$&&!/^S0/.test(a.ruleId)),[_,$]),ab=_?.replays.find(a=>a.member===$)?.report??null,ac=(0,i.useMemo)(()=>(function(a){let b={events:new Set,states:new Set,machines:new Set,objects:new Set,entities:new Set,actors:new Set};if(!a)return{events:[],states:[],machines:[],objects:[],entities:[],actors:[]};let{machines:c,erds:d}=a5(a.members);for(let{def:a}of(c.forEach(({def:a},c)=>{for(let d of(b.machines.add(a_(a,c)),a.events??[]))for(let a of[...d?.events??[],...d?.timers??[]])a?.id&&b.events.add(a.id);for(let c of a.settings?.objects??[])c?.instance&&b.objects.add(c.instance);let d=a=>{a&&(b.states.add(a.name),(a.states??[]).forEach(d),(a.parallel?.states??[]).forEach(d))};d(a.state)}),d))for(let c of a.entities??[])c?.name&&b.entities.add(c.name);for(let c of a.def?.actors??[])c?.name&&b.actors.add(c.name);let e=a=>[...a].sort((a,b)=>a.localeCompare(b));return{events:e(b.events),states:e(b.states),machines:e(b.machines),objects:e(b.objects),entities:e(b.entities),actors:e(b.actors)}})(f),[f]),ad=(0,i.useMemo)(()=>{let a=a=>a?/^(message|participant):/.test(a)?a:V?.participants.some(b=>b.name===a)?`participant:${a}`:"":"";return[...Z.map(b=>a(b.element)),...aa.filter(a=>"error"===a.severity).map(b=>a(b.element))].filter(Boolean)},[Z,aa,V]),ae=(0,i.useMemo)(()=>aa.filter(a=>"warning"===a.severity).map(a=>a.element??""),[aa]),af=(0,i.useMemo)(()=>{let a=new Map,b=(b,c)=>{let d=b?/^(message|participant):/.test(b)?b:V?.participants.some(a=>a.name===b)?`participant:${b}`:"":"";d&&a.set(d,[...a.get(d)??[],c])};return Z.forEach(a=>b(a.element,{severity:"error",text:a.message})),aa.forEach(a=>b(a.element,{severity:"error"===a.severity?"error":"warning",text:a.message})),a},[Z,aa,V]),ag=()=>{let a=K.current?.getBoundingClientRect();return{width:a?.width??0,height:a?.height??0}},ah=(0,i.useCallback)(a=>{let b=K.current?.getBoundingClientRect();if(!b?.width)return;let c=N(Math.max(S([a],b.width,b.height,{padding:24,maxScale:1.1}).scale,.7));o({scale:c,x:b.width/2-(a.x+a.width/2)*c,y:b.height/2-(a.y+a.height/2)*c})},[]),ai=(0,i.useCallback)(a=>{if(W)if("message"===a.kind){let b=W.rows.find(b=>b.ref===a.id);if(!b)return;let c=b.self?b.fromX:Math.min(b.fromX,b.toX),d=b.self?220:Math.abs(b.toX-b.fromX);ah({x:c-10,y:b.y-24,width:d+20,height:40})}else{let b=W.participants.find(b=>b.name===a.id);b&&ah({x:b.left-20,y:b.top,width:b.width+40,height:Math.min(260,W.height-b.top)})}},[W,ah]),aj=(0,i.useCallback)(a=>{if("diagram"===I.current)return ai(a);requestAnimationFrame(()=>document.getElementById(fc(a))?.scrollIntoView({block:"center",behavior:"smooth"}))},[ai]),ak=(0,i.useCallback)(a=>{s(a),a&&eB(`${a.kind}:${a.id}`)},[]);(0,i.useEffect)(()=>{if(!l||!W||U.current===g.nonce)return;U.current=g.nonce;let a=g.focus?a8(g.focus):null;if(!a)return;let b=null;if("message"===a.kind&&ay(V??l,a.name)&&(b={kind:"message",id:a.name}),"participant"===a.kind&&(V??l).participants.some(b=>b.name===a.name)&&(b={kind:"participant",id:a.name}),!b)return v(`${g.focus} is not in this sequence`,"warn");T.current=!1,s(b),aj(b)},[l,V,W,g,aj,v]),(0,i.useEffect)(()=>{if(!W||!T.current||"diagram"!==G)return;let{width:a,height:b}=ag();a&&(T.current=!1,Math.min((a-32)/W.width,(b-32)/W.height)>=.5||0===W.participants.length?q(a=>(a??0)+1):o({x:8,y:8,scale:.6}))},[W,G]);let al=(0,i.useCallback)(async a=>{let b;if(l&&j){try{b=a(l)}catch(a){return v(a instanceof Error?a.message:String(a),"warn")}m(b);try{let a=await fetch(`/api/file${(0,d4.docQuery)(j)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(b,null,2)+"\n"})});if(!a.ok)throw Error((await a.json())?.error??`HTTP ${a.status}`);R.current?.emitFull(b),v("saved")}catch(a){return v(`not saved: ${a instanceof Error?a.message:String(a)}`,"warn")}if(f?.def&&$){if("auto"===aO(f.def)){let{result:a,failed:b,conflicts:d}=await fn(f.path);if(a&&a.count>0){var c;return void(c=b.length?`auto: not written — ${b[0]}`:d.length?`auto: ${d.join(", ")} kept changing on disk; not written — save again`:be(a,"auto"),window.dispatchEvent(new CustomEvent(ey,{detail:{text:c,origin:void 0}})))}}fi()}}},[l,j,v,f,$]),am=a=>{let{width:b,height:c}=ag();o(d=>Q(d,a,{x:b/2,y:c/2}))},an=()=>{let a,b,c,d,e,f,g,h,i;l&&navigator.clipboard?.writeText((a=["sequenceDiagram"],b=new Map,(l.participants??[]).forEach((c,d)=>{let e=`p${d+1}`;b.set(c.name,e),a.push(` ${c.actor?"actor":"participant"} ${e} as ${aM(c.name)}`)}),c=a=>b.get(a)??aM(a).replace(/\W+/g,"_"),d=(a,b,d)=>{let e=a.reply?"-->>":"->>",f=[`${b} ${aM(a.label??"")}`,a.event?aM(a.event):""].filter(Boolean).join(" · "),g=`${d}${c(a.from)}${e}${c(a.to)}: ${f}`;return a.optional?[`${d}opt optional`,` ${g}`,`${d}end`]:[g]},e=l.messages??[],f=l.fragments??[],g=a=>f.filter(b=>b?.after===a),h=(b,c)=>(b.messages??[]).forEach((e,g)=>a.push(...d(e,`f${f.indexOf(b)+1}.${g+1}`,c+" "))),(i=(b,c,f)=>{for(let j=b;j<=e.length;j++){let b=j===f?[]:g(j);for(let d of b.filter(a=>"alt"!==a.kind))a.push(`${c}${d.kind} ${aM(d.label??"")}`),h(d,c),a.push(`${c}end`);let k=b.filter(a=>"alt"===a.kind);if(k.length){k.forEach((b,d)=>{a.push(`${c}${0===d?"alt":"else"} ${aM(b.label??"")}`),h(b,c)}),j<e.length&&(a.push(`${c}else as written`),i(j,c+" ",j)),a.push(`${c}end`);return}j<e.length&&a.push(...d(e[j],String(j+1),c))}})(0," ",null),a.join("\n")+"\n")).then(()=>v("mermaid copied"))},ao=a=>{let b=a?a8(a):null;if(!b||"message"!==b.kind&&"participant"!==b.kind)return;let c={kind:b.kind,id:b.name};ak(c),aj(c),L.close()},ap=V??aw("",""),ar=az(ap),as=l&&r?.kind==="message"?ay(ap,r.id):null,at=l&&r?.kind==="participant"?ap.participants.find(a=>a.name===r.id)??null:null,ax=ap.participants.map(a=>a.name),aK=j.split("/").pop()||"…",aN=Z.length+aa.filter(a=>"error"===a.severity).length,aP=aa.filter(a=>"warning"===a.severity).length,aQ=[{id:"participants",label:"Participants",icon:(0,h.jsx)(fa,{kind:"actor"})},{id:"messages",label:"Messages",icon:(0,h.jsx)(fa,{kind:"sequence"})},{id:"notes",label:"Notes",icon:"✎"},{id:"issues",label:"Issues",icon:(0,h.jsx)(et,{}),badge:aN+aP||void 0}],aR=a=>[{name:"from",label:"from",options:ax,initial:a?.from??ax[0]??""},{name:"to",label:"to",options:ax,initial:a?.to??ax[1]??ax[0]??""},{name:"label",label:"label",placeholder:"what is said or done",initial:a?.label??"",wide:!0},{name:"event",label:"event it fires",suggest:ac.events,initial:a?.event??""},{name:"state",label:"state after",suggest:ac.states,initial:a?.state??""},{name:"carries",label:"entity it carries",suggest:ac.entities,initial:a?.carries??""},{name:"machine",label:"machine",suggest:ac.machines,initial:a?.machine??""},{name:"optional",label:"optional",checkbox:!0,initial:!!a?.optional},{name:"reply",label:"reply (dashed)",checkbox:!0,initial:!!a?.reply}],aS=a=>a.actor?"actor":a.object?"object":a.service?"service":"",aT=["main: at the end",...as&&null===as.fragment?[`main: after ${as.index+1}`]:[],...(l?.fragments??[]).map((a,b)=>`fragment ${b+1}: ${a.kind} \xb7 ${a.label}`)];return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&D(!1),children:[(0,h.jsxs)("header",{className:"relative z-40 flex items-center gap-2 border-b border-gray-800 bg-gray-900 px-2 py-1.5 text-xs md:px-3 md:py-2",children:[(0,h.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,h.jsx)(fa,{kind:"sequence",size:14}),"SEQ"]}),(0,h.jsx)(d5,{}),(0,h.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:j,children:[l?.settings.name??aK,(0,h.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",aK]})]}),(0,h.jsx)("div",{className:"flex shrink-0 overflow-hidden rounded border border-gray-700 text-[12px] leading-none",role:"group","aria-label":"View",children:[["list","List","Read the messages in order, one under the other"],["diagram","Diagram","The lifelines and arrows"]].map(([a,b,c])=>(0,h.jsx)("button",{title:c,"aria-pressed":G===a,onClick:()=>{G!==a&&(r&&(T.current=!1),J(a),r&&requestAnimationFrame(()=>aj(r)))},className:`px-2.5 py-1.5 ${G===a?"bg-gray-700 text-gray-100":"bg-gray-800 text-gray-400 hover:text-gray-200"}`,children:b},a))}),(0,h.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,h.jsx)("button",{className:e7,onClick:an,children:"Copy mermaid"}),(0,h.jsx)("button",{className:e7,onClick:()=>F(a=>!a),"aria-pressed":!E,title:E?"Show the panel":"Hide the panel — the board takes the full width",children:E?"⟨ Panel":"Panel ⟩"})]}),(0,h.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,h.jsx)("button",{className:"rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-sm leading-none text-gray-200","aria-label":"More actions","aria-expanded":C,onClick:a=>{a.stopPropagation(),D(a=>!a)},children:"⋯"}),C&&(0,h.jsx)("div",{className:"absolute right-0 top-full z-50 mt-1 w-56 overflow-hidden rounded-lg border border-gray-700 bg-gray-900 py-1 shadow-xl",children:(0,h.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{D(!1),an()},children:"Copy as mermaid"})})]})]}),(0,h.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,h.jsxs)("div",{ref:K,className:"relative min-w-0 flex-1 overflow-hidden",children:[l&&W&&"list"===G&&V&&(0,h.jsx)(es,{what:"sequence",resetKey:l,children:(0,h.jsx)(fd,{definition:V,selection:r,issues:af,onSelect:a=>ak(a),onShowInDiagram:a=>{T.current=!1,J("diagram"),requestAnimationFrame(()=>ai(a))}})}),l&&W&&"diagram"===G&&(0,h.jsx)(es,{what:"sequence",resetKey:l,children:(0,h.jsx)(bS,{definition:V,layout:W,viewport:n,onViewportChange:o,selection:r,errorElements:ad,warningElements:ae,fitKey:p,onSelect:(a,b)=>ak({kind:a,id:b}),onClearSelection:()=>s(null),emptyHint:"No participants yet — add them in the panel, or let an agent write the scenario."})}),l&&W&&"diagram"===G&&(0,h.jsx)(eU,{docPath:j||null,kind:"sequence",viewport:n,setViewport:o,boxes:X,boardRef:K,focus:Y}),l&&W&&"list"===G&&(0,h.jsx)(eV,{docPath:j,onReveal:()=>J("diagram")}),(0,h.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 max-w-[75%] items-center gap-1.5 rounded bg-gray-950/70 px-1.5 py-0.5 text-[11px] ${"warn"===t.tone?"text-amber-300":"text-gray-500"} ${"list"===G&&w&&"ok"===t.tone?"hidden":"flex"}`,role:"status",children:[(0,h.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===t.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,h.jsxs)("span",{className:`truncate transition-opacity duration-500 ${w&&"ok"===t.tone?"opacity-0":"opacity-100"}`,children:[t.text,O>1?` \xb7 ${O} in the room`:""]})]}),(0,h.jsx)("div",{className:`absolute bottom-3 right-3 flex-col overflow-hidden rounded-lg border border-gray-700 bg-gray-900/90 shadow-lg backdrop-blur ${"diagram"===G?"flex":"hidden"}`,children:[["+","Zoom in",()=>am(1.25)],["−","Zoom out",()=>am(.8)],["⛶","Fit the whole diagram",()=>q(a=>(a??0)+1)]].map(([a,b,c])=>(0,h.jsx)("button",{title:b,"aria-label":b,onClick:c,className:"h-10 w-10 border-b border-gray-800 text-base leading-none text-gray-200 last:border-b-0 hover:bg-gray-800 md:h-8 md:w-8 md:text-sm",children:a},b))}),r&&!A&&(0,h.jsxs)("button",{className:"absolute bottom-3 left-1/2 max-w-[60%] -translate-x-1/2 truncate rounded-full border border-blue-500/60 bg-gray-900/95 px-4 py-2 text-sm text-blue-200 shadow-lg md:hidden",onClick:()=>{z("message"===r.kind?"messages":"participants"),B(!0)},children:["Edit ","message"===r.kind?`${r.id}. ${as?.message.label??""}`:r.id]})]}),A&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:L.close,"aria-hidden":"true"}),l&&(0,h.jsxs)("aside",{style:L.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 flex h-[var(--sheet-h)] flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${A?"translate-y-0":"pointer-events-none translate-y-full"} md:pointer-events-auto md:static md:z-auto md:h-auto md:w-80 md:translate-y-0 md:rounded-none md:border-l md:border-t-0 md:shadow-none md:transition-none ${E?"md:hidden":""}`,children:[(0,h.jsxs)("div",{className:"md:hidden",...L.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:aQ.find(a=>a.id===y)?.label}),(0,h.jsx)("button",{onClick:L.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:aQ.map(a=>(0,h.jsxs)("button",{onClick:()=>z(a.id),className:`relative flex-1 px-1 py-2 text-center text-xs transition-colors ${y===a.id?"border-b-2 border-blue-400 bg-gray-800/50 text-blue-400":"text-gray-500 hover:text-gray-300"}`,children:[a.label,void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1 top-1 min-w-[14px] rounded-full bg-red-900 px-1 text-[9px] text-red-100",children:a.badge})]},a.id))}),(0,h.jsx)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:(0,h.jsxs)(es,{what:"panel",resetKey:l,children:[(0,h.jsxs)("section",{className:"participants"===y?"":"hidden",children:[(0,h.jsx)("div",{className:e8,style:{marginTop:0},children:"Participants"}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:ap.participants.map(a=>(0,h.jsxs)("button",{className:`${e7} ${r?.kind==="participant"&&r.id===a.name?"border-blue-500 text-blue-300":""}`,onClick:()=>{ak({kind:"participant",id:a.name}),aj({kind:"participant",id:a.name})},title:aS(a)||"participant",children:[a.name,aS(a)&&(0,h.jsxs)("span",{className:"text-gray-500",children:[" · ",aS(a)]})]},a.name))}),(0,h.jsx)(e9,{id:"add-participant",reset:!0,required:["name"],fields:[{name:"name",placeholder:"new participant"},{name:"kind",options:fp,label:"kind"},{name:"value",placeholder:"actor / service / object",suggest:[...ac.actors,...ac.objects]},{name:"holds",placeholder:"holds: Entity, Entity",suggest:ac.entities}],submit:"+ Participant",onSubmit:a=>{let b=fq(a.name),c=fq(a.kind);al(d=>(function(a,b,c){if(!b.name?.trim())throw Error("A participant needs a name.");let d=aB(a);if(d.participants.some(a=>a.name===b.name))throw Error(`Participant '${b.name}' already exists.`);let e=d.participants.length;return d.participants.splice(e,0,aC({...b})),d})(d,{name:b,...c?{[c]:fq(a.value)||b}:{},holds:fr(a.holds)})),ak({kind:"participant",id:b})}}),at&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:`${e8} flex items-center justify-between gap-2`,children:[(0,h.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:at.name}),(0,h.jsx)("button",{className:`${e7} normal-case tracking-normal`,onClick:()=>aj({kind:"participant",id:at.name}),children:"◎ Show on board"})]}),(a=ap.participants.findIndex(a=>a.name===at.name),b=ap.participants.length-1,c=a=>al(b=>{var c;let d,e;return c=at.name,e=aD(d=aB(b),c),d.participants.splice(d.participants.indexOf(e),1),d.participants.splice(Math.max(0,Math.min(a,d.participants.length)),0,e),d}),(0,h.jsxs)("div",{className:"mb-1 flex items-center gap-1 text-[11px] text-gray-400",children:[(0,h.jsx)("button",{className:`${e7} disabled:opacity-40`,disabled:a<=0,onClick:()=>c(a-1),"aria-label":"Move one column left",children:"← Left"}),(0,h.jsxs)("span",{className:"flex-1 text-center",children:["column ",a+1," of ",b+1]}),(0,h.jsx)("button",{className:`${e7} disabled:opacity-40`,disabled:a>=b,onClick:()=>c(a+1),"aria-label":"Move one column right",children:"Right →"})]})),(0,h.jsx)(e9,{id:"rename-participant",required:["to"],fields:[{name:"to",label:"new name",initial:at.name}],submit:"Rename (every message follows)",onSubmit:a=>{let b=fq(a.to);b!==at.name&&(al(a=>(function(a,b,c){if(!c?.trim())throw Error("A participant needs a name.");let d=aB(a),e=aD(d,b);if(c===b)return d;if(d.participants.some(a=>a.name===c))throw Error(`Participant '${c}' already exists.`);e.name=c;let f=a=>{a.from===b&&(a.from=c),a.to===b&&(a.to=c)};for(let a of(d.messages.forEach(f),d.fragments??[]))a.messages.forEach(f);return d})(a,at.name,b)),ak({kind:"participant",id:b}))}},`rename:${at.name}`),(0,h.jsx)(e9,{id:"edit-participant",fields:[{name:"kind",options:fp,label:"kind",initial:aS(at)},{name:"value",placeholder:"actor / service / object",suggest:[...ac.actors,...ac.objects],initial:at.actor??at.object??at.service??""},{name:"holds",placeholder:"holds: Entity, Entity",suggest:ac.entities,initial:(at.holds??[]).join(", "),wide:!0},{name:"description",placeholder:"description",initial:at.description??"",wide:!0}],submit:"Save participant",onSubmit:a=>al(b=>{let c,d;return aG(b,at.name,{...(c=fq(a.kind),d=fq(a.value)||at.name,{actor:"actor"===c?d:"",service:"service"===c?d:"",object:"object"===c?d:""}),holds:fr(a.holds),description:fq(a.description)})})},`p:${JSON.stringify(at)}`),(0,h.jsxs)("button",{className:`${e7} mt-2 text-red-300`,onClick:()=>{al(a=>{var b;let c,d;return b=at.name,aD(c=aB(a),b),c.participants=c.participants.filter(a=>a.name!==b),d=a=>a.from!==b&&a.to!==b,c.messages=c.messages.filter(d),c.fragments&&(c.fragments=c.fragments.map(b=>{let c;return{...b,after:Math.max(0,b.after-(c=b.after,a.messages.slice(0,c).filter(a=>!d(a)).length)),messages:b.messages.filter(d)}}).filter(a=>a.messages.length>0),c.fragments.length||delete c.fragments),c}),s(null),eB(null)},title:"Also removes every message it sends or receives",children:["Delete ",at.name," and its messages"]})]})]}),(0,h.jsxs)("section",{className:"messages"===y?"":"hidden",children:[(0,h.jsx)("div",{className:e8,style:{marginTop:0},children:"Messages"}),0===ar.length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),(0,h.jsx)("div",{className:"flex flex-col",children:ar.map(({ref:a,message:b,fragment:c},d)=>{let e=null!==c&&(0===d||ar[d-1].fragment!==c),f=null!==c?ap.fragments?.[c]:void 0,g=r?.kind==="message"&&r.id===a;return(0,h.jsxs)("div",{children:[e&&f&&(0,h.jsxs)("div",{className:"mt-2 border-t border-gray-800 pt-1 text-[11px] text-indigo-300",children:[(0,h.jsx)("span",{className:"font-semibold",children:f.kind})," · after ",f.after," · ",f.label]}),(0,h.jsxs)("button",{className:`block w-full truncate rounded px-1 py-0.5 text-left text-[11px] ${g?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,onClick:()=>{ak({kind:"message",id:a}),aj({kind:"message",id:a})},title:`${b.from} → ${b.to}: ${b.label}`,children:[(0,h.jsxs)("span",{className:"text-gray-500",children:[a,"."]})," ",b.from," → ",b.to,": ",b.label,b.event?(0,h.jsxs)("span",{className:"text-blue-300",children:[" [",b.event,"]"]}):null,b.state?(0,h.jsxs)("span",{className:"text-emerald-400",children:[" → ",b.state]}):null,b.optional?(0,h.jsx)("span",{className:"text-gray-500",children:" opt"}):null]})]},a)})}),as&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:`${e8} flex items-center justify-between gap-2`,children:[(0,h.jsxs)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:["Message ",r.id]}),(0,h.jsxs)("span",{className:"flex gap-1 normal-case tracking-normal",children:[null===as.fragment&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("button",{className:e7,"aria-label":"Move up",title:"Move up",disabled:0===as.index,onClick:()=>{al(a=>aJ(a,as.index,as.index-1)),ak({kind:"message",id:String(as.index)})},children:"↑"}),(0,h.jsx)("button",{className:e7,"aria-label":"Move down",title:"Move down",disabled:as.index>=ap.messages.length-1,onClick:()=>{al(a=>aJ(a,as.index,as.index+1)),ak({kind:"message",id:String(as.index+2)})},children:"↓"})]}),(0,h.jsx)("button",{className:e7,onClick:()=>aj(r),children:"◎ Show"})]})]}),(0,h.jsx)(e9,{id:"edit-message",required:["label"],fields:[...aR(as.message),{name:"description",placeholder:"description",initial:as.message.description??"",wide:!0}],submit:"Save message",onSubmit:a=>al(b=>aI(b,as.index,fs(a),as.fragment))},`m:${r.id}:${JSON.stringify(as.message)}`),(0,h.jsxs)("button",{className:`${e7} mt-2 text-red-300`,onClick:()=>{al(a=>(function(a,b,c=null){let d=aB(a);if(null!==c){let a=aF(d,c);if(!a.messages[b])throw Error(`Message ${b+1} not found in fragment ${c+1}.`);return a.messages.splice(b,1),d}if(!d.messages[b])throw Error(`Message ${b+1} not found. The sequence has ${d.messages.length}.`);if(d.messages.splice(b,1),d.fragments)for(let a of d.fragments)a.after>b&&(a.after-=1);return d})(a,as.index,as.fragment)),s(null),eB(null)},children:["Delete message ",r.id]})]}),(0,h.jsx)("div",{className:e8,children:"Add a message"}),(0,h.jsx)(e9,{id:"add-message",reset:!0,required:["label"],fields:[{name:"where",options:aT,label:"where",wide:!0},...aR()],submit:"+ Message",onSubmit:a=>{let b=fq(a.where),c=fs(a),d=/^fragment (\d+):/.exec(b),e=/^main: after (\d+)$/.exec(b);d?al(a=>{var b;let e,f,g;return b=Number(d[1])-1,f=aF(e=aB(a),b),aE(e,c),g=f.messages.length,f.messages.splice(g,0,aC({...c})),e}):e?al(a=>aH(a,c,Number(e[1]))):al(a=>aH(a,c))}},`add:${aT.join("|")}:${ax.join("|")}`),(0,h.jsx)("div",{className:e8,children:"Fragments"}),0===(ap.fragments??[]).length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None."}),(ap.fragments??[]).map((a,b)=>(0,h.jsxs)("div",{className:"mb-2 rounded border border-gray-800 p-1.5",children:[(0,h.jsxs)("div",{className:"flex items-center justify-between text-[11px] text-indigo-300",children:[(0,h.jsxs)("span",{children:[b+1,". ",(0,h.jsx)("span",{className:"font-semibold",children:a.kind})," · after ",a.after," · ",a.messages.length," message(s)"]}),(0,h.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":`Remove fragment ${b+1}`,onClick:()=>al(a=>{let c;return aF(c=aB(a),b),c.fragments.splice(b,1),c.fragments.length||delete c.fragments,c}),children:"✕"})]}),(0,h.jsx)(e9,{id:`edit-fragment-${b}`,fields:[{name:"kind",options:au,initial:a.kind},{name:"after",placeholder:"after message",initial:String(a.after)},{name:"label",placeholder:"the condition, in words",initial:a.label,wide:!0}],submit:"Save fragment",onSubmit:a=>al(c=>(function(a,b,c){let d=aB(a),e=aF(d,b);if(void 0!==c.kind&&!au.includes(c.kind))throw Error(`A fragment is one of ${au.join(", ")}; got '${c.kind}'.`);if(void 0!==c.after&&(!Number.isInteger(c.after)||c.after<0||c.after>d.messages.length))throw Error(`A fragment branches after a main message, 0 to ${d.messages.length}; got ${c.after}.`);return d.fragments[b]={...aC({...e,...c,messages:void 0}),messages:e.messages??[]},d})(c,b,{kind:fq(a.kind),after:Number(fq(a.after)),label:fq(a.label)}))})]},`${b}:${JSON.stringify({...a,messages:void 0})}`)),(0,h.jsx)(e9,{id:"add-fragment",reset:!0,required:["label"],fields:[{name:"kind",options:au},{name:"after",placeholder:"after message",initial:String(as&&null===as.fragment?as.index+1:ap.messages.length)},{name:"label",placeholder:"the condition, in words",wide:!0},{name:"from",options:ax,label:"first message from"},{name:"to",options:ax,label:"to",initial:ax[1]??ax[0]??""},{name:"first",placeholder:"first message label (optional)",wide:!0}],submit:"+ Fragment",onSubmit:a=>al(b=>(function(a,b){if(!au.includes(b.kind))throw Error(`A fragment is one of ${au.join(", ")}; got '${b.kind}'.`);if(!b.label?.trim())throw Error("A fragment needs a label: the condition in words.");let c=aB(a);if(!Number.isInteger(b.after)||b.after<0||b.after>c.messages.length)throw Error(`A fragment branches after a main message, 0 to ${c.messages.length}; got ${b.after}.`);for(let a of b.messages??[])aE(c,a);return(c.fragments??=[]).push({...aC({...b,messages:void 0}),messages:(b.messages??[]).map(a=>aC({...a}))}),c})(b,{kind:fq(a.kind),after:Number(fq(a.after)),label:fq(a.label),messages:fq(a.first)?[{from:fq(a.from),to:fq(a.to),label:fq(a.first)}]:[]}))},`add-fragment:${ap.messages.length}:${as?.index??""}`)]}),(0,h.jsxs)("section",{className:"notes"===y?"":"hidden",children:[(0,h.jsx)("div",{className:e8,style:{marginTop:0},children:"Notes"}),(0,h.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the document, for whoever opens it next — you, or an agent."}),(0,h.jsx)(e4,{label:"On this sequence",value:l.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:a=>al(b=>{var c;let d;return c={notes:a},(d=aB(b)).settings=aC({...d.settings,...c}),d})},"sequence"),at&&(0,h.jsx)(e4,{label:`On ${at.name}`,value:at.notes??"",placeholder:`A question or a decision about ${at.name}…`,onSave:a=>al(b=>aG(b,at.name,{notes:a}))},`participant:${at.name}`),as&&(0,h.jsx)(e4,{label:`On message ${r.id}`,value:as.message.notes??"",placeholder:"A question or a decision about this message…",onSave:a=>al(b=>aI(b,as.index,{notes:a},as.fragment))},`message:${r.id}`),!r&&(0,h.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Select a participant or a message to leave a note on it."}),[...ap.participants.filter(a=>a.notes?.trim()),...ar.filter(a=>a.message.notes?.trim())].length>0&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:e8,children:"With notes"}),(0,h.jsxs)("div",{className:"flex flex-wrap gap-1",children:[ap.participants.filter(a=>a.notes?.trim()).map(a=>(0,h.jsx)("button",{className:e7,onClick:()=>ao(`participant:${a.name}`),children:a.name},`p${a.name}`)),ar.filter(a=>a.message.notes?.trim()).map(a=>(0,h.jsxs)("button",{className:e7,onClick:()=>ao(`message:${a.ref}`),children:["message ",a.ref]},`m${a.ref}`))]})]})]}),(0,h.jsxs)("section",{className:"issues"===y?"":"hidden",children:[(0,h.jsx)("div",{className:e8,style:{marginTop:0},children:"Issues"}),Z.map((a,b)=>(0,h.jsxs)("button",{className:"block w-full py-0.5 text-left text-[11px] text-red-300",onClick:()=>ao(a.element),children:["[",a.ruleId,"] ",a.message]},`p${b}`)),aa.map((a,b)=>(0,h.jsxs)("button",{className:`block w-full py-0.5 text-left text-[11px] ${"error"===a.severity?"text-red-300":"text-amber-300"}`,onClick:()=>ao(a.element),children:["[",a.ruleId,"] ",a.message]},`s${b}`)),0===Z.length&&0===aa.length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-green-400",children:_?"Valid, and every name it uses resolves in the system.":"The document is valid."}),!e&&(0,h.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Open this sequence from its system to check it against the machines and the data."}),e&&!$&&f&&(0,h.jsx)("p",{className:"mt-2 text-[11px] text-amber-300",children:"This document is not a member of the open system."}),ab&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:e8,children:["Replay against ",ab.machines.join(", ")||"no machine"]}),ab.paths.map(a=>(0,h.jsxs)("div",{className:"mb-2",children:[(0,h.jsxs)("div",{className:`text-[11px] font-semibold ${a.accepted?"text-green-400":"text-amber-300"}`,children:[a.name," — ",a.accepted?"accepted":"stops"]}),a.steps.filter(a=>"data"!==a.result).map(b=>(0,h.jsxs)("button",{className:`block w-full truncate py-0.5 pl-2 text-left font-mono text-[10.5px] ${"moved"===b.result||"stayed"===b.result?"text-gray-400":"text-amber-300"}`,title:b.note??b.result,onClick:()=>ao(`message:${b.ref}`),children:[b.ref,". ",b.event??""," ",b.from.join("|")||"·"," → ",b.to.join("|")||"·"," ",b.result]},`${a.name}:${b.ref}`))]},a.name))]})]})]})})]})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:aQ.map(a=>{let b=A&&y===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(A&&y===b?L.close():B(!0),z(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1/2 top-1 min-w-[16px] translate-x-5 rounded-full border border-red-900/80 bg-red-950/80 px-1 text-[10px] leading-4 text-red-200",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})})]})}function fu(a,b){let c=a?.members.find(a=>a.path===b)?.def;return c?.settings?.name||(b.split("/").pop()??b).replace(/\.(smdf|erdf|sqdf|sysdf)\.json$|\.json$/i,"")}let fv=(a,b)=>a?.members.find(a=>a.path===b)?.kind??"machine";function fw(a){return"message"===a.kind?`message ${a.name}`:`${a.kind} ${a.name}`}function fx({systemPath:a}){let b=ez("doc"),c=ez("focus"),{system:d}=fj(a),[e,f]=(0,i.useState)(!1),[g,j]=(0,i.useState)(null),k=(0,i.useRef)(d);(0,i.useEffect)(()=>{k.current=d},[d]);let l=(0,i.useMemo)(()=>d?eW(()=>a9(d.members),[]):[],[d]),m=fk(d,b),n=!!d&&(b===d.path||b===a),o=m&&c?function(a,b,c){let d=a8(c);if(!d)return[];let e=a=>a.member===b&&a.kind===d.kind&&a.name===d.name,f=[];for(let b of a)e(b.from)?f.push({other:b.to,text:b.text,rule:b.rule}):e(b.to)&&f.push({other:b.from,text:b.back,rule:b.rule});return f}(l,m,c):[],p=function(a,b){if(!b)return[];let c=new Map;for(let d of a)for(let a of[d.from,d.to]){if(a.member!==b)continue;let d=a7(a);c.set(d,(c.get(d)??0)+1)}return[...c.entries()].sort((a,b)=>a[0].localeCompare(b[0]))}(l,m);(0,i.useEffect)(()=>{let a=a=>{let b=a.detail;b?.text&&j({...b,at:Date.now()})};return window.addEventListener(ey,a),()=>window.removeEventListener(ey,a)},[]),(0,i.useEffect)(()=>{if(!g)return;let a=setTimeout(()=>j(null),9e3);return()=>clearTimeout(a)},[g]);let q=d?.path;(0,i.useEffect)(()=>{if(!q)return;let b=!0,c=null,d=null;return(async()=>{let{bridgeUrl:e}=await ed();if(b&&e){var g;let b,h,i,l;(c=dw({url:e,role:"web",docId:q,name:"web-system-strip"})).on("view",b=>{let c=k.current;if(!c)return;let d=b.member?void 0!==c.absOf[b.member]?b.member:Object.keys(c.absOf).find(a=>c.absOf[a]===b.member):void 0;if(b.member&&!d)return void j({text:`ignored a view of ${b.member.split("/").pop()}: it is not a member of this system`,origin:b.origin,at:Date.now()});eA({doc:d?c.absOf[d]:q,system:a,focus:b.focus??null}),f(!1);let e=[d?fu(c,d):"the system map",b.focus].filter(Boolean).join(" · ");j({text:b.note?b.note:`showing ${e}`,origin:b.origin,at:Date.now()})}),c.on("full",()=>fi()),g=c,b=!1,h=!1,i=()=>{g.join().then(()=>{b=!0}).catch(()=>{})},l=g.on("status",a=>{"connected"!==a?h=b:h&&(h=!1,i())}),i(),d=()=>{l()}}})(),()=>{b=!1,d?.(),c?.disconnect()}},[q,a]);let r=b=>{f(!1),d&&eA({doc:b.member?d.absOf[b.member]??aV(d.path,b.member):d.path,system:a,focus:b.focus??null})},s=d?.def?.members?.filter(a=>a?.path).map(a=>a.path)??[],t=d?.def?.settings?.name??(a.split("/").pop()??"system").replace(/\.sysdf\.json$/i,""),u=o.length;return(0,h.jsxs)("div",{className:"system-strip relative z-50 border-b border-gray-800 bg-gray-950 text-xs text-gray-300",children:[(0,h.jsxs)("div",{className:"flex h-[var(--strip-h)] items-center gap-1 px-1.5 md:px-2",children:[(0,h.jsxs)("button",{onClick:()=>r({}),className:`flex min-w-0 max-w-[30%] shrink-0 items-center gap-1 rounded px-1.5 py-1 md:max-w-[16rem] ${n?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,title:`${a} — the system map`,children:[(0,h.jsx)(fa,{kind:"system",size:15}),(0,h.jsx)("span",{className:"truncate font-semibold",children:t})]}),(0,h.jsx)("span",{className:"h-4 w-px shrink-0 bg-gray-800"}),(0,h.jsxs)("nav",{className:"flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto [scrollbar-width:none]","aria-label":"Members",children:[s.map(a=>{let b=a===m,c=d?.members.find(b=>b.path===a)?.error;return(0,h.jsxs)("button",{onClick:()=>r({member:a}),"aria-current":b?"page":void 0,title:`${fu(d,a)} — ${a}${c?` (cannot be read: ${c})`:""}`,className:`flex shrink-0 items-center gap-1 rounded px-1.5 py-1 ${b?"bg-blue-950/60 text-blue-200":c?"text-red-400 hover:bg-gray-800":"text-gray-400 hover:bg-gray-800 hover:text-gray-200"}`,children:[(0,h.jsx)(fa,{kind:fv(d,a),size:15}),(0,h.jsx)("span",{className:`max-w-[7.5rem] truncate md:max-w-[11rem] ${b?"":"hidden md:inline"}`,children:fu(d,a)})]},a)}),!d&&(0,h.jsx)("span",{className:"px-1 text-gray-600",children:"loading…"}),d?.error&&(0,h.jsx)("span",{className:"truncate px-1 text-amber-300",children:d.error})]}),(0,h.jsxs)("button",{onClick:()=>f(a=>!a),disabled:!m,"aria-expanded":e,title:m?c?`What ${c} links to in the other drawings`:"Elements of this drawing that link to the others":"Open a member to follow its links",className:`flex shrink-0 items-center gap-1 rounded px-1.5 py-1 disabled:opacity-40 ${e?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,children:[(0,h.jsx)(fa,{kind:"link",size:15}),(0,h.jsx)("span",{className:"hidden sm:inline",children:"Links"}),u>0&&(0,h.jsx)("span",{className:"rounded-full border border-gray-700 px-1 text-[10px] leading-4 text-gray-300",children:u})]})]}),g&&!e&&(0,h.jsx)("div",{className:"pointer-events-none absolute inset-x-0 top-full flex justify-center px-2 pt-1",role:"status",children:(0,h.jsxs)("span",{className:"max-w-full truncate rounded border border-gray-700 bg-gray-900/95 px-2 py-0.5 text-[11px] text-gray-300 shadow",children:[g.origin?(0,h.jsxs)("span",{className:"text-blue-300",children:[g.origin,": "]}):null,g.text]})}),e&&m&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:"fixed inset-0 z-40",onClick:()=>f(!1),"aria-hidden":"true"}),(0,h.jsxs)("div",{className:"absolute right-1 top-full z-50 mt-1 max-h-[60vh] w-[min(24rem,calc(100vw-0.5rem))] overflow-y-auto rounded-lg border border-gray-700 bg-gray-900 p-2 shadow-xl",children:[c&&a8(c)?(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:"mb-1 flex items-center justify-between gap-2 text-[11px] text-gray-500",children:[(0,h.jsxs)("span",{className:"truncate",children:[(0,h.jsx)("span",{className:"text-gray-200",children:fw(a8(c))})," in ",fu(d,m)]}),(0,h.jsx)("button",{className:"shrink-0 text-gray-500 hover:text-gray-200",onClick:()=>eA({doc:b,focus:null}),children:"clear"})]}),0===o.length&&(0,h.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"Nothing in the other drawings names it."}),o.map((a,b)=>(0,h.jsxs)("button",{onClick:()=>r({member:a.other.member,focus:a7(a.other)}),className:"flex w-full items-start gap-2 rounded px-1.5 py-1.5 text-left hover:bg-gray-800",children:[(0,h.jsx)("span",{className:"mt-0.5 text-gray-400",children:(0,h.jsx)(fa,{kind:fv(d,a.other.member),size:14})}),(0,h.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,h.jsx)("span",{className:"block text-[12px] text-gray-200",children:a.text}),(0,h.jsxs)("span",{className:"block truncate text-[10.5px] text-gray-500",children:[fw(a.other)," · ",fu(d,a.other.member)," · ",a.rule]})]})]},b))]}):null,(!c||!a8(c))&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["Elements of ",fu(d,m)," that the other drawings name — pick one to follow it."]}),0===p.length&&(0,h.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"None."}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:p.map(([a,c])=>(0,h.jsxs)("button",{onClick:()=>{f(!0),eA({doc:b,focus:a})},className:"rounded border border-gray-700 bg-gray-800 px-1.5 py-0.5 text-[11px] text-gray-200 hover:bg-gray-700",children:[a," ",(0,h.jsx)("span",{className:"text-gray-500",children:c})]},a))})]})]})]})]})}let fy={erd:"ERD",machine:"STATE MACHINE",sequence:"SEQUENCE",system:"SYSTEM"};function fz(a,b,c=!1){if(!b)return"";if("erd"===a)return`${b.entities?.length??0} entities \xb7 ${b.relationships?.length??0} relationships`;if("sequence"===a){let a=b.fragments?.length??0;return`${b.participants?.length??0} participants \xb7 ${b.messages?.length??0} messages${a&&!c?` \xb7 ${a} fragment${a>1?"s":""}`:""}`}let d=0,e=a=>{a&&(d+=1,(a.states??[]).forEach(e),(a.parallel?.states??[]).forEach(e))};(b.state?.states??[]).forEach(e),(b.state?.parallel?.states??[]).forEach(e);let f=(b.events??[]).reduce((a,b)=>a+(b?.events?.length??0)+(b?.timers?.length??0),0);return`${d} states \xb7 ${f} events`}let fA=(a,b)=>a<b?`${a}\u0000${b}`:`${b}\u0000${a}`;function fB(a){let b="message"===a.from.kind?`message ${a.from.name}`:`${a.from.kind} ${a.from.name}`;return`${b} ${a.text}`}function fC(){let a=(0,d4.useRequestedDoc)(),[b,c]=(0,i.useState)(a);(0,i.useEffect)(()=>{let b=!0;if(a)c(a);else fe(null).then(a=>b&&c(a.path||null));return()=>{b=!1}},[a]);let{system:d,reload:e}=fj(b),[f,g]=(0,i.useState)("members"),[j,k]=(0,i.useState)(!1),[l,m]=(0,i.useState)(!1),[n,o]=(0,i.useState)(!1),[p,q]=(0,i.useState)(null),[r,s]=(0,i.useState)({text:"loading…",tone:"ok"}),t=(0,i.useCallback)((a,b="ok")=>s({text:a,tone:b}),[]),[u,v]=(0,i.useState)(!1),w=ev({onClose:()=>k(!1),restVh:62,tallVh:92}),x=(0,i.useRef)(null),[y,z]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=x.current;if(!a)return;let b=()=>{let b=a.getBoundingClientRect();b.width&&z(b.height>1.1*b.width)};b();let c=new ResizeObserver(b);return c.observe(a),()=>c.disconnect()},[]);let A=(0,i.useRef)(!1);(0,i.useEffect)(()=>{d&&(d.error?t(d.error,"warn"):A.current||t(`${d.members.length} member${1===d.members.length?"":"s"} loaded`),A.current=!0)},[d,t]);let[B,C]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=setTimeout(()=>C(!0),4e3);return()=>{clearTimeout(a),C(!1)}},[r]);let D=(0,i.useMemo)(()=>d?.def?eW(()=>a6(d.def,d.members),null):null,[d]),E=(0,i.useMemo)(()=>d?eW(()=>a9(d.members),[]):[],[d]),F=(0,i.useMemo)(()=>d?.def?eW(()=>bd(d.def,d.members),null):null,[d]),G=aO(d?.def),H=(0,i.useMemo)(()=>{let a=new Map;for(let b of E){if(b.from.member===b.to.member)continue;let c=fA(b.from.member,b.to.member),d=a.get(c)??{a:c.split("\0")[0],b:c.split("\0")[1],links:[]};d.links.push(b),a.set(c,d)}return a},[E]),I=(D?.issues??[]).filter(a=>"error"===a.severity),J=(D?.issues??[]).filter(a=>"warning"===a.severity),K=(b,c)=>{d&&eA({doc:d.absOf[b]??b,system:a??d.path,focus:c??null})},L=async(a,b)=>{if(d)try{await fg(d.path,a,d.mtimes[d.path]),t(b),fi()}catch(a){a instanceof ff?(t("the system changed on disk — reloaded; make the change again","warn"),fi()):t(`not saved: ${a instanceof Error?a.message:String(a)}`,"warn")}},M=async()=>{if(!d||!F||!F.count)return;v(!0);let{result:a,written:b,failed:c,conflicts:e}=await fn(d.path);v(!1),c.length?t(`not all written: ${c.join("; ")}`,"warn"):e.length?t(`${e.join(", ")} kept changing on disk — not written; apply again`,"warn"):a?.count?t(`${be(a,"propose").replace(/ proposed/," applied")} — ${b.length} file(s) written`):t("nothing to apply: the drawings on disk already agree")},N=y?420:760,O=y?640:520,P=d?.def?.members?.filter(a=>a?.path).map(a=>a.path)??[],Q=d?.def?.actors??[],R=64*!!Q.length,S=(0,i.useMemo)(()=>{let a=P.length,b=N/2,c=(O-R)/2+6,d=Math.max(0,N/2-98-16),e=Math.max(0,(O-R)/2-46-18),f=new Map;return P.forEach((g,h)=>{if(1===a)return f.set(g,{x:b,y:c});if(y){let b=O-R-46-16;return f.set(g,{x:h%2?.67*N:.33*N,y:62+(b-62)*h/(a-1)})}if(2===a)return f.set(g,y?{x:b,y:h?c+e:c-e}:{x:h?b+d:b-d,y:c});let i=-Math.PI/2+2*h*Math.PI/a;f.set(g,{x:b+d*Math.cos(i),y:c+e*Math.sin(i)})}),f},[P.join("|"),N,O,196,R,y]),T=(0,i.useMemo)(()=>{let a=new Map;for(let{member:b,def:c}of a5(d?.members??[]).sequences)for(let d of c.participants??[]){if(!d?.actor)continue;let c=a.get(d.actor)??[];c.includes(b)||c.push(b),a.set(d.actor,c)}return a},[d]),U=d?.def,V=(d?.path??b??"").split("/").pop()||"…",W=[{id:"members",label:"Members",icon:(0,h.jsx)(fa,{kind:"system"})},{id:"checks",label:"Checks",icon:(0,h.jsx)(et,{}),badge:I.length+J.length||void 0},{id:"notes",label:"Notes",icon:"✎"}],X=p?H.get(p):void 0,Y=(0,i.useMemo)(()=>{let a=[];for(let b of["error","warning"]){let c=new Map;for(let a of D?.issues??[])a.severity===b&&c.set(a.ruleId,[...c.get(a.ruleId)??[],a]);for(let[d,e]of[...c.entries()].sort((a,b)=>a[0].localeCompare(b[0])))a.push({key:`${b}:${d}`,ruleId:d,severity:b,issues:e})}return a},[D]);return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>l&&m(!1),children:[(0,h.jsxs)("header",{className:"relative z-40 flex items-center gap-2 border-b border-gray-800 bg-gray-900 px-2 py-1.5 text-xs md:px-3 md:py-2",children:[(0,h.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,h.jsx)(fa,{kind:"system",size:14}),"SYS"]}),(0,h.jsx)(d5,{}),(0,h.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:d?.path,children:[U?.settings?.name??V,(0,h.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",V]})]}),(0,h.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,h.jsx)("button",{className:e7,onClick:e,title:"Read the system and every member again",children:"Re-check"}),(0,h.jsx)("button",{className:e7,onClick:()=>o(a=>!a),"aria-pressed":!n,children:n?"⟨ Panel":"Panel ⟩"})]}),(0,h.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,h.jsx)("button",{className:"rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-sm leading-none text-gray-200","aria-label":"More actions","aria-expanded":l,onClick:a=>{a.stopPropagation(),m(a=>!a)},children:"⋯"}),l&&(0,h.jsx)("div",{className:"absolute right-0 top-full z-50 mt-1 w-56 overflow-hidden rounded-lg border border-gray-700 bg-gray-900 py-1 shadow-xl",children:(0,h.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{m(!1),e()},children:"Re-check the system"})})]})]}),(0,h.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,h.jsxs)("div",{ref:x,className:"relative min-w-0 flex-1 overflow-hidden bg-[#030712]",children:[d&&U&&(0,h.jsx)(es,{what:"system map",resetKey:d,children:(0,h.jsxs)("svg",{className:"h-full w-full",viewBox:`0 0 ${N} ${O}`,preserveAspectRatio:"xMidYMid meet",role:"img","aria-label":`System map of ${U.settings?.name}`,children:[[...H.entries()].map(([a,b])=>{let c=S.get(b.a),d=S.get(b.b);if(!c||!d)return null;let e=(c.x+d.x)/2,f=(c.y+d.y)/2,i=`${b.links.length} link${1===b.links.length?"":"s"}`,j=6.4*i.length+16,l=p===a;return(0,h.jsxs)("g",{className:"cursor-pointer",onClick:()=>{q(l?null:a),g("members"),k(!0)},children:[(0,h.jsx)("line",{x1:c.x,y1:c.y,x2:d.x,y2:d.y,stroke:"transparent",strokeWidth:18}),(0,h.jsx)("line",{x1:c.x,y1:c.y,x2:d.x,y2:d.y,stroke:l?"#3b82f6":"#475569",strokeWidth:l?2.5:1.6}),(0,h.jsx)("rect",{x:e-j/2,y:f-11,width:j,height:22,rx:11,fill:"#0f172a",stroke:l?"#3b82f6":"#334155"}),(0,h.jsx)("text",{x:e,y:f+4,textAnchor:"middle",fontSize:11.5,fill:l?"#93c5fd":"#cbd5e1",children:i})]},a)}),Q.map((a,b)=>{let c=(b+1)*N/(Q.length+1),d=O-30;return(0,h.jsxs)("g",{children:[(T.get(a.name)??[]).map(a=>{let b=S.get(a);return b?(0,h.jsx)("line",{x1:c,y1:d-14,x2:b.x,y2:b.y+46,stroke:"#334155",strokeDasharray:"3 4"},a):null}),(0,h.jsx)("title",{children:[`${a.kind}`,a.description??"",a.wheelNode??""].filter(Boolean).join(" — ")}),(0,h.jsx)("rect",{x:c-62,y:d-14,width:124,height:28,rx:14,fill:"#0c1020",stroke:"#6366f1"}),(0,h.jsx)("g",{transform:`translate(${c-54} ${d-8})`,color:"#a5b4fc",children:(0,h.jsx)(fa,{kind:"actor",size:16})}),(0,h.jsx)("text",{x:c-34,y:d-1,fontSize:11.5,fontWeight:600,fill:"#e2e8f0",children:a.name.length>12?`${a.name.slice(0,11)}…`:a.name}),(0,h.jsx)("text",{x:c-34,y:d+9,fontSize:8.5,fill:"#94a3b8",children:a.kind})]},a.name)}),P.map(a=>{let b=S.get(a),c=d.members.find(b=>b.path===a);if(!b||!c)return null;let e=c.kind,f=(D?.issues??[]).filter(b=>b.member===a),g=f.filter(a=>"error"===a.severity).length,i=f.filter(a=>"warning"===a.severity).length,j=b.x-98,k=b.y-46,l=fu(d,a),m=X&&(X.a===a||X.b===a);return(0,h.jsxs)("g",{className:"cursor-pointer",onClick:()=>K(a),children:[(0,h.jsx)("title",{children:`${a}${c.error?` — cannot be read: ${c.error}`:""}
|
|
15
|
+
Tap to open it inside the system.`}),(0,h.jsx)("rect",{x:j,y:k,width:196,height:92,rx:10,fill:"#0f172a",stroke:c.error?"#ef4444":m?"#3b82f6":g?"#b91c1c":"#475569",strokeWidth:m?2.2:1.5,strokeDasharray:c.error?"5 4":void 0}),(0,h.jsx)("g",{transform:`translate(${j+10} ${k+9})`,color:"#93c5fd",children:(0,h.jsx)(fa,{kind:e,size:16})}),(0,h.jsx)("text",{x:j+32,y:k+21,fontSize:9,fontWeight:700,letterSpacing:"0.06em",fill:"#64748b",children:fy[e]}),(0,h.jsx)("text",{x:j+10,y:k+43,fontSize:14,fontWeight:600,fill:"#e2e8f0",children:l.length>22?`${l.slice(0,21)}…`:l}),(0,h.jsx)("text",{x:j+10,y:k+60,fontSize:10.5,fill:"#94a3b8",children:c.error?"cannot be read":fz(e,c.def,!0)}),(0,h.jsx)("text",{x:j+10,y:k+79,fontSize:10.5,fill:g?"#fca5a5":i?"#fcd34d":"#4ade80",children:c.error?c.error.length>30?`${c.error.slice(0,29)}…`:c.error:g||i?[g?`${g} error${g>1?"s":""}`:"",i?`${i} warning${i>1?"s":""}`:""].filter(Boolean).join(" · "):"checks pass"}),(0,h.jsx)("text",{x:j+196-10,y:k+79,fontSize:10.5,textAnchor:"end",fill:"#64748b",children:"open ›"})]},a)})]})}),d&&!U&&(0,h.jsx)("div",{className:"absolute inset-0 flex items-center justify-center p-6 text-center text-sm text-amber-300",children:d.error}),(0,h.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 flex max-w-[75%] items-center gap-1.5 rounded bg-gray-950/70 px-1.5 py-0.5 text-[11px] ${"warn"===r.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,h.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===r.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,h.jsx)("span",{className:`truncate transition-opacity duration-500 ${B&&"ok"===r.tone?"opacity-0":"opacity-100"}`,children:r.text})]})]}),j&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:w.close,"aria-hidden":"true"}),d&&U&&(0,h.jsxs)("aside",{style:w.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 flex h-[var(--sheet-h)] flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${j?"translate-y-0":"pointer-events-none translate-y-full"} md:pointer-events-auto md:static md:z-auto md:h-auto md:w-96 md:translate-y-0 md:rounded-none md:border-l md:border-t-0 md:shadow-none md:transition-none ${n?"md:hidden":""}`,children:[(0,h.jsxs)("div",{className:"md:hidden",...w.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:W.find(a=>a.id===f)?.label}),(0,h.jsx)("button",{onClick:w.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:W.map(a=>(0,h.jsxs)("button",{onClick:()=>g(a.id),className:`relative flex-1 px-1 py-2 text-center text-xs transition-colors ${f===a.id?"border-b-2 border-blue-400 bg-gray-800/50 text-blue-400":"text-gray-500 hover:text-gray-300"}`,children:[a.label,void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1 top-1 min-w-[14px] rounded-full bg-red-900 px-1 text-[9px] text-red-100",children:a.badge})]},a.id))}),(0,h.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,h.jsxs)("section",{className:"members"===f?"":"hidden",children:[(0,h.jsx)("div",{className:e8,style:{marginTop:0},children:"Members"}),P.map(a=>{let b=d.members.find(b=>b.path===a),c=U.members.find(b=>b.path===a)?.notes;return(0,h.jsxs)("div",{className:"mb-1 rounded border border-gray-800",children:[(0,h.jsxs)("button",{onClick:()=>K(a),className:"flex w-full items-start gap-2 p-2 text-left hover:bg-gray-800",children:[(0,h.jsx)("span",{className:"mt-0.5 text-blue-300",children:(0,h.jsx)(fa,{kind:b?.kind??"machine"})}),(0,h.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,h.jsx)("span",{className:"block truncate text-[12px] font-semibold text-gray-200",children:fu(d,a)}),(0,h.jsx)("span",{className:"block truncate text-[10.5px] text-gray-500",children:a}),(0,h.jsx)("span",{className:`block text-[11px] ${b?.error?"text-red-300":"text-gray-400"}`,children:b?.error?`cannot be read: ${b.error}`:fz(b?.kind??"machine",b?.def)})]}),(0,h.jsx)("span",{className:"shrink-0 text-[11px] text-gray-500",children:"open ›"})]}),(0,h.jsx)("div",{className:"px-2 pb-2 [&_label]:mt-0",children:(0,h.jsx)(e4,{label:"Note on this member, in the system",value:c??"",placeholder:`Why ${fu(d,a)} is part of this system, what is open…`,onSave:b=>void L(function(a,b,c){let d=aX(a),e=d.members.findIndex(a=>a.path===b);if(e<0)throw Error(`'${b}' is not a member. Members: ${a.members.map(a=>a.path).join(", ")||"none"}.`);return d.members[e]=aY({...d.members[e],...c}),d}(U,a,{notes:b}),"saved")},`member:${a}`)})]},a)}),(0,h.jsx)("div",{className:e8,children:"Links between members"}),0===H.size&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"No name crosses between the members yet."}),[...H.entries()].map(([a,b])=>(0,h.jsxs)("div",{className:"mb-1",children:[(0,h.jsxs)("button",{className:`flex w-full items-center justify-between rounded px-1.5 py-1 text-left text-[11px] ${p===a?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,onClick:()=>q(p===a?null:a),children:[(0,h.jsxs)("span",{className:"truncate",children:[fu(d,b.a)," ↔ ",fu(d,b.b)]}),(0,h.jsx)("span",{className:"shrink-0 text-gray-500",children:b.links.length})]}),p===a&&(0,h.jsx)("div",{className:"ml-2 border-l border-gray-800 pl-2",children:b.links.map((a,b)=>(0,h.jsxs)("button",{className:"block w-full truncate py-0.5 text-left text-[11px] text-gray-400 hover:text-gray-200",title:`${fB(a)} — ${a.rule}`,onClick:()=>{let b;return K((b=a.from).member,a7(b))},children:[(0,h.jsx)("span",{className:"text-gray-600",children:a.rule})," ",fB(a)]},b))})]},a)),Q.length>0&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:e8,children:"Actors"}),Q.map(a=>(0,h.jsxs)("div",{className:"py-0.5 text-[11px] text-gray-300",children:[a.name," ",(0,h.jsxs)("span",{className:"text-gray-500",children:["· ",a.kind]}),a.description?(0,h.jsxs)("span",{className:"text-gray-500",children:[" — ",a.description]}):null]},a.name))]})]}),(0,h.jsxs)("section",{className:"checks"===f?"":"hidden",children:[(0,h.jsx)("div",{className:e8,style:{marginTop:0},children:"Checks"}),(0,h.jsxs)("div",{className:`text-[11px] ${I.length?"text-red-300":J.length?"text-amber-300":"text-green-400"}`,children:[I.length," error",1===I.length?"":"s"," · ",J.length," warning",1===J.length?"":"s"]}),Y.map(a=>(0,h.jsxs)("div",{className:"mt-2",children:[(0,h.jsxs)("div",{className:`text-[11px] font-semibold ${"error"===a.severity?"text-red-300":"text-amber-300"}`,children:[a.ruleId," · ",a.issues.length," ",a.severity,1===a.issues.length?"":"s"]}),a.issues.map((a,b)=>(0,h.jsxs)("button",{className:"block w-full py-0.5 pl-2 text-left text-[11px] text-gray-300 hover:text-white",onClick:()=>{a.member&&K(a.member,a.element&&/^[a-z]+:/.test(a.element)?a.element:null)},title:a.member?`Open ${a.member}${a.element?` at ${a.element}`:""}`:void 0,children:[a.message,a.member&&(0,h.jsxs)("span",{className:"text-gray-500",children:[" — ",fu(d,a.member)]})]},b))]},a.key)),(0,h.jsx)("div",{className:e8,children:"Reconcile"}),(0,h.jsxs)("p",{className:"mb-1 text-[11px] text-gray-500",children:["What the scenarios imply for the machines and the data. ",(0,h.jsx)("b",{className:"text-gray-400",children:"propose"})," lists it here to apply by hand; ",(0,h.jsx)("b",{className:"text-gray-400",children:"auto"})," writes it each time a scenario is saved."]}),(0,h.jsx)("span",{className:"inline-flex overflow-hidden rounded border border-gray-700",role:"group","aria-label":"Reconcile mode",children:aN.map(a=>(0,h.jsx)("button",{"aria-pressed":G===a,onClick:()=>{d?.def&&a!==G&&L(function(a,b){if(!aN.includes(b))throw Error(`The reconcile mode is ${aN.join(" or ")}; got '${b}'.`);return aZ(a,{reconcile:b})}(d.def,a),`reconcile mode: ${a}`)},className:`px-3 py-1 text-xs ${G===a?"bg-blue-900/60 text-blue-200":"bg-gray-800 text-gray-400 hover:bg-gray-700"}`,children:a},a))}),(0,h.jsx)("div",{className:"mt-2 text-[11px] font-semibold text-gray-400",children:"Scenario changes"}),F&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:"text-[11px] text-gray-500",children:be(F,"propose")}),F.machines.map(a=>(0,h.jsxs)("div",{className:"mt-1",children:[(0,h.jsxs)("div",{className:"text-[11px] text-gray-300",children:[a.machine," ",(0,h.jsxs)("span",{className:"text-gray-500",children:["· ",a.member]})]}),a.reasons.map((a,b)=>(0,h.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",a]},b))]},a.member)),F.erds.map(a=>(0,h.jsxs)("div",{className:"mt-1",children:[(0,h.jsxs)("div",{className:"text-[11px] text-gray-300",children:[a.def.settings?.name??a.member," ",(0,h.jsxs)("span",{className:"text-gray-500",children:["· ",a.member]})]}),a.reasons.map((a,b)=>(0,h.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",a]},b))]},a.member)),F.system&&(0,h.jsxs)("div",{className:"mt-1",children:[(0,h.jsx)("div",{className:"text-[11px] text-gray-300",children:"the system"}),F.system.reasons.map((a,b)=>(0,h.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",a]},b))]}),F.unresolved.map((a,b)=>(0,h.jsxs)("div",{className:"mt-1 text-[11px] text-amber-300",children:["left open: ",a]},b)),(0,h.jsx)("button",{className:`${e7} mt-2 disabled:opacity-40`,disabled:!F.count||u,onClick:M,children:u?"Applying…":`Apply${F.count?` ${F.count} change${1===F.count?"":"s"}`:""}`})]}),(D?.replays??[]).map(({member:a,report:b})=>(0,h.jsxs)("div",{children:[(0,h.jsxs)("div",{className:e8,children:["Replay · ",fu(d,a)]}),(0,h.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["against ",b.machines.join(", ")||"no machine"]}),b.paths.map(b=>(0,h.jsxs)("div",{className:"mb-2",children:[(0,h.jsxs)("div",{className:`text-[11px] font-semibold ${b.accepted?"text-green-400":"text-amber-300"}`,children:[b.name," — ",b.accepted?"accepted":"stops"]}),b.steps.filter(a=>"data"!==a.result).map(c=>(0,h.jsxs)("button",{className:`block w-full truncate py-0.5 pl-2 text-left font-mono text-[10.5px] ${"moved"===c.result||"stayed"===c.result?"text-gray-400":"text-amber-300"}`,title:c.note??c.result,onClick:()=>K(a,`message:${c.ref}`),children:[c.ref,". ",c.event??""," ",c.from.join("|")||"·"," → ",c.to.join("|")||"·"," ",c.result]},`${b.name}:${c.ref}`))]},b.name))]},a))]}),(0,h.jsxs)("section",{className:"notes"===f?"":"hidden",children:[(0,h.jsx)("div",{className:e8,style:{marginTop:0},children:"Notes"}),(0,h.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the system file, for whoever opens it next."}),(0,h.jsx)(e4,{label:"On this system",value:U.settings?.notes??"",placeholder:"What the system is for, what is still open…",onSave:a=>void L(aZ(U,{notes:a}),"saved")},"system"),U.settings?.description&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:e8,children:"Description"}),(0,h.jsx)("p",{className:"text-[11px] text-gray-400",children:U.settings.description})]})]})]})]})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:W.map(a=>{let b=j&&f===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(j&&f===b?w.close():k(!0),g(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1/2 top-1 min-w-[16px] translate-x-5 rounded-full border border-red-900/80 bg-red-950/80 px-1 text-[10px] leading-4 text-red-200",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})})]})}function fD(){let a=dM(a=>a.definition),b=dM(a=>a.layout.positions),c=dM(a=>a.navigationPath),d=dM(a=>a.viewport),e=dM(a=>a.setViewport),f=dM(a=>a.docPath),g=ez("focus"),j=(0,i.useMemo)(()=>({get current(){return document.getElementById("machine-board")}}),[]),k=c.slice(1),l=(0,i.useMemo)(()=>a?.state?function(a,b){let c=[];for(let d of a){let a=d?.name?b[d.name]:void 0;a&&c.push({focus:`state:${d.name}`,box:a})}for(let d of a){let e=d?.name?b[d.name]:void 0;if(e)for(let f of d.transitions??[]){if(!f?.event)continue;let d=f.nextState?b[f.nextState]:void 0;c.push({focus:`event:${f.event}`,box:d&&a.some(a=>a.name===f.nextState)?bp([e,d]):e})}}return c}(bw(a.state,k),b):[],[a,b,c]);return(0,h.jsx)(eU,{docPath:f,kind:"machine",viewport:d,setViewport:e,boxes:l,boardRef:j,focus:g,level:c[c.length-1],onReveal:a=>{let b=a.map(a8).find(a=>a?.kind==="state");if(!b)return;let c=new URL(window.location.href);c.searchParams.set("focus",`state:${b.name}`),window.history.replaceState(window.history.state,"",c),window.dispatchEvent(new Event(ew))}})}let fE=a=>a.parallel?a.parallel.states:a.states??[];function fF(a,b){if(!a)return null;if(a.name===b)return[a.name];for(let c of fE(a)){let d=fF(c,b);if(d)return[a.name,...d]}return null}function fG(){let a=(0,d4.useRequestedDoc)(),b=ez("system"),[c,d]=(0,i.useState)(null);(0,i.useEffect)(()=>{let a=!0;return ed().then(b=>{a&&d(b.projectFile?aS(b.projectFile):"machine")}),()=>{a=!1}},[]);let e=a?aS(a):c;if(null===e)return(0,h.jsx)("div",{className:"app-shell bg-gray-950"});let f=a??"default",g="erd"===e?(0,h.jsx)(e3,{},f):"sequence"===e?(0,h.jsx)(ft,{},f):"system"===e?(0,h.jsx)(fC,{},f):(0,h.jsx)(fH,{}),j=(0,h.jsx)(es,{what:"document",resetKey:a,children:g});return b&&aQ(b)?(0,h.jsx)(eR,{children:(0,h.jsxs)("div",{className:"system-frame",children:[(0,h.jsx)(fx,{systemPath:b}),j]})}):(0,h.jsx)(eR,{children:j})}function fH(){let a,b;a=eC(),b=(0,i.useRef)(null),(0,i.useEffect)(()=>{let c=()=>{let a=b.current;if(!a)return;let c=dM.getState(),d=null;if(d&&c.docPath!==d||a.docAt!==c.docPath&&c.definition===a.defAt)return;b.current=null;let e=a8(a.focus);if(!e)return;let f=null,g=null;if("state"===e.kind)(f=fF(c.definition.state,e.name))&&(g={kind:"state",id:e.name});else if("event"===e.kind){let a=function a(b,c){if(!b)return null;let d=(b.transitions??[]).findIndex(a=>a?.event===c);if(d>=0)return{state:b.name,index:d};for(let d of fE(b)){let b=a(d,c);if(b)return b}return null}(c.definition.state,e.name);a&&(f=fF(c.definition.state,a.state),g={kind:"transition",id:`${a.state}:${a.index}`})}if(!f||!g)return;let h=f.length>1?f.slice(0,-1):f;dM.setState({navigationPath:h,currentParent:h[h.length-1]}),c.select(g.kind,g.id);let i=()=>{let a=dM.getState().layout.positions[f[f.length-1]],b=document.getElementById(dQ)?.getBoundingClientRect();if(!a||!b?.width)return;let c=S([a],b.width,b.height,{padding:60,maxScale:1});dM.getState().setViewport(c)};requestAnimationFrame(i),setTimeout(i,450)};if(a.nonce>0){let d=dM.getState();b.current=a.focus?{focus:a.focus,docAt:d.docPath,defAt:d.definition}:null,c()}return dM.subscribe(c)},[a]),(0,i.useEffect)(()=>dM.subscribe((a,b)=>{if(a.selection===b.selection||!a.selection.id)return;let{kind:c,id:d}=a.selection;if("state"===c)eB(`state:${d}`);else if("event"===c)eB(`event:${d}`);else if("transition"===c){let b=function(a,b){let c=b.lastIndexOf(":"),d=fF(a.state,b.slice(0,c));if(!d)return null;let e=a.state;for(let a of d.slice(1))e=fE(e).find(b=>b.name===a);return e?.transitions?.[Number(b.slice(c+1))]?.event??null}(a.definition,d);b&&eB(`event:${b}`)}}),[]);let[c,d]=(0,i.useState)("properties"),[e,f]=(0,i.useState)(!1),g=ev({onClose:()=>f(!1),restVh:70,tallVh:92}),j=dM(a=>a.errors),k=dM(a=>a.contextMenu),l=dM(a=>a.hideContextMenu),m=dM(a=>a.addState),n=dM(a=>a.removeState),o=dM(a=>a.setDrawMode),p=dM(a=>a.setDrawSource),q=[{id:"properties",label:"Properties",icon:"🎛"},{id:"events",label:"Events",icon:"⚡"},{id:"settings",label:"Settings",icon:"⚙"},{id:"validation",label:"Errors",icon:(0,h.jsx)(et,{}),badge:j.length||void 0}],r=q.find(a=>a.id===c)?.label??"";return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden",onClick:()=>k.visible&&l(),children:[(0,h.jsx)(ee,{}),(0,h.jsx)(eq,{}),(0,h.jsx)(d7,{}),(0,h.jsxs)("div",{className:"flex flex-1 min-h-0 overflow-hidden relative",children:[(0,h.jsxs)("div",{className:"relative flex-1 overflow-hidden",id:"machine-board",children:[(0,h.jsx)(es,{what:"state machine",children:(0,h.jsx)(dZ,{})}),(0,h.jsx)(fD,{})]}),e&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:g.close,"aria-hidden":"true"}),(0,h.jsxs)("aside",{style:g.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 h-[var(--sheet-h)] flex flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${e?"translate-y-0":"translate-y-full pointer-events-none"} md:static md:z-auto md:h-auto md:w-80 md:translate-y-0 md:pointer-events-auto md:rounded-none md:border-t-0 md:border-l md:shadow-none md:transition-none`,children:[(0,h.jsxs)("div",{className:"md:hidden",...g.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pt-2 pb-1",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:r}),(0,h.jsx)("button",{onClick:g.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:q.map(a=>(0,h.jsxs)("button",{onClick:()=>d(a.id),className:`flex-1 text-xs py-2 px-1 text-center transition-colors relative ${c===a.id?"text-blue-400 border-b-2 border-blue-400 bg-gray-800/50":"text-gray-500 hover:text-gray-300"}`,children:[a.label,void 0!==a.badge&&a.badge>0&&(0,h.jsx)("span",{className:"absolute top-1 right-1 bg-red-600 text-white text-[9px] rounded-full px-1 min-w-[14px]",children:a.badge})]},a.id))}),(0,h.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain",children:["properties"===c&&(0,h.jsx)(d_,{}),"events"===c&&(0,h.jsx)(d1,{}),"settings"===c&&(0,h.jsx)(d2,{}),"validation"===c&&(0,h.jsx)(d3,{})]})]}),(0,h.jsx)(d8,{})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:q.map(a=>{let b=e&&c===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(e&&c===b?g.close():f(!0),d(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&a.badge>0&&(0,h.jsx)("span",{className:"absolute top-1 right-1/2 translate-x-4 rounded-full bg-red-600 px-1 text-[10px] leading-4 text-white min-w-[16px]",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})}),k.visible&&(0,h.jsx)("div",{className:"fixed z-50 bg-gray-900 border border-gray-700 rounded-lg shadow-xl py-1 min-w-[180px] md:min-w-[140px]",style:{left:k.x,top:k.y,maxWidth:"calc(100vw - 1rem)",maxHeight:"calc(100dvh - 1rem)",overflowY:"auto",transform:"translate(0, 0)"},onClick:a=>a.stopPropagation(),children:k.target?.kind==="state"?(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("button",{className:"block w-full text-left text-sm text-gray-300 hover:bg-gray-800 px-4 py-3 md:text-xs md:px-3 md:py-1.5",onClick:()=>{o("transition"),p(k.target.id),l()},children:"↗ Draw transition from here"}),(0,h.jsx)("button",{className:"block w-full text-left text-sm text-red-400 hover:bg-gray-800 px-4 py-3 md:text-xs md:px-3 md:py-1.5",onClick:()=>{k.target?.id&&n(k.target.id),l()},children:"🗑 Delete state"})]}):(0,h.jsx)(h.Fragment,{children:(0,h.jsx)("button",{className:"block w-full text-left text-sm text-gray-300 hover:bg-gray-800 px-4 py-3 md:text-xs md:px-3 md:py-1.5",onClick:()=>{let a=prompt("State name:");a&&m(null,{name:a,kind:"normal"}),l()},children:"+ Add state here"})})})]})}a.s(["default",()=>fG],95421)}];
|
|
16
16
|
|
|
17
17
|
//# sourceMappingURL=%5Broot-of-the-server%5D__edbb995c._.js.map
|