feat(app): sheet draft editor route, modes, recovery offer and conflict dialog

This commit is contained in:
bchanot committed 2026-11-04 12:35:33 +01:00
1 parent b14509f221
commit 6aba9711f0
44 files changed
+3143 -13

No files matched your search

+7 -2
View File
@@ -9,8 +9,8 @@ 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
* The failure kinds the administration screens and the draft editor's saves 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.
*/
@@ -28,10 +28,15 @@ const ADMIN_FAILURE_KINDS: ReadonlySet<SheetFailureKind> =
'grant.ineligible',
'grant.revoked',
'grant.target_invalid',
'draft.frozen',
'draft.not_a_draft',
'document.shape',
'document.schema_version',
'document.species',
'document.too_large',
'sheet.inactive',
'sheet.state',
'sheet.historical_read_only',
'sheet.species_invalid',
'sheet.slug_taken',
'species.exists',
+2
View File
@@ -33,6 +33,7 @@ import AdminHomeRoute from './routes/app/admin/AdminHomeRoute'
import AdminSheetsRoute from './routes/app/admin/AdminSheetsRoute'
import AdminSheetCreateRoute from './routes/app/admin/AdminSheetCreateRoute'
import AdminSheetRoute from './routes/app/admin/AdminSheetRoute'
import AdminSheetDraftRoute from './routes/app/admin/AdminSheetDraftRoute'
import AdminSpeciesRoute from './routes/app/admin/AdminSpeciesRoute'
import AdminAccessRoute from './routes/app/admin/AdminAccessRoute'
import { useUnsavedGuard } from './useUnsavedGuard'
@@ -96,6 +97,7 @@ export function AppRoutes() {
<Route index element={<AdminSheetsRoute />} />
<Route path="new" element={<AdminSheetCreateRoute />} />
<Route path=":sheetId" element={<AdminSheetRoute />} />
<Route path=":sheetId/draft" element={<AdminSheetDraftRoute />} />
</Route>
<Route path="species" element={<AdminSpeciesRoute />} />
<Route path="access" element={<AdminAccessRoute />} />
@@ -90,7 +90,7 @@ async function createSheet(
}
}
/** /app/admin/sheets/new (A1, editor): species, names, slug; the new sheet's overview opens. */
/** /app/admin/sheets/new (A1, editor): species, names, slug; the new sheet's draft editor opens. */
export default function AdminSheetCreateRoute() {
const t = useT()
const heading = usePageHeading()
@@ -164,7 +164,7 @@ export default function AdminSheetCreateRoute() {
const result = await createSheet(parsed.value)
setPending(false)
if ('id' in result)
navigate(`/app/admin/sheets/${result.id}`, { replace: true })
navigate(`/app/admin/sheets/${result.id}/draft`, { replace: true })
else setOutcome(result)
}
@@ -0,0 +1,213 @@
import { useEffect, useRef, useState } from 'react'
import { useParams } from 'react-router-dom'
import {
getOfficialSheetAdmin,
type OfficialSheetAdmin,
} from '@faunosteo/supabase'
import ConflictDialog from '@/components/editor/ConflictDialog'
import CopyIssueNotice from '@/components/editor/CopyIssueNotice'
import DraftHeader from '@/components/editor/DraftHeader'
import EditorTabBody from '@/components/editor/EditorTabBody'
import EditorTabs, { PANEL_ID } from '@/components/editor/EditorTabs'
import ModeNotice from '@/components/editor/ModeNotice'
import RecoveryNotice from '@/components/editor/RecoveryNotice'
import CatalogueFailureNotice from '@/components/catalogue/CatalogueFailureNotice'
import AccessDenied from '@/components/shell/AccessDenied'
import PermissionsUnavailable from '@/components/shell/PermissionsUnavailable'
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 } from '@/admin/labels'
import { useAdminPermissions } from '@/admin/permissions'
import { isRightsRefusal, useAdminQuery } from '@/admin/useAdminQuery'
import { useLeaveGuard } from '@/app/useLeaveGuard'
import { saveFailureMessage } from '@/editor/messages'
import {
editorMode,
hasEditRight,
modeAfterSave,
storeCanEdit,
} from '@/editor/mode'
import { leaveGuardArmed, useEditorStore } from '@/editor/state/editorStore'
import type { EditorTabId } from '@/editor/tabs'
import { useTabTier } from '@/editor/useViewport'
import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT'
import { SheetNotFound } from './AdminSheetRoute'
/** The tab the boards open on (04 and 05 both show the annotations). */
const FIRST_TAB: EditorTabId = 'annotations'
interface DraftEditorProps {
sheet: OfficialSheetAdmin
versionId: string
userId: string
hasRight: boolean
reloadSheet: () => void
}
/** A refused save under the header, phrased from the closed kind and the copy's real flag. */
function SaveFailureNotice() {
const t = useT()
const failure = useEditorStore((s) => s.saveFailure)
const unsaved = useEditorStore((s) => s.unsaved)
const copyWritten = useEditorStore((s) => s.copyWritten)
const conflictOpen = useEditorStore((s) => s.conflict !== null)
if (failure === null || (failure === 'draft_conflict' && conflictOpen))
return null
return (
<Notice tone="error">
{saveFailureMessage(t, failure, { unsaved, copyWritten })}
</Notice>
)
}
/**
* The draft page once the sheet is read: opens the store session for this version, derives
* the mode, and renders what the store holds. Components only render and call actions.
*/
function DraftEditor({
sheet,
versionId,
userId,
hasRight,
reloadSheet,
}: DraftEditorProps) {
const t = useT()
const tier = useTabTier()
const [tab, setTab] = useState<EditorTabId>(FIRST_TAB)
const saveFailure = useEditorStore((s) => s.saveFailure)
const status = useEditorStore((s) => s.status)
const sessionVersion = useEditorStore((s) => s.versionId)
const failure = useEditorStore((s) => s.failure)
const recovery = useEditorStore((s) => s.recovery)
const mode = modeAfterSave(
editorMode({ hasRight, sheet, wide: tier === 'wide' }),
saveFailure,
)
const canEdit = storeCanEdit(mode)
const firstCanEdit = useRef(canEdit)
useEffect(() => {
useEditorStore
.getState()
.open(versionId, userId, { canEdit: firstCanEdit.current })
return () => useEditorStore.getState().close()
}, [versionId, userId])
useEffect(() => useEditorStore.getState().setCanEdit(canEdit), [canEdit])
useLeaveGuard(useEditorStore(leaveGuardArmed))
if (status === 'failed' && failure !== null) {
if (failure === 'denied') return <AccessDenied />
const retry = () =>
void useEditorStore.getState().open(versionId, userId, { canEdit })
return <CatalogueFailureNotice failure={failure} onRetry={retry} />
}
if (status !== 'ready' || sessionVersion !== versionId) {
return (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('editor.draft.loading')}
</p>
)
}
const readOnly = mode !== 'edit' || recovery !== 'none'
return (
<div className="space-y-4">
<DraftHeader sheet={sheet} mode={mode} />
<ModeNotice mode={mode} sheet={sheet} />
<SaveFailureNotice />
<RecoveryNotice />
<CopyIssueNotice />
<EditorTabs active={tab} tier={tier} onSelect={setTab} />
<div id={PANEL_ID} role="tabpanel" aria-label={t(`editor.tab.${tab}`)}>
<EditorTabBody
tab={tab}
readOnly={readOnly}
onSelectTab={setTab}
reloadSheet={reloadSheet}
/>
</div>
<ConflictDialog />
</div>
)
}
function NoDraft({ sheetId }: { sheetId: string }) {
const t = useT()
return (
<Card as="section" className="space-y-3 p-5 sm:p-6">
<Notice tone="info">{t('editor.draft.none')}</Notice>
<ButtonLink to={`/app/admin/sheets/${sheetId}`} variant="secondary">
{t('editor.draft.overview_link')}
</ButtonLink>
</Card>
)
}
/**
* /app/admin/sheets/:sheetId/draft (§11.1, boards 04 and 05): the draft editor, level 1.
* Permission states in BDR-099 order: own grants loading, a `rights.*` answer, own grants
* unreadable, an unknown sheet; then the draft itself, or a notice with the way back.
*/
export default function AdminSheetDraftRoute() {
const { sheetId = '' } = useParams()
const t = useT()
const grantsStatus = useAuthStore((s) => s.catalogGrantsStatus)
const reloadAccess = useAuthStore((s) => s.reloadAccess)
const roles = useAuthStore((s) => s.roles)
const userId = useAuthStore((s) => s.user?.id ?? null)
const { editor } = useAdminPermissions()
const { state, refresh } = useAdminQuery(`draft:${sheetId}`, (client) =>
getOfficialSheetAdmin(client, sheetId),
)
if (grantsStatus === 'loading') {
return (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('shell.loading_session')}
</p>
)
}
if (state.status === 'error' && isRightsRefusal(state.failure))
return <AccessDenied />
if (grantsStatus === 'failed') {
const retry = () => {
void reloadAccess()
if (state.status === 'error') refresh()
}
return <PermissionsUnavailable asPage onRetry={retry} />
}
if (state.status === 'error' && state.failure === 'not_found')
return <SheetNotFound />
if (state.status === 'loading') {
return (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('editor.draft.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 = state.data
if (!sheet.draft_version) return <NoDraft sheetId={sheetId} />
if (!userId) return null
return (
<DraftEditor
key={sheet.draft_version.version_id}
sheet={sheet}
versionId={sheet.draft_version.version_id}
userId={userId}
hasRight={hasEditRight(editor, roles)}
reloadSheet={refresh}
/>
)
}
@@ -26,6 +26,8 @@ import {
speciesLabel,
} from '@/admin/labels'
import { useAdminPermissions } from '@/admin/permissions'
import { draftEditable, hasEditRight } from '@/editor/mode'
import { useAuthStore } from '@/state/authStore'
import { isRightsRefusal, useAdminQuery } from '@/admin/useAdminQuery'
import { usePageHeading } from '@/app/usePageHeading'
import type { Locale } from '@/i18n/types'
@@ -190,7 +192,7 @@ function Section({
}
/** One answer for an unknown id and a sheet this account may not see (M7 `not_found`). */
function SheetNotFound() {
export function SheetNotFound() {
const t = useT()
const heading = usePageHeading()
return (
@@ -215,8 +217,9 @@ function SheetNotFound() {
/**
* /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.
* « Voir dans le catalogue » once a version is published. « Ouvrir le brouillon »
* (edit possible) or « Consulter le brouillon » opens the editor; deprecation and
* archive arrive with V1-2.7.
*/
export default function AdminSheetRoute() {
const { sheetId = '' } = useParams()
@@ -224,6 +227,7 @@ export default function AdminSheetRoute() {
const heading = usePageHeading()
const locale = useLocaleStore((s) => s.locale)
const { editor } = useAdminPermissions()
const roles = useAuthStore((s) => s.roles)
const { state, refresh } = useAdminQuery(`sheet:${sheetId}`, (client) =>
loadSheet(client, sheetId),
)
@@ -294,6 +298,19 @@ export default function AdminSheetRoute() {
copyActive={sheet.working_copy_active === true}
/>
)}
{sheet.draft_version && (
<ButtonLink
to={`/app/admin/sheets/${sheet.sheet_id}/draft`}
variant="secondary"
size="sm"
>
{t(
draftEditable(hasEditRight(editor, roles), sheet)
? 'admin.overview.open_draft'
: 'admin.overview.view_draft',
)}
</ButtonLink>
)}
{sheet.current_version && (
<ButtonLink
to={`/app/anatomy/${sheet.sheet_id}`}
@@ -33,7 +33,7 @@ function proposedSlug(slug: string): string {
/**
* « 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).
* version; the new copy's draft editor opens.
*/
export default function WorkingCopyAction({
slug,
@@ -77,7 +77,7 @@ export default function WorkingCopyAction({
typed,
)
setOpen(false)
navigate(`/app/admin/sheets/${sheetId}`)
navigate(`/app/admin/sheets/${sheetId}/draft`)
} catch (caught) {
setFailure(classifySheetError(caught))
} finally {
@@ -0,0 +1,51 @@
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
export interface ConfirmDialogProps {
open: boolean
title: string
body: string
confirmLabel: string
cancelLabel: string
onConfirm: () => void
onCancel: () => void
pending?: boolean
}
/** A question with its two answers; the cancel answer changes nothing. */
export default function ConfirmDialog({
open,
title,
body,
confirmLabel,
cancelLabel,
onConfirm,
onCancel,
pending = false,
}: ConfirmDialogProps) {
return (
<Dialog
open={open}
onClose={onCancel}
title={title}
description={
<p className="text-sm text-[var(--color-ink-muted)]">{body}</p>
}
size="sm"
>
<div className="mt-4 flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={onCancel}>
{cancelLabel}
</Button>
<Button
type="button"
variant="danger"
aria-disabled={pending}
onClick={pending ? undefined : onConfirm}
>
{confirmLabel}
</Button>
</div>
</Dialog>
)
}
@@ -0,0 +1,231 @@
import { useState } from 'react'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import Notice from '@/components/ui/Notice'
import { personName } from '@/admin/labels'
import { formatParisDateTime } from '@/editor/format'
import { loadFailureMessage, saveFailureMessage } from '@/editor/messages'
import { useEditorStore } from '@/editor/state/editorStore'
import type {
ConflictLastSave,
ConflictState,
} from '@/editor/state/editorTypes'
import type { Locale } from '@/i18n/types'
import { useLocaleStore } from '@/state/localeStore'
import { useT } from '@/i18n/useT'
type Translate = ReturnType<typeof useT>
type Step = 'choose' | 'reload' | 'keep'
type Known = Extract<ConflictState, { status: 'known' }>
/** Who and when, only when the server tells it (never invented). */
function whoAndWhen(
t: Translate,
locale: Locale,
last: ConflictLastSave | null,
) {
if (!last) return null
const date = formatParisDateTime(last.savedAt, locale)
if (last.byCaller) {
return {
line: t('editor.draft.conflict.by_you').replace('{date}', date),
who: null,
date,
}
}
const who = personName(t, last.savedBy)
const line = t('editor.draft.conflict.by_other')
.replace('{name}', who)
.replace('{date}', date)
return { line, who, date }
}
function conflictTitle(t: Translate, conflict: ConflictState): string {
if (conflict.status === 'known') {
return t('editor.draft.conflict.known').replace(
'{revision}',
String(conflict.revision),
)
}
return t(
conflict.status === 'reading'
? 'editor.draft.conflict.reading_title'
: 'editor.draft.conflict.unknown',
)
}
function reloadQuestion(t: Translate, conflict: ConflictState): string {
if (conflict.status !== 'known')
return t('editor.draft.conflict.reload_unknown_ask')
return t('editor.draft.conflict.reload_ask').replace(
'{revision}',
String(conflict.revision),
)
}
function keepQuestion(t: Translate, locale: Locale, conflict: Known): string {
const info = whoAndWhen(t, locale, conflict.lastSave)
const revision = String(conflict.revision)
if (!info)
return t('editor.draft.conflict.keep_ask').replace('{revision}', revision)
const who = info.who ?? t('editor.draft.conflict.by_you_short')
return t('editor.draft.conflict.keep_ask_by')
.replace('{revision}', revision)
.replace('{who}', who)
.replace('{date}', info.date)
}
/**
* The conflict dialog (C29): the page read the server draft after `draft_conflict`. The
* known variant names the revision N, and its author and time only when the server says;
* the unknown variant (failed read) offers « Recharger » and « Réessayer » only. Both
* overwrites ask first; the server's atomic revision check decides at write time.
*/
export default function ConflictDialog() {
const t = useT()
const conflict = useEditorStore((s) => s.conflict)
const dismiss = () => useEditorStore.getState().dismissConflict()
return (
<Dialog
open={conflict !== null}
onClose={dismiss}
title={conflict ? conflictTitle(t, conflict) : ''}
size="md"
>
{conflict && (
<ConflictBody
key={`${conflict.status}:${conflict.status === 'known' ? conflict.revision : ''}`}
conflict={conflict}
/>
)}
</Dialog>
)
}
function ConflictBody({ conflict }: { conflict: ConflictState }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const [step, setStep] = useState<Step>('choose')
const [pending, setPending] = useState(false)
const [error, setError] = useState<string | null>(null)
const store = useEditorStore
const known = conflict.status === 'known'
const run = async (action: () => Promise<string | null>) => {
setPending(true)
setError(null)
setError(await action())
setPending(false)
}
const reload = () =>
run(async () => {
const result = await store
.getState()
.reloadServerDraft({ confirmed: true })
return !result.ok && result.reason === 'load'
? loadFailureMessage(t, result.failure)
: null
})
const keep = () =>
run(async () => {
const result = await store.getState().keepMine({ confirmed: true })
if (
result.ok ||
result.reason !== 'server' ||
result.kind === 'draft_conflict'
)
return null
const { unsaved, copyWritten } = store.getState()
return saveFailureMessage(t, result.kind, { unsaved, copyWritten })
})
if (conflict.status === 'reading') {
return (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('editor.draft.conflict.reading')}
</p>
)
}
if (step !== 'choose') {
const ask =
step === 'reload'
? reloadQuestion(t, conflict)
: keepQuestion(t, locale, conflict as Known)
return (
<div className="space-y-4">
<p className="text-sm text-[var(--color-ink)]">{ask}</p>
{error && <Notice tone="error">{error}</Notice>}
<div className="flex flex-wrap justify-end gap-2">
<Button
type="button"
variant="ghost"
disabled={pending}
onClick={() => setStep('choose')}
>
{t('common.cancel')}
</Button>
<Button
type="button"
variant="danger"
disabled={pending}
onClick={() => void (step === 'reload' ? reload() : keep())}
>
{t(
step === 'reload'
? 'editor.draft.conflict.reload'
: 'editor.draft.conflict.keep',
)}
</Button>
</div>
</div>
)
}
const info = known ? whoAndWhen(t, locale, conflict.lastSave) : null
return (
<div className="space-y-4">
{info && <p className="text-sm text-[var(--color-ink)]">{info.line}</p>}
{error && <Notice tone="error">{error}</Notice>}
<div className="flex flex-wrap justify-end gap-2">
<Button
type="button"
variant="ghost"
onClick={() => store.getState().dismissConflict()}
>
{t('common.cancel')}
</Button>
{!known && (
<Button
type="button"
variant="secondary"
onClick={() => void store.getState().retryConflictRead()}
>
{t('editor.draft.conflict.retry')}
</Button>
)}
<Button
type="button"
variant="secondary"
onClick={() => setStep('reload')}
>
{t('editor.draft.conflict.reload')}
</Button>
<Button
type="button"
disabled={!known}
aria-describedby={known ? undefined : 'conflict-keep-hint'}
onClick={() => setStep('keep')}
>
{t('editor.draft.conflict.keep')}
</Button>
</div>
{!known && (
<p
id="conflict-keep-hint"
className="text-right text-sm text-[var(--color-ink-muted)]"
>
{t('editor.draft.conflict.keep_hint')}
</p>
)}
</div>
)
}
@@ -0,0 +1,115 @@
import { useState } from 'react'
import { Link } from 'react-router-dom'
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import { formatParisTime } from '@/editor/format'
import { copySheetId } from '@/editor/otherCopies'
import { useEditorStore } from '@/editor/state/editorStore'
import type { StoredCopyInfo } from '@/editor/state/recovery'
import type { Locale } from '@/i18n/types'
import { useLocaleStore } from '@/state/localeStore'
import { useT } from '@/i18n/useT'
import ConfirmDialog from './ConfirmDialog'
type Translate = ReturnType<typeof useT>
/** « <sheet_name> · révision R · <heure> », each part only when the copy tells it. */
function copyLine(t: Translate, locale: Locale, copy: StoredCopyInfo): string {
return [
copy.sheetName ?? t('editor.draft.copy.unreadable'),
copy.revision === null
? null
: t('editor.draft.copy.revision').replace(
'{revision}',
String(copy.revision),
),
copy.writtenAt === null ? null : formatParisTime(copy.writtenAt, locale),
]
.filter(Boolean)
.join(' · ')
}
/**
* The write failed (C28: cap of two other copies, or a full storage): the account's other
* copies are listed, each openable and abandonable (confirmed); abandoning writes the
* current copy again at once. Nothing is evicted by itself.
*/
export default function CopyIssueNotice() {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const issue = useEditorStore((s) => s.copyIssue)
const copies = useEditorStore((s) => s.otherCopies)
const userId = useEditorStore((s) => s.userId)
const [asking, setAsking] = useState<StoredCopyInfo | null>(null)
if (issue === null) return null
const abandon = () => {
if (asking)
useEditorStore
.getState()
.abandonOtherCopy(asking.versionId, { confirmed: true })
setAsking(null)
}
return (
<>
<Notice tone="error">
<p>{t(`editor.draft.copy_issue.${issue}`)}</p>
<ul className="mt-2 space-y-2">
{copies.map((copy) => {
const sheetId = userId ? copySheetId(userId, copy.versionId) : null
return (
<li
key={copy.versionId}
className="flex flex-wrap items-center gap-2"
>
<span>{copyLine(t, locale, copy)}</span>
{sheetId && (
<Link
to={`/app/admin/sheets/${sheetId}/draft`}
className="text-sm underline"
>
{t('editor.draft.copy.open')}
</Link>
)}
<Button
type="button"
size="sm"
variant="secondary"
onClick={() => setAsking(copy)}
>
{t('editor.draft.copy.abandon')}
</Button>
</li>
)
})}
</ul>
{issue === 'quota' && (
<Button
type="button"
size="sm"
variant="secondary"
className="mt-2"
onClick={() => useEditorStore.getState().retryCopyWrite()}
>
{t('common.retry')}
</Button>
)}
</Notice>
<ConfirmDialog
open={asking !== null}
title={t('editor.draft.copy.abandon')}
body={
asking?.revision != null && asking.writtenAt !== null
? t('editor.draft.recovery.ignore_body')
.replace('{revision}', String(asking.revision))
.replace('{time}', formatParisTime(asking.writtenAt, locale))
: t('editor.draft.recovery.ignore_unreadable_body')
}
confirmLabel={t('editor.draft.recovery.ignore_confirm')}
cancelLabel={t('common.cancel')}
onConfirm={abandon}
onCancel={() => setAsking(null)}
/>
</>
)
}
@@ -0,0 +1,167 @@
import { useState } from 'react'
import { Link } from 'react-router-dom'
import type { OfficialSheetAdmin } from '@faunosteo/supabase'
import Badge from '@/components/ui/Badge'
import Button from '@/components/ui/Button'
import Icon from '@/components/ui/Icon'
import Notice from '@/components/ui/Notice'
import { localized } from '@/admin/labels'
import { loadFailureMessage } from '@/editor/messages'
import type { EditorMode } from '@/editor/mode'
import { useEditorStore } from '@/editor/state/editorStore'
import { usePageHeading } from '@/app/usePageHeading'
import { useLocaleStore } from '@/state/localeStore'
import { useT } from '@/i18n/useT'
import ConfirmDialog from './ConfirmDialog'
type Translate = ReturnType<typeof useT>
interface Status {
copyIssue: 'cap' | 'quota' | null
saving: boolean
unsaved: boolean
revision: number
}
/** Board 04's line; only the copy failures replace it (the copy is temporary, this tab's). */
function statusText(t: Translate, status: Status): string {
if (status.copyIssue !== null)
return t(`editor.draft.status.copy_${status.copyIssue}`)
if (status.saving) return t('editor.draft.status.saving')
const revision = t('editor.draft.status.revision').replace(
'{revision}',
String(status.revision),
)
return status.unsaved
? `${revision} · ${t('editor.draft.status.unsaved')}`
: revision
}
/** Breadcrumb of board 04: Administration › Fiches officielles › the sheet › the draft. */
function Breadcrumb({
sheet,
title,
}: {
sheet: OfficialSheetAdmin
title: string
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const link = 'underline-offset-2 hover:underline'
return (
<nav
aria-label={t('catalogue.breadcrumb')}
className="text-sm text-[var(--color-ink-muted)]"
>
<Link to="/app/admin" className={link}>
{t('shell.nav.admin')}
</Link>
<span aria-hidden="true"> › </span>
<Link to="/app/admin/sheets" className={link}>
{t('admin.sheets.title')}
</Link>
<span aria-hidden="true"> › </span>
<Link to={`/app/admin/sheets/${sheet.sheet_id}`} className={link}>
{localized(sheet.name, locale)}
</Link>
<span aria-hidden="true"> › </span>
<span aria-current="page">{title}</span>
</nav>
)
}
/**
* The draft's header: title and badges, the revision line with the unsaved state, and in
* edit mode « Annuler les modifications » (confirmed) and « Enregistrer ». « Annuler les
* modifications » is the store's `discardChanges`; with an older base it reloads.
*/
export default function DraftHeader({
sheet,
mode,
}: {
sheet: OfficialSheetAdmin
mode: EditorMode
}) {
const t = useT()
const heading = usePageHeading()
const unsaved = useEditorStore((s) => s.unsaved)
const saving = useEditorStore((s) => s.saving)
const blocked = useEditorStore((s) => s.recovery !== 'none')
const revision = useEditorStore((s) => s.savedRevision)
const copyIssue = useEditorStore((s) => s.copyIssue)
const [asking, setAsking] = useState(false)
const [failure, setFailure] = useState<string | null>(null)
const title = t('editor.draft.title').replace(
'{number}',
String(sheet.draft_version?.version_number ?? ''),
)
const discard = async () => {
setAsking(false)
const result = await useEditorStore
.getState()
.discardChanges({ confirmed: true })
setFailure(
!result.ok && result.reason === 'load'
? loadFailureMessage(t, result.failure)
: null,
)
}
return (
<header className="space-y-3">
<Breadcrumb sheet={sheet} title={title} />
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<h1
ref={heading}
tabIndex={-1}
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
>
{title}
</h1>
<Badge>{t('admin.version_status.draft')}</Badge>
{sheet.working_copy && <Badge>{t('admin.badge.working_copy')}</Badge>}
{mode !== 'edit' && (
<Badge>
<Icon name="lock" size={14} className="mr-1" />
{t('editor.draft.read_only')}
</Badge>
)}
<p
role="status"
className="ml-auto text-sm text-[var(--color-ink-muted)]"
>
{statusText(t, { copyIssue, saving, unsaved, revision })}
</p>
{mode === 'edit' && (
<div className="flex flex-wrap gap-2">
<Button
type="button"
variant="secondary"
disabled={!unsaved || saving || blocked}
onClick={() => setAsking(true)}
>
{t('editor.draft.discard')}
</Button>
<Button
type="button"
disabled={!unsaved || saving || blocked}
onClick={() => void useEditorStore.getState().save()}
>
{t('common.save')}
</Button>
</div>
)}
</div>
{failure && <Notice tone="error">{failure}</Notice>}
<ConfirmDialog
open={asking}
title={t('editor.draft.discard')}
body={t('editor.draft.discard_ask')}
confirmLabel={t('editor.draft.discard_confirm')}
cancelLabel={t('common.cancel')}
onConfirm={() => void discard()}
onCancel={() => setAsking(false)}
/>
</header>
)
}
@@ -0,0 +1,28 @@
import type { ComponentType } from 'react'
import type { EditorTabId, EditorTabProps } from '@/editor/tabs'
import AnnotationsTab from './tabs/AnnotationsTab'
import FindingsTab from './tabs/FindingsTab'
import GeneralTab from './tabs/GeneralTab'
import ReferencesTab from './tabs/ReferencesTab'
import VerificationTab from './tabs/VerificationTab'
import VertebraeTab from './tabs/VertebraeTab'
import ViewsTab from './tabs/ViewsTab'
/** One component per tab (Lots F-J fill them); only the active one is mounted. */
const BODIES: Record<EditorTabId, ComponentType<EditorTabProps>> = {
general: GeneralTab,
views: ViewsTab,
annotations: AnnotationsTab,
findings: FindingsTab,
references: ReferencesTab,
vertebrae: VertebraeTab,
verification: VerificationTab,
}
export default function EditorTabBody({
tab,
...props
}: EditorTabProps & { tab: EditorTabId }) {
const Body = BODIES[tab]
return <Body {...props} />
}
@@ -0,0 +1,110 @@
import { useState, type KeyboardEvent } from 'react'
import { tabsFor, type EditorTabId } from '@/editor/tabs'
import type { TabTier } from '@/editor/useViewport'
import { useT } from '@/i18n/useT'
export const PANEL_ID = 'editor-panel'
export const tabDomId = (tab: EditorTabId) => `editor-tab-${tab}`
const BASE =
'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)]'
const ACTIVE =
'border-[var(--color-accent)] font-medium text-[var(--color-accent-strong)]'
const IDLE =
'border-transparent text-[var(--color-ink-muted)] hover:text-[var(--color-ink)]'
interface EditorTabsProps {
active: EditorTabId
tier: TabTier
onSelect: (tab: EditorTabId) => void
}
/**
* The draft's tabs (boards 04 and 05): all seven wide, the static lists of 640 px and over
* and below it narrow, with « Plus » opening a disclosure of the others (no measurement).
*/
export default function EditorTabs({
active,
tier,
onSelect,
}: EditorTabsProps) {
const t = useT()
const { shown, more } = tabsFor(tier)
const [open, setOpen] = useState(false)
const moreActive = more.includes(active)
const onKeyDown = (event: KeyboardEvent) => {
const at = shown.indexOf(active)
const step =
event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0
if (step === 0 || at < 0) return
event.preventDefault()
const next = shown[(at + step + shown.length) % shown.length]
onSelect(next)
document.getElementById(tabDomId(next))?.focus()
}
const pick = (tab: EditorTabId) => {
onSelect(tab)
setOpen(false)
}
return (
<div>
<div className="flex items-end gap-1 overflow-x-auto border-b border-[var(--color-border)]">
<div
role="tablist"
aria-label={t('editor.tab.list')}
onKeyDown={onKeyDown}
className="flex gap-1"
>
{shown.map((tab) => (
<button
key={tab}
id={tabDomId(tab)}
type="button"
role="tab"
aria-selected={tab === active}
aria-controls={PANEL_ID}
tabIndex={tab === active ? 0 : -1}
onClick={() => onSelect(tab)}
className={`-mb-px ${BASE} ${tab === active ? ACTIVE : IDLE}`}
>
{t(`editor.tab.${tab}`)}
</button>
))}
</div>
{more.length > 0 && (
<button
type="button"
aria-expanded={open}
aria-controls="editor-tabs-more"
onClick={() => setOpen((value) => !value)}
className={`-mb-px ${BASE} ${moreActive ? ACTIVE : IDLE}`}
>
{t('editor.tab.more')}
</button>
)}
</div>
{open && (
<ul
id="editor-tabs-more"
className="flex flex-wrap gap-1 border-b border-[var(--color-border)] py-1"
>
{more.map((tab) => (
<li key={tab}>
<button
id={tabDomId(tab)}
type="button"
aria-pressed={tab === active}
onClick={() => pick(tab)}
className={`rounded-md px-3 ${BASE} border-b-0 ${tab === active ? ACTIVE : IDLE}`}
>
{t(`editor.tab.${tab}`)}
</button>
</li>
))}
</ul>
)}
</div>
)
}
@@ -0,0 +1,65 @@
import { Link } from 'react-router-dom'
import Notice from '@/components/ui/Notice'
import { roundLabel } from '@/admin/labels'
import { freezingRound, type EditorMode } from '@/editor/mode'
import { useEditorStore } from '@/editor/state/editorStore'
import { useT } from '@/i18n/useT'
import type { OfficialSheetAdmin } from '@faunosteo/supabase'
type Translate = ReturnType<typeof useT>
/** « Revue n° N · vérification en cours », else the round's status label. */
function frozenText(t: Translate, sheet: OfficialSheetAdmin): string {
const round = freezingRound(sheet)
if (!round) return t('editor.draft.mode.frozen_generic')
const number = t('admin.overview.round').replace(
'{round}',
String(round.round),
)
if (round.status === 'verifying') {
return t('editor.draft.mode.frozen_verifying').replace('{round}', number)
}
return `${number} · ${roundLabel(t, round).title}`
}
function modeText(
t: Translate,
mode: EditorMode,
sheet: OfficialSheetAdmin,
): string {
return mode === 'frozen'
? frozenText(t, sheet)
: t(`editor.draft.mode.${mode}`)
}
/**
* Why the draft is read-only (boards 05): the reason alone, nothing repeated (L15). The
* frozen state links to the overview; a recovery copy that this state cannot use is named.
*/
export default function ModeNotice({
mode,
sheet,
}: {
mode: EditorMode
sheet: OfficialSheetAdmin
}) {
const t = useT()
const unusableCopy = useEditorStore((s) => s.unusableCopy)
if (mode === 'edit') return null
return (
<Notice tone="info">
<p className="font-medium">{modeText(t, mode, sheet)}</p>
{unusableCopy && (
<p className="mt-1">{t('editor.draft.mode.unusable_copy')}</p>
)}
{mode === 'frozen' && (
<Link
to={`/app/admin/sheets/${sheet.sheet_id}`}
className="mt-1 inline-block underline"
>
{t('editor.draft.overview_link')}
</Link>
)}
</Notice>
)
}
@@ -0,0 +1,100 @@
import { useState } from 'react'
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import { formatParisTime } from '@/editor/format'
import { useEditorStore } from '@/editor/state/editorStore'
import type { RecoveryOffer } from '@/editor/state/editorTypes'
import type { Locale } from '@/i18n/types'
import { useLocaleStore } from '@/state/localeStore'
import { useT } from '@/i18n/useT'
import ConfirmDialog from './ConfirmDialog'
type Translate = ReturnType<typeof useT>
function named(text: string, offer: RecoveryOffer, locale: Locale): string {
return text
.replace('{revision}', String(offer.revision))
.replace('{time}', formatParisTime(offer.writtenAt, locale))
}
/** The notice text: unreadable (the loss named), refused by the core, or the offer. */
function noticeText(
t: Translate,
locale: Locale,
offer: RecoveryOffer | null,
refused: string | null,
): string {
if (!offer || refused === 'unreadable')
return t('editor.draft.recovery.unreadable')
if (refused !== null)
return t('editor.draft.recovery.refused').replace('{kind}', refused)
const base = named(t('editor.draft.recovery.offer'), offer, locale)
if (offer.revision >= offer.serverRevision) return base
const older = t('editor.draft.recovery.older')
.replace('{revision}', String(offer.revision))
.replace('{server}', String(offer.serverRevision))
return `${base} ${older}`
}
/**
* The blocking offer under the header (C13, C27, C28): a temporary copy of this tab, not a
* server save. The store refuses every change until « Ignorer la copie » or a restore; the
* page only phrases it. An unreadable copy offers « Ignorer la copie » alone, a copy the
* core refused shows « Restaurer la copie » disabled.
*/
export default function RecoveryNotice() {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const recovery = useEditorStore((s) => s.recovery)
const offer = useEditorStore((s) => s.offer)
const refused = useEditorStore((s) => s.refusedKind)
const [asking, setAsking] = useState(false)
if (recovery === 'none') return null
const unreadable = !offer || refused === 'unreadable'
const busy = recovery === 'restoring'
const question = unreadable
? t('editor.draft.recovery.ignore_unreadable_body')
: named(t('editor.draft.recovery.ignore_body'), offer, locale)
const ignore = () => {
useEditorStore.getState().ignoreCopy({ confirmed: true })
setAsking(false)
}
return (
<>
<Notice tone={refused === null ? 'info' : 'error'}>
<p>{noticeText(t, locale, offer, refused)}</p>
<div className="mt-2 flex flex-wrap gap-2">
{!unreadable && (
<Button
type="button"
size="sm"
disabled={busy || refused !== null}
onClick={() => void useEditorStore.getState().restoreCopy()}
>
{t('editor.draft.recovery.restore')}
</Button>
)}
<Button
type="button"
size="sm"
variant="secondary"
disabled={busy}
onClick={() => setAsking(true)}
>
{t('editor.draft.recovery.ignore')}
</Button>
</div>
</Notice>
<ConfirmDialog
open={asking}
title={t('editor.draft.recovery.ignore')}
body={question}
confirmLabel={t('editor.draft.recovery.ignore_confirm')}
cancelLabel={t('common.cancel')}
onConfirm={ignore}
onCancel={() => setAsking(false)}
/>
</>
)
}
@@ -0,0 +1,9 @@
import Button, { type ButtonProps } from '@/components/ui/Button'
/** An action of a panel: absent from the page while the panel is read-only. */
export default function ActionButton({
readOnly,
...props
}: ButtonProps & { readOnly: boolean }) {
return readOnly ? null : <Button type="button" {...props} />
}
@@ -0,0 +1,30 @@
/** A label and its value as text: what a field shows when it cannot be edited. */
export default function ReadOnlyValue({
id,
label,
value,
multiline = false,
}: {
id: string
label: string
value: string
multiline?: boolean
}) {
return (
<div className="space-y-1">
<p
id={`${id}-label`}
className="text-sm font-medium text-[var(--color-ink)]"
>
{label}
</p>
<p
id={id}
aria-labelledby={`${id}-label`}
className={`text-sm text-[var(--color-ink-muted)] ${multiline ? 'whitespace-pre-wrap' : ''}`}
>
{value === '' ? '—' : value}
</p>
</div>
)
}
@@ -0,0 +1,54 @@
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Select from '@/components/ui/Select'
import ReadOnlyValue from './ReadOnlyValue'
export interface SelectOption {
value: string
label: string
}
export interface SelectFieldProps {
id: string
label: string
value: string
options: readonly SelectOption[]
/** A choice is a confirmation: it commits at once. */
onCommit: (value: string) => void
readOnly?: boolean
hint?: string
error?: string
}
/** A choice among fixed options; read-only, the chosen option's label as text. */
export default function SelectField({
id,
label,
value,
options,
onCommit,
readOnly,
hint,
error,
}: SelectFieldProps) {
if (readOnly) {
const chosen = options.find((option) => option.value === value)
return <ReadOnlyValue id={id} label={label} value={chosen?.label ?? ''} />
}
return (
<FormField id={id} label={label} hint={hint} error={error}>
<Select
id={id}
value={value}
onChange={(e) => onCommit(e.target.value)}
aria-invalid={Boolean(error)}
aria-describedby={fieldDescribedBy(id, hint, error)}
>
{options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</Select>
</FormField>
)
}
@@ -0,0 +1,95 @@
import { useEffect, useRef, useState, type KeyboardEvent } from 'react'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Input from '@/components/ui/Input'
import Textarea from '@/components/ui/Textarea'
import ReadOnlyValue from './ReadOnlyValue'
export interface TextFieldProps {
id: string
label: string
/** The committed value (the document's). */
value: string
/** One commit per change: blur with a changed value, Enter (single line), unmount. */
onCommit: (value: string) => void
/** Shows the value as text, no control (every mode that cannot edit). */
readOnly?: boolean
multiline?: boolean
maxLength?: number
hint?: string
/** The refusal phrased by the caller, shown next to the control. */
error?: string
}
/**
* A text field that commits once per change, never per keystroke (BDR-050): typing stays
* local, blur or Enter commits a changed value, and a value still pending when the field
* unmounts (a mode switch) is committed by the cleanup. Read-only, it is plain text.
*/
export default function TextField(props: TextFieldProps) {
if (props.readOnly) {
return (
<ReadOnlyValue
id={props.id}
label={props.label}
value={props.value}
multiline={props.multiline}
/>
)
}
return <EditableText {...props} />
}
function EditableText({
id,
label,
value,
onCommit,
multiline,
maxLength,
hint,
error,
}: TextFieldProps) {
const [draft, setDraft] = useState(value)
const [seen, setSeen] = useState(value)
// A new committed value (undo, reload, restore) replaces what was typed.
if (seen !== value) {
setSeen(value)
setDraft(value)
}
const latest = useRef({ draft, value, onCommit })
useEffect(() => {
latest.current = { draft, value, onCommit }
})
useEffect(
() => () => {
const pending = latest.current
if (pending.draft !== pending.value) pending.onCommit(pending.draft)
},
[],
)
const commit = () => {
if (draft !== value) onCommit(draft)
}
const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter' && !event.nativeEvent.isComposing) commit()
}
const shared = {
id,
value: draft,
maxLength,
onChange: (e: { target: { value: string } }) => setDraft(e.target.value),
onBlur: commit,
'aria-invalid': Boolean(error),
'aria-describedby': fieldDescribedBy(id, hint, error),
}
return (
<FormField id={id} label={label} hint={hint} error={error}>
{multiline ? (
<Textarea {...shared} />
) : (
<Input {...shared} onKeyDown={onKeyDown} />
)}
</FormField>
)
}
@@ -0,0 +1,14 @@
import type { EditorTabProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
/** Placeholder: Lot H replaces the body and keeps the props contract (`EditorTabProps`). */
export default function AnnotationsTab(_props: EditorTabProps) {
const t = useT()
return (
<section
data-testid="editor-tab-annotations"
aria-label={t('editor.tab.annotations')}
className="min-h-24"
/>
)
}
@@ -0,0 +1,14 @@
import type { EditorTabProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
/** Placeholder: Lot I replaces the body and keeps the props contract (`EditorTabProps`). */
export default function FindingsTab(_props: EditorTabProps) {
const t = useT()
return (
<section
data-testid="editor-tab-findings"
aria-label={t('editor.tab.findings')}
className="min-h-24"
/>
)
}
@@ -0,0 +1,14 @@
import type { EditorTabProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
/** Placeholder: Lot F replaces the body and keeps the props contract (`EditorTabProps`). */
export default function GeneralTab(_props: EditorTabProps) {
const t = useT()
return (
<section
data-testid="editor-tab-general"
aria-label={t('editor.tab.general')}
className="min-h-24"
/>
)
}
@@ -0,0 +1,14 @@
import type { EditorTabProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
/** Placeholder: Lot F replaces the body and keeps the props contract (`EditorTabProps`). */
export default function ReferencesTab(_props: EditorTabProps) {
const t = useT()
return (
<section
data-testid="editor-tab-references"
aria-label={t('editor.tab.references')}
className="min-h-24"
/>
)
}
@@ -0,0 +1,14 @@
import type { EditorTabProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
/** Placeholder: Lot J replaces the body and keeps the props contract (`EditorTabProps`). */
export default function VerificationTab(_props: EditorTabProps) {
const t = useT()
return (
<section
data-testid="editor-tab-verification"
aria-label={t('editor.tab.verification')}
className="min-h-24"
/>
)
}
@@ -0,0 +1,14 @@
import type { EditorTabProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
/** Placeholder: Lot F replaces the body and keeps the props contract (`EditorTabProps`). */
export default function VertebraeTab(_props: EditorTabProps) {
const t = useT()
return (
<section
data-testid="editor-tab-vertebrae"
aria-label={t('editor.tab.vertebrae')}
className="min-h-24"
/>
)
}
@@ -0,0 +1,14 @@
import type { EditorTabProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
/** Placeholder: Lot G replaces the body and keeps the props contract (`EditorTabProps`). */
export default function ViewsTab(_props: EditorTabProps) {
const t = useT()
return (
<section
data-testid="editor-tab-views"
aria-label={t('editor.tab.views')}
className="min-h-24"
/>
)
}
+6 -2
View File
@@ -1,5 +1,5 @@
import { useState, type MouseEvent } from 'react'
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom'
import { Link, Outlet, matchPath, useLocation, useNavigate } from 'react-router-dom'
import Brand from '@/components/brand/Brand'
import LanguageSwitcher from '@/components/brand/LanguageSwitcher'
import Button from '@/components/ui/Button'
@@ -13,6 +13,9 @@ import { useAuthStore } from '@/state/authStore'
import { useLeaveGuardStore } from '@/state/leaveGuardStore'
import { useT } from '@/i18n/useT'
/** The draft editor takes the whole width (board 04's three columns). */
const DRAFT_EDITOR_PATH = '/app/admin/sheets/:sheetId/draft'
/** Title of the current /app page for the top bar, from the nav table. */
function pageTitleKey(pathname: string): string {
const match = NAV_ITEMS.find((item) =>
@@ -64,6 +67,7 @@ export default function AppLayout() {
}
const profile = useAuthStore((s) => s.profile)
const user = useAuthStore((s) => s.user)
const fullWidth = matchPath(DRAFT_EDITOR_PATH, location.pathname) !== null
const displayName = profile?.display_name ?? user?.email ?? ''
return (
@@ -114,7 +118,7 @@ export default function AppLayout() {
</div>
</header>
<main className="flex-1 px-4 py-6 sm:px-8 sm:py-8">
<div className="mx-auto w-full max-w-4xl">
<div className={`mx-auto w-full ${fullWidth ? '' : 'max-w-4xl'}`}>
<Outlet />
</div>
</main>
+2
View File
@@ -15,6 +15,7 @@ export type IconName =
| 'eye-off'
| 'check'
| 'alert'
| 'lock'
| 'google'
| 'apple'
@@ -34,6 +35,7 @@ const PATHS: Record<IconName, string> = {
'eye-off':
'M3 3l18 18M10.6 10.6A3 3 0 0 0 13.4 13.4M9.9 5.2A10.5 10.5 0 0 1 12 5c6 0 10 7 10 7a17 17 0 0 1-3.2 3.9M6.1 6.1A17 17 0 0 0 2 12s4 7 10 7a10 10 0 0 0 4-.8',
check: 'M5 12l5 5L20 7',
lock: 'M6 11h12v9H6zM8 11V8a4 4 0 0 1 8 0v3',
alert: 'M12 9v4M12 17h.01M10.3 3.9L2.8 17a2 2 0 0 0 1.7 3h15a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z',
google:
'M21 12.2c0-.7-.1-1.3-.2-1.9H12v3.6h5.1a4.4 4.4 0 0 1-1.9 2.9v2.4h3.1c1.8-1.7 2.7-4.1 2.7-7zM12 21c2.4 0 4.5-.8 6-2.2l-3.1-2.4c-.8.6-1.8.9-2.9.9-2.3 0-4.2-1.5-4.9-3.6H4v2.5A9 9 0 0 0 12 21zM7.1 13.7a5.4 5.4 0 0 1 0-3.4V7.8H4a9 9 0 0 0 0 8.4zM12 6.6c1.3 0 2.5.5 3.4 1.3l2.6-2.6A9 9 0 0 0 4 7.8l3.1 2.5c.7-2.1 2.6-3.7 4.9-3.7z',
+24
View File
@@ -0,0 +1,24 @@
import type { Locale } from '@/i18n/types'
const ZONE = 'Europe/Paris'
/** « 4 novembre 2026 à 14:32 », in Paris time (conflict dialog). */
export function formatParisDateTime(iso: string, locale: Locale): string {
return new Date(iso).toLocaleString(locale, {
day: 'numeric',
month: 'long',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
timeZone: ZONE,
})
}
/** « 14:32 », in Paris time (recovery copy). */
export function formatParisTime(iso: string, locale: Locale): string {
return new Date(iso).toLocaleTimeString(locale, {
hour: '2-digit',
minute: '2-digit',
timeZone: ZONE,
})
}
+45
View File
@@ -0,0 +1,45 @@
import type { SheetFailureKind } from '@faunosteo/supabase'
import { failureMessage } from '@/admin/labels'
import type { CatalogueFailure } from '@/catalogue/failure'
import { coreFailureMessage } from '@/core/failure'
type Translate = (key: string) => string
/** Refusals whose message promises that the unsaved work is kept (plan, header status). */
const PROMISES_COPY: ReadonlySet<SheetFailureKind> = new Set([
'session_expired',
'rights.mfa',
'rights.capability',
'draft.frozen',
'sheet.inactive',
])
/**
* The header notice of a refused save. A message that promises kept work reads the real
* write flag of the recovery copy: the copy is temporary and limited to this tab, and
* when its last write failed the changes cannot be kept.
*/
export function saveFailureMessage(
t: Translate,
kind: SheetFailureKind,
state: { unsaved: boolean; copyWritten: boolean },
): string {
if (kind === 'draft_conflict') return t('editor.draft.conflict.unknown')
const base = failureMessage(t, kind)
if (!state.unsaved || !PROMISES_COPY.has(kind)) return base
const tail = state.copyWritten
? 'editor.draft.copy_kept'
: 'editor.draft.copy_not_kept'
return `${base} ${t(tail)}`
}
/** A failed reload of the server draft, phrased from the catalogue's closed kinds. */
export function loadFailureMessage(
t: Translate,
failure: CatalogueFailure,
): string {
if (failure === 'denied') return t('access_denied.body')
if (failure === 'core_unavailable')
return coreFailureMessage(t, 'sheet.core_unavailable')
return t(`catalogue.failure.${failure}`)
}
+92
View File
@@ -0,0 +1,92 @@
import type {
OfficialSheetAdmin,
PlatformRole,
SheetAdminRound,
SheetFailureKind,
} from '@faunosteo/supabase'
/**
* Why the draft is edited or only read (plan « Modes, permissions, layout »). A display
* rule: the server refuses every write it does not allow, this only decides what to show.
*/
export type EditorMode =
| 'edit'
| 'narrow'
| 'rights'
| 'frozen'
| 'historical'
| 'inactive'
/** Editing needs a viewport at least this wide (L15). */
export const MIN_EDIT_WIDTH = 1024
type ModeSheet = Pick<
OfficialSheetAdmin,
'status' | 'historical' | 'rounds' | 'draft_version'
>
/** Round states that freeze the draft on the server (`draft.frozen`). */
const FREEZING_ROUNDS: ReadonlySet<SheetAdminRound['status']> = new Set([
'verifying',
'open',
'approved',
])
/** The round that freezes the draft being edited, if any. */
export function freezingRound(sheet: ModeSheet): SheetAdminRound | null {
const draftId = sheet.draft_version?.version_id
const found = sheet.rounds.find(
(round) =>
round.version_id === draftId && FREEZING_ROUNDS.has(round.status),
)
return found ?? null
}
/** `grant_active` needs the editor capability AND the admin or owner role. */
export function hasEditRight(
editorGrant: boolean,
roles: readonly PlatformRole[],
): boolean {
return editorGrant && (roles.includes('admin') || roles.includes('owner'))
}
/**
* The reason the draft cannot be edited, strongest first: the account's own rights, then
* the sheet (archived, historical), the freezing round, last the screen width.
*/
export function editorMode(input: {
hasRight: boolean
sheet: ModeSheet
wide: boolean
}): EditorMode {
const { sheet } = input
if (!input.hasRight) return 'rights'
if (sheet.status !== 'active') return 'inactive'
if (sheet.historical) return 'historical'
if (freezingRound(sheet)) return 'frozen'
return input.wide ? 'edit' : 'narrow'
}
/**
* A refused save names the state the page missed: the matching read-only mode replaces
* the edit mode (the page never retries or sends again by itself).
*/
export function modeAfterSave(
mode: EditorMode,
failure: SheetFailureKind | null,
): EditorMode {
if (mode !== 'edit' || failure === null) return mode
if (failure === 'draft.frozen') return 'frozen'
if (failure === 'sheet.inactive') return 'inactive'
return failure.startsWith('rights.') ? 'rights' : mode
}
/** Whether the sheet's draft can be edited at a wide enough screen: « Ouvrir » or « Consulter ». */
export function draftEditable(hasRight: boolean, sheet: ModeSheet): boolean {
return editorMode({ hasRight, sheet, wide: true }) === 'edit'
}
/** The store may use a recovery copy where the account could save (also at a narrow screen). */
export function storeCanEdit(mode: EditorMode): boolean {
return mode === 'edit' || mode === 'narrow'
}
+10
View File
@@ -0,0 +1,10 @@
import { readCopy } from './state/recovery'
/**
* The sheet a stored copy of another draft belongs to, for « Ouvrir ce brouillon »; null
* when the copy cannot be read (it can still be abandoned).
*/
export function copySheetId(userId: string, versionId: string): string | null {
const stored = readCopy(userId, versionId)
return stored.kind === 'copy' ? stored.copy.sheet_id : null
}
+37
View File
@@ -0,0 +1,37 @@
import type { TabTier } from './useViewport'
export const EDITOR_TABS = [
'general',
'views',
'annotations',
'findings',
'references',
'vertebrae',
'verification',
] as const
export type EditorTabId = (typeof EDITOR_TABS)[number]
/** Board 05: the tabs shown beside « Plus » at each width; the rest sit under « Plus ». */
const SHOWN: Record<TabTier, readonly EditorTabId[]> = {
wide: EDITOR_TABS,
medium: ['general', 'annotations', 'findings', 'verification'],
small: ['annotations', 'verification'],
}
export function tabsFor(tier: TabTier): {
shown: readonly EditorTabId[]
more: readonly EditorTabId[]
} {
const shown = SHOWN[tier]
return { shown, more: EDITOR_TABS.filter((tab) => !shown.includes(tab)) }
}
/** Props of every tab body (Lots F-J fill them): read-only flag, tab jump, sheet reload. */
export interface EditorTabProps {
/** Not editable now: a mode that cannot save, or a recovery offer not answered yet. */
readOnly: boolean
/** « Aller à … » and any link between tabs. */
onSelectTab: (tab: EditorTabId) => void
/** Reads the sheet's overview again (after a submission: the round freezes the draft). */
reloadSheet: () => void
}
+24
View File
@@ -0,0 +1,24 @@
import { useEffect, useState } from 'react'
import { MIN_EDIT_WIDTH } from './mode'
/** The tab lists of board 05: all, the four of 640 px and over, the two below. */
export type TabTier = 'wide' | 'medium' | 'small'
const MEDIUM_WIDTH = 640
function tierOf(width: number): TabTier {
if (width >= MIN_EDIT_WIDTH) return 'wide'
return width >= MEDIUM_WIDTH ? 'medium' : 'small'
}
/** The viewport's tier, kept in step with the window (resize and rotation). */
export function useTabTier(): TabTier {
const [tier, setTier] = useState<TabTier>(() => tierOf(window.innerWidth))
useEffect(() => {
const update = () => setTier(tierOf(window.innerWidth))
update()
window.addEventListener('resize', update)
return () => window.removeEventListener('resize', update)
}, [])
return tier
}
+69
View File
@@ -1175,4 +1175,73 @@ export const en: Dict = {
'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.',
// V1-2.6 E: draft editor route, header, tabs, recovery, conflict
'admin.overview.open_draft': 'Open the draft',
'admin.overview.view_draft': 'View the draft',
'admin.failure.draft.frozen': 'A review is under way on this draft: it can no longer be edited.',
'admin.failure.draft.not_a_draft': 'This version is no longer a draft.',
'admin.failure.sheet.inactive': 'This sheet is archived: its draft can no longer be edited.',
'admin.failure.sheet.state': "The sheet's state does not allow this action. Reload the page.",
'admin.failure.sheet.historical_read_only': 'The historical sheet cannot be edited: create a working copy.',
'editor.tab.list': 'Draft sections',
'editor.tab.general': 'General',
'editor.tab.views': 'Views and drawings',
'editor.tab.annotations': 'Annotations',
'editor.tab.findings': 'Findings',
'editor.tab.references': 'References',
'editor.tab.vertebrae': 'Vertebrae',
'editor.tab.verification': 'Verification',
'editor.tab.more': 'More',
'editor.draft.loading': 'Loading the draft…',
'editor.draft.none': 'This sheet has no draft.',
'editor.draft.overview_link': 'View the sheet',
'editor.draft.title': 'Draft, version {number}',
'editor.draft.read_only': 'Read-only',
'editor.draft.discard': 'Discard changes',
'editor.draft.discard_ask': 'Discard the unsaved changes? The draft will return to the last revision saved on the server.',
'editor.draft.discard_confirm': 'Discard changes',
'editor.draft.status.revision': 'Revision {revision}',
'editor.draft.status.unsaved': 'unsaved changes',
'editor.draft.status.saving': 'Saving…',
'editor.draft.status.copy_quota': 'Local copy impossible (storage full)',
'editor.draft.status.copy_cap': 'Local copy impossible: two other drafts already have a copy in this tab',
'editor.draft.copy_kept': 'A temporary local copy exists in this tab.',
'editor.draft.copy_not_kept': 'The unsaved changes cannot be kept.',
'editor.draft.mode.narrow': 'Editing requires a screen at least 1,024 px wide.',
'editor.draft.mode.rights': 'Your permissions do not allow editing this draft. It remains readable.',
'editor.draft.mode.frozen_verifying': '{round} · verification in progress',
'editor.draft.mode.frozen_generic': 'A review is under way: the draft can no longer be edited.',
'editor.draft.mode.historical': 'The historical sheet cannot be edited: create a working copy to edit it.',
'editor.draft.mode.inactive': 'This sheet is archived: its draft can no longer be edited.',
'editor.draft.mode.unusable_copy': 'An unsaved local copy of this draft exists in this tab; it cannot be used in this state.',
'editor.draft.recovery.offer': 'A temporary local copy of this draft exists in this tab (revision {revision}, {time}). It is not saved on the server. Choose before editing the draft.',
'editor.draft.recovery.older': 'It is based on revision {revision}; the server is at revision {server}.',
'editor.draft.recovery.unreadable': 'A local copy of this draft exists in this tab but cannot be read. It is not saved on the server. Ignoring it deletes it from this tab: its content will be lost.',
'editor.draft.recovery.refused': 'The local copy does not pass the document check: {kind}. It is kept.',
'editor.draft.recovery.restore': 'Restore the copy',
'editor.draft.recovery.ignore': 'Ignore the copy',
'editor.draft.recovery.ignore_body': 'Abandon the unsaved local copy (revision {revision}, {time})? It will be deleted from this tab.',
'editor.draft.recovery.ignore_unreadable_body': 'Abandon the unreadable local copy? It will be deleted from this tab and its content will be lost.',
'editor.draft.recovery.ignore_confirm': 'Abandon the copy',
'editor.draft.copy_issue.cap': 'Two other drafts already have a local copy in this tab. The changes to this one are not kept until you abandon one.',
'editor.draft.copy_issue.quota': "This tab's storage is full: the unsaved changes to this draft are not kept. Save the draft or abandon a copy below.",
'editor.draft.copy.open': 'Open this draft',
'editor.draft.copy.abandon': 'Abandon this copy',
'editor.draft.copy.revision': 'revision {revision}',
'editor.draft.copy.unreadable': 'Unreadable copy',
'editor.draft.conflict.reading_title': 'Save conflict',
'editor.draft.conflict.reading': 'Reading the server revision…',
'editor.draft.conflict.known': 'Another session saved revision {revision}',
'editor.draft.conflict.unknown': 'Another session saved a newer version of this draft.',
'editor.draft.conflict.by_other': 'by {name}, on {date}',
'editor.draft.conflict.by_you': 'from another session of your account, on {date}',
'editor.draft.conflict.by_you_short': 'another session of your account',
'editor.draft.conflict.reload': 'Reload',
'editor.draft.conflict.retry': 'Retry',
'editor.draft.conflict.keep': 'Keep my version',
'editor.draft.conflict.keep_hint': 'Server revision unknown: reload or retry.',
'editor.draft.conflict.reload_ask': 'Abandon your changes and reload revision {revision}?',
'editor.draft.conflict.reload_unknown_ask': 'Abandon your changes and reload the server version?',
'editor.draft.conflict.keep_ask': 'Replace revision {revision} with your version?',
'editor.draft.conflict.keep_ask_by': 'Replace revision {revision} ({who}, {date}) with your version?',
}
+69
View File
@@ -1206,4 +1206,73 @@ export const fr: Dict = {
'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.",
// V1-2.6 E: draft editor route, header, tabs, recovery, conflict
'admin.overview.open_draft': 'Ouvrir le brouillon',
'admin.overview.view_draft': 'Consulter le brouillon',
'admin.failure.draft.frozen': 'Une revue est en cours sur ce brouillon : il ne peut plus être modifié.',
'admin.failure.draft.not_a_draft': "Cette version n'est plus un brouillon.",
'admin.failure.sheet.inactive': 'Cette fiche est archivée : son brouillon ne peut plus être modifié.',
'admin.failure.sheet.state': "L'état de la fiche ne permet pas cette action. Rechargez la page.",
'admin.failure.sheet.historical_read_only': 'La fiche historique ne se modifie pas : créez une copie de travail.',
'editor.tab.list': 'Sections du brouillon',
'editor.tab.general': 'Général',
'editor.tab.views': 'Vues et illustrations',
'editor.tab.annotations': 'Annotations',
'editor.tab.findings': 'Constats',
'editor.tab.references': 'Références',
'editor.tab.vertebrae': 'Vertèbres',
'editor.tab.verification': 'Vérification',
'editor.tab.more': 'Plus',
'editor.draft.loading': 'Chargement du brouillon…',
'editor.draft.none': "Cette fiche n'a pas de brouillon.",
'editor.draft.overview_link': 'Voir la fiche',
'editor.draft.title': 'Brouillon, version {number}',
'editor.draft.read_only': 'Lecture seule',
'editor.draft.discard': 'Annuler les modifications',
'editor.draft.discard_ask': 'Abandonner les modifications non enregistrées ? Le brouillon reprendra la dernière révision enregistrée sur le serveur.',
'editor.draft.discard_confirm': 'Abandonner les modifications',
'editor.draft.status.revision': 'Révision {revision}',
'editor.draft.status.unsaved': 'modifications non enregistrées',
'editor.draft.status.saving': 'Enregistrement…',
'editor.draft.status.copy_quota': 'Copie locale impossible (stockage plein)',
'editor.draft.status.copy_cap': 'Copie locale impossible : deux autres brouillons ont déjà une copie dans cet onglet',
'editor.draft.copy_kept': 'Une copie locale temporaire existe dans cet onglet.',
'editor.draft.copy_not_kept': 'Les modifications non enregistrées ne peuvent pas être conservées.',
'editor.draft.mode.narrow': "L'édition nécessite une largeur d'écran d'au moins 1 024 px.",
'editor.draft.mode.rights': 'Vos habilitations ne permettent pas de modifier ce brouillon. Il reste consultable.',
'editor.draft.mode.frozen_verifying': '{round} · vérification en cours',
'editor.draft.mode.frozen_generic': 'Une revue est en cours : le brouillon ne peut plus être modifié.',
'editor.draft.mode.historical': "La fiche historique ne se modifie pas : créez-en une copie de travail pour l'éditer.",
'editor.draft.mode.inactive': 'Cette fiche est archivée : son brouillon ne se modifie plus.',
'editor.draft.mode.unusable_copy': 'Une copie locale non enregistrée de ce brouillon existe dans cet onglet ; elle ne peut pas être utilisée dans cet état.',
'editor.draft.recovery.offer': "Une copie locale temporaire de ce brouillon existe dans cet onglet (révision {revision}, {time}). Elle n'est pas enregistrée sur le serveur. Choisissez avant de modifier le brouillon.",
'editor.draft.recovery.older': 'Elle est basée sur la révision {revision} ; le serveur est à la révision {server}.',
'editor.draft.recovery.unreadable': "Une copie locale de ce brouillon existe dans cet onglet mais ne peut pas être lue. Elle n'est pas enregistrée sur le serveur. L'ignorer la supprime de cet onglet : son contenu sera perdu.",
'editor.draft.recovery.refused': 'La copie locale ne passe pas le contrôle du document : {kind}. Elle est conservée.',
'editor.draft.recovery.restore': 'Restaurer la copie',
'editor.draft.recovery.ignore': 'Ignorer la copie',
'editor.draft.recovery.ignore_body': 'Abandonner la copie locale non enregistrée (révision {revision}, {time}) ? Elle sera supprimée de cet onglet.',
'editor.draft.recovery.ignore_unreadable_body': 'Abandonner la copie locale illisible ? Elle sera supprimée de cet onglet et son contenu sera perdu.',
'editor.draft.recovery.ignore_confirm': 'Abandonner la copie',
'editor.draft.copy_issue.cap': "Deux autres brouillons ont déjà une copie locale dans cet onglet. Les modifications de celui-ci ne sont pas conservées tant que vous n'en abandonnez pas une.",
'editor.draft.copy_issue.quota': 'Le stockage de cet onglet est plein : les modifications non enregistrées de ce brouillon ne sont pas conservées. Enregistrez le brouillon ou abandonnez une copie ci-dessous.',
'editor.draft.copy.open': 'Ouvrir ce brouillon',
'editor.draft.copy.abandon': 'Abandonner cette copie',
'editor.draft.copy.revision': 'révision {revision}',
'editor.draft.copy.unreadable': 'Copie illisible',
'editor.draft.conflict.reading_title': "Conflit d'enregistrement",
'editor.draft.conflict.reading': 'Lecture de la révision du serveur…',
'editor.draft.conflict.known': 'Une autre session a enregistré la révision {revision}',
'editor.draft.conflict.unknown': 'Une autre session a enregistré une version plus récente de ce brouillon.',
'editor.draft.conflict.by_other': 'par {name}, le {date}',
'editor.draft.conflict.by_you': 'depuis une autre session de votre compte, le {date}',
'editor.draft.conflict.by_you_short': 'une autre session de votre compte',
'editor.draft.conflict.reload': 'Recharger',
'editor.draft.conflict.retry': 'Réessayer',
'editor.draft.conflict.keep': 'Garder ma version',
'editor.draft.conflict.keep_hint': 'Révision du serveur inconnue : rechargez ou réessayez.',
'editor.draft.conflict.reload_ask': 'Abandonner vos modifications et recharger la révision {revision} ?',
'editor.draft.conflict.reload_unknown_ask': 'Abandonner vos modifications et recharger la version du serveur ?',
'editor.draft.conflict.keep_ask': 'Remplacer la révision {revision} par votre version ?',
'editor.draft.conflict.keep_ask_by': 'Remplacer la révision {revision} ({who}, {date}) par votre version ?',
}