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

@@ -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>
)
}