diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx index d2a47e16..4a283a25 100644 --- a/i18n/en/Admin.resx +++ b/i18n/en/Admin.resx @@ -50,12 +50,16 @@ Look for new and changed sequences on disk Sequences unverified + unverified + unverified Verify Read every original again and compare its SHA-256 + Actions Cancel Discard the changes Close Close this panel + The value of {0} is not valid; correct it and save again.long Keep Leave everything as it is Load more @@ -64,13 +68,22 @@ Save Save the changes on the server Saved. + Type the name above first + Type {0} to confirmlong + Type the name exactly as shown to confirm Recent activity All logs Open the audit log Archive Storage by year + {0} camera + {0} cameras discovery off discovery on + {0} done today + {0} done today + {0} failed + {0} failed {0} free {0} queued · {1} done today · {2} failedlong Jobs @@ -82,14 +95,25 @@ of {0} online originals {0} + {0} photo + {0} photos {0} photos · {1} cameras Queue and history Open the Jobs page + {0} queued + {0} queued + Read the dashboard again running + sequence + sequences sequences Storage frames per day · {0} total · peak {1}long Uploads · last 30 days + {0} sequence without proxieslong + {0} sequences without proxieslong + {0} worker + {0} workers {0} workers The server did not answer; try again.long Adopt @@ -137,9 +161,12 @@ Show or hide the job log {0} running · {1} nodes onlinelong No render nodes + Give a user the render-node right; their Titano client can then offer the PC Node Node Render nodes + {0} node online + {0} nodes online Owner Pause Stop at the next checkpoint and keep the progress @@ -154,7 +181,11 @@ Put the job back in the queue from its checkpoint Retry Queue the job again from its last checkpoint + {0} running + {0} running server + Show all + Show jobs in every state State Target Language of this panel @@ -186,10 +217,26 @@ Download Save this log file Nothing recorded yet + disabled + display name + enabled + no quota + notes + permissions + quota {0} + rating + role {0} + edit settings + tags + title Log files From + {0} line + {0} lines {0} lines How many of the latest lines to show + {0} sequence reassignedlong + {0} sequences reassignedlong Read the log again Audit Changes to users, sequences, the archive and settings @@ -247,6 +294,8 @@ Max file (MB) Largest single upload accepted Network and TLS + The PEM file was not found; enter its full path on the server.long + Used only in Own certificate mode Restart required Saved ports, TLS, workers, chunk size or job history apply after a restart Server @@ -269,7 +318,16 @@ Jobs this server runs at the same time Sign out Sign out of the admin panel + Switch between light and dark + {0} account + {0} accounts Active + {0} active + {0} active + Change password + Choose a new password for your account; your other sessions end + Clear search + Show every account again Password copied. Copy the password Create @@ -298,6 +356,9 @@ Always required for accounts created here New user Create an account; the user must change the password at first sign-in + Password changed. + Passwords: PBKDF2-SHA512, {0} character minimumlong + Passwords: PBKDF2-SHA512, {0} characters minimumlong Passwords: PBKDF2-SHA512, {0} characters minimum · tokens expire after {1} days idlelong Quota Originals uploaded by this user count against the quota; 0 = unlimited @@ -312,13 +373,17 @@ Import, edit, render, upload and download Upload only; cannot edit sequences Browse and download renders only + Replace your password; this session stays signed in Search Filter by user or display name Sign-in log Who signed in from where, and when Status + That user name is taken; choose another.long Temporary password Give this to the user; they must replace it at first sign-in + tokens expire after {0} day idlelong + tokens expire after {0} days idlelong Uploads 30 d User Username diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx index 45da50d6..d53594df 100644 --- a/i18n/it/Admin.it.resx +++ b/i18n/it/Admin.it.resx @@ -50,12 +50,16 @@ Cerca sequenze nuove e modificate sul disco Sequenze non verificate + non verificata + non verificate Verifica Rileggi ogni originale e confronta il suo SHA-256 + Azioni Annulla Scarta le modifiche Chiudi Chiudi questo pannello + Il valore di {0} non è valido; correggilo e salva di nuovo. Mantieni Lascia tutto com'è Carica altri @@ -64,13 +68,22 @@ Salva Salva le modifiche sul server Salvato. + Prima digita il nome qui sopra + Digita {0} per confermare + Digita il nome esattamente come mostrato per confermare Attività recenti Tutti i log Apri il registro di controllo Archivio Spazio per anno + {0} fotocamera + {0} fotocamere rilevamento spento rilevamento attivo + {0} completato oggi + {0} completati oggi + {0} fallito + {0} falliti {0} liberi {0} in coda · {1} completati oggi · {2} falliti Job @@ -82,14 +95,25 @@ di {0} online originali {0} + {0} foto + {0} foto {0} foto · {1} fotocamere Coda e cronologia Apri la pagina Job + {0} in coda + {0} in coda + Rileggi la panoramica in corso + sequenza + sequenze sequenze Spazio foto al giorno · {0} totali · picco {1} Caricamenti · ultimi 30 giorni + {0} sequenza senza proxy + {0} sequenze senza proxy + {0} worker + {0} worker {0} worker Il server non ha risposto; riprova. Adozione @@ -137,9 +161,12 @@ Mostra o nascondi il log del job {0} in corso · {1} nodi online Nessun nodo di rendering + Concedi a un utente il permesso di nodo di rendering; il suo client Titano potrà offrire il PC Nodo Nodo Nodi di rendering + {0} nodo online + {0} nodi online Proprietario Pausa Fermati al prossimo punto di controllo e mantieni l'avanzamento @@ -154,7 +181,11 @@ Rimetti il job in coda dal suo punto di controllo Riprova Rimetti in coda il job dall'ultimo punto di controllo + {0} in corso + {0} in corso server + Mostra tutti + Mostra i job in ogni stato Stato Oggetto Lingua di questo pannello @@ -186,10 +217,26 @@ Scarica Salva questo file di log Ancora nessuna registrazione + disattivato + nome visualizzato + riattivato + nessuna quota + note + permessi + quota {0} + valutazione + ruolo {0} + impostazioni di modifica + tag + titolo File di log Da + {0} riga + {0} righe {0} righe Quante delle ultime righe mostrare + {0} sequenza riassegnata + {0} sequenze riassegnate Rileggi il log Controllo Modifiche a utenti, sequenze, archivio e impostazioni @@ -247,6 +294,8 @@ File massimo (MB) Caricamento singolo più grande accettato Rete e TLS + File PEM non trovato; inserisci il percorso completo sul server. + Usato solo in modalità Certificato proprio Riavvio richiesto Porte, TLS, worker, dimensione blocchi o cronologia job salvati valgono dopo un riavvio Server @@ -269,7 +318,16 @@ Job che questo server esegue contemporaneamente Esci Esci dal pannello di amministrazione + Alterna tema chiaro e scuro + {0} account + {0} account Attivo + {0} attivo + {0} attivi + Cambia password + Scegli una nuova password per il tuo account; le altre sessioni terminano + Cancella ricerca + Mostra di nuovo tutti gli account Password copiata. Copia la password Crea @@ -298,6 +356,9 @@ Sempre richiesto per gli account creati qui Nuovo utente Crea un account; l'utente deve cambiare la password al primo accesso + Password cambiata. + Password: PBKDF2-SHA512, almeno {0} carattere + Password: PBKDF2-SHA512, almeno {0} caratteri Password: PBKDF2-SHA512, almeno {0} caratteri · i token scadono dopo {1} giorni di inattività Quota Gli originali caricati da questo utente contano nella quota; 0 = illimitata @@ -312,13 +373,17 @@ Importa, modifica, esegue rendering, carica e scarica Solo caricamento; non può modificare le sequenze Solo consultazione e download dei rendering + Sostituisci la password; questa sessione resta collegata Cerca Filtra per nome utente o nome visualizzato Registro accessi Chi ha effettuato l'accesso, da dove e quando Stato + Questo nome utente è già in uso; scegline un altro. Password temporanea Comunicala all'utente; dovrà sostituirla al primo accesso + i token scadono dopo {0} giorno di inattività + i token scadono dopo {0} giorni di inattività Caricamenti 30 g Utente Nome utente diff --git a/src/Titano.Server/Admin/web/admin.css b/src/Titano.Server/Admin/web/admin.css index feb6c1a8..1e48cf7e 100644 --- a/src/Titano.Server/Admin/web/admin.css +++ b/src/Titano.Server/Admin/web/admin.css @@ -1,94 +1,111 @@ -/* Titano Server admin — DESIGN.md light tokens (the web admin is light-only), mockups Admin.html and AdminUsers.html. */ +/* Titano 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 { - --bg: #f3f3f3; - --chrome: #ffffff; - --surface: #ffffff; - --card: #ffffff; - --card-hover: #f5f5f5; - --stroke: #e5e5e5; - --stroke-strong: #d1d1d1; - --text: #1a1a1a; - --text-muted: #616161; - --text-faint: #9e9e9e; - --accent: #0067c0; - --accent-hover: #1975c5; - --on-accent: #ffffff; - --accent-selected: #e8f1fa; - --sun: #e08a1e; - --sun-soft: #fff4e5; - --success: #0f7b4f; - --warning: #9a6700; - --error: #c42b1c; + 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: #004c8c; } +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); } -.right { text-align: right; justify-self: end; } +.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 */ -.shell { display: grid; grid-template-columns: 220px 1fr; min-height: 100vh; } -.sidebar { background: var(--chrome); border-right: 1px solid var(--stroke); display: flex; flex-direction: column; padding: 16px 12px; position: sticky; top: 0; height: 100vh; } -.brand { display: flex; align-items: center; gap: 10px; padding: 4px 8px 18px; } +/* The sidebar column keeps the chrome colour below the sticky sidebar on long pages. */ +.shell { display: grid; grid-template-columns: 220px 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 strong { font-size: 18px; } +.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); } +.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-left: 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; } +.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; } -.user .who strong { display: block; } +.user .who { flex: 1; min-width: 0; display: flex; flex-direction: column; } .user .who span { color: var(--text-muted); font-size: 11px; } -.main { display: flex; flex-direction: column; min-width: 0; } -.header { min-height: 60px; display: flex; align-items: center; gap: 14px; padding: 0 24px; border-bottom: 1px solid var(--stroke); background: var(--chrome); flex-wrap: wrap; } -.header h1 { font-size: 18px; font-weight: 600; } -.header .meta { color: var(--text-muted); } -.header .actions { display: flex; align-items: center; gap: 8px; } -.header .language { width: auto; } -.content { padding: 24px; display: grid; gap: 20px; align-content: start; } +.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); } -.btn:focus-visible, .input:focus-visible, .chip:focus-visible, .link:focus-visible, a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +.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); } +.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; } -.btn[aria-pressed="true"] { color: var(--accent); border-color: var(--accent); } -.link { border: 0; background: none; padding: 0; color: var(--text); cursor: pointer; text-align: left; } +/* 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); } -.input:focus { border-color: var(--accent); outline: none; } -.input[aria-invalid="true"] { border-color: var(--error); } +/* 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; } @@ -96,85 +113,125 @@ h2 { font-size: 14px; font-weight: 600; } 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[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); } .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-left: -1px; } -.segmented .btn:first-child { border-radius: var(--radius) 0 0 var(--radius); } -.segmented .btn:last-child { border-radius: 0 var(--radius) var(--radius) 0; } +.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; } +/* Panels and tiles. Panels are size containers: tables inside drop secondary columns when the panel is narrow. */ +.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; container-type: inline-size; } .panel.flush { padding: 0; gap: 0; overflow-x: auto; } -.panel-head { display: flex; align-items: center; gap: 12px; } +.panel-head { display: flex; align-items: center; gap: 12px; min-width: 0; } .panel-head h2 { flex: 1; } +.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); } -.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 20px; } +.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, .tile .sub { font-size: 12px; color: var(--text-muted); } -.tile .value { font-size: 26px; font-weight: 600; display: flex; align-items: baseline; gap: 6px; } +.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(380px, 1fr)); } -.grid.wide-right { grid-template-columns: minmax(300px, 1fr) minmax(400px, 1.4fr); } +.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) */ +/* 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); } svg.chart { width: 100%; height: auto; max-height: 220px; } 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; min-width: 40px; } +.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 (grid rows, 52 px in the admin) */ -.table { display: grid; min-width: 0; } -.table .thead, .table .row { display: grid; gap: 12px; align-items: center; padding: 0 18px; } -.table .thead { font-size: 11px; color: var(--text-muted); padding-top: 10px; padding-bottom: 10px; border-bottom: 1px solid var(--stroke); } +/* 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.compact .row { min-height: 32px; padding: 0; grid-template-columns: 1fr auto auto auto; border-bottom: 0; } +.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(80px, 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.users .thead, .table.users .row { grid-template-columns: minmax(110px, 1.4fr) 90px minmax(100px, 1.2fr) minmax(80px, 1fr) 70px 70px 230px; } -.table.jobs .thead, .table.jobs .row { grid-template-columns: 110px minmax(140px, 1.5fr) 100px minmax(110px, 1fr) 100px 80px 280px; } -.table.jobs-mini .thead, .table.jobs-mini .row { grid-template-columns: 96px minmax(120px, 1.5fr) 92px minmax(100px, 1fr) 90px 80px; padding: 0; min-height: 40px; } -.table.jobs-mini .row { border-bottom: 0; } -.table.nodes .thead, .table.nodes .row { grid-template-columns: minmax(140px, 1fr) 120px minmax(140px, 1fr) 170px 100px 100px; } -.table.audit .thead, .table.audit .row { grid-template-columns: 170px 120px 170px minmax(160px, 1fr) 130px; min-height: 40px; } +.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; } +@container (max-width: 900px) { + .table.users { grid-template-columns: minmax(140px, 1.4fr) max-content minmax(120px, 1.3fr) max-content max-content; } + .table.users .col-seen, .table.users .col-uploads { display: none; } + .table.jobs { grid-template-columns: minmax(70px, max-content) minmax(100px, 1.6fr) minmax(80px, 1fr) max-content max-content; } + .table.jobs .col-node, .table.jobs .col-created { display: none; } + .table.nodes { grid-template-columns: minmax(100px, 1fr) minmax(100px, 1.2fr) max-content max-content; } + .table.nodes .col-owner, .table.nodes .col-heartbeat { display: none; } + .table.audit { grid-template-columns: max-content minmax(70px, .8fr) minmax(90px, max-content) minmax(100px, 2fr); } + .table.audit .col-from { display: none; } +} +@container (max-width: 700px) { + .table.users { grid-template-columns: minmax(110px, 1fr) max-content max-content max-content; } + .table.users .col-quota { display: none; } +} +@container (max-width: 620px) { + .table.users { grid-template-columns: minmax(100px, 1fr) max-content max-content; } + .table.users .col-status { display: none; } +} +@container (max-width: 560px) { + .table.jobs-mini { grid-template-columns: minmax(60px, max-content) minmax(80px, 1.5fr) minmax(60px, 1fr) max-content max-content; } + .table.jobs-mini .col-node { display: none; } +} .table-foot { display: flex; align-items: center; gap: 16px; padding: 10px 18px; font-size: 12px; } -.row-actions { display: flex; gap: 6px; justify-content: flex-end; flex-wrap: wrap; } +.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: #eeeeee; color: var(--text-muted); } +.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 { display: grid; grid-template-columns: 64px 1fr; column-gap: 12px; row-gap: 9px; font-size: 12px; } -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: auto; max-height: 260px; } +.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: 1fr auto; gap: 20px; align-items: start; } -.side { width: 340px; } +.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 { display: grid; gap: 6px; color: var(--text-muted); } +.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; } +.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; } @@ -182,20 +239,20 @@ pre.log.tall { max-height: 60vh; border-top: 0; } .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); } -.fingerprint { font: 12px var(--mono); color: var(--text); overflow-wrap: anywhere; } +.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); box-shadow: 0 8px 24px rgba(0, 0, 0, .18); } -dialog.dialog::backdrop { background: rgba(0, 0, 0, .25); } +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; } +dialog.dialog h2 { font-size: 16px; overflow-wrap: anywhere; } dialog.dialog p { margin: 0; color: var(--text-muted); } -#toasts { position: fixed; right: 24px; bottom: 24px; display: grid; gap: 8px; z-index: 10; } -.toast { width: 420px; max-width: calc(100vw - 48px); padding: 12px 14px; background: var(--card); border: 1px solid var(--stroke); border-left: 3px solid var(--accent); border-radius: var(--radius-card); box-shadow: 0 4px 16px rgba(0, 0, 0, .12); } -.toast.error { border-left-color: var(--error); } +#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 1fr; gap: 8px 16px; margin: 0; } +.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; } @@ -207,13 +264,25 @@ dialog.dialog p { margin: 0; color: var(--text-muted); } .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: 1fr; } - .sidebar { flex-direction: row; overflow-x: auto; padding: 8px; position: static; height: auto; } + .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 { display: none; } .nav { display: flex; gap: 4px; } - .nav a span:not(.badge) { display: none; } - .split, .grid.wide-right { grid-template-columns: 1fr; } + .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: 1fr; } + .field { grid-template-columns: minmax(0, 1fr); } } diff --git a/src/Titano.Server/Admin/web/app.js b/src/Titano.Server/Admin/web/app.js index 29d8834a..3acf157e 100644 --- a/src/Titano.Server/Admin/web/app.js +++ b/src/Titano.Server/Admin/web/app.js @@ -1,21 +1,24 @@ // Titano Server admin panel — vanilla ES modules, no build step (BRIEF §14.8). import { api, ApiFailure } from "./api.js"; -import { t, loadStrings, applyStrings, setLanguage, languages, culture } from "./i18n.js"; +import { t, plural, loadStrings, applyStrings, setLanguage, languages, culture } from "./i18n.js"; import { icons } from "./icons.js"; -import { escapeHtml, attr, errorText, nativeName } from "./ui.js"; +import { escapeHtml, attr, errorText, nativeName, formatNumber } from "./ui.js"; const app = document.getElementById("app"); const pages = ["dashboard", "users", "archive", "jobs", "settings", "logs", "about"]; +const THEME_KEY = "titano.admin.theme"; let info = null; let events = null; const listeners = new Set(); +applyTheme(storedTheme()); + async function start() { await loadStrings(); info = await api.get("/api/v1/server/info").catch(() => null); await api.resume(); - window.addEventListener("hashchange", render); + window.addEventListener("hashchange", () => render("title")); window.addEventListener("titano:signed-out", () => { events?.stop(); events = null; @@ -29,11 +32,12 @@ function currentPage() { return pages.includes(p) ? p : "dashboard"; } -function render() { +/** 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()); + renderShell(currentPage(), focus); } function brand() { @@ -41,11 +45,12 @@ function brand() { } function renderLogin(message = "") { + document.title = `${t("Admin.Login.SignIn")} · Titano Server`; app.innerHTML = `
${brand()} - + @@ -74,6 +79,7 @@ function renderLogin(message = "") { } function renderPasswordChange() { + document.title = `${t("Admin.Password.Title")} · Titano Server`; app.innerHTML = `
@@ -114,9 +120,10 @@ function renderPasswordChange() { form.querySelector("input").focus(); } -function renderShell(page) { +function renderShell(page, focus) { const nav = pages.map((p) => ` - ${icons[p]}`).join(""); + ${icons[p]} + `).join(""); const user = api.user(); const options = languages().map((code) => ``).join(""); app.innerHTML = ` @@ -125,23 +132,25 @@ function renderShell(page) { ${brand()}
-
${escapeHtml(user.username.slice(0, 1).toUpperCase())}
-
${escapeHtml(user.username)}
+ +
${escapeHtml(user.username)}
-

+

+
-
+
`; applyStrings(app); + document.title = `${t(`Admin.Nav.${cap(page)}`)} · Titano Server`; app.querySelector("#signout").addEventListener("click", async () => { events?.stop(); events = null; @@ -150,20 +159,39 @@ function renderShell(page) { }); app.querySelector("#language").addEventListener("change", async (e) => { await setLanguage(e.target.value); - render(); + 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, - meta: app.querySelector("#meta"), + /** 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), }; @@ -174,24 +202,60 @@ function renderShell(page) { }); } +const badgeCounts = new Map(); let badgeTimer = null; +let badgeAgain = false; -/** Running jobs and accounts, as nav badges (refreshed at most every two seconds). */ +/** Running jobs and accounts as nav badges: fetched at most every two seconds (then once more if asked meanwhile). */ function updateBadges() { - if (badgeTimer) return; + 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, true)).catch(() => {}); - api.get("/api/v1/users").then((users) => setBadge("users", users.length, false)).catch(() => {}); + 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, accent) { +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}`); - if (!badge) return; + const count = badgeCounts.get(page); + if (!badge || count === undefined) return; badge.hidden = count === 0; - badge.textContent = String(count); - badge.classList.toggle("quiet", !accent); + 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) { diff --git a/src/Titano.Server/Admin/web/audit.js b/src/Titano.Server/Admin/web/audit.js new file mode 100644 index 00000000..6dab57fe --- /dev/null +++ b/src/Titano.Server/Admin/web/audit.js @@ -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 · Titano 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)]; +} diff --git a/src/Titano.Server/Admin/web/i18n.js b/src/Titano.Server/Admin/web/i18n.js index 5014e5ef..823fcd16 100644 --- a/src/Titano.Server/Admin/web/i18n.js +++ b/src/Titano.Server/Admin/web/i18n.js @@ -42,8 +42,16 @@ export function languages() { /** Localized string for key with {0}, {1}… placeholders filled from args. */ export function t(key, ...args) { const s = strings[key]; - if (s === undefined) return `⟦${key}⟧`; - return s.replace(/\{(\d+)(?:[,:][^}]*)?\}/g, (_, i) => String(args[Number(i)] ?? "")); + 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). */ @@ -64,3 +72,18 @@ export function applyStrings(root) { el.placeholder = t(el.dataset.i18nPlaceholder); }); } + +function fill(s, args) { + return s.replace(/\{(\d+)(?:[,:][^}]*)?\}/g, (_, i) => String(args[Number(i)] ?? "")); +} + +/** + * Plural category as Titano.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; +} diff --git a/src/Titano.Server/Admin/web/index.html b/src/Titano.Server/Admin/web/index.html index 12113418..8170f42a 100644 --- a/src/Titano.Server/Admin/web/index.html +++ b/src/Titano.Server/Admin/web/index.html @@ -3,13 +3,13 @@ - + Titano Server -
+
diff --git a/src/Titano.Server/Admin/web/jobs.js b/src/Titano.Server/Admin/web/jobs.js index bd0d6b41..60b49962 100644 --- a/src/Titano.Server/Admin/web/jobs.js +++ b/src/Titano.Server/Admin/web/jobs.js @@ -2,6 +2,10 @@ 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(""); } @@ -31,11 +35,24 @@ export function progressCell(job) { export function stateCell(state) { const glyph = { running: "◐", queued: "○", paused: "❚❚", done: "●", failed: "✕", cancelled: "○" }[state] ?? ""; - return `${glyph} ${escapeHtml(stateLabel(state))}`; + return ` ${escapeHtml(stateLabel(state))}`; } -/** Node encoders as "NVENC HEVC/H.264/AV1". */ +/** 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 names = [...new Set(node.encoders.map((e) => e.codec.toUpperCase()))]; - return names.join("/"); + 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(", "); } diff --git a/src/Titano.Server/Admin/web/pages/about.js b/src/Titano.Server/Admin/web/pages/about.js index f287dd9c..45c063fd 100644 --- a/src/Titano.Server/Admin/web/pages/about.js +++ b/src/Titano.Server/Admin/web/pages/about.js @@ -1,21 +1,22 @@ // About: version, API, database, uptime and the certificate fingerprint clients are asked to trust. import { applyStrings } from "../i18n.js"; -import { escapeHtml, formatDuration } from "../ui.js"; +import { escapeHtml, formatDuration, fingerprint } from "../ui.js"; -export async function render(root, { api, info }) { +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", info?.name], - ["Admin.About.Version", info?.version], - ["Admin.About.Api", info?.apiVersion], - ["Admin.About.Database", dashboard?.database], - ["Admin.About.Uptime", dashboard ? formatDuration(dashboard.uptimeSeconds) : null], - ["Admin.About.Fingerprint", info?.tlsFingerprint], + ["Admin.About.Name", `${escapeHtml(info?.name ?? "—")}`], + ["Admin.About.Version", `${escapeHtml(info?.version ?? "—")}`], + ["Admin.About.Api", `${escapeHtml(info?.apiVersion ?? "—")}`], + ["Admin.About.Database", `${escapeHtml(dashboard?.database ?? "—")}`], + ["Admin.About.Uptime", escapeHtml(dashboard ? formatDuration(dashboard.uptimeSeconds) : "—")], + ["Admin.About.Fingerprint", fingerprint(info?.tlsFingerprint)], ]; root.innerHTML = ` -
-
-
${rows.map(([key, value]) => `
${escapeHtml(value ?? "—")}
`).join("")}
-
`; +
+

+
${rows.map(([key, value]) => `
${value}
`).join("")}
+
`; applyStrings(root); } diff --git a/src/Titano.Server/Admin/web/pages/archive.js b/src/Titano.Server/Admin/web/pages/archive.js index ddd7c760..9c5db2d9 100644 --- a/src/Titano.Server/Admin/web/pages/archive.js +++ b/src/Titano.Server/Admin/web/pages/archive.js @@ -1,11 +1,11 @@ // Archive (BRIEF §14.8): naming templates, proxy policy, scan/rebuild/verify/maintenance, statistics. -import { t, applyStrings } from "../i18n.js"; -import { escapeHtml, attr, formatBytes, formatNumber, bar, columns, toast, errorText } from "../ui.js"; +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, meta }) { +export async function render(root, { api, setMeta }) { let settings; let stats; try { @@ -14,57 +14,58 @@ export async function render(root, { api, meta }) { root.innerHTML = `
${escapeHtml(errorText(err))}
`; return; } - meta.textContent = settings.rootPath; + 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) => ``).join(""); + const statsTable = (rows, labelId) => rows.length === 0 ? "" : `
${rows.map((r) => + `
${escapeHtml(r.label)}${formatNumber(r.count)}${escapeHtml(formatBytes(r.bytes))}
`).join("")}
`; + const scanButton = ``; root.innerHTML = `
-
${formatNumber(stats.sequences)} - ${escapeHtml(t("Admin.Dashboard.PhotosCameras", formatNumber(stats.photos), formatNumber(stats.cameras)))}
-
${escapeHtml(formatBytes(stats.bytes))} - ${escapeHtml(stats.firstYear ? `${stats.firstYear}–${stats.lastYear}` : "—")}
-
${escapeHtml(formatBytes(stats.freeBytes))} - ${bar(used)}${escapeHtml(t("Admin.Dashboard.Of", formatBytes(stats.capacityBytes)))}
-
${formatNumber(stats.unverifiedSequences)} - ${escapeHtml(t("Admin.Dashboard.NoProxies", formatNumber(stats.sequencesWithoutProxies)))}
+

${formatNumber(stats.sequences)} + ${escapeHtml(`${plural("Admin.Dashboard.PhotoCount", stats.photos)} · ${plural("Admin.Dashboard.CameraCount", stats.cameras)}`)}
+

${escapeHtml(formatBytes(stats.bytes))} + ${escapeHtml(stats.firstYear ? `${stats.firstYear}–${stats.lastYear}` : "—")}
+

${escapeHtml(formatBytes(stats.freeBytes))} + ${bar(used)}${escapeHtml(t("Admin.Dashboard.Of", formatBytes(stats.capacityBytes)))}
+

${formatNumber(stats.unverifiedSequences)}${escapeHtml(plural("Admin.Archive.UnverifiedUnit", stats.unverifiedSequences))} + ${escapeHtml(plural("Admin.Dashboard.WithoutProxies", stats.sequencesWithoutProxies))}
- -

- - - + +

+ + +
-
-

+
+

${ACTIONS.map((a) => ``).join("")}
-

-
- ${stats.byCamera.slice(0, 8).map((c) => `
${escapeHtml(c.key || "—")}${formatNumber(c.count)}${escapeHtml(formatBytes(c.bytes))}
`).join("") - || `

`} -
-
+

+ ${statsTable(stats.byCamera.slice(0, 8).map((c) => ({ label: c.key || "—", count: c.count, bytes: c.bytes })), "cameras-title") + || `

`} +
-

- ${stats.byYear.length === 0 ? `

` - : columns(stats.byYear.map((y) => ({ label: y.key, value: y.bytes, title: `${y.key} · ${formatBytes(y.bytes)}` })), { valueLabel: (i) => formatBytes(i.value) })}
-

-
- ${stats.byFormat.map((f) => `
${escapeHtml(f.key.toUpperCase())}${formatNumber(f.count)}${escapeHtml(formatBytes(f.bytes))}
`).join("") - || `

`} -
+

+ ${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) })}
+

+ ${statsTable(stats.byFormat.map((f) => ({ label: f.key.toUpperCase(), count: f.count, bytes: f.bytes })), "formats-title") + || emptyState("Admin.Dashboard.NoData", scanButton)}
`; applyStrings(root); const form = root.querySelector("form"); + escapeReverts(form); form.addEventListener("submit", async (e) => { e.preventDefault(); - form.querySelectorAll("[aria-invalid]").forEach((el) => el.removeAttribute("aria-invalid")); + form.querySelectorAll("[aria-invalid]").forEach(clearInvalid); const data = new FormData(form); try { settings = await api.put("/api/v1/archive/settings", { @@ -74,15 +75,23 @@ export async function render(root, { api, meta }) { 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) { - field.setAttribute("aria-invalid", "true"); - field.title = errorText(err); + markInvalid(field, message); + field.focus(); } - toast(errorText(err), true); + toast(message, true); } }); root.querySelectorAll("[data-action]").forEach((button) => button.addEventListener("click", async () => { @@ -94,6 +103,7 @@ export async function render(root, { api, meta }) { toast(errorText(err), true); } finally { button.disabled = false; + button.focus(); } })); } diff --git a/src/Titano.Server/Admin/web/pages/dashboard.js b/src/Titano.Server/Admin/web/pages/dashboard.js index 697d83b4..6707d50f 100644 --- a/src/Titano.Server/Admin/web/pages/dashboard.js +++ b/src/Titano.Server/Admin/web/pages/dashboard.js @@ -1,9 +1,12 @@ // Dashboard (mockup Admin.html, BRIEF §14.8): storage, archive, jobs, render nodes, charts, activity, active jobs. -import { t, has, applyStrings } from "../i18n.js"; -import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, columns, toast, errorText } from "../ui.js"; -import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders, pascal } from "../jobs.js"; +import { t, plural, applyStrings, culture } from "../i18n.js"; +import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, columns, toast, errorText, emptyState, redraw } from "../ui.js"; +import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders } from "../jobs.js"; +import { activityText } from "../audit.js"; -export async function render(root, { api, meta, onEvent }) { +const SCAN_BUTTON = ``; + +export async function render(root, { api, setMeta, onEvent }) { let timer = null; const refresh = () => { clearTimeout(timer); @@ -18,8 +21,13 @@ export async function render(root, { api, meta, onEvent }) { root.innerHTML = `
${escapeHtml(errorText(err))}
`; return; } - meta.textContent = t("Admin.Dashboard.Meta", formatDuration(d.uptimeSeconds), d.database, d.tlsMode, - t(d.discovery ? "Admin.Dashboard.DiscoveryOn" : "Admin.Dashboard.DiscoveryOff")); + 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"))); 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"); @@ -29,61 +37,68 @@ export async function render(root, { api, meta, onEvent }) { root.innerHTML = `
-
- +
+

${escapeHtml(formatBytes(a.capacityBytes - a.freeBytes))}${escapeHtml(t("Admin.Dashboard.Of", formatBytes(a.capacityBytes)))} ${bar(used)} ${escapeHtml(t("Admin.Dashboard.Free", formatBytes(a.freeBytes)))} · ${escapeHtml(t("Admin.Dashboard.Originals", formatBytes(a.bytes)))} -
-
- - ${formatNumber(a.sequences)} - ${escapeHtml(t("Admin.Dashboard.PhotosCameras", formatNumber(a.photos), formatNumber(a.cameras)))} - ${escapeHtml(t("Admin.Dashboard.NoProxies", formatNumber(a.sequencesWithoutProxies)))} -
-
- + +
+

+ ${formatNumber(a.sequences)}${escapeHtml(plural("Admin.Dashboard.SequenceUnit", a.sequences))} + ${escapeHtml(`${plural("Admin.Dashboard.PhotoCount", a.photos)} · ${plural("Admin.Dashboard.CameraCount", a.cameras)}`)} + ${escapeHtml(plural("Admin.Dashboard.WithoutProxies", a.sequencesWithoutProxies))} +
+
+

${formatNumber(d.jobs.running)} - ${escapeHtml(t("Admin.Dashboard.JobCounts", formatNumber(d.jobs.queued), formatNumber(d.jobs.doneToday), formatNumber(d.jobs.failedToday)))} - ${escapeHtml(t("Admin.Dashboard.Workers", formatNumber(d.workers)))} -
-
- + ${escapeHtml([plural("Admin.Dashboard.QueuedCount", d.jobs.queued), plural("Admin.Dashboard.DoneToday", d.jobs.doneToday), + plural("Admin.Dashboard.FailedToday", d.jobs.failedToday)].join(" · "))} + ${escapeHtml(plural("Admin.Dashboard.WorkerCount", d.workers))} + +
+

${formatNumber(online.length)} - ${online.slice(0, 2).map((n) => `${escapeHtml(n.clientName)} · ${escapeHtml(encoders(n))} · ${escapeHtml(stateLabel(n.state))}`).join("")} -
+ ${online.slice(0, 2).map((n) => `${escapeHtml(n.clientName)} · ${escapeHtml(encoders(n))} · ${escapeHtml(stateLabel(n.state))}`).join("")} +
-
+

- ${a.byYear.length === 0 ? `

` - : columns(a.byYear.map((y) => ({ label: y.key, value: y.bytes, title: `${y.key} · ${formatBytes(y.bytes)} · ${formatNumber(y.count)}` })), { valueLabel: (i) => formatBytes(i.value) })} -
-
+ ${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) })} + +

- ${escapeHtml(t("Admin.Dashboard.UploadTotals", formatNumber(totalUploads), formatNumber(peak)))}
- ${columns(uploads, { sun: true })} -
+ ${escapeHtml(t("Admin.Dashboard.UploadTotals", formatNumber(totalUploads), formatNumber(peak)))}
+ ${columns(uploads, { label: t("Admin.Dashboard.Uploads"), sun: true, edgeLabels: true })} +
-
+

-
${d.activity.map((e) => `${escapeHtml(formatTime(e.at))}${escapeHtml(activityText(e))}`).join("")}
- ${d.activity.length === 0 ? `

` : ""} -
-
+ ${d.activity.length === 0 ? emptyState("Admin.Dashboard.NoActivity", ``) + : `
    ${d.activity.map((e) => `
  • ${escapeHtml(activityText(e))}
  • `).join("")}
`} + +

- ${d.activeJobs.length === 0 ? `

` : ` -
-
- ${d.activeJobs.map((j) => ` -
- ${escapeHtml(kindLabel(j.kind))}${escapeHtml(j.targetLabel ?? "")}${escapeHtml(nodeLabel(j, d.nodes))} - ${progressCell(j)}${stateCell(j.state)} - -
`).join("")} + ${d.activeJobs.length === 0 ? emptyState("Admin.Jobs.Empty", SCAN_BUTTON) : ` +
+
+ +
+
${d.activeJobs.map((j) => ` +
+ ${escapeHtml(kindLabel(j.kind))} + ${escapeHtml(j.targetLabel ?? "")} + ${escapeHtml(nodeLabel(j, d.nodes))} + ${progressCell(j)}${stateCell(j.state)} + +
`).join("")}
`} -
+
`; applyStrings(root); root.querySelectorAll("[data-cancel]").forEach((button) => button.addEventListener("click", async () => { @@ -96,11 +111,20 @@ export async function render(root, { api, meta, onEvent }) { 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); } onEvent((e) => { if (e.type === "jobProgress") { - const cell = root.querySelector(`[data-job="${CSS.escape(e.jobId)}"] .progress`); + const cell = root.querySelector(`[data-key="${CSS.escape(e.jobId)}"] .progress`); if (cell) cell.innerHTML = progressCell({ progressDone: e.done, progressTotal: e.total }); } else { refresh(); @@ -109,23 +133,17 @@ export async function render(root, { api, meta, onEvent }) { await load(); } -/** One sentence per audit entry, e.g. "alberto signed in" (unknown actions show their code). */ -function activityText(entry) { - const key = `Admin.Activity.${pascal(entry.action)}`; - return has(key) ? t(key, entry.username ?? "—", entry.details ?? "") : `${entry.username ?? ""} ${entry.action}`; -} - -/** Frames per UTC day for the last 30 days, zero-filled. */ +/** 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 key = day.toISOString().slice(0, 10); - const value = byDay.get(key) ?? 0; - const label = i === 29 || i === 0 ? new Intl.DateTimeFormat(document.documentElement.lang, { day: "numeric", month: "short" }).format(day) : ""; - items.push({ value, label, title: `${key} · ${formatNumber(value)}` }); + 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; } diff --git a/src/Titano.Server/Admin/web/pages/jobs.js b/src/Titano.Server/Admin/web/pages/jobs.js index a4ce6966..79f47492 100644 --- a/src/Titano.Server/Admin/web/pages/jobs.js +++ b/src/Titano.Server/Admin/web/pages/jobs.js @@ -1,95 +1,117 @@ // Jobs (BRIEF §14.8): queue and history with cancel/pause/resume/retry/priority, log tails, render nodes. -import { t, applyStrings } from "../i18n.js"; -import { escapeHtml, attr, formatTime, formatDateTime, toast, errorText, confirmDialog } from "../ui.js"; -import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders } from "../jobs.js"; +import { t, plural, applyStrings } from "../i18n.js"; +import { escapeHtml, attr, formatTime, formatDateTime, toast, errorText, confirmDialog, emptyState, redraw } 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, meta, onEvent }) { +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 = ` -
${FILTERS.map((f) => ``).join("")}
-
-
-
-
-
+
${FILTERS.map((f) => ``).join("")}
+
+
+
+ + +
+
-
-
-

-
-
-
-
+ +
+

+
+
+ +
+
-
`; + `; applyStrings(root); - root.querySelectorAll("[data-filter]").forEach((chip) => chip.addEventListener("click", () => { - filter = chip.dataset.filter; - root.querySelectorAll("[data-filter]").forEach((c) => c.setAttribute("aria-pressed", String(c === chip))); - load(); - })); + 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 = await api.get(`/api/v1/jobs?limit=50${state}${more && cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`); + 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 = await api.get("/api/v1/nodes"); + nodes = list; + running = active.items.length; } catch (err) { toast(errorText(err), true); return; } - const running = jobs.filter((j) => j.state === "running").length; - meta.textContent = t("Admin.Jobs.Meta", running, nodes.filter((n) => n.state !== "offline").length); + 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"); - host.innerHTML = jobs.map((j) => ` -
- - ${escapeHtml(j.targetLabel ?? "")} - ${escapeHtml(nodeLabel(j, nodes))} - ${progressCell(j)} - ${stateCell(j.state)} - ${escapeHtml(formatTime(j.created))} - ${buttons(j)} -
- ${expanded.has(j.id) ? `
${escapeHtml(j.error ? `${j.logTail ?? ""}\n${j.error}`.trim() : j.logTail ?? "")}
` : ""}`).join("") - || `
`; - applyStrings(host); + redraw(host, () => { + host.innerHTML = jobs.map((j) => ` +
+ + ${escapeHtml(j.targetLabel ?? "")} + ${escapeHtml(nodeLabel(j, nodes))} + ${progressCell(j)} + ${stateCell(j.state)} + ${escapeHtml(formatTime(j.created))} + ${buttons(j)} +
+ ${expanded.has(j.id) ? `
${escapeHtml(logText(j))}
` : ""}`).join("") + || `
${filter === "all" + ? emptyState("Admin.Jobs.Empty", ``) + : emptyState("Admin.Jobs.Empty", ``)}
`; + 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(".row").dataset.job, b.dataset.act))); + 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"); - nodeHost.innerHTML = nodes.map((n) => ` -
- ${escapeHtml(n.clientName)}${escapeHtml(n.username)} - ${escapeHtml(encoders(n))} - ${escapeHtml(formatDateTime(n.lastHeartbeat))} - ${n.state === "offline" ? "○" : "●"} ${escapeHtml(stateLabel(n.state))} - -
`).join("") || `
`; - applyStrings(nodeHost); + redraw(nodeHost, () => { + nodeHost.innerHTML = nodes.map((n) => ` +
+ ${escapeHtml(n.clientName)} + ${escapeHtml(n.username)} + ${escapeHtml(encoders(n))} + ${escapeHtml(formatDateTime(n.lastHeartbeat))} + ${escapeHtml(stateLabel(n.state))} + +
`).join("") + || `
${emptyState("Admin.Jobs.NoNodes", + ``)}
`; + applyStrings(nodeHost); + }); nodeHost.querySelectorAll("[data-forget]").forEach((b) => b.addEventListener("click", () => forget(nodes.find((n) => n.id === b.dataset.forget)))); } @@ -124,6 +146,15 @@ export async function render(root, { api, meta, onEvent }) { } } + 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), @@ -147,7 +178,7 @@ export async function render(root, { api, meta, onEvent }) { if (job) { job.progressDone = e.done; job.progressTotal = e.total; - const cell = root.querySelector(`[data-job="${CSS.escape(e.jobId)}"] .progress`); + 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") { diff --git a/src/Titano.Server/Admin/web/pages/logs.js b/src/Titano.Server/Admin/web/pages/logs.js index 405fb917..0d8c3d5d 100644 --- a/src/Titano.Server/Admin/web/pages/logs.js +++ b/src/Titano.Server/Admin/web/pages/logs.js @@ -1,18 +1,18 @@ -// Logs (BRIEF §14.8): server log tail and downloads, diagnostics bundle, sign-in log, audit log. -import { t, has, applyStrings } from "../i18n.js"; -import { escapeHtml, attr, formatBytes, formatDateTime, toast, errorText, routeParams } from "../ui.js"; -import { pascal } from "../jobs.js"; +// 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 } 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, meta, actions }) { +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 = `
${VIEWS.map((v) => + actions.innerHTML = `
${VIEWS.map((v) => ``).join("")}
`; applyStrings(actions); actions.querySelectorAll("[data-view]").forEach((b) => b.addEventListener("click", () => { @@ -23,7 +23,7 @@ export async function render(root, { api, meta, actions }) { })); async function show() { - meta.textContent = ""; + setMeta(""); if (view === "server") await showServerLog(); else await showAudit(false); } @@ -37,37 +37,41 @@ export async function render(root, { api, meta, actions }) { toast(errorText(err), true); return; } - meta.textContent = tail.file; + setMeta(tail.file, { ltr: true }); root.innerHTML = ` -
+
- +
-
${escapeHtml(tail.lines.join("\n"))}
-
-
-

-
${files.map((f) => ` -
${escapeHtml(f.name)}${escapeHtml(formatBytes(f.size))} - ${escapeHtml(formatDateTime(f.modified))} -
`).join("")} -
-
`; +
${escapeHtml(tail.lines.join("\n"))}
+ +
+

+
${files.map((f) => ` +
${escapeHtml(f.name)}${escapeHtml(formatBytes(f.size))} + ${escapeHtml(formatDateTime(f.modified))} +
`).join("")} +
+
`; applyStrings(root); const pre = root.querySelector("pre"); pre.scrollTop = pre.scrollHeight; - root.querySelector("#lines").addEventListener("change", (e) => { + root.querySelector("#lines").addEventListener("change", async (e) => { lines = Number(e.target.value); - showServerLog(); + await showServerLog(); + root.querySelector("#lines").focus(); + }); + root.querySelector("#refresh").addEventListener("click", async () => { + await showServerLog(); + root.querySelector("#refresh").focus(); }); - root.querySelector("#refresh").addEventListener("click", showServerLog); } async function showAudit(more) { - const action = view === "signins" ? "&action=login" : ""; + 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; @@ -77,29 +81,35 @@ export async function render(root, { api, meta, actions }) { return; } root.innerHTML = ` -
-
-
-
- ${audit.map((e) => ` -
${escapeHtml(formatDateTime(e.at))}${escapeHtml(e.username ?? "—")} - ${escapeHtml(actionLabel(e.action))}${escapeHtml(e.details ?? "")} - ${escapeHtml(e.remoteAddress ?? "")}
`).join("") || `
`} +
+
+
+ +
+
${audit.map((e) => { + const details = detailText(e); + return ` +
${escapeHtml(formatDateTime(e.at))} + ${escapeHtml(e.username ?? "—")} + ${e.action === "login_failed" ? ` ${escapeHtml(actionLabel(e.action))}` : escapeHtml(actionLabel(e.action))} + ${escapeHtml(details)} + ${escapeHtml(e.remoteAddress ?? "")}
`; + }).join("") || `
${emptyState("Admin.Logs.Empty", + ``)}
`}
${cursor ? `
` : ""} -
`; + `; applyStrings(root); - root.querySelector("#more")?.addEventListener("click", () => showAudit(true)); + root.querySelector("#more")?.addEventListener("click", async () => { + await showAudit(true); + root.querySelector("#more")?.focus(); + }); + root.querySelector("#reload")?.addEventListener("click", () => showAudit(false)); } await show(); } -function actionLabel(action) { - const key = `Admin.Logs.Action.${pascal(action)}`; - return has(key) ? t(key) : action; -} - function cap(s) { return s.charAt(0).toUpperCase() + s.slice(1); } diff --git a/src/Titano.Server/Admin/web/pages/settings.js b/src/Titano.Server/Admin/web/pages/settings.js index 8659c01b..484fe805 100644 --- a/src/Titano.Server/Admin/web/pages/settings.js +++ b/src/Titano.Server/Admin/web/pages/settings.js @@ -1,17 +1,20 @@ // Settings (BRIEF §14.8): server name, ports, TLS, discovery, limits, language, retention. Values fixed by environment // variables are read-only here; ports, TLS, workers, chunk size and job history apply at the next restart. import { t, applyStrings, languages } from "../i18n.js"; -import { escapeHtml, attr, toast, errorText, nativeName } from "../ui.js"; +import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, markInvalid, clearInvalid, invalidText, escapeReverts } from "../ui.js"; /** Setting → environment variable that can fix it (BRIEF §14.9). */ const VARIABLES = { serverName: "TITANO_SERVER_NAME", httpPort: "TITANO_HTTP_PORT", httpsPort: "TITANO_HTTPS_PORT", tlsMode: "TITANO_TLS_MODE", tlsCert: "TITANO_TLS_CERT", tlsKey: "TITANO_TLS_KEY", language: "TITANO_LANG", workers: "TITANO_WORKERS", discovery: "TITANO_DISCOVERY", }; +/** 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, meta }) { +export async function render(root, { api, info, setMeta, actions }) { let settings; try { settings = await api.get("/api/v1/server/settings"); @@ -19,19 +22,22 @@ export async function render(root, { api, info, meta }) { root.innerHTML = `
${escapeHtml(errorText(err))}
`; return; } + setMeta(""); + // In the header, like the other pages' main action, so toasts never cover it. + actions.innerHTML = ``; + 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) => ``; - const number = (name, value, attrs = "") => field(name, ``); - const text = (name, value) => field(name, ``); + const number = (name, value, attrs = "") => field(name, ``); + const text = (name, value, attrs = "dir=\"auto\"") => field(name, ``); function draw() { - meta.textContent = ""; root.innerHTML = ` -
-
-

+ +
+

${settings.restartRequired ? `` : ""}
${text("serverName", settings.serverName)} ${field("language", ``)}
-
-

+
+

${number("httpPort", settings.httpPort, 'min="1" max="65535"')} ${number("httpsPort", settings.httpsPort, 'min="1" max="65535"')} ${field("tlsMode", ``)} - ${text("tlsCert", settings.tlsCert)} - ${text("tlsKey", settings.tlsKey)} - ${field("fingerprint", `${escapeHtml(info?.tlsFingerprint ?? "—")}`)} + ${text("tlsCert", settings.tlsCert, 'dir="ltr" spellcheck="false"')} + ${text("tlsKey", settings.tlsKey, 'dir="ltr" spellcheck="false"')} +
${fingerprint(info?.tlsFingerprint)}
-
-

+
+

${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"')}
-
`; applyStrings(root); - root.querySelector("form").addEventListener("submit", save); + const form = root.querySelector("form"); + escapeReverts(form); + form.addEventListener("submit", save); + form.elements.tlsMode.addEventListener("change", () => pemFiles(form)); + pemFiles(form); + } + + /** 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 = { @@ -90,13 +111,15 @@ export async function render(root, { api, info, meta }) { draw(); toast(t("Admin.Common.Saved")); } catch (err) { - toast(errorText(err), true); - const name = err.details && Object.keys(form.elements).find((k) => k.toLowerCase() === String(err.details).toLowerCase()); - const input = name ? form.elements[name] : null; - if (input) { - input.setAttribute("aria-invalid", "true"); - input.title = errorText(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); } } diff --git a/src/Titano.Server/Admin/web/pages/users.js b/src/Titano.Server/Admin/web/pages/users.js index 14eea30a..756d425e 100644 --- a/src/Titano.Server/Admin/web/pages/users.js +++ b/src/Titano.Server/Admin/web/pages/users.js @@ -1,24 +1,29 @@ -// Users (mockup AdminUsers.html, BRIEF §14.8): accounts table and a side panel to create, edit and reset. -import { t, applyStrings } from "../i18n.js"; -import { escapeHtml, attr, formatBytes, formatNumber, formatTime, bar, toast, confirmDialog, errorText } from "../ui.js"; +// 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 } 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, meta, actions }) { +export async function render(root, { api, info, setMeta, actions }) { let users = []; let filter = ""; let freeBytes = 0; let tokenDays = 30; + let opener = null; actions.innerHTML = ` - + `; applyStrings(actions); - actions.querySelector("#search").addEventListener("input", (e) => { - filter = e.target.value.trim().toLowerCase(); + const search = actions.querySelector("#search"); + search.addEventListener("input", () => { + filter = search.value.trim().toLowerCase(); drawTable(); }); actions.querySelector("#new").addEventListener("click", () => openForm(null)); @@ -26,10 +31,13 @@ export async function render(root, { api, info, meta, actions }) { root.innerHTML = `
-
-
-
-
+
+
+ + + +
+
@@ -37,6 +45,13 @@ export async function render(root, { api, info, meta, actions }) {
`; applyStrings(root); + const side = root.querySelector("#side"); + side.addEventListener("keydown", (e) => { + if (e.key === "Escape") { + e.preventDefault(); + closeSide(); + } + }); async function load() { try { @@ -53,53 +68,67 @@ export async function render(root, { api, info, meta, actions }) { return; } const active = users.filter((u) => !u.user.disabled).length; - meta.textContent = t("Admin.Users.Meta", formatNumber(users.length), formatNumber(active)); - root.querySelector("#policy").textContent = t("Admin.Users.Policy", info?.limits?.passwordMinLength ?? 10, tokenDays); + 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 rows = users.filter((u) => !filter || u.user.username.toLowerCase().includes(filter) || (u.user.displayName ?? "").toLowerCase().includes(filter)); const host = root.querySelector("#rows"); - host.innerHTML = rows.map((row) => { - const u = row.user; - const subtitle = [u.displayName, u.mustChangePassword ? t("Admin.Users.MustChange") : null, u.disabled ? t("Admin.Users.Disabled") : null] - .filter(Boolean).join(" · "); - const quota = u.quotaBytes > 0 - ? `
${bar(u.usedBytes / u.quotaBytes, u.disabled)}${escapeHtml(t("Admin.Users.QuotaOf", formatBytes(u.usedBytes), formatBytes(u.quotaBytes)))}
` - : `${escapeHtml(u.usedBytes > 0 ? formatBytes(u.usedBytes) : "—")}`; - const seen = row.lastSeen ? `${formatTime(row.lastSeen)}${row.lastClient ? " · " + row.lastClient : ""}` : "—"; - const buttons = u.disabled - ? ` - ` - : ` - - ${u.id === api.user().id ? "" : ``}`; - return ` -
- ${escapeHtml(u.username.slice(0, 1).toUpperCase())} - ${escapeHtml(u.username)}${escapeHtml(subtitle)} - - ${quota} - ${escapeHtml(seen)} - ${formatNumber(row.uploadsLast30Days)} - ${u.disabled ? "○" : "●"} - ${buttons} -
`; - }).join("") || `
`; - applyStrings(host); + 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("") || `
${emptyState("Admin.Users.Empty", + ``)}
`; + applyStrings(host); + }); host.querySelectorAll("[data-act]").forEach((button) => button.addEventListener("click", () => { - const row = users.find((u) => u.user.id === button.closest(".row").dataset.id); + 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(); + }); + } + + 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 + ? `
${bar(u.usedBytes / u.quotaBytes, u.disabled)}${escapeHtml(quotaText)}
` + : `${escapeHtml(u.usedBytes > 0 ? formatBytes(u.usedBytes) : "—")}`; + const seen = row.lastSeen ? `${formatTime(row.lastSeen)}${row.lastClient ? " · " + row.lastClient : ""}` : "—"; + const button = (act, key, extra = "") => ``; + 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 ` +
+ + ${escapeHtml(u.username)} + ${escapeHtml(subtitle)} + + ${quota} + ${escapeHtml(seen)} + ${formatNumber(row.uploadsLast30Days)} + + + ${buttons} +
`; } async function act(action, user) { try { if (action === "edit") return openForm(user); + if (action === "password") return openPasswordForm(); if (action === "reset") { - const r = await api.post(`/api/v1/users/${user.id}/reset-password`, {}); - showPassword(r); + 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") { @@ -121,49 +150,61 @@ export async function render(root, { api, info, meta, actions }) { } } + /** 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); + side.querySelector("#close").addEventListener("click", closeSide); + } + + function closeSide() { + side.hidden = true; + side.innerHTML = ""; + if (opener) restoreFocus(opener.scope, opener.place); + opener = null; + } + function openForm(user) { - const side = root.querySelector("#side"); 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; - side.hidden = false; - side.innerHTML = ` + openSide(`

+ +
${ROLES.map((r) => ``).join("")}
${editing ? "" : ` `} -
-
`; - applyStrings(side); + `); const form = side.querySelector("form"); - side.querySelector("#close").addEventListener("click", () => { - side.hidden = true; - }); side.querySelector("#regenerate")?.addEventListener("click", () => { form.elements.password.value = generatePassword(); + clearInvalid(form.elements.password); }); form.addEventListener("submit", async (e) => { e.preventDefault(); - const error = form.querySelector(".error"); - error.textContent = ""; + form.querySelectorAll("[aria-invalid]").forEach(clearInvalid); const data = new FormData(form); const quotaBytes = Math.round(Number(data.get("quota") || 0) * TB); try { @@ -171,51 +212,91 @@ export async function render(root, { api, info, meta, actions }) { await api.patch(`/api/v1/users/${user.id}`, { displayName: String(data.get("displayName")), role: data.get("role"), quotaBytes, allowRenderNode: data.get("renderNode") === "on", }); - side.hidden = true; + closeSide(); } else { - const r = await api.post("/api/v1/users", { + 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", - }); - showPassword(r); + })); } await load(); } catch (err) { - error.textContent = errorText(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) => ``; + openSide(` +
+

+ ${field("current", "Current", "current-password")}${field("next", "New", "new-password")}${field("repeat", "Repeat", "new-password")} +
+ + +
+
`); + 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) { - const side = root.querySelector("#side"); - side.hidden = false; - side.innerHTML = ` + openSide(`
-

${escapeHtml(result.user.username)}

+

${escapeHtml(result.user.username)}

-
`; - applyStrings(side); +
`); + const input = side.querySelector("input"); side.querySelector("#copy").addEventListener("click", async () => { try { await navigator.clipboard.writeText(result.temporaryPassword); toast(t("Admin.Users.Copied")); } catch { - side.querySelector("input").select(); + input.select(); } }); - side.querySelector("#close").addEventListener("click", () => { - side.hidden = true; - }); + 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"; diff --git a/src/Titano.Server/Admin/web/ui.js b/src/Titano.Server/Admin/web/ui.js index a9f25e67..a9187f4c 100644 --- a/src/Titano.Server/Admin/web/ui.js +++ b/src/Titano.Server/Admin/web/ui.js @@ -44,6 +44,11 @@ export function formatDuration(seconds) { 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 ? `${String(value).split(":").map(escapeHtml).join(":")}` : "—"; +} + /** 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))); @@ -52,28 +57,38 @@ export function bar(fraction, muted = false) { } /** - * Column chart: values with labels under each bar and, when given, the value above it. - * Bars use the accent colour, or the sun colour for upload activity. + * 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, { sun = false, valueLabel = null, height = 190 } = {}) { +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 = ``; + let svg = ``; svg += ``; 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 += `${escapeHtml(item.title ?? "")}`; - if (valueLabel) svg += `${escapeHtml(valueLabel(item))}`; - if (item.label) svg += `${escapeHtml(item.label)}`; + if (valueLabel) svg += `${escapeHtml(valueLabel(item))}`; + 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 += `${escapeHtml(item.label)}`; }); return svg + ""; } -/** Shows a toast at the bottom right for 8 s (hover pauses). */ +/** An empty state: one sentence and one button (BRIEF §0.2). */ +export function emptyState(sentenceKey, button = "") { + return `
${button}
`; +} + +/** 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"); @@ -94,28 +109,35 @@ export function toast(message, isError = false) { }); } +let dialogs = 0; + /** - * Two-button confirmation dialog (safe action left and default). Resolves true when the destructive action is chosen; - * with `typed`, that button stays disabled until the text is typed. + * 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 = `
-

${escapeHtml(title)}

- ${body ? `

${escapeHtml(body)}

` : ""} - ${typed ? `` : ""} +

${escapeHtml(title)}

+ ${body ? `

${escapeHtml(body)}

` : ""} + ${typed ? `` : ""}
- +
`; 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"); @@ -130,6 +152,89 @@ 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; + 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); + }); +} + +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] ?? "");