From 0176b3184d56eda0db843654770e1cd4fd5acb43 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 2 Nov 2026 17:18:27 +0100 Subject: [PATCH] feat(app): administration screens and anatomical catalogue (V1-2.5 G, H, I) Administration page (board 10), species, rights, official sheets list with filters, creation from the core's empty document, overview with the working-copy action; catalogue list (search by sheet name), sheet and version pages through PreviewSheet with zoom and pan. App 650, typecheck, lint, build green. --- apps/app/src/admin/filters.ts | 46 + apps/app/src/admin/labels.ts | 128 +++ apps/app/src/admin/permissions.ts | 45 + apps/app/src/admin/useAdminQuery.ts | 61 ++ apps/app/src/admin/validation.ts | 256 +++++ apps/app/src/app/App.tsx | 3 + .../app/routes/app/admin/AdminAccessRoute.tsx | 61 +- .../app/routes/app/admin/AdminHomeRoute.tsx | 200 +++- .../app/admin/AdminSheetCreateRoute.tsx | 293 +++++- .../app/routes/app/admin/AdminSheetRoute.tsx | 341 ++++++- .../app/routes/app/admin/AdminSheetsRoute.tsx | 253 ++++- .../routes/app/admin/AdminSpeciesRoute.tsx | 217 ++++- .../app/routes/app/anatomy/CatalogRoute.tsx | 110 ++- .../src/app/routes/app/anatomy/SheetRoute.tsx | 207 ++++ apps/app/src/auth/navigationHint.ts | 4 +- apps/app/src/catalogue/catalogue.ts | 130 +++ apps/app/src/catalogue/failure.ts | 60 ++ apps/app/src/catalogue/framing.ts | 63 ++ apps/app/src/catalogue/preview.ts | 99 ++ apps/app/src/catalogue/useCardDetails.ts | 56 ++ apps/app/src/catalogue/useCatalogue.ts | 81 ++ apps/app/src/catalogue/useFraming.ts | 159 +++ apps/app/src/catalogue/useSheetVersion.ts | 91 ++ apps/app/src/catalogue/versionText.ts | 16 + .../admin/ActivateSpeciesDialog.tsx | 99 ++ apps/app/src/components/admin/GrantList.tsx | 203 ++++ apps/app/src/components/admin/GrantPanel.tsx | 319 ++++++ .../components/admin/RevokeGrantDialog.tsx | 125 +++ apps/app/src/components/admin/SheetBadges.tsx | 35 + .../src/components/admin/SpeciesDialog.tsx | 206 ++++ .../components/admin/WorkingCopyAction.tsx | 164 ++++ .../components/catalogue/CatalogueCanvas.tsx | 167 ++++ .../components/catalogue/CatalogueCard.tsx | 77 ++ .../catalogue/CatalogueFailureNotice.tsx | 38 + .../src/components/catalogue/SheetAside.tsx | 65 ++ .../src/components/catalogue/VersionLine.tsx | 81 ++ .../src/components/catalogue/ZonePanel.tsx | 131 +++ .../src/components/shell/PlaceholderPage.tsx | 16 - apps/app/src/i18n/en.ts | 260 +++++ apps/app/src/i18n/fr.ts | 260 +++++ apps/app/tests/unit/routes.admin.test.tsx | 916 ++++++++++++++++++ apps/app/tests/unit/routes.catalogue.test.tsx | 335 +++++++ 42 files changed, 6438 insertions(+), 39 deletions(-) create mode 100644 apps/app/src/admin/filters.ts create mode 100644 apps/app/src/admin/labels.ts create mode 100644 apps/app/src/admin/permissions.ts create mode 100644 apps/app/src/admin/useAdminQuery.ts create mode 100644 apps/app/src/admin/validation.ts create mode 100644 apps/app/src/app/routes/app/anatomy/SheetRoute.tsx create mode 100644 apps/app/src/catalogue/catalogue.ts create mode 100644 apps/app/src/catalogue/failure.ts create mode 100644 apps/app/src/catalogue/framing.ts create mode 100644 apps/app/src/catalogue/preview.ts create mode 100644 apps/app/src/catalogue/useCardDetails.ts create mode 100644 apps/app/src/catalogue/useCatalogue.ts create mode 100644 apps/app/src/catalogue/useFraming.ts create mode 100644 apps/app/src/catalogue/useSheetVersion.ts create mode 100644 apps/app/src/catalogue/versionText.ts create mode 100644 apps/app/src/components/admin/ActivateSpeciesDialog.tsx create mode 100644 apps/app/src/components/admin/GrantList.tsx create mode 100644 apps/app/src/components/admin/GrantPanel.tsx create mode 100644 apps/app/src/components/admin/RevokeGrantDialog.tsx create mode 100644 apps/app/src/components/admin/SheetBadges.tsx create mode 100644 apps/app/src/components/admin/SpeciesDialog.tsx create mode 100644 apps/app/src/components/admin/WorkingCopyAction.tsx create mode 100644 apps/app/src/components/catalogue/CatalogueCanvas.tsx create mode 100644 apps/app/src/components/catalogue/CatalogueCard.tsx create mode 100644 apps/app/src/components/catalogue/CatalogueFailureNotice.tsx create mode 100644 apps/app/src/components/catalogue/SheetAside.tsx create mode 100644 apps/app/src/components/catalogue/VersionLine.tsx create mode 100644 apps/app/src/components/catalogue/ZonePanel.tsx delete mode 100644 apps/app/src/components/shell/PlaceholderPage.tsx create mode 100644 apps/app/tests/unit/routes.admin.test.tsx create mode 100644 apps/app/tests/unit/routes.catalogue.test.tsx diff --git a/apps/app/src/admin/filters.ts b/apps/app/src/admin/filters.ts new file mode 100644 index 00000000..4a411b14 --- /dev/null +++ b/apps/app/src/admin/filters.ts @@ -0,0 +1,46 @@ +import type { OfficialSheetAdminSummary } from '@faunosteo/supabase' + +export interface SheetFilters { + species: string + sheetStatus: string + versionStatus: string + roundStatus: string +} + +export const NO_FILTER: SheetFilters = { + species: '', + sheetStatus: '', + versionStatus: '', + roundStatus: '', +} +export const SHEET_STATUSES = ['active', 'archived'] as const +export const VERSION_STATUSES = ['draft', 'published', 'deprecated'] as const +export const ROUND_STATUSES = [ + 'verifying', + 'open', + 'approved', + 'changes_requested', + 'withdrawn', + 'verification_failed', +] as const + +/** + * The filters of §11.1, over the loaded list: a version status matches a sheet + * holding a version in it, a round status matches its latest round. + */ +export function filterSheets( + sheets: readonly OfficialSheetAdminSummary[], + filters: SheetFilters, +): OfficialSheetAdminSummary[] { + return sheets.filter( + (sheet) => + (!filters.species || sheet.species_id === filters.species) && + (!filters.sheetStatus || sheet.status === filters.sheetStatus) && + (!filters.versionStatus || + sheet.version_statuses.some( + (status) => status === filters.versionStatus, + )) && + (!filters.roundStatus || + sheet.latest_round?.status === filters.roundStatus), + ) +} diff --git a/apps/app/src/admin/labels.ts b/apps/app/src/admin/labels.ts new file mode 100644 index 00000000..5e914af9 --- /dev/null +++ b/apps/app/src/admin/labels.ts @@ -0,0 +1,128 @@ +import type { + CatalogSpecies, + SheetAdminPerson, + SheetAdminRound, + SheetFailureKind, +} from '@faunosteo/supabase' +import type { Locale } from '@/i18n/types' + +type Translate = (key: string) => string + +/** + * The failure kinds the administration screens can meet (the RPCs they call, + * their helpers and the shared session kinds), each with an + * `admin.failure.` message. Any other kind cannot come from these + * calls; it reads as the generic `unavailable`, never as a raw code. + */ +const ADMIN_FAILURE_KINDS: ReadonlySet = + new Set([ + 'authentication_required', + 'mfa_required', + 'forbidden', + 'rights.account', + 'rights.capability', + 'rights.mfa', + 'rights.owner', + 'not_found', + 'grant.active', + 'grant.ineligible', + 'grant.revoked', + 'grant.target_invalid', + 'document.shape', + 'document.schema_version', + 'document.species', + 'document.too_large', + 'sheet.species_invalid', + 'sheet.slug_taken', + 'species.exists', + 'species.not_active', + 'species.not_inactive', + 'working_copy.source_invalid', + 'working_copy.exists', + 'working_copy.assets_missing', + 'invalid_input', + 'rate_limited', + 'conflict_retry', + 'session_expired', + 'network', + 'unavailable', + ]) + +export function failureMessage(t: Translate, kind: SheetFailureKind): string { + return t( + `admin.failure.${ADMIN_FAILURE_KINDS.has(kind) ? kind : 'unavailable'}`, + ) +} + +/** A sheet or species name in the interface language. */ +export function localized( + name: { fr: string; en: string }, + locale: Locale, +): string { + return name[locale] +} + +export function speciesName(species: CatalogSpecies, locale: Locale): string { + return locale === 'fr' ? species.name_fr : species.name_en +} + +/** The species' name when the list knows it, else its id (never an empty cell). */ +export function speciesLabel( + id: string, + species: readonly CatalogSpecies[], + locale: Locale, +): string { + const row = species.find((s) => s.id === id) + return row ? speciesName(row, locale) : id +} + +export function personName( + t: Translate, + person: SheetAdminPerson | null, +): string { + return person?.display_name || t('admin.person.unnamed') +} + +/** A server timestamp as a date in the interface language. */ +export function formatDay(iso: string, locale: Locale): string { + return new Date(iso).toLocaleDateString(locale, { + day: 'numeric', + month: 'long', + year: 'numeric', + }) +} + +/** + * The round's state (§3). A failed verification names its cause only when + * the server recorded one (`failure_outcome`, BDR-095): the title of that + * outcome and its ratified sentence; otherwise the generic status label. + */ +export function roundLabel( + t: Translate, + round: Pick & { + failure_outcome?: SheetAdminRound['failure_outcome'] + }, +): { title: string; cause: string | null } { + if (round.status === 'verification_failed' && round.failure_outcome) { + return { + title: t(`admin.outcome.${round.failure_outcome}.title`), + cause: t(`admin.outcome.${round.failure_outcome}.body`), + } + } + return { title: t(`admin.round_status.${round.status}`), cause: null } +} + +export const ROUND_TONE = { + verifying: 'neutral', + open: 'accent', + approved: 'accent', + changes_requested: 'warn', + withdrawn: 'neutral', + verification_failed: 'danger', +} as const + +export const VERSION_TONE = { + draft: 'neutral', + published: 'accent', + deprecated: 'warn', +} as const diff --git a/apps/app/src/admin/permissions.ts b/apps/app/src/admin/permissions.ts new file mode 100644 index 00000000..9a6a443b --- /dev/null +++ b/apps/app/src/admin/permissions.ts @@ -0,0 +1,45 @@ +import type { OwnCatalogGrant } from '@faunosteo/supabase' +import { isGrantActive } from '@/auth/navigationHint' +import { useAuthStore } from '@/state/authStore' + +export type Capability = 'sheet_editor' | 'sheet_reviewer' | 'sheet_publisher' + +/** In the order the administration page names them (board 10). */ +export const CAPABILITIES: readonly Capability[] = [ + 'sheet_editor', + 'sheet_reviewer', + 'sheet_publisher', +] + +export interface AdminPermissions { + /** The caller's active capabilities, in CAPABILITIES order. */ + capabilities: Capability[] + editor: boolean + owner: boolean +} + +/** + * Which administration entries and actions to show (contract §11.1, §5.4), + * from the caller's own grant rows and platform roles. A display rule only, + * like the navigation hint: every page and action acts on the server's + * answer (capability, `aal2`, owner checks), never on this. + */ +export function adminPermissions( + grants: readonly OwnCatalogGrant[], + owner: boolean, + now: number = Date.now(), +): AdminPermissions { + const active = new Set( + grants + .filter((grant) => isGrantActive(grant, now)) + .map((grant) => grant.kind), + ) + const capabilities = CAPABILITIES.filter((kind) => active.has(kind)) + return { capabilities, editor: active.has('sheet_editor'), owner } +} + +export function useAdminPermissions(): AdminPermissions { + const grants = useAuthStore((s) => s.catalogGrants) + const owner = useAuthStore((s) => s.roles.includes('owner')) + return adminPermissions(grants, owner) +} diff --git a/apps/app/src/admin/useAdminQuery.ts b/apps/app/src/admin/useAdminQuery.ts new file mode 100644 index 00000000..909113f1 --- /dev/null +++ b/apps/app/src/admin/useAdminQuery.ts @@ -0,0 +1,61 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { + classifySheetError, + type FaunosteoClient, + type SheetFailureKind, +} from '@faunosteo/supabase' +import { getSupabaseClient } from '@/lib/supabase' + +export type AdminQueryState = + | { status: 'loading' } + | { status: 'ready'; data: T } + | { status: 'error'; failure: SheetFailureKind } + +/** + * One administration read (M7, species, grants), keyed: a new key shows the + * loading state, a refresh of the same key keeps the data on screen until the + * new answer. Every refusal arrives as its closed kind; the page decides what + * a `rights.*` or `not_found` answer shows. + */ +export function useAdminQuery( + key: string, + load: (client: FaunosteoClient) => Promise, +) { + const [state, setState] = useState>({ status: 'loading' }) + const [reload, setReload] = useState(0) + const shownKey = useRef(null) + // The latest loader, so an inline arrow does not restart the request. + const loader = useRef(load) + loader.current = load + + useEffect(() => { + let live = true + const client = getSupabaseClient() + if (shownKey.current !== key) setState({ status: 'loading' }) + shownKey.current = key + if (!client) { + setState({ status: 'error', failure: 'unavailable' }) + return + } + loader + .current(client) + .then((data) => { + if (live) setState({ status: 'ready', data }) + }) + .catch((error: unknown) => { + if (live) + setState({ status: 'error', failure: classifySheetError(error) }) + }) + return () => { + live = false + } + }, [key, reload]) + + const refresh = useCallback(() => setReload((n) => n + 1), []) + return { state, refresh } +} + +/** A refusal of the caller's rights: the page answers « Accès non autorisé ». */ +export function isRightsRefusal(kind: SheetFailureKind): boolean { + return kind.startsWith('rights.') +} diff --git a/apps/app/src/admin/validation.ts b/apps/app/src/admin/validation.ts new file mode 100644 index 00000000..75a5cedf --- /dev/null +++ b/apps/app/src/admin/validation.ts @@ -0,0 +1,256 @@ +import { z } from 'zod' +import { codePointLength } from '@faunosteo/supabase' +import { localDateIso } from '@/lib/dates' + +/** + * The administration forms (contract §5.2, §7.2, §7.4). Bounds and patterns + * are the SQL CHECKs and RPC guards, so a form never sends what the server + * refuses; the server still decides. Messages are i18n keys; `|n` carries + * the {max} placeholder. Lengths count code points, like char_length. + */ + +/** `species_id_format`, and `other` is never a catalogue species (create_species). */ +export const SPECIES_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/ +/** `anatomical_sheets_slug_format`. */ +export const SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{1,79}$/ +const SPECIES_NAME_MAX = 80 +/** `anatomical_sheets_name_length`. */ +const SHEET_NAME_MAX = 120 +/** reason, verification note and revocation reason (grant_catalog_right, revoke_catalog_right). */ +export const GRANT_TEXT_MAX = 1000 + +export type FieldErrors = Partial> + +function requiredText(max: number) { + return z + .string() + .trim() + .superRefine((value, ctx) => { + if (value === '') + ctx.addIssue({ code: 'custom', message: 'clients.error.required' }) + else if (codePointLength(value) > max) + ctx.addIssue({ + code: 'custom', + message: `clients.error.too_long|${max}`, + }) + }) +} + +/** The first message of each field. */ +function fieldErrors(error: z.ZodError): FieldErrors { + const errors: FieldErrors = {} + for (const issue of error.issues) { + const key = issue.path[0] as K + errors[key] ??= issue.message + } + return errors +} + +export type Parsed = + | { ok: true; value: T } + | { ok: false; errors: FieldErrors } + +function parse( + schema: z.ZodType, + values: unknown, +): Parsed { + const result = schema.safeParse(values) + return result.success + ? { ok: true, value: result.data } + : { ok: false, errors: fieldErrors(result.error) } +} + +// --- Species ---------------------------------------------------------------- +export interface SpeciesFormValues { + id: string + name_fr: string + name_en: string + sort_order: string +} + +const speciesSchema = z.object({ + id: z + .string() + .trim() + .refine( + (id) => SPECIES_ID_PATTERN.test(id) && id !== 'other', + 'admin.species.error.id', + ), + name_fr: requiredText(SPECIES_NAME_MAX), + name_en: requiredText(SPECIES_NAME_MAX), + sort_order: z + .string() + .trim() + .refine((order) => /^[0-9]{1,4}$/.test(order), 'admin.species.error.order') + .transform(Number), +}) + +export type SpeciesFields = z.infer + +export function parseSpecies( + values: SpeciesFormValues, +): Parsed { + return parse(speciesSchema, values) +} + +// --- Official sheet --------------------------------------------------------- +export interface SheetFormValues { + species_id: string + name_fr: string + name_en: string + slug: string +} + +const sheetSchema = z.object({ + species_id: z + .string() + .refine( + (id) => id !== '' && id !== 'other', + 'admin.sheet_form.error.species', + ), + name_fr: requiredText(SHEET_NAME_MAX), + name_en: requiredText(SHEET_NAME_MAX), + slug: z + .string() + .trim() + .refine((slug) => SLUG_PATTERN.test(slug), 'admin.sheet_form.error.slug'), +}) + +export type SheetFields = z.infer + +export function parseSheet( + values: SheetFormValues, +): Parsed { + return parse(sheetSchema, values) +} + +/** + * A slug proposed from a name: accents dropped, lower case, every other run + * of characters a single hyphen, cut to the 80 characters of the CHECK. The + * editor may change it; the CHECK is checked again on submit. + */ +export function proposeSlug(name: string): string { + return name + .normalize('NFD') + .replace(/[̀-ͯ]/g, '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+/, '') + .slice(0, 80) + .replace(/-+$/, '') +} + +// --- Rights ----------------------------------------------------------------- +export type GrantKind = + | 'catalog_reader' + | 'sheet_editor' + | 'sheet_reviewer' + | 'sheet_publisher' + +export const GRANT_KINDS: readonly GrantKind[] = [ + 'catalog_reader', + 'sheet_editor', + 'sheet_reviewer', + 'sheet_publisher', +] + +/** The three capabilities: a verification note is required for them. */ +const CAPABILITY_KINDS: readonly GrantKind[] = [ + 'sheet_editor', + 'sheet_reviewer', + 'sheet_publisher', +] + +export interface GrantFormValues { + kind: GrantKind | '' + reason: string + verification_note: string + /** YYYY-MM-DD or ''. */ + expires_on: string +} + +export interface GrantFields { + kind: GrantKind + reason: string + verification_note?: string + /** The end of the chosen day, device time zone. */ + expires_at?: string +} + +/** The expiry is a day after today (device date): the server refuses a past one. */ +function grantSchema(today: string) { + return z + .object({ + kind: z + .enum([ + '', + 'catalog_reader', + 'sheet_editor', + 'sheet_reviewer', + 'sheet_publisher', + ]) + .refine((kind) => kind !== '', 'admin.access.error.kind'), + reason: requiredText(GRANT_TEXT_MAX), + verification_note: z.string().trim(), + expires_on: z + .string() + .refine( + (day) => + day === '' || (/^\d{4}-\d{2}-\d{2}$/.test(day) && day > today), + 'admin.access.error.expiry', + ), + }) + .superRefine((values, ctx) => { + const note = values.verification_note + // Required for the three capabilities (§5.2), refused past 1 000 for every kind. + if ( + note === '' && + (CAPABILITY_KINDS as readonly string[]).includes(values.kind) + ) + ctx.addIssue({ + code: 'custom', + path: ['verification_note'], + message: 'clients.error.required', + }) + else if (codePointLength(note) > GRANT_TEXT_MAX) + ctx.addIssue({ + code: 'custom', + path: ['verification_note'], + message: `clients.error.too_long|${GRANT_TEXT_MAX}`, + }) + }) + .transform( + (values): GrantFields => ({ + kind: values.kind as GrantKind, + reason: values.reason, + ...(values.verification_note + ? { verification_note: values.verification_note } + : {}), + ...(values.expires_on + ? { + expires_at: new Date( + `${values.expires_on}T23:59:59`, + ).toISOString(), + } + : {}), + }), + ) +} + +export function parseGrant( + values: GrantFormValues, + today: string = localDateIso(), +): Parsed { + return parse(grantSchema(today), values) +} + +export function parseRevocation(reason: string): Parsed { + return parse( + z + .object({ reason: requiredText(GRANT_TEXT_MAX) }) + .transform((v) => v.reason), + { + reason, + }, + ) +} diff --git a/apps/app/src/app/App.tsx b/apps/app/src/app/App.tsx index 8a6df79a..b19a621c 100644 --- a/apps/app/src/app/App.tsx +++ b/apps/app/src/app/App.tsx @@ -28,6 +28,7 @@ import AnimalEditRoute from './routes/app/animals/AnimalEditRoute' import RequireCatalog from './guards/RequireCatalog' import RequireAdmin from './guards/RequireAdmin' import CatalogRoute from './routes/app/anatomy/CatalogRoute' +import SheetRoute from './routes/app/anatomy/SheetRoute' import AdminHomeRoute from './routes/app/admin/AdminHomeRoute' import AdminSheetsRoute from './routes/app/admin/AdminSheetsRoute' import AdminSheetCreateRoute from './routes/app/admin/AdminSheetCreateRoute' @@ -86,6 +87,8 @@ export function AppRoutes() { {/* V1-2 (§11.1): the server decides every read; these gates never use the nav hint. */} }> } /> + } /> + } /> }> } /> diff --git a/apps/app/src/app/routes/app/admin/AdminAccessRoute.tsx b/apps/app/src/app/routes/app/admin/AdminAccessRoute.tsx index e9dd96fd..83f0618e 100644 --- a/apps/app/src/app/routes/app/admin/AdminAccessRoute.tsx +++ b/apps/app/src/app/routes/app/admin/AdminAccessRoute.tsx @@ -1,6 +1,61 @@ -import PlaceholderPage from '@/components/shell/PlaceholderPage' +import { listCatalogGrants } from '@faunosteo/supabase' +import GrantList from '@/components/admin/GrantList' +import GrantPanel from '@/components/admin/GrantPanel' +import AccessDenied from '@/components/shell/AccessDenied' +import Button from '@/components/ui/Button' +import Notice from '@/components/ui/Notice' +import { failureMessage } from '@/admin/labels' +import { isRightsRefusal, useAdminQuery } from '@/admin/useAdminQuery' +import { usePageHeading } from '@/app/usePageHeading' +import { useT } from '@/i18n/useT' -/** V1-2.5 placeholder (slice E): the rights screen (owner), built by slice G. */ +/** + * /app/admin/access (owner, §5.2, A0): grant a right to an account found by + * e-mail, list and revoke grants. Rendered only at `aal2` (RequireAdmin); + * the list is the server's answer, so an account that is not the owner sees + * « Accès non autorisé » on its `rights.owner` refusal, never the form. + */ export default function AdminAccessRoute() { - return + const t = useT() + const heading = usePageHeading() + const { state, refresh } = useAdminQuery('grants', listCatalogGrants) + + if (state.status === 'error' && isRightsRefusal(state.failure)) + return + + return ( +
+
+

+ {t('admin.access.title')} +

+

+ {t('admin.access.lede')} +

+
+ {state.status === 'loading' && ( +

+ {t('admin.access.loading')} +

+ )} + {state.status === 'error' && ( +
+ {failureMessage(t, state.failure)} + +
+ )} + {state.status === 'ready' && ( + <> + + + + )} +
+ ) } diff --git a/apps/app/src/app/routes/app/admin/AdminHomeRoute.tsx b/apps/app/src/app/routes/app/admin/AdminHomeRoute.tsx index 7f2c4c63..8df67af1 100644 --- a/apps/app/src/app/routes/app/admin/AdminHomeRoute.tsx +++ b/apps/app/src/app/routes/app/admin/AdminHomeRoute.tsx @@ -1,6 +1,200 @@ -import PlaceholderPage from '@/components/shell/PlaceholderPage' +import { Link } from 'react-router-dom' +import { + listOfficialSheetsAdmin, + type OfficialSheetAdminSummary, +} from '@faunosteo/supabase' +import SheetBadges from '@/components/admin/SheetBadges' +import WorkingCopyAction from '@/components/admin/WorkingCopyAction' +import Button from '@/components/ui/Button' +import ButtonLink from '@/components/ui/ButtonLink' +import Card from '@/components/ui/Card' +import Notice from '@/components/ui/Notice' +import { failureMessage, localized } from '@/admin/labels' +import { useAdminPermissions, type AdminPermissions } from '@/admin/permissions' +import { isRightsRefusal, useAdminQuery } from '@/admin/useAdminQuery' +import { usePageHeading } from '@/app/usePageHeading' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' -/** V1-2.5 placeholder (slice E): the administration page (board 10), built by slice G. */ +type Translate = ReturnType + +/** At most this many sheets on the card; the full list is one link away. */ +const CARD_SHEETS = 5 + +const LINK = + 'inline-flex min-h-11 items-center text-sm font-medium text-[var(--color-accent-strong)] underline underline-offset-2' + +/** « Vos habilitations : … · rôle propriétaire · session renforcée … active. » (board 10). */ +function permissionsLine(t: Translate, permissions: AdminPermissions): string { + const list = permissions.capabilities.map((kind) => + t(`admin.home.capability.${kind}`), + ) + const parts = [ + t('admin.home.permissions').replace( + '{list}', + list.join(', ') || t('admin.home.permissions_none'), + ), + ...(permissions.owner ? [t('admin.home.owner_role')] : []), + t('admin.home.session'), + ] + return `${parts.join(' · ')}.` +} + +function SheetItem({ + sheet, + editor, +}: { + sheet: OfficialSheetAdminSummary + editor: boolean +}) { + const locale = useLocaleStore((s) => s.locale) + return ( +
  • +
    + + {localized(sheet.name, locale)} + + +
    + {/* The working copy action (W1): editors only, on the historical sheet. */} + {sheet.historical && editor && ( + + )} +
  • + ) +} + +function SheetsCard({ editor }: { editor: boolean }) { + const t = useT() + const { state, refresh } = useAdminQuery( + 'admin-sheets', + listOfficialSheetsAdmin, + ) + // Without a capability the server refuses the list: the card is not this account's. + if (state.status === 'error' && isRightsRefusal(state.failure)) return null + const shown = state.status === 'ready' ? state.data.slice(0, CARD_SHEETS) : [] + return ( + +

    + {t('admin.sheets.title')} +

    +

    + {t('admin.home.sheets_body')} +

    + {state.status === 'loading' && ( +

    + {t('admin.sheets.loading')} +

    + )} + {state.status === 'error' && ( +
    + {failureMessage(t, state.failure)} + +
    + )} + {state.status === 'ready' && state.data.length === 0 && ( +

    + {t('admin.sheets.empty')} +

    + )} + {shown.length > 0 && ( +
      + {shown.map((sheet) => ( + + ))} +
    + )} + {state.status === 'ready' && ( + + {t('admin.home.all_sheets')} + + )} +
    + ) +} + +function EntryCard({ + id, + title, + body, + to, +}: { + id: string + title: string + body: string + to: string +}) { + const t = useT() + return ( + +

    + {title} +

    +

    {body}

    + + {t('admin.home.open')} + +
    + ) +} + +/** + * /app/admin (board 10, §11.1): the caller's permissions and session, then + * one card per area it may use. The sheets card shows only when the server + * answers the list; « Accès et habilitations » only to the owner role. Every + * page behind a card checks again on the server. + */ export default function AdminHomeRoute() { - return + const t = useT() + const heading = usePageHeading() + const permissions = useAdminPermissions() + return ( +
    +
    +

    + {t('shell.nav.admin')} +

    +

    + {permissionsLine(t, permissions)} +

    +
    +
    + + + {permissions.owner && ( + + )} +
    +
    + ) } diff --git a/apps/app/src/app/routes/app/admin/AdminSheetCreateRoute.tsx b/apps/app/src/app/routes/app/admin/AdminSheetCreateRoute.tsx index 8786c688..fbba95f8 100644 --- a/apps/app/src/app/routes/app/admin/AdminSheetCreateRoute.tsx +++ b/apps/app/src/app/routes/app/admin/AdminSheetCreateRoute.tsx @@ -1,6 +1,293 @@ -import PlaceholderPage from '@/components/shell/PlaceholderPage' +import { useEffect, useState, type FormEvent } from 'react' +import { Link, useNavigate } from 'react-router-dom' +import { + classifySheetError, + createOfficialSheet, + listCatalogSpecies, + type Json, + type SheetFailureKind, +} from '@faunosteo/supabase' +import SpeciesDialog, { + type SpeciesDialogMode, +} from '@/components/admin/SpeciesDialog' +import AccessDenied from '@/components/shell/AccessDenied' +import Button, { buttonClassName } from '@/components/ui/Button' +import Card from '@/components/ui/Card' +import FormField, { fieldDescribedBy } from '@/components/ui/FormField' +import Input from '@/components/ui/Input' +import Notice from '@/components/ui/Notice' +import Select from '@/components/ui/Select' +import { failureMessage, speciesName } from '@/admin/labels' +import { isRightsRefusal, useAdminQuery } from '@/admin/useAdminQuery' +import { + parseSheet, + proposeSlug, + type FieldErrors, + type SheetFields, + type SheetFormValues, +} from '@/admin/validation' +import { translateFieldError } from '@/account/validation' +import { usePageHeading } from '@/app/usePageHeading' +import { coreFailureMessage } from '@/core/failure' +import { coreRuntime } from '@/core/runtime' +import { emptySheetDocument } from '@/core/sheetDocumentOps' +import { getSupabaseClient } from '@/lib/supabase' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' -/** V1-2.5 placeholder (slice E): the sheet creation form, built by slice H. */ +const EMPTY: SheetFormValues = { + species_id: '', + name_fr: '', + name_en: '', + slug: '', +} +const FIELD_ORDER: (keyof SheetFormValues)[] = [ + 'species_id', + 'name_fr', + 'name_en', + 'slug', +] +const fieldId = (key: keyof SheetFormValues) => `sheet-${key.replace('_', '-')}` + +type Outcome = + | { kind: 'failure'; failure: SheetFailureKind } + | { kind: 'core_unavailable' } + | null + +/** + * The core's empty document (§7.4), then `create_official_sheet`. A core that + * does not load is its own outcome: the notice of the sheet pages, the + * editor submits again once it is back. + */ +async function createSheet( + fields: SheetFields, +): Promise<{ id: string } | Exclude> { + const client = getSupabaseClient() + if (!client) return { kind: 'failure', failure: 'unavailable' } + if (!(await coreRuntime().ready())) return { kind: 'core_unavailable' } + const document = emptySheetDocument({ + speciesId: fields.species_id, + name: { fr: fields.name_fr, en: fields.name_en }, + }) + if (!document.ok) { + return document.kind === 'core_unavailable' + ? { kind: 'core_unavailable' } + : { kind: 'failure', failure: 'invalid_input' } + } + try { + return { + id: await createOfficialSheet( + client, + fields.slug, + document.value as unknown as Json, + ), + } + } catch (error) { + return { kind: 'failure', failure: classifySheetError(error) } + } +} + +/** /app/admin/sheets/new (A1, editor): species, names, slug; the new sheet's overview opens. */ export default function AdminSheetCreateRoute() { - return + const t = useT() + const heading = usePageHeading() + const navigate = useNavigate() + const locale = useLocaleStore((s) => s.locale) + const species = useAdminQuery('species', listCatalogSpecies) + const [values, setValues] = useState(EMPTY) + const [slugEdited, setSlugEdited] = useState(false) + const [errors, setErrors] = useState>({}) + const [errorRound, setErrorRound] = useState(0) + const [outcome, setOutcome] = useState(null) + const [pending, setPending] = useState(false) + const [dialog, setDialog] = useState(null) + + useEffect(() => { + if (errorRound === 0) return + const first = FIELD_ORDER.find((key) => errors[key]) + if (first) document.getElementById(fieldId(first))?.focus() + }, [errorRound, errors]) + + if ( + species.state.status === 'error' && + isRightsRefusal(species.state.failure) + ) + return + + const set = (key: keyof SheetFormValues) => (value: string) => + setValues((v) => { + const next = { ...v, [key]: value } + // The slug follows the French name until the editor types one. + if (key === 'name_fr' && !slugEdited) next.slug = proposeSlug(value) + return next + }) + + async function submit(event: FormEvent) { + event.preventDefault() + if (pending) return + const parsed = parseSheet(values) + if (!parsed.ok) { + setErrors(parsed.errors) + setErrorRound((n) => n + 1) + return + } + setErrors({}) + setOutcome(null) + setPending(true) + const result = await createSheet(parsed.value) + setPending(false) + if ('id' in result) + navigate(`/app/admin/sheets/${result.id}`, { replace: true }) + else setOutcome(result) + } + + const speciesSaved = (id: string) => { + setDialog(null) + set('species_id')(id) + species.refresh() + } + const err = (key: keyof SheetFormValues) => + translateFieldError(t, errors[key]) + const describedBy = (key: keyof SheetFormValues, hint?: string) => + fieldDescribedBy(fieldId(key), hint, errors[key]) + const rows = + species.state.status === 'ready' + ? species.state.data.filter((s) => s.id !== 'other') + : [] + const textField = (key: 'name_fr' | 'name_en', label: string) => ( + + set(key)(e.target.value)} + maxLength={120} + aria-invalid={Boolean(errors[key])} + aria-describedby={describedBy(key)} + /> + + ) + + return ( +
    +

    + {t('admin.sheets.new')} +

    + +
    void submit(e)} noValidate className="space-y-5"> +

    + {t('admin.sheet_form.lede')} +

    +
    + + + + {species.state.status === 'loading' && ( +

    + {t('admin.species.loading')} +

    + )} + {species.state.status === 'error' && ( + + {failureMessage(t, species.state.failure)} + + )} + +
    + {textField('name_fr', t('admin.sheet_form.name_fr'))} + {textField('name_en', t('admin.sheet_form.name_en'))} + + { + setSlugEdited(true) + set('slug')(e.target.value) + }} + maxLength={80} + spellCheck={false} + autoComplete="off" + aria-invalid={Boolean(errors.slug)} + aria-describedby={describedBy( + 'slug', + t('admin.sheet_form.slug_hint'), + )} + /> + + + {outcome?.kind === 'core_unavailable' && ( + + {coreFailureMessage(t, 'sheet.core_unavailable')} + + )} + {outcome?.kind === 'failure' && ( + {failureMessage(t, outcome.failure)} + )} + +
    + + {t('common.cancel')} + + +
    +
    +
    + setDialog(null)} + onSaved={speciesSaved} + /> +
    + ) } diff --git a/apps/app/src/app/routes/app/admin/AdminSheetRoute.tsx b/apps/app/src/app/routes/app/admin/AdminSheetRoute.tsx index 2c3673ed..a3b6f3e9 100644 --- a/apps/app/src/app/routes/app/admin/AdminSheetRoute.tsx +++ b/apps/app/src/app/routes/app/admin/AdminSheetRoute.tsx @@ -1,6 +1,341 @@ -import PlaceholderPage from '@/components/shell/PlaceholderPage' +import type { ReactNode } from 'react' +import { useParams } from 'react-router-dom' +import { + getOfficialSheetAdmin, + listCatalogSpecies, + type FaunosteoClient, + type SheetAdminRound, + type SheetAdminVersion, +} from '@faunosteo/supabase' +import SheetBadges from '@/components/admin/SheetBadges' +import WorkingCopyAction from '@/components/admin/WorkingCopyAction' +import AccessDenied from '@/components/shell/AccessDenied' +import Badge from '@/components/ui/Badge' +import Button from '@/components/ui/Button' +import ButtonLink from '@/components/ui/ButtonLink' +import Card from '@/components/ui/Card' +import Notice from '@/components/ui/Notice' +import { + ROUND_TONE, + VERSION_TONE, + failureMessage, + formatDay, + localized, + personName, + roundLabel, + speciesLabel, +} from '@/admin/labels' +import { useAdminPermissions } from '@/admin/permissions' +import { isRightsRefusal, useAdminQuery } from '@/admin/useAdminQuery' +import { usePageHeading } from '@/app/usePageHeading' +import type { Locale } from '@/i18n/types' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' -/** V1-2.5 placeholder (slice E): the sheet overview (versions, rounds, working copy), built by slice H. */ +type Translate = ReturnType + +/** The overview and the species names (both capability reads at aal2). */ +async function loadSheet(client: FaunosteoClient, sheetId: string) { + const [sheet, species] = await Promise.all([ + getOfficialSheetAdmin(client, sheetId), + listCatalogSpecies(client), + ]) + return { sheet, species } +} + +/** A dated line, with the account that acted when the row names one; null without a date. */ +function stamp( + t: Translate, + locale: Locale, + key: string, + at: string | null, + by?: string, +): string | null { + if (!at) return null + const line = by ? t(`${key}_by`).replace('{name}', by) : t(key) + return line.replace('{date}', formatDay(at, locale)) +} + +function VersionItem({ + version, + t, + locale, +}: { + version: SheetAdminVersion + t: Translate + locale: Locale +}) { + const authors = version.authors + .map((author) => personName(t, author)) + .join(', ') + const lines = [ + stamp(t, locale, 'admin.overview.created_on', version.created_at), + stamp(t, locale, 'admin.overview.published_on', version.published_at), + stamp(t, locale, 'admin.overview.deprecated_on', version.deprecated_at), + version.source_version_number !== null + ? t('admin.overview.source').replace( + '{number}', + String(version.source_version_number), + ) + : null, + authors ? t('admin.overview.authors').replace('{names}', authors) : null, + ].filter(Boolean) + return ( +
  • +

    + + {t('admin.overview.version').replace( + '{number}', + String(version.version_number), + )} + + + {t(`admin.version_status.${version.status}`)} + + + {t('admin.overview.revision').replace( + '{revision}', + String(version.revision), + )} + +

    + {version.change_note && ( +

    {version.change_note}

    + )} +

    + {lines.join(' · ')} +

    +
  • + ) +} + +function RoundItem({ + round, + t, + locale, +}: { + round: SheetAdminRound + t: Translate + locale: Locale +}) { + const label = roundLabel(t, round) + const lines = [ + stamp( + t, + locale, + 'admin.overview.submitted_on', + round.submitted_at, + round.submitted_by ? personName(t, round.submitted_by) : undefined, + ), + stamp( + t, + locale, + 'admin.overview.decided_on', + round.decided_at, + round.decided_by ? personName(t, round.decided_by) : undefined, + ), + stamp(t, locale, 'admin.overview.withdrawn_on', round.withdrawn_at), + ].filter(Boolean) + return ( +
  • +

    + + {t('admin.overview.round').replace('{round}', String(round.round))} + + {label.title} + + {t('admin.overview.version').replace( + '{number}', + String(round.version_number), + )} + +

    + {label.cause && ( +

    {label.cause}

    + )} + {lines.length > 0 && ( +

    + {lines.join(' · ')} +

    + )} +
  • + ) +} + +function Section({ + id, + title, + empty, + children, +}: { + id: string + title: string + empty: string | null + children: ReactNode +}) { + return ( +
    +

    + {title} +

    + {empty ? ( +

    {empty}

    + ) : ( +
      + {children} +
    + )} +
    + ) +} + +/** One answer for an unknown id and a sheet this account may not see (M7 `not_found`). */ +function SheetNotFound() { + const t = useT() + const heading = usePageHeading() + return ( + +

    + {t('admin.overview.not_found_title')} +

    +

    + {t('admin.overview.not_found_body')} +

    + + {t('admin.overview.back')} + +
    + ) +} + +/** + * /app/admin/sheets/:sheetId (§11.1): the sheet, its versions and rounds. + * « Créer une copie de travail » on the historical sheet for editors (W1); + * « Voir dans le catalogue » once a version is published. The editor link + * arrives with V1-2.6, deprecation and archive with V1-2.7. + */ export default function AdminSheetRoute() { - return + const { sheetId = '' } = useParams() + const t = useT() + const heading = usePageHeading() + const locale = useLocaleStore((s) => s.locale) + const { editor } = useAdminPermissions() + const { state, refresh } = useAdminQuery(`sheet:${sheetId}`, (client) => + loadSheet(client, sheetId), + ) + + if (state.status === 'error' && state.failure === 'not_found') + return + if (state.status === 'error' && isRightsRefusal(state.failure)) + return + if (state.status === 'loading') { + return ( +

    + {t('admin.overview.loading')} +

    + ) + } + if (state.status === 'error') { + return ( +
    + {failureMessage(t, state.failure)} + +
    + ) + } + + const { sheet, species } = state.data + const facts = [ + speciesLabel(sheet.species_id, species, locale), + t(`admin.sheet_status.${sheet.status}`), + sheet.current_version + ? t('admin.sheets.current_version').replace( + '{number}', + String(sheet.current_version.version_number), + ) + : t('admin.sheets.no_published'), + ...(sheet.working_copy_source + ? [ + t('admin.overview.copy_of').replace( + '{number}', + String(sheet.working_copy_source.version_number), + ), + ] + : []), + ] + + return ( +
    +
    +

    + {localized(sheet.name, locale)} +

    +

    + +

    +

    + {facts.join(' · ')} +

    +
    + {sheet.historical && editor && ( + + )} + {sheet.current_version && ( + + {t('admin.overview.to_catalogue')} + + )} +
    +
    + +
    + {sheet.versions.map((version) => ( + + ))} +
    +
    + {sheet.rounds.map((round) => ( + + ))} +
    +
    + ) } diff --git a/apps/app/src/app/routes/app/admin/AdminSheetsRoute.tsx b/apps/app/src/app/routes/app/admin/AdminSheetsRoute.tsx index b0cb6ff8..6ec5477c 100644 --- a/apps/app/src/app/routes/app/admin/AdminSheetsRoute.tsx +++ b/apps/app/src/app/routes/app/admin/AdminSheetsRoute.tsx @@ -1,6 +1,253 @@ -import PlaceholderPage from '@/components/shell/PlaceholderPage' +import { useState } from 'react' +import { Link } from 'react-router-dom' +import { + listCatalogSpecies, + listOfficialSheetsAdmin, + type CatalogSpecies, + type FaunosteoClient, + type OfficialSheetAdminSummary, +} from '@faunosteo/supabase' +import SheetBadges from '@/components/admin/SheetBadges' +import AccessDenied from '@/components/shell/AccessDenied' +import Button from '@/components/ui/Button' +import ButtonLink from '@/components/ui/ButtonLink' +import FormField from '@/components/ui/FormField' +import Notice from '@/components/ui/Notice' +import Select from '@/components/ui/Select' +import { + failureMessage, + localized, + roundLabel, + speciesLabel, +} from '@/admin/labels' +import { + NO_FILTER, + ROUND_STATUSES, + SHEET_STATUSES, + VERSION_STATUSES, + filterSheets, + type SheetFilters, +} from '@/admin/filters' +import { useAdminPermissions } from '@/admin/permissions' +import { isRightsRefusal, useAdminQuery } from '@/admin/useAdminQuery' +import { usePageHeading } from '@/app/usePageHeading' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' -/** V1-2.5 placeholder (slice E): the official sheets list with its filters, built by slice H. */ +type Translate = ReturnType + +/** The list and the species names, in one read: both are capability reads at aal2. */ +async function loadSheets(client: FaunosteoClient) { + const [sheets, species] = await Promise.all([ + listOfficialSheetsAdmin(client), + listCatalogSpecies(client), + ]) + return { sheets, species } +} + +function details(t: Translate, sheet: OfficialSheetAdminSummary): string[] { + return [ + t(`admin.sheet_status.${sheet.status}`), + sheet.current_version + ? t('admin.sheets.current_version').replace( + '{number}', + String(sheet.current_version.version_number), + ) + : t('admin.sheets.no_published'), + ...(sheet.draft_version + ? [ + t('admin.sheets.draft').replace( + '{number}', + String(sheet.draft_version.version_number), + ), + ] + : []), + ...(sheet.latest_round + ? [ + t('admin.sheets.latest_round') + .replace('{round}', String(sheet.latest_round.round)) + .replace('{status}', roundLabel(t, sheet.latest_round).title), + ] + : []), + ] +} + +function SheetRow({ + sheet, + species, + t, +}: { + sheet: OfficialSheetAdminSummary + species: CatalogSpecies[] + t: Translate +}) { + const locale = useLocaleStore((s) => s.locale) + return ( +
  • + + + + {localized(sheet.name, locale)} + + + + + {[ + speciesLabel(sheet.species_id, species, locale), + ...details(t, sheet), + ].join(' · ')} + + +
  • + ) +} + +interface FilterProps { + id: keyof SheetFilters + label: string + value: string + options: readonly { value: string; label: string }[] + onChange: (value: string) => void +} + +function Filter({ id, label, value, options, onChange }: FilterProps) { + const t = useT() + return ( + + + + ) +} + +/** /app/admin/sheets (§11.1): every official sheet with its badges and the four filters. */ export default function AdminSheetsRoute() { - return + const t = useT() + const heading = usePageHeading() + const locale = useLocaleStore((s) => s.locale) + const { editor } = useAdminPermissions() + const { state, refresh } = useAdminQuery('admin-sheets-page', loadSheets) + const [filters, setFilters] = useState(NO_FILTER) + + if (state.status === 'error' && isRightsRefusal(state.failure)) + return + + const set = (key: keyof SheetFilters) => (value: string) => + setFilters((f) => ({ ...f, [key]: value })) + const species = state.status === 'ready' ? state.data.species : [] + const shown = + state.status === 'ready' ? filterSheets(state.data.sheets, filters) : [] + const options = (prefix: string, values: readonly string[]) => + values.map((value) => ({ value, label: t(`${prefix}.${value}`) })) + const speciesOptions = [ + ...new Set( + state.status === 'ready' + ? state.data.sheets.map((s) => s.species_id) + : [], + ), + ].map((id) => ({ value: id, label: speciesLabel(id, species, locale) })) + + return ( +
    +
    +

    + {t('admin.sheets.title')} +

    + {editor && ( + + {t('admin.sheets.new')} + + )} +
    + +
    + + + + +
    + + {state.status === 'loading' && ( +

    + {t('admin.sheets.loading')} +

    + )} + {state.status === 'error' && ( +
    + {failureMessage(t, state.failure)} + +
    + )} + {state.status === 'ready' && shown.length === 0 && ( +

    + {t( + state.data.sheets.length === 0 + ? 'admin.sheets.empty' + : 'admin.sheets.no_match', + )} +

    + )} + {shown.length > 0 && ( +
      + {shown.map((sheet) => ( + + ))} +
    + )} +
    + ) } diff --git a/apps/app/src/app/routes/app/admin/AdminSpeciesRoute.tsx b/apps/app/src/app/routes/app/admin/AdminSpeciesRoute.tsx index a00b6763..733fab33 100644 --- a/apps/app/src/app/routes/app/admin/AdminSpeciesRoute.tsx +++ b/apps/app/src/app/routes/app/admin/AdminSpeciesRoute.tsx @@ -1,6 +1,217 @@ -import PlaceholderPage from '@/components/shell/PlaceholderPage' +import { useState } from 'react' +import { listCatalogSpecies, type CatalogSpecies } from '@faunosteo/supabase' +import ActivateSpeciesDialog from '@/components/admin/ActivateSpeciesDialog' +import SpeciesDialog, { + type SpeciesDialogMode, +} from '@/components/admin/SpeciesDialog' +import AccessDenied from '@/components/shell/AccessDenied' +import Badge from '@/components/ui/Badge' +import Button from '@/components/ui/Button' +import Notice from '@/components/ui/Notice' +import { failureMessage, speciesName } from '@/admin/labels' +import { useAdminPermissions, type AdminPermissions } from '@/admin/permissions' +import { isRightsRefusal, useAdminQuery } from '@/admin/useAdminQuery' +import { usePageHeading } from '@/app/usePageHeading' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' -/** V1-2.5 placeholder (slice E): the species screen, built by slice G. */ +type Translate = ReturnType + +interface RowActions { + permissions: AdminPermissions + onEdit: (mode: SpeciesDialogMode) => void + onActivate: (species: CatalogSpecies) => void +} + +function SpeciesRow({ + species, + t, + actions, +}: { + species: CatalogSpecies + t: Translate + actions: RowActions +}) { + const locale = useLocaleStore((s) => s.locale) + const { permissions } = actions + const name = speciesName(species, locale) + const named = (key: string) => t(key).replace('{name}', name) + return ( +
  • +
    +

    + {name} + + {t( + species.active + ? 'admin.species.state.active' + : 'admin.species.state.inactive', + )} + +

    +

    + {[ + species.id, + locale === 'fr' ? species.name_en : species.name_fr, + t('admin.species.order_value').replace( + '{order}', + String(species.sort_order), + ), + ].join(' · ')} +

    +
    +
    + {/* Matrix §5.4: the editor edits inactive rows, the owner activates and renames. */} + {!species.active && permissions.editor && ( + + )} + {!species.active && permissions.owner && ( + + )} + {species.active && permissions.owner && ( + + )} +
    +
  • + ) +} + +/** /app/admin/species (§7.2, S1): active and inactive species, the actions each role may take. */ export default function AdminSpeciesRoute() { - return + const t = useT() + const heading = usePageHeading() + const permissions = useAdminPermissions() + const { state, refresh } = useAdminQuery('species', listCatalogSpecies) + const [dialog, setDialog] = useState(null) + const [activating, setActivating] = useState(null) + const [done, setDone] = useState(null) + + if (state.status === 'error' && isRightsRefusal(state.failure)) + return + + const saved = () => { + setDone( + dialog?.kind === 'create' + ? 'admin.species.created' + : 'admin.species.saved', + ) + setDialog(null) + refresh() + } + const activated = () => { + setDone('admin.species.activate.done') + setActivating(null) + refresh() + } + const actions: RowActions = { + permissions, + onEdit: (mode) => { + setDone(null) + setDialog(mode) + }, + onActivate: (species) => { + setDone(null) + setActivating(species) + }, + } + + return ( +
    +
    +
    +

    + {t('admin.species.title')} +

    +

    + {t('admin.species.lede')} +

    +
    + {permissions.editor && ( + + )} +
    + + {done && {t(done)}} + {state.status === 'loading' && ( +

    + {t('admin.species.loading')} +

    + )} + {state.status === 'error' && ( +
    + {failureMessage(t, state.failure)} + +
    + )} + {state.status === 'ready' && state.data.length === 0 && ( +

    + {t('admin.species.empty')} +

    + )} + {state.status === 'ready' && state.data.length > 0 && ( +
      + {state.data.map((species) => ( + + ))} +
    + )} + + setDialog(null)} + onSaved={saved} + /> + setActivating(null)} + onActivated={activated} + /> +
    + ) } diff --git a/apps/app/src/app/routes/app/anatomy/CatalogRoute.tsx b/apps/app/src/app/routes/app/anatomy/CatalogRoute.tsx index f4374890..d4c226b6 100644 --- a/apps/app/src/app/routes/app/anatomy/CatalogRoute.tsx +++ b/apps/app/src/app/routes/app/anatomy/CatalogRoute.tsx @@ -1,6 +1,110 @@ -import PlaceholderPage from '@/components/shell/PlaceholderPage' +import { useState } from 'react' +import type { SpeciesLabel } from '@faunosteo/supabase' +import AccessDenied from '@/components/shell/AccessDenied' +import CatalogueCard from '@/components/catalogue/CatalogueCard' +import CatalogueFailureNotice from '@/components/catalogue/CatalogueFailureNotice' +import Chip from '@/components/ui/Chip' +import Input from '@/components/ui/Input' +import { speciesName } from '@/animals/species' +import type { CatalogEntry } from '@/catalogue/catalogue' +import { catalogSpecies, filterCatalog, useCatalogue } from '@/catalogue/useCatalogue' +import { usePageHeading } from '@/app/usePageHeading' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' -/** V1-2.5 placeholder (slice E): the catalogue list (board 01), built by slice I. */ +function CatalogueList({ + entries, + species, +}: { + entries: CatalogEntry[] + species: SpeciesLabel[] +}) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const [query, setQuery] = useState('') + const [speciesId, setSpeciesId] = useState(null) + const shown = filterCatalog(entries, query, speciesId) + const nameOf = (id: string) => speciesName(species, id, null, locale) + + return ( + <> +
    + setQuery(e.target.value)} + aria-label={t('catalogue.search')} + placeholder={t('catalogue.search')} + maxLength={100} + autoComplete="off" + className="sm:max-w-sm" + /> +
    + setSpeciesId(null)}> + {t('catalogue.all_species')} + + {catalogSpecies(entries, species).map((id) => ( + setSpeciesId(id)}> + {nameOf(id)} + + ))} +
    +
    + {shown.length === 0 ? ( +
    +

    + {entries.length === 0 ? t('catalogue.empty') : t('catalogue.no_results')} +

    + {entries.length === 0 && ( +

    {t('catalogue.empty_hint')}

    + )} +
    + ) : ( +
      + {shown.map((entry) => ( + + ))} +
    + )} + + ) +} + +/** + * /app/anatomy (board 01): the published official sheets by species, search + * by sheet name only (BDR-095), a chip per species that has a listed sheet. + * The server decides access: its refusal shows « Accès non autorisé ». + */ export default function CatalogRoute() { - return + const t = useT() + const heading = usePageHeading() + const { state, retry } = useCatalogue() + if (state.status === 'error' && state.failure === 'denied') return + + return ( +
    +
    +

    + {t('shell.nav.anatomy')} +

    +

    {t('catalogue.lede')}

    +
    + {state.status === 'loading' && ( +

    + {t('catalogue.loading')} +

    + )} + {state.status === 'error' && state.failure !== 'denied' && ( + + )} + {state.status === 'ready' && } +
    + ) } diff --git a/apps/app/src/app/routes/app/anatomy/SheetRoute.tsx b/apps/app/src/app/routes/app/anatomy/SheetRoute.tsx new file mode 100644 index 00000000..8c439c8c --- /dev/null +++ b/apps/app/src/app/routes/app/anatomy/SheetRoute.tsx @@ -0,0 +1,207 @@ +import { useCallback, useState, type KeyboardEvent } from 'react' +import { Link, useParams } from 'react-router-dom' +import type { PreviewState } from '@faunosteo/core-wasm/types' +import AccessDenied from '@/components/shell/AccessDenied' +import ButtonLink from '@/components/ui/ButtonLink' +import Icon from '@/components/ui/Icon' +import CatalogueCanvas from '@/components/catalogue/CatalogueCanvas' +import CatalogueFailureNotice from '@/components/catalogue/CatalogueFailureNotice' +import VersionLine from '@/components/catalogue/VersionLine' +import ZonePanel from '@/components/catalogue/ZonePanel' +import { DisclaimerNotice, ReferencesCard } from '@/components/catalogue/SheetAside' +import { navigationHint } from '@/auth/navigationHint' +import type { CataloguePreview } from '@/catalogue/preview' +import { useSheetVersion } from '@/catalogue/useSheetVersion' +import type { CatalogVersionItem } from '@faunosteo/supabase' +import type { VersionAnswer } from '@/catalogue/catalogue' +import { usePageHeading } from '@/app/usePageHeading' +import { pickLabel } from '@/i18n/pickLocaleLabel' +import { useAuthStore } from '@/state/authStore' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' + +/** A positive whole number from the address, else null (never a guess). */ +function versionNumber(raw: string | undefined): number | null | 'invalid' { + if (raw === undefined) return null + return /^[1-9]\d{0,8}$/.test(raw) ? Number(raw) : 'invalid' +} + +interface LoadedSheetProps { + versions: CatalogVersionItem[] + version: VersionAnswer + preview: CataloguePreview + state: PreviewState +} + +/** View tabs (main first, then the detail views), arrows move between them. */ +function ViewTabs({ + state, + viewId, + onView, +}: { + state: PreviewState + viewId: string + onView: (id: string) => void +}) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const views = state.document.views + const onKeyDown = (event: KeyboardEvent) => { + const at = views.findIndex((v) => v.id === viewId) + const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0 + if (step === 0 || at < 0) return + event.preventDefault() + const next = views[(at + step + views.length) % views.length] + onView(next.id) + document.getElementById(`catalogue-tab-${next.id}`)?.focus() + } + return ( +
    + {views.map((view) => { + const active = view.id === viewId + return ( + + ) + })} +
    + ) +} + +function LoadedSheet({ versions, version, preview, state }: LoadedSheetProps) { + const t = useT() + const heading = usePageHeading() + const locale = useLocaleStore((s) => s.locale) + const grants = useAuthStore((s) => s.catalogGrants) + // Without roles, the hint's « admin » holds for a capability only (an editor link, L25). + const editor = navigationHint(grants, []).admin + const { document, index } = state + const [viewId, setViewId] = useState(index?.main_view_id ?? document.views[0]?.id ?? '') + const [selectedId, setSelectedId] = useState(null) + const view = document.views.find((v) => v.id === viewId) + + // A link to a detail view opens its tab; any other annotation shows its zone. + const onAnnotation = useCallback( + (id: string) => { + const annotation = index ? document.annotations[index.annotation_by_id[id]] : undefined + if (!annotation) return + if (annotation.kind === 'detail_trigger') setViewId(annotation.opens_view_id) + else setSelectedId(id) + }, + [document, index], + ) + + return ( +
    + +
    +
    +
    +
    +

    + {pickLabel(document.name, locale)} +

    + +
    + {editor && ( + + + {t('catalogue.open_admin')} + + )} +
    + {document.views.length > 0 && view && ( + <> + +
    + +
    + + )} +
    + +
    +
    + ) +} + +/** + * /app/anatomy/:sheetId (the current version) and /:sheetId/versions/:number + * (one published or retired version), boards 02 and 03: the version comes + * from the server and the core (`get_sheet_version`, `PreviewSheet`); a + * refusal, an unknown sheet and an unknown number all show « Accès non + * autorisé ». The core handle is freed when the page leaves. + */ +export default function SheetRoute() { + const { sheetId = '', number: rawNumber } = useParams() + const number = versionNumber(rawNumber) + if (number === 'invalid') return + return +} + +function SheetVersionPage({ sheetId, number }: { sheetId: string; number: number | null }) { + const t = useT() + const { state, retry } = useSheetVersion(sheetId, number) + if (state.status === 'loading') { + return ( +

    + {t('catalogue.loading_sheet')} +

    + ) + } + if (state.status === 'error') { + if (state.failure === 'denied') return + return + } + return ( + + ) +} diff --git a/apps/app/src/auth/navigationHint.ts b/apps/app/src/auth/navigationHint.ts index 43f91854..69cd5269 100644 --- a/apps/app/src/auth/navigationHint.ts +++ b/apps/app/src/auth/navigationHint.ts @@ -14,7 +14,7 @@ const CAPABILITIES: ReadonlySet = new Set([ ]) /** Not revoked and not past its expiry, on the device clock. */ -function isActive(grant: OwnCatalogGrant, now: number): boolean { +export function isGrantActive(grant: OwnCatalogGrant, now: number): boolean { if (grant.revoked_at) return false return grant.expires_at === null || Date.parse(grant.expires_at) > now } @@ -30,7 +30,7 @@ export function navigationHint( roles: readonly PlatformRole[], now: number = Date.now(), ): NavigationHint { - const active = grants.filter((grant) => isActive(grant, now)) + const active = grants.filter((grant) => isGrantActive(grant, now)) const capability = active.some((grant) => CAPABILITIES.has(grant.kind)) return { catalog: capability || active.some((grant) => grant.kind === 'catalog_reader'), diff --git a/apps/app/src/catalogue/catalogue.ts b/apps/app/src/catalogue/catalogue.ts new file mode 100644 index 00000000..825ab834 --- /dev/null +++ b/apps/app/src/catalogue/catalogue.ts @@ -0,0 +1,130 @@ +import { z } from 'zod' +import { + SheetFailure, + downloadSheetDrawing, + getSheetVersion, + listOfficialCatalog, + type FaunosteoClient, +} from '@faunosteo/supabase' +import type { PreviewState } from '@faunosteo/core-wasm/types' +import { coreRuntime } from '@/core/runtime' +import { coreFailure, serverFailure, type CatalogueFailure } from './failure' +import { CataloguePreview, type PreviewDrawing } from './preview' + +/** + * The catalogue's reads (contract §10, §11.1): the list of published sheets and + * one published or deprecated version loaded into the core. The answers are + * checked against their shape only (a different one is `unavailable`); the + * document and the drawings are the core's to judge. + */ + +const LocalizedSchema = z.object({ fr: z.string(), en: z.string() }) + +const CatalogEntrySchema = z.object({ + sheet_id: z.string(), + species_id: z.string(), + slug: z.string(), + name: LocalizedSchema, + version_number: z.number(), + version_id: z.string(), +}) +export type CatalogEntry = z.infer + +const VersionAnswerSchema = z.object({ + sheet_id: z.string(), + version_id: z.string(), + version_number: z.number(), + status: z.enum(['draft', 'published', 'deprecated']), + species_id: z.string(), + document: z.unknown(), + fingerprint: z.string().nullable(), + drawings: z.array(z.object({ asset_id: z.string(), sha256: z.string() })), +}) +export type VersionAnswer = z.infer + +function parsed(schema: z.ZodType, data: unknown): T { + const result = schema.safeParse(data) + if (!result.success) throw new SheetFailure('unavailable', result.error) + return result.data +} + +/** The current published version of every listed sheet (`list_official_catalog`). */ +export async function fetchCatalog(client: FaunosteoClient): Promise { + return parsed(z.array(CatalogEntrySchema), await listOfficialCatalog(client)) +} + +export type VersionLoad = + | { + ok: true + version: VersionAnswer + preview: CataloguePreview + state: PreviewState + } + | { ok: false; failure: CatalogueFailure } + +async function downloadDrawings( + client: FaunosteoClient, + version: VersionAnswer, +): Promise { + return Promise.all( + version.drawings.map(async (drawing) => ({ + assetId: drawing.asset_id, + sha256: drawing.sha256, + bytes: await downloadSheetDrawing(client, drawing.sha256), + })), + ) +} + +type VersionRead = + | { ok: true; version: VersionAnswer; drawings: PreviewDrawing[] } + | { ok: false; failure: CatalogueFailure } + +async function readVersion( + client: FaunosteoClient, + versionId: string, +): Promise { + let version: VersionAnswer + try { + version = parsed(VersionAnswerSchema, await getSheetVersion(client, versionId)) + } catch (error) { + return { ok: false, failure: serverFailure(error) } + } + // The catalogue reads published and deprecated versions only (§11.1). + if (version.status === 'draft') return { ok: false, failure: 'denied' } + try { + return { ok: true, version, drawings: await downloadDrawings(client, version) } + } catch (error) { + // The version answered: a drawing it names that Storage does not give is missing. + const failure = serverFailure(error) + return { ok: false, failure: failure === 'denied' ? 'drawing_missing' : failure } + } +} + +/** + * One version through `get_sheet_version`, its drawings downloaded under RLS + * and the whole handed to `PreviewSheet`, which checks hashes, fingerprint and + * caps. Unknown and refused ids are the same `denied`. The caller frees the + * preview. + */ +export async function loadVersion( + client: FaunosteoClient, + versionId: string, +): Promise { + const read = await readVersion(client, versionId) + if (!read.ok) return read + const { version, drawings } = read + if (!(await coreRuntime().ready())) return { ok: false, failure: 'core_unavailable' } + const preview = new CataloguePreview( + coreRuntime(), + { + status: version.status, + document: JSON.stringify(version.document), + fingerprint: version.fingerprint ?? undefined, + }, + drawings, + ) + const state = preview.state() + if (state.ok) return { ok: true, version, preview, state: state.value } + preview.free() + return { ok: false, failure: coreFailure(state.kind) } +} diff --git a/apps/app/src/catalogue/failure.ts b/apps/app/src/catalogue/failure.ts new file mode 100644 index 00000000..74304a75 --- /dev/null +++ b/apps/app/src/catalogue/failure.ts @@ -0,0 +1,60 @@ +import { classifySheetError, type SheetFailureKind } from '@faunosteo/supabase' + +/** + * What a catalogue page can meet (contract §10, closed kinds), each phrased by + * `catalogue.failure.` except `denied` (« Accès non autorisé ») and + * `core_unavailable` (the core notice with its retry). `denied` folds the + * server's refusal and an unknown id into one answer (§5.3). + */ +export type CatalogueFailure = + | 'denied' + | 'network' + | 'session_expired' + | 'rate_limited' + | 'unavailable' + | 'drawing_missing' + | 'drawing_hash_mismatch' + | 'fingerprint_mismatch' + | 'invalid_document' + | 'caps' + | 'core_unavailable' + +const DENIED: ReadonlySet = new Set([ + 'rights.catalog', + 'not_found', + 'forbidden', + 'authentication_required', +]) + +const PASSED_THROUGH: ReadonlySet = new Set([ + 'network', + 'session_expired', + 'rate_limited', +]) + +/** A server or network answer of the access layer, folded for the page. */ +export function serverFailure(error: unknown): CatalogueFailure { + const kind = classifySheetError(error) + if (DENIED.has(kind)) return 'denied' + if (PASSED_THROUGH.has(kind)) return kind as CatalogueFailure + return 'unavailable' +} + +const CORE_REFUSALS: ReadonlySet = new Set([ + 'drawing_missing', + 'drawing_hash_mismatch', + 'fingerprint_mismatch', + 'invalid_document', + 'caps', +]) + +/** + * A refusal of the core's `PreviewBuilder` (`: `), or a runtime + * failure: the engine kinds ask for a retry, anything else unreadable is the + * document's fault (`invalid_shape`, `invalid_json`). + */ +export function coreFailure(kind: string): CatalogueFailure { + if (CORE_REFUSALS.has(kind)) return kind as CatalogueFailure + if (kind === 'core_unavailable' || kind === 'internal') return 'core_unavailable' + return 'invalid_document' +} diff --git a/apps/app/src/catalogue/framing.ts b/apps/app/src/catalogue/framing.ts new file mode 100644 index 00000000..069d4d7c --- /dev/null +++ b/apps/app/src/catalogue/framing.ts @@ -0,0 +1,63 @@ +/** + * Display framing of the catalogue canvas (board 03): a CSS scale and + * translation of the inserted drawing, never a change to the drawing. At + * scale 1 the drawing fills the box with its whole frame visible (the + * composer's `xMidYMid meet`); zooming keeps the point under the finger or + * the box centre in place, and panning never uncovers the box. + */ +export interface Framing { + scale: number + x: number + y: number +} + +export interface Box { + width: number + height: number +} + +export const FIT: Framing = { scale: 1, x: 0, y: 0 } +export const MAX_SCALE = 6 +/** One press of − or +. */ +export const ZOOM_STEP = 1.5 + +function clamp(value: number, min: number, max: number): number { + return Math.min(max, Math.max(min, value)) +} + +/** The translation that keeps the scaled drawing over the whole box. */ +function contained(framing: Framing, box: Box): Framing { + const { scale } = framing + return { + scale, + x: clamp(framing.x, box.width * (1 - scale), 0), + y: clamp(framing.y, box.height * (1 - scale), 0), + } +} + +/** Scales by `factor` around a point of the box (its centre by default). */ +export function zoomBy( + framing: Framing, + factor: number, + box: Box, + at = { x: box.width / 2, y: box.height / 2 }, +): Framing { + const scale = clamp(framing.scale * factor, 1, MAX_SCALE) + const ratio = scale / framing.scale + return contained( + { + scale, + x: at.x - (at.x - framing.x) * ratio, + y: at.y - (at.y - framing.y) * ratio, + }, + box, + ) +} + +export function panBy(framing: Framing, dx: number, dy: number, box: Box): Framing { + return contained({ ...framing, x: framing.x + dx, y: framing.y + dy }, box) +} + +export function transformOf(framing: Framing): string { + return `translate(${framing.x}px, ${framing.y}px) scale(${framing.scale})` +} diff --git a/apps/app/src/catalogue/preview.ts b/apps/app/src/catalogue/preview.ts new file mode 100644 index 00000000..57344f34 --- /dev/null +++ b/apps/app/src/catalogue/preview.ts @@ -0,0 +1,99 @@ +import { + CORE_UNAVAILABLE, + closedRefusal, + parseOutcome, + type CoreOutcome, + type CoreRuntime, + type GluePreviewSheet, +} from '@faunosteo/core-wasm' +import type { + CanvasView, + PreviewInput, + PreviewState, +} from '@faunosteo/core-wasm/types' + +/** One stored drawing as the page downloaded it: untrusted bytes the core hashes and reads. */ +export interface PreviewDrawing { + assetId: string + sha256: string + bytes: Uint8Array +} + +/** + * A stored version loaded into the core (`PreviewSheet`, RUST.md §12): the + * core checks each drawing's sha256 against its row, the fingerprint, the caps + * and every drawing through its SVG reader, then answers `preview.state` and + * `view.canvas`. Like `SheetSession`, the handle belongs to one instance of + * the module: after a trap and a recovery it is rebuilt from the kept input, + * a handle of a dropped instance is never called. `free` releases it when the + * page leaves. + */ +export class CataloguePreview { + private handle: GluePreviewSheet | null = null + private handleGeneration = -1 + private freed = false + + constructor( + private readonly runtime: CoreRuntime, + private readonly input: PreviewInput, + private readonly drawings: readonly PreviewDrawing[], + ) {} + + /** The first call builds the handle: the builder's refusals come back as closed kinds. */ + state(): CoreOutcome { + return this.call('preview.state', {}) + } + + /** The composed view (drawing framed, annotation layer, ids scoped per view). */ + canvas(viewId: string): CoreOutcome { + const view = this.call('view.canvas', { viewId }) + return view.ok ? { ok: true, value: view.value.svg } : view + } + + /** After this, every call answers `core_unavailable`: a page that left never rebuilds. */ + free(): void { + this.freed = true + const handle = this.handle + this.handle = null + if (!handle || this.handleGeneration !== this.runtime.generation) return + try { + handle.free() + } catch { + // Freeing never decides anything; a dead instance keeps its memory. + } + } + + private call(op: string, input: unknown): CoreOutcome { + const handle = this.current() + if (!handle.ok) return handle + return this.runtime.invoke(() => + parseOutcome(handle.value.call(op, JSON.stringify(input))), + ) + } + + private current(): CoreOutcome { + if (this.freed) return CORE_UNAVAILABLE + if (this.handle && this.handleGeneration === this.runtime.generation) { + return { ok: true, value: this.handle } + } + this.handle = null + return this.runtime.invoke((glue) => { + const builder = new glue.PreviewBuilder() + for (const drawing of this.drawings) { + // `false` past the handle's bounds: the build then refuses with `caps`. + builder.add_drawing(drawing.assetId, drawing.sha256, drawing.bytes) + } + try { + this.handle = builder.build(JSON.stringify(this.input)) + } catch (error) { + // Only the module's closed refusal is a refused version; anything else poisons. + const refusal = closedRefusal(error) + if (refusal === null) throw error + const [kind, ...detail] = refusal.split(': ') + return { ok: false, kind, detail: detail.join(': ') } + } + this.handleGeneration = this.runtime.generation + return { ok: true, value: this.handle } + }) + } +} diff --git a/apps/app/src/catalogue/useCardDetails.ts b/apps/app/src/catalogue/useCardDetails.ts new file mode 100644 index 00000000..b30ba684 --- /dev/null +++ b/apps/app/src/catalogue/useCardDetails.ts @@ -0,0 +1,56 @@ +import { useEffect, useState } from 'react' +import { listSheetVersions } from '@faunosteo/supabase' +import { getSupabaseClient } from '@/lib/supabase' +import { loadVersion, type CatalogEntry } from './catalogue' + +export interface CardDetails { + publishedAt: string | null + viewCount: number + zoneCount: number + /** Blob URL of the core's composed main view, shown as an image; null when it cannot be drawn. */ + thumbnail: string | null +} + +/** + * What a catalogue card adds to the list answer: the publication date, the + * counts the core read from the document, and a thumbnail of the main view. + * Loaded per card once the list is shown (one version and its drawings each); + * the core handle is freed as soon as the canvas is composed. Any failure + * leaves the card with its name and its link only. + */ +export function useCardDetails(entry: CatalogEntry): CardDetails | null { + const [details, setDetails] = useState(null) + + useEffect(() => { + let live = true + let thumbnail: string | null = null + const client = getSupabaseClient() + if (!client) return + void Promise.all([ + listSheetVersions(client, entry.sheet_id).catch(() => []), + loadVersion(client, entry.version_id), + ]).then(([versions, load]) => { + if (!load.ok) return + const { state, preview } = load + const main = state.index ? preview.canvas(state.index.main_view_id) : null + preview.free() + if (!live) return + if (main?.ok) { + thumbnail = URL.createObjectURL(new Blob([main.value], { type: 'image/svg+xml' })) + } + setDetails({ + publishedAt: + versions.find((v) => v.id === entry.version_id)?.published_at ?? null, + viewCount: state.document.views.length, + zoneCount: state.document.finding_zones.length, + thumbnail, + }) + }) + return () => { + live = false + if (thumbnail) URL.revokeObjectURL(thumbnail) + } + }, [entry.sheet_id, entry.version_id]) + + return details +} diff --git a/apps/app/src/catalogue/useCatalogue.ts b/apps/app/src/catalogue/useCatalogue.ts new file mode 100644 index 00000000..0c799174 --- /dev/null +++ b/apps/app/src/catalogue/useCatalogue.ts @@ -0,0 +1,81 @@ +import { useCallback, useEffect, useState } from 'react' +import { fetchSpeciesLabels, type SpeciesLabel } from '@faunosteo/supabase' +import { getSupabaseClient } from '@/lib/supabase' +import { fetchCatalog, type CatalogEntry } from './catalogue' +import { serverFailure, type CatalogueFailure } from './failure' + +export type CatalogueState = + | { status: 'loading' } + | { status: 'ready'; entries: CatalogEntry[]; species: SpeciesLabel[] } + | { status: 'error'; failure: CatalogueFailure } + +/** Species names are display only: a failed read leaves the ids as names. */ +async function speciesLabels( + client: NonNullable>, +): Promise { + try { + return await fetchSpeciesLabels(client) + } catch { + return [] + } +} + +/** The published catalogue and the species names, read once per visit (retry reads again). */ +export function useCatalogue() { + const [state, setState] = useState({ status: 'loading' }) + const [attempt, setAttempt] = useState(0) + + useEffect(() => { + let live = true + const client = getSupabaseClient() + setState({ status: 'loading' }) + if (!client) { + setState({ status: 'error', failure: 'unavailable' }) + return + } + Promise.all([fetchCatalog(client), speciesLabels(client)]) + .then(([entries, species]) => { + if (live) setState({ status: 'ready', entries, species }) + }) + .catch((error: unknown) => { + if (live) setState({ status: 'error', failure: serverFailure(error) }) + }) + return () => { + live = false + } + }, [attempt]) + + const retry = useCallback(() => setAttempt((n) => n + 1), []) + return { state, retry } +} + +/** Lower case without accents, so « epaule » finds « Épaule ». */ +function folded(text: string): string { + return text.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase() +} + +/** Search by sheet name only, French or English (BDR-095), then the species chip. */ +export function filterCatalog( + entries: readonly CatalogEntry[], + query: string, + speciesId: string | null, +): CatalogEntry[] { + const term = folded(query.trim()) + return entries.filter( + (entry) => + (speciesId === null || entry.species_id === speciesId) && + (term === '' || + folded(entry.name.fr).includes(term) || + folded(entry.name.en).includes(term)), + ) +} + +/** The species that have a listed sheet, in the reference order, unknown ids last. */ +export function catalogSpecies( + entries: readonly CatalogEntry[], + labels: readonly SpeciesLabel[], +): string[] { + const present = new Set(entries.map((entry) => entry.species_id)) + const known = labels.map((label) => label.id).filter((id) => present.has(id)) + return [...known, ...[...present].filter((id) => !known.includes(id))] +} diff --git a/apps/app/src/catalogue/useFraming.ts b/apps/app/src/catalogue/useFraming.ts new file mode 100644 index 00000000..4cc1b199 --- /dev/null +++ b/apps/app/src/catalogue/useFraming.ts @@ -0,0 +1,159 @@ +import { + useCallback, + useEffect, + useRef, + useState, + type KeyboardEvent, + type PointerEvent, + type RefObject, +} from 'react' +import { FIT, ZOOM_STEP, panBy, zoomBy, type Box, type Framing } from './framing' + +/** Movement past which a press is a drag, not a click on a zone. */ +const DRAG_THRESHOLD = 4 +const KEY_PAN = 40 + +type Point = { x: number; y: number } + +function boxOf(element: HTMLElement | null): Box & { left: number; top: number } { + const rect = element?.getBoundingClientRect() + return { + width: rect?.width ?? 0, + height: rect?.height ?? 0, + left: rect?.left ?? 0, + top: rect?.top ?? 0, + } +} + +function distance(a: Point, b: Point): number { + return Math.hypot(a.x - b.x, a.y - b.y) +} + +/** + * Zoom and pan of the canvas box: buttons, a drag with one pointer, a pinch + * with two, the wheel (pans when zoomed; with Ctrl, as a trackpad pinch + * sends it, zooms at the cursor) and the keyboard on the focused box (arrows, + * + and −, 0 fits). `reset` comes back to the whole drawing. A press that + * moved is not a click: `swallowClick` says so once. + */ +export function useFraming(viewport: RefObject, resetKey: string) { + const [framing, setFraming] = useState(FIT) + const pointers = useRef(new Map()) + const moved = useRef(0) + const dragged = useRef(false) + // The wheel listener reads the scale without re-subscribing on every change. + const scale = useRef(FIT.scale) + + useEffect(() => setFraming(FIT), [resetKey]) + useEffect(() => { + scale.current = framing.scale + }, [framing.scale]) + + const zoom = useCallback( + (factor: number, at?: Point) => + setFraming((f) => zoomBy(f, factor, boxOf(viewport.current), at)), + [viewport], + ) + const pan = useCallback( + (dx: number, dy: number) => + setFraming((f) => panBy(f, dx, dy, boxOf(viewport.current))), + [viewport], + ) + + useEffect(() => { + const element = viewport.current + if (!element) return + const onWheel = (event: WheelEvent) => { + const box = boxOf(element) + if (event.ctrlKey) { + event.preventDefault() + const at = { x: event.clientX - box.left, y: event.clientY - box.top } + zoom(event.deltaY < 0 ? 1.1 : 1 / 1.1, at) + return + } + // Unzoomed, the wheel scrolls the page as usual. + if (scale.current === 1) return + event.preventDefault() + setFraming((f) => panBy(f, -event.deltaX, -event.deltaY, box)) + } + element.addEventListener('wheel', onWheel, { passive: false }) + return () => element.removeEventListener('wheel', onWheel) + }, [viewport, zoom]) + + const onPointerDown = useCallback((event: PointerEvent) => { + pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY }) + if (pointers.current.size === 1) { + moved.current = 0 + dragged.current = false + } + }, []) + + const onPointerMove = useCallback( + (event: PointerEvent) => { + const before = pointers.current.get(event.pointerId) + if (!before) return + const now = { x: event.clientX, y: event.clientY } + const others = [...pointers.current].filter(([id]) => id !== event.pointerId) + pointers.current.set(event.pointerId, now) + moved.current += distance(before, now) + if (moved.current > DRAG_THRESHOLD) dragged.current = true + if (others.length === 1) { + const other = others[0][1] + const box = boxOf(viewport.current) + const at = { x: (now.x + other.x) / 2 - box.left, y: (now.y + other.y) / 2 - box.top } + const factor = distance(now, other) / Math.max(distance(before, other), 1) + zoom(factor, at) + } else if (others.length === 0 && dragged.current) { + event.currentTarget.setPointerCapture?.(event.pointerId) + pan(now.x - before.x, now.y - before.y) + } + }, + [viewport, zoom, pan], + ) + + const onPointerUp = useCallback((event: PointerEvent) => { + pointers.current.delete(event.pointerId) + }, []) + + const onKeyDown = useCallback( + (event: KeyboardEvent) => { + const keys: Record void> = { + ArrowLeft: () => pan(KEY_PAN, 0), + ArrowRight: () => pan(-KEY_PAN, 0), + ArrowUp: () => pan(0, KEY_PAN), + ArrowDown: () => pan(0, -KEY_PAN), + '+': () => zoom(ZOOM_STEP), + '=': () => zoom(ZOOM_STEP), + '-': () => zoom(1 / ZOOM_STEP), + '0': () => setFraming(FIT), + } + const action = keys[event.key] + if (!action) return + event.preventDefault() + action() + }, + [pan, zoom], + ) + + /** True once after a press that moved: the click that ends a drag selects nothing. */ + const swallowClick = useCallback(() => { + const was = dragged.current + dragged.current = false + return was + }, []) + + return { + framing, + zoomIn: () => zoom(ZOOM_STEP), + zoomOut: () => zoom(1 / ZOOM_STEP), + reset: () => setFraming(FIT), + swallowClick, + handlers: { + onPointerDown, + onPointerMove, + onPointerUp, + onPointerCancel: onPointerUp, + onKeyDown, + }, + } +} diff --git a/apps/app/src/catalogue/useSheetVersion.ts b/apps/app/src/catalogue/useSheetVersion.ts new file mode 100644 index 00000000..8c769cb7 --- /dev/null +++ b/apps/app/src/catalogue/useSheetVersion.ts @@ -0,0 +1,91 @@ +import { useCallback, useEffect, useState } from 'react' +import { listSheetVersions, type CatalogVersionItem } from '@faunosteo/supabase' +import type { PreviewState } from '@faunosteo/core-wasm/types' +import { coreRuntime } from '@/core/runtime' +import { getSupabaseClient } from '@/lib/supabase' +import { loadVersion, type VersionAnswer } from './catalogue' +import { serverFailure, type CatalogueFailure } from './failure' +import type { CataloguePreview } from './preview' + +export type SheetVersionState = + | { status: 'loading' } + | { + status: 'ready' + versions: CatalogVersionItem[] + version: VersionAnswer + preview: CataloguePreview + state: PreviewState + } + | { status: 'error'; failure: CatalogueFailure } + +/** + * The version a sheet page shows: `number` names it, otherwise the newest + * published one (the sheet's current version), else the newest at all (a + * sheet whose versions were all retired stays readable by id, §6.9). The + * list comes newest first under the reader policy; an unknown sheet, an + * unreadable one and a missing number are the same `denied`. + */ +function pickVersion( + versions: readonly CatalogVersionItem[], + number: number | null, +): CatalogVersionItem | undefined { + if (number !== null) return versions.find((v) => v.version_number === number) + return versions.find((v) => v.status === 'published') ?? versions[0] +} + +async function resolve(sheetId: string, number: number | null) { + const client = getSupabaseClient() + if (!client) return { ok: false as const, failure: 'unavailable' as const } + let versions: CatalogVersionItem[] + try { + versions = await listSheetVersions(client, sheetId) + } catch (error) { + return { ok: false as const, failure: serverFailure(error) } + } + const picked = pickVersion(versions, number) + if (!picked) return { ok: false as const, failure: 'denied' as const } + const load = await loadVersion(client, picked.id) + return load.ok ? { ...load, versions } : load +} + +/** Loads the page's version into the core; the handle is freed when the page leaves or changes. */ +export function useSheetVersion(sheetId: string, number: number | null) { + const [state, setState] = useState({ status: 'loading' }) + const [attempt, setAttempt] = useState(0) + + useEffect(() => { + let live = true + let preview: CataloguePreview | null = null + setState({ status: 'loading' }) + void resolve(sheetId, number).then((load) => { + if (!load.ok) { + if (live) setState({ status: 'error', failure: load.failure }) + return + } + if (!live) { + load.preview.free() + return + } + preview = load.preview + setState({ + status: 'ready', + versions: load.versions, + version: load.version, + preview: load.preview, + state: load.state, + }) + }) + return () => { + live = false + preview?.free() + } + }, [sheetId, number, attempt]) + + // The core may need a restart before the version is loaded again. + const retry = useCallback(() => { + void coreRuntime() + .retry() + .finally(() => setAttempt((n) => n + 1)) + }, []) + return { state, retry } +} diff --git a/apps/app/src/catalogue/versionText.ts b/apps/app/src/catalogue/versionText.ts new file mode 100644 index 00000000..c7954ea1 --- /dev/null +++ b/apps/app/src/catalogue/versionText.ts @@ -0,0 +1,16 @@ +import type { useT } from '@/i18n/useT' + +type Translate = ReturnType + +/** « Version 3 · publiée le 28/10/2026 », the date in the page's language. */ +export function versionText( + number: number, + publishedAt: string | null, + locale: string, + t: Translate, +): string { + if (!publishedAt) return t('catalogue.version').replace('{number}', String(number)) + return t('catalogue.version_published') + .replace('{number}', String(number)) + .replace('{date}', new Date(publishedAt).toLocaleDateString(locale)) +} diff --git a/apps/app/src/components/admin/ActivateSpeciesDialog.tsx b/apps/app/src/components/admin/ActivateSpeciesDialog.tsx new file mode 100644 index 00000000..42d8a2ac --- /dev/null +++ b/apps/app/src/components/admin/ActivateSpeciesDialog.tsx @@ -0,0 +1,99 @@ +import { useEffect, useState } from 'react' +import { + activateSpecies, + classifySheetError, + type CatalogSpecies, + type SheetFailureKind, +} from '@faunosteo/supabase' +import Button from '@/components/ui/Button' +import Dialog from '@/components/ui/Dialog' +import Notice from '@/components/ui/Notice' +import { failureMessage, speciesName } from '@/admin/labels' +import { getSupabaseClient } from '@/lib/supabase' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' + +export interface ActivateSpeciesDialogProps { + species: CatalogSpecies | null + onClose: () => void + /** Called once the server activated it; the caller closes the dialog. */ + onActivated: () => void +} + +/** + * The owner's confirmation before activation (§7.2): the only way a species + * becomes active, and from then on the animal forms offer it. No way back in + * V1-2 (no deactivation), so the dialog says so. + */ +export default function ActivateSpeciesDialog({ + species, + onClose, + onActivated, +}: ActivateSpeciesDialogProps) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const [pending, setPending] = useState(false) + const [failure, setFailure] = useState(null) + + useEffect(() => setFailure(null), [species]) + + const close = () => { + if (!pending) onClose() + } + + async function confirm() { + const client = getSupabaseClient() + if (!species || pending) return + if (!client) return setFailure('unavailable') + setPending(true) + setFailure(null) + try { + await activateSpecies(client, species.id) + onActivated() + } catch (error) { + setFailure(classifySheetError(error)) + } finally { + setPending(false) + } + } + + const name = species ? speciesName(species, locale) : '' + return ( + + {t('admin.species.activate.body')} +

    + } + size="sm" + > + {failure && ( + + {failureMessage(t, failure)} + + )} +
    + + +
    +
    + ) +} diff --git a/apps/app/src/components/admin/GrantList.tsx b/apps/app/src/components/admin/GrantList.tsx new file mode 100644 index 00000000..010bd89d --- /dev/null +++ b/apps/app/src/components/admin/GrantList.tsx @@ -0,0 +1,203 @@ +import { useState } from 'react' +import type { CatalogGrant } from '@faunosteo/supabase' +import RevokeGrantDialog from '@/components/admin/RevokeGrantDialog' +import Badge from '@/components/ui/Badge' +import Button from '@/components/ui/Button' +import FormField from '@/components/ui/FormField' +import Notice from '@/components/ui/Notice' +import Select from '@/components/ui/Select' +import { formatDay } from '@/admin/labels' +import type { Locale } from '@/i18n/types' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' + +type Translate = ReturnType +type GrantState = CatalogGrant['state'] + +/** The four states of the rights screen (§5.2), in reading order. */ +const GRANT_STATES: readonly GrantState[] = [ + 'active', + 'expiring', + 'expired', + 'revoked', +] + +const STATE_TONE = { + active: 'accent', + expiring: 'warn', + expired: 'neutral', + revoked: 'danger', +} as const + +function holder(t: Translate, grant: CatalogGrant): string { + const name = grant.display_name || t('admin.person.unnamed') + return grant.email ? `${name} (${grant.email})` : name +} + +function GrantItem({ + grant, + t, + locale, + onRevoke, +}: { + grant: CatalogGrant + t: Translate + locale: Locale + onRevoke: () => void +}) { + const granted = t('admin.access.list.granted') + .replace('{date}', formatDay(grant.granted_at, locale)) + .replace('{name}', grant.granted_by_name || t('admin.person.unnamed')) + const expiry = grant.expires_at + ? t('admin.access.list.expires').replace( + '{date}', + formatDay(grant.expires_at, locale), + ) + : t('admin.access.list.no_expiry') + const live = grant.state === 'active' || grant.state === 'expiring' + return ( +
  • +
    + + {holder(t, grant)} + + {t(`admin.grant_kind.${grant.kind}`)} + + {t(`admin.grant_state.${grant.state}`)} + + {live && !grant.effective && ( + {t('admin.access.list.suspended')} + )} +
    +
    +
    + {t('admin.access.form.reason')} +
    +
    {grant.reason}
    + {grant.verification_note && ( + <> +
    + {t('admin.access.form.note')} +
    +
    + {grant.verification_note} +
    + + )} + {grant.revoked_at && ( + <> +
    + {t('admin.access.list.revoked_on').replace( + '{date}', + formatDay(grant.revoked_at, locale), + )} +
    +
    + {grant.revocation_reason} +
    + + )} +
    +

    {`${granted} · ${expiry}`}

    + {live && ( + + )} +
  • + ) +} + +/** + * Every grant (§5.2): active, expiring within 30 days, expired and revoked, + * with reason and verification note; a state filter, and revocation of the + * grants still in force. A grant shown « suspendu » is active on paper while + * its holder no longer meets the eligibility rules (`effective` false). + */ +export default function GrantList({ + grants, + onChanged, +}: { + grants: CatalogGrant[] + onChanged: () => void +}) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const [state, setState] = useState('') + const [revoking, setRevoking] = useState(null) + const [done, setDone] = useState(false) + const shown = state ? grants.filter((grant) => grant.state === state) : grants + + const subject = revoking + ? `${holder(t, revoking)}, ${t(`admin.grant_kind.${revoking.kind}`)}` + : '' + const revoked = () => { + setRevoking(null) + setDone(true) + onChanged() + } + + return ( +
    +

    + {t('admin.access.list.title')} +

    +
    + + + +
    + {done && {t('admin.access.revoke.done')}} + {shown.length === 0 ? ( +

    + {t( + grants.length === 0 + ? 'admin.access.list.empty' + : 'admin.access.list.no_match', + )} +

    + ) : ( +
      + {shown.map((grant) => ( + { + setDone(false) + setRevoking(grant) + }} + /> + ))} +
    + )} + setRevoking(null)} + onRevoked={revoked} + /> +
    + ) +} diff --git a/apps/app/src/components/admin/GrantPanel.tsx b/apps/app/src/components/admin/GrantPanel.tsx new file mode 100644 index 00000000..b1a8f775 --- /dev/null +++ b/apps/app/src/components/admin/GrantPanel.tsx @@ -0,0 +1,319 @@ +import { useState, type FormEvent } from 'react' +import { + classifySheetError, + grantCatalogRight, + lookupCatalogAccount, + type CatalogAccount, + type SheetFailureKind, +} from '@faunosteo/supabase' +import Badge from '@/components/ui/Badge' +import Button from '@/components/ui/Button' +import Card from '@/components/ui/Card' +import ChoiceRadios from '@/components/ui/ChoiceRadios' +import FormField, { fieldDescribedBy } from '@/components/ui/FormField' +import Input from '@/components/ui/Input' +import Notice from '@/components/ui/Notice' +import Textarea from '@/components/ui/Textarea' +import { failureMessage } from '@/admin/labels' +import { + GRANT_KINDS, + GRANT_TEXT_MAX, + parseGrant, + type FieldErrors, + type GrantFormValues, +} from '@/admin/validation' +import { translateFieldError } from '@/account/validation' +import { localDateIso } from '@/lib/dates' +import { getSupabaseClient } from '@/lib/supabase' +import { useT } from '@/i18n/useT' + +type Translate = ReturnType + +const EMPTY: GrantFormValues = { + kind: '', + reason: '', + verification_note: '', + expires_on: '', +} + +/** One line per eligibility condition of §5.2, as the lookup answer shows it. */ +function AccountCard({ + account, + t, +}: { + account: CatalogAccount + t: Translate +}) { + const yesNo = (ok: boolean, yes: string, no: string) => ( + {t(ok ? yes : no)} + ) + return ( +
    +

    + {account.display_name || t('admin.person.unnamed')} +

    +
    + {!account.active && ( + {t('admin.access.account.inactive')} + )} + {yesNo( + account.email_confirmed, + 'admin.access.account.confirmed', + 'admin.access.account.unconfirmed', + )} + {yesNo( + account.verified_totp, + 'admin.access.account.factor', + 'admin.access.account.no_factor', + )} +
    +

    + {account.platform_roles.length > 0 + ? t('admin.access.account.roles').replace( + '{roles}', + account.platform_roles + .map((role) => t(`shell.role.${role}`)) + .join(', '), + ) + : t('admin.access.account.no_role')} +

    +
    + ) +} + +function useLookup() { + const [email, setEmail] = useState('') + const [account, setAccount] = useState(null) + const [failure, setFailure] = useState(null) + const [pending, setPending] = useState(false) + + async function find(event: FormEvent) { + event.preventDefault() + const client = getSupabaseClient() + const typed = email.trim() + if (pending || typed === '') return + if (!client) return setFailure('unavailable') + setPending(true) + setFailure(null) + setAccount(null) + try { + setAccount(await lookupCatalogAccount(client, typed)) + } catch (error) { + setFailure(classifySheetError(error)) + } finally { + setPending(false) + } + } + return { email, setEmail, account, failure, pending, find } +} + +/** + * Find an account by e-mail, then grant it a right (§5.2, A0): kind, reason, + * verification note for the three capabilities, optional expiry. The server + * checks eligibility at grant time; `grant.ineligible` is explained. + */ +export default function GrantPanel({ onGranted }: { onGranted: () => void }) { + const t = useT() + const lookup = useLookup() + const [values, setValues] = useState(EMPTY) + const [errors, setErrors] = useState>({}) + const [failure, setFailure] = useState(null) + const [pending, setPending] = useState(false) + const [done, setDone] = useState(false) + + const set = (key: keyof GrantFormValues) => (value: string) => + setValues((v) => ({ ...v, [key]: value })) + const err = (key: keyof GrantFormValues) => + translateFieldError(t, errors[key]) + + async function grant(event: FormEvent) { + event.preventDefault() + const client = getSupabaseClient() + if (!lookup.account || pending) return + const parsed = parseGrant(values) + if (!parsed.ok) return setErrors(parsed.errors) + if (!client) return setFailure('unavailable') + setErrors({}) + setFailure(null) + setDone(false) + setPending(true) + try { + await grantCatalogRight(client, { + user_id: lookup.account.user_id, + ...parsed.value, + }) + setValues(EMPTY) + setDone(true) + onGranted() + } catch (error) { + setFailure(classifySheetError(error)) + } finally { + setPending(false) + } + } + + const capability = values.kind !== '' && values.kind !== 'catalog_reader' + const noteHint = t( + capability + ? 'admin.access.form.note_hint' + : 'admin.access.form.note_hint_reader', + ) + return ( + +

    + {t('admin.access.grant_title')} +

    +
    void lookup.find(e)} + noValidate + className="grid gap-3 sm:grid-cols-[1fr_auto] sm:items-end" + > + + lookup.setEmail(e.target.value)} + maxLength={320} + autoComplete="off" + aria-describedby="grant-email-hint" + /> + + +
    + {lookup.failure && ( + + {lookup.failure === 'not_found' + ? t('admin.access.lookup.not_found') + : failureMessage(t, lookup.failure)} + + )} + + {lookup.account && ( + <> + +
    void grant(e)} + noValidate + className="space-y-4" + > + ({ + value: kind, + label: t(`admin.grant_kind.${kind}`), + }))} + value={values.kind} + onChange={(kind) => set('kind')(kind)} + error={err('kind')} + /> + +