feat(editor): internal access category kept out of the anatomical categories

This commit is contained in:
bchanot committed 2026-11-23 09:07:14 +01:00
1 parent a1c2aefbba
commit cc70a565ce
18 files changed
+440 -48

No files matched your search

@@ -4,6 +4,7 @@ import type {
PreviewState,
} from '@faunosteo/core-wasm/types'
import Card from '@/components/ui/Card'
import { categoryName } from '@/editor/accessCategory'
import { pickLabel } from '@/i18n/pickLocaleLabel'
import type { Locale } from '@/i18n/types'
import { useLocaleStore } from '@/state/localeStore'
@@ -45,7 +46,7 @@ function zoneLine(state: PreviewState, annotation: Annotation, locale: Locale, t
const { categories, vertebral_config } = state.document
const category = categories.find((c) => c.id === annotation.category_id)
const parts = category
? [t('catalogue.zone.category').replace('{name}', pickLabel(category.name, locale))]
? [t('catalogue.zone.category').replace('{name}', categoryName(category, locale))]
: []
const code = annotation.kind === 'detail_trigger' ? null : annotation.vertebral_region_code
const region = vertebral_config.regions.find((r) => r.code === code)
@@ -1,3 +1,4 @@
import { categoryName } from '@/editor/accessCategory'
import type { Annotation, SheetView } from '@faunosteo/core-wasm/types'
import type { AnnotationGroup } from '@/editor/annotations/overview'
import { useT } from '@/i18n/useT'
@@ -88,7 +89,9 @@ function GroupTitle({ group, id }: { group: AnnotationGroup; id: string }) {
style={{ backgroundColor: category?.color ?? undefined }}
/>
<span className="min-w-0 flex-1 truncate">
{category ? category.name[locale] : t('editor.overview.uncategorised')}
{category
? categoryName(category, locale)
: t('editor.overview.uncategorised')}
</span>
<span className="font-normal text-[var(--color-ink-muted)]">
{group.annotations.length}
@@ -3,6 +3,7 @@ import type {
AnatomicalSheetDocument,
Annotation,
} from '@faunosteo/core-wasm/types'
import { categoryName } from '@/editor/accessCategory'
import { useGeometryIssues } from '@/editor/annotations/useGeometryIssues'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
@@ -34,7 +35,7 @@ function CategoryValue({
className="size-3 shrink-0 rounded-full border border-[var(--color-border)]"
style={{ backgroundColor: category?.color ?? undefined }}
/>
{category ? category.name[locale] : annotation.category_id}
{category ? categoryName(category, locale) : annotation.category_id}
</span>
)
}
@@ -11,6 +11,11 @@ import {
type CreationForm,
type PendingElement,
} from '@/editor/annotations/creation'
import {
categoryName,
isAccessCategory,
ordinaryCategories,
} from '@/editor/accessCategory'
import type { MissingField } from '@/editor/annotations/missingFields'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
@@ -84,6 +89,58 @@ function OptionSelect({
)
}
/**
* The category: none for a new access (it enters the internal one), the fixed label for an
* existing access in it, else the ordinary categories plus the current one when it is the
* internal one (an N-1 point), so it can be changed.
*/
function CategoryField(
props: FieldsProps & { kind: PendingElement['kind']; error?: string },
) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const { doc, form, onChange, idPrefix = 'creation-', readOnly } = props
const internal = isAccessCategory(form.categoryId)
if (internal && props.kind === 'detail_trigger') {
return props.editing ? <FixedCategory id={`${idPrefix}category`} /> : null
}
const current = doc.categories.filter((c) => c.id === form.categoryId)
const options = [
...ordinaryCategories(doc.categories),
...current.filter((c) => internal && isAccessCategory(c.id)),
].map((c) => ({ value: c.id, label: categoryName(c, locale) }))
return (
<OptionSelect
id={`${idPrefix}category`}
label={t('editor.annotations.category')}
value={form.categoryId}
options={options}
blank={null}
onChange={(categoryId) => onChange({ categoryId })}
error={props.error}
readOnly={readOnly}
/>
)
}
/** An access in the internal category: its fixed label, nothing to choose. */
function FixedCategory({ id }: { id: string }) {
const t = useT()
return (
<div className="space-y-1">
<span
id={`${id}-label`}
className="mb-1 block text-sm font-medium text-[var(--color-ink)]"
>
{t('editor.annotations.category')}
</span>
<p id={id} aria-labelledby={`${id}-label`} className="py-2 text-sm">
{t('editor.annotations.access_group')}
</p>
</div>
)
}
/** The R-3 message under a missing field, else nothing. */
function useMissing(props: FieldsProps) {
const t = useT()
@@ -129,13 +186,8 @@ export default function CreationFields({
color?: ColorField
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const missing = useMissing(fields)
const { doc, form, onChange, idPrefix = 'creation-', readOnly } = fields
const categories = doc.categories.map((c) => ({
value: c.id,
label: c.name[locale],
}))
const { form, onChange, idPrefix = 'creation-', readOnly } = fields
const sides = LATERALITIES.map((l: Laterality) => ({
value: l,
label: t(`editor.annotations.laterality.${l}`),
@@ -144,16 +196,7 @@ export default function CreationFields({
return (
<div className={`grid gap-3 ${columns}`}>
<NameFields {...fields} />
<OptionSelect
id={`${idPrefix}category`}
label={t('editor.annotations.category')}
value={form.categoryId}
options={categories}
blank={null}
onChange={(categoryId) => onChange({ categoryId })}
error={missing('category')}
readOnly={readOnly}
/>
<CategoryField {...fields} kind={kind} error={missing('category')} />
{color && (
<ColorInput {...color} id={`${idPrefix}color`} readOnly={readOnly} />
)}
@@ -7,6 +7,7 @@ import type {
} from '@faunosteo/core-wasm/types'
import type { CommitContext } from '@/editor/annotations/annotationCommit'
import { useAnnotationRequest } from '@/editor/annotations/focusTarget'
import { ordinaryCategories } from '@/editor/accessCategory'
import type { NewKind } from '@/editor/annotations/creation'
import { creationTracing } from '@/editor/annotations/creationWork'
import { useCreationFollow } from '@/editor/annotations/useCreationFollow'
@@ -304,7 +305,7 @@ function CanvasColumn({
onDeselect: () => void
}) {
const { doc, dispatch, model } = scene
const noCategory = doc.categories.length === 0
const noCategory = ordinaryCategories(doc.categories).length === 0
return (
<div data-drawing-column className="min-w-0 space-y-3">
<ViewSwitcher
@@ -318,7 +319,8 @@ function CanvasColumn({
<CanvasStage scene={scene} work={work} onDeselect={onDeselect} />
<GestureMessage messages={work.message}>
<KeyboardAdd
disabled={!model.measured || noCategory || scene.frame === null}
disabled={!model.measured || scene.frame === null}
noCategory={noCategory}
linkDisabled={model.children.length === 0}
armed={armedTool(scene.ui)}
centre={centreOf(scene)}
@@ -412,7 +414,8 @@ function CanvasStage({
const zone = useZoneHandle(scene, work, shown)
const subject = pressSubject(scene, work)
const view = doc.views.find((v) => v.id === scene.viewId)
const blocked = !model.measured || doc.categories.length === 0
const blocked = !model.measured
const noCategory = ordinaryCategories(doc.categories).length === 0
if (!view) return null
return (
<AnnotationCanvas
@@ -437,6 +440,7 @@ function CanvasStage({
onTool: (tool, button) =>
guardedPress(button, () => dispatch({ type: 'tool', tool })),
drawingDisabled: blocked,
noCategory,
linkDisabled: model.children.length === 0,
}}
onRoot={scene.setRoot}
@@ -482,7 +486,8 @@ function centreOf(scene: Scene): (() => void) | null {
const { ui, doc, model, frame, creation } = scene
const tool = armedTool(ui)
if (tool === 'select' || creation !== null || ui.tracing !== null) return null
if (frame === null || !model.measured || doc.categories.length === 0)
if (frame === null || !model.measured) return null
if (tool !== 'link' && ordinaryCategories(doc.categories).length === 0)
return null
if (tool === 'link' && model.children.length === 0) return null
return () => placeAtCentre(scene, TOOL_TARGET[tool], ui.armedFrom)
@@ -19,14 +19,17 @@ const ARMED =
*/
export default function KeyboardAdd({
disabled,
noCategory,
linkDisabled,
armed,
centre,
onAdd,
onArm,
}: {
/** No measured frame, or no category: nothing can be placed. */
/** No measured frame: nothing can be placed. */
disabled: boolean
/** No ordinary category: no point or zone can be placed (an access needs none). */
noCategory: boolean
/** No detail view directly under this view: no link can be placed. */
linkDisabled: boolean
/** The armed tool (`armedTool`): its button shows pressed. */
@@ -41,9 +44,7 @@ export default function KeyboardAdd({
if (event.detail === 0) onAdd(kind)
else if (event.detail === 1) onArm(kind, event.currentTarget)
}
const armedKind = centre
? KINDS.find((k) => TOOL_OF[k] === armed)
: undefined
const armedKind = centre ? KINDS.find((k) => TOOL_OF[k] === armed) : undefined
return (
<div className="flex flex-wrap gap-2">
{KINDS.map((kind) => (
@@ -55,7 +56,9 @@ export default function KeyboardAdd({
className={`min-h-11 xl:min-h-9 ${ARMED}`}
data-add-kind={kind}
data-armed={armed === TOOL_OF[kind] ? '' : undefined}
disabled={disabled || (kind === 'detail_trigger' && linkDisabled)}
disabled={
disabled || (kind === 'detail_trigger' ? linkDisabled : noCategory)
}
onClick={press(kind)}
>
{t(`editor.annotations.add.${kind}`)}
@@ -8,6 +8,7 @@ import {
groupAnnotations,
useOverviewCounts,
} from '@/editor/annotations/overview'
import { ordinaryCategories } from '@/editor/accessCategory'
import type { AnnotationSection } from '@/editor/navigation'
import { usePlural } from '@/editor/plural'
import { useT } from '@/i18n/useT'
@@ -146,6 +147,7 @@ function CategoriesCard(props: OverviewPanelProps) {
const { doc, readOnly, onOpenSection } = props
const id = `${props.idPrefix ?? ''}overview-categories`
const counts = useOverviewCounts(doc)
const categories = ordinaryCategories(doc.categories)
return (
<section aria-labelledby={id} className={CARD}>
<h3 id={id} className={`${TITLE} flex items-center justify-between`}>
@@ -154,16 +156,16 @@ function CategoriesCard(props: OverviewPanelProps) {
data-testid="overview-categories-count"
className="font-normal text-[var(--color-ink-muted)]"
>
{doc.categories.length}
{categories.length}
</span>
</h3>
{doc.categories.length === 0 && (
{categories.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.overview.categories_empty')}
</p>
)}
<ul className="flex flex-wrap gap-2">
{doc.categories.map((category) => (
{categories.map((category) => (
<li
key={category.id}
className="inline-flex items-center gap-2 rounded-full border border-[var(--color-border)] px-3 py-1 text-sm"
@@ -1,5 +1,6 @@
import type { Annotation } from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
import { ordinaryCategories } from '@/editor/accessCategory'
import { useDeselect } from '@/editor/annotations/deselect'
import { isEditable } from '@/editor/annotations/geometryEdit'
import { dropCreation } from '@/editor/annotations/creationWork'
@@ -237,7 +238,7 @@ function useStripNotice(
return { tone: 'info', text: t('editor.annotations.strip.zoom_hint') }
}
if (!model.measured) return unmeasuredNotice(scene, t)
if (doc.categories.length === 0) {
if (ordinaryCategories(doc.categories).length === 0 && ui.tool !== 'link') {
return { tone: 'info', text: t('editor.annotations.no_category') }
}
if (ui.tool === 'link' && model.children.length === 0) {
@@ -7,8 +7,10 @@ export interface ToolColumnProps {
tool: ToolId
/** `button` is the pressed tool: the focus may land on it (Safari, see `guardedPress`). */
onTool: (tool: ToolId, button: HTMLElement) => void
/** Point, zone and link need a measured view and a category. */
/** Point, zone and link need a measured view. */
drawingDisabled: boolean
/** Point and zone need an ordinary category; the link tool needs none. */
noCategory: boolean
/** The link tool needs a detail view directly under the current one. */
linkDisabled: boolean
onZoomIn: () => void
@@ -79,8 +81,8 @@ export default function ToolColumn(props: ToolColumnProps) {
className="flex flex-row gap-2 lg:flex-col"
>
{tool('select', false)}
{tool('point', props.drawingDisabled)}
{tool('zone', props.drawingDisabled)}
{tool('point', props.drawingDisabled || props.noCategory)}
{tool('zone', props.drawingDisabled || props.noCategory)}
{tool('link', props.drawingDisabled || props.linkDisabled)}
<hr className="hidden border-[var(--color-border)] lg:block" />
<ToolButton
@@ -10,6 +10,7 @@ import TextField from '@/components/editor/fields/TextField'
import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import { ordinaryCategories } from '@/editor/accessCategory'
import { FOCUS_CLASS, focusAttrs, useRowFocus } from '@/editor/focusRequest'
import type { FocusRequest } from '@/editor/navigation'
import { isBlank, nullable } from '@/editor/sheetDocument'
@@ -36,7 +37,7 @@ export default function CategoriesSection({
return (
<div data-testid="editor-section-categories" className="space-y-3">
<ul className="space-y-3">
{doc.categories.map((category) => (
{ordinaryCategories(doc.categories).map((category) => (
<CategoryRow
key={category.id}
category={category}
+28
View File
@@ -0,0 +1,28 @@
import { getDict } from '@/i18n'
import type { Locale } from '@/i18n/types'
/** The internal category of detail-view accesses (owner 2026-11-22, README « Conséquences » 1):
* the core alone creates it, when an access enters it; the page never lists it among the
* anatomical categories and shows it under a fixed label, whatever the document stores. */
export const ACCESS_CATEGORY_ID = 'cat-access'
export function isAccessCategory(id: string): boolean {
return id === ACCESS_CATEGORY_ID
}
/** The categories a person picks from: every category but the internal one. */
export function ordinaryCategories<T extends { id: string }>(
categories: readonly T[],
): T[] {
return categories.filter((category) => !isAccessCategory(category.id))
}
/** The name a category shows: the fixed label for the internal one, else the stored name. */
export function categoryName(
category: { id: string; name: { fr: string; en: string } },
locale: Locale,
): string {
return isAccessCategory(category.id)
? getDict(locale)['editor.annotations.access_group']!
: category.name[locale]
}
+11 -2
View File
@@ -14,6 +14,7 @@ import {
type Frame,
type XY,
} from './frame'
import { ACCESS_CATEGORY_ID, ordinaryCategories } from '../accessCategory'
import type { Correction } from './correction'
import type { EditableGeometry } from './geometryEdit'
@@ -49,11 +50,19 @@ export const LATERALITIES: readonly Laterality[] = [
'right',
]
export function emptyForm(doc: AnatomicalSheetDocument): CreationForm {
/** An access starts in the internal category; a point or zone, in the first ordinary one. */
export function emptyForm(
doc: AnatomicalSheetDocument,
kind: NewKind = 'point',
): CreationForm {
const categoryId =
kind === 'detail_trigger'
? ACCESS_CATEGORY_ID
: (ordinaryCategories(doc.categories)[0]?.id ?? '')
return {
fr: '',
en: '',
categoryId: doc.categories[0]?.id ?? '',
categoryId,
laterality: '',
opensViewId: '',
zoneId: '',
+9 -2
View File
@@ -4,6 +4,7 @@ import type {
Annotation,
AnnotationCategory,
} from '@faunosteo/core-wasm/types'
import { isAccessCategory, ordinaryCategories } from '../accessCategory'
import { folded } from '@/catalogue/useCatalogue'
/**
@@ -52,10 +53,16 @@ export function groupAnnotations(
(a) => a.view_id === viewId && folded(nameOf(a)).includes(wanted),
)
const known = new Set(doc.categories.map((category) => category.id))
const groups: AnnotationGroup[] = doc.categories.map((category) => ({
const inCategory = (category: AnnotationCategory) => ({
category,
annotations: shown.filter((a) => a.category_id === category.id),
}))
})
const groups: AnnotationGroup[] = ordinaryCategories(doc.categories).map(
inCategory,
)
// The internal group comes last, whatever its place or name in the document.
const access = doc.categories.find((c) => isAccessCategory(c.id))
if (access) groups.push(inCategory(access))
groups.push({
category: null,
annotations: shown.filter((a) => !known.has(a.category_id)),
@@ -84,7 +84,8 @@ function closeRedraw(input: PlacementInput, tracing: Tracing): void {
const creationStart = (
{ viewId, frame, doc }: Pick<PlacementInput, 'viewId' | 'frame' | 'doc'>,
origin: CreationStart['origin'],
): CreationStart => ({ viewId, frame, origin, form: emptyForm(doc) })
kind: NewKind,
): CreationStart => ({ viewId, frame, origin, form: emptyForm(doc, kind) })
const isRedraw = (tracing: Tracing | null) => tracing?.target === 'replace'
@@ -109,7 +110,7 @@ export function placeAtCentre(
dispatch({ type: 'hint', hint: null })
const size = newPointSize(doc.annotations, viewId, frame, ui.size)
placePending(
creationStart(scene, origin),
creationStart(scene, origin, kind),
keyboardPending(kind, frame, size),
)
}
@@ -148,7 +149,7 @@ function tracingActions(input: PlacementInput) {
if (isRedraw(tracing))
return dispatch({ type: 'trace_add', point: asPoint(at) })
traceVertex(
creationStart(input, input.ui.armedFrom),
creationStart(input, input.ui.armedFrom, TOOL_TARGET[tool]),
TOOL_TARGET[tool],
asPoint(at),
)
@@ -260,7 +261,10 @@ export function usePlacement(input: PlacementInput) {
const outcome = pendingForClick(frame, at, size)
if (outcome.kind === 'pending') {
dispatch({ type: 'hint', hint: null })
return placePending(creationStart(input, ui.armedFrom), outcome.pending)
return placePending(
creationStart(input, ui.armedFrom, 'point'),
outcome.pending,
)
}
dispatch({ type: 'hint', hint: t('editor.annotations.outside') })
}
+11 -4
View File
@@ -6,6 +6,7 @@ import type {
SheetTexts,
} from '@faunosteo/core-wasm/types'
import type { Locale } from '@/i18n/types'
import { categoryName } from './accessCategory'
import { useEditorStore } from './state/editorStore'
/**
@@ -87,6 +88,15 @@ function localized(
return name?.[locale]
}
function categoryLabel(
doc: AnatomicalSheetDocument,
id: string,
locale: Locale,
): string {
const category = doc.categories.find((c) => c.id === id)
return category ? categoryName(category, locale) : id
}
/** The name an element shows in a list or a dependents message; its id as a last resort. */
export function elementLabel(
doc: AnatomicalSheetDocument,
@@ -106,10 +116,7 @@ export function elementLabel(
) ?? key.code
)
case 'category':
return (
localized(doc.categories.find((c) => c.id === key.id)?.name, locale) ??
key.id
)
return categoryLabel(doc, key.id, locale)
case 'view':
return (
localized(doc.views.find((v) => v.id === key.id)?.name, locale) ??
+1
View File
@@ -1785,6 +1785,7 @@ export const en: Dict = {
'editor.annotations.name_fr': 'Name (FR)',
'editor.annotations.name_en': 'Name (EN)',
'editor.annotations.category': 'Category',
'editor.annotations.access_group': 'Detail view access',
'editor.annotations.color': 'Colour',
'editor.annotations.color_hint':
'Leave empty for the category colour, or enter a hexadecimal value (#rrggbb).',
+1
View File
@@ -1851,6 +1851,7 @@ export const fr: Dict = {
'editor.annotations.name_fr': 'Nom (FR)',
'editor.annotations.name_en': 'Nom (EN)',
'editor.annotations.category': 'Catégorie',
'editor.annotations.access_group': 'Accès aux vues détaillées',
'editor.annotations.color': 'Couleur',
'editor.annotations.color_hint':
'Laissez vide pour la couleur de la catégorie, ou indiquez une valeur hexadécimale (#rrggbb).',
@@ -0,0 +1,273 @@
/** U2 Task 13: the internal category `cat-access` stays out of the anatomical categories. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
cleanup,
render,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Annotation } from '@faunosteo/core-wasm/types'
import CategoriesSection from '@/components/editor/general/CategoriesSection'
import { ACCESS_CATEGORY_ID } from '@/editor/accessCategory'
import { resetWork } from '@/editor/annotations/workStore'
import { useLocaleStore } from '@/state/localeStore'
import { addByKeyboard } from '../helpers/addByKeyboard'
import { LayeredTab } from '../helpers/annotationLayer'
import { edit, drawnText, insert, point } from '../helpers/editorFixtures'
import { 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,
navigate: vi.fn(),
reloadSheet: vi.fn(),
section: 'drawing' as const,
visited: ['drawing'] as const,
onOpenSection: vi.fn(),
onBack: vi.fn(),
}
const ACCESS_FR = 'Accès aux vues détaillées'
function stubCtm(): void {
const identity = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }
Object.defineProperty(window.SVGElement.prototype, 'getScreenCTM', {
configurable: true,
value: () => ({ ...identity, inverse: () => identity }),
})
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
stubCtm()
})
afterEach(() => {
cleanup()
resetStore()
resetWork()
})
const withDetail = (text: string) =>
insert(text, {
kind: 'view',
value: {
kind: 'detail',
id: 'view-det',
name: { fr: 'Tête', en: 'Head' },
svg_asset_id: null,
view_box: { min_x: 10, min_y: 10, width: 80, height: 80 },
parent_view_id: 'view-main',
},
})
const trigger = (id: string, category: string): Annotation =>
({
id,
view_id: 'view-main',
category_id: category,
laterality: 'unpaired',
geometry: { type: 'circle', cx: 90, cy: 90, r: 3 },
review_status: 'to_confirm',
color: null,
kind: 'detail_trigger',
name: null,
opens_view_id: 'view-det',
}) as Annotation
/** The sheet after the core created `cat-access` for a new access (cat-a is ordinary). */
function accessSheet(): string {
return insert(withDetail(insert(drawnText(), point('pt', 20, 20, 5))), {
kind: 'annotation',
value: trigger('acc', ACCESS_CATEGORY_ID),
})
}
/** An N-1 state: the point `pt` stored in the internal category, named « Navigation ». */
function n1Sheet(): string {
const doc = JSON.parse(accessSheet())
for (const category of doc.categories) {
if (category.id === ACCESS_CATEGORY_ID)
category.name = { fr: 'Navigation', en: 'Navigation' }
}
const stray = doc.annotations.find((a: Annotation) => a.id === 'pt')
stray.category_id = ACCESS_CATEGORY_ID
return JSON.stringify(doc)
}
async function mount(text: string) {
await openReady({ text })
render(
<div data-editor-workspace>
<LayeredTab {...props} />
</div>,
)
await waitFor(() =>
expect(
screen.getByTestId('annotation-canvas-drawing').querySelector('svg'),
).not.toBeNull(),
)
}
const overview = () =>
screen.getByRole('region', { name: 'Aperçu de la fiche' })
const rowOf = (id: string) =>
document.querySelector<HTMLElement>(
`[data-focus-key='{"kind":"annotation","id":"${id}"}']`,
)!
const doc = () => store.getState().previewState!.document
async function openEdit(id: string) {
const user = userEvent.setup()
await user.click(rowOf(id))
const strip = screen.getByTestId('edit-strip')
await user.click(
await within(strip).findByRole('button', { name: 'Propriétés' }),
)
const opened = await screen.findByRole('dialog')
await user.click(within(opened).getByRole('button', { name: 'Modifier' }))
return { user, opened }
}
const optionsOf = (select: HTMLElement) =>
within(select)
.getAllByRole('option')
.map((o) => o.textContent)
describe('the core creates the category', () => {
it('names it « Accès aux vues détaillées » when an access enters it', async () => {
await openReady({ text: accessSheet() })
const category = doc().categories.find((c) => c.id === ACCESS_CATEGORY_ID)
expect(category?.name.fr).toBe(ACCESS_FR)
})
})
describe('hidden as a category', () => {
it('the overview card counts and lists the ordinary categories only', async () => {
await mount(accessSheet())
expect(screen.getByTestId('overview-categories-count')).toHaveTextContent(
'1',
)
const card = screen
.getByTestId('overview-categories-count')
.closest('section')!
expect(within(card).queryByText(ACCESS_FR)).toBeNull()
})
it('the creation picker never offers it', async () => {
await mount(accessSheet())
await addByKeyboard(
userEvent.setup(),
screen.getByRole('button', { name: 'Ajouter un point' }),
)
const opened = await screen.findByRole('dialog', { name: 'Nouveau point' })
const select = within(opened).getByLabelText('Catégorie')
expect(optionsOf(select)).toEqual(['N'])
})
it('the Categories section never lists it', async () => {
await openReady({ text: accessSheet() })
render(<CategoriesSection doc={doc()} readOnly={false} />)
expect(screen.getAllByRole('listitem')).toHaveLength(1)
expect(screen.queryByDisplayValue(ACCESS_FR)).toBeNull()
})
it('a new access has no category field', async () => {
await mount(accessSheet())
await addByKeyboard(
userEvent.setup(),
screen.getByRole('button', { name: 'Ajouter un accès' }),
)
const opened = await screen.findByRole('dialog')
expect(within(opened).queryByLabelText('Catégorie')).toBeNull()
})
})
describe('its own group', () => {
it('comes last under the fixed label, whatever name the document stores', async () => {
await mount(n1Sheet())
const list = within(overview()).getByRole('list', {
name: 'Annotations de la vue',
})
const groups = within(list).getAllByRole('list')
expect(groups).toHaveLength(1)
expect(groups[0]).toHaveAccessibleName(`${ACCESS_FR} 2`)
expect(within(list).queryByText('Navigation')).toBeNull()
})
})
describe('an N-1 point stored in it', () => {
it('shows the fixed label as its category and can be moved to an ordinary one', async () => {
await mount(n1Sheet())
const { user, opened } = await openEdit('pt')
const select = within(opened).getByLabelText(
'Catégorie',
) as HTMLSelectElement
expect(optionsOf(select)).toEqual(['N', ACCESS_FR])
expect(select.selectedOptions[0]).toHaveTextContent(ACCESS_FR)
await user.selectOptions(select, 'N')
await user.click(
within(opened).getByRole('button', { name: 'Enregistrer' }),
)
await waitFor(() =>
expect(doc().annotations.find((a) => a.id === 'pt')?.category_id).toBe(
'cat-a',
),
)
})
})
describe('no ordinary category', () => {
function onlyAccess(): string {
const text = withDetail(drawnText())
const doc2 = JSON.parse(
edit(text, {
op: 'insert',
element: {
kind: 'annotation',
value: trigger('acc', ACCESS_CATEGORY_ID),
},
}),
)
doc2.categories = doc2.categories.filter(
(c: { id: string }) => c.id === ACCESS_CATEGORY_ID,
)
return JSON.stringify(doc2)
}
it('blocks Point and Zone and leaves the access tool available', async () => {
await mount(onlyAccess())
for (const name of [
'Point',
'Zone',
'Ajouter un point',
'Ajouter une zone',
])
expect(screen.getByRole('button', { name })).toBeDisabled()
for (const name of ['Accès à une vue détaillée', 'Ajouter un accès'])
expect(screen.getByRole('button', { name })).toBeEnabled()
})
})
describe('the head access', () => {
it('keeps the category select with the ordinary categories (D22)', async () => {
const text = insert(withDetail(drawnText()), {
kind: 'annotation',
value: trigger('head', 'cat-a'),
})
await mount(text)
const { opened } = await openEdit('head')
const select = within(opened).getByLabelText('Catégorie')
expect(optionsOf(select)).toEqual(['N'])
})
})