diff --git a/.gitignore b/.gitignore index 53c5b8c..cb53f20 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ node_modules/ .devdata/ +# A second dev instance beside the first (another port, another data folder). +.devdata-*/ .dockerdata/ *.log .DS_Store diff --git a/CHANGELOG.md b/CHANGELOG.md index 9dacf85..e1d567c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,6 +72,72 @@ changes what your listeners see, it says so. (libheif and librsvg), music-metadata 11.16.1 (crafted MP4, EBML and DSF files could crash the scanner — and the scanner reads whatever is dropped on the share). `npm audit` is clean. +### Fixed — things you could do that gave no answer, or the wrong one + +- **Remove or delete from an episode's own page now works.** The response re-targeted the + episode table, which only the show page has; on the episode page htmx refused it and the + page went on showing an episode that was gone. Both actions now take you to the show, with + the confirmation, when they were started on the episode page. +- **Check now, Pause, Resume and Stop following on the Subscription page do something you + can see.** They used to post into a redirect the browser swallowed; the page re-reads + itself now and says what happened. Stop following asks first, like every other action + that cannot be undone. +- **A password change is confirmed with a real notice.** The toast arrived as bare text with + a × that threw. +- **A button that is working says so.** Every decision, teach, check, rescan and settings + button is held while its request is out and shows a ring; a second press while one is in + flight is dropped rather than queued. A request that gets no answer at all — offline, a + tunnel that dropped, an extension in the way — now says so instead of failing in silence, + and a session that has run out no longer flashes "Something went wrong" on its way to the + sign-in page. +- **Check now and Teach no longer hold the page for the whole pass.** The panel comes back at + once with a note, and the work strip follows the pass; the plain-form path still waits. +- **A background refresh no longer wipes what you are typing.** The Adverts panel and the + episode's cuts card re-read themselves after every pass, scheduled ones included, and used + to throw away a half-typed boundary and close the settings fold under you. A refresh now + waits while a field inside it is in use, and is taken once it is not; a fold you opened + stays open; and the second render after every decision — the stream announcing what the + response already carried — is gone. +- **The Show page topbar fits a phone**: the actions take a row of their own under the + breadcrumb instead of pushing it onto four lines and "Follow a feed" off the edge. +- **The access log and the statistics tables are readable on a phone**: each row is a block + with its column names, like the episode table already was, rather than a six-column table + scrolling sideways. The column headers stay for screen readers. +- **The scan-progress strip sent over the live stream could be left behind forever** when + the stream dropped mid-scan: the streamed copy omitted the poll the clicked one has. It is + the same strip now. +- "New show" no longer opens with "New show" already typed into the name, and a refused form + keeps what you typed. The upload queue's success line is no longer painted red. The + dashboard is highlighted in the sidebar when you are on it — and `aria-current` on the + sidebar's current item is now a real attribute rather than escaped text. Settings toggles + and inline saves confirm themselves. The cut pill in the episode table links to the + episode page, where the bar always is, rather than to an anchor the Adverts page may have + paged away. + +### Changed + +- **A date at the start of a filename is the episode's publish date.** `2026-09-01-…`, + `2026_09_01…` or `20260901…` is taken as that day at midnight in `TZ`, unless the file's + modification time already falls on that day, in which case the time of day is kept. Three + dated files copied onto the share together used to land on the one minute they were + copied. Undated files keep the modification time, and a date set on the episode page is + never changed by a rescan. README, *How it finds new episodes*. +- **Colour and size, for people and thumbs.** Primary buttons, accent-coloured text and + selected chips use the darker terracotta (`#B84A1E`, 7.4:1 on white) rather than the one + that fell short of AA for text; the signal colour stays on bars, dots and marks. Muted + grey text that carried information — the "· test" affordance, stat-card hints, timestamps, + label hints — is a shade darker. On a touch screen every control is at least 44px: the + stretch ▶, the toast ×, chips, sign-out, the menu button, the small decision buttons, and + the cut bar gets a taller area to tap without looking any different. +- **Keyboard focus survives a swap.** After saving a setting, sorting the log, restoring an + episode or closing a modal, focus goes back to the control it was on — or to the control + that opened the modal — rather than to the top of the page. Errors are announced as alerts + and stay until dismissed; other notices stay six seconds plus fifty milliseconds a + character, and pausing with the pointer resumes when it leaves. The two Settings switches + have accessible names, card titles are real headings, a refused field says so to assistive + technology, the current breadcrumb is marked, and a refused sign-in puts the cursor on the + password. + ## 1.9.1 — 2026-09-16 ### Fixed diff --git a/README.md b/README.md index 353c88b..4f9ad29 100644 --- a/README.md +++ b/README.md @@ -263,7 +263,7 @@ of it can be changed later in **Settings** without touching the container. |---|---|---| | `PUBLIC_BASE_URL` | — | The address your proxy serves SelfPod on, e.g. `https://podcast.example.com`. Every feed and media URL is built from it. No trailing slash. Can also be set in the setup wizard. | | `PUID` / `PGID` | `1000` | The user and group SelfPod runs as. Match the owner of your audio files. | -| `TZ` | `UTC` | Used for displayed dates and an episode's default publish date. | +| `TZ` | `UTC` | Used for displayed dates and an episode's default publish date — see [How it finds new episodes](#how-it-finds-new-episodes). | | `PORT` | `8080` | Port inside the container. | | `RESCAN_INTERVAL_SECONDS` | `300` | How often the whole library is re-checked as a fallback. 60–21600. | | `MISSING_GRACE_SECONDS` | `86400` | How long an episode whose file vanished stays in the feed, so a brief share outage doesn't drop episodes. | @@ -471,6 +471,15 @@ shows the current mode. It deliberately does not sit in a banner across every pa a banner that is always there is a banner nobody reads when something is actually wrong. +**The publish date** of a new episode comes from its filename when the name starts +with a date — `2026-09-01-episode-one.mp3`, `2026_09_01 …` or `20260901 …` — at +midnight in your `TZ`. Otherwise it is the file's modification time, which is right +for a file that was just recorded and wrong for three dated files copied onto the +share together, which would all land on the minute they were copied. A modification +time that already falls on the named day is kept, because it also carries the time +of day. Either way it is only a starting point: the date you set on the episode page +is never changed by a rescan. + ## Security SelfPod is built to be published to the internet, so the design assumes the address diff --git a/doc/selfpod-spec.md b/doc/selfpod-spec.md index fdba2c0..4d3e0a1 100644 --- a/doc/selfpod-spec.md +++ b/doc/selfpod-spec.md @@ -246,7 +246,12 @@ Required behavior: used only as a *suggested* title if the user hasn't set one, never silently overwrites a user-edited title on rescan. - Compute/assign a stable GUID (§7.2). - - Insert into the database with `pub_date` defaulting to file mtime. + - Insert into the database with `pub_date` defaulting to the date the filename + starts with (`YYYY-MM-DD`, with `-`, `_`, `.` or nothing between the parts, + at midnight in `TZ`) when there is one and the file mtime falls on another + day; otherwise to the file mtime. First insert only — a rescan never + rewrites `pub_date`, and a user-set date (`pub_date_is_custom`) is never + touched. 3. For each file previously known but no longer present on disk, mark the episode `missing` (soft state, not deleted) rather than removing it from the feed immediately — avoids apps re-downloading/duplicating diff --git a/src/services/ad-pipeline.js b/src/services/ad-pipeline.js index 218e121..2298b27 100644 --- a/src/services/ad-pipeline.js +++ b/src/services/ad-pipeline.js @@ -287,6 +287,22 @@ export function createAdPipeline({ timers.clear(); }, + /** + * Resolves once nothing is running or queued. + * + * A pass started from a page is not awaited by the request that started it, so a + * test — or anything else tearing the app down — has to be able to wait for it: + * closing the database under a pass that is half-way through cutting an episode + * is how a test run came to hang at exit. Loops because a pass can queue another. + */ + async idle() { + // eslint-disable-next-line no-unmodified-loop-condition + while (active !== null || waiting.size) { + await chain; + await Promise.allSettled([...waiting.values()]); + } + }, + /** * Everything a show needs, in order: fingerprint, detect, cut, publish. * diff --git a/src/services/adverts-view.js b/src/services/adverts-view.js index a55725f..107d919 100644 --- a/src/services/adverts-view.js +++ b/src/services/adverts-view.js @@ -621,7 +621,11 @@ export function createAdvertsView({ db, adDetect, transcriber, episodes, shows } if (data.off) return summaries; for (const episode of episodes.listByShow(show.id)) { const state = api.episodeState(episode, api.stretchesOf(episode, data), data); - if (state) summaries.set(episode.id, { ...state, url: `/shows/${encodeURIComponent(show.slug)}/adverts#ep-${episode.id}` }); + // The episode's own page, where the same bar is drawn under #episode-cuts. The + // Adverts page used to be the link, with `#ep-` as the anchor — but that + // page shows thirty episodes at a time, so for anything older the anchor was + // not there and the link landed at the top. + if (state) summaries.set(episode.id, { ...state, url: `/shows/${encodeURIComponent(show.slug)}/episodes/${encodeURIComponent(episode.id)}#episode-cuts` }); } return summaries; }, diff --git a/src/services/scanner.js b/src/services/scanner.js index 0caef85..43a09b7 100644 --- a/src/services/scanner.js +++ b/src/services/scanner.js @@ -11,7 +11,7 @@ import { imageMimeType, isSupportedAudioFile, } from '../constants.js'; -import { nowIso } from '../lib/dates.js'; +import { fromLocalInputValue, nowIso, toLocalInputValue } from '../lib/dates.js'; import { EVENTS } from '../lib/events.js'; import { initialPublishHold } from '../lib/publish-hold.js'; import { computeIdentityKey } from '../lib/identity.js'; @@ -385,7 +385,9 @@ export function createScanner({ mtimeIso = nowIso(); warnings.push({ file: filename, - message: `\`${filename}\` has a modification time SelfPod cannot read, so today's date is used as its publish date. You can set the publish date yourself on the episode page.`, + message: dateInFilename(filename) + ? `\`${filename}\` has a modification time SelfPod cannot read, so its publish date is the date its name starts with. You can set the publish date yourself on the episode page.` + : `\`${filename}\` has a modification time SelfPod cannot read, so today's date is used as its publish date. You can set the publish date yourself on the episode page.`, }); } else { errors.push(activity.formatFileError(filename, err)); @@ -566,7 +568,9 @@ export function createScanner({ description: meta.description ?? '', season: meta.season ?? null, episode_number: meta.episodeNumber ?? null, - pub_date: mtimeIso, + // First sight only. A rescan never touches pub_date, so a date set on the + // episode page stays, whatever the file or its name says afterwards. + pub_date: publishDateFor(filename, mtimeIso, config.timeZone), duration_seconds: meta.durationSeconds, bitrate_kbps: meta.bitrateKbps, file_size_bytes: stats.size, @@ -931,6 +935,41 @@ function returnedFromExpiry(filename) { return `\`${filename}\` is back after being gone longer than the grace period, so it has returned to the feed with its original episode identity — subscribers keep their played state.`; } +/** + * The date a filename starts with, as `YYYY-MM-DD` — the same prefix titleFromFilename + * strips, and the one the remote fetcher writes. Null when there is none, or when the + * digits are not a day that exists. + */ +export function dateInFilename(filename) { + const match = String(filename ?? '').match(/^(\d{4})[-_.]?(\d{2})[-_.]?(\d{2})/); + if (!match) return null; + const [, y, m, d] = match; + const probe = new Date(Date.UTC(+y, +m - 1, +d)); + if (probe.getUTCFullYear() !== +y || probe.getUTCMonth() !== +m - 1 || probe.getUTCDate() !== +d) return null; + return `${y}-${m}-${d}`; +} + +/** + * The publish date an episode gets when it is first seen. + * + * A file named `2026-09-01-…` says when it was published, and that beats the + * modification time: three dated files copied onto the share together all carry the + * moment they were copied, which put them in the feed as one episode on the same + * minute. The name wins unless the modification time already falls on that day — in + * the instance's zone or in UTC — in which case it is kept, because it also carries + * the time of day and the remote fetcher sets it to the exact moment of publication. + * Without a date in the name the modification time is the answer, as it always was. + */ +export function publishDateFor(filename, mtimeIso, timeZone) { + const dated = dateInFilename(filename); + if (!dated) return mtimeIso; + const sameDay = + toLocalInputValue(mtimeIso, { timeZone }).slice(0, 10) === dated || + String(mtimeIso ?? '').slice(0, 10) === dated; + if (sameDay) return mtimeIso; + return fromLocalInputValue(`${dated}T00:00`, { timeZone }) ?? mtimeIso; +} + /** "2026-08-07-episode-one.m4a" → "Episode One" (a suggestion, never a lock). */ function titleFromFilename(filename) { const withoutExt = filename.replace(/\.[^.]+$/, ''); diff --git a/src/web/public/css/app.css b/src/web/public/css/app.css index 5d04e30..6d56fe5 100644 --- a/src/web/public/css/app.css +++ b/src/web/public/css/app.css @@ -90,8 +90,10 @@ --text: #1B1D22; /* primary text on paper */ /* --- Accent: Signal Terracotta (the signature) --- */ - --accent: #D9602B; /* primary accent — warm broadcast amber-red */ - --accent-2: #B84A1E; /* hover / pressed */ + --accent: #D9602B; /* primary accent — bars, dots, marks, outlines: never text */ + --accent-2: #B84A1E; /* A11Y · text-sized accent and button fills: 7.4:1 on white, 6.6:1 on paper + (#D9602B is 3.7:1, short of AA for text and for white on it) */ + --accent-3: #9A3C16; /* hover / pressed for --accent-2 fills */ --accent-soft: #F3D9C8; /* tint background */ --accent-ink: #7A3215; /* text on tint */ @@ -194,7 +196,7 @@ body::before { } .section-tag { - font-family: var(--mono); font-size: 11px; color: var(--accent); + font-family: var(--mono); font-size: 11px; color: var(--accent-2); font-weight: 600; letter-spacing: .06em; text-transform: uppercase; margin-bottom: 8px; } @@ -261,6 +263,25 @@ hr.soft { border: none; border-top: 1px solid var(--line); margin: 22px 0; } .htmx-request .htmx-indicator, .htmx-request.htmx-indicator { display: inline-flex; } +/* ADDED · a button that is waiting on its request says so. + htmx puts `htmx-request` on the element that made the request and on whatever + `hx-indicator` names — every action button in the app names itself — so the ring + appears in the button and goes when the answer comes, with no markup per button. + `hx-disabled-elt` holds it meanwhile, which is what the [disabled] rule draws. */ +.btn.htmx-request, +.icon-btn.htmx-request { pointer-events: none; } +.btn.htmx-request::after, +.icon-btn.htmx-request::after { + content: ""; width: 12px; height: 12px; flex: none; + border-radius: 50%; + border: 2px solid currentColor; border-right-color: transparent; + animation: sp-spin .6s linear infinite; +} +.icon-btn.htmx-request svg { display: none; } +.btn[disabled], +.icon-btn[disabled] { opacity: .55; cursor: not-allowed; } +.btn.htmx-request[disabled] { opacity: .8; cursor: progress; } + @keyframes sp-spin { to { transform: rotate(360deg); } } @@ -276,8 +297,9 @@ hr.soft { border: none; border-top: 1px solid var(--line); margin: 22px 0; } padding: 9px 15px; cursor: pointer; transition: .15s; text-decoration: none; } .btn svg { width: 16px; height: 16px; } -.btn-primary { background: var(--accent); color: #fff; } -.btn-primary:hover { background: var(--accent-2); } +/* A11Y · was --accent: white on #D9602B is 3.7:1 */ +.btn-primary { background: var(--accent-2); color: #fff; } +.btn-primary:hover { background: var(--accent-3); } .btn-ghost { background: transparent; color: var(--ink); border-color: var(--line-2); } .btn-ghost:hover { background: var(--paper-2); } .btn-ink { background: var(--ink); color: #ECE7DA; } @@ -764,8 +786,9 @@ hr.soft { border: none; border-top: 1px solid var(--line); margin: 22px 0; } } /* A11Y · was --ink-mute */ .dropzone p { color: var(--ink-soft); font-size: 14px; } -.dropzone p a { color: var(--accent); font-weight: 600; } -.dropzone .or { margin: 18px 0; font-size: 12px; color: var(--ink-mute); } +.dropzone p a { color: var(--accent-2); font-weight: 600; } +/* A11Y · was --ink-mute */ +.dropzone .or { margin: 18px 0; font-size: 12px; color: var(--ink-soft); } .queue { margin-top: 20px; } .queue-item { @@ -912,7 +935,7 @@ hr.soft { border: none; border-top: 1px solid var(--line); margin: 22px 0; } font-family: var(--mono); font-size: 12px; font-weight: 600; } .setup-progress .step.done .n { background: var(--ok); color: #fff; border-color: var(--ok); } -.setup-progress .step.active .n { background: var(--accent); color: #fff; border-color: var(--accent); } +.setup-progress .step.active .n { background: var(--accent-2); color: #fff; border-color: var(--accent-2); } .setup-progress .step.active { color: var(--ink); font-weight: 600; } .setup-progress .bar { flex: 1; height: 2px; background: var(--line); border-radius: 1px; } .setup-progress .bar.done { background: var(--ok); } @@ -984,6 +1007,8 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } } .toast--ok { border-left-color: var(--ok); } .toast--err { border-left-color: var(--err); } +.toast--warn { border-left-color: var(--warn); } +.toast--leaving { opacity: 0; transition: opacity .22s; } .toast__title { font-weight: 600; color: var(--ink); display: block; } .toast__body { flex: 1; min-width: 0; } .toast__close { @@ -1076,9 +1101,25 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } .toast { max-width: none; } } -/* larger hit targets on touch devices */ +/* ADDED · the topbar on a phone. The action cluster used to sit beside the + breadcrumb at any width, which squeezed a three-level breadcrumb into four lines + and pushed "Follow a feed" off the right edge. Below 640px the actions take a row + of their own under the breadcrumb, and a bar with no actions keeps one row. */ +@media (max-width: 640px) { + .topbar { flex-wrap: wrap; row-gap: 10px; } + .topbar .crumbs { flex: 1 1 0; min-width: 0; overflow-wrap: anywhere; } + .topbar .right { flex: 1 0 100%; margin-left: 0; flex-wrap: wrap; gap: 8px; } + .topbar .right:not(:has(.btn)) { display: none; } +} + +/* larger hit targets on touch devices: 44px, the size a thumb can be sure of. + The rules for components defined later in this file live at the very end (§18), + where they are not outranked by the component's own size. */ @media (pointer: coarse) { - .icon-btn { width: 40px; height: 40px; } + .icon-btn { width: 44px; height: 44px; } + .btn-sm { min-height: 44px; padding-top: 10px; padding-bottom: 10px; } + .nav-toggle { width: 44px; height: 44px; } + .toast__close { width: 44px; height: 44px; margin: -12px -14px -12px auto; } } @@ -1131,7 +1172,8 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } } .topbar .public-url:hover { border-color: var(--line-2); } .topbar .public-url__host { max-width: 22ch; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.topbar .public-url__action { color: var(--ink-mute); margin-left: 4px; } +/* A11Y · was --ink-mute: "· test" is an affordance, not decoration */ +.topbar .public-url__action { color: var(--ink-soft); margin-left: 4px; } .topbar .public-url--unset { color: var(--warn); } .topbar .public-url .d--warn { background: var(--warn); box-shadow: 0 0 6px var(--warn); } .topbar .public-url .d--err { background: var(--err); box-shadow: 0 0 6px var(--err); } @@ -1149,7 +1191,8 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } /* ---- forms ---- */ .mono-input { font-family: var(--mono); font-size: 13px; } -.label-hint { color: var(--ink-mute); font-weight: 400; } +/* A11Y · was --ink-mute */ +.label-hint { color: var(--ink-soft); font-weight: 400; } .static-value { font-size: 13px; color: var(--ink-soft); background: var(--paper-2); border: 1px solid var(--line); border-radius: var(--r-sm); padding: 10px 12px; @@ -1158,7 +1201,7 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } .form-card--narrow { max-width: 620px; } .form-saved { margin-right: auto; color: var(--ok); font-size: 13px; font-weight: 600; } .inline-form { display: inline-flex; align-items: center; gap: 8px; margin: 0; } -.link-button { color: var(--accent); font-weight: 600; cursor: pointer; } +.link-button { color: var(--accent-2); font-weight: 600; cursor: pointer; } .link-button:hover { text-decoration: underline; } .checkbox { display: flex; gap: 9px; align-items: flex-start; font-size: 13.5px; margin: 12px 0 4px; cursor: pointer; } .checkbox input { margin-top: 2px; flex: none; } @@ -1253,7 +1296,8 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } .log-item__warnings summary { cursor: pointer; font-weight: 600; } .log-item__warnings ul { margin: 7px 0 0; padding-left: 18px; } .log-item__warnings li + li { margin-top: 4px; } -.log-item .time small { display: block; color: var(--ink-mute); font-size: 11px; } +/* A11Y · was --ink-mute: the date is information */ +.log-item .time small { display: block; color: var(--ink-soft); font-size: 11px; } .activity-more { margin: 16px auto; display: block; } /* ---- settings rows ---- */ @@ -1344,7 +1388,7 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } .subscribe__app:hover { border-color: var(--line-2); color: var(--ink); } .chip.is-active, .subscribe__app.is-active { - background: var(--accent); border-color: var(--accent); color: #fff; + background: var(--accent-2); border-color: var(--accent-2); color: #fff; } .subscribe__body { min-height: 96px; } .subscribe__pane { display: flex; flex-direction: column; gap: 12px; align-items: flex-start; } @@ -1359,10 +1403,11 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } .subscribe__hint p { margin: 0 0 6px; } .subscribe__open { display: inline-block; font-weight: 600; font-size: 12.5px; - color: var(--accent); text-decoration: none; + color: var(--accent-2); text-decoration: none; } .subscribe__open:hover { text-decoration: underline; } -.subscribe__aside { color: var(--ink-mute); font-size: 11.5px; } +/* A11Y · was --ink-mute */ +.subscribe__aside { color: var(--ink-soft); font-size: 11.5px; } @media (max-width: 820px) { .subscribe .qr { width: 220px; height: 220px; } @@ -1416,7 +1461,8 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } color: var(--ink-soft); margin-top: 6px; } -.stat-card__h { font-size: 11.5px; color: var(--ink-mute); margin-top: 6px; line-height: 1.45; } +/* A11Y · was --ink-mute: this line says what the number counts */ +.stat-card__h { font-size: 11.5px; color: var(--ink-soft); margin-top: 6px; line-height: 1.45; } .stat-card--bad { border-color: var(--err); background: var(--err-soft); } .stat-card--bad .stat-card__n { color: var(--err); } @@ -1445,7 +1491,7 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } "why hasn't my podcast app picked up the new episode?", so it is worth the space. */ .reach-stat__when { font-size: 11px; - color: var(--ink-mute); + color: var(--ink-soft); /* A11Y · was --ink-mute */ margin-top: 3px; white-space: nowrap; } @@ -1534,8 +1580,20 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } width: auto; } - /* The header labels the columns of a grid that no longer exists. */ - .ep-table--pinned thead { display: none; } + /* The header labels the columns of a grid that no longer exists — visually. It is + kept for a screen reader, which still has a table to read and needs the column + names for it; `display: none` took them away from it too. */ + .ep-table--pinned thead, + .ep-table--stack thead { + position: absolute; + width: 1px; height: 1px; + padding: 0; margin: -1px; + overflow: hidden; + clip: rect(0 0 0 0); + clip-path: inset(50%); + white-space: nowrap; + border: 0; + } .ep-table--pinned tr { position: relative; @@ -1608,6 +1666,49 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } } +/* ═══════════════════════════════════════════════════════════════════════════ + 14b ANY OTHER TABLE ON A PHONE + The access log and the two statistics tables: six columns that scrolled + sideways with one row filling the screen. The same treatment as §14, made + general: each row becomes a block, the first cell (the title) runs full width, + and every other cell writes its column name in front of its value, taken from + a `data-label` the template puts on it. The stays for screen readers. + ═══════════════════════════════════════════════════════════════════════════ */ + +@media (max-width: 640px) { + /* Beats the 620px floor §11 puts on every non-pinned table in a scroller. */ + .table-scroll .ep-table.ep-table--stack { min-width: 0; } + .ep-table--stack, + .ep-table--stack tbody, + .ep-table--stack tr, + .ep-table--stack td { display: block; width: auto; } + + .ep-table--stack tr { padding: 12px 0; border-bottom: 1px solid var(--line); } + .ep-table--stack tbody tr:last-child { border-bottom: none; } + .ep-table--stack tr:hover td { background: transparent; } + .ep-table--stack tr.is-missing { background: var(--warn-soft); padding-left: 10px; border-radius: var(--r-sm); } + + .ep-table--stack td { + display: flex; align-items: baseline; gap: 10px; + padding: 3px 0; border: none; + font-size: 13px; + } + .ep-table--stack td[data-label]::before { + content: attr(data-label); + flex: 0 0 82px; + font-family: var(--mono); font-size: 10px; font-weight: 600; + letter-spacing: .06em; text-transform: uppercase; + color: var(--ink-soft); + } + .ep-table--stack td.ep-table__lead { display: block; padding-bottom: 6px; } + .ep-table--stack .ep-title small { white-space: normal; word-break: break-word; } + .ep-table--stack .log-range, .ep-table--stack .log-error { margin-left: 92px; } + + .ep-table--stack tr.log-more-row { border-bottom: none; } + .ep-table--stack tr.log-more-row td { display: block; padding-top: 6px; } +} + + /* ═══════════════════════════════════════════════════════════════════════════ 15 CHARTS Every plot here is plain HTML elements carrying an inline `height:%` or @@ -1779,7 +1880,7 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } .stat-card__d--good { color: var(--ok); } .stat-card__d--bad { color: var(--err); } .stat-card__d--flat { color: var(--ink-soft); font-weight: 400; } -.stat-card__d--none { color: var(--ink-mute); font-weight: 400; } +.stat-card__d--none { color: var(--ink-soft); font-weight: 400; } /* A11Y · was --ink-mute */ @media (max-width: 640px) { .chart__plot, @@ -2233,7 +2334,7 @@ a.cut-pill:hover { text-decoration: underline; } border: 1px solid var(--line-2); color: var(--ink); background: var(--card); } .stretch__play:hover { background: var(--paper-2); } -.stretch__play.is-playing { background: var(--accent); border-color: var(--accent); color: #fff; } +.stretch__play.is-playing { background: var(--accent-2); border-color: var(--accent-2); color: #fff; } .cuts-timeline__more { margin-top: 12px; } .cuts-settings > summary { cursor: pointer; margin-bottom: 0; } .cuts-settings[open] > summary { margin-bottom: 14px; } @@ -2267,3 +2368,19 @@ a.cut-pill:hover { text-decoration: underline; } .ep-cuts__players { grid-template-columns: 1fr; } .rule-teach select, .tx__teach-row select, .teach-range__row select { flex: 1 1 100%; } } + + +/* ═══════════════════════════════════════════════════════════════════════════ + 18 TOUCH TARGETS FOR THE COMPONENTS ABOVE + Last on purpose: these override sizes set by the component rules earlier in + the file, and at equal specificity the later rule wins. 44px is the size a + thumb can be sure of; the look of each control is unchanged apart from room. + ═══════════════════════════════════════════════════════════════════════════ */ + +@media (pointer: coarse) { + .sidebar .me-signout { width: 44px; height: 44px; } + .chip, .subscribe__app { min-height: 44px; display: inline-flex; align-items: center; padding: 8px 14px; } + .stretch__play { width: 44px; height: 44px; font-size: 13px; } + /* The bar keeps its 14px; the wrapper around it is what the thumb lands on. */ + .cutbar__hit { padding: 15px 0; margin: -9px 0; } +} diff --git a/src/web/public/js/app.js b/src/web/public/js/app.js index 3d86b71..adcb208 100644 --- a/src/web/public/js/app.js +++ b/src/web/public/js/app.js @@ -26,6 +26,9 @@ document.addEventListener('htmx:responseError', function (event) { var xhr = event.detail.xhr; + // A session that has run out answers 401 with HX-Redirect to the sign-in page. + // htmx follows it; saying "something went wrong" first would be untrue. + if (xhr && xhr.getResponseHeader && xhr.getResponseHeader('HX-Redirect')) return; var message = 'Something went wrong.'; try { var parsed = JSON.parse(xhr.responseText); @@ -40,14 +43,209 @@ toast(message, 'err'); }); + /* + * No response at all: offline, a tunnel that dropped, a request an extension + * blocked. htmx raises this instead of responseError, and until it was handled + * these failed in silence — the button un-pressed itself and nothing said why. + */ + document.addEventListener('htmx:sendError', function () { + toast('SelfPod could not be reached. Check your connection, or that the container is still running, and try again.', 'err'); + }); + + /* ------------------------------------------- background refreshes & focus */ + + /** + * Whether a request was started by the page rather than by a person: a server-sent + * event, a `load` trigger, or script. Those are the refreshes that may not throw + * away what someone is in the middle of typing. + */ + function isBackgroundRequest(detail) { + var config = detail && detail.requestConfig; + var trigger = config && config.triggeringEvent; + if (!trigger || !trigger.type) return true; + return String(trigger.type).indexOf('sse:') === 0 || trigger.type === 'load'; + } + + /** A field someone has focused, or has changed and not yet submitted. */ + function fieldInUse(field) { + if (field === document.activeElement) return true; + if (field.type === 'checkbox' || field.type === 'radio') return field.checked !== field.defaultChecked; + if (field.tagName === 'SELECT') { + // A select with no `selected` attribute shows its first option, and that is + // its default too — comparing each option's selected flag with defaultSelected + // would call every such select dirty from the moment it was rendered. + var defaultIndex = -1; + for (var i = 0; i < field.options.length; i += 1) { + if (field.multiple && field.options[i].selected !== field.options[i].defaultSelected) return true; + if (defaultIndex === -1 && field.options[i].defaultSelected) defaultIndex = i; + } + if (field.multiple) return false; + if (defaultIndex === -1 && field.options.length) defaultIndex = 0; + return field.selectedIndex !== defaultIndex; + } + if (field.type === 'hidden' || field.type === 'submit' || field.type === 'button') return false; + return field.value !== field.defaultValue; + } + + function beingEdited(root) { + if (!root || !root.querySelectorAll) return false; + var fields = root.querySelectorAll('input, select, textarea'); + for (var i = 0; i < fields.length; i += 1) { + if (fieldInUse(fields[i])) return true; + } + return false; + } + + /* + * A refresh the page asked for itself is held back while a field inside the + * region it would replace is in use, and taken again once it is not. The Adverts + * panel and the episode's cuts card re-read themselves whenever a pass finishes — + * scheduled passes included — and used to wipe a half-typed boundary and close the + * settings fold under the person using them. + */ + document.addEventListener('htmx:beforeSwap', function (event) { + if (!isBackgroundRequest(event.detail)) return; + var target = event.detail.target; + if (!target || !beingEdited(target)) return; + event.detail.shouldSwap = false; + target.setAttribute('data-refresh-pending', '1'); + }); + + function takePendingRefreshes() { + var pending = document.querySelectorAll('[data-refresh-pending]'); + Array.prototype.forEach.call(pending, function (el) { + if (beingEdited(el) || !window.htmx) return; + el.removeAttribute('data-refresh-pending'); + var url = el.getAttribute('hx-get'); + if (!url) return; + window.htmx.ajax('GET', url, { source: el, target: el, swap: el.getAttribute('hx-swap') || 'innerHTML' }); + }); + } + + document.addEventListener('focusout', function () { + // After the browser has moved focus, so the next field in the same region counts. + setTimeout(takePendingRefreshes, 0); + }); + + /* + * A decision posts and swaps the panel; the server also announces the change over + * SSE, which made the panel fetch itself a second time for the same state. While a + * person's own request is in flight to a target, the stream's refresh of that + * target is dropped — the response on its way is at least as fresh. + */ + var userRequestsInFlight = {}; + + document.addEventListener('htmx:beforeRequest', function (event) { + var target = event.detail.target; + var key = target && target.id; + if (isBackgroundRequest(event.detail)) { + if (key && userRequestsInFlight[key]) event.preventDefault(); + return; + } + if (key) userRequestsInFlight[key] = (userRequestsInFlight[key] || 0) + 1; + }); + + document.addEventListener('htmx:afterRequest', function (event) { + if (isBackgroundRequest(event.detail)) return; + var target = event.detail.target; + var key = target && target.id; + if (key && userRequestsInFlight[key]) userRequestsInFlight[key] -= 1; + }); + + /* + * A
someone opened or closed stays that way across a swap of the region + * it sits in — the server renders it in its default state every time. + */ + var detailsState = {}; + + function detailsKey(details) { + return details.id || details.className || null; + } + + document.addEventListener('toggle', function (event) { + var details = event.target; + if (!details || details.tagName !== 'DETAILS') return; + var key = detailsKey(details); + if (key) detailsState[key] = details.open; + }, true); + + /** + * The element a swap left in the document. After an outerHTML swap htmx still + * reports the element it replaced, which is out of the document by then; the one + * that took its place carries the same id. + */ + function swappedTarget(detail) { + var target = detail && detail.target; + if (target && target.id && !document.body.contains(target)) return document.getElementById(target.id); + return target; + } + + document.addEventListener('htmx:afterSwap', function (event) { + var target = swappedTarget(event.detail); + if (!target || !target.querySelectorAll) return; + Array.prototype.forEach.call(target.querySelectorAll('details'), function (details) { + var key = detailsKey(details); + if (key && Object.prototype.hasOwnProperty.call(detailsState, key)) details.open = detailsState[key]; + }); + }); + + /* + * Keyboard focus survives a swap. htmx replaces the element that had it, and the + * browser then puts focus on : after saving a setting, sorting the log or + * closing a modal, a keyboard user was back at the top of the page. The control's + * id is remembered before the request and looked up again after the settle; when + * it is gone, the first control in what was swapped in takes its place. + */ + var focusBeforeRequest = null; + + document.addEventListener('htmx:beforeRequest', function (event) { + if (isBackgroundRequest(event.detail)) return; + var active = document.activeElement; + var target = event.detail.target; + if (!active || active === document.body) { + focusBeforeRequest = null; + return; + } + focusBeforeRequest = { + id: active.id || null, + inTarget: Boolean(target && target.contains && target.contains(active)), + }; + }); + + document.addEventListener('htmx:afterSettle', function (event) { + var remembered = focusBeforeRequest; + if (!remembered || isBackgroundRequest(event.detail)) return; + focusBeforeRequest = null; + var active = document.activeElement; + if (active && active !== document.body) return; // focus survived, or was placed on purpose + var again = remembered.id ? document.getElementById(remembered.id) : null; + if (again && document.body.contains(again)) { + again.focus({ preventScroll: true }); + return; + } + if (!remembered.inTarget) return; + var target = swappedTarget(event.detail); + if (!target || !document.body.contains(target) || !target.querySelector) return; + var first = target.querySelector('[autofocus], button:not([disabled]), input:not([type=hidden]):not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href]'); + if (first) first.focus({ preventScroll: true }); + }); + /* ---------------------------------------------------------------- toasts */ + /** + * A notice stays long enough to be read: six seconds and fifty milliseconds a + * character, which gives the reachability verdicts their twenty. An error stays + * until it is dismissed, and is announced as an alert rather than a status. + */ + var TOAST_BASE_MS = 6000; + var TOAST_PER_CHAR_MS = 50; + function toast(message, level) { var root = document.getElementById('toast-root'); if (!root) return; var el = document.createElement('div'); el.className = 'toast toast--' + (level || 'ok'); - el.setAttribute('role', 'status'); + el.setAttribute('role', level === 'err' ? 'alert' : 'status'); var body = document.createElement('div'); body.className = 'toast__body'; body.textContent = message; @@ -55,6 +253,7 @@ close.type = 'button'; close.className = 'toast__close'; close.setAttribute('aria-label', 'Dismiss'); + close.setAttribute('data-toast-close', ''); close.textContent = '×'; el.appendChild(body); el.appendChild(close); @@ -62,21 +261,46 @@ scheduleToastDismissal(el); } + function dismissToast(el) { + if (!el || !el.parentNode) return; + el.classList.add('toast--leaving'); + setTimeout(function () { + el.remove(); + }, 240); + } + function scheduleToastDismissal(el) { - var timer = setTimeout(function () { - el.classList.add('toast--leaving'); - setTimeout(function () { - el.remove(); - }, 240); - }, 6000); - el.addEventListener('mouseenter', function () { + if (el.classList.contains('toast--err')) return; // stays until dismissed + var remaining = TOAST_BASE_MS + TOAST_PER_CHAR_MS * (el.textContent || '').length; + var timer = null; + var startedAt = 0; + + function start() { + if (timer !== null) return; + startedAt = Date.now(); + timer = setTimeout(function () { + timer = null; + dismissToast(el); + }, remaining); + } + function pause() { + if (timer === null) return; clearTimeout(timer); - }); + timer = null; + // Whatever is left, and at least a moment to finish reading after the pointer leaves. + remaining = Math.max(1500, remaining - (Date.now() - startedAt)); + } + + el.addEventListener('mouseenter', pause); + el.addEventListener('mouseleave', start); + el.addEventListener('focusin', pause); + el.addEventListener('focusout', start); + start(); } document.addEventListener('click', function (event) { var close = event.target.closest('[data-toast-close]'); - if (close) close.closest('.toast').remove(); + if (close) dismissToast(close.closest('.toast')); }); // Toasts raised out-of-band by an htmx response need the same auto-dismiss. @@ -100,11 +324,31 @@ } document.addEventListener('htmx:afterSwap', function (event) { - if (event.detail.target && event.detail.target.id === 'modal-root') { - openModalIn(event.detail.target); + var target = event.detail.target; + if (!target || target.id !== 'modal-root') return; + if (target.querySelector('dialog.modal')) { + openModalIn(target); + } else { + // A successful modal action answers with an empty root: the dialog is gone + // without closeModal() running, so focus is handed back here. + restoreFocusTo(modalOpener); + modalOpener = null; } }); + /* + * The control that opened the modal, so closing it can hand focus back. Only a + * request from outside the modal counts: the form inside posts to the same target. + */ + var modalOpener = null; + + document.addEventListener('htmx:beforeRequest', function (event) { + var target = event.detail.target; + if (!target || target.id !== 'modal-root') return; + var elt = event.detail.elt; + if (elt && !target.contains(elt)) modalOpener = elt; + }); + document.addEventListener('click', function (event) { if (event.target.closest('[data-modal-close]')) { closeModal(); @@ -117,12 +361,31 @@ document.body.addEventListener('selfpod:modal-close', closeModal); + // Escape closes a native dialog on its own; the root still has to be emptied and + // focus returned, the same as for Cancel. + document.addEventListener('close', function (event) { + var dialog = event.target; + if (dialog && dialog.tagName === 'DIALOG' && dialog.closest('#modal-root')) closeModal(); + }, true); + function closeModal() { var root = document.getElementById('modal-root'); if (!root) return; var dialog = root.querySelector('dialog.modal'); - if (dialog && typeof dialog.close === 'function') dialog.close(); + if (dialog && typeof dialog.close === 'function' && dialog.open) dialog.close(); root.innerHTML = ''; + restoreFocusTo(modalOpener); + modalOpener = null; + } + + function restoreFocusTo(opener) { + if (!opener) return; + var active = document.activeElement; + if (active && active !== document.body) return; + // The opener may have been swapped away with the table it sat in; the same + // control, re-rendered, carries the same id. + var again = document.body.contains(opener) ? opener : opener.id ? document.getElementById(opener.id) : null; + if (again && typeof again.focus === 'function') again.focus({ preventScroll: true }); } /* --------------------------------------------------- confirm gate helpers */ @@ -417,9 +680,12 @@ if (!form) return; var from = form.querySelector('[data-range-from]'); var to = form.querySelector('[data-range-to]'); - if (!from || !to || !track.clientWidth) return; - var rect = track.getBoundingClientRect(); - var share = Math.max(0, Math.min(1, (event.clientX - rect.left) / track.clientWidth)); + // The tap lands on a wrapper with room around the bar (a thumb needs it); the + // position is read off the drawn track inside it, so the geometry is the bar's. + var rail = track.querySelector('[data-cutbar-rail]') || track; + if (!from || !to || !rail.clientWidth) return; + var rect = rail.getBoundingClientRect(); + var share = Math.max(0, Math.min(1, (event.clientX - rect.left) / rail.clientWidth)); var ms = share * (Number(track.getAttribute('data-duration-ms')) || 0); // From, then To; a third tap starts a new range. var target = !from.value ? from : !to.value ? to : null; @@ -999,6 +1265,8 @@ row.querySelector('[data-pct]').textContent = 'done'; var message = row.querySelector('[data-message]'); message.hidden = false; + // `.msg` is styled as a problem; `.ok` is what makes this one read as good news. + message.classList.add('ok'); message.textContent = 'Uploaded — scanning now.'; } diff --git a/src/web/routes/events.js b/src/web/routes/events.js index 184526f..933840e 100644 --- a/src/web/routes/events.js +++ b/src/web/routes/events.js @@ -56,33 +56,48 @@ export default async function eventRoutes(fastify, { events, logger, shows, adPi reply.raw.write(`event: ${event}\ndata: ${payload}\n\n`); }; + /* + * The strip is the same partial the rescan button swaps in, rendered here rather + * than assembled by hand. The partial carries the slow poll of /ui/scan-status + * that clears the strip when the stream dies mid-scan; the hand-built copy used + * to leave that out, so the first SSE message replaced a strip that could clear + * itself with one that could not. Rendering is asynchronous, so each strip goes + * out through one queue and a later event can never overtake an earlier one. + */ + let queue = Promise.resolve(); + const sendStrip = (event, scope, label) => { + queue = queue + .then(() => renderStrip(fastify, scope, label)) + .then((html) => send(event, html)) + .catch((err) => logger?.debug({ err }, 'could not render the scan-progress strip for the live stream')); + }; + const sendAfterStrips = (event, data) => { + queue = queue.then(() => send(event, data)).catch(() => {}); + }; + const onScanStarted = (payload) => { const label = payload.scope === 'all' ? 'Scanning your whole library…' : `Scanning ${payload.slug ?? 'show'}…`; - send( - payload.scope === 'all' ? 'scan-progress-all' : `scan-progress-${payload.showId}`, - progressHtml(payload.scope === 'all' ? 'all' : payload.showId, label), - ); + const scope = payload.scope === 'all' ? 'all' : payload.showId; + sendStrip(`scan-progress-${scope}`, scope, label); }; const onScanProgress = (payload) => { if (payload.scope !== 'all') return; - send( - 'scan-progress-all', - progressHtml('all', `Scanning ${payload.title ?? payload.slug} (${payload.index} of ${payload.total})…`), - ); + sendStrip('scan-progress-all', 'all', `Scanning ${payload.title ?? payload.slug} (${payload.index} of ${payload.total})…`); }; const onScanFinished = (payload) => { const scope = payload.scope === 'all' ? 'all' : payload.showId; - // An empty swap clears the strip once the scan is done. - send(`scan-progress-${scope}`, ''); + // An empty swap clears the strip once the scan is done — queued behind any + // strip still rendering, or the clear would arrive before what it clears. + sendAfterStrips(`scan-progress-${scope}`, ''); // These are used as triggers (hx-trigger="sse:scan-finished-…"), where the // payload is irrelevant — only the event name matters. - if (payload.showId) send(`scan-finished-${payload.showId}`, 'done'); - if (payload.scope === 'all') send('scan-finished-all', 'done'); + if (payload.showId) sendAfterStrips(`scan-finished-${payload.showId}`, 'done'); + if (payload.scope === 'all') sendAfterStrips('scan-finished-all', 'done'); }; /* @@ -147,10 +162,24 @@ export default async function eventRoutes(fastify, { events, logger, shows, adPi }); } +/** + * The scan-progress strip for the stream: partials/scan-progress.eta, the one the + * rescan buttons use, so the two cannot drift apart. The hand-written copy below is + * the fallback if rendering fails, and carries the same polling backstop. + */ +export async function renderStrip(fastify, scope, label) { + try { + return await fastify.view('partials/scan-progress.eta', { scope, label }); + } catch { + return progressHtml(scope, label); + } +} + function progressHtml(scope, label) { - return `
${escapeHtml( + )}" hx-trigger="load delay:2500ms" hx-swap="outerHTML">${escapeHtml( label, )}
`; } diff --git a/src/web/routes/fragments.js b/src/web/routes/fragments.js index 87e2bcc..7de45e5 100644 --- a/src/web/routes/fragments.js +++ b/src/web/routes/fragments.js @@ -53,6 +53,46 @@ export default async function fragmentRoutes(fastify, services) { return reply.redirect(path, 303); } + /** + * The htmx answer to "go somewhere else, and say why": the flash is stored for the + * page that loads next, and `HX-Redirect` sends the browser there. Used wherever a + * fragment swap would leave the page describing something that is gone — a show + * that was removed, an episode deleted from the page about it — and wherever the + * only honest result is the whole page re-read. + */ + function redirectWithFlash(request, reply, path, message, level = 'ok') { + if (message) services.setFlash(request, message, level); + reply.header('HX-Redirect', path); + return reply.send(''); + } + + /** + * Sends a fragment with a toast riding along out of band. `viewAsync` rather than + * `view`, because `reply.view` renders *and sends*, and anything appended to its + * return value reaches nobody — which is how confirmations were lost here twice. + */ + async function sendWithToast(reply, html, toast) { + if (!toast) return reply.type('text/html; charset=utf-8').send(html); + const oob = await reply.viewAsync('partials/toast.eta', { + message: toast.message, + level: toast.level ?? 'ok', + helpers: fastify.viewHelpers, + }); + return reply.type('text/html; charset=utf-8').send(`${html}${oob}`); + } + + /** + * Starts a pass over a show without waiting for it. A pass reads every episode and + * may listen for minutes, which is far too long for a request from a phone to hang + * on; the work strip on the page follows it over SSE, and the panel re-reads itself + * when the pass says it changed something. The returned promise is only for tests. + */ + function startPass(showId) { + const run = services.adPipeline.processShow(showId); + run.catch((err) => services.logger?.warn({ err, showId }, 'a pass started from the page failed')); + return run; + } + /* ----------------------------------------------------------- ad segments */ function advertsPath(slug) { @@ -60,13 +100,14 @@ export default async function fragmentRoutes(fastify, services) { } /** The one place the Adverts panel is rendered, so htmx and a reload agree. */ - async function renderSegments(reply, show, extra = {}) { - return reply.view('partials/ad-panel.eta', { + async function renderSegments(reply, show, extra = {}, { toast = null } = {}) { + const html = await reply.viewAsync('partials/ad-panel.eta', { show: presentShow(show), ...(await services.advertsView.panel(show, { owed: services.adPipeline.workOwed(show.id) })), helpers: fastify.viewHelpers, ...extra, }); + return sendWithToast(reply, html, toast); } /** @@ -74,14 +115,15 @@ export default async function fragmentRoutes(fastify, services) { * waiting, and the words underneath it. One target, so a decision made there * re-renders the whole story rather than half of it. */ - async function renderEpisodeAdverts(reply, episode, show, extra = {}) { - return reply.view('partials/episode-adverts.eta', { + async function renderEpisodeAdverts(reply, episode, show, extra = {}, { toast = null } = {}) { + const html = await reply.viewAsync('partials/episode-adverts.eta', { show: presentShow(show), episode: presentEpisode(episode, show), adverts: await services.advertsView.episodeAdverts(episode, show), helpers: fastify.viewHelpers, ...extra, }); + return sendWithToast(reply, html, toast); } /** Just the words, for anything that wants them on their own. */ @@ -185,11 +227,17 @@ export default async function fragmentRoutes(fastify, services) { ? renderSegments(reply, show) : redirectBack(request, reply, advertsPath(show.slug), 'Advert detection is off for this show.', 'err'); } - await services.adPipeline.processShow(show.id); if (!isHtmx(request)) { + // A plain form post has nothing on the page to follow the work with, so it + // waits and says what happened; the browser shows its own loading state. + await services.adPipeline.processShow(show.id); return redirectBack(request, reply, advertsPath(show.slug), 'Checked.'); } - return renderSegments(reply, shows.get(show.id)); + // Started, not awaited: the work strip above the panel follows the pass. + startPass(show.id); + return renderSegments(reply, shows.get(show.id), {}, { + toast: { message: 'Checking this show now. What it finds appears here as it goes.' }, + }); }); scoped.post('/ui/shows/:slug/ad-segments/:segmentId', { preHandler: [fastify.rateLimit(DECIDE_LIMIT)] }, async (request, reply) => { @@ -328,13 +376,17 @@ export default async function fragmentRoutes(fastify, services) { * The reply every cut decision ends with: back where it was made. htmx gets the * panel or the episode card re-rendered; a plain form gets a redirect and a flash. */ - async function afterDecision(request, reply, show, note, { level = 'ok' } = {}) { + async function afterDecision(request, reply, show, note, { level = 'ok', toast = false } = {}) { const back = returnTarget(request, show); if (!isHtmx(request)) { return redirectBack(request, reply, back ? episodePath(show.slug, back.episode.id) : advertsPath(show.slug), note, level); } - if (back) return renderEpisodeAdverts(reply, episodes.get(back.episode.id), shows.get(show.id)); - return renderSegments(reply, shows.get(show.id)); + // `toast: true` says the note is worth saying out loud on the htmx path too — + // for work that was started rather than finished, where the re-rendered panel + // alone would not show what the press achieved. + const extra = toast ? { toast: { message: note, level } } : {}; + if (back) return renderEpisodeAdverts(reply, episodes.get(back.episode.id), shows.get(show.id), {}, extra); + return renderSegments(reply, shows.get(show.id), {}, extra); } function segmentOf(show, segmentId) { @@ -367,9 +419,15 @@ export default async function fragmentRoutes(fastify, services) { rawText: text, language: show.language ? String(show.language).slice(0, 2) : null, }); - // New words to listen for in every episode: a pass, not a cut. - await services.adPipeline.processShow(show.id); - return afterDecision(request, reply, show, `SelfPod now listens for “${text}” in every episode.`); + // New words to listen for in every episode: a pass, not a cut. The page gets the + // new rule at once and the strip follows the pass; a plain form waits for it. + const note = `SelfPod now listens for “${text}” in every episode.`; + if (!isHtmx(request)) { + await services.adPipeline.processShow(show.id); + return afterDecision(request, reply, show, note); + } + startPass(show.id); + return afterDecision(request, reply, show, note, { toast: true }); }); /** "Restore everywhere and stop": the rule behind a cut, undone for the whole show. */ @@ -441,10 +499,15 @@ export default async function fragmentRoutes(fastify, services) { if (error.status && error.status < 500) return fail(error.message); throw error; } - await services.adPipeline.processShow(show.id); - const note = kind === 'jingle' ? 'SelfPod now cuts whatever comes before that jingle, in every episode.' : 'Taught.'; - if (!isHtmx(request)) return redirectBack(request, reply, episodePath(show.slug, episode.id), note); - return renderEpisodeAdverts(reply, episodes.get(episode.id), shows.get(show.id)); + const jingleNote = 'SelfPod now cuts whatever comes before that jingle, in every episode.'; + if (!isHtmx(request)) { + await services.adPipeline.processShow(show.id); + return redirectBack(request, reply, episodePath(show.slug, episode.id), kind === 'jingle' ? jingleNote : 'Taught.'); + } + startPass(show.id); + return renderEpisodeAdverts(reply, episodes.get(episode.id), shows.get(show.id), {}, { + toast: { message: kind === 'jingle' ? jingleNote : 'Taught. The cut lands as soon as the pass reaches this episode.' }, + }); }); scoped.get('/ui/episodes/:id/adverts', async (request, reply) => { @@ -482,9 +545,14 @@ export default async function fragmentRoutes(fastify, services) { ...range, status: verdict === 'advert' ? STATUS.APPROVED : STATUS.REJECTED, }); + const span = `${fastify.viewHelpers.formatDuration(Math.round(range.startMs / 1000))}–${fastify.viewHelpers.formatDuration(Math.round(range.endMs / 1000))}`; + // Past tense once the pass has run (the plain form waits for it); the page, + // which only starts the pass, is told what is under way. note = verdict === 'advert' - ? `Removed ${fastify.viewHelpers.formatDuration(Math.round(range.startMs / 1000))}–${fastify.viewHelpers.formatDuration(Math.round(range.endMs / 1000))} from this episode. The same words will be cut from later episodes.` + ? isHtmx(request) + ? `Removing ${span} from this episode. The same words will be cut from later episodes.` + : `Removed ${span} from this episode. The same words will be cut from later episodes.` : 'Kept, and SelfPod will not offer those words again.'; } else if (verdict === 'programme_starts' || verdict === 'programme_ends' || verdict === 'tail_starts') { services.adDetect.addMarker({ @@ -503,9 +571,12 @@ export default async function fragmentRoutes(fastify, services) { } else { return fail('Say what those words are.'); } - await services.adPipeline.processShow(show.id); - if (!isHtmx(request)) return redirectBack(request, reply, episodePath(show.slug, episode.id), note); - return renderEpisodeAdverts(reply, episodes.get(episode.id), shows.get(show.id)); + if (!isHtmx(request)) { + await services.adPipeline.processShow(show.id); + return redirectBack(request, reply, episodePath(show.slug, episode.id), note); + } + startPass(show.id); + return renderEpisodeAdverts(reply, episodes.get(episode.id), shows.get(show.id), {}, { toast: { message: note } }); }); /* ---------------------------------------------------------- subscription */ @@ -635,7 +706,7 @@ export default async function fragmentRoutes(fastify, services) { message = error.message; level = 'err'; } - return redirectBack(request, reply, subscriptionPath(show.slug), message, level); + return afterSubscriptionAction(request, reply, show, message, level); }); scoped.post('/ui/subscriptions/:id/toggle', async (request, reply) => { @@ -644,26 +715,49 @@ export default async function fragmentRoutes(fastify, services) { const updated = services.subscriptions.update(subscription.id, { enabled: !subscription.enabled, }); - return redirectBack( + return afterSubscriptionAction( request, reply, - subscriptionPath(show.slug), + show, updated.enabled ? 'Following again.' : 'Paused. Nothing new will be downloaded until you resume.', ); }); + /** Asks before the feed is forgotten, like every other action that cannot be undone. */ + scoped.get('/ui/modals/stop-following/:id', async (request, reply) => { + const subscription = services.subscriptions.getOrThrow(request.params.id); + const show = shows.getOrThrow(subscription.show_id); + return reply.view('partials/modal-stop-following.eta', { + show: presentShow(show), + subscription: presentSubscription(subscription, services), + helpers: fastify.viewHelpers, + }); + }); + scoped.post('/ui/subscriptions/:id/delete', async (request, reply) => { const subscription = services.subscriptions.getOrThrow(request.params.id); const show = shows.getOrThrow(subscription.show_id); services.subscriptions.remove(subscription.id); - return redirectBack( + return afterSubscriptionAction( request, reply, - subscriptionPath(show.slug), + show, 'Stopped following that feed. The episodes it already downloaded are untouched.', ); }); + /** + * Every one of these changes the status card, the next-check time and the ledger + * at once, which is the whole page; so the page is re-read, and the message rides + * on the flash either way. The buttons used to swap nothing and follow the 303 + * inside the XHR, which left the page unchanged and the message waiting for a + * reload nobody knew to do. + */ + function afterSubscriptionAction(request, reply, show, message, level = 'ok') { + if (!isHtmx(request)) return redirectBack(request, reply, subscriptionPath(show.slug), message, level); + return redirectWithFlash(request, reply, subscriptionPath(show.slug), message, level); + } + scoped.get('/ui/subscriptions/:id/items', async (request, reply) => { const subscription = services.subscriptions.getOrThrow(request.params.id); const show = shows.getOrThrow(subscription.show_id); @@ -1100,6 +1194,17 @@ export default async function fragmentRoutes(fastify, services) { } }); + /** + * Where the delete-episode modal was opened from. On the show page the episode + * table is re-rendered in place; on the episode's own page there is no table, and + * the page is about something that is now gone, so the answer is the show page + * with the message on the flash. The modal carries this as a hidden field, since + * SelfPod sends `Referrer-Policy: no-referrer` and the referer cannot say. + */ + function cameFromEpisodePage(request, episode) { + return String(request.body?.returnTo ?? '') === `episode:${episode.id}`; + } + scoped.post('/ui/episodes/:id/remove', async (request, reply) => { const episode = episodes.get(request.params.id); if (!episode) throw notFound('That episode does not exist.', 'episode_not_found'); @@ -1107,9 +1212,9 @@ export default async function fragmentRoutes(fastify, services) { episodes.removeFromFeed(episode.id); const message = 'Removed from the feed. The audio file is untouched, and rescans will leave it out.'; - if (!isHtmx(request)) { - return redirectBack(request, reply, `/shows/${encodeURIComponent(show.slug)}`, message); - } + const showPage = `/shows/${encodeURIComponent(show.slug)}`; + if (!isHtmx(request)) return redirectBack(request, reply, showPage, message); + if (cameFromEpisodePage(request, episode)) return redirectWithFlash(request, reply, showPage, message); return renderEpisodeTableWithToast(reply, show, message); }); @@ -1142,9 +1247,9 @@ export default async function fragmentRoutes(fastify, services) { const result = await episodes.deleteWithFile(episode.id); const message = `Deleted ${result.filename} from disk.`; - if (!isHtmx(request)) { - return redirectBack(request, reply, `/shows/${encodeURIComponent(show.slug)}`, message, 'warn'); - } + const showPage = `/shows/${encodeURIComponent(show.slug)}`; + if (!isHtmx(request)) return redirectBack(request, reply, showPage, message, 'warn'); + if (cameFromEpisodePage(request, episode)) return redirectWithFlash(request, reply, showPage, message, 'warn'); return renderEpisodeTableWithToast(reply, show, message, 'warn'); }); @@ -1497,9 +1602,9 @@ export default async function fragmentRoutes(fastify, services) { }, }; - function renderSettingRow(reply, key, { editing = false, errors = null } = {}) { + async function renderSettingRow(reply, key, { editing = false, errors = null } = {}, { toast = null } = {}) { const row = SETTING_ROWS[key]; - return reply.view('partials/settings-row.eta', { + const html = await reply.viewAsync('partials/settings-row.eta', { key, title: row.title, description: row.description, @@ -1515,6 +1620,7 @@ export default async function fragmentRoutes(fastify, services) { errors, helpers: fastify.viewHelpers, }); + return sendWithToast(reply, html, toast); } scoped.get('/ui/settings/:key', async (request, reply) => { @@ -1544,7 +1650,10 @@ export default async function fragmentRoutes(fastify, services) { } if (!isHtmx(request)) return redirectBack(request, reply, '/settings', `${row.title} updated.`); - return renderSettingRow(reply, key, { editing: false }); + // The row re-renders as its display view; the toast is what says it was saved, + // because a row that quietly stops being a form looks much like one that was + // cancelled. + return renderSettingRow(reply, key, { editing: false }, { toast: { message: `${row.title} updated.` } }); }); scoped.post('/ui/settings/watcher', async (request, reply) => { @@ -1552,16 +1661,12 @@ export default async function fragmentRoutes(fastify, services) { settings.update({ [SETTING_KEYS.WATCHER_ENABLED]: enabled ? '1' : '0' }); await watcher?.restart(); - if (!isHtmx(request)) { - return redirectBack( - request, - reply, - '/settings', - enabled ? 'Live file detection switched on.' : 'Live file detection switched off.', - ); - } + const message = enabled ? 'Live file detection switched on.' : 'Live file detection switched off.'; + if (!isHtmx(request)) return redirectBack(request, reply, '/settings', message); // Re-render the whole settings page section by asking the browser to reload - // it: the watcher's mode label depends on state this fragment doesn't own. + // it: the watcher's mode label depends on state this fragment doesn't own. The + // flash survives the reload, so the switch is seen to have done something. + services.setFlash(request, message); reply.header('HX-Refresh', 'true'); return reply.send(''); }); @@ -1571,18 +1676,13 @@ export default async function fragmentRoutes(fastify, services) { request.body?.subscriptionsEnabled === '1' || request.body?.subscriptionsEnabled === 'on'; settings.update({ [SETTING_KEYS.SUBSCRIPTIONS_ENABLED]: enabled ? '1' : '0' }); - if (!isHtmx(request)) { - return redirectBack( - request, - reply, - '/settings', - enabled - ? 'SelfPod can now follow podcast feeds. Set the rules on a show\'s own page.' - : 'Feed following switched off. SelfPod will not fetch from the internet.', - ); - } + const message = enabled + ? 'SelfPod can now follow podcast feeds. Set the rules on a show\'s own page.' + : 'Feed following switched off. SelfPod will not fetch from the internet.'; + if (!isHtmx(request)) return redirectBack(request, reply, '/settings', message); // Whole-page refresh: every show page's subscription section reads this, and // the banner it controls is not part of this fragment. + services.setFlash(request, message); reply.header('HX-Refresh', 'true'); return reply.send(''); }); @@ -1611,6 +1711,7 @@ export default async function fragmentRoutes(fastify, services) { if (!isHtmx(request)) return redirectBack(request, reply, '/settings', 'Password changed.'); return reply.view('partials/modal-closed.eta', { toast: { message: 'Password changed.', level: 'ok' }, + helpers: fastify.viewHelpers, }); }); @@ -1647,6 +1748,9 @@ export default async function fragmentRoutes(fastify, services) { return reply.view('partials/modal-delete-episode.eta', { episode: presentEpisode(episode, show), show: presentShow(show), + // `?from=episode`: opened on the episode's own page, which the action then + // has to leave (see cameFromEpisodePage). + returnTo: request.query?.from === 'episode' ? `episode:${episode.id}` : null, helpers: fastify.viewHelpers, }); }); diff --git a/src/web/routes/pages.js b/src/web/routes/pages.js index 13c5a23..1f12060 100644 --- a/src/web/routes/pages.js +++ b/src/web/routes/pages.js @@ -238,6 +238,7 @@ export default async function pageRoutes(fastify, services) { 'pages/dashboard.eta', shell(request, { title: 'Dashboard', + active: 'dashboard', crumbs: [{ label: 'Dashboard' }], shows: all.filter((s) => s.status === SHOW_STATUS.ACTIVE), pausedShows: all.filter((s) => s.status === SHOW_STATUS.FOLDER_MISSING), @@ -272,8 +273,8 @@ export default async function pageRoutes(fastify, services) { shell(request, { title: 'New show', crumbs: [{ label: 'Dashboard', href: '/' }, { label: 'New show' }], - title_: request.body?.title, - slug: request.body?.slug, + // Echoed back as the field values, so a refusal never discards what was typed. + form: { title: request.body?.title, slug: request.body?.slug }, errors: err.fields ?? { title: err.message }, }), APP_LAYOUT, @@ -980,9 +981,17 @@ export default async function pageRoutes(fastify, services) { }); } +/* + * Topbar actions. A button that makes a request is held and shows it is working until + * the answer comes (`hx-disabled-elt`, and htmx's own `htmx-request` class, which the + * stylesheet draws as a spinner), and a second press while one is in flight is dropped + * rather than queued as a second scan. + */ +const BUSY = 'hx-disabled-elt="this" hx-sync="this:drop"'; + function dashboardActions() { return ` - @@ -78,7 +78,7 @@
-
This episode's reach
+

This episode's reach

<% if (reach.lastAt) { %> Last fetched <%= it.helpers.relativeTime(reach.lastAt) %>. diff --git a/src/web/views/pages/login.eta b/src/web/views/pages/login.eta index c454b1c..a8c57ec 100644 --- a/src/web/views/pages/login.eta +++ b/src/web/views/pages/login.eta @@ -22,7 +22,7 @@

<% if (it.error) { %> -