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.
This commit is contained in:
bchanot committed 2026-11-02 17:18:27 +01:00
1 parent 9f7824dc08
commit 0176b3184d
42 files changed
+6438 -39

No files matched your search

+46
View File
@@ -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),
)
}
+128
View File
@@ -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.<kind>` 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<SheetFailureKind> =
new Set<SheetFailureKind>([
'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<SheetAdminRound, 'status'> & {
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
+45
View File
@@ -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)
}
+61
View File
@@ -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<T> =
| { 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<T>(
key: string,
load: (client: FaunosteoClient) => Promise<T>,
) {
const [state, setState] = useState<AdminQueryState<T>>({ status: 'loading' })
const [reload, setReload] = useState(0)
const shownKey = useRef<string | null>(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.')
}
+256
View File
@@ -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<K extends string> = Partial<Record<K, string>>
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<K extends string>(error: z.ZodError): FieldErrors<K> {
const errors: FieldErrors<K> = {}
for (const issue of error.issues) {
const key = issue.path[0] as K
errors[key] ??= issue.message
}
return errors
}
export type Parsed<T, K extends string> =
| { ok: true; value: T }
| { ok: false; errors: FieldErrors<K> }
function parse<T, K extends string>(
schema: z.ZodType<T, z.ZodTypeDef, unknown>,
values: unknown,
): Parsed<T, K> {
const result = schema.safeParse(values)
return result.success
? { ok: true, value: result.data }
: { ok: false, errors: fieldErrors<K>(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<typeof speciesSchema>
export function parseSpecies(
values: SpeciesFormValues,
): Parsed<SpeciesFields, keyof SpeciesFormValues> {
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<typeof sheetSchema>
export function parseSheet(
values: SheetFormValues,
): Parsed<SheetFields, keyof SheetFormValues> {
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<GrantFields, keyof GrantFormValues> {
return parse(grantSchema(today), values)
}
export function parseRevocation(reason: string): Parsed<string, 'reason'> {
return parse(
z
.object({ reason: requiredText(GRANT_TEXT_MAX) })
.transform((v) => v.reason),
{
reason,
},
)
}
+3
View File
@@ -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. */}
<Route path="anatomy" element={<RequireCatalog />}>
<Route index element={<CatalogRoute />} />
<Route path=":sheetId" element={<SheetRoute />} />
<Route path=":sheetId/versions/:number" element={<SheetRoute />} />
</Route>
<Route path="admin" element={<RequireAdmin />}>
<Route index element={<AdminHomeRoute />} />
@@ -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 <PlaceholderPage titleKey="admin.access.title" />
const t = useT()
const heading = usePageHeading()
const { state, refresh } = useAdminQuery('grants', listCatalogGrants)
if (state.status === 'error' && isRightsRefusal(state.failure))
return <AccessDenied />
return (
<div className="space-y-6">
<header className="space-y-1">
<h1
ref={heading}
tabIndex={-1}
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
>
{t('admin.access.title')}
</h1>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('admin.access.lede')}
</p>
</header>
{state.status === 'loading' && (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('admin.access.loading')}
</p>
)}
{state.status === 'error' && (
<div className="space-y-3">
<Notice tone="error">{failureMessage(t, state.failure)}</Notice>
<Button type="button" variant="secondary" onClick={refresh}>
{t('common.retry')}
</Button>
</div>
)}
{state.status === 'ready' && (
<>
<GrantPanel onGranted={refresh} />
<GrantList grants={state.data} onChanged={refresh} />
</>
)}
</div>
)
}
@@ -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<typeof useT>
/** 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 (
<li className="space-y-2 py-3 first:pt-0 last:pb-0">
<div className="flex flex-wrap items-center gap-2">
<Link
to={`/app/admin/sheets/${sheet.sheet_id}`}
className="mr-auto min-w-0 font-medium text-[var(--color-ink)] underline-offset-2 hover:underline"
>
{localized(sheet.name, locale)}
</Link>
<SheetBadges sheet={sheet} />
</div>
{/* The working copy action (W1): editors only, on the historical sheet. */}
{sheet.historical && editor && (
<WorkingCopyAction
slug={sheet.slug}
sourceVersionId={sheet.latest_version?.version_id ?? null}
copyActive={sheet.working_copy_active === true}
/>
)}
</li>
)
}
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 (
<Card
as="section"
aria-labelledby="admin-sheets-title"
className="space-y-3 p-5 sm:p-6"
>
<h2
id="admin-sheets-title"
className="font-serif text-xl text-[var(--color-ink)]"
>
{t('admin.sheets.title')}
</h2>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('admin.home.sheets_body')}
</p>
{state.status === 'loading' && (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('admin.sheets.loading')}
</p>
)}
{state.status === 'error' && (
<div className="space-y-2">
<Notice tone="error">{failureMessage(t, state.failure)}</Notice>
<Button type="button" variant="secondary" size="sm" onClick={refresh}>
{t('common.retry')}
</Button>
</div>
)}
{state.status === 'ready' && state.data.length === 0 && (
<p className="text-sm text-[var(--color-ink)]">
{t('admin.sheets.empty')}
</p>
)}
{shown.length > 0 && (
<ul className="divide-y divide-[var(--color-border)] text-sm">
{shown.map((sheet) => (
<SheetItem key={sheet.sheet_id} sheet={sheet} editor={editor} />
))}
</ul>
)}
{state.status === 'ready' && (
<Link to="/app/admin/sheets" className={LINK}>
{t('admin.home.all_sheets')}
</Link>
)}
</Card>
)
}
function EntryCard({
id,
title,
body,
to,
}: {
id: string
title: string
body: string
to: string
}) {
const t = useT()
return (
<Card as="section" aria-labelledby={id} className="space-y-3 p-5 sm:p-6">
<h2 id={id} className="font-serif text-xl text-[var(--color-ink)]">
{title}
</h2>
<p className="text-sm text-[var(--color-ink-muted)]">{body}</p>
<ButtonLink to={to} variant="secondary" size="sm" aria-describedby={id}>
{t('admin.home.open')}
</ButtonLink>
</Card>
)
}
/**
* /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 <PlaceholderPage titleKey="shell.nav.admin" />
const t = useT()
const heading = usePageHeading()
const permissions = useAdminPermissions()
return (
<div className="space-y-5">
<header className="space-y-1">
<h1
ref={heading}
tabIndex={-1}
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
>
{t('shell.nav.admin')}
</h1>
<p className="text-sm text-[var(--color-ink-muted)]">
{permissionsLine(t, permissions)}
</p>
</header>
<div className="grid gap-4 md:grid-cols-2">
<SheetsCard editor={permissions.editor} />
<EntryCard
id="admin-species-title"
title={t('admin.species.title')}
body={t('admin.home.species_body')}
to="/app/admin/species"
/>
{permissions.owner && (
<EntryCard
id="admin-access-title"
title={t('admin.access.title')}
body={t('admin.home.access_body')}
to="/app/admin/access"
/>
)}
</div>
</div>
)
}
@@ -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<Outcome, null>> {
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 <PlaceholderPage titleKey="admin.sheets.new" />
const t = useT()
const heading = usePageHeading()
const navigate = useNavigate()
const locale = useLocaleStore((s) => s.locale)
const species = useAdminQuery('species', listCatalogSpecies)
const [values, setValues] = useState<SheetFormValues>(EMPTY)
const [slugEdited, setSlugEdited] = useState(false)
const [errors, setErrors] = useState<FieldErrors<keyof SheetFormValues>>({})
const [errorRound, setErrorRound] = useState(0)
const [outcome, setOutcome] = useState<Outcome>(null)
const [pending, setPending] = useState(false)
const [dialog, setDialog] = useState<SpeciesDialogMode | null>(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 <AccessDenied />
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) => (
<FormField id={fieldId(key)} label={label} error={err(key)}>
<Input
id={fieldId(key)}
value={values[key]}
onChange={(e) => set(key)(e.target.value)}
maxLength={120}
aria-invalid={Boolean(errors[key])}
aria-describedby={describedBy(key)}
/>
</FormField>
)
return (
<div className="space-y-5">
<h1
ref={heading}
tabIndex={-1}
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
>
{t('admin.sheets.new')}
</h1>
<Card className="p-5 sm:p-6">
<form onSubmit={(e) => void submit(e)} noValidate className="space-y-5">
<p className="text-sm text-[var(--color-ink-muted)]">
{t('admin.sheet_form.lede')}
</p>
<div className="space-y-2">
<FormField
id={fieldId('species_id')}
label={t('admin.sheet_form.species')}
hint={t('admin.sheet_form.species_hint')}
error={err('species_id')}
>
<Select
id={fieldId('species_id')}
value={values.species_id}
onChange={(e) => set('species_id')(e.target.value)}
aria-invalid={Boolean(errors.species_id)}
aria-describedby={describedBy(
'species_id',
t('admin.sheet_form.species_hint'),
)}
>
<option value="">{t('admin.sheet_form.species_choose')}</option>
{rows.map((row) => (
<option key={row.id} value={row.id}>
{row.active
? speciesName(row, locale)
: t('admin.sheet_form.species_inactive').replace(
'{name}',
speciesName(row, locale),
)}
</option>
))}
</Select>
</FormField>
{species.state.status === 'loading' && (
<p
role="status"
className="text-sm text-[var(--color-ink-muted)]"
>
{t('admin.species.loading')}
</p>
)}
{species.state.status === 'error' && (
<Notice tone="error">
{failureMessage(t, species.state.failure)}
</Notice>
)}
<Button
type="button"
variant="secondary"
size="sm"
onClick={() => setDialog({ kind: 'create' })}
>
{t('admin.species.new')}
</Button>
</div>
{textField('name_fr', t('admin.sheet_form.name_fr'))}
{textField('name_en', t('admin.sheet_form.name_en'))}
<FormField
id={fieldId('slug')}
label={t('admin.sheet_form.slug')}
hint={t('admin.sheet_form.slug_hint')}
error={err('slug')}
>
<Input
id={fieldId('slug')}
value={values.slug}
onChange={(e) => {
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'),
)}
/>
</FormField>
{outcome?.kind === 'core_unavailable' && (
<Notice tone="error">
{coreFailureMessage(t, 'sheet.core_unavailable')}
</Notice>
)}
{outcome?.kind === 'failure' && (
<Notice tone="error">{failureMessage(t, outcome.failure)}</Notice>
)}
<div className="flex flex-wrap justify-end gap-2">
<Link
to="/app/admin/sheets"
className={buttonClassName('ghost', 'md', 'min-h-11')}
>
{t('common.cancel')}
</Link>
<Button type="submit" className="min-h-11" aria-disabled={pending}>
{pending
? t('admin.sheet_form.creating')
: t('admin.sheet_form.submit')}
</Button>
</div>
</form>
</Card>
<SpeciesDialog
mode={dialog}
onClose={() => setDialog(null)}
onSaved={speciesSaved}
/>
</div>
)
}
@@ -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<typeof useT>
/** 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 (
<li className="space-y-1 px-4 py-3">
<p className="flex flex-wrap items-center gap-2">
<span className="font-medium text-[var(--color-ink)]">
{t('admin.overview.version').replace(
'{number}',
String(version.version_number),
)}
</span>
<Badge tone={VERSION_TONE[version.status]}>
{t(`admin.version_status.${version.status}`)}
</Badge>
<span className="text-sm text-[var(--color-ink-muted)]">
{t('admin.overview.revision').replace(
'{revision}',
String(version.revision),
)}
</span>
</p>
{version.change_note && (
<p className="text-sm text-[var(--color-ink)]">{version.change_note}</p>
)}
<p className="text-sm text-[var(--color-ink-muted)]">
{lines.join(' · ')}
</p>
</li>
)
}
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 (
<li className="space-y-1 px-4 py-3">
<p className="flex flex-wrap items-center gap-2">
<span className="font-medium text-[var(--color-ink)]">
{t('admin.overview.round').replace('{round}', String(round.round))}
</span>
<Badge tone={ROUND_TONE[round.status]}>{label.title}</Badge>
<span className="text-sm text-[var(--color-ink-muted)]">
{t('admin.overview.version').replace(
'{number}',
String(round.version_number),
)}
</span>
</p>
{label.cause && (
<p className="text-sm text-[var(--color-ink)]">{label.cause}</p>
)}
{lines.length > 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{lines.join(' · ')}
</p>
)}
</li>
)
}
function Section({
id,
title,
empty,
children,
}: {
id: string
title: string
empty: string | null
children: ReactNode
}) {
return (
<section aria-labelledby={id} className="space-y-3">
<h2 id={id} className="font-serif text-xl text-[var(--color-ink)]">
{title}
</h2>
{empty ? (
<p className="text-sm text-[var(--color-ink-muted)]">{empty}</p>
) : (
<ul className="divide-y divide-[var(--color-border)] rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)]">
{children}
</ul>
)}
</section>
)
}
/** 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 (
<Card as="section" className="space-y-3 p-5 sm:p-6">
<h1
ref={heading}
tabIndex={-1}
className="outline-none font-serif text-2xl text-[var(--color-ink)]"
>
{t('admin.overview.not_found_title')}
</h1>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('admin.overview.not_found_body')}
</p>
<ButtonLink to="/app/admin/sheets" variant="secondary">
{t('admin.overview.back')}
</ButtonLink>
</Card>
)
}
/**
* /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 <PlaceholderPage titleKey="admin.sheets.title" />
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 <SheetNotFound />
if (state.status === 'error' && isRightsRefusal(state.failure))
return <AccessDenied />
if (state.status === 'loading') {
return (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('admin.overview.loading')}
</p>
)
}
if (state.status === 'error') {
return (
<div className="space-y-3">
<Notice tone="error">{failureMessage(t, state.failure)}</Notice>
<Button type="button" variant="secondary" onClick={refresh}>
{t('common.retry')}
</Button>
</div>
)
}
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 (
<div className="space-y-6">
<header className="space-y-2">
<h1
ref={heading}
tabIndex={-1}
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
>
{localized(sheet.name, locale)}
</h1>
<p className="flex flex-wrap items-center gap-2">
<SheetBadges sheet={sheet} />
</p>
<p className="text-sm text-[var(--color-ink-muted)]">
{facts.join(' · ')}
</p>
<div className="flex flex-wrap items-start gap-3 pt-1">
{sheet.historical && editor && (
<WorkingCopyAction
slug={sheet.slug}
sourceVersionId={sheet.latest_version?.version_id ?? null}
copyActive={sheet.working_copy_active === true}
/>
)}
{sheet.current_version && (
<ButtonLink
to={`/app/anatomy/${sheet.sheet_id}`}
variant="secondary"
size="sm"
>
{t('admin.overview.to_catalogue')}
</ButtonLink>
)}
</div>
</header>
<Section
id="sheet-versions-title"
title={t('admin.overview.versions')}
empty={
sheet.versions.length === 0 ? t('admin.overview.no_versions') : null
}
>
{sheet.versions.map((version) => (
<VersionItem
key={version.version_id}
version={version}
t={t}
locale={locale}
/>
))}
</Section>
<Section
id="sheet-rounds-title"
title={t('admin.overview.rounds')}
empty={sheet.rounds.length === 0 ? t('admin.overview.no_rounds') : null}
>
{sheet.rounds.map((round) => (
<RoundItem
key={round.review_id}
round={round}
t={t}
locale={locale}
/>
))}
</Section>
</div>
)
}
@@ -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<typeof useT>
/** 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 (
<li>
<Link
to={`/app/admin/sheets/${sheet.sheet_id}`}
className="flex min-h-11 flex-col gap-1 rounded-xl px-4 py-3 hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
>
<span className="flex flex-wrap items-center gap-2">
<span className="min-w-0 font-medium text-[var(--color-ink)]">
{localized(sheet.name, locale)}
</span>
<SheetBadges sheet={sheet} />
</span>
<span className="text-sm text-[var(--color-ink-muted)]">
{[
speciesLabel(sheet.species_id, species, locale),
...details(t, sheet),
].join(' · ')}
</span>
</Link>
</li>
)
}
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 (
<FormField id={`filter-${id}`} label={label}>
<Select
id={`filter-${id}`}
value={value}
onChange={(e) => onChange(e.target.value)}
>
<option value="">{t('admin.sheets.filter.all')}</option>
{options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</Select>
</FormField>
)
}
/** /app/admin/sheets (§11.1): every official sheet with its badges and the four filters. */
export default function AdminSheetsRoute() {
return <PlaceholderPage titleKey="admin.sheets.title" />
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<SheetFilters>(NO_FILTER)
if (state.status === 'error' && isRightsRefusal(state.failure))
return <AccessDenied />
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 (
<div className="space-y-5">
<header className="flex flex-wrap items-center justify-between gap-3">
<h1
ref={heading}
tabIndex={-1}
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
>
{t('admin.sheets.title')}
</h1>
{editor && (
<ButtonLink to="/app/admin/sheets/new" className="min-h-11">
{t('admin.sheets.new')}
</ButtonLink>
)}
</header>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<Filter
id="species"
label={t('admin.sheets.filter.species')}
value={filters.species}
options={speciesOptions}
onChange={set('species')}
/>
<Filter
id="sheetStatus"
label={t('admin.sheets.filter.sheet_status')}
value={filters.sheetStatus}
options={options('admin.sheet_status', SHEET_STATUSES)}
onChange={set('sheetStatus')}
/>
<Filter
id="versionStatus"
label={t('admin.sheets.filter.version_status')}
value={filters.versionStatus}
options={options('admin.version_status', VERSION_STATUSES)}
onChange={set('versionStatus')}
/>
<Filter
id="roundStatus"
label={t('admin.sheets.filter.round_status')}
value={filters.roundStatus}
options={options('admin.round_status', ROUND_STATUSES)}
onChange={set('roundStatus')}
/>
</div>
{state.status === 'loading' && (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('admin.sheets.loading')}
</p>
)}
{state.status === 'error' && (
<div className="space-y-3">
<Notice tone="error">{failureMessage(t, state.failure)}</Notice>
<Button type="button" variant="secondary" onClick={refresh}>
{t('common.retry')}
</Button>
</div>
)}
{state.status === 'ready' && shown.length === 0 && (
<p
role="status"
className="rounded-2xl border border-dashed border-[var(--color-border)] p-6 text-center text-[var(--color-ink)]"
>
{t(
state.data.sheets.length === 0
? 'admin.sheets.empty'
: 'admin.sheets.no_match',
)}
</p>
)}
{shown.length > 0 && (
<ul
aria-label={t('admin.sheets.results_label')}
className="divide-y divide-[var(--color-border)] rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)]"
>
{shown.map((sheet) => (
<SheetRow
key={sheet.sheet_id}
sheet={sheet}
species={species}
t={t}
/>
))}
</ul>
)}
</div>
)
}
@@ -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<typeof useT>
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 (
<li className="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
<div className="min-w-0 space-y-1">
<p className="flex flex-wrap items-center gap-2">
<span className="font-medium text-[var(--color-ink)]">{name}</span>
<Badge tone={species.active ? 'accent' : 'neutral'}>
{t(
species.active
? 'admin.species.state.active'
: 'admin.species.state.inactive',
)}
</Badge>
</p>
<p className="text-sm text-[var(--color-ink-muted)]">
{[
species.id,
locale === 'fr' ? species.name_en : species.name_fr,
t('admin.species.order_value').replace(
'{order}',
String(species.sort_order),
),
].join(' · ')}
</p>
</div>
<div className="flex flex-wrap gap-2">
{/* Matrix §5.4: the editor edits inactive rows, the owner activates and renames. */}
{!species.active && permissions.editor && (
<Button
type="button"
variant="secondary"
size="sm"
aria-label={named('admin.species.edit_named')}
onClick={() => actions.onEdit({ kind: 'edit', species })}
>
{t('admin.species.edit')}
</Button>
)}
{!species.active && permissions.owner && (
<Button
type="button"
size="sm"
aria-label={named('admin.species.activate.action_named')}
onClick={() => actions.onActivate(species)}
>
{t('admin.species.activate.action')}
</Button>
)}
{species.active && permissions.owner && (
<Button
type="button"
variant="secondary"
size="sm"
aria-label={named('admin.species.rename_named')}
onClick={() => actions.onEdit({ kind: 'rename', species })}
>
{t('admin.species.rename')}
</Button>
)}
</div>
</li>
)
}
/** /app/admin/species (§7.2, S1): active and inactive species, the actions each role may take. */
export default function AdminSpeciesRoute() {
return <PlaceholderPage titleKey="admin.species.title" />
const t = useT()
const heading = usePageHeading()
const permissions = useAdminPermissions()
const { state, refresh } = useAdminQuery('species', listCatalogSpecies)
const [dialog, setDialog] = useState<SpeciesDialogMode | null>(null)
const [activating, setActivating] = useState<CatalogSpecies | null>(null)
const [done, setDone] = useState<string | null>(null)
if (state.status === 'error' && isRightsRefusal(state.failure))
return <AccessDenied />
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 (
<div className="space-y-5">
<header className="flex flex-wrap items-center justify-between gap-3">
<div className="space-y-1">
<h1
ref={heading}
tabIndex={-1}
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
>
{t('admin.species.title')}
</h1>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('admin.species.lede')}
</p>
</div>
{permissions.editor && (
<Button
type="button"
className="min-h-11"
onClick={() => actions.onEdit({ kind: 'create' })}
>
{t('admin.species.new')}
</Button>
)}
</header>
{done && <Notice tone="success">{t(done)}</Notice>}
{state.status === 'loading' && (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('admin.species.loading')}
</p>
)}
{state.status === 'error' && (
<div className="space-y-3">
<Notice tone="error">{failureMessage(t, state.failure)}</Notice>
<Button type="button" variant="secondary" onClick={refresh}>
{t('common.retry')}
</Button>
</div>
)}
{state.status === 'ready' && state.data.length === 0 && (
<p
role="status"
className="rounded-2xl border border-dashed border-[var(--color-border)] p-6 text-center text-[var(--color-ink)]"
>
{t('admin.species.empty')}
</p>
)}
{state.status === 'ready' && state.data.length > 0 && (
<ul
aria-label={t('admin.species.title')}
className="divide-y divide-[var(--color-border)] rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)]"
>
{state.data.map((species) => (
<SpeciesRow
key={species.id}
species={species}
t={t}
actions={actions}
/>
))}
</ul>
)}
<SpeciesDialog
mode={dialog}
onClose={() => setDialog(null)}
onSaved={saved}
/>
<ActivateSpeciesDialog
species={activating}
onClose={() => setActivating(null)}
onActivated={activated}
/>
</div>
)
}
@@ -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<string | null>(null)
const shown = filterCatalog(entries, query, speciesId)
const nameOf = (id: string) => speciesName(species, id, null, locale)
return (
<>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
<Input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
aria-label={t('catalogue.search')}
placeholder={t('catalogue.search')}
maxLength={100}
autoComplete="off"
className="sm:max-w-sm"
/>
<div role="group" aria-label={t('catalogue.species_filter')} className="flex flex-wrap gap-2">
<Chip active={speciesId === null} onClick={() => setSpeciesId(null)}>
{t('catalogue.all_species')}
</Chip>
{catalogSpecies(entries, species).map((id) => (
<Chip key={id} active={speciesId === id} onClick={() => setSpeciesId(id)}>
{nameOf(id)}
</Chip>
))}
</div>
</div>
{shown.length === 0 ? (
<div
role="status"
className="space-y-2 rounded-2xl border border-dashed border-[var(--color-border)] p-6"
>
<p className="text-[var(--color-ink)]">
{entries.length === 0 ? t('catalogue.empty') : t('catalogue.no_results')}
</p>
{entries.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">{t('catalogue.empty_hint')}</p>
)}
</div>
) : (
<ul aria-label={t('catalogue.results')} className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
{shown.map((entry) => (
<CatalogueCard key={entry.sheet_id} entry={entry} speciesName={nameOf(entry.species_id)} />
))}
</ul>
)}
</>
)
}
/**
* /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 <PlaceholderPage titleKey="shell.nav.anatomy" />
const t = useT()
const heading = usePageHeading()
const { state, retry } = useCatalogue()
if (state.status === 'error' && state.failure === 'denied') return <AccessDenied />
return (
<div className="space-y-5">
<header className="space-y-1">
<h1
ref={heading}
tabIndex={-1}
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
>
{t('shell.nav.anatomy')}
</h1>
<p className="text-sm text-[var(--color-ink-muted)]">{t('catalogue.lede')}</p>
</header>
{state.status === 'loading' && (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('catalogue.loading')}
</p>
)}
{state.status === 'error' && state.failure !== 'denied' && (
<CatalogueFailureNotice failure={state.failure} onRetry={retry} />
)}
{state.status === 'ready' && <CatalogueList entries={state.entries} species={state.species} />}
</div>
)
}
@@ -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 (
<div
role="tablist"
aria-label={t('catalogue.views')}
onKeyDown={onKeyDown}
className="flex gap-1 overflow-x-auto border-b border-[var(--color-border)]"
>
{views.map((view) => {
const active = view.id === viewId
return (
<button
key={view.id}
id={`catalogue-tab-${view.id}`}
type="button"
role="tab"
aria-selected={active}
aria-controls="catalogue-view"
tabIndex={active ? 0 : -1}
onClick={() => onView(view.id)}
className={`-mb-px min-h-11 whitespace-nowrap border-b-2 px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] ${
active
? 'border-[var(--color-accent)] font-medium text-[var(--color-accent-strong)]'
: 'border-transparent text-[var(--color-ink-muted)] hover:text-[var(--color-ink)]'
}`}
>
{pickLabel(view.name, locale)}
</button>
)
})}
</div>
)
}
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<string | null>(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 (
<div className="space-y-5">
<nav aria-label={t('catalogue.breadcrumb')} className="text-sm text-[var(--color-ink-muted)]">
<Link to="/app/anatomy" className="underline-offset-2 hover:underline">
{t('shell.nav.anatomy')}
</Link>
<span aria-hidden="true"> › </span>
</nav>
<div className="grid gap-5 lg:grid-cols-[minmax(0,1fr)_20rem]">
<div className="min-w-0 space-y-4">
<header className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0 space-y-1">
<h1
ref={heading}
tabIndex={-1}
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
>
{pickLabel(document.name, locale)}
</h1>
<VersionLine sheetId={version.sheet_id} versions={versions} shownId={version.version_id} />
</div>
{editor && (
<ButtonLink
to={`/app/admin/sheets/${version.sheet_id}`}
variant="secondary"
className="min-h-11 gap-2"
>
<Icon name="shield" size={18} />
{t('catalogue.open_admin')}
</ButtonLink>
)}
</header>
{document.views.length > 0 && view && (
<>
<ViewTabs state={state} viewId={viewId} onView={setViewId} />
<div id="catalogue-view" role="tabpanel" aria-labelledby={`catalogue-tab-${viewId}`}>
<CatalogueCanvas
preview={preview}
viewId={viewId}
viewName={pickLabel(view.name, locale)}
selectedId={selectedId}
onAnnotation={onAnnotation}
/>
</div>
</>
)}
</div>
<aside className="space-y-4">
<ZonePanel state={state} viewId={viewId} selectedId={selectedId} onSelect={onAnnotation} />
<ReferencesCard references={document.references} />
<DisclaimerNotice document={document} />
</aside>
</div>
</div>
)
}
/**
* /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 <AccessDenied />
return <SheetVersionPage key={`${sheetId}/${number ?? ''}`} sheetId={sheetId} number={number} />
}
function SheetVersionPage({ sheetId, number }: { sheetId: string; number: number | null }) {
const t = useT()
const { state, retry } = useSheetVersion(sheetId, number)
if (state.status === 'loading') {
return (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('catalogue.loading_sheet')}
</p>
)
}
if (state.status === 'error') {
if (state.failure === 'denied') return <AccessDenied />
return <CatalogueFailureNotice failure={state.failure} onRetry={retry} />
}
return (
<LoadedSheet
versions={state.versions}
version={state.version}
preview={state.preview}
state={state.state}
/>
)
}
+2 -2
View File
@@ -14,7 +14,7 @@ const CAPABILITIES: ReadonlySet<OwnCatalogGrant['kind']> = 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'),
+130
View File
@@ -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<typeof CatalogEntrySchema>
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<typeof VersionAnswerSchema>
function parsed<T>(schema: z.ZodType<T>, 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<CatalogEntry[]> {
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<PreviewDrawing[]> {
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<VersionRead> {
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<VersionLoad> {
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) }
}
+60
View File
@@ -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.<kind>` 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<SheetFailureKind> = new Set([
'rights.catalog',
'not_found',
'forbidden',
'authentication_required',
])
const PASSED_THROUGH: ReadonlySet<SheetFailureKind> = 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<string> = new Set([
'drawing_missing',
'drawing_hash_mismatch',
'fingerprint_mismatch',
'invalid_document',
'caps',
])
/**
* A refusal of the core's `PreviewBuilder` (`<kind>: <detail>`), 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'
}
+63
View File
@@ -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})`
}
+99
View File
@@ -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<PreviewState> {
return this.call<PreviewState>('preview.state', {})
}
/** The composed view (drawing framed, annotation layer, ids scoped per view). */
canvas(viewId: string): CoreOutcome<string> {
const view = this.call<CanvasView>('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<T>(op: string, input: unknown): CoreOutcome<T> {
const handle = this.current()
if (!handle.ok) return handle
return this.runtime.invoke(() =>
parseOutcome<T>(handle.value.call(op, JSON.stringify(input))),
)
}
private current(): CoreOutcome<GluePreviewSheet> {
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<GluePreviewSheet>((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 }
})
}
}
+56
View File
@@ -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<CardDetails | null>(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
}
+81
View File
@@ -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<ReturnType<typeof getSupabaseClient>>,
): Promise<SpeciesLabel[]> {
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<CatalogueState>({ 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))]
}
+159
View File
@@ -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<HTMLElement | null>, resetKey: string) {
const [framing, setFraming] = useState<Framing>(FIT)
const pointers = useRef(new Map<number, Point>())
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<string, () => 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,
},
}
}
+91
View File
@@ -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<SheetVersionState>({ 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 }
}
+16
View File
@@ -0,0 +1,16 @@
import type { useT } from '@/i18n/useT'
type Translate = ReturnType<typeof useT>
/** « 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))
}
@@ -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<SheetFailureKind | null>(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 (
<Dialog
open={species !== null}
onClose={close}
title={t('admin.species.activate.title').replace('{name}', name)}
description={
<p className="text-sm text-[var(--color-ink-muted)]">
{t('admin.species.activate.body')}
</p>
}
size="sm"
>
{failure && (
<Notice tone="error" className="mt-3">
{failureMessage(t, failure)}
</Notice>
)}
<div className="mt-4 flex flex-wrap justify-end gap-2">
<Button
type="button"
variant="ghost"
onClick={close}
aria-disabled={pending}
>
{t('common.cancel')}
</Button>
<Button
type="button"
onClick={() => void confirm()}
aria-disabled={pending}
>
{pending
? t('admin.species.activate.pending')
: t('admin.species.activate.confirm')}
</Button>
</div>
</Dialog>
)
}
+203
View File
@@ -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<typeof useT>
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 (
<li className="space-y-2 px-4 py-3">
<div className="flex flex-wrap items-center gap-2">
<span className="min-w-0 font-medium text-[var(--color-ink)]">
{holder(t, grant)}
</span>
<Badge>{t(`admin.grant_kind.${grant.kind}`)}</Badge>
<Badge tone={STATE_TONE[grant.state]}>
{t(`admin.grant_state.${grant.state}`)}
</Badge>
{live && !grant.effective && (
<Badge tone="warn">{t('admin.access.list.suspended')}</Badge>
)}
</div>
<dl className="grid gap-1 text-sm sm:grid-cols-[auto_1fr] sm:gap-x-3">
<dt className="text-[var(--color-ink-muted)]">
{t('admin.access.form.reason')}
</dt>
<dd className="text-[var(--color-ink)] break-words">{grant.reason}</dd>
{grant.verification_note && (
<>
<dt className="text-[var(--color-ink-muted)]">
{t('admin.access.form.note')}
</dt>
<dd className="text-[var(--color-ink)] break-words">
{grant.verification_note}
</dd>
</>
)}
{grant.revoked_at && (
<>
<dt className="text-[var(--color-ink-muted)]">
{t('admin.access.list.revoked_on').replace(
'{date}',
formatDay(grant.revoked_at, locale),
)}
</dt>
<dd className="text-[var(--color-ink)] break-words">
{grant.revocation_reason}
</dd>
</>
)}
</dl>
<p className="text-sm text-[var(--color-ink-muted)]">{`${granted} · ${expiry}`}</p>
{live && (
<Button type="button" variant="secondary" size="sm" onClick={onRevoke}>
{t('admin.access.revoke.action')}
</Button>
)}
</li>
)
}
/**
* 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<GrantState | ''>('')
const [revoking, setRevoking] = useState<CatalogGrant | null>(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 (
<section aria-labelledby="grants-title" className="space-y-3">
<h2
id="grants-title"
className="font-serif text-xl text-[var(--color-ink)]"
>
{t('admin.access.list.title')}
</h2>
<div className="max-w-xs">
<FormField id="grant-state" label={t('admin.access.list.filter')}>
<Select
id="grant-state"
value={state}
onChange={(e) => setState(e.target.value as GrantState | '')}
>
<option value="">{t('admin.access.list.all')}</option>
{GRANT_STATES.map((value) => (
<option key={value} value={value}>
{t(`admin.grant_state.${value}`)}
</option>
))}
</Select>
</FormField>
</div>
{done && <Notice tone="success">{t('admin.access.revoke.done')}</Notice>}
{shown.length === 0 ? (
<p
role="status"
className="rounded-2xl border border-dashed border-[var(--color-border)] p-6 text-center text-[var(--color-ink)]"
>
{t(
grants.length === 0
? 'admin.access.list.empty'
: 'admin.access.list.no_match',
)}
</p>
) : (
<ul
aria-label={t('admin.access.list.title')}
className="divide-y divide-[var(--color-border)] rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)]"
>
{shown.map((grant) => (
<GrantItem
key={grant.id}
grant={grant}
t={t}
locale={locale}
onRevoke={() => {
setDone(false)
setRevoking(grant)
}}
/>
))}
</ul>
)}
<RevokeGrantDialog
grant={revoking}
subject={subject}
onClose={() => setRevoking(null)}
onRevoked={revoked}
/>
</section>
)
}
@@ -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<typeof useT>
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) => (
<Badge tone={ok ? 'accent' : 'warn'}>{t(ok ? yes : no)}</Badge>
)
return (
<div className="space-y-2 rounded-xl border border-[var(--color-border)] p-4">
<p className="font-medium text-[var(--color-ink)]">
{account.display_name || t('admin.person.unnamed')}
</p>
<div className="flex flex-wrap gap-2">
{!account.active && (
<Badge tone="danger">{t('admin.access.account.inactive')}</Badge>
)}
{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',
)}
</div>
<p className="text-sm text-[var(--color-ink-muted)]">
{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')}
</p>
</div>
)
}
function useLookup() {
const [email, setEmail] = useState('')
const [account, setAccount] = useState<CatalogAccount | null>(null)
const [failure, setFailure] = useState<SheetFailureKind | null>(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<GrantFormValues>(EMPTY)
const [errors, setErrors] = useState<FieldErrors<keyof GrantFormValues>>({})
const [failure, setFailure] = useState<SheetFailureKind | null>(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 (
<Card
as="section"
aria-labelledby="grant-title"
className="space-y-4 p-5 sm:p-6"
>
<h2
id="grant-title"
className="font-serif text-xl text-[var(--color-ink)]"
>
{t('admin.access.grant_title')}
</h2>
<form
onSubmit={(e) => void lookup.find(e)}
noValidate
className="grid gap-3 sm:grid-cols-[1fr_auto] sm:items-end"
>
<FormField
id="grant-email"
label={t('admin.access.lookup.email')}
hint={t('admin.access.lookup.hint')}
>
<Input
id="grant-email"
type="email"
value={lookup.email}
onChange={(e) => lookup.setEmail(e.target.value)}
maxLength={320}
autoComplete="off"
aria-describedby="grant-email-hint"
/>
</FormField>
<Button
type="submit"
variant="secondary"
className="min-h-11"
aria-disabled={lookup.pending}
>
{lookup.pending
? t('admin.access.lookup.pending')
: t('admin.access.lookup.submit')}
</Button>
</form>
{lookup.failure && (
<Notice tone="error">
{lookup.failure === 'not_found'
? t('admin.access.lookup.not_found')
: failureMessage(t, lookup.failure)}
</Notice>
)}
{lookup.account && (
<>
<AccountCard account={lookup.account} t={t} />
<form
onSubmit={(e) => void grant(e)}
noValidate
className="space-y-4"
>
<ChoiceRadios
id="grant-kind"
legend={t('admin.access.form.kind')}
options={GRANT_KINDS.map((kind) => ({
value: kind,
label: t(`admin.grant_kind.${kind}`),
}))}
value={values.kind}
onChange={(kind) => set('kind')(kind)}
error={err('kind')}
/>
<FormField
id="grant-reason"
label={t('admin.access.form.reason')}
hint={t('admin.access.form.reason_hint')}
error={err('reason')}
>
<Textarea
id="grant-reason"
value={values.reason}
onChange={(e) => set('reason')(e.target.value)}
maxLength={GRANT_TEXT_MAX}
aria-invalid={Boolean(errors.reason)}
aria-describedby={fieldDescribedBy(
'grant-reason',
t('admin.access.form.reason_hint'),
errors.reason,
)}
/>
</FormField>
<FormField
id="grant-note"
label={t('admin.access.form.note')}
optional={capability ? undefined : t('clients.form.optional')}
hint={noteHint}
error={err('verification_note')}
>
<Textarea
id="grant-note"
value={values.verification_note}
onChange={(e) => set('verification_note')(e.target.value)}
maxLength={GRANT_TEXT_MAX}
aria-invalid={Boolean(errors.verification_note)}
aria-describedby={fieldDescribedBy(
'grant-note',
noteHint,
errors.verification_note,
)}
/>
</FormField>
<FormField
id="grant-expiry"
label={t('admin.access.form.expiry')}
optional={t('clients.form.optional')}
hint={t('admin.access.form.expiry_hint')}
error={err('expires_on')}
>
<Input
id="grant-expiry"
type="date"
min={localDateIso(new Date(Date.now() + 86_400_000))}
value={values.expires_on}
onChange={(e) => set('expires_on')(e.target.value)}
aria-invalid={Boolean(errors.expires_on)}
aria-describedby={fieldDescribedBy(
'grant-expiry',
t('admin.access.form.expiry_hint'),
errors.expires_on,
)}
/>
</FormField>
{failure === 'grant.ineligible' && (
<Notice tone="error">
<p>{t('admin.failure.grant.ineligible')}</p>
<p>{t('admin.access.ineligible_detail')}</p>
</Notice>
)}
{failure && failure !== 'grant.ineligible' && (
<Notice tone="error">{failureMessage(t, failure)}</Notice>
)}
{done && (
<Notice tone="success">{t('admin.access.granted')}</Notice>
)}
<div className="flex justify-end">
<Button
type="submit"
className="min-h-11"
aria-disabled={pending}
>
{pending
? t('admin.access.form.pending')
: t('admin.access.form.submit')}
</Button>
</div>
</form>
</>
)}
</Card>
)
}
@@ -0,0 +1,125 @@
import { useEffect, useState, type FormEvent } from 'react'
import {
classifySheetError,
revokeCatalogRight,
type CatalogGrant,
type SheetFailureKind,
} from '@faunosteo/supabase'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Notice from '@/components/ui/Notice'
import Textarea from '@/components/ui/Textarea'
import { failureMessage } from '@/admin/labels'
import { GRANT_TEXT_MAX, parseRevocation } from '@/admin/validation'
import { translateFieldError } from '@/account/validation'
import { getSupabaseClient } from '@/lib/supabase'
import { useT } from '@/i18n/useT'
export interface RevokeGrantDialogProps {
grant: CatalogGrant | null
/** The holder and the right, as the list names them. */
subject: string
onClose: () => void
/** Called once the server revoked it; the caller closes the dialog. */
onRevoked: () => void
}
/** Revocation with its required reason (§5.2): it takes effect at the holder's next request. */
export default function RevokeGrantDialog({
grant,
subject,
onClose,
onRevoked,
}: RevokeGrantDialogProps) {
const t = useT()
const [reason, setReason] = useState('')
const [error, setError] = useState<string | undefined>()
const [failure, setFailure] = useState<SheetFailureKind | null>(null)
const [pending, setPending] = useState(false)
useEffect(() => {
setReason('')
setError(undefined)
setFailure(null)
}, [grant])
const close = () => {
if (!pending) onClose()
}
async function submit(event: FormEvent) {
event.preventDefault()
const client = getSupabaseClient()
if (!grant || pending) return
const parsed = parseRevocation(reason)
if (!parsed.ok) return setError(parsed.errors.reason)
if (!client) return setFailure('unavailable')
setError(undefined)
setFailure(null)
setPending(true)
try {
await revokeCatalogRight(client, grant.id, parsed.value)
onRevoked()
} catch (caught) {
setFailure(classifySheetError(caught))
} finally {
setPending(false)
}
}
const message = translateFieldError(t, error)
return (
<Dialog
open={grant !== null}
onClose={close}
title={t('admin.access.revoke.title')}
description={
<p className="text-sm text-[var(--color-ink-muted)]">
{t('admin.access.revoke.body').replace('{subject}', subject)}
</p>
}
>
<form
onSubmit={(e) => void submit(e)}
noValidate
className="mt-3 space-y-4"
>
<FormField
id="revoke-reason"
label={t('admin.access.revoke.reason')}
error={message}
>
<Textarea
id="revoke-reason"
value={reason}
onChange={(e) => setReason(e.target.value)}
maxLength={GRANT_TEXT_MAX}
aria-invalid={Boolean(error)}
aria-describedby={fieldDescribedBy(
'revoke-reason',
undefined,
error,
)}
/>
</FormField>
{failure && <Notice tone="error">{failureMessage(t, failure)}</Notice>}
<div className="flex flex-wrap justify-end gap-2">
<Button
type="button"
variant="ghost"
onClick={close}
aria-disabled={pending}
>
{t('common.cancel')}
</Button>
<Button type="submit" variant="danger" aria-disabled={pending}>
{pending
? t('admin.access.revoke.pending')
: t('admin.access.revoke.confirm')}
</Button>
</div>
</form>
</Dialog>
)
}
@@ -0,0 +1,35 @@
import type { OfficialSheetAdminSummary } from '@faunosteo/supabase'
import Badge from '@/components/ui/Badge'
import { useT } from '@/i18n/useT'
/**
* The badges of an official sheet (§3, §11.1, board 10): « Fiche historique »,
* « Copie de travail », archived, and « N à relire » for its open rounds.
*/
export default function SheetBadges({
sheet,
}: {
sheet: Pick<
OfficialSheetAdminSummary,
'historical' | 'working_copy' | 'status' | 'open_rounds'
>
}) {
const t = useT()
return (
<>
{sheet.historical && <Badge>{t('admin.badge.historical')}</Badge>}
{sheet.working_copy && <Badge>{t('admin.badge.working_copy')}</Badge>}
{sheet.status === 'archived' && (
<Badge tone="warn">{t('admin.sheet_status.archived')}</Badge>
)}
{sheet.open_rounds > 0 && (
<Badge tone="accent">
{t('admin.badge.to_review').replace(
'{count}',
String(sheet.open_rounds),
)}
</Badge>
)}
</>
)
}
@@ -0,0 +1,206 @@
import { useEffect, useState, type FormEvent } from 'react'
import {
classifySheetError,
createSpecies,
renameSpecies,
updateInactiveSpecies,
type CatalogSpecies,
type FaunosteoClient,
type SheetFailureKind,
} from '@faunosteo/supabase'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Input from '@/components/ui/Input'
import Notice from '@/components/ui/Notice'
import { failureMessage } from '@/admin/labels'
import {
parseSpecies,
type FieldErrors,
type SpeciesFields,
type SpeciesFormValues,
} from '@/admin/validation'
import { translateFieldError } from '@/account/validation'
import { getSupabaseClient } from '@/lib/supabase'
import { useT } from '@/i18n/useT'
/**
* create: a new species, always inactive (editor). edit: names and order of
* an inactive species (editor). rename: names of an active species (owner).
* The id never changes once created (§7.2).
*/
export type SpeciesDialogMode =
| { kind: 'create' }
| { kind: 'edit'; species: CatalogSpecies }
| { kind: 'rename'; species: CatalogSpecies }
export interface SpeciesDialogProps {
mode: SpeciesDialogMode | null
onClose: () => void
/** Called with the species id once the server accepted; the caller closes the dialog. */
onSaved: (id: string) => void
}
const EMPTY: SpeciesFormValues = {
id: '',
name_fr: '',
name_en: '',
sort_order: '100',
}
function initialValues(mode: SpeciesDialogMode | null): SpeciesFormValues {
if (!mode || mode.kind === 'create') return EMPTY
const { id, name_fr, name_en, sort_order } = mode.species
return { id, name_fr, name_en, sort_order: String(sort_order) }
}
function save(
client: FaunosteoClient,
mode: SpeciesDialogMode,
fields: SpeciesFields,
) {
const { id, name_fr, name_en, sort_order } = fields
if (mode.kind === 'create')
return createSpecies(client, { id, name_fr, name_en, sort_order })
if (mode.kind === 'edit')
return updateInactiveSpecies(client, { id, name_fr, name_en, sort_order })
return renameSpecies(client, { id, name_fr, name_en })
}
export default function SpeciesDialog({
mode,
onClose,
onSaved,
}: SpeciesDialogProps) {
const t = useT()
const [values, setValues] = useState<SpeciesFormValues>(EMPTY)
const [errors, setErrors] = useState<FieldErrors<keyof SpeciesFormValues>>({})
const [failure, setFailure] = useState<SheetFailureKind | null>(null)
const [pending, setPending] = useState(false)
useEffect(() => {
setValues(initialValues(mode))
setErrors({})
setFailure(null)
}, [mode])
const set = (key: keyof SpeciesFormValues) => (value: string) =>
setValues((v) => ({ ...v, [key]: value }))
const close = () => {
if (!pending) onClose()
}
async function submit(event: FormEvent) {
event.preventDefault()
if (!mode || pending) return
// The order is not sent by a rename: a stored order outside the form's range never blocks it.
const parsed = parseSpecies(
mode.kind === 'rename' ? { ...values, sort_order: '0' } : values,
)
if (!parsed.ok) return setErrors(parsed.errors)
const client = getSupabaseClient()
if (!client) return setFailure('unavailable')
setErrors({})
setFailure(null)
setPending(true)
try {
onSaved(await save(client, mode, parsed.value))
} catch (error) {
setFailure(classifySheetError(error))
} finally {
setPending(false)
}
}
const err = (key: keyof SpeciesFormValues) =>
translateFieldError(t, errors[key])
const field = (
key: keyof SpeciesFormValues,
label: string,
hint?: string,
extra = {},
) => (
<FormField id={`species-${key}`} label={label} hint={hint} error={err(key)}>
<Input
id={`species-${key}`}
value={values[key]}
onChange={(e) => set(key)(e.target.value)}
aria-invalid={Boolean(errors[key])}
aria-describedby={fieldDescribedBy(`species-${key}`, hint, errors[key])}
autoComplete="off"
{...extra}
/>
</FormField>
)
const title = mode ? t(`admin.species.dialog.${mode.kind}_title`) : ''
return (
<Dialog
open={mode !== null}
onClose={close}
title={title}
description={
mode?.kind === 'create' ? (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('admin.species.dialog.create_body')}
</p>
) : undefined
}
>
<form
onSubmit={(e) => void submit(e)}
noValidate
className="mt-3 space-y-4"
>
{mode?.kind === 'create'
? field(
'id',
t('admin.species.field.id'),
t('admin.species.field.id_hint'),
{
maxLength: 64,
spellCheck: false,
},
)
: mode && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('admin.species.field.id_value').replace(
'{id}',
mode.species.id,
)}
</p>
)}
{field('name_fr', t('admin.species.field.name_fr'), undefined, {
maxLength: 80,
})}
{field('name_en', t('admin.species.field.name_en'), undefined, {
maxLength: 80,
})}
{mode?.kind !== 'rename' &&
field(
'sort_order',
t('admin.species.field.order'),
t('admin.species.field.order_hint'),
{
inputMode: 'numeric',
maxLength: 4,
},
)}
{failure && <Notice tone="error">{failureMessage(t, failure)}</Notice>}
<div className="flex flex-wrap justify-end gap-2">
<Button
type="button"
variant="ghost"
onClick={close}
aria-disabled={pending}
>
{t('common.cancel')}
</Button>
<Button type="submit" aria-disabled={pending}>
{pending ? t('account.saving') : t('common.save')}
</Button>
</div>
</form>
</Dialog>
)
}
@@ -0,0 +1,164 @@
import { useId, useState, type FormEvent } from 'react'
import { useNavigate } from 'react-router-dom'
import {
classifySheetError,
createSheetWorkingCopy,
type SheetFailureKind,
} from '@faunosteo/supabase'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Input from '@/components/ui/Input'
import Notice from '@/components/ui/Notice'
import { failureMessage } from '@/admin/labels'
import { SLUG_PATTERN } from '@/admin/validation'
import { getSupabaseClient } from '@/lib/supabase'
import { useT } from '@/i18n/useT'
export interface WorkingCopyActionProps {
/** The historical sheet's slug, the root of the proposed one. */
slug: string
/** The source version (the historical sheet's latest); null leaves the action off. */
sourceVersionId: string | null
/** The single slot of §14.3 is taken: the action stays visible, disabled, with its reason. */
copyActive: boolean
}
/** `<slug>-copie-de-travail`, cut so the result still fits the 80 characters of the CHECK. */
function proposedSlug(slug: string): string {
const suffix = '-copie-de-travail'
return `${slug.slice(0, 80 - suffix.length).replace(/-+$/, '')}${suffix}`
}
/**
* « Créer une copie de travail » (W1, §14.3, BDR-097), editor only, on the
* historical sheet: a slug, then `create_sheet_working_copy` on the source
* version; the new copy's overview opens (its editor arrives with V1-2.6).
*/
export default function WorkingCopyAction({
slug,
sourceVersionId,
copyActive,
}: WorkingCopyActionProps) {
const t = useT()
const navigate = useNavigate()
const reasonId = useId()
const [open, setOpen] = useState(false)
const [value, setValue] = useState('')
const [error, setError] = useState<string | undefined>()
const [failure, setFailure] = useState<SheetFailureKind | null>(null)
const [pending, setPending] = useState(false)
const start = () => {
setValue(proposedSlug(slug))
setError(undefined)
setFailure(null)
setOpen(true)
}
const close = () => {
if (!pending) setOpen(false)
}
async function submit(event: FormEvent) {
event.preventDefault()
const client = getSupabaseClient()
if (pending || !sourceVersionId) return
const typed = value.trim()
if (!SLUG_PATTERN.test(typed))
return setError(t('admin.sheet_form.error.slug'))
if (!client) return setFailure('unavailable')
setError(undefined)
setFailure(null)
setPending(true)
try {
const sheetId = await createSheetWorkingCopy(
client,
sourceVersionId,
typed,
)
setOpen(false)
navigate(`/app/admin/sheets/${sheetId}`)
} catch (caught) {
setFailure(classifySheetError(caught))
} finally {
setPending(false)
}
}
const disabled = copyActive || !sourceVersionId
return (
<div className="space-y-1">
<Button
type="button"
variant="secondary"
size="sm"
disabled={disabled}
aria-describedby={copyActive ? reasonId : undefined}
onClick={start}
>
{t('admin.working_copy.create')}
</Button>
{copyActive && (
<p id={reasonId} className="text-sm text-[var(--color-ink-muted)]">
{t('admin.working_copy.active')}
</p>
)}
<Dialog
open={open}
onClose={close}
title={t('admin.working_copy.create')}
description={
<p className="text-sm text-[var(--color-ink-muted)]">
{t('admin.working_copy.body')}
</p>
}
>
<form
onSubmit={(e) => void submit(e)}
noValidate
className="mt-3 space-y-4"
>
<FormField
id="working-copy-slug"
label={t('admin.sheet_form.slug')}
hint={t('admin.sheet_form.slug_hint')}
error={error}
>
<Input
id="working-copy-slug"
value={value}
onChange={(e) => setValue(e.target.value)}
maxLength={80}
spellCheck={false}
autoComplete="off"
aria-invalid={Boolean(error)}
aria-describedby={fieldDescribedBy(
'working-copy-slug',
t('admin.sheet_form.slug_hint'),
error,
)}
/>
</FormField>
{failure && (
<Notice tone="error">{failureMessage(t, failure)}</Notice>
)}
<div className="flex flex-wrap justify-end gap-2">
<Button
type="button"
variant="ghost"
onClick={close}
aria-disabled={pending}
>
{t('common.cancel')}
</Button>
<Button type="submit" aria-disabled={pending}>
{pending
? t('admin.working_copy.pending')
: t('admin.working_copy.confirm')}
</Button>
</div>
</form>
</Dialog>
</div>
)
}
@@ -0,0 +1,167 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import { coreRuntime, useCoreStopped } from '@/core/runtime'
import { coreFailureMessage } from '@/core/failure'
import type { CataloguePreview } from '@/catalogue/preview'
import { transformOf } from '@/catalogue/framing'
import { useFraming } from '@/catalogue/useFraming'
import { useT } from '@/i18n/useT'
export interface CatalogueCanvasProps {
preview: CataloguePreview
viewId: string
viewName: string
selectedId: string | null
onAnnotation: (annotationId: string) => void
}
type CanvasFailure = 'engine' | 'view'
const ANNOTATED = '[data-anno-id]'
const ENGINE_KINDS: ReadonlySet<string> = new Set(['core_unavailable', 'internal'])
/** The core's composed view parsed into the page (`DOMParser` runs no script), or why not. */
function buildView(
preview: CataloguePreview,
viewId: string,
): { ok: true; svg: Element } | { ok: false; failure: CanvasFailure } {
const text = preview.canvas(viewId)
if (!text.ok) {
if (import.meta.env.DEV) console.warn(`catalogue canvas: ${text.kind}`, text.detail ?? '')
return { ok: false, failure: ENGINE_KINDS.has(text.kind) ? 'engine' : 'view' }
}
const parsed = new DOMParser().parseFromString(text.value, 'image/svg+xml')
const root = parsed.documentElement
if (parsed.querySelector('parsererror') || root.localName !== 'svg') {
return { ok: false, failure: 'view' }
}
return { ok: true, svg: document.importNode(root, true) }
}
/**
* One view of a published sheet, read-only (contract §10: the editor canvas
* without observations): the core-composed tree inserted as AnatomyCanvas
* does, the selected annotation restyled in place, clicks delegated on
* `data-anno-id`. The whole drawing fits the box at opening; −, + and
* « Ajuster » (44 px), a drag, a pinch, the wheel and the keyboard scale and
* move the display only (board 03).
*/
export default function CatalogueCanvas({
preview,
viewId,
viewName,
selectedId,
onAnnotation,
}: CatalogueCanvasProps) {
const t = useT()
const viewport = useRef<HTMLDivElement | null>(null)
const host = useRef<HTMLDivElement | null>(null)
const [attempt, setAttempt] = useState(0)
const [failure, setFailure] = useState<CanvasFailure | null>(null)
const stopped = useCoreStopped()
const { framing, zoomIn, zoomOut, reset, swallowClick, handlers } = useFraming(
viewport,
viewId,
)
const retryEngine = useCallback(() => {
void coreRuntime()
.retry()
.finally(() => setAttempt((n) => n + 1))
}, [])
useEffect(() => {
const element = host.current
if (!element) return
const build = buildView(preview, viewId)
setFailure(build.ok ? null : build.failure)
element.replaceChildren(...(build.ok ? [build.svg] : []))
}, [preview, viewId, attempt])
useEffect(() => {
host.current?.querySelectorAll<Element>(ANNOTATED).forEach((el) => {
if (el.getAttribute('data-anno-id') === selectedId) el.setAttribute('data-state', 'current')
else el.removeAttribute('data-state')
})
}, [selectedId, preview, viewId, attempt])
useEffect(() => {
const element = host.current
if (!element) return
const onClick = (event: Event) => {
if (swallowClick()) return
const target = event.target instanceof Element ? event.target.closest(ANNOTATED) : null
const id = target?.getAttribute('data-anno-id')
if (id) onAnnotation(id)
}
element.addEventListener('click', onClick)
return () => element.removeEventListener('click', onClick)
}, [onAnnotation, swallowClick])
return (
<div className="space-y-2">
<div className="relative overflow-hidden rounded-xl border border-[var(--color-border)] bg-[var(--color-surface)]">
<div
ref={viewport}
tabIndex={0}
role="group"
aria-label={t('catalogue.canvas.label').replace('{view}', viewName)}
aria-describedby="catalogue-canvas-help"
data-testid="catalogue-canvas"
className="svg-canvas aspect-[4/3] w-full cursor-grab select-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--color-accent)] sm:aspect-[3/2]"
style={{ touchAction: framing.scale === 1 ? 'pan-x pan-y' : 'none' }}
{...handlers}
>
<div
ref={host}
data-testid="catalogue-canvas-drawing"
className="h-full w-full origin-top-left [&>svg]:block [&>svg]:h-full [&>svg]:w-full"
style={{ transform: transformOf(framing) }}
/>
</div>
<div className="absolute right-2 top-2 flex gap-2">
<Button
type="button"
variant="secondary"
className="h-11 min-w-11 px-0"
aria-label={t('catalogue.zoom.out')}
onClick={zoomOut}
>
−
</Button>
<Button
type="button"
variant="secondary"
className="h-11 min-w-11 px-0"
aria-label={t('catalogue.zoom.in')}
onClick={zoomIn}
>
+
</Button>
<Button type="button" variant="secondary" className="h-11 px-3" onClick={reset}>
{t('catalogue.zoom.fit')}
</Button>
</div>
{failure && (
<div className="absolute inset-0 grid place-items-center bg-[var(--color-surface)] p-4">
<div className="max-w-sm space-y-3">
<Notice tone="error">
{failure === 'view'
? t('catalogue.failure.view')
: coreFailureMessage(t, 'sheet.core_unavailable')}
</Notice>
{failure === 'engine' && !stopped && (
<Button onClick={retryEngine}>{t('sheet.core_retry')}</Button>
)}
</div>
</div>
)}
</div>
<p id="catalogue-canvas-help" className="text-sm text-[var(--color-ink-muted)]">
<span className="lg:hidden">{t('catalogue.canvas.help')}</span>
<span className="sr-only">{t('catalogue.canvas.keys')}</span>
</p>
</div>
)
}
@@ -0,0 +1,77 @@
import type { CatalogEntry } from '@/catalogue/catalogue'
import { useCardDetails } from '@/catalogue/useCardDetails'
import { versionText } from '@/catalogue/versionText'
import Badge from '@/components/ui/Badge'
import ButtonLink from '@/components/ui/ButtonLink'
import Card from '@/components/ui/Card'
import Icon from '@/components/ui/Icon'
import { pickLabel } from '@/i18n/pickLocaleLabel'
import { useLocaleStore } from '@/state/localeStore'
import { useT } from '@/i18n/useT'
type Translate = ReturnType<typeof useT>
function counted(count: number, key: string, t: Translate): string {
return t(`${key}_${count === 1 ? 'one' : 'other'}`).replace('{count}', String(count))
}
/**
* One published sheet of the catalogue (board 01): species, « Publiée », name,
* version line with the counts the core read, a thumbnail of the main view,
* « Consulter ». Until its details load (or when they cannot), the card keeps
* its name, version and link.
*/
export default function CatalogueCard({
entry,
speciesName,
}: {
entry: CatalogEntry
speciesName: string
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const details = useCardDetails(entry)
const name = pickLabel(entry.name, locale)
const line = [
versionText(entry.version_number, details?.publishedAt ?? null, locale, t),
...(details
? [
`${counted(details.viewCount, 'catalogue.card.views', t)}, ${counted(details.zoneCount, 'catalogue.card.zones', t)}`,
]
: []),
].join(' · ')
return (
<li>
<Card as="article" className="flex h-full flex-col gap-3 p-5">
<div className="flex items-center justify-between gap-2">
<Badge>{speciesName}</Badge>
<span className="inline-flex items-center gap-1 rounded-md bg-[color-mix(in_srgb,var(--severity-mild)_14%,white)] px-2 py-0.5 text-xs font-medium text-[#3f5e3f]">
<Icon name="check" size={14} />
{t('catalogue.status.published')}
</span>
</div>
<h2 className="font-serif text-xl text-[var(--color-ink)]">{name}</h2>
<p className="text-sm text-[var(--color-ink-muted)]">{line}</p>
{details?.thumbnail && (
<img
src={details.thumbnail}
alt=""
className="aspect-[16/9] w-full rounded-xl bg-[var(--color-surface-strong)] object-contain"
/>
)}
<div className="mt-auto">
<ButtonLink
to={`/app/anatomy/${entry.sheet_id}`}
variant="secondary"
className="min-h-11 gap-2"
aria-label={t('catalogue.view_sheet').replace('{name}', name)}
>
<Icon name="eye" size={18} />
{t('catalogue.view')}
</ButtonLink>
</div>
</Card>
</li>
)
}
@@ -0,0 +1,38 @@
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import type { CatalogueFailure } from '@/catalogue/failure'
import { useCoreStopped } from '@/core/runtime'
import { coreFailureMessage } from '@/core/failure'
import { useT } from '@/i18n/useT'
/**
* A catalogue page that could not load: the core's degraded notice when the
* engine did not run (none of the retry once it stopped for good), otherwise
* the closed kind's message. Both offer to try again.
*/
export default function CatalogueFailureNotice({
failure,
onRetry,
}: {
failure: Exclude<CatalogueFailure, 'denied'>
onRetry: () => void
}) {
const t = useT()
const stopped = useCoreStopped()
// Once the engine stopped for good, the stopped text replaces a retry that cannot work.
if (failure === 'core_unavailable' && stopped) {
return <Notice tone="error">{coreFailureMessage(t, 'sheet.core_unavailable')}</Notice>
}
return (
<div className="space-y-3">
<Notice tone="error">
{failure === 'core_unavailable'
? coreFailureMessage(t, 'sheet.core_unavailable')
: t(`catalogue.failure.${failure}`)}
</Notice>
<Button type="button" variant="secondary" onClick={onRetry}>
{failure === 'core_unavailable' ? t('sheet.core_retry') : t('common.retry')}
</Button>
</div>
)
}
@@ -0,0 +1,65 @@
import type { AnatomicalSheetDocument, Reference } from '@faunosteo/core-wasm/types'
import Card from '@/components/ui/Card'
import Notice from '@/components/ui/Notice'
import { pickLabel } from '@/i18n/pickLocaleLabel'
import { useLocaleStore } from '@/state/localeStore'
import { useT } from '@/i18n/useT'
/** A link only for an http(s) address: document data never becomes a `javascript:` link. */
function safeHref(reference: Reference): string | null {
const candidate = reference.url ?? (reference.doi ? `https://doi.org/${reference.doi}` : null)
if (!candidate) return null
try {
const { protocol } = new URL(candidate)
return protocol === 'https:' || protocol === 'http:' ? candidate : null
} catch {
return null
}
}
/** « Références » (board 02): every reference the sheet declares, with its link. */
export function ReferencesCard({ references }: { references: readonly Reference[] }) {
const t = useT()
return (
<Card as="section" aria-labelledby="catalogue-references" className="space-y-2 p-5">
<h2 id="catalogue-references" className="text-sm font-semibold text-[var(--color-ink)]">
{t('catalogue.references.title')}
</h2>
{references.length === 0 ? (
<p className="text-sm text-[var(--color-ink-muted)]">{t('catalogue.references.none')}</p>
) : (
<ul className="space-y-2 text-sm text-[var(--color-ink-muted)]">
{references.map((reference) => {
const href = safeHref(reference)
return (
<li key={reference.id} className="break-words">
{reference.citation}
{href && (
<>
{' '}
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-[var(--color-accent-strong)] underline"
>
{t('catalogue.references.link')}
</a>
</>
)}
</li>
)
})}
</ul>
)}
</Card>
)
}
/** The sheet's own scope disclaimer, in the page's language. */
export function DisclaimerNotice({ document }: { document: AnatomicalSheetDocument }) {
const locale = useLocaleStore((s) => s.locale)
const text = pickLabel(document.scope_disclaimer, locale)
if (!text) return null
return <Notice tone="info">{text}</Notice>
}
@@ -0,0 +1,81 @@
import { useState } from 'react'
import { Link } from 'react-router-dom'
import type { CatalogVersionItem } from '@faunosteo/supabase'
import Badge from '@/components/ui/Badge'
import { useLocaleStore } from '@/state/localeStore'
import { useT } from '@/i18n/useT'
import { versionText } from '@/catalogue/versionText'
export interface VersionLineProps {
sheetId: string
versions: readonly CatalogVersionItem[]
shownId: string
}
type Translate = ReturnType<typeof useT>
function toggleText(earlier: number, t: Translate): string {
if (earlier === 0) return t('catalogue.versions.all')
return earlier === 1
? t('catalogue.versions.earlier_one')
: t('catalogue.versions.earlier_other').replace('{count}', String(earlier))
}
/**
* The shown version, its « Retirée » mark when deprecated, and the sheet's
* other published and deprecated versions behind « N versions antérieures »,
* each linking to its own page.
*/
export default function VersionLine({ sheetId, versions, shownId }: VersionLineProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const [open, setOpen] = useState(false)
const shown = versions.find((v) => v.id === shownId)
if (!shown) return null
const earlier = versions.filter((v) => v.version_number < shown.version_number).length
return (
<div className="space-y-2">
<p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm text-[var(--color-ink-muted)]">
<span>{versionText(shown.version_number, shown.published_at, locale, t)}</span>
{shown.status === 'deprecated' && <Badge tone="warn">{t('catalogue.status.deprecated')}</Badge>}
{versions.length > 1 && (
<>
<span aria-hidden="true">·</span>
<button
type="button"
aria-expanded={open}
aria-controls="catalogue-versions"
onClick={() => setOpen((o) => !o)}
className="min-h-11 underline underline-offset-2 hover:text-[var(--color-ink)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] sm:min-h-0"
>
{toggleText(earlier, t)}
</button>
</>
)}
</p>
{open && (
<ul
id="catalogue-versions"
aria-label={t('catalogue.versions.title')}
className="divide-y divide-[var(--color-border)] rounded-xl border border-[var(--color-border)] bg-[var(--color-surface)]"
>
{versions.map((v) => (
<li key={v.id}>
<Link
to={`/app/anatomy/${sheetId}/versions/${v.version_number}`}
aria-current={v.id === shownId ? 'page' : undefined}
className="flex min-h-11 flex-wrap items-center gap-2 px-4 py-2 text-sm text-[var(--color-ink)] hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] aria-[current=page]:font-medium"
>
{versionText(v.version_number, v.published_at, locale, t)}
{v.status === 'deprecated' && (
<Badge tone="warn">{t('catalogue.status.deprecated')}</Badge>
)}
</Link>
</li>
))}
</ul>
)}
</div>
)
}
@@ -0,0 +1,131 @@
import type {
Annotation,
FindingNode,
PreviewState,
} from '@faunosteo/core-wasm/types'
import Card from '@/components/ui/Card'
import { pickLabel } from '@/i18n/pickLocaleLabel'
import type { Locale } from '@/i18n/types'
import { useLocaleStore } from '@/state/localeStore'
import { useT } from '@/i18n/useT'
export interface ZonePanelProps {
state: PreviewState
viewId: string
selectedId: string | null
onSelect: (annotationId: string) => void
}
type Translate = ReturnType<typeof useT>
/** A node and its children, read-only; a node with children opens and closes. */
function FindingItem({ node, locale }: { node: FindingNode; locale: Locale }) {
const name = pickLabel(node.name, locale)
if (node.children.length === 0) {
return <li className="py-2 text-sm text-[var(--color-ink)]">{name}</li>
}
return (
<li className="py-1">
<details>
<summary className="flex min-h-11 cursor-pointer items-center text-sm font-medium text-[var(--color-ink)]">
{name}
</summary>
<ul className="ml-4 divide-y divide-[var(--color-border)] border-l border-[var(--color-border)] pl-3">
{node.children.map((child) => (
<FindingItem key={child.id} node={child} locale={locale} />
))}
</ul>
</details>
</li>
)
}
/** « Catégorie : rachis · vertèbres T1 à T18 » from the annotation's own fields. */
function zoneLine(state: PreviewState, annotation: Annotation, locale: Locale, t: Translate) {
const { categories, vertebral_config } = state.document
const category = categories.find((c) => c.id === annotation.category_id)
const parts = category
? [t('catalogue.zone.category').replace('{name}', pickLabel(category.name, locale))]
: []
const code = annotation.kind === 'detail_trigger' ? null : annotation.vertebral_region_code
const region = vertebral_config.regions.find((r) => r.code === code)
if (region) {
parts.push(
t('catalogue.zone.vertebrae')
.replace('{first}', `${region.code}1`)
.replace('{last}', `${region.code}${region.count}`),
)
}
return parts.join(' · ')
}
/**
* The selected zone (board 02): its name, category and vertebra range, then
* the findings of its finding zone by category, browsable read-only. A select lists the
* view's zones for the keyboard and screen readers, as clicking the drawing
* does.
*/
export default function ZonePanel({ state, viewId, selectedId, onSelect }: ZonePanelProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const { document, index } = state
const annotation =
selectedId !== null && index ? document.annotations[index.annotation_by_id[selectedId]] : undefined
const zoneId = annotation && annotation.kind !== 'detail_trigger' ? annotation.finding_zone_id : null
const findingZone =
zoneId !== null && index ? document.finding_zones[index.finding_zone_by_id[zoneId]] : undefined
const choices = document.annotations.filter(
(a) => a.view_id === viewId && a.kind !== 'detail_trigger',
)
const nameOf = (id: string) => (index ? pickLabel(index.names[id], locale) : id)
return (
<Card as="section" aria-labelledby="catalogue-zone-title" className="space-y-3 p-5">
<label className="block space-y-1 text-sm">
<span className="font-medium text-[var(--color-ink)]">{t('catalogue.zone.choose')}</span>
<select
className="h-11 w-full rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)] px-3 text-sm"
value={annotation && annotation.view_id === viewId ? annotation.id : ''}
onChange={(e) => e.target.value && onSelect(e.target.value)}
>
<option value="">{t('catalogue.zone.none')}</option>
{choices.map((a) => (
<option key={a.id} value={a.id}>
{nameOf(a.id)}
</option>
))}
</select>
</label>
{annotation ? (
<div aria-live="polite" className="space-y-2">
<h2 id="catalogue-zone-title" className="font-serif text-lg text-[var(--color-ink)]">
{t('catalogue.zone.title').replace('{name}', nameOf(annotation.id))}
</h2>
<p className="text-sm text-[var(--color-ink-muted)]">
{zoneLine(state, annotation, locale, t)}
</p>
{findingZone && findingZone.categories.length > 0 ? (
findingZone.categories.map((category) => (
<section key={category.id} className="space-y-1 pt-1">
<h3 className="text-xs font-semibold uppercase tracking-wide text-[var(--color-ink-muted)]">
{pickLabel(category.name, locale)}
</h3>
<ul className="divide-y divide-[var(--color-border)]">
{category.children.map((node) => (
<FindingItem key={node.id} node={node} locale={locale} />
))}
</ul>
</section>
))
) : (
<p className="text-sm text-[var(--color-ink-muted)]">{t('catalogue.zone.no_findings')}</p>
)}
</div>
) : (
<p id="catalogue-zone-title" className="text-sm text-[var(--color-ink-muted)]">
{t('catalogue.zone.prompt')}
</p>
)}
</Card>
)
}
@@ -1,16 +0,0 @@
import { usePageHeading } from '@/app/usePageHeading'
import { useT } from '@/i18n/useT'
/**
* V1-2.5 placeholder: the heading of a catalogue or administration page that
* a later slice of the step builds (G to I). It requests nothing.
*/
export default function PlaceholderPage({ titleKey }: { titleKey: string }) {
const t = useT()
const heading = usePageHeading()
return (
<h1 ref={heading} tabIndex={-1} className="outline-none font-serif text-2xl sm:text-3xl text-[var(--color-ink)]">
{t(titleKey)}
</h1>
)
}
+260
View File
@@ -913,4 +913,264 @@ export const en: Dict = {
'mfa.failure.session_expired': 'Your session has expired. Sign in again.',
'mfa.failure.network': 'Cannot reach the server. Check your network.',
'mfa.failure.unavailable': 'Two-factor authentication is temporarily unavailable. Try again later.',
// V1-2.5 G, H: administration page, species, rights, official sheets
'admin.home.permissions': 'Your permissions: {list}',
'admin.home.permissions_none': 'none',
'admin.home.capability.sheet_editor': 'sheet editor',
'admin.home.capability.sheet_reviewer': 'reviewer',
'admin.home.capability.sheet_publisher': 'publisher',
'admin.home.owner_role': 'owner role',
'admin.home.session': 'strengthened session (two-factor authentication) active',
'admin.home.sheets_body': 'Drafts, reviews, versions.',
'admin.home.species_body': 'Catalogue species, active or not.',
'admin.home.access_body': 'Catalogue access and permissions: grant, expiry, revocation.',
'admin.home.open': 'Open',
'admin.home.all_sheets': 'All official sheets',
'admin.badge.historical': 'Historical sheet',
'admin.badge.working_copy': 'Working copy',
'admin.badge.to_review': '{count} awaiting review',
'admin.working_copy.create': 'Create a working copy',
'admin.working_copy.active': 'An active working copy already exists (one at a time).',
'admin.working_copy.body': "A new draft takes the historical sheet's content and drawings, without changing it. Choose the copy's identifier.",
'admin.working_copy.confirm': 'Create the copy',
'admin.working_copy.pending': 'Creating…',
'admin.sheet_status.active': 'Active',
'admin.sheet_status.archived': 'Archived',
'admin.sheet_status.deleted': 'Deleted',
'admin.version_status.draft': 'Draft',
'admin.version_status.published': 'Published',
'admin.version_status.deprecated': 'Withdrawn',
'admin.round_status.verifying': 'Verifying',
'admin.round_status.open': 'Awaiting review',
'admin.round_status.approved': 'Approved',
'admin.round_status.changes_requested': 'Changes requested',
'admin.round_status.withdrawn': 'Submission withdrawn',
'admin.round_status.verification_failed': 'Verification failed',
'admin.outcome.failed.title': 'Verification failed',
'admin.outcome.failed.body': 'The sheet did not pass verification.',
'admin.outcome.unavailable.title': 'Verification unavailable',
'admin.outcome.unavailable.body': 'Verification could not complete.',
'admin.person.unnamed': 'Unnamed account',
'admin.grant_kind.catalog_reader': 'Catalogue access',
'admin.grant_kind.sheet_editor': 'Sheet editor',
'admin.grant_kind.sheet_reviewer': 'Reviewer',
'admin.grant_kind.sheet_publisher': 'Publisher',
'admin.grant_state.active': 'In force',
'admin.grant_state.expiring': 'Expires within 30 days',
'admin.grant_state.expired': 'Expired',
'admin.grant_state.revoked': 'Revoked',
'admin.access.lede': 'Grant and revoke catalogue access and permissions. Every right carries a reason and stays on record.',
'admin.access.loading': 'Loading rights…',
'admin.access.grant_title': 'Grant a right',
'admin.access.lookup.email': 'Account e-mail address',
'admin.access.lookup.hint': 'The exact address the person signs in with.',
'admin.access.lookup.submit': 'Find',
'admin.access.lookup.pending': 'Searching…',
'admin.access.lookup.not_found': 'No account with this address.',
'admin.access.account.inactive': 'Account deactivated',
'admin.access.account.confirmed': 'E-mail confirmed',
'admin.access.account.unconfirmed': 'E-mail not confirmed',
'admin.access.account.factor': 'Verified factor',
'admin.access.account.no_factor': 'No verified factor',
'admin.access.account.roles': 'Platform roles: {roles}',
'admin.access.account.no_role': 'No platform role',
'admin.access.form.kind': 'Right',
'admin.access.form.reason': 'Reason',
'admin.access.form.reason_hint': 'Why this right is granted, 1,000 characters at most.',
'admin.access.form.note': 'Verification note',
'admin.access.form.note_hint': 'Required for a permission: the qualification declared and what you checked, never a certification.',
'admin.access.form.note_hint_reader': 'Optional for catalogue access.',
'admin.access.form.expiry': 'Expiry',
'admin.access.form.expiry_hint': 'The right ends at the end of this day. Without a date, it lasts until revoked.',
'admin.access.form.submit': 'Grant',
'admin.access.form.pending': 'Granting…',
'admin.access.error.kind': 'Choose a right.',
'admin.access.error.expiry': 'Choose a date after today.',
'admin.access.granted': 'Right granted.',
'admin.access.ineligible_detail': 'Conditions: an active account with a confirmed e-mail for every right; a verified authentication factor for a permission; the owner or admin platform role for Sheet editor and Publisher.',
'admin.access.list.title': 'Granted rights',
'admin.access.list.filter': 'State',
'admin.access.list.all': 'All',
'admin.access.list.empty': 'No right granted yet.',
'admin.access.list.no_match': 'No right in this state.',
'admin.access.list.granted': 'Granted on {date} by {name}',
'admin.access.list.expires': 'expires on {date}',
'admin.access.list.no_expiry': 'no expiry',
'admin.access.list.revoked_on': 'Revoked on {date}',
'admin.access.list.suspended': 'Suspended: conditions not met',
'admin.access.revoke.action': 'Revoke',
'admin.access.revoke.title': 'Revoke this right?',
'admin.access.revoke.body': "{subject}. Revocation takes effect at the account's next request and cannot be undone; a new right can be granted later.",
'admin.access.revoke.reason': 'Reason for revocation',
'admin.access.revoke.confirm': 'Revoke',
'admin.access.revoke.pending': 'Revoking…',
'admin.access.revoke.done': 'Right revoked.',
'admin.sheets.loading': 'Loading sheets…',
'admin.sheets.empty': 'No official sheet yet.',
'admin.sheets.no_match': 'No sheet matches these filters.',
'admin.sheets.results_label': 'Official sheet list',
'admin.sheets.filter.species': 'Species',
'admin.sheets.filter.sheet_status': 'Sheet status',
'admin.sheets.filter.version_status': 'Version status',
'admin.sheets.filter.round_status': 'Latest review status',
'admin.sheets.filter.all': 'All',
'admin.sheets.current_version': 'published version {number}',
'admin.sheets.no_published': 'no published version',
'admin.sheets.draft': 'draft version {number}',
'admin.sheets.latest_round': 'review no. {round}: {status}',
'admin.sheet_form.lede': 'The sheet starts empty: views, annotations and findings are entered later in the editor.',
'admin.sheet_form.species': 'Species',
'admin.sheet_form.species_hint': 'Active or not. Creating a sheet does not activate the species.',
'admin.sheet_form.species_choose': 'Choose a species',
'admin.sheet_form.species_inactive': '{name} (inactive)',
'admin.sheet_form.name_fr': 'Name (French)',
'admin.sheet_form.name_en': 'Name (English)',
'admin.sheet_form.slug': 'Identifier (slug)',
'admin.sheet_form.slug_hint': 'Lower-case letters without accents, digits and hyphens, 2 to 80 characters; unique among official sheets.',
'admin.sheet_form.submit': 'Create the sheet',
'admin.sheet_form.creating': 'Creating…',
'admin.sheet_form.error.species': 'Choose a species.',
'admin.sheet_form.error.slug': 'Lower-case letters without accents, digits and hyphens, 2 to 80 characters, not starting with a hyphen.',
'admin.overview.loading': 'Loading the sheet…',
'admin.overview.not_found_title': 'Sheet not found',
'admin.overview.not_found_body': 'This sheet does not exist or is not available with your permissions.',
'admin.overview.back': 'Back to official sheets',
'admin.overview.copy_of': 'copy of version {number} of the historical sheet',
'admin.overview.to_catalogue': 'View in the catalogue',
'admin.overview.versions': 'Versions',
'admin.overview.rounds': 'Reviews',
'admin.overview.no_versions': 'No version.',
'admin.overview.no_rounds': 'No review yet.',
'admin.overview.version': 'Version {number}',
'admin.overview.revision': 'revision {revision}',
'admin.overview.round': 'Review no. {round}',
'admin.overview.created_on': 'created on {date}',
'admin.overview.published_on': 'published on {date}',
'admin.overview.deprecated_on': 'withdrawn on {date}',
'admin.overview.source': 'based on version {number}',
'admin.overview.authors': 'authors: {names}',
'admin.overview.submitted_on': 'submitted on {date}',
'admin.overview.submitted_on_by': 'submitted on {date} by {name}',
'admin.overview.decided_on': 'decided on {date}',
'admin.overview.decided_on_by': 'decided on {date} by {name}',
'admin.overview.withdrawn_on': 'withdrawn on {date}',
'admin.species.lede': 'The species of the sheet catalogue. An inactive species does not appear in the animal forms.',
'admin.species.loading': 'Loading species…',
'admin.species.empty': 'No species.',
'admin.species.new': 'New species',
'admin.species.state.active': 'Active',
'admin.species.state.inactive': 'Inactive',
'admin.species.order_value': 'order {order}',
'admin.species.edit': 'Edit',
'admin.species.edit_named': 'Edit {name}',
'admin.species.rename': 'Rename',
'admin.species.rename_named': 'Rename {name}',
'admin.species.activate.action': 'Activate',
'admin.species.activate.action_named': 'Activate {name}',
'admin.species.activate.title': 'Activate “{name}”?',
'admin.species.activate.body': 'The animal forms will then offer this species to every account. An activated species cannot be deactivated.',
'admin.species.activate.confirm': 'Activate',
'admin.species.activate.pending': 'Activating…',
'admin.species.activate.done': 'Species activated.',
'admin.species.created': 'Species created, inactive.',
'admin.species.saved': 'Species saved.',
'admin.species.dialog.create_title': 'New species',
'admin.species.dialog.edit_title': 'Edit the species',
'admin.species.dialog.rename_title': 'Rename the species',
'admin.species.dialog.create_body': 'Created inactive: the animal forms offer it only once the owner activates it. Its identifier never changes afterwards.',
'admin.species.field.id': 'Identifier',
'admin.species.field.id_hint': 'Lower-case letters without accents, digits, hyphens and underscores, 64 characters at most; “other” is reserved.',
'admin.species.field.id_value': 'Identifier: {id}',
'admin.species.field.name_fr': 'Name (French)',
'admin.species.field.name_en': 'Name (English)',
'admin.species.field.order': 'Display order',
'admin.species.field.order_hint': 'A number from 0 to 9999, smaller first.',
'admin.species.error.id': 'Invalid identifier: lower-case letters without accents, digits, hyphens and underscores; “other” is reserved.',
'admin.species.error.order': 'A whole number from 0 to 9999.',
'admin.failure.authentication_required': 'Sign in to continue.',
'admin.failure.mfa_required': 'This action needs a session strengthened by two-factor authentication.',
'admin.failure.forbidden': 'Action not allowed.',
'admin.failure.rights.account': 'Your account must be active, with a confirmed e-mail, for this action.',
'admin.failure.rights.capability': 'Your permissions do not allow this action.',
'admin.failure.rights.mfa': 'This action needs a session strengthened by two-factor authentication.',
'admin.failure.rights.owner': 'Only the platform owner can do this.',
'admin.failure.not_found': 'Item not found or not available. Reload the page.',
'admin.failure.grant.active': 'This account already holds this right.',
'admin.failure.grant.ineligible': 'This account does not meet the conditions of this right.',
'admin.failure.grant.revoked': 'This right is already revoked.',
'admin.failure.grant.target_invalid': 'This account no longer exists.',
'admin.failure.document.shape': 'The server did not accept the sheet document.',
'admin.failure.document.schema_version': 'The server does not accept this sheet format version.',
'admin.failure.document.species': "The document's species does not match the sheet's.",
'admin.failure.document.too_large': 'The sheet document exceeds the allowed size.',
'admin.failure.sheet.species_invalid': 'This species cannot have an official sheet.',
'admin.failure.sheet.slug_taken': 'Another official sheet already uses this identifier.',
'admin.failure.species.exists': 'A species already has this identifier.',
'admin.failure.species.not_active': 'This species is not active: edit it instead of renaming it.',
'admin.failure.species.not_inactive': 'This species is already active: only the owner can rename it.',
'admin.failure.working_copy.source_invalid': 'Only a version of the historical sheet can be copied.',
'admin.failure.working_copy.exists': 'An active working copy already exists (one at a time).',
'admin.failure.working_copy.assets_missing': 'Some drawings of the historical sheet are missing from storage: no copy was created. They must be uploaded first.',
'admin.failure.invalid_input': 'A value was not accepted. Check the fields.',
'admin.failure.rate_limited': 'Too many actions in a short time. Try again in a few minutes.',
'admin.failure.conflict_retry': 'Another action was in progress. Retry.',
'admin.failure.session_expired': 'Your session has expired. Sign in again.',
'admin.failure.network': 'No connection. Check your network, then retry.',
'admin.failure.unavailable': 'The service is not answering right now. Retry.',
// V1-2.5: anatomical catalogue (slice I)
'catalogue.lede': 'Published official sheets, by species. Read-only: nothing is changed here.',
'catalogue.search': 'Search for a sheet',
'catalogue.species_filter': 'Filter by species',
'catalogue.all_species': 'All species',
'catalogue.loading': 'Loading the catalogue…',
'catalogue.results': 'Published sheets',
'catalogue.empty': 'A species appears here as soon as an official sheet is published for it.',
'catalogue.empty_hint': 'Drafts and reviews are never listed in the catalogue.',
'catalogue.no_results': 'No sheet matches this search.',
'catalogue.status.published': 'Published',
'catalogue.status.deprecated': 'Withdrawn',
'catalogue.version': 'Version {number}',
'catalogue.version_published': 'Version {number} · published on {date}',
'catalogue.card.views_one': '1 view',
'catalogue.card.views_other': '{count} views',
'catalogue.card.zones_one': '1 finding zone',
'catalogue.card.zones_other': '{count} finding zones',
'catalogue.view': 'View',
'catalogue.view_sheet': 'View {name}',
'catalogue.loading_sheet': 'Loading the sheet…',
'catalogue.breadcrumb': 'Breadcrumb',
'catalogue.open_admin': 'Open in administration',
'catalogue.versions.all': 'All versions',
'catalogue.versions.earlier_one': '1 earlier version',
'catalogue.versions.earlier_other': '{count} earlier versions',
'catalogue.versions.title': 'Sheet versions',
'catalogue.views': 'Sheet views',
'catalogue.canvas.label': 'Drawing: {view}',
'catalogue.canvas.help': 'Pinch to zoom, drag to move. Tap a zone to see its findings.',
'catalogue.canvas.keys': 'With the keyboard: arrows to move, + and − to zoom, 0 to show the whole drawing.',
'catalogue.zoom.out': 'Zoom out',
'catalogue.zoom.in': 'Zoom in',
'catalogue.zoom.fit': 'Fit',
'catalogue.zone.choose': 'Zone',
'catalogue.zone.none': 'Choose a zone',
'catalogue.zone.prompt': 'Tap a zone on the drawing, or choose it in the list, to see its findings.',
'catalogue.zone.title': 'Zone: {name}',
'catalogue.zone.category': 'Category: {name}',
'catalogue.zone.vertebrae': 'vertebrae {first} to {last}',
'catalogue.zone.no_findings': 'No findings for this zone.',
'catalogue.references.title': 'References',
'catalogue.references.none': 'This sheet cites no reference.',
'catalogue.references.link': 'Link',
'catalogue.failure.view': 'This view cannot be shown: its drawing was refused by the security checks or could not be composed.',
'catalogue.failure.network': 'Cannot reach the server. Check your network.',
'catalogue.failure.session_expired': 'Your session has expired. Sign in again.',
'catalogue.failure.rate_limited': 'Too many requests. Wait a few minutes before trying again.',
'catalogue.failure.unavailable': 'The catalogue is temporarily unavailable. Try again later.',
'catalogue.failure.drawing_missing': 'A drawing of this version cannot be found.',
'catalogue.failure.drawing_hash_mismatch': "A drawing's file content does not match its recorded SHA-256 fingerprint.",
'catalogue.failure.fingerprint_mismatch': "This version's fingerprint does not match the one recorded at its publication.",
'catalogue.failure.invalid_document': "This version's content cannot be read.",
'catalogue.failure.caps': 'This version exceeds the size limits of a sheet.',
}
+260
View File
@@ -944,4 +944,264 @@ export const fr: Dict = {
'mfa.failure.session_expired': 'Votre session a expiré. Reconnectez-vous.',
'mfa.failure.network': 'Connexion au serveur impossible. Vérifiez votre réseau.',
'mfa.failure.unavailable': 'La double authentification est momentanément indisponible. Réessayez plus tard.',
// V1-2.5 G, H: administration page, species, rights, official sheets
'admin.home.permissions': 'Vos habilitations : {list}',
'admin.home.permissions_none': 'aucune',
'admin.home.capability.sheet_editor': 'éditeur de fiches',
'admin.home.capability.sheet_reviewer': 'relecteur ou relectrice',
'admin.home.capability.sheet_publisher': 'responsable de publication',
'admin.home.owner_role': 'rôle propriétaire',
'admin.home.session': 'session renforcée (double authentification) active',
'admin.home.sheets_body': 'Brouillons, revues, versions.',
'admin.home.species_body': 'Espèces du catalogue, actives ou non.',
'admin.home.access_body': 'Accès au catalogue et habilitations : attribution, échéance, révocation.',
'admin.home.open': 'Ouvrir',
'admin.home.all_sheets': 'Toutes les fiches officielles',
'admin.badge.historical': 'Fiche historique',
'admin.badge.working_copy': 'Copie de travail',
'admin.badge.to_review': '{count} à relire',
'admin.working_copy.create': 'Créer une copie de travail',
'admin.working_copy.active': 'Une copie de travail active existe déjà (une seule à la fois).',
'admin.working_copy.body': "Un nouveau brouillon reprend le contenu et les illustrations de la fiche historique, sans la modifier. Choisissez l'identifiant de la copie.",
'admin.working_copy.confirm': 'Créer la copie',
'admin.working_copy.pending': 'Création…',
'admin.sheet_status.active': 'Active',
'admin.sheet_status.archived': 'Archivée',
'admin.sheet_status.deleted': 'Supprimée',
'admin.version_status.draft': 'Brouillon',
'admin.version_status.published': 'Publiée',
'admin.version_status.deprecated': 'Retirée',
'admin.round_status.verifying': 'Vérification en cours',
'admin.round_status.open': 'À relire',
'admin.round_status.approved': 'Approuvée',
'admin.round_status.changes_requested': 'Modifications demandées',
'admin.round_status.withdrawn': 'Soumission retirée',
'admin.round_status.verification_failed': 'Vérification échouée',
'admin.outcome.failed.title': 'Vérification échouée',
'admin.outcome.failed.body': 'La fiche ne passe pas la vérification.',
'admin.outcome.unavailable.title': 'Vérification indisponible',
'admin.outcome.unavailable.body': "La vérification n'a pas pu aboutir.",
'admin.person.unnamed': 'Compte sans nom',
'admin.grant_kind.catalog_reader': 'Accès au catalogue',
'admin.grant_kind.sheet_editor': 'Éditeur de fiches',
'admin.grant_kind.sheet_reviewer': 'Relecteur, relectrice',
'admin.grant_kind.sheet_publisher': 'Responsable de publication',
'admin.grant_state.active': 'En vigueur',
'admin.grant_state.expiring': 'Expire sous 30 jours',
'admin.grant_state.expired': 'Expiré',
'admin.grant_state.revoked': 'Révoqué',
'admin.access.lede': "Attribuer et révoquer l'accès au catalogue et les habilitations. Chaque droit porte un motif et reste tracé.",
'admin.access.loading': 'Chargement des droits…',
'admin.access.grant_title': 'Attribuer un droit',
'admin.access.lookup.email': 'Adresse e-mail du compte',
'admin.access.lookup.hint': "L'adresse exacte avec laquelle la personne se connecte.",
'admin.access.lookup.submit': 'Rechercher',
'admin.access.lookup.pending': 'Recherche…',
'admin.access.lookup.not_found': 'Aucun compte avec cette adresse.',
'admin.access.account.inactive': 'Compte désactivé',
'admin.access.account.confirmed': 'E-mail confirmé',
'admin.access.account.unconfirmed': 'E-mail non confirmé',
'admin.access.account.factor': 'Facteur vérifié',
'admin.access.account.no_factor': 'Aucun facteur vérifié',
'admin.access.account.roles': 'Rôles de plateforme : {roles}',
'admin.access.account.no_role': 'Aucun rôle de plateforme',
'admin.access.form.kind': 'Droit',
'admin.access.form.reason': 'Motif',
'admin.access.form.reason_hint': 'Pourquoi ce droit est attribué, 1 000 caractères au plus.',
'admin.access.form.note': 'Note de vérification',
'admin.access.form.note_hint': 'Obligatoire pour une habilitation : la qualification déclarée et ce que vous avez vérifié, jamais une certification.',
'admin.access.form.note_hint_reader': "Facultative pour l'accès au catalogue.",
'admin.access.form.expiry': 'Échéance',
'admin.access.form.expiry_hint': "Le droit prend fin à la fin de ce jour. Sans date, il dure jusqu'à sa révocation.",
'admin.access.form.submit': 'Attribuer',
'admin.access.form.pending': 'Attribution…',
'admin.access.error.kind': 'Choisissez un droit.',
'admin.access.error.expiry': "Choisissez une date postérieure à aujourd'hui.",
'admin.access.granted': 'Droit attribué.',
'admin.access.ineligible_detail': "Conditions : compte actif et e-mail confirmé pour tout droit ; facteur d'authentification vérifié pour une habilitation ; rôle de plateforme propriétaire ou administrateur pour Éditeur de fiches et Responsable de publication.",
'admin.access.list.title': 'Droits attribués',
'admin.access.list.filter': 'État',
'admin.access.list.all': 'Tous',
'admin.access.list.empty': 'Aucun droit attribué pour le moment.',
'admin.access.list.no_match': 'Aucun droit dans cet état.',
'admin.access.list.granted': 'Attribué le {date} par {name}',
'admin.access.list.expires': 'échéance le {date}',
'admin.access.list.no_expiry': 'sans échéance',
'admin.access.list.revoked_on': 'Révoqué le {date}',
'admin.access.list.suspended': 'Suspendu : conditions non remplies',
'admin.access.revoke.action': 'Révoquer',
'admin.access.revoke.title': 'Révoquer ce droit ?',
'admin.access.revoke.body': "{subject}. La révocation prend effet à la prochaine requête du compte et ne s'annule pas ; un nouveau droit pourra être attribué plus tard.",
'admin.access.revoke.reason': 'Motif de la révocation',
'admin.access.revoke.confirm': 'Révoquer',
'admin.access.revoke.pending': 'Révocation…',
'admin.access.revoke.done': 'Droit révoqué.',
'admin.sheets.loading': 'Chargement des fiches…',
'admin.sheets.empty': 'Aucune fiche officielle pour le moment.',
'admin.sheets.no_match': 'Aucune fiche ne correspond à ces filtres.',
'admin.sheets.results_label': 'Liste des fiches officielles',
'admin.sheets.filter.species': 'Espèce',
'admin.sheets.filter.sheet_status': 'État de la fiche',
'admin.sheets.filter.version_status': 'Statut de version',
'admin.sheets.filter.round_status': 'État de la dernière revue',
'admin.sheets.filter.all': 'Tous',
'admin.sheets.current_version': 'version publiée {number}',
'admin.sheets.no_published': 'aucune version publiée',
'admin.sheets.draft': 'brouillon version {number}',
'admin.sheets.latest_round': 'revue n° {round} : {status}',
'admin.sheet_form.lede': "La fiche démarre vide : vues, annotations et constats se saisissent ensuite dans l'éditeur.",
'admin.sheet_form.species': 'Espèce',
'admin.sheet_form.species_hint': "Active ou non. Créer une fiche n'active pas l'espèce.",
'admin.sheet_form.species_choose': 'Choisir une espèce',
'admin.sheet_form.species_inactive': '{name} (inactive)',
'admin.sheet_form.name_fr': 'Nom (français)',
'admin.sheet_form.name_en': 'Nom (anglais)',
'admin.sheet_form.slug': 'Identifiant (slug)',
'admin.sheet_form.slug_hint': 'Lettres minuscules sans accent, chiffres et tirets, 2 à 80 caractères ; unique parmi les fiches officielles.',
'admin.sheet_form.submit': 'Créer la fiche',
'admin.sheet_form.creating': 'Création…',
'admin.sheet_form.error.species': 'Choisissez une espèce.',
'admin.sheet_form.error.slug': 'Lettres minuscules sans accent, chiffres et tirets, 2 à 80 caractères, sans tiret au début.',
'admin.overview.loading': 'Chargement de la fiche…',
'admin.overview.not_found_title': 'Fiche introuvable',
'admin.overview.not_found_body': "Cette fiche n'existe pas ou n'est pas accessible avec vos habilitations.",
'admin.overview.back': 'Retour aux fiches officielles',
'admin.overview.copy_of': 'copie de la version {number} de la fiche historique',
'admin.overview.to_catalogue': 'Voir dans le catalogue',
'admin.overview.versions': 'Versions',
'admin.overview.rounds': 'Revues',
'admin.overview.no_versions': 'Aucune version.',
'admin.overview.no_rounds': 'Aucune revue pour le moment.',
'admin.overview.version': 'Version {number}',
'admin.overview.revision': 'révision {revision}',
'admin.overview.round': 'Revue n° {round}',
'admin.overview.created_on': 'créée le {date}',
'admin.overview.published_on': 'publiée le {date}',
'admin.overview.deprecated_on': 'retirée le {date}',
'admin.overview.source': 'issue de la version {number}',
'admin.overview.authors': 'auteurs : {names}',
'admin.overview.submitted_on': 'soumise le {date}',
'admin.overview.submitted_on_by': 'soumise le {date} par {name}',
'admin.overview.decided_on': 'décidée le {date}',
'admin.overview.decided_on_by': 'décidée le {date} par {name}',
'admin.overview.withdrawn_on': 'retirée le {date}',
'admin.species.lede': "Les espèces du catalogue des fiches. Une espèce inactive n'apparaît pas dans les formulaires des animaux.",
'admin.species.loading': 'Chargement des espèces…',
'admin.species.empty': 'Aucune espèce.',
'admin.species.new': 'Nouvelle espèce',
'admin.species.state.active': 'Active',
'admin.species.state.inactive': 'Inactive',
'admin.species.order_value': 'ordre {order}',
'admin.species.edit': 'Modifier',
'admin.species.edit_named': 'Modifier {name}',
'admin.species.rename': 'Renommer',
'admin.species.rename_named': 'Renommer {name}',
'admin.species.activate.action': 'Activer',
'admin.species.activate.action_named': 'Activer {name}',
'admin.species.activate.title': 'Activer « {name} » ?',
'admin.species.activate.body': 'Les formulaires des animaux proposeront ensuite cette espèce à tous les comptes. Une espèce activée ne peut pas être désactivée.',
'admin.species.activate.confirm': 'Activer',
'admin.species.activate.pending': 'Activation…',
'admin.species.activate.done': 'Espèce activée.',
'admin.species.created': 'Espèce créée, inactive.',
'admin.species.saved': 'Espèce enregistrée.',
'admin.species.dialog.create_title': 'Nouvelle espèce',
'admin.species.dialog.edit_title': "Modifier l'espèce",
'admin.species.dialog.rename_title': "Renommer l'espèce",
'admin.species.dialog.create_body': "Créée inactive : les formulaires des animaux ne la proposent qu'après son activation par le propriétaire. Son identifiant ne change plus ensuite.",
'admin.species.field.id': 'Identifiant',
'admin.species.field.id_hint': 'Lettres minuscules sans accent, chiffres, tirets et soulignés, 64 caractères au plus ; « other » est réservé.',
'admin.species.field.id_value': 'Identifiant : {id}',
'admin.species.field.name_fr': 'Nom (français)',
'admin.species.field.name_en': 'Nom (anglais)',
'admin.species.field.order': "Ordre d'affichage",
'admin.species.field.order_hint': 'Un nombre de 0 à 9999, les plus petits en premier.',
'admin.species.error.id': 'Identifiant invalide : lettres minuscules sans accent, chiffres, tirets et soulignés ; « other » est réservé.',
'admin.species.error.order': 'Un nombre entier de 0 à 9999.',
'admin.failure.authentication_required': 'Connectez-vous pour continuer.',
'admin.failure.mfa_required': 'Cette action demande une session renforcée par la double authentification.',
'admin.failure.forbidden': 'Action non autorisée.',
'admin.failure.rights.account': 'Votre compte doit être actif, avec un e-mail confirmé, pour cette action.',
'admin.failure.rights.capability': 'Vos habilitations ne permettent pas cette action.',
'admin.failure.rights.mfa': 'Cette action demande une session renforcée par la double authentification.',
'admin.failure.rights.owner': 'Action réservée au propriétaire de la plateforme.',
'admin.failure.not_found': 'Élément introuvable ou non accessible. Rechargez la page.',
'admin.failure.grant.active': 'Ce compte détient déjà ce droit.',
'admin.failure.grant.ineligible': 'Ce compte ne remplit pas les conditions de ce droit.',
'admin.failure.grant.revoked': 'Ce droit est déjà révoqué.',
'admin.failure.grant.target_invalid': "Ce compte n'existe plus.",
'admin.failure.document.shape': "Le serveur n'a pas accepté le document de la fiche.",
'admin.failure.document.schema_version': "Le serveur n'accepte pas cette version du format de fiche.",
'admin.failure.document.species': "L'espèce du document ne correspond pas à celle de la fiche.",
'admin.failure.document.too_large': 'Le document de la fiche dépasse la taille autorisée.',
'admin.failure.sheet.species_invalid': 'Cette espèce ne peut pas recevoir de fiche officielle.',
'admin.failure.sheet.slug_taken': 'Une autre fiche officielle utilise déjà cet identifiant.',
'admin.failure.species.exists': 'Une espèce porte déjà cet identifiant.',
'admin.failure.species.not_active': "Cette espèce n'est pas active : modifiez-la au lieu de la renommer.",
'admin.failure.species.not_inactive': 'Cette espèce est déjà active : seul le propriétaire peut la renommer.',
'admin.failure.working_copy.source_invalid': 'Seule une version de la fiche historique peut être copiée.',
'admin.failure.working_copy.exists': 'Une copie de travail active existe déjà (une seule à la fois).',
'admin.failure.working_copy.assets_missing': "Des illustrations de la fiche historique manquent dans le stockage : aucune copie n'a été créée. Elles doivent d'abord être téléversées.",
'admin.failure.invalid_input': "Une valeur n'a pas été acceptée. Vérifiez les champs.",
'admin.failure.rate_limited': "Trop d'actions en peu de temps. Réessayez dans quelques minutes.",
'admin.failure.conflict_retry': 'Une autre action était en cours. Réessayez.',
'admin.failure.session_expired': 'Votre session a expiré. Reconnectez-vous.',
'admin.failure.network': 'Connexion impossible. Vérifiez votre réseau, puis réessayez.',
'admin.failure.unavailable': 'Le service ne répond pas pour le moment. Réessayez.',
// V1-2.5: anatomical catalogue (slice I)
'catalogue.lede': "Les fiches officielles publiées, par espèce. Consultation seule : rien n'est modifié ici.",
'catalogue.search': 'Rechercher une fiche',
'catalogue.species_filter': 'Filtrer par espèce',
'catalogue.all_species': 'Toutes les espèces',
'catalogue.loading': 'Chargement du catalogue…',
'catalogue.results': 'Fiches publiées',
'catalogue.empty': "Une espèce apparaît ici dès qu'une fiche officielle est publiée pour elle.",
'catalogue.empty_hint': 'Les brouillons et les revues ne sont jamais listés dans le catalogue.',
'catalogue.no_results': 'Aucune fiche ne correspond à cette recherche.',
'catalogue.status.published': 'Publiée',
'catalogue.status.deprecated': 'Retirée',
'catalogue.version': 'Version {number}',
'catalogue.version_published': 'Version {number} · publiée le {date}',
'catalogue.card.views_one': '1 vue',
'catalogue.card.views_other': '{count} vues',
'catalogue.card.zones_one': '1 zone de constats',
'catalogue.card.zones_other': '{count} zones de constats',
'catalogue.view': 'Consulter',
'catalogue.view_sheet': 'Consulter {name}',
'catalogue.loading_sheet': 'Chargement de la fiche…',
'catalogue.breadcrumb': "Fil d'Ariane",
'catalogue.open_admin': "Ouvrir dans l'administration",
'catalogue.versions.all': 'Toutes les versions',
'catalogue.versions.earlier_one': '1 version antérieure',
'catalogue.versions.earlier_other': '{count} versions antérieures',
'catalogue.versions.title': 'Versions de la fiche',
'catalogue.views': 'Vues de la fiche',
'catalogue.canvas.label': 'Dessin : {view}',
'catalogue.canvas.help': 'Pincer pour zoomer, glisser pour se déplacer. Toucher une zone pour voir ses constats.',
'catalogue.canvas.keys': 'Au clavier : flèches pour se déplacer, + et − pour zoomer, 0 pour revenir au dessin entier.',
'catalogue.zoom.out': 'Zoom arrière',
'catalogue.zoom.in': 'Zoom avant',
'catalogue.zoom.fit': 'Ajuster',
'catalogue.zone.choose': 'Zone',
'catalogue.zone.none': 'Choisir une zone',
'catalogue.zone.prompt': 'Touchez une zone du dessin, ou choisissez-la dans la liste, pour voir ses constats.',
'catalogue.zone.title': 'Zone : {name}',
'catalogue.zone.category': 'Catégorie : {name}',
'catalogue.zone.vertebrae': 'vertèbres {first} à {last}',
'catalogue.zone.no_findings': 'Aucun constat pour cette zone.',
'catalogue.references.title': 'Références',
'catalogue.references.none': 'Aucune référence citée par cette fiche.',
'catalogue.references.link': 'Lien',
'catalogue.failure.view': "Cette vue ne peut pas être affichée : son dessin a été refusé par les contrôles de sécurité ou n'a pas pu être composé.",
'catalogue.failure.network': 'Connexion au serveur impossible. Vérifiez votre réseau.',
'catalogue.failure.session_expired': 'Votre session a expiré. Reconnectez-vous.',
'catalogue.failure.rate_limited': 'Trop de demandes. Patientez quelques minutes avant de réessayer.',
'catalogue.failure.unavailable': 'Le catalogue est momentanément indisponible. Réessayez plus tard.',
'catalogue.failure.drawing_missing': 'Une illustration de cette version est introuvable.',
'catalogue.failure.drawing_hash_mismatch': "Le contenu du fichier de l'illustration ne correspond pas à son empreinte SHA-256 enregistrée.",
'catalogue.failure.fingerprint_mismatch': "L'empreinte de cette version ne correspond pas à celle enregistrée à sa publication.",
'catalogue.failure.invalid_document': 'Le contenu de cette version ne peut pas être lu.',
'catalogue.failure.caps': "Cette version dépasse les limites de taille d'une fiche.",
}
+916
View File
@@ -0,0 +1,916 @@
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest'
import {
cleanup,
render,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
import type { OwnCatalogGrant, PlatformRole } from '@faunosteo/supabase'
import { createFakeSupabase, type FakeSupabase } from '../helpers/fakeSupabase'
import { testCoreRuntime } from '../helpers/core'
const mocks = vi.hoisted(() => ({ fake: null as unknown }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
import AdminHomeRoute from '@/app/routes/app/admin/AdminHomeRoute'
import AdminSheetsRoute from '@/app/routes/app/admin/AdminSheetsRoute'
import AdminSheetCreateRoute from '@/app/routes/app/admin/AdminSheetCreateRoute'
import AdminSheetRoute from '@/app/routes/app/admin/AdminSheetRoute'
import AdminSpeciesRoute from '@/app/routes/app/admin/AdminSpeciesRoute'
import AdminAccessRoute from '@/app/routes/app/admin/AdminAccessRoute'
import { NO_FILTER, filterSheets } from '@/admin/filters'
import { parseGrant, proposeSlug } from '@/admin/validation'
import { setCoreRuntime } from '@/core/runtime'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
/**
* The administration screens (V1-2.5 G, H) on a fake client: what each
* account sees (a display rule: the server decides), the calls the actions
* make and how refusals read. RPC shapes are proven in packages/supabase;
* the journeys run in Chromium in the e2e shell suite.
*/
const SHEET = '33333333-3333-4333-8333-333333333333'
const HISTORICAL = '503dc301-0000-4000-8000-000000000001'
const NEW_ID = '44444444-4444-4444-8444-444444444444'
let fake: FakeSupabase
function grant(kind: OwnCatalogGrant['kind']): OwnCatalogGrant {
return { kind, expires_at: null, revoked_at: null }
}
function summary(patch: Record<string, unknown> = {}) {
return {
sheet_id: SHEET,
species_id: 'equine',
slug: 'cheval-squelette',
status: 'active',
archived_at: null,
created_at: '2026-11-01T10:00:00Z',
updated_at: '2026-11-01T10:00:00Z',
name: {
fr: 'Cheval, squelette et rachis',
en: 'Horse, skeleton and spine',
},
historical: false,
working_copy: true,
working_copy_active: null,
latest_version: {
version_id: 'v-1',
version_number: 1,
status: 'draft',
revision: 3,
},
current_version: null,
draft_version: { version_id: 'v-1', version_number: 1, revision: 3 },
version_statuses: ['draft'],
open_rounds: 1,
latest_round: {
review_id: 'r-1',
version_number: 1,
round: 1,
status: 'open',
submitted_at: null,
},
...patch,
}
}
const historical = () =>
summary({
sheet_id: HISTORICAL,
slug: 'equine',
name: { fr: 'Cheval', en: 'Horse' },
historical: true,
working_copy: false,
working_copy_active: true,
open_rounds: 0,
latest_round: null,
latest_version: {
version_id: 'v-h',
version_number: 1,
status: 'draft',
revision: 0,
},
})
const SPECIES = [
{
id: 'equine',
name_fr: 'Cheval',
name_en: 'Horse',
sort_order: 10,
active: true,
},
{
id: 'camelid',
name_fr: 'Chameau',
name_en: 'Camel',
sort_order: 120,
active: false,
},
{
id: 'other',
name_fr: 'Autre',
name_en: 'Other',
sort_order: 999,
active: true,
},
]
const refusal = (message: string) => ({ error: { code: '42501', message } })
const rpcArgs = (name: string) =>
fake.rpcCalls
.filter(([n]) => n === name)
.map(([, a]) => a as Record<string, unknown>)
function Where() {
return <span data-testid="where">{useLocation().pathname}</span>
}
function mount(
path: string,
grants: OwnCatalogGrant[],
roles: PlatformRole[] = [],
) {
useAuthStore.setState({ catalogGrants: grants, roles })
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/app/admin">
<Route index element={<AdminHomeRoute />} />
<Route path="sheets" element={<AdminSheetsRoute />} />
<Route path="sheets/new" element={<AdminSheetCreateRoute />} />
<Route path="sheets/:sheetId" element={<AdminSheetRoute />} />
<Route path="species" element={<AdminSpeciesRoute />} />
<Route path="access" element={<AdminAccessRoute />} />
</Route>
<Route path="/app/anatomy/:sheetId" element={<p>catalogue page</p>} />
</Routes>
<Where />
</MemoryRouter>,
)
}
beforeAll(async () => {
setCoreRuntime(await testCoreRuntime())
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
fake = createFakeSupabase()
fake.rpcResults.list_official_sheets_admin = {
data: [summary(), historical()],
}
fake.rpcResults.list_catalog_species = { data: SPECIES }
mocks.fake = fake
})
afterEach(() => cleanup())
describe('Administration page (board 10)', () => {
it('editor and publisher: permissions line, sheets with badges, the working copy action disabled with its reason', async () => {
mount('/app/admin', [
grant('sheet_editor'),
grant('sheet_publisher'),
grant('catalog_reader'),
])
expect(
screen.getByText(
'Vos habilitations : éditeur de fiches, responsable de publication · session renforcée (double authentification) active.',
),
).toBeInTheDocument()
expect(
await screen.findByRole('link', { name: 'Cheval, squelette et rachis' }),
).toBeInTheDocument()
expect(screen.getByText('Copie de travail')).toBeInTheDocument()
expect(screen.getByText('1 à relire')).toBeInTheDocument()
expect(screen.getByText('Fiche historique')).toBeInTheDocument()
const action = screen.getByRole('button', {
name: 'Créer une copie de travail',
})
expect(action).toBeDisabled()
expect(action).toHaveAccessibleDescription(fr['admin.working_copy.active'])
expect(screen.getByRole('heading', { name: 'Espèces' })).toBeInTheDocument()
expect(
screen.queryByRole('heading', { name: 'Accès et habilitations' }),
).toBeNull()
})
it('reviewer only: the sheets card without the working copy action, no rights card', async () => {
mount('/app/admin', [grant('sheet_reviewer')])
expect(
screen.getByText(
/^Vos habilitations : relecteur ou relectrice · session/,
),
).toBeInTheDocument()
expect(
await screen.findByRole('link', { name: 'Cheval' }),
).toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'Créer une copie de travail' }),
).toBeNull()
expect(
screen.queryByRole('heading', { name: 'Accès et habilitations' }),
).toBeNull()
expect(screen.getByRole('heading', { name: 'Espèces' })).toBeInTheDocument()
})
it('publisher only: no working copy action', async () => {
mount('/app/admin', [grant('sheet_publisher')])
expect(
await screen.findByRole('link', { name: 'Cheval' }),
).toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'Créer une copie de travail' }),
).toBeNull()
})
it('owner without capability: the server refuses the list, so only species and rights show', async () => {
fake.rpcResults.list_official_sheets_admin = refusal('rights.capability')
mount('/app/admin', [], ['owner'])
expect(
screen.getByText(
'Vos habilitations : aucune · rôle propriétaire · session renforcée (double authentification) active.',
),
).toBeInTheDocument()
expect(
await screen.findByRole('heading', { name: 'Accès et habilitations' }),
).toBeInTheDocument()
await waitFor(() =>
expect(
screen.queryByRole('heading', { name: 'Fiches officielles' }),
).toBeNull(),
)
expect(screen.getByRole('heading', { name: 'Espèces' })).toBeInTheDocument()
expect(screen.queryByRole('alert')).toBeNull()
})
it('an expired grant is no permission', () => {
mount('/app/admin', [
{
kind: 'sheet_editor',
expires_at: '2020-01-01T00:00:00Z',
revoked_at: null,
},
])
expect(
screen.getByText(/^Vos habilitations : aucune · session/),
).toBeInTheDocument()
})
})
describe('Species (S1, matrix §5.4)', () => {
const rows = () => within(screen.getByRole('list', { name: 'Espèces' }))
it('editor: creates and edits inactive species, never activates or renames', async () => {
mount('/app/admin/species', [grant('sheet_editor')])
await screen.findByRole('list', { name: 'Espèces' })
expect(
screen.getByRole('button', { name: 'Nouvelle espèce' }),
).toBeInTheDocument()
expect(
rows().getByRole('button', { name: 'Modifier Chameau' }),
).toBeInTheDocument()
expect(
rows().queryByRole('button', {
name: /Activer|Renommer|Modifier Cheval/,
}),
).toBeNull()
})
it('owner: activates inactive species and renames active ones, creates nothing', async () => {
mount('/app/admin/species', [], ['owner'])
await screen.findByRole('list', { name: 'Espèces' })
expect(screen.queryByRole('button', { name: 'Nouvelle espèce' })).toBeNull()
expect(
rows().getByRole('button', { name: 'Activer Chameau' }),
).toBeInTheDocument()
expect(
rows().getByRole('button', { name: 'Renommer Cheval' }),
).toBeInTheDocument()
expect(rows().queryByRole('button', { name: /Modifier/ })).toBeNull()
})
it('reviewer: reads the list, no action', async () => {
mount('/app/admin/species', [grant('sheet_reviewer')])
await screen.findByRole('list', { name: 'Espèces' })
expect(screen.queryByRole('button')).toBeNull()
expect(screen.getAllByText('Inactive')).toHaveLength(1)
})
it('activation is confirmed, says the animal forms will show it, then calls activate_species', async () => {
const user = userEvent.setup()
fake.rpcResults.activate_species = { data: 'camelid' }
mount('/app/admin/species', [], ['owner'])
await screen.findByRole('list', { name: 'Espèces' })
await user.click(rows().getByRole('button', { name: 'Activer Chameau' }))
const dialog = screen.getByRole('dialog', { name: 'Activer « Chameau » ?' })
expect(dialog).toHaveAccessibleDescription(
fr['admin.species.activate.body'],
)
expect(rpcArgs('activate_species')).toEqual([])
await user.click(within(dialog).getByRole('button', { name: 'Activer' }))
await waitFor(() =>
expect(rpcArgs('activate_species')).toEqual([{ id: 'camelid' }]),
)
expect(await screen.findByText('Espèce activée.')).toBeInTheDocument()
})
it('creation checks the id, then shows the server refusal in words', async () => {
const user = userEvent.setup()
fake.rpcResults.create_species = {
error: { code: 'P0001', message: 'species.exists' },
}
mount('/app/admin/species', [grant('sheet_editor')])
await user.click(
await screen.findByRole('button', { name: 'Nouvelle espèce' }),
)
const dialog = within(
screen.getByRole('dialog', { name: 'Nouvelle espèce' }),
)
await user.type(dialog.getByLabelText('Identifiant'), 'other')
await user.type(dialog.getByLabelText('Nom (français)'), 'Lama')
await user.type(dialog.getByLabelText('Nom (anglais)'), 'Llama')
await user.click(dialog.getByRole('button', { name: 'Enregistrer' }))
expect(dialog.getByText(fr['admin.species.error.id'])).toBeInTheDocument()
expect(rpcArgs('create_species')).toEqual([])
await user.clear(dialog.getByLabelText('Identifiant'))
await user.type(dialog.getByLabelText('Identifiant'), 'llama')
await user.click(dialog.getByRole('button', { name: 'Enregistrer' }))
expect(
await dialog.findByText(fr['admin.failure.species.exists']),
).toBeInTheDocument()
expect(rpcArgs('create_species')).toEqual([
{ id: 'llama', name_fr: 'Lama', name_en: 'Llama', sort_order: 100 },
])
})
})
describe('Rights (A0, §5.2)', () => {
const GRANTS = [
{
id: 'g-1',
user_id: 'user-2',
display_name: 'Dr Marie Lefèvre',
email: 'marie@example.test',
kind: 'sheet_reviewer',
reason: 'Relecture équine',
verification_note: 'Diplôme vérifié',
granted_by: 'user-1',
granted_by_name: 'Alice Local',
granted_at: '2026-11-01T10:00:00Z',
expires_at: null,
revoked_at: null,
revoked_by: null,
revocation_reason: null,
state: 'active',
effective: true,
},
{
id: 'g-2',
user_id: 'user-3',
display_name: 'Paul',
email: 'paul@example.test',
kind: 'catalog_reader',
reason: 'Essai',
verification_note: null,
granted_by: 'user-1',
granted_by_name: 'Alice Local',
granted_at: '2026-10-01T10:00:00Z',
expires_at: null,
revoked_at: '2026-10-20T10:00:00Z',
revoked_by: 'user-1',
revocation_reason: 'Fin de l’essai',
state: 'revoked',
effective: false,
},
]
const ACCOUNT = {
user_id: 'user-4',
display_name: 'Jean Martin',
active: true,
email_confirmed: true,
verified_totp: false,
platform_roles: [],
}
beforeEach(() => {
fake.rpcResults.list_catalog_grants = { data: GRANTS }
fake.rpcResults.lookup_catalog_account = { data: ACCOUNT }
})
it('answers « Accès non autorisé » on the server refusal', async () => {
fake.rpcResults.list_catalog_grants = refusal('rights.owner')
mount('/app/admin/access', [grant('sheet_editor')])
expect(
await screen.findByRole('heading', { name: 'Accès non autorisé' }),
).toBeInTheDocument()
expect(screen.queryByLabelText('Adresse e-mail du compte')).toBeNull()
})
it('lists grants with reason and note, filtered by state', async () => {
const user = userEvent.setup()
mount('/app/admin/access', [], ['owner'])
const list = within(
await screen.findByRole('list', { name: 'Droits attribués' }),
)
expect(list.getByText('Relecture équine')).toBeInTheDocument()
expect(list.getByText('Diplôme vérifié')).toBeInTheDocument()
expect(list.getByText('Fin de l’essai')).toBeInTheDocument()
await user.selectOptions(screen.getByLabelText('État'), 'revoked')
expect(list.queryByText('Relecture équine')).toBeNull()
expect(list.getByText('Paul (paul@example.test)')).toBeInTheDocument()
expect(list.queryByRole('button', { name: 'Révoquer' })).toBeNull()
})
it('grant form: a capability needs a note, an expiry in the future; then grant_catalog_right', async () => {
const user = userEvent.setup()
fake.rpcResults.grant_catalog_right = { data: 'g-9' }
mount('/app/admin/access', [], ['owner'])
await user.type(
await screen.findByLabelText('Adresse e-mail du compte'),
'jean@example.test',
)
await user.click(screen.getByRole('button', { name: 'Rechercher' }))
expect(await screen.findByText('Jean Martin')).toBeInTheDocument()
expect(screen.getByText('Aucun facteur vérifié')).toBeInTheDocument()
expect(rpcArgs('lookup_catalog_account')).toEqual([
{ email: 'jean@example.test' },
])
await user.click(screen.getByRole('button', { name: 'Attribuer' }))
expect(screen.getByText(fr['admin.access.error.kind'])).toBeInTheDocument()
await user.click(screen.getByLabelText('Relecteur, relectrice'))
await user.type(screen.getByLabelText('Motif'), 'Relecture')
await user.type(screen.getByLabelText(/Échéance/), '2020-01-01')
await user.click(screen.getByRole('button', { name: 'Attribuer' }))
expect(screen.getByText(fr['clients.error.required'])).toBeInTheDocument()
expect(
screen.getByText(fr['admin.access.error.expiry']),
).toBeInTheDocument()
expect(rpcArgs('grant_catalog_right')).toEqual([])
await user.type(
screen.getByLabelText('Note de vérification'),
'DMV vérifié',
)
await user.clear(screen.getByLabelText(/Échéance/))
await user.click(screen.getByRole('button', { name: 'Attribuer' }))
await waitFor(() =>
expect(rpcArgs('grant_catalog_right')).toEqual([
{
user_id: 'user-4',
kind: 'sheet_reviewer',
reason: 'Relecture',
verification_note: 'DMV vérifié',
},
]),
)
expect(await screen.findByText('Droit attribué.')).toBeInTheDocument()
})
it('explains an ineligible account', async () => {
const user = userEvent.setup()
fake.rpcResults.grant_catalog_right = {
error: { code: 'P0001', message: 'grant.ineligible' },
}
mount('/app/admin/access', [], ['owner'])
await user.type(
await screen.findByLabelText('Adresse e-mail du compte'),
'jean@example.test',
)
await user.click(screen.getByRole('button', { name: 'Rechercher' }))
await user.click(await screen.findByLabelText('Accès au catalogue'))
await user.type(screen.getByLabelText('Motif'), 'Lecture')
await user.click(screen.getByRole('button', { name: 'Attribuer' }))
expect(
await screen.findByText(fr['admin.access.ineligible_detail']),
).toBeInTheDocument()
expect(rpcArgs('grant_catalog_right')[0]).toEqual({
user_id: 'user-4',
kind: 'catalog_reader',
reason: 'Lecture',
})
})
it('an unknown address reads as such', async () => {
const user = userEvent.setup()
fake.rpcResults.lookup_catalog_account = refusal('not_found')
mount('/app/admin/access', [], ['owner'])
await user.type(
await screen.findByLabelText('Adresse e-mail du compte'),
'nobody@example.test',
)
await user.click(screen.getByRole('button', { name: 'Rechercher' }))
expect(
await screen.findByText('Aucun compte avec cette adresse.'),
).toBeInTheDocument()
})
it('revocation asks a reason in a dialog, then calls revoke_catalog_right', async () => {
const user = userEvent.setup()
fake.rpcResults.revoke_catalog_right = { data: 'g-1' }
mount('/app/admin/access', [], ['owner'])
const list = within(
await screen.findByRole('list', { name: 'Droits attribués' }),
)
await user.click(list.getByRole('button', { name: 'Révoquer' }))
const dialog = within(
screen.getByRole('dialog', { name: 'Révoquer ce droit ?' }),
)
await user.click(dialog.getByRole('button', { name: 'Révoquer' }))
expect(dialog.getByText(fr['clients.error.required'])).toBeInTheDocument()
expect(rpcArgs('revoke_catalog_right')).toEqual([])
await user.type(
dialog.getByLabelText('Motif de la révocation'),
'Fin de mission',
)
await user.click(dialog.getByRole('button', { name: 'Révoquer' }))
await waitFor(() =>
expect(rpcArgs('revoke_catalog_right')).toEqual([
{ grant_id: 'g-1', reason: 'Fin de mission' },
]),
)
expect(await screen.findByText('Droit révoqué.')).toBeInTheDocument()
})
it('parseGrant: the reader needs no note; the expiry is the end of the chosen day', () => {
const parsed = parseGrant(
{
kind: 'catalog_reader',
reason: ' Lecture ',
verification_note: '',
expires_on: '2026-12-31',
},
'2026-11-02',
)
expect(parsed).toEqual({
ok: true,
value: {
kind: 'catalog_reader',
reason: 'Lecture',
expires_at: new Date('2026-12-31T23:59:59').toISOString(),
},
})
const today = parseGrant(
{
kind: 'catalog_reader',
reason: 'x',
verification_note: '',
expires_on: '2026-11-02',
},
'2026-11-02',
)
expect(today).toMatchObject({
ok: false,
errors: { expires_on: 'admin.access.error.expiry' },
})
})
})
describe('Official sheets list (H1)', () => {
it('filters over the loaded list', () => {
const sheets = [summary(), historical()] as Parameters<
typeof filterSheets
>[0]
expect(filterSheets(sheets, NO_FILTER)).toHaveLength(2)
expect(
filterSheets(sheets, { ...NO_FILTER, roundStatus: 'open' }).map(
(s) => s.sheet_id,
),
).toEqual([SHEET])
expect(
filterSheets(sheets, { ...NO_FILTER, versionStatus: 'published' }),
).toEqual([])
expect(
filterSheets(sheets, {
...NO_FILTER,
sheetStatus: 'active',
species: 'equine',
}),
).toHaveLength(2)
})
it('shows every sheet with badges and details; the filters narrow it; « Nouvelle fiche » for editors only', async () => {
const user = userEvent.setup()
const view = mount('/app/admin/sheets', [grant('sheet_editor')])
const list = within(
await screen.findByRole('list', { name: 'Liste des fiches officielles' }),
)
expect(list.getAllByRole('link')).toHaveLength(2)
expect(
list.getByText(
/Cheval · Active · aucune version publiée · brouillon version 1 · revue n° 1 : À relire/,
),
).toBeInTheDocument()
expect(
screen.getByRole('link', { name: 'Nouvelle fiche' }),
).toHaveAttribute('href', '/app/admin/sheets/new')
await user.selectOptions(
screen.getByLabelText('État de la dernière revue'),
'open',
)
expect(list.getAllByRole('link')).toHaveLength(1)
await user.selectOptions(
screen.getByLabelText('Statut de version'),
'published',
)
expect(
screen.getByText('Aucune fiche ne correspond à ces filtres.'),
).toBeInTheDocument()
view.unmount()
mount('/app/admin/sheets', [grant('sheet_reviewer')])
await screen.findByRole('list', { name: 'Liste des fiches officielles' })
expect(screen.queryByRole('link', { name: 'Nouvelle fiche' })).toBeNull()
})
})
describe('Sheet creation (A1)', () => {
it('proposes a slug from the French name', () => {
expect(proposeSlug('Chien : squelette et rachis ')).toBe(
'chien-squelette-et-rachis',
)
expect(proposeSlug('Équidé')).toBe('equide')
})
it('builds the core empty document, calls create_official_sheet, opens the overview', async () => {
const user = userEvent.setup()
fake.rpcResults.create_official_sheet = { data: NEW_ID }
fake.rpcResults.get_official_sheet_admin = {
data: {
...summary({ sheet_id: NEW_ID }),
working_copy_source: null,
versions: [],
rounds: [],
},
}
mount('/app/admin/sheets/new', [grant('sheet_editor')])
const species = await screen.findByLabelText('Espèce')
await waitFor(() =>
expect(within(species).getAllByRole('option')).toHaveLength(3),
)
expect(
within(species).getByRole('option', { name: 'Chameau (inactive)' }),
).toBeInTheDocument()
expect(within(species).queryByRole('option', { name: 'Autre' })).toBeNull()
await user.click(screen.getByRole('button', { name: 'Créer la fiche' }))
expect(
screen.getByText(fr['admin.sheet_form.error.species']),
).toBeInTheDocument()
expect(rpcArgs('create_official_sheet')).toEqual([])
await user.selectOptions(species, 'camelid')
await user.type(
screen.getByLabelText('Nom (français)'),
'Chameau, squelette',
)
await user.type(screen.getByLabelText('Nom (anglais)'), 'Camel, skeleton')
expect(screen.getByLabelText('Identifiant (slug)')).toHaveValue(
'chameau-squelette',
)
await user.click(screen.getByRole('button', { name: 'Créer la fiche' }))
await waitFor(() =>
expect(screen.getByTestId('where')).toHaveTextContent(
`/app/admin/sheets/${NEW_ID}`,
),
)
const [args] = rpcArgs('create_official_sheet')
expect(args.slug).toBe('chameau-squelette')
expect(args.document).toMatchObject({
species_id: 'camelid',
name: { fr: 'Chameau, squelette', en: 'Camel, skeleton' },
})
})
it('shows a slug taken by another sheet in words', async () => {
const user = userEvent.setup()
fake.rpcResults.create_official_sheet = {
error: { code: 'P0001', message: 'sheet.slug_taken' },
}
mount('/app/admin/sheets/new', [grant('sheet_editor')])
const species = await screen.findByLabelText('Espèce')
await waitFor(() =>
expect(within(species).getAllByRole('option')).toHaveLength(3),
)
await user.selectOptions(species, 'equine')
await user.type(screen.getByLabelText('Nom (français)'), 'Cheval bis')
await user.type(screen.getByLabelText('Nom (anglais)'), 'Horse bis')
await user.click(screen.getByRole('button', { name: 'Créer la fiche' }))
expect(
await screen.findByText(fr['admin.failure.sheet.slug_taken']),
).toBeInTheDocument()
expect(screen.getByTestId('where')).toHaveTextContent(
'/app/admin/sheets/new',
)
})
})
describe('Sheet overview (H3)', () => {
function overview(patch: Record<string, unknown> = {}) {
return {
...summary({
current_version: {
version_id: 'v-0',
version_number: 1,
published_at: '2026-10-01T10:00:00Z',
},
}),
working_copy_source: { version_id: 'v-h', version_number: 1 },
versions: [
{
version_id: 'v-1',
version_number: 2,
status: 'draft',
revision: 3,
change_note: 'Rachis repris',
created_at: '2026-11-01T10:00:00Z',
published_at: null,
deprecated_at: null,
source_version_number: 1,
authors: [{ user_id: 'user-1', display_name: 'Bastien Chanot' }],
},
],
rounds: [
{
review_id: 'r-2',
version_id: 'v-1',
version_number: 2,
round: 2,
revision: 3,
status: 'verification_failed',
submitted_by: { user_id: 'user-1', display_name: 'Bastien Chanot' },
submitted_at: '2026-11-01T11:00:00Z',
verified_at: null,
failure_outcome: 'unavailable',
failure_code: null,
decided_by: null,
decided_at: null,
withdrawn_at: null,
},
{
review_id: 'r-1',
version_id: 'v-1',
version_number: 2,
round: 1,
revision: 2,
status: 'verification_failed',
submitted_by: null,
submitted_at: null,
verified_at: null,
failure_outcome: null,
failure_code: null,
decided_by: null,
decided_at: null,
withdrawn_at: null,
},
],
...patch,
}
}
it('shows versions and rounds; a failure outcome only when the server recorded it', async () => {
fake.rpcResults.get_official_sheet_admin = { data: overview() }
mount(`/app/admin/sheets/${SHEET}`, [grant('sheet_reviewer')])
expect(
await screen.findByRole('heading', {
level: 1,
name: 'Cheval, squelette et rachis',
}),
).toBeInTheDocument()
expect(rpcArgs('get_official_sheet_admin')).toEqual([{ sheet_id: SHEET }])
const versions = within(screen.getByRole('region', { name: 'Versions' }))
expect(versions.getByText('Rachis repris')).toBeInTheDocument()
expect(
versions.getByText(/issue de la version 1 · auteurs : Bastien Chanot/),
).toBeInTheDocument()
const rounds = within(screen.getByRole('region', { name: 'Revues' }))
const [second, first] = rounds.getAllByRole('listitem')
expect(
within(second).getByText('Vérification indisponible'),
).toBeInTheDocument()
expect(
within(second).getByText("La vérification n'a pas pu aboutir."),
).toBeInTheDocument()
expect(
within(second).getByText(/soumise le .* par Bastien Chanot/),
).toBeInTheDocument()
expect(within(first).getByText('Vérification échouée')).toBeInTheDocument()
expect(within(first).queryByText(/ne passe pas|pas pu aboutir/)).toBeNull()
expect(
screen.getByRole('link', { name: 'Voir dans le catalogue' }),
).toHaveAttribute('href', `/app/anatomy/${SHEET}`)
expect(
screen.queryByRole('button', { name: 'Créer une copie de travail' }),
).toBeNull()
})
it('historical sheet: the working copy action disabled while a copy is active', async () => {
fake.rpcResults.get_official_sheet_admin = {
data: {
...historical(),
working_copy_source: null,
versions: [],
rounds: [],
},
}
mount(`/app/admin/sheets/${HISTORICAL}`, [grant('sheet_editor')])
const action = await screen.findByRole('button', {
name: 'Créer une copie de travail',
})
expect(action).toBeDisabled()
expect(
screen.getByText(fr['admin.working_copy.active']),
).toBeInTheDocument()
expect(
screen.queryByRole('link', { name: 'Voir dans le catalogue' }),
).toBeNull()
})
it('historical sheet: creates the copy from the latest version and opens its overview', async () => {
const user = userEvent.setup()
fake.rpcResults.get_official_sheet_admin = () => ({
data: {
...historical(),
working_copy_active: false,
working_copy_source: null,
versions: [],
rounds: [],
},
})
fake.rpcResults.create_sheet_working_copy = { data: NEW_ID }
mount(`/app/admin/sheets/${HISTORICAL}`, [grant('sheet_editor')])
await user.click(
await screen.findByRole('button', { name: 'Créer une copie de travail' }),
)
const dialog = within(
screen.getByRole('dialog', { name: 'Créer une copie de travail' }),
)
expect(dialog.getByLabelText('Identifiant (slug)')).toHaveValue(
'equine-copie-de-travail',
)
await user.click(dialog.getByRole('button', { name: 'Créer la copie' }))
await waitFor(() =>
expect(screen.getByTestId('where')).toHaveTextContent(
`/app/admin/sheets/${NEW_ID}`,
),
)
expect(rpcArgs('create_sheet_working_copy')).toEqual([
{ source_version_id: 'v-h', slug: 'equine-copie-de-travail' },
])
})
it('names missing drawings when the copy cannot be made', async () => {
const user = userEvent.setup()
fake.rpcResults.get_official_sheet_admin = {
data: {
...historical(),
working_copy_active: false,
working_copy_source: null,
versions: [],
rounds: [],
},
}
fake.rpcResults.create_sheet_working_copy = {
error: { code: 'P0001', message: 'working_copy.assets_missing' },
}
mount(`/app/admin/sheets/${HISTORICAL}`, [grant('sheet_editor')])
await user.click(
await screen.findByRole('button', { name: 'Créer une copie de travail' }),
)
await user.click(screen.getByRole('button', { name: 'Créer la copie' }))
expect(
await screen.findByText(fr['admin.failure.working_copy.assets_missing']),
).toBeInTheDocument()
})
it('one answer for an unknown or hidden id', async () => {
fake.rpcResults.get_official_sheet_admin = refusal('not_found')
mount(`/app/admin/sheets/${SHEET}`, [grant('sheet_editor')])
expect(
await screen.findByRole('heading', { name: 'Fiche introuvable' }),
).toBeInTheDocument()
cleanup()
mount('/app/admin/sheets/not-a-uuid', [grant('sheet_editor')])
expect(
await screen.findByRole('heading', { name: 'Fiche introuvable' }),
).toBeInTheDocument()
})
})
@@ -0,0 +1,335 @@
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type { PreviewState } from '@faunosteo/core-wasm/types'
import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase'
import { bundledSheet } from '../helpers/sheet'
const mocks = vi.hoisted(() => ({ fake: null as unknown }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
import CatalogRoute from '@/app/routes/app/anatomy/CatalogRoute'
import SheetRoute from '@/app/routes/app/anatomy/SheetRoute'
import { coreRuntime } from '@/core/runtime'
import { CataloguePreview } from '@/catalogue/preview'
import { coreFailure, serverFailure } from '@/catalogue/failure'
import { SheetFailure } from '@faunosteo/supabase'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
/**
* The catalogue screens (V1-2.5 slice I, boards 01 to 03) on a fake client and
* the real core: the equine draft stands for a published version, its
* drawing served as Storage would, so the core checks the hash, the
* fingerprint and the caps exactly as in the browser.
*/
const SHEET = '503dc301-0000-4000-8000-000000000001'
const OTHER = '503dc301-0000-4000-8000-000000000002'
const V1 = 'aaaaaaaa-0000-4000-8000-000000000001'
const V2 = 'aaaaaaaa-0000-4000-8000-000000000002'
const V3 = 'aaaaaaaa-0000-4000-8000-000000000003'
const DOG = 'bbbbbbbb-0000-4000-8000-000000000001'
let fake: FakeSupabase
let document: unknown
let assetId: string
let sha256: string
let bytes: Uint8Array<ArrayBuffer>
let fingerprint: string
beforeAll(async () => {
const bundle = await bundledSheet()
document = bundle.document
;[assetId] = Object.keys(bundle.assets)
sha256 = bundle.assetHashes[assetId]
bytes = new TextEncoder().encode(bundle.assets[assetId])
// The fingerprint a publication stores: the core's, read from a draft preview.
const draft = new CataloguePreview(
coreRuntime(),
{ status: 'draft', document: JSON.stringify(document) },
[{ assetId, sha256, bytes }],
)
const state = draft.state()
if (!state.ok || !state.value.fingerprint) throw new Error('draft preview refused')
fingerprint = state.value.fingerprint
draft.free()
})
function versionAnswer(id: string, status: 'published' | 'deprecated', patch: Record<string, unknown> = {}) {
return {
sheet_id: SHEET,
version_id: id,
version_number: Number(id.slice(-1)),
status,
species_id: 'equine',
document,
revision: 1,
// PreviewSheet requires the stored fingerprint for deprecated versions too, while
// `get_sheet_version` returns it for published ones only (gap reported at V1-2.5).
fingerprint,
drawings: [{ asset_id: assetId, sha256, byte_size: bytes.length }],
...patch,
}
}
/** `get_sheet_version` answers per id, as the server would; unknown ids are `not_found`. */
function serveVersions(answers: Record<string, unknown>) {
fake.rpcResults.get_sheet_version = () => {
const [, args] = fake.rpcCalls.filter(([n]) => n === 'get_sheet_version').at(-1)!
const answer = answers[(args as { version_id: string }).version_id]
return answer ? { data: answer } : { error: { message: 'not_found', code: '42501' } }
}
}
function mount(path: string) {
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/app/anatomy" element={<CatalogRoute />} />
<Route path="/app/anatomy/:sheetId" element={<SheetRoute />} />
<Route path="/app/anatomy/:sheetId/versions/:number" element={<SheetRoute />} />
</Routes>
</MemoryRouter>,
)
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
useAuthStore.setState({ status: 'signed_in', user: fakeUser(), profile: fakeProfile(), catalogGrants: [] })
fake = createFakeSupabase()
fake.tables.species = [
{ id: 'equine', name_fr: 'Cheval', name_en: 'Horse', sort_order: 1 },
{ id: 'canine', name_fr: 'Chien', name_en: 'Dog', sort_order: 2 },
]
fake.tables.anatomical_sheet_versions = [
{ sheet_id: SHEET, id: V3, version_number: 3, status: 'published', published_at: '2026-10-28T10:00:00Z', deprecated_at: null },
{ sheet_id: SHEET, id: V2, version_number: 2, status: 'deprecated', published_at: '2026-10-20T10:00:00Z', deprecated_at: '2026-10-28T10:00:00Z' },
{ sheet_id: SHEET, id: V1, version_number: 1, status: 'published', published_at: '2026-10-10T10:00:00Z', deprecated_at: null },
]
fake.rpcResults.list_official_catalog = {
data: [
{ sheet_id: SHEET, species_id: 'equine', slug: 'cheval', name: { fr: 'Cheval', en: 'Horse' }, description: {}, version_number: 3, version_id: V3 },
{ sheet_id: OTHER, species_id: 'canine', slug: 'chien', name: { fr: 'Chien, rachis', en: 'Dog spine' }, description: {}, version_number: 1, version_id: DOG },
],
}
serveVersions({ [V3]: versionAnswer(V3, 'published'), [V2]: versionAnswer(V2, 'deprecated'), [V1]: versionAnswer(V1, 'published') })
fake.storage.download.mockImplementation(async () => ({ data: new Blob([bytes]), error: null }))
mocks.fake = fake
})
afterEach(() => cleanup())
describe('/app/anatomy', () => {
it('shows each published sheet with its species, status, version line and link', async () => {
mount('/app/anatomy')
expect(await screen.findByRole('heading', { level: 1, name: fr['shell.nav.anatomy'] })).toBeInTheDocument()
const card = (await screen.findByRole('heading', { level: 2, name: 'Cheval' })).closest('article')!
expect(within(card).getByText(fr['catalogue.status.published'])).toBeInTheDocument()
expect(within(card).getByText('Cheval', { selector: 'span' })).toBeInTheDocument()
expect(
await within(card).findByText('Version 3 · publiée le 28/10/2026 · 2 vues, 27 zones de constats'),
).toBeInTheDocument()
// The thumbnail is the core's composed main view, as an image (never inserted as markup).
expect(card.querySelector('img')?.getAttribute('src')).toMatch(/^blob:/)
expect(within(card).getByRole('link', { name: 'Consulter Cheval' })).toHaveAttribute('href', `/app/anatomy/${SHEET}`)
// The card whose version cannot be read keeps its name, version and link.
const dog = screen.getByRole('heading', { level: 2, name: 'Chien, rachis' }).closest('article')!
expect(within(dog).getByText('Version 1')).toBeInTheDocument()
})
it('searches by sheet name in either language and filters by species', async () => {
mount('/app/anatomy')
await screen.findByRole('heading', { level: 2, name: 'Cheval' })
const search = screen.getByRole('searchbox', { name: fr['catalogue.search'] })
await userEvent.type(search, 'dog')
expect(screen.queryByRole('heading', { level: 2, name: 'Cheval' })).toBeNull()
expect(screen.getByRole('heading', { level: 2, name: 'Chien, rachis' })).toBeInTheDocument()
await userEvent.clear(search)
await userEvent.type(search, 'thoracique')
expect(screen.getByText(fr['catalogue.no_results'])).toBeInTheDocument()
await userEvent.clear(search)
const chips = screen.getByRole('group', { name: fr['catalogue.species_filter'] })
expect(within(chips).getAllByRole('button').map((b) => b.textContent)).toEqual([
fr['catalogue.all_species'],
'Cheval',
'Chien',
])
await userEvent.click(within(chips).getByRole('button', { name: 'Cheval' }))
expect(screen.getByRole('heading', { level: 2, name: 'Cheval' })).toBeInTheDocument()
expect(screen.queryByRole('heading', { level: 2, name: 'Chien, rachis' })).toBeNull()
})
it('says when no sheet is published', async () => {
fake.rpcResults.list_official_catalog = { data: [] }
mount('/app/anatomy')
expect(await screen.findByText(fr['catalogue.empty'])).toBeInTheDocument()
})
it('shows « Accès non autorisé » on the server refusal', async () => {
fake.rpcResults.list_official_catalog = { error: { message: 'rights.catalog', code: '42501' } }
mount('/app/anatomy')
expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument()
})
it('names an unavailable server and reads again on retry', async () => {
fake.rpcResults.list_official_catalog = { error: { message: 'boom' } }
mount('/app/anatomy')
expect(await screen.findByText(fr['catalogue.failure.unavailable'])).toBeInTheDocument()
fake.rpcResults.list_official_catalog = { data: [] }
await userEvent.click(screen.getByRole('button', { name: fr['common.retry'] }))
expect(await screen.findByText(fr['catalogue.empty'])).toBeInTheDocument()
})
})
describe('/app/anatomy/:sheetId', () => {
it('shows the current version: views, zone panel, references and disclaimer', async () => {
mount(`/app/anatomy/${SHEET}`)
expect(await screen.findByRole('heading', { level: 1, name: 'Cheval' })).toBeInTheDocument()
expect(screen.getByText('Version 3 · publiée le 28/10/2026')).toBeInTheDocument()
const tabs = screen.getAllByRole('tab')
expect(tabs.map((tab) => tab.textContent)).toEqual(['Vue latérale gauche', 'Tête (vue latérale gauche)'])
expect(tabs[0]).toHaveAttribute('aria-selected', 'true')
const canvas = screen.getByTestId('catalogue-canvas-drawing')
await waitFor(() => expect(canvas.querySelector('svg')).not.toBeNull())
fireEvent.click(canvas.querySelector('[data-anno-id="thoracic"]')!)
expect(screen.getByRole('heading', { name: 'Zone : Vertèbres thoraciques' })).toBeInTheDocument()
expect(screen.getByText('Catégorie : Segments vertébraux · vertèbres T1 à T18')).toBeInTheDocument()
expect(screen.getByRole('heading', { level: 3, name: 'Dysfonctions ostéopathiques' })).toBeInTheDocument()
expect(canvas.querySelector('[data-anno-id="thoracic"]')).toHaveAttribute('data-state', 'current')
expect(screen.getByRole('heading', { name: fr['catalogue.references.title'] })).toBeInTheDocument()
expect(screen.getByText(/Code rural et de la pêche maritime, art\. L\. 243-3/)).toBeInTheDocument()
expect(screen.getByText(/Aucun diagnostic médical n'est posé/)).toBeInTheDocument()
// No capability: no link to the administration.
expect(screen.queryByRole('link', { name: fr['catalogue.open_admin'] })).toBeNull()
})
it('opens the detail view from its link on the drawing', async () => {
mount(`/app/anatomy/${SHEET}`)
const canvas = await screen.findByTestId('catalogue-canvas-drawing')
await waitFor(() => expect(canvas.querySelector('[data-anno-id="head-trigger"]')).not.toBeNull())
fireEvent.click(canvas.querySelector('[data-anno-id="head-trigger"]')!)
expect(screen.getByRole('tab', { name: 'Tête (vue latérale gauche)' })).toHaveAttribute('aria-selected', 'true')
})
it('lists the versions with the « Retirée » mark, each linking to its page', async () => {
mount(`/app/anatomy/${SHEET}`)
await userEvent.click(await screen.findByRole('button', { name: '2 versions antérieures' }))
const list = screen.getByRole('list', { name: fr['catalogue.versions.title'] })
const links = within(list).getAllByRole('link')
expect(links.map((l) => l.getAttribute('href'))).toEqual([3, 2, 1].map((n) => `/app/anatomy/${SHEET}/versions/${n}`))
expect(links[0]).toHaveAttribute('aria-current', 'page')
expect(within(links[1]).getByText(fr['catalogue.status.deprecated'])).toBeInTheDocument()
})
it('opens a retired version by number with its mark', async () => {
mount(`/app/anatomy/${SHEET}/versions/2`)
expect(await screen.findByText('Version 2 · publiée le 20/10/2026')).toBeInTheDocument()
expect(screen.getByText(fr['catalogue.status.deprecated'])).toBeInTheDocument()
expect(fake.rpcCalls.filter(([n]) => n === 'get_sheet_version').map(([, a]) => a)).toEqual([{ version_id: V2 }])
})
it('links an editor to the administration', async () => {
useAuthStore.setState({ catalogGrants: [{ kind: 'sheet_editor', expires_at: null, revoked_at: null }] })
mount(`/app/anatomy/${SHEET}`)
expect(await screen.findByRole('link', { name: fr['catalogue.open_admin'] })).toHaveAttribute(
'href',
`/app/admin/sheets/${SHEET}`,
)
})
it.each([
['an unknown sheet', `/app/anatomy/${OTHER}`],
['a malformed id', '/app/anatomy/not-a-uuid'],
['an unknown number', `/app/anatomy/${SHEET}/versions/9`],
['a malformed number', `/app/anatomy/${SHEET}/versions/0`],
])('shows « Accès non autorisé » for %s', async (_case, path) => {
mount(path)
expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument()
})
it('shows « Accès non autorisé » when the version read is refused', async () => {
serveVersions({})
mount(`/app/anatomy/${SHEET}`)
expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument()
})
it('zooms with the buttons and « Ajuster » brings the whole drawing back', async () => {
mount(`/app/anatomy/${SHEET}`)
const drawing = await screen.findByTestId('catalogue-canvas-drawing')
expect(drawing.style.transform).toBe('translate(0px, 0px) scale(1)')
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.in'] }))
expect(drawing.style.transform).toContain('scale(1.5)')
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.in'] }))
expect(drawing.style.transform).toContain('scale(2.25)')
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.out'] }))
expect(drawing.style.transform).toContain('scale(1.5)')
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.fit'] }))
expect(drawing.style.transform).toBe('translate(0px, 0px) scale(1)')
// The keyboard on the focused box: + zooms, 0 fits.
fireEvent.keyDown(screen.getByTestId('catalogue-canvas'), { key: '+' })
expect(drawing.style.transform).toContain('scale(1.5)')
fireEvent.keyDown(screen.getByTestId('catalogue-canvas'), { key: '0' })
expect(drawing.style.transform).toBe('translate(0px, 0px) scale(1)')
})
})
describe('failures', () => {
it.each([
[
'a drawing whose bytes do not hash to its row',
() => {
const altered = bytes.slice()
altered[200] ^= 1
fake.storage.download.mockImplementation(async () => ({ data: new Blob([altered]), error: null }))
},
'catalogue.failure.drawing_hash_mismatch',
],
[
'a stored fingerprint the core does not recompute',
() => serveVersions({ [V3]: versionAnswer(V3, 'published', { fingerprint: 'a'.repeat(64) }) }),
'catalogue.failure.fingerprint_mismatch',
],
[
'a drawing Storage does not give',
() =>
fake.storage.download.mockImplementation(async () => ({ data: null, error: { status: 400, name: 'StorageApiError' } })),
'catalogue.failure.drawing_missing',
],
[
'an unreadable document',
() => serveVersions({ [V3]: versionAnswer(V3, 'published', { document: { schema_version: 2 } }) }),
'catalogue.failure.invalid_document',
],
])('names %s', async (_case, arrange, key) => {
arrange()
mount(`/app/anatomy/${SHEET}`)
expect(await screen.findByText(fr[key])).toBeInTheDocument()
expect(screen.getByRole('button', { name: fr['common.retry'] })).toBeInTheDocument()
})
it('folds server and core kinds into the closed page kinds', () => {
expect(serverFailure(new SheetFailure('rights.catalog'))).toBe('denied')
expect(serverFailure(new SheetFailure('not_found'))).toBe('denied')
expect(serverFailure(new SheetFailure('network'))).toBe('network')
expect(serverFailure(new SheetFailure('draft_conflict'))).toBe('unavailable')
expect(coreFailure('caps')).toBe('caps')
expect(coreFailure('internal')).toBe('core_unavailable')
expect(coreFailure('invalid_json')).toBe('invalid_document')
})
it('a freed preview never rebuilds its handle', () => {
const preview = new CataloguePreview(
coreRuntime(),
{ status: 'published', document: JSON.stringify(document), fingerprint },
[{ assetId, sha256, bytes }],
)
const state = preview.state()
expect(state.ok && (state.value as PreviewState).status).toBe('published')
preview.free()
expect(preview.canvas('main')).toEqual({ ok: false, kind: 'core_unavailable' })
})
})