import type { Taxonomy } from "@cloudhal/core-contracts"; import { Badge, Banner, Checkbox, Field, Input, InputGroup, InsetPanel, LayerDialog, Radio, Switch, Text, TransitionArrow, } from "@cloudhal/ui"; import { Camera, Info, ShieldCheck, Star, Warning, WarningCircle } from "@phosphor-icons/react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { type ReactNode, useEffect, useState } from "react"; import { type MessageKey, useI18n, useT } from "../i18n/index.tsx"; import { api } from "../lib/api.ts"; import { useCollectionKeys } from "../lib/collections.ts"; import { primaryHostname } from "../lib/site-settings.ts"; import { archiveChange, type BasePathError, draftOf, effectiveBasePath, hasTaxonomyErrors, type KeyError, knownCollections, type LabelError, newTaxonomyDraft, TAXONOMY_LIMITS, type TaxonomyDraft, taxonomyFromDraft, validateTaxonomy, } from "../lib/taxonomy-settings.ts"; import { isDirty } from "../lib/util.ts"; import { ErrorBanner } from "./ErrorBanner.tsx"; import { invalidateTaxonomy, type TaxonomyData, taxonomyKeys } from "./Taxonomy.tsx"; import { useToast } from "./Toast.ts"; const KEY_ERROR: Record = { required: "taxonomySettings.errors.keyRequired", invalid: "taxonomySettings.errors.keyInvalid", tooLong: "taxonomySettings.errors.keyTooLong", reserved: "taxonomySettings.errors.keyReserved", taken: "taxonomySettings.errors.keyTaken", }; const LABEL_ERROR: Record = { required: "taxonomySettings.errors.labelRequired", tooLong: "taxonomySettings.errors.labelTooLong", pair: "taxonomySettings.errors.labelPair", }; const PATH_ERROR: Record = { required: "taxonomySettings.errors.pathRequired", invalid: "taxonomySettings.errors.pathInvalid", tooLong: "taxonomySettings.errors.pathTooLong", root: "taxonomySettings.errors.pathRoot", taxonomy: "taxonomySettings.errors.pathTaxonomy", page: "taxonomySettings.errors.pathPage", collection: "taxonomySettings.errors.pathCollection", }; const NEW_TERMS = ["none", "propose", "free"] as const; /** A `Switch` with its explanation underneath (related text close together). */ export function SwitchField({ label, hint, checked, onChange, disabled, testId, }: { label: string; hint: ReactNode; checked: boolean; onChange: (v: boolean) => void; disabled?: boolean; testId: string; }) { return (
onChange(v)} disabled={disabled} data-testid={testId} /> {hint}
); } /** One titled group of the form; groups are separated by hairlines. */ function FormSection({ title, description, children, testId, }: { title: string; description?: string; children: ReactNode; testId: string; }) { return (
{title} {description && ( {description} )}
{children}
); } /** * Create a taxonomy (custom ones such as `series` or `region`) or edit one's settings (DESIGN.md * §2p): the key (immutable once created; reserved words refused), labels per locale, structure, * who adds terms — spelled out for agents —, the per-article rule (required, maximum, * collections), archive pages and their address, feeds and the indexing threshold. Validated like * core-ts before anything is sent; moving an enabled archive previews the redirect the core leaves * behind. One save, one snapshot. */ export function TaxonomySettingsDialog({ open, onOpenChange, siteId, taxonomy, data, onCreated, }: { open: boolean; onOpenChange: (open: boolean) => void; siteId: string; /** The taxonomy to edit; absent: create a new one. */ taxonomy?: Taxonomy | undefined; data: TaxonomyData; onCreated?: (taxonomy: Taxonomy) => void; }) { const t = useT(); const { locale: uiLocale } = useI18n(); const qc = useQueryClient(); const toast = useToast(); const defaultLocale = data.defaultLocale; const [draft, setDraft] = useState(() => newTaxonomyDraft(defaultLocale)); const [submitted, setSubmitted] = useState(false); const pages = useQuery({ queryKey: ["pages", siteId], queryFn: () => api.pages.list(siteId), enabled: open, }); const entries = useQuery({ queryKey: ["entries", siteId, "all"], queryFn: () => api.entries.list(siteId), enabled: open, }); const redirects = useQuery({ queryKey: taxonomyKeys.redirects(siteId), queryFn: () => api.redirects.list(siteId), enabled: open && taxonomy !== undefined, }); useEffect(() => { if (!open) return; setDraft(taxonomy ? draftOf(taxonomy) : newTaxonomyDraft(defaultLocale)); setSubmitted(false); }, [open, taxonomy?.id, taxonomy?.rev]); const editing = taxonomy !== undefined; const set = (patch: Partial) => setDraft((d) => ({ ...d, ...patch })); const collections = knownCollections(entries.data ?? [], draft, useCollectionKeys(siteId)); const errors = validateTaxonomy(draft, { defaultLocale, taxonomies: data.taxonomies.data ?? [], pages: pages.data ?? [], collections: [...new Set((entries.data ?? []).map((e) => e.collection))], terms: taxonomy ? data.itemsOf(taxonomy).map((i) => i.term) : [], selfId: taxonomy?.id, }); const base = effectiveBasePath(draft); const example = `${base || "/…"}/${t("taxonomySettings.exampleSlug")}`; const change = archiveChange(taxonomy, draft, redirects.data ?? []); const dirty = !editing || isDirty(draft, taxonomy ? draftOf(taxonomy) : undefined); const host = primaryHostname(data.site.data?.domains ?? []); const plural = taxonomy ? data.label(taxonomy) : ""; const singularLabel = taxonomy ? data.label(taxonomy, "singular") : ""; const shown = (e: unknown) => (submitted || editing) && e !== undefined; // A taken or reserved key, or a colliding address, is worth knowing while typing. const keyError = errors.key && (shown(errors.key) || (draft.key !== "" && errors.key !== "required")) ? errors.key : undefined; const pathError = errors.basePath && (shown(errors.basePath) || (base !== "" && errors.basePath !== "required")) ? errors.basePath : undefined; const save = useMutation({ mutationFn: async () => { const next = taxonomyFromDraft(draft); if (!taxonomy) return (await api.taxonomies.create(siteId, next)).taxonomy; const { maxPerEntry: _m, collections: _c, ...stored } = taxonomy; return (await api.taxonomies.update({ ...stored, ...next, key: taxonomy.key })).taxonomy; }, onSuccess: async (saved) => { await invalidateTaxonomy(qc, siteId); const name = saved.labels[defaultLocale]?.plural ?? saved.key; toast.success( editing ? t("taxonomySettings.saved", { name }) : t("taxonomySettings.created", { name }), t("governance.oneSnapshot"), ); if (!editing) onCreated?.(saved); onOpenChange(false); }, }); const submit = () => { setSubmitted(true); if (hasTaxonomyErrors(errors)) return; save.mutate(); }; const labelLocales = [...new Set([defaultLocale, ...data.locales])]; const labelError = (l: string, form: "singular" | "plural") => { const e = errors.labels?.[l]?.[form]; return shown(e) && e ? t(LABEL_ERROR[e], { max: TAXONOMY_LIMITS.labelMax }) : undefined; }; return ( {editing ? t("taxonomySettings.titleEdit", { Singular: singularLabel }) : t("taxonomySettings.titleNew")} {editing ? t("taxonomySettings.descriptionEdit", { plural: plural.toLocaleLowerCase(uiLocale), }) : t("taxonomySettings.descriptionNew")}
set({ key: v.trim().toLowerCase() })} description={ editing ? t("taxonomySettings.keyFixed") : t("taxonomySettings.keyHint") } error={keyError ? t(KEY_ERROR[keyError], { key: draft.key }) : undefined} disabled={editing} maxLength={TAXONOMY_LIMITS.keyMax} spellCheck={false} className="w-full font-mono" autoFocus={!editing} data-testid="taxonomy-key" /> {labelLocales.map((l) => { const label = draft.labels[l] ?? { singular: "", plural: "" }; const edit = (patch: Partial) => set({ labels: { ...draft.labels, [l]: { ...label, ...patch } } }); return (
edit({ singular: v })} placeholder={t("taxonomySettings.singularPlaceholder")} error={labelError(l, "singular")} maxLength={TAXONOMY_LIMITS.labelMax} required={l === defaultLocale} className="w-full" data-testid={`label-singular-${l}`} /> edit({ plural: v })} placeholder={t("taxonomySettings.pluralPlaceholder")} error={labelError(l, "plural")} maxLength={TAXONOMY_LIMITS.labelMax} required={l === defaultLocale} className="w-full" data-testid={`label-plural-${l}`} />
{l === defaultLocale ? t("taxonomySettings.labelsHint") : t("taxonomySettings.labelsOptional", { locale: defaultLocale })}
); })}
set({ hierarchical: v })} testId="taxonomy-hierarchical" /> {errors.hierarchical !== undefined && ( } title={t("taxonomySettings.errors.hasParents", { count: errors.hierarchical })} /> )}
set({ allowNewTerms: v as Taxonomy["allowNewTerms"] })} > {NEW_TERMS.map((value) => ( {t(`taxonomySettings.newTermsOptions.${value}`)} {value === "none" && ( }> {t("taxonomySettings.badges.safest")} )} {value === "propose" && ( }> {t("taxonomySettings.badges.recommended")} )} {value === "free" && ( }> {t("taxonomySettings.badges.careful")} )} } description={t(`taxonomySettings.newTermsHints.${value}`)} /> ))}
{errors.allowNewTerms !== undefined && ( } title={t("taxonomySettings.errors.hasProposals", { count: errors.allowNewTerms })} /> )}
set({ required: v })} testId="taxonomy-required" /> set({ maxPerEntry: v })} placeholder={String(TAXONOMY_LIMITS.perEntryMax)} description={t("taxonomySettings.maxPerEntryHint", { max: TAXONOMY_LIMITS.perEntryMax, })} error={ shown(errors.maxPerEntry) ? t("taxonomySettings.errors.range", { min: 1, max: TAXONOMY_LIMITS.perEntryMax, }) : undefined } min={1} max={TAXONOMY_LIMITS.perEntryMax} required={false} className="w-full" data-testid="taxonomy-max" /> set({ collections: v ? undefined : collections.slice(0, 1) })} testId="taxonomy-all-collections" /> {draft.collections !== undefined && ( {collections.map((c) => ( {`/${c}`}} checked={draft.collections?.includes(c) ?? false} onCheckedChange={(v: boolean) => set({ collections: v ? [...(draft.collections ?? []), c].sort() : (draft.collections ?? []).filter((x) => x !== c), }) } /> ))} )} set({ archiveEnabled: v })} testId="taxonomy-archive" /> {host && {host}} set({ basePath: (e.target as HTMLInputElement).value.trim().toLowerCase() }) } spellCheck={false} className="font-mono" data-testid="taxonomy-base-path" /> set({ feed: v })} disabled={!draft.archiveEnabled} testId="taxonomy-feed" /> set({ minEntriesToIndex: v })} description={t("taxonomySettings.minEntriesHint")} error={ shown(errors.minEntriesToIndex) ? t("taxonomySettings.errors.range", { min: 0, max: TAXONOMY_LIMITS.indexMax }) : undefined } min={0} max={TAXONOMY_LIMITS.indexMax} className="w-full" data-testid="taxonomy-min-entries" />
{t("governance.oneSnapshot")}
{editing ? t("taxonomySettings.save") : t("taxonomySettings.create")}
); } /** What saving does to public addresses: the redirect a moved archive leaves, or archives that stop or start. */ function ArchiveChangePreview({ change }: { change: ReturnType }) { const t = useT(); if (change.redirect) return (
{t("governance.preview.redirects")} 1
{t("taxonomySettings.move.description")}
{change.redirect.from} {change.redirect.to} {t("governance.preview.permanent")}
{t("governance.preview.prefix")}
{change.follow > 0 && ( {t("governance.preview.repointed", { count: change.follow })} )}
); if (change.disabled) return ( } title={t("taxonomySettings.move.offTitle")} description={t("taxonomySettings.move.offDescription", { path: change.disabled })} data-testid="archive-off" /> ); if (change.enabled) return ( } title={t("taxonomySettings.move.onTitle", { path: change.enabled })} description={t("taxonomySettings.move.onDescription")} data-testid="archive-on" /> ); return null; }