import { useEffect, useMemo, useState } from "react"; import { api, type NameImportPreview, type NameTheme, type NameThemeSource } from "../../api/client"; import { confirmDialog } from "../../utils/dialogs"; import { formatDateTime } from "../../utils/date"; import { readableError } from "../../utils/errors"; import { parseNames } from "../../utils/nameLists"; import { ErrorNotice, SuccessNotice } from "../../components/Notice"; /** One list as it's being edited. The names are kept as the text in the box, so typing stays natural. */ interface Draft { /** Stable for the life of the page; a list that hasn't been saved yet has no `id`. */ key: string; id?: string; label: string; text: string; lastImport?: NameThemeSource; } const MAX_LABEL = 40; function toDraft(t: NameTheme): Draft { return { key: t.id, id: t.id, label: t.label, text: t.names.join("\n"), lastImport: t.lastImport }; } /** What identifies the content of a list, for telling whether anything changed. */ function snapshot(id: string | undefined, label: string, names: string[], lastImport: NameThemeSource | undefined): string { return JSON.stringify({ id, label, names, lastImport }); } function describeImport(s: NameThemeSource): string { const years = s.years.length === 0 ? "" : s.years.length === 1 ? String(s.years[0]) : `${s.years[0]}–${s.years[s.years.length - 1]}`; return `${s.sex === "girls" ? "girls" : "boys"}, ${years}, top ${s.count} — ${formatDateTime(new Date(s.importedAt))}`; } export default function NameSettings() { const [saved, setSaved] = useState(null); const [builtinIds, setBuiltinIds] = useState([]); const [drafts, setDrafts] = useState([]); const [selectedKey, setSelectedKey] = useState(null); const [error, setError] = useState(null); const [notice, setNotice] = useState(null); const [busy, setBusy] = useState(false); const [newCount, setNewCount] = useState(0); // Skatteverket import panel const [importOpen, setImportOpen] = useState(false); const [sex, setSex] = useState<"girls" | "boys">("girls"); const [years, setYears] = useState(3); const [count, setCount] = useState(100); const [fetching, setFetching] = useState(false); const [importError, setImportError] = useState(null); const [preview, setPreview] = useState(null); useEffect(() => { api.generator .themes() .then((res) => { setSaved(res.themes); setBuiltinIds(res.builtinIds); const next = res.themes.map(toDraft); setDrafts(next); setSelectedKey(next[0]?.key ?? null); }) .catch((err) => setError(readableError(err))); }, []); const parsed = useMemo(() => drafts.map((d) => parseNames(d.text)), [drafts]); const selectedIndex = Math.max(0, drafts.findIndex((d) => d.key === selectedKey)); const selected = drafts[selectedIndex]; const selectedParsed = parsed[selectedIndex]; const dirty = useMemo(() => { if (!saved) return false; const now = drafts.map((d, i) => snapshot(d.id, d.label.trim(), parsed[i].names, d.lastImport)); const before = saved.map((t) => snapshot(t.id, t.label, t.names, t.lastImport)); return JSON.stringify(now) !== JSON.stringify(before); }, [saved, drafts, parsed]); const problem = useMemo(() => { for (let i = 0; i < drafts.length; i++) { if (!drafts[i].label.trim()) return "Every list needs a name."; if (parsed[i].invalid.length > 0) return `“${drafts[i].label.trim() || "A list"}” has names that can't be used — see the list.`; } return null; }, [drafts, parsed]); function update(key: string, patch: Partial) { setDrafts((all) => all.map((d) => (d.key === key ? { ...d, ...patch } : d))); setNotice(null); } function select(key: string) { setSelectedKey(key); setImportOpen(false); setPreview(null); setImportError(null); } function addList() { const key = `new-${newCount}`; setNewCount((n) => n + 1); setDrafts((all) => [...all, { key, label: "New list", text: "" }]); select(key); setNotice(null); } async function removeList(d: Draft) { const ok = await confirmDialog({ title: "Delete list", message: `Delete “${d.label.trim() || "this list"}”? It's removed when you save${d.id && builtinIds.includes(d.id) ? ", and can be brought back with “Restore built-in lists”" : ""}.`, confirmLabel: "Delete", danger: true, }); if (!ok) return; const index = drafts.findIndex((x) => x.key === d.key); const rest = drafts.filter((x) => x.key !== d.key); setDrafts(rest); select(rest[Math.min(index, rest.length - 1)]?.key ?? ""); setNotice(null); } async function resetToBuiltIn(d: Draft) { if (!d.id) return; const ok = await confirmDialog({ title: "Reset list", message: `Put “${d.label.trim() || d.id}” back to its built-in names? Your edits to this list are lost (once you save).`, confirmLabel: "Reset", danger: true, }); if (!ok) return; try { const { themes } = await api.generator.defaults(); const original = themes.find((t) => t.id === d.id); if (!original) throw new Error("There's no built-in version of this list."); update(d.key, { label: original.label, text: original.names.join("\n"), lastImport: undefined }); } catch (err) { setError(readableError(err)); } } const missingBuiltIns = builtinIds.filter((id) => !drafts.some((d) => d.id === id)); async function restoreBuiltIns() { try { const { themes } = await api.generator.defaults(); const missing = themes.filter((t) => missingBuiltIns.includes(t.id)); setDrafts((all) => [...all, ...missing.map(toDraft)]); setNotice(`Brought back ${missing.length} built-in list${missing.length === 1 ? "" : "s"} — save to keep ${missing.length === 1 ? "it" : "them"}.`); } catch (err) { setError(readableError(err)); } } async function save() { setBusy(true); setError(null); setNotice(null); try { const res = await api.generator.save( drafts.map((d, i) => ({ id: d.id, label: d.label.trim(), names: parsed[i].names, lastImport: d.lastImport })), ); const keepAt = selectedIndex; setSaved(res.themes); const next = res.themes.map(toDraft); setDrafts(next); setSelectedKey(next[Math.min(keepAt, next.length - 1)]?.key ?? null); setNotice("Saved. The Generator uses these lists from now on."); } catch (err) { setError(readableError(err)); } finally { setBusy(false); } } function discard() { if (!saved) return; const next = saved.map(toDraft); setDrafts(next); setSelectedKey(next[0]?.key ?? null); setNotice(null); setError(null); setImportOpen(false); setPreview(null); } async function fetchPreview() { setFetching(true); setImportError(null); setPreview(null); try { setPreview(await api.generator.importNames(sex, years, count)); } catch (err) { setImportError(readableError(err)); } finally { setFetching(false); } } function applyPreview(mode: "add" | "replace") { if (!preview || !selected) return; const existing = mode === "add" ? selectedParsed.names : []; const have = new Set(existing); const fresh = preview.names.filter((n) => !have.has(n)); update(selected.key, { text: [...existing, ...fresh].join("\n"), lastImport: preview.source }); setNotice( mode === "add" ? `Added ${fresh.length} new name${fresh.length === 1 ? "" : "s"} (${preview.names.length - fresh.length} were already there) — save to keep ${fresh.length === 1 ? "it" : "them"}.` : `Replaced the list with ${preview.names.length} names — save to keep them.`, ); setPreview(null); setImportOpen(false); } function sortList() { if (!selected) return; update(selected.key, { text: [...selectedParsed.names].sort((a, b) => a.localeCompare(b, "sv")).join("\n") }); } if (!saved) { return error ?
{error}
:
Loading…
; } return ( <>

Name lists

{missingBuiltIns.length > 0 && ( )}
Operations → Generator picks server names from these lists. A name is letters, digits and hyphens (å, ä and ö become a, a and o), so it works as a hostname. Changes apply when you save.
{drafts.length === 0 ? (
No lists. Add one, or restore the built-in ones.
) : (
    {drafts.map((d, i) => (
  • ))}
)}
{selected && selectedParsed && (
update(selected.key, { label: e.target.value })} />
{selected.id && builtinIds.includes(selected.id) && ( )}
{importOpen && (
Import the most common names from Skatteverket
Skatteverket publishes the given names of newborns in Sweden, by sex and birth year, as open data. This fetches the most common ones across the years you pick (the running year isn't counted — it isn't complete). You see them first; nothing changes until you add them to this list and save.
setCount(Math.min(500, Math.max(10, Number(e.target.value) || 10)))} />
{preview && (
Found {preview.names.length} names for {preview.source.sex === "girls" ? "girls" : "boys"}, born{" "} {preview.source.years.join(", ")}. {preview.missingYears.length > 0 && No data yet for {preview.missingYears.join(", ")}.} {preview.skipped.length > 0 && ( {" "} {preview.skipped.length} left out because they can't be used as a server name ({preview.skipped.slice(0, 5).join(", ")} {preview.skipped.length > 5 ? ", …" : ""}). )}
{preview.names.join(", ")}
)}
)}