refactor(web): one ConfirmModal asks before what can't be undone; no native dialogs (DRY B2, B3)

Deleting a playlist asked in the browser's own confirm() box and
reported errors with alert(). Four other deletes each built Modal +
Cancel + a destructive button by hand, two of them in bronze rather
than the destructive oxblood. Suspect sources removed a file on a
second click while Reports asks in a dialog for the same act.

ConfirmModal is the web's twin of Android's ConfirmDestructiveDialog:
title, a body saying what goes, Cancel, and a confirm button in the
destructive action colour that can show a busy label. Reports (x2),
Needs a file, Admin > Users, the playlist page and Suspect sources use
it. The playlist page's errors go to toasts. A source guard keeps
confirm() and alert() out of the app; it flags the old playlist page.

The two web source guards share lib/testing/sourceGuard.ts.

ListenBrainz status (Settings > Connections) and the recommendation
metrics now offer Try again when they fail to load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 14:07:43 -05:00
co-authored by Claude Opus 5.5
parent a5d94754bf
commit cb7028c745
13 changed files with 281 additions and 142 deletions
@@ -0,0 +1,58 @@
<script lang="ts">
// Asks before something that can't be undone: deleting a playlist or an
// account, removing or forgetting a file. The body says what goes; the
// confirm button names the act and wears the destructive action colour
// (oxblood), which the design system keeps apart from the error colour: an
// error is a failure that already happened. Android's twin is
// ConfirmDestructiveDialog.
import type { Snippet } from 'svelte';
import Modal from './Modal.svelte';
import type { IconProp } from './TrackMenuItem.svelte';
let {
title,
open,
confirmLabel,
busyLabel,
confirmAriaLabel,
icon: Icon,
busy = false,
onCancel,
onConfirm,
children
}: {
title: string;
open: boolean;
confirmLabel: string;
/** Shown on the confirm button while the act runs ("Deleting…"). */
busyLabel?: string;
confirmAriaLabel?: string;
icon?: IconProp;
busy?: boolean;
onCancel: () => void;
onConfirm: () => void;
children: Snippet;
} = $props();
</script>
<Modal {title} {open} onClose={onCancel}>
<div class="-mt-2 text-sm text-text-secondary">{@render children()}</div>
<div class="mt-5 flex justify-end gap-2">
<button
type="button"
disabled={busy}
class="rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:text-text-primary disabled:opacity-50"
onclick={onCancel}>Cancel</button
>
<button
type="button"
aria-label={confirmAriaLabel}
disabled={busy}
class="inline-flex items-center gap-1 rounded-md bg-action-destructive px-3 py-1.5 text-sm text-action-fg disabled:cursor-not-allowed disabled:opacity-50"
onclick={onConfirm}
>
{#if Icon}<Icon size={14} strokeWidth={2} />{/if}
{busy && busyLabel ? busyLabel : confirmLabel}
</button>
</div>
</Modal>
@@ -0,0 +1,64 @@
import { describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/svelte';
import { createRawSnippet } from 'svelte';
import ConfirmModal from './ConfirmModal.svelte';
import { offendingSources } from '#lib/testing/sourceGuard.js';
const body = createRawSnippet(() => ({ render: () => `<span>Its songs stay in your library.</span>` }));
// The children Snippet isn't inferable through testing-library's render.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type AnyProps = any;
function show(extra: Record<string, unknown> = {}) {
const onCancel = vi.fn();
const onConfirm = vi.fn();
render(ConfirmModal, {
props: {
title: 'Delete this playlist?',
open: true,
confirmLabel: 'Delete',
onCancel,
onConfirm,
children: body,
...extra
} as AnyProps
});
return { onCancel, onConfirm };
}
describe('ConfirmModal', () => {
test('says what goes, and acts only on the confirm button', async () => {
const { onCancel, onConfirm } = show();
expect(screen.getByRole('dialog', { name: 'Delete this playlist?' })).toBeInTheDocument();
expect(screen.getByText('Its songs stay in your library.')).toBeInTheDocument();
await fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
expect(onCancel).toHaveBeenCalledOnce();
expect(onConfirm).not.toHaveBeenCalled();
await fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
expect(onConfirm).toHaveBeenCalledOnce();
});
test('the confirm button wears the destructive action colour, not the error colour', () => {
show();
const confirm = screen.getByRole('button', { name: 'Delete' });
expect(confirm.className).toContain('bg-action-destructive');
});
test('while the act runs, both buttons are off and the confirm says so', () => {
show({ busy: true, busyLabel: 'Deleting…' });
expect(screen.getByRole('button', { name: 'Deleting…' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'Cancel' })).toBeDisabled();
});
});
// Asking before an act that can't be undone goes through ConfirmModal, and an
// error goes to a toast. The browser's own confirm() and alert() boxes look
// like neither app and can't be styled or tested, so no page calls them.
const NATIVE = /(?<![\w.])(?:window\.)?(?:confirm|alert)\(/;
describe('native dialogs', () => {
test('no page calls the browser confirm() or alert()', () => {
expect(offendingSources([NATIVE])).toEqual([]);
});
});
@@ -83,7 +83,10 @@
{#if $metrics.isPending}
<p class="text-sm text-text-secondary">Loading…</p>
{:else if $metrics.isError}
<p class="text-sm text-text-secondary">Couldn't load metrics.</p>
<p role="alert" class="text-sm text-error-fg">
Couldn't load metrics.
<button type="button" class="underline hover:no-underline" onclick={() => $metrics.refetch()}>Try again</button>
</p>
{:else if $metrics.data && ($metrics.data.groups.length > 0 || $metrics.data.baseline)}
{@const baseline = $metrics.data.baseline}
{#if baseline}
+41
View File
@@ -0,0 +1,41 @@
// Helpers for source guards: tests that read the web app's own source to
// assert a shape is absent (a hand-written count label, a native confirm()).
// Test-only; nothing in the app imports this.
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
/** web/src. */
export const SRC = join(dirname(fileURLToPath(import.meta.url)), '../..');
/**
* Comments describe the forbidden shape; strip them before asserting its
* absence, or the prose explaining a rule trips the check that enforces it.
*/
export const stripComments = (s: string): string =>
s.replace(/<!--[\s\S]*?-->/g, '').replace(/^\s*\/\/.*$/gm, '');
/** Every .svelte and .ts file under web/src, tests left out. */
export function appSources(dir: string = SRC): string[] {
return readdirSync(dir).flatMap((name) => {
const path = join(dir, name);
if (statSync(path).isDirectory()) return appSources(path);
return /\.(svelte|ts)$/.test(name) && !/\.test\.ts$/.test(name) ? [path] : [];
});
}
/**
* The app files, relative to web/src, whose source (comments stripped)
* matches any of patterns. Throws if the walk finds almost nothing, so a
* wrong root can't pass as "no offenders".
*/
export function offendingSources(patterns: RegExp[]): string[] {
const all = appSources();
if (all.length < 100) throw new Error(`source guard found only ${all.length} files under ${SRC}`);
return all
.filter((path) => {
const text = stripComments(readFileSync(path, 'utf8'));
return patterns.some((re) => re.test(text));
})
.map((path) => relative(SRC, path));
}
+2 -21
View File
@@ -1,8 +1,6 @@
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, test } from 'vitest';
import { plural } from './plural.js';
import { offendingSources } from '#lib/testing/sourceGuard.js';
describe('plural', () => {
test('says a count with the noun that agrees with it', () => {
@@ -21,8 +19,6 @@ describe('plural', () => {
// - the suffix trick: `minute${n === 1 ? '' : 's'}`.
// A choice of words with no count in it ("it" / "they", "yesterday") is
// not a count label and stays a ternary.
const SRC = join(dirname(fileURLToPath(import.meta.url)), '../..');
const HAND_ROLLED = [
/=== 1 \? ['"`]1 /,
/\{([\w.]+)\}\s*\{\1 === 1 \?/,
@@ -30,23 +26,8 @@ const HAND_ROLLED = [
/=== 1 \? '' : 's'/
];
/** Comments describe the forbidden shape; strip them before asserting its absence. */
const stripComments = (s: string) => s.replace(/<!--[\s\S]*?-->/g, '').replace(/^\s*\/\/.*$/gm, '');
function sources(dir: string): string[] {
return readdirSync(dir).flatMap((name) => {
const path = join(dir, name);
if (statSync(path).isDirectory()) return sources(path);
return /\.(svelte|ts)$/.test(name) && !/\.test\.ts$/.test(name) ? [path] : [];
});
}
describe('count labels', () => {
test('every count in the web app is said by plural()', () => {
const offenders = sources(SRC).flatMap((path) => {
const text = stripComments(readFileSync(path, 'utf8'));
return HAND_ROLLED.some((re) => re.test(text)) ? [relative(SRC, path)] : [];
});
expect(offenders).toEqual([]);
expect(offendingSources(HAND_ROLLED)).toEqual([]);
});
});