@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.
Files changed (37) hide show
  1. package/package.json +1 -1
  2. package/server/.next/BUILD_ID +1 -1
  3. package/server/.next/build-manifest.json +2 -2
  4. package/server/.next/server/app/_global-error.html +2 -2
  5. package/server/.next/server/app/_global-error.rsc +1 -1
  6. package/server/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  7. package/server/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  8. package/server/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  9. package/server/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  10. package/server/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  11. package/server/.next/server/app/_not-found.html +1 -1
  12. package/server/.next/server/app/_not-found.rsc +1 -1
  13. package/server/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  14. package/server/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  15. package/server/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  16. package/server/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  17. package/server/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  18. package/server/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  19. package/server/.next/server/app/index.html +1 -1
  20. package/server/.next/server/app/index.rsc +2 -2
  21. package/server/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  22. package/server/.next/server/app/index.segments/_full.segment.rsc +2 -2
  23. package/server/.next/server/app/index.segments/_head.segment.rsc +1 -1
  24. package/server/.next/server/app/index.segments/_index.segment.rsc +1 -1
  25. package/server/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  26. package/server/.next/server/app/page_client-reference-manifest.js +1 -1
  27. package/server/.next/server/chunks/ssr/[root-of-the-server]__edbb995c._.js +3 -3
  28. package/server/.next/server/pages/404.html +1 -1
  29. package/server/.next/server/pages/500.html +2 -2
  30. package/server/.next/static/chunks/{f03f883bab5194ab.js → ec729c54327cc597.js} +3 -3
  31. package/server/package-lock.json +2 -2
  32. package/server/package.json +1 -1
  33. package/server/src/components/stage/CompanionLayer.tsx +10 -1
  34. package/server/stateloom-web.json +2 -2
  35. /package/server/.next/static/{HNER2j3kS6-hB98CL_HRG → pbn7-8jVWdRn8FLy4fHnU}/_buildManifest.js +0 -0
  36. /package/server/.next/static/{HNER2j3kS6-hB98CL_HRG → pbn7-8jVWdRn8FLy4fHnU}/_clientMiddlewareManifest.json +0 -0
  37. /package/server/.next/static/{HNER2j3kS6-hB98CL_HRG → pbn7-8jVWdRn8FLy4fHnU}/_ssgManifest.js +0 -0
@@ -7,8 +7,8 @@ ${t.error}`)}}catch(e){u(`# RISE rispec generation failed
7
7
  ${e}`)}h(!0)},J=async()=>{let e=a();try{let t=await fetch("/api/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({definition:e,language:H})});if(t.ok){let e=await t.json();u(e.code)}else{let n=await t.json().catch(()=>({error:"Unknown error"}));u(`// Code generation failed: ${n.error}
8
8
  // Showing definition JSON as fallback:
9
9
  ${e}`)}}catch{u(`// Backend unavailable — showing definition JSON
10
- ${e}`)}h(!0)};return(0,o.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,o.jsxs)("div",{className:"toolbar-ident",children:[(0,o.jsx)("input",{ref:S,type:"file",accept:".json,.smdf.json",onChange:e=>{let t=e.target.files?.[0];if(!t)return;let n=new FileReader;n.onload=e=>{r(e.target?.result,t.name)},n.readAsText(t),e.target.value=""},className:"hidden"}),(0,o.jsxs)("span",{className:"text-xs text-gray-400 mr-1 truncate max-w-[50vw] md:max-w-none",children:[t??"untitled.smdf.json",s&&(0,o.jsx)("span",{className:"text-yellow-500 ml-0.5",children:"●"})]}),(0,o.jsx)(s2,{}),"synced"===v&&(0,o.jsx)("span",{className:"text-[10px] text-emerald-500",title:"In sync with disk",children:"⌁ synced"}),"remote-changed"===v&&(0,o.jsx)("span",{className:"text-[10px] text-amber-400",title:w??"",children:"↻ remote changed"}),"error"===v&&(0,o.jsx)("span",{className:"text-[10px] text-red-400",title:w??"",children:"⚠ disk error"}),"idle"===v&&(0,o.jsx)("span",{className:"text-[10px] text-gray-600",title:w??"No file bound",children:"○ no disk"}),(0,o.jsx)(s5,{}),(0,o.jsx)("div",{className:"flex-1"})]}),(0,o.jsxs)("div",{className:"toolbar-strip",children:[(0,o.jsx)("button",{onClick:g,disabled:0===y.length,className:"toolbar-btn disabled:opacity-30",title:"Undo (Ctrl+Z)",children:"↩"}),(0,o.jsx)("button",{onClick:x,disabled:0===b.length,className:"toolbar-btn disabled:opacity-30",title:"Redo (Ctrl+Y)",children:"↪"}),(0,o.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,o.jsx)("button",{onClick:f,className:"toolbar-btn",title:"Arrange states into layers (auto-layout)",children:"⤢ Arrange"}),(0,o.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,o.jsx)("button",{onClick:()=>p("select"===m?"transition":"select"),className:`toolbar-btn ${"transition"===m?"!bg-amber-700 !text-white":""}`,title:"transition"===m?"Exit draw mode (Esc)":"Draw transition mode",children:"transition"===m?"✏️ Drawing":"↗ Draw"}),(0,o.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,o.jsx)("button",{onClick:()=>S.current?.click(),className:"toolbar-btn",title:"Open local .smdf.json (browser)",children:"📂"}),(0,o.jsx)("button",{onClick:F,disabled:_,className:"toolbar-btn disabled:opacity-40",title:"Save to disk (STATELOOM_PROJECT_FILE)",children:"💾 Disk"}),(0,o.jsx)("button",{onClick:z,className:"toolbar-btn",title:"Reload from disk",children:"🔄"}),(0,o.jsx)("button",{onClick:()=>{let e=new Blob([a()],{type:"application/json"}),n=URL.createObjectURL(e),s=document.createElement("a");s.href=n,s.download=t??"statemachine.smdf.json",s.click(),URL.revokeObjectURL(n)},className:"toolbar-btn",title:"Download as file",children:"📥"}),(0,o.jsx)("select",{value:T,onChange:e=>{O(e.target.value),B(null),D(null)},className:"bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 px-1 py-0.5",title:"Export format",children:sF.map(e=>(0,o.jsx)("option",{value:e,children:sU[e]},e))}),(0,o.jsx)("button",{onClick:U,disabled:P,className:`toolbar-btn disabled:opacity-40 ${L?"!text-red-400":""}`,title:L??`Export the board as ${sU[T]}`,children:P?"…":"🖼 Export"}),q&&!L&&(0,o.jsxs)("span",{className:"text-[10px] text-emerald-500 truncate max-w-[40vw] md:max-w-[16rem]",title:q,children:["⤓ ",q]}),(0,o.jsx)("div",{className:"w-px h-4 bg-gray-700"}),M?(0,o.jsxs)("div",{className:"flex items-center gap-1",children:[(0,o.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:E,onChange:e=>R(e.target.value),onKeyDown:e=>{"Enter"===e.key&&Y(),"Escape"===e.key&&C(!1)}}),(0,o.jsx)("button",{onClick:Y,className:"toolbar-btn-sm",children:"✓"}),(0,o.jsx)("button",{onClick:()=>C(!1),className:"toolbar-btn-sm",children:"✕"})]}):(0,o.jsx)("button",{onClick:()=>C(!0),className:"toolbar-btn",children:"+State"}),(0,o.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,o.jsx)("button",{onClick:()=>c(),className:"toolbar-btn",children:"✓ Validate"}),(0,o.jsxs)("select",{value:H,onChange:e=>X(e.target.value),className:"bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 px-1 py-0.5",children:[(0,o.jsx)("option",{value:"python",children:"Python"}),(0,o.jsx)("option",{value:"typescript",children:"TypeScript"})]}),(0,o.jsx)("button",{onClick:J,className:"toolbar-btn",children:"⚡ Generate"}),(0,o.jsx)("button",{onClick:V,className:"toolbar-btn",title:"Generate RISE rispec markdown",children:"📜 RISE"}),(0,o.jsxs)("button",{onClick:()=>h(!d),className:`toolbar-btn ${d?"text-blue-400":""}`,children:["</>"," Code"]})]})]})}function s3(){let e=sP(e=>e.generatedCode),t=sP(e=>e.showCodePreview),n=sP(e=>e.setShowCodePreview);return t?(0,o.jsx)("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/60 p-2 md:p-0",children:(0,o.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,o.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-800",children:[(0,o.jsx)("h3",{className:"text-sm font-semibold text-gray-300",children:"Generated Definition (JSON)"}),(0,o.jsx)("button",{onClick:()=>n(!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,o.jsx)("pre",{className:"flex-1 overflow-auto overscroll-contain p-4 text-[11px] leading-relaxed text-green-400 font-mono md:text-sm",children:e??"No code generated yet"}),(0,o.jsx)("div",{className:"flex justify-end px-4 py-2 border-t border-gray-800",children:(0,o.jsx)("button",{onClick:()=>{e&&navigator.clipboard.writeText(e)},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 s6(){let e=sP(e=>e.applyRemote),t=sP(e=>e.setRemoteStatus),n=sP(e=>e.setRemoteMtime),s=(0,s1.useRequestedDoc)();return(0,l.useEffect)(()=>{let r=!1,a=(0,s1.docQuery)(s);async function i(){try{let e=await fetch(`/api/file${a}`,{cache:"no-store"});if(!e.ok)return null;return await e.json()}catch{return null}}(async()=>{let n=await i();r||(n?.path&&sP.getState().setDocPath(n.path),n?.exists&&n.content?e(n.content,n.mtime,n.path.split("/").pop()):t("idle",n?`No file at ${n.path}`:null))})();let o=new EventSource(`/api/watch${a}`);return o.addEventListener("hello",e=>{try{let t=JSON.parse(e.data);"number"==typeof t?.mtime&&n(t.mtime)}catch{}}),o.addEventListener("change",async s=>{let r=0;try{r=JSON.parse(s.data)?.mtime??0}catch{}if(r<=(sP.getState().remoteMtime??0))return;let a=await i();a?.exists&&a.content&&(sP.getState().dirty?(t("remote-changed",`Disk changed at ${new Date(a.mtime).toLocaleTimeString()} — local has unsaved edits`),n(a.mtime)):e(a.content,a.mtime,a.path.split("/").pop()))}),o.addEventListener("error",()=>{t("error","Watch stream disconnected")}),()=>{r=!0,o.close()}},[e,t,n,s]),null}function s8({url:e}){let t=(0,s1.useRequestedDoc)();return(0,l.useEffect)(()=>{if(!e)return;let n=!1,s=null,r=null,a=null,i=null;return(async()=>{let o="";try{let e=await fetch(`/api/file${(0,s1.docQuery)(t)}`,{cache:"no-store"});e.ok&&(o=(await e.json())?.path??"")}catch{}n||(o&&sP.getState().setDocPath(o),(s=sv({url:e,role:"web",docId:o,name:"web-designer",onFull:e=>{sP.getState().applyRemote(JSON.stringify({stateMachine:e.def}),e.mtime??Date.now(),o&&o.split("/").pop()||void 0),i=e.def},onPatch:e=>{sP.getState().applyRemoteOps(e.ops,e.mtime??Date.now(),e.seq),i=sP.getState().definition},onPresence:e=>{sP.getState().setPresence(e)}})).connect(),r=sP.subscribe((e,t)=>{e.definition===t.definition||e._applyingRemote||(a&&clearTimeout(a),a=setTimeout(()=>{var e,t;let n,r;if(!s||"connected"!==s.getSnapshot().status)return;let a=sP.getState().definition;if(null===i){s.emitFull(a),i=a;return}let o=(e=i,t=a,n=e??{settings:{namespace:"",asynchronous:!1},events:[],state:{name:t.state.name,states:[]}},function(e,t,n){let s={},r=!1,a=new Set([...Object.keys(e.settings),...Object.keys(t.settings)]),i=e.settings,o=t.settings;for(let e of a)g(i[e],o[e])||void 0===o[e]||(s[e]=o[e],r=!0);void 0!==e.settings.notes&&void 0===t.settings.notes&&(s.notes="",r=!0),r&&n.push({op:"settings.update",patch:s})}(n,t,r=[]),function(e,t,n){let s=e.events,r=t.events,a=Math.min(s.length,r.length);for(let e=0;e<a;e++)!function(e,t,n,s){let r={},a=!1;for(let e of["name","file","feeder","description","timers"])g(t[e],n[e])||void 0===n[e]||(r[e]=n[e],a=!0);a&&s.push({op:"eventSource.update",index:e,patch:r});let i=t.events??[],o=n.events??[],l=new Set(o.map(e=>e.id));for(let e of i)l.has(e.id)||s.push({op:"event.remove",id:e.id});let c=i.filter(e=>l.has(e.id)),d=0;for(;d<o.length;){let t=o[d];d<c.length&&c[d].id===t.id?(function(e,t,n){let s={},r=!1;for(let n of["name","description","preAction","postAction"])g(e[n],t[n])||void 0===t[n]||(s[n]=t[n],r=!0);r&&n.push({op:"event.update",id:t.id,patch:s})}(c[d],t,s),function(e,t,n,s){let r=Math.min(t.length,n.length);for(let a=0;a<r;a++)if(!g(t[a],n[a])){let r={};t[a].name!==n[a].name&&(r.name=n[a].name),t[a].type!==n[a].type&&(r.type=n[a].type),s.push({op:"parameter.update",eventId:e,index:a,patch:r})}for(let t=r;t<n.length;t++)s.push({op:"parameter.add",eventId:e,parameter:n[t],index:t});for(let r=t.length-1;r>=n.length;r--)s.push({op:"parameter.remove",eventId:e,index:r})}(t.id,c[d].parameters??[],t.parameters??[],s)):(s.push({op:"event.add",sourceIndex:e,event:t,index:d}),c.splice(d,0,t)),d++}}(e,s[e],r[e],n);for(let e=s.length;e<r.length;e++)n.push({op:"eventSource.add",source:r[e]});for(let e=s.length-1;e>=r.length;e--)n.push({op:"eventSource.remove",index:e})}(n,t,r),function(e,t,n){let s=p(e.state),r=p(t.state),a=new Map(s.map(e=>[e.name,e])),i=new Map(r.map(e=>[e.name,e])),o=f(e.state),l=f(t.state),c=[];for(let e of r){if(a.has(e.name))continue;let t=l.get(e.name)??null,{states:s,transitions:r,...i}=e;n.push({op:"state.add",parent:t,state:{...i}}),r&&r.length>0&&c.push({state:e.name,transitions:r})}for(let e of r){if(!a.has(e.name))continue;let t=o.get(e.name)??null,s=l.get(e.name)??null;t!==s&&null!==s&&n.push({op:"state.nest",child:e.name,newParent:s})}for(let e of r){let t=a.get(e.name);if(!t)continue;let s={},r=!1;g(t.kind,e.kind)||void 0===e.kind||(s.kind=e.kind,r=!0),g(t.description,e.description)||void 0===e.description||(s.description=e.description,r=!0),g(t.notes,e.notes)||(s.notes=e.notes??"",r=!0),g(t.prompt,e.prompt)||(s.prompt=e.prompt??"",r=!0),r&&n.push({op:"state.update",name:e.name,patch:s}),x(e.name,"onEntry",t.onEntry?.actions??[],e.onEntry?.actions??[],n),x(e.name,"onExit",t.onExit?.actions??[],e.onExit?.actions??[],n)}for(let e of c)e.transitions.forEach((t,s)=>{n.push({op:"transition.add",state:e.state,transition:t,index:s})});for(let e of r){let t=a.get(e.name);t&&function(e,t,n,s){let r=Math.min(t.length,n.length);for(let a=0;a<r;a++){if(g(t[a],n[a]))continue;let r={};for(let e of["event","nextState","condition","description","actions"])g(t[a][e],n[a][e])||void 0===n[a][e]||(r[e]=n[a][e]);Object.keys(r).length>0&&s.push({op:"transition.update",state:e,index:a,patch:r})}for(let t=r;t<n.length;t++)s.push({op:"transition.add",state:e,transition:n[t],index:t});for(let r=t.length-1;r>=n.length;r--)s.push({op:"transition.remove",state:e,index:r})}(e.name,t.transitions??[],e.transitions??[],n)}for(let e=s.length-1;e>=0;e--){let t=s[e];if(i.has(t.name))continue;let r=t.transitions??[];for(let e=r.length-1;e>=0;e--)n.push({op:"transition.remove",state:t.name,index:e});n.push({op:"state.remove",name:t.name})}}(n,t,r),r);0!==o.length&&(s.emitPatch(o),i=a)},60))}))})(),()=>{n=!0,a&&clearTimeout(a),r&&r(),s&&s.disconnect()}},[e,t]),null}function s7(){let e=b.default.env.NEXT_PUBLIC_STATELOOM_BRIDGE_URL??b.default.env.NEXT_PUBLIC_SMCRAFT_BRIDGE_URL;return"string"==typeof e&&e.length>0?e:void 0}let s9=null;function re(){return s9||(s9=(async()=>{let e=s7()??null;try{let t=await fetch("/api/config",{cache:"no-store"});if(t.ok){let n=await t.json();return{bridgeUrl:n.bridgeUrl||e,projectFile:n.projectFile??null,stage:n.stage??null,companion:!0===n.companion,companionEpisode:n.companionEpisode??null}}}catch{}return{bridgeUrl:e,projectFile:null,stage:null,companion:!1,companionEpisode:null}})())}function rt(){let e=s7(),[t,n]=(0,l.useState)(e);return((0,l.useEffect)(()=>{let e=!0;return re().then(t=>{e&&t.bridgeUrl&&n(t.bridgeUrl)}),()=>{e=!1}},[]),"string"==typeof t&&t.length>0)?(0,o.jsx)(s8,{url:t}):(0,o.jsx)(s6,{})}let rn="stateloom.uiScale.v1";function rs(e){return Number.isFinite(e)?Math.min(1.75,Math.max(.75,e)):1}function rr(e){"u">typeof document&&(document.documentElement.style.fontSize=`${16*rs(e)}px`)}let ra=1,ri=!1,ro=new Set;function rl(){return ri||(ri=!0,ra=function(){try{let e=window.localStorage.getItem(rn);if(null===e)return 1;return rs(Number.parseFloat(e))}catch{return 1}}()),ra}function rc(){return 1}function rd(e){return ro.add(e),()=>{ro.delete(e)}}function rh(e,t){let n=rs(e);if(rr(n),t&&function(e){try{window.localStorage.setItem(rn,String(rs(e)))}catch{}}(n),ri=!0,n!==ra)for(let e of(ra=n,ro))e()}function ru(e,t){return Math.max(1,Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY))}function rm(e,t){for(let n=0;n<e.length;n++)if(e[n].identifier===t)return e[n];return null}function rp(){let e=(0,l.useSyncExternalStore)(rd,rl,rc),t=(0,l.useRef)(null),n=(0,l.useRef)(null),s=(0,l.useRef)(null);(0,l.useEffect)(()=>{rr(e)},[e]);let r=(0,l.useCallback)(e=>{n.current=e,null===s.current&&(s.current=requestAnimationFrame(()=>{s.current=null,null!==n.current&&rh(n.current,!1)}))},[]),a=(0,l.useCallback)(()=>{n.current=null,rh(1,!0)},[]);return((0,l.useEffect)(()=>{let e=()=>{let e=t.current;if(t.current=null,!e?.engaged)return;null!==s.current&&(cancelAnimationFrame(s.current),s.current=null);let r=n.current??rl();n.current=null,rh(rs(r),!0)},a=n=>{if(2!==n.touches.length){t.current&&e();return}let[s,r]=[n.touches[0],n.touches[1]];sD(s.target)||sD(r.target)||(t.current={a:s.identifier,b:r.identifier,startScale:rl(),startDist:ru(s,r),engaged:!1})},i=e=>{let n=t.current;if(!n)return;let s=rm(e.touches,n.a),a=rm(e.touches,n.b);if(!s||!a)return;e.preventDefault();let i=ru(s,a);if(!n.engaged){if(12>Math.abs(i-n.startDist))return;n.engaged=!0,n.startDist=i;return}r(rs(n.startScale*(i/n.startDist)))},o=n=>{let s=t.current;s&&(rm(n.touches,s.a)&&rm(n.touches,s.b)||e())};return document.addEventListener("touchstart",a,{passive:!0,capture:!0}),document.addEventListener("touchmove",i,{passive:!1,capture:!0}),document.addEventListener("touchend",o,{passive:!0,capture:!0}),document.addEventListener("touchcancel",o,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",a,{capture:!0}),document.removeEventListener("touchmove",i,{capture:!0}),document.removeEventListener("touchend",o,{capture:!0}),document.removeEventListener("touchcancel",o,{capture:!0}),null!==s.current&&cancelAnimationFrame(s.current)}},[r]),1===e)?null:(0,o.jsxs)("div",{className:"ui-scale-pill",role:"status","aria-live":"polite",children:[(0,o.jsxs)("span",{children:["UI ",Math.round(100*e),"%"]}),(0,o.jsx)("button",{type:"button",onClick:a,"aria-label":"Reset interface size to 100 percent",children:"Reset"})]})}var rf=l;class rg extends rf.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error(`[stateloom] the ${this.props.what} could not be drawn:`,e,t.componentStack)}componentDidUpdate(e){this.state.error&&e.resetKey!==this.props.resetKey&&this.setState({error:null})}render(){let{error:e}=this.state;return e?(0,o.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,o.jsxs)("p",{className:"max-w-md",children:["This ",this.props.what," cannot be drawn: ",e.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 rx({size:e=16}){return(0,o.jsxs)("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,o.jsx)("path",{d:"M12 4.5 21 19.5H3Z"}),(0,o.jsx)("path",{d:"M12 10v4.5"}),(0,o.jsx)("path",{d:"M12 17.3v.01"})]})}function ry({locked:e,size:t=16}){return(0,o.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,o.jsx)("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),(0,o.jsx)("path",{d:e?"M8 11V8a4 4 0 0 1 8 0v3":"M8 11V8a4 4 0 0 1 7.5-1.9"})]})}function rb(e){let{onClose:t,restVh:n,tallVh:s}=e,[r,a]=(0,l.useState)(!1),[i,o]=(0,l.useState)(null),c=(0,l.useRef)(null),d=()=>{a(!1),t()},h=e=>{let t=c.current;if(!t||t.id!==e.pointerId)return;c.current=null;let n=e.clientY-t.y;if(o(null),6>Math.abs(n))return a(e=>!e);if(n<=-50)return a(!0);if(n>=80){if(r&&n<260)return a(!1);d()}},u=r?s:n,m=null!==i;return{zoneProps:{onPointerDown:e=>{e.target.closest("button")||(c.current={y:e.clientY,id:e.pointerId},e.currentTarget.setPointerCapture(e.pointerId),o(0))},onPointerMove:e=>{let t=c.current;t&&t.id===e.pointerId&&o(e.clientY-t.y)},onPointerUp:h,onPointerCancel:h,style:{touchAction:"none",cursor:"grab"}},sheetStyle:{"--sheet-h":m&&i<0?`min(calc(${u}dvh + ${-i}px), ${s}dvh)`:`${u}dvh`,...m?{transition:"none"}:{},...m&&i>0?{transform:`translateY(${i}px)`}:{}},close:d}}let rv="stateloom:focus",rw="stateloom:focus-request",rj="stateloom:system-changed",rk="stateloom:strip-note";function r$(e){return new URLSearchParams(window.location.search).get(e)}function rN(e){let[t,n]=(0,l.useState)(null);return(0,l.useEffect)(()=>{let t=()=>n(r$(e));t();let s=["popstate",s1.DOC_CHANGE_EVENT,rv,rw];for(let e of s)window.addEventListener(e,t);return()=>{for(let e of s)window.removeEventListener(e,t)}},[e]),t}function rS(e){let t=new URL(window.location.href),n=t.searchParams.get("doc")!==e.doc;t.searchParams.set("doc",e.doc);let s=void 0===e.system?t.searchParams.get("system"):e.system;s?t.searchParams.set("system",s):t.searchParams.delete("system"),e.focus?t.searchParams.set("focus",e.focus):t.searchParams.delete("focus"),n?window.history.pushState({},"",t):window.history.replaceState(window.history.state,"",t),n&&window.dispatchEvent(new Event(s1.DOC_CHANGE_EVENT)),window.dispatchEvent(new Event(rw))}function rM(e){let t=new URL(window.location.href);(t.searchParams.get("focus")??null)!==e&&(e?t.searchParams.set("focus",e):t.searchParams.delete("focus"),window.history.replaceState(window.history.state,"",t),window.dispatchEvent(new CustomEvent(rv)))}function rC(){let[e,t]=(0,l.useState)({focus:null,nonce:0});return(0,l.useEffect)(()=>{let e=()=>t(e=>({focus:r$("focus"),nonce:e.nonce+1}));e();let n=["popstate",s1.DOC_CHANGE_EVENT,rw];for(let t of n)window.addEventListener(t,e);return()=>{for(let t of n)window.removeEventListener(t,e)}},[]),e}let rE="/api/companion/",rR="stateloom.companion.autoplay",r_=/^\d{4}-\d{2}-\d{2}-episode-\d+-[a-z0-9-]+$/,rA=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})},rT=e=>"starting"===e||"recording"===e||"sending"===e,rO={state:"idle",seconds:0,held:0,message:"",error:!1,stored:null},rP={episode:null,items:[],presence:null,waiting:null,error:null};function rI({stage:e,defaultEpisode:t}){let[n,s]=(0,l.useState)(!1),[r,a]=(0,l.useState)(()=>"0"!==function(e){try{return window.localStorage.getItem(e)}catch{return null}}(rR)),[i,c]=(0,l.useState)(()=>{var e;let n,s=r$("episode");return(s&&r_.test(s)?s:null)??(e=(0,s1.requestedDoc)(),(n=e?.match(/(?:^|\/)(\d{4}-\d{2}-\d{2}-episode-\d+-[a-z0-9-]+)\/diagrams\/[^/]+$/))?n[1]:null)??t}),[d,h]=(0,l.useState)([]),[u,m]=(0,l.useState)(rO),[p,f]=(0,l.useState)(rP),[g,x]=(0,l.useState)(null),[y,b]=(0,l.useState)([]),[v,w]=(0,l.useState)(null),[j,k]=(0,l.useState)(null),[$,N]=(0,l.useState)(()=>Date.now()),S=(0,l.useRef)(e),M=(0,l.useRef)(i),C=(0,l.useRef)(r);(0,l.useEffect)(()=>{S.current=e,M.current=i,C.current=r});let E=(0,l.useRef)(rO),R=(0,l.useRef)(null),_=(0,l.useRef)([]),A=(0,l.useRef)(!1),T=(0,l.useRef)([]),O=(0,l.useRef)(null),P=(0,l.useRef)(null),I=(0,l.useMemo)(()=>sw({recordings:!0,speech:!1}),[]),L=e=>{R.current=e,x(e)},D=(0,l.useRef)(async()=>{}),q=(0,l.useCallback)(async(e,t=0)=>{L(e.id),b(t=>t.filter(t=>t!==e.id)),e.steps?.length&&window.matchMedia("(max-width: 767px)").matches&&s(!1);let n=_.current.length;w(n?`${n} more of Mia's replies wait after this one.`:null);let r=await S.current.present(function(e,t,n="Mia"){let s=new Date(e.at),r=Number.isNaN(s.getTime())?`${n}'s reply`:`Reply at ${s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`,a=!e.unvoiced,i=(e,n)=>(function(e,t){if(!t)return;if(/^https?:\/\//.test(t))return t;let n=t.replace(/^\/?api\//,"");return`${e.endsWith("/")?e:`${e}/`}${n}`})(t,e||(a?n:null));return{settings:{namespace:"companion",name:r,author:n},steps:e.steps?.length?e.steps.map(({audio:t,...n},s)=>{let r=i(t,`api/replies/${e.id}/steps/${s}/audio`);return{...n,...r?{audio:r}:{}}}):[{say:e.text,...i(e.audio,`api/replies/${e.id}/audio`)?{audio:i(e.audio,`api/replies/${e.id}/audio`)}:{}}]}}(e,rE,"Mia"),{voice:I,origin:"Mia",from:t});if(R.current!==e.id||(L(null),A.current))return;if(!r){_.current=[];return}let a=_.current.shift();a&&!rT(E.current.state)?D.current(a):a&&_.current.unshift(a)},[I]);(0,l.useEffect)(()=>{D.current=q},[q]);let B=(0,l.useCallback)(e=>{let t=e.id;if(!C.current)return void b(e=>e.includes(t)?e:[...e,t]);if(rT(E.current.state)||R.current){b(e=>e.includes(t)?e:[...e,t]),_.current.some(e=>e.id===t)||_.current.push(e),w(rT(E.current.state)?`Mia replied at ${rA(e.at)}. Her voice waits until you have sent your take.`:`Mia replied again at ${rA(e.at)}. It plays when this one ends.`);return}D.current(e)},[]);(0,l.useEffect)(()=>{let e=function(e){let t=e.base.endsWith("/")?e.base:`${e.base}/`,n=e.fetch??((...e)=>fetch(...e)),s=e.everyMs??1e4,r=e.waitEveryMs??4e3,a=e.waitForMs??9e5,i={episode:null,items:[],presence:null,waiting:null,error:null},o=new Set,l=!1,c=null,d=null,h="",u=0,m=t=>{i={...i,...t},e.onChange?.(i)};async function p(){let s=i.episode;if(!s)return;let r=u;try{let c=await n(`${t}thread?episode=${encodeURIComponent(s)}`,{cache:"no-store"}),p=await c.json();if(r!==u)return;if(!p.success)return m({error:p.error??`HTTP ${c.status}`});let f=p.items??[],g=f.map(e=>"reply"===e.kind?`${e.id}:${+!!e.audio}:${e.feedback??""}`:`${e.take}:${e.text.length}`).join(",")+`|${p.presence?.state}`,x=f.filter(e=>"reply"===e.kind&&!o.has(e.id));for(let e of x)o.add(e.id);if((g!==h||i.error)&&(h=g,m({items:f,presence:p.presence??null,error:null})),l)for(let t of x)e.onReply?.(t);l=!0;let y=i.waiting;y&&(f.some(e=>"reply"===e.kind&&e.take===y.take)||Date.now()-y.since>a)&&(d&&clearInterval(d),d=null,m({waiting:null}))}catch(e){r===u&&m({error:e instanceof Error?e.message:String(e)})}}let f=()=>{"visible"===document.visibilityState&&p()};return"u">typeof document&&document.addEventListener("visibilitychange",f),{getSnapshot:()=>i,setEpisode(e){e!==i.episode&&(u+=1,o.clear(),l=!1,h="",d&&clearInterval(d),d=null,m({episode:e,items:[],presence:null,waiting:null,error:null}),e?(c&&clearInterval(c),c=setInterval(()=>{("u"<typeof document||"visible"===document.visibilityState)&&p()},s),p()):c&&(clearInterval(c),c=null))},refresh:p,waitFor(e){m({waiting:{take:e,since:Date.now()}}),d&&clearInterval(d),d=setInterval(()=>void p(),r),p()},async feedback(e,s){await n(`${t}replies/${e}/feedback`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({value:s})}),h="",await p()},destroy(){for(let e of(u+=1,[c,d]))e&&clearInterval(e);c=d=null,"u">typeof document&&document.removeEventListener("visibilitychange",f)}}}({base:rE,onChange:f,onReply:B}),t=function(e){let t,n=e.base.endsWith("/")?e.base:`${e.base}/`,s=e.fetch??((...e)=>fetch(...e)),r=e.partEveryMs??1e4,a=e.beatEveryMs??15e3,i=(t=window.MediaRecorder)&&sj.some(e=>!t.isTypeSupported||t.isTypeSupported(e))?"mp4":window.AudioContext??window.webkitAudioContext?"wav":null,o=!1!==window.isSecureContext,l=e.getUserMedia??(e=>navigator.mediaDevices.getUserMedia(e)),c=e.createRecorder??(e=>{let t,n,s,r,a,o,l,c;return"mp4"===i?new window.MediaRecorder(e,{mimeType:sj.find(e=>window.MediaRecorder.isTypeSupported?.(e)??!0)}):(n=(t=new(window.AudioContext??window.webkitAudioContext)).createMediaStreamSource(e),s=t.createScriptProcessor(4096,1,1),r=[],a=[],o=!1,l=null,c={mimeType:"audio/wav",ondataavailable:null,onstop:null,onerror:null,start(e=1e3){s.onaudioprocess=e=>{let t=e.inputBuffer.getChannelData(0),n=new Int16Array(t.length);for(let e=0;e<t.length;e++)n[e]=Math.max(-32768,Math.min(32767,Math.round(32767*t[e])));r.push(n),a.push(n)},n.connect(s),s.connect(t.destination),l=setInterval(()=>{if(!a.length)return;let e=o?[]:[sk(0x7fffffff,t.sampleRate)];o=!0,e.push(...a.map(e=>e.buffer)),a=[],c.ondataavailable?.({data:new Blob(e,{type:"audio/wav"})})},e)},stop(){l&&clearInterval(l),l=null;try{n.disconnect(),s.disconnect()}catch{}t.close().catch(()=>{}),c.whole=new Blob([sk(r.reduce((e,t)=>e+t.byteLength,0),t.sampleRate),...r.map(e=>e.buffer)],{type:"audio/wav"}),c.onstop?.()}})}),d={state:"idle",seconds:0,held:0,message:"",error:!1,stored:null,...!e.createRecorder&&(!i||!o)?{unavailable:o?"this browser cannot record audio":"the microphone needs a secure page (https, or this machine's own address)"}:{}},h=t=>{d={...d,...t},e.onChange?.(d)},u=null,m=null,p=[],f="",g="",x=null,y=0,b=null,v=null,w=null,j=null,k=!1,$=()=>y?Math.floor((Date.now()-y)/1e3):0,N=()=>(m?.mimeType||"audio/mp4").split(";")[0]||"audio/mp4",S=(e="")=>`episode=${encodeURIComponent(g)}${f?`&rec=${f}`:""}${x?`&context=${encodeURIComponent(x)}`:""}${e}`;function M(e){g&&s(`${n}recorder`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({episode:g,recording:e})}).catch(()=>{})}function C(e,t={}){f&&s(`${n}takes/diagnostic`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({rec:f,episode:g,kind:e,at:new Date().toISOString(),mime:m?.mimeType??i,visibility:"u">typeof document?document.visibilityState:"",agent:"u">typeof navigator?navigator.userAgent:"",source:"stateloom-canvas",...t}),keepalive:!0}).catch(()=>{})}function E(){for(let e of[v,w,j])e&&clearInterval(e);v=w=j=null}function R(){try{u?.getTracks().forEach(e=>e.stop())}catch{}u=null}async function _(){if(!f||k||!p.length)return;let e=new Blob(p,{type:N()});if(e.size<=d.held)return;k=!0;let t=f;try{let r=await s(`${n}takes/part?${S(`&offset=${d.held}`)}`,{method:"POST",headers:{"content-type":N()},body:e.slice(d.held)}),a=await r.json();t===f&&"number"==typeof a.bytes&&h({held:a.bytes})}catch{}finally{k=!1}}async function A(){let t;if("idle"!==d.state&&"retry"!==d.state)return;if(d.unavailable)return h({message:`Cannot record: ${d.unavailable}.`,error:!0});if(!(g=e.episode()??""))return h({message:"Choose the episode this take belongs to.",error:!0});let n=e.context?.()??null;x=n?JSON.stringify(n).slice(0,4e3):null,b=null,h({state:"starting",message:"",error:!1,held:0,seconds:0}),M(!0);try{t=await l({audio:!0})}catch(e){return M(!1),h({state:"idle",message:`Microphone refused: ${e instanceof Error?e.message:String(e)}`,error:!0})}if("starting"!==d.state)return void t.getTracks().forEach(e=>e.stop());u=t,p=[],f=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;try{m=c(t)}catch(e){return R(),M(!1),h({state:"idle",message:`This browser refused to record: ${e instanceof Error?e.message:String(e)}`,error:!0})}m.ondataavailable=e=>{e.data&&e.data.size&&p.push(e.data)},m.onerror=e=>{let t=$(),n=new Blob(p,{type:N()});if(C("recorder-error",{name:e?.error?.name??"",message:e?.error?.message??"",seconds:t,bytes:n.size,held:d.held}),E(),R(),M(!1),n.size)b=n,h({state:"retry",message:`The recorder stopped with an error after ${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}. What it captured is kept: Send again.${d.held?` ${s$(d.held)} of it is already stored.`:""}`,error:!0});else h({state:"idle",message:"The recorder stopped before it captured anything. Nothing was sent.",error:!0})},m.start(1e3),y=Date.now(),v=setInterval(()=>void _(),r),w=setInterval(()=>M(!0),a),j=setInterval(()=>h({seconds:$()}),500),h({state:"recording",seconds:0,message:""})}async function T(t){h({state:"sending",message:`Sending ${s$(t.size)}, then transcribing and storing…`,error:!1});try{let r=await s(`${n}takes?${S()}`,{method:"POST",headers:{"content-type":(t.type||"audio/mp4").split(";")[0]},body:t}),a=await r.json();if(!a.success||!a.take)throw Error(a.error||`HTTP ${r.status}`);b=null,f="";let i=a.presence??{state:a.listening?"listening":"away"},o=a.transcriptError?` Transcription failed, so no session wakes yet: ${a.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."})[i.state]??" No session is listening yet; the take waits, and her reply comes here when one answers.";h({state:"idle",seconds:0,held:0,message:`Take ${a.take} is in the episode.${o}`,error:!!a.transcriptError,stored:{take:a.take,english:a.english??"",transcriptError:a.transcriptError,presence:i}}),a.transcriptError||e.onStored?.(a.take)}catch(e){b=t,C("send-failed",{message:e instanceof Error?e.message:String(e),bytes:t.size,held:d.held}),h({state:"retry",message:`Not stored: ${e instanceof Error?e.message:String(e)}. Your recording is kept — Send again.${d.held?` ${s$(d.held)} of it is already stored, and becomes a take by itself if you leave.`:""}`,error:!0})}}async function O(){if("recording"!==d.state)return;let e=$();E(),M(!1),h({state:"sending",seconds:e});let t=await new Promise(e=>{let t=!1,n=()=>{t||(t=!0,e(m?.whole??new Blob(p,{type:N()})))},s=setTimeout(n,3e3);if(!m)return n();m.onstop=()=>{clearTimeout(s),n()};try{m.stop()}catch{clearTimeout(s),n()}});if(R(),!t.size)return C("empty-at-stop",{seconds:e,held:d.held}),h({state:"idle",message:d.held?`The recorder handed back nothing at Stop, but ${s$(d.held)} is stored; it becomes a take within a few minutes.`:"Nothing was recorded. Try again.",error:!0});await T(t)}async function P(){"retry"===d.state&&b&&await T(b)}return{getSnapshot:()=>d,press:async()=>"recording"===d.state?O():"retry"===d.state&&b?P():A(),start:A,stop:O,resend:P,destroy(){E(),("recording"===d.state||"starting"===d.state)&&M(!1);try{m?.stop()}catch{}R()}}}({base:rE,episode:()=>M.current,context:()=>{let e=S.current.shown,t=e?{...e.title||e.step.title?{title:[e.title,e.step.title].filter(Boolean).join(" · ")}:{},say:e.step.say.slice(0,400),...null!==e.index&&null!==e.count?{index:e.index,count:e.count}:{},...e.origin?{by:e.origin}:{}}:null;return function(e,t={}){if(!e?.doc)return null;let n={stage:e.stage,doc:e.doc,kind:e.kind,system:e.system,focus:e.focus??void 0,visible:e.visible,tour:e.tour,who:e.who,at:new Date().toISOString(),...t};for(let e of Object.keys(n))(void 0===n[e]||null===n[e])&&delete n[e];return n}(S.current.lastReport(),{...T.current.length?{marks:T.current}:{},...e?.step.spotlight?.length?{spotlight:e.step.spotlight}:{},...t?{step:t}:{}})},onChange:e=>{let t=E.current.state;if(E.current=e,m(e),!rT(t)||rT(e.state)||(A.current=!1,!C.current||R.current))return;let n=_.current.shift();n?D.current(n):w(null)},onStored:t=>e.waitFor(t)});return P.current=e,O.current=t,E.current=t.getSnapshot(),m(t.getSnapshot()),()=>{t.destroy(),e.destroy(),P.current=null,O.current=null}},[B]),(0,l.useEffect)(()=>{P.current?.setEpisode(i)},[i]),(0,l.useEffect)(()=>{let e=!0;return fetch(`${rE}health`,{cache:"no-store"}).then(e=>e.json()).then(t=>{if(e){if(!t.success)return k(`The companion does not answer: ${t.error??"no reason given"}.`);k(null),t.defaultEpisode&&c(e=>e??t.defaultEpisode??null)}}).catch(t=>e&&k(`The companion does not answer: ${t instanceof Error?t.message:String(t)}.`)),()=>{e=!1}},[]),(0,l.useEffect)(()=>{if(!n||d.length)return;let e=!0;return fetch(`${rE}episodes`,{cache:"no-store"}).then(e=>e.json()).then(t=>{e&&t.success&&t.episodes&&h(t.episodes)}).catch(()=>{}),()=>{e=!1}},[n,d.length]);let F=(0,l.useRef)(null),U=(0,l.useCallback)(async(e=!1)=>{let t=S.current.lastReport()?.doc??null;if(e||t!==F.current){if(F.current=t,!t){T.current=[];return}try{var n,s;let e=await fetch(`/api/marks?doc=${encodeURIComponent(t)}`,{cache:"no-store"}),r=await e.json();T.current=(n=function(e,t=""){let n=e&&"object"==typeof e?e:{},s=Array.isArray(n.marks)?n.marks.map(tp).filter(e=>null!==e):[];return{doc:th(n.doc)||t,marks:s}}(r,t).marks,s="agent",n.filter(e=>"open"===e.status&&e.author.role!==s||"answered"===e.status&&e.author.role===s)).map(e=>e.id)}catch{T.current=[]}}},[]);(0,l.useEffect)(()=>{U(!0);let e=S.current.onMarks(()=>void U(!0)),t=setInterval(()=>void U(),3e3);return()=>{e(),clearInterval(t)}},[U]),(0,l.useEffect)(()=>{if(!p.waiting)return;let e=setInterval(()=>N(Date.now()),1e3);return()=>clearInterval(e)},[p.waiting]);let z=(0,l.useCallback)(()=>{let e=O.current;e&&(!rT(E.current.state)&&"retry"!==E.current.state&&R.current&&(A.current=!0,S.current.stop()),e.press())},[]),Y=(0,l.useCallback)((e,t)=>{let n=P.current?.getSnapshot().items.find(t=>"reply"===t.kind&&t.id===e);if(n){if(rT(E.current.state))return void w(`Send your take first. Then press ▶ to hear Mia.`);_.current=[],A.current=!1,D.current(n,t)}},[]),H=(0,l.useCallback)(()=>{_.current=[],A.current=!1,S.current.stop()},[]),X=p.waiting?{take:p.waiting.take,seconds:Math.max(0,Math.floor(($-p.waiting.since)/1e3))}:null;return(0,o.jsx)("div",{className:"stage-talk-host",children:(0,o.jsx)(nd,{open:n,onOpenChange:e=>{s(e),e&&U(!0)},who:"Mia",episode:i,episodes:d,onEpisode:e=>{r_.test(e)&&e!==i&&(_.current=[],b([]),w(null),c(e))},presence:p.presence,recorder:u,onRecord:z,items:p.items,unheard:y,playing:g,playingStep:g&&e.shown?.origin==="Mia"?e.shown.index:null,onPlay:Y,onStop:H,onFeedback:(e,t)=>{P.current?.feedback(e,t).catch(e=>k(`Your thumb was not kept: ${e instanceof Error?e.message:String(e)}.`))},autoplay:r,onAutoplay:e=>{a(e);try{window.localStorage.setItem(rR,e?"1":"0")}catch{}e||(_.current=[])},waiting:X,notice:v,error:j??p.error})})}let rL=(0,l.createContext)(null);function rD(){return(0,l.useContext)(rL)}let rq="stateloom.stage.voice",rB="stateloom.author";function rF(e){try{return window.localStorage.getItem(e)??""}catch{return""}}function rU(e,t){try{window.localStorage.setItem(e,t)}catch{}}function rz({children:e}){var t;let n,s,r,a,i,c,d,h,[u,m]=(0,l.useState)({bridgeUrl:null,stage:ti,companion:!1,companionEpisode:null});(0,l.useEffect)(()=>{let e=!0;return re().then(t=>{if(!e)return;let n=r$("stage"),s=tl(n)?n:tl(t.stage)?t.stage:ti;m({bridgeUrl:t.bridgeUrl,stage:s,companion:t.companion,companionEpisode:t.companionEpisode})}),()=>{e=!1}},[]);let[p,f]=(0,l.useState)(()=>"1"===rF(rq)),[g,x]=(0,l.useState)(()=>rF(rB)),y=(0,l.useMemo)(()=>p?sw():null,[p]),b=(0,l.useMemo)(()=>(function(e={}){let t=window,n=t.SpeechRecognition??t.webkitSpeechRecognition;if(!n)return null;let s=null;return{start(t,r){s?.stop();let a=new n;s=a,a.lang=e.lang??("u">typeof navigator?navigator.language:"en-US"),a.continuous=!0,a.interimResults=!0;let i="";a.onresult=e=>{let n="";for(let t=e.resultIndex;t<e.results.length;t++){let s=e.results[t],r=s[0]?.transcript??"";s.isFinal?i+=r:n+=r}t((i+n).trim(),""===n)},a.onerror=e=>r?.(e.error??"error"),a.onend=()=>{s===a&&(s=null),r?.()},a.start()},stop(){s?.stop(),s=null}}})(),[]),[v,w]=(0,l.useState)(null),j=(0,l.useRef)(new Set),k=(0,l.useCallback)(e=>{if(!e)return void w(null);let{step:t}=e,n=(0,s1.requestedDoc)();if(e.caught&&r$("doc"))return void w({doc:t.doc,focus:t.focus,spotlight:t.spotlight,region:t.region,nonce:e.nonce});if(t.doc&&t.doc!==n)rS({doc:t.doc,system:t.system??void 0,focus:t.focus??null});else if(t.focus)if(t.system&&r$("system")!==t.system&&n)rS({doc:n,system:t.system,focus:t.focus});else{var s;let e;s=t.focus,(e=new URL(window.location.href)).searchParams.set("focus",s),window.history.replaceState(window.history.state,"",e),window.dispatchEvent(new Event(rw))}w({doc:t.doc,focus:t.focus,spotlight:t.spotlight,region:t.region,nonce:e.nonce})},[]),$=(t={url:u.bridgeUrl??"",stage:u.stage,name:"web-stage",voice:y,enabled:!!u.bridgeUrl,onShow:k,onMarks:e=>{for(let t of[...j.current])t(e)}},(n=(0,l.useRef)({onShow:t.onShow,onMarks:t.onMarks})).current={onShow:t.onShow,onMarks:t.onMarks},s=(0,l.useRef)(null),r=`${t.url}\u0000${t.stage??""}\u0000${t.token??""}`,a=(0,l.useRef)(r),(null===s.current||a.current!==r)&&(a.current=r,s.current=function(e){let t,n=tl(e.stage)?e.stage:ti,s=e.setTimer??((e,t)=>setTimeout(e,t)),r=e.clearTimer??(e=>clearTimeout(e)),a=e.gapMs??900,i=e.client??sy({url:e.url,role:e.role??"web",docId:`stage:${n}`,name:e.name??"web-stage",token:e.token,autoResync:!1}),o=e.voice??null,l=e=>e&&void 0!==t?t:o,c=null,d=null,h=e=>{let t=d;d=null,t?.(e)},u=null,m=null,p=[],f=[],g=0,x=!1,y=!1,b=0,v=null,w=0,j=!1,k=!1,$=!1,N=!1,S=!1,M={status:i.status,stage:n,shown:u,tour:m,index:g,playing:x,speaking:y,ownVoice:!1},C=new Set;function E(){for(let e of(M={status:i.status,stage:n,shown:u,tour:m,index:g,playing:x,speaking:y,ownVoice:!!m&&void 0!==t},[...C]))e()}function R(){w+=1,v&&r(v),v=null,y&&c?.cancel(),y=!1,c=null}function _(e,t,n=t){R();let r=++w,i=()=>{r!==w||(y&&(y=!1,E()),t&&x&&(v=s(()=>{v=null,r===w&&x&&L()},o?a:0)))},o=l(n);o?(y=!0,c=o,E(),o.speak(e).then(i,i)):t&&(v=s(()=>{v=null,i()},tg(e)))}function A(t,n){b+=1,R(),u=t?{...t,nonce:b,...S?{caught:!0}:{}}:null,E(),e.onShow?.(u);let s=!!u&&null!==u.index;u&&(l(s)||n)&&_(u.step,n,s)}function T(e){if(!m)return null;let t=m.def.steps[e];if(!t)return null;let n=t.doc??p[e],s=t.system??f[e];return{step:{...t,...n?{doc:n}:{},...s?{system:s}:{}},index:e,count:m.def.steps.length,title:m.def.settings?.name,origin:m.origin,tourPath:m.path}}function O(e,n,s){var r;let a,i;h(!1),t=s;let o=Array.isArray(e.tour?.steps)?e.tour.steps:[];r=(m={def:{...e.tour,steps:o},path:e.path,origin:e.origin}).def,i=void 0,p=r.steps.map(e=>i=e.doc??i),f=o.map(e=>a=e.system??a),g=Math.min(Math.max(0,e.from??0),Math.max(0,o.length-1)),j=!1,x=n&&o.length>0,A(T(g),x)}function P(e){x=!1,A({step:e.step,index:null,count:null,title:e.title,origin:e.origin,tourPath:e.tour},!1)}function I(e){if(!m)return;let t=m.def.steps.length-1;t<0||(j=!1,A(T(g=Math.min(Math.max(0,Math.floor(e)),t)),x))}function L(){if(m){if(g>=m.def.steps.length-1){let e=x;j=x||j,x=!1,R(),E(),e&&h(!0);return}I(g+1)}}function D(){m&&g>0&&I(g-1)}function q(){m&&m.def.steps.length&&(x=!0,j&&(j=!1,g=0),u?.index!==g||u.caught?A(T(g),!0):(E(),_(u.step,!0)))}function B(){x=!1,R(),E()}function F(){h(!1),t=void 0,j=!1,m=null,p=[],f=[],g=0,x=!1,A(null,!1)}function U(){N||(N=!0,i.joinStage(n).then(({state:e})=>{N=!1,$=!0,u||m||function(e){S=!0;try{e.tour&&O(e.tour,!1),e.step&&P(e.step)}finally{S=!1}}(e),E()}).catch(()=>{N=!1,E()}))}return i.on("stage-step",e=>{e?.stage===n&&e.step&&P(e)}),i.on("stage-load",e=>{e?.stage===n&&e.tour&&O(e,!1!==e.autoplay)}),i.on("stage-control",e=>{e?.stage===n&&function(e){switch(e.action){case"play":return q();case"pause":return B();case"next":return L();case"prev":return D();case"goto":return I(e.index??0);case"stop":return F()}}(e)}),i.on("marks",t=>e.onMarks?.(t)),i.on("status",e=>{"disconnected"===e||"error"===e?$=!1:"connected"===e&&k&&!$&&U(),E()}),{getSnapshot:()=>M,subscribe:e=>(C.add(e),()=>{C.delete(e)}),connect(){k=!0,U()},disconnect(){k=!1,R(),i.leaveStage(n),i.disconnect()},play:q,pause:B,next:L,prev:D,goto:I,stop:F,dismiss:function(){if(u){if(null===u.index&&m)return void A(T(g),!1);null===u.index?A(null,!1):F()}},setVoice(e){void 0===t&&R(),o=e,E()},present:(e,t={})=>Array.isArray(e?.steps)&&e.steps.length?new Promise(s=>{O({stage:n,tour:e,from:t.from??0,autoplay:!1!==t.autoplay,origin:t.origin??"page"},!1!==t.autoplay,t.voice),d=s}):Promise.resolve(!1),sendContext(e){i.emitContext({...e,stage:n,...m?{tour:{path:m.path,title:m.def.settings?.name,index:g,count:m.def.steps.length,playing:x}}:{}})},sendMarks(e){i.emitMarks({...e,stage:n}).catch(()=>{})}}}({...t,voice:t.voice??null,onShow:e=>n.current.onShow?.(e),onMarks:e=>n.current.onMarks?.(e)})),i=s.current,c=(0,l.useSyncExternalStore)(i.subscribe,i.getSnapshot,i.getSnapshot),d=!1!==t.enabled&&!!t.url,(0,l.useEffect)(()=>{if(d)return i.connect(),()=>i.disconnect()},[i,d]),h=t.voice??null,(0,l.useEffect)(()=>{i.setVoice(h)},[i,h]),{...c,play:i.play,pause:i.pause,next:i.next,prev:i.prev,goto:i.goto,stop:i.stop,dismiss:i.dismiss,sendContext:i.sendContext,sendMarks:i.sendMarks,present:i.present}),N=(0,l.useRef)(null),S=(0,l.useRef)(null),M=$.sendContext,C=(0,l.useCallback)(e=>{N.current={...e,stage:u.stage,who:g||void 0,at:new Date().toISOString()},S.current&&clearTimeout(S.current),S.current=setTimeout(()=>M({...e,who:g||void 0}),400)},[u.stage,g,M]);(0,l.useEffect)(()=>()=>{S.current&&clearTimeout(S.current)},[]),(0,l.useEffect)(()=>{N.current&&M({...N.current,who:g||void 0})},[$.index,$.playing,$.tour,M,g]);let[E,R]=(0,l.useState)(0),_=!!$.shown;(0,l.useEffect)(()=>{let e=document.documentElement,t=_?document.querySelector(".stage-caption-host .slc-stage-caption"):null;if(!t||"u"<typeof ResizeObserver)return void e.style.removeProperty("--stage-caption-h");let n=()=>e.style.setProperty("--stage-caption-h",`${Math.ceil(t.getBoundingClientRect().height)+12}px`),s=new ResizeObserver(n);return s.observe(t),n(),()=>{s.disconnect(),e.style.removeProperty("--stage-caption-h")}},[_]);let A=(0,l.useMemo)(()=>({stage:u.stage,connected:"connected"===$.status,lit:v,author:g,setAuthor:e=>{x(e),rU(rB,e)},listener:b,answerNonce:E,report:C,lastReport:()=>N.current,sendMarks:$.sendMarks,onMarks:e=>(j.current.add(e),()=>{j.current.delete(e)}),shown:$.shown,present:$.present,pause:$.pause,stop:$.stop}),[u.stage,$.status,$.shown,$.sendMarks,$.present,$.pause,$.stop,v,g,b,E,C]);return(0,o.jsxs)(rL.Provider,{value:A,children:[e,$.shown&&(0,o.jsx)("div",{className:"stage-caption-host",children:(0,o.jsx)(t7,{shown:$.shown,playing:$.playing,speaking:$.speaking,voice:$.ownVoice?void 0:p,onToggleVoice:()=>{let e=!p;f(e),rU(rq,e?"1":"0")},onPlay:$.play,onPause:$.pause,onNext:$.next,onPrev:$.prev,onGoto:$.goto,onClose:$.dismiss,onAnswer:()=>R(e=>e+1)})}),u.companion&&(0,o.jsx)(rI,{stage:A,defaultEpisode:u.companionEpisode})]})}let rY="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 rH(e,t){let n=await fetch(`/api/marks?doc=${encodeURIComponent(e)}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),s=await n.json().catch(()=>({}));if(!n.ok)throw Error(s?.error??`the marks could not be written (${n.status})`);return s}function rX({docPath:e,kind:t,viewport:n,setViewport:s,boxes:r,boardRef:a,focus:i=null,level:c,onReveal:d}){let h=rD(),[u,m]=(0,l.useState)([]),[p,f]=(0,l.useState)(!1),[g,x]=(0,l.useState)(null),[y,b]=(0,l.useState)(null),[v,w]=(0,l.useState)(!1),[j,k]=(0,l.useState)(!1),[$,N]=(0,l.useState)(null),[S,M]=(0,l.useState)(!1),C=(0,l.useCallback)(()=>{e&&fetch(`/api/marks?doc=${encodeURIComponent(e)}`,{cache:"no-store"}).then(e=>e.ok?e.json():null).then(e=>e&&Array.isArray(e.marks)&&m(e.marks)).catch(()=>{})},[e]);(0,l.useEffect)(()=>(m([]),b(null),x(null),C(),window.addEventListener("focus",C),()=>window.removeEventListener("focus",C)),[C]),(0,l.useEffect)(()=>h?.onMarks(t=>{e&&t.docId===e&&Array.isArray(t.marks)&&m(t.marks)}),[h,e]);let E=async t=>{if(!e)return!1;k(!0),N(null);try{let n=await rH(e,t);return m(n.marks),h?.sendMarks({docId:e,marks:n.marks,change:n.change}),!0}catch(e){return N(e instanceof Error?e.message:String(e)),!1}finally{k(!1)}},R=h?.lit??null,_=R&&(!R.doc||R.doc===e)?R:null,A=_?.spotlight,T=_?.region??null,O=(0,l.useRef)(-1),P=(0,l.useRef)(-1),I=(0,l.useRef)(null),L=(0,l.useMemo)(()=>A?.length?tb(r,A):[],[r,A]);(0,l.useEffect)(()=>{if(!_||O.current===_.nonce)return;let e=[...L,...T?[T]:[]];if(!e.length){A?.length&&P.current!==_.nonce&&(P.current=_.nonce,d?.(A));return}O.current=_.nonce;let t=()=>{let t=a.current?.getBoundingClientRect();if(!t?.width)return;let n=document.querySelector(".stage-caption-host .slc-stage-caption")?.getBoundingClientRect(),r=n&&n.top<t.bottom?Math.max(0,t.bottom-n.top+8):0,i=Math.max(.4*t.height,t.height-r);s(H(e,t.width,i,{padding:48,maxScale:1}))};t(),I.current&&clearTimeout(I.current),I.current=setTimeout(t,520)},[_,L,T,A,a,s,d]),(0,l.useEffect)(()=>()=>{I.current&&clearTimeout(I.current)},[]);let D=(0,l.useRef)(h?.answerNonce??0);(0,l.useEffect)(()=>{if(!h||h.answerNonce===D.current)return;D.current=h.answerNonce;let e=A?.length?[...A]:_?.focus?[_.focus]:i?[i]:[];w(!1),b(null),x({elements:e,region:T??void 0,listen:!!h.listener})},[h,A,_,i,T]);let q=h?.report;if((0,l.useEffect)(()=>{if(!q||!e)return;let s=a.current?.getBoundingClientRect(),r=F(n,{x:0,y:0}),o=s?F(n,{x:s.width,y:s.height}):r;q({doc:e,kind:t,system:r$("system")??void 0,focus:i,...s?.width?{visible:{x:Math.round(r.x),y:Math.round(r.y),width:Math.round(o.x-r.x),height:Math.round(o.y-r.y)}}:{}})},[q,e,t,i,n,a]),!e)return null;let B=u.filter(e=>"open"===e.status&&"person"===e.author.role).length,U=u.filter(e=>"open"===e.status&&"agent"===e.author.role).length,z=u.find(e=>e.id===y)??null;return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(tV,{viewport:n,boxes:r,spotlight:A,region:T,marks:u,selectedMark:y,onSelectMark:e=>{x(null),w(!1),b(t=>t===e?null:e)},marking:p,onDraft:e=>{f(!1),b(null),w(!1),x(e)},draft:g}),(0,o.jsxs)("div",{className:"stage-board-controls",children:[(0,o.jsxs)("button",{type:"button",className:`${rY} ${p?"!border-amber-400 !text-amber-300":""}`,"aria-pressed":p,onClick:()=>{x(null),f(e=>!e)},title:p?"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,o.jsx)(t8,{}),p&&(0,o.jsx)("span",{className:"text-xs",children:"marking"})]}),(0,o.jsxs)("button",{type:"button",className:rY,"aria-expanded":v,onClick:()=>{x(null),b(null),w(e=>!e)},title:"Marks on this drawing",children:[(0,o.jsx)(tG,{}),B+U>0&&(0,o.jsx)("span",{className:"text-xs text-amber-300",children:B+U})]})]}),p&&!g&&(0,o.jsx)("div",{className:"stage-board-hint",role:"status",children:"Tap an element, or drag around several, to say something about it."}),(g||z||v)&&(0,o.jsx)("div",{className:"stage-board-card",children:g?(0,o.jsx)(nn,{elements:g.elements,region:g.region,author:h?.author??"",onAuthorChange:h?.setAuthor,listener:h?.listener,listenAtOnce:!!g.listen,busy:j,error:$,onCancel:()=>{x(null),N(null)},onSubmit:async({text:e,kind:t,author:n})=>{await E({action:"add",mark:{text:e,kind:t,elements:g.elements,region:g.region,level:c,author:{name:n||"someone"}}})&&x(null)}},`${g.elements.join(",")}|${g.region?JSON.stringify(g.region):""}`):z?(0,o.jsx)(ns,{mark:z,number:u.indexOf(z)+1,listener:h?.listener,busy:j,error:$,onClose:()=>b(null),onReply:e=>void E({action:"reply",id:z.id,text:e,author:{name:h?.author||"someone"}}),onResolve:()=>void E({action:"resolve",id:z.id}),onReopen:()=>void E({action:"reopen",id:z.id}),onRemove:async()=>{await E({action:"remove",id:z.id})&&b(null)}}):(0,o.jsx)(nr,{marks:u,selected:y,onSelect:e=>{w(!1),b(e)},onCopy:()=>{var t,n;let s,r;if(!e)return;let a=(t=h?.lastReport()??null,s=(n=[{doc:e,marks:u.filter(e=>"resolved"!==e.status)}]).reduce((e,t)=>e+t.marks.length,0),r=function(e){if(!e||!e.doc)return"No canvas has said what it is showing.";let t=[`${e.who?`${e.who} is`:"The canvas is"} on ${tv(e.doc)}${e.kind?` (${e.kind})`:""}`];e.system&&t.push(`as a member of ${tv(e.system)}`),e.focus&&t.push(`with ${e.focus} in hand`);let n=t.join(", ")+".";return e.tour&&(n+=` Tour ${e.tour.title?`'${e.tour.title}' `:""}at step ${e.tour.index+1} of ${e.tour.count}, ${e.tour.playing?"playing":"paused"}.`),e.at&&(n+=` (reported ${e.at})`),n}(t),s?`${r}
10
+ ${e}`)}h(!0)};return(0,o.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,o.jsxs)("div",{className:"toolbar-ident",children:[(0,o.jsx)("input",{ref:S,type:"file",accept:".json,.smdf.json",onChange:e=>{let t=e.target.files?.[0];if(!t)return;let n=new FileReader;n.onload=e=>{r(e.target?.result,t.name)},n.readAsText(t),e.target.value=""},className:"hidden"}),(0,o.jsxs)("span",{className:"text-xs text-gray-400 mr-1 truncate max-w-[50vw] md:max-w-none",children:[t??"untitled.smdf.json",s&&(0,o.jsx)("span",{className:"text-yellow-500 ml-0.5",children:"●"})]}),(0,o.jsx)(s2,{}),"synced"===v&&(0,o.jsx)("span",{className:"text-[10px] text-emerald-500",title:"In sync with disk",children:"⌁ synced"}),"remote-changed"===v&&(0,o.jsx)("span",{className:"text-[10px] text-amber-400",title:w??"",children:"↻ remote changed"}),"error"===v&&(0,o.jsx)("span",{className:"text-[10px] text-red-400",title:w??"",children:"⚠ disk error"}),"idle"===v&&(0,o.jsx)("span",{className:"text-[10px] text-gray-600",title:w??"No file bound",children:"○ no disk"}),(0,o.jsx)(s5,{}),(0,o.jsx)("div",{className:"flex-1"})]}),(0,o.jsxs)("div",{className:"toolbar-strip",children:[(0,o.jsx)("button",{onClick:g,disabled:0===y.length,className:"toolbar-btn disabled:opacity-30",title:"Undo (Ctrl+Z)",children:"↩"}),(0,o.jsx)("button",{onClick:x,disabled:0===b.length,className:"toolbar-btn disabled:opacity-30",title:"Redo (Ctrl+Y)",children:"↪"}),(0,o.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,o.jsx)("button",{onClick:f,className:"toolbar-btn",title:"Arrange states into layers (auto-layout)",children:"⤢ Arrange"}),(0,o.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,o.jsx)("button",{onClick:()=>p("select"===m?"transition":"select"),className:`toolbar-btn ${"transition"===m?"!bg-amber-700 !text-white":""}`,title:"transition"===m?"Exit draw mode (Esc)":"Draw transition mode",children:"transition"===m?"✏️ Drawing":"↗ Draw"}),(0,o.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,o.jsx)("button",{onClick:()=>S.current?.click(),className:"toolbar-btn",title:"Open local .smdf.json (browser)",children:"📂"}),(0,o.jsx)("button",{onClick:F,disabled:_,className:"toolbar-btn disabled:opacity-40",title:"Save to disk (STATELOOM_PROJECT_FILE)",children:"💾 Disk"}),(0,o.jsx)("button",{onClick:z,className:"toolbar-btn",title:"Reload from disk",children:"🔄"}),(0,o.jsx)("button",{onClick:()=>{let e=new Blob([a()],{type:"application/json"}),n=URL.createObjectURL(e),s=document.createElement("a");s.href=n,s.download=t??"statemachine.smdf.json",s.click(),URL.revokeObjectURL(n)},className:"toolbar-btn",title:"Download as file",children:"📥"}),(0,o.jsx)("select",{value:T,onChange:e=>{O(e.target.value),B(null),D(null)},className:"bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 px-1 py-0.5",title:"Export format",children:sF.map(e=>(0,o.jsx)("option",{value:e,children:sU[e]},e))}),(0,o.jsx)("button",{onClick:U,disabled:P,className:`toolbar-btn disabled:opacity-40 ${L?"!text-red-400":""}`,title:L??`Export the board as ${sU[T]}`,children:P?"…":"🖼 Export"}),q&&!L&&(0,o.jsxs)("span",{className:"text-[10px] text-emerald-500 truncate max-w-[40vw] md:max-w-[16rem]",title:q,children:["⤓ ",q]}),(0,o.jsx)("div",{className:"w-px h-4 bg-gray-700"}),M?(0,o.jsxs)("div",{className:"flex items-center gap-1",children:[(0,o.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:E,onChange:e=>R(e.target.value),onKeyDown:e=>{"Enter"===e.key&&Y(),"Escape"===e.key&&C(!1)}}),(0,o.jsx)("button",{onClick:Y,className:"toolbar-btn-sm",children:"✓"}),(0,o.jsx)("button",{onClick:()=>C(!1),className:"toolbar-btn-sm",children:"✕"})]}):(0,o.jsx)("button",{onClick:()=>C(!0),className:"toolbar-btn",children:"+State"}),(0,o.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,o.jsx)("button",{onClick:()=>c(),className:"toolbar-btn",children:"✓ Validate"}),(0,o.jsxs)("select",{value:H,onChange:e=>X(e.target.value),className:"bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 px-1 py-0.5",children:[(0,o.jsx)("option",{value:"python",children:"Python"}),(0,o.jsx)("option",{value:"typescript",children:"TypeScript"})]}),(0,o.jsx)("button",{onClick:J,className:"toolbar-btn",children:"⚡ Generate"}),(0,o.jsx)("button",{onClick:V,className:"toolbar-btn",title:"Generate RISE rispec markdown",children:"📜 RISE"}),(0,o.jsxs)("button",{onClick:()=>h(!d),className:`toolbar-btn ${d?"text-blue-400":""}`,children:["</>"," Code"]})]})]})}function s3(){let e=sP(e=>e.generatedCode),t=sP(e=>e.showCodePreview),n=sP(e=>e.setShowCodePreview);return t?(0,o.jsx)("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/60 p-2 md:p-0",children:(0,o.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,o.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-800",children:[(0,o.jsx)("h3",{className:"text-sm font-semibold text-gray-300",children:"Generated Definition (JSON)"}),(0,o.jsx)("button",{onClick:()=>n(!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,o.jsx)("pre",{className:"flex-1 overflow-auto overscroll-contain p-4 text-[11px] leading-relaxed text-green-400 font-mono md:text-sm",children:e??"No code generated yet"}),(0,o.jsx)("div",{className:"flex justify-end px-4 py-2 border-t border-gray-800",children:(0,o.jsx)("button",{onClick:()=>{e&&navigator.clipboard.writeText(e)},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 s6(){let e=sP(e=>e.applyRemote),t=sP(e=>e.setRemoteStatus),n=sP(e=>e.setRemoteMtime),s=(0,s1.useRequestedDoc)();return(0,l.useEffect)(()=>{let r=!1,a=(0,s1.docQuery)(s);async function i(){try{let e=await fetch(`/api/file${a}`,{cache:"no-store"});if(!e.ok)return null;return await e.json()}catch{return null}}(async()=>{let n=await i();r||(n?.path&&sP.getState().setDocPath(n.path),n?.exists&&n.content?e(n.content,n.mtime,n.path.split("/").pop()):t("idle",n?`No file at ${n.path}`:null))})();let o=new EventSource(`/api/watch${a}`);return o.addEventListener("hello",e=>{try{let t=JSON.parse(e.data);"number"==typeof t?.mtime&&n(t.mtime)}catch{}}),o.addEventListener("change",async s=>{let r=0;try{r=JSON.parse(s.data)?.mtime??0}catch{}if(r<=(sP.getState().remoteMtime??0))return;let a=await i();a?.exists&&a.content&&(sP.getState().dirty?(t("remote-changed",`Disk changed at ${new Date(a.mtime).toLocaleTimeString()} — local has unsaved edits`),n(a.mtime)):e(a.content,a.mtime,a.path.split("/").pop()))}),o.addEventListener("error",()=>{t("error","Watch stream disconnected")}),()=>{r=!0,o.close()}},[e,t,n,s]),null}function s8({url:e}){let t=(0,s1.useRequestedDoc)();return(0,l.useEffect)(()=>{if(!e)return;let n=!1,s=null,r=null,a=null,i=null;return(async()=>{let o="";try{let e=await fetch(`/api/file${(0,s1.docQuery)(t)}`,{cache:"no-store"});e.ok&&(o=(await e.json())?.path??"")}catch{}n||(o&&sP.getState().setDocPath(o),(s=sv({url:e,role:"web",docId:o,name:"web-designer",onFull:e=>{sP.getState().applyRemote(JSON.stringify({stateMachine:e.def}),e.mtime??Date.now(),o&&o.split("/").pop()||void 0),i=e.def},onPatch:e=>{sP.getState().applyRemoteOps(e.ops,e.mtime??Date.now(),e.seq),i=sP.getState().definition},onPresence:e=>{sP.getState().setPresence(e)}})).connect(),r=sP.subscribe((e,t)=>{e.definition===t.definition||e._applyingRemote||(a&&clearTimeout(a),a=setTimeout(()=>{var e,t;let n,r;if(!s||"connected"!==s.getSnapshot().status)return;let a=sP.getState().definition;if(null===i){s.emitFull(a),i=a;return}let o=(e=i,t=a,n=e??{settings:{namespace:"",asynchronous:!1},events:[],state:{name:t.state.name,states:[]}},function(e,t,n){let s={},r=!1,a=new Set([...Object.keys(e.settings),...Object.keys(t.settings)]),i=e.settings,o=t.settings;for(let e of a)g(i[e],o[e])||void 0===o[e]||(s[e]=o[e],r=!0);void 0!==e.settings.notes&&void 0===t.settings.notes&&(s.notes="",r=!0),r&&n.push({op:"settings.update",patch:s})}(n,t,r=[]),function(e,t,n){let s=e.events,r=t.events,a=Math.min(s.length,r.length);for(let e=0;e<a;e++)!function(e,t,n,s){let r={},a=!1;for(let e of["name","file","feeder","description","timers"])g(t[e],n[e])||void 0===n[e]||(r[e]=n[e],a=!0);a&&s.push({op:"eventSource.update",index:e,patch:r});let i=t.events??[],o=n.events??[],l=new Set(o.map(e=>e.id));for(let e of i)l.has(e.id)||s.push({op:"event.remove",id:e.id});let c=i.filter(e=>l.has(e.id)),d=0;for(;d<o.length;){let t=o[d];d<c.length&&c[d].id===t.id?(function(e,t,n){let s={},r=!1;for(let n of["name","description","preAction","postAction"])g(e[n],t[n])||void 0===t[n]||(s[n]=t[n],r=!0);r&&n.push({op:"event.update",id:t.id,patch:s})}(c[d],t,s),function(e,t,n,s){let r=Math.min(t.length,n.length);for(let a=0;a<r;a++)if(!g(t[a],n[a])){let r={};t[a].name!==n[a].name&&(r.name=n[a].name),t[a].type!==n[a].type&&(r.type=n[a].type),s.push({op:"parameter.update",eventId:e,index:a,patch:r})}for(let t=r;t<n.length;t++)s.push({op:"parameter.add",eventId:e,parameter:n[t],index:t});for(let r=t.length-1;r>=n.length;r--)s.push({op:"parameter.remove",eventId:e,index:r})}(t.id,c[d].parameters??[],t.parameters??[],s)):(s.push({op:"event.add",sourceIndex:e,event:t,index:d}),c.splice(d,0,t)),d++}}(e,s[e],r[e],n);for(let e=s.length;e<r.length;e++)n.push({op:"eventSource.add",source:r[e]});for(let e=s.length-1;e>=r.length;e--)n.push({op:"eventSource.remove",index:e})}(n,t,r),function(e,t,n){let s=p(e.state),r=p(t.state),a=new Map(s.map(e=>[e.name,e])),i=new Map(r.map(e=>[e.name,e])),o=f(e.state),l=f(t.state),c=[];for(let e of r){if(a.has(e.name))continue;let t=l.get(e.name)??null,{states:s,transitions:r,...i}=e;n.push({op:"state.add",parent:t,state:{...i}}),r&&r.length>0&&c.push({state:e.name,transitions:r})}for(let e of r){if(!a.has(e.name))continue;let t=o.get(e.name)??null,s=l.get(e.name)??null;t!==s&&null!==s&&n.push({op:"state.nest",child:e.name,newParent:s})}for(let e of r){let t=a.get(e.name);if(!t)continue;let s={},r=!1;g(t.kind,e.kind)||void 0===e.kind||(s.kind=e.kind,r=!0),g(t.description,e.description)||void 0===e.description||(s.description=e.description,r=!0),g(t.notes,e.notes)||(s.notes=e.notes??"",r=!0),g(t.prompt,e.prompt)||(s.prompt=e.prompt??"",r=!0),r&&n.push({op:"state.update",name:e.name,patch:s}),x(e.name,"onEntry",t.onEntry?.actions??[],e.onEntry?.actions??[],n),x(e.name,"onExit",t.onExit?.actions??[],e.onExit?.actions??[],n)}for(let e of c)e.transitions.forEach((t,s)=>{n.push({op:"transition.add",state:e.state,transition:t,index:s})});for(let e of r){let t=a.get(e.name);t&&function(e,t,n,s){let r=Math.min(t.length,n.length);for(let a=0;a<r;a++){if(g(t[a],n[a]))continue;let r={};for(let e of["event","nextState","condition","description","actions"])g(t[a][e],n[a][e])||void 0===n[a][e]||(r[e]=n[a][e]);Object.keys(r).length>0&&s.push({op:"transition.update",state:e,index:a,patch:r})}for(let t=r;t<n.length;t++)s.push({op:"transition.add",state:e,transition:n[t],index:t});for(let r=t.length-1;r>=n.length;r--)s.push({op:"transition.remove",state:e,index:r})}(e.name,t.transitions??[],e.transitions??[],n)}for(let e=s.length-1;e>=0;e--){let t=s[e];if(i.has(t.name))continue;let r=t.transitions??[];for(let e=r.length-1;e>=0;e--)n.push({op:"transition.remove",state:t.name,index:e});n.push({op:"state.remove",name:t.name})}}(n,t,r),r);0!==o.length&&(s.emitPatch(o),i=a)},60))}))})(),()=>{n=!0,a&&clearTimeout(a),r&&r(),s&&s.disconnect()}},[e,t]),null}function s7(){let e=b.default.env.NEXT_PUBLIC_STATELOOM_BRIDGE_URL??b.default.env.NEXT_PUBLIC_SMCRAFT_BRIDGE_URL;return"string"==typeof e&&e.length>0?e:void 0}let s9=null;function re(){return s9||(s9=(async()=>{let e=s7()??null;try{let t=await fetch("/api/config",{cache:"no-store"});if(t.ok){let n=await t.json();return{bridgeUrl:n.bridgeUrl||e,projectFile:n.projectFile??null,stage:n.stage??null,companion:!0===n.companion,companionEpisode:n.companionEpisode??null}}}catch{}return{bridgeUrl:e,projectFile:null,stage:null,companion:!1,companionEpisode:null}})())}function rt(){let e=s7(),[t,n]=(0,l.useState)(e);return((0,l.useEffect)(()=>{let e=!0;return re().then(t=>{e&&t.bridgeUrl&&n(t.bridgeUrl)}),()=>{e=!1}},[]),"string"==typeof t&&t.length>0)?(0,o.jsx)(s8,{url:t}):(0,o.jsx)(s6,{})}let rn="stateloom.uiScale.v1";function rs(e){return Number.isFinite(e)?Math.min(1.75,Math.max(.75,e)):1}function rr(e){"u">typeof document&&(document.documentElement.style.fontSize=`${16*rs(e)}px`)}let ra=1,ri=!1,ro=new Set;function rl(){return ri||(ri=!0,ra=function(){try{let e=window.localStorage.getItem(rn);if(null===e)return 1;return rs(Number.parseFloat(e))}catch{return 1}}()),ra}function rc(){return 1}function rd(e){return ro.add(e),()=>{ro.delete(e)}}function rh(e,t){let n=rs(e);if(rr(n),t&&function(e){try{window.localStorage.setItem(rn,String(rs(e)))}catch{}}(n),ri=!0,n!==ra)for(let e of(ra=n,ro))e()}function ru(e,t){return Math.max(1,Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY))}function rm(e,t){for(let n=0;n<e.length;n++)if(e[n].identifier===t)return e[n];return null}function rp(){let e=(0,l.useSyncExternalStore)(rd,rl,rc),t=(0,l.useRef)(null),n=(0,l.useRef)(null),s=(0,l.useRef)(null);(0,l.useEffect)(()=>{rr(e)},[e]);let r=(0,l.useCallback)(e=>{n.current=e,null===s.current&&(s.current=requestAnimationFrame(()=>{s.current=null,null!==n.current&&rh(n.current,!1)}))},[]),a=(0,l.useCallback)(()=>{n.current=null,rh(1,!0)},[]);return((0,l.useEffect)(()=>{let e=()=>{let e=t.current;if(t.current=null,!e?.engaged)return;null!==s.current&&(cancelAnimationFrame(s.current),s.current=null);let r=n.current??rl();n.current=null,rh(rs(r),!0)},a=n=>{if(2!==n.touches.length){t.current&&e();return}let[s,r]=[n.touches[0],n.touches[1]];sD(s.target)||sD(r.target)||(t.current={a:s.identifier,b:r.identifier,startScale:rl(),startDist:ru(s,r),engaged:!1})},i=e=>{let n=t.current;if(!n)return;let s=rm(e.touches,n.a),a=rm(e.touches,n.b);if(!s||!a)return;e.preventDefault();let i=ru(s,a);if(!n.engaged){if(12>Math.abs(i-n.startDist))return;n.engaged=!0,n.startDist=i;return}r(rs(n.startScale*(i/n.startDist)))},o=n=>{let s=t.current;s&&(rm(n.touches,s.a)&&rm(n.touches,s.b)||e())};return document.addEventListener("touchstart",a,{passive:!0,capture:!0}),document.addEventListener("touchmove",i,{passive:!1,capture:!0}),document.addEventListener("touchend",o,{passive:!0,capture:!0}),document.addEventListener("touchcancel",o,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",a,{capture:!0}),document.removeEventListener("touchmove",i,{capture:!0}),document.removeEventListener("touchend",o,{capture:!0}),document.removeEventListener("touchcancel",o,{capture:!0}),null!==s.current&&cancelAnimationFrame(s.current)}},[r]),1===e)?null:(0,o.jsxs)("div",{className:"ui-scale-pill",role:"status","aria-live":"polite",children:[(0,o.jsxs)("span",{children:["UI ",Math.round(100*e),"%"]}),(0,o.jsx)("button",{type:"button",onClick:a,"aria-label":"Reset interface size to 100 percent",children:"Reset"})]})}var rf=l;class rg extends rf.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error(`[stateloom] the ${this.props.what} could not be drawn:`,e,t.componentStack)}componentDidUpdate(e){this.state.error&&e.resetKey!==this.props.resetKey&&this.setState({error:null})}render(){let{error:e}=this.state;return e?(0,o.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,o.jsxs)("p",{className:"max-w-md",children:["This ",this.props.what," cannot be drawn: ",e.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 rx({size:e=16}){return(0,o.jsxs)("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,o.jsx)("path",{d:"M12 4.5 21 19.5H3Z"}),(0,o.jsx)("path",{d:"M12 10v4.5"}),(0,o.jsx)("path",{d:"M12 17.3v.01"})]})}function ry({locked:e,size:t=16}){return(0,o.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,o.jsx)("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),(0,o.jsx)("path",{d:e?"M8 11V8a4 4 0 0 1 8 0v3":"M8 11V8a4 4 0 0 1 7.5-1.9"})]})}function rb(e){let{onClose:t,restVh:n,tallVh:s}=e,[r,a]=(0,l.useState)(!1),[i,o]=(0,l.useState)(null),c=(0,l.useRef)(null),d=()=>{a(!1),t()},h=e=>{let t=c.current;if(!t||t.id!==e.pointerId)return;c.current=null;let n=e.clientY-t.y;if(o(null),6>Math.abs(n))return a(e=>!e);if(n<=-50)return a(!0);if(n>=80){if(r&&n<260)return a(!1);d()}},u=r?s:n,m=null!==i;return{zoneProps:{onPointerDown:e=>{e.target.closest("button")||(c.current={y:e.clientY,id:e.pointerId},e.currentTarget.setPointerCapture(e.pointerId),o(0))},onPointerMove:e=>{let t=c.current;t&&t.id===e.pointerId&&o(e.clientY-t.y)},onPointerUp:h,onPointerCancel:h,style:{touchAction:"none",cursor:"grab"}},sheetStyle:{"--sheet-h":m&&i<0?`min(calc(${u}dvh + ${-i}px), ${s}dvh)`:`${u}dvh`,...m?{transition:"none"}:{},...m&&i>0?{transform:`translateY(${i}px)`}:{}},close:d}}let rv="stateloom:focus",rw="stateloom:focus-request",rj="stateloom:system-changed",rk="stateloom:strip-note";function r$(e){return new URLSearchParams(window.location.search).get(e)}function rN(e){let[t,n]=(0,l.useState)(null);return(0,l.useEffect)(()=>{let t=()=>n(r$(e));t();let s=["popstate",s1.DOC_CHANGE_EVENT,rv,rw];for(let e of s)window.addEventListener(e,t);return()=>{for(let e of s)window.removeEventListener(e,t)}},[e]),t}function rS(e){let t=new URL(window.location.href),n=t.searchParams.get("doc")!==e.doc;t.searchParams.set("doc",e.doc);let s=void 0===e.system?t.searchParams.get("system"):e.system;s?t.searchParams.set("system",s):t.searchParams.delete("system"),e.focus?t.searchParams.set("focus",e.focus):t.searchParams.delete("focus"),n?window.history.pushState({},"",t):window.history.replaceState(window.history.state,"",t),n&&window.dispatchEvent(new Event(s1.DOC_CHANGE_EVENT)),window.dispatchEvent(new Event(rw))}function rM(e){let t=new URL(window.location.href);(t.searchParams.get("focus")??null)!==e&&(e?t.searchParams.set("focus",e):t.searchParams.delete("focus"),window.history.replaceState(window.history.state,"",t),window.dispatchEvent(new CustomEvent(rv)))}function rC(){let[e,t]=(0,l.useState)({focus:null,nonce:0});return(0,l.useEffect)(()=>{let e=()=>t(e=>({focus:r$("focus"),nonce:e.nonce+1}));e();let n=["popstate",s1.DOC_CHANGE_EVENT,rw];for(let t of n)window.addEventListener(t,e);return()=>{for(let t of n)window.removeEventListener(t,e)}},[]),e}let rE="/api/companion/",rR="stateloom.companion.autoplay",r_="stateloom.companion.episode",rA=/^\d{4}-\d{2}-\d{2}-episode-\d+-[a-z0-9-]+$/;function rT(e){try{return window.localStorage.getItem(e)}catch{return null}}function rO(e,t){try{window.localStorage.setItem(e,t)}catch{}}let rP=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})},rI=e=>"starting"===e||"recording"===e||"sending"===e,rL={state:"idle",seconds:0,held:0,message:"",error:!1,stored:null},rD={episode:null,items:[],presence:null,waiting:null,error:null};function rq({stage:e,defaultEpisode:t}){let[n,s]=(0,l.useState)(!1),[r,a]=(0,l.useState)(()=>"0"!==rT(rR)),[i,c]=(0,l.useState)(()=>{var e;let n,s=r$("episode"),r=rT(r_);return(s&&rA.test(s)?s:null)??(e=(0,s1.requestedDoc)(),(n=e?.match(/(?:^|\/)(\d{4}-\d{2}-\d{2}-episode-\d+-[a-z0-9-]+)\/diagrams\/[^/]+$/))?n[1]:null)??(r&&rA.test(r)?r:null)??t}),[d,h]=(0,l.useState)([]),[u,m]=(0,l.useState)(rL),[p,f]=(0,l.useState)(rD),[g,x]=(0,l.useState)(null),[y,b]=(0,l.useState)([]),[v,w]=(0,l.useState)(null),[j,k]=(0,l.useState)(null),[$,N]=(0,l.useState)(()=>Date.now()),S=(0,l.useRef)(e),M=(0,l.useRef)(i),C=(0,l.useRef)(r);(0,l.useEffect)(()=>{S.current=e,M.current=i,C.current=r});let E=(0,l.useRef)(rL),R=(0,l.useRef)(null),_=(0,l.useRef)([]),A=(0,l.useRef)(!1),T=(0,l.useRef)([]),O=(0,l.useRef)(null),P=(0,l.useRef)(null),I=(0,l.useMemo)(()=>sw({recordings:!0,speech:!1}),[]),L=e=>{R.current=e,x(e)},D=(0,l.useRef)(async()=>{}),q=(0,l.useCallback)(async(e,t=0)=>{L(e.id),b(t=>t.filter(t=>t!==e.id)),e.steps?.length&&window.matchMedia("(max-width: 767px)").matches&&s(!1);let n=_.current.length;w(n?`${n} more of Mia's replies wait after this one.`:null);let r=await S.current.present(function(e,t,n="Mia"){let s=new Date(e.at),r=Number.isNaN(s.getTime())?`${n}'s reply`:`Reply at ${s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`,a=!e.unvoiced,i=(e,n)=>(function(e,t){if(!t)return;if(/^https?:\/\//.test(t))return t;let n=t.replace(/^\/?api\//,"");return`${e.endsWith("/")?e:`${e}/`}${n}`})(t,e||(a?n:null));return{settings:{namespace:"companion",name:r,author:n},steps:e.steps?.length?e.steps.map(({audio:t,...n},s)=>{let r=i(t,`api/replies/${e.id}/steps/${s}/audio`);return{...n,...r?{audio:r}:{}}}):[{say:e.text,...i(e.audio,`api/replies/${e.id}/audio`)?{audio:i(e.audio,`api/replies/${e.id}/audio`)}:{}}]}}(e,rE,"Mia"),{voice:I,origin:"Mia",from:t});if(R.current!==e.id||(L(null),A.current))return;if(!r){_.current=[];return}let a=_.current.shift();a&&!rI(E.current.state)?D.current(a):a&&_.current.unshift(a)},[I]);(0,l.useEffect)(()=>{D.current=q},[q]);let B=(0,l.useCallback)(e=>{let t=e.id;if(!C.current)return void b(e=>e.includes(t)?e:[...e,t]);if(rI(E.current.state)||R.current){b(e=>e.includes(t)?e:[...e,t]),_.current.some(e=>e.id===t)||_.current.push(e),w(rI(E.current.state)?`Mia replied at ${rP(e.at)}. Her voice waits until you have sent your take.`:`Mia replied again at ${rP(e.at)}. It plays when this one ends.`);return}D.current(e)},[]);(0,l.useEffect)(()=>{let e=function(e){let t=e.base.endsWith("/")?e.base:`${e.base}/`,n=e.fetch??((...e)=>fetch(...e)),s=e.everyMs??1e4,r=e.waitEveryMs??4e3,a=e.waitForMs??9e5,i={episode:null,items:[],presence:null,waiting:null,error:null},o=new Set,l=!1,c=null,d=null,h="",u=0,m=t=>{i={...i,...t},e.onChange?.(i)};async function p(){let s=i.episode;if(!s)return;let r=u;try{let c=await n(`${t}thread?episode=${encodeURIComponent(s)}`,{cache:"no-store"}),p=await c.json();if(r!==u)return;if(!p.success)return m({error:p.error??`HTTP ${c.status}`});let f=p.items??[],g=f.map(e=>"reply"===e.kind?`${e.id}:${+!!e.audio}:${e.feedback??""}`:`${e.take}:${e.text.length}`).join(",")+`|${p.presence?.state}`,x=f.filter(e=>"reply"===e.kind&&!o.has(e.id));for(let e of x)o.add(e.id);if((g!==h||i.error)&&(h=g,m({items:f,presence:p.presence??null,error:null})),l)for(let t of x)e.onReply?.(t);l=!0;let y=i.waiting;y&&(f.some(e=>"reply"===e.kind&&e.take===y.take)||Date.now()-y.since>a)&&(d&&clearInterval(d),d=null,m({waiting:null}))}catch(e){r===u&&m({error:e instanceof Error?e.message:String(e)})}}let f=()=>{"visible"===document.visibilityState&&p()};return"u">typeof document&&document.addEventListener("visibilitychange",f),{getSnapshot:()=>i,setEpisode(e){e!==i.episode&&(u+=1,o.clear(),l=!1,h="",d&&clearInterval(d),d=null,m({episode:e,items:[],presence:null,waiting:null,error:null}),e?(c&&clearInterval(c),c=setInterval(()=>{("u"<typeof document||"visible"===document.visibilityState)&&p()},s),p()):c&&(clearInterval(c),c=null))},refresh:p,waitFor(e){m({waiting:{take:e,since:Date.now()}}),d&&clearInterval(d),d=setInterval(()=>void p(),r),p()},async feedback(e,s){await n(`${t}replies/${e}/feedback`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({value:s})}),h="",await p()},destroy(){for(let e of(u+=1,[c,d]))e&&clearInterval(e);c=d=null,"u">typeof document&&document.removeEventListener("visibilitychange",f)}}}({base:rE,onChange:f,onReply:B}),t=function(e){let t,n=e.base.endsWith("/")?e.base:`${e.base}/`,s=e.fetch??((...e)=>fetch(...e)),r=e.partEveryMs??1e4,a=e.beatEveryMs??15e3,i=(t=window.MediaRecorder)&&sj.some(e=>!t.isTypeSupported||t.isTypeSupported(e))?"mp4":window.AudioContext??window.webkitAudioContext?"wav":null,o=!1!==window.isSecureContext,l=e.getUserMedia??(e=>navigator.mediaDevices.getUserMedia(e)),c=e.createRecorder??(e=>{let t,n,s,r,a,o,l,c;return"mp4"===i?new window.MediaRecorder(e,{mimeType:sj.find(e=>window.MediaRecorder.isTypeSupported?.(e)??!0)}):(n=(t=new(window.AudioContext??window.webkitAudioContext)).createMediaStreamSource(e),s=t.createScriptProcessor(4096,1,1),r=[],a=[],o=!1,l=null,c={mimeType:"audio/wav",ondataavailable:null,onstop:null,onerror:null,start(e=1e3){s.onaudioprocess=e=>{let t=e.inputBuffer.getChannelData(0),n=new Int16Array(t.length);for(let e=0;e<t.length;e++)n[e]=Math.max(-32768,Math.min(32767,Math.round(32767*t[e])));r.push(n),a.push(n)},n.connect(s),s.connect(t.destination),l=setInterval(()=>{if(!a.length)return;let e=o?[]:[sk(0x7fffffff,t.sampleRate)];o=!0,e.push(...a.map(e=>e.buffer)),a=[],c.ondataavailable?.({data:new Blob(e,{type:"audio/wav"})})},e)},stop(){l&&clearInterval(l),l=null;try{n.disconnect(),s.disconnect()}catch{}t.close().catch(()=>{}),c.whole=new Blob([sk(r.reduce((e,t)=>e+t.byteLength,0),t.sampleRate),...r.map(e=>e.buffer)],{type:"audio/wav"}),c.onstop?.()}})}),d={state:"idle",seconds:0,held:0,message:"",error:!1,stored:null,...!e.createRecorder&&(!i||!o)?{unavailable:o?"this browser cannot record audio":"the microphone needs a secure page (https, or this machine's own address)"}:{}},h=t=>{d={...d,...t},e.onChange?.(d)},u=null,m=null,p=[],f="",g="",x=null,y=0,b=null,v=null,w=null,j=null,k=!1,$=()=>y?Math.floor((Date.now()-y)/1e3):0,N=()=>(m?.mimeType||"audio/mp4").split(";")[0]||"audio/mp4",S=(e="")=>`episode=${encodeURIComponent(g)}${f?`&rec=${f}`:""}${x?`&context=${encodeURIComponent(x)}`:""}${e}`;function M(e){g&&s(`${n}recorder`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({episode:g,recording:e})}).catch(()=>{})}function C(e,t={}){f&&s(`${n}takes/diagnostic`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({rec:f,episode:g,kind:e,at:new Date().toISOString(),mime:m?.mimeType??i,visibility:"u">typeof document?document.visibilityState:"",agent:"u">typeof navigator?navigator.userAgent:"",source:"stateloom-canvas",...t}),keepalive:!0}).catch(()=>{})}function E(){for(let e of[v,w,j])e&&clearInterval(e);v=w=j=null}function R(){try{u?.getTracks().forEach(e=>e.stop())}catch{}u=null}async function _(){if(!f||k||!p.length)return;let e=new Blob(p,{type:N()});if(e.size<=d.held)return;k=!0;let t=f;try{let r=await s(`${n}takes/part?${S(`&offset=${d.held}`)}`,{method:"POST",headers:{"content-type":N()},body:e.slice(d.held)}),a=await r.json();t===f&&"number"==typeof a.bytes&&h({held:a.bytes})}catch{}finally{k=!1}}async function A(){let t;if("idle"!==d.state&&"retry"!==d.state)return;if(d.unavailable)return h({message:`Cannot record: ${d.unavailable}.`,error:!0});if(!(g=e.episode()??""))return h({message:"Choose the episode this take belongs to.",error:!0});let n=e.context?.()??null;x=n?JSON.stringify(n).slice(0,4e3):null,b=null,h({state:"starting",message:"",error:!1,held:0,seconds:0}),M(!0);try{t=await l({audio:!0})}catch(e){return M(!1),h({state:"idle",message:`Microphone refused: ${e instanceof Error?e.message:String(e)}`,error:!0})}if("starting"!==d.state)return void t.getTracks().forEach(e=>e.stop());u=t,p=[],f=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;try{m=c(t)}catch(e){return R(),M(!1),h({state:"idle",message:`This browser refused to record: ${e instanceof Error?e.message:String(e)}`,error:!0})}m.ondataavailable=e=>{e.data&&e.data.size&&p.push(e.data)},m.onerror=e=>{let t=$(),n=new Blob(p,{type:N()});if(C("recorder-error",{name:e?.error?.name??"",message:e?.error?.message??"",seconds:t,bytes:n.size,held:d.held}),E(),R(),M(!1),n.size)b=n,h({state:"retry",message:`The recorder stopped with an error after ${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}. What it captured is kept: Send again.${d.held?` ${s$(d.held)} of it is already stored.`:""}`,error:!0});else h({state:"idle",message:"The recorder stopped before it captured anything. Nothing was sent.",error:!0})},m.start(1e3),y=Date.now(),v=setInterval(()=>void _(),r),w=setInterval(()=>M(!0),a),j=setInterval(()=>h({seconds:$()}),500),h({state:"recording",seconds:0,message:""})}async function T(t){h({state:"sending",message:`Sending ${s$(t.size)}, then transcribing and storing…`,error:!1});try{let r=await s(`${n}takes?${S()}`,{method:"POST",headers:{"content-type":(t.type||"audio/mp4").split(";")[0]},body:t}),a=await r.json();if(!a.success||!a.take)throw Error(a.error||`HTTP ${r.status}`);b=null,f="";let i=a.presence??{state:a.listening?"listening":"away"},o=a.transcriptError?` Transcription failed, so no session wakes yet: ${a.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."})[i.state]??" No session is listening yet; the take waits, and her reply comes here when one answers.";h({state:"idle",seconds:0,held:0,message:`Take ${a.take} is in the episode.${o}`,error:!!a.transcriptError,stored:{take:a.take,english:a.english??"",transcriptError:a.transcriptError,presence:i}}),a.transcriptError||e.onStored?.(a.take)}catch(e){b=t,C("send-failed",{message:e instanceof Error?e.message:String(e),bytes:t.size,held:d.held}),h({state:"retry",message:`Not stored: ${e instanceof Error?e.message:String(e)}. Your recording is kept — Send again.${d.held?` ${s$(d.held)} of it is already stored, and becomes a take by itself if you leave.`:""}`,error:!0})}}async function O(){if("recording"!==d.state)return;let e=$();E(),M(!1),h({state:"sending",seconds:e});let t=await new Promise(e=>{let t=!1,n=()=>{t||(t=!0,e(m?.whole??new Blob(p,{type:N()})))},s=setTimeout(n,3e3);if(!m)return n();m.onstop=()=>{clearTimeout(s),n()};try{m.stop()}catch{clearTimeout(s),n()}});if(R(),!t.size)return C("empty-at-stop",{seconds:e,held:d.held}),h({state:"idle",message:d.held?`The recorder handed back nothing at Stop, but ${s$(d.held)} is stored; it becomes a take within a few minutes.`:"Nothing was recorded. Try again.",error:!0});await T(t)}async function P(){"retry"===d.state&&b&&await T(b)}return{getSnapshot:()=>d,press:async()=>"recording"===d.state?O():"retry"===d.state&&b?P():A(),start:A,stop:O,resend:P,destroy(){E(),("recording"===d.state||"starting"===d.state)&&M(!1);try{m?.stop()}catch{}R()}}}({base:rE,episode:()=>M.current,context:()=>{let e=S.current.shown,t=e?{...e.title||e.step.title?{title:[e.title,e.step.title].filter(Boolean).join(" · ")}:{},say:e.step.say.slice(0,400),...null!==e.index&&null!==e.count?{index:e.index,count:e.count}:{},...e.origin?{by:e.origin}:{}}:null;return function(e,t={}){if(!e?.doc)return null;let n={stage:e.stage,doc:e.doc,kind:e.kind,system:e.system,focus:e.focus??void 0,visible:e.visible,tour:e.tour,who:e.who,at:new Date().toISOString(),...t};for(let e of Object.keys(n))(void 0===n[e]||null===n[e])&&delete n[e];return n}(S.current.lastReport(),{...T.current.length?{marks:T.current}:{},...e?.step.spotlight?.length?{spotlight:e.step.spotlight}:{},...t?{step:t}:{}})},onChange:e=>{let t=E.current.state;if(E.current=e,m(e),!rI(t)||rI(e.state)||(A.current=!1,!C.current||R.current))return;let n=_.current.shift();n?D.current(n):w(null)},onStored:t=>e.waitFor(t)});return P.current=e,O.current=t,E.current=t.getSnapshot(),m(t.getSnapshot()),()=>{t.destroy(),e.destroy(),P.current=null,O.current=null}},[B]),(0,l.useEffect)(()=>{P.current?.setEpisode(i)},[i]),(0,l.useEffect)(()=>{let e=!0;return fetch(`${rE}health`,{cache:"no-store"}).then(e=>e.json()).then(t=>{if(e){if(!t.success)return k(`The companion does not answer: ${t.error??"no reason given"}.`);k(null),t.defaultEpisode&&c(e=>e??t.defaultEpisode??null)}}).catch(t=>e&&k(`The companion does not answer: ${t instanceof Error?t.message:String(t)}.`)),()=>{e=!1}},[]),(0,l.useEffect)(()=>{if(!n||d.length)return;let e=!0;return fetch(`${rE}episodes`,{cache:"no-store"}).then(e=>e.json()).then(t=>{e&&t.success&&t.episodes&&h(t.episodes)}).catch(()=>{}),()=>{e=!1}},[n,d.length]);let F=(0,l.useRef)(null),U=(0,l.useCallback)(async(e=!1)=>{let t=S.current.lastReport()?.doc??null;if(e||t!==F.current){if(F.current=t,!t){T.current=[];return}try{var n,s;let e=await fetch(`/api/marks?doc=${encodeURIComponent(t)}`,{cache:"no-store"}),r=await e.json();T.current=(n=function(e,t=""){let n=e&&"object"==typeof e?e:{},s=Array.isArray(n.marks)?n.marks.map(tp).filter(e=>null!==e):[];return{doc:th(n.doc)||t,marks:s}}(r,t).marks,s="agent",n.filter(e=>"open"===e.status&&e.author.role!==s||"answered"===e.status&&e.author.role===s)).map(e=>e.id)}catch{T.current=[]}}},[]);(0,l.useEffect)(()=>{U(!0);let e=S.current.onMarks(()=>void U(!0)),t=setInterval(()=>void U(),3e3);return()=>{e(),clearInterval(t)}},[U]),(0,l.useEffect)(()=>{if(!p.waiting)return;let e=setInterval(()=>N(Date.now()),1e3);return()=>clearInterval(e)},[p.waiting]);let z=(0,l.useCallback)(()=>{let e=O.current;e&&(!rI(E.current.state)&&"retry"!==E.current.state&&R.current&&(A.current=!0,S.current.stop()),e.press())},[]),Y=(0,l.useCallback)((e,t)=>{let n=P.current?.getSnapshot().items.find(t=>"reply"===t.kind&&t.id===e);if(n){if(rI(E.current.state))return void w(`Send your take first. Then press ▶ to hear Mia.`);_.current=[],A.current=!1,D.current(n,t)}},[]),H=(0,l.useCallback)(()=>{_.current=[],A.current=!1,S.current.stop()},[]),X=p.waiting?{take:p.waiting.take,seconds:Math.max(0,Math.floor(($-p.waiting.since)/1e3))}:null;return(0,o.jsx)("div",{className:"stage-talk-host",children:(0,o.jsx)(nd,{open:n,onOpenChange:e=>{s(e),e&&U(!0)},who:"Mia",episode:i,episodes:d,onEpisode:e=>{rA.test(e)&&e!==i&&(_.current=[],b([]),w(null),c(e),rO(r_,e))},presence:p.presence,recorder:u,onRecord:z,items:p.items,unheard:y,playing:g,playingStep:g&&e.shown?.origin==="Mia"?e.shown.index:null,onPlay:Y,onStop:H,onFeedback:(e,t)=>{P.current?.feedback(e,t).catch(e=>k(`Your thumb was not kept: ${e instanceof Error?e.message:String(e)}.`))},autoplay:r,onAutoplay:e=>{a(e),rO(rR,e?"1":"0"),e||(_.current=[])},waiting:X,notice:v,error:j??p.error})})}let rB=(0,l.createContext)(null);function rF(){return(0,l.useContext)(rB)}let rU="stateloom.stage.voice",rz="stateloom.author";function rY(e){try{return window.localStorage.getItem(e)??""}catch{return""}}function rH(e,t){try{window.localStorage.setItem(e,t)}catch{}}function rX({children:e}){var t;let n,s,r,a,i,c,d,h,[u,m]=(0,l.useState)({bridgeUrl:null,stage:ti,companion:!1,companionEpisode:null});(0,l.useEffect)(()=>{let e=!0;return re().then(t=>{if(!e)return;let n=r$("stage"),s=tl(n)?n:tl(t.stage)?t.stage:ti;m({bridgeUrl:t.bridgeUrl,stage:s,companion:t.companion,companionEpisode:t.companionEpisode})}),()=>{e=!1}},[]);let[p,f]=(0,l.useState)(()=>"1"===rY(rU)),[g,x]=(0,l.useState)(()=>rY(rz)),y=(0,l.useMemo)(()=>p?sw():null,[p]),b=(0,l.useMemo)(()=>(function(e={}){let t=window,n=t.SpeechRecognition??t.webkitSpeechRecognition;if(!n)return null;let s=null;return{start(t,r){s?.stop();let a=new n;s=a,a.lang=e.lang??("u">typeof navigator?navigator.language:"en-US"),a.continuous=!0,a.interimResults=!0;let i="";a.onresult=e=>{let n="";for(let t=e.resultIndex;t<e.results.length;t++){let s=e.results[t],r=s[0]?.transcript??"";s.isFinal?i+=r:n+=r}t((i+n).trim(),""===n)},a.onerror=e=>r?.(e.error??"error"),a.onend=()=>{s===a&&(s=null),r?.()},a.start()},stop(){s?.stop(),s=null}}})(),[]),[v,w]=(0,l.useState)(null),j=(0,l.useRef)(new Set),k=(0,l.useCallback)(e=>{if(!e)return void w(null);let{step:t}=e,n=(0,s1.requestedDoc)();if(e.caught&&r$("doc"))return void w({doc:t.doc,focus:t.focus,spotlight:t.spotlight,region:t.region,nonce:e.nonce});if(t.doc&&t.doc!==n)rS({doc:t.doc,system:t.system??void 0,focus:t.focus??null});else if(t.focus)if(t.system&&r$("system")!==t.system&&n)rS({doc:n,system:t.system,focus:t.focus});else{var s;let e;s=t.focus,(e=new URL(window.location.href)).searchParams.set("focus",s),window.history.replaceState(window.history.state,"",e),window.dispatchEvent(new Event(rw))}w({doc:t.doc,focus:t.focus,spotlight:t.spotlight,region:t.region,nonce:e.nonce})},[]),$=(t={url:u.bridgeUrl??"",stage:u.stage,name:"web-stage",voice:y,enabled:!!u.bridgeUrl,onShow:k,onMarks:e=>{for(let t of[...j.current])t(e)}},(n=(0,l.useRef)({onShow:t.onShow,onMarks:t.onMarks})).current={onShow:t.onShow,onMarks:t.onMarks},s=(0,l.useRef)(null),r=`${t.url}\u0000${t.stage??""}\u0000${t.token??""}`,a=(0,l.useRef)(r),(null===s.current||a.current!==r)&&(a.current=r,s.current=function(e){let t,n=tl(e.stage)?e.stage:ti,s=e.setTimer??((e,t)=>setTimeout(e,t)),r=e.clearTimer??(e=>clearTimeout(e)),a=e.gapMs??900,i=e.client??sy({url:e.url,role:e.role??"web",docId:`stage:${n}`,name:e.name??"web-stage",token:e.token,autoResync:!1}),o=e.voice??null,l=e=>e&&void 0!==t?t:o,c=null,d=null,h=e=>{let t=d;d=null,t?.(e)},u=null,m=null,p=[],f=[],g=0,x=!1,y=!1,b=0,v=null,w=0,j=!1,k=!1,$=!1,N=!1,S=!1,M={status:i.status,stage:n,shown:u,tour:m,index:g,playing:x,speaking:y,ownVoice:!1},C=new Set;function E(){for(let e of(M={status:i.status,stage:n,shown:u,tour:m,index:g,playing:x,speaking:y,ownVoice:!!m&&void 0!==t},[...C]))e()}function R(){w+=1,v&&r(v),v=null,y&&c?.cancel(),y=!1,c=null}function _(e,t,n=t){R();let r=++w,i=()=>{r!==w||(y&&(y=!1,E()),t&&x&&(v=s(()=>{v=null,r===w&&x&&L()},o?a:0)))},o=l(n);o?(y=!0,c=o,E(),o.speak(e).then(i,i)):t&&(v=s(()=>{v=null,i()},tg(e)))}function A(t,n){b+=1,R(),u=t?{...t,nonce:b,...S?{caught:!0}:{}}:null,E(),e.onShow?.(u);let s=!!u&&null!==u.index;u&&(l(s)||n)&&_(u.step,n,s)}function T(e){if(!m)return null;let t=m.def.steps[e];if(!t)return null;let n=t.doc??p[e],s=t.system??f[e];return{step:{...t,...n?{doc:n}:{},...s?{system:s}:{}},index:e,count:m.def.steps.length,title:m.def.settings?.name,origin:m.origin,tourPath:m.path}}function O(e,n,s){var r;let a,i;h(!1),t=s;let o=Array.isArray(e.tour?.steps)?e.tour.steps:[];r=(m={def:{...e.tour,steps:o},path:e.path,origin:e.origin}).def,i=void 0,p=r.steps.map(e=>i=e.doc??i),f=o.map(e=>a=e.system??a),g=Math.min(Math.max(0,e.from??0),Math.max(0,o.length-1)),j=!1,x=n&&o.length>0,A(T(g),x)}function P(e){x=!1,A({step:e.step,index:null,count:null,title:e.title,origin:e.origin,tourPath:e.tour},!1)}function I(e){if(!m)return;let t=m.def.steps.length-1;t<0||(j=!1,A(T(g=Math.min(Math.max(0,Math.floor(e)),t)),x))}function L(){if(m){if(g>=m.def.steps.length-1){let e=x;j=x||j,x=!1,R(),E(),e&&h(!0);return}I(g+1)}}function D(){m&&g>0&&I(g-1)}function q(){m&&m.def.steps.length&&(x=!0,j&&(j=!1,g=0),u?.index!==g||u.caught?A(T(g),!0):(E(),_(u.step,!0)))}function B(){x=!1,R(),E()}function F(){h(!1),t=void 0,j=!1,m=null,p=[],f=[],g=0,x=!1,A(null,!1)}function U(){N||(N=!0,i.joinStage(n).then(({state:e})=>{N=!1,$=!0,u||m||function(e){S=!0;try{e.tour&&O(e.tour,!1),e.step&&P(e.step)}finally{S=!1}}(e),E()}).catch(()=>{N=!1,E()}))}return i.on("stage-step",e=>{e?.stage===n&&e.step&&P(e)}),i.on("stage-load",e=>{e?.stage===n&&e.tour&&O(e,!1!==e.autoplay)}),i.on("stage-control",e=>{e?.stage===n&&function(e){switch(e.action){case"play":return q();case"pause":return B();case"next":return L();case"prev":return D();case"goto":return I(e.index??0);case"stop":return F()}}(e)}),i.on("marks",t=>e.onMarks?.(t)),i.on("status",e=>{"disconnected"===e||"error"===e?$=!1:"connected"===e&&k&&!$&&U(),E()}),{getSnapshot:()=>M,subscribe:e=>(C.add(e),()=>{C.delete(e)}),connect(){k=!0,U()},disconnect(){k=!1,R(),i.leaveStage(n),i.disconnect()},play:q,pause:B,next:L,prev:D,goto:I,stop:F,dismiss:function(){if(u){if(null===u.index&&m)return void A(T(g),!1);null===u.index?A(null,!1):F()}},setVoice(e){void 0===t&&R(),o=e,E()},present:(e,t={})=>Array.isArray(e?.steps)&&e.steps.length?new Promise(s=>{O({stage:n,tour:e,from:t.from??0,autoplay:!1!==t.autoplay,origin:t.origin??"page"},!1!==t.autoplay,t.voice),d=s}):Promise.resolve(!1),sendContext(e){i.emitContext({...e,stage:n,...m?{tour:{path:m.path,title:m.def.settings?.name,index:g,count:m.def.steps.length,playing:x}}:{}})},sendMarks(e){i.emitMarks({...e,stage:n}).catch(()=>{})}}}({...t,voice:t.voice??null,onShow:e=>n.current.onShow?.(e),onMarks:e=>n.current.onMarks?.(e)})),i=s.current,c=(0,l.useSyncExternalStore)(i.subscribe,i.getSnapshot,i.getSnapshot),d=!1!==t.enabled&&!!t.url,(0,l.useEffect)(()=>{if(d)return i.connect(),()=>i.disconnect()},[i,d]),h=t.voice??null,(0,l.useEffect)(()=>{i.setVoice(h)},[i,h]),{...c,play:i.play,pause:i.pause,next:i.next,prev:i.prev,goto:i.goto,stop:i.stop,dismiss:i.dismiss,sendContext:i.sendContext,sendMarks:i.sendMarks,present:i.present}),N=(0,l.useRef)(null),S=(0,l.useRef)(null),M=$.sendContext,C=(0,l.useCallback)(e=>{N.current={...e,stage:u.stage,who:g||void 0,at:new Date().toISOString()},S.current&&clearTimeout(S.current),S.current=setTimeout(()=>M({...e,who:g||void 0}),400)},[u.stage,g,M]);(0,l.useEffect)(()=>()=>{S.current&&clearTimeout(S.current)},[]),(0,l.useEffect)(()=>{N.current&&M({...N.current,who:g||void 0})},[$.index,$.playing,$.tour,M,g]);let[E,R]=(0,l.useState)(0),_=!!$.shown;(0,l.useEffect)(()=>{let e=document.documentElement,t=_?document.querySelector(".stage-caption-host .slc-stage-caption"):null;if(!t||"u"<typeof ResizeObserver)return void e.style.removeProperty("--stage-caption-h");let n=()=>e.style.setProperty("--stage-caption-h",`${Math.ceil(t.getBoundingClientRect().height)+12}px`),s=new ResizeObserver(n);return s.observe(t),n(),()=>{s.disconnect(),e.style.removeProperty("--stage-caption-h")}},[_]);let A=(0,l.useMemo)(()=>({stage:u.stage,connected:"connected"===$.status,lit:v,author:g,setAuthor:e=>{x(e),rH(rz,e)},listener:b,answerNonce:E,report:C,lastReport:()=>N.current,sendMarks:$.sendMarks,onMarks:e=>(j.current.add(e),()=>{j.current.delete(e)}),shown:$.shown,present:$.present,pause:$.pause,stop:$.stop}),[u.stage,$.status,$.shown,$.sendMarks,$.present,$.pause,$.stop,v,g,b,E,C]);return(0,o.jsxs)(rB.Provider,{value:A,children:[e,$.shown&&(0,o.jsx)("div",{className:"stage-caption-host",children:(0,o.jsx)(t7,{shown:$.shown,playing:$.playing,speaking:$.speaking,voice:$.ownVoice?void 0:p,onToggleVoice:()=>{let e=!p;f(e),rH(rU,e?"1":"0")},onPlay:$.play,onPause:$.pause,onNext:$.next,onPrev:$.prev,onGoto:$.goto,onClose:$.dismiss,onAnswer:()=>R(e=>e+1)})}),u.companion&&(0,o.jsx)(rq,{stage:A,defaultEpisode:u.companionEpisode})]})}let rV="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 rJ(e,t){let n=await fetch(`/api/marks?doc=${encodeURIComponent(e)}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),s=await n.json().catch(()=>({}));if(!n.ok)throw Error(s?.error??`the marks could not be written (${n.status})`);return s}function rW({docPath:e,kind:t,viewport:n,setViewport:s,boxes:r,boardRef:a,focus:i=null,level:c,onReveal:d}){let h=rF(),[u,m]=(0,l.useState)([]),[p,f]=(0,l.useState)(!1),[g,x]=(0,l.useState)(null),[y,b]=(0,l.useState)(null),[v,w]=(0,l.useState)(!1),[j,k]=(0,l.useState)(!1),[$,N]=(0,l.useState)(null),[S,M]=(0,l.useState)(!1),C=(0,l.useCallback)(()=>{e&&fetch(`/api/marks?doc=${encodeURIComponent(e)}`,{cache:"no-store"}).then(e=>e.ok?e.json():null).then(e=>e&&Array.isArray(e.marks)&&m(e.marks)).catch(()=>{})},[e]);(0,l.useEffect)(()=>(m([]),b(null),x(null),C(),window.addEventListener("focus",C),()=>window.removeEventListener("focus",C)),[C]),(0,l.useEffect)(()=>h?.onMarks(t=>{e&&t.docId===e&&Array.isArray(t.marks)&&m(t.marks)}),[h,e]);let E=async t=>{if(!e)return!1;k(!0),N(null);try{let n=await rJ(e,t);return m(n.marks),h?.sendMarks({docId:e,marks:n.marks,change:n.change}),!0}catch(e){return N(e instanceof Error?e.message:String(e)),!1}finally{k(!1)}},R=h?.lit??null,_=R&&(!R.doc||R.doc===e)?R:null,A=_?.spotlight,T=_?.region??null,O=(0,l.useRef)(-1),P=(0,l.useRef)(-1),I=(0,l.useRef)(null),L=(0,l.useMemo)(()=>A?.length?tb(r,A):[],[r,A]);(0,l.useEffect)(()=>{if(!_||O.current===_.nonce)return;let e=[...L,...T?[T]:[]];if(!e.length){A?.length&&P.current!==_.nonce&&(P.current=_.nonce,d?.(A));return}O.current=_.nonce;let t=()=>{let t=a.current?.getBoundingClientRect();if(!t?.width)return;let n=document.querySelector(".stage-caption-host .slc-stage-caption")?.getBoundingClientRect(),r=n&&n.top<t.bottom?Math.max(0,t.bottom-n.top+8):0,i=Math.max(.4*t.height,t.height-r);s(H(e,t.width,i,{padding:48,maxScale:1}))};t(),I.current&&clearTimeout(I.current),I.current=setTimeout(t,520)},[_,L,T,A,a,s,d]),(0,l.useEffect)(()=>()=>{I.current&&clearTimeout(I.current)},[]);let D=(0,l.useRef)(h?.answerNonce??0);(0,l.useEffect)(()=>{if(!h||h.answerNonce===D.current)return;D.current=h.answerNonce;let e=A?.length?[...A]:_?.focus?[_.focus]:i?[i]:[];w(!1),b(null),x({elements:e,region:T??void 0,listen:!!h.listener})},[h,A,_,i,T]);let q=h?.report;if((0,l.useEffect)(()=>{if(!q||!e)return;let s=a.current?.getBoundingClientRect(),r=F(n,{x:0,y:0}),o=s?F(n,{x:s.width,y:s.height}):r;q({doc:e,kind:t,system:r$("system")??void 0,focus:i,...s?.width?{visible:{x:Math.round(r.x),y:Math.round(r.y),width:Math.round(o.x-r.x),height:Math.round(o.y-r.y)}}:{}})},[q,e,t,i,n,a]),!e)return null;let B=u.filter(e=>"open"===e.status&&"person"===e.author.role).length,U=u.filter(e=>"open"===e.status&&"agent"===e.author.role).length,z=u.find(e=>e.id===y)??null;return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(tV,{viewport:n,boxes:r,spotlight:A,region:T,marks:u,selectedMark:y,onSelectMark:e=>{x(null),w(!1),b(t=>t===e?null:e)},marking:p,onDraft:e=>{f(!1),b(null),w(!1),x(e)},draft:g}),(0,o.jsxs)("div",{className:"stage-board-controls",children:[(0,o.jsxs)("button",{type:"button",className:`${rV} ${p?"!border-amber-400 !text-amber-300":""}`,"aria-pressed":p,onClick:()=>{x(null),f(e=>!e)},title:p?"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,o.jsx)(t8,{}),p&&(0,o.jsx)("span",{className:"text-xs",children:"marking"})]}),(0,o.jsxs)("button",{type:"button",className:rV,"aria-expanded":v,onClick:()=>{x(null),b(null),w(e=>!e)},title:"Marks on this drawing",children:[(0,o.jsx)(tG,{}),B+U>0&&(0,o.jsx)("span",{className:"text-xs text-amber-300",children:B+U})]})]}),p&&!g&&(0,o.jsx)("div",{className:"stage-board-hint",role:"status",children:"Tap an element, or drag around several, to say something about it."}),(g||z||v)&&(0,o.jsx)("div",{className:"stage-board-card",children:g?(0,o.jsx)(nn,{elements:g.elements,region:g.region,author:h?.author??"",onAuthorChange:h?.setAuthor,listener:h?.listener,listenAtOnce:!!g.listen,busy:j,error:$,onCancel:()=>{x(null),N(null)},onSubmit:async({text:e,kind:t,author:n})=>{await E({action:"add",mark:{text:e,kind:t,elements:g.elements,region:g.region,level:c,author:{name:n||"someone"}}})&&x(null)}},`${g.elements.join(",")}|${g.region?JSON.stringify(g.region):""}`):z?(0,o.jsx)(ns,{mark:z,number:u.indexOf(z)+1,listener:h?.listener,busy:j,error:$,onClose:()=>b(null),onReply:e=>void E({action:"reply",id:z.id,text:e,author:{name:h?.author||"someone"}}),onResolve:()=>void E({action:"resolve",id:z.id}),onReopen:()=>void E({action:"reopen",id:z.id}),onRemove:async()=>{await E({action:"remove",id:z.id})&&b(null)}}):(0,o.jsx)(nr,{marks:u,selected:y,onSelect:e=>{w(!1),b(e)},onCopy:()=>{var t,n;let s,r;if(!e)return;let a=(t=h?.lastReport()??null,s=(n=[{doc:e,marks:u.filter(e=>"resolved"!==e.status)}]).reduce((e,t)=>e+t.marks.length,0),r=function(e){if(!e||!e.doc)return"No canvas has said what it is showing.";let t=[`${e.who?`${e.who} is`:"The canvas is"} on ${tv(e.doc)}${e.kind?` (${e.kind})`:""}`];e.system&&t.push(`as a member of ${tv(e.system)}`),e.focus&&t.push(`with ${e.focus} in hand`);let n=t.join(", ")+".";return e.tour&&(n+=` Tour ${e.tour.title?`'${e.tour.title}' `:""}at step ${e.tour.index+1} of ${e.tour.count}, ${e.tour.playing?"playing":"paused"}.`),e.at&&(n+=` (reported ${e.at})`),n}(t),s?`${r}
11
11
  ${s} mark(s):
12
12
  ${function(e,t={}){let n=[],s=t.start??1;for(let{doc:t,marks:r}of e)for(let e of r){for(let r of(n.push(`${s}. [${e.status} \xb7 ${e.kind}] ${e.author.name}${"agent"===e.author.role?" (agent)":""} on ${tf(e)} (${tv(t)}) — ${e.id}`),n.push(` "${tw(e.text)}"`),e.replies??[]))n.push(` ↳ ${r.author.name}${"agent"===r.author.role?" (agent)":""}: "${tw(r.text)}"`);s++}return n.join("\n")}(n)}`:`${r}
13
- No marks.`);navigator.clipboard?.writeText(a).then(()=>{M(!0),setTimeout(()=>M(!1),2e3)})},copied:S,onClose:()=>w(!1)})})]})}function rV({docPath:e,onReveal:t}){let n=rD(),s=n?.lit??null,r=(0,l.useRef)(-1);return(0,l.useEffect)(()=>{!s||r.current===s.nonce||s.doc&&s.doc!==e||(s.spotlight?.length||s.region)&&(r.current=s.nonce,t())},[s,e,t]),null}function rJ(e,t,n){try{return e()}catch(s){let e=s instanceof Error?s.message:String(s);return console.warn("[stateloom] skipped on a malformed document:",e),n?.(e),t}}let rW=(e,t)=>"chen"===t?`stateloom:erd-layout:chen:${e}`:`stateloom:erd-layout:${e}`,rK="stateloom:erd-notation",rZ="stateloom:erd-lock";function rG(e,t){try{return JSON.parse(localStorage.getItem(rW(e,t))??"{}")}catch{return{}}}async function rQ(e){let t=e.slice(0,e.lastIndexOf("/")),n=((await (await fetch("/api/docs",{cache:"no-store"})).json()).docs??[]).map(e=>e.path).filter(e=>e.endsWith(".smdf.json")&&e.slice(0,e.lastIndexOf("/"))===t),s=[];for(let e of n)try{let t=await (await fetch(`/api/file${(0,s1.docQuery)(e)}`,{cache:"no-store"})).json(),n=JSON.parse(t.content??"null"),r=ex(n?.stateMachine??n?.StateMachine??n);r?.state&&s.push({path:e,def:r})}catch{}return s}let r0="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",r1="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",r2="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function r5(){let e=(0,s1.useRequestedDoc)(),[t,n]=(0,l.useState)(""),[s,r]=(0,l.useState)(null),[a,i]=(0,l.useState)({}),[c,d]=(0,l.useState)("crowsfoot"),[h,u]=(0,l.useState)(!1),[m,p]=(0,l.useState)({...q}),[f,g]=(0,l.useState)(0),[x,y]=(0,l.useState)(null),[b,v]=(0,l.useState)({text:"loading…",tone:"ok"}),w=(0,l.useCallback)((e,t="ok")=>v({text:e,tone:t}),[]),[j,k]=(0,l.useState)(!1);(0,l.useEffect)(()=>{let e=setTimeout(()=>k(!0),4e3);return()=>{clearTimeout(e),k(!1)}},[b]);let[$,N]=(0,l.useState)("entities"),[S,M]=(0,l.useState)(!1),[C,E]=(0,l.useState)(!1),[R,_]=(0,l.useState)(!1),A=(0,l.useRef)(null),T=rb({onClose:()=>M(!1),restVh:62,tallVh:92}),[O,P]=(0,l.useState)(0),[I,L]=(0,l.useState)(null),D=(0,l.useRef)(null);(0,l.useEffect)(()=>{let t=!1,s=null;return(async()=>{let a=await (await fetch(`/api/file${(0,s1.docQuery)(e)}`,{cache:"no-store"})).json();if(t)return;if(a.error)return w(a.error,"warn");let o=a.path??"",l=null;try{let e=a.content?ex(JSON.parse(a.content)):null;K(e)&&(l={...e,relationships:e.relationships??[]})}catch{}if(a.exists&&!l)return w(`${o} is not a readable ERD definition`,"warn");let c=(o.split("/").pop()??"Untitled").replace(/\.erdf\.json$/i,""),h=function(){try{return"chen"===localStorage.getItem(rK)?"chen":"crowsfoot"}catch{return"crowsfoot"}}();n(o),r(l??{settings:{namespace:"Default",name:c},entities:[],relationships:[]}),d(h),u(function(){try{let e=localStorage.getItem(rZ);if(null!==e)return"1"===e;return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}()),i(rG(o,h)),y(null),L(null),g(e=>e+1),w(a.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:m}=await re();!t&&m&&(D.current=s=sv({url:m,role:"web",docId:o,name:"web-designer",onFull:e=>{let t=e.def;K(t)&&(r({...t,relationships:t.relationships??[]}),w("updated live"))},onPatch:()=>{},onPresence:e=>P(e.length)}),s.connect())})().catch(e=>!t&&w(String(e),"warn")),()=>{t=!0,D.current=null,s?.disconnect()}},[e,w]);let B=(0,l.useMemo)(()=>{if(!s)return{};let e=rJ(()=>(function(e,t={}){let n=t.notation??"crowsfoot",s=t.hSpacing??70,r=t.vSpacing??("chen"===n?130:90),a="chen"===n?ed:eb,i=[],o=new Set;for(let t of e.entities??[])!t?.name||o.has(t.name)||(o.add(t.name),i.push(t));let l=new Map,c=(e,t,n=new Set)=>e===t||!n.has(e)&&(n.add(e),(l.get(e)??[]).some(e=>c(e,t,n)));for(let t of e.relationships??[]){if(!t||!o.has(t.from)||!o.has(t.to)||t.from===t.to)continue;let[e,n]="N:1"===t.cardinality?[t.to,t.from]:[t.from,t.to];if((l.get(e)??[]).includes(n)||c(n,e))continue;let s=l.get(e);s?s.push(n):l.set(e,[n])}let d=new Map,h=(e,t)=>{if(!((d.get(e)??-1)>=t))for(let n of(d.set(e,t),l.get(e)??[]))h(n,t+1)},u=new Set([...l.values()].flat());for(let e of i)u.has(e.name)||h(e.name,0);for(let e of i)d.has(e.name)||h(e.name,0);for(let e of[...i].sort((e,t)=>d.get(t.name)-d.get(e.name))){let t=l.get(e.name)??[];t.length&&d.set(e.name,Math.min(...t.map(e=>d.get(e)))-1)}let m=[],p=new Map,f=(e,t)=>((m[t]??=[]).push(e),p.set(e.id,e),e);for(let e of i)f({id:e.name,entity:e.name,...a(e),upper:[],lower:[],x:0},d.get(e.name)??0);let g=0;for(let[e,t]of l)for(let n of t){let t=e;for(let s=d.get(e)+1;s<d.get(n);s++){let e=f({id:`\u0000lane${g++}`,width:28,height:0,upper:[],lower:[],x:0},s);p.get(t).lower.push(e.id),e.upper.push(t),t=e.id}p.get(t).lower.push(n),p.get(n).upper.push(t)}for(let e=m.length-1;e>=0;e--)m[e]?.length||m.splice(e,1);let x=(e,t)=>e.length?e.reduce((e,n)=>e+t(p.get(n)),0)/e.length:null,y=(e,t)=>{let n=new Map;for(let e of m)e.forEach((e,t)=>n.set(e.id,t));let s=new Map(e.map((e,s)=>[e.id,x(e[t],e=>n.get(e.id))??s]));e.sort((e,t)=>s.get(e.id)-s.get(t.id))};for(let e=0;e<2;e++){for(let e=1;e<m.length;e++)y(m[e],"upper");for(let e=m.length-2;e>=0;e--)y(m[e],"lower")}let b=e=>e.x+e.width/2,v=(e,t)=>{let n=0;for(let r of e){let e=x(r[t],b);r.x=Math.max(n,null===e?n:e-r.width/2),n=r.x+r.width+s}};for(let e of m)v(e,"upper");for(let e=m.length-2;e>=0;e--)v(m[e],"lower");let w=Math.min(0,...[...p.values()].map(e=>e.x)),j={},k=40;for(let e of m){for(let t of e)t.entity&&(j[t.entity]={x:Math.round(t.x-w)+40,y:k,width:t.width,height:t.height});k+=Math.max(0,...e.map(e=>e.height))+r}return j})(s,{notation:c}),{});for(let[t,n]of Object.entries(a))e[t]&&(e[t]={...e[t],...n});return e},[s,a,c]),F=(0,l.useMemo)(()=>{if(!s)return[];let e="";return rJ(()=>Z(s),null,t=>e=t)??[{ruleId:"E000",message:`The document could not be checked (${e}): a field is not the shape Spec 80 gives it`}]},[s]),U=(0,l.useMemo)(()=>F.map(e=>(e.element??"").split(/[.[]/)[0]).filter(Boolean),[F]),Y=(0,l.useCallback)(async e=>{let n;if(s&&t){try{n=e(s)}catch(e){return w(e instanceof Error?e.message:String(e),"warn")}r(n),L(null);try{let e=await fetch(`/api/file${(0,s1.docQuery)(t)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(n,null,2)+"\n"})});if(!e.ok)throw Error((await e.json())?.error??`HTTP ${e.status}`);D.current?.emitFull(n),w("saved")}catch(e){w(`not saved: ${e instanceof Error?e.message:String(e)}`,"warn")}}},[s,t,w]),X=(0,l.useCallback)((e,n)=>{i(s=>{let r={...s,[e]:{x:Math.round(n.x),y:Math.round(n.y)}};try{localStorage.setItem(rW(t,c),JSON.stringify(r))}catch{}return r})},[t,c]),V=()=>{i({});try{localStorage.removeItem(rW(t,c))}catch{}g(e=>e+1)},G=async()=>{if(!s)return;w("checking links…");let e=await rQ(t);if(0===e.length)return L("none"),N("issues"),M(!0),w("no .smdf.json beside this document to check against","warn");let n=e.flatMap(e=>Q(e.def,s).map(t=>({...t,message:`${e.def.settings?.name??e.path}: ${t.message}`})));n.push(...ee(s,e.map(e=>e.def.settings?.name??""))),L(n),N("issues"),M(!0),_(!1),w(`checked ${e.length} machine(s): ${n.length} problem(s)`,n.length?"warn":"ok")},ei=async e=>{let n=(await rQ(t)).find(t=>t.def.settings?.name===e);n?(0,s1.navigateToDoc)(n.path):w(`no .smdf.json beside this document defines '${e}'`,"warn")},eo=()=>{let e=A.current?.getBoundingClientRect();return{width:e?.width??0,height:e?.height??0}},el=e=>{let{width:t,height:n}=eo();p(s=>z(s,e,{x:t/2,y:n/2}))},ec=e=>{let t=B[e],{width:n,height:s}=eo();t&&n&&(p(H([t],n,s,{padding:28,maxScale:1.25})),y(e),T.close())},eu=rC(),eg=rN("focus"),ey=(0,l.useMemo)(()=>s?rJ(()=>(function(e,t,n={}){let s=!1!==n.rows,r=[];for(let n of e?.entities??[]){let e=n?.name?t[n.name]:void 0;e&&(r.push({focus:`entity:${n.name}`,box:e}),(n.attributes??[]).filter(e=>e?.name).forEach((t,a)=>{r.push({focus:`attribute:${n.name}.${t.name}`,box:s?{x:e.x,y:e.y+30+20*a,width:e.width,height:20}:e})}))}return r})(s,B,{rows:"chen"!==c}),[]):[],[s,B,c]),ev=(0,l.useRef)(-1);(0,l.useEffect)(()=>{if(!s||ev.current===eu.nonce)return;ev.current=eu.nonce;let e=eu.focus?e9(eu.focus):null,t=e?.kind==="entity"?e.name:e?.kind==="attribute"?e.name.split(".")[0]:null;t&&B[t]&&ec(t)},[s,eu,B]),(0,l.useEffect)(()=>{x&&!r$("focus")?.startsWith(`attribute:${x}.`)&&rM(`entity:${x}`)},[x]);let ew=s?.entities.find(e=>e.name===x)??null,ej=t.split("/").pop()||"…",ek=Array.isArray(I)?I:[],e$=F.length+ek.length,eN=[{id:"entities",label:"Entities",icon:"▭"},{id:"relations",label:"Relations",icon:"⟷"},{id:"notes",label:"Notes",icon:"✎",badge:void 0},{id:"issues",label:"Issues",icon:(0,o.jsx)(rx,{}),badge:e$||void 0}],eS=e=>$===e?"":"hidden md:block",eM=()=>{s&&navigator.clipboard?.writeText(function(e){let t=["erDiagram"],n=" ",s=new Set;for(let r of e.relationships??[]){if(!r?.from||!r?.to)continue;let e=eh[r.cardinality]??eh["1:N"];t.push(`${n}${em(r.from)} ${e} ${em(r.to)} : ${ef(r.label??"")}`),s.add(r.from),s.add(r.to)}let r=new Set;for(let a of e.entities??[]){if(!a?.name||r.has(a.name))continue;r.add(a.name);let e=(a.attributes??[]).filter(e=>e?.name);if(0===e.length){s.has(a.name)||t.push(`${n}${em(a.name)}`);continue}for(let s of(t.push(`${n}${em(a.name)} {`),e))t.push(`${n}${n}${function(e){let t=[];"pk"===e.key&&t.push("PK"),"uk"===e.key&&t.push("UK"),e.references&&t.push("FK");let n=[],s=J(e);s.length&&n.push(`stateOf ${s.join(", ")}`),e.description&&n.push(e.description);let r=[ep(e.type??"","unknown"),ep(e.name,"unnamed")];return t.length&&r.push(t.join(", ")),n.length&&r.push(ef(n.join(" — "))),r.join(" ")}(s)}`);t.push(`${n}}`)}return t.join("\n")}(s)).then(()=>w("mermaid copied"))};return(0,o.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&E(!1),children:[(0,o.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,o.jsx)("span",{className:"font-semibold text-blue-300",children:"ERD"}),(0,o.jsx)(s2,{}),(0,o.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:t,children:[s?.settings.name??ej,(0,o.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",ej]})]}),(0,o.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(([e,n,s])=>(0,o.jsx)("button",{title:s,"aria-label":s,"aria-pressed":c===e,onClick:()=>(e=>{if(e!==c){try{localStorage.setItem(rK,e)}catch{}d(e),i(rG(t,e)),g(e=>e+1)}})(e),className:`px-2.5 py-1.5 text-sm leading-none md:px-2 md:py-1 ${c===e?"bg-blue-900/60 text-blue-200":"bg-gray-800 text-gray-400 hover:bg-gray-700"}`,children:n},e))}),(0,o.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,o.jsx)("button",{className:r1,onClick:V,title:"Forget the dragged positions and lay the board out again",children:"⤢ Arrange"}),(0,o.jsx)("button",{className:r1,onClick:G,title:"Check the state machines beside this document against it",children:"Check links"}),(0,o.jsx)("button",{className:r1,onClick:eM,children:"Copy mermaid"}),(0,o.jsx)("button",{className:r1,onClick:()=>_(e=>!e),"aria-pressed":!R,title:R?"Show the panel":"Hide the panel — the board takes the full width",children:R?"⟨ Panel":"Panel ⟩"})]}),(0,o.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,o.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:e=>{e.stopPropagation(),E(e=>!e)},children:"⋯"}),C&&(0,o.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",V],["Check links to the machines",G],["Copy as mermaid",eM]].map(([e,t])=>(0,o.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{E(!1),t()},children:e},e))})]})]}),(0,o.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,o.jsxs)("div",{ref:A,className:"relative min-w-0 flex-1 overflow-hidden",children:[s&&(0,o.jsx)(rg,{what:"diagram",resetKey:s,children:(0,o.jsx)(tq,{definition:s,notation:c,positions:B,viewport:m,onViewportChange:p,selection:x,readOnly:h,errorElements:U,fitKey:f,onSelect:y,onClearSelection:()=>y(null),onEntityMove:X,onOpenMachine:ei,emptyHint:"No entities yet — add one in the panel, or let an agent call add_entity."})}),s&&(0,o.jsx)(rX,{docPath:t||null,kind:"erd",viewport:m,setViewport:p,boxes:ey,boardRef:A,focus:eg}),(0,o.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"===b.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,o.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===b.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,o.jsxs)("span",{className:`truncate transition-opacity duration-500 ${j&&"ok"===b.tone?"opacity-0":"opacity-100"}`,children:[b.text,O>1?` \xb7 ${O} in the room`:""]})]}),(0,o.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,o.jsx)("button",{title:h?"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":h,onClick:()=>{let e=!h;u(e);try{localStorage.setItem(rZ,e?"1":"0")}catch{}w(e?"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 ${h?"bg-blue-950/60 text-blue-300":"text-gray-400"}`,children:(0,o.jsx)(ry,{locked:h})}),[["+","Zoom in",()=>el(1.25)],["−","Zoom out",()=>el(.8)],["⛶","Fit the whole diagram",()=>g(e=>e+1)]].map(([e,t,n])=>(0,o.jsx)("button",{title:t,"aria-label":t,onClick:n,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:e},t))]}),ew&&!S&&(0,o.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:()=>{N("entities"),M(!0)},children:["✎ ",ew.name]})]}),S&&(0,o.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:T.close,"aria-hidden":"true"}),s&&(0,o.jsxs)("aside",{style:T.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 ${S?"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 ${R?"md:hidden":""}`,children:[(0,o.jsxs)("div",{className:"md:hidden",...T.zoneProps,children:[(0,o.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,o.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,o.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,o.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:eN.find(e=>e.id===$)?.label}),(0,o.jsx)("button",{onClick:T.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,o.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,o.jsxs)("section",{className:eS("entities"),children:[(0,o.jsx)("div",{className:r2,style:{marginTop:0},children:"Entities"}),(0,o.jsx)("div",{className:"flex flex-wrap gap-1",children:s.entities.map(e=>(0,o.jsx)("button",{className:`${r1} ${x===e.name?"border-blue-500 text-blue-300":""}`,onClick:()=>y(e.name),children:e.name},e.name))}),(0,o.jsx)(r3,{fields:[{name:"name",placeholder:"new entity"}],submit:"+ Entity",onSubmit:e=>{Y(t=>er(t,{name:e.name.trim()})),y(e.name.trim())}}),ew&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:`${r2} flex items-center justify-between gap-2`,children:[(0,o.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:ew.name}),(0,o.jsx)("button",{className:`${r1} normal-case tracking-normal`,onClick:()=>ec(ew.name),title:"Bring this entity to the middle of the board at a readable size",children:"◎ Show on board"})]}),(0,o.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,o.jsx)("input",{type:"checkbox",checked:!!ew.weak,onChange:e=>Y(t=>ea(t,ew.name,{weak:e.target.checked}))}),"weak entity"]}),(ew.attributes??[]).map(e=>(0,o.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 font-mono text-[11px]",children:[(0,o.jsxs)("span",{className:e.stateOf?"text-blue-300":"text-gray-300",children:[e.name," : ",e.type,(0,o.jsxs)("span",{className:"text-gray-500",children:[e.key?` ${e.key.toUpperCase()}`:"",e.references?` → ${e.references}`:"",e.stateOf?` ◉ ${[e.stateOf].flat().join(", ")}`:""]})]}),(0,o.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":`Remove ${e.name}`,onClick:()=>Y(t=>(function(e,t,n){let s=et(e),r=en(s,t),a=r.attributes?.length??0;if(r.attributes=(r.attributes??[]).filter(e=>e.name!==n),r.attributes.length===a)throw Error(`Attribute '${t}.${n}' not found.`);return s})(t,ew.name,e.name)),children:"✕"})]},e.name)),(0,o.jsx)(r3,{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:e=>Y(t=>(function(e,t,n){if(!n.name?.trim())throw Error("An attribute needs a name.");let s=et(e),r=en(s,t);if(r.attributes??=[],r.attributes.some(e=>e.name===n.name))throw Error(`Attribute '${t}.${n.name}' already exists.`);return r.attributes.push(es({...n})),s})(t,ew.name,{name:e.name.trim(),type:e.type.trim()||"string",key:"pk"===e.key||"uk"===e.key?e.key:void 0,references:e.references.trim()||void 0,stateOf:e.stateOf.trim()||void 0}))}),(0,o.jsxs)("button",{className:`${r1} mt-2 text-red-300`,onClick:()=>{Y(e=>{var t;let n;return t=ew.name,en(n=et(e),t),n.entities=n.entities.filter(e=>e.name!==t),n.relationships=n.relationships.filter(e=>e.from!==t&&e.to!==t),n}),y(null)},children:["🗑 Delete ",ew.name]})]})]}),(0,o.jsxs)("section",{className:eS("relations"),children:[(0,o.jsx)("div",{className:`${r2} max-md:mt-0`,children:"Relationships"}),0===s.relationships.length&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),s.relationships.map((e,t)=>(0,o.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 text-[11px] text-gray-300",children:[(0,o.jsxs)("span",{children:[e.from," ",(0,o.jsx)("span",{className:"text-gray-500",children:e.cardinality})," ",e.to,e.label?(0,o.jsxs)("span",{className:"text-gray-500",children:[" : ",e.label]}):null]}),(0,o.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":"Remove relationship",onClick:()=>Y(t=>(function(e,t,n,s){let r=et(e),a=r.relationships.length;if(r.relationships=r.relationships.filter(e=>e.from!==t||e.to!==n||void 0!==s&&e.label!==s),r.relationships.length===a)throw Error(`No relationship from '${t}' to '${n}'${void 0===s?"":` labelled '${s}'`}.`);return r})(t,e.from,e.to,e.label)),children:"✕"})]},t)),s.entities.length>0&&(0,o.jsx)(r3,{fields:[{name:"from",options:s.entities.map(e=>e.name)},{name:"cardinality",options:[...W],initial:"1:N"},{name:"to",options:s.entities.map(e=>e.name)},{name:"label",placeholder:"label (a verb)"}],submit:"+ Relationship",onSubmit:e=>Y(t=>(function(e,t){let n=et(e);if(en(n,t.from),en(n,t.to),!W.includes(t.cardinality))throw Error(`Cardinality '${t.cardinality}' is not one of ${W.join(", ")}.`);return n.relationships.push(es({...t})),n})(t,{from:e.from,to:e.to,cardinality:e.cardinality,label:e.label.trim()||void 0}))})]}),(0,o.jsxs)("section",{className:eS("notes"),children:[(0,o.jsx)("div",{className:`${r2} max-md:mt-0`,children:"Notes"}),(0,o.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,o.jsx)(r4,{label:"On this diagram",value:s.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:e=>Y(t=>(function(e,t){let n=et(e);for(let e of["description","notes"]){let s=t[e];void 0!==s&&(s.trim()?n.settings[e]=s:delete n.settings[e])}return n})(t,{notes:e}))},"diagram"),ew?(0,o.jsx)(r4,{label:`On ${ew.name}`,value:ew.notes??"",placeholder:`A question or a decision about ${ew.name}…`,onSave:e=>Y(t=>ea(t,ew.name,{notes:e}))},`entity:${ew.name}`):(0,o.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Select an entity to leave a note on it."}),s.entities.some(e=>e.notes?.trim())&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:r2,children:"Entities with notes"}),(0,o.jsx)("div",{className:"flex flex-wrap gap-1",children:s.entities.filter(e=>e.notes?.trim()).map(e=>(0,o.jsx)("button",{className:`${r1} ${x===e.name?"border-blue-500 text-blue-300":""}`,onClick:()=>y(e.name),children:e.name},e.name))})]})]}),(0,o.jsxs)("section",{className:eS("issues"),children:[(0,o.jsx)("div",{className:`${r2} max-md:mt-0 ${0===e$&&!I?"md:hidden":""}`,children:"Issues"}),F.map((e,t)=>(0,o.jsxs)("div",{className:"py-0.5 text-[11px] text-red-300",children:["[",e.ruleId,"] ",e.message]},`p${t}`)),ek.map((e,t)=>(0,o.jsxs)("div",{className:"py-0.5 text-[11px] text-amber-300",children:["[",e.ruleId,"] ",e.message]},`l${t}`)),"none"===I&&(0,o.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===e$&&"none"!==I&&(0,o.jsx)("div",{className:`py-0.5 text-[11px] ${I?"text-green-400":"text-gray-600 md:hidden"}`,children:I?"Every name the machines use resolves.":"The document is valid. “Check links” (⋯) holds the state machines beside it against it."})]})]})]})]}),(0,o.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:eN.map(e=>{let t=S&&$===e.id;return(0,o.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(S&&$===t?T.close():M(!0),N(t))},"aria-pressed":t,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${t?"text-blue-400":"text-gray-500"}`,children:[(0,o.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,o.jsx)("span",{children:e.label}),void 0!==e.badge&&(0,o.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:e.badge}),t&&(0,o.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})})]})}function r4({label:e,value:t,placeholder:n,onSave:s}){let[r,a]=(0,l.useState)(t),[i,c]=(0,l.useState)(t),[d,h]=(0,l.useState)(!1);t!==i&&(c(t),d||a(t));let u=(0,l.useRef)(null),m=e=>{u.current&&clearTimeout(u.current),u.current=null,e!==t&&s(e)};return(0,o.jsxs)("label",{className:"mt-2 block",children:[(0,o.jsx)("span",{className:"text-[11px] text-gray-500",children:e}),(0,o.jsx)("textarea",{className:`${r0} h-24 resize-y leading-snug`,placeholder:n,value:r,onChange:e=>{let t=e.target.value;a(t),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>m(t),900)},onFocus:()=>h(!0),onBlur:()=>{h(!1),m(r)}})]})}function r3({fields:e,submit:t,onSubmit:n}){let s=()=>Object.fromEntries(e.map(e=>[e.name,e.initial??e.options?.[0]??""])),[r,a]=(0,l.useState)(s),i=e[0];return(0,o.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:t=>{t.preventDefault();let o={...s(),...r};o[i.name]?.trim()&&(n(o),a(t=>Object.fromEntries(e.map(e=>[e.name,e.options?t[e.name]??"":e.initial??""]))))},children:[e.map(e=>e.options?(0,o.jsx)("select",{className:r0,"aria-label":e.name,value:r[e.name]??"",onChange:t=>a(n=>({...n,[e.name]:t.target.value})),children:e.options.map(t=>(0,o.jsx)("option",{value:t,children:t||`(${e.name})`},t))},e.name):(0,o.jsx)("input",{className:r0,"aria-label":e.name,placeholder:e.placeholder,value:r[e.name]??"",onChange:t=>a(n=>({...n,[e.name]:t.target.value}))},e.name)),(0,o.jsx)("button",{type:"submit",className:`${r1} ${1===e.length?"":"col-span-2"}`,children:t})]})}let r6="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",r8="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",r7="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function r9({id:e,fields:t,submit:n,onSubmit:s,reset:r=!1,required:a}){let i=()=>Object.fromEntries(t.map(e=>[e.name,e.initial??(!e.checkbox&&(e.options?e.options[0]??"":""))])),[c,d]=(0,l.useState)(i),h=(e,t)=>d(n=>({...n,[e]:t}));return(0,o.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:e=>{e.preventDefault();let n={...i(),...c};!(a??[]).some(e=>!String(n[e]??"").trim())&&(s(n),r&&d(e=>Object.fromEntries(t.map(t=>[t.name,t.options||t.checkbox?e[t.name]??"":t.initial??""]))))},children:[t.map(t=>{let n=t.label??t.name;if(t.checkbox)return(0,o.jsxs)("label",{className:"flex items-center gap-2 text-[11px] text-gray-400",children:[(0,o.jsx)("input",{type:"checkbox",checked:!!c[t.name],onChange:e=>h(t.name,e.target.checked)}),n]},t.name);if(t.options)return(0,o.jsx)("select",{className:`${r6} ${t.wide?"col-span-2":""}`,"aria-label":n,title:n,value:String(c[t.name]??""),onChange:e=>h(t.name,e.target.value),children:t.options.map(e=>(0,o.jsx)("option",{value:e,children:e||`(${n})`},e))},t.name);let s=t.suggest?.length?`${e}-${t.name}`:void 0;return(0,o.jsxs)("span",{className:t.wide?"col-span-2":"",children:[(0,o.jsx)("input",{className:r6,"aria-label":n,title:n,placeholder:t.placeholder??n,list:s,value:String(c[t.name]??""),onChange:e=>h(t.name,e.target.value)}),s&&(0,o.jsx)("datalist",{id:s,children:t.suggest.map(e=>(0,o.jsx)("option",{value:e},e))})]},t.name)}),(0,o.jsx)("button",{type:"submit",className:`${r8} col-span-2`,children:n})]})}function ae({kind:e,size:t=16}){return(0,o.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"shrink-0",children:["erd"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("rect",{x:"4",y:"4.5",width:"16",height:"15",rx:"1.5"}),(0,o.jsx)("path",{d:"M4 9h16M8 13h8M8 16.5h6"})]}),"machine"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("rect",{x:"2.5",y:"4",width:"8",height:"6",rx:"2.5"}),(0,o.jsx)("rect",{x:"13.5",y:"14",width:"8",height:"6",rx:"2.5"}),(0,o.jsx)("path",{d:"M6.5 10v4.5a2.5 2.5 0 0 0 2.5 2.5h4.5"}),(0,o.jsx)("path",{d:"M11.5 15l2 2-2 2"})]}),"sequence"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("path",{d:"M6 4v16M18 4v16",strokeDasharray:"2 2.2"}),(0,o.jsx)("path",{d:"M6 9h11M15 7l2 2-2 2"}),(0,o.jsx)("path",{d:"M18 15H7M9 13l-2 2 2 2"})]}),"system"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("rect",{x:"3",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,o.jsx)("rect",{x:"14",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,o.jsx)("rect",{x:"8.5",y:"14.5",width:"7",height:"6",rx:"1.5"}),(0,o.jsx)("path",{d:"M10 6.5h4M7 9.5l3 5M17 9.5l-3 5"})]}),"link"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.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,o.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"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("circle",{cx:"12",cy:"7.5",r:"3.5"}),(0,o.jsx)("path",{d:"M5 20a7 7 0 0 1 14 0"})]})]})}let at=["text-sky-300","text-emerald-300","text-amber-300","text-rose-300","text-violet-300","text-cyan-300","text-lime-300","text-orange-300"],an=e=>`seq-read-${e.kind}-${e.id}`;function as({definition:e,selection:t,issues:n,onSelect:s,onShowInDiagram:r}){let a=new Map(e.participants.map((e,t)=>[e.name,at[t%at.length]])),i=eS(e),l=i.filter(e=>null===e.fragment),c=(e.fragments??[]).map((e,t)=>({f:e,fi:t,rows:i.filter(e=>e.fragment===t)})),d=(e,n)=>t?.kind===e&&t.id===n,h=e=>(0,o.jsx)("span",{className:`font-semibold ${a.get(e)??"text-gray-300"}`,children:e||"?"}),u=(e,t)=>{let a={kind:"message",id:e},i=n.get(`message:${e}`)??[],l=i.some(e=>"error"===e.severity)?"error":i.length?"warning":null,c=d("message",e);return(0,o.jsx)("li",{id:an(a),className:"scroll-mt-16 scroll-mb-24",children:(0,o.jsxs)("div",{role:"button",tabIndex:0,"aria-pressed":c,onClick:()=>s(a),onKeyDown:e=>("Enter"===e.key||" "===e.key)&&(e.preventDefault(),s(a)),className:`flex gap-3 rounded-lg border-l-2 px-3 py-2.5 ${c?"bg-blue-950/60 ring-1 ring-blue-500/60":"hover:bg-gray-900"} ${"error"===l?"border-red-500":"warning"===l?"border-amber-400":"border-transparent"}`,children:[(0,o.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:e}),(0,o.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,o.jsxs)("div",{className:"text-[13px] leading-5 text-gray-400",children:[h(t.from),t.from===t.to?(0,o.jsx)("span",{children:" to itself"}):(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("span",{className:"px-1.5 text-gray-500",children:t.reply?"⇠":"→"}),h(t.to)]}),t.reply&&(0,o.jsx)("span",{className:"ml-2 text-[11px] text-gray-500",children:"reply"}),t.optional&&(0,o.jsx)("span",{className:"ml-2 rounded border border-gray-700 px-1 text-[11px] text-gray-400",children:"optional"})]}),(0,o.jsx)("div",{className:`mt-0.5 break-words text-[15px] leading-6 ${t.reply?"text-gray-300":"text-gray-100"}`,children:t.label||(0,o.jsx)("span",{className:"text-gray-500",children:"no label"})}),(t.event||t.state||t.carries)&&(0,o.jsxs)("div",{className:"mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] leading-5",children:[t.event&&(0,o.jsx)("span",{className:"rounded border border-blue-500/50 bg-blue-950/50 px-1.5 font-mono text-blue-200",children:t.event}),t.event&&t.machine&&(0,o.jsxs)("span",{className:"text-gray-400",children:["on ",t.machine]}),t.state&&(0,o.jsxs)("span",{className:"text-emerald-300",children:["→ ",t.state]}),t.carries&&(0,o.jsxs)("span",{className:"text-gray-400",children:["carries ",t.carries]})]}),i.map((e,t)=>(0,o.jsx)("p",{className:`mt-1.5 text-[12px] leading-5 ${"error"===e.severity?"text-red-300":"text-amber-300"}`,children:e.text},t)),c&&(0,o.jsx)("button",{className:"mt-2 rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-[12px] text-gray-200",onClick:e=>{e.stopPropagation(),r(a)},children:"Show in the diagram"})]})]})},e)};return(0,o.jsx)("div",{className:"h-full overflow-y-auto overscroll-contain",children:(0,o.jsxs)("div",{className:"mx-auto max-w-2xl px-4 pb-28 pt-10",children:[e.participants.length>0&&(0,o.jsx)("ul",{className:"mb-4 flex flex-wrap gap-2","aria-label":"Participants",children:e.participants.map(e=>{let t={kind:"participant",id:e.name},r=e.actor?"actor":e.object?"object":e.service?"service":"",a=n.get(`participant:${e.name}`)??[];return(0,o.jsx)("li",{id:an(t),children:(0,o.jsxs)("button",{onClick:()=>s(t),"aria-pressed":d("participant",e.name),title:a.map(e=>e.text).join("\n")||void 0,className:`rounded-full border px-3 py-1 text-[13px] ${d("participant",e.name)?"border-blue-500 bg-blue-950/60":"border-gray-700 bg-gray-900"} ${a.length?"ring-1 ring-amber-400/70":""}`,children:[h(e.name),r&&(0,o.jsx)("span",{className:"ml-1.5 text-[11px] text-gray-400",children:r})]})},e.name)})}),0===i.length&&(0,o.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,o.jsx)("ol",{className:"flex flex-col gap-1",children:l.map(({ref:e,message:t})=>u(e,t))}),c.map(({f:e,fi:t,rows:n})=>(0,o.jsxs)("section",{className:"mt-5 rounded-xl border border-indigo-500/50 bg-indigo-950/20 p-1.5",children:[(0,o.jsxs)("header",{className:"px-3 pb-1.5 pt-2",children:[(0,o.jsxs)("div",{className:"text-[12px] text-indigo-200",children:[(0,o.jsx)("span",{className:"font-semibold uppercase tracking-wide",children:e.kind}),(0,o.jsxs)("span",{className:"text-indigo-300",children:[" · after ",e.after]})]}),(0,o.jsx)("div",{className:"mt-0.5 break-words text-[14px] leading-5 text-gray-100",children:e.label})]}),0===n.length?(0,o.jsx)("p",{className:"px-3 pb-2 text-[12px] text-gray-400",children:"No messages in this fragment."}):(0,o.jsx)("ol",{className:"flex flex-col gap-1",children:n.map(({ref:e,message:t})=>u(e,t))})]},t))]})})}async function ar(e){try{let t=await fetch(`/api/file${(0,s1.docQuery)(e)}`,{cache:"no-store"}),n=await t.json();if(!t.ok||n.error)return{path:e??"",content:null,exists:!1,error:n.error??`HTTP ${t.status}`};return{path:n.path??e??"",content:n.content??null,exists:!!n.exists,mtime:n.mtime}}catch(t){return{path:e??"",content:null,exists:!1,error:t instanceof Error?t.message:String(t)}}}class aa extends Error{constructor(e){super(`${e.split("/").pop()} changed on disk since it was read`)}}async function ai(e,t,n){let s=await fetch(`/api/file${(0,s1.docQuery)(e)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(t,null,2)+"\n",...void 0!==n?{mtime:n}:{}})}),r=await s.json().catch(()=>({}));if(409===s.status)throw new aa(e);if(!s.ok)throw Error(r?.error??`HTTP ${s.status}`);return r?.mtime}async function ao(e){let t=await ar(e),n={path:t.path||e,def:null,members:[],absOf:{},wrapped:{},mtimes:{}};if(t.error)return{...n,error:t.error};if(!t.exists||!t.content)return{...n,error:`${e} does not exist`};let s=null;try{let e=ex(JSON.parse(t.content));eY(e)&&(s=e)}catch{}if(!s)return{...n,error:`${t.path} is not a readable system definition`};let r={},a={},i={[t.path]:t.mtime??0},o=await Promise.all((s.members??[]).filter(e=>e?.path).map(async e=>{let n=eJ(t.path,e.path);r[e.path]=n;let s=eH(e.path),o=await ar(n);if(o.error)return{path:e.path,kind:s,def:null,error:o.error};if(!o.exists||!o.content)return{path:e.path,kind:s,def:null,error:"the file does not exist"};i[e.path]=o.mtime??0;try{let t=JSON.parse(o.content);if("machine"===s&&t&&(t.stateMachine||t.StateMachine))return a[e.path]=!0,{path:e.path,kind:s,def:ex(t.stateMachine??t.StateMachine)};return{path:e.path,kind:s,def:ex(t)}}catch(t){return{path:e.path,kind:s,def:null,error:`not JSON: ${t instanceof Error?t.message:String(t)}`}}}));return{path:t.path,def:s,members:o,absOf:r,wrapped:a,mtimes:i}}function al(){window.dispatchEvent(new Event(rj))}function ac(e){let[t,n]=(0,l.useState)(null),[s,r]=(0,l.useState)(0),a=(0,l.useCallback)(()=>r(e=>e+1),[]);return(0,l.useEffect)(()=>(window.addEventListener(rj,a),()=>window.removeEventListener(rj,a)),[a]),(0,l.useEffect)(()=>{if(!e)return;let t=!0;return ao(e).then(s=>t&&n({for:e,system:s})),()=>{t=!1}},[e,s]),{system:e&&t?.for===e?t.system:null,reload:a}}function ad(e,t){if(!e||!t)return null;for(let[n,s]of Object.entries(e.absOf))if(s===t)return n;return null}async function ah(e,t,n,s){let{bridgeUrl:r}=await re();if(!r)return;let a=sy({url:r,role:"web",docId:e,name:"web-reconcile",autoResync:!1});try{let e=await Promise.race([a.join(),new Promise((e,t)=>setTimeout(()=>t(Error("join timeout")),3e3))]),r=e.snapshot?.def,i=e=>(function(e){let t=JSON.stringify(e),n=0x811c9dc5;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,0x1000193);return(n>>>0).toString(16).padStart(8,"0")})(e);if(r&&i(r)===i(t))return;await new Promise(e=>{let o=a.on("ack",()=>{o(),e()});s&&r&&i(r)===i(s.from)?a.emitPatch(s.ops,n):a.emitFull(t,n),setTimeout(e,800)})}catch{}finally{a.disconnect()}}async function au(e,t){let n=[],s=[],r=[],a=async(e,t)=>{try{await t(),n.push(e)}catch(t){t instanceof aa?r.push(e):s.push(`${e}: ${t instanceof Error?t.message:String(t)}`)}};for(let n of t.machines){let t=e.absOf[n.member];t&&n.ops.length&&await a(n.member,async()=>{let s=e.wrapped[n.member]?{stateMachine:n.def}:n.def,r=await ai(t,s,e.mtimes[n.member]),a=e.members.find(e=>e.path===n.member)?.def;await ah(t,n.def,r,{from:a,ops:n.ops})})}for(let n of t.erds){let t=e.absOf[n.member];t&&await a(n.member,async()=>{let s=await ai(t,n.def,e.mtimes[n.member]);await ah(t,n.def,s)})}return t.system&&await a(e.path.split("/").pop()??e.path,async()=>{let n=await ai(e.path,t.system.def,e.mtimes[e.path]);await ah(e.path,t.system.def,n)}),al(),{written:n,failed:s,conflicts:r}}async function am(e){let t={result:null,written:[],failed:[],conflicts:[]};for(let n=0;n<2;n+=1){let s=await ao(e);if(!s.def)return{...t,failed:[s.error??"the system could not be read"],retried:n>0};let r=tr(s.def,s.members);if(!r.count)return{...t,result:r,conflicts:n?t.conflicts:[],retried:n>0};let a=await au(s,r);if(t={result:r,written:[...t.written,...a.written],failed:a.failed,conflicts:a.conflicts},!a.conflicts.length)return{...t,retried:n>0}}return{...t,retried:!0}}let ap="stateloom.sequence.view",af=["","actor","service","object"],ag=e=>"string"==typeof e?e.trim():"",ax=e=>ag(e).split(",").map(e=>e.trim()).filter(Boolean);function ay(e){return{from:ag(e.from),to:ag(e.to),label:ag(e.label),event:ag(e.event),machine:ag(e.machine),carries:ag(e.carries),state:ag(e.state),description:ag(e.description),optional:!!e.optional||void 0,reply:!!e.reply||void 0}}function ab(){let e,t,n,s=(0,s1.useRequestedDoc)(),r=rN("system"),{system:a}=ac(r),i=rC(),[c,d]=(0,l.useState)(""),[h,u]=(0,l.useState)(null),[m,p]=(0,l.useState)({...q}),[f,g]=(0,l.useState)(void 0),[x,y]=(0,l.useState)(null),[b,v]=(0,l.useState)({text:"loading…",tone:"ok"}),w=(0,l.useCallback)((e,t="ok")=>v({text:e,tone:t}),[]),[j,k]=(0,l.useState)(!1);(0,l.useEffect)(()=>{let e=setTimeout(()=>k(!0),4e3);return()=>{clearTimeout(e),k(!1)}},[b]);let[$,N]=(0,l.useState)("messages"),[S,M]=(0,l.useState)(!1),[C,E]=(0,l.useState)(!1),[R,_]=(0,l.useState)(!1),[A,T]=(0,l.useState)("diagram"),O=(0,l.useRef)("diagram");(0,l.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(ap)}catch{}let t="list"===e||"diagram"===e?e:window.matchMedia("(max-width: 767px)").matches?"list":"diagram";O.current=t,T(t)},[]);let P=(0,l.useCallback)(e=>{O.current=e,T(e);try{window.localStorage.setItem(ap,e)}catch{}},[]),I=(0,l.useRef)(null),L=rb({onClose:()=>M(!1),restVh:62,tallVh:92}),[D,F]=(0,l.useState)(0),U=(0,l.useRef)(null),Y=(0,l.useRef)(!0),X=(0,l.useRef)(-1);(0,l.useEffect)(()=>{let e=!1,t=null;return(async()=>{let n=await (await fetch(`/api/file${(0,s1.docQuery)(s)}`,{cache:"no-store"})).json();if(e)return;if(n.error)return w(n.error,"warn");let r=n.path??"",a=null;try{let e=n.content?ex(JSON.parse(n.content)):null;ej(e)&&(a=e)}catch{}if(n.exists&&!a)return w(`${r} is not a readable sequence definition`,"warn");let i=(r.split("/").pop()??"Untitled").replace(/\.sqdf\.json$/i,"");d(r),u(a??ek("Default",i)),w(n.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:o}=await re();!e&&o&&(U.current=t=sv({url:o,role:"web",docId:r,name:"web-designer",onFull:e=>{let t=e.def;ej(t)&&(u(t),w("updated live"))},onPatch:()=>{},onPresence:e=>F(e.length)}),t.connect())})().catch(t=>!e&&w(String(t),"warn")),()=>{e=!0,U.current=null,t?.disconnect()}},[s,w]);let V=(0,l.useMemo)(()=>h?tH(h):null,[h]),J=(0,l.useMemo)(()=>V?eD(V):null,[V]),W=(0,l.useMemo)(()=>V&&J?rJ(()=>(function(e,t){let n=[];for(let e of t.participants)n.push({focus:`participant:${e.name}`,box:{x:e.left,y:e.top,width:e.width,height:Math.max(e.height,t.lifelineBottom-e.top)}});let s=new Map(eS(e).map(e=>[e.ref,e.message]));for(let e of t.rows){let t=e.self?e.fromX:Math.min(e.fromX,e.toX),r=e.self?220:Math.max(40,Math.abs(e.toX-e.fromX)),a={x:t-10,y:e.y-24,width:r+20,height:40};n.push({focus:`message:${e.ref}`,box:a});let i=s.get(e.ref)?.event;i&&n.push({focus:`event:${i}`,box:a})}return n})(V,J),[]):[],[V,J]),K=rN("focus"),Z=(0,l.useMemo)(()=>{if(!h)return[];let e="";return rJ(()=>eM(h),null,t=>e=t)??[{ruleId:"S000",message:`The document could not be checked (${e}): a field is not the shape Spec 81 gives it`}]},[h]),G=ad(a,c),Q=(0,l.useMemo)(()=>a?.def&&G&&h?rJ(()=>e8(a.def,a.members.map(e=>e.path===G?{...e,def:h,error:void 0}:e)),null):null,[a,G,h]),ee=(0,l.useMemo)(()=>(Q?.issues??[]).filter(e=>e.member===G&&!/^S0/.test(e.ruleId)),[Q,G]),et=Q?.replays.find(e=>e.member===G)?.report??null,en=(0,l.useMemo)(()=>(function(e){let t={events:new Set,states:new Set,machines:new Set,objects:new Set,entities:new Set,actors:new Set};if(!e)return{events:[],states:[],machines:[],objects:[],entities:[],actors:[]};let{machines:n,erds:s}=e6(e.members);for(let{def:e}of(n.forEach(({def:e},n)=>{for(let s of(t.machines.add(e0(e,n)),e.events??[]))for(let e of[...s?.events??[],...s?.timers??[]])e?.id&&t.events.add(e.id);for(let n of e.settings?.objects??[])n?.instance&&t.objects.add(n.instance);let s=e=>{e&&(t.states.add(e.name),(e.states??[]).forEach(s),(e.parallel?.states??[]).forEach(s))};s(e.state)}),s))for(let n of e.entities??[])n?.name&&t.entities.add(n.name);for(let n of e.def?.actors??[])n?.name&&t.actors.add(n.name);let r=e=>[...e].sort((e,t)=>e.localeCompare(t));return{events:r(t.events),states:r(t.states),machines:r(t.machines),objects:r(t.objects),entities:r(t.entities),actors:r(t.actors)}})(a),[a]),es=(0,l.useMemo)(()=>{let e=e=>e?/^(message|participant):/.test(e)?e:V?.participants.some(t=>t.name===e)?`participant:${e}`:"":"";return[...Z.map(t=>e(t.element)),...ee.filter(e=>"error"===e.severity).map(t=>e(t.element))].filter(Boolean)},[Z,ee,V]),er=(0,l.useMemo)(()=>ee.filter(e=>"warning"===e.severity).map(e=>e.element??""),[ee]),ea=(0,l.useMemo)(()=>{let e=new Map,t=(t,n)=>{let s=t?/^(message|participant):/.test(t)?t:V?.participants.some(e=>e.name===t)?`participant:${t}`:"":"";s&&e.set(s,[...e.get(s)??[],n])};return Z.forEach(e=>t(e.element,{severity:"error",text:e.message})),ee.forEach(e=>t(e.element,{severity:"error"===e.severity?"error":"warning",text:e.message})),e},[Z,ee,V]),ei=()=>{let e=I.current?.getBoundingClientRect();return{width:e?.width??0,height:e?.height??0}},eo=(0,l.useCallback)(e=>{let t=I.current?.getBoundingClientRect();if(!t?.width)return;let n=B(Math.max(H([e],t.width,t.height,{padding:24,maxScale:1.1}).scale,.7));p({scale:n,x:t.width/2-(e.x+e.width/2)*n,y:t.height/2-(e.y+e.height/2)*n})},[]),el=(0,l.useCallback)(e=>{if(J)if("message"===e.kind){let t=J.rows.find(t=>t.ref===e.id);if(!t)return;let n=t.self?t.fromX:Math.min(t.fromX,t.toX),s=t.self?220:Math.abs(t.toX-t.fromX);eo({x:n-10,y:t.y-24,width:s+20,height:40})}else{let t=J.participants.find(t=>t.name===e.id);t&&eo({x:t.left-20,y:t.top,width:t.width+40,height:Math.min(260,J.height-t.top)})}},[J,eo]),ec=(0,l.useCallback)(e=>{if("diagram"===O.current)return el(e);requestAnimationFrame(()=>document.getElementById(an(e))?.scrollIntoView({block:"center",behavior:"smooth"}))},[el]),ed=(0,l.useCallback)(e=>{y(e),e&&rM(`${e.kind}:${e.id}`)},[]);(0,l.useEffect)(()=>{if(!h||!J||X.current===i.nonce)return;X.current=i.nonce;let e=i.focus?e9(i.focus):null;if(!e)return;let t=null;if("message"===e.kind&&eN(V??h,e.name)&&(t={kind:"message",id:e.name}),"participant"===e.kind&&(V??h).participants.some(t=>t.name===e.name)&&(t={kind:"participant",id:e.name}),!t)return w(`${i.focus} is not in this sequence`,"warn");Y.current=!1,y(t),ec(t)},[h,V,J,i,ec,w]),(0,l.useEffect)(()=>{if(!J||!Y.current||"diagram"!==A)return;let{width:e,height:t}=ei();e&&(Y.current=!1,Math.min((e-32)/J.width,(t-32)/J.height)>=.5||0===J.participants.length?g(e=>(e??0)+1):p({x:8,y:8,scale:.6}))},[J,A]);let eh=(0,l.useCallback)(async e=>{let t;if(h&&c){try{t=e(h)}catch(e){return w(e instanceof Error?e.message:String(e),"warn")}u(t);try{let e=await fetch(`/api/file${(0,s1.docQuery)(c)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(t,null,2)+"\n"})});if(!e.ok)throw Error((await e.json())?.error??`HTTP ${e.status}`);U.current?.emitFull(t),w("saved")}catch(e){return w(`not saved: ${e instanceof Error?e.message:String(e)}`,"warn")}if(a?.def&&G){if("auto"===eF(a.def)){let{result:e,failed:t,conflicts:s}=await am(a.path);if(e&&e.count>0){var n;return void(n=t.length?`auto: not written — ${t[0]}`:s.length?`auto: ${s.join(", ")} kept changing on disk; not written — save again`:ta(e,"auto"),window.dispatchEvent(new CustomEvent(rk,{detail:{text:n,origin:void 0}})))}}al()}}},[h,c,w,a,G]),eu=e=>{let{width:t,height:n}=ei();p(s=>z(s,e,{x:t/2,y:n/2}))},em=()=>{let e,t,n,s,r,a,i,o,l;h&&navigator.clipboard?.writeText((e=["sequenceDiagram"],t=new Map,(h.participants??[]).forEach((n,s)=>{let r=`p${s+1}`;t.set(n.name,r),e.push(` ${n.actor?"actor":"participant"} ${r} as ${eq(n.name)}`)}),n=e=>t.get(e)??eq(e).replace(/\W+/g,"_"),s=(e,t,s)=>{let r=e.reply?"-->>":"->>",a=[`${t} ${eq(e.label??"")}`,e.event?eq(e.event):""].filter(Boolean).join(" · "),i=`${s}${n(e.from)}${r}${n(e.to)}: ${a}`;return e.optional?[`${s}opt optional`,` ${i}`,`${s}end`]:[i]},r=h.messages??[],a=h.fragments??[],i=e=>a.filter(t=>t?.after===e),o=(t,n)=>(t.messages??[]).forEach((r,i)=>e.push(...s(r,`f${a.indexOf(t)+1}.${i+1}`,n+" "))),(l=(t,n,a)=>{for(let c=t;c<=r.length;c++){let t=c===a?[]:i(c);for(let s of t.filter(e=>"alt"!==e.kind))e.push(`${n}${s.kind} ${eq(s.label??"")}`),o(s,n),e.push(`${n}end`);let d=t.filter(e=>"alt"===e.kind);if(d.length){d.forEach((t,s)=>{e.push(`${n}${0===s?"alt":"else"} ${eq(t.label??"")}`),o(t,n)}),c<r.length&&(e.push(`${n}else as written`),l(c,n+" ",c)),e.push(`${n}end`);return}c<r.length&&e.push(...s(r[c],String(c+1),n))}})(0," ",null),e.join("\n")+"\n")).then(()=>w("mermaid copied"))},ep=e=>{let t=e?e9(e):null;if(!t||"message"!==t.kind&&"participant"!==t.kind)return;let n={kind:t.kind,id:t.name};ed(n),ec(n),L.close()},ef=V??ek("",""),eg=eS(ef),ey=h&&x?.kind==="message"?eN(ef,x.id):null,eb=h&&x?.kind==="participant"?ef.participants.find(e=>e.name===x.id)??null:null,ev=ef.participants.map(e=>e.name),e$=c.split("/").pop()||"…",eL=Z.length+ee.filter(e=>"error"===e.severity).length,eB=ee.filter(e=>"warning"===e.severity).length,eU=[{id:"participants",label:"Participants",icon:(0,o.jsx)(ae,{kind:"actor"})},{id:"messages",label:"Messages",icon:(0,o.jsx)(ae,{kind:"sequence"})},{id:"notes",label:"Notes",icon:"✎"},{id:"issues",label:"Issues",icon:(0,o.jsx)(rx,{}),badge:eL+eB||void 0}],ez=e=>[{name:"from",label:"from",options:ev,initial:e?.from??ev[0]??""},{name:"to",label:"to",options:ev,initial:e?.to??ev[1]??ev[0]??""},{name:"label",label:"label",placeholder:"what is said or done",initial:e?.label??"",wide:!0},{name:"event",label:"event it fires",suggest:en.events,initial:e?.event??""},{name:"state",label:"state after",suggest:en.states,initial:e?.state??""},{name:"carries",label:"entity it carries",suggest:en.entities,initial:e?.carries??""},{name:"machine",label:"machine",suggest:en.machines,initial:e?.machine??""},{name:"optional",label:"optional",checkbox:!0,initial:!!e?.optional},{name:"reply",label:"reply (dashed)",checkbox:!0,initial:!!e?.reply}],eY=e=>e.actor?"actor":e.object?"object":e.service?"service":"",eH=["main: at the end",...ey&&null===ey.fragment?[`main: after ${ey.index+1}`]:[],...(h?.fragments??[]).map((e,t)=>`fragment ${t+1}: ${e.kind} \xb7 ${e.label}`)];return(0,o.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&E(!1),children:[(0,o.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,o.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,o.jsx)(ae,{kind:"sequence",size:14}),"SEQ"]}),(0,o.jsx)(s2,{}),(0,o.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:c,children:[h?.settings.name??e$,(0,o.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",e$]})]}),(0,o.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(([e,t,n])=>(0,o.jsx)("button",{title:n,"aria-pressed":A===e,onClick:()=>{A!==e&&(x&&(Y.current=!1),P(e),x&&requestAnimationFrame(()=>ec(x)))},className:`px-2.5 py-1.5 ${A===e?"bg-gray-700 text-gray-100":"bg-gray-800 text-gray-400 hover:text-gray-200"}`,children:t},e))}),(0,o.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,o.jsx)("button",{className:r8,onClick:em,children:"Copy mermaid"}),(0,o.jsx)("button",{className:r8,onClick:()=>_(e=>!e),"aria-pressed":!R,title:R?"Show the panel":"Hide the panel — the board takes the full width",children:R?"⟨ Panel":"Panel ⟩"})]}),(0,o.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,o.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:e=>{e.stopPropagation(),E(e=>!e)},children:"⋯"}),C&&(0,o.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,o.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{E(!1),em()},children:"Copy as mermaid"})})]})]}),(0,o.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,o.jsxs)("div",{ref:I,className:"relative min-w-0 flex-1 overflow-hidden",children:[h&&J&&"list"===A&&V&&(0,o.jsx)(rg,{what:"sequence",resetKey:h,children:(0,o.jsx)(as,{definition:V,selection:x,issues:ea,onSelect:e=>ed(e),onShowInDiagram:e=>{Y.current=!1,P("diagram"),requestAnimationFrame(()=>el(e))}})}),h&&J&&"diagram"===A&&(0,o.jsx)(rg,{what:"sequence",resetKey:h,children:(0,o.jsx)(tX,{definition:V,layout:J,viewport:m,onViewportChange:p,selection:x,errorElements:es,warningElements:er,fitKey:f,onSelect:(e,t)=>ed({kind:e,id:t}),onClearSelection:()=>y(null),emptyHint:"No participants yet — add them in the panel, or let an agent write the scenario."})}),h&&J&&"diagram"===A&&(0,o.jsx)(rX,{docPath:c||null,kind:"sequence",viewport:m,setViewport:p,boxes:W,boardRef:I,focus:K}),h&&J&&"list"===A&&(0,o.jsx)(rV,{docPath:c,onReveal:()=>P("diagram")}),(0,o.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"===b.tone?"text-amber-300":"text-gray-500"} ${"list"===A&&j&&"ok"===b.tone?"hidden":"flex"}`,role:"status",children:[(0,o.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===b.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,o.jsxs)("span",{className:`truncate transition-opacity duration-500 ${j&&"ok"===b.tone?"opacity-0":"opacity-100"}`,children:[b.text,D>1?` \xb7 ${D} in the room`:""]})]}),(0,o.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"===A?"flex":"hidden"}`,children:[["+","Zoom in",()=>eu(1.25)],["−","Zoom out",()=>eu(.8)],["⛶","Fit the whole diagram",()=>g(e=>(e??0)+1)]].map(([e,t,n])=>(0,o.jsx)("button",{title:t,"aria-label":t,onClick:n,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:e},t))}),x&&!S&&(0,o.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:()=>{N("message"===x.kind?"messages":"participants"),M(!0)},children:["Edit ","message"===x.kind?`${x.id}. ${ey?.message.label??""}`:x.id]})]}),S&&(0,o.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:L.close,"aria-hidden":"true"}),h&&(0,o.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 ${S?"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 ${R?"md:hidden":""}`,children:[(0,o.jsxs)("div",{className:"md:hidden",...L.zoneProps,children:[(0,o.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,o.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,o.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,o.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:eU.find(e=>e.id===$)?.label}),(0,o.jsx)("button",{onClick:L.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,o.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:eU.map(e=>(0,o.jsxs)("button",{onClick:()=>N(e.id),className:`relative flex-1 px-1 py-2 text-center text-xs transition-colors ${$===e.id?"border-b-2 border-blue-400 bg-gray-800/50 text-blue-400":"text-gray-500 hover:text-gray-300"}`,children:[e.label,void 0!==e.badge&&(0,o.jsx)("span",{className:"absolute right-1 top-1 min-w-[14px] rounded-full bg-red-900 px-1 text-[9px] text-red-100",children:e.badge})]},e.id))}),(0,o.jsx)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:(0,o.jsxs)(rg,{what:"panel",resetKey:h,children:[(0,o.jsxs)("section",{className:"participants"===$?"":"hidden",children:[(0,o.jsx)("div",{className:r7,style:{marginTop:0},children:"Participants"}),(0,o.jsx)("div",{className:"flex flex-wrap gap-1",children:ef.participants.map(e=>(0,o.jsxs)("button",{className:`${r8} ${x?.kind==="participant"&&x.id===e.name?"border-blue-500 text-blue-300":""}`,onClick:()=>{ed({kind:"participant",id:e.name}),ec({kind:"participant",id:e.name})},title:eY(e)||"participant",children:[e.name,eY(e)&&(0,o.jsxs)("span",{className:"text-gray-500",children:[" · ",eY(e)]})]},e.name))}),(0,o.jsx)(r9,{id:"add-participant",reset:!0,required:["name"],fields:[{name:"name",placeholder:"new participant"},{name:"kind",options:af,label:"kind"},{name:"value",placeholder:"actor / service / object",suggest:[...en.actors,...en.objects]},{name:"holds",placeholder:"holds: Entity, Entity",suggest:en.entities}],submit:"+ Participant",onSubmit:e=>{let t=ag(e.name),n=ag(e.kind);eh(s=>(function(e,t,n){if(!t.name?.trim())throw Error("A participant needs a name.");let s=eC(e);if(s.participants.some(e=>e.name===t.name))throw Error(`Participant '${t.name}' already exists.`);let r=s.participants.length;return s.participants.splice(r,0,eE({...t})),s})(s,{name:t,...n?{[n]:ag(e.value)||t}:{},holds:ax(e.holds)})),ed({kind:"participant",id:t})}}),eb&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:`${r7} flex items-center justify-between gap-2`,children:[(0,o.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:eb.name}),(0,o.jsx)("button",{className:`${r8} normal-case tracking-normal`,onClick:()=>ec({kind:"participant",id:eb.name}),children:"◎ Show on board"})]}),(e=ef.participants.findIndex(e=>e.name===eb.name),t=ef.participants.length-1,n=e=>eh(t=>{var n;let s,r;return n=eb.name,r=eR(s=eC(t),n),s.participants.splice(s.participants.indexOf(r),1),s.participants.splice(Math.max(0,Math.min(e,s.participants.length)),0,r),s}),(0,o.jsxs)("div",{className:"mb-1 flex items-center gap-1 text-[11px] text-gray-400",children:[(0,o.jsx)("button",{className:`${r8} disabled:opacity-40`,disabled:e<=0,onClick:()=>n(e-1),"aria-label":"Move one column left",children:"← Left"}),(0,o.jsxs)("span",{className:"flex-1 text-center",children:["column ",e+1," of ",t+1]}),(0,o.jsx)("button",{className:`${r8} disabled:opacity-40`,disabled:e>=t,onClick:()=>n(e+1),"aria-label":"Move one column right",children:"Right →"})]})),(0,o.jsx)(r9,{id:"rename-participant",required:["to"],fields:[{name:"to",label:"new name",initial:eb.name}],submit:"Rename (every message follows)",onSubmit:e=>{let t=ag(e.to);t!==eb.name&&(eh(e=>(function(e,t,n){if(!n?.trim())throw Error("A participant needs a name.");let s=eC(e),r=eR(s,t);if(n===t)return s;if(s.participants.some(e=>e.name===n))throw Error(`Participant '${n}' already exists.`);r.name=n;let a=e=>{e.from===t&&(e.from=n),e.to===t&&(e.to=n)};for(let e of(s.messages.forEach(a),s.fragments??[]))e.messages.forEach(a);return s})(e,eb.name,t)),ed({kind:"participant",id:t}))}},`rename:${eb.name}`),(0,o.jsx)(r9,{id:"edit-participant",fields:[{name:"kind",options:af,label:"kind",initial:eY(eb)},{name:"value",placeholder:"actor / service / object",suggest:[...en.actors,...en.objects],initial:eb.actor??eb.object??eb.service??""},{name:"holds",placeholder:"holds: Entity, Entity",suggest:en.entities,initial:(eb.holds??[]).join(", "),wide:!0},{name:"description",placeholder:"description",initial:eb.description??"",wide:!0}],submit:"Save participant",onSubmit:e=>eh(t=>{let n,s;return eT(t,eb.name,{...(n=ag(e.kind),s=ag(e.value)||eb.name,{actor:"actor"===n?s:"",service:"service"===n?s:"",object:"object"===n?s:""}),holds:ax(e.holds),description:ag(e.description)})})},`p:${JSON.stringify(eb)}`),(0,o.jsxs)("button",{className:`${r8} mt-2 text-red-300`,onClick:()=>{eh(e=>{var t;let n,s;return t=eb.name,eR(n=eC(e),t),n.participants=n.participants.filter(e=>e.name!==t),s=e=>e.from!==t&&e.to!==t,n.messages=n.messages.filter(s),n.fragments&&(n.fragments=n.fragments.map(t=>{let n;return{...t,after:Math.max(0,t.after-(n=t.after,e.messages.slice(0,n).filter(e=>!s(e)).length)),messages:t.messages.filter(s)}}).filter(e=>e.messages.length>0),n.fragments.length||delete n.fragments),n}),y(null),rM(null)},title:"Also removes every message it sends or receives",children:["Delete ",eb.name," and its messages"]})]})]}),(0,o.jsxs)("section",{className:"messages"===$?"":"hidden",children:[(0,o.jsx)("div",{className:r7,style:{marginTop:0},children:"Messages"}),0===eg.length&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),(0,o.jsx)("div",{className:"flex flex-col",children:eg.map(({ref:e,message:t,fragment:n},s)=>{let r=null!==n&&(0===s||eg[s-1].fragment!==n),a=null!==n?ef.fragments?.[n]:void 0,i=x?.kind==="message"&&x.id===e;return(0,o.jsxs)("div",{children:[r&&a&&(0,o.jsxs)("div",{className:"mt-2 border-t border-gray-800 pt-1 text-[11px] text-indigo-300",children:[(0,o.jsx)("span",{className:"font-semibold",children:a.kind})," · after ",a.after," · ",a.label]}),(0,o.jsxs)("button",{className:`block w-full truncate rounded px-1 py-0.5 text-left text-[11px] ${i?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,onClick:()=>{ed({kind:"message",id:e}),ec({kind:"message",id:e})},title:`${t.from} → ${t.to}: ${t.label}`,children:[(0,o.jsxs)("span",{className:"text-gray-500",children:[e,"."]})," ",t.from," → ",t.to,": ",t.label,t.event?(0,o.jsxs)("span",{className:"text-blue-300",children:[" [",t.event,"]"]}):null,t.state?(0,o.jsxs)("span",{className:"text-emerald-400",children:[" → ",t.state]}):null,t.optional?(0,o.jsx)("span",{className:"text-gray-500",children:" opt"}):null]})]},e)})}),ey&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:`${r7} flex items-center justify-between gap-2`,children:[(0,o.jsxs)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:["Message ",x.id]}),(0,o.jsxs)("span",{className:"flex gap-1 normal-case tracking-normal",children:[null===ey.fragment&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("button",{className:r8,"aria-label":"Move up",title:"Move up",disabled:0===ey.index,onClick:()=>{eh(e=>eI(e,ey.index,ey.index-1)),ed({kind:"message",id:String(ey.index)})},children:"↑"}),(0,o.jsx)("button",{className:r8,"aria-label":"Move down",title:"Move down",disabled:ey.index>=ef.messages.length-1,onClick:()=>{eh(e=>eI(e,ey.index,ey.index+1)),ed({kind:"message",id:String(ey.index+2)})},children:"↓"})]}),(0,o.jsx)("button",{className:r8,onClick:()=>ec(x),children:"◎ Show"})]})]}),(0,o.jsx)(r9,{id:"edit-message",required:["label"],fields:[...ez(ey.message),{name:"description",placeholder:"description",initial:ey.message.description??"",wide:!0}],submit:"Save message",onSubmit:e=>eh(t=>eP(t,ey.index,ay(e),ey.fragment))},`m:${x.id}:${JSON.stringify(ey.message)}`),(0,o.jsxs)("button",{className:`${r8} mt-2 text-red-300`,onClick:()=>{eh(e=>(function(e,t,n=null){let s=eC(e);if(null!==n){let e=eA(s,n);if(!e.messages[t])throw Error(`Message ${t+1} not found in fragment ${n+1}.`);return e.messages.splice(t,1),s}if(!s.messages[t])throw Error(`Message ${t+1} not found. The sequence has ${s.messages.length}.`);if(s.messages.splice(t,1),s.fragments)for(let e of s.fragments)e.after>t&&(e.after-=1);return s})(e,ey.index,ey.fragment)),y(null),rM(null)},children:["Delete message ",x.id]})]}),(0,o.jsx)("div",{className:r7,children:"Add a message"}),(0,o.jsx)(r9,{id:"add-message",reset:!0,required:["label"],fields:[{name:"where",options:eH,label:"where",wide:!0},...ez()],submit:"+ Message",onSubmit:e=>{let t=ag(e.where),n=ay(e),s=/^fragment (\d+):/.exec(t),r=/^main: after (\d+)$/.exec(t);s?eh(e=>{var t;let r,a,i;return t=Number(s[1])-1,a=eA(r=eC(e),t),e_(r,n),i=a.messages.length,a.messages.splice(i,0,eE({...n})),r}):r?eh(e=>eO(e,n,Number(r[1]))):eh(e=>eO(e,n))}},`add:${eH.join("|")}:${ev.join("|")}`),(0,o.jsx)("div",{className:r7,children:"Fragments"}),0===(ef.fragments??[]).length&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None."}),(ef.fragments??[]).map((e,t)=>(0,o.jsxs)("div",{className:"mb-2 rounded border border-gray-800 p-1.5",children:[(0,o.jsxs)("div",{className:"flex items-center justify-between text-[11px] text-indigo-300",children:[(0,o.jsxs)("span",{children:[t+1,". ",(0,o.jsx)("span",{className:"font-semibold",children:e.kind})," · after ",e.after," · ",e.messages.length," message(s)"]}),(0,o.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":`Remove fragment ${t+1}`,onClick:()=>eh(e=>{let n;return eA(n=eC(e),t),n.fragments.splice(t,1),n.fragments.length||delete n.fragments,n}),children:"✕"})]}),(0,o.jsx)(r9,{id:`edit-fragment-${t}`,fields:[{name:"kind",options:ew,initial:e.kind},{name:"after",placeholder:"after message",initial:String(e.after)},{name:"label",placeholder:"the condition, in words",initial:e.label,wide:!0}],submit:"Save fragment",onSubmit:e=>eh(n=>(function(e,t,n){let s=eC(e),r=eA(s,t);if(void 0!==n.kind&&!ew.includes(n.kind))throw Error(`A fragment is one of ${ew.join(", ")}; got '${n.kind}'.`);if(void 0!==n.after&&(!Number.isInteger(n.after)||n.after<0||n.after>s.messages.length))throw Error(`A fragment branches after a main message, 0 to ${s.messages.length}; got ${n.after}.`);return s.fragments[t]={...eE({...r,...n,messages:void 0}),messages:r.messages??[]},s})(n,t,{kind:ag(e.kind),after:Number(ag(e.after)),label:ag(e.label)}))})]},`${t}:${JSON.stringify({...e,messages:void 0})}`)),(0,o.jsx)(r9,{id:"add-fragment",reset:!0,required:["label"],fields:[{name:"kind",options:ew},{name:"after",placeholder:"after message",initial:String(ey&&null===ey.fragment?ey.index+1:ef.messages.length)},{name:"label",placeholder:"the condition, in words",wide:!0},{name:"from",options:ev,label:"first message from"},{name:"to",options:ev,label:"to",initial:ev[1]??ev[0]??""},{name:"first",placeholder:"first message label (optional)",wide:!0}],submit:"+ Fragment",onSubmit:e=>eh(t=>(function(e,t){if(!ew.includes(t.kind))throw Error(`A fragment is one of ${ew.join(", ")}; got '${t.kind}'.`);if(!t.label?.trim())throw Error("A fragment needs a label: the condition in words.");let n=eC(e);if(!Number.isInteger(t.after)||t.after<0||t.after>n.messages.length)throw Error(`A fragment branches after a main message, 0 to ${n.messages.length}; got ${t.after}.`);for(let e of t.messages??[])e_(n,e);return(n.fragments??=[]).push({...eE({...t,messages:void 0}),messages:(t.messages??[]).map(e=>eE({...e}))}),n})(t,{kind:ag(e.kind),after:Number(ag(e.after)),label:ag(e.label),messages:ag(e.first)?[{from:ag(e.from),to:ag(e.to),label:ag(e.first)}]:[]}))},`add-fragment:${ef.messages.length}:${ey?.index??""}`)]}),(0,o.jsxs)("section",{className:"notes"===$?"":"hidden",children:[(0,o.jsx)("div",{className:r7,style:{marginTop:0},children:"Notes"}),(0,o.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,o.jsx)(r4,{label:"On this sequence",value:h.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:e=>eh(t=>{var n;let s;return n={notes:e},(s=eC(t)).settings=eE({...s.settings,...n}),s})},"sequence"),eb&&(0,o.jsx)(r4,{label:`On ${eb.name}`,value:eb.notes??"",placeholder:`A question or a decision about ${eb.name}…`,onSave:e=>eh(t=>eT(t,eb.name,{notes:e}))},`participant:${eb.name}`),ey&&(0,o.jsx)(r4,{label:`On message ${x.id}`,value:ey.message.notes??"",placeholder:"A question or a decision about this message…",onSave:e=>eh(t=>eP(t,ey.index,{notes:e},ey.fragment))},`message:${x.id}`),!x&&(0,o.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Select a participant or a message to leave a note on it."}),[...ef.participants.filter(e=>e.notes?.trim()),...eg.filter(e=>e.message.notes?.trim())].length>0&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:r7,children:"With notes"}),(0,o.jsxs)("div",{className:"flex flex-wrap gap-1",children:[ef.participants.filter(e=>e.notes?.trim()).map(e=>(0,o.jsx)("button",{className:r8,onClick:()=>ep(`participant:${e.name}`),children:e.name},`p${e.name}`)),eg.filter(e=>e.message.notes?.trim()).map(e=>(0,o.jsxs)("button",{className:r8,onClick:()=>ep(`message:${e.ref}`),children:["message ",e.ref]},`m${e.ref}`))]})]})]}),(0,o.jsxs)("section",{className:"issues"===$?"":"hidden",children:[(0,o.jsx)("div",{className:r7,style:{marginTop:0},children:"Issues"}),Z.map((e,t)=>(0,o.jsxs)("button",{className:"block w-full py-0.5 text-left text-[11px] text-red-300",onClick:()=>ep(e.element),children:["[",e.ruleId,"] ",e.message]},`p${t}`)),ee.map((e,t)=>(0,o.jsxs)("button",{className:`block w-full py-0.5 text-left text-[11px] ${"error"===e.severity?"text-red-300":"text-amber-300"}`,onClick:()=>ep(e.element),children:["[",e.ruleId,"] ",e.message]},`s${t}`)),0===Z.length&&0===ee.length&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-green-400",children:Q?"Valid, and every name it uses resolves in the system.":"The document is valid."}),!r&&(0,o.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."}),r&&!G&&a&&(0,o.jsx)("p",{className:"mt-2 text-[11px] text-amber-300",children:"This document is not a member of the open system."}),et&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:r7,children:["Replay against ",et.machines.join(", ")||"no machine"]}),et.paths.map(e=>(0,o.jsxs)("div",{className:"mb-2",children:[(0,o.jsxs)("div",{className:`text-[11px] font-semibold ${e.accepted?"text-green-400":"text-amber-300"}`,children:[e.name," — ",e.accepted?"accepted":"stops"]}),e.steps.filter(e=>"data"!==e.result).map(t=>(0,o.jsxs)("button",{className:`block w-full truncate py-0.5 pl-2 text-left font-mono text-[10.5px] ${"moved"===t.result||"stayed"===t.result?"text-gray-400":"text-amber-300"}`,title:t.note??t.result,onClick:()=>ep(`message:${t.ref}`),children:[t.ref,". ",t.event??""," ",t.from.join("|")||"·"," → ",t.to.join("|")||"·"," ",t.result]},`${e.name}:${t.ref}`))]},e.name))]})]})]})})]})]}),(0,o.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:eU.map(e=>{let t=S&&$===e.id;return(0,o.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(S&&$===t?L.close():M(!0),N(t))},"aria-pressed":t,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${t?"text-blue-400":"text-gray-500"}`,children:[(0,o.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,o.jsx)("span",{children:e.label}),void 0!==e.badge&&(0,o.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:e.badge}),t&&(0,o.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})})]})}function av(e,t){let n=e?.members.find(e=>e.path===t)?.def;return n?.settings?.name||(t.split("/").pop()??t).replace(/\.(smdf|erdf|sqdf|sysdf)\.json$|\.json$/i,"")}let aw=(e,t)=>e?.members.find(e=>e.path===t)?.kind??"machine";function aj(e){return"message"===e.kind?`message ${e.name}`:`${e.kind} ${e.name}`}function ak({systemPath:e}){let t=rN("doc"),n=rN("focus"),{system:s}=ac(e),[r,a]=(0,l.useState)(!1),[i,c]=(0,l.useState)(null),d=(0,l.useRef)(s);(0,l.useEffect)(()=>{d.current=s},[s]);let h=(0,l.useMemo)(()=>s?rJ(()=>te(s.members),[]):[],[s]),u=ad(s,t),m=!!s&&(t===s.path||t===e),p=u&&n?function(e,t,n){let s=e9(n);if(!s)return[];let r=e=>e.member===t&&e.kind===s.kind&&e.name===s.name,a=[];for(let t of e)r(t.from)?a.push({other:t.to,text:t.text,rule:t.rule}):r(t.to)&&a.push({other:t.from,text:t.back,rule:t.rule});return a}(h,u,n):[],f=function(e,t){if(!t)return[];let n=new Map;for(let s of e)for(let e of[s.from,s.to]){if(e.member!==t)continue;let s=e7(e);n.set(s,(n.get(s)??0)+1)}return[...n.entries()].sort((e,t)=>e[0].localeCompare(t[0]))}(h,u);(0,l.useEffect)(()=>{let e=e=>{let t=e.detail;t?.text&&c({...t,at:Date.now()})};return window.addEventListener(rk,e),()=>window.removeEventListener(rk,e)},[]),(0,l.useEffect)(()=>{if(!i)return;let e=setTimeout(()=>c(null),9e3);return()=>clearTimeout(e)},[i]);let g=s?.path;(0,l.useEffect)(()=>{if(!g)return;let t=!0,n=null,s=null;return(async()=>{let{bridgeUrl:r}=await re();if(t&&r){var i;let t,o,l,h;(n=sy({url:r,role:"web",docId:g,name:"web-system-strip"})).on("view",t=>{let n=d.current;if(!n)return;let s=t.member?void 0!==n.absOf[t.member]?t.member:Object.keys(n.absOf).find(e=>n.absOf[e]===t.member):void 0;if(t.member&&!s)return void c({text:`ignored a view of ${t.member.split("/").pop()}: it is not a member of this system`,origin:t.origin,at:Date.now()});rS({doc:s?n.absOf[s]:g,system:e,focus:t.focus??null}),a(!1);let r=[s?av(n,s):"the system map",t.focus].filter(Boolean).join(" · ");c({text:t.note?t.note:`showing ${r}`,origin:t.origin,at:Date.now()})}),n.on("full",()=>al()),i=n,t=!1,o=!1,l=()=>{i.join().then(()=>{t=!0}).catch(()=>{})},h=i.on("status",e=>{"connected"!==e?o=t:o&&(o=!1,l())}),l(),s=()=>{h()}}})(),()=>{t=!1,s?.(),n?.disconnect()}},[g,e]);let x=t=>{a(!1),s&&rS({doc:t.member?s.absOf[t.member]??eJ(s.path,t.member):s.path,system:e,focus:t.focus??null})},y=s?.def?.members?.filter(e=>e?.path).map(e=>e.path)??[],b=s?.def?.settings?.name??(e.split("/").pop()??"system").replace(/\.sysdf\.json$/i,""),v=p.length;return(0,o.jsxs)("div",{className:"system-strip relative z-50 border-b border-gray-800 bg-gray-950 text-xs text-gray-300",children:[(0,o.jsxs)("div",{className:"flex h-[var(--strip-h)] items-center gap-1 px-1.5 md:px-2",children:[(0,o.jsxs)("button",{onClick:()=>x({}),className:`flex min-w-0 max-w-[30%] shrink-0 items-center gap-1 rounded px-1.5 py-1 md:max-w-[16rem] ${m?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,title:`${e} — the system map`,children:[(0,o.jsx)(ae,{kind:"system",size:15}),(0,o.jsx)("span",{className:"truncate font-semibold",children:b})]}),(0,o.jsx)("span",{className:"h-4 w-px shrink-0 bg-gray-800"}),(0,o.jsxs)("nav",{className:"flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto [scrollbar-width:none]","aria-label":"Members",children:[y.map(e=>{let t=e===u,n=s?.members.find(t=>t.path===e)?.error;return(0,o.jsxs)("button",{onClick:()=>x({member:e}),"aria-current":t?"page":void 0,title:`${av(s,e)} — ${e}${n?` (cannot be read: ${n})`:""}`,className:`flex shrink-0 items-center gap-1 rounded px-1.5 py-1 ${t?"bg-blue-950/60 text-blue-200":n?"text-red-400 hover:bg-gray-800":"text-gray-400 hover:bg-gray-800 hover:text-gray-200"}`,children:[(0,o.jsx)(ae,{kind:aw(s,e),size:15}),(0,o.jsx)("span",{className:`max-w-[7.5rem] truncate md:max-w-[11rem] ${t?"":"hidden md:inline"}`,children:av(s,e)})]},e)}),!s&&(0,o.jsx)("span",{className:"px-1 text-gray-600",children:"loading…"}),s?.error&&(0,o.jsx)("span",{className:"truncate px-1 text-amber-300",children:s.error})]}),(0,o.jsxs)("button",{onClick:()=>a(e=>!e),disabled:!u,"aria-expanded":r,title:u?n?`What ${n} 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 ${r?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,children:[(0,o.jsx)(ae,{kind:"link",size:15}),(0,o.jsx)("span",{className:"hidden sm:inline",children:"Links"}),v>0&&(0,o.jsx)("span",{className:"rounded-full border border-gray-700 px-1 text-[10px] leading-4 text-gray-300",children:v})]})]}),i&&!r&&(0,o.jsx)("div",{className:"pointer-events-none absolute inset-x-0 top-full flex justify-center px-2 pt-1",role:"status",children:(0,o.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:[i.origin?(0,o.jsxs)("span",{className:"text-blue-300",children:[i.origin,": "]}):null,i.text]})}),r&&u&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:"fixed inset-0 z-40",onClick:()=>a(!1),"aria-hidden":"true"}),(0,o.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:[n&&e9(n)?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:"mb-1 flex items-center justify-between gap-2 text-[11px] text-gray-500",children:[(0,o.jsxs)("span",{className:"truncate",children:[(0,o.jsx)("span",{className:"text-gray-200",children:aj(e9(n))})," in ",av(s,u)]}),(0,o.jsx)("button",{className:"shrink-0 text-gray-500 hover:text-gray-200",onClick:()=>rS({doc:t,focus:null}),children:"clear"})]}),0===p.length&&(0,o.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"Nothing in the other drawings names it."}),p.map((e,t)=>(0,o.jsxs)("button",{onClick:()=>x({member:e.other.member,focus:e7(e.other)}),className:"flex w-full items-start gap-2 rounded px-1.5 py-1.5 text-left hover:bg-gray-800",children:[(0,o.jsx)("span",{className:"mt-0.5 text-gray-400",children:(0,o.jsx)(ae,{kind:aw(s,e.other.member),size:14})}),(0,o.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,o.jsx)("span",{className:"block text-[12px] text-gray-200",children:e.text}),(0,o.jsxs)("span",{className:"block truncate text-[10.5px] text-gray-500",children:[aj(e.other)," · ",av(s,e.other.member)," · ",e.rule]})]})]},t))]}):null,(!n||!e9(n))&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["Elements of ",av(s,u)," that the other drawings name — pick one to follow it."]}),0===f.length&&(0,o.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"None."}),(0,o.jsx)("div",{className:"flex flex-wrap gap-1",children:f.map(([e,n])=>(0,o.jsxs)("button",{onClick:()=>{a(!0),rS({doc:t,focus:e})},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:[e," ",(0,o.jsx)("span",{className:"text-gray-500",children:n})]},e))})]})]})]})]})}let a$={erd:"ERD",machine:"STATE MACHINE",sequence:"SEQUENCE",system:"SYSTEM"};function aN(e,t,n=!1){if(!t)return"";if("erd"===e)return`${t.entities?.length??0} entities \xb7 ${t.relationships?.length??0} relationships`;if("sequence"===e){let e=t.fragments?.length??0;return`${t.participants?.length??0} participants \xb7 ${t.messages?.length??0} messages${e&&!n?` \xb7 ${e} fragment${e>1?"s":""}`:""}`}let s=0,r=e=>{e&&(s+=1,(e.states??[]).forEach(r),(e.parallel?.states??[]).forEach(r))};(t.state?.states??[]).forEach(r),(t.state?.parallel?.states??[]).forEach(r);let a=(t.events??[]).reduce((e,t)=>e+(t?.events?.length??0)+(t?.timers?.length??0),0);return`${s} states \xb7 ${a} events`}let aS=(e,t)=>e<t?`${e}\u0000${t}`:`${t}\u0000${e}`;function aM(e){let t="message"===e.from.kind?`message ${e.from.name}`:`${e.from.kind} ${e.from.name}`;return`${t} ${e.text}`}function aC(){let e=(0,s1.useRequestedDoc)(),[t,n]=(0,l.useState)(e);(0,l.useEffect)(()=>{let t=!0;return e?n(e):r$("doc")||ar(null).then(e=>t&&n(e.path||null)),()=>{t=!1}},[e]);let{system:s,reload:r}=ac(t),[a,i]=(0,l.useState)("members"),[c,d]=(0,l.useState)(!1),[h,u]=(0,l.useState)(!1),[m,p]=(0,l.useState)(!1),[f,g]=(0,l.useState)(null),[x,y]=(0,l.useState)({text:"loading…",tone:"ok"}),b=(0,l.useCallback)((e,t="ok")=>y({text:e,tone:t}),[]),[v,w]=(0,l.useState)(!1),j=rb({onClose:()=>d(!1),restVh:62,tallVh:92}),k=(0,l.useRef)(null),[$,N]=(0,l.useState)(!1);(0,l.useEffect)(()=>{let e=k.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();t.width&&N(t.height>1.1*t.width)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let S=(0,l.useRef)(!1);(0,l.useEffect)(()=>{s&&(s.error?b(s.error,"warn"):S.current||b(`${s.members.length} member${1===s.members.length?"":"s"} loaded`),S.current=!0)},[s,b]);let[M,C]=(0,l.useState)(!1);(0,l.useEffect)(()=>{let e=setTimeout(()=>C(!0),4e3);return()=>{clearTimeout(e),C(!1)}},[x]);let E=(0,l.useMemo)(()=>s?.def?rJ(()=>e8(s.def,s.members),null):null,[s]),R=(0,l.useMemo)(()=>s?rJ(()=>te(s.members),[]):[],[s]),_=(0,l.useMemo)(()=>s?.def?rJ(()=>tr(s.def,s.members),null):null,[s]),A=eF(s?.def),T=(0,l.useMemo)(()=>{let e=new Map;for(let t of R){if(t.from.member===t.to.member)continue;let n=aS(t.from.member,t.to.member),s=e.get(n)??{a:n.split("\0")[0],b:n.split("\0")[1],links:[]};s.links.push(t),e.set(n,s)}return e},[R]),O=(E?.issues??[]).filter(e=>"error"===e.severity),P=(E?.issues??[]).filter(e=>"warning"===e.severity),I=(t,n)=>{s&&rS({doc:s.absOf[t]??t,system:e??s.path,focus:n??null})},L=async(e,t)=>{if(s)try{await ai(s.path,e,s.mtimes[s.path]),b(t),al()}catch(e){e instanceof aa?(b("the system changed on disk — reloaded; make the change again","warn"),al()):b(`not saved: ${e instanceof Error?e.message:String(e)}`,"warn")}},D=async()=>{if(!s||!_||!_.count)return;w(!0);let{result:e,written:t,failed:n,conflicts:r}=await am(s.path);w(!1),n.length?b(`not all written: ${n.join("; ")}`,"warn"):r.length?b(`${r.join(", ")} kept changing on disk — not written; apply again`,"warn"):e?.count?b(`${ta(e,"propose").replace(/ proposed/," applied")} — ${t.length} file(s) written`):b("nothing to apply: the drawings on disk already agree")},q=$?420:760,B=$?640:520,F=s?.def?.members?.filter(e=>e?.path).map(e=>e.path)??[],U=s?.def?.actors??[],z=64*!!U.length,Y=(0,l.useMemo)(()=>{let e=F.length,t=q/2,n=(B-z)/2+6,s=Math.max(0,q/2-98-16),r=Math.max(0,(B-z)/2-46-18),a=new Map;return F.forEach((i,o)=>{if(1===e)return a.set(i,{x:t,y:n});if($){let t=B-z-46-16;return a.set(i,{x:o%2?.67*q:.33*q,y:62+(t-62)*o/(e-1)})}if(2===e)return a.set(i,$?{x:t,y:o?n+r:n-r}:{x:o?t+s:t-s,y:n});let l=-Math.PI/2+2*o*Math.PI/e;a.set(i,{x:t+s*Math.cos(l),y:n+r*Math.sin(l)})}),a},[F.join("|"),q,B,196,z,$]),H=(0,l.useMemo)(()=>{let e=new Map;for(let{member:t,def:n}of e6(s?.members??[]).sequences)for(let s of n.participants??[]){if(!s?.actor)continue;let n=e.get(s.actor)??[];n.includes(t)||n.push(t),e.set(s.actor,n)}return e},[s]),X=s?.def,V=(s?.path??t??"").split("/").pop()||"…",J=[{id:"members",label:"Members",icon:(0,o.jsx)(ae,{kind:"system"})},{id:"checks",label:"Checks",icon:(0,o.jsx)(rx,{}),badge:O.length+P.length||void 0},{id:"notes",label:"Notes",icon:"✎"}],W=f?T.get(f):void 0,K=(0,l.useMemo)(()=>{let e=[];for(let t of["error","warning"]){let n=new Map;for(let e of E?.issues??[])e.severity===t&&n.set(e.ruleId,[...n.get(e.ruleId)??[],e]);for(let[s,r]of[...n.entries()].sort((e,t)=>e[0].localeCompare(t[0])))e.push({key:`${t}:${s}`,ruleId:s,severity:t,issues:r})}return e},[E]);return(0,o.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>h&&u(!1),children:[(0,o.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,o.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,o.jsx)(ae,{kind:"system",size:14}),"SYS"]}),(0,o.jsx)(s2,{}),(0,o.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:s?.path,children:[X?.settings?.name??V,(0,o.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",V]})]}),(0,o.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,o.jsx)("button",{className:r8,onClick:r,title:"Read the system and every member again",children:"Re-check"}),(0,o.jsx)("button",{className:r8,onClick:()=>p(e=>!e),"aria-pressed":!m,children:m?"⟨ Panel":"Panel ⟩"})]}),(0,o.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,o.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":h,onClick:e=>{e.stopPropagation(),u(e=>!e)},children:"⋯"}),h&&(0,o.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,o.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{u(!1),r()},children:"Re-check the system"})})]})]}),(0,o.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,o.jsxs)("div",{ref:k,className:"relative min-w-0 flex-1 overflow-hidden bg-[#030712]",children:[s&&X&&(0,o.jsx)(rg,{what:"system map",resetKey:s,children:(0,o.jsxs)("svg",{className:"h-full w-full",viewBox:`0 0 ${q} ${B}`,preserveAspectRatio:"xMidYMid meet",role:"img","aria-label":`System map of ${X.settings?.name}`,children:[[...T.entries()].map(([e,t])=>{let n=Y.get(t.a),s=Y.get(t.b);if(!n||!s)return null;let r=(n.x+s.x)/2,a=(n.y+s.y)/2,l=`${t.links.length} link${1===t.links.length?"":"s"}`,c=6.4*l.length+16,h=f===e;return(0,o.jsxs)("g",{className:"cursor-pointer",onClick:()=>{g(h?null:e),i("members"),d(!0)},children:[(0,o.jsx)("line",{x1:n.x,y1:n.y,x2:s.x,y2:s.y,stroke:"transparent",strokeWidth:18}),(0,o.jsx)("line",{x1:n.x,y1:n.y,x2:s.x,y2:s.y,stroke:h?"#3b82f6":"#475569",strokeWidth:h?2.5:1.6}),(0,o.jsx)("rect",{x:r-c/2,y:a-11,width:c,height:22,rx:11,fill:"#0f172a",stroke:h?"#3b82f6":"#334155"}),(0,o.jsx)("text",{x:r,y:a+4,textAnchor:"middle",fontSize:11.5,fill:h?"#93c5fd":"#cbd5e1",children:l})]},e)}),U.map((e,t)=>{let n=(t+1)*q/(U.length+1),s=B-30;return(0,o.jsxs)("g",{children:[(H.get(e.name)??[]).map(e=>{let t=Y.get(e);return t?(0,o.jsx)("line",{x1:n,y1:s-14,x2:t.x,y2:t.y+46,stroke:"#334155",strokeDasharray:"3 4"},e):null}),(0,o.jsx)("title",{children:[`${e.kind}`,e.description??"",e.wheelNode??""].filter(Boolean).join(" — ")}),(0,o.jsx)("rect",{x:n-62,y:s-14,width:124,height:28,rx:14,fill:"#0c1020",stroke:"#6366f1"}),(0,o.jsx)("g",{transform:`translate(${n-54} ${s-8})`,color:"#a5b4fc",children:(0,o.jsx)(ae,{kind:"actor",size:16})}),(0,o.jsx)("text",{x:n-34,y:s-1,fontSize:11.5,fontWeight:600,fill:"#e2e8f0",children:e.name.length>12?`${e.name.slice(0,11)}…`:e.name}),(0,o.jsx)("text",{x:n-34,y:s+9,fontSize:8.5,fill:"#94a3b8",children:e.kind})]},e.name)}),F.map(e=>{let t=Y.get(e),n=s.members.find(t=>t.path===e);if(!t||!n)return null;let r=n.kind,a=(E?.issues??[]).filter(t=>t.member===e),i=a.filter(e=>"error"===e.severity).length,l=a.filter(e=>"warning"===e.severity).length,c=t.x-98,d=t.y-46,h=av(s,e),u=W&&(W.a===e||W.b===e);return(0,o.jsxs)("g",{className:"cursor-pointer",onClick:()=>I(e),children:[(0,o.jsx)("title",{children:`${e}${n.error?` — cannot be read: ${n.error}`:""}
14
- Tap to open it inside the system.`}),(0,o.jsx)("rect",{x:c,y:d,width:196,height:92,rx:10,fill:"#0f172a",stroke:n.error?"#ef4444":u?"#3b82f6":i?"#b91c1c":"#475569",strokeWidth:u?2.2:1.5,strokeDasharray:n.error?"5 4":void 0}),(0,o.jsx)("g",{transform:`translate(${c+10} ${d+9})`,color:"#93c5fd",children:(0,o.jsx)(ae,{kind:r,size:16})}),(0,o.jsx)("text",{x:c+32,y:d+21,fontSize:9,fontWeight:700,letterSpacing:"0.06em",fill:"#64748b",children:a$[r]}),(0,o.jsx)("text",{x:c+10,y:d+43,fontSize:14,fontWeight:600,fill:"#e2e8f0",children:h.length>22?`${h.slice(0,21)}…`:h}),(0,o.jsx)("text",{x:c+10,y:d+60,fontSize:10.5,fill:"#94a3b8",children:n.error?"cannot be read":aN(r,n.def,!0)}),(0,o.jsx)("text",{x:c+10,y:d+79,fontSize:10.5,fill:i?"#fca5a5":l?"#fcd34d":"#4ade80",children:n.error?n.error.length>30?`${n.error.slice(0,29)}…`:n.error:i||l?[i?`${i} error${i>1?"s":""}`:"",l?`${l} warning${l>1?"s":""}`:""].filter(Boolean).join(" · "):"checks pass"}),(0,o.jsx)("text",{x:c+196-10,y:d+79,fontSize:10.5,textAnchor:"end",fill:"#64748b",children:"open ›"})]},e)})]})}),s&&!X&&(0,o.jsx)("div",{className:"absolute inset-0 flex items-center justify-center p-6 text-center text-sm text-amber-300",children:s.error}),(0,o.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"===x.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,o.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===x.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,o.jsx)("span",{className:`truncate transition-opacity duration-500 ${M&&"ok"===x.tone?"opacity-0":"opacity-100"}`,children:x.text})]})]}),c&&(0,o.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:j.close,"aria-hidden":"true"}),s&&X&&(0,o.jsxs)("aside",{style:j.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 ${c?"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 ${m?"md:hidden":""}`,children:[(0,o.jsxs)("div",{className:"md:hidden",...j.zoneProps,children:[(0,o.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,o.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,o.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,o.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:J.find(e=>e.id===a)?.label}),(0,o.jsx)("button",{onClick:j.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,o.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:J.map(e=>(0,o.jsxs)("button",{onClick:()=>i(e.id),className:`relative flex-1 px-1 py-2 text-center text-xs transition-colors ${a===e.id?"border-b-2 border-blue-400 bg-gray-800/50 text-blue-400":"text-gray-500 hover:text-gray-300"}`,children:[e.label,void 0!==e.badge&&(0,o.jsx)("span",{className:"absolute right-1 top-1 min-w-[14px] rounded-full bg-red-900 px-1 text-[9px] text-red-100",children:e.badge})]},e.id))}),(0,o.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,o.jsxs)("section",{className:"members"===a?"":"hidden",children:[(0,o.jsx)("div",{className:r7,style:{marginTop:0},children:"Members"}),F.map(e=>{let t=s.members.find(t=>t.path===e),n=X.members.find(t=>t.path===e)?.notes;return(0,o.jsxs)("div",{className:"mb-1 rounded border border-gray-800",children:[(0,o.jsxs)("button",{onClick:()=>I(e),className:"flex w-full items-start gap-2 p-2 text-left hover:bg-gray-800",children:[(0,o.jsx)("span",{className:"mt-0.5 text-blue-300",children:(0,o.jsx)(ae,{kind:t?.kind??"machine"})}),(0,o.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,o.jsx)("span",{className:"block truncate text-[12px] font-semibold text-gray-200",children:av(s,e)}),(0,o.jsx)("span",{className:"block truncate text-[10.5px] text-gray-500",children:e}),(0,o.jsx)("span",{className:`block text-[11px] ${t?.error?"text-red-300":"text-gray-400"}`,children:t?.error?`cannot be read: ${t.error}`:aN(t?.kind??"machine",t?.def)})]}),(0,o.jsx)("span",{className:"shrink-0 text-[11px] text-gray-500",children:"open ›"})]}),(0,o.jsx)("div",{className:"px-2 pb-2 [&_label]:mt-0",children:(0,o.jsx)(r4,{label:"Note on this member, in the system",value:n??"",placeholder:`Why ${av(s,e)} is part of this system, what is open…`,onSave:t=>void L(function(e,t,n){let s=eK(e),r=s.members.findIndex(e=>e.path===t);if(r<0)throw Error(`'${t}' is not a member. Members: ${e.members.map(e=>e.path).join(", ")||"none"}.`);return s.members[r]=eZ({...s.members[r],...n}),s}(X,e,{notes:t}),"saved")},`member:${e}`)})]},e)}),(0,o.jsx)("div",{className:r7,children:"Links between members"}),0===T.size&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"No name crosses between the members yet."}),[...T.entries()].map(([e,t])=>(0,o.jsxs)("div",{className:"mb-1",children:[(0,o.jsxs)("button",{className:`flex w-full items-center justify-between rounded px-1.5 py-1 text-left text-[11px] ${f===e?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,onClick:()=>g(f===e?null:e),children:[(0,o.jsxs)("span",{className:"truncate",children:[av(s,t.a)," ↔ ",av(s,t.b)]}),(0,o.jsx)("span",{className:"shrink-0 text-gray-500",children:t.links.length})]}),f===e&&(0,o.jsx)("div",{className:"ml-2 border-l border-gray-800 pl-2",children:t.links.map((e,t)=>(0,o.jsxs)("button",{className:"block w-full truncate py-0.5 text-left text-[11px] text-gray-400 hover:text-gray-200",title:`${aM(e)} — ${e.rule}`,onClick:()=>{let t;return I((t=e.from).member,e7(t))},children:[(0,o.jsx)("span",{className:"text-gray-600",children:e.rule})," ",aM(e)]},t))})]},e)),U.length>0&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:r7,children:"Actors"}),U.map(e=>(0,o.jsxs)("div",{className:"py-0.5 text-[11px] text-gray-300",children:[e.name," ",(0,o.jsxs)("span",{className:"text-gray-500",children:["· ",e.kind]}),e.description?(0,o.jsxs)("span",{className:"text-gray-500",children:[" — ",e.description]}):null]},e.name))]})]}),(0,o.jsxs)("section",{className:"checks"===a?"":"hidden",children:[(0,o.jsx)("div",{className:r7,style:{marginTop:0},children:"Checks"}),(0,o.jsxs)("div",{className:`text-[11px] ${O.length?"text-red-300":P.length?"text-amber-300":"text-green-400"}`,children:[O.length," error",1===O.length?"":"s"," · ",P.length," warning",1===P.length?"":"s"]}),K.map(e=>(0,o.jsxs)("div",{className:"mt-2",children:[(0,o.jsxs)("div",{className:`text-[11px] font-semibold ${"error"===e.severity?"text-red-300":"text-amber-300"}`,children:[e.ruleId," · ",e.issues.length," ",e.severity,1===e.issues.length?"":"s"]}),e.issues.map((e,t)=>(0,o.jsxs)("button",{className:"block w-full py-0.5 pl-2 text-left text-[11px] text-gray-300 hover:text-white",onClick:()=>{e.member&&I(e.member,e.element&&/^[a-z]+:/.test(e.element)?e.element:null)},title:e.member?`Open ${e.member}${e.element?` at ${e.element}`:""}`:void 0,children:[e.message,e.member&&(0,o.jsxs)("span",{className:"text-gray-500",children:[" — ",av(s,e.member)]})]},t))]},e.key)),(0,o.jsx)("div",{className:r7,children:"Reconcile"}),(0,o.jsxs)("p",{className:"mb-1 text-[11px] text-gray-500",children:["What the scenarios imply for the machines and the data. ",(0,o.jsx)("b",{className:"text-gray-400",children:"propose"})," lists it here to apply by hand; ",(0,o.jsx)("b",{className:"text-gray-400",children:"auto"})," writes it each time a scenario is saved."]}),(0,o.jsx)("span",{className:"inline-flex overflow-hidden rounded border border-gray-700",role:"group","aria-label":"Reconcile mode",children:eB.map(e=>(0,o.jsx)("button",{"aria-pressed":A===e,onClick:()=>{s?.def&&e!==A&&L(function(e,t){if(!eB.includes(t))throw Error(`The reconcile mode is ${eB.join(" or ")}; got '${t}'.`);return eG(e,{reconcile:t})}(s.def,e),`reconcile mode: ${e}`)},className:`px-3 py-1 text-xs ${A===e?"bg-blue-900/60 text-blue-200":"bg-gray-800 text-gray-400 hover:bg-gray-700"}`,children:e},e))}),(0,o.jsx)("div",{className:"mt-2 text-[11px] font-semibold text-gray-400",children:"Scenario changes"}),_&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:"text-[11px] text-gray-500",children:ta(_,"propose")}),_.machines.map(e=>(0,o.jsxs)("div",{className:"mt-1",children:[(0,o.jsxs)("div",{className:"text-[11px] text-gray-300",children:[e.machine," ",(0,o.jsxs)("span",{className:"text-gray-500",children:["· ",e.member]})]}),e.reasons.map((e,t)=>(0,o.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",e]},t))]},e.member)),_.erds.map(e=>(0,o.jsxs)("div",{className:"mt-1",children:[(0,o.jsxs)("div",{className:"text-[11px] text-gray-300",children:[e.def.settings?.name??e.member," ",(0,o.jsxs)("span",{className:"text-gray-500",children:["· ",e.member]})]}),e.reasons.map((e,t)=>(0,o.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",e]},t))]},e.member)),_.system&&(0,o.jsxs)("div",{className:"mt-1",children:[(0,o.jsx)("div",{className:"text-[11px] text-gray-300",children:"the system"}),_.system.reasons.map((e,t)=>(0,o.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",e]},t))]}),_.unresolved.map((e,t)=>(0,o.jsxs)("div",{className:"mt-1 text-[11px] text-amber-300",children:["left open: ",e]},t)),(0,o.jsx)("button",{className:`${r8} mt-2 disabled:opacity-40`,disabled:!_.count||v,onClick:D,children:v?"Applying…":`Apply${_.count?` ${_.count} change${1===_.count?"":"s"}`:""}`})]}),(E?.replays??[]).map(({member:e,report:t})=>(0,o.jsxs)("div",{children:[(0,o.jsxs)("div",{className:r7,children:["Replay · ",av(s,e)]}),(0,o.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["against ",t.machines.join(", ")||"no machine"]}),t.paths.map(t=>(0,o.jsxs)("div",{className:"mb-2",children:[(0,o.jsxs)("div",{className:`text-[11px] font-semibold ${t.accepted?"text-green-400":"text-amber-300"}`,children:[t.name," — ",t.accepted?"accepted":"stops"]}),t.steps.filter(e=>"data"!==e.result).map(n=>(0,o.jsxs)("button",{className:`block w-full truncate py-0.5 pl-2 text-left font-mono text-[10.5px] ${"moved"===n.result||"stayed"===n.result?"text-gray-400":"text-amber-300"}`,title:n.note??n.result,onClick:()=>I(e,`message:${n.ref}`),children:[n.ref,". ",n.event??""," ",n.from.join("|")||"·"," → ",n.to.join("|")||"·"," ",n.result]},`${t.name}:${n.ref}`))]},t.name))]},e))]}),(0,o.jsxs)("section",{className:"notes"===a?"":"hidden",children:[(0,o.jsx)("div",{className:r7,style:{marginTop:0},children:"Notes"}),(0,o.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the system file, for whoever opens it next."}),(0,o.jsx)(r4,{label:"On this system",value:X.settings?.notes??"",placeholder:"What the system is for, what is still open…",onSave:e=>void L(eG(X,{notes:e}),"saved")},"system"),X.settings?.description&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:r7,children:"Description"}),(0,o.jsx)("p",{className:"text-[11px] text-gray-400",children:X.settings.description})]})]})]})]})]}),(0,o.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:J.map(e=>{let t=c&&a===e.id;return(0,o.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(c&&a===t?j.close():d(!0),i(t))},"aria-pressed":t,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${t?"text-blue-400":"text-gray-500"}`,children:[(0,o.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,o.jsx)("span",{children:e.label}),void 0!==e.badge&&(0,o.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:e.badge}),t&&(0,o.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})})]})}function aE(){let e=sP(e=>e.definition),t=sP(e=>e.layout.positions),n=sP(e=>e.navigationPath),s=sP(e=>e.viewport),r=sP(e=>e.setViewport),a=sP(e=>e.docPath),i=rN("focus"),c=(0,l.useMemo)(()=>({get current(){return document.getElementById("machine-board")}}),[]),d=n.slice(1),h=(0,l.useMemo)(()=>e?.state?function(e,t){let n=[];for(let s of e){let e=s?.name?t[s.name]:void 0;e&&n.push({focus:`state:${s.name}`,box:e})}for(let s of e){let r=s?.name?t[s.name]:void 0;if(r)for(let a of s.transitions??[]){if(!a?.event)continue;let s=a.nextState?t[a.nextState]:void 0;n.push({focus:`event:${a.event}`,box:s&&e.some(e=>e.name===a.nextState)?tx([r,s]):r})}}return n}(t$(e.state,d),t):[],[e,t,n]);return(0,o.jsx)(rX,{docPath:a,kind:"machine",viewport:s,setViewport:r,boxes:h,boardRef:c,focus:i,level:n[n.length-1],onReveal:e=>{let t=e.map(e9).find(e=>e?.kind==="state");if(!t)return;let n=new URL(window.location.href);n.searchParams.set("focus",`state:${t.name}`),window.history.replaceState(window.history.state,"",n),window.dispatchEvent(new Event(rw))}})}let aR=e=>e.parallel?e.parallel.states:e.states??[];function a_(e,t){if(!e)return null;if(e.name===t)return[e.name];for(let n of aR(e)){let s=a_(n,t);if(s)return[e.name,...s]}return null}function aA(){let e=(0,s1.useRequestedDoc)(),t=rN("system"),[n,s]=(0,l.useState)(null);(0,l.useEffect)(()=>{let e=!0;return re().then(t=>{e&&s(t.projectFile?eH(t.projectFile):"machine")}),()=>{e=!1}},[]);let r=e?eH(e):n;if(null===r)return(0,o.jsx)("div",{className:"app-shell bg-gray-950"});let a=e??"default",i="erd"===r?(0,o.jsx)(r5,{},a):"sequence"===r?(0,o.jsx)(ab,{},a):"system"===r?(0,o.jsx)(aC,{},a):(0,o.jsx)(aT,{}),c=(0,o.jsx)(rg,{what:"document",resetKey:e,children:i});return t&&ez(t)?(0,o.jsx)(rz,{children:(0,o.jsxs)("div",{className:"system-frame",children:[(0,o.jsx)(ak,{systemPath:t}),c]})}):(0,o.jsx)(rz,{children:c})}function aT(){var e,t;let n,s,r,a;n=rC(),s=(0,l.useRef)(null),(0,l.useEffect)(()=>{let e=()=>{let e=s.current;if(!e)return;let t=sP.getState(),n=r$("doc");if(n&&t.docPath!==n||e.docAt!==t.docPath&&t.definition===e.defAt)return;s.current=null;let r=e9(e.focus);if(!r)return;let a=null,i=null;if("state"===r.kind)(a=a_(t.definition.state,r.name))&&(i={kind:"state",id:r.name});else if("event"===r.kind){let e=function e(t,n){if(!t)return null;let s=(t.transitions??[]).findIndex(e=>e?.event===n);if(s>=0)return{state:t.name,index:s};for(let s of aR(t)){let t=e(s,n);if(t)return t}return null}(t.definition.state,r.name);e&&(a=a_(t.definition.state,e.state),i={kind:"transition",id:`${e.state}:${e.index}`})}if(!a||!i)return;let o=a.length>1?a.slice(0,-1):a;sP.setState({navigationPath:o,currentParent:o[o.length-1]}),t.select(i.kind,i.id);let l=()=>{let e=sP.getState().layout.positions[a[a.length-1]],t=document.getElementById(sq)?.getBoundingClientRect();if(!e||!t?.width)return;let n=H([e],t.width,t.height,{padding:60,maxScale:1});sP.getState().setViewport(n)};requestAnimationFrame(l),setTimeout(l,450)};if(n.nonce>0){let t=sP.getState();s.current=n.focus?{focus:n.focus,docAt:t.docPath,defAt:t.definition}:null,e()}return sP.subscribe(e)},[n]),(0,l.useEffect)(()=>sP.subscribe((e,t)=>{if(e.selection===t.selection||!e.selection.id)return;let{kind:n,id:s}=e.selection;if("state"===n)rM(`state:${s}`);else if("event"===n)rM(`event:${s}`);else if("transition"===n){let t=function(e,t){let n=t.lastIndexOf(":"),s=a_(e.state,t.slice(0,n));if(!s)return null;let r=e.state;for(let e of s.slice(1))r=aR(r).find(t=>t.name===e);return r?.transitions?.[Number(t.slice(n+1))]?.event??null}(e.definition,s);t&&rM(`event:${t}`)}}),[]);let[i,c]=(0,l.useState)("properties"),[d,h]=(0,l.useState)(!1),u=rb({onClose:()=>h(!1),restVh:70,tallVh:92}),m=sP(e=>e.errors),p=sP(e=>e.contextMenu),f=sP(e=>e.hideContextMenu),g=sP(e=>e.addState),x=sP(e=>e.removeState),y=sP(e=>e.setDrawMode),b=sP(e=>e.setDrawSource),v=[{id:"properties",label:"Properties",icon:"🎛"},{id:"events",label:"Events",icon:"⚡"},{id:"settings",label:"Settings",icon:"⚙"},{id:"validation",label:"Errors",icon:(0,o.jsx)(rx,{}),badge:m.length||void 0}],w=v.find(e=>e.id===i)?.label??"";return(0,o.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden",onClick:()=>p.visible&&f(),children:[(0,o.jsx)(rt,{}),(0,o.jsx)(rp,{}),(0,o.jsx)(s4,{}),(0,o.jsxs)("div",{className:"flex flex-1 min-h-0 overflow-hidden relative",children:[(0,o.jsxs)("div",{className:"relative flex-1 overflow-hidden",id:"machine-board",children:[(0,o.jsx)(rg,{what:"state machine",children:(0,o.jsx)(sJ,{})}),(0,o.jsx)(aE,{})]}),d&&(0,o.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:u.close,"aria-hidden":"true"}),(0,o.jsxs)("aside",{style:u.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 ${d?"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,o.jsxs)("div",{className:"md:hidden",...u.zoneProps,children:[(0,o.jsx)("div",{className:"flex justify-center pt-2 pb-1",children:(0,o.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,o.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,o.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:w}),(0,o.jsx)("button",{onClick:u.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,o.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:v.map(e=>(0,o.jsxs)("button",{onClick:()=>c(e.id),className:`flex-1 text-xs py-2 px-1 text-center transition-colors relative ${i===e.id?"text-blue-400 border-b-2 border-blue-400 bg-gray-800/50":"text-gray-500 hover:text-gray-300"}`,children:[e.label,void 0!==e.badge&&e.badge>0&&(0,o.jsx)("span",{className:"absolute top-1 right-1 bg-red-600 text-white text-[9px] rounded-full px-1 min-w-[14px]",children:e.badge})]},e.id))}),(0,o.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain",children:["properties"===i&&(0,o.jsx)(sK,{}),"events"===i&&(0,o.jsx)(sG,{}),"settings"===i&&(0,o.jsx)(sQ,{}),"validation"===i&&(0,o.jsx)(s0,{})]})]}),(0,o.jsx)(s3,{})]}),(0,o.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:v.map(e=>{let t=d&&i===e.id;return(0,o.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(d&&i===t?u.close():h(!0),c(t))},"aria-pressed":t,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${t?"text-blue-400":"text-gray-500"}`,children:[(0,o.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,o.jsx)("span",{children:e.label}),void 0!==e.badge&&e.badge>0&&(0,o.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:e.badge}),t&&(0,o.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})}),p.visible&&(0,o.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:(e=p.x,t=p.y,r=window.innerWidth,a=window.innerHeight,{left:e,top:t,maxWidth:"calc(100vw - 1rem)",maxHeight:"calc(100dvh - 1rem)",overflowY:"auto",transform:`translate(${r>0&&e>r/2?"-100%":"0"}, ${a>0&&t>a/2?"-100%":"0"})`}),onClick:e=>e.stopPropagation(),children:p.target?.kind==="state"?(0,o.jsxs)(o.Fragment,{children:[(0,o.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:()=>{y("transition"),b(p.target.id),f()},children:"↗ Draw transition from here"}),(0,o.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:()=>{p.target?.id&&x(p.target.id),f()},children:"🗑 Delete state"})]}):(0,o.jsx)(o.Fragment,{children:(0,o.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 e=prompt("State name:");e&&g(null,{name:e,kind:"normal"}),f()},children:"+ Add state here"})})})]})}e.s(["default",()=>aA],63052)}]);
13
+ No marks.`);navigator.clipboard?.writeText(a).then(()=>{M(!0),setTimeout(()=>M(!1),2e3)})},copied:S,onClose:()=>w(!1)})})]})}function rK({docPath:e,onReveal:t}){let n=rF(),s=n?.lit??null,r=(0,l.useRef)(-1);return(0,l.useEffect)(()=>{!s||r.current===s.nonce||s.doc&&s.doc!==e||(s.spotlight?.length||s.region)&&(r.current=s.nonce,t())},[s,e,t]),null}function rZ(e,t,n){try{return e()}catch(s){let e=s instanceof Error?s.message:String(s);return console.warn("[stateloom] skipped on a malformed document:",e),n?.(e),t}}let rG=(e,t)=>"chen"===t?`stateloom:erd-layout:chen:${e}`:`stateloom:erd-layout:${e}`,rQ="stateloom:erd-notation",r0="stateloom:erd-lock";function r1(e,t){try{return JSON.parse(localStorage.getItem(rG(e,t))??"{}")}catch{return{}}}async function r2(e){let t=e.slice(0,e.lastIndexOf("/")),n=((await (await fetch("/api/docs",{cache:"no-store"})).json()).docs??[]).map(e=>e.path).filter(e=>e.endsWith(".smdf.json")&&e.slice(0,e.lastIndexOf("/"))===t),s=[];for(let e of n)try{let t=await (await fetch(`/api/file${(0,s1.docQuery)(e)}`,{cache:"no-store"})).json(),n=JSON.parse(t.content??"null"),r=ex(n?.stateMachine??n?.StateMachine??n);r?.state&&s.push({path:e,def:r})}catch{}return s}let r5="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",r4="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",r3="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function r6(){let e=(0,s1.useRequestedDoc)(),[t,n]=(0,l.useState)(""),[s,r]=(0,l.useState)(null),[a,i]=(0,l.useState)({}),[c,d]=(0,l.useState)("crowsfoot"),[h,u]=(0,l.useState)(!1),[m,p]=(0,l.useState)({...q}),[f,g]=(0,l.useState)(0),[x,y]=(0,l.useState)(null),[b,v]=(0,l.useState)({text:"loading…",tone:"ok"}),w=(0,l.useCallback)((e,t="ok")=>v({text:e,tone:t}),[]),[j,k]=(0,l.useState)(!1);(0,l.useEffect)(()=>{let e=setTimeout(()=>k(!0),4e3);return()=>{clearTimeout(e),k(!1)}},[b]);let[$,N]=(0,l.useState)("entities"),[S,M]=(0,l.useState)(!1),[C,E]=(0,l.useState)(!1),[R,_]=(0,l.useState)(!1),A=(0,l.useRef)(null),T=rb({onClose:()=>M(!1),restVh:62,tallVh:92}),[O,P]=(0,l.useState)(0),[I,L]=(0,l.useState)(null),D=(0,l.useRef)(null);(0,l.useEffect)(()=>{let t=!1,s=null;return(async()=>{let a=await (await fetch(`/api/file${(0,s1.docQuery)(e)}`,{cache:"no-store"})).json();if(t)return;if(a.error)return w(a.error,"warn");let o=a.path??"",l=null;try{let e=a.content?ex(JSON.parse(a.content)):null;K(e)&&(l={...e,relationships:e.relationships??[]})}catch{}if(a.exists&&!l)return w(`${o} is not a readable ERD definition`,"warn");let c=(o.split("/").pop()??"Untitled").replace(/\.erdf\.json$/i,""),h=function(){try{return"chen"===localStorage.getItem(rQ)?"chen":"crowsfoot"}catch{return"crowsfoot"}}();n(o),r(l??{settings:{namespace:"Default",name:c},entities:[],relationships:[]}),d(h),u(function(){try{let e=localStorage.getItem(r0);if(null!==e)return"1"===e;return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}()),i(r1(o,h)),y(null),L(null),g(e=>e+1),w(a.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:m}=await re();!t&&m&&(D.current=s=sv({url:m,role:"web",docId:o,name:"web-designer",onFull:e=>{let t=e.def;K(t)&&(r({...t,relationships:t.relationships??[]}),w("updated live"))},onPatch:()=>{},onPresence:e=>P(e.length)}),s.connect())})().catch(e=>!t&&w(String(e),"warn")),()=>{t=!0,D.current=null,s?.disconnect()}},[e,w]);let B=(0,l.useMemo)(()=>{if(!s)return{};let e=rZ(()=>(function(e,t={}){let n=t.notation??"crowsfoot",s=t.hSpacing??70,r=t.vSpacing??("chen"===n?130:90),a="chen"===n?ed:eb,i=[],o=new Set;for(let t of e.entities??[])!t?.name||o.has(t.name)||(o.add(t.name),i.push(t));let l=new Map,c=(e,t,n=new Set)=>e===t||!n.has(e)&&(n.add(e),(l.get(e)??[]).some(e=>c(e,t,n)));for(let t of e.relationships??[]){if(!t||!o.has(t.from)||!o.has(t.to)||t.from===t.to)continue;let[e,n]="N:1"===t.cardinality?[t.to,t.from]:[t.from,t.to];if((l.get(e)??[]).includes(n)||c(n,e))continue;let s=l.get(e);s?s.push(n):l.set(e,[n])}let d=new Map,h=(e,t)=>{if(!((d.get(e)??-1)>=t))for(let n of(d.set(e,t),l.get(e)??[]))h(n,t+1)},u=new Set([...l.values()].flat());for(let e of i)u.has(e.name)||h(e.name,0);for(let e of i)d.has(e.name)||h(e.name,0);for(let e of[...i].sort((e,t)=>d.get(t.name)-d.get(e.name))){let t=l.get(e.name)??[];t.length&&d.set(e.name,Math.min(...t.map(e=>d.get(e)))-1)}let m=[],p=new Map,f=(e,t)=>((m[t]??=[]).push(e),p.set(e.id,e),e);for(let e of i)f({id:e.name,entity:e.name,...a(e),upper:[],lower:[],x:0},d.get(e.name)??0);let g=0;for(let[e,t]of l)for(let n of t){let t=e;for(let s=d.get(e)+1;s<d.get(n);s++){let e=f({id:`\u0000lane${g++}`,width:28,height:0,upper:[],lower:[],x:0},s);p.get(t).lower.push(e.id),e.upper.push(t),t=e.id}p.get(t).lower.push(n),p.get(n).upper.push(t)}for(let e=m.length-1;e>=0;e--)m[e]?.length||m.splice(e,1);let x=(e,t)=>e.length?e.reduce((e,n)=>e+t(p.get(n)),0)/e.length:null,y=(e,t)=>{let n=new Map;for(let e of m)e.forEach((e,t)=>n.set(e.id,t));let s=new Map(e.map((e,s)=>[e.id,x(e[t],e=>n.get(e.id))??s]));e.sort((e,t)=>s.get(e.id)-s.get(t.id))};for(let e=0;e<2;e++){for(let e=1;e<m.length;e++)y(m[e],"upper");for(let e=m.length-2;e>=0;e--)y(m[e],"lower")}let b=e=>e.x+e.width/2,v=(e,t)=>{let n=0;for(let r of e){let e=x(r[t],b);r.x=Math.max(n,null===e?n:e-r.width/2),n=r.x+r.width+s}};for(let e of m)v(e,"upper");for(let e=m.length-2;e>=0;e--)v(m[e],"lower");let w=Math.min(0,...[...p.values()].map(e=>e.x)),j={},k=40;for(let e of m){for(let t of e)t.entity&&(j[t.entity]={x:Math.round(t.x-w)+40,y:k,width:t.width,height:t.height});k+=Math.max(0,...e.map(e=>e.height))+r}return j})(s,{notation:c}),{});for(let[t,n]of Object.entries(a))e[t]&&(e[t]={...e[t],...n});return e},[s,a,c]),F=(0,l.useMemo)(()=>{if(!s)return[];let e="";return rZ(()=>Z(s),null,t=>e=t)??[{ruleId:"E000",message:`The document could not be checked (${e}): a field is not the shape Spec 80 gives it`}]},[s]),U=(0,l.useMemo)(()=>F.map(e=>(e.element??"").split(/[.[]/)[0]).filter(Boolean),[F]),Y=(0,l.useCallback)(async e=>{let n;if(s&&t){try{n=e(s)}catch(e){return w(e instanceof Error?e.message:String(e),"warn")}r(n),L(null);try{let e=await fetch(`/api/file${(0,s1.docQuery)(t)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(n,null,2)+"\n"})});if(!e.ok)throw Error((await e.json())?.error??`HTTP ${e.status}`);D.current?.emitFull(n),w("saved")}catch(e){w(`not saved: ${e instanceof Error?e.message:String(e)}`,"warn")}}},[s,t,w]),X=(0,l.useCallback)((e,n)=>{i(s=>{let r={...s,[e]:{x:Math.round(n.x),y:Math.round(n.y)}};try{localStorage.setItem(rG(t,c),JSON.stringify(r))}catch{}return r})},[t,c]),V=()=>{i({});try{localStorage.removeItem(rG(t,c))}catch{}g(e=>e+1)},G=async()=>{if(!s)return;w("checking links…");let e=await r2(t);if(0===e.length)return L("none"),N("issues"),M(!0),w("no .smdf.json beside this document to check against","warn");let n=e.flatMap(e=>Q(e.def,s).map(t=>({...t,message:`${e.def.settings?.name??e.path}: ${t.message}`})));n.push(...ee(s,e.map(e=>e.def.settings?.name??""))),L(n),N("issues"),M(!0),_(!1),w(`checked ${e.length} machine(s): ${n.length} problem(s)`,n.length?"warn":"ok")},ei=async e=>{let n=(await r2(t)).find(t=>t.def.settings?.name===e);n?(0,s1.navigateToDoc)(n.path):w(`no .smdf.json beside this document defines '${e}'`,"warn")},eo=()=>{let e=A.current?.getBoundingClientRect();return{width:e?.width??0,height:e?.height??0}},el=e=>{let{width:t,height:n}=eo();p(s=>z(s,e,{x:t/2,y:n/2}))},ec=e=>{let t=B[e],{width:n,height:s}=eo();t&&n&&(p(H([t],n,s,{padding:28,maxScale:1.25})),y(e),T.close())},eu=rC(),eg=rN("focus"),ey=(0,l.useMemo)(()=>s?rZ(()=>(function(e,t,n={}){let s=!1!==n.rows,r=[];for(let n of e?.entities??[]){let e=n?.name?t[n.name]:void 0;e&&(r.push({focus:`entity:${n.name}`,box:e}),(n.attributes??[]).filter(e=>e?.name).forEach((t,a)=>{r.push({focus:`attribute:${n.name}.${t.name}`,box:s?{x:e.x,y:e.y+30+20*a,width:e.width,height:20}:e})}))}return r})(s,B,{rows:"chen"!==c}),[]):[],[s,B,c]),ev=(0,l.useRef)(-1);(0,l.useEffect)(()=>{if(!s||ev.current===eu.nonce)return;ev.current=eu.nonce;let e=eu.focus?e9(eu.focus):null,t=e?.kind==="entity"?e.name:e?.kind==="attribute"?e.name.split(".")[0]:null;t&&B[t]&&ec(t)},[s,eu,B]),(0,l.useEffect)(()=>{x&&!r$("focus")?.startsWith(`attribute:${x}.`)&&rM(`entity:${x}`)},[x]);let ew=s?.entities.find(e=>e.name===x)??null,ej=t.split("/").pop()||"…",ek=Array.isArray(I)?I:[],e$=F.length+ek.length,eN=[{id:"entities",label:"Entities",icon:"▭"},{id:"relations",label:"Relations",icon:"⟷"},{id:"notes",label:"Notes",icon:"✎",badge:void 0},{id:"issues",label:"Issues",icon:(0,o.jsx)(rx,{}),badge:e$||void 0}],eS=e=>$===e?"":"hidden md:block",eM=()=>{s&&navigator.clipboard?.writeText(function(e){let t=["erDiagram"],n=" ",s=new Set;for(let r of e.relationships??[]){if(!r?.from||!r?.to)continue;let e=eh[r.cardinality]??eh["1:N"];t.push(`${n}${em(r.from)} ${e} ${em(r.to)} : ${ef(r.label??"")}`),s.add(r.from),s.add(r.to)}let r=new Set;for(let a of e.entities??[]){if(!a?.name||r.has(a.name))continue;r.add(a.name);let e=(a.attributes??[]).filter(e=>e?.name);if(0===e.length){s.has(a.name)||t.push(`${n}${em(a.name)}`);continue}for(let s of(t.push(`${n}${em(a.name)} {`),e))t.push(`${n}${n}${function(e){let t=[];"pk"===e.key&&t.push("PK"),"uk"===e.key&&t.push("UK"),e.references&&t.push("FK");let n=[],s=J(e);s.length&&n.push(`stateOf ${s.join(", ")}`),e.description&&n.push(e.description);let r=[ep(e.type??"","unknown"),ep(e.name,"unnamed")];return t.length&&r.push(t.join(", ")),n.length&&r.push(ef(n.join(" — "))),r.join(" ")}(s)}`);t.push(`${n}}`)}return t.join("\n")}(s)).then(()=>w("mermaid copied"))};return(0,o.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&E(!1),children:[(0,o.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,o.jsx)("span",{className:"font-semibold text-blue-300",children:"ERD"}),(0,o.jsx)(s2,{}),(0,o.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:t,children:[s?.settings.name??ej,(0,o.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",ej]})]}),(0,o.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(([e,n,s])=>(0,o.jsx)("button",{title:s,"aria-label":s,"aria-pressed":c===e,onClick:()=>(e=>{if(e!==c){try{localStorage.setItem(rQ,e)}catch{}d(e),i(r1(t,e)),g(e=>e+1)}})(e),className:`px-2.5 py-1.5 text-sm leading-none md:px-2 md:py-1 ${c===e?"bg-blue-900/60 text-blue-200":"bg-gray-800 text-gray-400 hover:bg-gray-700"}`,children:n},e))}),(0,o.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,o.jsx)("button",{className:r4,onClick:V,title:"Forget the dragged positions and lay the board out again",children:"⤢ Arrange"}),(0,o.jsx)("button",{className:r4,onClick:G,title:"Check the state machines beside this document against it",children:"Check links"}),(0,o.jsx)("button",{className:r4,onClick:eM,children:"Copy mermaid"}),(0,o.jsx)("button",{className:r4,onClick:()=>_(e=>!e),"aria-pressed":!R,title:R?"Show the panel":"Hide the panel — the board takes the full width",children:R?"⟨ Panel":"Panel ⟩"})]}),(0,o.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,o.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:e=>{e.stopPropagation(),E(e=>!e)},children:"⋯"}),C&&(0,o.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",V],["Check links to the machines",G],["Copy as mermaid",eM]].map(([e,t])=>(0,o.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{E(!1),t()},children:e},e))})]})]}),(0,o.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,o.jsxs)("div",{ref:A,className:"relative min-w-0 flex-1 overflow-hidden",children:[s&&(0,o.jsx)(rg,{what:"diagram",resetKey:s,children:(0,o.jsx)(tq,{definition:s,notation:c,positions:B,viewport:m,onViewportChange:p,selection:x,readOnly:h,errorElements:U,fitKey:f,onSelect:y,onClearSelection:()=>y(null),onEntityMove:X,onOpenMachine:ei,emptyHint:"No entities yet — add one in the panel, or let an agent call add_entity."})}),s&&(0,o.jsx)(rW,{docPath:t||null,kind:"erd",viewport:m,setViewport:p,boxes:ey,boardRef:A,focus:eg}),(0,o.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"===b.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,o.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===b.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,o.jsxs)("span",{className:`truncate transition-opacity duration-500 ${j&&"ok"===b.tone?"opacity-0":"opacity-100"}`,children:[b.text,O>1?` \xb7 ${O} in the room`:""]})]}),(0,o.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,o.jsx)("button",{title:h?"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":h,onClick:()=>{let e=!h;u(e);try{localStorage.setItem(r0,e?"1":"0")}catch{}w(e?"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 ${h?"bg-blue-950/60 text-blue-300":"text-gray-400"}`,children:(0,o.jsx)(ry,{locked:h})}),[["+","Zoom in",()=>el(1.25)],["−","Zoom out",()=>el(.8)],["⛶","Fit the whole diagram",()=>g(e=>e+1)]].map(([e,t,n])=>(0,o.jsx)("button",{title:t,"aria-label":t,onClick:n,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:e},t))]}),ew&&!S&&(0,o.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:()=>{N("entities"),M(!0)},children:["✎ ",ew.name]})]}),S&&(0,o.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:T.close,"aria-hidden":"true"}),s&&(0,o.jsxs)("aside",{style:T.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 ${S?"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 ${R?"md:hidden":""}`,children:[(0,o.jsxs)("div",{className:"md:hidden",...T.zoneProps,children:[(0,o.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,o.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,o.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,o.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:eN.find(e=>e.id===$)?.label}),(0,o.jsx)("button",{onClick:T.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,o.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,o.jsxs)("section",{className:eS("entities"),children:[(0,o.jsx)("div",{className:r3,style:{marginTop:0},children:"Entities"}),(0,o.jsx)("div",{className:"flex flex-wrap gap-1",children:s.entities.map(e=>(0,o.jsx)("button",{className:`${r4} ${x===e.name?"border-blue-500 text-blue-300":""}`,onClick:()=>y(e.name),children:e.name},e.name))}),(0,o.jsx)(r7,{fields:[{name:"name",placeholder:"new entity"}],submit:"+ Entity",onSubmit:e=>{Y(t=>er(t,{name:e.name.trim()})),y(e.name.trim())}}),ew&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:`${r3} flex items-center justify-between gap-2`,children:[(0,o.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:ew.name}),(0,o.jsx)("button",{className:`${r4} normal-case tracking-normal`,onClick:()=>ec(ew.name),title:"Bring this entity to the middle of the board at a readable size",children:"◎ Show on board"})]}),(0,o.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,o.jsx)("input",{type:"checkbox",checked:!!ew.weak,onChange:e=>Y(t=>ea(t,ew.name,{weak:e.target.checked}))}),"weak entity"]}),(ew.attributes??[]).map(e=>(0,o.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 font-mono text-[11px]",children:[(0,o.jsxs)("span",{className:e.stateOf?"text-blue-300":"text-gray-300",children:[e.name," : ",e.type,(0,o.jsxs)("span",{className:"text-gray-500",children:[e.key?` ${e.key.toUpperCase()}`:"",e.references?` → ${e.references}`:"",e.stateOf?` ◉ ${[e.stateOf].flat().join(", ")}`:""]})]}),(0,o.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":`Remove ${e.name}`,onClick:()=>Y(t=>(function(e,t,n){let s=et(e),r=en(s,t),a=r.attributes?.length??0;if(r.attributes=(r.attributes??[]).filter(e=>e.name!==n),r.attributes.length===a)throw Error(`Attribute '${t}.${n}' not found.`);return s})(t,ew.name,e.name)),children:"✕"})]},e.name)),(0,o.jsx)(r7,{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:e=>Y(t=>(function(e,t,n){if(!n.name?.trim())throw Error("An attribute needs a name.");let s=et(e),r=en(s,t);if(r.attributes??=[],r.attributes.some(e=>e.name===n.name))throw Error(`Attribute '${t}.${n.name}' already exists.`);return r.attributes.push(es({...n})),s})(t,ew.name,{name:e.name.trim(),type:e.type.trim()||"string",key:"pk"===e.key||"uk"===e.key?e.key:void 0,references:e.references.trim()||void 0,stateOf:e.stateOf.trim()||void 0}))}),(0,o.jsxs)("button",{className:`${r4} mt-2 text-red-300`,onClick:()=>{Y(e=>{var t;let n;return t=ew.name,en(n=et(e),t),n.entities=n.entities.filter(e=>e.name!==t),n.relationships=n.relationships.filter(e=>e.from!==t&&e.to!==t),n}),y(null)},children:["🗑 Delete ",ew.name]})]})]}),(0,o.jsxs)("section",{className:eS("relations"),children:[(0,o.jsx)("div",{className:`${r3} max-md:mt-0`,children:"Relationships"}),0===s.relationships.length&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),s.relationships.map((e,t)=>(0,o.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 text-[11px] text-gray-300",children:[(0,o.jsxs)("span",{children:[e.from," ",(0,o.jsx)("span",{className:"text-gray-500",children:e.cardinality})," ",e.to,e.label?(0,o.jsxs)("span",{className:"text-gray-500",children:[" : ",e.label]}):null]}),(0,o.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":"Remove relationship",onClick:()=>Y(t=>(function(e,t,n,s){let r=et(e),a=r.relationships.length;if(r.relationships=r.relationships.filter(e=>e.from!==t||e.to!==n||void 0!==s&&e.label!==s),r.relationships.length===a)throw Error(`No relationship from '${t}' to '${n}'${void 0===s?"":` labelled '${s}'`}.`);return r})(t,e.from,e.to,e.label)),children:"✕"})]},t)),s.entities.length>0&&(0,o.jsx)(r7,{fields:[{name:"from",options:s.entities.map(e=>e.name)},{name:"cardinality",options:[...W],initial:"1:N"},{name:"to",options:s.entities.map(e=>e.name)},{name:"label",placeholder:"label (a verb)"}],submit:"+ Relationship",onSubmit:e=>Y(t=>(function(e,t){let n=et(e);if(en(n,t.from),en(n,t.to),!W.includes(t.cardinality))throw Error(`Cardinality '${t.cardinality}' is not one of ${W.join(", ")}.`);return n.relationships.push(es({...t})),n})(t,{from:e.from,to:e.to,cardinality:e.cardinality,label:e.label.trim()||void 0}))})]}),(0,o.jsxs)("section",{className:eS("notes"),children:[(0,o.jsx)("div",{className:`${r3} max-md:mt-0`,children:"Notes"}),(0,o.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,o.jsx)(r8,{label:"On this diagram",value:s.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:e=>Y(t=>(function(e,t){let n=et(e);for(let e of["description","notes"]){let s=t[e];void 0!==s&&(s.trim()?n.settings[e]=s:delete n.settings[e])}return n})(t,{notes:e}))},"diagram"),ew?(0,o.jsx)(r8,{label:`On ${ew.name}`,value:ew.notes??"",placeholder:`A question or a decision about ${ew.name}…`,onSave:e=>Y(t=>ea(t,ew.name,{notes:e}))},`entity:${ew.name}`):(0,o.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Select an entity to leave a note on it."}),s.entities.some(e=>e.notes?.trim())&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:r3,children:"Entities with notes"}),(0,o.jsx)("div",{className:"flex flex-wrap gap-1",children:s.entities.filter(e=>e.notes?.trim()).map(e=>(0,o.jsx)("button",{className:`${r4} ${x===e.name?"border-blue-500 text-blue-300":""}`,onClick:()=>y(e.name),children:e.name},e.name))})]})]}),(0,o.jsxs)("section",{className:eS("issues"),children:[(0,o.jsx)("div",{className:`${r3} max-md:mt-0 ${0===e$&&!I?"md:hidden":""}`,children:"Issues"}),F.map((e,t)=>(0,o.jsxs)("div",{className:"py-0.5 text-[11px] text-red-300",children:["[",e.ruleId,"] ",e.message]},`p${t}`)),ek.map((e,t)=>(0,o.jsxs)("div",{className:"py-0.5 text-[11px] text-amber-300",children:["[",e.ruleId,"] ",e.message]},`l${t}`)),"none"===I&&(0,o.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===e$&&"none"!==I&&(0,o.jsx)("div",{className:`py-0.5 text-[11px] ${I?"text-green-400":"text-gray-600 md:hidden"}`,children:I?"Every name the machines use resolves.":"The document is valid. “Check links” (⋯) holds the state machines beside it against it."})]})]})]})]}),(0,o.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:eN.map(e=>{let t=S&&$===e.id;return(0,o.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(S&&$===t?T.close():M(!0),N(t))},"aria-pressed":t,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${t?"text-blue-400":"text-gray-500"}`,children:[(0,o.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,o.jsx)("span",{children:e.label}),void 0!==e.badge&&(0,o.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:e.badge}),t&&(0,o.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})})]})}function r8({label:e,value:t,placeholder:n,onSave:s}){let[r,a]=(0,l.useState)(t),[i,c]=(0,l.useState)(t),[d,h]=(0,l.useState)(!1);t!==i&&(c(t),d||a(t));let u=(0,l.useRef)(null),m=e=>{u.current&&clearTimeout(u.current),u.current=null,e!==t&&s(e)};return(0,o.jsxs)("label",{className:"mt-2 block",children:[(0,o.jsx)("span",{className:"text-[11px] text-gray-500",children:e}),(0,o.jsx)("textarea",{className:`${r5} h-24 resize-y leading-snug`,placeholder:n,value:r,onChange:e=>{let t=e.target.value;a(t),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>m(t),900)},onFocus:()=>h(!0),onBlur:()=>{h(!1),m(r)}})]})}function r7({fields:e,submit:t,onSubmit:n}){let s=()=>Object.fromEntries(e.map(e=>[e.name,e.initial??e.options?.[0]??""])),[r,a]=(0,l.useState)(s),i=e[0];return(0,o.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:t=>{t.preventDefault();let o={...s(),...r};o[i.name]?.trim()&&(n(o),a(t=>Object.fromEntries(e.map(e=>[e.name,e.options?t[e.name]??"":e.initial??""]))))},children:[e.map(e=>e.options?(0,o.jsx)("select",{className:r5,"aria-label":e.name,value:r[e.name]??"",onChange:t=>a(n=>({...n,[e.name]:t.target.value})),children:e.options.map(t=>(0,o.jsx)("option",{value:t,children:t||`(${e.name})`},t))},e.name):(0,o.jsx)("input",{className:r5,"aria-label":e.name,placeholder:e.placeholder,value:r[e.name]??"",onChange:t=>a(n=>({...n,[e.name]:t.target.value}))},e.name)),(0,o.jsx)("button",{type:"submit",className:`${r4} ${1===e.length?"":"col-span-2"}`,children:t})]})}let r9="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",ae="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",at="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function an({id:e,fields:t,submit:n,onSubmit:s,reset:r=!1,required:a}){let i=()=>Object.fromEntries(t.map(e=>[e.name,e.initial??(!e.checkbox&&(e.options?e.options[0]??"":""))])),[c,d]=(0,l.useState)(i),h=(e,t)=>d(n=>({...n,[e]:t}));return(0,o.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:e=>{e.preventDefault();let n={...i(),...c};!(a??[]).some(e=>!String(n[e]??"").trim())&&(s(n),r&&d(e=>Object.fromEntries(t.map(t=>[t.name,t.options||t.checkbox?e[t.name]??"":t.initial??""]))))},children:[t.map(t=>{let n=t.label??t.name;if(t.checkbox)return(0,o.jsxs)("label",{className:"flex items-center gap-2 text-[11px] text-gray-400",children:[(0,o.jsx)("input",{type:"checkbox",checked:!!c[t.name],onChange:e=>h(t.name,e.target.checked)}),n]},t.name);if(t.options)return(0,o.jsx)("select",{className:`${r9} ${t.wide?"col-span-2":""}`,"aria-label":n,title:n,value:String(c[t.name]??""),onChange:e=>h(t.name,e.target.value),children:t.options.map(e=>(0,o.jsx)("option",{value:e,children:e||`(${n})`},e))},t.name);let s=t.suggest?.length?`${e}-${t.name}`:void 0;return(0,o.jsxs)("span",{className:t.wide?"col-span-2":"",children:[(0,o.jsx)("input",{className:r9,"aria-label":n,title:n,placeholder:t.placeholder??n,list:s,value:String(c[t.name]??""),onChange:e=>h(t.name,e.target.value)}),s&&(0,o.jsx)("datalist",{id:s,children:t.suggest.map(e=>(0,o.jsx)("option",{value:e},e))})]},t.name)}),(0,o.jsx)("button",{type:"submit",className:`${ae} col-span-2`,children:n})]})}function as({kind:e,size:t=16}){return(0,o.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"shrink-0",children:["erd"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("rect",{x:"4",y:"4.5",width:"16",height:"15",rx:"1.5"}),(0,o.jsx)("path",{d:"M4 9h16M8 13h8M8 16.5h6"})]}),"machine"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("rect",{x:"2.5",y:"4",width:"8",height:"6",rx:"2.5"}),(0,o.jsx)("rect",{x:"13.5",y:"14",width:"8",height:"6",rx:"2.5"}),(0,o.jsx)("path",{d:"M6.5 10v4.5a2.5 2.5 0 0 0 2.5 2.5h4.5"}),(0,o.jsx)("path",{d:"M11.5 15l2 2-2 2"})]}),"sequence"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("path",{d:"M6 4v16M18 4v16",strokeDasharray:"2 2.2"}),(0,o.jsx)("path",{d:"M6 9h11M15 7l2 2-2 2"}),(0,o.jsx)("path",{d:"M18 15H7M9 13l-2 2 2 2"})]}),"system"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("rect",{x:"3",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,o.jsx)("rect",{x:"14",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,o.jsx)("rect",{x:"8.5",y:"14.5",width:"7",height:"6",rx:"1.5"}),(0,o.jsx)("path",{d:"M10 6.5h4M7 9.5l3 5M17 9.5l-3 5"})]}),"link"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.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,o.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"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("circle",{cx:"12",cy:"7.5",r:"3.5"}),(0,o.jsx)("path",{d:"M5 20a7 7 0 0 1 14 0"})]})]})}let ar=["text-sky-300","text-emerald-300","text-amber-300","text-rose-300","text-violet-300","text-cyan-300","text-lime-300","text-orange-300"],aa=e=>`seq-read-${e.kind}-${e.id}`;function ai({definition:e,selection:t,issues:n,onSelect:s,onShowInDiagram:r}){let a=new Map(e.participants.map((e,t)=>[e.name,ar[t%ar.length]])),i=eS(e),l=i.filter(e=>null===e.fragment),c=(e.fragments??[]).map((e,t)=>({f:e,fi:t,rows:i.filter(e=>e.fragment===t)})),d=(e,n)=>t?.kind===e&&t.id===n,h=e=>(0,o.jsx)("span",{className:`font-semibold ${a.get(e)??"text-gray-300"}`,children:e||"?"}),u=(e,t)=>{let a={kind:"message",id:e},i=n.get(`message:${e}`)??[],l=i.some(e=>"error"===e.severity)?"error":i.length?"warning":null,c=d("message",e);return(0,o.jsx)("li",{id:aa(a),className:"scroll-mt-16 scroll-mb-24",children:(0,o.jsxs)("div",{role:"button",tabIndex:0,"aria-pressed":c,onClick:()=>s(a),onKeyDown:e=>("Enter"===e.key||" "===e.key)&&(e.preventDefault(),s(a)),className:`flex gap-3 rounded-lg border-l-2 px-3 py-2.5 ${c?"bg-blue-950/60 ring-1 ring-blue-500/60":"hover:bg-gray-900"} ${"error"===l?"border-red-500":"warning"===l?"border-amber-400":"border-transparent"}`,children:[(0,o.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:e}),(0,o.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,o.jsxs)("div",{className:"text-[13px] leading-5 text-gray-400",children:[h(t.from),t.from===t.to?(0,o.jsx)("span",{children:" to itself"}):(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("span",{className:"px-1.5 text-gray-500",children:t.reply?"⇠":"→"}),h(t.to)]}),t.reply&&(0,o.jsx)("span",{className:"ml-2 text-[11px] text-gray-500",children:"reply"}),t.optional&&(0,o.jsx)("span",{className:"ml-2 rounded border border-gray-700 px-1 text-[11px] text-gray-400",children:"optional"})]}),(0,o.jsx)("div",{className:`mt-0.5 break-words text-[15px] leading-6 ${t.reply?"text-gray-300":"text-gray-100"}`,children:t.label||(0,o.jsx)("span",{className:"text-gray-500",children:"no label"})}),(t.event||t.state||t.carries)&&(0,o.jsxs)("div",{className:"mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] leading-5",children:[t.event&&(0,o.jsx)("span",{className:"rounded border border-blue-500/50 bg-blue-950/50 px-1.5 font-mono text-blue-200",children:t.event}),t.event&&t.machine&&(0,o.jsxs)("span",{className:"text-gray-400",children:["on ",t.machine]}),t.state&&(0,o.jsxs)("span",{className:"text-emerald-300",children:["→ ",t.state]}),t.carries&&(0,o.jsxs)("span",{className:"text-gray-400",children:["carries ",t.carries]})]}),i.map((e,t)=>(0,o.jsx)("p",{className:`mt-1.5 text-[12px] leading-5 ${"error"===e.severity?"text-red-300":"text-amber-300"}`,children:e.text},t)),c&&(0,o.jsx)("button",{className:"mt-2 rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-[12px] text-gray-200",onClick:e=>{e.stopPropagation(),r(a)},children:"Show in the diagram"})]})]})},e)};return(0,o.jsx)("div",{className:"h-full overflow-y-auto overscroll-contain",children:(0,o.jsxs)("div",{className:"mx-auto max-w-2xl px-4 pb-28 pt-10",children:[e.participants.length>0&&(0,o.jsx)("ul",{className:"mb-4 flex flex-wrap gap-2","aria-label":"Participants",children:e.participants.map(e=>{let t={kind:"participant",id:e.name},r=e.actor?"actor":e.object?"object":e.service?"service":"",a=n.get(`participant:${e.name}`)??[];return(0,o.jsx)("li",{id:aa(t),children:(0,o.jsxs)("button",{onClick:()=>s(t),"aria-pressed":d("participant",e.name),title:a.map(e=>e.text).join("\n")||void 0,className:`rounded-full border px-3 py-1 text-[13px] ${d("participant",e.name)?"border-blue-500 bg-blue-950/60":"border-gray-700 bg-gray-900"} ${a.length?"ring-1 ring-amber-400/70":""}`,children:[h(e.name),r&&(0,o.jsx)("span",{className:"ml-1.5 text-[11px] text-gray-400",children:r})]})},e.name)})}),0===i.length&&(0,o.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,o.jsx)("ol",{className:"flex flex-col gap-1",children:l.map(({ref:e,message:t})=>u(e,t))}),c.map(({f:e,fi:t,rows:n})=>(0,o.jsxs)("section",{className:"mt-5 rounded-xl border border-indigo-500/50 bg-indigo-950/20 p-1.5",children:[(0,o.jsxs)("header",{className:"px-3 pb-1.5 pt-2",children:[(0,o.jsxs)("div",{className:"text-[12px] text-indigo-200",children:[(0,o.jsx)("span",{className:"font-semibold uppercase tracking-wide",children:e.kind}),(0,o.jsxs)("span",{className:"text-indigo-300",children:[" · after ",e.after]})]}),(0,o.jsx)("div",{className:"mt-0.5 break-words text-[14px] leading-5 text-gray-100",children:e.label})]}),0===n.length?(0,o.jsx)("p",{className:"px-3 pb-2 text-[12px] text-gray-400",children:"No messages in this fragment."}):(0,o.jsx)("ol",{className:"flex flex-col gap-1",children:n.map(({ref:e,message:t})=>u(e,t))})]},t))]})})}async function ao(e){try{let t=await fetch(`/api/file${(0,s1.docQuery)(e)}`,{cache:"no-store"}),n=await t.json();if(!t.ok||n.error)return{path:e??"",content:null,exists:!1,error:n.error??`HTTP ${t.status}`};return{path:n.path??e??"",content:n.content??null,exists:!!n.exists,mtime:n.mtime}}catch(t){return{path:e??"",content:null,exists:!1,error:t instanceof Error?t.message:String(t)}}}class al extends Error{constructor(e){super(`${e.split("/").pop()} changed on disk since it was read`)}}async function ac(e,t,n){let s=await fetch(`/api/file${(0,s1.docQuery)(e)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(t,null,2)+"\n",...void 0!==n?{mtime:n}:{}})}),r=await s.json().catch(()=>({}));if(409===s.status)throw new al(e);if(!s.ok)throw Error(r?.error??`HTTP ${s.status}`);return r?.mtime}async function ad(e){let t=await ao(e),n={path:t.path||e,def:null,members:[],absOf:{},wrapped:{},mtimes:{}};if(t.error)return{...n,error:t.error};if(!t.exists||!t.content)return{...n,error:`${e} does not exist`};let s=null;try{let e=ex(JSON.parse(t.content));eY(e)&&(s=e)}catch{}if(!s)return{...n,error:`${t.path} is not a readable system definition`};let r={},a={},i={[t.path]:t.mtime??0},o=await Promise.all((s.members??[]).filter(e=>e?.path).map(async e=>{let n=eJ(t.path,e.path);r[e.path]=n;let s=eH(e.path),o=await ao(n);if(o.error)return{path:e.path,kind:s,def:null,error:o.error};if(!o.exists||!o.content)return{path:e.path,kind:s,def:null,error:"the file does not exist"};i[e.path]=o.mtime??0;try{let t=JSON.parse(o.content);if("machine"===s&&t&&(t.stateMachine||t.StateMachine))return a[e.path]=!0,{path:e.path,kind:s,def:ex(t.stateMachine??t.StateMachine)};return{path:e.path,kind:s,def:ex(t)}}catch(t){return{path:e.path,kind:s,def:null,error:`not JSON: ${t instanceof Error?t.message:String(t)}`}}}));return{path:t.path,def:s,members:o,absOf:r,wrapped:a,mtimes:i}}function ah(){window.dispatchEvent(new Event(rj))}function au(e){let[t,n]=(0,l.useState)(null),[s,r]=(0,l.useState)(0),a=(0,l.useCallback)(()=>r(e=>e+1),[]);return(0,l.useEffect)(()=>(window.addEventListener(rj,a),()=>window.removeEventListener(rj,a)),[a]),(0,l.useEffect)(()=>{if(!e)return;let t=!0;return ad(e).then(s=>t&&n({for:e,system:s})),()=>{t=!1}},[e,s]),{system:e&&t?.for===e?t.system:null,reload:a}}function am(e,t){if(!e||!t)return null;for(let[n,s]of Object.entries(e.absOf))if(s===t)return n;return null}async function ap(e,t,n,s){let{bridgeUrl:r}=await re();if(!r)return;let a=sy({url:r,role:"web",docId:e,name:"web-reconcile",autoResync:!1});try{let e=await Promise.race([a.join(),new Promise((e,t)=>setTimeout(()=>t(Error("join timeout")),3e3))]),r=e.snapshot?.def,i=e=>(function(e){let t=JSON.stringify(e),n=0x811c9dc5;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,0x1000193);return(n>>>0).toString(16).padStart(8,"0")})(e);if(r&&i(r)===i(t))return;await new Promise(e=>{let o=a.on("ack",()=>{o(),e()});s&&r&&i(r)===i(s.from)?a.emitPatch(s.ops,n):a.emitFull(t,n),setTimeout(e,800)})}catch{}finally{a.disconnect()}}async function af(e,t){let n=[],s=[],r=[],a=async(e,t)=>{try{await t(),n.push(e)}catch(t){t instanceof al?r.push(e):s.push(`${e}: ${t instanceof Error?t.message:String(t)}`)}};for(let n of t.machines){let t=e.absOf[n.member];t&&n.ops.length&&await a(n.member,async()=>{let s=e.wrapped[n.member]?{stateMachine:n.def}:n.def,r=await ac(t,s,e.mtimes[n.member]),a=e.members.find(e=>e.path===n.member)?.def;await ap(t,n.def,r,{from:a,ops:n.ops})})}for(let n of t.erds){let t=e.absOf[n.member];t&&await a(n.member,async()=>{let s=await ac(t,n.def,e.mtimes[n.member]);await ap(t,n.def,s)})}return t.system&&await a(e.path.split("/").pop()??e.path,async()=>{let n=await ac(e.path,t.system.def,e.mtimes[e.path]);await ap(e.path,t.system.def,n)}),ah(),{written:n,failed:s,conflicts:r}}async function ag(e){let t={result:null,written:[],failed:[],conflicts:[]};for(let n=0;n<2;n+=1){let s=await ad(e);if(!s.def)return{...t,failed:[s.error??"the system could not be read"],retried:n>0};let r=tr(s.def,s.members);if(!r.count)return{...t,result:r,conflicts:n?t.conflicts:[],retried:n>0};let a=await af(s,r);if(t={result:r,written:[...t.written,...a.written],failed:a.failed,conflicts:a.conflicts},!a.conflicts.length)return{...t,retried:n>0}}return{...t,retried:!0}}let ax="stateloom.sequence.view",ay=["","actor","service","object"],ab=e=>"string"==typeof e?e.trim():"",av=e=>ab(e).split(",").map(e=>e.trim()).filter(Boolean);function aw(e){return{from:ab(e.from),to:ab(e.to),label:ab(e.label),event:ab(e.event),machine:ab(e.machine),carries:ab(e.carries),state:ab(e.state),description:ab(e.description),optional:!!e.optional||void 0,reply:!!e.reply||void 0}}function aj(){let e,t,n,s=(0,s1.useRequestedDoc)(),r=rN("system"),{system:a}=au(r),i=rC(),[c,d]=(0,l.useState)(""),[h,u]=(0,l.useState)(null),[m,p]=(0,l.useState)({...q}),[f,g]=(0,l.useState)(void 0),[x,y]=(0,l.useState)(null),[b,v]=(0,l.useState)({text:"loading…",tone:"ok"}),w=(0,l.useCallback)((e,t="ok")=>v({text:e,tone:t}),[]),[j,k]=(0,l.useState)(!1);(0,l.useEffect)(()=>{let e=setTimeout(()=>k(!0),4e3);return()=>{clearTimeout(e),k(!1)}},[b]);let[$,N]=(0,l.useState)("messages"),[S,M]=(0,l.useState)(!1),[C,E]=(0,l.useState)(!1),[R,_]=(0,l.useState)(!1),[A,T]=(0,l.useState)("diagram"),O=(0,l.useRef)("diagram");(0,l.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(ax)}catch{}let t="list"===e||"diagram"===e?e:window.matchMedia("(max-width: 767px)").matches?"list":"diagram";O.current=t,T(t)},[]);let P=(0,l.useCallback)(e=>{O.current=e,T(e);try{window.localStorage.setItem(ax,e)}catch{}},[]),I=(0,l.useRef)(null),L=rb({onClose:()=>M(!1),restVh:62,tallVh:92}),[D,F]=(0,l.useState)(0),U=(0,l.useRef)(null),Y=(0,l.useRef)(!0),X=(0,l.useRef)(-1);(0,l.useEffect)(()=>{let e=!1,t=null;return(async()=>{let n=await (await fetch(`/api/file${(0,s1.docQuery)(s)}`,{cache:"no-store"})).json();if(e)return;if(n.error)return w(n.error,"warn");let r=n.path??"",a=null;try{let e=n.content?ex(JSON.parse(n.content)):null;ej(e)&&(a=e)}catch{}if(n.exists&&!a)return w(`${r} is not a readable sequence definition`,"warn");let i=(r.split("/").pop()??"Untitled").replace(/\.sqdf\.json$/i,"");d(r),u(a??ek("Default",i)),w(n.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:o}=await re();!e&&o&&(U.current=t=sv({url:o,role:"web",docId:r,name:"web-designer",onFull:e=>{let t=e.def;ej(t)&&(u(t),w("updated live"))},onPatch:()=>{},onPresence:e=>F(e.length)}),t.connect())})().catch(t=>!e&&w(String(t),"warn")),()=>{e=!0,U.current=null,t?.disconnect()}},[s,w]);let V=(0,l.useMemo)(()=>h?tH(h):null,[h]),J=(0,l.useMemo)(()=>V?eD(V):null,[V]),W=(0,l.useMemo)(()=>V&&J?rZ(()=>(function(e,t){let n=[];for(let e of t.participants)n.push({focus:`participant:${e.name}`,box:{x:e.left,y:e.top,width:e.width,height:Math.max(e.height,t.lifelineBottom-e.top)}});let s=new Map(eS(e).map(e=>[e.ref,e.message]));for(let e of t.rows){let t=e.self?e.fromX:Math.min(e.fromX,e.toX),r=e.self?220:Math.max(40,Math.abs(e.toX-e.fromX)),a={x:t-10,y:e.y-24,width:r+20,height:40};n.push({focus:`message:${e.ref}`,box:a});let i=s.get(e.ref)?.event;i&&n.push({focus:`event:${i}`,box:a})}return n})(V,J),[]):[],[V,J]),K=rN("focus"),Z=(0,l.useMemo)(()=>{if(!h)return[];let e="";return rZ(()=>eM(h),null,t=>e=t)??[{ruleId:"S000",message:`The document could not be checked (${e}): a field is not the shape Spec 81 gives it`}]},[h]),G=am(a,c),Q=(0,l.useMemo)(()=>a?.def&&G&&h?rZ(()=>e8(a.def,a.members.map(e=>e.path===G?{...e,def:h,error:void 0}:e)),null):null,[a,G,h]),ee=(0,l.useMemo)(()=>(Q?.issues??[]).filter(e=>e.member===G&&!/^S0/.test(e.ruleId)),[Q,G]),et=Q?.replays.find(e=>e.member===G)?.report??null,en=(0,l.useMemo)(()=>(function(e){let t={events:new Set,states:new Set,machines:new Set,objects:new Set,entities:new Set,actors:new Set};if(!e)return{events:[],states:[],machines:[],objects:[],entities:[],actors:[]};let{machines:n,erds:s}=e6(e.members);for(let{def:e}of(n.forEach(({def:e},n)=>{for(let s of(t.machines.add(e0(e,n)),e.events??[]))for(let e of[...s?.events??[],...s?.timers??[]])e?.id&&t.events.add(e.id);for(let n of e.settings?.objects??[])n?.instance&&t.objects.add(n.instance);let s=e=>{e&&(t.states.add(e.name),(e.states??[]).forEach(s),(e.parallel?.states??[]).forEach(s))};s(e.state)}),s))for(let n of e.entities??[])n?.name&&t.entities.add(n.name);for(let n of e.def?.actors??[])n?.name&&t.actors.add(n.name);let r=e=>[...e].sort((e,t)=>e.localeCompare(t));return{events:r(t.events),states:r(t.states),machines:r(t.machines),objects:r(t.objects),entities:r(t.entities),actors:r(t.actors)}})(a),[a]),es=(0,l.useMemo)(()=>{let e=e=>e?/^(message|participant):/.test(e)?e:V?.participants.some(t=>t.name===e)?`participant:${e}`:"":"";return[...Z.map(t=>e(t.element)),...ee.filter(e=>"error"===e.severity).map(t=>e(t.element))].filter(Boolean)},[Z,ee,V]),er=(0,l.useMemo)(()=>ee.filter(e=>"warning"===e.severity).map(e=>e.element??""),[ee]),ea=(0,l.useMemo)(()=>{let e=new Map,t=(t,n)=>{let s=t?/^(message|participant):/.test(t)?t:V?.participants.some(e=>e.name===t)?`participant:${t}`:"":"";s&&e.set(s,[...e.get(s)??[],n])};return Z.forEach(e=>t(e.element,{severity:"error",text:e.message})),ee.forEach(e=>t(e.element,{severity:"error"===e.severity?"error":"warning",text:e.message})),e},[Z,ee,V]),ei=()=>{let e=I.current?.getBoundingClientRect();return{width:e?.width??0,height:e?.height??0}},eo=(0,l.useCallback)(e=>{let t=I.current?.getBoundingClientRect();if(!t?.width)return;let n=B(Math.max(H([e],t.width,t.height,{padding:24,maxScale:1.1}).scale,.7));p({scale:n,x:t.width/2-(e.x+e.width/2)*n,y:t.height/2-(e.y+e.height/2)*n})},[]),el=(0,l.useCallback)(e=>{if(J)if("message"===e.kind){let t=J.rows.find(t=>t.ref===e.id);if(!t)return;let n=t.self?t.fromX:Math.min(t.fromX,t.toX),s=t.self?220:Math.abs(t.toX-t.fromX);eo({x:n-10,y:t.y-24,width:s+20,height:40})}else{let t=J.participants.find(t=>t.name===e.id);t&&eo({x:t.left-20,y:t.top,width:t.width+40,height:Math.min(260,J.height-t.top)})}},[J,eo]),ec=(0,l.useCallback)(e=>{if("diagram"===O.current)return el(e);requestAnimationFrame(()=>document.getElementById(aa(e))?.scrollIntoView({block:"center",behavior:"smooth"}))},[el]),ed=(0,l.useCallback)(e=>{y(e),e&&rM(`${e.kind}:${e.id}`)},[]);(0,l.useEffect)(()=>{if(!h||!J||X.current===i.nonce)return;X.current=i.nonce;let e=i.focus?e9(i.focus):null;if(!e)return;let t=null;if("message"===e.kind&&eN(V??h,e.name)&&(t={kind:"message",id:e.name}),"participant"===e.kind&&(V??h).participants.some(t=>t.name===e.name)&&(t={kind:"participant",id:e.name}),!t)return w(`${i.focus} is not in this sequence`,"warn");Y.current=!1,y(t),ec(t)},[h,V,J,i,ec,w]),(0,l.useEffect)(()=>{if(!J||!Y.current||"diagram"!==A)return;let{width:e,height:t}=ei();e&&(Y.current=!1,Math.min((e-32)/J.width,(t-32)/J.height)>=.5||0===J.participants.length?g(e=>(e??0)+1):p({x:8,y:8,scale:.6}))},[J,A]);let eh=(0,l.useCallback)(async e=>{let t;if(h&&c){try{t=e(h)}catch(e){return w(e instanceof Error?e.message:String(e),"warn")}u(t);try{let e=await fetch(`/api/file${(0,s1.docQuery)(c)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(t,null,2)+"\n"})});if(!e.ok)throw Error((await e.json())?.error??`HTTP ${e.status}`);U.current?.emitFull(t),w("saved")}catch(e){return w(`not saved: ${e instanceof Error?e.message:String(e)}`,"warn")}if(a?.def&&G){if("auto"===eF(a.def)){let{result:e,failed:t,conflicts:s}=await ag(a.path);if(e&&e.count>0){var n;return void(n=t.length?`auto: not written — ${t[0]}`:s.length?`auto: ${s.join(", ")} kept changing on disk; not written — save again`:ta(e,"auto"),window.dispatchEvent(new CustomEvent(rk,{detail:{text:n,origin:void 0}})))}}ah()}}},[h,c,w,a,G]),eu=e=>{let{width:t,height:n}=ei();p(s=>z(s,e,{x:t/2,y:n/2}))},em=()=>{let e,t,n,s,r,a,i,o,l;h&&navigator.clipboard?.writeText((e=["sequenceDiagram"],t=new Map,(h.participants??[]).forEach((n,s)=>{let r=`p${s+1}`;t.set(n.name,r),e.push(` ${n.actor?"actor":"participant"} ${r} as ${eq(n.name)}`)}),n=e=>t.get(e)??eq(e).replace(/\W+/g,"_"),s=(e,t,s)=>{let r=e.reply?"-->>":"->>",a=[`${t} ${eq(e.label??"")}`,e.event?eq(e.event):""].filter(Boolean).join(" · "),i=`${s}${n(e.from)}${r}${n(e.to)}: ${a}`;return e.optional?[`${s}opt optional`,` ${i}`,`${s}end`]:[i]},r=h.messages??[],a=h.fragments??[],i=e=>a.filter(t=>t?.after===e),o=(t,n)=>(t.messages??[]).forEach((r,i)=>e.push(...s(r,`f${a.indexOf(t)+1}.${i+1}`,n+" "))),(l=(t,n,a)=>{for(let c=t;c<=r.length;c++){let t=c===a?[]:i(c);for(let s of t.filter(e=>"alt"!==e.kind))e.push(`${n}${s.kind} ${eq(s.label??"")}`),o(s,n),e.push(`${n}end`);let d=t.filter(e=>"alt"===e.kind);if(d.length){d.forEach((t,s)=>{e.push(`${n}${0===s?"alt":"else"} ${eq(t.label??"")}`),o(t,n)}),c<r.length&&(e.push(`${n}else as written`),l(c,n+" ",c)),e.push(`${n}end`);return}c<r.length&&e.push(...s(r[c],String(c+1),n))}})(0," ",null),e.join("\n")+"\n")).then(()=>w("mermaid copied"))},ep=e=>{let t=e?e9(e):null;if(!t||"message"!==t.kind&&"participant"!==t.kind)return;let n={kind:t.kind,id:t.name};ed(n),ec(n),L.close()},ef=V??ek("",""),eg=eS(ef),ey=h&&x?.kind==="message"?eN(ef,x.id):null,eb=h&&x?.kind==="participant"?ef.participants.find(e=>e.name===x.id)??null:null,ev=ef.participants.map(e=>e.name),e$=c.split("/").pop()||"…",eL=Z.length+ee.filter(e=>"error"===e.severity).length,eB=ee.filter(e=>"warning"===e.severity).length,eU=[{id:"participants",label:"Participants",icon:(0,o.jsx)(as,{kind:"actor"})},{id:"messages",label:"Messages",icon:(0,o.jsx)(as,{kind:"sequence"})},{id:"notes",label:"Notes",icon:"✎"},{id:"issues",label:"Issues",icon:(0,o.jsx)(rx,{}),badge:eL+eB||void 0}],ez=e=>[{name:"from",label:"from",options:ev,initial:e?.from??ev[0]??""},{name:"to",label:"to",options:ev,initial:e?.to??ev[1]??ev[0]??""},{name:"label",label:"label",placeholder:"what is said or done",initial:e?.label??"",wide:!0},{name:"event",label:"event it fires",suggest:en.events,initial:e?.event??""},{name:"state",label:"state after",suggest:en.states,initial:e?.state??""},{name:"carries",label:"entity it carries",suggest:en.entities,initial:e?.carries??""},{name:"machine",label:"machine",suggest:en.machines,initial:e?.machine??""},{name:"optional",label:"optional",checkbox:!0,initial:!!e?.optional},{name:"reply",label:"reply (dashed)",checkbox:!0,initial:!!e?.reply}],eY=e=>e.actor?"actor":e.object?"object":e.service?"service":"",eH=["main: at the end",...ey&&null===ey.fragment?[`main: after ${ey.index+1}`]:[],...(h?.fragments??[]).map((e,t)=>`fragment ${t+1}: ${e.kind} \xb7 ${e.label}`)];return(0,o.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&E(!1),children:[(0,o.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,o.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,o.jsx)(as,{kind:"sequence",size:14}),"SEQ"]}),(0,o.jsx)(s2,{}),(0,o.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:c,children:[h?.settings.name??e$,(0,o.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",e$]})]}),(0,o.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(([e,t,n])=>(0,o.jsx)("button",{title:n,"aria-pressed":A===e,onClick:()=>{A!==e&&(x&&(Y.current=!1),P(e),x&&requestAnimationFrame(()=>ec(x)))},className:`px-2.5 py-1.5 ${A===e?"bg-gray-700 text-gray-100":"bg-gray-800 text-gray-400 hover:text-gray-200"}`,children:t},e))}),(0,o.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,o.jsx)("button",{className:ae,onClick:em,children:"Copy mermaid"}),(0,o.jsx)("button",{className:ae,onClick:()=>_(e=>!e),"aria-pressed":!R,title:R?"Show the panel":"Hide the panel — the board takes the full width",children:R?"⟨ Panel":"Panel ⟩"})]}),(0,o.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,o.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:e=>{e.stopPropagation(),E(e=>!e)},children:"⋯"}),C&&(0,o.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,o.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{E(!1),em()},children:"Copy as mermaid"})})]})]}),(0,o.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,o.jsxs)("div",{ref:I,className:"relative min-w-0 flex-1 overflow-hidden",children:[h&&J&&"list"===A&&V&&(0,o.jsx)(rg,{what:"sequence",resetKey:h,children:(0,o.jsx)(ai,{definition:V,selection:x,issues:ea,onSelect:e=>ed(e),onShowInDiagram:e=>{Y.current=!1,P("diagram"),requestAnimationFrame(()=>el(e))}})}),h&&J&&"diagram"===A&&(0,o.jsx)(rg,{what:"sequence",resetKey:h,children:(0,o.jsx)(tX,{definition:V,layout:J,viewport:m,onViewportChange:p,selection:x,errorElements:es,warningElements:er,fitKey:f,onSelect:(e,t)=>ed({kind:e,id:t}),onClearSelection:()=>y(null),emptyHint:"No participants yet — add them in the panel, or let an agent write the scenario."})}),h&&J&&"diagram"===A&&(0,o.jsx)(rW,{docPath:c||null,kind:"sequence",viewport:m,setViewport:p,boxes:W,boardRef:I,focus:K}),h&&J&&"list"===A&&(0,o.jsx)(rK,{docPath:c,onReveal:()=>P("diagram")}),(0,o.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"===b.tone?"text-amber-300":"text-gray-500"} ${"list"===A&&j&&"ok"===b.tone?"hidden":"flex"}`,role:"status",children:[(0,o.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===b.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,o.jsxs)("span",{className:`truncate transition-opacity duration-500 ${j&&"ok"===b.tone?"opacity-0":"opacity-100"}`,children:[b.text,D>1?` \xb7 ${D} in the room`:""]})]}),(0,o.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"===A?"flex":"hidden"}`,children:[["+","Zoom in",()=>eu(1.25)],["−","Zoom out",()=>eu(.8)],["⛶","Fit the whole diagram",()=>g(e=>(e??0)+1)]].map(([e,t,n])=>(0,o.jsx)("button",{title:t,"aria-label":t,onClick:n,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:e},t))}),x&&!S&&(0,o.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:()=>{N("message"===x.kind?"messages":"participants"),M(!0)},children:["Edit ","message"===x.kind?`${x.id}. ${ey?.message.label??""}`:x.id]})]}),S&&(0,o.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:L.close,"aria-hidden":"true"}),h&&(0,o.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 ${S?"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 ${R?"md:hidden":""}`,children:[(0,o.jsxs)("div",{className:"md:hidden",...L.zoneProps,children:[(0,o.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,o.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,o.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,o.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:eU.find(e=>e.id===$)?.label}),(0,o.jsx)("button",{onClick:L.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,o.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:eU.map(e=>(0,o.jsxs)("button",{onClick:()=>N(e.id),className:`relative flex-1 px-1 py-2 text-center text-xs transition-colors ${$===e.id?"border-b-2 border-blue-400 bg-gray-800/50 text-blue-400":"text-gray-500 hover:text-gray-300"}`,children:[e.label,void 0!==e.badge&&(0,o.jsx)("span",{className:"absolute right-1 top-1 min-w-[14px] rounded-full bg-red-900 px-1 text-[9px] text-red-100",children:e.badge})]},e.id))}),(0,o.jsx)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:(0,o.jsxs)(rg,{what:"panel",resetKey:h,children:[(0,o.jsxs)("section",{className:"participants"===$?"":"hidden",children:[(0,o.jsx)("div",{className:at,style:{marginTop:0},children:"Participants"}),(0,o.jsx)("div",{className:"flex flex-wrap gap-1",children:ef.participants.map(e=>(0,o.jsxs)("button",{className:`${ae} ${x?.kind==="participant"&&x.id===e.name?"border-blue-500 text-blue-300":""}`,onClick:()=>{ed({kind:"participant",id:e.name}),ec({kind:"participant",id:e.name})},title:eY(e)||"participant",children:[e.name,eY(e)&&(0,o.jsxs)("span",{className:"text-gray-500",children:[" · ",eY(e)]})]},e.name))}),(0,o.jsx)(an,{id:"add-participant",reset:!0,required:["name"],fields:[{name:"name",placeholder:"new participant"},{name:"kind",options:ay,label:"kind"},{name:"value",placeholder:"actor / service / object",suggest:[...en.actors,...en.objects]},{name:"holds",placeholder:"holds: Entity, Entity",suggest:en.entities}],submit:"+ Participant",onSubmit:e=>{let t=ab(e.name),n=ab(e.kind);eh(s=>(function(e,t,n){if(!t.name?.trim())throw Error("A participant needs a name.");let s=eC(e);if(s.participants.some(e=>e.name===t.name))throw Error(`Participant '${t.name}' already exists.`);let r=s.participants.length;return s.participants.splice(r,0,eE({...t})),s})(s,{name:t,...n?{[n]:ab(e.value)||t}:{},holds:av(e.holds)})),ed({kind:"participant",id:t})}}),eb&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:`${at} flex items-center justify-between gap-2`,children:[(0,o.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:eb.name}),(0,o.jsx)("button",{className:`${ae} normal-case tracking-normal`,onClick:()=>ec({kind:"participant",id:eb.name}),children:"◎ Show on board"})]}),(e=ef.participants.findIndex(e=>e.name===eb.name),t=ef.participants.length-1,n=e=>eh(t=>{var n;let s,r;return n=eb.name,r=eR(s=eC(t),n),s.participants.splice(s.participants.indexOf(r),1),s.participants.splice(Math.max(0,Math.min(e,s.participants.length)),0,r),s}),(0,o.jsxs)("div",{className:"mb-1 flex items-center gap-1 text-[11px] text-gray-400",children:[(0,o.jsx)("button",{className:`${ae} disabled:opacity-40`,disabled:e<=0,onClick:()=>n(e-1),"aria-label":"Move one column left",children:"← Left"}),(0,o.jsxs)("span",{className:"flex-1 text-center",children:["column ",e+1," of ",t+1]}),(0,o.jsx)("button",{className:`${ae} disabled:opacity-40`,disabled:e>=t,onClick:()=>n(e+1),"aria-label":"Move one column right",children:"Right →"})]})),(0,o.jsx)(an,{id:"rename-participant",required:["to"],fields:[{name:"to",label:"new name",initial:eb.name}],submit:"Rename (every message follows)",onSubmit:e=>{let t=ab(e.to);t!==eb.name&&(eh(e=>(function(e,t,n){if(!n?.trim())throw Error("A participant needs a name.");let s=eC(e),r=eR(s,t);if(n===t)return s;if(s.participants.some(e=>e.name===n))throw Error(`Participant '${n}' already exists.`);r.name=n;let a=e=>{e.from===t&&(e.from=n),e.to===t&&(e.to=n)};for(let e of(s.messages.forEach(a),s.fragments??[]))e.messages.forEach(a);return s})(e,eb.name,t)),ed({kind:"participant",id:t}))}},`rename:${eb.name}`),(0,o.jsx)(an,{id:"edit-participant",fields:[{name:"kind",options:ay,label:"kind",initial:eY(eb)},{name:"value",placeholder:"actor / service / object",suggest:[...en.actors,...en.objects],initial:eb.actor??eb.object??eb.service??""},{name:"holds",placeholder:"holds: Entity, Entity",suggest:en.entities,initial:(eb.holds??[]).join(", "),wide:!0},{name:"description",placeholder:"description",initial:eb.description??"",wide:!0}],submit:"Save participant",onSubmit:e=>eh(t=>{let n,s;return eT(t,eb.name,{...(n=ab(e.kind),s=ab(e.value)||eb.name,{actor:"actor"===n?s:"",service:"service"===n?s:"",object:"object"===n?s:""}),holds:av(e.holds),description:ab(e.description)})})},`p:${JSON.stringify(eb)}`),(0,o.jsxs)("button",{className:`${ae} mt-2 text-red-300`,onClick:()=>{eh(e=>{var t;let n,s;return t=eb.name,eR(n=eC(e),t),n.participants=n.participants.filter(e=>e.name!==t),s=e=>e.from!==t&&e.to!==t,n.messages=n.messages.filter(s),n.fragments&&(n.fragments=n.fragments.map(t=>{let n;return{...t,after:Math.max(0,t.after-(n=t.after,e.messages.slice(0,n).filter(e=>!s(e)).length)),messages:t.messages.filter(s)}}).filter(e=>e.messages.length>0),n.fragments.length||delete n.fragments),n}),y(null),rM(null)},title:"Also removes every message it sends or receives",children:["Delete ",eb.name," and its messages"]})]})]}),(0,o.jsxs)("section",{className:"messages"===$?"":"hidden",children:[(0,o.jsx)("div",{className:at,style:{marginTop:0},children:"Messages"}),0===eg.length&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),(0,o.jsx)("div",{className:"flex flex-col",children:eg.map(({ref:e,message:t,fragment:n},s)=>{let r=null!==n&&(0===s||eg[s-1].fragment!==n),a=null!==n?ef.fragments?.[n]:void 0,i=x?.kind==="message"&&x.id===e;return(0,o.jsxs)("div",{children:[r&&a&&(0,o.jsxs)("div",{className:"mt-2 border-t border-gray-800 pt-1 text-[11px] text-indigo-300",children:[(0,o.jsx)("span",{className:"font-semibold",children:a.kind})," · after ",a.after," · ",a.label]}),(0,o.jsxs)("button",{className:`block w-full truncate rounded px-1 py-0.5 text-left text-[11px] ${i?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,onClick:()=>{ed({kind:"message",id:e}),ec({kind:"message",id:e})},title:`${t.from} → ${t.to}: ${t.label}`,children:[(0,o.jsxs)("span",{className:"text-gray-500",children:[e,"."]})," ",t.from," → ",t.to,": ",t.label,t.event?(0,o.jsxs)("span",{className:"text-blue-300",children:[" [",t.event,"]"]}):null,t.state?(0,o.jsxs)("span",{className:"text-emerald-400",children:[" → ",t.state]}):null,t.optional?(0,o.jsx)("span",{className:"text-gray-500",children:" opt"}):null]})]},e)})}),ey&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:`${at} flex items-center justify-between gap-2`,children:[(0,o.jsxs)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:["Message ",x.id]}),(0,o.jsxs)("span",{className:"flex gap-1 normal-case tracking-normal",children:[null===ey.fragment&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("button",{className:ae,"aria-label":"Move up",title:"Move up",disabled:0===ey.index,onClick:()=>{eh(e=>eI(e,ey.index,ey.index-1)),ed({kind:"message",id:String(ey.index)})},children:"↑"}),(0,o.jsx)("button",{className:ae,"aria-label":"Move down",title:"Move down",disabled:ey.index>=ef.messages.length-1,onClick:()=>{eh(e=>eI(e,ey.index,ey.index+1)),ed({kind:"message",id:String(ey.index+2)})},children:"↓"})]}),(0,o.jsx)("button",{className:ae,onClick:()=>ec(x),children:"◎ Show"})]})]}),(0,o.jsx)(an,{id:"edit-message",required:["label"],fields:[...ez(ey.message),{name:"description",placeholder:"description",initial:ey.message.description??"",wide:!0}],submit:"Save message",onSubmit:e=>eh(t=>eP(t,ey.index,aw(e),ey.fragment))},`m:${x.id}:${JSON.stringify(ey.message)}`),(0,o.jsxs)("button",{className:`${ae} mt-2 text-red-300`,onClick:()=>{eh(e=>(function(e,t,n=null){let s=eC(e);if(null!==n){let e=eA(s,n);if(!e.messages[t])throw Error(`Message ${t+1} not found in fragment ${n+1}.`);return e.messages.splice(t,1),s}if(!s.messages[t])throw Error(`Message ${t+1} not found. The sequence has ${s.messages.length}.`);if(s.messages.splice(t,1),s.fragments)for(let e of s.fragments)e.after>t&&(e.after-=1);return s})(e,ey.index,ey.fragment)),y(null),rM(null)},children:["Delete message ",x.id]})]}),(0,o.jsx)("div",{className:at,children:"Add a message"}),(0,o.jsx)(an,{id:"add-message",reset:!0,required:["label"],fields:[{name:"where",options:eH,label:"where",wide:!0},...ez()],submit:"+ Message",onSubmit:e=>{let t=ab(e.where),n=aw(e),s=/^fragment (\d+):/.exec(t),r=/^main: after (\d+)$/.exec(t);s?eh(e=>{var t;let r,a,i;return t=Number(s[1])-1,a=eA(r=eC(e),t),e_(r,n),i=a.messages.length,a.messages.splice(i,0,eE({...n})),r}):r?eh(e=>eO(e,n,Number(r[1]))):eh(e=>eO(e,n))}},`add:${eH.join("|")}:${ev.join("|")}`),(0,o.jsx)("div",{className:at,children:"Fragments"}),0===(ef.fragments??[]).length&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None."}),(ef.fragments??[]).map((e,t)=>(0,o.jsxs)("div",{className:"mb-2 rounded border border-gray-800 p-1.5",children:[(0,o.jsxs)("div",{className:"flex items-center justify-between text-[11px] text-indigo-300",children:[(0,o.jsxs)("span",{children:[t+1,". ",(0,o.jsx)("span",{className:"font-semibold",children:e.kind})," · after ",e.after," · ",e.messages.length," message(s)"]}),(0,o.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":`Remove fragment ${t+1}`,onClick:()=>eh(e=>{let n;return eA(n=eC(e),t),n.fragments.splice(t,1),n.fragments.length||delete n.fragments,n}),children:"✕"})]}),(0,o.jsx)(an,{id:`edit-fragment-${t}`,fields:[{name:"kind",options:ew,initial:e.kind},{name:"after",placeholder:"after message",initial:String(e.after)},{name:"label",placeholder:"the condition, in words",initial:e.label,wide:!0}],submit:"Save fragment",onSubmit:e=>eh(n=>(function(e,t,n){let s=eC(e),r=eA(s,t);if(void 0!==n.kind&&!ew.includes(n.kind))throw Error(`A fragment is one of ${ew.join(", ")}; got '${n.kind}'.`);if(void 0!==n.after&&(!Number.isInteger(n.after)||n.after<0||n.after>s.messages.length))throw Error(`A fragment branches after a main message, 0 to ${s.messages.length}; got ${n.after}.`);return s.fragments[t]={...eE({...r,...n,messages:void 0}),messages:r.messages??[]},s})(n,t,{kind:ab(e.kind),after:Number(ab(e.after)),label:ab(e.label)}))})]},`${t}:${JSON.stringify({...e,messages:void 0})}`)),(0,o.jsx)(an,{id:"add-fragment",reset:!0,required:["label"],fields:[{name:"kind",options:ew},{name:"after",placeholder:"after message",initial:String(ey&&null===ey.fragment?ey.index+1:ef.messages.length)},{name:"label",placeholder:"the condition, in words",wide:!0},{name:"from",options:ev,label:"first message from"},{name:"to",options:ev,label:"to",initial:ev[1]??ev[0]??""},{name:"first",placeholder:"first message label (optional)",wide:!0}],submit:"+ Fragment",onSubmit:e=>eh(t=>(function(e,t){if(!ew.includes(t.kind))throw Error(`A fragment is one of ${ew.join(", ")}; got '${t.kind}'.`);if(!t.label?.trim())throw Error("A fragment needs a label: the condition in words.");let n=eC(e);if(!Number.isInteger(t.after)||t.after<0||t.after>n.messages.length)throw Error(`A fragment branches after a main message, 0 to ${n.messages.length}; got ${t.after}.`);for(let e of t.messages??[])e_(n,e);return(n.fragments??=[]).push({...eE({...t,messages:void 0}),messages:(t.messages??[]).map(e=>eE({...e}))}),n})(t,{kind:ab(e.kind),after:Number(ab(e.after)),label:ab(e.label),messages:ab(e.first)?[{from:ab(e.from),to:ab(e.to),label:ab(e.first)}]:[]}))},`add-fragment:${ef.messages.length}:${ey?.index??""}`)]}),(0,o.jsxs)("section",{className:"notes"===$?"":"hidden",children:[(0,o.jsx)("div",{className:at,style:{marginTop:0},children:"Notes"}),(0,o.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,o.jsx)(r8,{label:"On this sequence",value:h.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:e=>eh(t=>{var n;let s;return n={notes:e},(s=eC(t)).settings=eE({...s.settings,...n}),s})},"sequence"),eb&&(0,o.jsx)(r8,{label:`On ${eb.name}`,value:eb.notes??"",placeholder:`A question or a decision about ${eb.name}…`,onSave:e=>eh(t=>eT(t,eb.name,{notes:e}))},`participant:${eb.name}`),ey&&(0,o.jsx)(r8,{label:`On message ${x.id}`,value:ey.message.notes??"",placeholder:"A question or a decision about this message…",onSave:e=>eh(t=>eP(t,ey.index,{notes:e},ey.fragment))},`message:${x.id}`),!x&&(0,o.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Select a participant or a message to leave a note on it."}),[...ef.participants.filter(e=>e.notes?.trim()),...eg.filter(e=>e.message.notes?.trim())].length>0&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:at,children:"With notes"}),(0,o.jsxs)("div",{className:"flex flex-wrap gap-1",children:[ef.participants.filter(e=>e.notes?.trim()).map(e=>(0,o.jsx)("button",{className:ae,onClick:()=>ep(`participant:${e.name}`),children:e.name},`p${e.name}`)),eg.filter(e=>e.message.notes?.trim()).map(e=>(0,o.jsxs)("button",{className:ae,onClick:()=>ep(`message:${e.ref}`),children:["message ",e.ref]},`m${e.ref}`))]})]})]}),(0,o.jsxs)("section",{className:"issues"===$?"":"hidden",children:[(0,o.jsx)("div",{className:at,style:{marginTop:0},children:"Issues"}),Z.map((e,t)=>(0,o.jsxs)("button",{className:"block w-full py-0.5 text-left text-[11px] text-red-300",onClick:()=>ep(e.element),children:["[",e.ruleId,"] ",e.message]},`p${t}`)),ee.map((e,t)=>(0,o.jsxs)("button",{className:`block w-full py-0.5 text-left text-[11px] ${"error"===e.severity?"text-red-300":"text-amber-300"}`,onClick:()=>ep(e.element),children:["[",e.ruleId,"] ",e.message]},`s${t}`)),0===Z.length&&0===ee.length&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-green-400",children:Q?"Valid, and every name it uses resolves in the system.":"The document is valid."}),!r&&(0,o.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."}),r&&!G&&a&&(0,o.jsx)("p",{className:"mt-2 text-[11px] text-amber-300",children:"This document is not a member of the open system."}),et&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:at,children:["Replay against ",et.machines.join(", ")||"no machine"]}),et.paths.map(e=>(0,o.jsxs)("div",{className:"mb-2",children:[(0,o.jsxs)("div",{className:`text-[11px] font-semibold ${e.accepted?"text-green-400":"text-amber-300"}`,children:[e.name," — ",e.accepted?"accepted":"stops"]}),e.steps.filter(e=>"data"!==e.result).map(t=>(0,o.jsxs)("button",{className:`block w-full truncate py-0.5 pl-2 text-left font-mono text-[10.5px] ${"moved"===t.result||"stayed"===t.result?"text-gray-400":"text-amber-300"}`,title:t.note??t.result,onClick:()=>ep(`message:${t.ref}`),children:[t.ref,". ",t.event??""," ",t.from.join("|")||"·"," → ",t.to.join("|")||"·"," ",t.result]},`${e.name}:${t.ref}`))]},e.name))]})]})]})})]})]}),(0,o.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:eU.map(e=>{let t=S&&$===e.id;return(0,o.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(S&&$===t?L.close():M(!0),N(t))},"aria-pressed":t,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${t?"text-blue-400":"text-gray-500"}`,children:[(0,o.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,o.jsx)("span",{children:e.label}),void 0!==e.badge&&(0,o.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:e.badge}),t&&(0,o.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})})]})}function ak(e,t){let n=e?.members.find(e=>e.path===t)?.def;return n?.settings?.name||(t.split("/").pop()??t).replace(/\.(smdf|erdf|sqdf|sysdf)\.json$|\.json$/i,"")}let a$=(e,t)=>e?.members.find(e=>e.path===t)?.kind??"machine";function aN(e){return"message"===e.kind?`message ${e.name}`:`${e.kind} ${e.name}`}function aS({systemPath:e}){let t=rN("doc"),n=rN("focus"),{system:s}=au(e),[r,a]=(0,l.useState)(!1),[i,c]=(0,l.useState)(null),d=(0,l.useRef)(s);(0,l.useEffect)(()=>{d.current=s},[s]);let h=(0,l.useMemo)(()=>s?rZ(()=>te(s.members),[]):[],[s]),u=am(s,t),m=!!s&&(t===s.path||t===e),p=u&&n?function(e,t,n){let s=e9(n);if(!s)return[];let r=e=>e.member===t&&e.kind===s.kind&&e.name===s.name,a=[];for(let t of e)r(t.from)?a.push({other:t.to,text:t.text,rule:t.rule}):r(t.to)&&a.push({other:t.from,text:t.back,rule:t.rule});return a}(h,u,n):[],f=function(e,t){if(!t)return[];let n=new Map;for(let s of e)for(let e of[s.from,s.to]){if(e.member!==t)continue;let s=e7(e);n.set(s,(n.get(s)??0)+1)}return[...n.entries()].sort((e,t)=>e[0].localeCompare(t[0]))}(h,u);(0,l.useEffect)(()=>{let e=e=>{let t=e.detail;t?.text&&c({...t,at:Date.now()})};return window.addEventListener(rk,e),()=>window.removeEventListener(rk,e)},[]),(0,l.useEffect)(()=>{if(!i)return;let e=setTimeout(()=>c(null),9e3);return()=>clearTimeout(e)},[i]);let g=s?.path;(0,l.useEffect)(()=>{if(!g)return;let t=!0,n=null,s=null;return(async()=>{let{bridgeUrl:r}=await re();if(t&&r){var i;let t,o,l,h;(n=sy({url:r,role:"web",docId:g,name:"web-system-strip"})).on("view",t=>{let n=d.current;if(!n)return;let s=t.member?void 0!==n.absOf[t.member]?t.member:Object.keys(n.absOf).find(e=>n.absOf[e]===t.member):void 0;if(t.member&&!s)return void c({text:`ignored a view of ${t.member.split("/").pop()}: it is not a member of this system`,origin:t.origin,at:Date.now()});rS({doc:s?n.absOf[s]:g,system:e,focus:t.focus??null}),a(!1);let r=[s?ak(n,s):"the system map",t.focus].filter(Boolean).join(" · ");c({text:t.note?t.note:`showing ${r}`,origin:t.origin,at:Date.now()})}),n.on("full",()=>ah()),i=n,t=!1,o=!1,l=()=>{i.join().then(()=>{t=!0}).catch(()=>{})},h=i.on("status",e=>{"connected"!==e?o=t:o&&(o=!1,l())}),l(),s=()=>{h()}}})(),()=>{t=!1,s?.(),n?.disconnect()}},[g,e]);let x=t=>{a(!1),s&&rS({doc:t.member?s.absOf[t.member]??eJ(s.path,t.member):s.path,system:e,focus:t.focus??null})},y=s?.def?.members?.filter(e=>e?.path).map(e=>e.path)??[],b=s?.def?.settings?.name??(e.split("/").pop()??"system").replace(/\.sysdf\.json$/i,""),v=p.length;return(0,o.jsxs)("div",{className:"system-strip relative z-50 border-b border-gray-800 bg-gray-950 text-xs text-gray-300",children:[(0,o.jsxs)("div",{className:"flex h-[var(--strip-h)] items-center gap-1 px-1.5 md:px-2",children:[(0,o.jsxs)("button",{onClick:()=>x({}),className:`flex min-w-0 max-w-[30%] shrink-0 items-center gap-1 rounded px-1.5 py-1 md:max-w-[16rem] ${m?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,title:`${e} — the system map`,children:[(0,o.jsx)(as,{kind:"system",size:15}),(0,o.jsx)("span",{className:"truncate font-semibold",children:b})]}),(0,o.jsx)("span",{className:"h-4 w-px shrink-0 bg-gray-800"}),(0,o.jsxs)("nav",{className:"flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto [scrollbar-width:none]","aria-label":"Members",children:[y.map(e=>{let t=e===u,n=s?.members.find(t=>t.path===e)?.error;return(0,o.jsxs)("button",{onClick:()=>x({member:e}),"aria-current":t?"page":void 0,title:`${ak(s,e)} — ${e}${n?` (cannot be read: ${n})`:""}`,className:`flex shrink-0 items-center gap-1 rounded px-1.5 py-1 ${t?"bg-blue-950/60 text-blue-200":n?"text-red-400 hover:bg-gray-800":"text-gray-400 hover:bg-gray-800 hover:text-gray-200"}`,children:[(0,o.jsx)(as,{kind:a$(s,e),size:15}),(0,o.jsx)("span",{className:`max-w-[7.5rem] truncate md:max-w-[11rem] ${t?"":"hidden md:inline"}`,children:ak(s,e)})]},e)}),!s&&(0,o.jsx)("span",{className:"px-1 text-gray-600",children:"loading…"}),s?.error&&(0,o.jsx)("span",{className:"truncate px-1 text-amber-300",children:s.error})]}),(0,o.jsxs)("button",{onClick:()=>a(e=>!e),disabled:!u,"aria-expanded":r,title:u?n?`What ${n} 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 ${r?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,children:[(0,o.jsx)(as,{kind:"link",size:15}),(0,o.jsx)("span",{className:"hidden sm:inline",children:"Links"}),v>0&&(0,o.jsx)("span",{className:"rounded-full border border-gray-700 px-1 text-[10px] leading-4 text-gray-300",children:v})]})]}),i&&!r&&(0,o.jsx)("div",{className:"pointer-events-none absolute inset-x-0 top-full flex justify-center px-2 pt-1",role:"status",children:(0,o.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:[i.origin?(0,o.jsxs)("span",{className:"text-blue-300",children:[i.origin,": "]}):null,i.text]})}),r&&u&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:"fixed inset-0 z-40",onClick:()=>a(!1),"aria-hidden":"true"}),(0,o.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:[n&&e9(n)?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:"mb-1 flex items-center justify-between gap-2 text-[11px] text-gray-500",children:[(0,o.jsxs)("span",{className:"truncate",children:[(0,o.jsx)("span",{className:"text-gray-200",children:aN(e9(n))})," in ",ak(s,u)]}),(0,o.jsx)("button",{className:"shrink-0 text-gray-500 hover:text-gray-200",onClick:()=>rS({doc:t,focus:null}),children:"clear"})]}),0===p.length&&(0,o.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"Nothing in the other drawings names it."}),p.map((e,t)=>(0,o.jsxs)("button",{onClick:()=>x({member:e.other.member,focus:e7(e.other)}),className:"flex w-full items-start gap-2 rounded px-1.5 py-1.5 text-left hover:bg-gray-800",children:[(0,o.jsx)("span",{className:"mt-0.5 text-gray-400",children:(0,o.jsx)(as,{kind:a$(s,e.other.member),size:14})}),(0,o.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,o.jsx)("span",{className:"block text-[12px] text-gray-200",children:e.text}),(0,o.jsxs)("span",{className:"block truncate text-[10.5px] text-gray-500",children:[aN(e.other)," · ",ak(s,e.other.member)," · ",e.rule]})]})]},t))]}):null,(!n||!e9(n))&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["Elements of ",ak(s,u)," that the other drawings name — pick one to follow it."]}),0===f.length&&(0,o.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"None."}),(0,o.jsx)("div",{className:"flex flex-wrap gap-1",children:f.map(([e,n])=>(0,o.jsxs)("button",{onClick:()=>{a(!0),rS({doc:t,focus:e})},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:[e," ",(0,o.jsx)("span",{className:"text-gray-500",children:n})]},e))})]})]})]})]})}let aM={erd:"ERD",machine:"STATE MACHINE",sequence:"SEQUENCE",system:"SYSTEM"};function aC(e,t,n=!1){if(!t)return"";if("erd"===e)return`${t.entities?.length??0} entities \xb7 ${t.relationships?.length??0} relationships`;if("sequence"===e){let e=t.fragments?.length??0;return`${t.participants?.length??0} participants \xb7 ${t.messages?.length??0} messages${e&&!n?` \xb7 ${e} fragment${e>1?"s":""}`:""}`}let s=0,r=e=>{e&&(s+=1,(e.states??[]).forEach(r),(e.parallel?.states??[]).forEach(r))};(t.state?.states??[]).forEach(r),(t.state?.parallel?.states??[]).forEach(r);let a=(t.events??[]).reduce((e,t)=>e+(t?.events?.length??0)+(t?.timers?.length??0),0);return`${s} states \xb7 ${a} events`}let aE=(e,t)=>e<t?`${e}\u0000${t}`:`${t}\u0000${e}`;function aR(e){let t="message"===e.from.kind?`message ${e.from.name}`:`${e.from.kind} ${e.from.name}`;return`${t} ${e.text}`}function a_(){let e=(0,s1.useRequestedDoc)(),[t,n]=(0,l.useState)(e);(0,l.useEffect)(()=>{let t=!0;return e?n(e):r$("doc")||ao(null).then(e=>t&&n(e.path||null)),()=>{t=!1}},[e]);let{system:s,reload:r}=au(t),[a,i]=(0,l.useState)("members"),[c,d]=(0,l.useState)(!1),[h,u]=(0,l.useState)(!1),[m,p]=(0,l.useState)(!1),[f,g]=(0,l.useState)(null),[x,y]=(0,l.useState)({text:"loading…",tone:"ok"}),b=(0,l.useCallback)((e,t="ok")=>y({text:e,tone:t}),[]),[v,w]=(0,l.useState)(!1),j=rb({onClose:()=>d(!1),restVh:62,tallVh:92}),k=(0,l.useRef)(null),[$,N]=(0,l.useState)(!1);(0,l.useEffect)(()=>{let e=k.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();t.width&&N(t.height>1.1*t.width)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let S=(0,l.useRef)(!1);(0,l.useEffect)(()=>{s&&(s.error?b(s.error,"warn"):S.current||b(`${s.members.length} member${1===s.members.length?"":"s"} loaded`),S.current=!0)},[s,b]);let[M,C]=(0,l.useState)(!1);(0,l.useEffect)(()=>{let e=setTimeout(()=>C(!0),4e3);return()=>{clearTimeout(e),C(!1)}},[x]);let E=(0,l.useMemo)(()=>s?.def?rZ(()=>e8(s.def,s.members),null):null,[s]),R=(0,l.useMemo)(()=>s?rZ(()=>te(s.members),[]):[],[s]),_=(0,l.useMemo)(()=>s?.def?rZ(()=>tr(s.def,s.members),null):null,[s]),A=eF(s?.def),T=(0,l.useMemo)(()=>{let e=new Map;for(let t of R){if(t.from.member===t.to.member)continue;let n=aE(t.from.member,t.to.member),s=e.get(n)??{a:n.split("\0")[0],b:n.split("\0")[1],links:[]};s.links.push(t),e.set(n,s)}return e},[R]),O=(E?.issues??[]).filter(e=>"error"===e.severity),P=(E?.issues??[]).filter(e=>"warning"===e.severity),I=(t,n)=>{s&&rS({doc:s.absOf[t]??t,system:e??s.path,focus:n??null})},L=async(e,t)=>{if(s)try{await ac(s.path,e,s.mtimes[s.path]),b(t),ah()}catch(e){e instanceof al?(b("the system changed on disk — reloaded; make the change again","warn"),ah()):b(`not saved: ${e instanceof Error?e.message:String(e)}`,"warn")}},D=async()=>{if(!s||!_||!_.count)return;w(!0);let{result:e,written:t,failed:n,conflicts:r}=await ag(s.path);w(!1),n.length?b(`not all written: ${n.join("; ")}`,"warn"):r.length?b(`${r.join(", ")} kept changing on disk — not written; apply again`,"warn"):e?.count?b(`${ta(e,"propose").replace(/ proposed/," applied")} — ${t.length} file(s) written`):b("nothing to apply: the drawings on disk already agree")},q=$?420:760,B=$?640:520,F=s?.def?.members?.filter(e=>e?.path).map(e=>e.path)??[],U=s?.def?.actors??[],z=64*!!U.length,Y=(0,l.useMemo)(()=>{let e=F.length,t=q/2,n=(B-z)/2+6,s=Math.max(0,q/2-98-16),r=Math.max(0,(B-z)/2-46-18),a=new Map;return F.forEach((i,o)=>{if(1===e)return a.set(i,{x:t,y:n});if($){let t=B-z-46-16;return a.set(i,{x:o%2?.67*q:.33*q,y:62+(t-62)*o/(e-1)})}if(2===e)return a.set(i,$?{x:t,y:o?n+r:n-r}:{x:o?t+s:t-s,y:n});let l=-Math.PI/2+2*o*Math.PI/e;a.set(i,{x:t+s*Math.cos(l),y:n+r*Math.sin(l)})}),a},[F.join("|"),q,B,196,z,$]),H=(0,l.useMemo)(()=>{let e=new Map;for(let{member:t,def:n}of e6(s?.members??[]).sequences)for(let s of n.participants??[]){if(!s?.actor)continue;let n=e.get(s.actor)??[];n.includes(t)||n.push(t),e.set(s.actor,n)}return e},[s]),X=s?.def,V=(s?.path??t??"").split("/").pop()||"…",J=[{id:"members",label:"Members",icon:(0,o.jsx)(as,{kind:"system"})},{id:"checks",label:"Checks",icon:(0,o.jsx)(rx,{}),badge:O.length+P.length||void 0},{id:"notes",label:"Notes",icon:"✎"}],W=f?T.get(f):void 0,K=(0,l.useMemo)(()=>{let e=[];for(let t of["error","warning"]){let n=new Map;for(let e of E?.issues??[])e.severity===t&&n.set(e.ruleId,[...n.get(e.ruleId)??[],e]);for(let[s,r]of[...n.entries()].sort((e,t)=>e[0].localeCompare(t[0])))e.push({key:`${t}:${s}`,ruleId:s,severity:t,issues:r})}return e},[E]);return(0,o.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>h&&u(!1),children:[(0,o.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,o.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,o.jsx)(as,{kind:"system",size:14}),"SYS"]}),(0,o.jsx)(s2,{}),(0,o.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:s?.path,children:[X?.settings?.name??V,(0,o.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",V]})]}),(0,o.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,o.jsx)("button",{className:ae,onClick:r,title:"Read the system and every member again",children:"Re-check"}),(0,o.jsx)("button",{className:ae,onClick:()=>p(e=>!e),"aria-pressed":!m,children:m?"⟨ Panel":"Panel ⟩"})]}),(0,o.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,o.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":h,onClick:e=>{e.stopPropagation(),u(e=>!e)},children:"⋯"}),h&&(0,o.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,o.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{u(!1),r()},children:"Re-check the system"})})]})]}),(0,o.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,o.jsxs)("div",{ref:k,className:"relative min-w-0 flex-1 overflow-hidden bg-[#030712]",children:[s&&X&&(0,o.jsx)(rg,{what:"system map",resetKey:s,children:(0,o.jsxs)("svg",{className:"h-full w-full",viewBox:`0 0 ${q} ${B}`,preserveAspectRatio:"xMidYMid meet",role:"img","aria-label":`System map of ${X.settings?.name}`,children:[[...T.entries()].map(([e,t])=>{let n=Y.get(t.a),s=Y.get(t.b);if(!n||!s)return null;let r=(n.x+s.x)/2,a=(n.y+s.y)/2,l=`${t.links.length} link${1===t.links.length?"":"s"}`,c=6.4*l.length+16,h=f===e;return(0,o.jsxs)("g",{className:"cursor-pointer",onClick:()=>{g(h?null:e),i("members"),d(!0)},children:[(0,o.jsx)("line",{x1:n.x,y1:n.y,x2:s.x,y2:s.y,stroke:"transparent",strokeWidth:18}),(0,o.jsx)("line",{x1:n.x,y1:n.y,x2:s.x,y2:s.y,stroke:h?"#3b82f6":"#475569",strokeWidth:h?2.5:1.6}),(0,o.jsx)("rect",{x:r-c/2,y:a-11,width:c,height:22,rx:11,fill:"#0f172a",stroke:h?"#3b82f6":"#334155"}),(0,o.jsx)("text",{x:r,y:a+4,textAnchor:"middle",fontSize:11.5,fill:h?"#93c5fd":"#cbd5e1",children:l})]},e)}),U.map((e,t)=>{let n=(t+1)*q/(U.length+1),s=B-30;return(0,o.jsxs)("g",{children:[(H.get(e.name)??[]).map(e=>{let t=Y.get(e);return t?(0,o.jsx)("line",{x1:n,y1:s-14,x2:t.x,y2:t.y+46,stroke:"#334155",strokeDasharray:"3 4"},e):null}),(0,o.jsx)("title",{children:[`${e.kind}`,e.description??"",e.wheelNode??""].filter(Boolean).join(" — ")}),(0,o.jsx)("rect",{x:n-62,y:s-14,width:124,height:28,rx:14,fill:"#0c1020",stroke:"#6366f1"}),(0,o.jsx)("g",{transform:`translate(${n-54} ${s-8})`,color:"#a5b4fc",children:(0,o.jsx)(as,{kind:"actor",size:16})}),(0,o.jsx)("text",{x:n-34,y:s-1,fontSize:11.5,fontWeight:600,fill:"#e2e8f0",children:e.name.length>12?`${e.name.slice(0,11)}…`:e.name}),(0,o.jsx)("text",{x:n-34,y:s+9,fontSize:8.5,fill:"#94a3b8",children:e.kind})]},e.name)}),F.map(e=>{let t=Y.get(e),n=s.members.find(t=>t.path===e);if(!t||!n)return null;let r=n.kind,a=(E?.issues??[]).filter(t=>t.member===e),i=a.filter(e=>"error"===e.severity).length,l=a.filter(e=>"warning"===e.severity).length,c=t.x-98,d=t.y-46,h=ak(s,e),u=W&&(W.a===e||W.b===e);return(0,o.jsxs)("g",{className:"cursor-pointer",onClick:()=>I(e),children:[(0,o.jsx)("title",{children:`${e}${n.error?` — cannot be read: ${n.error}`:""}
14
+ Tap to open it inside the system.`}),(0,o.jsx)("rect",{x:c,y:d,width:196,height:92,rx:10,fill:"#0f172a",stroke:n.error?"#ef4444":u?"#3b82f6":i?"#b91c1c":"#475569",strokeWidth:u?2.2:1.5,strokeDasharray:n.error?"5 4":void 0}),(0,o.jsx)("g",{transform:`translate(${c+10} ${d+9})`,color:"#93c5fd",children:(0,o.jsx)(as,{kind:r,size:16})}),(0,o.jsx)("text",{x:c+32,y:d+21,fontSize:9,fontWeight:700,letterSpacing:"0.06em",fill:"#64748b",children:aM[r]}),(0,o.jsx)("text",{x:c+10,y:d+43,fontSize:14,fontWeight:600,fill:"#e2e8f0",children:h.length>22?`${h.slice(0,21)}…`:h}),(0,o.jsx)("text",{x:c+10,y:d+60,fontSize:10.5,fill:"#94a3b8",children:n.error?"cannot be read":aC(r,n.def,!0)}),(0,o.jsx)("text",{x:c+10,y:d+79,fontSize:10.5,fill:i?"#fca5a5":l?"#fcd34d":"#4ade80",children:n.error?n.error.length>30?`${n.error.slice(0,29)}…`:n.error:i||l?[i?`${i} error${i>1?"s":""}`:"",l?`${l} warning${l>1?"s":""}`:""].filter(Boolean).join(" · "):"checks pass"}),(0,o.jsx)("text",{x:c+196-10,y:d+79,fontSize:10.5,textAnchor:"end",fill:"#64748b",children:"open ›"})]},e)})]})}),s&&!X&&(0,o.jsx)("div",{className:"absolute inset-0 flex items-center justify-center p-6 text-center text-sm text-amber-300",children:s.error}),(0,o.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"===x.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,o.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===x.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,o.jsx)("span",{className:`truncate transition-opacity duration-500 ${M&&"ok"===x.tone?"opacity-0":"opacity-100"}`,children:x.text})]})]}),c&&(0,o.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:j.close,"aria-hidden":"true"}),s&&X&&(0,o.jsxs)("aside",{style:j.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 ${c?"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 ${m?"md:hidden":""}`,children:[(0,o.jsxs)("div",{className:"md:hidden",...j.zoneProps,children:[(0,o.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,o.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,o.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,o.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:J.find(e=>e.id===a)?.label}),(0,o.jsx)("button",{onClick:j.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,o.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:J.map(e=>(0,o.jsxs)("button",{onClick:()=>i(e.id),className:`relative flex-1 px-1 py-2 text-center text-xs transition-colors ${a===e.id?"border-b-2 border-blue-400 bg-gray-800/50 text-blue-400":"text-gray-500 hover:text-gray-300"}`,children:[e.label,void 0!==e.badge&&(0,o.jsx)("span",{className:"absolute right-1 top-1 min-w-[14px] rounded-full bg-red-900 px-1 text-[9px] text-red-100",children:e.badge})]},e.id))}),(0,o.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,o.jsxs)("section",{className:"members"===a?"":"hidden",children:[(0,o.jsx)("div",{className:at,style:{marginTop:0},children:"Members"}),F.map(e=>{let t=s.members.find(t=>t.path===e),n=X.members.find(t=>t.path===e)?.notes;return(0,o.jsxs)("div",{className:"mb-1 rounded border border-gray-800",children:[(0,o.jsxs)("button",{onClick:()=>I(e),className:"flex w-full items-start gap-2 p-2 text-left hover:bg-gray-800",children:[(0,o.jsx)("span",{className:"mt-0.5 text-blue-300",children:(0,o.jsx)(as,{kind:t?.kind??"machine"})}),(0,o.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,o.jsx)("span",{className:"block truncate text-[12px] font-semibold text-gray-200",children:ak(s,e)}),(0,o.jsx)("span",{className:"block truncate text-[10.5px] text-gray-500",children:e}),(0,o.jsx)("span",{className:`block text-[11px] ${t?.error?"text-red-300":"text-gray-400"}`,children:t?.error?`cannot be read: ${t.error}`:aC(t?.kind??"machine",t?.def)})]}),(0,o.jsx)("span",{className:"shrink-0 text-[11px] text-gray-500",children:"open ›"})]}),(0,o.jsx)("div",{className:"px-2 pb-2 [&_label]:mt-0",children:(0,o.jsx)(r8,{label:"Note on this member, in the system",value:n??"",placeholder:`Why ${ak(s,e)} is part of this system, what is open…`,onSave:t=>void L(function(e,t,n){let s=eK(e),r=s.members.findIndex(e=>e.path===t);if(r<0)throw Error(`'${t}' is not a member. Members: ${e.members.map(e=>e.path).join(", ")||"none"}.`);return s.members[r]=eZ({...s.members[r],...n}),s}(X,e,{notes:t}),"saved")},`member:${e}`)})]},e)}),(0,o.jsx)("div",{className:at,children:"Links between members"}),0===T.size&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"No name crosses between the members yet."}),[...T.entries()].map(([e,t])=>(0,o.jsxs)("div",{className:"mb-1",children:[(0,o.jsxs)("button",{className:`flex w-full items-center justify-between rounded px-1.5 py-1 text-left text-[11px] ${f===e?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,onClick:()=>g(f===e?null:e),children:[(0,o.jsxs)("span",{className:"truncate",children:[ak(s,t.a)," ↔ ",ak(s,t.b)]}),(0,o.jsx)("span",{className:"shrink-0 text-gray-500",children:t.links.length})]}),f===e&&(0,o.jsx)("div",{className:"ml-2 border-l border-gray-800 pl-2",children:t.links.map((e,t)=>(0,o.jsxs)("button",{className:"block w-full truncate py-0.5 text-left text-[11px] text-gray-400 hover:text-gray-200",title:`${aR(e)} — ${e.rule}`,onClick:()=>{let t;return I((t=e.from).member,e7(t))},children:[(0,o.jsx)("span",{className:"text-gray-600",children:e.rule})," ",aR(e)]},t))})]},e)),U.length>0&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:at,children:"Actors"}),U.map(e=>(0,o.jsxs)("div",{className:"py-0.5 text-[11px] text-gray-300",children:[e.name," ",(0,o.jsxs)("span",{className:"text-gray-500",children:["· ",e.kind]}),e.description?(0,o.jsxs)("span",{className:"text-gray-500",children:[" — ",e.description]}):null]},e.name))]})]}),(0,o.jsxs)("section",{className:"checks"===a?"":"hidden",children:[(0,o.jsx)("div",{className:at,style:{marginTop:0},children:"Checks"}),(0,o.jsxs)("div",{className:`text-[11px] ${O.length?"text-red-300":P.length?"text-amber-300":"text-green-400"}`,children:[O.length," error",1===O.length?"":"s"," · ",P.length," warning",1===P.length?"":"s"]}),K.map(e=>(0,o.jsxs)("div",{className:"mt-2",children:[(0,o.jsxs)("div",{className:`text-[11px] font-semibold ${"error"===e.severity?"text-red-300":"text-amber-300"}`,children:[e.ruleId," · ",e.issues.length," ",e.severity,1===e.issues.length?"":"s"]}),e.issues.map((e,t)=>(0,o.jsxs)("button",{className:"block w-full py-0.5 pl-2 text-left text-[11px] text-gray-300 hover:text-white",onClick:()=>{e.member&&I(e.member,e.element&&/^[a-z]+:/.test(e.element)?e.element:null)},title:e.member?`Open ${e.member}${e.element?` at ${e.element}`:""}`:void 0,children:[e.message,e.member&&(0,o.jsxs)("span",{className:"text-gray-500",children:[" — ",ak(s,e.member)]})]},t))]},e.key)),(0,o.jsx)("div",{className:at,children:"Reconcile"}),(0,o.jsxs)("p",{className:"mb-1 text-[11px] text-gray-500",children:["What the scenarios imply for the machines and the data. ",(0,o.jsx)("b",{className:"text-gray-400",children:"propose"})," lists it here to apply by hand; ",(0,o.jsx)("b",{className:"text-gray-400",children:"auto"})," writes it each time a scenario is saved."]}),(0,o.jsx)("span",{className:"inline-flex overflow-hidden rounded border border-gray-700",role:"group","aria-label":"Reconcile mode",children:eB.map(e=>(0,o.jsx)("button",{"aria-pressed":A===e,onClick:()=>{s?.def&&e!==A&&L(function(e,t){if(!eB.includes(t))throw Error(`The reconcile mode is ${eB.join(" or ")}; got '${t}'.`);return eG(e,{reconcile:t})}(s.def,e),`reconcile mode: ${e}`)},className:`px-3 py-1 text-xs ${A===e?"bg-blue-900/60 text-blue-200":"bg-gray-800 text-gray-400 hover:bg-gray-700"}`,children:e},e))}),(0,o.jsx)("div",{className:"mt-2 text-[11px] font-semibold text-gray-400",children:"Scenario changes"}),_&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:"text-[11px] text-gray-500",children:ta(_,"propose")}),_.machines.map(e=>(0,o.jsxs)("div",{className:"mt-1",children:[(0,o.jsxs)("div",{className:"text-[11px] text-gray-300",children:[e.machine," ",(0,o.jsxs)("span",{className:"text-gray-500",children:["· ",e.member]})]}),e.reasons.map((e,t)=>(0,o.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",e]},t))]},e.member)),_.erds.map(e=>(0,o.jsxs)("div",{className:"mt-1",children:[(0,o.jsxs)("div",{className:"text-[11px] text-gray-300",children:[e.def.settings?.name??e.member," ",(0,o.jsxs)("span",{className:"text-gray-500",children:["· ",e.member]})]}),e.reasons.map((e,t)=>(0,o.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",e]},t))]},e.member)),_.system&&(0,o.jsxs)("div",{className:"mt-1",children:[(0,o.jsx)("div",{className:"text-[11px] text-gray-300",children:"the system"}),_.system.reasons.map((e,t)=>(0,o.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",e]},t))]}),_.unresolved.map((e,t)=>(0,o.jsxs)("div",{className:"mt-1 text-[11px] text-amber-300",children:["left open: ",e]},t)),(0,o.jsx)("button",{className:`${ae} mt-2 disabled:opacity-40`,disabled:!_.count||v,onClick:D,children:v?"Applying…":`Apply${_.count?` ${_.count} change${1===_.count?"":"s"}`:""}`})]}),(E?.replays??[]).map(({member:e,report:t})=>(0,o.jsxs)("div",{children:[(0,o.jsxs)("div",{className:at,children:["Replay · ",ak(s,e)]}),(0,o.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["against ",t.machines.join(", ")||"no machine"]}),t.paths.map(t=>(0,o.jsxs)("div",{className:"mb-2",children:[(0,o.jsxs)("div",{className:`text-[11px] font-semibold ${t.accepted?"text-green-400":"text-amber-300"}`,children:[t.name," — ",t.accepted?"accepted":"stops"]}),t.steps.filter(e=>"data"!==e.result).map(n=>(0,o.jsxs)("button",{className:`block w-full truncate py-0.5 pl-2 text-left font-mono text-[10.5px] ${"moved"===n.result||"stayed"===n.result?"text-gray-400":"text-amber-300"}`,title:n.note??n.result,onClick:()=>I(e,`message:${n.ref}`),children:[n.ref,". ",n.event??""," ",n.from.join("|")||"·"," → ",n.to.join("|")||"·"," ",n.result]},`${t.name}:${n.ref}`))]},t.name))]},e))]}),(0,o.jsxs)("section",{className:"notes"===a?"":"hidden",children:[(0,o.jsx)("div",{className:at,style:{marginTop:0},children:"Notes"}),(0,o.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the system file, for whoever opens it next."}),(0,o.jsx)(r8,{label:"On this system",value:X.settings?.notes??"",placeholder:"What the system is for, what is still open…",onSave:e=>void L(eG(X,{notes:e}),"saved")},"system"),X.settings?.description&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:at,children:"Description"}),(0,o.jsx)("p",{className:"text-[11px] text-gray-400",children:X.settings.description})]})]})]})]})]}),(0,o.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:J.map(e=>{let t=c&&a===e.id;return(0,o.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(c&&a===t?j.close():d(!0),i(t))},"aria-pressed":t,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${t?"text-blue-400":"text-gray-500"}`,children:[(0,o.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,o.jsx)("span",{children:e.label}),void 0!==e.badge&&(0,o.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:e.badge}),t&&(0,o.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})})]})}function aA(){let e=sP(e=>e.definition),t=sP(e=>e.layout.positions),n=sP(e=>e.navigationPath),s=sP(e=>e.viewport),r=sP(e=>e.setViewport),a=sP(e=>e.docPath),i=rN("focus"),c=(0,l.useMemo)(()=>({get current(){return document.getElementById("machine-board")}}),[]),d=n.slice(1),h=(0,l.useMemo)(()=>e?.state?function(e,t){let n=[];for(let s of e){let e=s?.name?t[s.name]:void 0;e&&n.push({focus:`state:${s.name}`,box:e})}for(let s of e){let r=s?.name?t[s.name]:void 0;if(r)for(let a of s.transitions??[]){if(!a?.event)continue;let s=a.nextState?t[a.nextState]:void 0;n.push({focus:`event:${a.event}`,box:s&&e.some(e=>e.name===a.nextState)?tx([r,s]):r})}}return n}(t$(e.state,d),t):[],[e,t,n]);return(0,o.jsx)(rW,{docPath:a,kind:"machine",viewport:s,setViewport:r,boxes:h,boardRef:c,focus:i,level:n[n.length-1],onReveal:e=>{let t=e.map(e9).find(e=>e?.kind==="state");if(!t)return;let n=new URL(window.location.href);n.searchParams.set("focus",`state:${t.name}`),window.history.replaceState(window.history.state,"",n),window.dispatchEvent(new Event(rw))}})}let aT=e=>e.parallel?e.parallel.states:e.states??[];function aO(e,t){if(!e)return null;if(e.name===t)return[e.name];for(let n of aT(e)){let s=aO(n,t);if(s)return[e.name,...s]}return null}function aP(){let e=(0,s1.useRequestedDoc)(),t=rN("system"),[n,s]=(0,l.useState)(null);(0,l.useEffect)(()=>{let e=!0;return re().then(t=>{e&&s(t.projectFile?eH(t.projectFile):"machine")}),()=>{e=!1}},[]);let r=e?eH(e):n;if(null===r)return(0,o.jsx)("div",{className:"app-shell bg-gray-950"});let a=e??"default",i="erd"===r?(0,o.jsx)(r6,{},a):"sequence"===r?(0,o.jsx)(aj,{},a):"system"===r?(0,o.jsx)(a_,{},a):(0,o.jsx)(aI,{}),c=(0,o.jsx)(rg,{what:"document",resetKey:e,children:i});return t&&ez(t)?(0,o.jsx)(rX,{children:(0,o.jsxs)("div",{className:"system-frame",children:[(0,o.jsx)(aS,{systemPath:t}),c]})}):(0,o.jsx)(rX,{children:c})}function aI(){var e,t;let n,s,r,a;n=rC(),s=(0,l.useRef)(null),(0,l.useEffect)(()=>{let e=()=>{let e=s.current;if(!e)return;let t=sP.getState(),n=r$("doc");if(n&&t.docPath!==n||e.docAt!==t.docPath&&t.definition===e.defAt)return;s.current=null;let r=e9(e.focus);if(!r)return;let a=null,i=null;if("state"===r.kind)(a=aO(t.definition.state,r.name))&&(i={kind:"state",id:r.name});else if("event"===r.kind){let e=function e(t,n){if(!t)return null;let s=(t.transitions??[]).findIndex(e=>e?.event===n);if(s>=0)return{state:t.name,index:s};for(let s of aT(t)){let t=e(s,n);if(t)return t}return null}(t.definition.state,r.name);e&&(a=aO(t.definition.state,e.state),i={kind:"transition",id:`${e.state}:${e.index}`})}if(!a||!i)return;let o=a.length>1?a.slice(0,-1):a;sP.setState({navigationPath:o,currentParent:o[o.length-1]}),t.select(i.kind,i.id);let l=()=>{let e=sP.getState().layout.positions[a[a.length-1]],t=document.getElementById(sq)?.getBoundingClientRect();if(!e||!t?.width)return;let n=H([e],t.width,t.height,{padding:60,maxScale:1});sP.getState().setViewport(n)};requestAnimationFrame(l),setTimeout(l,450)};if(n.nonce>0){let t=sP.getState();s.current=n.focus?{focus:n.focus,docAt:t.docPath,defAt:t.definition}:null,e()}return sP.subscribe(e)},[n]),(0,l.useEffect)(()=>sP.subscribe((e,t)=>{if(e.selection===t.selection||!e.selection.id)return;let{kind:n,id:s}=e.selection;if("state"===n)rM(`state:${s}`);else if("event"===n)rM(`event:${s}`);else if("transition"===n){let t=function(e,t){let n=t.lastIndexOf(":"),s=aO(e.state,t.slice(0,n));if(!s)return null;let r=e.state;for(let e of s.slice(1))r=aT(r).find(t=>t.name===e);return r?.transitions?.[Number(t.slice(n+1))]?.event??null}(e.definition,s);t&&rM(`event:${t}`)}}),[]);let[i,c]=(0,l.useState)("properties"),[d,h]=(0,l.useState)(!1),u=rb({onClose:()=>h(!1),restVh:70,tallVh:92}),m=sP(e=>e.errors),p=sP(e=>e.contextMenu),f=sP(e=>e.hideContextMenu),g=sP(e=>e.addState),x=sP(e=>e.removeState),y=sP(e=>e.setDrawMode),b=sP(e=>e.setDrawSource),v=[{id:"properties",label:"Properties",icon:"🎛"},{id:"events",label:"Events",icon:"⚡"},{id:"settings",label:"Settings",icon:"⚙"},{id:"validation",label:"Errors",icon:(0,o.jsx)(rx,{}),badge:m.length||void 0}],w=v.find(e=>e.id===i)?.label??"";return(0,o.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden",onClick:()=>p.visible&&f(),children:[(0,o.jsx)(rt,{}),(0,o.jsx)(rp,{}),(0,o.jsx)(s4,{}),(0,o.jsxs)("div",{className:"flex flex-1 min-h-0 overflow-hidden relative",children:[(0,o.jsxs)("div",{className:"relative flex-1 overflow-hidden",id:"machine-board",children:[(0,o.jsx)(rg,{what:"state machine",children:(0,o.jsx)(sJ,{})}),(0,o.jsx)(aA,{})]}),d&&(0,o.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:u.close,"aria-hidden":"true"}),(0,o.jsxs)("aside",{style:u.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 ${d?"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,o.jsxs)("div",{className:"md:hidden",...u.zoneProps,children:[(0,o.jsx)("div",{className:"flex justify-center pt-2 pb-1",children:(0,o.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,o.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,o.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:w}),(0,o.jsx)("button",{onClick:u.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,o.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:v.map(e=>(0,o.jsxs)("button",{onClick:()=>c(e.id),className:`flex-1 text-xs py-2 px-1 text-center transition-colors relative ${i===e.id?"text-blue-400 border-b-2 border-blue-400 bg-gray-800/50":"text-gray-500 hover:text-gray-300"}`,children:[e.label,void 0!==e.badge&&e.badge>0&&(0,o.jsx)("span",{className:"absolute top-1 right-1 bg-red-600 text-white text-[9px] rounded-full px-1 min-w-[14px]",children:e.badge})]},e.id))}),(0,o.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain",children:["properties"===i&&(0,o.jsx)(sK,{}),"events"===i&&(0,o.jsx)(sG,{}),"settings"===i&&(0,o.jsx)(sQ,{}),"validation"===i&&(0,o.jsx)(s0,{})]})]}),(0,o.jsx)(s3,{})]}),(0,o.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:v.map(e=>{let t=d&&i===e.id;return(0,o.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(d&&i===t?u.close():h(!0),c(t))},"aria-pressed":t,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${t?"text-blue-400":"text-gray-500"}`,children:[(0,o.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,o.jsx)("span",{children:e.label}),void 0!==e.badge&&e.badge>0&&(0,o.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:e.badge}),t&&(0,o.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})}),p.visible&&(0,o.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:(e=p.x,t=p.y,r=window.innerWidth,a=window.innerHeight,{left:e,top:t,maxWidth:"calc(100vw - 1rem)",maxHeight:"calc(100dvh - 1rem)",overflowY:"auto",transform:`translate(${r>0&&e>r/2?"-100%":"0"}, ${a>0&&t>a/2?"-100%":"0"})`}),onClick:e=>e.stopPropagation(),children:p.target?.kind==="state"?(0,o.jsxs)(o.Fragment,{children:[(0,o.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:()=>{y("transition"),b(p.target.id),f()},children:"↗ Draw transition from here"}),(0,o.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:()=>{p.target?.id&&x(p.target.id),f()},children:"🗑 Delete state"})]}):(0,o.jsx)(o.Fragment,{children:(0,o.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 e=prompt("State name:");e&&g(null,{name:e,kind:"normal"}),f()},children:"+ Add state here"})})})]})}e.s(["default",()=>aP],63052)}]);