import type { Term } from "@cloudhal/core-contracts"; import { Badge, Banner, Button, DropdownMenu, InlineCopyText, Input, InputArea, InsetPanel, LayerCard, PageLayout, SectionCard, SectionEmpty, SkeletonLine, Tabs, TagInput, Text, Tooltip, TransitionArrow, } from "@cloudhal/ui"; import { ArrowsMerge, Check, ClockCounterClockwise, DotsThree, Eye, EyeSlash, MagnifyingGlass, Notepad, TextAa, Trash, TreeStructure, } from "@phosphor-icons/react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useParams } from "@tanstack/react-router"; import { useEffect, useState } from "react"; import { SiteCrumbs } from "../components/Crumbs.tsx"; import { DangerZoneCard, type DetailRow, DetailsCard, EditorLayout, PreviewToggle, usePreviewVisible, } from "../components/EditorLayout.tsx"; import { ErrorBanner } from "../components/ErrorBanner.tsx"; import { ReadOnly, ViewOnlyBanner } from "../components/Gating.tsx"; import { GovernanceDialog, type GovernanceTarget } from "../components/GovernanceDialog.tsx"; import { UsedInMenusCard } from "../components/Menus.tsx"; import { RelativeTime } from "../components/RelativeTime.tsx"; import { CountedHint, CoverImageCard, SeoFields } from "../components/Seo.tsx"; import { IndexBadge, invalidateTaxonomy, TermStateBadges, useTaxonomyData, VisibilityBadge, } from "../components/Taxonomy.tsx"; import { TermArchivePreview } from "../components/TermArchivePreview.tsx"; import { useToast } from "../components/Toast.ts"; import { useGate } from "../components/useMe.ts"; import { type MessageKey, useI18n, useT } from "../i18n/index.tsx"; import { api } from "../lib/api.ts"; import { primaryHostname } from "../lib/site-settings.ts"; import { type AltNameError, archiveCounts, archivePath, cleanTerm, editLabel, hasTermErrors, indexStatus, TERM_LIMITS, validateTerm, } from "../lib/taxonomy.ts"; import { isDirty } from "../lib/util.ts"; const ALT_ERROR: Record = { tooLong: "termEditor.errors.altTooLong", duplicate: "termEditor.errors.altDuplicate", collision: "termEditor.errors.altCollision", }; /** * Site › Categories & tags › a term (DESIGN.md §2p): names and synonyms per locale, the archive * introduction (markdown), the image (the cover-image card) and search settings per locale (the * SEO fields), placement (parent, position), indexing and the read-only slug history with its * redirects, and a live preview of the archive page with the unsaved text and what its address * answers. Slug, parent, visibility and retirement change only through the governance dialogs. */ export function TermEditorPage() { const t = useT(); const { locale: uiLocale } = useI18n(); const { siteId, termId } = useParams({ from: "/sites/$siteId/taxonomy/$termId" }); const qc = useQueryClient(); const toast = useToast(); const data = useTaxonomyData(siteId); const detail = useQuery({ queryKey: ["term", siteId, termId], queryFn: () => api.terms.get(siteId, termId), }); const [draft, setDraft] = useState(); const [showErrors, setShowErrors] = useState(false); const [locale, setLocale] = useState(); const [governance, setGovernance] = useState(); const [previewVisible, setPreviewVisible] = usePreviewVisible(); useEffect(() => { if (detail.data) setDraft(detail.data.term); }, [detail.data]); const saved = detail.data?.term; const dirty = isDirty(draft, saved); const tax = data.taxonomies.data?.find((x) => x.id === saved?.taxonomyId); const siblings = tax ? data.itemsOf(tax) : []; const host = primaryHostname(data.site.data?.domains ?? []); const defaultLocale = data.defaultLocale; const activeLocale = locale ?? defaultLocale; // Terms are structure: Editors and above change them; others read (RFC-0005 §2.2, §2s). const structure = useGate("structure.write"); const save = useMutation({ mutationFn: (term: Term) => api.terms.update(cleanTerm(term, defaultLocale)), onSuccess: async ({ term }) => { setDraft(term); setShowErrors(false); qc.setQueryData(["term", siteId, termId], (old: typeof detail.data) => old ? { ...old, term } : old, ); await invalidateTaxonomy(qc, siteId); toast.success(t("editor.saved"), t("governance.oneSnapshot")); }, }); const approve = useMutation({ mutationFn: (term: Term) => api.terms.govern(term, { op: "review", decision: "approve" }), onSuccess: async () => { await invalidateTaxonomy(qc, siteId); toast.success(t("taxonomy.review.approved", { name: saved ? data.name(saved) : "" })); }, }); const listHref = `/sites/${siteId}/taxonomy${tax ? `?taxonomy=${tax.key}` : ""}`; const listCrumb = { label: t("pageHeaders.taxonomy.title"), href: listHref }; if (!draft || !saved || !tax) { return ( } title={undefined} loading={detail.isPending || data.taxonomies.isPending} > ); } const errors = validateTerm(draft, { defaultLocale, terms: siblings.map((i) => i.term) }); const localeErrors = errors.locales[activeLocale] ?? {}; const label = draft.labels[activeLocale]; const name = data.name(saved); const retired = saved.status === "retired"; const mergedInto = saved.mergedInto ? data.byId.get(saved.mergedInto)?.term : undefined; const parent = saved.parentId ? data.byId.get(saved.parentId)?.term : undefined; const path = archivePath(tax, saved.slug); const usage = detail.data?.usage ?? { total: 0, published: 0 }; const published = archiveCounts(siblings, tax.hierarchical).get(saved.id) ?? usage.published; const status = indexStatus(draft, tax, published, defaultLocale); const redirects = detail.data?.redirects ?? []; const singular = data.label(tax, "singular"); /** Every save path checks the invariants first; an invalid term never leaves Studio. */ const valid = () => { if (!hasTermErrors(errors)) return true; setShowErrors(true); toast.error(t("seo.fixErrors")); const bad = Object.keys(errors.locales).find((l) => l !== activeLocale); if (bad && !errors.locales[activeLocale]) setLocale(bad); return false; }; const show = (e: unknown) => showErrors && e !== undefined; const nameError = show(localeErrors.name) ? localeErrors.name === "required" ? t("termEditor.errors.nameRequired") : t("termEditor.errors.nameTooLong") : undefined; const altError = localeErrors.altNames?.[0]; const open = (kind: GovernanceTarget["kind"]) => setGovernance({ kind, term: saved }); const details: DetailRow[] = [ { label: t("editor.id"), value: {saved.id} }, { label: t("termEditor.details.taxonomy"), value: {data.label(tax)} }, { label: t("termEditor.details.visibility"), value: }, { label: t("termEditor.details.usage"), value: ( {t("taxonomy.usage.value", { published: usage.published, total: usage.total })} ), }, ...(usage.lastUsedAt ? [ { label: t("taxonomy.columns.lastUsed"), value: , }, ] : []), { label: t("editor.revision"), value: {saved.rev} }, { label: t("editor.updatedAt"), value: }, ]; return ( } title={name} description={ {singular} {path} } actions={ retired ? ( ) : ( <> {saved.status === "proposed" && ( )} } aria-label={t("editor.moreActions")} data-testid="term-actions" disabled={structure.reason !== undefined} /> } /> } /> {saved.status === "proposed" ? ( <> open("reviewMerge")}> {t("taxonomy.menu.mergeExisting")} open("reject")}> {t("taxonomy.review.reject")} ) : ( <> open("rename")}> {t("taxonomy.menu.rename")} open("merge")}> {t("taxonomy.menu.merge")} {tax.hierarchical && ( open("move")}> {t("taxonomy.menu.move")} )} open("visibility")} > {saved.visibility === "public" ? t("taxonomy.menu.makeInternal") : t("taxonomy.menu.makePublic")} )} ) } > {!retired && } {retired && ( } title={ mergedInto ? t("termEditor.retired.merged", { name: data.name(mergedInto) }) : t("termEditor.retired.title") } description={t("termEditor.retired.description")} /> )} {data.locales.length > 1 && (
{t("termEditor.language")} ({ value: l, label: ( {l} {l === defaultLocale && ( {t("termEditor.default")} )} {errors.locales[l] && showErrors && !} ), }))} data-testid="term-locales" />
)} } main={ <> } description={t("termEditor.names.description")} > setDraft(editLabel(draft, activeLocale, { name: v }))} description={ activeLocale === defaultLocale ? t("termEditor.names.nameHintDefault") : t("termEditor.names.nameHint", { locale: defaultLocale }) } error={nameError} maxLength={TERM_LIMITS.nameMax} required={activeLocale === defaultLocale} disabled={retired} className="w-full" data-testid="term-name" /> setDraft( editLabel(draft, activeLocale, { ...(label ? {} : { name: "" }), altNames: values.length ? ([...new Set(values.map((v) => v.trim()).filter(Boolean))] as [ string, ...string[], ]) : undefined, }), ) } maxValues={TERM_LIMITS.altNamesMax} description={t("termEditor.names.altNamesHint")} error={ altError ? t(ALT_ERROR[altError.code], { value: altError.value, other: altError.other ?? "", }) : undefined } labels={{ removeValue: (v: string) => t("pickers.remove", { name: v }), maxValuesReached: (max: number) => t("pickers.atMost", { max }), }} disabled={retired} className="w-full" data-testid="term-altnames" /> } description={t("termEditor.intro.description", { path })} > setDraft(editLabel(draft, activeLocale, { description: v || undefined })) } description={ } error={ show(localeErrors.description) ? t("termEditor.errors.introTooLong") : undefined } autoResize minRows={4} maxRows={16} disabled={retired} className="w-full font-mono" data-testid="term-intro" /> { const { image: _i, ...rest } = draft; setDraft(image ? { ...rest, image } : rest); }} /> } description={t("termEditor.seo.description", { locale: activeLocale })} > setDraft(editLabel(draft, activeLocale, { seo }))} fallbackTitle={label?.name || name} path={path} siteName={data.site.data?.name ?? ""} host={host} errors={localeErrors.seo ?? {}} showErrors={showErrors} /> } aside={ <> } actions={} > {status.kind === "indexed" ? t("termEditor.indexing.indexed", { count: status.published, path }) : status.kind === "thin" ? t("termEditor.indexing.thin", { count: status.published, min: status.min, path, }) : status.kind === "empty" ? t("termEditor.indexing.empty", { path }) : status.kind === "noindex" ? t("termEditor.indexing.noindex", { path }) : t(`taxonomy.index.noneHint.${status.reason}`)} } > {tax.hierarchical && (
{t("governance.move.parent")} {parent ? data.name(parent) : t("governance.move.topLevel")} {!retired && ( )}
)} { const { position: _p, ...rest } = draft; setDraft(v === "" ? rest : { ...rest, position: Number(v) }); }} description={t("termEditor.placement.positionHint")} error={ show(errors.position) ? t("termEditor.errors.position", { max: TERM_LIMITS.positionMax }) : undefined } min={0} max={TERM_LIMITS.positionMax} required={false} disabled={retired} className="w-full" data-testid="term-position" />
} actions={ retired ? undefined : ( ) } flush={(saved.slugHistory?.length ?? 0) === 0} > {(saved.slugHistory?.length ?? 0) === 0 ? ( } title={t("termEditor.history.empty")} description={t("termEditor.history.emptyDescription", { path })} /> ) : (
{t("termEditor.history.description")}
{[...(saved.slugHistory ?? [])].reverse().map((old) => { const from = archivePath(tax, old); const r = redirects.find((x) => x.from === from); return (
{from} {r ? ( <> {r.to} {r.status} ) : ( {t("termEditor.history.reserved")} )}
); })}
)}
{!retired && saved.status === "active" && ( open("retire")} /> )} } />
!o && setGovernance(undefined)} onDone={() => void detail.refetch()} />
); }