refactor(web): the admin settings cards share one load-and-save cycle (DRY W3)

Five settings cards (Fingerprinting, Loudness, Public address, Proxies,
Notification email) each hand-rolled the same cycle: load into a stored copy
and an editable one, say when they differ, save, adopt what the server
stored, toast. lib/settings/settingsForm.svelte.ts now runs it once
(createSettingsForm), and SettingsLoadStatus draws the "Loading…" / "Couldn't
load … Try again" line for those five and for Library folders and AcoustID.

The Proxies card dropped the server's reason when a save was refused and
toasted a fixed "Couldn't save proxy depth."; it now says why, as the other
cards do. Two cards' "Loading <thing>…" lines now read "Loading…" like the
rest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 03:13:32 -05:00
co-authored by Claude Opus 5.5
parent dae46ea980
commit 87c650aca1
10 changed files with 245 additions and 274 deletions
+3 -7
View File
@@ -12,6 +12,7 @@
import { pushToast } from '#lib/stores/toast.svelte.js';
import SettingsGroup from '#lib/components/settings/SettingsGroup.svelte';
import SettingRow from '#lib/components/settings/SettingRow.svelte';
import SettingsLoadStatus from '#lib/components/settings/SettingsLoadStatus.svelte';
// AcoustID recording-id lookup: fills the MusicBrainz ids that untagged
// tracks lack, so the similarity arms can see them. Off until an admin adds
@@ -131,13 +132,8 @@
</script>
<SettingsGroup title="AcoustID" id="acoustid" hint="Names untagged tracks from their sound, so radio and Songs-like can place them.">
{#if loadError}
<p class="px-4 py-3 text-sm text-error-fg">
Couldn't load AcoustID settings.
<button type="button" class="underline hover:no-underline" onclick={load}>Try again</button>
</p>
{:else if overview === null}
<p class="px-4 py-3 text-sm text-text-secondary">Loading AcoustID settings…</p>
{#if loadError || overview === null}
<SettingsLoadStatus failed={loadError} what="AcoustID settings" retry={load} />
{:else}
<SettingRow label="Status">
{#if overview.ready && !overview.status.problem}
@@ -1,14 +1,13 @@
<script lang="ts">
import { onMount } from 'svelte';
import {
getFingerprintSettings,
updateFingerprintSettings,
type FingerprintSettings
} from '#lib/api/admin.js';
import { errMessage } from '#lib/api/errors.js';
import { pushToast } from '#lib/stores/toast.svelte.js';
import SettingsGroup from '#lib/components/settings/SettingsGroup.svelte';
import SettingRow from '#lib/components/settings/SettingRow.svelte';
import { createSettingsForm } from '#lib/settings/settingsForm.svelte.js';
import SettingsLoadStatus from '#lib/components/settings/SettingsLoadStatus.svelte';
// How Minstrel fingerprints tracks and when it looks for duplicates.
// On Admin › Library; Duplicates says whether it is on and links here.
@@ -16,98 +15,67 @@
let { libraryTotal = 0, onSaved }: { libraryTotal?: number; onSaved?: () => void } =
$props();
let saved = $state<FingerprintSettings | null>(null);
let form = $state<FingerprintSettings | null>(null);
let saving = $state(false);
let loadError = $state(false);
const dirty = $derived(!!saved && !!form && JSON.stringify(saved) !== JSON.stringify(form));
const f = createSettingsForm<FingerprintSettings>({
load: getFingerprintSettings,
save: updateFingerprintSettings,
canSave: () => problems.length === 0,
savedMessage: 'Fingerprinting settings saved.',
onSaved: () => onSaved?.()
});
// Stored as the share of bits two fingerprints may disagree on; the report
// speaks in match percentages, so the card does too.
const matchPercent = $derived(
form ? Math.round((1 - form.acoustic_max_bit_error_rate) * 100) : 0
f.form ? Math.round((1 - f.form.acoustic_max_bit_error_rate) * 100) : 0
);
function onMatchInput(value: string) {
if (!form) return;
form.acoustic_max_bit_error_rate = value === '' ? NaN : Math.round(100 - Number(value)) / 100;
if (!f.form) return;
f.form.acoustic_max_bit_error_rate = value === '' ? NaN : Math.round(100 - Number(value)) / 100;
}
// The one setting with a cost an admin can't see from here: fingerprints
// taken at two lengths can't be compared, so a new length redoes the library.
const lengthChanged = $derived(
!!saved && !!form && form.chromaprint_length_sec !== saved.chromaprint_length_sec
!!f.saved && !!f.form && f.form.chromaprint_length_sec !== f.saved.chromaprint_length_sec
);
// Mirrors the server's ranges, so a bad value is named in the card's own
// terms (a percentage, not a bit-error rate) before anything is sent.
const between = (v: number, lo: number, hi: number) => Number.isInteger(v) && v >= lo && v <= hi;
const problems = $derived.by(() => {
if (!form) return [] as string[];
if (!f.form) return [] as string[];
const out: string[] = [];
if (!between(form.chromaprint_length_sec, 30, 600))
if (!between(f.form.chromaprint_length_sec, 30, 600))
out.push('Seconds of audio must be a whole number from 30 to 600.');
if (!between(matchPercent, 65, 99)) out.push('Minimum match must be from 65% to 99%.');
if (!between(form.backfill_concurrency, 1, 8))
if (!between(f.form.backfill_concurrency, 1, 8))
out.push('Files fingerprinted at once must be from 1 to 8.');
if (!between(form.sweep_interval_hours, 1, 168))
if (!between(f.form.sweep_interval_hours, 1, 168))
out.push('Hours between sweeps must be from 1 to 168.');
return out;
});
async function load() {
try {
saved = await getFingerprintSettings();
form = { ...saved };
loadError = false;
} catch {
loadError = true;
}
}
onMount(load);
async function save() {
if (!form || problems.length > 0) return;
saving = true;
try {
saved = await updateFingerprintSettings(form);
form = { ...saved };
pushToast('Fingerprinting settings saved.');
onSaved?.();
} catch (e) {
pushToast(errMessage(e), 'error');
} finally {
saving = false;
}
}
const button =
'rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50';
const field = 'w-24 rounded-md border border-border bg-background px-2 py-1.5 text-sm';
</script>
<SettingsGroup title="Fingerprinting" id="fingerprint-settings" hint="How alike two tracks must sound to be one recording. Identical files are always found.">
{#if loadError}
<p class="px-4 py-3 text-sm text-error-fg">
Couldn't load fingerprinting settings.
<button type="button" class="underline hover:no-underline" onclick={load}>Try again</button>
</p>
{:else if form === null}
<p class="px-4 py-3 text-sm text-text-secondary">Loading…</p>
{#if f.loadError || f.form === null}
<SettingsLoadStatus failed={f.loadError} what="fingerprinting settings" retry={load} />
{:else}
<SettingRow label="Fingerprint tracks" for="fp-enabled" hint="Off stops decoding audio; unfingerprinted tracks aren't compared.">
<input id="fp-enabled" type="checkbox" role="switch" aria-checked={form.enabled} bind:checked={form.enabled} class="h-4 w-4 cursor-pointer accent-accent" />
<input id="fp-enabled" type="checkbox" role="switch" aria-checked={f.form.enabled} bind:checked={f.form.enabled} class="h-4 w-4 cursor-pointer accent-accent" />
</SettingRow>
<SettingRow
label="Resolve duplicates automatically"
for="fp-auto"
hint="Merges clear cases into the best copy. Off, every group waits for you."
>
<input id="fp-auto" type="checkbox" role="switch" aria-checked={form.auto_resolve} bind:checked={form.auto_resolve} class="h-4 w-4 cursor-pointer accent-accent" />
<input id="fp-auto" type="checkbox" role="switch" aria-checked={f.form.auto_resolve} bind:checked={f.form.auto_resolve} class="h-4 w-4 cursor-pointer accent-accent" />
</SettingRow>
<SettingRow label="Seconds of audio to fingerprint" for="fp-length" hint="More tells apart late differences; slower per file.">
<input id="fp-length" type="number" min="30" max="600" bind:value={form.chromaprint_length_sec} class={field} />
<input id="fp-length" type="number" min="30" max="600" bind:value={f.form.chromaprint_length_sec} class={field} />
</SettingRow>
<SettingRow label="Minimum match" for="fp-match" hint="Higher proposes fewer, surer groups. Unrelated songs score about 50%.">
<input
@@ -122,10 +90,10 @@
<span class="text-sm text-text-secondary">%</span>
</SettingRow>
<SettingRow label="Files fingerprinted at once" for="fp-concurrency" hint="Lower it if playback stutters while it runs.">
<input id="fp-concurrency" type="number" min="1" max="8" bind:value={form.backfill_concurrency} class={field} />
<input id="fp-concurrency" type="number" min="1" max="8" bind:value={f.form.backfill_concurrency} class={field} />
</SettingRow>
<SettingRow label="Hours between sweeps" for="fp-sweep" hint="At least this long between automatic duplicate sweeps.">
<input id="fp-sweep" type="number" min="1" max="168" bind:value={form.sweep_interval_hours} class={field} />
<input id="fp-sweep" type="number" min="1" max="168" bind:value={f.form.sweep_interval_hours} class={field} />
</SettingRow>
{#if lengthChanged}
<!-- The one setting with a cost not visible here: fingerprints of two
@@ -143,8 +111,8 @@
{/each}
</ul>
{/if}
<button type="button" class={button} disabled={!dirty || saving || problems.length > 0} onclick={save}>
{saving ? 'Saving…' : 'Save'}
<button type="button" class={button} disabled={!f.dirty || f.saving || problems.length > 0} onclick={f.save}>
{f.saving ? 'Saving…' : 'Save'}
</button>
</div>
{/if}
@@ -9,6 +9,7 @@
import { pushToast } from '#lib/stores/toast.svelte.js';
import { plural } from '#lib/utils/plural.js';
import SettingRow from '#lib/components/settings/SettingRow.svelte';
import SettingsLoadStatus from '#lib/components/settings/SettingsLoadStatus.svelte';
// The library's folders, set here rather than only by
// MINSTREL_LIBRARY_SCAN_PATHS. Editing a folder's path says its files moved
@@ -75,13 +76,8 @@
const field = 'w-64 max-w-full rounded-md border border-border bg-background px-2 py-1.5 font-mono text-xs';
</script>
{#if loadError}
<p class="px-4 py-3 text-sm text-error-fg">
Couldn't load the library folders.
<button type="button" class="underline hover:no-underline" onclick={load}>Try again</button>
</p>
{:else if current === null}
<p class="px-4 py-3 text-sm text-text-secondary">Loading…</p>
{#if loadError || current === null}
<SettingsLoadStatus failed={loadError} what="the library folders" retry={load} />
{:else if !editing}
<SettingRow
label="Folders"
@@ -7,47 +7,37 @@
type LoudnessCoverage,
type LoudnessSettings
} from '#lib/api/admin.js';
import { errMessage } from '#lib/api/errors.js';
import { pushToast } from '#lib/stores/toast.svelte.js';
import SettingsGroup from '#lib/components/settings/SettingsGroup.svelte';
import SettingRow from '#lib/components/settings/SettingRow.svelte';
import SettingsLoadStatus from '#lib/components/settings/SettingsLoadStatus.svelte';
import { createSettingsForm } from '#lib/settings/settingsForm.svelte.js';
// Loudness analysis: the background measurement that loudness
// normalization levels playback from, its progress, and its knobs. The
// cache size bounds the leveled copies rendered for speakers.
let saved = $state<LoudnessSettings | null>(null);
let form = $state<LoudnessSettings | null>(null);
const f = createSettingsForm<LoudnessSettings>({
load: getLoudnessSettings,
save: updateLoudnessSettings,
canSave: () => valid,
savedMessage: 'Loudness analysis settings saved.',
onSaved: () => refreshCoverage()
});
let coverage = $state<LoudnessCoverage | null>(null);
let saving = $state(false);
let loadError = $state(false);
const dirty = $derived(!!saved && !!form && JSON.stringify(saved) !== JSON.stringify(form));
const concurrencyOk = $derived(
!!form &&
Number.isInteger(form.backfill_concurrency) &&
form.backfill_concurrency >= 1 &&
form.backfill_concurrency <= 8
!!f.form &&
Number.isInteger(f.form.backfill_concurrency) &&
f.form.backfill_concurrency >= 1 &&
f.form.backfill_concurrency <= 8
);
const cacheOk = $derived(
!!form &&
Number.isInteger(form.leveled_cache_mb) &&
form.leveled_cache_mb >= 256 &&
form.leveled_cache_mb <= 65536
!!f.form &&
Number.isInteger(f.form.leveled_cache_mb) &&
f.form.leveled_cache_mb >= 256 &&
f.form.leveled_cache_mb <= 65536
);
const valid = $derived(concurrencyOk && cacheOk);
async function load() {
try {
saved = await getLoudnessSettings();
form = { ...saved };
loadError = false;
} catch {
loadError = true;
}
await refreshCoverage();
}
// The gauge moves a few tracks a minute while the backfill runs, so a slow
// poll is enough; a failed read keeps the last figures rather than blanking.
async function refreshCoverage() {
@@ -59,29 +49,21 @@
}
onMount(() => {
load();
void refreshCoverage();
const timer = setInterval(refreshCoverage, 30_000);
return () => clearInterval(timer);
});
async function save() {
if (!form || !valid) return;
saving = true;
try {
saved = await updateLoudnessSettings(form);
form = { ...saved };
pushToast('Loudness analysis settings saved.');
await refreshCoverage();
} catch (e) {
pushToast(errMessage(e), 'error');
} finally {
saving = false;
}
}
const button =
'rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50';
const field = 'w-24 rounded-md border border-border bg-background px-2 py-1.5 text-sm';
// Try again reloads the gauge with the settings, as the first load does.
function retry() {
void f.load();
void refreshCoverage();
}
</script>
<SettingsGroup title="Loudness" id="loudness" hint="Measures each track so playback can even out the volume.">
@@ -104,22 +86,17 @@
</div>
{/if}
{#if loadError}
<p class="px-4 py-3 text-sm text-error-fg">
Couldn't load loudness analysis settings.
<button type="button" class="underline hover:no-underline" onclick={load}>Try again</button>
</p>
{:else if form === null}
<p class="px-4 py-3 text-sm text-text-secondary">Loading…</p>
{#if f.loadError || f.form === null}
<SettingsLoadStatus failed={f.loadError} what="loudness analysis settings" retry={retry} />
{:else}
<SettingRow label="Analyze tracks" for="loudness-enabled" hint="Off stops it; tracks already measured stay leveled.">
<input id="loudness-enabled" type="checkbox" role="switch" aria-checked={form.enabled} bind:checked={form.enabled} class="h-4 w-4 cursor-pointer accent-accent" />
<input id="loudness-enabled" type="checkbox" role="switch" aria-checked={f.form.enabled} bind:checked={f.form.enabled} class="h-4 w-4 cursor-pointer accent-accent" />
</SettingRow>
<SettingRow label="Files analyzed at once" for="loudness-concurrency" hint="Lower it if playback stutters while it runs.">
<input id="loudness-concurrency" type="number" min="1" max="8" bind:value={form.backfill_concurrency} class={field} />
<input id="loudness-concurrency" type="number" min="1" max="8" bind:value={f.form.backfill_concurrency} class={field} />
</SettingRow>
<SettingRow label="Speaker cache" for="loudness-cache" hint="Leveled copies for Sonos and UPnP speakers.">
<input id="loudness-cache" type="number" min="256" max="65536" step="256" bind:value={form.leveled_cache_mb} class={field} />
<input id="loudness-cache" type="number" min="256" max="65536" step="256" bind:value={f.form.leveled_cache_mb} class={field} />
<span class="text-sm text-text-secondary">MB</span>
</SettingRow>
<div class="flex flex-wrap items-center justify-end gap-2 px-4 py-3">
@@ -129,8 +106,8 @@
{#if !cacheOk}<p>Speaker cache must be a whole number of MB from 256 to 65536.</p>{/if}
</div>
{/if}
<button type="button" class={button} disabled={!dirty || saving || !valid} onclick={save}>
{saving ? 'Saving…' : 'Save'}
<button type="button" class={button} disabled={!f.dirty || f.saving || !valid} onclick={f.save}>
{f.saving ? 'Saving…' : 'Save'}
</button>
</div>
{/if}
@@ -1,28 +1,32 @@
<script lang="ts">
import { plural } from '#lib/utils/plural.js';
import { onMount } from 'svelte';
import {
getNetworkSettings,
updateNetworkSettings,
type NetworkSettings
} from '#lib/api/admin.js';
import { pushToast } from '#lib/stores/toast.svelte.js';
import SettingsGroup from '#lib/components/settings/SettingsGroup.svelte';
import SettingRow from '#lib/components/settings/SettingRow.svelte';
import { createSettingsForm } from '#lib/settings/settingsForm.svelte.js';
import SettingsLoadStatus from '#lib/components/settings/SettingsLoadStatus.svelte';
// Client IP detection, on Admin › Email & network: decides which address
// is recorded for each sign-in on the Active sessions list.
const f = createSettingsForm<NetworkSettings, number>({
load: getNetworkSettings,
save: updateNetworkSettings,
toForm: (s) => s.trusted_proxy_hops,
isDirty: (s, hops) => hops !== s.trusted_proxy_hops,
savedMessage: 'Proxy depth saved.',
failMessage: "Couldn't save proxy depth."
});
const button =
'rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50';
let settings = $state<NetworkSettings | null>(null);
let hops = $state(1);
let saving = $state(false);
let loadError = $state(false);
const dirty = $derived(!!settings && hops !== settings.trusted_proxy_hops);
const chain = $derived(
(settings?.forwarded_chain ?? '')
(f.saved?.forwarded_chain ?? '')
.split(',')
.map((s) => s.trim())
.filter(Boolean)
@@ -31,40 +35,11 @@
// than guessing — one XFF entry per proxy in front of us.
const suggested = $derived(chain.length);
async function load() {
try {
settings = await getNetworkSettings();
hops = settings.trusted_proxy_hops;
loadError = false;
} catch {
loadError = true;
}
}
onMount(load);
async function save() {
saving = true;
try {
settings = await updateNetworkSettings(hops);
hops = settings.trusted_proxy_hops;
pushToast('Proxy depth saved.');
} catch {
pushToast("Couldn't save proxy depth.", 'error');
} finally {
saving = false;
}
}
</script>
<SettingsGroup title="Proxies" id="proxies" hint="How many reverse proxies sit in front of Minstrel.">
{#if loadError}
<p class="px-4 py-3 text-sm text-error-fg">
Couldn't load network settings.
<button type="button" class="underline hover:no-underline" onclick={load}>Try again</button>
</p>
{:else if settings === null}
<p class="px-4 py-3 text-sm text-text-secondary">Loading…</p>
{#if f.loadError || f.saved === null}
<SettingsLoadStatus failed={f.loadError} what="network settings" retry={f.load} />
{:else}
<SettingRow
label="Trusted proxies"
@@ -75,15 +50,15 @@
id="proxy-hops"
type="number"
min="0"
max={settings.max_hops}
bind:value={hops}
max={f.saved.max_hops}
bind:value={f.form}
class="w-20 rounded-md border border-border bg-background px-2 py-1.5 text-sm"
/>
<button type="button" class={button} disabled={saving || !dirty} onclick={save}>
{saving ? 'Saving…' : 'Save'}
<button type="button" class={button} disabled={f.saving || !f.dirty} onclick={f.save}>
{f.saving ? 'Saving…' : 'Save'}
</button>
</SettingRow>
{#if suggested > 0 && settings.trusted_proxy_hops !== suggested}
{#if suggested > 0 && f.saved.trusted_proxy_hops !== suggested}
<p class="px-4 py-3 text-sm text-text-primary">
This request arrived with {plural(suggested, 'forwarded address', 'forwarded addresses')}, so
{plural(suggested, 'proxy is', 'proxies are')} likely.
@@ -92,13 +67,13 @@
<!-- Verification, not decoration: "the address Minstrel sees for you"
can be checked against the machine you're at. -->
<SettingRow label="Your address right now">
<span class="font-mono text-sm">{settings.detected_client_ip || 'unknown'}</span>
<span class="font-mono text-sm">{f.saved.detected_client_ip || 'unknown'}</span>
</SettingRow>
<SettingRow label="Direct connection from">
<span class="font-mono text-sm">{settings.remote_addr || 'unknown'}</span>
<span class="font-mono text-sm">{f.saved.remote_addr || 'unknown'}</span>
</SettingRow>
<SettingRow label="Forwarded chain">
<span class="break-all font-mono text-sm">{settings.forwarded_chain || 'none'}</span>
<span class="break-all font-mono text-sm">{f.saved.forwarded_chain || 'none'}</span>
</SettingRow>
<!-- X-Forwarded-For is written by whoever connects, so a depth set too
high lets a visitor pick the address their session shows. -->
@@ -1,6 +1,7 @@
import { describe, expect, test, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
import NetworkSettingsCard from './NetworkSettingsCard.svelte';
import { pushToast } from '#lib/stores/toast.svelte.js';
const getNetworkSettings = vi.fn();
const updateNetworkSettings = vi.fn();
@@ -97,6 +98,26 @@ describe('NetworkSettingsCard', () => {
expect(await screen.findByText(/Count your proxies/)).toBeTruthy();
});
test('a refused save says why, in the server\'s words', async () => {
getNetworkSettings.mockResolvedValue(settings());
updateNetworkSettings.mockRejectedValue({
code: 'invalid_setting',
message: 'trusted proxy hops must be from 0 to 10'
});
render(NetworkSettingsCard);
const input = await screen.findByRole('spinbutton');
await fireEvent.input(input, { target: { value: '2' } });
const save = screen.getByRole('button', { name: /Save/ });
await waitFor(() => expect(save).not.toBeDisabled());
await fireEvent.click(save);
await waitFor(() => expect(pushToast).toHaveBeenCalled());
const [text, kind] = vi.mocked(pushToast).mock.calls[0];
expect(kind).toBe('error');
expect(text).toContain('trusted proxy hops must be from 0 to 10');
});
test('offers a retry when loading fails', async () => {
getNetworkSettings.mockRejectedValue(new Error('boom'));
render(NetworkSettingsCard);
@@ -1,33 +1,27 @@
<script lang="ts">
import { onMount } from 'svelte';
import {
getNotificationEmailSettings,
updateNotificationEmailSettings,
type NotificationEmailSettings
} from '#lib/api/admin.js';
import { errMessage } from '#lib/api/errors.js';
import { pushToast } from '#lib/stores/toast.svelte.js';
import SettingsGroup from '#lib/components/settings/SettingsGroup.svelte';
import SettingRow from '#lib/components/settings/SettingRow.svelte';
import { createSettingsForm } from '#lib/settings/settingsForm.svelte.js';
import SettingsLoadStatus from '#lib/components/settings/SettingsLoadStatus.svelte';
// When notification emails go out. Nothing is emailed per
// event: new music is a daily summary, everything else a batch.
const f = createSettingsForm<NotificationEmailSettings>({
load: getNotificationEmailSettings,
save: updateNotificationEmailSettings,
savedMessage: 'Notification email schedule saved.'
});
const button =
'rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50';
const field = 'w-24 rounded-md border border-border bg-background px-2 py-1.5 text-sm';
let saved = $state<NotificationEmailSettings | null>(null);
let form = $state<NotificationEmailSettings | null>(null);
let saving = $state(false);
let loadError = $state(false);
const dirty = $derived(
!!saved &&
!!form &&
(saved.summary_hour !== form.summary_hour ||
saved.batch_window_minutes !== form.batch_window_minutes)
);
const hours = Array.from({ length: 24 }, (_, h) => h);
@@ -35,58 +29,26 @@
return `${String(h).padStart(2, '0')}:00`;
}
async function load() {
try {
saved = await getNotificationEmailSettings();
form = { ...saved };
loadError = false;
} catch {
loadError = true;
}
}
onMount(load);
async function save() {
if (!form) return;
saving = true;
try {
saved = await updateNotificationEmailSettings(form);
form = { ...saved };
pushToast('Notification email schedule saved.');
} catch (e) {
// The server names the field it refused (errMessage, not e.message:
// the client throws a plain object).
pushToast(errMessage(e), 'error');
} finally {
saving = false;
}
}
</script>
<SettingsGroup title="Notification emails" id="notification-emails" hint="Never one per event. Each person picks theirs in their own settings.">
{#if loadError}
<p class="px-4 py-3 text-sm text-error-fg">
Couldn't load the email schedule.
<button type="button" class="underline hover:no-underline" onclick={load}>Try again</button>
</p>
{:else if form === null}
<p class="px-4 py-3 text-sm text-text-secondary">Loading the email schedule…</p>
{#if f.loadError || f.form === null}
<SettingsLoadStatus failed={f.loadError} what="the email schedule" retry={f.load} />
{:else}
<SettingRow label="New music summary" for="summary-hour" hint="Daily, at this hour in each person's timezone.">
<select id="summary-hour" bind:value={form.summary_hour} class={field}>
<select id="summary-hour" bind:value={f.form.summary_hour} class={field}>
{#each hours as h (h)}
<option value={h}>{hourLabel(h)}</option>
{/each}
</select>
</SettingRow>
<SettingRow label="Batch everything else" for="batch-window" hint="One email this long after the first item.">
<input id="batch-window" type="number" min="15" max="1440" bind:value={form.batch_window_minutes} class={field} />
<input id="batch-window" type="number" min="15" max="1440" bind:value={f.form.batch_window_minutes} class={field} />
<span class="text-sm text-text-secondary">minutes</span>
</SettingRow>
<div class="flex justify-end px-4 py-3">
<button type="button" class={button} disabled={!dirty || saving} onclick={save}>
{saving ? 'Saving…' : 'Save'}
<button type="button" class={button} disabled={!f.dirty || f.saving} onclick={f.save}>
{f.saving ? 'Saving…' : 'Save'}
</button>
</div>
{/if}
+20 -48
View File
@@ -1,61 +1,33 @@
<script lang="ts">
import { onMount } from 'svelte';
import { getNetworkSettings, updatePublicUrl } from '#lib/api/admin.js';
import { errMessage } from '#lib/api/errors.js';
import { pushToast } from '#lib/stores/toast.svelte.js';
import { getNetworkSettings, updatePublicUrl, type NetworkSettings } from '#lib/api/admin.js';
import SettingsGroup from '#lib/components/settings/SettingsGroup.svelte';
import SettingRow from '#lib/components/settings/SettingRow.svelte';
import { createSettingsForm } from '#lib/settings/settingsForm.svelte.js';
import SettingsLoadStatus from '#lib/components/settings/SettingsLoadStatus.svelte';
// The address links in email point at, on Admin › Email & network.
const f = createSettingsForm<NetworkSettings, string>({
load: getNetworkSettings,
save: (url) => updatePublicUrl(url.trim()),
toForm: (s) => s.public_url,
isDirty: (s, url) => url.trim() !== s.public_url,
savedMessage: (s) => (s.public_url ? 'Public address saved.' : 'Public address cleared.'),
failMessage: "Couldn't save the public address."
});
const button =
'rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50';
let saved = $state<string | null>(null);
let value = $state('');
let saving = $state(false);
let loadError = $state(false);
const dirty = $derived(saved !== null && value.trim() !== saved);
// The address this page was loaded from is almost always the right answer,
// so offer it rather than making an admin type it.
const here = typeof window !== 'undefined' ? window.location.origin : '';
async function load() {
try {
const s = await getNetworkSettings();
saved = s.public_url;
value = s.public_url;
loadError = false;
} catch {
loadError = true;
}
}
onMount(load);
async function save() {
saving = true;
try {
const s = await updatePublicUrl(value.trim());
saved = s.public_url;
value = s.public_url;
pushToast(saved ? 'Public address saved.' : 'Public address cleared.');
} catch (e) {
pushToast(errMessage(e, "Couldn't save the public address."), 'error');
} finally {
saving = false;
}
}
</script>
<SettingsGroup title="Public address" id="public-address" hint="Where people reach Minstrel. Password-reset emails link here.">
{#if loadError}
<p class="px-4 py-3 text-sm text-error-fg">
Couldn't load the public address.
<button type="button" class="underline hover:no-underline" onclick={load}>Try again</button>
</p>
{:else if saved === null}
<p class="px-4 py-3 text-sm text-text-secondary">Loading…</p>
{#if f.loadError || f.saved === null}
<SettingsLoadStatus failed={f.loadError} what="the public address" retry={f.load} />
{:else}
<SettingRow label="Address" for="public-url">
<input
@@ -63,19 +35,19 @@
type="url"
inputmode="url"
placeholder="https://music.example.com"
bind:value
bind:value={f.form}
class="w-64 max-w-full rounded-md border border-border bg-background px-3 py-1.5 font-mono text-sm"
/>
<button type="button" class={button} disabled={saving || !dirty} onclick={save}>
{saving ? 'Saving…' : 'Save'}
<button type="button" class={button} disabled={f.saving || !f.dirty} onclick={f.save}>
{f.saving ? 'Saving…' : 'Save'}
</button>
</SettingRow>
{#if here && value.trim() !== here}
{#if here && f.form?.trim() !== here}
<SettingRow label="This page's address" hint={here}>
<button type="button" class={button} onclick={() => (value = here)}>Use {here}</button>
<button type="button" class={button} onclick={() => (f.form = here)}>Use {here}</button>
</SettingRow>
{/if}
{#if !saved}
{#if !f.saved?.public_url}
<!-- Not built from the request's own Host: anyone can claim any address. -->
<p class="px-4 py-3 text-sm text-error-fg" role="status">
Not set, so password-reset emails are not being sent.
@@ -0,0 +1,14 @@
<script lang="ts">
// The line a settings card shows in place of its rows until they load:
// "Loading…", or what failed to load with a Try again.
let { failed, what, retry }: { failed: boolean; what: string; retry: () => void } = $props();
</script>
{#if failed}
<p class="px-4 py-3 text-sm text-error-fg">
Couldn't load {what}.
<button type="button" class="underline hover:no-underline" onclick={retry}>Try again</button>
</p>
{:else}
<p class="px-4 py-3 text-sm text-text-secondary">Loading…</p>
{/if}