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

@@ -6,3 +6,78 @@ Ratified wordings used verbatim (REVUE.md, V1-2 contract §17.9, §17.11, L15).
separate review and is never declared approved. separate review and is never declared approved.
Each lot appends its rows to its own section (key, FR, EN, where it shows). Each lot appends its rows to its own section (key, FR, EN, where it shows).
## Lot E (draft route, header, tabs, modes, recovery offer, conflict dialog)
Status column: `ratified` = REVUE.md wording; `plan wording` = quoted in the plan (FR verbatim, EN proposed unless noted); `proposal` = new.
| Key | FR | EN | Where | Status |
|---|---|---|---|---|
| `admin.overview.open_draft` | Ouvrir le brouillon | Open the draft | Overview header, edit possible | plan wording |
| `admin.overview.view_draft` | Consulter le brouillon | View the draft | Overview header, read-only | plan wording |
| `admin.failure.draft.frozen` | Une revue est en cours sur ce brouillon : il ne peut plus être modifié. | A review is under way on this draft: it can no longer be edited. | Header notice after a refused save | proposal |
| `admin.failure.draft.not_a_draft` | Cette version n'est plus un brouillon. | This version is no longer a draft. | Header notice after a refused save | proposal |
| `admin.failure.sheet.inactive` | Cette fiche est archivée : son brouillon ne peut plus être modifié. | This sheet is archived: its draft can no longer be edited. | Header notice after a refused save | proposal |
| `admin.failure.sheet.state` | L'état de la fiche ne permet pas cette action. Rechargez la page. | The sheet's state does not allow this action. Reload the page. | Header notice after a refused save | proposal |
| `admin.failure.sheet.historical_read_only` | La fiche historique ne se modifie pas : créez une copie de travail. | The historical sheet cannot be edited: create a working copy. | Header notice after a refused save | proposal |
| `editor.tab.list` | Sections du brouillon | Draft sections | Tab list accessible name | proposal |
| `editor.tab.general` | Général | General | Tab | ratified (board 04) |
| `editor.tab.views` | Vues et illustrations | Views and drawings | Tab | ratified (board 04) |
| `editor.tab.annotations` | Annotations | Annotations | Tab | ratified (board 04) |
| `editor.tab.findings` | Constats | Findings | Tab | ratified (board 04) |
| `editor.tab.references` | Références | References | Tab | ratified (board 04) |
| `editor.tab.vertebrae` | Vertèbres | Vertebrae | Tab | ratified (board 04) |
| `editor.tab.verification` | Vérification | Verification | Tab | ratified FR (board 04); EN proposal |
| `editor.tab.more` | Plus | More | Narrow tab disclosure | ratified FR (board 05); EN proposal |
| `editor.draft.loading` | Chargement du brouillon… | Loading the draft… | Route, while loading | proposal |
| `editor.draft.none` | Cette fiche n'a pas de brouillon. | This sheet has no draft. | Route, no draft | plan wording (notice + link) |
| `editor.draft.overview_link` | Voir la fiche | View the sheet | Link to the overview (no draft, frozen) | proposal |
| `editor.draft.title` | Brouillon, version {number} | Draft, version {number} | Header title | ratified FR (board 04); EN proposal |
| `editor.draft.read_only` | Lecture seule | Read-only | Header badge with the lock icon | ratified (L16) |
| `editor.draft.discard` | Annuler les modifications | Discard changes | Header button and its dialog title | ratified FR (board 04); EN proposal |
| `editor.draft.discard_ask` | Abandonner les modifications non enregistrées ? Le brouillon reprendra la dernière révision enregistrée sur le serveur. | Discard the unsaved changes? The draft will return to the last revision saved on the server. | Discard confirmation | proposal |
| `editor.draft.discard_confirm` | Abandonner les modifications | Discard changes | Discard confirmation button | proposal |
| `editor.draft.status.revision` | Révision {revision} | Revision {revision} | Header status | ratified FR (board 04); EN proposal |
| `editor.draft.status.unsaved` | modifications non enregistrées | unsaved changes | Header status | ratified FR (board 04); EN proposal |
| `editor.draft.status.saving` | Enregistrement… | Saving… | Header status while a save runs | proposal |
| `editor.draft.status.copy_quota` | Copie locale impossible (stockage plein) | Local copy impossible (storage full) | Header status, write failure | plan wording |
| `editor.draft.status.copy_cap` | Copie locale impossible : deux autres brouillons ont déjà une copie dans cet onglet | Local copy impossible: two other drafts already have a copy in this tab | Header status, cap reached | plan wording |
| `editor.draft.copy_kept` | Une copie locale temporaire existe dans cet onglet. | A temporary local copy exists in this tab. | Appended to a refusal that promises kept work, copy written | plan wording |
| `editor.draft.copy_not_kept` | Les modifications non enregistrées ne peuvent pas être conservées. | The unsaved changes cannot be kept. | Appended to such a refusal, copy not written | plan wording (meaning); sentence proposal |
| `editor.draft.mode.narrow` | L'édition nécessite une largeur d'écran d'au moins 1 024 px. | Editing requires a screen at least 1,024 px wide. | Mode notice, narrow screen | ratified (L15, title alone) |
| `editor.draft.mode.rights` | Vos habilitations ne permettent pas de modifier ce brouillon. Il reste consultable. | Your permissions do not allow editing this draft. It remains readable. | Mode notice, rights | proposal |
| `editor.draft.mode.frozen_verifying` | {round} · vérification en cours | {round} · verification in progress | Mode notice, round verifying ({round} = « Revue n° N ») | plan wording |
| `editor.draft.mode.frozen_generic` | Une revue est en cours : le brouillon ne peut plus être modifié. | A review is under way: the draft can no longer be edited. | Mode notice, frozen without a known round (after a refused save) | proposal |
| `editor.draft.mode.historical` | La fiche historique ne se modifie pas : créez-en une copie de travail pour l'éditer. | The historical sheet cannot be edited: create a working copy to edit it. | Mode notice, historical sheet | proposal |
| `editor.draft.mode.inactive` | Cette fiche est archivée : son brouillon ne se modifie plus. | This sheet is archived: its draft can no longer be edited. | Mode notice, archived sheet | proposal |
| `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. | An unsaved local copy of this draft exists in this tab; it cannot be used in this state. | Mode notice addition | plan wording FR; EN proposal |
| `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. | 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. | Recovery offer | plan wording FR; EN proposal |
| `editor.draft.recovery.older` | Elle est basée sur la révision {revision} ; le serveur est à la révision {server}. | It is based on revision {revision}; the server is at revision {server}. | Recovery offer, older base | plan wording FR; EN proposal |
| `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. | 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. | Unreadable copy notice (C34) | plan wording FR; EN proposal |
| `editor.draft.recovery.refused` | La copie locale ne passe pas le contrôle du document : {kind}. Elle est conservée. | The local copy does not pass the document check: {kind}. It is kept. | Copy refused by the core ({kind} = the core's closed kind) | plan wording FR; EN proposal |
| `editor.draft.recovery.restore` | Restaurer la copie | Restore the copy | Recovery offer button | ratified (owner 2026-11-03); EN proposal |
| `editor.draft.recovery.ignore` | Ignorer la copie | Ignore the copy | Recovery offer button and dialog title | ratified (owner 2026-11-03); EN proposal |
| `editor.draft.recovery.ignore_body` | Abandonner la copie locale non enregistrée (révision {revision}, {time}) ? Elle sera supprimée de cet onglet. | Abandon the unsaved local copy (revision {revision}, {time})? It will be deleted from this tab. | Ignore / abandon confirmation | plan wording FR; EN proposal |
| `editor.draft.recovery.ignore_unreadable_body` | Abandonner la copie locale illisible ? Elle sera supprimée de cet onglet et son contenu sera perdu. | Abandon the unreadable local copy? It will be deleted from this tab and its content will be lost. | Ignore confirmation, unreadable copy | proposal |
| `editor.draft.recovery.ignore_confirm` | Abandonner la copie | Abandon the copy | Confirmation button | plan wording FR; EN proposal |
| `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. | Two other drafts already have a local copy in this tab. The changes to this one are not kept until you abandon one. | Cap notice | proposal |
| `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. | This tab's storage is full: the unsaved changes to this draft are not kept. Save the draft or abandon a copy below. | Quota notice | proposal |
| `editor.draft.copy.open` | Ouvrir ce brouillon | Open this draft | Other copy of the account | plan wording FR; EN proposal |
| `editor.draft.copy.abandon` | Abandonner cette copie | Abandon this copy | Other copy of the account, and dialog title | plan wording FR; EN proposal |
| `editor.draft.copy.revision` | révision {revision} | revision {revision} | Other copy line | plan wording |
| `editor.draft.copy.unreadable` | Copie illisible | Unreadable copy | Other copy line, no readable name | proposal |
| `editor.draft.conflict.reading_title` | Conflit d'enregistrement | Save conflict | Conflict dialog title while the server draft is read | proposal |
| `editor.draft.conflict.reading` | Lecture de la révision du serveur… | Reading the server revision… | Conflict dialog, reading | proposal |
| `editor.draft.conflict.known` | Une autre session a enregistré la révision {revision} | Another session saved revision {revision} | Conflict dialog title, N known | plan wording FR; EN proposal |
| `editor.draft.conflict.unknown` | Une autre session a enregistré une version plus récente de ce brouillon. | Another session saved a newer version of this draft. | Conflict dialog title, N unknown; header notice after dismissal | plan wording FR; EN proposal |
| `editor.draft.conflict.by_other` | par {name}, le {date} | by {name}, on {date} | Conflict dialog, author known | plan wording FR; EN proposal |
| `editor.draft.conflict.by_you` | depuis une autre session de votre compte, le {date} | from another session of your account, on {date} | Conflict dialog, saved by the caller | plan wording FR; EN proposal |
| `editor.draft.conflict.by_you_short` | une autre session de votre compte | another session of your account | Conflict confirmation, saved by the caller | proposal |
| `editor.draft.conflict.reload` | Recharger | Reload | Conflict dialog button | ratified (owner 2026-11-03); EN proposal |
| `editor.draft.conflict.retry` | Réessayer | Retry | Conflict dialog button, failed read | ratified (owner 2026-11-03); EN proposal |
| `editor.draft.conflict.keep` | Garder ma version | Keep my version | Conflict dialog button | ratified (owner 2026-11-03); EN proposal |
| `editor.draft.conflict.keep_hint` | Révision du serveur inconnue : rechargez ou réessayez. | Server revision unknown: reload or retry. | Hint under the disabled « Garder ma version » | plan wording FR; EN proposal |
| `editor.draft.conflict.reload_ask` | Abandonner vos modifications et recharger la révision {revision} ? | Abandon your changes and reload revision {revision}? | Reload confirmation | plan wording FR; EN proposal |
| `editor.draft.conflict.reload_unknown_ask` | Abandonner vos modifications et recharger la version du serveur ? | Abandon your changes and reload the server version? | Reload confirmation, N unknown | proposal |
| `editor.draft.conflict.keep_ask` | Remplacer la révision {revision} par votre version ? | Replace revision {revision} with your version? | Keep confirmation, author and date unknown | plan wording FR (author omitted); EN proposal |
| `editor.draft.conflict.keep_ask_by` | Remplacer la révision {revision} ({who}, {date}) par votre version ? | Replace revision {revision} ({who}, {date}) with your version? | Keep confirmation, author and date known | plan wording FR; EN proposal |
+7 -2
View File
@@ -9,8 +9,8 @@ import type { Locale } from '@/i18n/types'
type Translate = (key: string) => string type Translate = (key: string) => string
/** /**
* The failure kinds the administration screens can meet (the RPCs they call, * The failure kinds the administration screens and the draft editor's saves can
* their helpers and the shared session kinds), each with an * 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 * `admin.failure.<kind>` message. Any other kind cannot come from these
* calls; it reads as the generic `unavailable`, never as a raw code. * 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.ineligible',
'grant.revoked', 'grant.revoked',
'grant.target_invalid', 'grant.target_invalid',
'draft.frozen',
'draft.not_a_draft',
'document.shape', 'document.shape',
'document.schema_version', 'document.schema_version',
'document.species', 'document.species',
'document.too_large', 'document.too_large',
'sheet.inactive',
'sheet.state',
'sheet.historical_read_only',
'sheet.species_invalid', 'sheet.species_invalid',
'sheet.slug_taken', 'sheet.slug_taken',
'species.exists', 'species.exists',
+2
View File
@@ -33,6 +33,7 @@ import AdminHomeRoute from './routes/app/admin/AdminHomeRoute'
import AdminSheetsRoute from './routes/app/admin/AdminSheetsRoute' import AdminSheetsRoute from './routes/app/admin/AdminSheetsRoute'
import AdminSheetCreateRoute from './routes/app/admin/AdminSheetCreateRoute' import AdminSheetCreateRoute from './routes/app/admin/AdminSheetCreateRoute'
import AdminSheetRoute from './routes/app/admin/AdminSheetRoute' import AdminSheetRoute from './routes/app/admin/AdminSheetRoute'
import AdminSheetDraftRoute from './routes/app/admin/AdminSheetDraftRoute'
import AdminSpeciesRoute from './routes/app/admin/AdminSpeciesRoute' import AdminSpeciesRoute from './routes/app/admin/AdminSpeciesRoute'
import AdminAccessRoute from './routes/app/admin/AdminAccessRoute' import AdminAccessRoute from './routes/app/admin/AdminAccessRoute'
import { useUnsavedGuard } from './useUnsavedGuard' import { useUnsavedGuard } from './useUnsavedGuard'
@@ -96,6 +97,7 @@ export function AppRoutes() {
<Route index element={<AdminSheetsRoute />} /> <Route index element={<AdminSheetsRoute />} />
<Route path="new" element={<AdminSheetCreateRoute />} /> <Route path="new" element={<AdminSheetCreateRoute />} />
<Route path=":sheetId" element={<AdminSheetRoute />} /> <Route path=":sheetId" element={<AdminSheetRoute />} />
<Route path=":sheetId/draft" element={<AdminSheetDraftRoute />} />
</Route> </Route>
<Route path="species" element={<AdminSpeciesRoute />} /> <Route path="species" element={<AdminSpeciesRoute />} />
<Route path="access" element={<AdminAccessRoute />} /> <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() { export default function AdminSheetCreateRoute() {
const t = useT() const t = useT()
const heading = usePageHeading() const heading = usePageHeading()
@@ -164,7 +164,7 @@ export default function AdminSheetCreateRoute() {
const result = await createSheet(parsed.value) const result = await createSheet(parsed.value)
setPending(false) setPending(false)
if ('id' in result) if ('id' in result)
navigate(`/app/admin/sheets/${result.id}`, { replace: true }) navigate(`/app/admin/sheets/${result.id}/draft`, { replace: true })
else setOutcome(result) 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, speciesLabel,
} from '@/admin/labels' } from '@/admin/labels'
import { useAdminPermissions } from '@/admin/permissions' import { useAdminPermissions } from '@/admin/permissions'
import { draftEditable, hasEditRight } from '@/editor/mode'
import { useAuthStore } from '@/state/authStore'
import { isRightsRefusal, useAdminQuery } from '@/admin/useAdminQuery' import { isRightsRefusal, useAdminQuery } from '@/admin/useAdminQuery'
import { usePageHeading } from '@/app/usePageHeading' import { usePageHeading } from '@/app/usePageHeading'
import type { Locale } from '@/i18n/types' 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`). */ /** 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 t = useT()
const heading = usePageHeading() const heading = usePageHeading()
return ( return (
@@ -215,8 +217,9 @@ function SheetNotFound() {
/** /**
* /app/admin/sheets/:sheetId (§11.1): the sheet, its versions and rounds. * /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); * « 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 * « Voir dans le catalogue » once a version is published. « Ouvrir le brouillon »
* arrives with V1-2.6, deprecation and archive with V1-2.7. * (edit possible) or « Consulter le brouillon » opens the editor; deprecation and
* archive arrive with V1-2.7.
*/ */
export default function AdminSheetRoute() { export default function AdminSheetRoute() {
const { sheetId = '' } = useParams() const { sheetId = '' } = useParams()
@@ -224,6 +227,7 @@ export default function AdminSheetRoute() {
const heading = usePageHeading() const heading = usePageHeading()
const locale = useLocaleStore((s) => s.locale) const locale = useLocaleStore((s) => s.locale)
const { editor } = useAdminPermissions() const { editor } = useAdminPermissions()
const roles = useAuthStore((s) => s.roles)
const { state, refresh } = useAdminQuery(`sheet:${sheetId}`, (client) => const { state, refresh } = useAdminQuery(`sheet:${sheetId}`, (client) =>
loadSheet(client, sheetId), loadSheet(client, sheetId),
) )
@@ -294,6 +298,19 @@ export default function AdminSheetRoute() {
copyActive={sheet.working_copy_active === true} 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 && ( {sheet.current_version && (
<ButtonLink <ButtonLink
to={`/app/anatomy/${sheet.sheet_id}`} 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 * « 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 * 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({ export default function WorkingCopyAction({
slug, slug,
@@ -77,7 +77,7 @@ export default function WorkingCopyAction({
typed, typed,
) )
setOpen(false) setOpen(false)
navigate(`/app/admin/sheets/${sheetId}`) navigate(`/app/admin/sheets/${sheetId}/draft`)
} catch (caught) { } catch (caught) {
setFailure(classifySheetError(caught)) setFailure(classifySheetError(caught))
} finally { } 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 { 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 Brand from '@/components/brand/Brand'
import LanguageSwitcher from '@/components/brand/LanguageSwitcher' import LanguageSwitcher from '@/components/brand/LanguageSwitcher'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
@@ -13,6 +13,9 @@ import { useAuthStore } from '@/state/authStore'
import { useLeaveGuardStore } from '@/state/leaveGuardStore' import { useLeaveGuardStore } from '@/state/leaveGuardStore'
import { useT } from '@/i18n/useT' 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. */ /** Title of the current /app page for the top bar, from the nav table. */
function pageTitleKey(pathname: string): string { function pageTitleKey(pathname: string): string {
const match = NAV_ITEMS.find((item) => const match = NAV_ITEMS.find((item) =>
@@ -64,6 +67,7 @@ export default function AppLayout() {
} }
const profile = useAuthStore((s) => s.profile) const profile = useAuthStore((s) => s.profile)
const user = useAuthStore((s) => s.user) const user = useAuthStore((s) => s.user)
const fullWidth = matchPath(DRAFT_EDITOR_PATH, location.pathname) !== null
const displayName = profile?.display_name ?? user?.email ?? '' const displayName = profile?.display_name ?? user?.email ?? ''
return ( return (
@@ -114,7 +118,7 @@ export default function AppLayout() {
</div> </div>
</header> </header>
<main className="flex-1 px-4 py-6 sm:px-8 sm:py-8"> <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 /> <Outlet />
</div> </div>
</main> </main>
+2
View File
@@ -15,6 +15,7 @@ export type IconName =
| 'eye-off' | 'eye-off'
| 'check' | 'check'
| 'alert' | 'alert'
| 'lock'
| 'google' | 'google'
| 'apple' | 'apple'
@@ -34,6 +35,7 @@ const PATHS: Record<IconName, string> = {
'eye-off': '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', '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', 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', 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: 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', '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.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.invalid_document': "This version's content cannot be read.",
'catalogue.failure.caps': 'This version exceeds the size limits of a sheet.', '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.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.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.", '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 ?',
} }
+128
View File
@@ -0,0 +1,128 @@
import { render } from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import {
SheetFailure,
type OwnCatalogGrant,
type PlatformRole,
type SheetFailureKind,
} from '@faunosteo/supabase'
import AdminSheetDraftRoute from '@/app/routes/app/admin/AdminSheetDraftRoute'
import { useAuthStore } from '@/state/authStore'
import { useLeaveGuardStore } from '@/state/leaveGuardStore'
import { useLocaleStore } from '@/state/localeStore'
import { SHEET, USER, VERSION, sb } from './editorHarness'
/** The route harness: the calling file declares the same module mocks as the store harness. */
export const grant = (kind: OwnCatalogGrant['kind']): OwnCatalogGrant => ({
kind,
expires_at: null,
revoked_at: null,
})
export function adminAnswer(patch: Record<string, unknown> = {}) {
return {
sheet_id: SHEET,
species_id: 'equine',
slug: 'cheval',
status: 'active',
archived_at: null,
created_at: '2026-11-01T10:00:00Z',
updated_at: '2026-11-01T10:00:00Z',
name: {
fr: 'Cheval, squelette et rachis',
en: 'Horse, skeleton and spine',
},
historical: false,
working_copy: true,
working_copy_active: null,
working_copy_source: null,
latest_version: {
version_id: VERSION,
version_number: 4,
status: 'draft',
revision: 3,
},
current_version: null,
draft_version: { version_id: VERSION, version_number: 4, revision: 3 },
draft_last_save: null,
version_statuses: ['draft'],
open_rounds: 0,
latest_round: null,
versions: [],
rounds: [],
...patch,
}
}
export function round(status: string, patch: Record<string, unknown> = {}) {
return {
review_id: 'r-1',
version_id: VERSION,
version_number: 4,
round: 1,
revision: 3,
status,
submitted_by: null,
submitted_at: null,
verified_at: null,
failure_outcome: null,
failure_code: null,
decided_by: null,
decided_at: null,
withdrawn_at: null,
...patch,
}
}
export function setWidth(width: number): void {
Object.defineProperty(window, 'innerWidth', {
configurable: true,
value: width,
})
}
export interface MountOptions {
grants?: OwnCatalogGrant[]
roles?: PlatformRole[]
grantsStatus?: 'loading' | 'ready' | 'failed'
width?: number
answer?: Record<string, unknown>
/** The admin read is refused with this closed kind. */
adminFailure?: SheetFailureKind
}
/** Mounts the draft route as an editor with the admin role, at a wide screen, by default. */
export function mountDraft(options: MountOptions = {}) {
setWidth(options.width ?? 1280)
useLocaleStore.setState({ locale: 'fr' })
useLeaveGuardStore.setState({ armed: false })
useAuthStore.setState({
user: { id: USER } as never,
catalogGrants: options.grants ?? [grant('sheet_editor')],
catalogGrantsStatus: options.grantsStatus ?? 'ready',
roles: options.roles ?? ['admin'],
})
if (options.adminFailure) {
sb.getOfficialSheetAdmin.mockRejectedValue(
new SheetFailure(options.adminFailure),
)
} else {
sb.getOfficialSheetAdmin.mockResolvedValue(
(options.answer ?? adminAnswer()) as never,
)
}
return render(
<MemoryRouter initialEntries={[`/app/admin/sheets/${SHEET}/draft`]}>
<Routes>
<Route
path="/app/admin/sheets/:sheetId/draft"
element={<AdminSheetDraftRoute />}
/>
<Route
path="/app/admin/sheets/:sheetId"
element={<p>overview page</p>}
/>
</Routes>
</MemoryRouter>,
)
}
+122
View File
@@ -0,0 +1,122 @@
/** Lot E: the shared field components: commit once per change, text when read-only. */
import { describe, expect, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import ActionButton from '@/components/editor/fields/ActionButton'
import SelectField from '@/components/editor/fields/SelectField'
import TextField from '@/components/editor/fields/TextField'
const OPTIONS = [
{ value: 'a', label: 'Alpha' },
{ value: 'b', label: 'Beta' },
]
describe('TextField', () => {
it('commits on blur with a changed value, never per keystroke', async () => {
const user = userEvent.setup()
const onCommit = vi.fn()
render(<TextField id="f" label="Nom" value="Cheval" onCommit={onCommit} />)
await user.type(screen.getByLabelText('Nom'), 's')
expect(onCommit).not.toHaveBeenCalled()
await user.tab()
expect(onCommit).toHaveBeenCalledOnce()
expect(onCommit).toHaveBeenCalledWith('Chevals')
})
it('Enter commits a single line; an unchanged value commits nothing', async () => {
const user = userEvent.setup()
const onCommit = vi.fn()
render(<TextField id="f" label="Nom" value="Cheval" onCommit={onCommit} />)
const input = screen.getByLabelText('Nom')
await user.click(input)
await user.keyboard('{Enter}')
await user.tab()
expect(onCommit).not.toHaveBeenCalled()
await user.type(input, 'x{Enter}')
expect(onCommit).toHaveBeenCalledWith('Chevalx')
})
it('a value still pending when the field unmounts is committed', async () => {
const user = userEvent.setup()
const onCommit = vi.fn()
const view = render(
<TextField id="f" label="Nom" value="Cheval" onCommit={onCommit} />,
)
await user.type(screen.getByLabelText('Nom'), 'z')
view.unmount()
expect(onCommit).toHaveBeenCalledWith('Chevalz')
})
it('a new committed value replaces what was typed; the refusal shows next to the control', () => {
const view = render(
<TextField
id="f"
label="Nom"
value="a"
onCommit={vi.fn()}
error="Refusé"
/>,
)
expect(screen.getByRole('alert')).toHaveTextContent('Refusé')
expect(screen.getByLabelText('Nom')).toHaveAttribute('aria-invalid', 'true')
view.rerender(<TextField id="f" label="Nom" value="b" onCommit={vi.fn()} />)
expect(screen.getByLabelText('Nom')).toHaveValue('b')
})
it('read-only: the value as text, no control; empty reads as a dash', () => {
const view = render(
<TextField
id="f"
label="Nom"
value="Cheval"
onCommit={vi.fn()}
readOnly
/>,
)
expect(screen.queryByRole('textbox')).toBeNull()
expect(screen.getByText('Cheval')).toBeInTheDocument()
view.rerender(
<TextField id="f" label="Nom" value="" onCommit={vi.fn()} readOnly />,
)
expect(screen.getByText('—')).toBeInTheDocument()
})
})
describe('SelectField and ActionButton', () => {
it('a choice commits at once; read-only shows the option label', async () => {
const user = userEvent.setup()
const onCommit = vi.fn()
const view = render(
<SelectField
id="s"
label="Type"
value="a"
options={OPTIONS}
onCommit={onCommit}
/>,
)
await user.selectOptions(screen.getByLabelText('Type'), 'b')
expect(onCommit).toHaveBeenCalledWith('b')
view.rerender(
<SelectField
id="s"
label="Type"
value="b"
options={OPTIONS}
onCommit={onCommit}
readOnly
/>,
)
expect(screen.queryByRole('combobox')).toBeNull()
expect(screen.getByText('Beta')).toBeInTheDocument()
})
it('the action is absent while read-only', () => {
const view = render(<ActionButton readOnly={false}>Supprimer</ActionButton>)
expect(
screen.getByRole('button', { name: 'Supprimer' }),
).toBeInTheDocument()
view.rerender(<ActionButton readOnly>Supprimer</ActionButton>)
expect(screen.queryByRole('button')).toBeNull()
})
})
+117
View File
@@ -0,0 +1,117 @@
/** Lot E: the display rules of the draft's mode (the server decides every write). */
import { describe, expect, it } from 'vitest'
import {
draftEditable,
editorMode,
freezingRound,
hasEditRight,
modeAfterSave,
storeCanEdit,
} from '@/editor/mode'
import { tabsFor } from '@/editor/tabs'
const sheet = (patch: Record<string, unknown> = {}) =>
({
status: 'active',
historical: false,
draft_version: { version_id: 'v1', version_number: 1, revision: 1 },
rounds: [],
...patch,
}) as never
const round = (status: string, version_id = 'v1') =>
({ version_id, status }) as never
describe('editorMode', () => {
const base = { hasRight: true, sheet: sheet(), wide: true }
it('edit, narrow and the reasons that read only, strongest first', () => {
expect(editorMode(base)).toBe('edit')
expect(editorMode({ ...base, wide: false })).toBe('narrow')
expect(editorMode({ ...base, hasRight: false, wide: false })).toBe('rights')
expect(
editorMode({
...base,
sheet: sheet({ status: 'archived' }),
wide: false,
}),
).toBe('inactive')
expect(editorMode({ ...base, sheet: sheet({ historical: true }) })).toBe(
'historical',
)
expect(
editorMode({ ...base, sheet: sheet({ rounds: [round('open')] }) }),
).toBe('frozen')
})
it('only verifying, open and approved rounds of the edited draft freeze it', () => {
for (const status of ['verifying', 'open', 'approved']) {
expect(freezingRound(sheet({ rounds: [round(status)] }))).not.toBeNull()
}
for (const status of [
'changes_requested',
'withdrawn',
'verification_failed',
]) {
expect(freezingRound(sheet({ rounds: [round(status)] }))).toBeNull()
}
expect(
freezingRound(sheet({ rounds: [round('open', 'other')] })),
).toBeNull()
})
it('the right needs the capability and the admin or owner role', () => {
expect(hasEditRight(true, ['admin'])).toBe(true)
expect(hasEditRight(true, ['owner'])).toBe(true)
expect(hasEditRight(true, ['support'])).toBe(false)
expect(hasEditRight(false, ['admin'])).toBe(false)
})
it('the overview offers « Ouvrir » only when the draft can be edited', () => {
expect(draftEditable(true, sheet())).toBe(true)
expect(draftEditable(true, sheet({ rounds: [round('verifying')] }))).toBe(
false,
)
expect(draftEditable(false, sheet())).toBe(false)
})
it('the store may use a recovery copy where the account could save', () => {
expect(['edit', 'narrow'].every((m) => storeCanEdit(m as never))).toBe(true)
expect(
['rights', 'frozen', 'historical', 'inactive'].some((m) =>
storeCanEdit(m as never),
),
).toBe(false)
})
})
describe('modeAfterSave', () => {
it('a refused save names the state the page missed', () => {
expect(modeAfterSave('edit', 'draft.frozen')).toBe('frozen')
expect(modeAfterSave('edit', 'sheet.inactive')).toBe('inactive')
expect(modeAfterSave('edit', 'rights.mfa')).toBe('rights')
expect(modeAfterSave('edit', 'network')).toBe('edit')
expect(modeAfterSave('edit', null)).toBe('edit')
expect(modeAfterSave('narrow', 'draft.frozen')).toBe('narrow')
})
})
describe('tabsFor', () => {
it('the static lists of board 05', () => {
expect(tabsFor('wide').more).toEqual([])
expect(tabsFor('medium').shown).toEqual([
'general',
'annotations',
'findings',
'verification',
])
expect(tabsFor('small').shown).toEqual(['annotations', 'verification'])
expect(tabsFor('small').more).toEqual([
'general',
'views',
'findings',
'references',
'vertebrae',
])
})
})
@@ -0,0 +1,207 @@
/** Lot E: the conflict dialog, known and unknown variants, and its two confirmations. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SheetFailure } from '@faunosteo/supabase'
import {
USER,
VERSION,
baseText,
commitMove,
resetStore,
sb,
serverHas,
store,
} from '../helpers/editorHarness'
import { adminAnswer, mountDraft, setWidth } from '../helpers/editorRoute'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
getSheetVersion: vi.fn(),
downloadSheetDrawing: vi.fn(),
saveSheetDraft: vi.fn(),
getOfficialSheetAdmin: vi.fn(),
submitSheetReview: vi.fn(),
}))
beforeEach(() => serverHas(baseText(), 3))
afterEach(() => {
cleanup()
resetStore()
setWidth(1024)
})
const ready = () =>
screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
const conflict = () => new SheetFailure('draft_conflict')
function serverDraft(revision: number, lastSaveBy: string | null) {
const save =
lastSaveBy === null
? null
: {
revision,
saved_at: '2026-11-04T13:32:00Z',
saved_by: {
user_id: lastSaveBy,
display_name: lastSaveBy === USER ? 'Moi' : 'Autre Praticien',
},
}
return adminAnswer({
draft_version: { version_id: VERSION, version_number: 4, revision },
draft_last_save: save,
})
}
/** What the conflict read answers: a draft, or a failure (built when the read runs). */
type Read = ReturnType<typeof serverDraft> | (() => Promise<never>)
async function startConflict(next: Read) {
const user = userEvent.setup()
sb.saveSheetDraft.mockRejectedValueOnce(conflict())
mountDraft()
await ready()
act(() => void commitMove(40))
if (typeof next === 'function')
sb.getOfficialSheetAdmin.mockImplementationOnce(next as never)
else sb.getOfficialSheetAdmin.mockResolvedValueOnce(next as never)
await user.click(await screen.findByRole('button', { name: 'Enregistrer' }))
return { user, dialog: within(await screen.findByRole('dialog')) }
}
describe('known revision', () => {
it('names N, the author and the Paris time; keep asks first, then saves against N', async () => {
const { user, dialog } = await startConflict(serverDraft(5, 'other-user'))
expect(
await dialog.findByText(
'par Autre Praticien, le 4 novembre 2026 à 14:32',
),
).toBeInTheDocument()
expect(screen.getByRole('dialog')).toHaveAccessibleName(
'Une autre session a enregistré la révision 5',
)
expect(dialog.queryByRole('button', { name: 'Réessayer' })).toBeNull()
sb.saveSheetDraft.mockResolvedValueOnce({ revision: 6 } as never)
await user.click(dialog.getByRole('button', { name: 'Garder ma version' }))
expect(
dialog.getByText(
'Remplacer la révision 5 (Autre Praticien, 4 novembre 2026 à 14:32) par votre version ?',
),
).toBeInTheDocument()
expect(sb.saveSheetDraft).toHaveBeenCalledTimes(1)
await user.click(dialog.getByRole('button', { name: 'Garder ma version' }))
await waitFor(() => expect(sb.saveSheetDraft).toHaveBeenCalledTimes(2))
expect(sb.saveSheetDraft).toHaveBeenLastCalledWith(
expect.anything(),
expect.objectContaining({ expected_revision: 5 }),
)
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(await screen.findByText('Révision 6')).toBeInTheDocument()
})
it('saved by the caller: the neutral own-account wording', async () => {
const { dialog } = await startConflict(serverDraft(5, USER))
expect(
await dialog.findByText(
'depuis une autre session de votre compte, le 4 novembre 2026 à 14:32',
),
).toBeInTheDocument()
expect(dialog.queryByText(/Moi/)).toBeNull()
})
it('no matching last save: N alone, never an invented author', async () => {
const { user, dialog } = await startConflict(serverDraft(5, null))
expect(
await screen.findByRole('dialog', {
name: 'Une autre session a enregistré la révision 5',
}),
).toBeInTheDocument()
expect(dialog.queryByText(/par |depuis/)).toBeNull()
await user.click(dialog.getByRole('button', { name: 'Garder ma version' }))
expect(
dialog.getByText('Remplacer la révision 5 par votre version ?'),
).toBeInTheDocument()
})
it('reload asks first, then reloads the server draft and clears the dialog', async () => {
const { user, dialog } = await startConflict(serverDraft(5, 'other-user'))
await dialog.findByText(/Autre Praticien/)
serverHas(baseText(), 5)
await user.click(dialog.getByRole('button', { name: 'Recharger' }))
expect(
dialog.getByText(
'Abandonner vos modifications et recharger la révision 5 ?',
),
).toBeInTheDocument()
await user.click(dialog.getByRole('button', { name: 'Recharger' }))
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(store.getState()).toMatchObject({ unsaved: false, savedRevision: 5 })
expect(await screen.findByText('Révision 5')).toBeInTheDocument()
})
it('Annuler leaves everything as it was', async () => {
const { user, dialog } = await startConflict(serverDraft(5, 'other-user'))
await dialog.findByText(/Autre Praticien/)
await user.click(dialog.getByRole('button', { name: 'Annuler' }))
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(store.getState().unsaved).toBe(true)
expect(sb.saveSheetDraft).toHaveBeenCalledTimes(1)
})
})
describe('unknown revision (failed read)', () => {
const failed = () => Promise.reject(new SheetFailure('unavailable')) // a Read: built when called
it('no number, no author; keep disabled with its hint; reload and retry offered', async () => {
const { user, dialog } = await startConflict(failed)
expect(
await screen.findByRole('dialog', {
name: 'Une autre session a enregistré une version plus récente de ce brouillon.',
}),
).toBeInTheDocument()
expect(dialog.queryByText(/révision \d/)).toBeNull()
const keep = dialog.getByRole('button', { name: 'Garder ma version' })
expect(keep).toBeDisabled()
expect(keep).toHaveAccessibleDescription(
'Révision du serveur inconnue : rechargez ou réessayez.',
)
expect(dialog.getByRole('button', { name: 'Recharger' })).toBeEnabled()
// « Réessayer » repeats the read and reaches the known variant
sb.getOfficialSheetAdmin.mockResolvedValueOnce(
serverDraft(7, 'other-user') as never,
)
await user.click(dialog.getByRole('button', { name: 'Réessayer' }))
expect(
await screen.findByRole('dialog', {
name: 'Une autre session a enregistré la révision 7',
}),
).toBeInTheDocument()
})
it('reload names the server version without a number', async () => {
const { user, dialog } = await startConflict(failed)
await user.click(await dialog.findByRole('button', { name: 'Recharger' }))
expect(
dialog.getByText(
'Abandonner vos modifications et recharger la version du serveur ?',
),
).toBeInTheDocument()
})
})
describe('after the dialog is dismissed', () => {
it('the header keeps a notice that a newer version exists', async () => {
const { user, dialog } = await startConflict(() =>
Promise.reject(new SheetFailure('unavailable')),
)
await dialog.findByRole('button', { name: 'Garder ma version' })
await user.click(dialog.getByRole('button', { name: 'Annuler' }))
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(
screen.getByText(
'Une autre session a enregistré une version plus récente de ce brouillon.',
),
).toBeInTheDocument()
})
})
@@ -0,0 +1,286 @@
/** Lot E: the blocking recovery offer, the unreadable copy, the cap and quota notice. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { fr } from '@/i18n/fr'
import { useLeaveGuardStore } from '@/state/leaveGuardStore'
import {
SHEET,
USER,
VERSION,
baseText,
commitMove,
copyKeyOf,
resetStore,
sb,
serverHas,
storedCopy,
store,
} from '../helpers/editorHarness'
import { grant, mountDraft, setWidth } from '../helpers/editorRoute'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
getSheetVersion: vi.fn(),
downloadSheetDrawing: vi.fn(),
saveSheetDraft: vi.fn(),
getOfficialSheetAdmin: vi.fn(),
submitSheetReview: vi.fn(),
}))
beforeEach(() => serverHas(baseText(), 3))
afterEach(() => {
cleanup()
resetStore()
setWidth(1024)
})
const ready = () =>
screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
function movedText(x: number): string {
return JSON.stringify(
JSON.parse(baseText(), (key, value) => (key === 'cx' ? x : value)),
)
}
function seed(
version: string,
revision: number,
text = movedText(10),
over = {},
) {
sessionStorage.setItem(
copyKeyOf(version, USER),
JSON.stringify({
v: 1,
user_id: USER,
version_id: version,
sheet_id: version === VERSION ? SHEET : `sheet-${version}`,
sheet_name: 'Autre fiche',
revision,
written_at: '2026-11-03T10:00:00Z',
document: JSON.parse(text),
drawings: [],
...over,
}),
)
}
describe('the blocking offer', () => {
it('names the copy and its answers; consultation works, editing is refused', async () => {
const user = userEvent.setup()
seed(VERSION, 3)
mountDraft()
await ready()
expect(
screen.getByText(
/Une copie locale temporaire de ce brouillon existe dans cet onglet \(révision 3, \d\d:\d\d\)/,
),
).toBeInTheDocument()
expect(
screen.getByText(/Choisissez avant de modifier le brouillon\./),
).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Restaurer la copie' }),
).toBeEnabled()
expect(
screen.getByRole('button', { name: 'Ignorer la copie' }),
).toBeEnabled()
expect(useLeaveGuardStore.getState().armed).toBe(true)
// consultation: tabs still switch
await user.click(screen.getByRole('tab', { name: 'Références' }))
expect(screen.getByTestId('editor-tab-references')).toHaveAttribute(
'aria-label',
'Références',
)
// editing: refused by the store, no save offered
expect(commitMove(40)).toMatchObject({
ok: false,
kind: 'recovery.pending',
})
expect(screen.getByRole('button', { name: 'Enregistrer' })).toBeDisabled()
expect(sessionStorage.getItem(copyKeyOf())).not.toBeNull()
})
it('an older base adds the server revision to the notice', async () => {
seed(VERSION, 2)
mountDraft()
await ready()
expect(
screen.getByText(
/Elle est basée sur la révision 2 ; le serveur est à la révision 3\./,
),
).toBeInTheDocument()
})
it('restore applies the copy as unsaved work and lifts the block', async () => {
const user = userEvent.setup()
seed(VERSION, 3)
mountDraft()
await ready()
await user.click(screen.getByRole('button', { name: 'Restaurer la copie' }))
expect(
await screen.findByText('Révision 3 · modifications non enregistrées'),
).toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'Restaurer la copie' }),
).toBeNull()
expect(store.getState()).toMatchObject({ recovery: 'none', unsaved: true })
})
it('ignore asks first and keeps the copy until confirmed', async () => {
const user = userEvent.setup()
seed(VERSION, 3)
mountDraft()
await ready()
await user.click(screen.getByRole('button', { name: 'Ignorer la copie' }))
const dialog = within(await screen.findByRole('dialog'))
expect(
dialog.getByText(
/Abandonner la copie locale non enregistrée \(révision 3, \d\d:\d\d\) \? Elle sera supprimée de cet onglet\./,
),
).toBeInTheDocument()
await user.click(dialog.getByRole('button', { name: 'Annuler' }))
expect(sessionStorage.getItem(copyKeyOf())).not.toBeNull()
await user.click(screen.getByRole('button', { name: 'Ignorer la copie' }))
await user.click(
within(await screen.findByRole('dialog')).getByRole('button', {
name: 'Abandonner la copie',
}),
)
await waitFor(() => expect(sessionStorage.getItem(copyKeyOf())).toBeNull())
expect(
screen.queryByRole('button', { name: 'Ignorer la copie' }),
).toBeNull()
expect(useLeaveGuardStore.getState().armed).toBe(false)
expect(store.getState().recovery).toBe('none')
})
it('an unreadable copy: the loss named, « Ignorer » only, kept until ignored', async () => {
const user = userEvent.setup()
sessionStorage.setItem(copyKeyOf(), 'not json{')
mountDraft()
await ready()
expect(
screen.getByText(fr['editor.draft.recovery.unreadable']),
).toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'Restaurer la copie' }),
).toBeNull()
expect(commitMove(40)).toMatchObject({ kind: 'recovery.pending' })
expect(sessionStorage.getItem(copyKeyOf())).toBe('not json{')
await user.click(screen.getByRole('button', { name: 'Ignorer la copie' }))
await user.click(
within(await screen.findByRole('dialog')).getByRole('button', {
name: 'Abandonner la copie',
}),
)
await waitFor(() => expect(sessionStorage.getItem(copyKeyOf())).toBeNull())
})
it('a copy the core refuses is kept: its kind shown, restore disabled', async () => {
const broken = JSON.parse(baseText())
broken.views = 'broken'
seed(VERSION, 3, JSON.stringify(broken))
const user = userEvent.setup()
mountDraft()
await ready()
await user.click(screen.getByRole('button', { name: 'Restaurer la copie' }))
expect(
await screen.findByText(
/La copie locale ne passe pas le contrôle du document : .+\. Elle est conservée\./,
),
).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Restaurer la copie' }),
).toBeDisabled()
expect(sessionStorage.getItem(copyKeyOf())).not.toBeNull()
})
it('narrow screen: the offer shows; a mode that cannot save names the copy and leaves it', async () => {
seed(VERSION, 3)
mountDraft({ width: 800 })
await ready()
expect(
screen.getByRole('button', { name: 'Restaurer la copie' }),
).toBeInTheDocument()
cleanup()
resetStore()
serverHas(baseText(), 3)
seed(VERSION, 3)
const raw = sessionStorage.getItem(copyKeyOf())
mountDraft({ grants: [grant('sheet_reviewer')] })
await ready()
expect(
screen.queryByRole('button', { name: 'Restaurer la copie' }),
).toBeNull()
expect(
screen.getByText(fr['editor.draft.mode.unusable_copy']),
).toBeInTheDocument()
expect(sessionStorage.getItem(copyKeyOf())).toBe(raw)
})
})
describe('cap and quota', () => {
it('cap: the header says so, the other copies are listed with their sheet link; abandon retries the write', async () => {
const user = userEvent.setup()
seed('ver-2', 5)
seed('ver-3', 6)
mountDraft()
await ready()
act(() => void commitMove(40))
expect(
await screen.findByText(fr['editor.draft.status.copy_cap']),
).toBeInTheDocument()
expect(storedCopy()).toBeNull()
const items = screen.getAllByRole('listitem')
expect(items).toHaveLength(2)
expect(
within(items[0]).getByText(/Autre fiche · révision 5 · \d\d:\d\d/),
).toBeInTheDocument()
expect(
within(items[0]).getByRole('link', { name: 'Ouvrir ce brouillon' }),
).toHaveAttribute('href', '/app/admin/sheets/sheet-ver-2/draft')
await user.click(
within(items[0]).getByRole('button', { name: 'Abandonner cette copie' }),
)
const dialog = within(await screen.findByRole('dialog'))
expect(dialog.getByText(/révision 5/)).toBeInTheDocument()
await user.click(
dialog.getByRole('button', { name: 'Abandonner la copie' }),
)
await waitFor(() => expect(storedCopy()).not.toBeNull())
expect(sessionStorage.getItem(copyKeyOf('ver-2'))).toBeNull()
expect(sessionStorage.getItem(copyKeyOf('ver-3'))).not.toBeNull()
expect(screen.queryByText(fr['editor.draft.status.copy_cap'])).toBeNull()
})
it('quota: the full-storage status and notice, the other copies untouched', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError')
})
mountDraft()
await ready()
act(() => void commitMove(40))
expect(
await screen.findByText('Copie locale impossible (stockage plein)'),
).toBeInTheDocument()
expect(
screen.getByText(fr['editor.draft.copy_issue.quota']),
).toBeInTheDocument()
expect(store.getState().copyWritten).toBe(false)
})
})
describe('the save stays disabled while the offer is pending', () => {
it('no save call is made', async () => {
seed(VERSION, 3)
mountDraft()
await ready()
await store.getState().save()
expect(sb.saveSheetDraft).not.toHaveBeenCalled()
})
})
+394
View File
@@ -0,0 +1,394 @@
/** Lot E: the draft route, header, tabs, modes and permission states, leave guard. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SheetFailure } from '@faunosteo/supabase'
import { useAuthStore } from '@/state/authStore'
import { useLeaveGuardStore } from '@/state/leaveGuardStore'
import { fr } from '@/i18n/fr'
import {
VERSION,
baseText,
commitMove,
resetStore,
sb,
serverHas,
storedCopy,
store,
} from '../helpers/editorHarness'
import {
adminAnswer,
grant,
mountDraft,
round,
setWidth,
} from '../helpers/editorRoute'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
getSheetVersion: vi.fn(),
downloadSheetDrawing: vi.fn(),
saveSheetDraft: vi.fn(),
getOfficialSheetAdmin: vi.fn(),
submitSheetReview: vi.fn(),
}))
beforeEach(() => serverHas(baseText(), 3))
afterEach(() => {
cleanup()
resetStore()
setWidth(1024)
})
const ready = () =>
screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
const TABS = [
'Général',
'Vues et illustrations',
'Annotations',
'Constats',
'Références',
'Vertèbres',
'Vérification',
]
describe('edit mode', () => {
it('header, badges, the seven tabs, nothing read-only', async () => {
mountDraft()
await ready()
expect(screen.getByText('Brouillon')).toBeInTheDocument()
expect(screen.getByText('Copie de travail')).toBeInTheDocument()
expect(screen.getByRole('status', { name: '' })).toBeDefined()
expect(screen.getByText('Révision 3')).toBeInTheDocument()
const tabs = within(screen.getByRole('tablist')).getAllByRole('tab')
expect(tabs.map((tab) => tab.textContent)).toEqual(TABS)
expect(screen.getByRole('tab', { name: 'Annotations' })).toHaveAttribute(
'aria-selected',
'true',
)
expect(screen.queryByText('Lecture seule')).toBeNull()
expect(screen.getByRole('button', { name: 'Enregistrer' })).toBeDisabled()
expect(store.getState()).toMatchObject({
canEdit: true,
versionId: VERSION,
})
})
it('opens the draft read for this version only and closes the session on leaving', async () => {
const view = mountDraft()
await ready()
expect(sb.getSheetVersion).toHaveBeenCalledWith(expect.anything(), VERSION)
view.unmount()
expect(store.getState().status).toBe('idle')
})
it('a commit shows the unsaved line; Enregistrer saves against the loaded revision', async () => {
const user = userEvent.setup()
sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never)
mountDraft()
await ready()
act(() => void commitMove(40))
expect(
await screen.findByText('Révision 3 · modifications non enregistrées'),
).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
expect(await screen.findByText('Révision 4')).toBeInTheDocument()
expect(sb.saveSheetDraft).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ version_id: VERSION, expected_revision: 3 }),
)
expect(storedCopy()).toBeNull()
})
it('« Annuler les modifications » asks first, then reloads the server draft', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
act(() => void commitMove(40))
await user.click(
await screen.findByRole('button', { name: 'Annuler les modifications' }),
)
const dialog = within(await screen.findByRole('dialog'))
expect(dialog.getByText(fr['editor.draft.discard_ask'])).toBeInTheDocument()
await user.click(
dialog.getByRole('button', { name: 'Abandonner les modifications' }),
)
await waitFor(() => expect(store.getState().unsaved).toBe(false))
expect(await screen.findByText('Révision 3')).toBeInTheDocument()
})
})
describe('tabs', () => {
it('arrow keys move between the shown tabs, only the active body is mounted', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
expect(screen.getByTestId('editor-tab-annotations')).toBeInTheDocument()
await user.click(screen.getByRole('tab', { name: 'Annotations' }))
await user.keyboard('{ArrowRight}')
expect(screen.getByRole('tab', { name: 'Constats' })).toHaveAttribute(
'aria-selected',
'true',
)
expect(screen.getByTestId('editor-tab-findings')).toBeInTheDocument()
expect(screen.queryByTestId('editor-tab-annotations')).toBeNull()
expect(screen.getByRole('tabpanel')).toHaveAccessibleName('Constats')
})
it('640 to 1 023 px: four tabs and « Plus »; the others sit under the disclosure', async () => {
const user = userEvent.setup()
mountDraft({ width: 800 })
await ready()
const shown = within(screen.getByRole('tablist')).getAllByRole('tab')
expect(shown.map((tab) => tab.textContent)).toEqual([
'Général',
'Annotations',
'Constats',
'Vérification',
])
const more = screen.getByRole('button', { name: 'Plus' })
expect(more).toHaveAttribute('aria-expanded', 'false')
expect(screen.queryByRole('button', { name: 'Références' })).toBeNull()
await user.click(more)
expect(more).toHaveAttribute('aria-expanded', 'true')
await user.click(screen.getByRole('button', { name: 'Références' }))
expect(screen.getByTestId('editor-tab-references')).toBeInTheDocument()
expect(more).toHaveAttribute('aria-expanded', 'false')
})
it('below 640 px: two tabs and « Plus » listing the five others', async () => {
const user = userEvent.setup()
mountDraft({ width: 375 })
await ready()
const shown = within(screen.getByRole('tablist')).getAllByRole('tab')
expect(shown.map((tab) => tab.textContent)).toEqual([
'Annotations',
'Vérification',
])
await user.click(screen.getByRole('button', { name: 'Plus' }))
const rest = within(screen.getByRole('list')).getAllByRole('button')
expect(rest.map((b) => b.textContent)).toEqual([
'Général',
'Vues et illustrations',
'Constats',
'Références',
'Vertèbres',
])
})
})
describe('read-only modes', () => {
it('narrow: the L15 notice alone, the lock badge, no save, tabs readable, copy offered', async () => {
mountDraft({ width: 800 })
await ready()
expect(
screen.getByText(
"L'édition nécessite une largeur d'écran d'au moins 1 024 px.",
),
).toBeInTheDocument()
expect(screen.getByText('Lecture seule')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Enregistrer' })).toBeNull()
expect(screen.queryByText(/Ici, consultation seule/)).toBeNull()
})
it('a width switch keeps the unsaved work and the leave guard', async () => {
mountDraft()
await ready()
act(() => void commitMove(40))
act(() => {
setWidth(800)
window.dispatchEvent(new Event('resize'))
})
expect(await screen.findByText('Lecture seule')).toBeInTheDocument()
expect(store.getState().unsaved).toBe(true)
expect(useLeaveGuardStore.getState().armed).toBe(true)
act(() => {
setWidth(1280)
window.dispatchEvent(new Event('resize'))
})
expect(
await screen.findByRole('button', { name: 'Enregistrer' }),
).toBeEnabled()
expect(store.getState().unsaved).toBe(true)
})
it('rights: a reviewer without the editor capability reads the draft', async () => {
mountDraft({ grants: [grant('sheet_reviewer')] })
await ready()
expect(screen.getByText(fr['editor.draft.mode.rights'])).toBeInTheDocument()
expect(screen.getByText('Lecture seule')).toBeInTheDocument()
expect(store.getState().canEdit).toBe(false)
})
it('rights: the editor capability without the admin or owner role is read-only', async () => {
mountDraft({ roles: [] })
await ready()
expect(screen.getByText(fr['editor.draft.mode.rights'])).toBeInTheDocument()
})
it('frozen: the round, its label and the link to the overview', async () => {
mountDraft({ answer: adminAnswer({ rounds: [round('verifying')] }) })
await ready()
expect(
screen.getByText('Revue n° 1 · vérification en cours'),
).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Voir la fiche' })).toHaveAttribute(
'href',
expect.stringMatching(/\/app\/admin\/sheets\/[^/]+$/),
)
})
it('frozen by an open round: the round status label', async () => {
mountDraft({
answer: adminAnswer({ rounds: [round('open', { round: 2 })] }),
})
await ready()
expect(screen.getByText('Revue n° 2 · À relire')).toBeInTheDocument()
})
it('a round that no longer freezes (changes requested) leaves the draft editable', async () => {
mountDraft({
answer: adminAnswer({ rounds: [round('changes_requested')] }),
})
await ready()
expect(screen.queryByText('Lecture seule')).toBeNull()
})
it('historical and inactive sheets', async () => {
mountDraft({ answer: adminAnswer({ historical: true }) })
await ready()
expect(
screen.getByText(fr['editor.draft.mode.historical']),
).toBeInTheDocument()
cleanup()
resetStore()
serverHas(baseText(), 3)
mountDraft({ answer: adminAnswer({ status: 'archived' }) })
await ready()
expect(
screen.getByText(fr['editor.draft.mode.inactive']),
).toBeInTheDocument()
})
})
describe('permission states', () => {
it('own grants loading: waits, reads nothing of the draft', async () => {
mountDraft({ grantsStatus: 'loading' })
expect(screen.getByText(fr['shell.loading_session'])).toHaveAttribute(
'role',
'status',
)
await act(async () => {})
expect(sb.getSheetVersion).not.toHaveBeenCalled()
})
it('a rights refusal of the admin read: « Accès non autorisé »', async () => {
mountDraft({ adminFailure: 'rights.capability' })
expect(
await screen.findByRole('heading', { name: fr['access_denied.title'] }),
).toBeInTheDocument()
})
it('own grants unreadable: the unavailable notice with its retry', async () => {
const reloadAccess = vi.fn(async () =>
useAuthStore.setState({ catalogGrantsStatus: 'ready' }),
)
mountDraft({ grantsStatus: 'failed' })
act(() => useAuthStore.setState({ reloadAccess }))
await act(async () => {})
const user = userEvent.setup()
await user.click(await screen.findByRole('button', { name: 'Réessayer' }))
expect(reloadAccess).toHaveBeenCalled()
await ready()
})
it('an unknown sheet: the not found page', async () => {
mountDraft({ adminFailure: 'not_found' })
expect(
await screen.findByRole('heading', {
name: fr['admin.overview.not_found_title'],
}),
).toBeInTheDocument()
})
it('no draft: a notice and the link to the overview', async () => {
mountDraft({ answer: adminAnswer({ draft_version: null }) })
expect(await screen.findByText(fr['editor.draft.none'])).toBeInTheDocument()
expect(
screen.getByRole('link', { name: 'Voir la fiche' }),
).toBeInTheDocument()
expect(sb.getSheetVersion).not.toHaveBeenCalled()
})
})
describe('leave guard', () => {
it('armed from the store flag while unsaved, disarmed once saved', async () => {
const user = userEvent.setup()
sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never)
mountDraft()
await ready()
expect(useLeaveGuardStore.getState().armed).toBe(false)
act(() => void commitMove(40))
await waitFor(() => expect(useLeaveGuardStore.getState().armed).toBe(true))
const event = new Event('beforeunload', { cancelable: true })
window.dispatchEvent(event)
expect(event.defaultPrevented).toBe(true)
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
await waitFor(() => expect(useLeaveGuardStore.getState().armed).toBe(false))
const after = new Event('beforeunload', { cancelable: true })
window.dispatchEvent(after)
expect(after.defaultPrevented).toBe(false)
})
it('leaving the page disarms it', async () => {
const view = mountDraft()
await ready()
act(() => void commitMove(40))
await waitFor(() => expect(useLeaveGuardStore.getState().armed).toBe(true))
view.unmount()
expect(useLeaveGuardStore.getState().armed).toBe(false)
})
})
describe('permission lost during the session', () => {
async function refusedSave(
kind: ConstructorParameters<typeof SheetFailure>[0],
) {
const user = userEvent.setup()
sb.saveSheetDraft.mockRejectedValue(new SheetFailure(kind))
mountDraft()
await ready()
act(() => void commitMove(40))
await user.click(await screen.findByRole('button', { name: 'Enregistrer' }))
}
it('draft.frozen: the message promises a copy only because it was written; read-only follows', async () => {
await refusedSave('draft.frozen')
expect(
await screen.findByText(/Une revue est en cours sur ce brouillon/),
).toHaveTextContent('Une copie locale temporaire existe dans cet onglet.')
expect(screen.getByText('Lecture seule')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Enregistrer' })).toBeNull()
expect(sb.saveSheetDraft).toHaveBeenCalledTimes(1)
})
it('session lost with a failed copy write: the changes cannot be kept', async () => {
const user = userEvent.setup()
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError')
})
sb.saveSheetDraft.mockRejectedValue(new SheetFailure('session_expired'))
mountDraft()
await ready()
act(() => void commitMove(40))
expect(
await screen.findByText('Copie locale impossible (stockage plein)'),
).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
const notice = await screen.findByText(/Votre session a expiré/)
expect(notice).toHaveTextContent(fr['editor.draft.copy_not_kept'])
expect(notice).not.toHaveTextContent(fr['editor.draft.copy_kept'])
})
})
+23 -2
View File
@@ -159,6 +159,7 @@ function mount(
<Route path="sheets" element={<AdminSheetsRoute />} /> <Route path="sheets" element={<AdminSheetsRoute />} />
<Route path="sheets/new" element={<AdminSheetCreateRoute />} /> <Route path="sheets/new" element={<AdminSheetCreateRoute />} />
<Route path="sheets/:sheetId" element={<AdminSheetRoute />} /> <Route path="sheets/:sheetId" element={<AdminSheetRoute />} />
<Route path="sheets/:sheetId/draft" element={<p>draft page</p>} />
<Route path="species" element={<AdminSpeciesRoute />} /> <Route path="species" element={<AdminSpeciesRoute />} />
<Route path="access" element={<AdminAccessRoute />} /> <Route path="access" element={<AdminAccessRoute />} />
</Route> </Route>
@@ -782,7 +783,7 @@ describe('Sheet creation (A1)', () => {
await waitFor(() => await waitFor(() =>
expect(screen.getByTestId('where')).toHaveTextContent( expect(screen.getByTestId('where')).toHaveTextContent(
`/app/admin/sheets/${NEW_ID}`, `/app/admin/sheets/${NEW_ID}/draft`,
), ),
) )
const [args] = rpcArgs('create_official_sheet') const [args] = rpcArgs('create_official_sheet')
@@ -916,6 +917,26 @@ describe('Sheet overview (H3)', () => {
).toBeNull() ).toBeNull()
}) })
it('links to the draft: « Ouvrir » for an editor with the admin role, « Consulter » otherwise', async () => {
fake.rpcResults.get_official_sheet_admin = { data: overview() }
mount(`/app/admin/sheets/${SHEET}`, [grant('sheet_editor')], ['admin'])
const open = await screen.findByRole('link', { name: 'Ouvrir le brouillon' })
expect(open).toHaveAttribute('href', `/app/admin/sheets/${SHEET}/draft`)
cleanup()
mount(`/app/admin/sheets/${SHEET}`, [grant('sheet_reviewer')])
const view = await screen.findByRole('link', { name: 'Consulter le brouillon' })
expect(view).toHaveAttribute('href', `/app/admin/sheets/${SHEET}/draft`)
})
it('links nothing without a draft', async () => {
fake.rpcResults.get_official_sheet_admin = {
data: overview({ draft_version: null }),
}
mount(`/app/admin/sheets/${SHEET}`, [grant('sheet_editor')], ['admin'])
await screen.findByRole('heading', { level: 1 })
expect(screen.queryByRole('link', { name: /brouillon/ })).toBeNull()
})
it('historical sheet: the working copy action disabled while a copy is active', async () => { it('historical sheet: the working copy action disabled while a copy is active', async () => {
fake.rpcResults.get_official_sheet_admin = { fake.rpcResults.get_official_sheet_admin = {
data: { data: {
@@ -965,7 +986,7 @@ describe('Sheet overview (H3)', () => {
await user.click(dialog.getByRole('button', { name: 'Créer la copie' })) await user.click(dialog.getByRole('button', { name: 'Créer la copie' }))
await waitFor(() => await waitFor(() =>
expect(screen.getByTestId('where')).toHaveTextContent( expect(screen.getByTestId('where')).toHaveTextContent(
`/app/admin/sheets/${NEW_ID}`, `/app/admin/sheets/${NEW_ID}/draft`,
), ),
) )
expect(rpcArgs('create_sheet_working_copy')).toEqual([ expect(rpcArgs('create_sheet_working_copy')).toEqual([
@@ -41,6 +41,8 @@ function mount(path = '/app') {
<Route path="/app" element={<AppLayout />}> <Route path="/app" element={<AppLayout />}>
<Route index element={<p>dashboard page</p>} /> <Route index element={<p>dashboard page</p>} />
<Route path="account" element={<p>account page</p>} /> <Route path="account" element={<p>account page</p>} />
<Route path="admin/sheets/:sheetId/draft" element={<p>draft page</p>} />
<Route path="admin/sheets/:sheetId" element={<p>overview page</p>} />
</Route> </Route>
</Routes> </Routes>
</MemoryRouter>, </MemoryRouter>,
@@ -58,6 +60,18 @@ describe('AppLayout', () => {
expect(screen.getByText('dashboard page')).toBeInTheDocument() expect(screen.getByText('dashboard page')).toBeInTheDocument()
}) })
it('gives the draft editor the whole width, every other page the 4xl column', () => {
const column = (path: string) => {
const view = mount(path)
const wrapper = screen.getByText(/page$/).parentElement
view.unmount()
return wrapper
}
expect(column('/app/admin/sheets/s-1/draft')).not.toHaveClass('max-w-4xl')
expect(column('/app/admin/sheets/s-1')).toHaveClass('max-w-4xl')
expect(column('/app')).toHaveClass('max-w-4xl')
})
it('links the top-bar avatar and name to the account page', async () => { it('links the top-bar avatar and name to the account page', async () => {
const user = userEvent.setup() const user = userEvent.setup()
mount() mount()