feat(app): editor Général, Références and Vertèbres tabs, delete with dependents

This commit is contained in:
bchanot committed 2026-11-04 12:46:55 +01:00
1 parent 6aba9711f0
commit d163b2ce9a
24 files changed
+2239 -12

No files matched your search

@@ -81,3 +81,99 @@ Status column: `ratified` = REVUE.md wording; `plan wording` = quoted in the pla
| `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 |
## Lot F (Général, Références, Vertèbres, delete with dependents)
| Key | FR | EN | Where | Status |
|---|---|---|---|---|
| `editor.action.delete` | Supprimer | Delete | Row delete button | plan wording |
| `editor.action.remove` | Retirer | Remove | Remove an author | proposal |
| `editor.action.move_up` | Monter | Move up | Reorder button label (↑) | proposal |
| `editor.action.move_down` | Descendre | Move down | Reorder button label (↓) | proposal |
| `editor.field.required` | Ce champ est obligatoire. | This field is required. | Blank required field | proposal |
| `editor.field.required_names` | Renseignez le nom en français et en anglais. | Fill in the name in French and in English. | Creation form, names missing | proposal |
| `editor.field.integer` | Indiquez un nombre entier. | Enter a whole number. | Count field not a whole number | proposal |
| `editor.field.choose` | Choisir… | Choose… | Empty option of a required choice | proposal |
| `editor.refusal.blocked` | La modification n'a pas été appliquée. | The change was not applied. | Command blocked by the store | proposal |
| `editor.refusal.recovery` | Répondez d'abord à la copie locale proposée en haut de page. | First answer the local copy offered at the top of the page. | Command blocked by a pending recovery offer | proposal |
| `editor.refusal.core.unknown_key` | Cet élément n'existe plus dans le brouillon. | This element no longer exists in the draft. | Core refusal unknown_key | proposal |
| `editor.refusal.core.duplicate_key` | Un élément porte déjà cet identifiant. | An element already has this identifier. | Core refusal duplicate_key | proposal |
| `editor.refusal.core.invalid_target` | Cette modification ne s'applique pas à cet élément. | This change does not apply to this element. | Core refusal invalid_target | proposal |
| `editor.refusal.core.id_changed` | L'identifiant ou le code d'un élément ne se modifie pas. | An element's identifier or code cannot be changed. | Core refusal id_changed | proposal |
| `editor.refusal.core.invalid_position` | Cette position n'existe pas dans la liste. | This position does not exist in the list. | Core refusal invalid_position | proposal |
| `editor.refusal.core.too_deep` | L'arbre est trop profond (8 niveaux au plus). | The tree is too deep (8 levels at most). | Core refusal too_deep | plan wording (depth 8) |
| `editor.refusal.core.has_dependents` | D'autres éléments utilisent encore celui-ci. | Other elements still use this one. | Core refusal has_dependents | proposal |
| `editor.refusal.core.other` | Le contrôle du document refuse cette valeur ({kind}). | The document check refuses this value ({kind}). | Any other core refusal; {kind} = the core's closed kind | proposal |
| `editor.element.sheet` | Fiche | Sheet | Dependents list, element kind | proposal |
| `editor.element.reference` | Référence | Reference | Dependents list, element kind | proposal |
| `editor.element.region` | Région vertébrale | Vertebral region | Dependents list, element kind | proposal |
| `editor.element.category` | Catégorie | Category | Dependents list, element kind | proposal |
| `editor.element.view` | Vue | View | Dependents list, element kind | proposal |
| `editor.element.annotation` | Annotation | Annotation | Dependents list, element kind | proposal |
| `editor.element.zone` | Zone de constats | Finding zone | Dependents list, element kind | proposal |
| `editor.element.finding` | Constat | Finding | Dependents list, element kind | proposal |
| `editor.relation.drawn_in` | dessinée dans cette vue | drawn in this view | Dependents list, relation | proposal |
| `editor.relation.child_view` | vue de détail de cette vue | detail view of this view | Dependents list, relation | proposal |
| `editor.relation.opens` | ouvre cette vue | opens this view | Dependents list, relation | proposal |
| `editor.relation.uses_category` | utilise cette catégorie | uses this category | Dependents list, relation | proposal |
| `editor.relation.links_zone` | est liée à cette zone de constats | is linked to this finding zone | Dependents list, relation | proposal |
| `editor.relation.cites` | cite cette référence | cites this reference | Dependents list, relation | proposal |
| `editor.relation.uses_region` | utilise cette région vertébrale | uses this vertebral region | Dependents list, relation | proposal |
| `editor.relation.descendant` | fait partie de cet élément | is part of this element | Dependents list, relation | proposal |
| `editor.delete.title` | Supprimer « {name} » ? | Delete "{name}"? | Delete dialog title | proposal |
| `editor.delete.ask` | Supprimer « {name} » du brouillon ? | Delete "{name}" from the draft? | Delete dialog, no dependents | proposal |
| `editor.delete.descendants` | Les éléments suivants seront aussi supprimés : | These elements will be deleted too: | Delete dialog, descendants listed | plan wording (meaning) |
| `editor.delete.blocked` | « {name} » ne peut pas être supprimé : les éléments suivants l'utilisent encore. | "{name}" cannot be deleted: the following elements still use it. | Delete dialog, refusal with dependents | plan wording (meaning) |
| `editor.delete.lookup_failed` | Impossible de vérifier ce qui utilise cet élément. Réessayez. | Could not check what uses this element. Try again. | Delete dialog, dependents lookup failed | proposal |
| `editor.delete.confirm` | Supprimer | Delete | Delete dialog, confirm button | proposal |
| `editor.delete.cancel` | Annuler | Cancel | Delete dialog, cancel button | proposal |
| `editor.delete.close` | Fermer | Close | Delete dialog, close button | proposal |
| `editor.general.texts` | Fiche | Sheet | Général, section title | proposal |
| `editor.general.name_fr` | Nom (FR) | Name (FR) | Général, sheet name | plan wording FR; EN proposal |
| `editor.general.name_en` | Nom (EN) | Name (EN) | Général, sheet name | plan wording FR; EN proposal |
| `editor.general.description_fr` | Description (FR) | Description (FR) | Général | proposal |
| `editor.general.description_en` | Description (EN) | Description (EN) | Général | proposal |
| `editor.general.scope_disclaimer_fr` | Périmètre et limites (FR) | Scope and limits (FR) | Général, scope disclaimer | proposal |
| `editor.general.scope_disclaimer_en` | Périmètre et limites (EN) | Scope and limits (EN) | Général, scope disclaimer | proposal |
| `editor.general.attribution` | Attribution | Attribution | Général, section title | proposal |
| `editor.general.authors` | Auteurs | Authors | Général, authors list | proposal |
| `editor.general.author_new` | Nouvel auteur | New author | Général, add-author field | proposal |
| `editor.general.author_add` | Ajouter l'auteur | Add the author | Général, add-author button | proposal |
| `editor.general.author_remove` | Retirer {name} | Remove {name} | Général, remove-author accessible name | proposal |
| `editor.general.license` | Licence | Licence | Général | proposal |
| `editor.general.notes` | Notes | Notes | Général, attribution notes | proposal |
| `editor.general.categories` | Catégories d'annotation | Annotation categories | Général, section title | plan wording FR; EN proposal |
| `editor.general.category_name_fr` | Nom de la catégorie (FR) | Category name (FR) | Category field | proposal |
| `editor.general.category_name_en` | Nom de la catégorie (EN) | Category name (EN) | Category field | proposal |
| `editor.general.category_color` | Couleur | Colour | Category field | proposal |
| `editor.general.category_color_hint` | Facultative, au format #rrggbb. | Optional, as #rrggbb. | Category colour hint | proposal |
| `editor.general.category_new` | Nouvelle catégorie | New category | Category creation form | proposal |
| `editor.general.category_add` | Ajouter la catégorie | Add the category | Category creation button | proposal |
| `editor.reference.empty` | Aucune référence pour l'instant. | No reference yet. | Références, empty list | proposal |
| `editor.reference.type` | Type | Type | Reference field | proposal |
| `editor.reference.citation` | Citation | Citation | Reference field | proposal |
| `editor.reference.url` | Adresse web (URL) | Web address (URL) | Reference field | proposal |
| `editor.reference.doi` | DOI | DOI | Reference field | proposal |
| `editor.reference.new` | Nouvelle référence | New reference | Reference creation form | proposal |
| `editor.reference.add` | Ajouter la référence | Add the reference | Reference creation button | proposal |
| `editor.reference.required` | Choisissez un type et renseignez la citation. | Choose a type and fill in the citation. | Reference creation, missing field | proposal |
| `editor.reference.type.book` | Livre | Book | Reference type | proposal |
| `editor.reference.type.journal` | Article de revue | Journal article | Reference type | proposal |
| `editor.reference.type.standard` | Norme | Standard | Reference type | proposal |
| `editor.reference.type.legal` | Texte juridique | Legal text | Reference type | proposal |
| `editor.reference.type.web` | Site web | Web page | Reference type | proposal |
| `editor.reference.type.manual` | Manuel | Manual | Reference type | proposal |
| `editor.vertebra.empty` | Aucune région vertébrale pour l'instant. | No vertebral region yet. | Vertèbres, empty list | proposal |
| `editor.vertebra.code` | Code | Code | Region field (read-only after creation) | proposal |
| `editor.vertebra.name_fr` | Nom (FR) | Name (FR) | Region field | proposal |
| `editor.vertebra.name_en` | Nom (EN) | Name (EN) | Region field | proposal |
| `editor.vertebra.count` | Nombre de vertèbres | Number of vertebrae | Region field | proposal |
| `editor.vertebra.range` | Plage possible | Possible range | Region range, read-only label | proposal |
| `editor.vertebra.range_min` | Plage : minimum | Range: minimum | Region range field | proposal |
| `editor.vertebra.range_max` | Plage : maximum | Range: maximum | Region range field | proposal |
| `editor.vertebra.range_apply` | Appliquer la plage | Apply the range | Region range button | proposal |
| `editor.vertebra.range_pair` | Indiquez les deux bornes de la plage, ou aucune. | Fill in both bounds of the range, or neither. | Region range, one bound missing | proposal |
| `editor.vertebra.range_number` | Les bornes de la plage sont des nombres entiers. | The range bounds are whole numbers. | Region range, not numbers | proposal |
| `editor.vertebra.new` | Nouvelle région vertébrale | New vertebral region | Region creation form | proposal |
| `editor.vertebra.add` | Ajouter la région | Add the region | Region creation button | proposal |
| `editor.vertebra.required` | Renseignez le code et les noms français et anglais. | Fill in the code and the French and English names. | Region creation, missing field | proposal |
@@ -0,0 +1,167 @@
import { useMemo, useState } from 'react'
import type {
AnatomicalSheetDocument,
Dependent,
ElementKey,
} from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import { dependentsOf } from '@/editor/core/editOps'
import { refusalMessage } from '@/editor/refusal'
import { elementLabel, useSheetDocument } from '@/editor/sheetDocument'
import { useEditorStore } from '@/editor/state/editorStore'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
export interface DeleteTarget {
key: ElementKey
/** The element's name as the list shows it. */
label: string
}
export interface DeleteDialogProps {
/** null = closed. The dialog asks the core for the dependents each time it opens. */
target: DeleteTarget | null
onClose: () => void
}
/**
* Delete with dependents (shared by the Général, Références, Vertèbres, Vues and Constats
* panels): the core lists what still names the element; if anything does, the dialog
* shows the list and offers no deletion (the core would refuse it); descendants go with
* the element and are listed in the confirmation.
*/
export default function DeleteDialog({ target, onClose }: DeleteDialogProps) {
const t = useT()
const doc = useSheetDocument()
const heading = t('editor.delete.title').replace(
'{name}',
target?.label ?? '',
)
return (
<Dialog
open={target !== null && doc !== null}
onClose={onClose}
title={heading}
>
{target && doc && (
<DeleteBody target={target} doc={doc} onClose={onClose} />
)}
</Dialog>
)
}
function DeleteBody({
target,
doc,
onClose,
}: {
target: DeleteTarget
doc: AnatomicalSheetDocument
onClose: () => void
}) {
const t = useT()
const [failure, setFailure] = useState<string | null>(null)
const found = useMemo(
() => dependentsOf(useEditorStore.getState().documentText, target.key),
[target.key],
)
if (!found.ok) {
return (
<Closing message={t('editor.delete.lookup_failed')} onClose={onClose} />
)
}
const blocking = found.value.filter((d) => d.relation !== 'descendant')
const descendants = found.value.filter((d) => d.relation === 'descendant')
if (blocking.length > 0) {
return (
<>
<p className="text-sm">
{t('editor.delete.blocked').replace('{name}', target.label)}
</p>
<DependentList doc={doc} dependents={blocking} withRelation />
<Closing onClose={onClose} />
</>
)
}
const confirm = () => {
const outcome = useEditorStore
.getState()
.commit({ op: 'remove', key: target.key })
if (outcome.ok) onClose()
else setFailure(refusalMessage(t, outcome))
}
return (
<>
<p className="text-sm">
{t('editor.delete.ask').replace('{name}', target.label)}
</p>
{descendants.length > 0 && (
<>
<p className="mt-2 text-sm">{t('editor.delete.descendants')}</p>
<DependentList doc={doc} dependents={descendants} />
</>
)}
{failure && (
<p
role="alert"
className="mt-2 text-sm text-[var(--color-danger-strong)]"
>
{failure}
</p>
)}
<div className="mt-4 flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={onClose}>
{t('editor.delete.cancel')}
</Button>
<Button type="button" variant="danger" onClick={confirm}>
{t('editor.delete.confirm')}
</Button>
</div>
</>
)
}
function Closing({
message,
onClose,
}: {
message?: string
onClose: () => void
}) {
const t = useT()
return (
<>
{message && <p className="text-sm">{message}</p>}
<div className="mt-4 flex justify-end">
<Button type="button" variant="secondary" onClick={onClose}>
{t('editor.delete.close')}
</Button>
</div>
</>
)
}
function DependentList({
doc,
dependents,
withRelation = false,
}: {
doc: AnatomicalSheetDocument
dependents: readonly Dependent[]
withRelation?: boolean
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
return (
<ul className="mt-2 list-disc space-y-1 pl-5 text-sm">
{dependents.map((d) => (
<li key={JSON.stringify(d.element)}>
{t(`editor.element.${d.element.kind}`)} «{' '}
{elementLabel(doc, d.element, locale)} »
{withRelation && <> : {t(`editor.relation.${d.relation}`)}</>}
</li>
))}
</ul>
)
}
@@ -0,0 +1,38 @@
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Input from '@/components/ui/Input'
import Textarea from '@/components/ui/Textarea'
/**
* A controlled field of a creation form: it never commits, the form's own button does
* (BDR-050). The committed fields of existing elements are `TextField`.
*/
export default function DraftField({
id,
label,
value,
onChange,
multiline,
hint,
error,
}: {
id: string
label: string
value: string
onChange: (value: string) => void
multiline?: boolean
hint?: string
error?: string
}) {
const shared = {
id,
value,
onChange: (e: { target: { value: string } }) => onChange(e.target.value),
'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} />}
</FormField>
)
}
@@ -0,0 +1,41 @@
import { useT } from '@/i18n/useT'
import ActionButton from './ActionButton'
/** ↑ / ↓ for a list row: one `move` per press; absent while read-only. */
export default function MoveButtons({
index,
count,
readOnly,
onMove,
}: {
index: number
count: number
readOnly: boolean
onMove: (position: number) => void
}) {
const t = useT()
return (
<>
<ActionButton
readOnly={readOnly}
variant="ghost"
size="sm"
aria-label={t('editor.action.move_up')}
disabled={index === 0}
onClick={() => onMove(index - 1)}
>
↑
</ActionButton>
<ActionButton
readOnly={readOnly}
variant="ghost"
size="sm"
aria-label={t('editor.action.move_down')}
disabled={index >= count - 1}
onClick={() => onMove(index + 1)}
>
↓
</ActionButton>
</>
)
}
@@ -0,0 +1,129 @@
import { useState } from 'react'
import type {
AnatomicalSheetDocument,
Attribution,
} from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import DraftField from '@/components/editor/fields/DraftField'
import TextField from '@/components/editor/fields/TextField'
import { isBlank, nullable, textsOf } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
/** Authors (add / remove), licence and notes. */
export default function AttributionSection({
doc,
readOnly,
}: {
doc: AnatomicalSheetDocument
readOnly: boolean
}) {
const t = useT()
const edit = useEditCommand()
const attribution = doc.attribution
const send = (field: string, patch: Partial<Attribution>) =>
edit.run(field, {
op: 'update',
key: { kind: 'sheet' },
element: {
kind: 'sheet',
value: { ...textsOf(doc), attribution: { ...attribution, ...patch } },
},
})
return (
<section aria-labelledby="general-attribution" className="space-y-3">
<h3 id="general-attribution" className="text-base font-semibold">
{t('editor.general.attribution')}
</h3>
<Authors
authors={attribution.authors}
readOnly={readOnly}
error={edit.fieldError('authors')}
onChange={(authors) => send('authors', { authors })}
/>
<TextField
id="general-license"
label={t('editor.general.license')}
value={attribution.license ?? ''}
onCommit={(value) => send('license', { license: nullable(value) })}
readOnly={readOnly}
error={edit.fieldError('license')}
/>
<TextField
id="general-notes"
label={t('editor.general.notes')}
value={attribution.notes ?? ''}
onCommit={(value) => send('notes', { notes: nullable(value) })}
readOnly={readOnly}
multiline
error={edit.fieldError('notes')}
/>
</section>
)
}
function Authors({
authors,
readOnly,
error,
onChange,
}: {
authors: readonly string[]
readOnly: boolean
error?: string
onChange: (authors: string[]) => boolean
}) {
const t = useT()
const [draft, setDraft] = useState('')
const add = () => {
if (isBlank(draft)) return
if (onChange([...authors, draft])) setDraft('')
}
return (
<div className="space-y-2">
<p className="text-sm font-medium">{t('editor.general.authors')}</p>
{authors.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">—</p>
)}
<ul className="space-y-1">
{authors.map((author, index) => (
<li
key={`${index}-${author}`}
className="flex items-center gap-2 text-sm"
>
<span className="min-w-0 flex-1 break-words">{author}</span>
<ActionButton
readOnly={readOnly}
variant="ghost"
size="sm"
aria-label={t('editor.general.author_remove').replace(
'{name}',
author,
)}
onClick={() => onChange(authors.filter((_, i) => i !== index))}
>
{t('editor.action.remove')}
</ActionButton>
</li>
))}
</ul>
{!readOnly && (
<div className="flex items-end gap-2">
<div className="min-w-0 flex-1">
<DraftField
id="general-author-new"
label={t('editor.general.author_new')}
value={draft}
onChange={setDraft}
error={error}
/>
</div>
<ActionButton readOnly={readOnly} variant="secondary" onClick={add}>
{t('editor.general.author_add')}
</ActionButton>
</div>
)}
</div>
)
}
@@ -0,0 +1,173 @@
import { useState } from 'react'
import type {
AnatomicalSheetDocument,
AnnotationCategory,
} from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import DraftField from '@/components/editor/fields/DraftField'
import TextField from '@/components/editor/fields/TextField'
import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import { isBlank, nullable } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import type { Locale } from '@/i18n/types'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
/** Annotation categories: list, rename, colour, add, delete with dependents. */
export default function CategoriesSection({
doc,
readOnly,
}: {
doc: AnatomicalSheetDocument
readOnly: boolean
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
return (
<section aria-labelledby="general-categories" className="space-y-3">
<h3 id="general-categories" className="text-base font-semibold">
{t('editor.general.categories')}
</h3>
<ul className="space-y-3">
{doc.categories.map((category) => (
<CategoryRow
key={category.id}
category={category}
readOnly={readOnly}
onDelete={() =>
setDeleting({
key: { kind: 'category', id: category.id },
label: category.name[locale],
})
}
/>
))}
</ul>
{!readOnly && <CategoryForm />}
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
</section>
)
}
function CategoryRow({
category,
readOnly,
onDelete,
}: {
category: AnnotationCategory
readOnly: boolean
onDelete: () => void
}) {
const t = useT()
const edit = useEditCommand()
const send = (field: string, patch: Partial<AnnotationCategory>) =>
edit.run(field, {
op: 'update',
key: { kind: 'category', id: category.id },
element: { kind: 'category', value: { ...category, ...patch } },
})
const rename = (locale: Locale) => (value: string) =>
isBlank(value)
? edit.reject(locale, 'editor.field.required')
: send(locale, { name: { ...category.name, [locale]: value } })
const prefix = `category-${category.id}`
return (
<li className="rounded-lg border border-[var(--color-border)] p-3">
<div className="grid gap-3 md:grid-cols-3">
{(['fr', 'en'] as const).map((locale) => (
<TextField
key={locale}
id={`${prefix}-name-${locale}`}
label={t(`editor.general.category_name_${locale}`)}
value={category.name[locale]}
onCommit={rename(locale)}
readOnly={readOnly}
error={edit.fieldError(locale)}
/>
))}
<TextField
id={`${prefix}-color`}
label={t('editor.general.category_color')}
value={category.color ?? ''}
onCommit={(value) => send('color', { color: nullable(value) })}
readOnly={readOnly}
hint={t('editor.general.category_color_hint')}
error={edit.fieldError('color')}
/>
</div>
<div className="mt-2 flex justify-end">
<ActionButton
readOnly={readOnly}
variant="danger"
size="sm"
onClick={onDelete}
>
{t('editor.action.delete')}
</ActionButton>
</div>
</li>
)
}
function CategoryForm() {
const t = useT()
const edit = useEditCommand()
const [fr, setFr] = useState('')
const [en, setEn] = useState('')
const [color, setColor] = useState('')
const create = () => {
if (isBlank(fr) || isBlank(en)) {
edit.reject('form', 'editor.field.required_names')
return
}
const added = edit.runNew('form', 'cat', (id) => ({
op: 'insert',
element: {
kind: 'category',
value: { id, name: { fr, en }, color: nullable(color) },
},
}))
if (added) {
setFr('')
setEn('')
setColor('')
}
}
return (
<div className="space-y-2 rounded-lg border border-dashed border-[var(--color-border)] p-3">
<p className="text-sm font-medium">{t('editor.general.category_new')}</p>
<div className="grid gap-3 md:grid-cols-3">
<DraftField
id="category-new-fr"
label={t('editor.general.category_name_fr')}
value={fr}
onChange={setFr}
/>
<DraftField
id="category-new-en"
label={t('editor.general.category_name_en')}
value={en}
onChange={setEn}
/>
<DraftField
id="category-new-color"
label={t('editor.general.category_color')}
value={color}
onChange={setColor}
hint={t('editor.general.category_color_hint')}
/>
</div>
{edit.fieldError('form') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('form')}
</p>
)}
<ActionButton readOnly={false} variant="secondary" onClick={create}>
{t('editor.general.category_add')}
</ActionButton>
</div>
)
}
@@ -0,0 +1,70 @@
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import TextField from '@/components/editor/fields/TextField'
import { isBlank, optionalText, textsOf } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import type { Locale } from '@/i18n/types'
import { useT } from '@/i18n/useT'
const LOCALES: readonly Locale[] = ['fr', 'en']
/** Names, description and scope disclaimer of the sheet, FR and EN. */
export default function TextsSection({
doc,
readOnly,
}: {
doc: AnatomicalSheetDocument
readOnly: boolean
}) {
const t = useT()
const edit = useEditCommand()
const send = (field: string, patch: Partial<ReturnType<typeof textsOf>>) =>
edit.run(field, {
op: 'update',
key: { kind: 'sheet' },
element: { kind: 'sheet', value: { ...textsOf(doc), ...patch } },
})
const rename = (locale: Locale) => (value: string) => {
const field = `name-${locale}`
if (isBlank(value)) return edit.reject(field, 'editor.field.required')
return send(field, { name: { ...doc.name, [locale]: value } })
}
const describe =
(key: 'description' | 'scope_disclaimer', locale: Locale) =>
(value: string) =>
send(`${key}-${locale}`, { [key]: optionalText(doc[key], locale, value) })
return (
<section aria-labelledby="general-texts" className="space-y-3">
<h3 id="general-texts" className="text-base font-semibold">
{t('editor.general.texts')}
</h3>
<div className="grid gap-3 md:grid-cols-2">
{LOCALES.map((locale) => (
<TextField
key={`name-${locale}`}
id={`general-name-${locale}`}
label={t(`editor.general.name_${locale}`)}
value={doc.name[locale]}
onCommit={rename(locale)}
readOnly={readOnly}
error={edit.fieldError(`name-${locale}`)}
/>
))}
{(['description', 'scope_disclaimer'] as const).flatMap((key) =>
LOCALES.map((locale) => (
<TextField
key={`${key}-${locale}`}
id={`general-${key}-${locale}`}
label={t(`editor.general.${key}_${locale}`)}
value={doc[key][locale] ?? ''}
onCommit={describe(key, locale)}
readOnly={readOnly}
multiline
error={edit.fieldError(`${key}-${locale}`)}
/>
)),
)}
</div>
</section>
)
}
@@ -0,0 +1,87 @@
import { useState } from 'react'
import type { ReferenceType } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import DraftField from '@/components/editor/fields/DraftField'
import SelectField from '@/components/editor/fields/SelectField'
import { isBlank, nullable } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
import { REFERENCE_TYPES } from './referenceTypes'
const EMPTY = { type: '', citation: '', url: '', doi: '' }
/** Adds a reference: the type and the citation are required, URL and DOI optional. */
export default function ReferenceForm() {
const t = useT()
const edit = useEditCommand()
const [form, setForm] = useState(EMPTY)
const set = (patch: Partial<typeof EMPTY>) => setForm({ ...form, ...patch })
const options = [
{ value: '', label: t('editor.field.choose') },
...REFERENCE_TYPES.map((type) => ({
value: type,
label: t(`editor.reference.type.${type}`),
})),
]
const create = () => {
if (form.type === '' || isBlank(form.citation)) {
edit.reject('form', 'editor.reference.required')
return
}
const added = edit.runNew('form', 'ref', (id) => ({
op: 'insert',
element: {
kind: 'reference',
value: {
id,
type: form.type as ReferenceType,
citation: form.citation,
url: nullable(form.url),
doi: nullable(form.doi),
},
},
}))
if (added) setForm(EMPTY)
}
return (
<div className="space-y-2 rounded-lg border border-dashed border-[var(--color-border)] p-3">
<p className="text-sm font-medium">{t('editor.reference.new')}</p>
<div className="grid gap-3 md:grid-cols-2">
<SelectField
id="reference-new-type"
label={t('editor.reference.type')}
value={form.type}
options={options}
onCommit={(type) => set({ type })}
/>
<DraftField
id="reference-new-citation"
label={t('editor.reference.citation')}
value={form.citation}
onChange={(citation) => set({ citation })}
multiline
/>
<DraftField
id="reference-new-url"
label={t('editor.reference.url')}
value={form.url}
onChange={(url) => set({ url })}
/>
<DraftField
id="reference-new-doi"
label={t('editor.reference.doi')}
value={form.doi}
onChange={(doi) => set({ doi })}
/>
</div>
{edit.fieldError('form') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('form')}
</p>
)}
<ActionButton readOnly={false} variant="secondary" onClick={create}>
{t('editor.reference.add')}
</ActionButton>
</div>
)
}
@@ -0,0 +1,104 @@
import type { Reference, ReferenceType } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import MoveButtons from '@/components/editor/fields/MoveButtons'
import SelectField from '@/components/editor/fields/SelectField'
import TextField from '@/components/editor/fields/TextField'
import { isBlank, nullable } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
import { REFERENCE_TYPES } from './referenceTypes'
/** One reference: fields commit one by one, ↑ / ↓ reorder, delete asks the core. */
export default function ReferenceRow({
reference,
index,
count,
readOnly,
onDelete,
}: {
reference: Reference
index: number
count: number
readOnly: boolean
onDelete: () => void
}) {
const t = useT()
const edit = useEditCommand()
const key = { kind: 'reference', id: reference.id } as const
const send = (field: string, patch: Partial<Reference>) =>
edit.run(field, {
op: 'update',
key,
element: { kind: 'reference', value: { ...reference, ...patch } },
})
const options = REFERENCE_TYPES.map((type) => ({
value: type,
label: t(`editor.reference.type.${type}`),
}))
const prefix = `reference-${reference.id}`
return (
<li className="space-y-3 rounded-lg border border-[var(--color-border)] p-3">
<div className="grid gap-3 md:grid-cols-2">
<SelectField
id={`${prefix}-type`}
label={t('editor.reference.type')}
value={reference.type}
options={options}
onCommit={(type) => send('type', { type: type as ReferenceType })}
readOnly={readOnly}
error={edit.fieldError('type')}
/>
<TextField
id={`${prefix}-citation`}
label={t('editor.reference.citation')}
value={reference.citation}
onCommit={(value) =>
isBlank(value)
? edit.reject('citation', 'editor.field.required')
: send('citation', { citation: value })
}
readOnly={readOnly}
multiline
error={edit.fieldError('citation')}
/>
<TextField
id={`${prefix}-url`}
label={t('editor.reference.url')}
value={reference.url ?? ''}
onCommit={(value) => send('url', { url: nullable(value) })}
readOnly={readOnly}
error={edit.fieldError('url')}
/>
<TextField
id={`${prefix}-doi`}
label={t('editor.reference.doi')}
value={reference.doi ?? ''}
onCommit={(value) => send('doi', { doi: nullable(value) })}
readOnly={readOnly}
error={edit.fieldError('doi')}
/>
</div>
<div className="flex flex-wrap items-center justify-end gap-1">
<MoveButtons
index={index}
count={count}
readOnly={readOnly}
onMove={(position) => edit.run('move', { op: 'move', key, position })}
/>
<ActionButton
readOnly={readOnly}
variant="danger"
size="sm"
onClick={onDelete}
>
{t('editor.action.delete')}
</ActionButton>
</div>
{edit.fieldError('move') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('move')}
</p>
)}
</li>
)
}
@@ -0,0 +1,10 @@
import type { ReferenceType } from '@faunosteo/core-wasm/types'
export const REFERENCE_TYPES: readonly ReferenceType[] = [
'book',
'journal',
'standard',
'legal',
'web',
'manual',
]
@@ -1,14 +1,27 @@
import AttributionSection from '@/components/editor/general/AttributionSection'
import CategoriesSection from '@/components/editor/general/CategoriesSection'
import TextsSection from '@/components/editor/general/TextsSection'
import { useSheetDocument } from '@/editor/sheetDocument'
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) {
/** Général: the sheet's texts, attribution and annotation categories. */
export default function GeneralTab({ readOnly }: EditorTabProps) {
const t = useT()
const doc = useSheetDocument()
return (
<section
data-testid="editor-tab-general"
aria-label={t('editor.tab.general')}
className="min-h-24"
/>
className="min-h-24 space-y-8"
>
{doc && (
<>
<TextsSection doc={doc} readOnly={readOnly} />
<AttributionSection doc={doc} readOnly={readOnly} />
<CategoriesSection doc={doc} readOnly={readOnly} />
</>
)}
</section>
)
}
@@ -1,14 +1,49 @@
import { useState } from 'react'
import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import ReferenceForm from '@/components/editor/references/ReferenceForm'
import ReferenceRow from '@/components/editor/references/ReferenceRow'
import { useSheetDocument } from '@/editor/sheetDocument'
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) {
/** Références: the sheet's bibliography, cited by id from the findings. */
export default function ReferencesTab({ readOnly }: EditorTabProps) {
const t = useT()
const doc = useSheetDocument()
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
const references = doc?.references ?? []
return (
<section
data-testid="editor-tab-references"
aria-label={t('editor.tab.references')}
className="min-h-24"
/>
className="min-h-24 space-y-3"
>
{doc && references.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.reference.empty')}
</p>
)}
<ul className="space-y-3">
{references.map((reference, index) => (
<ReferenceRow
key={reference.id}
reference={reference}
index={index}
count={references.length}
readOnly={readOnly}
onDelete={() =>
setDeleting({
key: { kind: 'reference', id: reference.id },
label: reference.citation,
})
}
/>
))}
</ul>
{doc && !readOnly && <ReferenceForm />}
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
</section>
)
}
@@ -1,14 +1,51 @@
import { useState } from 'react'
import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import RegionForm from '@/components/editor/vertebrae/RegionForm'
import RegionRow from '@/components/editor/vertebrae/RegionRow'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { EditorTabProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
/** Placeholder: Lot F replaces the body and keeps the props contract (`EditorTabProps`). */
export default function VertebraeTab(_props: EditorTabProps) {
/** Vertèbres: the vertebral regions (code, names, count, optional range), ordered. */
export default function VertebraeTab({ readOnly }: EditorTabProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const doc = useSheetDocument()
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
const regions = doc?.vertebral_config.regions ?? []
return (
<section
data-testid="editor-tab-vertebrae"
aria-label={t('editor.tab.vertebrae')}
className="min-h-24"
/>
className="min-h-24 space-y-3"
>
{doc && regions.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.vertebra.empty')}
</p>
)}
<ul className="space-y-3">
{regions.map((region, index) => (
<RegionRow
key={region.code}
region={region}
index={index}
count={regions.length}
readOnly={readOnly}
onDelete={() =>
setDeleting({
key: { kind: 'region', code: region.code },
label: region.name[locale],
})
}
/>
))}
</ul>
{doc && !readOnly && <RegionForm />}
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
</section>
)
}
@@ -0,0 +1,33 @@
import DraftField from '@/components/editor/fields/DraftField'
import { useT } from '@/i18n/useT'
/** The optional count range, two controlled bounds; the caller commits them. */
export default function RangeFields({
idPrefix,
min,
max,
onChange,
}: {
idPrefix: string
min: string
max: string
onChange: (min: string, max: string) => void
}) {
const t = useT()
return (
<>
<DraftField
id={`${idPrefix}-min`}
label={t('editor.vertebra.range_min')}
value={min}
onChange={(value) => onChange(value, max)}
/>
<DraftField
id={`${idPrefix}-max`}
label={t('editor.vertebra.range_max')}
value={max}
onChange={(value) => onChange(min, value)}
/>
</>
)
}
@@ -0,0 +1,89 @@
import { useState } from 'react'
import ActionButton from '@/components/editor/fields/ActionButton'
import DraftField from '@/components/editor/fields/DraftField'
import { isBlank } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
import RangeFields from './RangeFields'
import { parseRange, wholeNumber } from './numbers'
const EMPTY = { code: '', fr: '', en: '', count: '', min: '', max: '' }
/** Adds a region: code (typed once, read-only afterwards), names, count, optional range. */
export default function RegionForm() {
const t = useT()
const edit = useEditCommand()
const [form, setForm] = useState(EMPTY)
const set = (patch: Partial<typeof EMPTY>) => setForm({ ...form, ...patch })
const create = () => {
const count = wholeNumber(form.count)
const range = parseRange(form.min, form.max)
if (isBlank(form.code) || isBlank(form.fr) || isBlank(form.en)) {
edit.reject('form', 'editor.vertebra.required')
} else if (count === null) {
edit.reject('form', 'editor.field.integer')
} else if (!range.ok) {
edit.reject('form', `editor.vertebra.range_${range.reason}`)
} else if (
edit.run('form', {
op: 'insert',
element: {
kind: 'region',
value: {
code: form.code,
name: { fr: form.fr, en: form.en },
count,
count_range: range.range,
},
},
})
) {
setForm(EMPTY)
}
}
return (
<div className="space-y-2 rounded-lg border border-dashed border-[var(--color-border)] p-3">
<p className="text-sm font-medium">{t('editor.vertebra.new')}</p>
<div className="grid gap-3 md:grid-cols-4">
<DraftField
id="region-new-code"
label={t('editor.vertebra.code')}
value={form.code}
onChange={(code) => set({ code })}
/>
<DraftField
id="region-new-fr"
label={t('editor.vertebra.name_fr')}
value={form.fr}
onChange={(fr) => set({ fr })}
/>
<DraftField
id="region-new-en"
label={t('editor.vertebra.name_en')}
value={form.en}
onChange={(en) => set({ en })}
/>
<DraftField
id="region-new-count"
label={t('editor.vertebra.count')}
value={form.count}
onChange={(count) => set({ count })}
/>
<RangeFields
idPrefix="region-new-range"
min={form.min}
max={form.max}
onChange={(min, max) => set({ min, max })}
/>
</div>
{edit.fieldError('form') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('form')}
</p>
)}
<ActionButton readOnly={false} variant="secondary" onClick={create}>
{t('editor.vertebra.add')}
</ActionButton>
</div>
)
}
@@ -0,0 +1,176 @@
import { useState } from 'react'
import type { VertebralRegion } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import MoveButtons from '@/components/editor/fields/MoveButtons'
import ReadOnlyValue from '@/components/editor/fields/ReadOnlyValue'
import TextField from '@/components/editor/fields/TextField'
import { isBlank } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import type { Locale } from '@/i18n/types'
import { useT } from '@/i18n/useT'
import RangeFields from './RangeFields'
import { parseRange, wholeNumber } from './numbers'
const textOf = (value: number | undefined): string =>
value === undefined ? '' : String(value)
/** One vertebral region: the code is read-only after creation, the rest commits per field. */
export default function RegionRow({
region,
index,
count,
readOnly,
onDelete,
}: {
region: VertebralRegion
index: number
count: number
readOnly: boolean
onDelete: () => void
}) {
const t = useT()
const edit = useEditCommand()
const key = { kind: 'region', code: region.code } as const
const send = (field: string, patch: Partial<VertebralRegion>) =>
edit.run(field, {
op: 'update',
key,
element: { kind: 'region', value: { ...region, ...patch } },
})
const rename = (locale: Locale) => (value: string) =>
isBlank(value)
? edit.reject(locale, 'editor.field.required')
: send(locale, { name: { ...region.name, [locale]: value } })
const recount = (value: string) => {
const parsed = wholeNumber(value)
return parsed === null
? edit.reject('count', 'editor.field.integer')
: send('count', { count: parsed })
}
const prefix = `region-${region.code}`
return (
<li className="space-y-3 rounded-lg border border-[var(--color-border)] p-3">
<div className="grid gap-3 md:grid-cols-4">
<ReadOnlyValue
id={`${prefix}-code`}
label={t('editor.vertebra.code')}
value={region.code}
/>
{(['fr', 'en'] as const).map((locale) => (
<TextField
key={locale}
id={`${prefix}-name-${locale}`}
label={t(`editor.vertebra.name_${locale}`)}
value={region.name[locale]}
onCommit={rename(locale)}
readOnly={readOnly}
error={edit.fieldError(locale)}
/>
))}
<TextField
id={`${prefix}-count`}
label={t('editor.vertebra.count')}
value={String(region.count)}
onCommit={recount}
readOnly={readOnly}
error={edit.fieldError('count')}
/>
</div>
<RangeEditor
region={region}
readOnly={readOnly}
onApply={(range) => send('range', { count_range: range })}
reject={(key) => edit.reject('range', key)}
error={edit.fieldError('range')}
/>
<div className="flex flex-wrap items-center justify-end gap-1">
<MoveButtons
index={index}
count={count}
readOnly={readOnly}
onMove={(position) => edit.run('move', { op: 'move', key, position })}
/>
<ActionButton
readOnly={readOnly}
variant="danger"
size="sm"
onClick={onDelete}
>
{t('editor.action.delete')}
</ActionButton>
</div>
{edit.fieldError('move') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('move')}
</p>
)}
</li>
)
}
function RangeEditor({
region,
readOnly,
onApply,
reject,
error,
}: {
region: VertebralRegion
readOnly: boolean
onApply: (range: VertebralRegion['count_range']) => boolean
reject: (messageKey: string) => false
error?: string
}) {
const t = useT()
const saved = {
min: textOf(region.count_range?.min),
max: textOf(region.count_range?.max),
}
const [draft, setDraft] = useState(saved)
const [seen, setSeen] = useState(saved)
if (seen.min !== saved.min || seen.max !== saved.max) {
setSeen(saved)
setDraft(saved)
}
if (readOnly) {
const text = region.count_range ? `${saved.min} – ${saved.max}` : ''
return (
<ReadOnlyValue
id={`region-${region.code}-range`}
label={t('editor.vertebra.range')}
value={text}
/>
)
}
const apply = () => {
const parsed = parseRange(draft.min, draft.max)
if (parsed.ok) onApply(parsed.range)
else reject(`editor.vertebra.range_${parsed.reason}`)
}
return (
<div className="grid items-end gap-3 md:grid-cols-4">
<RangeFields
idPrefix={`region-${region.code}-range`}
min={draft.min}
max={draft.max}
onChange={(min, max) => setDraft({ min, max })}
/>
<ActionButton
readOnly={readOnly}
variant="secondary"
size="sm"
onClick={apply}
>
{t('editor.vertebra.range_apply')}
</ActionButton>
{error && (
<p
role="alert"
className="text-sm text-[var(--color-danger-strong)] md:col-span-4"
>
{error}
</p>
)}
</div>
)
}
@@ -0,0 +1,21 @@
import type { CountRange } from '@faunosteo/core-wasm/types'
/** Digits only: the core decides whether the value is allowed. */
export function wholeNumber(text: string): number | null {
return /^\d+$/.test(text.trim()) ? Number(text.trim()) : null
}
export type RangeInput =
| { ok: true; range: CountRange | null }
| { ok: false; reason: 'pair' | 'number' }
/** Both bounds or none: a half-filled range never reaches the core. */
export function parseRange(min: string, max: string): RangeInput {
const blank = (text: string) => text.trim() === ''
if (blank(min) && blank(max)) return { ok: true, range: null }
if (blank(min) || blank(max)) return { ok: false, reason: 'pair' }
const low = wholeNumber(min)
const high = wholeNumber(max)
if (low === null || high === null) return { ok: false, reason: 'number' }
return { ok: true, range: { min: low, max: high } }
}
+33
View File
@@ -0,0 +1,33 @@
import type { CommitOutcome } from './state/editorTypes'
type Translate = (key: string) => string
const EDIT_KINDS: ReadonlySet<string> = new Set([
'unknown_key',
'duplicate_key',
'invalid_target',
'id_changed',
'invalid_position',
'too_deep',
'has_dependents',
])
/**
* The words for a command that was not kept: the core's closed kind, or the store's
* block. Never the core's detail text (it can echo document content).
*/
export function refusalMessage(
t: Translate,
outcome: Exclude<CommitOutcome, { ok: true }>,
): string {
if (outcome.reason === 'blocked') {
return outcome.kind === 'recovery.pending'
? t('editor.refusal.recovery')
: t('editor.refusal.blocked')
}
if (outcome.reason !== 'core') return t('editor.refusal.blocked')
const { kind } = outcome.failure
return EDIT_KINDS.has(kind)
? t(`editor.refusal.core.${kind}`)
: t('editor.refusal.core.other').replace('{kind}', kind)
}
+130
View File
@@ -0,0 +1,130 @@
import { useMemo } from 'react'
import type {
AnatomicalSheetDocument,
ElementKey,
LocalizedOptionalText,
SheetTexts,
} from '@faunosteo/core-wasm/types'
import type { Locale } from '@/i18n/types'
import { useEditorStore } from './state/editorStore'
/** The edited document, read from the store's text; null while nothing is loaded. */
export function useSheetDocument(): AnatomicalSheetDocument | null {
const text = useEditorStore((s) => s.documentText)
return useMemo(() => {
try {
return text === '' ? null : (JSON.parse(text) as AnatomicalSheetDocument)
} catch {
return null
}
}, [text])
}
export const isBlank = (value: string): boolean => value.trim() === ''
/** A blank optional text is absent (LocalizedOptionalText omits the key, never ""). */
export function optionalText(
current: LocalizedOptionalText,
locale: Locale,
value: string,
): LocalizedOptionalText {
const next = { ...current }
if (isBlank(value)) delete next[locale]
else next[locale] = value
return next
}
/** A blank optional field is null where the type is nullable. */
export const nullable = (value: string): string | null =>
isBlank(value) ? null : value
export function textsOf(doc: AnatomicalSheetDocument): SheetTexts {
return {
name: doc.name,
description: doc.description,
scope_disclaimer: doc.scope_disclaimer,
attribution: doc.attribution,
}
}
interface Named {
id: string
name: { fr: string; en: string }
children: readonly Named[]
}
function findNode(
nodes: readonly Named[],
path: readonly string[],
): Named | undefined {
const [head, ...rest] = path
const node = nodes.find((n) => n.id === head)
if (!node || rest.length === 0) return node
return findNode(node.children, rest)
}
function localized(
name: { fr: string; en: string } | null | undefined,
locale: Locale,
): string | undefined {
return name?.[locale]
}
/** The name an element shows in a list or a dependents message; its id as a last resort. */
export function elementLabel(
doc: AnatomicalSheetDocument,
key: ElementKey,
locale: Locale,
): string {
switch (key.kind) {
case 'sheet':
return doc.name[locale]
case 'reference':
return doc.references.find((r) => r.id === key.id)?.citation ?? key.id
case 'region':
return (
localized(
doc.vertebral_config.regions.find((r) => r.code === key.code)?.name,
locale,
) ?? key.code
)
case 'category':
return (
localized(doc.categories.find((c) => c.id === key.id)?.name, locale) ??
key.id
)
case 'view':
return (
localized(doc.views.find((v) => v.id === key.id)?.name, locale) ??
key.id
)
case 'annotation':
return (
localized(doc.annotations.find((a) => a.id === key.id)?.name, locale) ??
key.id
)
case 'zone':
return (
localized(
doc.finding_zones.find((z) => z.id === key.id)?.name,
locale,
) ?? key.id
)
case 'finding':
return findingLabel(doc, key, locale)
}
}
function findingLabel(
doc: AnatomicalSheetDocument,
key: Extract<ElementKey, { kind: 'finding' }>,
locale: Locale,
): string {
const zone = doc.finding_zones.find((z) => z.id === key.zone_id)
const found = zone ? findNode(zone.categories, key.path) : undefined
return (
localized(found?.name, locale) ??
key.path[key.path.length - 1] ??
key.zone_id
)
}
+64
View File
@@ -0,0 +1,64 @@
import { useState } from 'react'
import type { EditCommand } from '@faunosteo/core-wasm/types'
import { useT } from '@/i18n/useT'
import { newElementId, type IdPrefix } from './ids'
import { refusalMessage } from './refusal'
import { useEditorStore } from './state/editorStore'
interface FieldError {
field: string
message: string
}
export interface EditCommandApi {
/** The refusal phrased for `field`, to show next to its control. */
fieldError: (field: string) => string | undefined
/** Runs one command through the store; a refusal is kept for `field`. */
run: (field: string, command: EditCommand) => boolean
/** Inserts under a fresh id; one regeneration when the core answers `duplicate_key`. */
runNew: (
field: string,
prefix: IdPrefix,
build: (id: string) => EditCommand,
) => boolean
/** A refusal that never reached the core (a required field left blank). */
reject: (field: string, messageKey: string) => false
clear: () => void
}
/** The write path of an editor panel: commit once, keep the refusal next to the control. */
export function useEditCommand(): EditCommandApi {
const t = useT()
const [error, setError] = useState<FieldError | null>(null)
const attempt = (command: EditCommand) =>
useEditorStore.getState().commit(command)
const run = (field: string, command: EditCommand): boolean => {
const outcome = attempt(command)
setError(outcome.ok ? null : { field, message: refusalMessage(t, outcome) })
return outcome.ok
}
const runNew: EditCommandApi['runNew'] = (field, prefix, build) => {
let outcome = attempt(build(newElementId(prefix)))
const clash =
!outcome.ok &&
outcome.reason === 'core' &&
outcome.failure.kind === 'duplicate_key'
if (clash) outcome = attempt(build(newElementId(prefix)))
setError(outcome.ok ? null : { field, message: refusalMessage(t, outcome) })
return outcome.ok
}
return {
fieldError: (field) => (error?.field === field ? error.message : undefined),
run,
runNew,
reject: (field, messageKey) => {
setError({ field, message: t(messageKey) })
return false
},
clear: () => setError(null),
}
}
+91
View File
@@ -1244,4 +1244,95 @@ export const en: Dict = {
'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?',
'editor.action.delete': 'Delete',
'editor.action.remove': 'Remove',
'editor.action.move_up': 'Move up',
'editor.action.move_down': 'Move down',
'editor.field.required': 'This field is required.',
'editor.field.required_names': 'Fill in the name in French and in English.',
'editor.field.integer': 'Enter a whole number.',
'editor.field.choose': 'Choose…',
'editor.refusal.blocked': 'The change was not applied.',
'editor.refusal.recovery': 'First answer the local copy offered at the top of the page.',
'editor.refusal.core.unknown_key': 'This element no longer exists in the draft.',
'editor.refusal.core.duplicate_key': 'An element already has this identifier.',
'editor.refusal.core.invalid_target': 'This change does not apply to this element.',
'editor.refusal.core.id_changed': 'An element\'s identifier or code cannot be changed.',
'editor.refusal.core.invalid_position': 'This position does not exist in the list.',
'editor.refusal.core.too_deep': 'The tree is too deep (8 levels at most).',
'editor.refusal.core.has_dependents': 'Other elements still use this one.',
'editor.refusal.core.other': 'The document check refuses this value ({kind}).',
'editor.element.sheet': 'Sheet',
'editor.element.reference': 'Reference',
'editor.element.region': 'Vertebral region',
'editor.element.category': 'Category',
'editor.element.view': 'View',
'editor.element.annotation': 'Annotation',
'editor.element.zone': 'Finding zone',
'editor.element.finding': 'Finding',
'editor.relation.drawn_in': 'drawn in this view',
'editor.relation.child_view': 'detail view of this view',
'editor.relation.opens': 'opens this view',
'editor.relation.uses_category': 'uses this category',
'editor.relation.links_zone': 'is linked to this finding zone',
'editor.relation.cites': 'cites this reference',
'editor.relation.uses_region': 'uses this vertebral region',
'editor.relation.descendant': 'is part of this element',
'editor.delete.title': 'Delete "{name}"?',
'editor.delete.ask': 'Delete "{name}" from the draft?',
'editor.delete.descendants': 'These elements will be deleted too:',
'editor.delete.blocked': '"{name}" cannot be deleted: the following elements still use it.',
'editor.delete.lookup_failed': 'Could not check what uses this element. Try again.',
'editor.delete.confirm': 'Delete',
'editor.delete.cancel': 'Cancel',
'editor.delete.close': 'Close',
'editor.general.texts': 'Sheet',
'editor.general.name_fr': 'Name (FR)',
'editor.general.name_en': 'Name (EN)',
'editor.general.description_fr': 'Description (FR)',
'editor.general.description_en': 'Description (EN)',
'editor.general.scope_disclaimer_fr': 'Scope and limits (FR)',
'editor.general.scope_disclaimer_en': 'Scope and limits (EN)',
'editor.general.attribution': 'Attribution',
'editor.general.authors': 'Authors',
'editor.general.author_new': 'New author',
'editor.general.author_add': 'Add the author',
'editor.general.author_remove': 'Remove {name}',
'editor.general.license': 'Licence',
'editor.general.notes': 'Notes',
'editor.general.categories': 'Annotation categories',
'editor.general.category_name_fr': 'Category name (FR)',
'editor.general.category_name_en': 'Category name (EN)',
'editor.general.category_color': 'Colour',
'editor.general.category_color_hint': 'Optional, as #rrggbb.',
'editor.general.category_new': 'New category',
'editor.general.category_add': 'Add the category',
'editor.reference.empty': 'No reference yet.',
'editor.reference.type': 'Type',
'editor.reference.citation': 'Citation',
'editor.reference.url': 'Web address (URL)',
'editor.reference.doi': 'DOI',
'editor.reference.new': 'New reference',
'editor.reference.add': 'Add the reference',
'editor.reference.required': 'Choose a type and fill in the citation.',
'editor.reference.type.book': 'Book',
'editor.reference.type.journal': 'Journal article',
'editor.reference.type.standard': 'Standard',
'editor.reference.type.legal': 'Legal text',
'editor.reference.type.web': 'Web page',
'editor.reference.type.manual': 'Manual',
'editor.vertebra.empty': 'No vertebral region yet.',
'editor.vertebra.code': 'Code',
'editor.vertebra.name_fr': 'Name (FR)',
'editor.vertebra.name_en': 'Name (EN)',
'editor.vertebra.count': 'Number of vertebrae',
'editor.vertebra.range': 'Possible range',
'editor.vertebra.range_min': 'Range: minimum',
'editor.vertebra.range_max': 'Range: maximum',
'editor.vertebra.range_apply': 'Apply the range',
'editor.vertebra.range_pair': 'Fill in both bounds of the range, or neither.',
'editor.vertebra.range_number': 'The range bounds are whole numbers.',
'editor.vertebra.new': 'New vertebral region',
'editor.vertebra.add': 'Add the region',
'editor.vertebra.required': 'Fill in the code and the French and English names.',
}
+91
View File
@@ -1275,4 +1275,95 @@ export const fr: Dict = {
'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 ?',
'editor.action.delete': 'Supprimer',
'editor.action.remove': 'Retirer',
'editor.action.move_up': 'Monter',
'editor.action.move_down': 'Descendre',
'editor.field.required': 'Ce champ est obligatoire.',
'editor.field.required_names': 'Renseignez le nom en français et en anglais.',
'editor.field.integer': 'Indiquez un nombre entier.',
'editor.field.choose': 'Choisir…',
'editor.refusal.blocked': 'La modification n\'a pas été appliquée.',
'editor.refusal.recovery': 'Répondez d\'abord à la copie locale proposée en haut de page.',
'editor.refusal.core.unknown_key': 'Cet élément n\'existe plus dans le brouillon.',
'editor.refusal.core.duplicate_key': 'Un élément porte déjà cet identifiant.',
'editor.refusal.core.invalid_target': 'Cette modification ne s\'applique pas à cet élément.',
'editor.refusal.core.id_changed': 'L\'identifiant ou le code d\'un élément ne se modifie pas.',
'editor.refusal.core.invalid_position': 'Cette position n\'existe pas dans la liste.',
'editor.refusal.core.too_deep': 'L\'arbre est trop profond (8 niveaux au plus).',
'editor.refusal.core.has_dependents': 'D\'autres éléments utilisent encore celui-ci.',
'editor.refusal.core.other': 'Le contrôle du document refuse cette valeur ({kind}).',
'editor.element.sheet': 'Fiche',
'editor.element.reference': 'Référence',
'editor.element.region': 'Région vertébrale',
'editor.element.category': 'Catégorie',
'editor.element.view': 'Vue',
'editor.element.annotation': 'Annotation',
'editor.element.zone': 'Zone de constats',
'editor.element.finding': 'Constat',
'editor.relation.drawn_in': 'dessinée dans cette vue',
'editor.relation.child_view': 'vue de détail de cette vue',
'editor.relation.opens': 'ouvre cette vue',
'editor.relation.uses_category': 'utilise cette catégorie',
'editor.relation.links_zone': 'est liée à cette zone de constats',
'editor.relation.cites': 'cite cette référence',
'editor.relation.uses_region': 'utilise cette région vertébrale',
'editor.relation.descendant': 'fait partie de cet élément',
'editor.delete.title': 'Supprimer « {name} » ?',
'editor.delete.ask': 'Supprimer « {name} » du brouillon ?',
'editor.delete.descendants': 'Les éléments suivants seront aussi supprimés :',
'editor.delete.blocked': '« {name} » ne peut pas être supprimé : les éléments suivants l\'utilisent encore.',
'editor.delete.lookup_failed': 'Impossible de vérifier ce qui utilise cet élément. Réessayez.',
'editor.delete.confirm': 'Supprimer',
'editor.delete.cancel': 'Annuler',
'editor.delete.close': 'Fermer',
'editor.general.texts': 'Fiche',
'editor.general.name_fr': 'Nom (FR)',
'editor.general.name_en': 'Nom (EN)',
'editor.general.description_fr': 'Description (FR)',
'editor.general.description_en': 'Description (EN)',
'editor.general.scope_disclaimer_fr': 'Périmètre et limites (FR)',
'editor.general.scope_disclaimer_en': 'Périmètre et limites (EN)',
'editor.general.attribution': 'Attribution',
'editor.general.authors': 'Auteurs',
'editor.general.author_new': 'Nouvel auteur',
'editor.general.author_add': 'Ajouter l\'auteur',
'editor.general.author_remove': 'Retirer {name}',
'editor.general.license': 'Licence',
'editor.general.notes': 'Notes',
'editor.general.categories': 'Catégories d\'annotation',
'editor.general.category_name_fr': 'Nom de la catégorie (FR)',
'editor.general.category_name_en': 'Nom de la catégorie (EN)',
'editor.general.category_color': 'Couleur',
'editor.general.category_color_hint': 'Facultative, au format #rrggbb.',
'editor.general.category_new': 'Nouvelle catégorie',
'editor.general.category_add': 'Ajouter la catégorie',
'editor.reference.empty': 'Aucune référence pour l\'instant.',
'editor.reference.type': 'Type',
'editor.reference.citation': 'Citation',
'editor.reference.url': 'Adresse web (URL)',
'editor.reference.doi': 'DOI',
'editor.reference.new': 'Nouvelle référence',
'editor.reference.add': 'Ajouter la référence',
'editor.reference.required': 'Choisissez un type et renseignez la citation.',
'editor.reference.type.book': 'Livre',
'editor.reference.type.journal': 'Article de revue',
'editor.reference.type.standard': 'Norme',
'editor.reference.type.legal': 'Texte juridique',
'editor.reference.type.web': 'Site web',
'editor.reference.type.manual': 'Manuel',
'editor.vertebra.empty': 'Aucune région vertébrale pour l\'instant.',
'editor.vertebra.code': 'Code',
'editor.vertebra.name_fr': 'Nom (FR)',
'editor.vertebra.name_en': 'Nom (EN)',
'editor.vertebra.count': 'Nombre de vertèbres',
'editor.vertebra.range': 'Plage possible',
'editor.vertebra.range_min': 'Plage : minimum',
'editor.vertebra.range_max': 'Plage : maximum',
'editor.vertebra.range_apply': 'Appliquer la plage',
'editor.vertebra.range_pair': 'Indiquez les deux bornes de la plage, ou aucune.',
'editor.vertebra.range_number': 'Les bornes de la plage sont des nombres entiers.',
'editor.vertebra.new': 'Nouvelle région vertébrale',
'editor.vertebra.add': 'Ajouter la région',
'editor.vertebra.required': 'Renseignez le code et les noms français et anglais.',
}
@@ -0,0 +1,243 @@
/** Lot F: Général (texts, attribution, annotation categories) and the delete dialog. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import DeleteDialog from '@/components/editor/DeleteDialog'
import GeneralTab from '@/components/editor/tabs/GeneralTab'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
baseText,
openReady,
resetStore,
store,
} from '../helpers/editorHarness'
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(),
}))
const props = { readOnly: false, onSelectTab: vi.fn(), reloadSheet: vi.fn() }
const doc = (): AnatomicalSheetDocument =>
JSON.parse(store.getState().documentText)
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
})
describe('Général: texts and attribution', () => {
it('commits a renamed sheet on blur as one update, nothing per keystroke', async () => {
await openReady()
const user = userEvent.setup()
render(<GeneralTab {...props} />)
const field = screen.getByLabelText('Nom (FR)')
await user.clear(field)
await user.type(field, 'Nouvelle fiche')
expect(store.getState().undo).toHaveLength(0)
await user.tab()
expect(doc().name.fr).toBe('Nouvelle fiche')
expect(store.getState().undo).toHaveLength(1)
})
it('refuses a blank name without reaching the core', async () => {
await openReady()
const user = userEvent.setup()
render(<GeneralTab {...props} />)
await user.clear(screen.getByLabelText('Nom (EN)'))
await user.tab()
expect(screen.getByRole('alert')).toHaveTextContent(
'Ce champ est obligatoire.',
)
expect(store.getState().unsaved).toBe(false)
})
it('a blank optional text is omitted, never an empty string', async () => {
const text = edit(baseText(), {
op: 'update',
key: { kind: 'sheet' },
element: {
kind: 'sheet',
value: { ...texts(), description: { fr: 'Texte', en: 'Text' } },
},
})
await openReady({ text })
const user = userEvent.setup()
render(<GeneralTab {...props} />)
await user.clear(screen.getByLabelText('Description (FR)'))
await user.tab()
expect(doc().description).toEqual({ en: 'Text' })
})
it('adds and removes an author; a blank licence is null', async () => {
await openReady()
const user = userEvent.setup()
render(<GeneralTab {...props} />)
await user.type(screen.getByLabelText('Nouvel auteur'), 'A. Martin')
await user.click(screen.getByRole('button', { name: "Ajouter l'auteur" }))
expect(doc().attribution.authors).toEqual(['A. Martin'])
await user.type(screen.getByLabelText('Licence'), 'CC-BY')
await user.tab()
expect(doc().attribution.license).toBe('CC-BY')
await user.clear(screen.getByLabelText('Licence'))
await user.tab()
expect(doc().attribution.license).toBeNull()
await user.click(screen.getByRole('button', { name: 'Retirer A. Martin' }))
expect(doc().attribution.authors).toEqual([])
})
it('read-only: values as text, no control, no button', async () => {
await openReady()
render(<GeneralTab {...props} readOnly />)
expect(screen.queryByRole('textbox')).toBeNull()
expect(screen.queryByRole('button')).toBeNull()
})
})
describe('Général: annotation categories', () => {
it('renames, recolours and adds a category', async () => {
await openReady()
const user = userEvent.setup()
render(<GeneralTab {...props} />)
const row = screen.getByLabelText('Nom de la catégorie (FR)', {
selector: '#category-cat-a-name-fr',
})
await user.clear(row)
await user.type(row, 'Os')
await user.tab()
expect(doc().categories[0].name.fr).toBe('Os')
await user.type(
screen.getByLabelText('Nom de la catégorie (FR)', {
selector: '#category-new-fr',
}),
'Muscle',
)
await user.type(
screen.getByLabelText('Nom de la catégorie (EN)', {
selector: '#category-new-en',
}),
'Muscle',
)
await user.click(
screen.getByRole('button', { name: 'Ajouter la catégorie' }),
)
expect(doc().categories).toHaveLength(2)
expect(doc().categories[1]).toMatchObject({
name: { fr: 'Muscle' },
color: null,
})
expect(doc().categories[1].id).toMatch(/^cat-[a-z2-7]{10}$/)
})
it('a new category needs both names', async () => {
await openReady()
const user = userEvent.setup()
render(<GeneralTab {...props} />)
await user.click(
screen.getByRole('button', { name: 'Ajouter la catégorie' }),
)
expect(screen.getByRole('alert')).toHaveTextContent('Renseignez le nom')
expect(doc().categories).toHaveLength(1)
})
it('a used category cannot be deleted: the dialog lists the dependents', async () => {
await openReady()
const user = userEvent.setup()
render(<GeneralTab {...props} />)
await user.click(screen.getByRole('button', { name: 'Supprimer' }))
const dialog = await screen.findByRole('dialog')
expect(within(dialog).getByText(/utilise cette catégorie/)).toBeTruthy()
expect(
within(dialog).queryByRole('button', { name: 'Supprimer' }),
).toBeNull()
await user.click(
within(dialog).getAllByRole('button', { name: 'Fermer' }).at(-1)!,
)
expect(doc().categories).toHaveLength(1)
})
it('an unused category is deleted after the confirmation', async () => {
const text = insert(baseText(), {
kind: 'category',
value: { id: 'cat-b', name: { fr: 'Libre', en: 'Free' }, color: null },
})
await openReady({ text })
const user = userEvent.setup()
render(<GeneralTab {...props} />)
const buttons = screen.getAllByRole('button', { name: 'Supprimer' })
await user.click(buttons[1])
const dialog = await screen.findByRole('dialog')
expect(
within(dialog).getByText('Supprimer « Libre » du brouillon ?'),
).toBeTruthy()
await user.click(within(dialog).getByRole('button', { name: 'Supprimer' }))
expect(doc().categories.map((c) => c.id)).toEqual(['cat-a'])
})
})
describe('DeleteDialog', () => {
it('lists the descendants that go with the element and removes them', async () => {
const withZone = insert(baseText(), {
kind: 'zone',
value: {
id: 'zone-a',
name: { fr: 'Zone A', en: 'Zone A' },
categories: [],
},
})
const text = edit(withZone, {
op: 'insert',
parent: { kind: 'zone', id: 'zone-a' },
element: {
kind: 'finding_category',
value: {
id: 'fcat-a',
kind: 'dysfunction',
name: { fr: 'Boiterie', en: 'Lameness' },
description: {},
reference_ids: [],
review_status: 'to_confirm',
children: [],
},
},
})
await openReady({ text })
const user = userEvent.setup()
const onClose = vi.fn()
render(
<DeleteDialog
target={{ key: { kind: 'zone', id: 'zone-a' }, label: 'Zone A' }}
onClose={onClose}
/>,
)
const dialog = await screen.findByRole('dialog')
expect(within(dialog).getByText(/Boiterie/)).toBeTruthy()
await user.click(within(dialog).getByRole('button', { name: 'Supprimer' }))
expect(onClose).toHaveBeenCalled()
expect(doc().finding_zones).toEqual([])
})
it('a closed dialog asks nothing and renders nothing', async () => {
await openReady()
render(<DeleteDialog target={null} onClose={vi.fn()} />)
expect(screen.queryByRole('dialog')).toBeNull()
})
})
function texts() {
const d: AnatomicalSheetDocument = JSON.parse(baseText())
return {
name: d.name,
description: d.description,
scope_disclaimer: d.scope_disclaimer,
attribution: d.attribution,
}
}
@@ -0,0 +1,256 @@
/** Lot F: Références and Vertèbres. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import ReferencesTab from '@/components/editor/tabs/ReferencesTab'
import VertebraeTab from '@/components/editor/tabs/VertebraeTab'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert, point } from '../helpers/editorFixtures'
import {
baseText,
openReady,
resetStore,
store,
} from '../helpers/editorHarness'
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(),
}))
const props = { readOnly: false, onSelectTab: vi.fn(), reloadSheet: vi.fn() }
const doc = (): AnatomicalSheetDocument =>
JSON.parse(store.getState().documentText)
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
})
const reference = (id: string, citation: string) =>
({
kind: 'reference',
value: { id, type: 'book', citation, url: null, doi: null },
}) as const
describe('Références', () => {
it('adds a reference only with a type and a citation', async () => {
await openReady()
const user = userEvent.setup()
render(<ReferencesTab {...props} />)
await user.click(
screen.getByRole('button', { name: 'Ajouter la référence' }),
)
expect(screen.getByRole('alert')).toHaveTextContent('Choisissez un type')
expect(doc().references).toEqual([])
await user.selectOptions(screen.getByLabelText('Type'), 'web')
await user.type(screen.getByLabelText('Citation'), 'Anatomie du cheval')
await user.click(
screen.getByRole('button', { name: 'Ajouter la référence' }),
)
expect(doc().references).toHaveLength(1)
expect(doc().references[0]).toMatchObject({
type: 'web',
citation: 'Anatomie du cheval',
url: null,
doi: null,
})
expect(doc().references[0].id).toMatch(/^ref-[a-z2-7]{10}$/)
})
it('edits a field on blur and reorders with the arrows', async () => {
const text = insert(
insert(baseText(), reference('ref-a', 'Alpha')),
reference('ref-b', 'Beta'),
)
await openReady({ text })
const user = userEvent.setup()
render(<ReferencesTab {...props} />)
const url = screen.getByLabelText('Adresse web (URL)', {
selector: '#reference-ref-a-url',
})
await user.type(url, 'https://example.org')
await user.tab()
expect(doc().references[0].url).toBe('https://example.org')
await user.click(screen.getAllByRole('button', { name: 'Monter' })[1])
expect(doc().references.map((r) => r.id)).toEqual(['ref-b', 'ref-a'])
expect(screen.getAllByRole('button', { name: 'Monter' })[0]).toBeDisabled()
})
it('a cited reference is refused with the citing findings listed; an uncited one is deleted', async () => {
let text = insert(
insert(baseText(), reference('ref-a', 'Alpha')),
reference('ref-b', 'Beta'),
)
text = insert(text, {
kind: 'zone',
value: { id: 'zone-a', name: { fr: 'Z', en: 'Z' }, categories: [] },
})
text = edit(text, {
op: 'insert',
parent: { kind: 'zone', id: 'zone-a' },
element: {
kind: 'finding_category',
value: {
id: 'fcat-a',
kind: 'dysfunction',
name: { fr: 'Boiterie', en: 'Lameness' },
description: {},
reference_ids: ['ref-a'],
review_status: 'to_confirm',
children: [],
},
},
})
await openReady({ text })
const user = userEvent.setup()
render(<ReferencesTab {...props} />)
await user.click(screen.getAllByRole('button', { name: 'Supprimer' })[0])
const refused = await screen.findByRole('dialog')
expect(within(refused).getByText(/cite cette référence/)).toBeTruthy()
expect(within(refused).getByText(/Boiterie/)).toBeTruthy()
await user.click(
within(refused).getAllByRole('button', { name: 'Fermer' }).at(-1)!,
)
await user.click(screen.getAllByRole('button', { name: 'Supprimer' })[1])
const asked = await screen.findByRole('dialog')
await user.click(within(asked).getByRole('button', { name: 'Supprimer' }))
expect(doc().references.map((r) => r.id)).toEqual(['ref-a'])
})
it('read-only shows the citations as text', async () => {
await openReady({ text: insert(baseText(), reference('ref-a', 'Alpha')) })
render(<ReferencesTab {...props} readOnly />)
expect(screen.getByText('Alpha')).toBeTruthy()
expect(screen.queryByRole('textbox')).toBeNull()
expect(screen.queryByRole('button')).toBeNull()
})
})
const region = (code: string, count: number) =>
({
kind: 'region',
value: {
code,
name: { fr: `R ${code}`, en: `R ${code}` },
count,
count_range: null,
},
}) as const
describe('Vertèbres', () => {
it('adds a region with a typed code; a bad count or half range never reaches the core', async () => {
await openReady()
const user = userEvent.setup()
render(<VertebraeTab {...props} />)
await user.type(screen.getByLabelText('Code'), 'C')
await user.type(screen.getByLabelText('Nom (FR)'), 'Cervicales')
await user.type(screen.getByLabelText('Nom (EN)'), 'Cervical')
await user.type(screen.getByLabelText('Nombre de vertèbres'), 'sept')
await user.click(screen.getByRole('button', { name: 'Ajouter la région' }))
expect(screen.getByRole('alert')).toHaveTextContent('nombre entier')
await user.clear(screen.getByLabelText('Nombre de vertèbres'))
await user.type(screen.getByLabelText('Nombre de vertèbres'), '7')
await user.type(screen.getByLabelText('Plage : minimum'), '6')
await user.click(screen.getByRole('button', { name: 'Ajouter la région' }))
expect(screen.getByRole('alert')).toHaveTextContent('les deux bornes')
expect(doc().vertebral_config.regions).toEqual([])
await user.type(screen.getByLabelText('Plage : maximum'), '8')
await user.click(screen.getByRole('button', { name: 'Ajouter la région' }))
expect(doc().vertebral_config.regions).toEqual([
{
code: 'C',
name: { fr: 'Cervicales', en: 'Cervical' },
count: 7,
count_range: { min: 6, max: 8 },
},
])
})
it('edits the count, applies and clears a range, reorders', async () => {
const text = insert(insert(baseText(), region('C', 7)), region('T', 18))
await openReady({ text })
const user = userEvent.setup()
render(<VertebraeTab {...props} />)
const count = screen.getByLabelText('Nombre de vertèbres', {
selector: '#region-T-count',
})
await user.clear(count)
await user.type(count, '17')
await user.tab()
expect(doc().vertebral_config.regions[1].count).toBe(17)
await user.type(
screen.getByLabelText('Plage : minimum', {
selector: '#region-T-range-min',
}),
'17',
)
await user.type(
screen.getByLabelText('Plage : maximum', {
selector: '#region-T-range-max',
}),
'19',
)
await user.click(
screen.getAllByRole('button', { name: 'Appliquer la plage' })[1],
)
expect(doc().vertebral_config.regions[1].count_range).toEqual({
min: 17,
max: 19,
})
await user.clear(
screen.getByLabelText('Plage : minimum', {
selector: '#region-T-range-min',
}),
)
await user.clear(
screen.getByLabelText('Plage : maximum', {
selector: '#region-T-range-max',
}),
)
await user.click(
screen.getAllByRole('button', { name: 'Appliquer la plage' })[1],
)
expect(doc().vertebral_config.regions[1].count_range).toBeNull()
await user.click(screen.getAllByRole('button', { name: 'Monter' })[1])
expect(doc().vertebral_config.regions.map((r) => r.code)).toEqual([
'T',
'C',
])
})
it('a region used by an annotation is refused with that annotation listed', async () => {
const used = point('anno-v', 20, 20, 3)
const value = {
...used.value,
vertebral_region_code: 'C',
} as typeof used.value
const text = insert(insert(baseText(), region('C', 7)), {
kind: 'annotation',
value,
})
await openReady({ text })
const user = userEvent.setup()
render(<VertebraeTab {...props} />)
await user.click(screen.getByRole('button', { name: 'Supprimer' }))
const dialog = await screen.findByRole('dialog')
expect(
within(dialog).getByText(/utilise cette région vertébrale/),
).toBeTruthy()
expect(doc().vertebral_config.regions).toHaveLength(1)
})
it('read-only has no control', async () => {
await openReady({ text: insert(baseText(), region('C', 7)) })
render(<VertebraeTab {...props} readOnly />)
expect(screen.queryByRole('textbox')).toBeNull()
expect(screen.queryByRole('button')).toBeNull()
})
})