diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 73e5478..89888d8 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -22,7 +22,9 @@ jobs: run: npm run check:sync - name: ESLint run: npm run lint - - name: Type check + - name: Type check (page scripts; server, tools and tests in strict mode) run: npm run typecheck - - name: Strict type check (no new errors vs baseline) + - name: Strict type check (shared core 0 errors; rest no new errors vs baseline) run: npm run typecheck:strict + - name: Unit tests (parsers, layout, styles, server) + run: npm test diff --git a/3d.html b/3d.html index 2c4db7d..2257a71 100644 --- a/3d.html +++ b/3d.html @@ -48,7 +48,7 @@ --d-mono:ui-monospace,"SF Mono",Menlo,Consolas,monospace; --d-bg:#f5f0e6; --d-bg2:#fbf7ee; --d-ink:#1f2430; --d-accent:#ee5a3a; --d-accent-fg:#fff; --d-plate:#fffdf8; --d-plate-fg:#1f2430; --d-plate-bd:#1f2430; --d-on:#1f2430; --d-on-fg:#f5f0e6; --d-muted:#6b6f7b; - --d-zone:rgba(31,36,48,.035); --d-zone-bd:rgba(31,36,48,.45); --d-chip:rgba(245,240,230,.75); --d-lab-shadow:rgba(31,36,48,.2); + --d-zone:rgba(31,36,48,.035); --d-zone-bd:rgba(31,36,48,.45); --d-chip:rgba(245,240,230,.75); --d-lab-shadow:rgba(31,36,48,.2); --d-lab:var(--d-sans); } *{box-sizing:border-box} [hidden]{display:none!important} @@ -263,7 +263,7 @@ .lab.in{opacity:1} .lab.in.ghost{opacity:.2} .lab.node{transform-origin:50% 100%;padding-bottom:8px} -.lab.node span{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:3;overflow:hidden;max-width:150px;white-space:normal;text-align:center;font:600 12.5px/1.25 var(--d-sans);color:var(--d-plate-fg);background:var(--d-plate);border:1.4px solid var(--d-plate-bd);border-radius:8px;padding:4px 9px;box-shadow:0 2px 0 var(--d-lab-shadow);overflow-wrap:anywhere;transition:background .3s,color .3s} +.lab.node span{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:3;overflow:hidden;max-width:150px;white-space:normal;text-align:center;font:600 12.5px/1.25 var(--d-lab);color:var(--d-plate-fg);background:var(--d-plate);border:1.4px solid var(--d-plate-bd);border-radius:8px;padding:4px 9px;box-shadow:0 2px 0 var(--d-lab-shadow);overflow-wrap:anywhere;transition:background .3s,color .3s} .lab.node::after{content:"";position:absolute;left:50%;bottom:4px;width:8px;height:8px;background:var(--d-plate);border:solid var(--d-plate-bd);border-width:0 1.4px 1.4px 0;transform:translateX(-50%) rotate(45deg);transition:background .3s} .lab.node.active span{background:var(--d-on);border-color:var(--d-on);color:var(--d-on-fg)} .lab.node.active::after{background:var(--d-on);border-color:var(--d-on)} @@ -910,19 +910,32 @@

Flow
Explainer

import * as THREE from './vendor/three.module.js'; "use strict"; const $=s=>document.querySelector(s); -const esc=s=>String(s).replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c])); +/* ---------- shared core: helpers, markdown + Mermaid parsers, layout, diagram styles + settings (same in index.html and 3d.html; edit in index.html, then run tools/sync-parser.py) ---------- */ +/** @typedef {{id:string,label:string,shape:string,group:number|null,gx?:number,gy?:number,note?:string,icon?:string,iconFallback?:string,ci?:number,hk?:number,actor?:boolean,special?:string,kind?:string,members?:{f:string[],a:string[]},attrs?:string[],junction?:boolean,rank?:number,color?:string}} FxNode */ +/** @typedef {FxNode & {gx:number,gy:number}} PlacedNode */ +/** @typedef {{u:number,v:number,fw:boolean,bw:boolean,flip:boolean,a:number,b:number,chain:LayoutItem[],pts:number[][]}} Route */ +/** @typedef {{real:boolean,i?:number,r:number,up:LayoutItem[],down:LayoutItem[],y:number,p?:number,bc?:number}} LayoutItem */ +/** @typedef {{from:string,to:string,label:string,dotted:boolean,arrow:boolean,pts?:number[][]|null,route?:Route|null,an?:string,bn?:string}} FxLink */ +/** @typedef {{title:string,icon?:string}} Group */ +/** @typedef {{type:string,nodes:FxNode[],links:FxLink[],steps:Step[],groups:Group[],fixed?:boolean,noZones?:boolean,diagramTitle?:string,title?:string,intro?:string}} Graph */ +/** @typedef {{title:string,intro:string,code:string,ordered:string[],named:Array<[string,string]>}} Scene */ +/** @typedef {{docTitle:string,scenes:Scene[]}} MdDoc */ +/** @param {unknown} s */ +const esc=s=>String(s).replace(/[&<>"]/g,c=>/** @type {Record} */({'&':'&','<':'<','>':'>','"':'"'})[c]); +/** @param {string} s */ const mdInline=s=>esc(s).replace(/\*\*(.+?)\*\*/g,'$1').replace(/`([^`]+)`/g,'$1'); /* ---------- markdown ---------- */ +/** @param {string} md @returns {MdDoc} */ function parseMarkdown(md){ const lines=md.replace(/\r/g,'').split('\n'); - let docTitle='',heading='',para=[],cur=null;const scenes=[]; + let docTitle='',heading='',para=/** @type {string[]} */([]),cur=/** @type {Scene|null} */(null);const scenes=/** @type {Scene[]} */([]); for(let i=0;iFlow
Explainer } /* ---------- mermaid: shared ---------- */ +/** @param {string|null|undefined} t @returns {string} */ function cleanText(t){ t=(t||'').trim(); if(/^".*"$/.test(t)||/^'.*'$/.test(t))t=t.slice(1,-1); if(/^`.*`$/.test(t))t=t.slice(1,-1); - return t.replace(//gi,' ').replace(/<[^>]+>/g,'').replace(/#quot;/g,'"').replace(/#(\d+);/g,(_,n)=>String.fromCharCode(n)) + return t.replace(//gi,' ').replace(/<[^>]+>/g,'').replace(/#quot;/g,'"').replace(/#(\d+);/g,(_,/** @type {string} */n)=>String.fromCharCode(+n)) .replace(/\bfa[bsrl]?:fa-[\w-]+\s*/g,'').replace(/\*\*|__/g,'').replace(/\\n/g,' ').replace(/\s+/g,' ').trim(); } +/** @param {string} code */ function codeLines(code){ let ls=code.split('\n').map(l=>l.replace(/%%.*$/,'').trim().replace(/;$/,'')); if(ls.find(l=>l)==='---'){const a=ls.indexOf('---'),b=ls.indexOf('---',a+1);if(b>a)ls=ls.slice(b+1)} return ls.filter(l=>l); } +/** @param {string} code @returns {Graph} */ function parseMermaid(code){ + const ls=codeLines(code); if(!ls.length)throw new Error('The mermaid block is empty.'); if(/^(flowchart|graph)\b/i.test(ls[0]))return parseFlow(ls.slice(1)); @@ -983,16 +1000,20 @@

Flow
Explainer

/* ---------- mermaid: flowchart ---------- */ const ID_RE=/^[\wÀ-￿]+(?:[-.][\wÀ-￿]+)*/; +/** @type {Array<[string,string|null,string]>} */ const SHAPES=[['(((',')))','circle'],['([','])','pill'],['[[',']]','box'],['[(',')]','cyl'],['((','))','circle'],['{{','}}','hex'],['[/',null,'box'],['[\\',null,'box'],['[',']','box'],['(',')','pill'],['{','}','hex'],['>',']','box']]; +/** @type {Record} */ const SHAPE_ALIAS={cyl:'cyl',cylinder:'cyl',database:'cyl',db:'cyl',diamond:'hex',diam:'hex',decision:'hex',hex:'hex',hexagon:'hex',circle:'circle',circ:'circle','sm-circ':'circle',stadium:'pill',pill:'pill',rounded:'pill',terminal:'pill'}; +/** @param {string[]} ls @returns {Graph} */ function parseFlow(ls){ - const nodes=new Map(),links=[],groups=[],stack=[]; + const nodes=/** @type {Map} */(new Map()),links=/** @type {FxLink[]} */([]),groups=/** @type {Group[]} */([]),stack=/** @type {number[]} */([]); + /** @param {string} id @returns {FxNode} */ const getNode=id=>{ if(!nodes.has(id))nodes.set(id,{id,label:id,shape:'box',group:null}); - const n=nodes.get(id);if(n.group==null&&stack.length)n.group=stack[stack.length-1];return n; + const n=/** @type {FxNode} */(nodes.get(id));if(n.group==null&&stack.length)n.group=stack[stack.length-1];return n; }; for(const line of ls){ - let m; + /** @type {RegExpMatchArray|null} */ let m; if(/^(classDef|class|style|linkStyle|click|direction|accTitle|accDescr)\b/.test(line))continue; if(m=line.match(/^subgraph\s+(.*)$/)){ const rest=m[1].trim();const t=rest.match(/^[\w-]+\s*\[(.+)\]$/); @@ -1001,6 +1022,7 @@

Flow
Explainer

if(line==='end'){stack.pop();continue} statement(line); } + /** @param {string} s */ function statement(s){ let pos=0; const ws=()=>{while(s[pos]===' '||s[pos]==='\t')pos++}; @@ -1030,7 +1052,8 @@

Flow
Explainer

return arr; }; const edgeTok=()=>{ - ws();const r=s.slice(pos);let m,label='',tok; + ws();const r=s.slice(pos);let label='',tok;/** @type {RegExpMatchArray|null} */let m; + if(m=r.match(/^|-{3,}|-{2,}[ox](?=\s)|={2,}>|={3,}|-\.+->?|~{3,})/)){tok=m[0];pos+=m[0].length} else if(m=r.match(/^.])\s*(.+?)\s*(\.+-+>?|={2,}>?|-{2,}>?)(?=\s|$|[\w("'[])/)){tok=m[1]+m[3];label=m[2];pos+=m[0].length} else return null; @@ -1045,8 +1068,10 @@

Flow
Explainer

} } const N=[...nodes.values()];if(!N.length)throw new Error('No boxes found in the flowchart.'); - const by=id=>nodes.get(id); + const by=(/** @type {string} */id)=>/** @type {FxNode} */(nodes.get(id)); + /** @type {Step[]} */ const steps=links.map((l,i)=>{ + const a=by(l.from),b=by(l.to); if(a===b)return {kind:'node',nodes:[a.id],title:a.label,auto:l.label||('**'+a.label+'** repeats.')}; let auto; @@ -1058,15 +1083,19 @@

Flow
Explainer

} /* ---------- mermaid: sequence ---------- */ +/** @param {string[]} ls @returns {Graph} */ function parseSeq(ls){ - const nodes=new Map(),links=[],lmap=new Map(),steps=[],ctx=[]; + const nodes=/** @type {Map} */(new Map()),links=/** @type {FxLink[]} */([]),lmap=/** @type {Map} */(new Map()),steps=/** @type {Step[]} */([]),ctx=/** @type {Array<{text:string|null}>} */([]); + /** @type {Record} */ const WORD={alt:'When',else:'Otherwise',opt:'Optional',loop:'Repeat',par:'In parallel',and:'In parallel',critical:'Critical',break:'Stop if',option:'Otherwise'}; + /** @param {string} id @param {string} [label] @param {boolean} [actor] @returns {FxNode} */ const getNode=(id,label,actor)=>{ id=id.trim(); if(!nodes.has(id)){const lb=cleanText(label||id);nodes.set(id,{id,label:lb,shape:actor?'pill':(/\b(db|database|sql|mysql|postgres|redis|cache|storage|store|s3)\b|資料庫/i.test(lb)?'cyl':'box'),group:null,actor:!!actor})} - return nodes.get(id); + return /** @type {FxNode} */(nodes.get(id)); }; - const tag=()=>{for(let i=ctx.length-1;i>=0;i--)if(ctx[i].text!=null)return ctx[i].text;return ''}; + + const tag=()=>{for(let i=ctx.length-1;i>=0;i--)if(ctx[i].text!=null)return /** @type {string} */(ctx[i].text);return ''}; for(const line of ls){ let m; if(m=line.match(/^(?:create\s+)?(participant|actor)\s+(.+?)(?:\s+as\s+(.+))?$/i)){getNode(m[2],m[3],/actor/i.test(m[1]));continue} @@ -1092,40 +1121,50 @@

Flow
Explainer

/* ---------- mermaid: shared helpers for the other diagram types ---------- */ /** @typedef {{kind:string,nodes:string[],title:string,auto:string,tag?:string,chip?:string,link?:number,reverse?:boolean,from?:string,to?:string,text?:string,custom?:boolean}} Step */ +/** @typedef {{label?:string,dotted?:boolean,arrow?:boolean}} LinkOpts */ +/** @typedef {{auto:string,title?:string,chip?:string,tag?:string}} StepOpts */ +/** @param {string} s */ const ucWords=s=>/[a-z]/.test(s)||!/[A-Z]/.test(s)?s:s.toLowerCase().replace(/[_-]+/g,' ').replace(/^\w/,c=>c.toUpperCase()); function graphKit(){ - const nodes=new Map(),links=[],groups=[],stack=[]; + const nodes=/** @type {Map} */(new Map()),links=/** @type {FxLink[]} */([]),groups=/** @type {Group[]} */([]),stack=/** @type {number[]} */([]); + /** @param {string} id @param {string|null} [label] @param {string} [shape] @returns {FxNode} */ const node=(id,label,shape)=>{ if(!nodes.has(id))nodes.set(id,{id,label:label||id,shape:shape||'box',group:stack.length?stack[stack.length-1]:null}); - return nodes.get(id); + return /** @type {FxNode} */(nodes.get(id)); }; + /** @param {FxNode} a @param {FxNode} b @param {LinkOpts} [o] */ const link=(a,b,o={})=>{links.push({from:a.id,to:b.id,label:o.label||'',dotted:!!o.dotted,arrow:!!o.arrow});return links.length-1}; - /** @returns {Step} */ - const edgeStep=(li,o)=>{const l=links[li],a=nodes.get(l.from),b=nodes.get(l.to); + /** @param {number} li @param {StepOpts} o @returns {Step} */ + const edgeStep=(li,o)=>{const l=links[li],a=/** @type {FxNode} */(nodes.get(l.from)),b=/** @type {FxNode} */(nodes.get(l.to)); return {kind:'edge',link:li,reverse:false,from:a.id,to:b.id,nodes:[a.id,b.id],title:o.title||(a.label+' → '+b.label),chip:o.chip||'',auto:o.auto,tag:o.tag||''}}; - /** @returns {Step} */ + /** @param {FxNode} n @param {StepOpts} o @returns {Step} */ const nodeStep=(n,o)=>({kind:'node',nodes:[n.id],title:o.title||n.label,auto:o.auto,tag:o.tag||''}); - const addNote=(n,t)=>{t=cleanText(t);if(t)n.note=n.note?n.note+' '+t:t}; + /** @param {FxNode} n @param {string} t */ + const addNote=(n,t)=>{ +t=cleanText(t);if(t)n.note=n.note?n.note+' '+t:t}; return {nodes,links,groups,stack,node,link,edgeStep,nodeStep,addNote}; } /* ---------- mermaid: state ---------- */ +/** @param {string[]} ls @returns {Graph} */ function parseState(ls){ - const K=graphKit(),steps=[],comp=[],trs=[]; - const B=s=>'**'+s+'**'; + const K=graphKit(),steps=/** @type {Step[]} */([]),comp=/** @type {string[]} */([]),trs=/** @type {Array<{li:number,label:string,tag:string}>} */([]); + const B=(/** @type {string} */s)=>'**'+s+'**'; + /** @param {string} raw */ const ref=raw=>{ raw=raw.trim().replace(/:::[\w-]+$/,''); if(raw==='[*]')return null; return K.node(raw,raw); }; - const ends=new Map(); + const ends=/** @type {Map} */(new Map()); + /** @param {string} kind @returns {FxNode} */ const special=(kind)=>{ const g=K.stack.length?K.stack[K.stack.length-1]:'root',key=kind+'_'+g; if(!ends.has(key)){const inner=g!=='root';const n=K.node('__'+key,kind==='start'?(inner?'Start ('+K.groups[g].title+')':'Start'):(inner?'Done ('+K.groups[g].title+')':'End'),'circle');n.special=kind;n.icon=kind==='start'?'🟢':'🏁';ends.set(key,n)} - return ends.get(key); + return /** @type {FxNode} */(ends.get(key)); }; for(let i=0;iFlow
Explainer const N=[...K.nodes.values()];if(!N.length)throw new Error('No states found in the state diagram.'); N.forEach(n=>{if(!n.special&&n.label===n.id)n.label=ucWords(n.label)}); for(const {li,label,tag} of trs){ - const l=K.links[li],a=K.nodes.get(l.from),b=K.nodes.get(l.to);let auto; - if(a.special==='start')auto=tag?'Inside '+B(tag)+', it starts in '+B(b.label)+'.':'It all starts in '+B(b.label)+'.'; + const l=K.links[li],a=/** @type {FxNode} */(K.nodes.get(l.from)),b=/** @type {FxNode} */(K.nodes.get(l.to));let auto; + if(a.special==='start') +auto=tag?'Inside '+B(tag)+', it starts in '+B(b.label)+'.':'It all starts in '+B(b.label)+'.'; else if(b.special==='end')auto=B(a.label)+' is where it finishes'+(label?' — when '+label:'')+'.'; else if(a.shape==='hex')auto=label?'If '+label+', it goes to '+B(b.label)+'.':'The check sends it to '+B(b.label)+'.'; else auto=label?'When '+B(label)+' happens, '+B(a.label)+' changes to '+B(b.label)+'.':B(a.label)+' moves on to '+B(b.label)+'.'; @@ -1156,15 +1196,18 @@

Flow
Explainer

} /* ---------- mermaid: class ---------- */ +/** @type {Array<[string,string,number,number,string?]>} */ const CLASS_REL=[ ['<|--','is a kind of',1,0],['--|>','is a kind of',0,0],['<|..','is a way of doing',1,1],['..|>','is a way of doing',0,1], ['*--','is made up of',0,0,'contains'],['--*','is part of',0,0],['o--','has',0,0],['--o','belongs to',0,0], ['<-->','works with',0,0],['-->','uses',0,0],['<--','uses',1,0],['..>','depends on',0,1],['<..','depends on',1,1],['--','is linked to',0,0],['..','is loosely linked to',0,1] ]; +/** @param {string[]} ls @returns {Graph} */ function parseClass(ls){ - const K=graphKit(),steps=[],rels=[]; + const K=graphKit(),steps=/** @type {Step[]} */([]),rels=/** @type {RegExpMatchArray[]} */([]); + /** @param {string} raw */ const cls=raw=>{ - let id=raw.trim().replace(/:::[\w-]+$/,''),label=null;let m; + let id=raw.trim().replace(/:::[\w-]+$/,''),label=/** @type {string|null} */(null);/** @type {RegExpMatchArray|null} */let m; if(m=id.match(/^([\w.-]+)\s*\["?([^"\]]*)"?\]$/)){id=m[1];label=cleanText(m[2])} if(m=id.match(/^`(.+)`$/))id=m[1]; const base=id.replace(/~[^~]*~/g,''),n=K.node(base,base); @@ -1173,7 +1216,8 @@

Flow
Explainer

n.iconFallback='🧩'; return n; }; - const member=(n,t)=>{t=t.trim();if(!t)return;let m; + /** @param {FxNode} n @param {string} t */ + const member=(n,t)=>{t=t.trim();if(!t)return;/** @type {RegExpMatchArray|null} */let m; if(m=t.match(/^<<(.+)>>$/)){n.kind=cleanText(m[1]);return} t=t.replace(/[$*]$/,'').replace(/^[+\-#~]/,'').trim(); (n.members=n.members||{f:[],a:[]})[/\(/.test(t)?'a':'f'].push(t.replace(/\s+/g,' ')); @@ -1192,12 +1236,14 @@

Flow
Explainer

if(m=line.match(relRe)){rels.push(m);continue} if(m=line.match(/^([\w.-]+)\s*:\s*(.+)$/)){member(cls(m[1]),m[2]);continue} } - const card=s=>{s=(s||'').trim();return ({'1':'one','0..1':'zero or one','1..*':'one or more','*':'many','n':'many','0..n':'zero or more','0..*':'zero or more','1..n':'one or more','many':'many'})[s]||s}; + /** @param {string|undefined} s */ + const card=s=>{s=(s||'').trim();return /** @type {Record} */({'1':'one','0..1':'zero or one','1..*':'one or more','*':'many','n':'many','0..n':'zero or more','0..*':'zero or more','1..n':'one or more','many':'many'})[s]||s}; for(const m of rels){ - const r=CLASS_REL.find(x=>x[0]===m[3]);const a=cls(m[1]),b=cls(m[5]); + const r=/** @type {[string,string,number,number,string?]} */(CLASS_REL.find(x=>x[0]===m[3]));const a=cls(m[1]),b=cls(m[5]); + const label=cleanText(m[6]||''); const li=K.link(a,b,{label,dotted:!!r[3],arrow:/>|\|>/.test(m[3])&&!/^'**'+x.label+'**'; + const [s,o]=r[2]?[b,a]:[a,b],B=(/** @type {FxNode} */x)=>'**'+x.label+'**'; let auto=label?B(s)+' '+label+' '+B(o)+' ('+(r[4]||r[1])+').':B(s)+' '+r[1]+' '+B(o)+'.'; if(r[1]==='is a kind of')auto=B(s)+' is a kind of '+B(o)+', so it gets everything '+o.label+' has.'+(label?' ('+label+')':''); if(r[1]==='is a way of doing')auto=B(s)+' follows the rules set by '+B(o)+'.'+(label?' ('+label+')':''); @@ -1216,15 +1262,19 @@

Flow
Explainer

} /* ---------- mermaid: ER ---------- */ +/** @type {Record} */ const ER_CARD={'||':'exactly one','|o':'zero or one','o|':'zero or one','}|':'one or more','|{':'one or more','}o':'zero or more','o{':'zero or more'}; +/** @param {string[]} ls @returns {Graph} */ function parseER(ls){ - const K=graphKit(),steps=[]; + const K=graphKit(),steps=/** @type {Step[]} */([]); + /** @param {string} raw */ const ent=raw=>{ - raw=raw.trim();let m,id=raw,label=null; + raw=raw.trim();/** @type {RegExpMatchArray|null} */let m;let id=raw,label=/** @type {string|null} */(null); if(m=raw.match(/^([\w-]+)\s*\[\s*"?([^"\]]*)"?\s*\]$/)){id=m[1];label=m[2]} else if(m=raw.match(/^"(.+)"$/))id=m[1]; const n=K.node(id,label?cleanText(label):ucWords(id));n.iconFallback='📋';return n; }; + /** @param {FxNode} n @param {string} t */ const attr=(n,t)=>{const m=t.trim().match(/^(\S+)\s+(\S+)((?:\s+(?:PK|FK|UK)\s*,?)*)\s*(?:"(.*)")?$/);if(!m)return; const keys=m[3]||'',extra=/PK/.test(keys)?' (ID)':/FK/.test(keys)?' (link)':'';(n.attrs=n.attrs||[]).push(m[2].replace(/_/g,' ')+extra+(m[4]?' — '+m[4]:''))}; for(let i=0;iFlow
Explainer if(m=line.match(/^(.+?)\s*(\|o|\|\||\}o|\}\|)(--|\.\.)(o\||\|\||o\{|\|\{)\s*(.+?)\s*:\s*(.+)$/)){ const a=ent(m[1]),b=ent(m[5]),label=cleanText(m[6]),cl=ER_CARD[m[2]],cr=ER_CARD[m[4]]; const li=K.link(a,b,{label,dotted:m[3]==='..'}); - const one=x=>x.label.toLowerCase(); + const one=(/** @type {FxNode} */x)=>x.label.toLowerCase(); + steps.push(K.edgeStep(li,{chip:label,auto:'Each **'+a.label+'** '+label+' **'+cr+'** '+one(b)+'. Each '+one(b)+' is linked to **'+cl+'** '+one(a)+'.'})); continue; } @@ -1247,15 +1298,19 @@

Flow
Explainer

} /* ---------- mermaid: gantt ---------- */ +/** @typedef {{label:string,id:string,start:string|null,end:string|null,tags:string[],section:number|null,deps:GanttTask[],s:number|null,e:number|null,d:number|null,soft?:boolean,n:FxNode}} GanttTask */ +/** @param {string[]} ls @returns {Graph} */ function parseGantt(ls){ - const K=graphKit(),tasks=[];let title='',fmt='YYYY-MM-DD',section=null; - const DAY=864e5,UNIT={ms:1,s:1e3,m:6e4,h:36e5,d:DAY,w:7*DAY,M:30*DAY,y:365*DAY}; - const parseDate=s=>{s=s.trim();let m; - if(/^YYYY-MM-DD/.test(fmt)&&(m=s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})(?:[ T](\d{1,2}):(\d{2}))?$/)))return Date.UTC(+m[1],m[2]-1,+m[3],+(m[4]||0),+(m[5]||0)); - if(/^DD[-/.]MM[-/.]YYYY/.test(fmt)&&(m=s.match(/^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/)))return Date.UTC(+m[3],m[2]-1,+m[1]); - if(/^MM[-/.]DD[-/.]YYYY/.test(fmt)&&(m=s.match(/^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/)))return Date.UTC(+m[3],m[1]-1,+m[2]); + const K=graphKit(),tasks=/** @type {GanttTask[]} */([]);let title='',fmt='YYYY-MM-DD',section=/** @type {number|null} */(null); + const DAY=864e5,UNIT=/** @type {Record} */({ms:1,s:1e3,m:6e4,h:36e5,d:DAY,w:7*DAY,M:30*DAY,y:365*DAY}); + /** @param {string} s @returns {number|null} */ + const parseDate=s=>{s=s.trim();/** @type {RegExpMatchArray|null} */let m; + if(/^YYYY-MM-DD/.test(fmt)&&(m=s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})(?:[ T](\d{1,2}):(\d{2}))?$/)))return Date.UTC(+m[1],+m[2]-1,+m[3],+(m[4]||0),+(m[5]||0)); + if(/^DD[-/.]MM[-/.]YYYY/.test(fmt)&&(m=s.match(/^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/)))return Date.UTC(+m[3],+m[2]-1,+m[1]); + if(/^MM[-/.]DD[-/.]YYYY/.test(fmt)&&(m=s.match(/^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/)))return Date.UTC(+m[3],+m[1]-1,+m[2]); if(/^\d{4}-\d{2}-\d{2}/.test(s)){const t=Date.parse(s);if(!isNaN(t))return t} return null}; + /** @param {string} s */ const dur=s=>{const m=s.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w|M|y)$/);return m?+m[1]*UNIT[m[2]]:null}; for(const line of ls){ let m; @@ -1264,45 +1319,49 @@

Flow
Explainer

if(/^(axisFormat|tickInterval|excludes|includes|todayMarker|weekday|inclusiveEndDates|topAxis|displayMode|accTitle|accDescr|click)\b/.test(line))continue; if(m=line.match(/^section\s+(.+)$/)){K.groups.push({title:cleanText(m[1])});section=K.groups.length-1;continue} if(m=line.match(/^(.+?)\s*:\s*(.*)$/)){ - const parts=m[2].split(',').map(s=>s.trim()).filter(Boolean),tags=[]; - while(parts.length&&/^(done|active|crit|milestone|vert)$/.test(parts[0]))tags.push(parts.shift()); - let id=null,start=null,end=null; + const parts=m[2].split(',').map(s=>s.trim()).filter(Boolean),tags=/** @type {string[]} */([]); + while(parts.length&&/^(done|active|crit|milestone|vert)$/.test(parts[0]))tags.push(/** @type {string} */(parts.shift())); + let id=/** @type {string|null} */(null),start=/** @type {string|null} */(null),end=/** @type {string|null} */(null); if(parts.length>=3)[id,start,end]=parts; else if(parts.length===2){if(parseDate(parts[0])!=null||/^after\s/.test(parts[0]))[start,end]=parts;else[id,end]=parts} else if(parts.length===1)end=parts[0]; - tasks.push({label:cleanText(m[1]),id:id||('task'+(tasks.length+1)),start,end,tags,section}); + tasks.push(/** @type {GanttTask} */({label:cleanText(m[1]),id:id||('task'+(tasks.length+1)),start,end,tags,section})); } } if(!tasks.length)throw new Error('No tasks found in the gantt chart.'); - const byId=new Map();tasks.forEach(t=>byId.set(t.id,t)); - let prev=null; + const byId=/** @type {Map} */(new Map());tasks.forEach(t=>byId.set(t.id,t)); + let prev=/** @type {GanttTask|null} */(null); tasks.forEach(t=>{ t.deps=[]; - if(t.start&&/^after\s/.test(t.start)){t.deps=t.start.replace(/^after\s+/,'').split(/\s+/).map(x=>byId.get(x)).filter(Boolean);t.s=t.deps.length&&t.deps.every(d=>d.e!=null)?Math.max(...t.deps.map(d=>d.e)):null} + if(t.start&&/^after\s/.test(t.start)){t.deps=/** @type {GanttTask[]} */(t.start.replace(/^after\s+/,'').split(/\s+/).map(x=>byId.get(x)).filter(Boolean));t.s=t.deps.length&&t.deps.every(d=>d.e!=null)?Math.max(...t.deps.map(d=>/** @type {number} */(d.e))):null} else if(t.start){t.s=parseDate(t.start)} else{if(prev)t.deps=[prev];t.s=prev?prev.e:null} const d=t.end?dur(t.end):null,ed=t.end?parseDate(t.end):null,un=t.end&&t.end.match(/^until\s+(\S+)/); if(t.tags.includes('milestone'))t.e=t.s; else if(d!=null&&t.s!=null)t.e=t.s+d; else if(ed!=null)t.e=ed; - else if(un&&byId.get(un[1])&&byId.get(un[1]).s!=null)t.e=byId.get(un[1]).s; + else if(un&&byId.get(un[1])&&/** @type {GanttTask} */(byId.get(un[1])).s!=null)t.e=/** @type {GanttTask} */(byId.get(un[1])).s; else t.e=null; t.d=d;prev=t; }); tasks.forEach(t=>{ if(t.start&&!/^after\s/.test(t.start)&&t.s!=null&&!t.deps.length){ - let best=null;tasks.forEach(o=>{if(o!==t&&o.e!=null&&o.e<=t.s&&tasks.indexOf(o)best.e))best=o}); + let best=/** @type {GanttTask|null} */(null);tasks.forEach(o=>{if(o!==t&&o.e!=null&&o.e<=/** @type {number} */(t.s)&& +tasks.indexOf(o)/** @type {number} */(best.e)))best=o}); if(best){t.deps=[best];t.soft=true} } }); + /** @param {number} ms */ const fd=ms=>{const d=new Date(ms);return d.getUTCDate()+' '+['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getUTCMonth()]+' '+d.getUTCFullYear()}; + /** @param {number} ms */ const fdur=ms=>{const dd=ms/DAY;if(dd>=1){const w=dd/7;return Number.isInteger(w)&&w>1?w+' weeks':(Math.round(dd*10)/10)+(dd===1?' day':' days')}const h=ms/36e5;return h>=1?Math.round(h*10)/10+' hours':Math.round(ms/6e4)+' minutes'}; tasks.forEach(t=>{const n=K.node(t.id,t.label,t.tags.includes('milestone')?'circle':'box');n.group=t.section; if(t.tags.includes('milestone'))n.icon='🚩';else if(t.tags.includes('done'))n.icon='✅';else if(t.tags.includes('active'))n.icon='⏳';else if(t.tags.includes('crit'))n.icon='❗'; t.n=n}); const order=tasks.slice().sort((a,b)=>(a.s??Infinity)-(b.s??Infinity)||tasks.indexOf(a)-tasks.indexOf(b)); - const steps=[],B=s=>'**'+s+'**'; + const steps=/** @type {Step[]} */([]),B=(/** @type {string} */s)=>'**'+s+'**'; order.forEach(t=>{ + const lis=t.deps.map(d=>K.link(d.n,t.n,{arrow:true,dotted:!!t.soft})); const ms=t.tags.includes('milestone'),when=t.s!=null?(ms?'is reached on '+B(fd(t.s)):'starts on '+B(fd(t.s))):''; let auto; @@ -1321,16 +1380,17 @@

Flow
Explainer

} /* ---------- mermaid: pie ---------- */ +/** @param {string} first @param {string[]} ls @returns {Graph} */ function parsePie(first,ls){ - let title=(first.match(/^pie\b(?:\s+showData)?(?:\s+title\s+(.+))?$/i)||[])[1]||'';const slices=[]; + let title=(first.match(/^pie\b(?:\s+showData)?(?:\s+title\s+(.+))?$/i)||[])[1]||'';const slices=/** @type {Array<{label:string,v:number}>} */([]); for(const line of ls){let m; if(m=line.match(/^title\s+(.+)$/i)){title=m[1];continue} if(m=line.match(/^"([^"]+)"\s*:\s*(-?\d+(?:\.\d+)?)$/))slices.push({label:cleanText(m[1]),v:+m[2]}); } if(!slices.length)throw new Error('No slices found in the pie chart. Write them like "Dogs" : 42'); const tot=slices.reduce((s,x)=>s+Math.max(0,x.v),0)||1,max=Math.max(...slices.map(x=>x.v),1e-9); - const pct=v=>{const p=v/tot*100;return (p>=10||Number.isInteger(p)?Math.round(p):Math.round(p*10)/10)+'%'}; - const fmt=v=>Number.isInteger(v)?v.toLocaleString('en-US'):String(v); + const pct=(/** @type {number} */v)=>{const p=v/tot*100;return (p>=10||Number.isInteger(p)?Math.round(p):Math.round(p*10)/10)+'%'}; + const fmt=(/** @type {number} */v)=>Number.isInteger(v)?v.toLocaleString('en-US'):String(v); const nodes=slices.map((s,i)=>({id:'slice'+(i+1),label:s.label+' · '+pct(s.v),shape:'box',group:null,ci:i,hk:.35+2.3*Math.max(0,s.v)/max,gx:i*2.7,gy:0,note:fmt(s.v)+' of '+fmt(tot)+' in total ('+pct(s.v)+').'})); const rank=slices.map((s,i)=>i).sort((a,b)=>slices[b].v-slices[a].v); const steps=rank.map((i,k)=>{const s=slices[i]; @@ -1340,18 +1400,20 @@

Flow
Explainer

} /* ---------- mermaid: mindmap ---------- */ +/** @param {string} code @returns {Graph} */ function parseMindmap(code){ let raw=code.replace(/\r/g,'').split('\n'); if(raw.find(l=>l.trim())?.trim()==='---'){const a=raw.findIndex(l=>l.trim()==='---'),b=raw.findIndex((l,i)=>i>a&&l.trim()==='---');if(b>a)raw=raw.slice(b+1)} raw=raw.map(l=>l.replace(/%%.*$/,'').replace(/\t/g,' ')).filter(l=>l.trim()); const hi=raw.findIndex(l=>/^\s*mindmap\b/.test(l));raw=raw.slice(hi+1); - const K=graphKit(),steps=[],stack=[];let count=0; + const K=graphKit(),steps=/** @type {Step[]} */([]),stack=/** @type {Array<{ind:number,n:FxNode}>} */([]);let count=0; /** @type {Array<[RegExp,string]>} */ const FORMS=[[/^\(\((.*)\)\)$/s,'circle'],[/^\)\)(.*)\(\($/s,'pill'],[/^\)(.*)\($/s,'pill'],[/^\{\{(.*)\}\}$/s,'box'],[/^\((.*)\)$/s,'pill'],[/^\[(.*)\]$/s,'box']]; for(const l of raw){ const t=l.trim();if(/^::icon\(/.test(t)||/^:::/.test(t))continue; - const ind=l.match(/^ */)[0].length; + const ind=/** @type {RegExpMatchArray} */(l.match(/^ */))[0].length; const body=t.replace(/:::[\w\s-]+$/,'').trim();let label=body,shape='box'; + const idm=body.match(/^([\w-]+)(?=[[({)])/);const rest=idm?body.slice(idm[0].length):body; for(const [re,sh] of FORMS){const m=rest.match(re);if(m){label=m[1];shape=sh;break}} if(label===body&&idm)label=body; @@ -1371,8 +1433,9 @@

Flow
Explainer

} /* ---------- mermaid: fixed-position helpers ---------- */ +/** Straight / elbow arrow points for parsers that place their own nodes (every node has gx/gy). @param {FxNode[]} nodes @param {FxLink[]} links */ function routeFixed(nodes,links){ - const by=new Map(nodes.map(n=>[n.id,n])); + const by=/** @type {Map} */(new Map(nodes.map(n=>[n.id,n]))); links.forEach(l=>{ const a=by.get(l.from),b=by.get(l.to);if(!a||!b||a===b){l.pts=null;return} if(Math.abs(a.gx-b.gx)<.02){const s=Math.sign(b.gy-a.gy)||1;l.pts=[[a.gx,a.gy+s*T0],[b.gx,b.gy-s*T1]];return} @@ -1382,12 +1445,15 @@

Flow
Explainer

l.pts=[[a.gx+s*T0,a.gy],[xm,a.gy],[xm,b.gy],[b.gx-s*T1,b.gy]]; }); } +/** @param {string} s @param {string} k */ const kv=(s,k)=>{const m=s.match(new RegExp('\\b'+k+'\\s*:\\s*(?:"([^"]*)"|([^\\s,]+))'));return m?(m[1]??m[2]):null}; /* ---------- mermaid: journey ---------- */ +/** @param {string[]} ls @returns {Graph} */ function parseJourney(ls){ - const K=graphKit(),tasks=[];let title='',section=null; - const MOOD=[null,['very unhappy','😫'],['frustrating','😟'],['okay','😐'],['good','🙂'],['great','😀']]; + const K=graphKit(),tasks=/** @type {Array<{n:FxNode,sc:number,raw:string,who:string[],section:number|null}>} */([]);let title='',section=/** @type {number|null} */(null); + // index 0 is never used: scores are clamped to 1..5 + const MOOD=/** @type {Array<[string,string]>} */([null,['very unhappy','😫'],['frustrating','😟'],['okay','😐'],['good','🙂'],['great','😀']]); for(const line of ls){let m; if(m=line.match(/^title\s+(.+)$/)){title=cleanText(m[1]);continue} if(/^(accTitle|accDescr)\b/.test(line))continue; @@ -1400,9 +1466,10 @@

Flow
Explainer

} } if(!tasks.length)throw new Error('No steps found in the journey. Write them like Pay for ticket: 3: Customer'); - const B=s=>'**'+s+'**',steps=[]; + const B=(/** @type {string} */s)=>'**'+s+'**',steps=/** @type {Step[]} */([]); tasks.forEach((t,i)=>{ - const feel=MOOD[t.sc][0],whoTxt=t.who.length?' for '+t.who.map(B).join(t.who.length>2?', ':' and ').replace(/, ([^,]*)$/,' and $1'):''; + const feel=MOOD[t.sc][0] +,whoTxt=t.who.length?' for '+t.who.map(B).join(t.who.length>2?', ':' and ').replace(/, ([^,]*)$/,' and $1'):''; const auto=(i===0?'It starts with '+B(t.n.label)+'. ':'Next: '+B(t.n.label)+'. ')+'This feels '+B(feel)+whoTxt+' ('+t.raw+' out of 5).'+(t.sc<=2?' A pain point worth fixing.':''); const tag=t.section!=null?K.groups[t.section].title:'',chip=MOOD[t.sc][1]+' '+t.raw+'/5'; if(i===0){const s=K.nodeStep(t.n,{auto,tag});s.chip=chip;steps.push(s)} @@ -1412,8 +1479,9 @@

Flow
Explainer

} /* ---------- mermaid: timeline ---------- */ +/** @param {string[]} ls @returns {Graph} */ function parseTimeline(ls){ - const K=graphKit(),periods=[];let title='',section=null; + const K=graphKit(),periods=/** @type {Array<{label:string,ev:string[],section:number|null}>} */([]);let title='',section=/** @type {number|null} */(null); for(const line of ls){let m; if(m=line.match(/^title\s+(.+)$/)){title=cleanText(m[1]);continue} if(/^(accTitle|accDescr|direction)\b/.test(line))continue; @@ -1423,7 +1491,7 @@

Flow
Explainer

periods.push({label:cleanText(parts[0]),ev:parts.slice(1).map(cleanText).filter(Boolean),section}); } if(!periods.length)throw new Error('No periods found in the timeline. Write them like 2024 : Shop opens'); - const steps=[],B=s=>'**'+s+'**';let prev=null; + const steps=/** @type {Step[]} */([]),B=(/** @type {string} */s)=>'**'+s+'**';let prev=/** @type {FxNode|null} */(null); periods.forEach((p,i)=>{ const n=K.node('p'+(i+1),p.label,'box');n.group=p.section;n.gx=i*DX;n.gy=0;n.icon='📅'; const evs=p.ev.map((e,k)=>{const en=K.node('p'+(i+1)+'e'+(k+1),e,'pill');en.group=p.section;en.gx=i*DX;en.gy=(k+1)*2.9;K.link(n,en,{dotted:true});return en}); @@ -1440,17 +1508,18 @@

Flow
Explainer

} /* ---------- mermaid: quadrant ---------- */ +/** @param {string[]} ls @returns {Graph} */ function parseQuadrant(ls){ - let title='',xa=['',''],ya=['',''];const q=['','','',''],pts=[]; + let title='',xa=['',''],ya=['',''];const q=['','','',''],pts=/** @type {Array<{label:string,x:number,y:number}>} */([]); for(const line of ls){let m; if(m=line.match(/^title\s+(.+)$/)){title=cleanText(m[1]);continue} if(m=line.match(/^([xy])-axis\s+(.+?)(?:\s*-->\s*(.+))?$/)){const v=[cleanText(m[2]),cleanText(m[3]||'')];if(m[1]==='x')xa=v;else ya=v;continue} - if(m=line.match(/^quadrant-([1-4])\s+(.+)$/)){q[m[1]-1]=cleanText(m[2]);continue} + if(m=line.match(/^quadrant-([1-4])\s+(.+)$/)){q[+m[1]-1]=cleanText(m[2]);continue} if(/^(classDef|accTitle|accDescr)\b/.test(line))continue; if(m=line.match(/^(.+?)(?::::[\w-]+)?\s*:\s*\[\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*\]/))pts.push({label:cleanText(m[1]),x:Math.max(0,Math.min(1,+m[2])),y:Math.max(0,Math.min(1,+m[3]))}); } if(!pts.length)throw new Error('No points found in the quadrant chart. Write them like Gift cards: [0.3, 0.8]'); - const qn=p=>p.y>=.5?(p.x>=.5?0:1):(p.x<.5?2:3); + const qn=(/** @type {{x:number,y:number}} */p)=>p.y>=.5?(p.x>=.5?0:1):(p.x<.5?2:3); const groups=q.map((t,i)=>({title:t||['Top right','Top left','Bottom left','Bottom right'][i]})); const S=Math.max(12,Math.sqrt(pts.length)*4.4); const nodes=pts.map((p,i)=>({id:'pt'+(i+1),label:p.label,shape:'box',group:qn(p),gx:p.x*S,gy:(1-p.y)*S,note:''})); @@ -1458,8 +1527,10 @@

Flow
Explainer

const a=nodes[i],b=nodes[j],dx=b.gx-a.gx,dy=b.gy-a.gy,d=Math.hypot(dx,dy),min=3; if(d(v>=.5?ax[1]:ax[0])||((v>=.5?'high':'low')+' '+dir+' ('+Math.round(v*100)+'%)'); - const B=s=>'**'+s+'**'; + /** @param {number} v @param {string[]} ax @param {string} dir */ + const lvl=(v,ax,dir)=> +(v>=.5?ax[1]:ax[0])||((v>=.5?'high':'low')+' '+dir+' ('+Math.round(v*100)+'%)'); + const B=(/** @type {string} */s)=>'**'+s+'**'; const steps=pts.map((p,i)=>{const n=nodes[i],g=groups[n.group].title; n.note='Across: '+Math.round(p.x*100)+'%'+(xa[0]?' ('+xa[0]+' → '+(xa[1]||'')+')':'')+'. Up: '+Math.round(p.y*100)+'%'+(ya[0]?' ('+ya[0]+' → '+(ya[1]||'')+')':'')+'.'; const auto=B(p.label)+' is '+B(lvl(p.x,xa,'across').toLowerCase())+' and '+B(lvl(p.y,ya,'up').toLowerCase())+', so it lands in '+B(g)+'.'; @@ -1469,12 +1540,19 @@

Flow
Explainer

} /* ---------- mermaid: git graph ---------- */ +/** @typedef {{name:string,lane:number,g:number,head:GitCommit|null,count:number}} GitBranch */ +/** @typedef {{id?:string|null,tag?:string|null,type?:string,kind:string,from?:string}} GitOpts */ +/** @typedef {{n:FxNode,b:GitBranch,parent:GitCommit|null,o:GitOpts}} GitCommit */ +/** @param {string[]} ls @returns {Graph} */ function parseGit(ls){ - const K=graphKit(),branches=new Map(),commits=[],steps=[],byId=new Map(),B=s=>'**'+s+'**'; + const K=graphKit(),branches=/** @type {Map} */(new Map()),commits=/** @type {GitCommit[]} */([]),steps=/** @type {Step[]} */([]),byId=/** @type {Map} */(new Map()),B=(/** @type {string} */s)=>'**'+s+'**'; let cur='main'; - const br=name=>{name=name.replace(/^"|"$/g,'');if(!branches.has(name)){K.groups.push({title:name});branches.set(name,{name,lane:branches.size,g:K.groups.length-1,head:null,count:0})}return branches.get(name)}; + /** @param {string} name @returns {GitBranch} */ + const br=name=>{name=name.replace(/^"|"$/g,'');if(!branches.has(name)){K.groups.push({title:name});branches.set(name,{name,lane:branches.size,g:K.groups.length-1,head:null,count:0})}return /** @type {GitBranch} */(branches.get(name))}; br('main'); + /** @param {GitOpts} o @returns {GitCommit} */ const add=(o)=>{ + const b=br(cur),i=commits.length;b.count++; const id=o.id||(o.kind==='merge'?'Merge '+o.from:b.name+' #'+b.count); const n=K.node('c'+(i+1),cleanText(id),o.kind==='merge'?'hex':'circle');n.group=b.g;n.gx=i*DX;n.gy=b.lane*DY; @@ -1523,16 +1601,29 @@

Flow
Explainer

} /* ---------- mermaid: helpers for the chart-like types ---------- */ +/** @param {unknown} v @returns {v is number} */ +const isNum=v=>typeof v==='number'; +/** @param {number} v */ const fmtNum=v=>Number.isInteger(v)?v.toLocaleString('en-US'):v.toLocaleString('en-US',{maximumFractionDigits:2}); +/** @param {string} s */ const humanId=s=>{s=cleanText(s);return /\s/.test(s)||!/[_-]/.test(s)?s:s.replace(/[_-]+/g,' ').replace(/^./,c=>c.toUpperCase())}; +/** @param {string[]} a @param {(s:string)=>string} B */ const andList=(a,B)=>{a=a.map(B);return a.length<2?a.join(''):a.slice(0,-1).join(', ')+' and '+a[a.length-1]}; +/** @param {string} s */ const lcFirst=s=>/^[A-Z][a-z]/.test(s)?s[0].toLowerCase()+s.slice(1):s; +/** @param {string} s @returns {string[]} */ function splitArgs(s){const out=[];let cur='',q=false;for(const ch of s){if(ch==='"'){q=!q;continue}if(ch===','&&!q){out.push(cur.trim());cur='';continue}cur+=ch}if(cur.trim()||out.length)out.push(cur.trim());return out} +/** @param {string} l @returns {string[]} */ function splitCsv(l){const out=[];let cur='',q=false;for(let i=0;is.trim())} /* ---------- mermaid: xy chart ---------- */ +/** @param {string[]} ls @returns {Graph} */ function parseXY(ls){ - let title='',cats=null,range=null,yTitle='',xTitle='',ymin=null,ymax=null;const series=[]; + /** @type {string[]|null} */ let cats=null;/** @type {number[]|null} */ let range=null;/** @type {number|null} */ let ymin=null;/** @type {number|null} */ let ymax=null; + let title='',yTitle='',xTitle=''; + /** @type {{kind:string,name:string,v:number[]}[]} */ + const series=[]; + /** @param {string} s */ const list=s=>splitArgs(s).map(cleanText).filter(x=>x!==''); for(const line of ls){let m; if(m=line.match(/^title\s+(.+)$/)){title=cleanText(m[1]);continue} @@ -1544,25 +1635,25 @@

Flow
Explainer

const n=Math.max(...series.map(s=>s.v.length)); if(!cats||cats.lengthc[i]??(range?fmtNum(Math.round((range[0]+(range[1]-range[0])*(n>1?i/(n-1):0))*100)/100):String(i+1)))} const all=series.flatMap(s=>s.v),lo=ymin!=null?ymin:Math.min(0,...all),hi=Math.max(ymax!=null?ymax:-Infinity,...all),span=hi-lo||1; - const counts={bar:0,line:0}; + /** @type {Record} */ const counts={bar:0,line:0}; series.forEach(s=>{counts[s.kind]++;s.name=s.name||(series.length===1?(yTitle||'Value'):(s.kind==='bar'?'Bars':'Line')+(series.filter(x=>x.kind===s.kind).length>1?' '+counts[s.kind]:''))}); - const multi=series.length>1,groups=multi?series.map(s=>({title:s.name})):[],nodes=[],links=[]; + const multi=series.length>1,groups=multi?series.map(s=>({title:s.name})):[],nodes=/** @type {FxNode[]} */([]),links=/** @type {FxLink[]} */([]); series.forEach((s,si)=>s.v.forEach((v,i)=>{ - const nd={id:'s'+si+'p'+i,label:cats[i]+' · '+fmtNum(v),shape:s.kind==='line'?'circle':'box',group:multi?si:null,ci:si,gx:i*2.7,gy:si*2.9,hk:.3+2.3*Math.max(0,v-lo)/span, + /** @type {FxNode} */ const nd={id:'s'+si+'p'+i,label:cats[i]+' · '+fmtNum(v),shape:s.kind==='line'?'circle':'box',group:multi?si:null,ci:si,gx:i*2.7,gy:si*2.9,hk:.3+2.3*Math.max(0,v-lo)/span, note:(multi?s.name+': ':'')+fmtNum(v)+(yTitle&&!multi?' ('+yTitle+')':'')+'.'}; if(s.kind==='line')nd.icon='📈';nodes.push(nd); if(s.kind==='line'&&i>0)links.push({from:'s'+si+'p'+(i-1),to:nd.id,label:'',dotted:false,arrow:true}); })); routeFixed(nodes,links); - const B=s=>'**'+s+'**',main=series[0]; + const B=(/** @type {string} */s)=>'**'+s+'**',main=series[0]; const steps=cats.slice(0,n).map((c,i)=>{ const ids=series.filter(s=>i's'+series.indexOf(s)+'p'+i); let auto; if(!multi){const v=main.v[i],p=i?main.v[i-1]:null,mx=Math.max(...main.v),mn=Math.min(...main.v); auto=(i===0?'It starts at '+B(fmtNum(v))+' in '+B(c):'In '+B(c)+': '+B(fmtNum(v)))+(p!=null&&p?(v===p?', the same as '+cats[i-1]:(v>p?', up ':', down ')+Math.abs(Math.round((v-p)/Math.abs(p)*100))+'% from '+cats[i-1]):'')+'.'+(v===mx&&main.v.length>2?' This is the highest point.':v===mn&&main.v.length>2?' This is the lowest point.':'');} else auto=B(c)+': '+series.filter(s=>is.name+' '+B(fmtNum(s.v[i]))).join(', ')+'.'; - const li=links.findIndex(l=>l.to===ids.find(id=>nodes.find(x=>x.id===id).shape==='circle')); - const s=li>=0?{kind:'edge',link:li,reverse:false,from:links[li].from,to:links[li].to,nodes:ids,title:c,chip:multi?'':fmtNum(main.v[i]),auto}:{kind:'node',nodes:ids,title:c,chip:multi?'':fmtNum(main.v[i]),auto}; + const li=links.findIndex(l=>l.to===ids.find(id=>nodes.find(x=>x.id===id)?.shape==='circle')); + /** @type {Step} */ const s=li>=0?{kind:'edge',link:li,reverse:false,from:links[li].from,to:links[li].to,nodes:ids,title:c,chip:multi?'':fmtNum(main.v[i]),auto}:{kind:'node',nodes:ids,title:c,chip:multi?'':fmtNum(main.v[i]),auto}; if(li>=0&&!ids.includes(links[li].from))s.nodes=[links[li].from,...ids]; return s; }); @@ -1570,26 +1661,43 @@

Flow
Explainer

} /* ---------- mermaid: sankey ---------- */ +/** @param {string[]} ls @returns {Graph} */ function parseSankey(ls){ - const K=graphKit(),flows=[]; - for(const line of ls){const f=splitCsv(line);if(f.length<3)continue;const v=+f[2];if(!f[0]||!f[1]||isNaN(v))continue;flows.push({a:cleanText(f[0]),b:cleanText(f[1]),v})} + const K=graphKit(); + /** @type {{a:string,b:string,v:number,li:number}[]} */ + const flows=[]; + for(const line of ls){const f=splitCsv(line);if(f.length<3)continue;const v=+f[2];if(!f[0]||!f[1]||isNaN(v))continue;flows.push({a:cleanText(f[0]),b:cleanText(f[1]),v,li:-1})} if(!flows.length)throw new Error('No flows found in the sankey diagram. Write each line as From,To,Amount'); - const id=s=>'k_'+s,inn=new Map(),out=new Map(),add=(m,k,v)=>m.set(k,(m.get(k)||0)+v); + /** @param {string} s */ + const id=s=>'k_'+s; + /** @type {Map} */ const inn=new Map(); + /** @type {Map} */ const out=new Map(); + /** @param {Map} m @param {string} k @param {number} v */ + const add=(m,k,v)=>m.set(k,(m.get(k)||0)+v); flows.forEach(f=>{f.li=K.link(K.node(id(f.a),f.a),K.node(id(f.b),f.b),{label:fmtNum(f.v),arrow:true});add(out,f.a,f.v);add(inn,f.b,f.v)}); - const N=[...K.nodes.values()],thr=s=>Math.max(inn.get(s)||0,out.get(s)||0),mx=Math.max(...N.map(n=>thr(n.label)))||1; + const N=[...K.nodes.values()],thr=(/** @type {string} */s)=>Math.max(inn.get(s)||0,out.get(s)||0),mx=Math.max(...N.map(n=>thr(n.label)))||1; N.forEach(n=>{const i=inn.get(n.label)||0,o=out.get(n.label)||0;n.hk=.45+1.6*thr(n.label)/mx; n.note=[i?'Comes in: '+fmtNum(i)+'.':'',o?'Goes out: '+fmtNum(o)+'.':'',i&&o&&Math.abs(i-o)>1e-9?(i>o?'Keeps ':'Adds ')+fmtNum(Math.abs(i-o))+'.':''].filter(Boolean).join(' '); if(!i)n.icon='🚰';else if(!o)n.icon='🎯'}); - const B=s=>'**'+s+'**'; + const B=(/** @type {string} */s)=>'**'+s+'**'; const steps=flows.map(f=>{const share=Math.round(f.v/(out.get(f.a)||1)*100); return K.edgeStep(f.li,{chip:fmtNum(f.v),auto:B(f.a)+' sends '+B(fmtNum(f.v))+' to '+B(f.b)+(share<100?' — '+share+'% of everything leaving '+f.a+'.':' — all of it.')})}); return {type:'sankey',nodes:N,links:K.links,steps,groups:[]}; } /* ---------- mermaid: block ---------- */ +/** @typedef {{span:number,cols?:number,items?:BlockItem[],g?:number|null,space?:boolean,n?:FxNode,w?:number,h?:number,x?:number,y?:number,ww?:number,ncol?:number,cw?:number,rows?:BlockItem[][]}} BlockItem */ +/** @typedef {{a:string,b:string,label:string,arrow:boolean,dotted:boolean,aName?:string,bName?:string}} BlockLink */ +/** @param {string[]} ls @returns {Graph} */ function parseBlock(ls){ - const nodes=new Map(),links=[],groups=[],root={cols:0,items:[],g:null},stack=[root],byBlock=new Map(); + /** @type {Map} */ const nodes=new Map(); + /** @type {BlockLink[]} */ const links=[]; + /** @type {Group[]} */ const groups=[]; + /** @type {BlockItem} */ const root={cols:0,items:[],g:null,span:1}; + const stack=[root]; + /** @type {Map} */ const byBlock=new Map(); const OPEN=[['(((',')))','circle'],['((','))','circle'],['([','])','pill'],['[(',')]','cyl'],['[[',']]','box'],['{{','}}','hex'],['<[',']>','pill'],['[/','/]','box'],['[\\','\\]','box'],['[/','\\]','box'],['[\\','/]','box'],['[',']','box'],['(',')','pill'],['{','}','hex'],['>',']','box']]; + /** @param {string} line */ const tokens=line=>{const out=[];let i=0; while(i=line.length)break; @@ -1598,7 +1706,7 @@

Flow
Explainer

for(const [o,c,sh] of OPEN){if(!line.startsWith(o,i))continue;let j=i+o.length,q=false; for(;j} */({right:'→',left:'←',up:'↑',down:'↓'})[(dm?dm[1]:'').split(',')[0].trim()]||'→')} let span=1;const sm=line.slice(i).match(/^:(\d+)/);if(sm){span=+sm[1];i+=sm[0].length} out.push({id,label,shape,span,arrow}); }return out}; @@ -1608,45 +1716,52 @@

Flow
Explainer

if(m=line.match(/^columns\s+(\d+|auto)$/)){top.cols=m[1]==='auto'?0:+m[1];continue} if(m=line.match(/^block(?::([^\s:[]+))?(?:\["?([^"\]]*)"?\])?(?::(\d+))?$/)){ groups.push({title:cleanText(m[2]||'')||humanId(m[1]||'Group '+(groups.length+1))}); - const c={cols:0,items:[],g:groups.length-1,span:+(m[3]||1)};if(m[1])byBlock.set(m[1],c);top.items.push(c);stack.push(c);continue} + /** @type {BlockItem} */ const c={cols:0,items:[],g:groups.length-1,span:+(m[3]||1)};if(m[1])byBlock.set(m[1],c);(top.items||[]).push(c);stack.push(c);continue} if(line==='end'){if(stack.length>1)stack.pop();continue} if(m=line.match(/^([^\s"]+)\s*(?:--\s*"([^"]*)"\s*(-->|---)|(-->|---|==>|-\.->|-\.-))\s*([^\s"]+)$/)){links.push({a:m[1],b:m[5],label:cleanText(m[2]||''),arrow:/>$/.test(m[3]||m[4]),dotted:/\./.test(m[4]||'')});continue} for(const t of tokens(line)){ - if(t.id==='space'){top.items.push({space:true,span:t.span});continue} - if(!nodes.has(t.id))nodes.set(t.id,{id:t.id,label:t.label||t.id,shape:t.shape,group:top.g}); - const n=nodes.get(t.id);if(t.label){n.label=t.label;n.shape=t.shape}if(t.arrow)n.icon={'↓':'⬇️','↑':'⬆️','←':'⬅️'}[n.label]||'➡️'; - top.items.push({n,span:t.span}); + const items=top.items||[]; + if(t.id==='space'){items.push({space:true,span:t.span});continue} + if(!nodes.has(t.id))nodes.set(t.id,{id:t.id,label:t.label||t.id,shape:t.shape,group:top.g??null}); + const n=/** @type {FxNode} */(nodes.get(t.id));if(t.label){n.label=t.label;n.shape=t.shape}if(t.arrow)n.icon=/** @type {Record} */({'↓':'⬇️','↑':'⬆️','←':'⬅️'})[n.label]||'➡️'; + items.push({n,span:t.span}); } } + /** @param {BlockItem} it @returns {FxNode[]} */ const leaves0=it=>it.items?it.items.flatMap(leaves0):it.n?[it.n]:[]; - links.forEach(l=>{for(const e of ['a','b'])if(!nodes.has(l[e])&&byBlock.has(l[e])){const ls=leaves0(byBlock.get(l[e]));if(ls.length){l[e+'Name']=groups[byBlock.get(l[e]).g].title;l[e]=ls[Math.floor((ls.length-1)/2)].id}}}); - links.forEach(l=>{for(const k of [l.a,l.b])if(!nodes.has(k)){nodes.set(k,{id:k,label:k,shape:'box',group:null});root.items.push({n:nodes.get(k),span:1})}}); + links.forEach(l=>{for(const e of /** @type {('a'|'b')[]} */(['a','b'])){const blk=byBlock.get(l[e]);if(!nodes.has(l[e])&&blk){const ls=leaves0(blk);if(ls.length){const nm=groups[/** @type {number} */(blk.g)].title;if(e==='a')l.aName=nm;else l.bName=nm;l[e]=ls[Math.floor((ls.length-1)/2)].id}}}}); + links.forEach(l=>{for(const k of [l.a,l.b])if(!nodes.has(k)){/** @type {FxNode} */ const nn={id:k,label:k,shape:'box',group:null};nodes.set(k,nn);(root.items||[]).push({n:nn,span:1})}}); if(!nodes.size)throw new Error('No blocks found in the block diagram.'); - const size=c=>{c.items.forEach(it=>{if(it.items)Object.assign(it,size(it));else{it.w=it.span;it.h=1}}); - const cols=c.cols||c.items.reduce((s,it)=>s+it.span,0)||1;c.ncol=cols; - c.cw=Math.max(1,...c.items.map(it=>it.w/Math.min(it.span,cols))); - let col=0,y=0,rh=0;c.rows=[[]]; - c.items.forEach(it=>{const sp=Math.min(it.span,cols);if(col+sp>cols){y+=rh;rh=0;col=0;c.rows.push([])}it.x=col*c.cw;it.y=y;it.ww=sp*c.cw;col+=sp;rh=Math.max(rh,it.h);c.rows[c.rows.length-1].push(it)}); - return {w:cols*c.cw,h:y+rh}}; + /** @param {BlockItem} c @returns {{w:number,h:number}} */ + const size=c=>{const items=c.items||[];items.forEach(it=>{if(it.items)Object.assign(it,size(it));else{it.w=it.span;it.h=1}}); + const cols=c.cols||items.reduce((s,it)=>s+it.span,0)||1;c.ncol=cols; + const cw=Math.max(1,...items.map(it=>(it.w||0)/Math.min(it.span,cols)));c.cw=cw; + let col=0,y=0,rh=0;const rows=/** @type {BlockItem[][]} */([[]]);c.rows=rows; + items.forEach(it=>{const sp=Math.min(it.span,cols);if(col+sp>cols){y+=rh;rh=0;col=0;rows.push([])}it.x=col*cw;it.y=y;it.ww=sp*cw;col+=sp;rh=Math.max(rh,it.h||0);rows[rows.length-1].push(it)}); + return {w:cols*cw,h:y+rh}}; size(root); - const place=(c,ox,oy)=>c.items.forEach(it=>{if(it.items)place(it,ox+it.x+(it.ww-it.w)/2,oy+it.y);else if(it.n){it.n.gx=(ox+it.x+it.ww/2)*DX;it.n.gy=(oy+it.y+.5)*DY*1.15}}); + /** @param {BlockItem} c @param {number} ox @param {number} oy @returns {void} */ + const place=(c,ox,oy)=>(c.items||[]).forEach(it=>{const x=it.x||0,y=it.y||0,ww=it.ww||0;if(it.items)place(it,ox+x+(ww-(it.w||0))/2,oy+y);else if(it.n){it.n.gx=(ox+x+ww/2)*DX;it.n.gy=(oy+y+.5)*DY*1.15}}); place(root,0,0); const N=[...nodes.values()],L=links.map(l=>({from:l.a,to:l.b,label:l.label,dotted:l.dotted,arrow:l.arrow,an:l.aName,bn:l.bName}));routeFixed(N,L); - const B=s=>'**'+s+'**',by=id=>nodes.get(id);let steps; + const B=(/** @type {string} */s)=>'**'+s+'**',by=(/** @type {string} */id)=>/** @type {FxNode} */(nodes.get(id));/** @type {Step[]} */ let steps; if(L.length)steps=L.map((l,i)=>{const a={...by(l.from)},b={...by(l.to)};if(l.an)a.label=l.an;if(l.bn)b.label=l.bn; return {kind:'edge',link:i,reverse:false,from:a.id,to:b.id,nodes:[a.id,b.id],title:a.label+' → '+b.label,chip:l.label,tag:a.group!=null?groups[a.group].title:'', auto:l.label?B(a.label)+' → '+B(b.label)+': '+l.label+'.':l.arrow?B(a.label)+' hands over to '+B(b.label)+'.':B(a.label)+' is connected to '+B(b.label)+'.'}}); - else{steps=[];const leaves=it=>it.items?it.items.flatMap(leaves):it.n?[it.n]:[]; - root.rows.forEach((row,ri)=>{const ns=row.flatMap(leaves);if(!ns.length)return; - const inner=row.filter(it=>it.items&&leaves(it).length).map(it=>B(groups[it.g].title)+' holds '+andList(leaves(it).map(n=>n.label),B)); - steps.push({kind:'node',nodes:ns.map(n=>n.id),title:root.rows.length>1?'Row '+(ri+1):'Blocks',auto:(root.rows.length>1?'Row '+(ri+1)+' has ':'This has ')+andList(row.map(it=>it.items?groups[it.g].title:it.n?it.n.label:null).filter(Boolean),B)+'.'+(inner.length?' '+inner.join('. ')+'.':'')})});} + else{const st=/** @type {Step[]} */([]);steps=st;const leaves=leaves0,rows=root.rows||[],gt=(/** @type {BlockItem} */it)=>groups[/** @type {number} */(it.g)].title; + rows.forEach((row,ri)=>{const ns=row.flatMap(leaves);if(!ns.length)return; + const inner=row.filter(it=>it.items&&leaves(it).length).map(it=>B(gt(it))+' holds '+andList(leaves(it).map(n=>n.label),B)); + st.push({kind:'node',nodes:ns.map(n=>n.id),title:rows.length>1?'Row '+(ri+1):'Blocks',auto:(rows.length>1?'Row '+(ri+1)+' has ':'This has ')+andList(/** @type {string[]} */(row.map(it=>it.items?gt(it):it.n?it.n.label:null).filter(Boolean)),B)+'.'+(inner.length?' '+inner.join('. ')+'.':'')})});} return {type:'block',nodes:N,links:L,steps,groups,fixed:true}; } /* ---------- mermaid: architecture ---------- */ +/** @type {Record} */ const ARCH_ICON={cloud:'☁️',database:'🗄️',disk:'💾',internet:'🌐',server:'🖥️'}; +/** @param {string[]} ls @returns {Graph} */ function parseArch(ls){ const K=graphKit(),gid=new Map(),edges=[]; + /** @param {FxNode} n @param {string|undefined} ic */ const icon=(n,ic)=>{if(!ic)return;if(ic==='database'||ic==='disk')n.shape='cyl';if(ic==='internet')n.shape='circle'; n.icon=ARCH_ICON[ic]||(/(db|sql|dynamo|rds|mongo|redis)/i.test(ic)?'🗄️':/(s3|storage|bucket|blob)/i.test(ic)?'💾':/(lambda|function)/i.test(ic)?'⚡':/(queue|sqs|kafka|pubsub)/i.test(ic)?'📨':'🧩')}; for(const line of ls){let m; @@ -1657,7 +1772,7 @@

Flow
Explainer

if(m=line.match(/^([\w-]+)(?:\{group\})?\s*:\s*([LRTB])\s*(<)?-(?:\[([^\]]*)\]-|-)(>)?\s*([LRTB])\s*:\s*([\w-]+)(?:\{group\})?$/))edges.push({a:m[1],b:m[7],label:cleanText(m[4]||''),back:!!m[3],fwd:!!m[5]}); } if(!K.nodes.size)throw new Error('No services found in the architecture diagram. Write them like service db(database)[Database]'); - const B=s=>'**'+s+'**',steps=[]; + const B=(/** @type {string} */s)=>'**'+s+'**',steps=[]; for(const e of edges){ let a=K.nodes.get(e.a)||K.node(e.a,humanId(e.a)),b=K.nodes.get(e.b)||K.node(e.b,humanId(e.b)); if(e.back&&!e.fwd)[a,b]=[b,a]; @@ -1672,6 +1787,7 @@

Flow
Explainer

} /* ---------- mermaid: C4 ---------- */ +/** @param {string} first @param {string[]} ls @returns {Graph} */ function parseC4(first,ls){ const K=graphKit(),rels=[];let title='',pending=null; const level=(first.match(/^C4(\w+)/)||[])[1]||'Context'; @@ -1699,7 +1815,7 @@

Flow
Explainer

} } if(!K.nodes.size)throw new Error('No people or systems found in the C4 diagram. Write them like Person(customer, "Customer")'); - const B=s=>'**'+s+'**',steps=[]; + const B=(/** @type {string} */s)=>'**'+s+'**',steps=[]; for(const r of rels){ const a=K.nodes.get(r.from)||K.node(r.from,humanId(r.from)),b=K.nodes.get(r.to)||K.node(r.to,humanId(r.to)); const li=K.link(a,b,{label:r.label,arrow:true}); @@ -1709,22 +1825,28 @@

Flow
Explainer

} const N=[...K.nodes.values()]; if(!steps.length)N.forEach(n=>steps.push(K.nodeStep(n,{auto:B(n.label)+(n.note?': '+n.note:'.')}))); - return {type:'c4',nodes:N,links:K.links,steps,groups:K.groups,diagramTitle:title||({Context:'System context',Container:'Containers',Component:'Components',Dynamic:'How the parts talk',Deployment:'Where it runs'}[level]||'')}; + return {type:'c4',nodes:N,links:K.links,steps,groups:K.groups,diagramTitle:title||(/** @type {Record} */({Context:'System context',Container:'Containers',Component:'Components',Dynamic:'How the parts talk',Deployment:'Where it runs'})[level]||'')}; } /* ---------- mermaid: kanban ---------- */ +/** @typedef {{text:string,meta:Record}} KanbanItem */ +/** @param {string} code @returns {Graph} */ function parseKanban(code){ let raw=code.replace(/\r/g,'').split('\n'); if(raw.find(l=>l.trim())?.trim()==='---'){const a=raw.findIndex(l=>l.trim()==='---'),b=raw.findIndex((l,i)=>i>a&&l.trim()==='---');if(b>a)raw=raw.slice(b+1)} raw=raw.map(l=>l.replace(/%%.*$/,'').replace(/\t/g,' ')).filter(l=>l.trim()); raw=raw.slice(raw.findIndex(l=>/^\s*kanban\b/.test(l))+1); if(!raw.length)throw new Error('The kanban board is empty.'); - const base=Math.min(...raw.map(l=>l.match(/^ */)[0].length)),cols=[]; - const item=t=>{const meta={};const mm=t.match(/@\{(.*)\}\s*$/);if(mm){t=t.slice(0,mm.index).trim();for(const x of mm[1].matchAll(/([\w-]+)\s*:\s*(?:'([^']*)'|"([^"]*)"|([^,}]+))/g))meta[x[1].toLowerCase()]=(x[2]??x[3]??x[4]).trim()} + const base=Math.min(...raw.map(l=>(l.match(/^ */)||[''])[0].length)); + /** @type {(KanbanItem & {cards:KanbanItem[]})[]} */ const cols=[]; + /** @param {string} t @returns {KanbanItem} */ + const item=t=>{const meta=/** @type {Record} */({});const mm=t.match(/@\{(.*)\}\s*$/);if(mm){t=t.slice(0,mm.index).trim();for(const x of mm[1].matchAll(/([\w-]+)\s*:\s*(?:'([^']*)'|"([^"]*)"|([^,}]+))/g))meta[x[1].toLowerCase()]=(x[2]??x[3]??x[4]).trim()} const b=t.match(/^([^[\s]*)\[(.*)\]$/);return {text:cleanText(b?b[2]:t),meta}}; - for(const l of raw){const ind=l.match(/^ */)[0].length,t=l.trim(); + for(const l of raw){const ind=(l.match(/^ */)||[''])[0].length,t=l.trim(); if(ind<=base||!cols.length)cols.push({...item(t),cards:[]});else cols[cols.length-1].cards.push(item(t));} - const K=graphKit(),steps=[],B=s=>'**'+s+'**',PRI={'very high':'🔴',high:'🟠',low:'🟢','very low':'⚪'};let prev=null; + const K=graphKit(),steps=/** @type {Step[]} */([]),B=(/** @type {string} */s)=>'**'+s+'**'; + /** @type {Record} */ const PRI={'very high':'🔴',high:'🟠',low:'🟢','very low':'⚪'}; + /** @type {FxNode|null} */ let prev=null; cols.forEach((c,i)=>{ K.groups.push({title:c.text});const g=K.groups.length-1; const h=K.node('col'+(i+1),c.text,'box');h.group=g;h.gx=i*DX;h.gy=0;h.icon='📋';h.note=c.cards.length+' card'+(c.cards.length===1?'':'s')+'.'; @@ -1743,6 +1865,7 @@

Flow
Explainer

} /* ---------- mermaid: packet ---------- */ +/** @param {string[]} ls @returns {Graph} */ function parsePacket(ls){ let title='',next=0;const f=[]; for(const line of ls){let m; @@ -1751,25 +1874,31 @@

Flow
Explainer

if(m=line.match(/^\+(\d+)\s*:\s*(.+)$/)){const a=next,b=next+Math.max(1,+m[1])-1;f.push({a,b,label:cleanText(m[2])});next=b+1} } if(!f.length)throw new Error('No fields found in the packet diagram. Write them like 0-15: "Source Port"'); - const W=32,groups=[],rowIx=new Map(),count=new Map(),mx=Math.max(...f.map(x=>x.b-x.a+1)); + const W=32,groups=/** @type {Group[]} */([]),rowIx=/** @type {Map} */(new Map()),count=/** @type {Map} */(new Map()),mx=Math.max(...f.map(x=>x.b-x.a+1)); const nodes=f.map((x,i)=>{const r=Math.floor(x.a/W);if(!rowIx.has(r)){groups.push({title:'Bits '+r*W+'–'+(r*W+W-1)});rowIx.set(r,groups.length-1)} const k=count.get(r)||0;count.set(r,k+1);const bits=x.b-x.a+1; - return {id:'f'+(i+1),label:x.label,shape:bits===1?'circle':'box',group:rowIx.get(r),gx:k*DX,gy:rowIx.get(r)*2.9,hk:bits===1?1:.5+1.5*Math.log2(bits)/Math.log2(Math.max(2,mx)), + return {id:'f'+(i+1),label:x.label,shape:bits===1?'circle':'box',group:rowIx.get(r)??null,gx:k*DX,gy:(rowIx.get(r)||0)*2.9,hk:bits===1?1:.5+1.5*Math.log2(bits)/Math.log2(Math.max(2,mx)), note:(bits===1?'Bit '+x.a:'Bits '+x.a+'–'+x.b)+' ('+bits+' bit'+(bits===1?'':'s')+(bits%8===0?', '+bits/8+' byte'+(bits===8?'':'s'):'')+').'}}); - const B=s=>'**'+s+'**'; + const B=(/** @type {string} */s)=>'**'+s+'**'; const steps=f.map((x,i)=>{const bits=x.b-x.a+1,n=nodes[i]; const auto=bits===1?'Bit '+B(String(x.a))+' is '+B(x.label)+', a single on/off flag.': (i===0?'The message starts with ':'Next, bits ')+(i===0?B(x.label)+' in bits '+B(x.a+'–'+x.b):B(x.a+'–'+x.b)+' hold '+B(x.label))+' ('+bits+' bits'+(bits%8===0?', '+bits/8+' byte'+(bits===8?'':'s'):'')+').'; - return {kind:'node',nodes:[n.id],title:x.label,chip:bits+' bit'+(bits===1?'':'s'),auto,tag:groups[n.group].title}}); + return {kind:'node',nodes:[n.id],title:x.label,chip:bits+' bit'+(bits===1?'':'s'),auto,tag:groups[/** @type {number} */(n.group)].title}}); return {type:'packet',nodes,links:[],steps,groups,fixed:true,diagramTitle:title}; } /* ---------- mermaid: requirement ---------- */ +/** @type {Record} */ const REQ_KIND={requirement:'Requirement',functionalrequirement:'Functional requirement',interfacerequirement:'Interface requirement',performancerequirement:'Performance requirement',physicalrequirement:'Physical requirement',designconstraint:'Design constraint'}; +/** @type {Recordstring>} */ const REQ_VERB={satisfies:(a,b)=>a+' meets the requirement '+b,verifies:(a,b)=>a+' checks that '+b+' is met',contains:(a,b)=>a+' includes '+b,copies:(a,b)=>a+' is a copy of '+b, derives:(a,b)=>b+' is worked out from '+a,refines:(a,b)=>a+' adds detail to '+b,traces:(a,b)=>a+' traces back to '+b}; +/** @param {string[]} ls @returns {Graph} */ function parseReq(ls){ - const K=graphKit(),rels=[],B=s=>'**'+s+'**';let cur=null; + const K=graphKit(),B=(/** @type {string} */s)=>'**'+s+'**'; + /** @type {{a:string,v:string,b:string}[]} */ const rels=[]; + /** @type {{n:FxNode,el:boolean,kind:string,f:Record}|null} */ let cur=null; + /** @param {string} s */ const name=s=>s.trim().replace(/:::[\w-]+$/,'').replace(/^"|"$/g,''); for(const line of ls){let m; if(cur){if(line==='}'){const f=cur.f,n=cur.n; @@ -1795,27 +1924,31 @@

Flow
Explainer

} /* ---------- mermaid: radar ---------- */ +/** @param {string[]} ls @returns {Graph} */ function parseRadar(ls){ - let title='',min=null,max=null;const axes=[],curves=[]; + let title='';/** @type {number|null} */ let min=null;/** @type {number|null} */ let max=null; + /** @type {{id:string,label:string}[]} */ const axes=[]; + /** @type {{id:string,label:string,v:Record,vals:(number|null)[]}[]} */ const curves=[]; + /** @param {string} s */ const label=s=>{const m=s.trim().match(/^([\w-]+)\s*(?:\[\s*"?(.*?)"?\s*\])?$/);return m?{id:m[1],label:cleanText(m[2]||humanId(m[1]))}:{id:s.trim(),label:cleanText(s)}}; for(const line of ls){let m; if(m=line.match(/^title\s+(.+)$/)){title=cleanText(m[1]);continue} if(m=line.match(/^axis\s+(.+)$/)){splitArgs(m[1]).filter(Boolean).forEach(a=>axes.push(label(a)));continue} if(m=line.match(/^curve\s+(.+?)\s*\{(.*)\}\s*$/)){ - const c=label(m[1]),body=m[2].trim(),v={}; + const c=label(m[1]),body=m[2].trim(),v=/** @type {Record} */({}); if(/:/.test(body))splitArgs(body).forEach(p=>{const q=p.match(/^\s*([\w-]+)\s*:\s*(-?[\d.]+)\s*$/);if(q)v[q[1]]=+q[2]}); else splitArgs(body).map(Number).forEach((x,i)=>{v['#'+i]=x}); - curves.push({...c,v});continue} + curves.push({...c,v,vals:[]});continue} if(m=line.match(/^max\s+(-?[\d.]+)/)){max=+m[1];continue} if(m=line.match(/^min\s+(-?[\d.]+)/)){min=+m[1];continue} } if(!axes.length)throw new Error('No axes found in the radar chart. Write them like axis a["Speed"], b["Price"]'); if(!curves.length)throw new Error('No curves found in the radar chart. Write them like curve x["Team A"]{4, 3, 5}'); curves.forEach(c=>{c.vals=axes.map((a,i)=>c.v[a.id]!=null?c.v[a.id]:c.v['#'+i]!=null?c.v['#'+i]:null)}); - const all=curves.flatMap(c=>c.vals).filter(v=>v!=null),lo=min!=null?min:Math.min(0,...all),hi=max!=null?max:Math.max(...all),span=hi-lo||1; - const n=axes.length,R0=1.5,R1=5.2,multi=curves.length>1,nodes=[],links=[]; + const all=curves.flatMap(c=>c.vals).filter(isNum),lo=min!=null?min:Math.min(0,...all),hi=max!=null?max:Math.max(...all),span=hi-lo||1; + const n=axes.length,R0=1.5,R1=5.2,multi=curves.length>1,nodes=/** @type {PlacedNode[]} */([]),links=/** @type {FxLink[]} */([]); curves.forEach((c,ci)=>{ - const ids=[]; + const ids=/** @type {string[]} */([]); c.vals.forEach((v,i)=>{if(v==null)return; const t=Math.max(0,Math.min(1,(v-lo)/span)),r=R0+(R1-R0)*t,ang=-Math.PI/2+2*Math.PI*i/n+(multi?(ci-(curves.length-1)/2)*.16:0); const id='c'+ci+'a'+i;ids.push(id); @@ -1824,46 +1957,55 @@

Flow
Explainer

ids.forEach((id,k)=>{if(ids.length>2||k[x.id,x])); - links.forEach(l=>{const a=by.get(l.from),b=by.get(l.to),dx=b.gx-a.gx,dy=b.gy-a.gy,d=Math.hypot(dx,dy)||1,k=Math.min(.55,d/3); + links.forEach(l=>{const a=/** @type {PlacedNode} */(by.get(l.from)),b=/** @type {PlacedNode} */(by.get(l.to)),dx=b.gx-a.gx,dy=b.gy-a.gy,d=Math.hypot(dx,dy)||1,k=Math.min(.55,d/3); l.pts=[[a.gx+dx/d*k,a.gy+dy/d*k],[b.gx-dx/d*k,b.gy-dy/d*k]]}); - const B=s=>'**'+s+'**'; - const steps=axes.map((a,i)=>{ - const ids=curves.map((c,ci)=>c.vals[i]!=null?'c'+ci+'a'+i:null).filter(Boolean); + const B=(/** @type {string} */s)=>'**'+s+'**'; + const steps=/** @type {Step[]} */(axes.map((a,i)=>{ + const ids=/** @type {string[]} */(curves.map((c,ci)=>c.vals[i]!=null?'c'+ci+'a'+i:null).filter(Boolean)); if(!ids.length)return null; let auto; - if(!multi){const v=curves[0].vals[i],vs=curves[0].vals.filter(x=>x!=null),mx=Math.max(...vs),mn=Math.min(...vs); + if(!multi){const v=/** @type {number} */(curves[0].vals[i]),vs=curves[0].vals.filter(isNum),mx=Math.max(...vs),mn=Math.min(...vs); auto=B(a.label)+' scores '+B(fmtNum(v))+(max!=null?' out of '+fmtNum(hi):'')+'.'+(vs.length>2&&v===mx?' This is the strongest point.':vs.length>2&&v===mn?' This is the weakest point.':'');} - else{const xs=curves.map(c=>({c,v:c.vals[i]})).filter(x=>x.v!=null).sort((p,q)=>q.v-p.v); + else{const xs=/** @type {{c:{label:string},v:number}[]} */(curves.map(c=>({c,v:c.vals[i]})).filter(x=>x.v!=null)).sort((p,q)=>q.v-p.v); auto='On '+B(a.label)+': '+xs.map(x=>x.c.label+' '+B(fmtNum(x.v))).join(', ')+'.'+(xs.length>1&&xs[0].v>xs[1].v?' '+xs[0].c.label+' leads here.':xs.length>1?' A tie at the top.':'');} - return {kind:'node',nodes:ids,title:a.label,chip:multi?'':fmtNum(curves[0].vals[i]),auto}; - }).filter(Boolean); + return {kind:'node',nodes:ids,title:a.label,chip:multi?'':fmtNum(/** @type {number} */(curves[0].vals[i])),auto}; + }).filter(s=>s!=null)); return {type:'radar',nodes,links,steps,groups:multi?curves.map(c=>({title:c.label})):[],fixed:true,noZones:true,diagramTitle:title}; } /* ---------- mermaid: treemap ---------- */ +/** @typedef {{label:string,v:number|null,kids:TreeItem[]}} TreeItem */ +/** @param {string} code @returns {Graph} */ function parseTreemap(code){ let raw=code.replace(/\r/g,'').split('\n'); if(raw.find(l=>l.trim())?.trim()==='---'){const a=raw.findIndex(l=>l.trim()==='---'),b=raw.findIndex((l,i)=>i>a&&l.trim()==='---');if(b>a)raw=raw.slice(b+1)} raw=raw.map(l=>l.replace(/%%.*$/,'').replace(/\t/g,' ')).filter(l=>l.trim()); raw=raw.slice(raw.findIndex(l=>/^\s*treemap(-beta)?\b/.test(l))+1).filter(l=>!/^\s*classDef\b/.test(l)); - const roots=[],stack=[]; + /** @type {TreeItem[]} */ const roots=[]; + /** @type {{ind:number,it:TreeItem}[]} */ const stack=[]; for(const l of raw){ - const ind=l.match(/^ */)[0].length,t=l.trim().replace(/:::[\w-]+\s*$/,'').trim(); + const ind=(l.match(/^ */)||[''])[0].length,t=l.trim().replace(/:::[\w-]+\s*$/,'').trim(); const m=t.match(/^("([^"]*)"|'([^']*)'|[^:]+?)\s*(?::\s*(-?[\d.]+))?$/);if(!m)continue; + /** @type {TreeItem} */ const it={label:cleanText(m[2]??m[3]??m[1]),v:m[4]!=null?+m[4]:null,kids:[]}; while(stack.length&&stack[stack.length-1].ind>=ind)stack.pop(); (stack.length?stack[stack.length-1].it.kids:roots).push(it);stack.push({ind,it}); } if(!roots.length)throw new Error('The treemap is empty. Write sections like "Section" and items like "Item": 12 indented under them.'); + /** @param {TreeItem} it @returns {number} */ const total=it=>it.kids.length?it.kids.reduce((s,k)=>s+total(k),0):Math.max(0,it.v||0); - const grand=roots.reduce((s,r)=>s+total(r),0)||1,leafMax=Math.max(1e-9,...(function all(a){return a.flatMap(x=>x.kids.length?all(x.kids):[x.v||0])})(roots)); + const grand=roots.reduce((s,r)=>s+total(r),0)||1,leafMax=Math.max(1e-9,...(/** @param {TreeItem[]} a @returns {number[]} */ function all(a){return a.flatMap(x=>x.kids.length?all(x.kids):[x.v||0])})(roots)); + /** @param {number} v */ const pct=v=>{const p=v/grand*100;return (p>=10||Number.isInteger(p)?Math.round(p):Math.round(p*10)/10)+'%'}; - const K=graphKit(),steps=[],B=s=>'**'+s+'**';let prev=null,cnt=0; + const K=graphKit(),steps=/** @type {Step[]} */([]),B=(/** @type {string} */s)=>'**'+s+'**'; + /** @type {FxNode|null} */ let prev=null; + let cnt=0; roots.forEach((r,i)=>{ K.groups.push({title:r.label});const g=K.groups.length-1,tot=total(r); const h=K.node('t'+(++cnt),r.label+' · '+pct(tot),'box');h.group=g;h.gx=i*DX;h.gy=0;h.ci=i; h.hk=r.kids.length?.5:.4+2.2*Math.max(0,r.v||0)/leafMax;h.icon=r.kids.length?'🗂️':'';h.note=fmtNum(tot)+' of '+fmtNum(grand)+' ('+pct(tot)+').'; let row=1;const members=[h.id]; + /** @param {TreeItem} it @param {FxNode} parent @param {number} depth @returns {void} */ const walk=(it,parent,depth)=>it.kids.forEach(k=>{ const t=total(k),n=K.node('t'+(++cnt),(depth>1?'› ':'')+k.label+' · '+fmtNum(t),k.kids.length?'pill':'box'); n.group=g;n.gx=i*DX+(depth>1?.35*(depth-1):0);n.gy=row++*2.6;n.ci=i;n.hk=k.kids.length?.5:.35+2.3*Math.max(0,k.v||0)/leafMax; @@ -1883,17 +2025,31 @@

Flow
Explainer

} /* ---------- mermaid: zenuml ---------- */ +/** @param {string[]} ls @returns {Graph} */ function parseZen(ls){ - const nodes=new Map(),links=[],lmap=new Map(),steps=[],groups=[],ctx=[],calls=[];let title='',note='',starter=null,grp=null; + /** @type {Map} */ const nodes=new Map(); + /** @type {FxLink[]} */ const links=[]; + /** @type {Map} */ const lmap=new Map(); + /** @type {Step[]} */ const steps=[]; + /** @type {Group[]} */ const groups=[]; + /** @type {(string|null)[]} */ const ctx=[]; + /** @type {{node?:FxNode,ctl?:boolean,group?:boolean}[]} */ const calls=[]; + let title='',note=''; + /** @type {FxNode|null} */ let starter=null; + /** @type {number|null} */ let grp=null; const DBRE=/^(database|db|dynamodb|rds|s3|sqs|sns|kafka|redis|elasticache|aurora|mysql|postgres\w*|storage|bucket|queue)$/i; + /** @param {string} id @param {string} [label] @param {string} [kind] @returns {FxNode} */ const getNode=(id,label,kind)=>{ id=id.trim(); if(!nodes.has(id)){const lb=cleanText(label||humanId(id));nodes.set(id,{id,label:lb,shape:kind==='actor'?'pill':(kind==='db'||/\b(db|database|sql|repo\w*|store|storage|cache|queue)\b|資料庫/i.test(lb)?'cyl':'box'),group:grp,actor:kind==='actor'})} - return nodes.get(id); + return /** @type {FxNode} */(nodes.get(id)); }; - const caller=()=>{for(let i=calls.length-1;i>=0;i--)if(calls[i].node)return calls[i].node;return starter||getNode('__start','Caller','actor')}; - const tag=()=>{for(let i=ctx.length-1;i>=0;i--)if(ctx[i])return ctx[i];return ''}; + /** @returns {FxNode} */ + const caller=()=>{for(let i=calls.length-1;i>=0;i--){const c=calls[i].node;if(c)return c}return starter||getNode('__start','Caller','actor')}; + const tag=()=>{for(let i=ctx.length-1;i>=0;i--){const t=ctx[i];if(t)return t}return ''}; + /** @type {Record} */ const WORD={if:'If',else:'Otherwise',while:'While',for:'For each',foreach:'For each',loop:'Repeat',par:'In parallel',opt:'Optional',try:'Try',catch:'If it fails',finally:'Finally',critical:'Critical',section:'',group:''}; + /** @param {FxNode} a @param {FxNode} b @param {string} text @param {{auto?:string,reply?:boolean,async?:boolean}} [o] */ const msg=(a,b,text,o={})=>{ if(a===b){steps.push({kind:'node',nodes:[a.id],title:text||a.label,auto:o.auto||'**'+a.label+'** does this on its own.',tag:tag()});return} const key=[a.id,b.id].sort().join('\u0001');let li=lmap.get(key); @@ -1901,14 +2057,17 @@

Flow
Explainer

steps.push({kind:'edge',link:li,reverse:links[li].from!==a.id,from:a.id,to:b.id,nodes:[a.id,b.id],title:text||(a.label+' → '+b.label), auto:o.auto||'**'+a.label+'** '+(o.reply?'replies to':o.async?'sends this to':'asks')+' **'+b.label+'**'+(o.reply||o.async?'.':' to do this.'),tag:tag()}); }; + /** @param {(n:string)=>void} f */ const withNote=f=>{const n=note;note='';f(n)}; - for(let line of ls){let m; + for(let line of ls){ + /** @type {RegExpMatchArray|null} */ + let m; if(m=line.match(/^\/\/\s*(.*)$/)){note=(note?note+' ':'')+cleanText(m[1].replace(/^`|`$/g,''));continue} if(m=line.match(/^title\s+(.+)$/i)){title=cleanText(m[1]);continue} if(m=line.match(/^group\s+("?[^{"]*"?)\s*\{\s*$/i)){groups.push({title:cleanText(m[1])||'Group'});grp=groups.length-1;ctx.push(null);calls.push({group:true});continue} if(m=line.match(/^@(\w+)\s+(?:<<[^>]*>>\s*)?([\w.]+)(?:\s+as\s+(.+?))?(?:\s+#\w+)?\s*$/)){getNode(m[2],m[3],/^actor$/i.test(m[1])?'actor':DBRE.test(m[1])?'db':'');continue} - if(m=line.match(/^@Starter\s*\(\s*([\w.]+)\s*\)\s*$/i)){starter=getNode(m[1],null,'actor');continue} - if(m=line.match(/^(?:<<[^>]*>>\s*)?([A-Za-z_][\w]*)(?:\s+as\s+(.+?))?(?:\s+#\w+)?\s*$/)&&!/^(if|else|while|for|forEach|loop|par|opt|try|catch|finally|critical|section|return|end)$/i.test(m[1])){getNode(m[1],m[2]);continue} + if(m=line.match(/^@Starter\s*\(\s*([\w.]+)\s*\)\s*$/i)){starter=getNode(m[1],undefined,'actor');continue} + if((m=line.match(/^(?:<<[^>]*>>\s*)?([A-Za-z_][\w]*)(?:\s+as\s+(.+?))?(?:\s+#\w+)?\s*$/))&&!/^(if|else|while|for|forEach|loop|par|opt|try|catch|finally|critical|section|return|end)$/i.test(m[1])){getNode(m[1],m[2]);continue} // closing braces (possibly followed by else / catch / finally) while(line.startsWith('}')){const top=calls.pop();if(top&&top.group){grp=null;ctx.pop()}else if(top&&top.ctl)ctx.pop();line=line.slice(1).trim()} if(!line)continue; @@ -1917,13 +2076,14 @@

Flow
Explainer

const w=k==='else if'?'Otherwise, if':WORD[k];ctx.push((w?w:'')+(cond?(w?': ':'')+cond:'')||null);calls.push({ctl:true});continue} if(m=line.match(/^(?:@return|return)\b\s*(.*)$/i)){ const real=calls.filter(c=>c.node),me=real[real.length-1],to=real.length>1?real[real.length-2].node:(starter||nodes.get('__start')); - if(me&&to)withNote(n=>msg(me.node,to,cleanText(m[1])?'Returns '+cleanText(m[1]):'Done',{reply:true,auto:n||undefined}));continue} + const rv=cleanText(m[1]),meN=me&&me.node;if(meN&&to)withNote(n=>msg(meN,to,rv?'Returns '+rv:'Done',{reply:true,auto:n||undefined}));continue} if(m=line.match(/^([\w.]+)\s*(->|-->)\s*([\w.]+)\s*:\s*(.*)$/)){ - const a=getNode(m[1]),b=getNode(m[3]);withNote(n=>msg(a,b,cleanText(m[4]),{async:true,auto:n||undefined}));continue} + const a=getNode(m[1]),b=getNode(m[3]),txt=cleanText(m[4]);withNote(n=>msg(a,b,txt,{async:true,auto:n||undefined}));continue} const open=/\{\s*$/.test(line),body=line.replace(/\{\s*$/,'').trim().replace(/;$/,''); if(m=body.match(/^(?:(?:[\w<>[\]]+\s+)?([\w]+)\s*=\s*)?new\s+([\w.]+)\s*\((.*)\)$/)){ const fromN=caller(),b=getNode(m[2]); - withNote(n=>msg(fromN,b,'Create '+b.label,{auto:n||'**'+fromN.label+'** creates a new **'+b.label+'**'+(m[3]?' with '+cleanText(m[3]):'')+'.'})); + const withArgs=m[3]?' with '+cleanText(m[3]):''; + withNote(n=>msg(fromN,b,'Create '+b.label,{auto:n||'**'+fromN.label+'** creates a new **'+b.label+'**'+withArgs+'.'})); if(open)calls.push({node:b});continue} if(m=body.match(/^(?:(?:[\w<>[\]]+\s+)?([\w]+)\s*=\s*)?(?:([\w]+)\.)?([\w]+)\s*\((.*)\)$/)){ const fromN=caller(),b=m[2]?getNode(m[2]):fromN,fn=m[3],args=cleanText(m[4]); @@ -1936,49 +2096,56 @@

Flow
Explainer

} /* ---------- layout ---------- */ -const DX=3.0,DY=2.2,T0=0.56,T1=1.08; +// 3D blocks are drawn a little closer together than the flat 2D ones +const IS_3D_PAGE=typeof document!=='undefined'&&document.body.dataset.view==='3d'; +const DX=IS_3D_PAGE?3.0:3.1,DY=IS_3D_PAGE?2.2:2.3,T0=0.56,T1=1.08; +/** Layered layout for graphs without fixed positions: sets gx/gy on nodes and pts on links. @param {FxNode[]} nodes @param {FxLink[]} links */ function layout(nodes,links){ - const ix=new Map(nodes.map((n,i)=>[n.id,i])),N=nodes.length,routes=[],rmap=new Map(); + const ix=new Map(nodes.map((n,i)=>/** @type {[string,number]} */([n.id,i]))),N=nodes.length,routes=/** @type {Route[]} */([]),rmap=/** @type {Map} */(new Map()); links.forEach(l=>{ - l.route=null;const a=ix.get(l.from),b=ix.get(l.to);if(a===b)return; + l.route=null;const a=/** @type {number} */(ix.get(l.from)),b=/** @type {number} */(ix.get(l.to));if(a===b)return; const k=a[]);routes.forEach(r=>out[r.u].push(r)); + const out=Array.from({length:N},()=>/** @type {Route[]} */([]));routes.forEach(r=>out[r.u].push(r)); const st=new Array(N).fill(0); + /** @param {number} u @returns {void} */ const dfs=u=>{st[u]=1;for(const r of out[u]){if(st[r.v]===1)r.flip=true;else if(!st[r.v])dfs(r.v)}st[u]=2}; for(let i=0;i{r.a=r.flip?r.v:r.u;r.b=r.flip?r.u:r.v}); - const rank=new Array(N).fill(0),indeg=new Array(N).fill(0),succ=Array.from({length:N},()=>[]); + const rank=new Array(N).fill(0),indeg=new Array(N).fill(0),succ=Array.from({length:N},()=>/** @type {number[]} */([])); routes.forEach(r=>{succ[r.a].push(r.b);indeg[r.b]++}); - const deg=indeg.slice(),q=[];for(let i=0;irank[v]))-1; - const R=Math.max(...rank)+1,layers=Array.from({length:R},()=>[]); - const items=nodes.map((n,i)=>({real:true,i,r:rank[i],up:[],down:[],y:0})); + const R=Math.max(...rank)+1,layers=Array.from({length:R},()=>/** @type {LayoutItem[]} */([])); + const items=nodes.map((n,i)=>/** @type {LayoutItem} */({real:true,i,r:rank[i],up:[],down:[],y:0})); items.forEach(it=>layers[it.r].push(it)); routes.forEach(r=>{ const chain=[items[r.a]]; - for(let k=rank[r.a]+1;kL.forEach((it,p)=>it.p=p)); + /** @param {LayoutItem[]} a @param {(x:LayoutItem)=>number} f */ const avg=(a,f)=>a.reduce((s,x)=>s+f(x),0)/a.length; for(let t=0;t<14;t++){ const down=t%2===0; for(let k=0;k{const ns=down?it.up:it.down;it.bc=ns.length?avg(ns,x=>x.p):it.p}); - L.sort((x,y)=>x.bc-y.bc||x.p-y.p);L.forEach((it,p)=>it.p=p); + L.forEach(it=>{const ns=down?it.up:it.down;it.bc=ns.length?avg(ns,x=>x.p||0):it.p}); + L.sort((x,y)=>(x.bc||0)-(y.bc||0)||(x.p||0)-(y.p||0));L.forEach((it,p)=>it.p=p); } } layers.forEach(L=>L.forEach((it,p)=>it.y=p-(L.length-1)/2)); + /** @param {LayoutItem} a @param {LayoutItem} b */ const sep=(a,b)=>(a.real&&b.real)?1:0.6; + /** @param {LayoutItem[]} L @param {number[]} des */ const place=(L,des)=>{ - const n=L.length,F=[],B=[]; + const n=L.length,F=/** @type {number[]} */([]),B=/** @type {number[]} */([]); F[0]=des[0];for(let i=1;i=0;i--)B[i]=Math.min(des[i],B[i+1]-sep(L[i],L[i+1])); L.forEach((it,i)=>it.y=(F[i]+B[i])/2); @@ -2006,6 +2173,9 @@

Flow
Explainer

/* ---------- diagram styles + settings (same block in index.html and 3d.html) ---------- */ // One entry per diagram style. Add a style by copying an entry; both pages read the same fields. // 2D uses bg/bg2, blocks, neutral, ink, edge, accent, shadow, gridOp, sw, opacity; 3D also uses mat, rough, outline, ground, grid3. +// Optional: chips (flat chip look: inset top square + pins), flat (block height factor), labMono / labUpper (plain monospace capital labels). +/** @typedef {{name:string,desc:string,dark?:boolean,bg:string,bg2:string,blocks:string[],neutral:string,ink:string,edge:string,edge3d:string|null,accent:string,accentFg:string,plate:string,plateFg:string,plateBd:string,on:string,onFg:string,muted:string,zone:string,zoneBd:string,chip:string,labShadow:string,shadow:string,gridOp:number,grid3:number,ground:number,mat:string,rough:number,opacity:number,outline:number,sw:number,chips?:boolean,flat?:number,labMono?:boolean,labUpper?:boolean}} DiagramStyle */ +/** @type {Record} */ const STYLES={ original:{name:'Original',desc:'Pastel blocks on warm paper', bg:'#f5f0e6',bg2:'#fbf7ee',blocks:['#a9c8f5','#b6e3b1','#cdbdf6','#f7da8c','#f5b9c5','#f8c59b','#a9e0dc'],neutral:'#e6e0d2', @@ -2036,20 +2206,29 @@

Flow
Explainer

ink:'#0f4c5c',edge:'#5b9aa6',edge3d:'#ffffff',accent:'#fcaf17',accentFg:'#1f1300', plate:'rgba(255,255,255,.85)',plateFg:'#0f172a',plateBd:'rgba(15,76,92,.3)',on:'#007c90',onFg:'#ffffff',muted:'#3b6f7b', zone:'rgba(0,124,144,.05)',zoneBd:'rgba(0,124,144,.35)',chip:'rgba(255,255,255,.75)',labShadow:'rgba(15,23,42,.08)',shadow:'rgba(15,76,92,.10)', - gridOp:.07,grid3:.07,ground:.1,mat:'glass',rough:.15,opacity:.6,outline:0,sw:1} + gridOp:.07,grid3:.07,ground:.1,mat:'glass',rough:.15,opacity:.6,outline:0,sw:1}, + circuit:{name:'Circuit',desc:'Dark board, flat chips, thin blue lines',dark:true, + bg:'#080c17',bg2:'#0e1527',blocks:['#1a2438','#1b2a42','#172236'],neutral:'#1a2438', + ink:'#4d6a90',edge:'#7393bd',edge3d:'#86a6d0',accent:'#bfe1ff',accentFg:'#0a0e1a', + plate:'transparent',plateFg:'#c9d6e8',plateBd:'transparent',on:'rgba(191,225,255,.12)',onFg:'#ffffff',muted:'#8094ae', + zone:'rgba(115,147,189,.05)',zoneBd:'rgba(115,147,189,.35)',chip:'rgba(8,12,23,.7)',labShadow:'transparent',shadow:'rgba(0,0,0,.35)', + gridOp:.11,grid3:.11,ground:0,mat:'basic',rough:1,opacity:1,outline:0,sw:.8, + chips:true,flat:.42,labMono:true,labUpper:true} }; let DS=STYLES.original,DSK='original'; const UI_ICON={check:'',chev:''}; const hashStyle=()=>{const m=location.hash.match(/[#&]s=([\w-]+)/);return m&&STYLES[m[1]]?m[1]:null}; +/** @param {string|null} k */ function useStyle(k){ - DSK=STYLES[k]?k:'original';DS=STYLES[DSK];const s=DS,r=document.documentElement.style; + DSK=k&&STYLES[k]?k:'original';DS=STYLES[DSK];const s=DS,r=document.documentElement.style; Object.entries({'--d-bg':s.bg,'--d-bg2':s.bg2,'--d-ink':s.ink,'--d-accent':s.accent,'--d-accent-fg':s.accentFg,'--d-plate':s.plate,'--d-plate-fg':s.plateFg,'--d-plate-bd':s.plateBd, - '--d-on':s.on,'--d-on-fg':s.onFg,'--d-muted':s.muted,'--d-zone':s.zone,'--d-zone-bd':s.zoneBd,'--d-chip':s.chip,'--d-lab-shadow':s.labShadow}).forEach(([p,v])=>r.setProperty(p,v)); + '--d-on':s.on,'--d-on-fg':s.onFg,'--d-muted':s.muted,'--d-zone':s.zone,'--d-zone-bd':s.zoneBd,'--d-chip':s.chip,'--d-lab-shadow':s.labShadow,'--d-lab':s.labMono?'var(--d-mono)':'var(--d-sans)'}).forEach(([p,v])=>r.setProperty(p,v)); document.body.classList.toggle('d-dark',!!s.dark); document.querySelectorAll('#arr path').forEach(p=>p.setAttribute('fill',s.ink)); document.querySelectorAll('#arrA path').forEach(p=>p.setAttribute('fill',s.accent)); /** @type {NodeListOf} */(document.querySelectorAll('#styleSel .opt')).forEach(b=>{const on=b.dataset.s===DSK;b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on))}); } +/** @param {string} k */ function setStyle(k){ if(!STYLES[k]||k===DSK)return;useStyle(k); try{localStorage.setItem('flowx.style',k)}catch(e){} @@ -2060,6 +2239,7 @@

Flow
Explainer

const hi=location.hash.match(/[#&]i=([01])/);let ic=hi?hi[1]:null;if(ic==null)try{ic=localStorage.getItem('flowx.icons')}catch(e){}ICONS_ON=ic!=='0'} // emoji icons on the blocks: on by default; saved in the browser and carried in client links as &i=0 let ICONS_ON=true; +/** @param {boolean} on */ function setIcons(on){ if(on===ICONS_ON)return;ICONS_ON=on;markIcons(); try{localStorage.setItem('flowx.icons',on?'1':'0')}catch(e){} @@ -2070,9 +2250,10 @@

Flow
Explainer

function buildSettings(){ $('#styleSel').innerHTML=Object.entries(STYLES).map(([k,s])=>'').join(''); - $('#viewSel').querySelectorAll('button').forEach(b=>b.classList.toggle('on',b.dataset.v===document.body.dataset.view)); + $('#viewSel').querySelectorAll('button').forEach((/** @type {HTMLElement} */b)=>b.classList.toggle('on',b.dataset.v===document.body.dataset.view)); useStyle(DSK); } +/** @param {string|null} name */ function openPop(name){ [['set',$('#settings')],['share',$('#share')]].forEach(([k,el])=>el.classList.toggle('open',k===name)); $('#btnSet').classList.toggle('on',name==='set');$('#btnSet').setAttribute('aria-expanded',name==='set'); @@ -2091,37 +2272,44 @@

Flow
Explainer

const rootUrl=()=>location.origin+appBase(); /** @param {string} u */ const tidyUrl=u=>u.replace(/([^:]\/)\/+/g,'$1'); +/** Page URL without a trailing slash: `/3d/` would break relative asset URLs and is a 404 on static hosts. @param {string} sub */ +const pageUrl=sub=>sub?tidyUrl(rootUrl()+sub):tidyUrl(rootUrl()+'/'); const linkOpts=()=>(DSK!=='original'?'&s='+DSK:'')+(ICONS_ON?'':'&i=0'); -const clientLink=async()=>tidyUrl(rootUrl()+(is3dView()?'/3d':'')+'/')+'#c='+await encode(/** @type {any} */(S).md)+linkOpts(); -const embedLink=async()=>tidyUrl(rootUrl()+'/embed'+(is3dView()?'/3d':'')+'/')+'#c='+await encode(/** @type {any} */(S).md)+linkOpts(); +const clientLink=async()=>pageUrl(is3dView()?'/3d':'')+'#c='+await encode(/** @type {any} */(S).md)+linkOpts(); +const embedLink=async()=>pageUrl('/embed'+(is3dView()?'/3d':''))+'#c='+await encode(/** @type {any} */(S).md)+linkOpts(); /** @param {'2d'|'3d'} dim */ function viewHref(dim){ const h=location.hash||''; - if(isEmbed()) return tidyUrl(rootUrl()+'/embed'+(dim==='3d'?'/3d':'')+'/')+h; + if(isEmbed()) return pageUrl('/embed'+(dim==='3d'?'/3d':''))+h; if(/\.html$/.test(location.pathname)) return tidyUrl(rootUrl()+'/'+(dim==='3d'?'3d.html':'index.html'))+(/(?:^|[?&])embed/.test(location.search)?'?embed=1':'')+h; - return tidyUrl(rootUrl()+(dim==='3d'?'/3d':'')+'/')+h; + return pageUrl(dim==='3d'?'/3d':'')+h; } +/** UI state kept on S by this block. */ +const uiState=()=>/** @type {{stepsOpen?:boolean|null}} */(/** @type {unknown} */(S)); +/** @param {Event} e */ +const tgt=e=>/** @type {HTMLElement} */(e.target); +/** @param {Graph} g @param {number} i @returns {string} */ function stepsHtml(g,i){ - const n=g.steps.length,by=id=>g.nodes.find(x=>x.id===id); - if(S.stepsOpen==null)S.stepsOpen=!matchMedia('(max-width:820px)').matches; + const n=g.steps.length,by=(/** @type {string|undefined} */id)=>g.nodes.find(x=>x.id===id),U=uiState(); + if(U.stepsOpen==null)U.stepsOpen=!matchMedia('(max-width:820px)').matches; const rows=g.steps.map((s,k)=>{ - const st=k+1(by(id)||{}).label).filter(Boolean).join(', '); + const st=k+1by(id)?.label).filter(Boolean).join(', '); const lb=l&&l.label&&l.label.length<=14&&l.label!==s.title?l.label:'',yes=/^(yes|y|true|ok|success|pass(ed)?|approved?|valid)$/i.test(lb),no=/^(no|n|false|fail(ed)?|error|reject(ed)?|denied|invalid)$/i.test(lb); const tag=lb&&(yes||no||(a&&a.shape==='hex'))?'if '+esc(lb)+'':''; return '
  • '+(st==='done'?UI_ICON.check:k+1)+''+esc(s.title)+''+tag+(st==='on'?'Now':'')+'' +(sub&&sub!==s.title?''+esc(sub)+'':'')+'
  • '; }).join(''); - return '
    All steps'+(i?'Step '+i+' of '+n:n+' step'+(n===1?'':'s'))+''+UI_ICON.chev+'' + return '
    All steps'+(i?'Step '+i+' of '+n:n+' step'+(n===1?'':'s'))+''+UI_ICON.chev+'' +'
      '+rows+'
    '; } function wireUi(){ buildSettings(); - $('#btnSet').onclick=e=>{e.stopPropagation();openPop($('#settings').classList.contains('open')?null:'set')}; + $('#btnSet').onclick=(/** @type {MouseEvent} */e)=>{e.stopPropagation();openPop($('#settings').classList.contains('open')?null:'set')}; $('#setClose').onclick=$('#shareClose').onclick=$('#popScrim').onclick=()=>openPop(null); - $('#styleSel').onclick=e=>{const b=e.target.closest('.opt');if(b)setStyle(b.dataset.s)}; - markIcons();$('#iconSel').onclick=e=>{const b=e.target.closest('button');if(b)setIcons(b.dataset.i==='1')}; - $('#viewSel').onclick=e=>{const b=e.target.closest('button');if(b&&b.dataset.v!==document.body.dataset.view)$('#btnMode').click()}; + $('#styleSel').onclick=(/** @type {MouseEvent} */e)=>{const b=/** @type {HTMLElement|null} */(tgt(e).closest('.opt'));if(b)setStyle(b.dataset.s||'')}; + markIcons();$('#iconSel').onclick=(/** @type {MouseEvent} */e)=>{const b=/** @type {HTMLElement|null} */(tgt(e).closest('button'));if(b)setIcons(b.dataset.i==='1')}; + $('#viewSel').onclick=(/** @type {MouseEvent} */e)=>{const b=/** @type {HTMLElement|null} */(tgt(e).closest('button'));if(b&&b.dataset.v!==document.body.dataset.view)$('#btnMode').click()}; $('#btnShare').onclick=async()=>{ const url=await clientLink();let ok=true; try{await navigator.clipboard.writeText(url)}catch(e){ok=false} @@ -2133,18 +2321,18 @@

    Flow
    Explainer

    const url=await embedLink(); try{await navigator.clipboard.writeText(url);toast('Embed link copied')}catch(e){prompt('Copy this embed link',url)} }; - $('#panel').addEventListener('keydown',e=>{const li=e.target.closest&&e.target.closest('.stepper li');if(li&&(e.key==='Enter'||e.key===' ')){e.preventDefault();e.stopPropagation();go(+li.dataset.s)}}); - const ab=$('#about'),about=o=>{ab.classList.toggle('open',o);if(o){openPop(null);ab.querySelector('.about-card').scrollTop=0;$('#aboutClose').focus({preventScroll:true})}}; - $('#btnAbout').onclick=()=>about(true);$('#aboutClose').onclick=()=>about(false);ab.onclick=e=>{if(e.target===ab)about(false)}; - /** @type {NodeListOf} */(document.querySelectorAll('[data-about]')).forEach(a=>a.onclick=e=>{e.preventDefault();about(true)}); + $('#panel').addEventListener('keydown',(/** @type {KeyboardEvent} */e)=>{const t=tgt(e),li=/** @type {HTMLElement|null} */(t.closest&&t.closest('.stepper li'));if(li&&(e.key==='Enter'||e.key===' ')){e.preventDefault();e.stopPropagation();go(+(li.dataset.s||0))}}); + const ab=$('#about'),about=(/** @type {boolean} */o)=>{ab.classList.toggle('open',o);if(o){openPop(null);/** @type {HTMLElement} */(ab.querySelector('.about-card')).scrollTop=0;$('#aboutClose').focus({preventScroll:true})}}; + $('#btnAbout').onclick=()=>about(true);$('#aboutClose').onclick=()=>about(false);ab.onclick=(/** @type {MouseEvent} */e)=>{if(e.target===ab)about(false)}; + /** @type {NodeListOf} */(document.querySelectorAll('[data-about]')).forEach(a=>a.onclick=(/** @type {MouseEvent} */e)=>{e.preventDefault();about(true)}); // New: empty editor with a starter template one click away; Examples: load a sample straight from the header const TPL=$('#tplNew').textContent.trim()+'\n'; $('#btnNew').onclick=()=>{drawer(true);$('#src').value='';$('#src').placeholder=TPL;$('#drawerTitle').textContent='New walkthrough';showErr('');$('#src').focus()}; $('#btnTpl').onclick=()=>{$('#src').value=TPL;$('#src').focus()}; $('#btnEdit').addEventListener('click',()=>{$('#drawerTitle').textContent='Paste your markdown';$('#src').placeholder=''}); const ex2=$('#exHead');ex2.innerHTML=$('#exSel').innerHTML.replace('Load example…','Examples'); - ex2.onchange=e=>{const v=e.target.value;if(v){$('#src').value=$('#'+v).textContent.trim()+'\n';e.target.value='';tryRender()}}; - $('#panel').addEventListener('toggle',e=>{if(e.target.matches&&e.target.matches('details.steps'))S.stepsOpen=e.target.open},true); + ex2.onchange=(/** @type {Event} */e)=>{const t=/** @type {HTMLSelectElement} */(e.target),v=t.value;if(v){$('#src').value=$('#'+v).textContent.trim()+'\n';t.value='';tryRender()}}; + $('#panel').addEventListener('toggle',(/** @type {Event} */e)=>{const t=/** @type {HTMLDetailsElement} */(e.target);if(t.matches&&t.matches('details.steps'))uiState().stepsOpen=t.open},true); } /* ---------- end of diagram styles + settings ---------- */ @@ -2202,6 +2390,19 @@

    Flow
    Explainer

    vs.forEach(p=>pos.push(p[0],0,-p[1],p[0],def.H,-p[1])); const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.Float32BufferAttribute(pos,3));return g; } +// Chip look (Circuit style): inset squares on the top face and short pins along the straight sides +/** @param {{H:number,poly:number[][]}} def */ +function chipGeo(def){ + const P=def.poly,n=P.length,pos=[],cx=P.reduce((a,p)=>a+p[0],0)/n,cy=P.reduce((a,p)=>a+p[1],0)/n; + [.8,.56].forEach(k=>{for(let i=0;iFlow
    Explainer else{const n=find(k);if(n)n.note=v} }); g.title=raw.title||g.diagramTitle||'';g.intro=raw.intro; - const ranks=[...new Set(g.nodes.map(n=>n.gx))].sort((a,b)=>a-b); + const ranks=[...new Set(g.nodes.map(n=>n.gx||0))].sort((a,b)=>a-b); g.nodes.forEach(n=>{n.rank=ranks.indexOf(n.gx)}); return g; } @@ -2325,18 +2526,19 @@

    Flow
    Explainer

    g.nodes.forEach(n=>{ const base=SHAPE_DEF[n.shape]||SHAPE_DEF.box,def=n.hk?{H:base.H*n.hk,poly:rr(.5,.14),geo:()=>[prismGeo(rr(.5,.14),base.H*n.hk)]}:base,grp=new THREE.Group(),body=new THREE.Group();grp.position.set(n.gx,0,n.gy); - const mat=blockMat(n.color),lines=[]; - const meshes=def.geo().map(ge=>{const m=new THREE.Mesh(ge,mat);m.castShadow=m.receiveShadow=DS.ground>0;m.userData.id=n.id;m.renderOrder=5;body.add(m);S.pick.push(m); - if(DS.outline){const hm=new THREE.MeshBasicMaterial({color:DS.edge3d,side:THREE.BackSide,transparent:true});hm.userData.base=1;lines.push(hm); - const h=new THREE.Mesh(ge,hm);h.scale.set(1+DS.outline,1+DS.outline*.5,1+DS.outline);h.position.y=-.004;h.renderOrder=4;body.add(h)} + const mat=blockMat(n.color),lines=[],fz=DS.flat||1,inner=new THREE.Group(),H=def.H*fz;inner.scale.y=fz;body.add(inner); + const meshes=def.geo().map(ge=>{const m=new THREE.Mesh(ge,mat);m.castShadow=m.receiveShadow=DS.ground>0;m.userData.id=n.id;m.renderOrder=5;inner.add(m);S.pick.push(m); + if(DS.outline){const hm=new THREE.MeshBasicMaterial({color:DS.edge3d||DS.edge,side:THREE.BackSide,transparent:true});hm.userData.base=1;lines.push(hm); + const h=new THREE.Mesh(ge,hm);h.scale.set(1+DS.outline,1+DS.outline*.5,1+DS.outline);h.position.y=-.004;h.renderOrder=4;inner.add(h)} return m}); - if(DS.edge3d){const lm=new THREE.LineBasicMaterial({color:DS.edge3d,transparent:true,opacity:.95});lm.userData.base=.95;lines.push(lm);const e=new THREE.LineSegments(edgeGeo(def),lm);e.renderOrder=6;body.add(e)} - const ic=ICONS_ON?iconFor(n):'',icon=ic?emoji(ic):null;if(icon){icon.position.y=def.H+.36;body.add(icon)} + if(DS.edge3d){const lm=new THREE.LineBasicMaterial({color:DS.edge3d,transparent:true,opacity:.95});lm.userData.base=.95;lines.push(lm);const e=new THREE.LineSegments(edgeGeo(def),lm);e.renderOrder=6;inner.add(e); + if(DS.chips){const c=new THREE.LineSegments(chipGeo(def),lm);c.renderOrder=6;inner.add(c)}} + const ic=ICONS_ON?iconFor(n):'',icon=ic?emoji(ic):null;if(icon){icon.position.y=H+.36;body.add(icon)} const ringMat=new THREE.MeshBasicMaterial({color:DS.accent,transparent:true,opacity:0,depthWrite:false,side:THREE.DoubleSide}); const ring=new THREE.Mesh(new THREE.RingGeometry(.84,.95,64),ringMat);ring.rotation.x=-Math.PI/2;ring.position.y=.04;ring.renderOrder=3;ring.visible=false; grp.add(body,ring);root.add(grp); - n.o={body,mat,lines,base:DS.mat==='basic'||DS.mat==='glass'?DS.opacity:1,meshes,icon,ring,ringMat,H:def.H,lift:0,v:0,op:1,ghost:false,active:false,source:false,born:now+250+n.rank*110}; - n.o.L=lab('node',n.label,V(n.gx,def.H+(icon?.74:.2),n.gy),'-50%,-100%',{n,born:n.o.born+260}); + n.o={body,mat,lines,base:DS.mat==='basic'||DS.mat==='glass'?DS.opacity:1,meshes,icon,ring,ringMat,H,lift:0,v:0,op:1,ghost:false,active:false,source:false,born:now+250+n.rank*110}; + n.o.L=lab('node',DS.labUpper?n.label.toUpperCase():n.label,V(n.gx,H+(icon?.74:.2),n.gy),'-50%,-100%',{n,born:n.o.born+260}); }); packets=[.13,.1,.075].map(r=>{const m=new THREE.Mesh(new THREE.SphereGeometry(r,20,14),new THREE.MeshStandardMaterial({color:DS.accent,emissive:DS.accent,emissiveIntensity:.45,roughness:.4}));m.castShadow=true;m.visible=false;root.add(m);return m}); @@ -2705,7 +2907,7 @@

    Flow
    Explainer

    ctx.fillStyle=DS.labShadow;rrect(ctx,r.x,r.y+2*s,r.w,r.h,8*s);ctx.fill(); ctx.fillStyle=bg;ctx.strokeStyle=bc;ctx.lineWidth=1.4*s;rrect(ctx,r.x,r.y,r.w,r.h,8*s);ctx.fill();ctx.stroke(); ctx.beginPath();ctx.moveTo(cx-5*s,b-.5*s);ctx.lineTo(cx,b+5.5*s);ctx.lineTo(cx+5*s,b-.5*s);ctx.fill();ctx.stroke(); - ctx.font='600 '+(12.5*s)+'px ui-sans-serif, system-ui, -apple-system, "Segoe UI", "PingFang HK", "Noto Sans TC", sans-serif'; + ctx.font='600 '+(12.5*s)+'px '+cs.fontFamily; const lines=[],toks=txt.match(/[⺀-鿿豈-﫿＀-￯]|[^\s⺀-鿿豈-﫿＀-￯]+\s*/g)||[txt],mw=r.w-16*s;let cur=''; for(const t of toks){if(cur&&ctx.measureText((cur+t).trimEnd()).width>mw){lines.push(cur.trimEnd());cur=t}else cur+=t} if(cur.trim())lines.push(cur.trimEnd());lines.length=Math.min(lines.length,3); diff --git a/AGENTS.md b/AGENTS.md index 0df67bb..bd5b207 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ Turns pasted GitHub markdown (Mermaid flowchart, sequence, state, class, ER, gan - `index.html` — 2D isometric SVG version. Also served from zo.space API route `/flow-explainer` (not linked publicly). - `3d.html` — Three.js version (real 3D blocks, rotatable camera). Also served via zo.space (route `/flow-explainer/:file`; Three.js 0.187.0 jsDelivr-minified in `vendor/`, imported as `./vendor/three.module.js` and served by route `/flow-explainer/vendor/:file`). -- Both files are standalone and edited directly; they share the same markdown parser, layout, panel, timeline and `#c=` client-link code (copied, not imported). The parser block (`/* ---------- markdown` … `/* ---------- layout`) and the diagram styles block are edited in `index.html` only, then copied with `python3 tools/sync-parser.py` (`--check` to verify). Non-parser fixes (render, buildScene, iconFor) still go into both files by hand. +- Both files are standalone and edited directly; they share the same markdown parser, layout, panel, timeline and `#c=` client-link code (copied, not imported). The shared core (`/* ---------- shared core:` … `/* ---------- end of diagram styles + settings`: helpers, markdown + Mermaid parsers, layout, diagram styles/settings UI) is edited in `index.html` only, then copied with `python3 tools/sync-parser.py` (`--check` to verify). Layout spacing differs per page via `IS_3D_PAGE`. Non-parser fixes (render, buildScene, iconFor) still go into both files by hand. - Every diagram type is converted into the same `{nodes,links,steps,groups}` graph. Extra node fields: `note`, `icon` (forced emoji), `iconFallback`, `ci` (palette index), `hk` (height factor: pie, journey, xychart, sankey, packet). Graph flags: `fixed` (parser set `gx/gy`, skip `layout()`; non-pie fixed parsers call `routeFixed()` to give links `pts`: timeline, quadrant, git, xychart, block, kanban, packet), `noZones` (colour groups without zone slabs, mindmap), `diagramTitle` (used when the markdown has no heading). - Both read the same `localStorage` key `flowx.md`; the 2D/3D button keeps the URL hash and works with both `/flow-explainer` ↔ `/flow-explainer/3d` and `index.html` ↔ `3d.html` (static hosting). - Public repo: https://github.com/solutionforest/flow-explainer (MIT). README images in `docs/images/` were made with the Snapshot button; sample inputs in `examples/`. @@ -21,3 +21,7 @@ Turns pasted GitHub markdown (Mermaid flowchart, sequence, state, class, ER, gan - Icons: Settings → Icons (Show/Hide) toggles the emoji on blocks (`ICONS_ON`, `localStorage` `flowx.icons`, client links carry `&i=0` when hidden); renderers call `ICONS_ON?iconFor(n):''`. - radar (`parseRadar`, points on a circle, `noZones`), treemap (`parseTreemap`, kanban-like columns per top section) and zenuml (`parseZen`, sequence model with a call stack) were added after the first 20 types. - Code checks: `npm run check` = sync check + ESLint (`eslint.config.mjs`) + `tsc -p tsconfig.basic.json` (checkJs, must be 0 errors) + strict TS with baseline (`tools/typecheck-strict.mjs`, `tsc-baseline.json`; no new errors allowed, run `npm run typecheck:baseline` after fixing some). Page scripts are copied to `.check/` with line numbers kept (`tools/extract-scripts.mjs`). CI: `.github/workflows/check.yml`. In index.html the play-stop function is `stopPlay()` (avoids shadowing `window.stop`). +- Strict typing: the shared core must have 0 TypeScript strict errors (JSDoc typedefs `FxNode`, `FxLink`, `Step`, `Graph`, `Scene`, `MdDoc`, `DiagramStyle`…); `tools/typecheck-strict.mjs` fails on any core error regardless of the baseline. server.js / tools / tests are strict via `tsconfig.node.json`. +- Tests: `npm test` (node:test) — `tests/load-core.mjs` evaluates the shared core from index.html in a VM; `tests/parser.snapshot.json` pins parser output (`npm run test:update` to accept intended changes); `tests/server.test.mjs` covers routes incl. `/embed`, `/embed/3d`, trailing slashes, assets under sub-paths and private files. +- Circuit style (`circuit`): `chips` (2D `chipDetail()`, 3D `chipGeo()`), `flat` (block height factor), `labMono`/`labUpper` (plain monospace capital labels, `--d-lab`). +- server.js exports `resolveFile`/`handle` (listens only when run directly). Links are built without trailing slashes (`pageUrl()`): `/3d/` used to 404 and `/embed/…/` broke relative asset URLs. diff --git a/README.md b/README.md index 8a0df5e..4b4871c 100644 --- a/README.md +++ b/README.md @@ -245,7 +245,7 @@ If a browser has no WebGL, the 3D page opens the 2D page automatically. Open **⚙ Settings** to change how the diagram looks. The same style is used in 2D and 3D, it is saved in your browser, and a client link opens with the style you picked. -![The ticket-order example in the five diagram styles: Original, Teal, Line Art, Blueprint and Glass](docs/images/diagram-styles.png) +![The ticket-order example in the six diagram styles: Original, Teal, Line Art, Blueprint, Glass and Circuit](docs/images/diagram-styles.png) | Style | Look | |---|---| @@ -254,6 +254,7 @@ Open **⚙ Settings** to change how the diagram looks. The same style is used in | Line Art | White blocks with bold black outlines | | Blueprint | Dark background, cyan wireframe blocks | | Glass | See-through blocks | +| Circuit | Dark board with flat chip-shaped blocks (inset top, pins), thin steel-blue lines and plain capital labels | Each style is one entry in the `STYLES` list in `index.html` (background, block colours, outline, highlight, label colours, and the 3D material). To add a style, copy an entry, change the values, and run `python3 tools/sync-parser.py` so `3d.html` gets it too. The site itself always uses the Solution Forest colours; only the diagram changes. @@ -314,26 +315,34 @@ Both pages share the same markdown reader, step panel, timeline, settings and cl ## Code checks -The pages have no build step, but the code inside them is checked the way a typed project would be. `npm run check` runs four steps, and GitHub Actions runs the same on every push and pull request ([`check.yml`](.github/workflows/check.yml)): +The pages have no build step, but the code inside them is checked the way a typed project would be. `npm run check` runs five steps, and GitHub Actions runs the same on every push and pull request ([`check.yml`](.github/workflows/check.yml)): | Step | Command | What it does | Must be | |---|---|---|---| -| Shared code in sync | `npm run check:sync` | The parser and diagram-style blocks in `3d.html` match `index.html` | in sync | -| Lint | `npm run lint` | ESLint (recommended rules plus stricter ones: no unused or undefined names, `const` where possible, `===`, no `eval`) on the page scripts, `server.js` and `tools/` | 0 problems | -| Type check | `npm run typecheck` | TypeScript reads the page scripts as JavaScript (`checkJs`) and reports wrong property names, wrong argument types and similar mistakes | 0 errors | -| Strict type check | `npm run typecheck:strict` | TypeScript `strict` mode, the closest match to PHPStan level 10: no implicit `any`, null checks, strict function types | no **new** errors | +| Shared code in sync | `npm run check:sync` | The shared core in `3d.html` matches `index.html` | in sync | +| Lint | `npm run lint` | ESLint (recommended rules plus stricter ones: no unused or undefined names, `const` where possible, `===`, no `eval`) on the page scripts, `server.js`, `tools/` and `tests/` | 0 problems | +| Type check | `npm run typecheck` | TypeScript reads the page scripts as JavaScript (`checkJs`), and checks `server.js`, `tools/` and `tests/` in **strict** mode | 0 errors | +| Strict type check | `npm run typecheck:strict` | TypeScript `strict` mode on the page scripts, the closest match to PHPStan level 10 (no implicit `any`, null checks, strict function types) | **shared core: 0 errors**; rest: no new errors | +| Unit tests | `npm test` | Node's built-in test runner: every example parses into a valid graph, each diagram type has behaviour tests, a snapshot of the parsed output catches any change, the diagram styles are complete, and `server.js` serves pages, assets and `/embed` correctly and refuses private files | all pass | -How the strict level works, like a PHPStan baseline: -- The known strict-mode errors are listed in [`tsc-baseline.json`](tsc-baseline.json), counted per file and message, not per line. -- Any error that is not in the baseline fails the check. -- After you fix some, run `npm run typecheck:baseline` so the baseline shrinks. Never grow it to hide a real problem. +**What "shared core" means.** Both pages are single files, so the code they share is one block, copied from `index.html` into `3d.html` by `python3 tools/sync-parser.py`. It covers: +- the helpers, the markdown reader and all 23 Mermaid parsers; +- the layout; +- the diagram styles and the settings / share / steps UI. -Most of the remaining errors are function parameters without type information. Adding JSDoc types (`/** @param {string} label */`) as code is touched brings the baseline down. +This block is fully typed with JSDoc (`FxNode`, `FxLink`, `Step`, `Graph`, `DiagramStyle`…) and must stay at zero strict-mode errors. That rule can't be baselined. + +**The rest** (2D/3D rendering, events, snapshot) uses a PHPStan-style baseline: +- [`tsc-baseline.json`](tsc-baseline.json) lists the known strict-mode errors, counted per file and message, not per line. Any error not in the list fails. +- After you fix some, run `npm run typecheck:baseline` so the list shrinks; never grow it to hide a real problem. +- It went from 1,995 to 809 when the core was typed. + +**Tests** load the shared core straight out of `index.html` into a Node VM ([`tests/load-core.mjs`](tests/load-core.mjs)), so the pages stay standalone and the logic is still testable. If you change the parser output on purpose, run `npm run test:update` and review the diff of `tests/parser.snapshot.json`. The page code lives inside the HTML files, so [`tools/extract-scripts.mjs`](tools/extract-scripts.mjs) first copies each script into `.check/*.js`. It keeps the same line numbers, so every reported line matches `index.html` or `3d.html`. ```bash -npm install # dev tools only: eslint, typescript, @types/three +npm install # dev tools only: eslint, typescript, @types/three, @types/node npm run check ``` diff --git a/docs/images/diagram-styles.png b/docs/images/diagram-styles.png index 323452f..d9bf7c6 100644 Binary files a/docs/images/diagram-styles.png and b/docs/images/diagram-styles.png differ diff --git a/eslint.config.mjs b/eslint.config.mjs index 4f337e8..d1dcd94 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -35,7 +35,7 @@ export default [ { files: ['.check/index.js'], rules: { 'no-implicit-globals': 'off' } }, { files: ['.check/3d.js'], languageOptions: { sourceType: 'module' } }, { - files: ['server.js', 'tools/**/*.mjs', 'eslint.config.mjs'], + files: ['server.js', 'tools/**/*.mjs', 'tests/**/*.mjs', 'eslint.config.mjs'], languageOptions: { ecmaVersion: 2023, globals: { ...globals.node } }, }, { files: ['server.js'], languageOptions: { sourceType: 'commonjs' } }, diff --git a/index.html b/index.html index 128f5d8..2d9625d 100644 --- a/index.html +++ b/index.html @@ -48,7 +48,7 @@ --d-mono:ui-monospace,"SF Mono",Menlo,Consolas,monospace; --d-bg:#f5f0e6; --d-bg2:#fbf7ee; --d-ink:#1f2430; --d-accent:#ee5a3a; --d-accent-fg:#fff; --d-plate:#fffdf8; --d-plate-fg:#1f2430; --d-plate-bd:#1f2430; --d-on:#1f2430; --d-on-fg:#f5f0e6; --d-muted:#6b6f7b; - --d-zone:rgba(31,36,48,.035); --d-zone-bd:rgba(31,36,48,.45); --d-chip:rgba(245,240,230,.75); --d-lab-shadow:rgba(31,36,48,.2); + --d-zone:rgba(31,36,48,.035); --d-zone-bd:rgba(31,36,48,.45); --d-chip:rgba(245,240,230,.75); --d-lab-shadow:rgba(31,36,48,.2); --d-lab:var(--d-sans); } *{box-sizing:border-box} [hidden]{display:none!important} @@ -282,7 +282,7 @@ .tail{fill:var(--d-plate);stroke:var(--d-plate-bd);stroke-width:1.4;stroke-linejoin:round} .stem{stroke:var(--d-plate-bd);stroke-width:1.2;stroke-dasharray:2 3} .node.active .tail{fill:var(--d-on);stroke:var(--d-on)} -.plate text{font:600 12px var(--d-sans);fill:var(--d-plate-fg)} +.plate text{font:600 12px var(--d-lab);fill:var(--d-plate-fg)} .node.active .plate rect{fill:var(--d-on);stroke:var(--d-on)} .node.active .plate text{fill:var(--d-on-fg)} .zone polygon{fill:var(--d-zone);stroke:var(--d-zone-bd);stroke-width:1.2;stroke-dasharray:6 5} @@ -926,19 +926,32 @@

    Flow
    Explainer