---
title: "Database Explorer"
description: "Application scaffold: a MongoDB Compass / Robo 3T style database explorer on defuss-db 3.1.0 - databases and collections in a Data Tree, a Mongo-style query bar, every document an editable Property Tree, an editable Data Grid view, aggregations, a sampled schema, indexes, document history and restore, timestamps, query history and an operation log; kept in the browser's Origin Private File System."
slug: "scaffold-db-explorer"
---

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

<DocPage meta={meta}>

<PageHeader slug="scaffold-db-explorer" title="Database Explorer" introStyle="max-width:44rem;">
  A database tool as a working app, in the manner of MongoDB Compass and Robo 3T, over <a class="link" href="https://www.npmjs.com/package/defuss-db" target="_blank" rel="noopener">defuss-db 3.1.0</a>. The databases and their collections are a <DocLink href="data-tree.html">Data Tree</DocLink>; a collection opens with a <strong>query bar</strong> that reads MongoDB's filter language (<code>{"{ country: 'DE', amount: { $gt: 500 } }"}</code>), and every document it finds is an editable <DocLink href="property-tree.html">Property Tree</DocLink> - or a row of an editable <DocLink href="data-grid.html">Data Grid</DocLink>. Aggregations, a sampled schema, indexes, the query history and a log of every operation sit around it. Full screen, the data lives in this browser's Origin Private File System and is still there next time. 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-db-explorer.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="Database explorer" schema="none" mode="desktop" sandbox="downloads" hint="Pick a collection on the left (shop / orders is the big one), type a filter such as { status: 'shipped', amount: { $gt: 500 } } and press Find. Change a value in a document and Save it; switch to Table to edit cells in place. Ctrl+Space suggests fields, operators and values. Aggregations groups by text, dates and array elements and measures, Export / Import move a collection as JSON, NDJSON or CSV (gzip or Brotli), Schema samples the field types, Indexes creates and drops them - watch the query plan in the result line change. Here in the docs the database runs in memory; full screen it is kept in this browser (OPFS)." previewStyle="align-items:stretch;padding:0;"
<style>
  /* Strata: the scaffold's own glue. Every control is a shipped component (Border Layout, Panel, Resizer, Data Tree,
     Property Tree, Data Grid, Tabs, Button Group, Toggle Group, Input, Select, Textarea, Switch, Label, Badge, Table,
     Progress, Alert, Dialog, Alert Dialog, Toast, Swap, Language Switcher, Spinner) */
  .dx {
    position: relative;
    block-size: var(--scaffold-height, 50rem);
    font-size: 0.875rem;
  }
  .dx [hidden] {
    display: none !important;
  }
  .dx-bar {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 0.75rem;
    border-bottom: 1px solid var(--border);
  }
  .dx-brand {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-weight: 600;
    & small {
      color: var(--muted-foreground);
      font-weight: 400;
    }
  }
  .dx-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);
  }
  .dx-mark svg,
  .dx-ico svg {
    inline-size: 1rem;
    block-size: 1rem;
  }
  .dx-ico {
    display: inline-grid;
    place-items: center;
    color: var(--muted-foreground);
  }
  .dx-mono,
  .dx code,
  .dx-json {
    font-family: var(--font-mono);
    font-size: 0.8125rem;
  }
  .dx-nav {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    padding: 0.5rem;
    block-size: 100%;
    & .data-tree {
      flex: 1;
      min-block-size: 0;
    }
  }
  .data-tree-label:has(> .dx-node) {
    flex: 1;
  }
  .dx-node {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 0.375rem;
    min-inline-size: 0;
    & > span:nth-child(2) {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    & small {
      color: var(--muted-foreground);
      font-variant-numeric: tabular-nums;
    }
  }
  /* a row's button lies over the end of its row (over the count) - hidden, it takes no room from the name */
  .data-tree-item:has(.dx-node-act) {
    position: relative;
  }
  .dx-node-act.btn {
    position: absolute;
    inset-inline-end: 0.375rem;
    inset-block: 0;
    margin-block: auto;
    block-size: 1.375rem;
    opacity: 0;
    background: var(--accent);
    & svg {
      inline-size: 0.875rem;
      block-size: 0.875rem;
    }
    &[data-size='xs'] {
      gap: 0.125rem;
      padding-inline: 0.375rem;
    }
  }
  .data-tree-item[aria-selected='true'] .dx-node-act.btn {
    background: color-mix(in oklch, var(--primary) 14%, var(--card));
  }
  .data-tree-item:is(:hover, [aria-selected='true']) .dx-node-act,
  .data-tree:focus-visible .data-tree-item[data-active] .dx-node-act,
  .dx-node-act:focus-visible {
    opacity: 1;
  }
  /* the count gives way to the + while it shows (the button is narrower than a count such as 12,000) */
  .data-tree-item:is(:hover, [aria-selected='true']):has(.dx-node-act) small,
  .data-tree:focus-visible .data-tree-item[data-active]:has(.dx-node-act) small,
  .data-tree-item:has(.dx-node-act:focus-visible) small {
    visibility: hidden;
  }
  @media (hover: none) {
    .dx-node-act.btn {
      opacity: 1;
    }
  }
  .dx-main {
    display: flex;
    flex-direction: column;
    min-block-size: 0;
    block-size: 100%;
    overflow: auto;
    padding: 0.75rem;
    gap: 0.75rem;
  }
  .dx-crumbs {
    display: flex;
    align-items: center;
    gap: 0.375rem;
    min-inline-size: 0;
    & a {
      color: inherit;
    }
  }
  /* a narrow query bar: a row of several fields becomes label | field pairs, its buttons at the end */
  @container dx-query (inline-size < 44rem) {
    .dx-q-row:has(> .dx-q-label ~ .dx-q-label) {
      display: grid;
      grid-template-columns: auto minmax(0, 1fr);
      & > .select {
        justify-self: start;
      }
      & > .btn {
        grid-column: 1 / -1;
        justify-self: end;
      }
      & > .flex-1 {
        display: none;
      }
    }
  }
  .dx-query {
    container: dx-query / inline-size;
    display: grid;
    gap: 0.5rem;
  }
  .dx-q-row {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 0.5rem;
    & .input {
      flex: 1 1 12rem;
      min-inline-size: 0;
    }
    & .select {
      inline-size: auto;
    }
  }
  .dx-q-label {
    flex: none;
    min-inline-size: 4.25rem;
    white-space: nowrap;
    color: var(--muted-foreground);
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.04em;
  }
  /* the suggestions: one list under the field being typed in (anchored to it), opened at the word */
  .dx-ac {
    position: fixed;
    position-anchor: --dx-ac;
    inset: auto;
    top: anchor(bottom);
    left: anchor(left);
    position-try-fallbacks: flip-block;
    translate: var(--dx-ac-x, 0) 0;
    margin: 2px 0 0;
    padding: 0.25rem;
    min-inline-size: 14rem;
    max-inline-size: min(28rem, 90vw);
    max-block-size: 16rem;
    overflow: auto;
    overscroll-behavior: contain;
    border: 1px solid var(--border);
    border-radius: var(--radius-md);
    background: var(--popover);
    color: var(--popover-foreground);
    box-shadow: var(--shadow-md);
  }
  .dx-ac-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.25rem 0.5rem;
    border-radius: var(--radius-sm);
    cursor: pointer;
    font-family: var(--font-mono);
    font-size: 0.8125rem;
    white-space: nowrap;
    &[aria-selected='true'] {
      background: var(--accent);
      color: var(--accent-foreground);
    }
    &:hover {
      background: var(--muted);
    }
  }
  .dx-ac-kind {
    flex: none;
    inline-size: 1.25rem;
    color: var(--muted-foreground);
    font-size: 0.6875rem;
    text-align: center;
  }
  .dx-ac-item[data-kind='operator'] .dx-ac-kind {
    color: var(--chart-2);
  }
  .dx-ac-item[data-kind='field'] .dx-ac-kind {
    color: var(--chart-1);
  }
  .dx-ac-label {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .dx-ac-detail {
    flex: none;
    max-inline-size: 14rem;
    overflow: hidden;
    text-overflow: ellipsis;
    color: var(--muted-foreground);
    font-family: var(--font-sans);
    font-size: 0.75rem;
  }
  .dx-syntax {
    margin: -0.25rem 0 0 4.75rem;
    color: var(--destructive);
    font-size: 0.75rem;
  }
  .dx-query .input[aria-invalid='true'] {
    border-color: var(--destructive);
  }
  .dx-help {
    inline-size: min(26rem, 92vw);
  }
  .dx-help-ops {
    display: grid;
    grid-template-columns: auto 1fr;
    gap: 0.25rem 0.75rem;
    margin: 0;
    font-size: 0.8125rem;
    & dd {
      margin: 0;
      color: var(--muted-foreground);
    }
  }
  .dx-help-keys {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 0.375rem;
    margin: 0.75rem 0 0;
    color: var(--muted-foreground);
    font-size: 0.75rem;
  }
  /* the aggregation builder: keys and measures side by side, a row per key / measure */
  .dx-agg-parts {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(18rem, 1fr));
    gap: 0.75rem;
  }
  .dx-agg-part {
    display: grid;
    align-content: start;
    justify-items: start;
    gap: 0.375rem;
    margin: 0;
    padding: 0.5rem 0.75rem 0.625rem;
    border: 1px solid var(--border);
    border-radius: var(--radius-md);
    min-inline-size: 0;
  }
  .dx-agg-legend {
    padding-inline: 0.25rem;
    color: var(--muted-foreground);
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.04em;
  }
  .dx-agg-list {
    display: grid;
    gap: 0.375rem;
    justify-self: stretch;
    margin: 0;
    padding: 0;
    list-style: none;
  }
  .dx-agg-row {
    display: flex;
    align-items: center;
    gap: 0.375rem;
    & .input {
      flex: 1 1 8rem;
      min-inline-size: 0;
    }
    & .select {
      inline-size: auto;
      flex: 0 1 11rem;
    }
  }
  .dx-values {
    display: inline-flex;
    flex-wrap: wrap;
    gap: 0.25rem;
  }
  .dx-none {
    color: var(--muted-foreground);
    font-style: italic;
  }
  /* the labels, legends and tabs lead with an icon */
  .dx-q-label,
  .dx-agg-legend {
    display: inline-flex;
    align-items: center;
    gap: 0.375rem;
  }
  .dx-q-label svg,
  .dx-agg-legend svg,
  .dx .tab-trigger svg,
  .dx-foot > svg {
    inline-size: 0.875rem;
    block-size: 0.875rem;
    flex: none;
  }
  .dx .tab-trigger {
    gap: 0.375rem;
  }
  /* the foot of a result: what is shown, the plan and the pages - kept in view while the list scrolls */
  .dx-foot {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 0.5rem;
    padding-block: 0.5rem 0;
    border-block-start: 1px solid var(--border);
    background: var(--card);
    color: var(--muted-foreground);
    font-size: 0.8125rem;
    font-variant-numeric: tabular-nums;
  }
  .dx-json-view {
    display: grid;
    flex: 1 1 0;
    min-block-size: 0;
    grid-template-rows: auto minmax(0, 1fr);
    border: 1px solid var(--border);
    border-radius: var(--radius-md);
    overflow: hidden;
    & .dx-json {
      border: 0;
      border-radius: 0;
      max-block-size: none;
    }
  }
  .dx-json-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0.5rem;
    padding: 0.25rem 0.25rem 0.25rem 0.75rem;
    border-block-end: 1px solid var(--border);
    background: var(--card);
    color: var(--muted-foreground);
    font-size: 0.75rem;
  }
  /* token colours (the theme has no syntax tokens): literal, readable on --muted in both modes */
  .dx-t-key {
    color: light-dark(oklch(0.45 0.15 260), oklch(0.78 0.11 250));
  }
  .dx-t-str {
    color: light-dark(oklch(0.48 0.13 150), oklch(0.8 0.13 150));
  }
  .dx-t-num {
    color: light-dark(oklch(0.5 0.15 50), oklch(0.8 0.12 60));
  }
  .dx-t-lit {
    color: light-dark(oklch(0.48 0.17 330), oklch(0.78 0.13 330));
  }
  .dx-t-fn {
    color: light-dark(oklch(0.45 0.16 290), oklch(0.78 0.12 290));
  }
  @media (forced-colors: active) {
    .dx-t-key,
    .dx-t-str,
    .dx-t-num,
    .dx-t-lit,
    .dx-t-fn {
      color: CanvasText;
    }
    /* forced colours paint the field's own text: the twin under it would double it */
    .dx-code .dx-code-paint {
      visibility: hidden;
    }
  }
  /* Indexes: the form, then the list - or, without one, the empty state in the middle of what is left */
  .dx [data-dx-view='coll']:not([hidden]),
  #dx-p-idx:not([hidden]),
  #dx-p-agg:not([hidden]) {
    display: flex;
    flex-direction: column;
    flex: 1 0 auto;
  }
  #dx-p-idx:not([hidden]),
  #dx-p-agg:not([hidden]) {
    gap: 0.75rem;
  }
  /* Documents: the query bar and the foot stay, the records scroll in their own box between them (all three
     views: the List scrolls the box, the Table and the JSON fill it and scroll themselves) */
  .dx [data-dx-view='coll']:not([hidden]):has(> #dx-p-docs:not([hidden])) {
    flex: 1 1 0;
    min-block-size: 0;
  }
  #dx-p-docs:not([hidden]) {
    display: flex;
    flex-direction: column;
    flex: 1 1 0;
    gap: 0.75rem;
    min-block-size: 0;
  }
  #dx-p-docs [data-dx-results] {
    flex: 1 1 0;
    min-block-size: 14rem;
    overflow: auto;
    overscroll-behavior: contain;
    /* a batch put in above keeps the reader's place by script, in every browser */
    overflow-anchor: none;
  }
  #dx-p-docs [data-dx-results]:has(> .dx-grid-host, > .dx-json-view) {
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  .dx-idx-empty:not([hidden]) {
    display: grid;
    flex: 1;
    place-items: center;
  }
  .dx-import-sample {
    margin: 0.375rem 0 0;
    max-block-size: 7rem;
    overflow: auto;
    white-space: pre;
    font-size: 0.75rem;
  }
  /* the Schema tab's As of: as wide as a date and time, beside the view switch */
  .dx-schema-at {
    inline-size: 14rem;
    flex: none;
  }
  .dx-results-bar {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 0.5rem;
    color: var(--muted-foreground);
    font-variant-numeric: tabular-nums;
  }
  .dx-docs {
    display: grid;
    gap: 0.375rem;
    container: dx-docs / inline-size;
  }
  @container dx-docs (inline-size < 56rem) {
    .dx-doc-head .dx-act-label {
      position: absolute;
      inline-size: 1px;
      block-size: 1px;
      overflow: hidden;
      clip-path: inset(50%);
      white-space: nowrap;
    }
  }
  /* a document is one row (its id and a preview of its fields) until it is opened - a native <details> */
  .dx-doc {
    display: block;
    /* a long list lays out and paints only the cards near the view (VERIFIED tmp/probe-dx-list.ts: a batch's long
       task 63-95 ms, growing with the list, gone with it); a folded card is 38px, an opened one keeps its last size */
    content-visibility: auto;
    contain-intrinsic-block-size: auto 38px;
    padding: 0;
    overflow: hidden;
    &[data-dirty] {
      border-color: var(--ring);
    }
    &[open] .dx-doc-head {
      border-bottom: 1px solid var(--border);
      background: var(--muted);
      &::before {
        rotate: 135deg;
      }
    }
  }
  .dx-doc-head {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.25rem 0.5rem 0.25rem 0.625rem;
    cursor: pointer;
    list-style: none;
    &::-webkit-details-marker {
      display: none;
    }
    /* the disclosure chevron: turns down when the row opens */
    &::before {
      content: '';
      flex: none;
      inline-size: 0.4rem;
      block-size: 0.4rem;
      margin-inline-end: 0.125rem;
      border-block-start: 1.5px solid currentColor;
      border-inline-end: 1.5px solid currentColor;
      rotate: 45deg;
      transition: rotate 0.15s;
      color: var(--muted-foreground);
    }
    &:hover {
      background: var(--muted);
    }
    &:focus-visible {
      outline: 2px solid var(--ring);
      outline-offset: -2px;
    }
    & .dx-doc-id {
      flex: none;
      max-inline-size: 40%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    & .dx-doc-preview {
      flex: 1;
      min-inline-size: 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      color: var(--muted-foreground);
      font-family: var(--font-mono);
      font-size: 0.75rem;
    }
  }
  @media (prefers-reduced-motion: reduce) {
    .dx-doc-head::before {
      transition: none;
    }
  }
  /* a badge with an icon (a collection's History / Timestamps): the Badge sets no gap of its own */
  .dx .badge:has(> svg) {
    gap: 0.25rem;
  }
  .dx-revs {
    padding: 0.5rem 0.75rem 0.25rem;
    border-block-start: 1px solid var(--border);
  }
  .dx-rev {
    display: grid;
    gap: 0.125rem;
    margin: -0.25rem -0.375rem;
    padding: 0.25rem 0.375rem;
    border: 0;
    border-radius: var(--radius-sm);
    background: none;
    color: inherit;
    font: inherit;
    text-align: inherit;
    cursor: pointer;
    &:hover:not(:disabled) {
      background: var(--accent);
      color: var(--accent-foreground);
    }
    &:focus-visible {
      outline: 2px solid var(--ring);
      outline-offset: 1px;
    }
    &:disabled {
      cursor: default;
    }
    &[aria-pressed='true'] .timeline-title {
      color: var(--primary);
      font-weight: 600;
    }
  }
  /* the insert dialog's JSON: a transparent textarea over its painted twin - the textarea stays the field (caret,
     selection, undo, the form), the paint under it shows the same text coloured like the JSON view */
  .dx-code {
    position: relative;
    & textarea,
    & .dx-code-paint {
      box-sizing: border-box;
      margin: 0;
      padding: 0.5rem 0.75rem;
      border: 1px solid transparent;
      font-family: var(--font-mono);
      font-size: 0.8125rem;
      line-height: 1.5;
      white-space: pre-wrap;
      overflow-wrap: anywhere;
      tab-size: 2;
      scrollbar-gutter: stable;
    }
    & textarea {
      display: block;
      min-block-size: 16rem;
      max-block-size: 60dvh;
      overflow: auto;
      color: transparent;
      caret-color: var(--foreground);
      background: var(--background);
      border-color: var(--input);
    }
    & textarea::selection {
      color: transparent;
      background: color-mix(in oklch, var(--primary) 30%, transparent);
    }
    & .dx-code-paint {
      position: absolute;
      inset: 0;
      z-index: 1;
      overflow: hidden;
      pointer-events: none;
      color: var(--foreground);
      background: transparent;
    }
  }
  .dx-ins-tabs .tab-panel {
    padding-block-start: 0.5rem;
  }
  .dx-ins-tree {
    --property-tree-row-height: 1.75rem;
    block-size: 16rem;
  }
  .dx-doc .property-tree {
    --property-tree-row-height: 1.75rem;
    border: 0;
    border-radius: 0;
  }
  .dx-json {
    margin: 0;
    padding: 0.75rem;
    border: 1px solid var(--border);
    border-radius: var(--radius-md);
    background: var(--muted);
    overflow: auto;
    max-block-size: 32rem;
    white-space: pre;
  }
  /* the Table and JSON views fill the records' box */
  .dx-grid-host {
    flex: 1 1 0;
    min-block-size: 0;
  }
  .dx-grid-host .data-grid,
  .dx-json-lines {
    block-size: 100%;
  }
  /* Virtual List reads its row height once, in px */
  .dx-json-lines {
    --virtual-list-row-height: 20px;
    padding: 0;
    border: 0;
    border-radius: 0;
    background: transparent;
    & .virtual-list-row {
      display: block;
      padding-inline: 0.75rem;
      border: 0;
      font: inherit;
      line-height: 20px;
      white-space: pre;
    }
  }
  .dx-bars {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    & .progress {
      flex: 1;
      min-inline-size: 4rem;
    }
  }
  .dx-history {
    display: grid;
    gap: 0.25rem;
    margin: 0;
    padding: 0.375rem;
    list-style: none;
  }
  .dx-history-item {
    display: grid;
    grid-template-columns: 1fr auto;
    gap: 0.25rem 0.5rem;
    align-items: center;
    padding: 0.375rem 0.5rem;
    border-radius: var(--radius-md);
    &:hover {
      background: var(--accent);
    }
    & button.dx-run {
      all: unset;
      cursor: pointer;
      min-inline-size: 0;
      font-family: var(--font-mono);
      font-size: 0.75rem;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    & button.dx-run:focus-visible {
      outline: 2px solid var(--ring);
    }
    & small {
      grid-column: 1 / -1;
      color: var(--muted-foreground);
    }
  }
  .dx-log {
    margin: 0;
    padding: 0.25rem 0.5rem;
    list-style: none;
    font-size: 0.75rem;
    & li {
      display: grid;
      grid-template-columns: 5.5rem 6.5rem 1fr auto;
      gap: 0.5rem;
      padding-block: 0.125rem;
      border-bottom: 1px solid var(--border);
    }
    & time,
    & .dx-ms {
      color: var(--muted-foreground);
      font-variant-numeric: tabular-nums;
    }
    & [data-failed] {
      color: var(--destructive);
    }
  }
  .dx-empty {
    display: grid;
    gap: 0.75rem;
    max-inline-size: 48rem;
    & > :is(h2, p) {
      margin: 0;
    }
  }
  .dx-cards {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr));
    gap: 0.75rem;
  }
  .dx-db-card {
    text-decoration: none;
    color: inherit;
    &:hover {
      border-color: var(--ring);
    }
  }
  .dx-form {
    display: grid;
    gap: 0.75rem;
    & .field {
      display: grid;
      gap: 0.375rem;
    }
  }
  .dx-opt-field {
    display: grid;
    grid-template-columns: auto 1fr;
    gap: 0.125rem 0.5rem;
    align-items: center;
    & .dx-hint {
      grid-column: 2;
    }
  }
  .dx-zone {
    inline-size: 11rem;
  }
  .dx-history-dialog {
    inline-size: min(52rem, calc(100vw - 2rem));
  }
  .dx-versions {
    display: grid;
    grid-template-columns: minmax(14rem, 18rem) minmax(0, 1fr);
    gap: 0.75rem;
    min-block-size: 16rem;
    max-block-size: 60dvh;
    @media (width < 40rem) {
      grid-template-columns: minmax(0, 1fr);
    }
  }
  .dx-version-list {
    list-style: none;
    margin: 0;
    padding: 0;
    overflow: auto;
    display: grid;
    align-content: start;
    gap: 0.125rem;
    & .dx-version {
      inline-size: 100%;
      justify-content: flex-start;
      gap: 0.5rem;
      &[aria-pressed='true'] {
        background: var(--accent);
        color: var(--accent-foreground);
      }
    }
    & small {
      margin-inline-start: auto;
      color: var(--muted-foreground);
    }
  }
  .dx-version-json {
    margin: 0;
    overflow: auto;
  }
  .dx-hint {
    color: var(--muted-foreground);
    font-size: 0.75rem;
  }
</style>
<div class="dx" data-dx data-i18n-component aria-busy="true">
  <div class="border-layout" id="dx-app" data-frame="none" data-center-min="420" style="block-size: 100%">
    <header class="border-layout-north dx-bar">
      <span class="dx-brand"
        ><span class="dx-mark" aria-hidden="true"
          ><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
            <ellipse cx="12" cy="5" rx="8" ry="3" />
            <path d="M4 5v14c0 1.7 3.6 3 8 3s8-1.3 8-3V5M4 12c0 1.7 3.6 3 8 3s8-1.3 8-3" /></svg></span
        ><span data-i18n-target="dx-brand">Database Explorer</span></span
      >
      <div class="separator" data-orientation="vertical" role="separator"></div>
      <div class="flex-1"></div>
      <div
        class="btn-group"
        role="group"
        aria-label="Archive"
        data-i18n-aria-label-en="Archive"
        data-i18n-aria-label-de="Archiv"
      >
        <button class="btn" data-variant="ghost" data-size="sm" type="button" data-dx-action="import">
          <i data-lucide="upload"></i><span data-i18n-target="dx-import">Import</span>
        </button>
        <button class="btn" data-variant="ghost" data-size="sm" type="button" data-dx-action="export">
          <i data-lucide="download"></i><span data-i18n-target="dx-export">Export</span>
        </button>
      </div>
      <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>
      <label class="swap" data-variant="rotate" data-size="sm">
        <input
          type="checkbox"
          data-dx-dark
          aria-label="Dark mode"
          data-i18n-aria-label-en="Dark mode"
          data-i18n-aria-label-de="Dunkelmodus"
        />
        <span class="swap-on" aria-hidden="true"
          ><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" /></svg
        ></span>
        <span class="swap-off" aria-hidden="true"
          ><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="4" />
            <path
              d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"
            /></svg
        ></span>
      </label>
      <div class="separator" data-orientation="vertical" role="separator"></div>
      <span class="badge" data-variant="outline" data-dx-mode title="">…</span>
      <span class="badge" data-variant="secondary" data-dx-revision hidden></span>
    </header>

    <div class="resizer border-layout-west" data-min="200" data-max="460">
      <section
        class="card panel"
        id="dx-nav-panel"
        style="inline-size: 16rem; block-size: 100%"
        aria-labelledby="dx-nav-title"
        data-density="compact"
      >
        <header class="panel-header">
          <i data-lucide="database" class="panel-icon" aria-hidden="true"></i>
          <h3 class="panel-title" id="dx-nav-title"><span data-i18n-target="dx-t-databases">Databases</span></h3>
          <div class="panel-tools">
            <button
              class="btn"
              data-variant="ghost"
              data-size="icon-sm"
              type="button"
              data-dx-action="new-db"
              aria-label="New database"
              data-i18n-aria-label-en="New database"
              data-i18n-aria-label-de="Neue Datenbank"
            >
              <i data-lucide="plus"></i>
            </button>
            <button
              class="btn"
              data-variant="ghost"
              data-size="icon-sm"
              type="button"
              data-dx-action="refresh"
              aria-label="Refresh"
              title="Refresh"
              data-i18n-aria-label-en="Refresh"
              data-i18n-aria-label-de="Aktualisieren"
              data-i18n-title-en="Refresh"
              data-i18n-title-de="Aktualisieren"
            >
              <i data-lucide="refresh-cw"></i>
            </button>
            <label class="swap panel-minimize">
              <input
                type="checkbox"
                aria-label="Minimize Databases"
                data-i18n-aria-label-en="Minimize Databases"
                data-i18n-aria-label-de="Datenbanken 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>
          <div class="dx-nav">
            <input
              class="input"
              data-size="sm"
              type="search"
              data-tree-filter="dx-tree"
              placeholder="Find a collection…"
              aria-label="Find a collection"
              data-i18n-placeholder-en="Find a collection…"
              data-i18n-placeholder-de="Collection finden…"
              data-i18n-aria-label-en="Find a collection"
              data-i18n-aria-label-de="Collection finden"
            />
            <div
              class="data-tree"
              id="dx-tree"
              aria-label="Databases and collections"
              data-i18n-aria-label-en="Databases and collections"
              data-i18n-aria-label-de="Datenbanken und Collections"
              data-label-field="label"
              data-persist="none"
              data-density="compact"
            ></div>
          </div>
        </div>
      </section>
    </div>

    <section class="card panel border-layout-center" id="dx-center" aria-labelledby="dx-center-title">
      <header class="panel-header">
        <i data-lucide="braces" class="panel-icon" aria-hidden="true"></i>
        <h3 class="panel-title dx-crumbs" id="dx-center-title" data-dx-crumbs>Databases</h3>
        <div class="panel-tools">
          <span class="badge" data-variant="secondary" data-dx-opt="history" hidden
            ><i data-lucide="history"></i><span data-i18n-target="dx-opt-history">History</span></span
          >
          <span class="badge" data-variant="secondary" data-dx-opt="timestamps" hidden
            ><i data-lucide="clock"></i><span data-i18n-target="dx-opt-timestamps">Timestamps</span></span
          >
          <button class="btn" data-variant="outline" data-size="xs" type="button" data-dx-action="restore" hidden>
            <i data-lucide="archive-restore"></i><span data-i18n-target="dx-restore">Restore</span>
          </button>
          <button class="btn" data-variant="ghost" data-size="xs" type="button" data-dx-action="enable-history" hidden>
            <i data-lucide="history"></i><span data-i18n-target="dx-enable-history">Track history</span>
          </button>
          <button
            class="btn"
            data-variant="ghost"
            data-size="xs"
            type="button"
            data-dx-action="enable-timestamps"
            hidden
          >
            <i data-lucide="clock"></i><span data-i18n-target="dx-enable-timestamps">Add timestamps</span>
          </button>
          <button class="btn" data-variant="destructive" data-size="xs" type="button" data-dx-action="drop-db" hidden>
            <i data-lucide="trash-2"></i><span data-i18n-target="dx-drop-db">Drop database</span>
          </button>
          <button class="btn" data-variant="destructive" data-size="xs" type="button" data-dx-action="drop-coll" hidden>
            <i data-lucide="trash-2"></i><span data-i18n-target="dx-drop-coll">Drop collection</span>
          </button>
        </div>
      </header>
      <div class="panel-body" data-flush>
        <div class="dx-main">
          <!-- overview: every database -->
          <div class="dx-empty" data-dx-view="home">
            <h2 class="h3" data-i18n-target="dx-home-title">Databases in this browser</h2>
            <p class="dx-hint" data-dx-home-hint></p>
            <div class="dx-cards" data-dx-home-cards></div>
          </div>

          <!-- a database: its collections -->
          <div class="dx-empty" data-dx-view="db" hidden>
            <div class="table-container">
              <table class="table" data-size="sm">
                <thead class="table-header">
                  <tr class="table-row">
                    <th class="table-head" data-i18n-target="dx-th-collection">Collection</th>
                    <th class="table-head" style="text-align: right" data-i18n-target="dx-th-documents">Documents</th>
                    <th class="table-head" style="text-align: right" data-i18n-target="dx-th-indexes">Indexes</th>
                  </tr>
                </thead>
                <tbody class="table-body" data-dx-db-rows></tbody>
              </table>
            </div>
          </div>

          <!-- a collection -->
          <div class="tabs" data-dx-view="coll" hidden>
            <div
              class="tab-list"
              role="tablist"
              aria-label="Collection"
              data-i18n-aria-label-en="Collection"
              data-i18n-aria-label-de="Collection"
            >
              <button
                class="tab-trigger"
                role="tab"
                aria-selected="true"
                aria-controls="dx-p-docs"
                id="dx-tab-docs"
                data-dx-tab="docs"
              >
                <i data-lucide="files"></i><span data-i18n-target="dx-tab-docs">Documents</span>
              </button>
              <button
                class="tab-trigger"
                role="tab"
                aria-selected="false"
                aria-controls="dx-p-agg"
                id="dx-tab-agg"
                tabindex="-1"
                data-dx-tab="agg"
              >
                <i data-lucide="chart-column"></i><span data-i18n-target="dx-tab-agg">Aggregations</span>
              </button>
              <button
                class="tab-trigger"
                role="tab"
                aria-selected="false"
                aria-controls="dx-p-schema"
                id="dx-tab-schema"
                tabindex="-1"
                data-dx-tab="schema"
              >
                <i data-lucide="shapes"></i><span data-i18n-target="dx-tab-schema">Schema</span>
              </button>
              <button
                class="tab-trigger"
                role="tab"
                aria-selected="false"
                aria-controls="dx-p-idx"
                id="dx-tab-idx"
                tabindex="-1"
                data-dx-tab="idx"
              >
                <i data-lucide="key-round"></i><span data-i18n-target="dx-tab-idx">Indexes</span>
              </button>
            </div>

            <div class="tab-content" role="tabpanel" id="dx-p-docs" aria-labelledby="dx-tab-docs" tabindex="0">
              <form class="dx-query" data-dx-query autocomplete="off">
                <div class="dx-q-row">
                  <label class="dx-q-label" for="dx-filter"
                    ><i data-lucide="funnel"></i><span data-i18n-target="dx-l-filter">Filter</span></label
                  >
                  <input
                    class="input dx-mono"
                    id="dx-filter"
                    name="filter"
                    spellcheck="false"
                    placeholder="{ field: 'value' }"
                    data-size="sm"
                    data-dx-complete="filter"
                  />
                  <button class="btn" data-size="sm" type="submit"
                    ><i data-lucide="search"></i><span data-i18n-target="dx-find">Find</span></button
                  >
                  <button class="btn" data-variant="outline" data-size="sm" type="button" data-dx-reset>
                    <i data-lucide="rotate-ccw"></i><span data-i18n-target="dx-reset">Reset</span>
                  </button>
                  <button
                    class="btn"
                    data-variant="ghost"
                    data-size="icon-sm"
                    type="button"
                    popovertarget="dx-help"
                    aria-label="Query language"
                    data-i18n-aria-label-en="Query language"
                    data-i18n-aria-label-de="Abfragesprache"
                  >
                    <i data-lucide="circle-help"></i>
                  </button>
                </div>
                <div class="dx-q-row">
                  <label class="dx-q-label" for="dx-sort"
                    ><i data-lucide="arrow-up-down"></i><span data-i18n-target="dx-l-sort">Sort</span></label
                  >
                  <input
                    class="input dx-mono"
                    id="dx-sort"
                    name="sort"
                    spellcheck="false"
                    placeholder="{ field: -1 }"
                    data-size="sm"
                    data-dx-complete="sort"
                  />
                  <label class="dx-q-label" for="dx-project"
                    ><i data-lucide="columns-3"></i><span data-i18n-target="dx-l-project">Project</span></label
                  >
                  <input
                    class="input dx-mono"
                    id="dx-project"
                    name="project"
                    spellcheck="false"
                    placeholder="{ field: 1 }"
                    data-size="sm"
                    data-dx-complete="project"
                  />
                  <label class="dx-q-label" for="dx-limit"
                    ><i data-lucide="list-ordered"></i><span data-i18n-target="dx-l-limit">Limit</span></label
                  >
                  <select class="select" id="dx-limit" name="limit" data-size="sm">
                    <option>10</option>
                    <option selected>20</option>
                    <option>50</option>
                    <option>100</option>
                  </select>
                </div>
              </form>
              <p class="dx-syntax" data-dx-syntax hidden></p>
              <div class="dx-results-bar">
                <span class="flex-1"></span>
                <div
                  class="toggle-group"
                  role="group"
                  data-type="single"
                  aria-label="View"
                  data-i18n-aria-label-en="View"
                  data-i18n-aria-label-de="Ansicht"
                  data-dx-views
                >
                  <button class="toggle" data-size="sm" aria-pressed="true" value="list" type="button">
                    <i data-lucide="rows-3"></i><span data-i18n-target="dx-v-list">List</span>
                  </button>
                  <button class="toggle" data-size="sm" aria-pressed="false" value="table" type="button">
                    <i data-lucide="table"></i><span data-i18n-target="dx-v-table">Table</span>
                  </button>
                  <button class="toggle" data-size="sm" aria-pressed="false" value="json" type="button">
                    <i data-lucide="braces"></i><span data-i18n-target="dx-v-json">JSON</span>
                  </button>
                </div>
              </div>
              <div class="alert" data-variant="destructive" role="alert" data-dx-error hidden>
                <div class="alert-content"><p class="alert-description" data-dx-error-text></p></div>
              </div>
              <div data-dx-results></div>
              <div
                class="dx-foot"
                role="toolbar"
                aria-label="Results"
                data-i18n-aria-label-en="Results"
                data-i18n-aria-label-de="Ergebnisse"
              >
                <span data-dx-count></span>
                <span class="badge" data-variant="outline" data-dx-plan hidden></span>
                <span class="flex-1"></span>
                <div
                  class="btn-group"
                  role="group"
                  data-dx-pager
                  aria-label="Pages"
                  data-i18n-aria-label-en="Pages"
                  data-i18n-aria-label-de="Seiten"
                >
                  <button class="btn" data-variant="outline" data-size="sm" type="button" data-dx-page="-1">
                    <i data-lucide="chevron-left"></i><span data-i18n-target="dx-prev">Previous</span>
                  </button>
                  <button class="btn" data-variant="outline" data-size="sm" type="button" data-dx-page="1">
                    <span data-i18n-target="dx-next">Next</span><i data-lucide="chevron-right"></i>
                  </button>
                </div>
              </div>
            </div>

            <div class="tab-content" role="tabpanel" id="dx-p-agg" aria-labelledby="dx-tab-agg" tabindex="0" hidden>
              <form class="dx-query dx-agg" data-dx-agg autocomplete="off">
                <div class="dx-q-row">
                  <label class="dx-q-label" for="dx-agg-filter"
                    ><i data-lucide="funnel"></i><span data-i18n-target="dx-l-filter-2">Filter</span></label
                  >
                  <input
                    class="input dx-mono"
                    id="dx-agg-filter"
                    name="filter"
                    spellcheck="false"
                    placeholder="{ }"
                    data-size="sm"
                    data-dx-complete="filter"
                  />
                  <button class="btn" data-variant="outline" data-size="sm" type="button" data-dx-pipeline-open>
                    <i data-lucide="import"></i><span data-i18n-target="dx-pipeline-open">MongoDB pipeline</span>
                  </button>
                </div>
                <div class="dx-agg-parts">
                  <fieldset class="dx-agg-part">
                    <legend class="dx-agg-legend"
                      ><i data-lucide="group"></i><span data-i18n-target="dx-l-group">Group by</span></legend
                    >
                    <ol class="dx-agg-list" data-dx-keys></ol>
                    <button class="btn" data-variant="ghost" data-size="sm" type="button" data-dx-add-key>
                      <i data-lucide="plus"></i><span data-i18n-target="dx-add-key">Add a key</span>
                    </button>
                  </fieldset>
                  <fieldset class="dx-agg-part">
                    <legend class="dx-agg-legend"
                      ><i data-lucide="sigma"></i><span data-i18n-target="dx-l-measure">Measures</span></legend
                    >
                    <ol class="dx-agg-list" data-dx-measures></ol>
                    <button class="btn" data-variant="ghost" data-size="sm" type="button" data-dx-add-measure>
                      <i data-lucide="plus"></i><span data-i18n-target="dx-add-measure">Add a measure</span>
                    </button>
                  </fieldset>
                </div>
                <div class="dx-q-row">
                  <label class="dx-q-label" for="dx-agg-order"
                    ><i data-lucide="arrow-down-wide-narrow"></i><span data-i18n-target="dx-l-order">Order</span></label
                  >
                  <select class="select" id="dx-agg-order" name="order" data-size="sm">
                    <option value="measure" data-i18n-target="dx-o-by-measure">first measure, largest first</option>
                    <option value="key" data-i18n-target="dx-o-by-key">first key, ascending</option>
                  </select>
                  <label class="dx-q-label" for="dx-agg-limit"
                    ><i data-lucide="hash"></i><span data-i18n-target="dx-l-groups">Groups</span></label
                  >
                  <select class="select" id="dx-agg-limit" name="limit" data-size="sm">
                    <option>10</option>
                    <option selected>50</option>
                    <option>200</option>
                    <option>1000</option>
                  </select>
                  <label class="dx-q-label" for="dx-agg-zone"
                    ><i data-lucide="globe"></i><span data-i18n-target="dx-l-zone">Time zone</span></label
                  >
                  <input
                    class="input dx-mono dx-zone"
                    id="dx-agg-zone"
                    name="zone"
                    list="dx-zones"
                    value="UTC"
                    spellcheck="false"
                    autocomplete="off"
                    data-size="sm"
                  />
                  <datalist id="dx-zones"></datalist>
                  <span class="flex-1"></span>
                  <button class="btn" data-size="sm" type="submit"
                    ><i data-lucide="play"></i><span data-i18n-target="dx-run">Run</span></button
                  >
                </div>
              </form>
              <div data-dx-agg-result></div>
              <div class="dx-idx-empty" data-dx-agg-empty>
                <section class="mk-empty-state" aria-labelledby="dx-agg-empty-title">
                  <span class="mk-empty-state-icon" aria-hidden="true"><i data-lucide="chart-column"></i></span>
                  <h2 class="mk-empty-state-title" id="dx-agg-empty-title" data-i18n-target="dx-agg-empty-title"
                    >No aggregation run yet</h2
                  >
                  <p class="mk-empty-state-text" data-i18n-target="dx-agg-empty-text"
                    >Pick the keys to group by and what to measure, then Run - or paste a MongoDB pipeline.</p
                  >
                </section>
              </div>
            </div>

            <div
              class="tab-content"
              role="tabpanel"
              id="dx-p-schema"
              aria-labelledby="dx-tab-schema"
              tabindex="0"
              hidden
            >
              <div class="dx-results-bar">
                <div
                  class="toggle-group"
                  role="group"
                  data-type="single"
                  aria-label="Schema view"
                  data-i18n-aria-label-en="Schema view"
                  data-i18n-aria-label-de="Schema-Ansicht"
                  data-dx-schema-views
                >
                  <button class="toggle" data-size="sm" aria-pressed="true" value="fields" type="button">
                    <i data-lucide="list-tree"></i><span data-i18n-target="dx-sv-fields">Fields</span>
                  </button>
                  <button class="toggle" data-size="sm" aria-pressed="false" value="json" type="button">
                    <i data-lucide="braces"></i><span data-i18n-target="dx-sv-json">JSON Schema</span>
                  </button>
                </div>
                <span class="flex-1"></span>
                <label class="dx-q-label" for="dx-schema-at" data-dx-schema-at-label hidden
                  ><i data-lucide="history"></i><span data-i18n-target="dx-l-at">As of</span></label
                >
                <input
                  class="input dx-schema-at"
                  type="datetime-local"
                  step="1"
                  id="dx-schema-at"
                  data-size="sm"
                  data-dx-schema-at
                  hidden
                />
              </div>
              <div class="alert" data-variant="destructive" role="alert" data-dx-schema-error hidden>
                <div class="alert-content"><p class="alert-description" data-dx-schema-error-text></p></div>
              </div>
              <div data-dx-schema></div>
              <div class="dx-foot" role="status">
                <i data-lucide="info"></i><span class="dx-hint" data-dx-schema-hint></span>
              </div>
            </div>

            <div class="tab-content" role="tabpanel" id="dx-p-idx" aria-labelledby="dx-tab-idx" tabindex="0" hidden>
              <form class="dx-query" data-dx-index-form autocomplete="off">
                <div class="dx-q-row">
                  <label class="dx-q-label" for="dx-idx-name"
                    ><i data-lucide="tag"></i><span data-i18n-target="dx-l-name">Name</span></label
                  >
                  <input
                    class="input dx-mono"
                    id="dx-idx-name"
                    name="name"
                    required
                    pattern="[A-Za-z][A-Za-z0-9_\-]{0,63}"
                    placeholder="byStatus"
                    data-size="sm"
                  />
                  <label class="dx-q-label" for="dx-idx-fields"
                    ><i data-lucide="list"></i><span data-i18n-target="dx-l-fields">Fields</span></label
                  >
                  <input
                    class="input dx-mono"
                    id="dx-idx-fields"
                    name="fields"
                    required
                    placeholder="status, createdAt:-1"
                    data-size="sm"
                    data-dx-complete="field"
                  />
                  <div class="flex items-center gap-2">
                    <input class="switch" type="checkbox" role="switch" id="dx-idx-unique" name="unique" />
                    <label class="label" for="dx-idx-unique" data-i18n-target="dx-l-unique">Unique</label>
                  </div>
                  <button class="btn" data-size="sm" type="submit"
                    ><i data-lucide="plus"></i><span data-i18n-target="dx-create-index">Create index</span></button
                  >
                </div>
              </form>
              <div class="dx-indexes" data-dx-indexes></div>
              <div class="dx-idx-empty" data-dx-idx-empty hidden>
                <section class="mk-empty-state" aria-labelledby="dx-idx-empty-title">
                  <span class="mk-empty-state-icon" aria-hidden="true"><i data-lucide="key-round"></i></span>
                  <h2 class="mk-empty-state-title" id="dx-idx-empty-title" data-i18n-target="dx-idx-empty-title"
                    >No index yet</h2
                  >
                  <p class="mk-empty-state-text" data-i18n-target="dx-idx-empty-text"
                    >Every query scans the whole collection. Create an index above on the fields you filter or sort by,
                    and the query plan uses it.</p
                  >
                </section>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <div class="resizer border-layout-east" data-min="200" data-max="460">
      <section
        class="card panel"
        id="dx-history-panel"
        style="inline-size: 16rem; block-size: 100%"
        aria-labelledby="dx-history-title"
        data-density="compact"
        data-minimized
      >
        <header class="panel-header">
          <i data-lucide="history" class="panel-icon" aria-hidden="true"></i>
          <h3 class="panel-title" id="dx-history-title"><span data-i18n-target="dx-t-history">Query history</span></h3>
          <div class="panel-tools">
            <label class="swap panel-minimize">
              <input
                type="checkbox"
                aria-label="Minimize Query history"
                data-i18n-aria-label-en="Minimize Query history"
                data-i18n-aria-label-de="Abfrageverlauf 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>
          <ol class="dx-history" data-dx-history></ol>
        </div>
      </section>
    </div>

    <div class="resizer border-layout-south" data-min="72" data-max="360">
      <section
        class="card panel"
        id="dx-log-panel"
        style="block-size: 7.5rem"
        aria-labelledby="dx-log-title"
        data-density="compact"
        data-minimized
      >
        <header class="panel-header">
          <i data-lucide="activity" class="panel-icon" aria-hidden="true"></i>
          <h3 class="panel-title" id="dx-log-title"><span data-i18n-target="dx-t-log">Operations</span></h3>
          <div class="panel-tools">
            <button class="btn" data-variant="ghost" data-size="xs" type="button" data-dx-clear-log>
              <span data-i18n-target="dx-clear">Clear</span>
            </button>
            <label class="swap panel-minimize">
              <input
                type="checkbox"
                aria-label="Minimize Operations"
                data-i18n-aria-label-en="Minimize Operations"
                data-i18n-aria-label-de="Operationen 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>
          <ol class="dx-log" data-dx-log role="log" aria-live="off"></ol>
        </div>
      </section>
    </div>
  </div>

  <!-- new database: a name and its first collection (a database holds at least one) -->
  <dialog class="dialog" id="dx-db-dialog" role="dialog" aria-modal="true" aria-labelledby="dx-db-dialog-title">
    <form class="dialog-content dx-form" method="dialog" data-dx-db-form>
      <div class="dialog-header">
        <h2 class="dialog-title" id="dx-db-dialog-title" data-i18n-target="dx-db-dialog-title">New database</h2>
      </div>
      <div class="field">
        <label class="label" for="dx-db-name" data-i18n-target="dx-l-db-name">Database name</label>
        <input
          class="input dx-mono"
          id="dx-db-name"
          name="db"
          required
          pattern="[a-z][a-z0-9_\-]{0,63}"
          placeholder="inventory"
        />
        <p class="dx-hint" data-i18n-target="dx-db-name-hint"
          >Lowercase letters, digits, _ and -, starting with a letter.</p
        >
      </div>
      <div class="field">
        <label class="label" for="dx-db-coll" data-i18n-target="dx-l-first-coll">First collection</label>
        <input
          class="input dx-mono"
          id="dx-db-coll"
          name="coll"
          required
          pattern="[A-Za-z][A-Za-z0-9_\-]{0,63}"
          placeholder="items"
        />
      </div>
      <div class="dialog-footer">
        <button class="btn" data-variant="outline" type="button" data-dialog-close>
          <span data-i18n-target="dx-cancel">Cancel</span>
        </button>
        <button class="btn" type="submit" value="ok"><span data-i18n-target="dx-create">Create</span></button>
      </div>
    </form>
  </dialog>

  <!-- new collection in a database -->
  <dialog class="dialog" id="dx-coll-dialog" role="dialog" aria-modal="true" aria-labelledby="dx-coll-dialog-title">
    <form class="dialog-content dx-form" method="dialog" data-dx-coll-form>
      <div class="dialog-header">
        <h2 class="dialog-title" id="dx-coll-dialog-title" data-i18n-target="dx-coll-dialog-title">New collection</h2>
      </div>
      <div class="field">
        <label class="label" for="dx-coll-db" data-i18n-target="dx-l-database">Database</label>
        <select class="select" id="dx-coll-db" name="db" required></select>
      </div>
      <div class="field">
        <label class="label" for="dx-coll-name" data-i18n-target="dx-l-coll-name">Collection name</label>
        <input
          class="input dx-mono"
          id="dx-coll-name"
          name="coll"
          required
          pattern="[A-Za-z][A-Za-z0-9_\-]{0,63}"
          placeholder="reviews"
        />
      </div>
      <div class="dx-opt-field">
        <input class="switch" type="checkbox" role="switch" id="dx-coll-history" name="history" />
        <label class="label" for="dx-coll-history" data-i18n-target="dx-l-history">Track history</label>
        <span class="dx-hint" data-i18n-target="dx-l-history-hint"
          >Every version is kept: As of, a document's history, restore after a delete.</span
        >
      </div>
      <div class="dx-opt-field">
        <input class="switch" type="checkbox" role="switch" id="dx-coll-timestamps" name="timestamps" />
        <label class="label" for="dx-coll-timestamps" data-i18n-target="dx-l-timestamps">Timestamps</label>
        <span class="dx-hint" data-i18n-target="dx-l-timestamps-hint">Every write sets _createdAt and _updatedAt.</span>
      </div>
      <div class="dialog-footer">
        <button class="btn" data-variant="outline" type="button" data-dialog-close>
          <span data-i18n-target="dx-cancel-2">Cancel</span>
        </button>
        <button class="btn" type="submit" value="ok"><span data-i18n-target="dx-create-2">Create</span></button>
      </div>
    </form>
  </dialog>

  <!-- restore a deleted document (a collection that tracks history) -->
  <dialog class="dialog" id="dx-restore-dialog" role="dialog" aria-modal="true" aria-labelledby="dx-restore-title">
    <form class="dialog-content dx-form" method="dialog" data-dx-restore-form>
      <div class="dialog-header">
        <h2 class="dialog-title" id="dx-restore-title" data-i18n-target="dx-restore-title"
          >Restore a deleted document</h2
        >
        <p class="dialog-description" data-i18n-target="dx-restore-hint">
          The id of a document deleted from this collection: its last version comes back as a new version.
        </p>
      </div>
      <div class="field">
        <label class="label" for="dx-restore-id" data-i18n-target="dx-l-doc-id">Document id</label>
        <input class="input dx-mono" id="dx-restore-id" name="id" required spellcheck="false" autocomplete="off" />
      </div>
      <div class="dialog-footer">
        <button class="btn" data-variant="outline" type="button" data-dialog-close>
          <span data-i18n-target="dx-cancel-r">Cancel</span>
        </button>
        <button class="btn" type="submit" value="ok"><span data-i18n-target="dx-restore-ok">Restore</span></button>
      </div>
    </form>
  </dialog>

  <!-- a document's versions (a collection that tracks history), newest first -->
  <dialog
    class="dialog dx-history-dialog"
    id="dx-history-dialog"
    role="dialog"
    aria-modal="true"
    aria-labelledby="dx-versions-title"
  >
    <div class="dialog-content">
      <div class="dialog-header">
        <h2 class="dialog-title" id="dx-versions-title" data-dx-versions-title></h2>
        <p class="dialog-description" data-dx-versions-count></p>
      </div>
      <div class="dx-versions">
        <ol class="dx-version-list" data-dx-versions></ol>
        <pre class="dx-json dx-version-json" data-dx-version-json></pre>
      </div>
      <div class="dialog-footer">
        <button class="btn" data-variant="outline" type="button" data-dialog-close>
          <span data-i18n-target="dx-close-h">Close</span>
        </button>
        <button class="btn" type="button" data-dx-put-back>
          <span data-i18n-target="dx-put-back">Put back this version</span>
        </button>
      </div>
    </div>
  </dialog>

  <!-- insert a document: the shell's relaxed JSON (ISODate, NumberLong) -->
  <dialog
    class="dialog"
    id="dx-insert-dialog"
    role="dialog"
    aria-modal="true"
    aria-labelledby="dx-insert-title"
    style="max-inline-size: 40rem"
  >
    <form class="dialog-content dx-form" method="dialog" data-dx-insert-form>
      <div class="dialog-header">
        <h2 class="dialog-title" id="dx-insert-title" data-i18n-target="dx-insert-title">Insert document</h2>
        <p class="dialog-description" data-dx-insert-target></p>
      </div>
      <div class="tabs dx-ins-tabs">
        <div
          class="tab-list"
          role="tablist"
          aria-label="Editor"
          data-i18n-aria-label-en="Editor"
          data-i18n-aria-label-de="Editor"
        >
          <button
            class="tab-trigger"
            type="button"
            role="tab"
            aria-selected="true"
            aria-controls="dx-ins-p-json"
            id="dx-ins-t-json"
            data-dx-ins-mode="json"
          >
            <i data-lucide="braces"></i><span>JSON</span>
          </button>
          <button
            class="tab-trigger"
            type="button"
            role="tab"
            aria-selected="false"
            aria-controls="dx-ins-p-tree"
            id="dx-ins-t-tree"
            data-dx-ins-mode="tree"
          >
            <i data-lucide="list-tree"></i><span data-i18n-target="dx-ins-tree">Tree</span>
          </button>
        </div>
        <div class="tab-panel" role="tabpanel" id="dx-ins-p-json" aria-labelledby="dx-ins-t-json">
          <div class="dx-code">
            <pre class="dx-code-paint dx-mono" aria-hidden="true" data-dx-ins-paint></pre>
            <textarea class="textarea dx-mono" name="doc" rows="12" spellcheck="false" autocomplete="off" aria-label="Document" data-i18n-aria-label-en="Document" data-i18n-aria-label-de="Dokument"></textarea>
          </div>
        </div>
        <div class="tab-panel" role="tabpanel" id="dx-ins-p-tree" aria-labelledby="dx-ins-t-tree" hidden>
          <div
            class="property-tree dx-ins-tree"
            data-root-label="document"
            aria-label="Document"
            data-i18n-aria-label-en="Document"
            data-i18n-aria-label-de="Dokument"
            data-dx-ins-tree
          ></div>
        </div>
      </div>
      <p class="dx-hint" data-i18n-target="dx-insert-hint"
        >An array inserts several documents. Without an id, one is generated. Dates: ISODate("2026-11-21").</p
      >
      <div class="alert" data-variant="destructive" role="alert" data-dx-insert-error hidden>
        <div class="alert-content"><p class="alert-description" data-dx-insert-error-text></p></div>
      </div>
      <div class="dialog-footer">
        <button class="btn" data-variant="outline" type="button" data-dialog-close>
          <span data-i18n-target="dx-cancel-3">Cancel</span>
        </button>
        <button class="btn" type="submit" value="ok"><span data-i18n-target="dx-insert-ok">Insert</span></button>
      </div>
    </form>
  </dialog>

  <!-- export: a database archive, or a collection's documents as JSON / NDJSON / CSV, compressed -->
  <dialog class="dialog" id="dx-export-dialog" role="dialog" aria-modal="true" aria-labelledby="dx-export-title">
    <form class="dialog-content dx-form" method="dialog" data-dx-export-form>
      <div class="dialog-header">
        <h2 class="dialog-title" id="dx-export-title" data-i18n-target="dx-export-title">Export</h2>
        <p class="dialog-description" data-i18n-target="dx-export-desc"
          >A collection's documents as a file other tools read, or a whole database as an archive this app imports
          again.</p
        >
      </div>
      <fieldset class="radio-group" data-orientation="horizontal">
        <legend class="label" data-i18n-target="dx-l-what">What</legend>
        <div class="radio-item">
          <input class="radio" type="radio" name="what" id="dx-ex-coll" value="coll" checked />
          <label for="dx-ex-coll" data-i18n-target="dx-ex-coll">Documents of a collection</label>
        </div>
        <div class="radio-item">
          <input class="radio" type="radio" name="what" id="dx-ex-db" value="db" />
          <label for="dx-ex-db" data-i18n-target="dx-ex-db">Database archive</label>
        </div>
      </fieldset>
      <div class="field">
        <label class="label" for="dx-ex-source" data-i18n-target="dx-l-source">From</label>
        <select class="select dx-mono" id="dx-ex-source" name="source"></select>
      </div>
      <div class="dx-form" data-dx-ex-docs>
        <fieldset class="radio-group" data-orientation="horizontal">
          <legend class="label" data-i18n-target="dx-l-format">Format</legend>
          <div class="radio-item">
            <input class="radio" type="radio" name="format" id="dx-ex-json" value="json" />
            <label for="dx-ex-json">JSON</label>
          </div>
          <div class="radio-item">
            <input class="radio" type="radio" name="format" id="dx-ex-ndjson" value="ndjson" checked />
            <label for="dx-ex-ndjson">NDJSON</label>
          </div>
          <div class="radio-item">
            <input class="radio" type="radio" name="format" id="dx-ex-csv" value="csv" />
            <label for="dx-ex-csv">CSV</label>
          </div>
        </fieldset>
        <div class="field">
          <label class="label" for="dx-ex-compression" data-i18n-target="dx-l-compression">Compression</label>
          <select class="select" id="dx-ex-compression" name="compression">
            <option value="brotli" selected>Brotli (.br, defuss-brotli)</option>
            <option value="gzip">gzip (.gz)</option>
            <option value="none" data-i18n-target="dx-o-none">none</option>
          </select>
        </div>
        <div class="flex items-center gap-2" data-dx-ex-filter-row>
          <input class="checkbox" type="checkbox" id="dx-ex-filtered" name="filtered" />
          <label class="label" for="dx-ex-filtered" style="margin: 0" data-i18n-target="dx-ex-filtered"
            >Only the documents the query bar finds</label
          >
        </div>
      </div>
      <p class="dx-hint dx-mono" data-dx-ex-name></p>
      <div class="dialog-footer">
        <button class="btn" data-variant="outline" type="button" data-dialog-close>
          <span data-i18n-target="dx-cancel-6">Cancel</span>
        </button>
        <button class="btn" type="submit" value="ok"><span data-i18n-target="dx-export-ok">Export</span></button>
      </div>
    </form>
  </dialog>

  <!-- import: a database archive, or documents (JSON / NDJSON / CSV, plain, gzip or Brotli) into a collection -->
  <dialog class="dialog" id="dx-import-dialog" role="dialog" aria-modal="true" aria-labelledby="dx-import-title">
    <form class="dialog-content dx-form" method="dialog" data-dx-import-form>
      <div class="dialog-header">
        <h2 class="dialog-title" id="dx-import-title" data-i18n-target="dx-import-title">Import</h2>
        <p class="dialog-description" data-i18n-target="dx-import-desc"
          >A database archive from Export, or documents as JSON, NDJSON or CSV - also compressed with gzip or Brotli.</p
        >
      </div>
      <div class="field">
        <label class="label" for="dx-import-file" data-i18n-target="dx-l-file">File</label>
        <input
          class="file-input"
          id="dx-import-file"
          name="file"
          type="file"
          required
          accept=".br,.gz,.json,.ndjson,.jsonl,.csv"
        />
      </div>
      <div class="alert" data-dx-import-info hidden>
        <div class="alert-content">
          <p class="alert-title" data-dx-import-kind></p>
          <pre class="dx-import-sample dx-mono" data-dx-import-sample></pre>
        </div>
      </div>
      <div class="field">
        <label class="label" for="dx-import-db" data-i18n-target="dx-l-into">Into database</label>
        <input
          class="input dx-mono"
          id="dx-import-db"
          name="db"
          required
          pattern="[a-z][a-z0-9_\-]{0,63}"
          placeholder="restored"
          list="dx-dbs"
        />
        <datalist id="dx-dbs"></datalist>
      </div>
      <div class="field" data-dx-import-docs hidden>
        <label class="label" for="dx-import-coll" data-i18n-target="dx-l-into-coll">Into collection</label>
        <input class="input dx-mono" id="dx-import-coll" name="coll" pattern="[A-Za-z][A-Za-z0-9_\-]{0,63}" />
      </div>
      <fieldset class="radio-group" data-dx-import-docs hidden>
        <legend class="label" data-i18n-target="dx-l-known">A document whose id is already there</legend>
        <div class="radio-item">
          <input class="radio" type="radio" name="mode" id="dx-im-insert" value="insert" checked />
          <label for="dx-im-insert" data-i18n-target="dx-im-insert"
            >stops the import (nothing of that part is written)</label
          >
        </div>
        <div class="radio-item">
          <input class="radio" type="radio" name="mode" id="dx-im-upsert" value="upsert" />
          <label for="dx-im-upsert" data-i18n-target="dx-im-upsert">replaces the document</label>
        </div>
      </fieldset>
      <div class="dialog-footer">
        <button class="btn" data-variant="outline" type="button" data-dialog-close>
          <span data-i18n-target="dx-cancel-4">Cancel</span>
        </button>
        <button class="btn" type="submit" value="ok"><span data-i18n-target="dx-import-ok">Import</span></button>
      </div>
    </form>
  </dialog>

  <!-- a MongoDB pipeline becomes the aggregation builder's rows (runtime/db/pipeline.ts) -->
  <dialog class="dialog" id="dx-pipeline-dialog" role="dialog" aria-modal="true" aria-labelledby="dx-pipeline-title">
    <form class="dialog-content dx-form" method="dialog" data-dx-pipeline-form>
      <div class="dialog-header">
        <h2 class="dialog-title" id="dx-pipeline-title" data-i18n-target="dx-pipeline-title"
          >From a MongoDB pipeline</h2
        >
        <p class="dialog-description" data-i18n-target="dx-pipeline-desc"
          >Paste an aggregation pipeline: $match, $unwind, $group, $set with $size, $sort, $limit and $count become the
          filter, the keys and the measures defuss-db runs.</p
        >
      </div>
      <div class="field">
        <label class="label" for="dx-pipeline-text" data-i18n-target="dx-l-pipeline">Pipeline</label>
        <textarea
          class="textarea dx-mono"
          id="dx-pipeline-text"
          name="pipeline"
          rows="9"
          spellcheck="false"
          required
          placeholder="[
  { $match: { status: 'shipped' } },
  { $group: { _id: '$country', orders: { $sum: 1 }, revenue: { $sum: '$amount' } } },
  { $sort: { revenue: -1 } }
]"
        ></textarea>
      </div>
      <div class="alert" data-variant="destructive" role="alert" data-dx-pipeline-error hidden>
        <div class="alert-content"><p class="alert-description" data-dx-pipeline-error-text></p></div>
      </div>
      <div class="dialog-footer">
        <button class="btn" data-variant="outline" type="button" data-dialog-close>
          <span data-i18n-target="dx-cancel-7">Cancel</span>
        </button>
        <button class="btn" type="submit" value="ok"
          ><i data-lucide="play"></i><span data-i18n-target="dx-pipeline-ok">Convert and run</span></button
        >
      </div>
    </form>
  </dialog>

  <!-- the query language at a glance (the ? beside the filter) -->
  <div class="popover dx-help" id="dx-help" popover data-align="end">
    <div class="popover-header">
      <p class="popover-title" data-i18n-target="dx-help-title">Query language</p>
      <p class="popover-description" data-i18n-target="dx-help-intro"
        >MongoDB's filter documents, as the shell types them: unquoted keys, single quotes, ISODate('2026-01-31').</p
      >
    </div>
    <div class="popover-content">
      <dl class="dx-help-ops" data-dx-help-ops></dl>
      <p class="dx-help-keys">
        <kbd class="kbd-group"><kbd class="kbd">Ctrl</kbd><kbd class="kbd">Space</kbd></kbd>
        <span data-i18n-target="dx-help-k1">suggestions</span>
        <kbd class="kbd">Tab</kbd>
        <span data-i18n-target="dx-help-k2">takes one</span>
        <kbd class="kbd-group"><kbd class="kbd">Ctrl</kbd><kbd class="kbd">Enter</kbd></kbd>
        <span data-i18n-target="dx-help-k3">runs</span>
      </p>
    </div>
  </div>

  <!-- the suggestions of the field being typed in (one list, shown under that field) -->
  <div
    class="dx-ac"
    id="dx-ac"
    popover="manual"
    role="listbox"
    aria-label="Suggestions"
    data-i18n-aria-label-en="Suggestions"
    data-i18n-aria-label-de="Vorschläge"
  ></div>

  <!-- confirm what cannot be undone -->
  <dialog
    class="alert-dialog"
    id="dx-confirm"
    role="alertdialog"
    aria-modal="true"
    aria-labelledby="dx-confirm-title"
    aria-describedby="dx-confirm-text"
  >
    <div class="alert-dialog-content">
      <div class="alert-dialog-header">
        <h2 class="alert-dialog-title" id="dx-confirm-title" data-dx-confirm-title></h2>
        <p class="alert-dialog-description" id="dx-confirm-text" data-dx-confirm-text></p>
      </div>
      <div class="alert-dialog-footer">
        <button class="btn" data-variant="outline" data-alert-dialog-close>
          <span data-i18n-target="dx-cancel-5">Cancel</span>
        </button>
        <button class="btn" data-variant="destructive" data-alert-dialog-close data-dx-confirm-ok>
          <span data-i18n-target="dx-confirm-ok">Delete</span><span data-dx-confirm-alt hidden></span>
        </button>
      </div>
    </div>
  </dialog>

  <template data-i18n-for="dx-brand" data-i18n-locale="en">Database Explorer</template>
  <template data-i18n-for="dx-brand" data-i18n-locale="de">Datenbank-Explorer</template>
  <template data-i18n-for="dx-import" data-i18n-locale="en">Import</template>
  <template data-i18n-for="dx-import" data-i18n-locale="de">Importieren</template>
  <template data-i18n-for="dx-export" data-i18n-locale="en">Export</template>
  <template data-i18n-for="dx-export" data-i18n-locale="de">Exportieren</template>
  <template data-i18n-for="dx-t-databases" data-i18n-locale="en">Databases</template>
  <template data-i18n-for="dx-t-databases" data-i18n-locale="de">Datenbanken</template>
  <template data-i18n-for="dx-home-title" data-i18n-locale="en">Databases in this browser</template>
  <template data-i18n-for="dx-home-title" data-i18n-locale="de">Datenbanken in diesem Browser</template>
  <template data-i18n-for="dx-drop-db" data-i18n-locale="en">Drop database</template>
  <template data-i18n-for="dx-drop-db" data-i18n-locale="de">Datenbank löschen</template>
  <template data-i18n-for="dx-th-collection" data-i18n-locale="en">Collection</template>
  <template data-i18n-for="dx-th-collection" data-i18n-locale="de">Collection</template>
  <template data-i18n-for="dx-th-documents" data-i18n-locale="en">Documents</template>
  <template data-i18n-for="dx-th-documents" data-i18n-locale="de">Dokumente</template>
  <template data-i18n-for="dx-th-indexes" data-i18n-locale="en">Indexes</template>
  <template data-i18n-for="dx-th-indexes" data-i18n-locale="de">Indizes</template>
  <template data-i18n-for="dx-tab-docs" data-i18n-locale="en">Documents</template>
  <template data-i18n-for="dx-tab-docs" data-i18n-locale="de">Dokumente</template>
  <template data-i18n-for="dx-tab-agg" data-i18n-locale="en">Aggregations</template>
  <template data-i18n-for="dx-tab-agg" data-i18n-locale="de">Aggregationen</template>
  <template data-i18n-for="dx-tab-schema" data-i18n-locale="en">Schema</template>
  <template data-i18n-for="dx-tab-schema" data-i18n-locale="de">Schema</template>
  <template data-i18n-for="dx-tab-idx" data-i18n-locale="en">Indexes</template>
  <template data-i18n-for="dx-tab-idx" data-i18n-locale="de">Indizes</template>
  <template data-i18n-for="dx-l-filter" data-i18n-locale="en">Filter</template>
  <template data-i18n-for="dx-l-filter" data-i18n-locale="de">Filter</template>
  <template data-i18n-for="dx-l-filter-2" data-i18n-locale="en">Filter</template>
  <template data-i18n-for="dx-l-filter-2" data-i18n-locale="de">Filter</template>
  <template data-i18n-for="dx-find" data-i18n-locale="en">Find</template>
  <template data-i18n-for="dx-find" data-i18n-locale="de">Suchen</template>
  <template data-i18n-for="dx-reset" data-i18n-locale="en">Reset</template>
  <template data-i18n-for="dx-reset" data-i18n-locale="de">Zurücksetzen</template>
  <template data-i18n-for="dx-l-sort" data-i18n-locale="en">Sort</template>
  <template data-i18n-for="dx-l-sort" data-i18n-locale="de">Sortierung</template>
  <template data-i18n-for="dx-l-project" data-i18n-locale="en">Project</template>
  <template data-i18n-for="dx-l-project" data-i18n-locale="de">Felder</template>
  <template data-i18n-for="dx-l-limit" data-i18n-locale="en">Limit</template>
  <template data-i18n-for="dx-l-limit" data-i18n-locale="de">Anzahl</template>
  <template data-i18n-for="dx-v-list" data-i18n-locale="en">List</template>
  <template data-i18n-for="dx-v-list" data-i18n-locale="de">Liste</template>
  <template data-i18n-for="dx-v-table" data-i18n-locale="en">Table</template>
  <template data-i18n-for="dx-v-table" data-i18n-locale="de">Tabelle</template>
  <template data-i18n-for="dx-v-json" data-i18n-locale="en">JSON</template>
  <template data-i18n-for="dx-v-json" data-i18n-locale="de">JSON</template>
  <template data-i18n-for="dx-sv-fields" data-i18n-locale="en">Fields</template>
  <template data-i18n-for="dx-sv-fields" data-i18n-locale="de">Felder</template>
  <template data-i18n-for="dx-sv-json" data-i18n-locale="en">JSON Schema</template>
  <template data-i18n-for="dx-sv-json" data-i18n-locale="de">JSON Schema</template>
  <template data-i18n-for="dx-l-at" data-i18n-locale="en">As of</template>
  <template data-i18n-for="dx-l-at" data-i18n-locale="de">Stand</template>
  <template data-i18n-for="dx-prev" data-i18n-locale="en">Previous</template>
  <template data-i18n-for="dx-prev" data-i18n-locale="de">Zurück</template>
  <template data-i18n-for="dx-next" data-i18n-locale="en">Next</template>
  <template data-i18n-for="dx-next" data-i18n-locale="de">Weiter</template>
  <template data-i18n-for="dx-l-group" data-i18n-locale="en">Group by</template>
  <template data-i18n-for="dx-l-group" data-i18n-locale="de">Gruppieren</template>
  <template data-i18n-for="dx-l-measure" data-i18n-locale="en">Measures</template>
  <template data-i18n-for="dx-l-measure" data-i18n-locale="de">Maße</template>
  <template data-i18n-for="dx-run" data-i18n-locale="en">Run</template>
  <template data-i18n-for="dx-run" data-i18n-locale="de">Ausführen</template>
  <template data-i18n-for="dx-l-name" data-i18n-locale="en">Name</template>
  <template data-i18n-for="dx-l-name" data-i18n-locale="de">Name</template>
  <template data-i18n-for="dx-l-fields" data-i18n-locale="en">Fields</template>
  <template data-i18n-for="dx-l-fields" data-i18n-locale="de">Felder</template>
  <template data-i18n-for="dx-l-unique" data-i18n-locale="en">Unique</template>
  <template data-i18n-for="dx-l-unique" data-i18n-locale="de">Eindeutig</template>
  <template data-i18n-for="dx-create-index" data-i18n-locale="en">Create index</template>
  <template data-i18n-for="dx-create-index" data-i18n-locale="de">Index anlegen</template>
  <template data-i18n-for="dx-t-history" data-i18n-locale="en">Query history</template>
  <template data-i18n-for="dx-t-history" data-i18n-locale="de">Abfrageverlauf</template>
  <template data-i18n-for="dx-t-log" data-i18n-locale="en">Operations</template>
  <template data-i18n-for="dx-t-log" data-i18n-locale="de">Operationen</template>
  <template data-i18n-for="dx-clear" data-i18n-locale="en">Clear</template>
  <template data-i18n-for="dx-clear" data-i18n-locale="de">Leeren</template>
  <template data-i18n-for="dx-db-dialog-title" data-i18n-locale="en">New database</template>
  <template data-i18n-for="dx-db-dialog-title" data-i18n-locale="de">Neue Datenbank</template>
  <template data-i18n-for="dx-l-db-name" data-i18n-locale="en">Database name</template>
  <template data-i18n-for="dx-l-db-name" data-i18n-locale="de">Name der Datenbank</template>
  <template data-i18n-for="dx-db-name-hint" data-i18n-locale="en"
    >Lowercase letters, digits, _ and -, starting with a letter.</template
  >
  <template data-i18n-for="dx-db-name-hint" data-i18n-locale="de"
    >Kleinbuchstaben, Ziffern, _ und -, am Anfang ein Buchstabe.</template
  >
  <template data-i18n-for="dx-l-first-coll" data-i18n-locale="en">First collection</template>
  <template data-i18n-for="dx-l-first-coll" data-i18n-locale="de">Erste Collection</template>
  <template data-i18n-for="dx-cancel" data-i18n-locale="en">Cancel</template>
  <template data-i18n-for="dx-cancel" data-i18n-locale="de">Abbrechen</template>
  <template data-i18n-for="dx-cancel-2" data-i18n-locale="en">Cancel</template>
  <template data-i18n-for="dx-cancel-2" data-i18n-locale="de">Abbrechen</template>
  <template data-i18n-for="dx-cancel-3" data-i18n-locale="en">Cancel</template>
  <template data-i18n-for="dx-cancel-3" data-i18n-locale="de">Abbrechen</template>
  <template data-i18n-for="dx-cancel-4" data-i18n-locale="en">Cancel</template>
  <template data-i18n-for="dx-cancel-4" data-i18n-locale="de">Abbrechen</template>
  <template data-i18n-for="dx-cancel-5" data-i18n-locale="en">Cancel</template>
  <template data-i18n-for="dx-cancel-5" data-i18n-locale="de">Abbrechen</template>
  <template data-i18n-for="dx-create" data-i18n-locale="en">Create</template>
  <template data-i18n-for="dx-create" data-i18n-locale="de">Anlegen</template>
  <template data-i18n-for="dx-create-2" data-i18n-locale="en">Create</template>
  <template data-i18n-for="dx-create-2" data-i18n-locale="de">Anlegen</template>
  <template data-i18n-for="dx-coll-dialog-title" data-i18n-locale="en">New collection</template>
  <template data-i18n-for="dx-coll-dialog-title" data-i18n-locale="de">Neue Collection</template>
  <template data-i18n-for="dx-l-database" data-i18n-locale="en">Database</template>
  <template data-i18n-for="dx-l-database" data-i18n-locale="de">Datenbank</template>
  <template data-i18n-for="dx-l-coll-name" data-i18n-locale="en">Collection name</template>
  <template data-i18n-for="dx-l-coll-name" data-i18n-locale="de">Name der Collection</template>
  <template data-i18n-for="dx-l-history" data-i18n-locale="en">Track history</template>
  <template data-i18n-for="dx-l-history" data-i18n-locale="de">Historie führen</template>
  <template data-i18n-for="dx-l-history-hint" data-i18n-locale="en"
    >Every version is kept: As of, a document's history, restore after a delete.</template
  >
  <template data-i18n-for="dx-l-history-hint" data-i18n-locale="de"
    >Jede Version bleibt: Stand, die Historie eines Dokuments, Wiederherstellen nach dem Löschen.</template
  >
  <template data-i18n-for="dx-l-timestamps" data-i18n-locale="en">Timestamps</template>
  <template data-i18n-for="dx-l-timestamps" data-i18n-locale="de">Zeitstempel</template>
  <template data-i18n-for="dx-l-timestamps-hint" data-i18n-locale="en"
    >Every write sets _createdAt and _updatedAt.</template
  >
  <template data-i18n-for="dx-l-timestamps-hint" data-i18n-locale="de"
    >Jedes Schreiben setzt _createdAt und _updatedAt.</template
  >
  <template data-i18n-for="dx-opt-history" data-i18n-locale="en">History</template>
  <template data-i18n-for="dx-opt-history" data-i18n-locale="de">Historie</template>
  <template data-i18n-for="dx-opt-timestamps" data-i18n-locale="en">Timestamps</template>
  <template data-i18n-for="dx-opt-timestamps" data-i18n-locale="de">Zeitstempel</template>
  <template data-i18n-for="dx-restore" data-i18n-locale="en">Restore</template>
  <template data-i18n-for="dx-restore" data-i18n-locale="de">Wiederherstellen</template>
  <template data-i18n-for="dx-enable-history" data-i18n-locale="en">Track history</template>
  <template data-i18n-for="dx-enable-history" data-i18n-locale="de">Historie führen</template>
  <template data-i18n-for="dx-enable-timestamps" data-i18n-locale="en">Add timestamps</template>
  <template data-i18n-for="dx-enable-timestamps" data-i18n-locale="de">Zeitstempel hinzufügen</template>
  <template data-i18n-for="dx-restore-title" data-i18n-locale="en">Restore a deleted document</template>
  <template data-i18n-for="dx-restore-title" data-i18n-locale="de">Ein gelöschtes Dokument wiederherstellen</template>
  <template data-i18n-for="dx-restore-hint" data-i18n-locale="en"
    >The id of a document deleted from this collection: its last version comes back as a new version.</template
  >
  <template data-i18n-for="dx-restore-hint" data-i18n-locale="de"
    >Die Id eines aus dieser Collection gelöschten Dokuments: seine letzte Version kommt als neue Version
    zurück.</template
  >
  <template data-i18n-for="dx-l-doc-id" data-i18n-locale="en">Document id</template>
  <template data-i18n-for="dx-l-doc-id" data-i18n-locale="de">Id des Dokuments</template>
  <template data-i18n-for="dx-cancel-r" data-i18n-locale="en">Cancel</template>
  <template data-i18n-for="dx-cancel-r" data-i18n-locale="de">Abbrechen</template>
  <template data-i18n-for="dx-restore-ok" data-i18n-locale="en">Restore</template>
  <template data-i18n-for="dx-restore-ok" data-i18n-locale="de">Wiederherstellen</template>
  <template data-i18n-for="dx-close-h" data-i18n-locale="en">Close</template>
  <template data-i18n-for="dx-close-h" data-i18n-locale="de">Schließen</template>
  <template data-i18n-for="dx-put-back" data-i18n-locale="en">Put back this version</template>
  <template data-i18n-for="dx-put-back" data-i18n-locale="de">Diese Version zurückschreiben</template>
  <template data-i18n-for="dx-l-zone" data-i18n-locale="en">Time zone</template>
  <template data-i18n-for="dx-l-zone" data-i18n-locale="de">Zeitzone</template>
  <template data-i18n-for="dx-insert-title" data-i18n-locale="en">Insert document</template>
  <template data-i18n-for="dx-insert-title" data-i18n-locale="de">Dokument einfügen</template>
  <template data-i18n-for="dx-insert-hint" data-i18n-locale="en"
    >An array inserts several documents. Without an id, one is generated. Dates: ISODate("2026-11-21").</template
  >
  <template data-i18n-for="dx-insert-hint" data-i18n-locale="de"
    >Ein Array fügt mehrere Dokumente ein. Ohne id wird eine erzeugt. Datumswerte: ISODate("2026-11-21").</template
  >
  <template data-i18n-for="dx-ins-tree" data-i18n-locale="en">Tree</template>
  <template data-i18n-for="dx-ins-tree" data-i18n-locale="de">Baum</template>
  <template data-i18n-for="dx-insert-ok" data-i18n-locale="en">Insert</template>
  <template data-i18n-for="dx-insert-ok" data-i18n-locale="de">Einfügen</template>
  <template data-i18n-for="dx-import-title" data-i18n-locale="en">Import</template>
  <template data-i18n-for="dx-import-title" data-i18n-locale="de">Importieren</template>
  <template data-i18n-for="dx-import-desc" data-i18n-locale="en"
    >A database archive from Export, or documents as JSON, NDJSON or CSV - also compressed with gzip or
    Brotli.</template
  >
  <template data-i18n-for="dx-import-desc" data-i18n-locale="de"
    >Ein Datenbankarchiv aus dem Export oder Dokumente als JSON, NDJSON oder CSV - auch mit gzip oder Brotli
    komprimiert.</template
  >
  <template data-i18n-for="dx-l-file" data-i18n-locale="en">File</template>
  <template data-i18n-for="dx-l-file" data-i18n-locale="de">Datei</template>
  <template data-i18n-for="dx-l-into" data-i18n-locale="en">Into database</template>
  <template data-i18n-for="dx-l-into" data-i18n-locale="de">In die Datenbank</template>
  <template data-i18n-for="dx-import-ok" data-i18n-locale="en">Import</template>
  <template data-i18n-for="dx-import-ok" data-i18n-locale="de">Importieren</template>
  <template data-i18n-for="dx-confirm-ok" data-i18n-locale="en">Delete</template>
  <template data-i18n-for="dx-confirm-ok" data-i18n-locale="de">Löschen</template>
  <template data-i18n-for="dx-add-key" data-i18n-locale="en">Add a key</template>
  <template data-i18n-for="dx-add-key" data-i18n-locale="de">Schlüssel hinzufügen</template>
  <template data-i18n-for="dx-add-measure" data-i18n-locale="en">Add a measure</template>
  <template data-i18n-for="dx-add-measure" data-i18n-locale="de">Maß hinzufügen</template>
  <template data-i18n-for="dx-l-order" data-i18n-locale="en">Order</template>
  <template data-i18n-for="dx-l-order" data-i18n-locale="de">Ordnung</template>
  <template data-i18n-for="dx-o-by-measure" data-i18n-locale="en">first measure, largest first</template>
  <template data-i18n-for="dx-o-by-measure" data-i18n-locale="de">erstes Maß, größtes zuerst</template>
  <template data-i18n-for="dx-o-by-key" data-i18n-locale="en">first key, ascending</template>
  <template data-i18n-for="dx-o-by-key" data-i18n-locale="de">erster Schlüssel, aufsteigend</template>
  <template data-i18n-for="dx-l-groups" data-i18n-locale="en">Groups</template>
  <template data-i18n-for="dx-l-groups" data-i18n-locale="de">Gruppen</template>
  <template data-i18n-for="dx-export-title" data-i18n-locale="en">Export</template>
  <template data-i18n-for="dx-export-title" data-i18n-locale="de">Exportieren</template>
  <template data-i18n-for="dx-export-desc" data-i18n-locale="en"
    >A collection's documents as a file other tools read, or a whole database as an archive this app imports
    again.</template
  >
  <template data-i18n-for="dx-export-desc" data-i18n-locale="de"
    >Die Dokumente einer Collection als Datei für andere Werkzeuge oder eine ganze Datenbank als Archiv, das diese App
    wieder importiert.</template
  >
  <template data-i18n-for="dx-l-what" data-i18n-locale="en">What</template>
  <template data-i18n-for="dx-l-what" data-i18n-locale="de">Was</template>
  <template data-i18n-for="dx-ex-coll" data-i18n-locale="en">Documents of a collection</template>
  <template data-i18n-for="dx-ex-coll" data-i18n-locale="de">Dokumente einer Collection</template>
  <template data-i18n-for="dx-ex-db" data-i18n-locale="en">Database archive</template>
  <template data-i18n-for="dx-ex-db" data-i18n-locale="de">Datenbankarchiv</template>
  <template data-i18n-for="dx-l-source" data-i18n-locale="en">From</template>
  <template data-i18n-for="dx-l-source" data-i18n-locale="de">Aus</template>
  <template data-i18n-for="dx-l-format" data-i18n-locale="en">Format</template>
  <template data-i18n-for="dx-l-format" data-i18n-locale="de">Format</template>
  <template data-i18n-for="dx-l-compression" data-i18n-locale="en">Compression</template>
  <template data-i18n-for="dx-l-compression" data-i18n-locale="de">Kompression</template>
  <template data-i18n-for="dx-o-none" data-i18n-locale="en">none</template>
  <template data-i18n-for="dx-o-none" data-i18n-locale="de">keine</template>
  <template data-i18n-for="dx-ex-filtered" data-i18n-locale="en">Only the documents the query bar finds</template>
  <template data-i18n-for="dx-ex-filtered" data-i18n-locale="de">Nur die Dokumente, die die Abfrage findet</template>
  <template data-i18n-for="dx-cancel-6" data-i18n-locale="en">Cancel</template>
  <template data-i18n-for="dx-cancel-6" data-i18n-locale="de">Abbrechen</template>
  <template data-i18n-for="dx-export-ok" data-i18n-locale="en">Export</template>
  <template data-i18n-for="dx-export-ok" data-i18n-locale="de">Exportieren</template>
  <template data-i18n-for="dx-l-into-coll" data-i18n-locale="en">Into collection</template>
  <template data-i18n-for="dx-l-into-coll" data-i18n-locale="de">In die Collection</template>
  <template data-i18n-for="dx-l-known" data-i18n-locale="en">A document whose id is already there</template>
  <template data-i18n-for="dx-l-known" data-i18n-locale="de">Ein Dokument, dessen id es schon gibt</template>
  <template data-i18n-for="dx-im-insert" data-i18n-locale="en"
    >stops the import (nothing of that part is written)</template
  >
  <template data-i18n-for="dx-im-insert" data-i18n-locale="de"
    >bricht den Import ab (von diesem Teil wird nichts geschrieben)</template
  >
  <template data-i18n-for="dx-im-upsert" data-i18n-locale="en">replaces the document</template>
  <template data-i18n-for="dx-im-upsert" data-i18n-locale="de">ersetzt das Dokument</template>
  <template data-i18n-for="dx-help-title" data-i18n-locale="en">Query language</template>
  <template data-i18n-for="dx-help-title" data-i18n-locale="de">Abfragesprache</template>
  <template data-i18n-for="dx-help-intro" data-i18n-locale="en"
    >MongoDB's filter documents, as the shell types them: unquoted keys, single quotes, ISODate('2026-01-31').</template
  >
  <template data-i18n-for="dx-help-intro" data-i18n-locale="de"
    >MongoDBs Filterdokumente, wie die Shell sie schreibt: Schlüssel ohne Anführungszeichen, einfache Anführungszeichen,
    ISODate('2026-01-31').</template
  >
  <template data-i18n-for="dx-help-k1" data-i18n-locale="en">suggestions</template>
  <template data-i18n-for="dx-help-k1" data-i18n-locale="de">Vorschläge</template>
  <template data-i18n-for="dx-help-k2" data-i18n-locale="en">takes one</template>
  <template data-i18n-for="dx-help-k2" data-i18n-locale="de">übernimmt einen</template>
  <template data-i18n-for="dx-help-k3" data-i18n-locale="en">runs</template>
  <template data-i18n-for="dx-help-k3" data-i18n-locale="de">führt aus</template>
  <template data-i18n-for="dx-pipeline-open" data-i18n-locale="en">MongoDB pipeline</template>
  <template data-i18n-for="dx-pipeline-open" data-i18n-locale="de">MongoDB-Pipeline</template>
  <template data-i18n-for="dx-pipeline-title" data-i18n-locale="en">From a MongoDB pipeline</template>
  <template data-i18n-for="dx-pipeline-title" data-i18n-locale="de">Aus einer MongoDB-Pipeline</template>
  <template data-i18n-for="dx-pipeline-desc" data-i18n-locale="en"
    >Paste an aggregation pipeline: $match, $unwind, $group, $set with $size, $sort, $limit and $count become the
    filter, the keys and the measures defuss-db runs.</template
  >
  <template data-i18n-for="dx-pipeline-desc" data-i18n-locale="de"
    >Füge eine Aggregationspipeline ein: $match, $unwind, $group, $set mit $size, $sort, $limit und $count werden zu
    Filter, Schlüsseln und Maßen, die defuss-db ausführt.</template
  >
  <template data-i18n-for="dx-l-pipeline" data-i18n-locale="en">Pipeline</template>
  <template data-i18n-for="dx-l-pipeline" data-i18n-locale="de">Pipeline</template>
  <template data-i18n-for="dx-cancel-7" data-i18n-locale="en">Cancel</template>
  <template data-i18n-for="dx-cancel-7" data-i18n-locale="de">Abbrechen</template>
  <template data-i18n-for="dx-pipeline-ok" data-i18n-locale="en">Convert and run</template>
  <template data-i18n-for="dx-pipeline-ok" data-i18n-locale="de">Übernehmen und ausführen</template>
  <template data-i18n-for="dx-drop-coll" data-i18n-locale="en">Drop collection</template>
  <template data-i18n-for="dx-drop-coll" data-i18n-locale="de">Collection löschen</template>
  <template data-i18n-for="dx-agg-empty-title" data-i18n-locale="en">No aggregation run yet</template>
  <template data-i18n-for="dx-agg-empty-title" data-i18n-locale="de">Noch keine Auswertung</template>
  <template data-i18n-for="dx-agg-empty-text" data-i18n-locale="en"
    >Pick the keys to group by and what to measure, then Run - or paste a MongoDB pipeline.</template
  >
  <template data-i18n-for="dx-agg-empty-text" data-i18n-locale="de"
    >Wählen Sie die Schlüssel zum Gruppieren und was gemessen wird, dann Ausführen - oder fügen Sie eine
    MongoDB-Pipeline ein.</template
  >
  <template data-i18n-for="dx-idx-empty-title" data-i18n-locale="en">No index yet</template>
  <template data-i18n-for="dx-idx-empty-title" data-i18n-locale="de">Noch kein Index</template>
  <template data-i18n-for="dx-idx-empty-text" data-i18n-locale="en"
    >Every query scans the whole collection. Create an index above on the fields you filter or sort by, and the query
    plan uses it.</template
  >
  <template data-i18n-for="dx-idx-empty-text" data-i18n-locale="de"
    >Jede Abfrage durchsucht die ganze Collection. Lege oben einen Index auf die Felder an, nach denen du filterst oder
    sortierst - der Abfrageplan nutzt ihn.</template
  >
</div>
<script type="module">
  // Strata: routing (defuss-dom-router), translation (defuss-i18n) and the explorer's wiring over defuss-db - the
  // database runs in an OPFS worker on the full-screen page and in memory in a docs card (js/db/db.js decides)
  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 $ = df$;
    const S = df$.shadcn;
    const root = $('[data-dx]').get(0);
    const tree = $('#dx-tree').get(0);

    // -- translation: the markup is the catalog; what the script writes comes from T
    const locale = createI18n({ locale: 'en' });
    createDomI18n($).bind(root, locale);
    S.languageSwitcher.bind($('[data-app-locale]').get(0), locale);
    const T = {
      en: {
        opfs: 'OPFS',
        memory: 'In memory',
        memoryWhy: (r) =>
          `No Origin Private File System here (${r}): the databases live in memory until the page closes.`,
        opfsWhy: "The databases are files in this browser's Origin Private File System, written by a dedicated worker.",
        homeHint: (n) => `${n} - pick one, or a collection on the left.`,
        dbs: (n) => (n === 1 ? '1 database' : `${n} databases`),
        colls: (n) => (n === 1 ? '1 collection' : `${n} collections`),
        docs: (n) => (n === 1 ? '1 document' : `${n} documents`),
        range: (a, b, n) => `${a}-${b} of ${n}`,
        firstShown: (n) => `the first ${n} in the view`,
        revisions: 'Revisions',
        none: 'No document matches.',
        took: (ms) => `${ms} ms`,
        scan: 'full scan',
        viaIndex: (k, i) => (i ? `${k} · ${i}` : k),
        save: 'Save',
        revert: 'Revert',
        duplicate: 'Duplicate',
        remove: 'Delete',
        copy: 'Copy JSON',
        copyAll: 'Copy',
        copied: 'Copied to the clipboard',
        databases: 'Databases',
        jsonShown: (n) => `${n} documents as Extended JSON`,
        modified: 'modified',
        saved: 'Saved',
        deleted: 'Deleted',
        inserted: (n) => (n === 1 ? '1 document inserted' : `${n} documents inserted`),
        group: 'Group',
        value: 'Value',
        share: 'Share',
        total: 'All documents',
        field: 'Field',
        types: 'Types',
        presence: 'Present in',
        examples: 'Examples',
        sampled: (n) =>
          `Sampled ${n} documents. A field may hold several types; the bar shows how many documents hold it.`,
        schemaJson: (n, t) => `JSON Schema (draft 2020-12) of ${n} of ${t} documents`,
        schemaSampled: (n, t, at) =>
          `Sampled ${n} of ${t} documents, spread over the collection${at ? ` as it was on ${at}` : ''}. Optional fields carry x-presence, DSON types x-dson. As of reads a collection that tracks history.`,
        schemaNoHistory: 'This collection keeps no history - As of needs a collection created with $trackHistory.',
        idxName: 'Name',
        idxFields: 'Fields',
        idxUnique: 'Unique',
        idxDrop: 'Drop',
        noIndexes: 'No index yet - every query scans the collection.',
        indexCreated: (n) => `Index ${n} created`,
        indexDropped: (n) => `Index ${n} dropped`,
        dropDbTitle: (d) => `Drop the database ${d}?`,
        dropDbText: 'Every collection, document and index in it is deleted. This cannot be undone.',
        dropCollTitle: (c) => `Drop the collection ${c}?`,
        dropCollText: 'Every document and index in it is deleted. This cannot be undone.',
        deleteDocTitle: 'Delete this document?',
        deleteDocText: (id) => `The document ${id} is deleted. This cannot be undone.`,
        dropIndexTitle: (i) => `Drop the index ${i}?`,
        dropIndexText: 'Queries that used it scan the collection again.',
        dropColl: 'Drop collection',
        collDropped: (c) => `${c} dropped`,
        insertInto: (d, c) => `Into ${d}.${c}`,
        newCollIn: (d) => `New collection in ${d}`,
        addTo: (d, c) => `Add a document to ${d}.${c}`,
        add: 'Add',
        exported: (d, size) => `${d} exported (${size})`,
        imported: (d) => `Imported into ${d}`,
        seeding: 'Writing the sample databases…',
        historyEmpty: 'Queries you run on a collection appear here.',
        star: 'Keep',
        unstar: 'Forget',
        failed: 'failed',
        unsaved: 'Unsaved changes',
        open: 'Open',
        enableHistoryTitle: (c) => `Track the history of ${c}?`,
        enableHistoryText:
          'From now on every version of every document is kept, starting with the documents as they are now. History cannot be turned off again.',
        enableTimestampsTitle: (c) => `Add timestamps to ${c}?`,
        enableTimestampsText:
          'Every document gets _createdAt and _updatedAt now, and every write sets _updatedAt. Timestamps cannot be turned off again.',
        turnOn: 'Turn on',
        historyOn: (c) => `${c} tracks its history`,
        timestampsOn: (c) => `${c} stamps its documents`,
        restored: (id) => `${id} restored`,
        notDeleted: (id) => `${id} is no deleted document of this collection`,
        history: 'History',
        historyOf: (id) => `History of ${id}`,
        versions: (n) => (n === 1 ? '1 version, newest first' : `${n} versions, newest first`),
        versionKinds: { seed: 'first version', put: 'written', delete: 'deleted' },
        revision: (r) => `revision ${r}`,
        putBack: (id) => `${id} put back`,
        deleteDocRestorable: (id) =>
          `The document ${id} is deleted. This collection keeps its history: Restore brings it back.`,
        unknownZone: (z) => `${z} is no time zone - pick one from the list (UTC, Europe/Berlin ...)`,
        every: (n, unit) => `every ${n} ${unit}s`,
        weekFrom: (d) => `from ${d}`,
        ops: {
          $eq: 'equal to',
          $ne: 'not equal to',
          $gt: 'greater than',
          $gte: 'greater than or equal',
          $lt: 'less than',
          $lte: 'less than or equal',
          $in: 'one of a list',
          $nin: 'none of a list',
          $exists: 'the field is there (true) or not (false)',
          $type: "the value's type: 'string', 'number', 'date', 'array' ...",
          $regex: "text: '^prefix', 'suffix$' or 'part'",
          $options: "beside $regex: 'i' ignores case",
          $mod: '[divisor, remainder]',
          $bitsAllSet: 'every bit of a mask (or of bit positions) is 1',
          $bitsAnySet: 'some bit of a mask is 1',
          $bitsAllClear: 'every bit of a mask is 0',
          $bitsAnyClear: 'some bit of a mask is 0',
          $all: 'the array holds every value of a list',
          $size: 'the array has this many elements',
          $elemMatch: 'one element matches every condition',
          $not: 'negates an operator document',
          $or: 'any of a list of filters',
          $and: 'all of a list of filters',
          $nor: 'none of a list of filters',
        },
        kinds: { field: 'field', operator: 'operator', value: 'value', snippet: 'template' },
        by: {
          value: 'its value',
          lower: 'lower case',
          upper: 'upper case',
          each: 'each element',
          year: 'year',
          quarter: 'quarter',
          month: 'month',
          week: 'week',
          day: 'day',
          hour: 'hour',
          minute: 'minute',
          hourOfDay: 'hour of day',
          weekday: 'weekday',
          dayOfMonth: 'day of month',
          monthOfYear: 'month of year',
          dayOfYear: 'day of year',
          isoWeek: 'ISO week number',
        },
        opNames: {
          count: 'count',
          countDistinct: 'distinct count',
          distinct: 'distinct values',
          sum: 'sum',
          avg: 'average',
          min: 'minimum',
          max: 'maximum',
          median: 'median',
          p90: '90th percentile',
          p95: '95th percentile',
          p99: '99th percentile',
          stdDevPop: 'standard deviation',
          stdDevSamp: 'sample standard deviation',
        },
        textMin: 'first (A-Z)',
        textMax: 'last (A-Z)',
        dateMin: 'earliest',
        dateMax: 'latest',
        keyField: 'Field to group by',
        groupsBy: 'How it groups',
        measureOp: 'Measure',
        measureField: 'Measured field',
        documents: '(documents)',
        fieldPh: 'field',
        removeRow: 'Remove',
        noValue: '(none)',
        weekOf: (d) => `week of ${d}`,
        groupsShown: (n, all, ms) => `${n} of ${all} groups · ${ms} ms`,
        noKeys: 'Group by at least one key, or measure all documents.',
        exportedDocs: (n, name, size) => `${n} documents → ${name} (${size})`,
        kindArchive: 'A database archive: its collections, documents and indexes',
        kindDocs: (n, how) => `${n} documents · ${how}`,
        importedDocs: (n, d, c) => `${n} documents imported into ${d}.${c}`,
        auto: 'format by content',
      },
      de: {
        opfs: 'OPFS',
        memory: 'Im Speicher',
        memoryWhy: (r) =>
          `Hier gibt es kein Origin Private File System (${r}): Die Datenbanken liegen im Speicher, bis die Seite schließt.`,
        opfsWhy:
          'Die Datenbanken sind Dateien im Origin Private File System dieses Browsers, geschrieben von einem eigenen Worker.',
        homeHint: (n) => `${n} - wähle eine aus oder links eine Collection.`,
        dbs: (n) => (n === 1 ? '1 Datenbank' : `${n} Datenbanken`),
        colls: (n) => (n === 1 ? '1 Collection' : `${n} Collections`),
        docs: (n) => (n === 1 ? '1 Dokument' : `${n} Dokumente`),
        range: (a, b, n) => `${a}-${b} von ${n}`,
        firstShown: (n) => `die ersten ${n} in der Ansicht`,
        revisions: 'Revisionen',
        none: 'Kein Dokument passt.',
        took: (ms) => `${ms} ms`,
        scan: 'vollständiger Scan',
        viaIndex: (k, i) => (i ? `${k} · ${i}` : k),
        save: 'Speichern',
        revert: 'Verwerfen',
        duplicate: 'Duplizieren',
        remove: 'Löschen',
        copy: 'JSON kopieren',
        copyAll: 'Kopieren',
        copied: 'In die Zwischenablage kopiert',
        databases: 'Datenbanken',
        jsonShown: (n) => `${n} Dokumente als Extended JSON`,
        modified: 'geändert',
        saved: 'Gespeichert',
        deleted: 'Gelöscht',
        inserted: (n) => (n === 1 ? '1 Dokument eingefügt' : `${n} Dokumente eingefügt`),
        group: 'Gruppe',
        value: 'Wert',
        share: 'Anteil',
        total: 'Alle Dokumente',
        field: 'Feld',
        types: 'Typen',
        presence: 'Vorhanden in',
        examples: 'Beispiele',
        sampled: (n) =>
          `Stichprobe aus ${n} Dokumenten. Ein Feld kann mehrere Typen haben; der Balken zeigt, wie viele Dokumente es enthalten.`,
        schemaJson: (n, t) => `JSON Schema (Draft 2020-12) aus ${n} von ${t} Dokumenten`,
        schemaSampled: (n, t, at) =>
          `Stichprobe aus ${n} von ${t} Dokumenten, über die ganze Collection verteilt${at ? `, Stand ${at}` : ''}. Optionale Felder tragen x-presence, DSON-Typen x-dson. Stand liest eine Collection mit Historie.`,
        schemaNoHistory: 'Diese Collection führt keine Historie - Stand braucht eine Collection mit $trackHistory.',
        idxName: 'Name',
        idxFields: 'Felder',
        idxUnique: 'Eindeutig',
        idxDrop: 'Löschen',
        noIndexes: 'Noch kein Index - jede Abfrage durchsucht die ganze Collection.',
        indexCreated: (n) => `Index ${n} angelegt`,
        indexDropped: (n) => `Index ${n} gelöscht`,
        dropDbTitle: (d) => `Die Datenbank ${d} löschen?`,
        dropDbText:
          'Alle Collections, Dokumente und Indizes darin werden gelöscht. Das lässt sich nicht rückgängig machen.',
        dropCollTitle: (c) => `Die Collection ${c} löschen?`,
        dropCollText: 'Alle Dokumente und Indizes darin werden gelöscht. Das lässt sich nicht rückgängig machen.',
        deleteDocTitle: 'Dieses Dokument löschen?',
        deleteDocText: (id) => `Das Dokument ${id} wird gelöscht. Das lässt sich nicht rückgängig machen.`,
        dropIndexTitle: (i) => `Den Index ${i} löschen?`,
        dropIndexText: 'Abfragen, die ihn genutzt haben, durchsuchen die Collection wieder ganz.',
        dropColl: 'Collection löschen',
        collDropped: (c) => `${c} gelöscht`,
        insertInto: (d, c) => `In ${d}.${c}`,
        newCollIn: (d) => `Neue Collection in ${d}`,
        addTo: (d, c) => `Dokument zu ${d}.${c} hinzufügen`,
        add: 'Neu',
        exported: (d, size) => `${d} exportiert (${size})`,
        imported: (d) => `In ${d} importiert`,
        seeding: 'Die Beispieldatenbanken werden geschrieben…',
        historyEmpty: 'Abfragen, die du auf einer Collection ausführst, erscheinen hier.',
        star: 'Behalten',
        unstar: 'Vergessen',
        failed: 'fehlgeschlagen',
        unsaved: 'Ungespeicherte Änderungen',
        open: 'Öffnen',
        enableHistoryTitle: (c) => `Die Historie von ${c} führen?`,
        enableHistoryText:
          'Ab jetzt bleibt jede Version jedes Dokuments erhalten, beginnend mit den Dokumenten, wie sie jetzt sind. Die Historie lässt sich nicht wieder abschalten.',
        enableTimestampsTitle: (c) => `${c} Zeitstempel geben?`,
        enableTimestampsText:
          'Jedes Dokument bekommt jetzt _createdAt und _updatedAt, und jedes Schreiben setzt _updatedAt. Zeitstempel lassen sich nicht wieder abschalten.',
        turnOn: 'Einschalten',
        historyOn: (c) => `${c} führt seine Historie`,
        timestampsOn: (c) => `${c} stempelt seine Dokumente`,
        restored: (id) => `${id} wiederhergestellt`,
        notDeleted: (id) => `${id} ist kein gelöschtes Dokument dieser Collection`,
        history: 'Historie',
        historyOf: (id) => `Historie von ${id}`,
        versions: (n) => (n === 1 ? '1 Version, die neueste zuerst' : `${n} Versionen, die neueste zuerst`),
        versionKinds: { seed: 'erste Version', put: 'geschrieben', delete: 'gelöscht' },
        revision: (r) => `Revision ${r}`,
        putBack: (id) => `${id} zurückgeschrieben`,
        deleteDocRestorable: (id) =>
          `Das Dokument ${id} wird gelöscht. Diese Collection führt ihre Historie: Wiederherstellen holt es zurück.`,
        unknownZone: (z) => `${z} ist keine Zeitzone - wähle eine aus der Liste (UTC, Europe/Berlin ...)`,
        every: (n, unit) => `alle ${n} ${unit}`,
        weekFrom: (d) => `ab ${d}`,
        ops: {
          $eq: 'gleich',
          $ne: 'ungleich',
          $gt: 'größer als',
          $gte: 'größer oder gleich',
          $lt: 'kleiner als',
          $lte: 'kleiner oder gleich',
          $in: 'einer aus einer Liste',
          $nin: 'keiner aus einer Liste',
          $exists: 'das Feld ist da (true) oder nicht (false)',
          $type: "der Typ des Werts: 'string', 'number', 'date', 'array' ...",
          $regex: "Text: '^Anfang', 'Ende$' oder 'Teil'",
          $options: "neben $regex: 'i' ignoriert Groß- und Kleinschreibung",
          $mod: '[Teiler, Rest]',
          $bitsAllSet: 'jedes Bit einer Maske (oder Bitposition) ist 1',
          $bitsAnySet: 'ein Bit einer Maske ist 1',
          $bitsAllClear: 'jedes Bit einer Maske ist 0',
          $bitsAnyClear: 'ein Bit einer Maske ist 0',
          $all: 'das Array enthält jeden Wert einer Liste',
          $size: 'das Array hat so viele Elemente',
          $elemMatch: 'ein Element erfüllt jede Bedingung',
          $not: 'verneint ein Operatordokument',
          $or: 'einer aus einer Liste von Filtern',
          $and: 'alle aus einer Liste von Filtern',
          $nor: 'keiner aus einer Liste von Filtern',
        },
        kinds: { field: 'Feld', operator: 'Operator', value: 'Wert', snippet: 'Vorlage' },
        by: {
          value: 'Wert',
          lower: 'Kleinschreibung',
          upper: 'Großschreibung',
          each: 'jedes Element',
          year: 'Jahr',
          quarter: 'Quartal',
          month: 'Monat',
          week: 'Woche',
          day: 'Tag',
          hour: 'Stunde',
          minute: 'Minute',
          hourOfDay: 'Stunde des Tages',
          weekday: 'Wochentag',
          dayOfMonth: 'Tag des Monats',
          monthOfYear: 'Monat des Jahres',
          dayOfYear: 'Tag des Jahres',
          isoWeek: 'ISO-Kalenderwoche',
        },
        opNames: {
          count: 'Anzahl',
          countDistinct: 'Anzahl verschiedener',
          distinct: 'verschiedene Werte',
          sum: 'Summe',
          avg: 'Mittelwert',
          min: 'Minimum',
          max: 'Maximum',
          median: 'Median',
          p90: '90. Perzentil',
          p95: '95. Perzentil',
          p99: '99. Perzentil',
          stdDevPop: 'Standardabweichung',
          stdDevSamp: 'Stichproben-Standardabweichung',
        },
        textMin: 'erster (A-Z)',
        textMax: 'letzter (A-Z)',
        dateMin: 'frühester',
        dateMax: 'spätester',
        keyField: 'Feld, nach dem gruppiert wird',
        groupsBy: 'Wie es gruppiert',
        measureOp: 'Maß',
        measureField: 'Gemessenes Feld',
        documents: '(Dokumente)',
        fieldPh: 'Feld',
        removeRow: 'Entfernen',
        noValue: '(keiner)',
        weekOf: (d) => `Woche ab ${d}`,
        groupsShown: (n, all, ms) => `${n} von ${all} Gruppen · ${ms} ms`,
        noKeys: 'Gruppiere nach mindestens einem Schlüssel oder miss alle Dokumente.',
        exportedDocs: (n, name, size) => `${n} Dokumente → ${name} (${size})`,
        kindArchive: 'Ein Datenbankarchiv: Collections, Dokumente und Indizes',
        kindDocs: (n, how) => `${n} Dokumente · ${how}`,
        importedDocs: (n, d, c) => `${n} Dokumente in ${d}.${c} importiert`,
        auto: 'Format nach Inhalt',
      },
    };
    const lang = () => (root.getAttribute('lang') || 'en').slice(0, 2);
    const tr = (k, ...a) => {
      const v = (T[lang()] || T.en)[k] ?? T.en[k];
      return typeof v === 'function' ? v(...a) : v;
    };
    const esc = (s) =>
      String(s).replace(
        /[&<>"']/g,
        (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
      );
    const fmt = (n) => new Intl.NumberFormat(lang()).format(n);
    const ICON = {
      history:
        '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/></svg>',
      copy: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>',
      duplicate:
        '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 12v6M12 15h6"/><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>',
      undo: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11"/></svg>',
      check:
        '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>',
      plus: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>',
      trash:
        '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M10 11v6M14 11v6"/></svg>',
      db: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><ellipse cx="12" cy="5" rx="8" ry="3"/><path d="M4 5v14c0 1.7 3.6 3 8 3s8-1.3 8-3V5M4 12c0 1.7 3.6 3 8 3s8-1.3 8-3"/></svg>',
      coll: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 10h18M9 10v10"/></svg>',
      x: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg>',
    };

    // -- light / dark
    const dark = $('[data-dx-dark]').get(0);
    dark.checked = document.documentElement.classList.contains('dark');
    $(dark).on('change', () => {
      document.documentElement.classList.toggle('dark', dark.checked);
      document.dispatchEvent(new CustomEvent('defuss-theme-change'));
    });

    // -- the database: an OPFS worker where the page may have one, else memory (js/db/db.js)
    const DB_MODULE = 'js/db/db.js';
    const dbx = await import(new URL(DB_MODULE, document.baseURI).href);
    const conn = await dbx.connect({ namespace: 'strata' });
    const showMode = () => {
      $('[data-dx-mode]')
        .text(tr(conn.mode))
        .attr('title', conn.mode === 'opfs' ? tr('opfsWhy') : tr('memoryWhy', conn.reason));
      root.dataset.dxStore = conn.mode;
    };
    showMode();

    // -- every call goes through here: the operation log hears it
    const logEl = $('[data-dx-log]').get(0);
    const addLog = (op, args, ms, ok, error) => {
      const where = args
        .slice(0, 2)
        .filter((a) => typeof a === 'string')
        .join('.');
      const li = document.createElement('li');
      $(li).html(
        `<time>${new Date().toLocaleTimeString(lang())}</time><code>${esc(op)}</code><span>${esc(where)}${
          error ? ` <span data-failed>${esc(tr('failed'))}: ${esc(error)}</span>` : ''
        }</span><span class="dx-ms">${ms} ms</span>`,
      );
      if (!ok) li.dataset.failed = '';
      logEl.prepend(li);
      while (logEl.children.length > 200) logEl.lastElementChild.remove();
    };
    const call = async (op, ...args) => {
      const t0 = performance.now();
      try {
        const value = await conn.call(op, ...args);
        addLog(op, args, Math.round(performance.now() - t0), true);
        return value;
      } catch (err) {
        addLog(op, args, Math.round(performance.now() - t0), false, err.message);
        throw err;
      }
    };
    $('[data-dx-clear-log]').on('click', () => $(logEl).html(''));
    // spelled out: the app bundle finds a namespace a script uses by this name (scripts/lib/apps.ts)
    const toast = (title, variant) => df$.shadcn.toast.show({ title, ...(variant ? { variant } : {}) });

    // -- sample data: a shop, its analytics and a small CMS - deterministic, written once per browser
    const rng = (seed) => () => {
      seed |= 0;
      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 seedData = () => {
      const r = rng(7);
      const pick = (a) => a[Math.floor(r() * a.length)];
      const first = [
        'Ada',
        'Alan',
        'Grace',
        'Linus',
        'Margaret',
        'Ken',
        'Barbara',
        'Dennis',
        'Frances',
        'Edsger',
        'Radia',
        'John',
        'Hedy',
        'Tim',
        'Karen',
        'Guido',
      ];
      const last = [
        'Lovelace',
        'Turing',
        'Hopper',
        'Torvalds',
        'Hamilton',
        'Thompson',
        'Liskov',
        'Ritchie',
        'Allen',
        'Dijkstra',
        'Perlman',
        'Backus',
        'Lamarr',
        'Berners-Lee',
        'Spärck Jones',
        'van Rossum',
      ];
      const places = [
        ['DE', 'Berlin', '10115'],
        ['DE', 'Hamburg', '20095'],
        ['AT', 'Wien', '1010'],
        ['CH', 'Zürich', '8001'],
        ['FR', 'Paris', '75001'],
        ['NL', 'Amsterdam', '1012'],
        ['US', 'Boston', '02108'],
        ['GB', 'London', 'EC1A'],
      ];
      const customers = Array.from({ length: 800 }, (_, i) => {
        const [country, city, zip] = pick(places);
        const name = `${pick(first)} ${pick(last)}`;
        return {
          id: `cus-${String(i + 1).padStart(4, '0')}`,
          name,
          email: `${name.toLowerCase().replace(/[^a-z]+/g, '.')}.${i + 1}@example.com`,
          tier: r() < 0.1 ? 'gold' : r() < 0.35 ? 'silver' : 'bronze',
          address: {
            street: `${pick(['Main', 'Park', 'Mill', 'Station', 'Lake'])} Street ${1 + Math.floor(r() * 120)}`,
            zip,
            city,
            country,
          },
          since: new Date(Date.UTC(2019 + Math.floor(r() * 7), Math.floor(r() * 12), 1 + Math.floor(r() * 28))),
          marketing: r() < 0.4,
          tags: r() < 0.3 ? ['b2b'] : [],
        };
      });
      const nouns = [
        'Lamp',
        'Chair',
        'Desk',
        'Kettle',
        'Backpack',
        'Notebook',
        'Headphones',
        'Mug',
        'Shelf',
        'Rug',
        'Monitor',
        'Keyboard',
      ];
      const adjectives = ['Nordic', 'Compact', 'Classic', 'Studio', 'Travel', 'Oak', 'Steel', 'Linen', 'Pro', 'Mini'];
      const categories = {
        Lamp: 'home',
        Chair: 'furniture',
        Desk: 'furniture',
        Kettle: 'kitchen',
        Backpack: 'travel',
        Notebook: 'office',
        Headphones: 'electronics',
        Mug: 'kitchen',
        Shelf: 'furniture',
        Rug: 'home',
        Monitor: 'electronics',
        Keyboard: 'electronics',
      };
      const products = Array.from({ length: 240 }, (_, i) => {
        const noun = pick(nouns);
        return {
          id: `sku-${1001 + i}`,
          name: `${pick(adjectives)} ${noun}`,
          category: categories[noun],
          price: Math.round((5 + r() * 395) * 100) / 100,
          stock: Math.floor(r() * 400),
          rating: Math.round((2.5 + r() * 2.5) * 10) / 10,
          dimensions: { w: 10 + Math.floor(r() * 90), h: 10 + Math.floor(r() * 90), d: 5 + Math.floor(r() * 60) },
          tags: r() < 0.2 ? ['bestseller'] : r() < 0.3 ? ['new'] : [],
        };
      });
      const statuses = ['pending', 'paid', 'shipped', 'shipped', 'delivered', 'delivered', 'delivered', 'refunded'];
      const orders = Array.from({ length: 12000 }, (_, i) => {
        const c = customers[Math.floor(r() * customers.length)];
        const items = Array.from({ length: 1 + Math.floor(r() * 4) }, () => {
          const p = products[Math.floor(r() * products.length)];
          return { sku: p.id, name: p.name, qty: 1 + Math.floor(r() * 3), price: p.price };
        });
        const status = pick(statuses);
        return {
          id: 100001 + i,
          customer: c.id,
          country: c.address.country,
          status,
          paid: status !== 'pending',
          createdAt: new Date(Date.UTC(2025, 0, 1) + Math.floor(r() * 690) * 864e5 + Math.floor(r() * 864e5)),
          items,
          amount: Math.round(items.reduce((n, it) => n + it.qty * it.price, 0) * 100) / 100,
          currency: 'EUR',
          shipping: { method: pick(['standard', 'standard', 'express', 'pickup']), city: c.address.city },
        };
      });
      const types = [
        'page_view',
        'page_view',
        'page_view',
        'click',
        'click',
        'search',
        'add_to_cart',
        'signup',
        'purchase',
      ];
      const paths = ['/', '/shop', '/shop/lamps', '/shop/chairs', '/cart', '/checkout', '/account', '/blog', '/help'];
      const events = Array.from({ length: 30000 }, (_, i) => ({
        id: `ev-${String(i + 1).padStart(6, '0')}`,
        type: pick(types),
        path: pick(paths),
        at: new Date(Date.UTC(2026, 9, 1) + Math.floor(r() * 50 * 864e5)),
        session: `s-${Math.floor(r() * 4000)}`,
        device: pick(['desktop', 'desktop', 'mobile', 'mobile', 'tablet']),
        country: pick(places)[0],
        durationMs: Math.floor(r() * 90000),
        bytes: BigInt(Math.floor(r() * 2_000_000)),
      }));
      const topics = ['databases', 'design', 'accessibility', 'performance', 'search', 'offline'];
      const articles = Array.from({ length: 120 }, (_, i) => {
        const topic = pick(topics);
        const published = r() < 0.75;
        return {
          id: `post-${i + 1}`,
          title: `${pick(['Notes on', 'A guide to', 'Why we chose', 'Ten lessons in', 'Rethinking'])} ${topic}`,
          slug: `${topic}-${i + 1}`,
          author: { name: `${pick(first)} ${pick(last)}`, role: pick(['editor', 'engineer', 'designer']) },
          status: published ? 'published' : 'draft',
          publishedAt: published ? new Date(Date.UTC(2024, 0, 1) + Math.floor(r() * 1000) * 864e5) : null,
          tags: [topic, ...(r() < 0.4 ? ['featured'] : [])],
          wordCount: 300 + Math.floor(r() * 2700),
          comments: Array.from({ length: Math.floor(r() * 4) }, (_, k) => ({
            author: pick(first),
            text: pick(['Great read!', 'Thanks for this.', 'What about mobile?', 'Bookmarked.']),
            at: new Date(Date.UTC(2026, 0, 1 + k)),
          })),
        };
      });
      return { customers, products, orders, events, articles };
    };
    // the sample databases, written once per origin. A first visit may stop half way (the tab closes) or run beside
    // another tab (VERIFIED by the defuss-db site e2e: either left customers without the marker, and every later visit
    // failed on a duplicate key): one tab seeds at a time (a Web Lock), each collection is one step with its own
    // marker, and a step that did not finish is emptied and written again
    const SEED_STEPS = [
      ['shop', 'customers', [{ name: 'byEmail', fields: ['email'], unique: true }]],
      ['shop', 'products', []],
      [
        'shop',
        'orders',
        [
          { name: 'byStatus', fields: ['status'] },
          { name: 'countryByDate', fields: ['country', 'createdAt'], order: ['asc', 'desc'] },
        ],
        2000,
      ],
      ['analytics', 'events', [{ name: 'byType', fields: ['type'] }], 2500],
      // the articles keep their history and stamp their writes (defuss-db 3.1): As of, History and Restore have one to show
      ['cms', 'articles', [], 1000, { history: true, timestamps: true }],
    ];
    const marked = (id) => call('get', 'admin', 'settings', id).catch(() => undefined);
    const seedSteps = async () => {
      if (await marked('seeded')) return;
      root.dataset.dxSeeding = '';
      $('[data-dx-home-hint]').text(tr('seeding'));
      let d;
      for (const [db, coll, indexes, batch = 1000, options] of SEED_STEPS) {
        const step = `seed:${db}.${coll}`;
        if (await marked(step)) continue;
        d ??= seedData();
        if (options) await call('createCollection', db, coll, options);
        // what an interrupted step wrote goes first: the documents are written whole again
        await call('deleteMany', db, coll, '');
        // indexes before the documents: each batch then keeps its index entries current
        const has = new Set((await call('indexes', db, coll)).map((i) => i.name));
        for (const spec of indexes) if (!has.has(spec.name)) await call('createIndex', db, coll, spec);
        await call('insertMany', db, coll, d[coll], batch);
        await call('put', 'admin', 'settings', { id: step, at: new Date() });
      }
      await call('put', 'admin', 'settings', { id: 'seeded', at: new Date() });
    };
    const seed = async () => {
      try {
        // a tab that waited for the lock finds the marker and goes on
        if (globalThis.navigator?.locks) await navigator.locks.request('dx-seed', seedSteps);
        else await seedSteps();
      } catch (err) {
        // an opaque docs card may refuse Web Locks (SecurityError): its memory database is its own anyway
        if (err?.name !== 'SecurityError') throw err;
        await seedSteps();
      } finally {
        delete root.dataset.dxSeeding;
      }
    };
    await seed();

    // -- the tree: databases, their collections and counts
    let databases = [];
    let collections = new Map(); // db → [{ name, count, indexes, history, timestamps }]
    /** What the open collection keeps besides its documents (ops.collectionOptions, read with the tree). */
    const optionsOf = (db, coll) => (collections.get(db) || []).find((c) => c.name === coll) ?? {};
    const loadTree = async () => {
      // read whole, then swapped in: a card rendered while the tree reloads still finds its collection's options
      // (VERIFIED: an empty map during the reload rendered a tracked collection's cards without History)
      const nextDbs = await call('databases');
      const next = new Map();
      for (const d of nextDbs) next.set(d.name, await call('collections', d.name));
      databases = nextDbs;
      collections = next;
      const rows = [];
      for (const d of databases) {
        rows.push({
          id: `db:${d.name}`,
          parentId: null,
          label: d.name,
          kind: 'db',
          db: d.name,
          count: collections.get(d.name).length,
        });
        for (const c of collections.get(d.name))
          rows.push({
            id: `c:${d.name}/${c.name}`,
            parentId: `db:${d.name}`,
            label: c.name,
            kind: 'coll',
            db: d.name,
            coll: c.name,
            count: c.count,
          });
      }
      const selected = current.coll ? `c:${current.db}/${current.coll}` : current.db ? `db:${current.db}` : null;
      S.dataTree.setSource(tree, rows, {
        render: (el, rec) =>
          void $(el).html(
            `<span class="dx-node"><span class="dx-ico">${ICON[rec.kind]}</span><span>${esc(rec.label)}</span><small>${fmt(rec.count)}</small></span>${
              rec.kind === 'db'
                ? `<button class="btn dx-node-act" data-variant="ghost" data-size="icon-xs" type="button" tabindex="-1" data-dx-tree-act="new-coll" data-db="${esc(rec.db)}" aria-label="${esc(tr('newCollIn', rec.db))}" title="${esc(tr('newCollIn', rec.db))}">${ICON.plus}</button>`
                : `<button class="btn dx-node-act" data-variant="ghost" data-size="icon-xs" type="button" tabindex="-1" data-dx-tree-act="insert" data-db="${esc(rec.db)}" data-coll="${esc(rec.coll)}" aria-label="${esc(tr('addTo', rec.db, rec.coll))}" title="${esc(tr('addTo', rec.db, rec.coll))}">${ICON.plus}</button>`
            }`,
          ),
        query: { expanded: databases.filter((d) => d.name !== 'admin').map((d) => `db:${d.name}`), selected },
      });
      $('#dx-coll-db').html(
        databases
          .filter((d) => d.name !== 'admin')
          .map((d) => `<option>${esc(d.name)}</option>`)
          .join(''),
      );
    };
    // a row's button acts on its database or collection - the click never reaches the tree (no selection, no route);
    // from the keyboard, + on a focused row does the same
    tree.addEventListener(
      'click',
      (e) => {
        const btn = e.target.closest('[data-dx-tree-act]');
        if (!btn) return;
        e.stopPropagation();
        e.preventDefault();
        treeAction(btn);
      },
      true,
    );
    tree.addEventListener(
      'dblclick',
      (e) => {
        if (e.target.closest('[data-dx-tree-act]')) e.stopPropagation();
      },
      true,
    );
    $(tree).on('keydown', (e) => {
      if (e.key !== '+') return;
      const btn = $(tree).find('.data-tree-item[data-active] [data-dx-tree-act]').get(0);
      if (!btn) return;
      e.preventDefault();
      treeAction(btn);
    });
    const treeAction = (btn) => {
      const { db, coll } = btn.dataset;
      if (btn.dataset.dxTreeAct === 'new-coll') newCollection(db);
      else insertInto(db, coll);
    };
    $(tree).on('data-tree-select', (e) => {
      const rec = e.detail.record;
      go(rec.kind === 'db' ? `/${rec.db}` : `/${rec.db}/${rec.coll}`);
    });

    // -- views
    let current = { db: null, coll: null };
    const view = (name) =>
      $('[data-dx-view]').each((_i, el) => {
        el.hidden = el.dataset.dxView !== name;
      });
    const go = (path) => {
      if (location.hash !== `#${path}`) location.hash = path;
    };
    const crumbs = () => {
      const parts = [`<a href="#/" class="link">${esc(tr('databases'))}</a>`];
      if (current.db) parts.push(`<a href="#/${esc(current.db)}" class="link">${esc(current.db)}</a>`);
      if (current.coll) parts.push(`<span>${esc(current.coll)}</span>`);
      $('[data-dx-crumbs]').html(parts.join('<span aria-hidden="true">›</span>'));
    };
    // a size in the unit that keeps it between 1 and 999: B, KiB, MiB, GiB, TiB
    const sizeText = (n) => {
      const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
      let v = n;
      let u = 0;
      while (v > 999 && u < units.length - 1) {
        v /= 1024;
        u++;
      }
      return `${new Intl.NumberFormat(lang(), { maximumFractionDigits: u ? 1 : 0 }).format(v)} ${units[u]}`;
    };
    const showRevision = async () => {
      const badge = $('[data-dx-revision]').get(0);
      if (!current.db) return void (badge.hidden = true);
      const s = await call('stats', current.db);
      badge.hidden = false;
      $(badge).text(`rev ${s.revision}${s.bytes ? ` · ${sizeText(s.bytes)}` : ''}`);
    };

    const renderHome = () => {
      view('home');
      const shown = databases.filter((d) => d.name !== 'admin');
      $('[data-dx-home-hint]').text(tr('homeHint', tr('dbs', shown.length)));
      $('[data-dx-home-cards]').html(
        databases
          .map(
            (d) =>
              `<a class="card dx-db-card" data-size="sm" href="#/${esc(d.name)}" data-dx-db="${esc(d.name)}"><div class="card-header"><h3 class="card-title"><span class="dx-ico">${ICON.db}</span> ${esc(d.name)}</h3><p class="card-description">${esc(tr('colls', d.collections))} · ${esc(tr('docs', fmt(d.documents)))}</p></div></a>`,
          )
          .join(''),
      );
    };
    const renderDb = () => {
      view('db');
      const list = collections.get(current.db) || [];
      $('[data-dx-db-rows]').html(
        list
          .map(
            (c) =>
              `<tr class="table-row"><td class="table-cell"><a class="link" href="#/${esc(current.db)}/${esc(c.name)}">${esc(c.name)}</a>${c.history ? ` <span class="badge" data-variant="secondary" data-dx-coll-opt="history">${esc(tr('history'))}</span>` : ''}${c.timestamps ? ` <span class="badge" data-variant="secondary" data-dx-coll-opt="timestamps">_updatedAt</span>` : ''}</td><td class="table-cell" style="text-align:right">${fmt(c.count)}</td><td class="table-cell" style="text-align:right">${fmt(c.indexes)}</td></tr>`,
          )
          .join(''),
      );
    };

    // -- a collection: Documents (query bar, list / table / JSON), Aggregations, Schema, Indexes
    const qform = $('[data-dx-query]').get(0);
    // where the List view's query starts: 0, or where Next / Previous moved it
    let startAt = 0;
    let mode = 'list';
    let lastResult = null;
    let fields = [];
    const showError = (msg) => {
      const el = $('[data-dx-error]').get(0);
      el.hidden = !msg;
      $('[data-dx-error-text]').text(msg || '');
    };
    const spec = () => ({
      filter: qform.filter.value,
      sort: qform.sort.value,
      project: qform.project.value,
      limit: Number(qform.limit.value),
      skip: startAt,
    });
    /** a sample's fields with the type most of their values have */
    const asFields = (s) =>
      s.fields.map((f) => ({
        path: f.path,
        type: Object.entries(f.types).sort((a, b) => b[1] - a[1])[0]?.[0] ?? 'unknown',
      }));

    // -- completion: what fits at the caret of a query field (runtime/db/complete.ts); a field's values from a sample
    const ac = $('#dx-ac').get(0);
    let acInput = null;
    let acState = null; // { completion, active }
    const valueCache = new Map();
    const valuesOf = (field) => {
      const key = `${current.db}.${current.coll}.${field}`;
      if (!valueCache.has(key))
        valueCache.set(
          key,
          call('values', current.db, current.coll, field, 400).catch(() => []),
        );
      return valueCache.get(key);
    };
    const KIND_MARK = { field: 'F', operator: '$', value: '=', snippet: '{}' };
    const detailText = (s) =>
      s.kind === 'operator' ? (tr('ops')[s.label] ?? s.detail) : s.kind === 'snippet' ? tr('kinds').snippet : s.detail;
    const measureCanvas = document.createElement('canvas').getContext('2d');
    // where a position of the field's text is, in px from its left edge (the list opens there)
    const caretX = (input, pos) => {
      const cs = getComputedStyle(input);
      measureCanvas.font = `${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;
      return measureCanvas.measureText(input.value.slice(0, pos)).width + parseFloat(cs.paddingLeft) - input.scrollLeft;
    };
    const acClose = () => {
      acState = null;
      if (ac.matches(':popover-open')) ac.hidePopover();
      if (acInput) {
        acInput.setAttribute('aria-expanded', 'false');
        acInput.removeAttribute('aria-activedescendant');
      }
    };
    const acRender = () => {
      const { completion: c, active } = acState;
      $(ac).html(
        c.items
          .map(
            (s, i) =>
              `<div class="dx-ac-item" role="option" id="dx-ac-${i}" data-kind="${s.kind}" aria-selected="${i === active}"><span class="dx-ac-kind" aria-hidden="true">${KIND_MARK[s.kind]}</span><span class="dx-ac-label">${esc(s.label)}</span>${s.detail || s.kind === 'snippet' ? `<span class="dx-ac-detail">${esc(detailText(s) ?? '')}</span>` : ''}</div>`,
          )
          .join(''),
      );
      acInput.setAttribute('aria-activedescendant', `dx-ac-${active}`);
      $(ac).find(`#dx-ac-${active}`).get(0)?.scrollIntoView({ block: 'nearest' });
    };
    const acUpdate = async (input, force = false) => {
      const mode = input.dataset.dxComplete;
      const caret = input.selectionStart ?? input.value.length;
      let c = dbx.complete(input.value, caret, mode, fields);
      if (c.context === 'value' && mode === 'filter' && c.field && current.coll) {
        const values = await valuesOf(c.field);
        // the reader moved on while the values came
        if (document.activeElement !== input || input.selectionStart !== caret) return;
        c = dbx.complete(input.value, caret, mode, fields, values);
      }
      // nothing fits, or the one suggestion is what is typed already
      if (!c.items.length || (!force && c.items.length === 1 && c.items[0].insert === input.value.slice(c.from, c.to)))
        return acClose();
      if (acInput && acInput !== input) acInput.style.removeProperty('anchor-name');
      acInput = input;
      input.style.setProperty('anchor-name', '--dx-ac');
      ac.style.setProperty('--dx-ac-x', `${Math.max(0, Math.min(caretX(input, c.from), input.clientWidth - 200))}px`);
      acState = { completion: c, active: 0 };
      acRender();
      if (!ac.matches(':popover-open')) ac.showPopover();
      input.setAttribute('aria-expanded', 'true');
    };
    const acAccept = (i = acState?.active ?? 0) => {
      const input = acInput;
      const c = acState?.completion;
      const s = c?.items[i];
      if (!s) return false;
      input.value = input.value.slice(0, c.from) + s.insert + input.value.slice(c.to);
      const pos = c.from + (s.caret ?? s.insert.length);
      input.setSelectionRange(pos, pos);
      acClose();
      input.dispatchEvent(new Event('change', { bubbles: true }));
      validate(input);
      // a key or an operator asks for what follows it (the field's values, its operators)
      if (s.kind !== 'value') acUpdate(input);
      return true;
    };
    // the syntax, checked when the typing pauses: the field is marked, the query bar names the error
    const syntax = $('[data-dx-syntax]').get(0);
    let syntaxTimer;
    const validate = (input) => {
      clearTimeout(syntaxTimer);
      input.removeAttribute('aria-invalid');
      if (input.form === qform) syntax.hidden = true;
      if (!['filter', 'sort', 'project'].includes(input.dataset.dxComplete)) return;
      syntaxTimer = setTimeout(() => {
        try {
          dbx.parseDocument(input.value, $(`label[for="${input.id}"]`).text() || input.name);
        } catch (err) {
          input.setAttribute('aria-invalid', 'true');
          if (input.form === qform) {
            syntax.hidden = false;
            $(syntax).text(err.message);
          }
        }
      }, 700);
    };
    // braces, brackets and quotes close themselves; typing the closer steps over it; Backspace removes an empty pair
    const PAIRS = { '{': '}', '[': ']', '(': ')', "'": "'", '"': '"' };
    const onKey = (e) => {
      const input = e.currentTarget;
      const open = acState && acInput === input;
      if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
        e.preventDefault();
        acClose();
        input.form.requestSubmit();
        return;
      }
      if (e.ctrlKey && (e.key === ' ' || e.code === 'Space')) {
        e.preventDefault();
        acUpdate(input, true);
        return;
      }
      if (open) {
        const n = acState.completion.items.length;
        if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
          e.preventDefault();
          acState.active = (acState.active + (e.key === 'ArrowDown' ? 1 : n - 1)) % n;
          acRender();
          return;
        }
        if (e.key === 'Enter' || e.key === 'Tab') {
          if (acAccept()) e.preventDefault();
          return;
        }
        if (e.key === 'Escape') {
          e.preventDefault();
          e.stopPropagation();
          acClose();
          return;
        }
      }
      if (e.ctrlKey || e.metaKey || e.altKey || input.dataset.dxComplete === 'field') return;
      const { selectionStart: a, selectionEnd: b, value: v } = input;
      if (a !== b) return;
      const next = v[a] ?? '';
      if (['}', ']', ')', "'", '"'].includes(e.key) && next === e.key) {
        e.preventDefault();
        input.setSelectionRange(a + 1, a + 1);
        return;
      }
      if (PAIRS[e.key] && /^$|[\s,}\])]/.test(next)) {
        if ((e.key === "'" || e.key === '"') && /[\w$]/.test(v[a - 1] ?? '')) return;
        e.preventDefault();
        input.setRangeText(e.key + PAIRS[e.key], a, a, 'end');
        input.setSelectionRange(a + 1, a + 1);
        input.dispatchEvent(new Event('input', { bubbles: true }));
        return;
      }
      if (e.key === 'Backspace' && next && PAIRS[v[a - 1]] === next) {
        e.preventDefault();
        input.setRangeText('', a - 1, a + 1, 'end');
        input.dispatchEvent(new Event('input', { bubbles: true }));
      }
    };
    const bindComplete = (input) => {
      input.setAttribute('role', 'combobox');
      input.setAttribute('aria-autocomplete', 'list');
      input.setAttribute('aria-controls', 'dx-ac');
      input.setAttribute('aria-expanded', 'false');
      $(input).on('keydown', onKey);
      $(input).on('input', (e) => {
        validate(input);
        if (!e.inputType || /^(insert|deleteContent)/.test(e.inputType)) acUpdate(input);
        else acClose();
      });
      $(input).on('blur', () =>
        setTimeout(() => {
          if (document.activeElement !== input && acInput === input) acClose();
        }, 0),
      );
    };
    $('[data-dx-complete]').each((_i, input) => {
      bindComplete(input);
    });
    // a press on the list keeps the focus in the field; a click takes the suggestion
    $(ac).on('pointerdown', (e) => e.preventDefault());
    $(ac).on('click', (e) => {
      const o = e.target.closest('[role="option"]');
      if (o) acAccept(Number(o.id.slice('dx-ac-'.length)));
    });
    // the help popover's operator list, in the page's language
    const renderHelp = () =>
      $('[data-dx-help-ops]').html(
        [...dbx.OPERATORS.map((o) => o.op), '$or', '$and', '$nor']
          .map((op) => `<dt><code>${op}</code></dt><dd>${esc(tr('ops')[op] ?? '')}</dd>`)
          .join(''),
      );
    renderHelp();

    const runQuery = async ({ record = false } = {}) => {
      acClose();
      showError('');
      let result;
      // the results remember their collection: a card or a cell writes there, even after the reader moved on
      const where = { db: current.db, coll: current.coll };
      try {
        result = windowed()
          ? await call('findAll', where.db, where.coll, { ...spec(), skip: 0 })
          : await call('find', where.db, where.coll, spec());
      } catch (err) {
        showError(err.message);
        return;
      }
      if (where.db !== current.db || where.coll !== current.coll) return; // a newer collection is open
      lastResult = { ...result, ...where };
      listStart = windowed() ? 0 : spec().skip;
      if (record) remember();
      showCount();
      const plan = $('[data-dx-plan]').get(0);
      plan.hidden = false;
      $(plan).text(result.access === 'scan' ? tr('scan') : tr('viaIndex', result.access, result.index));
      plan.dataset.access = result.access;
      await renderResults();
    };
    // the Table and JSON views hold every match and window it themselves (Data Grid, Virtual List)
    const windowed = () => mode !== 'list';
    // the documents in view, 0-based numbers of the matches: what the view shows inside its box
    let inView = null;
    // the List view loads batches both ways: its first row is match number listStart
    let listStart = 0;
    // "21-34 of 12,000": the documents in view (before the first measure: what is loaded)
    const showCount = () => {
      if (!lastResult) return;
      const n = lastResult.rows.length;
      const total = lastResult.total ?? n;
      const [a, b] = inView ?? (windowed() ? [0, Math.min(n, 1) - 1] : [listStart, listStart + n - 1]);
      const capped = windowed() && n < total ? ` · ${tr('firstShown', fmt(n))}` : '';
      $('[data-dx-count]').text(
        total
          ? `${tr('range', fmt(a + 1), fmt(b + 1), fmt(total))}${capped} · ${tr('took', lastResult.ms)}`
          : tr('none'),
      );
      $('[data-dx-pager]').get(0).hidden = windowed();
      $('[data-dx-page="-1"]').get(0).disabled = listStart === 0;
      $('[data-dx-page="1"]').get(0).disabled = listStart + n >= total;
    };
    // follows a windowed view's scrolling: once a frame, the first and last rendered row inside the box
    const followView = (box, rowsOf) => {
      let queued = false;
      const measure = () => {
        queued = false;
        const r = box.getBoundingClientRect();
        let first = Infinity;
        let last = -1;
        for (const [el, index] of rowsOf()) {
          const q = el.getBoundingClientRect();
          if (q.bottom <= r.top + 1 || q.top >= r.bottom - 1) continue;
          first = Math.min(first, index);
          last = Math.max(last, index);
        }
        inView = last < 0 ? null : [first, last];
        showCount();
      };
      // a frame later: Virtual List moves its rows in the frame after the scroll (VERIFIED: measured in the same frame,
      // every row still sat above the box)
      $(box).on('scroll', () => {
        if (queued) return;
        queued = true;
        requestAnimationFrame(() => requestAnimationFrame(measure));
      });
      requestAnimationFrame(() => requestAnimationFrame(measure));
    };
    // the List view: a batch fills at least the box, and the next one loads while the reader still has more than
    // a box of rows ahead, in the direction they scroll - up too, when the list started on a later page
    const results = $('[data-dx-results]').get(0);
    const batchSize = () => {
      const card = $(results).find('.dx-doc:not([open])').get(0);
      const row = card ? card.getBoundingClientRect().height + 6 : 40;
      return Math.max(Number(qform.limit.value), Math.ceil(results.clientHeight / row));
    };
    const cardsHtml = (rows, from) => rows.map((r, k) => cardHtml(r, from + k)).join('');
    let loadingMore = false;
    const loadMore = async (dir) => {
      if (loadingMore || !lastResult || windowed()) return;
      const where = lastResult;
      const total = where.total ?? 0;
      const size = batchSize();
      const skip = dir > 0 ? listStart + where.rows.length : Math.max(0, listStart - size);
      const limit = dir > 0 ? size : listStart - skip;
      if (limit <= 0 || skip >= total) return;
      loadingMore = true;
      try {
        // the total is known: a later batch skips the count, which scans every match (~170 ms over 12,000 orders)
        const more = await call('find', where.db, where.coll, { ...spec(), skip, limit, count: false });
        if (lastResult !== where || windowed()) return;
        const list = $(results).find('.dx-docs').get(0);
        const holder = document.createElement('div');
        if (dir > 0) {
          $(holder).html(cardsHtml(more.rows, where.rows.length));
          where.rows.push(...more.rows);
          list.append(...holder.children);
        } else {
          const before = results.scrollHeight;
          $(holder).html(cardsHtml(more.rows, 0));
          where.rows.unshift(...more.rows);
          listStart = skip;
          const shift = more.rows.length;
          $(list)
            .children()
            .each((_k, card) => {
              card.dataset.dxDoc = String(Number(card.dataset.dxDoc) + shift);
            });
          list.prepend(...holder.children);
          // the rows the reader looks at stay where they were
          results.scrollTop += results.scrollHeight - before;
        }
        where.ms = more.ms;
        showCount();
      } catch (err) {
        showError(err.message);
      } finally {
        loadingMore = false;
      }
      ahead();
    };
    // a scroll the reader makes (wheel, touch, keys, the scroll bar) - never one a script or a focus makes - loads;
    // it keeps loading while they stay near an end
    let userAt = -Infinity;
    let barPress = false;
    let dir = 1;
    let lastTop = 0;
    const user = () => {
      userAt = performance.now();
    };
    const ahead = () => {
      if (mode !== 'list' || root.dataset.dxShows !== 'coll') return;
      if (!barPress && performance.now() - userAt > 1500) return;
      const room = results.clientHeight * 1.5;
      if (dir > 0 && results.scrollHeight - results.scrollTop - results.clientHeight < room) loadMore(1);
      else if (dir < 0 && results.scrollTop < room) loadMore(-1);
    };
    // the documents in view: the cards at the top and bottom edge of the box (two hit tests, not one per card)
    let measuring = false;
    const measureList = () => {
      measuring = false;
      if (mode !== 'list' || !lastResult?.rows.length) return;
      const r = results.getBoundingClientRect();
      const x = r.left + Math.min(40, r.width / 2);
      const at = (y, step) => {
        for (let k = 0; k < 4; k++) {
          const card = document.elementFromPoint(x, y + k * step)?.closest('.dx-doc');
          if (card && results.contains(card)) return Number(card.dataset.dxDoc);
        }
        return null;
      };
      const first = at(Math.max(r.top, 0) + 2, 4);
      const last = at(Math.min(r.bottom, innerHeight) - 2, -4) ?? lastResult.rows.length - 1;
      inView = first === null ? null : [listStart + first, listStart + Math.max(first, last)];
      showCount();
    };
    $(results).on('wheel', (e) => {
      user();
      if (e.deltaY) dir = e.deltaY > 0 ? 1 : -1;
      ahead();
    });
    $(results).on('touchmove', user);
    $(results).on('keydown', (e) => {
      if (['PageDown', 'PageUp', 'End', 'Home', 'ArrowDown', 'ArrowUp', ' '].includes(e.key)) user();
    });
    $(results).on('pointerdown', (e) => {
      barPress = e.target === results;
    });
    $(document).on('pointerup', () => {
      barPress = false;
    });
    $(results).on('scroll', () => {
      if (mode !== 'list') return;
      dir = results.scrollTop >= lastTop ? 1 : -1;
      lastTop = results.scrollTop;
      if (!measuring) {
        measuring = true;
        requestAnimationFrame(measureList);
      }
      ahead();
    });

    // the documents as the chosen view shows them
    const isScalar = (v) =>
      v === null || ['string', 'number', 'boolean', 'bigint'].includes(typeof v) || v instanceof Date;
    const idText = (id) => (typeof id === 'string' ? `"${id}"` : String(id));
    /** a folded document's one line: its fields after the id, nested values abbreviated */
    const short = (v) =>
      v instanceof Date
        ? v.toISOString().slice(0, 10)
        : Array.isArray(v)
          ? `[${v.length}]`
          : v && typeof v === 'object'
            ? '{…}'
            : typeof v === 'string'
              ? `'${v.length > 40 ? v.slice(0, 40) + '…' : v}'`
              : String(v);
    const preview = (doc) =>
      Object.entries(doc)
        .filter(([k]) => k !== 'id')
        .slice(0, 8)
        .map(([k, v]) => `${k}: ${short(v)}`)
        .join(', ');
    // a Property Tree shows its open rows; the card is as high as they are (the tree scrolls past 24 rows)
    const rowsOpen = (value, expanded) => {
      let n = 1;
      const walk = (v, ptr) => {
        if (!v || typeof v !== 'object' || (ptr !== '' && !expanded.has(ptr))) return;
        for (const [k, x] of v instanceof Map ? v : Object.entries(v)) {
          n++;
          walk(x, `${ptr}/${String(k).replace(/~/g, '~0').replace(/\//g, '~1')}`);
        }
      };
      walk(value, '');
      return Math.min(n, 24);
    };
    const fit = (el) => {
      const value = S.propertyTree.value(el);
      const expanded = new Set(el.api.getState().config.expanded ?? []);
      el.style.blockSize = `calc(${rowsOpen(value, expanded)} * 1.75rem + 2px)`;
    };
    const cardHtml = (r, i) =>
      `<details class="card dx-doc" data-dx-doc="${i}"><summary class="dx-doc-head"><code class="dx-doc-id">id: ${esc(idText(r.id))}</code><span class="dx-doc-preview">${esc(preview(r))}</span><span class="badge" data-variant="outline" data-dx-dirty hidden>${esc(tr('modified'))}</span><button class="btn" data-size="xs" type="button" data-dx-doc-act="save" hidden>${ICON.check}${esc(tr('save'))}</button><button class="btn" data-variant="ghost" data-size="xs" type="button" data-dx-doc-act="revert" hidden>${ICON.undo}${esc(tr('revert'))}</button><button class="btn" data-variant="ghost" data-size="xs" type="button" data-dx-doc-act="copy" title="${esc(tr('copy'))}">${ICON.copy}<span class="dx-act-label">${esc(tr('copy'))}</span></button><button class="btn" data-variant="ghost" data-size="xs" type="button" data-dx-doc-act="duplicate" title="${esc(tr('duplicate'))}">${ICON.duplicate}<span class="dx-act-label">${esc(tr('duplicate'))}</span></button>${lastResult && optionsOf(lastResult.db, lastResult.coll).history ? `<button class="btn" data-variant="ghost" data-size="xs" type="button" data-dx-doc-act="history" title="${esc(tr('history'))}">${ICON.history}<span class="dx-act-label">${esc(tr('history'))}</span></button>` : ''}<button class="btn" data-variant="destructive" data-size="xs" type="button" data-dx-doc-act="delete" title="${esc(tr('remove'))}">${ICON.trash}<span class="dx-act-label">${esc(tr('remove'))}</span></button></summary><div class="dx-doc-body" data-dx-doc-body></div></details>`;
    // the JSON view: shell-style Extended JSON, coloured by token (strings, keys, numbers, literals, constructors)
    const TOKEN =
      /('(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*")(\s*:)?|\b(ISODate|NumberLong|NumberDecimal|ObjectId|BinData|UUID)(?=\()|\b(true|false|null|undefined|NaN|Infinity)\b|(-?\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?n?\b)|([A-Za-z_$][\w$]*)(?=\s*:)/g;
    const highlight = (text) => {
      let out = '';
      let last = 0;
      for (const m of text.matchAll(TOKEN)) {
        const kind = m[1] ? (m[2] ? 'key' : 'str') : m[3] ? 'fn' : m[4] ? 'lit' : m[5] ? 'num' : 'key';
        out += `${esc(text.slice(last, m.index))}<span class="dx-t-${kind}">${esc(m[1] ?? m[0])}</span>${m[2] ? esc(m[2]) : ''}`;
        last = m.index + m[0].length;
      }
      return out + esc(text.slice(last));
    };
    const jsonText = () => `[\n${(lastResult?.rows ?? []).map((r) => dbx.stringify(r)).join(',\n')}\n]`;
    const copyText = async (text) => {
      try {
        await navigator.clipboard.writeText(text);
        toast(tr('copied'));
      } catch (err) {
        toast(err.message, 'destructive');
      }
    };
    const renderResults = async () => {
      const rows = lastResult?.rows ?? [];
      inView = null;
      if (mode === 'json') return renderJson(rows);
      if (mode === 'table') return renderGrid(rows);
      $(results).html(`<div class="dx-docs">${rows.map(cardHtml).join('')}</div>`);
      // .html() morphs: a card element may carry over with the stashes of the document it showed before (VERIFIED:
      // a reused card kept its old tree promise and never made a tree for its new document)
      $(results)
        .find('.dx-doc')
        .each((_i, card) => {
          card._tree = card._opened = card._revs = card._shownRev = undefined;
        });
      results.scrollTop = 0;
      lastTop = 0;
      requestAnimationFrame(measureList);
    };
    // one line per row of a Virtual List (VERIFIED: one preformatted block of 12,000 documents is 300,000 lines in one box), each
    // line knowing its document - the foot counts documents, not lines
    const renderJson = async (rows) => {
      const lines = ['['];
      const docOf = [0];
      rows.forEach((r, i) => {
        const parts = dbx.stringify(r).split('\n');
        parts.forEach((p, k) => {
          lines.push(`  ${p}${k === parts.length - 1 && i < rows.length - 1 ? ',' : ''}`);
          docOf.push(i);
        });
      });
      lines.push(']');
      docOf.push(Math.max(0, rows.length - 1));
      $(results).html(
        `<div class="dx-json-view"><div class="dx-json-bar" role="toolbar" aria-label="JSON"><span>${esc(tr('jsonShown', fmt(rows.length)))}</span><button class="btn" data-variant="ghost" data-size="xs" type="button" data-dx-copy-json>${ICON.copy}${esc(tr('copyAll'))}</button></div><div class="virtual-list dx-json dx-json-lines" id="dx-json-lines" data-dx-json tabindex="0" aria-label="Extended JSON"></div></div>`,
      );
      const list = $('#dx-json-lines').get(0);
      df$.shadcn.virtualList.setData(list, lines.length, (row, i) => {
        $(row).html(highlight(lines[i]));
      });
      followView(list, () =>
        $(list)
          .find('.virtual-list-row')
          .toArray()
          .map((el) => [el, docOf[Number(el.dataset.index)] ?? 0]),
      );
    };
    // a card's tree is made when the card first opens, or an action needs it (VERIFIED tmp/probe-dx-list.ts: every
    // card's tree mounted with its page cost 400-590 ms per 20 cards); the tree holds a copy - edits stay local
    // until Save
    const frame = () => new Promise((res) => requestAnimationFrame(res));
    const treeOf = (card) =>
      (card._tree ??= (async () => {
        const doc = lastResult.rows[Number(card.dataset.dxDoc)];
        $(card)
          .find('[data-dx-doc-body]')
          .html(`<div class="property-tree" aria-label="Document ${esc(idText(doc.id))}"></div>`);
        const el = $(card).find('.property-tree').get(0);
        S.propertyTree.configure(el, {
          value: structuredClone(doc),
          // the id names the document: it does not edit (Duplicate makes a new one)
          getEditorFn: (_path, _value, ctx) =>
            ctx.pointer === '/id' || (ctx.kind === 'key' && ctx.pointer === '/id') ? false : null,
        });
        // the component starts it from its observer
        for (let k = 0; !el.store && k < 120; k++) await frame();
        fit(el);
        el.store.subscribe(() => fit(el));
        return el;
      })());
    const setDirty = (card, dirty) => {
      if (dirty) card.dataset.dirty = '';
      else delete card.dataset.dirty;
      $(card)
        .find('[data-dx-dirty], [data-dx-doc-act="save"], [data-dx-doc-act="revert"]')
        .each((_i, b) => {
          b.hidden = !dirty;
        });
    };
    // a tracked collection's card: its revisions under the tree, oldest to newest - a click shows one in the tree,
    // Save writes it back as the newest, Revert returns to the document as it is
    const showRevisions = async (card) => {
      const { db, coll } = lastResult;
      if (!optionsOf(db, coll).history) return;
      const doc = lastResult.rows[Number(card.dataset.dxDoc)];
      const versions = (await call('history', db, coll, doc.id)).slice().reverse();
      card._revs = versions;
      const when = (d) => new Intl.DateTimeFormat(lang(), { dateStyle: 'medium', timeStyle: 'medium' }).format(d);
      const shown = versions.length - 1;
      $(card)
        .find('.dx-revs')
        .each((_i, old) => {
          old.remove();
        });
      const body = $(card).find('[data-dx-doc-body]').get(0);
      $(body).append(
        $(
          `<ol class="timeline dx-revs" data-orientation="horizontal" data-density="compact" aria-label="${esc(tr('revisions'))}">${versions
            .map(
              (v, k) =>
                `<li class="timeline-item"><div class="timeline-dot" data-variant="${k === shown ? 'active' : v.kind === 'delete' ? 'destructive' : v.kind === 'seed' ? 'outline' : 'default'}"></div><div class="timeline-content"><button class="dx-rev" type="button" data-dx-rev="${k}" aria-pressed="${k === shown}"${v.document ? '' : ' disabled'}><span class="timeline-title">${esc(tr('versionKinds')[v.kind])} · ${esc(tr('revision', v.revision))}</span><time class="timeline-time" datetime="${v.from.toISOString()}">${esc(when(v.from))}</time></button></div></li>`,
            )
            .join('')}</ol>`,
        ),
      );
      const ol = $(card).find('.dx-revs').get(0);
      ol.scrollLeft = ol.scrollWidth;
    };
    const markRevision = (card, k) => {
      const last = (card._revs?.length ?? 1) - 1;
      $(card)
        .find('[data-dx-rev]')
        .each((_i, b) => {
          const i = Number(b.dataset.dxRev);
          b.setAttribute('aria-pressed', String(i === k));
          const v = card._revs[i];
          $(b.closest('.timeline-item')).find('.timeline-dot').get(0).dataset.variant =
            i === k ? 'active' : v.kind === 'delete' ? 'destructive' : v.kind === 'seed' ? 'outline' : 'default';
        });
      card._shownRev = k === last ? undefined : k;
    };
    $(results).on(
      'toggle',
      async (e) => {
        const card = e.target;
        if (!card.matches?.('.dx-doc') || !card.open || card._opened) return;
        card._opened = true;
        await treeOf(card);
        await showRevisions(card);
      },
      { capture: true },
    );
    // a card's edits: modified until saved or reverted
    $(results).on('property-tree-change', (e) => {
      const card = e.target.closest('.dx-doc');
      if (!card) return;
      setDirty(card, true);
      $(card)
        .find('.dx-doc-preview')
        .text(preview(S.propertyTree.value($(card).find('.property-tree').get(0))));
    });
    $(results).on('click', async (e) => {
      if (e.target.closest('[data-dx-copy-json]')) return copyText(jsonText());
      const rev = e.target.closest('[data-dx-rev]');
      if (rev) {
        const card = rev.closest('.dx-doc');
        const k = Number(rev.dataset.dxRev);
        const el = await treeOf(card);
        S.propertyTree.setValue(el, structuredClone(card._revs[k].document));
        fit(el);
        markRevision(card, k);
        $(card).find('.dx-doc-preview').text(preview(card._revs[k].document));
        // the newest revision is the document as it is; an older one is an edit until Save or Revert
        setDirty(card, card._shownRev !== undefined);
        return;
      }
      const btn = e.target.closest('[data-dx-doc-act]');
      if (!btn) return;
      // what the database refuses (a duplicate key, a document too large) is said, not swallowed
      try {
        await docAction(btn);
      } catch (err) {
        toast(err.message, 'destructive');
      }
    });
    const docAction = async (btn) => {
      const card = btn.closest('.dx-doc');
      const act = btn.dataset.dxDocAct;
      // delete and history need no tree
      const el = act === 'delete' || act === 'history' ? null : await treeOf(card);
      const original = lastResult.rows[Number(card.dataset.dxDoc)];
      if (act === 'save') {
        const { db, coll } = lastResult;
        const doc = structuredClone(S.propertyTree.value(el));
        // a stamped collection sets the stamps itself and refuses an older _updatedAt (an earlier revision's)
        if (optionsOf(db, coll).timestamps) {
          delete doc._createdAt;
          delete doc._updatedAt;
        }
        await call('put', db, coll, doc);
        lastResult.rows[Number(card.dataset.dxDoc)] = (await call('get', db, coll, doc.id)) ?? doc;
        setDirty(card, false);
        toast(tr('saved'));
        refreshCounts();
        if (card._revs) await showRevisions(card);
      } else if (act === 'revert') {
        S.propertyTree.setValue(el, structuredClone(original));
        $(card).find('.dx-doc-preview').text(preview(original));
        setDirty(card, false);
        if (card._revs) markRevision(card, card._revs.length - 1);
        fit(el);
      } else if (act === 'copy') {
        await copyText(dbx.stringify(S.propertyTree.value(el)));
      } else if (act === 'duplicate') {
        const copy = structuredClone(S.propertyTree.value(el));
        delete copy.id;
        const where = lastResult;
        const id = await call('insert', where.db, where.coll, copy);
        toast(tr('inserted', 1));
        const doc = (await call('get', where.db, where.coll, id)) ?? { ...copy, id };
        if (lastResult !== where) return void refreshCounts();
        const i = lastResult.rows.push(doc) - 1;
        if (lastResult.total !== undefined) lastResult.total++;
        showCount();
        const holder = document.createElement('div');
        $(holder).html(cardHtml(doc, i));
        const added = holder.firstElementChild;
        card.after(added);
        added.open = true;
        added.scrollIntoView({ block: 'nearest' });
        refreshCounts();
      } else if (act === 'history') {
        await openHistory(lastResult.db, lastResult.coll, original.id);
      } else if (act === 'delete') {
        const restorable = optionsOf(lastResult.db, lastResult.coll).history;
        const text = tr(restorable ? 'deleteDocRestorable' : 'deleteDocText', idText(original.id));
        if (!(await confirmDialog(tr('deleteDocTitle'), text))) return;
        await call('remove', lastResult.db, lastResult.coll, original.id);
        toast(tr('deleted'));
        await runQuery();
        refreshCounts();
      }
    };

    // the Table view: a Data Grid over the page - columns from the documents' top-level fields, scalars edit in place
    const renderGrid = async (rows) => {
      const keys = [];
      for (const r of rows) for (const k of Object.keys(r)) if (!keys.includes(k)) keys.push(k);
      const cols = keys.slice(0, 14);
      const editable = (k) =>
        k !== 'id' &&
        rows.every(
          (r) => r[k] === undefined || (isScalar(r[k]) && !(r[k] instanceof Date) && typeof r[k] !== 'bigint'),
        );
      const typeOf = (k) => (rows.some((r) => typeof r[k] === 'number') ? ' data-type="number"' : '');
      $(results).html(
        `<div class="dx-grid-host"><div class="data-grid" id="dx-grid" aria-label="${esc(current.coll)}" data-density="compact" data-persist="none" data-select="single"><div class="data-grid-viewport"><div class="data-grid-head"><div class="data-grid-row">${cols
          .map(
            (k) =>
              `<div class="data-grid-header" data-field="${esc(k)}"${typeOf(k)} data-width="${k === 'id' ? '9rem' : '10rem'}"${k === 'id' ? ' data-locked' : ''}${editable(k) ? ' data-editable' : ''}>${esc(k)}</div>`,
          )
          .join('')}</div></div><div class="data-grid-body"></div></div></div></div>`,
      );
      await new Promise((res) => requestAnimationFrame(res));
      const cells = {};
      for (const k of cols)
        if (!editable(k))
          cells[k] = (el, record) => {
            const v = record[k];
            $(el).text(
              v instanceof Date
                ? v.toLocaleString(lang())
                : typeof v === 'bigint'
                  ? `${v}n`
                  : Array.isArray(v)
                    ? `[ ${v.length} ]`
                    : v && typeof v === 'object'
                      ? `{ ${Object.keys(v).length} }`
                      : v === undefined
                        ? ''
                        : String(v),
            );
          };
      S.dataGrid.setSource(
        '#dx-grid',
        rows.map((r) => ({ ...r })),
        { cells },
      );
      // the grid's rows carry their place in its (sorted, filtered) order, 0-based
      const grid = $('#dx-grid').get(0);
      followView($(grid).find('.data-grid-viewport').get(0), () =>
        $(grid)
          .find('.data-grid-body .data-grid-row[data-index]')
          .toArray()
          .map((el) => [el, Number(el.dataset.index)]),
      );
    };
    $(results).on('data-grid-edit', async (e) => {
      const { record, field, value } = e.detail;
      await call('update', lastResult.db, lastResult.coll, record.id, { [field]: value });
      const i = lastResult.rows.findIndex((r) => Object.is(r.id, record.id));
      if (i >= 0) lastResult.rows[i] = { ...lastResult.rows[i], [field]: value };
    });

    // view switch and paging
    const views = $('[data-dx-views]').get(0);
    $(views).on('click', async (e) => {
      const b = e.target.closest('button[value]');
      if (!b) return;
      const was = windowed();
      mode = b.value;
      $(views)
        .find('button')
        .each((_i, x) => x.setAttribute('aria-pressed', String(x === b)));
      if (was !== windowed()) {
        startAt = 0;
        await runQuery();
      } else await renderResults();
      showCount();
    });
    $('[data-dx-page]').on('click', async (e) => {
      // Next goes on after what is loaded (batches scrolled into included), Previous one page before it
      const step = Number(e.currentTarget.dataset.dxPage);
      const loaded = lastResult?.rows.length ?? 0;
      startAt = step > 0 ? listStart + loaded : Math.max(0, listStart - Number(qform.limit.value));
      await runQuery();
    });
    $(qform).on('submit', async (e) => {
      e.preventDefault();
      startAt = 0;
      await runQuery({ record: true });
    });
    $('[data-dx-reset]').on('click', async () => {
      qform.filter.value = qform.sort.value = qform.project.value = '';
      startAt = 0;
      await runQuery();
    });

    // the query history: per collection, newest first; a kept query stays at the top
    const history = df$.store.persisted(
      'strata:history',
      {},
      { validate: (v) => !!v && typeof v === 'object' && !Array.isArray(v) },
    );
    const historyKey = () => `${current.db}.${current.coll}`;
    const remember = () => {
      const q = {
        filter: qform.filter.value.trim(),
        sort: qform.sort.value.trim(),
        project: qform.project.value.trim(),
      };
      if (!q.filter && !q.sort && !q.project) return;
      const all = { ...history.value };
      const list = (all[historyKey()] || []).filter(
        (x) => x.filter !== q.filter || x.sort !== q.sort || x.project !== q.project || x.kept,
      );
      all[historyKey()] = [{ ...q, at: Date.now(), kept: false }, ...list].slice(0, 30);
      history.set(all);
      renderHistory();
    };
    const renderHistory = () => {
      const list = current.coll
        ? [...(history.value[historyKey()] || [])].sort((a, b) => Number(b.kept) - Number(a.kept))
        : [];
      $('[data-dx-history]').html(
        list.length
          ? list
              .map(
                (q, i) =>
                  `<li class="dx-history-item"><button class="dx-run" type="button" data-dx-history-run="${i}" title="${esc(q.filter || '{ }')}">${esc(q.filter || '{ }')}${q.sort ? ` · ${esc(q.sort)}` : ''}</button><button class="btn" data-variant="ghost" data-size="xs" type="button" data-dx-history-keep="${i}" aria-pressed="${q.kept}">${esc(tr(q.kept ? 'unstar' : 'star'))}</button><small>${esc(new Date(q.at).toLocaleString(lang()))}</small></li>`,
              )
              .join('')
          : `<li class="dx-hint" style="padding:0.5rem">${esc(tr('historyEmpty'))}</li>`,
      );
      root._historyList = list;
    };
    $('[data-dx-history]').on('click', async (e) => {
      const run = e.target.closest('[data-dx-history-run]');
      const keep = e.target.closest('[data-dx-history-keep]');
      const list = root._historyList || [];
      if (run) {
        const q = list[Number(run.dataset.dxHistoryRun)];
        qform.filter.value = q.filter;
        qform.sort.value = q.sort;
        qform.project.value = q.project;
        startAt = 0;
        selectTab('docs');
        await runQuery();
      } else if (keep) {
        const q = list[Number(keep.dataset.dxHistoryKeep)];
        const all = { ...history.value };
        all[historyKey()] = (all[historyKey()] || []).map((x) => (x.at === q.at ? { ...x, kept: !x.kept } : x));
        history.set(all);
        renderHistory();
      }
    });

    // tabs: the Tabs component switches panels; the page loads a tab's data when it shows
    const selectTab = (name) => {
      const trigger = $(`[data-dx-tab="${name}"]`).get(0);
      if (trigger.getAttribute('aria-selected') !== 'true') trigger.click();
    };
    $('[data-dx-tab]').on('click', (e) => {
      const name = e.currentTarget.dataset.dxTab;
      if (name === 'schema') renderSchema();
      if (name === 'idx') renderIndexes();
    });

    // Aggregations: keys (a field and how it groups) and measures (an operator over a field), row by row; the result
    // is a table with a bar per group and the same aggregation as a MongoDB pipeline
    const aggForm = $('[data-dx-agg]').get(0);
    const keysEl = $('[data-dx-keys]').get(0);
    const measuresEl = $('[data-dx-measures]').get(0);
    const typeOfField = (path) => fields.find((x) => x.path === path)?.type;
    // defuss-db 3.1: the start of a unit (minute too, binned, weeks from any day) or a part of the date, in a time zone
    const DATE_UNITS = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute'];
    const DATE_PARTS = ['hourOfDay', 'weekday', 'dayOfMonth', 'monthOfYear', 'dayOfYear', 'isoWeek'];
    const byFor = (type) =>
      type === 'string'
        ? ['value', 'lower', 'upper']
        : type === 'array'
          ? ['each', 'value']
          : type === 'date'
            ? ['value', ...DATE_UNITS, ...DATE_PARTS]
            : type === undefined
              ? ['value', 'lower', 'upper', 'each', ...DATE_UNITS, ...DATE_PARTS]
              : ['value'];
    const OPS = [
      'count',
      'countDistinct',
      'distinct',
      'sum',
      'avg',
      'min',
      'max',
      'median',
      'p90',
      'p95',
      'p99',
      'stdDevPop',
      'stdDevSamp',
    ];
    const NUMERIC_OPS = ['sum', 'avg', 'median', 'p90', 'p95', 'p99', 'stdDevPop', 'stdDevSamp'];
    const opsFor = (type) =>
      type === 'number' || type === 'bigint' || type === undefined ? OPS : OPS.filter((o) => !NUMERIC_OPS.includes(o));
    // the zones the platform knows; a typed one must be one of them
    const ZONES = new Set(['UTC', ...(Intl.supportedValuesOf?.('timeZone') ?? [])]);
    $('#dx-zones').html([...ZONES].map((z) => `<option value="${esc(z)}"></option>`).join(''));
    const opName = (op, type) =>
      op === 'min' && type === 'string'
        ? tr('textMin')
        : op === 'max' && type === 'string'
          ? tr('textMax')
          : op === 'min' && type === 'date'
            ? tr('dateMin')
            : op === 'max' && type === 'date'
              ? tr('dateMax')
              : tr('opNames')[op];
    const removeBtn = () =>
      `<button class="btn" data-variant="ghost" data-size="icon-sm" type="button" data-dx-remove aria-label="${esc(tr('removeRow'))}">${ICON.x}</button>`;
    const fieldInput = (value, label, placeholder) =>
      `<input class="input dx-mono" data-size="sm" data-dx-complete="field" spellcheck="false" autocomplete="off" value="${esc(value)}" placeholder="${esc(placeholder)}" aria-label="${esc(label)}" />`;
    const keyOptions = (type, chosen) =>
      byFor(type)
        .map((b) => `<option value="${b}"${b === chosen ? ' selected' : ''}>${esc(tr('by')[b])}</option>`)
        .join('');
    const opOptions = (type, chosen) =>
      OPS.map(
        (o) =>
          `<option value="${o}"${o === chosen ? ' selected' : ''}${opsFor(type).includes(o) ? '' : ' disabled'}>${esc(opName(o, type))}</option>`,
      ).join('');
    // a pasted pipeline's bin (every 15 minutes) and week start stay on the row until its unit changes
    const addKey = (field = '', by = 'value', { bin, weekStart } = {}) => {
      const li = document.createElement('li');
      li.className = 'dx-agg-row';
      li.dataset.dxKey = '';
      if (bin > 1) li.dataset.dxBin = String(bin);
      if (weekStart) li.dataset.dxWeekStart = weekStart;
      const type = field ? typeOfField(field) : undefined;
      $(li).html(
        `${fieldInput(field, tr('keyField'), tr('fieldPh'))}<select class="select" data-size="sm" aria-label="${esc(tr('groupsBy'))}">${keyOptions(type, by)}</select>${removeBtn()}`,
      );
      keysEl.append(li);
      bindComplete($(li).find('input').get(0));
      return li;
    };
    const addMeasure = (op = 'count', field = '') => {
      const li = document.createElement('li');
      li.className = 'dx-agg-row';
      li.dataset.dxMeasure = '';
      const type = field ? typeOfField(field) : undefined;
      $(li).html(
        `<select class="select" data-size="sm" aria-label="${esc(tr('measureOp'))}">${opOptions(type, op)}</select>${fieldInput(field, tr('measureField'), op === 'count' ? tr('documents') : tr('fieldPh'))}${removeBtn()}`,
      );
      measuresEl.append(li);
      bindComplete($(li).find('input').get(0));
      return li;
    };
    // a field's type decides how it groups and what measures it
    const refreshRow = (li) => {
      const input = $(li).find('input').get(0);
      const select = $(li).find('select').get(0);
      const type = input.value.trim() ? typeOfField(input.value.trim()) : undefined;
      if (li.hasAttribute('data-dx-key')) {
        const keep = byFor(type).includes(select.value) ? select.value : byFor(type)[0];
        $(select).html(keyOptions(type, keep));
      } else {
        const keep = opsFor(type).includes(select.value) ? select.value : 'count';
        $(select).html(opOptions(type, keep));
        input.placeholder = keep === 'count' ? tr('documents') : tr('fieldPh');
      }
    };
    $(aggForm).on('change', (e) => {
      const li = e.target.closest('.dx-agg-row');
      if (!li) return;
      if (e.target.matches('select')) {
        delete li.dataset.dxBin;
        delete li.dataset.dxWeekStart;
      }
      refreshRow(li);
    });
    $(aggForm).on('click', (e) => {
      const rm = e.target.closest('[data-dx-remove]');
      if (rm) rm.closest('.dx-agg-row').remove();
    });
    $('[data-dx-add-key]').on('click', () => $(addKey()).find('input').get(0).focus());
    $('[data-dx-add-measure]').on('click', () => $(addMeasure()).find('select').get(0).focus());
    const resetAgg = () => {
      $(keysEl).html('');
      $(measuresEl).html('');
      addKey();
      addMeasure('count');
      aggForm.zone.value = 'UTC';
      $('[data-dx-agg-result]').html('');
      $('[data-dx-agg-empty]').get(0).hidden = false;
    };
    // the builder in the page's language
    const relabelAgg = () =>
      $(aggForm)
        .find('.dx-agg-row')
        .each((_i, li) => {
          refreshRow(li);
          $(li).find('[data-dx-remove]').attr('aria-label', tr('removeRow'));
          const input = $(li).find('input').get(0);
          input.setAttribute('aria-label', li.hasAttribute('data-dx-key') ? tr('keyField') : tr('measureField'));
          $(li)
            .find('select')
            .attr('aria-label', li.hasAttribute('data-dx-key') ? tr('groupsBy') : tr('measureOp'));
        });
    const rowsOf = (list) => {
      const out = [];
      $(list)
        .find('.dx-agg-row')
        .each((_i, li) => {
          out.push({
            field: $(li).find('input').get(0).value.trim(),
            choice: $(li).find('select').get(0).value,
            ...(li.dataset.dxBin ? { bin: Number(li.dataset.dxBin) } : {}),
            ...(li.dataset.dxWeekStart ? { weekStart: li.dataset.dxWeekStart } : {}),
          });
        });
      return out;
    };
    const aggSpec = () => ({
      filter: aggForm.filter.value,
      groupBy: rowsOf(keysEl)
        .filter((r) => r.field)
        .map((r) => ({
          field: r.field,
          by: r.choice,
          ...(r.bin ? { bin: r.bin } : {}),
          ...(r.weekStart ? { weekStart: r.weekStart } : {}),
        })),
      measures: rowsOf(measuresEl).map((r) => ({ op: r.choice, ...(r.field ? { field: r.field } : {}) })),
      order: aggForm.order.value,
      limit: Number(aggForm.limit.value),
      ...(aggZone() !== 'UTC' ? { timeZone: aggZone() } : {}),
    });
    const aggZone = () => aggForm.zone.value.trim() || 'UTC';
    // the groups' dates read in the zone they were grouped in
    let shownZone = 'UTC';
    const fmtDate = (d, opts) => new Intl.DateTimeFormat(lang(), { timeZone: shownZone, ...opts }).format(d);
    // an ISO weekday (1 = Monday) or a month (1-12) by its name: 2024-01-01 was a Monday
    const weekdayName = (n) =>
      new Intl.DateTimeFormat(lang(), { weekday: 'long', timeZone: 'UTC' }).format(Date.UTC(2024, 0, n));
    const monthName = (n) =>
      new Intl.DateTimeFormat(lang(), { month: 'long', timeZone: 'UTC' }).format(Date.UTC(2024, n - 1, 1));
    const showKey = (v, by) => {
      if (v === null || v === undefined) return `<span class="dx-none">${esc(tr('noValue'))}</span>`;
      if (typeof v === 'number' && by === 'hourOfDay') return esc(`${String(v).padStart(2, '0')}:00`);
      if (typeof v === 'number' && by === 'weekday') return esc(weekdayName(v));
      if (typeof v === 'number' && by === 'monthOfYear') return esc(monthName(v));
      if (v instanceof Date) {
        const text =
          by === 'year'
            ? fmtDate(v, { year: 'numeric' })
            : by === 'quarter'
              ? `Q${Math.ceil(Number(fmtDate(v, { month: 'numeric' })) / 3)} ${fmtDate(v, { year: 'numeric' })}`
              : by === 'month'
                ? fmtDate(v, { month: 'long', year: 'numeric' })
                : by === 'week'
                  ? tr('weekOf', fmtDate(v, { dateStyle: 'medium' }))
                  : by === 'hour' || by === 'minute'
                    ? fmtDate(v, { dateStyle: 'medium', timeStyle: 'short' })
                    : fmtDate(v, { dateStyle: 'medium' });
        return esc(text);
      }
      return esc(typeof v === 'object' ? dbx.stringify(v, 0) : String(v));
    };
    const showValue = (v) =>
      Array.isArray(v)
        ? `<span class="dx-values">${v
            .slice(0, 8)
            .map((x) => `<span class="badge" data-variant="secondary">${showKey(x)}</span>`)
            .join('')}${v.length > 8 ? `<span class="dx-none">+${v.length - 8}</span>` : ''}</span>`
        : v instanceof Date
          ? esc(fmtDate(v, { dateStyle: 'medium' }))
          : typeof v === 'number'
            ? esc(fmt(Math.round(v * 100) / 100))
            : v === null || v === undefined
              ? '-'
              : esc(String(v));
    const keyHead = (k) =>
      k.by === 'value'
        ? k.field
        : `${k.field} · ${k.bin > 1 ? tr('every', k.bin, tr('by')[k.by]) : tr('by')[k.by]}${k.weekStart ? ` (${tr('weekFrom', weekdayName(['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'].indexOf(k.weekStart) + 1))})` : ''}`;
    const measureHead = (m) => (m.field ? `${tr('opNames')[m.op]}(${m.field})` : tr('opNames')[m.op]);
    // the builder in MongoDB's pipeline language - the pipeline dialog starts from it (runtime/db/pipeline.ts reads it back)
    const pipeline = (spec) => {
      const ref = (f) => `'$${f}'`;
      const name = (f) => f.replace(/\./g, '_');
      const zone = spec.timeZone ? `, timezone: '${spec.timeZone}'` : '';
      const PART_OP = {
        hourOfDay: '$hour',
        weekday: '$isoDayOfWeek',
        dayOfMonth: '$dayOfMonth',
        monthOfYear: '$month',
        dayOfYear: '$dayOfYear',
        isoWeek: '$isoWeek',
      };
      const keyExpr = (k) =>
        k.by === 'lower'
          ? `{ $toLower: ${ref(k.field)} }`
          : k.by === 'upper'
            ? `{ $toUpper: ${ref(k.field)} }`
            : DATE_UNITS.includes(k.by)
              ? `{ $dateTrunc: { date: ${ref(k.field)}, unit: '${k.by}'${k.bin > 1 ? `, binSize: ${k.bin}` : ''}${k.by === 'week' ? `, startOfWeek: '${k.weekStart ?? 'monday'}'` : ''}${zone} } }`
              : PART_OP[k.by]
                ? `{ ${PART_OP[k.by]}: ${zone ? `{ date: ${ref(k.field)}${zone} }` : ref(k.field)} }`
                : ref(k.field);
      const alias = (m) => (m.field ? `${m.op}_${name(m.field)}` : m.op);
      const acc = (m) =>
        m.op === 'count'
          ? m.field
            ? `{ $sum: { $cond: [{ $gt: [${ref(m.field)}, null] }, 1, 0] } }`
            : '{ $sum: 1 }'
          : m.op === 'countDistinct' || m.op === 'distinct'
            ? `{ $addToSet: ${ref(m.field)} }`
            : m.op === 'median'
              ? `{ $median: { input: ${ref(m.field)}, method: 'approximate' } }`
              : /^p\d\d$/.test(m.op)
                ? `{ $percentile: { input: ${ref(m.field)}, p: [0.${m.op.slice(1)}], method: 'approximate' } }`
                : `{ $${m.op}: ${ref(m.field)} }`;
      const stages = [];
      if (spec.filter.trim()) stages.push(`{ $match: ${spec.filter.trim()} }`);
      for (const k of spec.groupBy) if (k.by === 'each') stages.push(`{ $unwind: ${ref(k.field)} }`);
      const id = spec.groupBy.length
        ? `{ ${spec.groupBy.map((k) => `${name(k.field)}: ${keyExpr(k)}`).join(', ')} }`
        : 'null';
      stages.push(`{ $group: { _id: ${id}, ${spec.measures.map((m) => `${alias(m)}: ${acc(m)}`).join(', ')} } }`);
      const sets = spec.measures
        .filter((m) => m.op === 'countDistinct' || m.op === 'distinct')
        .map((m) =>
          m.op === 'countDistinct'
            ? `${alias(m)}: { $size: '$${alias(m)}' }`
            : `${alias(m)}: { $sortArray: { input: '$${alias(m)}', sortBy: 1 } }`,
        );
      if (sets.length) stages.push(`{ $set: { ${sets.join(', ')} } }`);
      const first = spec.measures[0];
      stages.push(
        spec.order === 'key' && spec.groupBy.length
          ? `{ $sort: { '_id.${name(spec.groupBy[0].field)}': 1 } }`
          : `{ $sort: { ${alias(first)}: ${first.op === 'distinct' ? 1 : -1} } }`,
      );
      stages.push(`{ $limit: ${spec.limit} }`);
      return `[\n  ${stages.join(',\n  ')}\n]`;
    };
    const pipelineError = (msg) => {
      $('[data-dx-pipeline-error-text]').text(msg ?? '');
      $('[data-dx-pipeline-error]').get(0).hidden = !msg;
    };
    $('[data-dx-pipeline-open]').on('click', () => {
      const spec = aggSpec();
      const text = $('#dx-pipeline-text').get(0);
      if (spec.measures.length) text.value = pipeline(spec);
      pipelineError('');
      openDialog('dx-pipeline-dialog');
    });
    $(aggForm).on('submit', async (e) => {
      e.preventDefault();
      acClose();
      const out = $('[data-dx-agg-result]').get(0);
      $('[data-dx-agg-empty]').get(0).hidden = true;
      const spec = aggSpec();
      if (!spec.measures.length) spec.measures = [{ op: 'count' }];
      try {
        if (!ZONES.has(aggZone())) throw new Error(tr('unknownZone', aggZone()));
        const r = await call('aggregate', current.db, current.coll, spec);
        shownZone = spec.timeZone ?? 'UTC';
        const numeric = r.rows.every((x) => typeof x.values[0] === 'number' || x.values[0] === null);
        const max = Math.max(1, ...r.rows.map((x) => Math.abs(Number(x.values[0]) || 0)));
        const heads = [
          ...(spec.groupBy.length
            ? spec.groupBy.map((k) => `<th class="table-head">${esc(keyHead(k))}</th>`)
            : [`<th class="table-head"></th>`]),
          ...spec.measures.map(
            (m, i) =>
              `<th class="table-head"${i === 0 && numeric ? ' style="text-align:right"' : ''}>${esc(measureHead(m))}</th>`,
          ),
          ...(numeric ? [`<th class="table-head">${esc(tr('share'))}</th>`] : []),
        ];
        const body = r.rows
          .map(
            (x) =>
              `<tr class="table-row">${(spec.groupBy.length
                ? x.keys.map((k, i) => showKey(k, spec.groupBy[i].by))
                : [esc(tr('total'))]
              )
                .map((k) => `<td class="table-cell">${k}</td>`)
                .join('')}${x.values
                .map(
                  (v) =>
                    `<td class="table-cell"${typeof v === 'number' ? ' style="text-align:right;font-variant-numeric:tabular-nums"' : ''}>${showValue(v)}</td>`,
                )
                .join(
                  '',
                )}${numeric ? `<td class="table-cell"><div class="dx-bars"><progress class="progress" max="${max}" value="${Math.abs(Number(x.values[0]) || 0)}"></progress></div></td>` : ''}</tr>`,
          )
          .join('');
        $(out).html(
          `<div class="table-container"><table class="table" data-size="sm" data-dx-agg-table><thead class="table-header"><tr class="table-row">${heads.join('')}</tr></thead><tbody class="table-body">${body}</tbody></table></div><p class="dx-hint" data-dx-agg-hint>${esc(tr('groupsShown', fmt(r.rows.length), fmt(r.groups ?? r.rows.length), r.ms))}</p>`,
        );
      } catch (err) {
        $(out).html(
          `<div class="alert" data-variant="destructive" role="alert"><div class="alert-content"><p class="alert-description">${esc(err.message)}</p></div></div>`,
        );
      }
    });
    resetAgg();

    // Schema: the Fields view (a sample's paths, their types and how often they appear) or the JSON Schema view
    // (defuss-db's analyzeSchema: a sample spread over the collection, As of = the collection at that time)
    let schemaView = 'fields';
    let schemaText = '';
    const schemaAt = $('[data-dx-schema-at]').get(0);
    const renderSchema = async () => {
      const jsonView = schemaView === 'json';
      $('[data-dx-schema-at], [data-dx-schema-at-label]').each((_i, el) => {
        el.hidden = !jsonView;
      });
      $('[data-dx-schema-error]').get(0).hidden = true;
      if (jsonView) return renderJsonSchema();
      const s = await call('schema', current.db, current.coll, 500);
      fields = asFields(s);
      $('[data-dx-schema-hint]').text(tr('sampled', fmt(s.sampled)));
      const show = (v) =>
        v instanceof Date ? v.toISOString().slice(0, 10) : typeof v === 'bigint' ? `${v}n` : JSON.stringify(v);
      $('[data-dx-schema]').html(
        `<div class="table-container"><table class="table" data-size="sm" data-dx-schema-table><thead class="table-header"><tr class="table-row"><th class="table-head">${esc(tr('field'))}</th><th class="table-head">${esc(tr('types'))}</th><th class="table-head">${esc(tr('presence'))}</th><th class="table-head">${esc(tr('examples'))}</th></tr></thead><tbody class="table-body">${s.fields
          .map(
            (f) =>
              `<tr class="table-row"><td class="table-cell"><code>${esc(f.path)}</code></td><td class="table-cell">${Object.entries(
                f.types,
              )
                .map(([t, n]) => `<span class="badge" data-variant="secondary" title="${fmt(n)}">${esc(t)}</span>`)
                .join(
                  ' ',
                )}</td><td class="table-cell"><div class="dx-bars"><progress class="progress" max="${s.sampled}" value="${f.count}"></progress><span>${Math.round((f.count / Math.max(1, s.sampled)) * 100)} %</span></div></td><td class="table-cell"><code>${esc(f.examples.map(show).join(', '))}</code></td></tr>`,
          )
          .join('')}</tbody></table></div>`,
      );
    };

    const renderJsonSchema = async () => {
      const at = schemaAt.value ? new Date(schemaAt.value) : null;
      let r;
      try {
        r = await call('jsonSchema', current.db, current.coll, {
          sample: 1000,
          ...(at && !Number.isNaN(at.getTime()) ? { at: at.toISOString() } : {}),
        });
      } catch (err) {
        $('[data-dx-schema-error-text]').text(
          /history is disabled/i.test(err.message) ? tr('schemaNoHistory') : err.message,
        );
        $('[data-dx-schema-error]').get(0).hidden = false;
        $('[data-dx-schema]').html('');
        $('[data-dx-schema-hint]').text('');
        return;
      }
      schemaText = JSON.stringify(r.schema, null, 2);
      const when = r.at ? new Date(r.at).toISOString().replace('T', ' ').slice(0, 19) + ' UTC' : '';
      $('[data-dx-schema-hint]').text(tr('schemaSampled', fmt(r.sampled), fmt(r.total), when));
      $('[data-dx-schema]').html(
        `<div class="dx-json-view"><div class="dx-json-bar" role="toolbar" aria-label="JSON Schema"><span>${esc(tr('schemaJson', fmt(r.sampled), fmt(r.total)))}</span><button class="btn" data-variant="ghost" data-size="xs" type="button" data-dx-copy-schema>${ICON.copy}${esc(tr('copyAll'))}</button></div><pre class="dx-json" data-dx-json-schema>${highlight(schemaText)}</pre></div>`,
      );
    };
    const schemaViews = $('[data-dx-schema-views]').get(0);
    $(schemaViews).on('click', async (e) => {
      const b = e.target.closest('button[value]');
      if (!b) return;
      schemaView = b.value;
      $(schemaViews)
        .find('button')
        .each((_i, x) => x.setAttribute('aria-pressed', String(x === b)));
      await renderSchema();
    });
    $(schemaAt).on('change', () => renderSchema());
    $('[data-dx-schema]').on('click', (e) => {
      if (e.target.closest('[data-dx-copy-schema]')) copyText(schemaText);
    });

    // Indexes: the definitions, a drop per index, a form to create one ("status, createdAt:-1")
    const renderIndexes = async () => {
      const list = await call('indexes', current.db, current.coll);
      $('[data-dx-indexes]').html(
        list.length
          ? `<div class="table-container"><table class="table" data-size="sm" data-dx-index-table><thead class="table-header"><tr class="table-row"><th class="table-head">${esc(tr('idxName'))}</th><th class="table-head">${esc(tr('idxFields'))}</th><th class="table-head">${esc(tr('idxUnique'))}</th><th class="table-head"></th></tr></thead><tbody class="table-body">${list
              .map(
                (i) =>
                  `<tr class="table-row"><td class="table-cell"><code>${esc(i.name)}</code></td><td class="table-cell"><code>${esc(
                    i.fields.map((f, k) => (i.order?.[k] === 'desc' ? `${f}:-1` : f)).join(', '),
                  )}</code></td><td class="table-cell">${i.unique ? '✓' : ''}</td><td class="table-cell" style="text-align:right"><button class="btn" data-variant="destructive" data-size="xs" type="button" data-dx-drop-index="${esc(i.name)}">${ICON.trash}${esc(tr('idxDrop'))}</button></td></tr>`,
              )
              .join('')}</tbody></table></div>`
          : '',
      );
      $('[data-dx-idx-empty]').get(0).hidden = list.length > 0;
    };
    $('[data-dx-indexes]').on('click', async (e) => {
      const b = e.target.closest('[data-dx-drop-index]');
      if (!b) return;
      const name = b.dataset.dxDropIndex;
      if (!(await confirmDialog(tr('dropIndexTitle', name), tr('dropIndexText')))) return;
      await call('dropIndex', current.db, current.coll, name);
      toast(tr('indexDropped', name));
      await renderIndexes();
      refreshCounts();
    });
    $('[data-dx-index-form]').on('submit', async (e) => {
      e.preventDefault();
      const f = e.currentTarget;
      const parts = f.fields.value
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean);
      const fieldsList = parts.map((p) => p.split(':')[0].trim());
      const order = parts.map((p) => (/:\s*-1$/.test(p) ? 'desc' : 'asc'));
      try {
        await call('createIndex', current.db, current.coll, {
          name: f.name.value.trim(),
          fields: fieldsList,
          ...(order.includes('desc') ? { order } : {}),
          unique: f.unique.checked,
        });
        toast(tr('indexCreated', f.name.value.trim()));
        f.reset();
        await renderIndexes();
        refreshCounts();
      } catch (err) {
        toast(err.message, 'destructive');
      }
    });

    // -- dialogs: confirm, new database, new collection, insert, import
    // okLabel: a confirmation that turns something on instead of deleting (the button says so and is not red)
    const confirmDialog = (title, text, okLabel) =>
      new Promise((resolve) => {
        const d = $('#dx-confirm').get(0);
        $('[data-dx-confirm-title]').text(title);
        $('[data-dx-confirm-text]').text(text);
        const okButton = $('[data-dx-confirm-ok]').get(0);
        if (okLabel) delete okButton.dataset.variant;
        else okButton.dataset.variant = 'destructive';
        $(okButton).find('[data-i18n-target="dx-confirm-ok"]').get(0).hidden = !!okLabel;
        const alt = $(okButton).find('[data-dx-confirm-alt]').get(0);
        alt.hidden = !okLabel;
        $(alt).text(okLabel ?? '');
        let ok = false;
        const okBtn = $('[data-dx-confirm-ok]').get(0);
        const onOk = () => (ok = true);
        okBtn.addEventListener('click', onOk, { once: true });
        d.addEventListener(
          'close',
          () => {
            okBtn.removeEventListener('click', onOk);
            resolve(ok);
          },
          { once: true },
        );
        d.showModal();
      });
    const openDialog = (id) => $(`#${id}`).get(0).showModal();
    const closeOn = (form, fn) =>
      $(form).on('submit', async (e) => {
        e.preventDefault();
        // currentTarget is null once the handler awaits: keep the form
        const el = e.currentTarget;
        try {
          if ((await fn(el)) !== false) el.closest('dialog').close();
        } catch (err) {
          toast(err.message, 'destructive');
        }
      });
    // an id as typed: a number, a quoted string or NumberLong as the shell writes them, anything else as text
    const parseId = (t) => {
      try {
        return dbx.parseDocument(`{ v: ${t} }`, 'id').v;
      } catch {
        return t;
      }
    };
    closeOn('[data-dx-restore-form]', async (f) => {
      const { db, coll } = current;
      const id = parseId(f.id.value.trim());
      if (!(await call('restore', db, coll, id))) {
        toast(tr('notDeleted', idText(id)), 'destructive');
        return false;
      }
      toast(tr('restored', idText(id)));
      // the dialog closes at once; the list and the counts follow behind it
      f.closest('dialog').close();
      runQuery();
      refreshCounts();
    });
    // a document's versions: a list (newest first), the chosen one as Extended JSON, Put back writes it as the next
    let historyOf = null;
    const showVersion = (i) => {
      const v = historyOf.versions[i];
      $('[data-dx-versions] [data-dx-version]').each((_k, b) => {
        b.setAttribute('aria-pressed', String(Number(b.dataset.dxVersion) === i));
      });
      $('[data-dx-version-json]').html(v.document ? highlight(dbx.stringify(v.document)) : '');
      // the newest version is the document as it is; a delete has nothing to put back
      $('[data-dx-put-back]').get(0).disabled = !v.document || i === 0;
      historyOf.shown = i;
    };
    const openHistory = async (db, coll, id) => {
      const versions = await call('history', db, coll, id);
      historyOf = { db, coll, id, versions, shown: 0 };
      $('[data-dx-versions-title]').text(tr('historyOf', idText(id)));
      $('[data-dx-versions-count]').text(tr('versions', versions.length));
      const when = (d) => new Intl.DateTimeFormat(lang(), { dateStyle: 'medium', timeStyle: 'medium' }).format(d);
      $('[data-dx-versions]').html(
        versions
          .map(
            (v, i) =>
              `<li><button class="btn dx-version" data-variant="ghost" data-size="sm" type="button" data-dx-version="${i}" aria-pressed="false"><span class="badge" data-variant="${v.kind === 'delete' ? 'destructive' : v.kind === 'seed' ? 'outline' : 'secondary'}">${esc(tr('versionKinds')[v.kind])}</span><span class="dx-version-when">${esc(when(v.from))}</span><small>${esc(tr('revision', v.revision))}</small></button></li>`,
          )
          .join(''),
      );
      showVersion(0);
      openDialog('dx-history-dialog');
    };
    $('[data-dx-versions]').on('click', (e) => {
      const b = e.target.closest('[data-dx-version]');
      if (b) showVersion(Number(b.dataset.dxVersion));
    });
    $('[data-dx-put-back]').on('click', async () => {
      const { db, coll, id, versions, shown } = historyOf;
      try {
        // a stamped collection sets the stamps itself and refuses an old _updatedAt (VERIFIED: "_updatedAt is
        // maintained by defuss-db; omit it or pass the stored value") - the version goes back without them
        const doc = { ...versions[shown].document };
        if (optionsOf(db, coll).timestamps) {
          delete doc._createdAt;
          delete doc._updatedAt;
        }
        await call('put', db, coll, doc);
        $('#dx-history-dialog').get(0).close();
        toast(tr('putBack', idText(id)));
        await runQuery();
        refreshCounts();
      } catch (err) {
        toast(err.message, 'destructive');
      }
    });

    // a pasted MongoDB pipeline: the builder's rows, then a run (an error stays in the dialog)
    closeOn('[data-dx-pipeline-form]', async (f) => {
      let spec;
      try {
        spec = dbx.fromPipeline(dbx.parsePipeline(f.pipeline.value));
      } catch (err) {
        pipelineError(err.message);
        return false;
      }
      aggForm.filter.value = spec.filter;
      $(keysEl).html('');
      $(measuresEl).html('');
      for (const k of spec.groupBy) addKey(k.field, k.by, k);
      for (const m of spec.measures) addMeasure(m.op, m.field ?? '');
      aggForm.zone.value = spec.timeZone ?? 'UTC';
      if (!spec.groupBy.length) addKey();
      aggForm.order.value = spec.order;
      const limit = aggForm.limit;
      if (![...limit.options].some((o) => o.value === String(spec.limit)))
        limit.append(new Option(fmt(spec.limit), String(spec.limit)));
      limit.value = String(spec.limit);
      aggForm.requestSubmit();
    });
    closeOn('[data-dx-db-form]', async (f) => {
      const db = f.db.value.trim();
      const coll = f.coll.value.trim();
      await call('createCollection', db, coll);
      f.reset();
      await loadTree();
      go(`/${db}/${coll}`);
    });
    closeOn('[data-dx-coll-form]', async (f) => {
      const db = f.db.value;
      const coll = f.coll.value.trim();
      await call('createCollection', db, coll, { history: f.history.checked, timestamps: f.timestamps.checked });
      f.coll.value = '';
      f.history.checked = f.timestamps.checked = false;
      await loadTree();
      go(`/${db}/${coll}`);
    });
    closeOn('[data-dx-insert-form]', async (f) => {
      const err = $('[data-dx-insert-error]').get(0);
      err.hidden = true;
      let value;
      try {
        if (insMode === 'tree') value = structuredClone(S.propertyTree.value(insTree));
        else {
          const text = f.doc.value.trim();
          value = text.startsWith('[')
            ? dbx.parseDocument(`{ "list": ${text} }`, 'document').list
            : dbx.parseDocument(text, 'document');
        }
      } catch (e) {
        err.hidden = false;
        $('[data-dx-insert-error-text]').text(e.message);
        return false;
      }
      const docs = Array.isArray(value) ? value : [value];
      try {
        for (const d of docs) await call('insert', insertTarget.db, insertTarget.coll, d);
      } catch (e) {
        err.hidden = false;
        $('[data-dx-insert-error-text]').text(e.message);
        return false;
      }
      toast(tr('inserted', docs.length));
      f.doc.value = '';
      paintInsert();
      if (insMode === 'tree') await showInsertTree({});
      // the collection it went into is shown: open, or its results again
      const { db, coll } = insertTarget;
      if (current.db === db && current.coll === coll) await runQuery();
      else go(`/${db}/${coll}`);
      refreshCounts();
    });
    // -- export: a database archive, or a collection's documents (JSON / NDJSON / CSV, gzip / Brotli / plain)
    const save = (bytes, name) => {
      const a = document.createElement('a');
      a.href = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' }));
      a.download = name;
      a.click();
      setTimeout(() => URL.revokeObjectURL(a.href), 1000);
    };
    const exportForm = $('[data-dx-export-form]').get(0);
    const userDbs = () => databases.filter((d) => d.name !== 'admin').map((d) => d.name);
    const exportFile = () => {
      const what = exportForm.what.value;
      if (what === 'db') return `strata-${exportForm.source.value}.dbsonl.br`;
      const coll = exportForm.source.value.split('.')[1] ?? 'collection';
      return coll + dbx.extension(exportForm.format.value, exportForm.compression.value);
    };
    const refreshExport = (fill = false) => {
      const what = exportForm.what.value;
      if (fill) {
        const options =
          what === 'db' ? userDbs() : userDbs().flatMap((d) => (collections.get(d) || []).map((c) => `${d}.${c.name}`));
        const chosen = what === 'db' ? current.db : current.coll ? `${current.db}.${current.coll}` : null;
        $(exportForm.source).html(
          options.map((o) => `<option${o === chosen ? ' selected' : ''}>${esc(o)}</option>`).join(''),
        );
      }
      $('[data-dx-ex-docs]').get(0).hidden = what === 'db';
      // the query bar's documents only for the collection it queries, and only when it filters
      const filtered =
        what === 'coll' && exportForm.source.value === `${current.db}.${current.coll}` && qform.filter.value.trim();
      $('[data-dx-ex-filter-row]').get(0).hidden = !filtered;
      if (!filtered) exportForm.filtered.checked = false;
      $('[data-dx-ex-name]').text(exportFile());
    };
    $(exportForm).on('change', (e) => refreshExport(e.target.name === 'what'));
    const openExport = () => {
      exportForm.what.value = current.coll ? 'coll' : 'db';
      refreshExport(true);
      openDialog('dx-export-dialog');
    };
    closeOn('[data-dx-export-form]', async (f) => {
      const name = exportFile();
      if (f.what.value === 'db') {
        const db = f.source.value;
        const bytes = await call('export', db);
        save(bytes, name);
        toast(tr('exported', db, sizeText(bytes.byteLength)));
        return;
      }
      const [db, coll] = f.source.value.split('.');
      const out = await call('exportCollection', db, coll, {
        format: f.format.value,
        compression: f.compression.value,
        ...(f.filtered.checked ? { filter: qform.filter.value, sort: qform.sort.value } : {}),
      });
      save(out.bytes, name);
      toast(tr('exportedDocs', fmt(out.count), name, sizeText(out.bytes.byteLength)));
    });

    // -- import: what the file is decides the rest (an archive needs a database, documents a collection too)
    const importForm = $('[data-dx-import-form]').get(0);
    let importing = null; // { bytes, kind: 'archive' | 'docs', format, compression }
    const slug = (s, lower) => {
      const x = (lower ? s.toLowerCase() : s).replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^[^A-Za-z]+/, '');
      return x.slice(0, 64) || '';
    };
    const showImport = (kind, text, sample, failed) => {
      const info = $('[data-dx-import-info]').get(0);
      info.hidden = !kind;
      if (failed) info.dataset.variant = 'destructive';
      else delete info.dataset.variant;
      $('[data-dx-import-kind]').text(text || '');
      const pre = $('[data-dx-import-sample]').get(0);
      pre.hidden = !sample;
      $(pre).text(sample || '');
      $('[data-dx-import-docs]').each((_i, el) => {
        el.hidden = kind !== 'docs';
      });
      importForm.coll.required = kind === 'docs';
    };
    const readImport = async () => {
      importing = null;
      showImport(null);
      const file = importForm.file.files[0];
      if (!file) return;
      const bytes = new Uint8Array(await file.arrayBuffer());
      const d = dbx.detect(file.name);
      const base = file.name
        .replace(/\.(gz|br)$/i, '')
        .replace(/\.(dbsonl|ndjson|jsonl|json|csv)$/i, '')
        .replace(/^strata-/, '');
      if (d.archive) {
        importing = { bytes, kind: 'archive' };
        showImport('archive', tr('kindArchive'));
        if (!importForm.db.value) importForm.db.value = slug(base, true) || 'restored';
        return;
      }
      try {
        // a copy: a call to the worker transfers its bytes, and the import sends them again
        const p = await call('previewImport', bytes.slice(), { format: d.format, compression: d.compression });
        importing = { bytes, kind: 'docs', format: d.format, compression: d.compression };
        const how = [d.format ? d.format.toUpperCase() : tr('auto'), d.compression].filter(Boolean).join(' · ');
        showImport(
          'docs',
          tr('kindDocs', fmt(p.count), how),
          p.sample.map((x) => dbx.stringify(x, 0).slice(0, 160)).join('\n'),
        );
        if (!importForm.db.value) importForm.db.value = current.db && current.db !== 'admin' ? current.db : 'imported';
        if (!importForm.coll.value) importForm.coll.value = slug(base) || 'documents';
      } catch (err) {
        showImport('error', err.message, '', true);
      }
    };
    $(importForm.file).on('change', readImport);
    const openImport = (file) => {
      importForm.reset();
      showImport(null);
      $('#dx-dbs').html(
        userDbs()
          .map((d) => `<option value="${esc(d)}"></option>`)
          .join(''),
      );
      if (file) {
        const dt = new DataTransfer();
        dt.items.add(file);
        importForm.file.files = dt.files;
        readImport();
      }
      openDialog('dx-import-dialog');
    };
    closeOn('[data-dx-import-form]', async (f) => {
      if (!importing) await readImport();
      if (!importing) return false;
      const db = f.db.value.trim();
      if (importing.kind === 'archive') {
        await call('import', db, importing.bytes);
        toast(tr('imported', db));
        importing = null;
        f.reset();
        await loadTree();
        go(`/${db}`);
        return;
      }
      const coll = f.coll.value.trim();
      const n = await call('importCollection', db, coll, importing.bytes, {
        format: importing.format,
        compression: importing.compression,
        mode: f.mode.value,
      });
      toast(tr('importedDocs', fmt(n), db, coll));
      importing = null;
      f.reset();
      await loadTree();
      if (current.db === db && current.coll === coll) await runQuery();
      else go(`/${db}/${coll}`);
    });
    // a file dropped on the app opens the import with it
    $(root).on('dragover', (e) => {
      if (e.dataTransfer?.types?.includes('Files')) e.preventDefault();
    });
    $(root).on('drop', (e) => {
      const file = e.dataTransfer?.files?.[0];
      if (!file) return;
      e.preventDefault();
      openImport(file);
    });

    // -- create: a collection in a database, documents into a collection (the tree's row buttons, the database view)
    const newCollection = (db) => {
      if (db && db !== 'admin') $('#dx-coll-db').get(0).value = db;
      openDialog('dx-coll-dialog');
    };
    let insertTarget = null;
    // the insert dialog edits in two modes: JSON (the shell's relaxed syntax, painted like the JSON view) or a
    // Property Tree that builds the record from scratch; a switch carries the value over
    const insText = $('[data-dx-insert-form] textarea[name="doc"]').get(0);
    const insPaint = $('[data-dx-ins-paint]').get(0);
    const insTree = $('[data-dx-ins-tree]').get(0);
    let insMode = 'json';
    const paintInsert = () => {
      // the trailing newline keeps the painted box as tall as a text that ends in one
      $(insPaint).html(`${highlight(insText.value)}\n`);
      insPaint.scrollTop = insText.scrollTop;
    };
    $(insText).on('input', paintInsert);
    $(insText).on('scroll', () => {
      insPaint.scrollTop = insText.scrollTop;
    });
    const showInsertTree = async (value) => {
      S.propertyTree.setValue(insTree, value);
      for (let k = 0; !insTree.store && k < 120; k++) await frame();
      S.propertyTree.expandAll(insTree, 2);
    };
    const insError = (message) => {
      $('[data-dx-insert-error]').get(0).hidden = !message;
      $('[data-dx-insert-error-text]').text(message ?? '');
    };
    const readInsert = () => {
      const text = insText.value.trim();
      if (!text) return {};
      return text.startsWith('[')
        ? dbx.parseDocument(`{ "list": ${text} }`, 'document').list
        : dbx.parseDocument(text, 'document');
    };
    // the Tree mode takes only a text that reads: caught before the Tabs' own click on the trigger (capture), the
    // text stays with the reason under it
    $('.dx-ins-tabs > .tab-list').on(
      'click',
      (e) => {
        if (!e.target.closest?.('[data-dx-ins-mode="tree"]') || insMode === 'tree') return;
        try {
          readInsert();
        } catch (err) {
          e.stopPropagation();
          e.preventDefault();
          insError(err.message);
        }
      },
      { capture: true },
    );
    $('[data-dx-ins-mode]').on('click', async (e) => {
      const next = e.currentTarget.dataset.dxInsMode;
      if (next === insMode) return;
      insMode = next;
      if (next === 'tree') {
        insError(null);
        await showInsertTree(readInsert());
      } else {
        const value = S.propertyTree.value(insTree);
        const empty = value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length;
        insText.value = empty ? '' : dbx.stringify(value);
        paintInsert();
      }
    });
    const insertInto = (db, coll) => {
      insertTarget = { db, coll };
      $('[data-dx-insert-target]').text(tr('insertInto', db, coll));
      insError(null);
      paintInsert();
      if (insMode === 'tree' && insTree.store) {
        const v = S.propertyTree.value(insTree);
        if (v == null || typeof v !== 'object') showInsertTree({});
      }
      openDialog('dx-insert-dialog');
    };

    // -- the toolbar
    $('[data-dx-action]').on('click', async (e) => {
      const act = e.currentTarget.dataset.dxAction;
      if (act === 'new-db') openDialog('dx-db-dialog');
      else if (act === 'new-coll') newCollection(current.db);
      else if (act === 'import') openImport();
      else if (act === 'export') openExport();
      else if (act === 'refresh') {
        await loadTree();
        await show(currentRoute);
      } else if (act === 'drop-db') {
        const db = current.db;
        if (!(await confirmDialog(tr('dropDbTitle', db), tr('dropDbText')))) return;
        await call('dropDatabase', db);
        await loadTree();
        go('/');
      } else if (act === 'restore') {
        $('[data-dx-restore-form]').get(0).reset();
        openDialog('dx-restore-dialog');
      } else if (act === 'enable-history' || act === 'enable-timestamps') {
        const { db, coll } = current;
        const option = act === 'enable-history' ? 'history' : 'timestamps';
        const title = tr(option === 'history' ? 'enableHistoryTitle' : 'enableTimestampsTitle', coll);
        const textOf = tr(option === 'history' ? 'enableHistoryText' : 'enableTimestampsText');
        if (!(await confirmDialog(title, textOf, tr('turnOn')))) return;
        await call('enableOption', db, coll, option);
        toast(tr(option === 'history' ? 'historyOn' : 'timestampsOn', `${db}.${coll}`));
        await loadTree();
        renderOptions();
        await runQuery();
      } else if (act === 'drop-coll') {
        const { db, coll } = current;
        if (!(await confirmDialog(tr('dropCollTitle', coll), tr('dropCollText')))) return;
        await call('dropCollection', db, coll);
        toast(tr('collDropped', `${db}.${coll}`));
        await loadTree();
        go(`/${db}`);
      }
    });

    const refreshCounts = async () => {
      await loadTree();
      await showRevision();
    };

    // -- routing: #/ the databases, #/<db> its collections, #/<db>/<collection> the collection
    let currentRoute = null;
    const show = async (to) => {
      currentRoute = to;
      const p = to?.params ?? {};
      const db = p.db && databases.some((d) => d.name === p.db) ? p.db : null;
      const coll = db && p.coll && (collections.get(db) || []).some((c) => c.name === p.coll) ? p.coll : null;
      const changed = coll !== current.coll || db !== current.db;
      current = { db, coll };
      crumbs();
      if (db) S.dataTree.reveal(tree, coll ? `c:${db}/${coll}` : `db:${db}`);
      showRevision();
      if (!db) renderHome();
      else if (!coll) renderDb();
      else {
        view('coll');
        if (changed) {
          qform.filter.value = qform.sort.value = qform.project.value = '';
          startAt = 0;
          lastResult = null;
          $(results).html('');
          $('[data-dx-count]').text('');
          $('[data-dx-agg-result]').html('');
          $('[data-dx-agg-empty]').get(0).hidden = false;
          $('[data-dx-schema]').html('');
          renderHistory();
          // the fields for the suggestions and the aggregation builder; a field's values are asked for anew
          valueCache.clear();
          resetAgg();
          call('schema', db, coll, 200).then((s) => {
            fields = asFields(s);
          });
          selectTab('docs');
          await runQuery();
          const idx = $('[aria-selected="true"][data-dx-tab]').get(0)?.dataset.dxTab;
          if (idx === 'idx') renderIndexes();
        }
      }
      root.dataset.dxShows = coll ? 'coll' : db ? 'db' : 'home';
      $('[data-dx-action="drop-db"]').get(0).hidden = !db || !!coll;
      $('[data-dx-action="drop-coll"]').get(0).hidden = !coll;
      renderOptions();
    };
    // the open collection's history and timestamps: badges, Restore, and the one-way switches that turn them on
    const renderOptions = () => {
      const o = current.coll ? optionsOf(current.db, current.coll) : {};
      $('[data-dx-opt="history"]').get(0).hidden = !o.history;
      $('[data-dx-opt="timestamps"]').get(0).hidden = !o.timestamps;
      $('[data-dx-action="restore"]').get(0).hidden = !o.history;
      $('[data-dx-action="enable-history"]').get(0).hidden = !current.coll || !!o.history;
      $('[data-dx-action="enable-timestamps"]').get(0).hidden = !current.coll || !!o.timestamps;
    };

    await loadTree();
    locale.subscribe(() => {
      showMode();
      loadTree();
      renderHelp();
      relabelAgg();
      show(currentRoute);
      renderHistory();
      // the result line and the cards' buttons are the script's words
      if (current.coll) runQuery();
    });

    const routes = [
      { id: 'home', path: '/' },
      { id: 'db', path: '/:db' },
      { id: 'coll', path: '/:db/:coll' },
    ];
    const router = createRouter({ mode: 'hash', routes, prepare: ({ to }) => ({ commit: () => show(to) }) });
    if ((await router.start()).status === 'rejected') {
      // a docs card is an about:srcdoc frame the router cannot own: the same routes match its hash
      const preview = createRouter({ mode: 'hash', routes, baseUrl: 'https://preview.invalid/' });
      const followHash = () => show(preview.resolve(location.hash.startsWith('#/') ? location.hash : '#/'));
      addEventListener('hashchange', followHash);
      await followHash();
    }
    root.dataset.dxReady = '';
    // loading: the database opens, the samples are written once - aria-busy says when it is done
    root.removeAttribute('aria-busy');
  });
</script>
```

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

<DocText>A page, not a component: it composes the library around defuss-db and keeps its own glue in one script.</DocText>

<ul class="text-sm" style="display:grid;gap:0.5rem;max-width:46rem;padding-inline-start:1.25rem">
  <li><strong>The database.</strong> defuss-db 3.1.0 stores collections as DBSONL pages in the browser's Origin Private File System. Its <code>openOPFS</code> runs only in a dedicated worker (it needs OPFS sync access handles and Web Locks), so the page talks to a worker through <code>js/db/db.js</code>: <code>connect()</code> starts it and returns one call per operation - find, aggregate, insert, put, update, delete, create and drop an index, export and import. A docs card is an opaque-origin sandbox without OPFS: there the same operations open <code>openMemory</code> on the page, and the badge in the toolbar says which one runs. The worker and its packages are bundled by <code>scripts/build-db.ts</code> (a module worker reads no import map of its page).</li>
  <li><strong>Databases and collections.</strong> A <DocLink href="data-tree.html">Data Tree</DocLink> lists them with their document counts; its filter finds a collection by name. The + in its title bar creates a database, a database row's + a collection in it and a collection row's + inserts documents (<kbd>+</kbd> on a focused row does the same). The insert dialog takes the shell's relaxed JSON, coloured as it is typed (a transparent field over its painted twin, so caret, selection and undo stay the browser's), or builds the record from scratch in a <DocLink href="property-tree.html">Property Tree</DocLink> - its Tree tab; a switch carries the value over, and a text that does not parse stays with the reason under it. A database's page is the table of its collections; Drop database and Drop collection sit at the end of the title bar of the database or collection shown. defuss-db has no drop for a collection or a database: a drop deletes the documents and indexes and records the name in the <code>admin</code> database, which also lists the databases - MongoDB's own place for them.</li>
  <li><strong>The query bar.</strong> Filter, sort and projection are MongoDB documents as the shell types them - unquoted keys, single quotes, <code>ISODate()</code>, <code>NumberLong()</code>. <code>$eq $ne $gt $gte $lt $lte $in</code> on a top-level field become defuss-db <code>filters</code>, which an index can answer; <code>$or $and $nor $not $nin $exists</code> and dot paths (<code>'address.city'</code>) become one <code>where</code> expression; <code>$regex</code> takes a prefix (<code>^Al</code>), a suffix (<code>son$</code>) or plain text, with <code>$options: 'i'</code> in any case. Arrays match as in MongoDB: a condition matches an array when one of its elements does, a dot path reaches through arrays of documents, and <code>$all</code>, <code>$size</code> and <code>$elemMatch</code> test the array itself; <code>$type</code>, <code>$mod</code> and the <code>$bits</code> operators test a value. A condition on a top-level field stays one an index answers only when an index covers that field (an index holds no arrays). The result line names the access path from <code>explain()</code> - create an index on Indexes and watch it change from a full scan. Every query field completes as you type (<code>runtime/db/complete.ts</code>, a scan of the half-written text rather than the parser, which only sees an error there): a field where a key goes, the field's operators inside <code>{"{ $ }"}</code> (by its type - no <code>$regex</code> on a number), its values from a sample where a value goes; <kbd class="kbd-group"><kbd class="kbd">Ctrl</kbd><kbd class="kbd">Space</kbd></kbd> asks, <kbd class="kbd">Tab</kbd> takes one, <kbd class="kbd-group"><kbd class="kbd">Ctrl</kbd><kbd class="kbd">Enter</kbd></kbd> runs. Braces, brackets and quotes close themselves, a syntax error is named when the typing pauses, and the ? beside the filter lists the operators.</li>
  <li><strong>Documents.</strong> In the List view every document is one row - its id and its first fields - that opens (a native <code>&lt;details&gt;</code>) into a <DocLink href="property-tree.html">Property Tree</DocLink> over a copy of it: a change marks the card modified, Save writes the whole document (<code>put</code>), Revert puts the copy back; Duplicate inserts it under a new id and opens the copy under its original, Delete asks first. Dates, BigInts and nested documents keep their types on the way through the worker (structured clone). The Table view is an editable <DocLink href="data-grid.html">Data Grid</DocLink> - a scalar cell writes one field (<code>update</code>); the JSON view shows the page as Extended JSON, coloured by token, with a Copy button above it. Scrolling to the end of the list loads the next page under it (wheel, touch, keys or the scroll bar - never a scroll a script or a focus makes); the toolbar at the foot keeps the range shown, the query plan and Previous / Next, where Next goes on after everything shown.</li>
  <li><strong>Aggregations.</strong> Keys and measures are built row by row, and each row offers what its field's type allows: text groups by its value or case-folded, a date by the start of its year, quarter, month, week, day, hour or minute or by a part of it - hour of day, weekday, day of month, month of year, day of year, ISO week - in a time zone (the Time zone field, UTC by default), an array by each element (as <code>$unwind</code>); text and dates measure the number of distinct values, the distinct values themselves and their first and last, numbers also a sum, an average, the median, the 90th, 95th and 99th percentile (exact, interpolated between the closest ranks) and the standard deviation of the population or of a sample. The keys and these measures are defuss-db 3.1's (<code>q.lower</code>, <code>q.dateTrunc</code> with a time zone, a bin and a week start, <code>q.datePart</code>, <code>q.each</code>, <code>q.countDistinct</code>, <code>q.distinct</code>, <code>q.median</code>, <code>q.percentile</code>, <code>q.stdDevPop</code>, <code>q.stdDevSamp</code>): DataView's aggregate over the raw values, folded into the groups - the query cache and the query workers stay as they are. MongoDB pipeline, beside the filter, goes the other way: a pasted pipeline (<code>$match</code>, <code>$unwind</code>, <code>$group</code> with <code>_id</code> a field, a document of fields, <code>$toLower</code> / <code>$toUpper</code>, <code>$dateTrunc</code> with <code>timezone</code>, <code>binSize</code> and <code>startOfWeek</code> (MongoDB's weeks start on Sunday unless it says otherwise, and so do the builder's rows then), <code>$dateToString</code>, <code>$year</code>, <code>$hour</code>, <code>$isoDayOfWeek</code>, <code>$dayOfMonth</code>, <code>$month</code>, <code>$dayOfYear</code> or <code>$isoWeek</code>, accumulators <code>$sum</code>, <code>$avg</code>, <code>$min</code>, <code>$max</code>, <code>$stdDevPop</code>, <code>$stdDevSamp</code>, <code>$median</code>, <code>$percentile</code> of 0.9, 0.95 or 0.99, <code>$addToSet</code> and <code>$size</code> of it, <code>$sort</code>, <code>$limit</code>, <code>$count</code>) becomes the builder's rows and runs; a stage the builder has no place for (<code>$lookup</code>, a <code>$match</code> after the <code>$group</code>) is named instead of being run differently (<code>runtime/db/pipeline.ts</code>). The dialog starts from the builder's own aggregation written as a pipeline.</li>
  <li><strong>Schema, Indexes.</strong> Schema samples 500 documents and lists every field path with its types and how often it appears; the completion and the aggregation builder read their types from it. Its JSON Schema view shows defuss-db's <code>analyzeSchema</code>: a JSON Schema (draft 2020-12) of 1,000 documents read in eight windows spread over the collection, coloured and with a Copy button - optional fields carry <code>x-presence</code>, Dates, BigInts, Maps and Sets keep a JSON type and name theirs in <code>x-dson</code>. As of reads the collection as it was then, which needs a collection that tracks history (the sample articles do; the other samples say they do not). Indexes lists the definitions and creates equality or ordered ones (<code>status, createdAt:-1</code>).</li>
  <li><strong>History and timestamps.</strong> A collection can keep every version of its documents (defuss-db's <code>$trackHistory</code>) and stamp every write with <code>_createdAt</code> and <code>_updatedAt</code> (<code>$timestamps</code>, defuss-db 3.1) - two switches in New collection, badges in the collection's title bar, and Track history / Add timestamps there for a collection that has neither yet. Both are one way: history starts with the documents as they are, stamps are written into the existing documents, and neither can be turned off again, so the switch asks first. defuss-db reports neither option; the explorer reads them from how the collection answers (<code>audit()</code> refuses without history, opening with <code>$timestamps: false</code> refuses once they are on). In a collection that tracks history, a document's History lists its versions newest first - first version, written, deleted - each readable as Extended JSON and put back as the next version, a delete says it can be undone, and Restore brings a deleted document back by its id (<code>restore()</code>). The sample <code>cms.articles</code> tracks history and stamps its writes.</li>
  <li><strong>Around it.</strong> The Query history keeps each collection's queries in this browser (<code>df$.store.persisted</code>); Keep pins one. The Operations panel logs every call with its time in milliseconds. Both start folded to their title bars (<DocLink href="panel.html">Panel</DocLink> <code>data-minimized</code>, the Border Layout region folds with them), and the Databases panel folds the same way. Export writes a collection's documents as JSON, NDJSON or CSV - Brotli (defuss-brotli, the default), gzip (the platform's CompressionStream) or plain, all of them or only what the query bar finds - or a whole database as defuss-db's Brotli archive. Import reads either: an archive into a database, documents into a collection (the format from the name, else from the content; gzip from its first bytes), after a preview of what the file holds; a document whose id is there either stops that part of the import or replaces the document. Dates and BigInts survive JSON and NDJSON as Extended JSON; CSV flattens nested fields to dot paths and reads numbers, booleans and ISO dates back as such (<code>runtime/db/transfer.ts</code>). A file dropped on the app opens the import. Routes are <code>#/</code>, <code>#/&lt;db&gt;</code> and <code>#/&lt;db&gt;/&lt;collection&gt;</code>.</li>
  <li><strong>The sample data.</strong> On the first visit the app writes three databases: <code>shop</code> (800 customers, 240 products, 12,000 orders with their items), <code>analytics</code> (30,000 events with a BigInt byte count) and <code>cms</code> (120 articles with comments) - deterministic, from a seeded random generator.</li>
</ul>

</DocPage>
