---
title: "Knowledge Graph"
description: "Application scaffold: a knowledge graph of a million services, datasets and people - the Graph Explorer in a Border Layout of Panels, details that drill down from a domain to a system to a dataset, links you can inspect, and detail pages composed from Chart, Geo Map, Avatar, Timeline, Progress, Table, Badge and Statistic; built only from the shipped components."
slug: "scaffold-knowledge-graph"
---

import { DocPage, PageHeader, DocText, DocLink } from "../../lib/components/index";

<DocPage meta={meta}>

<PageHeader slug="scaffold-knowledge-graph" title="Knowledge Graph" introStyle="max-width:44rem;">
  A knowledge graph of a million services, datasets and people as a clickdummy - "Atlas" for a fictional company. Zoom from the domains into a system, pick an API system or a dataset for its details, then press <strong>Expand</strong>: its page shows latency and traffic charts, the regions it runs in on a map, its endpoints, its team and its deploys - and every name on it opens the next page down. Click a link between two domains for its traffic and its circuit breakers. Every page is a route, so Back walks the drill-down back up. Part of the <DocLink href="application-scaffolds.html">Application Scaffolds</DocLink>.
</PageHeader>

<div class="flex flex-wrap items-center gap-2 mb-6">
  <a class="btn" href="app-knowledge-graph.html" target="_blank" rel="noopener"><i data-lucide="maximize-2"></i> Open full screen</a>
  <a class="btn" data-variant="outline" href="#how-it-works">How it works</a>
</div>

```html example standalone label="Knowledge graph" schema="none" mode="desktop" hint="Zoom into a domain, then a system. Pick an API system or a dataset, press E for its page, then follow a name further down. Back in the graph's header returns to the selection before. The layer switch shows Labels, Health and Owners on top of the nodes and their relations. Press ⌘K (Ctrl+K) and type ledger; in the Hierarchy Explorer open a branch to go deeper. Live mode in the toolbar sends changes: dots on nodes, flashing links, rows in Updates. The language switch is in the toolbar." previewStyle="align-items:stretch;padding:0;"
<script src="https://cdn.jsdelivr.net/npm/echarts@6.1.0/dist/echarts.min.js"></script>
<style>
  /* Atlas: the scaffold's own glue. Every control is a shipped component (Border Layout, Panel, Resizer, Graph
     Explorer, Button, Separator, Select, Swap); the details the plugins draw compose Chart, Geo Map, Avatar,
     Timeline, Progress, Table, Badge and Statistic */
  .kg {
    block-size: var(--scaffold-height, 46rem);
  }
  .kg-brand {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-weight: 650;
    white-space: nowrap;
  }
  .kg-brand-mark {
    display: grid;
    place-items: center;
    inline-size: 1.75rem;
    block-size: 1.75rem;
    border-radius: var(--radius-md);
    background: var(--primary);
    color: var(--primary-foreground);
  }
  .kg-brand-sub {
    color: var(--muted-foreground);
    font-weight: 400;
  }
  /* the graph's header: its title keeps its word and the layer switch scrolls sideways in a narrow panel - with the
     switch as wide as its layers, the title shrank to nothing and Compact ran past the panel's edge */
  [aria-labelledby='kg-graph-title'] > .panel-header {
    & .panel-title {
      flex: 0 1 auto;
      min-inline-size: 3.5rem;
    }
    & .panel-tools {
      flex: 1 1 auto;
      min-inline-size: 0;
      justify-content: flex-end;
    }
    & [data-graph-explorer-outlet='layers'] {
      min-inline-size: 0;
      overflow-x: auto;
      scrollbar-width: none;
    }
  }
  .kg-title-sub {
    color: var(--muted-foreground);
    font-weight: 400;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    &:not(:empty)::before {
      content: '· ';
    }
  }
  /* the search trigger: an input's look, the palette behind it */
  .kg-search {
    inline-size: min(100%, 20rem);
    justify-content: flex-start;
    color: var(--muted-foreground);
    font-weight: 400;
    & .kbd {
      margin-inline-start: auto;
    }
  }
  .kg-search-text {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  /* the Hierarchy Explorer: the filter, the graph as a tree of any depth */
  .kg-tree {
    display: flex;
    flex-direction: column;
    min-block-size: 0;
  }
  .kg-tree-filter {
    padding: 0.375rem;
  }
  /* two columns that always fit the panel: the name gives way (an ellipsis), the size stays */
  #kg-tree :is(.data-grid-head, .data-grid-row) {
    width: 100%;
  }
  #kg-tree {
    flex: 1;
    min-block-size: 0;
    border-inline: 0;
    border-block-end: 0;
    border-radius: 0;
  }
  .kg-tree-more {
    color: var(--muted-foreground);
    font-style: italic;
  }
  .kg-tree-label {
    display: flex;
    align-items: center;
    gap: 0.375rem;
    min-inline-size: 0;
    & > span:last-child {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .kg-tree-dot {
    flex: none;
    inline-size: 0.5rem;
    block-size: 0.5rem;
    border-radius: 50%;
    background: var(--chart-1);
    &[data-kind='Domain'] {
      background: var(--chart-2);
    }
    &[data-kind='system'] {
      background: var(--chart-3);
    }
    &[data-kind='entity'] {
      background: var(--chart-4);
    }
  }
  /* the palette's hits: the name, then what and where */
  .kg-hit {
    display: grid;
    gap: 0.0625rem;
    text-align: start;
  }
  .kg-hit-path {
    color: var(--muted-foreground);
    font-size: 0.75rem;
  }
  .kg-palette-status {
    margin: 0;
    padding: 0.375rem 0.75rem;
    border-block-start: 1px solid var(--border);
    color: var(--muted-foreground);
    font-size: 0.75rem;
    &:empty {
      display: none;
    }
  }
  /* the graph's header: Back to the previous selection and Out, a divider, then the title */
  .kg-graph-nav {
    display: flex;
    flex: none;
    align-items: center;
    gap: 0.125rem;
    & .separator {
      block-size: 1.25rem;
      margin-inline: 0.375rem 0.125rem;
    }
  }
  /* the Owners layer: avatars, overlapping a little */
  .kg-owners {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    & .graph-explorer-avatar + .graph-explorer-avatar {
      margin-inline-start: -0.375rem;
    }
  }
  p.kg-owners {
    display: flex;
  }
  .kg .panel-title {
    display: flex;
    gap: 0.375rem;
    min-inline-size: 0;
  }
  .kg-endpoint {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-family: var(--font-mono);
    font-size: 0.75rem;
  }
  .kg-note {
    margin: 0;
    font-size: 0.75rem;
    color: var(--muted-foreground);
  }
  .kg-team {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 0.75rem;
  }
  .kg-checks {
    display: flex;
    flex-wrap: wrap;
    gap: 0.375rem;
  }
  .kg-details .geo-map {
    --geo-map-height: 15rem;
  }
  .kg-records {
    display: grid;
    gap: 0.75rem;
    min-inline-size: 0;
  }
  .kg-records-count {
    margin: 0;
    font-size: 0.8125rem;
    font-variant-numeric: tabular-nums;
  }
  .kg-records-charts {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(min(14rem, 100%), 1fr));
    gap: 1rem;
  }
  .kg-records-chart {
    margin: 0;
    min-inline-size: 0;
    & figcaption {
      font-size: 0.75rem;
      color: var(--muted-foreground);
    }
  }
  .kg-records .data-grid {
    --data-grid-row-height: 30px;
    font-size: 0.8125rem;
  }
  .kg-theme[aria-pressed='true'] .kg-theme-light,
  .kg-theme[aria-pressed='false'] .kg-theme-dark {
    display: none;
  }
  .kg-theme > span {
    display: contents;
  }
</style>
<div class="kg" data-kg data-i18n-component>
  <div class="border-layout" id="kg-app" data-frame="none" data-center-min="360" style="block-size: 100%">
    <header class="border-layout-north flex items-center gap-3 px-3 py-2">
      <span class="kg-brand"
        ><span class="kg-brand-mark"><i data-lucide="waypoints"></i></span><span>Atlas</span
        ><span class="kg-brand-sub" data-i18n-target="kg-brand-sub">knowledge graph</span></span
      >
      <div class="flex-1 min-w-0" data-graph-explorer-for="kg" data-graph-explorer-outlet="breadcrumb"></div>
      <button
        class="btn kg-search"
        data-variant="outline"
        data-size="sm"
        type="button"
        data-command-trigger="kg-palette"
        aria-keyshortcuts="Meta+K Control+K"
      >
        <i data-lucide="search"></i> <span class="kg-search-text" data-i18n-target="kg-search">Search the graph</span>
        <kbd class="kbd">⌘K</kbd>
      </button>
      <div class="flex items-center gap-2">
        <button
          class="btn"
          data-variant="outline"
          data-size="sm"
          type="button"
          title="Fit the view (0)"
          data-i18n-title-en="Fit the view (0)"
          data-i18n-title-de="Ansicht einpassen (0)"
          data-graph-explorer-for="kg"
          data-graph-explorer-action="fit"
        >
          <i data-lucide="scan"></i> <span data-i18n-target="kg-fit">Fit</span>
        </button>
        <button
          class="btn"
          data-variant="outline"
          data-size="sm"
          type="button"
          aria-pressed="false"
          title="Live mode: changes arrive as they happen - a dot on a changed node, a flash on a changed link, a row in Updates"
          data-i18n-title-en="Live mode: changes arrive as they happen - a dot on a changed node, a flash on a changed link, a row in Updates"
          data-i18n-title-de="Live-Modus: Änderungen kommen, sobald sie passieren - ein Punkt am geänderten Knoten, ein Aufleuchten der geänderten Verbindung, eine Zeile in Aktualisierungen"
          data-graph-explorer-for="kg"
          data-graph-explorer-action="live"
        >
          <i data-lucide="radio-tower"></i> <span data-i18n-target="kg-live">Live mode</span>
        </button>
        <button
          class="btn kg-theme"
          data-variant="ghost"
          data-size="icon-sm"
          type="button"
          aria-pressed="false"
          aria-label="Dark mode"
          title="Dark mode"
          data-i18n-aria-label-en="Dark mode"
          data-i18n-aria-label-de="Dunkelmodus"
          data-i18n-title-en="Dark mode"
          data-i18n-title-de="Dunkelmodus"
          data-kg-theme
        >
          <span class="kg-theme-light"><i data-lucide="moon"></i></span
          ><span class="kg-theme-dark"><i data-lucide="sun"></i></span>
        </button>
        <div
          class="language-switcher"
          data-app-locale
          role="group"
          aria-label="Language"
          data-i18n-aria-label-en="Language"
          data-i18n-aria-label-de="Sprache"
          data-languages="en de"
          data-value="en"
          data-size="sm"
          data-display="icon"
          data-flag-shape="circle"
          data-flag-style="ring"
          data-align="end"
        ></div>
        <button
          class="btn"
          data-variant="ghost"
          data-size="icon-sm"
          type="button"
          aria-label="Keyboard map (?)"
          title="Keyboard map (?)"
          data-i18n-aria-label-en="Keyboard map (?)"
          data-i18n-aria-label-de="Tastaturbelegung (?)"
          data-i18n-title-en="Keyboard map (?)"
          data-i18n-title-de="Tastaturbelegung (?)"
          data-graph-explorer-for="kg"
          data-graph-explorer-action="help"
        >
          <i data-lucide="keyboard"></i>
        </button>
      </div>
    </header>
    <div class="resizer border-layout-west" data-min="160" data-max="420">
      <div
        class="border-layout-stack"
        style="width: 15rem"
        aria-label="Hierarchy and updates"
        data-i18n-aria-label-en="Hierarchy and updates"
        data-i18n-aria-label-de="Hierarchie und Aktualisierungen"
      >
        <section
          class="card panel"
          id="kg-outline"
          style="--border-layout-share: 3"
          aria-labelledby="kg-outline-title"
          data-density="compact"
        >
          <header class="panel-header">
            <i data-lucide="list-tree" class="panel-icon" aria-hidden="true"></i>
            <h3 class="panel-title" id="kg-outline-title">
              <span data-i18n-target="kg-t-outline">Hierarchy Explorer</span>
            </h3>
            <div class="panel-tools">
              <label class="swap panel-minimize">
                <input
                  type="checkbox"
                  aria-label="Minimize Hierarchy Explorer"
                  data-i18n-aria-label-en="Minimize Hierarchy Explorer"
                  data-i18n-aria-label-de="Hierarchie-Explorer einklappen"
                />
                <span class="swap-off"><i data-lucide="chevron-up"></i></span>
                <span class="swap-on"><i data-lucide="chevron-down"></i></span>
              </label>
            </div>
          </header>
          <div class="panel-body kg-tree" data-flush>
            <div class="kg-tree-filter">
              <input
                class="input"
                data-size="sm"
                type="search"
                placeholder="Filter the open branches"
                aria-label="Filter the hierarchy"
                data-i18n-placeholder-en="Filter the open branches"
                data-i18n-placeholder-de="Die offenen Zweige filtern"
                data-i18n-aria-label-en="Filter the hierarchy"
                data-i18n-aria-label-de="Die Hierarchie filtern"
                data-kg-tree-filter
              />
            </div>
            <div
              class="data-grid"
              id="kg-tree"
              aria-label="The graph as a hierarchy"
              data-i18n-aria-label-en="The graph as a hierarchy"
              data-i18n-aria-label-de="Der Graph als Hierarchie"
              data-parent-field="parent"
              data-select="single"
              data-persist="none"
              data-density="compact"
              data-empty-text="Nothing in the open branches matches."
            >
              <div class="data-grid-viewport">
                <div class="data-grid-head">
                  <div class="data-grid-row">
                    <div class="data-grid-header" data-field="label" data-width="minmax(0, 1fr)"
                      ><span data-i18n-target="kg-tree-name">Name</span></div
                    >
                    <div class="data-grid-header" data-field="count" data-type="number" data-width="5.75rem"
                      ><span data-i18n-target="kg-tree-count">Size</span></div
                    >
                  </div>
                </div>
                <div class="data-grid-body"></div>
              </div>
            </div>
          </div>
        </section>
        <section
          class="card panel"
          id="kg-updates"
          style="--border-layout-share: 2"
          aria-labelledby="kg-updates-title"
          data-density="compact"
        >
          <header class="panel-header">
            <i data-lucide="activity" class="panel-icon" aria-hidden="true"></i>
            <h3 class="panel-title" id="kg-updates-title">
              <span data-i18n-target="kg-t-updates">Updates</span>
            </h3>
            <div class="panel-tools">
              <label class="swap panel-minimize">
                <input
                  type="checkbox"
                  aria-label="Minimize Updates"
                  data-i18n-aria-label-en="Minimize Updates"
                  data-i18n-aria-label-de="Aktualisierungen einklappen"
                />
                <span class="swap-off"><i data-lucide="chevron-up"></i></span>
                <span class="swap-on"><i data-lucide="chevron-down"></i></span>
              </label>
            </div>
          </header>
          <div class="panel-body" data-flush data-graph-explorer-for="kg" data-graph-explorer-outlet="updates"></div>
        </section>
      </div>
    </div>
    <section
      class="card panel border-layout-center"
      id="kg-graph"
      aria-labelledby="kg-graph-title"
      data-density="compact"
      data-title-collapse="false"
    >
      <header class="panel-header">
        <div class="kg-graph-nav">
          <button
            class="btn"
            data-variant="ghost"
            data-size="xs"
            type="button"
            data-kg-back
            disabled
            title="Back to the previous selection"
          >
            <i data-lucide="arrow-left"></i> <span data-i18n-target="kg-back">Back</span>
          </button>
          <button
            class="btn"
            data-variant="ghost"
            data-size="xs"
            type="button"
            title="Move out (Backspace)"
            data-i18n-title-en="Move out (Backspace)"
            data-i18n-title-de="Hinaus (Rücktaste)"
            data-graph-explorer-for="kg"
            data-graph-explorer-action="up"
          >
            <i data-lucide="arrow-up"></i> <span data-i18n-target="kg-out">Out</span>
          </button>
          <div class="separator" data-orientation="vertical" role="separator"></div>
        </div>
        <i data-lucide="waypoints" class="panel-icon" aria-hidden="true"></i>
        <h3 class="panel-title" id="kg-graph-title">
          <span data-i18n-target="kg-t-graph">Graph</span
          ><span class="kg-title-sub" data-graph-explorer-for="kg" data-graph-explorer-output="view"></span>
        </h3>
        <div class="panel-tools">
          <div data-graph-explorer-for="kg" data-graph-explorer-outlet="layers"></div>
          <label class="swap panel-maximize">
            <input
              type="checkbox"
              aria-label="Maximize Graph"
              data-i18n-aria-label-en="Maximize Graph"
              data-i18n-aria-label-de="Graph maximieren"
            />
            <span class="swap-off"><i data-lucide="maximize-2"></i></span>
            <span class="swap-on"><i data-lucide="minimize-2"></i></span>
          </label>
        </div>
      </header>
      <div class="panel-body" data-flush>
        <div
          class="graph-explorer"
          id="kg"
          data-nodes="1000000"
          data-seed="7"
          aria-label="A knowledge graph of a million services, datasets and people"
        ></div>
      </div>
    </section>
    <div class="resizer border-layout-east" data-min="260" data-max="680">
      <section
        class="card panel kg-details"
        id="kg-details"
        style="width: 24rem"
        aria-labelledby="kg-details-title"
        data-density="compact"
      >
        <header class="panel-header">
          <i data-lucide="panel-right" class="panel-icon" aria-hidden="true"></i>
          <h3 class="panel-title" id="kg-details-title">
            <span data-i18n-target="kg-t-details">Details</span
            ><span
              class="kg-title-sub"
              id="kg-details-sub"
              data-graph-explorer-for="kg"
              data-graph-explorer-output="details-title"
            ></span>
          </h3>
          <div class="panel-tools">
            <label class="swap panel-maximize">
              <input
                type="checkbox"
                aria-label="Maximize Details"
                data-i18n-aria-label-en="Maximize Details"
                data-i18n-aria-label-de="Details maximieren"
              />
              <span class="swap-off"><i data-lucide="maximize-2"></i></span>
              <span class="swap-on"><i data-lucide="minimize-2"></i></span>
            </label>
            <label class="swap panel-minimize">
              <input
                type="checkbox"
                aria-label="Minimize Details"
                data-i18n-aria-label-en="Minimize Details"
                data-i18n-aria-label-de="Details einklappen"
              />
              <span class="swap-off"><i data-lucide="chevron-up"></i></span>
              <span class="swap-on"><i data-lucide="chevron-down"></i></span>
            </label>
          </div>
        </header>
        <div class="panel-body" data-graph-explorer-for="kg" data-graph-explorer-outlet="details"></div>
      </section>
    </div>
    <div class="resizer border-layout-south" data-min="96" data-max="520">
      <section
        class="card panel"
        id="kg-relations"
        style="height: 13rem"
        aria-labelledby="kg-relations-title"
        data-density="compact"
        data-minimized
      >
        <header class="panel-header">
          <i data-lucide="table" class="panel-icon" aria-hidden="true"></i>
          <h3 class="panel-title" id="kg-relations-title">
            <span data-i18n-target="kg-t-relations">Relations</span
            ><span
              class="kg-title-sub"
              id="kg-relations-sub"
              data-graph-explorer-for="kg"
              data-graph-explorer-output="relations-title"
            ></span>
          </h3>
          <div class="panel-tools">
            <label class="swap panel-maximize">
              <input
                type="checkbox"
                aria-label="Maximize Relations"
                data-i18n-aria-label-en="Maximize Relations"
                data-i18n-aria-label-de="Beziehungen maximieren"
              />
              <span class="swap-off"><i data-lucide="maximize-2"></i></span>
              <span class="swap-on"><i data-lucide="minimize-2"></i></span>
            </label>
            <label class="swap panel-minimize">
              <input
                type="checkbox"
                aria-label="Minimize Relations"
                data-i18n-aria-label-en="Minimize Relations"
                data-i18n-aria-label-de="Beziehungen einklappen"
              />
              <span class="swap-off"><i data-lucide="chevron-up"></i></span>
              <span class="swap-on"><i data-lucide="chevron-down"></i></span>
            </label>
          </div>
        </header>
        <div class="panel-body" data-flush data-graph-explorer-for="kg" data-graph-explorer-outlet="relations"></div>
      </section>
    </div>
  </div>
  <dialog
    id="kg-palette"
    class="command"
    aria-label="Search the graph"
    data-i18n-aria-label-en="Search the graph"
    data-i18n-aria-label-de="Den Graphen durchsuchen"
    data-density="compact"
  >
    <div class="command-content">
      <div class="command-input-wrapper">
        <i data-lucide="search" aria-hidden="true"></i>
        <input
          class="command-input"
          type="text"
          placeholder="Domains, systems or entities - or #4711"
          aria-label="Search"
          data-i18n-placeholder-en="Domains, systems or entities - or #4711"
          data-i18n-placeholder-de="Domänen, Systeme oder Entitäten - oder #4711"
          data-i18n-aria-label-en="Search"
          data-i18n-aria-label-de="Suchen"
          autocomplete="off"
          autocorrect="off"
          spellcheck="false"
          data-kg-find
        />
      </div>
      <div class="command-list">
        <div class="command-group" data-kg-hits hidden>
          <p class="command-group-heading" data-i18n-target="kg-p-nodes">Nodes</p>
        </div>
        <div class="command-separator"></div>
        <div class="command-group">
          <p class="command-group-heading" data-i18n-target="kg-p-actions">Actions</p>
          <button class="command-item" type="button" data-graph-explorer-for="kg" data-graph-explorer-action="fit">
            <i data-lucide="scan"></i> <span data-i18n-target="kg-p-fit">Fit the view</span>
            <span class="command-shortcut">0</span>
          </button>
          <button class="command-item" type="button" data-graph-explorer-for="kg" data-graph-explorer-action="up">
            <i data-lucide="arrow-up"></i> <span data-i18n-target="kg-p-out">Move out</span>
            <span class="command-shortcut">⌫</span>
          </button>
          <button class="command-item" type="button" data-kg-do="live">
            <i data-lucide="radio-tower"></i> <span data-i18n-target="kg-p-live">Live mode on or off</span>
          </button>
          <button class="command-item" type="button" data-kg-do="theme">
            <i data-lucide="sun-moon"></i> <span data-i18n-target="kg-p-theme">Light or dark</span>
          </button>
          <button class="command-item" type="button" data-graph-explorer-for="kg" data-graph-explorer-action="help">
            <i data-lucide="keyboard"></i> <span data-i18n-target="kg-p-help">Keyboard map</span>
            <span class="command-shortcut">?</span>
          </button>
        </div>
      </div>
      <div class="command-empty" hidden data-i18n-target="kg-p-empty">No node or action matches.</div>
      <p class="kg-palette-status" aria-live="polite" data-kg-find-status></p>
    </div>
  </dialog>
  <template data-i18n-for="kg-brand-sub" data-i18n-locale="en">knowledge graph</template>
  <template data-i18n-for="kg-brand-sub" data-i18n-locale="de">Wissensgraph</template>
  <template data-i18n-for="kg-out" data-i18n-locale="en">Out</template>
  <template data-i18n-for="kg-out" data-i18n-locale="de">Hinaus</template>
  <template data-i18n-for="kg-fit" data-i18n-locale="en">Fit</template>
  <template data-i18n-for="kg-fit" data-i18n-locale="de">Einpassen</template>
  <template data-i18n-for="kg-live" data-i18n-locale="en">Live mode</template>
  <template data-i18n-for="kg-live" data-i18n-locale="de">Live-Modus</template>
  <template data-i18n-for="kg-t-updates" data-i18n-locale="en">Updates</template>
  <template data-i18n-for="kg-t-updates" data-i18n-locale="de">Aktualisierungen</template>
  <template data-i18n-for="kg-t-outline" data-i18n-locale="en">Hierarchy Explorer</template>
  <template data-i18n-for="kg-t-outline" data-i18n-locale="de">Hierarchie-Explorer</template>
  <template data-i18n-for="kg-search" data-i18n-locale="en">Search the graph</template>
  <template data-i18n-for="kg-search" data-i18n-locale="de">Graph durchsuchen</template>
  <template data-i18n-for="kg-back" data-i18n-locale="en">Back</template>
  <template data-i18n-for="kg-back" data-i18n-locale="de">Zurück</template>
  <template data-i18n-for="kg-tree-name" data-i18n-locale="en">Name</template>
  <template data-i18n-for="kg-tree-name" data-i18n-locale="de">Name</template>
  <template data-i18n-for="kg-tree-count" data-i18n-locale="en">Size</template>
  <template data-i18n-for="kg-tree-count" data-i18n-locale="de">Größe</template>
  <template data-i18n-for="kg-p-nodes" data-i18n-locale="en">Nodes</template>
  <template data-i18n-for="kg-p-nodes" data-i18n-locale="de">Knoten</template>
  <template data-i18n-for="kg-p-actions" data-i18n-locale="en">Actions</template>
  <template data-i18n-for="kg-p-actions" data-i18n-locale="de">Aktionen</template>
  <template data-i18n-for="kg-p-fit" data-i18n-locale="en">Fit the view</template>
  <template data-i18n-for="kg-p-fit" data-i18n-locale="de">Ansicht einpassen</template>
  <template data-i18n-for="kg-p-out" data-i18n-locale="en">Move out</template>
  <template data-i18n-for="kg-p-out" data-i18n-locale="de">Hinaus</template>
  <template data-i18n-for="kg-p-live" data-i18n-locale="en">Live mode on or off</template>
  <template data-i18n-for="kg-p-live" data-i18n-locale="de">Live-Modus an oder aus</template>
  <template data-i18n-for="kg-p-theme" data-i18n-locale="en">Light or dark</template>
  <template data-i18n-for="kg-p-theme" data-i18n-locale="de">Hell oder dunkel</template>
  <template data-i18n-for="kg-p-help" data-i18n-locale="en">Keyboard map</template>
  <template data-i18n-for="kg-p-help" data-i18n-locale="de">Tastaturbelegung</template>
  <template data-i18n-for="kg-p-empty" data-i18n-locale="en">No node or action matches.</template>
  <template data-i18n-for="kg-p-empty" data-i18n-locale="de">Kein Knoten und keine Aktion passt.</template>
  <template data-i18n-for="kg-t-graph" data-i18n-locale="en">Graph</template>
  <template data-i18n-for="kg-t-graph" data-i18n-locale="de">Graph</template>
  <template data-i18n-for="kg-t-details" data-i18n-locale="en">Details</template>
  <template data-i18n-for="kg-t-details" data-i18n-locale="de">Details</template>
  <template data-i18n-for="kg-t-relations" data-i18n-locale="en">Relations</template>
  <template data-i18n-for="kg-t-relations" data-i18n-locale="de">Beziehungen</template>
</div>
<script type="module">
  // Atlas' plugins: the explorer draws the graph and the details; these renderers turn an API system, a domain, a
  // dataset and a link between clusters into pages composed from the library - Chart and Geo Map in islands (their
  // scripts keep what they drew while the details re-render), Avatar, Timeline, Progress, Table, Badge, Statistic.
  // The numbers are synthetic and stable per node: a metrics service would answer through ctx.request.
  const OWNERS = ['mira', 'jonas', 'li', 'sam', 'ada', 'omar', 'noor', 'tomas'];
  const COUNTRIES = [
    'USA',
    'DEU',
    'IRL',
    'JPN',
    'BRA',
    'IND',
    'SGP',
    'AUS',
    'CAN',
    'FRA',
    'GBR',
    'NLD',
    'SWE',
    'ZAF',
    'KOR',
  ];
  const NOUNS = ['orders', 'payments', 'users', 'sessions', 'invoices', 'items', 'events', 'tokens', 'reports'];
  const HOURS = Array.from({ length: 24 }, (_, k) => String(k).padStart(2, '0') + 'h');
  const DAYS = Array.from({ length: 30 }, (_, k) => 'd' + (k + 1));
  const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  const fmt = (n) => Number(n).toLocaleString('en-US');
  const hash = (s) => [...String(s)].reduce((h, ch) => Math.imul(h ^ ch.charCodeAt(0), 16777619) >>> 0, 2166136261);
  // a seeded generator: the same node always shows the same numbers
  const rng = (seed) => () => {
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
  const series = (id, n, base, spread, salt = 0) => {
    const r = rng(hash(id) + salt);
    let v = base;
    return Array.from({ length: n }, (_, k) => {
      v = v * 0.6 + (base + (r() - 0.5) * spread + Math.sin(k / 3.5) * spread * 0.35) * 0.4;
      return Math.max(0, Math.round(v * 10) / 10);
    });
  };
  const pick = (id, list, n, salt = 0) => {
    const r = rng(hash(id) + salt),
      out = [];
    while (out.length < Math.min(n, list.length)) {
      const x = list[Math.floor(r() * list.length)];
      if (!out.includes(x)) out.push(x);
    }
    return out;
  };

  // -- what a node or a link reports (a pretend observability service)
  const apiMetrics = (id) => {
    const r = rng(hash(id));
    const p50 = series(id, 24, 30 + r() * 60, 30, 1),
      p95 = p50.map((v, k) => Math.round(v * (2.2 + 0.4 * Math.sin(k / 4)))),
      p99 = p95.map((v) => Math.round(v * 1.6)),
      rps = series(id, 24, 200 + r() * 3000, 900, 2).map(Math.round),
      errors = series(id, 24, 0.4 + r() * 1.5, 1.2, 3);
    const endpoints = Array.from({ length: 6 }, (_, k) => {
      const noun = NOUNS[(hash(id) + k * 7) % NOUNS.length];
      const method = ['GET', 'GET', 'POST', 'PUT', 'DELETE', 'GET'][k];
      return {
        method,
        path: `/v${1 + (k % 2)}/${noun}${method === 'POST' ? '' : '/{id}'}`,
        p95: Math.round(p95[k * 3] * (0.6 + r() * 0.8)),
        rps: Math.round(rps[k * 3] / (2 + k)),
        errors: Math.round(errors[k * 3] * (0.5 + r()) * 100) / 100,
      };
    });
    const team = pick(id, OWNERS, 3 + (hash(id) % 3), 4);
    const regions = pick(id, COUNTRIES, 3 + (hash(id) % 3), 5);
    const last = (list) => list[list.length - 1];
    return {
      p50,
      p95,
      p99,
      rps,
      errors,
      endpoints,
      team,
      regions,
      now: { p95: last(p95), p99: last(p99), rps: last(rps), errors: last(errors) },
      slo: 99 + ((hash(id) >>> 4) % 99) / 100,
      events: [
        {
          title: 'Deployed ' + `v${2 + (hash(id) % 5)}.${hash(id) % 20}.${hash(id) % 9}`,
          text: `by ${team[0]}, canary 10 % then 100 %`,
          when: '2 h ago',
          active: true,
        },
        {
          title: 'Latency alert resolved',
          text: `p95 back under ${Math.round(last(p95) * 1.3)} ms`,
          when: 'yesterday',
        },
        { title: 'Breaker tripped', text: 'to a dependency, recovered after 4 probes', when: '3 days ago' },
        {
          title: 'Deployed ' + `v${1 + (hash(id) % 5)}.${(hash(id) >>> 3) % 20}.0`,
          text: `by ${team[1] ?? team[0]}`,
          when: 'last week',
        },
      ],
    };
  };
  // the metrics arrive like a service answer: after a moment, once per node (ctx.request caches them)
  const later = (value, id) => new Promise((resolve) => setTimeout(() => resolve(value), 150 + (hash(id) % 300)));

  // -- building blocks: the explorer's detail parts and the library's components
  const stats = (c, rows) =>
    c.html`<dl class="graph-explorer-stats">${rows.map(([k, v, tone]) => c.html`<div class="graph-explorer-stat"${tone ? c.html` data-tone="${tone}"` : ''}><dt>${k}</dt><dd>${v}</dd></div>`)}</dl>`;
  const section = (c, title, body, count) =>
    c.html`<section class="graph-explorer-section"><h4 class="graph-explorer-section-title"><span>${title}</span>${count != null ? c.html`<span class="graph-explorer-section-count">${count}</span>` : ''}</h4>${body}</section>`;
  const card = (c, title, body, { icon, note, wide } = {}) =>
    c.html`<section class="card graph-explorer-page-card" data-size="sm"${wide ? c.html` data-wide` : ''}><header class="card-header"><h3 class="card-title">${icon ? c.icon(icon, { size: 'sm' }) : ''}${title}</h3>${note ? c.html`<p class="card-description">${note}</p>` : ''}</header><div class="card-content">${body}</div></section>`;
  const kpi = (c, title, value, note, tone) =>
    c.html`<div class="statistic graph-explorer-kpi"${tone ? c.html` data-tone="${tone}"` : ''}><p class="statistic-title">${title}</p><p class="statistic-value">${value}</p>${note != null ? c.html`<p class="statistic-description">${note}</p>` : ''}</div>`;
  const head = (c, icon, kicker, path) =>
    c.html`<header class="graph-explorer-detail-head"><span class="graph-explorer-detail-tile">${c.icon(icon, { size: c.expanded ? 'xl' : 'lg' })}</span><div class="graph-explorer-detail-titles"><p class="graph-explorer-detail-kicker">${kicker}</p>${trail(c, path)}</div></header>`;
  const pageHead = (c, icon, title, kicker, path, actions) =>
    c.html`<header class="graph-explorer-page-head"><span class="graph-explorer-detail-tile" data-size="xl">${c.icon(icon, { size: 'xl' })}</span><div class="graph-explorer-page-titles">${trail(c, path)}<h2 class="graph-explorer-page-title">${title}</h2><p class="graph-explorer-detail-kicker">${kicker}</p></div>${actions}</header>`;
  const trail = (c, path, last = false) =>
    path
      ? c.html`<nav class="graph-explorer-trail" aria-label="Path">${(last ? path : path.slice(0, -1)).map((p, k) => c.html`${k ? c.html`<span class="graph-explorer-trail-sep" aria-hidden="true">›</span>` : ''}${p.id === 'c0' ? c.html`<span>${p.label}</span>` : c.html`<button type="button" class="graph-explorer-link" data-graph-explorer-goto="${p.id}">${p.label}</button>`}`)}</nav>`
      : '';
  // a cluster's button says what it does: the graph zooms in and shows its systems (a domain) or its entities
  const inside = (n) => `${fmt(n.children)} ${n.typeName === 'Domain' ? 'systems' : 'entities'}`;
  const actions = (c, n) =>
    c.html`<div class="graph-explorer-detail-actions">${n && n.kind === 'cluster' ? c.html`<button type="button" class="btn" data-size="sm" data-graph-explorer-action="enter" title="Zoom into ${n.label} (Enter)">${c.icon('scan')} Show its ${inside(n)}</button>` : ''}${n && !c.expanded ? c.html`<button type="button" class="btn" data-variant="outline" data-size="sm" data-graph-explorer-action="bring" title="Gather the busiest neighbours of ${n.label} around it and fly to the one you pick (B)">${c.icon('crosshair')} Jump to a neighbour</button>` : ''}${c.expanded ? c.html`<button type="button" class="btn" data-variant="outline" data-size="sm" data-graph-explorer-action="collapse">${c.icon('shrink')} Back to graph</button>` : c.expandable ? c.html`<button type="button" class="btn" data-variant="ghost" data-size="sm" data-graph-explorer-action="expand">${c.icon('expand')} Expand</button>` : ''}</div>`;
  const row = (c, r) =>
    c.html`<li class="graph-explorer-row"><button type="button" class="graph-explorer-row-main" data-graph-explorer-goto="${r.id}">${r.icon ?? ''}<span class="graph-explorer-row-name">${r.label}</span>${r.meta != null ? c.html`<span class="graph-explorer-row-meta">${r.meta}</span>` : ''}</button>${r.badge ?? ''}${r.edge ? c.html`<button type="button" class="graph-explorer-row-link" data-graph-explorer-edge="${r.edge}" title="Inspect the link" aria-label="Inspect the link to ${r.label}">${c.icon('link-2', { size: 'sm' })}</button>` : ''}</li>`;
  const rows = (c, list) => c.html`<ul class="graph-explorer-rows">${list}</ul>`;
  const badge = (c, text, variant = 'secondary') =>
    c.html`<span class="badge" data-variant="${variant}">${text}</span>`;
  const stateBadge = (c, state) =>
    c.html`<span class="badge graph-explorer-state" data-variant="${state === 'closed' ? 'secondary' : 'outline'}" data-state="${state}">${state}</span>`;
  const loading = (c) => c.html`<p class="kg-note">Loading...</p>`;
  // a Chart: the data-chart JSON is the ECharts option; in an island its canvas survives the details' re-renders
  const chart = (c, key, label, option, height = '8.5rem') =>
    c.island(
      key,
      c.html`<div class="chart" role="img" aria-label="${label}" style="height:${height}" data-chart="${JSON.stringify({ grid: { left: 40, right: 12, top: 28, bottom: 22 }, tooltip: { trigger: 'axis' }, ...option })}"></div>`,
    );
  const lines = (labels, list, extra = {}) => ({
    legend: { top: 0, right: 0, itemWidth: 10, itemHeight: 6, textStyle: { fontSize: 10 } },
    xAxis: { type: 'category', data: labels, boundaryGap: false, axisLabel: { fontSize: 10 } },
    yAxis: { type: 'value', splitNumber: 3, axisLabel: { fontSize: 10 }, ...extra },
    series: list.map(([name, data, area]) => ({
      name,
      type: 'line',
      smooth: true,
      showSymbol: false,
      data,
      ...(area ? { areaStyle: { opacity: 0.14 } } : {}),
    })),
  });
  const donut = (data) => ({
    tooltip: { trigger: 'item' },
    grid: undefined,
    legend: { orient: 'vertical', right: 0, top: 'middle', itemWidth: 8, itemHeight: 8, textStyle: { fontSize: 11 } },
    series: [{ type: 'pie', radius: ['52%', '78%'], center: ['32%', '50%'], label: { show: false }, data }],
  });
  // a Geo Map of the countries a node runs in (the data loads with the first map)
  const map = (c, key, countries, label) =>
    c.island(
      key,
      c.html`<div class="geo-map" data-select="none" data-palette="mono" data-highlight="fill" data-selected="${countries.map((k) => 'country:' + k).join(' ')}" aria-label="${label}"></div>`,
    );
  // an Avatar group of the people behind a node
  const team = (c, key, people) =>
    c.island(
      key,
      c.html`<div class="kg-team"><div class="avatar-group">${people.map((p) => c.html`<span class="avatar" data-size="sm" title="${p}"><span class="avatar-fallback">${p.slice(0, 2).toUpperCase()}</span></span>`)}</div><p class="kg-note">${people.join(', ')} · on call: ${people[0]}</p></div>`,
    );
  // a Timeline of what happened to it
  const timeline = (c, events) =>
    c.html`<ol class="timeline">${events.map((e) => c.html`<li class="timeline-item"><div class="timeline-dot"${e.active ? c.html` data-variant="active"` : ''}></div><div class="timeline-content"><p class="timeline-title">${e.title}</p><p class="timeline-description">${e.text}</p><time class="timeline-time">${e.when}</time></div></li>`)}</ol>`;
  const table = (c, heads, body) =>
    c.html`<div class="table-container"><table class="table graph-explorer-rel-table"><thead><tr class="table-row">${heads.map((h) => c.html`<th class="table-head" scope="col"${/^(p95|Links|Rows|Requests|Errors|Trips)/.test(h) ? c.html` style="text-align:right"` : ''}>${h}</th>`)}</tr></thead><tbody>${body}</tbody></table></div>`;
  const num = (c, v) => c.html`<td class="table-cell" style="text-align:right">${v}</td>`;
  const relationRows = (c, n, d, limit = 10) =>
    rows(
      c,
      (d.relations ?? []).slice(0, limit).map((r) =>
        row(c, {
          id: r.id,
          label: r.label,
          meta: c.html`${r.out ? c.html`<span>→ ${fmt(r.out)}</span>` : ''}${r.in ? c.html`<span>← ${fmt(r.in)}</span>` : ''}`,
          badge: r.breaker && r.breaker.state !== 'closed' ? stateBadge(c, r.breaker.state) : '',
          edge: n.id + '>' + r.id,
        }),
      ),
    );

  // -- an API system: metrics, latency, endpoints, regions, team, deploys
  const apiSystem = {
    kind: 'detail',
    name: 'atlas-api-system',
    match: (n) => (n.kind === 'cluster' && n.typeName === 'API' ? 20 : false),
    title: (n) => `${n.label} (API)`,
    render: (n, c) => {
      const m = c.request('metrics:' + n.id, () => later(apiMetrics(n.id), n.id));
      const d = c.request('details:' + n.id, () => c.fetchDetails(n.id));
      const kicker = c.html`API system · ${fmt(n.members)} nodes`;
      if (!m || !d) return c.html`${head(c, 'plug-zap', kicker, d?.path)}${loading(c)}`;
      const tone = m.now.errors > 1.5 ? 'danger' : m.now.errors > 0.8 ? 'warn' : 'ok';
      const latency = (h) =>
        chart(
          c,
          `latency:${n.id}:${h}`,
          `${n.label} latency, the last 24 hours`,
          lines(HOURS, [['p50', m.p50], ['p95', m.p95, true], ...(c.expanded ? [['p99', m.p99]] : [])], { name: 'ms' }),
          h,
        );
      const open = (d.relations ?? []).filter((r) => r.breaker && r.breaker.state !== 'closed');
      const endpointRows = m.endpoints.map(
        (e) =>
          c.html`<tr class="table-row"><td class="table-cell"><span class="kg-endpoint">${badge(c, e.method, e.method === 'GET' ? 'secondary' : 'outline')}${e.path}</span></td>${num(c, e.p95 + ' ms')}${c.expanded ? c.html`${num(c, fmt(e.rps) + ' /s')}${num(c, e.errors.toFixed(2) + ' %')}<td class="table-cell">${e.errors > 1.5 ? badge(c, 'degraded', 'destructive') : badge(c, 'healthy', 'outline')}</td>` : ''}</tr>`,
      );
      if (!c.expanded)
        return c.html`${head(c, 'plug-zap', kicker, d.path)}${actions(c, n)}
          ${stats(c, [
            ['p95 latency', m.now.p95 + ' ms'],
            ['Error rate', m.now.errors.toFixed(2) + ' %', tone],
            ['Requests', fmt(m.now.rps) + ' /s'],
            ['SLO', m.slo.toFixed(2) + ' %', m.slo >= 99.5 ? 'ok' : 'warn'],
          ])}
          ${section(c, 'Latency, 24 h', latency('8.5rem'))}
          ${section(c, 'Endpoints', table(c, ['Endpoint', 'p95'], endpointRows), m.endpoints.length)}
          ${section(c, 'Team', team(c, 'team:' + n.id, m.team))}
          ${open.length ? section(c, 'Breakers not closed', relationRows(c, n, { relations: open }), open.length) : ''}`;
      return c.html`<div class="graph-explorer-page">${pageHead(c, 'plug-zap', n.label, kicker, d.path, actions(c, n))}
        <section class="graph-explorer-kpis">
          ${kpi(c, 'p95 latency', m.now.p95 + ' ms', `p99 ${m.now.p99} ms`)}
          ${kpi(c, 'Error rate', m.now.errors.toFixed(2) + ' %', 'the last hour', tone)}
          ${kpi(c, 'Requests', fmt(m.now.rps) + ' /s', `${fmt(m.rps.reduce((a, b) => a + b, 0) * 3600)} a day`)}
          ${kpi(c, 'SLO', m.slo.toFixed(2) + ' %', 'target 99.5 %', m.slo >= 99.5 ? 'ok' : 'warn')}
          ${kpi(c, 'Regions', m.regions.length, m.regions.join(', '))}
        </section>
        <div class="graph-explorer-page-grid">
          ${card(c, 'Latency, the last 24 hours', latency('15rem'), { icon: 'timer', note: 'p50, p95 and p99 per hour', wide: true })}
          ${card(
            c,
            'Throughput and errors',
            chart(
              c,
              'rps:' + n.id,
              `${n.label} requests and errors`,
              {
                legend: { top: 0, right: 0, itemWidth: 10, itemHeight: 6, textStyle: { fontSize: 10 } },
                xAxis: { type: 'category', data: HOURS, axisLabel: { fontSize: 10 } },
                yAxis: [
                  { type: 'value', splitNumber: 3, axisLabel: { fontSize: 10 } },
                  { type: 'value', splitNumber: 3, axisLabel: { fontSize: 10 } },
                ],
                series: [
                  { name: 'requests /s', type: 'bar', data: m.rps },
                  { name: 'errors %', type: 'line', yAxisIndex: 1, smooth: true, showSymbol: false, data: m.errors },
                ],
              },
              '13rem',
            ),
            { icon: 'activity' },
          )}
          ${card(c, 'Deployment regions', map(c, 'regions:' + n.id, m.regions, `${n.label} runs in ${m.regions.join(', ')}`), { icon: 'globe', note: m.regions.join(' · ') })}
          ${card(c, 'Deploys and incidents', timeline(c, m.events), { icon: 'history' })}
          ${card(c, 'Endpoints', table(c, ['Endpoint', 'p95', 'Requests', 'Errors', 'Status'], endpointRows), { icon: 'plug', wide: true })}
          ${card(c, 'Team', team(c, 'team:' + n.id, m.team), { icon: 'users' })}
          ${card(c, 'Relations', d.relations?.length ? relationRows(c, n, d, 20) : c.html`<p class="kg-note">No relations at this level.</p>`, { icon: 'link-2', note: 'a name opens its page, the link button its traffic' })}
        </div></div>`;
    },
  };

  // -- a domain: its systems by kind, its regions, its cost, its teams
  const domain = {
    kind: 'detail',
    name: 'atlas-domain',
    match: (n) => (n.kind === 'cluster' && n.typeName === 'Domain' ? 20 : false),
    render: (n, c) => {
      const d = c.request('details:' + n.id, () => c.fetchDetails(n.id));
      const v = c.request('view:' + n.id, () => c.fetchView(n.id));
      const kicker = c.html`Domain · ${fmt(n.members)} nodes`;
      if (!d || !v) return c.html`${head(c, 'boxes', kicker, d?.path)}${loading(c)}`;
      const kinds = new Map();
      for (const s of v.children) kinds.set(s.typeName, (kinds.get(s.typeName) || 0) + 1);
      const mix = chart(
        c,
        'kinds:' + n.id,
        `${n.label} systems by kind`,
        donut([...kinds].map(([name, value]) => ({ name, value }))),
        c.expanded ? '13rem' : '8.5rem',
      );
      const people = pick(n.id, OWNERS, 4 + (hash(n.id) % 3), 6);
      const b = n.breakers || { open: 0, half: 0, cut: 0, total: 0 };
      const bad = b.open + b.half + b.cut;
      if (!c.expanded)
        return c.html`${head(c, 'boxes', kicker, d.path)}${actions(c, n)}
          ${stats(c, [
            ['Systems', fmt(d.children)],
            ['Nodes', fmt(d.members)],
            ['Relations', fmt(d.relations?.length ?? 0)],
            ['Not closed', bad ? `${bad} of ${b.total}` : 'none', bad ? 'warn' : 'ok'],
          ])}
          ${section(c, 'Systems by kind', mix)}
          ${section(c, 'Teams', team(c, 'teams:' + n.id, people))}
          ${section(c, 'Relations', relationRows(c, n, d), d.relations?.length)}`;
      const cost = series(n.id, 12, 40 + (hash(n.id) % 60), 25, 7).map((x) => Math.round(x));
      const systems = [...v.children].sort((a, b) => b.members - a.members).slice(0, 30);
      return c.html`<div class="graph-explorer-page">${pageHead(c, 'boxes', n.label, kicker, d.path, actions(c, n))}
        <section class="graph-explorer-kpis">
          ${kpi(c, 'Systems', fmt(d.children), [...kinds].map(([k, x]) => `${x} ${k}`).join(' · '))}
          ${kpi(c, 'Nodes', fmt(d.members), 'entities below')}
          ${kpi(c, 'Links not closed', fmt(bad), `of ${fmt(b.total)} bundled`, bad ? 'warn' : 'ok')}
          ${kpi(c, 'Cost', '$' + cost[11] + 'k', 'this month')}
        </section>
        <div class="graph-explorer-page-grid">
          ${card(c, 'Systems by kind', mix, { icon: 'layers' })}
          ${card(c, 'Regions', map(c, 'regions:' + n.id, pick(n.id, COUNTRIES, 5, 8), `${n.label} runs in these countries`), { icon: 'globe' })}
          ${card(c, 'Cost per month', chart(c, 'cost:' + n.id, `${n.label} cost per month`, { xAxis: { type: 'category', data: MONTHS, axisLabel: { fontSize: 10 } }, yAxis: { type: 'value', splitNumber: 3, name: '$k', axisLabel: { fontSize: 10 } }, series: [{ type: 'bar', data: cost }] }, '13rem'), { icon: 'activity' })}
          ${card(
            c,
            'Systems',
            table(
              c,
              ['System', 'Kind', 'Links'],
              systems.map(
                (s) =>
                  c.html`<tr class="table-row"><td class="table-cell"><button type="button" class="graph-explorer-link" data-graph-explorer-goto="${s.id}">${s.label}</button></td><td class="table-cell">${badge(c, s.typeName, s.typeName === 'API' ? 'default' : 'secondary')}</td>${num(c, fmt(s.members))}</tr>`,
              ),
            ),
            { icon: 'boxes', note: 'pick one for its page', wide: true },
          )}
          ${card(c, 'Teams', team(c, 'teams:' + n.id, people), { icon: 'users' })}
          ${card(c, 'Relations', relationRows(c, n, d, 20), { icon: 'link-2', note: 'the link button shows the traffic between the domains' })}
        </div></div>`;
    },
  };

  // -- a dataset: freshness, quality, schema, lineage, pipeline runs
  // -- a dataset's records: synthetic and stable per dataset, up to a million rows. The Data Grid holds them, the
  //    charts draw their aggregation (df$.shadcn.chart.bind over the grid's own dataview source) and follow its
  //    filters; a click on a country or a status filters the grid in turn
  const REGIONS = ['DEU', 'USA', 'IRL', 'JPN', 'BRA', 'IND', 'SGP', 'FRA', 'GBR', 'CAN'];
  const CHANNELS = ['web', 'app', 'api', 'partner'];
  const STATUSES = ['ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'late', 'failed'];
  const USER_IDS = Array.from({ length: 60000 }, (_, k) => 'u-' + String(k).padStart(5, '0'));
  const DAY = 864e5;
  const NOW = Date.UTC(2026, 10, 1);
  const RECORD_FIELDS = [
    ['id', 'bigint'],
    ['created_at', 'timestamp'],
    ['country', 'char(3)'],
    ['channel', 'enum'],
    ['status', 'enum'],
    ['amount', 'decimal'],
    ['user_id', 'text'],
  ];
  const recordCount = (n) => Math.min(1_000_000, n.attrs.rows * 1000);
  // one dataset's records at a time - a million rows take about 100 MB
  let kept = null;
  const records = (n) => {
    if (kept?.id === n.id) return kept.rows;
    const count = recordCount(n),
      seed = hash(n.id),
      rows = new Array(count);
    for (let i = 0; i < count; i++) {
      let h = Math.imul(seed ^ (i + 1), 0x9e3779b1);
      h = Math.imul(h ^ (h >>> 16), 0x85ebca6b);
      h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
      h = (h ^ (h >>> 16)) >>> 0;
      const g = Math.imul(h ^ 0x5bd1e995, 0x27d4eb2d) >>> 0;
      rows[i] = {
        id: i + 1,
        // more rows lately: the dataset grows - an age density falling linearly to 40 % over the month
        created_at: NOW - Math.floor(((1 - Math.sqrt(1 - (0.84 * h) / 4294967296)) / 0.6) * 30 * DAY),
        country: REGIONS[g % REGIONS.length],
        channel: CHANNELS[(g >>> 4) & 3],
        status: STATUSES[(g >>> 6) & 7],
        amount: (((g >>> 9) % 40000) + 100) / 100,
        user_id: USER_IDS[(g >>> 3) % USER_IDS.length],
      };
    }
    kept = { id: n.id, rows };
    return rows;
  };
  // the aggregations: plain JSON (df$.dataview's aggregate spec)
  const PER_DAY = { groupBy: { field: 'created_at', bucket: 'day', as: 'day' }, fill: true };
  const BY_COUNTRY = {
    groupBy: 'country',
    measures: [{ op: 'sum', field: 'amount', as: 'amount' }],
    sort: { by: 'amount', direction: 'desc' },
  };
  const BY_STATUS = { groupBy: 'status', sort: { by: 'count', direction: 'desc' } };
  // a static option: the groups join it as dataset.source, the series encode the keys
  const dayOption = {
    grid: { left: 44, right: 12, top: 12, bottom: 22 },
    tooltip: { trigger: 'axis' },
    dataset: { dimensions: ['day', 'count'] },
    xAxis: { type: 'time', axisLabel: { fontSize: 10 } },
    yAxis: { type: 'value', splitNumber: 3, axisLabel: { fontSize: 10 } },
    series: [{ type: 'bar', name: 'records', encode: { x: 'day', y: 'count' }, barMaxWidth: 10 }],
  };
  // an option of the groups
  const countryOption = (rows) => ({
    grid: { left: 48, right: 16, top: 8, bottom: 20 },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'value', splitNumber: 3, axisLabel: { fontSize: 10 } },
    yAxis: { type: 'category', inverse: true, data: rows.map((r) => r.country), axisLabel: { fontSize: 10 } },
    series: [{ type: 'bar', name: 'amount (EUR)', data: rows.map((r) => Math.round(r.amount)), barMaxWidth: 14 }],
  });
  const statusOption = (rows) => donut(rows.map((r) => ({ name: r.status, value: r.count })));
  // a chart bound to a source (an island: bound once, released when the island goes)
  const boundChart = (c, key, label, height, bind) =>
    c.island(key, c.html`<div class="chart" role="img" aria-label="${label}" style="height:${height}"></div>`, (el) => {
      const binding = df$.shadcn.chart.bind(df$(el).find('.chart').get(0), bind());
      return () => binding.dispose();
    });
  // every record in a Data Grid, three charts of what its filters match - the grid's filter scan is theirs too
  const recordsView = (c, n) =>
    c.island(
      'records:' + n.id,
      c.html`<div class="kg-records">
        <p class="kg-records-count" aria-live="polite">${fmt(recordCount(n))} records</p>
        <div class="kg-records-charts">
          <figure class="kg-records-chart"><figcaption>Records per day</figcaption><div class="chart" data-kg-chart="day" role="img" aria-label="${n.label}: records per day" style="height: 10rem"></div></figure>
          <figure class="kg-records-chart"><figcaption>Amount by country - click to filter</figcaption><div class="chart" data-kg-chart="country" role="img" aria-label="${n.label}: amount by country" style="height: 10rem"></div></figure>
          <figure class="kg-records-chart"><figcaption>Status - click to filter</figcaption><div class="chart" data-kg-chart="status" role="img" aria-label="${n.label}: records by status" style="height: 10rem"></div></figure>
        </div>
        <div class="data-grid" aria-label="${n.label}: records" data-persist="none" data-empty-text="No record matches the filters." style="height: 22rem">
          <div class="data-grid-viewport"><div class="data-grid-head"><div class="data-grid-row">
            <div class="data-grid-header" data-field="id" data-type="number" data-format="" data-width="7rem">Id</div>
            <div class="data-grid-header" data-field="created_at" data-type="number" data-format="date" data-width="8rem">Created</div>
            <div class="data-grid-header" data-field="country" data-width="7rem" data-filter="select">Country</div>
            <div class="data-grid-header" data-field="channel" data-width="7rem" data-filter="select">Channel</div>
            <div class="data-grid-header" data-field="status" data-width="7rem" data-filter="select">Status</div>
            <div class="data-grid-header" data-field="amount" data-type="number" data-format="currency:EUR" data-width="8rem" data-filter="number">Amount</div>
            <div class="data-grid-header" data-field="user_id" data-width="8rem" data-filter="text">User</div>
          </div></div><div class="data-grid-body"></div></div>
        </div>
      </div>`,
      (el) => {
        const grid = df$(el).find('.data-grid').get(0);
        const count = df$(el).find('.kg-records-count').get(0);
        df$.shadcn.dataGrid.setSource(grid, records(n));
        const source = df$.shadcn.dataGrid.source(grid);
        const charts = {
          day: [PER_DAY, dayOption],
          country: [BY_COUNTRY, countryOption],
          status: [BY_STATUS, statusOption],
        };
        const bound = Object.entries(charts).map(([name, [aggregate, option]]) =>
          df$.shadcn.chart.bind(df$(el).find(`[data-kg-chart="${name}"]`).get(0), {
            source,
            aggregate,
            option,
            follow: grid,
          }),
        );
        // chart-data: how many records the groups were made of
        df$(el)
          .find('[data-kg-chart="day"]')
          .on('chart-data', (e) => {
            const { matched, total, ms } = e.detail;
            df$(count).text(
              `${fmt(matched)} of ${fmt(total)} records${matched < total ? ' match the filters' : ''} · grouped in ${ms} ms`,
            );
          });
        // a click on a bar or a slice filters the grid by it (again: lets it go) - the charts follow the grid
        const toggle = (field, value) => {
          const now = grid.store.value.config.filters ?? [];
          const had = now.some((f) => f.field === field && f.value === value);
          const rest = now.filter((f) => f.field !== field);
          df$.shadcn.dataGrid.query(grid, { filters: had ? rest : [...rest, { field, op: 'eq', value }] });
        };
        bound[1].mounted.then((chart) => chart.on('click', (p) => toggle('country', p.name)));
        bound[2].mounted.then((chart) => chart.on('click', (p) => toggle('status', p.name)));
        return () => bound.forEach((b) => b.dispose());
      },
    );

  const dataset = {
    kind: 'detail',
    name: 'atlas-dataset',
    match: (n) => (n.kind === 'entity' && n.typeName === 'Dataset' ? 20 : false),
    render: (n, c) => {
      const d = c.request('details:' + n.id, () => c.fetchDetails(n.id));
      const a = n.attrs;
      const stale = a.freshness > 24;
      const quality = 70 + (hash(n.id) % 30);
      const kicker = c.html`Dataset · owned by ${a.owner}`;
      if (!d) return c.html`${head(c, 'database', kicker, null)}${loading(c)}`;
      const checks = [
        ['not null', true],
        ['unique id', true],
        ['fresh < 24 h', !stale],
        ['schema stable', hash(n.id) % 4 !== 0],
      ];
      const quality$ = c.island(
        'quality:' + n.id,
        c.html`<progress class="progress" value="${quality}" max="100" aria-label="Quality score">${quality} %</progress>`,
      );
      const lineage = (list, incoming) =>
        list.length
          ? rows(
              c,
              list.slice(0, 8).map((r) =>
                row(c, {
                  id: r.id,
                  label: r.label,
                  icon: c.icon(r.edge === 'reads' ? 'eye' : r.edge === 'owns' ? 'key-round' : 'zap', { size: 'xs' }),
                  meta: `${r.type} · ${r.same ? 'here' : r.system}`,
                  edge: r.same ? (incoming ? r.id + '>' + n.id : n.id + '>' + r.id) : null,
                }),
              ),
            )
          : c.html`<p class="kg-note">None.</p>`;
      const schema = table(
        c,
        ['Column', 'Type'],
        RECORD_FIELDS.map(
          ([col, type]) =>
            c.html`<tr class="table-row"><td class="table-cell"><code>${col}</code></td><td class="table-cell">${badge(c, type, 'outline')}</td></tr>`,
        ),
      );
      const checkBadges = c.html`<div class="kg-checks">${checks.map(([k, ok]) => badge(c, (ok ? '✓ ' : '✗ ') + k, ok ? 'secondary' : 'destructive'))}</div>`;
      // the side: a chart of every record - a million rows aggregated by day, in the sidebar
      if (!c.expanded)
        return c.html`${head(c, 'database', kicker, d.path)}${actions(c, n)}
          ${stats(c, [
            ['Rows', fmt(a.rows) + 'k'],
            ['Freshness', a.freshness + ' h', stale ? 'warn' : 'ok'],
            ['Quality', quality + ' %', quality >= 85 ? 'ok' : 'warn'],
            ['Links', `${d.outDeg} out · ${d.inDeg} in`],
          ])}
          ${section(
            c,
            'Records per day',
            boundChart(c, 'side-day:' + n.id, `${n.label}: records per day`, '7.5rem', () => ({
              source: df$.dataview.source(records(n)),
              aggregate: PER_DAY,
              option: dayOption,
            })),
            fmt(recordCount(n)),
          )}
          ${section(c, 'Quality', c.html`${quality$}${checkBadges}`)}
          ${section(c, 'Schema', schema, RECORD_FIELDS.length)}
          ${section(c, 'Upstream', lineage(d.in ?? [], true), d.inDeg)}
          ${section(c, 'Downstream', lineage(d.out ?? [], false), d.outDeg)}`;
      const runs = [
        {
          title: 'Pipeline run succeeded',
          text: `${fmt(Math.round(a.rows * 12))} rows written`,
          when: `${a.freshness} h ago`,
          active: true,
        },
        { title: 'Schema change', text: `added ${RECORD_FIELDS[RECORD_FIELDS.length - 1][0]}`, when: 'last week' },
        { title: 'Backfill', text: 'the last 90 days', when: 'last month' },
      ];
      return c.html`<div class="graph-explorer-page">${pageHead(c, 'database', n.label, kicker, d.path, actions(c, n))}
        <section class="graph-explorer-kpis">
          ${kpi(c, 'Rows', fmt(a.rows) + 'k', `the latest ${fmt(recordCount(n))} below`)}
          ${kpi(c, 'Freshness', a.freshness + ' h', stale ? 'stale' : 'fresh', stale ? 'warn' : 'ok')}
          ${kpi(c, 'Quality', quality + ' %', `${checks.filter(([, ok]) => ok).length} of ${checks.length} checks pass`, quality >= 85 ? 'ok' : 'warn')}
          ${kpi(c, 'Lineage', `${d.inDeg} → · → ${d.outDeg}`, 'upstream · downstream')}
        </section>
        <div class="graph-explorer-page-grid">
          ${card(c, 'Records', recordsView(c, n), { icon: 'database', wide: true, note: 'every record in a Data Grid; the charts group what its filters match' })}
          ${card(c, 'Quality', c.html`${quality$}${checkBadges}`, { icon: 'shield-check', note: 'checks of the last run' })}
          ${card(c, 'Pipeline runs', timeline(c, runs), { icon: 'history' })}
          ${card(c, 'Schema', schema, { icon: 'table' })}
          ${card(c, 'Upstream', lineage(d.in ?? [], true), { icon: 'arrow-left', note: 'what it is built from' })}
          ${card(c, 'Downstream', lineage(d.out ?? [], false), { icon: 'arrow-right', note: 'what reads or owns it' })}
        </div></div>`;
    },
  };

  // -- a link between two clusters: its traffic both ways, by relation, its breakers, who sends and who receives
  const traffic = {
    kind: 'edge',
    name: 'atlas-traffic',
    detail: {
      match: (item) => (item.edge.kind === 'agg' ? 20 : false),
      title: (item) => `${item.source.label} → ${item.target.label}`,
      render: (item, c) => {
        const d = c.request('edge:' + item.id, () => c.fetchEdge(item.id));
        const e = item.edge;
        const kicker = c.html`Links between ${item.source.typeName === 'Domain' ? 'domains' : 'systems'} · ${fmt(e.count + e.count2)}`;
        const ends = c.html`<div class="graph-explorer-ends">${[item.source, item.target].map((x, k) => c.html`${k ? c.html`<span class="graph-explorer-ends-arrow">${c.icon(e.bidir ? 'arrow-left-right' : 'arrow-right', { size: 'sm' })}</span>` : ''}<button type="button" class="graph-explorer-end" data-graph-explorer-goto="${x.id}">${c.icon(x.typeName === 'Domain' ? 'boxes' : 'plug-zap', { size: 'sm' })}<span class="graph-explorer-end-name">${x.label}</span><span class="graph-explorer-end-type">${x.typeName}</span></button>`)}</div>`;
        if (!d) return c.html`${head(c, 'link-2', kicker, null)}${ends}${loading(c)}`;
        const fwd = series(item.id, 24, d.forward * 2.4, d.forward, 13).map(Math.round),
          back = series(item.id, 24, d.backward * 2.4, d.backward + 1, 14).map(Math.round),
          errs = series(item.id, 24, 0.3 + (hash(item.id) % 20) / 10, 0.8, 15);
        const bad = d.pairs.filter((p) => p.state !== 'closed');
        const callsChart = (h) =>
          chart(
            c,
            `calls:${item.id}:${h}`,
            `calls per minute between ${item.source.label} and ${item.target.label}`,
            lines(HOURS, [
              [`→ ${item.target.label}`, fwd, true],
              [`← ${item.source.label}`, back],
            ]),
            h,
          );
        const share = (list) =>
          rows(
            c,
            list.slice(0, 6).map((x) => row(c, { id: x.id, label: x.label, meta: fmt(x.count) })),
          );
        const pairsTable = table(
          c,
          ['Caller', 'Callee', 'Links', 'State', 'Trips'],
          d.pairs
            .slice(0, c.expanded ? 40 : 6)
            .map(
              (p) =>
                c.html`<tr class="table-row"><td class="table-cell"><button type="button" class="graph-explorer-link" data-graph-explorer-goto="${p.from.id}">${p.from.label}</button></td><td class="table-cell"><button type="button" class="graph-explorer-link" data-graph-explorer-goto="${p.to.id}">${p.to.label}</button></td>${num(c, fmt(p.count))}<td class="table-cell">${stateBadge(c, p.state)}</td>${num(c, p.trips)}</tr>`,
            ),
        );
        const errNow = errs[23];
        if (!c.expanded)
          return c.html`${head(c, 'link-2', kicker, d.path)}${ends}${actions(c, null)}
            ${stats(c, [
              ['Forward', fmt(d.forward)],
              ['Back', fmt(d.backward)],
              ['Errors', errNow.toFixed(2) + ' %', errNow > 1.5 ? 'danger' : errNow > 0.8 ? 'warn' : 'ok'],
              ['Breakers', `${bad.length} of ${d.pairs.length} not closed`, bad.length ? 'warn' : 'ok'],
            ])}
            ${section(c, 'Calls per minute, 24 h', callsChart('8.5rem'))}
            ${bad.length ? section(c, 'Breakers not closed', pairsTable, bad.length) : ''}
            ${d.sources.length ? section(c, 'Top senders', share(d.sources)) : ''}`;
        return c.html`<div class="graph-explorer-page">${pageHead(c, 'link-2', `${item.source.label} → ${item.target.label}`, kicker, d.path, actions(c, null))}${ends}
          <section class="graph-explorer-kpis">
            ${kpi(c, 'Forward', fmt(d.forward), `${fmt(fwd[23])} calls / min now`)}
            ${kpi(c, 'Back', fmt(d.backward), `${fmt(back[23])} calls / min now`)}
            ${kpi(c, 'Errors', errNow.toFixed(2) + ' %', 'the last hour', errNow > 1.5 ? 'danger' : errNow > 0.8 ? 'warn' : 'ok')}
            ${kpi(c, 'Breakers', fmt(d.pairs.length), `${bad.length} not closed`, bad.length ? 'warn' : 'ok')}
          </section>
          <div class="graph-explorer-page-grid">
            ${card(c, 'Calls per minute, the last 24 hours', callsChart('15rem'), { icon: 'activity', wide: true })}
            ${card(
              c,
              'By relation',
              chart(
                c,
                'types:' + item.id,
                'links by relation',
                donut(
                  Object.entries(d.byType)
                    .filter(([, x]) => x > 0)
                    .map(([name, value]) => ({ name, value })),
                ),
                '12rem',
              ),
              { icon: 'workflow' },
            )}
            ${card(c, 'Error rate', chart(c, 'errors:' + item.id, 'error rate per hour', lines(HOURS, [['errors %', errs, true]]), '12rem'), { icon: 'triangle-alert' })}
            ${card(c, 'Top senders', share(d.sources), { icon: 'send', note: 'in ' + item.source.label })}
            ${card(c, 'Top receivers', share(d.targets), { icon: 'target', note: 'in ' + item.target.label })}
            ${card(c, 'Circuit breakers', pairsTable, { icon: 'shield-check', note: 'the system pairs this link bundles, the worst first', wide: true })}
          </div></div>`;
      },
    },
  };

  document.addEventListener('DOMContentLoaded', () => {
    const ge = df$.shadcn.graphExplorer;
    // a dataset's row count joins the Labels layer; an Owners layer of its own; the pages above
    ge.register('global', {
      kind: 'node',
      name: 'atlas-dataset-labels',
      layer: 'labels',
      match: (n) => (n.kind === 'entity' && n.typeName === 'Dataset' ? 10 : false),
      sizes: { chip: [64, 0], card: [0, 29] },
      render: (n, c) =>
        c.tier === 'chip'
          ? c.html`<span class="graph-explorer-count">${fmt(n.attrs.rows)}k rows</span>`
          : c.html`<p class="graph-explorer-card-meta">Dataset · ${fmt(n.attrs.rows)}k rows</p>`,
    });
    // Owners: an entity's owner, a cluster's team - a layer of its own in the layer switch, drawn in its colour
    ge.register('global', {
      kind: 'node',
      name: 'atlas-owners',
      layer: 'owners',
      layerLabel: 'Owners',
      layerIcon: 'users',
      match: () => 0,
      sizes: (n) => ({ chip: [n.kind === 'entity' ? 30 : 58, 0], card: [0, 30] }),
      render: (n, c) => {
        const people = n.kind === 'entity' ? [n.attrs.owner] : pick(n.id, OWNERS, 3, 6);
        const avatars = c.html`${people.map((p) => c.html`<span class="graph-explorer-avatar" data-type="${OWNERS.indexOf(p)}" title="${p}">${p.slice(0, 2).toUpperCase()}</span>`)}`;
        if (c.tier === 'chip') return c.html`<span class="kg-owners">${avatars}</span>`;
        return c.html`<p class="graph-explorer-card-meta kg-owners">${avatars}<span>${n.kind === 'entity' ? 'owned by ' + people[0] : 'team ' + people.join(', ')}</span></p>`;
      },
    });
    for (const plugin of [apiSystem, domain, dataset, traffic]) ge.register('global', plugin);
    // Updates: a deploy names who shipped it - the people of the Owners layer, as their avatar
    ge.register('global', {
      kind: 'update',
      name: 'atlas-deploys',
      update: {
        match: (u) => (u.type === 'deploy' ? 1 : false),
        render: (u, c) => {
          const who = pick(u.target, OWNERS, 1, 7)[0];
          return c.html`<span class="indicator-dot" data-size="sm" aria-hidden="true"></span>${c.icon('send', { size: 'sm' })}<span class="graph-explorer-update-label">${u.label}</span><span class="graph-explorer-update-text">${u.text}</span><span class="graph-explorer-avatar kg-update-who" data-type="${OWNERS.indexOf(who)}" title="by ${who}">${who.slice(0, 2).toUpperCase()}</span><time class="graph-explorer-update-time" datetime="${new Date(u.time).toISOString()}">${c.time(u.time)}</time>`;
        },
      },
    });
  });
</script>
<script type="module">
  // routing and translation: defuss-dom-router owns the address, defuss-i18n the language
  import { createRouter } from 'https://cdn.jsdelivr.net/npm/defuss-dom-router@0.1.1/dist/index.js';
  import { createDomI18n, createI18n } from 'https://cdn.jsdelivr.net/npm/defuss-i18n@0.2.0/dist/core.js';

  // df$ comes with the component bundle - a full-screen page loads it after this module
  addEventListener('DOMContentLoaded', async () => {
    const app = df$('[data-kg]').get(0);
    const kg = df$('#kg').get(0);

    // -- translation: the markup is the catalog (the templates at the end of the app)
    const locale = createI18n({
      locale: 'en', // the demos start in English; the language select offers German
    });
    createDomI18n(df$).bind(app, locale);
    // the Language Switcher sets the locale on a pick and follows it when something else sets it
    df$.shadcn.languageSwitcher.bind(df$('[data-app-locale]').get(0), locale);

    // -- light / dark: the button writes the class every token reads; the explorer, its charts and the map follow it
    const theme = df$('[data-kg-theme]');
    const showTheme = () => theme.attr('aria-pressed', String(document.documentElement.classList.contains('dark')));
    showTheme();
    theme.on('click', () => {
      document.documentElement.classList.toggle('dark');
      showTheme();
      document.dispatchEvent(new CustomEvent('defuss-theme-change'));
    });

    // -- routing: an expanded page is a route - a node's (#/node/c26) or a link's (#/link/c1/c5), so Back walks a
    //    drill-down back up and a page can be linked
    const routes = [
      { id: 'graph', path: '/' },
      { id: 'node', path: '/node/:id' },
      { id: 'link', path: '/link/:from/:to' },
      { id: 'missing', path: '*' },
    ];
    await kg.api.settled();
    const show = (to) => {
      const now = kg.api.getState().config;
      if (to.routeId === 'node') {
        if (!now.expanded || now.selected[0] !== to.params.id || now.selected.length !== 1)
          void kg.api.setState('selected', { selected: [to.params.id], edge: null, expanded: true });
      } else if (to.routeId === 'link') {
        const edge = to.params.from + '>' + to.params.to;
        if (!now.expanded || now.edge !== edge)
          void kg.api.setState('selected', { selected: [], edge, expanded: true });
      } else if (now.expanded) void kg.api.setState(kg.api.getState().name, { expanded: false });
    };
    // the explorer moves the address: an expanded page names its route, the graph is #/
    const routeOf = ({ config }) =>
      config.expanded && config.selected.length === 1
        ? '#/node/' + config.selected[0]
        : config.expanded && config.edge
          ? '#/link/' + config.edge.replace('>', '/')
          : '#/';
    kg.store.subscribe((state) => {
      const want = routeOf(state);
      if ((location.hash || '#/') !== want) location.hash = want.slice(1);
    });
    const router = createRouter({ mode: 'hash', routes, prepare: ({ to }) => ({ commit: () => show(to) }) });
    if ((await router.start()).status === 'rejected') {
      // no address the router may own - a docs preview is an about:srcdoc frame: the same routes match its hash
      const preview = createRouter({ mode: 'hash', routes, baseUrl: 'https://preview.invalid/' });
      const follow = () => show(preview.resolve(location.hash.startsWith('#/') ? location.hash : '#/'));
      addEventListener('hashchange', follow);
      follow();
    }
  });
</script>
<script type="module">
  // the tree and the palette - both ask the explorer's worker, which owns the million nodes
  addEventListener('DOMContentLoaded', async () => {
    const ge = df$.shadcn.graphExplorer;
    const { dataGrid } = df$.shadcn;
    const kg = df$('#kg').get(0);
    const grid = df$('#kg-tree').get(0);
    await kg.api.settled();
    const fmt = (n) => Number(n).toLocaleString('en-US');

    // -- the Hierarchy Explorer: the graph as a tree of any depth. A branch's children load when it opens (the
    //    worker answers); one branch per level is open - opening one closes its open sibling and lets go of what
    //    was loaded below that, so the tree holds one path of open branches and their children, never the million
    const rows = new Map(); // id -> the row the worker gave (the root, the children of every open branch)
    const loaded = new Set(); // the branches whose children are in rows
    const open = new Set(); // the open branches: the root, then one per level
    let filters = [];
    let follow = null; // the id the graph was sent to from the tree (its echo is not a new selection)
    const label = (el, record) => {
      const kind = record.more
        ? 'more'
        : record.kind === 'entity'
          ? 'entity'
          : record.type === 'Domain'
            ? 'Domain'
            : record.level === 0
              ? 'graph'
              : 'system';
      df$(el).html(
        record.more
          ? '<span class="kg-tree-more"></span>'
          : '<span class="kg-tree-label"><span class="kg-tree-dot"></span><span></span></span>',
      );
      if (record.more) df$(el).find('.kg-tree-more').text(record.hint);
      else {
        df$(el).find('.kg-tree-dot').attr('data-kind', kind);
        df$(el)
          .find('.kg-tree-label > span:last-child')
          .text(record.label)
          .attr('title', record.type + ' · ' + record.label);
      }
    };
    const count = (el, record) => df$(el).text(record.more ? '' : fmt(record.count));
    // a branch whose children are not loaded has a stand-in child, so its toggle shows (and says how many wait)
    const records = () => {
      const out = [];
      for (const row of rows.values()) {
        out.push({ ...row, parent: row.parent || null });
        if (row.children > 0 && !loaded.has(row.id))
          out.push({
            id: row.id + '/more',
            parent: row.id,
            label: '',
            more: true,
            hint: open.has(row.id) ? 'Loading ...' : fmt(row.count) + ' below',
            count: 0,
          });
      }
      return out;
    };
    const draw = () => {
      const selected = kg.api.getState().config.selected.filter((x) => rows.has(x));
      dataGrid.setSource(grid, records(), {
        idField: 'id',
        parentIdField: 'parent',
        cells: { label, count },
        query: { expanded: [...open], selected, filters },
        persist: { area: 'none' },
      });
    };
    // the rows below a branch (not the branch itself)
    const below = (id) => {
      const out = [];
      for (const rid of rows.keys())
        for (let p = rows.get(rid).parent; p; p = rows.get(p)?.parent)
          if (p === id) {
            out.push(rid);
            break;
          }
      return out;
    };
    const close = (id) => {
      open.delete(id);
      loaded.delete(id);
      for (const rid of below(id)) {
        rows.delete(rid);
        open.delete(rid);
        loaded.delete(rid);
      }
    };
    // open a branch: its open sibling closes, its children load
    async function expand(id) {
      const row = rows.get(id);
      if (!row) return;
      for (const other of [...open]) if (other !== id && rows.get(other)?.parent === row.parent) close(other);
      open.add(id);
      if (loaded.has(id) || !row.children) return;
      draw(); // the stand-in says Loading ... meanwhile
      const list = await ge.subtree(kg, id, 2);
      if (!open.has(id) || !rows.has(id)) return; // closed while it loaded
      for (const child of list) if (child.id !== id) rows.set(child.id, child);
      loaded.add(id);
    }
    // the branches above a node, the top first: the palette's hits know them, for a graph selection the worker answers
    const pathTo = async (id) => (await ge.path(kg, id)).slice(0, -1).map((step) => step.id);
    // show a node: every branch on its way opens (one per level, so the way replaces what was open), then it is selected
    // and scrolled to
    let revealing = 0;
    async function reveal(id, path) {
      const turn = ++revealing;
      for (const branch of path ?? (await pathTo(id))) {
        if (turn !== revealing) return;
        await expand(branch);
      }
      if (turn !== revealing || !rows.has(id)) return draw();
      follow = id;
      draw();
      dataGrid.query(grid, { selected: [id] });
      // the row into view: its place among the rows the open branches show
      const order = [];
      const walk = (pid) => {
        for (const r of rows.values())
          if ((r.parent || null) === pid) {
            order.push(r.id);
            if (open.has(r.id)) walk(r.id);
          }
      };
      walk(null);
      const k = order.indexOf(id);
      const viewport = df$(grid).find('.data-grid-viewport').get(0);
      const h = df$(grid).find('.data-grid-body .data-grid-row').get(0)?.offsetHeight || 28;
      const head = df$(grid).find('.data-grid-head').get(0)?.offsetHeight || 0;
      if (k >= 0 && viewport) {
        const top = k * h,
          view = viewport.clientHeight - head;
        if (top < viewport.scrollTop || top + h > viewport.scrollTop + view)
          viewport.scrollTop = Math.max(0, top - view / 2);
      }
    }

    // a store delivers a change after the code that made it returns, so a notice can arrive after a newer write -
    // only the store's current value counts (a stale selection once flew the graph back to the previous hit)
    grid.store.subscribe((state) => {
      if (state !== grid.store.get()) return;
      const { config } = state;
      const now = new Set((config.expanded || []).filter((id) => rows.has(id)));
      const opened = [...now].filter((id) => !open.has(id));
      const closed = [...open].filter((id) => !now.has(id));
      if (opened.length || closed.length) {
        revealing++; // the user's toggle wins over a reveal on its way
        for (const id of closed) close(id);
        void Promise.all(opened.map(expand)).then(draw);
        if (!opened.length) draw();
        return;
      }
      // a picked row: the graph flies there (a stand-in opens its branch)
      const picked = (config.selected || [])[0];
      if (picked && picked.endsWith('/more') && rows.has(picked.slice(0, -5))) {
        void expand(picked.slice(0, -5)).then(draw);
        return;
      }
      if (picked && rows.has(picked) && picked !== follow && kg.api.getState().config.selected[0] !== picked) {
        follow = picked;
        void ge.navigate(kg, picked);
      }
    });
    // the filter: the tree keeps the ancestors of every match in the open branches
    const filter = df$('[data-kg-tree-filter]');
    filter.on('input', () => {
      const q = String(filter.val() || '').trim();
      filters = q ? [{ field: 'label', op: 'contains', value: q }] : [];
      dataGrid.query(grid, { filters });
    });
    // the graph's selection shows in the tree: the way to it opens
    kg.store.subscribe((state) => {
      if (state !== kg.store.get()) return;
      const id = state.config.selected[0];
      if (!id || id === follow) return;
      follow = id;
      void reveal(id);
    });
    for (const row of await ge.subtree(kg, 'c0', 2)) rows.set(row.id, row);
    loaded.add('c0');
    open.add('c0');
    draw();

    // -- the palette: the worker scans the million names in chunks; its hits are Command items, so the palette's
    //    filter, keys and Enter work on them like on the actions
    const palette = df$('#kg-palette').get(0);
    const input = df$('[data-kg-find]');
    const hits = df$('[data-kg-hits]');
    const status = df$('[data-kg-find-status]');
    let asked = '';
    const write = (results, scanned) => {
      hits.find('.command-item').each((k, el) => {
        el.remove();
      });
      for (const r of results) {
        const item = df$(
          '<button class="command-item kg-hit-item" type="button"><span class="kg-hit"><span class="kg-hit-label"></span><span class="kg-hit-path"></span></span><span class="sr-only kg-hit-id"></span></button>',
        );
        item.attr('data-kg-hit', r.id).attr('data-kg-parents', JSON.stringify(r.parents));
        item.find('.kg-hit-label').text(r.label);
        item.find('.kg-hit-path').text(r.type + (r.path ? ' · ' + r.path : ''));
        item.find('.kg-hit-id').text(r.kind === 'entity' ? ' #' + r.id.slice(1) : '');
        hits.append(item);
      }
      status.text(
        !asked
          ? ''
          : scanned != null
            ? 'Scanning ... ' + fmt(scanned) + ' of ' + fmt(Number(kg.dataset.nodes) || 1000000)
            : results.length
              ? fmt(results.length) + (results.length === 1 ? ' node' : ' nodes')
              : '',
      );
      // let the palette filter and highlight what is there now (the hits hold the query, so they stay)
      input.get(0).dispatchEvent(new Event('input'));
    };
    input.on('input', () => {
      const q = String(input.val() || '').trim();
      if (q === asked) return;
      asked = q;
      if (!q) return write([], null);
      void ge
        .find(kg, q, (partial, scanned) => asked === q && write(partial, scanned))
        .then((results) => {
          if (asked === q) write(results, null);
        });
    });
    // a hit: the graph flies there, the tree opens the way to it
    hits.on('click', (event) => {
      const item = event.target.closest('[data-kg-hit]');
      if (!item) return;
      const id = item.dataset.kgHit;
      const parents = JSON.parse(item.dataset.kgParents || '[]').map((p) => p.id);
      follow = id;
      void ge.navigate(kg, id);
      void reveal(id, parents.includes('c0') ? parents : ['c0', ...parents]);
    });
    palette.addEventListener('close', () => {
      asked = '';
      write([], null);
    });
    df$('[data-kg-do]').on('click', (event) => {
      const what = event.currentTarget.dataset.kgDo;
      if (what === 'theme') df$('[data-kg-theme]').get(0).click();
      if (what === 'live') df$('#kg-app [data-graph-explorer-action="live"]').get(0).click();
    });

    // -- Back in the graph's header: the node or link selected before this one. Every selection that lands is a
    //    step - a click, the tree, the palette, a drill-down from a page's table to the next node; Back returns to the
    //    step before, on its page while a page is open (a drill-down walks back up), in the graph otherwise
    const backButton = df$('[data-kg-back]');
    const keyOf = ({ config }) =>
      config.selected.length === 1 ? 'n:' + config.selected[0] : config.edge ? 'e:' + config.edge : '';
    const steps = [];
    const names = new Map();
    let current = keyOf(kg.store.get());
    let returning = '';
    // a step's name for the button's title, from the worker (a link: both ends)
    const nameOf = (key) => {
      if (!names.has(key))
        names.set(
          key,
          Promise.all(
            key
              .slice(2)
              .split('>')
              .map((id) => ge.subtree(kg, id, 1)),
          ).then((rows) => rows.map((r) => r[0]?.label ?? '').join(' → ')),
        );
      return names.get(key);
    };
    // the title follows the language
    new MutationObserver(() => drawBack()).observe(df$('.kg').get(0), { attributes: true, attributeFilter: ['lang'] });
    const drawBack = () => {
      const to = steps.at(-1);
      const de = df$('.kg').attr('lang') === 'de';
      backButton.prop('disabled', !to);
      backButton.attr('title', de ? 'Zurück zur vorigen Auswahl' : 'Back to the previous selection');
      if (to)
        void nameOf(to).then((name) => {
          if (steps.at(-1) === to) backButton.attr('title', (de ? 'Zurück zu ' : 'Back to ') + name);
        });
    };
    // the selection the store holds now becomes the current step (the one before it goes on the stack). The store
    // delivers a notice after later commits - a click on Back can come first, so the click asks the store too
    const sync = () => {
      const key = keyOf(kg.store.get());
      // nothing selected is no step: the next selection still goes back to the last one
      if (!key || key === current) return;
      if (key === returning) returning = '';
      else if (current) {
        steps.push(current);
        if (steps.length > 50) steps.shift();
      }
      current = key;
    };
    kg.store.subscribe((state) => {
      if (state !== kg.store.get()) return;
      sync();
      drawBack();
    });
    backButton.on('click', () => {
      sync();
      const to = steps.pop();
      if (!to) return;
      returning = to;
      const id = to.slice(2);
      const { expanded } = kg.api.getState().config;
      if (to.startsWith('e:')) void kg.api.setState('selected', { selected: [], edge: id, expanded });
      else if (expanded) void kg.api.setState('selected', { selected: [id], edge: null, expanded: true });
      else void ge.navigate(kg, id);
      drawBack();
    });
  });
</script>
```

<h2 id="how-it-works" class="h2-display">How it works</h2>

<DocText>A page, not a component: it composes the library and keeps its own glue small - the plugins and two short scripts.</DocText>

<ul class="text-sm" style="display:grid;gap:0.5rem;max-width:46rem;padding-inline-start:1.25rem">
  <li><strong>Layout</strong> - a <DocLink href="border-layout.html">Border Layout</DocLink> whose regions are <DocLink href="panel.html">Panels</DocLink> in <DocLink href="resizer.html">Resizers</DocLink>: the toolbar north, a stack of two Panels west (the Hierarchy Explorer above, Updates below - drag the line between them, fold either), the graph in the center, the details east, the relations south (folded at first). Every Panel resizes, folds and maximizes.</li>
  <li><strong>The graph</strong> - one <DocLink href="graph-explorer.html">Graph Explorer</DocLink> of a million nodes; the toolbar, the layer switch, the details and the relations are its outlets (<code>data-graph-explorer-for="kg"</code>), the Panel titles show its outputs beside a translated label.</li>
  <li><strong>Layers</strong> - the switch in the graph's header shows or hides layers of information, each in its own colour: Nodes and Relations (shown at first), Labels, Health and the page's own Owners layer. Each is a filter - with none shown only the clusters' circles remain -, and a node shows a part for every layer, bordered and tinted in its colour. Compact draws every node as its one-line chip. See <DocLink href="graph-nodes.html">Node Renderers</DocLink>.</li>
  <li><strong>Live mode</strong> - the toolbar button starts the explorer's simulation: breakers trip and close, systems deploy, traffic moves, counts change. A changed node gets a glowing dot at its top right, a changed link lights up in its layer's colour, and each change becomes a row in Updates (a <DocLink href="virtual-list.html">Virtual List</DocLink>, newest first) - only the shown layers' changes; a row selects its node or link. A deploy names who shipped it: the page's own update renderer.</li>
  <li><strong>Hierarchy Explorer</strong> - a Tree Grid (the <DocLink href="data-grid.html">Data Grid</DocLink> with <code>data-parent-field</code>) over the same million nodes, to any depth: a branch's children load when it opens (<code>df$.shadcn.graphExplorer.subtree(kg, id, 2)</code> asks the explorer's worker). One branch per level is open - opening one closes its open sibling and lets go of what was loaded below it -, so the tree holds one path and its children. The filter narrows the open branches; a row selects its node in the graph, and the graph's selection opens the way to it (<code>graphExplorer.path(kg, id)</code>).</li>
  <li><strong>Search</strong> - the search field in the toolbar opens a <DocLink href="command.html">Command</DocLink> palette, also with <kbd class="kbd">⌘K</kbd> / <kbd class="kbd">Ctrl+K</kbd>: <code>graphExplorer.find(kg, query)</code> has the worker scan the million names in chunks and its hits become Command items, so the palette's filter, arrow keys and Enter work on them like on the actions below them. A hit flies the graph there and opens the way to it in the Hierarchy Explorer.</li>
  <li><strong>Drill-down</strong> - Expand (<kbd class="kbd">E</kbd>) maximizes the details Panel with the node's page; every name on a page opens the next page down - a domain's systems, a system's datasets, a dataset's lineage - and the path above the title goes back up. See <DocLink href="graph-details.html">Details & Pages</DocLink>.</li>
  <li><strong>Links</strong> - a click on a link (its label, its line, or the link button in a list) selects it: the details show its traffic both ways, its circuit breakers and who sends and receives most; Expand shows its page. See <DocLink href="graph-edges.html">Edge Rules & Labels</DocLink>.</li>
  <li><strong>Plugins</strong> - four detail renderers (API systems, domains, datasets, links between clusters) compose <DocLink href="chart.html">Chart</DocLink>, <DocLink href="geo-map.html">Geo Map</DocLink>, <DocLink href="avatar.html">Avatar</DocLink>, <DocLink href="timeline.html">Timeline</DocLink>, <DocLink href="progress.html">Progress</DocLink>, <DocLink href="table.html">Table</DocLink>, <DocLink href="badge.html">Badge</DocLink> and <DocLink href="statistic.html">Statistic</DocLink>; components with a script sit in islands (<code>ctx.island</code>), so a chart keeps its canvas while the details re-render. A dataset's row count joins the Labels layer; Owners is a layer of the page's own.</li>
  <li><strong>Routing</strong> - <a href="https://dom-router.defuss.org" target="_blank" rel="noopener">defuss-dom-router</a> in hash mode: <code>#/</code> is the graph, <code>#/node/:id</code> a node's page, <code>#/link/:from/:to</code> a link's page. The explorer's store moves the address as you drill down, so Back walks back up; a page can be linked. Inside the docs preview the same routes match the frame's hash. See <DocLink href="routing.html">Client-side Routing</DocLink>.</li>
  <li><strong>Back and Out</strong> - in the graph's header, before its title: Back returns to the node or link selected before (a click, a row of the Hierarchy Explorer, a palette hit and a drill-down from a page's table are steps; its title names the step, read from the worker), Out moves the view up a level. A cluster's button in the details says what it shows - "Show its 14 systems".</li>
  <li><strong>Translation</strong> - <a href="https://i18n.defuss.org" target="_blank" rel="noopener">defuss-i18n</a>: the language switch in the toolbar translates the brand, the buttons, the Panel labels and the tool labels between English and German; what the explorer and the plugins write stays as written. See <DocLink href="translation.html">Translation</DocLink>.</li>
  <li><strong>Full screen</strong> - <DocLink href="app-knowledge-graph.html">app-knowledge-graph.html</DocLink> is generated from this page's example at build time and loads only its own bundle.</li>
</ul>

</DocPage>
