Skip to content

TsukiNi22/ai-utils / skills/docs/html-doc

html-doc

Verified

FileKindSize
SKILL.mdskill md26.5 KB
requires.txtmarkdown11 B
scripts/build_explorer.mjsscript1.9 KB
scripts/build_graph.mjsscript5.7 KB
scripts/sync_nav.pyexecutablescript665 B
templates/graph.htmlother311.8 KB
templates/technical.htmlother57.5 KB
templates/user.htmlother61.0 KB

templates/graph.html

View on GitHub
<!doctype html>
<html lang="en" data-page="graph" data-storage-key="{{STORAGE_KEY}}" data-repo="{{GITHUB_REPO}}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>{{PROJECT}} · Project graph</title>
<style>

:root {
  color-scheme: light; /* the fields, the scrollbars and the rest drawn by the browser follow the theme */
  accent-color: var(--accent);
  --bg: #efede8;
  --surface: #f7f5f0;
  --text: #1d1f23;
  --muted: #5d636e;
  --border: #dad6cd;
  --accent: #2f5bd3;
  --accent-soft: #e6ecfb;
  --warn: #a8540a;
  --warn-soft: #fbefe3;
  --ok: #1f7a4a;
  --ok-soft: #e3f4ea;
  --code-bg: #e9e6df;
  --node: #f7f5f0;
  --node-alt: #eef1f8;
  --line: #868c97;
}
@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    color-scheme: dark;
    --bg: #15171b;
    --surface: #1d2025;
    --text: #e6e7ea;
    --muted: #9aa0ab;
    --border: #30343b;
    --accent: #7d9cf0;
    --accent-soft: #232c45;
    --warn: #f0a868;
    --warn-soft: #3a2a1b;
    --ok: #6fcf97;
    --ok-soft: #1b3326;
    --code-bg: #24272d;
    --node: #23262c;
    --node-alt: #283043;
    --line: #747a85;
  }
}
:root[data-theme="dark"] {
  color-scheme: dark;
  --bg: #15171b;
  --surface: #1d2025;
  --text: #e6e7ea;
  --muted: #9aa0ab;
  --border: #30343b;
  --accent: #7d9cf0;
  --accent-soft: #232c45;
  --warn: #f0a868;
  --warn-soft: #3a2a1b;
  --ok: #6fcf97;
  --ok-soft: #1b3326;
  --code-bg: #24272d;
  --node: #23262c;
  --node-alt: #283043;
  --line: #747a85;
}
/* scrollbars: thin, a transparent track, a rounded thumb in the theme (never the wide grey bar of the browser on hover) */
* { scrollbar-width: thin; scrollbar-color: color-mix(in srgb, var(--line) 55%, transparent) transparent; }
*:hover { scrollbar-color: var(--line) transparent; }
::-webkit-scrollbar { width: 10px; height: 10px; }
::-webkit-scrollbar-track, ::-webkit-scrollbar-corner { background: transparent; }
::-webkit-scrollbar-thumb { background: color-mix(in srgb, var(--line) 55%, transparent); background-clip: padding-box; border: 3px solid transparent; border-radius: 10px; }
::-webkit-scrollbar-thumb:hover { background: var(--line); background-clip: padding-box; border-width: 2px; }
* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body {
  margin: 0;
  background: var(--bg);
  color: var(--text);
  font: 16px/1.6 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
.topbar {
  position: sticky; top: 0; z-index: 20;
  display: flex; align-items: center; gap: 18px;
  height: 56px; padding: 0 20px;
  background: var(--surface);
  border-bottom: 1px solid var(--border);
}
.tabs { display: flex; gap: 4px; margin-left: 8px; overflow-x: auto; }
.tabs[hidden] { display: none; }
.tabs a {
  padding: 6px 12px; border-radius: 6px;
  color: var(--muted); text-decoration: none; font-size: 14px; white-space: nowrap;
}
.tabs a:hover { color: var(--text); background: var(--code-bg); }
.tabs a.current { color: var(--accent); background: var(--accent-soft); font-weight: 600; }
.topbar .spacer { flex: 1; }
.icon-btn {
  display: grid; place-items: center;
  width: 36px; height: 36px; padding: 0;
  background: var(--surface); color: var(--text);
  border: 1px solid var(--border); border-radius: 50%;
  cursor: pointer; text-decoration: none;
  transition: border-color .15s, color .15s;
}
.icon-btn:hover { color: var(--accent); border-color: var(--accent); }
.icon-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.icon-btn svg { width: 18px; height: 18px; }
body { overflow: hidden; }
code { font: 0.9em ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: var(--text); background: var(--code-bg); padding: 1px 5px; border-radius: 4px; overflow-wrap: anywhere; }
.panel, .details, .helpcard, .node-tip, .tip { overflow-wrap: break-word; }
input { text-overflow: ellipsis; }
input::placeholder { color: var(--muted); opacity: 1; }
input:focus-visible, select:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
.graph-shell {
  display: grid;
  grid-template-columns: 330px minmax(0, 1fr);
  height: calc(100vh - 56px);
  height: calc(100dvh - 56px);
}
.panel {
  overflow-y: auto;
  background: var(--surface);
  border-right: 1px solid var(--border);
  padding: 18px 18px 40px;
  font-size: 14px;
}
.panel h1 { font-size: 20px; margin: 0 0 6px; }
.panel p { margin: 0 0 10px; }
.muted { color: var(--muted); }
.small { font-size: 12.5px; }
.ps { border-top: 1px solid var(--border); padding: 14px 0 4px; margin-top: 12px; }
.ps h4 {
  margin: 0 0 8px; font-size: 12px; color: var(--muted);
  text-transform: uppercase; letter-spacing: .06em;
  display: flex; flex-wrap: wrap; align-items: center; gap: 6px;
}
.ps h4 .count { text-transform: none; letter-spacing: 0; font-weight: 500; }
.ps h4 .mini-group { margin-left: auto; display: inline-flex; gap: 4px; }
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-bottom: 10px; }
.btn {
  display: inline-flex; align-items: center; gap: 6px;
  padding: 6px 11px; border-radius: 7px;
  border: 1px solid var(--border); background: var(--surface); color: var(--text);
  font: inherit; font-size: 13px; cursor: pointer;
}
.btn:hover { border-color: var(--accent); color: var(--accent); }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--surface); }
.btn.primary:hover { filter: brightness(1.08); color: var(--surface); }
.btn:disabled { opacity: .55; cursor: progress; }
.btn svg { width: 15px; height: 15px; }
.btn.spin svg { animation: spin 1s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.mini { border: 1px solid var(--border); background: var(--surface); color: var(--muted); border-radius: 6px; padding: 3px 9px; font: 600 11.5px system-ui, sans-serif; text-transform: none; letter-spacing: 0; cursor: pointer; }
.mini:hover { color: var(--accent); border-color: var(--accent); }
.seg { display: inline-flex; border: 1px solid var(--border); border-radius: 7px; overflow: hidden; }
.seg button { border: 0; background: var(--surface); color: var(--muted); padding: 6px 12px; font: inherit; font-size: 13px; cursor: pointer; }
.seg button.active { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
input[type="search"], input[type="text"], select {
  width: 100%; padding: 7px 10px; border-radius: 7px;
  border: 1px solid var(--border); background: var(--bg); color: var(--text); font: inherit; font-size: 13.5px;
}
select { width: auto; }
.status {
  border-radius: 8px; padding: 9px 11px; margin: 10px 0;
  background: var(--code-bg); font-size: 12.5px; line-height: 1.45;
  border-left: 3px solid var(--line);
}
.status.ok { background: var(--ok-soft); border-left-color: var(--ok); }
.status.warn { background: var(--warn-soft); border-left-color: var(--warn); }
.status.busy { background: var(--accent-soft); border-left-color: var(--accent); }
.status code { font-size: 12px; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; }
.chip {
  display: inline-flex; align-items: center; gap: 6px;
  padding: 4px 9px; border-radius: 999px;
  border: 1px solid var(--border); background: var(--surface); color: var(--text);
  font: inherit; font-size: 12.5px; cursor: pointer; user-select: none;
}
.chip .dot { width: 9px; height: 9px; border-radius: 50%; flex: none; }
.chip .n { color: var(--muted); font-size: 11.5px; }
.chip.off { color: var(--muted); border-color: color-mix(in srgb, var(--border) 55%, transparent); }
.chip.off .dot { background: transparent !important; outline: 1.5px solid var(--line); }
.chip:hover { border-color: var(--accent); }
.opt { display: flex; align-items: center; gap: 8px; margin: 6px 0; cursor: pointer; }
.stage { position: relative; min-width: 0; overflow: hidden; background: var(--bg); }
#graph { position: absolute; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; touch-action: none; }
#graph.dragging { cursor: grabbing; }
#graph.pointer { cursor: pointer; }
.hint {
  position: absolute; left: 50%; bottom: 16px; transform: translateX(-50%);
  background: var(--surface); border: 1px solid var(--border); border-radius: 16px;
  padding: 5px 12px; font-size: 12px; color: var(--muted); pointer-events: none; text-align: center;
  width: max-content; max-width: min(760px, calc(100% - 360px)); /* room for the axes (left) and the 3D style (right) */
}
.flowbar { position: absolute; left: 14px; top: 14px; display: flex; flex-wrap: wrap; gap: 8px; align-items: center; max-width: calc(100% - 28px); }
.flowbar[hidden], .flowbar select[hidden] { display: none; }
.flowbar .seg { box-shadow: 0 4px 14px rgba(0, 0, 0, .12); }
.flowbar select { max-width: 260px; }
.repo-bar { display: flex; gap: 8px; margin-bottom: 12px; align-items: stretch; }
.repo-bar .btn { padding: 0 14px; flex: none; }
.repo-bar[hidden] { display: none; }
.repo-bar input { flex: 1; min-width: 0; }
.repo-card input { width: 100%; margin: 6px 0 8px; }
.repo-err { color: var(--warn); font-size: 13px; margin-bottom: 6px; }
.repo-err[hidden] { display: none; }
.repo-ex { font-size: 12.5px; color: var(--muted); display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-bottom: 10px; }
.repo-ex button { border: 1px solid var(--border); background: var(--code-bg); color: var(--text); border-radius: 6px; padding: 2px 8px; font: inherit; cursor: pointer; }
.repo-ex button:hover { border-color: var(--accent); color: var(--accent); }
.repo-ex button small { margin-left: 6px; color: var(--muted); font-size: 11px; }
.repo-actions { display: flex; justify-content: flex-end; margin: 14px 0 14px; }
.repo-actions .btn { padding: 8px 20px; }
.brand .ver:empty { display: none; }
.controls-btn {
  position: absolute; left: 14px; bottom: 14px; width: 34px; height: 34px; border-radius: 50%;
  border: 1px solid var(--border); background: var(--surface); color: var(--text); font: 700 15px system-ui, sans-serif;
  cursor: pointer; box-shadow: 0 4px 14px rgba(0, 0, 0, .12);
}
.controls-btn:hover { border-color: var(--accent); color: var(--accent); }
.helpcard.wide { width: min(620px, 100%); }
.ctl-list { display: grid; gap: 6px; margin-top: 6px; }
.ctl { display: grid; grid-template-columns: 64px minmax(0, 1fr); gap: 12px; align-items: center; padding: 6px 8px; border-radius: 8px; background: var(--code-bg); }
.ctl svg { width: 64px; height: 44px; margin: 0; background: none; border: 0; }
.ctl b { display: block; font-size: 13.5px; }
.ctl span { color: var(--muted); font-size: 13px; }
.style3d { position: absolute; right: 14px; bottom: 14px; box-shadow: 0 4px 14px rgba(0, 0, 0, .12); }
.style3d[hidden] { display: none; }
@media (max-width: 760px) { .hint { bottom: 60px; max-width: calc(100% - 32px); } }
.details {
  position: absolute; z-index: 3; top: var(--details-top, 14px); right: 14px; width: min(340px, calc(100% - 28px)); max-height: calc(100% - var(--details-top, 14px) - 14px); overflow-y: auto; /* over the buttons of the stage, it closes by its own; under the bar of the diagrams when it would cover it */
  background: var(--surface); border: 1px solid var(--border); border-radius: 10px;
  padding: 16px 18px; font-size: 13.5px; box-shadow: 0 8px 28px rgba(0, 0, 0, .14);
}
.details h3 { margin: 4px 0 8px; padding-right: 22px; font-size: 17px; overflow-wrap: anywhere; }
.details .close { position: absolute; top: 8px; right: 10px; border: 0; background: none; color: var(--muted); font-size: 22px; cursor: pointer; }
.details .kind { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .05em; }
.details dl { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 3px 10px; margin: 0 0 10px; }
.details dt { color: var(--muted); }
.details dd { margin: 0; overflow-wrap: anywhere; }
.details h5 { margin: 12px 0 4px; font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .05em; }
.details ul { list-style: none; padding: 0; margin: 0; }
.details li a { display: flex; align-items: center; gap: 6px; padding: 2px 0; color: var(--text); text-decoration: none; cursor: pointer; overflow-wrap: anywhere; }
.details li a:hover { color: var(--accent); }
.details li .dot { width: 8px; height: 8px; border-radius: 50%; flex: none; }
.brand { display: flex; align-items: center; gap: 10px; color: var(--text); text-decoration: none; font-weight: 700; white-space: nowrap; }
.brand .logo { width: 26px; height: 26px; flex: none; color: var(--accent); object-fit: contain; }
.brand { min-width: 0; }
.brand .repo-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
.brand .ver { font-size: 12px; color: var(--muted); font-weight: 500; padding: 2px 6px; border: 1px solid var(--border); border-radius: 6px; }
.page-eyebrow { font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: .1em; color: var(--accent); margin-bottom: 4px; }
/* Legends: 2 columns, swatch (dot for nodes / groups, line for relations), count on the right, off = faded */
.legend { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); grid-auto-flow: row dense; gap: 2px 8px; }
.legend .lg {
  display: flex; align-items: center; gap: 7px; width: 100%; min-width: 0; padding: 3px 5px;
  border: 0; border-radius: 6px; background: none; color: var(--text); font: inherit; font-size: 12.5px;
  text-align: left; cursor: pointer; user-select: none;
}
.legend .lg:hover { background: var(--code-bg); }
.legend .lg.off { color: var(--muted); }
.legend .lg.off .sw { opacity: .3; }
.legend .lg .sw { width: 11px; height: 11px; border-radius: 50%; flex: 0 0 11px; box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .15); }
.legend .lg .sw.line { width: 16px; height: 3px; flex-basis: 16px; border-radius: 2px; box-shadow: none; }
.legend .lg .t { min-width: 0; line-height: 1.3; overflow-wrap: anywhere; }
.legend .lg.wide { grid-column: 1 / -1; }
.legend .lg .n { margin-left: auto; color: var(--muted); font-size: 11px; font-variant-numeric: tabular-nums; }
/* Hover card of a node: kind (colour of the node), name, path */
.node-tip {
  position: absolute; z-index: 15; max-width: min(360px, calc(100% - 24px)); pointer-events: none;
  background: var(--surface); border: 1px solid var(--border); border-radius: 8px; padding: 7px 11px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, .22); font-size: 12.5px; line-height: 1.35;
}
.node-tip[hidden] { display: none; }
.node-tip .k { font-size: 10.5px; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; }
.node-tip .t { font-weight: 600; color: var(--text); overflow-wrap: anywhere; }
.node-tip .p { color: var(--muted); font-size: 12px; overflow-wrap: anywhere; }
.tip {
  position: fixed; z-index: 30; max-width: min(280px, calc(100vw - 16px)); pointer-events: none;
  background: var(--text); color: var(--bg);
  border-radius: 6px; padding: 6px 9px; font-size: 12.5px; line-height: 1.4;
  box-shadow: 0 6px 18px rgba(0, 0, 0, .18);
}
.tip small { display: block; opacity: .7; margin-top: 3px; font-size: 11px; }
.helpcard-back { position: fixed; inset: 0; z-index: 40; display: grid; place-items: center; background: rgba(0, 0, 0, .35); padding: 16px; }
.helpcard-back[hidden] { display: none; }
.helpcard {
  position: relative; width: min(440px, 100%); max-height: calc(100vh - 32px); max-height: calc(100dvh - 32px); overflow-y: auto;
  background: var(--surface); color: var(--text);
  border: 1px solid var(--border); border-radius: 10px; padding: 18px 20px;
  box-shadow: 0 14px 40px rgba(0, 0, 0, .25); font-size: 14px;
}
.helpcard h3 { margin: 4px 0 8px; padding-right: 22px; font-size: 18px; }
.helpcard p { margin: 0 0 8px; }
.helpcard .kind { font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .05em; }
.helpcard .close { position: absolute; top: 8px; right: 10px; border: 0; background: none; color: var(--muted); font-size: 22px; cursor: pointer; }
.helpcard svg { width: 100%; height: auto; display: block; margin-top: 8px; background: var(--bg); border: 1px solid var(--border); border-radius: 8px; }
.helpcard .ctl svg { margin: 0; } /* centered on its row */
.helpcard svg .n-lbl { fill: var(--text); font: 11px system-ui, sans-serif; }
.helpcard svg .e-lbl { fill: var(--muted); font: 10.5px system-ui, sans-serif; paint-order: stroke; stroke: var(--bg); stroke-width: 3px; stroke-linejoin: round; }
[data-help] { user-select: none; -webkit-user-select: none; }
button[data-help], .chip[data-help], .lg[data-help], label[data-help], select[data-help] { cursor: pointer; }
input[type="search"][data-help] { cursor: text; user-select: text; -webkit-user-select: text; }
/* Diagram mode: the filters of the 2D / 3D graph don't apply, they are greyed */
.in-flow .graph-only { opacity: .38; filter: grayscale(.7); pointer-events: none; }
.panel-toggle { display: none; position: absolute; top: 12px; left: 12px; z-index: 5; }
.panel-close { display: none; position: sticky; top: 0; z-index: 1; float: right; width: 34px; height: 34px; padding: 0; place-items: center; border: 1px solid var(--border); border-radius: 50%; background: var(--surface); color: var(--text); font: 20px/1 system-ui, sans-serif; cursor: pointer; }
.panel-close:hover { border-color: var(--accent); color: var(--accent); }
.help p { font-size: 12.5px; color: var(--muted); }
@media (max-width: 860px) {
  .topbar { gap: 10px; padding: 0 12px; }
  .brand .ver { display: none; }
  .graph-shell { grid-template-columns: 1fr; }
  .panel { position: absolute; z-index: 6; top: 56px; bottom: 0; left: 0; width: min(340px, 88vw); transform: translateX(-100%); transition: transform .2s; box-shadow: 0 8px 28px rgba(0, 0, 0, .2); }
  .panel:not(.open) { box-shadow: none; }
  .panel.open { transform: none; }
  .panel-toggle { display: inline-flex; }
  .panel-close { display: grid; }
  .flowbar { top: 60px; }
  .details { left: 12px; right: 12px; width: auto; top: auto; bottom: 12px; max-height: 50%; }
}
/* Language switch (EN / FR pill) */
.lang-switch {
  display: inline-flex; align-items: center; gap: 2px; padding: 3px;
  border: 1.5px solid var(--border); border-radius: 999px; background: var(--surface);
}
.lang-switch button {
  border: 0; background: none; color: var(--text); cursor: pointer;
  font: 600 12.5px system-ui, sans-serif; letter-spacing: .03em;
  padding: 4px 11px; border-radius: 999px; transition: background .2s, color .2s;
}
.lang-switch button.on { background: var(--accent); color: var(--surface); }
.lang-switch button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
/* Theme switch: blue track + sun (light), black track + moon and stars (dark) */
.theme-switch {
  position: relative; width: 58px; height: 30px; flex: none; padding: 0; border: 0; border-radius: 999px;
  background: #2196f3; cursor: pointer; transition: background .3s;
}
.theme-switch:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.theme-switch .knob {
  position: absolute; top: 3px; left: 3px; width: 24px; height: 24px; border-radius: 50%;
  display: grid; place-items: center; transition: transform .3s, background .3s;
}
.theme-switch .knob svg { width: 22px; height: 22px; }
.theme-switch .sun { display: block; }
.theme-switch .moon, .theme-switch .stars { display: none; }
.theme-switch .stars { position: absolute; inset: 0; }
.theme-switch .stars i { position: absolute; width: 2px; height: 2px; border-radius: 50%; background: #fff; }
.theme-switch .stars i:nth-child(1) { left: 9px; top: 9px; }
.theme-switch .stars i:nth-child(2) { left: 16px; top: 18px; width: 1.5px; height: 1.5px; }
.theme-switch .stars i:nth-child(3) { left: 21px; top: 8px; width: 1.5px; height: 1.5px; }
@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) .theme-switch { background: #0b0b0d; box-shadow: inset 0 0 0 1px #2a2c31; }
  :root:not([data-theme="light"]) .theme-switch .knob { transform: translateX(28px); background: #ffffff; }
  :root:not([data-theme="light"]) .theme-switch .sun { display: none; }
  :root:not([data-theme="light"]) .theme-switch .moon, :root:not([data-theme="light"]) .theme-switch .stars { display: block; }
}
:root[data-theme="dark"] .theme-switch { background: #0b0b0d; box-shadow: inset 0 0 0 1px #2a2c31; }
:root[data-theme="dark"] .theme-switch .knob { transform: translateX(28px); background: #ffffff; }
:root[data-theme="dark"] .theme-switch .sun { display: none; }
:root[data-theme="dark"] .theme-switch .moon, :root[data-theme="dark"] .theme-switch .stars { display: block; }
/* Bilingual content: only the active language is shown */
:root[lang="en"] [data-lang="fr"], :root[lang="fr"] [data-lang="en"] { display: none !important; }
.topbar .icon-btn, .topbar .lang-switch, .topbar .theme-switch { flex: none; }
.topbar .tabs { min-width: 0; scrollbar-width: none; }
.topbar .top-actions { margin-left: auto; } /* on the right even when no tab or spacer pushes them (a single page on a small screen) */
@media (max-width: 860px) {
  .topbar .spacer { display: none; }
  .topbar .tabs { flex: 1 1 0; min-width: 72px; }
  .topbar .icon-btn { width: 32px; height: 32px; }
}
@media (max-width: 480px) {
  .topbar { gap: 8px; padding: 0 10px; }
  .topbar a.icon-btn[href] { display: none; } /* GitHub link: also in the footer / graph panel */
  .lang-switch button { padding: 4px 9px; }
}
/* ---------- No scroll beyond the page ---------- */
html, body { overscroll-behavior: none; }
/* ---------- Top right actions: same height, grouped, divider ---------- */
.top-actions { display: flex; align-items: center; gap: 8px; flex: none; }
.top-actions .divider { width: 1px; height: 22px; background: var(--border); margin: 0 2px; }
.top-actions .icon-btn { width: 34px; height: 34px; }
.top-actions .lang-switch { height: 34px; padding: 3px; background: var(--code-bg); border: 1px solid var(--border); }
.top-actions .lang-switch button { height: 26px; padding: 0 10px; font-size: 12px; }
.top-actions .theme-switch { width: 56px; height: 30px; border: 1px solid transparent; }
.top-actions .theme-switch .knob { top: 2px; left: 2px; }
@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) .top-actions .theme-switch { border-color: var(--border); box-shadow: none; }
  :root:not([data-theme="light"]) .top-actions .theme-switch .knob { transform: translateX(26px); }
}
:root[data-theme="dark"] .top-actions .theme-switch { border-color: var(--border); box-shadow: none; }
:root[data-theme="dark"] .top-actions .theme-switch .knob { transform: translateX(26px); }
@media (max-width: 480px) { .top-actions .divider { display: none; } }
/* Responsive: notches, touch targets, short screens */
@supports (padding: max(0px)) { .topbar { padding-left: max(12px, env(safe-area-inset-left)); padding-right: max(12px, env(safe-area-inset-right)); } }
html { -webkit-text-size-adjust: 100%; text-size-adjust: 100%; }
@media (pointer: coarse) {
  .icon-btn { width: 44px; height: 44px; }
  .btn, .seg button, .chip, .legend .lg, .mini { min-height: 40px; }
  .controls-btn, .panel-close { width: 44px; height: 44px; }
  .details .close, .helpcard .close { width: 44px; height: 44px; font-size: 26px; }
  input, select, textarea { font-size: 16px; } /* no zoom of the page on focus (iOS) */
}
@media (max-width: 860px) {
  .panel { padding-bottom: max(16px, env(safe-area-inset-bottom)); overflow-y: auto; }
  .details { bottom: max(12px, env(safe-area-inset-bottom)); }
  .flowbar select { max-width: 46vw; }
}
@media (max-width: 480px) {
  .panel { width: 100vw; }
  .topbar .icon-btn[href] { display: none; }
}
@media (max-height: 480px) and (orientation: landscape) { .topbar { height: 48px; } .panel { top: 48px; } .graph-shell { height: calc(100vh - 48px); height: calc(100dvh - 48px); } }
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { transition-duration: .01ms !important; animation-duration: .01ms !important; } }
@media (forced-colors: active) {
  .theme-switch, .lang-switch, .icon-btn { border: 1px solid ButtonText; }
  .tabs a.current, .seg button.active, .lang-switch button.on { outline: 2px solid Highlight; }
  .legend .lg .sw, .chip .dot, .details .dot, .node-tip .k { forced-color-adjust: none; } /* a colour that means something */
}
@media print {
  :root, :root[data-theme="dark"], :root:not([data-theme="light"]) {
    color-scheme: light;
    --bg: #ffffff; --surface: #ffffff; --text: #1d1f23; --muted: #5d636e; --border: #dad6cd; --accent: #2f5bd3; --accent-soft: #e6ecfb;
    --warn: #a8540a; --warn-soft: #fbefe3; --ok: #1f7a4a; --ok-soft: #e3f4ea; --code-bg: #e9e6df; --node: #f7f5f0; --node-alt: #eef1f8; --line: #868c97;
  }
  .topbar, .panel, .panel-toggle, .controls-btn, .flowbar, .style3d, .hint { display: none !important; }
  .graph-shell { display: block; }
  .stage { height: 100%; }
}
</style>
</head>
<body>
<header class="topbar">
  <a class="brand" href="index.html"><svg class="logo" viewBox="0 0 32 32" fill="none" aria-hidden="true"><!-- default logo: replace with the project logo (inline SVG, currentColor) --><rect x="4" y="4" width="18" height="22" rx="3" fill="currentColor" opacity=".35"/><rect x="9" y="7" width="18" height="22" rx="3" fill="currentColor"/><path d="M13 14h10M13 18h10M13 22h6" stroke="var(--surface)" stroke-width="2" stroke-linecap="round"/></svg><span class="repo-name">{{PROJECT}}</span><span class="ver repo-version">{{VERSION}}</span></a>
  <nav class="tabs" aria-label="Pages">
    <!-- PAGES: keep only the pages that exist, the first one is index.html -->
    <a href="index.html" data-i18n>Guide</a>
    <a href="technical.html" data-i18n>Technical</a>
    <a href="graph.html" class="current" aria-current="page" data-i18n>Graph</a>
  </nav>
  <span class="spacer"></span>
  <div class="top-actions">
  <a class="icon-btn repo-link" href="{{REPO_URL}}" title="GitHub repository" data-i18n-title aria-label="GitHub repository" data-i18n-aria-label>
    <svg viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38v-1.33c-2.23.48-2.7-1.07-2.7-1.07-.36-.93-.89-1.17-.89-1.17-.73-.5.06-.49.06-.49.8.06 1.23.83 1.23.83.71 1.23 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.6 7.6 0 0 1 4 0c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48v2.2c0 .21.15.46.55.38A8 8 0 0 0 16 8c0-4.42-3.58-8-8-8Z"/></svg>
  </a>
  <span class="divider" aria-hidden="true"></span>
  <div class="lang-switch" role="group" aria-label="Language">
    <button type="button" data-set-lang="en" class="on">EN</button>
    <button type="button" data-set-lang="fr">FR</button>
  </div>
  <button class="theme-switch" type="button" id="themeToggle" role="switch" aria-checked="false" aria-label="Toggle theme" data-i18n-aria-label title="Toggle theme" data-i18n-title>
    <span class="stars" aria-hidden="true"><i></i><i></i><i></i></span>
    <span class="knob" aria-hidden="true">
      <svg class="sun" viewBox="0 0 24 24" fill="#ffffff"><circle cx="12" cy="12" r="5.2"/><g stroke="#ffffff" stroke-width="2.2" stroke-linecap="round"><path d="M12 1.8v2.6M12 19.6v2.6M1.8 12h2.6M19.6 12h2.6M4.8 4.8l1.8 1.8M17.4 17.4l1.8 1.8M4.8 19.2l1.8-1.8M17.4 6.6l1.8-1.8"/></g></svg>
      <svg class="moon" viewBox="0 0 24 24"><path d="M15.6 4.2a8 8 0 1 0 4.2 11.6A7 7 0 0 1 15.6 4.2z" fill="#f6c343"/></svg>
    </span>
  </button>
  </div>
</header>

<div class="graph-shell">
  <aside class="panel" id="panel" aria-label="Graph controls" data-i18n-aria-label>
    <button class="panel-close" id="panelClose" type="button" aria-label="Hide the controls" data-i18n-aria-label>×</button>
    <div class="page-eyebrow" data-i18n>Architecture</div>
    <h1 data-i18n>Project graph</h1>
    <p class="muted small" data-i18n>Files, classes, functions, tests, build targets (CMake, packages) and external dependencies of <code class="repo-name">{{PROJECT}}</code>, extracted from the sources. Click a node to inspect it, drag to move, scroll to zoom.</p>

    <form class="repo-bar" id="repoBar" hidden>
      <input id="repoInput" type="text" spellcheck="false" autocomplete="off" aria-label="Repository" data-i18n-aria-label placeholder="github.com/owner/repo" data-help="repo">
      <button class="btn" type="submit" data-i18n>Open</button>
    </form>
    <div class="status" id="status">Loading…</div>
    <div class="row">
      <button class="btn primary" id="update" type="button" data-help="update">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-2.64-6.36"/><path d="M21 3v6h-6"/></svg>
        <span data-i18n>Update</span>
      </button>
    </div>

    <div class="ps">
      <div class="row">
        <div class="seg" role="group" aria-label="Rendu">
          <button id="mode2d" class="active" type="button" data-help="mode2d">2D</button>
          <button id="mode3d" type="button" data-help="mode3d">3D</button>
          <button id="modeFlow" type="button" data-help="modeFlow" data-i18n>Diagram</button>
        </div>
        <button class="btn" id="fit" type="button" data-help="fit" data-i18n>Fit</button>
        <button class="btn" id="pause" type="button" data-help="pause">Freeze</button>
      </div>
      <input id="search" data-help="search" type="search" placeholder="Search a node… (e.g. Server, parse, .hpp)" data-i18n-placeholder autocomplete="off">
    </div>

    <div class="ps graph-only">
      <h4 data-i18n>Views</h4>
      <div class="chips" id="presets">
        <button class="chip" type="button" data-preset="overview" data-help="preset:overview" data-i18n>Overview</button>
        <button class="chip" type="button" data-preset="files" data-help="preset:files" data-i18n>Files &amp; includes</button>
        <button class="chip" type="button" data-preset="classes" data-help="preset:classes" data-i18n>Classes &amp; inheritance</button>
        <button class="chip" type="button" data-preset="members" data-help="preset:members" data-i18n>Classes &amp; methods</button>
        <button class="chip" type="button" data-preset="tests" data-help="preset:tests" data-i18n>Tests</button>
        <button class="chip" type="button" data-preset="build" data-help="preset:build" data-i18n>Build</button>
        <button class="chip" type="button" data-preset="all" data-help="preset:all" data-i18n>All</button>
      </div>
    </div>

    <div class="ps graph-only">
      <h4><span data-i18n>Categories</span> <span class="count muted" id="nodeCount"></span><span class="mini-group"><button class="mini" type="button" data-all="kinds" data-i18n>all</button><button class="mini" type="button" data-none="kinds" data-i18n>none</button></span></h4>
      <div class="legend" id="kinds"></div>
    </div>

    <div class="ps graph-only">
      <h4><span data-i18n>Groups</span> <span class="count muted" id="groupCount"></span><span class="mini-group"><button class="mini" type="button" data-all="groups" data-i18n>all</button><button class="mini" type="button" data-none="groups" data-i18n>none</button></span></h4>
      <div class="legend" id="groups"></div>
    </div>

    <div class="ps graph-only">
      <h4><span data-i18n>Relations</span> <span class="count muted" id="linkCount"></span><span class="mini-group"><button class="mini" type="button" data-all="links" data-i18n>all</button><button class="mini" type="button" data-none="links" data-i18n>none</button></span></h4>
      <div class="legend" id="linkKinds"></div>
    </div>

    <div class="ps">
      <h4 data-i18n>Options</h4>
      <label class="opt graph-only" data-help="colorBy"><span data-i18n>Color by</span>
        <select id="colorBy"><option value="kind" data-i18n>category</option><option value="group" data-i18n>group</option></select>
      </label>
      <label class="opt graph-only" data-help="cluster"><input type="checkbox" id="cluster"> <span data-i18n>Cluster the nodes of a group</span></label>
      <label class="opt graph-only" data-help="labels"><input type="checkbox" id="labels" checked> <span data-i18n>Show names</span></label>
      <label class="opt graph-only" data-help="particles"><input type="checkbox" id="particles"> <span data-i18n>Animate the direction of the relations</span></label>
      <label class="opt graph-only" data-help="isolate"><input type="checkbox" id="isolate"> <span data-i18n>Isolate the selection (neighbours only)</span></label>
    </div>

    <div class="ps help">
      <h4 data-i18n>Reading</h4>
      <p data-i18n>Arrows go from the dependent to the dependency: <em>file → included / imported file</em>, <em>class → base class</em>, <em>source → build target / package</em>, <em>target → linked library</em>, <em>test → tested class</em>. The size of a node grows with its number of relations.</p>
      <p data-i18n>The embedded graph comes from the commit shown above; "Update" (run once at load) fetches the last version of the GitHub repository and rebuilds it in the browser. Hover a control for a short help, double click it for a detailed one.</p>
    </div>
  </aside>

  <div class="stage">
    <canvas id="graph" aria-label="Interactive project graph" data-i18n-aria-label></canvas>
    <div class="node-tip" id="nodeTip" hidden><div class="k"></div><div class="t"></div><div class="p"></div></div>
    <button class="btn panel-toggle" id="panelToggle" type="button" aria-label="Show the controls" data-i18n-aria-label><span data-i18n>☰ Controls</span></button>
    <div class="details" id="details" hidden></div>
    <div class="hint" id="hint">Loading the graph…</div>
    <button class="controls-btn" id="controlsBtn" type="button" title="Controls (? or H)" aria-label="Controls" data-i18n-title data-i18n-aria-label>?</button>
    <div class="flowbar" id="flowBar" hidden>
      <div class="seg" id="flowViews" role="group" aria-label="Diagram" data-i18n-aria-label>
        <button type="button" class="active" data-flow="exec" data-help="flow:exec" data-i18n>Execution</button>
        <button type="button" data-flow="inherit" data-help="flow:inherit" data-i18n>Inheritance</button>
        <button type="button" data-flow="flame" data-help="flow:flame" data-i18n>Flame graph</button>
      </div>
      <select id="flowRoot" aria-label="Entry point" data-i18n-aria-label data-help="flowRoot"></select>
    </div>
    <div class="seg style3d" id="style3d" role="group" aria-label="3D style" data-i18n-aria-label hidden>
      <button type="button" class="active" data-style="real" data-help="style3d" data-i18n>Realistic</button>
      <button type="button" data-style="tech" data-help="style3d" data-i18n>Technical</button>
    </div>
  </div>
</div>
<div class="tip" id="tip" role="tooltip" hidden></div>
<div class="helpcard-back" id="repoBack" hidden>
  <form class="helpcard repo-card" id="repoForm" role="dialog" aria-modal="true" aria-labelledby="repoTitle">
    <div class="kind" data-i18n>Graph explorer</div>
    <h3 id="repoTitle" data-i18n>Which repository?</h3>
    <p data-i18n>A public GitHub or GitLab repository: its sources are read by your browser to draw the graph of its files, classes, functions, calls, tests and packages.</p>
    <input id="repoAsk" type="text" spellcheck="false" autocomplete="off" placeholder="github.com/owner/repo · gitlab.com/group/project">
    <div class="repo-err" id="repoErr" hidden></div>
    <div class="repo-ex"><span data-i18n>Examples:</span> <button type="button" data-ex="llvm/llvm-project">llvm/llvm-project<small>C++</small></button> <button type="button" data-ex="curl/curl">curl/curl<small>C</small></button> <button type="button" data-ex="BurntSushi/ripgrep">BurntSushi/ripgrep<small>Rust</small></button> <button type="button" data-ex="psf/requests">psf/requests<small>Python</small></button> <button type="button" data-ex="expressjs/express">expressjs/express<small>JS</small></button> <button type="button" data-ex="spring-projects/spring-petclinic">spring-projects/spring-petclinic<small>Java</small></button> <button type="button" data-ex="spf13/cobra">spf13/cobra<small>Go</small></button> <button type="button" data-ex="https://gitlab.com/gitlab-org/cli">gitlab.com/gitlab-org/cli<small>Go · GitLab</small></button></div>
    <div class="repo-actions"><button class="btn primary" type="submit" data-i18n>Open</button></div>
    <p class="muted small" data-i18n>The link is remembered by this browser until Ctrl + Shift + R (forgets it and reloads the page).</p>
  </form>
</div>
<div class="helpcard-back" id="helpBack" hidden>
  <div class="helpcard" role="dialog" aria-modal="true" aria-labelledby="helpTitle">
    <button class="close" type="button" id="helpClose" aria-label="Close" data-i18n-aria-label>×</button>
    <div class="kind" data-i18n>Help · double click</div>
    <h3 id="helpTitle"></h3>
    <div id="helpBody"></div>
    <div id="helpSvg"></div>
  </div>
</div>

<script id="graph-config" type="application/json">{"project": "{{PROJECT}}", "repo": "{{GITHUB_REPO}}", "branch": "{{BRANCH}}", "storageKey": "{{STORAGE_KEY}}"}</script>
<script id="graph-snapshot" type="application/json">{"meta": {}, "nodes": [], "links": []}</script>
<script>
// French texts of the page (English text -> French text), extend it with the page content
window.DOC_FR = {
  "Guide": "Guide",
  "Technical": "Technique",
  "Graph": "Graphe",
  "GitHub repository": "Dépôt GitHub",
  "Toggle theme": "Changer de thème",
  "Contents": "Sommaire",
  "Language": "Langue",
  "Pages": "Pages",
  "Project graph": "Graphe du projet",
  "The embedded graph comes from the commit shown above; \"Update\" (run once at load) fetches the last version of the GitHub repository and rebuilds it in the browser. Hover a control for a short help, double click it for a detailed one.": "Le graphe embarqué vient du commit indiqué ci-dessus ; « Mettre à jour » (lancé une fois au chargement) récupère la dernière version du dépôt GitHub et le reconstruit dans le navigateur. Survoler un contrôle affiche une aide courte, un double-clic une aide détaillée.",
  "Update": "Mettre à jour",
  "Fit": "Ajuster",
  "Freeze": "Figer",
  "Resume": "Relancer",
  "Views": "Vues",
  "Overview": "Vue d'ensemble",
  "Files &amp; includes": "Fichiers &amp; includes",
  "Classes &amp; inheritance": "Classes &amp; héritage",
  "Classes &amp; methods": "Classes &amp; méthodes",
  "Tests": "Tests",
  "Build": "Build",
  "All": "Tout",
  "Categories": "Catégories",
  "Groups": "Groupes",
  "Relations": "Relations",
  "all": "tout",
  "none": "aucun",
  "Options": "Options",
  "Color by": "Couleur par",
  "category": "catégorie",
  "group": "groupe",
  "Cluster the nodes of a group": "Rapprocher les nœuds d'un même groupe",
  "Show names": "Afficher les noms",
  "Animate the direction of the relations": "Animer le sens des relations",
  "Isolate the selection (neighbours only)": "Isoler la sélection (voisins seulement)",
  "Reading": "Lecture",
  "☰ Controls": "☰ Contrôles",
  "Help · double click": "Aide · double-clic",
  "Search a node… (e.g. Server, parse, .hpp)": "Rechercher un nœud… (ex : Server, parse, .hpp)",
  "Show the controls": "Afficher les contrôles",
  "Hide the controls": "Masquer les contrôles",
  "Graph controls": "Contrôles du graphe",
  "Interactive project graph": "Graphe interactif du projet",
  "Close": "Fermer",
  "Header": "Header",
  "Source": "Source",
  "Test file": "Fichier de test",
  "Class": "Classe",
  "Struct": "Struct",
  "Interface": "Interface",
  "Abstract": "Abstraite",
  "Enum": "Enum",
  "Function": "Fonction",
  "Method": "Méthode",
  "Test": "Test",
  "Test helper": "Aide de test",
  "Executable": "Exécutable",
  "Library": "Bibliothèque",
  "External": "Externe",
  "defines": "définit",
  "member": "membre",
  "inherits": "hérite de",
  "implements": "implémente",
  "compiled into": "compilé dans",
  "links": "lié à",
  "tests": "teste",
  "Outgoing": "Sortant",
  "Incoming": "Entrant",
  "more": "de plus",
  "Group": "Groupe",
  "Path": "Chemin",
  "Namespace": "Namespace",
  "Lines": "Lignes",
  "Access": "Accès",
  "Overloads": "Surcharges",
  "Pure virtual": "Virtuelle pure",
  "yes": "oui",
  "No node: enable some categories / groups": "Aucun nœud : activer des catégories / groupes",
  "Double click: description and example": "Double-clic : description et exemple",
  "of": "du",
  " (fetched from the repository)": " (récupéré du dépôt)",
  " (embedded)": " (embarqué)",
  "No repository configured for the update.": "Aucun dépôt configuré pour la mise à jour.",
  "Checking the repository": "Vérification du dépôt",
  "Up to date:": "À jour :",
  "The graph shown": "Le graphe affiché",
  "is newer than the repository": "est plus récent que le dépôt",
  "local commits not pushed?": "commits locaux non poussés ?",
  "Updated:": "Mis à jour :",
  "Downloading the sources:": "Téléchargement des sources :",
  "Building the graph…": "Construction du graphe…",
  "nodes": "nœuds",
  "Update impossible": "Mise à jour impossible",
  "Graph shown:": "Graphe affiché :",
  "GitHub API rate limit reached": "limite de l'API GitHub atteinte",
  "repository not found or private": "dépôt introuvable ou privé",
  "Architecture": "Architecture",
  "Realistic": "Réaliste",
  "3D style": "Style 3D",
  "calls": "appelle",
  "Diagram": "Schéma",
  "Execution": "Exécution",
  "Inheritance": "Héritage",
  "Flame graph": "Flame graph",
  "Entry point": "Point d'entrée",
  "No call found in the sources (the calls are read in the bodies of the C / C++ functions).": "Aucun appel trouvé dans les sources (les appels sont lus dans le corps des fonctions C / C++).",
  "No inheritance between the classes of the project.": "Aucun héritage entre les classes du projet.",
  "Help": "Aide",
  "Controls": "Contrôles",
  "Controls (? or H)": "Contrôles (? ou H)",
  "Files, classes, functions, tests, build targets (CMake, packages) and external dependencies of <code class=\"repo-name\">{{PROJECT}}</code>, extracted from the sources. Click a node to inspect it, drag to move, scroll to zoom.": "Fichiers, classes, fonctions, tests, cibles de build (CMake, paquets) et dépendances externes de <code class=\"repo-name\">{{PROJECT}}</code>, extraits des sources. Cliquer sur un nœud pour l'inspecter, glisser pour déplacer, molette pour zoomer.",
  "Arrows go from the dependent to the dependency: <em>file → included / imported file</em>, <em>class → base class</em>, <em>source → build target / package</em>, <em>target → linked library</em>, <em>test → tested class</em>. The size of a node grows with its number of relations.": "Les flèches vont du dépendant vers la dépendance : <em>fichier → fichier inclus / importé</em>, <em>classe → classe de base</em>, <em>source → cible de build / paquet</em>, <em>cible → bibliothèque liée</em>, <em>test → classe testée</em>. La taille d'un nœud augmente avec son nombre de relations.",
  "includes / imports": "inclut / importe",
  "Page": "Page",
  "Stylesheet": "Feuille de style",
  "Open": "Ouvrir",
  "Repository": "Dépôt",
  "Graph explorer": "Explorateur de graphe",
  "Which repository?": "Quel dépôt ?",
  "A public GitHub or GitLab repository: its sources are read by your browser to draw the graph of its files, classes, functions, calls, tests and packages.": "Un dépôt GitHub ou GitLab public : ses sources sont lues par ton navigateur pour dessiner le graphe de ses fichiers, classes, fonctions, appels, tests et paquets.",
  "Examples:": "Exemples :",
  "Unsupported link: a GitHub (owner/repo, github.com/...) or GitLab (gitlab.com/..., a self-hosted GitLab) repository.": "Lien non pris en charge : un dépôt GitHub (owner/repo, github.com/...) ou GitLab (gitlab.com/..., un GitLab auto-hébergé).",
  "Choose a repository to explore.": "Choisis un dépôt à explorer.",
  "GitLab API rate limit reached": "Limite de l'API GitLab atteinte",
  "The link is remembered by this browser until Ctrl + Shift + R (forgets it and reloads the page).": "Le lien est mémorisé par ce navigateur jusqu'à Ctrl + Maj + R (l'oublie et recharge la page).",
  "API limit reached, pause…": "Limite de l'API atteinte, pause…",
  "(first 2500 source files of": "(les 2500 premiers fichiers source sur"
};
</script>
<script>
// Language (English by default, French on demand): [data-i18n] elements and [data-i18n-<attr>] attributes are
// translated with window.DOC_FR (English text -> French text), [data-lang] blocks are shown for their language only.
(function () {
  var root = document.documentElement;
  var key = (root.getAttribute('data-storage-key') || 'doc') + '-lang';
  var FR = window.DOC_FR || {};
  var listeners = [];
  function tr(s) { return root.lang === 'fr' && Object.prototype.hasOwnProperty.call(FR, s) ? FR[s] : s; }
  function apply() {
    document.querySelectorAll('[data-i18n]').forEach(function (el) {
      if (el.dataset.i18nEn === undefined) el.dataset.i18nEn = el.innerHTML.trim();
      el.innerHTML = tr(el.dataset.i18nEn);
    });
    ['aria-label', 'title', 'placeholder'].forEach(function (attr) {
      document.querySelectorAll('[data-i18n-' + attr + ']').forEach(function (el) {
        var store = 'i18nEn' + attr.replace(/-(\w)/g, function (m, c) { return c.toUpperCase(); });
        if (el.dataset[store] === undefined) el.dataset[store] = el.getAttribute(attr) || '';
        el.setAttribute(attr, tr(el.dataset[store]));
      });
    });
    document.querySelectorAll('[data-set-lang]').forEach(function (b) {
      b.classList.toggle('on', b.dataset.setLang === root.lang);
      b.setAttribute('aria-pressed', b.dataset.setLang === root.lang ? 'true' : 'false');
    });
  }
  function set(lang) {
    root.lang = lang === 'fr' ? 'fr' : 'en';
    try { localStorage.setItem(key, root.lang); } catch (e) { /* storage unavailable */ }
    apply();
    listeners.forEach(function (f) { f(root.lang); });
  }
  var saved = null;
  try { saved = localStorage.getItem(key); } catch (e) { /* storage unavailable */ }
  // Choice carried by a link of the site (?lang=): pages opened from file:// don't share their storage
  var askedLang = new URLSearchParams(location.search).get('lang');
  if (askedLang === 'en' || askedLang === 'fr') { saved = askedLang; try { localStorage.setItem(key, askedLang); } catch (e) { /* storage unavailable */ } }
  root.lang = saved === 'fr' ? 'fr' : 'en';
  window.docI18n = { tr: tr, set: set, onChange: function (f) { listeners.push(f); }, lang: function () { return root.lang; } };
  document.querySelectorAll('[data-set-lang]').forEach(function (b) {
    b.addEventListener('click', function () { set(b.dataset.setLang); });
  });
  apply();
})();
</script>
<script>
// Project data from the linked GitHub repository (<html data-repo="owner/repo">): name, latest version, license and
// URL are fetched (cached 1 h) and replace the written values in .repo-name / .repo-version / .repo-license /
// .repo-link and in the page title. Offline, private repository or API limit: the written values stay.
(function () {
  var root = document.documentElement, repo = root.getAttribute('data-repo') || '';
  if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) return;
  var key = (root.getAttribute('data-storage-key') || 'doc') + '-repo', TTL = 3600 * 1000;
  function apply(info) {
    if (!info) return;
    var oldName = (document.querySelector('.repo-name') || {}).textContent;
    if (info.name) document.querySelectorAll('.repo-name').forEach(function (e) { e.textContent = info.name; });
    if (info.version) document.querySelectorAll('.repo-version').forEach(function (e) { e.textContent = info.version; });
    if (info.license) document.querySelectorAll('.repo-license').forEach(function (e) { e.textContent = info.license; });
    if (info.url) document.querySelectorAll('a.repo-link').forEach(function (e) { e.href = info.url; });
    if (info.name && oldName && document.title.indexOf(oldName) === 0) document.title = info.name + document.title.slice(oldName.length);
  }
  var cached = null;
  try { cached = JSON.parse(localStorage.getItem(key) || 'null'); } catch (e) { /* storage unavailable */ }
  if (cached && cached.repo === repo) apply(cached);
  // A language change rewrites the translated texts from their original: apply the fetched data again
  if (window.docI18n) window.docI18n.onChange(function () { var c = null; try { c = JSON.parse(localStorage.getItem(key) || 'null'); } catch (e) { /* storage unavailable */ } apply(window.docRepoInfo || c); });
  if (cached && cached.repo === repo && Date.now() - cached.time < TTL) return;
  var api = 'https://api.github.com/repos/' + repo;
  var get = function (u) { return fetch(u, { headers: { Accept: 'application/vnd.github+json' } }).then(function (r) { if (!r.ok) throw new Error(r.status); return r.json(); }); };
  get(api).then(function (r) {
    var info = { repo: repo, time: Date.now(), name: r.name, url: r.html_url, license: r.license && r.license.spdx_id && r.license.spdx_id !== 'NOASSERTION' ? r.license.spdx_id : '' };
    return get(api + '/releases/latest').then(function (rel) { info.version = rel.tag_name; return info; })
      .catch(function () { return get(api + '/tags?per_page=1').then(function (tags) { if (tags[0]) info.version = tags[0].name; return info; }); })
      .catch(function () { return info; });
  }).then(function (info) {
    window.docRepoInfo = info;
    apply(info);
    try { localStorage.setItem(key, JSON.stringify(info)); } catch (e) { /* storage unavailable */ }
  }).catch(function () { /* keep the written values */ });
})();
</script>
<script>
// <extractor> (shared with scripts/build_graph.mjs: keep it free of DOM / browser APIs)
function extractGraph(files, opts) {
    opts = opts || {};
    const nodes = new Map();
    const links = [];
    const linkKeys = new Set();
    const HEADER = /\.(hpp|hh|hxx|h|tpp|inl|ipp|h\+\+)$/;
    const CODE = /\.(hpp|hh|hxx|h|tpp|inl|ipp|cpp|cc|cxx|c|c\+\+)$/;
    const POSIX = new Set(("unistd fcntl poll dlfcn signal errno termios pthread sched semaphore dirent netdb pwd grp glob spawn syslog time string strings stdio stdlib math assert limits stdint stddef ctype locale wchar wctype setjmp stdarg float iso646 fenv inttypes stdbool complex tgmath uchar execinfo cxxabi elf link malloc memory alloca getopt libgen regex fnmatch ifaddrs utime ucontext").split(" "));
    const SYSDIRS = new Set(["sys", "netinet", "arpa", "linux", "bits", "net", "asm", "machine", "mach", "x86intrin"]);
    const ATTR = /^_[a-z]+$/; // libutils attribute macros (_hot, _nodiscard, ...)
    const SKIPNAMES = new Set(["if", "for", "while", "switch", "return", "sizeof", "decltype", "alignas", "alignof", "requires", "static_assert", "noexcept", "throw", "catch", "defined", "static_cast", "reinterpret_cast", "const_cast", "dynamic_cast", "operator"]);
    const byPath = new Map(files.map(f => [f.path, f]));
    const classByName = new Map(); // simple name -> [ids]
    const pendingImpl = []; // [fileId, className]
    const pendingBases = []; // [classId, baseName]
    const bodies = []; // function / method bodies: {owner, cls, name, body} -> "calls" relations
    const fields = new Map(); // class id -> Map(field name -> type name): resolves obj.method() on the members

    function node(id, kind, label, extra) {
        if (!nodes.has(id)) nodes.set(id, Object.assign({id, kind, label}, extra || {}));
        return nodes.get(id);
    }
    function link(source, target, kind) {
        if (source === target) return;
        const key = source + "\u0000" + target + "\u0000" + kind;
        if (linkKeys.has(key)) return;
        linkKeys.add(key);
        links.push({source, target, kind});
    }
    function isTest(path) { // test files of every ecosystem
        return /(^|\/)(tests?|Tests|__tests__|spec|specs)\//.test(path) || /(^|\/)(test_[^/]+\.py|[^/]+_test\.(py|go|rb|exs|dart|lua|zig)|[^/]+\.(test|spec)\.[jt]sx?|[^/]+(Test|Tests|Spec)\.(java|kt|cs|php|scala|swift|hs|m)|[^/]+_spec\.(rb|lua)|[^/]+\.bats)$/.test(path);
    }
    function groupOf(path) {
        if (!CODE.test(path)) { // other languages: the last folder that is not a generic one (src, lib, main, java, com...)
            if (isTest(path)) return "tests";
            const dirs = path.split("/").slice(0, -1).filter(d => !/^(src|lib|libs|app|main|java|kotlin|scala|internal|pkg|source|sources|Sources|include|js|ts|com|org|io|net|public|static|assets|resources|lua)$/.test(d));
            return dirs.length ? dirs[dirs.length - 1] : "root";
        }
        const p = path.split("/");
        if (p[0] === "tests" || p[0] === "test") return p.length >= 3 ? p[1] : "tests";
        if (p[0] === "include" || p[0] === "src" || p[0] === "lib" || p[0] === "source") {
            if (p.length >= 4) return p[2];
            if (p.length === 3) return p[1];
            return "root";
        }
        return p.length > 1 ? p[0] : "root";
    }
    function dirname(p) { const i = p.lastIndexOf("/"); return i < 0 ? "" : p.slice(0, i); }
    function normalize(p) {
        const out = [];
        for (const s of p.split("/")) {
            if (!s || s === ".") continue;
            if (s === "..") out.pop(); else out.push(s);
        }
        return out.join("/");
    }
    function stripCode(text) {
        // Remove comments, strings, chars and preprocessor lines (keeps the structure)
        let out = "", i = 0, n = text.length, lineStart = true;
        while (i < n) {
            const c = text[i], d = text[i + 1];
            if (lineStart) {
                let j = i;
                while (j < n && (text[j] === " " || text[j] === "\t")) j++;
                if (text[j] === "#") { // preprocessor (with continuations)
                    while (j < n && text[j] !== "\n") { if (text[j] === "\\" && text[j + 1] === "\n") j++; j++; }
                    i = j; out += "\n"; continue;
                }
                lineStart = false;
            }
            if (c === "/" && d === "/") { while (i < n && text[i] !== "\n") i++; continue; }
            if (c === "/" && d === "*") { const e = text.indexOf("*/", i + 2); i = e < 0 ? n : e + 2; out += " "; continue; }
            if (c === "R" && d === "\"") { // raw string R"delim(...)delim"
                const p = text.indexOf("(", i + 2);
                const delim = text.slice(i + 2, p);
                const e = text.indexOf(")" + delim + "\"", p);
                i = e < 0 ? n : e + delim.length + 2; out += "\"\""; continue;
            }
            if (c === "\"" || c === "'") {
                let j = i + 1;
                while (j < n && text[j] !== c && text[j] !== "\n") { if (text[j] === "\\") j++; j++; }
                i = j + 1; out += c + c; continue;
            }
            if (c === "\n") lineStart = true;
            out += c; i++;
        }
        return out;
    }
    function stripTemplate(h) {
        h = h.trim();
        while (h.startsWith("template")) {
            const s = h.indexOf("<");
            if (s < 0) break;
            let depth = 0, i = s;
            for (; i < h.length; i++) {
                if (h[i] === "<") depth++;
                else if (h[i] === ">" && --depth === 0) break;
            }
            h = h.slice(i + 1).trim();
        }
        return h;
    }
    function funcName(h) {
        h = stripTemplate(h).replace(/\[\[.*?\]\]/g, " ");
        const re = /(operator\s*(?:\(\)|\[\]|[^\s(]+)|~?[A-Za-z_][\w:]*)\s*\(/g;
        let m;
        while ((m = re.exec(h))) {
            const full = m[1].replace(/\s+/g, "");
            const name = full.split("::").pop();
            if (SKIPNAMES.has(name) || ATTR.test(name)) continue;
            return full;
        }
        return "";
    }
    function addClassName(name, id) {
        if (!classByName.has(name)) classByName.set(name, []);
        if (!classByName.get(name).includes(id)) classByName.get(name).push(id);
    }

    // Files & includes
    for (const f of files) {
        if (!CODE.test(f.path)) continue;
        const kind = isTest(f.path) ? "test-file" : HEADER.test(f.path) ? "header" : "source";
        node("file:" + f.path, kind, f.path.split("/").pop(), {path: f.path, group: groupOf(f.path), loc: f.text.split("\n").length});
    }
    const paths = files.map(f => f.path);
    function resolveInclude(from, inc, quoted) {
        const cands = [];
        if (quoted) cands.push(normalize(dirname(from) + "/" + inc));
        cands.push("include/" + inc, "src/" + inc, inc, "tests/" + inc);
        for (const c of cands) if (byPath.has(c) && CODE.test(c)) return c;
        const suffix = paths.filter(p => p.endsWith("/" + inc));
        return suffix.length === 1 ? suffix[0] : null;
    }
    for (const f of files) {
        if (!CODE.test(f.path)) continue;
        const re = /^[ \t]*#[ \t]*include[ \t]*([<"])([^>"]+)[>"]/gm;
        let m;
        while ((m = re.exec(f.text))) {
            const target = resolveInclude(f.path, m[2], m[1] === "\"");
            if (target) { link("file:" + f.path, "file:" + target, "includes"); continue; }
            if (m[1] === "\"") continue; // generated / not in the repository
            const inc = m[2], first = inc.split("/")[0], base = first.replace(/\.(h|hpp|hh|hxx|h\+\+)$/, "");
            if (!inc.includes("/") && !inc.includes(".")) continue; // standard library
            if (SYSDIRS.has(first) || POSIX.has(base)) continue;
            node("ext:" + base.toLowerCase(), "external", base, {group: "external"});
            link("file:" + f.path, "ext:" + base.toLowerCase(), "includes");
        }
    }

    // C++ declarations
    for (const f of files) {
        if (!CODE.test(f.path)) continue;
        const fileId = "file:" + f.path;
        const group = groupOf(f.path);
        const code = stripCode(f.text);
        const stack = []; // {type, name, id, access}
        let head = "";
        let skip = 0; // depth inside a function / enum / initializer body
        let body = null; // {start, owner...}: body of the function being skipped
        const nsName = () => stack.filter(s => s.type === "namespace" && s.name).map(s => s.name).join("::");
        const inClass = () => stack.length && stack[stack.length - 1].type === "class" ? stack[stack.length - 1] : null;
        const atNamespace = () => stack.every(s => s.type === "namespace");
        function takeAccess(h) {
            const cls = inClass();
            let m;
            while ((m = /^\s*(public|private|protected)\s*:(?!:)/.exec(h))) {
                if (cls) cls.access = m[1];
                h = h.slice(m[0].length);
            }
            return h.trim();
        }
        function onFunction(h, isDefinition) {
            if (/^(using|typedef|friend|static_assert|return|extern\s+template)\b/.test(h) || /=\s*delete\s*$/.test(h)) return;
            if (/^(class|struct|union|enum)\b/.test(h) && !h.includes("(")) return;
            const full = funcName(h);
            if (!full) return;
            const name = full.split("::").pop();
            if (/^(TEST|TEST_F|TEST_P|TYPED_TEST|TYPED_TEST_P|INSTANTIATE_TEST_SUITE_P|TYPED_TEST_SUITE)$/.test(name)) return; // GoogleTest macros, not functions
            const cls = inClass();
            if (cls) {
                if (name === cls.name || name === "~" + cls.name) return {owner: cls.id, cls: cls.id}; // constructor: calls of the class
                if (name.startsWith("operator")) return;
                const id = cls.id + "::" + name;
                const n = node(id, "method", name + "()", {group, path: f.path, access: cls.access, overloads: 0});
                n.overloads++;
                if (/=\s*0\s*$/.test(h)) { n.pure = true; cls.pure = true; }
                link(cls.id, id, "member");
                return {owner: id, cls: cls.id};
            }
            if (!atNamespace()) return;
            const parts = full.split("::");
            if (parts.length >= 2 && isDefinition) { // ns::Class::method definition in a source
                const owner = parts[parts.length - 2];
                if (owner && owner[0] === owner[0].toUpperCase()) { pendingImpl.push([fileId, owner, name]); return {className: owner, name}; }
            }
            if (name === "main") { // entry point of the program
                node("fn:main@" + f.path, "function", "main()", {group, path: f.path, entry: true});
                link(fileId, "fn:main@" + f.path, "defines");
                return {owner: "fn:main@" + f.path};
            }
            const ns = nsName() || (parts.length > 1 ? parts.slice(0, -1).join("::") : "");
            const id = "fn:" + (ns ? ns + "::" : "") + name;
            node(id, "function", name + "()", {group, path: f.path, ns});
            link(fileId, id, "defines");
            return {owner: id};
        }
        for (let i = 0; i < code.length; i++) {
            const c = code[i];
            if (skip) {
                if (c === "{") skip++;
                else if (c === "}") {
                    skip--;
                    if (!skip) { head = ""; if (body) { bodies.push(Object.assign(body, {body: code.slice(body.start, i)})); body = null; } }
                }
                continue;
            }
            if (c === "{") {
                let h = takeAccess(head.replace(/\s+/g, " "));
                head = "";
                const t = stripTemplate(h);
                if (/^(inline\s+)?namespace\b/.test(t) || /^extern\s*""$/.test(t) || t === "") {
                    const m = /namespace\s+([\w:]+)/.exec(t);
                    stack.push({type: t.startsWith("extern") || t === "" ? "block" : "namespace", name: m ? m[1] : ""});
                    if (t === "" && !atNamespace()) { stack.pop(); skip = 1; }
                    continue;
                }
                let m = /^(class|struct|union)\s+(?:(?:\[\[.*?\]\]|alignas\([^)]*\)|_[a-z]+(?:\([^)]*\))?)\s+)*([A-Za-z_]\w*)(?:\s*<[^{]*>)?(?:\s+final)?\s*(?::\s*(.*))?$/.exec(t);
                if (m && !/\)\s*$/.test(t.split(":")[0])) {
                    const name = m[2];
                    const parent = inClass();
                    const qual = (parent ? parent.id.slice(4) : (nsName() ? nsName() + "::" : "")) + (parent ? "::" : "") + name;
                    const id = "cls:" + qual;
                    let kind = m[1] === "class" ? "class" : "struct";
                    if (/^I[A-Z]/.test(name)) kind = "interface";
                    else if (/^A[A-Z]/.test(name)) kind = "abstract";
                    const n = node(id, kind, name, {group, path: f.path, ns: nsName()});
                    if (n.kind === "struct" && kind !== "struct") n.kind = kind;
                    addClassName(name, id);
                    link(fileId, id, "defines");
                    if (m[3]) {
                        let depth = 0, cur = "";
                        const bases = [];
                        for (const ch of m[3]) {
                            if (ch === "<") depth++;
                            if (ch === ">") depth--;
                            if (ch === "," && !depth) { bases.push(cur); cur = ""; } else cur += ch;
                        }
                        bases.push(cur);
                        for (let b of bases) {
                            b = b.replace(/\b(public|protected|private|virtual)\b/g, "").replace(/<.*>/, "").trim();
                            if (b) pendingBases.push([id, b.split("::").pop()]);
                        }
                    }
                    stack.push({type: "class", name, id, access: m[1] === "class" ? "private" : "public", kindRef: n});
                    continue;
                }
                m = /^enum\s+(?:class\s+|struct\s+)?(?:_[a-z]+\s+)?([A-Za-z_]\w*)/.exec(t);
                if (m) {
                    const parent = inClass();
                    const id = "enum:" + (parent ? parent.id.slice(4) + "::" : (nsName() ? nsName() + "::" : "")) + m[1];
                    node(id, "enum", m[1], {group, path: f.path, ns: nsName()});
                    link(parent ? parent.id : fileId, id, parent ? "member" : "defines");
                    skip = 1;
                    continue;
                }
                if (t.includes(")") && !/=\s*$/.test(t)) {
                    const o = onFunction(t.replace(/\)\s*:(?!:).*$/s, ")").replace(/\s*(const|noexcept|override|final|->[^{]*)\s*$/g, ""), true);
                    if (o) body = Object.assign(o, {start: i + 1, group});
                }
                skip = 1;
                continue;
            }
            if (c === "}") {
                const s = stack.pop();
                if (s && s.type === "class" && s.pure && s.kindRef.kind === "class") s.kindRef.kind = "abstract";
                head = "";
                continue;
            }
            if (c === ";") {
                const h = takeAccess(head.replace(/\s+/g, " "));
                head = "";
                const fc = inClass(), fm = fc && !h.includes("(") && /^(?:(?:static|mutable|const|inline|constexpr)\s+)*(?:[\w]+::)*([A-Za-z_]\w*)\s*(?:<[^;]*>)?\s*[&*]*\s+([A-Za-z_]\w*)\s*(?:=.*|\{.*\})?$/.exec(h);
                if (fm) { if (!fields.has(fc.id)) fields.set(fc.id, new Map()); fields.get(fc.id).set(fm[2], fm[1]); } // member field
                if (h.includes("(") && (inClass() || atNamespace())) onFunction(stripTemplate(h), false);
                continue;
            }
            head += c;
        }
    }
    // ---------- Other languages: Python, JS / TS, Java / Kotlin, C#, Go, Rust, PHP, Ruby, HTML / CSS ---------- //
    // Light regex parsers (no AST): files, imports, classes + bases, functions, methods, bodies (-> calls)
    const LANGS = [["py", /\.pyi?$/], ["js", /\.(m?js|cjs|jsx|ts|tsx|mts|cts|vue|svelte)$/], ["java", /\.(java|kt|kts|scala|groovy)$/],
        ["cs", /\.cs$/], ["go", /\.go$/], ["rs", /\.rs$/], ["php", /\.php$/], ["rb", /\.rb$/], ["zig", /\.zig$/], ["swift", /\.swift$/],
        ["dart", /\.dart$/], ["lua", /\.lua$/], ["jl", /\.jl$/], ["ex", /\.exs?$/], ["hs", /\.l?hs$/], ["objc", /\.mm?$/], ["sh", /\.(sh|bash|zsh)$/]];
    const SLASH = new Set(["js", "java", "cs", "go", "rs", "php", "zig", "swift", "dart", "objc"]), HASH = new Set(["py", "rb", "php", "jl", "ex", "sh"]);
    const langOf = (p) => (LANGS.find(l => l[1].test(p)) || [null])[0];
    const PAGE = /\.html?$/, STYLE = /\.(css|scss|sass|less)$/;
    const PY_STD = new Set(("abc argparse array ast asyncio base64 bisect builtins calendar collections concurrent configparser contextlib copy csv ctypes dataclasses datetime decimal difflib email enum errno fnmatch fractions functools gc getpass glob gzip hashlib heapq hmac html http importlib inspect io ipaddress itertools json logging math mimetypes multiprocessing numbers operator os pathlib pickle platform pprint queue random re secrets select shlex shutil signal socket sqlite3 ssl stat statistics string struct subprocess sys tempfile textwrap threading time timeit tkinter traceback types typing unittest urllib uuid venv warnings weakref xml zipfile zlib __future__ typing_extensions").split(" "));
    const NODE_STD = new Set(("assert buffer child_process cluster crypto dgram dns events fs http http2 https net os path perf_hooks process querystring readline stream string_decoder timers tls tty url util v8 vm worker_threads zlib module").split(" "));
    const RB_STD = new Set(("json set yaml date time fileutils pathname securerandom digest open3 optparse logger erb uri net/http socket tempfile stringio benchmark forwardable singleton ostruct").split(" "));
    function stripOther(text, lang) { // comments and string contents removed, the line breaks kept
        let out = "", i = 0;
        const n = text.length, hash = HASH.has(lang), slash = SLASH.has(lang);
        while (i < n) {
            const c = text[i], d = text[i + 1];
            if (slash && c === "/" && d === "/") { while (i < n && text[i] !== "\n") i++; continue; }
            if (slash && c === "/" && d === "*") { const e = text.indexOf("*/", i + 2), end = e < 0 ? n : e + 2; out += text.slice(i, end).replace(/[^\n]/g, " "); i = end; continue; }
            if (lang === "jl" && c === "#" && d === "=") { const e = text.indexOf("=#", i + 2), end = e < 0 ? n : e + 2; out += text.slice(i, end).replace(/[^\n]/g, " "); i = end; continue; }
            if (hash && c === "#" && !(lang === "php" && d === "[") && !(lang === "sh" && i && !/\s/.test(text[i - 1]))) { while (i < n && text[i] !== "\n") i++; continue; }
            if ((lang === "lua" || lang === "hs") && c === "-" && d === "-") { // -- comment, --[[ long ]] comment (Lua)
                const lb = lang === "lua" && /^--\[=*\[/.exec(text.slice(i, i + 12));
                const end = lb ? (text.indexOf("]" + lb[0].slice(3, -1) + "]", i) + lb[0].length - 2) : text.indexOf("\n", i);
                const stop = end < i ? n : end;
                out += text.slice(i, stop).replace(/[^\n]/g, " "); i = stop; continue;
            }
            if (lang === "rs" && (c === "r" || c === "b") && /^b?r#*"/.test(text.slice(i, i + 12)) && !/\w/.test(text[i - 1] || "")) { // raw string r#"..."#
                const open = /^b?r(#*)"/.exec(text.slice(i, i + 12)), e = text.indexOf('"' + open[1], i + open[0].length), end = e < 0 ? n : e + 1 + open[1].length;
                out += '""' + text.slice(i, end).replace(/[^\n]/g, ""); i = end; continue;
            }
            if (lang === "hs" && c === "{" && d === "-") { const e = text.indexOf("-}", i + 2), end = e < 0 ? n : e + 2; out += text.slice(i, end).replace(/[^\n]/g, " "); i = end; continue; }
            if (lang === "lua" && c === "[" && /^\[=*\[/.test(text.slice(i, i + 8))) { const q = /^\[=*\[/.exec(text.slice(i, i + 8))[0], e = text.indexOf(q.replace(/\[/g, "]"), i + q.length), end = e < 0 ? n : e + q.length; out += '""' + text.slice(i, end).replace(/[^\n]/g, ""); i = end; continue; }
            if (lang === "rb" && c === "=" && text.startsWith("=begin", i) && (i === 0 || text[i - 1] === "\n")) { const e = text.indexOf("\n=end", i), end = e < 0 ? n : e + 5; out += text.slice(i, end).replace(/[^\n]/g, " "); i = end; continue; }
            if ((lang === "py" || lang === "ex" || lang === "jl" || lang === "swift" || lang === "dart") && (text.startsWith('"""', i) || text.startsWith("'''", i))) { const q = text.slice(i, i + 3), e = text.indexOf(q, i + 3), end = e < 0 ? n : e + 3; out += '""' + text.slice(i, end).replace(/[^\n]/g, ""); i = end; continue; }
            if (c === '"' || (c === "`" && lang !== "sh") || (c === "'" && !(/^(rs|hs|jl)$/.test(lang) && !/^'(\\.|[^\\'])'/.test(text.slice(i, i + 4))))) {
                let j = i + 1;
                while (j < n && text[j] !== c && (c === "`" || text[j] !== "\n")) { if (text[j] === "\\") j++; j++; }
                out += c + text.slice(i + 1, Math.min(j, n)).replace(/[^\n]/g, "") + c; i = j + 1; continue;
            }
            out += c; i++;
        }
        return lang === "php" ? out.replace(/\$this\b/g, "this").replace(/\$(\w)/g, "$1") : out;
    }
    const others = files.filter(f => langOf(f.path) || PAGE.test(f.path) || STYLE.test(f.path));
    for (const f of others) {
        const lang = langOf(f.path), kind = isTest(f.path) && lang ? "test-file" : PAGE.test(f.path) ? "page" : STYLE.test(f.path) ? "style" : /\.d\.ts$/.test(f.path) ? "header" : "source";
        node("file:" + f.path, kind, f.path.split("/").pop(), {path: f.path, group: groupOf(f.path), loc: f.text.split("\n").length, lang: lang || (PAGE.test(f.path) ? "html" : "css")});
    }
    const filesIn = (dir, test) => paths.filter(p => dirname(p) === dir && (!test || test(p)));
    function tryFiles(cands) { for (const c of cands) if (byPath.has(c)) return c; return null; }
    function ext(name) { // external dependency node (shared with the manifests); null for a name that is not one
        if (!name || !/^[@\w][\w.\-\/@]*$/.test(name)) return null;
        const id = "ext:" + name.toLowerCase();
        node(id, "external", name, {group: "external"});
        return id;
    }
    // Go: module path of go.mod; Java / C#: the files of a package / namespace
    const goMod = byPath.has("go.mod") ? (/^module\s+(\S+)/m.exec(byPath.get("go.mod").text) || [])[1] : null;
    const nsFiles = new Map(); // namespace / package -> [files]
    for (const f of others) {
        const m = /^\s*(?:package|namespace)\s+([\w.\\]+)\s*[;{]?/m.exec(f.text);
        if (m && /^(java|cs|php)$/.test(langOf(f.path))) { const k = m[1].replace(/\\/g, "."); if (!nsFiles.has(k)) nsFiles.set(k, []); nsFiles.get(k).push(f.path); }
    }
    const capped = (list) => list.slice(0, 6);
    const RUST_STD = new Set("Default Debug Clone Copy PartialEq Eq PartialOrd Ord Hash Display From Into TryFrom TryInto Drop AsRef AsMut Deref DerefMut Iterator IntoIterator FusedIterator DoubleEndedIterator ExactSizeIterator FromIterator Extend Read Write BufRead Seek Send Sync Sized Unpin FromStr Error Add AddAssign Sub SubAssign Mul MulAssign Div Rem Neg Not BitAnd BitOr BitXor Shl Shr Index IndexMut Fn FnMut FnOnce ToString Borrow BorrowMut ToOwned Future Any".split(" "));
    const SWIFT_STD = new Set("Foundation UIKit AppKit SwiftUI Combine XCTest Darwin Dispatch os CoreData CoreGraphics CoreFoundation Cocoa ObjectiveC Glibc Swift MapKit AVFoundation WebKit Security Network".split(" "));
    const JL_STD = new Set("Base Core Main LinearAlgebra Statistics Random Printf Test Dates Distributed Logging Markdown Pkg REPL SparseArrays Serialization Sockets Unicode InteractiveUtils Libdl Mmap SHA UUIDs DelimitedFiles".split(" "));
    const EX_STD = new Set("Kernel Enum String Map List Keyword Logger GenServer Supervisor Agent Task Process Application Code IO File Path System Regex Integer Float Atom Tuple Stream Range Access Protocol Module Macro Inspect ExUnit Mix Registry DynamicSupervisor URI Base Bitwise Calendar Date DateTime NaiveDateTime Time".split(" "));
    const HS_STD = new Set("Prelude Data Control System GHC Text Foreign Numeric Debug Unsafe Type".split(" "));
    const dartPkg = () => { const y = byPath.get("pubspec.yaml"); return y ? (/^name:\s*(\S+)/m.exec(y.text) || [])[1] : null; };
    const modFiles = new Map(); // Julia / Elixir / Haskell: module name -> file
    for (const f of others) {
        const l = langOf(f.path), re = l === "jl" ? /^\s*module\s+(\w+)/gm : l === "ex" ? /^\s*defmodule\s+([\w.]+)/gm : l === "hs" ? /^module\s+([\w.]+)/gm : null;
        if (!re) continue;
        let m;
        while ((m = re.exec(f.text))) if (!modFiles.has(m[1])) modFiles.set(m[1], f.path);
    }
    function imports(f, lang) { // -> [target file] or external ids
        const t = /^(rs|java|cs)$/.test(lang) ? stripOther(f.text, lang) : f.text, dir = dirname(f.path), res = []; // no "use ..." of a comment / string
        const add = (p) => { if (p && p !== f.path) res.push("file:" + p); };
        const one = (re, fn) => { let m; re.lastIndex = 0; while ((m = re.exec(t))) fn(m); };
        if (lang === "py") {
            const mod = (name, dots) => {
                const base = dots ? normalize(dir + "/" + "../".repeat(Math.max(0, dots - 1))) : "";
                const rel = name.replace(/\./g, "/"), pre = base ? base + "/" : "";
                return tryFiles([pre + rel + ".py", pre + rel + "/__init__.py", "src/" + rel + ".py", "src/" + rel + "/__init__.py"]);
            };
            one(/^[ \t]*from[ \t]+(\.*)([\w.]*)[ \t]+import[ \t]+\(?([\w ,*\n]+)/gm, (m) => {
                const dots = m[1].length, p = mod(m[2], dots);
                if (p) add(p);
                if (!m[2] || (dots && !p)) for (const x of m[3].split(",")) { const q = mod((m[2] ? m[2] + "." : "") + x.trim().split(/\s/)[0], dots); if (q) add(q); }
                if (!p && !dots && m[2]) { const top = m[2].split(".")[0]; if (!PY_STD.has(top) && !tryFiles([top + ".py", top + "/__init__.py", "src/" + top + "/__init__.py"])) res.push(ext(top)); }
            });
            one(/^[ \t]*import[ \t]+([\w., ]+)/gm, (m) => { for (const x of m[1].split(",")) { const name = x.trim().split(/\s/)[0], p = mod(name, 0); if (p) add(p); else { const top = name.split(".")[0]; if (top && !PY_STD.has(top)) res.push(ext(top)); } } });
        } else if (lang === "js" || PAGE.test(f.path) || STYLE.test(f.path)) {
            const specs = [];
            if (!STYLE.test(f.path)) one(/(?:\bimport\s+(?:[\w*{}\s,$]+?\s+from\s+)?|\bexport\s+[\w*{}\s,$]+?\s+from\s+|\brequire\s*\(\s*|\bimport\s*\(\s*)["'`]([^"'`]+)["'`]/g, m => specs.push(m[1]));
            if (PAGE.test(f.path)) one(/<(?:script|img|iframe)[^>]*\bsrc=["']([^"']+)["']|<link[^>]*\bhref=["']([^"']+\.(?:css|scss))["']|<a[^>]*\bhref=["']([^"'#?]+\.html?)["']/gi, m => specs.push("./" + (m[1] || m[2] || m[3]).replace(/^\.\//, "")));
            if (STYLE.test(f.path)) one(/@(?:import|use|forward)\s+(?:url\()?["']([^"']+)["']/g, m => specs.push(m[1].startsWith(".") ? m[1] : "./" + m[1]));
            for (const s of specs) {
                if (/^(https?:)?\/\//.test(s) || s.startsWith("data:")) continue;
                if (s.startsWith(".") || s.startsWith("/") || /^[@~]\//.test(s)) {
                    const base = s.startsWith("/") ? s.slice(1) : /^[@~]\//.test(s) ? "src/" + s.slice(2) : normalize(dir + "/" + s);
                    const exts = ["", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".vue", ".svelte", ".css", ".scss", ".d.ts"];
                    const partial = dirname(base) + (dirname(base) ? "/_" : "_") + base.split("/").pop(); // SCSS partial _x.scss
                    add(tryFiles(exts.map(e => base + e).concat(["/index.ts", "/index.tsx", "/index.js", "/index.jsx"].map(e => base + e), [".scss", ".sass", ""].map(e => partial + e))));
                    continue;
                }
                const name = s.startsWith("@") ? s.split("/").slice(0, 2).join("/") : s.split("/")[0];
                if (!NODE_STD.has(name.replace(/^node:/, "")) && !name.startsWith("node:") && !/^[@~]$/.test(name)) res.push(ext(name));
            }
        } else if (lang === "java") {
            one(/^\s*import\s+(?:static\s+)?([\w.]+?)(?:\.\*)?\s*;?\s*$/gm, (m) => {
                const parts = m[1].split(".");
                const p = paths.find(x => /\.(java|kt|scala|groovy)$/.test(x) && x.replace(/\.\w+$/, "").endsWith(parts.join("/")));
                if (p) { add(p); return; }
                const pk = nsFiles.get(m[1]) || nsFiles.get(parts.slice(0, -1).join("."));
                if (pk) { capped(pk).forEach(add); return; }
                if (/^(java|javax|kotlin|scala|groovy|jdk|sun)$/.test(parts[0])) return;
                res.push(ext(/^(com|org|io|net|de|fr|me|dev|edu)$/.test(parts[0]) && parts[1] ? parts[1] : parts[0]));
            });
        } else if (lang === "cs") {
            one(/^\s*using\s+(?:static\s+)?(?:\w+\s*=\s*)?([\w.]+)\s*;/gm, (m) => {
                if (nsFiles.has(m[1])) { capped(nsFiles.get(m[1])).forEach(add); return; }
                if (!/^(System|Microsoft\.CSharp)\b/.test(m[1])) res.push(ext(m[1].split(".").slice(0, 2).join(".")));
            });
        } else if (lang === "go") {
            const block = /\bimport\s*\(([^)]*)\)|\bimport\s+(?:\w+\s+)?"([^"]+)"/g;
            let m;
            while ((m = block.exec(t))) for (const imp of m[2] ? [m[2]] : (m[1].match(/"[^"]+"/g) || []).map(x => x.slice(1, -1))) {
                if (goMod && imp.startsWith(goMod)) { capped(filesIn(imp.slice(goMod.length + 1), p => p.endsWith(".go") && !p.endsWith("_test.go"))).forEach(add); continue; }
                if (!imp.split("/")[0].includes(".")) continue; // standard library
                res.push(ext(imp.split("/").slice(-1)[0].replace(/^v\d+$/, imp.split("/").slice(-2)[0])));
            }
        } else if (lang === "rs") {
            const root = f.path.includes("src/") ? f.path.slice(0, f.path.indexOf("src/") + 4) : "";
            one(/^\s*(?:pub\s+)?mod\s+(\w+)\s*;/gm, (m) => add(tryFiles([dir + "/" + m[1] + ".rs", dir + "/" + m[1] + "/mod.rs", normalize(f.path.replace(/\.rs$/, "") + "/" + m[1] + ".rs")])));
            one(/^\s*(?:pub\s+)?use\s+([\w:]+)/gm, (m) => {
                const parts = m[1].split("::");
                if (parts[0] === "crate") { for (let k = parts.length; k > 1; k--) { const p = tryFiles([root + parts.slice(1, k).join("/") + ".rs", root + parts.slice(1, k).join("/") + "/mod.rs"]); if (p) { add(p); break; } } return; }
                if (parts[0] === "self" || parts[0] === "super") { // relative module path
                    const base = parts[0] === "super" ? dirname(dir) || dir : dir;
                    const p = tryFiles([base + "/" + parts[1] + ".rs", base + "/" + parts[1] + "/mod.rs"]);
                    if (p) add(p);
                    return;
                }
                const local = tryFiles([dir + "/" + parts[0] + ".rs", dir + "/" + parts[0] + "/mod.rs"]); // sibling module (use module::Item)
                if (local) { add(local); return; }
                if (!/^(std|core|alloc)$/.test(parts[0])) res.push(ext(parts[0].replace(/_/g, "-")));
            });
        } else if (lang === "php") {
            one(/^\s*use\s+(?:function\s+|const\s+)?([\w\\]+)/gm, (m) => {
                const parts = m[1].replace(/^\\/, "").split("\\"), tail = parts.slice(1).join("/");
                if (parts.length < 2) return; // global class of PHP (Closure, Exception...)
                const p = paths.find(x => x.endsWith(".php") && (x.endsWith("/" + parts.join("/") + ".php") || (tail && x.endsWith("/" + tail + ".php"))));
                if (p) add(p); else res.push(ext(parts[0]));
            });
            one(/\b(?:require|include)(?:_once)?\s*\(?\s*(?:__DIR__\s*\.\s*)?["']([^"']+\.php)["']/g, (m) => add(tryFiles([normalize(dir + "/" + m[1]), normalize(m[1])])));
        } else if (lang === "rb") {
            one(/^\s*require_relative\s+["']([^"']+)["']/gm, (m) => add(tryFiles([normalize(dir + "/" + m[1]) + ".rb", normalize(dir + "/" + m[1])])));
            one(/^\s*require\s+["']([^"']+)["']/gm, (m) => { const p = tryFiles(["lib/" + m[1] + ".rb", m[1] + ".rb"]) || paths.find(x => x.endsWith("/" + m[1] + ".rb")); if (p) add(p); else if (!RB_STD.has(m[1])) res.push(ext(m[1].split("/")[0])); });
        }
        else if (lang === "zig") {
            one(/@import\s*\(\s*"([^"]+)"\s*\)/g, (m) => { if (m[1].endsWith(".zig")) add(tryFiles([normalize(dir + "/" + m[1]), normalize(m[1])])); else if (!/^(std|builtin|root)$/.test(m[1])) res.push(ext(m[1])); });
        } else if (lang === "swift") {
            one(/^\s*(?:@testable\s+)?import\s+(?:class\s+|struct\s+|enum\s+|func\s+)?(\w+)/gm, (m) => { if (!SWIFT_STD.has(m[1]) && !paths.some(p => p.includes("/" + m[1] + "/") && p.endsWith(".swift"))) res.push(ext(m[1])); });
        } else if (lang === "dart") {
            const own = dartPkg();
            one(/^\s*(?:import|export|part)\s+["']([^"']+)["']/gm, (m) => {
                const s = m[1];
                if (s.startsWith("dart:")) return;
                if (s.startsWith("package:")) { const [pk, ...rest] = s.slice(8).split("/"); if (pk === own) add(tryFiles(["lib/" + rest.join("/")])); else res.push(ext(pk)); return; }
                add(tryFiles([normalize(dir + "/" + s)]));
            });
        } else if (lang === "lua") {
            one(/\brequire\s*\(?\s*["']([\w.\/-]+)["']/g, (m) => { const r = m[1].replace(/\./g, "/"); const p = tryFiles([r + ".lua", r + "/init.lua", "src/" + r + ".lua", "lua/" + r + ".lua", "lua/" + r + "/init.lua"]) || paths.find(x => x.endsWith("/" + r + ".lua")); if (p) add(p); else res.push(ext(m[1].split(".")[0])); });
        } else if (lang === "jl") {
            one(/\binclude\s*\(\s*"([^"]+)"\s*\)/g, (m) => add(tryFiles([normalize(dir + "/" + m[1])])));
            one(/^\s*(?:using|import)\s+([\w., :]+)/gm, (m) => { for (const x of m[1].split(":")[0].split(",")) { const name = x.trim().split(".")[0]; if (!name || name === "." || JL_STD.has(name)) continue; const p = modFiles.get(name); if (p) add(p); else res.push(ext(name)); } });
        } else if (lang === "ex") {
            one(/^\s*(?:alias|import|use|require)\s+([A-Z][\w.]*)/gm, (m) => { const p = modFiles.get(m[1]); if (p) add(p); else if (!EX_STD.has(m[1].split(".")[0])) res.push(ext(m[1].split(".")[0])); });
        } else if (lang === "hs") {
            one(/^import\s+(?:qualified\s+)?([A-Z][\w.]*)/gm, (m) => { const p = modFiles.get(m[1]) || paths.find(x => /\.l?hs$/.test(x) && x.replace(/\.l?hs$/, "").endsWith("/" + m[1].replace(/\./g, "/"))); if (p) add(p); else if (!HS_STD.has(m[1].split(".")[0])) res.push(ext(m[1].split(".")[0])); });
        } else if (lang === "objc") {
            one(/^[ \t]*#[ \t]*(?:import|include)[ \t]*([<"])([^>"]+)[>"]/gm, (m) => { const p = resolveInclude(f.path, m[2], m[1] === '"'); if (p) add(p); else if (m[1] === "<" && m[2].includes("/") && !/^(Foundation|UIKit|AppKit|CoreFoundation|CoreGraphics|QuartzCore|Security|SystemConfiguration|MobileCoreServices|CoreServices|XCTest|objc)\//.test(m[2])) res.push(ext(m[2].split("/")[0])); });
        } else if (lang === "sh") {
            one(/^\s*(?:source|\.)\s+["']?([^\s"';|&]+)/gm, (m) => { const name = m[1].split("/").pop(); add(tryFiles([normalize(dir + "/" + m[1])]) || paths.find(x => x.endsWith("/" + name) || x === name)); });
        }
        return res.filter(Boolean);
    }
    for (const f of others) for (const target of imports(f, langOf(f.path))) link("file:" + f.path, target, "includes");

    // Declarations of the brace languages: the "head" before each { says what the block is
    const KEYWORDS = new Set("if for while switch catch return new else do try finally synchronized using lock foreach when match loop unsafe with yield await typeof sizeof function fn func fun def get set constructor init".split(" "));
    function classHead(h, lang) {
        const m = /(?:^|[\s;])(?:(?:abstract|sealed|data|open|final|static|public|private|protected|internal|export|default|partial|inner|enum|annotation|readonly|declare|pub(?:\([\w ]+\))?)\s+)*(class|interface|trait|struct|enum|record|object|protocol|mixin|actor)\s+([A-Za-z_$][\w$]*)([\s\S]*)$/.exec(h);
        if (!m) {
            const g = lang === "go" && /\btype\s+([A-Z_a-z]\w*)\s*(?:\[[^\]]*\])?\s+(struct|interface)\s*$/.exec(h);
            const z = lang === "zig" && /\bconst\s+([A-Za-z_]\w*)\s*=\s*(?:extern\s+|packed\s+)?(struct|enum|union|opaque)\b[^=]*$/.exec(h);
            return g ? {name: g[1], kw: g[2], bases: []} : z ? {name: z[1], kw: z[2] === "union" ? "struct" : z[2], bases: []} : null;
        }
        let rest = m[3].replace(/<[^<>]*(?:<[^<>]*>[^<>]*)*>/g, "").replace(/^\s*\([^)]*\)/, "").replace(/\bwhere\b[\s\S]*$/, "");
        const bases = [];
        const grab = (re) => { const x = re.exec(rest); if (x) x[1].split(",").forEach(b => { b = b.replace(/\([^)]*\)/g, "").replace(/\b(public|private|protected|virtual|readonly)\b/g, "").trim().split(/[.:\\]/).pop(); if (/^[A-Za-z_$][\w$]*$/.test(b)) bases.push(b); }); };
        grab(/\bextends\s+([\w$.,\s\\]+?)(?=\s+(?:implements|with)\b|\s*$|\s*\{)/); grab(/\bwith\s+([\w$.,\s]+?)(?=\s+implements\b|\s*$)/); grab(/\bon\s+([\w$.,\s]+?)\s*$/); grab(/\bimplements\s+([\w$.,\s\\]+)/); grab(/^\s*:\s*([\w$.,\s()]+)/); grab(/^\s*\(([\w$.,\s]+)\)\s*$/);
        return {name: m[2], kw: m[1] === "mixin" ? "abstract" : m[1] === "actor" ? "class" : m[1], bases, abstract: /\babstract\b/.test(h)};
    }
    function funcHead(h, lang) {
        let m;
        if (lang === "go" && (m = /\bfunc\s*\(\s*(\w+)?\s*\*?\s*([A-Za-z_]\w*)(?:\[[^\]]*\])?\s*\)\s*([A-Za-z_]\w*)\s*\(/.exec(h))) return {name: m[3], recv: m[2], self: m[1]};
        if ((m = /\b(?:fn|func|fun|function|def)\s*\*?\s+(?:<[^>]*>\s*)?([A-Za-z_$][\w$]*)\s*(?:<[^()]*>)?\s*\(/.exec(h))) return {name: m[1]};
        if ((m = /(?:^|[\s,;(])([A-Za-z_$][\w$]*)\s*(?::[^=;]*)?=\s*(?:async\s*)?(?:function\b[^(]*\(|(?:<[^>]*>)?\([^()]*\)\s*(?::[^=]*)?=>|[A-Za-z_$][\w$]*\s*=>)/.exec(h))) return {name: m[1]};
        if ((m = /([A-Za-z_$][\w$]*)\s*(?:<[^()]*>)?\s*\((?:[^()]|\([^()]*\))*\)\s*(?:(?::|->)\s*[^{;]*|throws\s+[^{]*|where\s+[^{]*|const|override|async|noexcept)*\s*$/.exec(h)) && !KEYWORDS.has(m[1]) && !/\b(new|return|=)\s*$/.test(h.slice(0, m.index))) return {name: m[1]};
        return null;
    }
    function scopeHead(h, lang) {
        let m;
        if ((m = /\b(?:namespace|module|mod)\s+([\w.\\:]+)\s*$/.exec(h))) return {ns: m[1].replace(/\\/g, ".")};
        if (lang === "rs" && (m = /\bimpl(?:<[^>]*>)?\s+(?:([\w:]+)(?:<[^>]*>)?\s+for\s+)?([\w:]+)(?:<[^>]*>)?\s*(?:where[\s\S]*)?$/.exec(h))) return {impl: m[2].split("::").pop(), trait: m[1] ? m[1].split("::").pop() : null};
        if ((lang === "swift" || lang === "dart") && (m = /\bextension\s+(?:\w+\s+on\s+)?([\w.]+)(?:<[^>]*>)?(?:\s*:\s*([\w., ]+))?(?:\s+where[\s\S]*)?$/.exec(h))) return {impl: m[1].split(".").pop(), traits: (m[2] || "").split(",").map(x => x.trim()).filter(Boolean)};
        return null;
    }
    const lateImpls = []; // [type name, base name]: Elixir defimpl / Haskell instance, resolved once all the types are known
    function endBlocks(f, lang, code, x) { // blocks closed by "end": Lua (function / if / for / while / do / repeat ... until), Julia, Elixir (do ... end, fn ... end)
        const lines = code.split("\n"), stack = [];
        const TOK = lang === "lua" ? /\b(function|if|for|while|do|repeat|end|until)\b/g : lang === "jl" ? /\b(function|struct|module|baremodule|if|for|while|let|begin|do|try|macro|quote|end)\b/g : /\bdo\b(?!:)|\bfn\b|\bend\b/g;
        const close = (li) => {
            const s = stack.pop();
            if (s && s.owner) bodies.push({owner: s.owner, cls: s.cls, body: lines.slice(s.line + 1, li).join("\n"), selfs: ["self"]});
        };
        const clsOfStack = () => { for (let k = stack.length - 1; k >= 0; k--) if (stack[k].clsId) return stack[k].clsId; return null; };
        for (let li = 0; li < lines.length; li++) {
            let l = lines[li], m, def = null;
            if (lang === "jl") { for (let k = 0; k < 4; k++) l = l.replace(/\[[^\[\]]*\]/g, "[]").replace(/\([^()]*\bfor\b[^()]*\)/g, "()"); }
            const cls = clsOfStack();
            if (lang === "lua") {
                if ((m = /^\s*(?:local\s+)?function\s+([\w.:]+)\s*\(/.exec(l)) || (m = /^\s*(?:local\s+)?([\w.:]+)\s*=\s*function\s*\(/.exec(l))) {
                    const parts = m[1].split(/[.:]/), name = parts.pop(), owner = parts.pop();
                    if (owner && /^[A-Z]/.test(owner)) { const ids = classByName.get(owner); const c = ids ? ids[0] : x.addClass({name: owner, kw: "class", bases: []}); def = {owner: name === "new" || name === "init" ? c : x.addMethod(c, name), cls: c}; }
                    else def = {owner: x.addFn(name)};
                } else if ((m = /^\s*(?:local\s+)?([A-Z]\w*)\s*=\s*(?:\{\s*\}|setmetatable\s*\(|class\s*\(|(?:\w+\.)?(?:extend|subclass)\s*\()/.exec(l))) {
                    if (!classByName.has(m[1])) { const base = /(?:class\s*\(\s*["']?\w*["']?\s*,\s*|(\w+)[:.](?:extend|subclass)\s*\()(\w+)?/.exec(l); x.addClass({name: m[1], kw: "class", bases: base && (base[1] || base[2]) && /^[A-Z]/.test(base[1] || base[2]) ? [base[1] || base[2]] : []}); }
                }
            } else if (lang === "jl") {
                if ((m = /^\s*(?:mutable\s+)?struct\s+(\w+)(?:\{[^}]*\})?(?:\s*<:\s*(\w+))?/.exec(l))) def = {clsId: x.addClass({name: m[1], kw: "struct", bases: m[2] ? [m[2]] : []})};
                else if ((m = /^\s*(abstract|primitive)\s+type\s+(\w+)(?:\{[^}]*\})?(?:\s*<:\s*(\w+))?/.exec(l))) { x.addClass({name: m[2], kw: "interface", bases: m[3] ? [m[3]] : []}); continue; }
                else if ((m = /^\s*function\s+(?:[\w.]+\.)?([\w!]+)\s*[({]/.exec(l))) def = {owner: x.addFn(m[1])};
                else if (!stack.some(s => s.owner) && (m = /^([\w!]+)\s*\([^=]*\)\s*=[^=]/.exec(l))) { const id = x.addFn(m[1]); bodies.push({owner: id, body: l.slice(l.indexOf("=") + 1)}); }
            } else if (lang === "ex") {
                if ((m = /^\s*(defmodule|defprotocol)\s+([\w.]+)\s+do\b/.exec(l))) def = {clsId: x.addClass({name: m[2].split(".").pop(), kw: m[1] === "defprotocol" ? "interface" : "class", bases: []})};
                else if ((m = /^\s*defimpl\s+([\w.]+)\s*,\s*for:\s*([\w.]+)/.exec(l))) { lateImpls.push([m[2].split(".").pop(), m[1].split(".").pop()]); def = {}; }
                else if ((m = /^\s*(?:def|defp|defmacro|defmacrop)\s+([\w?!]+)/.exec(l))) {
                    const owner = cls ? x.addMethod(cls, m[1]) : x.addFn(m[1]);
                    if (/,\s*do:/.test(l)) { bodies.push({owner, cls, body: l.slice(l.indexOf("do:") + 3)}); continue; }
                    def = {owner, cls};
                }
            }
            let first = true, pendingDo = false;
            const toks = (lang === "jl" && /^\s*(abstract|primitive)\s+type\b/.test(l)) ? [] : (l.match(TOK) || []);
            for (const tk of toks) {
                if (tk === "end" || tk === "until") { close(li); continue; }
                if (lang === "lua" && tk === "do" && pendingDo) { pendingDo = false; continue; }
                if (lang === "lua" && (tk === "for" || tk === "while")) pendingDo = true;
                stack.push(Object.assign({line: li}, first && def ? def : {}));
                first = false;
            }
        }
        while (stack.length) close(lines.length);
    }
    function haskell(f, code, x) { // module, data / newtype (struct), class (interface), instance (base), top-level functions and their bodies
        const lines = code.split("\n");
        let cur = null, start = 0, buf = [];
        const flush = (li) => { if (cur) bodies.push({owner: cur, body: buf.join("\n"), bare: true}); cur = null; buf = []; };
        for (let li = 0; li < lines.length; li++) {
            const l = lines[li];
            let m;
            if (/^\s/.test(l) || !l.trim()) { if (cur) buf.push(l); continue; }
            if ((m = /^(?:data|newtype)\s+(?:[\w\s]*=>\s*)?([A-Z]\w*)/.exec(l))) { flush(li); x.addClass({name: m[1], kw: "struct", bases: []}); continue; }
            if ((m = /^class\s+(?:\([^)]*\)\s*=>\s*|[\w\s]+=>\s*)?([A-Z]\w*)/.exec(l))) { flush(li); x.addClass({name: m[1], kw: "interface", bases: []}); continue; }
            if ((m = /^instance\s+(?:\([^)]*\)\s*=>\s*|[\w\s]+=>\s*)?([A-Z]\w*)\s+\(?([A-Z]\w*)/.exec(l))) { flush(li); lateImpls.push([m[2], m[1]]); continue; }
            if ((m = /^([a-z_][\w']*)\s*::/.exec(l))) { flush(li); x.addFn(m[1]); continue; }
            if ((m = /^([a-z_][\w']*)\b[^=]*?=(?!=)/.exec(l)) && !/^(import|module|type|infix[lr]?|deriving|where|let|in)\b/.test(l)) {
                flush(li);
                cur = nodes.has("fn:" + f.path.replace(/\.\w+$/, "") + "::" + m[1]) ? "fn:" + f.path.replace(/\.\w+$/, "") + "::" + m[1] : x.addFn(m[1]);
                buf = [l.slice(l.indexOf("=") + 1)];
                continue;
            }
            flush(li);
        }
        flush(lines.length);
    }
    function shell(f, code, x) { // functions name() { ... } / function name { ... }, their bodies (commands = calls)
        const lines = code.split("\n");
        let cur = null, depth = 0, buf = [];
        for (const l of lines) {
            const s = l.replace(/\$\{[^}]*\}/g, "").replace(/\$\([^)]*\)/g, "");
            const m = !cur && (/^\s*(?:function\s+)?([\w:.-]+)\s*\(\s*\)\s*\{?/.exec(s) || /^\s*function\s+([\w:.-]+)\s*\{?/.exec(s));
            if (m) { cur = x.addFn(m[1]); depth = 0; buf = []; }
            if (cur) {
                depth += (s.match(/\{/g) || []).length - (s.match(/\}/g) || []).length;
                buf.push(s);
                if (depth <= 0 && /\}/.test(s)) { bodies.push({owner: cur, body: buf.join("\n"), bare: true}); cur = null; }
            }
        }
    }
    function objc(f, code, x) { // @interface / @protocol / @implementation, methods, message sends
        let m, cls = null;
        const re = /@(interface|protocol|implementation)\s+(\w+)(?:\s*:\s*(\w+))?(?:\s*\([^)]*\))?(?:\s*<([^>]+)>)?|^[ \t]*[-+]\s*\([^)]*\)\s*(\w+)[^{;]*\{|@end/gm;
        while ((m = re.exec(code))) {
            if (m[0] === "@end") { cls = null; continue; }
            if (m[1]) {
                const ids = classByName.get(m[2]);
                cls = ids ? ids[0] : x.addClass({name: m[2], kw: m[1] === "protocol" ? "interface" : "class", bases: [m[3], ...(m[4] || "").split(",")].map(b => (b || "").trim()).filter(b => b && b !== "NSObject")});
                continue;
            }
            if (m[5] && cls) {
                let depth = 1, i = re.lastIndex;
                for (; i < code.length && depth; i++) { if (code[i] === "{") depth++; else if (code[i] === "}") depth--; }
                const owner = /^(init|dealloc)/.test(m[5]) ? cls : x.addMethod(cls, m[5]);
                bodies.push({owner, cls, body: code.slice(re.lastIndex, i).replace(/\[\s*(\w+)\s+(\w+)/g, " $1.$2("), selfs: ["self"]}); // [obj msg] -> obj.msg(
                re.lastIndex = i;
            }
        }
    }
    function headOf(raw) { // the statement before a "{": its last line + the lines it continues (newline-terminated languages)
        const lines = raw.split("\n").map(l => l.trim()).filter(Boolean);
        if (!lines.length) return "";
        let k = lines.length - 1;
        while (k > 0 && (/[,(&|+\-*\/=:<>?]$/.test(lines[k - 1]) || /^([).:?,]|extends\b|implements\b|where\b|throws\b|->|=>)/.test(lines[k]))) k--;
        return lines.slice(k).join(" ");
    }
    for (const f of others) {
        const lang = langOf(f.path);
        if (!lang) continue;
        const src = /\.(vue|svelte)$/.test(f.path) ? f.text.replace(/<script\b[^>]*>([\s\S]*?)<\/script>|[^<]+|</g, (m0, s) => s !== undefined ? s : m0.replace(/[^\n]/g, "")) : f.text;
        const code = stripOther(src, lang), fileId = "file:" + f.path, group = groupOf(f.path);
        const pkg = (/^\s*(?:package|namespace)\s+([\w.\\]+)/m.exec(code) || [])[1];
        const nsBase = pkg ? pkg.replace(/\\/g, ".") : f.path.replace(/\.\w+$/, "");
        const addFn = (name, start, extra) => {
            const id = "fn:" + nsBase + "::" + name;
            node(id, "function", name + "()", Object.assign({group, path: f.path, ns: pkg || ""}, extra || {}));
            link(fileId, id, "defines");
            return id;
        };
        const addClass = (c, parentId) => {
            const id = (parentId || "cls:" + nsBase) + "::" + c.name;
            let kind = c.kw === "interface" || c.kw === "trait" || c.kw === "protocol" ? "interface" : c.kw === "enum" ? "enum" : c.kw === "struct" || c.kw === "record" ? "struct" : c.abstract ? "abstract" : "class";
            if (kind === "class" && c.bases.some(b => /^(ABC|Protocol)$/.test(b))) kind = /Protocol/.test(c.bases.join()) ? "interface" : "abstract";
            node(id, kind, c.name, {group, path: f.path, ns: pkg || ""});
            addClassName(c.name, id);
            link(parentId || fileId, id, parentId ? "member" : "defines");
            for (const b of c.bases) if (!/^(object|Object|ABC|Protocol|Generic|Enum|Exception|Error)$/.test(b)) pendingBases.push([id, b]);
            return id;
        };
        const addMethod = (clsId, name) => {
            const id = clsId + "::" + name;
            const n = node(id, "method", name + "()", {group, path: f.path, overloads: 0});
            n.overloads++;
            link(clsId, id, "member");
            return id;
        };
        if (lang === "py" || lang === "rb") { // indentation (Python) / keyword ... end (Ruby)
            const lines = code.split("\n"), stack = []; // {indent, type, id, end}
            const indentOf = (l) => l.length - l.trimStart().length;
            const closeBodies = (upto, li) => { while (stack.length && (lang === "py" ? stack[stack.length - 1].indent >= upto : false)) finish(stack.pop(), li); };
            const finish = (s, li) => { if (s.type === "def" && s.owner) bodies.push({owner: s.owner, cls: s.cls, body: lines.slice(s.line + 1, li).join("\n"), selfs: ["self", "cls", "this"]}); };
            for (let li = 0; li < lines.length; li++) {
                const l = lines[li], tr = l.trim();
                if (!tr) continue;
                const ind = indentOf(l);
                if (lang === "py") closeBodies(ind, li);
                else if (/^end\b/.test(tr)) { const s = stack.pop(); if (s) finish(s, li); continue; }
                const cls = [...stack].reverse().find(s => s.type === "class");
                const inDef = stack.some(s => s.type === "def");
                let m;
                if ((m = lang === "py" ? /^class\s+(\w+)\s*(?:\(([^)]*)\))?\s*:/.exec(tr) : /^class\s+(?:<<\s*self|([A-Z]\w*(?:::\w+)*)\s*(?:<\s*([\w:]+))?)/.exec(tr))) {
                    if (!m[1]) { stack.push({indent: ind, type: "block", line: li}); continue; }
                    const name = m[1].split("::").pop(), bases = (m[2] || "").split(",").map(b => b.replace(/\[.*$/, "").replace(/=.*$/, "").trim().split(/[.:]/).pop()).filter(b => /^\w+$/.test(b));
                    stack.push({indent: ind, type: "class", id: inDef ? null : addClass({name, kw: "class", bases}, cls && cls.id), line: li});
                } else if (lang === "py" && !ind && /^if\s+__name__\s*==\s*(""|'')\s*:/.test(tr)) { // script entry point
                    const id = "fn:main@" + f.path;
                    node(id, "function", "main()", {group, path: f.path, entry: true});
                    link(fileId, id, "defines");
                    stack.push({indent: ind, type: "def", owner: id, line: li});
                } else if ((m = lang === "py" ? /^(?:async\s+)?def\s+(\w+)\s*\(/.exec(tr) : /^def\s+(?:self\.)?([\w?!=]+)/.exec(tr))) {
                    let owner = null;
                    if (!inDef) owner = cls && cls.id ? (m[1] === "__init__" || m[1] === "initialize" ? cls.id : addMethod(cls.id, m[1])) : addFn(m[1]);
                    stack.push({indent: ind, type: "def", owner, cls: cls && cls.id, line: li});
                    if (lang === "rb" && /^def\s.*=\s*\S/.test(tr) && !/\bdo\b/.test(tr)) finish(stack.pop(), li + 1); // endless method
                } else if (lang === "rb" && (/^(module|if|unless|while|until|case|begin|for)\b/.test(tr) || /\bdo(\s*\|[^|]*\|)?\s*$/.test(tr))) {
                    stack.push({indent: ind, type: "block", line: li});
                }
            }
            if (lang === "py") closeBodies(-1, lines.length);
            continue;
        }
        if (lang === "lua" || lang === "jl" || lang === "ex") { endBlocks(f, lang, code, {addFn, addClass, addMethod, group, fileId}); continue; }
        if (lang === "hs") { haskell(f, code, {addFn, addClass, fileId}); continue; }
        if (lang === "sh") { shell(f, code, {addFn}); continue; }
        if (lang === "objc") { objc(f, code, {addClass, addMethod}); continue; }
        // brace languages
        const stack = [];
        let head = "", skip = 0, body = null;
        const curClass = () => { for (let k = stack.length - 1; k >= 0; k--) if (stack[k].cls) return stack[k].cls; return null; };
        for (let i = 0; i < code.length; i++) {
            const c = code[i];
            if (skip) {
                if (c === "{") skip++;
                else if (c === "}" && !--skip) { head = ""; if (body) { bodies.push(Object.assign(body, {body: code.slice(body.start, i)})); body = null; } }
                continue;
            }
            if (c === "{") {
                const h = headOf(head).replace(/\s+/g, " ").replace(/@\w+(?:\([^)]*\))?\s*/g, "").replace(/\[[\w(), ."=]+\]\s*/g, "").trim();
                head = "";
                let x;
                if ((x = classHead(h, lang))) { stack.push({cls: addClass(x, curClass()), close: true}); continue; }
                if ((x = scopeHead(h, lang))) {
                    if (x.impl) { // Rust impl block: the methods belong to the type
                        const target = classByName.get(x.impl);
                        const id = target ? target[0] : null;
                        if (id && x.trait && !(lang === "rs" && RUST_STD.has(x.trait))) pendingBases.push([id, x.trait]); // std traits (Debug, Clone...) are not dependencies
                        if (id && x.traits) for (const tr of x.traits) pendingBases.push([id, tr]);
                        stack.push({cls: id, implName: x.impl, close: true});
                    } else stack.push({ns: x.ns, close: true});
                    continue;
                }
                if ((x = funcHead(h, lang)) && !/=\s*$/.test(h)) {
                    const cls = curClass(), impl = [...stack].reverse().find(s => s.implName);
                    let owner = null, ownerCls = cls;
                    if (x.recv) { const ids = classByName.get(x.recv); ownerCls = ids ? ids[0] : null; owner = ownerCls ? addMethod(ownerCls, x.name) : null; }
                    else if (cls) owner = /^(constructor|__construct|init)$/.test(x.name) || (classHead("class " + x.name, lang) && nodes.get(cls).label === x.name) ? cls : addMethod(cls, x.name);
                    else if (impl && !impl.cls) owner = null; // impl of a type declared in another file: resolved below
                    else owner = addFn(x.name);
                    body = {owner, cls: ownerCls, start: i + 1, selfs: ["this", "self", x.self].filter(Boolean)};
                    if (!owner) Object.assign(body, {late: {type: x.recv || impl.implName, name: x.name, addMethod, addFn}});
                    skip = 1;
                    continue;
                }
                stack.push({close: true}); // other block (object literal, if, ...): its content is read
                continue;
            }
            if (c === "}") { stack.pop(); head = ""; continue; }
            if (c === ";") { head = ""; continue; }
            head += c;
            if (head.length > 600) head = head.slice(-400);
        }
    }
    for (const [type, base] of lateImpls) { const ids = classByName.get(type); if (ids) for (const id of ids) pendingBases.push([id, base]); }
    // Objective-C classes declared in the headers (.h read as C / C++)
    for (const f of files) if (/\.h$/.test(f.path) && /@(interface|protocol)\b/.test(f.text)) {
        const fileId = "file:" + f.path, group = groupOf(f.path);
        objc(f, f.text, {addClass: (c) => { const id = "cls:" + f.path.replace(/\.\w+$/, "") + "::" + c.name; node(id, c.kw === "interface" ? "interface" : "class", c.name, {group, path: f.path}); addClassName(c.name, id); link(fileId, id, "defines"); for (const b of c.bases) pendingBases.push([id, b]); return id; }, addMethod: () => null});
    }
    // Go receivers / Rust impl blocks of a type declared in another file
    for (const b of bodies) if (b.late) {
        const ids = classByName.get(b.late.type);
        b.cls = ids ? ids[0] : null;
        b.owner = b.cls ? b.late.addMethod(b.cls, b.late.name) : b.late.addFn(b.late.name);
        delete b.late;
    }
    // entry points of the other languages: main() / Main()
    for (const n of nodes.values()) if ((n.kind === "function" || n.kind === "method") && /^(main|Main)\(\)$/.test(n.label)) n.entry = true;

    for (const [cls, base] of pendingBases) {
        const ids = classByName.get(base);
        if (ids) for (const id of ids) link(cls, id, "inherits");
        else {
            const ext = /^std$|^[a-z]/.test(base) ? null : base;
            if (ext) { node("cls:?" + base, "external", base, {group: "external", external: true}); link(cls, "cls:?" + base, "inherits"); }
        }
    }
    for (const [fileId, owner] of pendingImpl) {
        const ids = classByName.get(owner);
        if (ids) for (const id of ids) link(fileId, id, "implements");
    }

    // Calls: the bodies of the functions / methods, resolved by name on the functions, methods and classes of the project
    const fnByName = new Map(), methodByName = new Map();
    const add = (m, k, v) => { if (!m.has(k)) m.set(k, []); m.get(k).push(v); };
    for (const n of nodes.values()) {
        if (n.kind === "function" && !n.entry) add(fnByName, n.label.replace(/\(\)$/, ""), n.id);
        if (n.kind === "method") add(methodByName, n.label.replace(/\(\)$/, ""), n.id);
    }
    const clsOf = (methodId) => methodId.slice(0, methodId.lastIndexOf("::"));
    for (const b of bodies) if (b.cls) {
        const fre = /\b(?:self|this)\s*(?:\.|->)\s*(\w+)\s*=\s*(?:new\s+)?([A-Z]\w*)\s*[({]/g;
        let m;
        while ((m = fre.exec(b.body))) if (classByName.has(m[2])) { if (!fields.has(b.cls)) fields.set(b.cls, new Map()); fields.get(b.cls).set(m[1], m[2]); }
    }
    for (const b of bodies) {
        let owners = b.owner ? [b.owner] : [], cls = b.cls || null;
        if (b.className) { // Class::method defined in a source
            const ids = classByName.get(b.className) || [];
            owners = ids.map(c => b.name === b.className || b.name === "~" + b.className ? c : c + "::" + b.name).filter(id => nodes.has(id));
            cls = ids[0] || null;
        }
        if (!owners.length) continue;
        const group = nodes.get(owners[0]).group, inTests = isTest(nodes.get(owners[0]).path || "");
        const selfs = b.selfs || ["this"];
        const targets = new Set();
        // types of the local variables (Type name; Type name(...); Type *name = ...) and of the fields of the class
        const vars = new Map(cls && fields.get(cls) ? fields.get(cls) : []);
        const vre = /\b(?:[\w]+::)*([A-Z]\w*)\s*(?:<[^<>;(){}]*>)?\s*[&*]*\s+([A-Za-z_]\w*)\s*[;({=]/g;
        let v;
        while ((v = vre.exec(b.body))) if (classByName.has(v[1])) vars.set(v[2], v[1]);
        const are = /\b([A-Za-z_$][\w$]*)\s*(?::\s*[\w<>\[\], ]+)?\s*(?::=|=)\s*(?:new\s+|&)?([A-Z][\w$]*)\s*(?:<[^<>;]*>)?\s*[({]/g; // x = Type(...) / new Type / &Type{}
        while ((v = are.exec(b.body))) if (classByName.has(v[2])) vars.set(v[1], v[2]);
        const typed = (q) => { const ty = q && vars.get(q); return ty && classByName.has(ty) ? classByName.get(ty) : null; };
        const re = /(?:\b([A-Za-z_]\w*)\s*(::|\.|->)\s*)?\b(~?[A-Za-z_]\w*)\s*(?:<([^<>;(){}]*)>)?\s*\(/g;
        let m;
        while ((m = re.exec(b.body))) {
            const [, qual, op, name, targs] = m;
            if (SKIPNAMES.has(name) || qual === "std" || ATTR.test(name)) continue;
            if (/^make_(unique|shared)$/.test(name) && targs) { // std::make_unique<Class>(...)
                const c = classByName.get(targs.trim().split("::").pop());
                if (c) c.forEach(x => targets.add(x));
                continue;
            }
            let cands = [];
            if (op === "::" && qual === "Self" && cls && nodes.has(cls + "::" + name)) cands = [cls + "::" + name]; // Rust Self::f()
            else if (op === "::" && classByName.has(qual)) cands = classByName.get(qual).map(c => c + "::" + name).filter(id => nodes.has(id));
            else if (!op) {
                if (cls && nodes.has(cls + "::" + name)) cands = [cls + "::" + name]; // this->method()
                else if (fnByName.has(name)) cands = fnByName.get(name);
                else if (classByName.has(name)) cands = classByName.get(name); // construction
            } else if (op === "::") cands = (fnByName.get(name) || []).filter(id => id.endsWith(qual + "::" + name));
            else if (selfs.includes(qual) && cls && nodes.has(cls + "::" + name)) cands = [cls + "::" + name]; // this.method() / self.method()
            else if (classByName.has(qual) && classByName.get(qual).some(c => nodes.has(c + "::" + name))) cands = classByName.get(qual).map(c => c + "::" + name).filter(id => nodes.has(id)); // Class.static() / Module.fn()
            else if (typed(qual)) cands = typed(qual).map(c => c + "::" + name).filter(id => nodes.has(id)); // typed object
            else { // object.method() / ptr->method() of an unknown type: unique name, else another class of the same group
                const all = methodByName.get(name) || [];
                cands = all.length === 1 ? all : all.filter(id => nodes.get(id).group === group && clsOf(id) !== cls);
                if (cands.length > 2) cands = [];
                if (!all.length && fnByName.has(name) && fnByName.get(name).length <= 2) cands = fnByName.get(name); // module.function()
            }
            if (!inTests) cands = cands.filter(id => !isTest(nodes.get(id).path || "")); // the sources never call the tests
            if (cands.length <= 3) cands.forEach(x => targets.add(x));
        }
        if (b.bare) { // languages calling without parentheses: every word that is a function of the project
            for (const w of new Set(b.body.match(/[A-Za-z_][\w'.-]*/g) || [])) { const c = fnByName.get(w); if (c && c.length <= 2) c.forEach(x => targets.add(x)); }
        }
        for (const o of owners) for (const x of targets) link(o, x, "calls");
    }

    // Tests: test cases + tested classes
    const classNames = [...classByName.keys()].filter(n => n.length > 2);
    for (const f of files) {
        if (!(isTest(f.path) || /\.zig$/.test(f.path)) || !(CODE.test(f.path) || langOf(f.path))) continue;
        const fileId = "file:" + f.path;
        const lang = CODE.test(f.path) ? "c" : langOf(f.path);
        const RE = {
            c: [/\b(?:TEST|TEST_F|TEST_P|TYPED_TEST)\s*\(\s*(\w+)\s*,\s*(\w+)\s*\)/g, m => m[1] + "." + m[2]],
            py: [/^[ \t]*(?:async\s+)?def\s+(test\w*)\s*\(/gm, m => m[1]],
            js: [/\b(?:it|test)(?:\.(?:only|skip|each\([^)]*\)))?\s*\(\s*(["'`])(.+?)\1/g, m => m[2]],
            go: [/^func\s+(Test\w+|Benchmark\w+)\s*\(/gm, m => m[1]],
            rs: [/#\[(?:tokio::)?test\][\s\S]{0,80}?\bfn\s+(\w+)/g, m => m[1]],
            java: [/@(?:Test|ParameterizedTest)\b[\s\S]{0,200}?\b(?:void|fun)\s+`?([\w ]+?)`?\s*\(/g, m => m[1]],
            cs: [/\[(?:Fact|Theory|Test|TestMethod|TestCase)\b[^\]]*\][\s\S]{0,200}?\s(\w+)\s*\(/g, m => m[1]],
            php: [/function\s+(test\w*)\s*\(/g, m => m[1]],
            rb: [/\b(?:it|test|scenario|specify)\s*\(?\s*["'](.+?)["']/g, m => m[1]],
            zig: [/^\s*test\s+"([^"]+)"\s*\{/gm, m => m[1]],
            swift: [/\bfunc\s+(test\w*)\s*\(|@Test(?:\s*\(\s*"([^"]+)")?[\s\S]{0,120}?\bfunc\s+(\w+)/g, m => m[1] || m[2] || m[3]],
            dart: [/\b(?:test|testWidgets)\s*\(\s*(["'])(.+?)\1/g, m => m[2]],
            lua: [/\bit\s*\(\s*(["'])(.+?)\1/g, m => m[2]],
            jl: [/@testset\s+"(.+?)"/g, m => m[1]],
            ex: [/^\s*test\s+"(.+?)"/gm, m => m[1]],
            hs: [/\bit\s+"(.+?)"/g, m => m[1]],
            objc: [/-\s*\(void\)\s*(test\w*)/g, m => m[1]],
            sh: [/@test\s+["'](.+?)["']/g, m => m[1]]
        }[lang];
        let m;
        if (RE) while ((m = RE[0].exec(f.text))) {
            const label = RE[1](m).slice(0, 70);
            const id = "test:" + f.path + ":" + label;
            node(id, "test", label, {group: groupOf(f.path), path: f.path});
            link(fileId, id, "defines");
        }
        const words = new Set(f.text.match(/[A-Za-z_]\w*/g) || []);
        for (const name of classNames) if (words.has(name)) for (const id of classByName.get(name)) link(fileId, id, "tests");
    }

    // CMake: targets, sources, linked libraries
    const vars = {CMAKE_SOURCE_DIR: "", CMAKE_CURRENT_SOURCE_DIR: "", PROJECT_SOURCE_DIR: ""};
    const targets = new Set();
    function expand(s, v) {
        for (let k = 0; k < 10 && /\$\{\w+\}/.test(s); k++) s = s.replace(/\$\{(\w+)\}/g, (_, x) => v[x] !== undefined ? v[x] : "");
        return s;
    }
    function args(s, v) {
        const out = [];
        for (const tok of s.match(/"[^"]*"|[^\s"]+/g) || []) {
            const e = expand(tok.replace(/^"|"$/g, ""), v);
            for (const p of e.split(";")) if (p) out.push(p);
        }
        return out;
    }
    function cmakeCommands(text) {
        const clean = text.replace(/"[^"]*"|#[^\n]*/g, m => m[0] === "#" ? "" : m);
        const cmds = [];
        const re = /([A-Za-z_]\w*)\s*\(/g;
        let m;
        while ((m = re.exec(clean))) {
            let depth = 1, i = re.lastIndex;
            for (; i < clean.length && depth; i++) { if (clean[i] === "(") depth++; else if (clean[i] === ")") depth--; }
            cmds.push([m[1].toLowerCase(), clean.slice(re.lastIndex, i - 1)]);
            re.lastIndex = i;
        }
        return cmds;
    }
    function runCMake(dir, v, depth) {
        const path = (dir ? dir + "/" : "") + "CMakeLists.txt";
        if (!byPath.has(path) || depth > 4) return;
        v = Object.assign({}, v, {CMAKE_CURRENT_SOURCE_DIR: dir});
        const cmds = cmakeCommands(byPath.get(path).text);
        const exec = (list) => {
            for (let k = 0; k < list.length; k++) {
                const [name, raw] = list[k];
                if (name === "foreach") {
                    let d = 1, e = k + 1;
                    for (; e < list.length; e++) { if (list[e][0] === "foreach") d++; if (list[e][0] === "endforeach" && !--d) break; }
                    const a = args(raw, v);
                    const items = a[1] === "IN" ? a.slice(3) : a.slice(1);
                    for (const it of items) { v[a[0]] = it; exec(list.slice(k + 1, e)); }
                    k = e;
                    continue;
                }
                const a = args(raw, v);
                if (name === "set" && a.length) v[a[0]] = a.slice(1).filter(x => x !== "PARENT_SCOPE" && x !== "CACHE").join(";");
                else if (name === "list" && a[0] === "REMOVE_ITEM") v[a[1]] = (v[a[1]] || "").split(";").filter(x => !a.slice(2).includes(x)).join(";");
                else if (name === "list" && a[0] === "APPEND") v[a[1]] = [(v[a[1]] || ""), ...a.slice(2)].filter(Boolean).join(";");
                else if (name === "list" && a[0] === "TRANSFORM" && a[2] === "PREPEND") v[a[1]] = (v[a[1]] || "").split(";").filter(Boolean).map(x => a[3] + x).join(";");
                else if (name === "add_subdirectory" && a[0]) runCMake(normalize((dir ? dir + "/" : "") + a[0]), v, depth + 1);
                else if ((name === "add_executable" || name === "add_library") && a[0]) {
                    const tname = a[0];
                    const type = name === "add_executable" ? "executable" : "library";
                    targets.add(tname);
                    node("target:" + tname, type, tname, {group: "build"});
                    for (const s of a.slice(1)) {
                        if (/^(STATIC|SHARED|MODULE|INTERFACE|OBJECT|EXCLUDE_FROM_ALL|WIN32|IMPORTED)$/.test(s)) continue;
                        const p = normalize(s.startsWith("/") ? s.slice(1) : (dir && !s.startsWith(dir + "/") && !byPath.has(s) ? dir + "/" + s : s));
                        if (byPath.has(p)) link("file:" + p, "target:" + tname, "compiled-into");
                    }
                }
                else if (name === "target_link_libraries" && a[0]) {
                    for (const lib of a.slice(1)) {
                        if (/^(PRIVATE|PUBLIC|INTERFACE|debug|optimized|general)$/.test(lib) || lib.startsWith("$<") || lib.startsWith("-")) continue;
                        if (targets.has(lib)) { link("target:" + a[0], "target:" + lib, "links"); continue; }
                        let root = lib.includes("::") ? lib.split("::")[lib.toLowerCase().startsWith("pkgconfig::") ? 1 : 0] : lib;
                        root = root.toLowerCase().replace(/xx$/, "");
                        if (root === "ssl" || root === "crypto") root = "openssl";
                        node("ext:" + root, "external", root, {group: "external"});
                        link("target:" + a[0], "ext:" + root, "links");
                    }
                }
            }
        };
        exec(cmds);
    }
    runCMake("", vars, 0);
    // Packages of the other ecosystems: one target per manifest (its dependencies as externals, the files of its folder
    // compiled into it): package.json, pyproject.toml / setup.py / requirements.txt, go.mod, Cargo.toml, pom.xml,
    // build.gradle, *.csproj, composer.json, Gemfile / *.gemspec
    const pkgs = []; // {dir, id}
    function pkg(dir, name, type, deps) {
        const same = pkgs.find(p => p.dir === dir); // pyproject + setup.py, Gemfile + gemspec...: one package per folder
        if (same) { for (const d of deps || []) { const x = ext(d); if (x && d.toLowerCase() !== nodes.get(same.id).label.toLowerCase()) link(same.id, x, "links"); } return same.id; }
        const id = "target:" + name;
        node(id, type || "library", name, {group: "build"});
        if (!pkgs.some(p => p.id === id)) pkgs.push({dir, id});
        for (const d of deps || []) if (d && !/^(python|php|ext-.*|node)$/i.test(d)) { const x = nodes.has("target:" + d) ? "target:" + d : ext(d); if (x) link(id, x, "links"); }
        return id;
    }
    const tomlTable = (t, name) => { // lines of a [table] of a TOML file
        const out = [];
        let on = false;
        for (const l of t.split("\n")) { const h = /^\s*\[\[?([^\]]+)\]\]?\s*(#.*)?$/.exec(l); if (h) { on = h[1].trim() === name; continue; } if (on) out.push(l); }
        return out.join("\n");
    };
    const tomlKeys = (block) => (block.match(/^\s*([\w.-]+)\s*=/gm) || []).map(x => x.replace(/\s*=$/, "").trim());
    const reqName = (s) => s.trim().replace(/^["']|["']$/g, "").split(/[\s<>=!~;\[@]/)[0];
    const late = /^(Gemfile|requirements[\w.-]*\.txt|setup\.py)$/; // generic manifests after the ones that name the package
    for (const f of [...files].sort((a, b) => late.test(a.path.split("/").pop()) - late.test(b.path.split("/").pop()))) {
        const dir = dirname(f.path), base = f.path.split("/").pop(), t = f.text, dname = dir.split("/").pop() || null;
        try {
            if (base === "package.json") {
                const j = JSON.parse(t);
                pkg(dir, j.name || dname || "app", j.bin ? "executable" : "library", Object.keys(Object.assign({}, j.dependencies, j.peerDependencies)));
            } else if (base === "pyproject.toml") {
                const proj = tomlTable(t, "project"), poetry = tomlTable(t, "tool.poetry");
                const name = (/^\s*name\s*=\s*["']([^"']+)/m.exec(proj || poetry) || [])[1] || dname || "app";
                const arr = (/^\s*dependencies\s*=\s*\[([\s\S]*?)\]/m.exec(proj) || [])[1] || "";
                const deps = (arr.match(/["'][^"']+["']/g) || []).map(reqName).concat(tomlKeys(tomlTable(t, "tool.poetry.dependencies")));
                pkg(dir, name, tomlTable(t, "project.scripts") || tomlTable(t, "tool.poetry.scripts") ? "executable" : "library", deps);
            } else if (base === "setup.py") {
                const name = (/\bname\s*=\s*["']([^"']+)/.exec(t) || [])[1] || dname || "app";
                const arr = (/install_requires\s*=\s*\[([\s\S]*?)\]/.exec(t) || [])[1] || "";
                pkg(dir, name, /entry_points|scripts\s*=/.test(t) ? "executable" : "library", (arr.match(/["'][^"']+["']/g) || []).map(reqName));
            } else if (/^requirements[\w.-]*\.txt$/.test(base) && !/dev|test|doc/.test(base)) {
                const own = pkgs.find(p => p.dir === dir);
                const deps = t.split("\n").map(l => l.replace(/#.*/, "").trim()).filter(l => l && !l.startsWith("-")).map(reqName);
                if (own) for (const d of deps) link(own.id, ext(d), "links"); else pkg(dir, dname || "app", "executable", deps);
            } else if (base === "go.mod") {
                const mod = (/^module\s+(\S+)/m.exec(t) || [])[1] || dname || "app";
                const req = ((/^require\s*\(([\s\S]*?)\)/m.exec(t) || [])[1] || "") + "\n" + (t.match(/^require\s+[^(\s]\S*\s+\S+/gm) || []).join("\n").replace(/^require\s+/gm, "");
                const deps = req.split("\n").map(l => l.trim().split(/\s+/)[0]).filter(x => x && !x.startsWith("//") && /\//.test(x) && !/\/\/\s*indirect/.test(x)).map(x => { const s = x.split("/"); return /^v\d+$/.test(s[s.length - 1]) ? s[s.length - 2] : s[s.length - 1]; });
                pkg(dir, mod.split("/").pop(), "library", deps);
            } else if (base === "Cargo.toml") {
                const name = (/^\s*name\s*=\s*["']([^"']+)/m.exec(tomlTable(t, "package")) || [])[1];
                if (name) pkg(dir, name, byPath.has((dir ? dir + "/" : "") + "src/main.rs") || /\[\[bin\]\]/.test(t) ? "executable" : "library", tomlKeys(tomlTable(t, "dependencies")));
            } else if (base === "pom.xml") {
                const body = t.replace(/<parent>[\s\S]*?<\/parent>/, "").replace(/<dependencyManagement>[\s\S]*?<\/dependencyManagement>/, "").replace(/<build>[\s\S]*?<\/build>/, "");
                const name = (/<artifactId>([^<]+)<\/artifactId>/.exec(body) || [])[1] || dname || "app";
                const deps = [...body.matchAll(/<dependency>[\s\S]*?<artifactId>([^<]+)<\/artifactId>[\s\S]*?<\/dependency>/g)].map(m => m[1]);
                pkg(dir, name, "library", deps);
            } else if (/^build\.gradle(\.kts)?$/.test(base)) {
                const settings = byPath.get((dir ? dir + "/" : "") + "settings.gradle") || byPath.get((dir ? dir + "/" : "") + "settings.gradle.kts");
                const name = (settings && (/rootProject\.name\s*=\s*["']([^"']+)/.exec(settings.text) || [])[1]) || dname || "app";
                const deps = [...t.matchAll(/\b(?:implementation|api|compile|runtimeOnly|compileOnly|kapt|ksp)\s*\(?\s*["']([^:"']+):([^:"']+)/g)].map(m => m[2]);
                pkg(dir, name, /application\b|mainClass/.test(t) ? "executable" : "library", deps);
            } else if (/\.csproj$/.test(base)) {
                pkg(dir, base.replace(/\.csproj$/, ""), /<OutputType>\s*(Win)?Exe/i.test(t) ? "executable" : "library", [...t.matchAll(/<PackageReference\s+Include="([^"]+)"/g)].map(m => m[1]));
            } else if (base === "composer.json") {
                const j = JSON.parse(t);
                pkg(dir, (j.name || dname || "app").split("/").pop(), j.bin ? "executable" : "library", Object.keys(j.require || {}).map(k => k.split("/").pop()));
            } else if (base === "build.zig.zon") {
                const name = (/\.name\s*=\s*(?:\.@?"?|")([\w-]+)/.exec(t) || [])[1] || dname || "app";
                const dep = (/\.dependencies\s*=\s*\.\{([\s\S]*?)\n\s*\},?\s*\n\s*\.(?!\w+\s*=\s*\.\{)/.exec(t) || /\.dependencies\s*=\s*\.\{([\s\S]*)/.exec(t) || [])[1] || "";
                pkg(dir, name, byPath.has((dir ? dir + "/" : "") + "src/main.zig") ? "executable" : "library", [...dep.matchAll(/^\s*\.(@?"?[\w-]+"?)\s*=\s*\.\{/gm)].map(m => m[1].replace(/[@"]/g, "")));
            } else if (base === "Package.swift") {
                const name = (/\bname\s*:\s*"([^"]+)"/.exec(t) || [])[1] || dname || "app";
                const deps = [...t.matchAll(/\.package\s*\(\s*(?:name\s*:\s*"([^"]+)"[^)]*|url\s*:\s*"[^"]*\/([\w.-]+?)(?:\.git)?")/g)].map(m => m[1] || m[2]);
                pkg(dir, name, /\.executableTarget|\.executable\s*\(/.test(t) ? "executable" : "library", deps);
            } else if (base === "pubspec.yaml") {
                const name = (/^name:\s*(\S+)/m.exec(t) || [])[1] || dname || "app";
                const block = (/^dependencies:\s*\n((?:[ \t]+.*\n?|\s*\n)*)/m.exec(t) || [])[1] || "";
                pkg(dir, name, byPath.has((dir ? dir + "/" : "") + "lib/main.dart") || /^executables:/m.test(t) ? "executable" : "library", [...block.matchAll(/^[ \t]{2}(\w+):/gm)].map(m => m[1]).filter(d => !/^(flutter|sdk)$/.test(d)));
            } else if (/\.rockspec$/.test(base)) {
                const name = (/\bpackage\s*=\s*["']([^"']+)/.exec(t) || [])[1] || dname || "app";
                const arr = (/\bdependencies\s*=\s*\{([\s\S]*?)\}/.exec(t) || [])[1] || "";
                pkg(dir, name, "library", (arr.match(/["'][^"']+["']/g) || []).map(s => s.slice(1).split(/[\s<>=~]/)[0]).filter(d => d !== "lua"));
            } else if (base === "mix.exs") {
                const name = (/\bapp:\s*:(\w+)/.exec(t) || [])[1] || dname || "app";
                pkg(dir, name, /\bmod:\s*\{/.test(t) || /escript/.test(t) ? "executable" : "library", [...t.matchAll(/\{\s*:(\w+)\s*,/g)].map(m => m[1]));
            } else if (/\.cabal$/.test(base)) {
                const name = (/^name:\s*(\S+)/mi.exec(t) || [])[1] || base.replace(/\.cabal$/, "");
                const deps = [...t.matchAll(/build-depends:\s*([\s\S]*?)(?=\n\s*[\w-]+:|\n\S|$)/gi)].flatMap(m => m[1].split(",").map(d => d.trim().split(/[\s<>=^]/)[0])).filter(d => d && d !== "base" && d !== name);
                pkg(dir, name, /^executable\s/mi.test(t) ? "executable" : "library", [...new Set(deps)]);
            } else if (base === "Project.toml" && /\.jl$/.test(paths.find(p => p.startsWith(dir ? dir + "/" : "")) || ".jl") ) {
                const name = (/^\s*name\s*=\s*"([^"]+)"/m.exec(t) || [])[1] || dname || "app";
                pkg(dir, name, "library", tomlKeys(tomlTable(t, "deps")));
            } else if (base === "meson.build") { // C / C++ with Meson: executables / libraries, their sources, dependency('x')
                const name = (/\bproject\s*\(\s*'([^']+)'/.exec(t) || [])[1];
                if (name && !dir) pkg(dir, name, "library", []);
                const vars = {};
                for (const m of t.matchAll(/^\s*(\w+)\s*=\s*(?:files\s*\()?\[?([^\n\]]*(?:\n[^\n\]]*)*?)\]?\)?\s*$/gm)) vars[m[1]] = (m[2].match(/'([^']+\.(?:c|cc|cpp|cxx|m|mm))'/g) || []).map(s => s.slice(1, -1));
                for (const m of t.matchAll(/\b(executable|library|shared_library|static_library|both_libraries)\s*\(\s*'([^']+)'([\s\S]*?)\)\s*\n/g)) {
                    const id = "target:" + m[2];
                    node(id, m[1] === "executable" ? "executable" : "library", m[2], {group: "build"});
                    const srcs = (m[3].match(/'([^']+\.(?:c|cc|cpp|cxx|m|mm))'/g) || []).map(s => s.slice(1, -1)).concat(...(m[3].match(/\b\w+\b/g) || []).map(v => vars[v] || []));
                    for (const s of srcs) { const pth = normalize((dir ? dir + "/" : "") + s); if (byPath.has(pth)) link("file:" + pth, id, "compiled-into"); }
                    for (const d of m[3].matchAll(/\bdependency\s*\(\s*'([^']+)'/g)) { const x = ext(d[1]); if (x) link(id, x, "links"); }
                }
                for (const d of t.matchAll(/(\w+)\s*=\s*dependency\s*\(\s*'([^']+)'/g)) for (const m of t.matchAll(new RegExp("\\b(?:executable|library|shared_library|static_library)\\s*\\(\\s*'([^']+)'[^)]*\\b" + d[1] + "\\b", "g"))) { const x = ext(d[2]); if (x) link("target:" + m[1], x, "links"); }
            } else if (base === "Gemfile" || /\.(gemspec|podspec)$/.test(base)) {
                const name = (/\.name\s*=\s*["']([^"']+)/.exec(t) || [])[1] || (base === "Gemfile" ? dname || "app" : base.replace(/\.(gemspec|podspec)$/, ""));
                const deps = [...t.matchAll(/^\s*(?:gem|\w+\.add(?:_runtime)?_dependency)\s*\(?\s*["']([^"']+)["']/gm)].map(m => m[1]);
                const own = pkgs.find(p => p.dir === dir);
                if (own) for (const d of deps) link(own.id, ext(d), "links"); else pkg(dir, name, base === "Gemfile" ? "executable" : "library", deps);
            }
        } catch (e) { /* malformed manifest: skipped */ }
    }
    // files of the other languages -> the package of the closest folder; a package with an entry point is an executable
    for (const f of others) {
        if (!nodes.has("file:" + f.path)) continue;
        let best = null;
        for (const p of pkgs) if ((!p.dir || f.path.startsWith(p.dir + "/")) && (!best || p.dir.length > best.dir.length)) best = p;
        if (best) link("file:" + f.path, best.id, "compiled-into");
    }
    for (const p of pkgs) { // an import of a package of the repository (examples, workspaces) points to that package
        const e = "ext:" + nodes.get(p.id).label.toLowerCase();
        if (!nodes.has(e)) continue;
        for (const l of links) if (l.target === e) l.target = p.id;
        nodes.delete(e);
    }
    const entryPaths = new Set([...nodes.values()].filter(x => x.entry).map(x => x.path));
    for (const p of pkgs) {
        const n = nodes.get(p.id);
        if (n.kind === "library" && links.some(l => l.kind === "compiled-into" && l.target === p.id && entryPaths.has(nodes.get(l.source).path))) n.kind = "executable";
    }


    // Classes / functions / methods written in the tests are test helpers (fixtures, mocks)
    for (const n of nodes.values()) if (n.path && isTest(n.path) && !["test-file", "test", "page", "style"].includes(n.kind)) n.kind = "test-helper";

    // Degrees
    const deg = new Map();
    for (const l of links) { deg.set(l.source, (deg.get(l.source) || 0) + 1); deg.set(l.target, (deg.get(l.target) || 0) + 1); }
    const out = [...nodes.values()];
    for (const n of out) { n.degree = deg.get(n.id) || 0; if (!n.group) n.group = "root"; }
    return {nodes: out, links: links.filter(l => nodes.has(l.source) && nodes.has(l.target))};
}
// Files read by the extractor (build_graph.mjs and the update of the page use the same filter)
extractGraph.wanted = function (p) {
    if (/(^|\/)(build|_deps|third_party|vendor|external|\.git|docs|node_modules|dist|out|target|venv|\.venv|env|__pycache__|\.next|\.nuxt|\.svelte-kit|\.output|coverage|site-packages|bin|obj|\.idea|\.vscode|\.gradle|\.mypy_cache|\.pytest_cache|\.tox|Pods|DerivedData|\.build|\.dart_tool|_build|deps|\.stack-work|dist-newstyle|zig-cache|\.zig-cache|zig-out|Carthage|\.pub-cache)\//.test(p)) return false;
    if (/\.min\.(js|css)$|\.bundle\.js$|\.d\.ts\.map$/.test(p)) return false;
    return /\.(hpp|hh|hxx|h|tpp|inl|ipp|cpp|cc|cxx|c|pyi?|m?js|cjs|jsx|ts|tsx|mts|cts|vue|svelte|java|kt|kts|scala|groovy|cs|go|rs|php|rb|html?|css|scss|sass|less|zig|swift|dart|lua|jl|exs?|l?hs|mm?|sh|bash|zsh)$/.test(p) ||
        /(^|\/)(CMakeLists\.txt|package\.json|pyproject\.toml|setup\.py|requirements[\w.-]*\.txt|go\.mod|Cargo\.toml|pom\.xml|build\.gradle(\.kts)?|settings\.gradle(\.kts)?|composer\.json|Gemfile|[^/]+\.gemspec|[^/]+\.podspec|[^/]+\.csproj|build\.zig\.zon|Package\.swift|pubspec\.yaml|[^/]+\.rockspec|mix\.exs|[^/]+\.cabal|Project\.toml|meson\.build)$/.test(p);
};
// </extractor>

(function () {
    "use strict";
    const $ = (id) => document.getElementById(id);
    const CONFIG = JSON.parse($("graph-config").textContent);
    const tr = (s) => window.docI18n ? window.docI18n.tr(s) : s;
    let SNAPSHOT = JSON.parse($("graph-snapshot").textContent);
    let KEY = (CONFIG.storageKey || "doc") + "-graph"; // explorer: one key per repository
    const KINDS = {
        header: ["#5b8def", "Header"], source: ["#2fa36b", "Source"], "test-file": ["#d9822b", "Test file"],
        class: ["#8e6cf0", "Class"], struct: ["#a77bd9", "Struct"], interface: ["#e05a9b", "Interface"],
        abstract: ["#c44fd1", "Abstract"], enum: ["#c9a227", "Enum"], function: ["#20a4b8", "Function"],
        method: ["#7f8ea3", "Method"], test: ["#e0a458", "Test"], "test-helper": ["#b98a5e", "Test helper"], executable: ["#e5484d", "Executable"],
        library: ["#f07a3a", "Library"], external: ["#98a2b3", "External"], page: ["#d65f8c", "Page"], style: ["#5fb3d6", "Stylesheet"]
    };
    const LINKS = {
        includes: ["#8a909b", "includes / imports"], defines: ["#9aa5b8", "defines"], member: ["#a3acbd", "member"],
        inherits: ["#8e6cf0", "inherits"], implements: ["#2fa36b", "implements"], "compiled-into": ["#f07a3a", "compiled into"],
        links: ["#e5484d", "links"], tests: ["#d9822b", "tests"], calls: ["#3fb8a9", "calls"]
    };
    const KIND_INDEX = {}; // relation kind -> small integer (keys of the batches)
    Object.keys(LINKS).forEach((k, i) => { KIND_INDEX[k] = i; });
    const PRESETS = {
        overview: [["header", "source", "page", "class", "struct", "interface", "abstract", "enum", "function", "executable", "library", "external"], ["includes", "inherits", "defines", "compiled-into", "links"]],
        files: [["header", "source", "test-file", "page", "style", "external"], ["includes"]],
        classes: [["class", "struct", "interface", "abstract"], ["inherits"]],
        members: [["class", "struct", "interface", "abstract", "enum", "method"], ["inherits", "member"]],
        tests: [["test-file", "test", "test-helper", "class", "struct", "interface", "abstract"], ["tests", "defines", "inherits"]],
        build: [["source", "executable", "library", "external"], ["compiled-into", "links"]],
        all: [Object.keys(KINDS), Object.keys(LINKS)]
    };

    const canvas = $("graph"), ctx = canvas.getContext("2d");
    window.graphState = null; // set below, handy to inspect the graph from the console
    const VIEW = {yaw: 0.15, pitch: 0.22}; // default 3D angle: almost facing (X to the right, Z slightly to the left), seen a little from above (~13°; pitch > 0 = from above)
    const state = {
        data: {nodes: [], links: []}, byId: new Map(), pos: new Map(),
        kinds: new Set(PRESETS.overview[0]), linkKinds: new Set(PRESETS.overview[1]), groups: new Set(), knownGroups: new Set(),
        mode: "2d", colorBy: "kind", cluster: false, labels: true, particles: false, isolate: false, search: "",
        visible: [], vlinks: [], neighbors: new Map(), selected: null, hover: null,
        alpha: 1, paused: false, cam: {x: 0, y: 0, z: 0, k: 1, yaw: VIEW.yaw, pitch: VIEW.pitch, dist: 600}, style3d: "real", layoutV: 0, flowSel: new Set(), lock: null, flowView: "exec", flowRoot: null, flamePath: [], flow: null, flowHit: null, cams: {}, w: 0, h: 0, dpr: 1, colors: {}
    };

    window.graphState = state;

    // ---------- Storage (optional, never required) ---------- //
    function store(k, v) { try { localStorage.setItem(KEY + ":" + k, JSON.stringify(v)); } catch (e) { /* quota / private mode */ } }
    function load(k) { try { const v = localStorage.getItem(KEY + ":" + k); return v ? JSON.parse(v) : null; } catch (e) { return null; } }

    // ---------- Data ---------- //
    function setData(graph, meta) {
        state.data = graph;
        state.meta = meta || graph.meta || {};
        state.byId = new Map(graph.nodes.map(n => [n.id, n]));
        const groups = new Set(graph.nodes.map(n => n.group));
        for (const g of groups) if (!state.knownGroups.has(g)) { state.knownGroups.add(g); state.groups.add(g); }
        const r = Math.sqrt(graph.nodes.length) * 14 + 40;
        for (const n of graph.nodes) {
            if (!state.pos.has(n.id)) {
                const a = Math.random() * Math.PI * 2, b = Math.acos(2 * Math.random() - 1), d = r * Math.cbrt(Math.random());
                state.pos.set(n.id, {x: d * Math.sin(b) * Math.cos(a), y: d * Math.sin(b) * Math.sin(a), z: d * Math.cos(b), vx: 0, vy: 0, vz: 0});
            }
        }
        if (state.selected && !state.byId.has(state.selected)) state.selected = null;
        buildLegends();
        refilter(true);
        if (state.mode === "flow") buildFlow();
    }
    // Letters of the movement keys on the user's keyboard (AZERTY: ZQSD + A / E, QWERTY: WASD + Q / E)
    const KEYS = {move: "WASD", updown: "Q / E"};
    if (navigator.keyboard && navigator.keyboard.getLayoutMap) navigator.keyboard.getLayoutMap().then(m => {
        const k = (c) => (m.get(c) || "").toUpperCase();
        if (k("KeyW")) { KEYS.move = k("KeyW") + k("KeyA") + k("KeyS") + k("KeyD"); KEYS.updown = k("KeyQ") + " / " + k("KeyE"); refilter(false); }
    }).catch(() => { /* not available */ });
    else if (/^fr/.test(navigator.language || "")) { KEYS.move = "ZQSD"; KEYS.updown = "A / E"; }
    function refilter(reheat) {
        const q = state.search.trim().toLowerCase();
        let vis = state.data.nodes.filter(n => state.kinds.has(n.kind) && state.groups.has(n.group));
        let ids = new Set(vis.map(n => n.id));
        let vl = state.data.links.filter(l => state.linkKinds.has(l.kind) && ids.has(l.source) && ids.has(l.target));
        if (state.isolate && state.selected && ids.has(state.selected)) {
            const keep = new Set([state.selected]);
            for (const l of vl) { if (l.source === state.selected) keep.add(l.target); if (l.target === state.selected) keep.add(l.source); }
            vis = vis.filter(n => keep.has(n.id)); ids = keep;
            vl = vl.filter(l => keep.has(l.source) && keep.has(l.target));
        }
        state.visible = vis;
        state.vlinks = vl;
        state.match = q ? new Set(vis.filter(n => n.label.toLowerCase().includes(q) || (n.path || "").toLowerCase().includes(q)).map(n => n.id)) : null;
        state.neighbors = new Map();
        for (const l of vl) {
            if (!state.neighbors.has(l.source)) state.neighbors.set(l.source, new Set());
            if (!state.neighbors.has(l.target)) state.neighbors.set(l.target, new Set());
            state.neighbors.get(l.source).add(l.target); state.neighbors.get(l.target).add(l.source);
        }
        $("nodeCount").textContent = vis.length + " / " + state.data.nodes.length;
        $("linkCount").textContent = vl.length + " / " + state.data.links.length;
        $("groupCount").textContent = state.groups.size + " / " + state.knownGroups.size;
        updateChips();
        if (reheat) state.alpha = Math.max(state.alpha, reheat === "soft" ? 0.25 : 0.6);
        $("hint").hidden = !!vis.length || state.mode === "flow" || !state.data.nodes.length; // the controls are in the "?" card; nothing loaded yet: no hint
        $("hint").textContent = tr("No node: enable some categories / groups");
    }

    // ---------- Legends / chips ---------- //
    function chip(label, color, count, on, onclick, help) {
        const b = document.createElement("button");
        b.type = "button"; b.className = "chip" + (on ? "" : " off");
        if (help) b.dataset.help = help;
        b.innerHTML = (color ? '<span class="dot"></span>' : "") + "<span></span>" + (count !== undefined ? ' <span class="n">' + count + "</span>" : "");
        if (color) b.firstChild.style.background = color;
        b.querySelector("span:not(.dot):not(.n)").textContent = label;
        b.addEventListener("click", onclick);
        return b;
    }
    function groupColor(g) {
        let h = 0;
        for (const c of String(g)) h = (h * 31 + c.charCodeAt(0)) >>> 0;
        return "hsl(" + (h % 360) + " 55% 55%)";
    }
    function legendItem(label, color, count, on, onclick, help, line, hover) {
        const b = document.createElement("button");
        const longest = Math.max(...String(label).split(/[\s/_.-]+/).map(w => w.length));
        b.type = "button"; b.className = "lg" + (on ? "" : " off") + (String(label).length > 26 || longest > 12 ? " wide" : ""); // a column holds ~13 characters: never a word cut or a word per line
        if (help) b.dataset.help = help;
        b.innerHTML = '<span class="sw' + (line ? " line" : "") + '"></span><span class="t"></span><span class="n"></span>';
        b.querySelector(".sw").style.background = color;
        b.querySelector(".t").textContent = label;
        b.querySelector(".n").textContent = count;
        b.addEventListener("click", onclick);
        if (hover) {
            b.addEventListener("mouseenter", () => { state.legendHover = hover; state.dirty = true; });
            b.addEventListener("mouseleave", () => { state.legendHover = null; state.dirty = true; });
        }
        return b;
    }
    function buildLegends() {
        const kc = {}, gc = {}, lc = {};
        for (const n of state.data.nodes) { kc[n.kind] = (kc[n.kind] || 0) + 1; gc[n.group] = (gc[n.group] || 0) + 1; }
        for (const l of state.data.links) lc[l.kind] = (lc[l.kind] || 0) + 1;
        // Click: show / hide (relations don't move the graph); hover: highlight the matching nodes / relations
        const fill = (el, entries, set, color, label, help, type) => {
            el.textContent = "";
            for (const [k, n] of entries) el.appendChild(legendItem(label(k), color(k), n, set.has(k),
                () => { set.has(k) ? set.delete(k) : set.add(k); refilter(type === "link" ? false : "soft"); state.dirty = true; },
                help(k), type === "link", {type, key: k}));
        };
        fill($("kinds"), Object.keys(KINDS).filter(k => kc[k]).map(k => [k, kc[k]]), state.kinds, k => KINDS[k][0], k => tr(KINDS[k][1]), k => "kind:" + k, "kind");
        fill($("groups"), Object.keys(gc).sort().map(g => [g, gc[g]]), state.groups, g => groupColor(g), g => g, g => g === "external" ? "group:external" : g === "build" ? "group:build" : "group", "group");
        fill($("linkKinds"), Object.keys(LINKS).filter(k => lc[k]).map(k => [k, lc[k]]), state.linkKinds, k => LINKS[k][0], k => tr(LINKS[k][1]), k => "link:" + k, "link");
    }
    function updateChips() {
        const sync = (el, set, keys) => [...el.children].forEach((c, i) => c.classList.toggle("off", !set.has(keys[i])));
        const kc = new Set(state.data.nodes.map(n => n.kind)), lc = new Set(state.data.links.map(l => l.kind));
        sync($("kinds"), state.kinds, Object.keys(KINDS).filter(k => kc.has(k)));
        sync($("groups"), state.groups, [...new Set(state.data.nodes.map(n => n.group))].sort());
        sync($("linkKinds"), state.linkKinds, Object.keys(LINKS).filter(k => lc.has(k)));
        for (const b of $("presets").children) {
            const p = PRESETS[b.dataset.preset];
            b.classList.toggle("off", !(p[0].length === state.kinds.size && p[0].every(k => state.kinds.has(k)) && p[1].length === state.linkKinds.size && p[1].every(k => state.linkKinds.has(k))));
        }
    }
    function colorOf(n) {
        if (state.colorBy === "group") return groupColor(n.group);
        return (KINDS[n.kind] || KINDS.external)[0];
    }
    const NODE_2D = 1.25; // size factor of the nodes in 2D
    const LABEL_MAX = 48; // characters of a name drawn on the canvas: the whole name is in the hover card and the details
    const clipLabel = (s) => { s = String(s); return s.length > LABEL_MAX ? s.slice(0, LABEL_MAX - 1) + "…" : s; };
    // Layout density: node size, length of the relations, repulsion (bigger + closer nodes, like a 3d-force-graph)
    const LAYOUT = {size: 1.3, link: 34, linkShort: 18, repulsion: 150, gap: 3};
    function radiusOf(n) {
        const base = n.kind === "method" || n.kind === "test" ? 2.2 : n.kind === "external" || n.kind === "executable" || n.kind === "library" ? 5 : 3.2;
        return (base + Math.sqrt(n.degree || 0) * 1.3) * LAYOUT.size;
    }

    // ---------- Simulation ---------- //
    // Barnes-Hut repulsion: an octree (quadtree in 2D) of the nodes, a far cell acts as one body at its center of mass.
    // Same force as the exact loop (strength / d², cut at 500, collision of the close pairs), approximated for the far cells.
    // Flat typed arrays (no object per cell): fast enough for ~10 000 nodes.
    const BH = {cap: 0};
    function bhAlloc(n) {
        if (BH.cap >= n) return;
        BH.cap = n;
        for (const k of ["cx", "cy", "cz", "h", "m", "mx", "my", "mz"]) BH[k] = new Float64Array(n);
        BH.body = new Int32Array(n); BH.kids = new Int32Array(n * 8); BH.stack = new Int32Array(n);
    }
    function repulseTree(P, R, strength, d3) {
        const N = P.length, K = d3 ? 8 : 4;
        bhAlloc(N * 10 + 64);
        const {cx, cy, cz, h, m, mx, my, mz, body, kids, stack} = BH, cap = BH.cap - 9;
        let x0 = Infinity, y0 = Infinity, z0 = Infinity, x1 = -Infinity, y1 = -Infinity, z1 = -Infinity;
        for (const p of P) { if (p.x < x0) x0 = p.x; if (p.x > x1) x1 = p.x; if (p.y < y0) y0 = p.y; if (p.y > y1) y1 = p.y; if (d3) { if (p.z < z0) z0 = p.z; if (p.z > z1) z1 = p.z; } }
        if (!d3) { z0 = 0; z1 = 0; }
        let used = 0;
        const cell = (x, y, z, hh) => { const c = used++; cx[c] = x; cy[c] = y; cz[c] = z; h[c] = hh; m[c] = 0; mx[c] = 0; my[c] = 0; mz[c] = 0; body[c] = -1; kids.fill(-1, c * 8, c * 8 + 8); kids[c * 8] = -2; return c; }; // kids[c*8] = -2: leaf
        const root = cell((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2, Math.max(x1 - x0, y1 - y0, z1 - z0, 1) / 2 + 1);
        const childOf = (c, p) => {
            const k = (p.x > cx[c] ? 1 : 0) + (p.y > cy[c] ? 2 : 0) + (d3 && p.z > cz[c] ? 4 : 0);
            let ch = kids[c * 8 + k];
            if (ch < 0) { const hh = h[c] / 2; ch = cell(cx[c] + (k & 1 ? hh : -hh), cy[c] + (k & 2 ? hh : -hh), cz[c] + (k & 4 ? hh : -hh), hh); kids[c * 8 + k] = ch; }
            return ch;
        };
        const insert = (c, i, depth) => {
            const p = P[i];
            m[c]++; mx[c] += p.x; my[c] += p.y; mz[c] += d3 ? p.z : 0;
            if (kids[c * 8] === -2) { // leaf
                if (body[c] < 0 && m[c] === 1) { body[c] = i; return; }
                if (depth > 40 || used >= cap) return; // same position / no room: kept in the mass only
                const old = body[c]; body[c] = -1; kids[c * 8] = -1; // becomes an inner cell
                if (old >= 0) insert(childOf(c, P[old]), old, depth + 1);
            }
            insert(childOf(c, p), i, depth + 1);
        };
        for (let i = 0; i < N; i++) insert(root, i, 0);
        const THETA2 = N > 3000 ? 1.44 : 0.81; // coarser on the very big graphs
        for (let i = 0; i < N; i++) {
            const p = P[i];
            let sp = 0; stack[sp++] = root;
            while (sp) {
                const c = stack[--sp];
                if (!m[c]) continue;
                const leaf = kids[c * 8] === -2;
                if (leaf && body[c] === i) continue;
                const ox = Math.max(0, Math.abs(p.x - cx[c]) - h[c]), oy = Math.max(0, Math.abs(p.y - cy[c]) - h[c]), oz = d3 ? Math.max(0, Math.abs(p.z - cz[c]) - h[c]) : 0;
                if (ox * ox + oy * oy + oz * oz > 250000) continue; // the whole cell is beyond the cut (500)
                const gx = mx[c] / m[c], gy = my[c] / m[c], gz = mz[c] / m[c];
                let dx = p.x - gx, dy = p.y - gy, dz = d3 ? p.z - gz : 0, d2 = dx * dx + dy * dy + dz * dz;
                const size = h[c] * 2;
                if (!leaf && size * size >= THETA2 * d2) { for (let k = 0; k < K; k++) { const ch = kids[c * 8 + k]; if (ch >= 0) stack[sp++] = ch; } continue; }
                if (leaf && body[c] >= 0 && m[c] === 1) { // a single node: exact force + collision
                    const j = body[c];
                    if (d2 < 0.01) { dx = Math.random() - 0.5; dy = Math.random() - 0.5; }
                    if (d2 < 25) d2 = 25;
                    let f = strength / d2;
                    const min = R[i] + R[j] + LAYOUT.gap;
                    if (d2 < min * min) f += 0.5 * (min - Math.sqrt(d2)) / Math.sqrt(d2);
                    p.vx += dx * f; p.vy += dy * f; if (d3) p.vz += dz * f;
                    continue;
                }
                if (d2 < 25) d2 = 25;
                const f = strength * m[c] / d2; // far cell: one body of mass m
                p.vx += dx * f; p.vy += dy * f; if (d3) p.vz += dz * f;
            }
        }
    }
    function tick() {
        const nodes = state.visible, n = nodes.length;
        if (!n || state.paused || state.alpha < 0.004 || state.mode === "flow" || bigSim()) return false; // big graphs: in the worker
        const a = state.alpha, d3 = state.mode === "3d";
        const P = nodes.map(x => state.pos.get(x.id));
        const strength = LAYOUT.repulsion * a, R = nodes.map(radiusOf);
        if (n > 300) repulseTree(P, R, strength, d3); // big graphs: Barnes-Hut (n log n) instead of every pair
        else for (let i = 0; i < n; i++) {
            const p = P[i];
            for (let j = i + 1; j < n; j++) {
                const q = P[j];
                let dx = p.x - q.x, dy = p.y - q.y, dz = d3 ? p.z - q.z : 0;
                let d2 = dx * dx + dy * dy + dz * dz;
                if (d2 > 250000) continue;
                if (d2 < 0.01) { dx = Math.random() - 0.5; dy = Math.random() - 0.5; }
                if (d2 < 25) d2 = 25;
                let f = strength / d2;
                const min = R[i] + R[j] + LAYOUT.gap; // collision: the nodes don't overlap
                if (d2 < min * min) f += 0.5 * (min - Math.sqrt(d2)) / Math.sqrt(d2);
                p.vx += dx * f; p.vy += dy * f; q.vx -= dx * f; q.vy -= dy * f;
                if (d3) { p.vz += dz * f; q.vz -= dz * f; }
            }
        }
        if (!state.springs || state.springs.src !== state.vlinks) { // relations prepared once per filter: positions, length, strength, bias
            state.springs = state.vlinks.map(l => {
                const ns = state.byId.get(l.source), nt = state.byId.get(l.target);
                return {p: state.pos.get(l.source), q: state.pos.get(l.target), len: l.kind === "member" || l.kind === "defines" ? LAYOUT.linkShort : LAYOUT.link,
                    w: 0.7 / Math.max(1, Math.min(ns.degree, nt.degree)), bias: (ns.degree || 1) / ((ns.degree || 1) + (nt.degree || 1))};
            });
            state.springs.src = state.vlinks;
        }
        for (const sp of state.springs) {
            const p = sp.p, q = sp.q;
            const dx = q.x - p.x, dy = q.y - p.y, dz = d3 ? q.z - p.z : 0;
            const d = Math.sqrt(dx * dx + dy * dy + dz * dz) || 1;
            // d3-like: strength 1 / min(degree), the node with the lowest degree moves the most
            const k = (d - sp.len) / d * a * sp.w, bias = sp.bias;
            q.vx -= dx * k * bias; q.vy -= dy * k * bias; p.vx += dx * k * (1 - bias); p.vy += dy * k * (1 - bias);
            if (d3) { q.vz -= dz * k * bias; p.vz += dz * k * (1 - bias); }
        }
        if (state.cluster) {
            const c = new Map();
            nodes.forEach((x, i) => { const g = c.get(x.group) || {x: 0, y: 0, z: 0, n: 0}; g.x += P[i].x; g.y += P[i].y; g.z += P[i].z; g.n++; c.set(x.group, g); });
            nodes.forEach((x, i) => { const g = c.get(x.group); P[i].vx += (g.x / g.n - P[i].x) * 0.06 * a; P[i].vy += (g.y / g.n - P[i].y) * 0.06 * a; if (d3) P[i].vz += (g.z / g.n - P[i].z) * 0.06 * a; });
        }
        let cx = 0, cy = 0, cz = 0;
        for (const p of P) { cx += p.x; cy += p.y; cz += p.z; }
        cx /= n; cy /= n; cz /= n;
        for (const p of P) {
            if (p.fixed) { p.vx = p.vy = p.vz = 0; continue; }
            p.vx *= 0.6; p.vy *= 0.6; p.vz *= 0.6;
            const sp = Math.hypot(p.vx, p.vy, p.vz);
            if (sp > 40) { p.vx *= 40 / sp; p.vy *= 40 / sp; p.vz *= 40 / sp; }
            p.x += p.vx - cx * 0.02; p.y += p.vy - cy * 0.02;
            p.z = d3 ? p.z + p.vz - cz * 0.02 : p.z * 0.9;
        }
        state.alpha *= n > 3000 ? 0.97 : 0.985; // the very big graphs settle faster
        state.layoutV++;
        return true;
    }

    // ---------- Projection ---------- //
    const NEAR = 12; // near plane of the 3D camera: what is closer (or behind) is not drawn, like a WebGL camera
    function clipNear(a, b) { // screen point where the segment a -> b (b in front) enters the near plane
        const k = (NEAR - a.d) / (b.d - a.d), vx = a.vx + (b.vx - a.vx) * k, vy = a.vy + (b.vy - a.vy) * k, s = 700 / NEAR;
        return {x: state.w / 2 + vx * s, y: state.h / 2 + vy * s, s, z: a.z + (b.z - a.z) * k, d: NEAR};
    }
    function project(p) {
        const c = state.cam;
        if (state.mode !== "3d") return {x: state.w / 2 + (p.x - c.x) * c.k, y: state.h / 2 + (p.y - c.y) * c.k, s: c.k, z: 0};
        const cy = Math.cos(c.yaw), sy = Math.sin(c.yaw), cp = Math.cos(c.pitch), sp = Math.sin(c.pitch);
        const x1 = (p.x - c.x) * cy - (p.z - c.z) * sy, z1 = (p.x - c.x) * sy + (p.z - c.z) * cy;
        const y2 = (p.y - c.y) * cp - z1 * sp, z2 = (p.y - c.y) * sp + z1 * cp;
        const d = z2 + c.dist, s = 700 / Math.max(NEAR, d); // d: distance in front of the camera
        return {x: state.w / 2 + x1 * s, y: state.h / 2 + y2 * s, s, z: z2, vx: x1, vy: y2, d, behind: d < NEAR};
    }
    function fit() {
        if (state.mode === "flow") { if (state.flow) fitFlow(); return; }
        const nodes = state.visible;
        if (!nodes.length) return;
        let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity, r = 0;
        let mx = 0, my = 0;
        for (const n of nodes) { const p = state.pos.get(n.id); x0 = Math.min(x0, p.x); x1 = Math.max(x1, p.x); y0 = Math.min(y0, p.y); y1 = Math.max(y1, p.y); mx += p.x; my += p.y; }
        mx /= nodes.length; my /= nodes.length;
        const ds = nodes.map(n => { const p = state.pos.get(n.id); return Math.hypot(p.x - mx, p.y - my, p.z); }).sort((a, b) => a - b);
        r = ds[Math.floor((ds.length - 1) * 0.9)] || 0; // 90 % of the nodes: the far isolated ones don't shrink the view
        state.cam.x = (x0 + x1) / 2; state.cam.y = (y0 + y1) / 2; state.cam.z = 0;
        state.cam.k = Math.min(4, 0.88 * Math.min(state.w / Math.max(60, x1 - x0), state.h / Math.max(60, y1 - y0)));
        state.cam.dist = Math.max(120, r * 2.7 * Math.max(1, 700 / Math.min(state.w, state.h)));
        if (state.mode === "3d") { // centered on the mean position (the isolated nodes don't shift it)
            let mz = 0;
            for (const n of nodes) mz += state.pos.get(n.id).z;
            state.cam.x = mx; state.cam.y = my; state.cam.z = mz / nodes.length;
        }
    }

    // ---------- Drawing ---------- //
    function readColors() {
        const s = getComputedStyle(document.documentElement);
        for (const k of ["bg", "surface", "text", "muted", "border", "accent", "line"]) state.colors[k] = s.getPropertyValue("--" + k).trim();
    }
    // 3D cues: rotation of a direction (no translation), floor grid under the nodes, axes gizmo
    function rotateDir(x, y, z) {
        const c = state.cam, cy = Math.cos(c.yaw), sy = Math.sin(c.yaw), cp = Math.cos(c.pitch), sp = Math.sin(c.pitch);
        const x1 = x * cy - z * sy, z1 = x * sy + z * cy;
        return {x: x1, y: y * cp - z1 * sp, z: y * sp + z1 * cp};
    }
    function unrotateDir(x, y, z) { // view direction -> world direction (inverse of rotateDir)
        const c = state.cam, cy = Math.cos(c.yaw), sy = Math.sin(c.yaw), cp = Math.cos(c.pitch), sp = Math.sin(c.pitch);
        const y0 = y * cp + z * sp, z1 = -y * sp + z * cp;
        return {x: x * cy + z1 * sy, y: y0, z: -x * sy + z1 * cy};
    }
    const GIZMO = {x: 44, r: 38, len: 26}; // axes gizmo, bottom left (y = state.h - 44)
    const LIGHT = (() => { const v = [-0.55, -0.75, -0.35], l = Math.hypot(...v); return v.map(x => x / l); })(); // world direction to the light (top, left, front)
    // Technical 3D style: low poly spheres, each face flat shaded by the scene light (like a WebGL Lambert material)
    const RGB = new Map();
    function toRgb(c) { // "#rrggbb" or "hsl(h s% l%)" -> [r, g, b]
        if (RGB.has(c)) return RGB.get(c);
        let v = null, m;
        if ((m = /^#([0-9a-f]{6})$/i.exec(c))) v = [0, 2, 4].map(i => parseInt(m[1].slice(i, i + 2), 16));
        else if ((m = /^hsl\(\s*([\d.]+)[\s,]+([\d.]+)%[\s,]+([\d.]+)%/i.exec(c))) {
            const h = +m[1] / 360, s = +m[2] / 100, l = +m[3] / 100, q = l < 0.5 ? l * (1 + s) : l + s - l * s, p = 2 * l - q;
            const f = (x) => { x = (x + 1) % 1; return x < 1 / 6 ? p + (q - p) * 6 * x : x < 1 / 2 ? q : x < 2 / 3 ? p + (q - p) * (2 / 3 - x) * 6 : p; };
            v = [f(h + 1 / 3), f(h), f(h - 1 / 3)].map(x => Math.round(x * 255));
        }
        RGB.set(c, v);
        return v;
    }
    function shadeRgb(c, k) { const v = toRgb(c); return v ? "rgb(" + v.map(x => Math.min(255, Math.round(x * k))).join(",") + ")" : c; }
    const MESH = (() => { // unit sphere 8 x 8 segments, like the nodes of 3d-force-graph (nodeResolution 8): faces = vertices + world normal
        const LON = 8, LAT = 8, faces = [], pt = (i, j) => { const th = j / LAT * Math.PI, ph = i / LON * Math.PI * 2; return [Math.sin(th) * Math.cos(ph), -Math.cos(th), Math.sin(th) * Math.sin(ph)]; };
        for (let j = 0; j < LAT; j++) for (let i = 0; i < LON; i++) {
            const v = [pt(i, j), pt(i + 1, j), pt(i + 1, j + 1), pt(i, j + 1)].filter((q, k, a) => k === 0 || Math.hypot(q[0] - a[k - 1][0], q[1] - a[k - 1][1], q[2] - a[k - 1][2]) > 1e-6);
            const n = v.reduce((s, q) => [s[0] + q[0], s[1] + q[1], s[2] + q[2]], [0, 0, 0]), l = Math.hypot(...n);
            faces.push({v, n: n.map(x => x / l)});
        }
        return faces;
    })();
    // Lights of 3d-force-graph: ambient 0xcccccc (0.8) + directional 0.6 from the top of the scene, Lambert material
    // (no spot); the light is computed at the vertices (normal = position on the unit sphere) and interpolated on the face
    const lambert = (q) => 0.8 + 0.6 * Math.max(0, -q[1]);
    function meshFrame() { // the faces turned with the camera, back faces removed, far first
        return MESH.map(f => ({pts: f.v.map(q => rotateDir(...q)), ks: f.v.map(lambert), n: rotateDir(...f.n)}))
            .filter(f => f.n.z < 0.05).sort((a, b) => b.n.z - a.n.z);
    }
    // The sphere looks the same for every node of a colour (only the angle of the camera changes it): one sprite per
    // colour and size bucket, redrawn when the angle changes, then scaled to each node (fast with many nodes)
    const SPRITES = {key: "", map: new Map(), real: new Map()};
    function withSnapped(f) { // run f with the camera at the snapped angle of the sprites
        const c = state.cam, y = c.yaw, p = c.pitch;
        c.yaw = SPRITES.yaw; c.pitch = SPRITES.pitch;
        try { return f(); } finally { c.yaw = y; c.pitch = p; }
    }
    function snapSprites() { // the sprites are drawn for the camera angle snapped to ~1.5°: rebuilt only when it changes
        const Q = 0.026, qy = Math.round(state.cam.yaw / Q), qp = Math.round(state.cam.pitch / Q), key = qy + "," + qp + "," + state.dpr + "," + state.colors.bg; // + the theme (fog colour)
        if (SPRITES.key !== key) { SPRITES.key = key; SPRITES.map.clear(); SPRITES.real.clear(); SPRITES.yaw = qy * Q; SPRITES.pitch = qp * Q; }
    }
    function realSprite(color, r, fog) { // realistic node: the shaded sphere (scene light) drawn once per colour / size / angle (/ fog)
        snapSprites();
        const R = [8, 16, 32, 64, 128, 256].find(x => x >= r) || 256, id = color + "|" + R + "|" + (fog || 0);
        let cv = SPRITES.real.get(id);
        if (cv) return cv;
        cv = document.createElement("canvas");
        const m = R + 2, size = Math.ceil(2 * m * state.dpr), g = cv.getContext("2d");
        cv.width = cv.height = size; g.setTransform(state.dpr, 0, 0, state.dpr, 0, 0);
        const light = withSnapped(() => rotateDir(...LIGHT));
        g.beginPath(); g.arc(m, m, R, 0, Math.PI * 2); g.fillStyle = color; g.fill();
        const hx = m + light.x * R * 0.55, hy = m + light.y * R * 0.55, front = Math.max(0, -light.z);
        const hl = g.createRadialGradient(hx, hy, R * 0.05, hx, hy, R * 1.75);
        hl.addColorStop(0, "rgba(255,255,255," + (0.25 + 0.5 * front).toFixed(2) + ")"); hl.addColorStop(0.25, "rgba(255,255,255,.1)");
        hl.addColorStop(0.55, "rgba(0,0,0,0)"); hl.addColorStop(1, "rgba(0,0,0,.55)");
        g.fillStyle = hl; g.fill();
        if (fog) { g.globalAlpha = fog / 10; g.fillStyle = state.colors.bg; g.fill(); } // fog baked (big graphs)
        cv.R = R;
        SPRITES.real.set(id, cv);
        return cv;
    }
    function sphereSprite(color, r, mesh) {
        // angle snapped to ~1.5°: the sprites are rebuilt only every few frames while rotating (invisible difference)
        snapSprites();
        const R = [16, 32, 64, 128, 256].find(x => x >= r) || 256, id = color + "|" + R;
        let cv = SPRITES.map.get(id);
        if (cv) return cv;
        cv = document.createElement("canvas");
        const m = R + 2, size = Math.ceil(2 * m * state.dpr), faces = mesh.list; // mesh.list: computed once per frame, only when a sprite is drawn
        cv.width = cv.height = size;
        const g = cv.getContext("2d");
        g.setTransform(state.dpr, 0, 0, state.dpr, 0, 0); g.lineWidth = 0.6; g.lineJoin = "round";
        const path = (f) => { g.beginPath(); g.moveTo(m + f.pts[0].x * R, m + f.pts[0].y * R); for (let i = 1; i < f.pts.length; i++) g.lineTo(m + f.pts[i].x * R, m + f.pts[i].y * R); g.closePath(); };
        g.fillStyle = g.strokeStyle = "#fff";
        for (const f of faces) { path(f); g.fill(); g.stroke(); } // faceted outline of the 8 x 8 sphere
        // Lambert per pixel with the smooth normal of the sphere (like the interpolated normals of WebGL)
        const img = g.getImageData(0, 0, size, size), px = img.data, up = withSnapped(() => rotateDir(0, -1, 0)), rgb = toRgb(color) || [150, 150, 150];
        for (let yy = 0; yy < size; yy++) for (let xx = 0; xx < size; xx++) {
            const i = (yy * size + xx) * 4;
            if (!px[i + 3]) continue;
            const X = ((xx + 0.5) / state.dpr - m) / R, Y = ((yy + 0.5) / state.dpr - m) / R, Z = -Math.sqrt(Math.max(0, 1 - X * X - Y * Y));
            const k = 0.8 + 0.6 * Math.max(0, X * up.x + Y * up.y + Z * up.z);
            px[i] = Math.min(255, rgb[0] * k); px[i + 1] = Math.min(255, rgb[1] * k); px[i + 2] = Math.min(255, rgb[2] * k);
        }
        g.putImageData(img, 0, 0);
        g.globalCompositeOperation = "source-atop"; g.globalAlpha = 0.18; // a hint of the faces
        for (const f of faces) { const k = f.ks.reduce((s, x) => s + x, 0) / f.ks.length; g.fillStyle = shadeRgb(color, k); path(f); g.fill(); }
        cv.R = R;
        SPRITES.map.set(id, cv);
        return cv;
    }
    function drawPolySphere(x, y, r, color, mesh) { // drawn opaque in the sprite, pasted with the current alpha
        const cv = sphereSprite(color, r, mesh), k = r / cv.R, m = (cv.R + 2) * k;
        ctx.drawImage(cv, x - m, y - m, 2 * m, 2 * m);
    }
    function drawFloor(C) {
        const nodes = state.visible;
        if (!nodes.length) return;
        bounds(); // (validates the cache of the layout)
        if (!BCACHE.f) {
            let y1 = -Infinity, mx = 0, mz = 0;
            for (const n of nodes) { const p = state.pos.get(n.id); y1 = Math.max(y1, p.y); mx += p.x; mz += p.z; }
            mx /= nodes.length; mz /= nodes.length;
            const ds = nodes.map(n => { const p = state.pos.get(n.id); return Math.hypot(p.x - mx, p.z - mz); }).sort((a, b) => a - b);
            BCACHE.f = {y1, mx, mz, r: ds[Math.floor(ds.length * 0.9)] || 1}; // r: ignores the far isolated nodes
        }
        const {y1, r} = BCACHE.f;
        const floor = y1 + 40, step = Math.max(20, Math.round(r / 4 / 10) * 10), ext = Math.ceil(r * 1.4 / step) * step;
        // Centered on the camera target (snapped to the grid): the floor follows a move, like an endless plane
        const gx = Math.round(state.cam.x / step) * step, gz = Math.round(state.cam.z / step) * step;
        const ok = (q) => q.z + state.cam.dist > 80; // in front of the camera
        ctx.strokeStyle = C.muted; ctx.lineWidth = 1;
        for (let v = -ext; v <= ext; v += step) {
            for (let u = -ext; u < ext; u += step) { // short segments, faded towards the border of the floor
                for (const [a, b] of [[{x: gx + v, y: floor, z: gz + u}, {x: gx + v, y: floor, z: gz + u + step}],
                                      [{x: gx + u, y: floor, z: gz + v}, {x: gx + u + step, y: floor, z: gz + v}]]) {
                    const pa = project(a), pb = project(b);
                    if (!ok(pa) || !ok(pb)) continue;
                    const mid = Math.hypot((a.x + b.x) / 2 - state.cam.x, (a.z + b.z) / 2 - state.cam.z);
                    ctx.globalAlpha = 0.22 * Math.max(0, 1 - mid / (ext + step));
                    ctx.beginPath(); ctx.moveTo(pa.x, pa.y); ctx.lineTo(pb.x, pb.y); ctx.stroke();
                }
            }
        }
        ctx.globalAlpha = 1;
    }
    // ---------- Limits of the space ---------- //
    // 3D: a box around the nodes (margin M, the floor is its bottom) that the camera can't leave; its walls fade in
    // near the camera. 2D: the center of the view stays near the graph and the zoom out keeps it readable.
    const BCACHE = {v: -1, vis: null, b: null, f: null}; // bounds / floor of the layout, recomputed only when the positions change
    function bounds() {
        const nodes = state.visible;
        if (!nodes.length) return null;
        if (BCACHE.v === state.layoutV && BCACHE.vis === nodes && BCACHE.b) return BCACHE.b;
        const lo = {x: Infinity, y: Infinity, z: Infinity}, hi = {x: -Infinity, y: -Infinity, z: -Infinity};
        for (const n of nodes) { const p = state.pos.get(n.id); for (const a of ["x", "y", "z"]) { lo[a] = Math.min(lo[a], p[a]); hi[a] = Math.max(hi[a], p[a]); } }
        const size = Math.max(hi.x - lo.x, hi.y - lo.y, hi.z - lo.z, 100), M = Math.max(300, size * 1.3 * Math.max(1, 700 / Math.min(state.w, state.h))); // the fitted camera is inside (further on a narrow screen, see fit())
        BCACHE.b = {lo: {x: lo.x - M, y: lo.y - M, z: lo.z - M}, hi: {x: hi.x + M, y: hi.y + 40 - 6, z: hi.z + M}, M, raw: {lo, hi}}; // bottom: just above the floor
        if (BCACHE.v !== state.layoutV || BCACHE.vis !== nodes) BCACHE.f = null;
        BCACHE.v = state.layoutV; BCACHE.vis = nodes;
        return BCACHE.b;
    }
    function camPos() { const c = state.cam, b = unrotateDir(0, 0, -c.dist); return {x: c.x + b.x, y: c.y + b.y, z: c.z + b.z}; }
    function clampCam() { // keep the camera (3D) / the view center and zoom (2D) inside the limits; true when moved
        const c = state.cam;
        if (state.mode === "flow") { // the center stays near the diagram
            if (!state.flow) return false;
            const r = state.flow.bbox, mx = state.w / 2 / c.k * 0.4, my = state.h / 2 / c.k * 0.4;
            const kMin = 0.3 * Math.min(state.w / Math.max(80, r.x1 - r.x0), state.h / Math.max(80, r.y1 - r.y0), 1);
            let moved = false;
            if (c.k < kMin) { c.k = kMin; moved = true; }
            const x = Math.min(r.x1 + mx, Math.max(r.x0 - mx, c.x)), y = Math.min(r.y1 + my, Math.max(r.y0 - my, c.y));
            if (x !== c.x || y !== c.y) { c.x = x; c.y = y; moved = true; }
            return moved;
        }
        const B = bounds();
        if (!B || drag && drag.node) return false;
        let moved = false;
        if (state.mode === "3d") {
            const p = camPos(), gap = Math.max(60, B.M * 0.12); // stopped a bit before the walls: they stay visible in front
            for (const a of ["x", "y", "z"]) {
                const v = Math.min(B.hi[a] - (a === "y" ? 0 : gap), Math.max(B.lo[a] + gap, p[a]));
                if (v !== p[a]) { c[a] += v - p[a]; moved = true; }
            }
        } else {
            const r = B.raw, w = Math.max(60, r.hi.x - r.lo.x), h = Math.max(60, r.hi.y - r.lo.y);
            const kMin = 0.3 * 0.88 * Math.min(state.w / w, state.h / h); // the graph keeps at least ~30 % of the fitted size
            if (c.k < kMin) { c.k = kMin; moved = true; }
            const mx = state.w / 2 / c.k * 0.4, my = state.h / 2 / c.k * 0.4; // the graph keeps reaching the middle part of the view
            const x = Math.min(r.hi.x + mx, Math.max(r.lo.x - mx, c.x)), y = Math.min(r.hi.y + my, Math.max(r.lo.y - my, c.y));
            if (x !== c.x || y !== c.y) { c.x = x; c.y = y; moved = true; }
        }
        return moved;
    }
    function drawWalls(C) { // the walls of the 3D box close to the camera, as an accent grid fading in
        const B = bounds();
        if (!B) return;
        const p = camPos(), gap = Math.max(60, B.M * 0.12), W = gap * 4, ok = (q) => !q.behind; // gap: stop distance (clampCam)
        const walls = [["x", B.lo.x, 1], ["x", B.hi.x, -1], ["y", B.lo.y, 1], ["z", B.lo.z, 1], ["z", B.hi.z, -1]]; // the bottom is the floor
        ctx.strokeStyle = C.accent; ctx.lineWidth = 1;
        for (const [axis, v, sgn] of walls) {
            const d = (p[axis] - v) * sgn; // distance to the wall, inside > 0
            if (d > W) continue;
            const strength = Math.min(1, 1 - d / W);
            const [u, w] = axis === "x" ? ["y", "z"] : axis === "y" ? ["x", "z"] : ["x", "y"];
            const step = Math.max(10, Math.round(gap / 2.5 / 5) * 5), ext = gap * 5; // cells sized for the stop distance
            const cu = Math.round(p[u] / step) * step, cw = Math.round(p[w] / step) * step;
            const pt = (a, b) => { const q = {}; q[axis] = v; q[u] = a; q[w] = b; return project(q); };
            ctx.fillStyle = C.accent; // light tint of the wall around the camera
            const corners = [pt(cu - ext, cw - ext), pt(cu + ext, cw - ext), pt(cu + ext, cw + ext), pt(cu - ext, cw + ext)];
            if (corners.every(ok)) { ctx.globalAlpha = 0.05 * strength; ctx.beginPath(); corners.forEach((q, i) => i ? ctx.lineTo(q.x, q.y) : ctx.moveTo(q.x, q.y)); ctx.fill(); }
            for (let i = -ext; i <= ext; i += step) for (let j = -ext; j < ext; j += step) {
                for (const [a0, b0, a1, b1] of [[cu + i, cw + j, cu + i, cw + j + step], [cu + j, cw + i, cu + j + step, cw + i]]) {
                    const qa = pt(a0, b0), qb = pt(a1, b1);
                    if (!ok(qa) || !ok(qb)) continue;
                    const fade = 1 - Math.min(1, Math.hypot((a0 + a1) / 2 - p[u], (b0 + b1) / 2 - p[w]) / ext); // round patch around the camera
                    ctx.globalAlpha = 0.5 * strength * fade;
                    if (ctx.globalAlpha < 0.01) continue;
                    ctx.beginPath(); ctx.moveTo(qa.x, qa.y); ctx.lineTo(qb.x, qb.y); ctx.stroke();
                }
            }
        }
        ctx.globalAlpha = 1;
    }
    function drawAxes(C) {
        const ox = GIZMO.x, oy = state.h - GIZMO.x, R = GIZMO.r, len = GIZMO.len;
        // Ball: flat disc + the 3 great circles of the sphere (back half faint), then the axes on top
        ctx.globalAlpha = 1;
        ctx.fillStyle = C.surface; ctx.beginPath(); ctx.arc(ox, oy, R, 0, Math.PI * 2); ctx.fill(); // flat: no light effect
        ctx.lineWidth = 1; ctx.strokeStyle = state.gizmoHover ? C.accent : C.border; ctx.stroke();
        const rings = [[(a) => [Math.cos(a), Math.sin(a), 0], "#539bf5"], [(a) => [Math.cos(a), 0, Math.sin(a)], "#3fb950"], [(a) => [0, Math.cos(a), Math.sin(a)], "#e5534b"]];
        for (const [f, col] of rings) { // each ring is perpendicular to the axis of its colour
            ctx.strokeStyle = col;
            for (let i = 0; i < 48; i++) {
                const a0 = rotateDir(...f(i / 48 * Math.PI * 2)), a1 = rotateDir(...f((i + 1) / 48 * Math.PI * 2));
                ctx.globalAlpha = a0.z + a1.z > 0 ? 0.12 : 0.38;
                ctx.beginPath(); ctx.moveTo(ox + a0.x * R * 0.92, oy + a0.y * R * 0.92); ctx.lineTo(ox + a1.x * R * 0.92, oy + a1.y * R * 0.92); ctx.stroke();
            }
        }
        const axes = [["X", 1, 0, 0, "#e5534b"], ["Y", 0, -1, 0, "#3fb950"], ["Z", 0, 0, 1, "#539bf5"]]
            .map(([l, x, y, z, c]) => ({l, c, d: rotateDir(x, y, z)})).sort((a, b) => b.d.z - a.d.z);
        ctx.lineWidth = 2; ctx.font = "600 10px system-ui, sans-serif"; ctx.textAlign = "center";
        for (const a of axes) {
            const ex = ox + a.d.x * len, ey = oy + a.d.y * len, back = a.d.z > 0;
            ctx.globalAlpha = back ? 0.45 : 1; // pointing away: fainter
            ctx.strokeStyle = a.c; ctx.fillStyle = a.c;
            ctx.beginPath(); ctx.moveTo(ox, oy); ctx.lineTo(ex, ey); ctx.stroke();
            ctx.beginPath(); ctx.arc(ex, ey, back ? 2 : 3, 0, Math.PI * 2); ctx.fill();
            ctx.globalAlpha = back ? 0.75 : 1; ctx.fillStyle = C.text;
            ctx.fillText(a.l, ox + a.d.x * (len + 8), oy + a.d.y * (len + 8) + 3.5);
        }
        ctx.globalAlpha = 1;
    }
    function draw() {
        const C = state.colors;
        ctx.setTransform(state.dpr, 0, 0, state.dpr, 0, 0);
        ctx.clearRect(0, 0, state.w, state.h);
        if (state.mode === "flow") { drawFlow(C); return; }
        const proj = new Map();
        const d3p = state.mode === "3d";
        // Big graphs (> 2000 nodes) while the view or the layout moves: light drawing (square nodes, no arrow heads, few
        // names); the full drawing comes back as soon as the view is still (state.lod is read by frame())
        const lod = state.visible.length > 2000 && (performance.now() - (state.moveT || 0) < 160 || (state.alpha >= 0.05 && !state.paused)); // the end of the layout (small moves) is drawn in full
        state.lod = lod;
        for (const n of state.visible) { // projection + drawn radius, once per node and per frame
            const q = project(state.pos.get(n.id));
            q.r = Math.max(1.5, radiusOf(n) * (d3p ? q.s : NODE_2D * Math.sqrt(q.s)));
            q.n = n;
            proj.set(n.id, q);
        }
        const d3 = state.mode === "3d";
        let z0 = Infinity, z1 = -Infinity;
        const real = d3 && state.style3d !== "tech"; // technical style: flat nodes, arrows, no light / fog / floor
        if (real) { for (const p of proj.values()) { z0 = Math.min(z0, p.z); z1 = Math.max(z1, p.z); } drawFloor(C); }
        if (d3) drawWalls(C);
        const depth = (z) => real && z1 > z0 ? (z - z0) / (z1 - z0) : 0; // 0 = closest, 1 = farthest
        const light = d3 ? rotateDir(...LIGHT) : null; // light direction in the view
        let meshCache = null;
        const mesh = d3 && !real ? {get list() { return meshCache || (meshCache = withSnapped(meshFrame)); }} : null;
        const focus = state.hover || state.selected;
        const near = focus ? state.neighbors.get(focus) || new Set() : null;
        const lh = state.legendHover;
        const lhNodes = lh && lh.type === "link" ? new Set(state.vlinks.filter(l => l.kind === lh.key).flatMap(l => [l.source, l.target])) : null;
        const lhMatch = (id) => { const n = state.byId.get(id); return lh.type === "kind" ? n.kind === lh.key : lh.type === "group" ? n.group === lh.key : lhNodes.has(id); };
        const dim = (id) => (near && id !== focus && !near.has(id)) || (state.match && !state.match.has(id)) || (lh && !focus && !lhMatch(id));
        ctx.lineWidth = 1;
        const drawnR = (n, q) => q.r !== undefined ? q.r : Math.max(1.5, radiusOf(n) * (d3 ? q.s : NODE_2D * Math.sqrt(q.s))); // radius as drawn below
        const ring = (id) => id === state.selected || id === state.hover ? 1.5 : 0.5; // accent ring of the focused node
        const ends = (l) => { // screen ends of a relation, outside the nodes (on their border); null when nothing to draw
            let a = proj.get(l.source), b = proj.get(l.target), ca = false, cb = false;
            if (d3 && (a.behind || b.behind)) {
                if (a.behind && b.behind) return null;
                if (a.behind) { a = clipNear(a, b); ca = true; } else { b = clipNear(b, a); cb = true; }
            }
            const len = Math.hypot(b.x - a.x, b.y - a.y);
            const ra = ca ? 0 : a.r + ring(l.source), rb = cb ? 0 : b.r + ring(l.target);
            if (len <= ra + rb) return null; // the nodes overlap
            const ux = (b.x - a.x) / len, uy = (b.y - a.y) / len;
            return {a, b, ux, uy, cb, len: len - ra - rb, x0: a.x + ux * ra, y0: a.y + uy * ra, x1: b.x - ux * rb, y1: b.y - uy * rb};
        };
        // Big graphs (> 2500 relations): the plain relations are batched by colour / opacity / width (one path per batch),
        // the highlighted ones drawn after, on top; the smaller graphs keep the exact drawing, one relation at a time
        const bigL = state.vlinks.length > 2500, batches = new Map(), later = [];
        let lodLinks = 0; // relations drawn while the view moves (big graphs)
        let heads = 0; // arrow heads of the batches: a big fill of tiny triangles is the slowest part of the canvas
        const drawOne = (l, e, hot, lit, fog) => {
            const a = e.a, b = e.b;
            ctx.globalAlpha = (hot || lit ? 0.95 : (focus || state.match || lh ? 0.07 : real ? 0.4 : d3 ? 0.45 : 0.35)) * (hot ? 1 : fog);
            ctx.strokeStyle = hot ? C.accent : LINKS[l.kind][0];
            ctx.lineWidth = (hot ? 1.6 : lit ? 2 : 1) * (real ? Math.min(2.2, Math.max(0.5, (a.s + b.s) / 2)) : 1);
            const arrow = (hot || (state.mode === "2d" && state.cam.k > 1.6) || d3) && !e.cb;
            const al = !d3 ? 7 : Math.max(4.5, Math.min(10, 6.5 * b.s)) * (hot ? 1.15 : 1); // same size in the realistic and technical 3D styles
            const back = arrow ? Math.min(e.len, al * 0.9) : 0; // the line stops at the base of the arrow
            ctx.beginPath(); ctx.moveTo(e.x0, e.y0); ctx.lineTo(e.x1 - e.ux * back, e.y1 - e.uy * back); ctx.stroke();
            if (arrow) { // arrow head, its tip on the border of the target
                const ang = Math.atan2(e.uy, e.ux), tx = e.x1, ty = e.y1;
                const lx = tx - Math.cos(ang - 0.38) * al, ly = ty - Math.sin(ang - 0.38) * al;
                const rx = tx - Math.cos(ang + 0.38) * al, ry = ty - Math.sin(ang + 0.38) * al;
                if (d3 && !real) { // cone: lit half + shaded half
                    const mx = (lx + rx) / 2, my = (ly + ry) / 2, col = ctx.strokeStyle;
                    ctx.fillStyle = shadeRgb(col, 1.15); ctx.beginPath(); ctx.moveTo(tx, ty); ctx.lineTo(lx, ly); ctx.lineTo(mx, my); ctx.fill();
                    ctx.fillStyle = shadeRgb(col, 0.7); ctx.beginPath(); ctx.moveTo(tx, ty); ctx.lineTo(mx, my); ctx.lineTo(rx, ry); ctx.fill();
                } else {
                    ctx.fillStyle = ctx.strokeStyle;
                    ctx.beginPath(); ctx.moveTo(tx, ty); ctx.lineTo(lx, ly); ctx.lineTo(rx, ry); ctx.fill();
                }
            }
        };
        for (const l of state.vlinks) {
            const e = ends(l);
            if (!e) continue;
            if (Math.max(e.x0, e.x1) < 0 || Math.min(e.x0, e.x1) > state.w || Math.max(e.y0, e.y1) < 0 || Math.min(e.y0, e.y1) > state.h) continue; // off screen
            if (bigL && e.len < 3 && !(focus && (l.source === focus || l.target === focus))) continue; // big graphs: a relation of < 3 px is hidden by its nodes
            if (lod && !(focus && (l.source === focus || l.target === focus)) && (e.len < 8 || ++lodLinks > 8000)) continue; // moving: a part of the relations
            const hot = focus && (l.source === focus || l.target === focus);
            const lit = lh && !focus && (lh.type === "link" ? l.kind === lh.key : lhMatch(l.source) && lhMatch(l.target));
            const fog = 1 - 0.75 * depth((e.a.z + e.b.z) / 2);
            if (!bigL) { drawOne(l, e, hot, lit, fog); continue; }
            if (hot || lit) { later.push([l, e, hot, lit, fog]); continue; }
            const aq = Math.round((focus || state.match || lh ? 0.07 : real ? 0.4 : d3 ? 0.45 : 0.35) * fog * 20); // opacity in 1/20
            const key = (KIND_INDEX[l.kind] || 0) * 32 + aq; // numeric key: no string per relation and per frame
            let bt = batches.get(key);
            if (!bt) batches.set(key, bt = {color: LINKS[l.kind][0], alpha: aq / 20, width: 1, segs: [], heads: []}); // hairline: fast path of the canvas
            const arrow = !lod && (state.mode === "2d" && state.cam.k > 1.6 || d3) && !e.cb && e.len > 30 && heads < 2000; // readable heads only
            if (arrow) heads++;
            const al = !d3 ? 7 : Math.max(4.5, Math.min(10, 6.5 * e.b.s)), back = arrow ? Math.min(e.len, al * 0.9) : 0;
            bt.segs.push(e.x0, e.y0, e.x1 - e.ux * back, e.y1 - e.uy * back);
            if (arrow) { const ang = Math.atan2(e.uy, e.ux); bt.heads.push(e.x1, e.y1, e.x1 - Math.cos(ang - 0.38) * al, e.y1 - Math.sin(ang - 0.38) * al, e.x1 - Math.cos(ang + 0.38) * al, e.y1 - Math.sin(ang + 0.38) * al); }
        }
        for (const bt of batches.values()) {
            ctx.globalAlpha = bt.alpha; ctx.strokeStyle = bt.color; ctx.fillStyle = bt.color; ctx.lineWidth = bt.width;
            ctx.beginPath();
            for (let i = 0; i < bt.segs.length; i += 4) { ctx.moveTo(bt.segs[i], bt.segs[i + 1]); ctx.lineTo(bt.segs[i + 2], bt.segs[i + 3]); }
            ctx.stroke();
            if (!bt.heads.length) continue;
            ctx.beginPath();
            for (let i = 0; i < bt.heads.length; i += 6) { ctx.moveTo(bt.heads[i], bt.heads[i + 1]); ctx.lineTo(bt.heads[i + 2], bt.heads[i + 3]); ctx.lineTo(bt.heads[i + 4], bt.heads[i + 5]); } // fill closes them
            ctx.fill();
        }
        for (const x of later) drawOne(...x);
        if (state.particles && state.vlinks.length) { // moving dots: source -> target (direction of the relation)
            const time = performance.now() / 1000;
            for (const l of state.vlinks) {
                const a = proj.get(l.source), b = proj.get(l.target);
                const hot = focus && (l.source === focus || l.target === focus);
                if ((focus && !hot) || a.behind || b.behind) continue;
                const e = ends(l);
                if (!e) continue;
                if (l._h === undefined) l._h = Math.random();
                ctx.fillStyle = hot ? C.accent : LINKS[l.kind][0];
                ctx.globalAlpha = hot ? 1 : 0.85;
                for (let k = 0; k < 2; k++) {
                    const f = (time * 0.32 + l._h + k / 2) % 1;
                    ctx.beginPath(); ctx.arc(e.x0 + (e.x1 - e.x0) * f, e.y0 + (e.y1 - e.y0) * f, hot ? 2.6 : 1.9, 0, Math.PI * 2); ctx.fill();
                }
            }
            ctx.globalAlpha = 1;
        }
        const order = state.mode === "3d" ? [...proj.values()].sort((a, b) => b.z - a.z).map(q => q.n) : state.visible; // far first
        ctx.font = "11px system-ui, sans-serif";
        ctx.textAlign = "center";
        // Big graphs (> 2000 nodes): the tiny nodes (< 3.2 px) as one path per colour, drawn first (they are the far ones)
        const bigN = order.length > 2000, tiny = new Set();
        if (bigN) {
            const byColor = new Map();
            for (const n of order) {
                const p = proj.get(n.id);
                if (d3 && p.behind) continue;
                const r = drawnR(n, p);
                const faded = dim(n.id);
                if ((r >= 3.2 && !lod) || n.id === state.selected || n.id === state.hover || (state.match && state.match.has(n.id)) || (faded && !lod)) continue;
                tiny.add(n.id);
                if (p.x + r < 0 || p.y + r < 0 || p.x - r > state.w || p.y - r > state.h) continue;
                const c = (faded ? "~" : "") + colorOf(n); // the faded ones (selection) in their own batches
                if (!byColor.has(c)) byColor.set(c, []);
                byColor.get(c).push(p.x, p.y, r);
            }
            for (const [key, list] of byColor) {
                const c = key.replace(/^~/, "");
                ctx.globalAlpha = key[0] === "~" ? 0.12 : real ? 0.7 : 0.9;
                ctx.fillStyle = c; ctx.beginPath();
                if (lod) for (let i = 0; i < list.length; i += 3) { const r = list[i + 2] * 0.9; ctx.rect(list[i] - r, list[i + 1] - r, 2 * r, 2 * r); } // squares: the fastest
                else for (let i = 0; i < list.length; i += 3) { ctx.moveTo(list[i] + list[i + 2], list[i + 1]); ctx.arc(list[i], list[i + 1], list[i + 2], 0, Math.PI * 2); }
                ctx.fill();
            }
        }
        let labels = 0;
        const labelMax = bigN ? (lod ? 0 : 150) : Infinity; // names: budget per frame in big graphs (the focus, its neighbours and the search always)
        for (const n of order) {
            if (tiny.has(n.id)) continue;
            const p = proj.get(n.id);
            if (d3 && p.behind) continue; // passed behind the camera
            const r = drawnR(n, p);
            if (p.x + r < 0 || p.y + r < 0 || p.x - r > state.w || p.y - r > state.h) continue;
            const faded = dim(n.id);
            // light transparency in 3D (realistic 0.88, technical 0.95 like context-forge), fading out just before the camera
            const base = (faded ? 0.12 : 1) * (real ? 0.88 : d3 ? 0.95 : 1) * (d3 ? Math.min(1, (p.d - NEAR) / 40) : 1);
            ctx.globalAlpha = base;
            if (d3 && !real && r > 2.5) {
                drawPolySphere(p.x, p.y, r, colorOf(n), mesh);
                ctx.beginPath(); ctx.arc(p.x, p.y, r, 0, Math.PI * 2); // path for the selection ring below
            } else if (real && r > 1.6) { // shaded sphere: cached sprite (the light is fixed in the scene, its side turns with the camera)
                const fogLv = bigN ? Math.round(depth(p.z) * 0.62 * 10) : 0; // big graphs: the fog is in the sprite (one draw per node)
                const cv = realSprite(colorOf(n), r, fogLv), k = r / cv.R, mm = (cv.R + 2) * k;
                ctx.drawImage(cv, p.x - mm, p.y - mm, 2 * mm, 2 * mm);
                ctx.beginPath(); ctx.arc(p.x, p.y, r, 0, Math.PI * 2); // path of the fog and the selection ring
            } else {
                ctx.fillStyle = colorOf(n);
                ctx.beginPath(); ctx.arc(p.x, p.y, r, 0, Math.PI * 2); ctx.fill();
            }
            if (real && !(bigN && r > 1.6)) { // fog towards the background with the depth
                const t = depth(p.z);
                if (t > 0.02) { ctx.globalAlpha = base * 0.62 * t; ctx.fillStyle = C.bg; ctx.fill(); ctx.globalAlpha = base; }
            }
            if (n.id === state.selected || n.id === state.hover || (state.match && state.match.has(n.id))) {
                ctx.lineWidth = 2; ctx.strokeStyle = C.accent; ctx.stroke();
            } else if (n.pure || n.external) {
                ctx.lineWidth = 1.2; ctx.strokeStyle = C.bg; ctx.stroke();
            }
            const must = n.id === focus || (near && near.has(n.id)) || (state.match && state.match.has(n.id));
            const showLabel = must || (labels < labelMax && state.labels && !faded && (bigN ? r > 5 : true) &&
                (state.mode === "2d" ? state.cam.k * (1 + Math.sqrt(n.degree) / 3) > 1.25 : p.s > 1.25 || n.degree > 12));
            if (showLabel && !must) labels++;
            if (showLabel && !faded) {
                ctx.globalAlpha = 1;
                ctx.fillStyle = C.text;
                ctx.globalAlpha = 1 - 0.55 * depth(p.z);
                ctx.fillText(clipLabel(n.label), p.x, p.y + r + 11);
            }
        }
        ctx.globalAlpha = 1;
        if (d3) drawAxes(C);
    }
    const keysHeld = new Set(); // arrow keys: move the view while held
    function keyMove() {
        if (!keysHeld.size) return false;
        const sp = (keysHeld.has("Shift") ? 3 : 1) * 9; // pixels per frame on the screen
        let dx = 0, dy = 0;
        if (keysHeld.has("ArrowLeft")) dx -= sp; if (keysHeld.has("ArrowRight")) dx += sp;
        if (keysHeld.has("ArrowUp")) dy -= sp; if (keysHeld.has("ArrowDown")) dy += sp;
        // Physical keys (same place on AZERTY / QWERTY): KeyW/S forward/back, KeyA/D left/right, KeyQ/E down/up
        let fw = 0, side = 0, up = 0;
        if (keysHeld.has("KeyW")) fw += sp; if (keysHeld.has("KeyS")) fw -= sp;
        if (keysHeld.has("KeyD")) side += sp; if (keysHeld.has("KeyA")) side -= sp;
        if (keysHeld.has("KeyE")) up += sp; if (keysHeld.has("KeyQ")) up -= sp;
        if (!dx && !dy && !fw && !side && !up) return false;
        if (dx || dy || fw || side || (up && state.mode === "3d")) state.lock = null; // a move ends the focus of F (zoom keys keep it)
        const c = state.cam;
        if (state.mode !== "3d") {
            c.x += (dx + side) / c.k; c.y += (dy - fw) / c.k;
            if (up) c.k = Math.max(0.05, Math.min(12, c.k * Math.exp(up * 0.004))); // no height in 2D: E / A zoom in / out
        } else {
            const s = 700 / c.dist, w = unrotateDir(dx / s, dy / s, 0); // arrows: in the plane of the screen
            c.x += w.x; c.y += w.y; c.z += w.z;
            const f = unrotateDir(0, 0, 1), r = unrotateDir(1, 0, 0); // view directions, kept horizontal (along the floor)
            const fl = Math.hypot(f.x, f.z) || 1, rl = Math.hypot(r.x, r.z) || 1;
            c.x += (f.x / fl * fw + r.x / rl * side) / s; c.z += (f.z / fl * fw + r.z / rl * side) / s;
            c.y -= up / s; // world y points down
        }
        return true;
    }
    let mouse = null, camSig = ""; // last mouse position on the graph; signature of the camera
    function rehover() { // the view moved under a still mouse: update the hovered node and its card
        const c = state.cam, sig = [c.x, c.y, c.z, c.k, c.dist, c.yaw, c.pitch, state.mode].join();
        if (sig === camSig) return;
        camSig = sig; state.moveT = performance.now(); // the view moves: light drawing of the big graphs
        if (!mouse || drag) return;
        const n = onGizmo(mouse.x, mouse.y) ? null : pick(mouse.x, mouse.y), id = n ? n.id : null;
        if (id !== state.hover) { state.hover = id; state.dirty = true; canvas.classList.toggle("pointer", !!n); }
        nodeTip(n, mouse.x, mouse.y);
    }
    function follow() { // focus of F: the camera follows the node while the layout moves
        if (!state.lock || state.animating || state.mode === "flow") return false;
        const q = state.pos.get(state.lock), c = state.cam;
        if (!q) { state.lock = null; return false; }
        const moved = Math.abs(c.x - q.x) + Math.abs(c.y - q.y) + (state.mode === "3d" ? Math.abs(c.z - q.z) : 0) > 0.01;
        if (moved) { c.x = q.x; c.y = q.y; if (state.mode === "3d") c.z = q.z; }
        return moved;
    }
    // ---------- Simulation of the big graphs (> 3000 nodes) in a Web Worker: the page stays fluid while it settles ----------
    // Same forces as tick() (Barnes-Hut repulsion, relations, groups, damping), on typed arrays; the positions come back
    // after each step. Small graphs keep tick() on the page (no difference of layout).
    function simWorker() { // runs inside the worker (no access to the page)
        let S = null, timer = 0;
        onmessage = (e) => {
            const m = e.data;
            if (m.type === "init") { S = m; S.vx = new Float64Array(S.n); S.vy = new Float64Array(S.n); S.vz = new Float64Array(S.n); S.fixed = new Uint8Array(S.n); run(); return; }
            if (!S) return;
            if (m.type === "alpha") S.alpha = Math.max(S.alpha, m.alpha);
            else if (m.type === "fix") { S.fixed[m.i] = 1; S.x[m.i] = m.x; S.y[m.i] = m.y; S.z[m.i] = m.z; S.alpha = Math.max(S.alpha, 0.25); }
            else if (m.type === "unfix") S.fixed[m.i] = 0;
            else if (m.type === "pause") S.paused = m.on;
            run();
        };
        const run = () => { if (!timer) timer = setTimeout(step, 0); };
        let cap = 0, CX, CY, CZ, H, M, MX, MY, MZ, BODY, KIDS, STACK;
        function step() {
            timer = 0;
            if (!S || S.paused || S.alpha < 0.004) return;
            tick();
            postMessage({type: "pos", gen: S.gen, alpha: S.alpha, x: Float32Array.from(S.x), y: Float32Array.from(S.y), z: Float32Array.from(S.z)});
            run();
        }
        function tick() {
            const {n, x, y, z, vx, vy, vz, r, d3, gap} = S, a = S.alpha, strength = S.repulsion * a, K = d3 ? 8 : 4;
            if (cap < n * 10 + 64) { cap = n * 10 + 64; CX = new Float64Array(cap); CY = new Float64Array(cap); CZ = new Float64Array(cap); H = new Float64Array(cap); M = new Float64Array(cap); MX = new Float64Array(cap); MY = new Float64Array(cap); MZ = new Float64Array(cap); BODY = new Int32Array(cap); KIDS = new Int32Array(cap * 8); STACK = new Int32Array(cap); }
            let x0 = Infinity, y0 = Infinity, z0 = Infinity, x1 = -Infinity, y1 = -Infinity, z1 = -Infinity;
            for (let i = 0; i < n; i++) { if (x[i] < x0) x0 = x[i]; if (x[i] > x1) x1 = x[i]; if (y[i] < y0) y0 = y[i]; if (y[i] > y1) y1 = y[i]; if (z[i] < z0) z0 = z[i]; if (z[i] > z1) z1 = z[i]; }
            if (!d3) { z0 = 0; z1 = 0; }
            let used = 0;
            const cell = (cx, cy, cz, h) => { const c = used++; CX[c] = cx; CY[c] = cy; CZ[c] = cz; H[c] = h; M[c] = 0; MX[c] = 0; MY[c] = 0; MZ[c] = 0; BODY[c] = -1; KIDS.fill(-1, c * 8, c * 8 + 8); KIDS[c * 8] = -2; return c; };
            const root = cell((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2, Math.max(x1 - x0, y1 - y0, z1 - z0, 1) / 2 + 1);
            const child = (c, i) => {
                const k = (x[i] > CX[c] ? 1 : 0) + (y[i] > CY[c] ? 2 : 0) + (d3 && z[i] > CZ[c] ? 4 : 0);
                let ch = KIDS[c * 8 + k];
                if (ch < 0) { const h = H[c] / 2; ch = cell(CX[c] + (k & 1 ? h : -h), CY[c] + (k & 2 ? h : -h), CZ[c] + (k & 4 ? h : -h), h); KIDS[c * 8 + k] = ch; }
                return ch;
            };
            const insert = (c, i, depth) => {
                M[c]++; MX[c] += x[i]; MY[c] += y[i]; MZ[c] += d3 ? z[i] : 0;
                if (KIDS[c * 8] === -2) {
                    if (BODY[c] < 0 && M[c] === 1) { BODY[c] = i; return; }
                    if (depth > 40 || used >= cap - 9) return;
                    const old = BODY[c]; BODY[c] = -1; KIDS[c * 8] = -1;
                    if (old >= 0) insert(child(c, old), old, depth + 1);
                }
                insert(child(c, i), i, depth + 1);
            };
            for (let i = 0; i < n; i++) insert(root, i, 0);
            const T2 = n > 3000 ? 1.44 : 0.81;
            for (let i = 0; i < n; i++) {
                let sp = 0; STACK[sp++] = root;
                while (sp) {
                    const c = STACK[--sp];
                    if (!M[c]) continue;
                    const leaf = KIDS[c * 8] === -2;
                    if (leaf && BODY[c] === i) continue;
                    const ox = Math.max(0, Math.abs(x[i] - CX[c]) - H[c]), oy = Math.max(0, Math.abs(y[i] - CY[c]) - H[c]), oz = d3 ? Math.max(0, Math.abs(z[i] - CZ[c]) - H[c]) : 0;
                    if (ox * ox + oy * oy + oz * oz > 250000) continue;
                    let dx = x[i] - MX[c] / M[c], dy = y[i] - MY[c] / M[c], dz = d3 ? z[i] - MZ[c] / M[c] : 0, d2 = dx * dx + dy * dy + dz * dz;
                    const size = H[c] * 2;
                    if (!leaf && size * size >= T2 * d2) { for (let k = 0; k < K; k++) { const ch = KIDS[c * 8 + k]; if (ch >= 0) STACK[sp++] = ch; } continue; }
                    if (leaf && BODY[c] >= 0 && M[c] === 1) {
                        const j = BODY[c];
                        if (d2 < 0.01) { dx = Math.random() - 0.5; dy = Math.random() - 0.5; }
                        if (d2 < 25) d2 = 25;
                        let f = strength / d2;
                        const min = r[i] + r[j] + gap;
                        if (d2 < min * min) f += 0.5 * (min - Math.sqrt(d2)) / Math.sqrt(d2);
                        vx[i] += dx * f; vy[i] += dy * f; if (d3) vz[i] += dz * f;
                        continue;
                    }
                    if (d2 < 25) d2 = 25;
                    const f = strength * M[c] / d2;
                    vx[i] += dx * f; vy[i] += dy * f; if (d3) vz[i] += dz * f;
                }
            }
            const {si, ti, len, w, bias} = S;
            for (let k = 0; k < si.length; k++) {
                const p = si[k], q = ti[k], dx = x[q] - x[p], dy = y[q] - y[p], dz = d3 ? z[q] - z[p] : 0;
                const d = Math.sqrt(dx * dx + dy * dy + dz * dz) || 1, kk = (d - len[k]) / d * a * w[k], b = bias[k];
                vx[q] -= dx * kk * b; vy[q] -= dy * kk * b; vx[p] += dx * kk * (1 - b); vy[p] += dy * kk * (1 - b);
                if (d3) { vz[q] -= dz * kk * b; vz[p] += dz * kk * (1 - b); }
            }
            if (S.groups) { // cluster the nodes of a group
                const G = S.ngroups, gx = new Float64Array(G), gy = new Float64Array(G), gz = new Float64Array(G), gn = new Float64Array(G);
                for (let i = 0; i < n; i++) { const g = S.groups[i]; gx[g] += x[i]; gy[g] += y[i]; gz[g] += z[i]; gn[g]++; }
                for (let i = 0; i < n; i++) { const g = S.groups[i]; vx[i] += (gx[g] / gn[g] - x[i]) * 0.06 * a; vy[i] += (gy[g] / gn[g] - y[i]) * 0.06 * a; if (d3) vz[i] += (gz[g] / gn[g] - z[i]) * 0.06 * a; }
            }
            let cx = 0, cy = 0, cz = 0;
            for (let i = 0; i < n; i++) { cx += x[i]; cy += y[i]; cz += z[i]; }
            cx /= n; cy /= n; cz /= n;
            for (let i = 0; i < n; i++) {
                if (S.fixed[i]) { vx[i] = vy[i] = vz[i] = 0; continue; }
                vx[i] *= 0.6; vy[i] *= 0.6; vz[i] *= 0.6;
                const sp = Math.hypot(vx[i], vy[i], vz[i]);
                if (sp > 40) { vx[i] *= 40 / sp; vy[i] *= 40 / sp; vz[i] *= 40 / sp; }
                x[i] += vx[i] - cx * 0.02; y[i] += vy[i] - cy * 0.02;
                z[i] = d3 ? z[i] + vz[i] - cz * 0.02 : z[i] * 0.9;
            }
            S.alpha *= n > 3000 ? 0.97 : 0.985;
        }
    }
    const SIM = {worker: null, sig: null, gen: 0, latest: null, sent: 0, paused: false, fixed: -1, fit: false, cam: ""};
    const bigSim = () => state.visible.length > 3000 && state.mode !== "flow" && typeof Worker !== "undefined" && SIM.worker !== false;
    function simSync() { // called each frame: (re)start the worker, send the changes, apply the positions it computed
        if (!bigSim()) { if (SIM.worker) { SIM.worker.terminate(); SIM.worker = null; SIM.sig = null; } return false; }
        if (!SIM.worker) {
            try {
                SIM.worker = new Worker(URL.createObjectURL(new Blob(["(" + simWorker.toString() + ")()"], {type: "text/javascript"})));
                SIM.worker.onmessage = (e) => { if (e.data.gen === SIM.gen) SIM.latest = e.data; };
            } catch (err) { SIM.worker = false; return false; } // no worker (strict file:// policy): tick() on the page
        }
        const sig = [state.visible, state.vlinks, state.mode, state.cluster];
        if (!SIM.sig || sig.some((v, i) => v !== SIM.sig[i])) {
            SIM.sig = sig; SIM.gen++; SIM.latest = null;
            const nodes = state.visible, n = nodes.length, index = new Map(nodes.map((x, i) => [x.id, i]));
            const x = new Float64Array(n), y = new Float64Array(n), z = new Float64Array(n), r = new Float64Array(n);
            nodes.forEach((nd, i) => { const p = state.pos.get(nd.id); x[i] = p.x; y[i] = p.y; z[i] = p.z; r[i] = radiusOf(nd); });
            const L = state.vlinks, si = new Int32Array(L.length), ti = new Int32Array(L.length), len = new Float64Array(L.length), w = new Float64Array(L.length), bias = new Float64Array(L.length);
            L.forEach((l, k) => { const ns = state.byId.get(l.source), nt = state.byId.get(l.target); si[k] = index.get(l.source); ti[k] = index.get(l.target); len[k] = l.kind === "member" || l.kind === "defines" ? LAYOUT.linkShort : LAYOUT.link; w[k] = 0.7 / Math.max(1, Math.min(ns.degree, nt.degree)); bias[k] = (ns.degree || 1) / ((ns.degree || 1) + (nt.degree || 1)); });
            let groups = null, ngroups = 0;
            if (state.cluster) { const gi = new Map(); groups = new Int32Array(n); nodes.forEach((nd, i) => { if (!gi.has(nd.group)) gi.set(nd.group, gi.size); groups[i] = gi.get(nd.group); }); ngroups = gi.size; }
            SIM.worker.postMessage({type: "init", gen: SIM.gen, n, x, y, z, r, si, ti, len, w, bias, groups, ngroups, d3: state.mode === "3d", alpha: state.alpha, repulsion: LAYOUT.repulsion, gap: LAYOUT.gap, paused: state.paused});
            SIM.sent = state.alpha; SIM.paused = state.paused; SIM.fit = true; SIM.cam = JSON.stringify(state.cam);
        }
        if (state.alpha > SIM.sent + 1e-6) { SIM.worker.postMessage({type: "alpha", alpha: state.alpha}); SIM.sent = state.alpha; }
        if (state.paused !== SIM.paused) { SIM.worker.postMessage({type: "pause", on: state.paused}); SIM.paused = state.paused; }
        const dragged = drag && drag.node ? state.visible.indexOf(drag.node) : -1;
        if (dragged >= 0) { const p = state.pos.get(drag.node.id); SIM.worker.postMessage({type: "fix", i: dragged, x: p.x, y: p.y, z: p.z}); SIM.fixed = dragged; }
        else if (SIM.fixed >= 0) { SIM.worker.postMessage({type: "unfix", i: SIM.fixed}); SIM.fixed = -1; }
        const m = SIM.latest;
        if (!m) return false;
        SIM.latest = null;
        state.visible.forEach((nd, i) => { if (i === dragged) return; const p = state.pos.get(nd.id); p.x = m.x[i]; p.y = m.y[i]; p.z = m.z[i]; });
        state.alpha = m.alpha; SIM.sent = m.alpha; state.layoutV++;
        if (SIM.fit && m.alpha < 0.15) { SIM.fit = false; if (JSON.stringify(state.cam) === SIM.cam) { fit(); } } // first layout: fitted if the camera didn't move
        return true;
    }
    function frame() {
        let moved = keyMove();
        if (simSync()) moved = true;
        if (follow()) moved = true;
        if (clampCam()) moved = true;
        rehover();
        for (let i = 0; i < (state.visible.length > 900 ? 1 : 2); i++) moved = tick() || moved;
        if (state.lod && performance.now() - (state.moveT || 0) >= 160 && !(state.alpha >= 0.05 && !state.paused)) moved = true; // still again: full drawing
        if (moved || state.dirty || state.particles) { draw(); state.dirty = false; }
        requestAnimationFrame(frame);
    }
    function resize() {
        const r = canvas.getBoundingClientRect();
        state.dpr = window.devicePixelRatio || 1;
        state.w = r.width; state.h = r.height;
        canvas.width = Math.round(r.width * state.dpr); canvas.height = Math.round(r.height * state.dpr);
        state.dirty = true;
        placeDetails();
    }
    // The details of a narrow stage start under the bar of the diagrams: its views stay reachable
    function placeDetails() {
        const bar = $("flowBar"), stage = canvas.parentElement, room = stage.clientWidth - 14 - Math.min(340, stage.clientWidth - 28);
        stage.style.setProperty("--details-top", (!bar.hidden && bar.offsetLeft + bar.offsetWidth > room ? bar.offsetTop + bar.offsetHeight + 8 : 14) + "px");
    }
    if ("ResizeObserver" in window) new ResizeObserver(placeDetails).observe($("flowBar")); // shown, hidden, on one or two rows

    // ---------- Interaction ---------- //
    function pick(mx, my) {
        if (state.mode === "flow") return flowPick(mx, my);
        let best = null, bd = Infinity;
        for (const n of state.visible) {
            const p = project(state.pos.get(n.id));
            if (state.mode === "3d" && p.behind) continue;
            const r = Math.max(6, radiusOf(n) * (state.mode === "3d" ? p.s : NODE_2D * Math.sqrt(p.s)) + 3);
            const d = Math.hypot(p.x - mx, p.y - my);
            if (d < r && (d < bd || (state.mode === "3d" && d - bd < 2))) { best = n; bd = d; }
        }
        return best;
    }
    let drag = null;
    canvas.addEventListener("pointerdown", (e) => {
        const r = canvas.getBoundingClientRect(), mx = e.clientX - r.left, my = e.clientY - r.top;
        if (onGizmo(mx, my)) { resetAngle(); return; }
        const n = pick(mx, my);
        drag = {x: mx, y: my, sx: mx, sy: my, node: n && !(e.shiftKey || e.button === 2) && state.mode !== "flow" ? n : null, clicked: n, pan: e.shiftKey || e.button === 2};
        if (state.mode === "flow") flowDragStart(drag, mx, my, e);
        else if (state.mode === "3d" && !drag.node && !drag.pan && !state.lock) repivot(); // orbit around what is in front of the camera
        canvas.setPointerCapture(e.pointerId);
        canvas.classList.add("dragging");
    });
    canvas.addEventListener("pointermove", (e) => {
        const r = canvas.getBoundingClientRect(), mx = e.clientX - r.left, my = e.clientY - r.top;
        mouse = {x: mx, y: my};
        if (!drag) {
            const g = onGizmo(mx, my);
            if (g !== !!state.gizmoHover) { state.gizmoHover = g; state.dirty = true; canvas.classList.toggle("pointer", g); }
            if (g) { nodeTip(null); return; }
            const n = pick(mx, my);
            const id = n ? n.id : null;
            if (id !== state.hover) { state.hover = id; state.dirty = true; canvas.classList.toggle("pointer", !!n); }
            nodeTip(n, mx, my);
            return;
        }
        $("nodeTip").hidden = true;
        const dx = mx - drag.x, dy = my - drag.y;
        drag.x = mx; drag.y = my;
        const c = state.cam;
        if (drag.boxes) { for (const b of drag.boxes) { b.x += dx / c.k; b.y += dy / c.k; } state.dirty = true; return; } // diagram: move boxes
        if (drag.band) { drag.band.x1 = mx; drag.band.y1 = my; state.dirty = true; return; } // diagram: selection area
        if (!drag.node && Math.hypot(mx - drag.sx, my - drag.sy) > 3 && (drag.pan || state.mode !== "3d")) state.lock = null; // a move of the camera ends the focus of F
        if (drag.node) {
            const p = state.pos.get(drag.node.id);
            if (state.mode === "2d") { p.x += dx / c.k; p.y += dy / c.k; }
            else { const s = project(p).s, w = unrotateDir(dx / s, dy / s, 0); p.x += w.x; p.y += w.y; p.z += w.z; } // in the plane of the screen
            p.fixed = true; state.layoutV++;
            state.alpha = Math.max(state.alpha, 0.25);
        } else if (state.mode !== "3d") {
            c.x -= dx / c.k; c.y -= dy / c.k;
        } else if (drag.pan) { // move the target (and the rotation center) in the plane of the screen
            const s = 700 / c.dist, w = unrotateDir(-dx / s, -dy / s, 0);
            c.x += w.x; c.y += w.y; c.z += w.z;
        } else {
            c.yaw += dx * 0.006; c.pitch = Math.max(-1.5, Math.min(1.5, c.pitch + dy * 0.006)); // orbit
        }
        state.dirty = true;
    });
    function nodeTip(n, mx, my) { // hover card next to the cursor, kept inside the graph
        const tip = $("nodeTip");
        if (!n) { tip.hidden = true; return; }
        const ext = /\.[\w]+$/.exec(n.path || ""), file = /^(header|source|test-file)$/.test(n.kind);
        tip.querySelector(".k").textContent = tr((KINDS[n.kind] || ["", n.kind])[1]) + (file && ext ? " (" + ext[0] + ")" : "");
        tip.querySelector(".k").style.color = "color-mix(in srgb, " + colorOf(n) + " 50%, var(--text))"; // the colour of the node, readable on the card in both themes
        tip.querySelector(".t").textContent = n.label;
        tip.querySelector(".p").textContent = n.path || [n.ns, n.group].filter(Boolean).join(" · ");
        tip.hidden = false;
        const W = canvas.clientWidth, H = canvas.clientHeight, w = tip.offsetWidth, h = tip.offsetHeight;
        let x = mx + 14, y = my + 16;
        if (x + w > W - 8) x = mx - w - 14;
        if (y + h > H - 8) y = my - h - 12;
        tip.style.left = Math.max(8, x) + "px"; tip.style.top = Math.max(8, y) + "px";
    }
    canvas.addEventListener("pointerleave", () => { mouse = null; $("nodeTip").hidden = true; if (state.hover && !drag) { state.hover = null; state.dirty = true; } });
    function endDrag(e) {
        if (!drag) return;
        if (drag.node) state.pos.get(drag.node.id).fixed = false;
        const still = Math.hypot(drag.x - drag.sx, drag.y - drag.sy) < 4;
        if (state.mode === "flow") flowDragEnd(drag, still, e);
        else if (still) select(drag.clicked ? drag.clicked.id : null);
        drag = null;
        canvas.classList.remove("dragging");
    }
    function onGizmo(mx, my) { return state.mode === "3d" && Math.hypot(mx - GIZMO.x, my - (state.h - GIZMO.x)) <= GIZMO.r; }
    function repivot() { // the rotation center moves to the depth of what is in front of the camera (closer than the far target)
        const c = state.cam, cx = state.w / 2, cy = state.h / 2, rad = Math.min(state.w, state.h) * 0.3, ds = [];
        for (const n of state.visible) { const q = project(state.pos.get(n.id)); if (!q.behind && Math.hypot(q.x - cx, q.y - cy) < rad) ds.push(q.d); }
        if (!ds.length) return;
        ds.sort((a, b) => a - b);
        const d = Math.max(60, Math.min(ds[Math.floor((ds.length - 1) * 0.2)], c.dist * 0.75)); // the nearest central nodes, at least 25 % closer
        if (d >= c.dist) return;
        const p = camPos(), f = unrotateDir(0, 0, 1); // same view: only the pivot moves along the axis of the camera
        c.x = p.x + f.x * d; c.y = p.y + f.y * d; c.z = p.z + f.z * d; c.dist = d;
    }
    let camAnim = 0; // id of the running camera animation (a new one stops the previous one)
    function animateCam(to, ms = 350) { // eased move of the camera to the given fields (x, y, z, k, dist, yaw, pitch)
        const c = state.cam, from = {}, id = ++camAnim, t0 = performance.now();
        if ("yaw" in to) { while (to.yaw - c.yaw > Math.PI) to.yaw -= 2 * Math.PI; while (c.yaw - to.yaw > Math.PI) to.yaw += 2 * Math.PI; } // shortest turn
        for (const k in to) from[k] = c[k];
        const step = (now) => {
            if (id !== camAnim) return;
            const k = Math.min(1, (now - t0) / ms), e = 1 - Math.pow(1 - k, 3);
            for (const f in to) c[f] = from[f] + (to[f] - from[f]) * e;
            state.dirty = true;
            state.animating = k < 1;
            if (k < 1) requestAnimationFrame(step); else if ("yaw" in to) c.yaw = VIEW.yaw + Math.round((c.yaw - VIEW.yaw) / (2 * Math.PI)) * 2 * Math.PI;
        };
        requestAnimationFrame(step);
    }
    function resetAngle() { animateCam({yaw: VIEW.yaw, pitch: VIEW.pitch}); } // the position and the zoom are kept
    function resetView() { // position, zoom and angle of the start (what Fit computes, at the default angle)
        state.lock = null;
        const c = state.cam, save = {...c};
        c.yaw = VIEW.yaw; c.pitch = VIEW.pitch; fit();
        const to = {x: c.x, y: c.y, z: c.z, k: c.k, dist: c.dist, yaw: VIEW.yaw, pitch: VIEW.pitch};
        Object.assign(c, save);
        animateCam(to, 450);
    }
    function centerOn(id) { // animated move + zoom of the camera onto a node, framed with its direct neighbours; the focus stays on it
        state.lock = id; // (zoom / dezoom keep it, the other moves of the camera end it)
        if (state.mode === "flow") { const b = state.flow && state.flow.byId.get(id); if (b) animateCam({x: b.x + b.w / 2, y: b.y + b.h / 2, k: Math.max(state.cam.k, 1.2)}); return; }
        const q = state.pos.get(id);
        if (!q) return;
        // radius of the close neighbourhood: 60 % of the visible neighbours (a far one doesn't cancel the zoom)
        const ds = [...(state.neighbors.get(id) || [])].map(nb => state.pos.get(nb)).filter(Boolean).map(p => Math.hypot(p.x - q.x, p.y - q.y, state.mode === "3d" ? p.z - q.z : 0)).sort((a, b) => a - b);
        const r = Math.min(Math.max(ds.length ? ds[Math.floor((ds.length - 1) * 0.6)] : 40, 35), 200);
        if (state.mode === "3d") animateCam({x: q.x, y: q.y, z: q.z, dist: Math.max(90, r * 2.3)}, 450);
        else animateCam({x: q.x, y: q.y, k: Math.min(6, Math.max(1.2, 0.36 * Math.min(state.w, state.h) / r))}, 450);
    }
    const typing = () => { // a field that takes the letters (not a checkbox / button keeping the focus after a click)
        const el = document.activeElement;
        return !!el && (el.tagName === "TEXTAREA" || el.tagName === "SELECT" || el.isContentEditable || (el.tagName === "INPUT" && !/^(checkbox|radio|button|submit|range|color)$/.test(el.type)));
    };
    function moveCode(e) { // physical key (KeyW...), or from the character when the browser gives no code
        if (/^Key[WASDQE]$/.test(e.code)) return e.code;
        if (e.code && e.code !== "Unidentified") return null;
        const ch = (e.key || "").toUpperCase(), mv = KEYS.move, ud = KEYS.updown.split(" / ");
        const i = mv.indexOf(ch);
        return i >= 0 ? ["KeyW", "KeyA", "KeyS", "KeyD"][i] : ch === ud[0] ? "KeyQ" : ch === ud[1] ? "KeyE" : null;
    }
    document.addEventListener("keydown", (e) => {
        const free = !typing() && !e.ctrlKey && !e.metaKey && !e.altKey && $("helpBack").hidden;
        if (free && /^Arrow/.test(e.key)) { keysHeld.add(e.key); if (e.shiftKey) keysHeld.add("Shift"); e.preventDefault(); }
        else if (free && moveCode(e)) { keysHeld.add(moveCode(e)); if (e.shiftKey) keysHeld.add("Shift"); e.preventDefault(); }
        else if (e.key === "Shift") keysHeld.add("Shift");
    });
    document.addEventListener("keyup", (e) => { keysHeld.delete(e.key); keysHeld.delete(e.code); const c = moveCode(e); if (c) keysHeld.delete(c); if (e.key === "Shift") keysHeld.delete("Shift"); });
    window.addEventListener("blur", () => keysHeld.clear());
    document.addEventListener("keydown", (e) => {
        if (e.key !== "f" && e.key !== "F") return;
        if (e.ctrlKey || e.metaKey || e.altKey || typing()) return;
        if (state.selected) { e.preventDefault(); centerOn(state.selected); }
    });
    document.addEventListener("keydown", (e) => { // R: back to the start view (position, zoom, angle)
        if ((e.key === "r" || e.key === "R") && !typing() && !e.ctrlKey && !e.metaKey && !e.altKey && $("helpBack").hidden) { e.preventDefault(); resetView(); }
    });
    canvas.addEventListener("dblclick", (e) => { // double click on the axes: full reset (a single click resets the angle)
        const r = canvas.getBoundingClientRect();
        if (onGizmo(e.clientX - r.left, e.clientY - r.top)) { e.preventDefault(); resetView(); }
    });
    canvas.addEventListener("pointerup", endDrag);
    canvas.addEventListener("pointercancel", endDrag);
    canvas.addEventListener("contextmenu", (e) => e.preventDefault());
    canvas.addEventListener("wheel", (e) => {
        e.preventDefault();
        // Touchpad: many small pixel deltas (a mouse wheel sends big steps): damped, and capped for both
        const pad = e.deltaMode === 0 && Math.abs(e.deltaY) < 50, dy = Math.max(-120, Math.min(120, e.deltaY)) * (pad ? 0.35 : 1);
        zoomAt(Math.exp(-dy * 0.0015), e.clientX, e.clientY);
    }, {passive: false});
    function zoomAt(f, clientX, clientY) { // factor f > 1: zoom in (wheel and two finger pinch)
        const c = state.cam, r = canvas.getBoundingClientRect();
        // Anchor of the zoom: the selected node, else the mouse / the fingers (the point under it stays under it, zoom in and out)
        let ax = clientX - r.left, ay = clientY - r.top;
        if (state.lock && state.mode === "3d" && state.pos.get(state.lock)) { // focus of F: zoom towards / from the node, it stays the center
            c.dist = Math.max(20, Math.min(20000, c.dist / f)); state.dirty = true; return;
        }
        const lockedBox = state.lock && state.mode === "flow" && state.flow && state.flow.byId.get(state.lock);
        const sel = state.selected && state.pos.get(state.lock || state.selected);
        if (lockedBox) { const q = state.cam; ax = state.w / 2 + (lockedBox.x + lockedBox.w / 2 - q.x) * q.k; ay = state.h / 2 + (lockedBox.y + lockedBox.h / 2 - q.y) * q.k; }
        if (sel && state.mode !== "flow" && !lockedBox) { const q = project(sel); if (!(state.mode === "3d" && q.behind)) { ax = q.x; ay = q.y; } }
        const mx = ax - state.w / 2, my = ay - state.h / 2;
        if (state.mode === "3d") { // the scroll moves the camera forward / backward along the ray under the anchor (no limit)
            const step = -dy * c.dist * 0.0009, l = Math.hypot(mx / 700, my / 700, 1); // > 0: forward, same step back
            const w = unrotateDir(mx / 700 / l * step, my / 700 / l * step, step / l);
            c.x += w.x; c.y += w.y; c.z += w.z; // camera and target move together: free flight
        } else {
            const k = Math.max(0.02, Math.min(60, c.k * f));
            c.x += mx / c.k - mx / k; c.y += my / c.k - my / k; c.k = k;
        }
        state.dirty = true;
    }

    // Touch screens: two fingers = pinch to zoom + move to pan (one finger keeps drag / orbit / tap to select)
    const touches = new Map();
    let pinch = null;
    function pinchState() { const [a, b] = [...touches.values()]; return {d: Math.max(1, Math.hypot(a.x - b.x, a.y - b.y)), x: (a.x + b.x) / 2, y: (a.y + b.y) / 2}; }
    canvas.addEventListener("pointerdown", (e) => {
        if (e.pointerType !== "touch") return;
        touches.set(e.pointerId, {x: e.clientX, y: e.clientY});
        if (touches.size === 2) { drag = null; canvas.classList.remove("dragging"); pinch = pinchState(); $("nodeTip").hidden = true; } // the first finger no longer drags
    });
    canvas.addEventListener("pointermove", (e) => {
        if (!touches.has(e.pointerId)) return;
        touches.set(e.pointerId, {x: e.clientX, y: e.clientY});
        if (!pinch || touches.size !== 2) return;
        const n = pinchState(), c = state.cam, dx = n.x - pinch.x, dy = n.y - pinch.y;
        zoomAt(n.d / pinch.d, n.x, n.y);
        if (!state.lock) { // the middle of the fingers moves the view like a pan
            if (state.mode !== "3d") { c.x -= dx / c.k; c.y -= dy / c.k; }
            else { const s = 700 / c.dist, w = unrotateDir(-dx / s, -dy / s, 0); c.x += w.x; c.y += w.y; c.z += w.z; }
        }
        pinch = n; state.dirty = true;
    });
    function touchEnd(e) { touches.delete(e.pointerId); if (touches.size < 2) pinch = null; }
    canvas.addEventListener("pointerup", touchEnd);
    canvas.addEventListener("pointercancel", touchEnd);

    // ---------- Details ---------- //
    function esc(s) { return String(s).replace(/[&<>"]/g, c => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;"})[c]); }
    function select(id) {
        state.selected = id;
        const box = $("details");
        if (!id) { box.hidden = true; if (state.isolate) refilter(true); state.dirty = true; return; }
        const n = state.byId.get(id);
        const out = {}, inc = {};
        for (const l of state.data.links) {
            if (l.source === id) (out[l.kind] = out[l.kind] || []).push(l.target);
            if (l.target === id) (inc[l.kind] = inc[l.kind] || []).push(l.source);
        }
        const list = (title, m) => Object.keys(m).map(k => "<h5>" + esc(title) + " · " + esc(tr(LINKS[k] ? LINKS[k][1] : k)) + " (" + m[k].length + ")</h5><ul>" +
            m[k].slice(0, 60).map(t => { const x = state.byId.get(t); return x ? '<li><a data-id="' + esc(t) + '"><span class="dot" style="background:' + colorOf(x) + '"></span>' + esc(x.label) + "</a></li>" : ""; }).join("") +
            (m[k].length > 60 ? '<li class="muted">… ' + (m[k].length - 60) + " " + tr("more") + "</li>" : "") + "</ul>").join("");
        const meta = [["Group", n.group], ["Path", n.path], ["Namespace", n.ns], ["Lines", n.loc], ["Access", n.access], ["Overloads", n.overloads > 1 ? n.overloads : ""], ["Pure virtual", n.pure ? tr("yes") : ""], ["Relations", n.degree]].map(x => [tr(x[0]), x[1]])
            .filter(x => x[1] !== undefined && x[1] !== "").map(x => "<dt>" + x[0] + "</dt><dd>" + esc(x[1]) + "</dd>").join("");
        box.innerHTML = '<button class="close" type="button" aria-label="' + esc(tr("Close")) + '">×</button><div class="kind"><span class="dot" style="width:9px;height:9px;border-radius:50%;background:' + colorOf(n) + '"></span>' +
            esc(tr((KINDS[n.kind] || ["", n.kind])[1])) + "</div><h3>" + esc(n.label) + "</h3><dl>" + meta + "</dl>" + list(tr("Outgoing"), out) + list(tr("Incoming"), inc);
        box.hidden = false;
        box.querySelector(".close").addEventListener("click", () => select(null));
        box.querySelectorAll("a[data-id]").forEach(a => a.addEventListener("click", () => { focusOn(a.dataset.id); }));
        if (state.isolate) refilter(true);
        state.dirty = true;
    }
    function focusOn(id) {
        const n = state.byId.get(id);
        if (!n) return;
        if (!state.kinds.has(n.kind)) state.kinds.add(n.kind);
        if (!state.groups.has(n.group)) state.groups.add(n.group);
        refilter(false);
        select(id);
        const p = state.pos.get(id);
        state.cam.x = p.x; state.cam.y = p.y; if (state.mode === "3d") state.cam.z = p.z;
        if (state.mode === "2d") state.cam.k = Math.max(state.cam.k, 1.6);
        state.dirty = true;
    }

    // ---------- Status / update from GitHub ---------- //
    function short(sha) { return sha ? String(sha).slice(0, 7) : "?"; }
    function day(d) { return d ? String(d).slice(0, 10) : "?"; }
    let lastStatus = null;
    function setStatus(html, cls) { // html: string or function (re-rendered on a language change)
        lastStatus = [html, cls];
        const s = $("status"); s.className = "status" + (cls ? " " + cls : ""); s.innerHTML = typeof html === "function" ? html() : html;
    }
    function describe(meta) { return "commit <code>" + short(meta.sha) + "</code> " + tr("of") + " " + day(meta.date) + (meta.source === "live" ? tr(" (fetched from the repository)") : tr(" (embedded)")); }
    // Sources of the repository: GitHub or GitLab (gitlab.com or a self-hosted one), public, read from the browser
    async function getJSON(url, host) {
        const r = await fetch(url, {headers: host === "github" ? {Accept: "application/vnd.github+json"} : {}});
        if (!r.ok) throw new Error(r.status === 403 || r.status === 429 ? (host === "gitlab" ? "GitLab" : "GitHub") + " API rate limit reached" : r.status === 404 ? "repository not found or private" : "HTTP " + r.status);
        return {json: await r.json(), headers: r.headers};
    }
    const HOSTS = {
        github: {
            async head(c) {
                const branch = c.branch || (c.explorer ? (await getJSON("https://api.github.com/repos/" + c.repo, "github")).json.default_branch : "main");
                const h = (await getJSON("https://api.github.com/repos/" + c.repo + "/commits/" + encodeURIComponent(branch), "github")).json;
                return {sha: h.sha, date: h.commit && h.commit.committer && h.commit.committer.date};
            },
            async tree(c, sha) { return (await getJSON("https://api.github.com/repos/" + c.repo + "/git/trees/" + sha + "?recursive=1", "github")).json.tree.filter(x => x.type === "blob" && x.size < 600000).map(x => x.path); },
            raw: (c, sha, path) => "https://raw.githubusercontent.com/" + c.repo + "/" + sha + "/" + path.split("/").map(encodeURIComponent).join("/"),
            web: (c) => "https://github.com/" + c.repo
        },
        gitlab: {
            api: (c) => (c.api || "https://gitlab.com") + "/api/v4/projects/" + encodeURIComponent(c.repo),
            async head(c) {
                const branch = c.branch || (await getJSON(HOSTS.gitlab.api(c), "gitlab")).json.default_branch || "main";
                const h = (await getJSON(HOSTS.gitlab.api(c) + "/repository/commits/" + encodeURIComponent(branch), "gitlab")).json;
                return {sha: h.id, date: h.committed_date};
            },
            async tree(c, sha) { // pages of 100 entries: the first one gives the count, the others are asked in parallel
                const page = (n) => getJSON(HOSTS.gitlab.api(c) + "/repository/tree?recursive=true&per_page=100&ref=" + sha + "&page=" + n, "gitlab");
                const first = await page(1), out = first.json.filter(x => x.type === "blob").map(x => x.path);
                let total = +first.headers.get("x-total-pages") || 0;
                if (!total) { for (let n = 2, r = first; r.headers.get("x-next-page") && n <= 80; n++) { r = await page(n); out.push(...r.json.filter(x => x.type === "blob").map(x => x.path)); } return out; }
                const rest = [];
                for (let n = 2; n <= Math.min(total, 80); n++) rest.push(n);
                const worker = async () => { while (rest.length) { const r = await page(rest.shift()); out.push(...r.json.filter(x => x.type === "blob").map(x => x.path)); } };
                await Promise.all(Array.from({length: 6}, worker));
                return out;
            },
            raw: (c, sha, path) => HOSTS.gitlab.api(c) + "/repository/files/" + encodeURIComponent(path) + "/raw?ref=" + sha,
            async files(c, sha, paths, progress) { // contents by batches of 90 files through GraphQL (CORS allowed, ~12 requests for 1000 files)
                const url = (c.api || "https://gitlab.com") + "/api/graphql", out = [], queue = [];
                for (let i = 0; i < paths.length; i += 90) queue.push(paths.slice(i, i + 90)); // max complexity 200 (2 per path)
                const q = "query($p: ID!, $r: String!, $f: [String!]!) { project(fullPath: $p) { repository { blobs(ref: $r, paths: $f) { nodes { path rawTextBlob } } } } }";
                let done = 0;
                const worker = async () => {
                    while (queue.length) {
                        const batch = queue.shift();
                        let j = null;
                        for (let k = 0; k < 4 && !j; k++) {
                            const r = await fetch(url, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({query: q, variables: {p: c.repo, r: sha, f: batch}})}).catch(() => null);
                            if (r && r.ok) j = await r.json(); else await new Promise(res => setTimeout(res, 3000 * (k + 1))); // limit / network: pause and retry
                        }
                        if (!j || j.errors || !j.data || !j.data.project) throw new Error("GraphQL");
                        for (const b of j.data.project.repository.blobs.nodes) if (typeof b.rawTextBlob === "string" && b.rawTextBlob.length < 600000) out.push({path: b.path, text: b.rawTextBlob});
                        done += batch.length; progress(done, paths.length);
                    }
                };
                await Promise.all(Array.from({length: 4}, worker));
                return out;
            },
            web: (c) => (c.api || "https://gitlab.com") + "/" + c.repo
        }
    };
    async function update(manual) {
        const btn = $("update");
        if (!CONFIG.repo || CONFIG.repo.includes("{{")) { setStatus(() => tr("Graph") + " " + describe(state.meta) + ". " + tr("No repository configured for the update."), "warn"); return; }
        btn.disabled = true; btn.classList.add("spin");
        try {
            setStatus(() => tr("Checking the repository") + " <code>" + esc(CONFIG.repo) + "</code>…", "busy");
            const host = HOSTS[CONFIG.host || "github"];
            const {sha, date} = await host.head(CONFIG);
            if (sha === state.meta.sha) { setStatus(() => tr("Up to date:") + " " + describe(state.meta) + ".", "ok"); return; }
            if (date && state.meta.date && new Date(date) < new Date(state.meta.date)) {
                setStatus(() => tr("The graph shown") + " (" + describe(state.meta) + ") " + tr("is newer than the repository") + " (<code>" + short(sha) + "</code> " + tr("of") + " " + day(date) + "): " + tr("local commits not pushed?"), "ok");
                return;
            }
            const cached = load("graph");
            if (cached && cached.meta && cached.meta.sha === sha) { setData(cached, cached.meta); setStatus(() => tr("Updated:") + " " + describe(cached.meta) + ".", "ok"); return; }
            let files = null;
            const wantedAll = (await host.tree(CONFIG, sha)).filter(p => extractGraph.wanted(p)), all = wantedAll.slice(0, 2500);
            const capped = wantedAll.length > all.length ? " " + tr("(first 2500 source files of") + " " + wantedAll.length + ")" : ""; // very big repositories
            if (host.files) { // GitLab: batches through GraphQL
                try { files = await host.files(CONFIG, sha, all, (d, n) => setStatus(tr("Downloading the sources:") + " " + d + " / " + n + "…", "busy")); }
                catch (err) { files = null; } // GraphQL refused: one request per file
            }
            const wanted = files ? [] : all;
            files = files || [];
            let done = 0;
            const queue = wanted.slice();
            const worker = async () => {
                while (queue.length) {
                    const path = queue.shift();
                    const get = () => fetch(host.raw(CONFIG, sha, path)).catch(() => ({status: 429, ok: false, headers: new Headers()})); // no CORS on a 429: network error
                    let r = await get();
                    for (let k = 0; r.status === 429 && k < 4; k++) { // limit of the API: pause, then the same file again
                        setStatus(tr("API limit reached, pause…"), "busy");
                        await new Promise(res => setTimeout(res, 1000 * Math.min(60, +r.headers.get("retry-after") || 15)));
                        r = await get();
                    }
                    if (r.ok) files.push({path, text: await r.text()});
                    if (++done % 10 === 0 || done === wanted.length) setStatus(tr("Downloading the sources:") + " " + done + " / " + wanted.length + "…", "busy");
                }
            };
            await Promise.all(Array.from({length: host.files ? 8 : 32}, worker)); // GitHub raw files (CDN): 32 at a time; the GitLab API: 8
            setStatus(() => tr("Building the graph…"), "busy");
            const graph = extractGraph(files);
            graph.meta = {sha, date, source: "live", files: files.length, capped};
            setData(graph, graph.meta);
            store("graph", graph);
            setStatus(() => tr("Updated:") + " " + describe(graph.meta) + " · " + graph.nodes.length + " " + tr("nodes") + (graph.meta.capped || "") + ".", "ok");
        } catch (e) {
            setStatus(() => tr("Update impossible") + " (" + esc(tr(String(e.message || e))) + "). " + tr("Graph shown:") + " " + describe(state.meta) + ".", "warn");
        } finally {
            btn.disabled = false; btn.classList.remove("spin");
        }
    }

    // ---------- Controls ---------- //
    // ---------- Diagram mode: execution flow, inheritance tree, flame graph ---------- //
    // Built from the relations of the graph (calls / inherits), drawn as boxes on a 2D plane (same camera as the 2D view)
    function callsOut() {
        const out = new Map();
        for (const l of state.data.links) if (l.kind === "calls") { if (!out.has(l.source)) out.set(l.source, []); if (!out.get(l.source).includes(l.target)) out.get(l.source).push(l.target); }
        return out;
    }
    function reach(out, id, limit = 400) { const seen = new Set([id]), q = [id]; while (q.length && seen.size < limit) for (const x of out.get(q.shift()) || []) if (!seen.has(x)) { seen.add(x); q.push(x); } return seen.size - 1; }
    function flowRoots() { // entry points: main() first, then the callers nobody calls, the biggest first
        const out = callsOut(), called = new Set([...out.values()].flat());
        const list = state.data.nodes.filter(n => out.has(n.id) && (n.entry || !called.has(n.id)));
        const rank = (n) => (n.kind === "test-helper" || n.kind === "test" ? 2 : 0) + (n.entry ? 0 : 1); // real main() first, the tests last
        return list.map(n => ({n, size: reach(out, n.id)})).sort((a, b) => rank(a.n) - rank(b.n) || b.size - a.size).map(x => x.n);
    }
    function flowSub(n) { // second line of a box: class of a method, namespace / file of a function, kind otherwise
        if (n.kind === "method") { const c = state.byId.get(n.id.slice(0, n.id.lastIndexOf("::"))); return c ? c.label : ""; }
        if (n.kind === "function") return n.ns || (n.path || "").split("/").pop();
        return tr((KINDS[n.kind] || ["", n.kind])[1]);
    }
    function measure(text, font) { ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.font = font; const w = ctx.measureText(text).width; ctx.restore(); return w; }
    const FONT = {t: "600 12px system-ui, sans-serif", s: "11px system-ui, sans-serif"};
    function makeBox(n, extra) {
        const whole = flowSub(n), label = clipLabel(n.label), sub = clipLabel(whole);
        return Object.assign({id: n.id, n, label, sub, owner: whole, w: Math.max(measure(label, FONT.t), sub ? measure(sub, FONT.s) : 0) + 22, h: sub ? 40 : 28}, extra || {});
    }
    function layered(layers, parentsOf, groupKey) { // order the layers (barycenter of the parents, boxes of a group side by side), then place them
        const pos = new Map();
        layers.forEach(L => L.forEach((b, i) => pos.set(b.id, i)));
        for (let pass = 0; pass < 4; pass++) for (let d = 1; d < layers.length; d++) {
            const bary = (b) => { const ps = parentsOf(b.id).filter(p => pos.has(p)); return ps.length ? ps.reduce((s, p) => s + pos.get(p), 0) / ps.length : pos.get(b.id); };
            const gb = new Map(); // barycenter of each group in the layer
            for (const b of layers[d]) { const k = groupKey(b); const g = gb.get(k) || [0, 0]; g[0] += bary(b); g[1]++; gb.set(k, g); }
            layers[d].sort((a, b) => { const ga = gb.get(groupKey(a)), gb2 = gb.get(groupKey(b)); return ga[0] / ga[1] - gb2[0] / gb2[1] || bary(a) - bary(b); });
            layers[d].forEach((b, i) => pos.set(b.id, i));
        }
        const GAP = 26, ROW = 96, MAXW = 1500; // a layer wider than MAXW wraps on several rows
        let y = 0;
        layers.forEach((L, d) => {
            const rows = [[]];
            let w = 0;
            for (const b of L) { if (w + b.w > MAXW && rows[rows.length - 1].length) { rows.push([]); w = 0; } rows[rows.length - 1].push(b); w += b.w + GAP; }
            rows.forEach((R, ri) => {
                const width = R.reduce((s, b) => s + b.w, 0) + GAP * Math.max(0, R.length - 1);
                let x = -width / 2;
                for (const b of R) { b.x = x; b.y = y + ri * (b.h + 18); b.depth = d; x += b.w + GAP; }
            });
            y += ROW + (rows.length - 1) * 58;
        });
    }
    function bboxOf(boxes) {
        const r = {x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity};
        for (const b of boxes) { r.x0 = Math.min(r.x0, b.x); r.y0 = Math.min(r.y0, b.y); r.x1 = Math.max(r.x1, b.x + b.w); r.y1 = Math.max(r.y1, b.y + b.h); }
        return boxes.length ? r : {x0: -100, y0: -100, x1: 100, y1: 100};
    }
    function buildFlow() {
        const view = state.flowView, out = callsOut();
        const roots = flowRoots();
        // entry point selector (execution / flame)
        const sel = $("flowRoot");
        if (!state.flowRoot || !state.byId.has(state.flowRoot) || !out.has(state.flowRoot)) state.flowRoot = roots[0] ? roots[0].id : null;
        sel.textContent = "";
        const opts = roots.slice(0, 60);
        if (state.flowRoot && !opts.some(n => n.id === state.flowRoot)) opts.unshift(state.byId.get(state.flowRoot));
        for (const n of opts) { const o = document.createElement("option"); o.value = n.id; const s = flowSub(n); o.textContent = clipLabel(n.label) + (n.kind === "method" && s ? " · " + clipLabel(s) : ""); sel.appendChild(o); }
        sel.value = state.flowRoot || "";
        sel.hidden = view === "inherit" || !opts.length;
        let boxes = [], edges = [], groups = [], empty = "";
        if (view === "exec") {
            if (!state.flowRoot) empty = "No call found in the sources (the calls are read in the bodies of the C / C++ functions).";
            else {
                const depth = new Map([[state.flowRoot, 0]]), q = [state.flowRoot];
                while (q.length && depth.size < 160) { const id = q.shift(); if (depth.get(id) >= 9) continue; for (const x of out.get(id) || []) if (!depth.has(x)) { depth.set(x, depth.get(id) + 1); q.push(x); } }
                const layers = [];
                for (const [id, d] of depth) { (layers[d] = layers[d] || []).push(makeBox(state.byId.get(id))); }
                const parents = new Map();
                for (const [a, list] of out) if (depth.has(a)) for (const b of list) if (depth.has(b)) { edges.push({a, b}); if (!parents.has(b)) parents.set(b, []); parents.get(b).push(a); }
                layered(layers, id => parents.get(id) || [], b => b.n.kind === "method" ? b.owner : b.id);
                boxes = layers.flat();
                for (const L of layers) { // dashed containers around the methods of the same class in a layer
                    let i = 0;
                    while (i < L.length) { let j = i; while (j + 1 < L.length && L[j + 1].n.kind === "method" && L[i].n.kind === "method" && L[j + 1].owner === L[i].owner) j++; if (j > i) groups.push({label: L[i].sub, boxes: L.slice(i, j + 1)}); i = j + 1; }
                }
            }
        } else if (view === "inherit") {
            const bases = new Map(), set = new Set();
            const src = (id) => !/^tests?\//.test((state.byId.get(id) || {}).path || ""); // the classes of the sources (not the test helpers)
            for (const l of state.data.links) if (l.kind === "inherits" && src(l.source)) { set.add(l.source); set.add(l.target); if (!bases.has(l.source)) bases.set(l.source, []); bases.get(l.source).push(l.target); }
            if (!set.size) empty = "No inheritance between the classes of the project.";
            const depth = new Map(), visiting = new Set();
            const dep = (id) => { if (depth.has(id)) return depth.get(id); if (visiting.has(id)) return 0; visiting.add(id); const d = Math.max(-1, ...(bases.get(id) || []).map(dep)) + 1; visiting.delete(id); depth.set(id, d); return d; };
            const layers = [];
            for (const id of set) { const d = dep(id); (layers[d] = layers[d] || []).push(makeBox(state.byId.get(id))); }
            for (let d = 0; d < layers.length; d++) layers[d] = layers[d] || [];
            for (const [a, list] of bases) for (const b of list) edges.push({a, b, inherit: true});
            layered(layers, id => bases.get(id) || [], b => b.id);
            boxes = layers.flat();
        } else { // flame graph: call tree from the entry point, width = size of the subtree (static: no run time)
            const rootId = state.flamePath.length ? state.flamePath[state.flamePath.length - 1] : state.flowRoot;
            if (!rootId) empty = "No call found in the sources (the calls are read in the bodies of the C / C++ functions).";
            else {
                let count = 0;
                const build = (id, path, d) => { count++; const f = {id, kids: []}; if (d < 18 && count < 4000) for (const x of out.get(id) || []) if (!path.has(x)) { path.add(x); f.kids.push(build(x, path, d + 1)); path.delete(x); } f.size = 1 + f.kids.reduce((s, k) => s + k.size, 0); return f; };
                const tree = build(rootId, new Set([rootId]), 0), W = Math.max(900, Math.min(4000, tree.size * 28)), H = 24;
                const anc = state.flamePath.slice(0, -1); // zoomed in: the ancestors as full rows below (click to go back)
                anc.forEach((id, i) => boxes.push({id, n: state.byId.get(id), label: state.byId.get(id).label, sub: "", x: 0, y: (anc.length - i) * H, w: W, h: H - 2, anc: i}));
                const place = (f, x, d) => {
                    const w = W * f.size / tree.size, n = state.byId.get(f.id);
                    boxes.push({id: f.id, n, label: n.label, sub: flowSub(n), x, y: -d * H, w: Math.max(1, w - 1), h: H - 2, flame: true, size: f.size, depth: d});
                    let cx = x;
                    for (const k of f.kids) { place(k, cx, d + 1); cx += W * k.size / tree.size; }
                };
                place(tree, 0, 0);
            }
        }
        state.flowSel = new Set();
        state.flow = {boxes, edges, groups, empty, bbox: bboxOf(boxes), byId: new Map(boxes.filter(b => !b.anc && b.anc !== 0).map(b => [b.id, b]))};
    }
    function fitFlow() {
        const r = state.flow.bbox, c = state.cam;
        c.x = (r.x0 + r.x1) / 2; c.y = (r.y0 + r.y1) / 2;
        c.k = Math.min(1.4, 0.9 * Math.min(state.w / Math.max(80, r.x1 - r.x0), state.h / Math.max(80, r.y1 - r.y0)));
    }
    function flowPick(mx, my) {
        if (!state.flow) return null;
        const c = state.cam, x = (mx - state.w / 2) / c.k + c.x, y = (my - state.h / 2) / c.k + c.y;
        for (let i = state.flow.boxes.length - 1; i >= 0; i--) { const b = state.flow.boxes[i]; if (x >= b.x && x <= b.x + b.w && y >= b.y && y <= b.y + b.h) { state.flowHit = b; return b.n; } }
        state.flowHit = null;
        return null;
    }
    function roundRect(x, y, w, h, r) { ctx.beginPath(); if (ctx.roundRect) ctx.roundRect(x, y, w, h, Math.min(r, h / 2, w / 2)); else ctx.rect(x, y, w, h); }
    function drawFlow(C) {
        const F = state.flow, c = state.cam, k = c.k;
        if (!F) return;
        const S = (x, y) => [state.w / 2 + (x - c.x) * k, state.h / 2 + (y - c.y) * k];
        if (F.empty) { // the message on the lines the width of the screen allows
            ctx.fillStyle = C.muted; ctx.font = "13px system-ui, sans-serif"; ctx.textAlign = "center";
            const lines = [""];
            for (const word of tr(F.empty).split(" ")) {
                const line = lines[lines.length - 1] + (lines[lines.length - 1] ? " " : "") + word;
                if (ctx.measureText(line).width > state.w - 40 && lines[lines.length - 1]) lines.push(word); else lines[lines.length - 1] = line;
            }
            lines.forEach((line, i) => ctx.fillText(line, state.w / 2, state.h / 2 + (i - (lines.length - 1) / 2) * 18));
            return;
        }
        const focus = state.hover || state.selected;
        const q = state.search.trim().toLowerCase(); // search: matching boxes outlined, the others faded
        const hit = q ? new Set(F.boxes.filter(b => (b.n.label + " " + (b.owner || b.sub) + " " + (b.n.path || "")).toLowerCase().includes(q)).map(b => b)) : null;
        // containers (classes) of the execution flow
        ctx.setLineDash([5, 4]); ctx.lineWidth = 1;
        for (const g of F.groups) {
            const r = bboxOf(g.boxes), [x, y] = S(r.x0 - 10, r.y0 - 18);
            ctx.strokeStyle = C.muted; ctx.globalAlpha = 0.5; roundRect(x, y, (r.x1 - r.x0 + 20) * k, (r.y1 - r.y0 + 28) * k, 8 * k); ctx.stroke();
            if (k > 0.45) { ctx.globalAlpha = 1; ctx.fillStyle = C.muted; ctx.font = Math.round(10.5 * k) + "px system-ui, sans-serif"; ctx.textAlign = "left"; ctx.fillText(g.label, x + 8 * k, y + 12 * k); }
        }
        ctx.setLineDash([]); ctx.globalAlpha = 1;
        // relations
        for (const e of F.edges) {
            const a = F.byId.get(e.a), b = F.byId.get(e.b);
            if (!a || !b) continue;
            const hot = focus && (e.a === focus || e.b === focus);
            ctx.strokeStyle = hot ? C.accent : e.inherit ? LINKS.inherits[0] : LINKS.calls[0];
            ctx.globalAlpha = hot ? 1 : focus ? 0.25 : 0.7; ctx.lineWidth = hot ? 2 : 1.3;
            let p0, p1, c0, c1;
            if (e.inherit) { p0 = S(a.x + a.w / 2, a.y); p1 = S(b.x + b.w / 2, b.y + b.h); const m = (p0[1] + p1[1]) / 2; c0 = [p0[0], m]; c1 = [p1[0], m]; }
            else if (b.depth > a.depth) { p0 = S(a.x + a.w / 2, a.y + a.h); p1 = S(b.x + b.w / 2, b.y); const m = (p0[1] + p1[1]) / 2; c0 = [p0[0], m]; c1 = [p1[0], m]; }
            else { p0 = S(a.x + a.w, a.y + a.h / 2); p1 = S(b.x + b.w, b.y + b.h / 2); const o = (60 + 20 * Math.abs(a.depth - b.depth)) * k; c0 = [p0[0] + o, p0[1]]; c1 = [p1[0] + o, p1[1]]; ctx.setLineDash([5, 4]); } // back / same level call
            ctx.beginPath(); ctx.moveTo(p0[0], p0[1]); ctx.bezierCurveTo(c0[0], c0[1], c1[0], c1[1], p1[0], p1[1]); ctx.stroke(); ctx.setLineDash([]);
            const ang = Math.atan2(p1[1] - c1[1], p1[0] - c1[0]), al = Math.max(5, 8 * Math.min(1.2, k));
            ctx.beginPath(); ctx.moveTo(p1[0], p1[1]); ctx.lineTo(p1[0] - Math.cos(ang - 0.42) * al, p1[1] - Math.sin(ang - 0.42) * al); ctx.lineTo(p1[0] - Math.cos(ang + 0.42) * al, p1[1] - Math.sin(ang + 0.42) * al); ctx.closePath();
            if (e.inherit) { ctx.fillStyle = C.surface; ctx.fill(); ctx.stroke(); } else { ctx.fillStyle = ctx.strokeStyle; ctx.fill(); } // UML: hollow triangle for the inheritance
        }
        ctx.globalAlpha = 1;
        // boxes
        for (const b of F.boxes) {
            const [x, y] = S(b.x, b.y), w = b.w * k, h = b.h * k;
            if (x > state.w || y > state.h || x + w < 0 || y + h < 0) continue;
            const col = (KINDS[b.n.kind] || KINDS.external)[0], on = b.id === state.selected || b.id === state.hover || state.flowSel.has(b.id) || (hit && hit.has(b)), dim = (hit && !hit.has(b)) || focus && !on && !(b.flame || b.anc !== undefined) && !F.edges.some(e => (e.a === focus && e.b === b.id) || (e.b === focus && e.a === b.id));
            ctx.globalAlpha = dim ? 0.35 : 1;
            roundRect(x, y, w, h, (b.flame || b.anc !== undefined ? 3 : 8) * k);
            ctx.fillStyle = C.surface; ctx.fill();
            ctx.globalAlpha *= b.flame ? 0.45 : b.anc !== undefined ? 0.25 : 0.16; ctx.fillStyle = col; ctx.fill();
            ctx.globalAlpha = dim ? 0.35 : 1; ctx.lineWidth = on ? 2 : 1; ctx.strokeStyle = on ? C.accent : col; ctx.stroke();
            const fs = 12 * k;
            if (fs < 6 || w < 18) continue;
            ctx.save(); ctx.beginPath(); ctx.rect(x + 3, y, w - 6, h); ctx.clip();
            ctx.fillStyle = C.text; ctx.textAlign = b.flame || b.anc !== undefined ? "left" : "center";
            const tx = b.flame || b.anc !== undefined ? x + 6 * k : x + w / 2;
            ctx.font = "600 " + fs.toFixed(1) + "px system-ui, sans-serif";
            if (b.sub && !b.flame) { ctx.fillText(b.label, tx, y + h / 2 - 2 * k); ctx.fillStyle = C.muted; ctx.font = (11 * k).toFixed(1) + "px system-ui, sans-serif"; ctx.fillText(b.sub, tx, y + h / 2 + 12 * k); }
            else ctx.fillText(b.label + (b.flame && b.sub && w > measure(b.label + " · " + b.sub, FONT.t) * k + 12 ? " · " + b.sub : ""), tx, y + h / 2 + 4 * k);
            ctx.restore();
        }
        ctx.globalAlpha = 1;
        if (drag && drag.band) { // selection area
            const b = drag.band;
            ctx.setLineDash([4, 3]); ctx.strokeStyle = C.accent; ctx.fillStyle = C.accent; ctx.lineWidth = 1;
            ctx.globalAlpha = 0.08; ctx.fillRect(Math.min(b.x0, b.x1), Math.min(b.y0, b.y1), Math.abs(b.x1 - b.x0), Math.abs(b.y1 - b.y0));
            ctx.globalAlpha = 0.9; ctx.strokeRect(Math.min(b.x0, b.x1), Math.min(b.y0, b.y1), Math.abs(b.x1 - b.x0), Math.abs(b.y1 - b.y0));
            ctx.setLineDash([]); ctx.globalAlpha = 1;
        }
    }
    // Moving the boxes of a diagram: a box, the boxes of a dashed group (class), several selected boxes (Ctrl / Shift +
    // click, or Shift / Ctrl + drag on the background for an area); not in the flame graph (its frames are the layout)
    function flowDragStart(drag, mx, my, e) {
        const F = state.flow;
        if (!F || state.flowView === "flame") return;
        const c = state.cam, wx = (mx - state.w / 2) / c.k + c.x, wy = (my - state.h / 2) / c.k + c.y;
        const multi = e.ctrlKey || e.metaKey || e.shiftKey, hit = drag.clicked ? state.flowHit : null;
        if (hit && hit.anc === undefined) {
            drag.hitBox = hit; drag.multi = multi;
            drag.boxes = state.flowSel.has(hit.id) && state.flowSel.size > 1 ? F.boxes.filter(b => state.flowSel.has(b.id)) : [hit];
            return;
        }
        for (const g of F.groups) { // the dashed frame of a group (around its boxes, its label on top)
            const r = bboxOf(g.boxes);
            if (wx >= r.x0 - 10 && wx <= r.x1 + 10 && wy >= r.y0 - 18 && wy <= r.y1 + 10) { drag.group = g; drag.boxes = g.boxes; return; }
        }
        if (multi) drag.band = {x0: mx, y0: my, x1: mx, y1: my, add: e.ctrlKey || e.metaKey};
    }
    function flowDragEnd(drag, still) {
        const F = state.flow, c = state.cam;
        if (!F) return;
        if (drag.band) { // boxes inside the area
            const b = drag.band, W = (x) => (x - state.w / 2) / c.k + c.x, H = (y) => (y - state.h / 2) / c.k + c.y;
            const x0 = W(Math.min(b.x0, b.x1)), x1 = W(Math.max(b.x0, b.x1)), y0 = H(Math.min(b.y0, b.y1)), y1 = H(Math.max(b.y0, b.y1));
            if (!b.add) state.flowSel.clear();
            for (const bx of F.boxes) if (bx.anc === undefined && bx.x + bx.w >= x0 && bx.x <= x1 && bx.y + bx.h >= y0 && bx.y <= y1) state.flowSel.add(bx.id);
        } else if (drag.boxes && !still) F.bbox = bboxOf(F.boxes);
        else if (still && drag.hitBox) {
            const id = drag.hitBox.id;
            if (drag.multi) { if (state.flowSel.has(id)) state.flowSel.delete(id); else state.flowSel.add(id); }
            else state.flowSel = new Set([id]);
            select(id);
        } else if (still && drag.group) state.flowSel = new Set(drag.group.boxes.map(b => b.id));
        else if (still) { state.flowSel.clear(); select(drag.clicked ? drag.clicked.id : null); }
        state.dirty = true;
    }
    function setFlowView(v) {
        state.flowView = v; state.flamePath = [];
        for (const b of $("flowViews").children) b.classList.toggle("active", b.dataset.flow === v);
        store("flowView", v);
        buildFlow(); fitFlow(); state.dirty = true;
    }
    for (const b of $("flowViews").children) b.addEventListener("click", () => setFlowView(b.dataset.flow));
    $("flowRoot").addEventListener("change", (e) => { state.flowRoot = e.target.value; state.flamePath = []; buildFlow(); fitFlow(); state.dirty = true; });
    canvas.addEventListener("dblclick", (e) => { // double click on a box: start the execution / flame graph from it (flame: zoom into the frame)
        if (state.mode !== "flow") return;
        const r = canvas.getBoundingClientRect(), n = flowPick(e.clientX - r.left, e.clientY - r.top), hit = state.flowHit;
        if (!n || state.flowView === "inherit") return;
        if (state.flowView === "flame") {
            if (hit && hit.anc !== undefined) state.flamePath = state.flamePath.slice(0, hit.anc + 1);
            else if (hit && hit.depth > 0) { // zoom: path from the current root to this frame
                state.flamePath = state.flamePath.length ? state.flamePath : [state.flowRoot];
                state.flamePath.push(n.id);
            } else if (state.flamePath.length) state.flamePath.pop();
        } else if (callsOut().has(n.id)) { state.flowRoot = n.id; }
        else return;
        buildFlow(); fitFlow(); state.dirty = true;
    });
    function setStyle3d(s) {
        state.style3d = s === "tech" ? "tech" : "real";
        for (const b of $("style3d").children) b.classList.toggle("active", b.dataset.style === state.style3d);
        store("style3d", state.style3d); state.dirty = true;
    }
    for (const b of $("style3d").children) b.addEventListener("click", () => setStyle3d(b.dataset.style));
    if (load("style3d")) setStyle3d(load("style3d"));
    function setMode(m) {
        const old = state.mode;
        state.cams[old] = {...state.cam}; state.lock = null;
        state.mode = m;
        $("style3d").hidden = m !== "3d";
        $("flowBar").hidden = m !== "flow";
        $("panel").classList.toggle("in-flow", m === "flow");
        $("panel").querySelectorAll(".graph-only").forEach(el => { if (m === "flow") el.setAttribute("aria-disabled", "true"); else el.removeAttribute("aria-disabled"); }); // no effect on the diagrams
        $("controlsBtn").style.left = m === "3d" ? "96px" : "14px"; // right of the axes in 3D
        $("mode2d").classList.toggle("active", m === "2d"); $("mode3d").classList.toggle("active", m === "3d"); $("modeFlow").classList.toggle("active", m === "flow");
        if (m === "flow") { buildFlow(); if (state.cams.flow) Object.assign(state.cam, state.cams.flow); else fitFlow(); refilter(false); state.dirty = true; return; }
        if (old === "flow" && state.cams[m]) { Object.assign(state.cam, state.cams[m]); refilter(false); state.dirty = true; return; }
        if (m === "3d") for (const n of state.visible) { const p = state.pos.get(n.id); if (Math.abs(p.z) < 1) p.z = (Math.random() - 0.5) * 80; }
        state.alpha = Math.max(state.alpha, 0.7);
        fit(); refilter(false); state.dirty = true;
    }
    $("mode2d").addEventListener("click", () => setMode("2d"));
    $("mode3d").addEventListener("click", () => setMode("3d"));
    $("modeFlow").addEventListener("click", () => setMode("flow"));
    if (load("flowView")) { state.flowView = load("flowView"); for (const b of $("flowViews").children) b.classList.toggle("active", b.dataset.flow === state.flowView); }
    $("fit").addEventListener("click", () => { fit(); state.dirty = true; });
    $("pause").addEventListener("click", () => { state.paused = !state.paused; $("pause").textContent = state.paused ? tr("Resume") : tr("Freeze"); if (!state.paused) state.alpha = Math.max(state.alpha, 0.3); });
    $("search").addEventListener("input", (e) => { state.search = e.target.value; refilter(false); state.dirty = true; });
    $("search").addEventListener("keydown", (e) => {
        if (e.key !== "Enter") return;
        if (state.mode === "flow") { flowSearch(); return; }
        if (state.match && state.match.size) focusOn([...state.match][0]);
    });
    function flowSearch() { // Enter in the diagrams: first matching box, else start the diagram from the matching node
        const q = state.search.trim().toLowerCase();
        if (!q || !state.flow) return;
        const test = (n) => (n.label + " " + (n.path || "")).toLowerCase().includes(q);
        let b = state.flow.boxes.find(b => b.anc === undefined && test(b.n));
        if (!b && state.flowView !== "inherit") {
            const n = state.data.nodes.find(n => test(n) && callsOut().has(n.id));
            if (n) { state.flowRoot = n.id; state.flamePath = []; buildFlow(); fitFlow(); b = state.flow.byId.get(n.id); }
        }
        if (b) { select(b.id); centerOn(b.id); }
        state.dirty = true;
    }
    $("colorBy").addEventListener("change", (e) => { state.colorBy = e.target.value; state.dirty = true; if (state.selected) select(state.selected); });
    $("cluster").addEventListener("change", (e) => { state.cluster = e.target.checked; state.alpha = Math.max(state.alpha, 0.6); });
    $("labels").addEventListener("change", (e) => { state.labels = e.target.checked; state.dirty = true; });
    $("particles").addEventListener("change", (e) => { state.particles = e.target.checked; state.dirty = true; });
    $("isolate").addEventListener("change", (e) => { state.isolate = e.target.checked; refilter(true); state.dirty = true; });
    $("update").addEventListener("click", () => update(true));
    // Drawer of the small screens: its button, the button of its own, a touch on the graph, Escape (it may cover the whole screen)
    const closePanel = () => $("panel").classList.remove("open");
    $("panelToggle").addEventListener("click", () => $("panel").classList.toggle("open"));
    $("panelClose").addEventListener("click", closePanel);
    canvas.addEventListener("pointerdown", closePanel);
    document.addEventListener("keydown", (e) => { if (e.key === "Escape") closePanel(); });
    for (const b of $("presets").children) b.addEventListener("click", () => {
        const p = PRESETS[b.dataset.preset];
        // Fill the sets in place: the legend entries keep a reference to them (a new Set would cut them off)
        state.kinds.clear(); p[0].forEach(k => state.kinds.add(k));
        state.linkKinds.clear(); p[1].forEach(k => state.linkKinds.add(k));
        refilter(true); setTimeout(() => { fit(); state.dirty = true; }, 400);
    });
    document.querySelectorAll("[data-all],[data-none]").forEach(b => b.addEventListener("click", () => {
        const what = b.dataset.all || b.dataset.none, on = !!b.dataset.all;
        const set = what === "kinds" ? state.kinds : what === "links" ? state.linkKinds : state.groups;
        set.clear();
        if (on) {
            const src = what === "kinds" ? state.data.nodes.map(n => n.kind) : what === "links" ? state.data.links.map(l => l.kind) : state.data.nodes.map(n => n.group);
            for (const k of src) set.add(k);
        }
        refilter(true);
        state.dirty = true; // nothing left to simulate: the drawing is not refreshed by the layout
    }));

    // ---------- Help: tooltip (hover) + card with a visual example (double click) ---------- //
    const K = (k) => (KINDS[k] || KINDS.external)[0];
    const L = (k) => (LINKS[k] || LINKS.includes)[0];
    // Example diagram: nodes [label, kind, x, y], edges [from index, to index, link kind]
    function diagram(nodes, edges, opts) {
        opts = opts || {};
        const W = 320, H = opts.h || 120, ns = "http://www.w3.org/2000/svg";
        let s = '<svg viewBox="0 0 ' + W + " " + H + '" role="img" aria-label="Example" xmlns="' + ns + '"><defs>';
        const kinds = [...new Set(edges.map(e => e[2]))];
        for (const k of kinds) s += '<marker id="hm-' + k + '" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="' + L(k) + '"/></marker>';
        s += "</defs>";
        let names = "";
        // The name of a relation where nothing is: on its line, else above or below it (the nodes, their names, the other names of relations)
        const placed = [], fontE = "10.5px system-ui, sans-serif", fontN = "11px system-ui, sans-serif";
        const blocked = (x, y, w) => placed.some(p => Math.abs(x - p[0]) < (w + p[2]) / 2 + 2 && Math.abs(y - p[1]) < 12) || nodes.some(n => {
            const r = n[4] || 9, over = (cx, half, top, bottom) => Math.abs(x - cx) < w / 2 + half + 5 && y + 2 > top && y - 9 < bottom;
            return over(n[2], r, n[3] - r, n[3] + r) || over(n[2], measure(n[0], fontN) / 2 + 2, n[3] + 10, n[3] + 28);
        });
        const nameAt = (x, y, w) => {
            for (const dy of [-5, -12, -19, -26, 13, 20, 27, -33, 34]) if (y + dy - 9 >= 0 && y + dy + 2 <= H && !blocked(x, y + dy, w)) return y + dy;
            return y - 5;
        };
        edges.forEach((e, i) => {
            const a = nodes[e[0]], b = nodes[e[1]];
            const dx = b[2] - a[2], dy = b[3] - a[3], d = Math.hypot(dx, dy) || 1;
            const x1 = a[2] + dx / d * 11, y1 = a[3] + dy / d * 11, x2 = b[2] - dx / d * 13, y2 = b[3] - dy / d * 13;
            s += '<path id="he' + i + '" d="M' + x1 + " " + y1 + "L" + x2 + " " + y2 + '" stroke="' + L(e[2]) + '" stroke-width="1.6" fill="none" marker-end="url(#hm-' + e[2] + ')"' + (opts.dim && opts.dim.includes(i) ? ' opacity=".15"' : "") + "/>";
            const name = tr((LINKS[e[2]] || ["", e[2]])[1]), nameW = measure(name, fontE), nameX = Math.max(nameW / 2 + 2, Math.min(W - nameW / 2 - 2, (x1 + x2) / 2)), nameY = nameAt(nameX, (y1 + y2) / 2, nameW);
            placed.push([nameX, nameY, nameW]);
            if (!(opts.dim && opts.dim.includes(i))) names += '<text class="e-lbl" x="' + nameX + '" y="' + nameY + '" text-anchor="middle">' + esc(name) + "</text>"; // a faded relation: no name to squint at
            if (opts.particles !== false) for (let k = 0; k < 2; k++)
                s += '<circle r="2.6" fill="' + L(e[2]) + '"><animateMotion dur="2.4s" begin="' + (k * 1.2) + 's" repeatCount="indefinite"><mpath href="#he' + i + '"/></animateMotion></circle>';
        });
        nodes.forEach((n, i) => {
            const faded = opts.dimNodes && opts.dimNodes.includes(i);
            s += '<circle cx="' + n[2] + '" cy="' + n[3] + '" r="' + (n[4] || 9) + '" fill="' + (n[5] || K(n[1])) + '"' + (faded ? ' opacity=".2"' : "") + (opts.ring === i ? ' stroke="' + state.colors.accent + '" stroke-width="2.5"' : "") + "/>";
            if (!faded) s += '<text class="n-lbl" x="' + n[2] + '" y="' + (n[3] + 22) + '" text-anchor="middle">' + esc(n[0]) + "</text>";
        });
        return s + names + "</svg>";
    }
    const EX = {
        header: () => diagram([["Server.cpp", "source", 50, 45], ["Server.hpp", "header", 160, 45], ["Server", "class", 270, 45]], [[0, 1, "includes"], [1, 2, "defines"]]),
        source: () => diagram([["Server.hpp", "header", 50, 45], ["Server.cpp", "source", 160, 45], ["app", "executable", 270, 45]], [[1, 0, "includes"], [1, 2, "compiled-into"]]),
        testFile: () => diagram([["tests/Server.cpp", "test-file", 60, 45], ["Server.Listen", "test", 180, 90], ["Server", "class", 270, 35]], [[0, 1, "defines"], [0, 2, "tests"]]),
        cls: () => diagram([["Server.hpp", "header", 45, 45], ["Server", "class", 160, 45], ["listen()", "method", 270, 85], ["AServer", "abstract", 270, 20]], [[0, 1, "defines"], [1, 2, "member"], [1, 3, "inherits"]]),
        iface: () => diagram([["TCPSocket", "class", 45, 45], ["ASocket", "abstract", 160, 45], ["ISocket", "interface", 270, 45]], [[0, 1, "inherits"], [1, 2, "inherits"]]),
        enumT: () => diagram([["NetworkDefine.hpp", "header", 70, 45], ["Status", "enum", 250, 45]], [[0, 1, "defines"]]),
        func: () => diagram([["ASocket.hpp", "header", 70, 45], ["is_ip()", "function", 250, 45]], [[0, 1, "defines"]]),
        method: () => diagram([["Scheduler", "class", 70, 45], ["schedule()", "method", 250, 25], ["cancel()", "method", 250, 80]], [[0, 1, "member"], [0, 2, "member"]]),
        test: () => diagram([["tests/IdHandler.cpp", "test-file", 70, 45], ["IdHandler.Allocate", "test", 250, 45]], [[0, 1, "defines"]]),
        helper: () => diagram([["tests/Rules.cpp", "test-file", 60, 45], ["MockRule", "test-helper", 170, 45], ["IRule", "interface", 275, 45]], [[0, 1, "defines"], [1, 2, "inherits"]]),
        exe: () => diagram([["main.cpp", "source", 45, 45], ["app", "executable", 160, 45], ["utils", "external", 275, 45]], [[0, 1, "compiled-into"], [1, 2, "links"]]),
        lib: () => diagram([["Core.cpp", "source", 45, 45], ["libcore", "library", 160, 45], ["openssl", "external", 275, 45]], [[0, 1, "compiled-into"], [1, 2, "links"]]),
        ext: () => diagram([["Forge.hpp", "header", 50, 45], ["app", "executable", 50, 95], ["libconfig", "external", 250, 70]], [[0, 2, "includes"], [1, 2, "links"]], {h: 125}),
        link: (k, a, b) => diagram([[a[0], a[1], 70, 45], [b[0], b[1], 250, 45]], [[0, 1, k]]),
        overview: () => diagram([["main.cpp", "source", 40, 30], ["Core.hpp", "header", 150, 30], ["Core", "class", 270, 30], ["app", "executable", 130, 95], ["utils", "external", 265, 95]], [[0, 1, "includes"], [1, 2, "defines"], [0, 3, "compiled-into"], [3, 4, "links"]], {h: 125}),
        groups: () => diagram([["Server", "class", 60, 40, 9, "hsl(210 55% 55%)"], ["Client", "class", 110, 85, 9, "hsl(210 55% 55%)"], ["IdHandler", "class", 230, 40, 9, "hsl(30 55% 55%)"], ["Scheduler", "class", 275, 90, 9, "hsl(30 55% 55%)"]], [[0, 1, "includes"], [3, 2, "includes"]], {h: 125}),
        isolate: () => diagram([["Server", "class", 175, 62], ["Client", "class", 40, 22], ["ISocket", "interface", 285, 22], ["Matrix", "class", 40, 100], ["Vector2", "class", 285, 100]], [[1, 0, "includes"], [0, 2, "inherits"], [3, 4, "includes"]], {h: 125, ring: 0, dim: [2], dimNodes: [3, 4]}),
        flat: () => diagram([["A", "class", 40, 45], ["B", "header", 160, 45], ["C", "source", 280, 45]], [[2, 1, "includes"], [1, 0, "defines"]], {particles: false}),
        persp: () => diagram([["A", "class", 45, 35, 13], ["B", "header", 160, 60, 9], ["C", "source", 285, 80, 6]], [[2, 1, "includes"], [1, 0, "defines"]], {particles: false})
    };
    const HELP = {
        update: ["Update", "Fetches the last version of the GitHub repository and rebuilds the graph.", "Asks the GitHub API for the last commit of the branch. If it is newer than the graph shown, the sources are downloaded and the graph is rebuilt in the browser (and cached). Run once automatically at load. Offline, private repository or API limit: the embedded graph stays and the status says why.", "overview"],
        mode2d: ["2D view", "Flat graph: drag to move, scroll to zoom.", "Flat rendering, the most readable for the names. Dragging the background moves the view, dragging a node moves it, the scroll zooms under the cursor, a click opens the details.", "flat"],
        mode3d: ["3D view", "Graph in perspective: drag to rotate, Shift + drag to move.", "Nodes are shaded spheres spread in depth: the closest are bigger and brighter, the farthest fade out; the light is fixed in the scene, a floor grid and the X / Y / Z gizmo (bottom left, click: reset the angle) show the orientation. Dragging a node moves it in the plane of the screen; dragging the background rotates the scene, Shift + drag (or right click) moves it, the scroll brings the camera closer. Useful to untangle a dense graph.", "persp"],
        style3d: ["3D style", "Realistic or technical rendering of the 3D view.", "Realistic (default): shaded spheres lit by a light fixed in the scene, depth fog and a floor grid. Technical: the faceted spheres of a WebGL graph (8 x 8 faces, soft light from the top, no light spot) and cone arrows, no fog or floor; closer to a 3D modeling tool.", "persp"],
        fit: ["Fit", "Centers and zooms to see every displayed node.", "Computes the box containing every visible node and adapts the zoom (2D) or the camera distance (3D).", "overview"],
        pause: ["Freeze / Resume", "Stops or restarts the force simulation.", "Nodes are placed by a physical simulation (repulsion between nodes, springs on the relations). Freeze keeps the current layout to read it quietly; Resume puts it in motion again.", "flat"],
        search: ["Search", "Highlights the nodes whose name or path contains the text.", "The search looks at the name and the path of the visible nodes. The others are faded; Enter centers the view on the first result and opens its details.", "isolate"],
        colorBy: ["Color by", "Colors the nodes by category (kind) or by group (module).", "\"category\": one color per kind of node (header, class, test...). \"group\": one color per module folder, handy to see how the project is split.", "groups"],
        cluster: ["Cluster by group", "Pulls the nodes of a same module together.", "Adds a force pulling every node towards the center of its group: modules become separate islands. Combine it with \"Color by group\".", "groups"],
        labels: ["Show names", "Shows the name of the nodes when the zoom allows it.", "Names appear from a given zoom (and always for the hovered or selected node, its neighbours and the search results). Uncheck for a cleaner view.", "flat"],
        particles: ["Animate the direction", "Dots travel along every relation, from the source to the target.", "Shows the direction of the arrows without zooming: dots go from the dependent to the dependency (file -> included header, class -> base class, source -> CMake target...). Off by default since it redraws continuously (more CPU).", "overview"],
        isolate: ["Isolate the selection", "Only shows the selected node and its direct neighbours.", "Once a node is selected (click), only it and the nodes linked by the visible relations stay displayed. Handy to follow the dependencies of a class.", "isolate"],
        "preset:overview": ["Overview", "Files, types, functions, targets and external dependencies, no methods nor tests.", "Shows the structure of the project: headers, sources, classes/structs/enums, free functions, CMake targets and external libraries, linked by includes, inherits, defines, compiled into and links.", "overview"],
        "preset:files": ["Files & includes", "Only the files and their #include.", "The include graph: useful to spot the central headers, circular dependencies or useless includes.", "header"],
        "preset:classes": ["Classes & inheritance", "The types and their inheritance.", "Interfaces (I...), abstract classes (A...), classes and structs, linked by \"inherits\": the hierarchy of the project.", "iface"],
        "preset:members": ["Classes & methods", "The types with their methods.", "Adds the methods linked to their class by \"member\". Can be dense on a big project: combine it with the search or the isolation.", "method"],
        "preset:tests": ["Tests", "Test files, test cases and tested classes.", "Shows what each test file covers (\"tests\") and its test cases: a class without an incoming \"tests\" arrow is not tested.", "testFile"],
        "preset:build": ["Build", "Sources, build targets / packages and their dependencies.", "Which sources are compiled into which executable / library, and what each target links.", "exe"],
        "preset:all": ["All", "Every category and relation.", "The whole graph, methods and tests included. On a big project, use the filters afterwards.", "overview"],
        "kind:header": ["Header", "Header file (.hpp, .h...).", "Declares the classes, functions and types. It is included by the sources and the other headers, and defines types.", "header"],
        "kind:source": ["Source", "Source file (.cpp, .py, .ts, .java, .go, .rs...).", "Implements the functions, classes and methods. It includes / imports other files and is part of a build target (CMake target or package).", "source"],
        "kind:test-file": ["Test file", "File of the tests/ folder.", "Contains test cases and references the classes it tests.", "testFile"],
        "kind:class": ["Class", "C++ class (declared with class).", "Defined by a header, it has methods (member) and can inherit other classes.", "cls"],
        "kind:struct": ["Struct", "Data structure (struct).", "Usually a plain data type defined in a types header (XType.hpp).", "enumT"],
        "kind:interface": ["Interface", "Class named I... (pure virtual methods).", "Common contract: the abstract A... then the concrete classes inherit it.", "iface"],
        "kind:abstract": ["Abstract", "Class named A... or with pure virtual methods.", "Shared implementation between an interface and the concrete classes.", "iface"],
        "kind:enum": ["Enum", "Enumeration (enum / enum class).", "Set of named values, usually defined in an XDefine.hpp header.", "enumT"],
        "kind:function": ["Function", "Free function (outside a class).", "Tool function declared in a header or a source.", "func"],
        "kind:method": ["Method", "Method of a class.", "Linked to its class by \"member\". Overloaded methods appear once (number of overloads in the details).", "method"],
        "kind:test": ["Test", "Test case (TEST, TEST_F, TEST_P).", "Defined by a test file.", "test"],
        "kind:test-helper": ["Test helper", "Class or function written for the tests (fixture, mock).", "E.g. a mock implementing an interface to test the code using it.", "helper"],
        "kind:executable": ["Executable", "Program: CMake add_executable, or a package with an entry point (main, bin, scripts).", "The sources compiled into it point to it; it points to the libraries it links.", "exe"],
        "kind:library": ["Library", "Library: CMake add_library, or a package (package.json, pyproject, Cargo, go.mod, pom...).", "Sources are compiled into it; it can link other libraries.", "lib"],
        "kind:page": ["Page", "HTML page (.html).", "Points to the scripts, stylesheets and pages it loads or links (script src, link href, a href).", "header"],
        "kind:style": ["Stylesheet", "Stylesheet (.css, .scss, .sass, .less).", "Imported by the pages and the components; points to the stylesheets it @imports.", "header"],
        "kind:external": ["External", "Dependency outside the project (system library, base class of a library).", "Comes from an #include <...> or a target_link_libraries: utils, gtest, openssl...", "ext"],
        "link:includes": ["includes / imports", "A file includes / imports another one.", "Arrow from the file to the file it #includes / imports (import, require, use, using, script / link of a page, @import of a stylesheet), or to the external package.", ["includes", ["Server.cpp", "source"], ["Server.hpp", "header"]]],
        "link:defines": ["defines", "A file declares a type, a function or a test.", "Arrow from the file to what it defines.", ["defines", ["Server.hpp", "header"], ["Server", "class"]]],
        "link:member": ["member", "A method (or an inner enum) belongs to a class.", "Arrow from the class to its method.", ["member", ["Server", "class"], ["listen()", "method"]]],
        "link:inherits": ["inherits", "A class derives from another one.", "Arrow from the derived class to the base class.", ["inherits", ["TCPSocket", "class"], ["ASocket", "abstract"]]],
        "link:implements": ["implements", "A source defines the methods of a class.", "Arrow from the .cpp to the class whose definitions it contains (Server::listen...).", ["implements", ["Server.cpp", "source"], ["Server", "class"]]],
        "link:compiled-into": ["compiled into", "A source is part of a build target.", "Arrow from the source to the executable / library compiling it (CMake SRC list) or to the package of its folder.", ["compiled-into", ["main.cpp", "source"], ["app", "executable"]]],
        "link:links": ["links", "A target links a library / a package depends on another one.", "Arrow from the target to the library (target_link_libraries) or from the package to its dependency (manifest).", ["links", ["app", "executable"], ["utils", "external"]]],
        "link:tests": ["tests", "A test file uses a class.", "Arrow from the test file to the class it references: a class without an incoming \"tests\" arrow is not covered.", ["tests", ["tests/Server.cpp", "test-file"], ["Server", "class"]]],
        modeFlow: ["Diagrams", "Execution flow, inheritance tree or flame graph of the project.", "Readable diagrams built from the relations of the graph: the execution flow from an entry point (who calls what, the methods of a class grouped), the inheritance tree of the classes, and a flame graph of the call tree. The calls are read in the bodies of the C / C++ functions (static: no run time).", ["calls", ["main()", "function"], ["run()", "method"]]],
        "flow:exec": ["Execution", "Calls from an entry point, level by level.", "Starts from main() (or the entry point of the list) and follows the calls: each level is one call deeper, the methods of the same class are grouped in a dashed box, a dashed arrow goes back to an earlier level (loop or recursion). Double click a box to start from it.", ["calls", ["run()", "method"], ["exec()", "method"]]],
        "flow:inherit": ["Inheritance", "Tree of the classes of the sources.", "The bases on top, the derived classes below, a hollow triangle on the base (UML). Only the classes of the sources (not the test helpers).", "iface"],
        "flow:flame": ["Flame graph", "Call tree, the width of a frame = size of its subtree.", "The entry point at the bottom, each row is one call deeper. Static: the width is the number of calls below, not a measured time. Double click a frame to zoom into it, the rows below to go back.", ["calls", ["server()", "method"], ["formatCFG()", "method"]]],
        repo: ["Repository", "The repository shown: GitHub or GitLab link, Enter / Open to load it.", "owner/repo, https://github.com/owner/repo(/tree/branch), https://gitlab.com/group/project(/-/tree/branch) or a self-hosted GitLab. The sources are read by the browser (GitHub: 60 API requests per hour without account, 3 per load). The link is remembered until Ctrl + Shift + R (forgets it and reloads the page); ?repo=owner/name in the address opens a repository directly.", "overview"],
        flowRoot: ["Entry point", "Where the execution flow / flame graph starts.", "main() first, then the functions and methods nobody calls (the biggest first).", ["calls", ["main()", "function"], ["init()", "method"]]],
        "link:calls": ["calls", "A function / method calls another one.", "Arrow from the caller to the called function, method or class (construction). Read in the bodies of the functions, resolved by name and by the type of the objects.", ["calls", ["run()", "method"], ["exec()", "method"]]],
        group: ["Group", "Module folder (include/<project>/<module>, src/..., tests/<module>).", "Every node belongs to the module of its file. Disabling a group hides everything coming from it; \"Color by group\" and \"Cluster by group\" make the split visible.", "groups"],
        "group:external": ["External group", "Everything coming from outside the project.", "Linked or included libraries and base classes belonging to a library.", "ext"],
        "group:build": ["Build group", "The build targets and the packages.", "Executables and libraries of the CMakeLists.txt and the packages of the manifests (package.json, pyproject.toml, Cargo.toml, go.mod...).", "exe"]
    };
    const HELP_FR = {
        update: ["Mettre à jour", "Récupère la dernière version du dépôt GitHub et reconstruit le graphe.", "Interroge l'API GitHub pour le dernier commit de la branche. S'il est plus récent que le graphe affiché, les sources sont téléchargées et le graphe est reconstruit dans le navigateur (gardé en cache). Lancé une fois automatiquement au chargement. Hors ligne, dépôt privé ou limite d'API : le graphe embarqué reste affiché et le statut dit pourquoi.", "overview"],
        mode2d: ["Vue 2D", "Graphe à plat : glisser pour déplacer, molette pour zoomer.", "Rendu à plat, le plus lisible pour lire les noms. Glisser le fond déplace la vue, glisser un nœud le déplace, la molette zoome sous le curseur, un clic ouvre les détails.", "flat"],
        mode3d: ["Vue 3D", "Graphe en perspective : glisser pour tourner, Maj + glisser pour déplacer.", "Les nœuds sont des sphères ombrées réparties en profondeur : les plus proches sont plus gros et plus nets, les plus lointains s'estompent ; la lumière est fixe dans la scène, un sol quadrillé et le repère X / Y / Z (en bas à gauche, clic : réinitialiser l'angle) montrent l'orientation. Glisser un nœud le déplace dans le plan de l'écran ; glisser le fond fait tourner la scène, Maj + glisser (ou clic droit) la déplace, la molette rapproche la caméra. Utile pour démêler un graphe dense.", "persp"],
        style3d: ["Style 3D", "Rendu réaliste ou technique de la vue 3D.", "Réaliste (par défaut) : sphères ombrées éclairées par une lumière fixe dans la scène, brouillard de profondeur et sol quadrillé. Technique : les sphères à facettes d'un graphe WebGL (8 x 8 faces, lumière douce par le haut, sans point de lumière) et flèches en cônes, sans brouillard ni sol ; plus proche d'un outil de modélisation 3D.", "persp"],
        fit: ["Ajuster", "Recentre et zoome pour voir tous les nœuds affichés.", "Calcule la boîte qui contient tous les nœuds visibles et adapte le zoom (2D) ou la distance de la caméra (3D).", "overview"],
        pause: ["Figer / Relancer", "Arrête ou relance la simulation des forces.", "Le placement des nœuds est calculé par une simulation physique (répulsion entre nœuds, ressorts sur les relations). Figer la fige dans son état actuel pour lire tranquillement ; Relancer la remet en mouvement.", "flat"],
        search: ["Recherche", "Surligne les nœuds dont le nom ou le chemin contient le texte.", "La recherche porte sur le nom et le chemin des nœuds visibles. Les autres sont estompés ; Entrée centre la vue sur le premier résultat et ouvre ses détails.", "isolate"],
        colorBy: ["Couleur par", "Colore les nœuds par catégorie (type) ou par groupe (module).", "« catégorie » : une couleur par type de nœud (header, classe, test...). « groupe » : une couleur par dossier de module, pratique pour voir le découpage du projet.", "groups"],
        cluster: ["Rapprocher par groupe", "Attire les nœuds d'un même module les uns vers les autres.", "Ajoute une force qui tire chaque nœud vers le centre de son groupe : les modules forment des îlots séparés. À combiner avec « Couleur par groupe ».", "groups"],
        labels: ["Afficher les noms", "Affiche le nom des nœuds quand le zoom le permet.", "Les noms apparaissent à partir d'un certain zoom (et toujours pour le nœud survolé, sélectionné, ses voisins et les résultats de recherche). Décocher pour une vue plus épurée.", "flat"],
        particles: ["Animer le sens des relations", "Des points circulent sur chaque relation, de la source vers la cible.", "Montre le sens des flèches sans zoomer : les points partent du dépendant et vont vers la dépendance (fichier -> header inclus, classe -> classe de base, source -> cible CMake...). Désactivé par défaut car il redessine en continu (plus de calcul).", "overview"],
        isolate: ["Isoler la sélection", "N'affiche que le nœud sélectionné et ses voisins directs.", "Une fois un nœud sélectionné (clic), seuls lui et les nœuds reliés par les relations visibles restent affichés. Pratique pour suivre les dépendances d'une classe.", "isolate"],
        "preset:overview": ["Vue d'ensemble", "Fichiers, types, fonctions, cibles et dépendances externes, sans méthodes ni tests.", "Montre la structure du projet : headers, sources, classes/structs/enums, fonctions libres, cibles CMake et bibliothèques externes, reliés par inclut, hérite de, définit, compilé dans et lié à.", "overview"],
        "preset:files": ["Fichiers & includes", "Uniquement les fichiers et leurs #include.", "Le graphe des inclusions : utile pour repérer les headers centraux, les dépendances circulaires ou les inclusions inutiles.", "header"],
        "preset:classes": ["Classes & héritage", "Les types et leurs relations d'héritage.", "Interfaces (I...), classes abstraites (A...), classes et structs, reliées par « hérite de » : la hiérarchie du projet.", "iface"],
        "preset:members": ["Classes & méthodes", "Les types avec leurs méthodes.", "Ajoute les méthodes reliées à leur classe par « membre ». Peut être dense sur un gros projet : combiner avec la recherche ou l'isolement.", "method"],
        "preset:tests": ["Tests", "Fichiers de test, cas de test et classes testées.", "Montre ce que chaque fichier de test couvre (« teste ») et ses cas de test : une classe sans flèche « teste » n'est pas testée.", "testFile"],
        "preset:build": ["Build", "Sources, cibles de build / paquets et leurs dépendances.", "Quelles sources sont compilées dans quel exécutable / bibliothèque, et ce que chaque cible lie.", "exe"],
        "preset:all": ["Tout", "Toutes les catégories et relations.", "Tout le graphe, méthodes et tests compris. Sur un gros projet, utiliser les filtres ensuite.", "overview"],
        "kind:header": ["Header", "Fichier d'en-tête (.hpp, .h...).", "Déclare les classes, fonctions et types. Il est inclus par les sources et les autres headers, et définit des types.", "header"],
        "kind:source": ["Source", "Fichier source (.cpp, .py, .ts, .java, .go, .rs...).", "Implémente les fonctions, classes et méthodes. Il inclut / importe d'autres fichiers et fait partie d'une cible de build (cible CMake ou paquet).", "source"],
        "kind:test-file": ["Fichier de test", "Fichier du dossier tests/.", "Contient des cas de test et référence les classes qu'il teste.", "testFile"],
        "kind:class": ["Classe", "Classe C++ (déclarée avec class).", "Définie par un header, elle a des méthodes (membre) et peut hériter d'autres classes.", "cls"],
        "kind:struct": ["Struct", "Structure de données (struct).", "Souvent un type de données simple défini dans un header de types (XType.hpp).", "enumT"],
        "kind:interface": ["Interface", "Classe nommée I... (méthodes virtuelles pures).", "Contrat commun : les classes abstraites A... puis concrètes en héritent.", "iface"],
        "kind:abstract": ["Abstraite", "Classe nommée A... ou avec des méthodes virtuelles pures.", "Implémentation partagée entre une interface et les classes concrètes.", "iface"],
        "kind:enum": ["Enum", "Énumération (enum / enum class).", "Ensemble de valeurs nommées, en général défini dans un header XDefine.hpp.", "enumT"],
        "kind:function": ["Fonction", "Fonction libre (hors classe).", "Fonction outil déclarée dans un header ou une source.", "func"],
        "kind:method": ["Méthode", "Méthode d'une classe.", "Reliée à sa classe par « membre ». Les méthodes surchargées n'apparaissent qu'une fois (nombre de surcharges dans les détails).", "method"],
        "kind:test": ["Test", "Cas de test (TEST, TEST_F, TEST_P).", "Défini par un fichier de test.", "test"],
        "kind:test-helper": ["Aide de test", "Classe ou fonction écrite pour les tests (fixture, mock).", "Ex. un mock qui implémente une interface pour tester le code qui l'utilise.", "helper"],
        "kind:executable": ["Exécutable", "Programme : CMake add_executable, ou un paquet avec un point d'entrée (main, bin, scripts).", "Les sources qui y sont compilées pointent vers elle ; elle pointe vers les bibliothèques qu'elle lie.", "exe"],
        "kind:library": ["Bibliothèque", "Bibliothèque : CMake add_library, ou un paquet (package.json, pyproject, Cargo, go.mod, pom...).", "Les sources y sont compilées ; elle peut lier d'autres bibliothèques.", "lib"],
        "kind:page": ["Page", "Page HTML (.html).", "Pointe vers les scripts, feuilles de style et pages qu'elle charge ou lie (script src, link href, a href).", "header"],
        "kind:style": ["Feuille de style", "Feuille de style (.css, .scss, .sass, .less).", "Importée par les pages et les composants ; pointe vers les feuilles qu'elle @importe.", "header"],
        "kind:external": ["Externe", "Dépendance hors du projet (bibliothèque système, classe de base d'une lib).", "Apparaît par un #include <...> ou un target_link_libraries : utils, gtest, openssl...", "ext"],
        "link:includes": ["inclut / importe", "Un fichier en inclut / importe un autre.", "Flèche du fichier vers le fichier qu'il inclut / importe (import, require, use, using, script / link d'une page, @import d'une feuille de style), ou vers le paquet externe.", ["includes", ["Server.cpp", "source"], ["Server.hpp", "header"]]],
        "link:defines": ["définit", "Un fichier déclare un type, une fonction ou un test.", "Flèche du fichier vers ce qu'il définit.", ["defines", ["Server.hpp", "header"], ["Server", "class"]]],
        "link:member": ["membre", "Une méthode (ou un enum interne) appartient à une classe.", "Flèche de la classe vers sa méthode.", ["member", ["Server", "class"], ["listen()", "method"]]],
        "link:inherits": ["hérite de", "Une classe dérive d'une autre.", "Flèche de la classe dérivée vers la classe de base.", ["inherits", ["TCPSocket", "class"], ["ASocket", "abstract"]]],
        "link:implements": ["implémente", "Une source définit les méthodes d'une classe.", "Flèche du .cpp vers la classe dont il contient les définitions (Server::listen...).", ["implements", ["Server.cpp", "source"], ["Server", "class"]]],
        "link:compiled-into": ["compilé dans", "Une source fait partie d'une cible de build.", "Flèche de la source vers l'exécutable / la bibliothèque qui la compile (liste SRC de CMake) ou vers le paquet de son dossier.", ["compiled-into", ["main.cpp", "source"], ["app", "executable"]]],
        "link:links": ["lié à", "Une cible lie une bibliothèque / un paquet dépend d'un autre.", "Flèche de la cible vers la bibliothèque (target_link_libraries) ou du paquet vers sa dépendance (manifeste).", ["links", ["app", "executable"], ["utils", "external"]]],
        "link:tests": ["teste", "Un fichier de test utilise une classe.", "Flèche du fichier de test vers la classe qu'il référence : une classe sans flèche entrante « teste » n'est pas couverte.", ["tests", ["tests/Server.cpp", "test-file"], ["Server", "class"]]],
        modeFlow: ["Schémas", "Flux d'exécution, arbre d'héritage ou flame graph du projet.", "Schémas lisibles construits à partir des relations du graphe : le flux d'exécution depuis un point d'entrée (qui appelle quoi, les méthodes d'une classe regroupées), l'arbre d'héritage des classes et un flame graph de l'arbre d'appels. Les appels sont lus dans le corps des fonctions C / C++ (statique : pas de temps d'exécution).", ["calls", ["main()", "function"], ["run()", "method"]]],
        "flow:exec": ["Exécution", "Appels depuis un point d'entrée, niveau par niveau.", "Part de main() (ou du point d'entrée de la liste) et suit les appels : chaque niveau est un appel plus profond, les méthodes d'une même classe sont regroupées dans un cadre pointillé, une flèche pointillée revient à un niveau précédent (boucle ou récursion). Double clic sur une boîte pour partir d'elle.", ["calls", ["run()", "method"], ["exec()", "method"]]],
        "flow:inherit": ["Héritage", "Arbre des classes des sources.", "Les bases en haut, les classes dérivées en dessous, un triangle creux sur la base (UML). Uniquement les classes des sources (pas les aides des tests).", "iface"],
        "flow:flame": ["Flame graph", "Arbre d'appels, la largeur d'un bloc = taille de son sous-arbre.", "Le point d'entrée en bas, chaque ligne est un appel plus profond. Statique : la largeur est le nombre d'appels en dessous, pas un temps mesuré. Double clic sur un bloc pour zoomer, sur les lignes du dessous pour revenir.", ["calls", ["server()", "method"], ["formatCFG()", "method"]]],
        repo: ["Dépôt", "Le dépôt affiché : lien GitHub ou GitLab, Entrée / Ouvrir pour le charger.", "owner/repo, https://github.com/owner/repo(/tree/branche), https://gitlab.com/groupe/projet(/-/tree/branche) ou un GitLab auto-hébergé. Les sources sont lues par le navigateur (GitHub : 60 requêtes d'API par heure sans compte, 3 par chargement). Le lien est mémorisé jusqu'à Ctrl + Maj + R (l'oublie et recharge la page) ; ?repo=owner/nom dans l'adresse ouvre directement un dépôt.", "overview"],
        flowRoot: ["Point d'entrée", "Là où commencent le flux d'exécution / le flame graph.", "main() d'abord, puis les fonctions et méthodes que personne n'appelle (les plus grosses d'abord).", ["calls", ["main()", "function"], ["init()", "method"]]],
        "link:calls": ["appelle", "Une fonction / méthode en appelle une autre.", "Flèche de l'appelant vers la fonction, la méthode ou la classe (construction) appelée. Lue dans le corps des fonctions, résolue par le nom et par le type des objets.", ["calls", ["run()", "method"], ["exec()", "method"]]],
        group: ["Groupe", "Dossier de module (include/<projet>/<module>, src/..., tests/<module>).", "Chaque nœud appartient au module de son fichier. Désactiver un groupe masque tout ce qui en vient ; « Couleur par groupe » et « Rapprocher par groupe » rendent le découpage visible.", "groups"],
        "group:external": ["Groupe externe", "Tout ce qui vient de l'extérieur du projet.", "Bibliothèques liées ou incluses et classes de base appartenant à une bibliothèque.", "ext"],
        "group:build": ["Groupe build", "Les cibles de build et les paquets.", "Exécutables et bibliothèques des CMakeLists.txt et paquets des manifestes (package.json, pyproject.toml, Cargo.toml, go.mod...).", "exe"]
    };
    const tip = $("tip");
    let tipTimer = null, tipEl = null, tipBlocked = null; // tipBlocked: control clicked (open list): no tooltip until it loses the focus
    const helpTable = () => (window.docI18n && window.docI18n.lang() === "fr") ? HELP_FR : HELP;
    function helpOf(el) { const k = el && el.dataset ? el.dataset.help : null; const H = helpTable(); return k && H[k] ? [k, H[k]] : null; }
    document.addEventListener("mouseover", (e) => {
        const el = e.target.closest ? e.target.closest("[data-help]") : null;
        if (el === tipEl) return;
        clearTimeout(tipTimer); tip.hidden = true; tipEl = el;
        const h = helpOf(el);
        if (!h || el === tipBlocked) return;
        tipTimer = setTimeout(() => {
            tip.innerHTML = "<strong>" + esc(h[1][0]) + "</strong><br>" + esc(h[1][1]) + "<small>" + tr("Double click: description and example") + "</small>";
            tip.hidden = false;
            const r = el.getBoundingClientRect(), tw = tip.offsetWidth, th = tip.offsetHeight;
            let x = Math.min(window.innerWidth - tw - 8, Math.max(8, r.left));
            let y = r.bottom + 6;
            if (y + th > window.innerHeight - 8) y = r.top - th - 6;
            tip.style.left = x + "px"; tip.style.top = y + "px";
        }, 450);
    });
    document.addEventListener("pointerdown", (e) => { // a click hides the tooltip (it would cover a drop-down list)
        clearTimeout(tipTimer); tip.hidden = true;
        const el = e.target.closest ? e.target.closest("[data-help]") : null;
        tipBlocked = el;
        if (el) el.addEventListener("blur", () => { if (tipBlocked === el) tipBlocked = null; }, {once: true});
    }, true);
    document.addEventListener("mouseout", (e) => {
        if (tipEl && (!e.relatedTarget || !tipEl.contains(e.relatedTarget))) { clearTimeout(tipTimer); tip.hidden = true; tipEl = null; }
    });
    function openHelp(key) {
        const h = helpTable()[key];
        if (!h) return;
        clearTimeout(tipTimer); tip.hidden = true;
        $("helpBack").querySelector(".helpcard").classList.remove("wide");
        $("helpBack").querySelector(".kind").textContent = tr("Help · double click");
        $("helpTitle").textContent = h[0];
        $("helpBody").innerHTML = "<p><strong>" + esc(h[1]) + "</strong></p><p>" + esc(h[2]) + "</p>";
        const ex = h[3];
        $("helpSvg").innerHTML = Array.isArray(ex) ? EX.link(ex[0], ex[1], ex[2]) : (EX[ex] ? EX[ex]() : "");
        $("helpBack").hidden = false;
        $("helpClose").focus();
    }
    function closeHelp() { $("helpBack").hidden = true; }
    document.addEventListener("dblclick", (e) => {
        const el = e.target.closest ? e.target.closest("[data-help]") : null;
        if (el) { e.preventDefault(); try { window.getSelection().removeAllRanges(); } catch (err) { /* no selection API */ } openHelp(el.dataset.help); }
    });
    // ---------- Controls card (button "?" / key ? or H) ---------- //
    // One row per control of the current mode: a small drawing of the gesture, its name and what it does
    const ICON = {
        mouse(btn, motion) { // btn: left / right / wheel / none; motion: drag / scroll / click / dbl / hover
            const hl = "var(--accent)", base = "var(--muted)";
            let s = '<svg viewBox="0 0 64 44" aria-hidden="true"><rect x="22" y="4" width="20" height="32" rx="10" fill="none" stroke="' + base + '" stroke-width="1.5"/>' +
                '<line x1="32" y1="4" x2="32" y2="16" stroke="' + base + '" stroke-width="1.2"/>';
            if (btn === "left") s += '<path d="M22 14 a10 10 0 0 1 10 -10 v12 h-10z" fill="' + hl + '" opacity=".75"/>';
            if (btn === "right") s += '<path d="M42 14 a10 10 0 0 0 -10 -10 v12 h10z" fill="' + hl + '" opacity=".75"/>';
            if (btn === "wheel" || motion === "scroll") s += '<rect x="30" y="8" width="4" height="7" rx="2" fill="' + hl + '"/>';
            if (motion === "drag") s += '<path d="M48 30 q8 -8 0 -16" fill="none" stroke="' + hl + '" stroke-width="1.6"><animate attributeName="opacity" values="1;.3;1" dur="1.6s" repeatCount="indefinite"/></path><path d="M44 14 l4 0 l0 4" fill="none" stroke="' + hl + '" stroke-width="1.6"/><path d="M16 14 q-8 8 0 16" fill="none" stroke="' + hl + '" stroke-width="1.6"/><path d="M20 30 l-4 0 l0 -4" fill="none" stroke="' + hl + '" stroke-width="1.6"/>';
            if (motion === "scroll") s += '<path d="M50 12 l4 -5 l4 5 M50 30 l4 5 l4 -5" fill="none" stroke="' + hl + '" stroke-width="1.6"/>';
            if (motion === "dbl") s += '<text x="48" y="16" fill="' + hl + '" font-size="10" font-weight="700" font-family="system-ui">×2</text>';
            if (motion === "hover") s += '<path d="M50 20 l0 14 l4 -4 l3 6 l2 -1 l-3 -6 l5 0 z" fill="' + hl + '"/>';
            return s + "</svg>";
        },
        keys(list) { // key caps on one or two rows
            const rows = Array.isArray(list[0]) ? list : [list], w = (k) => Math.max(14, 7 * k.length + 7);
            const wide = Math.max(64, ...rows.map(r => r.reduce((a, k) => a + w(k) + 2, 2)));
            let s = '<svg viewBox="' + (32 - wide / 2) + " 0 " + wide + ' 44" aria-hidden="true">';
            rows.forEach((r, ri) => {
                const total = r.reduce((a, k) => a + w(k) + 2, -2);
                let x = 32 - total / 2;
                const y = rows.length === 1 ? 13 : 3 + ri * 20;
                for (const k of r) { s += '<rect x="' + x + '" y="' + y + '" width="' + w(k) + '" height="17" rx="3.5" fill="var(--code-bg)" stroke="var(--border)"/><text x="' + (x + w(k) / 2) + '" y="' + (y + 12) + '" text-anchor="middle" fill="var(--text)" font-size="9.5" font-weight="600" font-family="system-ui">' + esc(k) + "</text>"; x += w(k) + 2; }
            });
            return s + "</svg>";
        },
        axes() { return '<svg viewBox="0 0 64 44" aria-hidden="true"><circle cx="32" cy="22" r="18" fill="var(--surface)" stroke="var(--border)"/><line x1="32" y1="22" x2="46" y2="22" stroke="#e5534b" stroke-width="2"/><line x1="32" y1="22" x2="32" y2="8" stroke="#3fb950" stroke-width="2"/><line x1="32" y1="22" x2="24" y2="28" stroke="#539bf5" stroke-width="2"/></svg>'; }
    };
    function controls() {
        const fr = window.docI18n && window.docI18n.lang() === "fr", L = (en, f) => fr ? f : en;
        const mv = KEYS.move.split(""), ud = KEYS.updown.split(" / ");
        const common = [
            [ICON.mouse("left", "click"), L("Click a node", "Clic sur un nœud"), L("Selects it: details panel on the right, its relations highlighted. Click the background to unselect.", "Le sélectionne : panneau de détails à droite, ses relations en surbrillance. Clic sur le fond pour désélectionner.")],
            [ICON.mouse("none", "hover"), L("Hover a node", "Survol d'un nœud"), L("Card with its kind, its name and its path.", "Carte avec sa catégorie, son nom et son chemin.")],
            [ICON.keys(["F"]), "F", L("Centers and zooms on the selected node; the zoom then stays on it until another move of the camera.", "Centre et zoome sur le nœud sélectionné ; le zoom reste ensuite sur lui jusqu'à un autre mouvement de la caméra.")],
            [ICON.keys(["R"]), "R", L("Back to the start view (position, zoom and angle).", "Retour à la vue de départ (position, zoom et angle).")],
            ...(CONFIG.explorer ? [[ICON.keys(["Ctrl", "⇧", "R"]), "Ctrl + Shift + R", L("Forgets the repository (and the graphs kept by this browser) and reloads the page, which asks for another one.", "Oublie le dépôt (et les graphes gardés par ce navigateur) et recharge la page, qui en demande un autre.")]] : []),
            [ICON.mouse("left", "dbl"), L("Double click a control", "Double clic sur un contrôle"), L("Help card of a button, a category, a group or a relation of the panel.", "Fiche d'aide d'un bouton, d'une catégorie, d'un groupe ou d'une relation du panneau.")]
        ];
        if (state.mode === "3d") return [L("Controls · 3D view", "Contrôles · vue 3D"), [
            [ICON.mouse("left", "drag"), L("Drag the background", "Glisser le fond"), L("Orbits around the center of the view.", "Tourne autour du centre de la vue.")],
            [ICON.mouse("right", "drag"), L("Right drag (or Shift + drag)", "Clic droit + glisser (ou Maj + glisser)"), L("Moves the view in the plane of the screen; the center of rotation follows.", "Déplace la vue dans le plan de l'écran ; le centre de rotation suit.")],
            [ICON.mouse("left", "drag"), L("Drag a node", "Glisser un nœud"), L("Moves the node in the plane of the screen.", "Déplace le nœud dans le plan de l'écran.")],
            [ICON.mouse("wheel", "scroll"), L("Scroll", "Molette"), L("Moves forward / backward towards the mouse (or the selected node), through the graph, no limit.", "Avance / recule vers la souris (ou le nœud sélectionné), à travers le graphe, sans limite.")],
            [ICON.keys([[mv[0]], [mv[1], mv[2], mv[3]]]), mv.join(""), L("Moves forward, left, backward, right along the floor (Shift: faster).", "Avance, gauche, recule, droite le long du sol (Maj : plus vite).")],
            [ICON.keys([ud[0], ud[1]]), ud.join(" / "), L("Goes down / up.", "Descend / monte.")],
            [ICON.keys([["↑"], ["←", "↓", "→"]]), L("Arrows", "Flèches"), L("Move the view in the plane of the screen.", "Déplacent la vue dans le plan de l'écran.")],
            [ICON.axes(), L("Axes (bottom left)", "Axes (en bas à gauche)"), L("Click: back to the default angle. Double click: whole start view.", "Clic : retour à l'angle par défaut. Double clic : toute la vue de départ.")],
            ...common,
            [ICON.mouse("none", "hover"), L("Walls", "Murs"), L("The camera stays in a box around the graph: its walls appear when you get close.", "La caméra reste dans une boîte autour du graphe : ses murs apparaissent quand on s'en approche.")]
        ]];
        if (state.mode === "flow") return [L("Controls · diagrams", "Contrôles · schémas"), [
            [ICON.mouse("left", "drag"), L("Drag the background", "Glisser le fond"), L("Moves the view.", "Déplace la vue.")],
            [ICON.mouse("wheel", "scroll"), L("Scroll", "Molette"), L("Zooms in / out towards the mouse.", "Zoome / dézoome vers la souris.")],
            [ICON.mouse("left", "click"), L("Click a box", "Clic sur une boîte"), L("Selects it: details panel, its calls / bases highlighted.", "La sélectionne : panneau de détails, ses appels / bases en surbrillance.")],
            [ICON.mouse("left", "drag"), L("Drag a box / a dashed group", "Glisser une boîte / un groupe pointillé"), L("Moves the box, or all the methods of the class (execution, inheritance).", "Déplace la boîte, ou toutes les méthodes de la classe (exécution, héritage).")],
            [ICON.keys(["Ctrl", "Shift"]), L("Ctrl / Shift + click, Shift + drag", "Ctrl / Maj + clic, Maj + glisser"), L("Selects several boxes (one by one, or an area of the background), then drag one of them to move them together.", "Sélectionne plusieurs boîtes (une à une, ou une zone du fond), puis glisser l'une d'elles les déplace ensemble.")],
            [ICON.mouse("left", "dbl"), L("Double click a box", "Double clic sur une boîte"), L("Execution: starts the flow from it. Flame graph: zooms into the frame; double click the rows below to go back.", "Exécution : démarre le flux depuis elle. Flame graph : zoome sur le bloc ; double clic sur les lignes du dessous pour revenir.")],
            [ICON.keys([["↑"], ["←", "↓", "→"]]), L("Arrows / ", "Flèches / ") + mv.join(""), L("Move the view (Shift: faster).", "Déplacent la vue (Maj : plus vite).")],
            [ICON.keys([ud[0], ud[1]]), ud.join(" / "), L("Zoom out / in.", "Dézoome / zoome.")],
            [ICON.keys(["F"]), "F", L("Centers the view on the selected box.", "Centre la vue sur la boîte sélectionnée.")],
            [ICON.keys(["R"]), "R", L("Fits the whole diagram in the view.", "Cadre tout le schéma.")],
            [ICON.mouse("left", "click"), L("Views (top left)", "Vues (en haut à gauche)"), L("Execution: calls from an entry point. Inheritance: tree of the classes. Flame graph: call tree, width = size of the subtree. The list chooses the entry point.", "Exécution : appels depuis un point d'entrée. Héritage : arbre des classes. Flame graph : arbre d'appels, largeur = taille du sous-arbre. La liste choisit le point d'entrée.")]
        ]];
        return [L("Controls · 2D view", "Contrôles · vue 2D"), [
            [ICON.mouse("left", "drag"), L("Drag the background", "Glisser le fond"), L("Moves the view.", "Déplace la vue.")],
            [ICON.mouse("left", "drag"), L("Drag a node", "Glisser un nœud"), L("Moves the node; its relations pull the others.", "Déplace le nœud ; ses relations entraînent les autres.")],
            [ICON.mouse("wheel", "scroll"), L("Scroll", "Molette"), L("Zooms in / out towards the mouse (or the selected node).", "Zoome / dézoome vers la souris (ou le nœud sélectionné).")],
            [ICON.keys([["↑"], ["←", "↓", "→"]]), L("Arrows / ", "Flèches / ") + mv.join(""), L("Move the view (Shift: faster).", "Déplacent la vue (Maj : plus vite).")],
            [ICON.keys([ud[0], ud[1]]), ud.join(" / "), L("Zoom out / in.", "Dézoome / zoome.")],
            ...common
        ]];
    }
    function openControls() {
        const [title, rows] = controls();
        clearTimeout(tipTimer); tip.hidden = true;
        $("helpBack").querySelector(".helpcard").classList.add("wide");
        $("helpBack").querySelector(".kind").textContent = tr("Help");
        $("helpTitle").textContent = title;
        $("helpBody").innerHTML = '<div class="ctl-list">' + rows.map(r => '<div class="ctl">' + r[0] + '<div><b>' + esc(r[1]) + "</b><span>" + esc(r[2]) + "</span></div></div>").join("") + "</div>";
        $("helpSvg").innerHTML = "";
        $("helpBack").hidden = false;
        $("helpClose").focus();
    }
    $("controlsBtn").addEventListener("click", openControls);
    document.addEventListener("keydown", (e) => {
        if ((e.key === "?" || e.key === "h" || e.key === "H") && !typing() && !e.ctrlKey && !e.metaKey && !e.altKey && $("helpBack").hidden) { e.preventDefault(); openControls(); }
    });
    $("helpClose").addEventListener("click", closeHelp);
    $("helpBack").addEventListener("click", (e) => { if (e.target === $("helpBack")) closeHelp(); });
    document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !$("helpBack").hidden) closeHelp(); });

    // ---------- Theme ---------- //
    const root = document.documentElement, themeKey = (CONFIG.storageKey || "doc") + "-theme";
    try { const saved = localStorage.getItem(themeKey); if (saved) root.setAttribute("data-theme", saved); } catch (e) { /* storage unavailable */ }
    const askedTheme = new URLSearchParams(location.search).get("theme"); // carried by a link of the site
    if (askedTheme === "dark" || askedTheme === "light") { root.setAttribute("data-theme", askedTheme); try { localStorage.setItem(themeKey, askedTheme); } catch (e) { /* storage unavailable */ } }
    const isDark = () => root.getAttribute("data-theme") === "dark" || (!root.getAttribute("data-theme") && matchMedia("(prefers-color-scheme: dark)").matches);
    $("themeToggle").setAttribute("aria-checked", isDark() ? "true" : "false");
    $("themeToggle").addEventListener("click", () => {
        const next = isDark() ? "light" : "dark";
        root.setAttribute("data-theme", next);
        $("themeToggle").setAttribute("aria-checked", next === "dark" ? "true" : "false");
        try { localStorage.setItem(themeKey, next); } catch (e) { /* storage unavailable */ }
        readColors(); state.dirty = true;
    });
    matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => { readColors(); state.dirty = true; });
    // Print: the drawing in the colours of the light theme (the white text of a dark page on white paper)
    let themeBeforePrint = null;
    window.addEventListener("beforeprint", () => { themeBeforePrint = root.getAttribute("data-theme"); root.setAttribute("data-theme", "light"); readColors(); draw(); });
    window.addEventListener("afterprint", () => { if (themeBeforePrint) root.setAttribute("data-theme", themeBeforePrint); else root.removeAttribute("data-theme"); readColors(); state.dirty = true; });

    // ---------- Language ---------- //
    if (window.docI18n) window.docI18n.onChange(() => {
        buildLegends(); refilter(false);
        if (state.mode === "flow") buildFlow(); // the kinds on the boxes are translated
        $("pause").textContent = state.paused ? tr("Resume") : tr("Freeze");
        if (lastStatus) setStatus(lastStatus[0], lastStatus[1]);
        if (state.selected) select(state.selected);
        state.dirty = true;
    });
    $("pause").textContent = state.paused ? tr("Resume") : tr("Freeze");

    // ---------- Explorer (any repository given by the user, e.g. the gh-pages of the ai-utils repository) ---------- //
    const EXPLORER = "graph-explorer:repo";
    function parseRepo(s) { // owner/repo, GitHub / GitLab URLs (with /tree/<branch>)
        s = (s || "").trim().replace(/\.git$/, "").replace(/\/+$/, "");
        let m;
        if ((m = /^([\w.-]+)\/([\w.-]+)$/.exec(s))) return {host: "github", repo: m[1] + "/" + m[2], branch: ""};
        let u;
        try { u = new URL(/^https?:\/\//.test(s) ? s : "https://" + s); } catch (e) { return null; }
        const parts = u.pathname.split("/").filter(Boolean).map(decodeURIComponent);
        if (u.hostname === "github.com" && parts.length >= 2) return {host: "github", repo: parts[0] + "/" + parts[1], branch: parts[2] === "tree" ? parts.slice(3).join("/") : ""};
        if (/gitlab/.test(u.hostname) && parts.length >= 2) {
            const i = parts.indexOf("-"), p = i > 0 ? parts.slice(0, i) : parts;
            return {host: "gitlab", api: u.origin, repo: p.join("/"), branch: i > 0 && parts[i + 1] === "tree" ? parts.slice(i + 2).join("/") : ""};
        }
        return null;
    }
    function askRepo(error) {
        $("repoErr").hidden = !error; $("repoErr").textContent = error ? tr(error) : "";
        $("repoAsk").value = $("repoInput").value;
        $("repoBack").hidden = false; $("repoAsk").focus();
    }
    function openRepo(spec) {
        const r = parseRepo(spec);
        if (!r) { askRepo("Unsupported link: a GitHub (owner/repo, github.com/...) or GitLab (gitlab.com/..., a self-hosted GitLab) repository."); return; }
        Object.assign(CONFIG, r, {explorer: true});
        KEY = "graph-explorer:" + r.host + ":" + (r.api || "") + r.repo + (r.branch ? "@" + r.branch : "");
        try { localStorage.setItem(EXPLORER, spec.trim()); } catch (e) { /* storage unavailable */ }
        $("repoInput").value = spec.trim(); $("repoBack").hidden = true;
        const name = r.repo.split("/").pop();
        document.querySelectorAll(".repo-name").forEach(e => { e.textContent = name; });
        document.querySelectorAll("a.repo-link").forEach(a => { a.href = HOSTS[r.host].web(CONFIG); });
        document.title = name + " · " + tr("Graph explorer");
        Object.assign(state, {pos: new Map(), selected: null, hover: null, flowRoot: null, flamePath: [], groups: new Set(), knownGroups: new Set(), cams: {}, meta: {}});
        $("details").hidden = true;
        const cached = load("graph");
        setData(cached || {nodes: [], links: []}, cached ? cached.meta : {});
        for (let i = 0; i < 120; i++) tick();
        fit(); state.dirty = true;
        update(true).then(() => { for (let i = 0; i < 150; i++) tick(); fit(); state.dirty = true; }); // fitted once the layout has settled
    }
    if (CONFIG.explorer) {
        $("repoBar").hidden = false;
        $("repoBar").addEventListener("submit", (e) => { e.preventDefault(); openRepo($("repoInput").value); });
        $("repoForm").addEventListener("submit", (e) => { e.preventDefault(); openRepo($("repoAsk").value); });
        $("repoBack").addEventListener("click", (e) => { if (e.target === $("repoBack") && CONFIG.repo) $("repoBack").hidden = true; });
        document.querySelectorAll("[data-ex]").forEach(b => b.addEventListener("click", () => { $("repoAsk").value = b.dataset.ex; openRepo(b.dataset.ex); }));
        document.addEventListener("keydown", (e) => { // Ctrl + Shift + R: forget the repository (and its graphs), then reload the page
            if (!((e.ctrlKey || e.metaKey) && e.shiftKey && (e.key === "R" || e.key === "r"))) return;
            e.preventDefault();
            try { for (const k of Object.keys(localStorage)) if (k.startsWith("graph-explorer:")) localStorage.removeItem(k); } catch (err) { /* storage unavailable */ }
            location.replace(location.pathname); // without ?repo=
        });
    }

    // ---------- Start ---------- //
    readColors();
    resize();
    window.addEventListener("resize", () => { resize(); });
    if (CONFIG.explorer) {
        state.meta = {};
        setData({nodes: [], links: []}, {});
        requestAnimationFrame(frame);
        let saved = null;
        try { saved = localStorage.getItem(EXPLORER); } catch (e) { /* storage unavailable */ }
        const q = new URLSearchParams(location.search).get("repo"); // ?repo=owner/name also works (shareable link)
        if (q || saved) openRepo(q || saved); else { setStatus(() => tr("Choose a repository to explore."), ""); askRepo(""); }
        return;
    }
    const cached = load("graph");
    const start = cached && cached.meta && SNAPSHOT.meta && cached.meta.date && (!SNAPSHOT.meta.date || cached.meta.date > SNAPSHOT.meta.date) ? cached : SNAPSHOT;
    setData(start, start.meta);
    for (let i = 0; i < 120; i++) tick();
    fit();
    setStatus(() => tr("Graph") + " " + describe(state.meta) + ".", "");
    state.dirty = true;
    requestAnimationFrame(frame);
    update(false);
})();

// Hide the tabs of the pages that don't exist, and the whole bar when a single page remains
// (online: HEAD request; file://: the page is loaded as a hidden script, a missing file fails to load)
(function () {
  var nav = document.querySelector('nav.tabs');
  if (!nav) return;
  function showCurrent() { // a narrow bar scrolls its tabs: the current one in sight
    var current = nav.querySelector('a.current');
    if (current) nav.scrollLeft = current.offsetLeft - nav.offsetLeft;
  }
  function done(a, ok) {
    if (!ok) a.remove();
    if (nav.querySelectorAll('a').length < 2) nav.hidden = true;
    showCurrent();
  }
  nav.querySelectorAll('a:not(.current)').forEach(function (a) {
    if (/^https?:$/.test(location.protocol)) {
      fetch(a.href, { method: 'HEAD' }).then(function (r) { done(a, r.ok); }).catch(function () {});
      return;
    }
    var s = document.createElement('script');
    var mute = function (e) { if (e.filename === s.src) { e.preventDefault(); e.stopImmediatePropagation(); } }; // an HTML page is not JS
    window.addEventListener('error', mute, true);
    s.src = a.href;
    s.onload = function () { window.removeEventListener('error', mute, true); s.remove(); done(a, true); };
    s.onerror = function () { window.removeEventListener('error', mute, true); s.remove(); done(a, false); };
    document.head.appendChild(s);
  });
  if (nav.querySelectorAll('a').length < 2) nav.hidden = true;
  showCurrent();
})();
</script>
<script>
// Links between the pages of the site carry the language, theme and level (?lang=fr&theme=dark&level=technical):
// the choice applies to every page, also from file:// where each page has its own storage
(function () {
  var root = document.documentElement;
  function carry(e) {
    var a = e.target.closest && e.target.closest('a[href]');
    if (!a || a.target === '_blank') return;
    var href = a.getAttribute('href');
    if (!/^[^:?#\/]+\.html(#.*)?$/.test(href) && !/^\.\/[^:?#\/]+\.html(#.*)?$/.test(href)) return; // pages of the same folder only
    var u = new URL(a.href);
    u.searchParams.set('lang', root.lang || 'en');
    if (root.getAttribute('data-theme')) u.searchParams.set('theme', root.getAttribute('data-theme'));
    if (root.getAttribute('data-level')) u.searchParams.set('level', root.getAttribute('data-level'));
    a.href = u.href;
  }
  document.addEventListener('click', carry, true);
  document.addEventListener('auxclick', carry, true);
})();
</script>
</body>
</html>
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 197kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall