dorfteich/apps/web/src/pages/TrashPage.tsx
Claude Fable 5 418aafd5ec
Some checks failed
CI / Lint, typecheck, test (pull_request) Successful in 4m43s
CI / Build container images (pull_request) Successful in 1m11s
CI / Auth e2e pack (pull_request) Successful in 7m14s
CI / Import/export fidelity gate (pull_request) Successful in 56s
CD / Deploy to Test (push) Blocked by required conditions
CD / Smoke tests against Test (push) Blocked by required conditions
CD / Promote to Int (push) Blocked by required conditions
CI / Auth e2e pack (push) Blocked by required conditions
CI / Import/export fidelity gate (push) Blocked by required conditions
CI / Build container images (push) Blocked by required conditions
CD / Build and push images (push) Has been cancelled
CI / Lint, typecheck, test (push) Has been cancelled
#163: Dokumentsprache und Seitentitel der SPA
i18n spiegelt die aktive Sprache auf <html lang> (Init + languageChanged;
der User-Locale-Wechsel in auth-context läuft über dasselbe Event). Neuer
useDocumentTitle-Hook setzt je Route einen sprechenden Titel
(Seite — Teich — Dorfteich), verdrahtet in allen Routen-Komponenten;
dynamische Titel folgen den geladenen Daten.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AGM8jo3hwoV9wsCVGfy8iq
2026-07-21 13:52:59 +02:00

191 lines
6.8 KiB
TypeScript

import type { PageView, PondView } from '@dorfteich/shared';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom';
import { FormError } from '../components/forms';
import { apiDelete, apiGet, apiPost } from '../lib/api';
import { useDocumentTitle } from '../lib/use-document-title';
/** Pond trash view (issue #31): list, restore, and permanently delete —
* single pages or a checkbox multi-selection at once (#128). */
export function TrashPage(): React.JSX.Element {
const { t } = useTranslation('editor');
const { pondSlug = '' } = useParams<{ pondSlug: string }>();
const queryClient = useQueryClient();
const [selected, setSelected] = useState<Set<string>>(new Set());
const [busy, setBusy] = useState(false);
const [failedCount, setFailedCount] = useState(0);
const pond = useQuery({
queryKey: ['pond', pondSlug],
queryFn: () => apiGet<PondView>(`/ponds/${pondSlug}`),
});
useDocumentTitle(pond.data ? t('trash.title', { pond: pond.data.name }) : undefined);
const trash = useQuery({
queryKey: ['trash', pond.data?.id],
queryFn: () => apiGet<PageView[]>(`/ponds/${pond.data!.id}/trash`),
enabled: Boolean(pond.data),
});
// Selection pruned to pages still in the trash — restored/purged entries
// drop out on refresh, failed ones stay selected for a retry.
const pages = trash.data ?? [];
const selectedIds = pages.filter((page) => selected.has(page.id)).map((page) => page.id);
const allSelected = pages.length > 0 && selectedIds.length === pages.length;
// Native indeterminate state for a partial selection — only settable via
// the DOM property, not an attribute.
const selectAllRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (selectAllRef.current) {
selectAllRef.current.indeterminate = selectedIds.length > 0 && !allSelected;
}
}, [selectedIds.length, allSelected]);
async function refresh(): Promise<void> {
await queryClient.invalidateQueries({ queryKey: ['trash', pond.data?.id] });
await queryClient.invalidateQueries({ queryKey: ['pages', pond.data?.id] });
}
function toggle(id: string): void {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}
function toggleAll(): void {
setSelected(allSelected ? new Set() : new Set(pages.map((page) => page.id)));
}
/** Run one action over the ids, keep going past failures (#128): a page
* that stopped being restorable must not strand the rest of the selection.
* Sequential on purpose — purge promotes leftover children (#107), so
* concurrent tree mutations would race each other. */
async function runBulk(ids: string[], action: (id: string) => Promise<unknown>): Promise<void> {
setBusy(true);
setFailedCount(0);
let failed = 0;
for (const id of ids) {
try {
await action(id);
setSelected((prev) => {
const next = new Set(prev);
next.delete(id);
return next;
});
} catch {
failed += 1;
}
}
setFailedCount(failed);
setBusy(false);
await refresh();
}
async function restore(id: string): Promise<void> {
await runBulk([id], (pageId) => apiPost(`/pages/${pageId}/restore`));
}
async function purge(id: string): Promise<void> {
if (!window.confirm(t('trash.purgeConfirm'))) return;
await runBulk([id], (pageId) => apiDelete(`/pages/${pageId}/purge`));
}
async function restoreSelected(): Promise<void> {
await runBulk(selectedIds, (pageId) => apiPost(`/pages/${pageId}/restore`));
}
async function purgeSelected(): Promise<void> {
if (!window.confirm(t('trash.purgeConfirmMany', { count: selectedIds.length }))) return;
await runBulk(selectedIds, (pageId) => apiDelete(`/pages/${pageId}/purge`));
}
if (pond.error || trash.error) return <FormError error={pond.error ?? trash.error} />;
if (!pond.data || !trash.data) return <></>;
return (
<div className="trash-page">
<h1>{t('trash.title', { pond: pond.data.name })}</h1>
{failedCount > 0 && (
<p className="trash-page__bulk-error" role="alert">
{t('trash.bulkFailed', { count: failedCount })}
</p>
)}
{pages.length === 0 ? (
<p>{t('trash.empty')}</p>
) : (
<>
<div className="trash-page__bulk">
<label className="trash-page__select-all">
<input
ref={selectAllRef}
type="checkbox"
checked={allSelected}
disabled={busy}
onChange={toggleAll}
/>
{t('trash.selectAll')}
</label>
<button
type="button"
className="button trash-page__restore-selected"
disabled={busy || selectedIds.length === 0}
onClick={() => void restoreSelected()}
>
{t('trash.restoreSelected', { count: selectedIds.length })}
</button>
<button
type="button"
className="button button--danger trash-page__purge-selected"
disabled={busy || selectedIds.length === 0}
onClick={() => void purgeSelected()}
>
{t('trash.purgeSelected', { count: selectedIds.length })}
</button>
</div>
<ul className="trash-page__list">
{pages.map((page) => (
<li key={page.id} className="trash-page__item">
<input
type="checkbox"
className="trash-page__select"
checked={selected.has(page.id)}
disabled={busy}
aria-label={t('trash.select', { title: page.title })}
onChange={() => toggle(page.id)}
/>
<span className="trash-page__title">{page.title}</span>
<span className="trash-page__deleted-at">
{page.deletedAt &&
t('trash.deletedAt', { date: new Date(page.deletedAt).toLocaleDateString() })}
</span>
<button
type="button"
className="button"
disabled={busy}
onClick={() => void restore(page.id)}
>
{t('trash.restore')}
</button>
<button
type="button"
className="button"
disabled={busy}
onClick={() => void purge(page.id)}
>
{t('trash.purge')}
</button>
</li>
))}
</ul>
</>
)}
</div>
);
}