/* ---------- 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 @@
}
/* ---------- 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 @@
}
/* ---------- 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 @@
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 @@
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 '
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.
-
+
| 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 @@