refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

+301
View File
@@ -0,0 +1,301 @@
/* Chronos Server admin — DESIGN.md tokens in light and dark (BRIEF §14.8), mockups Admin.html and AdminUsers.html.
Logical properties throughout, so right-to-left languages mirror the layout. */
:root {
color-scheme: light dark;
--bg: light-dark(#f3f3f3, #1f1f23);
--chrome: light-dark(#ffffff, #1a1a1e);
--surface: light-dark(#ffffff, #26262c);
--card: light-dark(#ffffff, #2f3038);
--card-hover: light-dark(#f5f5f5, #383943);
--card-pressed: light-dark(#ebebeb, #2a2b32);
--stroke: light-dark(#e5e5e5, #3e404a);
--stroke-strong: light-dark(#d1d1d1, #535663);
--text: light-dark(#1a1a1a, #f2f3f5);
--text-muted: light-dark(#616161, #a9aeb9);
--text-faint: light-dark(#9e9e9e, #7b818e);
--accent: light-dark(#0067c0, #4cc2ff);
--accent-hover: light-dark(#1975c5, #6fcfff);
--link-hover: light-dark(#004c8c, #6fcfff);
--on-accent: light-dark(#ffffff, #0b1b24);
--accent-selected: light-dark(#e8f1fa, rgba(76, 194, 255, .25));
--sun: light-dark(#e08a1e, #f5a524);
--sun-soft: light-dark(#fff4e5, rgba(245, 165, 36, .15));
--success: light-dark(#0f7b4f, #35c48f);
--warning: light-dark(#9a6700, #e8b339);
--error: light-dark(#c42b1c, #f0625d);
--shadow: light-dark(rgba(0, 0, 0, .18), rgba(0, 0, 0, .4));
--scrim: light-dark(rgba(0, 0, 0, .25), rgba(0, 0, 0, .6));
--radius: 6px;
--radius-card: 8px;
--font: "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, "Noto Sans", sans-serif;
--mono: Consolas, "Cascadia Mono", ui-monospace, monospace;
}
/* The header's theme button overrides the operating system's choice. */
:root[data-theme="light"] { color-scheme: light; }
:root[data-theme="dark"] { color-scheme: dark; }
* { box-sizing: border-box; }
html, body { height: 100%; }
body { margin: 0; font: 13px/1.45 var(--font); color: var(--text); background: var(--bg); }
button, input, select { font: inherit; color: inherit; }
a { color: var(--accent); }
a:hover { color: var(--link-hover); }
h1, h2 { margin: 0; }
h2 { font-size: 14px; font-weight: 600; }
.num { font-variant-numeric: tabular-nums; }
.mono { font-family: var(--mono); }
.muted { color: var(--text-muted); }
.end { text-align: end; justify-self: end; }
.nowrap { white-space: nowrap; }
.ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
.spacer { flex: 1; }
.sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
[hidden] { display: none !important; }
/* Shell */
/* The sidebar column keeps the chrome colour below the sticky sidebar on long pages. */
.shell { display: grid; grid-template-columns: 256px minmax(0, 1fr); min-height: 100vh; background: var(--chrome); }
.sidebar { display: flex; flex-direction: column; padding: 16px 12px; position: sticky; top: 0; height: 100vh; min-width: 0; }
.brand { display: flex; align-items: center; gap: 10px; padding: 4px 8px 18px; min-width: 0; }
.brand img { width: 22px; height: 22px; }
.brand strong { display: block; font-size: 14px; }
.brand span { display: block; font-size: 11px; color: var(--text-muted); }
.brand.large img { width: 40px; height: 40px; }
.brand.large h2 { font-size: 18px; }
.nav { display: grid; gap: 2px; }
.nav a { display: flex; align-items: center; gap: 10px; height: 36px; padding: 0 10px; border-radius: var(--radius); color: var(--text); text-decoration: none; }
.nav a:hover { background: var(--card-hover); color: var(--text); }
.nav a[aria-current="page"] { background: var(--accent-selected); color: var(--accent); font-weight: 600; }
.nav svg { flex: none; }
.badge { margin-inline-start: auto; min-width: 18px; padding: 0 6px; border-radius: 8px; background: var(--accent); color: var(--on-accent); font-size: 11px; font-weight: 600; text-align: center; font-variant-numeric: tabular-nums; }
.badge.quiet { background: none; color: var(--text-muted); font-weight: 400; }
.sidebar .user { margin-top: auto; border-top: 1px solid var(--stroke); padding: 8px 10px 0; display: flex; align-items: center; gap: 10px; }
.user .who { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.user .who span { color: var(--text-muted); font-size: 11px; }
/* Owner review 1: the menu collapses to its icons (the button, or Ctrl+B); the names stay for screen readers. */
.sidebar-toggle { align-self: flex-start; margin-block-end: 6px; margin-inline-start: 2px; }
.nav a { position: relative; }
/* Exactly the widths the narrow layout below leaves (fractional widths at 125 % scaling included). */
@media not all and (max-width: 900px) {
.shell.collapsed { grid-template-columns: 56px minmax(0, 1fr); }
.shell.collapsed .sidebar { padding-inline: 8px; }
.shell.collapsed .sidebar-toggle { align-self: center; margin-inline-start: 0; }
.shell.collapsed .brand > div, .shell.collapsed .user .avatar, .shell.collapsed .user .who { display: none; }
.shell.collapsed .brand { padding-inline: 9px; }
.shell.collapsed .user { padding: 8px 0 0; justify-content: center; }
.shell.collapsed .nav a { justify-content: center; padding: 0; }
.shell.collapsed .nav a > span:not(.badge) { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
.shell.collapsed .badge { position: absolute; top: 2px; inset-inline-end: 2px; min-width: 16px; padding: 0 4px; font-size: 10px; }
}
.main { display: flex; flex-direction: column; min-width: 0; background: var(--bg); border-inline-start: 1px solid var(--stroke); }
.header { position: sticky; top: 0; z-index: 5; min-height: 60px; display: flex; align-items: center; gap: 14px; padding: 0 24px; border-bottom: 1px solid var(--stroke); background: var(--chrome); }
.header h1 { font-size: 18px; font-weight: 600; white-space: nowrap; }
.header h1:focus { outline: none; }
.header .meta { flex: 0 1 auto; min-width: 0; color: var(--text-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.header .actions { display: flex; align-items: center; gap: 8px; flex: none; }
.header .language { width: auto; flex: none; }
.header > .btn { flex: none; }
.content { padding: 24px; display: grid; gap: 20px; align-content: start; min-width: 0; }
/* Controls */
.btn { height: 32px; min-width: 44px; padding: 0 12px; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--card); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; gap: 8px; text-decoration: none; color: var(--text); white-space: nowrap; }
.btn:hover { background: var(--card-hover); border-color: var(--stroke-strong); color: var(--text); }
.btn:active { background: var(--card-pressed); }
.btn:focus-visible, .chip:focus-visible, .link:focus-visible, a:focus-visible, pre.log:focus-visible,
input[type="checkbox"]:focus-visible, input[type="radio"]:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); font-weight: 600; }
.btn.primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); color: var(--on-accent); }
.btn.destructive { border-color: var(--error); color: var(--error); background: transparent; }
.btn.subtle { border-color: transparent; background: transparent; }
.btn.icon { width: 32px; min-width: 32px; padding: 0; }
.btn.small { height: 28px; padding: 0 10px; font-size: 12px; }
.btn:disabled { opacity: .4; cursor: default; }
/* Pressed toggles: accent text, a doubled accent border and bold text, so the state does not rest on colour alone. */
.btn[aria-pressed="true"], .chip[aria-pressed="true"] { color: var(--accent); border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); font-weight: 600; }
.link { border: 0; background: none; padding: 0; color: var(--text); cursor: pointer; text-align: start; }
.link:hover { color: var(--accent); }
.link.ellipsis { display: block; max-width: 100%; }
.input { height: 32px; width: 100%; padding: 0 10px; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--card); }
.input:hover { border-color: var(--stroke-strong); }
/* The transparent outline shows in Windows High Contrast, where border colours are forced. */
.input:focus { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); outline: 2px solid transparent; }
.input[aria-invalid="true"] { border-color: var(--error); box-shadow: 0 0 0 1px var(--error); }
.input:disabled, .input[readonly] { background: var(--bg); color: var(--text-muted); }
.input.small { height: 28px; width: auto; font-size: 12px; }
.input.narrow { width: 120px; }
.input.search { width: 220px; }
input[type="checkbox"], input[type="radio"] { accent-color: var(--accent); margin: 0; }
.chips, .button-row { display: flex; gap: 8px; flex-wrap: wrap; }
.chip { height: 24px; padding: 0 10px; border: 1px solid var(--stroke); border-radius: 12px; background: var(--card); font-size: 11px; cursor: pointer; }
.chip.warn { border-color: var(--warning); color: var(--warning); cursor: default; display: inline-flex; align-items: center; }
.segmented { display: inline-flex; }
.segmented .btn { border-radius: 0; margin-inline-start: -1px; }
.segmented .btn:first-child { margin-inline-start: 0; border-start-start-radius: var(--radius); border-end-start-radius: var(--radius); }
.segmented .btn:last-child { border-start-end-radius: var(--radius); border-end-end-radius: var(--radius); }
.segmented .btn[aria-pressed="true"] { position: relative; }
/* Panels and tiles */
.panel { background: var(--surface); border: 1px solid var(--stroke); border-radius: var(--radius-card); padding: 16px 18px; display: grid; gap: 10px; align-content: start; min-width: 0; }
.panel.flush { padding: 0; gap: 0; overflow-x: auto; }
.panel-head { display: flex; align-items: center; gap: 12px; min-width: 0; }
/* Headings stay on one line; the figures beside them give way first. */
.panel-head h2 { flex: 1 0 auto; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.panel-head > .ellipsis { flex: 0 1 auto; }
.panel-head.padded { padding: 12px 18px; border-bottom: 1px solid var(--stroke); }
.empty { padding: 24px 18px; color: var(--text-muted); display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.panel:not(.flush) > .empty { padding: 8px 0; }
.tiles { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 20px; }
.tile { gap: 8px; }
.tile .label { font-size: 12px; font-weight: 400; color: var(--text-muted); }
.tile .sub { font-size: 12px; color: var(--text-muted); }
.tile .value { font-size: 26px; font-weight: 600; display: flex; flex-wrap: wrap; align-items: baseline; column-gap: 6px; }
.tile .value small { font-size: 13px; font-weight: 400; color: var(--text-muted); }
.grid { display: grid; gap: 20px; }
.grid.two { grid-template-columns: repeat(auto-fit, minmax(min(380px, 100%), 1fr)); }
.grid.wide-right { grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); }
/* Bars and charts (SVG attributes only: the panel runs under a strict CSP). Progress fills from the reading start. */
svg.bar { width: 100%; height: 6px; display: block; }
svg.bar .track { fill: var(--stroke); }
svg.bar .fill { fill: var(--accent); }
svg.bar.muted .fill { fill: var(--text-faint); }
[dir="rtl"] svg.bar { transform: scaleX(-1); }
/* Charts keep a left-to-right axis in right-to-left pages (SVG ignores the HTML dir attribute). */
svg.chart { width: 100%; height: auto; max-height: 220px; direction: ltr; }
svg.chart .axis { stroke: var(--stroke); }
svg.chart .column { fill: var(--accent); }
svg.chart.sun .column { fill: var(--sun); }
svg.chart text { font: 10px var(--font); text-anchor: middle; }
svg.chart text.start { text-anchor: start; }
svg.chart text.end { text-anchor: end; }
svg.chart .value { fill: var(--text); }
svg.chart .label { fill: var(--text-muted); }
.progress-cell { display: flex; align-items: center; gap: 8px; min-width: 0; }
.progress-cell svg.bar { flex: 1 1 0; min-width: 16px; }
.progress-cell span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* Tables: ARIA rows laid out as subgrids of one grid, so every column fits its widest cell; 52 px rows in the admin. */
.table { display: grid; column-gap: 12px; min-width: 0; }
.table > [role="rowgroup"], .table .thead, .table .row { grid-column: 1 / -1; display: grid; grid-template-columns: subgrid; }
.table .thead, .table .row { align-items: center; padding: 0 18px; }
.table .thead { font-size: 11px; color: var(--text-muted); padding-block: 10px; border-bottom: 1px solid var(--stroke); white-space: nowrap; }
.table .row { min-height: 52px; border-bottom: 1px solid var(--stroke); }
.table .row:hover { background: var(--card-hover); }
.table .row.dim { color: var(--text-muted); }
.table .row.log-row { min-height: 0; padding: 0; }
.table .row.log-row:hover { background: none; }
.table [role="cell"], .table [role="columnheader"] { min-width: 0; }
.table .wide { grid-column: 1 / -1; }
.table.users { grid-template-columns: minmax(120px, 1.4fr) max-content minmax(100px, 1.3fr) minmax(70px, 1fr) max-content max-content max-content; }
.table.jobs { grid-template-columns: minmax(70px, max-content) minmax(120px, 1.6fr) minmax(60px, max-content) minmax(90px, 1fr) max-content max-content max-content; }
.table.jobs-mini { grid-template-columns: minmax(60px, max-content) minmax(120px, 1.5fr) minmax(50px, max-content) minmax(70px, 1fr) max-content max-content; }
.table.jobs-mini .thead, .table.jobs-mini .row { padding: 0; }
.table.jobs-mini .row { min-height: 40px; border-bottom: 0; }
.table.nodes { grid-template-columns: minmax(100px, 1fr) minmax(60px, max-content) minmax(100px, 1.2fr) max-content max-content max-content; }
.table.audit { grid-template-columns: max-content minmax(70px, .8fr) minmax(90px, max-content) minmax(100px, 2fr) minmax(0, max-content); }
.table.audit .row { min-height: 40px; }
.table.compact .row { min-height: 32px; padding: 0; border-bottom: 0; }
.table.compact .row:hover { background: none; }
.table.compact.stats { grid-template-columns: minmax(0, 1fr) max-content max-content; }
.table.compact.files { grid-template-columns: minmax(0, 1fr) max-content max-content max-content; }
/* Narrow panels or long translations: fitColumns() (ui.js) hides secondary columns level by level until the rows fit. */
.table.users.fit-1 { grid-template-columns: minmax(120px, 1.4fr) max-content minmax(100px, 1.3fr) max-content max-content; }
.table.users.fit-1 .col-seen, .table.users.fit-1 .col-uploads { display: none; }
.table.users.fit-2 { grid-template-columns: minmax(110px, 1fr) max-content max-content max-content; }
.table.users.fit-2 .col-quota { display: none; }
.table.users.fit-3 { grid-template-columns: minmax(100px, 1fr) max-content max-content; }
.table.users.fit-3 .col-status { display: none; }
.table.jobs.fit-1 { grid-template-columns: minmax(70px, max-content) minmax(100px, 1.6fr) minmax(80px, 1fr) max-content max-content; }
.table.jobs.fit-1 .col-node, .table.jobs.fit-1 .col-created { display: none; }
.table.jobs-mini.fit-1 { grid-template-columns: minmax(60px, max-content) minmax(80px, 1.5fr) minmax(60px, 1fr) max-content max-content; }
.table.jobs-mini.fit-1 .col-node { display: none; }
.table.nodes.fit-1 { grid-template-columns: minmax(100px, 1fr) minmax(100px, 1.2fr) max-content max-content; }
.table.nodes.fit-1 .col-owner, .table.nodes.fit-1 .col-heartbeat { display: none; }
.table.audit.fit-1 { grid-template-columns: max-content minmax(70px, .8fr) minmax(90px, max-content) minmax(100px, 2fr); }
.table.audit.fit-1 .col-from { display: none; }
.table-foot { display: flex; align-items: center; gap: 16px; padding: 10px 18px; font-size: 12px; }
.table-foot a { white-space: nowrap; }
.row-actions { display: flex; gap: 6px; justify-content: flex-end; }
.person { display: flex; align-items: center; gap: 10px; min-width: 0; }
.stack { display: flex; flex-direction: column; min-width: 0; }
.stack small { font-size: 11px; color: var(--text-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.avatar { width: 30px; height: 30px; flex: none; border-radius: 50%; background: var(--accent-selected); color: var(--accent); display: grid; place-items: center; font-weight: 600; }
.avatar.uploader { background: var(--sun-soft); color: var(--warning); }
.row.dim .avatar { background: var(--card-pressed); color: var(--text-muted); }
.state { white-space: nowrap; }
.state.running { color: var(--accent); }
.state.done { color: var(--success); }
.state.failed { color: var(--error); }
.state.paused { color: var(--warning); }
.state.queued, .state.cancelled { color: var(--text-muted); }
.activity { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: max-content minmax(0, 1fr); column-gap: 12px; row-gap: 9px; font-size: 12px; }
.activity li { grid-column: 1 / -1; display: grid; grid-template-columns: subgrid; }
pre.log { margin: 0; padding: 12px 18px; background: var(--bg); border-top: 1px solid var(--stroke); font: 12px/1.5 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; overflow: auto; max-height: 260px; text-align: left; }
pre.log.tall { max-height: 60vh; border-top: 0; }
/* Forms */
.split { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 20px; align-items: start; }
.side { width: clamp(300px, 26vw, 340px); }
.form { display: grid; gap: 12px; }
.form label, .field-label { display: grid; gap: 6px; color: var(--text-muted); }
.form label.check, label.check { display: flex; align-items: center; gap: 8px; color: var(--text); }
.form fieldset { border: 0; margin: 0; padding: 0; display: grid; gap: 8px; }
.form legend { color: var(--text-muted); margin-bottom: 8px; padding: 0; }
.form h2 { font-size: 16px; }
.inline { display: flex; align-items: center; gap: 8px; }
.buttons { display: flex; gap: 8px; justify-content: flex-end; }
.error { color: var(--error); min-height: 18px; }
.settings { display: grid; gap: 20px; }
.field { display: grid; grid-template-columns: 180px minmax(0, 420px); align-items: center; gap: 12px; color: var(--text-muted); }
.settings-form .field { grid-template-columns: 140px minmax(0, 1fr); }
/* Levels of the priority queue (owner review 1): several per row on a wide screen. */
.priorities { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(280px, 100%), 1fr)); gap: 8px 24px; }
.priorities .field { grid-template-columns: minmax(0, 1fr) 120px; }
.fingerprint { font: 12px var(--mono); color: var(--text); }
/* Dialogs and toasts */
dialog.dialog { border: 1px solid var(--stroke); border-radius: 12px; padding: 20px 22px; width: 420px; max-width: calc(100vw - 32px); background: var(--surface); color: var(--text); box-shadow: 0 8px 24px var(--shadow); }
dialog.dialog::backdrop { background: var(--scrim); }
dialog.dialog form { display: grid; gap: 14px; }
dialog.dialog h2 { font-size: 16px; overflow-wrap: anywhere; }
dialog.dialog p { margin: 0; color: var(--text-muted); }
#toasts { position: fixed; inset-inline-end: 24px; bottom: 24px; display: grid; gap: 8px; z-index: 10; }
.toast { width: 420px; max-width: calc(100vw - 48px); padding: 12px 14px; color: var(--text); background: var(--card); border: 1px solid var(--stroke); border-inline-start: 3px solid var(--accent); border-radius: var(--radius-card); box-shadow: 0 4px 16px var(--shadow); }
.toast.error { border-inline-start-color: var(--error); }
/* About */
.about dl { display: grid; grid-template-columns: 180px minmax(0, 1fr); gap: 8px 16px; margin: 0; }
.about dt { color: var(--text-muted); }
.about dd { margin: 0; overflow-wrap: anywhere; }
/* Login */
.login { min-height: 100vh; display: grid; place-items: center; padding: 16px; }
.login form { width: 360px; max-width: 100%; display: grid; gap: 14px; }
.login .brand { padding: 0 0 8px; }
.login h1 { font-size: 16px; font-weight: 600; }
.login label { display: grid; gap: 6px; color: var(--text-muted); }
.login .row { display: flex; gap: 8px; }
/* Windows High Contrast: selection and progress in system colours, since backgrounds and fills are not forced. */
@media (forced-colors: active) {
.btn[aria-pressed="true"], .chip[aria-pressed="true"], .nav a[aria-current="page"] { forced-color-adjust: none; background: Highlight; color: HighlightText; border-color: Highlight; }
svg.bar .fill, svg.chart .column { fill: Highlight; }
svg.bar .track { fill: GrayText; }
svg.chart .axis { stroke: CanvasText; }
svg.chart text { fill: CanvasText; }
}
@media (max-width: 900px) {
.shell { grid-template-columns: minmax(0, 1fr); }
.sidebar { flex-direction: row; overflow-x: auto; padding: 8px; position: static; height: auto; border-bottom: 1px solid var(--stroke); }
.main { border-inline-start: 0; }
.sidebar .brand, .sidebar .user, .sidebar-toggle { display: none; }
.nav { display: flex; gap: 4px; }
.nav a > span:not(.badge) { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
.header { position: static; flex-wrap: wrap; padding-block: 10px; }
.tiles { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.split, .grid.wide-right { grid-template-columns: minmax(0, 1fr); }
.side { width: auto; }
.field { grid-template-columns: minmax(0, 1fr); }
}
+116
View File
@@ -0,0 +1,116 @@
// Same API as the desktop clients: cookie session + CSRF header for the web admin (BRIEF §14.2).
import { culture } from "./i18n.js";
export class ApiFailure extends Error {
constructor(status, code, message, details) {
super(message);
this.status = status;
this.code = code;
this.details = details;
}
}
let currentUser = null;
function csrfToken() {
const m = document.cookie.match(/(?:^|; )chronos_csrf=([^;]+)/);
return m ? decodeURIComponent(m[1]) : "";
}
async function request(method, url, body) {
const headers = { Accept: "application/json", "Accept-Language": culture() };
if (body !== undefined) headers["Content-Type"] = "application/json";
if (method !== "GET") headers["X-CSRF-Token"] = csrfToken();
let res;
try {
res = await fetch(url, { method, headers, credentials: "same-origin", body: body === undefined ? undefined : JSON.stringify(body) });
} catch {
throw new ApiFailure(0, "unreachable", "");
}
if (res.status === 401 && url !== "/api/v1/auth/login") {
currentUser = null;
window.dispatchEvent(new Event("chronos:signed-out"));
}
if (!res.ok) {
let err = { code: "http_" + res.status, message: res.statusText };
try {
err = await res.json();
} catch {
// Not a JSON error body.
}
throw new ApiFailure(res.status, err.code, err.message, err.details);
}
return res.status === 204 ? null : res.json();
}
export const api = {
get: (url) => request("GET", url),
post: (url, body) => request("POST", url, body ?? {}),
put: (url, body) => request("PUT", url, body),
patch: (url, body) => request("PATCH", url, body),
del: (url) => request("DELETE", url),
user: () => currentUser,
/** Restores the session from the cookie; null when signed out. */
async resume() {
try {
currentUser = await request("GET", "/api/v1/auth/me");
} catch {
currentUser = null;
}
return currentUser;
},
async signIn(username, password) {
const r = await request("POST", "/api/v1/auth/login", { username, password, clientName: "admin-web", cookie: true });
currentUser = r.user;
return r;
},
async changePassword(currentPassword, newPassword) {
await request("POST", "/api/v1/auth/password", { currentPassword, newPassword });
currentUser = await request("GET", "/api/v1/auth/me");
},
async signOut() {
try {
await request("POST", "/api/v1/auth/logout", {});
} catch {
// Already signed out.
}
currentUser = null;
},
/** Server events over WebSocket (cookie session), reconnecting with back-off until stop() is called. */
events(onEvent) {
let socket = null;
let stopped = false;
let delay = 1000;
const connect = () => {
if (stopped) return;
socket = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/api/v1/events`);
socket.onopen = () => {
delay = 1000;
};
socket.onmessage = (m) => {
try {
onEvent(JSON.parse(m.data));
} catch {
// Ignore malformed or unknown events.
}
};
socket.onclose = () => {
if (stopped) return;
setTimeout(connect, delay);
delay = Math.min(delay * 2, 30000);
};
};
connect();
return {
stop() {
stopped = true;
socket?.close();
},
};
},
};
+325
View File
@@ -0,0 +1,325 @@
// Chronos Server admin panel — vanilla ES modules, no build step (BRIEF §14.8).
import { api, ApiFailure } from "./api.js";
import { t, plural, loadStrings, applyStrings, setLanguage, languages, culture } from "./i18n.js";
import { icons } from "./icons.js";
import { escapeHtml, attr, errorText, nativeName, formatNumber, fitColumns } from "./ui.js";
const app = document.getElementById("app");
const pages = ["dashboard", "users", "archive", "jobs", "settings", "logs", "about"];
const THEME_KEY = "chronos.admin.theme";
const SIDEBAR_KEY = "chronos.admin.sidebar";
/** The narrow layout of admin.css, where the menu is the top bar and does not collapse. */
const NARROW = window.matchMedia("(max-width: 900px)");
let info = null;
let events = null;
const listeners = new Set();
/** The sidebar choice made on this page, kept here too: a browser that refuses storage still keeps it across pages. */
let sidebarChoice = null;
applyTheme(storedTheme());
async function start() {
await loadStrings();
info = await api.get("/api/v1/server/info").catch(() => null);
await api.resume();
window.addEventListener("hashchange", () => render("title"));
// The menu's names or its icons alone, as on the desktop (owner review 1). A layout whose B key types another letter
// (Cyrillic, Greek, Hebrew, Arabic) is matched on the physical key, so the tooltips' Ctrl+B holds in every language. In the
// narrow layout the menu is the top bar with no toggle: the browser keeps its own Ctrl+B there.
document.addEventListener("keydown", (e) => {
if (!(e.ctrlKey || e.metaKey) || e.shiftKey || e.altKey || e.repeat || !app.querySelector(".shell") || NARROW.matches) return;
const key = e.key.toLowerCase();
if (key !== "b" && !(e.code === "KeyB" && !/^[a-z]$/.test(key))) return;
e.preventDefault();
toggleSidebar();
});
window.addEventListener("chronos:signed-out", () => {
events?.stop();
events = null;
render();
});
render();
}
function currentPage() {
const p = location.hash.replace(/^#\/?/, "").split("?")[0];
return pages.includes(p) ? p : "dashboard";
}
/** Draws the page for the session state; focus names the shell element that gets the keyboard focus. */
function render(focus = null) {
const user = api.user();
if (!user) return renderLogin();
if (user.mustChangePassword) return renderPasswordChange();
renderShell(currentPage(), focus);
}
function brand() {
return `<div class="brand"><img src="favicon.svg" alt=""><div><strong>Chronos Server</strong><span class="num">${escapeHtml(info?.name ?? "")} · v${escapeHtml(info?.version ?? "")}</span></div></div>`;
}
function renderLogin(message = "") {
document.title = `${t("Admin.Login.SignIn")} · Chronos Server`;
app.innerHTML = `
<main class="login">
<form novalidate>
${brand()}
<label><span data-i18n="Admin.Login.User"></span><input class="input" name="username" autocomplete="username" required dir="auto" data-i18n-title="Admin.Login.User.Tip"></label>
<label><span data-i18n="Admin.Login.Password"></span><input class="input" name="password" type="password" autocomplete="current-password" required data-i18n-title="Admin.Login.Password.Tip"></label>
<div class="error" role="alert">${escapeHtml(message)}</div>
<button class="btn primary" type="submit" data-i18n="Admin.Login.SignIn" data-i18n-title="Admin.Login.SignIn.Tip"></button>
</form>
</main>`;
applyStrings(app);
const form = app.querySelector("form");
const error = form.querySelector(".error");
form.addEventListener("submit", async (e) => {
e.preventDefault();
error.textContent = "";
const data = new FormData(form);
try {
const r = await api.signIn(String(data.get("username")), String(data.get("password")));
if (r.user.role !== "admin") {
await api.signOut();
error.textContent = t("Admin.Login.NotAdmin");
return;
}
render();
} catch (err) {
error.textContent = err instanceof ApiFailure && err.status === 401 ? t("Admin.Login.Failed") : errorText(err);
}
});
form.querySelector("input").focus();
}
function renderPasswordChange() {
document.title = `${t("Admin.Password.Title")} · Chronos Server`;
app.innerHTML = `
<main class="login">
<form novalidate>
${brand()}
<h1 data-i18n="Admin.Password.Title"></h1>
<label><span data-i18n="Admin.Password.Current"></span><input class="input" name="current" type="password" autocomplete="current-password" required data-i18n-title="Admin.Password.Current.Tip"></label>
<label><span data-i18n="Admin.Password.New"></span><input class="input" name="next" type="password" autocomplete="new-password" required data-i18n-title="Admin.Password.New.Tip"></label>
<label><span data-i18n="Admin.Password.Repeat"></span><input class="input" name="repeat" type="password" autocomplete="new-password" required data-i18n-title="Admin.Password.Repeat.Tip"></label>
<div class="error" role="alert"></div>
<div class="row">
<button class="btn" type="button" id="cancel" data-i18n="Admin.SignOut" data-i18n-title="Admin.SignOut.Tip"></button>
<span class="spacer"></span>
<button class="btn primary" type="submit" data-i18n="Admin.Password.Save" data-i18n-title="Admin.Password.Save.Tip"></button>
</div>
</form>
</main>`;
applyStrings(app);
const form = app.querySelector("form");
const error = form.querySelector(".error");
app.querySelector("#cancel").addEventListener("click", async () => {
await api.signOut();
render();
});
form.addEventListener("submit", async (e) => {
e.preventDefault();
const data = new FormData(form);
if (data.get("next") !== data.get("repeat")) {
error.textContent = t("Admin.Password.Mismatch");
return;
}
try {
await api.changePassword(String(data.get("current")), String(data.get("next")));
render();
} catch (err) {
error.textContent = errorText(err);
}
});
form.querySelector("input").focus();
}
function renderShell(page, focus) {
const nav = pages.map((p) => `
<a href="#/${p}" ${p === page ? 'aria-current="page"' : ""} data-i18n-title="Admin.Nav.${cap(p)}.Tip">${icons[p]}<span data-i18n="Admin.Nav.${cap(p)}"></span>
<span class="sr-only" id="badge-text-${p}"></span><span class="badge" id="badge-${p}" aria-hidden="true" hidden></span></a>`).join("");
const user = api.user();
const options = languages().map((code) => `<option value="${attr(code)}" ${code === culture() ? "selected" : ""}>${escapeHtml(nativeName(code))}</option>`).join("");
app.innerHTML = `
<div class="shell">
<aside class="sidebar">
<button class="btn icon sidebar-toggle" id="sidebar-toggle">${icons.menu}</button>
${brand()}
<nav class="nav">${nav}</nav>
<div class="user">
<div class="avatar" aria-hidden="true">${escapeHtml(user.username.slice(0, 1).toUpperCase())}</div>
<div class="who"><strong class="ellipsis" dir="auto" title="${attr(user.username)}">${escapeHtml(user.username)}</strong><span data-i18n="Admin.Role.Admin"></span></div>
<button class="btn icon" id="signout" data-i18n-title="Admin.SignOut.Tip">${icons.power}</button>
</div>
</aside>
<div class="main">
<header class="header">
<h1 id="title" tabindex="-1" data-i18n="Admin.Nav.${cap(page)}"></h1>
<span class="meta" id="meta"></span>
<span class="spacer"></span>
<span class="actions" id="actions"></span>
<select class="input language" id="language" data-i18n-title="Admin.Language.Tip">${options}</select>
<button class="btn icon" id="theme" aria-pressed="${isDark()}" data-i18n-title="Admin.Theme.Tip">${icons.moon}</button>
</header>
<main class="content" id="content"></main>
</div>
</div>`;
applyStrings(app);
applySidebar(sidebarCollapsed());
app.querySelector("#sidebar-toggle").addEventListener("click", toggleSidebar);
document.title = `${t(`Admin.Nav.${cap(page)}`)} · Chronos Server`;
app.querySelector("#signout").addEventListener("click", async () => {
events?.stop();
events = null;
await api.signOut();
render();
});
app.querySelector("#language").addEventListener("change", async (e) => {
await setLanguage(e.target.value);
render("language");
});
app.querySelector("#theme").addEventListener("click", (e) => {
const theme = isDark() ? "light" : "dark";
applyTheme(theme);
try {
localStorage.setItem(THEME_KEY, theme);
} catch {
// Only this page keeps the theme then.
}
e.currentTarget.setAttribute("aria-pressed", String(theme === "dark"));
});
if (focus) app.querySelector(`#${focus}`)?.focus();
events ??= api.events((e) => listeners.forEach((fn) => fn(e)));
listeners.clear();
pages.forEach(showBadge);
updateBadges();
listeners.add((e) => {
if (e.type === "jobState") updateBadges();
});
const meta = app.querySelector("#meta");
const content = app.querySelector("#content");
const context = {
api,
info,
/** Header text after the title (one line, full text in the tooltip); paths and file names stay left to right. */
setMeta(text, { ltr = false } = {}) {
meta.textContent = text;
meta.title = text;
meta.dir = ltr ? "ltr" : "auto";
},
actions: app.querySelector("#actions"),
onEvent: (fn) => listeners.add(fn),
};
import(`./pages/${page}.js`)
.then((m) => m.render(content, context))
.catch((err) => {
content.innerHTML = `<div class="panel empty"><span>${escapeHtml(errorText(err))}</span></div>`;
});
}
/** The menu shows icons alone: their tooltips then name the page, and the choice is kept in this browser. */
function applySidebar(collapsed) {
const shell = app.querySelector(".shell");
if (!shell) return;
shell.classList.toggle("collapsed", collapsed);
const toggle = shell.querySelector("#sidebar-toggle");
const tip = t(collapsed ? "Admin.Nav.Expand.Tip" : "Admin.Nav.Collapse.Tip");
toggle.title = tip;
toggle.setAttribute("aria-label", tip);
toggle.setAttribute("aria-expanded", String(!collapsed));
shell.querySelectorAll(".nav a").forEach((a) => {
const page = a.getAttribute("href").replace("#/", "");
const tip = t(`Admin.Nav.${cap(page)}.Tip`);
a.title = collapsed ? t("Admin.Nav.Collapsed", t(`Admin.Nav.${cap(page)}`), tip) : tip;
// Screen readers already have the name (the hidden label): their description stays the tip alone.
if (collapsed) a.setAttribute("aria-description", tip);
else a.removeAttribute("aria-description");
});
}
function sidebarCollapsed() {
if (sidebarChoice !== null) return sidebarChoice;
try {
return localStorage.getItem(SIDEBAR_KEY) === "collapsed";
} catch {
return false;
}
}
function toggleSidebar() {
const collapsed = !app.querySelector(".shell")?.classList.contains("collapsed");
sidebarChoice = collapsed;
applySidebar(collapsed);
// The page's width changed by 200 px without a window resize: the tables fit their columns again.
document.querySelectorAll(".table[data-levels]").forEach(fitColumns);
try {
localStorage.setItem(SIDEBAR_KEY, collapsed ? "collapsed" : "expanded");
} catch {
// Only this page keeps the choice then (sidebarChoice).
}
}
const badgeCounts = new Map();
let badgeTimer = null;
let badgeAgain = false;
/** Running jobs and accounts as nav badges: fetched at most every two seconds (then once more if asked meanwhile). */
function updateBadges() {
if (badgeTimer) {
badgeAgain = true;
return;
}
badgeTimer = setTimeout(() => {
badgeTimer = null;
if (badgeAgain) {
badgeAgain = false;
updateBadges();
}
}, 2000);
api.get("/api/v1/jobs?state=running&limit=100").then((page) => setBadge("jobs", page.items.length)).catch(() => {});
api.get("/api/v1/users").then((users) => setBadge("users", users.length)).catch(() => {});
}
function setBadge(page, count) {
badgeCounts.set(page, count);
showBadge(page);
}
/** The last known count on the page's nav link: a pill for the eye, a phrase for screen readers. */
function showBadge(page) {
const badge = document.getElementById(`badge-${page}`);
const count = badgeCounts.get(page);
if (!badge || count === undefined) return;
badge.hidden = count === 0;
badge.textContent = formatNumber(count);
badge.classList.toggle("quiet", page !== "jobs");
document.getElementById(`badge-text-${page}`).textContent =
count === 0 ? "" : plural(page === "jobs" ? "Admin.Jobs.RunningCount" : "Admin.Users.Accounts", count);
}
function storedTheme() {
try {
return localStorage.getItem(THEME_KEY);
} catch {
return null;
}
}
/** Light or dark as chosen in this browser; without a choice the operating system's setting applies (admin.css). */
function applyTheme(theme) {
if (theme === "light" || theme === "dark") document.documentElement.dataset.theme = theme;
}
function isDark() {
const chosen = document.documentElement.dataset.theme;
return chosen ? chosen === "dark" : matchMedia("(prefers-color-scheme: dark)").matches;
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
start();
+59
View File
@@ -0,0 +1,59 @@
// Audit entries as the dashboard and the Logs page show them: server codes (actions, job kinds, roles, changed
// fields) in words; names, titles and templates stay as recorded.
import { t, has, plural } from "./i18n.js";
import { formatBytes } from "./ui.js";
import { kindLabel, pascal } from "./jobs.js";
export function actionLabel(action) {
const key = `Admin.Logs.Action.${pascal(action)}`;
return has(key) ? t(key) : action;
}
/** One sentence per entry, e.g. "alberto signed in · Chronos 0.1.0" (unknown actions show their code). */
export function activityText(entry) {
const key = `Admin.Activity.${pascal(entry.action)}`;
return has(key) ? t(key, entry.username ?? "—", detailText(entry)) : `${entry.username ?? ""} ${entry.action}`;
}
/** The details of an entry: "verify" → "Verify", "lucia · editor" → "lucia · Editor", "role=viewer, quota=0" → "role Viewer, no quota". */
export function detailText(entry) {
const details = entry.details ?? "";
if (!details) return "";
switch (entry.action) {
case "job_created": {
const [kind, ...label] = details.split(" · ");
return [kindLabel(kind), ...label].join(" · ");
}
case "user_created": {
const [name, role] = splitLast(details);
return role === undefined ? details : `${name} · ${roleLabel(role)}`;
}
case "user_deleted": {
const [name, count] = splitLast(details);
return /^\d+$/.test(count ?? "") ? `${name} · ${plural("Admin.Logs.Reassigned", Number(count))}` : details;
}
case "user_updated":
case "sequence_updated":
return details.split(", ").map(changeLabel).join(", ");
default:
return details;
}
}
export function roleLabel(role) {
const key = `Admin.Role.${pascal(role)}`;
return has(key) ? t(key) : role;
}
function changeLabel(change) {
const [field, value] = change.split("=");
if (field === "role") return t("Admin.Logs.Field.Role", roleLabel(value ?? ""));
if (field === "quota") return Number(value) > 0 ? t("Admin.Logs.Field.Quota", formatBytes(Number(value))) : t("Admin.Logs.Field.NoQuota");
const key = `Admin.Logs.Field.${pascal(field)}`;
return has(key) ? t(key) : change;
}
function splitLast(details) {
const at = details.lastIndexOf(" · ");
return at < 0 ? [details] : [details.slice(0, at), details.slice(at + 3)];
}
+17
View File
@@ -0,0 +1,17 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">
<rect x="0" y="0" width="256" height="256" rx="56" fill="#1a1a1e"/>
<path d="M142.4 37.1 A92 92 0 0 1 161.0 42.1" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.14"/>
<path d="M185.9 56.5 A92 92 0 0 1 199.5 70.1" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.22"/>
<path d="M213.9 95.0 A92 92 0 0 1 218.9 113.6" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.3"/>
<path d="M218.9 142.4 A92 92 0 0 1 213.9 161.0" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.37"/>
<path d="M199.5 185.9 A92 92 0 0 1 185.9 199.5" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.45"/>
<path d="M161.0 213.9 A92 92 0 0 1 142.4 218.9" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.53"/>
<path d="M113.6 218.9 A92 92 0 0 1 95.0 213.9" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.61"/>
<path d="M70.1 199.5 A92 92 0 0 1 56.5 185.9" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.69"/>
<path d="M42.1 161.0 A92 92 0 0 1 37.1 142.4" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.77"/>
<path d="M37.1 113.6 A92 92 0 0 1 42.1 95.0" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.84"/>
<path d="M56.5 70.1 A92 92 0 0 1 70.1 56.5" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.92"/>
<path d="M95.0 42.1 A92 92 0 0 1 113.6 37.1" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="1.0"/>
<circle cx="152" cy="104" r="30" fill="#f5a524"/>
<circle cx="204" cy="204" r="40" fill="#1a1a1e" stroke="#4cc2ff" stroke-width="6"/><rect x="185" y="188" width="38" height="12" rx="4" fill="#4cc2ff"/><rect x="185" y="208" width="38" height="12" rx="4" fill="#4cc2ff"/>
</svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

+89
View File
@@ -0,0 +1,89 @@
// Strings come from /api/v1/i18n/{culture}, generated from the same .resx catalog as the desktop apps.
const LANGUAGE_KEY = "chronos.admin.language";
let strings = {};
/** Loads the strings of the chosen language (remembered per browser), else of the browser's language. */
export async function loadStrings(requested) {
let preferred = requested;
try {
preferred ??= localStorage.getItem(LANGUAGE_KEY);
} catch {
// Storage may be blocked; the browser language is used.
}
try {
const res = await fetch(`/api/v1/i18n/${encodeURIComponent(preferred || navigator.language || "en")}`);
strings = await res.json();
} catch {
strings = {};
}
document.documentElement.lang = strings.$culture || "en";
document.documentElement.dir = strings.$rtl === "true" ? "rtl" : "ltr";
}
export async function setLanguage(code) {
try {
localStorage.setItem(LANGUAGE_KEY, code);
} catch {
// Only this session uses the language then.
}
await loadStrings(code);
}
/** The current culture (e.g. "it"), used for numbers, dates and the Accept-Language of API calls. */
export function culture() {
return strings.$culture || "en";
}
/** Languages with translated strings, as codes. */
export function languages() {
return (strings.$languages || "en").split(",");
}
/** Localized string for key with {0}, {1}… placeholders filled from args. */
export function t(key, ...args) {
const s = strings[key];
return s === undefined ? `⟦${key}⟧` : fill(s, args);
}
/**
* Plural-aware t(): the key.one / .few / .many / .other form for count n (CLDR rules of the current language),
* with the formatted count as {0} and args as {1}…
*/
export function plural(key, n, ...args) {
const s = strings[`${key}.${pluralCategory(n)}`] ?? strings[`${key}.other`];
return s === undefined ? `⟦${key}⟧` : fill(s, [new Intl.NumberFormat(culture()).format(n), ...args]);
}
/** True when the catalog has the key (for keys built from data, e.g. audit actions). */
export function has(key) {
return strings[key] !== undefined;
}
/** Fills data-i18n (text), data-i18n-title (tooltip, also the accessible name of icon buttons) and data-i18n-placeholder. */
export function applyStrings(root) {
root.querySelectorAll("[data-i18n]").forEach((el) => {
el.textContent = t(el.dataset.i18n);
});
root.querySelectorAll("[data-i18n-title]").forEach((el) => {
el.title = t(el.dataset.i18nTitle);
if (el.classList.contains("icon")) el.setAttribute("aria-label", el.title);
});
root.querySelectorAll("[data-i18n-placeholder]").forEach((el) => {
el.placeholder = t(el.dataset.i18nPlaceholder);
});
}
function fill(s, args) {
return s.replace(/\{(\d+)(?:[,:][^}]*)?\}/g, (_, i) => String(args[Number(i)] ?? ""));
}
/**
* Plural category as Chronos.Core PluralRules folds CLDR for the catalog: "two" is written as few, and "zero" as
* many in Latvian and as other elsewhere (Arabic).
*/
function pluralCategory(n) {
const category = new Intl.PluralRules(culture()).select(n);
if (category === "two") return "few";
if (category === "zero") return culture().startsWith("lv") ? "many" : "other";
return category;
}
+18
View File
@@ -0,0 +1,18 @@
// Generated from branding/ui-icons/icons.py (same 16-px set as the desktop apps).
export const icons = {
dashboard: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 1.5 H6.0 A1 1 0 0 1 7.0 2.5 V6.0 A1 1 0 0 1 6.0 7.0 H2.5 A1 1 0 0 1 1.5 6.0 V2.5 A1 1 0 0 1 2.5 1.5 ZM10 1.5 H13.5 A1 1 0 0 1 14.5 2.5 V6.0 A1 1 0 0 1 13.5 7.0 H10 A1 1 0 0 1 9 6.0 V2.5 A1 1 0 0 1 10 1.5 ZM2.5 9 H6.0 A1 1 0 0 1 7.0 10 V13.5 A1 1 0 0 1 6.0 14.5 H2.5 A1 1 0 0 1 1.5 13.5 V10 A1 1 0 0 1 2.5 9 ZM10 9 H13.5 A1 1 0 0 1 14.5 10 V13.5 A1 1 0 0 1 13.5 14.5 H10 A1 1 0 0 1 9 13.5 V10 A1 1 0 0 1 10 9 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
users: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5 5 A3 3 0 1 0 11 5 A3 3 0 1 0 5 5 Z M2.5 14 A5.5 5.5 0 0 1 13.5 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
archive: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2 4.5 H14 V13.5 H2 Z M2 2 H14 V4.5 H2 Z M6 8 H10" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
jobs: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3 8 H13 M3 4 H13 M3 12 H9" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
settings: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5.8 8 A2.2 2.2 0 1 0 10.2 8 A2.2 2.2 0 1 0 5.8 8 Z M8 1.5 V3.5 M8 12.5 V14.5 M1.5 8 H3.5 M12.5 8 H14.5 M3.4 3.4 L4.8 4.8 M11.2 11.2 L12.6 12.6 M3.4 12.6 L4.8 11.2 M11.2 4.8 L12.6 3.4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
logs: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3.5 1.5 H9.5 L12.5 4.5 V14.5 H3.5 Z M5.5 7 H10.5 M5.5 9.5 H10.5 M5.5 12 H8.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
about: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M1.5 8 A6.5 6.5 0 1 0 14.5 8 A6.5 6.5 0 1 0 1.5 8 Z M8 7 V11 M8 4.8 V5.2" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
menu: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 4 H13.5 M2.5 8 H13.5 M2.5 12 H13.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
power: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 V7.5 M11.54 4.59 A5.5 5.5 0 1 1 4.46 4.59" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
moon: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M9.5 1.8 A6.5 6.5 0 1 0 14.2 11.2 A5.5 5.5 0 0 1 9.5 1.8 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
refresh: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M10.75 3.24 A5.5 5.5 0 1 1 4.46 3.79 M13.2 2.6 L13.2 5.3 L10.5 5.3" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
close: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M4 4 L12 12 M12 4 L4 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
plus: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 3 V13 M3 8 H13" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
copy: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M6.5 5 H13.0 A1.5 1.5 0 0 1 14.5 6.5 V13.0 A1.5 1.5 0 0 1 13.0 14.5 H6.5 A1.5 1.5 0 0 1 5 13.0 V6.5 A1.5 1.5 0 0 1 6.5 5 Z M11 5 V2.5 A1 1 0 0 0 10 1.5 H2.5 A1 1 0 0 0 1.5 2.5 V10 A1 1 0 0 0 2.5 11 H5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
search: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 7 A4.5 4.5 0 1 0 11.5 7 A4.5 4.5 0 1 0 2.5 7 Z M10.4 10.4 L14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
};
+15
View File
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Chronos Server</title>
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="admin.css">
<script type="module" src="app.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
+58
View File
@@ -0,0 +1,58 @@
// Job and node labels shared by the dashboard and the Jobs page.
import { t, has } from "./i18n.js";
import { escapeHtml, attr, bar } from "./ui.js";
const CODECS = { h264: "H.264", hevc: "HEVC", av1: "AV1" };
/** Hardware encoder families as users know them, recognised in the Media Foundation encoder names. */
const VENDORS = [[/nvidia|nvenc/i, "NVENC"], [/intel|quick ?sync|qsv/i, "QSV"], [/amd|radeon|amf/i, "AMF"]];
export function pascal(text) {
return String(text).split(/[-_]/).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
}
export function kindLabel(kind) {
const key = `Admin.Job.Kind.${pascal(kind)}`;
return has(key) ? t(key) : kind;
}
export function stateLabel(state) {
const key = `Admin.Job.State.${pascal(state)}`;
return has(key) ? t(key) : state;
}
/** Where a job runs: this server, a render node by name, or nowhere yet. */
export function nodeLabel(job, nodes) {
if (!job.nodeId) return "—";
if (job.nodeId.startsWith("server:")) return t("Admin.Jobs.Server");
return nodes.find((n) => n.id === job.nodeId)?.clientName ?? "—";
}
export function progressCell(job) {
if (job.progressTotal <= 0) return `<div class="progress-cell">${bar(0, true)}<span class="muted">—</span></div>`;
const fraction = job.progressDone / job.progressTotal;
return `<div class="progress-cell">${bar(fraction)}<span class="num">${Math.floor(fraction * 100)} %</span></div>`;
}
export function stateCell(state) {
const glyph = { running: "◐", queued: "○", paused: "❚❚", done: "●", failed: "✕", cancelled: "○" }[state] ?? "";
return `<span class="state ${attr(state)}"><span aria-hidden="true">${glyph}</span> ${escapeHtml(stateLabel(state))}</span>`;
}
/** The job log: the tail, then the error unless the tail already ends with it. */
export function logText(job) {
const tail = (job.logTail ?? "").trimEnd();
return job.error && !tail.endsWith(job.error.trim()) ? `${tail}\n${job.error}`.trim() : tail;
}
/** Node encoders by family, as "NVENC HEVC/H.264/AV1" (software encoders without a family name). */
export function encoders(node) {
const families = new Map();
for (const e of node.encoders) {
const family = e.hardware ? VENDORS.find(([pattern]) => pattern.test(e.name))?.[1] ?? "" : "";
const codec = CODECS[e.codec] ?? e.codec.toUpperCase();
const codecs = families.get(family) ?? [];
if (!codecs.includes(codec)) codecs.push(codec);
families.set(family, codecs);
}
return [...families].map(([family, codecs]) => `${family} ${codecs.join("/")}`.trim()).join(", ");
}
@@ -0,0 +1,22 @@
// About: version, API, database, uptime and the certificate fingerprint clients are asked to trust.
import { applyStrings } from "../i18n.js";
import { escapeHtml, formatDuration, fingerprint } from "../ui.js";
export async function render(root, { api, info, setMeta }) {
setMeta("");
const dashboard = await api.get("/api/v1/server/dashboard").catch(() => null);
const rows = [
["Admin.About.Name", `<span dir="auto">${escapeHtml(info?.name ?? "—")}</span>`],
["Admin.About.Version", `<span class="num" dir="ltr">${escapeHtml(info?.version ?? "—")}</span>`],
["Admin.About.Api", `<span class="num">${escapeHtml(info?.apiVersion ?? "—")}</span>`],
["Admin.About.Database", `<span dir="ltr">${escapeHtml(dashboard?.database ?? "—")}</span>`],
["Admin.About.Uptime", escapeHtml(dashboard ? formatDuration(dashboard.uptimeSeconds) : "—")],
["Admin.About.Fingerprint", fingerprint(info?.tlsFingerprint)],
];
root.innerHTML = `
<section class="panel about" aria-labelledby="about-title">
<div class="brand large"><img src="favicon.svg" alt=""><h2 id="about-title" data-i18n="Admin.About.Title"></h2></div>
<dl>${rows.map(([key, value]) => `<dt data-i18n="${key}"></dt><dd>${value}</dd>`).join("")}</dl>
</section>`;
applyStrings(root);
}
@@ -0,0 +1,119 @@
// Archive (BRIEF §14.8): naming templates, proxy policy, scan/rebuild/verify/maintenance, statistics.
import { t, plural, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, bar, columns, toast, errorText, emptyState, markInvalid, clearInvalid, invalidText, escapeReverts } from "../ui.js";
const PROXY_SIZES = [-1, 1280, 1920, 2560, 3840, 0];
const ACTIONS = ["scan", "rebuild", "verify", "maintenance"];
export async function render(root, { api, setMeta }) {
let settings;
let stats;
try {
[settings, stats] = await Promise.all([api.get("/api/v1/archive/settings"), api.get("/api/v1/archive/stats")]);
} catch (err) {
root.innerHTML = `<div class="panel empty">${escapeHtml(errorText(err))}</div>`;
return;
}
setMeta(settings.rootPath, { ltr: true });
const used = stats.capacityBytes > 0 ? (stats.capacityBytes - stats.freeBytes) / stats.capacityBytes : 0;
const sizes = PROXY_SIZES.includes(settings.proxyLongEdge) ? PROXY_SIZES : [settings.proxyLongEdge, ...PROXY_SIZES];
const proxyOptions = sizes.map((size) => `<option value="${size}" ${size === settings.proxyLongEdge ? "selected" : ""}>${escapeHtml(proxyLabel(size))}</option>`).join("");
const statsTable = (rows, labelId) => rows.length === 0 ? "" : `<div class="table compact stats" role="table" aria-labelledby="${labelId}"><div role="rowgroup">${rows.map((r) =>
`<div class="row" role="row"><span class="ellipsis" role="cell" dir="auto">${escapeHtml(r.label)}</span><span class="num end" role="cell">${formatNumber(r.count)}</span><span class="num end" role="cell">${escapeHtml(formatBytes(r.bytes))}</span></div>`).join("")}</div></div>`;
const scanButton = `<button class="btn small" data-action="scan" data-i18n="Admin.Archive.Scan" data-i18n-title="Admin.Archive.Scan.Tip"></button>`;
root.innerHTML = `
<div class="tiles">
<section class="panel tile" aria-labelledby="tile-sequences"><h2 class="label" id="tile-sequences" data-i18n="Admin.Archive.Sequences"></h2><span class="value num">${formatNumber(stats.sequences)}</span>
<span class="sub">${escapeHtml(`${plural("Admin.Dashboard.PhotoCount", stats.photos)} · ${plural("Admin.Dashboard.CameraCount", stats.cameras)}`)}</span></section>
<section class="panel tile" aria-labelledby="tile-originals"><h2 class="label" id="tile-originals" data-i18n="Admin.Archive.Originals"></h2><span class="value">${escapeHtml(formatBytes(stats.bytes))}</span>
<span class="sub num">${escapeHtml(stats.firstYear ? `${stats.firstYear}–${stats.lastYear}` : "—")}</span></section>
<section class="panel tile" aria-labelledby="tile-storage"><h2 class="label" id="tile-storage" data-i18n="Admin.Dashboard.Storage"></h2><span class="value">${escapeHtml(formatBytes(stats.freeBytes))}<small data-i18n="Admin.Archive.FreeShort"></small></span>
${bar(used)}<span class="sub">${escapeHtml(t("Admin.Dashboard.Of", formatBytes(stats.capacityBytes)))}</span></section>
<section class="panel tile" aria-labelledby="tile-health"><h2 class="label" id="tile-health" data-i18n="Admin.Archive.Health"></h2><span class="value num">${formatNumber(stats.unverifiedSequences)}<small>${escapeHtml(plural("Admin.Archive.UnverifiedUnit", stats.unverifiedSequences))}</small></span>
<span class="sub">${escapeHtml(plural("Admin.Dashboard.WithoutProxies", stats.sequencesWithoutProxies))}</span></section>
</div>
<div class="grid two">
<form class="panel form settings-form" novalidate aria-labelledby="layout-title">
<h2 id="layout-title" data-i18n="Admin.Archive.Layout"></h2>
<label class="field"><span data-i18n="Admin.Archive.Name"></span><input class="input" name="name" dir="auto" value="${attr(settings.name)}" data-i18n-title="Admin.Archive.Name.Tip"></label>
<label class="field"><span data-i18n="Admin.Archive.FolderTemplate"></span><input class="input mono" name="folderTemplate" dir="ltr" spellcheck="false" value="${attr(settings.folderTemplate)}" data-i18n-title="Admin.Archive.FolderTemplate.Tip"></label>
<label class="field"><span data-i18n="Admin.Archive.FileTemplate"></span><input class="input mono" name="fileTemplate" dir="ltr" spellcheck="false" value="${attr(settings.fileTemplate)}" data-i18n-title="Admin.Archive.FileTemplate.Tip"></label>
<label class="field"><span data-i18n="Admin.Archive.Proxies"></span><select class="input" name="proxyLongEdge" data-i18n-title="Admin.Archive.Proxies.Tip">${proxyOptions}</select></label>
<div class="buttons"><button class="btn primary" type="submit" data-i18n="Admin.Common.Save" data-i18n-title="Admin.Common.Save.Tip"></button></div>
</form>
<section class="panel" aria-labelledby="maintenance-title">
<h2 id="maintenance-title" data-i18n="Admin.Archive.Maintenance"></h2>
<div class="button-row">${ACTIONS.map((a) => `<button class="btn" data-action="${a}" data-i18n="Admin.Archive.${cap(a)}" data-i18n-title="Admin.Archive.${cap(a)}.Tip"></button>`).join("")}</div>
<h2 id="cameras-title" data-i18n="Admin.Archive.ByCamera"></h2>
${statsTable(stats.byCamera.slice(0, 8).map((c) => ({ label: c.key || "—", count: c.count, bytes: c.bytes })), "cameras-title")
|| `<p class="muted" data-i18n="Admin.Dashboard.NoData"></p>`}
</section>
</div>
<div class="grid two charts">
<section class="panel" aria-labelledby="years-title"><h2 id="years-title" data-i18n="Admin.Dashboard.ByYear"></h2>
${stats.byYear.length === 0 ? emptyState("Admin.Dashboard.NoData", scanButton)
: columns(stats.byYear.map((y) => ({ label: y.key, value: y.bytes, title: `${y.key} · ${formatBytes(y.bytes)}` })),
{ label: t("Admin.Dashboard.ByYear"), valueLabel: (i) => formatBytes(i.value) })}</section>
<section class="panel" aria-labelledby="formats-title"><h2 id="formats-title" data-i18n="Admin.Archive.ByFormat"></h2>
${statsTable(stats.byFormat.map((f) => ({ label: f.key.toUpperCase(), count: f.count, bytes: f.bytes })), "formats-title")
|| emptyState("Admin.Dashboard.NoData", scanButton)}</section>
</div>`;
applyStrings(root);
const form = root.querySelector("form");
escapeReverts(form);
form.addEventListener("submit", async (e) => {
e.preventDefault();
form.querySelectorAll("[aria-invalid]").forEach(clearInvalid);
const data = new FormData(form);
try {
settings = await api.put("/api/v1/archive/settings", {
...settings,
name: String(data.get("name")).trim(),
folderTemplate: String(data.get("folderTemplate")),
fileTemplate: String(data.get("fileTemplate")),
proxyLongEdge: Number(data.get("proxyLongEdge")),
});
// Esc now reverts to what was saved.
form.querySelectorAll("input").forEach((input) => {
input.defaultValue = input.value;
});
form.querySelectorAll("option").forEach((option) => {
option.defaultSelected = option.selected;
});
toast(t("Admin.Common.Saved"));
} catch (err) {
// Errors name the field in details; the field gets the error border and the message as its tooltip.
const field = err.details && form.elements[err.details];
const message = field ? invalidText(field) : errorText(err);
if (field) {
markInvalid(field, message);
field.focus();
}
toast(message, true);
}
});
root.querySelectorAll("[data-action]").forEach((button) => button.addEventListener("click", async () => {
button.disabled = true;
try {
await api.post(`/api/v1/archive/${button.dataset.action}`);
toast(t("Admin.Archive.Queued"));
} catch (err) {
toast(errorText(err), true);
} finally {
button.disabled = false;
button.focus();
}
}));
}
function proxyLabel(size) {
if (size === -1) return t("Admin.Archive.ProxiesOff");
if (size === 0) return t("Admin.Archive.ProxiesFull");
return t("Admin.Archive.ProxiesEdge", size);
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
@@ -0,0 +1,152 @@
// Dashboard (mockup Admin.html, BRIEF §14.8): storage, archive, jobs, render nodes, charts, activity, active jobs.
import { t, plural, applyStrings, culture } from "../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, columns, toast, errorText, emptyState, redraw, fitColumns, PROXY_WARNING } from "../ui.js";
import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders } from "../jobs.js";
import { activityText } from "../audit.js";
const SCAN_BUTTON = `<button class="btn small" data-scan data-i18n="Admin.Archive.Scan" data-i18n-title="Admin.Archive.Scan.Tip"></button>`;
export async function render(root, { api, setMeta, actions, onEvent }) {
let timer = null;
const refresh = () => {
clearTimeout(timer);
timer = setTimeout(load, 1500);
};
async function load() {
let d;
try {
d = await api.get("/api/v1/server/dashboard");
} catch (err) {
root.innerHTML = `<div class="panel empty">${escapeHtml(errorText(err))}</div>`;
return;
}
redraw(root, () => draw(d));
}
function draw(d) {
const tls = `Admin.Settings.Tls.${d.tlsMode.charAt(0).toUpperCase()}${d.tlsMode.slice(1)}`;
setMeta(t("Admin.Dashboard.Meta", formatDuration(d.uptimeSeconds), d.database, t(tls),
t(d.discovery ? "Admin.Dashboard.DiscoveryOn" : "Admin.Dashboard.DiscoveryOff")));
actions.innerHTML = d.proxyWarning ? PROXY_WARNING : "";
applyStrings(actions);
const a = d.archive;
const used = a.capacityBytes > 0 ? (a.capacityBytes - a.freeBytes) / a.capacityBytes : 0;
const online = d.nodes.filter((n) => n.state !== "offline");
const uploads = lastThirtyDays(d.uploads);
const totalUploads = uploads.reduce((s, u) => s + u.value, 0);
const peak = Math.max(0, ...uploads.map((u) => u.value));
root.innerHTML = `
<div class="tiles">
<section class="panel tile" aria-labelledby="tile-storage">
<h2 class="label" id="tile-storage" data-i18n="Admin.Dashboard.Storage"></h2>
<span class="value">${escapeHtml(formatBytes(a.capacityBytes - a.freeBytes))}<small>${escapeHtml(t("Admin.Dashboard.Of", formatBytes(a.capacityBytes)))}</small></span>
${bar(used)}
<span class="sub">${escapeHtml(t("Admin.Dashboard.Free", formatBytes(a.freeBytes)))} · ${escapeHtml(t("Admin.Dashboard.Originals", formatBytes(a.bytes)))}</span>
</section>
<section class="panel tile" aria-labelledby="tile-archive">
<h2 class="label" id="tile-archive" data-i18n="Admin.Dashboard.Archive"></h2>
<span class="value num">${formatNumber(a.sequences)}<small>${escapeHtml(plural("Admin.Dashboard.SequenceUnit", a.sequences))}</small></span>
<span class="sub">${escapeHtml(`${plural("Admin.Dashboard.PhotoCount", a.photos)} · ${plural("Admin.Dashboard.CameraCount", a.cameras)}`)}</span>
<span class="sub">${escapeHtml(plural("Admin.Dashboard.WithoutProxies", a.sequencesWithoutProxies))}</span>
</section>
<section class="panel tile" aria-labelledby="tile-jobs">
<h2 class="label" id="tile-jobs" data-i18n="Admin.Dashboard.Jobs"></h2>
<span class="value num">${formatNumber(d.jobs.running)}<small data-i18n="Admin.Dashboard.Running"></small></span>
<span class="sub">${escapeHtml([plural("Admin.Dashboard.QueuedCount", d.jobs.queued), plural("Admin.Dashboard.DoneToday", d.jobs.doneToday),
plural("Admin.Dashboard.FailedToday", d.jobs.failedToday)].join(" · "))}</span>
<span class="sub">${escapeHtml([plural("Admin.Dashboard.Parallelism", d.parallelism), ...(d.priorityQueue ? [t("Admin.Dashboard.PriorityQueue")] : [])].join(" · "))}</span>
</section>
<section class="panel tile" aria-labelledby="tile-nodes">
<h2 class="label" id="tile-nodes" data-i18n="Admin.Dashboard.Nodes"></h2>
<span class="value num">${formatNumber(online.length)}<small data-i18n="Admin.Dashboard.Online"></small></span>
${online.slice(0, 2).map((n) => `<span class="sub"><bdi>${escapeHtml(n.clientName)}</bdi> · ${escapeHtml(encoders(n))} · ${escapeHtml(stateLabel(n.state))}</span>`).join("")}
</section>
</div>
<div class="grid two charts">
<section class="panel">
<div class="panel-head"><h2 data-i18n="Admin.Dashboard.ByYear"></h2></div>
${a.byYear.length === 0 ? emptyState("Admin.Dashboard.NoData", SCAN_BUTTON)
: columns(a.byYear.map((y) => ({ label: y.key, value: y.bytes, title: `${y.key} · ${formatBytes(y.bytes)} · ${formatNumber(y.count)}` })),
{ label: t("Admin.Dashboard.ByYear"), valueLabel: (i) => formatBytes(i.value) })}
</section>
<section class="panel">
<div class="panel-head"><h2 data-i18n="Admin.Dashboard.Uploads"></h2>
<span class="muted ellipsis">${escapeHtml(t("Admin.Dashboard.UploadTotals", formatNumber(totalUploads), formatNumber(peak)))}</span></div>
${columns(uploads, { label: t("Admin.Dashboard.Uploads"), sun: true, edgeLabels: true })}
</section>
</div>
<div class="grid wide-right">
<section class="panel">
<div class="panel-head"><h2 data-i18n="Admin.Dashboard.Activity"></h2><a href="#/logs?view=audit" data-i18n="Admin.Dashboard.AllLogs" data-i18n-title="Admin.Dashboard.AllLogs.Tip"></a></div>
${d.activity.length === 0 ? emptyState("Admin.Dashboard.NoActivity", `<button class="btn small" id="reload" data-i18n="Admin.Common.Refresh" data-i18n-title="Admin.Dashboard.Refresh.Tip"></button>`)
: `<ul class="activity">${d.activity.map((e) => `<li><time class="muted num" datetime="${attr(e.at)}">${escapeHtml(formatTime(e.at))}</time><span dir="auto">${escapeHtml(activityText(e))}</span></li>`).join("")}</ul>`}
</section>
<section class="panel">
<div class="panel-head"><h2 data-i18n="Admin.Dashboard.Jobs"></h2><a href="#/jobs" data-i18n="Admin.Dashboard.Queue" data-i18n-title="Admin.Dashboard.Queue.Tip"></a></div>
${d.activeJobs.length === 0 ? emptyState("Admin.Jobs.Empty", SCAN_BUTTON) : `
<div class="table jobs-mini" data-levels="1" role="table" aria-label="${attr(t("Admin.Dashboard.Jobs"))}">
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Jobs.Kind"></span><span role="columnheader" data-i18n="Admin.Jobs.Target"></span>
<span role="columnheader" class="col-node" data-i18n="Admin.Jobs.Node"></span><span role="columnheader" data-i18n="Admin.Jobs.Progress"></span>
<span role="columnheader" data-i18n="Admin.Jobs.State"></span><span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
<div role="rowgroup">${d.activeJobs.map((j) => `
<div class="row" role="row" data-key="${attr(j.id)}">
<span class="ellipsis" role="cell">${escapeHtml(kindLabel(j.kind))}</span>
<span class="ellipsis" role="cell" dir="auto" title="${attr(j.targetLabel ?? "")}">${escapeHtml(j.targetLabel ?? "")}</span>
<span class="col-node ellipsis" role="cell" dir="auto">${escapeHtml(nodeLabel(j, d.nodes))}</span>
<span class="progress" role="cell">${progressCell(j)}</span><span role="cell">${stateCell(j.state)}</span>
<span class="row-actions" role="cell"><button class="btn small" data-cancel="${attr(j.id)}" data-i18n="${j.state === "queued" ? "Admin.Jobs.Remove" : "Admin.Jobs.Cancel"}"
data-i18n-title="${j.state === "queued" ? "Admin.Jobs.Remove.Tip" : "Admin.Jobs.Cancel.Tip"}"></button></span>
</div>`).join("")}</div>
</div>`}
</section>
</div>`;
applyStrings(root);
root.querySelectorAll("[data-cancel]").forEach((button) => button.addEventListener("click", async () => {
button.disabled = true;
try {
await api.post(`/api/v1/jobs/${button.dataset.cancel}/cancel`);
refresh();
} catch (err) {
toast(errorText(err), true);
button.disabled = false;
}
}));
root.querySelectorAll("[data-scan]").forEach((button) => button.addEventListener("click", async () => {
try {
await api.post("/api/v1/archive/scan");
toast(t("Admin.Archive.Queued"));
} catch (err) {
toast(errorText(err), true);
}
}));
root.querySelector("#reload")?.addEventListener("click", load);
root.querySelectorAll(".table[data-levels]").forEach(fitColumns);
}
onEvent((e) => {
if (e.type === "jobProgress") {
const cell = root.querySelector(`[data-key="${CSS.escape(e.jobId)}"] .progress`);
if (cell) cell.innerHTML = progressCell({ progressDone: e.done, progressTotal: e.total });
} else {
refresh();
}
});
await load();
}
/** Frames per UTC day for the last 30 days, zero-filled; the first and last days are labelled (in UTC, like the keys). */
function lastThirtyDays(days) {
const byDay = new Map(days.map((d) => [d.day, d.frames]));
const short = new Intl.DateTimeFormat(culture(), { day: "numeric", month: "short", timeZone: "UTC" });
const long = new Intl.DateTimeFormat(culture(), { dateStyle: "medium", timeZone: "UTC" });
const items = [];
const today = new Date();
for (let i = 29; i >= 0; i--) {
const day = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate() - i));
const value = byDay.get(day.toISOString().slice(0, 10)) ?? 0;
items.push({ value, label: i === 29 || i === 0 ? short.format(day) : "", title: `${long.format(day)} · ${formatNumber(value)}` });
}
return items;
}
+195
View File
@@ -0,0 +1,195 @@
// Jobs (BRIEF §14.8): queue and history with cancel/pause/resume/retry/priority, log tails, render nodes.
import { t, plural, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatTime, formatDateTime, toast, errorText, confirmDialog, emptyState, redraw, fitColumns } from "../ui.js";
import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders, logText } from "../jobs.js";
const FILTERS = ["all", "running", "queued", "paused", "failed", "done", "cancelled"];
const PRIORITIES = ["background", "normal", "user"];
export async function render(root, { api, setMeta, onEvent }) {
let filter = "all";
let jobs = [];
let nodes = [];
let running = 0;
let cursor = null;
const expanded = new Set();
let timer = null;
root.innerHTML = `
<div class="chips" role="group" aria-label="${attr(t("Admin.Jobs.State"))}">${FILTERS.map((f) => `<button class="chip" data-filter="${f}" aria-pressed="${f === filter}" data-i18n="Admin.Jobs.Filter.${cap(f)}" data-i18n-title="Admin.Jobs.Filter.Tip"></button>`).join("")}</div>
<section class="panel flush">
<div class="table jobs" data-levels="1" role="table" aria-label="${attr(t("Admin.Nav.Jobs"))}">
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Jobs.Kind"></span><span role="columnheader" data-i18n="Admin.Jobs.Target"></span>
<span role="columnheader" class="col-node" data-i18n="Admin.Jobs.Node"></span><span role="columnheader" data-i18n="Admin.Jobs.Progress"></span>
<span role="columnheader" data-i18n="Admin.Jobs.State"></span><span role="columnheader" class="col-created" data-i18n="Admin.Jobs.Created"></span>
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
<div id="rows" role="rowgroup"></div>
</div>
<div class="table-foot" id="foot" hidden><span class="spacer"></span><button class="btn small" id="more" data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button></div>
</section>
<section class="panel flush" aria-labelledby="nodes-title">
<div class="panel-head padded"><h2 id="nodes-title" data-i18n="Admin.Jobs.Nodes"></h2></div>
<div class="table nodes" data-levels="1" role="table" aria-labelledby="nodes-title">
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Jobs.NodeName"></span><span role="columnheader" class="col-owner" data-i18n="Admin.Jobs.Owner"></span>
<span role="columnheader" data-i18n="Admin.Jobs.Encoders"></span><span role="columnheader" class="col-heartbeat" data-i18n="Admin.Jobs.Heartbeat"></span>
<span role="columnheader" data-i18n="Admin.Jobs.State"></span><span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
<div id="nodes" role="rowgroup"></div>
</div>
</section>`;
applyStrings(root);
root.querySelectorAll("[data-filter]").forEach((chip) => chip.addEventListener("click", () => setFilter(chip.dataset.filter)));
root.querySelector("#more").addEventListener("click", () => load(true));
function setFilter(value) {
filter = value;
root.querySelectorAll("[data-filter]").forEach((c) => c.setAttribute("aria-pressed", String(c.dataset.filter === value)));
load();
}
async function load(more = false) {
try {
const state = filter === "all" ? "" : `&state=${filter}`;
const [page, list, active] = await Promise.all([
api.get(`/api/v1/jobs?limit=50${state}${more && cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`),
api.get("/api/v1/nodes"),
// The header counts running jobs whatever the filter shows.
api.get("/api/v1/jobs?state=running&limit=100"),
]);
jobs = more ? jobs.concat(page.items) : page.items;
cursor = page.nextCursor;
nodes = list;
running = active.items.length;
} catch (err) {
toast(errorText(err), true);
return;
}
setMeta(`${plural("Admin.Jobs.RunningCount", running)} · ${plural("Admin.Jobs.NodesOnline", nodes.filter((n) => n.state !== "offline").length)}`);
draw();
}
function draw() {
const host = root.querySelector("#rows");
redraw(host, () => {
host.innerHTML = jobs.map((j) => `
<div class="row" role="row" data-key="${attr(j.id)}">
<span role="cell"><button class="link ellipsis" data-toggle="${attr(j.id)}" aria-expanded="${expanded.has(j.id)}" aria-controls="log-${attr(j.id)}" data-i18n-title="Admin.Jobs.Log.Tip">${escapeHtml(kindLabel(j.kind))}</button></span>
<span class="ellipsis" role="cell" dir="auto" title="${attr(j.targetLabel ?? "")}">${escapeHtml(j.targetLabel ?? "")}</span>
<span class="col-node ellipsis" role="cell" dir="auto">${escapeHtml(nodeLabel(j, nodes))}</span>
<span class="progress" role="cell">${progressCell(j)}</span>
<span role="cell">${stateCell(j.state)}</span>
<span class="col-created muted nowrap" role="cell">${escapeHtml(formatTime(j.created))}</span>
<span class="row-actions" role="cell">${buttons(j)}</span>
</div>
${expanded.has(j.id) ? `<div class="row log-row" role="row"><pre class="log wide" role="cell" id="log-${attr(j.id)}" dir="ltr">${escapeHtml(logText(j))}</pre></div>` : ""}`).join("")
|| `<div class="row" role="row"><div class="wide" role="cell">${filter === "all"
? emptyState("Admin.Jobs.Empty", `<button class="btn small" id="scan" data-i18n="Admin.Archive.Scan" data-i18n-title="Admin.Archive.Scan.Tip"></button>`)
: emptyState("Admin.Jobs.Empty", `<button class="btn small" id="show-all" data-i18n="Admin.Jobs.ShowAll" data-i18n-title="Admin.Jobs.ShowAll.Tip"></button>`)}</div></div>`;
applyStrings(host);
});
host.querySelectorAll("[data-toggle]").forEach((b) => b.addEventListener("click", () => {
const id = b.dataset.toggle;
if (!expanded.delete(id)) expanded.add(id);
draw();
}));
host.querySelectorAll("[data-act]").forEach((b) => b.addEventListener("click", () => act(b.closest("[data-key]").dataset.key, b.dataset.act)));
host.querySelectorAll("select[data-priority]").forEach((s) => s.addEventListener("change", () => setPriority(s.dataset.priority, s.value)));
host.querySelector("#show-all")?.addEventListener("click", () => setFilter("all"));
host.querySelector("#scan")?.addEventListener("click", scan);
root.querySelector("#foot").hidden = !cursor;
const nodeHost = root.querySelector("#nodes");
redraw(nodeHost, () => {
nodeHost.innerHTML = nodes.map((n) => `
<div class="row" role="row" data-key="${attr(n.id)}">
<span class="ellipsis" role="cell" dir="auto" title="${attr(n.clientName)}"><strong>${escapeHtml(n.clientName)}</strong></span>
<span class="col-owner ellipsis" role="cell" dir="auto">${escapeHtml(n.username)}</span>
<span class="ellipsis" role="cell" title="${attr(n.encoders.map((e) => e.name).join(", "))}">${escapeHtml(encoders(n))}</span>
<span class="col-heartbeat muted nowrap" role="cell">${escapeHtml(formatDateTime(n.lastHeartbeat))}</span>
<span class="state ${n.state === "offline" ? "cancelled" : n.state === "busy" ? "running" : "done"}" role="cell"><span aria-hidden="true">${n.state === "offline" ? "○" : "●"}</span> ${escapeHtml(stateLabel(n.state))}</span>
<span class="row-actions" role="cell"><button class="btn small destructive" data-forget="${attr(n.id)}" data-i18n="Admin.Jobs.Forget" data-i18n-title="Admin.Jobs.Forget.Tip"></button></span>
</div>`).join("")
|| `<div class="row" role="row"><div class="wide" role="cell">${emptyState("Admin.Jobs.NoNodes",
`<a class="btn small" href="#/users" data-i18n="Admin.Nav.Users" data-i18n-title="Admin.Jobs.NoNodes.Tip"></a>`)}</div></div>`;
applyStrings(nodeHost);
});
nodeHost.querySelectorAll("[data-forget]").forEach((b) => b.addEventListener("click", () => forget(nodes.find((n) => n.id === b.dataset.forget))));
root.querySelectorAll(".table[data-levels]").forEach(fitColumns);
}
function buttons(job) {
const button = (act, key) => `<button class="btn small" data-act="${act}" data-i18n="Admin.Jobs.${key}" data-i18n-title="Admin.Jobs.${key}.Tip"></button>`;
const priority = `<select class="input small" data-priority="${attr(job.id)}" data-i18n-title="Admin.Jobs.Priority.Tip">${PRIORITIES.map((p) =>
`<option value="${p}" ${p === job.priority ? "selected" : ""}>${escapeHtml(t(`Admin.Jobs.Priority.${cap(p)}`))}</option>`).join("")}</select>`;
switch (job.state) {
case "running": return button("pause", "Pause") + button("cancel", "Cancel");
case "queued": return priority + button("pause", "Pause") + button("cancel", "Remove");
case "paused": return priority + button("resume", "Resume") + button("cancel", "Cancel");
case "failed":
case "cancelled": return button("retry", "Retry");
default: return "";
}
}
async function act(id, action) {
try {
await api.post(`/api/v1/jobs/${id}/${action}`);
await load();
} catch (err) {
toast(errorText(err), true);
}
}
async function setPriority(id, priority) {
try {
await api.post(`/api/v1/jobs/${id}/priority`, { priority });
} catch (err) {
toast(errorText(err), true);
}
}
async function scan() {
try {
await api.post("/api/v1/archive/scan");
toast(t("Admin.Archive.Queued"));
} catch (err) {
toast(errorText(err), true);
}
}
async function forget(node) {
const confirmed = await confirmDialog({
title: t("Admin.Jobs.ForgetTitle", node.clientName),
confirm: t("Admin.Jobs.Forget"),
confirmTip: t("Admin.Jobs.Forget.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
});
if (!confirmed) return;
try {
await api.del(`/api/v1/nodes/${node.id}`);
await load();
} catch (err) {
toast(errorText(err), true);
}
}
onEvent((e) => {
if (e.type === "jobProgress") {
const job = jobs.find((j) => j.id === e.jobId);
if (job) {
job.progressDone = e.done;
job.progressTotal = e.total;
const cell = root.querySelector(`[data-key="${CSS.escape(e.jobId)}"] .progress`);
if (cell) cell.innerHTML = progressCell(job);
}
} else if (e.type === "jobState" || e.type === "nodeState") {
clearTimeout(timer);
timer = setTimeout(load, 800);
}
});
await load();
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
+116
View File
@@ -0,0 +1,116 @@
// Logs (BRIEF §14.8): server log tail and downloads, diagnostics bundle, sign-in log (with failed attempts), audit log.
import { t, plural, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatBytes, formatDateTime, toast, errorText, routeParams, emptyState, fitColumns } from "../ui.js";
import { actionLabel, detailText } from "../audit.js";
const VIEWS = ["server", "signins", "audit"];
const LINES = [100, 300, 1000];
export async function render(root, { api, setMeta, actions }) {
let view = VIEWS.includes(routeParams().get("view")) ? routeParams().get("view") : "server";
let lines = 300;
let audit = [];
let cursor = null;
actions.innerHTML = `<div class="segmented" role="group" aria-label="${attr(t("Admin.Nav.Logs"))}">${VIEWS.map((v) =>
`<button class="btn" data-view="${v}" aria-pressed="${v === view}" data-i18n="Admin.Logs.View.${cap(v)}" data-i18n-title="Admin.Logs.View.${cap(v)}.Tip"></button>`).join("")}</div>`;
applyStrings(actions);
actions.querySelectorAll("[data-view]").forEach((b) => b.addEventListener("click", () => {
view = b.dataset.view;
actions.querySelectorAll("[data-view]").forEach((x) => x.setAttribute("aria-pressed", String(x === b)));
history.replaceState(null, "", `#/logs?view=${view}`);
show();
}));
async function show() {
setMeta("");
if (view === "server") await showServerLog();
else await showAudit(false);
}
async function showServerLog() {
let tail;
let files;
try {
[tail, files] = await Promise.all([api.get(`/api/v1/logs?lines=${lines}`), api.get("/api/v1/logs/files")]);
} catch (err) {
toast(errorText(err), true);
return;
}
setMeta(tail.file, { ltr: true });
root.innerHTML = `
<section class="panel flush">
<div class="panel-head padded">
<select class="input small" id="lines" data-i18n-title="Admin.Logs.Lines.Tip">${LINES.map((n) => `<option value="${n}" ${n === lines ? "selected" : ""}>${escapeHtml(plural("Admin.Logs.LastLines", n))}</option>`).join("")}</select>
<span class="spacer"></span>
<button class="btn small" id="refresh" data-i18n="Admin.Common.Refresh" data-i18n-title="Admin.Logs.Refresh.Tip"></button>
<a class="btn small" href="/api/v1/server/diagnostics" download data-i18n="Admin.Logs.Diagnostics" data-i18n-title="Admin.Logs.Diagnostics.Tip"></a>
</div>
<pre class="log tall" dir="ltr" tabindex="0" aria-label="${attr(t("Admin.Logs.View.Server"))}">${escapeHtml(tail.lines.join("\n"))}</pre>
</section>
<section class="panel" aria-labelledby="files-title">
<h2 id="files-title" data-i18n="Admin.Logs.Files"></h2>
<div class="table compact files" role="table" aria-labelledby="files-title"><div role="rowgroup">${files.map((f) => `
<div class="row" role="row" data-key="${attr(f.name)}"><span class="mono ellipsis" role="cell" dir="ltr">${escapeHtml(f.name)}</span><span class="num end" role="cell">${escapeHtml(formatBytes(f.size))}</span>
<span class="muted nowrap" role="cell">${escapeHtml(formatDateTime(f.modified))}</span>
<span role="cell"><a class="btn small" href="/api/v1/logs/files/${encodeURIComponent(f.name)}" download="${attr(f.name)}" data-i18n="Admin.Logs.Download" data-i18n-title="Admin.Logs.Download.Tip"></a></span></div>`).join("")}
</div></div>
</section>`;
applyStrings(root);
const pre = root.querySelector("pre");
pre.scrollTop = pre.scrollHeight;
root.querySelector("#lines").addEventListener("change", async (e) => {
lines = Number(e.target.value);
await showServerLog();
root.querySelector("#lines").focus();
});
root.querySelector("#refresh").addEventListener("click", async () => {
await showServerLog();
root.querySelector("#refresh").focus();
});
}
async function showAudit(more) {
const action = view === "signins" ? "&action=login,login_failed" : "";
try {
const page = await api.get(`/api/v1/audit?limit=100${action}${more && cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
audit = more ? audit.concat(page.items) : page.items;
cursor = page.nextCursor;
} catch (err) {
toast(errorText(err), true);
return;
}
root.innerHTML = `
<section class="panel flush">
<div class="table audit" data-levels="1" role="table" aria-label="${attr(t(view === "signins" ? "Admin.Logs.View.Signins" : "Admin.Logs.View.Audit"))}">
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Logs.When"></span><span role="columnheader" data-i18n="Admin.Logs.Who"></span>
<span role="columnheader" data-i18n="Admin.Logs.What"></span><span role="columnheader" data-i18n="Admin.Logs.Details"></span>
<span role="columnheader" class="col-from" data-i18n="Admin.Logs.From"></span></div>
<div role="rowgroup">${audit.map((e) => {
const details = detailText(e);
return `
<div class="row" role="row" data-key="${attr(e.id)}"><span class="num nowrap" role="cell">${escapeHtml(formatDateTime(e.at))}</span>
<span class="ellipsis" role="cell" dir="auto" title="${attr(e.username ?? "")}">${escapeHtml(e.username ?? "—")}</span>
<span class="ellipsis" role="cell">${e.action === "login_failed" ? `<span class="state failed"><span aria-hidden="true">✕</span> ${escapeHtml(actionLabel(e.action))}</span>` : escapeHtml(actionLabel(e.action))}</span>
<span class="ellipsis" role="cell" dir="auto" title="${attr(details)}">${escapeHtml(details)}</span>
<span class="col-from mono ellipsis" role="cell" dir="ltr">${escapeHtml(e.remoteAddress ?? "")}</span></div>`;
}).join("") || `<div class="row" role="row"><div class="wide" role="cell">${emptyState("Admin.Logs.Empty",
`<button class="btn small" id="reload" data-i18n="Admin.Common.Refresh" data-i18n-title="Admin.Logs.Refresh.Tip"></button>`)}</div></div>`}</div>
</div>
${cursor ? `<div class="table-foot"><span class="spacer"></span><button class="btn small" id="more" data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button></div>` : ""}
</section>`;
applyStrings(root);
fitColumns(root.querySelector(".table.audit"));
root.querySelector("#more")?.addEventListener("click", async () => {
await showAudit(true);
root.querySelector("#more")?.focus();
});
root.querySelector("#reload")?.addEventListener("click", () => showAudit(false));
}
await show();
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
@@ -0,0 +1,150 @@
// Settings (BRIEF §14.8): server name, ports, TLS, discovery, jobs, limits, language, retention. Values fixed by environment
// variables are read-only here; ports, TLS, chunk size and job history apply at the next restart. Jobs run one at a time
// (owner review 1): the parallelism (photos at once) and the priority queue apply at once.
import { t, applyStrings, languages } from "../i18n.js";
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, markInvalid, clearInvalid, invalidText, escapeReverts, PROXY_WARNING } from "../ui.js";
import { kindLabel } from "../jobs.js";
/** Setting → environment variable that can fix it (BRIEF §14.9). */
const VARIABLES = {
serverName: "CHRONOS_SERVER_NAME", httpPort: "CHRONOS_HTTP_PORT", httpsPort: "CHRONOS_HTTPS_PORT", tlsMode: "CHRONOS_TLS_MODE",
tlsCert: "CHRONOS_TLS_CERT", tlsKey: "CHRONOS_TLS_KEY", language: "CHRONOS_LANG", parallelism: "CHRONOS_PARALLELISM", discovery: "CHRONOS_DISCOVERY",
priorityQueue: "CHRONOS_PRIORITY_QUEUE",
};
/** Levels of the priority queue, highest first. */
const LEVELS = ["high", "normal", "low"];
/** Settings the server names in error details whose field here has another name. */
const FIELDS = { maxuploadbytes: "maxUploadMb", chunksizebytes: "chunkSizeMib" };
const PEM_FILES = ["tlsCert", "tlsKey"];
const MB = 1e6;
const MIB = 1024 * 1024;
export async function render(root, { api, info, setMeta, actions }) {
let settings;
try {
settings = await api.get("/api/v1/server/settings");
} catch (err) {
root.innerHTML = `<div class="panel empty">${escapeHtml(errorText(err))}</div>`;
return;
}
setMeta("");
// In the header, like the other pages' main action, so toasts never cover it.
actions.innerHTML = `<button class="btn primary" type="submit" form="settings-form" data-i18n="Admin.Common.Save" data-i18n-title="Admin.Common.Save.Tip"></button>`;
applyStrings(actions);
const locked = (name) => settings.locked.some((l) => l.toLowerCase() === name.toLowerCase());
const lock = (name) => locked(name) ? `disabled title="${attr(t("Admin.Settings.Locked.Tip", VARIABLES[name] ?? name))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`;
const field = (name, input) => `<label class="field"><span data-i18n="Admin.Settings.${cap(name)}"></span>${input}</label>`;
const number = (name, value, attrs = "") => field(name, `<input class="input narrow num" type="number" name="${name}" value="${attr(value)}" ${attrs} ${lock(name)}>`);
const text = (name, value, attrs = "dir=\"auto\"") => field(name, `<input class="input" name="${name}" value="${attr(value ?? "")}" ${attrs} ${lock(name)}>`);
function draw() {
root.innerHTML = `
<form class="settings" id="settings-form" novalidate>
<section class="panel" aria-labelledby="server-title">
<div class="panel-head"><h2 id="server-title" data-i18n="Admin.Settings.Server"></h2>
${settings.restartRequired ? `<span class="chip warn" data-i18n="Admin.Settings.Restart" data-i18n-title="Admin.Settings.Restart.Tip"></span>` : ""}</div>
${text("serverName", settings.serverName)}
${field("language", `<select class="input" name="language" ${lock("language")}>${languages().concat(languages().includes(settings.language) ? [] : [settings.language])
.map((code) => `<option value="${attr(code)}" ${code === settings.language ? "selected" : ""}>${escapeHtml(nativeName(code))}</option>`).join("")}</select>`)}
${field("discovery", `<span class="inline"><input type="checkbox" name="discovery" ${settings.discovery ? "checked" : ""} ${lock("discovery")}></span>`)}
</section>
<section class="panel" aria-labelledby="jobs-title">
<h2 id="jobs-title" data-i18n="Admin.Settings.Jobs"></h2>
${number("parallelism", settings.parallelism, 'min="1" max="64"')}
${field("priorityQueue", `<span class="inline"><input type="checkbox" name="priorityQueue" ${settings.priorityQueue ? "checked" : ""} ${lock("priorityQueue")}></span>`)}
<div class="priorities" ${settings.priorityQueue ? "" : "hidden"}>
${settings.jobPriorities.map((p) => `<label class="field"><span>${escapeHtml(kindLabel(p.kind))}</span>
<select class="input narrow" name="priority:${attr(p.kind)}" title="${attr(t("Admin.Settings.JobPriority.Tip", kindLabel(p.kind)))}">${LEVELS.map((l) =>
`<option value="${l}" ${l === p.level ? "selected" : ""}>${escapeHtml(t(`Admin.Settings.Priority.${cap(l)}`))}</option>`).join("")}</select></label>`).join("")}
</div>
</section>
<section class="panel" aria-labelledby="network-title">
<div class="panel-head"><h2 id="network-title" data-i18n="Admin.Settings.Network"></h2>
${settings.proxyWarning ? PROXY_WARNING : ""}</div>
${number("httpPort", settings.httpPort, 'min="1" max="65535"')}
${number("httpsPort", settings.httpsPort, 'min="1" max="65535"')}
${field("tlsMode", `<select class="input" name="tlsMode" ${lock("tlsMode")}>${["auto", "pem", "proxy"].map((m) =>
`<option value="${m}" ${m === settings.tlsMode ? "selected" : ""}>${escapeHtml(t(`Admin.Settings.Tls.${cap(m)}`))}</option>`).join("")}</select>`)}
${text("tlsCert", settings.tlsCert, 'dir="ltr" spellcheck="false"')}
${text("tlsKey", settings.tlsKey, 'dir="ltr" spellcheck="false"')}
<div class="field"><span data-i18n="Admin.Settings.Fingerprint"></span><code data-i18n-title="Admin.Settings.Fingerprint.Tip">${fingerprint(info?.tlsFingerprint)}</code></div>
</section>
<section class="panel" aria-labelledby="limits-title">
<h2 id="limits-title" data-i18n="Admin.Settings.Limits"></h2>
${number("maxUploadMb", Math.round(settings.maxUploadBytes / MB), 'min="1"')}
${number("chunkSizeMib", settings.chunkSizeBytes / MIB, 'min="0.0625" max="64" step="0.0625"')}
${number("tokenLifetimeDays", settings.tokenLifetimeDays, 'min="1" max="365"')}
${number("uploadRetentionHours", settings.uploadRetentionHours, 'min="1" max="8760"')}
${number("jobHistoryDays", settings.jobHistoryDays, 'min="1" max="3650"')}
</section>
</form>`;
applyStrings(root);
const form = root.querySelector("form");
escapeReverts(form);
form.addEventListener("submit", save);
form.elements.tlsMode.addEventListener("change", () => pemFiles(form));
pemFiles(form);
// The levels matter only while the priority queue is on.
form.elements.priorityQueue.addEventListener("change", () => { root.querySelector(".priorities").hidden = !form.elements.priorityQueue.checked; });
}
/** The certificate and key files are used only in Own certificate mode; elsewhere they are off and say so. */
function pemFiles(form) {
const pem = form.elements.tlsMode.value === "pem";
for (const name of PEM_FILES.filter((n) => !locked(n))) {
const input = form.elements[name];
clearInvalid(input);
input.disabled = !pem;
input.title = t(pem ? `Admin.Settings.${cap(name)}.Tip` : "Admin.Settings.PemOnly.Tip");
}
}
async function save(e) {
e.preventDefault();
const form = e.target;
form.querySelectorAll("[aria-invalid]").forEach(clearInvalid);
const data = new FormData(form);
const value = (name, fallback) => (form.elements[name]?.disabled ? fallback : data.get(name));
const request = {
...settings,
serverName: String(value("serverName", settings.serverName)).trim(),
language: String(value("language", settings.language)),
parallelism: Number(value("parallelism", settings.parallelism)),
priorityQueue: form.elements.priorityQueue.disabled ? settings.priorityQueue : form.elements.priorityQueue.checked,
jobPriorities: settings.jobPriorities.map((p) => ({ kind: p.kind, level: String(data.get(`priority:${p.kind}`) ?? p.level) })),
discovery: form.elements.discovery.disabled ? settings.discovery : form.elements.discovery.checked,
httpPort: Number(value("httpPort", settings.httpPort)),
httpsPort: Number(value("httpsPort", settings.httpsPort)),
tlsMode: String(value("tlsMode", settings.tlsMode)),
tlsCert: String(value("tlsCert", settings.tlsCert ?? "")).trim() || null,
tlsKey: String(value("tlsKey", settings.tlsKey ?? "")).trim() || null,
maxUploadBytes: Math.round(Number(data.get("maxUploadMb")) * MB),
chunkSizeBytes: Math.round(Number(data.get("chunkSizeMib")) * MIB),
tokenLifetimeDays: Number(data.get("tokenLifetimeDays")),
uploadRetentionHours: Number(data.get("uploadRetentionHours")),
jobHistoryDays: Number(data.get("jobHistoryDays")),
};
try {
settings = await api.put("/api/v1/server/settings", request);
draw();
toast(t("Admin.Common.Saved"));
} catch (err) {
const key = String(err.details ?? "").toLowerCase();
const input = (FIELDS[key] && form.elements[FIELDS[key]]) || [...form.elements].find((el) => el.name && el.name.toLowerCase() === key);
let message = errorText(err);
if (input && err.code === "invalid_setting") message = PEM_FILES.includes(input.name) ? t("Admin.Settings.PemMissing") : invalidText(input);
if (input && !input.disabled) {
markInvalid(input, message);
input.focus();
}
toast(message, true);
}
}
draw();
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
+319
View File
@@ -0,0 +1,319 @@
// Users (mockup AdminUsers.html, BRIEF §14.8): accounts table and a side panel to create, edit and reset accounts, or to
// change one's own password (a reset of one's own account would end this session and lose the temporary password).
import { t, plural, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, formatTime, bar, toast, confirmDialog, errorText, emptyState, markInvalid, clearInvalid, redraw, focusPlace, restoreFocus, fitColumns } from "../ui.js";
import { icons } from "../icons.js";
const ROLES = ["viewer", "uploader", "editor", "admin"];
const TB = 1e12;
const RENDER_NODE = 32;
/** API error codes that belong to one field of the side forms. */
const FIELD_ERRORS = { invalid_username: "username", username_taken: "username", weak_password: "password", wrong_password: "current", same_password: "next" };
export async function render(root, { api, info, setMeta, actions }) {
let users = [];
let filter = "";
let freeBytes = 0;
let tokenDays = 30;
let opener = null;
actions.innerHTML = `
<input class="input search" type="search" id="search" dir="auto" data-i18n-placeholder="Admin.Users.Search" data-i18n-title="Admin.Users.Search.Tip" aria-label="${attr(t("Admin.Users.Search"))}">
<button class="btn primary" id="new" data-i18n="Admin.Users.New" data-i18n-title="Admin.Users.New.Tip"></button>`;
applyStrings(actions);
const search = actions.querySelector("#search");
search.addEventListener("input", () => {
filter = search.value.trim().toLowerCase();
drawTable();
});
actions.querySelector("#new").addEventListener("click", () => openForm(null));
root.innerHTML = `
<div class="split">
<div class="panel flush">
<div class="table users" data-levels="3" role="table" aria-label="${attr(t("Admin.Nav.Users"))}">
<div class="thead" role="row">
<span role="columnheader" data-i18n="Admin.Users.User"></span><span role="columnheader" data-i18n="Admin.Users.Role"></span>
<span role="columnheader" class="col-quota" data-i18n="Admin.Users.Quota"></span><span role="columnheader" class="col-seen" data-i18n="Admin.Users.LastSeen"></span>
<span role="columnheader" class="col-uploads end" data-i18n="Admin.Users.Uploads"></span><span role="columnheader" class="col-status" data-i18n="Admin.Users.Status"></span>
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
<div id="rows" role="rowgroup"></div>
</div>
<div class="table-foot"><span id="policy" class="muted"></span><span class="spacer"></span>
<a href="#/logs?view=signins" data-i18n="Admin.Users.SignInLog" data-i18n-title="Admin.Users.SignInLog.Tip"></a></div>
</div>
<aside class="panel side" id="side" hidden></aside>
</div>`;
applyStrings(root);
const table = root.querySelector(".table");
const side = root.querySelector("#side");
side.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
e.preventDefault();
closeSide();
}
});
async function load() {
try {
const [list, stats, settings] = await Promise.all([
api.get("/api/v1/users"),
api.get("/api/v1/archive/stats").catch(() => null),
api.get("/api/v1/server/settings").catch(() => null),
]);
users = list;
freeBytes = stats?.freeBytes ?? 0;
tokenDays = settings?.tokenLifetimeDays ?? tokenDays;
} catch (err) {
toast(errorText(err), true);
return;
}
const active = users.filter((u) => !u.user.disabled).length;
setMeta(`${plural("Admin.Users.Accounts", users.length)} · ${plural("Admin.Users.ActiveCount", active)}`);
root.querySelector("#policy").textContent =
`${plural("Admin.Users.PasswordPolicy", info?.limits?.passwordMinLength ?? 10)} · ${plural("Admin.Users.TokenPolicy", tokenDays)}`;
drawTable();
}
function drawTable() {
const host = root.querySelector("#rows");
redraw(host, () => {
const rows = users.filter((u) => !filter || u.user.username.toLowerCase().includes(filter) || (u.user.displayName ?? "").toLowerCase().includes(filter));
host.innerHTML = rows.map(rowHtml).join("") || `<div class="row" role="row"><div class="wide" role="cell">${emptyState("Admin.Users.Empty",
`<button class="btn small" id="clear" data-i18n="Admin.Users.ClearSearch" data-i18n-title="Admin.Users.ClearSearch.Tip"></button>`)}</div></div>`;
applyStrings(host);
});
host.querySelectorAll("[data-act]").forEach((button) => button.addEventListener("click", () => {
const row = users.find((u) => u.user.id === button.closest("[data-key]").dataset.key);
act(button.dataset.act, row.user);
}));
host.querySelector("#clear")?.addEventListener("click", () => {
search.value = "";
filter = "";
drawTable();
search.focus();
});
fitColumns(table);
}
function rowHtml(row) {
const u = row.user;
const own = u.id === api.user().id;
const subtitle = [u.displayName, u.mustChangePassword ? t("Admin.Users.MustChange") : null, u.disabled ? t("Admin.Users.Disabled") : null]
.filter(Boolean).join(" · ");
const quotaText = t("Admin.Users.QuotaOf", formatBytes(u.usedBytes), formatBytes(u.quotaBytes));
const quota = u.quotaBytes > 0
? `<div class="progress-cell">${bar(u.usedBytes / u.quotaBytes, u.disabled)}<span class="num ellipsis" title="${attr(quotaText)}">${escapeHtml(quotaText)}</span></div>`
: `<span class="muted num">${escapeHtml(u.usedBytes > 0 ? formatBytes(u.usedBytes) : "—")}</span>`;
const seen = row.lastSeen ? `${formatTime(row.lastSeen)}${row.lastClient ? " · " + row.lastClient : ""}` : "—";
const button = (act, key, extra = "") => `<button class="btn small${extra}" data-act="${act}" data-i18n="Admin.Users.${key}" data-i18n-title="Admin.Users.${key}.Tip"></button>`;
const buttons = u.disabled
? button("enable", "Enable") + button("delete", "Delete", " destructive")
: button("edit", "Edit") + (own ? button("password", "ChangePassword") : button("reset", "Reset") + button("disable", "Disable"));
return `
<div class="row${u.disabled ? " dim" : ""}" role="row" data-key="${attr(u.id)}">
<span class="person" role="cell"><span class="avatar ${attr(u.role)}" aria-hidden="true">${escapeHtml(u.username.slice(0, 1).toUpperCase())}</span>
<span class="stack"><strong class="ellipsis" dir="auto" title="${attr(u.username)}">${escapeHtml(u.username)}</strong>
<small dir="auto" title="${attr(subtitle)}">${escapeHtml(subtitle)}</small></span></span>
<span class="ellipsis" role="cell" data-i18n="Admin.Role.${cap(u.role)}"></span>
<span class="col-quota" role="cell">${quota}</span>
<span class="col-seen ellipsis" role="cell" dir="auto" title="${attr(seen)}">${escapeHtml(seen)}</span>
<span class="col-uploads num end" role="cell">${formatNumber(row.uploadsLast30Days)}</span>
<span class="col-status state ${u.disabled ? "cancelled" : "done"}" role="cell"><span aria-hidden="true">${u.disabled ? "○" : "●"}</span>
<span data-i18n="${u.disabled ? "Admin.Users.Disabled" : "Admin.Users.Active"}"></span></span>
<span class="row-actions" role="cell">${buttons}</span>
</div>`;
}
async function act(action, user) {
try {
if (action === "edit") return openForm(user);
if (action === "password") return openPasswordForm();
if (action === "reset") {
showPassword(await api.post(`/api/v1/users/${user.id}/reset-password`, {}));
} else if (action === "disable" || action === "enable") {
await api.patch(`/api/v1/users/${user.id}`, { disabled: action === "disable" });
} else if (action === "delete") {
const confirmed = await confirmDialog({
title: t("Admin.Users.DeleteTitle", user.username),
body: t("Admin.Users.DeleteBody"),
confirm: t("Admin.Users.DeleteConfirm"),
confirmTip: t("Admin.Users.Delete.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
typed: user.username,
});
if (!confirmed) return;
await api.del(`/api/v1/users/${user.id}`);
}
await load();
} catch (err) {
toast(errorText(err), true);
}
}
/** Shows the side panel, remembering which control opened it so closing returns the keyboard there. */
function openSide(html) {
if (side.hidden) {
const scope = actions.contains(document.activeElement) ? actions : root;
opener = { scope, place: focusPlace(scope) };
}
side.hidden = false;
side.innerHTML = html;
applyStrings(side);
fitColumns(table);
side.querySelector("#close").addEventListener("click", closeSide);
}
function closeSide() {
side.hidden = true;
side.innerHTML = "";
fitColumns(table);
if (opener) restoreFocus(opener.scope, opener.place);
opener = null;
}
function openForm(user) {
const editing = user !== null;
const quotaTb = editing && user.quotaBytes > 0 ? +(user.quotaBytes / TB).toFixed(3) : 0;
const renderNode = editing ? (user.permissions & RENDER_NODE) !== 0 : false;
openSide(`
<form class="form" novalidate>
<h2 data-i18n="${editing ? "Admin.Users.EditTitle" : "Admin.Users.New"}"></h2>
<label><span data-i18n="Admin.Users.Username"></span>
<input class="input" name="username" required autocomplete="off" dir="auto" value="${attr(user?.username ?? "")}" ${editing ? "disabled" : ""} data-i18n-title="Admin.Users.Username.Tip"></label>
<label><span data-i18n="Admin.Users.DisplayName"></span>
<input class="input" name="displayName" autocomplete="off" dir="auto" value="${attr(user?.displayName ?? "")}" data-i18n-title="Admin.Users.DisplayName.Tip"></label>
<fieldset><legend data-i18n="Admin.Users.Role"></legend>
${ROLES.map((r) => `<label class="check"><input type="radio" name="role" value="${r}" ${(user?.role ?? "editor") === r ? "checked" : ""} data-i18n-title="Admin.Users.Role.${cap(r)}.Tip"><span data-i18n="Admin.Role.${cap(r)}"></span></label>`).join("")}
</fieldset>
<label><span data-i18n="Admin.Users.Quota"></span>
<span class="inline"><input class="input narrow num" name="quota" type="number" min="0" step="0.1" value="${quotaTb}" data-i18n-title="Admin.Users.Quota.Tip"><span>TB</span>
<small class="muted">${escapeHtml(t("Admin.Users.FreeOnServer", formatBytes(freeBytes)))}</small></span></label>
${editing ? "" : `
<label><span data-i18n="Admin.Users.TempPassword"></span>
<span class="inline"><input class="input mono" name="password" autocomplete="off" spellcheck="false" dir="ltr" value="${attr(generatePassword())}" data-i18n-title="Admin.Users.TempPassword.Tip">
<button class="btn icon" type="button" id="regenerate" data-i18n-title="Admin.Users.Regenerate.Tip">${icons.refresh}</button></span></label>
<label class="check"><input type="checkbox" checked disabled data-i18n-title="Admin.Users.MustChangeFlag.Tip"><span data-i18n="Admin.Users.MustChangeFlag"></span></label>`}
<label class="check"><input type="checkbox" name="renderNode" ${renderNode ? "checked" : ""} data-i18n-title="Admin.Users.RenderNode.Tip"><span data-i18n="Admin.Users.RenderNode"></span></label>
<div class="buttons">
<button class="btn" type="button" id="close" data-i18n="Admin.Common.Cancel" data-i18n-title="Admin.Common.Cancel.Tip"></button>
<button class="btn primary" type="submit" data-i18n="${editing ? "Admin.Common.Save" : "Admin.Users.Create"}" data-i18n-title="${editing ? "Admin.Common.Save.Tip" : "Admin.Users.Create.Tip"}"></button>
</div>
</form>`);
const form = side.querySelector("form");
side.querySelector("#regenerate")?.addEventListener("click", () => {
form.elements.password.value = generatePassword();
clearInvalid(form.elements.password);
});
form.addEventListener("submit", async (e) => {
e.preventDefault();
form.querySelectorAll("[aria-invalid]").forEach(clearInvalid);
const data = new FormData(form);
const quotaBytes = Math.round(Number(data.get("quota") || 0) * TB);
try {
if (editing) {
await api.patch(`/api/v1/users/${user.id}`, {
displayName: String(data.get("displayName")), role: data.get("role"), quotaBytes, allowRenderNode: data.get("renderNode") === "on",
});
closeSide();
} else {
showPassword(await api.post("/api/v1/users", {
username: String(data.get("username")).trim(), displayName: String(data.get("displayName")), role: data.get("role"), quotaBytes,
password: String(data.get("password")), allowRenderNode: data.get("renderNode") === "on",
}));
}
await load();
} catch (err) {
fieldError(form, err, err.details === "quotaBytes" ? "quota" : FIELD_ERRORS[err.code]);
}
});
form.querySelector("input:not([disabled])").focus();
}
/** The caller's own password, changed with the current one; this session stays signed in. */
function openPasswordForm() {
const field = (name, key, complete) => `<label><span data-i18n="Admin.Password.${key}"></span>
<input class="input" name="${name}" type="password" autocomplete="${complete}" required data-i18n-title="Admin.Password.${key}.Tip"></label>`;
openSide(`
<form class="form" novalidate>
<h2 data-i18n="Admin.Password.Title"></h2>
${field("current", "Current", "current-password")}${field("next", "New", "new-password")}${field("repeat", "Repeat", "new-password")}
<div class="buttons">
<button class="btn" type="button" id="close" data-i18n="Admin.Common.Cancel" data-i18n-title="Admin.Common.Cancel.Tip"></button>
<button class="btn primary" type="submit" data-i18n="Admin.Password.Save" data-i18n-title="Admin.Users.SavePassword.Tip"></button>
</div>
</form>`);
const form = side.querySelector("form");
form.addEventListener("submit", async (e) => {
e.preventDefault();
form.querySelectorAll("[aria-invalid]").forEach(clearInvalid);
const data = new FormData(form);
if (data.get("next") !== data.get("repeat")) {
fieldError(form, { message: t("Admin.Password.Mismatch"), status: 400 }, "repeat");
return;
}
try {
await api.changePassword(String(data.get("current")), String(data.get("next")));
closeSide();
toast(t("Admin.Users.PasswordChanged"));
} catch (err) {
fieldError(form, err, FIELD_ERRORS[err.code]);
}
});
form.querySelector("input").focus();
}
/** The one-time password of a new or reset account, shown once in the side panel. */
function showPassword(result) {
openSide(`
<div class="form">
<h2 dir="auto">${escapeHtml(result.user.username)}</h2>
<label><span data-i18n="Admin.Users.TempPassword"></span>
<span class="inline"><input class="input mono" readonly dir="ltr" value="${attr(result.temporaryPassword)}" data-i18n-title="Admin.Users.TempPassword.Tip">
<button class="btn icon" type="button" id="copy" data-i18n-title="Admin.Users.Copy.Tip">${icons.copy}</button></span></label>
<div class="buttons"><button class="btn" type="button" id="close" data-i18n="Admin.Common.Close" data-i18n-title="Admin.Common.Close.Tip"></button></div>
</div>`);
const input = side.querySelector("input");
side.querySelector("#copy").addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(result.temporaryPassword);
toast(t("Admin.Users.Copied"));
} catch {
input.select();
}
});
input.focus();
input.select();
}
await load();
}
/** An API failure on a side form: the field it concerns gets the error border, the message and the focus; a toast announces it. */
function fieldError(form, err, name) {
const message = err.code === "username_taken" ? t("Admin.Users.Taken") : errorText(err);
const field = name ? form.elements[name] : null;
if (field) {
markInvalid(field, message);
field.focus();
}
toast(message, true);
}
/** Three groups of four unambiguous characters, like the server's own temporary passwords. */
function generatePassword() {
const alphabet = "abcdefghjkmnpqrstuvwxyz23456789";
const chars = [];
while (chars.length < 12) {
// Bytes at or above 248 (8 × 31) are skipped so every character is equally likely.
for (const b of crypto.getRandomValues(new Uint8Array(16))) {
if (b < 248 && chars.length < 12) chars.push(alphabet[b % alphabet.length]);
}
}
return `${chars.slice(0, 4).join("")}-${chars.slice(4, 8).join("")}-${chars.slice(8).join("")}`;
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
+272
View File
@@ -0,0 +1,272 @@
// Small DOM and formatting helpers shared by the admin pages. No inline styles: the panel runs under a strict CSP.
import { t, culture } from "./i18n.js";
export function escapeHtml(s) {
return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
}
/** Escaped attribute value for title="…" tooltips. */
export const attr = escapeHtml;
export function formatNumber(n) {
return new Intl.NumberFormat(culture()).format(n ?? 0);
}
/** 9.4 TB, 610 GB … (decimal units, like disk vendors and the desktop client). */
export function formatBytes(bytes) {
const units = ["B", "KB", "MB", "GB", "TB", "PB"];
let value = Number(bytes ?? 0);
let unit = 0;
while (value >= 1000 && unit < units.length - 1) {
value /= 1000;
unit++;
}
const digits = value >= 100 || unit === 0 ? 0 : 1;
return `${new Intl.NumberFormat(culture(), { maximumFractionDigits: digits }).format(value)} ${units[unit]}`;
}
export function formatTime(iso) {
if (!iso) return "—";
const date = new Date(iso);
const sameDay = new Date().toDateString() === date.toDateString();
return new Intl.DateTimeFormat(culture(), sameDay ? { timeStyle: "short" } : { dateStyle: "medium" }).format(date);
}
export function formatDateTime(iso) {
return iso ? new Intl.DateTimeFormat(culture(), { dateStyle: "short", timeStyle: "medium" }).format(new Date(iso)) : "—";
}
export function formatDuration(seconds) {
const s = Math.max(0, Math.round(seconds ?? 0));
if (s >= 86400) return t("Common.Duration.Days", Math.floor(s / 86400), Math.floor((s % 86400) / 3600));
if (s >= 3600) return t("Common.Duration.Hours", Math.floor(s / 3600), Math.floor((s % 3600) / 60));
if (s >= 60) return t("Common.Duration.Minutes", Math.floor(s / 60));
return t("Common.Duration.Seconds", s);
}
/** A certificate fingerprint that wraps only between its byte pairs, always left to right. */
export function fingerprint(value) {
return value ? `<span class="fingerprint" dir="ltr">${String(value).split(":").map(escapeHtml).join(":<wbr>")}</span>` : "—";
}
/** 6 px progress bar drawn as SVG (attributes, not inline styles). */
export function bar(fraction, muted = false) {
const width = Math.max(0, Math.min(100, Math.round((fraction ?? 0) * 100)));
return `<svg class="bar${muted ? " muted" : ""}" viewBox="0 0 100 6" preserveAspectRatio="none" aria-hidden="true">` +
`<rect class="track" width="100" height="6" rx="3"/><rect class="fill" width="${width}" height="6" rx="3"/></svg>`;
}
/**
* Column chart named by label: values with labels under the bars and, when given, the value above each bar. Bars use
* the accent colour, or the sun colour for upload activity. With edgeLabels the first and last labels align with the
* chart edges (a time axis labelled only at its ends). Charts keep their left-to-right axis in right-to-left pages.
*/
export function columns(items, { label, sun = false, valueLabel = null, edgeLabels = false, height = 190 } = {}) {
const width = 400;
const base = height - 30;
const max = Math.max(1, ...items.map((i) => i.value));
const step = width / Math.max(1, items.length);
const barWidth = Math.max(2, Math.min(32, step * 0.65));
let svg = `<svg class="chart${sun ? " sun" : ""}" viewBox="0 0 ${width} ${height}" role="img" aria-label="${attr(label)}">`;
svg += `<line class="axis" x1="0" y1="${base}" x2="${width}" y2="${base}"/>`;
items.forEach((item, i) => {
const h = item.value > 0 ? Math.max(2, (item.value / max) * (base - 18)) : 0;
const x = i * step + (step - barWidth) / 2;
const middle = (x + barWidth / 2).toFixed(1);
svg += `<rect class="column" x="${x.toFixed(1)}" y="${(base - h).toFixed(1)}" width="${barWidth.toFixed(1)}" height="${h.toFixed(1)}" rx="2"><title>${escapeHtml(item.title ?? "")}</title></rect>`;
if (valueLabel) svg += `<text class="value" x="${middle}" y="${(base - h - 5).toFixed(1)}">${escapeHtml(valueLabel(item))}</text>`;
if (!item.label) return;
const edge = !edgeLabels ? "" : i === 0 ? "start" : i === items.length - 1 ? "end" : "";
const at = edge === "start" ? 0 : edge === "end" ? width : middle;
svg += `<text class="label${edge ? " " + edge : ""}" x="${at}" y="${base + 16}">${escapeHtml(item.label)}</text>`;
});
return svg + "</svg>";
}
/**
* Hides a table's secondary columns level by level (fit-1 … fit-n in admin.css, n = data-levels) until its rows fit
* the panel: the widths depend on the language and on the side panel, so they are measured rather than guessed.
*/
export function fitColumns(table) {
const levels = Number(table.dataset.levels);
for (let level = 0; level <= levels; level++) {
for (let i = 1; i <= levels; i++) table.classList.toggle(`fit-${i}`, i <= level);
if (table.scrollWidth <= table.clientWidth) return;
}
}
window.addEventListener("resize", () => document.querySelectorAll(".table[data-levels]").forEach(fitColumns));
/** Chip of the Dashboard and Settings: TLS mode is proxy, but this page did not come through a trusted proxy over HTTPS (BRIEF §14.2). */
export const PROXY_WARNING = `<span class="chip warn" data-i18n="Admin.Settings.ProxyBypassed" data-i18n-title="Admin.Settings.ProxyBypassed.Tip"></span>`;
/** An empty state: one sentence and one button (BRIEF §0.2). */
export function emptyState(sentenceKey, button = "") {
return `<div class="empty"><span data-i18n="${attr(sentenceKey)}"></span>${button}</div>`;
}
/** Shows a toast at the bottom (inline end) for 8 s (hover pauses). */
export function toast(message, isError = false) {
const host = document.getElementById("toasts") ?? document.body.appendChild(Object.assign(document.createElement("div"), { id: "toasts" }));
const item = document.createElement("div");
item.className = `toast${isError ? " error" : ""}`;
item.setAttribute("role", isError ? "alert" : "status");
item.textContent = message;
host.appendChild(item);
let remaining = 8000;
let started = Date.now();
let timer = setTimeout(() => item.remove(), remaining);
item.addEventListener("mouseenter", () => {
clearTimeout(timer);
remaining -= Date.now() - started;
});
item.addEventListener("mouseleave", () => {
started = Date.now();
timer = setTimeout(() => item.remove(), remaining);
});
}
let dialogs = 0;
/**
* Two-button confirmation dialog (safe action left and default, Esc keeps). Resolves true when the destructive action
* is chosen; with `typed`, that button stays disabled until the text is typed into the labelled field.
*/
export function confirmDialog({ title, body, confirm, confirmTip, cancel, cancelTip, typed }) {
return new Promise((resolve) => {
const id = `dialog-${++dialogs}`;
const dialog = document.createElement("dialog");
dialog.className = "dialog";
dialog.setAttribute("aria-labelledby", `${id}-title`);
if (body) dialog.setAttribute("aria-describedby", `${id}-body`);
dialog.innerHTML = `
<form method="dialog">
<h2 id="${id}-title" dir="auto">${escapeHtml(title)}</h2>
${body ? `<p id="${id}-body">${escapeHtml(body)}</p>` : ""}
${typed ? `<label class="field-label"><span>${escapeHtml(t("Admin.Common.TypeToConfirm", typed))}</span>
<input class="input" name="typed" autocomplete="off" spellcheck="false" dir="auto" title="${attr(t("Admin.Common.TypeToConfirm.Tip"))}"></label>` : ""}
<div class="buttons">
<button class="btn" value="cancel" title="${attr(cancelTip)}" autofocus>${escapeHtml(cancel)}</button>
<button class="btn destructive" value="ok" title="${attr(typed ? t("Admin.Common.TypeFirst.Tip") : confirmTip)}" ${typed ? "disabled" : ""}>${escapeHtml(confirm)}</button>
</div>
</form>`;
document.body.appendChild(dialog);
const ok = dialog.querySelector('button[value="ok"]');
dialog.querySelector('input[name="typed"]')?.addEventListener("input", (e) => {
ok.disabled = e.target.value !== typed;
ok.title = ok.disabled ? t("Admin.Common.TypeFirst.Tip") : confirmTip;
});
dialog.addEventListener("close", () => {
resolve(dialog.returnValue === "ok");
dialog.remove();
});
dialog.showModal();
});
}
/** The localised message of an API failure, or the generic one when the server was not reached. */
export function errorText(err) {
return err?.message && err.status ? err.message : t("Admin.Error.Unreachable");
}
/**
* Marks a form field invalid (DESIGN §4): error border and the message as its tooltip, until the value changes and
* the field's own tooltip comes back.
*/
export function markInvalid(field, message) {
if (field.getAttribute("aria-invalid") !== "true") field.dataset.tip = field.title;
field.setAttribute("aria-invalid", "true");
field.title = message;
field.addEventListener("input", () => clearInvalid(field), { once: true });
}
/** "The value of Folder template is not valid; …": a field the server refused, named by its label. */
export function invalidText(field) {
return t("Admin.Common.Invalid", field.closest("label")?.querySelector("span")?.textContent ?? field.name);
}
export function clearInvalid(field) {
if (field.getAttribute("aria-invalid") !== "true") return;
field.removeAttribute("aria-invalid");
field.title = field.dataset.tip ?? "";
}
/** Esc in a field of the form puts back the value the page was drawn with (DESIGN §4: Esc reverts). */
export function escapeReverts(form) {
form.addEventListener("keydown", (e) => {
const field = e.target;
if (e.key !== "Escape" || !(field instanceof HTMLInputElement || field instanceof HTMLSelectElement) || field.type === "search") return;
const checkable = field.type === "checkbox" || field.type === "radio";
const before = checkable ? field.checked : field.value;
if (field instanceof HTMLSelectElement) {
[...field.options].forEach((o) => {
o.selected = o.defaultSelected;
});
} else if (field.type === "checkbox" || field.type === "radio") {
field.checked = field.defaultChecked;
} else {
field.value = field.defaultValue;
}
clearInvalid(field);
// What follows the value (the certificate files of a TLS mode, the levels of the priority queue) follows it back.
if ((checkable ? field.checked : field.value) !== before) field.dispatchEvent(new Event("change", { bubbles: true }));
});
}
const FOCUSABLE = "a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex='-1'])";
/**
* Where the keyboard focus is inside root, in terms that survive a re-render: the row (data-key), the control
* (data-act, data-toggle, id or name) and positions as fallbacks.
*/
export function focusPlace(root) {
const el = document.activeElement;
if (!el || el === document.body || !root.contains(el)) return null;
const row = el.closest("[data-key]");
const rows = [...root.querySelectorAll("[data-key]")];
return { row: row?.dataset.key ?? null, rowIndex: rows.indexOf(row), control: controlKey(el), index: [...(row ?? root).querySelectorAll(FOCUSABLE)].indexOf(el) };
}
/**
* Focuses the same control after a re-render, else the control at the same place in the same (or same-position) row,
* else the first control left (an empty state's button).
*/
export function restoreFocus(root, place) {
if (!place) return;
let scope = root;
let index = place.index;
if (place.row !== null) {
const rows = [...root.querySelectorAll("[data-key]")];
const row = rows.find((r) => r.dataset.key === place.row) ?? rows[Math.min(place.rowIndex, rows.length - 1)];
if (row) scope = row;
else index = 0;
}
const controls = [...scope.querySelectorAll(FOCUSABLE)];
(controls.find((c) => controlKey(c) === place.control) ?? controls[Math.min(Math.max(index, 0), controls.length - 1)])?.focus();
}
/** Redraws with draw() and puts the keyboard focus back where it was. */
export function redraw(root, draw) {
const place = focusPlace(root);
draw();
restoreFocus(root, place);
}
function controlKey(el) {
return el.dataset.act ?? el.dataset.toggle ?? el.dataset.cancel ?? el.dataset.forget ?? (el.id || el.name || "");
}
/** Query parameters of the hash route (#/logs?view=signins). */
export function routeParams() {
return new URLSearchParams(location.hash.split("?")[1] ?? "");
}
/** A language's own name ("Italiano"), for language menus. */
export function nativeName(code) {
try {
const name = new Intl.DisplayNames([code], { type: "language" }).of(code) ?? code;
return name.charAt(0).toLocaleUpperCase(code) + name.slice(1);
} catch {
return code;
}
}